File size: 207,124 Bytes
31e282f 039a22e 31e282f 547daee 8e010d8 1e36958 c80079e 02ffd4e 51465b0 6578111 9386626 070199d 6d8611d fa057e6 dba47b0 355ed3b 029acd5 018b133 9af7403 7414b6b 018b133 f876bac 018b133 66048d7 2e3fb63 9214ec3 23a5c3d 0527f8b 31e282f 018b133 31e282f 738c2a1 7414b6b 2e3fb63 f876bac 738c2a1 547daee 31e282f 738c2a1 31e282f 039a22e 31e282f 8e010d8 66048d7 31e282f 8e010d8 66048d7 31e282f 738c2a1 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 51465b0 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 070199d 31e282f 8e010d8 31e282f 018b133 31e282f 8e010d8 018b133 31e282f 018b133 31e282f 8e010d8 018b133 31e282f 018b133 31e282f 8e010d8 23a5c3d 8e010d8 31e282f 23a5c3d 31e282f 039a22e 31e282f 039a22e 31e282f 738c2a1 31e282f 8e010d8 23a5c3d 31e282f 039a22e 31e282f 23a5c3d 31e282f 8e010d8 31e282f 039a22e 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 6578111 31e282f 738c2a1 31e282f 8e010d8 66048d7 31e282f 66048d7 31e282f 738c2a1 31e282f 8e010d8 31e282f 8e010d8 31e282f 738c2a1 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 547daee 8e010d8 547daee 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f ba5bd49 31e282f 8e010d8 31e282f 8e010d8 31e282f 2e3fb63 31e282f 8e010d8 31e282f dba47b0 31e282f 738c2a1 31e282f ba5bd49 31e282f 738c2a1 31e282f 738c2a1 31e282f 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f 738c2a1 018b133 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 029acd5 0280109 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f b2e363c 8e010d8 b2e363c 8e010d8 b2e363c 31e282f 6b93046 8e010d8 6b93046 8e010d8 6b93046 31e282f 8e010d8 fa057e6 8e010d8 fa057e6 31e282f fa057e6 31e282f 738c2a1 31e282f 8e010d8 fa057e6 8e010d8 fa057e6 31e282f fa057e6 31e282f fa057e6 31e282f 8e010d8 31e282f 8e010d8 31e282f 738c2a1 31e282f 738c2a1 31e282f 8e010d8 31e282f d9c36b3 738c2a1 d9c36b3 738c2a1 d9c36b3 8e010d8 d9c36b3 8e010d8 d9c36b3 31e282f 738c2a1 31e282f 8e010d8 31e282f 8e010d8 738c2a1 31e282f 738c2a1 8e010d8 c80079e 8e010d8 c80079e 8e010d8 c80079e 31e282f c80079e 31e282f b102502 31e282f b102502 547daee 31e282f 8e010d8 738c2a1 31e282f 8e010d8 31e282f b102502 31e282f 8e010d8 31e282f 8e010d8 31e282f 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f 8e010d8 31e282f b102502 8e010d8 b102502 8e010d8 b102502 31e282f 2e3fb63 31e282f 738c2a1 31e282f 2e3fb63 31e282f 2e3fb63 31e282f 8e010d8 31e282f 7414b6b 31e282f 8e010d8 31e282f 039a22e 7414b6b 039a22e 8e010d8 039a22e 8e010d8 039a22e 7414b6b 31e282f 8e010d8 738c2a1 31e282f 8e010d8 31e282f 547daee 8e010d8 31e282f e2b0863 9fac7bb fabc531 3edcbe2 fabc531 0ba26a1 039a22e 8e010d8 738c2a1 039a22e 8e010d8 039a22e 8e010d8 039a22e 9214ec3 8e010d8 9214ec3 039a22e 8e010d8 6d8611d 8e010d8 6d8611d 039a22e 6d8611d 8e010d8 039a22e 31e282f 738c2a1 31e282f 8e010d8 738c2a1 31e282f 8e010d8 31e282f db0b7e6 8e010d8 31e282f 52381ac 738c2a1 31e282f 8e010d8 31e282f 52381ac 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f aa3c6fc 8e010d8 aa3c6fc 8e010d8 aa3c6fc 018b133 8e010d8 018b133 8e010d8 018b133 31e282f 8e010d8 31e282f 738c2a1 31e282f 8e010d8 738c2a1 31e282f 8e010d8 31e282f f8e624f 738c2a1 31e282f 8e010d8 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f 8e010d8 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f eed69b5 8e010d8 31e282f 8e010d8 738c2a1 31e282f 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f 8e010d8 31e282f 8e010d8 31e282f 018b133 31e282f 8e010d8 31e282f 8e010d8 31e282f 738c2a1 039a22e 31e282f 738c2a1 039a22e 31e282f 039a22e 31e282f 738c2a1 31e282f 8e010d8 31e282f 039a22e 31e282f 738c2a1 31e282f 8e010d8 31e282f 92f06d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 2e3fb63 31e282f 2e3fb63 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 355ed3b 8e010d8 355ed3b 31e282f 8e010d8 1b5f4a6 8e010d8 1b5f4a6 31e282f 1b5f4a6 31e282f 018b133 738c2a1 018b133 8e010d8 018b133 8e010d8 92f06d8 8e010d8 018b133 52381ac 8e010d8 52381ac 244b49f 0527f8b 52381ac 738c2a1 52381ac 8e010d8 52381ac 738c2a1 52381ac 738c2a1 52381ac 8e010d8 52381ac 92f06d8 31e282f 8e010d8 31e282f 8276d45 31e282f 8e010d8 31e282f 8e010d8 31e282f 738c2a1 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 9386626 8e010d8 9386626 31e282f f2a2475 8e010d8 9386626 31e282f b102502 738c2a1 b102502 8e010d8 b102502 31e282f 547daee 31e282f 8e010d8 738c2a1 31e282f 738c2a1 31e282f 8e010d8 31e282f 8e010d8 738c2a1 31e282f 8e010d8 738c2a1 31e282f 8e010d8 31e282f 2e3fb63 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 f876bac 31e282f f876bac 31e282f f876bac 31e282f 8e010d8 31e282f 52381ac f876bac 52381ac 8e010d8 52381ac f876bac 52381ac f876bac 52381ac 8e010d8 52381ac f876bac 8e010d8 52381ac f876bac 52381ac 8e010d8 52381ac 31e282f 8e010d8 31e282f b102502 31e282f 52381ac 547daee 52381ac 8e010d8 738c2a1 52381ac 31e282f 52381ac 31e282f 738c2a1 31e282f 8e010d8 31e282f f2a2475 31e282f 52381ac 31e282f 738c2a1 31e282f 8e010d8 31e282f 52381ac 738c2a1 52381ac 8e010d8 52381ac 547daee 52381ac 738c2a1 52381ac 8e010d8 52381ac 31e282f 547daee 8e010d8 547daee 31e282f 52381ac 31e282f 52381ac 738c2a1 31e282f 8e010d8 31e282f 8e010d8 31e282f f2a2475 31e282f b102502 31e282f f2a2475 31e282f f2a2475 31e282f 738c2a1 31e282f 8e010d8 31e282f 1e36958 31e282f 8e010d8 31e282f 02ffd4e 31e282f 8e010d8 738c2a1 31e282f 8e010d8 018b133 31e282f 018b133 31e282f 738c2a1 31e282f 8e010d8 31e282f 9af7403 31e282f 738c2a1 31e282f 8e010d8 31e282f b102502 31e282f 738c2a1 31e282f 7414b6b 31e282f 8e010d8 31e282f 738c2a1 31e282f 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f 738c2a1 31e282f 8e010d8 31e282f 738c2a1 31e282f 738c2a1 7414b6b 31e282f 8e010d8 31e282f 018b133 31e282f 738c2a1 7414b6b 8e010d8 31e282f 018b133 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f 8e010d8 31e282f | 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 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 | """Tests for ctx_monitor — dashboard aggregation and HTML rendering."""
from __future__ import annotations
import http.client
import hashlib
import gzip
import json
import os
import sqlite3
import tarfile
import threading
import time
import urllib.error
import urllib.request
import zlib
from pathlib import Path
import pytest
import ctx_init as ci
from ctx import dashboard_entities
from ctx import dashboard_docs
from ctx.monitor import testing as mt
from ctx.monitor.pages import config as config_page
from ctx.monitor.pages import graph as graph_page
from ctx.monitor.pages import harness as harness_page
from ctx.monitor.pages import home as home_page
from ctx.monitor.pages import loaded as loaded_page
from ctx.monitor.pages import manage as manage_page
from ctx.monitor.pages import skills as skills_page
from ctx.monitor.pages import skillspector as skillspector_page
from ctx.monitor.pages import wiki as wiki_page
from ctx.monitor.api import mutations as mutations_api
from ctx.monitor.api import readonly as readonly_api
from ctx.monitor import routes as monitor_routes
from ctx.monitor import cli as monitor_cli
from ctx.monitor.services import config as config_service
from ctx.monitor.services import graph as graph_service
from ctx.monitor.services import harness as harness_service
from ctx.monitor.services import kpi as kpi_service
from ctx.monitor.services import manifest as manifest_service
from ctx.monitor.services import runtime as runtime_service
from ctx.monitor.services import sidecars as sidecar_service
from ctx.monitor.services import skillspector as skillspector_service
from ctx.monitor.services import status as status_service
from ctx.monitor.services import wiki as wiki_service
from ctx.core.wiki import wiki_queue
@pytest.fixture
def fake_claude(tmp_path: Path, monkeypatch) -> Path:
"""Point monitor compatibility helpers at a throwaway ~/.claude tree."""
claude = tmp_path / ".claude"
(claude / "skill-quality").mkdir(parents=True)
monkeypatch.setattr(mt, "claude_dir", lambda: claude)
monkeypatch.setattr(mt, "dashboard_graph_index_archives", lambda: [])
graph_service.reset_caches()
sidecar_service.reset_caches()
kpi_service.reset_cache()
monkeypatch.setattr(mt, "WIKI_RENDER_CACHE_KEY", None)
monkeypatch.setattr(mt, "WIKI_RENDER_CACHE_VALUE", None)
dashboard_docs.reset_docs_render_cache()
return claude
def _write_audit(claude: Path, records: list[dict]) -> None:
path = claude / "ctx-audit.jsonl"
path.write_text(
"\n".join(json.dumps(r) for r in records) + "\n",
encoding="utf-8",
)
def _write_events(claude: Path, records: list[dict]) -> None:
path = claude / "skill-events.jsonl"
path.write_text(
"\n".join(json.dumps(r) for r in records) + "\n",
encoding="utf-8",
)
def _write_runtime_events(path: Path, records: list[dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
"\n".join(json.dumps(r) for r in records) + "\n",
encoding="utf-8",
)
def _write_sidecar(claude: Path, slug: str, body: dict) -> None:
(claude / "skill-quality" / f"{slug}.json").write_text(
json.dumps(body), encoding="utf-8",
)
def test_monitor_testing_facade_rejects_private_helper_names() -> None:
with pytest.raises(AttributeError):
getattr(mt, "_render_graph")
with pytest.raises(AttributeError):
setattr(mt, "_claude_dir", lambda: None)
def _write_mcp_sidecar(claude: Path, slug: str, body: dict) -> None:
mcp_dir = claude / "skill-quality" / "mcp"
mcp_dir.mkdir(parents=True, exist_ok=True)
(mcp_dir / f"{slug}.json").write_text(json.dumps(body), encoding="utf-8")
def _write_graph_manifest(claude: Path, export_id: str) -> None:
graph_dir = claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True, exist_ok=True)
(graph_dir / "graph-export-manifest.json").write_text(
json.dumps({"version": 1, "export_id": export_id}),
encoding="utf-8",
)
def _write_skillspector_audit(claude: Path, records: list[dict]) -> Path:
path = claude / "skill-wiki" / "security" / "skillspector-audit.jsonl.gz"
path.parent.mkdir(parents=True, exist_ok=True)
with gzip.open(path, "wt", encoding="utf-8", newline="\n") as f:
for record in records:
f.write(json.dumps(record, sort_keys=True))
f.write("\n")
return path
def test_read_jsonl_skips_non_object_lines(tmp_path: Path) -> None:
path = tmp_path / "events.jsonl"
path.write_text(
"\n".join([
json.dumps({"event": "ok"}),
json.dumps(["not", "an", "object"]),
"not-json",
json.dumps("scalar"),
]),
encoding="utf-8",
)
assert mt.read_jsonl(path) == [{"event": "ok"}]
assert runtime_service.read_jsonl(path) == [{"event": "ok"}]
def test_read_jsonl_limit_keeps_tail_without_full_slice(tmp_path: Path) -> None:
path = tmp_path / "events.jsonl"
path.write_text(
"\n".join(json.dumps({"i": i}) for i in range(5)),
encoding="utf-8",
)
assert mt.read_jsonl(path, limit=2) == [{"i": 3}, {"i": 4}]
assert runtime_service.read_jsonl(path, limit=2) == [{"i": 3}, {"i": 4}]
def _post_json(port: int, path: str, body: dict, token: str | None = None) -> tuple[int, dict]:
headers = {"Content-Type": "application/json"}
if token is not None:
headers["X-CTX-Monitor-Token"] = token
request = urllib.request.Request(
f"http://127.0.0.1:{port}{path}",
data=json.dumps(body).encode("utf-8"),
headers=headers,
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=5) as response:
return response.status, json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
return exc.code, json.loads(exc.read().decode("utf-8"))
def _get_json(port: int, path: str) -> tuple[int, dict]:
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=5) as response:
return response.status, json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
return exc.code, json.loads(exc.read().decode("utf-8"))
def _get_raw(
port: int,
path: str,
*,
headers: dict[str, str],
) -> tuple[int, dict]:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
try:
conn.putrequest("GET", path, skip_host=True)
for key, value in headers.items():
conn.putheader(key, value)
conn.endheaders()
response = conn.getresponse()
payload = json.loads(response.read().decode("utf-8"))
return response.status, payload
finally:
conn.close()
def _post_raw(
port: int,
path: str,
*,
headers: dict[str, str],
body: bytes = b"",
) -> tuple[int, dict]:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
try:
conn.putrequest("POST", path, skip_host=True)
if "Host" not in headers:
conn.putheader("Host", f"127.0.0.1:{port}")
for key, value in headers.items():
conn.putheader(key, value)
conn.endheaders()
if body:
conn.send(body)
response = conn.getresponse()
payload = json.loads(response.read().decode("utf-8"))
return response.status, payload
finally:
conn.close()
def _serve_monitor(
monkeypatch: pytest.MonkeyPatch,
token: str = "test-token",
host: str = "127.0.0.1",
):
monkeypatch.setattr(mt, "MONITOR_TOKEN", token)
server = mt.make_monitor_server(host, 0)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return server, thread, server.server_port
def test_summarize_sessions_merges_audit_and_events(fake_claude: Path) -> None:
_write_audit(fake_claude, [
{"ts": "2026-04-19T10:00:00Z", "event": "skill.loaded",
"subject_type": "skill", "subject": "python-patterns",
"actor": "hook", "session_id": "S1"},
{"ts": "2026-04-19T10:05:00Z", "event": "skill.score_updated",
"subject_type": "skill", "subject": "python-patterns",
"actor": "hook", "session_id": "S1"},
{"ts": "2026-04-19T10:10:00Z", "event": "agent.loaded",
"subject_type": "agent", "subject": "code-reviewer",
"actor": "hook", "session_id": "S2"},
])
_write_events(fake_claude, [
{"timestamp": "2026-04-19T10:01:00Z", "event": "load",
"skill": "fastapi-pro", "session_id": "S1"},
{"timestamp": "2026-04-19T10:02:00Z", "event": "unload",
"skill": "fastapi-pro", "session_id": "S1"},
])
sessions = mt.summarize_sessions()
by_id = {s["session_id"]: s for s in sessions}
assert "S1" in by_id
assert "S2" in by_id
assert "python-patterns" in by_id["S1"]["skills_loaded"]
assert "fastapi-pro" in by_id["S1"]["skills_loaded"]
assert "fastapi-pro" in by_id["S1"]["skills_unloaded"]
assert by_id["S1"]["score_updates"] == 1
assert "code-reviewer" in by_id["S2"]["agents_loaded"]
def test_grade_distribution(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "a", {"slug": "a", "grade": "A", "raw_score": 0.9})
_write_sidecar(fake_claude, "b1", {"slug": "b1", "grade": "B", "raw_score": 0.7})
_write_sidecar(fake_claude, "b2", {"slug": "b2", "grade": "B", "raw_score": 0.6})
_write_sidecar(fake_claude, "f", {"slug": "f", "grade": "F", "raw_score": 0.1})
_write_mcp_sidecar(fake_claude, "mcp-one", {
"slug": "mcp-one", "subject_type": "mcp-server",
"grade": "C", "raw_score": 0.5,
})
dist = mt.grade_distribution()
assert dist["A"] == 1
assert dist["B"] == 2
assert dist["C"] == 1
assert dist["F"] == 1
def test_grade_distribution_skips_dotfiles_and_lifecycle(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "real", {"slug": "real", "grade": "C", "raw_score": 0.4})
(fake_claude / "skill-quality" / ".hook-state.json").write_text("{}",
encoding="utf-8")
(fake_claude / "skill-quality" / "real.lifecycle.json").write_text("{}",
encoding="utf-8")
dist = mt.grade_distribution()
assert sum(dist.values()) == 1 # only "real.json"
def test_session_detail_filters_by_session_id(fake_claude: Path) -> None:
_write_audit(fake_claude, [
{"ts": "t1", "event": "skill.loaded",
"subject_type": "skill", "subject": "x",
"actor": "hook", "session_id": "A"},
{"ts": "t2", "event": "skill.loaded",
"subject_type": "skill", "subject": "y",
"actor": "hook", "session_id": "B"},
])
_write_events(fake_claude, [
{"timestamp": "t3", "event": "load", "skill": "z", "session_id": "A"},
])
detail = mt.session_detail("A")
assert detail["session_id"] == "A"
assert len(detail["audit_entries"]) == 1
assert detail["audit_entries"][0]["subject"] == "x"
assert len(detail["load_events"]) == 1
assert detail["load_events"][0]["skill"] == "z"
def test_render_home_has_grade_pills(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "s1", {"slug": "s1", "grade": "A", "raw_score": 0.9})
html = mt.render_home()
assert "ctx monitor" in html
assert "grade-A" in html
assert "/sessions" in html
def test_home_page_module_renders_stats_and_recent_activity() -> None:
html = home_page.render_home(
manifest={"load": [{"skill": "reviewer"}]},
sessions=[{
"session_id": "sess-1234567890",
"last_seen": "2026-06-21T00:00:00Z",
"skills_loaded": ["python"],
"skills_unloaded": [],
"agents_loaded": ["reviewer"],
"score_updates": 2,
}],
wiki_stats={
"skills": 1000,
"agents": 2,
"mcps": 3,
"harnesses": 4,
"total": 1009,
"split_known": True,
},
graph_stats={"nodes": 1009, "edges": 2000},
runtime_summary={
"validations_total": 5,
"validation_failures": 1,
"open_escalations_total": 0,
},
audit_lines=12,
recent_audit=[{"ts": "2026-06-21T01:02:03Z", "event": "skill.loaded", "subject": "python"}],
layout=lambda _title, body: body,
format_count=lambda value: f"{value:,}",
)
assert "ctx monitor" in html
assert "1,009" in html
assert "1,000 skills" in html
assert "sess-1234567890" in html
assert "skill.loaded" in html
assert "home-sidecar-count" in html
def test_render_session_detail_escapes_html(fake_claude: Path) -> None:
hostile = "evil</script><script>alert(1)</script>"
_write_audit(fake_claude, [
{"ts": "t", "event": "skill.loaded",
"subject_type": "skill", "subject": hostile,
"actor": "hook", "session_id": "sess"},
])
html = mt.render_session_detail("sess")
assert "<script>alert(1)</script>" not in html
# HTML-escaped form must appear
assert "</script>" in html or "<script>" in html
def test_render_skills_sorts_grade_then_score(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "low", {"slug": "low", "grade": "D", "raw_score": 0.2})
_write_sidecar(fake_claude, "mid", {"slug": "mid", "grade": "B", "raw_score": 0.6})
_write_sidecar(fake_claude, "top", {"slug": "top", "grade": "A", "raw_score": 0.9})
html = mt.render_skills()
# 'top' should appear before 'mid' before 'low' in the grade-sorted output
idx_top = html.index("top</code>")
idx_mid = html.index("mid</code>")
idx_low = html.index("low</code>")
assert idx_top < idx_mid < idx_low
def test_render_skills_includes_harness_filter_and_typed_links(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "langgraph-harness", {
"slug": "langgraph",
"subject_type": "harness",
"grade": "A",
"raw_score": 0.95,
})
html = mt.render_skills()
assert "class='type-filter'" in html
assert "value='harness'" in html
assert "/skill/langgraph?type=harness" in html
assert "/wiki/langgraph?type=harness" in html
assert "/graph?slug=langgraph&type=harness" in html
def test_skills_page_module_renders_filters_cards_and_pagination() -> None:
html_out = skills_page.render_skills(
payload={
"items": [{
"slug": "reviewer",
"grade": "A",
"raw_score": 0.91,
"subject_type": "agent",
"hard_floor": "",
}],
"page": 2,
"limit": 50,
"total": 75,
"catalog_total": 100,
"filtered": True,
"has_prev": True,
"has_next": False,
"pages": 2,
"types": ["agent"],
"grades": ["A"],
"hide_floor": True,
"q": "review",
},
query_params={"q": "review", "type": "agent", "grade": "A", "hide_floor": "1"},
entity_types=("skill", "agent", "mcp-server", "harness"),
layout=lambda _title, body: body,
sidecar_entity_type=lambda sidecar: str(sidecar.get("subject_type", "skill")),
)
assert "<h1>Quality sidecars</h1>" in html_out
assert "Showing 51-75 of 75 matching sidecars" in html_out
assert "class='skill-card'" in html_out
assert "data-type='agent'" in html_out
assert "class='type-filter'" in html_out
assert "class='grade-filter'" in html_out
assert "name='hide_floor' value='1' checked" in html_out
assert "/skill/reviewer?type=agent" in html_out
def test_read_manifest_empty_when_missing(fake_claude: Path) -> None:
m = mt.read_manifest()
assert m == {"load": [], "unload": [], "warnings": []}
assert manifest_service.read_manifest(
fake_claude / "skill-manifest.json",
fake_claude,
) == m
def test_read_manifest_reads_real_manifest(fake_claude: Path) -> None:
(fake_claude / "skill-manifest.json").write_text(
json.dumps({"load": [{"skill": "a"}], "unload": [{"skill": "b"}],
"warnings": []}),
encoding="utf-8",
)
m = mt.read_manifest()
direct = manifest_service.read_manifest(
fake_claude / "skill-manifest.json",
fake_claude,
)
assert [e["skill"] for e in m["load"]] == ["a"]
assert [e["skill"] for e in m["unload"]] == ["b"]
assert direct == m
def test_read_manifest_includes_installed_harness_records(fake_claude: Path) -> None:
harness_dir = fake_claude / "harness-installs"
harness_dir.mkdir()
(harness_dir / "langgraph.json").write_text(
json.dumps({
"slug": "langgraph",
"status": "installed",
"repo_url": "https://github.com/langchain-ai/langgraph",
"target": str(fake_claude / "harnesses" / "langgraph"),
"installed_at": "2026-05-01T00:00:00Z",
}),
encoding="utf-8",
)
m = mt.read_manifest()
direct = manifest_service.read_manifest(
fake_claude / "skill-manifest.json",
fake_claude,
)
assert m["load"] == [{
"skill": "langgraph",
"entity_type": "harness",
"source": "ctx-harness-install",
"command": str(fake_claude / "harnesses" / "langgraph"),
"installed_at": "2026-05-01T00:00:00Z",
"status": "installed",
}]
assert direct == m
def test_queue_status_summarizes_worker_jobs(fake_claude: Path) -> None:
wiki = fake_claude / "skill-wiki"
db_path = wiki_queue.queue_db_path(wiki)
first = wiki_queue.enqueue_maintenance_job(
wiki,
kind=wiki_queue.GRAPH_EXPORT_JOB,
payload={"graph_only": True},
source="test",
now=10.0,
)
second = wiki_queue.enqueue_maintenance_job(
wiki,
kind=wiki_queue.TAR_REFRESH_JOB,
payload={"catalog": "graph/skills-sh-catalog.json.gz"},
source="test",
now=11.0,
)
third = wiki_queue.enqueue_maintenance_job(
wiki,
kind=wiki_queue.CATALOG_REFRESH_JOB,
payload={"catalog": "graph/skills-sh-catalog.json.gz"},
source="test",
now=12.0,
)
leased = wiki_queue.lease_next(db_path, worker_id="worker-a", now=12.0)
assert leased is not None
wiki_queue.mark_failed(db_path, leased.id, error="boom", retry=False, now=13.0)
wiki_queue.cancel_job(db_path, third.id, reason="operator skipped", now=14.0)
status = mt.queue_status()
direct_status = status_service.queue_status(wiki)
html_out = mt.render_status()
assert status["available"] is True
assert status["counts"] == {
wiki_queue.STATUS_PENDING: 1,
wiki_queue.STATUS_RUNNING: 0,
wiki_queue.STATUS_SUCCEEDED: 0,
wiki_queue.STATUS_FAILED: 1,
wiki_queue.STATUS_CANCELLED: 1,
}
assert status["total"] == 3
assert [job["id"] for job in status["recent_jobs"]] == [third.id, second.id, first.id]
assert status["recent_jobs"][0]["status"] == wiki_queue.STATUS_CANCELLED
assert direct_status == status
assert "cancelled: 1" in html_out
def test_artifact_status_reads_promotion_metadata(
fake_claude: Path,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
from ctx.core.graph.graph_packs import write_base_pack, write_overlay_pack
from ctx.core.graph.graph_store import ensure_graph_store
from ctx.core.wiki.wiki_packs import write_wiki_base_pack, write_wiki_overlay_pack
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True)
graph = graph_dir / "graph.json"
graph.write_text('{"nodes":[],"edges":[]}', encoding="utf-8")
pack_graph = nx.Graph()
pack_graph.add_node("skill:pack-skill", label="pack-skill", type="skill")
write_base_pack(
pack_dir=graph_dir / "packs" / "base-export-1",
pack_id="base-export-1",
base_export_id="export-1",
config_hash="config-1",
model_id="model-1",
graph=pack_graph,
)
write_overlay_pack(
pack_dir=graph_dir / "packs" / "overlay-pack-skill",
pack_id="overlay-pack-skill",
base_export_id="export-1",
parent_export_id="export-1",
config_hash="config-1",
model_id="model-1",
nodes=[{"id": "skill:pack-skill", "label": "pack-skill", "type": "skill"}],
edges=[],
tombstones=[],
)
write_wiki_base_pack(
pack_dir=fake_claude / "skill-wiki" / "wiki-packs" / "base-export-1",
pack_id="base-export-1",
base_export_id="export-1",
pages={"entities/skills/pack-skill.md": "# Pack Skill\n"},
)
write_wiki_overlay_pack(
pack_dir=fake_claude / "skill-wiki" / "wiki-packs" / "overlay-pack-skill",
pack_id="overlay-pack-skill",
base_export_id="export-1",
parent_export_id="export-1",
pages={"entities/skills/pack-skill.md": "# Pack Skill\n\nUpdated.\n"},
tombstones=[],
)
ensure_graph_store(graph_dir, graph_dir / "graph-store.sqlite3")
repo_graph = tmp_path / "repo-graph"
repo_graph.mkdir()
(repo_graph / "wiki-graph.tar.gz").write_bytes(b"tar")
runtime_catalog = (
fake_claude / "skill-wiki" / "external-catalogs" / "skills-sh" / "catalog.json"
)
runtime_catalog.parent.mkdir(parents=True)
runtime_catalog.write_text("{}", encoding="utf-8")
monkeypatch.setattr(mt, "repo_graph_dir", lambda: repo_graph)
(graph_dir / "graph.json.promotion.json").write_text(
json.dumps({
"status": "promoted",
"target": str(graph),
"previous": {"sha256": "old", "size": 10},
"current": {"sha256": "new", "size": 22},
"promoted_at": "2026-05-04T00:00:00+00:00",
}),
encoding="utf-8",
)
status = mt.artifact_status()
direct_status = status_service.artifact_status(
wiki_dir=fake_claude / "skill-wiki",
claude_dir=fake_claude,
repo_graph_dir=repo_graph,
)
assert status["graph_json"]["exists"] is True
assert status["graph_json"]["size"] == graph.stat().st_size
assert status["graph_packs"]["exists"] is True
assert status["graph_packs"]["pack_count"] == 2
assert status["graph_packs"]["base_count"] == 1
assert status["graph_packs"]["overlay_count"] == 1
assert status["wiki_packs"]["pack_count"] == 2
assert status["wiki_packs"]["base_count"] == 1
assert status["wiki_packs"]["overlay_count"] == 1
assert status["pack_compaction"]["needs_compaction"] is False
assert status["pack_compaction"]["can_compact_now"] is True
assert status["pack_compaction"]["max_overlay_count"] == 1
assert status["graph_store"]["exists"] is True
assert status["graph_store"]["fresh"] is True
assert status["graph_store"]["ok"] is True
assert status["graph_store"]["nodes"] == 1
assert status["graph_store"]["edges"] == 0
assert status["wiki_graph_tar"]["path"] == str(repo_graph / "wiki-graph.tar.gz")
assert status["skills_sh_catalog"]["path"] == str(runtime_catalog)
assert status["promotion_count"] == 1
assert status["promotions"][0]["status"] == "promoted"
assert status["promotions"][0]["current_sha256"] == "new"
assert direct_status == status
def test_status_page_and_api_show_queue_and_artifacts(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
wiki = fake_claude / "skill-wiki"
wiki_queue.enqueue_maintenance_job(
wiki,
kind=wiki_queue.GRAPH_EXPORT_JOB,
payload={"graph_only": True},
source="test",
now=10.0,
)
html_out = mt.render_status()
assert "Queue state" in html_out
assert "Artifact versions" in html_out
assert "graph packs" in html_out
assert "graph-store.sqlite3" in html_out
assert "wiki packs" in html_out
assert "pack compaction" in html_out
assert "packs: 0 (base 0, overlay 0)" in html_out
assert "compaction: not needed, 0 overlays / threshold" in html_out
assert "store: stale or missing, 0 nodes, 0 edges" in html_out
assert wiki_queue.GRAPH_EXPORT_JOB in html_out
server, _thread, port = _serve_monitor(monkeypatch)
try:
with urllib.request.urlopen(
f"http://127.0.0.1:{port}/api/status.json",
timeout=5,
) as response:
payload = json.loads(response.read().decode("utf-8"))
assert payload["queue"]["total"] == 1
assert payload["artifacts"]["graph_json"]["path"].endswith("graph.json")
finally:
server.shutdown()
server.server_close()
def test_status_page_shows_queue_db_errors(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
db_path = wiki_queue.queue_db_path(fake_claude / "skill-wiki")
db_path.parent.mkdir(parents=True)
db_path.write_bytes(b"exists")
def fail_count_jobs_by_status(_db_path: Path) -> dict[str, int]:
raise RuntimeError("cannot read queue")
monkeypatch.setattr(
mt.wiki_queue,
"count_jobs_by_status",
fail_count_jobs_by_status,
)
status = mt.queue_status()
html_out = mt.render_status()
assert status["available"] is False
assert status["error"] == "cannot read queue"
assert "Queue DB error" in html_out
assert "cannot read queue" in html_out
assert "Durable worker DB: error" in html_out
def test_render_loaded_shows_manifest_entries(fake_claude: Path) -> None:
(fake_claude / "skill-manifest.json").write_text(
json.dumps({
"load": [{"skill": "python-patterns", "source": "user-approved",
"priority": 7, "reason": "fuzzy match"}],
"unload": [{"skill": "old-skill", "source": "stale"}],
"warnings": [],
}),
encoding="utf-8",
)
html = mt.render_loaded()
assert "python-patterns" in html
assert "old-skill" in html
# Action buttons must be present for each row.
assert "btn-unload" in html
assert "btn-load" in html
# Navigation must include new pages.
assert "/loaded" in html
assert "/logs" in html
def test_render_loaded_shows_harness_install_without_unload_button(fake_claude: Path) -> None:
harness_dir = fake_claude / "harness-installs"
harness_dir.mkdir()
(harness_dir / "langgraph.json").write_text(
json.dumps({"slug": "langgraph", "status": "installed"}),
encoding="utf-8",
)
html = mt.render_loaded()
assert "langgraph" in html
assert "ctx-harness-install langgraph --uninstall --dry-run" in html
assert "data-slug='langgraph'" not in html
def test_loaded_page_module_renders_read_only_state() -> None:
html = loaded_page.render_loaded(
{
"load": [{"skill": "reviewer", "entity_type": "agent", "source": "manual"}],
"unload": [{"skill": "old-skill", "entity_type": "skill", "reason": "stale"}],
},
mutations_enabled=False,
monitor_token="secret-token",
layout=lambda _title, body: body,
)
assert "Read-only mode" in html
assert "reviewer" in html
assert "old-skill" in html
assert "btn-unload" in html
assert " disabled" in html
assert "secret-token" not in html
def test_runtime_lifecycle_summary_reads_validation_and_escalation_events(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
events = tmp_path / "runtime" / "events.jsonl"
monkeypatch.setattr(mt, "runtime_lifecycle_path", lambda: events)
_write_runtime_events(events, [
{
"action": "validation",
"session_id": "s-1",
"check_name": "pytest",
"status": "passed",
"created_at": "2026-05-08T01:00:00Z",
},
{
"action": "validation",
"session_id": "s-1",
"check_name": "mypy",
"status": "failed",
"summary": "type gate failed",
"created_at": "2026-05-08T01:05:00Z",
},
{
"action": "escalation",
"session_id": "s-1",
"trigger": "validation-failed",
"reason": "mypy failed after retry",
"status": "open",
"severity": "blocking",
"created_at": "2026-05-08T01:06:00Z",
},
{
"action": "escalation",
"session_id": "s-2",
"trigger": "user-review",
"reason": "review completed",
"status": "resolved",
"severity": "info",
"created_at": "2026-05-08T01:07:00Z",
},
])
summary = mt.runtime_lifecycle_summary()
direct_summary = runtime_service.lifecycle_summary(events)
assert summary["validations_total"] == 2
assert summary["validation_failures"] == 1
assert summary["open_escalations_total"] == 1
assert summary["latest_validation"]["check_name"] == "mypy"
assert summary["open_escalations"][0]["trigger"] == "validation-failed"
assert direct_summary == summary
def test_runtime_lifecycle_summary_uses_full_history_for_open_state(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
events = tmp_path / "runtime" / "events.jsonl"
monkeypatch.setattr(mt, "runtime_lifecycle_path", lambda: events)
records = [{
"action": "escalation",
"session_id": "s-1",
"trigger": "validation-failed",
"reason": "pytest failed",
"status": "open",
"severity": "blocking",
"created_at": "2026-05-08T00:00:00Z",
}]
records.extend({
"action": "validation",
"session_id": "s-1",
"check_name": f"check-{idx}",
"status": "passed",
"created_at": f"2026-05-08T01:{idx % 60:02d}:00Z",
} for idx in range(201))
_write_runtime_events(events, records)
summary = mt.runtime_lifecycle_summary()
assert summary["validations_total"] == 201
assert summary["open_escalations_total"] == 1
assert summary["open_escalations"][0]["trigger"] == "validation-failed"
records.append({
"action": "escalation",
"session_id": "s-1",
"trigger": "validation-failed",
"reason": "pytest failed",
"status": "resolved",
"severity": "blocking",
"created_at": "2026-05-08T02:00:00Z",
})
_write_runtime_events(events, records)
summary = mt.runtime_lifecycle_summary()
assert summary["open_escalations_total"] == 0
assert summary["escalations_total"] == 2
def test_render_runtime_lifecycle_surfaces_checks_and_open_escalations(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
events = tmp_path / "runtime" / "events.jsonl"
monkeypatch.setattr(mt, "runtime_lifecycle_path", lambda: events)
_write_runtime_events(events, [
{
"action": "validation",
"session_id": "s-1",
"check_name": "mypy",
"status": "failed",
"summary": "<type gate failed>",
"created_at": "2026-05-08T01:05:00Z",
},
{
"action": "escalation",
"session_id": "s-1",
"trigger": "validation-failed",
"reason": "<mypy failed>",
"status": "open",
"severity": "blocking",
"created_at": "2026-05-08T01:06:00Z",
},
])
html = mt.render_runtime_lifecycle()
assert "Runtime lifecycle" in html
assert "mypy" in html
assert "validation-failed" in html
assert "<type gate failed>" in html
assert "<mypy failed>" in html
def test_render_logs_filters_and_renders(fake_claude: Path) -> None:
_write_audit(fake_claude, [
{"ts": "t1", "event": "skill.loaded", "subject_type": "skill",
"subject": "s1", "actor": "hook", "session_id": "sess"},
{"ts": "t2", "event": "skill.score_updated", "subject_type": "skill",
"subject": "s1", "actor": "hook", "session_id": "sess"},
])
html = mt.render_logs()
assert "skill.loaded" in html
assert "skill.score_updated" in html
# Filter input must be wired.
assert "id='filter'" in html
def test_perform_load_rejects_invalid_slug() -> None:
ok, msg = mt.perform_load("../etc/passwd")
assert ok is False
assert "invalid slug" in msg
helper_ok, helper_msg = dashboard_entities.perform_load(
"../etc/passwd",
deps=mt.entity_runtime_deps(),
)
assert (helper_ok, helper_msg) == (ok, msg)
def test_perform_load_runs_skill_security_scan_and_surfaces_output(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from ctx.adapters.claude_code.install import skill_install
calls: list[bool] = []
class Scan:
output = "SkillSpector found no issues"
class Result:
status = "installed"
message = "SkillSpector: passed"
security_scan = Scan()
def fake_install_skill(*args: object, **kwargs: object) -> Result:
calls.append(bool(kwargs.get("security_scan")))
return Result()
monkeypatch.setattr(skill_install, "install_skill", fake_install_skill)
ok, msg = mt.perform_load("python-patterns", entity_type="skill")
assert ok is True
assert calls == [True]
assert "SkillSpector: passed" in msg
assert "SkillSpector report:" in msg
assert "found no issues" in msg
def test_perform_unload_rejects_invalid_slug() -> None:
ok, msg = mt.perform_unload("../../hostile")
assert ok is False
assert "invalid slug" in msg
def test_load_sidecar_rejects_unsafe_slug(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "python-patterns", {"slug": "python-patterns"})
assert mt.load_sidecar("../python-patterns") is None
def test_load_sidecar_reads_mcp_quality_subdir(fake_claude: Path) -> None:
_write_mcp_sidecar(fake_claude, "filesystem", {
"slug": "filesystem",
"grade": "A",
"raw_score": 0.91,
})
sidecar = mt.load_sidecar("filesystem")
assert sidecar is not None
assert sidecar["subject_type"] == "mcp-server"
def test_skill_sidecar_api_reads_typed_sidecar(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_mcp_sidecar(fake_claude, "filesystem", {
"slug": "filesystem",
"grade": "A",
"raw_score": 0.91,
})
server, thread, port = _serve_monitor(monkeypatch)
try:
status, payload = _get_json(port, "/api/skill/filesystem.json?type=mcp-server")
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
assert status == 200
assert payload["slug"] == "filesystem"
assert payload["subject_type"] == "mcp-server"
def test_load_sidecar_can_disambiguate_duplicate_slug(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "langgraph", {
"slug": "langgraph",
"subject_type": "skill",
"grade": "D",
})
harness_sidecar = {
"slug": "langgraph",
"subject_type": "harness",
"grade": "A",
}
# Dashboard sidecars are flat for non-MCP entity types; duplicate slugs
# are disambiguated by the subject_type inside the sidecar.
(fake_claude / "skill-quality" / "langgraph-harness.json").write_text(
json.dumps(harness_sidecar), encoding="utf-8",
)
skill_sidecar = mt.load_sidecar("langgraph", entity_type="skill")
assert skill_sidecar is not None
assert skill_sidecar["grade"] == "D"
harness = mt.load_sidecar("langgraph", entity_type="harness")
assert harness is not None
assert harness["grade"] == "A"
def test_load_sidecar_typed_miss_does_not_build_global_index(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_sidecar(fake_claude, "unrelated", {"slug": "unrelated"})
monkeypatch.setattr(
sidecar_service,
"sidecar_index",
lambda *args, **kwargs: (
_ for _ in ()
).throw(AssertionError("cold full sidecar scan")),
)
assert mt.load_sidecar("missing", entity_type="skill") is None
def test_monitor_post_requires_token(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
server, thread, port = _serve_monitor(monkeypatch)
try:
status, body = _post_json(port, "/api/load", {"slug": "python-patterns"})
assert status == 403
assert "token" in body["detail"]
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_monitor_post_accepts_valid_token(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
direct_calls: list[tuple[str, str, dict[str, str]]] = []
def direct_load(
slug: str,
entity_type: str,
kwargs: dict[str, str],
) -> tuple[bool, str]:
direct_calls.append((slug, entity_type, kwargs))
return True, "loaded"
direct = mutations_api.handle_mutation_route(
"api_load",
{"slug": "python-patterns", "entity_type": "agent"},
mutations_api.MutationApiDeps(
perform_load=direct_load,
perform_unload=lambda _slug, _type: (False, "unused"),
save_config_updates=lambda _updates: {"ok": False, "detail": "unused"},
upsert_wiki_entity=lambda _body: (False, "unused"),
delete_wiki_entity=lambda _slug, _type: (False, "unused"),
),
)
assert direct is not None
assert direct.status == 200
assert direct.payload == {"ok": True, "detail": "loaded"}
assert direct_calls == [("python-patterns", "agent", {})]
calls: list[tuple[str, str]] = []
def fake_load(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
calls.append((slug, entity_type))
return True, "loaded"
monkeypatch.setattr(mt, "perform_load", fake_load)
server, thread, port = _serve_monitor(monkeypatch)
try:
status, body = _post_json(
port,
"/api/load",
{"slug": "python-patterns", "entity_type": "agent"},
token="test-token",
)
assert status == 200
assert body == {"ok": True, "detail": "loaded"}
assert calls == [("python-patterns", "agent")]
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_monitor_post_unload_accepts_valid_token_without_mocking_runtime(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
manifest_path = fake_claude / "skill-manifest.json"
manifest_path.write_text(
json.dumps({
"load": [{"skill": "code-reviewer", "entity_type": "agent", "source": "test"}],
"unload": [],
"warnings": [],
}),
encoding="utf-8",
)
server, thread, port = _serve_monitor(monkeypatch)
try:
status, body = _post_json(
port,
"/api/unload",
{"slug": "code-reviewer", "entity_type": "agent"},
token="test-token",
)
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
assert status == 200
assert body == {"ok": True, "detail": "unloaded code-reviewer"}
updated = json.loads(manifest_path.read_text(encoding="utf-8"))
assert updated["load"] == []
assert updated["unload"] == [
{"skill": "code-reviewer", "entity_type": "agent", "source": "test"},
]
def test_monitor_load_forwards_mcp_command_and_json_config(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
calls: list[tuple[str, str, dict[str, str]]] = []
def fake_load(
slug: str,
entity_type: str = "skill",
**kwargs: str,
) -> tuple[bool, str]:
calls.append((slug, entity_type, kwargs))
return True, "loaded mcp"
monkeypatch.setattr(mt, "perform_load", fake_load)
server, thread, port = _serve_monitor(monkeypatch)
try:
status, body = _post_json(
port,
"/api/load",
{
"slug": "github",
"entity_type": "mcp-server",
"command": "npx -y @modelcontextprotocol/server-github",
"json_config": '{"env":{"GITHUB_TOKEN":"${GITHUB_TOKEN}"}}',
},
token="test-token",
)
assert status == 200
assert body == {"ok": True, "detail": "loaded mcp"}
assert calls == [
(
"github",
"mcp-server",
{
"command": "npx -y @modelcontextprotocol/server-github",
"json_config": '{"env":{"GITHUB_TOKEN":"${GITHUB_TOKEN}"}}',
},
)
]
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_monitor_post_rejects_cross_origin_with_valid_token(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
calls: list[str] = []
def fake_load(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
calls.append(slug)
return True, f"loaded {entity_type}"
monkeypatch.setattr(mt, "perform_load", fake_load)
server, thread, port = _serve_monitor(monkeypatch)
body = json.dumps({"slug": "python-patterns"}).encode("utf-8")
try:
status, payload = _post_raw(
port,
"/api/load",
headers={
"Content-Type": "application/json",
"Content-Length": str(len(body)),
"X-CTX-Monitor-Token": "test-token",
"Origin": "http://evil.example",
},
body=body,
)
assert status == 403
assert "cross-origin" in payload["detail"]
assert calls == []
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_monitor_post_rejects_rebound_host_with_valid_token(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
calls: list[str] = []
def fake_load(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
calls.append(slug)
return True, f"loaded {entity_type}"
monkeypatch.setattr(mt, "perform_load", fake_load)
server, thread, port = _serve_monitor(monkeypatch)
body = json.dumps({"slug": "python-patterns"}).encode("utf-8")
try:
status, payload = _post_raw(
port,
"/api/load",
headers={
"Host": "evil.example",
"Content-Type": "application/json",
"Content-Length": str(len(body)),
"X-CTX-Monitor-Token": "test-token",
"Origin": "http://evil.example",
},
body=body,
)
assert status == 403
assert "cross-origin" in payload["detail"]
assert calls == []
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_monitor_get_rejects_rebound_host_in_loopback_mode(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
server, thread, port = _serve_monitor(monkeypatch)
try:
status, payload = _get_raw(
port,
"/api/status.json",
headers={"Host": "evil.example"},
)
assert status == 403
assert "monitor read" in payload["detail"]
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
@pytest.mark.parametrize(
("length", "status", "detail"),
[
("nope", 400, "invalid Content-Length"),
("-1", 400, "invalid Content-Length"),
(str(mt.MAX_POST_BODY_BYTES + 1), 413, "too large"),
],
)
def test_monitor_post_rejects_bad_content_length_before_body_read(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
length: str,
status: int,
detail: str,
) -> None:
server, thread, port = _serve_monitor(monkeypatch)
try:
code, payload = _post_raw(
port,
"/api/load",
headers={
"Content-Type": "application/json",
"Content-Length": length,
"X-CTX-Monitor-Token": "test-token",
},
)
assert code == status
assert detail in payload["detail"]
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_monitor_post_rejects_non_object_json_body(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
server, thread, port = _serve_monitor(monkeypatch)
body = b"[]"
try:
status, payload = _post_raw(
port,
"/api/load",
headers={
"Content-Type": "application/json",
"Content-Length": str(len(body)),
"X-CTX-Monitor-Token": "test-token",
},
body=body,
)
assert status == 400
assert "object" in payload["detail"]
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_monitor_non_loopback_bind_is_read_only(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
calls: list[str] = []
def fake_load(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
calls.append(slug)
return True, f"loaded {entity_type}"
(fake_claude / "skill-manifest.json").write_text(
json.dumps({"load": [], "unload": [], "warnings": []}),
encoding="utf-8",
)
monkeypatch.setattr(mt, "perform_load", fake_load)
server, thread, port = _serve_monitor(
monkeypatch,
token="browser-token",
host="0.0.0.0",
)
try:
with pytest.raises(urllib.error.HTTPError) as excinfo:
urllib.request.urlopen(f"http://127.0.0.1:{port}/loaded", timeout=5)
assert excinfo.value.code == 403
assert "monitor read token required" in excinfo.value.read().decode("utf-8")
with urllib.request.urlopen(
f"http://127.0.0.1:{port}/loaded?token=browser-token",
timeout=5,
) as response:
loaded_html = response.read().decode("utf-8")
csp = response.headers.get("Content-Security-Policy", "")
cookie = response.headers.get("Set-Cookie", "")
assert "browser-token" not in loaded_html
assert "Read-only mode" in loaded_html
assert "script-src 'self' 'unsafe-inline'" in csp
assert "ctx_monitor_read_token=browser-token" in cookie
with pytest.raises(urllib.error.HTTPError) as excinfo:
urllib.request.urlopen(
f"http://127.0.0.1:{port}/api/manifest.json",
timeout=5,
)
assert excinfo.value.code == 403
body = json.loads(excinfo.value.read().decode("utf-8"))
assert "read token required" in body["detail"]
status, body = _get_raw(
port,
"/api/manifest.json",
headers={
"Host": f"127.0.0.1:{port}",
"Cookie": "ctx_monitor_read_token=browser-token",
},
)
assert status == 200
assert body["load"] == []
status, body = _post_json(
port,
"/api/load",
{"slug": "python-patterns"},
token="browser-token",
)
assert status == 403
assert "disabled" in body["detail"]
assert calls == []
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_serve_generates_read_token_for_non_loopback(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
class FakeServer:
_ctx_mutations_enabled = False
def serve_forever(self) -> None:
raise KeyboardInterrupt
def server_close(self) -> None:
return None
monkeypatch.setattr(mt, "MONITOR_TOKEN", "")
monkeypatch.setattr(mt, "make_monitor_server", lambda _host, _port: FakeServer())
monkeypatch.setattr(monitor_cli.secrets, "token_urlsafe", lambda _size: "lan-token")
monkeypatch.setattr(monitor_cli.socket, "gethostname", lambda: "devbox")
monkeypatch.setattr(monitor_cli.socket, "gethostbyname", lambda _name: "192.168.1.50")
mt.serve(host="0.0.0.0", port=8765)
assert mt.MONITOR_TOKEN == "lan-token"
out = capsys.readouterr().out
assert "http://192.168.1.50:8765/?token=lan-token" in out
assert "http://0.0.0.0:8765" not in out
assert "read token required" in out
def test_host_allows_mutations_only_for_loopback() -> None:
assert mt.host_allows_mutations("127.0.0.1")
assert mt.host_allows_mutations("::1")
assert mt.host_allows_mutations("localhost")
assert not mt.host_allows_mutations("0.0.0.0")
assert not mt.host_allows_mutations("::")
assert not mt.host_allows_mutations("example.com")
def test_monitor_route_inventory_covers_nav_and_api_routes() -> None:
nav_hrefs = {href for _key, _label, href in monitor_routes.NAV_ROUTES}
assert {
"/",
"/loaded",
"/skills",
"/skillspector",
"/wiki",
"/graph",
"/manage",
"/harness",
"/docs",
"/config",
"/status",
"/kpi",
"/runtime",
"/sessions",
"/logs",
"/events",
} <= nav_hrefs
assert nav_hrefs <= monitor_routes.PAGE_ROUTES
assert "/catalog" in monitor_routes.PAGE_ROUTES
assert "/api/graph/<slug>.json" in monitor_routes.GET_API_PATTERNS
assert "/api/entities/search.json" in monitor_routes.GET_API_ROUTES
assert "/api/entity/upsert" in monitor_routes.POST_API_ROUTES
def test_monitor_route_matchers_cover_dynamic_and_mutation_routes() -> None:
parsed = monitor_routes.parse_request_target(
"/api/graph/github%2Fcli.json?type=mcp-server&limit=20",
)
assert parsed.path == "/api/graph/github%2Fcli.json"
assert parsed.query == {"type": "mcp-server", "limit": "20"}
home = monitor_routes.match_get_route("/")
catalog = monitor_routes.match_get_route("/catalog/")
wiki_entity = monitor_routes.match_get_route("/wiki/langgraph")
graph_api = monitor_routes.match_get_route("/api/graph/github%2Fcli.json")
assert home is not None and home.name == "home"
assert catalog is not None and catalog.name == "wiki_index"
assert wiki_entity is not None and wiki_entity.params == {"slug": "langgraph"}
assert graph_api is not None and graph_api.params == {"slug": "github/cli"}
assert monitor_routes.match_get_route("/missing") is None
entity_upsert = monitor_routes.match_post_route("/api/entity/upsert")
assert entity_upsert is not None and entity_upsert.name == (
"api_entity_upsert"
)
assert monitor_routes.match_post_route("/api/nope") is None
def test_graph_api_invalid_params_return_400(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
server, thread, port = _serve_monitor(monkeypatch)
try:
with pytest.raises(urllib.error.HTTPError) as excinfo:
urllib.request.urlopen(
f"http://127.0.0.1:{port}/api/graph/langgraph.json?hops=abc",
timeout=5,
)
assert excinfo.value.code == 400
body = json.loads(excinfo.value.read().decode("utf-8"))
assert body["detail"] == "hops and limit must be integers"
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_parse_frontmatter_basic() -> None:
text = "---\nname: python-patterns\nuse_count: 3\n---\n# Body\n\nhello"
meta, body = mt.parse_frontmatter(text)
assert meta == {"name": "python-patterns", "use_count": "3"}
assert body.startswith("# Body")
def test_parse_frontmatter_missing_returns_empty_meta() -> None:
text = "# No frontmatter\n\nBody only."
meta, body = mt.parse_frontmatter(text)
assert meta == {}
assert body == text
def test_parse_frontmatter_multiline_tags() -> None:
text = "---\ntags:\n - python\n - api\n---\n# Body\n"
meta, body = mt.parse_frontmatter(text)
assert meta["tags"] == ["python", "api"]
assert body == "# Body"
def test_wiki_entity_path_rejects_unsafe_slug(fake_claude: Path) -> None:
assert mt.wiki_entity_path("../../etc/passwd") is None
assert mt.wiki_entity_path("path/with/slash") is None
assert mt.wiki_entity_path("con.txt") is None
# Absent slug returns None but doesn't raise.
assert mt.wiki_entity_path("no-such-skill") is None
@pytest.mark.parametrize("slug", ["python-patterns", "mcp.v2", "0-service"])
def test_monitor_slug_validator_accepts_safe_values(slug: str) -> None:
assert mt.is_safe_slug(slug)
@pytest.mark.parametrize("slug", ["con.txt", "nul.", "COM1", "LPT9.ini"])
def test_monitor_slug_validator_rejects_windows_reserved_names(slug: str) -> None:
assert not mt.is_safe_slug(slug)
def test_monitor_sse_stream_does_not_block_json_requests(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_audit(fake_claude, [
{"ts": "t", "event": "skill.loaded", "subject": "python-patterns",
"session_id": "s1"},
])
server, thread, port = _serve_monitor(monkeypatch)
stream = urllib.request.urlopen(
f"http://127.0.0.1:{port}/api/events.stream", timeout=2
)
try:
with urllib.request.urlopen(
f"http://127.0.0.1:{port}/api/sessions.json", timeout=2,
) as response:
assert response.status == 200
body = json.loads(response.read().decode("utf-8"))
assert body[0]["session_id"] == "s1"
finally:
stream.close()
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_monitor_shutdown_signals_open_sse_workers(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
server, thread, port = _serve_monitor(monkeypatch)
stream = urllib.request.urlopen(
f"http://127.0.0.1:{port}/api/events.stream", timeout=2
)
try:
server.shutdown()
thread.join(timeout=2)
assert not thread.is_alive()
assert server._ctx_shutdown.is_set()
finally:
stream.close()
server.server_close()
def test_render_events_shows_recent_audit_backlog(fake_claude: Path) -> None:
_write_audit(fake_claude, [
{"ts": "t1", "event": "skill.loaded", "subject": "python-patterns"},
{"ts": "t2", "event": "agent.loaded", "subject": "repo-reviewer"},
])
html_out = mt.render_events()
assert "Showing last 2 audit events" in html_out
assert "skill.loaded" in html_out
assert "python-patterns" in html_out
assert "agent.loaded" in html_out
assert "repo-reviewer" in html_out
assert "id='stream-status'" in html_out
def test_live_alias_renders_events_page(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_audit(fake_claude, [
{"ts": "t1", "event": "skill.loaded", "subject": "python-patterns"},
])
server, thread, port = _serve_monitor(monkeypatch)
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/live", timeout=5) as response:
html_out = response.read().decode("utf-8")
assert response.status == 200
assert "Live events" in html_out
assert "python-patterns" in html_out
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_wiki_entity_path_finds_skill_page(fake_claude: Path) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
target = skills_dir / "python-patterns.md"
target.write_text("---\nname: python-patterns\n---\n# body\n",
encoding="utf-8")
assert mt.wiki_entity_path("python-patterns") == target
def test_render_wiki_entity_with_real_page(fake_claude: Path) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
(skills_dir / "python-patterns.md").write_text(
"---\nname: python-patterns\nuse_count: 2\n---\n# Python patterns\n\nBody text.",
encoding="utf-8",
)
html_out = mt.render_wiki_entity("python-patterns")
assert "python-patterns" in html_out
assert "Python patterns" in html_out or "Body text" in html_out
assert "use_count" in html_out # frontmatter table
assert "class='card wiki-body'" in html_out
direct_html = wiki_page.render_wiki_entity_page(
slug="python-patterns",
entity_type="skill",
meta={"name": "python-patterns", "use_count": 2},
md_body="# Python patterns\n\nBody text.",
sidecar={"grade": "A", "raw_score": 0.9},
dashboard_entity_types=mt.DASHBOARD_ENTITY_TYPES,
display_slug=mt.display_slug,
frontmatter_text=mt.frontmatter_text,
truncate_text=mt.truncate_text,
extract_embedded_quality_block=mt.extract_embedded_quality_block,
strip_duplicate_wiki_heading=mt.strip_duplicate_wiki_heading,
render_entity_subgraph=lambda _slug, _entity_type: "<div>subgraph</div>",
render_entity_tabs=mt.render_entity_tabs,
render_quality_drilldown=mt.render_quality_drilldown,
render_wiki_markdown=mt.render_wiki_markdown,
layout=lambda _title, body: body,
)
assert "Python patterns" in direct_html or "Body text" in direct_html
assert "grade-A" in direct_html
def test_render_wiki_entity_wrapper_matches_extracted_orchestration(
fake_claude: Path,
) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
(skills_dir / "python-patterns.md").write_text(
"---\nname: python-patterns\ntype: skill\nuse_count: 2\n---\n"
"# Python patterns\n\nBody text.",
encoding="utf-8",
)
wrapper_html = mt.render_wiki_entity("python-patterns", entity_type="skill")
direct_html = wiki_page.render_wiki_entity(
"python-patterns",
entity_type="skill",
entity_path=mt.wiki_entity_path,
read_entity_text=mt.read_wiki_entity_text,
parse_frontmatter=mt.parse_frontmatter,
load_sidecar=mt.load_sidecar,
render_runtime_graph_entity=mt.render_runtime_graph_entity,
dashboard_entity_types=mt.DASHBOARD_ENTITY_TYPES,
display_slug=mt.display_slug,
frontmatter_text=mt.frontmatter_text,
truncate_text=mt.truncate_text,
extract_embedded_quality_block=mt.extract_embedded_quality_block,
strip_duplicate_wiki_heading=mt.strip_duplicate_wiki_heading,
render_entity_subgraph=mt.render_entity_subgraph,
render_entity_tabs=mt.render_entity_tabs,
render_quality_drilldown=mt.render_quality_drilldown,
render_wiki_markdown=mt.render_wiki_markdown,
layout=mt.layout,
)
assert wrapper_html == direct_html
assert "Body text" in wrapper_html
def test_render_wiki_entity_renders_markdown_and_wikilinks(fake_claude: Path) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
(skills_dir / "markdown-page.md").write_text(
"---\n"
"type: skill\n"
"tags: [python, testing]\n"
"---\n"
"# Markdown Page\n\n"
"Use `pytest` with [[entities/skills/find-skills]].\n\n"
"Source: [Homepage](https://example.com/docs).\n\n"
"Unsafe: [bad](javascript:alert(1)).\n\n"
"Protocol relative: [offsite](//evil.example/x).\n\n"
"- first item\n"
"- [[entities/agents/reviewer|reviewer agent]]\n",
encoding="utf-8",
)
html_out = mt.render_wiki_entity("markdown-page", entity_type="skill")
markdown_out = wiki_page.render_wiki_markdown(
"Use `pytest` with [[entities/skills/find-skills]].\n\n"
"Source: [Homepage](https://example.com/docs).",
wiki_link_href=mt.wiki_link_href,
)
assert "<h1>Markdown Page</h1>" not in html_out
assert "<code>pytest</code>" in html_out
assert "<code>pytest</code>" in markdown_out
assert "href='/wiki/find-skills?type=skill'" in markdown_out
assert "href='/wiki/find-skills?type=skill'" in html_out
assert "href='/wiki/reviewer?type=agent'" in html_out
assert "<a href='https://example.com/docs'>Homepage</a>" in html_out
assert "href='javascript:alert(1)'" not in html_out
assert "href='//evil.example/x'" not in html_out
assert "<li>first item</li>" in html_out
assert "<pre style=" not in html_out
def test_render_mcp_wiki_entity_has_tabs_subgraph_and_quality(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
mcp_dir = fake_claude / "skill-wiki" / "entities" / "mcp-servers" / "g"
mcp_dir.mkdir(parents=True)
(mcp_dir / "github.md").write_text(
"---\n"
"type: mcp-server\n"
"description: Manage repositories and issues.\n"
"---\n"
"# GitHub\n\n"
"Manage repositories, issues, and search code via GitHub API.\n",
encoding="utf-8",
)
_write_mcp_sidecar(fake_claude, "github", {
"slug": "github",
"subject_type": "mcp-server",
"grade": "B",
"raw_score": 0.7106,
"hard_floor": "missing-license",
"weights": {"freshness": 0.25, "docs": 0.75},
"signals": {
"docs": {"score": 0.9, "evidence": {"has_install": True}},
"freshness": {"score": 0.2, "evidence": {"last_commit_at": None}},
},
})
_write_sidecar(fake_claude, "github-actions", {
"slug": "github-actions",
"subject_type": "skill",
"grade": "A",
"raw_score": 0.91,
})
_write_sidecar(fake_claude, "repo-reviewer", {
"slug": "repo-reviewer",
"subject_type": "agent",
"grade": "C",
"raw_score": 0.43,
"hard_floor": "needs-usage",
})
graph = nx.Graph()
graph.add_node("mcp-server:github", label="github", type="mcp-server", tags=["reference"])
graph.add_node("skill:github-actions", label="github-actions", type="skill", tags=["github", "ci"])
graph.add_node("agent:repo-reviewer", label="repo-reviewer", type="agent", tags=["github", "review"])
graph.add_edge("mcp-server:github", "skill:github-actions", weight=0.91, shared_tags=["github", "ci"])
graph.add_edge("mcp-server:github", "agent:repo-reviewer", weight=0.83, shared_tags=["github"])
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: graph)
html_out = mt.render_wiki_entity("github", entity_type="mcp-server")
direct_tabs = wiki_page.render_entity_tabs(
overview_html="overview",
subgraph_html="subgraph",
quality_html="quality",
)
direct_quality = wiki_page.render_quality_drilldown(
{
"grade": "B",
"raw_score": 0.7106,
"signals": {},
},
wiki_link_href=mt.wiki_link_href,
truncate_text=mt.truncate_text,
)
assert "data-entity-tab='overview'" in html_out
assert "data-entity-tab='overview'" in direct_tabs
assert "data-entity-tab='subgraph'" in html_out
assert "data-entity-tab='quality'" in html_out
assert "<h2>Subgraph</h2>" in html_out
assert "data-testid='entity-subgraph-graph'" in html_out
assert "data-testid='entity-subgraph-3d'" in html_out
assert "data-testid=\"entity-subgraph-node\"" in html_out
assert "data-testid=\"entity-subgraph-edge\"" in html_out
assert "id='entity-subgraph-zoom-in'" in html_out
assert "id='entity-subgraph-zoom-out'" in html_out
assert "drag to rotate" in html_out
assert "wheel to zoom" in html_out
assert "data-testid='entity-subgraph-node-detail'" in html_out
assert "data-testid='entity-subgraph-edge-detail'" in html_out
assert "Open interactive graph view" not in html_out
assert "href='/wiki/github-actions?type=skill'" in html_out
assert "href='/wiki/repo-reviewer?type=agent'" in html_out
assert "grade-A" in html_out
assert "grade-C" in html_out
assert "needs-usage" in html_out
assert "<h2>Quality</h2>" in html_out
assert "freshness" in html_out
assert "No signal breakdown was recorded" in direct_quality
assert "has_install" in html_out
assert "missing-license" in html_out
assert "<pre style=" not in html_out
@pytest.mark.parametrize(
("entity_type", "subdir", "slug"),
[
("skill", "skills", "quality-skill"),
("agent", "agents", "quality-agent"),
("mcp-server", "mcp-servers/q", "quality-mcp"),
("harness", "harnesses", "quality-harness"),
],
)
def test_render_wiki_entity_moves_embedded_quality_block_to_quality_tab(
fake_claude: Path,
entity_type: str,
subdir: str,
slug: str,
) -> None:
entity_dir = fake_claude / "skill-wiki" / "entities" / subdir
entity_dir.mkdir(parents=True)
(entity_dir / f"{slug}.md").write_text(
"---\n"
f"type: {entity_type}\n"
"---\n"
f"# {slug}\n\n"
"Overview body stays here.\n\n"
"<!-- quality:begin -->\n"
"## Quality\n\n"
"- **Grade:** C\n"
"- **Score:** 0.45 (raw 0.45)\n"
"- **Computed:** 2026-05-09T15:47:33+00:00\n\n"
"| Signal | Score | Weight |\n"
"| --- | --- | --- |\n"
"| telemetry | 0.45 | 0.40 |\n"
"<!-- quality:end -->\n\n"
"Overview continues here.\n",
encoding="utf-8",
)
html_out = mt.render_wiki_entity(slug, entity_type=entity_type)
overview_start = html_out.index("data-entity-tab-panel='overview'")
overview_end = html_out.index("data-entity-tab-panel='subgraph'")
overview_html = html_out[overview_start:overview_end]
quality_start = html_out.index("data-entity-tab-panel='quality'")
quality_html = html_out[quality_start:]
assert "data-entity-tab='overview'" in html_out
assert "data-entity-tab='quality'" in html_out
assert "Overview body stays here." in overview_html
assert "Overview continues here." in overview_html
assert "quality:begin" not in html_out
assert "quality:end" not in html_out
assert "**Grade:** C" not in overview_html
assert "**Score:** 0.45" not in overview_html
assert "Grade:" in quality_html
assert "0.45 (raw 0.45)" in quality_html
assert "No quality sidecar exists" not in quality_html
def test_render_wiki_entity_missing_slug(fake_claude: Path) -> None:
out = mt.render_wiki_entity("nope-not-here")
assert "No wiki page" in out
def test_render_wiki_entity_falls_back_to_runtime_graph_metadata(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(mt, "MONITOR_MUTATIONS_ENABLED", True)
monkeypatch.setattr(mt, "MONITOR_TOKEN", "runtime-token")
def fake_graph(slug: str, **_kwargs) -> dict:
assert slug == "github"
return {
"center": "mcp-server:github",
"nodes": [{
"data": {
"id": "mcp-server:github",
"label": "GitHub",
"type": "mcp-server",
"tags": ["git", "issues", "pull-requests"],
"description": "Manage repositories, issues, and pull requests.",
"quality_score": 0.81,
"usage_score": 0.42,
"degree": 27,
},
}],
"edges": [],
}
monkeypatch.setattr(mt, "graph_neighborhood", fake_graph)
html_out = mt.render_wiki_entity("github", entity_type="mcp-server")
assert "Runtime graph entity" in html_out
assert "Manage repositories, issues, and pull requests." in html_out
assert "git" in html_out
assert "0.810" in html_out
assert "ctx-init --graph --graph-install-mode full" in html_out
assert "data-entity-tab='overview'" in html_out
assert "data-entity-tab='subgraph'" in html_out
assert "data-entity-tab='quality'" in html_out
assert "data-testid='runtime-entity-load'" in html_out
assert "/api/load" in html_out
assert "X-CTX-Monitor-Token" in html_out
assert "payload.detail || payload.msg || response.status" in html_out
def test_runtime_graph_entity_wrapper_matches_extracted_wiki_renderer(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(mt, "MONITOR_MUTATIONS_ENABLED", True)
monkeypatch.setattr(mt, "MONITOR_TOKEN", "runtime-token")
def fake_graph(slug: str, **_kwargs) -> dict:
assert slug == "github"
return {
"center": "mcp-server:github",
"nodes": [{
"data": {
"id": "mcp-server:github",
"label": "GitHub",
"type": "mcp-server",
"tags": ["git"],
"description": "Manage GitHub.",
"quality_score": 0.81,
"usage_score": 0.42,
"degree": 27,
},
}],
"edges": [],
}
monkeypatch.setattr(mt, "graph_neighborhood", fake_graph)
wrapper_html = mt.render_runtime_graph_entity("github", entity_type="mcp-server")
direct_html = wiki_page.render_runtime_graph_entity(
"github",
entity_type="mcp-server",
monitor_mutations_enabled=mt.MONITOR_MUTATIONS_ENABLED,
monitor_token=mt.MONITOR_TOKEN,
normalize_dashboard_entity_type=mt.normalize_dashboard_entity_type,
graph_neighborhood=mt.graph_neighborhood,
graph_slug_from_node_id=mt.graph_slug_from_node_id,
graph_type_from_node_id=mt.graph_type_from_node_id,
display_label=mt.display_label,
display_slug=mt.display_slug,
load_sidecar=mt.load_sidecar,
render_quality_drilldown=mt.render_quality_drilldown,
render_entity_subgraph=mt.render_entity_subgraph,
render_entity_tabs=mt.render_entity_tabs,
layout=mt.layout,
)
assert wrapper_html == direct_html
assert wrapper_html is not None
assert "Runtime graph entity" in wrapper_html
assert "runtime-token" in wrapper_html
def test_render_runtime_harness_entity_shows_install_commands(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
def fake_graph(slug: str, **_kwargs) -> dict:
assert slug == "mirage"
return {
"center": "harness:mirage",
"nodes": [{
"data": {
"id": "harness:mirage",
"label": "Mirage",
"type": "harness",
"tags": ["harness", "sandbox"],
"description": "Virtual filesystem harness for agent tools.",
},
}],
"edges": [],
}
monkeypatch.setattr(mt, "graph_neighborhood", fake_graph)
html_out = mt.render_wiki_entity("mirage", entity_type="harness")
assert "Install harness" in html_out
assert "ctx-harness-install mirage --dry-run" in html_out
assert "ctx-harness-install mirage" in html_out
assert "data-testid='runtime-entity-load'" not in html_out
def test_render_graph_uses_builtin_3d_mount(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
mt,
"graph_stats",
lambda: {"nodes": 0, "edges": 0, "available": False},
)
monkeypatch.setattr(mt, "graph_match_default_min_percent", lambda: 7)
html_out = mt.render_graph("python-patterns")
direct_html = graph_page.render_graph(
focus="python-patterns",
graph_stats=lambda: {"nodes": 0, "edges": 0, "available": False},
top_degree_seeds=lambda **_kwargs: [],
default_focus_slug="github",
json_for_script=mt.json_for_script,
graph_match_default_min_percent=lambda: 7,
format_count=mt.format_count,
layout=lambda _title, body: body,
)
assert "id='cy'" in html_out
assert "id='cy'" in direct_html
assert "https://unpkg.com" not in html_out
assert "data-testid=\"graph-renderer\"" in html_out
assert "data-testid=\"graph-3d\"" in html_out
assert "button id=\"graph-zoom-in\"" in html_out
assert "button id=\"graph-zoom-out\"" in html_out
assert "id='cy' class='graph-stage'" in html_out
assert "height:75vh" not in html_out
assert "data-testid=\"graph-edge-detail\"" in html_out
assert "data-testid=\"graph-live-results\"" in html_out
assert "data-testid=\"graph-inspector-resize\"" in html_out
assert "id='match-filter-min'" in html_out
assert "id='match-filter-max'" in html_out
assert "class='card graph-match-card'" in html_out
assert "data-testid=\"match-histogram\"" in html_out
assert "data-testid=\"match-range-control\"" in html_out
assert "id='match-filter-min-value'" in html_out
assert "id='match-filter-max-value'" in html_out
assert "id='match-filter-value'" not in html_out
assert "value='7'" in html_out
assert "max='100'" in html_out
assert "<span>99%+</span>" not in html_out
assert "<span>100%</span>" in html_out
assert "function clampInspectorHeight" in html_out
assert "ctx-monitor-graph-inspector-height" in html_out
assert "ArrowUp" in html_out
assert "ArrowDown" in html_out
assert "data-testid=\"graph-node-detail-tree\"" in html_out
assert "function renderNodeTree" in html_out
assert "function scheduleLiveSearch" in html_out
assert "function qualityText" in html_out
assert "function nodeShapeSvg" in html_out
assert "data-node-shape=" in html_out
assert "<polygon" in html_out
assert "<rect" in html_out
assert "function isGraphOnlyEdge" in html_out
assert "function isWeakGraphOnlyEdge" in html_out
assert "return clampedUnit(value) == null ? 'unknown' : percentText(value);" in html_out
assert "Number(value).toFixed(3)" not in html_out
assert "focus.addEventListener('input', scheduleLiveSearch)" in html_out
assert "function drillIntoNode" in html_out
assert "function restorePreviousGraph" in html_out
assert "let nodeClickTimer" in html_out
assert "function scheduleNodeClick" in html_out
assert "function handleNodeDoubleClick" in html_out
assert "svg.addEventListener('click', ev => {" not in html_out
assert "graph-fallback-label" in html_out
assert "class=\"graph-toolbar\"" in html_out
assert "class=\"graph-inspector-grid\"" in html_out
assert "graph-edge-detail-inline" in html_out
assert "background:transparent" in html_out
assert "fill=\"transparent\" pointer-events=\"all\"" in html_out
assert "onmouseup=" not in html_out
assert "onpointerup=" not in html_out
assert "querySelectorAll('[data-testid=\"graph-svg-edge\"]')" in html_out
assert "data-edge-weight=" in html_out
assert "nodePassesMatch" in html_out
assert "function currentMatchWindow" in html_out
assert "function renderMatchRange" in html_out
assert "function renderMatchHistogram" in html_out
assert "function setMatchWindow" in html_out
assert "data-match-bin-min" in html_out
assert "aria-label=\"Filter match " in html_out
assert "bar.addEventListener('click', useBin)" in html_out
assert "function edgeInMatchWindow" in html_out
assert "highPct >= 99 ? 1" not in html_out
assert "max: highPct / 100" in html_out
assert "document.getElementById('match-filter-min').addEventListener('input', applyFilters)" in html_out
assert "document.getElementById('match-filter-max').addEventListener('input', applyFilters)" in html_out
assert "No neighbors in this view." in html_out
assert "graph neighbor" in html_out
assert "<strong>match</strong>" in html_out
assert "These links have no shared tags" not in html_out
assert "unproven links filtered" not in html_out
assert "Connections: " in html_out
assert "raw score clamped" in html_out
assert "graph score" not in html_out
assert "renderFallback(g); return;" in html_out
assert "renderFallback(g);\n const list" not in html_out
assert "data-testid=\"graph-list\" class=\"graph-list-panel\" hidden" in html_out
assert "id='graph-explanation'" in html_out
assert "g.explanations" in html_out
assert "Graph renderer unavailable" not in html_out
assert "Enter a slug to render the graph" in html_out
# Initial slug must be embedded as JSON literal so the JS picks it up.
assert "\"python-patterns\"" in html_out
def test_render_graph_focus_controls_preserve_type(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
mt,
"graph_stats",
lambda: {"nodes": 0, "edges": 0, "available": False},
)
html_out = mt.render_graph("langgraph", focus_type="harness")
assert "id='focus-type'" in html_out
assert "<option value='harness' selected>harness</option>" in html_out
assert "document.getElementById('go').addEventListener('click', () => load(focus.value.trim(), selectedFocusType()))" in html_out
assert "focus.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') load(ev.target.value.trim(), selectedFocusType()); })" in html_out
def test_graph_neighborhood_rejects_unsafe_slug() -> None:
result = mt.graph_neighborhood("../../evil")
assert result == {"nodes": [], "edges": [], "center": None}
def test_graph_neighborhood_supports_mcp_nodes(
fake_claude: Path,
monkeypatch,
) -> None:
import networkx as nx
import sys
G = nx.Graph()
G.add_node(
"mcp-server:anthropic-python-sdk",
label="anthropic-python-sdk",
type="mcp-server",
tags=["sdk"],
)
fake = type("M", (), {"load_graph": staticmethod(lambda _path=None: G)})
monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake)
monkeypatch.setitem(sys.modules, "resolve_graph", fake)
result = mt.graph_neighborhood("anthropic-python-sdk")
assert result["center"] == "mcp-server:anthropic-python-sdk"
assert result["nodes"][0]["data"]["type"] == "mcp-server"
def test_graph_neighborhood_resolves_partial_slug(
fake_claude: Path,
monkeypatch,
) -> None:
import networkx as nx
G = nx.Graph()
G.add_node(
"skill:brainstorming",
label="brainstorming",
type="skill",
tags=["creative", "planning"],
)
G.add_node(
"skill:multi-agent-brainstorming",
label="multi-agent-brainstorming",
type="skill",
tags=["creative", "agents"],
)
G.add_edge(
"skill:brainstorming",
"skill:multi-agent-brainstorming",
weight=0.89,
shared_tags=["creative"],
)
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: G)
result = mt.graph_neighborhood("brainstorm", entity_type="skill")
assert result["center"] == "skill:brainstorming"
assert result["resolved"]["query"] == "brainstorm"
assert result["resolved"]["slug"] == "brainstorming"
assert "brainstorming" in result["suggestions"]
def test_graph_neighborhood_sizes_nodes_by_score_usage_and_popularity(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
G = nx.Graph()
G.add_node(
"skill:hub",
label="hub",
type="skill",
tags=["python"],
quality_score=0.95,
usage_score=0.8,
)
G.add_node(
"skill:leaf-low",
label="leaf-low",
type="skill",
tags=["python"],
quality_score=0.1,
usage_score=0.0,
)
G.add_node(
"skill:leaf-high",
label="leaf-high",
type="skill",
tags=["python"],
quality_score=0.85,
usage_score=0.7,
)
G.add_edge("skill:hub", "skill:leaf-low", weight=0.2)
G.add_edge("skill:hub", "skill:leaf-high", weight=0.9)
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: G)
result = mt.graph_neighborhood("hub", entity_type="skill")
sizes = {
node["data"]["id"]: node["data"]["node_size"]
for node in result["nodes"]
}
assert sizes["skill:hub"] > sizes["skill:leaf-high"] > sizes["skill:leaf-low"]
assert 8 <= sizes["skill:leaf-low"] <= 24
assert 8 <= sizes["skill:hub"] <= 24
hub = next(node["data"] for node in result["nodes"] if node["data"]["id"] == "skill:hub")
assert hub["size_signal"] > 0
assert "quality 0.950" in hub["size_reason"]
assert "usage 0.800" in hub["size_reason"]
assert "popularity" in hub["size_reason"]
def test_dashboard_score_payload_clamps_raw_outliers() -> None:
payload = mt.dashboard_score_payload("quality_score", 18.0)
assert payload == {"quality_score": 1.0, "quality_score_raw": 18.0}
assert mt.dashboard_score_payload("quality_score", None) == {"quality_score": None}
def test_graph_neighborhood_uses_direct_sidecar_scores_without_global_index(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
sidecar_service.reset_caches()
sidecar_dir = fake_claude / "skill-quality"
for i in range(6):
(sidecar_dir / f"node-{i}.json").write_text(
json.dumps({
"slug": f"node-{i}",
"subject_type": "skill",
"score": 0.5,
"signals": {"telemetry": {"score": 0.1}},
}),
encoding="utf-8",
)
G = nx.Graph()
G.add_node("skill:center", label="center", type="skill", tags=["x"])
for i in range(6):
G.add_node(f"skill:node-{i}", label=f"node-{i}", type="skill", tags=["x"])
G.add_edge("skill:center", f"skill:node-{i}", weight=1.0)
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: G)
def fail_index(*args: object, **kwargs: object) -> dict:
raise AssertionError("graph rendering should not build the global sidecar index")
monkeypatch.setattr(sidecar_service, "sidecar_index", fail_index)
result = mt.graph_neighborhood("center", entity_type="skill")
assert result["center"] == "skill:center"
assert all(
node["data"]["size_reason"].startswith("quality ")
for node in result["nodes"]
)
def test_graph_helpers_reuse_graph_loaded_from_same_file(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
import sys
graph_file = fake_claude / "skill-wiki" / "graphify-out" / "graph.json"
graph_file.parent.mkdir(parents=True)
graph_file.write_text("{}", encoding="utf-8")
G = nx.Graph()
G.add_edge("skill:python-patterns", "skill:fastapi-pro", weight=2)
G.nodes["skill:python-patterns"]["label"] = "python-patterns"
calls: list[Path | None] = []
def _load_graph(path: Path | None = None):
calls.append(path)
return G
fake = type("M", (), {"load_graph": staticmethod(_load_graph)})
monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake)
graph_service.reset_caches()
assert mt.graph_stats()["nodes"] == 2
assert mt.top_degree_seeds(limit=1)[0]["slug"] == "python-patterns"
assert mt.graph_neighborhood("python-patterns")["center"] == "skill:python-patterns"
assert calls == [graph_file]
def test_dashboard_graph_cache_reuses_pack_only_graph(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
import sys
from ctx.core.graph.graph_packs import write_base_pack, write_overlay_pack
graph_out = fake_claude / "skill-wiki" / "graphify-out"
graph_file = graph_out / "graph.json"
pack_graph = nx.Graph()
pack_graph.add_node("skill:python-patterns", label="python-patterns", type="skill")
write_base_pack(
pack_dir=graph_out / "packs" / "base-export-1",
pack_id="base-export-1",
base_export_id="export-1",
config_hash="config-1",
model_id="model-1",
graph=pack_graph,
)
assert not graph_file.exists()
G = nx.Graph()
G.add_node("skill:python-patterns", label="python-patterns", type="skill")
calls: list[tuple[Path | None, dict[str, object]]] = []
def _load_graph(path: Path | None = None, **kwargs: object):
calls.append((path, kwargs))
return G
fake = type("M", (), {"load_graph": staticmethod(_load_graph)})
monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake)
graph_service.reset_caches()
assert mt.load_dashboard_graph() is G
assert mt.load_dashboard_graph() is G
assert calls == [(graph_file, {"apply_runtime_filter": False})]
write_overlay_pack(
pack_dir=graph_out / "packs" / "overlay-pack-target",
pack_id="overlay-pack-target",
base_export_id="export-1",
parent_export_id="export-1",
config_hash="config-1",
model_id="model-1",
nodes=[{"id": "skill:pack-target", "label": "pack-target", "type": "skill"}],
edges=[],
tombstones=[],
)
assert mt.load_dashboard_graph() is G
assert calls == [
(graph_file, {"apply_runtime_filter": False}),
(graph_file, {"apply_runtime_filter": False}),
]
def test_graph_service_cache_invalidates_when_pack_overlay_changes(fake_claude: Path) -> None:
import networkx as nx
from ctx.core.graph.graph_packs import write_base_pack, write_overlay_pack
graph_out = fake_claude / "skill-wiki" / "graphify-out"
graph_file = graph_out / "graph.json"
base_graph = nx.Graph()
base_graph.add_node("skill:python-patterns", label="python-patterns", type="skill")
write_base_pack(
pack_dir=graph_out / "packs" / "base-export-1",
pack_id="base-export-1",
base_export_id="export-1",
config_hash="config-1",
model_id="model-1",
graph=base_graph,
)
loaded = [nx.Graph(), nx.Graph()]
calls: list[Path | None] = []
def load_graph(path: Path | None = None, **_kwargs: object):
calls.append(path)
return loaded[min(len(calls) - 1, len(loaded) - 1)]
graph_service.reset_caches()
first = graph_service.load_dashboard_graph(fake_claude / "skill-wiki", load_graph)
second = graph_service.load_dashboard_graph(fake_claude / "skill-wiki", load_graph)
assert first is second
assert calls == [graph_file]
write_overlay_pack(
pack_dir=graph_out / "packs" / "overlay-pack-target",
pack_id="overlay-pack-target",
base_export_id="export-1",
parent_export_id="export-1",
config_hash="config-1",
model_id="model-1",
nodes=[{"id": "skill:pack-target", "label": "pack-target", "type": "skill"}],
edges=[],
tombstones=[],
)
refreshed = graph_service.load_dashboard_graph(fake_claude / "skill-wiki", load_graph)
assert refreshed is loaded[1]
assert calls == [graph_file, graph_file]
def test_graph_neighborhood_uses_dashboard_index_without_full_graph_load(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_graph_manifest(fake_claude, "test-export")
index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
index_path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[
("max_degree", "10"),
("export_id", json.dumps("test-export")),
("nodes_count", "2"),
("edges_count", "1"),
],
)
conn.executemany(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
[
("skill:python-patterns", "python-patterns", "skill", '["python"]', "", 0.9, 0.1, 10),
("skill:fastapi-pro", "fastapi-pro", "skill", '["python","api"]', "", 0.8, 0.0, 4),
],
)
conn.executemany(
"INSERT INTO slug_index VALUES(?,?,?)",
[
("python-patterns", "skill", "skill:python-patterns"),
("fastapi-pro", "skill", "skill:fastapi-pro"),
],
)
payload = zlib.compress(json.dumps([
{
"target": "skill:fastapi-pro",
"weight": 0.8,
"shared_tags": ["python"],
"reasons": ["semantic"],
}
]).encode("utf-8"))
conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:python-patterns", payload))
conn.commit()
finally:
conn.close()
monkeypatch.setattr(
mt,
"load_dashboard_graph",
lambda: (_ for _ in ()).throw(AssertionError("full graph loaded")),
)
result = mt.graph_neighborhood("python-patterns", entity_type="skill")
assert result["center"] == "skill:python-patterns"
assert [node["data"]["id"] for node in result["nodes"]] == [
"skill:python-patterns",
"skill:fastapi-pro",
]
assert result["edges"][0]["data"]["shared_tags"] == ["python"]
assert result["schema"] == {
"name": "ctx.dashboard.graph.neighborhood",
"version": 1,
}
assert result["layout"] == {
"kind": "radial-3d",
"node_size_field": "node_size",
"node_size_min": 8.0,
"node_size_max": 24.0,
"edge_weight_field": "weight",
}
assert result["insights"] == {
"source": "dashboard-index",
"node_count": 2,
"edge_count": 1,
"by_type": {"skill": 2, "agent": 0, "mcp-server": 0, "harness": 0},
"max_degree": 10,
"center_degree": 10,
}
assert "cached dashboard index" in result["explanations"]["source"]
assert "exact or normalized slug" in result["explanations"]["search"]
assert "quality, usage, and graph degree" in result["explanations"]["layout"]
assert "shared_tags" in result["explanations"]["edges"]
assert mt.graph_stats() == {"nodes": 2, "edges": 1, "available": True}
assert mt.wiki_stats() == {
"skills": 2,
"agents": 0,
"mcps": 0,
"harnesses": 0,
"total": 2,
"split_known": True,
}
def test_graph_service_resolves_dashboard_index_center() -> None:
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
try:
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.executemany(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
[
(
"skill:brainstorming",
"Brainstorming",
"skill",
'["creative","planning"]',
"",
0.9,
0.1,
12,
),
(
"skill:multi-agent-brainstorming",
"Multi Agent Brainstorming",
"skill",
'["creative","agents"]',
"",
0.8,
0.0,
4,
),
],
)
conn.executemany(
"INSERT INTO slug_index VALUES(?,?,?)",
[
("brainstorming", "skill", "skill:brainstorming"),
(
"multi-agent-brainstorming",
"skill",
"skill:multi-agent-brainstorming",
),
],
)
conn.commit()
center, resolved, suggestions = graph_service.resolve_index_center(
conn,
"brainstorming",
"skill",
)
assert center == "skill:brainstorming"
assert resolved is None
assert suggestions == ["brainstorming"]
center, resolved, suggestions = graph_service.resolve_index_center(
conn,
"multi brainstorm",
"skill",
)
assert center == "skill:multi-agent-brainstorming"
assert resolved == {
"query": "multi brainstorm",
"slug": "multi-agent-brainstorming",
"id": "skill:multi-agent-brainstorming",
}
assert suggestions == ["multi-agent-brainstorming"]
assert graph_service.resolve_index_center(conn, "../brainstorming", "skill") == (
None,
None,
[],
)
finally:
conn.close()
def test_graph_service_builds_dashboard_index_neighborhood() -> None:
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[("max_degree", "10"), ("top_k", "40")],
)
conn.executemany(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
[
("skill:python-patterns", "python-patterns", "skill", '["python"]', "", 0.9, 0.1, 10),
("skill:fastapi-pro", "fastapi-pro", "skill", '["python","api"]', "", 0.8, 0.0, 4),
],
)
conn.executemany(
"INSERT INTO slug_index VALUES(?,?,?)",
[
("python-patterns", "skill", "skill:python-patterns"),
("fastapi-pro", "skill", "skill:fastapi-pro"),
],
)
payload = zlib.compress(json.dumps([{
"target": "skill:fastapi-pro",
"weight": 0.8,
"shared_tags": ["python"],
"reasons": ["semantic"],
}]).encode("utf-8"))
conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:python-patterns", payload))
conn.commit()
result = graph_service.dashboard_index_neighborhood(
conn,
"python-patterns",
hops=1,
limit=40,
entity_type="skill",
node_size=lambda **_: {
"node_size": 12.0,
"size_signal": 0.25,
"size_reason": "test",
},
score_payload=lambda field, value: {field: value},
)
finally:
conn.close()
assert result is not None
assert result["center"] == "skill:python-patterns"
assert [node["data"]["id"] for node in result["nodes"]] == [
"skill:python-patterns",
"skill:fastapi-pro",
]
assert result["edges"][0]["data"]["shared_tags"] == ["python"]
assert result["schema"]["name"] == "ctx.dashboard.graph.neighborhood"
assert result["insights"]["source"] == "dashboard-index"
def test_graph_service_reads_dashboard_index_stats(tmp_path: Path) -> None:
report = tmp_path / "graph-report.md"
report.write_text("> Nodes: 1,234 | Edges: 5,678 | Communities: 9\n", encoding="utf-8")
assert graph_service.graph_report_stats(report) == {
"nodes": 1234,
"edges": 5678,
"available": True,
}
index_path = tmp_path / "dashboard-neighborhoods.sqlite3"
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[("nodes_count", "3"), ("edges_count", "2")],
)
conn.executemany(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
[
("skill:python-patterns", "python-patterns", "skill", "[]", "", 1.0, 0.0, 2),
("agent:reviewer", "reviewer", "agent", "[]", "", 0.7, 0.0, 1),
("mcp-server:github", "github", "mcp-server", "[]", "", 0.8, 0.0, 1),
],
)
conn.commit()
finally:
conn.close()
assert graph_service.dashboard_index_graph_stats(index_path) == {
"nodes": 3,
"edges": 2,
"available": True,
}
assert graph_service.dashboard_index_wiki_stats(
index_path,
index_matches_manifest=lambda path: path == index_path,
) == {
"skills": 1,
"agents": 1,
"mcps": 1,
"harnesses": 0,
"total": 3,
"split_known": True,
}
assert graph_service.top_degree_seeds_from_index(index_path, limit=2) == [
{
"slug": "python-patterns",
"type": "skill",
"degree": 2,
"label": "python-patterns",
},
{
"slug": "reviewer",
"type": "agent",
"degree": 1,
"label": "reviewer",
},
]
def test_graph_service_reads_graph_store_neighborhood(tmp_path: Path) -> None:
import networkx as nx
from networkx.readwrite import node_link_data
from ctx.core.graph.graph_store import ensure_graph_store
graph_dir = tmp_path / "graphify-out"
graph_dir.mkdir(parents=True)
graph = nx.Graph()
graph.add_node(
"skill:python-patterns",
label="python-patterns",
type="skill",
tags=["python"],
)
graph.add_node(
"skill:fastapi-pro",
label="fastapi-pro",
type="skill",
tags=["python", "api"],
)
graph.add_edge(
"skill:python-patterns",
"skill:fastapi-pro",
weight=0.8,
shared_tags=["python"],
reasons=["semantic"],
)
(graph_dir / "graph.json").write_text(
json.dumps(node_link_data(graph, edges="edges")),
encoding="utf-8",
)
ensure_graph_store(graph_dir, graph_dir / "graph-store.sqlite3")
result = graph_service.graph_store_neighborhood(
graph_dir,
"python-patterns",
hops=1,
limit=40,
entity_type="skill",
node_size=lambda *_args, **_kwargs: {
"node_size": 12.0,
"size_signal": 0.25,
"size_reason": "test",
},
score_payload=lambda field, value: {field: value},
)
assert result is not None
assert result["center"] == "skill:python-patterns"
assert result["insights"]["source"] == "graph-store"
assert [node["data"]["id"] for node in result["nodes"]] == [
"skill:python-patterns",
"skill:fastapi-pro",
]
assert result["edges"][0]["data"]["shared_tags"] == ["python"]
def test_graph_neighborhood_uses_fresh_graph_store_without_full_graph_load(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
from networkx.readwrite import node_link_data
from ctx.core.graph.graph_store import ensure_graph_store
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True, exist_ok=True)
graph = nx.Graph()
graph.add_node(
"skill:python-patterns",
label="python-patterns",
type="skill",
tags=["python"],
)
graph.add_node(
"skill:fastapi-pro",
label="fastapi-pro",
type="skill",
tags=["python", "api"],
)
graph.add_edge(
"skill:python-patterns",
"skill:fastapi-pro",
weight=0.8,
shared_tags=["python"],
reasons=["semantic"],
)
(graph_dir / "graph.json").write_text(
json.dumps(node_link_data(graph, edges="edges")),
encoding="utf-8",
)
ensure_graph_store(graph_dir, graph_dir / "graph-store.sqlite3")
monkeypatch.setattr(
mt,
"load_dashboard_graph",
lambda: (_ for _ in ()).throw(AssertionError("full graph loaded")),
)
result = mt.graph_neighborhood("python-patterns", entity_type="skill")
assert result["center"] == "skill:python-patterns"
assert result["insights"]["source"] == "graph-store"
assert [node["data"]["id"] for node in result["nodes"]] == [
"skill:python-patterns",
"skill:fastapi-pro",
]
assert result["edges"][0]["data"]["shared_tags"] == ["python"]
def test_skillspector_payload_filters_by_tag_and_graph_family(
fake_claude: Path,
) -> None:
_write_graph_manifest(fake_claude, "audit-export")
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[
("export_id", json.dumps("audit-export")),
("max_degree", "10"),
],
)
conn.executemany(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
[
(
"skill:danger-skill",
"Danger Skill",
"skill",
'["security","shell"]',
"Runs shell checks for exfiltration review.",
0.2,
0.0,
9,
),
(
"skill:safe-skill",
"Safe Skill",
"skill",
'["python"]',
"Safe Python helper.",
0.9,
0.1,
2,
),
],
)
conn.commit()
finally:
conn.close()
(graph_dir / "communities.json").write_text(
json.dumps({
"communities": {
"7": {
"label": "Security Tools",
"members": ["skill:danger-skill"],
},
"8": {
"label": "Python Tools",
"members": ["skill:safe-skill"],
},
},
}),
encoding="utf-8",
)
_write_skillspector_audit(fake_claude, [
{
"schema_version": 1,
"slug": "danger-skill",
"status": "blocked",
"risk_score": 99,
"risk_severity": "CRITICAL",
"recommendation": "BLOCK",
"issues": 2,
"components": 1,
"content_sha256": "a" * 64,
"scanned_at": "2026-06-18T00:00:00+00:00",
"scanner": "NVIDIA SkillSpector",
"scanner_repo": "https://github.com/NVIDIA/SkillSpector",
"scanner_version": "2.2.3",
"mode": "static-no-llm",
"llm_requested": False,
"issue_rules": ["exfiltration-risk"],
},
{
"schema_version": 1,
"slug": "safe-skill",
"status": "passed",
"risk_score": 0,
"risk_severity": "LOW",
"recommendation": "SAFE",
"issues": 0,
"components": 1,
"content_sha256": "b" * 64,
"scanned_at": "2026-06-18T00:00:00+00:00",
"scanner": "NVIDIA SkillSpector",
"scanner_repo": "https://github.com/NVIDIA/SkillSpector",
"scanner_version": "2.2.3",
"mode": "static-no-llm",
"llm_requested": False,
"issue_rules": [],
},
])
payload = mt.skillspector_audit_payload({
"q": "exfiltration",
"status": "blocked",
"severity": "CRITICAL",
"tag": "security",
"family": "Security Tools",
"limit": "10",
})
assert payload["summary"]["total"] == 2
assert payload["summary"]["problematic"] == 1
assert payload["summary"]["visible"] == 1
assert payload["records"][0]["slug"] == "danger-skill"
assert payload["records"][0]["family"] == "Security Tools"
assert payload["records"][0]["tags"] == ["security", "shell"]
assert {"value": "security", "count": 1} in payload["filters"]["tags"]
assert {"value": "Security Tools", "count": 1} in payload["filters"]["families"]
def test_skillspector_service_payload_uses_dashboard_metadata(
fake_claude: Path,
) -> None:
_write_graph_manifest(fake_claude, "service-audit-export")
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"INSERT INTO meta VALUES(?,?)",
("export_id", json.dumps("service-audit-export")),
)
conn.execute(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
(
"skill:review-skill",
"Review Skill",
"skill",
'["review","python"]',
"Reviews Python changes.",
0.8,
0.2,
4,
),
)
conn.commit()
finally:
conn.close()
_write_skillspector_audit(fake_claude, [{
"schema_version": 1,
"slug": "review-skill",
"status": "findings",
"risk_score": 80,
"risk_severity": "HIGH",
"recommendation": "REVIEW",
"issues": 1,
"components": 1,
"content_sha256": "c" * 64,
"scanned_at": "2026-06-18T00:00:00+00:00",
"scanner": "NVIDIA SkillSpector",
"scanner_repo": "https://github.com/NVIDIA/SkillSpector",
"scanner_version": "2.2.3",
"mode": "static-no-llm",
"llm_requested": False,
"issue_rules": ["prompt-injection"],
}])
payload = skillspector_service.audit_payload(
fake_claude / "skill-wiki",
mt.repo_graph_dir(),
index_path,
lambda _path: True,
{"q": "python", "limit": "1"},
)
assert payload["audit_available"] is True
assert payload["records"][0]["slug"] == "review-skill"
assert payload["records"][0]["tags"] == ["review", "python"]
assert payload["audit_path"].endswith("skillspector-audit.jsonl.gz")
def test_skillspector_page_and_api_route_render_audit(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_skillspector_audit(fake_claude, [{
"schema_version": 1,
"slug": "review-skill",
"status": "findings",
"risk_score": 80,
"risk_severity": "HIGH",
"recommendation": "REVIEW",
"issues": 1,
"components": 1,
"content_sha256": "c" * 64,
"scanned_at": "2026-06-18T00:00:00+00:00",
"scanner": "NVIDIA SkillSpector",
"scanner_repo": "https://github.com/NVIDIA/SkillSpector",
"scanner_version": "2.2.3",
"mode": "static-no-llm",
"llm_requested": False,
"issue_rules": ["prompt-injection"],
}])
html_out = mt.render_skillspector({"q": "prompt", "severity": "HIGH"})
direct_html = skillspector_page.render_skillspector(
mt.skillspector_audit_payload({"q": "prompt", "severity": "HIGH"}),
layout=lambda _title, body: body,
)
assert "SkillSpector audit" in html_out
assert "/api/skillspector.json" in html_out
assert "review-skill" in html_out
assert "prompt-injection" in html_out
assert "review-skill" in direct_html
assert "prompt-injection" in direct_html
assert "/skillspector" in mt.layout("test", "<p>body</p>")
server, _thread, port = _serve_monitor(monkeypatch)
try:
status, payload = _get_json(port, "/api/skillspector.json?severity=HIGH&q=prompt")
finally:
server.shutdown()
server.server_close()
assert status == 200
assert payload["summary"]["visible"] == 1
assert payload["records"][0]["slug"] == "review-skill"
def test_graph_neighborhood_uses_dashboard_index_when_overlay_is_already_indexed(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_graph_manifest(fake_claude, "test-export")
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
overlay_path = graph_dir / "entity-overlays.jsonl"
graph_dir.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[
("max_degree", "10"),
("top_k", "40"),
("export_id", json.dumps("test-export")),
("nodes_count", "2"),
("edges_count", "1"),
],
)
conn.executemany(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
[
("harness:mirage", "mirage", "harness", '["sandbox"]', "", 0.82, 0.0, 10),
("skill:codex-review", "codex-review", "skill", '["review"]', "", 0.7, 0.0, 5),
],
)
conn.executemany(
"INSERT INTO slug_index VALUES(?,?,?)",
[
("mirage", "harness", "harness:mirage"),
("codex-review", "skill", "skill:codex-review"),
],
)
conn.execute(
"INSERT INTO neighbors VALUES(?,?)",
(
"harness:mirage",
zlib.compress(json.dumps([
{
"target": "skill:codex-review",
"weight": 0.18,
"shared_tags": ["sandbox"],
},
]).encode("utf-8")),
),
)
conn.commit()
finally:
conn.close()
overlay_path.write_text(
json.dumps({
"overlay_id": "mirage-overlay",
"nodes": [{"id": "harness:mirage", "type": "harness"}],
"edges": [{"source": "harness:mirage", "target": "skill:codex-review"}],
})
+ "\n",
encoding="utf-8",
)
monkeypatch.setattr(mt, "dashboard_overlay_matches_known_release", lambda overlay: False)
monkeypatch.setattr(
mt,
"load_dashboard_graph",
lambda: (_ for _ in ()).throw(AssertionError("full graph loaded")),
)
result = mt.graph_neighborhood("mirage", entity_type="harness")
assert result["center"] == "harness:mirage"
assert [node["data"]["id"] for node in result["nodes"]] == [
"harness:mirage",
"skill:codex-review",
]
def test_dashboard_overlay_release_hash_normalizes_crlf(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
overlay = tmp_path / "entity-overlays.jsonl"
overlay.write_bytes(b'{"overlay_id":"release"}\r\n')
expected = hashlib.sha256(b'{"overlay_id":"release"}\n').hexdigest()
monkeypatch.setattr(ci, "_GRAPH_ENTITY_OVERLAY_SHA256", expected)
assert graph_service.dashboard_overlay_matches_known_release(overlay)
assert mt.dashboard_overlay_matches_known_release(overlay)
def test_graph_neighborhood_bypasses_index_for_local_overlay_even_when_node_exists(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
_write_graph_manifest(fake_claude, "test-export")
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
overlay_path = graph_dir / "entity-overlays.jsonl"
graph_dir.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[
("max_degree", "10"),
("top_k", "40"),
("export_id", json.dumps("test-export")),
("nodes_count", "1"),
("edges_count", "0"),
],
)
conn.execute(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
("skill:existing", "existing", "skill", "[]", "", 0.7, 0.0, 0),
)
conn.execute(
"INSERT INTO slug_index VALUES(?,?,?)",
("existing", "skill", "skill:existing"),
)
conn.execute(
"INSERT INTO neighbors VALUES(?,?)",
("skill:existing", zlib.compress(b"[]")),
)
conn.commit()
finally:
conn.close()
overlay_path.write_text(
json.dumps({
"kind": "ann_attach",
"nodes": [{"id": "skill:existing", "type": "skill"}],
"edges": [{"source": "skill:existing", "target": "skill:new-runtime-edge"}],
})
+ "\n",
encoding="utf-8",
)
G = nx.Graph()
G.add_node("skill:existing", label="existing", type="skill", tags=[])
graph_loads = 0
def load_graph():
nonlocal graph_loads
graph_loads += 1
return G
monkeypatch.setattr(mt, "load_dashboard_graph", load_graph)
result = mt.graph_neighborhood("existing", entity_type="skill")
assert result["center"] == "skill:existing"
assert graph_loads == 1
def test_graph_index_honors_requested_type_on_exact_slug(
fake_claude: Path,
) -> None:
_write_graph_manifest(fake_claude, "test-export")
index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
index_path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[("max_degree", "1"), ("top_k", "40"), ("export_id", json.dumps("test-export"))],
)
conn.executemany(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
[
("skill:github", "github", "skill", "[]", "", None, None, 0),
("mcp-server:github", "github", "mcp-server", "[]", "", None, None, 0),
],
)
conn.executemany(
"INSERT INTO slug_index VALUES(?,?,?)",
[
("github", "skill", "skill:github"),
("github", "mcp-server", "mcp-server:github"),
],
)
conn.executemany(
"INSERT INTO neighbors VALUES(?,?)",
[
("skill:github", zlib.compress(b"[]")),
("mcp-server:github", zlib.compress(b"[]")),
],
)
conn.commit()
finally:
conn.close()
result = mt.graph_neighborhood("github", entity_type="skill")
assert result["center"] == "skill:github"
def test_graph_index_matches_fuzzy_slug_resolution(
fake_claude: Path,
) -> None:
_write_graph_manifest(fake_claude, "test-export")
index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
index_path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[("max_degree", "1"), ("top_k", "40"), ("export_id", json.dumps("test-export"))],
)
conn.execute(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
("skill:github-actions", "GitHub Actions", "skill", '["ci"]', "", None, None, 0),
)
conn.execute(
"INSERT INTO slug_index VALUES(?,?,?)",
("github-actions", "skill", "skill:github-actions"),
)
conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:github-actions", zlib.compress(b"[]")))
conn.commit()
finally:
conn.close()
result = mt.graph_neighborhood("git hub", entity_type="skill")
assert result["center"] == "skill:github-actions"
assert result["resolved"]["slug"] == "github-actions"
def test_entity_subgraph_script_json_escapes_script_end_tag() -> None:
graph_html = mt.render_entity_subgraph_svg(
center="skill:evil",
node_by_id={
"skill:evil": {
"label": "</script><script>alert(1)</script>",
"type": "skill",
},
},
edges=[],
sidecar_by_id={},
)
assert "</script><script>alert(1)</script>" not in graph_html
assert "<\\/script>" in graph_html
def test_entity_subgraph_wrapper_matches_extracted_wiki_renderer() -> None:
node_by_id = {
"skill:github": {"label": "GitHub", "type": "skill", "degree": 7},
"mcp-server:github-api": {"label": "GitHub API", "type": "mcp-server", "degree": 3},
}
edges = [
{
"data": {
"source": "skill:github",
"target": "mcp-server:github-api",
"weight": 0.82,
"shared": ["github"],
},
},
]
wrapper_html = mt.render_entity_subgraph_svg(
node_by_id=node_by_id,
edges=edges,
center="skill:github",
sidecar_by_id={},
)
direct_html = wiki_page.render_entity_subgraph_svg(
node_by_id=node_by_id,
edges=edges,
center="skill:github",
sidecar_by_id={},
graph_type_from_node_id=mt.graph_type_from_node_id,
graph_slug_from_node_id=mt.graph_slug_from_node_id,
display_label=mt.display_label,
display_slug=mt.display_slug,
entity_wiki_href=mt.entity_wiki_href,
json_for_script=mt.json_for_script,
)
assert wrapper_html == direct_html
assert "/wiki/github-api?type=mcp-server" in wrapper_html
assert "mcp-server" in wrapper_html
def test_entity_subgraph_page_renderer_uses_injected_graph_dependencies() -> None:
graph = {
"center": "skill:github",
"nodes": [
{"data": {"id": "skill:github", "label": "GitHub", "type": "skill"}},
{
"data": {
"id": "mcp-server:github-api",
"label": "GitHub API",
"type": "mcp-server",
},
},
],
"edges": [
{
"data": {
"source": "skill:github",
"target": "mcp-server:github-api",
"weight": 0.82,
"shared_tags": ["github"],
},
},
],
}
html_out = wiki_page.render_entity_subgraph(
"github",
"skill",
graph_neighborhood=lambda *_args, **_kwargs: graph,
graph_type_from_node_id=mt.graph_type_from_node_id,
graph_slug_from_node_id=mt.graph_slug_from_node_id,
subgraph_sidecar=lambda slug, _entity_type: {
"grade": "A",
"raw_score": 0.91,
}
if slug == "github-api"
else None,
display_label=mt.display_label,
display_slug=mt.display_slug,
entity_wiki_href=mt.entity_wiki_href,
json_for_script=mt.json_for_script,
)
assert "1-hop neighborhood" in html_out
assert "/wiki/github-api?type=mcp-server" in html_out
assert "github" in html_out
assert "grade-A" in html_out
def test_graph_page_initial_query_escapes_script_end_tag() -> None:
html_out = mt.render_graph("</script><script>alert(1)</script>")
assert "const initial = \"<\\/script>" in html_out
assert "const initial = \"</script>" not in html_out
def test_graph_neighborhood_extracts_missing_dashboard_index_from_archive(
fake_claude: Path,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
seed = tmp_path / "dashboard-neighborhoods.sqlite3"
conn = sqlite3.connect(seed)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[
("max_degree", "10"),
("export_id", json.dumps("archive-export")),
("nodes_count", "1"),
("edges_count", "0"),
("top_k", "40"),
],
)
conn.execute(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
("skill:python-patterns", "python-patterns", "skill", '["python"]', "", 0.9, 0.1, 10),
)
conn.execute(
"INSERT INTO slug_index VALUES(?,?,?)",
("python-patterns", "skill", "skill:python-patterns"),
)
conn.execute(
"INSERT INTO neighbors VALUES(?,?)",
("skill:python-patterns", zlib.compress(b"[]")),
)
conn.commit()
finally:
conn.close()
manifest = fake_claude / "skill-wiki" / "graphify-out" / "graph-export-manifest.json"
manifest.parent.mkdir(parents=True)
manifest.write_text(
json.dumps({"version": 1, "export_id": "archive-export"}),
encoding="utf-8",
)
archive = tmp_path / "wiki-graph-runtime.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
monkeypatch.setattr(mt, "dashboard_graph_index_archives", lambda: [archive])
monkeypatch.setattr(mt, "packaged_graph_export_id", lambda: "archive-export")
monkeypatch.setattr(
mt,
"load_dashboard_graph",
lambda: (_ for _ in ()).throw(AssertionError("full graph loaded")),
)
result = mt.graph_neighborhood("python-patterns", entity_type="skill")
assert result["center"] == "skill:python-patterns"
assert (fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3").is_file()
def test_dashboard_index_extraction_skips_archive_export_mismatch(
fake_claude: Path,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True)
(graph_dir / "graph-export-manifest.json").write_text(
json.dumps({"version": 1, "export_id": "local-export"}),
encoding="utf-8",
)
manifest = tmp_path / "graph-export-manifest.json"
manifest.write_text(
json.dumps({"version": 1, "export_id": "archive-export"}),
encoding="utf-8",
)
seed = tmp_path / "dashboard-neighborhoods.sqlite3"
seed.write_bytes(b"should-not-be-extracted")
archive = tmp_path / "wiki-graph-runtime.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
tar.add(manifest, arcname="./graphify-out/graph-export-manifest.json")
tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
assert graph_service.archive_graph_export_id(archive) == "archive-export"
monkeypatch.setattr(mt, "dashboard_graph_index_archives", lambda: [archive])
monkeypatch.setattr(mt, "packaged_graph_export_id", lambda: None)
monkeypatch.setattr(
mt,
"dashboard_index_matches_manifest",
lambda path: (_ for _ in ()).throw(
AssertionError(f"should not validate extracted index: {path}"),
),
)
assert mt.ensure_dashboard_graph_index() is None
assert not (graph_dir / "dashboard-neighborhoods.sqlite3").exists()
def test_dashboard_index_extraction_skips_packaged_export_mismatch(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True)
(graph_dir / "graph-export-manifest.json").write_text(
json.dumps({"version": 1, "export_id": "old-local-export"}),
encoding="utf-8",
)
monkeypatch.setattr(mt, "packaged_graph_export_id", lambda: "new-packaged-export")
monkeypatch.setattr(
mt,
"dashboard_graph_index_archives",
lambda: (_ for _ in ()).throw(AssertionError("archive scan should be skipped")),
)
assert mt.ensure_dashboard_graph_index() is None
def test_graph_neighborhood_uses_local_graph_on_packaged_export_mismatch(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True)
(graph_dir / "graph-export-manifest.json").write_text(
json.dumps({"version": 1, "export_id": "old-local-export"}),
encoding="utf-8",
)
monkeypatch.setattr(mt, "packaged_graph_export_id", lambda: "new-packaged-export")
G = nx.Graph()
G.add_node("mcp-server:github", label="GitHub", type="mcp-server", tags=["git"])
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: G)
result = mt.graph_neighborhood("github", entity_type="mcp-server")
assert result["center"] == "mcp-server:github"
assert result["nodes"][0]["data"]["type"] == "mcp-server"
def test_dashboard_index_extraction_works_with_installed_graph_report(
fake_claude: Path,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True)
(graph_dir / "graph-export-manifest.json").write_text(
json.dumps({"version": 1, "export_id": "local-export"}),
encoding="utf-8",
)
(graph_dir / "graph-report.md").write_text(
"> Nodes: 12 | Edges: 34 | Communities: 2\n",
encoding="utf-8",
)
seed = tmp_path / "dashboard-neighborhoods.sqlite3"
conn = sqlite3.connect(seed)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute("INSERT INTO meta VALUES(?,?)", ("export_id", json.dumps("local-export")))
conn.commit()
finally:
conn.close()
archive_manifest = tmp_path / "graph-export-manifest.json"
archive_manifest.write_text(
json.dumps({"version": 1, "export_id": "local-export"}),
encoding="utf-8",
)
archive = tmp_path / "wiki-graph-runtime.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
tar.add(archive_manifest, arcname="./graphify-out/graph-export-manifest.json")
tar.add(seed, arcname="./graphify-out/dashboard-neighborhoods.sqlite3")
monkeypatch.setattr(mt, "dashboard_graph_index_archives", lambda: [archive])
monkeypatch.setattr(mt, "packaged_graph_export_id", lambda: "local-export")
wiki_dir = fake_claude / "skill-wiki"
assert graph_service.dashboard_graph_index_path(wiki_dir) == (
graph_dir / "dashboard-neighborhoods.sqlite3"
)
assert graph_service.dashboard_graph_manifest_export_id(wiki_dir) == "local-export"
assert graph_service.dashboard_index_matches_manifest(seed, wiki_dir)
assert mt.ensure_dashboard_graph_index() == graph_dir / "dashboard-neighborhoods.sqlite3"
def test_graph_neighborhood_bypasses_archive_index_when_runtime_overlays_exist(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
overlay = fake_claude / "skill-wiki" / "graphify-out" / "entity-overlays.jsonl"
overlay.parent.mkdir(parents=True)
overlay.write_text('{"source":"test"}\n', encoding="utf-8")
monkeypatch.setattr(
mt,
"dashboard_graph_index_archives",
lambda: (_ for _ in ()).throw(AssertionError("archive index should be bypassed")),
)
G = nx.Graph()
G.add_node("skill:local-overlay", label="local-overlay", type="skill", tags=["local"])
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: G)
result = mt.graph_neighborhood("local-overlay", entity_type="skill")
assert result["center"] == "skill:local-overlay"
def test_graph_neighborhood_rejects_stale_dashboard_index(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True)
(graph_dir / "graph-export-manifest.json").write_text(
json.dumps({"version": 1, "export_id": "new-export"}),
encoding="utf-8",
)
index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany("INSERT INTO meta VALUES(?,?)", [("export_id", json.dumps("old-export"))])
conn.commit()
finally:
conn.close()
G = nx.Graph()
G.add_node("skill:fallback", label="fallback", type="skill", tags=[])
monkeypatch.setattr(mt, "packaged_graph_export_id", lambda: None)
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: G)
result = mt.graph_neighborhood("fallback", entity_type="skill")
assert result["center"] == "skill:fallback"
assert not index_path.exists()
def test_graph_neighborhood_rejects_orphan_dashboard_index_without_manifest(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import networkx as nx
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True)
index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.executemany("INSERT INTO meta VALUES(?,?)", [("export_id", json.dumps("old-export"))])
conn.commit()
finally:
conn.close()
G = nx.Graph()
G.add_node("skill:fallback", label="fallback", type="skill", tags=[])
monkeypatch.setattr(mt, "load_dashboard_graph", lambda: G)
result = mt.graph_neighborhood("fallback", entity_type="skill")
assert result["center"] == "skill:fallback"
assert not index_path.exists()
def test_graph_index_node_size_uses_live_sidecar_when_scores_missing(
fake_claude: Path,
) -> None:
_write_graph_manifest(fake_claude, "test-export")
_write_sidecar(fake_claude, "python-patterns", {
"slug": "python-patterns",
"subject_type": "skill",
"grade": "A",
"score": 1.0,
"signals": {"telemetry": {"score": 1.0}},
})
index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
index_path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.execute(
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
"PRIMARY KEY(slug,type,node_id))"
)
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[("max_degree", "1"), ("top_k", "40"), ("export_id", json.dumps("test-export"))],
)
conn.execute(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
("skill:python-patterns", "python-patterns", "skill", "[]", "", None, None, 0),
)
conn.execute(
"INSERT INTO slug_index VALUES(?,?,?)",
("python-patterns", "skill", "skill:python-patterns"),
)
conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:python-patterns", zlib.compress(b"[]")))
conn.commit()
finally:
conn.close()
result = mt.graph_neighborhood("python-patterns", entity_type="skill")
node = result["nodes"][0]["data"]
assert node["size_signal"] > 0.7
assert "quality 1.000" in node["size_reason"]
assert "usage 1.000" in node["size_reason"]
def test_graph_neighborhood_empty_when_graph_absent(
fake_claude: Path,
monkeypatch,
) -> None:
# Force load_graph to raise so the helper returns the empty shape
# deterministically, independent of whether the user's graph is built.
def _bad(*_a, **_k):
raise RuntimeError("no graph")
# resolve_graph may be imported lazily inside _graph_neighborhood — force
# the import to yield a stub that raises.
import sys
fake = type("M", (), {"load_graph": _bad})
# ctx.monitor.compat lazy-imports 'from ctx.core.graph.resolve_graph import load_graph'
# at call time; inject at the canonical dotted path so the lazy import
# resolves to our stub. Also populate the legacy shim path belt-and-
# braces in case a downstream path still routes through it.
monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake)
monkeypatch.setitem(sys.modules, "resolve_graph", fake)
result = mt.graph_neighborhood("python-patterns")
assert result == {"nodes": [], "edges": [], "center": None}
def test_render_home_shows_stat_grid_even_with_no_sessions(fake_claude: Path) -> None:
"""The previous home page was near-blank when the user had no sessions.
The rc11 layout must show the six stat cards + grade pills + empty-state
messages so the page never feels empty."""
html_out = mt.render_home()
# Six stat-card titles must all be present regardless of data volume.
for label in ("Currently loaded", "Sidecars", "Wiki entities",
"Knowledge graph", "Audit events", "Sessions"):
assert label in html_out
# Links into each section.
for href in ("/loaded", "/skills", "/graph", "/logs", "/events", "/sessions"):
assert href in html_out
# Grade pills always render (values may be zero).
for grade in ("A", "B", "C", "D", "F"):
assert f"grade-{grade}" in html_out
# Empty-state copy kicks in when there are no sessions / audit entries.
assert "No sessions recorded" in html_out or "Recent sessions" in html_out
def test_render_home_formats_large_counts_with_commas(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(mt, "summarize_sessions", lambda: [])
monkeypatch.setattr(mt, "read_manifest", lambda: {"load": [None] * 10000})
monkeypatch.setattr(mt, "read_jsonl", lambda *_args, **_kwargs: [])
monkeypatch.setattr(mt, "graph_stats", lambda: {
"nodes": 79958,
"edges": 1778069,
"available": True,
})
monkeypatch.setattr(mt, "wiki_stats", lambda: {
"skills": 68494,
"agents": 467,
"mcps": 10790,
"harnesses": 207,
"total": 79958,
"split_known": True,
})
monkeypatch.setattr(mt, "runtime_lifecycle_summary", lambda: {
"validations_total": 10000,
"validation_failures": 1000,
"open_escalations_total": 100,
})
html_out = mt.render_home()
assert ">10,000</div>" in html_out
assert ">79,958</div>" in html_out
assert "1,778,069 edges" in html_out
assert "68,494 skills" in html_out
assert "10,790 MCPs" in html_out
assert "10000</div>" not in html_out
assert "100000</div>" not in html_out
def test_render_home_defers_sidecar_grade_scan(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
def fail_scan() -> dict[str, int]:
raise AssertionError("home page should not synchronously scan sidecars")
monkeypatch.setattr(mt, "grade_distribution", fail_scan)
html_out = mt.render_home()
assert "/api/grades.json" in html_out
assert "home-sidecar-count" in html_out
assert "data-home-grade='A'" in html_out
def test_api_grades_reuses_kpi_summary_without_sidecar_scan() -> None:
class Summary:
def to_dict(self) -> dict[str, object]:
return {"grade_counts": {"A": 2, "B": 1, "F": 4}}
def fail_scan() -> dict[str, object]:
raise AssertionError("grades API should reuse the cached KPI summary")
response = readonly_api.handle_readonly_route(
"api_grades",
{},
{},
readonly_api.ReadOnlyApiDeps(
summarize_sessions=lambda: {},
read_manifest=lambda: {},
status_payload=lambda: {},
kpi_summary=lambda: Summary(),
grade_distribution_payload=fail_scan,
sidecar_page_payload=lambda _qs: {},
runtime_lifecycle_summary=lambda: {},
skillspector_audit_payload=lambda _qs: {},
effective_config_payload=lambda: {},
search_wiki_entities=lambda _q, _type, _limit: [],
wiki_entity_detail=lambda _slug, _type: None,
load_sidecar=lambda _slug, _type: None,
graph_neighborhood=lambda _slug, _hops, _limit, _type: {},
normalize_dashboard_entity_type=lambda raw: raw,
),
)
assert response is not None
assert response.payload == {
"grades": {"A": 2, "B": 1, "C": 0, "D": 0, "F": 4},
"total": 7,
}
def test_render_skills_emits_sidebar_filters(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "a", {"slug": "a", "grade": "A", "raw_score": 0.9,
"subject_type": "skill"})
_write_sidecar(fake_claude, "b", {"slug": "b", "grade": "F", "raw_score": 0.1,
"subject_type": "agent",
"hard_floor": "intake_fail"})
html_out = mt.render_skills()
# Sidebar must expose text search plus grade/type filters.
assert "id='skill-search'" in html_out
assert "class='grade-filter'" in html_out
assert "class='type-filter'" in html_out
# Cards, not a legacy table-row element.
assert "class='skill-card'" in html_out
# Per-card links to sidecar/wiki/graph drill-downs.
assert ">sidecar</a>" in html_out
assert ">wiki</a>" in html_out
assert ">graph</a>" in html_out
def test_render_skills_paginates_sidecar_page(fake_claude: Path) -> None:
for slug in ("a", "b", "c"):
_write_sidecar(fake_claude, slug, {
"slug": slug,
"grade": "A",
"raw_score": 0.9,
"subject_type": "skill",
})
html_out = mt.render_skills({"limit": "2"})
assert "Showing 1-2 of 3 sidecars" in html_out
assert "next</a>" in html_out
assert "a</code>" in html_out
assert "b</code>" in html_out
assert "c</code>" not in html_out
def test_sidecar_page_payload_searches_full_catalog(fake_claude: Path) -> None:
for slug in ("alpha-review", "beta-build", "gamma-review"):
_write_sidecar(fake_claude, slug, {
"slug": slug,
"grade": "A",
"raw_score": 0.9,
"subject_type": "skill",
})
payload = mt.sidecar_page_payload({"q": "review", "limit": "1"})
assert payload["total"] == 2
assert payload["pages"] == 2
assert [item["slug"] for item in payload["items"]] == ["alpha-review"]
def test_sidecar_page_payload_filters_type_grade_and_floor(fake_claude: Path) -> None:
_write_sidecar(fake_claude, "agent-a", {
"slug": "agent-a",
"grade": "A",
"raw_score": 0.9,
"subject_type": "agent",
})
_write_sidecar(fake_claude, "skill-a", {
"slug": "skill-a",
"grade": "A",
"raw_score": 0.9,
"subject_type": "skill",
})
_write_sidecar(fake_claude, "agent-floored", {
"slug": "agent-floored",
"grade": "A",
"raw_score": 0.9,
"subject_type": "agent",
"hard_floor": "intake_fail",
})
payload = mt.sidecar_page_payload({
"type": "agent",
"grade": "A",
"hide_floor": "1",
})
assert payload["total"] == 1
assert payload["items"][0]["slug"] == "agent-a"
def test_sidecar_page_payload_reuses_cached_search_records(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
for slug in ("alpha-review", "beta-review"):
_write_sidecar(fake_claude, slug, {
"slug": slug,
"grade": "A",
"raw_score": 0.9,
"subject_type": "skill",
})
original_read = sidecar_service.read_sidecar_file
reads = 0
def counting_read(path: Path) -> dict | None:
nonlocal reads
reads += 1
return original_read(path)
monkeypatch.setattr(sidecar_service, "read_sidecar_file", counting_read)
first = mt.sidecar_page_payload({"q": "review"})
reads_after_first_search = reads
second = mt.sidecar_page_payload({"q": "review"})
assert [item["slug"] for item in first["items"]] == ["alpha-review", "beta-review"]
assert [item["slug"] for item in second["items"]] == ["alpha-review", "beta-review"]
assert reads_after_first_search == 2
assert reads == reads_after_first_search
_write_sidecar(fake_claude, "delta-review", {
"slug": "delta-review",
"grade": "A",
"raw_score": 0.8,
"subject_type": "skill",
})
refreshed = mt.sidecar_page_payload({"q": "delta"})
assert [item["slug"] for item in refreshed["items"]] == ["delta-review"]
assert reads > reads_after_first_search
def test_sidecar_page_payload_cache_invalidates_on_file_rewrite(
fake_claude: Path,
) -> None:
path = fake_claude / "skill-quality" / "alpha-review.json"
path.write_text(
json.dumps({
"slug": "alpha-review",
"grade": "A",
"raw_score": 0.9,
"subject_type": "skill",
}),
encoding="utf-8",
)
first = mt.sidecar_page_payload({"q": "review"})
assert first["items"][0]["grade"] == "A"
path.write_text(
json.dumps({
"slug": "alpha-review",
"grade": "F",
"raw_score": 0.1,
"subject_type": "skill",
"notes": "changed content to force a different cache signature size",
}),
encoding="utf-8",
)
second = mt.sidecar_page_payload({"q": "review"})
assert second["items"][0]["grade"] == "F"
def test_sidecars_api_applies_route_filters_and_limit_bounds(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_sidecar(fake_claude, "review-agent-a", {
"slug": "review-agent-a",
"grade": "A",
"raw_score": 0.9,
"subject_type": "agent",
})
_write_sidecar(fake_claude, "review-agent-floored", {
"slug": "review-agent-floored",
"grade": "A",
"raw_score": 0.8,
"subject_type": "agent",
"hard_floor": "never_load_stale",
})
_write_sidecar(fake_claude, "review-skill", {
"slug": "review-skill",
"grade": "A",
"raw_score": 0.7,
"subject_type": "skill",
})
_write_sidecar(fake_claude, "review-agent-b", {
"slug": "review-agent-b",
"grade": "B",
"raw_score": 0.95,
"subject_type": "agent",
})
direct = readonly_api.handle_readonly_route(
"api_sidecars",
{},
{"q": "review", "type": "agent", "grade": "A", "hide_floor": "1", "limit": "1"},
readonly_api.ReadOnlyApiDeps(
summarize_sessions=lambda: {},
read_manifest=lambda: {},
status_payload=lambda: {},
kpi_summary=lambda: None,
grade_distribution_payload=lambda: {},
sidecar_page_payload=mt.sidecar_page_payload,
runtime_lifecycle_summary=lambda: {},
skillspector_audit_payload=lambda _qs: {},
effective_config_payload=lambda: {},
search_wiki_entities=lambda _q, _type, _limit: [],
wiki_entity_detail=lambda _slug, _type: None,
load_sidecar=lambda _slug, _type: None,
graph_neighborhood=lambda _slug, _hops, _limit, _type: {},
normalize_dashboard_entity_type=lambda raw: raw,
),
)
assert direct is not None
assert direct.status == 200
assert direct.payload["limit"] == 1
assert [item["slug"] for item in direct.payload["items"]] == ["review-agent-a"]
server, thread, port = _serve_monitor(monkeypatch)
try:
status, payload = _get_json(
port,
"/api/sidecars.json?q=review&type=agent&grade=A&hide_floor=1&limit=1",
)
assert status == 200
assert payload["total"] == 1
assert payload["limit"] == 1
assert payload["filtered"] is True
assert payload["types"] == ["agent"]
assert payload["grades"] == ["A"]
assert payload["hide_floor"] is True
assert [item["slug"] for item in payload["items"]] == ["review-agent-a"]
status, floor_payload = _get_json(port, "/api/sidecars.json?limit=0")
assert status == 200
assert floor_payload["limit"] == 1
assert len(floor_payload["items"]) == 1
status, capped_payload = _get_json(port, "/api/sidecars.json?limit=9999")
assert status == 200
assert capped_payload["limit"] == 500
finally:
server.shutdown()
thread.join(timeout=5)
server.server_close()
def test_render_wiki_index_lists_entities(fake_claude: Path) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
agents_dir = fake_claude / "skill-wiki" / "entities" / "agents"
skills_dir.mkdir(parents=True)
agents_dir.mkdir(parents=True)
(skills_dir / "python-patterns.md").write_text(
"---\nname: python-patterns\ntype: skill\n"
"description: Idiomatic Python patterns\ntags: [python, patterns]\n"
"---\n# body\n",
encoding="utf-8",
)
(agents_dir / "code-reviewer.md").write_text(
"---\nname: code-reviewer\ntype: agent\n"
"description: Reviews code for issues\ntags: [review, quality]\n"
"---\n# body\n",
encoding="utf-8",
)
html_out = mt.render_wiki_index()
direct_out = wiki_page.render_wiki_index_page(
entries=[{
"slug": "python-patterns",
"display_slug": "python-patterns",
"type": "skill",
"description": "Idiomatic Python patterns",
"tags": ["python", "patterns"],
"search_tags": ["python", "patterns"],
}],
selected_type=None,
initial_query="python",
total_available=1,
type_counts={"skill": 1, "agent": 0, "mcp-server": 0, "harness": 0},
grade_by_key={("python-patterns", "skill"): "A"},
dashboard_entity_types=mt.DASHBOARD_ENTITY_TYPES,
layout=lambda _title, body: body,
)
# Both entities render as cards with their slug.
assert "python-patterns" in html_out
assert "python-patterns" in direct_out
assert "grade-A" in direct_out
assert "code-reviewer" in html_out
# Descriptions surface on the card.
assert "Idiomatic Python patterns" in html_out
assert "Reviews code for issues" in html_out
# Search + type filter must be present.
assert "id='wiki-search'" in html_out
assert "class='wiki-type-filter'" in html_out
# Cards link to the typed per-entity wiki page so duplicate slugs can
# disambiguate skill/agent/MCP/harness pages.
assert "href='/wiki/python-patterns?type=skill'" in html_out
assert "href='/wiki/code-reviewer?type=agent'" in html_out
def test_render_wiki_index_wrapper_matches_extracted_orchestration(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
(skills_dir / "python-patterns.md").write_text(
"---\nname: python-patterns\ntype: skill\n"
"description: Idiomatic Python patterns\ntags: [python, patterns]\n"
"---\n# body\n",
encoding="utf-8",
)
monkeypatch.setattr(mt, "wiki_render_cache_key", lambda _type, _query: None)
wrapper_html = mt.render_wiki_index(query="python")
direct_html = wiki_page.render_wiki_index(
query="python",
normalize_dashboard_entity_type=mt.normalize_dashboard_entity_type,
wiki_render_cache_key=mt.wiki_render_cache_key,
read_memory_cache=mt.wiki_render_memory_cache_get,
write_memory_cache=mt.wiki_render_memory_cache_set,
disk_cache_token=mt.cache_service.disk_cache_token,
read_html_disk_cache=mt.cache_service.read_html_disk_cache,
write_html_disk_cache=mt.cache_service.write_html_disk_cache,
wiki_render_disk_cache_path=mt.wiki_render_disk_cache_path,
wiki_index_entries=mt.wiki_index_entries,
search_wiki_entities=mt.search_wiki_entities,
wiki_stats=mt.wiki_stats,
load_sidecar=mt.load_sidecar,
dashboard_entity_types=mt.DASHBOARD_ENTITY_TYPES,
layout=mt.layout,
)
assert wrapper_html == direct_html
assert "python-patterns" in wrapper_html
def test_wiki_index_entries_use_dashboard_index_without_markdown_pages(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_write_graph_manifest(fake_claude, "test-export")
graph_dir = fake_claude / "skill-wiki" / "graphify-out"
graph_dir.mkdir(parents=True, exist_ok=True)
index_path = graph_dir / "dashboard-neighborhoods.sqlite3"
conn = sqlite3.connect(index_path)
try:
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
conn.execute(
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
)
conn.executemany(
"INSERT INTO meta VALUES(?,?)",
[
("export_id", json.dumps("test-export")),
("nodes_count", "2"),
("edges_count", "0"),
],
)
conn.executemany(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
[
(
"skill:python-patterns",
"python-patterns",
"skill",
'["python","patterns"]',
"Idiomatic Python patterns",
0.9,
0.1,
5,
),
(
"agent:code-reviewer",
"code-reviewer",
"agent",
'["review","quality"]',
"Reviews code for issues",
0.8,
0.1,
4,
),
],
)
conn.commit()
finally:
conn.close()
entries = mt.wiki_index_entries(limit_per_type=10)
slugs = {entry["slug"] for entry in entries}
assert slugs == {"python-patterns", "code-reviewer"}
assert entries[0]["description"] == "Idiomatic Python patterns"
assert wiki_service.index_entries(
fake_claude / "skill-wiki",
index_path,
limit_per_type=10,
index_matches_manifest=lambda path: path == index_path,
) == entries
assert wiki_service.search_entities_from_index(
index_path,
"python",
"skill",
limit=5,
index_matches_manifest=lambda path: path == index_path,
) == [{
"slug": "python-patterns",
"display_slug": "python-patterns",
"type": "skill",
"title": "python-patterns",
"description": "Idiomatic Python patterns",
"tags": ["python", "patterns"],
"path": "",
"href": "/wiki/python-patterns?type=skill",
"quality_score": 0.9,
"usage_score": 0.1,
"degree": 5,
}]
def fail_sidecar_probe(*args: object, **kwargs: object) -> object:
raise AssertionError("index-backed wiki catalog should not probe sidecars")
monkeypatch.setattr(mt, "load_sidecar", fail_sidecar_probe)
html_out = mt.render_wiki_index(query="python")
assert "href='/wiki/python-patterns?type=skill'" in html_out
assert "Idiomatic Python patterns" in html_out
assert "grade-A" in html_out
assert (fake_claude / ".ctx-monitor-wiki-cache.json").is_file()
monkeypatch.setattr(mt, "WIKI_RENDER_CACHE_KEY", None)
monkeypatch.setattr(mt, "WIKI_RENDER_CACHE_VALUE", None)
def fail_entry_rebuild(*args: object, **kwargs: object) -> object:
raise AssertionError("fresh process should read the rendered wiki cache")
monkeypatch.setattr(mt, "wiki_index_entries", fail_entry_rebuild)
assert mt.render_wiki_index(query="python") == html_out
def test_render_wiki_index_query_uses_bounded_search(
monkeypatch: pytest.MonkeyPatch,
) -> None:
def fail_catalog_rebuild(*args: object, **kwargs: object) -> object:
raise AssertionError("queried catalog should use bounded search results")
monkeypatch.setattr(mt, "wiki_index_entries", fail_catalog_rebuild)
monkeypatch.setattr(
mt,
"search_wiki_entities",
lambda query, entity_type=None, limit=80: [{
"slug": "code-reviewer",
"display_slug": "code-reviewer",
"type": entity_type or "agent",
"description": f"{query} result",
"tags": ["review"],
"search_tags": ["review"],
}],
)
html_out = mt.render_wiki_index(entity_type="agent", query="review")
assert "code-reviewer" in html_out
assert "review result" in html_out
assert "href='/wiki/code-reviewer?type=agent'" in html_out
def test_render_wiki_index_supports_type_query_and_autocomplete(fake_claude: Path) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
agents_dir = fake_claude / "skill-wiki" / "entities" / "agents"
skills_dir.mkdir(parents=True)
agents_dir.mkdir(parents=True)
(skills_dir / "python-patterns.md").write_text(
"---\ntype: skill\ndescription: Python work\ntags: [python]\n---\n# body\n",
encoding="utf-8",
)
(agents_dir / "code-reviewer.md").write_text(
"---\ntype: agent\ndescription: Review work\ntags: [review]\n---\n# body\n",
encoding="utf-8",
)
html_out = mt.render_wiki_index(entity_type="agent", query="review")
assert "id='wiki-entity-suggestions'" in html_out
assert "value='code-reviewer'" in html_out
assert 'wsearch.value = "review";' in html_out
assert "href='/wiki?type=agent'" in html_out
assert "value='agent' checked" in html_out
assert "value='skill' checked" not in html_out
def test_catalog_route_serves_searchable_wiki_catalog(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
agents_dir = fake_claude / "skill-wiki" / "entities" / "agents"
agents_dir.mkdir(parents=True)
(agents_dir / "code-reviewer.md").write_text(
"---\ntype: agent\ndescription: Review work\ntags: [review]\n---\n# body\n",
encoding="utf-8",
)
server, thread, port = _serve_monitor(monkeypatch)
try:
with urllib.request.urlopen(
f"http://127.0.0.1:{port}/catalog?type=agent&q=review",
timeout=5,
) as response:
body = response.read().decode("utf-8")
assert response.status == 200
assert "id='wiki-search'" in body
assert "code-reviewer" in body
assert "href='/wiki/code-reviewer?type=agent'" in body
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
def test_render_wiki_index_hides_legacy_skill_source_prefix(fake_claude: Path) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
(skills_dir / "skills-sh-owner-repo-brainstorming.md").write_text(
"---\nname: skills-sh-owner-repo-brainstorming\ntype: skill\n"
"description: Brainstorm with constraints\ntags: [brainstorming]\n"
"---\n# body\n",
encoding="utf-8",
)
html_out = mt.render_wiki_index()
assert "<code style='font-size:0.84rem;'>owner-repo-brainstorming</code>" in html_out
assert "href='/wiki/skills-sh-owner-repo-brainstorming?type=skill'" in html_out
def test_render_wiki_index_does_not_bleed_grade_across_duplicate_slugs(
fake_claude: Path,
) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
harnesses_dir = fake_claude / "skill-wiki" / "entities" / "harnesses"
skills_dir.mkdir(parents=True)
harnesses_dir.mkdir(parents=True)
(skills_dir / "langgraph.md").write_text(
"---\nname: langgraph\ntype: skill\n---\n# body\n",
encoding="utf-8",
)
(harnesses_dir / "langgraph.md").write_text(
"---\nname: langgraph\ntype: harness\n---\n# body\n",
encoding="utf-8",
)
_write_sidecar(fake_claude, "langgraph", {
"slug": "langgraph",
"subject_type": "skill",
"grade": "D",
"raw_score": 0.2,
})
html_out = mt.render_wiki_index()
harness_start = html_out.index("href='/wiki/langgraph?type=harness'")
harness_card = html_out[harness_start:html_out.index("</a>", harness_start)]
assert "grade-D" not in harness_card
assert "<span class='pill'>harness</span>" in harness_card
def test_render_wiki_index_uses_visible_sidecars_without_full_scan(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
(skills_dir / "python-patterns.md").write_text(
"---\nname: python-patterns\ntype: skill\n---\n# body\n",
encoding="utf-8",
)
_write_sidecar(fake_claude, "python-patterns", {
"slug": "python-patterns",
"subject_type": "skill",
"grade": "A",
"raw_score": 0.9,
})
def fail_full_sidecar_scan() -> list[dict]:
raise AssertionError("_render_wiki_index should not scan every sidecar")
monkeypatch.setattr(mt, "all_sidecars", fail_full_sidecar_scan)
html_out = mt.render_wiki_index()
assert "href='/wiki/python-patterns?type=skill'" in html_out
assert "grade-A" in html_out
def test_render_wiki_index_empty_when_no_entities(fake_claude: Path) -> None:
html_out = mt.render_wiki_index()
# No entities → still renders the chrome + a helpful empty state.
assert "<h1>Wiki</h1>" in html_out
assert "No wiki entities found" in html_out
def test_render_wiki_index_rejects_unsafe_filenames(fake_claude: Path) -> None:
"""A file on disk with a slug that doesn't pass the allowlist must
not appear in the index, even if glob returns it."""
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
# Valid entry alongside an uppercase-first filename (fails ^[a-z0-9]).
(skills_dir / "python-patterns.md").write_text(
"---\nname: python-patterns\n---\n", encoding="utf-8",
)
(skills_dir / "Bad-Start.md").write_text(
"---\nname: Bad-Start\n---\n", encoding="utf-8",
)
entries = mt.wiki_index_entries()
slugs = {e["slug"] for e in entries}
assert "python-patterns" in slugs
assert "Bad-Start" not in slugs
def test_render_manage_includes_crud_and_upload_wizard(fake_claude: Path) -> None:
html_out = mt.render_manage(mutations_enabled=True)
direct_html = manage_page.render_manage(
mutations_enabled=True,
token="token",
initial_results_json=mt.json_for_script([]),
entity_types=("skill", "agent", "mcp-server", "harness"),
inline_script=lambda _name: "<script>// manage</script>",
layout=lambda _title, body: body,
)
assert "<h1>Manage catalog</h1>" in html_out
assert "id='manage-search'" in html_out
assert "id='entity-editor-form'" in html_out
assert "data-testid='entity-delete-button'" in html_out
assert "Add or update entity" in html_out
assert "window.CTX_MONITOR_MANAGE" in html_out
assert mt.monitor_asset_text("monitor-manage.js").strip() in html_out
assert "id='manage-search'" in direct_html
assert "window.CTX_MONITOR_MANAGE" in direct_html
assert "mcp-server" in direct_html
def test_entity_search_and_detail_apis_support_edit_flow(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
(skills_dir / "python-patterns.md").write_text(
"---\n"
"title: Python Patterns\n"
"type: skill\n"
"description: Idiomatic Python patterns\n"
"tags: [python, patterns]\n"
"---\n"
"# Python Patterns\n\nUse dataclasses and context managers.\n",
encoding="utf-8",
)
server, thread, port = _serve_monitor(monkeypatch)
try:
status, payload = _get_json(
port,
"/api/entities/search.json?q=patterns&type=skill",
)
assert status == 200
assert payload["results"][0]["slug"] == "python-patterns"
assert payload["results"][0]["type"] == "skill"
status, detail = _get_json(
port,
"/api/entity/python-patterns.json?type=skill",
)
assert status == 200
assert detail["slug"] == "python-patterns"
assert detail["frontmatter"]["description"] == "Idiomatic Python patterns"
assert "Use dataclasses" in detail["body"]
finally:
server.shutdown()
thread.join(timeout=5)
server.server_close()
def test_entity_search_uses_dashboard_index_for_live_graph_search(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
index_path = fake_claude / "skill-wiki" / "graphify-out" / "dashboard-neighborhoods.sqlite3"
index_path.parent.mkdir(parents=True)
conn = sqlite3.connect(index_path)
try:
conn.execute(
"CREATE TABLE nodes("
"id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,description TEXT,"
"quality_score REAL,usage_score REAL,degree INTEGER)",
)
conn.execute(
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
(
"skill:brainstorming",
"brainstorming",
"skill",
json.dumps(["planning", "creative"]),
"Generate better project options before implementation.",
0.91,
0.4,
17,
),
)
conn.commit()
finally:
conn.close()
monkeypatch.setattr(mt, "dashboard_graph_index_path", lambda: index_path)
monkeypatch.setattr(mt, "dashboard_index_matches_manifest", lambda _path: True)
results = mt.search_wiki_entities("brainstorm", "skill", limit=5)
assert results[0]["slug"] == "brainstorming"
assert results[0]["type"] == "skill"
assert results[0]["tags"] == ["planning", "creative"]
def test_entity_search_api_rejects_bad_type_and_clamps_limit(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
skills_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skills_dir.mkdir(parents=True)
for i in range(205):
(skills_dir / f"bulk-{i:03d}.md").write_text(
"---\n"
"type: skill\n"
"description: Bulk search boundary entity\n"
"tags: [bulk]\n"
"---\n"
"# Bulk\n",
encoding="utf-8",
)
server, thread, port = _serve_monitor(monkeypatch)
try:
status, bad_type = _get_json(
port,
"/api/entities/search.json?q=bulk&type=bad",
)
assert status == 400
assert "unsupported entity_type" in bad_type["detail"]
status, capped = _get_json(
port,
"/api/entities/search.json?q=bulk&type=skill&limit=9999",
)
assert status == 200
assert capped["total"] == 200
assert len(capped["results"]) == 200
assert capped["results"][0]["slug"] == "bulk-000"
status, floored = _get_json(
port,
"/api/entities/search.json?q=bulk&type=skill&limit=0",
)
assert status == 200
assert floored["total"] == 1
assert [item["slug"] for item in floored["results"]] == ["bulk-000"]
finally:
server.shutdown()
thread.join(timeout=5)
server.server_close()
def test_entity_upsert_api_writes_wiki_page_and_queues_graph_refresh(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
server, thread, port = _serve_monitor(monkeypatch)
try:
status, payload = _post_json(
port,
"/api/entity/upsert",
{
"slug": "custom-reviewer",
"entity_type": "agent",
"title": "Custom Reviewer",
"description": "Reviews Python changes with local policy.",
"tags": "python, review, policy",
"source_url": "https://example.com/custom-reviewer",
"body": "# Custom Reviewer\n\nUse this agent before merging Python changes.\n",
},
token="test-token",
)
assert status == 200
assert payload["ok"] is True
assert payload["detail"].startswith("saved agent:custom-reviewer")
entity_path = (
fake_claude
/ "skill-wiki"
/ "entities"
/ "agents"
/ "custom-reviewer.md"
)
text = entity_path.read_text(encoding="utf-8")
assert "title: Custom Reviewer" in text
assert "type: agent" in text
assert "tags: [python, review, policy]" in text
assert "Use this agent before merging Python changes." in text
jobs = wiki_queue.list_recent_jobs(
wiki_queue.queue_db_path(fake_claude / "skill-wiki"),
limit=10,
)
assert [job.kind for job in jobs[:2]] == [
wiki_queue.GRAPH_EXPORT_JOB,
wiki_queue.ENTITY_UPSERT_JOB,
]
finally:
server.shutdown()
thread.join(timeout=5)
server.server_close()
def test_entity_upsert_api_requires_confirmation_for_existing_page(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
entity_path = (
fake_claude / "skill-wiki" / "entities" / "agents" / "custom-reviewer.md"
)
entity_path.parent.mkdir(parents=True)
entity_path.write_text(
"---\ntitle: Custom Reviewer\ntype: agent\ntags: [python]\n"
"---\n# Custom Reviewer\n\nOriginal body.\n",
encoding="utf-8",
)
server, thread, port = _serve_monitor(monkeypatch)
try:
status, payload = _post_json(
port,
"/api/entity/upsert",
{
"slug": "custom-reviewer",
"entity_type": "agent",
"title": "Custom Reviewer",
"body": "# Custom Reviewer\n\nReplacement body.\n",
},
token="test-token",
)
assert status == 400
assert payload["ok"] is False
assert "confirm_update=true" in payload["detail"]
assert "Original body." in entity_path.read_text(encoding="utf-8")
status, payload = _post_json(
port,
"/api/entity/upsert",
{
"slug": "custom-reviewer",
"entity_type": "agent",
"title": "Custom Reviewer",
"body": "# Custom Reviewer\n\nReplacement body.\n",
"confirm_update": "true",
},
token="test-token",
)
assert status == 200
assert payload["ok"] is True
assert "Replacement body." in entity_path.read_text(encoding="utf-8")
finally:
server.shutdown()
thread.join(timeout=5)
server.server_close()
def test_entity_delete_api_removes_wiki_page_and_queues_graph_refresh(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
harness_dir = fake_claude / "skill-wiki" / "entities" / "harnesses"
harness_dir.mkdir(parents=True)
entity_path = harness_dir / "local-harness.md"
entity_path.write_text(
"---\ntitle: Local Harness\ntype: harness\ntags: [local, llm]\n"
"---\n# Local Harness\n",
encoding="utf-8",
)
server, thread, port = _serve_monitor(monkeypatch)
try:
status, payload = _post_json(
port,
"/api/entity/delete",
{"slug": "local-harness", "entity_type": "harness"},
token="test-token",
)
assert status == 200
assert payload == {
"ok": True,
"detail": "deleted harness:local-harness and queued graph refresh",
}
assert not entity_path.exists()
jobs = wiki_queue.list_recent_jobs(
wiki_queue.queue_db_path(fake_claude / "skill-wiki"),
limit=10,
)
assert [job.kind for job in jobs] == [wiki_queue.ENTITY_UPSERT_JOB]
assert jobs[0].payload["action"] == "delete"
finally:
server.shutdown()
thread.join(timeout=5)
server.server_close()
def test_entity_delete_unloads_live_entity_before_removing_page(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
assert dashboard_entities.normalize_entity_tags(["Code Review"]) == ["code-review"]
skill_dir = fake_claude / "skill-wiki" / "entities" / "skills"
skill_dir.mkdir(parents=True)
entity_path = skill_dir / "python-patterns.md"
entity_path.write_text(
"---\ntitle: Python Patterns\ntype: skill\n---\n# Python Patterns\n",
encoding="utf-8",
)
calls: list[tuple[str, str]] = []
monkeypatch.setattr(
mt,
"read_manifest",
lambda: {"load": [{"skill": "python-patterns", "entity_type": "skill"}]},
)
def fake_unload(slug: str, entity_type: str = "skill") -> tuple[bool, str]:
calls.append((slug, entity_type))
return True, "unloaded"
monkeypatch.setattr(mt, "perform_unload", fake_unload)
ok, detail = mt.delete_wiki_entity("python-patterns", "skill")
assert ok is True
assert "deleted skill:python-patterns" in detail
assert calls == [("python-patterns", "skill")]
assert not entity_path.exists()
def test_entity_delete_keeps_page_when_live_unload_fails(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
harness_dir = fake_claude / "skill-wiki" / "entities" / "harnesses"
harness_dir.mkdir(parents=True)
entity_path = harness_dir / "local-harness.md"
entity_path.write_text(
"---\ntitle: Local Harness\ntype: harness\n---\n# Local Harness\n",
encoding="utf-8",
)
monkeypatch.setattr(
mt,
"read_manifest",
lambda: {"load": [{"skill": "local-harness", "entity_type": "harness"}]},
)
monkeypatch.setattr(
mt,
"perform_unload",
lambda slug, entity_type="skill": (False, "use ctx-harness-install"),
)
ok, detail = mt.delete_wiki_entity("local-harness", "harness")
assert ok is False
assert "is loaded" in detail
assert entity_path.exists()
def test_sidecar_cache_invalidates_on_file_rewrite(fake_claude: Path) -> None:
sidecar_service.reset_caches()
path = fake_claude / "skill-quality" / "alpha.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps({"slug": "alpha", "subject_type": "skill", "grade": "A"}),
encoding="utf-8",
)
assert mt.all_sidecars()[0]["grade"] == "A"
path.write_text(
json.dumps({"slug": "alpha", "subject_type": "skill", "grade": "F"}),
encoding="utf-8",
)
os.utime(path, (time.time() + 2.0, time.time() + 2.0))
assert mt.all_sidecars()[0]["grade"] == "F"
def test_render_kpi_empty_state(fake_claude: Path) -> None:
"""With no sidecars, /kpi must render a helpful empty state, not 500."""
html_out = mt.render_kpi()
assert "<h1>KPIs</h1>" in html_out
assert "No KPI data yet" in html_out
assert "ctx-skill-quality recompute --all" in html_out
assert "ctx-skill-quality score --all" not in html_out
def test_render_kpi_with_sidecars(fake_claude: Path) -> None:
"""With real sidecars + lifecycle files, /kpi must surface the four
main tables: grade distribution, lifecycle tiers, categories,
demotion candidates. Mirrors kpi_dashboard.render_markdown sections."""
_write_sidecar(fake_claude, "alpha", {
"slug": "alpha", "subject_type": "skill",
"grade": "A", "raw_score": 0.92, "score": 0.92,
"hard_floor": None, "computed_at": "2026-04-19T10:00:00+00:00",
})
_write_sidecar(fake_claude, "foxtrot", {
"slug": "foxtrot", "subject_type": "skill",
"grade": "F", "raw_score": 0.08, "score": 0.08,
"hard_floor": "intake_fail",
"computed_at": "2026-04-19T10:00:00+00:00",
})
_write_sidecar(fake_claude, "reviewer", {
"slug": "reviewer", "subject_type": "agent",
"grade": "F", "raw_score": 0.06, "score": 0.06,
"hard_floor": None,
"computed_at": "2026-04-19T10:00:00+00:00",
})
html_out = mt.render_kpi()
# The five section headings must all be present.
assert "Grade distribution" in html_out
assert "Lifecycle tiers" in html_out
assert "Top demotion candidates" in html_out
assert "By category" in html_out
assert "Archived" in html_out
# Slug must be linked into the demotion-candidates table.
assert "foxtrot" in html_out
assert "/skill/reviewer?type=agent" in html_out
# Cross-link to the JSON endpoint + /skills drill-down.
assert "/api/kpi.json" in html_out
assert "/skills" in html_out
def test_api_kpi_summary_shape(fake_claude: Path) -> None:
"""The JSON endpoint must return a DashboardSummary-shaped dict."""
_write_sidecar(fake_claude, "alpha", {
"slug": "alpha", "subject_type": "skill",
"grade": "A", "raw_score": 0.9, "score": 0.9,
"hard_floor": None, "computed_at": "2026-04-19T10:00:00+00:00",
})
summary = mt.kpi_summary()
direct_summary = kpi_service.kpi_summary(fake_claude / "skill-quality")
assert summary is not None
assert direct_summary is not None
assert direct_summary.to_dict() == summary.to_dict()
d = summary.to_dict()
for key in ("total", "grade_counts", "lifecycle_counts",
"category_breakdown", "hard_floor_counts",
"low_quality_candidates", "archived", "generated_at"):
assert key in d, f"missing {key}"
assert d["total"] == 1
assert d["grade_counts"].get("A", 0) == 1
def test_kpi_summary_cache_reuses_recent_summary(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
import kpi_dashboard as kd
_write_sidecar(fake_claude, "alpha", {
"slug": "alpha", "subject_type": "skill",
"grade": "A", "raw_score": 0.9, "score": 0.9,
"hard_floor": None, "computed_at": "2026-04-19T10:00:00+00:00",
})
kpi_service.reset_cache()
real_generate = kd.generate
calls = 0
def wrapped_generate(*, sources, top_n=10, now=None):
nonlocal calls
calls += 1
return real_generate(sources=sources, top_n=top_n, now=now)
monkeypatch.setattr(kd, "generate", wrapped_generate)
assert mt.kpi_summary() is not None
assert mt.kpi_summary() is not None
assert calls == 1
def test_kpi_summary_reuses_disk_cache_after_process_cache_reset(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
import kpi_dashboard as kd
_write_sidecar(fake_claude, "alpha", {
"slug": "alpha", "subject_type": "skill",
"grade": "A", "raw_score": 0.9, "score": 0.9,
"hard_floor": None, "computed_at": "2026-04-19T10:00:00+00:00",
})
kpi_service.reset_cache()
first = mt.kpi_summary()
assert first is not None
assert kpi_service.summary_disk_cache_path(fake_claude / "skill-quality").is_file()
kpi_service.reset_cache()
def fail_generate(*args: object, **kwargs: object) -> object:
raise AssertionError("fresh process should read the KPI disk cache")
monkeypatch.setattr(kd, "generate", fail_generate)
second = mt.kpi_summary()
assert second is not None
assert second.total == first.total
assert second.grade_counts == first.grade_counts
def test_kpi_summary_disk_cache_invalidates_on_sidecar_rewrite(
fake_claude: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
import kpi_dashboard as kd
_write_sidecar(fake_claude, "alpha", {
"slug": "alpha", "subject_type": "skill",
"grade": "A", "raw_score": 0.9, "score": 0.9,
"hard_floor": None, "computed_at": "2026-04-19T10:00:00+00:00",
})
sidecar = fake_claude / "skill-quality" / "alpha.json"
kpi_service.reset_cache()
assert mt.kpi_summary() is not None
sidecar.write_text(
json.dumps({
"slug": "alpha", "subject_type": "skill",
"grade": "F", "raw_score": 0.1, "score": 0.1,
"hard_floor": None,
"computed_at": "2026-04-19T10:00:00+00:00",
}),
encoding="utf-8",
)
os.utime(sidecar, (time.time() + 2.0, time.time() + 2.0))
kpi_service.reset_cache()
real_generate = kd.generate
calls = 0
def wrapped_generate(*, sources, top_n=10, now=None):
nonlocal calls
calls += 1
return real_generate(sources=sources, top_n=top_n, now=now)
monkeypatch.setattr(kd, "generate", wrapped_generate)
summary = mt.kpi_summary()
assert summary is not None
assert summary.grade_counts.get("F") == 1
assert calls == 1
def test_layout_nav_includes_wiki_and_kpi() -> None:
"""Every rendered page must include the new Wiki + KPI tabs in the
top nav — the user explicitly asked for them to be accessible."""
out = mt.layout("test", "<p>body</p>")
assert "href='/wiki'" in out
assert "href='/harness'" in out
assert "href='/docs'" in out
assert "href='/kpi'" in out
assert "href='/graph'" in out
assert "href='/config'" in out
assert "class='app-shell'" in out
assert "class='app-header'" in out
assert "class='app-brand'" in out
assert ">Wiki<" in out
assert ">Harness Setup<" in out
assert ">Docs<" in out
assert ">KPIs<" in out
assert ">Config<" in out
assert "--surface" in out
assert "--accent" in out
def _use_temp_docs_cache(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
dashboard_docs.reset_docs_render_cache()
monkeypatch.setattr(
mt,
"docs_render_disk_cache_path",
lambda: tmp_path / ".ctx-monitor-docs-cache.json",
)
def test_render_docs_lists_repo_docs(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_use_temp_docs_cache(tmp_path, monkeypatch)
(tmp_path / "docs").mkdir()
(tmp_path / "docs" / "harness").mkdir()
(tmp_path / "graph").mkdir()
(tmp_path / "mkdocs.yml").write_text(
"\n".join([
"nav:",
" - Home: index.md",
" - Dashboard: dashboard.md",
" - Harness:",
" - Attach to hosts: harness/attaching-to-hosts.md",
"extra:",
" custom: !!python/name:material.extensions.emoji.twemoji",
]),
encoding="utf-8",
)
(tmp_path / "README.md").write_text(
"# ctx\n\nMain repo docs.\n",
encoding="utf-8",
)
(tmp_path / "docs" / "index.md").write_text(
"\n".join([
"# Home",
"",
"Repo docs home.",
"",
"!!! tip \"Install\"",
"",
" ctx-init --graph",
"",
"## Explore the docs",
"",
"Jump to the [dashboard docs](dashboard.md).",
"",
"### Deep section",
"",
"Nested docs body.",
"",
"<div class=\"grid cards\" markdown>",
"",
"- **Knowledge graph**",
"",
" ---",
"",
" Graph docs.",
"",
" [:octicons-arrow-right-24: Knowledge graph](knowledge-graph.md)",
"",
"</div>",
]),
encoding="utf-8",
)
(tmp_path / "docs" / "dashboard.md").write_text(
"# Dashboard\n\n- **Monitor** skills, agents, MCPs, harnesses, and graph state.\n\n## Runtime view\n",
encoding="utf-8",
)
(tmp_path / "docs" / "knowledge-graph.md").write_text(
"# Knowledge graph\n\n## Graph artifact\n\nGraph internals.\n",
encoding="utf-8",
)
(tmp_path / "docs" / "harness" / "attaching-to-hosts.md").write_text(
"# Attach to hosts\n\nConnect ctx to a non-Claude harness.\n",
encoding="utf-8",
)
(tmp_path / "graph" / "README.md").write_text(
"# Graph Artifacts\n\nCompressed wiki and knowledge graph artifacts.\n",
encoding="utf-8",
)
monkeypatch.setattr(mt, "docs_roots", lambda: [tmp_path])
html_out = mt.render_docs()
docs_script = mt.monitor_asset_text("monitor-docs.js")
assert "<h1>Docs</h1>" in html_out
assert "class='docs-shell'" in html_out
assert "class='docs-hero'" in html_out
assert "Repo documentation" in html_out
assert "sections</span>" in html_out
assert "pages</span>" in html_out
assert "class='docs-tabs'" in html_out
assert "data-doc-tab='home'" in html_out
assert "data-doc-tab='dashboard'" in html_out
assert "data-doc-tab='harness'" in html_out
assert "data-doc-tab='repo'" in html_out
assert "README.md" in html_out
assert "docs/dashboard.md" in html_out
assert "docs/harness/attaching-to-hosts.md" in html_out
assert "graph/README.md" in html_out
assert "<strong>Monitor</strong> skills, agents, MCPs, harnesses, and graph state." in html_out
assert "Connect ctx to a non-Claude harness." in html_out
assert "class=\"admonition tip\"" in html_out
assert "docs-heading-link docs-heading-level-2" in html_out
assert "docs-heading-link docs-heading-level-3" in html_out
assert "href='#doc-home-docs-index-md-explore-the-docs'" in html_out
assert "href='#doc-home-docs-index-md-deep-section'" in html_out
assert 'href="#doc-dashboard-docs-dashboard-md"' in html_out
assert 'href="#doc-other-docs-knowledge-graph-md"' in html_out
assert 'data-doc-tab="other"' in html_out
assert "id='docs-search-results'" in html_out
assert docs_script in html_out
assert "jumpToDocTarget" in html_out
assert "nested docs body" in html_out
assert '<div class="grid cards">' in html_out
assert "<strong>Knowledge graph</strong>" in html_out
assert "-> Knowledge graph" in html_out
assert ":octicons-arrow-right-24:" not in html_out
assert "!!! tip" not in html_out
assert "**Monitor**" not in html_out
assert "id='docs-search'" in html_out
assert "https://stevesolun.github.io/ctx/" in html_out
assert "doc-card" not in html_out
def test_render_docs_sanitizes_active_html(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_use_temp_docs_cache(tmp_path, monkeypatch)
(tmp_path / "docs").mkdir()
(tmp_path / "mkdocs.yml").write_text(
"site_name: ctx\nnav:\n - Home: index.md\n",
encoding="utf-8",
)
(tmp_path / "docs" / "index.md").write_text(
"# Home\n\n"
"<script>alert('x')</script>\n\n"
"<input type=\"text\" value=\"bad\">\n\n"
"<a href=\"javascript:alert('x')\" onclick=\"alert('x')\">bad</a>\n",
encoding="utf-8",
)
monkeypatch.setattr(mt, "docs_roots", lambda: [tmp_path])
html_out = mt.render_docs()
assert "<script>alert('x')</script>" not in html_out
assert "<script" in html_out
assert "<input" in html_out
assert "<input type=\"text\"" not in html_out
assert "onclick=" not in html_out
assert "href=\"javascript:" not in html_out
def test_render_docs_reuses_disk_cache_after_process_cache_reset(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_use_temp_docs_cache(tmp_path, monkeypatch)
(tmp_path / "docs").mkdir()
(tmp_path / "mkdocs.yml").write_text(
"site_name: ctx\nnav:\n - Home: index.md\n",
encoding="utf-8",
)
(tmp_path / "docs" / "index.md").write_text(
"# Home\n\nDocs body.\n",
encoding="utf-8",
)
monkeypatch.setattr(mt, "docs_roots", lambda: [tmp_path])
first = mt.render_docs()
assert (tmp_path / ".ctx-monitor-docs-cache.json").is_file()
dashboard_docs.reset_docs_render_cache()
def fail_render_markdown(*args: object, **kwargs: object) -> str:
raise AssertionError("fresh process should read the rendered docs cache")
monkeypatch.setattr(mt, "render_docs_markdown", fail_render_markdown)
second = mt.render_docs()
assert second == first
def test_render_docs_markdown_preserves_mkdocs_tab_controls() -> None:
markdown_text = (
'=== "One"\n\n'
" First body\n\n"
'=== "Two"\n\n'
" Second body\n"
)
html_out = dashboard_docs.render_docs_markdown(
markdown_text,
"doc-home",
fallback_renderer=mt.render_wiki_markdown,
)
assert "<input" not in html_out
assert 'type="radio"' in html_out
assert 'name="__tabbed_' in html_out
assert '<label for="__tabbed_' in html_out
assert "First body" in html_out
assert "Second body" in html_out
def test_render_docs_falls_back_to_public_docs(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
_use_temp_docs_cache(tmp_path, monkeypatch)
monkeypatch.setattr(mt, "docs_roots", lambda: [])
html_out = mt.render_docs()
assert "No local docs found." in html_out
assert "https://stevesolun.github.io/ctx/" in html_out
def test_layout_nav_tabs_are_draggable_and_persist_order() -> None:
out = mt.layout("test", "<p>body</p>")
css = mt.monitor_asset_text("monitor.css")
assert "name='viewport'" in out
assert css.startswith(":root")
assert f"<style>{css}</style>" in out
assert "id='dashboard-nav'" in out
assert "app-shell" in out
assert ".app-shell" in css
assert ".graph-canvas-wrap [data-3d-node-id]:focus" in css
assert ".graph-stage { width: 100%; height: calc(100vh - 2rem); height: calc(100dvh - 2rem);" in css
assert ".graph-canvas-wrap { position: relative; min-height: 0; background: transparent; cursor: grab; }" in css
assert ".graph-canvas-wrap:active { cursor: grabbing; }" in css
assert ".graph-canvas-wrap [data-edge-detail] { cursor: help; }" in css
assert ".graph-match-histogram" in css
assert ".graph-match-bar:hover" in css
assert ".graph-range-wrap" in css
assert ".graph-range-fill" in css
assert "width: 1rem; height: 1rem" in css
assert "margin-top: calc((0.3rem - 1rem) / 2);" in css
assert 'background: transparent; border: 0; box-shadow: none;' in css
assert '.graph-range-wrap input[type="range"]:focus-visible,' in css
assert "outline: none !important; box-shadow: none !important;" in css
assert '.graph-range-wrap input[type="range"]::-moz-focus-outer { border: 0; }' in css
assert 'border: 0; box-shadow: none; }' in css
assert 'outline: none;' in css
assert 'box-shadow: 0 0 0 0.24rem var(--accent-ring)' in css
assert "font-size: 0.72rem; line-height: 1; margin-top: 0.22rem;" in css
assert "pointer-events: none" in css
assert "pointer-events: auto" in css
assert "cursor: none" not in css
assert "grid-template-rows: auto minmax(18rem, 1fr) 0.65rem minmax(10rem, var(--graph-inspector-height))" in css
assert "grid-template-columns: minmax(0,1fr)" in css
assert "clamp(18rem, 34vw, 30rem)" not in css
assert ".graph-resize-handle" in css
assert "cursor: ns-resize" in css
assert "[data-testid=\"graph-edge-detail\"] { min-height: 0; max-height: 100%; overflow: auto; }" in css
assert ".graph-edge-detail-inline" in css
assert "border-left: 1px solid var(--border)" not in css
assert "minmax(180px, 0.42fr) 30%" not in css
assert ".graph-node-selected [data-testid=\"graph-svg-node\"]" in css
assert "fill: #facc15" in css
assert "outline: none" in css
assert "data-nav-storage-key='ctx-monitor-nav-order'" in out
assert "data-nav-default-keys=" in out
assert "draggable='true'" in out
assert "data-nav-key='graph'" in out
assert "const defaultKeys = JSON.parse(nav.dataset.navDefaultKeys || '[]');" in out
assert "const defaultKeys = [" not in out
assert "localStorage.setItem(storageKey" in out
assert "dragstart" in out
assert "function insertionTarget" in out
assert "nav.addEventListener('dragover'" in out
assert "nav.insertBefore(dragged, target" in out
assert "drop" in out
assert "id='nav-reset'" in out
def test_render_config_page_shows_required_defaults_and_examples(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(mt, "claude_dir", lambda: tmp_path / ".claude")
html_out = mt.render_config()
assert "<h1>Config</h1>" in html_out
assert "skill_transformer.line_threshold" in html_out
assert "resolver.recommendation_top_k" in html_out
assert "graph.semantic.min_cosine" in html_out
assert "knowledge.mode" in html_out
assert "Required" in html_out
assert "Default: <code>180</code>" in html_out
assert "Example:" in html_out
assert "id='config-form'" in html_out
def test_config_page_module_renders_controls_and_overrides() -> None:
remove = object()
def get_value(raw: dict[str, object], path: str, default: object = None) -> object:
current: object = raw
for part in path.split("."):
if not isinstance(current, dict) or part not in current:
return default
current = current[part]
return current
html_out = config_page.render_config(
payload={
"defaults": {"resolver": {"recommendation_top_k": 5}, "intake": {"enabled": True}},
"user": {"resolver": {"recommendation_top_k": 3}},
"effective": {"resolver": {"recommendation_top_k": 3}, "intake": {"enabled": True}},
"path": "C:/tmp/skill-system-config.json",
},
specs=(
{
"group": "Recommendation",
"path": "resolver.recommendation_top_k",
"type": "int",
"required": True,
"label": "Max mixed recommendations",
"help": "Caps recommendations.",
"example": 5,
},
{
"group": "Intake",
"path": "intake.enabled",
"type": "bool",
"label": "Intake quality gate",
"help": "Runs quality checks.",
"example": True,
},
),
monitor_token="tok",
layout=lambda _title, body: body,
config_value=get_value,
config_remove=remove,
)
assert "<h1>Config</h1>" in html_out
assert "resolver.recommendation_top_k" in html_out
assert "data-original-value='3'" in html_out
assert "data-config-clear='resolver.recommendation_top_k'" in html_out
assert "intake.enabled" in html_out
assert "X-CTX-Monitor-Token" in html_out
def test_render_harness_wizard_guides_model_choice_and_real_commands(
fake_claude: Path,
) -> None:
harness_dir = fake_claude / "skill-wiki" / "entities" / "harnesses"
harness_dir.mkdir(parents=True)
(harness_dir / "langgraph.md").write_text(
"\n".join([
"---",
"title: LangGraph harness",
"type: harness",
"description: Durable Python agent workflows with tool routing.",
"tags: [python, api, local, verification]",
"repo_url: https://github.com/langchain-ai/langgraph",
"---",
"# LangGraph harness",
]),
encoding="utf-8",
)
_write_sidecar(fake_claude, "langgraph-harness", {
"slug": "langgraph",
"subject_type": "harness",
"grade": "A",
"raw_score": 0.93,
"hard_floor": "",
})
html_out = mt.render_harness_wizard()
assert "<h1>Harness Setup</h1>" in html_out
assert "class='setup-flow'" in html_out
assert "Model -> intent -> install -> attach ctx" in html_out
assert "id='harness-wizard-form'" in html_out
assert "Model provider" in html_out
assert "Development goal" in html_out
assert "data-harness-slug='langgraph'" in html_out
assert "ctx-harness-install --recommend" in html_out
assert "ctx-harness-install langgraph --dry-run" in html_out
assert "ctx-scan-repo --repo . --recommend" in html_out
assert "ctx-scan-repo --recommend" not in html_out
assert "--plan-on-no-fit" in html_out
assert "ctx attachment" in html_out
assert "data-testid='harness-command-output'" in html_out
def test_harness_page_module_renders_catalog_cards_and_commands() -> None:
html_out = harness_page.render_harness_wizard(
harnesses=[{
"slug": "langgraph",
"title": "LangGraph harness",
"description": "Durable Python agent workflows.",
"tags": ["python", "api", "verification"],
"score": 0.93,
"grade": "A",
"repo_url": "https://github.com/langchain-ai/langgraph",
}],
layout=lambda _title, body: body,
)
assert "<h1>Harness Setup</h1>" in html_out
assert "id='harness-wizard-form'" in html_out
assert "data-harness-slug='langgraph'" in html_out
assert "ctx-harness-install langgraph --dry-run" in html_out
assert "ctx-harness-install --recommend" in html_out
assert "--plan-on-no-fit" in html_out
assert "X-CTX-Monitor-Token" not in html_out
def test_harness_wizard_entries_do_not_scan_full_sidecar_tree(
fake_claude: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
harness_dir = fake_claude / "skill-wiki" / "entities" / "harnesses"
harness_dir.mkdir(parents=True)
(harness_dir / "langgraph.md").write_text(
"---\ntitle: LangGraph harness\ntype: harness\n---\n# body\n",
encoding="utf-8",
)
_write_sidecar(fake_claude, "langgraph-harness", {
"slug": "langgraph",
"subject_type": "harness",
"grade": "A",
"raw_score": 0.93,
})
monkeypatch.setattr(
mt,
"sidecar_files",
lambda: (_ for _ in ()).throw(AssertionError("full sidecar scan")),
)
entries = mt.harness_wizard_entries()
direct_entries = harness_service.harness_wizard_entries(
fake_claude / "skill-wiki",
fake_claude / "skill-quality",
)
assert entries[0]["slug"] == "langgraph"
assert entries[0]["grade"] == "A"
assert entries == direct_entries
def test_save_config_updates_casts_values_and_blank_removes_override(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
claude = tmp_path / ".claude"
monkeypatch.setattr(mt, "claude_dir", lambda: claude)
config_path = claude / "skill-system-config.json"
config_path.parent.mkdir(parents=True)
config_path.write_text(
json.dumps({
"resolver": {"recommendation_top_k": 4},
"skill_transformer": {"line_threshold": 220},
}),
encoding="utf-8",
)
saved = mt.save_config_updates({
"resolver.recommendation_top_k": "",
"skill_transformer.line_threshold": "240",
"intake.enabled": "false",
"graph.edge_weights.semantic": "0.65",
})
raw = json.loads(config_path.read_text(encoding="utf-8"))
assert saved["ok"] is True
assert "recommendation_top_k" not in raw.get("resolver", {})
assert raw["skill_transformer"]["line_threshold"] == 240
assert raw["intake"]["enabled"] is False
assert raw["graph"]["edge_weights"]["semantic"] == 0.65
direct = config_service.save_config_updates(
{"skill_transformer.line_threshold": "260"},
config_path,
)
raw = json.loads(config_path.read_text(encoding="utf-8"))
assert direct["ok"] is True
assert raw["skill_transformer"]["line_threshold"] == 260
def test_render_config_posts_only_dirty_fields_and_can_clear_overrides(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
claude = tmp_path / ".claude"
monkeypatch.setattr(mt, "claude_dir", lambda: claude)
config_path = claude / "skill-system-config.json"
config_path.parent.mkdir(parents=True)
config_path.write_text(
json.dumps({"resolver": {"recommendation_top_k": 4}}),
encoding="utf-8",
)
html_out = mt.render_config()
assert "Saves only changed fields" in html_out
assert "data-original-value='4'" in html_out
assert "data-config-path='intake.enabled' data-original-value='true'" in html_out
assert "data-config-clear='resolver.recommendation_top_k'" in html_out
assert "no config changes to save" in html_out
assert "el.dataset.originalValue" in html_out
def test_render_graph_landing_shows_seeds_when_available(monkeypatch) -> None:
"""With a non-empty graph, /graph (no slug) should surface popular
seed slugs when the graph is already cached."""
import networkx as nx
G = nx.Graph()
# High-degree hub: 'skill:python-patterns' with 5 neighbors.
for peer in ("skill:fastapi-pro", "skill:async-patterns",
"agent:code-reviewer", "skill:pydantic", "skill:sqlalchemy"):
G.add_edge("skill:python-patterns", peer, weight=2)
G.nodes["skill:python-patterns"]["label"] = "python-patterns"
monkeypatch.setattr(mt, "graph_stats", lambda: {
"nodes": G.number_of_nodes(),
"edges": G.number_of_edges(),
"available": True,
})
monkeypatch.setattr(graph_service, "cached_dashboard_graph", lambda: G)
html_out = mt.render_graph(None)
# Landing page shows the seeds block.
assert "Popular seed slugs" in html_out
# Hub slug must appear as a clickable chip.
assert "python-patterns" in html_out
# Graph stats line shows node/edge counts.
assert "nodes" in html_out
def test_render_graph_landing_auto_loads_top_seed(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(mt, "graph_stats", lambda: {
"nodes": 100000,
"edges": 2900834,
"available": True,
})
monkeypatch.setattr(mt, "top_degree_seeds", lambda **_kwargs: [{
"slug": "python-patterns",
"type": "skill",
"degree": 10000,
"label": "python-patterns",
}])
html_out = mt.render_graph(None)
assert "const initial = \"python-patterns\";" in html_out
assert "const initialType = \"skill\";" in html_out
assert "value='python-patterns'" in html_out
assert "deg 10,000" in html_out
def test_render_graph_landing_uses_default_focus_when_seed_index_absent(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(mt, "graph_stats", lambda: {
"nodes": 102928,
"edges": 2900834,
"available": True,
})
monkeypatch.setattr(mt, "top_degree_seeds", lambda **_kwargs: [])
html_out = mt.render_graph(None)
assert "const initial = \"github\";" in html_out
assert "const initialType = \"\";" in html_out
assert "value='github'" in html_out
assert "Popular seed slugs" not in html_out
def test_render_graph_landing_does_not_cold_load_graph_for_seed_chips(
monkeypatch,
) -> None:
calls = 0
def fake_load_graph():
nonlocal calls
calls += 1
raise AssertionError("graph cold-loaded")
monkeypatch.setattr(mt, "graph_stats", lambda: {
"nodes": 102697,
"edges": 2900910,
"available": True,
})
monkeypatch.setattr(mt, "load_dashboard_graph", fake_load_graph)
monkeypatch.setattr(mt, "top_degree_seeds_from_index", lambda _limit=18: [])
monkeypatch.setattr(graph_service, "cached_dashboard_graph", lambda: None)
html_out = mt.render_graph(None)
assert "id='focus'" in html_out
assert "Popular seed slugs" not in html_out
assert calls == 0
def test_render_graph_landing_hides_seeds_when_graph_absent(monkeypatch) -> None:
import sys
def _bad(*_a, **_k):
raise RuntimeError("no graph")
fake = type("M", (), {"load_graph": _bad})
# ctx.monitor.compat lazy-imports 'from ctx.core.graph.resolve_graph import load_graph'
# at call time; inject at the canonical dotted path so the lazy import
# resolves to our stub. Also populate the legacy shim path belt-and-
# braces in case a downstream path still routes through it.
monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake)
monkeypatch.setitem(sys.modules, "resolve_graph", fake)
monkeypatch.setattr(mt, "graph_stats", lambda: {"available": False})
graph_service.reset_caches()
html_out = mt.render_graph(None)
# No seeds section when graph isn't available.
assert "Popular seed slugs" not in html_out
# But the search box and graph list mount still render.
assert "id='focus'" in html_out
assert "id='cy'" in html_out
def test_cli_argparser_exposes_serve() -> None:
import ctx_monitor
assert ctx_monitor.main is mt.main
assert ctx_monitor.serve is mt.serve
# argparse should not raise; subcommand "serve" is required
with pytest.raises(SystemExit):
mt.main([])
# Valid invocation parses (we don't actually start the server; parse_args
# returns args but mt.main() would call serve() which blocks. So just
# test the parser path.)
__import__("argparse").ArgumentParser()
# Minimal smoke: main with --help exits 0.
with pytest.raises(SystemExit) as exc:
mt.main(["serve", "--help"])
assert exc.value.code == 0
def test_monitor_server_suppresses_aborted_connection_traceback(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
server = mt.make_monitor_server("127.0.0.1", 0)
try:
monkeypatch.setattr(
mt.sys,
"exc_info",
lambda: (ConnectionAbortedError, ConnectionAbortedError(), None),
)
server.handle_error(object(), ("127.0.0.1", 12345))
captured = capsys.readouterr()
assert captured.err == ""
finally:
server.server_close()
|