返回 last30days-skill
store.py
根目录 / skills / last30days / scripts / store.py
1 #!/usr/bin/env python3
2 """SQLite research accumulator for last30days.
3
4 Stores topics, research runs, and findings with:
5 - WAL mode for safe concurrent access (cron + user)
6 - FTS5 full-text search with porter+unicode61 tokenizer
7 - URL-based dedup with engagement metric updates on re-sighting
8 - Lightweight schema migrations without external dependencies
9
10 Database location: ~/.local/share/last30days/research.db
11 """
12
13 import argparse
14 import json
15 import math
16 import re
17 import sqlite3
18 import sys
19 from contextlib import contextmanager
20 from datetime import datetime, timedelta, timezone
21 from decimal import Decimal, InvalidOperation
22 from pathlib import Path
23 from typing import Any, Dict, Iterator, List, Optional
24
25 SCRIPT_DIR = Path(__file__).parent.resolve()
26 sys.path.insert(0, str(SCRIPT_DIR))
27
28 from lib import dedupe, entity_extract, schema
29 from lib.private_files import prepare_private_sqlite_files
30
31 DB_DIR = Path.home() / ".local" / "share" / "last30days"
32 DB_PATH = DB_DIR / "research.db"
33
34 # Allow override for testing
35 _db_override = None
36
37
38 def _get_db_path() -> Path:
39 return _db_override or DB_PATH
40
41
42 @contextmanager
43 def scoped_db(db_path: Optional[Path]) -> Iterator[None]:
44 """Route all store access inside the block to ``db_path``.
45
46 ``None`` keeps the shared store. Scoped runs (``--save-dir``) use this so
47 their findings land next to their briefs instead of leaking into the
48 shared research.db that unscoped searches read.
49 """
50 global _db_override
51 if db_path is None:
52 yield
53 return
54 previous = _db_override
55 _db_override = Path(db_path)
56 try:
57 yield
58 finally:
59 _db_override = previous
60
61
62 def ensure_private_db_files(db_path: Optional[Path] = None) -> Path:
63 """Create/harden the research database and SQLite sidecars owner-only."""
64 path = db_path or _get_db_path()
65 path.parent.mkdir(parents=True, exist_ok=True)
66 return prepare_private_sqlite_files(path, create=True)
67
68
69 SCHEMA_V1 = """
70 PRAGMA journal_mode=WAL;
71 PRAGMA synchronous=NORMAL;
72 PRAGMA cache_size=-64000;
73
74 CREATE TABLE IF NOT EXISTS schema_version (
75 version INTEGER PRIMARY KEY,
76 applied_at TEXT DEFAULT (datetime('now'))
77 );
78
79 CREATE TABLE IF NOT EXISTS topics (
80 id INTEGER PRIMARY KEY,
81 name TEXT UNIQUE NOT NULL,
82 search_queries TEXT,
83 schedule TEXT,
84 enabled INTEGER DEFAULT 1,
85 created_at TEXT DEFAULT (datetime('now')),
86 updated_at TEXT DEFAULT (datetime('now'))
87 );
88
89 CREATE TABLE IF NOT EXISTS research_runs (
90 id INTEGER PRIMARY KEY,
91 topic_id INTEGER REFERENCES topics(id),
92 run_date TEXT NOT NULL,
93 source_mode TEXT,
94 prompt_tokens INTEGER,
95 completion_tokens INTEGER,
96 token_cost REAL,
97 duration_seconds REAL,
98 status TEXT DEFAULT 'completed',
99 error_message TEXT,
100 findings_new INTEGER DEFAULT 0,
101 findings_updated INTEGER DEFAULT 0,
102 created_at TEXT DEFAULT (datetime('now'))
103 );
104
105 CREATE TABLE IF NOT EXISTS findings (
106 id INTEGER PRIMARY KEY,
107 run_id INTEGER REFERENCES research_runs(id),
108 topic_id INTEGER REFERENCES topics(id),
109 source TEXT NOT NULL,
110 source_url TEXT UNIQUE,
111 source_title TEXT,
112 author TEXT,
113 content TEXT,
114 summary TEXT,
115 engagement_score REAL,
116 relevance_score REAL,
117 first_seen TEXT DEFAULT (datetime('now')),
118 last_seen TEXT DEFAULT (datetime('now')),
119 sighting_count INTEGER DEFAULT 1,
120 dismissed INTEGER DEFAULT 0
121 );
122
123 CREATE INDEX IF NOT EXISTS idx_findings_topic ON findings(topic_id, first_seen);
124 CREATE INDEX IF NOT EXISTS idx_findings_source ON findings(source, topic_id);
125 CREATE INDEX IF NOT EXISTS idx_findings_url ON findings(source_url);
126
127 CREATE VIRTUAL TABLE IF NOT EXISTS findings_fts USING fts5(
128 content, summary, source_title, author,
129 tokenize='porter unicode61',
130 content='findings',
131 content_rowid='id'
132 );
133
134 CREATE TRIGGER IF NOT EXISTS findings_ai AFTER INSERT ON findings BEGIN
135 INSERT INTO findings_fts(rowid, content, summary, source_title, author)
136 VALUES (new.id, new.content, new.summary, new.source_title, new.author);
137 END;
138
139 CREATE TRIGGER IF NOT EXISTS findings_ad AFTER DELETE ON findings BEGIN
140 INSERT INTO findings_fts(findings_fts, rowid, content, summary, source_title, author)
141 VALUES ('delete', old.id, old.content, old.summary, old.source_title, old.author);
142 END;
143
144 CREATE TRIGGER IF NOT EXISTS findings_au AFTER UPDATE ON findings BEGIN
145 INSERT INTO findings_fts(findings_fts, rowid, content, summary, source_title, author)
146 VALUES ('delete', old.id, old.content, old.summary, old.source_title, old.author);
147 INSERT INTO findings_fts(rowid, content, summary, source_title, author)
148 VALUES (new.id, new.content, new.summary, new.source_title, new.author);
149 END;
150
151 CREATE TABLE IF NOT EXISTS settings (
152 key TEXT PRIMARY KEY,
153 value TEXT,
154 updated_at TEXT DEFAULT (datetime('now'))
155 );
156 """
157
158 _DEFAULT_SETTINGS = {
159 "daily_budget": "5.00",
160 "delivery_channel": "",
161 "delivery_mode": "announce",
162 "briefing_format": "concise",
163 "default_schedule": "0 8 * * *",
164 }
165
166 _UPDATABLE_RUN_COLUMNS = frozenset({
167 "source_mode",
168 "prompt_tokens",
169 "completion_tokens",
170 "token_cost",
171 "cost_unknown",
172 "duration_seconds",
173 "status",
174 "error_message",
175 "findings_new",
176 "findings_updated",
177 })
178 _RUN_ACCOUNTING_COLUMNS = frozenset({"token_cost", "cost_unknown"})
179
180 _UPDATABLE_FINDING_COLUMNS = frozenset({
181 "source",
182 "source_url",
183 "source_title",
184 "author",
185 "content",
186 "summary",
187 "engagement_score",
188 "relevance_score",
189 "last_seen",
190 "sighting_count",
191 "dismissed",
192 })
193
194 # Future migrations keyed by version number
195 MIGRATIONS: Dict[int, str] = {
196 2: """
197 CREATE TABLE IF NOT EXISTS finding_sightings (
198 id INTEGER PRIMARY KEY,
199 finding_id INTEGER NOT NULL REFERENCES findings(id) ON DELETE CASCADE,
200 run_id INTEGER REFERENCES research_runs(id) ON DELETE CASCADE,
201 topic_id INTEGER REFERENCES topics(id) ON DELETE CASCADE,
202 source TEXT NOT NULL,
203 source_url TEXT NOT NULL,
204 source_title TEXT,
205 engagement_score REAL,
206 relevance_score REAL,
207 seen_at TEXT DEFAULT (datetime('now')),
208 UNIQUE(run_id, finding_id)
209 );
210
211 CREATE INDEX IF NOT EXISTS idx_finding_sightings_run
212 ON finding_sightings(run_id, topic_id);
213 CREATE INDEX IF NOT EXISTS idx_finding_sightings_topic_seen
214 ON finding_sightings(topic_id, seen_at);
215 CREATE INDEX IF NOT EXISTS idx_finding_sightings_url
216 ON finding_sightings(source_url);
217 """,
218 3: """
219 CREATE TABLE IF NOT EXISTS discovery_topics (
220 id INTEGER PRIMARY KEY,
221 name TEXT NOT NULL,
222 normalized_name TEXT NOT NULL UNIQUE,
223 entity_key TEXT,
224 domain TEXT,
225 first_surfaced TEXT NOT NULL,
226 last_surfaced TEXT NOT NULL,
227 surface_count INTEGER NOT NULL DEFAULT 1,
228 status TEXT NOT NULL DEFAULT 'surfaced' CHECK(status IN ('surfaced','covered')),
229 covered_at TEXT,
230 last_run_ref TEXT
231 );
232
233 CREATE INDEX IF NOT EXISTS idx_discovery_topics_status_surfaced
234 ON discovery_topics(status, last_surfaced);
235 """,
236 4: """
237 ALTER TABLE research_runs ADD COLUMN cost_unknown INTEGER NOT NULL DEFAULT 1;
238 UPDATE research_runs SET cost_unknown = 0 WHERE token_cost > 0;
239 """,
240 5: """
241 CREATE TABLE IF NOT EXISTS removed_run_usage (
242 run_id INTEGER PRIMARY KEY,
243 run_day TEXT,
244 token_cost REAL,
245 cost_unknown INTEGER NOT NULL
246 );
247
248 CREATE INDEX IF NOT EXISTS idx_removed_run_usage_day ON removed_run_usage(run_day);
249 """,
250 }
251
252
253 def _connect(db_path: Optional[Path] = None) -> sqlite3.Connection:
254 """Open a connection with WAL mode and row factory."""
255 path = ensure_private_db_files(db_path)
256 conn = sqlite3.connect(str(path))
257 conn.row_factory = sqlite3.Row
258 conn.execute("PRAGMA journal_mode=WAL")
259 conn.execute("PRAGMA synchronous=NORMAL")
260 conn.execute("PRAGMA foreign_keys=ON")
261 # WAL lets readers coexist with one writer, but two writers (cron + user)
262 # still contend for the write lock. Default busy_timeout is 0, so the loser
263 # raises "database is locked" instantly; wait instead.
264 conn.execute("PRAGMA busy_timeout=5000")
265 return conn
266
267
268 def init_db(db_path: Optional[Path] = None) -> Path:
269 """Create database and tables if they don't exist. Returns the DB path."""
270 path = db_path or _get_db_path()
271 conn = _connect(path)
272 try:
273 conn.executescript(SCHEMA_V1)
274 if not conn.execute("SELECT 1 FROM schema_version WHERE version = 1").fetchone():
275 conn.execute("INSERT OR IGNORE INTO schema_version (version) VALUES (1)")
276 existing_settings = {row["key"] for row in conn.execute("SELECT key FROM settings")}
277 missing_defaults = [
278 (key, value) for key, value in _DEFAULT_SETTINGS.items()
279 if key not in existing_settings
280 ]
281 if missing_defaults:
282 conn.executemany(
283 "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
284 missing_defaults,
285 )
286 conn.commit()
287 _run_migrations(conn)
288 conn.commit()
289 _backfill_owner_sightings(conn)
290 finally:
291 conn.close()
292
293 return path
294
295
296 def _run_migrations(conn: sqlite3.Connection):
297 """Apply pending schema migrations."""
298 current = conn.execute("SELECT MAX(version) FROM schema_version").fetchone()[0] or 0
299 if current >= max(MIGRATIONS, default=0):
300 return
301 conn.execute("BEGIN IMMEDIATE")
302 try:
303 current = conn.execute(
304 "SELECT MAX(version) FROM schema_version"
305 ).fetchone()[0] or 0
306 for version in sorted(MIGRATIONS):
307 if version <= current:
308 continue
309 # executescript commits before running; keep DDL and its marker atomic.
310 statement = ""
311 for character in MIGRATIONS[version]:
312 statement += character
313 if character == ";" and sqlite3.complete_statement(statement):
314 conn.execute(statement)
315 statement = ""
316 if statement.strip():
317 conn.execute(statement)
318 conn.execute("INSERT INTO schema_version (version) VALUES (?)", (version,))
319 conn.commit()
320 except BaseException:
321 conn.rollback()
322 raise
323
324
325 def _backfill_owner_sightings(conn: sqlite3.Connection) -> None:
326 """Preserve legacy first observations before aggregate ownership can change."""
327 marker = "_topic_sightings_backfilled_v1"
328 if conn.execute("SELECT 1 FROM settings WHERE key = ?", (marker,)).fetchone():
329 return
330 with conn:
331 conn.execute("BEGIN IMMEDIATE")
332 if conn.execute("SELECT 1 FROM settings WHERE key = ?", (marker,)).fetchone():
333 return
334 conn.execute(
335 """INSERT INTO finding_sightings
336 (finding_id, run_id, topic_id, source, source_url, source_title,
337 engagement_score, relevance_score, seen_at)
338 SELECT f.id, NULL, f.topic_id, f.source, COALESCE(f.source_url, ''),
339 f.source_title, f.engagement_score, f.relevance_score, f.first_seen
340 FROM findings f
341 WHERE f.topic_id IS NOT NULL AND f.first_seen IS NOT NULL
342 AND NOT EXISTS (
343 SELECT 1 FROM finding_sightings s
344 WHERE s.finding_id = f.id AND s.topic_id = f.topic_id
345 AND s.seen_at <= f.first_seen
346 )"""
347 )
348 conn.execute("INSERT INTO settings (key, value) VALUES (?, '1')", (marker,))
349
350
351 # --- Topics ---
352
353
354 # Ledger dates survive aggregate ownership reassignment; references are a legacy fallback.
355 _FINDING_TOPICS_SQL = """
356 SELECT finding_id, topic_id,
357 COALESCE(MIN(sighting_seen), MIN(legacy_first_seen)) AS first_seen
358 FROM (
359 SELECT id AS finding_id, topic_id, NULL AS sighting_seen, first_seen AS legacy_first_seen
360 FROM findings WHERE topic_id IS NOT NULL
361 UNION ALL
362 SELECT finding_id, topic_id, seen_at, NULL
363 FROM finding_sightings WHERE topic_id IS NOT NULL
364 UNION ALL
365 SELECT f.id, r.topic_id, NULL, r.run_date FROM findings f
366 JOIN research_runs r ON r.id = f.run_id WHERE r.topic_id IS NOT NULL
367 )
368 GROUP BY finding_id, topic_id
369 """
370
371
372 def add_topic(
373 name: str,
374 search_queries: Optional[List[str]] = None,
375 schedule: str = "0 8 * * *",
376 *,
377 update_existing: bool = True,
378 ) -> Dict[str, Any]:
379 """Add a topic, optionally preserving an existing topic's configuration."""
380 init_db()
381 conn = _connect()
382 try:
383 queries_json = json.dumps(search_queries) if search_queries else None
384 conn.execute(
385 """INSERT INTO topics (name, search_queries, schedule)
386 VALUES (?, ?, ?)
387 ON CONFLICT(name) DO UPDATE SET
388 search_queries = excluded.search_queries,
389 schedule = excluded.schedule,
390 updated_at = datetime('now')
391 WHERE ?""",
392 (name, queries_json, schedule, update_existing),
393 )
394 conn.commit()
395 row = conn.execute(
396 "SELECT * FROM topics WHERE name = ?", (name,)
397 ).fetchone()
398 return dict(row)
399 finally:
400 conn.close()
401
402
403 def remove_topic(name: str) -> bool:
404 """Remove a topic from the watchlist. Returns True if found."""
405 init_db()
406 conn = _connect()
407 try:
408 conn.execute("BEGIN IMMEDIATE")
409 row = conn.execute(
410 "SELECT id FROM topics WHERE name = ?", (name,)
411 ).fetchone()
412 if not row:
413 return False
414 topic_id = row["id"]
415 findings = conn.execute(
416 f"""WITH memberships AS ({_FINDING_TOPICS_SQL})
417 SELECT f.id, f.topic_id, f.run_id, r.topic_id AS run_topic_id,
418 (SELECT MIN(m.topic_id) FROM memberships m
419 WHERE m.finding_id = f.id AND m.topic_id != ?) AS survivor
420 FROM findings f
421 LEFT JOIN research_runs r ON r.id = f.run_id
422 WHERE f.id IN (SELECT finding_id FROM memberships WHERE topic_id = ?)""",
423 (topic_id, topic_id),
424 ).fetchall()
425 for finding in findings:
426 if finding["survivor"] is None:
427 conn.execute("DELETE FROM findings WHERE id = ?", (finding["id"],))
428 continue
429 owner_id = finding["topic_id"]
430 if owner_id == topic_id:
431 owner_id = finding["survivor"]
432 run_id = finding["run_id"]
433 if finding["run_topic_id"] == topic_id:
434 surviving_run = conn.execute(
435 """SELECT s.run_id FROM finding_sightings s
436 JOIN research_runs r ON r.id = s.run_id
437 WHERE s.finding_id = ? AND s.topic_id != ? AND r.topic_id != ?
438 ORDER BY s.seen_at DESC, s.id DESC LIMIT 1""",
439 (finding["id"], topic_id, topic_id),
440 ).fetchone()
441 run_id = surviving_run["run_id"] if surviving_run else None
442 conn.execute(
443 "UPDATE findings SET topic_id = ?, run_id = ? WHERE id = ?",
444 (owner_id, run_id, finding["id"]),
445 )
446 conn.execute(
447 """INSERT INTO removed_run_usage (run_id, run_day, token_cost, cost_unknown)
448 SELECT id, date(run_date), token_cost, cost_unknown
449 FROM research_runs WHERE topic_id = ?""",
450 (topic_id,),
451 )
452 conn.execute("DELETE FROM research_runs WHERE topic_id = ?", (topic_id,))
453 conn.execute("DELETE FROM topics WHERE id = ?", (topic_id,))
454 conn.commit()
455 return True
456 finally:
457 conn.close()
458
459
460 def list_topics() -> List[Dict[str, Any]]:
461 """List all topics with stats."""
462 init_db()
463 conn = _connect()
464 try:
465 rows = conn.execute(
466 f"""WITH memberships AS ({_FINDING_TOPICS_SQL})
467 SELECT t.*,
468 (SELECT COUNT(*) FROM memberships WHERE topic_id = t.id) as finding_count,
469 (SELECT MAX(run_date) FROM research_runs WHERE topic_id = t.id) as last_run,
470 (SELECT status FROM research_runs WHERE topic_id = t.id
471 ORDER BY created_at DESC, id DESC LIMIT 1) as last_status
472 FROM topics t
473 ORDER BY t.name"""
474 ).fetchall()
475 return [dict(r) for r in rows]
476 finally:
477 conn.close()
478
479
480 def get_topic(name: str) -> Optional[Dict[str, Any]]:
481 """Get a topic by name."""
482 init_db()
483 conn = _connect()
484 try:
485 row = conn.execute(
486 "SELECT * FROM topics WHERE name = ?", (name,)
487 ).fetchone()
488 return dict(row) if row else None
489 finally:
490 conn.close()
491
492
493 # --- Research Runs ---
494
495
496 def record_run(
497 topic_id: int,
498 source_mode: str = "both",
499 status: str = "completed",
500 error_message: Optional[str] = None,
501 duration_seconds: float = 0,
502 prompt_tokens: int = 0,
503 completion_tokens: int = 0,
504 token_cost: Optional[float] = None,
505 ) -> int:
506 """Record a research run. Returns the run ID."""
507 conn = _connect()
508 try:
509 # A worker can flush its usage journal after topic deletion. Retain the
510 # identity across both tables so a late update cannot hit a newer run.
511 cursor = conn.execute(
512 """INSERT INTO research_runs
513 (id, topic_id, run_date, source_mode, status, error_message,
514 duration_seconds, prompt_tokens, completion_tokens, token_cost, cost_unknown)
515 VALUES (
516 max(coalesce((SELECT max(id) FROM research_runs), 0),
517 coalesce((SELECT max(run_id) FROM removed_run_usage), 0)) + 1,
518 ?, datetime('now'), ?, ?, ?, ?, ?, ?, ?, ?
519 )""",
520 (
521 topic_id, source_mode, status, error_message,
522 duration_seconds, prompt_tokens, completion_tokens, token_cost,
523 int(token_cost is None),
524 ),
525 )
526 conn.commit()
527 return cursor.lastrowid
528 finally:
529 conn.close()
530
531
532 def update_run(run_id: int, **kwargs):
533 """Update a research run's fields."""
534 conn = _connect()
535 try:
536 invalid_columns = sorted(set(kwargs) - _UPDATABLE_RUN_COLUMNS)
537 if invalid_columns:
538 raise ValueError(
539 f"Invalid run update fields: {', '.join(invalid_columns)}"
540 )
541 sets = ", ".join(f"{k} = ?" for k in kwargs)
542 values = list(kwargs.values()) + [run_id]
543 updated = conn.execute(f"UPDATE research_runs SET {sets} WHERE id = ?", values)
544 if updated.rowcount == 0:
545 usage = {key: value for key, value in kwargs.items() if key in _RUN_ACCOUNTING_COLUMNS}
546 if usage:
547 sets = ", ".join(f"{key} = ?" for key in usage)
548 conn.execute(
549 f"UPDATE removed_run_usage SET {sets} WHERE run_id = ?",
550 [*usage.values(), run_id],
551 )
552 conn.commit()
553 finally:
554 conn.close()
555
556
557 def get_latest_completed_runs(topic_id: int, limit: int = 2) -> List[Dict[str, Any]]:
558 """Return newest completed runs for a topic."""
559 conn = _connect()
560 try:
561 rows = conn.execute(
562 """SELECT * FROM research_runs
563 WHERE topic_id = ? AND status = 'completed'
564 ORDER BY datetime(run_date) DESC, id DESC
565 LIMIT ?""",
566 (topic_id, limit),
567 ).fetchall()
568 return [dict(r) for r in rows]
569 finally:
570 conn.close()
571
572
573 # --- Findings ---
574
575
576 _SUPPORTS_RETURNING = sqlite3.sqlite_version_info >= (3, 35, 0)
577
578
579 def _merge_finding_scores(target: Dict[str, Any], incoming: Dict[str, Any]) -> None:
580 """Keep the higher engagement and relevance scores when collapsing duplicate URLs."""
581 prev_eng = target.get("engagement_score") or 0
582 new_eng = incoming.get("engagement_score") or 0
583 if new_eng > prev_eng:
584 target["engagement_score"] = new_eng
585 prev_rel = target.get("relevance_score") or 0
586 new_rel = incoming.get("relevance_score") or 0
587 if new_rel > prev_rel:
588 target["relevance_score"] = new_rel
589
590
591 def store_findings(
592 run_id: int,
593 topic_id: int,
594 findings: List[Dict[str, Any]],
595 *,
596 count_by_topic: bool = False,
597 ) -> Dict[str, int]:
598 """Store deduplicated findings and count new/updated URLs.
599
600 Watchlist runs classify a URL by whether the topic has seen it before.
601 """
602 # Collect findings that have a URL, preserving first-seen order while
603 # collapsing same-batch duplicate URLs so one run never self-conflicts on
604 # source_url or double-increments sighting_count.
605 by_url: Dict[str, Dict[str, Any]] = {}
606 for f in findings:
607 url = f.get("source_url") or f.get("url")
608 if not url:
609 continue
610 existing_in_batch = by_url.get(url)
611 if existing_in_batch is None:
612 by_url[url] = dict(f)
613 else:
614 _merge_finding_scores(existing_in_batch, f)
615 with_urls: List[tuple[str, Dict[str, Any]]] = list(by_url.items())
616
617 if not with_urls:
618 conn = _connect()
619 try:
620 conn.execute(
621 "UPDATE research_runs SET findings_new = 0, findings_updated = 0 WHERE id = ?",
622 (run_id,),
623 )
624 conn.commit()
625 finally:
626 conn.close()
627 return {"new": 0, "updated": 0}
628
629 conn = _connect()
630 try:
631 conn.execute("BEGIN IMMEDIATE")
632 topic_updated_count = None
633 if count_by_topic:
634 # Check the same membership sources as _FINDING_TOPICS_SQL for
635 # this batch, before the upsert advances the latest run pointer.
636 urls = list(by_url)
637 placeholders = ",".join("?" for _ in urls)
638 topic_updated_count = conn.execute(
639 f"""SELECT COUNT(*) FROM findings f
640 LEFT JOIN research_runs r ON r.id = f.run_id
641 WHERE f.source_url IN ({placeholders})
642 AND (f.topic_id = ? OR r.topic_id = ? OR f.id IN (
643 SELECT finding_id FROM finding_sightings WHERE topic_id = ?
644 ))""",
645 (*urls, topic_id, topic_id, topic_id),
646 ).fetchone()[0]
647 # A legacy latest-run link can be the only record of a topic's
648 # observation. Save it as a historical sighting before the upsert.
649 conn.executemany(
650 """INSERT INTO finding_sightings
651 (finding_id, topic_id, source, source_url, source_title,
652 engagement_score, relevance_score, seen_at)
653 SELECT f.id, r.topic_id, f.source, f.source_url, f.source_title,
654 f.engagement_score, f.relevance_score, r.run_date
655 FROM findings f
656 JOIN research_runs r ON r.id = f.run_id
657 JOIN topics t ON t.id = r.topic_id
658 WHERE f.source_url = ? AND f.topic_id IS NOT r.topic_id
659 AND NOT EXISTS (
660 SELECT 1 FROM finding_sightings s
661 WHERE s.finding_id = f.id AND s.topic_id = r.topic_id
662 )""",
663 ((url,) for url in by_url),
664 )
665 upsert_sql = """INSERT INTO findings
666 (run_id, topic_id, source, source_url, source_title,
667 author, content, summary, engagement_score, relevance_score)
668 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
669 ON CONFLICT(source_url) DO UPDATE SET
670 last_seen = datetime('now'),
671 sighting_count = max(coalesce(sighting_count, 1), 1) + 1,
672 engagement_score = max(
673 coalesce(engagement_score, 0), excluded.engagement_score),
674 run_id = excluded.run_id"""
675 upsert_rows = [
676 (
677 run_id,
678 topic_id,
679 f.get("source", "unknown"),
680 url,
681 f.get("source_title") or f.get("title", ""),
682 f.get("author", ""),
683 f.get("content") or f.get("text", ""),
684 f.get("summary", ""),
685 f.get("engagement_score") or 0,
686 f.get("relevance_score", 0),
687 )
688 for url, f in with_urls
689 ]
690 if _SUPPORTS_RETURNING:
691 new_count = 0
692 updated_count = 0
693 rows_by_url: Dict[str, sqlite3.Row] = {}
694 returning_sql = f"{upsert_sql} RETURNING id, source_url, sighting_count"
695 for params in upsert_rows:
696 row = conn.execute(returning_sql, params).fetchone()
697 rows_by_url[params[3]] = row
698 if row["sighting_count"] == 1:
699 new_count += 1
700 else:
701 updated_count += 1
702 _record_sightings(conn, run_id, topic_id, with_urls, rows_by_url)
703 else:
704 # SQLite < 3.35 fallback: BEGIN IMMEDIATE prevents concurrent
705 # inserts or deletes between this lookup and the upsert.
706 urls = [url for url, _ in with_urls]
707 placeholders = ",".join("?" for _ in urls)
708 existing_urls = {
709 row["source_url"]
710 for row in conn.execute(
711 f"SELECT source_url FROM findings WHERE source_url IN ({placeholders})",
712 urls,
713 ).fetchall()
714 }
715 unique_new = len(set(urls) - existing_urls)
716 new_count = unique_new
717 updated_count = len(with_urls) - unique_new
718 conn.executemany(upsert_sql, upsert_rows)
719 _record_sightings(conn, run_id, topic_id, with_urls)
720 if topic_updated_count is not None:
721 updated_count = topic_updated_count
722 new_count = len(with_urls) - updated_count
723 conn.execute(
724 "UPDATE research_runs SET findings_new = ?, findings_updated = ? WHERE id = ?",
725 (new_count, updated_count, run_id),
726 )
727 conn.commit()
728 except sqlite3.IntegrityError as exc:
729 if conn.in_transaction:
730 conn.rollback()
731 if exc.sqlite_errorcode != sqlite3.SQLITE_CONSTRAINT_FOREIGNKEY:
732 raise
733 if conn.execute("SELECT 1 FROM removed_run_usage WHERE run_id = ?", (run_id,)).fetchone():
734 return {"new": 0, "updated": 0}
735 raise
736 except BaseException:
737 if conn.in_transaction:
738 conn.rollback()
739 raise
740 finally:
741 conn.close()
742
743 return {"new": new_count, "updated": updated_count}
744
745
746 def _record_sightings(
747 conn: sqlite3.Connection,
748 run_id: int,
749 topic_id: int,
750 findings_with_urls: List[tuple[str, Dict[str, Any]]],
751 existing_by_url: Optional[Dict[str, sqlite3.Row]] = None,
752 ) -> None:
753 """Record the findings observed during this run.
754
755 The aggregate findings table keeps one row per URL and updates that row on
756 re-sighting. This ledger preserves the run/topic membership needed for
757 watchlist deltas and dossiers.
758 """
759 if not findings_with_urls:
760 return
761
762 by_url = {url: finding for url, finding in findings_with_urls}
763 rows_by_url = dict(existing_by_url or {})
764
765 missing_urls = [url for url in by_url if url not in rows_by_url]
766 if missing_urls:
767 placeholders = ",".join("?" for _ in missing_urls)
768 rows = conn.execute(
769 f"SELECT id, source_url FROM findings WHERE source_url IN ({placeholders})",
770 missing_urls,
771 ).fetchall()
772 rows_by_url.update({row["source_url"]: row for row in rows})
773
774 sighting_rows = []
775 for url, finding in by_url.items():
776 row = rows_by_url.get(url)
777 if row is None:
778 continue
779 sighting_rows.append((
780 row["id"],
781 run_id,
782 topic_id,
783 finding.get("source", "unknown"),
784 url,
785 finding.get("source_title") or finding.get("title", ""),
786 finding.get("engagement_score") if finding.get("engagement_score") is not None else 0,
787 finding.get("relevance_score") if finding.get("relevance_score") is not None else 0,
788 ))
789
790 if not sighting_rows:
791 return
792
793 conn.executemany(
794 """INSERT INTO finding_sightings
795 (finding_id, run_id, topic_id, source, source_url, source_title,
796 engagement_score, relevance_score)
797 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
798 ON CONFLICT(run_id, finding_id) DO UPDATE SET
799 topic_id = excluded.topic_id,
800 source = excluded.source,
801 source_url = excluded.source_url,
802 source_title = excluded.source_title,
803 engagement_score = excluded.engagement_score,
804 relevance_score = excluded.relevance_score""",
805 sighting_rows,
806 )
807
808
809 def get_sightings_for_run(topic_id: int, run_id: int) -> List[Dict[str, Any]]:
810 """Return findings observed for a topic during a specific run."""
811 conn = _connect()
812 try:
813 rows = conn.execute(
814 """SELECT * FROM finding_sightings
815 WHERE topic_id = ? AND run_id = ?
816 ORDER BY id""",
817 (topic_id, run_id),
818 ).fetchall()
819 return [dict(r) for r in rows]
820 finally:
821 conn.close()
822
823
824 def compute_topic_delta(topic_id: int) -> Dict[str, Any]:
825 """Compare the latest completed watchlist run with the previous run."""
826 runs = get_latest_completed_runs(topic_id, limit=2)
827 topic = _get_topic_by_id(topic_id)
828 topic_name = topic["name"] if topic else str(topic_id)
829 if len(runs) < 2:
830 return {
831 "topic": topic_name,
832 "status": "insufficient_history",
833 "message": "Need at least two completed runs to compute a delta.",
834 }
835
836 current_run, previous_run = runs[0], runs[1]
837 current = _sightings_by_url(get_sightings_for_run(topic_id, current_run["id"]))
838 previous = _sightings_by_url(get_sightings_for_run(topic_id, previous_run["id"]))
839
840 current_urls = set(current)
841 previous_urls = set(previous)
842 new_urls = sorted(current_urls - previous_urls)
843 continued_urls = sorted(current_urls & previous_urls)
844 dropped_urls = sorted(previous_urls - current_urls)
845
846 findings = {
847 "new": [current[url] for url in new_urls],
848 "continued": [current[url] for url in continued_urls],
849 "dropped": [previous[url] for url in dropped_urls],
850 }
851
852 return {
853 "topic": topic_name,
854 "status": "ok",
855 "current_run_id": current_run["id"],
856 "previous_run_id": previous_run["id"],
857 "new": len(new_urls),
858 "continued": len(continued_urls),
859 "dropped": len(dropped_urls),
860 "sources": _delta_source_counts(findings),
861 "findings": findings,
862 }
863
864
865 def _get_topic_by_id(topic_id: int) -> Optional[Dict[str, Any]]:
866 conn = _connect()
867 try:
868 row = conn.execute("SELECT * FROM topics WHERE id = ?", (topic_id,)).fetchone()
869 return dict(row) if row else None
870 finally:
871 conn.close()
872
873
874 def _sightings_by_url(sightings: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
875 """Index sightings by stable URL identity for run-to-run delta comparisons.
876
877 URL-less sightings are intentionally excluded because there is no stable
878 cross-run identity to classify them as new, continued, or dropped.
879 """
880 return {
881 sighting["source_url"]: sighting
882 for sighting in sightings
883 if sighting.get("source_url")
884 }
885
886
887 def _delta_source_counts(
888 findings: Dict[str, List[Dict[str, Any]]]
889 ) -> Dict[str, Dict[str, int]]:
890 sources = sorted({
891 finding.get("source") or "unknown"
892 for group in findings.values()
893 for finding in group
894 })
895 counts = {
896 source: {"new": 0, "continued": 0, "dropped": 0}
897 for source in sources
898 }
899 for group_name, group in findings.items():
900 for finding in group:
901 source = finding.get("source") or "unknown"
902 counts[source][group_name] += 1
903 return counts
904
905
906 def get_new_findings(
907 topic_id: int,
908 since: Optional[str] = None,
909 before: Optional[str] = None,
910 ) -> List[Dict[str, Any]]:
911 """Get findings by their first observation for this topic within the date bounds."""
912 conn = _connect()
913 try:
914 date_filter = ""
915 parameters: List[Any] = [topic_id]
916 if since:
917 date_filter += " AND m.first_seen >= ?"
918 parameters.append(since)
919 if before:
920 date_filter += " AND m.first_seen < ?"
921 parameters.append(before)
922 rows = conn.execute(
923 f"""WITH memberships AS ({_FINDING_TOPICS_SQL})
924 SELECT f.*, m.first_seen AS topic_first_seen FROM findings f
925 JOIN memberships m ON m.finding_id = f.id
926 WHERE m.topic_id = ? AND f.dismissed = 0{date_filter}
927 ORDER BY m.first_seen DESC""",
928 parameters,
929 ).fetchall()
930 findings = [dict(r) for r in rows]
931 for finding in findings:
932 finding["first_seen"] = finding.pop("topic_first_seen")
933 return findings
934 finally:
935 conn.close()
936
937
938 _FTS_TOKEN = re.compile(r"[^\W_]+", re.UNICODE)
939
940
941 def _fts_query_expression(query: str) -> str:
942 """Build a literal FTS5 AND-query expression from arbitrary user text."""
943 if not isinstance(query, str):
944 return ""
945 tokens = _FTS_TOKEN.findall(query)
946 return " AND ".join(f'"{token.replace(chr(34), chr(34) * 2)}"' for token in tokens)
947
948
949 def search_findings(query: str, limit: int = 20) -> List[Dict[str, Any]]:
950 """FTS5 search across all findings with BM25 ranking."""
951 expression = _fts_query_expression(query)
952 if not expression or limit <= 0:
953 return []
954 conn = _connect()
955 try:
956 rows = conn.execute(
957 """SELECT f.*, bm25(findings_fts) as rank, t.name as topic_name
958 FROM findings_fts
959 JOIN findings f ON f.id = findings_fts.rowid
960 LEFT JOIN topics t ON t.id = f.topic_id
961 WHERE findings_fts MATCH ? AND f.dismissed = 0
962 ORDER BY rank
963 LIMIT ?""",
964 (expression, limit),
965 ).fetchall()
966 return [dict(r) for r in rows]
967 except sqlite3.OperationalError:
968 return []
969 finally:
970 conn.close()
971
972
973 def update_finding(finding_id: int, **kwargs):
974 """Update a finding's fields."""
975 conn = _connect()
976 try:
977 invalid_columns = sorted(set(kwargs) - _UPDATABLE_FINDING_COLUMNS)
978 if invalid_columns:
979 raise ValueError(
980 f"Invalid finding update fields: {', '.join(invalid_columns)}"
981 )
982 sets = ", ".join(f"{k} = ?" for k in kwargs)
983 values = list(kwargs.values()) + [finding_id]
984 conn.execute(f"UPDATE findings SET {sets} WHERE id = ?", values)
985 conn.commit()
986 finally:
987 conn.close()
988
989
990 def delete_finding(finding_id: int):
991 """Delete a finding."""
992 conn = _connect()
993 try:
994 conn.execute("DELETE FROM findings WHERE id = ?", (finding_id,))
995 conn.commit()
996 finally:
997 conn.close()
998
999
1000 def dismiss_finding(finding_id: int):
1001 """Mark a finding as dismissed."""
1002 update_finding(finding_id, dismissed=1)
1003
1004
1005 # --- Discovery topic queue ---
1006
1007 # Conservative floor for fuzzy queue matching (overlap coefficient of entity
1008 # tokens via entity_extract.entity_overlap). Tunable: raise toward 1.0 for
1009 # stricter matching, lower for looser. Matching is annotate-only - a fuzzy
1010 # match stamps prior-surfacing context onto an incoming topic but NEVER merges
1011 # queue rows, so a too-loose threshold can mislabel a card yet never lose data.
1012 DISCOVERY_QUEUE_OVERLAP_THRESHOLD = 0.6
1013
1014
1015 def _normalize_discovery_name(name: str) -> str:
1016 """Queue identity: lowercased, punctuation-stripped, whitespace-collapsed
1017 (thin alias for dedupe.normalize_text)."""
1018 return dedupe.normalize_text(name)
1019
1020
1021 def _discovery_entity_key(name: str) -> str:
1022 """Sorted joined significant tokens, computed once at write time."""
1023 return " ".join(sorted(entity_extract.extract_text_entities(name)))
1024
1025
1026 def _discovery_anchor_entities(name: str) -> set[str]:
1027 """Anchor tokens for fuzzy matching: capitalized, all-caps, or
1028 digit-bearing words minus stopwords (product/person/version anchors).
1029
1030 Generic lowercase words ("chat", "templates") are excluded so two angles
1031 on the same subject ("Gemma 4 chat templates" / "Gemma 4 tool calling
1032 fixes") cross-match while different subjects sharing filler words don't.
1033 """
1034 anchors = set()
1035 for word in re.sub(r"[^\w\s]", " ", name).split():
1036 lower = word.casefold()
1037 if lower in entity_extract.ENTITY_STOPWORDS:
1038 continue
1039 if entity_extract.has_anchor_signal(word):
1040 anchors.add(lower)
1041 return anchors
1042
1043
1044 def record_discovery_surfacing(
1045 name: str,
1046 domain: str = "",
1047 run_ref: str = "",
1048 as_of: str = "",
1049 inherit_covered_at: Optional[str] = None,
1050 ) -> Dict[str, Any]:
1051 """Upsert a queue row by normalized name.
1052
1053 A fresh topic inserts with surface_count 1; re-surfacing the same
1054 normalized name increments the count and refreshes last_surfaced and
1055 last_run_ref (first_surfaced never changes). Returns the resulting row.
1056
1057 A resurfacing with a blank domain (e.g. a global-trending sweep with no
1058 domain) never blanks a domain recorded by an earlier, domain-scoped
1059 surfacing - the stored domain only changes when the incoming domain is
1060 non-empty. ``domain`` is normalized to "" here (never NULL bound) so the
1061 column's storage convention stays consistent regardless of whether a
1062 caller passes "" or None.
1063
1064 ``inherit_covered_at`` makes a FRESH row be born covered (status
1065 'covered', covered_at set to the given date). Callers pass it when this
1066 name fuzzy-matched an already-covered prior row, so a user's covered
1067 mark survives judge naming drift instead of forking into a fresh
1068 uncovered row. An existing row's status/covered_at are never modified
1069 by this function - the ON CONFLICT path deliberately ignores it.
1070
1071 Idempotency guard: when the existing row's last_run_ref already equals
1072 this call's (non-blank) run_ref, the surfacing was ALREADY counted by
1073 this run identity - a retry (e.g. a --finalize re-run with a corrected
1074 angles file) returns the row unchanged instead of double-counting.
1075 Blank run_refs never guard, so callers without a run identity keep the
1076 every-call-increments behavior.
1077 """
1078 init_db()
1079 domain = domain or ""
1080 normalized = _normalize_discovery_name(name)
1081 entity_key = _discovery_entity_key(name)
1082 status = "covered" if inherit_covered_at else "surfaced"
1083 conn = _connect()
1084 try:
1085 conn.execute(
1086 """INSERT INTO discovery_topics
1087 (name, normalized_name, entity_key, domain, first_surfaced,
1088 last_surfaced, surface_count, last_run_ref, status, covered_at)
1089 VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?)
1090 ON CONFLICT(normalized_name) DO UPDATE SET
1091 surface_count = surface_count + 1,
1092 last_surfaced = excluded.last_surfaced,
1093 last_run_ref = excluded.last_run_ref,
1094 domain = CASE WHEN excluded.domain <> '' THEN excluded.domain ELSE domain END
1095 WHERE excluded.last_run_ref IS NULL
1096 OR excluded.last_run_ref = ''
1097 OR discovery_topics.last_run_ref IS NULL
1098 OR discovery_topics.last_run_ref <> excluded.last_run_ref""",
1099 (name, normalized, entity_key, domain, as_of, as_of, run_ref, status, inherit_covered_at),
1100 )
1101 conn.commit()
1102 row = conn.execute(
1103 "SELECT * FROM discovery_topics WHERE normalized_name = ?",
1104 (normalized,),
1105 ).fetchone()
1106 return dict(row)
1107 finally:
1108 conn.close()
1109
1110
1111 def match_discovery_topic(name: str) -> Optional[Dict[str, Any]]:
1112 """Find the queue row a topic name refers to, or None.
1113
1114 Exact normalized-name match wins; otherwise the best entity-overlap match
1115 at or above DISCOVERY_QUEUE_OVERLAP_THRESHOLD. Overlap is the better of
1116 the full entity_key token overlap and the anchor-token overlap (see
1117 _discovery_anchor_entities) - full-token overlap alone dilutes the subject
1118 anchor with generic words, so same-subject near-duplicates would never
1119 clear a conservative floor. Matching NEVER merges rows: a fuzzy match only
1120 annotates the incoming topic with the prior row's context.
1121 """
1122 init_db()
1123 normalized = _normalize_discovery_name(name)
1124 conn = _connect()
1125 try:
1126 row = conn.execute(
1127 "SELECT * FROM discovery_topics WHERE normalized_name = ?",
1128 (normalized,),
1129 ).fetchone()
1130 if row:
1131 return dict(row)
1132
1133 entities = entity_extract.extract_text_entities(name)
1134 anchors = _discovery_anchor_entities(name)
1135 if not entities and not anchors:
1136 return None
1137 best: Optional[sqlite3.Row] = None
1138 best_overlap = 0.0
1139 for candidate in conn.execute("SELECT * FROM discovery_topics").fetchall():
1140 candidate_entities = set((candidate["entity_key"] or "").split())
1141 overlap = max(
1142 entity_extract.entity_overlap(entities, candidate_entities),
1143 entity_extract.entity_overlap(
1144 anchors, _discovery_anchor_entities(candidate["name"])
1145 ),
1146 )
1147 if overlap > best_overlap:
1148 best, best_overlap = candidate, overlap
1149 if best is not None and best_overlap >= DISCOVERY_QUEUE_OVERLAP_THRESHOLD:
1150 return dict(best)
1151 return None
1152 finally:
1153 conn.close()
1154
1155
1156 def list_discovery_queue(status: Optional[str] = None) -> List[Dict[str, Any]]:
1157 """List queue rows, newest surfacing first, optionally filtered by status."""
1158 init_db()
1159 conn = _connect()
1160 try:
1161 if status:
1162 rows = conn.execute(
1163 """SELECT * FROM discovery_topics WHERE status = ?
1164 ORDER BY last_surfaced DESC, id DESC""",
1165 (status,),
1166 ).fetchall()
1167 else:
1168 rows = conn.execute(
1169 "SELECT * FROM discovery_topics ORDER BY last_surfaced DESC, id DESC"
1170 ).fetchall()
1171 return [dict(r) for r in rows]
1172 finally:
1173 conn.close()
1174
1175
1176 def mark_discovery_covered(name: str, as_of: str) -> Optional[Dict[str, Any]]:
1177 """Mark a queued topic covered by EXACT normalized name.
1178
1179 Returns the updated row, or None when no row matches - callers must error
1180 loudly on None, never silently no-op. Fuzzy matching is deliberately not
1181 offered here: covering mutates state, so it demands the exact name.
1182 """
1183 init_db()
1184 normalized = _normalize_discovery_name(name)
1185 conn = _connect()
1186 try:
1187 cursor = conn.execute(
1188 """UPDATE discovery_topics
1189 SET status = 'covered', covered_at = ?
1190 WHERE normalized_name = ?""",
1191 (as_of, normalized),
1192 )
1193 conn.commit()
1194 if cursor.rowcount == 0:
1195 return None
1196 row = conn.execute(
1197 "SELECT * FROM discovery_topics WHERE normalized_name = ?",
1198 (normalized,),
1199 ).fetchone()
1200 return dict(row)
1201 finally:
1202 conn.close()
1203
1204
1205 # --- Cost Tracking ---
1206
1207
1208 def get_daily_usage(date: Optional[str] = None) -> tuple[float, int]:
1209 """Get the known cost and count of unknown-cost runs for one UTC day."""
1210 conn = _connect()
1211 try:
1212 date = date or datetime.now(timezone.utc).strftime("%Y-%m-%d")
1213 row = conn.execute(
1214 """SELECT coalesce(sum(token_cost), 0), coalesce(sum(cost_unknown = 1), 0)
1215 FROM (
1216 SELECT token_cost, cost_unknown FROM research_runs WHERE date(run_date) = date(?1)
1217 UNION ALL
1218 SELECT token_cost, cost_unknown FROM removed_run_usage WHERE run_day = date(?1)
1219 )""",
1220 (date,),
1221 ).fetchone()
1222 return row[0], row[1]
1223 finally:
1224 conn.close()
1225
1226
1227 def get_daily_cost(date: Optional[str] = None) -> float:
1228 """Get total token cost for a given day (default: today)."""
1229 return get_daily_usage(date)[0]
1230
1231
1232 def get_daily_unknown_cost_runs(date: Optional[str] = None) -> int:
1233 return get_daily_usage(date)[1]
1234
1235
1236 # --- Settings ---
1237
1238
1239 def get_setting(key: str, default: Optional[str] = None) -> Optional[str]:
1240 """Get a setting value."""
1241 init_db()
1242 conn = _connect()
1243 try:
1244 row = conn.execute(
1245 "SELECT value FROM settings WHERE key = ?", (key,)
1246 ).fetchone()
1247 return row["value"] if row else default
1248 finally:
1249 conn.close()
1250
1251
1252 def set_setting(key: str, value: str):
1253 """Set a setting value."""
1254 init_db()
1255 conn = _connect()
1256 try:
1257 conn.execute(
1258 """INSERT INTO settings (key, value, updated_at)
1259 VALUES (?, ?, datetime('now'))
1260 ON CONFLICT(key) DO UPDATE SET
1261 value = excluded.value,
1262 updated_at = datetime('now')""",
1263 (key, value),
1264 )
1265 conn.commit()
1266 finally:
1267 conn.close()
1268
1269
1270 def parse_budget(raw: object) -> float:
1271 """Parse and validate a finite non-negative daily budget value."""
1272 if isinstance(raw, bool) or raw is None:
1273 raise ValueError(f"Invalid daily_budget value: {raw!r}")
1274 if isinstance(raw, str):
1275 text = raw.strip()
1276 if not text:
1277 raise ValueError("Invalid daily_budget value: empty")
1278 try:
1279 dec = Decimal(text)
1280 except InvalidOperation as exc:
1281 raise ValueError(f"Invalid daily_budget value: {raw!r}") from exc
1282 if not dec.is_finite() or dec < 0:
1283 raise ValueError(
1284 f"Invalid daily_budget value: {raw!r} (must be a finite number >= 0)"
1285 )
1286 try:
1287 value = float(dec)
1288 except OverflowError as exc:
1289 raise ValueError(f"Invalid daily_budget value: {raw!r} (overflow)") from exc
1290 elif isinstance(raw, (int, float)):
1291 if raw < 0:
1292 raise ValueError(
1293 f"Invalid daily_budget value: {raw!r} (must be a finite number >= 0)"
1294 )
1295 try:
1296 value = float(raw)
1297 except OverflowError as exc:
1298 raise ValueError(f"Invalid daily_budget value: {raw!r} (overflow)") from exc
1299 else:
1300 raise ValueError(f"Invalid daily_budget value: {raw!r}")
1301 if not math.isfinite(value) or value < 0:
1302 raise ValueError(
1303 f"Invalid daily_budget value: {raw!r} (must be a finite number >= 0)"
1304 )
1305 return 0.0 if value == 0 else value
1306
1307
1308 # --- Stats ---
1309
1310
1311 def get_stats() -> Dict[str, Any]:
1312 """Get overall database stats."""
1313 conn = _connect()
1314 try:
1315 topic_count = conn.execute("SELECT COUNT(*) FROM topics WHERE enabled = 1").fetchone()[0]
1316 finding_count = conn.execute("SELECT COUNT(*) FROM findings").fetchone()[0]
1317
1318 week_ago = (datetime.now(timezone.utc) - timedelta(days=7)).strftime("%Y-%m-%d")
1319 runs_7d = conn.execute(
1320 "SELECT COUNT(*) FROM research_runs WHERE run_date >= ?", (week_ago,)
1321 ).fetchone()[0]
1322 successful_7d = conn.execute(
1323 "SELECT COUNT(*) FROM research_runs WHERE run_date >= ? AND status = 'completed'",
1324 (week_ago,),
1325 ).fetchone()[0]
1326 failed_7d = conn.execute(
1327 "SELECT COUNT(*) FROM research_runs WHERE run_date >= ? AND status = 'failed'",
1328 (week_ago,),
1329 ).fetchone()[0]
1330 cost_7d = conn.execute(
1331 """SELECT COALESCE(SUM(token_cost), 0)
1332 FROM (
1333 SELECT token_cost FROM research_runs WHERE run_date >= ?1
1334 UNION ALL
1335 SELECT token_cost FROM removed_run_usage WHERE run_day >= ?1
1336 )""",
1337 (week_ago,),
1338 ).fetchone()[0]
1339
1340 # Source breakdown
1341 sources = {}
1342 for row in conn.execute(
1343 "SELECT source, COUNT(*) as cnt FROM findings GROUP BY source"
1344 ).fetchall():
1345 sources[row["source"]] = row["cnt"]
1346
1347 db_path = _get_db_path()
1348 db_size = db_path.stat().st_size if db_path.exists() else 0
1349
1350 return {
1351 "topics_active": topic_count,
1352 "total_findings": finding_count,
1353 "db_size_bytes": db_size,
1354 "runs_7d": runs_7d,
1355 "successful_7d": successful_7d,
1356 "failed_7d": failed_7d,
1357 "cost_7d": cost_7d,
1358 "sources": sources,
1359 "daily_budget": get_setting("daily_budget", "5.00"),
1360 }
1361 finally:
1362 conn.close()
1363
1364
1365 def get_trending(days: int = 7) -> List[Dict[str, Any]]:
1366 """Get topics ranked by recent finding activity."""
1367 conn = _connect()
1368 try:
1369 since = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d")
1370 rows = conn.execute(
1371 f"""WITH memberships AS ({_FINDING_TOPICS_SQL})
1372 SELECT t.name, t.id,
1373 COUNT(f.id) as new_findings,
1374 COALESCE(SUM(f.engagement_score), 0) as total_engagement
1375 FROM topics t
1376 LEFT JOIN memberships m ON m.topic_id = t.id
1377 LEFT JOIN findings f ON f.id = m.finding_id AND m.first_seen >= ?
1378 WHERE t.enabled = 1
1379 GROUP BY t.id
1380 ORDER BY new_findings DESC""",
1381 (since,),
1382 ).fetchall()
1383 return [dict(r) for r in rows]
1384 finally:
1385 conn.close()
1386
1387
1388 def finding_from_candidate(candidate: schema.Candidate) -> Dict[str, Any]:
1389 """Convert a ranked candidate into a persisted finding."""
1390 primary_item = schema.candidate_primary_item(candidate)
1391 corroborating_sources = [
1392 source for source in schema.candidate_sources(candidate)
1393 if source and source != candidate.source
1394 ]
1395 summary = candidate.explanation or candidate.snippet or ""
1396 if corroborating_sources:
1397 prefix = f"Also seen in: {', '.join(corroborating_sources)}."
1398 summary = f"{prefix} {summary}".strip()
1399 body = (
1400 primary_item.body
1401 if primary_item and primary_item.body
1402 else candidate.snippet or candidate.title
1403 )
1404 author = primary_item.author if primary_item and primary_item.author else ""
1405 return {
1406 "source": candidate.source or "unknown",
1407 "source_url": candidate.url,
1408 "source_title": candidate.title,
1409 "author": author,
1410 "content": body,
1411 "summary": summary,
1412 "engagement_score": candidate.engagement or 0,
1413 "relevance_score": candidate.final_score or candidate.rerank_score or candidate.local_relevance,
1414 }
1415
1416
1417 def findings_from_report(
1418 report: schema.Report,
1419 *,
1420 limit: Optional[int] = None,
1421 ) -> List[Dict[str, Any]]:
1422 """Convert report into persisted findings.
1423
1424 Uses ranked candidates (post-rerank) when available for quality scores and explanations.
1425 Supplements with raw items from items_by_source for HN/PM that didn't rank highly
1426 but are valuable for watchlist persistence. When ranked_candidates is empty
1427 (degraded path — rerank failed or was skipped), falls back to supplementing
1428 all sources from items_by_source so findings aren't silently dropped.
1429 """
1430 findings: List[Dict[str, Any]] = []
1431 seen_by_url: Dict[str, Dict[str, Any]] = {}
1432
1433 for candidate in report.ranked_candidates:
1434 converted = finding_from_candidate(candidate)
1435 if candidate.url and candidate.url in seen_by_url:
1436 _merge_finding_scores(seen_by_url[candidate.url], converted)
1437 continue
1438 findings.append(converted)
1439 if candidate.url:
1440 seen_by_url[candidate.url] = converted
1441
1442 supplement_sources = (
1443 list(report.items_by_source)
1444 if not report.ranked_candidates
1445 else ["hackernews", "polymarket"]
1446 )
1447 for source_name in supplement_sources:
1448 if source_name not in report.items_by_source:
1449 continue
1450 for item in report.items_by_source[source_name]:
1451 converted = {
1452 "source": source_name,
1453 "source_url": item.url,
1454 "source_title": item.title,
1455 "author": item.author or "",
1456 "content": item.body or "",
1457 "summary": item.snippet or (item.body[:500] if item.body else ""),
1458 "engagement_score": item.engagement_score or 0.0,
1459 "relevance_score": item.local_relevance or 0.5,
1460 }
1461 if item.url and item.url in seen_by_url:
1462 _merge_finding_scores(seen_by_url[item.url], converted)
1463 continue
1464 findings.append(converted)
1465 if item.url:
1466 seen_by_url[item.url] = converted
1467
1468 return findings[:limit] if limit is not None else findings
1469
1470
1471 # --- CLI interface ---
1472
1473
1474 def _since_cutoff(value: str) -> str:
1475 if re.fullmatch(r"[0-9]+d", value) is None:
1476 raise argparse.ArgumentTypeError(
1477 "must be a non-negative integer duration like 7d"
1478 )
1479 try:
1480 days = int(value[:-1])
1481 # Use UTC to match SQLite's datetime('now') timestamps.
1482 return (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d")
1483 except (ValueError, OverflowError) as exc:
1484 raise argparse.ArgumentTypeError("duration is out of range") from exc
1485
1486
1487 def _cli_query(args):
1488 """Handle CLI query command."""
1489 topic = get_topic(args.topic)
1490 if not topic:
1491 print(json.dumps({"error": f"Topic not found: {args.topic}"}))
1492 return
1493
1494 findings = get_new_findings(topic["id"], args.since)
1495 print(json.dumps({"topic": topic["name"], "findings": findings, "count": len(findings)}, default=str))
1496
1497
1498 def _cli_search(args):
1499 """Handle CLI search command."""
1500 results = search_findings(args.query, limit=args.limit)
1501 print(json.dumps({"query": args.query, "results": results, "count": len(results)}, default=str))
1502
1503
1504 def _cli_trending(args):
1505 """Handle CLI trending command."""
1506 results = get_trending(args.days)
1507 print(json.dumps({"trending": results}, default=str))
1508
1509
1510 def _cli_stats(args):
1511 """Handle CLI stats command."""
1512 stats = get_stats()
1513 print(json.dumps(stats, default=str))
1514
1515
1516 def main():
1517 parser = argparse.ArgumentParser(description="Query the last30days research database")
1518 sub = parser.add_subparsers(dest="command")
1519
1520 # query
1521 q = sub.add_parser("query", help="Query findings for a topic")
1522 q.add_argument("topic", help="Topic name")
1523 q.add_argument(
1524 "--since",
1525 type=_since_cutoff,
1526 metavar="DURATION",
1527 help="Non-negative day duration like '7d' or '30d'",
1528 )
1529 q.set_defaults(func=_cli_query)
1530
1531 # search
1532 s = sub.add_parser("search", help="Full-text search across findings")
1533 s.add_argument("query", help="Search query")
1534 s.add_argument("--limit", type=int, default=20, help="Max results")
1535 s.set_defaults(func=_cli_search)
1536
1537 # trending
1538 t = sub.add_parser("trending", help="Show trending topics")
1539 t.add_argument("--days", type=int, default=7, help="Look back N days")
1540 t.set_defaults(func=_cli_trending)
1541
1542 # stats
1543 st = sub.add_parser("stats", help="Show database stats")
1544 st.set_defaults(func=_cli_stats)
1545
1546 args = parser.parse_args()
1547 if not args.command:
1548 parser.print_help()
1549 sys.exit(1)
1550
1551 # Ensure DB exists
1552 init_db()
1553 args.func(args)
1554
1555
1556 if __name__ == "__main__":
1557 main()
1558
1558 lines PYTHON