All files / js jsmain.js

90.48% Statements 1483/1639
75.34% Branches 486/645
89.79% Functions 44/49
90.48% Lines 1483/1639

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 164072x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 15380x 15380x 15380x 15380x 15380x 15380x 15380x 15380x 15380x 15380x 15380x 2x 2x 1x 1x 1x 15380x 337x 337x 337x 337x 337x 15378x 15041x 15041x 15041x 15041x 15041x 15041x 15380x 15380x             15380x 15380x 1573936x 15380x 15380x 15380x 15380x 15380x 15380x 15380x 15380x 2x 2x 2x 15380x 15378x 15378x 15380x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 69x 69x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 69x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 1x 1x 72x     72x 72x 72x 72x 72x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 1x 1x 1x 1x 1x 1x 1x 71x 71x 71x 71x 71x 71x 3x 3x 71x 71x 71x 72x 72x 72x 72x                                               72x 72x 72x 72x 72x                 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 1x 1x 1x 1x         1x 1x     1x 1x 1x 1x   1x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 261x 261x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 260x 258x 653x 653x 653x 653x 653x 653x 653x 653x 494x 494x 494x 494x 431x 368x 305x 242x 179x 119x 116x 104x 26x 3x 26x 653x 159x 159x 159x 143x 127x 125x 68x 54x 40x 40x 24x 24x 23x 20x 17x 17x 17x 17x   159x 653x 258x 260x 261x 260x 260x 260x 261x 1x 1x 1x 260x 261x       260x 260x 260x 261x 1x 1x 1x 261x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 11708x 15x 15x 15x 11708x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x                         72x 15307x 15307x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 8284x                             8284x 8284x 8283x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 66x 66x 66x 3x 3x 3x 66x 70x 70x     8214x 8214x 8284x 8284x 8214x 8214x 8284x 8284x 3088x 3088x             8284x 5125x 5125x 5125x 8284x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 75x 75x 75x 4x 4x 71x 71x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 1384x 1384x 9x 9x 1384x 1384x 72x 286x 286x 286x 286x 274x 286x 286x 286x 286x 286x 286x 286x 286x 286x 247x 247x   286x 72x 592x 592x 369x 369x 366x 366x 369x 369x 369x 369x 369x 369x 369x 369x 300x 300x 223x 592x 72x 524x 524x 306x 306x 306x 306x 306x 306x 306x 306x 306x 288x 288x 218x 524x 72x 613x 613x 408x 408x 408x 408x 408x 408x 408x 408x 408x 282x 282x 205x 613x 72x 72x 72x 6x 6x 6x 6x 6x 60x 60x 60x 60x 3x 6x 12x 3x 3x 3x 12x                               6x 72x 72x 7x 7x 7x 7x 7x 72x 72x 1x 1x 1x 1x 1x 72x 33x 33x 33x 33x 72x 8x 8x 104x 104x 104x 8x 8x       8x 8x 72x 8x 8x 8x       8x 8x 72x 7x 7x 7x       7x 7x 72x 7x 7x 7x       7x 7x 72x 8x 8x 6x 4x   8x 72x 39x 39x 39x 39x 39x 9x 4x 4x 4x 4x 9x 6x 6x 6x 6x 9x 7x 7x 7x 7x 9x 39x 72x 14x 14x 14x 182x 182x 182x 182x 182x 2x 182x 24x 24x 182x 14x 182x 182x 182x 14x 14x 72x 18x 18x 61x 61x 61x 18x 18x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 32x 32x 2x       2x 2x 30x 30x 30x       30x 30x 30x 30x 30x 30x 30x 30x 16x 16x 30x 30x 32x 72x 44x 44x 44x 44x 23x 44x 44x 44x 30x 30x 30x 30x 14x 44x 44x 44x 44x 72x 72x 72x 90x 90x 90x 90x 90x 90x 90x 16x 16x 16x 90x 24x 24x 5x 5x 5x     5x 24x 24x 90x 24x 24x 5x 5x 5x 5x 5x 24x 24x 26x 26x 26x 8x 8x 8x 8x 8x 26x 4x 4x 4x 4x 4x 26x 26x   90x 72x         72x 309x 309x 309x 309x 72x 72x 72x 72x 72x 102x 102x 86x 86x 86x 86x 86x 102x 72x 72x 72x 72x 72x 72x 72x 72x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 72x 72x 72x 51x 51x 51x 51x 51x 72x 72x 72x 72x 72x 72x 51x 51x 51x 51x 15x 15x 15x 15x 15x 15x 15x 15x 51x 36x 36x 51x 51x 72x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x   51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 1224x 834x 1224x 390x 15825x 15825x 390x 1224x 51x 51x 51x 51x 51x 7x 28x 28x 7x 51x 51x 51x 51x 51x 51x 51x 811x 701x 194x 194x 194x 194x 194x 194x 194x 507x 507x 811x 811x 51x 72x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 14x 148x 148x 14x 14x 14x 14x 14x 14x 14x 14x 14x 6x 6x 14x 14x 14x 14x 14x 14x 30x 16x 40x 40x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 10x 10x 16x 16x 10x 10x 16x 16x 12x 12x 16x 16x 16x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 72x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 72x 72x 72x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 5x 5x 5x 5x 5x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 3x 3x 3x 3x 1x 1x 72x 72x 72x 1x 1x 1x 1x 1x 1x 1x 27x 27x 23x 23x 23x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 189x 28x 28x 28x 189x 189x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 7x 7x 1x 1x 1x 1x 7x       6x 6x 6x 6x 6x 6x 7x 1x 1x 1x 1x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 72x 72x 72x 72x 9x 9x 9x 9x 9x 9x 9x 9x 72x 72x 72x 72x 72x 63x 63x 63x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 72x 72x 9x 72x 9x 72x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 5x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         7x 6x 1x 1x 1x 6x 6x 9x 4x 4x 4x 4x 6x 6x 6x       6x 6x 21x       21x 14x 14x 14x 14x 14x 14x 12x 10x 8x 5x             5x 14x 14x 21x 9x 9x 7x 7x 7x 7x 5x 5x 5x 5x           5x 7x 9x 21x 9x 9x 7x 7x 7x 7x 6x 6x 6x 6x 1x 1x 1x 1x 1x 5x 7x 9x 21x 9x 9x 9x 9x 9x 4x 4x 4x 4x 3x 3x 3x 3x           3x 4x 9x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 3x 7x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 2x 2x 2x 2x 2x 7x 7x 6x 6x 4x 72x 8x 8x 8x 72x 72x 72x 72x 72x 15379x 15379x 15307x 15307x 15307x 15307x 72x 72x  
// jsmain.js — Top-level game entry point
// This is the JS equivalent of C's unixmain.c → nethack_main().
// Creates and runs a full NetHack game session.
//
// Usage:
//   const game = new NethackGame({ seed: 42, role: 'Wizard', ... });
//   await game.start();         // newgame + moveloop_preamble
//   await game.playTurns(keys); // feed keystrokes through moveloop
//   game.getRngLog();           // get RNG call log for comparison
 
import { decl_globals_init } from './decl.js';
import { game } from './gstate.js';
import { initRng, enableRngLog, getRngLog, getRngCallCount, pushRngLogEntry } from './rng.js';
import {
    getlin,
    isStartupPromptPhase,
    nhgetch,
    pushInput,
    resetInputModuleState,
    setStartupPromptPhase,
    ynFunction,
} from './input.js';
import { newgame, moveloop_preamble, moveloop_core, moveloop_core_monsters_only, maybe_do_tutorial } from './allmain.js';
import { time_from_yyyymmddhhmmss } from './calendar.js';
import { rn2 } from './rng.js';
import { COPYRIGHT_BANNER_A, COPYRIGHT_BANNER_B, COPYRIGHT_BANNER_C, COPYRIGHT_BANNER_D, TELEPORT_BANNER_C, NHW_MENU, PRIMARYSET, ROGUESET, ROLE_ALIGNMASK, ROLE_ALIGNS, ROLE_FEMALE, ROLE_GENDERS, ROLE_GENDMASK, ROLE_MALE, ROLE_NONE, ROLE_RACEMASK, ROLE_RANDOM, TOPLINE_EMPTY, AUTOUNLOCK_APPLY_KEY } from './const.js';
import { roles, races, aligns } from './roles.js';
import { createHeadlessPromptRuntime } from './headless_prompt_runtime.js';
import { docorner, docrt, erase_menu_or_text, init_tty_windows, resetDisplayState, serialize_terminal_grid, setBotlx, status_initialize, tty_create_nhwindow, tty_destroy_nhwindow, tty_dismiss_nhwindow, tty_display_nhwindow } from './display.js';
import { ATR_INVERSE, CLR_GRAY } from './terminal.js';
import { enterModal, exitModal } from './modal_guard.js';
import { init_symbols, load_symset, parsesymbols, reglyph_darkroom } from './drawing.js';
import { bind_key } from './cmd.js';
import { You } from './pline.js';
import { resetSpoteffectsState } from './hack.js';
 
export class NethackGame {
    constructor(options = {}) {
        this.seed = options.seed || 1;
        this.nethackrc = options.nethackrc || ''; // .nethackrc contents
        this.datetime = options.datetime || null; // "yyyymmddhhmmss" string
        this.logRng = options.logRng ?? true;
        // Parsed from nethackrc during start()
        this._parsedOptions = null;
        // Per-step screen captures for comparison
        this._screens = [];
        this._cursors = [];
    }
 
