-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjobs.py
More file actions
862 lines (754 loc) · 30.7 KB
/
jobs.py
File metadata and controls
862 lines (754 loc) · 30.7 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
import logging
import os
import re
import time
from datetime import datetime, timezone
from urllib.parse import urlsplit, urlunsplit
import requests
import schedule
from dotenv import load_dotenv
from tenacity import before_sleep_log, retry, stop_after_attempt, wait_fixed
from config import load_config
from constants import ENGINEERING_TEAM_SLUG, PRIORITY_TO_SCORE
from fleet_health_cache import refresh_fleet_health_cache, should_use_redis_cache
from github import (
get_pr_diff,
get_prs_waiting_for_review_by_reviewer,
get_prs_with_changes_requested_by_reviewer,
merged_prs_by_author,
merged_prs_by_reviewer,
)
from issue_timing import format_issue_sla_text, parse_linear_dt
from leaderboard import (
calculate_cycle_project_lead_points,
calculate_cycle_project_member_points,
)
from linear.issues import (
get_completed_issues,
get_completed_issues_for_person,
get_open_issues,
get_stale_issues_by_assignee,
)
from linear.projects import get_projects
from openai_client import get_chat_function_call
from project_dates import format_project_target_status, parse_iso_date
from support import get_support_slugs
load_dotenv()
# Retry configuration for the with_retries decorator.
MAX_RETRY_COUNT = 3
RETRY_SLEEP_SECONDS = 5
MAX_DIFF_CHARS = 12000
MAX_DIFF_FILES = 20
FLEET_HEALTH_REFRESH_DEFAULT_SECONDS = 60
AIRFLOW_FLEET_HEARTBEAT_TIMEOUT_SECONDS = 10
INACTIVE_PROJECT_STATUS_NAMES = {
"completed",
"incomplete",
"canceled",
"cancelled",
"released",
}
def _read_positive_int_env(name: str, default: int) -> int:
raw = os.getenv(name, "").strip()
if not raw:
return default
try:
parsed = int(raw)
except ValueError:
return default
return parsed if parsed > 0 else default
def _is_inactive_project(project: dict) -> bool:
status_name = ((project.get("status") or {}).get("name") or "").strip().lower()
return bool(project.get("completedAt")) or status_name in INACTIVE_PROJECT_STATUS_NAMES
def _normalize_linear_display_name(name: str) -> str:
return name.replace(".", " ").replace("-", " ").title()
def _is_engineering_lead_project(project: dict, people_config: dict) -> bool:
engineering_slugs = {
slug for slug, info in people_config.items() if info.get("team") == ENGINEERING_TEAM_SLUG
}
name_to_slug = {}
for slug, info in people_config.items():
username = info.get("linear_username") or slug
full = _normalize_linear_display_name(username)
name_to_slug[full] = slug
first = full.split()[0]
name_to_slug.setdefault(first, slug)
lead = (project.get("lead") or {}).get("displayName")
if not lead:
return False
normalized = _normalize_linear_display_name(lead)
slug = name_to_slug.get(normalized) or name_to_slug.get(normalized.split()[0])
return slug in engineering_slugs
def post_to_slack(markdown: str):
"""Send a message to Slack and raise or log on failure."""
url = os.environ.get("SLACK_WEBHOOK_URL")
if not url:
logging.error("SLACK_WEBHOOK_URL environment variable is not set or empty.")
raise RuntimeError("Missing SLACK_WEBHOOK_URL environment variable.")
response = requests.post(url, json={"text": markdown})
if response.status_code != 200:
logging.error("Slack API returned %s: %s", response.status_code, response.text)
response.raise_for_status()
def refresh_airflow_fleet_health_cache_job():
payload, status = refresh_fleet_health_cache()
report_airflow_fleet_health_heartbeat(payload, status)
logging.info(
"Refreshed airflow fleet health cache (status=%s, http_status=%s, evaluated_dags=%s)",
payload.get("status"),
status,
payload.get("evaluated_dags"),
)
def report_airflow_fleet_health_heartbeat(payload: dict, status: int) -> None:
heartbeat_url = os.getenv("AIRFLOW_FLEET_HEARTBEAT_URL", "").strip()
if not heartbeat_url:
return
is_healthy = status < 400 and payload.get("status") == "healthy"
url = heartbeat_url if is_healthy else _append_url_path(heartbeat_url, "fail")
try:
response = requests.get(url, timeout=AIRFLOW_FLEET_HEARTBEAT_TIMEOUT_SECONDS)
if response.status_code >= 400:
logging.error(
"Airflow fleet Better Stack heartbeat returned %s: %s",
response.status_code,
response.text,
)
except requests.RequestException:
logging.exception("Failed to report airflow fleet Better Stack heartbeat")
def _append_url_path(url: str, segment: str) -> str:
parsed = urlsplit(url)
path = f"{parsed.path.rstrip('/')}/{segment}"
return urlunsplit((parsed.scheme, parsed.netloc, path, parsed.query, parsed.fragment))
def post_to_manager_slack(markdown: str):
"""Send a message to the manager Slack webhook, or return early if not configured."""
url = os.environ.get("MANAGER_SLACK_WEBHOOK_URL")
if not url:
logging.error(
"MANAGER_SLACK_WEBHOOK_URL environment variable is not set or empty; "
"unable to send manager Slack message."
)
return
response = requests.post(url, json={"text": markdown})
if response.status_code != 200:
logging.error("Manager Slack API returned %s: %s", response.status_code, response.text)
response.raise_for_status()
def format_bug_line(bug):
"""Return a formatted Slack message line for a bug."""
sla_text = format_issue_sla_text(bug, now=datetime.now(timezone.utc))
timing_text = sla_text or f"+{bug['daysOpen']}d"
reviewer = (
get_slack_markdown_by_linear_username(bug["assignee"]["displayName"])
if bug["assignee"]
else ""
)
platform_text = f", {bug['platform']}" if bug["platform"] else ""
reviewer_text = f", {reviewer}" if reviewer else ""
content = f"<{bug['url']}|{bug['title']}> ({timing_text}{platform_text}{reviewer_text})"
if bug.get("priority") == 1:
return f"- \U0001f6a8 {content} \U0001f6a8"
return f"- {content}"
def with_retries(func):
"""Decorator that retries the wrapped function.
Retries up to MAX_RETRY_COUNT times on failure. After each failure, logs the
exception and waits RETRY_SLEEP_SECONDS before retrying. After the final
attempt, the last exception is re-raised.
"""
logger = logging.getLogger(__name__)
retry_decorator = retry(
reraise=True,
stop=stop_after_attempt(MAX_RETRY_COUNT),
wait=wait_fixed(RETRY_SLEEP_SECONDS),
before_sleep=before_sleep_log(logger, logging.ERROR),
)
return retry_decorator(func)
def get_team_members(team_slug: str):
"""Return the subset of people config entries on a given team."""
config = load_config()
people = config.get("people", {})
return {slug: info for slug, info in people.items() if info.get("team") == team_slug}
def get_slack_markdown_by_linear_username(username):
# Handle missing or empty usernames explicitly to avoid unnecessary config access.
if username is None or (isinstance(username, str) and not username.strip()):
return "No Assignee"
config = load_config()
for person in config["people"].values():
if person.get("linear_username") == username:
return f"<@{person['slack_id']}>"
return "No Assignee"
def get_slack_markdown_by_github_username(username):
# Validate input to avoid propagating None or empty usernames.
if username is None or (isinstance(username, str) and not username.strip()):
logging.warning(
"get_slack_markdown_by_github_username called with invalid username: %r",
username,
)
return "Unknown user"
config = load_config()
for person in config["people"].values():
if person.get("github_username") == username:
return f"<@{person['slack_id']}>"
return username
def _normalize_platform_name(value: str | None) -> str | None:
if value is None:
return None
normalized = value.strip().lower().replace(" ", "-")
return normalized or None
def _person_matches_any_unassigned_platform(person: dict, bugs: list[dict]) -> bool:
platform_whitelist = person.get("platform_whitelist")
if platform_whitelist is None:
return True
allowed_platforms = {
normalized
for normalized in (_normalize_platform_name(platform) for platform in platform_whitelist)
if normalized
}
if not allowed_platforms:
person_identifier = (
person.get("linear_username") or person.get("slack_id") or "unknown-person"
)
logging.warning(
"Ignoring empty or invalid platform_whitelist for %s; "
"falling back to unfiltered unassigned bug notifications (raw value: %r)",
person_identifier,
platform_whitelist,
)
return True
return any(_normalize_platform_name(bug.get("platform")) in allowed_platforms for bug in bugs)
def _get_pr_diffs(issue):
"""Return a list of diffs for PRs linked in the issue attachments."""
def summarize_diff(diff_text: str) -> str:
files = []
for line in diff_text.splitlines():
if not line.startswith("diff --git "):
continue
parts = line.split(" ")
if len(parts) < 4:
continue
path = parts[2]
if path.startswith("a/"):
path = path[2:]
if path and path not in files:
files.append(path)
total_files = len(files)
shown_files = files[:MAX_DIFF_FILES]
file_list = ", ".join(shown_files)
if total_files > MAX_DIFF_FILES:
file_list += f", +{total_files - MAX_DIFF_FILES} more"
if not file_list:
file_list = "File list unavailable"
return f"Diff too large ({len(diff_text)} chars). Files ({total_files}): {file_list}"
diffs = []
for attachment in issue.get("attachments", {}).get("nodes", []):
metadata = attachment.get("metadata", {})
url = metadata.get("url")
if not url:
continue
match = re.search(r"github.com/([^/]+)/([^/]+)/pull/(\d+)", url)
if not match:
continue
owner, repo, number = match.groups()
try:
diff = get_pr_diff(owner, repo, int(number))
if len(diff) > MAX_DIFF_CHARS:
diffs.append(summarize_diff(diff))
else:
diffs.append(diff)
except Exception as e: # pragma: no cover - network errors are ignored
logging.error(
"Failed to fetch diff for %s/%s#%s (error type: %s)",
owner,
repo,
number,
type(e).__name__,
)
return diffs
@with_retries
def post_priority_bugs():
config = load_config()
open_priority_bugs = get_open_issues(2, "Bug")
unassigned = [bug for bug in open_priority_bugs if bug["assignee"] is None]
now = datetime.now(timezone.utc)
def issue_has_sla(issue: dict) -> bool:
return any(
issue.get(field_name)
for field_name in (
"slaType",
"slaStartedAt",
"slaMediumRiskAt",
"slaHighRiskAt",
"slaBreachesAt",
)
)
def issue_reached_sla(issue: dict, field_name: str) -> bool:
reached_at = parse_linear_dt(issue.get(field_name))
if not reached_at:
return False
return reached_at <= now
open_priority_bugs = [bug for bug in open_priority_bugs if issue_has_sla(bug)]
unassigned = [bug for bug in open_priority_bugs if bug["assignee"] is None]
overdue = [bug for bug in open_priority_bugs if issue_reached_sla(bug, "slaBreachesAt")]
overdue_ids = {bug["id"] for bug in overdue if bug.get("id")}
at_risk = [
bug
for bug in open_priority_bugs
if bug.get("id") not in overdue_ids and issue_reached_sla(bug, "slaHighRiskAt")
]
sections = []
if unassigned:
unassigned_section = "*Unassigned Priority Bugs*\n\n"
unassigned_section += "\n".join(
[
format_bug_line(bug)
for bug in sorted(
unassigned,
key=lambda x: x["daysOpen"],
reverse=True,
)
]
)
assigned = {bug["assignee"]["displayName"] for bug in open_priority_bugs if bug["assignee"]}
notified_slack_ids: set[str] = set()
slug_by_slack_id: dict[str, str] = {}
support_slugs = get_support_slugs()
for slug in support_slugs:
person = config["people"].get(slug)
if not person:
continue
if person.get("linear_username") in assigned:
continue
if not _person_matches_any_unassigned_platform(person, unassigned):
continue
slack_id = person.get("slack_id")
if not slack_id:
continue
notified_slack_ids.add(slack_id)
slug_by_slack_id.setdefault(slack_id, slug)
if notified_slack_ids:
notified_lines = []
for slack_id in sorted(
notified_slack_ids,
key=lambda sid: slug_by_slack_id.get(sid, ""),
):
notified_lines.append(f"<@{slack_id}>")
notified_text = "\n".join(notified_lines)
unassigned_section += f"\n\nattn:\n\n{notified_text}"
sections.append(unassigned_section)
if at_risk:
sections.append(
"*At Risk*\n\n"
+ "\n".join(
[
format_bug_line(bug)
for bug in sorted(
at_risk,
key=lambda x: x["daysOpen"],
reverse=True,
)
]
)
)
if overdue:
sections.append(
"*Overdue*\n\n"
+ "\n".join(
[
format_bug_line(bug)
for bug in sorted(
overdue,
key=lambda x: x["daysOpen"],
reverse=True,
)
]
)
)
if sections:
markdown = "\n\n".join(sections)
markdown += f"\n\n<{os.getenv('APP_URL')}|View Bug Board>"
post_to_slack(markdown)
@with_retries
def post_leaderboard():
days = 7
config = load_config()
people_config = config.get("people", {})
engineering_team_slugs = {
slug for slug, info in people_config.items() if info.get("team") == ENGINEERING_TEAM_SLUG
}
def normalize_identity(value: str | None) -> str:
if not value:
return ""
return re.sub(r"[^a-z0-9]", "", value.lower())
alias_to_slug = {}
for slug, info in people_config.items():
linear_username = info.get("linear_username") or slug
display_alias = re.sub(r"[._-]+", " ", linear_username).title() if linear_username else slug
aliases = {slug, linear_username, display_alias}
slack_id = info.get("slack_id")
if slack_id:
aliases.add(f"<@{slack_id}>")
github_username = info.get("github_username")
if github_username:
aliases.add(github_username)
for alias in aliases:
normalized = normalize_identity(alias)
if normalized:
alias_to_slug[normalized] = slug
items = (
get_completed_issues(5, "Bug", days)
+ get_completed_issues(5, "Feature Request", days)
+ get_completed_issues(5, "Technical Change", days)
)
items = [item for item in items if not item.get("project")]
priority_to_score = PRIORITY_TO_SCORE
leaderboard = {}
for item in items:
assignee = item["assignee"]
if not assignee:
continue
assignee_name = assignee["displayName"]
slack_markdown = get_slack_markdown_by_linear_username(assignee_name)
if slack_markdown not in leaderboard:
leaderboard[slack_markdown] = 0
score = priority_to_score.get(item["priority"], 0)
leaderboard[slack_markdown] += score
for reviewer, prs in merged_prs_by_reviewer(days).items():
slack_markdown = get_slack_markdown_by_github_username(reviewer)
if slack_markdown not in leaderboard:
leaderboard[slack_markdown] = 0
leaderboard[slack_markdown] += len(prs)
for author, prs in merged_prs_by_author(days).items():
slack_markdown = get_slack_markdown_by_github_username(author)
if slack_markdown not in leaderboard:
leaderboard[slack_markdown] = 0
leaderboard[slack_markdown] += len(prs)
cycle_points = calculate_cycle_project_lead_points(days)
for lead_name, points in cycle_points.items():
slack_markdown = get_slack_markdown_by_linear_username(lead_name)
key = slack_markdown if slack_markdown != "No Assignee" else lead_name
leaderboard[key] = leaderboard.get(key, 0) + points
member_points = calculate_cycle_project_member_points(days)
for member_name, points in member_points.items():
slack_markdown = get_slack_markdown_by_linear_username(member_name)
key = slack_markdown if slack_markdown != "No Assignee" else member_name
leaderboard[key] = leaderboard.get(key, 0) + points
filtered_leaderboard = {
assignee: score
for assignee, score in leaderboard.items()
if alias_to_slug.get(normalize_identity(assignee)) in engineering_team_slugs
}
leaderboard = dict(sorted(filtered_leaderboard.items(), key=lambda x: x[1], reverse=True))
medals = ["🥇", "🥈", "🥉"]
markdown = "*Weekly Leaderboard*\n\n"
for rank, (assignee, score) in enumerate(leaderboard.items()):
if rank >= 3:
break
markdown += f"{medals[rank]} {assignee}: {score}\n"
markdown += "\n\n"
markdown += (
"_scores - 20pts for urgent, 10pts for high, 5pts for medium, 1pt for low, "
"1pt per merged PR, 1pt per PR review, 30pts/week for completed cycle project leads, "
"15pts/week for completed cycle project members_\n\n"
)
markdown += f"<{os.getenv('APP_URL')}?days={days}|View Bug Board>"
post_to_slack(markdown)
@with_retries
def post_stale():
engineering_team_members = get_team_members(ENGINEERING_TEAM_SLUG)
people_by_github_username = {
person.get("github_username"): person
for person in engineering_team_members.values()
if person.get("github_username")
}
engineering_linear_usernames = {
person.get("linear_username")
for person in engineering_team_members.values()
if person.get("linear_username")
}
prs = get_prs_waiting_for_review_by_reviewer()
cr_prs = get_prs_with_changes_requested_by_reviewer()
stale_issues = get_stale_issues_by_assignee(
get_open_issues(5, "Bug")
+ get_open_issues(5, "Feature Request")
+ get_open_issues(5, "Technical Change"),
7,
)
if not prs and not stale_issues:
return
markdown = ""
filtered = {}
for reviewer, pr_list in prs.items():
if reviewer not in people_by_github_username:
continue
keep = []
for pr in pr_list:
crers = [r for r, pls in cr_prs.items() if pr in pls]
if any(r != reviewer for r in crers):
continue
keep.append(pr)
if keep:
filtered[reviewer] = keep
prs = filtered
if prs:
markdown += "*PRs - Checks Passing, Waiting for Review (+24h, <200 lines added)*\n"
for reviewer, pr_list in prs.items():
if not pr_list:
continue
unique_prs = {pr["url"]: pr for pr in pr_list}.values()
reviewer_slack_id = people_by_github_username.get(reviewer, {}).get("slack_id")
if reviewer_slack_id:
reviewer_slack_markdown = f"<@{reviewer_slack_id}>"
else:
reviewer_slack_markdown = reviewer
markdown += f"\n{reviewer_slack_markdown}:\n\n"
pr_days = []
for pr in unique_prs:
events = [
ev
for ev in pr.get("timelineItems", {}).get("nodes", [])
if ev.get("requestedReviewer", {}).get("login") == reviewer
]
if events:
created = max(ev["createdAt"] for ev in events)
# Parse GitHub-style ISO 8601 timestamp with explicit UTC timezone
dt = datetime.strptime(created, "%Y-%m-%dT%H:%M:%SZ").replace(
tzinfo=timezone.utc
)
days_waiting = (datetime.now(timezone.utc) - dt).days
else:
days_waiting = 0
pr_days.append((days_waiting, pr))
for days_waiting, pr in sorted(pr_days, key=lambda x: x[0], reverse=True):
markdown += f"- <{pr['url']}|{pr['title']}> (+{days_waiting}d)\n"
markdown += "\n\n"
filtered_stale_issues = {
assignee: issues
for assignee, issues in stale_issues.items()
if assignee in engineering_linear_usernames and issues
}
if not prs and not filtered_stale_issues:
return
if any(filtered_stale_issues.values()):
markdown += "*Stale Open Issues*\n"
for assignee, issues in filtered_stale_issues.items():
assignee_slack_markdown = get_slack_markdown_by_linear_username(assignee)
markdown += f"\n{assignee_slack_markdown}:\n\n"
for issue in issues:
markdown += f"- <{issue['url']}|{issue['title']}> ({issue['daysStale']}d)\n"
markdown += "\n\n"
markdown += f"<{os.getenv('APP_URL')}|View Bug Board>"
post_to_slack(markdown)
@with_retries
def post_inactive_engineers():
"""Send list of engineers with no completed Linear issues in the last 7 days."""
engineering_team_members = get_team_members(ENGINEERING_TEAM_SLUG)
inactive = []
base_url = os.getenv("APP_URL", "")
for person_key, person in engineering_team_members.items():
login = person.get("linear_username")
if not login:
continue
try:
completed = get_completed_issues_for_person(login, 7)
except Exception as e:
logging.error(f"Failed to fetch completed issues for {login}: {e}")
continue
if not completed:
# link to user page filtered to last 7 days
url = f"{base_url.rstrip('/')}/team/{person_key}?days=7"
inactive.append(f"- <{url}|{person_key}>")
if not inactive:
return
markdown = "*Engineers with no completed issues in the last 7 days*\n\n"
markdown += "\n".join(inactive)
post_to_manager_slack(markdown)
@with_retries
def post_project_updates():
"""Daily digest of overdue, ending-soon, and starting-soon projects."""
projects = get_projects()
people_config = load_config().get("people", {})
now = datetime.now(timezone.utc)
today = now.date()
overdue = []
ending_soon = []
starting_soon = []
for project in projects:
if not _is_engineering_lead_project(project, people_config):
continue
name = project.get("name") or "Untitled Project"
url = project.get("url")
lead = (project.get("lead") or {}).get("displayName")
lead_md = get_slack_markdown_by_linear_username(lead) if lead else "No Lead"
inactive = _is_inactive_project(project)
target_dt = parse_iso_date(project.get("targetDate"))
days_left, target_status_text = format_project_target_status(target_dt, now=now)
if not inactive and target_dt and target_status_text:
line = f"- <{url}|{name}> - {target_status_text} - Lead: {lead_md}"
if target_status_text.endswith("overdue"):
overdue.append({"name": name, "target_dt": target_dt, "line": line})
elif days_left is not None and 0 <= days_left <= 3:
ending_soon.append({"name": name, "target_dt": target_dt, "line": line})
if inactive:
continue
start_dt = parse_iso_date(project.get("startDate"))
if start_dt:
days_until_start = (start_dt - today).days
if 0 <= days_until_start <= 3:
starting_soon.append(
{
"name": name,
"start_dt": start_dt,
"line": f"- <{url}|{name}> - Lead: {lead_md}",
}
)
sections = []
if overdue:
ordered = sorted(overdue, key=lambda item: (item["target_dt"], item["name"].lower()))
sections.append("*Overdue Projects*\n\n" + "\n".join(item["line"] for item in ordered))
if ending_soon:
ordered = sorted(ending_soon, key=lambda item: (item["target_dt"], item["name"].lower()))
sections.append("*Projects Ending Soon*\n\n" + "\n".join(item["line"] for item in ordered))
if starting_soon:
ordered = sorted(starting_soon, key=lambda item: (item["start_dt"], item["name"].lower()))
sections.append(
"*Projects Starting Soon*\n\n" + "\n".join(item["line"] for item in ordered)
)
if sections:
post_to_slack("\n\n".join(sections))
@with_retries
def post_weekly_changelog():
"""Generate a customer changelog from completed issues."""
issues = (
get_completed_issues(5, "Bug", 7)
+ get_completed_issues(5, "Feature Request", 7)
+ get_completed_issues(5, "Technical Change", 7)
)
if not issues:
return
# remove any duplicate issues by id to avoid repeated entries in changelog
seen_ids = set()
unique = []
for issue in issues:
if issue.get("id") and issue["id"] not in seen_ids:
seen_ids.add(issue["id"])
unique.append(issue)
issues = unique
if not issues:
return
chunks = []
for issue in issues:
desc = issue.get("description") or ""
comments = " ".join(c.get("body", "") for c in issue.get("comments", {}).get("nodes", []))
diffs = _get_pr_diffs(issue)
chunk_parts = [
f"ID: {issue['id']}",
f"Title: {issue['title']}",
f"Platform: {issue.get('platform', '')}",
f"Description: {desc}",
f"Comments: {comments}",
]
if diffs:
chunk_parts.append("Diff:\n" + "\n".join(diffs))
chunks.append("\n".join(chunk_parts))
instructions = (
"Create a short customer-facing changelog from the provided issues. "
"Each issue chunk begins with 'ID: <issue id>'. "
"Group items under 'New Features', 'Bug Fixes', and 'Improvements'. "
"List each change as a short sentence with no markdown or bullet characters. "
"Ignore technical tasks, internal changes, and unfinished work. "
"Ensure each change appears only once in the changelog. "
"When a chunk includes a 'Diff:' section, use that diff as additional context. "
"Return a JSON object with keys 'New Features', 'Bug Fixes', and 'Improvements'. "
"Each item should be an object with fields 'id' (the issue id)"
"and 'summary' (the changelog text)."
)
input_text = "\n\n".join(chunks)
# Use OpenAI function calling to generate a structured changelog
item_schema = {
"type": "object",
"properties": {
"id": {"type": "string"},
"summary": {"type": "string"},
},
"required": ["id", "summary"],
}
function_spec = {
"name": "generate_changelog",
"description": "Generate a customer-facing changelog.",
"parameters": {
"type": "object",
"properties": {
"New Features": {"type": "array", "items": item_schema},
"Bug Fixes": {"type": "array", "items": item_schema},
"Improvements": {"type": "array", "items": item_schema},
},
"required": ["New Features", "Bug Fixes", "Improvements"],
},
}
try:
changelog_data = get_chat_function_call(
instructions,
user_input=input_text,
functions=function_spec,
function_call_name="generate_changelog",
)
except Exception as e:
logging.error(
"Failed to generate changelog via function call. Error: %s",
e,
)
changelog_data = {}
url_by_id = {issue["id"]: issue["url"] for issue in issues}
sections = []
for heading in ["New Features", "Bug Fixes", "Improvements"]:
items = changelog_data.get(heading, [])
if items:
sections.append(f"*{heading}*")
for item in items:
summary = item.get("summary", "")
issue_id = item.get("id")
url = url_by_id.get(issue_id)
if url:
sections.append(f"- <{url}|{summary}>")
else:
sections.append(f"- {summary}")
sections.append("")
changelog_text = "*Changelog (Experimental)*\n\n" + "\n".join(sections).rstrip()
changelog_text += f"\n\n<{os.getenv('APP_URL')}|View Bug Board>"
post_to_slack(changelog_text)
def run_debug_jobs() -> None:
if should_use_redis_cache():
refresh_airflow_fleet_health_cache_job()
post_inactive_engineers()
post_priority_bugs()
post_leaderboard()
# post_weekly_changelog()
post_stale()
post_project_updates()
def configure_scheduled_jobs() -> None:
if should_use_redis_cache():
refresh_interval_seconds = _read_positive_int_env(
"AIRFLOW_FLEET_HEALTH_REFRESH_SECONDS",
FLEET_HEALTH_REFRESH_DEFAULT_SECONDS,
)
schedule.every(refresh_interval_seconds).seconds.do(refresh_airflow_fleet_health_cache_job)
refresh_airflow_fleet_health_cache_job()
logging.info(
"Scheduled airflow fleet health cache refresh every %s seconds",
refresh_interval_seconds,
)
else:
logging.info("REDIS_URL not set; airflow fleet health cache refresh is disabled")
schedule.every().friday.at("13:00").do(post_inactive_engineers)
schedule.every().day.at("12:00").do(post_priority_bugs)
schedule.every().friday.at("20:00").do(post_leaderboard)
# schedule.every().thursday.at("19:00").do(post_weekly_changelog)
schedule.every().day.at("10:00", "America/New_York").do(post_stale)
schedule.every().day.at("14:00", "America/New_York").do(post_project_updates)
def main() -> None:
if os.getenv("DEBUG") == "true":
run_debug_jobs()
return
configure_scheduled_jobs()
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
main()