Class: DecisionAgent::Web::Server

Inherits:
Object
  • Object
show all
Includes:
RackHelpers, RackRequestHelpers
Defined in:
lib/decision_agent/web/server.rb

Overview

Framework-agnostic Rack application - works with any Rack-compatible server

Constant Summary collapse

PUBLIC_FOLDER =
File.expand_path("public", __dir__)
VIEWS_FOLDER =
File.expand_path("views", __dir__)

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RackRequestHelpers

read_body

Class Attribute Details

.access_audit_loggerObject



103
104
105
106
107
108
109
# File 'lib/decision_agent/web/server.rb', line 103

def self.access_audit_logger
  return @access_audit_logger if @access_audit_logger

  @auth_mutex.synchronize do
    @access_audit_logger ||= Auth::AccessAuditLogger.new
  end
end

.authenticatorObject



87
88
89
90
91
92
93
# File 'lib/decision_agent/web/server.rb', line 87

def self.authenticator
  return @authenticator if @authenticator

  @auth_mutex.synchronize do
    @authenticator ||= Auth::Authenticator.new
  end
end

.batch_test_storageObject (readonly)

Returns the value of attribute batch_test_storage.



81
82
83
# File 'lib/decision_agent/web/server.rb', line 81

def batch_test_storage
  @batch_test_storage
end

.batch_test_storage_mutexObject (readonly)

Returns the value of attribute batch_test_storage_mutex.



81
82
83
# File 'lib/decision_agent/web/server.rb', line 81

def batch_test_storage_mutex
  @batch_test_storage_mutex
end

.bindObject

Returns the value of attribute bind.



80
81
82
# File 'lib/decision_agent/web/server.rb', line 80

def bind
  @bind
end

.permission_checkerObject



95
96
97
98
99
100
101
# File 'lib/decision_agent/web/server.rb', line 95

def self.permission_checker
  return @permission_checker if @permission_checker

  @auth_mutex.synchronize do
    @permission_checker ||= Auth::PermissionChecker.new(adapter: DecisionAgent.rbac_config.adapter)
  end
end

.portObject

Returns the value of attribute port.



80
81
82
# File 'lib/decision_agent/web/server.rb', line 80

def port
  @port
end

.public_folderObject

Returns the value of attribute public_folder.



80
81
82
# File 'lib/decision_agent/web/server.rb', line 80

def public_folder
  @public_folder
end

.simulation_storageObject (readonly)

Returns the value of attribute simulation_storage.



81
82
83
# File 'lib/decision_agent/web/server.rb', line 81

def simulation_storage
  @simulation_storage
end

.simulation_storage_mutexObject (readonly)

Returns the value of attribute simulation_storage_mutex.



81
82
83
# File 'lib/decision_agent/web/server.rb', line 81

def simulation_storage_mutex
  @simulation_storage_mutex
end

.views_folderObject

Returns the value of attribute views_folder.



80
81
82
# File 'lib/decision_agent/web/server.rb', line 80

def views_folder
  @views_folder
end

Class Method Details

.call(env) ⇒ Object

Rack call method - entry point for Rack requests



143
144
145
# File 'lib/decision_agent/web/server.rb', line 143

def self.call(env)
  new.call(env)
end

.define_routes(router) ⇒ Object

Define all routes (will be populated below)



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
# File 'lib/decision_agent/web/server.rb', line 348