    // Initialize game state and generate first level.
    // The nethackrc string is parsed the same way C parses .nethackrc:
    // OPTIONS lines set flags. If role/race/gender/align are all specified,
    // character selection prompts are skipped. If any are missing, the game
    // prompts for them via the input queue (same code path, different inputs).
    // Install replay/test capture hook — fires at each input boundary.
    // Harness-only: this collects PES artifacts (screen/cursor/RNG slices)
    // and must never own gameplay behavior.
    installCaptureHook() {
        const nhGame = this;
        game._nhGameRef = nhGame; // menu.js needs access to screens array
        nhGame._rngSlices = []; // per-step RNG log slices
        nhGame._lastRngIdx = 0; // track position in flat RNG log
        nhGame._nhgetchCount = 0; // tracks key index for type-ahead detection
        game._preNhgetchHook = async () => {
            // Capture the frame that exists just before the next key is read.
            // This models C NOMUX session capture timing.
            // Skip capture for type-ahead keys: C consumed them without a
            // NOMUX blocking point, so no screen was captured.
            const keyIdx = nhGame._nhgetchCount++;
            if (nhGame._typeAheadCaptures?.has(keyIdx)) return;
            const fullLog = getRngLog() || [];
            const slice = fullLog.slice(nhGame._lastRngIdx);
            let screen = '';
            const queuedScreens = game._captureScreensQueue;
            if (Array.isArray(queuedScreens) && queuedScreens.length > 0) {
                screen = queuedScreens.shift() || '';
                if (queuedScreens.length === 0) {
                    game._captureScreensQueue = null;
                    game._menuActive = false;
                }
            } else if (game.startupPromptPhase) {
                // During startup (copyright, welcome, chargen): use docrt
                // since there's no map state to conflict with. Startup
                // screens need docrt's cursor positioning from the render.
                await docrt(false, true);
                screen = game._screen_output || '';
            } else {
                // C only paints gnew during explicit flush_screen() calls
                // (pline, curs_on_u, etc.), never at nhgetch time. The
                // capture hook is pure observation — no flush_glyph_buf.
                const disp = game?.nhDisplay;
                screen = disp?.grid ? serialize_terminal_grid(disp) : '';
            }
            nhGame._screens.push(screen);
            if (process?.env?.WEBHACK_TRACE_CAPIDX) {
                const disp = game?.nhDisplay;
                const top = String(screen.split('\n')[0] || '');
                const hasMore = slice.some(e => typeof e === 'string' && e.includes('>more'));
                // eslint-disable-next-line no-console
                console.log('[CAP]', keyIdx, 'owner=', game.modalOwner || '-', 'hasMore=', hasMore, 'toplin=', disp?.toplin ?? 'na', 'top=', JSON.stringify(top));
            }
            // Capture per-step RNG slice
            nhGame._rngSlices.push(slice.map(e =>
                typeof e === 'string' ? e.replace(/^\d+\s+/, '') : String(e)
            ));
            nhGame._lastRngIdx = fullLog.length;
            game._monmove_since_capture = false;
            // Capture cursor position for comparison
            const disp = game?.nhDisplay || null;
            if (disp) {
                const queuedCursors = game._captureCursorsQueue;
                if (Array.isArray(queuedCursors) && queuedCursors.length > 0) {
                    const nextCursor = queuedCursors.shift();
                    nhGame._cursors.push(nextCursor || [disp.cursorCol, disp.cursorRow, disp.cursorVisible ? 1 : 0]);
                    if (queuedCursors.length === 0) game._captureCursorsQueue = null;
                } else {
                    nhGame._cursors.push([disp.cursorCol, disp.cursorRow, disp.cursorVisible ? 1 : 0]);
                }
            }
        };
    }
 
    async start() {
        decl_globals_init();  // creates game + calls all init_*_globals()
        // resetDisplayState and resetSpoteffectsState now in init_*_globals
        // Install pending display from gameFromSession (after game exists)
        if (this._pendingDisplay) {
            game.nhDisplay = this._pendingDisplay;
            setStartupPromptPhase(true);
            this._pendingDisplay = null;
        }
        const g = game;
        // Install capture hook right after game state exists, before any prompts
        if (this._installHookAfterInit) {
            this.installCaptureHook();
        }
        // from-keylog: force startup prompt flow so legacy/welcome display
        if (this._forcePromptedStartup) {
            g.promptedStartup = true;
        }
 
        // Pin datetime (must be before any calendar functions)
        if (this.datetime) {
            g.fixed_datetime = time_from_yyyymmddhhmmss(this.datetime);
        }
        // Debug: trace all nhgetch key reads
        if (this._dbgTraceKeys) g._dbgTraceKeys = true;
 
        // Parse nethackrc to set game options (same as C's initoptions)
        const opts = parseNethackrc(this.nethackrc);
        g.flags.initrole = opts.role;
        g.flags.initrace = opts.race;
        g.flags.initgend = opts.gender;
        g.flags.initalign = opts.align;
        g.plname = opts.name || '';
        g.flags.debug = opts.wizard;
        g.flags.explore = opts.explore;
        // C ref: options.c set_playmode() — wizard mode overrides plname
        if (g.flags.debug) g.plname = 'wizard';
        g.flags.randomall = false;
        g.flags.pickup = opts.autopickup;
        // C ref: options.c:1089 optfn_autounlock(do_init) default = AUTOUNLOCK_APPLY_KEY
        g.flags.autounlock = AUTOUNLOCK_APPLY_KEY;
        // Boolean display flags from nethackrc
        g.flags.showexp = opts.showexp;
        g.flags.time = opts.time;
        g.flags.verbose = opts.verbose;
        g.flags.lit_corridor = opts.lit_corridor;
        g.flags.pushweapon = opts.pushweapon;
        g.flags.mention_walls = opts.mention_walls;
        g.flags.color = opts.color;
        g.flags.dark_room = opts.dark_room;
        g.flags.pettype = opts.pettype;
        g.flags.legacy = opts.legacy;
        g.iflags.fireassist = opts.fireassist;
        g.iflags.wc_splash_screen = opts.splash_screen;
        // C ref: options.c:3217-3242 optfn_pettype maps to preferred_pet.
        if (opts.pettype === 'cat' || opts.pettype === 'c') g.preferred_pet = 'c';
        else if (opts.pettype === 'dog' || opts.pettype === 'd') g.preferred_pet = 'd';
        else if (opts.pettype === 'horse' || opts.pettype === 'h') g.preferred_pet = 'h';
        else if (opts.pettype === 'none' || opts.pettype === 'n') g.preferred_pet = 'n';
        else g.preferred_pet = '\0';
        // C ref: topl.c/tty defaults — Ctrl-P repeats prior topline in-place.
        g.iflags.prevmsg_window = opts.msg_window || 's';
        g.flags.tutorial = opts.tutorial;
        g.flags.biff = opts.mail; // C ref: flags.biff — enable mail daemon
        g.flags.symset = opts.symset || null;
        g.tutorial_set_in_config = !!opts.tutorial_set;
 
        // Initialize symbol set system (C ref: symbols.c init_symbols())
        init_symbols();
        if (g.flags.symset) load_symset(g.flags.symset);
        // Apply per-symbol SYMBOLS= overrides from .nethackrc
        // C ref: cfgfiles.c SYMBOLS= lines → parsesymbols()
        if (opts.symbols) {
            for (const line of opts.symbols) parsesymbols(line, PRIMARYSET);
        }
        if (opts.rogueSymbols) {
            for (const line of opts.rogueSymbols) parsesymbols(line, ROGUESET);
        }
        reglyph_darkroom();
 
        // Apply BIND= custom key bindings from .nethackrc
        // C ref: cfgfiles.c BIND=key:command → cmd.c bind_key()
        if (opts.bindings) {
            for (const spec of opts.bindings) {
                const colonIdx = spec.indexOf(':');
                if (colonIdx < 0) continue;
                const keySpec = spec.slice(0, colonIdx).trim();
                const cmdName = spec.slice(colonIdx + 1).trim();
                // Parse key spec: single char, ^X for ctrl, M-x for meta
                const keyCode = parseKeySpec(keySpec);
                if (keyCode != null && cmdName) {
                    bind_key(keyCode, cmdName);
                }
            }
        }
 
        g.u.uz = { dnum: 0, dlevel: 1 };
        g._statusWindowDataInit = false;
 
        // Initialize RNG
        initRng(this.seed);
        if (this.logRng) enableRngLog(false);
 
        // C ref: tty_init_nhwindows creates BASE window, then newgame
        // creates MESSAGE, STATUS, MAP, INVEN windows (slots 0-4).
        init_tty_windows();
        // C ref: windows.c:692 — set after choose_windows/init_nhwindows
        if (game.iflags) game.iflags.window_inited = true;
        pushRngLogEntry('^toplin[tty_init_nhwindows=0]');
        status_initialize();
        // C ref: allmain.c:758 — display_nhwindow(WIN_MESSAGE, FALSE)
        // Called after status_initialize, before newgame, to flush message window.
        await tty_display_nhwindow('message', false);
 
        // C ref: wintty.c:568 — display copyright banner at row 4
        // before "Who are you?" prompt. Uses tty_curs + tty_putstr.
        const display = game?.nhDisplay || null;
        if (display) {
            // C ref: wintty.c:568 — copyright at row 4
            const bannerC = this.versionBanner || TELEPORT_BANNER_C;
            display.putstr(0, 4, COPYRIGHT_BANNER_A);
            display.putstr(0, 5, COPYRIGHT_BANNER_B);
            display.putstr(0, 6, bannerC);
            display.putstr(0, 7, COPYRIGHT_BANNER_D);
            // Save banner for restoration after chargen menu clears
            game._copyrightBanner = [
                COPYRIGHT_BANNER_A,
                COPYRIGHT_BANNER_B,
                bannerC,
                COPYRIGHT_BANNER_D,
            ];
            game._bannerVisible = true;
        }
        await playerSelection(g);
        if (g._chargenQuit) {
            // C ref: tty_player_selection → bail() → tty_exit_nhwindows
            // → tty_suspend_nhwindows → settty → end_screen, which clears
            // MAP and STATUS windows producing 2 botlx events.
            setBotlx('tty_clear_nhwindow');
            setBotlx('tty_clear_nhwindow');
            return;
        }
 
        // Run full game initialization
        await newgame();
 
        // C ref: sys/unix/unixmain.c wd_message() after newgame().
        if (g.flags.explore) {
            await You('are in non-scoring explore/discovery mode.');
        }
 
        // Run moveloop preamble (moon phase, luck, initial movement)
        await moveloop_preamble(false);
    }
 
    // Feed keystrokes and run game turns (chargen replay)
    async playTurns(keys) {
        if (typeof keys === 'string') {
            keys = [...keys].map(ch => ch.charCodeAt(0));
        }
        // playTurns pushes one key at a time, creating an extra screen
        // capture at each moveloop nhgetch. Menu commands need to replace
        // this pre-command capture with the menu screen.
        game._chargenMenuReplace = true;

        for (const key of keys) {
            pushInput(key);
            try {
                await moveloop_core();
            } catch (e) {
                if (!e.message?.includes('not yet ported')
                    && !e.message?.includes('Input queue empty'))
                    throw e;
                // Swallow "not yet ported" and "Input queue empty"
                // (menu/prompt waiting for dismiss key not in session)
            }
        }
        game._chargenMenuReplace = false;

    }
 
