| 1 | //! Privacy redaction, context stripping, and parallel batch fingerprinting for |
| 2 | //! saved last30days Markdown reports. |
| 3 | //! |
| 4 | //! Mirrors the hot paths of `skills/last30days/scripts/lib/library.py` and |
| 5 | //! `skills/last30days/scripts/lib/library_index.py`. |
| 6 | |
| 7 | use std::fmt::Write as _; |
| 8 | use std::fs::File; |
| 9 | use std::io::Read as _; |
| 10 | use std::path::Path; |
| 11 | use std::sync::LazyLock; |
| 12 | |
| 13 | use rayon::prelude::*; |
| 14 | use regex::Regex; |
| 15 | use serde::{Deserialize, Serialize}; |
| 16 | use sha2::{Digest, Sha256}; |
| 17 | |
| 18 | use crate::error::CoreError; |
| 19 | |
| 20 | /// Marker preceding a public drill follow-up section. |
| 21 | pub const PUBLIC_DRILL_MARKER: &str = "<!-- LAST30DAYS_PUBLIC_DRILL -->"; |
| 22 | /// Marker preceding a public freshness verification table. |
| 23 | pub const PUBLIC_FRESHNESS_MARKER: &str = "<!-- LAST30DAYS_PUBLIC_FRESHNESS -->"; |
| 24 | /// Marker preceding a public ranked clusters section. |
| 25 | pub const PUBLIC_CLUSTERS_MARKER: &str = "<!-- LAST30DAYS_PUBLIC_CLUSTERS -->"; |
| 26 | /// Opening marker for an explicit private corpus block. |
| 27 | pub const PRIVATE_CORPUS_START: &str = "<!-- LAST30DAYS_PRIVATE_CORPUS_START -->"; |
| 28 | /// Closing marker for an explicit private corpus block. |
| 29 | pub const PRIVATE_CORPUS_END: &str = "<!-- LAST30DAYS_PRIVATE_CORPUS_END -->"; |
| 30 | /// Opening marker for inherited library context injected into saved reports. |
| 31 | pub const LIBRARY_CONTEXT_START: &str = "<!-- last30days:library-context:start -->"; |
| 32 | /// Closing marker for inherited library context injected into saved reports. |
| 33 | pub const LIBRARY_CONTEXT_END: &str = "<!-- last30days:library-context:end -->"; |
| 34 | /// Version prefix embedded in SHA-256 index fingerprints. |
| 35 | pub const INDEX_FINGERPRINT_VERSION: &str = "last30days-library-index/v3"; |
| 36 | |
| 37 | /// Output of sanitizing and fingerprinting one Markdown document in a batch. |
| 38 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 39 | pub struct SanitizedDocument { |
| 40 | /// Whether the document is an unbounded private brief (excluded from public index). |
| 41 | pub unbounded_private: bool, |
| 42 | /// Publicly shareable Markdown after redaction (empty when `unbounded_private` is `true`). |
| 43 | pub public_markdown: String, |
| 44 | /// SHA-256 fingerprint of the indexable (library-context-stripped) public content. |
| 45 | pub indexable_fingerprint: String, |
| 46 | } |
| 47 | |
| 48 | /// Input item for [`sanitize_markdown_batch`]. |
| 49 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 50 | pub struct MarkdownBatchItem { |
| 51 | /// Raw saved Markdown text. |
| 52 | pub content: String, |
| 53 | /// Optional source format (`"markdown"`, `"finished-brief"`, `"json"`). |
| 54 | pub source_format: Option<String>, |
| 55 | } |
| 56 | |
| 57 | /// Output item for [`sanitize_markdown_batch`]. |
| 58 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 59 | pub struct MarkdownBatchResult { |
| 60 | /// Whether `is_unbounded_private_brief` returned `true`. |
| 61 | pub unbounded_private: bool, |
| 62 | /// Publicly shareable Markdown (`public_markdown(content)`). |
| 63 | pub public_markdown: String, |
| 64 | /// SHA-256 fingerprint of `_indexable_content(content)`. |
| 65 | pub indexable_fingerprint: String, |
| 66 | } |
| 67 | |
| 68 | static REPORT_TITLE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 69 | Regex::new(r"(?im)^#\s+last30days(?:\s+v[^:]+)?:\s*(.+?)\s*$") |
| 70 | .expect("REPORT_TITLE_RE is a valid literal regex") |
| 71 | }); |
| 72 | |
| 73 | static BADGE_LINE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 74 | Regex::new(r"(?m)^🌐\s*last30days\b[^\r\n]*$").expect("BADGE_LINE_RE is a valid literal regex") |
| 75 | }); |
| 76 | |
| 77 | static CORPUS_FOOTER_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 78 | Regex::new(r"(?i)\bYour f[i\u{0130}\u{0131}]les\b") |
| 79 | .expect("CORPUS_FOOTER_RE is a valid literal regex") |
| 80 | }); |
| 81 | |
| 82 | static BOLD_FROM_YOUR_FILES_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 83 | Regex::new(r"(?im)^\s*(?:\*\*|__)?From your f[i\u{0130}\u{0131}]les:?(?:\*\*|__)?:?\s*$") |
| 84 | .expect("BOLD_FROM_YOUR_FILES_RE is a valid literal regex") |
| 85 | }); |
| 86 | |
| 87 | static PRIVATE_FRESHNESS_ROW_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 88 | Regex::new( |
| 89 | r"(?im)^\| \*\*contrad[i\u{0130}\u{0131}]cted\*\* \| [^\r\n]*(?:\]\(corpus://| \(Newer corpus [i\u{0130}\u{0131}]tem d[i\u{0130}\u{0131}]sagrees\))[^\r\n]*(?:\r?\n|$)", |
| 90 | ) |
| 91 | .expect("PRIVATE_FRESHNESS_ROW_RE is a valid literal regex") |
| 92 | }); |
| 93 | |
| 94 | static LEGACY_CORPUS_SIGNAL_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 95 | Regex::new( |
| 96 | r"(?im)^#{1,3}[ \t]+From your f[i\u{0130}\u{0131}]les:?[ \t]*\r?$|^- (?:Sources|Re-researched sources):[^\r\n]*\bYour f[i\u{0130}\u{0131}]les\b|^[0-9]+\. \[[^\]\r\n]*\b(?:corpus|your f[i\u{0130}\u{0131}]les)\b[^\]\r\n]*\]", |
| 97 | ) |
| 98 | .expect("LEGACY_CORPUS_SIGNAL_RE is a valid literal regex") |
| 99 | }); |
| 100 | |
| 101 | static FROM_YOUR_FILES_ANY_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 102 | Regex::new(r"(?i)from your f[i\u{0130}\u{0131}]les") |
| 103 | .expect("FROM_YOUR_FILES_ANY_RE is a valid literal regex") |
| 104 | }); |
| 105 | |
| 106 | static FROM_YOUR_FILES_H12_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 107 | Regex::new(r"(?i)^#{1,2}[ \t]+From your f[i\u{0130}\u{0131}]les:?[ \t]*$") |
| 108 | .expect("FROM_YOUR_FILES_H12_RE is a valid literal regex") |
| 109 | }); |
| 110 | |
| 111 | static FROM_YOUR_FILES_H3_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 112 | Regex::new(r"(?i)^###[ \t]+From your f[i\u{0130}\u{0131}]les:?[ \t]*$") |
| 113 | .expect("FROM_YOUR_FILES_H3_RE is a valid literal regex") |
| 114 | }); |
| 115 | |
| 116 | static FROM_YOUR_FILES_BOLD_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 117 | Regex::new(r"(?i)^[ \t]*(?:\*\*|__)From your f[i\u{0130}\u{0131}]les:?(?:\*\*|__)?:?[ \t]*$") |
| 118 | .expect("FROM_YOUR_FILES_BOLD_RE is a valid literal regex") |
| 119 | }); |
| 120 | |
| 121 | static RANKED_CLUSTER_HEADING_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 122 | Regex::new(r"^(?P<prefix>### [0-9]+\. )(?P<title>[^\r\n]*)$") |
| 123 | .expect("RANKED_CLUSTER_HEADING_RE is a valid literal regex") |
| 124 | }); |
| 125 | |
| 126 | static RANKED_CLUSTER_STATS_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 127 | Regex::new(r" \(score -?[0-9]+, [0-9]+ items?, sources: [^()\r\n]*\)$") |
| 128 | .expect("RANKED_CLUSTER_STATS_RE is a valid literal regex") |
| 129 | }); |
| 130 | |
| 131 | static RANKED_REPRESENTATIVE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 132 | Regex::new(r"^[0-9]+\. \[(?P<sources>[^\]\r\n]+)\] (?P<title>[^\r\n]+)$") |
| 133 | .expect("RANKED_REPRESENTATIVE_RE is a valid literal regex") |
| 134 | }); |
| 135 | |
| 136 | static RANKED_FRESHNESS_BADGE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 137 | Regex::new(r" \[freshness:[^\]]+\]$") |
| 138 | .expect("RANKED_FRESHNESS_BADGE_RE is a valid literal regex") |
| 139 | }); |
| 140 | |
| 141 | /// Returns `true` when `haystack` contains `"corpus://"` after Python-style lowercasing. |
| 142 | #[inline] |
| 143 | fn contains_corpus_scheme(haystack: &str) -> bool { |
| 144 | haystack.contains("://") && haystack.to_lowercase().contains("corpus://") |
| 145 | } |
| 146 | |
| 147 | /// Splits `text` into lines keeping their original line endings, matching |
| 148 | /// Python `str.splitlines(keepends=True)` across all 11 Unicode line breaks: |
| 149 | /// `\r\n`, `\n`, `\r`, `\x0b`, `\x0c`, `\x1c`, `\x1d`, `\x1e`, U+0085, |
| 150 | /// U+2028, and U+2029. |
| 151 | fn splitlines_keepends(text: &str) -> Vec<&str> { |
| 152 | if text.is_empty() { |
| 153 | return Vec::new(); |
| 154 | } |
| 155 | let bytes = text.as_bytes(); |
| 156 | let len = bytes.len(); |
| 157 | let mut lines = Vec::new(); |
| 158 | let mut start = 0; |
| 159 | let mut i = 0; |
| 160 | while i < len { |
| 161 | let b = bytes[i]; |
| 162 | let step = match b { |
| 163 | b'\r' => { |
| 164 | if i + 1 < len && bytes[i + 1] == b'\n' { |
| 165 | 2 |
| 166 | } else { |
| 167 | 1 |
| 168 | } |
| 169 | } |
| 170 | b'\n' | 0x0B | 0x0C | 0x1C | 0x1D | 0x1E => 1, |
| 171 | // U+0085 NEXT LINE (UTF-8: C2 85) |
| 172 | 0xC2 if i + 1 < len && bytes[i + 1] == 0x85 => 2, |
| 173 | // U+2028 LINE SEPARATOR (E2 80 A8) and U+2029 PARAGRAPH SEPARATOR (E2 80 A9) |
| 174 | 0xE2 if i + 2 < len |
| 175 | && bytes[i + 1] == 0x80 |
| 176 | && (bytes[i + 2] == 0xA8 || bytes[i + 2] == 0xA9) => |
| 177 | { |
| 178 | 3 |
| 179 | } |
| 180 | _ => 0, |
| 181 | }; |
| 182 | if step > 0 { |
| 183 | i += step; |
| 184 | lines.push(&text[start..i]); |
| 185 | start = i; |
| 186 | } else { |
| 187 | i += 1; |
| 188 | } |
| 189 | } |
| 190 | if start < len { |
| 191 | lines.push(&text[start..]); |
| 192 | } |
| 193 | lines |
| 194 | } |
| 195 | |
| 196 | #[inline] |
| 197 | fn trim_line_end(line: &str) -> &str { |
| 198 | line.trim_end_matches(['\r', '\n']) |
| 199 | } |
| 200 | |
| 201 | /// Tracks `CommonMark` backtick/tilde fenced code block state across lines without regex. |
| 202 | #[inline] |
| 203 | fn fence_step(line_text: &str, fence: Option<(u8, usize)>) -> Option<(u8, usize)> { |
| 204 | let bytes = line_text.as_bytes(); |
| 205 | let mut indent = 0; |
| 206 | while indent < 3 && indent < bytes.len() && bytes[indent] == b' ' { |
| 207 | indent += 1; |
| 208 | } |
| 209 | let rest = &bytes[indent..]; |
| 210 | match fence { |
| 211 | None => { |
| 212 | let first = *rest.first()?; |
| 213 | if first != b'`' && first != b'~' { |
| 214 | return None; |
| 215 | } |
| 216 | let count = rest.iter().take_while(|&&b| b == first).count(); |
| 217 | if count < 3 { |
| 218 | return None; |
| 219 | } |
| 220 | if first == b'`' && rest[count..].contains(&b'`') { |
| 221 | return None; |
| 222 | } |
| 223 | Some((first, count)) |
| 224 | } |
| 225 | Some((ch, min_len)) => { |
| 226 | let count = rest.iter().take_while(|&&b| b == ch).count(); |
| 227 | if count >= min_len && rest[count..].iter().all(|&b| b == b' ' || b == b'\t') { |
| 228 | None |
| 229 | } else { |
| 230 | Some((ch, min_len)) |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | #[inline] |
| 237 | fn is_top_level_heading(line_text: &str) -> bool { |
| 238 | let b = line_text.as_bytes(); |
| 239 | (b.len() >= 2 && b[0] == b'#' && (b[1] == b' ' || b[1] == b'\t')) |
| 240 | || (b.len() >= 3 && b[0] == b'#' && b[1] == b'#' && (b[2] == b' ' || b[2] == b'\t')) |
| 241 | } |
| 242 | |
| 243 | #[inline] |
| 244 | fn is_h1_to_h3_heading(line_text: &str) -> bool { |
| 245 | is_top_level_heading(line_text) || { |
| 246 | let b = line_text.as_bytes(); |
| 247 | b.len() >= 4 |
| 248 | && b[0] == b'#' |
| 249 | && b[1] == b'#' |
| 250 | && b[2] == b'#' |
| 251 | && (b[3] == b' ' || b[3] == b'\t') |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | #[inline] |
| 256 | fn is_drill_heading(line_text: &str) -> bool { |
| 257 | line_text |
| 258 | .strip_prefix("## Drill Follow-up") |
| 259 | .is_some_and(|rest| rest.bytes().all(|b| b == b' ' || b == b'\t')) |
| 260 | } |
| 261 | |
| 262 | #[inline] |
| 263 | fn is_drill_deeper_heading(line_text: &str) -> bool { |
| 264 | line_text |
| 265 | .strip_prefix("### Deeper") |
| 266 | .is_some_and(|rest| rest.bytes().all(|b| b == b' ' || b == b'\t')) |
| 267 | } |
| 268 | |
| 269 | #[inline] |
| 270 | fn is_drill_new_items(line_text: &str) -> bool { |
| 271 | line_text |
| 272 | .strip_prefix("- ") |
| 273 | .and_then(|s| s.strip_suffix(" new items after dedupe")) |
| 274 | .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())) |
| 275 | } |
| 276 | |
| 277 | #[inline] |
| 278 | fn is_drill_sources(line_text: &str) -> bool { |
| 279 | line_text.starts_with("- Re-researched sources:") |
| 280 | } |
| 281 | |
| 282 | #[inline] |
| 283 | fn is_from_your_files_h12(line_text: &str) -> bool { |
| 284 | FROM_YOUR_FILES_H12_RE.is_match(line_text) |
| 285 | } |
| 286 | |
| 287 | #[inline] |
| 288 | fn is_from_your_files_h3(line_text: &str) -> bool { |
| 289 | FROM_YOUR_FILES_H3_RE.is_match(line_text) |
| 290 | } |
| 291 | |
| 292 | #[inline] |
| 293 | fn is_from_your_files_bold(line_text: &str) -> bool { |
| 294 | FROM_YOUR_FILES_BOLD_RE.is_match(line_text) |
| 295 | } |
| 296 | |
| 297 | #[inline] |
| 298 | fn is_ranked_clusters_heading(line_text: &str) -> bool { |
| 299 | line_text |
| 300 | .strip_prefix("## Ranked Evidence Clusters") |
| 301 | .is_some_and(|rest| rest.bytes().all(|b| b == b' ' || b == b'\t')) |
| 302 | } |
| 303 | |
| 304 | #[inline] |
| 305 | fn brief_clusters_heading_name(line_text: &str) -> Option<&'static str> { |
| 306 | for name in ["Ranked Storylines", "Topic Tensions", "Source Clusters"] { |
| 307 | if let Some(rest) = line_text |
| 308 | .strip_prefix("## ") |
| 309 | .and_then(|s| s.strip_prefix(name)) |
| 310 | { |
| 311 | if rest.bytes().all(|b| b == b' ' || b == b'\t') { |
| 312 | return Some(name); |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | None |
| 317 | } |
| 318 | |
| 319 | #[inline] |
| 320 | fn is_freshness_heading(line_text: &str) -> bool { |
| 321 | line_text |
| 322 | .strip_prefix("## Freshness Verification") |
| 323 | .is_some_and(|rest| rest.bytes().all(|b| b == b' ' || b == b'\t')) |
| 324 | } |
| 325 | |
| 326 | #[derive(Clone, Copy)] |
| 327 | enum SectionBoundary { |
| 328 | TopLevel, |
| 329 | H1ToH3, |
| 330 | } |
| 331 | |
| 332 | impl SectionBoundary { |
| 333 | #[inline] |
| 334 | fn matches(self, line_text: &str) -> bool { |
| 335 | match self { |
| 336 | Self::TopLevel => is_top_level_heading(line_text), |
| 337 | Self::H1ToH3 => is_h1_to_h3_heading(line_text), |
| 338 | } |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | fn find_section_end(lines: &[&str], start: usize, boundary: SectionBoundary) -> usize { |
| 343 | let mut fence = None; |
| 344 | for (offset, line) in lines[start..].iter().enumerate() { |
| 345 | let text = trim_line_end(line); |
| 346 | if fence.is_some() { |
| 347 | fence = fence_step(text, fence); |
| 348 | continue; |
| 349 | } |
| 350 | if boundary.matches(text) { |
| 351 | return start + offset; |
| 352 | } |
| 353 | fence = fence_step(text, None); |
| 354 | } |
| 355 | lines.len() |
| 356 | } |
| 357 | |
| 358 | /// Returns `true` when `markdown` carries local-corpus markers or citations. |
| 359 | pub fn has_private_corpus(markdown: &str) -> bool { |
| 360 | markdown.contains(PRIVATE_CORPUS_START) |
| 361 | || LEGACY_CORPUS_SIGNAL_RE.is_match(markdown) |
| 362 | || PRIVATE_FRESHNESS_ROW_RE.is_match(markdown) |
| 363 | || contains_corpus_scheme(markdown) |
| 364 | || CORPUS_FOOTER_RE.is_match(markdown) |
| 365 | || BOLD_FROM_YOUR_FILES_RE.is_match(markdown) |
| 366 | } |
| 367 | |
| 368 | fn is_structured_engine_report(markdown: &str) -> bool { |
| 369 | (markdown.contains(PRIVATE_CORPUS_START) && markdown.contains(PRIVATE_CORPUS_END)) |
| 370 | || markdown.contains(PUBLIC_CLUSTERS_MARKER) |
| 371 | || markdown.contains("## Ranked Evidence Clusters") |
| 372 | || markdown.contains("<!-- EVIDENCE FOR SYNTHESIS") |
| 373 | || markdown.contains("# END OF last30days CANONICAL OUTPUT") |
| 374 | || REPORT_TITLE_RE.is_match(markdown) |
| 375 | } |
| 376 | |
| 377 | /// Returns `true` when a synthesized chat brief carries unbounded local-corpus content. |
| 378 | pub fn is_unbounded_private_brief(markdown: &str, source_format: Option<&str>) -> bool { |
| 379 | if let Some(fmt) = source_format { |
| 380 | if fmt != "finished-brief" { |
| 381 | return false; |
| 382 | } |
| 383 | } |
| 384 | if is_structured_engine_report(markdown) { |
| 385 | return false; |
| 386 | } |
| 387 | markdown.contains('🌐') && BADGE_LINE_RE.is_match(markdown) && has_private_corpus(markdown) |
| 388 | } |
| 389 | |
| 390 | fn strip_private_corpus_blocks(markdown: &str) -> String { |
| 391 | if !markdown.contains(PRIVATE_CORPUS_START) { |
| 392 | return markdown.to_owned(); |
| 393 | } |
| 394 | let mut out = String::with_capacity(markdown.len()); |
| 395 | let mut cursor = 0; |
| 396 | while let Some(rel_start) = markdown[cursor..].find(PRIVATE_CORPUS_START) { |
| 397 | let block_start = cursor + rel_start; |
| 398 | out.push_str(&markdown[cursor..block_start]); |
| 399 | |
| 400 | let search_from = block_start + PRIVATE_CORPUS_START.len(); |
| 401 | let block_end = if let Some(rel_end) = markdown[search_from..].find(PRIVATE_CORPUS_END) { |
| 402 | let after_end = search_from + rel_end + PRIVATE_CORPUS_END.len(); |
| 403 | let ws_len = markdown[after_end..] |
| 404 | .char_indices() |
| 405 | .find(|&(_, ch)| !ch.is_whitespace()) |
| 406 | .map_or(markdown.len() - after_end, |(i, _)| i); |
| 407 | after_end + ws_len |
| 408 | } else { |
| 409 | markdown.len() |
| 410 | }; |
| 411 | |
| 412 | let mut marker_end = block_start; |
| 413 | while marker_end > 0 { |
| 414 | let prev = markdown.as_bytes()[marker_end - 1]; |
| 415 | if matches!(prev, b' ' | b'\t' | b'\r' | b'\n') { |
| 416 | marker_end -= 1; |
| 417 | } else { |
| 418 | break; |
| 419 | } |
| 420 | } |
| 421 | let prefix = &markdown[..marker_end]; |
| 422 | if prefix.ends_with(PUBLIC_DRILL_MARKER) |
| 423 | || prefix.ends_with(PUBLIC_CLUSTERS_MARKER) |
| 424 | || prefix.ends_with(PUBLIC_FRESHNESS_MARKER) |
| 425 | { |
| 426 | out.push_str("\n\n"); |
| 427 | } |
| 428 | cursor = block_end; |
| 429 | } |
| 430 | out.push_str(&markdown[cursor..]); |
| 431 | out |
| 432 | } |
| 433 | |
| 434 | fn strip_unmarked_drills(markdown: &str) -> String { |
| 435 | if !markdown.contains("## Drill Follow-up") { |
| 436 | return markdown.to_owned(); |
| 437 | } |
| 438 | let mut lines = splitlines_keepends(markdown); |
| 439 | loop { |
| 440 | let mut fence = None; |
| 441 | let mut unmarked_idx = None; |
| 442 | for (idx, line) in lines.iter().enumerate() { |
| 443 | let text = trim_line_end(line); |
| 444 | if fence.is_some() { |
| 445 | fence = fence_step(text, fence); |
| 446 | continue; |
| 447 | } |
| 448 | if is_drill_heading(text) { |
| 449 | let prev_text = if idx > 0 { |
| 450 | trim_line_end(lines[idx - 1]) |
| 451 | } else { |
| 452 | "" |
| 453 | }; |
| 454 | if prev_text != PUBLIC_DRILL_MARKER && prev_text != PRIVATE_CORPUS_START { |
| 455 | unmarked_idx = Some(idx); |
| 456 | break; |
| 457 | } |
| 458 | } |
| 459 | fence = fence_step(text, None); |
| 460 | } |
| 461 | let Some(start_idx) = unmarked_idx else { |
| 462 | return lines.concat(); |
| 463 | }; |
| 464 | let mut end = lines.len(); |
| 465 | let mut inner_fence = None; |
| 466 | for idx in (start_idx + 1)..lines.len() { |
| 467 | let text = trim_line_end(lines[idx]); |
| 468 | if inner_fence.is_some() { |
| 469 | inner_fence = fence_step(text, inner_fence); |
| 470 | continue; |
| 471 | } |
| 472 | if is_drill_deeper_heading(text) |
| 473 | && idx + 3 < lines.len() |
| 474 | && trim_line_end(lines[idx + 1]) |
| 475 | .bytes() |
| 476 | .all(|b| b == b' ' || b == b'\t') |
| 477 | && is_drill_new_items(trim_line_end(lines[idx + 2])) |
| 478 | && is_drill_sources(trim_line_end(lines[idx + 3])) |
| 479 | { |
| 480 | end = idx + 4; |
| 481 | } |
| 482 | inner_fence = fence_step(text, None); |
| 483 | } |
| 484 | lines.drain(start_idx..end); |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | fn strip_from_your_files_sections(markdown: &str) -> String { |
| 489 | if !FROM_YOUR_FILES_ANY_RE.is_match(markdown) { |
| 490 | return markdown.to_owned(); |
| 491 | } |
| 492 | let lines = splitlines_keepends(markdown); |
| 493 | let mut out = String::with_capacity(markdown.len()); |
| 494 | let mut fence = None; |
| 495 | let mut skip_until: Option<SectionBoundary> = None; |
| 496 | |
| 497 | for line in lines { |
| 498 | let text = trim_line_end(line); |
| 499 | if fence.is_some() { |
| 500 | fence = fence_step(text, fence); |
| 501 | if skip_until.is_none() { |
| 502 | out.push_str(line); |
| 503 | } |
| 504 | continue; |
| 505 | } |
| 506 | if let Some(boundary) = skip_until { |
| 507 | if boundary.matches(text) { |
| 508 | skip_until = None; |
| 509 | } else { |
| 510 | fence = fence_step(text, None); |
| 511 | continue; |
| 512 | } |
| 513 | } |
| 514 | if is_from_your_files_h12(text) || is_from_your_files_bold(text) { |
| 515 | skip_until = Some(SectionBoundary::TopLevel); |
| 516 | continue; |
| 517 | } |
| 518 | if is_from_your_files_h3(text) { |
| 519 | skip_until = Some(SectionBoundary::H1ToH3); |
| 520 | continue; |
| 521 | } |
| 522 | fence = fence_step(text, None); |
| 523 | out.push_str(line); |
| 524 | } |
| 525 | out |
| 526 | } |
| 527 | |
| 528 | fn public_legacy_cluster_lines(heading_line: &str, body_lines: &[&str]) -> String { |
| 529 | let heading_text = trim_line_end(heading_line); |
| 530 | let ending = &heading_line[heading_text.len()..]; |
| 531 | let Some(heading_caps) = RANKED_CLUSTER_HEADING_RE.captures(heading_text) else { |
| 532 | let mut s = String::from(heading_line); |
| 533 | for l in body_lines { |
| 534 | s.push_str(l); |
| 535 | } |
| 536 | return s; |
| 537 | }; |
| 538 | |
| 539 | let mut preamble: Vec<&str> = Vec::new(); |
| 540 | let mut rep_blocks: Vec<(String, String, Vec<&str>)> = Vec::new(); |
| 541 | let mut fence = None; |
| 542 | |
| 543 | for &line in body_lines { |
| 544 | let text = trim_line_end(line); |
| 545 | if fence.is_some() { |
| 546 | fence = fence_step(text, fence); |
| 547 | if let Some((_, _, block)) = rep_blocks.last_mut() { |
| 548 | block.push(line); |
| 549 | } else { |
| 550 | preamble.push(line); |
| 551 | } |
| 552 | continue; |
| 553 | } |
| 554 | if let Some(rep_caps) = RANKED_REPRESENTATIVE_RE.captures(text) { |
| 555 | let sources = rep_caps["sources"].to_owned(); |
| 556 | let title = rep_caps["title"].to_owned(); |
| 557 | rep_blocks.push((sources, title, vec![line])); |
| 558 | continue; |
| 559 | } |
| 560 | fence = fence_step(text, None); |
| 561 | if let Some((_, _, block)) = rep_blocks.last_mut() { |
| 562 | block.push(line); |
| 563 | } else { |
| 564 | preamble.push(line); |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | let had_representatives = !rep_blocks.is_empty(); |
| 569 | let mut public_reps: Vec<(String, Vec<&str>)> = Vec::new(); |
| 570 | for (sources_str, title, block) in rep_blocks { |
| 571 | let has_private = sources_str.split(',').any(|s| { |
| 572 | let trimmed = s.trim(); |
| 573 | trimmed.eq_ignore_ascii_case("corpus") || trimmed.eq_ignore_ascii_case("your files") |
| 574 | }); |
| 575 | if has_private { |
| 576 | continue; |
| 577 | } |
| 578 | public_reps.push((title, block)); |
| 579 | } |
| 580 | |
| 581 | let raw_body: String = body_lines.concat(); |
| 582 | let mut cleaned_body = preamble.concat(); |
| 583 | for (_, block) in &public_reps { |
| 584 | for &l in block { |
| 585 | cleaned_body.push_str(l); |
| 586 | } |
| 587 | } |
| 588 | if raw_body.ends_with("\n\n") && !cleaned_body.is_empty() && !cleaned_body.ends_with("\n\n") { |
| 589 | let trimmed = cleaned_body.trim_end_matches(['\r', '\n']); |
| 590 | cleaned_body = format!("{trimmed}\n\n"); |
| 591 | } |
| 592 | |
| 593 | for (raw_title, _) in &public_reps { |
| 594 | let stripped = RANKED_FRESHNESS_BADGE_RE.replace(raw_title, ""); |
| 595 | let title = stripped.trim(); |
| 596 | if !title.is_empty() { |
| 597 | let stats = RANKED_CLUSTER_STATS_RE |
| 598 | .find(&heading_caps["title"]) |
| 599 | .map_or("", |m| m.as_str()); |
| 600 | return format!( |
| 601 | "{}{}{}{}{}", |
| 602 | &heading_caps["prefix"], title, stats, ending, cleaned_body |
| 603 | ); |
| 604 | } |
| 605 | } |
| 606 | if had_representatives { |
| 607 | return String::new(); |
| 608 | } |
| 609 | if LEGACY_CORPUS_SIGNAL_RE.is_match(&cleaned_body) |
| 610 | || contains_corpus_scheme(&cleaned_body) |
| 611 | || BOLD_FROM_YOUR_FILES_RE.is_match(&cleaned_body) |
| 612 | { |
| 613 | return String::new(); |
| 614 | } |
| 615 | cleaned_body |
| 616 | } |
| 617 | |
| 618 | fn rewrite_ranked_clusters_sections(markdown: &str) -> String { |
| 619 | if !markdown.contains("## Ranked Evidence Clusters") { |
| 620 | return markdown.to_owned(); |
| 621 | } |
| 622 | let lines = splitlines_keepends(markdown); |
| 623 | let mut out = String::with_capacity(markdown.len()); |
| 624 | let mut fence = None; |
| 625 | let mut idx = 0; |
| 626 | |
| 627 | while idx < lines.len() { |
| 628 | let line = lines[idx]; |
| 629 | let text = trim_line_end(line); |
| 630 | if fence.is_some() { |
| 631 | fence = fence_step(text, fence); |
| 632 | out.push_str(line); |
| 633 | idx += 1; |
| 634 | continue; |
| 635 | } |
| 636 | if is_ranked_clusters_heading(text) { |
| 637 | let end = find_section_end(&lines, idx + 1, SectionBoundary::TopLevel); |
| 638 | let prev_text = if idx > 0 { |
| 639 | trim_line_end(lines[idx - 1]) |
| 640 | } else { |
| 641 | "" |
| 642 | }; |
| 643 | if prev_text == PUBLIC_CLUSTERS_MARKER { |
| 644 | for l in &lines[idx..end] { |
| 645 | out.push_str(l); |
| 646 | } |
| 647 | idx = end; |
| 648 | continue; |
| 649 | } |
| 650 | out.push_str(line); |
| 651 | let mut sec_fence = None; |
| 652 | let mut cluster_heading: Option<&str> = None; |
| 653 | let mut cluster_body: Vec<&str> = Vec::new(); |
| 654 | for &sec_line in &lines[idx + 1..end] { |
| 655 | let sec_text = trim_line_end(sec_line); |
| 656 | if sec_fence.is_some() { |
| 657 | sec_fence = fence_step(sec_text, sec_fence); |
| 658 | if cluster_heading.is_some() { |
| 659 | cluster_body.push(sec_line); |
| 660 | } else { |
| 661 | out.push_str(sec_line); |
| 662 | } |
| 663 | continue; |
| 664 | } |
| 665 | if RANKED_CLUSTER_HEADING_RE.is_match(sec_text) { |
| 666 | if let Some(prev_heading) = cluster_heading { |
| 667 | out.push_str(&public_legacy_cluster_lines(prev_heading, &cluster_body)); |
| 668 | } |
| 669 | cluster_heading = Some(sec_line); |
| 670 | cluster_body.clear(); |
| 671 | continue; |
| 672 | } |
| 673 | sec_fence = fence_step(sec_text, None); |
| 674 | if cluster_heading.is_some() { |
| 675 | cluster_body.push(sec_line); |
| 676 | } else { |
| 677 | out.push_str(sec_line); |
| 678 | } |
| 679 | } |
| 680 | if let Some(prev_heading) = cluster_heading { |
| 681 | out.push_str(&public_legacy_cluster_lines(prev_heading, &cluster_body)); |
| 682 | } |
| 683 | idx = end; |
| 684 | continue; |
| 685 | } |
| 686 | fence = fence_step(text, None); |
| 687 | out.push_str(line); |
| 688 | idx += 1; |
| 689 | } |
| 690 | out |
| 691 | } |
| 692 | |
| 693 | fn rewrite_brief_clusters_sections(markdown: &str) -> String { |
| 694 | let lines = splitlines_keepends(markdown); |
| 695 | let mut out = String::with_capacity(markdown.len()); |
| 696 | let mut fence = None; |
| 697 | let mut idx = 0; |
| 698 | |
| 699 | while idx < lines.len() { |
| 700 | let line = lines[idx]; |
| 701 | let text = trim_line_end(line); |
| 702 | if fence.is_some() { |
| 703 | fence = fence_step(text, fence); |
| 704 | out.push_str(line); |
| 705 | idx += 1; |
| 706 | continue; |
| 707 | } |
| 708 | if let Some(name) = brief_clusters_heading_name(text) { |
| 709 | let end = find_section_end(&lines, idx + 1, SectionBoundary::TopLevel); |
| 710 | let prev_text = if idx > 0 { |
| 711 | trim_line_end(lines[idx - 1]) |
| 712 | } else { |
| 713 | "" |
| 714 | }; |
| 715 | if prev_text == PUBLIC_CLUSTERS_MARKER { |
| 716 | for l in &lines[idx..end] { |
| 717 | out.push_str(l); |
| 718 | } |
| 719 | idx = end; |
| 720 | continue; |
| 721 | } |
| 722 | out.push_str(line); |
| 723 | let is_storylines = name == "Ranked Storylines"; |
| 724 | let mut sec_fence = None; |
| 725 | for &sec_line in &lines[idx + 1..end] { |
| 726 | let sec_text = trim_line_end(sec_line); |
| 727 | if sec_fence.is_some() { |
| 728 | sec_fence = fence_step(sec_text, sec_fence); |
| 729 | out.push_str(sec_line); |
| 730 | continue; |
| 731 | } |
| 732 | let drop_label = if is_storylines { |
| 733 | RANKED_CLUSTER_HEADING_RE.is_match(sec_text) |
| 734 | } else { |
| 735 | sec_text.starts_with("- **") |
| 736 | }; |
| 737 | if drop_label { |
| 738 | continue; |
| 739 | } |
| 740 | sec_fence = fence_step(sec_text, None); |
| 741 | out.push_str(sec_line); |
| 742 | } |
| 743 | idx = end; |
| 744 | continue; |
| 745 | } |
| 746 | fence = fence_step(text, None); |
| 747 | out.push_str(line); |
| 748 | idx += 1; |
| 749 | } |
| 750 | out |
| 751 | } |
| 752 | |
| 753 | fn strip_unmarked_freshness_sections(markdown: &str) -> String { |
| 754 | if !markdown.contains("## Freshness Verification") { |
| 755 | return markdown.to_owned(); |
| 756 | } |
| 757 | let lines = splitlines_keepends(markdown); |
| 758 | let mut out = String::with_capacity(markdown.len()); |
| 759 | let mut fence = None; |
| 760 | let mut idx = 0; |
| 761 | |
| 762 | while idx < lines.len() { |
| 763 | let line = lines[idx]; |
| 764 | let text = trim_line_end(line); |
| 765 | if fence.is_some() { |
| 766 | fence = fence_step(text, fence); |
| 767 | out.push_str(line); |
| 768 | idx += 1; |
| 769 | continue; |
| 770 | } |
| 771 | if is_freshness_heading(text) |
| 772 | && idx + 3 < lines.len() |
| 773 | && trim_line_end(lines[idx + 1]) |
| 774 | .bytes() |
| 775 | .all(|b| b == b' ' || b == b'\t') |
| 776 | && trim_line_end(lines[idx + 2]) == "| Verdict | Claim | Evidence | Checked |" |
| 777 | && trim_line_end(lines[idx + 3]) == "| --- | --- | --- | --- |" |
| 778 | { |
| 779 | let end = find_section_end(&lines, idx + 4, SectionBoundary::TopLevel); |
| 780 | let prev_text = if idx > 0 { |
| 781 | trim_line_end(lines[idx - 1]) |
| 782 | } else { |
| 783 | "" |
| 784 | }; |
| 785 | if prev_text == PUBLIC_FRESHNESS_MARKER { |
| 786 | for l in &lines[idx..end] { |
| 787 | out.push_str(l); |
| 788 | } |
| 789 | } |
| 790 | idx = end; |
| 791 | continue; |
| 792 | } |
| 793 | fence = fence_step(text, None); |
| 794 | out.push_str(line); |
| 795 | idx += 1; |
| 796 | } |
| 797 | out |
| 798 | } |
| 799 | |
| 800 | /// Redacts private corpus sections and unmarked local-corpus rows from `markdown`. |
| 801 | /// |
| 802 | /// Mirrors `library.py:public_markdown`. |
| 803 | pub fn public_markdown(markdown: &str) -> String { |
| 804 | if is_unbounded_private_brief(markdown, None) { |
| 805 | return String::new(); |
| 806 | } |
| 807 | let corpus_document = has_private_corpus(markdown); |
| 808 | let mut current = strip_private_corpus_blocks(markdown); |
| 809 | current = strip_unmarked_drills(¤t); |
| 810 | current = strip_from_your_files_sections(¤t); |
| 811 | if corpus_document { |
| 812 | current = rewrite_ranked_clusters_sections(¤t); |
| 813 | if current.starts_with("# Production Brief: ") { |
| 814 | current = rewrite_brief_clusters_sections(¤t); |
| 815 | } |
| 816 | current = strip_unmarked_freshness_sections(¤t); |
| 817 | } |
| 818 | if PRIVATE_FRESHNESS_ROW_RE.is_match(¤t) { |
| 819 | PRIVATE_FRESHNESS_ROW_RE |
| 820 | .replace_all(¤t, "") |
| 821 | .into_owned() |
| 822 | } else { |
| 823 | current |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | /// Strips marked and legacy `## From your library` context sections. |
| 828 | /// |
| 829 | /// Mirrors `library_index.py:_without_library_context`. |
| 830 | pub fn without_library_context(content: &str) -> String { |
| 831 | let stripped_marked = if content.contains(LIBRARY_CONTEXT_START) { |
| 832 | strip_marked_library_context(content) |
| 833 | } else { |
| 834 | content.to_owned() |
| 835 | }; |
| 836 | if stripped_marked.contains("## From your library") { |
| 837 | strip_legacy_library_context(&stripped_marked) |
| 838 | } else { |
| 839 | stripped_marked |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | static MARKED_LIBRARY_CONTEXT_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 844 | Regex::new( |
| 845 | r"(?ms)^<!-- last30days:library-context:start -->\s*$.*?^<!-- last30days:library-context:end -->\s*$\n?", |
| 846 | ) |
| 847 | .expect("MARKED_LIBRARY_CONTEXT_RE is a valid literal regex") |
| 848 | }); |
| 849 | |
| 850 | fn strip_marked_library_context(content: &str) -> String { |
| 851 | MARKED_LIBRARY_CONTEXT_RE |
| 852 | .replace_all(content, "") |
| 853 | .into_owned() |
| 854 | } |
| 855 | |
| 856 | fn strip_legacy_library_context(content: &str) -> String { |
| 857 | let lines = splitlines_keepends(content); |
| 858 | let mut out = String::with_capacity(content.len()); |
| 859 | let mut skipping = false; |
| 860 | for line in lines { |
| 861 | let text = trim_line_end(line); |
| 862 | if skipping { |
| 863 | let starts_h2 = text |
| 864 | .strip_prefix("##") |
| 865 | .is_some_and(|rest| rest.chars().next().is_some_and(char::is_whitespace)); |
| 866 | if starts_h2 { |
| 867 | skipping = false; |
| 868 | out.push_str(line); |
| 869 | } |
| 870 | continue; |
| 871 | } |
| 872 | if text |
| 873 | .strip_prefix("## From your library") |
| 874 | .is_some_and(|rest| rest.chars().all(char::is_whitespace)) |
| 875 | { |
| 876 | skipping = true; |
| 877 | continue; |
| 878 | } |
| 879 | out.push_str(line); |
| 880 | } |
| 881 | out |
| 882 | } |
| 883 | |
| 884 | /// Computes the SHA-256 fingerprint of indexable content matching `library_index._fingerprint`. |
| 885 | pub fn indexable_fingerprint_from_public(public_md: &str) -> String { |
| 886 | let indexable = without_library_context(public_md); |
| 887 | let mut hasher = Sha256::new(); |
| 888 | hasher.update(INDEX_FINGERPRINT_VERSION.as_bytes()); |
| 889 | hasher.update(b"\0"); |
| 890 | hasher.update(indexable.as_bytes()); |
| 891 | let digest = hasher.finalize(); |
| 892 | let mut hex = String::with_capacity(64); |
| 893 | for byte in digest { |
| 894 | let _ = write!(&mut hex, "{byte:02x}"); |
| 895 | } |
| 896 | hex |
| 897 | } |
| 898 | |
| 899 | /// Sanitizes and fingerprints a single Markdown document in one pass. |
| 900 | pub fn sanitize_markdown_one(content: &str, source_format: Option<&str>) -> MarkdownBatchResult { |
| 901 | let unbounded_private = is_unbounded_private_brief(content, source_format); |
| 902 | let public = if unbounded_private { |
| 903 | String::new() |
| 904 | } else { |
| 905 | public_markdown(content) |
| 906 | }; |
| 907 | let fingerprint = indexable_fingerprint_from_public(&public); |
| 908 | MarkdownBatchResult { |
| 909 | unbounded_private, |
| 910 | public_markdown: public, |
| 911 | indexable_fingerprint: fingerprint, |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | /// Maximum Markdown file size accepted during library scans (10 MiB). |
| 916 | pub const MAX_LIBRARY_FILE_BYTES: u64 = 10 * 1024 * 1024; |
| 917 | |
| 918 | /// File descriptor input for [`scan_markdown_files_batch`]. |
| 919 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 920 | pub struct MarkdownFileRequest { |
| 921 | /// Absolute path to a regular non-symlink Markdown file. |
| 922 | pub path: String, |
| 923 | /// Filename stem (without `.md`). |
| 924 | pub stem: String, |
| 925 | /// Source format (`"markdown"` or `"finished-brief"`). |
| 926 | pub source_format: String, |
| 927 | /// Expected `(dev, ino)` from caller's `lstat` on POSIX, if available. |
| 928 | pub expected_dev_ino: Option<(u64, u64)>, |
| 929 | /// Fallback `YYYY-MM-DD` date derived from file mtime in local timezone. |
| 930 | pub fallback_date: String, |
| 931 | } |
| 932 | |
| 933 | /// Metadata and index fingerprint extracted from one saved Markdown file. |
| 934 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 935 | pub struct MarkdownFileMeta { |
| 936 | /// Path echoed from the request. |
| 937 | pub path: String, |
| 938 | /// Extracted topic string. |
| 939 | pub topic: String, |
| 940 | /// URL-safe slug derived from `topic`. |
| 941 | pub slug: String, |
| 942 | /// 8-hex-char identity hash of `"{topic}\n{stem}"`. |
| 943 | pub identity_hash: String, |
| 944 | /// Resolved `YYYY-MM-DD` published date. |
| 945 | pub published_date: String, |
| 946 | /// Full deterministic entry URN. |
| 947 | pub entry_id: String, |
| 948 | /// Extracted headline. |
| 949 | pub headline: String, |
| 950 | /// Extracted summary. |
| 951 | pub summary: String, |
| 952 | /// Source format echoed from request. |
| 953 | pub source_format: String, |
| 954 | /// Whether the document is an unbounded private brief. |
| 955 | pub unbounded_private: bool, |
| 956 | /// SHA-256 fingerprint of indexable public content (without library context). |
| 957 | pub indexable_fingerprint: String, |
| 958 | /// Whether `public_markdown(content) != content`. |
| 959 | pub redacted: bool, |
| 960 | } |
| 961 | |
| 962 | /// Per-file outcome returned by [`scan_markdown_files_batch`]. |
| 963 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 964 | #[serde(tag = "status", rename_all = "snake_case")] |
| 965 | #[non_exhaustive] |
| 966 | pub enum MarkdownScanOutcome { |
| 967 | /// File was safely read, sanitized, and parsed. |
| 968 | Ok { |
| 969 | /// Parsed metadata and fingerprint. |
| 970 | meta: MarkdownFileMeta, |
| 971 | }, |
| 972 | /// File was skipped (unreadable, symlink, oversized, invalid UTF-8, or missing title). |
| 973 | Skipped { |
| 974 | /// Path echoed from request. |
| 975 | path: String, |
| 976 | /// Human-readable skip reason. |
| 977 | reason: String, |
| 978 | }, |
| 979 | } |
| 980 | |
| 981 | static TOPIC_META_COMMENT_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 982 | Regex::new(r"(?m)^<!--\s*last30days-topic:\s*(.+?)\s*-->$") |
| 983 | .expect("TOPIC_META_COMMENT_RE is a valid literal regex") |
| 984 | }); |
| 985 | |
| 986 | static FIRST_TITLE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 987 | Regex::new(r"(?m)^#\s+(.+?)\s*$").expect("FIRST_TITLE_RE is a valid literal regex") |
| 988 | }); |
| 989 | |
| 990 | static COMPARISON_TITLE_SUFFIX_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 991 | Regex::new(r"(?i):\s*What the Community Says\s*\(/Last30Days\)\s*$") |
| 992 | .expect("COMPARISON_TITLE_SUFFIX_RE is a valid literal regex") |
| 993 | }); |
| 994 | |
| 995 | static BADGE_SYNCED_DATE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 996 | Regex::new(r"(?i)\bsynced\s+(\d{4}-\d{2}-\d{2})\b") |
| 997 | .expect("BADGE_SYNCED_DATE_RE is a valid literal regex") |
| 998 | }); |
| 999 | |
| 1000 | static BADGE_VERSION_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1001 | Regex::new(r"^v\d+\.\d+(?:\.\d+)*(?:[-+][A-Za-z0-9._-]+)?$") |
| 1002 | .expect("BADGE_VERSION_RE is a valid literal regex") |
| 1003 | }); |
| 1004 | |
| 1005 | static BADGE_MONTH_DAY_YEAR_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1006 | Regex::new(r"(?i)\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)[a-z]*\.?\s+(\d{1,2}),\s*(\d{4})\b") |
| 1007 | .expect("BADGE_MONTH_DAY_YEAR_RE is a valid literal regex") |
| 1008 | }); |
| 1009 | |
| 1010 | static BADGE_ISO_DATE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1011 | Regex::new(r"\b(\d{4}-\d{2}-\d{2})\b").expect("BADGE_ISO_DATE_RE is a valid literal regex") |
| 1012 | }); |
| 1013 | |
| 1014 | static DATE_RANGE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1015 | Regex::new(r"(?im)^-\s*Date range:\s*\d{4}-\d{2}-\d{2}\s+to\s+(\d{4}-\d{2}-\d{2})\s*$") |
| 1016 | .expect("DATE_RANGE_RE is a valid literal regex") |
| 1017 | }); |
| 1018 | |
| 1019 | static DATED_FILENAME_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1020 | Regex::new(r"-(\d{4}-\d{2}-\d{2})(?:-\d+)?$") |
| 1021 | .expect("DATED_FILENAME_RE is a valid literal regex") |
| 1022 | }); |
| 1023 | |
| 1024 | static RANKED_HEADLINE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1025 | Regex::new(r"(?m)^###\s+1[.)]\s+(.+?)\s*$") |
| 1026 | .expect("RANKED_HEADLINE_RE is a valid literal regex") |
| 1027 | }); |
| 1028 | |
| 1029 | static SCORE_SUFFIX_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1030 | Regex::new(r"(?i)\s+\(score\s+[^)]*\)\s*$").expect("SCORE_SUFFIX_RE is a valid literal regex") |
| 1031 | }); |
| 1032 | |
| 1033 | static MARKDOWN_LINK_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1034 | Regex::new(r"\[([^\]]+)]\([^)]+\)").expect("MARKDOWN_LINK_RE is a valid literal regex") |
| 1035 | }); |
| 1036 | |
| 1037 | static PROSE_LABEL_LINE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1038 | Regex::new( |
| 1039 | r"(?i)^(?:\*\*|__)?(?:what i learned|key patterns(?:\s+from the research)?|best takes|tl;?dr|summary|verdict|bottom line)(?:\*\*|__)?:?(?:\*\*|__)?$", |
| 1040 | ) |
| 1041 | .expect("PROSE_LABEL_LINE_RE is a valid literal regex") |
| 1042 | }); |
| 1043 | |
| 1044 | static EVIDENCE_LINE_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1045 | Regex::new(r"(?im)^[ \t]*-\s*Evidence:\s*(.+?)\s*$") |
| 1046 | .expect("EVIDENCE_LINE_RE is a valid literal regex") |
| 1047 | }); |
| 1048 | |
| 1049 | static LEARNED_HEADING_RE: LazyLock<Regex> = LazyLock::new(|| { |
| 1050 | Regex::new(r"(?im)^(?:##\s+What I learned|(?:\*\*|__)?What I learned:?(?:\*\*|__)?)[ \t]*$") |
| 1051 | .expect("LEARNED_HEADING_RE is a valid literal regex") |
| 1052 | }); |
| 1053 | |
| 1054 | /// Sanitizes and fingerprints a batch of Markdown documents in parallel using Rayon. |
| 1055 | pub fn sanitize_markdown_batch(items: &[MarkdownBatchItem]) -> Vec<MarkdownBatchResult> { |
| 1056 | items |
| 1057 | .par_iter() |
| 1058 | .map(|item| sanitize_markdown_one(&item.content, item.source_format.as_deref())) |
| 1059 | .collect() |
| 1060 | } |
| 1061 | |
| 1062 | /// Computes the URL-safe slug matching `library.slugify`. |
| 1063 | pub fn slugify(value: &str) -> String { |
| 1064 | let mut out = String::with_capacity(value.len()); |
| 1065 | let mut prev_dash = true; |
| 1066 | for ch in value.to_lowercase().chars() { |
| 1067 | if ch.is_ascii_lowercase() || ch.is_ascii_digit() { |
| 1068 | out.push(ch); |
| 1069 | prev_dash = false; |
| 1070 | } else if !prev_dash { |
| 1071 | out.push('-'); |
| 1072 | prev_dash = true; |
| 1073 | } |
| 1074 | } |
| 1075 | while out.ends_with('-') { |
| 1076 | out.pop(); |
| 1077 | } |
| 1078 | if out.is_empty() { |
| 1079 | "last30days".to_owned() |
| 1080 | } else { |
| 1081 | out |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | /// Computes the 8-hex-char identity hash matching `LibraryEntry.identity_hash`. |
| 1086 | pub fn identity_hash(topic: &str, stem: &str) -> String { |
| 1087 | let mut hasher = Sha256::new(); |
| 1088 | hasher.update(topic.as_bytes()); |
| 1089 | hasher.update(b"\n"); |
| 1090 | hasher.update(stem.as_bytes()); |
| 1091 | let digest = hasher.finalize(); |
| 1092 | let mut hex = String::with_capacity(8); |
| 1093 | for byte in &digest[..4] { |
| 1094 | let _ = write!(&mut hex, "{byte:02x}"); |
| 1095 | } |
| 1096 | hex |
| 1097 | } |
| 1098 | |
| 1099 | fn month_number(raw: &str) -> Option<u32> { |
| 1100 | let lower = raw.to_ascii_lowercase(); |
| 1101 | let prefix = if lower.starts_with("sept") { |
| 1102 | "sept" |
| 1103 | } else if lower.len() >= 3 { |
| 1104 | &lower[..3] |
| 1105 | } else { |
| 1106 | return None; |
| 1107 | }; |
| 1108 | match prefix { |
| 1109 | "jan" => Some(1), |
| 1110 | "feb" => Some(2), |
| 1111 | "mar" => Some(3), |
| 1112 | "apr" => Some(4), |
| 1113 | "may" => Some(5), |
| 1114 | "jun" => Some(6), |
| 1115 | "jul" => Some(7), |
| 1116 | "aug" => Some(8), |
| 1117 | "sep" | "sept" => Some(9), |
| 1118 | "oct" => Some(10), |
| 1119 | "nov" => Some(11), |
| 1120 | "dec" => Some(12), |
| 1121 | _ => None, |
| 1122 | } |
| 1123 | } |
| 1124 | |
| 1125 | fn format_valid_ymd(year: i64, month: u32, day: u32) -> Option<String> { |
| 1126 | let candidate = format!("{year:04}-{month:02}-{day:02}"); |
| 1127 | crate::signals::parse_ymd_days(&candidate).ok()?; |
| 1128 | Some(candidate) |
| 1129 | } |
| 1130 | |
| 1131 | fn parse_badge_date(text: &str) -> Option<String> { |
| 1132 | if let Some(last) = BADGE_MONTH_DAY_YEAR_RE.captures_iter(text).last() { |
| 1133 | if let (Some(month), Ok(day), Ok(year)) = ( |
| 1134 | month_number(&last[1]), |
| 1135 | last[2].parse::<u32>(), |
| 1136 | last[3].parse::<i64>(), |
| 1137 | ) { |
| 1138 | if let Some(valid) = format_valid_ymd(year, month, day) { |
| 1139 | return Some(valid); |
| 1140 | } |
| 1141 | } |
| 1142 | } |
| 1143 | if let Some(last) = BADGE_ISO_DATE_RE.captures_iter(text).last() { |
| 1144 | if crate::signals::parse_ymd_days(&last[1]).is_ok() { |
| 1145 | return Some(last[1].to_owned()); |
| 1146 | } |
| 1147 | } |
| 1148 | None |
| 1149 | } |
| 1150 | |
| 1151 | fn parse_badge_line(content: &str) -> (String, Option<String>) { |
| 1152 | if !content.contains('🌐') { |
| 1153 | return (String::new(), None); |
| 1154 | } |
| 1155 | let Some(m) = BADGE_LINE_RE.find(content) else { |
| 1156 | return (String::new(), None); |
| 1157 | }; |
| 1158 | let line = m.as_str().trim(); |
| 1159 | let parts: Vec<&str> = line |
| 1160 | .split('·') |
| 1161 | .map(str::trim) |
| 1162 | .filter(|p| !p.is_empty()) |
| 1163 | .collect(); |
| 1164 | let mut topic = String::new(); |
| 1165 | let mut published: Option<String> = None; |
| 1166 | if let Some(caps) = BADGE_SYNCED_DATE_RE.captures(line) { |
| 1167 | if crate::signals::parse_ymd_days(&caps[1]).is_ok() { |
| 1168 | published = Some(caps[1].to_owned()); |
| 1169 | } |
| 1170 | } else { |
| 1171 | for &segment in parts.iter().skip(1) { |
| 1172 | if published.is_none() { |
| 1173 | if let Some(parsed) = parse_badge_date(segment) { |
| 1174 | published = Some(parsed); |
| 1175 | continue; |
| 1176 | } |
| 1177 | } |
| 1178 | if topic.is_empty() |
| 1179 | && !BADGE_VERSION_RE.is_match(segment) |
| 1180 | && !matches!( |
| 1181 | segment.to_ascii_lowercase().as_str(), |
| 1182 | "quick" | "default" | "deep" | "cached" |
| 1183 | ) |
| 1184 | { |
| 1185 | segment.clone_into(&mut topic); |
| 1186 | } |
| 1187 | } |
| 1188 | } |
| 1189 | (topic, published) |
| 1190 | } |
| 1191 | |
| 1192 | /// Strips inline Markdown emphasis/code/links and collapses whitespace (`library._clean_inline`). |
| 1193 | pub(crate) fn clean_inline(value: &str) -> String { |
| 1194 | let no_links = MARKDOWN_LINK_RE.replace_all(value, "$1"); |
| 1195 | // Strip leading blockquote marker `^\s*>\s?` |
| 1196 | let trimmed_start = no_links.trim_start(); |
| 1197 | let no_quote = if let Some(rest) = trimmed_start.strip_prefix('>') { |
| 1198 | rest.strip_prefix(|c: char| c.is_whitespace()) |
| 1199 | .unwrap_or(rest) |
| 1200 | } else { |
| 1201 | no_links.as_ref() |
| 1202 | }; |
| 1203 | // Match Python's exact three left-to-right regex passes so nested emphasis |
| 1204 | // such as `**__Rust__**` produces `_Rust_` identically in both engines. |
| 1205 | let s1 = strip_delimited_any(no_quote, &["**", "__"]); |
| 1206 | let s2 = strip_delimited_any(&s1, &["*", "_"]); |
| 1207 | let s3 = strip_delimited_any(&s2, &["`"]); |
| 1208 | let mut collapsed = String::with_capacity(s3.len()); |
| 1209 | for word in s3.split_whitespace() { |
| 1210 | if !collapsed.is_empty() { |
| 1211 | collapsed.push(' '); |
| 1212 | } |
| 1213 | collapsed.push_str(word); |
| 1214 | } |
| 1215 | collapsed |
| 1216 | } |
| 1217 | |
| 1218 | /// Mirrors `(?<!\w)(d1|d2)(?=\S)(.+?)(?<=\S)\1(?!\w)` in a single left-to-right pass. |
| 1219 | fn strip_delimited_any(input: &str, delims: &[&str]) -> String { |
| 1220 | if !delims.iter().any(|d| input.contains(d)) { |
| 1221 | return input.to_owned(); |
| 1222 | } |
| 1223 | let mut out = String::with_capacity(input.len()); |
| 1224 | let mut cursor = 0; |
| 1225 | |
| 1226 | while cursor < input.len() { |
| 1227 | let next_open = delims |
| 1228 | .iter() |
| 1229 | .filter_map(|&delim| input[cursor..].find(delim).map(|rel| (cursor + rel, delim))) |
| 1230 | .min_by_key(|&(pos, _)| pos); |
| 1231 | let Some((open, delim)) = next_open else { |
| 1232 | out.push_str(&input[cursor..]); |
| 1233 | break; |
| 1234 | }; |
| 1235 | let dlen = delim.len(); |
| 1236 | let prev_is_word = input[..open] |
| 1237 | .chars() |
| 1238 | .next_back() |
| 1239 | .is_some_and(crate::cjk::is_word_char); |
| 1240 | let after_open = open + dlen; |
| 1241 | let next_is_non_ws = input[after_open..] |
| 1242 | .chars() |
| 1243 | .next() |
| 1244 | .is_some_and(|c| !c.is_whitespace()); |
| 1245 | |
| 1246 | if !prev_is_word && next_is_non_ws { |
| 1247 | // Find earliest valid matching closing delimiter on the same line (no `.` across `\n`). |
| 1248 | let line_end = input[after_open..] |
| 1249 | .find('\n') |
| 1250 | .map_or(input.len(), |i| after_open + i); |
| 1251 | let mut search = after_open; |
| 1252 | let mut matched_close: Option<usize> = None; |
| 1253 | while search < line_end { |
| 1254 | let Some(rel_close) = input[search..line_end].find(delim) else { |
| 1255 | break; |
| 1256 | }; |
| 1257 | let close = search + rel_close; |
| 1258 | if close > after_open { |
| 1259 | let before_close_non_ws = input[after_open..close] |
| 1260 | .chars() |
| 1261 | .next_back() |
| 1262 | .is_some_and(|c| !c.is_whitespace()); |
| 1263 | let after_close = close + dlen; |
| 1264 | let after_close_is_word = input[after_close..] |
| 1265 | .chars() |
| 1266 | .next() |
| 1267 | .is_some_and(crate::cjk::is_word_char); |
| 1268 | if before_close_non_ws && !after_close_is_word { |
| 1269 | matched_close = Some(close); |
| 1270 | break; |
| 1271 | } |
| 1272 | } |
| 1273 | search = close + 1; |
| 1274 | } |
| 1275 | if let Some(close) = matched_close { |
| 1276 | out.push_str(&input[cursor..open]); |
| 1277 | out.push_str(&input[after_open..close]); |
| 1278 | cursor = close + dlen; |
| 1279 | continue; |
| 1280 | } |
| 1281 | } |
| 1282 | // Advance by one character past `open` so an alternative delimiter |
| 1283 | // inside a failed multi-char opener (e.g. `**` followed by `__`) is not skipped. |
| 1284 | let step = input[open..].chars().next().map_or(1, char::len_utf8); |
| 1285 | out.push_str(&input[cursor..open + step]); |
| 1286 | cursor = open + step; |
| 1287 | } |
| 1288 | out |
| 1289 | } |
| 1290 | |
| 1291 | fn brief_prose_paragraph(content: &str) -> String { |
| 1292 | let mut in_fence = false; |
| 1293 | let mut para: Vec<&str> = Vec::new(); |
| 1294 | for raw_line in splitlines_keepends(content) { |
| 1295 | let stripped = raw_line.trim(); |
| 1296 | if stripped.starts_with("```") { |
| 1297 | in_fence = !in_fence; |
| 1298 | if !para.is_empty() { |
| 1299 | break; |
| 1300 | } |
| 1301 | continue; |
| 1302 | } |
| 1303 | if in_fence { |
| 1304 | continue; |
| 1305 | } |
| 1306 | if stripped.is_empty() { |
| 1307 | if !para.is_empty() { |
| 1308 | break; |
| 1309 | } |
| 1310 | continue; |
| 1311 | } |
| 1312 | if stripped.starts_with("🌐 last30days") |
| 1313 | || stripped.starts_with("<!--") |
| 1314 | || stripped.starts_with('#') |
| 1315 | || stripped.starts_with("---") |
| 1316 | || stripped.starts_with('|') |
| 1317 | || PROSE_LABEL_LINE_RE.is_match(stripped) |
| 1318 | { |
| 1319 | if !para.is_empty() { |
| 1320 | break; |
| 1321 | } |
| 1322 | continue; |
| 1323 | } |
| 1324 | para.push(stripped.trim_end_matches('\\')); |
| 1325 | } |
| 1326 | clean_inline(¶.join(" ")) |
| 1327 | } |
| 1328 | |
| 1329 | fn truncate_chars(text: &str, max_chars: usize) -> String { |
| 1330 | text.chars().take(max_chars).collect() |
| 1331 | } |
| 1332 | |
| 1333 | fn brief_prose_headline(content: &str) -> String { |
| 1334 | let text = brief_prose_paragraph(content); |
| 1335 | if text.is_empty() { |
| 1336 | return String::new(); |
| 1337 | } |
| 1338 | // Split on `(?<=[.!?])\s+` (first sentence). |
| 1339 | let mut split_at = text.len(); |
| 1340 | let mut prev_punct = false; |
| 1341 | for (idx, ch) in text.char_indices() { |
| 1342 | if prev_punct && ch.is_whitespace() { |
| 1343 | split_at = idx; |
| 1344 | break; |
| 1345 | } |
| 1346 | prev_punct = matches!(ch, '.' | '!' | '?'); |
| 1347 | } |
| 1348 | truncate_chars(&text[..split_at], 140) |
| 1349 | } |
| 1350 | |
| 1351 | fn brief_prose_summary(content: &str) -> String { |
| 1352 | let text = brief_prose_paragraph(content); |
| 1353 | if text.is_empty() { |
| 1354 | String::new() |
| 1355 | } else { |
| 1356 | truncate_chars(&text, 500) |
| 1357 | } |
| 1358 | } |
| 1359 | |
| 1360 | fn markdown_headline(content: &str) -> String { |
| 1361 | if let Some(caps) = RANKED_HEADLINE_RE.captures(content) { |
| 1362 | let without_score = SCORE_SUFFIX_RE.replace(&caps[1], ""); |
| 1363 | return clean_inline(&without_score); |
| 1364 | } |
| 1365 | String::new() |
| 1366 | } |
| 1367 | |
| 1368 | fn markdown_summary(content: &str) -> String { |
| 1369 | if let Some(m) = LEARNED_HEADING_RE.find(content) { |
| 1370 | let after_heading = &content[m.end()..]; |
| 1371 | if let Some(nl_pos) = after_heading.find('\n') { |
| 1372 | let mut body_start = m.end() + nl_pos + 1; |
| 1373 | while body_start < content.len() && content.as_bytes()[body_start] == b'\n' { |
| 1374 | body_start += 1; |
| 1375 | } |
| 1376 | let body = &content[body_start..]; |
| 1377 | // Stop at `\n#{1,3}\s`, `\n---`, or `\n````. |
| 1378 | let mut body_end = body.len(); |
| 1379 | let mut offset = 0; |
| 1380 | for line in splitlines_keepends(body) { |
| 1381 | let text = trim_line_end(line); |
| 1382 | if offset > 0 |
| 1383 | && (is_h1_to_h3_heading(text) |
| 1384 | || text.starts_with("---") |
| 1385 | || text.starts_with("```")) |
| 1386 | { |
| 1387 | body_end = offset; |
| 1388 | break; |
| 1389 | } |
| 1390 | offset += line.len(); |
| 1391 | } |
| 1392 | let section = &body[..body_end]; |
| 1393 | // Split paragraphs on blank lines (`\n\s*\n`). |
| 1394 | let mut para = String::new(); |
| 1395 | for line in section.lines() { |
| 1396 | if line.trim().is_empty() { |
| 1397 | if !para.is_empty() { |
| 1398 | let cleaned = clean_inline(¶); |
| 1399 | if !cleaned.is_empty() && !PROSE_LABEL_LINE_RE.is_match(&cleaned) { |
| 1400 | return truncate_chars(&cleaned, 500); |
| 1401 | } |
| 1402 | para.clear(); |
| 1403 | } |
| 1404 | } else { |
| 1405 | if !para.is_empty() { |
| 1406 | para.push('\n'); |
| 1407 | } |
| 1408 | para.push_str(line); |
| 1409 | } |
| 1410 | } |
| 1411 | if !para.is_empty() { |
| 1412 | let cleaned = clean_inline(¶); |
| 1413 | if !cleaned.is_empty() && !PROSE_LABEL_LINE_RE.is_match(&cleaned) { |
| 1414 | return truncate_chars(&cleaned, 500); |
| 1415 | } |
| 1416 | } |
| 1417 | } |
| 1418 | } |
| 1419 | if let Some(caps) = EVIDENCE_LINE_RE.captures(content) { |
| 1420 | return truncate_chars(&clean_inline(&caps[1]), 500); |
| 1421 | } |
| 1422 | String::new() |
| 1423 | } |
| 1424 | |
| 1425 | fn markdown_date(content: &str, stem: &str, fallback_date: &str) -> String { |
| 1426 | if let Some(caps) = DATE_RANGE_RE.captures(content) { |
| 1427 | if crate::signals::parse_ymd_days(&caps[1]).is_ok() { |
| 1428 | return caps[1].to_owned(); |
| 1429 | } |
| 1430 | } |
| 1431 | if let Some(caps) = DATED_FILENAME_RE.captures(stem) { |
| 1432 | if crate::signals::parse_ymd_days(&caps[1]).is_ok() { |
| 1433 | return caps[1].to_owned(); |
| 1434 | } |
| 1435 | } |
| 1436 | fallback_date.to_owned() |
| 1437 | } |
| 1438 | |
| 1439 | /// Parses metadata and index fingerprint from one Markdown document's text. |
| 1440 | /// |
| 1441 | /// # Errors |
| 1442 | /// |
| 1443 | /// Returns [`CoreError::MissingMarkdownTitle`] or [`CoreError::EmptyMarkdownTitle`] |
| 1444 | /// when the document has no extractable title. |
| 1445 | pub fn parse_markdown_meta( |
| 1446 | content: &str, |
| 1447 | path: &str, |
| 1448 | stem: &str, |
| 1449 | source_format: &str, |
| 1450 | fallback_date: &str, |
| 1451 | ) -> Result<MarkdownFileMeta, CoreError> { |
| 1452 | let unbounded_private = is_unbounded_private_brief(content, Some(source_format)); |
| 1453 | let public_content = if unbounded_private { |
| 1454 | String::new() |
| 1455 | } else { |
| 1456 | public_markdown(content) |
| 1457 | }; |
| 1458 | let parse_source = if unbounded_private { |
| 1459 | content |
| 1460 | } else { |
| 1461 | &public_content |
| 1462 | }; |
| 1463 | let redacted = !unbounded_private && public_content != content; |
| 1464 | |
| 1465 | let meta_topic = TOPIC_META_COMMENT_RE |
| 1466 | .captures(content) |
| 1467 | .map(|c| c[1].to_owned()); |
| 1468 | let (badge_topic, badge_date) = parse_badge_line(parse_source); |
| 1469 | let report_title = REPORT_TITLE_RE |
| 1470 | .captures(parse_source) |
| 1471 | .map(|c| c[1].to_owned()); |
| 1472 | let first_title = FIRST_TITLE_RE |
| 1473 | .captures(parse_source) |
| 1474 | .map(|c| c[1].to_owned()); |
| 1475 | |
| 1476 | let topic = if let Some(t) = meta_topic { |
| 1477 | clean_inline(&t) |
| 1478 | } else if source_format == "finished-brief" && !badge_topic.is_empty() { |
| 1479 | clean_inline(&badge_topic) |
| 1480 | } else if let Some(t) = report_title { |
| 1481 | clean_inline(&t) |
| 1482 | } else if !badge_topic.is_empty() { |
| 1483 | clean_inline(&badge_topic) |
| 1484 | } else if let Some(t) = first_title { |
| 1485 | let stripped = COMPARISON_TITLE_SUFFIX_RE.replace(&t, ""); |
| 1486 | clean_inline(&stripped) |
| 1487 | } else { |
| 1488 | return Err(CoreError::MissingMarkdownTitle); |
| 1489 | }; |
| 1490 | |
| 1491 | if topic.is_empty() { |
| 1492 | return Err(CoreError::EmptyMarkdownTitle); |
| 1493 | } |
| 1494 | |
| 1495 | let published_date = |
| 1496 | badge_date.unwrap_or_else(|| markdown_date(parse_source, stem, fallback_date)); |
| 1497 | |
| 1498 | let (headline, summary) = if unbounded_private { |
| 1499 | ( |
| 1500 | topic.clone(), |
| 1501 | "Private local-corpus brief (stored locally only).".to_owned(), |
| 1502 | ) |
| 1503 | } else { |
| 1504 | let hl = { |
| 1505 | let m = markdown_headline(parse_source); |
| 1506 | if m.is_empty() { |
| 1507 | let p = brief_prose_headline(parse_source); |
| 1508 | if p.is_empty() { topic.clone() } else { p } |
| 1509 | } else { |
| 1510 | m |
| 1511 | } |
| 1512 | }; |
| 1513 | let sum = { |
| 1514 | let m = markdown_summary(parse_source); |
| 1515 | if m.is_empty() { |
| 1516 | let p = brief_prose_summary(parse_source); |
| 1517 | if p.is_empty() { hl.clone() } else { p } |
| 1518 | } else { |
| 1519 | m |
| 1520 | } |
| 1521 | }; |
| 1522 | (hl, sum) |
| 1523 | }; |
| 1524 | |
| 1525 | let slug = slugify(&topic); |
| 1526 | let id_hash = identity_hash(&topic, stem); |
| 1527 | let entry_id = format!("urn:last30days:{slug}:{id_hash}:{published_date}"); |
| 1528 | let indexable_fingerprint = indexable_fingerprint_from_public(&public_content); |
| 1529 | |
| 1530 | Ok(MarkdownFileMeta { |
| 1531 | path: path.to_owned(), |
| 1532 | topic, |
| 1533 | slug, |
| 1534 | identity_hash: id_hash, |
| 1535 | published_date, |
| 1536 | entry_id, |
| 1537 | headline, |
| 1538 | summary, |
| 1539 | source_format: source_format.to_owned(), |
| 1540 | unbounded_private, |
| 1541 | indexable_fingerprint, |
| 1542 | redacted, |
| 1543 | }) |
| 1544 | } |
| 1545 | |
| 1546 | fn read_regular_markdown_file( |
| 1547 | path: &Path, |
| 1548 | expected_dev_ino: Option<(u64, u64)>, |
| 1549 | ) -> Result<String, String> { |
| 1550 | let lmeta = std::fs::symlink_metadata(path).map_err(|e| e.to_string())?; |
| 1551 | if lmeta.file_type().is_symlink() { |
| 1552 | return Err(format!("Refusing to follow symlink: {}", path.display())); |
| 1553 | } |
| 1554 | if !lmeta.file_type().is_file() { |
| 1555 | return Err(format!("Not a regular file: {}", path.display())); |
| 1556 | } |
| 1557 | |
| 1558 | let mut opts = std::fs::OpenOptions::new(); |
| 1559 | opts.read(true); |
| 1560 | #[cfg(unix)] |
| 1561 | { |
| 1562 | use std::os::unix::fs::OpenOptionsExt as _; |
| 1563 | // O_NOFOLLOW prevents TOCTOU symlink swaps; O_NONBLOCK prevents blocking on a swapped FIFO. |
| 1564 | opts.custom_flags(unix_open_flags()); |
| 1565 | } |
| 1566 | let file = opts.open(path).map_err(|e| e.to_string())?; |
| 1567 | let meta = file.metadata().map_err(|e| e.to_string())?; |
| 1568 | if !meta.file_type().is_file() { |
| 1569 | return Err(format!("Not a regular file: {}", path.display())); |
| 1570 | } |
| 1571 | #[cfg(unix)] |
| 1572 | { |
| 1573 | use std::os::unix::fs::MetadataExt as _; |
| 1574 | if (meta.dev(), meta.ino()) != (lmeta.dev(), lmeta.ino()) { |
| 1575 | return Err(format!("File changed during open: {}", path.display())); |
| 1576 | } |
| 1577 | if let Some((exp_dev, exp_ino)) = expected_dev_ino { |
| 1578 | if (meta.dev(), meta.ino()) != (exp_dev, exp_ino) { |
| 1579 | return Err(format!("File changed during open: {}", path.display())); |
| 1580 | } |
| 1581 | } |
| 1582 | } |
| 1583 | #[cfg(not(unix))] |
| 1584 | let _ = expected_dev_ino; |
| 1585 | |
| 1586 | if meta.len() > MAX_LIBRARY_FILE_BYTES { |
| 1587 | return Err(format!("file exceeds {MAX_LIBRARY_FILE_BYTES} byte limit")); |
| 1588 | } |
| 1589 | |
| 1590 | let mut raw = Vec::new(); |
| 1591 | let limit_plus_one = MAX_LIBRARY_FILE_BYTES + 1; |
| 1592 | let mut handle = File::take(file, limit_plus_one); |
| 1593 | handle.read_to_end(&mut raw).map_err(|e| e.to_string())?; |
| 1594 | if u64::try_from(raw.len()).unwrap_or(u64::MAX) > MAX_LIBRARY_FILE_BYTES { |
| 1595 | return Err(format!("file exceeds {MAX_LIBRARY_FILE_BYTES} byte limit")); |
| 1596 | } |
| 1597 | |
| 1598 | let text = String::from_utf8(raw).map_err(|e| e.to_string())?; |
| 1599 | if text.contains('\r') { |
| 1600 | Ok(text.replace("\r\n", "\n").replace('\r', "\n")) |
| 1601 | } else { |
| 1602 | Ok(text) |
| 1603 | } |
| 1604 | } |
| 1605 | |
| 1606 | #[cfg(unix)] |
| 1607 | const fn unix_open_flags() -> i32 { |
| 1608 | #[cfg(target_os = "macos")] |
| 1609 | { |
| 1610 | // O_NOFOLLOW (0x0100) | O_NONBLOCK (0x0004) |
| 1611 | 0x0100 | 0x0004 |
| 1612 | } |
| 1613 | #[cfg(target_os = "linux")] |
| 1614 | { |
| 1615 | #[cfg(any(target_arch = "aarch64", target_arch = "arm"))] |
| 1616 | { |
| 1617 | // O_NOFOLLOW (0o100000) | O_NONBLOCK (0o4000) |
| 1618 | 0o100_000 | 0o4000 |
| 1619 | } |
| 1620 | #[cfg(not(any(target_arch = "aarch64", target_arch = "arm")))] |
| 1621 | { |
| 1622 | // O_NOFOLLOW (0o400000) | O_NONBLOCK (0o4000) |
| 1623 | 0o400_000 | 0o4000 |
| 1624 | } |
| 1625 | } |
| 1626 | #[cfg(not(any(target_os = "macos", target_os = "linux")))] |
| 1627 | { |
| 1628 | 0 |
| 1629 | } |
| 1630 | } |
| 1631 | |
| 1632 | /// Reads, sanitizes, extracts metadata, and fingerprints a batch of saved Markdown |
| 1633 | /// files in parallel using Rayon. |
| 1634 | pub fn scan_markdown_files_batch(requests: &[MarkdownFileRequest]) -> Vec<MarkdownScanOutcome> { |
| 1635 | requests |
| 1636 | .par_iter() |
| 1637 | .map(|req| { |
| 1638 | let path = Path::new(&req.path); |
| 1639 | let content = match read_regular_markdown_file(path, req.expected_dev_ino) { |
| 1640 | Ok(text) => text, |
| 1641 | Err(reason) => { |
| 1642 | return MarkdownScanOutcome::Skipped { |
| 1643 | path: req.path.clone(), |
| 1644 | reason, |
| 1645 | }; |
| 1646 | } |
| 1647 | }; |
| 1648 | match parse_markdown_meta( |
| 1649 | &content, |
| 1650 | &req.path, |
| 1651 | &req.stem, |
| 1652 | &req.source_format, |
| 1653 | &req.fallback_date, |
| 1654 | ) { |
| 1655 | Ok(meta) => MarkdownScanOutcome::Ok { meta }, |
| 1656 | Err(err) => MarkdownScanOutcome::Skipped { |
| 1657 | path: req.path.clone(), |
| 1658 | reason: err.to_string(), |
| 1659 | }, |
| 1660 | } |
| 1661 | }) |
| 1662 | .collect() |
| 1663 | } |
| 1664 |