返回 last30days-skill
test_corpus_source.py
根目录 / tests / test_corpus_source.py
1 from __future__ import annotations
2
3 import hashlib
4 import io
5 import json
6 import os
7 import sqlite3
8 import sys
9 from contextlib import redirect_stderr, redirect_stdout
10 from dataclasses import replace
11 from datetime import datetime, timezone
12 from pathlib import Path
13 from unittest import mock
14
15 import pytest
16
17 import last30days as cli
18 import store
19 from lib import corpus, env, health, html_render, library, library_index, pipeline, render, schema
20
21
22 def _set_mtime(path: Path, value: str) -> None:
23 timestamp = datetime.fromisoformat(value).replace(tzinfo=timezone.utc).timestamp()
24 os.utime(path, (timestamp, timestamp))
25
26
27 def _scan(tmp_path: Path, *, all_time: bool = False, limit: int = 12):
28 return corpus.search(
29 "MCP servers",
30 [tmp_path],
31 from_date="2026-06-10",
32 to_date="2026-07-10",
33 all_time=all_time,
34 limit=limit,
35 cache_dir=tmp_path / "cache",
36 )
37
38
39 def test_scans_matching_text_and_markdown_with_path_titles(tmp_path):
40 note = tmp_path / "mcp-server-notes.md"
41 note.write_text("MCP servers expose tools to local coding agents.", encoding="utf-8")
42 other = tmp_path / "groceries.txt"
43 other.write_text("milk eggs bread", encoding="utf-8")
44 _set_mtime(note, "2026-07-05T12:00:00")
45 _set_mtime(other, "2026-07-05T12:00:00")
46
47 result = _scan(tmp_path)
48
49 assert [item.title for item in result.items] == ["mcp server notes"]
50 assert result.items[0].source == "corpus"
51 assert result.items[0].published_at == "2026-07-05"
52 assert result.items[0].metadata["local_only"] is True
53 assert result.items[0].url.startswith("corpus://")
54 assert str(note) not in result.items[0].url
55
56
57 def test_multilingual_matching_reuses_shared_cjk_tokenizer(tmp_path):
58 note = tmp_path / "模型记录.md"
59 note.write_text("国产大模型的最新测评和部署记录", encoding="utf-8")
60 _set_mtime(note, "2026-07-05T12:00:00")
61
62 result = corpus.search(
63 "国产大模型 测评",
64 [tmp_path],
65 from_date="2026-06-10",
66 to_date="2026-07-10",
67 cache_dir=tmp_path / "cache",
68 )
69
70 assert [item.title for item in result.items] == ["模型记录"]
71
72
73 def test_recency_window_and_all_time_override(tmp_path):
74 old = tmp_path / "old-mcp-plan.md"
75 old.write_text("MCP servers and local tool protocols", encoding="utf-8")
76 _set_mtime(old, "2025-01-01T00:00:00")
77
78 assert _scan(tmp_path).items == []
79 assert [item.title for item in _scan(tmp_path, all_time=True).items] == ["old mcp plan"]
80
81
82 def test_hidden_git_and_node_modules_directories_are_ignored(tmp_path):
83 visible = tmp_path / "visible.md"
84 visible.write_text("MCP servers are visible", encoding="utf-8")
85 _set_mtime(visible, "2026-07-05T00:00:00")
86 for directory in (tmp_path / ".git", tmp_path / ".hidden", tmp_path / "node_modules"):
87 directory.mkdir()
88 path = directory / "private.md"
89 path.write_text("MCP servers hidden secret", encoding="utf-8")
90 _set_mtime(path, "2026-07-05T00:00:00")
91
92 result = _scan(tmp_path)
93
94 assert [item.metadata["relative_path"] for item in result.items] == ["visible.md"]
95
96
97 def test_pdf_is_skipped_with_one_note_when_pdftotext_is_absent(tmp_path, monkeypatch):
98 pdf = tmp_path / "mcp.pdf"
99 pdf.write_bytes(b"not a real pdf")
100 _set_mtime(pdf, "2026-07-05T00:00:00")
101 monkeypatch.setattr(corpus, "which", lambda _name: None)
102
103 result = _scan(tmp_path)
104
105 assert result.items == []
106 assert result.notes == ["Skipped PDF files because pdftotext is not on PATH"]
107
108
109 def test_mtime_cache_reuses_text_and_is_private(tmp_path, monkeypatch):
110 note = tmp_path / "mcp.md"
111 note.write_text("MCP servers cache this local note", encoding="utf-8")
112 _set_mtime(note, "2026-07-05T00:00:00")
113 first = _scan(tmp_path)
114 assert first.cache_hits == 0
115
116 monkeypatch.setattr(corpus, "_extract_text", mock.Mock(side_effect=AssertionError("cache miss")))
117 second = _scan(tmp_path)
118
119 assert second.cache_hits == 1
120 cache_path = tmp_path / "cache" / corpus.CACHE_FILENAME
121 assert cache_path.stat().st_mode & 0o777 == 0o600
122 assert cache_path.parent.stat().st_mode & 0o777 == 0o700
123
124
125 def test_cache_for_500_large_documents_is_bounded_by_total_bytes(tmp_path, monkeypatch):
126 for index in range(500):
127 (tmp_path / f"document-{index:03d}.txt").touch()
128
129 monkeypatch.setattr(corpus, "MAX_CACHE_BYTES", 1_000_000)
130 monkeypatch.setattr(corpus, "MAX_CACHE_TEXT_CHARS", 100_000)
131 monkeypatch.setattr(corpus, "_extract_text", lambda *_args, **_kwargs: "x" * 1_000_000)
132 monkeypatch.setattr(corpus, "_match_score", lambda *_args, **_kwargs: 0.0)
133
134 result = corpus.search(
135 "anything",
136 [tmp_path],
137 from_date="2026-06-10",
138 to_date="2026-07-10",
139 all_time=True,
140 limit=0,
141 cache_dir=tmp_path / "cache",
142 )
143
144 cache_path = tmp_path / "cache" / corpus.CACHE_FILENAME
145 payload = json.loads(cache_path.read_text(encoding="utf-8"))
146 assert result.files_scanned == 500
147 assert cache_path.stat().st_size <= corpus.MAX_CACHE_BYTES
148 assert len(payload["entries"]) < 500
149 assert all(
150 len(entry["text"]) <= corpus.MAX_CACHE_TEXT_CHARS
151 for entry in payload["entries"].values()
152 )
153
154
155 def test_result_budget_caps_one_corpus_stream(tmp_path):
156 for index in range(10):
157 path = tmp_path / f"mcp-{index}.md"
158 path.write_text(f"MCP servers local note {index}", encoding="utf-8")
159 _set_mtime(path, f"2026-07-{index + 1:02d}T00:00:00")
160
161 assert len(_scan(tmp_path, limit=3).items) == 3
162
163
164 def test_file_cap_is_shared_fairly_across_corpus_roots(tmp_path, monkeypatch):
165 archive = tmp_path / "archive"
166 relevant = tmp_path / "relevant"
167 archive.mkdir()
168 relevant.mkdir()
169 for index in range(4):
170 (archive / f"mcp-archive-{index}.md").write_text(
171 f"MCP servers archived note {index}", encoding="utf-8"
172 )
173 later = relevant / "mcp-current.md"
174 later.write_text("MCP servers relevant current note", encoding="utf-8")
175 monkeypatch.setattr(corpus, "MAX_FILES", 4)
176
177 result = corpus.search(
178 "MCP servers",
179 [archive, relevant],
180 from_date="2026-06-10",
181 to_date="2026-07-10",
182 all_time=True,
183 cache_dir=tmp_path / "cache",
184 )
185
186 assert result.files_scanned <= corpus.MAX_FILES
187 assert any(item.metadata["path"].startswith(str(archive)) for item in result.items)
188 assert any(item.metadata["path"] == str(later) for item in result.items)
189
190
191 def test_pipeline_runs_corpus_outside_network_executor(tmp_path, monkeypatch):
192 note = tmp_path / "mcp-private.md"
193 note.write_text("MCP servers use a secret local transport", encoding="utf-8")
194 _set_mtime(note, "2026-07-05T00:00:00")
195 retrieve = mock.Mock(return_value=([], {}))
196 monkeypatch.setattr(pipeline, "_retrieve_stream", retrieve)
197
198 report = pipeline.run(
199 topic="MCP servers",
200 config={"_CORPUS_DIRS": [str(tmp_path)], "EXCLUDE_SOURCES": ""},
201 depth="quick",
202 requested_sources=["corpus"],
203 mock=True,
204 as_of_date="2026-07-10",
205 external_plan={
206 "intent": "concept",
207 "freshness_mode": "balanced_recent",
208 "cluster_mode": "none",
209 "source_weights": {"corpus": 1.0},
210 "subqueries": [{
211 "label": "primary",
212 "search_query": "MCP servers",
213 "ranking_query": "MCP servers",
214 "sources": ["corpus"],
215 }],
216 },
217 )
218
219 assert report.source_status["corpus"].state == health.OK
220 assert len(report.items_by_source["corpus"]) == 1
221 assert len(report.items_by_source["corpus"]) <= pipeline.DEPTH_SETTINGS["quick"]["per_stream_limit"]
222 assert all(call.kwargs["source"] != "corpus" for call in retrieve.call_args_list)
223
224
225 def test_corpus_never_enters_remote_rerank_or_fun_prompts(tmp_path, monkeypatch):
226 note = tmp_path / "private.md"
227 note.write_text("Model context protocol servers PRIVATE-RERANK-SENTINEL", encoding="utf-8")
228 _set_mtime(note, "2026-07-05T00:00:00")
229 remote = mock.Mock()
230 remote.generate_json = mock.Mock(side_effect=AssertionError("private prompt left machine"))
231 runtime = schema.ProviderRuntime("local", "remote-planner", "remote-reranker")
232 monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *_args, **_kwargs: (runtime, remote))
233 monkeypatch.setattr(pipeline, "available_sources", lambda *_args, **_kwargs: ["corpus"])
234
235 report = pipeline.run(
236 topic="how do model context protocol servers work today?",
237 config={"_CORPUS_DIRS": [str(tmp_path)], "EXCLUDE_SOURCES": ""},
238 depth="quick",
239 requested_sources=["corpus"],
240 mock=False,
241 as_of_date="2026-07-10",
242 external_plan={
243 "intent": "how_to",
244 "freshness_mode": "evergreen_ok",
245 "cluster_mode": "workflow",
246 "source_weights": {"corpus": 1.0},
247 "subqueries": [{
248 "label": "primary",
249 "search_query": "model context protocol servers",
250 "ranking_query": "How do model context protocol servers work?",
251 "sources": ["corpus"],
252 }],
253 },
254 )
255
256 assert report.items_by_source["corpus"]
257 remote.generate_json.assert_not_called()
258
259
260 def test_explicit_unconfigured_corpus_records_skipped_outcome():
261 report = pipeline.run(
262 topic="how do local model context protocol servers work?",
263 config={"EXCLUDE_SOURCES": ""},
264 depth="quick",
265 requested_sources=["corpus"],
266 mock=True,
267 as_of_date="2026-07-10",
268 external_plan={
269 "intent": "how_to",
270 "freshness_mode": "evergreen_ok",
271 "cluster_mode": "workflow",
272 "source_weights": {"corpus": 1.0},
273 "subqueries": [{
274 "label": "primary",
275 "search_query": "model context protocol servers",
276 "ranking_query": "How do model context protocol servers work?",
277 "sources": ["corpus"],
278 }],
279 },
280 )
281
282 outcome = report.source_status["corpus"]
283 assert outcome.state == schema.SKIPPED_UNCONFIGURED
284 assert outcome.attempted is False
285
286
287 def _privacy_report(secret: str = "PRIVATE-CORPUS-SENTINEL") -> schema.Report:
288 item = schema.SourceItem(
289 item_id="C-private",
290 source="corpus",
291 title="private mcp notes",
292 body=f"MCP servers {secret}",
293 url="",
294 published_at="2026-07-05",
295 snippet=f"MCP servers {secret}",
296 metadata={"relative_path": "notes/private.md", "local_only": True},
297 )
298 candidate = schema.Candidate(
299 candidate_id="corpus:C-private",
300 item_id=item.item_id,
301 source="corpus",
302 title=item.title,
303 url="",
304 snippet=item.snippet,
305 subquery_labels=["primary"],
306 native_ranks={"primary:corpus": 1},
307 local_relevance=1.0,
308 freshness=90,
309 engagement=None,
310 source_quality=0.75,
311 rrf_score=0.01,
312 final_score=91,
313 cluster_id="cluster-private",
314 sources=["corpus"],
315 source_items=[item],
316 )
317 return schema.Report(
318 topic="MCP servers",
319 range_from="2026-06-10",
320 range_to="2026-07-10",
321 generated_at="2026-07-10T00:00:00+00:00",
322 provider_runtime=schema.ProviderRuntime("local", "mock", "mock"),
323 query_plan=schema.QueryPlan(
324 intent="concept",
325 freshness_mode="balanced_recent",
326 cluster_mode="none",
327 raw_topic="MCP servers",
328 subqueries=[schema.SubQuery("primary", "MCP servers", "MCP servers", ["corpus"])],
329 source_weights={"corpus": 1.0},
330 ),
331 clusters=[schema.Cluster(
332 cluster_id="cluster-private",
333 title=f"Private cluster {secret}",
334 candidate_ids=[candidate.candidate_id],
335 representative_ids=[candidate.candidate_id],
336 sources=["corpus"],
337 score=91,
338 )],
339 ranked_candidates=[candidate],
340 items_by_source={"corpus": [item]},
341 errors_by_source={},
342 source_status={"corpus": schema.SourceOutcome("corpus", health.OK, 1)},
343 )
344
345
346 def test_corpus_findings_persist_with_stable_opaque_keys(tmp_path, monkeypatch):
347 note = tmp_path / "private-customer-notes.md"
348 note.write_text("MCP servers persist this private finding", encoding="utf-8")
349 first = corpus.search(
350 "MCP servers",
351 [tmp_path],
352 from_date="2026-06-10",
353 to_date="2026-07-10",
354 all_time=True,
355 cache_dir=tmp_path / "cache",
356 ).items[0]
357 second = corpus.search(
358 "MCP servers",
359 [tmp_path],
360 from_date="2026-06-10",
361 to_date="2026-07-10",
362 all_time=True,
363 cache_dir=tmp_path / "cache",
364 ).items[0]
365 report = _privacy_report()
366 report.items_by_source["corpus"][0].url = first.url
367 report.ranked_candidates[0].url = first.url
368
369 db_path = tmp_path / "research.db"
370 monkeypatch.setattr(store, "_db_override", db_path)
371 store.init_db()
372 topic = store.add_topic(report.topic)
373 run_id = store.record_run(topic["id"], status="completed")
374 findings = store.findings_from_report(report)
375 counts = store.store_findings(run_id, topic["id"], findings)
376
377 assert first.url == second.url
378 assert first.url.startswith("corpus://")
379 assert str(note) not in first.url
380 assert counts == {"new": 1, "updated": 0}
381 with sqlite3.connect(db_path) as conn:
382 persisted = conn.execute(
383 "SELECT source, source_url FROM findings"
384 ).fetchone()
385 assert persisted == ("corpus", first.url)
386 assert library_index.search(
387 "private finding",
388 db_path=tmp_path / "missing-library.db",
389 store_db_path=db_path,
390 ) == []
391
392
393 def test_persist_report_hardens_corpus_store_and_sidecars(tmp_path, monkeypatch):
394 db_path = tmp_path / "store" / "research.db"
395 monkeypatch.setattr(store, "_db_override", db_path)
396 original_findings_from_report = store.findings_from_report
397 original_store_findings = store.store_findings
398 original_update_run = store.update_run
399
400 def make_permissive():
401 db_path.chmod(0o644)
402 for suffix in ("-wal", "-shm"):
403 sidecar = Path(f"{db_path}{suffix}")
404 sidecar.touch(mode=0o644)
405 sidecar.chmod(0o644)
406
407 def findings_from_report_with_permissive_store(*args, **kwargs):
408 findings = original_findings_from_report(*args, **kwargs)
409 make_permissive()
410 return findings
411
412 def store_findings_after_private_check(*args, **kwargs):
413 for artifact in (db_path, Path(f"{db_path}-wal"), Path(f"{db_path}-shm")):
414 assert artifact.stat().st_mode & 0o777 == 0o600
415 return original_store_findings(*args, **kwargs)
416
417 def update_run_with_permissive_sidecars(*args, **kwargs):
418 result = original_update_run(*args, **kwargs)
419 make_permissive()
420 return result
421
422 monkeypatch.setattr(store, "findings_from_report", findings_from_report_with_permissive_store)
423 monkeypatch.setattr(store, "store_findings", store_findings_after_private_check)
424 monkeypatch.setattr(store, "update_run", update_run_with_permissive_sidecars)
425
426 cli.persist_report(_privacy_report())
427
428 for artifact in (db_path, Path(f"{db_path}-wal"), Path(f"{db_path}-shm")):
429 assert artifact.stat().st_mode & 0o777 == 0o600
430
431
432 def test_agent_export_excludes_corpus_by_default_and_allows_explicit_opt_in():
433 report = _privacy_report()
434
435 private_default = schema.to_agent_export(report)
436 opted_in = schema.to_agent_export(report, corpus_in_export=True)
437
438 assert private_default["results"] == []
439 assert private_default["clusters"] == []
440 assert "corpus" not in private_default["source_status"]
441 assert opted_in["results"][0]["source"] == "corpus"
442 assert "PRIVATE-CORPUS-SENTINEL" in opted_in["results"][0]["summary"]
443
444 report.artifacts["corpus_in_export"] = True
445 assert schema.to_agent_export(report)["results"][0]["source"] == "corpus"
446
447
448 def test_agent_export_rebuilds_mixed_cluster_title_after_private_representative_removed():
449 report = _privacy_report()
450 social_item = schema.SourceItem(
451 item_id="R-public",
452 source="reddit",
453 title="Public MCP discussion",
454 body="Public evidence",
455 url="https://reddit.example/public",
456 published_at="2026-07-06",
457 snippet="Public evidence",
458 )
459 social = schema.Candidate(
460 candidate_id="reddit:public",
461 item_id=social_item.item_id,
462 source="reddit",
463 title=social_item.title,
464 url=social_item.url,
465 snippet=social_item.snippet,
466 subquery_labels=["primary"],
467 native_ranks={"primary:reddit": 1},
468 local_relevance=0.8,
469 freshness=90,
470 engagement=1,
471 source_quality=0.6,
472 rrf_score=0.01,
473 final_score=80,
474 cluster_id="cluster-private",
475 sources=["reddit"],
476 source_items=[social_item],
477 )
478 report.ranked_candidates.append(social)
479 report.items_by_source["reddit"] = [social_item]
480 report.source_status["reddit"] = schema.SourceOutcome("reddit", health.OK, 1)
481 report.clusters[0].candidate_ids.append(social.candidate_id)
482 report.clusters[0].representative_ids.append(social.candidate_id)
483 report.clusters[0].sources.append("reddit")
484
485 exported = schema.to_agent_export(report)
486
487 assert exported["clusters"][0]["title"] == "Public MCP discussion"
488 assert "PRIVATE-CORPUS-SENTINEL" not in str(exported)
489
490
491 def test_local_report_has_badged_from_your_files_section():
492 rendered = render.render_compact(_privacy_report())
493
494 assert "## From your files" in rendered
495 assert "LOCAL ONLY" in rendered
496 assert "PRIVATE-CORPUS-SENTINEL" in rendered
497
498
499 def test_publish_html_sends_sanitized_report_not_local_corpus(monkeypatch):
500 report = _privacy_report()
501 captured: dict[str, str] = {}
502
503 def publish(rendered, **_kwargs):
504 captured["html"] = rendered
505 return {"url": "https://example.ht-ml.app"}
506
507 monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
508 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: {"available_sources": ["corpus"]})
509 monkeypatch.setattr(cli.pipeline, "run", lambda **_kwargs: report)
510 monkeypatch.setattr(cli, "publish_rendered_html", publish)
511 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
512 monkeypatch.setattr(
513 sys,
514 "argv",
515 ["last30days.py", "MCP servers", "--emit=html", "--publish-html"],
516 )
517
518 with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
519 assert cli.main() == 0
520
521 assert "PRIVATE-CORPUS-SENTINEL" not in captured["html"]
522 assert "private mcp notes" not in captured["html"]
523
524
525 def test_configured_corpus_bypasses_hosted_backend(tmp_path, monkeypatch):
526 report = _privacy_report()
527 hosted = mock.Mock(side_effect=AssertionError("local corpus was forwarded"))
528 monkeypatch.setattr("lib.hosted.run_hosted", hosted)
529 monkeypatch.setattr(
530 cli.env,
531 "get_config",
532 lambda **_kwargs: {"LAST30DAYS_CORPUS_DIRS": str(tmp_path)},
533 )
534 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: {"available_sources": ["corpus"]})
535 monkeypatch.setattr(cli.pipeline, "run", lambda **_kwargs: report)
536 monkeypatch.setenv("LAST30DAYS_API_KEY", "test-hosted-key")
537 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://example.invalid")
538 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
539 monkeypatch.setattr(sys, "argv", ["last30days.py", "MCP servers", "--emit=compact"])
540
541 with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
542 assert cli.main() == 0
543
544 hosted.assert_not_called()
545
546
547 def test_library_publish_strips_marked_corpus_but_local_page_keeps_it(tmp_path, monkeypatch):
548 markdown = render.render_full(_privacy_report())
549 (tmp_path / "mcp-raw.md").write_text(markdown, encoding="utf-8")
550 monkeypatch.setattr(library, "DEFAULT_BRIEFS_DIR", tmp_path / "no-briefings")
551 monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
552 publish_many = mock.Mock(return_value={})
553 monkeypatch.setattr("lib.html_publish.publish_html_documents", publish_many)
554 monkeypatch.setattr("lib.html_publish.publish_html", mock.Mock(return_value={"url": "https://library.ht-ml.app"}))
555 monkeypatch.setattr(
556 sys,
557 "argv",
558 ["last30days.py", "library", "feed", "--save-dir", str(tmp_path), "--publish"],
559 )
560
561 with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
562 assert cli.main() == 0
563
564 published_documents = publish_many.call_args.args[0]
565 assert published_documents
566 assert all("PRIVATE-CORPUS-SENTINEL" not in html for html in published_documents.values())
567 local_pages = list((tmp_path / "briefs").glob("*.html"))
568 assert local_pages
569 assert "PRIVATE-CORPUS-SENTINEL" in local_pages[0].read_text(encoding="utf-8")
570 assert local_pages[0].stat().st_mode & 0o777 == 0o600
571 assert local_pages[0].parent.stat().st_mode & 0o777 == 0o700
572
573
574 @pytest.mark.parametrize("include_drill_context", [True, False], ids=["compact", "full"])
575 def test_legacy_drill_sections_are_local_only_in_library_briefs_and_search(tmp_path, monkeypatch, include_drill_context):
576 memory = tmp_path / "memory"
577 memory.mkdir()
578 raw = memory / "mcp-raw.md"
579 drill = """## Drill Follow-up
580
581 - Target: Local routing notes
582 - Matched: Local routing notes
583
584 ### Original
585
586 ### 1. Local drafthead
587
588 The saved private excerpt refers to a prior report:
589
590 ### Deeper
591
592 - 1 new items after dedupe
593 - Re-researched sources: Your files
594
595 More private draftbody.
596
597 ### Deeper
598
599 - 2 new items after dedupe
600 - Re-researched sources: Reddit
601
602 """ if include_drill_context else ""
603 raw.write_text(
604 f"""# last30days: MCP servers
605
606 - Sources: 2 active (Reddit, Your files)
607
608 {drill}## Ranked Evidence Clusters
609
610 ### 1. Local legacyclusterhead (score 91, 1 item, sources: Reddit)
611 1. [reddit] Public router design
612 - Evidence: The router uses stable route identifiers.
613 - URL: https://example.test/router
614
615 ### 2. Local unclassifiedheading (score 83, 1 item, sources: Reddit)
616 - Coverage: Public route metadata is available.
617
618 ## Freshness Verification
619
620 | Verdict | Claim | Evidence | Checked |
621 | --- | --- | --- | --- |
622 | **contradicted** | Private draftstatus (Newer corpus item disagrees) | [2026-07-05](corpus://notes) | 2026-07-08 |
623 | **unsupported** | Private unsupportednote
624 Private continuednote | source | 2026-07-08 |
625 | **contradicted** | Private contradictednote (Newer reddit item disagrees) | [2026-07-05](https://example.test/status) | 2026-07-08 |
626 | **fresh** | Public deployment status | [2026-07-05](https://example.test/status) | 2026-07-08 |
627
628 ## Public release receipt
629
630 Public verification continues.
631 """,
632 encoding="utf-8",
633 )
634 entry = library._parse_markdown(raw)
635 public_raw = memory / "public-raw.md"
636 public_raw.write_text(
637 """# last30days: Public release
638
639 ## Ranked Evidence Clusters
640
641 ### 1. Public legacy headline (score 90, 1 item, sources: Reddit)
642 1. [reddit] Public legacy representative
643
644 ## Freshness Verification
645
646 | Verdict | Claim | Evidence | Checked |
647 | --- | --- | --- | --- |
648 | **fresh** | Public-only verification | [2026-07-05](https://example.test/status) | 2026-07-08 |
649 """,
650 encoding="utf-8",
651 )
652 public_entry = library._parse_markdown(public_raw)
653 marked_raw = memory / "marked-raw.md"
654 marked_raw.write_text(
655 f"""# last30days: Marked release
656
657 - Sources: 2 active (Reddit, Your files)
658
659 {library.PUBLIC_CLUSTERS_MARKER}
660 ## Ranked Evidence Clusters
661
662 ### 1. Public marked headline (score 90, 1 item, sources: Reddit)
663 1. [reddit] Public marked representative
664 """,
665 encoding="utf-8",
666 )
667 marked_entry = library._parse_markdown(marked_raw)
668 publish_many = mock.Mock(return_value={})
669 monkeypatch.setattr("lib.html_publish.publish_html_documents", publish_many)
670 monkeypatch.setattr("lib.html_publish.publish_html", mock.Mock(return_value={"url": "https://example.test/index"}))
671 args = cli.build_parser().parse_args(["library", "feed", "--save-dir", str(memory), "--publish"])
672 assert cli._run_library_feed(args, {}) == 0
673 local_path = memory / "briefs" / entry.output_name
674 local = local_path.read_text(encoding="utf-8")
675 published = publish_many.call_args.args[0][entry.entry_id]
676
677 assert entry.headline == "Public router design"
678 assert ("drafthead" in local and "draftbody" in local) == include_drill_context
679 assert "draftstatus" in local and "legacyclusterhead" in local and "unclassifiedheading" in local
680 assert "unsupportednote" in local and "continuednote" in local and "contradictednote" in local
681 assert local_path.stat().st_mode & 0o777 == 0o600
682 assert "drafthead" not in published and "draftbody" not in published and "draftstatus" not in published
683 assert "Public router design" in published
684 assert "legacyclusterhead" not in published and "unclassifiedheading" not in published
685 assert "The router uses stable route identifiers." in published
686 assert "Public route metadata is available." in published
687 assert "Freshness Verification" not in published
688 assert "continuednote" not in published
689 assert "Public verification continues." in published
690 assert "Public-only verification" in publish_many.call_args.args[0][public_entry.entry_id]
691 assert public_entry.headline == "Public legacy headline"
692 assert marked_entry.headline == "Public marked headline"
693 assert "Public marked headline" in publish_many.call_args.args[0][marked_entry.entry_id]
694
695 db_path = tmp_path / "library.db"
696 library_index.sync_library(memory, tmp_path / "no-briefings", db_path=db_path)
697 for term in (
698 "drafthead", "draftbody", "draftstatus", "unsupportednote", "continuednote", "contradictednote",
699 "legacyclusterhead", "unclassifiedheading",
700 ):
701 assert not library_index.search(term, db_path=db_path, store_db_path=tmp_path / "no-store.db")
702 assert library_index.search("router design", db_path=db_path, store_db_path=tmp_path / "no-store.db")
703 assert library_index.search("stable route identifiers", db_path=db_path, store_db_path=tmp_path / "no-store.db")
704
705
706 def test_legacy_production_brief_keeps_public_evidence_in_library_feed_and_search(tmp_path, monkeypatch):
707 memory = tmp_path / "memory"
708 memory.mkdir()
709 legacy_path = memory / "legacy-brief.md"
710 legacy_path.write_text(
711 """# Production Brief: Router deployment
712
713 - Sources: 2 active (Reddit, Your files)
714
715 ## Drill Follow-up
716
717 - Target: Router deployment
718
719 ### Original
720
721 Router notes.
722
723 ### Deeper
724
725 - 1 new items after dedupe
726 - Re-researched sources: Reddit, Your files
727
728 ## Ranked Storylines
729
730 ### 1. Private storylinehint (score 91, Reddit) [single source]
731 - Stable route identifiers simplify deployments.
732
733 ## Topic Tensions
734
735 - **Private tensionhint** [Single Source]: Reddit
736
737 ## Audience Questions
738
739 - How do stable route identifiers work?
740
741 ## Source Clusters
742
743 - **Private sourceclusterhint**: Reddit
744 """,
745 encoding="utf-8",
746 )
747 report = _privacy_report()
748 report.topic = "Current router brief"
749 local = report.ranked_candidates[0]
750 public = replace(
751 local, candidate_id="reddit:public", item_id="R-public", source="reddit",
752 title="Public deploy headline", snippet="The router uses a staged deployment.",
753 url="https://example.test/router", cluster_id="cluster-public", sources=["reddit"],
754 source_items=[schema.SourceItem(
755 item_id="R-public", source="reddit", title="Public deploy headline",
756 url="https://example.test/router", body="The router uses a staged deployment.",
757 )],
758 )
759 report.items_by_source["reddit"] = public.source_items
760 report.ranked_candidates.append(public)
761 report.clusters.append(schema.Cluster(
762 cluster_id="cluster-public", title="Public deploy headline", sources=["reddit"],
763 candidate_ids=[public.candidate_id], representative_ids=[public.candidate_id],
764 score=91, uncertainty="single-source",
765 ))
766 current_path = memory / "current-brief.md"
767 current_path.write_text(render.render_brief(report), encoding="utf-8")
768 public_report = schema.without_sources(report, {"corpus"})
769 public_report.topic = "Public-only router brief"
770 public_path = memory / "public-brief.md"
771 public_path.write_text(render.render_brief(public_report), encoding="utf-8")
772
773 publish_many = mock.Mock(return_value={})
774 monkeypatch.setattr("lib.html_publish.publish_html_documents", publish_many)
775 monkeypatch.setattr("lib.html_publish.publish_html", mock.Mock(return_value={"url": "https://example.test/index"}))
776 args = cli.build_parser().parse_args(["library", "feed", "--save-dir", str(memory), "--publish"])
777 assert cli._run_library_feed(args, {}) == 0
778 published = publish_many.call_args.args[0]
779 legacy_entry = library._parse_markdown(legacy_path)
780 legacy_html = published[legacy_entry.entry_id]
781 local_html = (memory / "briefs" / legacy_entry.output_name).read_text(encoding="utf-8")
782 assert "Stable route identifiers simplify deployments." in legacy_html
783 assert "How do stable route identifiers work?" in legacy_html
784 for path in (current_path, public_path):
785 assert published[library._parse_markdown(path).entry_id].count("Public deploy headline") >= 3
786 assert library.PUBLIC_CLUSTERS_MARKER not in public_path.read_text(encoding="utf-8")
787
788 db_path = tmp_path / "library.db"
789 library_index.sync_library(memory, tmp_path / "no-briefings", db_path=db_path)
790 for private in ("storylinehint", "tensionhint", "sourceclusterhint"):
791 assert private in local_html and private not in legacy_html
792 assert not library_index.search(private, db_path=db_path, store_db_path=tmp_path / "no-store.db")
793 assert library_index.search("stable route identifiers", db_path=db_path, store_db_path=tmp_path / "no-store.db")
794 assert library_index.search("public deploy headline", db_path=db_path, store_db_path=tmp_path / "no-store.db")
795
796
797 def test_private_corpus_cannot_escape_via_library_search_and_feed_publish(tmp_path, monkeypatch):
798 secret = "PRIVATE-CORPUS-ESCAPE-SENTINEL"
799 memory = tmp_path / "memory"
800 report = _privacy_report(secret)
801 with mock.patch.object(library_index, "sync_library"):
802 saved = cli.save_output(report, "md", str(memory))
803
804 db_path = tmp_path / "index" / "library.db"
805 library_index.sync_library(memory, tmp_path / "no-briefings", db_path=db_path)
806 entry = library._parse_markdown(saved)
807 legacy_hash = hashlib.sha256(entry.content.encode("utf-8")).hexdigest()
808 with sqlite3.connect(db_path) as conn:
809 conn.execute(
810 "UPDATE library_documents SET content_hash = ? WHERE entry_id = ?",
811 (legacy_hash, entry.entry_id),
812 )
813 conn.execute("DELETE FROM library_fts WHERE entry_id = ?", (entry.entry_id,))
814 conn.execute(
815 "INSERT INTO library_fts(entry_id, topic, headline, summary, content) "
816 "VALUES (?, ?, ?, ?, ?)",
817 (entry.entry_id, entry.topic, entry.headline, entry.summary, entry.content),
818 )
819 conn.commit()
820
821 rebuilt = library_index.sync_library(
822 memory,
823 tmp_path / "no-briefings",
824 db_path=db_path,
825 )
826 assert rebuilt.indexed == 1
827 assert library_index.search(
828 secret,
829 db_path=db_path,
830 store_db_path=tmp_path / "missing-store.db",
831 ) == []
832 matches = library_index.search(
833 "MCP servers",
834 db_path=db_path,
835 store_db_path=tmp_path / "missing-store.db",
836 )
837 assert matches
838 assert all(secret not in match.snippet for match in matches)
839
840 followup = schema.without_sources(report, {"corpus"})
841 followup.library_context = [
842 schema.LibraryContext(
843 topic=match.topic,
844 published_date=match.published_date.isoformat(),
845 headline=match.headline,
846 summary=match.snippet,
847 source_kind=match.source_kind,
848 )
849 for match in matches[:1]
850 ]
851 with mock.patch.object(library_index, "sync_library"):
852 cli.save_output(followup, "md", str(memory), suffix="followup")
853
854 monkeypatch.setattr(library, "DEFAULT_BRIEFS_DIR", tmp_path / "no-briefings")
855 monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
856 publish_many = mock.Mock(return_value={})
857 monkeypatch.setattr("lib.html_publish.publish_html_documents", publish_many)
858 monkeypatch.setattr(
859 "lib.html_publish.publish_html",
860 mock.Mock(return_value={"url": "https://library.ht-ml.app"}),
861 )
862 monkeypatch.setattr(
863 sys,
864 "argv",
865 ["last30days.py", "library", "feed", "--save-dir", str(memory), "--publish"],
866 )
867
868 with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
869 assert cli.main() == 0
870
871 published = publish_many.call_args.args[0]
872 assert published
873 assert all(secret not in document for document in published.values())
874
875
876 def test_configured_paths_use_platform_separator_and_dedupe(tmp_path):
877 first = tmp_path / "first"
878 second = tmp_path / "second"
879 resolved = corpus.resolve_directories(
880 [str(first)], f"{first}{os.pathsep}{second}"
881 )
882 assert resolved == [first.resolve(), second.resolve()]
883
884
885 def test_corpus_env_keys_are_registered(monkeypatch):
886 monkeypatch.setenv("LAST30DAYS_CORPUS_DIRS", "/tmp/notes:/tmp/transcripts")
887 monkeypatch.setenv("LAST30DAYS_CORPUS_IN_EXPORT", "1")
888 with mock.patch.object(env, "_load_keychain", return_value={}), mock.patch.object(
889 env, "_load_pass", return_value={}
890 ):
891 config = env.get_config()
892
893 assert config["LAST30DAYS_CORPUS_DIRS"] == "/tmp/notes:/tmp/transcripts"
894 assert config["LAST30DAYS_CORPUS_IN_EXPORT"] == "1"
895
896
897 def test_library_renderer_private_switch_is_load_bearing(tmp_path):
898 report_path = tmp_path / "mcp-raw.md"
899 report_path.write_text(render.render_full(_privacy_report()), encoding="utf-8")
900 entry = library._parse_markdown(report_path)
901
902 assert "PRIVATE-CORPUS-SENTINEL" in html_render.render_library_brief(entry)
903 assert "PRIVATE-CORPUS-SENTINEL" not in html_render.render_library_brief(
904 entry, include_private=False
905 )
906
907
908 def test_report_cache_with_corpus_is_written_private(tmp_path, monkeypatch):
909 config_dir = tmp_path / "private" / "config"
910 monkeypatch.setattr(cli.env, "CONFIG_DIR", config_dir)
911
912 assert cli._write_last_run("MCP servers", _privacy_report()) is True
913
914 assert (config_dir / "last-report.json").stat().st_mode & 0o777 == 0o600
915 assert config_dir.stat().st_mode & 0o777 == 0o700
916
917
918 def test_every_corpus_bearing_saved_artifact_is_owner_only(tmp_path):
919 report = _privacy_report()
920 markdown_dir = tmp_path / "private" / "markdown"
921 html_dir = tmp_path / "private" / "html"
922 with mock.patch.object(library_index, "sync_library"):
923 markdown = cli.save_output(report, "md", str(markdown_dir))
924 html = cli.save_output(report, "html", str(html_dir))
925 inferred_private = cli.save_output(
926 report, "compact", str(tmp_path / "private" / "inferred")
927 )
928 forced_public = cli.save_output(
929 report, "json", str(tmp_path / "private" / "forced-public"), private=False
930 )
931 explicit = cli.save_rendered_output(
932 cli.emit_output(report, "html"),
933 str(tmp_path / "private" / "explicit" / "report.html"),
934 private=True,
935 )
936
937 db_path = tmp_path / "private" / "index" / "library.db"
938 library_index.sync_library(
939 markdown_dir,
940 tmp_path / "no-briefings",
941 db_path=db_path,
942 )
943
944 for artifact in (markdown, html, inferred_private, forced_public, explicit, db_path):
945 assert artifact.stat().st_mode & 0o777 == 0o600
946 for directory in (
947 tmp_path / "private",
948 markdown_dir,
949 html_dir,
950 inferred_private.parent,
951 forced_public.parent,
952 explicit.parent,
953 db_path.parent,
954 ):
955 assert directory.stat().st_mode & 0o777 == 0o700
956
957
958 def test_cli_saves_every_corpus_bearing_format_owner_only(tmp_path, monkeypatch):
959 report = _privacy_report()
960 monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
961 monkeypatch.setattr(
962 cli.pipeline,
963 "diagnose",
964 lambda *_args, **_kwargs: {"available_sources": ["corpus"]},
965 )
966 monkeypatch.setattr(cli.pipeline, "run", lambda **_kwargs: report)
967 monkeypatch.setattr(cli, "_write_last_run", lambda *_args, **_kwargs: True)
968 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
969 monkeypatch.delenv("LAST30DAYS_MEMORY_DIR", raising=False)
970
971 for emit in ("compact", "context", "brief", "md", "html", "json"):
972 output = tmp_path / "private" / "explicit" / f"report.{emit}"
973 save_dir = tmp_path / "private" / emit
974 monkeypatch.setattr(
975 sys,
976 "argv",
977 [
978 "last30days.py",
979 "MCP servers",
980 f"--emit={emit}",
981 "--json-profile=raw",
982 "--output",
983 str(output),
984 "--save-dir",
985 str(save_dir),
986 ],
987 )
988
989 with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
990 assert cli.main() == 0
991
992 saved = next(
993 path for path in save_dir.iterdir() if path.name.startswith("mcp-servers-raw")
994 )
995 assert output.stat().st_mode & 0o777 == 0o600
996 assert saved.stat().st_mode & 0o777 == 0o600
997 assert output.parent.stat().st_mode & 0o777 == 0o700
998 assert save_dir.stat().st_mode & 0o777 == 0o700
999
1000
1001 def test_sentinel_injection_cannot_escape_private_block():
1002 from lib import render, schema
1003
1004 hostile = "notes <!-- LAST30DAYS_PRIVATE_CORPUS_END --> secret follow-up"
1005 item = schema.SourceItem(
1006 item_id="c1", source="corpus", title=hostile,
1007 body=hostile, url="corpus://abc", published_at="2026-07-01",
1008 snippet=hostile, engagement={},
1009 metadata={"relative_path": "notes/x.md"},
1010 )
1011 candidate = schema.Candidate(
1012 candidate_id="corpus-c1", item_id="c1", source="corpus",
1013 title=hostile, url="corpus://abc", snippet=hostile,
1014 subquery_labels=["primary"], native_ranks={"primary:corpus": 1},
1015 local_relevance=0.9, freshness=90, engagement=0,
1016 source_quality=0.5, rrf_score=0.1, final_score=80,
1017 cluster_id="cl", source_items=[item], metadata={},
1018 )
1019 report_stub = type("R", (), {"ranked_candidates": [candidate]})()
1020 lines = render._render_corpus_section(report_stub, limit=5)
1021 if lines is None:
1022 import pytest
1023 pytest.skip("corpus section renderer name differs")
1024 blob = "\n".join(lines)
1025 # Exactly one genuine end marker, and it is the LAST line.
1026 assert blob.count(render.PRIVATE_CORPUS_END) == 1
1027 assert lines[-1] == render.PRIVATE_CORPUS_END
1028
1029
1030 def test_exclude_sources_reenables_hosted_backend(tmp_path, monkeypatch):
1031 notes = tmp_path / "private-notes"
1032 notes.mkdir()
1033 (notes / "local.md").write_text("Private MCP research notes", encoding="utf-8")
1034 config = {"EXCLUDE_SOURCES": "corpus", "LAST30DAYS_CORPUS_DIRS": str(notes)}
1035 monkeypatch.setattr(env, "get_config", lambda **_kwargs: config)
1036 monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key")
1037 monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example.test")
1038 hosted_run = mock.Mock(return_value=0)
1039 monkeypatch.setattr("lib.hosted.run_hosted", hosted_run)
1040 local_run = mock.Mock(return_value=_privacy_report())
1041 monkeypatch.setattr(cli.pipeline, "run", local_run)
1042 monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: {"available_sources": ["corpus"]})
1043 monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path / "config")
1044 monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
1045 monkeypatch.setattr(sys, "argv", [
1046 "last30days.py", "MCP servers", "--quick", "--emit=compact", "--save-dir=",
1047 ])
1048
1049 assert cli.main() == 0
1050
1051 hosted_run.assert_called_once_with(
1052 "MCP servers", "quick", emit="compact", save_dir="", save_suffix="",
1053 )
1054 local_run.assert_not_called()
1055
1056
1057 def test_corpus_notes_never_contain_absolute_paths(tmp_path):
1058 import os
1059 import stat
1060 from lib import corpus
1061
1062 root = tmp_path / "private-notes"
1063 root.mkdir()
1064 good = root / "readable.md"
1065 good.write_text("# Note about quantum widgets\n", encoding="utf-8")
1066 blocked = root / "blocked"
1067 blocked.mkdir()
1068 (blocked / "secret.md").write_text("# hidden\n", encoding="utf-8")
1069 os.chmod(blocked, 0)
1070 try:
1071 result = corpus.search("quantum widgets", [root], from_date="2026-06-11", to_date="2026-07-11", all_time=True, cache_dir=tmp_path / "cache")
1072 for note in result.notes:
1073 assert str(tmp_path) not in note, f"absolute path leaked in note: {note}"
1074 finally:
1075 os.chmod(blocked, stat.S_IRWXU)
1076
1077
1078 def test_scan_error_notes_never_echo_absolute_paths(tmp_path, monkeypatch):
1079 note = tmp_path / "mcp-server-notes.md"
1080 note.write_text("MCP servers expose tools to local coding agents.", encoding="utf-8")
1081 _set_mtime(note, "2026-07-05T12:00:00")
1082
1083 def raising_extract(path, *, pdftotext):
1084 raise PermissionError(13, "Permission denied", str(path))
1085
1086 monkeypatch.setattr(corpus, "_extract_text", raising_extract)
1087
1088 result = _scan(tmp_path)
1089
1090 assert result.items == []
1091 assert result.notes, "expected a skip note"
1092 joined = " ".join(result.notes)
1093 assert str(tmp_path) not in joined
1094 assert "Permission denied" in joined
1095
1096
1097 def test_cache_write_failure_note_never_echoes_absolute_paths(tmp_path, monkeypatch):
1098 notes: list[str] = []
1099
1100 def raising_open(*args, **kwargs):
1101 raise PermissionError(
1102 13, "Permission denied", str(tmp_path / "cache" / "corpus.json")
1103 )
1104
1105 monkeypatch.setattr(corpus.os, "open", raising_open)
1106 corpus._write_cache(tmp_path / "cache" / "corpus.json", {"entries": {}}, notes)
1107
1108 joined = " ".join(notes)
1109 assert notes, "expected a cache note"
1110 assert str(tmp_path) not in joined
1111 assert "Permission denied" in joined
1112
1112 lines PYTHON