    // Capture current screen state for comparison.
    // During replay, moveloop_core calls docrt() at the display phase,
    // matching C's screen capture timing (after monsters, before input).
    async captureScreen() {
        // Always redraw before capture to reflect current game state
        // (monster positions, hero position, messages) after command execution.
        await docrt(false, true);
        game._lastCapturedScreen = game._screen_output || '';
        this._screens.push(game._lastCapturedScreen);
        // Clear so next iteration produces a fresh capture
        game._screen_output = '';
    }
 
    // Get captured screens for comparison
    getScreens() { return this._screens; }
    getCursors() { return this._cursors; }
    getRngSlices() { return this._rngSlices || []; }
 
    // Get the RNG call log for comparison
    getRngLog() { return getRngLog(); }
    getRngCallCount() { return getRngCallCount(); }
}
 
// NOTE: differs from canonical options.js — local returns flat { name, role, race, ... } object
// for direct use by nethack.js start(); canonical returns array of { target, value } parse results
// Parse a key specification from BIND= lines.
// C ref: cmd.c txt2key() — converts "^X", "M-x", single char, etc. to key code.
function parseKeySpec(spec) {
    if (!spec) return null;
    // ^X = Ctrl-X
    if (spec.length === 2 && spec[0] === '^') {
        const c = spec[1].toUpperCase().charCodeAt(0);
        if (c >= 64 && c <= 95) return c & 0x1f; // ^A=1, ^Z=26, ^[=27, etc.
        return null;
    }
    // M-x = Meta-x (Alt-x)
    if (spec.length === 3 && spec.startsWith('M-')) {
        return spec.charCodeAt(2) | 0x80;
    }
    // Single character
    if (spec.length === 1) {
        return spec.charCodeAt(0);
    }
    return null;
}
 
function parseNethackrc(rc) {
    const raceMap = { 'human': 0, 'elf': 1, 'dwarf': 2, 'gnome': 3, 'orc': 4 };
    const genderMap = { 'male': 0, 'female': 1 };
    const alignMap = { 'chaotic': 0, 'neutral': 1, 'lawful': 2 };
 
    const result = {
        name: '', role: -1, race: -1, gender: -1, align: -1,
        wizard: false, explore: false,
        // Boolean flags from OPTIONS
        showexp: false, time: false, autopickup: false, lit_corridor: false,
        color: true, dark_room: true, pushweapon: false, fireassist: true, verbose: true, symset: null,
        mention_walls: false,
        pettype: null,
        legacy: true, splash_screen: true,
        tutorial: false, tutorial_set: false,
        mail: true, // C ref: flags.biff — intentionally true; causes seed0209
                    // parity failure until C harness records with mail enabled
                    // or sessions add OPTIONS=!mail to their nethackrc
    };
 
    for (const line of (rc || '').split('\n')) {
        const trimmedLine = line.trim();
        if (!trimmedLine || trimmedLine.startsWith('#')) continue;
 
        // cfgfiles-style standalone directives (outside OPTIONS=).
        // C config accepts NAME=/ROLE=/RACE=/GENDER=/ALIGN= in addition
        // to their OPTIONS:key:value equivalents.
        const kvMatch = trimmedLine.match(/^([A-Za-z_]+)\s*=\s*(.*)$/);
        if (kvMatch) {
            const key = kvMatch[1].toUpperCase();
            const rawVal = kvMatch[2].trim();
            const lval = rawVal.toLowerCase();
            if (key === 'NAME') result.name = rawVal;
            else if (key === 'ROLE' && lval in roleMap) result.role = roleMap[lval];
            else if (key === 'RACE' && lval in raceMap) result.race = raceMap[lval];
            else if (key === 'GENDER' && lval in genderMap) result.gender = genderMap[lval];
            else if (key === 'ALIGN' && lval in alignMap) result.align = alignMap[lval];
        }
 
        const m = line.match(/^OPTIONS=(.+)/);
        if (m) {
            for (const opt of m[1].split(',')) {
                const trimmed = opt.trim();
                // Handle boolean flags: "flag" enables, "!flag" disables
                const negated = trimmed.startsWith('!');
                const flagName = negated ? trimmed.slice(1) : trimmed;
 
                // Check for key:value pairs
                const colonIdx = flagName.indexOf(':');
                if (colonIdx >= 0) {
                    const key = flagName.slice(0, colonIdx).trim();
                    const val = flagName.slice(colonIdx + 1).trim();
                    const lval = val.toLowerCase();
                    if (key === 'name') result.name = val || '';
                    else if (key === 'role' && lval in roleMap) result.role = roleMap[lval];
                    else if (key === 'race' && lval in raceMap) result.race = raceMap[lval];
                    else if (key === 'gender' && lval in genderMap) result.gender = genderMap[lval];
                    else if (key === 'align' && lval in alignMap) result.align = alignMap[lval];
                    else if (key === 'symset') result.symset = val;
                    else if (key === 'pettype') result.pettype = lval;
                    else if (key === 'msg_window') result.msg_window = lval;
                    else if (key === 'playmode') {
                        if (lval === 'debug') result.wizard = true;
                        else if (lval === 'explore') result.explore = true;
                    }
                } else {
                    // Boolean flag
                    const lname = flagName.toLowerCase();
                    if (lname === 'showexp') result.showexp = !negated;
                    else if (lname === 'time') result.time = !negated;
                    else if (lname === 'verbose') result.verbose = !negated;
                    else if (lname === 'autopickup') result.autopickup = !negated;
                    else if (lname === 'lit_corridor') result.lit_corridor = !negated;
                    else if (lname === 'pushweapon') result.pushweapon = !negated;
                    else if (lname === 'fireassist') result.fireassist = !negated;
                    else if (lname === 'color') result.color = !negated;
                    else if (lname === 'dark_room') result.dark_room = !negated;
                    else if (lname === 'mention_walls') result.mention_walls = !negated;
                    else if (lname === 'legacy') result.legacy = !negated;
                    else if (lname === 'splash_screen') result.splash_screen = !negated;
                    else if (lname === 'tutorial') {
                        result.tutorial = !negated;
                        result.tutorial_set = true;
                    }
                    else if (lname === 'mail') result.mail = !negated;
                }
            }
        }
        // WIZARD=name directive
        if (line.match(/^WIZARD=/i)) result.wizard = true;
        // SYMBOLS= per-symbol overrides (separate from OPTIONS=)
        // C ref: cfgfiles.c:1189-1195 — SYMBOLS= and ROGUESYMBOLS= lines
        const symMatch = line.match(/^SYMBOLS=(.+)/i);
        if (symMatch) {
            if (!result.symbols) result.symbols = [];
            result.symbols.push(symMatch[1].trim());
        }
        const rogueSymMatch = line.match(/^ROGUESYMBOLS=(.+)/i);
        if (rogueSymMatch) {
            if (!result.rogueSymbols) result.rogueSymbols = [];
            result.rogueSymbols.push(rogueSymMatch[1].trim());
        }
        // BIND=key:command — custom key bindings
        // C ref: cfgfiles.c BIND= → cmd.c bind_key()
        const bindMatch = line.match(/^BIND=(.+)/i);
        if (bindMatch) {
            if (!result.bindings) result.bindings = [];
            result.bindings.push(bindMatch[1].trim());
        }
    }
    return result;
}
 
