-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_finder.py
More file actions
1849 lines (1609 loc) · 65.6 KB
/
Copy pathcontent_finder.py
File metadata and controls
1849 lines (1609 loc) · 65.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Content Finder — credible agentic-AI news digest for AI product managers.
Pulls from a curated set of RSS feeds plus Hacker News, scores items for
relevance to agentic engineering / LLM industry trends, and prints a digest
to stdout (optionally synthesised by Claude into a themed brief).
"""
from __future__ import annotations
import argparse
import html
import json
import os
import re
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import Iterable
from urllib.parse import urlparse
from zoneinfo import ZoneInfo
import feedparser
import httpx
import yaml
HK_TZ = ZoneInfo("Asia/Hong_Kong")
def today_hkt(now: datetime | None = None) -> date:
"""Return today's calendar date in Hong Kong (HKT, UTC+8).
Why: GitHub Actions runs in UTC, so a 23:00-UTC cron lands at 07:00 HKT
the *next* day. Using `datetime.now()` for the page header puts the wrong
date on every cron run; we anchor on HKT instead.
"""
now = now or datetime.now(timezone.utc)
return now.astimezone(HK_TZ).date()
# Fixed taxonomy used both in the LLM prompt and the chip filter bar.
TAG_TAXONOMY: list[str] = [
"Models", "Agents", "Tooling", "Regulation", "Enterprise", "Research",
]
_TAG_LOOKUP = {t.lower(): t for t in TAG_TAXONOMY}
# --------------------------------------------------------------------------- #
# Source configuration — loaded from sources.yml
# --------------------------------------------------------------------------- #
@dataclass
class SourceConfig:
rss_sources: list[tuple[str, str]] # (name, url)
hn_queries: list[str]
keyword_weights: dict[int, list[str]]
trusted_weights: dict[str, int] # source_name → credibility bonus
def load_sources(path: "Path | None" = None) -> SourceConfig:
"""Load and validate sources.yml. Raises FileNotFoundError or ValueError on bad input."""
from pathlib import Path as _Path
if path is None:
path = _Path(__file__).resolve().parent / "sources.yml"
path = _Path(path)
if not path.exists():
raise FileNotFoundError(f"sources.yml not found at {path}")
with path.open(encoding="utf-8") as fh:
raw = yaml.safe_load(fh) or {}
# --- required top-level keys ---
for key in ("rss_sources", "hn_queries", "keyword_weights"):
if key not in raw:
raise ValueError(f"sources.yml missing required key: '{key}'")
# --- rss_sources ---
rss_raw = raw["rss_sources"]
if not isinstance(rss_raw, list) or len(rss_raw) == 0:
raise ValueError("rss_sources must be a non-empty list")
rss_sources: list[tuple[str, str]] = []
trusted_weights: dict[str, int] = {}
seen_names: set[str] = set()
for i, entry in enumerate(rss_raw):
if not isinstance(entry, dict):
raise ValueError(f"rss_sources[{i}] must be a mapping, got {type(entry).__name__}")
if "name" not in entry:
raise ValueError(f"rss_sources[{i}] missing required field 'name'")
if "url" not in entry:
raise ValueError(f"rss_sources[{i}] missing required field 'url'")
name = str(entry["name"]).strip()
url = str(entry["url"]).strip()
trust = int(entry.get("trust", 0))
if not name:
raise ValueError(f"rss_sources[{i}] 'name' must not be empty")
if name in seen_names:
raise ValueError(f"Duplicate source name in rss_sources: {name!r}")
if not url.startswith("https://"):
raise ValueError(
f"rss_sources entry {name!r} url must start with https://, got {url!r}"
)
if not (0 <= trust <= 5):
raise ValueError(
f"rss_sources entry {name!r} trust={trust} is out of range 0-5"
)
seen_names.add(name)
rss_sources.append((name, url))
if trust > 0:
trusted_weights[name] = trust
# --- hn_queries ---
hn_raw = raw["hn_queries"]
if not isinstance(hn_raw, list) or len(hn_raw) == 0:
raise ValueError("hn_queries must be a non-empty list")
hn_queries: list[str] = []
for i, q in enumerate(hn_raw):
if not isinstance(q, str) or not q.strip():
raise ValueError(f"hn_queries[{i}] must be a non-empty string, got {q!r}")
hn_queries.append(q)
# --- keyword_weights ---
kw_raw = raw["keyword_weights"]
if not isinstance(kw_raw, dict) or len(kw_raw) == 0:
raise ValueError("keyword_weights must be a non-empty mapping")
keyword_weights: dict[int, list[str]] = {}
for k, terms in kw_raw.items():
if not isinstance(k, int) or k <= 0:
raise ValueError(
f"keyword_weights key must be a positive integer, got {k!r}"
)
if not isinstance(terms, list):
raise ValueError(f"keyword_weights[{k}] must be a list, got {type(terms).__name__}")
keyword_weights[k] = [str(t) for t in terms]
return SourceConfig(
rss_sources=rss_sources,
hn_queries=hn_queries,
keyword_weights=keyword_weights,
trusted_weights=trusted_weights,
)
# Load once at import time so module-level constants stay backward-compatible.
_SOURCE_CFG: SourceConfig = load_sources()
RSS_SOURCES: list[tuple[str, str]] = _SOURCE_CFG.rss_sources
HN_QUERIES: list[str] = _SOURCE_CFG.hn_queries
KEYWORD_WEIGHTS: dict[int, list[str]] = _SOURCE_CFG.keyword_weights
_TRUSTED_WEIGHTS: dict[str, int] = _SOURCE_CFG.trusted_weights
# --------------------------------------------------------------------------- #
# Data types
# --------------------------------------------------------------------------- #
@dataclass
class Item:
title: str
url: str
source: str
published: datetime
summary: str = ""
score: float = 0.0
extra: dict = field(default_factory=dict)
first_seen: "date | None" = None
@property
def domain(self) -> str:
try:
return urlparse(self.url).netloc.replace("www.", "")
except Exception:
return ""
@property
def age_hours(self) -> float:
return (datetime.now(timezone.utc) - self.published).total_seconds() / 3600
# --------------------------------------------------------------------------- #
# Fetchers
# --------------------------------------------------------------------------- #
def _to_utc(struct_time) -> datetime:
if not struct_time:
return datetime.now(timezone.utc) - timedelta(days=30)
return datetime.fromtimestamp(time.mktime(struct_time), tz=timezone.utc)
def fetch_rss(source: str, url: str, since: datetime) -> list[Item]:
items: list[Item] = []
try:
parsed = feedparser.parse(url, request_headers={"User-Agent": "ContentFinder/1.0"})
except Exception as exc:
print(f"[warn] {source}: {exc}", file=sys.stderr)
return items
if parsed.bozo and not parsed.entries:
print(f"[warn] {source}: feed parse error ({parsed.bozo_exception})", file=sys.stderr)
return items
for entry in parsed.entries:
published = _to_utc(
getattr(entry, "published_parsed", None)
or getattr(entry, "updated_parsed", None)
)
if published < since:
continue
title = getattr(entry, "title", "").strip()
link = getattr(entry, "link", "").strip()
if not title or not link:
continue
summary_html = getattr(entry, "summary", "") or ""
summary = re.sub(r"<[^>]+>", " ", summary_html)
summary = re.sub(r"\s+", " ", summary).strip()
items.append(Item(
title=title,
url=link,
source=source,
published=published,
summary=summary[:500],
))
return items
def fetch_hn(query: str, since: datetime, min_points: int = 50) -> list[Item]:
"""Hacker News stories matching a query, recent and with traction."""
url = "https://hn.algolia.com/api/v1/search"
params = {
"query": query,
"tags": "story",
"numericFilters": (
f"created_at_i>{int(since.timestamp())},"
f"points>={min_points}"
),
"hitsPerPage": 20,
}
items: list[Item] = []
try:
r = httpx.get(url, params=params, timeout=15)
r.raise_for_status()
data = r.json()
except Exception as exc:
print(f"[warn] HN '{query}': {exc}", file=sys.stderr)
return items
for hit in data.get("hits", []):
link = hit.get("url") or f"https://news.ycombinator.com/item?id={hit['objectID']}"
title = hit.get("title") or ""
if not title:
continue
published = datetime.fromtimestamp(hit["created_at_i"], tz=timezone.utc)
items.append(Item(
title=title,
url=link,
source=f"Hacker News",
published=published,
summary=f"{hit.get('points', 0)} points · {hit.get('num_comments', 0)} comments · query: {query}",
extra={"points": hit.get("points", 0), "comments": hit.get("num_comments", 0)},
))
return items
# --------------------------------------------------------------------------- #
# Scoring + dedupe
# --------------------------------------------------------------------------- #
def keyword_score(text: str) -> int:
text_l = text.lower()
score = 0
for weight, terms in KEYWORD_WEIGHTS.items():
for t in terms:
if t in text_l:
score += weight
return score
def score_item(item: Item) -> float:
body = f"{item.title} {item.summary}"
base = keyword_score(body)
# Recency bonus: fresher = higher.
age_days = item.age_hours / 24
recency = max(0.0, 7 - age_days) / 7 # 0..1
# Source-credibility bonus (loaded from sources.yml).
src_bonus = _TRUSTED_WEIGHTS.get(item.source, 0)
# HN points contribute lightly (caps to avoid drowning the rest).
hn_bonus = 0.0
if item.source == "Hacker News":
pts = item.extra.get("points", 0)
hn_bonus = min(pts / 100.0, 4.0)
return base + 2 * recency + src_bonus + hn_bonus
# --------------------------------------------------------------------------- #
# Cross-day dedup state (dedup-state.json)
# --------------------------------------------------------------------------- #
DEDUP_STATE_PATH = Path("dedup-state.json")
DEDUP_STATE_VERSION = 1
DEDUP_TTL_DAYS = 5
DEDUP_MAX_AGE_DAYS = 30
MIN_RENDERED_ITEMS = 10
def load_dedup_state(path: "Path | str") -> dict[str, str]:
"""Load the cross-day dedup state file.
Returns a flat {canonical_url: ISO_first_seen_date} map. Missing,
malformed, or unknown-version files return {} so the daily cron is
never broken by state-file corruption.
"""
p = Path(path)
if not p.exists():
return {}
try:
data = json.loads(p.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
print(f"[warn] dedup-state load failed ({exc}); proceeding with empty state",
file=sys.stderr)
return {}
if not isinstance(data, dict):
return {}
if data.get("version") != DEDUP_STATE_VERSION:
return {}
entries = data.get("entries")
if not isinstance(entries, dict):
return {}
return {str(k): str(v) for k, v in entries.items()}
def save_dedup_state(path: "Path | str", state: dict[str, str]) -> None:
"""Atomically write the dedup state to disk (write-temp + rename)."""
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
payload = {"version": DEDUP_STATE_VERSION, "entries": dict(state)}
tmp = p.with_suffix(p.suffix + ".tmp")
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2,
sort_keys=True), encoding="utf-8")
tmp.replace(p)
def update_seen_state(
state: dict[str, str],
items: list["Item"],
*,
today: date,
max_age_days: int,
) -> dict[str, str]:
"""Return a new state map with today's items added and old entries pruned.
Semantics:
- Items not in state get today's date.
- Items already in state keep their (earlier) first_seen date.
- Entries older than max_age_days (inclusive boundary kept) are dropped.
- Entries with corrupt date strings are dropped (defensive).
"""
out: dict[str, str] = {}
cutoff = today - timedelta(days=max_age_days)
for url, raw in state.items():
try:
d = date.fromisoformat(raw)
except ValueError:
continue
if d >= cutoff:
out[url] = raw
today_iso = today.isoformat()
for it in items:
canon = canonical_url(it.url)
out.setdefault(canon, today_iso)
return out
def topup_to_minimum(
*,
fresh: list["Item"],
filtered_out: list["Item"],
minimum: int,
) -> list["Item"]:
"""If `fresh` has fewer than `minimum` items, top up from `filtered_out`
by score (highest first). Topped-up items retain their first_seen flag
so the renderer can show the resurfacing badge. Source cap is applied
later in the pipeline.
"""
if len(fresh) >= minimum:
return list(fresh)
needed = minimum - len(fresh)
topup = sorted(filtered_out, key=lambda x: x.score, reverse=True)[:needed]
return list(fresh) + topup
def annotate_first_seen(items: list["Item"], state: dict[str, str]) -> None:
"""Set Item.first_seen on every item whose canonical URL is in state."""
for it in items:
canon = canonical_url(it.url)
raw = state.get(canon)
if not raw:
continue
try:
it.first_seen = date.fromisoformat(raw)
except ValueError:
continue
def filter_unseen(
items: list["Item"], *, today: date, ttl_days: int
) -> list["Item"]:
"""Drop items first seen within `ttl_days` of today (inclusive boundary).
Items with no first_seen always pass through. ttl_days <= 0 disables
filtering entirely (used by --dedup-ttl-days 0).
"""
if ttl_days <= 0:
return list(items)
out: list[Item] = []
for it in items:
if it.first_seen is None:
out.append(it)
continue
age_days = (today - it.first_seen).days
if age_days > ttl_days:
out.append(it)
return out
def canonical_url(url: str) -> str:
"""Strip query string and trailing slash for cross-run URL comparison.
The same canonicalization is used by within-run dedup() and by the
cross-day dedup-state filter, so a URL with a tracker tomorrow still
matches the bare URL stored today.
"""
return url.split("?")[0].rstrip("/")
def dedupe(items: list[Item]) -> list[Item]:
"""Drop near-duplicate titles / same URLs across sources."""
seen_urls: set[str] = set()
seen_titles: set[str] = set()
out: list[Item] = []
for it in sorted(items, key=lambda x: x.score, reverse=True):
u = canonical_url(it.url)
t_norm = re.sub(r"[^a-z0-9 ]+", "", it.title.lower()).strip()
t_key = " ".join(t_norm.split()[:8])
if u in seen_urls or (t_key and t_key in seen_titles):
continue
seen_urls.add(u)
seen_titles.add(t_key)
out.append(it)
return out
def apply_source_cap(items: list[Item], max_per_source: int) -> list[Item]:
"""Keep at most `max_per_source` items per source, preferring higher scores.
Why: a single hot day on arXiv or Simon Willison can otherwise crowd out
the rest. Balancing per-source preserves diversity for the synthesis
layer and the no-summarize ranked view alike.
"""
if max_per_source <= 0:
return items
by_source: dict[str, int] = {}
out: list[Item] = []
for it in sorted(items, key=lambda x: x.score, reverse=True):
cnt = by_source.get(it.source, 0)
if cnt >= max_per_source:
continue
by_source[it.source] = cnt + 1
out.append(it)
return out
# --------------------------------------------------------------------------- #
# Output
# --------------------------------------------------------------------------- #
def render_plain(items: list[Item], top_n: int) -> str:
lines = [
f"# Agentic AI Digest — {datetime.now().strftime('%Y-%m-%d')}",
f"_{len(items)} items collected, top {min(top_n, len(items))} shown_",
"",
]
for it in items[:top_n]:
age = f"{int(it.age_hours)}h ago" if it.age_hours < 48 else f"{int(it.age_hours / 24)}d ago"
lines.append(f"## {it.title}")
lines.append(f"_{it.source} · {it.domain} · {age} · score {it.score:.1f}_")
if it.summary:
lines.append("")
lines.append(it.summary)
lines.append("")
lines.append(it.url)
lines.append("")
return "\n".join(lines)
HTML_CSS = """
:root {
/* Backgrounds — Route A spec */
--bg-0: #0a0a0d;
--bg-1: #111116;
--bg-2: #18181f;
--bg-3: #202028;
--bg-4: #28282f;
--border: #22222c;
--border-2: #2e2e3a;
--fg: #e2e2ea;
--fg-mid: #9a9ab0;
--fg-dim: #606072;
/* Purple — primary accent (hue 292) */
--purple: oklch(65% 0.22 292);
--purple-bright: oklch(72% 0.24 292);
--purple-soft: oklch(65% 0.22 292 / 0.15);
--purple-border: oklch(65% 0.22 292 / 0.35);
--purple-dim: oklch(65% 0.22 292 / 0.08);
/* Backwards-compat aliases — earlier code referred to --accent. */
--accent: var(--purple);
--accent-bg: var(--purple-soft);
--accent-border: var(--purple-border);
/* Secondary accents */
--green: oklch(68% 0.13 145);
--green-bg: oklch(68% 0.13 145 / 0.1);
--amber: oklch(72% 0.13 75);
--amber-bg: oklch(72% 0.13 75 / 0.1);
--teal: oklch(68% 0.13 210);
--teal-bg: oklch(68% 0.13 210 / 0.1);
--slate: oklch(68% 0.12 260);
--slate-bg: oklch(68% 0.12 260 / 0.1);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { background: var(--bg-0); color: var(--fg); }
body {
font: 14px/1.55 "DM Sans", system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
min-height: 100vh;
}
.page {
max-width: 680px;
margin: 0 auto;
background: var(--bg-0);
min-height: 100vh;
}
/* Top bar */
.topbar {
background: var(--bg-0);
border-bottom: 1px solid var(--border);
padding: 16px 20px;
display: flex; align-items: baseline; gap: 12px;
}
.topbar-left { display: flex; align-items: baseline; gap: 12px; }
.topbar-title { font-size: 16px; font-weight: 600; color: var(--fg); }
.topbar-date { font-size: 13px; color: var(--fg-dim); }
.topbar-right {
margin-left: auto; font-size: 12px; color: var(--fg-dim);
}
.topbar-right a { color: var(--fg-dim); text-decoration: none; }
.topbar-right a:hover { color: var(--fg-mid); }
/* Takeaways block */
.takeaways {
background: var(--bg-1);
border-bottom: 1px solid var(--border);
}
.takeaways-toggle {
width: 100%; min-height: 44px;
padding: 12px 20px;
background: none; border: none; cursor: pointer;
display: flex; align-items: center; gap: 10px;
font-family: inherit; text-align: left;
}
.takeaways-label {
font-size: 11px; font-weight: 600;
color: var(--purple);
letter-spacing: 0.07em; text-transform: uppercase;
}
.takeaways-count {
margin-left: 4px; font-size: 11px; color: var(--purple); opacity: 0.6;
}
.takeaways-chevron {
margin-left: auto; font-size: 13px; color: var(--fg-dim);
display: inline-block; transition: transform 0.15s;
}
.takeaways-toggle[aria-expanded="false"] .takeaways-chevron {
transform: rotate(180deg);
}
.takeaways-body {
padding: 4px 20px 18px;
display: flex; flex-direction: column; gap: 16px;
}
.takeaways-body.is-collapsed { display: none; }
.takeaway {
display: flex; gap: 10px; align-items: flex-start;
}
.takeaway-num {
font-family: "DM Mono", monospace;
font-size: 12px; font-weight: 700; color: var(--purple);
min-width: 20px; padding-top: 3px; flex-shrink: 0;
}
.takeaway-content { flex: 1; min-width: 0; }
.takeaway-content p {
font-size: 14px; color: var(--fg-mid); line-height: 1.65;
}
.takeaway-links {
margin-top: 8px; display: flex; flex-direction: column; gap: 4px;
}
.takeaway-link-row {
display: flex; align-items: center; gap: 6px;
min-height: 28px;
background: none; border: none; padding: 2px 6px;
margin-left: -6px; margin-right: -6px;
border-radius: 4px;
cursor: pointer;
font-family: inherit; text-align: left;
text-decoration: none;
transition: background .12s, color .12s;
width: 100%;
}
.takeaway-link-row:hover {
background: var(--purple-dim);
}
.takeaway-link-tick {
display: inline-block; width: 2px; height: 12px;
background: var(--purple); border-radius: 1px; flex-shrink: 0;
transition: background .12s;
}
.takeaway-link-row:hover .takeaway-link-tick {
background: var(--purple-bright);
}
.takeaway-link-label {
font-size: 12px; color: var(--purple);
text-decoration: underline;
text-decoration-color: var(--purple-border);
text-underline-offset: 2px;
}
.takeaway-link-row:hover .takeaway-link-label {
color: var(--purple-bright);
text-decoration-color: var(--purple);
}
.takeaway-link-source {
font-size: 11px; color: var(--fg-dim);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.takeaway-link-arrow {
font-size: 11px; color: var(--fg-dim); margin-left: auto;
transition: color .12s;
}
.takeaway-link-row:hover .takeaway-link-arrow {
color: var(--purple-bright);
}
/* Filter chips */
.chips {
display: flex; flex-wrap: wrap; gap: 6px;
padding: 10px 20px;
border-bottom: 1px solid var(--border);
}
.chip {
font-family: inherit; font-size: 12px; font-weight: 500;
padding: 4px 12px;
border: 1px solid var(--border);
border-radius: 20px;
background: transparent;
color: var(--fg-dim);
cursor: pointer;
white-space: nowrap;
transition: color .12s, background .12s, border-color .12s;
}
.chip:hover { color: var(--fg); }
.chip.is-active { color: var(--fg); background: var(--bg-3); border-color: var(--border-2); }
.chip[data-tag="Models"].is-active { color: var(--green); background: var(--green-bg); border-color: oklch(68% 0.13 145 / 0.4); }
.chip[data-tag="Agents"].is-active { color: var(--purple); background: var(--purple-soft); border-color: var(--purple-border); }
.chip[data-tag="Tooling"].is-active { color: var(--teal); background: var(--teal-bg); border-color: oklch(68% 0.13 210 / 0.4); }
.chip[data-tag="Regulation"].is-active { color: var(--amber); background: var(--amber-bg); border-color: oklch(72% 0.13 75 / 0.4); }
.chip[data-tag="Enterprise"].is-active { color: var(--purple); background: var(--purple-dim); border-color: var(--purple-border); }
.chip[data-tag="Research"].is-active { color: var(--slate); background: var(--slate-bg); border-color: oklch(68% 0.12 260 / 0.4); }
/* Article list + section labels */
.article-list { padding-bottom: 24px; }
.section-label {
padding: 16px 20px 8px;
display: flex; align-items: center; gap: 10px;
font-size: 11px; font-weight: 600;
color: var(--purple);
letter-spacing: 0.06em; text-transform: uppercase;
background: var(--bg-0);
}
.section-label::after {
content: ""; flex: 1; height: 1px; background: var(--border);
}
/* Item card */
.item {
border-bottom: 1px solid var(--border);
padding: 14px 20px;
border-left: 3px solid transparent;
transition: background 0.15s, border-color 0.15s;
}
.item.is-expanded {
border-left-color: var(--purple);
background: var(--purple-dim);
}
.item .tags {
display: flex; gap: 6px; flex-wrap: wrap;
margin-bottom: 8px;
}
.tag {
display: inline-block;
font-size: 11px; font-weight: 500;
padding: 2px 7px;
border-radius: 4px;
letter-spacing: 0.01em;
border: 1px solid;
}
.tag-Models { color: var(--green); background: var(--green-bg); border-color: oklch(68% 0.13 145 / 0.3); }
.tag-Agents { color: var(--purple); background: oklch(65% 0.22 292 / 0.12); border-color: var(--purple-border); }
.tag-Tooling { color: var(--teal); background: var(--teal-bg); border-color: oklch(68% 0.13 210 / 0.3); }
.tag-Regulation { color: var(--amber); background: var(--amber-bg); border-color: oklch(72% 0.13 75 / 0.3); }
.tag-Enterprise { color: var(--purple); background: var(--purple-dim); border-color: var(--purple-border); }
.tag-Research { color: var(--slate); background: var(--slate-bg); border-color: oklch(68% 0.12 260 / 0.3); }
.item-title {
display: flex; align-items: flex-start; gap: 10px;
width: 100%; min-height: 44px;
background: none; border: none; padding: 0;
margin-bottom: 6px;
text-align: left; cursor: pointer;
font-family: inherit;
color: var(--fg);
}
.item-title-text {
flex: 1; min-width: 0;
font-size: 15px; font-weight: 500; line-height: 1.4;
text-wrap: pretty;
}
.item-title-chev {
flex-shrink: 0; padding-top: 3px;
font-size: 12px; color: var(--fg-dim);
transition: transform .15s, color .15s;
}
.item-title:hover .item-title-text { color: var(--purple); }
.item-title:hover .item-title-chev { color: var(--purple); }
.item.is-expanded .item-title-chev { transform: rotate(180deg); color: var(--purple); }
.item-body { display: none; margin-top: 8px; margin-bottom: 12px; }
.item.is-expanded .item-body { display: block; }
.item-snippet {
font-size: 14px; color: var(--fg-mid); line-height: 1.65;
margin-bottom: 10px;
}
.so-what {
background: var(--purple-soft);
border: 1px solid var(--purple-border);
border-radius: 5px;
padding: 8px 11px;
}
.so-what-label { font-size: 12px; font-weight: 600; color: var(--purple); }
.so-what-body { font-size: 12px; color: var(--fg-mid); line-height: 1.55; }
.item-actions {
display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap;
}
.read-article {
display: inline-flex; align-items: center; gap: 6px;
font-size: 13px; padding: 8px 16px; min-height: 40px;
background: var(--purple-soft); border: 1px solid var(--purple-border);
border-radius: 6px;
color: var(--purple-bright); text-decoration: none;
font-family: inherit;
}
.read-article:hover { background: var(--purple-dim); border-color: var(--purple-bright); }
.collapse-btn {
display: inline-flex; align-items: center;
font-size: 13px; padding: 8px 14px; min-height: 40px;
background: none; border: 1px solid var(--border-2);
border-radius: 6px; color: var(--fg-dim);
cursor: pointer; font-family: inherit;
}
.collapse-btn:hover { color: var(--fg); border-color: var(--fg-mid); }
.item .meta {
display: flex; gap: 10px; align-items: center; flex-wrap: wrap;
margin-top: 4px;
}
.item .meta .source {
font-size: 12px; color: var(--fg-mid); font-weight: 500;
}
.item .meta .source::before {
content: ""; display: inline-block;
width: 4px; height: 4px; border-radius: 50%;
background: var(--fg-dim); margin-right: 8px;
vertical-align: middle;
}
.item .meta .date { font-size: 12px; color: var(--fg-dim); }
.score-pill {
font-family: "DM Mono", monospace;
font-size: 11px;
border: 1px solid; border-radius: 3px;
padding: 1px 6px;
}
.score-pill.score-high { color: var(--green); background: oklch(68% 0.13 145 / 0.18); border-color: oklch(68% 0.13 145 / 0.3); }
.score-pill.score-mid { color: var(--purple); background: var(--purple-soft); border-color: var(--purple-border); }
.score-pill.score-low { color: var(--fg-dim); background: rgba(255,255,255,0.05); border-color: rgba(255,255,255,0.18); }
.resurfacing {
font-size: 12px; color: var(--fg-dim);
cursor: help; user-select: none;
}
footer {
padding: 24px 20px; text-align: center;
font-size: 12px; color: var(--fg-dim);
border-top: 1px solid var(--border);
}
footer a { color: var(--fg-dim); }
.is-hidden { display: none !important; }
@media (max-width: 600px) {
body { font-size: 16px; }
.item-title { font-size: 17px; }
.item-summary, .item-body p { font-size: 15px; }
.so-what-body { font-size: 14px; }
.chip { font-size: 13px; }
.topbar-title { font-size: 18px; }
.topbar-date { font-size: 14px; }
.meta, .item .meta .date, .score-pill, .tag-pill { font-size: 12px; }
}
"""
# --------------------------------------------------------------------------- #
# Tag post-processing + chip filter
# --------------------------------------------------------------------------- #
_TAG_ELEMENT_RE = re.compile(
r'^(<li([^>]*)>)(.*?)(</li>)\s*$',
re.DOTALL,
)
# Match the {tags: ...} literal at the tail of a bullet, tolerating an
# optional closing </p> tag (markdown wraps loose-list items in <p>).
_TAG_SUFFIX_RE = re.compile(r'\s*\{tags:\s*([^}]*)\}\s*(</p>)?\s*$')
_BODY_LI_RE = re.compile(r'<li\b[^>]*>.*?</li>', re.DOTALL)
def _canonicalize_tags(raw: str) -> list[str]:
"""Normalise a comma-separated tag list to canonical taxonomy casing."""
out: list[str] = []
seen: set[str] = set()
for part in raw.split(","):
key = part.strip().lower()
if not key:
continue
canonical = _TAG_LOOKUP.get(key)
if canonical and canonical not in seen:
out.append(canonical)
seen.add(canonical)
return out
def transform_tag_element(snippet: str) -> tuple[str, set[str]]:
"""Strip a `{tags: …}` suffix from a single `<li>` and attach `data-tags`.
Returns the rewritten element and the set of canonical tags found.
"""
m = _TAG_ELEMENT_RE.match(snippet)
if not m:
return snippet, set()
_open, attrs, content, close = m.groups()
suffix = _TAG_SUFFIX_RE.search(content)
if suffix:
tag_list = _canonicalize_tags(suffix.group(1))
# Re-attach the closing </p> if the suffix consumed it, so the LI
# stays well-formed for the structured card parser downstream.
closing = suffix.group(2) or ""
content = content[: suffix.start()].rstrip() + closing
else:
tag_list = []
new_open = f'<li{attrs} data-tags="{" ".join(tag_list)}">'
return new_open + content + close, set(tag_list)
def _process_tags_in_body(body_html: str) -> tuple[str, set[str]]:
seen: set[str] = set()
def repl(m: re.Match) -> str:
new, tags = transform_tag_element(m.group(0))
seen.update(tags)
return new
return _BODY_LI_RE.sub(repl, body_html), seen
def render_chip_bar(counts: dict[str, int] | None = None) -> str:
parts = ['<div class="chips" role="tablist">']
parts.append(
'<button type="button" class="chip is-active" data-tag="all">All</button>'
)
for tag in TAG_TAXONOMY:
if counts is None:
label = tag
else:
label = f"{tag} ({counts.get(tag, 0)})"
parts.append(
f'<button type="button" class="chip" data-tag="{tag}">{label}</button>'
)
parts.append("</div>")
return "\n".join(parts)
_ARTICLE_DATA_TAGS_RE = re.compile(
r'<article\b[^>]*\bdata-tags="([^"]*)"', re.IGNORECASE
)
def _count_tags_in_body(body_html: str) -> dict[str, int]:
"""Count taxonomy tags across rendered ``<article data-tags="…">`` cards.
Items with multiple tags increment each tag — the chip count is "items
matching this filter," not a partition.
"""
counts: dict[str, int] = {tag: 0 for tag in TAG_TAXONOMY}
for match in _ARTICLE_DATA_TAGS_RE.finditer(body_html):
for tag in match.group(1).split():
if tag in counts:
counts[tag] += 1
return counts
def _chip_counts_for_body(body_html: str) -> dict[str, int] | None:
"""Return tag counts to render on chips, or ``None`` to render plain.
The ``--no-summarize`` ranked-list path doesn't assign tags, so every
count would be ``0`` — a chip bar full of ``(0)`` is worse than no
counts at all. Suppress in that case.
"""
counts = _count_tags_in_body(body_html)
return counts if any(counts.values()) else None
INTERACTIONS_JS = """
<script>
(function () {
// Topic filter chips
var chips = document.querySelectorAll('.chip');
function applyFilter(tag) {
chips.forEach(function (c) {
c.classList.toggle('is-active', c.dataset.tag === tag);
});
document.querySelectorAll('[data-tags]').forEach(function (el) {
var tags = (el.dataset.tags || '').split(' ').filter(Boolean);
// Untagged items (e.g. Key takeaways bullets) stay visible under
// every filter — they're synthesis, not topic-scoped.
var show = tag === 'all' || tags.length === 0 || tags.indexOf(tag) !== -1;
el.classList.toggle('is-hidden', !show);
});
}
chips.forEach(function (chip) {
chip.addEventListener('click', function () {
applyFilter(chip.dataset.tag);
});
});
// Item expand/collapse on title click
document.querySelectorAll('.item-title').forEach(function (btn) {
btn.addEventListener('click', function () {
var item = btn.closest('.item');
if (item) item.classList.toggle('is-expanded');
});
});
// Item explicit collapse button
document.querySelectorAll('.collapse-btn').forEach(function (btn) {
btn.addEventListener('click', function () {
var item = btn.closest('.item');
if (item) item.classList.remove('is-expanded');
});
});
// Takeaways collapsible
var takeawaysToggle = document.querySelector('.takeaways-toggle');
var takeawaysBody = document.querySelector('.takeaways-body');
function setTakeawaysCollapsed(collapsed) {
if (!takeawaysBody || !takeawaysToggle) return;
takeawaysBody.classList.toggle('is-collapsed', collapsed);
takeawaysToggle.setAttribute('aria-expanded', String(!collapsed));
var chev = takeawaysToggle.querySelector('.takeaways-chevron');
if (chev) chev.textContent = collapsed ? '▼' : '▲';
}
if (takeawaysToggle) {