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: finalize X evidence after relevance filtering (#1309)

CapoAi44a288c32e4c
diff --git a/AGENTS.md b/AGENTS.md
index 881a6d47..4347e206 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -30,7 +30,7 @@ Agent Skills package for researching any topic across Reddit, X, YouTube, and we
python3 skills/last30days/scripts/last30days.py "test query" --emit=compact
npx skills add . -g -y # copies skill into ~/.agents/skills/<name>/ (frozen at install time); re-run to sync working-tree edits — see Rules below
-# Tests (pytest, ~89 files under tests/, configured in pyproject.toml)
+# Tests (pytest, ~200 files under tests/, configured in pyproject.toml)
uv run pytest # full suite
uv run pytest tests/test_dedupe_v3.py # single file
uv run pytest tests/test_dedupe_v3.py -k some_case # single case
diff --git a/changelog.d/+query-second-person-prefixes.fixed.md b/changelog.d/+query-second-person-prefixes.fixed.md
new file mode 100644
index 00000000..9372aa19
--- /dev/null
+++ b/changelog.d/+query-second-person-prefixes.fixed.md
@@ -0,0 +1 @@
+Search-query cleanup now strips "how do you use", "how can I use", "how do you" and "how can I" openers, so "how do you use Cursor" searches for "cursor" instead of "do you cursor".
diff --git a/changelog.d/+x-floor-before-finalize.fixed.md b/changelog.d/+x-floor-before-finalize.fixed.md
new file mode 100644
index 00000000..183264e8
--- /dev/null
+++ b/changelog.d/+x-floor-before-finalize.fixed.md
@@ -0,0 +1 @@
+The deferred X relevance floor now runs before the per-source evidence view is finalized, so the report's X items and X source status count reflect the same post-floor evidence set that ranking sees.
diff --git a/docs/solutions/architecture-patterns/discovery-topic-queue-design-conventions.md b/docs/solutions/architecture-patterns/discovery-topic-queue-design-conventions.md
index 11375482..060f3481 100644
--- a/docs/solutions/architecture-patterns/discovery-topic-queue-design-conventions.md
+++ b/docs/solutions/architecture-patterns/discovery-topic-queue-design-conventions.md
@@ -61,7 +61,7 @@ disables it. The knob is registered in `env.get_config`'s keys allowlist
```
and read from the resolved config dict, never `os.environ`
-(`skills/last30days/scripts/last30days.py:1312-1314`):
+(`_annotate_and_record_discovery_queue` in `skills/last30days/scripts/last30days.py`):
```python
queue_setting = str(config.get("LAST30DAYS_DISCOVERY_QUEUE") or "").strip().lower()
@@ -73,15 +73,15 @@ WHY: `.env`-file users' values only reach the engine through the `get_config`
allowlist merge - a bare `os.environ` read silently ignores them, a documented
invisible-failure class in this repo. Scoped runs (`--save-dir`) write the scoped
research.db via `store.scoped_db(_scoped_store_db(args))`
-(`last30days.py:432-437`, `store.py:41-53`), never the global one; `--mock` runs
-stay 100% side-effect-free (`last30days.py:1505`).
+(`_scoped_store_db` in `last30days.py`, `store.scoped_db`), never the global one; `--mock` runs
+stay 100% side-effect-free (both discovery call sites guard the queue hook with `if not args.mock`).
### 2. Annotate-only fuzzy matching - a match stamps context, it never merges rows
`store.match_discovery_topic` tries exact normalized-name match first, then the
best entity-overlap candidate - the better of full `entity_key` token overlap and
anchor-token overlap - at a conservative floor
-(`skills/last30days/scripts/store.py:810`, `898-938`):
+(`DISCOVERY_QUEUE_OVERLAP_THRESHOLD` and `match_discovery_topic` in `skills/last30days/scripts/store.py`):
```python
DISCOVERY_QUEUE_OVERLAP_THRESHOLD = 0.6
@@ -91,8 +91,8 @@ if best is not None and best_overlap >= DISCOVERY_QUEUE_OVERLAP_THRESHOLD:
```
A fuzzy match only annotates the rendered card - the `Pipeline: surfaced Nth
-time, marked covered` line (`skills/last30days/scripts/lib/render.py:153-168`) -
-and never merges or rewrites queue rows (`store.py:806-809`, `906-907`).
+time, marked covered` line (`render_discovery` in `skills/last30days/scripts/lib/render.py`) -
+and never merges or rewrites queue rows (see the `record_discovery_surfacing` and `match_discovery_topic` docstrings in `store.py`).
WHY: with annotate-only semantics a false-positive match costs one noisy line on
one card; a false merge would silently collapse two distinct stories into one
@@ -103,7 +103,7 @@ mislabeling is recoverable and data loss is not.
`_annotate_and_record_discovery_queue` computes priors for every topic first,
then records surfacings, inside one `store.scoped_db` block
-(`skills/last30days/scripts/last30days.py:1323-1345`):
+(`_annotate_and_record_discovery_queue` in `skills/last30days/scripts/last30days.py`):
```python
with store.scoped_db(_scoped_store_db(args)):
@@ -112,7 +112,12 @@ with store.scoped_db(_scoped_store_db(args)):
# match+record in one loop lets topic N fuzzy-match a same-anchor
# sibling row this very run recorded seconds earlier, falsely
# annotating a first-ever topic as "surfaced 2nd time".
- priors = [store.match_discovery_topic(topic.name) for topic in report.topics]
+ priors = [
+ _pre_run_prior_state(prior, run_ref)
+ for prior in (
+ store.match_discovery_topic(topic.name) for topic in report.topics
+ )
+ ]
# Phase 2: record this run's surfacings. ...
for topic, prior in zip(report.topics, priors):
```
@@ -122,12 +127,17 @@ WHY: one report often contains same-anchor siblings ("Gemma 4 chat templates" /
the row topic N-1 wrote seconds earlier, falsely annotating a first-ever topic
as a repeat. Caught in review; regression-tested.
+`_pre_run_prior_state` wraps each match so a finalize retry sees the state from
+BEFORE its own earlier attempt: a row stamped with this run's `run_ref` has its
+own surfacing subtracted (covered state kept), so the retry renders exactly like
+the first attempt instead of annotating "surfaced 2nd time".
+
### 4. Covered inheritance: fresh rows born covered, existing rows never mutated
`record_discovery_surfacing(inherit_covered_at=...)` makes a fresh row start in
`covered` status when its fuzzy-matched prior is covered; the `ON CONFLICT`
update path deliberately never touches `status`/`covered_at`
-(`skills/last30days/scripts/store.py:842-895`):
+(`record_discovery_surfacing` in `skills/last30days/scripts/store.py`):
```python
status = "covered" if inherit_covered_at else "surfaced"
@@ -140,10 +150,11 @@ ON CONFLICT(normalized_name) DO UPDATE SET
```
The caller passes it when a topic's prior is covered
-(`last30days.py:1334-1344`). Locked by the flip-flop regression test
-`test_covered_status_survives_judge_rename_across_runs`
-(`tests/test_store.py:1082-1101`) and by
-`tests/test_store.py:1060-1079` (ON CONFLICT ignores `inherit_covered_at`).
+(`_annotate_and_record_discovery_queue`). Locked by the flip-flop regression test
+`test_covered_status_survives_judge_rename_across_runs` and by
+`test_record_discovery_surfacing_inherit_never_alters_existing_row_status`
+(both in `tests/test_store.py`; the second pins that ON CONFLICT ignores
+`inherit_covered_at`).
WHY: the LLM judge renames the same story across runs; without inheritance a
rename forks a fresh uncovered row and the user's covered mark silently
@@ -152,14 +163,18 @@ user just changed.
### 5. Guarded, synchronous end-of-run write - never crash a finished pipeline
-The hook call in `_run_discover` is wrapped so a broken queue db degrades to a
-stderr warning and an unannotated report
-(`skills/last30days/scripts/last30days.py:1505-1515`):
+Both discovery paths (one-shot `_run_discover` and the protocol's finalize leg)
+call the hook through `_record_discovery_queue_safely`, so a broken queue db
+degrades to a stderr warning and an unannotated report
+(`skills/last30days/scripts/last30days.py`):
```python
-if not args.mock:
+# call sites: `if not args.mock: report = _record_discovery_queue_safely(...)`
+def _record_discovery_queue_safely(report, args, config, run_ref=None):
try:
- report = _annotate_and_record_discovery_queue(report, args, config)
+ return _annotate_and_record_discovery_queue(
+ report, args, config, run_ref=run_ref,
+ )
except (sqlite3.Error, OSError) as exc:
# A broken queue db (locked, read-only dir, corrupt) must never
# destroy a finished multi-minute pipeline run: warn and render
@@ -168,12 +183,13 @@ if not args.mock:
f"[last30days] Warning: discovery queue unavailable ({exc}); "
"continuing without queue annotations.\n"
)
+ return report
```
WHY: unguarded, a locked/read-only/corrupt research.db raises AFTER the
multi-minute research pipeline finished and discards all of its output - the PR
#852 code review's P0, empirically reproduced. The write also runs synchronously
-after the pipeline returns (`last30days.py:1308-1310` docstring): it touches
+after the pipeline returns (see the `_annotate_and_record_discovery_queue` docstring): it touches
disk, so the abandon-on-timeout daemon-thread pattern is forbidden here (see
`docs/solutions/logic-errors/non-daemon-executor-threads-defeat-wall-clock-budget.md`).
@@ -213,7 +229,7 @@ Ranked by blast radius when a convention is violated:
## Examples
Covered flip-flop, the archetype 3-run scenario (mirrors
-`tests/test_store.py:1082-1101`):
+`test_covered_status_survives_judge_rename_across_runs` in `tests/test_store.py`):
1. Run 1 surfaces "Gemma 4 chat templates"; the user records an episode and
runs `queue cover "Gemma 4 chat templates"` (row status: covered).
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 6a7be437..04af639a 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -2973,11 +2973,6 @@ def run(
bundle.artifacts["hiring_signals"] = hiring_summary
_check_research(config)
- items_by_source = _finalize_items_by_source(
- bundle.items_by_source, topic=topic, config=config, depth=depth, mock=mock,
- elapsed=time.monotonic() - run_started,
- )
- source_status = _finalize_source_status(bundle.source_status, items_by_source)
# Normalized set of handles this run resolved for the topic. A candidate
# authored by one of these is first-party and is exempted from the
# entity-miss demotion in rerank (a post never repeats its own author's
@@ -3041,6 +3036,14 @@ def run(
_log_prune_drop("x", len(x_stream), len(pruned), scope="merged stream")
bundle.items_by_source["x"] = pruned
+ # Finalize after the deferred floor so the report's per-source view and the
+ # source_status counts describe the same post-floor evidence set fusion sees.
+ items_by_source = _finalize_items_by_source(
+ bundle.items_by_source, topic=topic, config=config, depth=depth, mock=mock,
+ elapsed=time.monotonic() - run_started,
+ )
+ source_status = _finalize_source_status(bundle.source_status, items_by_source)
+
candidates = weighted_rrf(
bundle.items_by_source_and_query,
plan,
diff --git a/skills/last30days/scripts/lib/query.py b/skills/last30days/scripts/lib/query.py
index f3a4f97b..8057a71f 100644
--- a/skills/last30days/scripts/lib/query.py
+++ b/skills/last30days/scripts/lib/query.py
@@ -8,7 +8,8 @@ from typing import FrozenSet, List, Optional, Set
PREFIXES = [
'what are the best', 'what is the best', 'what are the latest',
'what are people saying about', 'what do people think about',
- 'how do i use', 'how to use', 'how to',
+ 'how do i use', 'how do you use', 'how can i use', 'how to use',
+ 'how do you', 'how can i', 'how to',
'what are', 'what is', 'tips for', 'best practices for',
# Hebrew question/meta prefixes
'מה יש חדש ב', 'מה יש חדש על', 'מה אנשים אומרים על',
diff --git a/tests/test_first_party_floor.py b/tests/test_first_party_floor.py
index 65b8ff4a..11a00801 100644
--- a/tests/test_first_party_floor.py
+++ b/tests/test_first_party_floor.py
@@ -388,6 +388,65 @@ def test_deferred_prune_runs_after_resolution_and_before_fusion():
)
+def test_deferred_prune_reaches_the_report_not_just_fusion():
+ """The floor must run before the per-source view is finalized. Pruning only
+ the fusion streams left report.items_by_source and the X source_status
+ count describing the pre-floor pool."""
+ from unittest.mock import patch
+
+ from lib import dates, pipeline
+
+ day = dates.get_date_range(2)[0]
+
+ def _raw(item_id, author, text, likes):
+ return {
+ "id": item_id,
+ "text": text,
+ "url": f"https://x.com/{author}/status/{item_id}",
+ "author_handle": author,
+ "date": day,
+ "engagement": {"likes": likes, "reposts": 0, "replies": 0, "quotes": 0},
+ "relevance": 0.5,
+ "why_relevant": "test",
+ }
+
+ raw_items = [
+ _raw("1", "steipete", "unrelated lunch photo", 500),
+ _raw("2", "dev_a", "agent loops are great, agent loops everywhere", 300),
+ _raw("3", "dev_b", "agent loops need better evals", 200),
+ _raw("4", "spam_acct", "buy cheap watches now", 0),
+ ]
+ plan = {
+ "intent": "general",
+ "freshness_mode": "balanced_recent",
+ "cluster_mode": "story",
+ "subqueries": [
+ {
+ "label": "primary",
+ "search_query": "agent loops",
+ "ranking_query": "agent loops",
+ "sources": ["x"],
+ }
+ ],
+ "source_weights": {"x": 1.0},
+ }
+ with patch("lib.pipeline._retrieve_stream_impl", return_value=(raw_items, {})):
+ report = pipeline.run(
+ topic="agent loops",
+ config={},
+ depth="quick",
+ requested_sources=["x"],
+ mock=True,
+ x_handle="steipete",
+ external_plan=plan,
+ )
+
+ authors = {item.author for item in report.items_by_source["x"]}
+ assert "steipete" in authors, "first-party post must survive the floor"
+ assert "spam_acct" not in authors, "the floor must reach the report's per-source view"
+ assert report.source_status["x"].items_returned == len(report.items_by_source["x"])
+
+
def test_non_x_sources_still_prune_in_place():
"""Only X defers; everything else keeps its existing behavior."""
import inspect
diff --git a/tests/test_query.py b/tests/test_query.py
index 3b4e5eb4..491f974e 100644
--- a/tests/test_query.py
+++ b/tests/test_query.py
@@ -4,6 +4,7 @@ import unittest
from lib.query import (
NOISE_WORDS,
+ PREFIXES,
SOCIAL_NOISE,
VIRAL_NOISE,
extract_compound_terms,
@@ -35,6 +36,24 @@ class TestExtractCoreSubject(unittest.TestCase):
def test_empty_string(self):
self.assertEqual(extract_core_subject(""), "")
+ def test_second_person_use_prefixes_are_stripped(self):
+ self.assertEqual(extract_core_subject("how do you use Cursor"), "cursor")
+ self.assertEqual(extract_core_subject("how can I use Cursor"), "cursor")
+
+ def test_bare_how_do_you_and_how_can_i_are_stripped(self):
+ self.assertEqual(extract_core_subject("how can I debug docker"), "debug docker")
+ self.assertEqual(extract_core_subject("how do you deploy Next.js"), "deploy next.js")
+
+ def test_prefixes_are_ordered_longest_first(self):
+ """Prefix stripping stops after the first match, so a shorter prefix
+ listed before a longer one it leads would shadow it."""
+ for i, shorter in enumerate(PREFIXES):
+ for longer in PREFIXES[i + 1:]:
+ self.assertFalse(
+ longer.startswith(shorter + " "),
+ f"{shorter!r} is listed before {longer!r} and would shadow it",
+ )
+
def test_all_noise_returns_original(self):
# When all words are noise, fall back to original text
result = extract_core_subject("best latest new")
diff --git a/tests/test_x_envelope.py b/tests/test_x_envelope.py
index de7d966c..526095e7 100644
--- a/tests/test_x_envelope.py
+++ b/tests/test_x_envelope.py
@@ -214,7 +214,9 @@ class TestIngestion:
def test_mention_lane_rows_reach_the_report(self, tmp_path):
envelope = _read(_write(tmp_path, _envelope([
_call("topic", posts=[_row(0, "alice", "ai agents review")]),
- _call("mention", handles=[SUBJECT], posts=[_row(4, "fan", f"@{SUBJECT} love the agent work")]),
+ # On-topic enough to clear the relevance floor: the report's X view is
+ # finalized after that floor, so an off-topic mention row would be pruned.
+ _call("mention", handles=[SUBJECT], posts=[_row(4, "fan", f"@{SUBJECT} love the ai agents work")]),
])))
assert envelope.lane_counts["mention"] == 1
report = _run(envelope, x_handle=SUBJECT)