AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix: account for watchlist spending before scheduling more topics (#1214)
Ilia Alshanetsky5398e6db9f48
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 540ce639..5c61aa2c 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -612,6 +612,12 @@ python3 scripts/watchlist.py run-allThe schedule field stored on each topic is metadata - the actual cron / Task Scheduler invocation is your responsibility. Watchlist runs hardcode `--quick` and `--lookback-days 90` when spawning the underlying engine.+The daily budget defaults to USD 5.00 and applies before each `run-one` or `run-all` topic. It stops subsequent runs after recorded spending reaches the limit; it cannot cap an already-running request or spending outside this local store. Days use UTC. Free sources consume no budget. Watchlist runs record provider-reported OpenRouter account charges (`usage.cost`) and synchronous Perplexity Agent USD charges (`usage.cost.total_cost`), including charges incurred before a later error or local timeout. No model price estimates are substituted for missing billing data.++If a paid backend does not report a supported USD amount, its cost is **unknown**. This includes direct OpenAI, Gemini, and xAI calls, the official X API (including xurl), ScrapeCreators, paid web-search APIs, transcription, BrightData, Grok CLI, hosted research, and unfinished remote background operations. The output retains any known subtotal as `budget_used` and reports `budget_unknown_runs`; subsequent topics stop while today's store contains unknown spending. A provider's free allowance is not assumed to make an unreported charge zero. Existing zero-cost records and direct engine `--store` runs without accounting also remain unknown. For unattended runs that must continue below the limit, use free sources and providers with supported cost reporting, and inspect the provider's own billing limits for protection outside this guard.++`LAST30DAYS_USAGE_JOURNAL` is an internal subprocess variable managed by `watchlist.py`; do not configure it yourself. Watchlist creates an owner-only temporary journal, records requests before transport, persists the totals even on failure, and removes the journal after the run. It contains provider names, amounts, and token counts, without credentials, queries, or response text. Watchlist disables child `LAST30DAYS_STORE` persistence so the parent records each run once.+### `briefing.py` - daily / weekly digests[`scripts/briefing.py`](skills/last30days/scripts/briefing.py) reads the SQLite store and emits structured data the agent then synthesizes into prose. Modes: `generate` (daily), `generate --weekly`, `show [--date DATE]` (display a saved briefing). Briefs save to `~/.local/share/last30days/briefs/`.diff --git a/changelog.d/+cr-009-watchlist-cost-accounting.fixed.md b/changelog.d/+cr-009-watchlist-cost-accounting.fixed.mdnew file mode 100644index 00000000..fd1b2cfe--- /dev/null+++ b/changelog.d/+cr-009-watchlist-cost-accounting.fixed.md@@ -0,0 +1 @@+Fixed watchlist daily budgets to accumulate provider-reported OpenRouter and Perplexity USD charges, preserve spending after failed or timed-out runs, and stop subsequent topics when the budget is exhausted or paid usage has unknown cost.diff --git a/skills/last30days/scripts/lib/brightdata.py b/skills/last30days/scripts/lib/brightdata.pyindex 1bd3772b..2a6243c3 100644--- a/skills/last30days/scripts/lib/brightdata.py+++ b/skills/last30days/scripts/lib/brightdata.py@@ -36,7 +36,7 @@ import sysfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Sequence-from . import log, subproc+from . import log, subproc, usageCLI_BIN = "brightdata"@@ -235,6 +235,7 @@ def run_pipeline(cmd = _build_args(pipeline_type, params, cli_timeout=cli_timeout)try:+ usage.begin("brightdata")result = subproc.run_with_timeout(cmd, timeout=timeout, env=_child_env(key))except subproc.SubprocTimeout as exc:_log(f"Timeout: {exc}")diff --git a/skills/last30days/scripts/lib/grok_x.py b/skills/last30days/scripts/lib/grok_x.pyindex b5e20e96..b4f7ec86 100644--- a/skills/last30days/scripts/lib/grok_x.py+++ b/skills/last30days/scripts/lib/grok_x.py@@ -41,7 +41,7 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple-from . import log+from . import log, usagefrom .relevance import token_overlap_relevance as _compute_relevance# One copy of the snowflake, handle-grammar, and generated-sequence helpers# lives in x_api; grok_x keeps its private names for its callers and@@ -792,6 +792,7 @@ def _invoke(prompt: str, timeout: int) -> Dict[str, Any]:try:with tempfile.TemporaryDirectory(prefix="last30days-grok-") as workdir:child_home = _stage_child_home(workdir)+ usage.begin("grok")result = subprocess.run([binary,diff --git a/skills/last30days/scripts/lib/hosted.py b/skills/last30days/scripts/lib/hosted.pyindex 2e5e7b76..addae36e 100644--- a/skills/last30days/scripts/lib/hosted.py+++ b/skills/last30days/scripts/lib/hosted.py@@ -33,7 +33,7 @@ import reimport sysimport time-from . import env, http+from . import env, http, usagefrom .log import source_log# Distinct exit code for the clarify gate so the invoking model can tell@@ -84,6 +84,7 @@ def submit(query: str, depth: str, register: str = "default") -> dict:payload = {"query": query, "depth": depth}if register != "default":payload["register"] = register+ usage.begin("hosted")return http.post(f"{_api_base()}/search",json_data=payload,diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.pyindex f2384137..b5f0c26c 100644--- a/skills/last30days/scripts/lib/http.py+++ b/skills/last30days/scripts/lib/http.py@@ -18,7 +18,7 @@ from pathlib import Pathfrom typing import Any, Callable, Dict, Optional, Unionfrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit, quote-from . import health+from . import health, usagefrom . import log as _logDEFAULT_TIMEOUT = 30@@ -909,7 +909,13 @@ def request(breakrequest_timeout = min(timeout, remaining)try:+ charge = usage.begin_http(url, method)response_status, body, response_error = open_and_read_before_deadline(request_timeout)+ if body:+ try:+ usage.finish(charge, json.loads(body))+ except (ValueError, TypeError):+ passif (deadline_monotonic is not Noneand time.monotonic() >= deadline_monotonicdiff --git a/skills/last30days/scripts/lib/parallel_mcp.py b/skills/last30days/scripts/lib/parallel_mcp.pyindex 51f27946..fb3b12e0 100644--- a/skills/last30days/scripts/lib/parallel_mcp.py+++ b/skills/last30days/scripts/lib/parallel_mcp.py@@ -8,7 +8,7 @@ import urllib.requestfrom typing import Anyfrom urllib.parse import urlparse-from . import dates, http+from . import dates, http, usagePARALLEL_MCP_URL = "https://search.parallel.ai/mcp"_PROTOCOL_VERSION = "2025-03-26"@@ -87,6 +87,8 @@ def _request(headers=headers,method="POST" if message is not None else "DELETE",)+ if api_key and message is not None and message.get("method") == "tools/call":+ usage.begin("parallel")with urllib.request.build_opener(_NoRedirect()).open(request, timeout=http.DEFAULT_TIMEOUT) as response:result = _read_response(response, message.get("id")) if message is not None else {}return result, response.headers.get("Mcp-Session-Id") or session_iddiff --git a/skills/last30days/scripts/lib/transcribe.py b/skills/last30days/scripts/lib/transcribe.pyindex dce0fd8c..d3191fb3 100644--- a/skills/last30days/scripts/lib/transcribe.py+++ b/skills/last30days/scripts/lib/transcribe.py@@ -24,7 +24,7 @@ import tempfilefrom dataclasses import dataclass, fieldfrom typing import Optional-from . import env, health, http, log, subproc+from . import env, health, http, log, subproc, usage# Whisper's documented upload ceiling. We compress to stay under it and chunk# when a single clip still exceeds it.@@ -225,6 +225,7 @@ def _post_audio(provider: str, path: str, api_key: str, timeout: float) -> Optio},method="POST",)+ usage.begin(provider)with urllib.request.urlopen(req, timeout=timeout) as resp:data = json.loads(resp.read().decode("utf-8"))return data.get("text")diff --git a/skills/last30days/scripts/lib/usage.py b/skills/last30days/scripts/lib/usage.pynew file mode 100644index 00000000..5b69a51a--- /dev/null+++ b/skills/last30days/scripts/lib/usage.py@@ -0,0 +1,132 @@+"""Provider-reported charges for a scoped watchlist subprocess."""++from __future__ import annotations++import math+import os+import sqlite3+import uuid+from contextlib import contextmanager+from pathlib import Path+from urllib.parse import urlsplit++JOURNAL_ENV = "LAST30DAYS_USAGE_JOURNAL"++_PAID_HOSTS = {+ "openrouter.ai": "openrouter",+ "api.perplexity.ai": "perplexity",+ "api.openai.com": "openai",+ "api.x.ai": "xai",+ "generativelanguage.googleapis.com": "gemini",+ "api.scrapecreators.com": "scrapecreators",+ "api.search.brave.com": "brave",+ "api.tavily.com": "tavily",+ "api.exa.ai": "exa",+ "google.serper.dev": "serper",+ "api.parallel.ai": "parallel",+ "api.x.com": "x",+ "api.twitter.com": "x",+ "xquik.com": "xquik",+ "api.groq.com": "groq",+}+++@contextmanager+def _connection(path):+ conn = sqlite3.connect(path)+ try:+ with conn:+ yield conn+ finally:+ conn.close()+++def create_journal(path: Path) -> None:+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)+ os.close(fd)+ with _connection(path) as conn:+ conn.execute(+ "CREATE TABLE attempts (id TEXT PRIMARY KEY, provider TEXT NOT NULL, "+ "cost REAL, unknown INTEGER NOT NULL DEFAULT 1, "+ "prompt_tokens INTEGER DEFAULT 0, completion_tokens INTEGER DEFAULT 0)"+ )+++def begin(provider: str) -> tuple[str, str, str] | None:+ path = os.environ.get(JOURNAL_ENV)+ if not path:+ return None+ attempt_id = uuid.uuid4().hex+ with _connection(path) as conn:+ conn.execute("INSERT INTO attempts (id, provider) VALUES (?, ?)", (attempt_id, provider))+ return path, attempt_id, provider+++def begin_http(url: str, method: str) -> tuple[str, str, str] | None:+ if not os.environ.get(JOURNAL_ENV):+ return None+ parts = urlsplit(url)+ provider = _PAID_HOSTS.get(parts.hostname)+ if provider == "perplexity" and method == "GET":+ return None # Retrieving an existing background operation does not start another charge.+ if provider is None:+ for name in ("OPENAI", "XAI", "OPENROUTER"):+ override = os.environ.get(f"{name}_BASE_URL")+ if override and urlsplit(override).netloc == parts.netloc:+ provider = name.lower()+ break+ return begin(provider) if provider else None+++def cancel(attempt: tuple[str, str, str] | None) -> None:+ """Remove an attempt when the transport provably never started."""+ if attempt is not None:+ path, attempt_id, _ = attempt+ with _connection(path) as conn:+ conn.execute("DELETE FROM attempts WHERE id = ?", (attempt_id,))+++def finish(attempt: tuple[str, str, str] | None, payload: object) -> None:+ if attempt is None or not isinstance(payload, dict):+ return+ path, attempt_id, provider = attempt+ usage = payload.get("usage")+ if not isinstance(usage, dict):+ return+ cost = usage.get("cost")+ if provider == "perplexity":+ if not isinstance(cost, dict) or cost.get("currency") != "USD":+ return+ cost = cost.get("total_cost")+ elif provider != "openrouter":+ return+ if isinstance(cost, bool) or not isinstance(cost, (int, float)) or not math.isfinite(cost) or cost < 0:+ return+ # A background response may expose a running subtotal rather than its final bill.+ unknown = int(payload.get("status") in {"queued", "in_progress"})+ prompt = usage.get("prompt_tokens", usage.get("input_tokens", 0))+ completion = usage.get("completion_tokens", usage.get("output_tokens", 0))+ prompt = prompt if type(prompt) is int and prompt >= 0 else 0+ completion = completion if type(completion) is int and completion >= 0 else 0+ with _connection(path) as conn:+ conn.execute(+ "UPDATE attempts SET cost = ?, unknown = ?, prompt_tokens = ?, completion_tokens = ? WHERE id = ?",+ (cost, unknown, prompt, completion, attempt_id),+ )+++def read_journal(path: Path) -> dict:+ try:+ with _connection(path) as conn:+ row = conn.execute(+ "SELECT COALESCE(SUM(cost), 0), COALESCE(SUM(unknown), 0), "+ "COALESCE(SUM(prompt_tokens), 0), COALESCE(SUM(completion_tokens), 0) FROM attempts"+ ).fetchone()+ except sqlite3.Error:+ return {"token_cost": 0.0, "cost_unknown": 1, "prompt_tokens": 0, "completion_tokens": 0}+ return {+ "token_cost": row[0],+ "cost_unknown": int(row[1] > 0),+ "prompt_tokens": row[2],+ "completion_tokens": row[3],+ }diff --git a/skills/last30days/scripts/lib/xurl_x.py b/skills/last30days/scripts/lib/xurl_x.pyindex 7a48eaa9..2d267526 100644--- a/skills/last30days/scripts/lib/xurl_x.py+++ b/skills/last30days/scripts/lib/xurl_x.py@@ -19,7 +19,7 @@ import subprocessfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple-from . import health, http, log+from . import health, http, log, usagefrom . import x_api# One X API v2 depth table and one parser: xurl_x re-imports both.from .x_api import DEPTH_CONFIG@@ -278,10 +278,12 @@ def search_x(# X API v2 search/recent requires max_results in 10–100 rangemax_results = max(10, min(100, max_results))+ charge = Nonetry:# --auth app (app-only bearer): xurl >=1.1 mis-signs OAuth1 requests# whose query needs percent-encoding (spaces, parens, ...) -> 401.# 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"],capture_output=True,@@ -300,6 +302,7 @@ def search_x(return json.loads(result.stdout)except FileNotFoundError:+ usage.cancel(charge)return {"error": ERR_NOT_FOUND}except subprocess.TimeoutExpired:return {"error": ERR_TIMED_OUT}diff --git a/skills/last30days/scripts/store.py b/skills/last30days/scripts/store.pyindex 3755c015..70ffeac6 100644--- a/skills/last30days/scripts/store.py+++ b/skills/last30days/scripts/store.py@@ -178,6 +178,7 @@ _UPDATABLE_RUN_COLUMNS = frozenset({"prompt_tokens","completion_tokens","token_cost",+ "cost_unknown","duration_seconds","status","error_message",@@ -240,6 +241,10 @@ CREATE TABLE IF NOT EXISTS discovery_topics (CREATE INDEX IF NOT EXISTS idx_discovery_topics_status_surfacedON discovery_topics(status, last_surfaced);+""",+ 4: """+ALTER TABLE research_runs ADD COLUMN cost_unknown INTEGER NOT NULL DEFAULT 1;+UPDATE research_runs SET cost_unknown = 0 WHERE token_cost > 0;""",}@@ -291,16 +296,31 @@ def init_db(db_path: Optional[Path] = None) -> Path:def _run_migrations(conn: sqlite3.Connection):"""Apply pending schema migrations."""- current = conn.execute(- "SELECT MAX(version) FROM schema_version"- ).fetchone()[0] or 0-- for version in sorted(MIGRATIONS.keys()):- if version > current:- conn.executescript(MIGRATIONS[version])- conn.execute(- "INSERT INTO schema_version (version) VALUES (?)", (version,)- )+ current = conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] or 0+ if current >= max(MIGRATIONS, default=0):+ return+ conn.execute("BEGIN IMMEDIATE")+ try:+ current = conn.execute(+ "SELECT MAX(version) FROM schema_version"+ ).fetchone()[0] or 0+ for version in sorted(MIGRATIONS):+ if version <= current:+ continue+ # executescript commits before running; keep DDL and its marker atomic.+ statement = ""+ for character in MIGRATIONS[version]:+ statement += character+ if character == ";" and sqlite3.complete_statement(statement):+ conn.execute(statement)+ statement = ""+ if statement.strip():+ conn.execute(statement)+ conn.execute("INSERT INTO schema_version (version) VALUES (?)", (version,))+ conn.commit()+ except BaseException:+ conn.rollback()+ raisedef _backfill_owner_sightings(conn: sqlite3.Connection) -> None:@@ -476,7 +496,7 @@ def record_run(duration_seconds: float = 0,prompt_tokens: int = 0,completion_tokens: int = 0,- token_cost: float = 0,+ token_cost: Optional[float] = None,) -> int:"""Record a research run. Returns the run ID."""conn = _connect()@@ -484,11 +504,12 @@ def record_run(cursor = conn.execute("""INSERT INTO research_runs(topic_id, run_date, source_mode, status, error_message,- duration_seconds, prompt_tokens, completion_tokens, token_cost)- VALUES (?, datetime('now'), ?, ?, ?, ?, ?, ?, ?)""",+ duration_seconds, prompt_tokens, completion_tokens, token_cost, cost_unknown)+ VALUES (?, datetime('now'), ?, ?, ?, ?, ?, ?, ?, ?)""",(topic_id, source_mode, status, error_message,duration_seconds, prompt_tokens, completion_tokens, token_cost,+ int(token_cost is None),),)conn.commit()@@ -1122,6 +1143,18 @@ def get_daily_cost(date: Optional[str] = None) -> float:# --- Settings ---+def get_daily_unknown_cost_runs(date: Optional[str] = None) -> int:+ conn = _connect()+ try:+ date = date or datetime.now(timezone.utc).strftime("%Y-%m-%d")+ return conn.execute(+ "SELECT COUNT(*) FROM research_runs WHERE date(run_date) = date(?) AND cost_unknown = 1",+ (date,),+ ).fetchone()[0]+ finally:+ conn.close()++def get_setting(key: str, default: Optional[str] = None) -> Optional[str]:"""Get a setting value."""init_db()diff --git a/skills/last30days/scripts/watchlist.py b/skills/last30days/scripts/watchlist.pyindex 085e663b..e65bc7bb 100644--- a/skills/last30days/scripts/watchlist.py+++ b/skills/last30days/scripts/watchlist.py@@ -5,9 +5,11 @@ from __future__ import annotationsimport argparseimport json+import osimport subprocessimport sysimport time+import tempfileimport urllib.parsefrom pathlib import Path@@ -15,7 +17,7 @@ SCRIPT_DIR = Path(__file__).parent.resolve()sys.path.insert(0, str(SCRIPT_DIR))import store-from lib import http, schema+from lib import http, schema, usage# --- Webhook Delivery Functions ---@@ -121,6 +123,7 @@ def cmd_list(args):"topics": topics,"budget_used": budget_used,"budget_limit": budget_limit,+ "budget_unknown_runs": store.get_daily_unknown_cost_runs(),}, default=str))@@ -137,7 +140,7 @@ def cmd_run_one(args):if not topic:print(json.dumps({"error": f'Topic not found: "{args.topic}"'}))sys.exit(1)- print(json.dumps(_run_topic(topic), default=str))+ print(json.dumps(_budget_skip(topic) or _run_topic(topic), default=str))def cmd_run_all(args):@@ -150,27 +153,49 @@ def cmd_run_all(args):budget_limit = float(store.get_setting("daily_budget", "5.00"))results = []for topic in topics:- if store.get_daily_cost() >= budget_limit:- results.append({- "topic": topic["name"],- "status": "skipped",- "reason": f"Budget exceeded: ${store.get_daily_cost():.2f}/${budget_limit:.2f}",- })- continue- results.append(_run_topic(topic))+ results.append(_budget_skip(topic) or _run_topic(topic))print(json.dumps({"action": "run_all","results": results,"budget_used": store.get_daily_cost(),"budget_limit": budget_limit,+ "budget_unknown_runs": store.get_daily_unknown_cost_runs(),}, default=str))+def _budget_skip(topic: dict) -> dict | None:+ limit = float(store.get_setting("daily_budget", "5.00"))+ cost = store.get_daily_cost()+ unknown = store.get_daily_unknown_cost_runs()+ if cost >= limit:+ reason = f"Budget exceeded: ${cost:.2f}/${limit:.2f}"+ elif unknown:+ reason = f"Budget unknown: {unknown} run(s) today have unreported provider charges"+ else:+ return None+ return {"topic": topic["name"], "status": "skipped", "reason": reason}++def _run_topic(topic: dict) -> dict:+ topic_id = topic["id"]+ with tempfile.TemporaryDirectory(prefix="last30days-usage-") as temp_dir:+ journal = Path(temp_dir) / "usage.db"+ usage.create_journal(journal)+ child_env = dict(os.environ, **{usage.JOURNAL_ENV: str(journal), "LAST30DAYS_STORE": "0"})+ run_id = store.record_run(topic_id, source_mode="v3", status="running")+ try:+ result = _research_topic(topic, run_id, child_env)+ finally:+ costs = usage.read_journal(journal)+ store.update_run(run_id, **costs)+ result.update(costs)+ return result+++def _research_topic(topic: dict, run_id: int, child_env: dict) -> dict:start_time = time.time()topic_id = topic["id"]- run_id = store.record_run(topic_id, source_mode="v3", status="running")try:search_queries = json.loads(topic["search_queries"]) if topic.get("search_queries") else None@@ -194,6 +219,7 @@ def _run_topic(topic: dict) -> dict:capture_output=True,text=True,timeout=300,+ env=child_env,)duration = time.time() - start_timeif result.returncode != 0:diff --git a/tests/test_env_doc_contract.py b/tests/test_env_doc_contract.pyindex 939e72b4..ccb0d8c8 100644--- a/tests/test_env_doc_contract.py+++ b/tests/test_env_doc_contract.py@@ -30,7 +30,8 @@ DOC_ONLY_KEYS = {"LAST30DAYS_MCP_ALLOW_BROWSER_COOKIES","LAST30DAYS_MCP_TIMEOUT","LAST30DAYS_PYTHON",- "LAST30DAYS_MCP_ALLOW_BROWSER_COOKIES",+ # Watchlist owns this private temporary subprocess path; it is not user configuration.+ "LAST30DAYS_USAGE_JOURNAL",# Read from the process environment before or outside get_config# (config-dir override, Keychain/pass source switches), so they are# documented in CONFIGURATION.md without being config keys.diff --git a/tests/test_store.py b/tests/test_store.pyindex 4e44c918..6fbd2a78 100644--- a/tests/test_store.py+++ b/tests/test_store.py@@ -892,8 +892,8 @@ def test_get_new_findings_filters_by_date(temp_db, sample_report):# === Tests for the discovery topic queue (migration 3, U6) ===-def test_init_db_reaches_migration_3_with_discovery_topics_table(temp_db):- """A fresh database lands on migration 3 with the queue table present."""+def test_init_db_reaches_migration_4_with_discovery_topics_table(temp_db):+ """A fresh database lands on migration 4 with the queue table present."""conn = sqlite3.connect(str(temp_db))version = conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0]table = conn.execute(@@ -904,7 +904,7 @@ def test_init_db_reaches_migration_3_with_discovery_topics_table(temp_db):}conn.close()- assert version == 3+ assert version == 4assert table is not Noneassert {"id", "name", "normalized_name", "entity_key", "domain",@@ -913,7 +913,7 @@ def test_init_db_reaches_migration_3_with_discovery_topics_table(temp_db):} <= columns-def test_migration_2_db_upgrades_to_3_without_data_loss(tmp_path, monkeypatch):+def test_migration_2_db_upgrades_to_4_without_data_loss(tmp_path, monkeypatch):"""A database built at migration 2 gains the queue table without losing rows."""db_path = tmp_path / "research.db"monkeypatch.setattr(store, "_db_override", db_path)@@ -922,7 +922,11 @@ def test_migration_2_db_upgrades_to_3_without_data_loss(tmp_path, monkeypatch):monkeypatch.setattr(store, "MIGRATIONS", {2: full_migrations[2]})store.init_db()topic = store.add_topic("Preexisting Topic")- run_id = store.record_run(topic["id"], source_mode="v3")+ with sqlite3.connect(db_path) as conn:+ run_id = conn.execute(+ "INSERT INTO research_runs (topic_id, run_date, source_mode) VALUES (?, datetime('now'), 'v3')",+ (topic["id"],),+ ).lastrowidstore.store_findings(run_id, topic["id"], [{"source": "reddit","source_url": "https://reddit.com/preexisting",@@ -941,7 +945,7 @@ def test_migration_2_db_upgrades_to_3_without_data_loss(tmp_path, monkeypatch):store.init_db()conn = sqlite3.connect(str(db_path))- assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 3+ assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 4assert conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='discovery_topics'").fetchone() is not None@@ -950,6 +954,29 @@ def test_migration_2_db_upgrades_to_3_without_data_loss(tmp_path, monkeypatch):conn.close()+def test_cost_migration_preserves_known_spend_and_marks_legacy_zero_unknown(tmp_path, monkeypatch):+ db_path = tmp_path / "research.db"+ monkeypatch.setattr(store, "_db_override", db_path)+ full_migrations = store.MIGRATIONS+ monkeypatch.setattr(store, "MIGRATIONS", {key: value for key, value in full_migrations.items() if key < 4})+ store.init_db()+ topic = store.add_topic("Legacy")+ conn = sqlite3.connect(db_path)+ try:+ conn.executemany(+ "INSERT INTO research_runs (topic_id, run_date, token_cost) VALUES (?, datetime('now'), ?)",+ [(topic["id"], 0), (topic["id"], 1.25)],+ )+ conn.commit()+ finally:+ conn.close()+ monkeypatch.setattr(store, "MIGRATIONS", full_migrations)+ store.init_db()+ store.init_db()+ assert store.get_daily_cost() == 1.25+ assert store.get_daily_unknown_cost_runs() == 1++def test_record_discovery_surfacing_inserts_fresh_row(temp_db):row = store.record_discovery_surfacing("Gemma 4 chat templates",diff --git a/tests/test_store_migrations.py b/tests/test_store_migrations.pynew file mode 100644index 00000000..197dae42--- /dev/null+++ b/tests/test_store_migrations.py@@ -0,0 +1,117 @@+"""Migrations publish schema changes and their version marker together."""++import sqlite3+import threading+from concurrent.futures import ThreadPoolExecutor++import pytest++import store+++def version_three(tmp_path, monkeypatch):+ path = tmp_path / "research.db"+ monkeypatch.setattr(store, "_db_override", path)+ migrations = store.MIGRATIONS+ monkeypatch.setattr(store, "MIGRATIONS", {key: value for key, value in migrations.items() if key < 4})+ store.init_db()+ monkeypatch.setattr(store, "MIGRATIONS", migrations)+ return path+++def test_failed_version_write_rolls_back_schema_and_retry_succeeds(version_three):+ conn = store._connect()++ def deny_version_write(action, table, *unused):+ return sqlite3.SQLITE_DENY if action == sqlite3.SQLITE_INSERT and table == "schema_version" else sqlite3.SQLITE_OK++ conn.set_authorizer(deny_version_write)+ try:+ with pytest.raises(sqlite3.DatabaseError, match="authorized"):+ store._run_migrations(conn)+ finally:+ conn.close()++ conn = store._connect()+ try:+ assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 3+ assert "cost_unknown" not in {row[1] for row in conn.execute("PRAGMA table_info(research_runs)")}+ finally:+ conn.close()+ store.init_db()+ conn = store._connect()+ try:+ assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 4+ assert "cost_unknown" in {row[1] for row in conn.execute("PRAGMA table_info(research_runs)")}+ finally:+ conn.close()+++def test_concurrent_initialization_applies_each_version_once(version_three):+ barrier = threading.Barrier(8)++ def initialize(_):+ barrier.wait(timeout=5)+ return store.init_db()++ with ThreadPoolExecutor(max_workers=8) as executor:+ assert list(executor.map(initialize, range(8))) == [version_three] * 8+ conn = store._connect()+ try:+ assert [row[0] for row in conn.execute("SELECT version FROM schema_version ORDER BY version")] == [1, 2, 3, 4]+ finally:+ conn.close()+++def test_current_schema_check_succeeds_while_another_connection_holds_writer(version_three):+ store.init_db()+ writer = store._connect()+ reader = store._connect()+ try:+ writer.execute("BEGIN IMMEDIATE")+ writer.execute("INSERT INTO settings (key, value) VALUES ('held-writer', 'uncommitted')")+ reader.execute("PRAGMA busy_timeout=1")++ store._run_migrations(reader)++ assert not reader.in_transaction+ assert reader.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 4+ assert reader.execute("SELECT value FROM settings WHERE key = 'held-writer'").fetchone() is None+ finally:+ writer.rollback()+ writer.close()+ reader.close()+++def test_pending_migration_after_committed_default_seeding(version_three):+ conn = store._connect()+ try:+ conn.execute("DELETE FROM settings WHERE key = 'daily_budget'")+ conn.execute("INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", ("daily_budget", "9.25"))+ conn.commit()++ store._run_migrations(conn)++ assert conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] == 4+ assert conn.execute("SELECT value FROM settings WHERE key = 'daily_budget'").fetchone()[0] == "9.25"+ assert "cost_unknown" in {row[1] for row in conn.execute("PRAGMA table_info(research_runs)")}+ finally:+ conn.close()+++def test_migration_retains_trigger_body_and_quoted_semicolons(version_three, monkeypatch):+ monkeypatch.setattr(store, "MIGRATIONS", {+ **store.MIGRATIONS,+ 5: """+CREATE TABLE migration_probe (value TEXT);+CREATE TRIGGER migration_probe_insert AFTER INSERT ON migration_probe BEGIN+ INSERT INTO settings(key, value) VALUES ('trigger-one', 'value;one');+ INSERT INTO settings(key, value) VALUES ('trigger-two', new.value);+END;+INSERT INTO migration_probe VALUES ('value;two');+""",+ })+ store.init_db()+ assert store.get_setting("trigger-one") == "value;one"+ assert store.get_setting("trigger-two") == "value;two"diff --git a/tests/test_usage_accounting.py b/tests/test_usage_accounting.pynew file mode 100644index 00000000..6059642e--- /dev/null+++ b/tests/test_usage_accounting.py@@ -0,0 +1,162 @@+"""Only authoritative provider response amounts become budget dollars."""++import io+import json+import sqlite3+import subprocess+from concurrent.futures import ThreadPoolExecutor++import pytest++from lib import brightdata, grok_x, hosted, http, parallel_mcp, transcribe, usage, xurl_x+++def journal(tmp_path, monkeypatch):+ path = tmp_path / "usage.db"+ usage.create_journal(path)+ monkeypatch.setenv(usage.JOURNAL_ENV, str(path))+ return path+++def request(monkeypatch, url, payload):+ class Response(io.BytesIO):+ status = 200++ monkeypatch.setattr(http, "_open_request", lambda req, timeout: Response(json.dumps(payload).encode()))+ return http.post(url, {"model": "example"}, retries=1)+++def test_perplexity_agent_records_usd_and_tokens(journal, monkeypatch):+ request(monkeypatch, "https://api.perplexity.ai/v1/agent", {+ "status": "completed",+ "usage": {"input_tokens": 80, "output_tokens": 20, "cost": {"currency": "USD", "total_cost": 0.75}},+ })+ assert usage.read_journal(journal) == {+ "token_cost": 0.75, "cost_unknown": 0, "prompt_tokens": 80, "completion_tokens": 20,+ }++[email protected]("cost", [None, True, -0.1, float("nan"), float("inf"), "0.50", {}])+def test_invalid_cost_never_becomes_known_spend(journal, monkeypatch, cost):+ request(monkeypatch, "https://openrouter.ai/api/v1/chat/completions", {"usage": {"cost": cost}})+ assert usage.read_journal(journal)["cost_unknown"] == 1+++def test_usage_counts_and_non_usd_currency_are_unknown(journal, monkeypatch):+ request(monkeypatch, "https://api.perplexity.ai/v1/agent", {+ "usage": {"input_tokens": 1000, "cost": {"currency": "credits", "total_cost": 20}},+ })+ assert usage.read_journal(journal)["cost_unknown"] == 1+ assert usage.read_journal(journal)["token_cost"] == 0+++def test_in_progress_remote_charge_is_unknown(journal, monkeypatch):+ request(monkeypatch, "https://api.perplexity.ai/v1/agent", {+ "status": "in_progress", "usage": {"cost": {"currency": "USD", "total_cost": 0.3}},+ })+ assert usage.read_journal(journal)["cost_unknown"] == 1+ assert usage.read_journal(journal)["token_cost"] == 0.3+++def test_untrusted_search_result_cannot_add_cost(journal, monkeypatch):+ request(monkeypatch, "https://example.org/article", {"usage": {"cost": 99.9}})+ assert usage.read_journal(journal)["token_cost"] == 0+ assert usage.read_journal(journal)["cost_unknown"] == 0+++def test_parallel_requests_keep_every_charge(journal, monkeypatch):+ request(monkeypatch, "https://openrouter.ai/api/v1/chat/completions", {"usage": {"cost": 0.1}})+ with ThreadPoolExecutor(max_workers=5) as executor:+ list(executor.map(lambda _: http.post("https://openrouter.ai/api/v1/chat/completions", {}), range(20)))+ assert usage.read_journal(journal)["token_cost"] == pytest.approx(2.1)+ assert usage.read_journal(journal)["cost_unknown"] == 0+++def test_pending_transport_is_unknown_and_journal_excludes_secrets(journal, monkeypatch):+ def interrupted(req, timeout):+ raise KeyboardInterrupt++ monkeypatch.setattr(http, "_open_request", interrupted)+ with pytest.raises(KeyboardInterrupt):+ http.post("https://openrouter.ai/api/v1/chat/completions?secret=forbidden-query", {"input": "forbidden-prompt"}, headers={"Authorization": "Bearer forbidden-token"})+ assert usage.read_journal(journal)["cost_unknown"] == 1+ assert b"forbidden" not in journal.read_bytes()+ assert journal.stat().st_mode & 0o777 == 0o600+++def test_unscoped_calls_have_no_accounting_side_effects(tmp_path, monkeypatch):+ monkeypatch.delenv(usage.JOURNAL_ENV, raising=False)+ request(monkeypatch, "https://openrouter.ai/api/v1/chat/completions", {"usage": {"cost": 0.1}})+ assert list(tmp_path.iterdir()) == []+++def test_broken_journal_remains_unknown(journal):+ with sqlite3.connect(journal) as conn:+ conn.execute("DROP TABLE attempts")+ assert usage.read_journal(journal)["cost_unknown"] == 1+++def test_transcription_charge_without_usd_remains_unknown(journal, tmp_path, monkeypatch):+ audio = tmp_path / "sample.mp3"+ audio.write_bytes(b"dummy-audio")+ monkeypatch.setattr("urllib.request.urlopen", lambda *a, **kw: io.BytesIO(b'{"text":"words"}'))+ assert transcribe._post_audio("openai", str(audio), "dummy-key", 1) == "words"+ assert usage.read_journal(journal)["cost_unknown"] == 1+++def test_brightdata_charge_without_usd_remains_unknown(journal, monkeypatch):+ monkeypatch.setattr(brightdata, "is_installed", lambda: True)+ monkeypatch.setattr(brightdata.subproc, "run_with_timeout", lambda *a, **kw: subprocess.CompletedProcess([], 0, "[]", ""))+ brightdata.run_pipeline("amazon_product_search", [], timeout=1, config={"BRIGHTDATA_API_KEY": "dummy-key"})+ assert usage.read_journal(journal)["cost_unknown"] == 1+++def test_grok_charge_without_usd_remains_unknown(journal, tmp_path, monkeypatch):+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/dummy/grok")+ monkeypatch.setattr(grok_x, "_stage_child_home", lambda _: str(tmp_path))+ monkeypatch.setattr(grok_x.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess([], 0, "{}", ""))+ grok_x._invoke("topic", 1)+ assert usage.read_journal(journal)["cost_unknown"] == 1+++def test_hosted_charge_without_usd_remains_unknown(journal, monkeypatch):+ monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1")+ monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-key")+ request(monkeypatch, "https://example.org", {})+ hosted.submit("topic", "quick")+ assert usage.read_journal(journal)["cost_unknown"] == 1+++def test_authenticated_parallel_tool_charge_without_usd_remains_unknown(journal, monkeypatch):+ class Response(io.BytesIO):+ headers = {"Content-Type": "application/json"}++ class Opener:+ def open(self, *args, **kwargs):+ return Response(b'{"jsonrpc":"2.0","id":1,"result":{}}')++ monkeypatch.setattr("urllib.request.build_opener", lambda *args: Opener())+ parallel_mcp._request({"jsonrpc": "2.0", "id": 1, "method": "tools/call"}, "dummy-key")+ assert usage.read_journal(journal)["cost_unknown"] == 1+++def test_xurl_search_charge_without_usd_remains_unknown(journal, monkeypatch):+ monkeypatch.setattr(xurl_x.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess([], 0, '{"data":[]}', ""))+ assert xurl_x.search_x("topic") == {"data": []}+ assert usage.read_journal(journal)["cost_unknown"] == 1+++def test_xurl_local_auth_probe_does_not_consume_budget(journal, monkeypatch):+ monkeypatch.setattr(xurl_x.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess([], 0, "bearer: ✓", ""))+ assert xurl_x._is_available_uncached()+ assert usage.read_journal(journal)["cost_unknown"] == 0+++def test_missing_xurl_binary_has_no_charge(journal, monkeypatch):+ def missing(*args, **kwargs):+ raise FileNotFoundError++ monkeypatch.setattr(xurl_x.subprocess, "run", missing)+ assert xurl_x.search_x("topic") == {"error": xurl_x.ERR_NOT_FOUND}+ assert usage.read_journal(journal)["cost_unknown"] == 0diff --git a/tests/test_watchlist_costs.py b/tests/test_watchlist_costs.pynew file mode 100644index 00000000..9fe90ad5--- /dev/null+++ b/tests/test_watchlist_costs.py@@ -0,0 +1,151 @@+"""Exercise provider accounting through real child processes and SQLite."""++import json+import subprocess+from pathlib import Path+from types import SimpleNamespace++import pytest++import store+import watchlist+from lib import usage+++def isolated_store(tmp_path, monkeypatch):+ monkeypatch.setattr(store, "_db_override", tmp_path / "research.db")+ store.init_db()+ store.set_setting("daily_budget", "1.00")+ for name in ("First", "Second", "Third"):+ store.add_topic(name)+++def install_child(tmp_path, monkeypatch, *, cost=0.6, fail=False, free=False, after=""):+ script_dir = Path(watchlist.__file__).resolve().parent+ child = tmp_path / "last30days.py"+ child.write_text(+ "import io, json, sys\n"+ f"sys.path.insert(0, {str(script_dir)!r})\n"+ "from lib import http, providers\n"+ f"payload = {{'choices': [{{'message': {{'content': 'ok'}}}}], 'usage': {{'cost': {cost!r}}}}}\n"+ "class Response(io.BytesIO):\n"+ " status = 200\n"+ "def respond(req, timeout):\n"+ " return Response(json.dumps(payload).encode())\n"+ "http._open_request = respond\n"+ + (+ "http.get('https://www.reddit.com/r/example.json')\n"+ if free else+ "providers.OpenRouterClient('dummy-key').generate_text('example/model', 'prompt')\n"+ )+ + ("raise SystemExit(1)\n" if fail else "")+ + after+ + "print(json.dumps({'topic': sys.argv[1], 'range_from': '2026-01-01', 'range_to': '2026-04-01', "+ "'generated_at': '2026-04-01T00:00:00Z', 'provider_runtime': {'reasoning_provider': 'local', "+ "'planner_model': 'local', 'rerank_model': 'local'}, 'query_plan': {'intent': 'test', "+ "'freshness_mode': 'recent', 'cluster_mode': 'standard', 'raw_topic': sys.argv[1]}}))\n"+ )+ monkeypatch.setattr(watchlist, "SCRIPT_DIR", tmp_path)+++def test_paid_topics_continue_below_budget_and_stop_at_limit(isolated_store, tmp_path, monkeypatch, capsys):+ install_child(tmp_path, monkeypatch)+ watchlist.cmd_run_all(None)+ output = json.loads(capsys.readouterr().out)+ assert output["budget_used"] == pytest.approx(1.2)+ assert [row["status"] for row in output["results"]] == ["completed", "completed", "skipped"]+++def test_spend_survives_later_child_failure(isolated_store, tmp_path, monkeypatch, capsys):+ install_child(tmp_path, monkeypatch, cost=1.25, fail=True)+ watchlist.cmd_run_all(None)+ output = json.loads(capsys.readouterr().out)+ assert output["budget_used"] == pytest.approx(1.25)+ assert [row["status"] for row in output["results"]] == ["failed", "skipped", "skipped"]+++def test_free_topics_do_not_consume_budget(isolated_store, tmp_path, monkeypatch, capsys):+ install_child(tmp_path, monkeypatch, free=True)+ watchlist.cmd_run_all(None)+ output = json.loads(capsys.readouterr().out)+ assert output["budget_used"] == 0+ assert [row["status"] for row in output["results"]] == ["completed"] * 3+++def test_missing_paid_cost_is_explicit_and_blocks_next_topic(isolated_store, tmp_path, monkeypatch, capsys):+ install_child(tmp_path, monkeypatch, cost=None)+ watchlist.cmd_run_all(None)+ output = json.loads(capsys.readouterr().out)+ assert [row["status"] for row in output["results"]] == ["completed", "skipped", "skipped"]+ assert output["budget_unknown_runs"] == 1+ assert "unknown" in output["results"][1]["reason"].lower()+++def test_completed_spend_survives_child_timeout(isolated_store, tmp_path, monkeypatch, capsys):+ install_child(tmp_path, monkeypatch, cost=1.25, after="import time; time.sleep(60)\n")+ run = subprocess.run++ def short_timeout(*args, **kwargs):+ kwargs["timeout"] = 1+ return run(*args, **kwargs)++ monkeypatch.setattr(watchlist.subprocess, "run", short_timeout)+ watchlist.cmd_run_all(None)+ output = json.loads(capsys.readouterr().out)+ assert output["budget_used"] == pytest.approx(1.25)+ assert output["results"][0]["error"] == "timeout"+ assert [row["status"] for row in output["results"]] == ["failed", "skipped", "skipped"]+++def test_partial_unknown_spend_retains_known_subtotal(isolated_store, tmp_path, monkeypatch, capsys):+ install_child(+ tmp_path, monkeypatch, cost=0.4,+ after="http.post('https://api.openai.com/v1/responses', {'model': 'example'})\n",+ )+ watchlist.cmd_run_all(None)+ output = json.loads(capsys.readouterr().out)+ assert output["budget_used"] == pytest.approx(0.4)+ assert output["budget_unknown_runs"] == 1+ assert [row["status"] for row in output["results"]] == ["completed", "skipped", "skipped"]+++def test_run_one_respects_spend_from_previous_failure(isolated_store, tmp_path, monkeypatch, capsys):+ install_child(tmp_path, monkeypatch, cost=1.25, fail=True)+ watchlist._run_topic(store.get_topic("First"))+ args = type("Args", (), {"topic": "Second"})()+ watchlist.cmd_run_one(args)+ output = json.loads(capsys.readouterr().out)+ assert output["status"] == "skipped"+ assert store.get_daily_cost() == pytest.approx(1.25)++[email protected]("failure", ["directory", "journal"])+def test_prelaunch_setup_failure_does_not_block_later_research(+ isolated_store, tmp_path, monkeypatch, capsys, failure,+):+ install_child(tmp_path, monkeypatch)+ topic = store.get_topic("First")+ with monkeypatch.context() as setup_failure:+ if failure == "directory":+ unavailable = tmp_path / "not-a-directory"+ unavailable.write_text("file blocks temporary directory creation")+ setup_failure.setattr(watchlist.tempfile, "tempdir", str(unavailable))+ else:+ original_open = usage.os.open++ def deny_journal(path, *args, **kwargs):+ if Path(path).name == "usage.db":+ raise PermissionError("journal creation denied")+ return original_open(path, *args, **kwargs)++ setup_failure.setattr(usage.os, "open", deny_journal)+ with pytest.raises(OSError):+ watchlist._run_topic(topic)++ assert store.get_daily_unknown_cost_runs() == 0+ assert store.get_daily_cost() == 0+ watchlist.cmd_run_one(SimpleNamespace(topic="First"))+ output = json.loads(capsys.readouterr().out)+ assert output["status"] == "completed"+ assert store.get_daily_cost() == pytest.approx(0.6)