-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreport.py
More file actions
2068 lines (1861 loc) · 96.2 KB
/
report.py
File metadata and controls
2068 lines (1861 loc) · 96.2 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
"""
report.py — Daily digest HTML for GitHub Copilot sessions.
Layout: Act 1 (Story) → Act 2 (Journey) → Act 3 (Evidence)
Act 1: Header → Narrative → KPIs → ROI
Act 2: How I Collaborated → What Got Built → Skills Augmented → When I Worked
Act 3: What Got Accomplished → Pricing → Estimation Evidence
"""
from datetime import datetime, timezone
from harvest import compute_elapsed_minutes
def _utc_to_local(ts: str) -> datetime:
"""Parse an ISO-8601 UTC timestamp and convert to the system's local timezone."""
dt = datetime.strptime(ts[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc)
return dt.astimezone()
C = {
"bg": "#f0f2f5",
"card": "#ffffff",
"border": "#dde1e7",
"accent": "#0078d4",
"accent_dk": "#005a9e",
"accent_lt": "#e8f2fb",
"text": "#1b1f23",
"muted": "#6a737d",
"subtle": "#f7f9fc",
"green": "#1a7f37",
"green_lt": "#dff6dd",
"orange": "#e65100",
"orange_lt": "#fff3e0",
}
DOMAIN_PILL = ("background:#fff3e0;color:#e65100;padding:2px 8px;border-radius:9px;"
"font-size:11px;font-weight:600;display:inline-block;margin:2px 3px 2px 0;"
"white-space:nowrap")
TECH_PILL = ("background:#e3f2fd;color:#1565c0;padding:2px 8px;border-radius:9px;"
"font-size:11px;font-weight:600;display:inline-block;margin:2px 3px 2px 0;"
"white-space:nowrap")
def _pills(domain: list, tech: list) -> str:
out = [f'<span style="{DOMAIN_PILL}">{s}</span>' for s in domain]
out += [f'<span style="{TECH_PILL}">{s}</span>' for s in tech]
return "".join(out)
def _fmt_h(h: float) -> str:
if h <= 0: return "—"
if h < 1: return f"{int(round(h * 60))}m"
if h == int(h): return f"{int(h)}h"
return f"{h:.1f}h"
def _fmt_ms(ms: int) -> str:
"""Format milliseconds as Xm Ys."""
if not ms:
return "—"
s = ms // 1000
if s < 60:
return f"{s}s"
return f"{s // 60}m {s % 60}s"
def _cost(tokens: dict) -> str:
"""Calculate API cost using Anthropic token pricing (Copilot sessions use Claude models)."""
c = (tokens.get("input", 0) * 3.00
+ tokens.get("output", 0) * 15.00
+ tokens.get("cache_read", 0) * 0.30
+ tokens.get("cache_creation", 0) * 3.75) / 1_000_000
return f"~${c:.2f}"
HOURLY_RATE = 72 # $/hr — blended professional services rate (conservative)
SEAT_COST_PER_MONTH = 39 # Enterprise Copilot seat $/month
def _prorated_seat_cost(analysis: dict) -> "tuple[int, int]":
"""Return (seat_cost, n_months) prorated over the report's time span.
For short reports (≤31 days), always use 1 month regardless of calendar
month boundaries — a 7-day export shouldn't show 2 months of seat cost
just because it crosses a month boundary.
"""
dates = analysis.get("active_dates", [])
if not dates:
return SEAT_COST_PER_MONTH, 1
# Parse dates and determine the span
parsed = []
for d in dates:
try:
parsed.append(datetime.strptime(str(d)[:10], "%Y-%m-%d"))
except ValueError:
pass
if not parsed:
return SEAT_COST_PER_MONTH, 1
span_days = (max(parsed) - min(parsed)).days + 1
if span_days <= 31:
return SEAT_COST_PER_MONTH, 1
# For longer reports, prorate by distinct calendar months
months = {(dt.year, dt.month) for dt in parsed}
n_months = max(1, len(months))
return SEAT_COST_PER_MONTH * n_months, n_months
def _kpi_card(value: str, label: str, sub: str = "") -> str:
return f"""
<td style="padding:6px;width:20%;vertical-align:top">
<div style="background:{C['card']};border:1px solid {C['border']};border-radius:10px;
padding:16px 10px;text-align:center;height:80px;
box-shadow:0 1px 4px rgba(0,0,0,0.06)">
<div style="font-size:26px;font-weight:700;color:{C['accent']};line-height:1;
letter-spacing:-0.5px">{value}</div>
<div style="font-size:9px;font-weight:700;color:{C['muted']};text-transform:uppercase;
letter-spacing:0.8px;margin-top:6px;line-height:1.3">{label}</div>
{f'<div style="font-size:10px;color:{C["muted"]};margin-top:3px;line-height:1.3">{sub}</div>' if sub else ""}
</div>
</td>"""
def _kpi_section(goals: list, analysis: dict, n_sessions: int, total_prs: int = 0, total_commits: int = 0) -> str:
total_human_h = sum(g.get("human_hours", 0) for g in goals)
n_goals = len(goals)
lines_added = analysis.get("lines_added", 0)
lines_removed = analysis.get("lines_removed", 0)
active_days = max(1, len(analysis.get("active_dates", ["x"])))
h_str = _fmt_h(total_human_h)
days_label = f"{active_days}"
# Code impact
if lines_added or lines_removed:
code_val = f"+{lines_added:,}"
code_sub = f"{lines_removed:,} removed"
else:
code_val = "—"
code_sub = ""
# PRs & Commits
pr_commit_val = f"{total_prs}"
pr_commit_sub = f"{total_commits} commit{'s' if total_commits != 1 else ''}"
return f"""
<tr>
<td style="background:{C['bg']};padding:12px 24px;
border-left:1px solid {C['border']};border-right:1px solid {C['border']}">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
{_kpi_card(str(n_goals), "Projects<br>Assisted", f"{n_sessions} sessions")}
{_kpi_card(h_str, "Human Effort<br>Equivalent", f"@ ${HOURLY_RATE}/hr")}
{_kpi_card(code_val, "Lines of Code<br>Added", code_sub)}
{_kpi_card(pr_commit_val, "PRs<br>Merged", pr_commit_sub)}
{_kpi_card(days_label, "Active Days", "")}
</tr>
</table>
</td>
</tr>"""
def _leverage_banner(goals: list, analysis: dict) -> str:
"""Hero-style ROI banner: services equivalent, seat cost, API savings."""
total_human_h = sum(g.get("human_hours", 0) for g in goals)
human_value = total_human_h * HOURLY_RATE
seat_cost, n_months = _prorated_seat_cost(analysis)
leverage = round(human_value / seat_cost) if seat_cost > 0 else 0
# Market API cost
tokens = analysis.get("tokens", {})
market_cost = (tokens.get("input", 0) * 3.00
+ tokens.get("output", 0) * 15.00
+ tokens.get("cache_read", 0) * 0.30
+ tokens.get("cache_creation", 0) * 3.75) / 1_000_000
api_savings = max(0, market_cost - seat_cost)
if leverage <= 0:
return ""
seat_label = (f"${seat_cost}/mo" if n_months == 1
else f"${seat_cost} ({n_months}mo)")
return f"""
<tr>
<td style="padding:0;border-left:1px solid {C['border']};border-right:1px solid {C['border']}">
<table width="100%" cellpadding="0" cellspacing="0" bgcolor="{C['green']}"
style="background:linear-gradient(135deg,{C['green']},#15803d);border-collapse:collapse">
<tr>
<td bgcolor="{C['green']}" style="padding:18px 24px 6px;text-align:center">
<div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1.5px;
color:rgba(255,255,255,0.65);margin-bottom:6px">Return on Copilot Investment</div>
<div style="font-size:44px;font-weight:800;color:#ffffff;line-height:1;
letter-spacing:-2px">{leverage:,}×</div>
</td>
</tr>
<tr>
<td bgcolor="#1a7f37" style="padding:4px 24px 14px">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td style="width:33%;text-align:center;padding:8px 8px;
border-right:1px solid rgba(255,255,255,0.2)">
<div style="font-size:10px;font-weight:700;text-transform:uppercase;
letter-spacing:0.8px;color:rgba(255,255,255,0.55)">Professional Services<br>Equivalent</div>
<div style="font-size:18px;font-weight:700;color:#fff;margin-top:4px">
${human_value:,.0f}</div>
<div style="font-size:11px;color:rgba(255,255,255,0.7);margin-top:2px">
{total_human_h:.0f}h @ ${HOURLY_RATE}/hr</div>
</td>
<td style="width:33%;text-align:center;padding:8px 8px;
border-right:1px solid rgba(255,255,255,0.2)">
<div style="font-size:10px;font-weight:700;text-transform:uppercase;
letter-spacing:0.8px;color:rgba(255,255,255,0.55)">Copilot Seat<br>Cost</div>
<div style="font-size:18px;font-weight:700;color:#fff;margin-top:4px">
{seat_label}</div>
<div style="font-size:11px;color:rgba(255,255,255,0.7);margin-top:2px">
Enterprise plan</div>
</td>
<td style="width:33%;text-align:center;padding:8px 8px">
<div style="font-size:10px;font-weight:700;text-transform:uppercase;
letter-spacing:0.8px;color:rgba(255,255,255,0.55)">API Token<br>Savings</div>
<div style="font-size:18px;font-weight:700;color:#fff;margin-top:4px">
${api_savings:,.0f}</div>
<div style="font-size:11px;color:rgba(255,255,255,0.7);margin-top:2px">
vs. ${market_cost:,.0f} at market rate</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>"""
def _what_i_work_on(goals: list, sessions: list, project_label_map: dict = None) -> str:
"""Section: 'What Got Produced' — deliverables files categorized."""
import re
if project_label_map is None:
project_label_map = {}
file_categories = {
"Scripts": {"icon": "💻", "extensions": {".py", ".js", ".ts", ".sh", ".ps1"}},
"Reports": {"icon": "📊", "extensions": {".html"}},
"Documents": {"icon": "📄", "extensions": {".md", ".txt", ".docx", ".pdf"}},
"Data & Config": {"icon": "⚙", "extensions": {".json", ".yaml", ".yml", ".toml", ".env", ".gitignore", ".cfg"}},
"Presentations": {"icon": "📑", "extensions": {".pptx", ".ppt"}},
}
all_files: dict = {}
for s in sessions:
raw_proj = s.get("project", "")
proj = project_label_map.get(raw_proj, raw_proj)
for f in s.get("code_changes", {}).get("filesModified", []):
fname = f.replace("\\", "/").split("/")[-1]
all_files.setdefault(fname, proj)
for f in s.get("files_touched", []):
fname = f.replace("\\", "/").split("/")[-1]
all_files.setdefault(fname, proj)
for msg in s.get("messages", []):
for tool in msg.get("tools_after", []):
m = re.search(r'(?:create|edit).+[\\/]([^\\/]+\.\w{1,8})', tool, re.I)
if m:
all_files.setdefault(m.group(1).rstrip('.'), proj)
if not all_files:
return ""
counts: dict = {k: [] for k in file_categories}
for fname in sorted(all_files.keys()):
ext = "." + fname.rsplit(".", 1)[-1].lower() if "." in fname else ""
if fname.lower() == ".gitignore":
ext = ".gitignore"
for cat, info in file_categories.items():
if ext in info["extensions"]:
counts[cat].append((fname, all_files[fname]))
break
total_files = len(all_files)
cells = ""
for cat, info in file_categories.items():
c = len(counts[cat])
if c <= 0:
continue
cells += (
f'<td style="padding:8px 12px;text-align:center;vertical-align:top">'
f'<div style="font-size:24px;font-weight:700;color:{C["accent"]};line-height:1">{c}</div>'
f'<div style="font-size:10px;font-weight:600;color:{C["muted"]};margin-top:4px;'
f'text-transform:uppercase;letter-spacing:0.5px">{info["icon"]} {cat}</div>'
f'</td>'
)
file_list_rows = ""
for cat, info in file_categories.items():
if not counts[cat]:
continue
fnames = ", ".join(
f'<span style="font-size:10px;color:{C["accent"]};font-weight:500">{proj}</span>'
f'<span style="font-size:10px;color:{C["muted"]}">/{fn}</span>'
for fn, proj in counts[cat]
)
file_list_rows += (
f'<tr><td style="padding:4px 0;font-size:10px;font-weight:600;'
f'color:{C["muted"]};white-space:nowrap;vertical-align:top;width:100px">'
f'{info["icon"]} {cat}</td>'
f'<td style="padding:4px 8px;font-size:10px;color:{C["text"]}">{fnames}</td></tr>'
)
return f"""
<tr>
<td style="background:{C['card']};padding:0;
border-left:1px solid {C['border']};border-right:1px solid {C['border']}">
<table width="100%" cellpadding="0" cellspacing="0"><tr><td bgcolor="#24292f" style="background:linear-gradient(135deg,#24292f,#1b1f23);padding:10px 24px">
<div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;
color:rgba(255,255,255,0.7)">What Got Produced</div>
<div style="font-size:11px;color:rgba(255,255,255,0.5);margin-top:2px">
Artifacts created and skills augmented to produce them</div>
</td></tr></table>
<div style="padding:14px 24px 18px">
<div style="font-size:11px;color:{C['muted']};margin-bottom:10px">
<strong style="color:{C['text']}">{total_files} files</strong> created or modified</div>
<table cellpadding="0" cellspacing="0">
<tr>{cells}</tr>
</table>
<div id="deliverables-detail-hdr" style="cursor:pointer;padding:6px 0 0;margin-top:6px"
onclick="toggleDetail('deliverables-detail')">
<span id="deliverables-detail-arrow" style="font-size:10px;color:{C['accent']};margin-right:5px">▶</span>
<span style="font-size:10px;font-weight:600;color:{C['accent']}">Show file names</span>
</div>
<div id="deliverables-detail-tasks" style="display:none;margin-top:6px">
<table cellpadding="0" cellspacing="0" width="100%">{file_list_rows}</table>
</div>
</div>
</td>
</tr>"""
def _daily_activity_detail(sessions: list) -> str:
"""GitHub-style heatmap grid: rows=days, columns=time periods, color=intensity."""
from datetime import datetime as _dt
from collections import defaultdict
PERIODS = [
("Early Morning", "5–9am", 5, 9),
("Morning", "9am–12pm", 9, 12),
("Afternoon", "12–5pm", 12, 17),
("Evening", "5–9pm", 17, 21),
("Night", "9pm–5am", 21, 29), # 21-24 + 0-5
]
def _period_idx(hour: int) -> int:
if 5 <= hour < 9: return 0
if 9 <= hour < 12: return 1
if 12 <= hour < 17: return 2
if 17 <= hour < 21: return 3
return 4 # 21-24 and 0-5
# Collect messages per day per period
day_periods: dict = defaultdict(lambda: [0] * 5)
for s in sessions:
for msg in s.get("messages", []):
ts = msg.get("timestamp", "")
if not ts:
continue
try:
dt = _utc_to_local(ts)
day_key = dt.strftime("%Y-%m-%d")
day_periods[day_key][_period_idx(dt.hour)] += 1
except (ValueError, TypeError):
pass
if not day_periods:
return ""
# Color intensity scale — logarithmic breaks for better visual spread
global_max = max(max(p) for p in day_periods.values()) or 1
SHADES = [
(C["bg"], C["text"]), # 0 = no activity
("#dbeafe", C["text"]), # 1 = very light
("#93c5fd", C["text"]), # 2 = light
("#3b82f6", "#ffffff"), # 3 = medium
("#1d4ed8", "#ffffff"), # 4 = high
("#1e3a5f", "#ffffff"), # 5 = intense
]
def _shade(count: int) -> tuple:
"""Return (bg_color, text_color) based on message count."""
if count == 0:
return SHADES[0]
# Log-based scaling: 1→1, 2-3→2, 4-8→3, 9-20→4, 21+→5
import math
level = min(5, max(1, int(math.log2(count) + 1)))
return SHADES[level]
# Column headers
header_cells = f'<td style="width:70px;padding:4px 0"></td>'
for name, times, _, _ in PERIODS:
header_cells += (
f'<td style="text-align:center;padding:4px 2px;width:18%">'
f'<div style="font-size:9px;font-weight:700;color:{C["muted"]};'
f'text-transform:uppercase;letter-spacing:0.3px">{name}</div>'
f'<div style="font-size:8px;color:{C["muted"]}">{times}</div>'
f'</td>'
)
header_cells += f'<td style="width:50px;padding:4px 4px;text-align:right"></td>'
# Data rows
data_rows = ""
for day in sorted(day_periods.keys()):
periods = day_periods[day]
total = sum(periods)
try:
d = _dt.strptime(day, "%Y-%m-%d")
day_label = d.strftime("%b %d")
weekday = d.strftime("%a")
except ValueError:
day_label = day[5:]
weekday = ""
cells = (
f'<td style="padding:3px 10px 3px 0;vertical-align:middle;width:70px">'
f'<span style="font-size:10px;font-weight:700;color:{C["text"]}">{day_label}</span>'
f' <span style="font-size:9px;color:{C["muted"]}">{weekday}</span>'
f'</td>'
)
for i, count in enumerate(periods):
bg, fg = _shade(count)
count_label = str(count) if count > 0 else ""
cells += (
f'<td style="padding:2px;vertical-align:middle">'
f'<div style="background:{bg};border-radius:4px;height:28px;'
f'line-height:28px;text-align:center;font-size:9px;font-weight:600;'
f'color:{fg}">{count_label}</div>'
f'</td>'
)
cells += (
f'<td style="padding:3px 0 3px 6px;vertical-align:middle;text-align:right">'
f'<span style="font-size:9px;color:{C["muted"]}">{total}</span>'
f'</td>'
)
data_rows += f'<tr>{cells}</tr>'
# Legend
legend = (
f'<div style="margin-top:8px;text-align:right">'
f'<span style="font-size:8px;color:{C["muted"]};margin-right:4px">Less</span>'
)
for bg, _ in SHADES:
legend += (
f'<span style="display:inline-block;width:12px;height:12px;'
f'background:{bg};border-radius:2px;margin:0 1px;'
f'border:1px solid {C["border"]};vertical-align:middle"></span>'
)
legend += (
f'<span style="font-size:8px;color:{C["muted"]};margin-left:4px">More</span>'
f'</div>'
)
return f"""
<table width="100%" cellpadding="0" cellspacing="0">
<tr>{header_cells}</tr>
{data_rows}
</table>
{legend}"""
def _work_pattern(sessions: list) -> str:
"""Horizontal bar chart of message counts by time-of-day bucket."""
from datetime import datetime as _dt
buckets = {
"Early Morning (5–9am)": 0,
"Morning (9am–12pm)": 0,
"Afternoon (12–5pm)": 0,
"Evening (5–9pm)": 0,
"Night (9pm–5am)": 0,
}
def _bucket_for_hour(h: int) -> str:
if 5 <= h < 9: return "Early Morning (5–9am)"
if 9 <= h < 12: return "Morning (9am–12pm)"
if 12 <= h < 17: return "Afternoon (12–5pm)"
if 17 <= h < 21: return "Evening (5–9pm)"
return "Night (9pm–5am)"
for s in sessions:
for msg in s.get("messages", []):
ts = msg.get("timestamp", "")
if not ts:
continue
try:
dt = _utc_to_local(ts)
buckets[_bucket_for_hour(dt.hour)] += 1
except (ValueError, TypeError):
pass
total = sum(buckets.values())
if total == 0:
return ""
max_count = max(buckets.values())
peak_bucket = max(buckets, key=buckets.get)
rows = ""
for label, count in buckets.items():
if count == 0 and label != peak_bucket:
bar_width = 0
else:
bar_width = int(count / max_count * 100) if max_count else 0
is_peak = label == peak_bucket
label_style = (
f"font-size:11px;font-weight:{'700' if is_peak else '400'};"
f"color:{C['text'] if is_peak else C['muted']};white-space:nowrap"
)
count_style = (
f"font-size:11px;font-weight:{'700' if is_peak else '400'};"
f"color:{C['text'] if is_peak else C['muted']};white-space:nowrap"
)
peak_tag = (
f' <span style="font-size:9px;color:{C["accent"]};font-weight:700">← Peak</span>'
if is_peak else ""
)
rows += f"""
<tr>
<td style="padding:3px 12px 3px 0;{label_style};width:160px">{label}</td>
<td style="padding:3px 0;width:auto">
<div style="background:{C['accent_lt']};border-radius:4px;height:16px;width:100%">
<div style="background:{C['accent']};border-radius:4px;height:16px;width:{bar_width}%;
min-width:{2 if count else 0}px"></div>
</div>
</td>
<td style="padding:3px 0 3px 10px;{count_style};width:100px">
{count} msg{'s' if count != 1 else ''}{peak_tag}
</td>
</tr>"""
return f"""
<tr>
<td style="background:{C['card']};padding:0;
border-left:1px solid {C['border']};border-right:1px solid {C['border']}">
<table width="100%" cellpadding="0" cellspacing="0"><tr><td bgcolor="#24292f" style="background:linear-gradient(135deg,#24292f,#1b1f23);padding:10px 24px">
<div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;
color:rgba(255,255,255,0.7)">When I Worked</div>
<div style="font-size:11px;color:rgba(255,255,255,0.5);margin-top:2px">
When Copilot-assisted work happened during the day</div>
</td></tr></table>
<div style="padding:14px 24px 18px">
<table width="100%" cellpadding="0" cellspacing="0">
{rows}
</table>
<div id="daily-detail-hdr" style="margin-top:12px;padding:8px 12px;background:{C['accent_lt']};
border-radius:6px;cursor:pointer;border:1px solid rgba(0,120,212,0.15)"
onclick="toggleDetail('daily-detail')">
<span id="daily-detail-arrow" style="font-size:10px;color:{C['accent']};margin-right:5px">▶</span>
<span style="font-size:11px;font-weight:600;color:{C['accent']}">See daily breakdown</span>
<span style="font-size:10px;color:{C['muted']};margin-left:8px">Hourly activity heatmap per day</span>
</div>
<div id="daily-detail-tasks" style="display:none;margin-top:8px">
{_daily_activity_detail(sessions)}
</div>
</div>
</td>
</tr>"""
def _collaboration_intent(sessions: list, project_label_map: dict = None) -> str:
"""Section: 'How I Collaborated' — intent donut chart with per-project breakdowns."""
from harvest import aggregate_intents
import harvest as _harvest
if project_label_map is None:
project_label_map = {}
# Prefer intent metadata from `harvest` when available; fall back to empty mappings.
_INTENT_COLORS = getattr(_harvest, "_INTENT_COLORS", {})
_INTENT_ICONS = getattr(_harvest, "_INTENT_ICONS", {})
intent_data = aggregate_intents(sessions)
counts = intent_data["counts"]
by_project_raw = intent_data["by_project"]
total = intent_data["total"]
# Remap raw project names to consistent goal labels when possible.
# If no mapping exists for a project, preserve its raw name so the
# per-project breakdown is not dropped when `project_label_map` is empty
# or incomplete.
by_project = {}
for raw_name, pcounts in by_project_raw.items():
display = project_label_map.get(raw_name) or raw_name
if display in by_project:
for cat, n in pcounts.items():
by_project[display][cat] = by_project[display].get(cat, 0) + n
else:
by_project[display] = dict(pcounts)
if total == 0:
return ""
# Sort categories by count descending, take top 6
sorted_cats = sorted(counts.items(), key=lambda x: -x[1])
if len(sorted_cats) > 6:
top = sorted_cats[:5]
other_count = sum(v for _, v in sorted_cats[5:])
top.append(("Other", other_count))
else:
top = sorted_cats
# Build conic-gradient stops for donut chart
gradient_stops = []
cumulative = 0
for cat, n in top:
pct = n / total * 100
color = _INTENT_COLORS.get(cat, C["muted"])
gradient_stops.append(f"{color} {cumulative:.1f}% {cumulative + pct:.1f}%")
cumulative += pct
gradient = ", ".join(gradient_stops)
# Legend items — vertical list beside the donut
legend_rows = ""
for cat, n in top:
pct = n / total * 100
if n == 0:
continue
color = _INTENT_COLORS.get(cat, C["muted"])
icon = _INTENT_ICONS.get(cat, "💡")
legend_rows += (
f'<div style="display:flex;align-items:center;margin-bottom:6px">'
f'<span style="display:inline-block;width:10px;height:10px;background:{color};'
f'border-radius:2px;margin-right:8px;flex-shrink:0"></span>'
f'<span style="font-size:11px;font-weight:600;color:{C["text"]};'
f'margin-right:6px;white-space:nowrap">{icon} {cat}</span>'
f'<span style="font-size:10px;color:{C["muted"]};white-space:nowrap">'
f'{n} ({pct:.0f}%)</span>'
f'</div>'
)
# Top intent insight line
top_cat, top_n = top[0]
top_pct = round(top_n / total * 100)
n_modes = len([c for c, n in top if n > 0])
insight = (
f'Worked across <strong style="color:{C["text"]}">{n_modes} collaboration modes</strong>. '
f'Primary mode: <strong style="color:{_INTENT_COLORS.get(top_cat, C["accent"])}">'
f'{top_cat}</strong> ({top_pct}% of interactions)'
)
# Per-project mini-bars (only if multiple projects)
project_bars_html = ""
if len(by_project) > 1:
proj_rows = ""
for proj, pcounts in sorted(by_project.items(), key=lambda x: -sum(x[1].values())):
ptotal = sum(pcounts.values())
if ptotal == 0:
continue
proj_sorted = sorted(pcounts.items(), key=lambda x: -x[1])
proj_bar = ""
for cat, n in proj_sorted:
pct = n / ptotal * 100
if pct < 3:
continue
color = _INTENT_COLORS.get(cat, C["muted"])
proj_bar += (
f'<td style="width:{pct:.1f}%;background:{color};height:12px;'
f'font-size:0;padding:0"></td>'
)
top2 = [f'{c} {round(n/ptotal*100)}%' for c, n in proj_sorted[:2] if n > 0]
proj_rows += (
f'<tr>'
f'<td style="padding:4px 10px 4px 0;font-size:10px;font-weight:600;'
f'color:{C["text"]};white-space:nowrap;width:120px;vertical-align:middle">{proj}</td>'
f'<td style="padding:4px 0;vertical-align:middle">'
f'<table width="100%" cellpadding="0" cellspacing="0" '
f'style="border-radius:4px;overflow:hidden"><tr>{proj_bar}</tr></table></td>'
f'<td style="padding:4px 0 4px 10px;font-size:9px;color:{C["muted"]};'
f'white-space:nowrap;width:140px;vertical-align:middle">{" · ".join(top2)}</td>'
f'</tr>'
)
if proj_rows:
project_bars_html = f"""
<div style="border-top:1px solid {C['border']};margin-top:14px;padding-top:10px">
<div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:0.7px;
color:{C['muted']};margin-bottom:6px">By Project</div>
<table width="100%" cellpadding="0" cellspacing="0">{proj_rows}</table>
</div>"""
return f"""
<tr>
<td style="background:{C['card']};padding:0;
border-left:1px solid {C['border']};border-right:1px solid {C['border']}">
<table width="100%" cellpadding="0" cellspacing="0"><tr><td bgcolor="#24292f" style="background:linear-gradient(135deg,#24292f,#1b1f23);padding:10px 24px">
<div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:1px;
color:rgba(255,255,255,0.7)">How I Collaborated</div>
<div style="font-size:11px;color:rgba(255,255,255,0.5);margin-top:2px">
Intent behind every interaction — from research to shipping</div>
</td></tr></table>
<div style="padding:14px 24px 16px">
<div style="font-size:11px;color:{C['muted']};margin-bottom:14px;line-height:1.5">
{insight}
</div>
<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td style="width:140px;vertical-align:middle;text-align:center;padding-right:20px">
<div style="width:130px;height:130px;border-radius:50%;
background:conic-gradient({gradient});
display:inline-block;position:relative">
<div style="position:absolute;top:25px;left:25px;width:80px;height:80px;
border-radius:50%;background:{C['card']}">
<div style="text-align:center;padding-top:22px">
<div style="font-size:22px;font-weight:800;color:{C['accent']};line-height:1">{total}</div>
<div style="font-size:8px;font-weight:600;color:{C['muted']};text-transform:uppercase;
letter-spacing:0.5px;margin-top:2px">interactions</div>
</div>
</div>
</div>
</td>
<td style="vertical-align:middle;padding-left:10px">
{legend_rows}
</td>
</tr>
</table>
{project_bars_html}
</div>
</td>
</tr>"""
def _skills_mobilized(goals: list) -> str:
"""Ranked horizontal bar chart of professional roles by hours of assistance."""
from collections import defaultdict
ROLE_ICONS = {
# Technical
"Software Engineer": "💻", # 💻 laptop
"Frontend Developer": "🌐", # 🌐 globe
"Data Analyst": "📈", # 📈 chart
"Data Engineer": "📊", # 📊 bar chart
"DevOps Engineer": "⚙", # ⚙ gear
"Solutions Architect": "🏗", # 🏗 building
"Security Engineer": "🔒", # 🔒 lock
"QA Engineer": "🔍", # 🔍 magnifying glass
# Design & communication
"UX Designer": "✎", # ✎ pencil
"Visual Designer": "🎨", # 🎨 palette
"Technical Writer": "📝", # 📝 memo
# Business & strategy
"Product Manager": "🎯", # 🎯 target
"Program Manager": "📋", # 📋 clipboard
"Business Analyst": "📄", # 📄 page
"Management Consultant": "💼", # 💼 briefcase
# Domain & industry
"Research Scientist": "🔬", # 🔬 microscope
"Financial Analyst": "💹", # 💹 chart with currency
"Risk & Compliance Analyst": "🛡", # 🛡 shield
"Domain Expert": "🎓", # 🎓 graduation cap
}
# Tech skill → role affinity weights.
# Used to split hours between roles on multi-role tasks rather than
# proration — e.g. Python weights toward Software Engineer, SQL toward
# Data Analyst, HTML/CSS toward UX/Visual Designer.
TECH_AFFINITY: dict = {
"Python": {"Software Engineer": 3, "Data Analyst": 1, "Data Engineer": 2},
"SQL": {"Data Analyst": 3, "Data Engineer": 2},
"JavaScript": {"Software Engineer": 3, "Frontend Developer": 2},
"TypeScript": {"Software Engineer": 3, "Frontend Developer": 2},
"HTML/CSS": {"Frontend Developer": 2, "UX Designer": 2, "Visual Designer": 1},
"CSS": {"UX Designer": 2, "Visual Designer": 2},
"Bash/Shell": {"Software Engineer": 2, "DevOps Engineer": 2},
"PowerShell": {"DevOps Engineer": 3, "Software Engineer": 1},
"R": {"Data Analyst": 3, "Data Engineer": 1},
"Java": {"Software Engineer": 3},
"Go": {"Software Engineer": 3, "DevOps Engineer": 1},
"Rust": {"Software Engineer": 3},
"C#": {"Software Engineer": 3},
"C++": {"Software Engineer": 3},
}
role_data: dict = defaultdict(lambda: {"count": 0, "hours": 0.0})
for g in goals:
for t in g.get("tasks", []):
task_hours = t.get("human_hours", 0) or 0
roles = t.get("professional_roles", [])
if not roles:
roles = t.get("domain_skills", []) + t.get("tech_skills", [])
if not roles:
continue
tech = [s for s in t.get("tech_skills", []) if s in TECH_AFFINITY]
# Build per-role affinity score from tech skills
scores: dict = {}
for r in roles:
scores[r] = sum(TECH_AFFINITY[sk].get(r, 0) for sk in tech)
total_score = sum(scores.values())
for r in roles:
role_data[r]["count"] += 1
if total_score > 0:
role_data[r]["hours"] += task_hours * (scores[r] / total_score)
else:
role_data[r]["hours"] += task_hours / len(roles)
if not role_data:
return ""
sorted_roles = sorted(role_data.items(), key=lambda x: x[1]["hours"], reverse=True)
max_hours = sorted_roles[0][1]["hours"] or 1
total_hours = sum(d["hours"] for _, d in sorted_roles)
n_roles = len(sorted_roles)
total_tasks = sum(d["count"] for _, d in sorted_roles)
rows = ""
for role, data in sorted_roles:
icon = ROLE_ICONS.get(role, "💡")
hrs = data["hours"]
count = data["count"]
bar = round(hrs / max_hours * 100)
h_str = _fmt_h(hrs)
rows += f"""
<tr>
<td style="padding:5px 10px 5px 0;white-space:nowrap;vertical-align:middle;width:24px">
<span style="font-size:15px">{icon}</span>
</td>
<td style="padding:5px 12px 5px 0;white-space:nowrap;vertical-align:middle;width:130px">
<span style="font-size:12px;font-weight:600;color:{C['text']}">{role}</span>
</td>
<td style="padding:5px 0;vertical-align:middle">
<div style="background:{C['bg']};border-radius:4px;height:14px;width:100%">
<div style="background:{C['accent']};border-radius:4px;height:14px;width:{bar}%;
min-width:4px"></div>
</div>
</td>
<td style="padding:5px 0 5px 12px;white-space:nowrap;vertical-align:middle;width:40px;text-align:right">
<span style="font-size:13px;font-weight:700;color:{C['accent']}">{h_str}</span>
</td>
<td style="padding:5px 0 5px 8px;white-space:nowrap;vertical-align:middle;width:55px">
<span style="font-size:10px;color:{C['muted']}">{count} task{'s' if count != 1 else ''}</span>
</td>
</tr>"""
return f"""
<tr>
<td style="background:{C['card']};padding:16px 24px 18px;
border-left:1px solid {C['border']};border-right:1px solid {C['border']}">
<div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.8px;
color:{C['muted']};margin-bottom:6px">SKILLS AUGMENTED</div>
<div style="font-size:14px;font-weight:700;color:{C['text']};margin-bottom:4px;line-height:1.4">
This is the team GitHub Copilot assembled for me — on demand, at zero headcount cost.</div>
<div style="font-size:11px;color:{C['muted']};margin-bottom:14px">
{_fmt_h(total_hours)} of expert-level assistance across {n_roles} professional disciplines · {total_tasks} tasks delivered</div>
<table width="100%" cellpadding="0" cellspacing="0">
{rows}
</table>
</td>
</tr>"""
def _resolve_metrics(project: str, session_metrics: dict, goal_date: str = "") -> dict:
"""Look up session metrics for a goal, trying date-prefixed key first."""
if goal_date:
dated_key = goal_date + "|" + project
metrics = session_metrics.get(dated_key, {})
if metrics:
return metrics
last = project.replace("\\", "/").split("/")[-1]
metrics = session_metrics.get(goal_date + "|" + last, {})
if metrics:
return metrics
# Fall back to non-dated key (single-day reports)
metrics = session_metrics.get(project, {})
if not metrics:
last = project.replace("\\", "/").split("/")[-1]
metrics = session_metrics.get(last, {})
return metrics
# ── Deterministic effort formula ─────────────────────────────────────────────
def _tier_tools(n: int) -> float:
"""Tool invocations → expert human hours.
Each action (read file, edit, run command, search) averages 2-3 min for
a human. Diminishing returns at scale as many become quick reads."""
if n <= 0: return 0.0
if n <= 10: return 0.5 # exploration / setup
if n <= 30: return 1.5 # focused change (~3 min each)
if n <= 75: return 3.0 # multi-file work (~2.4 min each)
if n <= 150: return 5.0 # substantial feature (~2 min each)
if n <= 300: return 8.0 # major implementation
if n <= 600: return 12.0 # full system build
return 16.0 # very large project
def _tier_reqs(n: int) -> float:
"""Premium requests → expert human hours.
Each request = a research/thinking cycle: formulate problem, read docs,
try approaches, iterate. ~8-12 min per meaningful turn."""
if n <= 0: return 0.0
if n <= 5: return 0.5 # quick consultation
if n <= 15: return 2.0 # research session
if n <= 40: return 4.0 # deep work session
if n <= 80: return 8.0 # full-day equivalent
if n <= 150: return 12.0 # multi-day research
return 16.0
def _tier_lines(n: int) -> float:
"""Lines added → additional coding effort on top of research/iteration.
Expert writes 100-150 LoC/hr including boilerplate and comments.
Partially overlaps with tool invocations (edits/creates), so effective
rate is ~200 LoC/hr when used as an additive component."""
if n <= 0: return 0.0
if n <= 50: return 0.25 # config tweak
if n <= 150: return 0.75 # small feature
if n <= 300: return 1.5 # moderate module
if n <= 500: return 2.5 # major implementation
if n <= 800: return 4.0 # large feature
return round(n / 200, 1) # continuous above 800
def _tier_active(m: float) -> float:
"""Active engagement multiplier — a human without AI would need roughly
4× the active collaboration time, accounting for the specialist skills
Copilot augments."""
return round(m * 4 / 60, 1) # 4× active minutes, converted to hours
def compute_formula_estimate(metrics: dict) -> dict:
"""Deterministic effort estimate: max(tools, requests, active) + lines.
Returns dict with per-signal multipliers and final estimate.
"""
tool_h = _tier_tools(metrics.get("tool_invocations", 0))
req_h = _tier_reqs(metrics.get("premium_requests", 0))
active_h = _tier_active(metrics.get("active_minutes", 0))
lines_h = _tier_lines(metrics.get("lines_added", 0))
base = max(tool_h, req_h, active_h)
total = base + lines_h
total = max(total, 0.25) # Floor at 0.25h
return {
"tool_h": tool_h,
"req_h": req_h,
"active_h": active_h,
"lines_h": lines_h,
"base": base,
"total": round(total * 4) / 4, # Nearest 0.25h
}
def _estimation_waterfall_inner(goals: list, analysis: dict) -> str:
"""Evidence table showing raw signals, per-signal multipliers, and formula result."""
session_metrics = analysis.get("session_metrics", {})
if not goals:
return ""
VISIBLE = 5
total_h = sum(g.get("human_hours", 0) for g in goals)
total_formula_h = 0.0
rows = ""
for i, g in enumerate(goals):
bg = C["subtle"] if i % 2 == 0 else C["card"]
project = g.get("project", "")
metrics = _resolve_metrics(project, session_metrics, g.get("date", ""))
fe = compute_formula_estimate(metrics)
total_formula_h += fe["total"]
tools = metrics.get("tool_invocations", 0)
reqs = metrics.get("premium_requests", 0)
la = metrics.get("lines_added", 0)
active = metrics.get("active_minutes", 0)
active_str = f"{active:.0f}m" if active else "—"
ai_h = _fmt_h(g.get("human_hours", 0))
formula_h = _fmt_h(fe["total"])
title = g.get("label") or g.get("title", "")
if len(title) > 40:
title = title[:37] + "..."
# Highlight which signal is the max (the "base" driver)
max_val = fe["base"]
def _hl(v: float) -> str:
"""Bold the multiplier if it equals the max (base driver)."""
s = _fmt_h(v) if v > 0 else "—"
if v > 0 and v == max_val:
return (f'<strong style="color:{C["accent"]}">{s}</strong>')
return f'<span style="color:{C["muted"]}">{s}</span>'
lines_m = _fmt_h(fe["lines_h"]) if fe["lines_h"] > 0 else "—"
# Formula string: max(tool, req, active) + lines = total
formula_str = (
f'max({_fmt_h(fe["tool_h"])}, {_fmt_h(fe["req_h"])}, {_fmt_h(fe["active_h"])})'
f' + {_fmt_h(fe["lines_h"])} = <strong>{formula_h}</strong>'