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(competitors): stop silently dropping vs-entities beyond 4

Trevin Chowd5ab765b6423
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec492124..0ef298f2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
-- Docs now match Reddit ScrapeCreators search backup semantics: empty-only by default (not "when public Reddit is unavailable" / rate-limited). `CONFIGURATION.md` documents `LAST30DAYS_REDDIT_SC_MIN_ITEMS`; `SKILL.md` Security, Manual setup, NUX, and the Reddit backend pin describe the real empty-path / thinness-floor / SC-primary knobs. NUX Step 4/5 no longer claim SC Reddit comment enrichment or `public + ScrapeCreators` merge on the default free path (comments stay keyless via shreddit) ([#867](https://github.com/mvanhorn/last30days-skill/issues/867)).
+- Comparison / vs-mode no longer silently drops entities beyond 4. Entity ceiling is now `COMPETITORS_MAX + 1` (7), truncation warns on stderr naming dropped entities, and `--competitors-plan` implies competitor mode so a vs-topic + plan keeps all named peers (plan remains targeting-only; discover-N via bare `--competitors` is unchanged) ([#868](https://github.com/mvanhorn/last30days-skill/issues/868)).
## [3.18.0] - 2026-07-21
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index c47ed9e0..8b3c7a72 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -49,7 +49,7 @@ if os.name == "nt":
SCRIPT_DIR = Path(__file__).parent.resolve()
sys.path.insert(0, str(SCRIPT_DIR))
-from lib import corpus, dates, discovery_handoff, env, freshness, html_render, http, permission_preflight, pipeline, registers, render, schema, ui
+from lib import competitors as competitors_mod, corpus, dates, discovery_handoff, env, freshness, html_render, http, permission_preflight, pipeline, registers, render, schema, ui
_child_pids: set[int] = set()
_child_pids_lock = threading.Lock()
@@ -739,7 +739,8 @@ def parse_competitors_plan(raw: str | None) -> dict[str, dict]:
f"{sorted(unknown)}; ignoring.\n"
)
normalized[entity.strip().lower()] = {
- k: v for k, v in entry.items() if k in known_fields
+ **{k: v for k, v in entry.items() if k in known_fields},
+ "_name": entity.strip(),
}
return normalized
@@ -810,16 +811,103 @@ def subrun_kwargs_for(
}
-COMPETITORS_MIN = 1
-COMPETITORS_MAX = 6
-COMPETITORS_DEFAULT = 2
+COMPETITORS_MIN = competitors_mod.COMPETITORS_MIN
+COMPETITORS_MAX = competitors_mod.COMPETITORS_MAX
+COMPETITORS_DEFAULT = competitors_mod.COMPETITORS_DEFAULT
+COMPARISON_ENTITY_MAX = competitors_mod.COMPARISON_ENTITY_MAX
+
+
+def truncate_comparison_entities(
+ entities: list[str],
+ *,
+ warn: bool = True,
+ max_entities: int | None = None,
+) -> list[str]:
+ """Cap a vs-entity list; optionally warn on stderr naming dropped entities."""
+ ceiling = COMPARISON_ENTITY_MAX if max_entities is None else max_entities
+ if len(entities) <= ceiling:
+ return list(entities)
+ kept = entities[:ceiling]
+ dropped = entities[ceiling:]
+ if warn:
+ sys.stderr.write(
+ f"[Competitors] vs-topic has {len(entities)} entities; "
+ f"using first {ceiling}, dropped: {', '.join(dropped)}\n"
+ )
+ return kept
+
+
+def apply_vs_competitor_routing(
+ topic: str,
+ *,
+ competitors_flag: int | None,
+ comp_enabled: bool,
+ comp_count: int,
+ comp_explicit: list[str],
+ has_plan: bool,
+ comp_plan: dict[str, dict] | None = None,
+) -> tuple[str, bool, int, list[str]]:
+ """Apply vs-string / plan routing on top of resolve_competitors_args.
+
+ Precedence for *who* runs:
+ 1. ``--competitors-list`` (explicit peers; topic unchanged)
+ 2. Pure discover-N (``--competitors`` without list or plan) — topic
+ unchanged, even if it contains ``vs``
+ 3. vs-string split (first entity becomes main topic) — used for bare
+ vs-topics and vs-topic + ``--competitors-plan``
+ 4. ``--competitors-plan`` keys as peers when there is no vs-string
+ 5. ``--competitors N`` + plan without vs-string → discover-N
+ """
+ from lib import planner as _planner
+
+ if comp_explicit:
+ return topic, True, len(comp_explicit), list(comp_explicit)
+
+ # Preserve discover-N semantics: numeric flag without plan/list must not
+ # rewrite a vs-string into named peers.
+ if competitors_flag is not None and not has_plan:
+ return topic, True, comp_count, []
+
+ vs_entities = truncate_comparison_entities(
+ _planner._comparison_entities(topic, max_entities=-1),
+ warn=True,
+ )
+ if len(vs_entities) >= 2:
+ main, peers = vs_entities[0], vs_entities[1:]
+ sys.stderr.write(
+ f"[Competitors] vs-mode: routing to N-pass fanout: "
+ f"{main} vs {' vs '.join(peers)}\n"
+ )
+ return main, True, len(peers), peers
+
+ if has_plan and comp_plan:
+ plan_peers = [
+ (entry.get("_name") or key)
+ for key, entry in comp_plan.items()
+ if isinstance(entry, dict)
+ ]
+ plan_peers = [name for name in plan_peers if name]
+ if len(plan_peers) > COMPETITORS_MAX:
+ sys.stderr.write(
+ f"[Competitors] --competitors-plan has {len(plan_peers)} entries, "
+ f"clamping to {COMPETITORS_MAX}.\n"
+ )
+ plan_peers = plan_peers[:COMPETITORS_MAX]
+ return topic, True, len(plan_peers), plan_peers
+
+ if competitors_flag is not None:
+ return topic, True, comp_count, []
+
+ return topic, comp_enabled, comp_count, comp_explicit
def resolve_competitors_args(args: argparse.Namespace) -> tuple[bool, int, list[str]]:
- """Normalize --competitors / --competitors-list into (enabled, count, explicit_list).
+ """Normalize competitors flags into (enabled, count, explicit_list).
- - (False, 0, []) when neither flag is set.
- - An explicit list always wins; count is derived from list length.
+ - (False, 0, []) when neither flag, list, nor plan is set.
+ - An explicit ``--competitors-list`` always wins; count is derived from list length.
+ - ``--competitors-plan`` alone enables mode with an empty peer list; vs-routing
+ fills peers from the vs-string or plan keys.
- A numeric count outside [1, 6] is clamped with a stderr warning.
- count <= 0 (explicit) raises SystemExit(2).
"""
@@ -838,8 +926,9 @@ def resolve_competitors_args(args: argparse.Namespace) -> tuple[bool, int, list[
competitors_flag = args.competitors
list_present = bool(explicit_list)
flag_present = competitors_flag is not None
+ plan_present = bool(getattr(args, "competitors_plan", None))
- if not list_present and not flag_present:
+ if not list_present and not flag_present and not plan_present:
return False, 0, []
if list_present:
@@ -857,19 +946,22 @@ def resolve_competitors_args(args: argparse.Namespace) -> tuple[bool, int, list[
count = COMPETITORS_MAX
return True, count, explicit_list
- # flag_present, no explicit list
- count = competitors_flag
- if count < COMPETITORS_MIN:
- sys.stderr.write(
- f"[Competitors] --competitors must be >= {COMPETITORS_MIN} (got {count}).\n"
- )
- raise SystemExit(2)
- if count > COMPETITORS_MAX:
- sys.stderr.write(
- f"[Competitors] --competitors={count} exceeds max {COMPETITORS_MAX}; clamping.\n"
- )
- count = COMPETITORS_MAX
- return True, count, []
+ if flag_present:
+ count = competitors_flag
+ if count < COMPETITORS_MIN:
+ sys.stderr.write(
+ f"[Competitors] --competitors must be >= {COMPETITORS_MIN} (got {count}).\n"
+ )
+ raise SystemExit(2)
+ if count > COMPETITORS_MAX:
+ sys.stderr.write(
+ f"[Competitors] --competitors={count} exceeds max {COMPETITORS_MAX}; clamping.\n"
+ )
+ count = COMPETITORS_MAX
+ return True, count, []
+
+ # plan_present alone: enable; peers filled by apply_vs_competitor_routing.
+ return True, 0, []
def _missing_sources_for_promo(diag: dict[str, object]) -> str | None:
@@ -3085,23 +3177,17 @@ def _main(
if keywords:
config["_polymarket_keywords"] = keywords
- # vs-mode: if the topic string contains " vs " / " versus " and the
- # planner can split it into >=2 entities, route through the same
- # N-pass fanout path as --competitors. The first entity becomes the
- # main topic; remaining entities become the competitor list. User's
- # outer --x-handle / --subreddits apply to the first entity unless
- # --competitors-plan covers it.
- from lib import planner as _planner
- vs_entities = _planner._comparison_entities(topic)
- if len(vs_entities) >= 2 and not comp_enabled:
- topic = vs_entities[0]
- comp_enabled = True
- comp_count = len(vs_entities) - 1
- comp_explicit = vs_entities[1:]
- sys.stderr.write(
- f"[Competitors] vs-mode: routing to N-pass fanout: "
- f"{' vs '.join(vs_entities)}\n"
- )
+ # vs-mode / plan routing: split a vs-topic into main + peers unless
+ # discover-N or an explicit --competitors-list already decided who runs.
+ topic, comp_enabled, comp_count, comp_explicit = apply_vs_competitor_routing(
+ topic,
+ competitors_flag=args.competitors,
+ comp_enabled=comp_enabled,
+ comp_count=comp_count,
+ comp_explicit=comp_explicit,
+ has_plan=bool(comp_plan),
+ comp_plan=comp_plan,
+ )
# Dedicated subs ride the config dict (already threaded to every source
# fetch) so the keyless Reddit path can pull them floor-exempt without
diff --git a/skills/last30days/scripts/lib/competitors.py b/skills/last30days/scripts/lib/competitors.py
index b45c6100..4bfb475d 100644
--- a/skills/last30days/scripts/lib/competitors.py
+++ b/skills/last30days/scripts/lib/competitors.py
@@ -19,6 +19,14 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from . import dates, grounding, log
from .resolve import _has_backend
+# Shared with CLI resolve_competitors_args / vs-mode routing / planner + render
+# comparison entity caps. COMPETITORS_MAX is peer count; a vs-string may name
+# the main topic plus that many peers.
+COMPETITORS_MIN = 1
+COMPETITORS_MAX = 6
+COMPETITORS_DEFAULT = 2
+COMPARISON_ENTITY_MAX = COMPETITORS_MAX + 1
+
# A "brand-shaped" token starts with uppercase OR is camelCase with an
# uppercase letter later. Catches "Anthropic", "OpenAI", "xAI", "iPhone",
# "eBay", "Hugging", "Face".
diff --git a/skills/last30days/scripts/lib/planner.py b/skills/last30days/scripts/lib/planner.py
index fa75ffd7..23de7d6c 100644
--- a/skills/last30days/scripts/lib/planner.py
+++ b/skills/last30days/scripts/lib/planner.py
@@ -804,7 +804,19 @@ _TRAILING_CONTEXT = re.compile(
)
-def _comparison_entities(topic: str) -> list[str]:
+def _comparison_entities(
+ topic: str,
+ *,
+ max_entities: int | None = None,
+) -> list[str]:
+ """Split a comparison topic into entity names.
+
+ Default ceiling is ``competitors.COMPARISON_ENTITY_MAX`` (main + up to
+ COMPETITORS_MAX peers). Pass ``max_entities=None`` explicitly only via the
+ default; pass a negative value for an uncapped split (caller truncates).
+ """
+ from . import competitors as competitors_mod
+
# "difference between X and Y" -> "X vs Y" (replace "and" only in this context)
normalized = re.sub(
r"\bdifference between\s+(.+?)\s+and\s+",
@@ -819,14 +831,21 @@ def _comparison_entities(topic: str) -> list[str]:
if part.strip(" \t\r\n?.,:;!()[]{}\"'")
]
# Strip trailing context from parts ("Svelte for frontend in 2026" -> "Svelte")
- if len(parts) >= 2:
- parts = [_TRAILING_CONTEXT.sub("", part).strip() or part for part in parts]
- deduped = []
- for part in parts:
- if part and part not in deduped:
- deduped.append(part)
- return deduped[:_max_subqueries("comparison")]
- return []
+ if len(parts) < 2:
+ return []
+ parts = [_TRAILING_CONTEXT.sub("", part).strip() or part for part in parts]
+ deduped: list[str] = []
+ for part in parts:
+ if part and part not in deduped:
+ deduped.append(part)
+ ceiling = (
+ competitors_mod.COMPARISON_ENTITY_MAX
+ if max_entities is None
+ else max_entities
+ )
+ if ceiling < 0:
+ return deduped
+ return deduped[:ceiling]
def _should_force_deterministic_plan(topic: str) -> bool:
@@ -901,7 +920,8 @@ def _max_subqueries(intent: str, topic: str | None = None) -> int:
# Hermes Agent Use Cases failure: prior cap of 3 produced near-literal
# echoes of the topic instead of a paraphrase fanout.
if intent == "comparison":
- return 4
+ from . import competitors as competitors_mod
+ return competitors_mod.COMPARISON_ENTITY_MAX
# Intent-modifier topics get headroom for paraphrase fanout even when
# the intent itself is factual/concept. Without this, a "Hermes Agent
# use cases" query (classified "concept" after the 2026-04-19 default
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 0d107311..b948b8d1 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -1016,17 +1016,19 @@ def _render_degraded_run_warning(report: schema.Report) -> list[str]:
def _parse_comparison_entities(topic: str) -> list[str] | None:
"""Return list of entity names if topic is a comparison query, else None.
- Splits on ` vs ` or ` versus ` (case-insensitive). Caps at 4 entities
- for table readability. Returns None if only one entity or empty input.
+ Splits on ` vs ` or ` versus ` (case-insensitive). Caps at
+ ``competitors.COMPARISON_ENTITY_MAX`` (main + COMPETITORS_MAX peers).
+ Returns None if only one entity or empty input.
"""
if not topic:
return None
+ from . import competitors as competitors_mod
import re
parts = re.split(r"\s+(?:vs\.?|versus)\s+", topic.strip(), flags=re.IGNORECASE)
parts = [p.strip() for p in parts if p.strip()]
if len(parts) < 2:
return None
- return parts[:4]
+ return parts[: competitors_mod.COMPARISON_ENTITY_MAX]
def _render_comparison_scaffold(topic: str) -> list[str]:
diff --git a/tests/test_adversarial_v3.py b/tests/test_adversarial_v3.py
index 54354056..6b92defe 100644
--- a/tests/test_adversarial_v3.py
+++ b/tests/test_adversarial_v3.py
@@ -115,7 +115,8 @@ class TestFiveWayComparison(unittest.TestCase):
provider=None,
model=None,
)
- self.assertLessEqual(len(plan.subqueries), 4)
+ from lib import competitors
+ self.assertLessEqual(len(plan.subqueries), competitors.COMPARISON_ENTITY_MAX)
class TestDegenerateInputs(unittest.TestCase):
@@ -153,7 +154,8 @@ class TestDegenerateInputs(unittest.TestCase):
provider=None,
model=None,
)
- self.assertLessEqual(len(plan.subqueries), 4)
+ from lib import competitors
+ self.assertLessEqual(len(plan.subqueries), competitors.COMPARISON_ENTITY_MAX)
class TestMixedCaseAndPunctuation(unittest.TestCase):
diff --git a/tests/test_competitors_routing.py b/tests/test_competitors_routing.py
new file mode 100644
index 00000000..0f3ab848
--- /dev/null
+++ b/tests/test_competitors_routing.py
@@ -0,0 +1,151 @@
+"""Routing for vs-mode / --competitors / --competitors-plan (#868).
+
+Plan implies competitor mode; vs-split supplies peers when not in discover-N
+mode; entity caps align with COMPETITORS_MAX and warn when truncating.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import unittest
+from contextlib import redirect_stderr
+
+import last30days as cli
+from lib import competitors, planner, render
+
+
+def _parse(*argv: str):
+ return cli.build_parser().parse_args(argv)
+
+
+def _route(topic: str, *argv: str):
+ args = _parse(topic, *argv)
+ enabled, count, explicit = cli.resolve_competitors_args(args)
+ plan = cli.parse_competitors_plan(args.competitors_plan)
+ return cli.apply_vs_competitor_routing(
+ topic,
+ competitors_flag=args.competitors,
+ comp_enabled=enabled,
+ comp_count=count,
+ comp_explicit=explicit,
+ has_plan=bool(plan),
+ comp_plan=plan,
+ )
+
+
+FIVE_WAY = "Weber vs Traeger vs Big Green Egg vs Blackstone vs Napoleon Grills"
+
+
+class TestCompetitorsPlanImpliesEnabled(unittest.TestCase):
+ def test_plan_alone_enables_competitor_mode(self):
+ plan = json.dumps({
+ "Traeger": {"x_handle": "TraegerGrills"},
+ "Napoleon Grills": {"subreddits": ["NapoleonGrill"]},
+ })
+ args = _parse("Weber grills", "--competitors-plan", plan)
+ enabled, count, explicit = cli.resolve_competitors_args(args)
+ self.assertTrue(enabled)
+ self.assertEqual(explicit, []) # peers filled by routing from plan keys
+ topic, enabled, count, explicit = _route(
+ "Weber grills", "--competitors-plan", plan,
+ )
+ self.assertEqual(topic, "Weber grills")
+ self.assertTrue(enabled)
+ self.assertEqual(explicit, ["Traeger", "Napoleon Grills"])
+ self.assertEqual(count, 2)
+
+ def test_plan_does_not_override_explicit_list(self):
+ plan = json.dumps({"Ignored": {}})
+ topic, enabled, count, explicit = _route(
+ "Weber",
+ "--competitors-list", "Traeger,Blackstone",
+ "--competitors-plan", plan,
+ )
+ self.assertEqual(topic, "Weber")
+ self.assertTrue(enabled)
+ self.assertEqual(explicit, ["Traeger", "Blackstone"])
+ self.assertEqual(count, 2)
+
+
+class TestVsRoutingWithPlan(unittest.TestCase):
+ def test_five_way_vs_plus_plan_keeps_all_five(self):
+ plan = json.dumps({
+ "Traeger": {},
+ "Big Green Egg": {},
+ "Blackstone": {},
+ "Napoleon Grills": {"subreddits": ["NapoleonGrill"]},
+ })
+ err = io.StringIO()
+ with redirect_stderr(err):
+ topic, enabled, count, explicit = _route(
+ FIVE_WAY, "--competitors-plan", plan,
+ )
+ self.assertEqual(topic, "Weber")
+ self.assertTrue(enabled)
+ self.assertEqual(
+ explicit,
+ ["Traeger", "Big Green Egg", "Blackstone", "Napoleon Grills"],
+ )
+ self.assertEqual(count, 4)
+ self.assertIn("Napoleon Grills", err.getvalue())
+
+ def test_bare_five_way_vs_keeps_all_five(self):
+ with redirect_stderr(io.StringIO()):
+ topic, enabled, count, explicit = _route(FIVE_WAY)
+ self.assertEqual(topic, "Weber")
+ self.assertEqual(
+ explicit,
+ ["Traeger", "Big Green Egg", "Blackstone", "Napoleon Grills"],
+ )
+
+ def test_competitors_n_on_vs_topic_skips_vs_split(self):
+ """Discover-N mode must not rewrite a vs-string into named peers."""
+ topic, enabled, count, explicit = _route(FIVE_WAY, "--competitors", "2")
+ self.assertEqual(topic, FIVE_WAY)
+ self.assertTrue(enabled)
+ self.assertEqual(count, 2)
+ self.assertEqual(explicit, [])
+
+
+class TestEntityCapAlignment(unittest.TestCase):
+ def test_comparison_entity_max_matches_competitors_max_plus_main(self):
+ self.assertEqual(
+ competitors.COMPARISON_ENTITY_MAX,
+ competitors.COMPETITORS_MAX + 1,
+ )
+ self.assertEqual(
+ planner._max_subqueries("comparison"),
+ competitors.COMPARISON_ENTITY_MAX,
+ )
+
+ def test_five_way_not_silently_truncated(self):
+ entities = planner._comparison_entities(FIVE_WAY)
+ self.assertEqual(
+ entities,
+ ["Weber", "Traeger", "Big Green Egg", "Blackstone", "Napoleon Grills"],
+ )
+
+ def test_over_max_warns_and_names_dropped(self):
+ # main + 6 peers = max; 8th entity dropped with warning
+ topic = "A vs B vs C vs D vs E vs F vs G vs H"
+ err = io.StringIO()
+ with redirect_stderr(err):
+ kept = cli.truncate_comparison_entities(
+ planner._comparison_entities(topic, max_entities=-1),
+ warn=True,
+ )
+ self.assertEqual(len(kept), competitors.COMPARISON_ENTITY_MAX)
+ self.assertIn("dropped", err.getvalue().lower())
+ self.assertIn("H", err.getvalue())
+
+ def test_render_scaffold_keeps_five_columns(self):
+ entities = render._parse_comparison_entities(FIVE_WAY)
+ self.assertEqual(len(entities), 5)
+ lines = render._render_comparison_scaffold(FIVE_WAY)
+ header = next(line for line in lines if line.startswith("| Dimension |"))
+ self.assertIn("Napoleon Grills", header)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_planner_v3.py b/tests/test_planner_v3.py
index a3512fcb..5cfa0a40 100644
--- a/tests/test_planner_v3.py
+++ b/tests/test_planner_v3.py
@@ -342,7 +342,11 @@ class IntentModifierBreadthTests(unittest.TestCase):
self.assertEqual(5, planner._max_subqueries("product"))
def test_max_subqueries_unchanged_for_comparison(self):
- self.assertEqual(4, planner._max_subqueries("comparison"))
+ from lib import competitors
+ self.assertEqual(
+ competitors.COMPARISON_ENTITY_MAX,
+ planner._max_subqueries("comparison"),
+ )
def test_max_subqueries_unchanged_for_factual_and_concept(self):
self.assertEqual(2, planner._max_subqueries("factual"))