返回 last30days-skill
library.py
根目录 / skills / last30days / scripts / lib / library.py
1 """Scan saved last30days research artifacts into a deterministic library."""
2
3 from __future__ import annotations
4
5 import errno
6 import hashlib
7 import json
8 import os
9 import re
10 import stat
11 import sys
12 import uuid
13 from contextlib import contextmanager
14 from dataclasses import dataclass
15 from datetime import date, datetime, timezone
16 from pathlib import Path
17
18 from . import rust_accel
19
20 try:
21 import fcntl
22 except ImportError:
23 fcntl = None # type: ignore[assignment]
24
25
26 DEFAULT_MEMORY_DIR = Path.home() / "Documents" / "Last30Days"
27 DEFAULT_BRIEFS_DIR = Path.home() / ".local" / "share" / "last30days" / "briefs"
28 FINISHED_SUBDIR = "finished"
29 LIBRARY_ID_FILENAME = ".last30days-library-id"
30 MAX_LIBRARY_FILE_BYTES = 10 * 1024 * 1024
31 _IS_JUNCTION = getattr(os.path, "isjunction", None)
32 _SUPPORTS_DIR_FD = (
33 os.name == "posix"
34 and hasattr(os, "O_DIRECTORY")
35 and os.open in getattr(os, "supports_dir_fd", set())
36 and os.stat in getattr(os, "supports_dir_fd", set())
37 )
38 _SUPPORTS_LISTDIR_FD = os.listdir in getattr(os, "supports_fd", set())
39 _DARWIN_F_GETPATH = 50
40 _DARWIN_MAXPATHLEN = 1024
41 PUBLIC_DRILL_MARKER = "<!-- LAST30DAYS_PUBLIC_DRILL -->"
42 PUBLIC_FRESHNESS_MARKER = "<!-- LAST30DAYS_PUBLIC_FRESHNESS -->"
43 PUBLIC_CLUSTERS_MARKER = "<!-- LAST30DAYS_PUBLIC_CLUSTERS -->"
44 PRIVATE_CORPUS_START = "<!-- LAST30DAYS_PRIVATE_CORPUS_START -->"
45 PRIVATE_CORPUS_END = "<!-- LAST30DAYS_PRIVATE_CORPUS_END -->"
46
47 _REPORT_TITLE = re.compile(r"^#\s+last30days(?:\s+v[^:]+)?:\s*(.+?)\s*$", re.MULTILINE | re.IGNORECASE)
48 _FIRST_TITLE = re.compile(r"^#\s+(.+?)\s*$", re.MULTILINE)
49 _COMPARISON_TITLE_SUFFIX = re.compile(r":\s*What the Community Says\s*\(/Last30Days\)\s*$", re.IGNORECASE)
50 _TOPIC_META_COMMENT = re.compile(r"^<!--\s*last30days-topic:\s*(.+?)\s*-->$", re.MULTILINE)
51 _BADGE_LINE = re.compile(r"^🌐\s*last30days\b[^\r\n]*$", re.MULTILINE)
52 _BADGE_SYNCED_DATE = re.compile(r"\bsynced\s+(\d{4}-\d{2}-\d{2})\b", re.IGNORECASE)
53 _BADGE_VERSION = re.compile(r"^v\d+\.\d+(?:\.\d+)*(?:[-+][A-Za-z0-9._-]+)?$")
54 _BADGE_MONTH_DAY_YEAR = re.compile(
55 r"\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]*\.?\s+(\d{1,2}),\s*(\d{4})\b",
56 re.IGNORECASE,
57 )
58 _BADGE_ISO_DATE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
59 _BADGE_MONTHS = {
60 "jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6,
61 "jul": 7, "aug": 8, "sep": 9, "sept": 9, "oct": 10, "nov": 11, "dec": 12,
62 }
63 _UNSUFFIXED_RAW_STEM = re.compile(r"^(.+)-raw(?:-\d{4}-\d{2}-\d{2}(?:-\d+)?)?$")
64 _PROSE_LABEL_LINE = re.compile(
65 r"^(?:\*\*|__)?(?:what i learned|key patterns(?:\s+from the research)?|best takes|tl;?dr|summary|verdict|bottom line)(?:\*\*|__)?:?(?:\*\*|__)?$",
66 re.IGNORECASE,
67 )
68 _CORPUS_FOOTER_LINE = re.compile(r"\bYour files\b", re.IGNORECASE)
69 _BOLD_FROM_YOUR_FILES = re.compile(
70 r"^\s*(?:\*\*|__)?From your files:?(?:\*\*|__)?:?\s*$",
71 re.MULTILINE | re.IGNORECASE,
72 )
73 _DATE_RANGE = re.compile(
74 r"^-\s*Date range:\s*\d{4}-\d{2}-\d{2}\s+to\s+(\d{4}-\d{2}-\d{2})\s*$",
75 re.MULTILINE | re.IGNORECASE,
76 )
77 _DATED_FILENAME = re.compile(r"-(\d{4}-\d{2}-\d{2})(?:-\d+)?$")
78 _RANKED_HEADLINE = re.compile(r"^###\s+1[.)]\s+(.+?)\s*$", re.MULTILINE)
79 _SCORE_SUFFIX = re.compile(r"\s+\(score\s+[^)]*\)\s*$", re.IGNORECASE)
80 _MARKDOWN_LINK = re.compile(r"\[([^]]+)]\([^)]+\)")
81 _LIBRARY_ID = re.compile(r"[0-9a-f]{32}")
82 _GENERATED_BRIEF_NAME = re.compile(
83 r"[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}-\d{4}-\d{2}-\d{2}\.html"
84 )
85 _PRIVATE_CORPUS_BLOCK = re.compile(
86 re.escape(PRIVATE_CORPUS_START) + r".*?(?:" + re.escape(PRIVATE_CORPUS_END) + r"\s*|\Z)",
87 re.DOTALL,
88 )
89 _FENCE_OPEN_BACKTICK = re.compile(r"^[ ]{0,3}(`{3,})[^`\r\n]*$")
90 _FENCE_OPEN_TILDE = re.compile(r"^[ ]{0,3}(~{3,})[^\r\n]*$")
91 _TOP_LEVEL_HEADING = re.compile(r"^#{1,2}[ \t]")
92 _H1_TO_H3_HEADING = re.compile(r"^#{1,3}[ \t]")
93 _DRILL_HEADING = re.compile(r"^## Drill Follow-up[ \t]*$")
94 _DRILL_DEEPER_HEADING = re.compile(r"^### Deeper[ \t]*$")
95 _DRILL_NEW_ITEMS = re.compile(r"^- [0-9]+ new items after dedupe$")
96 _DRILL_SOURCES = re.compile(r"^- Re-researched sources:[^\r\n]*$")
97 _PRIVATE_FRESHNESS_ROW = re.compile(
98 r"^\| \*\*contradicted\*\* \| [^\r\n]*"
99 r"(?:\]\(corpus://| \(Newer corpus item disagrees\))[^\r\n]*(?:\r?\n|\Z)",
100 re.MULTILINE | re.IGNORECASE,
101 )
102 _LEGACY_CORPUS_SIGNAL = re.compile(
103 r"^#{1,3}[ \t]+From your files:?[ \t]*\r?$"
104 r"|^- (?:Sources|Re-researched sources):[^\r\n]*\bYour files\b"
105 r"|^[0-9]+\. \[[^\]\r\n]*\b(?:corpus|your files)\b[^\]\r\n]*\]",
106 re.MULTILINE | re.IGNORECASE,
107 )
108 _FROM_YOUR_FILES_H12 = re.compile(r"^#{1,2}[ \t]+From your files:?[ \t]*$", re.IGNORECASE)
109 _FROM_YOUR_FILES_H3 = re.compile(r"^###[ \t]+From your files:?[ \t]*$", re.IGNORECASE)
110 _FROM_YOUR_FILES_BOLD = re.compile(
111 r"^[ \t]*(?:\*\*|__)From your files:?(?:\*\*|__)?:?[ \t]*$",
112 re.IGNORECASE,
113 )
114 _FRESHNESS_HEADING = re.compile(r"^## Freshness Verification[ \t]*$")
115 _FRESHNESS_TABLE_HEADER = re.compile(r"^\| Verdict \| Claim \| Evidence \| Checked \|$")
116 _FRESHNESS_TABLE_SEP = re.compile(r"^\| --- \| --- \| --- \| --- \|$")
117 _RANKED_CLUSTERS_HEADING = re.compile(r"^## Ranked Evidence Clusters[ \t]*$")
118 _RANKED_CLUSTER_HEADING = re.compile(r"^(?P<prefix>### [0-9]+\. )(?P<title>[^\r\n]*)$")
119 _RANKED_CLUSTER_STATS = re.compile(r" \(score -?[0-9]+, [0-9]+ items?, sources: [^()\r\n]*\)$")
120 _RANKED_REPRESENTATIVE = re.compile(
121 r"^[0-9]+\. \[(?P<sources>[^\]\r\n]+)\] (?P<title>[^\r\n]+)$",
122 )
123 _RANKED_FRESHNESS_BADGE = re.compile(r" \[freshness:[^\]]+\]$")
124 _BRIEF_CLUSTERS_HEADING = re.compile(
125 r"^## (?P<name>Ranked Storylines|Topic Tensions|Source Clusters)[ \t]*$"
126 )
127 _BRIEF_STORYLINE_TITLE = re.compile(r"^### [0-9]+\. [^\r\n]*$")
128 _BRIEF_CLUSTER_LABEL = re.compile(r"^- \*\*[^\r\n]*$")
129
130
131 def _fence_step(line_text: str, fence: tuple[str, int] | None) -> tuple[str, int] | None:
132 """Track CommonMark backtick/tilde fenced code block state across lines."""
133 if fence is None:
134 match = _FENCE_OPEN_BACKTICK.match(line_text) or _FENCE_OPEN_TILDE.match(line_text)
135 if match:
136 token = match.group(1)
137 return token[0], len(token)
138 return None
139 char, min_len = fence
140 stripped_indent = line_text[:3].lstrip(" ") + line_text[3:]
141 count = 0
142 while count < len(stripped_indent) and stripped_indent[count] == char:
143 count += 1
144 if count >= min_len and stripped_indent[count:].strip(" \t") == "":
145 return None
146 return fence
147
148
149 def _find_section_end(
150 lines: list[str],
151 start: int,
152 boundary: re.Pattern[str],
153 ) -> int:
154 """Return index of next non-fenced line matching ``boundary``, or ``len(lines)``."""
155 fence: tuple[str, int] | None = None
156 for idx in range(start, len(lines)):
157 text = lines[idx].rstrip("\r\n")
158 if fence is not None:
159 fence = _fence_step(text, fence)
160 continue
161 if boundary.match(text):
162 return idx
163 fence = _fence_step(text, None)
164 return len(lines)
165
166
167 def _strip_unmarked_drills(markdown: str) -> str:
168 """Strip every non-fenced ``## Drill Follow-up`` not preceded by a known marker."""
169 markers = (PUBLIC_DRILL_MARKER, PRIVATE_CORPUS_START)
170 lines = markdown.splitlines(keepends=True)
171 while True:
172 fence: tuple[str, int] | None = None
173 unmarked_idx: int | None = None
174 for idx, line in enumerate(lines):
175 text = line.rstrip("\r\n")
176 if fence is not None:
177 fence = _fence_step(text, fence)
178 continue
179 if _DRILL_HEADING.match(text):
180 prev_text = lines[idx - 1].rstrip("\r\n") if idx > 0 else ""
181 if prev_text not in markers:
182 unmarked_idx = idx
183 break
184 fence = _fence_step(text, None)
185 if unmarked_idx is None:
186 return "".join(lines)
187 # Legacy drill summaries did not identify their sources. Use the last
188 # non-fenced generated trailer so headings or fenced excerpts cannot end it.
189 end = len(lines)
190 inner_fence: tuple[str, int] | None = None
191 for idx in range(unmarked_idx + 1, len(lines)):
192 text = lines[idx].rstrip("\r\n")
193 if inner_fence is not None:
194 inner_fence = _fence_step(text, inner_fence)
195 continue
196 if (
197 _DRILL_DEEPER_HEADING.match(text)
198 and idx + 3 < len(lines)
199 and lines[idx + 1].rstrip("\r\n").strip(" \t") == ""
200 and _DRILL_NEW_ITEMS.match(lines[idx + 2].rstrip("\r\n"))
201 and _DRILL_SOURCES.match(lines[idx + 3].rstrip("\r\n"))
202 ):
203 end = idx + 4
204 inner_fence = _fence_step(text, None)
205 del lines[unmarked_idx:end]
206
207
208 def _strip_from_your_files_sections(markdown: str) -> str:
209 """Strip unmarked ``From your files`` sections without stopping inside code fences."""
210 lines = markdown.splitlines(keepends=True)
211 out: list[str] = []
212 fence: tuple[str, int] | None = None
213 skip_until: re.Pattern[str] | None = None
214 for line in lines:
215 text = line.rstrip("\r\n")
216 if fence is not None:
217 fence = _fence_step(text, fence)
218 if skip_until is None:
219 out.append(line)
220 continue
221 if skip_until is not None:
222 if skip_until.match(text):
223 skip_until = None
224 else:
225 fence = _fence_step(text, None)
226 continue
227 if _FROM_YOUR_FILES_H12.match(text) or _FROM_YOUR_FILES_BOLD.match(text):
228 skip_until = _TOP_LEVEL_HEADING
229 continue
230 if _FROM_YOUR_FILES_H3.match(text):
231 skip_until = _H1_TO_H3_HEADING
232 continue
233 fence = _fence_step(text, None)
234 out.append(line)
235 return "".join(out)
236
237
238 def _public_legacy_cluster_lines(heading_line: str, body_lines: list[str]) -> str:
239 """Redact corpus representatives and corpus-tainted body from one legacy cluster."""
240 heading_text = heading_line.rstrip("\r\n")
241 ending = heading_line[len(heading_text):]
242 heading_match = _RANKED_CLUSTER_HEADING.match(heading_text)
243 if heading_match is None:
244 return heading_line + "".join(body_lines)
245
246 preamble: list[str] = []
247 rep_blocks: list[tuple[re.Match[str], list[str]]] = []
248 fence: tuple[str, int] | None = None
249 for line in body_lines:
250 text = line.rstrip("\r\n")
251 if fence is not None:
252 fence = _fence_step(text, fence)
253 if rep_blocks:
254 rep_blocks[-1][1].append(line)
255 else:
256 preamble.append(line)
257 continue
258 rep_match = _RANKED_REPRESENTATIVE.match(text)
259 if rep_match is not None:
260 rep_blocks.append((rep_match, [line]))
261 continue
262 fence = _fence_step(text, None)
263 if rep_blocks:
264 rep_blocks[-1][1].append(line)
265 else:
266 preamble.append(line)
267
268 had_representatives = bool(rep_blocks)
269 public_reps: list[tuple[re.Match[str], list[str]]] = []
270 for rep_match, block_lines in rep_blocks:
271 sources = {source.strip().lower() for source in rep_match["sources"].split(",")}
272 if {"corpus", "your files"} & sources:
273 continue
274 public_reps.append((rep_match, block_lines))
275
276 raw_body = "".join(body_lines)
277 cleaned_body = "".join(preamble) + "".join("".join(block) for _, block in public_reps)
278 if raw_body.endswith("\n\n") and cleaned_body and not cleaned_body.endswith("\n\n"):
279 cleaned_body = cleaned_body.rstrip("\r\n") + "\n\n"
280
281 for rep_match, _ in public_reps:
282 title = _RANKED_FRESHNESS_BADGE.sub("", rep_match["title"]).strip()
283 if title:
284 stats = _RANKED_CLUSTER_STATS.search(heading_match["title"])
285 return (
286 heading_match["prefix"]
287 + title
288 + (stats.group() if stats else "")
289 + ending
290 + cleaned_body
291 )
292 if had_representatives:
293 return ""
294 if (
295 _LEGACY_CORPUS_SIGNAL.search(cleaned_body)
296 or "corpus://" in cleaned_body.lower()
297 or _BOLD_FROM_YOUR_FILES.search(cleaned_body)
298 ):
299 return ""
300 return cleaned_body
301
302
303 def _rewrite_ranked_clusters_sections(markdown: str) -> str:
304 """Rewrite unmarked ``## Ranked Evidence Clusters`` sections using fence-aware boundaries."""
305 lines = markdown.splitlines(keepends=True)
306 out: list[str] = []
307 fence: tuple[str, int] | None = None
308 idx = 0
309 while idx < len(lines):
310 line = lines[idx]
311 text = line.rstrip("\r\n")
312 if fence is not None:
313 fence = _fence_step(text, fence)
314 out.append(line)
315 idx += 1
316 continue
317 if _RANKED_CLUSTERS_HEADING.match(text):
318 end = _find_section_end(lines, idx + 1, _TOP_LEVEL_HEADING)
319 prev_text = lines[idx - 1].rstrip("\r\n") if idx > 0 else ""
320 if prev_text == PUBLIC_CLUSTERS_MARKER:
321 out.extend(lines[idx:end])
322 idx = end
323 continue
324 out.append(line)
325 # Split clusters on non-fenced `### N. ` headings.
326 sec_fence: tuple[str, int] | None = None
327 cluster_heading: str | None = None
328 cluster_body: list[str] = []
329 for sec_line in lines[idx + 1:end]:
330 sec_text = sec_line.rstrip("\r\n")
331 if sec_fence is not None:
332 sec_fence = _fence_step(sec_text, sec_fence)
333 if cluster_heading is not None:
334 cluster_body.append(sec_line)
335 else:
336 out.append(sec_line)
337 continue
338 if _RANKED_CLUSTER_HEADING.match(sec_text):
339 if cluster_heading is not None:
340 out.append(_public_legacy_cluster_lines(cluster_heading, cluster_body))
341 cluster_heading = sec_line
342 cluster_body = []
343 continue
344 sec_fence = _fence_step(sec_text, None)
345 if cluster_heading is not None:
346 cluster_body.append(sec_line)
347 else:
348 out.append(sec_line)
349 if cluster_heading is not None:
350 out.append(_public_legacy_cluster_lines(cluster_heading, cluster_body))
351 idx = end
352 continue
353 fence = _fence_step(text, None)
354 out.append(line)
355 idx += 1
356 return "".join(out)
357
358
359 def _rewrite_brief_clusters_sections(markdown: str) -> str:
360 """Strip legacy Production Brief cluster titles using fence-aware boundaries."""
361 lines = markdown.splitlines(keepends=True)
362 out: list[str] = []
363 fence: tuple[str, int] | None = None
364 idx = 0
365 while idx < len(lines):
366 line = lines[idx]
367 text = line.rstrip("\r\n")
368 if fence is not None:
369 fence = _fence_step(text, fence)
370 out.append(line)
371 idx += 1
372 continue
373 match = _BRIEF_CLUSTERS_HEADING.match(text)
374 if match is not None:
375 end = _find_section_end(lines, idx + 1, _TOP_LEVEL_HEADING)
376 prev_text = lines[idx - 1].rstrip("\r\n") if idx > 0 else ""
377 if prev_text == PUBLIC_CLUSTERS_MARKER:
378 out.extend(lines[idx:end])
379 idx = end
380 continue
381 out.append(line)
382 label_re = (
383 _BRIEF_STORYLINE_TITLE
384 if match["name"] == "Ranked Storylines"
385 else _BRIEF_CLUSTER_LABEL
386 )
387 sec_fence: tuple[str, int] | None = None
388 for sec_line in lines[idx + 1:end]:
389 sec_text = sec_line.rstrip("\r\n")
390 if sec_fence is not None:
391 sec_fence = _fence_step(sec_text, sec_fence)
392 out.append(sec_line)
393 continue
394 if label_re.match(sec_text):
395 continue
396 sec_fence = _fence_step(sec_text, None)
397 out.append(sec_line)
398 idx = end
399 continue
400 fence = _fence_step(text, None)
401 out.append(line)
402 idx += 1
403 return "".join(out)
404
405
406 def _strip_unmarked_freshness_sections(markdown: str) -> str:
407 """Strip unmarked ``## Freshness Verification`` tables using fence-aware boundaries."""
408 lines = markdown.splitlines(keepends=True)
409 out: list[str] = []
410 fence: tuple[str, int] | None = None
411 idx = 0
412 while idx < len(lines):
413 line = lines[idx]
414 text = line.rstrip("\r\n")
415 if fence is not None:
416 fence = _fence_step(text, fence)
417 out.append(line)
418 idx += 1
419 continue
420 if (
421 _FRESHNESS_HEADING.match(text)
422 and idx + 3 < len(lines)
423 and lines[idx + 1].rstrip("\r\n").strip(" \t") == ""
424 and _FRESHNESS_TABLE_HEADER.match(lines[idx + 2].rstrip("\r\n"))
425 and _FRESHNESS_TABLE_SEP.match(lines[idx + 3].rstrip("\r\n"))
426 ):
427 end = _find_section_end(lines, idx + 4, _TOP_LEVEL_HEADING)
428 prev_text = lines[idx - 1].rstrip("\r\n") if idx > 0 else ""
429 if prev_text == PUBLIC_FRESHNESS_MARKER:
430 out.extend(lines[idx:end])
431 idx = end
432 continue
433 fence = _fence_step(text, None)
434 out.append(line)
435 idx += 1
436 return "".join(out)
437
438
439 def has_private_corpus(markdown: str) -> bool:
440 """Return whether a document carries local-corpus markers or citations."""
441 return bool(
442 PRIVATE_CORPUS_START in markdown
443 or _LEGACY_CORPUS_SIGNAL.search(markdown)
444 or _PRIVATE_FRESHNESS_ROW.search(markdown)
445 or "corpus://" in markdown.lower()
446 or _CORPUS_FOOTER_LINE.search(markdown)
447 or _BOLD_FROM_YOUR_FILES.search(markdown)
448 )
449
450
451 def _is_structured_engine_report(markdown: str) -> bool:
452 """Return True when markdown carries structured engine report markers.
453
454 Structured engine reports (including saved comparison reports emitted by
455 ``render_comparison_multi``) delimit private corpus sections explicitly via
456 ``PRIVATE_CORPUS_START``/``PRIVATE_CORPUS_END`` and should be redacted in
457 place by ``public_markdown`` rather than excluded wholesale.
458 """
459 return bool(
460 _REPORT_TITLE.search(markdown)
461 or (PRIVATE_CORPUS_START in markdown and PRIVATE_CORPUS_END in markdown)
462 or PUBLIC_CLUSTERS_MARKER in markdown
463 or "## Ranked Evidence Clusters" in markdown
464 or "<!-- EVIDENCE FOR SYNTHESIS" in markdown
465 or "# END OF last30days CANONICAL OUTPUT" in markdown
466 )
467
468
469 def is_unbounded_private_brief(
470 markdown: str,
471 *,
472 source_format: str | None = None,
473 ) -> bool:
474 """Return True when a synthesized chat brief carries unbounded local-corpus content.
475
476 Chat synthesis weaves corpus evidence into heading-free prose, so private
477 passages cannot be reliably isolated by heading or marker stripping.
478 Structured engine reports (including comparisons with bounded corpus blocks)
479 are NOT unbounded and keep their in-place redaction behavior.
480 """
481 if source_format is not None and source_format != "finished-brief":
482 return False
483 if _is_structured_engine_report(markdown):
484 return False
485 return bool(_BADGE_LINE.search(markdown) and has_private_corpus(markdown))
486
487
488 def _strip_private_corpus_blocks(markdown: str) -> str:
489 """Strip explicit private corpus blocks without splicing an earlier public marker onto the next section."""
490 def _replace(match: re.Match[str]) -> str:
491 marker_end = match.start()
492 while marker_end > 0 and markdown[marker_end - 1] in " \t\r\n":
493 marker_end -= 1
494 if markdown.endswith(
495 (PUBLIC_DRILL_MARKER, PUBLIC_CLUSTERS_MARKER, PUBLIC_FRESHNESS_MARKER),
496 0,
497 marker_end,
498 ):
499 return "\n\n"
500 return ""
501
502 return _PRIVATE_CORPUS_BLOCK.sub(_replace, markdown)
503
504
505 def public_markdown(markdown: str) -> str:
506 mode = rust_accel.engine_mode()
507 if mode == "rust" or (mode == "auto" and len(markdown) >= 2048):
508 accelerated = rust_accel.public_markdown(markdown)
509 if accelerated is not None:
510 return accelerated
511 if is_unbounded_private_brief(markdown):
512 return ""
513 corpus_document = has_private_corpus(markdown)
514 markdown = _strip_private_corpus_blocks(markdown)
515 markdown = _strip_unmarked_drills(markdown)
516 markdown = _strip_from_your_files_sections(markdown)
517 if corpus_document:
518 # The old renderer could keep a drill's local-derived cluster title
519 # after dedupe left only public representatives.
520 markdown = _rewrite_ranked_clusters_sections(markdown)
521 if markdown.startswith("# Production Brief: "):
522 markdown = _rewrite_brief_clusters_sections(markdown)
523 # Old rendered rows do not identify the claim's source, so a row
524 # with a public evidence link can still represent a private claim.
525 markdown = _strip_unmarked_freshness_sections(markdown)
526 return _PRIVATE_FRESHNESS_ROW.sub("", markdown)
527
528
529 @dataclass(frozen=True, slots=True)
530 class LibraryEntry:
531 """Metadata and source content for one saved research artifact."""
532
533 slug: str
534 topic: str
535 published_date: date
536 headline: str
537 summary: str
538 source_path: Path
539 content: str
540 source_updated_at: datetime
541 source_format: str = "markdown"
542 source_mtime_ns: int | None = None
543 source_size: int | None = None
544
545 @property
546 def entry_id(self) -> str:
547 return f"urn:last30days:{self.slug}:{self.identity_hash}:{self.published_date.isoformat()}"
548
549 @property
550 def output_name(self) -> str:
551 return f"{filename_slug(self.slug)}-{self.identity_hash}-{self.published_date.isoformat()}.html"
552
553 @property
554 def identity_hash(self) -> str:
555 # Include the source filename stem so per-suffix runs of the same
556 # topic on the same date (--save-suffix per-client workflow) stay
557 # distinct entries instead of collapsing to one.
558 seed = f"{self.topic}\n{self.source_path.stem}"
559 return hashlib.sha256(seed.encode("utf-8")).hexdigest()[:8]
560
561
562 def slugify(value: str) -> str:
563 slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
564 return slug or "last30days"
565
566
567 def filename_slug(slug: str, max_length: int = 180) -> str:
568 """Shorten a slug for use in a filename.
569
570 Filenames built from long topics can exceed the OS 255-byte limit
571 (macOS errno 63). Truncate and append a hash of the full slug so distinct
572 long topics still get distinct, deterministic names.
573 """
574 if len(slug) <= max_length:
575 return slug
576 digest = hashlib.sha1(slug.encode("utf-8")).hexdigest()[:10]
577 return f"{slug[:max_length].rstrip('-')}-{digest}"
578
579
580 @contextmanager
581 def _open_dir_fd(
582 target: Path | str,
583 *,
584 dir_fd: int | None = None,
585 nofollow: bool = False,
586 ):
587 """Open a directory descriptor pinned against concurrent directory swaps on POSIX."""
588 flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_CLOEXEC", 0)
589 if nofollow:
590 flags |= getattr(os, "O_NOFOLLOW", 0)
591 fd = os.open(target, flags, dir_fd=dir_fd) if dir_fd is not None else os.open(target, flags)
592 try:
593 yield fd
594 finally:
595 os.close(fd)
596
597
598 def _listdir_pinned(dir_fd: int, dir_path: Path) -> list[str]:
599 if _SUPPORTS_LISTDIR_FD:
600 return sorted(os.listdir(dir_fd))
601 return sorted(os.listdir(dir_path))
602
603
604 def _norm_parts(path: Path) -> tuple[str, ...]:
605 if sys.platform == "darwin":
606 return tuple(part.casefold() for part in path.parts)
607 if sys.platform == "win32":
608 return tuple(os.path.normcase(part) for part in path.parts)
609 return path.parts
610
611
612 def _same_normalized_path(left: Path, right: Path) -> bool:
613 return _norm_parts(left) == _norm_parts(right)
614
615
616 def _path_is_within(child: Path, parent: Path) -> bool:
617 c_parts = _norm_parts(child)
618 p_parts = _norm_parts(parent)
619 return bool(p_parts) and len(c_parts) >= len(p_parts) and c_parts[:len(p_parts)] == p_parts
620
621
622 def _win32_fd_real_path(fd: int) -> Path | None:
623 """Canonical path of an open Windows descriptor via ``GetFinalPathNameByHandleW``."""
624 try:
625 import ctypes
626 import msvcrt
627
628 handle = msvcrt.get_osfhandle(fd)
629 kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
630 get_path = kernel32.GetFinalPathNameByHandleW
631 get_path.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint32, ctypes.c_uint32]
632 get_path.restype = ctypes.c_uint32
633 needed = get_path(handle, None, 0, 0)
634 if not needed:
635 return None
636 buf = ctypes.create_unicode_buffer(needed + 1)
637 written = get_path(handle, buf, len(buf), 0)
638 if not written or written >= len(buf):
639 return None
640 raw = buf.value
641 except (AttributeError, ImportError, OSError, ValueError):
642 return None
643 if raw.startswith("\\\\?\\UNC\\"):
644 raw = "\\\\" + raw[8:]
645 elif raw.startswith("\\\\?\\"):
646 raw = raw[4:]
647 return Path(raw) if raw else None
648
649
650 def _fd_real_path(fd: int) -> Path | None:
651 """Canonical kernel path of an open descriptor (Windows, macOS, Linux)."""
652 if sys.platform == "win32":
653 return _win32_fd_real_path(fd)
654 target: str | None = None
655 if sys.platform == "darwin" and fcntl is not None:
656 f_getpath = getattr(fcntl, "F_GETPATH", _DARWIN_F_GETPATH)
657 try:
658 raw = fcntl.fcntl(fd, f_getpath, b"\x00" * _DARWIN_MAXPATHLEN)
659 except (OSError, ValueError):
660 return None
661 if isinstance(raw, (bytes, bytearray)):
662 target = os.fsdecode(bytes(raw).split(b"\x00", 1)[0])
663 elif isinstance(raw, str):
664 target = raw.split("\x00", 1)[0]
665 else:
666 try:
667 target = os.readlink(f"/proc/self/fd/{fd}")
668 except OSError:
669 return None
670 if not target or not target.startswith("/"):
671 return None
672 return Path(target)
673
674
675 def _checked_subdir_stat(subdir: Path, root: Path) -> os.stat_result | None:
676 """Return ``lstat`` for ``subdir`` when it is a non-symlink directory inside ``root``."""
677 if _IS_JUNCTION is not None and _IS_JUNCTION(subdir):
678 return None
679 try:
680 st = subdir.lstat()
681 except OSError:
682 return None
683 if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
684 return None
685 try:
686 root_resolved = root.resolve(strict=True)
687 subdir_resolved = subdir.resolve(strict=True)
688 except (OSError, RuntimeError):
689 return None
690 if not _path_is_within(subdir_resolved, root_resolved):
691 return None
692 return st
693
694
695 def _is_safe_subdir(subdir: Path, root: Path) -> bool:
696 """Return True when ``subdir`` is a non-symlink directory contained inside ``root``."""
697 return _checked_subdir_stat(subdir, root) is not None
698
699
700 def _verify_checked_parent(
701 path: Path,
702 *,
703 root_resolved: Path,
704 expected_parent_dir: Path | None = None,
705 expected_parent_id: tuple[int, int] | None = None,
706 ) -> None:
707 """Verify intermediate directories and parent directory identity have not changed."""
708 target_parent = expected_parent_dir if expected_parent_dir is not None else path.parent
709 if expected_parent_dir is not None and not _same_normalized_path(path.parent, expected_parent_dir):
710 raise OSError(f"File parent does not match checked directory: {path}")
711
712 rel_parts: tuple[str, ...] | None = None
713 try:
714 rel_parts = target_parent.relative_to(root_resolved).parts
715 except ValueError:
716 if expected_parent_dir is not None:
717 raise OSError(f"Directory escapes library root: {target_parent}") from None
718
719 if rel_parts is not None:
720 cur = root_resolved
721 for part in rel_parts:
722 if part in ("", ".", ".."):
723 raise OSError(f"Invalid directory component in {target_parent}")
724 cur = cur / part
725 if _IS_JUNCTION is not None and _IS_JUNCTION(cur):
726 raise OSError(errno.ELOOP, f"Refusing to follow junction directory: {cur}")
727 cur_st = cur.lstat()
728 if stat.S_ISLNK(cur_st.st_mode):
729 raise OSError(errno.ELOOP, f"Refusing to follow symlink directory: {cur}")
730 if not stat.S_ISDIR(cur_st.st_mode):
731 raise OSError(f"Not a directory: {cur}")
732
733 if _IS_JUNCTION is not None and _IS_JUNCTION(target_parent):
734 raise OSError(errno.ELOOP, f"Refusing to follow junction directory: {target_parent}")
735 parent_st = target_parent.lstat()
736 if stat.S_ISLNK(parent_st.st_mode):
737 raise OSError(errno.ELOOP, f"Refusing to follow symlink directory: {target_parent}")
738 if not stat.S_ISDIR(parent_st.st_mode):
739 raise OSError(f"Not a directory: {target_parent}")
740 if (
741 expected_parent_id is not None
742 and (os.name == "posix" or (expected_parent_id[1] and parent_st.st_ino))
743 and (parent_st.st_dev, parent_st.st_ino) != expected_parent_id
744 ):
745 raise OSError(f"Directory changed during scan: {target_parent}")
746
747
748 def _read_regular_text(
749 path: Path,
750 *,
751 root: Path | None = None,
752 max_bytes: int | None = None,
753 dir_fd: int | None = None,
754 expected_parent_dir: Path | None = None,
755 expected_parent_id: tuple[int, int] | None = None,
756 ) -> tuple[str, os.stat_result]:
757 """Read UTF-8 text from a regular, non-symlink file within ``root`` and size cap."""
758 limit = MAX_LIBRARY_FILE_BYTES if max_bytes is None else max_bytes
759 root_resolved: Path | None = None
760 if dir_fd is not None:
761 entry_name = path.name
762 if not entry_name or entry_name in (".", "..") or "/" in entry_name or "\\" in entry_name:
763 raise OSError(f"Invalid library entry name: {path}")
764 lstat_res = os.lstat(entry_name, dir_fd=dir_fd)
765 else:
766 if root is not None:
767 root_resolved = root.resolve(strict=True)
768 _verify_checked_parent(
769 path,
770 root_resolved=root_resolved,
771 expected_parent_dir=expected_parent_dir,
772 expected_parent_id=expected_parent_id,
773 )
774 if _IS_JUNCTION is not None and _IS_JUNCTION(path):
775 raise OSError(errno.ELOOP, f"Refusing to follow junction: {path}")
776 lstat_res = path.lstat()
777 if stat.S_ISLNK(lstat_res.st_mode):
778 raise OSError(errno.ELOOP, f"Refusing to follow symlink: {path}")
779 if not stat.S_ISREG(lstat_res.st_mode):
780 raise OSError(f"Not a regular file: {path}")
781 if dir_fd is None and root_resolved is not None:
782 resolved_path = path.resolve(strict=True)
783 if not _path_is_within(resolved_path, root_resolved):
784 raise OSError(f"Path escapes library root: {path}")
785 if expected_parent_dir is not None and not _same_normalized_path(
786 resolved_path.parent, expected_parent_dir
787 ):
788 raise OSError(f"Path escapes checked directory: {path}")
789 flags = os.O_RDONLY
790 for attr in ("O_NOFOLLOW", "O_NONBLOCK", "O_CLOEXEC", "O_BINARY"):
791 flags |= getattr(os, attr, 0)
792 try:
793 if dir_fd is not None:
794 fd = os.open(entry_name, flags, dir_fd=dir_fd)
795 else:
796 fd = os.open(path, flags)
797 except OSError as exc:
798 if exc.errno == errno.ELOOP:
799 raise OSError(errno.ELOOP, f"Refusing to follow symlink: {path}") from exc
800 raise
801 try:
802 st = os.fstat(fd)
803 if not stat.S_ISREG(st.st_mode):
804 raise OSError(f"Not a regular file: {path}")
805 if (os.name == "posix" or (lstat_res.st_ino and st.st_ino)) and (
806 st.st_dev,
807 st.st_ino,
808 ) != (lstat_res.st_dev, lstat_res.st_ino):
809 raise OSError(f"File changed during open: {path}")
810 if dir_fd is None and root_resolved is not None:
811 _verify_checked_parent(
812 path,
813 root_resolved=root_resolved,
814 expected_parent_dir=expected_parent_dir,
815 expected_parent_id=expected_parent_id,
816 )
817 fd_path = _fd_real_path(fd)
818 if fd_path is None:
819 raise OSError(f"Unable to verify opened file location: {path}")
820 if not _path_is_within(fd_path, root_resolved):
821 raise OSError(f"Opened file escapes library root: {path}")
822 if expected_parent_dir is not None and not _same_normalized_path(
823 fd_path, expected_parent_dir / path.name
824 ):
825 raise OSError(f"Opened file escapes checked directory: {path}")
826 if st.st_size > limit:
827 raise ValueError(f"file exceeds {limit} byte limit")
828 chunks: list[bytes] = []
829 remaining = limit + 1
830 while remaining > 0:
831 chunk = os.read(fd, min(65536, remaining))
832 if not chunk:
833 break
834 chunks.append(chunk)
835 remaining -= len(chunk)
836 raw = b"".join(chunks)
837 if len(raw) > limit:
838 raise ValueError(f"file exceeds {limit} byte limit")
839 finally:
840 os.close(fd)
841 text = raw.decode("utf-8").replace("\r\n", "\n").replace("\r", "\n")
842 return text, st
843
844
845 def get_or_create_library_id(memory_dir: Path | str) -> str:
846 """Return the persisted random namespace for one research library."""
847 memory_path = Path(memory_dir).expanduser()
848 memory_path.mkdir(parents=True, exist_ok=True)
849 resolved_memory = memory_path.resolve(strict=True)
850 id_path = resolved_memory / LIBRARY_ID_FILENAME
851 if _SUPPORTS_DIR_FD:
852 with _open_dir_fd(resolved_memory) as memory_fd:
853 try:
854 raw_id, _ = _read_regular_text(id_path, max_bytes=1024, dir_fd=memory_fd)
855 library_id = raw_id.strip()
856 except FileNotFoundError:
857 library_id = uuid.uuid4().hex
858 flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
859 for attr in ("O_NOFOLLOW", "O_CLOEXEC"):
860 flags |= getattr(os, attr, 0)
861 try:
862 fd = os.open(LIBRARY_ID_FILENAME, flags, 0o600, dir_fd=memory_fd)
863 except FileExistsError:
864 raw_id, _ = _read_regular_text(id_path, max_bytes=1024, dir_fd=memory_fd)
865 library_id = raw_id.strip()
866 else:
867 try:
868 stream = os.fdopen(fd, "w", encoding="utf-8")
869 except BaseException:
870 os.close(fd)
871 raise
872 with stream:
873 stream.write(f"{library_id}\n")
874 else:
875 memory_stat = _checked_subdir_stat(resolved_memory, resolved_memory)
876 memory_id = (memory_stat.st_dev, memory_stat.st_ino) if memory_stat is not None else None
877 try:
878 raw_id, _ = _read_regular_text(
879 id_path,
880 root=resolved_memory,
881 max_bytes=1024,
882 expected_parent_dir=resolved_memory,
883 expected_parent_id=memory_id,
884 )
885 library_id = raw_id.strip()
886 except FileNotFoundError:
887 library_id = uuid.uuid4().hex
888 flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY
889 for attr in ("O_NOFOLLOW", "O_CLOEXEC"):
890 flags |= getattr(os, attr, 0)
891 try:
892 fd = os.open(id_path, flags, 0o600)
893 except FileExistsError:
894 raw_id, _ = _read_regular_text(
895 id_path,
896 root=resolved_memory,
897 max_bytes=1024,
898 expected_parent_dir=resolved_memory,
899 expected_parent_id=memory_id,
900 )
901 library_id = raw_id.strip()
902 else:
903 try:
904 stream = os.fdopen(fd, "w", encoding="utf-8")
905 except BaseException:
906 os.close(fd)
907 raise
908 with stream:
909 stream.write(f"{library_id}\n")
910 if not _LIBRARY_ID.fullmatch(library_id):
911 raise ValueError(f"invalid library ID in {id_path}")
912 return library_id
913
914
915 def is_generated_brief_name(name: str) -> bool:
916 """Return whether a filename has the exact library-renderer output shape."""
917 return _GENERATED_BRIEF_NAME.fullmatch(name) is not None
918
919
920 def _resolve_scan_root(raw_path: Path, notes: list[str]) -> Path | None:
921 """Strictly resolve an existing scan root without collapsing missing ``..`` segments."""
922 try:
923 return raw_path.resolve(strict=True)
924 except (FileNotFoundError, NotADirectoryError):
925 return None
926 except (OSError, RuntimeError) as exc:
927 if isinstance(exc, OSError) and exc.errno in (errno.ENOENT, errno.ENOTDIR):
928 return None
929 notes.append(f"Skipped {raw_path}: {exc}")
930 return None
931
932
933 def scan_library(
934 memory_dir: Path | str = DEFAULT_MEMORY_DIR,
935 briefs_dir: Path | str = DEFAULT_BRIEFS_DIR,
936 ) -> tuple[list[LibraryEntry], list[str]]:
937 """Return valid saved entries and notes for files that could not be read.
938
939 Hand-edited and foreign files are tolerated: a generic Markdown heading is
940 enough to include a file, while unreadable or unrecognizable files are
941 skipped with a note instead of aborting the entire feed generation.
942 """
943 entries: dict[str, LibraryEntry] = {}
944 notes: list[str] = []
945 memory_path = _resolve_scan_root(Path(memory_dir).expanduser(), notes)
946 briefs_path = _resolve_scan_root(Path(briefs_dir).expanduser(), notes)
947
948 if _SUPPORTS_DIR_FD:
949 if memory_path is not None:
950 try:
951 with _open_dir_fd(memory_path) as memory_fd:
952 finished_path = memory_path / FINISHED_SUBDIR
953 try:
954 with _open_dir_fd(
955 FINISHED_SUBDIR, dir_fd=memory_fd, nofollow=True
956 ) as finished_fd:
957 for name in _listdir_pinned(finished_fd, finished_path):
958 if not name.endswith(".md"):
959 continue
960 path = finished_path / name
961 try:
962 entry = parse_markdown_file(
963 path,
964 source_format="finished-brief",
965 dir_fd=finished_fd,
966 )
967 _keep_preferred(entries, entry)
968 except (OSError, UnicodeError, ValueError) as exc:
969 notes.append(f"Skipped {path}: {exc}")
970 continue
971 except FileNotFoundError:
972 pass
973 except OSError as exc:
974 if exc.errno == errno.ELOOP:
975 notes.append(f"Skipped {finished_path}: refusing to follow symlink directory")
976 elif exc.errno == errno.ENOTDIR:
977 try:
978 if stat.S_ISLNK(os.lstat(FINISHED_SUBDIR, dir_fd=memory_fd).st_mode):
979 notes.append(
980 f"Skipped {finished_path}: refusing to follow symlink directory"
981 )
982 except OSError:
983 pass
984 else:
985 notes.append(f"Skipped {finished_path}: {exc}")
986
987 for name in _listdir_pinned(memory_fd, memory_path):
988 if not name.endswith(".md"):
989 continue
990 path = memory_path / name
991 try:
992 entry = parse_markdown_file(
993 path,
994 source_format="markdown",
995 dir_fd=memory_fd,
996 )
997 _keep_preferred(entries, entry)
998 except (OSError, UnicodeError, ValueError) as exc:
999 notes.append(f"Skipped {path}: {exc}")
1000 continue
1001 except (FileNotFoundError, NotADirectoryError):
1002 pass
1003 except OSError as exc:
1004 if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
1005 notes.append(f"Skipped {memory_path}: {exc}")
1006
1007 if briefs_path is not None:
1008 try:
1009 with _open_dir_fd(briefs_path) as briefs_fd:
1010 for name in _listdir_pinned(briefs_fd, briefs_path):
1011 if not name.endswith(".json"):
1012 continue
1013 path = briefs_path / name
1014 try:
1015 entry = _parse_briefing(path, dir_fd=briefs_fd)
1016 _keep_preferred(entries, entry)
1017 except (OSError, UnicodeError, ValueError, json.JSONDecodeError) as exc:
1018 notes.append(f"Skipped {path}: {exc}")
1019 continue
1020 except (FileNotFoundError, NotADirectoryError):
1021 pass
1022 except OSError as exc:
1023 if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
1024 notes.append(f"Skipped {briefs_path}: {exc}")
1025 else:
1026 if memory_path is not None:
1027 memory_stat = _checked_subdir_stat(memory_path, memory_path)
1028 if memory_stat is not None:
1029 memory_id = (memory_stat.st_dev, memory_stat.st_ino)
1030 finished_path = memory_path / FINISHED_SUBDIR
1031 finished_stat = _checked_subdir_stat(finished_path, memory_path)
1032 if finished_stat is not None:
1033 finished_id = (finished_stat.st_dev, finished_stat.st_ino)
1034 for path in sorted(finished_path.glob("*.md")):
1035 try:
1036 entry = parse_markdown_file(
1037 path,
1038 source_format="finished-brief",
1039 root=memory_path,
1040 expected_parent_dir=finished_path,
1041 expected_parent_id=finished_id,
1042 )
1043 _keep_preferred(entries, entry)
1044 except (OSError, UnicodeError, ValueError) as exc:
1045 notes.append(f"Skipped {path}: {exc}")
1046 continue
1047 elif finished_path.is_symlink() or (
1048 _IS_JUNCTION is not None and _IS_JUNCTION(finished_path)
1049 ):
1050 notes.append(f"Skipped {finished_path}: refusing to follow symlink directory")
1051
1052 for path in sorted(memory_path.glob("*.md")):
1053 try:
1054 entry = parse_markdown_file(
1055 path,
1056 source_format="markdown",
1057 root=memory_path,
1058 expected_parent_dir=memory_path,
1059 expected_parent_id=memory_id,
1060 )
1061 _keep_preferred(entries, entry)
1062 except (OSError, UnicodeError, ValueError) as exc:
1063 notes.append(f"Skipped {path}: {exc}")
1064 continue
1065
1066 if briefs_path is not None:
1067 briefs_stat = _checked_subdir_stat(briefs_path, briefs_path)
1068 if briefs_stat is not None:
1069 briefs_id = (briefs_stat.st_dev, briefs_stat.st_ino)
1070 for path in sorted(briefs_path.glob("*.json")):
1071 try:
1072 entry = _parse_briefing(
1073 path,
1074 root=briefs_path,
1075 expected_parent_dir=briefs_path,
1076 expected_parent_id=briefs_id,
1077 )
1078 _keep_preferred(entries, entry)
1079 except (OSError, UnicodeError, ValueError, json.JSONDecodeError) as exc:
1080 notes.append(f"Skipped {path}: {exc}")
1081 continue
1082
1083 filtered = _suppress_superseded_raw(entries)
1084 ordered = sorted(
1085 filtered.values(),
1086 key=lambda entry: (entry.published_date, entry.topic.casefold(), entry.source_path.name),
1087 reverse=True,
1088 )
1089 return ordered, notes
1090
1091
1092 def _suppress_superseded_raw(entries: dict[str, LibraryEntry]) -> dict[str, LibraryEntry]:
1093 """Hide unsuffixed raw dumps when a public finished brief covers the same topic and date."""
1094 # Require agreement on the parsed topic as well as the slug and date.
1095 # Distinct topics such as C# and C++ can share a slug.
1096 finished_keys = {
1097 (entry.slug, entry.topic.casefold(), entry.published_date)
1098 for entry in entries.values()
1099 if entry.source_format == "finished-brief"
1100 and not is_unbounded_private_brief(entry.content)
1101 }
1102 if not finished_keys:
1103 return entries
1104 kept: dict[str, LibraryEntry] = {}
1105 for entry_id, entry in entries.items():
1106 if (
1107 entry.source_format == "markdown"
1108 and (entry.slug, entry.topic.casefold(), entry.published_date) in finished_keys
1109 and _is_unsuffixed_raw_dump(entry.source_path.stem)
1110 ):
1111 continue
1112 kept[entry_id] = entry
1113 return kept
1114
1115
1116 def _is_unsuffixed_raw_dump(stem: str) -> bool:
1117 return _UNSUFFIXED_RAW_STEM.fullmatch(stem) is not None
1118
1119
1120 def _keep_preferred(entries: dict[str, LibraryEntry], entry: LibraryEntry) -> None:
1121 existing = entries.get(entry.entry_id)
1122 if existing is None:
1123 entries[entry.entry_id] = entry
1124 return
1125 if entry.source_mtime_ns is not None and existing.source_mtime_ns is not None:
1126 newer = entry.source_mtime_ns > existing.source_mtime_ns
1127 else:
1128 newer = entry.source_updated_at > existing.source_updated_at
1129 if newer:
1130 entries[entry.entry_id] = entry
1131
1132
1133 def parse_markdown_file(
1134 path: Path,
1135 *,
1136 source_format: str = "markdown",
1137 root: Path | None = None,
1138 dir_fd: int | None = None,
1139 expected_parent_dir: Path | None = None,
1140 expected_parent_id: tuple[int, int] | None = None,
1141 ) -> LibraryEntry:
1142 """Parse one saved Markdown report or finished brief into a LibraryEntry."""
1143 content, st = _read_regular_text(
1144 path,
1145 root=root,
1146 dir_fd=dir_fd,
1147 expected_parent_dir=expected_parent_dir,
1148 expected_parent_id=expected_parent_id,
1149 )
1150 unbounded_private = is_unbounded_private_brief(content, source_format=source_format)
1151 parse_source = content if unbounded_private else public_markdown(content)
1152 meta_topic_match = _TOPIC_META_COMMENT.search(content)
1153 badge_topic, badge_date = _parse_badge_line(parse_source)
1154 report_title_match = _REPORT_TITLE.search(parse_source)
1155 first_title_match = _FIRST_TITLE.search(parse_source)
1156
1157 if meta_topic_match:
1158 topic = _clean_inline(meta_topic_match.group(1))
1159 elif source_format == "finished-brief" and badge_topic:
1160 # Preserve the badge topic so comparison display headings like
1161 # "# Codex vs Cursor: What the Community Says (/Last30Days)" do not
1162 # diverge from the raw report's topic and slug.
1163 topic = _clean_inline(badge_topic)
1164 elif report_title_match:
1165 topic = _clean_inline(report_title_match.group(1))
1166 elif badge_topic:
1167 topic = _clean_inline(badge_topic)
1168 elif first_title_match:
1169 raw_heading = _COMPARISON_TITLE_SUFFIX.sub("", first_title_match.group(1))
1170 topic = _clean_inline(raw_heading)
1171 else:
1172 raise ValueError("no Markdown title found")
1173 if not topic:
1174 raise ValueError("empty Markdown title")
1175 published_date = badge_date or _markdown_date(parse_source, path, st=st)
1176 if unbounded_private:
1177 headline = topic
1178 summary = "Private local-corpus brief (stored locally only)."
1179 else:
1180 headline = _markdown_headline(parse_source) or _brief_prose_headline(parse_source) or topic
1181 summary = _markdown_summary(parse_source) or _brief_prose_summary(parse_source) or headline
1182 return LibraryEntry(
1183 slug=slugify(topic),
1184 topic=topic,
1185 published_date=published_date,
1186 headline=headline,
1187 summary=summary,
1188 source_path=path,
1189 content=content,
1190 source_updated_at=_source_updated_at(path, st=st),
1191 source_format=source_format,
1192 source_mtime_ns=st.st_mtime_ns,
1193 source_size=st.st_size,
1194 )
1195
1196
1197 def _parse_markdown(path: Path) -> LibraryEntry:
1198 return parse_markdown_file(path, source_format="markdown")
1199
1200
1201 def _parse_badge_line(content: str) -> tuple[str, date | None]:
1202 match = _BADGE_LINE.search(content)
1203 if match is None:
1204 return "", None
1205 line = match.group(0).strip()
1206 parts = [part.strip() for part in line.split("·") if part.strip()]
1207 topic = ""
1208 published: date | None = None
1209 if synced := _BADGE_SYNCED_DATE.search(line):
1210 try:
1211 published = date.fromisoformat(synced.group(1))
1212 except ValueError:
1213 published = None
1214 else:
1215 for segment in parts[1:]:
1216 if published is None:
1217 parsed = _parse_badge_date(segment)
1218 if parsed is not None:
1219 published = parsed
1220 continue
1221 if not topic and not _BADGE_VERSION.fullmatch(segment) and segment.lower() not in {"quick", "default", "deep", "cached"}:
1222 topic = segment
1223 return topic, published
1224
1225
1226 def _parse_badge_date(text: str) -> date | None:
1227 month_matches = list(_BADGE_MONTH_DAY_YEAR.finditer(text))
1228 if month_matches:
1229 m = month_matches[-1]
1230 month_num = _BADGE_MONTHS.get(m.group(1).lower()[:4]) or _BADGE_MONTHS.get(m.group(1).lower()[:3])
1231 if month_num:
1232 try:
1233 return date(int(m.group(3)), month_num, int(m.group(2)))
1234 except ValueError:
1235 pass
1236 iso_matches = list(_BADGE_ISO_DATE.finditer(text))
1237 if iso_matches:
1238 try:
1239 return date.fromisoformat(iso_matches[-1].group(1))
1240 except ValueError:
1241 pass
1242 return None
1243
1244
1245 def _brief_prose_paragraph(content: str) -> str:
1246 in_fence = False
1247 para: list[str] = []
1248 for raw_line in content.splitlines():
1249 stripped = raw_line.strip()
1250 if stripped.startswith("```"):
1251 in_fence = not in_fence
1252 if para:
1253 break
1254 continue
1255 if in_fence:
1256 continue
1257 if not stripped:
1258 if para:
1259 break
1260 continue
1261 if (
1262 stripped.startswith("🌐 last30days")
1263 or stripped.startswith("<!--")
1264 or stripped.startswith("#")
1265 or stripped.startswith("---")
1266 or stripped.startswith("|")
1267 or _PROSE_LABEL_LINE.fullmatch(stripped) is not None
1268 ):
1269 if para:
1270 break
1271 continue
1272 para.append(stripped.rstrip("\\"))
1273 return _clean_inline(" ".join(para))
1274
1275
1276 def _brief_prose_headline(content: str) -> str:
1277 text = _brief_prose_paragraph(content)
1278 if not text:
1279 return ""
1280 sentence = re.split(r"(?<=[.!?])\s+", text, maxsplit=1)[0]
1281 return sentence[:140]
1282
1283
1284 def _brief_prose_summary(content: str) -> str:
1285 text = _brief_prose_paragraph(content)
1286 return text[:500] if text else ""
1287
1288
1289 def _markdown_date(content: str, path: Path, *, st: os.stat_result | None = None) -> date:
1290 if match := _DATE_RANGE.search(content):
1291 return date.fromisoformat(match.group(1))
1292 if match := _DATED_FILENAME.search(path.stem):
1293 return date.fromisoformat(match.group(1))
1294 stat_res = st if st is not None else path.stat()
1295 return datetime.fromtimestamp(stat_res.st_mtime).date()
1296
1297
1298 def _markdown_headline(content: str) -> str:
1299 if match := _RANKED_HEADLINE.search(content):
1300 return _clean_inline(_SCORE_SUFFIX.sub("", match.group(1)))
1301 return ""
1302
1303
1304 def _markdown_summary(content: str) -> str:
1305 learned = re.search(
1306 r"^(?:##\s+What I learned|(?:\*\*|__)?What I learned:?(?:\*\*|__)?)\s*$\n+(.+?)(?=\n#{1,3}\s|\n---|\n```|\Z)",
1307 content,
1308 re.MULTILINE | re.DOTALL | re.IGNORECASE,
1309 )
1310 if learned:
1311 for paragraph in re.split(r"\n\s*\n", learned.group(1)):
1312 cleaned = _clean_inline(paragraph)
1313 if cleaned and _PROSE_LABEL_LINE.fullmatch(cleaned) is None:
1314 return cleaned[:500]
1315 evidence = re.search(r"^\s*-\s*Evidence:\s*(.+?)\s*$", content, re.MULTILINE | re.IGNORECASE)
1316 if evidence:
1317 return _clean_inline(evidence.group(1))[:500]
1318 return ""
1319
1320
1321 def _parse_briefing(
1322 path: Path,
1323 *,
1324 root: Path | None = None,
1325 dir_fd: int | None = None,
1326 expected_parent_dir: Path | None = None,
1327 expected_parent_id: tuple[int, int] | None = None,
1328 ) -> LibraryEntry:
1329 raw_text, st = _read_regular_text(
1330 path,
1331 root=root,
1332 dir_fd=dir_fd,
1333 expected_parent_dir=expected_parent_dir,
1334 expected_parent_id=expected_parent_id,
1335 )
1336 data = json.loads(raw_text)
1337 if not isinstance(data, dict):
1338 raise ValueError("briefing JSON is not an object")
1339 is_weekly = data.get("type") == "weekly" or path.stem.endswith("-weekly")
1340 raw_date = path.stem[:10] if is_weekly else data.get("date") or path.stem[:10]
1341 try:
1342 published_date = date.fromisoformat(str(raw_date))
1343 except ValueError as exc:
1344 raise ValueError("briefing has no valid date") from exc
1345 topic = "Weekly research briefing" if is_weekly else "Daily research briefing"
1346 top = data.get("top_finding") if isinstance(data.get("top_finding"), dict) else {}
1347 headline = _briefing_public_headline(data, topic)
1348 summary = _briefing_summary(data, headline)
1349 markdown = _briefing_markdown(data, topic, published_date, summary)
1350 local_title = str(top.get("title") or "")
1351 if local_title and local_title != headline:
1352 local_title = local_title.replace("LAST30DAYS_PRIVATE_CORPUS", "LAST30DAYS_PRIVATE-CORPUS")
1353 markdown += (
1354 "\n<!-- LAST30DAYS_PRIVATE_CORPUS_START -->\n"
1355 "## Local briefing highlight\n\n"
1356 f"{local_title}\n"
1357 "<!-- LAST30DAYS_PRIVATE_CORPUS_END -->\n"
1358 )
1359 return LibraryEntry(
1360 slug=slugify(topic),
1361 topic=topic,
1362 published_date=published_date,
1363 headline=headline,
1364 summary=summary,
1365 source_path=path,
1366 content=markdown,
1367 source_updated_at=_source_updated_at(path, st=st),
1368 source_format="json",
1369 source_mtime_ns=st.st_mtime_ns,
1370 source_size=st.st_size,
1371 )
1372
1373
1374 def _briefing_public_headline(data: dict[str, object], fallback: str) -> str:
1375 top = data.get("top_finding")
1376 candidates = [top] if isinstance(top, dict) else []
1377 # Legacy daily archives lack source on top_finding but retain it on findings.
1378 topics = data.get("topics")
1379 if isinstance(topics, list):
1380 for topic in topics:
1381 if not isinstance(topic, dict):
1382 continue
1383 for field in ("findings", "top_findings"):
1384 findings = topic.get(field)
1385 if isinstance(findings, list):
1386 candidates.extend(findings)
1387
1388 public_titles = []
1389 for finding in candidates:
1390 if not isinstance(finding, dict):
1391 continue
1392 source = str(finding.get("source") or "").strip().lower()
1393 url = str(finding.get("source_url") or "").strip().lower()
1394 if not source or source == "corpus" or url.startswith("corpus:"):
1395 continue
1396 title = finding.get("source_title") or finding.get("title")
1397 if title:
1398 engagement = finding.get("engagement_score", finding.get("engagement"))
1399 score = engagement if isinstance(engagement, (int, float)) else 0
1400 public_titles.append((score, str(title)))
1401 return max(public_titles, key=lambda item: item[0])[1] if public_titles else fallback
1402
1403
1404 def _source_updated_at(path: Path, *, st: os.stat_result | None = None) -> datetime:
1405 stat_res = st if st is not None else path.stat()
1406 seconds, nanoseconds = divmod(stat_res.st_mtime_ns, 1_000_000_000)
1407 return datetime.fromtimestamp(seconds, tz=timezone.utc).replace(
1408 microsecond=nanoseconds // 1_000
1409 )
1410
1411
1412 def _briefing_summary(data: dict[str, object], fallback: str) -> str:
1413 total_new = data.get("total_new")
1414 total_topics = data.get("total_topics")
1415 if total_new is not None and total_topics is not None:
1416 return f"{total_new} new findings across {total_topics} monitored topics. {fallback}"[:500]
1417 topics = data.get("topics")
1418 if isinstance(topics, list):
1419 return f"Updates across {len(topics)} monitored topics. {fallback}"[:500]
1420 return fallback[:500]
1421
1422
1423 def _briefing_markdown(data: dict[str, object], topic: str, published_date: date, summary: str) -> str:
1424 lines = [f"# {topic}", "", f"- Date: {published_date.isoformat()}", "", summary]
1425 if data.get("type") == "weekly" and data.get("week_of"):
1426 lines[3:3] = [f"- Week of: {data['week_of']}"]
1427 topics = data.get("topics")
1428 if isinstance(topics, list):
1429 lines.extend(["", "## Topics", ""])
1430 for item in topics:
1431 if not isinstance(item, dict):
1432 continue
1433 name = str(item.get("name") or "Untitled topic")
1434 count = item.get("new_count", item.get("this_week_count", 0))
1435 lines.append(f"- **{name}** — {count} new findings")
1436 return "\n".join(lines).strip() + "\n"
1437
1438
1439 def _clean_inline(value: str) -> str:
1440 value = _MARKDOWN_LINK.sub(r"\1", value)
1441 value = re.sub(r"^\s*>\s?", "", value)
1442 value = re.sub(r"(?<!\w)(\*\*|__)(?=\S)(.+?)(?<=\S)\1(?!\w)", r"\2", value)
1443 value = re.sub(r"(?<!\w)([*_])(?=\S)(.+?)(?<=\S)\1(?!\w)", r"\2", value)
1444 value = re.sub(r"(?<!\w)`(?=\S)(.+?)(?<=\S)`(?!\w)", r"\1", value)
1445 return re.sub(r"\s+", " ", value).strip()
1446
1447
1448 def _dir_matches_fd(dir_path: Path, dir_fd: int) -> bool:
1449 """Return True when ``dir_path`` still refers to the same non-symlink directory as ``dir_fd``."""
1450 try:
1451 path_st = dir_path.lstat()
1452 fd_st = os.fstat(dir_fd)
1453 except OSError:
1454 return False
1455 if stat.S_ISLNK(path_st.st_mode) or not stat.S_ISDIR(path_st.st_mode):
1456 return False
1457 return (path_st.st_dev, path_st.st_ino) == (fd_st.st_dev, fd_st.st_ino)
1458
1459
1460 def _collect_sync_inputs(
1461 memory_dir: Path | str = DEFAULT_MEMORY_DIR,
1462 briefs_dir: Path | str = DEFAULT_BRIEFS_DIR,
1463 ) -> tuple[list[dict[str, object]], list[LibraryEntry], list[str]]:
1464 """Collect validated Markdown file descriptors and direct/JSON entries without reading unswapped Markdown bodies."""
1465 md_requests: list[dict[str, object]] = []
1466 json_entries: list[LibraryEntry] = []
1467 notes: list[str] = []
1468 memory_path = _resolve_scan_root(Path(memory_dir).expanduser(), notes)
1469 briefs_path = _resolve_scan_root(Path(briefs_dir).expanduser(), notes)
1470
1471 def _enqueue_md(
1472 path: Path,
1473 source_format: str,
1474 *,
1475 dir_fd: int | None = None,
1476 root: Path | None = None,
1477 expected_parent_dir: Path | None = None,
1478 expected_parent_id: tuple[int, int] | None = None,
1479 ) -> None:
1480 try:
1481 if dir_fd is not None:
1482 entry_name = path.name
1483 if not entry_name or entry_name in (".", "..") or "/" in entry_name or "\\" in entry_name:
1484 raise OSError(f"Invalid library entry name: {path}")
1485 st = os.lstat(entry_name, dir_fd=dir_fd)
1486 else:
1487 if root is not None:
1488 _verify_checked_parent(
1489 path,
1490 root_resolved=root,
1491 expected_parent_dir=expected_parent_dir,
1492 expected_parent_id=expected_parent_id,
1493 )
1494 if _IS_JUNCTION is not None and _IS_JUNCTION(path):
1495 raise OSError(errno.ELOOP, f"Refusing to follow junction: {path}")
1496 st = path.lstat()
1497 if stat.S_ISLNK(st.st_mode):
1498 raise OSError(errno.ELOOP, f"Refusing to follow symlink: {path}")
1499 if not stat.S_ISREG(st.st_mode):
1500 raise OSError(f"Not a regular file: {path}")
1501 if st.st_size > MAX_LIBRARY_FILE_BYTES:
1502 raise ValueError(f"file exceeds {MAX_LIBRARY_FILE_BYTES} byte limit")
1503 md_requests.append(
1504 {
1505 "path": str(path),
1506 "stem": path.stem,
1507 "source_format": source_format,
1508 "expected_dev_ino": [int(st.st_dev), int(st.st_ino)] if os.name == "posix" else None,
1509 "fallback_date": datetime.fromtimestamp(st.st_mtime).date().isoformat(),
1510 "_mtime_ns": int(st.st_mtime_ns),
1511 "_size": int(st.st_size),
1512 "_root": root,
1513 "_expected_parent_dir": expected_parent_dir,
1514 "_expected_parent_id": expected_parent_id,
1515 }
1516 )
1517 except (OSError, ValueError) as exc:
1518 notes.append(f"Skipped {path}: {exc}")
1519
1520 if _SUPPORTS_DIR_FD:
1521 if memory_path is not None:
1522 try:
1523 with _open_dir_fd(memory_path) as memory_fd:
1524 memory_fd_st = os.fstat(memory_fd)
1525 memory_id = (memory_fd_st.st_dev, memory_fd_st.st_ino)
1526 finished_path = memory_path / FINISHED_SUBDIR
1527 try:
1528 with _open_dir_fd(
1529 FINISHED_SUBDIR, dir_fd=memory_fd, nofollow=True
1530 ) as finished_fd:
1531 finished_fd_st = os.fstat(finished_fd)
1532 finished_id = (finished_fd_st.st_dev, finished_fd_st.st_ino)
1533 names = _listdir_pinned(finished_fd, finished_path)
1534 finished_intact = _dir_matches_fd(finished_path, finished_fd)
1535 for name in names:
1536 if not name.endswith(".md"):
1537 continue
1538 if finished_intact:
1539 _enqueue_md(
1540 finished_path / name,
1541 "finished-brief",
1542 dir_fd=finished_fd,
1543 root=memory_path,
1544 expected_parent_dir=finished_path,
1545 expected_parent_id=finished_id,
1546 )
1547 else:
1548 path = finished_path / name
1549 try:
1550 json_entries.append(
1551 parse_markdown_file(
1552 path,
1553 source_format="finished-brief",
1554 dir_fd=finished_fd,
1555 )
1556 )
1557 except (OSError, UnicodeError, ValueError) as exc:
1558 notes.append(f"Skipped {path}: {exc}")
1559 except FileNotFoundError:
1560 pass
1561 except OSError as exc:
1562 if exc.errno == errno.ELOOP:
1563 notes.append(f"Skipped {finished_path}: refusing to follow symlink directory")
1564 elif exc.errno == errno.ENOTDIR:
1565 try:
1566 if stat.S_ISLNK(os.lstat(FINISHED_SUBDIR, dir_fd=memory_fd).st_mode):
1567 notes.append(
1568 f"Skipped {finished_path}: refusing to follow symlink directory"
1569 )
1570 except OSError:
1571 pass
1572 else:
1573 notes.append(f"Skipped {finished_path}: {exc}")
1574
1575 mem_names = _listdir_pinned(memory_fd, memory_path)
1576 mem_intact = _dir_matches_fd(memory_path, memory_fd)
1577 for name in mem_names:
1578 if not name.endswith(".md"):
1579 continue
1580 if mem_intact:
1581 _enqueue_md(
1582 memory_path / name,
1583 "markdown",
1584 dir_fd=memory_fd,
1585 root=memory_path,
1586 expected_parent_dir=memory_path,
1587 expected_parent_id=memory_id,
1588 )
1589 else:
1590 path = memory_path / name
1591 try:
1592 json_entries.append(
1593 parse_markdown_file(
1594 path,
1595 source_format="markdown",
1596 dir_fd=memory_fd,
1597 )
1598 )
1599 except (OSError, UnicodeError, ValueError) as exc:
1600 notes.append(f"Skipped {path}: {exc}")
1601 except (FileNotFoundError, NotADirectoryError):
1602 pass
1603 except OSError as exc:
1604 if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
1605 notes.append(f"Skipped {memory_path}: {exc}")
1606
1607 if briefs_path is not None:
1608 try:
1609 with _open_dir_fd(briefs_path) as briefs_fd:
1610 for name in _listdir_pinned(briefs_fd, briefs_path):
1611 if not name.endswith(".json"):
1612 continue
1613 path = briefs_path / name
1614 try:
1615 json_entries.append(_parse_briefing(path, dir_fd=briefs_fd))
1616 except (OSError, UnicodeError, ValueError, json.JSONDecodeError) as exc:
1617 notes.append(f"Skipped {path}: {exc}")
1618 except (FileNotFoundError, NotADirectoryError):
1619 pass
1620 except OSError as exc:
1621 if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
1622 notes.append(f"Skipped {briefs_path}: {exc}")
1623 else:
1624 if memory_path is not None:
1625 memory_stat = _checked_subdir_stat(memory_path, memory_path)
1626 if memory_stat is not None:
1627 memory_id = (memory_stat.st_dev, memory_stat.st_ino)
1628 finished_path = memory_path / FINISHED_SUBDIR
1629 finished_stat = _checked_subdir_stat(finished_path, memory_path)
1630 if finished_stat is not None:
1631 finished_id = (finished_stat.st_dev, finished_stat.st_ino)
1632 for path in sorted(finished_path.glob("*.md")):
1633 _enqueue_md(
1634 path,
1635 "finished-brief",
1636 root=memory_path,
1637 expected_parent_dir=finished_path,
1638 expected_parent_id=finished_id,
1639 )
1640 elif finished_path.is_symlink() or (
1641 _IS_JUNCTION is not None and _IS_JUNCTION(finished_path)
1642 ):
1643 notes.append(f"Skipped {finished_path}: refusing to follow symlink directory")
1644 for path in sorted(memory_path.glob("*.md")):
1645 _enqueue_md(
1646 path,
1647 "markdown",
1648 root=memory_path,
1649 expected_parent_dir=memory_path,
1650 expected_parent_id=memory_id,
1651 )
1652
1653 if briefs_path is not None:
1654 briefs_stat = _checked_subdir_stat(briefs_path, briefs_path)
1655 if briefs_stat is not None:
1656 briefs_id = (briefs_stat.st_dev, briefs_stat.st_ino)
1657 for path in sorted(briefs_path.glob("*.json")):
1658 try:
1659 json_entries.append(
1660 _parse_briefing(
1661 path,
1662 root=briefs_path,
1663 expected_parent_dir=briefs_path,
1664 expected_parent_id=briefs_id,
1665 )
1666 )
1667 except (OSError, UnicodeError, ValueError, json.JSONDecodeError) as exc:
1668 notes.append(f"Skipped {path}: {exc}")
1669
1670 return md_requests, json_entries, notes
1671
1672
1673 _ORIGINAL_SCAN_LIBRARY = scan_library
1674
1674 lines PYTHON