返回 last30days-skill
library_index.py
根目录 / skills / last30days / scripts / lib / library_index.py
1 """Offline FTS search across the saved research library and store sightings."""
2
3 from __future__ import annotations
4
5 import errno
6 import hashlib
7 import os
8 import re
9 import sqlite3
10 import stat
11 import unicodedata
12 from contextlib import contextmanager
13 from dataclasses import dataclass, replace
14 from datetime import date
15 from pathlib import Path
16
17 from . import library, private_files, rust_accel
18 from .private_files import prepare_private_sqlite_files
19
20 _IS_JUNCTION = getattr(os.path, "isjunction", None)
21
22
23 DEFAULT_LIBRARY_DB = library.DEFAULT_BRIEFS_DIR.parent / "library.db"
24 DEFAULT_STORE_DB = library.DEFAULT_BRIEFS_DIR.parent / "research.db"
25 INDEX_FINGERPRINT_VERSION = "last30days-library-index/v3"
26 LIBRARY_CONTEXT_START = "<!-- last30days:library-context:start -->"
27 LIBRARY_CONTEXT_END = "<!-- last30days:library-context:end -->"
28 # Keep combining diacritics attached to their word so SQLite's unicode61
29 # tokenizer sees the same spelling on the query and indexing paths.
30 _TOKEN = re.compile(r"[^\W_](?:[^\W_]|[\u0300-\u036f])*")
31 _MARKED_LIBRARY_CONTEXT = re.compile(
32 rf"^{re.escape(LIBRARY_CONTEXT_START)}\s*$.*?"
33 rf"^{re.escape(LIBRARY_CONTEXT_END)}\s*$\n?",
34 re.MULTILINE | re.DOTALL,
35 )
36 _LEGACY_LIBRARY_CONTEXT = re.compile(
37 r"^## From your library\s*$.*?(?=^##\s|\Z)",
38 re.MULTILINE | re.DOTALL,
39 )
40
41
42 def saved_report_index_path(save_dir: Path) -> Path:
43 if save_dir == Path(library.DEFAULT_MEMORY_DIR).expanduser().resolve():
44 return DEFAULT_LIBRARY_DB
45 return save_dir / ".last30days-library.db"
46
47
48 class LibrarySearchUnavailable(RuntimeError):
49 """Raised when this Python SQLite build cannot provide FTS5."""
50
51
52 @dataclass(frozen=True, slots=True)
53 class LibrarySearchMatch:
54 topic: str
55 published_date: date
56 headline: str
57 snippet: str
58 source_kind: str
59 rank: float
60 source_path: str = ""
61 url: str = ""
62 engagement: float | None = None
63
64 @property
65 def run_key(self) -> tuple[str, date]:
66 return self.topic, self.published_date
67
68
69 @dataclass(frozen=True, slots=True)
70 class SyncResult:
71 indexed: int = 0
72 removed: int = 0
73 unchanged: int = 0
74 notes: tuple[str, ...] = ()
75 rebuilt: bool = False
76
77
78 _SCHEMA = """
79 CREATE TABLE IF NOT EXISTS library_documents (
80 entry_id TEXT PRIMARY KEY,
81 source_path TEXT UNIQUE NOT NULL,
82 source_mtime_ns INTEGER NOT NULL,
83 source_size INTEGER NOT NULL,
84 content_hash TEXT NOT NULL,
85 topic TEXT NOT NULL,
86 published_date TEXT NOT NULL,
87 headline TEXT NOT NULL,
88 summary TEXT NOT NULL,
89 source_format TEXT NOT NULL
90 );
91 CREATE VIRTUAL TABLE IF NOT EXISTS library_fts USING fts5(
92 entry_id UNINDEXED,
93 topic,
94 headline,
95 summary,
96 content,
97 tokenize='porter unicode61'
98 );
99 """
100
101
102 @contextmanager
103 def _managed_connection(conn: sqlite3.Connection):
104 """Commit or roll back ``conn`` and always close it on exit."""
105 try:
106 with conn as active:
107 yield active
108 finally:
109 conn.close()
110
111
112 def fts5_available() -> bool:
113 try:
114 with _managed_connection(sqlite3.connect(":memory:")) as conn:
115 conn.execute("CREATE VIRTUAL TABLE probe USING fts5(value)")
116 except sqlite3.DatabaseError:
117 return False
118 return True
119
120
121 def sync_library(
122 memory_dir: Path | str = library.DEFAULT_MEMORY_DIR,
123 briefs_dir: Path | str = library.DEFAULT_BRIEFS_DIR,
124 *,
125 db_path: Path | str = DEFAULT_LIBRARY_DB,
126 ) -> SyncResult:
127 """Incrementally index the shared ``scan_library`` view of saved research."""
128 if not fts5_available():
129 raise LibrarySearchUnavailable(
130 "library search requires a Python SQLite build with FTS5 support"
131 )
132 target = Path(db_path).expanduser()
133 try:
134 return _sync_library(memory_dir, briefs_dir, target)
135 except sqlite3.DatabaseError as exc:
136 if "fts5" in str(exc).lower() and "malformed" not in str(exc).lower():
137 raise LibrarySearchUnavailable(
138 "library search requires a Python SQLite build with FTS5 support"
139 ) from exc
140 if not _is_confirmed_corruption(exc):
141 raise
142 _remove_database(target)
143 return replace(_sync_library(memory_dir, briefs_dir, target), rebuilt=True)
144
145
146 def _resolve_regular_source_path(path: Path | str) -> Path | None:
147 """Strictly resolve an existing regular non-symlink source file path."""
148 raw_source = Path(path).expanduser()
149 if _IS_JUNCTION is not None and _IS_JUNCTION(raw_source):
150 return None
151 try:
152 lstat_res = raw_source.lstat()
153 except OSError:
154 return None
155 if stat.S_ISLNK(lstat_res.st_mode) or not stat.S_ISREG(lstat_res.st_mode):
156 return None
157 try:
158 canonical_parent = raw_source.parent.resolve(strict=True)
159 except (OSError, RuntimeError):
160 return None
161 canonical_source = canonical_parent / raw_source.name
162 if _IS_JUNCTION is not None and _IS_JUNCTION(canonical_source):
163 return None
164 try:
165 canonical_stat = canonical_source.lstat()
166 except OSError:
167 return None
168 if stat.S_ISLNK(canonical_stat.st_mode) or not stat.S_ISREG(canonical_stat.st_mode):
169 return None
170 if (os.name == "posix" or (lstat_res.st_ino and canonical_stat.st_ino)) and (
171 canonical_stat.st_dev,
172 canonical_stat.st_ino,
173 ) != (lstat_res.st_dev, lstat_res.st_ino):
174 return None
175 return canonical_source
176
177
178 def index_entry(
179 path: Path | str,
180 *,
181 db_path: Path | str = DEFAULT_LIBRARY_DB,
182 source_format: str = "markdown",
183 ) -> bool:
184 """Index one saved Markdown artifact in O(1) without scanning its directory."""
185 if not fts5_available():
186 raise LibrarySearchUnavailable(
187 "library search requires a Python SQLite build with FTS5 support"
188 )
189 canonical_source = _resolve_regular_source_path(path)
190 if canonical_source is None:
191 return False
192 try:
193 entry = library.parse_markdown_file(canonical_source, source_format=source_format)
194 except (OSError, UnicodeError, ValueError):
195 return False
196 if library.is_unbounded_private_brief(entry.content, source_format=entry.source_format):
197 return False
198 target = Path(db_path).expanduser()
199 _ensure_private_directory(target.parent)
200 with _managed_connection(_connect(target)) as conn:
201 _upsert_entry(conn, entry)
202 conn.commit()
203 return True
204
205
206 def index_brief(
207 path: Path | str,
208 *,
209 db_path: Path | str = DEFAULT_LIBRARY_DB,
210 ) -> bool:
211 """Index one saved artifact, parsing it through ``scan_library``."""
212 source = _resolve_regular_source_path(path)
213 if source is None:
214 return False
215 if source.suffix.lower() == ".json":
216 entries, _ = library.scan_library(source.parent / ".missing", source.parent)
217 else:
218 entries, _ = library.scan_library(source.parent, source.parent / ".missing")
219 entry = next((item for item in entries if item.source_path == source), None)
220 if entry is None:
221 return False
222 target = Path(db_path).expanduser()
223 _ensure_private_directory(target.parent)
224 with _managed_connection(_connect(target)) as conn:
225 _upsert_entry(conn, entry)
226 conn.commit()
227 return True
228
229
230 def search(
231 query: str,
232 *,
233 limit: int = 20,
234 db_path: Path | str = DEFAULT_LIBRARY_DB,
235 store_db_path: Path | str = DEFAULT_STORE_DB,
236 ) -> list[LibrarySearchMatch]:
237 """Search indexed briefs plus dated per-run findings from the research store."""
238 expression = _fts_expression(query)
239 if not expression or limit <= 0:
240 return []
241 target = Path(db_path).expanduser()
242 brief_matches: list[LibrarySearchMatch] = []
243 if target.is_file():
244 try:
245 with _managed_connection(_connect(target)) as conn:
246 rows = conn.execute(
247 """SELECT d.topic, d.published_date, d.headline,
248 snippet(library_fts, 4, '', '', ' … ', 36) AS snippet,
249 d.source_path, bm25(library_fts) AS rank
250 FROM library_fts
251 JOIN library_documents d ON d.entry_id = library_fts.entry_id
252 WHERE library_fts MATCH ?
253 ORDER BY rank, d.published_date DESC
254 LIMIT ?""",
255 (expression, limit),
256 ).fetchall()
257 except sqlite3.DatabaseError:
258 rows = []
259 brief_matches = [
260 LibrarySearchMatch(
261 topic=str(row["topic"]),
262 published_date=date.fromisoformat(str(row["published_date"])),
263 headline=str(row["headline"]),
264 snippet=_clean_snippet(row["snippet"]),
265 source_kind="brief",
266 rank=float(row["rank"]),
267 source_path=str(row["source_path"]),
268 )
269 for row in rows
270 ]
271 store_matches = _search_store_sightings(
272 expression, Path(store_db_path).expanduser(), limit
273 )
274 return _merge_ranked_matches([brief_matches, store_matches], limit=limit)
275
276
277 def sync_and_search(
278 query: str,
279 *,
280 memory_dir: Path | str = library.DEFAULT_MEMORY_DIR,
281 briefs_dir: Path | str = library.DEFAULT_BRIEFS_DIR,
282 db_path: Path | str = DEFAULT_LIBRARY_DB,
283 store_db_path: Path | str = DEFAULT_STORE_DB,
284 limit: int = 20,
285 ) -> tuple[list[LibrarySearchMatch], SyncResult]:
286 synced = sync_library(memory_dir, briefs_dir, db_path=db_path)
287 return search(
288 query,
289 limit=limit,
290 db_path=db_path,
291 store_db_path=store_db_path,
292 ), synced
293
294
295 def _sync_library_rust(
296 memory_dir: Path | str,
297 briefs_dir: Path | str,
298 db_path: Path,
299 ) -> SyncResult | None:
300 """Fast parallel sync path using ``last30days-core`` for Markdown scanning and fingerprinting."""
301 md_requests, json_entries, notes = library._collect_sync_inputs(memory_dir, briefs_dir)
302 if md_requests:
303 wire_requests = [
304 {
305 "path": r["path"],
306 "stem": r["stem"],
307 "source_format": r["source_format"],
308 "expected_dev_ino": r["expected_dev_ino"],
309 "fallback_date": r["fallback_date"],
310 }
311 for r in md_requests
312 ]
313 outcomes = rust_accel.scan_markdown_files(wire_requests)
314 if outcomes is None:
315 return None
316 else:
317 outcomes = []
318
319 # Merge scanned Markdown metadata + JSON entries using exact _keep_preferred semantics.
320 # Each value: (kind, mtime_ns, size, entry_id, slug, pub_date, stem, source_format, unbounded, fingerprint, payload)
321 preferred: dict[str, dict[str, object]] = {}
322
323 def _keep(record: dict[str, object]) -> None:
324 eid = str(record["entry_id"])
325 existing_rec = preferred.get(eid)
326 if existing_rec is None or int(record["mtime_ns"]) > int(existing_rec["mtime_ns"]):
327 preferred[eid] = record
328
329 for req, outcome in zip(md_requests, outcomes):
330 if outcome.get("status") != "ok":
331 notes.append(f"Skipped {req['path']}: {outcome.get('reason', 'scan failed')}")
332 continue
333 meta = outcome["meta"]
334 _keep(
335 {
336 "kind": "md",
337 "mtime_ns": req["_mtime_ns"],
338 "size": req["_size"],
339 "entry_id": meta["entry_id"],
340 "slug": meta["slug"],
341 "topic": meta["topic"],
342 "published_date": meta["published_date"],
343 "stem": req["stem"],
344 "source_format": meta["source_format"],
345 "unbounded_private": bool(meta["unbounded_private"]),
346 "fingerprint": meta["indexable_fingerprint"],
347 "path": Path(str(req["path"])),
348 "root": req.get("_root"),
349 "expected_parent_dir": req.get("_expected_parent_dir"),
350 "expected_parent_id": req.get("_expected_parent_id"),
351 }
352 )
353
354 for entry in json_entries:
355 mtime_ns, file_size = _entry_file_identity(entry)
356 _keep(
357 {
358 "kind": "json",
359 "mtime_ns": mtime_ns,
360 "size": file_size,
361 "entry_id": entry.entry_id,
362 "slug": entry.slug,
363 "topic": entry.topic,
364 "published_date": entry.published_date.isoformat(),
365 "stem": entry.source_path.stem,
366 "source_format": entry.source_format,
367 "unbounded_private": library.is_unbounded_private_brief(
368 entry.content, source_format=entry.source_format
369 ),
370 "fingerprint": _fingerprint(_indexable_content(entry.content)),
371 "entry": entry,
372 }
373 )
374
375 # Mirror library._suppress_superseded_raw (requires full topic agreement
376 # alongside slug and date so distinct topics such as C# and C++ stay visible).
377 finished_keys = {
378 (rec["slug"], str(rec["topic"]).casefold(), rec["published_date"])
379 for rec in preferred.values()
380 if rec["source_format"] == "finished-brief" and not rec["unbounded_private"]
381 }
382 if finished_keys:
383 preferred = {
384 eid: rec
385 for eid, rec in preferred.items()
386 if not (
387 rec["source_format"] == "markdown"
388 and (rec["slug"], str(rec["topic"]).casefold(), rec["published_date"]) in finished_keys
389 and library._is_unsuffixed_raw_dump(str(rec["stem"]))
390 )
391 }
392
393 _ensure_private_directory(db_path.parent)
394 indexed = unchanged = 0
395 with _managed_connection(_connect(db_path)) as conn:
396 existing = {
397 row["entry_id"]: (row["source_mtime_ns"], row["source_size"], row["content_hash"])
398 for row in conn.execute(
399 "SELECT entry_id, source_mtime_ns, source_size, content_hash FROM library_documents"
400 )
401 }
402 current_ids: set[str] = set()
403 fts_rows = conn.execute("SELECT count(*) FROM library_fts").fetchone()[0]
404 fts_trustworthy = fts_rows >= len(existing) if existing else True
405
406 for rec in preferred.values():
407 if rec["unbounded_private"]:
408 continue
409 eid = str(rec["entry_id"])
410 current_ids.add(eid)
411 mtime_ns = int(rec["mtime_ns"])
412 file_size = int(rec["size"])
413 fingerprint = str(rec["fingerprint"])
414 if fts_trustworthy and existing.get(eid) == (mtime_ns, file_size, fingerprint):
415 unchanged += 1
416 continue
417 if rec["kind"] == "json":
418 _upsert_entry(conn, rec["entry"], fingerprint=fingerprint) # type: ignore[arg-type]
419 indexed += 1
420 else:
421 try:
422 entry = library.parse_markdown_file(
423 rec["path"], # type: ignore[arg-type]
424 source_format=str(rec["source_format"]),
425 root=rec.get("root"), # type: ignore[arg-type]
426 expected_parent_dir=rec.get("expected_parent_dir"), # type: ignore[arg-type]
427 expected_parent_id=rec.get("expected_parent_id"), # type: ignore[arg-type]
428 )
429 except (OSError, UnicodeError, ValueError) as exc:
430 notes.append(f"Skipped {rec['path']}: {exc}")
431 current_ids.discard(eid)
432 continue
433 if library.is_unbounded_private_brief(
434 entry.content, source_format=entry.source_format
435 ):
436 current_ids.discard(eid)
437 continue
438 if entry.entry_id != eid:
439 current_ids.discard(eid)
440 current_ids.add(entry.entry_id)
441 if (
442 entry.entry_id != eid
443 or entry.source_mtime_ns != mtime_ns
444 or entry.source_size != file_size
445 ):
446 fingerprint = _fingerprint(_indexable_content(entry.content))
447 _upsert_entry(conn, entry, fingerprint=fingerprint)
448 indexed += 1
449
450 stale_ids = set(existing) - current_ids
451 for entry_id in stale_ids:
452 conn.execute("DELETE FROM library_fts WHERE entry_id = ?", (entry_id,))
453 conn.execute("DELETE FROM library_documents WHERE entry_id = ?", (entry_id,))
454 conn.commit()
455
456 return SyncResult(
457 indexed=indexed,
458 removed=len(stale_ids),
459 unchanged=unchanged,
460 notes=tuple(notes),
461 )
462
463
464 def _sync_library(
465 memory_dir: Path | str,
466 briefs_dir: Path | str,
467 db_path: Path,
468 ) -> SyncResult:
469 if (
470 rust_accel.engine_mode() != "python"
471 and library.scan_library is library._ORIGINAL_SCAN_LIBRARY
472 ):
473 accelerated = _sync_library_rust(memory_dir, briefs_dir, db_path)
474 if accelerated is not None:
475 return accelerated
476
477 entries, notes = library.scan_library(memory_dir, briefs_dir)
478 _ensure_private_directory(db_path.parent)
479 indexed = unchanged = 0
480 with _managed_connection(_connect(db_path)) as conn:
481 existing = {
482 row["entry_id"]: (row["source_mtime_ns"], row["source_size"], row["content_hash"])
483 for row in conn.execute(
484 "SELECT entry_id, source_mtime_ns, source_size, content_hash FROM library_documents"
485 )
486 }
487 current_ids: set[str] = set()
488 # If the FTS table was lost or recreated empty while library_documents
489 # survived, the fingerprint check alone would mark everything unchanged
490 # and searches would silently return nothing. Verify row counts agree
491 # before trusting fingerprints.
492 fts_rows = conn.execute("SELECT count(*) FROM library_fts").fetchone()[0]
493 fts_trustworthy = fts_rows >= len(existing) if existing else True
494 for entry in entries:
495 if library.is_unbounded_private_brief(entry.content, source_format=entry.source_format):
496 continue
497 current_ids.add(entry.entry_id)
498 mtime_ns, file_size = _entry_file_identity(entry)
499 fingerprint = _fingerprint(_indexable_content(entry.content))
500 if fts_trustworthy and existing.get(entry.entry_id) == (
501 mtime_ns, file_size, fingerprint
502 ):
503 unchanged += 1
504 continue
505 _upsert_entry(conn, entry, fingerprint=fingerprint)
506 indexed += 1
507 stale_ids = set(existing) - current_ids
508 for entry_id in stale_ids:
509 conn.execute("DELETE FROM library_fts WHERE entry_id = ?", (entry_id,))
510 conn.execute("DELETE FROM library_documents WHERE entry_id = ?", (entry_id,))
511 conn.commit()
512 return SyncResult(
513 indexed=indexed,
514 removed=len(stale_ids),
515 unchanged=unchanged,
516 notes=tuple(notes),
517 )
518
519
520 def _regular_stat(path: Path) -> os.stat_result:
521 if _IS_JUNCTION is not None and _IS_JUNCTION(path):
522 raise OSError(errno.ELOOP, f"Refusing to follow junction: {path}")
523 st = path.lstat()
524 if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode):
525 raise OSError(f"Expected a regular library file: {path}")
526 return st
527
528
529 def _entry_file_identity(entry: library.LibraryEntry) -> tuple[int, int]:
530 if entry.source_mtime_ns is not None and entry.source_size is not None:
531 return entry.source_mtime_ns, entry.source_size
532 st = _regular_stat(entry.source_path)
533 return st.st_mtime_ns, st.st_size
534
535
536 def _connect(path: Path) -> sqlite3.Connection:
537 _ensure_private_directory(path.parent)
538 safe_path = prepare_private_sqlite_files(path, create=True)
539 conn = sqlite3.connect(str(safe_path))
540 try:
541 conn.row_factory = sqlite3.Row
542 conn.execute("PRAGMA busy_timeout=5000")
543 conn.executescript(_SCHEMA)
544 except BaseException:
545 conn.close()
546 raise
547 return conn
548
549
550 def _upsert_entry(
551 conn: sqlite3.Connection,
552 entry: library.LibraryEntry,
553 *,
554 fingerprint: str | None = None,
555 ) -> None:
556 mtime_ns, file_size = _entry_file_identity(entry)
557 private_free_content = library.public_markdown(entry.content)
558 indexed_content = _without_library_context(private_free_content)
559 headline = entry.headline
560 summary = entry.summary
561 if private_free_content != entry.content and entry.source_format in {"markdown", "finished-brief"}:
562 headline = library._markdown_headline(private_free_content) or library._brief_prose_headline(private_free_content) or entry.topic
563 summary = library._markdown_summary(private_free_content) or library._brief_prose_summary(private_free_content) or headline
564 content_hash = fingerprint or _fingerprint(indexed_content)
565 if (
566 entry.source_mtime_ns is not None
567 and entry.source_path.is_absolute()
568 and ".." not in entry.source_path.parts
569 ):
570 source_path = str(entry.source_path)
571 else:
572 try:
573 source_path = str(entry.source_path.resolve(strict=True))
574 except (OSError, RuntimeError):
575 source_path = str(entry.source_path)
576 replaced = conn.execute(
577 "SELECT entry_id FROM library_documents WHERE source_path = ? AND entry_id != ?",
578 (source_path, entry.entry_id),
579 ).fetchall()
580 for row in replaced:
581 conn.execute("DELETE FROM library_fts WHERE entry_id = ?", (row["entry_id"],))
582 conn.execute("DELETE FROM library_documents WHERE entry_id = ?", (row["entry_id"],))
583 conn.execute("DELETE FROM library_fts WHERE entry_id = ?", (entry.entry_id,))
584 conn.execute(
585 """INSERT INTO library_documents
586 (entry_id, source_path, source_mtime_ns, source_size, content_hash,
587 topic, published_date, headline, summary, source_format)
588 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
589 ON CONFLICT(entry_id) DO UPDATE SET
590 source_path=excluded.source_path,
591 source_mtime_ns=excluded.source_mtime_ns,
592 source_size=excluded.source_size,
593 content_hash=excluded.content_hash,
594 topic=excluded.topic,
595 published_date=excluded.published_date,
596 headline=excluded.headline,
597 summary=excluded.summary,
598 source_format=excluded.source_format""",
599 (
600 entry.entry_id,
601 source_path,
602 mtime_ns,
603 file_size,
604 content_hash,
605 entry.topic,
606 entry.published_date.isoformat(),
607 headline,
608 summary,
609 entry.source_format,
610 ),
611 )
612 conn.execute(
613 "INSERT INTO library_fts(entry_id, topic, headline, summary, content) VALUES (?, ?, ?, ?, ?)",
614 (entry.entry_id, entry.topic, headline, summary, indexed_content),
615 )
616
617
618 def _search_store_sightings(
619 expression: str,
620 store_db_path: Path,
621 limit: int,
622 ) -> list[LibrarySearchMatch]:
623 if not store_db_path.is_file():
624 return []
625 try:
626 path = prepare_private_sqlite_files(store_db_path)
627 # Standard SQLite builds reject a UNC server name in a URI authority.
628 use_uri = os.name == "posix"
629 database = f"{path.as_uri()}?mode=ro" if use_uri else str(path)
630 with _managed_connection(sqlite3.connect(database, uri=use_uri)) as conn:
631 conn.row_factory = sqlite3.Row
632 rows = conn.execute(
633 """SELECT t.name AS topic, rr.run_date,
634 COALESCE(fs.source_title, f.source_title, f.summary) AS headline,
635 snippet(findings_fts, 0, '', '', ' … ', 30) AS snippet,
636 fs.source_url, fs.engagement_score, bm25(findings_fts) AS rank
637 FROM findings_fts
638 JOIN findings f ON f.id = findings_fts.rowid
639 JOIN finding_sightings fs ON fs.finding_id = f.id
640 JOIN research_runs rr ON rr.id = fs.run_id
641 JOIN topics t ON t.id = fs.topic_id
642 WHERE findings_fts MATCH ? AND rr.status IN ('completed', 'degraded')
643 AND fs.source != 'corpus' AND f.dismissed = 0
644 ORDER BY rank, rr.run_date DESC
645 LIMIT ?""",
646 (expression, limit),
647 ).fetchall()
648 except (sqlite3.DatabaseError, OSError):
649 return []
650 matches: list[LibrarySearchMatch] = []
651 for row in rows:
652 try:
653 published = date.fromisoformat(str(row["run_date"])[:10])
654 except ValueError:
655 continue
656 matches.append(
657 LibrarySearchMatch(
658 topic=str(row["topic"]),
659 published_date=published,
660 headline=str(row["headline"] or "Saved finding"),
661 snippet=_clean_snippet(row["snippet"]),
662 source_kind="store",
663 rank=float(row["rank"]),
664 url=str(row["source_url"] or ""),
665 engagement=(
666 float(row["engagement_score"])
667 if row["engagement_score"] is not None
668 else None
669 ),
670 )
671 )
672 return matches
673
674
675 def _fts_expression(query: str) -> str:
676 terms = []
677 for word in _TOKEN.findall(query):
678 # unicode61 can index a multi-accent letter and its decomposed form
679 # differently. Include both spellings without rewriting other words.
680 decomposed = unicodedata.normalize("NFD", word)
681 if re.search(r"[\u0300-\u036f]", decomposed):
682 forms = dict.fromkeys((word, unicodedata.normalize("NFC", word), decomposed))
683 else:
684 forms = (word,)
685 quoted = [f'"{form}"' for form in forms]
686 terms.append(quoted[0] if len(quoted) == 1 else "(" + " OR ".join(quoted) + ")")
687 return " AND ".join(terms)
688
689
690 def _fingerprint(content: str) -> str:
691 payload = f"{INDEX_FINGERPRINT_VERSION}\0{content}"
692 return hashlib.sha256(payload.encode("utf-8")).hexdigest()
693
694
695 def _clean_snippet(value: object) -> str:
696 return re.sub(r"\s+", " ", str(value or "")).strip()[:500]
697
698
699 def _indexable_content(content: str) -> str:
700 return _without_library_context(library.public_markdown(content))
701
702
703 def _without_library_context(content: str) -> str:
704 without_marked = _MARKED_LIBRARY_CONTEXT.sub("", content)
705 return _LEGACY_LIBRARY_CONTEXT.sub("", without_marked)
706
707
708 def _harden_private_directory_fd(directory: Path) -> None:
709 """Verify ``directory`` is an owned real directory and fchmod it to 0o700."""
710 if _IS_JUNCTION is not None and _IS_JUNCTION(directory):
711 raise OSError(errno.ELOOP, f"Refusing to follow junction directory: {directory}")
712 if os.name != "posix":
713 st = directory.lstat()
714 if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
715 raise OSError(f"Expected a real private directory: {directory}")
716 return
717 flags = os.O_RDONLY
718 for attr in ("O_DIRECTORY", "O_NOFOLLOW", "O_CLOEXEC"):
719 flags |= getattr(os, attr, 0)
720 try:
721 fd = os.open(directory, flags)
722 except OSError as exc:
723 if exc.errno == errno.ELOOP:
724 raise OSError(
725 errno.ELOOP, f"Refusing to follow symlink directory: {directory}"
726 ) from exc
727 raise
728 try:
729 st = os.fstat(fd)
730 if not stat.S_ISDIR(st.st_mode):
731 raise OSError(f"Expected a real private directory: {directory}")
732 geteuid = getattr(os, "geteuid", None)
733 if geteuid is not None and st.st_uid != geteuid():
734 raise OSError(f"Refusing to use private directory owned by another user: {directory}")
735 if stat.S_IMODE(st.st_mode) != 0o700:
736 os.fchmod(fd, 0o700)
737 finally:
738 os.close(fd)
739
740
741 def _ensure_private_directory(path: Path) -> Path:
742 target = Path(path).expanduser()
743 abs_target = target if target.is_absolute() else Path(os.getcwd()) / target
744 missing_names: list[str] = []
745 current = abs_target
746 while True:
747 if _IS_JUNCTION is not None and _IS_JUNCTION(current):
748 raise OSError(errno.ELOOP, f"Refusing to follow junction directory: {current}")
749 try:
750 current.lstat()
751 break
752 except FileNotFoundError:
753 if current == current.parent:
754 raise
755 if current.name in ("", ".", ".."):
756 raise OSError(f"Invalid private directory component: {current}")
757 missing_names.append(current.name)
758 current = current.parent
759
760 # Validate the deepest existing ancestor chain BEFORE creating anything.
761 if os.name == "posix":
762 verified = private_files._resolve_trusted_parent_dir(current)
763 else:
764 st = current.lstat()
765 if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
766 raise OSError(f"Expected a directory for private file: {current}")
767 verified = current.resolve(strict=True)
768
769 for name in reversed(missing_names):
770 verified = verified / name
771 if _IS_JUNCTION is not None and _IS_JUNCTION(verified):
772 raise OSError(errno.ELOOP, f"Refusing to follow junction directory: {verified}")
773 try:
774 os.mkdir(verified, 0o700)
775 except FileExistsError:
776 pass
777 _harden_private_directory_fd(verified)
778 return verified
779
780
781 def _is_confirmed_corruption(exc: sqlite3.DatabaseError) -> bool:
782 message = str(exc).casefold()
783 return any(
784 marker in message
785 for marker in (
786 "file is not a database",
787 "database disk image is malformed",
788 "database schema is corrupt",
789 "malformed database schema",
790 )
791 )
792
793
794 def _merge_ranked_matches(
795 corpora: list[list[LibrarySearchMatch]],
796 *,
797 limit: int,
798 ) -> list[LibrarySearchMatch]:
799 normalized: list[LibrarySearchMatch] = []
800 for matches in corpora:
801 for position, match in enumerate(matches, start=1):
802 normalized.append(replace(match, rank=-(1.0 / (60 + position))))
803 combined = _dedupe_matches(normalized)
804 return sorted(
805 combined,
806 key=lambda match: (
807 match.rank,
808 -match.published_date.toordinal(),
809 match.topic.casefold(),
810 match.headline.casefold(),
811 ),
812 )[:limit]
813
814
815 def _dedupe_matches(matches: list[LibrarySearchMatch]) -> list[LibrarySearchMatch]:
816 seen: set[tuple[str, date, str, str, str]] = set()
817 kept: list[LibrarySearchMatch] = []
818 for match in matches:
819 key = (
820 match.topic.casefold(),
821 match.published_date,
822 match.headline.casefold(),
823 match.source_kind,
824 match.source_path,
825 )
826 if key not in seen:
827 seen.add(key)
828 kept.append(match)
829 return kept
830
831
832 def _remove_database(path: Path) -> None:
833 for candidate in (
834 path,
835 Path(f"{path}-wal"),
836 Path(f"{path}-shm"),
837 Path(f"{path}-journal"),
838 ):
839 try:
840 st = candidate.lstat()
841 if not stat.S_ISREG(st.st_mode):
842 continue
843 candidate.unlink()
844 except FileNotFoundError:
845 pass
846
846 lines PYTHON