返回 last30days-skill
briefing.py
根目录 / skills / last30days / scripts / briefing.py
1 #!/usr/bin/env python3
2 """Morning briefing generator for last30days.
3
4 Synthesizes accumulated findings into formatted briefings.
5 The Python script collects the data; the agent (via SKILL.md) does the
6 beautiful synthesis. This script provides the structured data.
7
8 Usage:
9 python3 briefing.py generate # Daily briefing data
10 python3 briefing.py generate --weekly # Weekly digest data
11 python3 briefing.py show [--date DATE] # Show saved briefing
12 """
13
14 import argparse
15 import json
16 import os
17 import re
18 import stat
19 import sys
20 from datetime import datetime, timedelta, timezone
21 from pathlib import Path
22
23 SCRIPT_DIR = Path(__file__).parent.resolve()
24 sys.path.insert(0, str(SCRIPT_DIR))
25
26 import store
27 from lib.private_files import write_private_text
28
29 _parse_budget = store.parse_budget
30
31 BRIEFS_DIR = Path.home() / ".local" / "share" / "last30days" / "briefs"
32
33
34 def _parse_sqlite_utc_timestamp(value: str) -> datetime:
35 return datetime.strptime(value, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
36
37
38 def generate_daily(since: str = None) -> dict:
39 """Generate daily briefing data.
40
41 Returns structured data for the agent to synthesize into a beautiful briefing.
42 """
43 store.init_db()
44 topics = store.list_topics()
45
46 if not topics:
47 return {
48 "status": "no_topics",
49 "message": "No watchlist topics yet. Add one with: last30days watch add \"your topic\"",
50 }
51
52 enabled = [t for t in topics if t["enabled"]]
53 if not enabled:
54 return {
55 "status": "no_enabled",
56 "message": "All topics are paused. Enable a topic to generate briefings.",
57 }
58
59 # Default: findings since yesterday
60 if not since:
61 since = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
62
63 briefing_topics = []
64 total_new = 0
65
66 for topic in enabled:
67 findings = store.get_new_findings(topic["id"], since)
68 last_run = topic.get("last_run")
69 last_status = topic.get("last_status", "unknown")
70
71 # Calculate staleness
72 stale = False
73 hours_ago = None
74 if last_run:
75 try:
76 run_dt = _parse_sqlite_utc_timestamp(last_run)
77 hours_ago = (datetime.now(timezone.utc) - run_dt).total_seconds() / 3600
78 stale = hours_ago > 36 # Stale if > 36 hours
79 except (ValueError, TypeError):
80 stale = True
81
82 topic_data = {
83 "name": topic["name"],
84 "findings": findings,
85 "new_count": len(findings),
86 "last_run": last_run,
87 "last_status": last_status,
88 "stale": stale,
89 "hours_ago": round(hours_ago, 1) if hours_ago else None,
90 }
91
92 # Extract top finding by engagement
93 if findings:
94 top = max(findings, key=lambda f: f.get("engagement_score") or 0)
95 topic_data["top_finding"] = {
96 "title": top.get("source_title", ""),
97 "source": top.get("source", ""),
98 "author": top.get("author", ""),
99 "engagement": top.get("engagement_score", 0),
100 "content": top.get("content", "")[:300],
101 }
102
103 briefing_topics.append(topic_data)
104 total_new += len(findings)
105
106 # Cost info
107 daily_cost = store.get_daily_cost()
108 raw_budget = store.get_setting("daily_budget", "5.00")
109 try:
110 budget: float | None = _parse_budget(raw_budget)
111 budget_error = None
112 except ValueError as exc:
113 budget = None
114 budget_error = str(exc)
115
116 # Find the single top finding across all topics (for TL;DR)
117 all_findings = []
118 for t in briefing_topics:
119 for f in t["findings"]:
120 f["_topic"] = t["name"]
121 all_findings.append(f)
122
123 top_overall = None
124 if all_findings:
125 top_overall = max(all_findings, key=lambda f: f.get("engagement_score") or 0)
126
127 cost_info: dict = {
128 "daily": daily_cost,
129 "budget": budget,
130 }
131 if budget_error is not None:
132 cost_info["budget_error"] = budget_error
133
134 result = {
135 "status": "ok",
136 "date": datetime.now().strftime("%Y-%m-%d"),
137 "since": since,
138 "topics": briefing_topics,
139 "total_new": total_new,
140 "total_topics": len(briefing_topics),
141 "top_finding": {
142 "title": top_overall.get("source_title", ""),
143 "source": top_overall.get("source", ""),
144 "source_url": top_overall.get("source_url", ""),
145 "topic": top_overall.get("_topic", ""),
146 "engagement": top_overall.get("engagement_score", 0),
147 } if top_overall else None,
148 "cost": cost_info,
149 "failed_topics": [
150 t["name"] for t in briefing_topics if t["last_status"] == "failed"
151 ],
152 }
153
154 # Save briefing data
155 _save_briefing(result)
156
157 return result
158
159
160 def generate_weekly() -> dict:
161 """Generate weekly digest data with trend analysis."""
162 store.init_db()
163
164 week_ago = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
165 two_weeks_ago = (datetime.now() - timedelta(days=14)).strftime("%Y-%m-%d")
166
167 topics = store.list_topics()
168 if not topics:
169 return {"status": "no_topics", "message": "No watchlist topics."}
170
171 weekly_topics = []
172
173 for topic in topics:
174 if not topic["enabled"]:
175 continue
176
177 # This week's findings
178 this_week = store.get_new_findings(topic["id"], week_ago)
179
180 # Last week's findings (for comparison)
181 last_week = store.get_new_findings(topic["id"], two_weeks_ago, before=week_ago)
182
183 this_engagement = sum(f.get("engagement_score") or 0 for f in this_week)
184 last_engagement = sum(f.get("engagement_score") or 0 for f in last_week)
185
186 # Trend calculation
187 if last_engagement > 0:
188 engagement_change = ((this_engagement - last_engagement) / last_engagement) * 100
189 else:
190 engagement_change = 100 if this_engagement > 0 else 0
191
192 weekly_topics.append({
193 "name": topic["name"],
194 "this_week_count": len(this_week),
195 "last_week_count": len(last_week),
196 "this_week_engagement": this_engagement,
197 "last_week_engagement": last_engagement,
198 "engagement_change_pct": round(engagement_change, 1),
199 # get_new_findings returns first_seen DESC, so sort by engagement
200 # before slicing — otherwise the digest headlines the most recent
201 # items, not the highest-engagement ones (the daily path keys on
202 # engagement too).
203 "top_findings": sorted(
204 this_week,
205 key=lambda f: f.get("engagement_score") or 0,
206 reverse=True,
207 )[:5],
208 })
209
210 result = {
211 "status": "ok",
212 "type": "weekly",
213 "week_of": week_ago,
214 "topics": weekly_topics,
215 }
216
217 _save_briefing(result, suffix="-weekly")
218
219 return result
220
221
222 _BRIEFING_DATE_RE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
223
224
225 def _read_briefing_json(candidate: Path, root: Path) -> dict | None:
226 if candidate.is_symlink() or (
227 hasattr(os.path, "isjunction") and os.path.isjunction(candidate)
228 ):
229 return None
230 try:
231 resolved = candidate.resolve(strict=False)
232 except OSError:
233 return None
234 if not resolved.is_relative_to(root):
235 return None
236 flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
237 fd = -1
238 parent_fd = -1
239 try:
240 if (
241 candidate.name
242 and os.open in os.supports_dir_fd
243 and hasattr(os, "O_DIRECTORY")
244 and hasattr(os, "O_NOFOLLOW")
245 ):
246 parent_fd = os.open(
247 root,
248 os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
249 )
250 fd = os.open(candidate.name, flags, dir_fd=parent_fd)
251 else:
252 fd = os.open(candidate, flags)
253 except OSError:
254 return None
255 finally:
256 if parent_fd >= 0:
257 try:
258 os.close(parent_fd)
259 except OSError:
260 pass
261 try:
262 st = os.fstat(fd)
263 if not stat.S_ISREG(st.st_mode):
264 return None
265 handle = os.fdopen(fd, "r", encoding="utf-8")
266 fd = -1
267 with handle as f:
268 data = json.load(f)
269 return data if isinstance(data, dict) else None
270 except (OSError, UnicodeDecodeError, json.JSONDecodeError):
271 return None
272 finally:
273 if fd >= 0:
274 try:
275 os.close(fd)
276 except OSError:
277 pass
278
279
280 def show_briefing(date: str = None) -> dict:
281 """Load a saved briefing by date."""
282 if not date:
283 date = datetime.now().strftime("%Y-%m-%d")
284 if not isinstance(date, str) or not _BRIEFING_DATE_RE.fullmatch(date):
285 return {
286 "status": "invalid_date",
287 "message": "Invalid date format; expected YYYY-MM-DD.",
288 }
289 try:
290 datetime.strptime(date, "%Y-%m-%d")
291 except ValueError:
292 return {
293 "status": "invalid_date",
294 "message": "Invalid calendar date; expected YYYY-MM-DD.",
295 }
296
297 root = BRIEFS_DIR.resolve(strict=False)
298 for filename in (f"{date}.json", f"{date}-weekly.json"):
299 loaded = _read_briefing_json(BRIEFS_DIR / filename, root)
300 if loaded is not None:
301 return loaded
302
303 return {"status": "not_found", "message": f"No briefing found for {date}."}
304
305
306 def _save_briefing(data: dict, suffix: str = ""):
307 """Save briefing data to local archive."""
308 BRIEFS_DIR.mkdir(parents=True, exist_ok=True)
309 date = datetime.now().strftime("%Y-%m-%d")
310 path = BRIEFS_DIR / f"{date}{suffix}.json"
311 write_private_text(path, json.dumps(data, indent=2, default=str), encoding="utf-8")
312
313
314 def main():
315 # Briefings run on a schedule: any engine run started from here is a
316 # scheduled run, which keeps the logged-in Reddit session off.
317 os.environ.setdefault("LAST30DAYS_SCHEDULED_RUN", "1")
318 parser = argparse.ArgumentParser(description="Generate last30days briefings")
319 sub = parser.add_subparsers(dest="command")
320
321 # generate
322 g = sub.add_parser("generate", help="Generate a briefing")
323 g.add_argument("--weekly", action="store_true", help="Weekly digest")
324 g.add_argument("--since", help="Findings since date (YYYY-MM-DD)")
325
326 # show
327 s = sub.add_parser("show", help="Show a saved briefing")
328 s.add_argument("--date", help="Date (YYYY-MM-DD, default: today)")
329
330 args = parser.parse_args()
331
332 if args.command == "generate":
333 if args.weekly:
334 result = generate_weekly()
335 else:
336 result = generate_daily(since=args.since)
337 print(json.dumps(result, indent=2, default=str))
338
339 elif args.command == "show":
340 result = show_briefing(date=args.date)
341 print(json.dumps(result, indent=2, default=str))
342 if result.get("status") == "invalid_date":
343 sys.exit(2)
344
345 else:
346 parser.print_help()
347 sys.exit(1)
348
349
350 if __name__ == "__main__":
351 main()
352
352 lines PYTHON