返回 last30days-skill
corpus.py
根目录 / skills / last30days / scripts / lib / corpus.py
1 """Deterministic, local-only document corpus source.
2
3 The corpus adapter deliberately has no HTTP dependency. It scans explicitly
4 registered directories, extracts small text documents (and PDFs only when the
5 local ``pdftotext`` binary is available), and returns normalized ``SourceItem``
6 objects for the shared relevance/fusion pipeline.
7 """
8
9 from __future__ import annotations
10
11 import hashlib
12 import io
13 import json
14 import os
15 import selectors
16 import signal
17 import subprocess
18 import threading
19 import time
20 from dataclasses import dataclass, field
21 from datetime import datetime, timezone
22 from pathlib import Path
23 from shutil import which
24 from typing import Any, Iterable
25
26 from . import entity_extract, log, relevance, schema, subproc
27
28 SOURCE = "corpus"
29 SUPPORTED_SUFFIXES = {".md", ".txt", ".pdf"}
30 IGNORED_DIRECTORIES = {".git", "node_modules"}
31 MAX_FILES = 500
32 MAX_TEXT_CHARS = 1_000_000
33 MAX_CACHE_TEXT_CHARS = MAX_TEXT_CHARS
34 MAX_CACHE_BYTES = 50 * 1024 * 1024
35 MAX_CACHE_ENTRIES = 2_000
36 PDF_TIMEOUT_SECONDS = 20.0
37 _PDF_READ_CHUNK_BYTES = 65536
38 CACHE_FILENAME = "corpus-cache.json"
39 CACHE_SCHEMA_VERSION = "last30days-corpus-cache/v2"
40
41 _CACHE_LOCK = threading.Lock()
42
43
44 @dataclass
45 class CorpusScanResult:
46 """One bounded scan, including non-fatal extraction notes."""
47
48 items: list[schema.SourceItem]
49 notes: list[str] = field(default_factory=list)
50 files_scanned: int = 0
51 cache_hits: int = 0
52
53
54 def resolve_directories(
55 cli_directories: Iterable[str] | None,
56 configured: str | Iterable[str] | None,
57 ) -> list[Path]:
58 """Merge repeatable CLI paths with ``os.pathsep``-separated config paths."""
59 raw: list[str] = [str(value) for value in (cli_directories or []) if str(value).strip()]
60 if isinstance(configured, str):
61 raw.extend(value for value in configured.split(os.pathsep) if value.strip())
62 elif configured:
63 raw.extend(str(value) for value in configured if str(value).strip())
64
65 resolved: list[Path] = []
66 seen: set[str] = set()
67 for value in raw:
68 path = Path(value.strip()).expanduser().resolve()
69 key = os.path.normcase(str(path))
70 if key in seen:
71 continue
72 seen.add(key)
73 resolved.append(path)
74 return resolved
75
76
77 def _safe_error(exc: BaseException) -> str:
78 """Describe an error without str(exc), which embeds absolute paths.
79
80 These notes travel into source_status detail and render in coverage
81 diagnostics outside the private corpus block.
82 """
83 reason = getattr(exc, "strerror", None)
84 return str(reason) if reason else exc.__class__.__name__
85
86
87 def search(
88 topic: str,
89 directories: Iterable[Path | str],
90 *,
91 from_date: str,
92 to_date: str,
93 all_time: bool = False,
94 limit: int = 12,
95 cache_dir: Path | None = None,
96 ) -> CorpusScanResult:
97 """Search registered directories without making any network calls."""
98 roots = resolve_directories([str(path) for path in directories], None)
99 notes: list[str] = []
100 cache_path = cache_dir / CACHE_FILENAME if cache_dir is not None else None
101 with _CACHE_LOCK:
102 cache = _load_cache(cache_path)
103 cache_entries = cache.setdefault("entries", {})
104 cache_entry_sizes = {
105 path: _cache_entry_fragment_size(path, value)
106 for path, value in cache_entries.items()
107 }
108
109 candidates: list[tuple[float, int, schema.SourceItem]] = []
110 seen_files: set[str] = set()
111 files_scanned = 0
112 cache_hits = 0
113 pdf_available = which("pdftotext")
114 pdf_unavailable_noted = False
115
116 readable_roots: list[Path] = []
117 for root in roots:
118 if not root.is_dir():
119 notes.append(f"Skipped corpus root '{Path(root).name}': not a readable directory")
120 continue
121 readable_roots.append(root)
122
123 per_root_limit, extra_slots = divmod(MAX_FILES, len(readable_roots) or 1)
124 scan_limit_reached = False
125 for root_index, root in enumerate(readable_roots):
126 root_limit = per_root_limit + (1 if root_index < extra_slots else 0)
127 root_files_scanned = 0
128 for path in _iter_files(root, notes=notes):
129 if root_files_scanned >= root_limit:
130 scan_limit_reached = True
131 break
132 key = os.path.normcase(str(path))
133 if key in seen_files:
134 continue
135 seen_files.add(key)
136 root_files_scanned += 1
137 files_scanned += 1
138
139 try:
140 stat = path.stat()
141 except OSError as exc:
142 notes.append(f"Skipped {_display_path(path, root)}: {_safe_error(exc)}")
143 continue
144 published_at = datetime.fromtimestamp(
145 stat.st_mtime, tz=timezone.utc
146 ).date().isoformat()
147 if not all_time and not (from_date <= published_at <= to_date):
148 continue
149
150 cached = cache_entries.get(str(path))
151 if (
152 isinstance(cached, dict)
153 and cached.get("mtime_ns") == stat.st_mtime_ns
154 and cached.get("size") == stat.st_size
155 and isinstance(cached.get("text"), str)
156 ):
157 text = cached["text"]
158 cache_hits += 1
159 else:
160 if path.suffix.lower() == ".pdf" and not pdf_available:
161 if not pdf_unavailable_noted:
162 notes.append("Skipped PDF files because pdftotext is not on PATH")
163 pdf_unavailable_noted = True
164 continue
165 try:
166 text = _extract_text(path, pdftotext=pdf_available)
167 except (OSError, subprocess.SubprocessError, UnicodeError) as exc:
168 notes.append(f"Skipped {_display_path(path, root)}: {_safe_error(exc)}")
169 continue
170 _cache_entry_put(cache_entries, cache_entry_sizes, str(path), {
171 "mtime_ns": stat.st_mtime_ns,
172 "size": stat.st_size,
173 "text": text[:MAX_CACHE_TEXT_CHARS],
174 })
175
176 title = _path_title(path)
177 score = _match_score(topic, f"{title}\n{text}")
178 if score < 0.15:
179 continue
180 relative_path = str(path.relative_to(root))
181 path_digest = hashlib.sha256(str(path).encode("utf-8")).hexdigest()
182 item = schema.SourceItem(
183 item_id=f"C{path_digest[:12]}",
184 source=SOURCE,
185 title=title,
186 body=text,
187 url=f"corpus://{path_digest}",
188 container=str(path.parent),
189 published_at=published_at,
190 date_confidence="high",
191 relevance_hint=score,
192 why_relevant=f"Matched local file {relative_path}",
193 # Leave empty so extract_best_snippet derives the matching
194 # window; a file-prefix snippet is preserved verbatim and can
195 # show unrelated intro text (and draw entity-miss demotion).
196 snippet="",
197 metadata={
198 "path": str(path),
199 "relative_path": relative_path,
200 "extension": path.suffix.lower(),
201 "local_only": True,
202 },
203 )
204 candidates.append((score, stat.st_mtime_ns, item))
205 if scan_limit_reached:
206 notes.append(f"Stopped after the {MAX_FILES}-file corpus scan limit")
207
208 cache["schema_version"] = CACHE_SCHEMA_VERSION
209 cache["entries"] = _bounded_entries(cache_entries)
210 with _CACHE_LOCK:
211 _write_cache(cache_path, cache, notes)
212
213 candidates.sort(key=lambda row: (-row[0], -row[1], row[2].title.casefold()))
214 items = [item for _score, _mtime, item in candidates[: max(0, limit)]]
215 log.source_log(
216 "Corpus",
217 f"scanned {files_scanned} file(s), {cache_hits} cache hit(s), {len(items)} match(es)",
218 tty_only=False,
219 )
220 return CorpusScanResult(
221 items=items,
222 notes=notes,
223 files_scanned=files_scanned,
224 cache_hits=cache_hits,
225 )
226
227
228 def _display_path(path: Path | str, root: Path | None = None) -> str:
229 """Render a note-safe path: never the absolute local path.
230
231 Corpus notes flow into source_status detail and the Partial Coverage
232 block, which render OUTSIDE the private corpus markers - an absolute
233 path like /home/user/private/notes/foo.md must not escape there.
234 """
235 candidate = Path(path)
236 if root is not None:
237 try:
238 return str(Path(root).name / candidate.relative_to(root))
239 except ValueError:
240 pass
241 return candidate.name
242
243
244 def _iter_files(root: Path, notes: list[str] | None = None) -> Iterable[Path]:
245 # Bounded newest-first selection: keep only the newest MAX_FILES paths in a
246 # heap while walking, so registering a huge tree does not materialize every
247 # path before the caller's extraction cap applies.
248 import heapq
249
250 heap: list[tuple[int, str]] = []
251 walk_errors = 0
252
253 def _on_walk_error(error: OSError) -> None:
254 nonlocal walk_errors
255 walk_errors += 1
256 if notes is not None and walk_errors <= 3:
257 unreadable = _display_path(error.filename, root) if error.filename else Path(root).name
258 notes.append(f"corpus: could not read {unreadable}: {error.strerror}")
259
260 for current, directory_names, file_names in os.walk(
261 root, followlinks=False, onerror=_on_walk_error
262 ):
263 directory_names[:] = sorted(
264 name
265 for name in directory_names
266 if name not in IGNORED_DIRECTORIES and not name.startswith(".")
267 )
268 current_path = Path(current)
269 for name in sorted(file_names):
270 if name.startswith("."):
271 continue
272 path = current_path / name
273 if path.suffix.lower() in SUPPORTED_SUFFIXES and not path.is_symlink():
274 entry = (_safe_mtime_ns(path), str(path))
275 if len(heap) < MAX_FILES:
276 heapq.heappush(heap, entry)
277 else:
278 heapq.heappushpop(heap, entry)
279 if notes is not None and walk_errors > 3:
280 notes.append(f"corpus: {walk_errors - 3} more unreadable directories suppressed")
281 ordered = sorted(heap, key=lambda item: (-item[0], item[1].casefold()))
282 for _mtime, raw_path in ordered:
283 yield Path(raw_path)
284
285
286 def _safe_mtime_ns(path: Path) -> int:
287 try:
288 return path.stat().st_mtime_ns
289 except OSError:
290 return 0
291
292
293 def _terminate_pdf_proc(
294 proc: subprocess.Popen[bytes],
295 *,
296 own_group: bool,
297 force: bool,
298 ) -> None:
299 if own_group:
300 sig = signal.SIGKILL if force else signal.SIGTERM
301 try:
302 os.killpg(proc.pid, sig)
303 return
304 except (ProcessLookupError, PermissionError, OSError):
305 pass
306 try:
307 if force:
308 proc.kill()
309 else:
310 proc.terminate()
311 except OSError:
312 pass
313
314
315 def _stdout_selectable_fd(stream: Any) -> int | None:
316 if os.name == "nt" or stream is None:
317 return None
318 try:
319 fd = stream.fileno()
320 except (AttributeError, OSError, io.UnsupportedOperation, TypeError, ValueError):
321 return None
322 if not isinstance(fd, int) or fd < 0:
323 return None
324 try:
325 os.set_blocking(fd, False)
326 except (AttributeError, OSError):
327 return None
328 return fd
329
330
331 def _read_stdout_selector(
332 fd: int,
333 *,
334 max_bytes: int,
335 deadline: float,
336 ) -> tuple[list[bytes], bool, bool]:
337 """Drain up to ``max_bytes`` from a non-blocking POSIX pipe fd before ``deadline``.
338
339 Returns ``(chunks, truncated, timed_out)`` with no background thread, so a
340 detached grandchild holding the write end open can never leak a blocked
341 reader thread or pipe fd after timeout.
342 """
343 chunks: list[bytes] = []
344 total = 0
345 with selectors.DefaultSelector() as selector:
346 selector.register(fd, selectors.EVENT_READ)
347 while total < max_bytes:
348 remaining = deadline - time.monotonic()
349 if remaining <= 0:
350 return chunks, False, True
351 events = selector.select(timeout=remaining)
352 if not events:
353 return chunks, False, True
354 try:
355 chunk = os.read(fd, min(_PDF_READ_CHUNK_BYTES, max_bytes - total))
356 except BlockingIOError:
357 continue
358 if not chunk:
359 return chunks, False, False
360 chunks.append(chunk)
361 total += len(chunk)
362 return chunks, True, False
363
364
365 def _extract_pdf_text(path: Path, pdftotext: str) -> str:
366 cmd = [pdftotext, "-enc", "UTF-8", "--", str(path), "-"]
367 max_bytes = MAX_TEXT_CHARS * 4
368 timeout = PDF_TIMEOUT_SECONDS
369 deadline = time.monotonic() + timeout
370 own_group = hasattr(os, "setsid") and hasattr(os, "killpg")
371 proc = subprocess.Popen(
372 cmd,
373 stdin=subprocess.DEVNULL,
374 stdout=subprocess.PIPE,
375 stderr=subprocess.DEVNULL,
376 start_new_session=own_group,
377 )
378 chunks: list[bytes] = []
379 truncated = False
380 read_error: list[BaseException] = []
381 reader: threading.Thread | None = None
382 reader_started = False
383 kill_wait_attempted = False
384 registered = False
385
386 def _force_kill_and_reap() -> None:
387 nonlocal kill_wait_attempted
388 if kill_wait_attempted or proc.returncode is not None:
389 return
390 kill_wait_attempted = True
391 _terminate_pdf_proc(proc, own_group=own_group, force=True)
392 try:
393 proc.wait(timeout=2.0)
394 except subprocess.TimeoutExpired:
395 pass
396
397 try:
398 subproc.register_child_pid(proc.pid)
399 registered = True
400
401 fd = _stdout_selectable_fd(proc.stdout)
402 if fd is not None:
403 chunks, truncated, timed_out = _read_stdout_selector(
404 fd,
405 max_bytes=max_bytes,
406 deadline=deadline,
407 )
408 if timed_out:
409 _force_kill_and_reap()
410 raise subprocess.TimeoutExpired(cmd, timeout)
411 else:
412 def _drain_stdout() -> None:
413 nonlocal truncated
414 assert proc.stdout is not None
415 total = 0
416 try:
417 while total < max_bytes:
418 chunk = proc.stdout.read(min(_PDF_READ_CHUNK_BYTES, max_bytes - total))
419 if not chunk:
420 break
421 chunks.append(chunk)
422 total += len(chunk)
423 if total >= max_bytes:
424 truncated = True
425 except BaseException as exc:
426 read_error.append(exc)
427 finally:
428 try:
429 proc.stdout.close()
430 except OSError:
431 pass
432
433 reader = threading.Thread(target=_drain_stdout, daemon=True)
434 reader.start()
435 reader_started = True
436
437 remaining = deadline - time.monotonic()
438 reader.join(timeout=max(0.0, remaining))
439 if reader.is_alive():
440 _force_kill_and_reap()
441 reader.join(timeout=0.5)
442 raise subprocess.TimeoutExpired(cmd, timeout)
443
444 if truncated:
445 if fd is not None and proc.stdout is not None:
446 try:
447 proc.stdout.close()
448 except OSError:
449 pass
450 if proc.poll() is None:
451 _terminate_pdf_proc(proc, own_group=own_group, force=False)
452 try:
453 proc.wait(timeout=1.0)
454 except subprocess.TimeoutExpired:
455 _force_kill_and_reap()
456 if read_error:
457 raise read_error[0]
458 return b"".join(chunks).decode("utf-8", errors="replace")[:MAX_TEXT_CHARS]
459
460 remaining = deadline - time.monotonic()
461 if remaining <= 0:
462 if proc.poll() is None:
463 _force_kill_and_reap()
464 raise subprocess.TimeoutExpired(cmd, timeout)
465 else:
466 try:
467 proc.wait(timeout=remaining)
468 except subprocess.TimeoutExpired:
469 _force_kill_and_reap()
470 raise
471
472 if read_error:
473 raise read_error[0]
474 if proc.returncode != 0:
475 raise subprocess.CalledProcessError(proc.returncode, cmd)
476 return b"".join(chunks).decode("utf-8", errors="replace")[:MAX_TEXT_CHARS]
477 finally:
478 _force_kill_and_reap()
479 if registered:
480 subproc.unregister_child_pid(proc.pid)
481 # On the selector path no reader thread exists; on the Windows/mock
482 # fallback path, close only when no reader thread is still blocked in
483 # BufferedReader.read() to avoid deadlocking on its internal lock.
484 if proc.stdout is not None and (
485 reader is None or not reader_started or not reader.is_alive()
486 ):
487 try:
488 proc.stdout.close()
489 except OSError:
490 pass
491
492
493 def _extract_text(path: Path, *, pdftotext: str | None) -> str:
494 if path.suffix.lower() == ".pdf":
495 if not pdftotext:
496 return ""
497 return _extract_pdf_text(path, pdftotext)
498 with path.open("r", encoding="utf-8", errors="replace") as handle:
499 return handle.read(MAX_TEXT_CHARS)
500
501
502 def _path_title(path: Path) -> str:
503 title = path.stem.replace("_", " ").replace("-", " ")
504 return " ".join(title.split()) or path.name
505
506
507 def _match_score(topic: str, text: str) -> float:
508 lexical = relevance.token_overlap_relevance(topic, text)
509 topic_entities = entity_extract.extract_text_entities(topic)
510 text_entities = entity_extract.extract_text_entities(text)
511 entity_score = entity_extract.entity_overlap(topic_entities, text_entities)
512 return round(max(lexical, entity_score * 0.9), 4)
513
514
515 def _load_cache(path: Path | None) -> dict[str, Any]:
516 if path is None:
517 return {"schema_version": CACHE_SCHEMA_VERSION, "entries": {}}
518 try:
519 if path.stat().st_size > MAX_CACHE_BYTES:
520 return {"schema_version": CACHE_SCHEMA_VERSION, "entries": {}}
521 payload = json.loads(path.read_text(encoding="utf-8"))
522 except (OSError, UnicodeError, json.JSONDecodeError):
523 return {"schema_version": CACHE_SCHEMA_VERSION, "entries": {}}
524 if not isinstance(payload, dict) or payload.get("schema_version") != CACHE_SCHEMA_VERSION:
525 return {"schema_version": CACHE_SCHEMA_VERSION, "entries": {}}
526 if not isinstance(payload.get("entries"), dict):
527 payload["entries"] = {}
528 payload["entries"] = _bounded_entries(payload["entries"])
529 return payload
530
531
532 def _bounded_entries(entries: Any) -> dict[str, Any]:
533 if not isinstance(entries, dict):
534 return {}
535 ordered = sorted(
536 (
537 (path, value)
538 for path, value in entries.items()
539 if (
540 isinstance(path, str)
541 and isinstance(value, dict)
542 and isinstance(value.get("text"), str)
543 )
544 ),
545 key=lambda row: int(row[1].get("mtime_ns") or 0),
546 reverse=True,
547 )
548 base_bytes = len(
549 json.dumps(
550 {"schema_version": CACHE_SCHEMA_VERSION, "entries": {}},
551 ensure_ascii=False,
552 ).encode("utf-8")
553 )
554 used_bytes = base_bytes
555 bounded: dict[str, Any] = {}
556 for path, value in ordered[:MAX_CACHE_ENTRIES]:
557 normalized = {
558 "mtime_ns": value.get("mtime_ns"),
559 "size": value.get("size"),
560 "text": value["text"][:MAX_CACHE_TEXT_CHARS],
561 }
562 fragment = json.dumps({path: normalized}, ensure_ascii=False).encode("utf-8")
563 fragment_bytes = len(fragment) - 2 + (2 if bounded else 0)
564 if used_bytes + fragment_bytes > MAX_CACHE_BYTES:
565 continue
566 bounded[path] = normalized
567 used_bytes += fragment_bytes
568 return bounded
569
570
571 def _cache_entry_fragment_size(path: str, value: dict[str, Any]) -> int:
572 return len(json.dumps({path: value}, ensure_ascii=False).encode("utf-8")) - 2
573
574
575 def _cache_entry_put(
576 entries: dict[str, Any],
577 sizes: dict[str, int],
578 path: str,
579 value: dict[str, Any],
580 ) -> None:
581 entries[path] = value
582 sizes[path] = _cache_entry_fragment_size(path, value)
583 while (
584 len(entries) > MAX_CACHE_ENTRIES
585 or _cache_payload_size(sizes) > MAX_CACHE_BYTES
586 ):
587 oldest = min(
588 entries,
589 key=lambda candidate: (
590 int(entries[candidate].get("mtime_ns") or 0),
591 candidate,
592 ),
593 )
594 del entries[oldest]
595 del sizes[oldest]
596
597
598 def _cache_payload_size(sizes: dict[str, int]) -> int:
599 base_bytes = len(
600 json.dumps(
601 {"schema_version": CACHE_SCHEMA_VERSION, "entries": {}},
602 ensure_ascii=False,
603 ).encode("utf-8")
604 )
605 separators = max(0, len(sizes) - 1) * 2
606 return base_bytes + sum(sizes.values()) + separators
607
608
609 def _write_cache(path: Path | None, payload: dict[str, Any], notes: list[str]) -> None:
610 if path is None:
611 return
612 try:
613 _ensure_private_directory(path.parent)
614 payload["entries"] = _bounded_entries(payload.get("entries", {}))
615 encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")
616 temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
617 try:
618 fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
619 except FileExistsError:
620 temporary.unlink()
621 fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
622 with os.fdopen(fd, "wb") as handle:
623 handle.write(encoded)
624 temporary.replace(path)
625 path.chmod(0o600)
626 except OSError as exc:
627 notes.append(f"Corpus cache unavailable: {_safe_error(exc)}")
628
629
630 def _ensure_private_directory(path: Path) -> None:
631 missing: list[Path] = []
632 current = path
633 while not current.exists():
634 missing.append(current)
635 current = current.parent
636 path.mkdir(parents=True, exist_ok=True, mode=0o700)
637 for directory in missing:
638 directory.chmod(0o700)
639
639 lines PYTHON