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(x): sanitize the xurl search query and name invalid-request failures (#1179)

Claire Novotnya126620f6495
diff --git a/changelog.d/1177.fixed.md b/changelog.d/1177.fixed.md
new file mode 100644
index 00000000..58ac6ed8
--- /dev/null
+++ b/changelog.d/1177.fixed.md
@@ -0,0 +1 @@
+X search through `xurl` no longer fails with "xurl: search failed" when a topic contains a bare `and`/`or`: the topic is sanitized into plain keywords (operators, negation, grouping and quotes removed, capped at 512 characters) before it reaches the X API, and an X "Invalid Request" rejection is now reported as "xurl: X rejected the query (invalid request)".
diff --git a/skills/last30days/scripts/lib/x_api.py b/skills/last30days/scripts/lib/x_api.py
index 6179bcf2..c8dcb666 100644
--- a/skills/last30days/scripts/lib/x_api.py
+++ b/skills/last30days/scripts/lib/x_api.py
@@ -314,13 +314,15 @@ def parse_v2_response(
# ---------------------------------------------------------------------------
-def _topic_tokens(topic: str) -> List[str]:
+def _topic_tokens(topic: str, *, preserve_trailing_colon: bool = False) -> List[str]:
"""Sanitized topic tokens: no quotes, grouping, operators, or negation."""
separators = str.maketrans({char: " " for char in _GROUPING_CHARS + _QUOTE_CHARS})
cleaned = str(topic or "").translate(separators)
tokens: List[str] = []
for token in cleaned.split():
clean = token.strip(_APOSTROPHES)
+ if preserve_trailing_colon and clean.endswith(":") and clean.count(":") == 1:
+ clean = clean[:-1]
if not clean:
continue
if ":" in clean or clean.startswith("-"):
@@ -335,6 +337,27 @@ def _compile(tokens: List[str]) -> str:
return f'"{" ".join(tokens)}" -is:retweet'
+def _compile_keywords(tokens: List[str]) -> str:
+ return " ".join(tokens)
+
+
+def _fit(tokens: List[str], compile_tokens: Callable[[List[str]], str]) -> str:
+ """Compile *tokens*, dropping trailing ones until under ``MAX_QUERY_CHARS``."""
+ if not tokens:
+ return ""
+ tokens = list(tokens)
+ compiled = compile_tokens(tokens)
+ while len(compiled) > MAX_QUERY_CHARS and len(tokens) > 1:
+ tokens.pop()
+ compiled = compile_tokens(tokens)
+ if len(compiled) > MAX_QUERY_CHARS:
+ # One token longer than the whole budget: keep as much of it as fits.
+ overhead = len(compile_tokens([""]))
+ tokens = [tokens[0][: MAX_QUERY_CHARS - overhead]]
+ compiled = compile_tokens(tokens)
+ return compiled
+
+
def build_query(topic: str) -> str:
"""Compile a topic into one quoted phrase plus ``-is:retweet``.
@@ -346,19 +369,22 @@ def build_query(topic: str) -> str:
result stays under ``MAX_QUERY_CHARS``, cut at a token boundary. Returns
"" when nothing lexical survives.
"""
- tokens = _topic_tokens(topic)
- if not tokens:
- return ""
- compiled = _compile(tokens)
- while len(compiled) > MAX_QUERY_CHARS and len(tokens) > 1:
- tokens.pop()
- compiled = _compile(tokens)
- if len(compiled) > MAX_QUERY_CHARS:
- # One token longer than the whole budget: keep as much of it as fits.
- overhead = len(_compile([""]))
- tokens = [tokens[0][: MAX_QUERY_CHARS - overhead]]
- compiled = _compile(tokens)
- return compiled
+ return _fit(_topic_tokens(topic), _compile)
+
+
+def build_keyword_query(topic: str) -> str:
+ """Compile a topic into space-joined keywords (implicit AND), no operators.
+
+ The keyword counterpart of :func:`build_query` for callers that keep
+ X's default any-order keyword matching instead of one exact phrase
+ (``xurl_x``). The same operator safeguards apply, while ordinary trailing
+ colons preserve subject words: bare ``and``/``or`` in any case, colon
+ operators, leading ``-`` negation, grouping and quote characters never
+ reach X, whose v2 grammar rejects a bare lowercase ``and``/``or`` with
+ HTTP 400. Capped at ``MAX_QUERY_CHARS`` on a token boundary. Returns ""
+ when nothing lexical survives.
+ """
+ return _fit(_topic_tokens(topic, preserve_trailing_colon=True), _compile_keywords)
# ---------------------------------------------------------------------------
diff --git a/skills/last30days/scripts/lib/xurl_x.py b/skills/last30days/scripts/lib/xurl_x.py
index c49b1243..987a7939 100644
--- a/skills/last30days/scripts/lib/xurl_x.py
+++ b/skills/last30days/scripts/lib/xurl_x.py
@@ -238,6 +238,9 @@ ERR_UNAUTHORIZED = "xurl: unauthorized (bearer token rejected)"
ERR_FORBIDDEN = "xurl: forbidden (bearer token lacks access)"
ERR_RATE_LIMITED = "xurl: rate limit exceeded (X API)"
ERR_FAILED = "xurl: search failed"
+# HTTP 400 from X's query grammar (for example a bare lowercase "and").
+ERR_INVALID_REQUEST = "xurl: X rejected the query (invalid request)"
+ERR_EMPTY_QUERY = "xurl: no searchable keywords left after removing X search operators"
ERR_INVALID_JSON = "xurl: invalid JSON from xurl"
ERR_NOT_FOUND = "xurl not found in PATH"
ERR_TIMED_OUT = "xurl search timed out (30s)"
@@ -257,6 +260,12 @@ def _classify_cli_failure(output: str) -> str:
return ERR_FORBIDDEN
if state == health.RATE_LIMITED:
return ERR_RATE_LIMITED
+ # X's v2 problem type (".../2/problems/invalid-request") or its title
+ # ("Invalid Request"). Only the fixed string leaves; the body may echo
+ # the query or request headers.
+ lowered = text.lower()
+ if "invalid-request" in lowered or "invalid request" in lowered:
+ return ERR_INVALID_REQUEST
return ERR_FAILED
@@ -267,8 +276,14 @@ def search_x(
) -> Dict[str, Any]:
"""Search X via xurl CLI using X API v2 search/recent.
+ The topic is sanitized into space-joined keywords first
+ (``x_api.build_keyword_query``): X's v2 grammar rejects a bare lowercase
+ ``and``/``or`` with HTTP 400 and treats ``from:``-style tokens, leading
+ ``-``, parentheses and quotes as operators, and the pipeline always
+ passes the raw user topic here.
+
Args:
- query: Search query string
+ query: Search topic (raw user text is fine; it is sanitized)
depth: "quick", "default", or "deep"
deadline: Optional shared wall-clock deadline (``time.monotonic()``
instant) from the X backend chain. The single subprocess timeout
@@ -279,6 +294,10 @@ def search_x(
with an "error" key holding a fixed string on failure. The CLI's
own output reaches only the debug log, never the error.
"""
+ search_query = x_api.build_keyword_query(query)
+ if not search_query:
+ return {"error": ERR_EMPTY_QUERY}
+
max_results = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
# X API v2 search/recent requires max_results in 10–100 range
max_results = max(10, min(100, max_results))
@@ -296,7 +315,7 @@ def search_x(
# Bearer auth sends no signature, so multi-word queries work.
charge = usage.begin("x")
result = subprocess.run(
- ["xurl", "search", query, "-n", str(max_results), "--auth", "app"],
+ ["xurl", "search", search_query, "-n", str(max_results), "--auth", "app"],
capture_output=True,
text=True,
timeout=timeout,
diff --git a/tests/test_x_api.py b/tests/test_x_api.py
index f930cc28..36ebf9ad 100644
--- a/tests/test_x_api.py
+++ b/tests/test_x_api.py
@@ -194,6 +194,9 @@ class TestBuildQuery:
q = x_api.build_query("(Peter Steinberger) -steipete “quoted” [x] {y}")
assert q == '"Peter Steinberger quoted x y" -is:retweet'
+ def test_trailing_colon_handling_stays_out_of_phrase_query(self):
+ assert x_api.build_query("Python: what's new") == '"what\'s new" -is:retweet'
+
def test_600_char_topic_compiles_under_512_with_balanced_quotes(self):
topic = " ".join(f"word{i}" for i in range(100))
assert len(topic) >= 600
@@ -215,6 +218,31 @@ class TestBuildQuery:
assert x_api.build_query("from:attacker OR -is:reply lang:en") == ""
+class TestBuildKeywordQuery:
+ def test_space_joined_keywords_without_phrase_or_retweet_filter(self):
+ assert x_api.build_keyword_query("Claude Code agents") == "Claude Code agents"
+
+ def test_bare_and_or_are_dropped_in_any_case(self):
+ q = x_api.build_keyword_query("review and security Or tools AND codex or x")
+ assert q == "review security tools codex x"
+
+ def test_operators_negation_grouping_and_quotes_are_stripped(self):
+ q = x_api.build_keyword_query('(foo) "bar from:attacker -baz lang:en')
+ assert q == "foo bar"
+
+ def test_capped_at_token_boundary(self):
+ q = x_api.build_keyword_query(" ".join(f"word{i}" for i in range(200)))
+ assert len(q) <= x_api.MAX_QUERY_CHARS
+ assert all(tok.startswith("word") and tok[4:].isdigit() for tok in q.split())
+
+ def test_single_giant_token_is_truncated(self):
+ q = x_api.build_keyword_query("a" * 700)
+ assert len(q) == x_api.MAX_QUERY_CHARS
+
+ def test_only_operators_yields_empty_query(self):
+ assert x_api.build_keyword_query("and from:x -y ()") == ""
+
+
# ---------------------------------------------------------------------------
# Request shape (KTD4)
# ---------------------------------------------------------------------------
@@ -938,6 +966,7 @@ class TestXurlFixedStrings:
("401 Unauthorized", "ERR_UNAUTHORIZED", health.AUTH_FAILED),
("403 Forbidden: client-not-enrolled", "ERR_FORBIDDEN", health.AUTH_FAILED),
("402 Payment Required", "ERR_PAYMENT_REQUIRED", health.PAYMENT_REQUIRED),
+ ("400 Invalid Request: Ambiguous use of and", "ERR_INVALID_REQUEST", health.ERROR),
("something else entirely", "ERR_FAILED", health.ERROR),
])
def test_status_words_map_to_fixed_strings(self, stderr, expected, state):
diff --git a/tests/test_xurl_x.py b/tests/test_xurl_x.py
index a86eca55..d4e2b000 100644
--- a/tests/test_xurl_x.py
+++ b/tests/test_xurl_x.py
@@ -434,6 +434,116 @@ class TestSearchX(unittest.TestCase):
n_idx = call_args.index("-n")
self.assertEqual(int(call_args[n_idx + 1]), xurl_x.DEPTH_CONFIG["default"])
+
+class TestSearchXQuerySanitization(unittest.TestCase):
+ """X's v2 grammar 400s on a bare lowercase and/or and treats colon
+ tokens, leading "-", parentheses and quotes as operators. The pipeline
+ hands search_x the raw user topic, so search_x must sanitize it while
+ keeping space-joined keyword semantics (not one exact phrase)."""
+
+ def _argv_query(self, topic):
+ completed = mock.Mock(returncode=0, stdout=json.dumps({}))
+ with mock.patch("subprocess.run", return_value=completed) as run_mock:
+ xurl_x.search_x(topic)
+ argv = run_mock.call_args[0][0]
+ self.assertEqual(argv[:2], ["xurl", "search"])
+ return argv[2]
+
+ def test_bare_lowercase_and_is_dropped(self):
+ query = self._argv_query(
+ "AI code review and security review tools for Claude Code and Codex"
+ )
+ self.assertEqual(
+ query, "AI code review security review tools for Claude Code Codex"
+ )
+
+ def test_or_and_in_any_case_are_dropped(self):
+ self.assertEqual(self._argv_query("cats or dogs OR birds AND fish"), "cats dogs birds fish")
+
+ def test_keyword_semantics_not_exact_phrase(self):
+ query = self._argv_query("claude code")
+ self.assertEqual(query, "claude code")
+ self.assertNotIn('"', query)
+ self.assertNotIn("-is:retweet", query)
+
+ def test_trailing_colon_keeps_python_subject(self):
+ self.assertEqual(self._argv_query("Python: what's new"), "Python what's new")
+
+ def test_trailing_colon_keeps_cplusplus_subject(self):
+ self.assertEqual(self._argv_query("C++: memory safety"), "C++ memory safety")
+
+ def test_trailing_colon_still_drops_operators_and_negation(self):
+ query = self._argv_query("Python: from:attacker since:2020-01-01 -spam and review")
+ self.assertEqual(query, "Python review")
+
+ def test_colon_operator_tokens_are_dropped(self):
+ self.assertEqual(self._argv_query("from:x claude since:2020-01-01 code"), "claude code")
+
+ def test_leading_negation_is_dropped(self):
+ query = self._argv_query("-foo claude -bar")
+ self.assertEqual(query, "claude")
+ self.assertFalse(query.startswith("-"))
+
+ def test_parentheses_and_unbalanced_quotes_become_spaces(self):
+ self.assertEqual(self._argv_query('(claude "code) [agents] {x}'), "claude code agents x")
+
+ def test_query_is_capped(self):
+ query = self._argv_query(" ".join(["word"] * 300))
+ self.assertLessEqual(len(query), xurl_x.x_api.MAX_QUERY_CHARS)
+ self.assertTrue(query.startswith("word word"))
+
+ def test_nothing_left_returns_error_without_spawning(self):
+ with mock.patch(
+ "subprocess.run",
+ side_effect=AssertionError("an empty query must not reach xurl"),
+ ):
+ result = xurl_x.search_x("and OR from:x -foo ()")
+ self.assertEqual(result, {"error": xurl_x.ERR_EMPTY_QUERY})
+
+
+class TestClassifyInvalidRequest(unittest.TestCase):
+ _BODY = (
+ '{"errors":[{"parameters":{"query":["AI and dummy-x-bearer-secret-000"]},'
+ '"message":"Ambiguous use of and as a keyword. Use a space to logically '
+ 'join two clauses, or \\"and\\" to find occurrences of and in text"}],'
+ '"title":"Invalid Request","detail":"One or more parameters to your '
+ 'request was invalid.","type":"https://api.twitter.com/2/problems/invalid-request"}'
+ )
+
+ def test_invalid_request_problem_type(self):
+ self.assertEqual(
+ xurl_x._classify_cli_failure("type: .../2/problems/invalid-request"),
+ xurl_x.ERR_INVALID_REQUEST,
+ )
+
+ def test_invalid_request_title(self):
+ self.assertEqual(
+ xurl_x._classify_cli_failure("Error: Invalid Request"),
+ xurl_x.ERR_INVALID_REQUEST,
+ )
+
+ def test_search_x_surfaces_fixed_invalid_request_error(self):
+ completed = mock.Mock(returncode=1, stdout="", stderr=self._BODY)
+ with mock.patch("subprocess.run", return_value=completed):
+ result = xurl_x.search_x("AI code review")
+ self.assertEqual(result, {"error": xurl_x.ERR_INVALID_REQUEST})
+ self.assertNotIn("dummy-x-bearer-secret-000", result["error"])
+ self.assertNotIn("Ambiguous", result["error"])
+
+ def test_auth_and_rate_limit_still_win(self):
+ self.assertEqual(
+ xurl_x._classify_cli_failure("HTTP 401 Unauthorized invalid-request"),
+ xurl_x.ERR_UNAUTHORIZED,
+ )
+ self.assertEqual(
+ xurl_x._classify_cli_failure("rate limit exceeded"),
+ xurl_x.ERR_RATE_LIMITED,
+ )
+
+ def test_unrelated_failure_stays_generic(self):
+ self.assertEqual(xurl_x._classify_cli_failure("boom"), xurl_x.ERR_FAILED)
+
+
# ---------------------------------------------------------------------------
# parse_x_response
# ---------------------------------------------------------------------------