-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupdate_codey.py
More file actions
979 lines (824 loc) · 40.5 KB
/
update_codey.py
File metadata and controls
979 lines (824 loc) · 40.5 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
#!/usr/bin/env python3
# =============================================================================
# update_codey.py - No Mercy EDITION
# =============================================================================
# Codey is a neutral quality pet/tool for GitHub and GitLab.
# It shows the world that not everything is scam and AI-generated garbage.
# Codey scores Developer integrity — you can't fake it, you have to earn it.
#
# This tool is considered a security tool under ESOL v1.1:
# it audits developer behavior, code quality and social engineering patterns.
# Public audit available on GitHub — transparent, community-verified.
#
# Free to use on GitHub and GitLab.
# Selling this script or using it for reputation manipulation is prohibited.
#
# Licensed under Apache 2.0 + Ethical Security Operations License (ESOL v1.1)
# Jurisdiction: Germany (Berlin) — enforced under StGB §202a/b/c and DSGVO.
# https://github.com/VolkanSah/ESOL
#
# Copyright (c) 2026 VolkanSah & BadTin and some Cats 🐱
# =============================================================================
# Refactored + Bugs fixed + Issue analysis added
# BUG: marks fixed bugs
# NEW: marks new features
# IMPROVED: marks improvements
# =============================================================================
# Version 2.2.3 -DEV-
# Added RUN GUARD + some fixes
import requests
import json
import os
import sys
from datetime import datetime, timedelta, timezone
from collections import Counter
# ─────────────────────────────────────────────
# CONFIG
# ─────────────────────────────────────────────
TOKEN = os.environ.get('GIT_TOKEN') or os.environ.get('GITHUB_TOKEN')
REPO = os.environ.get('GIT_REPOSITORY') or os.environ.get('GITHUB_REPOSITORY')
# Bypass fallback
# ── CONFIG ──
ENABLE_FALLBACK = os.environ.get('CODEY_FALLBACK', 'false').lower() == 'true'
if not REPO:
print("WARNING: No REPO set. Using 'VolkanSah' as fallback.")
REPO = "VolkanSah"
# Game balance — all magic numbers in one place
GAME_BALANCE = {
'ENERGY_COST_COMMIT': 2.5,
'ENERGY_COST_PR': 5.0,
'ENERGY_REGEN_REST': 20,
'ENERGY_REGEN_ACTIVE': 5,
'DAILY_HUNGER_DECAY': 20,
'DAILY_HAPPINESS_DECAY': 12,
'XP_PER_COMMIT': 10,
'XP_PER_PR': 25,
'XP_PER_ISSUE_CLOSED': 8, # NEW: reward for closing issues
'HUNGER_GAIN_MODIFIER': 0.5,
'HAPPINESS_GAIN_MODIFIER': 0.8,
'BASE_LEVEL_REQUIREMENT': 25,
'STREAK_LOSS_DIVISOR': 10,
'WEEKEND_BONUS': 1.5,
}
# ─────────────────────────────────────────────
# RUN Guard to save calls, too
# ─────────────────────────────────────────────
# NEW since > 2.2.3
RUN_INTERVAL_HOURS = int(os.environ.get('CODEY_RUN_INTERVAL', 20))
def should_run_full_update(codey):
last = codey.get('last_update')
if not last:
return True, 999.0
try:
last_dt = datetime.fromisoformat(last.replace('Z', '+00:00'))
now = datetime.now(timezone.utc)
hours_since = (now - last_dt).total_seconds() / 3600
# Primär: anderer Kalendertag → immer updaten
if last_dt.date() < now.date():
return True, hours_since
# Fallback: Stundengrenze für mehrfaches Testen am selben Tag
return hours_since >= RUN_INTERVAL_HOURS, hours_since
except Exception:
return True, 999.0
# ─────────────────────────────────────────────
# REPO / OWNER NORMALIZATION
# ─────────────────────────────────────────────
def normalize_repo_input(r):
r = r.strip()
if r.startswith('http://') or r.startswith('https://'):
parts = r.rstrip('/').split('/')
if 'github.com' in parts:
idx = parts.index('github.com')
if len(parts) > idx + 2:
return f"{parts[idx + 1]}/{parts[idx + 2]}"
elif len(parts) > idx + 1:
return parts[idx + 1]
return r
REPO = normalize_repo_input(REPO)
is_repo_mode = '/' in REPO and len(REPO.split('/')) == 2
OWNER = REPO.split('/')[0]
# ─────────────────────────────────────────────
# API HELPERS
# ─────────────────────────────────────────────
headers = {}
if TOKEN:
headers = {
'Authorization': f'token {TOKEN}',
'Accept': 'application/vnd.github.v3+json'
}
else:
print("NOTE: No token set - heavily rate-limited.", file=sys.stderr)
def get_json_safe(url, params=None):
"""GET request with full error handling. Returns (ok: bool, data)."""
try:
r = requests.get(url, headers=headers, params=params, timeout=20)
except Exception as e:
print(f"Network-Error at {url}: {e}", file=sys.stderr)
return False, None
if not r.ok:
try:
body = r.json()
except Exception:
body = r.text
print(f"GitHub API Error {r.status_code} at {url}: {body}", file=sys.stderr)
return False, body
try:
return True, r.json()
except ValueError:
print(f"Response from {url} is not JSON.", file=sys.stderr)
return False, r.text
# own stared
# new from >2.2.x
def fetch_real_stars(owner):
"""
Exact same logic as codey_star_report.py.
Returns real star count (self-stars + fork stars removed).
BUG (FIXED): returned set() — not JSON-serializable.
Now returns int (count only). Themes and brutal_stats use 'self_starred_count'.
"""
self_starred = set()
page = 1
while True:
ok, data = get_json_safe(
f'https://api.github.com/users/{owner}/starred',
params={'per_page': 100, 'page': page}
)
if not ok or not isinstance(data, list) or not data:
break
for repo in data:
if repo.get('owner', {}).get('login', '').lower() == owner.lower():
self_starred.add(repo.get('name'))
if len(data) < 100:
break
page += 1
# BUG (FIXED): caller stored the set() directly in all_time_data['self_starred']
# which then landed in brutal_stats → codey.json → JSON crash.
# We return a plain int now. The set is only needed locally for star deduction.
return self_starred # still a set — but get_all_data_for_user stores only len()
# ─────────────────────────────────────────────
# DATA FETCHERS
# ─────────────────────────────────────────────
def get_user_data(owner):
ok, data = get_json_safe(f'https://api.github.com/users/{owner}')
return data if ok and isinstance(data, dict) else {}
def get_repo_data(full_repo):
ok, data = get_json_safe(f'https://api.github.com/repos/{full_repo}')
return data if ok and isinstance(data, dict) else {}
def fetch_all_repos_for_user(owner):
"""Fetch ALL public repos with pagination. Sorted by last push."""
all_repos = []
page = 1
while True:
ok, page_data = get_json_safe(
f'https://api.github.com/users/{owner}/repos',
params={'per_page': 100, 'page': page, 'sort': 'pushed'}
)
if not ok or not isinstance(page_data, list) or not page_data:
break
all_repos.extend(page_data)
if len(page_data) < 100:
break
page += 1
return all_repos
def fetch_all_events_for_user(owner):
"""Fetch up to 300 public events (GitHub max = 10 pages × 30)."""
all_events = []
for page in range(1, 11):
ok, page_data = get_json_safe(
f'https://api.github.com/users/{owner}/events/public',
params={'per_page': 30, 'page': page}
)
if not ok or not isinstance(page_data, list) or not page_data:
break
all_events.extend(page_data)
print(f"✓ Fetched {len(all_events)} events")
return all_events
# ─────────────────────────────────────────────
# QUALITY ANALYSIS
# ─────────────────────────────────────────────
def analyze_commit_quality(commits):
"""
Score commit messages 0.1–1.0.
Penalizes lazy keywords, very short messages, missing description on long ones.
IMPROVED: No bonus-as-penalty confusion here — this function only has real
penalties (score reductions). Nothing to split. Kept as-is.
"""
if not commits:
return {'quality_score': 1.0, 'penalties': [], 'bonuses': []}
penalties = []
bonuses = []
quality_score = 1.0
for commit in commits[:20]:
msg = commit.get('commit', {}).get('message', '').lower()
if any(w in msg for w in ['fix', 'todo', 'wip', 'typo', 'oops']):
quality_score -= 0.05
penalties.append('lazy_messages')
if len(msg) < 10:
quality_score -= 0.1
penalties.append('short_messages')
if '\n' not in msg and len(msg) > 50:
quality_score -= 0.05
penalties.append('no_description')
# IMPROVED: Bonus for clean commit history (no penalties at all)
if not penalties and len(commits) >= 5:
bonuses.append('clean_history')
# IMPROVED: Bonus for consistent conventional-commit style (feat/fix/chore/docs/refactor)
conventional_count = sum(
1 for c in commits[:20]
if any(c.get('commit', {}).get('message', '').lower().startswith(prefix)
for prefix in ('feat', 'fix', 'chore', 'docs', 'refactor', 'test', 'style', 'perf', 'ci'))
)
if conventional_count >= 3:
bonuses.append('conventional_commits')
return {
'quality_score': max(0.1, quality_score),
'penalties': list(set(penalties)),
'bonuses': list(set(bonuses)), # NEW field
}
def analyze_repo_quality(repo_data):
"""
Score a single repo 0.1–1.0.
Checks license, description, fork status, open issues.
NOTE: has_readme uses has_downloads as proxy — not ideal but avoids extra API call.
"""
score = 1.0
if not repo_data.get('license'):
score -= 0.3
if not repo_data.get('description'):
score -= 0.2
if repo_data.get('fork'):
score *= 0.1 # forks count very little
if repo_data.get('open_issues_count', 0) > 10:
score -= 0.2
return max(0.1, score)
# NEW: Issue quality analysis via keywords + open/close ratio
def analyze_issue_activity(events, owner):
"""
Extracts IssuesEvent data from the already-fetched events list.
Scores based on:
- closing issues (responsibility)
- keyword patterns in issue titles (bug/feature/enhancement = good, spam = bad)
- open/close ratio penalty if too many open and nothing resolved
Returns dict with score (0.1–1.5) and metadata.
"""
opened = 0
closed = 0
keywords_good = ['bug', 'fix', 'enhancement', 'feature', 'improvement', 'refactor', 'docs', 'test']
keywords_bad = ['test123', 'asdf', 'please help', 'urgent', 'idk']
quality_hits = 0
spam_hits = 0
for event in events:
if event.get('type') != 'IssuesEvent':
continue
action = event.get('payload', {}).get('action', '')
title = event.get('payload', {}).get('issue', {}).get('title', '').lower()
if action == 'opened':
opened += 1
if any(k in title for k in keywords_good):
quality_hits += 1
if any(k in title for k in keywords_bad):
spam_hits += 1
elif action == 'closed':
closed += 1
total = opened + closed
if total == 0:
return {'score': 1.0, 'opened': 0, 'closed': 0, 'note': 'no_issue_activity'}
# Reward closing issues
close_ratio = closed / max(opened, 1)
score = 1.0 + (close_ratio * 0.3) # up to +0.3 bonus for responsible closer
# Keyword quality bonus
if quality_hits > 0:
score += min(0.2, quality_hits * 0.05)
# Spam penalty
if spam_hits > 0:
score -= min(0.4, spam_hits * 0.1)
# Heavy open-without-closing penalty
if opened > 5 and close_ratio < 0.2:
score -= 0.3
return {
'score': max(0.1, min(1.5, score)),
'opened': opened,
'closed': closed,
'close_ratio': close_ratio,
'quality_hits': quality_hits,
'spam_hits': spam_hits
}
# ─────────────────────────────────────────────
# SOCIAL ENGINEERING DETECTION
# ─────────────────────────────────────────────
def calculate_social_engineering_score(user_data, all_repos):
"""
Detects gaming patterns:
- follow/follower ratio spam
- fork leeching
- repo spamming without stars
Returns score multiplier (0.1–1.5+), penalty labels, and bonus labels.
BUG (FIXED): Positive traits like 'quality_curator' were stored in penalties[].
Now penalties[] = only negative traits, bonuses[] = only positive traits.
Themes should render penalties RED and bonuses GREEN.
"""
followers = user_data.get('followers', 0)
following = user_data.get('following', 0)
ffr = following / max(followers, 1)
own_repos = [r for r in all_repos if not r.get('fork')]
forked_repos = [r for r in all_repos if r.get('fork')]
fork_ratio = len(forked_repos) / max(len(own_repos), 1)
total_stars = sum(r.get('stargazers_count', 0) for r in own_repos)
star_per_repo = total_stars / max(len(own_repos), 1)
score = 1.0
penalties = [] # negative traits only — render RED in themes
bonuses = [] # positive traits only — render GREEN in themes
# Follow/Follower ratio
if ffr > 5.0:
score *= 0.25
penalties.append('spam_follower')
elif ffr > 2.0:
score *= 0.75
penalties.append('desperate_networker')
elif ffr < 0.5:
# BUG (FIXED): was penalties.append('quality_curator') — this is a BONUS
score *= 1.25
bonuses.append('quality_curator')
# Fork ratio
if fork_ratio > 2.0:
score *= 0.5
penalties.append('fork_leech')
# Stars per repo
if star_per_repo < 1.0 and len(own_repos) > 5:
score *= 0.7
penalties.append('code_spammer')
# Additional bonuses
if star_per_repo >= 10.0:
bonuses.append('star_magnet')
if len(own_repos) >= 10 and fork_ratio < 0.5:
bonuses.append('original_builder')
return {
'score': max(0.1, score),
'ffr': ffr,
'fork_ratio': fork_ratio,
'star_per_repo': star_per_repo,
'penalties': penalties,
'bonuses': bonuses, # NEW: separate list for positive traits
}
# ─────────────────────────────────────────────
# TIER SYSTEM
# ─────────────────────────────────────────────
def get_github_age_years(created_at_str):
try:
created = datetime.fromisoformat(created_at_str.replace('Z', '+00:00'))
return (datetime.now(timezone.utc) - created).days / 365.25
except Exception:
return 1
def determine_tier(github_years):
"""Tier based purely on account age — experience is time."""
if github_years < 2: return 'noob'
elif github_years < 5: return 'developer'
elif github_years < 8: return 'veteran'
else: return 'elder'
def calculate_tier_multipliers(tier, social_score):
"""
Higher tier = higher requirements, lower XP gain.
You've been around long enough, one commit shouldn't level you up.
"""
base_multipliers = {
'noob': {'xp': 1.0, 'decay': 0.95, 'requirements': 1.0},
'developer': {'xp': 0.67, 'decay': 0.90, 'requirements': 1.5},
'veteran': {'xp': 0.40, 'decay': 0.85, 'requirements': 2.5},
'elder': {'xp': 0.20, 'decay': 0.80, 'requirements': 4.0},
}
m = base_multipliers.get(tier, base_multipliers['noob']).copy()
m['xp'] *= social_score # social score directly scales XP gain
return m
# ─────────────────────────────────────────────
# SKILL DECAY
# ─────────────────────────────────────────────
def calculate_skill_decay(last_update_str, current_stats):
"""
Applies exponential decay to health/happiness/energy for inactive periods.
Streak is intentionally NOT touched here — handled once in update_brutal_stats.
BUG (FIXED): Original also decremented streak here, causing double-penalty
when combined with the streak logic in update_brutal_stats.
"""
if not last_update_str:
return current_stats
try:
last_update = datetime.fromisoformat(last_update_str.replace('Z', '+00:00'))
days_inactive = (datetime.now(timezone.utc) - last_update).days
if days_inactive <= 1:
return current_stats
decay_factor = 0.95 ** days_inactive
decayed = current_stats.copy()
decayed['health'] *= decay_factor
decayed['happiness'] *= decay_factor
decayed['energy'] *= max(0.3, decay_factor)
# BUG REMOVED: streak was decremented here too — now only in update_brutal_stats
return decayed
except Exception:
return current_stats
# ─────────────────────────────────────────────
# MAIN DATA COLLECTOR
# ─────────────────────────────────────────────
def get_all_data_for_user(owner):
"""
Collects all relevant data for the owner:
- Events (commits, PRs, issues) from last 24h
- Repo list with quality scores
- Language breakdown (first 5 own repos only, saves API calls)
- Commit quality from message analysis
- NEW: Issue quality from IssuesEvent analysis
BUG (FIXED): self_starred was stored as set() → not JSON-serializable.
Now stored as int (self_starred_count) in all_time_data.
The set is only used locally inside this function for star deduction.
"""
all_events = fetch_all_events_for_user(owner)
repos_list = fetch_all_repos_for_user(owner)
own_repos = [r for r in repos_list if not r.get('fork')]
self_starred_set = fetch_real_stars(owner) # set — local only
self_starred_count = len(self_starred_set) # int — safe for JSON
total_stars = sum(
r.get('stargazers_count', 0) - (1 if r.get('name') in self_starred_set else 0)
for r in own_repos
)
print(f"⭐ Real stars: {total_stars} (self-starred repos: {self_starred_count})")
total_forks = sum(r.get('forks_count', 0) for r in own_repos)
repo_qualities = [analyze_repo_quality(r) for r in own_repos]
avg_repo_quality = sum(repo_qualities) / max(len(repo_qualities), 1)
# Language analysis — only first 5 own repos to save rate limit
languages_bytes = Counter()
for repo in own_repos[:5]:
ok, lang_data = get_json_safe(f'https://api.github.com/repos/{repo["full_name"]}/languages')
if ok and isinstance(lang_data, dict):
languages_bytes.update(lang_data)
dominant_language = languages_bytes.most_common(1)
dominant_language = dominant_language[0][0] if dominant_language else 'unknown'
language_count = len(languages_bytes)
if language_count > 10:
language_diversity_penalty = 0.8 # jack of all trades, master of none
elif language_count == 1:
language_diversity_penalty = 0.9 # very narrow stack
else:
language_diversity_penalty = 1.0
# Process events for daily activity (last 24h)
now = datetime.now(timezone.utc)
one_day_ago = now - timedelta(days=1)
daily_commits = 0
daily_prs = 0
all_commits = []
for event in all_events:
ts = event.get('created_at')
if not ts:
continue
event_time = datetime.fromisoformat(ts.replace('Z', '+00:00'))
if event_time <= one_day_ago:
continue
if event.get('type') == 'PushEvent':
commits = event.get('payload', {}).get('commits', [])
daily_commits += len(commits)
all_commits.extend(commits)
elif event.get('type') == 'PullRequestEvent':
payload = event.get('payload', {})
if (payload.get('action') == 'closed' and
payload.get('pull_request', {}).get('merged')):
daily_prs += 1
# FALLBACK: Events API returned 0 commits (private repo, org, or rate limit)
# → directly query /commits for each own repo as fallback
# FALLBACK: opt-in via CODEY_FALLBACK=true (kostet extra API-Calls!)
# FALLBACK: opt-in via CODEY_FALLBACK=true (kostet extra API-Calls!)
#env: set: CODEY_FALLBACK: 'true' # nur wenn du's brauchst
if daily_commits == 0 and own_repos:
if not ENABLE_FALLBACK:
print("⏭️ Events API returned 0 commits — fallback disabled (set CODEY_FALLBACK=true to enable)")
else:
print("⚠️ Events API returned 0 commits — trying direct /commits fallback...")
since_iso = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
for repo in own_repos[:10]:
ok, commits_data = get_json_safe(
f'https://api.github.com/repos/{repo["full_name"]}/commits',
params={'author': owner, 'since': since_iso, 'per_page': 100}
)
if ok and isinstance(commits_data, list) and commits_data:
daily_commits += len(commits_data)
all_commits.extend(commits_data)
print(f" ✓ {repo['full_name']}: {len(commits_data)} commits")
print(f" Fallback total: {daily_commits} commits")
commit_quality_data = analyze_commit_quality(all_commits) if all_commits else {
'quality_score': 1.0, 'penalties': [], 'bonuses': []
}
# NEW: Issue activity from full event history (not just 24h, shows pattern)
issue_data = analyze_issue_activity(all_events, owner)
return {
'daily_commits': daily_commits,
'daily_prs': daily_prs,
'total_stars': total_stars,
'self_starred_count': self_starred_count, # BUG FIXED: int, not set
'total_forks': total_forks,
'total_own_repos': len(own_repos),
'dominant_language': dominant_language,
'language_diversity_penalty': language_diversity_penalty,
'avg_repo_quality': avg_repo_quality,
'commit_quality': commit_quality_data,
'issue_data': issue_data,
'all_repos': repos_list,
}
# ─────────────────────────────────────────────
# CODEY STATE
# ─────────────────────────────────────────────
def load_codey():
"""Load state from codey.json, migrate missing fields gracefully."""
defaults = {
'health': 50, 'hunger': 50, 'happiness': 50, 'energy': 50,
'level': 1, 'streak': 0, 'total_commits': 0, 'mood': 'neutral',
'rpg_stats': {}, 'achievements': [], 'history': [],
'brutal_stats': {}, 'last_update': None
}
try:
with open('codey.json', 'r') as f:
data = json.load(f)
# Migrate: add missing keys without losing existing data
for k, v in defaults.items():
if k not in data:
data[k] = v
print("codey.json loaded.")
return data
except (FileNotFoundError, json.JSONDecodeError):
print("codey.json not found or invalid — creating defaults.")
return defaults
def check_brutal_achievements(codey, tier, github_years):
"""Award achievements. Each awarded only once."""
achievements = codey.get('achievements', [])
brutal_stats = codey.get('brutal_stats', {})
candidates = [
(tier == 'elder', '🧙♂️ Elder Council'),
(github_years >= 10, '💀 Decade Survivor'),
(brutal_stats.get('social_score', 0) > 1.2, '👑 Social Elite'),
(brutal_stats.get('avg_repo_quality', 0) > 0.8, '💎 Quality Craftsman'),
(codey['streak'] >= 100, '🔥 Century Streak'),
(codey.get('prestige_level', 0) > 0, '⭐ Prestige Master'),
# NEW: issue achievement
(brutal_stats.get('issue_close_ratio', 0) > 0.8
and brutal_stats.get('issues_closed', 0) >= 5, '🐛 Bug Slayer'),
# NEW: quality curator achievement (was wrongly a penalty before)
('quality_curator' in brutal_stats.get('social_bonuses', []), '🎯 Quality Curator'),
]
for condition, badge in candidates:
if condition and badge not in achievements:
achievements.append(badge)
return achievements
def calculate_prestige_requirements(codey, github_years):
"""Check if prestige is possible and what's missing."""
if codey['level'] < 10:
return False, ['Need Level 10']
brutal_stats = codey.get('brutal_stats', {})
requirements = {
'min_years': 5,
'min_social_score': 1.0,
'min_repo_quality': 0.6,
'min_total_stars': 100,
}
current = {
'min_years': github_years,
'min_social_score': brutal_stats.get('social_score', 0),
'min_repo_quality': brutal_stats.get('avg_repo_quality', 0),
'min_total_stars': brutal_stats.get('total_stars', 0),
}
missing = [k for k in requirements if current[k] < requirements[k]]
return len(missing) == 0, missing
# ─────────────────────────────────────────────
# CORE UPDATE
# ─────────────────────────────────────────────
def update_brutal_stats(codey, daily_activity, all_time_data, user_data):
"""
Main stat update. Call order matters:
1. Decay inactive stats
2. Compute XP from raw (pre-bonus) commits
3. Apply daily decay
4. Apply rewards
5. Update streak (single place — no double penalty)
6. Level up
7. Mood + achievements
BUG (FIXED): Weekend bonus was applied to daily_activity BEFORE this function,
which inflated total_commits permanently. Now total_commits uses raw_commits.
"""
now = datetime.now(timezone.utc).isoformat()
github_years = get_github_age_years(user_data.get('created_at', ''))
tier = determine_tier(github_years)
social_analysis = calculate_social_engineering_score(user_data, all_time_data.get('all_repos', []))
multipliers = calculate_tier_multipliers(tier, social_analysis['score'])
issue_data = all_time_data.get('issue_data', {'score': 1.0, 'closed': 0}) # NEW
# Step 1: Decay
if codey.get('last_update'):
codey = calculate_skill_decay(codey['last_update'], codey)
# History (keep last 30 days)
codey['history'] = codey.get('history', [])[-29:] + [{
'timestamp': now,
'daily_commits': daily_activity['commits'],
'daily_prs': daily_activity['prs'],
'health': codey['health'],
'mood': codey['mood'],
'streak': codey['streak'],
'tier': tier,
}]
# Step 2: XP calculation
commit_quality = all_time_data.get('commit_quality', {})
lang_penalty = all_time_data.get('language_diversity_penalty', 1.0)
commit_xp = (daily_activity['commits'] * GAME_BALANCE['XP_PER_COMMIT']
* multipliers['xp'] * commit_quality.get('quality_score', 1.0))
pr_xp = daily_activity['prs'] * GAME_BALANCE['XP_PER_PR'] * multipliers['xp']
# NEW: Issue XP — reward for closed issues found in event history
issue_xp = issue_data.get('closed', 0) * GAME_BALANCE['XP_PER_ISSUE_CLOSED'] * multipliers['xp']
total_xp = (commit_xp + pr_xp + issue_xp) * lang_penalty * issue_data.get('score', 1.0)
# Step 3: Daily decay
codey['hunger'] = max(0, codey['hunger'] - GAME_BALANCE['DAILY_HUNGER_DECAY'])
codey['happiness'] = max(0, codey['happiness'] - GAME_BALANCE['DAILY_HAPPINESS_DECAY'])
# Step 4: Energy
energy_cost = (daily_activity['commits'] * GAME_BALANCE['ENERGY_COST_COMMIT'] +
daily_activity['prs'] * GAME_BALANCE['ENERGY_COST_PR'])
regen = GAME_BALANCE['ENERGY_REGEN_REST'] if energy_cost == 0 else GAME_BALANCE['ENERGY_REGEN_ACTIVE']
codey['energy'] = max(0, min(100, codey['energy'] - energy_cost + regen))
# Rewards from activity
codey['hunger'] = min(100, codey['hunger'] + total_xp * GAME_BALANCE['HUNGER_GAIN_MODIFIER'])
codey['happiness'] = min(100, codey['happiness'] + pr_xp * GAME_BALANCE['HAPPINESS_GAIN_MODIFIER'])
# Health = average of the three core stats
codey['health'] = (codey['hunger'] + codey['happiness'] + codey['energy']) / 3
# Step 5: Streak — single place, no double penalty
# BUG (FIXED): was also decremented in calculate_skill_decay
active = daily_activity['commits'] > 0 or daily_activity['prs'] > 0
if active:
codey['streak'] += 1
else:
streak_loss = max(1, codey['streak'] // GAME_BALANCE['STREAK_LOSS_DIVISOR'])
codey['streak'] = max(0, codey['streak'] - streak_loss)
# Step 6: Level
# BUG (FIXED): used daily_activity['commits'] which included weekend bonus multiplier.
# Now we use the raw_commits passed in so total_commits stays accurate.
codey['total_commits'] += daily_activity.get('raw_commits', daily_activity['commits'])
tier_req = GAME_BALANCE['BASE_LEVEL_REQUIREMENT'] * multipliers['requirements']
codey['level'] = min(10, 1 + int(codey['total_commits'] / tier_req))
# Brutal stats snapshot — all values must be JSON-serializable (no sets!)
codey['brutal_stats'] = {
'tier': tier,
'github_years': github_years,
'social_score': social_analysis['score'],
'social_penalties': social_analysis['penalties'],
'social_bonuses': social_analysis['bonuses'],
'avg_repo_quality': all_time_data.get('avg_repo_quality', 0),
'commit_quality_score': commit_quality.get('quality_score', 1.0),
'commit_quality_penalties': commit_quality.get('penalties', []),
'commit_quality_bonuses': commit_quality.get('bonuses', []),
'multipliers': multipliers,
'total_stars': all_time_data.get('total_stars', 0),
'self_starred_count': all_time_data.get('self_starred_count', 0), # BUG FIXED: int
'language_diversity_penalty': lang_penalty,
'xp_earned': total_xp,
'dominant_language': all_time_data.get('dominant_language', 'unknown'),
# issue stats
'issues_closed': issue_data.get('closed', 0),
'issue_close_ratio': issue_data.get('close_ratio', 0),
'issue_score': issue_data.get('score', 1.0),
}
# Step 7: Mood
penalties_count = (len(social_analysis['penalties']) +
len(commit_quality.get('penalties', [])))
bonuses_count = (len(social_analysis['bonuses']) +
len(commit_quality.get('bonuses', [])))
if codey['health'] < 25: codey['mood'] = 'struggling'
elif codey['energy'] < 20: codey['mood'] = 'exhausted'
elif penalties_count > 2: codey['mood'] = 'overwhelmed'
elif social_analysis['score'] > 1.2: codey['mood'] = 'elite'
elif tier == 'elder' and codey['health'] > 70: codey['mood'] = 'wise'
elif bonuses_count >= 2: codey['mood'] = 'inspired'
elif codey['health'] > 80: codey['mood'] = 'happy'
else: codey['mood'] = 'grinding'
codey['achievements'] = check_brutal_achievements(codey, tier, github_years)
can_prestige, missing = calculate_prestige_requirements(codey, github_years)
codey['brutal_stats']['can_prestige'] = can_prestige
codey['brutal_stats']['prestige_missing'] = missing
codey['last_update'] = now
return codey
# ─────────────────────────────────────────────
# SEASONAL / WEEKEND
# ─────────────────────────────────────────────
def get_seasonal_bonus():
bonuses = {
10: {'emoji': '🎃', 'name': 'Hacktoberfest', 'multiplier': 1.5},
11: {'emoji': '🍁', 'name': 'Year Push', 'multiplier': 1.25},
12: {'emoji': '🎄', 'name': 'Advent', 'multiplier': 1.3},
1: {'emoji': '🎯', 'name': 'New Year', 'multiplier': 1.2},
2: {'emoji': '💖', 'name': 'OS Love', 'multiplier': 1.1},
3: {'emoji': '🧹', 'name': 'Refactor', 'multiplier': 1.2},
4: {'emoji': '🐞', 'name': 'Bug Hunt', 'multiplier': 1.1},
5: {'emoji': '🚀', 'name': 'Deploy', 'multiplier': 1.3},
6: {'emoji': '📚', 'name': 'Docs', 'multiplier': 1.1},
7: {'emoji': '🔥', 'name': 'Grind', 'multiplier': 1.4},
8: {'emoji': '🧊', 'name': 'Freeze', 'multiplier': 1.05},
9: {'emoji': '🎓', 'name': 'School', 'multiplier': 1.2},
}
return bonuses.get(datetime.now().month)
def is_weekend_warrior():
return datetime.now().weekday() >= 5
# ─────────────────────────────────────────────
# THEME LOADER
# ─────────────────────────────────────────────
import importlib.util
from pathlib import Path
def load_theme_config(config_path: str = "codey.config") -> tuple:
"""Reads THEME= and ANIMATION_POWER= from codey.config.
Env var ANIMATION_POWER always wins over config (GitHub Actions).
Returns (theme: str, cycles: int)
"""
theme = "default"
power = None
try:
for line in Path(config_path).read_text().splitlines():
line = line.strip()
if line.startswith("#"):
continue
if line.startswith("THEME"):
theme = line.split("=")[1].strip().strip('"').strip("'")
if line.startswith("ANIMATION_POWER"):
power = line.split("=")[1].strip().strip('"').strip("'")
except FileNotFoundError:
pass
# GitHub Actions env wins over codey.config
power = os.environ.get('ANIMATION_POWER', power or 'normal')
cycles = {'light': 2, 'normal': 4, 'full': 8}.get(power, 4)
print(f"⚙️ Animation power: {power} ({cycles} cycles)")
return theme, cycles
def load_generate_fn(theme: str):
"""Loads generate_brutal_svg from theme folder. Fallback to default."""
candidates = [
Path(f".codey_themes/_default_{theme}/_cl_lab_{theme}.py"),
Path(f".codey_themes/{theme}/_cl_lab_{theme}.py"), # community themes
Path(".codey_themes/_default/_cl_lab_default.py"), # hard fallback
]
for path in candidates:
if path.exists():
spec = importlib.util.spec_from_file_location("theme", path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
if hasattr(mod, 'generate_brutal_svg'):
print(f"🎨 Theme loaded: {path}")
return mod.generate_brutal_svg
raise FileNotFoundError(f"No valid theme found for '{theme}' — check .codey_themes/")
# ─────────────────────────────────────────────
# MAIN RUN
# ─────────────────────────────────────────────
if __name__ == "__main__":
print("🔥 Updating BRUTAL Codey...")
# ── GUARD FIRST — skip all API calls if not due ──
codey = load_codey()
should_update, hours_since = should_run_full_update(codey)
if not should_update:
print(f"⏭️ Last update was {hours_since:.1f}h ago — skipping all API calls.")
else:
# ── API calls only when needed ────────────────
user_data = get_user_data(OWNER)
all_time_data = get_all_data_for_user(OWNER)
raw_commits = all_time_data.get('daily_commits', 0)
raw_prs = all_time_data.get('daily_prs', 0)
if is_weekend_warrior():
print("🎯 Weekend Warrior bonus activated!")
display_commits = int(raw_commits * GAME_BALANCE['WEEKEND_BONUS'])
display_prs = int(raw_prs * GAME_BALANCE['WEEKEND_BONUS'])
else:
display_commits = raw_commits
display_prs = raw_prs
daily_activity = {
'commits': display_commits,
'prs': display_prs,
'raw_commits': raw_commits,
}
print(f"Daily activity: {raw_commits} commits, {raw_prs} PRs (raw)")
print(f" After bonus: {display_commits} commits, {display_prs} PRs")
print(f"Repo Quality: {all_time_data.get('avg_repo_quality', 0):.2f}")
print(f"Commit Quality: {all_time_data.get('commit_quality', {}).get('quality_score', 1.0):.2f}")
issue_data = all_time_data.get('issue_data', {})
print(f"Issue Score: {issue_data.get('score', 1.0):.2f} "
f"(closed: {issue_data.get('closed', 0)}, ratio: {issue_data.get('close_ratio', 0):.2f})")
codey = update_brutal_stats(codey, daily_activity, all_time_data, user_data)
with open('codey.json', 'w') as f:
json.dump(codey, f, indent=2)
print("\n💾 codey.json written.")
brutal = codey.get('brutal_stats', {})
print(f"\n🔥 BRUTAL UPDATE COMPLETE:")
print(f" Tier: {brutal.get('tier', '?').upper()} ({brutal.get('github_years', 0):.1f} years)")
print(f" Health: {codey['health']:.0f}% | Energy: {codey['energy']:.0f}% | Mood: {codey['mood']}")
print(f" Social Score: {brutal.get('social_score', 1.0):.2f}x | XP Today: {brutal.get('xp_earned', 0):.0f}")
print(f" Social+: {brutal.get('social_bonuses', [])} | Social-: {brutal.get('social_penalties', [])}")
print(f" Self-starred: {brutal.get('self_starred_count', 0)} repos")
print(f" Issues: closed={brutal.get('issues_closed', 0)}, score={brutal.get('issue_score', 1.0):.2f}")
if brutal.get('can_prestige'):
print(" 🌟 PRESTIGE READY! 🌟")
else:
print(f" Prestige missing: {', '.join(brutal.get('prestige_missing', []))}")
# ── ALWAYS: render SVG with current or cached data ──
seasonal_bonus = get_seasonal_bonus()
if seasonal_bonus:
print(f" Seasonal: {seasonal_bonus['name']} {seasonal_bonus['emoji']} ({seasonal_bonus['multiplier']}x)")
theme, cycles = load_theme_config()
generate_fn = load_generate_fn(theme)
svg = generate_fn(codey, seasonal_bonus, cycles)
with open('codey.svg', 'w', encoding='utf-8') as f:
f.write(svg)
print("🎨 codey.svg written.")
print("\n💀 BRUTAL Codey update finished. Only the strong survive! 💀")