File size: 59,314 Bytes
c72fe58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
# Polyhedra β€” Full Codebase Implementation Reference

> Version: **4.4** | Branch: `V4.4` | Python β‰₯ 3.11  
> Paper trading simulation only. No real capital. Not financial advice.

---

## Table of Contents

1. [Project Overview](#1-project-overview)
2. [Repository Layout](#2-repository-layout)
3. [Package Entry Points](#3-package-entry-points)
4. [Core Infrastructure (`core/`)](#4-core-infrastructure-core)
5. [Agent System (`agents/`)](#5-agent-system-agents)
6. [Quant Pipeline (`agents/quant/`)](#6-quant-pipeline-agentsquant)
7. [Services (`services/`)](#7-services-services)
8. [Messaging (`messaging/`)](#8-messaging-messaging)
9. [CLI (`cli/`)](#9-cli-cli)
10. [Agent Workflow Engine (`agent/`)](#10-agent-workflow-engine-agent)
11. [Schemas (`schemas/`)](#11-schemas-schemas)
12. [MCP Server (`server.py`)](#12-mcp-server-serverpy)
13. [FastAPI App (`app.py`)](#13-fastapi-app-apppy)
14. [Routing System](#14-routing-system)
15. [Data Flow β€” Full Quant Chain](#15-data-flow--full-quant-chain)
16. [Environment Variables](#16-environment-variables)
17. [Key Design Patterns](#17-key-design-patterns)
18. [Known Bugs & Fixes Applied](#18-known-bugs--fixes-applied)

---

## 1. Project Overview

Polyhedra is a **multi-agent research and paper-trading system** that runs as:

| Surface | Entry point | Purpose |
|---|---|---|
| Slack bot | `messaging/slack.py` | Live @mention-driven quant chain |
| CLI | `cli/main.py` β†’ `poly` command | Terminal sessions |
| MCP server | `server.py` β†’ `polyhedra` command | VS Code / Cursor tool-call integration |
| FastAPI | `app.py` | Slack webhook receiver + health probe |

Two agent families operate in parallel:

- **Research family** β€” Scout β†’ Strategist β†’ Critic β†’ Scribe (literature review; disabled from Slack in V4.3)
- **Quant family** β€” DataFetcher β†’ TrendAnalyst β†’ SentimentAnalyst β†’ QuantResearcher β†’ Backtester β†’ RiskAnalyst β†’ QuantStrategist β†’ VizAgent + PortfolioMonitor

---

## 2. Repository Layout

```
src/polyhedra/
β”œβ”€β”€ __init__.py           # version = "4.4.0", re-exports main
β”œβ”€β”€ app.py                # FastAPI application factory
β”œβ”€β”€ server.py             # MCP server (polyhedra CLI entry point)
β”œβ”€β”€ agent/                # Standalone workflow engine (Intent β†’ Workflow β†’ Steps)
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ checkpoint.py
β”‚   β”œβ”€β”€ config.py
β”‚   β”œβ”€β”€ intent_parser.py
β”‚   β”œβ”€β”€ models.py
β”‚   β”œβ”€β”€ research_agent.py
β”‚   β”œβ”€β”€ retry.py
β”‚   β”œβ”€β”€ state.py
β”‚   β”œβ”€β”€ tool_adapter.py
β”‚   └── workflow_generator.py
β”œβ”€β”€ agents/               # Multi-agent orchestration
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ base.py           # Agent ABC, AgentResponse, Mention
β”‚   β”œβ”€β”€ coordinator.py    # CoordinatorAgent + CoordinatorService
β”‚   β”œβ”€β”€ critic.py
β”‚   β”œβ”€β”€ scout.py
β”‚   β”œβ”€β”€ scribe.py
β”‚   β”œβ”€β”€ strategist.py
β”‚   └── quant/
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ routing.py    # LLM_ROUTING_PROMPT, parse_llm_routing, parse_proposals_block (V4.4)
β”‚       β”œβ”€β”€ datafetcher.py
β”‚       β”œβ”€β”€ trendanalyst.py
β”‚       β”œβ”€β”€ sentimentanalyst.py
β”‚       β”œβ”€β”€ quantresearcher.py
β”‚       β”œβ”€β”€ backtester.py
β”‚       β”œβ”€β”€ riskanalyst.py
β”‚       β”œβ”€β”€ quantstrategist.py
β”‚       β”œβ”€β”€ outputs.py    # Typed Pydantic output models (V4.4)
β”‚       β”œβ”€β”€ vizagent.py
β”‚       └── portfoliomonitor.py
β”œβ”€β”€ cli/
β”‚   └── main.py           # Typer app β€” `poly` command
β”œβ”€β”€ core/
β”‚   β”œβ”€β”€ __init__.py       # Re-exports all core types
β”‚   β”œβ”€β”€ agent_router.py   # AgentRouter, QUANT_ROLES, ALT_AGENT_MAP (V4.4)
β”‚   β”œβ”€β”€ cache.py          # SharedCache (V4.3)
β”‚   β”œβ”€β”€ cost_gate.py      # CostGate β€” approval threshold logic (V4.4)
β”‚   β”œβ”€β”€ eventbus.py       # EventBus + event dataclasses (V4.3)
β”‚   β”œβ”€β”€ mention_parser.py
β”‚   β”œβ”€β”€ research_state.py # ResearchState, QuantState, all domain dataclasses
β”‚   β”œβ”€β”€ role_registry.py
β”‚   β”œβ”€β”€ session.py
β”‚   β”œβ”€β”€ state_patcher.py  # StatePatcher β€” ResearchState update helper (V4.4)
β”‚   β”œβ”€β”€ template_builder.py # TemplateBuilder, COMMAND_REGISTRY, render_help_* (V4.4)
β”‚   β”œβ”€β”€ token_budget.py   # TokenBudget, PromptBuilder (V4.3)
β”‚   └── trace_logger.py   # TraceLogger β€” session trace.jsonl writer (V4.4)
β”œβ”€β”€ messaging/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── slack.py          # SlackIntegration
β”œβ”€β”€ schemas/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── paper.py          # Pydantic models for Semantic Scholar
└── services/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ alpha_vantage.py
    β”œβ”€β”€ citation_manager.py
    β”œβ”€β”€ context_manager.py
    β”œβ”€β”€ file_writer.py    # FileWriter (V4.3: cache + RAG integration)
    β”œβ”€β”€ finnhub.py
    β”œβ”€β”€ literature_review_service.py
    β”œβ”€β”€ llm_service.py
    β”œβ”€β”€ project_initializer.py
    β”œβ”€β”€ rag_service.py
    └── semantic_scholar.py
```

---

## 3. Package Entry Points

Defined in `pyproject.toml`:

```toml
[project.scripts]
polyhedra = "polyhedra.server:main"   # MCP server
poly      = "polyhedra.cli.main:main" # CLI
```

**Dependencies (core):** `mcp`, `httpx`, `pydantic`, `bibtexparser`, `sentence-transformers`, `numpy`, `typer`, `rich`, `fastapi`, `uvicorn`, `slack-bolt`, `python-dotenv`, `aiohttp`, `redis`, `yfinance`, `matplotlib`

---

## 4. Core Infrastructure (`core/`)

### 4.1 `core/__init__.py`

Re-exports all types that other modules need to import from a single location:

```python
SharedCache, AgentBlockedEvent, AgentCompletedEvent, EventBus,
HumanInputRequiredEvent, PortfolioAlertEvent, ResearchState,
ResearchStateManager, TokenUsageEntry, RoleEntry, RoleRegistry,
Session, SessionManager, PromptBuilder, TokenBudget, get_bus
```

---

### 4.2 `core/cache.py` β€” SharedCache (V4.3)

In-memory session cache. Replaces file-based shared state; filesystem is persistence backup only.

**Cache key conventions:**

| Prefix | TTL | Contents |
|---|---|---|
| `state:<session_id>` | None (never expires) | ResearchState / QuantState |
| `artifact:<session_id>:<path>` | None | Artifact contents by path |
| `llm:<prompt_hash>` | None | LLM output by hash |
| `api:market:<...>` | 86 400 s (24 h) | Market API responses |
| `api:sentiment:<...>` | 3 600 s (1 h) | Sentiment API responses |
| `api:quote:<...>` | 60 s (1 min) | Real-time quote responses |

**Key classes:**

```python
class CacheStats:
    hits: int
    misses: int
    def record_hit() -> None
    def record_miss() -> None
    def to_dict() -> dict

class SharedCache:
    def get(key: str) -> Any | None
    def set(key: str, value: Any, ttl: int | None = _SENTINEL) -> None
    def invalidate(key: str) -> None
    def invalidate_prefix(prefix: str) -> None
    def clear() -> None
    def flush_to_disk(path: Path) -> None
    def warm_from_disk(path: Path) -> None
    async def async_flush_to_disk(path: Path) -> None
```

**Module-level helpers:**

```python
_SENTINEL = object()          # sentinel for "use default TTL"
prompt_hash(prompt: str) -> str   # SHA-256 hex[:16] of prompt
```

> **Bug fixed:** `_SENTINEL` must be at module level β€” walrus operator `:=` is illegal in default parameter positions.

---

### 4.3 `core/eventbus.py` β€” EventBus (V4.3)

In-process pub/sub. Agents emit events; Coordinator reacts as subscriber. No external broker.

**Event dataclasses:**

```python
@dataclass
class AgentCompletedEvent:
    session_id: str
    agent_role: str
    artifact_path: str | None
    next_role: str | None        # None = chain complete
    reason: str
    depth: int
    content: str
    updates_state: bool
    state_patch: dict[str, Any]
    checkpoint_required: bool
    checkpoint_summary: str
    origin_id: str               # chain origin message_id for depth tracking

@dataclass
class AgentBlockedEvent:
    session_id: str
    agent_role: str
    reason: str
    missing_artifact: str | None
    suggested_role: str | None
    content: str

@dataclass
class HumanInputRequiredEvent:
    session_id: str
    agent_role: str
    question: str
    suggested_templates: str
    content: str

@dataclass
class PortfolioAlertEvent:
    session_id: str
    position_id: str
    ticker: str
    alert_type: str              # "take_profit" | "stop_loss" | "move_pct"
    current_price: float
    threshold: float
    content: str
```

**EventBus API:**

```python
class EventBus:
    def subscribe(event_type: type, handler: Callable) -> None
    def unsubscribe(event_type: type, handler: Callable) -> None
    async def publish(event: Any) -> None
    async def _call_handler(handler: Callable, event: Any) -> None

# Module-level per-session bus registry
def get_bus(session_id: str) -> EventBus
def clear_bus(session_id: str) -> None
```

---

### 4.4 `core/research_state.py` β€” Domain Model

All domain dataclasses for research and quant state.

**Research domain:**

```python
@dataclass class Gap:             description, source_papers, confidence
@dataclass class Hypothesis:      statement, methodology_sketch, confidence, created_at
@dataclass class Paper:           title, paper_id, year, relevance_score, one_line_summary, bibtex_key
@dataclass class Decision:        description, rationale, made_by, timestamp
```

**Quant domain:**

```python
@dataclass class Signal:          signal_id, name, ticker, entry_condition, exit_condition, confidence, assumptions, created_at
@dataclass class BacktestResult:  signal_id, ticker, win_rate, avg_return_pct, max_drawdown_pct, sharpe_ratio, num_trades, notes, created_at
@dataclass class TradeProposal:   proposal_id, ticker, direction, entry_condition, target_entry_price, take_profit, stop_loss, position_size_pct, rationale, confidence, risk_rating, status, created_at
@dataclass class PaperPosition:   position_id, ticker, direction, entry_price, size_pct, opened_at, proposal_id, status, take_profit, stop_loss, close_price, close_date
@dataclass class TradeEvent:      event_id, proposal_id, action, reason, timestamp
@dataclass class TokenUsageEntry: agent_role, timestamp, prompt_tokens, completion_tokens, estimated_cost_usd, cache_hit
```

**Top-level state:**

```python
@dataclass class QuantState:
    watchlist: list[str]
    last_fetch: str | None
    last_run: str | None
    signals: list[Signal]
    backtest_results: list[BacktestResult]
    risk_ratings: dict[str, str]
    trade_proposals: list[TradeProposal]
    portfolio: list[PaperPosition]
    trade_log: list[TradeEvent]
    alerts: list[str]
    monitor_paused: bool
    last_monitor_run: str | None
    token_log: list[TokenUsageEntry]
    def to_dict() / from_dict() / to_markdown()

@dataclass class ResearchState:
    goal: str
    field: str
    gaps: list[Gap]
    active_hypothesis: Hypothesis | None
    key_papers: list[Paper]
    decisions: list[Decision]
    open_questions: list[str]
    pending_tasks: list[str]
    last_updated: str
    version: int
    quant_state: QuantState | None
    def to_dict() / from_dict() / to_markdown() / compress()
```

**Constants:**

```python
_CHARS_PER_TOKEN = 4
_MAX_TOKENS = 4_000
_MAX_CHARS = 16_000
```

---

### 4.5 `core/session.py` β€” Session Management

```python
_SESSIONS_DIR = Path.home() / ".polyhedra" / "sessions"

@dataclass class ThreadMessage:
    from_role: str
    content: str
    message_id: str
    timestamp: str
    metadata: dict
    def to_dict() / from_dict()

class Session:
    session_id: str
    session_dir: Path
    state_manager: ResearchStateManager
    registry: RoleRegistry
    goal: str
    active_roles: list[str]
    created_at: str
    platform: str
    def post(role, content, message_id, metadata) -> ThreadMessage
    def thread_history(limit) -> list[ThreadMessage]
    def full_thread() -> list[dict]
    @property research_state -> ResearchState
    def save_meta() / load_meta()

class SessionManager:
    def create(goal, platform, roles) -> Session
    def resume(session_id) -> Session
    def list_sessions() -> list[dict]
    def export(session_id) -> Path

# V4.4 additions (FIX-2)
def active_sessions_with_positions() -> list[str]  # sessions that have open positions
def _registry_path() -> Path                        # ~/.polyhedra/sessions/registry.json
def _save_registry(entry: dict) -> None             # persists session β†’ positions map
```

---

### 4.6 `core/token_budget.py` β€” Token Budget & Prompt Assembly (V4.3)

Agents declare a `TokenBudget`. `PromptBuilder` enforces it: never trims `system`, `task`, or `routing`; trims `context` first, then `thread`.

```python
@dataclass class TokenBudget:
    system:  int = 500    # role + constraints β€” NEVER trimmed
    context: int = 2000   # RAG artifact chunks β€” trimmed first
    task:    int = 500    # task instruction β€” NEVER trimmed
    thread:  int = 500    # recent messages β€” trimmed last
    routing: int = 200    # routing block β€” NEVER trimmed
    total:   int = 4000   # hard ceiling
    @property fixed -> int  # system + task + routing

DEFAULT_BUDGET = TokenBudget()   # applied when agent declares none

@dataclass class Chunk:
    text: str
    score: float
    metadata: dict
    def token_count() -> int

class PromptBuilder:
    def set_system(text: str) -> PromptBuilder
    def set_task(text: str) -> PromptBuilder
    def set_routing(text: str) -> PromptBuilder
    def set_context(chunks: list[Chunk]) -> PromptBuilder
    def set_thread(messages: list[dict]) -> PromptBuilder
    def build() -> str
    def _trim_thread(budget: int) -> str
    def _assemble() -> str

class PromptOverBudgetError(Exception): ...
```

---

### 4.7 `core/role_registry.py`

```python
HELD_BY_AGENT = "agent"
HELD_BY_HUMAN = "human"

@dataclass class RoleEntry:
    role: str
    agent: Agent
    held_by: str
    takeover_message_id: str | None
    @property is_human -> bool
    @property is_agent -> bool

class RoleRegistry:
    def register(role, agent) -> None
    def unregister(role) -> None
    def get(role) -> RoleEntry | None
    def roles() -> list[str]
    def agent_roles() / human_roles() -> list[str]
    def take_over(role, message_id) -> None
    def reinstate(role) -> None
    def to_dict() -> dict
    def summary() -> str
```

---

### 4.8 `core/mention_parser.py`

```python
_AT_MENTION_RE = re.compile(r"@(\w+)")

@dataclass class ParsedMention:
    mentioned_roles: list[str]
    human_addressed: bool
    raw_text: str

class MentionParser:
    def parse(text: str) -> ParsedMention
    def extract_roles(text: str) -> list[str]
    def strip_mentions(text: str) -> str
```

---

### 4.9 `core/agent_router.py` β€” AgentRouter (V4.4)

Extracted from `coordinator.py` (STRUCT-1). Owns all routing constants and depth tracking.

```python
QUANT_ROLES: frozenset[str] = frozenset({
    "datafetcher", "trendanalyst", "sentimentanalyst",
    "quantresearcher", "backtester", "riskanalyst",
    "quantstrategist", "vizagent", "portfoliomonitor", "human"
})

ALT_AGENT_MAP: dict[str, str] = {   # skip-forward map on agent block
    "trendanalyst":     "sentimentanalyst",
    "sentimentanalyst": "quantresearcher",
    "quantresearcher":  "backtester",
    "backtester":       "riskanalyst",
    "riskanalyst":      "quantstrategist",
    "quantstrategist":  "human",
}

class AgentRouter:
    def init_origin(message_id: str) -> None       # set chain origin for depth tracking
    def can_dispatch(role: str) -> bool            # depth gate check
    def record_dispatch(role: str) -> None         # increment depth counter
    def reset_depth() -> None                      # reset after chain completes
    def current_depth() -> int
    def next_alt(role: str) -> str | None          # skip-forward lookup
    def is_quant_role(role: str) -> bool
```

---

### 4.10 `core/template_builder.py` β€” TemplateBuilder (V4.4)

Extracted from `coordinator.py` (STRUCT-1 / STRUCT-4). Owns `COMMAND_REGISTRY` and help renderers.

```python
@dataclass class CommandEntry:
    command: str           # e.g. "/poly approve"
    description: str
    example: str | None

COMMAND_REGISTRY: list[CommandEntry]   # 25 entries covering all /poly and @agent commands

def render_help_slack() -> str    # Block Kit–formatted Slack help message
def render_help_cli() -> str      # Rich table for terminal

class TemplateBuilder:
    def build(touchpoint: str, *, next_role: str, proposal_id: str,
              session_id: str) -> str
    # Touchpoints: "checkpoint" | "trade_proposals" | "agent_blocked"
    #              | "uncertainty" | "resume"
    def _opts_checkpoint() -> list[str]
    def _opts_trade_proposals(proposal_id: str) -> list[str]
    def _opts_agent_blocked(next_role: str) -> list[str]
    def _opts_uncertainty() -> list[str]
    def _opts_resume(session_id: str) -> list[str]
```

---

### 4.11 `core/state_patcher.py` β€” StatePatcher (V4.4)

Extracted from `coordinator.py` (STRUCT-1). Applies `AgentResponse.state_patch` to persisted `ResearchState`.

```python
class StatePatcher:
    def validate(patch: dict) -> list[str]          # returns list of validation errors
    def apply(session: Session, patch: dict) -> None
    # Loads ResearchState, applies patch keys, compresses, saves back to disk
```

---

### 4.12 `core/cost_gate.py` β€” CostGate (V4.4)

Extracted from `coordinator.py` (STRUCT-1). Encapsulates cost approval threshold logic.

```python
_COST_APPROVAL_THRESHOLD = 0.50   # USD

class CostGate:
    def requires_approval(estimated_cost: float) -> bool
    def format_approval_request(estimated_cost: float, action: str) -> str
```

---

### 4.13 `core/trace_logger.py` β€” TraceLogger (V4.4)

New. Writes per-run JSON entries to `{session_dir}/trace.jsonl`. Injected into each agent by Coordinator (STRUCT-3).

```python
class TraceLogger:
    def __init__(session_dir: Path)
    def start_run(agent_role: str, prompt_tokens: int) -> str   # returns run_id sha256_prefix
    def end_run(run_id: str, completion_tokens: int,
                next_role: str | None, cost: float) -> None
    def read_trace(last_n: int = 10) -> list[dict]              # for /poly trace

def _sha256_prefix(data: str) -> str   # module-level 8-char ID helper
```

---

## 5. Agent System (`agents/`)

### 5.1 `agents/base.py` β€” Agent ABC

```python
@dataclass class Mention:
    mentioned_role: str
    from_role: str
    content: str
    thread_message_id: str | None
    timestamp: str
    metadata: dict[str, Any]

@dataclass class AgentResponse:
    agent_role: str
    content: str
    mentions: list[str]           # roles to dispatch next
    artifact_path: str | None
    artifact_mode: str            # "overwrite" | "append"
    updates_state: bool
    state_patch: dict[str, Any]
    checkpoint_required: bool
    checkpoint_summary: str
    error: str | None
    output: BaseModel | None = None  # typed output model (V4.4 STRUCT-2)
    metadata: dict[str, Any]         # deprecated in favour of output (V4.4)

class Agent(ABC):
    name: str                     # display name
    role: str                     # kebab-case routing key
    role_title: str
    system_prompt: str
    files: FileWriter             # injected by coordinator
    bus: EventBus | None          # injected by coordinator
    token_budget: TokenBudget     # class-level default
    trace: "TraceLogger | None" = None  # injected by coordinator (V4.4 STRUCT-3)
    logger: logging.Logger

    @abstractmethod async def handle(mention, thread_context, research_state) -> AgentResponse
    @abstractmethod async def can_handle(mention) -> bool
    def _format_thread_context(thread_context) -> str
    def _format_research_state(research_state) -> str
    def _log_token_usage(research_state, prompt_tokens, completion_tokens, cache_hit) -> None
```

---

### 5.2 `agents/coordinator.py` β€” Coordinator

**Constants (V4.4 β€” moved to delegated helpers):**

```python
_MAX_MENTION_DEPTH = 3           # hard stop for non-quant chains
# _QUANT_ROLES and _ALT_AGENT_MAP have moved to core/agent_router.py (V4.4 STRUCT-1)
```

**V4.4 delegates (injected at `__init__`):**
- `self._router` β€” `AgentRouter` (depth tracking, quant role set, skip-forward map)
- `self._templates` β€” `TemplateBuilder` (input suggestion templates)
- `self._patcher` β€” `StatePatcher` (ResearchState patch application)
- `self._cost_gate` β€” `CostGate` (approval threshold check)
- `self._trace` β€” `TraceLogger` (session `trace.jsonl` writer; injected into each agent)

**CoordinatorService** drives session lifecycle. On each inbound message:
1. Parses @mentions via `MentionParser`
2. Assembles `Mention` with `from_role`, `thread_message_id`
3. Calls `self._router.can_dispatch()` + `record_dispatch()` + `init_origin()`
4. Finds matching agent via `RoleRegistry`; injects `entry.agent.trace = self._trace`
5. Calls `agent.handle()` inside an event-bus transaction
6. Publishes `AgentCompletedEvent` / `AgentBlockedEvent` / `HumanInputRequiredEvent`
7. Depth-tracks via `AgentRouter`; pauses (not hard-stops) at limit for quant chain
8. Applies `state_patch` via `self._patcher.apply()`
9. Cost gate via `self._cost_gate.requires_approval()` + `format_approval_request()`

**`_build_input_templates()`** β€” now delegates to `self._templates.build()`; see `core/template_builder.py`.

**`_handle_slash_command()`:**
- `/poly trace` β†’ `_post_trace_summary()` β€” posts last 10 trace entries as Slack table
- `/poly help` β†’ `render_help_slack()` from `TemplateBuilder`

**`_post_token_summary()`** β€” reads from `trace.jsonl` first; falls back to `QuantState.token_log`.

---

### 5.3 Research Agents (`agents/scout.py`, `strategist.py`, `critic.py`, `scribe.py`)

> **Status in V4.3:** Implemented but **disabled from Slack session registration**. Only 9 quant agents are registered.

| Agent | Role | Job |
|---|---|---|
| `ScoutAgent` | `scout` | Semantic Scholar search; `_MAX_PAPERS = 50`, default `_DEFAULT_LIMIT = 20` |
| `StrategistAgent` | `strategist` | Plans next research steps from Scout summary; uses LLM |
| `CriticAgent` | `critic` | Reviews draft sections for logical gaps; uses LLM |
| `ScribeAgent` | `scribe` | Writes/appends paper sections; uses LLM; `_KNOWN_SECTIONS` set |

All four use lazy LLM initialisation:

```python
@property
def _llm(self) -> LLMService:
    if self.__llm is None:
        self.__llm = self._llm_service or LLMService()
    return self.__llm
```

---

## 6. Quant Pipeline (`agents/quant/`)

### 6.1 Pipeline Overview

```
Human (@datafetcher)
        β”‚
        β–Ό
  DataFetcherAgent          ──── Finnhub API ────► quant/raw/<TICKER>_<date>.json
        β”‚                                          quant/raw/<TICKER>_<date>_summary.md
        β”‚ (trend_analysis_<date>.md absent β†’ trendanalyst)
        β”‚ (trend_analysis_<date>.md present β†’ sentimentanalyst) ← V4.3 mid-chain fix
        β–Ό
  TrendAnalystAgent (LLM)  ──────────────────────► quant/trend_analysis_<date>.md
        β”‚ (cycle guard: datafetcher β†’ sentimentanalyst)
        β–Ό
  SentimentAnalystAgent (LLM) ───────────────────► quant/sentiment_analysis_<date>.md
        β–Ό
  QuantResearcherAgent (LLM) ────────────────────► quant/signal_hypotheses_<date>.md
        β–Ό
  BacktesterAgent (LLM)     ─────────────────────► quant/backtest_results_<date>.md
        β–Ό
  RiskAnalystAgent (LLM)    ─────────────────────► quant/risk_assessment_<date>.md
        β–Ό
  QuantStrategistAgent (LLM) ────────────────────► quant/trade_proposals_<date>.md
        β”‚ (always β†’ @human)
        β–Ό
  Human (reviews + approves)
        β”‚
        β–Ό
  VizAgent (on demand)      ─────────────────────► quant/viz/<chart_type>_<TICKER>_<date>.png
  PortfolioMonitorAgent (scheduled) ─────────────► quant/portfolio_log_<date>.md
```

---

### 6.2 `agents/quant/routing.py` β€” LLM Routing

```python
QUANT_ROLES: frozenset[str] = frozenset({
    "datafetcher", "trendanalyst", "sentimentanalyst",
    "quantresearcher", "backtester", "riskanalyst",
    "quantstrategist", "vizagent", "portfoliomonitor", "human"
})

LLM_ROUTING_PROMPT: str  # Appended to every LLM agent prompt (see Β§14)

def parse_llm_routing(content: str | None) -> tuple[str | None, str, str]:
    """
    Extracts last {"next": "<role>", "reason": "<...>"} JSON block.
    Returns (next_role, reason, stripped_content).
    next_role is None if JSON is absent or next=null.
    Validates next_role against QUANT_ROLES.
    """

# V4.4 additions (FIX-3) β€” structured trade proposal parsing
def parse_proposals_block(content: str) -> list[dict]:
    """
    Extracts ```proposals ... ``` JSON array block from QuantStrategist output.
    Each element is validated with _validate_proposal().
    Returns empty list if block is absent or malformed.
    """
def _balance_brackets(text: str) -> str   # repair truncated JSON before parse attempt
def _validate_proposal(obj: dict) -> bool  # checks required keys + value ranges
```

---

### 6.3 DataFetcherAgent (`datafetcher.py`)

- **No LLM** β€” routing is fully deterministic
- Resolves watchlist from: `research_state.quant_state.watchlist` β†’ @mention text extraction β†’ `POLYHEDRA_QUANT_WATCHLIST` env
- Calls `FinnhubService.fetch_ticker_data()` per ticker
- Writes `quant/raw/<TICKER>_<date>.json` and `quant/raw/<TICKER>_<date>_summary.md`
- **Routing logic (V4.4):**

```python
# _fetch_one() returns 4-tuple: (fetched: bool, cap_hit: bool, ticker: str, has_ohlcv: bool)
# _fetch_all() returns 5-tuple; tracks ohlcv_failures, sets all_ohlcv_failed

if all_ohlcv_failed:
    # FIX-5: route to @human with yfinance_alert: True in state_patch
    next_mentions = ["human"]
elif not fetched and cap_hit:
    next_mentions = ["human"]
elif trend_exists:
    next_mentions = ["sentimentanalyst"]   # mid-chain β†’ skip TrendAnalyst
else:
    next_mentions = ["trendanalyst"]       # fresh session start
```

- **`_is_valid_ticker(token: str) -> bool`** (V4.4 FIX-8) β€” replaces `_SKIP_TOKENS`; checks against `POLYHEDRA_VALID_TICKERS` env var allow-list if set, otherwise falls back to regex heuristics

---

### 6.4 TrendAnalystAgent (`trendanalyst.py`)

- **TokenBudget:** `system=500, context=2000, task=500, thread=500, routing=200, total=4000`
- Reads `quant/raw/*_<date>_summary.md` files written by DataFetcher
- If no summaries exist β†’ returns `AgentResponse(mentions=["datafetcher"])`
- LLM call β†’ `parse_llm_routing`
- **Cycle guard (V4.3):** forcibly overrides any `datafetcher` routing to `sentimentanalyst`

```python
if next_role == "datafetcher":
    logger.warning("TrendAnalyst: suppressing datafetcher re-route (cycle guard) β†’ sentimentanalyst")
    next_role = "sentimentanalyst"
```

- **`_ETF_CONSTRAINT`** β€” instructs LLM to omit earnings section for ETFs
- Writes `quant/trend_analysis_<date>.md`

**Prompt structure:**
1. `[1] ROLE` β€” system prompt
2. `[2] INPUTS` β€” tickers + raw summaries (capped 4000 chars) + thread context
3. `[3] TASK` β€” per-ticker sections: price trend, volume, momentum, earnings
4. `[4] CONSTRAINTS` β€” ETF rule, data gap rule, **datafetcher cycle guard rule**
5. `[5] ROUTING` β€” `LLM_ROUTING_PROMPT`

---

### 6.5 SentimentAnalystAgent (`sentimentanalyst.py`)

- **TokenBudget:** same as TrendAnalyst
- Reads trend analysis + raw summaries
- Three additional constraints:
  - `_ETF_CONSTRAINT` β€” skip earnings for ETFs
  - `_THIN_SENTIMENT_CONSTRAINT` β€” >50% zero-score news β†’ flag as insufficient, route `datafetcher`
  - `_NO_REPACKAGE_CONSTRAINT` β€” must add new signal layer beyond technical findings
- Writes `quant/sentiment_analysis_<date>.md`

---

### 6.6 QuantResearcherAgent (`quantresearcher.py`)

- **TokenBudget:** same as TrendAnalyst
- Reads trend + sentiment analyses
- Identifies named signal hypotheses with entry/exit conditions, confidence level, and falsification criteria
- Does NOT backtest
- Writes `quant/signal_hypotheses_<date>.md`

---

### 6.7 BacktesterAgent (`backtester.py`)

- **TokenBudget:** same as TrendAnalyst
- **`_MIN_TRADES_THRESHOLD = 5`** β€” signals with fewer occurrences are flagged as statistically weak
- Reads signal hypotheses + raw OHLCV summaries
- Reports honest metrics: win rate, avg return %, max drawdown %, Sharpe ratio, trade count
- Never cherry-picks results
- Writes `quant/backtest_results_<date>.md`

---

### 6.8 RiskAnalystAgent (`riskanalyst.py`)

- **TokenBudget:** same as TrendAnalyst
- Reads backtest results + signal hypotheses + portfolio state
- Evaluates: correlation risk, concentration risk, drawdown risk, stress scenarios
- Assigns risk verdict per signal: **Acceptable / Elevated / Reject**
- Does NOT make allocation decisions
- Writes `quant/risk_assessment_<date>.md`

---

### 6.9 QuantStrategistAgent (`quantstrategist.py`)

- **TokenBudget:** same as TrendAnalyst
- **`_MAX_PROPOSALS = 3`** β€” hard cap on proposals per run
- Hard constraints:
  - Only proposes Acceptable or Elevated signals (never Reject)
  - Elevated signals must include specific risk mitigation note
  - **Always routes to `@human`** β€” never chains further
- Writes `quant/trade_proposals_<date>.md`
- **V4.4 FIX-3:** prompt now requires a fenced ` ```proposals ``` ` JSON block; `parse_proposals_block()` from `routing.py` extracts and validates it; narrative text before the block is preserved separately.

---

### 6.10 VizAgent (`vizagent.py`)

- **TokenBudget:** same as TrendAnalyst
- Triggered by TrendAnalyst, Backtester, RiskAnalyst, or direct human @mention
- **`_CHART_KEYWORDS`** β€” maps free-text keywords to chart type:
  - `"candlestick"/"candle"` β†’ `"candlestick"`
  - `"rsi"/"macd"` β†’ `"rsi_macd"`
  - `"backtest"` β†’ `"backtest"`
  - `"risk"/"heatmap"` β†’ `"risk_heatmap"`
  - `"portfolio"/"pnl"/"p&l"` β†’ `"portfolio_pnl"`
- Saves charts to `quant/viz/<chart_type>_<ticker>_<date>.png`
- Uses `matplotlib` for static PNG generation
- LLM generates a 2–3 sentence chart caption

---

### 6.11 PortfolioMonitorAgent (`portfoliomonitor.py`)

- **Schedule:** every `POLYHEDRA_MONITOR_INTERVAL` minutes (default 30), Mon–Fri 09:30–16:00 ET
- **`_DEFAULT_ALERT_MOVE_PCT = 2.0`** β€” threshold for unrealised move alerts
- On each run:
  1. Fetches latest quote for every open position via `FinnhubService.get_quote()`
  2. Evaluates take-profit, stop-loss, Β±move thresholds
  3. Publishes `PortfolioAlertEvent` on breach
  4. Writes `quant/portfolio_log_<date>.md`
- **`_is_market_hours(tz_name)`** β€” checks Mon–Fri 09:30–16:00 in given timezone; graceful fallback if `zoneinfo` unavailable

**Environment variables specific to PortfolioMonitor:**

```
POLYHEDRA_MONITOR_INTERVAL   interval in minutes (default: 30)
POLYHEDRA_MARKET_TZ          timezone string (default: America/New_York)
POLYHEDRA_ALERT_MOVE_PCT     move threshold percentage (default: 2.0)
```

---

### 6.12 `agents/quant/outputs.py` β€” Typed Output Models (V4.4)

Seven Pydantic `BaseModel` subclasses matching each quant agent's structured output. Assigned to `AgentResponse.output` (STRUCT-2).

```python
class DataFetcherOutput(BaseModel):
    tickers: list[str]
    fetched: list[str]
    failed: list[str]
    all_ohlcv_failed: bool

class TrendAnalystOutput(BaseModel):
    tickers: list[str]
    artifact_path: str

class SentimentAnalystOutput(BaseModel):
    tickers: list[str]
    artifact_path: str

class QuantResearcherOutput(BaseModel):
    signal_count: int
    artifact_path: str

class BacktesterOutput(BaseModel):
    tested_signals: list[str]
    artifact_path: str

class RiskAnalystOutput(BaseModel):
    verdicts: dict[str, str]   # signal_id β†’ "Acceptable" | "Elevated" | "Reject"
    artifact_path: str

class QuantStrategistOutput(BaseModel):
    proposals: list[dict]      # validated proposal dicts from parse_proposals_block()
    artifact_path: str
```

---

## 7. Services (`services/`)

### 7.1 `services/llm_service.py` β€” LLM Abstraction

**Exceptions:**

```python
ConfigurationError     # missing API key or config
RateLimitError         # HTTP 429; carries retry_after: int | None
AuthenticationError    # 401/403
TimeoutError           # request timeout
```

**Abstract adapter:**

```python
class LLMAdapter(ABC):
    async def complete(prompt, model=None) -> tuple[str, int, int]
    # Returns (response_text, input_tokens, output_tokens)
    def calculate_cost(input_tokens, output_tokens, model) -> float
    async def close() -> None
```

**AnthropicAdapter:**

```python
DEFAULT_MODEL = "claude-3-5-sonnet-20241022"
PRICING = {
    "claude-3-5-sonnet-20241022": {"input": 3.0, "output": 15.0},
    # ... per million tokens
}
```

**GeminiAdapter:** Same structure with Gemini pricing table.

**LLMService** wraps the active adapter selected from environment:

```python
class LLMService:
    async def complete(prompt: str) -> tuple[str, int, int]
    def estimate_tokens(text: str) -> int   # len(text) // 4
    def calculate_cost(input_tokens, output_tokens) -> float
```

---

### 7.2 `services/file_writer.py` β€” FileWriter (V4.3)

Single shared file I/O service. All agents use this exclusively β€” no agent calls `open()` directly.

```python
class FileWriter:
    def __init__(session_dir, session_id="", cache=None, rag=None)

    def read(path: str) -> str | None
    # 1. Check SharedCache (artifact:<session_id>:<path>)
    # 2. On miss: read disk, populate cache

    def write(path: str, content: str, mode: str = "overwrite") -> None
    # 1. Write to disk (creates parent dirs)
    # 2. Update SharedCache
    # 3. Call rag.index_artifact()
    # 4. If writing agent is "datafetcher": invalidate artifact:* keys for ticker

    def list(prefix: str = "") -> list[str]
    # Returns relative paths under session_dir matching prefix

    def exists(path: str) -> bool
```

**`_extract_ticker_from_path(path)`** β€” module-level helper: extracts ticker symbol from artifact paths like `quant/raw/AAPL_2026-03-26.json`.

---

### 7.3 `services/finnhub.py` β€” Finnhub Market Data

Rate-aware client. Free tier: 60 calls/minute.

```python
_BASE_URL = "https://finnhub.io/api/v1"
_PER_MINUTE_LIMIT = 60
_MIN_CALL_DELAY = 1.1   # seconds between calls
_CANDLE_DAYS = 90

class RateLimitExceeded(Exception): ...

class FinnhubService:
    async def get_quote(ticker: str) -> dict
    # Returns: c (price), h (high), l (low), o (open), pc (prev close), t (timestamp)

    async def fetch_ticker_data(ticker: str, session_dir: Path) -> dict
    # Fetches:
    #   - OHLCV daily candles (90 days) β†’ TIME_SERIES_DAILY_ADJUSTED
    #   - SMA-20, EMA-20, RSI-14, MACD(12/26/9) computed locally
    #   - Company news (last 30 days) β†’ NEWS_SENTIMENT
    #   - Earnings (last 8 quarters) β†’ EARNINGS
    # Outputs AV-compatible JSON

    def calls_remaining_today() -> int
    async def _call(endpoint: str, params: dict) -> dict
    def _fetch_ohlcv_yfinance(ticker: str) -> dict | None  # V4.4 FIX-5: returns None on any exception
    def _compute_sma(prices, period) -> list[float]
    def _compute_ema(prices, period) -> list[float]
    def _compute_rsi(prices, period=14) -> list[float]
    def _compute_macd(prices, fast=12, slow=26, signal=9) -> dict
    def _news_to_av(news: list) -> dict   # normalise to AV news format
    def _earnings_to_av(earnings: list) -> dict  # normalise to AV earnings format
```

> **V4.4 FIX-5:** `_fetch_ohlcv_yfinance` is now wrapped in `try/except`, returning `None` on any exception. `fetch_ticker_data()` checks for `None` and sets `has_ohlcv=False` in the returned tuple; DataFetcher uses `all_ohlcv_failed` to route to `@human` with `yfinance_alert: True`.

---

### 7.4 `services/alpha_vantage.py`

```python
_BASE_URL = "https://www.alphavantage.co/query"
_DAILY_LIMIT = 25
_PER_MINUTE_LIMIT = 5
_BATCH_DELAY = 15.0   # seconds between batches

class DailyCapExceeded(Exception): ...

class AlphaVantageService:
    async def fetch_ticker_data(ticker, session_dir) -> dict
    def calls_remaining_today() -> int
    async def _call(params: dict) -> dict
    def _reset_daily_if_needed() -> None
```

---

### 7.5 `services/rag_service.py` β€” RAG (V4.4)

```python
class RAGService:
    def __init__(project_root, model_name="all-MiniLM-L6-v2",
                 session_id: str = "")   # V4.4 FIX-1: session-scoped init
    # Embeddings stored at ~/.polyhedra/sessions/{session_id}/embeddings.json
    # (previously: shared literature/embeddings.json β€” caused cross-session leakage)

    def _load_model() -> SentenceTransformer
    def _load_index() -> dict   # deserialises JSON; returns {} if file absent
    def is_indexed() -> bool
    def index_papers(papers: list[dict]) -> None
    def query(query_text: str, top_k=5) -> list[dict]
    def index_artifact(path: str, content: str, session_id: str) -> None
    def query_artifacts(query_text: str, session_id: str, top_k=5) -> list[Chunk]
    def rebuild_artifact_index_from_disk(session_dir: Path, session_id: str) -> None
```

---

### 7.6 `services/semantic_scholar.py`

```python
BASE_URL = "https://api.semanticscholar.org/graph/v1"
MAX_RETRIES = 3
RETRY_DELAY = 1.0  # seconds

class SemanticScholarService:
    async def search(query, limit=20, fields=None) -> SemanticScholarResponse
    async def get_paper(paper_id: str) -> Paper
    async def generate_bibtex(paper: Paper) -> str
    async def query_similar_papers(query_text: str, limit=10) -> list[Paper]
    async def close() -> None
```

---

### 7.7 `services/citation_manager.py`

```python
class CitationManager:
    bib_path: Path
    def load() -> dict[str, str]   # key β†’ bibtex entry
    def save(entries: dict) -> None
    def add_entry(key: str, bibtex: str) -> None
    def get_all_keys() -> list[str]
    def get_all_entries() -> dict[str, str]
```

---

### 7.8 `services/literature_review_service.py`

```python
DEPTH_CONFIG = {
    "quick":    {"min": 400,  "max": 800,  "target": 600},
    "standard": {"min": 800,  "max": 1600, "target": 1200},
    "deep":     {"min": 1600, "max": 3200, "target": 2400},
}

class LiteratureReviewService:
    def generate(papers: list[Paper], depth: str = "standard") -> str
    def estimate_cost(papers: list[Paper], depth: str) -> float
    def _prepare_papers_summary(papers) -> str
    def _format_authors(authors) -> str
    def _build_prompt(papers_summary, depth) -> str
    def _extract_metadata(content: str) -> dict
```

---

## 8. Messaging (`messaging/`)

### 8.1 `messaging/slack.py` β€” SlackIntegration

**`_ROLE_DISPLAY`** β€” maps role keys to Slack display names with emoji:

```python
{
    "datafetcher":    "DataFetcher πŸ“Š",
    "trendanalyst":   "TrendAnalyst πŸ“ˆ",
    "sentimentanalyst": "SentimentAnalyst πŸ“°",
    "quantresearcher": "QuantResearcher πŸ”¬",
    "backtester":     "Backtester ⏱️",
    "riskanalyst":    "RiskAnalyst ⚠️",
    "quantstrategist": "QuantStrategist 🎯",
    "vizagent":       "VizAgent πŸ“‰",
    "portfoliomonitor": "PortfolioMonitor πŸ””",
    # ... research agents
}
```

**SlackIntegration:**

```python
class SlackIntegration:
    def __init__(signing_secret: str, bot_token: str)
    def mount_to_fastapi(app: FastAPI) -> None
    def _build_slack_app() -> AsyncApp
    async def _process_mention(body, say, client) -> None
    async def _init_from_mention(body, say, client) -> None
    # Slash commands:
    async def _cmd_init(body, ...) -> None
    async def _cmd_status(body, ...) -> None
    async def _cmd_approve(body, ...) -> None
    async def _cmd_reject(body, ...) -> None
    async def _cmd_role(body, ...) -> None
    async def _cmd_export(body, ...) -> None
```

**Session registration (V4.3, quant-only):**

Both `_init_from_mention` and `_cmd_init` register exactly these 9 quant agents:

```python
selected_roles = [
    "datafetcher", "trendanalyst", "sentimentanalyst",
    "quantresearcher", "backtester", "riskanalyst",
    "quantstrategist", "vizagent", "portfoliomonitor"
]
```

Research agents (Scout, Strategist, Critic, Scribe) are **not registered**.

**`_find_proposal_in_md(content: str, proposal_id: str) -> dict`** (V4.4 FIX-3) β€” replaces `_parse_proposal_block`; uses `parse_proposals_block()` from `routing.py` to extract validated proposal by `proposal_id`.

**`_monitor_loop()`** (V4.4 FIX-2) β€” uses `active_sessions_with_positions()` to filter only sessions with open positions before iterating; avoids unnecessary API calls for idle sessions.

> **Bug fixed:** `_SayClient.chat_postMessage` had duplicate `channel` kwarg β€” renamed positional param from `_channel` to `channel`.

---

## 9. CLI (`cli/`)

### 9.1 `cli/main.py`

Typer app β€” `poly` command family:

```
poly init [--goal TEXT] [--field TEXT]     # Start new research session
poly search QUERY [--limit INT]            # Invoke ScoutAgent directly
poly state [--session-id TEXT]             # Print ResearchState as markdown
poly resume [--session-id TEXT]            # Re-attach to existing session
poly export [--session-id TEXT]            # Export artifacts to zip
poly role take <role>                      # Human takes over a role
poly role release <role>                   # Reinstate agent for role
poly mcp [--host TEXT] [--port INT]        # Start MCP server
poly sessions                              # List all saved sessions
poly cache stats                           # SharedCache hit/miss stats (V4.3)
poly tokens [--session-id TEXT]            # Token usage log table (V4.3)
poly trace [--session-id TEXT] [--last N]  # Print last N trace entries (V4.4 STRUCT-3)
poly help                                  # Rich table of all commands (V4.4 STRUCT-4)
```

**Internal helpers:**

```python
_build_full_session(goal, field) -> Session
_latest_session_id() -> str | None
```

---

## 10. Agent Workflow Engine (`agent/`)

Standalone workflow runner β€” distinct from the multi-agent system. Used by the MCP server for structured tool-call sequences.

### 10.1 `agent/models.py`

```python
class StepStatus(Enum):
    pending | running | completed | failed | skipped

class IntentType(Enum):
    research_survey | paper_comparison | gap_analysis | citation_finding | unknown

@dataclass class Intent:
    type: IntentType
    topic: str
    parameters: dict
    confidence: float
    raw_command: str

@dataclass class WorkflowStep:
    name: str
    tool: str
    arguments: dict
    critical: bool
    timeout: int
    retry_count: int
    description: str

@dataclass class Workflow:
    name: str
    description: str
    steps: list[WorkflowStep]
    metadata: dict
    def validate() -> bool

@dataclass class WorkflowResult:
    success: bool
    results: dict
    errors: list[str]
    message: str
    elapsed_seconds: float
```

### 10.2 `agent/research_agent.py`

```python
class ResearchAgent:
    def __init__(tool_adapter, intent_parser, workflow_generator, config)
    async def execute_command(command: str) -> WorkflowResult
    async def execute_workflow(workflow: Workflow) -> WorkflowResult
    async def _execute_step(step: WorkflowStep, context: dict) -> dict
    def _resolve_arguments(args: dict, context: dict) -> dict
```

### 10.3 `agent/retry.py`

```python
@dataclass class RetryConfig:
    max_attempts: int = 3
    initial_delay: float = 1.0
    max_delay: float = 60.0
    exponential_base: float = 2.0
    jitter: bool = True

class CircuitBreaker:
    failure_threshold: int
    timeout: float
    def record_success() / record_failure() / can_attempt() / reset()

async def retry_with_backoff(fn, config: RetryConfig, circuit_breaker=None) -> Any
```

### 10.4 `agent/checkpoint.py`

```python
@dataclass class CheckpointConfig:
    cost_threshold: float = 0.50
    require_approval: bool = True
    auto_approve_below: float = 0.10
    timeout: int = 300  # seconds

@dataclass class Checkpoint:
    step_name: str
    operation: str
    estimated_cost: float
    rationale: str
    auto_approved: bool
    user_approved: bool

class CheckpointManager:
    def should_checkpoint(estimated_cost: float) -> bool
    def request_approval(checkpoint: Checkpoint) -> bool
    def get_checkpoint_history() -> list[Checkpoint]
    def clear_history() -> None
```

### 10.5 `agent/state.py`

```python
class StateManager:
    state_dir: Path
    def save_state(state: WorkflowState) -> None
    def load_state(workflow_id: str) -> WorkflowState | None
    def delete_state(workflow_id: str) -> None
    def list_workflows() -> list[str]
    def cleanup_old_states(days: int = 7) -> int
    def can_resume(workflow_id: str) -> bool
```

### 10.6 `agent/config.py`

```python
@dataclass class AgentConfig:
    max_retry_attempts: int = 3
    initial_retry_delay: float = 1.0
    max_retry_delay: float = 60.0
    exponential_base: float = 2.0
    retry_jitter: bool = True
    circuit_breaker_threshold: int = 5
    circuit_breaker_timeout: float = 60.0
    checkpoint_cost_threshold: float = 0.50
    checkpoint_auto_approve_below: float = 0.10
    checkpoint_timeout: int = 300
    checkpoint_enabled: bool = True
    state_dir: Path = Path("~/.polyhedra/state")
    state_cleanup_days: int = 7
    log_level: str = "INFO"

    @classmethod def from_env() -> AgentConfig
    @classmethod def from_file(path: Path) -> AgentConfig
    def to_dict() -> dict
    def save(path: Path) -> None
```

---

## 11. Schemas (`schemas/`)

Pydantic models for Semantic Scholar API responses:

```python
class Author(BaseModel):
    name: str
    author_id: str | None

class Paper(BaseModel):
    id: str
    title: str
    authors: list[Author]
    year: int | None
    venue: str | None
    abstract: str | None
    citation_count: int
    bibtex_key: str | None
    bibtex_entry: str | None
    url: str | None
    pdf_url: str | None
    fields_of_study: list[str]

class SemanticScholarResponse(BaseModel):
    total: int
    offset: int
    next_offset: int | None
    data: list[Paper]
```

---

## 12. MCP Server (`server.py`)

Entry point: `polyhedra` command. Exposes research tools to VS Code / Cursor via the **Model Context Protocol**.

```python
DEFAULT_PAPERS_PATH = "literature/papers.json"

def get_project_root() -> Path       # returns Path.cwd()
def _generate_bibtex(paper) -> str   # constructs BibTeX entry from paper metadata
def _format_authors_for_bibtex(authors) -> str
def get_services() -> dict           # lazy-initialises service singletons
def list_tools() -> list[Tool]       # declares all MCP tools
def main() -> None                   # starts MCP stdio server
```

**MCP Tools exposed:**

| Tool | Description |
|---|---|
| `search_papers` | Search Semantic Scholar |
| `get_paper` | Get paper by ID |
| `get_context` | Read project files |
| `query_similar_papers` | Semantic similarity search |
| `add_citation` | Add BibTeX to references.bib |
| `get_citations` | List all citations |
| `save_file` | Write to project files |
| `get_project_status` | Project overview |
| `index_papers` | Build/rebuild RAG index |
| `init_project` | Initialise project structure |

---

## 13. FastAPI App (`app.py`)

```python
def create_app() -> FastAPI:
    # Registers:
    #   GET  /health      β€” liveness probe β†’ {"status": "ok"}
    #   POST /slack/events β€” Bolt async handler
    # Initialises Slack Bolt only if SLACK_BOT_TOKEN + SLACK_SIGNING_SECRET present
    # HMAC request verification using signing_secret
```

---

## 14. Routing System

### LLM Routing Protocol

Every LLM-enabled quant agent appends `LLM_ROUTING_PROMPT` to its task prompt:

```
After completing your analysis, decide who should be next.
Available quant roles: datafetcher, trendanalyst, sentimentanalyst,
                       quantresearcher, backtester, riskanalyst, quantstrategist, human

Rules:
- Choose exactly ONE role (or null if complete).
- Base your choice on what the analysis needs, not a fixed sequence.
- If uncertain or blocked, choose human.
- You cannot choose yourself.

Respond with a JSON block at the very end of your output:
{"next": "<role>", "reason": "<one sentence why>"}
or if no further action needed:
{"next": null, "reason": "Work complete."}
```

`parse_llm_routing()` extracts the **last** `{"next": ..., "reason": ...}` JSON object, validates `next` against `QUANT_ROLES`, and returns `(next_role, reason, stripped_content)`.

### Cycle Guard (V4.3)

TrendAnalyst has a hard post-parse guard:

```python
if next_role == "datafetcher":
    next_role = "sentimentanalyst"  # always; log warning
```

### Coordinator Depth Control

- **Non-quant chain:** `_MAX_MENTION_DEPTH = 3` β†’ hard stop β†’ routes to `@human`
- **Quant chain:** separate depth counter, pauses (not hard-stops) at limit
- **`_ALT_AGENT_MAP`** β€” when an agent is blocked, Coordinator can skip forward to the next stage

---

## 15. Data Flow β€” Full Quant Chain

```
1. Human sends "@datafetcher fetch MSTR MSTR" in Slack

2. SlackIntegration._process_mention()
   β†’ builds Mention(mentioned_role="datafetcher", from_role="human", content="...")
   β†’ CoordinatorService.dispatch()

3. DataFetcherAgent.handle()
   β†’ resolves watchlist: ["MSTR"]
   β†’ calls FinnhubService.fetch_ticker_data("MSTR", session_dir)
   β†’ writes quant/raw/MSTR_2026-03-26.json
   β†’ writes quant/raw/MSTR_2026-03-26_summary.md
   β†’ checks: trend_analysis_2026-03-26.md exists? No
   β†’ returns AgentResponse(mentions=["trendanalyst"])

4. CoordinatorService receives response
   β†’ publishes AgentCompletedEvent(next_role="trendanalyst", depth=1)
   β†’ dispatches Mention(mentioned_role="trendanalyst", from_role="datafetcher")

5. TrendAnalystAgent.handle()
   β†’ reads quant/raw/MSTR_2026-03-26_summary.md
   β†’ calls LLMService.complete(prompt)
   β†’ parse_llm_routing() β†’ next_role from LLM
   β†’ cycle guard: if next_role=="datafetcher" β†’ override to "sentimentanalyst"
   β†’ writes quant/trend_analysis_2026-03-26.md
   β†’ returns AgentResponse(mentions=["sentimentanalyst"])

6. SentimentAnalystAgent.handle() β†’ ... β†’ mentions=["quantresearcher"]

7. QuantResearcherAgent.handle() β†’ ... β†’ mentions=["backtester"]

8. BacktesterAgent.handle() β†’ ... β†’ mentions=["riskanalyst"]

9. RiskAnalystAgent.handle() β†’ ... β†’ mentions=["quantstrategist"]

10. QuantStrategistAgent.handle()
    β†’ synthesises all upstream artifacts
    β†’ produces ≀3 trade proposals
    β†’ always returns mentions=["human"]
    β†’ writes quant/trade_proposals_2026-03-26.md

11. CoordinatorService posts trade proposals to Slack with approval templates
    β†’ Human reviews and responds with /approve <proposal_id>

12. (Async, scheduled) PortfolioMonitorAgent checks open positions every 30 min
    β†’ publishes PortfolioAlertEvent on threshold breach
    β†’ CoordinatorService posts alert to Slack
```

---

## 16. Environment Variables

| Variable | Used by | Default | Description |
|---|---|---|---|
| `FINNHUB_API_KEY` | FinnhubService, PortfolioMonitor | β€” | Finnhub API key |
| `ALPHAVANTAGE_API_KEY` | AlphaVantageService | β€” | Alpha Vantage key |
| `ANTHROPIC_API_KEY` | AnthropicAdapter | β€” | Claude API key |
| `GEMINI_API_KEY` | GeminiAdapter | β€” | Gemini API key |
| `SLACK_BOT_TOKEN` | SlackIntegration | β€” | `xoxb-...` bot token |
| `SLACK_SIGNING_SECRET` | SlackIntegration, app.py | β€” | Request HMAC verification |
| `POLYHEDRA_QUANT_WATCHLIST` | DataFetcherAgent | `""` | Comma-separated tickers e.g. `MSTR,BTBT,MARA` |
| `POLYHEDRA_VALID_TICKERS` | DataFetcherAgent | `""` | Allow-list for ticker validation; blank = regex heuristics (V4.4) |
| `POLYHEDRA_ENABLE_RESEARCH` | `agents/__init__.py` | `0` | Set to `1` to enable Scout/Strategist/Critic/Scribe in Slack sessions (V4.4) |
| `POLYHEDRA_MONITOR_INTERVAL` | PortfolioMonitor | `30` | Monitor run interval (minutes) |
| `POLYHEDRA_MARKET_TZ` | PortfolioMonitor | `America/New_York` | Market timezone |
| `POLYHEDRA_ALERT_MOVE_PCT` | PortfolioMonitor | `2.0` | Position move alert threshold (%) |
| `LLM_PROVIDER` | LLMService | `anthropic` | Active LLM adapter (`anthropic`/`gemini`) |
| `LLM_MODEL` | LLMService | provider default | Model name override |

---

## 17. Key Design Patterns

### Lazy LLM Initialisation (V4.3)

All 11 agents use a property-based lazy loader β€” `LLMService()` is never called at `__init__` time:

```python
def __init__(self, llm_service: LLMService | None = None) -> None:
    super().__init__()
    self._llm_service = llm_service
    self.__llm: LLMService | None = None

@property
def _llm(self) -> LLMService:
    if self.__llm is None:
        self.__llm = self._llm_service or LLMService()
    return self.__llm
```

### Agent ABC Pattern

All agents inherit `Agent(ABC)`. The Coordinator discovers agents by calling `can_handle(mention)` on every registered agent in the session registry until one returns `True`.

### EventBus Transaction (V4.3)

The Coordinator subscribes to 4 event types at session creation:
- `AgentCompletedEvent` β†’ depth-check, state merge, chain continuation
- `AgentBlockedEvent` β†’ skip-forward via `_ALT_AGENT_MAP` or escalate to human
- `HumanInputRequiredEvent` β†’ post templates to Slack/CLI
- `PortfolioAlertEvent` β†’ post alert to Slack

### Artifact Path Convention

All quant artifacts follow `quant/<type>_<date>.md`. The date is always `date.today().isoformat()` at run time. Same-day re-runs overwrite (`mode="overwrite"`).

### Cache-Aside with Write-Through (V4.3)

```
read:   SharedCache.get(key) β†’ hit: return | miss: disk.read + cache.set
write:  disk.write + cache.set + rag.index_artifact
```

---

## 18. Known Bugs & Fixes Applied

### Fix 1 β€” `cache.py` SyntaxError (V4.3 hotfix 1)

**Problem:** `_SENTINEL := object()` (walrus operator) used as default parameter in `set()`.  
**Fix:** Move `_SENTINEL = object()` to module level.

---

### Fix 2 β€” `slack.py` duplicate `channel` kwarg (V4.3 hotfix 2)

**Problem:** `_SayClient.chat_postMessage(self, _channel, ...)` did not capture `channel=` keyword argument from callers.  
**Fix:** Rename parameter from `_channel` to `channel`.

---

### Fix 3 β€” 11Γ— LLM init at startup (V4.3 hotfix 3)

**Problem:** All 11 agents called `LLMService()` eagerly in `__init__`, causing 11 simultaneous API client initialisations on session creation.  
**Fix:** Lazy `_llm` property in all agents (see Β§17).

---

### Fix 4 β€” TrendAnalyst ↔ DataFetcher infinite loop (V4.3 hotfix 4)

**Problem (two-sided):**
- DataFetcher always hard-coded `next_mentions = ["trendanalyst"]` after any successful fetch, even when DataFetcher was called mid-chain
- TrendAnalyst LLM prompt instructed the model to route to `@datafetcher` on any data gap; MSTR missing earnings always triggered this

**Fixes applied (`cec724c`):**

1. **`trendanalyst.py` β€” cycle guard:**  
   After `parse_llm_routing`, any `datafetcher` route is overridden to `sentimentanalyst`; warning logged.

2. **`trendanalyst.py` β€” prompt constraint:**  
   Added rule: if summaries are present (DataFetcher already ran), treat remaining gaps as unavailable data and proceed to `@sentimentanalyst` β€” never route back to `@datafetcher`.

3. **`datafetcher.py` β€” smart mid-chain routing:**  
   Checks whether `quant/trend_analysis_<today>.md` exists. If it does, DataFetcher was called mid-chain β†’ routes to `sentimentanalyst`. If not, fresh session β†’ routes to `trendanalyst`.

---

## V4.4 Fixes & Structural Changes

### FIX-1 β€” RAG session isolation (V4.4)

**Problem:** `RAGService` used a single `literature/embeddings.json` shared across all sessions. Embeddings from session A leaked into session B context.

**Fix:** `RAGService.__init__` now accepts `session_id`; embeddings stored at `~/.polyhedra/sessions/{session_id}/embeddings.json`. JSON serialisation used throughout; `{}` returned if file is absent.

---

### FIX-2 β€” PortfolioMonitor session registry (V4.4)

**Problem:** `_monitor_loop()` iterated all sessions even those with no open positions, wasting API quota.

**Fix:** `core/session.py` gains `active_sessions_with_positions()`, `_registry_path()`, `_save_registry()`. `_monitor_loop()` filters by this set.

---

### FIX-3 β€” Structured proposal output (V4.4)

**Problem:** `_parse_proposal_block()` in `slack.py` parsed Markdown heuristically from free text; fragile against formatting variation.

**Fix:** QuantStrategist's prompt now requires a fenced ` ```proposals ``` ` JSON block. `parse_proposals_block()` in `routing.py` extracts + validates it. `slack.py._find_proposal_in_md()` uses this function.

---

### FIX-4 β€” Version 4.4.0 (V4.4)

Version strings updated in `__init__.py`, `pyproject.toml`, and `app.py` health endpoint.

---

### FIX-5 β€” yfinance fallback β†’ @human routing (V4.4)

**Problem:** `_fetch_ohlcv_yfinance` raised unhandled exceptions when yfinance returned errors, causing DataFetcher to crash silently.

**Fix:** Wrapped in `try/except` returning `None`. `fetch_ticker_data()` propagates `has_ohlcv=False`. DataFetcher tracks `all_ohlcv_failed`; when true, routes to `@human` with `state_patch={"yfinance_alert": True}`.

---

### FIX-6 β€” Module docstrings (V4.4)

Added docstrings to `agent/__init__.py` and `agents/__init__.py` clarifying the two execution models.

---

### FIX-7 β€” `POLYHEDRA_ENABLE_RESEARCH` flag (V4.4)

**Problem:** Research agents (Scout etc.) were silently excluded from Slack sessions with no opt-in mechanism.

**Fix:** `agents/__init__.py` gates research agent imports behind `POLYHEDRA_ENABLE_RESEARCH=1`.

---

### FIX-8 β€” `_is_valid_ticker()` replaces `_SKIP_TOKENS` (V4.4)

**Problem:** Hardcoded frozenset of 70+ stop-words was brittle and required code changes to extend.

**Fix:** `_is_valid_ticker(token)` checks `POLYHEDRA_VALID_TICKERS` env var allow-list first; falls back to regex heuristics (uppercase, 1–5 chars, not in common English words).

---

### STRUCT-1 β€” CoordinatorService decomposed (V4.4)

`coordinator.py` was ~700 lines. Four responsibilities extracted into dedicated `core/` modules:
- `AgentRouter` (`core/agent_router.py`) β€” depth tracking + routing constants
- `TemplateBuilder` (`core/template_builder.py`) β€” input templates + `COMMAND_REGISTRY`
- `StatePatcher` (`core/state_patcher.py`) β€” `ResearchState` patch application
- `CostGate` (`core/cost_gate.py`) β€” approval threshold

---

### STRUCT-2 β€” Typed output models (V4.4)

`agents/quant/outputs.py` introduces 7 `BaseModel` subclasses. `AgentResponse.output: BaseModel | None` added; `metadata` deprecated.

---

### STRUCT-3 β€” TraceLogger + `/poly trace` (V4.4)

`core/trace_logger.py` writes per-run entries to `trace.jsonl`. Coordinator injects `TraceLogger` into each agent. `/poly trace` Slack command and `poly trace` CLI both read the last N entries.

---

### STRUCT-4 β€” COMMAND_REGISTRY + help commands (V4.4)

`COMMAND_REGISTRY` (25 entries) in `template_builder.py`. `render_help_slack()` and `render_help_cli()` render it appropriately. Exposed via `/poly help` (Slack) and `poly help` (CLI).