def self.define_routes(router)
  # OPTIONS handler for CORS preflight
  router.options "*" do |ctx|
    ctx.status(200)
    ctx.body("")
  end

  # Main page - serve the rule builder UI
  router.get "/" do |ctx|
    html_file = File.join(Server.public_folder, "index.html")
    Server.serve_html_with_base_tag(ctx, html_file, "Index page not found")
  rescue StandardError => e
    ctx.status(500)
    ctx.content_type "text/html"
    ctx.body("Error loading page: #{e.message}")
  end

  # Serve static assets explicitly
  router.get "/styles.css" do |ctx|
    ctx.content_type "text/css"
    css_file = File.join(Server.public_folder, "styles.css")
    ctx.send_file(css_file) if File.exist?(css_file)
  end

  router.get "/app.js" do |ctx|
    ctx.content_type "application/javascript"
    js_file = File.join(Server.public_folder, "app.js")
    ctx.send_file(js_file) if File.exist?(js_file)
  end

  # API: Validate rules
  router.post "/api/validate" do |ctx|
    ctx.content_type "application/json"

    begin
      # Parse request body
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      # Validate using DecisionAgent's SchemaValidator
      DecisionAgent::Dsl::SchemaValidator.validate!(data)

      # If validation passes
      ctx.json({
                 valid: true,
                 message: "Rules are valid!"
               })
    rescue JSON::ParserError => e
      ctx.status(400)
      ctx.json({
                 valid: false,
                 errors: ["Invalid JSON: #{e.message}"]
               })
    rescue DecisionAgent::InvalidRuleDslError => e
      # Validation failed
      ctx.status(422)
      ctx.json({
                 valid: false,
                 errors: Server.parse_validation_errors(e.message)
               })
    rescue StandardError => e
      # Unexpected error
      ctx.status(500)
      ctx.json({
                 valid: false,
                 errors: ["Server error: #{e.message}"]
               })
    end
  end

  # API: Test rule evaluation (optional feature)
  router.post "/api/evaluate" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      rules_json = data["rules"]
      context = data["context"] || {}

      # Create evaluator
      evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: rules_json)

      # Evaluate
      result = evaluator.evaluate(DecisionAgent::Context.new(context))

      if result
        # Get explainability data from metadata if available
        explainability = result.[:explainability] if result..is_a?(Hash)

        # Structure response as explainability by default
        # This makes explainability the primary format for decision results
        response = if explainability
                     {
                       success: true,
                       decision: explainability[:decision] || result.decision,
                       because: explainability[:because] || [],
                       failed_conditions: explainability[:failed_conditions] || [],
                       # Include additional metadata for completeness
                       confidence: result.weight,
                       reason: result.reason,
                       evaluator_name: result.evaluator_name,
                       # Full explainability data (includes rule_traces in verbose mode)
                       explainability: explainability
                     }
                   else
                     # Fallback if explainability is not available
                     {
                       success: true,
                       decision: result.decision,
                       because: [],
                       failed_conditions: [],
                       confidence: result.weight,
                       reason: result.reason,
                       evaluator_name: result.evaluator_name,
                       explainability: {
                         decision: result.decision,
                         because: [],
                         failed_conditions: []
                       }
                     }
                   end

        ctx.json(response)
      else
        ctx.json({
                   success: true,
                   decision: nil,
                   because: [],
                   failed_conditions: [],
                   message: "No rules matched the given context",
                   explainability: {
                     decision: nil,
                     because: [],
                     failed_conditions: []
                   }
                 })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({
                 success: false,
                 error: e.message
               })
    end
  end

  # API: Get example rules
  router.get "/api/examples" do |ctx|
    ctx.content_type "application/json"

    examples = [
      {
        name: "Approval Workflow",
        description: "Basic approval rules for requests",
        rules: {
          version: "1.0",
          ruleset: "approval_workflow",
          rules: [
            {
              id: "admin_auto_approve",
              if: { field: "user.role", op: "eq", value: "admin" },
              then: { decision: "approve", weight: 0.95, reason: "Admin user" }
            },
            {
              id: "low_amount_approve",
              if: { field: "amount", op: "lt", value: 1000 },
              then: { decision: "approve", weight: 0.8, reason: "Low amount" }
            },
            {
              id: "high_amount_review",
              if: { field: "amount", op: "gte", value: 10_000 },
              then: { decision: "manual_review", weight: 0.9, reason: "High amount requires review" }
            }
          ]
        }
      },
      {
        name: "User Access Control",
        description: "Role-based access control rules",
        rules: {
          version: "1.0",
          ruleset: "access_control",
          rules: [
            {
              id: "admin_full_access",
              if: {
                all: [
                  { field: "user.role", op: "eq", value: "admin" },
                  { field: "user.active", op: "eq", value: true }
                ]
              },
              then: { decision: "allow", weight: 1.0, reason: "Active admin user" }
            },
            {
              id: "guest_read_only",
              if: {
                all: [
                  { field: "user.role", op: "eq", value: "guest" },
                  { field: "action", op: "eq", value: "read" }
                ]
              },
              then: { decision: "allow", weight: 0.7, reason: "Guest read access" }
            },
            {
              id: "inactive_user_deny",
              if: { field: "user.active", op: "eq", value: false },
              then: { decision: "deny", weight: 1.0, reason: "Inactive user account" }
            }
          ]
        }
      },
      {
        name: "Content Moderation",
        description: "Automatic content moderation rules",
        rules: {
          version: "1.0",
          ruleset: "content_moderation",
          rules: [
            {
              id: "verified_user_approve",
              if: {
                all: [
                  { field: "author.verified", op: "eq", value: true },
                  { field: "content_length", op: "lt", value: 5000 }
                ]
              },
              then: { decision: "approve", weight: 0.85, reason: "Verified author with reasonable length" }
            },
            {
              id: "missing_content_reject",
              if: {
                any: [
                  { field: "content", op: "blank" },
                  { field: "content_length", op: "eq", value: 0 }
                ]
              },
              then: { decision: "reject", weight: 1.0, reason: "Empty content" }
            },
            {
              id: "flagged_content_review",
              if: { field: "flags", op: "present" },
              then: { decision: "manual_review", weight: 0.9, reason: "Content has been flagged" }
            }
          ]
        }
      }
    ]

    ctx.json(examples)
  end

  # Health check
  router.get "/health" do |ctx|
    ctx.content_type "application/json"
    ctx.json({ status: "ok", version: DecisionAgent::VERSION })
  end

  # Authentication API endpoints

  # POST /api/auth/login - User login
  router.post "/api/auth/login" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      email = data["email"]
      password = data["password"]

      unless email && password
        ctx.status(400)
        ctx.json({ error: "Email and password are required" })
        next
      end

      session = Server.authenticator.(email, password)

      unless session
        Server.access_audit_logger.log_authentication(
          "login",
          user_id: nil,
          email: email,
          success: false,
          reason: "Invalid credentials"
        )
        ctx.status(401)
        ctx.json({ error: "Invalid email or password" })
        next
      end

      user = Server.authenticator.find_user(session.user_id)

      Server.access_audit_logger.log_authentication(
        "login",
        user_id: user.id,
        email: user.email,
        success: true
      )

      ctx.json({
                 token: session.token,
                 user: user.to_h,
                 expires_at: session.expires_at.iso8601
               })
    rescue JSON::ParserError
      ctx.status(400)
      ctx.json({ error: "Invalid JSON" })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # POST /api/auth/logout - User logout
  router.post "/api/auth/logout" do |ctx|
    ctx.content_type "application/json"

    begin
      token = Server.extract_token(ctx)
      if token
        Server.authenticator.logout(token)
        if ctx.current_user
          checker = Server.permission_checker
          Server.access_audit_logger.log_authentication(
            "logout",
            user_id: checker.user_id(ctx.current_user),
            email: checker.user_email(ctx.current_user),
            success: true
          )
        end
      end

      ctx.json({ success: true, message: "Logged out successfully" })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # GET /api/auth/me - Current user info
  router.get "/api/auth/me" do |ctx|
    ctx.content_type "application/json"

    if ctx.current_user
      ctx.json(ctx.current_user.to_h)
    else
      ctx.status(401)
      ctx.json({ error: "Not authenticated" })
    end
  end

  # GET /api/auth/roles - List all roles
  router.get "/api/auth/roles" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :read)
    next if ctx.halted?

    roles = Auth::Role.all.map do |role|
      {
        id: role.to_s,
        name: Auth::Role.name_for(role),
        permissions: Auth::Role.permissions_for(role).map(&:to_s)
      }
    end

    ctx.json(roles)
  end

  # POST /api/auth/users - Create user (admin only)
  router.post "/api/auth/users" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :manage_users)
    next if ctx.halted?

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      email = data["email"]
      password = data["password"]
      roles = data["roles"] || []

      unless email && password
        ctx.status(400)
        ctx.json({ error: "Email and password are required" })
        next
      end

      # Validate roles
      invalid_role = nil
      roles.each do |role|
        unless Auth::Role.exists?(role)
          invalid_role = role
          break
        end
      end

      if invalid_role
        ctx.status(400)
        ctx.json({ error: "Invalid role: #{invalid_role}" })
        next
      end

      user = Server.authenticator.create_user(
        email: email,
        password: password,
        roles: roles
      )

      checker = Server.permission_checker
      Server.access_audit_logger.log_access(
        user_id: checker.user_id(ctx.current_user),
        action: "create_user",
        resource_type: "user",
        resource_id: user.id,
        success: true
      )

      ctx.status(201)
      ctx.json(user.to_h)
    rescue JSON::ParserError
      ctx.status(400)
      ctx.json({ error: "Invalid JSON" })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # GET /api/auth/users - List users (admin only)
  router.get "/api/auth/users" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :manage_users)
    next if ctx.halted?

    users = Server.authenticator.user_store.all.map(&:to_h)
    ctx.json(users)
  end

  # POST /api/auth/users/:id/roles - Assign role to user (admin only)
  router.post "/api/auth/users/:id/roles" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :manage_users)
    next if ctx.halted?

    begin
      user_id = ctx.params[:id] || ctx.params["id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      role = data["role"]

      unless role
        ctx.status(400)
        ctx.json({ error: "Role is required" })
        next
      end

      unless Auth::Role.exists?(role)
        ctx.status(400)
        ctx.json({ error: "Invalid role: #{role}" })
        next
      end

      user = Server.authenticator.find_user(user_id)
      unless user
        ctx.status(404)
        ctx.json({ error: "User not found" })
        next
      end

      user.assign_role(role)

      checker = Server.permission_checker
      Server.access_audit_logger.log_access(
        user_id: checker.user_id(ctx.current_user),
        action: "assign_role",
        resource_type: "user",
        resource_id: user.id,
        success: true
      )

      ctx.json(user.to_h)
    rescue JSON::ParserError
      ctx.status(400)
      ctx.json({ error: "Invalid JSON" })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # DELETE /api/auth/users/:id/roles/:role - Remove role from user (admin only)
  router.delete "/api/auth/users/:id/roles/:role" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :manage_users)
    next if ctx.halted?

    begin
      user_id = ctx.params[:id] || ctx.params["id"]
      role = ctx.params[:role] || ctx.params["role"]

      user = Server.authenticator.find_user(user_id)
      unless user
        ctx.status(404)
        ctx.json({ error: "User not found" })
        next
      end

      user.remove_role(role)

      checker = Server.permission_checker
      Server.access_audit_logger.log_access(
        user_id: checker.user_id(ctx.current_user),
        action: "remove_role",
        resource_type: "user",
        resource_id: user.id,
        success: true
      )

      ctx.json(user.to_h)
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # GET /api/auth/audit - Query access audit logs
  router.get "/api/auth/audit" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :audit)
    next if ctx.halted?

    begin
      filters = {}

      filters[:user_id] = ctx.params[:user_id] || ctx.params["user_id"] if ctx.params[:user_id] || ctx.params["user_id"]
      filters[:event_type] = ctx.params[:event_type] || ctx.params["event_type"] if ctx.params[:event_type] || ctx.params["event_type"]
      filters[:start_time] = ctx.params[:start_time] || ctx.params["start_time"] if ctx.params[:start_time] || ctx.params["start_time"]
      filters[:end_time] = ctx.params[:end_time] || ctx.params["end_time"] if ctx.params[:end_time] || ctx.params["end_time"]
      filters[:limit] = (ctx.params[:limit] || ctx.params["limit"])&.to_i if ctx.params[:limit] || ctx.params["limit"]

      logs = Server.access_audit_logger.query(filters)
      ctx.json(logs)
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # POST /api/auth/password/reset-request - Request password reset
  router.post "/api/auth/password/reset-request" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      email = data["email"]

      unless email
        ctx.status(400)
        ctx.json({ error: "Email is required" })
        next
      end

      token = Server.authenticator.request_password_reset(email)

      # For security, we always return success even if user doesn't exist
      # In production, you would send the token via email
      if token
        Server.access_audit_logger.log_authentication(
          "password_reset_request",
          user_id: token.user_id,
          email: email,
          success: true
        )

        ctx.json({
                   success: true,
                   message: "If the email exists, a password reset token has been generated",
                   # In production, remove this token from response and send via email
                   token: token.token,
                   expires_at: token.expires_at.iso8601
                 })
      else
        # Log failed attempt (but don't reveal if user exists)
        Server.access_audit_logger.log_authentication(
          "password_reset_request",
          user_id: nil,
          email: email,
          success: false,
          reason: "User not found or inactive"
        )

        ctx.json({
                   success: true,
                   message: "If the email exists, a password reset token has been generated"
                 })
      end
    rescue JSON::ParserError
      ctx.status(400)
      ctx.json({ error: "Invalid JSON" })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # POST /api/auth/password/reset - Reset password with token
  router.post "/api/auth/password/reset" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      token = data["token"]
      new_password = data["password"]

      unless token && new_password
        ctx.status(400)
        ctx.json({ error: "Token and password are required" })
        next
      end

      unless new_password.length >= 8
        ctx.status(400)
        ctx.json({ error: "Password must be at least 8 characters long" })
        next
      end

      user = Server.authenticator.reset_password(token, new_password)

      unless user
        ctx.status(400)
        ctx.json({ error: "Invalid or expired reset token" })
        next
      end

      Server.access_audit_logger.log_authentication(
        "password_reset",
        user_id: user.id,
        email: user.email,
        success: true
      )

      ctx.json({
                 success: true,
                 message: "Password has been reset successfully"
               })
    rescue JSON::ParserError
      ctx.status(400)
      ctx.json({ error: "Invalid JSON" })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # Versioning API endpoints

  # Create a new version
  router.post "/api/versions" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :write)
    next if ctx.halted?

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      rule_id = data["rule_id"]
      rule_content = data["content"]
      created_by = data["created_by"] || (ctx.current_user&.email || "system")
      changelog = data["changelog"]

      version = Server.version_manager.save_version(
        rule_id: rule_id,
        rule_content: rule_content,
        created_by: created_by,
        changelog: changelog
      )

      ctx.status(201)
      ctx.json(version)
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # List all versions for a rule
  router.get "/api/rules/:rule_id/versions" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :read)
    next if ctx.halted?

    begin
      rule_id = ctx.params[:rule_id] || ctx.params["rule_id"]
      limit = (ctx.params[:limit] || ctx.params["limit"])&.to_i

      versions = Server.version_manager.get_versions(rule_id: rule_id, limit: limit)

      ctx.json(versions)
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # Get version history with metadata
  router.get "/api/rules/:rule_id/history" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :read)
    next if ctx.halted?

    begin
      rule_id = ctx.params[:rule_id] || ctx.params["rule_id"]
      history = Server.version_manager.get_history(rule_id: rule_id)

      ctx.json(history)
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # Get a specific version
  router.get "/api/versions/:version_id" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :read)
    next if ctx.halted?

    begin
      version_id = ctx.params[:version_id] || ctx.params["version_id"]
      version = Server.version_manager.get_version(version_id: version_id)

      if version
        ctx.json(version)
      else
        ctx.status(404)
        ctx.json({ error: "Version not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # Activate a version (rollback)
  router.post "/api/versions/:version_id/activate" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :deploy)
    next if ctx.halted?

    begin
      version_id = ctx.params[:version_id] || ctx.params["version_id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = request_body.empty? ? {} : JSON.parse(request_body)
      performed_by = data["performed_by"] || (ctx.current_user&.email || "system")

      version = Server.version_manager.rollback(
        version_id: version_id,
        performed_by: performed_by
      )

      ctx.json(version)
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # Compare two versions
  router.get "/api/versions/:version_id_1/compare/:version_id_2" do |ctx|
    ctx.content_type "application/json"
    Server.require_permission!(ctx, :read)
    next if ctx.halted?

    begin
      version_id_1 = ctx.params[:version_id_1] || ctx.params["version_id_1"]
      version_id_2 = ctx.params[:version_id_2] || ctx.params["version_id_2"]

      comparison = Server.version_manager.compare(
        version_id_1: version_id_1,
        version_id_2: version_id_2
      )

      if comparison
        ctx.json(comparison)
      else
        ctx.status(404)
        ctx.json({ error: "One or both versions not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # Delete a version
  router.delete "/api/versions/:version_id" do |ctx|
    ctx.content_type "application/json"

    begin
      Server.require_permission!(ctx, :delete)
      next if ctx.halted?

      version_id = ctx.params[:version_id] || ctx.params["version_id"]

      # Ensure version_id is present
      unless version_id
        ctx.status(400)
        ctx.json({ error: "Version ID is required" })
        next
      end

      result = Server.version_manager.delete_version(version_id: version_id)

      if result == false
        ctx.status(404)
        ctx.json({ error: "Version not found" })
      else
        ctx.status(200)
        ctx.json({ success: true, message: "Version deleted successfully" })
      end
    rescue DecisionAgent::NotFoundError => e
      ctx.status(404)
      ctx.json({ error: e.message })
    rescue DecisionAgent::ValidationError => e
      ctx.status(422)
      ctx.json({ error: e.message })
    rescue StandardError => e
      # Log the error for debugging but return a safe response
      warn "[DecisionAgent] Version API error: #{e.message}"
      ctx.status(500)
      ctx.json({ error: "Internal server error" })
    end
  end

  # Batch Testing API Endpoints

  # POST /api/testing/batch/import - Upload CSV/Excel file
  router.post "/api/testing/batch/import" do |ctx|
    ctx.content_type "application/json"

    begin
      # Handle file upload from multipart form data
      file_param = ctx.params[:file] || ctx.params["file"]

      unless file_param && (file_param[:tempfile] || file_param["tempfile"])
        ctx.status(400)
        ctx.json({ error: "No file uploaded" })
        next
      end

      uploaded_file = file_param[:tempfile] || file_param["tempfile"]
      filename = file_param[:filename] || file_param["filename"] || "uploaded_file"
      file_extension = File.extname(filename).downcase

      # Validate file type before processing
      allowed_extensions = %w[.csv .xlsx .xls]
      unless allowed_extensions.include?(file_extension)
        ctx.status(422)
        ctx.json({ error: "Unsupported file type '#{file_extension}'. Allowed types: .csv, .xlsx, .xls" })
        next
      end

      # Create temporary file
      temp_file = Tempfile.new(["batch_test", file_extension])
      temp_file.binmode
      temp_file.write(uploaded_file.read)
      temp_file.rewind

      # Import scenarios based on file type
      importer = DecisionAgent::Testing::BatchTestImporter.new

      scenarios = if [".xlsx", ".xls"].include?(file_extension)
                    importer.import_excel(temp_file.path)
                  else
                    importer.import_csv(temp_file.path)
                  end

      temp_file.close
      temp_file.unlink

      # Check for import errors - return error status if there are errors and no scenarios
      if importer.errors.any? && scenarios.empty?
        ctx.status(422)
        ctx.json({ error: "Import failed: #{importer.errors.join('; ')}" })
        next
      end

      # If there are errors but some scenarios were created, still return error status
      if importer.errors.any?
        ctx.status(422)
        ctx.json({
                   error: "Import completed with errors: #{importer.errors.join('; ')}",
                   test_id: nil,
                   scenarios_count: scenarios.size,
                   errors: importer.errors,
                   warnings: importer.warnings
                 })
        next
      end

      # Store scenarios with a unique ID
      test_id = SecureRandom.uuid
      Server.batch_test_storage_mutex.synchronize do
        Server.batch_test_storage[test_id] = {
          id: test_id,
          scenarios: scenarios,
          status: "imported",
          created_at: Time.now.utc.iso8601,
          results: nil,
          coverage: nil
        }
      end

      ctx.status(201)
      ctx.json({
                 test_id: test_id,
                 scenarios_count: scenarios.size,
                 errors: importer.errors,
                 warnings: importer.warnings
               })
    rescue DecisionAgent::ImportError => e
      ctx.status(422)
      ctx.json({ error: e.message, errors: importer&.errors || [] })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: "Failed to import file: #{e.message}" })
    end
  end

  # POST /api/testing/batch/run - Execute batch test
  router.post "/api/testing/batch/run" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = request_body.empty? ? {} : JSON.parse(request_body)

      test_id = data["test_id"] || (ctx.params[:test_id] || ctx.params["test_id"])
      rules_json = data["rules"]
      options = data["options"] || {}

      unless test_id
        ctx.status(400)
        ctx.json({ error: "test_id is required" })
        next
      end

      unless rules_json
        ctx.status(400)
        ctx.json({ error: "rules JSON is required" })
        next
      end

      # Get stored scenarios
      test_data = nil
      Server.batch_test_storage_mutex.synchronize do
        test_data = Server.batch_test_storage[test_id]
      end

      unless test_data
        ctx.status(404)
        ctx.json({ error: "Test not found" })
        next
      end

      # Create agent from rules
      evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: rules_json)
      agent = DecisionAgent::Agent.new(evaluators: [evaluator])

      # Update status
      Server.batch_test_storage_mutex.synchronize do
        Server.batch_test_storage[test_id][:status] = "running"
        Server.batch_test_storage[test_id][:started_at] = Time.now.utc.iso8601
      end

      # Run batch test
      runner = DecisionAgent::Testing::BatchTestRunner.new(agent)
      results = runner.run(
        test_data[:scenarios],
        parallel: options.fetch("parallel", true),
        thread_count: options.fetch("thread_count", 4),
        checkpoint_file: options["checkpoint_file"]
      )

      # Calculate comparison if expected results exist
      comparison = nil
      if test_data[:scenarios].any?(&:expected_result?)
        comparator = DecisionAgent::Testing::TestResultComparator.new
        comparison = comparator.compare(results, test_data[:scenarios])
      end

      # Calculate coverage
      coverage_analyzer = DecisionAgent::Testing::TestCoverageAnalyzer.new
      coverage = coverage_analyzer.analyze(results, agent)

      # Store results
      Server.batch_test_storage_mutex.synchronize do
        Server.batch_test_storage[test_id][:status] = "completed"
        Server.batch_test_storage[test_id][:results] = results.map(&:to_h)
        Server.batch_test_storage[test_id][:comparison] = comparison
        Server.batch_test_storage[test_id][:coverage] = coverage.to_h
        Server.batch_test_storage[test_id][:statistics] = runner.statistics
        Server.batch_test_storage[test_id][:completed_at] = Time.now.utc.iso8601
      end

      ctx.json({
                 test_id: test_id,
                 status: "completed",
                 results_count: results.size,
                 statistics: runner.statistics,
                 comparison: comparison,
                 coverage: coverage.to_h
               })
    rescue StandardError => e
      # Update status to failed
      test_id_for_error = test_id || (data && data["test_id"])
      if test_id_for_error
        Server.batch_test_storage_mutex.synchronize do
          if Server.batch_test_storage[test_id_for_error]
            Server.batch_test_storage[test_id_for_error][:status] = "failed"
            Server.batch_test_storage[test_id_for_error][:error] = e.message
          end
        end
      end

      ctx.status(500)
      ctx.json({ error: "Batch test execution failed: #{e.message}" })
    end
  end

  # GET /api/testing/batch/:id/results - Get batch test results
  router.get "/api/testing/batch/:id/results" do |ctx|
    ctx.content_type "application/json"

    begin
      test_id = ctx.params[:id] || ctx.params["id"]

      test_data = nil
      Server.batch_test_storage_mutex.synchronize do
        test_data = Server.batch_test_storage[test_id]
      end

      unless test_data
        ctx.status(404)
        ctx.json({ error: "Test not found" })
        next
      end

      ctx.json({
                 test_id: test_data[:id],
                 status: test_data[:status],
                 created_at: test_data[:created_at],
                 started_at: test_data[:started_at],
                 completed_at: test_data[:completed_at],
                 scenarios_count: test_data[:scenarios]&.size || 0,
                 results: test_data[:results],
                 comparison: test_data[:comparison],
                 statistics: test_data[:statistics],
                 error: test_data[:error]
               })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # GET /api/testing/batch/:id/coverage - Get coverage report
  router.get "/api/testing/batch/:id/coverage" do |ctx|
    ctx.content_type "application/json"

    begin
      test_id = ctx.params[:id] || ctx.params["id"]

      test_data = nil
      Server.batch_test_storage_mutex.synchronize do
        test_data = Server.batch_test_storage[test_id]
      end

      unless test_data
        ctx.status(404)
        ctx.json({ error: "Test not found" })
        next
      end

      unless test_data[:coverage]
        ctx.status(404)
        ctx.json({ error: "Coverage report not available. Run the batch test first." })
        next
      end

      ctx.json({
                 test_id: test_data[:id],
                 coverage: test_data[:coverage]
               })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # GET /testing/batch - Batch testing UI page
  router.get "/testing/batch" do |ctx|
    batch_file = File.join(Server.public_folder, "batch_testing.html")
    Server.serve_html_with_base_tag(ctx, batch_file, "Batch testing page not found")
  rescue StandardError => e
    ctx.status(404)
    ctx.body("Batch testing page not found: #{e.message}")
  end

  # Simulation API Endpoints

  # POST /api/simulation/replay - Historical replay/backtesting
  router.post "/api/simulation/replay" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = request_body.empty? ? {} : JSON.parse(request_body)

      historical_data = data["historical_data"]
      rule_version = data["rule_version"]
      compare_with = data["compare_with"]
      options = data["options"] || {}

      unless historical_data
        ctx.status(400)
        ctx.json({ error: "historical_data is required" })
        next
      end

      # Get rules for agent creation
      rules_json = data["rules"]
      unless rules_json
        ctx.status(400)
        ctx.json({ error: "rules JSON is required" })
        next
      end

      # Create agent
      evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: rules_json)
      agent = DecisionAgent::Agent.new(evaluators: [evaluator])
      version_manager = DecisionAgent::Versioning::VersionManager.new

      # Create replay engine
      replay_engine = DecisionAgent::Simulation::ReplayEngine.new(
        agent: agent,
        version_manager: version_manager
      )

      # Convert historical data if it's a file path (for future file upload support)
      contexts = if historical_data.is_a?(Array)
                   historical_data
                 else
                   # Assume it's a file path - load it
                   raise ArgumentError, "File not found: #{historical_data}" unless File.exist?(historical_data)

                   if historical_data.end_with?(".json")
                     JSON.parse(File.read(historical_data))
                   elsif historical_data.end_with?(".csv")
                     # Simple CSV parsing
                     require "csv"
                     csv_data = CSV.read(historical_data, headers: true)
                     csv_data.map(&:to_h)
                   else
                     raise ArgumentError, "Unsupported file format"
                   end
                 end

      # Execute replay
      results = if compare_with
                  replay_engine.replay(
                    historical_data: contexts,
                    rule_version: rule_version,
                    compare_with: compare_with
                  )
                else
                  replay_engine.replay(
                    historical_data: contexts,
                    rule_version: rule_version,
                    options: options
                  )
                end

      # Store results
      replay_id = SecureRandom.uuid
      Server.simulation_storage_mutex.synchronize do
        Server.simulation_storage[replay_id] = {
          id: replay_id,
          type: "replay",
          status: "completed",
          created_at: Time.now.utc.iso8601,
          results: results
        }
      end

      ctx.json({
                 replay_id: replay_id,
                 results: results
               })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: "Replay failed: #{e.message}" })
    end
  end

  # POST /api/simulation/whatif - What-if analysis
  router.post "/api/simulation/whatif" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = request_body.empty? ? {} : JSON.parse(request_body)

      scenarios = data["scenarios"]
      rule_version = data["rule_version"]
      options = data["options"] || {}

      unless scenarios.is_a?(Array)
        ctx.status(400)
        ctx.json({ error: "scenarios array is required" })
        next
      end

      # Get rules for agent creation
      rules_json = data["rules"]
      unless rules_json
        ctx.status(400)
        ctx.json({ error: "rules JSON is required" })
        next
      end

      # Create agent
      evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: rules_json)
      agent = DecisionAgent::Agent.new(evaluators: [evaluator])
      version_mgr = Server.version_manager

      # Create what-if analyzer
      analyzer = DecisionAgent::Simulation::WhatIfAnalyzer.new(
        agent: agent,
        version_manager: version_mgr
      )

      # Execute analysis
      results = analyzer.analyze(
        scenarios: scenarios,
        rule_version: rule_version,
        options: options
      )

      # Store results
      analysis_id = SecureRandom.uuid
      Server.simulation_storage_mutex.synchronize do
        Server.simulation_storage[analysis_id] = {
          id: analysis_id,
          type: "whatif",
          status: "completed",
          created_at: Time.now.utc.iso8601,
          results: results
        }
      end

      ctx.json({
                 analysis_id: analysis_id,
                 results: results
               })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: "What-if analysis failed: #{e.message}" })
    end
  end

  # POST /api/simulation/whatif/sensitivity - Sensitivity analysis
  router.post "/api/simulation/whatif/sensitivity" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = request_body.empty? ? {} : JSON.parse(request_body)

      base_scenario = data["base_scenario"]
      variations = data["variations"]
      rule_version = data["rule_version"]

      unless base_scenario && variations
        ctx.status(400)
        ctx.json({ error: "base_scenario and variations are required" })
        next
      end

      # Get rules for agent creation
      rules_json = data["rules"]
      unless rules_json
        ctx.status(400)
        ctx.json({ error: "rules JSON is required" })
        next
      end

      # Create agent
      evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: rules_json)
      agent = DecisionAgent::Agent.new(evaluators: [evaluator])
      version_mgr = Server.version_manager

      # Create what-if analyzer
      analyzer = DecisionAgent::Simulation::WhatIfAnalyzer.new(
        agent: agent,
        version_manager: version_mgr
      )

      # Execute sensitivity analysis
      results = analyzer.sensitivity_analysis(
        base_scenario: base_scenario,
        variations: variations,
        rule_version: rule_version
      )

      ctx.json({ results: results })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: "Sensitivity analysis failed: #{e.message}" })
    end
  end

  # POST /api/simulation/impact - Impact analysis
  router.post "/api/simulation/impact" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = request_body.empty? ? {} : JSON.parse(request_body)

      baseline_version = data["baseline_version"]
      proposed_version = data["proposed_version"]
      test_data = data["test_data"]
      options = data["options"] || {}

      unless baseline_version && proposed_version && test_data
        ctx.status(400)
        ctx.json({ error: "baseline_version, proposed_version, and test_data are required" })
        next
      end

      version_mgr = Server.version_manager

      # Create impact analyzer
      analyzer = DecisionAgent::Simulation::ImpactAnalyzer.new(
        version_manager: version_mgr
      )

      # Execute impact analysis
      results = analyzer.analyze(
        baseline_version: baseline_version,
        proposed_version: proposed_version,
        test_data: test_data,
        options: options
      )

      # Store results
      impact_id = SecureRandom.uuid
      Server.simulation_storage_mutex.synchronize do
        Server.simulation_storage[impact_id] = {
          id: impact_id,
          type: "impact",
          status: "completed",
          created_at: Time.now.utc.iso8601,
          results: results
        }
      end

      ctx.json({
                 impact_id: impact_id,
                 results: results
               })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: "Impact analysis failed: #{e.message}" })
    end
  end

  # POST /api/simulation/shadow - Shadow testing
  router.post "/api/simulation/shadow" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = request_body.empty? ? {} : JSON.parse(request_body)

      context = data["context"]
      shadow_version = data["shadow_version"]
      production_rules = data["production_rules"]
      shadow_rules = data["shadow_rules"]
      options = data["options"] || {}

      unless context
        ctx.status(400)
        ctx.json({ error: "context is required" })
        next
      end

      unless (production_rules && shadow_rules) || shadow_version
        ctx.status(400)
        ctx.json({ error: "Either (production_rules and shadow_rules) or shadow_version is required" })
        next
      end

      version_mgr = Server.version_manager

      # Create production agent
      if production_rules
        prod_evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: production_rules)
        production_agent = DecisionAgent::Agent.new(evaluators: [prod_evaluator])
      else
        # Use active version
        active_version = version_mgr.get_active_version
        if active_version
          prod_evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: active_version[:content])
          production_agent = DecisionAgent::Agent.new(evaluators: [prod_evaluator])
        else
          ctx.status(400)
          ctx.json({ error: "No active version found and production_rules not provided" })
          next
        end
      end

      # Create shadow test engine
      shadow_engine = DecisionAgent::Simulation::ShadowTestEngine.new(
        production_agent: production_agent,
        version_manager: version_mgr
      )

      # Execute shadow test
      if shadow_rules
        # Create a temporary version for shadow rules
        temp_version = {
          content: shadow_rules,
          rule_id: "shadow_temp",
          version_number: 1
        }
        result = shadow_engine.test(
          context: context,
          shadow_version: temp_version,
          options: options
        )
      else
        result = shadow_engine.test(
          context: context,
          shadow_version: shadow_version,
          options: options
        )
      end

      ctx.json({ result: result })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: "Shadow test failed: #{e.message}" })
    end
  end

  # POST /api/simulation/shadow/batch - Batch shadow testing
  router.post "/api/simulation/shadow/batch" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = request_body.empty? ? {} : JSON.parse(request_body)

      contexts = data["contexts"]
      shadow_version = data["shadow_version"]
      production_rules = data["production_rules"]
      shadow_rules = data["shadow_rules"]
      options = data["options"] || {}

      unless contexts.is_a?(Array)
        ctx.status(400)
        ctx.json({ error: "contexts array is required" })
        next
      end

      unless (production_rules && shadow_rules) || shadow_version
        ctx.status(400)
        ctx.json({ error: "Either (production_rules and shadow_rules) or shadow_version is required" })
        next
      end

      version_mgr = Server.version_manager

      # Create production agent
      if production_rules
        prod_evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: production_rules)
        production_agent = DecisionAgent::Agent.new(evaluators: [prod_evaluator])
      else
        # Use active version
        active_version = version_mgr.get_active_version
        if active_version
          prod_evaluator = DecisionAgent::Evaluators::JsonRuleEvaluator.new(rules_json: active_version[:content])
          production_agent = DecisionAgent::Agent.new(evaluators: [prod_evaluator])
        else
          ctx.status(400)
          ctx.json({ error: "No active version found and production_rules not provided" })
          next
        end
      end

      # Create shadow test engine
      shadow_engine = DecisionAgent::Simulation::ShadowTestEngine.new(
        production_agent: production_agent,
        version_manager: version_mgr
      )

      # Execute batch shadow test
      if shadow_rules
        # Create a temporary version for shadow rules
        temp_version = {
          content: shadow_rules,
          rule_id: "shadow_temp",
          version_number: 1
        }
        results = shadow_engine.batch_test(
          contexts: contexts,
          shadow_version: temp_version,
          options: options
        )
      else
        results = shadow_engine.batch_test(
          contexts: contexts,
          shadow_version: shadow_version,
          options: options
        )
      end

      ctx.json({ results: results })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: "Batch shadow test failed: #{e.message}" })
    end
  end

  # GET /api/simulation/:id - Get simulation results
  router.get "/api/simulation/:id" do |ctx|
    ctx.content_type "application/json"

    begin
      sim_id = ctx.params[:id] || ctx.params["id"]

      sim_data = nil
      Server.simulation_storage_mutex.synchronize do
        sim_data = Server.simulation_storage[sim_id]
      end

      unless sim_data
        ctx.status(404)
        ctx.json({ error: "Simulation not found" })
        next
      end

      ctx.json(sim_data)
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # GET /api/versions - List all versions (for simulation dropdowns)
  router.get "/api/versions" do |ctx|
    ctx.content_type "application/json"

    begin
      version_mgr = Server.version_manager
      versions = version_mgr.list_all_versions

      ctx.json({
                 versions: versions.map do |v|
                   {
                     id: v[:id] || v["id"],
                     rule_id: v[:rule_id] || v["rule_id"],
                     version_number: v[:version_number] || v["version_number"],
                     status: v[:status] || v["status"],
                     created_at: v[:created_at] || v["created_at"]
                   }
                 end
               })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # GET /simulation - Simulation dashboard UI page
  router.get "/simulation" do |ctx|
    sim_file = File.join(Server.public_folder, "simulation.html")
    Server.serve_html_with_base_tag(ctx, sim_file, "Simulation page not found")
  rescue StandardError => e
    warn "[DecisionAgent] Error serving simulation page: #{e.message}"
    ctx.status(404)
    ctx.body("Simulation page not found")
  end

  # GET /simulation/replay - Historical replay UI page
  router.get "/simulation/replay" do |ctx|
    replay_file = File.join(Server.public_folder, "simulation_replay.html")
    Server.serve_html_with_base_tag(ctx, replay_file, "Historical replay page not found")
  rescue StandardError => e
    warn "[DecisionAgent] Error serving replay page: #{e.message}"
    ctx.status(404)
    ctx.body("Historical replay page not found")
  end

  # GET /simulation/whatif - What-if analysis UI page
  router.get "/simulation/whatif" do |ctx|
    whatif_file = File.join(Server.public_folder, "simulation_whatif.html")
    Server.serve_html_with_base_tag(ctx, whatif_file, "What-if analysis page not found")
  rescue StandardError => e
    warn "[DecisionAgent] Error serving what-if page: #{e.message}"
    ctx.status(404)
    ctx.body("What-if analysis page not found")
  end

  # GET /simulation/impact - Impact analysis UI page
  router.get "/simulation/impact" do |ctx|
    impact_file = File.join(Server.public_folder, "simulation_impact.html")
    Server.serve_html_with_base_tag(ctx, impact_file, "Impact analysis page not found")
  rescue StandardError => e
    warn "[DecisionAgent] Error serving impact page: #{e.message}"
    ctx.status(404)
    ctx.body("Impact analysis page not found")
  end

  # GET /simulation/shadow - Shadow testing UI page
  router.get "/simulation/shadow" do |ctx|
    shadow_file = File.join(Server.public_folder, "simulation_shadow.html")
    Server.serve_html_with_base_tag(ctx, shadow_file, "Shadow testing page not found")
  rescue StandardError => e
    warn "[DecisionAgent] Error serving shadow testing page: #{e.message}"
    ctx.status(404)
    ctx.body("Shadow testing page not found")
  end

  # GET /auth/login - Login page
  router.get "/auth/login" do |ctx|
     = File.join(Server.public_folder, "login.html")
    Server.serve_html_with_base_tag(ctx, , "Login page not found")
  rescue StandardError => e
    warn "[DecisionAgent] Error serving login page: #{e.message}"
    ctx.status(404)
    ctx.body("Login page not found")
  end

  # GET /auth/users - User management page
  router.get "/auth/users" do |ctx|
    users_file = File.join(Server.public_folder, "users.html")
    Server.serve_html_with_base_tag(ctx, users_file, "User management page not found")
  rescue StandardError => e
    warn "[DecisionAgent] Error serving users page: #{e.message}"
    ctx.status(404)
    ctx.body("User management page not found")
  end

  # DMN Editor Routes

  # GET /dmn/editor - DMN Editor UI page
  router.get "/dmn/editor" do |ctx|
    dmn_file = File.join(Server.public_folder, "dmn-editor.html")
    Server.serve_html_with_base_tag(ctx, dmn_file, "DMN Editor page not found")
  rescue StandardError => e
    warn "[DecisionAgent] Error serving DMN editor page: #{e.message}"
    ctx.status(404)
    ctx.body("DMN Editor page not found")
  end

  # API: List all DMN models
  router.get "/api/dmn/models" do |ctx|
    ctx.content_type "application/json"
    ctx.json(Server.dmn_editor.list_models)
  end

  # API: Create new DMN model
  router.post "/api/dmn/models" do |ctx|
    ctx.content_type "application/json"

    begin
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      model = Server.dmn_editor.create_model(
        name: data["name"],
        namespace: data["namespace"]
      )

      ctx.status(201)
      ctx.json(model)
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # API: Get DMN model
  router.get "/api/dmn/models/:id" do |ctx|
    ctx.content_type "application/json"

    model_id = ctx.params[:id] || ctx.params["id"]
    model = Server.dmn_editor.get_model(model_id)
    if model
      ctx.json(model)
    else
      ctx.status(404)
      ctx.json({ error: "Model not found" })
    end
  end

  # API: Update DMN model
  router.put "/api/dmn/models/:id" do |ctx|
    ctx.content_type "application/json"

    begin
      model_id = ctx.params[:id] || ctx.params["id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      model = Server.dmn_editor.update_model(
        model_id,
        name: data["name"],
        namespace: data["namespace"]
      )

      if model
        ctx.json(model)
      else
        ctx.status(404)
        ctx.json({ error: "Model not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # API: Delete DMN model
  router.delete "/api/dmn/models/:id" do |ctx|
    ctx.content_type "application/json"

    model_id = ctx.params[:id] || ctx.params["id"]
    result = Server.dmn_editor.delete_model(model_id)
    ctx.json({ success: result })
  end

  # API: Add decision to model
  router.post "/api/dmn/models/:model_id/decisions" do |ctx|
    ctx.content_type "application/json"

    begin
      model_id = ctx.params[:model_id] || ctx.params["model_id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      decision = Server.dmn_editor.add_decision(
        model_id: model_id,
        decision_id: data["decision_id"],
        name: data["name"],
        type: data["type"] || "decision_table"
      )

      if decision
        ctx.status(201)
        ctx.json(decision)
      else
        ctx.status(404)
        ctx.json({ error: "Model not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # API: Update decision
  router.put "/api/dmn/models/:model_id/decisions/:decision_id" do |ctx|
    ctx.content_type "application/json"

    begin
      model_id = ctx.params[:model_id] || ctx.params["model_id"]
      decision_id = ctx.params[:decision_id] || ctx.params["decision_id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      decision = Server.dmn_editor.update_decision(
        model_id: model_id,
        decision_id: decision_id,
        name: data["name"],
        logic: data["logic"]
      )

      if decision
        ctx.json(decision)
      else
        ctx.status(404)
        ctx.json({ error: "Decision not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # API: Delete decision
  router.delete "/api/dmn/models/:model_id/decisions/:decision_id" do |ctx|
    ctx.content_type "application/json"

    model_id = ctx.params[:model_id] || ctx.params["model_id"]
    decision_id = ctx.params[:decision_id] || ctx.params["decision_id"]
    result = Server.dmn_editor.delete_decision(
      model_id: model_id,
      decision_id: decision_id
    )

    ctx.json({ success: result })
  end

  # API: Add input column
  router.post "/api/dmn/models/:model_id/decisions/:decision_id/inputs" do |ctx|
    ctx.content_type "application/json"

    begin
      model_id = ctx.params[:model_id] || ctx.params["model_id"]
      decision_id = ctx.params[:decision_id] || ctx.params["decision_id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      input = Server.dmn_editor.add_input(
        model_id: model_id,
        decision_id: decision_id,
        input_id: data["input_id"],
        label: data["label"],
        type_ref: data["type_ref"],
        expression: data["expression"]
      )

      if input
        ctx.status(201)
        ctx.json(input)
      else
        ctx.status(404)
        ctx.json({ error: "Decision not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # API: Add output column
  router.post "/api/dmn/models/:model_id/decisions/:decision_id/outputs" do |ctx|
    ctx.content_type "application/json"

    begin
      model_id = ctx.params[:model_id] || ctx.params["model_id"]
      decision_id = ctx.params[:decision_id] || ctx.params["decision_id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      output = Server.dmn_editor.add_output(
        model_id: model_id,
        decision_id: decision_id,
        output_id: data["output_id"],
        label: data["label"],
        type_ref: data["type_ref"],
        name: data["name"]
      )

      if output
        ctx.status(201)
        ctx.json(output)
      else
        ctx.status(404)
        ctx.json({ error: "Decision not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # API: Add rule
  router.post "/api/dmn/models/:model_id/decisions/:decision_id/rules" do |ctx|
    ctx.content_type "application/json"

    begin
      model_id = ctx.params[:model_id] || ctx.params["model_id"]
      decision_id = ctx.params[:decision_id] || ctx.params["decision_id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      rule = Server.dmn_editor.add_rule(
        model_id: model_id,
        decision_id: decision_id,
        rule_id: data["rule_id"],
        input_entries: data["input_entries"],
        output_entries: data["output_entries"],
        description: data["description"]
      )

      if rule
        ctx.status(201)
        ctx.json(rule)
      else
        ctx.status(404)
        ctx.json({ error: "Decision not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # API: Update rule
  router.put "/api/dmn/models/:model_id/decisions/:decision_id/rules/:rule_id" do |ctx|
    ctx.content_type "application/json"

    begin
      model_id = ctx.params[:model_id] || ctx.params["model_id"]
      decision_id = ctx.params[:decision_id] || ctx.params["decision_id"]
      rule_id = ctx.params[:rule_id] || ctx.params["rule_id"]
      request_body = RackRequestHelpers.read_body(ctx.env)
      data = JSON.parse(request_body)

      rule = Server.dmn_editor.update_rule(
        model_id: model_id,
        decision_id: decision_id,
        rule_id: rule_id,
        input_entries: data["input_entries"],
        output_entries: data["output_entries"],
        description: data["description"]
      )

      if rule
        ctx.json(rule)
      else
        ctx.status(404)
        ctx.json({ error: "Rule not found" })
      end
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: e.message })
    end
  end

  # API: Delete rule
  router.delete "/api/dmn/models/:model_id/decisions/:decision_id/rules/:rule_id" do |ctx|
    ctx.content_type "application/json"

    model_id = ctx.params[:model_id] || ctx.params["model_id"]
    decision_id = ctx.params[:decision_id] || ctx.params["decision_id"]
    rule_id = ctx.params[:rule_id] || ctx.params["rule_id"]
    result = Server.dmn_editor.delete_rule(
      model_id: model_id,
      decision_id: decision_id,
      rule_id: rule_id
    )

    ctx.json({ success: result })
  end

  # API: Validate DMN model
  router.get "/api/dmn/models/:id/validate" do |ctx|
    ctx.content_type "application/json"
    model_id = ctx.params[:id] || ctx.params["id"]
    ctx.json(Server.dmn_editor.validate_model(model_id))
  end

  # API: Export DMN model to XML
  router.get "/api/dmn/models/:id/export" do |ctx|
    ctx.content_type "application/xml"

    model_id = ctx.params[:id] || ctx.params["id"]
    xml = Server.dmn_editor.export_to_xml(model_id)
    if xml
      ctx.body(xml)
    else
      ctx.status(404)
      ctx.body("Model not found")
    end
  end

  # API: Visualize decision tree
  router.get "/api/dmn/models/:model_id/decisions/:decision_id/visualize/tree" do |ctx|
    model_id = ctx.params[:model_id] || ctx.params["model_id"]
    decision_id = ctx.params[:decision_id] || ctx.params["decision_id"]
    format = (ctx.params[:format] || ctx.params["format"]) || "svg"

    visualization = Server.dmn_editor.visualize_tree(
      model_id: model_id,
      decision_id: decision_id,
      format: format
    )

    if visualization
      ctx.content_type(format == "svg" ? "image/svg+xml" : "text/plain")
      ctx.body(visualization)
    else
      ctx.status(404)
      ctx.body("Decision not found or not a tree")
    end
  end

  # API: Visualize decision graph
  router.get "/api/dmn/models/:id/visualize/graph" do |ctx|
    model_id = ctx.params[:id] || ctx.params["id"]
    format = (ctx.params[:format] || ctx.params["format"]) || "svg"

    visualization = Server.dmn_editor.visualize_graph(
      model_id: model_id,
      format: format
    )

    if visualization
      ctx.content_type(format == "svg" ? "image/svg+xml" : "text/plain")
      ctx.body(visualization)
    else
      ctx.status(404)
      ctx.body("Model not found")
    end
  end

  # API: Import DMN file (uploads and imports to versioning system)
  router.post "/api/dmn/import" do |ctx|
    ctx.content_type "application/json"

    begin
      # Check if request has multipart form data (file upload)
      file_param = ctx.params[:file] || ctx.params["file"]
      content_type_header = ctx.request.content_type || ""

      if file_param && (file_param[:tempfile] || file_param["tempfile"])
        # File upload
        file = file_param[:tempfile] || file_param["tempfile"]
        xml_content = file.read
        filename = file_param[:filename] || file_param["filename"] || ""
        ruleset_name = (ctx.params[:ruleset_name] || ctx.params["ruleset_name"]) || filename.gsub(/\.dmn$/i, "")
        created_by = ctx.current_user ? ctx.current_user.id.to_s : (ctx.params[:created_by] || ctx.params["created_by"] || "system")
      elsif content_type_header.include?("application/json")
        # JSON body with XML content
        request_body = RackRequestHelpers.read_body(ctx.env)
        data = JSON.parse(request_body)
        xml_content = data["xml"] || data["content"]
        ruleset_name = data["ruleset_name"] || data["name"]
        created_by = ctx.current_user ? ctx.current_user.id.to_s : (data["created_by"] || "system")
      elsif content_type_header.include?("application/xml") || content_type_header.include?("text/xml")
        # Direct XML upload
        xml_content = RackRequestHelpers.read_body(ctx.env)
        ruleset_name = ctx.params[:ruleset_name] || ctx.params["ruleset_name"] || "imported_dmn"
        created_by = ctx.current_user ? ctx.current_user.id.to_s : (ctx.params[:created_by] || ctx.params["created_by"] || "system")
      else
        ctx.status(400)
        ctx.json({ error: "Invalid request. Expected file upload, JSON with 'xml' field, or XML content." })
        next
      end

      raise ArgumentError, "DMN XML content is required" if xml_content.nil? || xml_content.strip.empty?

      # Import using DMN Importer
      importer = Dmn::Importer.new(version_manager: Server.version_manager)
      result = importer.import_from_xml(
        xml_content,
        ruleset_name: ruleset_name,
        created_by: created_by
      )

      ctx.status(201)
      ctx.json({
                 success: true,
                 ruleset_name: ruleset_name,
                 decisions_imported: result[:decisions_imported],
                 model: {
                   id: result[:model].id,
                   name: result[:model].name,
                   namespace: result[:model].namespace,
                   decisions: result[:model].decisions.map do |d|
                     {
                       id: d.id,
                       name: d.name
                     }
                   end
                 },
                 versions: result[:versions].map do |v|
                   {
                     version: v[:version],
                     rule_id: v[:rule_id],
                     created_by: v[:created_by],
                     created_at: v[:created_at]
                   }
                 end
               })
    rescue Dmn::InvalidDmnModelError, Dmn::DmnParseError => e
      ctx.status(400)
      ctx.json({ error: "DMN validation error", message: e.message })
    rescue StandardError => e
      ctx.status(500)
      ctx.json({ error: "Import failed", message: e.message })
    end
  end

  # API: Export ruleset as DMN XML
  router.get "/api/dmn/export/:ruleset_id" do |ctx|
    ctx.content_type "application/xml"

    begin
      ruleset_id = ctx.params[:ruleset_id] || ctx.params["ruleset_id"]
      exporter = Dmn::Exporter.new(version_manager: Server.version_manager)
      dmn_xml = exporter.export(ruleset_id)

      ctx.headers["Content-Disposition"] = "attachment; filename=\"#{ruleset_id}.dmn\""
      ctx.body(dmn_xml)
    rescue Dmn::InvalidDmnModelError => e
      ctx.status(404)
      ctx.content_type "application/json"
      ctx.json({ error: "Ruleset not found", message: e.message })
    rescue StandardError => e
      ctx.status(500)
      ctx.content_type "application/json"
      ctx.json({ error: "Export failed", message: e.message })
    end
  end
end

.dmn_editorObject



318
319
320
# File 'lib/decision_agent/web/server.rb', line 318

def self.dmn_editor
  @dmn_editor ||= DecisionAgent::Web::DmnEditor.new
end

.extract_token(ctx) ⇒ Object

Helper methods for routes - work with RequestContext



224
225
226
# File 'lib/decision_agent/web/server.rb', line 224

def self.extract_token(ctx)
  extract_token_from_context(ctx)
end

.extract_token_from_context(ctx) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/decision_agent/web/server.rb', line 210

def self.extract_token_from_context(ctx)
  # Check Authorization header: Bearer <token>
  auth_header = ctx.request.get_header("HTTP_AUTHORIZATION")
  return auth_header[7..] if auth_header&.start_with?("Bearer ")

  # Check session cookie
  cookie_token = ctx.cookies["decision_agent_session"]
  return cookie_token if cookie_token

  # Check query parameter
  ctx.params["token"] || ctx.params[:token]
end

.parse_validation_errors(error_message) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/decision_agent/web/server.rb', line 295

def self.parse_validation_errors(error_message)
  # Extract individual errors from the formatted error message
  errors = []

  # The error message is formatted with numbered errors
  lines = error_message.split("\n")

  lines.each do |line|
    # Match lines like "  1. Error message"
    if line.match?(/^\s*\d+\.\s+/)
      error = line.gsub(/^\s*\d+\.\s+/, "").strip
      errors << error unless error.empty?
    end
  end

  # If no errors were parsed, return the full message
  errors.empty? ? [error_message] : errors
end

.permissions_disabled?Boolean

Returns:

  • (Boolean)


281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/decision_agent/web/server.rb', line 281

def self.permissions_disabled?
  # Check explicit environment variable first
  disable_flag = ENV.fetch("DISABLE_WEBUI_PERMISSIONS", nil)
  if disable_flag
    normalized = disable_flag.to_s.strip.downcase
    return true if %w[true 1 yes].include?(normalized)
    return false if %w[false 0 no].include?(normalized)
  end

  # Auto-disable in development environments if not explicitly set
  env = ENV["RACK_ENV"] || ENV["RAILS_ENV"] || "development"
  env == "development"
end

.require_authentication!(ctx) ⇒ Object



228
229
230
231
232
233
# File 'lib/decision_agent/web/server.rb', line 228

def self.require_authentication!(ctx)
  return if ctx.current_user

  ctx.content_type "application/json"
  ctx.halt(401, { error: "Authentication required" }.to_json)
end

.require_permission!(ctx, permission, resource = nil) ⇒ Object



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
# File 'lib/decision_agent/web/server.rb', line 235

def self.require_permission!(ctx, permission, resource = nil)
  # Skip all permission checks if disabled via environment variable
  return true if permissions_disabled?

  # Require authentication only if permissions are enabled
  require_authentication!(ctx)
  return if ctx.halted?

  checker = Server.permission_checker
  granted = checker.can?(ctx.current_user, permission, resource)

  unless granted
    # Log the permission denial
    begin
      user_id = checker.user_id(ctx.current_user)
      Server.access_audit_logger.log_permission_check(
        user_id: user_id,
        permission: permission,
        resource_type: resource&.class&.name,
        resource_id: resource&.id,
        granted: false
      )
    rescue StandardError => e
      # If logging fails, continue with permission denial
      warn "[DecisionAgent] Failed to log permission denial: #{e.message}"
    end
    ctx.content_type "application/json"
    ctx.halt(403, { error: "Permission denied: #{permission}" }.to_json)
  end

  # Log successful permission check
  begin
    user_id = checker.user_id(ctx.current_user)
    Server.access_audit_logger.log_permission_check(
      user_id: user_id,
      permission: permission,
      resource_type: resource&.class&.name,
      resource_id: resource&.id,
      granted: true
    )
  rescue StandardError => e
    # If logging fails, continue - permission was granted
    warn "[DecisionAgent] Failed to log permission grant: #{e.message}"
  end
end

.routerObject

Initialize router and define routes



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
# File 'lib/decision_agent/web/server.rb', line 112

def self.router
  return @router if @router

  @router = Router.new

  # Enable CORS for API calls
  @router.before do |ctx|
    ctx.headers["Access-Control-Allow-Origin"] = "*"
    ctx.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS, PUT"
    ctx.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
  end

  # Auth middleware - extract user from token
  @router.before do |ctx|
    token = Server.extract_token_from_context(ctx)
    if token
      auth_result = Server.authenticator.authenticate(token)
      if auth_result
        ctx.current_user = auth_result[:user]
        ctx.current_session = auth_result[:session]
      end
    end
  end

  # Define all routes
  define_routes(@router)

  @router
end

.serve_html_with_base_tag(ctx, html_file, not_found_message = "Page not found") ⇒ Object

Serve an HTML file with tag injection for subpath mounting



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/decision_agent/web/server.rb', line 323

def self.serve_html_with_base_tag(ctx, html_file, not_found_message = "Page not found")
  unless File.exist?(html_file)
    ctx.status(404)
    ctx.body(not_found_message)
    return
  end

  html_content = File.read(html_file, encoding: "UTF-8")

  # Determine the base path from the request
  base_path = ctx.script_name.empty? ? "./" : "#{ctx.script_name}/"

  # Inject or update base tag
  base_tag = "<base href=\"#{base_path}\">"
  html_content = if html_content.include?("<base")
                   html_content.sub(/<base[^>]*>/, base_tag)
                 else
                   html_content.sub("<head>", "<head>\n    #{base_tag}")
                 end

  ctx.content_type "text/html"
  ctx.body(html_content)
end

.start!(port: 4567, host: "0.0.0.0") ⇒ Object

Class method to start the server (for CLI usage) Framework-agnostic: uses Rack::Server which supports any Rack-compatible server



2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
# File 'lib/decision_agent/web/server.rb', line 2483

def self.start!(port: 4567, host: "0.0.0.0")
  @port = port
  @bind = host

  puts "🎯 DecisionAgent Web UI starting..."
  puts "📍 Server: http://#{host == '0.0.0.0' ? 'localhost' : host}:#{port}"
  puts "⚡️  Press Ctrl+C to stop"
  puts ""

  # Use Rack::Server which automatically selects the best available handler
  # Supports: Puma, WEBrick, Thin, Unicorn, etc. (any Rack-compatible server)
  Rack::Server.start(
    app: self,
    Port: port,
    Host: host,
    server: ENV.fetch("RACK_HANDLER", nil), # Allows override via ENV
    environment: ENV.fetch("RACK_ENV", "development")
  )
end

.version_managerObject



314
315
316
# File 'lib/decision_agent/web/server.rb', line 314

def self.version_manager
  @version_manager ||= DecisionAgent::Versioning::VersionManager.new
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/decision_agent/web/server.rb', line 147

def call(env)
  # Try to serve static files first
  path = env["PATH_INFO"] || "/"
  static_file = serve_static_file(path, env)
  return static_file if static_file

  # Route the request
  route_match = self.class.router.match(env)
  return [404, { "Content-Type" => "application/json" }, [{ error: "Not Found", path: path }.to_json]] unless route_match

  # Create request context with route params
  ctx = RequestContext.new(env, route_match[:params] || {})

  # Run before filters
  route_match[:before_filters].each do |filter|
    filter.call(ctx)
    return ctx.to_rack_response if ctx.halted?
  end

  # Execute route handler
  begin
    route_match[:handler].call(ctx)
    ctx.to_rack_response
  rescue StandardError => e
    [500, { "Content-Type" => "application/json" }, [{ error: e.message }.to_json]]
  end
end