返回 last30days-skill
test_brief_capture.py
根目录 / tests / test_brief_capture.py
1 """Unit tests for finished-brief detection, atomic persistence, and corpus redaction."""
2
3 from __future__ import annotations
4
5 import os
6 import stat
7 from datetime import date
8 from pathlib import Path
9
10 import pytest
11
12 from lib import brief_capture, library
13
14
15 MODERN_BRIEF = """🌐 last30days · Anthropic · Oct 22 to Nov 21, 2026 · v4.5.0
16
17 ## What I learned
18
19 Anthropic dominates developer threads this month with rapid releases and active debate over pricing and tool use.
20
21 **KEY PATTERNS from the research:**
22 1. Developers praise Claude Code reliability on large refactors.
23 2. Teams debate API rate limits during peak launches.
24
25 ```text
26 ---
27 ✅ All agents reported back!
28 ├─ 🟠 Reddit: 12 threads │ 48 comments
29 ├─ 𝕏 X: 18 posts │ 410 likes
30 └─ 🗓️ Oct 22 to Nov 21, 2026
31 ---
32 ```
33
34 ---
35 I'm now an expert on Anthropic based on the last 30 days of community discussion. Want me to dig deeper into pricing or compare against OpenAI? Just ask.
36 """
37
38 LEGACY_SYNCED_BRIEF = """🌐 last30days v3.32.0 · synced 2026-11-09
39
40 # Nvidia
41
42 Blackwell rack shipments and CUDA moat discussions lead engineering forums.
43
44 ```text
45 ---
46 ✅ All agents reported back!
47 ├─ 🟠 Reddit: 8 threads
48 └─ 🗓️ Oct 10 to Nov 9, 2026
49 ---
50 ```
51 """
52
53 COMPARISON_BRIEF = """🌐 last30days · Codex vs Cursor · Oct 22 to Nov 21, 2026 · v4.5.0
54
55 # Codex vs Cursor
56
57 | Dimension | Codex | Cursor |
58 |---|---|---|
59 | Strength | Autonomous terminal runs | Fast inline editor loop |
60
61 ```text
62 ---
63 ✅ All agents reported back!
64 ├─ 🟠 Reddit: 14 threads
65 └─ 🗓️ Oct 22 to Nov 21, 2026
66 ---
67 ```
68
69 I've compared Codex and Cursor across the last 30 days. Ask if you want a workflow recommendation.
70 """
71
72 CLAUDE_LIST_FREE_BRIEF = """🌐 last30days · MCP servers · Oct 22 to Nov 21, 2026 · v4.5.0
73
74 Teams are standardizing around local stdio servers with strict capability scopes.
75
76 KEY PATTERNS from the research:\\
77 1\\. Auth and token scoping remain the top complaint.\\
78 2\\. Developers favor zero-config local launchers.
79
80 ```text
81 ---
82 ✅ All agents reported back!
83 ├─ 🟠 Reddit: 10 threads
84 └─ 🗓️ Oct 22 to Nov 21, 2026
85 ---
86 ```
87 """
88
89 CORPUS_BRIEF = """🌐 last30days · Acme Strategy · Oct 22 to Nov 21, 2026 · v4.5.0
90
91 ## What I learned
92
93 Public forums focus on Acme's new pricing tier.
94
95 ## From your files
96
97 Internal Q4 memo notes Project Falcon launches on Dec 15 with secret margin targets.
98
99 ## Key patterns
100
101 1. Customers ask for annual billing discounts.
102
103 ```text
104 ---
105 ✅ All agents reported back!
106 ├─ 🟠 Reddit: 6 threads
107 ├─ 📁 Your files: 2 notes
108 └─ 🗓️ Oct 22 to Nov 21, 2026
109 ---
110 ```
111 """
112
113
114 def test_extract_modern_brief_strips_invitation_and_parses_metadata():
115 brief = brief_capture.extract_finished_brief(MODERN_BRIEF)
116
117 assert brief is not None
118 assert brief.topic == "Anthropic"
119 assert brief.slug == "anthropic"
120 assert brief.published_date == date(2026, 11, 21)
121 assert brief.version == "4.5.0"
122 assert brief.is_private is False
123 assert brief.content.startswith("🌐 last30days · Anthropic · Oct 22 to Nov 21, 2026 · v4.5.0")
124 assert "All agents reported back!" in brief.content
125 assert "I'm now an expert" not in brief.content
126
127
128 def test_extract_legacy_synced_brief_uses_heading_and_synced_date():
129 brief = brief_capture.extract_finished_brief(LEGACY_SYNCED_BRIEF)
130
131 assert brief is not None
132 assert brief.topic == "Nvidia"
133 assert brief.slug == "nvidia"
134 assert brief.published_date == date(2026, 11, 9)
135 assert brief.version == "3.32.0"
136
137
138 def test_extract_comparison_brief_strips_comparison_invitation():
139 brief = brief_capture.extract_finished_brief(COMPARISON_BRIEF)
140
141 assert brief is not None
142 assert brief.topic == "Codex vs Cursor"
143 assert brief.slug == "codex-vs-cursor"
144 assert brief.published_date == date(2026, 11, 21)
145 assert "| Dimension | Codex | Cursor |" in brief.content
146 assert "I've compared Codex and Cursor" not in brief.content
147
148
149 def test_extract_preserves_claude_code_list_free_hard_breaks():
150 brief = brief_capture.extract_finished_brief(CLAUDE_LIST_FREE_BRIEF)
151
152 assert brief is not None
153 assert "KEY PATTERNS from the research:\\\n1\\. Auth" in brief.content
154 assert "2\\. Developers favor zero-config local launchers." in brief.content
155
156
157 def test_extract_handles_preamble_and_rejects_partial_quoted_and_raw_dumps():
158 with_preamble = "Here is your research summary:\n\n" + MODERN_BRIEF
159 extracted = brief_capture.extract_finished_brief(with_preamble)
160 assert extracted is not None
161 assert extracted.content.startswith("🌐 last30days · Anthropic")
162
163 # Missing footer
164 assert brief_capture.extract_finished_brief("🌐 last30days · Anthropic · Oct 22 to Nov 21, 2026\n\nHalf written") is None
165
166 # Missing badge
167 assert brief_capture.extract_finished_brief("```text\n---\n✅ All agents reported back!\n---\n```") is None
168
169 # Quoted excerpt only
170 quoted = "\n".join(f"> {line}" for line in MODERN_BRIEF.splitlines())
171 assert brief_capture.extract_finished_brief(quoted) is None
172
173 # Raw evidence dump
174 raw_dump = MODERN_BRIEF + "\n<!-- EVIDENCE FOR SYNTHESIS -->\nraw data\n<!-- END EVIDENCE FOR SYNTHESIS -->\n"
175 assert brief_capture.extract_finished_brief(raw_dump) is None
176
177 canonical_dump = MODERN_BRIEF + "\n---\n# END OF last30days CANONICAL OUTPUT\n"
178 assert brief_capture.extract_finished_brief(canonical_dump) is None
179
180
181 def test_save_finished_brief_is_idempotent_and_suffixes_distinct_content(tmp_path):
182 brief = brief_capture.extract_finished_brief(MODERN_BRIEF)
183 assert brief is not None
184
185 first = brief_capture.save_finished_brief(brief, tmp_path)
186 assert first.status == "saved"
187 assert first.path == tmp_path / "finished" / "anthropic-2026-11-21.md"
188 assert first.path.read_text(encoding="utf-8") == brief.content
189 if os.name == "posix":
190 assert stat.S_IMODE(first.path.stat().st_mode) == 0o644
191
192 # Repeating identical brief is an idempotent no-op.
193 second = brief_capture.save_finished_brief(brief, tmp_path)
194 assert second.status == "duplicate"
195 assert second.path == first.path
196 assert sorted((tmp_path / "finished").glob("*.md")) == [first.path]
197
198 # Distinct content on the same topic and date gets a numeric suffix.
199 updated_text = MODERN_BRIEF.replace("active debate over pricing", "new benchmark results")
200 updated_brief = brief_capture.extract_finished_brief(updated_text)
201 assert updated_brief is not None
202 third = brief_capture.save_finished_brief(updated_brief, tmp_path)
203 assert third.status == "saved"
204 assert third.path == tmp_path / "finished" / "anthropic-2026-11-21-2.md"
205
206 # Re-saving the second variant also deduplicates cleanly.
207 fourth = brief_capture.save_finished_brief(updated_brief, tmp_path)
208 assert fourth.status == "duplicate"
209 assert fourth.path == third.path
210
211
212 def test_corpus_brief_uses_private_permissions_and_fails_closed_for_public_output(tmp_path):
213 brief = brief_capture.extract_finished_brief(CORPUS_BRIEF)
214 assert brief is not None
215 assert brief.is_private is True
216
217 result = brief_capture.save_finished_brief(brief, tmp_path)
218 assert result.status == "saved"
219 if os.name == "posix":
220 assert stat.S_IMODE(result.path.stat().st_mode) == 0o600
221 assert stat.S_IMODE(result.path.parent.stat().st_mode) == 0o700
222
223 # Synthesized chat briefs with local corpus markers fail closed for public output.
224 assert library.is_unbounded_private_brief(brief.content) is True
225 assert library.public_markdown(brief.content) == ""
226
227 # Even heading-free woven prose with only a footer `Your files` marker fails closed.
228 woven = """🌐 last30days · Acme Strategy · Oct 22 to Nov 21, 2026 · v4.5.0
229
230 What I learned:
231
232 Internal Q4 memo notes Project Cobalt launches on Dec 15 alongside public forum rumors.
233
234 ```text
235 ---
236 ✅ All agents reported back!
237 ├─ 🟠 Reddit: 6 threads
238 ├─ 📁 Your files: 1 note
239 └─ 🗓️ Oct 22 to Nov 21, 2026
240 ---
241 ```
242 """
243 woven_brief = brief_capture.extract_finished_brief(woven)
244 assert woven_brief is not None
245 assert woven_brief.is_private is True
246 assert library.public_markdown(woven_brief.content) == ""
247
248
249 def test_concurrent_saves_do_not_overwrite_distinct_briefs(tmp_path):
250 import concurrent.futures
251
252 briefs = [
253 brief_capture.extract_finished_brief(
254 MODERN_BRIEF.replace("active debate over pricing", f"unique variant {idx}")
255 )
256 for idx in range(6)
257 ]
258 assert all(b is not None for b in briefs)
259
260 with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
261 results = list(
262 pool.map(lambda b: brief_capture.save_finished_brief(b, tmp_path), briefs)
263 )
264
265 assert all(r.status == "saved" for r in results)
266 saved_paths = {r.path for r in results}
267 assert len(saved_paths) == 6
268 saved_contents = {p.read_text(encoding="utf-8") for p in saved_paths}
269 for idx in range(6):
270 assert any(f"unique variant {idx}" in text for text in saved_contents)
271
272
273 def test_long_truncated_badge_recovers_full_topic_from_raw_footer(tmp_path):
274 full_topic = (
275 "Comparing open source local vector databases for hybrid retrieval "
276 "in production agent workflows"
277 )
278 raw_path = tmp_path / "comparing-open-source-local-vector-databases-for-hybrid-retrieval-in-production-agent-workflows-raw.md"
279 raw_path.write_text(
280 f"# last30days v4.5.0: {full_topic}\n\n- Date range: 2026-10-22 to 2026-11-21\n",
281 encoding="utf-8",
282 )
283 long_brief_text = f"""🌐 last30days · Comparing open source local vector databases for hybrid... · Oct 22 to Nov 21, 2026 · v4.5.0
284
285 What I learned:
286
287 Engineers compare Qdrant, LanceDB, and SQLite-vec for hybrid search.
288
289 ```text
290 ---
291 ✅ All agents reported back!
292 ├─ 🟠 Reddit: 10 threads
293 ├─ 🗓️ Oct 22 to Nov 21, 2026
294 └─ 📎 Raw results saved to {raw_path}
295 ---
296 ```
297 """
298 captured = brief_capture.extract_finished_brief(long_brief_text)
299 assert captured is not None
300 assert captured.topic == full_topic
301 assert captured.slug == library.slugify(full_topic)
302 assert f"<!-- last30days-topic: {full_topic} -->" in captured.content
303
304 saved = brief_capture.save_finished_brief(captured, tmp_path)
305 parsed = library.parse_markdown_file(saved.path, source_format="finished-brief")
306 assert parsed.topic == full_topic
307 assert parsed.slug == library.slugify(full_topic)
308 # Staging temp files are cleaned up after atomic publish.
309 assert list((tmp_path / "finished").glob("*.tmp")) == []
310
311
312 def test_finished_brief_for_a_long_topic_gets_a_short_filename(tmp_path):
313 full_topic = "multi model comparison across providers and pricing tiers " * 8
314 raw_path = tmp_path / "long-topic-raw.md"
315 raw_path.write_text(
316 f"# last30days v4.5.0: {full_topic}\n\n- Date range: 2026-10-22 to 2026-11-21\n",
317 encoding="utf-8",
318 )
319 brief_text = f"""🌐 last30days · Multi model comparison across providers... · Oct 22 to Nov 21, 2026 · v4.5.0
320
321 What I learned:
322
323 Teams compare model pricing tiers across providers.
324
325 ```text
326 ---
327 ✅ All agents reported back!
328 ├─ 🟠 Reddit: 10 threads
329 ├─ 🗓️ Oct 22 to Nov 21, 2026
330 └─ 📎 Raw results saved to {raw_path}
331 ---
332 ```
333 """
334 captured = brief_capture.extract_finished_brief(brief_text)
335 assert captured is not None
336 assert captured.slug == library.slugify(full_topic)
337
338 saved = brief_capture.save_finished_brief(captured, tmp_path)
339 assert saved.status == "saved"
340 assert len(saved.path.name.encode("utf-8")) < 255
341 parsed = library.parse_markdown_file(saved.path, source_format="finished-brief")
342 assert parsed.slug == captured.slug
343 assert len(parsed.output_name.encode("utf-8")) < 255
344
345
346 def test_resaving_a_long_topic_brief_saved_under_its_full_slug_is_a_duplicate(tmp_path):
347 # A 190-character slug fit under the 255-byte limit before filenames were
348 # shortened, so a brief may already exist under its full-slug name.
349 topic = "agent frameworks compared " * 8
350 raw_path = tmp_path / "raw.md"
351 raw_path.write_text(
352 f"# last30days v4.5.0: {topic}\n\n- Date range: 2026-10-22 to 2026-11-21\n",
353 encoding="utf-8",
354 )
355 brief_text = f"""🌐 last30days · Agent frameworks compared... · Oct 22 to Nov 21, 2026 · v4.5.0
356
357 What I learned:
358
359 Teams keep comparing agent frameworks.
360
361 ```text
362 ---
363 ✅ All agents reported back!
364 ├─ 🟠 Reddit: 10 threads
365 ├─ 🗓️ Oct 22 to Nov 21, 2026
366 └─ 📎 Raw results saved to {raw_path}
367 ---
368 ```
369 """
370 captured = brief_capture.extract_finished_brief(brief_text)
371 assert captured is not None
372 assert len(captured.slug) > 180
373 finished = tmp_path / "finished"
374 finished.mkdir()
375 legacy = finished / f"{captured.slug}-{captured.published_date.isoformat()}.md"
376 legacy.write_text(captured.content, encoding="utf-8")
377
378 saved = brief_capture.save_finished_brief(captured, tmp_path)
379
380 assert saved.status == "duplicate"
381 assert saved.path == legacy
382 assert sorted(p.name for p in finished.glob("*.md")) == [legacy.name]
383
383 lines PYTHON