// Convenience: create and start a game from session data
export async function gameFromSession(sessionData) {
    const env = sessionData.env || {};
    const seed = sessionData.seed || parseInt(env.NETHACK_SEED || '0');
    const datetime = env.NETHACK_FIXED_DATETIME || null;
    // All sessions use from-keylog mode: moves contains the complete key
    // sequence from game launch (startup prompts + gameplay).
    let rc = sessionData.nethackrc || '';
 
    // Extract build version banner from session screen data (build-specific).
    // The version line may have 9 leading spaces or \x1b[9C cursor-forward.
    let versionBanner = null;
    for (const step of (sessionData.steps || [])) {
        if (step.screen && step.screen.includes('Version ')) {
            const m = step.screen.match(/(?:\x1b\[\d+C| {9})(Version [^\n]+)/);
            if (m) { versionBanner = '         ' + m[1]; break; }
        }
    }
 
    const nhGame = new NethackGame({
        seed,
        datetime,
        nethackrc: rc,
    });
    if (versionBanner) nhGame.versionBanner = versionBanner;
 
    // All sessions use from-keylog: push all keys and replay through
    // startup (chargen/lore/tutorial) + gameplay in one pass.
    // Display installed inside start() after game object exists.
    const display = createHeadlessPromptRuntime();
    display.onEmptyQueue = () => { throw new Error('Input queue empty - test may be missing keystrokes'); };
    nhGame._pendingDisplay = display;
 
    const allSteps = sessionData.steps || [];
    // Prefer regen.moves when available — it contains the complete key
    // sequence including type-ahead keys that C consumed within a step.
    // extractSessionKeys(steps) misses type-ahead keys because they
    // don't get their own step entry in the C recording.
    const stepKeys = extractSessionKeys(allSteps);
    // Check if regen.moves is in raw char format (not escaped hex).
    // Escaped format has literal '\' 'x' sequences; raw has actual control chars.
    const regenRaw = sessionData.regen?.moves;
    const regenKeys = regenRaw && !regenRaw.startsWith('\\x')
        ? [...regenRaw].map(ch => ch.charCodeAt(0))
        : null;
    const allKeys = (regenKeys && regenKeys.length >= stepKeys.length)
        ? regenKeys : stepKeys;
    // Compute type-ahead nhgetch indices where screen capture should be
    // suppressed. These are keys present in regen.moves but not in steps —
    // C consumed them as type-ahead without a NOMUX blocking point.
    // Only apply when regen.moves is a good match for step keys (some
    // sessions have regen.moves in escaped encoding that doesn't match).
    if (regenKeys && regenKeys.length > stepKeys.length) {
        const typeAhead = new Set();
        let ri = 0, si = 0;
        while (ri < regenKeys.length && si < stepKeys.length) {
            if (regenKeys[ri] === stepKeys[si]) { ri++; si++; }
            else { typeAhead.add(ri); ri++; }
        }
        while (ri < regenKeys.length) { typeAhead.add(ri); ri++; }
        // Sanity check: most step keys should have matched
        if (si === stepKeys.length && typeAhead.size > 0) {
            nhGame._typeAheadCaptures = typeAhead;
        }
    }
    for (const key of allKeys) {
        display.pushKey(key);
    }
 
    nhGame._installHookAfterInit = true;
    // Force promptedStartup for legacy startup flows in older sessions, but
    // not when rc explicitly disables startup pagers/tutorials (starter flows).
    const noLegacyStartup =
        /OPTIONS=.*(?:^|,)!legacy(?:,|$)/mi.test(rc)
        && /OPTIONS=.*(?:^|,)!splash_screen(?:,|$)/mi.test(rc)
        && /OPTIONS=.*(?:^|,)!tutorial(?:,|$)/mi.test(rc);
    nhGame._forcePromptedStartup = !noLegacyStartup;
    await nhGame.start();
    // Chargen quit sessions end at player selection; C records no gameplay/tut.
    // Stop replay here to avoid post-quit capture drift.
    if (game._chargenQuit) {
        // Some chargen-quit fixtures include one final frame equal to the
        // previous menu image. Pad missing capture(s) by repeating the last
        // captured frame rather than running gameplay loops.
        const targetScreens = allSteps.length;
        const screens = nhGame.getScreens();
        const cursors = nhGame.getCursors();
        if (screens.length > 0) {
            const lastScreen = screens[screens.length - 1];
            const lastCursor = cursors.length > 0 ? cursors[cursors.length - 1] : [0, 0, 1];
            while (screens.length < targetScreens) {
                screens.push(lastScreen);
                cursors.push(lastCursor);
            }
        }
        return nhGame;
    }
    await maybe_do_tutorial();
    game.promptedStartup = false;
    setStartupPromptPhase(false);
 
    {
        // C harness records one capture per input boundary: initial frame plus
        // one frame per consumed key. Stop as soon as we have that many.
        const targetScreens = allSteps.length;
        const maxIter = Math.max(targetScreens * 8, 1024);
        let stallIters = 0;
        let lastScreenCount = nhGame.getScreens().length;
 
        for (let iter = 0; iter < maxIter; iter++) {
            if (nhGame.getScreens().length >= targetScreens) {
                // C records RNG/events through the final monster-phase boundary
                // before the next input read. If replay has reached target
                // captures while a turn is still pending, flush that boundary
                // without attempting to read another key.
                if (game.context?.move) {
                    try {
                        await moveloop_core_monsters_only();
                    } catch (flushErr) {
                        const flushMsg = String(flushErr?.message || '');
                        if (!flushMsg.includes('Input queue empty')) throw flushErr;
                    }
                }
                break;
            }
            try {
                await moveloop_core();
            } catch (e) {
                // ShellEscape (! command) and GameInterrupt (^C) are
                // flow-control signals. During replay, skip them and
                // continue the loop — there's no subshell to enter.
                if (e?.constructor?.name === 'ShellEscape'
                    || e?.constructor?.name === 'GameInterrupt')
                    continue;
                // GameQuit (#quit y) is the normal game-over signal.
                // Break out of replay so gameFromSession can finalize
                // the RNG log and return the game state.
                if (e?.constructor?.name === 'GameQuit') break;
                const msg = String(e?.message || '');
                if (msg.includes('not yet ported'))
                    break;
                if (msg.includes('Input queue empty')) {
                    // C reaches nhgetch only after finishing any pending
                    // post-command monster-phase work. Replay can hit an empty
                    // queue at command-read boundary with context.move still
                    // pending; flush that phase without reading more input.
                    if (game.context?.move) {
                        try {
                            await moveloop_core_monsters_only();
                        } catch (flushErr) {
                            const flushMsg = String(flushErr?.message || '');
                            if (!flushMsg.includes('Input queue empty')) throw flushErr;
                        }
                    }
                    break;
                }
                throw e;
            }
 
            const screensNow = nhGame.getScreens().length;
            const queueEmpty = (game?.nhDisplay?.inputQueueLength ?? 0) === 0;
            if (queueEmpty && screensNow >= targetScreens) break;
            // No keys left and no new input-boundary capture after a core tick:
            // replay has reached fixture boundary; stop before autonomous drift.
            if (queueEmpty && screensNow === lastScreenCount) break;
            if (screensNow === lastScreenCount) {
                stallIters++;
                if (stallIters > 256) {
                    throw new Error(
                        `Replay stalled before reaching target captures: `
                        + `screens=${screensNow}/${targetScreens}, `
                        + `keys=${allKeys.length}, iter=${iter + 1}/${maxIter}`
                    );
                }
            } else {
                stallIters = 0;
                lastScreenCount = screensNow;
            }
        }
    }
 
    // Trim trailing monster-movement events from the last partial iteration.
    // C's recording stops at nhgetch; JS runs monster turns before nhgetch
    // throws "Input queue empty". Remove these extra events from the end.
    const log = getRngLog();
    // C ref: recording stops at nhgetch; JS runs one more partial iteration.
    // Trim only monster-movement events from that trailing iteration.
    // Do NOT trim >bot/<bot — they are legitimately the last events in sessions
    // where the final step includes a menu dismiss with docorner's bot call.
    // Extra JS bot calls beyond C's event count are ignored by the comparator
    // (it uses C's count as authoritative), so trimming them is unnecessary.
    const monsterEventPrefixes = ['^mcalcmove', '^movemon_turn', '^distfleeck',
        '>m_move', '>dog_move', '>mfndpos', '^dog_invent', '^dog_goal',
        '^dog_move'];
    while (log.length > 0) {
        const last = log[log.length - 1];
        if (typeof last !== 'string') break;
        if (!monsterEventPrefixes.some(p => last.startsWith(p))) break;
        log.pop();
    }
 
    return nhGame;
}
 
const roleMap = {
    'archeologist': 0, 'barbarian': 1, 'caveman': 2, 'healer': 3,
    // C ref: role.c roles[] — Rogue precedes Ranger (comment at line 316)
    'knight': 4, 'monk': 5, 'priest': 6, 'rogue': 7,
    'ranger': 8, 'samurai': 9, 'tourist': 10, 'valkyrie': 11, 'wizard': 12,
};
 
const genders = [
    { adj: 'male', allow: ROLE_MALE },
    { adj: 'female', allow: ROLE_FEMALE },
];
 
// C ref: role.c gr.rfilter — role filter state for reset_role_filtering
function ensureRfilter() {
    if (!game.rfilter) {
        game.rfilter = { mask: 0, roles: new Array(roles.length).fill(false) };
    }
    return game.rfilter;
}
 
function okRole(rolenum, racenum, gendnum, alignnum) {
    if (rolenum >= 0 && rolenum < roles.length) {
        const rf = ensureRfilter();
        if (rf.roles[rolenum]) return false;
        const allow = roles[rolenum].allow;
        if (racenum >= 0 && racenum < races.length
            && !(allow & races[racenum].allow & ROLE_RACEMASK))
            return false;
        if (gendnum >= 0 && gendnum < ROLE_GENDERS
            && !(allow & genders[gendnum].allow & ROLE_GENDMASK))
            return false;
        if (alignnum >= 0 && alignnum < ROLE_ALIGNS
            && !(allow & aligns[alignnum].allow & ROLE_ALIGNMASK))
            return false;
        return true;
    }
    return roles.some((_, i) => okRole(i, racenum, gendnum, alignnum));
}
 
function okRace(rolenum, racenum, gendnum, alignnum) {
    if (racenum >= 0 && racenum < races.length) {
        const rf = ensureRfilter();
        if (rf.mask & (races[racenum].selfmask ?? 0)) return false;
        const allow = races[racenum].allow;
        if (rolenum >= 0 && rolenum < roles.length
            && !(allow & roles[rolenum].allow & ROLE_RACEMASK))
            return false;
        if (gendnum >= 0 && gendnum < ROLE_GENDERS
            && !(allow & genders[gendnum].allow & ROLE_GENDMASK))
            return false;
        if (alignnum >= 0 && alignnum < ROLE_ALIGNS
            && !(allow & aligns[alignnum].allow & ROLE_ALIGNMASK))
            return false;
        return true;
    }
    return races.some((_, i) => okRace(rolenum, i, gendnum, alignnum));
}
 
function okGend(rolenum, racenum, gendnum) {
    if (gendnum >= 0 && gendnum < ROLE_GENDERS) {
        const rf = ensureRfilter();
        if (rf.mask & genders[gendnum].allow) return false;
        const allow = genders[gendnum].allow;
        if (rolenum >= 0 && rolenum < roles.length
            && !(allow & roles[rolenum].allow & ROLE_GENDMASK))
            return false;
        if (racenum >= 0 && racenum < races.length
            && !(allow & races[racenum].allow & ROLE_GENDMASK))
            return false;
        return true;
    }
    return genders.some((_, i) => okGend(rolenum, racenum, i));
}
 
function okAlign(rolenum, racenum, alignnum) {
    if (alignnum >= 0 && alignnum < ROLE_ALIGNS) {
        const rf = ensureRfilter();
        if (rf.mask & aligns[alignnum].allow) return false;
        const allow = aligns[alignnum].allow;
        if (rolenum >= 0 && rolenum < roles.length
            && !(allow & roles[rolenum].allow & ROLE_ALIGNMASK))
            return false;
        if (racenum >= 0 && racenum < races.length
            && !(allow & races[racenum].allow & ROLE_ALIGNMASK))
            return false;
        return true;
    }
    return aligns.slice(0, ROLE_ALIGNS).some((_, i) => okAlign(rolenum, racenum, i));
}
 
// C ref: role.c:1284 setrolefilter() — parse a string like "Caveman" or "Orc"
// and set the corresponding filter bit/role slot.
function setRoleFilter(bufp) {
    const rf = ensureRfilter();
    const lower = bufp.toLowerCase();
    // Try role names
    for (let i = 0; i < roles.length; i++) {
        const m = roles[i].name?.m?.toLowerCase();
        const f = roles[i].name?.f?.toLowerCase();
        if (m === lower || f === lower) { rf.roles[i] = true; return true; }
    }
    // Try race nouns
    for (let i = 0; i < races.length; i++) {
        if (races[i].noun?.toLowerCase() === lower) {
            rf.mask |= (races[i].selfmask ?? 0);
            return true;
        }
    }
    // Try gender adj
    for (let i = 0; i < ROLE_GENDERS; i++) {
        if (genders[i].adj?.toLowerCase() === lower) {
            rf.mask |= genders[i].allow;
            return true;
        }
    }
    // Try alignment adj
    for (let i = 0; i < ROLE_ALIGNS; i++) {
        if (aligns[i].adj?.toLowerCase() === lower) {
            rf.mask |= aligns[i].allow;
            return true;
        }
    }
    return false;
}
 
// C ref: role.c:1303 gotrolefilter()
function gotRoleFilter() {
    const rf = ensureRfilter();
    if (rf.mask) return true;
    return rf.roles.some(v => v);
}
 
// C ref: role.c:1358 clearrolefilter(RS_filter) — clear all filters
function clearRoleFilterAll() {
    const rf = ensureRfilter();
    rf.mask = 0;
    for (let i = 0; i < rf.roles.length; i++) rf.roles[i] = false;
}
 
function pickOne(indices) {
    if (indices.length === 0) return ROLE_NONE;
    return indices[rn2(indices.length)];
}
 
function pickRole(racenum, gendnum, alignnum) {
    const ok = roles.map((_, i) => i).filter(i =>
        okRole(i, racenum, gendnum, alignnum)
        && okRace(i, racenum >= 0 ? racenum : ROLE_RANDOM, gendnum, alignnum)
        && okGend(i, racenum, gendnum >= 0 ? gendnum : ROLE_RANDOM)
        && okAlign(i, racenum, alignnum >= 0 ? alignnum : ROLE_RANDOM));
    if (typeof process !== 'undefined' && process.env?.CHARGEN_TRACE) {
        // eslint-disable-next-line no-console
        console.error(`[CHARGEN] pickRole race=${racenum} gend=${gendnum} align=${alignnum} -> ok=[${ok.join(',')}] count=${ok.length}`);
    }
    return pickOne(ok);
}
 
function pickRace(rolenum, gendnum, alignnum) {
    const ok = races.map((_, i) => i).filter(i => okRace(rolenum, i, gendnum, alignnum));
    if (typeof process !== 'undefined' && process.env?.CHARGEN_TRACE) {
        // eslint-disable-next-line no-console
        console.error(`[CHARGEN] pickRace role=${rolenum} gend=${gendnum} align=${alignnum} -> ok=[${ok.join(',')}] count=${ok.length}`);
    }
    return pickOne(ok);
}
 
function pickGend(rolenum, racenum, _alignnum) {
    const ok = genders.map((_, i) => i).filter(i => okGend(rolenum, racenum, i));
    if (typeof process !== 'undefined' && process.env?.CHARGEN_TRACE) {
        // eslint-disable-next-line no-console
        console.error(`[CHARGEN] pickGend role=${rolenum} race=${racenum} -> ok=[${ok.join(',')}] count=${ok.length}`);
    }
    return pickOne(ok);
}
 
function pickAlign(rolenum, racenum, _gendnum) {
    const ok = aligns.slice(0, ROLE_ALIGNS).map((_, i) => i).filter(i => okAlign(rolenum, racenum, i));
    if (typeof process !== 'undefined' && process.env?.CHARGEN_TRACE) {
        // eslint-disable-next-line no-console
        console.error(`[CHARGEN] pickAlign role=${rolenum} race=${racenum} -> ok=[${ok.join(',')}] count=${ok.length}`);
    }
    return pickOne(ok);
}
 
function normalizeStartupAlignIndex(alignnum) {
    if (alignnum === 0) return 2; // lawful -> internal lawful
    if (alignnum === 1) return 1; // neutral -> internal neutral
    if (alignnum === 2) return 0; // chaotic -> internal chaotic
    return alignnum;
}
 
function rigidRoleChecks(flags) {
    // C ref: role.c:1234 rigid_role_checks()
    // Uses pick_* with PICK_RIGID which returns value ONLY if single choice.
    // CRITICAL: pick_* calls rn2(count) even for count=1. Must consume RNG.
    if (flags.initrole !== ROLE_NONE) {
        if (flags.initrace === ROLE_NONE) {
            const choices = races.map((_, i) => i).filter(i =>
                okRace(flags.initrole, i, flags.initgend, flags.initalign));
            if (choices.length === 1) flags.initrace = pickOne(choices);
        }
        if (flags.initalign === ROLE_NONE) {
            const choices = aligns.slice(0, ROLE_ALIGNS).map((_, i) => i).filter(i =>
                okAlign(flags.initrole, flags.initrace, i));
            if (choices.length === 1) flags.initalign = pickOne(choices);
        }
        if (flags.initgend === ROLE_NONE) {
            const choices = genders.map((_, i) => i).filter(i =>
                okGend(flags.initrole, flags.initrace, i));
            if (choices.length === 1) flags.initgend = pickOne(choices);
        }
    }
}
 
function roleMenuChoices(gendnum, racenum, alignnum) {
    let last = '';
    return roles.map((role, index) => {
        let key = role.name.m[0].toLowerCase();
        if (key === last) key = key.toUpperCase();
        last = key.toLowerCase();
        let label = role.name.m;
        if (gendnum === 1 && role.name.f) {
            label = role.name.f;
        } else if (gendnum < 0 && role.name.f) {
            label = `${role.name.m}/${role.name.f}`;
        }
        return { index, key, label };
    }).filter(choice =>
        okRole(choice.index, racenum, gendnum, alignnum)
        && okRace(choice.index, racenum, gendnum, alignnum)
        && okGend(choice.index, racenum, gendnum)
        && okAlign(choice.index, racenum, alignnum));
}
 
function facetChoices(items, labelKey, predicate) {
    return items.map((item, index) => ({
        index,
        key: item[labelKey][0],
        label: item[labelKey],
    })).filter(choice => predicate(choice.index));
}
 
// Chargen navigation codes returned by selectPrompt
const CHARGEN_QUIT = -1;
const CHARGEN_RANDOM = -2;
const CHARGEN_PICK_ROLE = -10;
const CHARGEN_PICK_RACE = -11;
const CHARGEN_PICK_GENDER = -12;
const CHARGEN_PICK_ALIGN = -13;
const CHARGEN_FILTER = -14;
 
async function selectPrompt(query, choices) {
    if (choices.length === 1) {
        if (typeof process !== 'undefined' && process.env?.CHARGEN_TRACE) {
            // eslint-disable-next-line no-console
            console.error(`[CHARGEN] selectPrompt(${query}) short-circuit single choice=${choices[0].index}`);
        }
        return choices[0].index;
    }
    while (true) {
        const key = await selectPromptMenu(query, choices);
        if (typeof process !== 'undefined' && process.env?.CHARGEN_TRACE) {
            // eslint-disable-next-line no-console
            console.error(`[CHARGEN] selectPrompt(${query}) got key=${JSON.stringify(key)}`);
        }
        // C ref: role_menu_extra items for cross-navigation
        if (key === 'q') return CHARGEN_QUIT;
        if (key === '*') return CHARGEN_RANDOM;
        if (key === '?') return CHARGEN_PICK_ROLE;
        if (key === '/') return CHARGEN_PICK_RACE;
        if (key === '"') return CHARGEN_PICK_GENDER;
        if (key === '[') return CHARGEN_PICK_ALIGN;
        if (key === '~') return CHARGEN_FILTER;
        const picked = choices.find(choice => choice.key === key);
        if (picked) return picked.index;
        // Unknown key: bell and loop (C behavior)
    }
}
 
function selectionSummary(g) {
    const roleName = (g.flags.initrole < 0)
        ? '<role>'
        : (g.flags.initgend === 1 && roles[g.flags.initrole].name.f)
            ? roles[g.flags.initrole].name.f
            : roles[g.flags.initrole].name.m;
    if (!g.plname || g.flags.initrole < 0 || g.flags.initrace < 0
        || g.flags.initgend < 0 || g.flags.initalign < 0) {
        return `${roleName} ${g.flags.initrace < 0 ? '<race>' : races[g.flags.initrace].noun}`
            + ` ${g.flags.initgend < 0 ? '<gender>' : genders[g.flags.initgend].adj}`
            + ` ${g.flags.initalign < 0 ? '<alignment>' : aligns[g.flags.initalign].adj}`;
    }
    return `${g.plname} the ${aligns[g.flags.initalign].adj}`
        + ` ${g.flags.initgend < 0 ? '<gender>' : genders[g.flags.initgend].adj}`
        + ` ${g.flags.initrace < 0 ? '<race>' : races[g.flags.initrace].adj}`
        + ` ${roleName}`;
}
 
// C ref: role.c:1816 role_menu_extra — generates one line for a facet.
// Returns either a forced-value note or a navigation item.
function roleMenuExtraLine(facet, g) {
    const r = g.flags.initrole;
    const c = g.flags.initrace;
    const letters = { role: '?', race: '/', gender: '"', alignment: '[' };
    const letter = letters[facet] || '?';
 
    if (facet === 'role') {
        // Role: never forced by another facet (only by filter, which we don't port)
        return `${letter} - Pick${r >= 0 ? ' another' : ''} role first`;
    }
    if (facet === 'race') {
        // C ref: role.c:1848-1866 — race forced if role allows only one race
        if (r >= 0) {
            const raceChoices = races.map((_, i) => i).filter(i =>
                okRace(r, i, g.flags.initgend, g.flags.initalign));
            if (raceChoices.length === 1) {
                return `    role forces ${races[raceChoices[0]].noun}`;
            }
        }
        return `${letter} - Pick${g.flags.initrace >= 0 ? ' another' : ''} race first`;
    }
    if (facet === 'gender') {
        // C ref: role.c:1868-1888 — gender forced if role allows only one
        if (r >= 0) {
            const ROLE_GENDMASK_VAL = ROLE_GENDMASK;
            const allowmask = roles[r].allow & ROLE_GENDMASK_VAL;
            if (allowmask === ROLE_MALE) return '    role forces male';
            if (allowmask === ROLE_FEMALE) return '    role forces female';
        }
        return `${letter} - Pick${g.flags.initgend >= 0 ? ' another' : ''} gender first`;
    }
    if (facet === 'alignment') {
        // C ref: role.c:1890-1925 — alignment forced by role or race
        if (r >= 0) {
            const allowmask = roles[r].allow & ROLE_ALIGNMASK;
            if (allowmask === 0x04) return '    role forces lawful';
            if (allowmask === 0x02) return '    role forces neutral';
            if (allowmask === 0x01) return '    role forces chaotic';
        }
        if (c >= 0) {
            const allowmask = races[c].allow & ROLE_ALIGNMASK;
            if (allowmask === 0x04) return '    race forces lawful';
            if (allowmask === 0x02) return '    race forces neutral';
            if (allowmask === 0x01) return '    race forces chaotic';
        }
        return `${letter} - Pick${g.flags.initalign >= 0 ? ' another' : ''} alignment first`;
    }
    return '';
}
 
function allowSingleAlign(mask) {
    const bits = mask & ROLE_ALIGNMASK;
    return bits && (bits & (bits - 1)) === 0;
}
 
function articleize(label) {
    const lower = label[0]?.toLowerCase() || '';
    return ` ${'aeiou'.includes(lower) ? 'an' : 'a'} ${label}`;
}
 
// C ref: H2344_BROKEN offx computation + putchar(' ') leading space.
// C: maxcol = max(strlen(str) + 2) across items; offx = min(min(82, cols/2), cols - maxcol - 1)
// C renders at offx (cursor column) then putchar(' '), so text starts at offx + 1.
// JS returns the TEXT column (= C's offx + 1) directly.
function computeMenuOffset(cols, lines, { fullWidth = false } = {}) {
    if (fullWidth) return 1; // C fullscreen: offx=0, text at column 1
    const maxcol = lines.reduce((m, line) => Math.max(m, line.length), 0);
    // C's strlen + 2 accounts for leading + trailing space margins.
    // offx = min(min(82, cols/2), cols - (maxcol+2) - 1); textPos = offx + 1
    const cOffx = Math.min(Math.min(82, Math.trunc(cols / 2)), cols - maxcol - 3);
    return Math.max(1, cOffx + 1);
}
 
// C ref: wintty.c tty_end_menu + tty_display_nhwindow for NHW_MENU
// C (with H2344_BROKEN defined) computes:
//   cols = max(strlen(item->str) + 2) across all items and morestr
//   offx = min(min(82, tty_cols/2), tty_cols - cols - 1)
//   fullscreen if maxrow >= rows or !menu_overlay
//   if fullscreen: offx=0
// maxrow = nitems + 1 for single-page menus.
function computeCMenuLayout(cols, rows, lines) {
    // C's tty_end_menu: len = strlen(str) + 2 for each item
    let cCols = Math.max(6, ...lines.map(l => l.length + 2)); // 6 = strlen("(end) ")
    // C ref: H2344_BROKEN offx formula
    let offx = Math.min(Math.min(82, Math.trunc(cols / 2)), cols - cCols - 1);
    if (offx < 0) offx = 0;
    const maxrow = lines.length;
    const fullscreen = (maxrow >= rows);
    if (fullscreen) offx = 0;
    return { offx, maxrow };
}
 
// Create a NHW_MENU window, mark active, return winId.
// C ref: plsel_startmenu → create_nhwindow(NHW_MENU)
function chargenMenuCreate() {
    const winId = tty_create_nhwindow(NHW_MENU);
    if (winId >= 0 && game.wins[winId]) game.wins[winId].active = true;
    return winId;
}
 
// Dismiss a chargen menu window matching C's destroy_nhwindow sequence.
// C ref: tty_dismiss_nhwindow(win) → erase_menu_or_text → docorner
// For fullscreen menus (offx=0): erase_menu_or_text → term_clear_screen
//   which clears MAP (setBotlx) and STATUS (setBotlx).
// For corner menus (offx!=0): erase_menu_or_text → docorner
async function chargenMenuDismiss(winId, offx, maxrow) {
    tty_dismiss_nhwindow(winId);
    erase_menu_or_text(winId, offx, maxrow);
    if (offx === 0) {
        // C ref: erase_menu_or_text offx=0 with in_role_selection → clear=TRUE
        // → term_clear_screen() → erase_tty_screen → tty_clear_nhwindow(WIN_MAP)
        // + tty_clear_nhwindow(WIN_STATUS). Each emits SET_BOTLX.
        setBotlx('tty_clear_nhwindow');
        setBotlx('tty_clear_nhwindow');
        // Fullscreen clear wipes everything — reset the minimum offx
        // so subsequent corner menus don't over-clear below their area.
        game._chargenMinOffx = undefined;
    } else {
        await docorner(offx, maxrow + 1);
    }
    tty_destroy_nhwindow(winId);
}
 
async function renderChargenMenu(display, title, lines, options = {}) {
    if (!display) return 0;
    const startupOverlay = isStartupPromptPhase();
    // C ref: tty_display_nhwindow(WIN_MENU) clears windows before rendering
    const maxcol = lines.reduce((m, l) => Math.max(m, l.length), title.length);
    await tty_display_nhwindow('menu', false, { maxcol, maxrow: lines.length });
    // C ref: wintty.c:1926-1935 — fullscreen menus use term_clear_screen(),
    // corner menus use cl_end() per row from offx. During startup overlay,
    const cols = display.cols || 80;
    // clear from menu offset onwards to preserve copyright text to the left.
    if (!startupOverlay) {
        display.clearScreen();
    } else {
        // C ref: wintty.c process_menu_window — cl_end from offx per row.
        // Menu rows (0 to menu height): clear fully to remove prior content.
        // Rows below menu: clear only from offx onwards (preserve "Who are
        // you?" prompt, copyright banner, and other prior screen content).
        const offx = computeMenuOffset(cols, lines, options);
        const menuHeight = lines.length;
        // Track the minimum offx seen across chargen menus. Rows below
        // menuHeight need clearing from the smallest offx ever used
        // (e.g., fullWidth role menu used offx=1, race menu uses offx=30,
        // but "Tourist" from the role menu at column 1 must be cleared).
        const prevMinOffx = game._chargenMinOffx ?? offx;
        game._chargenMinOffx = Math.min(prevMinOffx, offx);
        const clearFromCol = Math.max(0, game._chargenMinOffx - 1);
        for (let r = 0; r < (display.rows || 24); r++) {
            if (r < menuHeight) {
                display.clearRow(r);
            } else {
                for (let c = clearFromCol; c < cols; c++) {
                    display.setCell(c, r, ' ', 7/*CLR_GRAY*/, 0);
                }
            }
        }
        // Restore copyright banner to rows 4-7 only if the menu offset
        // is large enough AND the banner hasn't been cleared by a prior
        // fullscreen menu (like role selection with offx=1).
        const banner = game._copyrightBanner;
        if (banner && offx >= 30 && menuHeight > 4 && game._bannerVisible) {
            for (let i = 0; i < banner.length; i++) {
                if (banner[i]) display.putstr(0, 4 + i, banner[i]);
            }
        }
        // Track banner visibility: banner survives corner menus (offx>=30)
        // but is cleared by fullscreen menus (offx<30 covering rows 4-7)
        if (offx < 30 && menuHeight > 4) game._bannerVisible = false;
    }
    const offx = computeMenuOffset(cols, lines, options);
    display.putstr(offx, 0, title, CLR_GRAY, ATR_INVERSE);
    for (let i = 1; i < lines.length; i++) {
        if (lines[i]) {
            if (startupOverlay && i >= 4 && i <= 7 && offx > 0 && display.grid?.[i]) {
                const prefix = display.grid[i].slice(0, offx - 1).map(cell => cell.ch).join('');
                display.clearRow(i);
                if (prefix) display.putstr(0, i, prefix, CLR_GRAY);
                display.putstr(offx - 1, i, ' ', CLR_GRAY);
                display.putstr(offx, i, lines[i], CLR_GRAY);
                continue;
            }
            display.putstr(offx, i, lines[i], CLR_GRAY);
        }
    }
    return offx;
}
 
async function selectPromptMenu(query, choices) {
    const display = game?.nhDisplay || null;
    const g = game;
    // C ref: role.c:2814 plsel_startmenu() calls rigid_role_checks()
    // at the start of every chargen menu display. This forces single-choice
    // facets (e.g., Rogue → chaotic) WITH RNG consumption (rn2(1)).
    rigidRoleChecks(g.flags);
    const lines = [
        query,
        '',
        selectionSummary(g),
        '',
    ];
 
    const extras = [];
    if (query === 'Pick a role or profession') {
        for (const choice of choices) {
            lines.push(`${choice.key} -${articleize(choice.label)}`);
        }
        lines.push('* * Random');
        // C ref: role.c:2307+2316 — maybe_skip_seps counts total lines
        // (title,sep,status,sep + roles + random,sep + 5 nav + footer = n).
        // If n > screenheight, excess = n - rows; skip separator when
        // excess is 1 or 2 (i.e., only add separator when excess < 1 or > 2).
        const screenRows = (display?.rows || 24);
        const totalIfSep = 4 + choices.length + 2 + 5 + 1;
        const excess = totalIfSep > screenRows ? totalIfSep - screenRows : 0;
        if (excess < 1 || excess > 2) {
            lines.push('');
        }
        // C ref: role_menu_extra for race/gender/alignment/filter/quit
        lines.push(roleMenuExtraLine('race', g));
        lines.push(roleMenuExtraLine('gender', g));
        lines.push(roleMenuExtraLine('alignment', g));
        lines.push('~ - Set role/race/&c filtering');
        lines.push('q - Quit');
    } else {
        for (const choice of choices) {
            lines.push(`${choice.key} - ${choice.label}`);
        }
        lines.push('* * Random');
        lines.push('');
        // C ref: role_menu_extra adds navigation items for each facet.
        // For FORCED facets (single choice): "    role/race forces X" (disabled text)
        // For PICKABLE facets: "? - Pick [another] X first" (selectable)
        const menuType = query === 'Pick a race or species' ? 'race'
            : query === 'Pick a gender or sex' ? 'gender'
            : query === 'Pick an alignment or creed' ? 'alignment' : 'other';
        // Role extra (only for non-role menus)
        if (menuType !== 'role') {
            lines.push(roleMenuExtraLine('role', g));
        }
        // Race extra (only for non-race menus)
        if (menuType !== 'race') {
            lines.push(roleMenuExtraLine('race', g));
        }
        // Gender extra (only for non-gender menus)
        if (menuType !== 'gender') {
            lines.push(roleMenuExtraLine('gender', g));
        }
        // Alignment extra (only for non-alignment menus)
        if (menuType !== 'alignment') {
            lines.push(roleMenuExtraLine('alignment', g));
        }
        lines.push('~ - Set role/race/&c filtering');
        lines.push('q - Quit');
    }
    lines.push('(end)');
    // C ref: plsel_startmenu → create_nhwindow(NHW_MENU)
    const winId = chargenMenuCreate();
    const cols = display?.cols || 80;
    const rows = display?.rows || 24;
    const { offx: cOffx, maxrow: cMaxrow } = computeCMenuLayout(
        cols, rows, lines,
    );
    // C ref: fullscreen when maxrow >= rows (H2344_BROKEN path)
    const fullWidth = lines.length >= rows;
    const offx = await renderChargenMenu(display, query, lines, {
        fullWidth,
    });
    if (display) display.setCursor(offx + 6, lines.length - 1);
    enterModal('chargen-menu');
    try {
        const ch = await nhgetch();
        return String.fromCharCode(ch);
    } finally {
        exitModal('chargen-menu');
        // C ref: destroy_nhwindow(win) → tty_dismiss → erase_menu_or_text → docorner
        await chargenMenuDismiss(winId, cOffx, cMaxrow);
    }
}
 
async function confirmSelectionMenu() {
    const display = game?.nhDisplay || null;
    const g = game;
    const allowRename = true;
    const title = `Is this ok? [yn${allowRename ? 'a' : ''}q]`;
    const lines = [
        title,
        '',
        selectionSummary(g),
        '',
        'y * Yes; start game',
        'n - No; choose role again',
    ];
    if (allowRename) lines.push('a - Not yet; choose another name');
    lines.push('q - Quit');
    lines.push('(end)');
    // C ref: plsel_startmenu → create_nhwindow(NHW_MENU)
    const winId = chargenMenuCreate();
    const cols = display?.cols || 80;
    const rows = display?.rows || 24;
    const { offx: cOffx, maxrow: cMaxrow } = computeCMenuLayout(
        cols, rows, lines,
    );
    // C ref: tty menu width tracks this prompt one column wider here than
    // our visible string lengths, which shifts the confirmation box left by 1.
    const offx = await renderChargenMenu(display, title, lines);
    if (display) display.setCursor(offx + 6, lines.length - 1);
    enterModal('chargen-menu');
    try {
        const ch = await nhgetch();
        return String.fromCharCode(ch).toLowerCase();
    } finally {
        exitModal('chargen-menu');
        // C ref: destroy_nhwindow(win) → tty_dismiss → erase_menu_or_text → docorner
        await chargenMenuDismiss(winId, cOffx, cMaxrow);
    }
}
 
// C ref: role.c:2852 setup_rolemenu — accelerators are lowercase first letter,
// with uppercase fallback on duplicates ('r' Rogue, 'R' Ranger).
function buildFilterItems() {
    const items = [];
    // Roles
    items.push({ header: 'Unacceptable roles' });
    let lastCh = '\0';
    for (let i = 0; i < roles.length; i++) {
        let ch = (roles[i].name.m[0] || '').toLowerCase();
        if (ch === lastCh) ch = ch.toUpperCase();
        lastCh = ch.toLowerCase();
        let label = roles[i].name.m;
        if (roles[i].name.f) label = `${label}/${roles[i].name.f}`;
        items.push({ key: ch, name: roles[i].name.m, type: 'role', index: i, label });
    }
    // Races (uppercase first letter)
    items.push({ header: 'Unacceptable races' });
    for (let i = 0; i < races.length; i++) {
        const noun = races[i].noun || '';
        if (!noun) continue;
        const ch = (noun[0] || '').toUpperCase();
        items.push({ key: ch, name: noun, type: 'race', index: i, label: noun });
    }
    // Genders (uppercase first letter)
    items.push({ header: 'Unacceptable genders' });
    for (let i = 0; i < ROLE_GENDERS; i++) {
        const adj = genders[i].adj || '';
        const ch = (adj[0] || '').toUpperCase();
        items.push({ key: ch, name: adj, type: 'gender', index: i, label: adj });
    }
    // Alignments (uppercase first letter)
    items.push({ header: 'Unacceptable alignments' });
    for (let i = 0; i < ROLE_ALIGNS; i++) {
        const adj = aligns[i].adj || '';
        const ch = (adj[0] || '').toUpperCase();
        items.push({ key: ch, name: adj, type: 'alignment', index: i, label: adj });
    }
    return items;
}
 
// C ref: role.c:2727 reset_role_filtering() — "Pick all that apply" menu.
// Returns true if any filters were selected (n > 0).
async function resetRoleFiltering() {
    const g = game;
    const items = buildFilterItems();
    const selected = new Set();
    // Pre-select items currently in rfilter state.
    const rf = ensureRfilter();
    items.forEach((it, idx) => {
        if (it.header) return;
        if (it.type === 'role' && rf.roles[it.index]) selected.add(idx);
        else if (it.type === 'race' && (rf.mask & (races[it.index].selfmask ?? 0))) selected.add(idx);
        else if (it.type === 'gender' && (rf.mask & genders[it.index].allow)) selected.add(idx);
        else if (it.type === 'alignment' && (rf.mask & aligns[it.index].allow)) selected.add(idx);
    });
 
    const display = g?.nhDisplay || null;
    let closed = false;
    let confirmed = 0;
    const startingSelected = new Set(selected);
 
    const render = async () => {
        const title = `Pick all that apply${gotRoleFilter() ? ' and/or unpick any that no longer apply' : ''}`;
        const lines = [];
        items.forEach((it, idx) => {
            if (it.header) {
                lines.push(it.header);
                return;
            }
            const mark = selected.has(idx) ? '+' : '-';
            lines.push(`${it.key} ${mark} ${articleize(it.label)}`);
        });
        lines.push('(end)');
        const winId = chargenMenuCreate();
        const cols = display?.cols || 80;
        const rows = display?.rows || 24;
        const { offx: cOffx, maxrow: cMaxrow } = computeCMenuLayout(cols, rows, lines);
        await renderChargenMenu(display, title, lines);
        enterModal('chargen-menu');
        let key;
        try {
            const ch = await nhgetch();
            key = String.fromCharCode(ch);
        } finally {
            exitModal('chargen-menu');
            await chargenMenuDismiss(winId, cOffx, cMaxrow);
        }
        return key;
    };
 
    while (!closed) {
        const key = await render();
        if (key === '\r' || key === '\n' || key === ' ') {
            closed = true;
            confirmed = selected.size;
            break;
        }
        if (key === '\x1b' || key === 'q') {
            // Cancel — leave filter unchanged
            return false;
        }
        // Toggle by accelerator
        const toggleIdx = items.findIndex(it => it.key === key);
        if (toggleIdx >= 0) {
            if (selected.has(toggleIdx)) selected.delete(toggleIdx);
            else selected.add(toggleIdx);
        }
    }
 
    // Apply: clear existing filters and re-apply from selected set.
    clearRoleFilterAll();
    for (const idx of selected) {
        const it = items[idx];
        if (!it || it.header) continue;
        setRoleFilter(it.name);
    }
    // C ref: role.c:2764 — reset all four facets when any filter applied.
    if (confirmed > 0) {
        g.flags.initrole = ROLE_NONE;
        g.flags.initrace = ROLE_NONE;
        g.flags.initgend = ROLE_NONE;
        g.flags.initalign = ROLE_NONE;
    }
    return confirmed > 0;
}
 
async function playerSelection(g) {
    let prompted = false;
    if (!g.plname) {
        prompted = true;
        // C ref: wintty.c:581 — cursor is at row 12 after copyright banner
        g.plname = await getlin('Who are you?', null, { row: 12 }) || '';
        // C ref: tty_askname uses BASE_WINDOW, not WIN_MESSAGE, so it
        // never touches toplin. Reset toplin to match C's state.
        const disp0 = game?.nhDisplay;
        if (disp0) disp0.toplin = TOPLINE_EMPTY;
    }
 
    if (g.flags.initrole !== ROLE_NONE
        && g.flags.initrace !== ROLE_NONE
        && g.flags.initgend !== ROLE_NONE
        && g.flags.initalign !== ROLE_NONE) {
        g.flags.female = (g.flags.initgend === 1);
        return;
    }
 
    rigidRoleChecks(g.flags);
    prompted = true;
    // C ref: plnamesiz (role.c) — choices "ynaq", no default
    let pick4u = await ynFunction(
        "Shall I pick character's race, role, gender and alignment for you?",
        "ynaq",
        0,
        null
    );
    pick4u = String.fromCharCode(pick4u).toLowerCase();
    if (pick4u === ' ' || pick4u === '\r' || pick4u === '\n') pick4u = 'y';
    if (pick4u === '\x1b' || pick4u === 'q') { g._chargenQuit = true; return; }
    // C ref: role.c:2267 — '@' or '*' treated as 'a' (auto-pick)
    if (pick4u === '@' || pick4u === '*') pick4u = 'a';
 
    if (pick4u === 'y' || pick4u === 'a') {
        if (g.flags.initrole === ROLE_NONE) g.flags.initrole = pickRole(g.flags.initrace, g.flags.initgend, g.flags.initalign);
        if (g.flags.initrace === ROLE_NONE) g.flags.initrace = pickRace(g.flags.initrole, g.flags.initgend, g.flags.initalign);
        if (g.flags.initgend === ROLE_NONE) g.flags.initgend = pickGend(g.flags.initrole, g.flags.initrace, g.flags.initalign);
        if (g.flags.initalign === ROLE_NONE) g.flags.initalign = pickAlign(g.flags.initrole, g.flags.initrace, g.flags.initgend);
        g.flags.female = (g.flags.initgend === 1);
        // C ref: role.c:2653-2718 — getconfirmation loop for 'y' (not 'a')
        if (pick4u !== 'a') {
            let confirmed = false;
            while (!confirmed) {
                const conf = await confirmSelectionMenu();
                if (conf === 'y' || conf === ' ' || conf === '\r' || conf === '\n') {
                    confirmed = true;
                } else if (conf === 'n') {
                    // C ref: role.c:2709-2711 — reset all choices, restart picks
                    g.flags.initrole = ROLE_NONE;
                    g.flags.initrace = ROLE_NONE;
                    g.flags.initgend = ROLE_NONE;
                    g.flags.initalign = ROLE_NONE;
                    pick4u = 'n';
                    break; // fall through to the manual pick loop below
                } else if (conf === 'a') {
                    // C ref: role.c:2694-2703 — rename, keep role/race/etc
                    g.plname = await getlin('Who are you?', null, { row: 12 }) || '';
                    const disp0 = game?.nhDisplay;
                    if (disp0) disp0.toplin = TOPLINE_EMPTY;
                    // loop back to show confirmation again
                } else {
                    // 'q' or ESC
                    g._chargenQuit = true;
                    return;
                }
            }
            if (!confirmed) {
                // 'n' was pressed — fall through to manual pick loop
                pick4u = 'n';
            }
        }
    }
    if (pick4u === 'n') {
        // C ref: role.c:2288-2694 — makepicks loop with nextpick + confirmation
        const RS_ROLE = 0, RS_RACE = 1, RS_GENDER = 2, RS_ALGNMNT = 3;
        let repick = true;
        while (repick) {
            repick = false;
            let nextpick = RS_ROLE;
            if (typeof process !== 'undefined' && process.env?.CHARGEN_TRACE) {
                // eslint-disable-next-line no-console
                console.error(`[CHARGEN] makepicks entered role=${g.flags.initrole} race=${g.flags.initrace} gend=${g.flags.initgend} align=${g.flags.initalign}`);
            }
            makepicks:
            do {
                if (typeof process !== 'undefined' && process.env?.CHARGEN_TRACE) {
                    // eslint-disable-next-line no-console
                    console.error(`[CHARGEN] do-while top nextpick=${nextpick} role=${g.flags.initrole} race=${g.flags.initrace} gend=${g.flags.initgend} align=${g.flags.initalign}`);
                }
                if (nextpick === RS_ROLE) {
                    nextpick = RS_RACE;
                    if (g.flags.initrole < 0) {
                        const r = await selectPrompt('Pick a role or profession',
                            roleMenuChoices(g.flags.initgend, g.flags.initrace, g.flags.initalign));
                        if (r === CHARGEN_QUIT) { g._chargenQuit = true; return; }
                        else if (r === CHARGEN_RANDOM) g.flags.initrole = pickRole(g.flags.initrace, g.flags.initgend, g.flags.initalign);
                        else if (r === CHARGEN_PICK_RACE) { g.flags.initrace = ROLE_NONE; nextpick = RS_RACE; continue makepicks; }
                        else if (r === CHARGEN_PICK_GENDER) { g.flags.initgend = ROLE_NONE; nextpick = RS_GENDER; continue makepicks; }
                        else if (r === CHARGEN_PICK_ALIGN) { g.flags.initalign = ROLE_NONE; nextpick = RS_ALGNMNT; continue makepicks; }
                        else if (r === CHARGEN_FILTER) {
                            // C ref: role.c:2357 — role block does not check reset_role_filtering return
                            g.flags.initrole = ROLE_NONE;
                            await resetRoleFiltering();
                            nextpick = RS_ROLE;
                            continue makepicks;
                        }
                        else g.flags.initrole = r;
                    }
                }
                if (nextpick === RS_RACE) {
                    nextpick = (g.flags.initrole < 0) ? RS_ROLE : RS_GENDER;
                    if (g.flags.initrace < 0 || !okRace(g.flags.initrole, g.flags.initrace, g.flags.initgend, g.flags.initalign)) {
                        const r = await selectPrompt('Pick a race or species',
                            facetChoices(races, 'noun', i => okRace(g.flags.initrole, i, g.flags.initgend, g.flags.initalign)));
                        if (r === CHARGEN_QUIT) { g._chargenQuit = true; return; }
                        else if (r === CHARGEN_RANDOM) g.flags.initrace = pickRace(g.flags.initrole, g.flags.initgend, g.flags.initalign);
                        else if (r === CHARGEN_PICK_ROLE) { g.flags.initrole = ROLE_NONE; nextpick = RS_ROLE; continue makepicks; }
                        else if (r === CHARGEN_PICK_GENDER) { g.flags.initgend = ROLE_NONE; nextpick = RS_GENDER; continue makepicks; }
                        else if (r === CHARGEN_PICK_ALIGN) { g.flags.initalign = ROLE_NONE; nextpick = RS_ALGNMNT; continue makepicks; }
                        else if (r === CHARGEN_FILTER) {
                            // C ref: role.c:2441 — if filter selected, nextpick=RS_ROLE else RS_RACE
                            g.flags.initrace = ROLE_NONE;
                            nextpick = (await resetRoleFiltering()) ? RS_ROLE : RS_RACE;
                            continue makepicks;
                        }
                        else g.flags.initrace = r;
                    }
                }
                if (nextpick === RS_GENDER) {
                    nextpick = (g.flags.initrole < 0) ? RS_ROLE : RS_ALGNMNT;
                    if (g.flags.initgend < 0) {
                        const r = await selectPrompt('Pick a gender or sex',
                            facetChoices(genders, 'adj', i => okGend(g.flags.initrole, g.flags.initrace, i)));
                        if (r === CHARGEN_QUIT) { g._chargenQuit = true; return; }
                        else if (r === CHARGEN_RANDOM) g.flags.initgend = pickGend(g.flags.initrole, g.flags.initrace, g.flags.initalign);
                        else if (r === CHARGEN_PICK_ROLE) { g.flags.initrole = ROLE_NONE; nextpick = RS_ROLE; continue makepicks; }
                        else if (r === CHARGEN_PICK_RACE) { g.flags.initrace = ROLE_NONE; nextpick = RS_RACE; continue makepicks; }
                        else if (r === CHARGEN_PICK_ALIGN) { g.flags.initalign = ROLE_NONE; nextpick = RS_ALGNMNT; continue makepicks; }
                        else if (r === CHARGEN_FILTER) {
                            // C ref: role.c:2529 — if filter selected, nextpick=RS_ROLE else RS_GENDER
                            g.flags.initgend = ROLE_NONE;
                            nextpick = (await resetRoleFiltering()) ? RS_ROLE : RS_GENDER;
                            continue makepicks;
                        }
                        else g.flags.initgend = r;
                    }
                }
                if (nextpick === RS_ALGNMNT) {
                    // C ref: role.c:2549 — default next is RS_GENDER when role+race set
                    nextpick = (g.flags.initrole < 0) ? RS_ROLE
                        : (g.flags.initrace < 0) ? RS_RACE
                        : RS_GENDER;
                    if (g.flags.initalign < 0) {
                        const r = await selectPrompt('Pick an alignment or creed',
                            facetChoices(aligns.slice(0, ROLE_ALIGNS), 'adj', i => okAlign(g.flags.initrole, g.flags.initrace, i)));
                        if (r === CHARGEN_QUIT) { g._chargenQuit = true; return; }
                        else if (r === CHARGEN_RANDOM) g.flags.initalign = pickAlign(g.flags.initrole, g.flags.initrace, g.flags.initgend);
                        else if (r === CHARGEN_PICK_ROLE) { g.flags.initrole = ROLE_NONE; nextpick = RS_ROLE; continue makepicks; }
                        else if (r === CHARGEN_PICK_RACE) { g.flags.initrace = ROLE_NONE; nextpick = RS_RACE; continue makepicks; }
                        else if (r === CHARGEN_PICK_GENDER) { g.flags.initgend = ROLE_NONE; nextpick = RS_GENDER; continue makepicks; }
                        else if (r === CHARGEN_FILTER) {
                            // C ref: role.c:2615 — if filter selected, nextpick=RS_ROLE else RS_ALGNMNT
                            g.flags.initalign = ROLE_NONE;
                            nextpick = (await resetRoleFiltering()) ? RS_ROLE : RS_ALGNMNT;
                            continue makepicks;
                        }
                        else g.flags.initalign = r;
                    }
                }
            } while (g.flags.initrole < 0 || g.flags.initrace < 0
                     || g.flags.initgend < 0 || g.flags.initalign < 0);
 
            g.flags.female = (g.flags.initgend === 1);
 
            // C ref: role.c:2653 — confirmation loop
            if (pick4u !== 'a') {
                let confirmed = false;
                while (!confirmed) {
                    const confirm = await confirmSelectionMenu();
                    if (confirm === 'y' || confirm === ' ') {
                        confirmed = true; // accept — exit both loops
                    } else if (confirm === 'q') {
                        g._chargenQuit = true; return; // quit
                    } else if (confirm === 'a') {
                        // rename — re-ask name, then re-show confirmation
                        // C ref: after confirmation menu (9 items+end = maxrow 9),
                        // docorner sets BASE_WINDOW cury to maxrow (=9).
                        // tty_askname adds empty line (cury+1=10) then prompt.
                        // Confirmation has 8 items + "(end)" = 9 lines (maxrow).
                        const renameRow = 9 + 1; // maxrow + 1 (for empty line in askname)
                        g.plname = await getlin('Who are you?', null, { row: renameRow }) || '';
                        // C ref: tty_askname uses BASE_WINDOW, not WIN_MESSAGE,
                        // so toplin stays EMPTY. Reset to match C.
                        const dispRename = game?.nhDisplay;
                        if (dispRename) dispRename.toplin = TOPLINE_EMPTY;
                        // Loop to re-show confirmation with new name
                    } else if (confirm === 'n') {
                        // choose again — reset and re-enter makepicks
                        g.flags.initrole = ROLE_NONE;
                        g.flags.initrace = ROLE_NONE;
                        g.flags.initgend = ROLE_NONE;
                        g.flags.initalign = ROLE_NONE;
                        repick = true;
                        break; // exit confirmation, re-enter outer while
                    }
                    // else: invalid key (like '*') — C rings bell, re-shows menu
                }
            }
        }
    }
    if (prompted && g.flags.initalign !== ROLE_NONE) {
        g.flags.initalign = normalizeStartupAlignIndex(g.flags.initalign);
    }
    g.promptedStartup = prompted;
}
 
function extractSessionKeys(steps) {
    const keys = [];
    for (const step of steps) {
        if (step.key == null || step.key === '') continue;
        if (typeof step.key !== 'string') continue;
        for (const ch of step.key) {
            keys.push(ch.charCodeAt(0));
        }
    }
    return keys;
}