File size: 52,052 Bytes
7215e83 | 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 | """
AST-CatalaGen Studio Web Server (Strictly Zero Regex)
====================================================
Dedicated interactive Web Studio & visualization server for AST-CatalaGen.
Serves a responsive, dual-column/single-column chat-like UI with:
- Rich multi-line statutory text input area (no terminal limits)
- Interactive top-to-bottom Rule Lifecycle Flow Diagrams (Mermaid & structured DAG)
- Side-by-side Statutory AST (.ast.json) and Literate Catala (.catala_en) views
- Tasks, benchmark presets (SARA Gold 20, US IRC, India Tax), queries, and history
- Clickable links to disk artifacts (.ast.json, .catala_en, HTML/PDF reports)
- Live pipeline stage controls (Stage 1 -> Stage 2B -> Stage 3 Emitter)
Uses Python standard library http.server (100% zero external web dependencies).
Strictly ZERO regex. Zero emojis.
"""
from __future__ import annotations
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
from typing import Any
import urllib.parse
import webbrowser
from canonical_pipeline import (
MudraForgeCanonicalPipeline,
normalize_stage_name,
resolve_stage_range,
)
from catala_ast_emitter import (
build_statutory_ast,
render_catala_source,
write_ast_and_catala_artifacts,
)
from statutory_diagram import generate_rule_lifecycle_diagram
ROOT_DIR = Path(os.environ.get("MUDRAFORGE_ROOT", str(Path(__file__).resolve().parent.parent)))
STUDIO_EMIT_DIR = ROOT_DIR / "emitted" / "studio"
STUDIO_EMIT_DIR.mkdir(parents=True, exist_ok=True)
DEFAULT_PORT = 8765
STUDIO_PRESETS: dict[str, dict[str, str]] = {
"US_IRC_1_A": {
"id": "US_IRC_1_A",
"title": "IRC Section 1(a) -- Married Joint Return (5 Progressive Tax Brackets)",
"law": "26 U.S. Code Section 1(a)",
"category": "US Federal Income Tax",
"text": (
"(a) Married individuals filing joint returns and surviving spouses: "
"There is hereby imposed on the taxable income of every married individual who makes a single return jointly with his spouse under section 6013, and of every surviving spouse: "
"If taxable income is: Not over $36,900, the tax is 15% of taxable income. "
"Over $36,900 but not over $89,150, the tax is $5,535, plus 28% of the excess over $36,900. "
"Over $89,150 but not over $140,000, the tax is $20,165, plus 31% of the excess over $89,150. "
"Over $140,000 but not over $250,000, the tax is $35,928.50, plus 36% of the excess over $140,000. "
"Over $250,000, the tax is $75,528.50, plus 39.6% of the excess over $250,000."
),
},
"US_IRC_63_A": {
"id": "US_IRC_63_A",
"title": "IRC Section 63(a) -- Taxable Income Definition & Subsection (b) Exception",
"law": "26 U.S. Code Section 63(a)",
"category": "US Federal Income Tax",
"text": (
"(a) In general: Except as provided in subsection (b), for purposes of this subtitle, "
"the term taxable income means gross income minus the deductions allowed by this chapter (other than the standard deduction)."
),
},
"US_IRC_63_B": {
"id": "US_IRC_63_B",
"title": "IRC Section 63(b) -- Non-Itemizers Subtraction Formula",
"law": "26 U.S. Code Section 63(b)",
"category": "US Federal Income Tax",
"text": (
"(b) Individuals who do not itemize deductions: In the case of an individual who does not elect to itemize his deductions for the taxable year, "
"for purposes of this subtitle, the term taxable income means adjusted gross income, minus- (1) the standard deduction, and (2) the deduction for personal exemptions provided in section 151."
),
},
"US_IRC_68_A": {
"id": "US_IRC_68_A",
"title": "IRC Section 68(a) -- Itemized Deduction Haircut (Dual-Rate Min Combinator)",
"law": "26 U.S. Code Section 68(a)",
"category": "US Federal Income Tax",
"text": (
"(a) General rule: In the case of an individual whose adjusted gross income exceeds the applicable amount, "
"the amount of the itemized deductions otherwise allowable for the taxable year shall be reduced by the lesser of- "
"(1) 3 percent of the excess of adjusted gross income over the applicable amount, or "
"(2) 80 percent of the amount of the itemized deductions otherwise allowable for such taxable year."
),
},
"US_IRC_68_B": {
"id": "US_IRC_68_B",
"title": "IRC Section 68(b) -- Applicable Amount (Subparagraph Value Lookup Table)",
"law": "26 U.S. Code Section 68(b)",
"category": "US Federal Income Tax",
"text": (
"(b) Applicable amount: (1) In general For purposes of this section, the term \"applicable amount\" means- "
"(A) $300,000 in the case of a joint return or a surviving spouse (as defined in section 2(a)), "
"(B) $275,000 in the case of a head of household (as defined in section 2(b)), "
"(C) $250,000 in the case of an individual who is not married and who is not a surviving spouse or head of household, and "
"(D) 1/2 the amount applicable under subparagraph (A) in the case of a married individual filing a separate return. "
"For purposes of this paragraph, marital status shall be determined under section 7703."
),
},
"US_IRC_68_F": {
"id": "US_IRC_68_F",
"title": "IRC Section 68(f) -- TCJA Temporary Suspension Date Window",
"law": "26 U.S. Code Section 68(f)",
"category": "US Federal Income Tax",
"text": (
"(f) Section not to apply: This section shall not apply to any taxable year beginning after December 31, 2017, and before January 1, 2026."
),
},
"US_IRC_3301": {
"id": "US_IRC_3301",
"title": "IRC Section 3301 -- Federal Unemployment Tax Act (FUTA) 6% Rate",
"law": "26 U.S. Code Section 3301",
"category": "US Federal Employment Tax",
"text": (
"There is hereby imposed on every employer (as defined in section 3306(a)) for each calendar year an excise tax, "
"with respect to having individuals in his employ, equal to 6.0 percent of the total wages (as defined in section 3306(b)) "
"paid by him during the calendar year with respect to employment (as defined in section 3306(c))."
),
},
"US_IRC_7703_B": {
"id": "US_IRC_7703_B",
"title": "IRC Section 7703(b) -- Married Individuals Living Apart",
"law": "26 U.S. Code Section 7703(b)",
"category": "US Federal Income Tax",
"text": (
"(b) Certain married individuals living apart: For purposes of those provisions of this title which refer to this subsection, if- "
"(1) an individual who is married (within the meaning of subsection (a)) and who files a separate return maintains as his home a household "
"which constitutes for more than one-half of the taxable year the principal place of abode of a child, such individual shall not be considered as married."
),
},
"IN_ITA_194Q": {
"id": "IN_ITA_194Q",
"title": "India Income-tax Act Section 194Q -- TDS on Purchase of Goods Exceeding Rs 50 Lakh",
"law": "Section 194Q, Income-tax Act, 1961",
"category": "India Direct Tax",
"text": (
"Any person, being a buyer who is responsible for paying any sum to any resident for purchase of any goods "
"of the value or aggregate of such value exceeding fifty lakh rupees in any previous year, shall, at the time of credit "
"of such sum to the account of the seller or at the time of payment thereof by any mode, whichever is earlier, "
"deduct an amount equal to 0.1 per cent of such sum exceeding fifty lakh rupees as income-tax."
),
},
"IN_ITA_194C": {
"id": "IN_ITA_194C",
"title": "India Income-tax Act Section 194C -- TDS on Payments to Contractors",
"law": "Section 194C, Income-tax Act, 1961",
"category": "India Direct Tax",
"text": (
"Any person responsible for paying any sum to any resident for carrying out any work in pursuance of a contract between the contractor "
"and a specified person shall deduct an amount equal to- (i) one per cent where the payment is being made or credit is given to an individual or a Hindu undivided family; "
"(ii) two per cent where the payment is being made or credit is given to a person other than an individual or a Hindu undivided family, of such sum as income-tax."
),
},
}
_SESSION_HISTORY: list[dict[str, Any]] = []
_HISTORY_LOCK = threading.Lock()
class StudioRequestHandler(BaseHTTPRequestHandler):
"""Zero-regex, high-performance request handler for AST-CatalaGen Studio."""
pipeline_ref: MudraForgeCanonicalPipeline | None = None
def log_message(self, format: str, *args: Any) -> None:
"""Suppress noisy default request logs; write to sys.stderr cleanly."""
sys.stderr.write(f"[Studio HTTP] {format % args}\n")
def _send_json(self, status: int, data: Any) -> None:
raw = json.dumps(data, indent=2, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
self.wfile.write(raw)
def _send_html(self, status: int, html_str: str) -> None:
raw = html_str.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(raw)
def do_OPTIONS(self) -> None:
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def do_GET(self) -> None:
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
query = urllib.parse.parse_qs(parsed.query)
if path in ("/", "/index.html", "/studio"):
self._send_html(200, _get_studio_html())
return
if path == "/api/status":
pipe = self.pipeline_ref
res = {
"status": "online",
"app": "AST-CatalaGen Studio v6.1.0",
"device": pipe.device if pipe else "unknown",
"loaded_stages": list(pipe.loaded_stages) if pipe else [],
"statutory_guard": "isAuthorizedToDisburse: false",
"zero_regex_safety": True,
"history_count": len(_SESSION_HISTORY),
}
self._send_json(200, res)
return
if path == "/api/presets":
self._send_json(200, list(STUDIO_PRESETS.values()))
return
if path == "/api/history":
with _HISTORY_LOCK:
self._send_json(200, list(_SESSION_HISTORY))
return
if path == "/api/open":
target = query.get("file", [""])[0]
if not target:
self._send_json(400, {"error": "Missing 'file' parameter"})
return
p = Path(target)
if not p.exists():
self._send_json(404, {"error": f"File '{target}' not found"})
return
try:
if sys.platform == "win32":
os.startfile(str(p))
elif sys.platform == "darwin":
subprocess.run(["open", str(p)], check=False)
else:
subprocess.run(["xdg-open", str(p)], check=False)
self._send_json(200, {"opened": str(p)})
except Exception as exc:
self._send_json(500, {"error": f"Failed to open file: {exc}"})
return
if path.startswith("/api/artifacts/"):
rel_name = path[len("/api/artifacts/"):]
art_path = STUDIO_EMIT_DIR / rel_name
if art_path.exists() and art_path.is_file():
content = art_path.read_text(encoding="utf-8")
if art_path.suffix == ".json":
self._send_json(200, json.loads(content))
else:
self._send_html(200, f"<pre>{content}</pre>")
return
self._send_json(404, {"error": "Artifact not found"})
return
self._send_json(404, {"error": f"Not found: {path}"})
def do_POST(self) -> None:
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
if path == "/api/clear_history":
with _HISTORY_LOCK:
_SESSION_HISTORY.clear()
self._send_json(200, {"cleared": True})
return
if path == "/api/compile":
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length).decode("utf-8")
try:
payload = json.loads(body)
except Exception as exc:
self._send_json(400, {"error": f"Invalid JSON payload: {exc}"})
return
text = str(payload.get("text", "")).strip()
if not text:
self._send_json(400, {"error": "No statutory text provided."})
return
doc_id = str(payload.get("doc_id") or "STATUTE_001").strip()
start_st = normalize_stage_name(str(payload.get("start_stage", "stage1")))
end_st = normalize_stage_name(str(payload.get("end_stage", "stage2b")))
use_mem = bool(payload.get("use_memory", True))
pipe = self.pipeline_ref
if pipe is None:
stages = resolve_stage_range(start_st, end_st)
pipe = MudraForgeCanonicalPipeline(stages=stages, device="auto")
StudioRequestHandler.pipeline_ref = pipe
t0 = time.perf_counter()
run_res = pipe.run_pipeline(
text=text,
doc_id=doc_id,
start_stage=start_st,
end_stage=end_st,
use_memory=use_mem,
)
ast_obj = build_statutory_ast(run_res)
catala_src = render_catala_source(ast_obj)
diagram_data = generate_rule_lifecycle_diagram(ast_obj, run_res)
# Write artifacts to disk
emitted = write_ast_and_catala_artifacts(run_res, emit_dir=STUDIO_EMIT_DIR)
tot_latency_ms = round((time.perf_counter() - t0) * 1000.0, 2)
# Generate lightweight printable HTML report
report_path = STUDIO_EMIT_DIR / f"{doc_id}_report.html"
report_html = _build_standalone_statute_report(doc_id, text, ast_obj, catala_src, diagram_data["mermaid"])
report_path.write_text(report_html, encoding="utf-8")
written_paths = {
"ast_json": str(emitted.get("written", {}).get("ast_json", "")),
"catala_en": str(emitted.get("written", {}).get("catala_en", "")),
"html_report": str(report_path),
}
resp_item = {
"run_id": run_res.get("run_id"),
"timestamp_utc": ast_obj.get("generated_at_utc"),
"doc_id": doc_id,
"text": text,
"latency_ms": tot_latency_ms,
"pipeline_latency_ms": run_res.get("latency_ms", {}),
"stages_executed": run_res.get("stages_executed", []),
"stage_sources": run_res.get("stage_sources", {}),
"device": run_res.get("device", "cuda"),
"token_count": len(run_res.get("tokens", [])),
"ast": ast_obj,
"catala": catala_src,
"diagram": diagram_data,
"review_flags": ast_obj.get("review_flags", []),
"statutory_guard": "isAuthorizedToDisburse: false",
"written_artifacts": written_paths,
}
with _HISTORY_LOCK:
_SESSION_HISTORY.insert(0, resp_item)
if len(_SESSION_HISTORY) > 50:
_SESSION_HISTORY.pop()
self._send_json(200, resp_item)
return
self._send_json(404, {"error": f"Unknown POST endpoint: {path}"})
def _build_standalone_statute_report(
doc_id: str,
text: str,
ast_obj: dict[str, Any],
catala_src: str,
mermaid_code: str,
) -> str:
"""Creates a print-ready standalone HTML report for the compiled statute."""
ast_json_str = json.dumps(ast_obj, indent=2, ensure_ascii=False)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MudraForge Statutory AST Report - {doc_id}</title>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
<style>
body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #0b0f19; color: #f1f5f9; padding: 2rem; margin: 0; }}
h1, h2, h3 {{ color: #38bdf8; }}
.badge {{ display: inline-block; padding: 0.25rem 0.6rem; border-radius: 4px; font-size: 0.85rem; font-weight: bold; background: #1e293b; color: #10b981; border: 1px solid #334155; margin-right: 0.5rem; }}
.badge.warn {{ color: #f59e0b; border-color: #f59e0b; }}
.box {{ background: #111827; border: 1px solid #1f2937; border-radius: 8px; padding: 1.25rem; margin-bottom: 1.5rem; }}
pre {{ background: #030712; padding: 1rem; border-radius: 6px; overflow-x: auto; color: #a5f3fc; font-size: 0.9rem; line-height: 1.4; }}
.grid {{ display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }}
@media print {{ body {{ background: #fff; color: #000; }} pre {{ background: #f8fafc; color: #000; }} }}
</style>
</head>
<body>
<h1>MudraForge Formal Statutory Compiler Report</h1>
<div>
<span class="badge">Doc ID: {doc_id}</span>
<span class="badge">Pipeline: v6.1.0-prod</span>
<span class="badge warn">isAuthorizedToDisburse: false (Statutory Invariant)</span>
<span class="badge">Zero-Regex Verified</span>
</div>
<h2>1. Raw Statutory Text</h2>
<div class="box">
<p style="white-space: pre-wrap; font-family: Georgia, serif; line-height: 1.6;">{text}</p>
</div>
<h2>2. Statutory Rule Lifecycle Flow Diagram</h2>
<div class="box">
<pre class="mermaid">
{mermaid_code}
</pre>
</div>
<h2>3. Emitted Formal Specifications</h2>
<div class="grid">
<div class="box">
<h3>Formal Statutory AST (.ast.json)</h3>
<pre><code>{ast_json_str}</code></pre>
</div>
<div class="box">
<h3>Literate INRIA Catala (.catala_en)</h3>
<pre><code>{catala_src}</code></pre>
</div>
</div>
<script>
mermaid.initialize({{ startOnLoad: true, theme: 'dark' }});
</script>
</body>
</html>
"""
def _get_studio_html() -> str:
"""Returns the embedded single-page application for AST-CatalaGen Studio."""
return """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AST-CatalaGen Studio | MudraForge Formal Legal Engine</title>
<!-- Mermaid.js for visual rule flowcharts -->
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
<style>
:root {
--bg: #090d16;
--bg-panel: #0f172a;
--bg-card: #131d34;
--bg-code: #050811;
--border: #1e293b;
--border-accent: #0284c7;
--primary: #38bdf8;
--primary-hover: #0ea5e9;
--emerald: #10b981;
--amber: #f59e0b;
--rose: #f43f5e;
--purple: #a855f7;
--text: #f8fafc;
--text-muted: #94a3b8;
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background-color: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
/* Top Config & Brand Bar */
header {
background: #060911;
border-bottom: 1px solid var(--border);
padding: 0.65rem 1.25rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-shrink: 0;
}
.brand {
display: flex;
align-items: center;
gap: 0.75rem;
}
.brand-title {
font-size: 1.15rem;
font-weight: 800;
letter-spacing: -0.02em;
color: var(--primary);
text-transform: uppercase;
}
.brand-sub {
font-size: 0.78rem;
color: var(--text-muted);
background: #1e293b;
padding: 0.15rem 0.5rem;
border-radius: 4px;
border: 1px solid #334155;
}
.top-controls {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.badge {
display: inline-flex;
align-items: center;
gap: 0.35rem;
font-size: 0.75rem;
font-weight: 600;
padding: 0.2rem 0.6rem;
border-radius: 4px;
background: var(--bg-card);
border: 1px solid var(--border);
color: var(--text-muted);
}
.badge.green { color: var(--emerald); border-color: rgba(16, 185, 129, 0.4); }
.badge.amber { color: var(--amber); border-color: rgba(245, 158, 11, 0.4); }
.badge.blue { color: var(--primary); border-color: rgba(56, 189, 248, 0.4); }
.badge.guard { color: var(--purple); border-color: rgba(168, 85, 247, 0.4); background: rgba(168, 85, 247, 0.08); }
.btn {
background: var(--bg-card);
color: var(--text);
border: 1px solid var(--border);
padding: 0.35rem 0.75rem;
border-radius: 6px;
font-size: 0.8rem;
font-weight: 600;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 0.4rem;
transition: all 0.15s ease;
}
.btn:hover { background: #1e293b; border-color: var(--primary); }
.btn-primary {
background: #0284c7;
color: #fff;
border-color: #38bdf8;
}
.btn-primary:hover { background: #0369a1; }
.btn-emerald {
background: rgba(16, 185, 129, 0.15);
color: var(--emerald);
border-color: rgba(16, 185, 129, 0.5);
}
.btn-emerald:hover { background: rgba(16, 185, 129, 0.25); }
/* Main Layout */
.app-body {
display: flex;
flex: 1;
height: calc(100vh - 58px);
overflow: hidden;
}
/* Left Sidebar: Tasks, Presets, History */
aside {
width: 320px;
background: #0a0e1a;
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
flex-shrink: 0;
}
.sidebar-tabs {
display: flex;
border-bottom: 1px solid var(--border);
background: #060911;
}
.sidebar-tab {
flex: 1;
padding: 0.65rem;
text-align: center;
font-size: 0.8rem;
font-weight: 700;
color: var(--text-muted);
cursor: pointer;
border-bottom: 2px solid transparent;
transition: all 0.15s ease;
}
.sidebar-tab.active {
color: var(--primary);
border-bottom-color: var(--primary);
background: rgba(56, 189, 248, 0.05);
}
.sidebar-content {
flex: 1;
overflow-y: auto;
padding: 0.75rem;
}
.preset-card, .history-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.75rem;
margin-bottom: 0.6rem;
cursor: pointer;
transition: all 0.15s ease;
}
.preset-card:hover, .history-card:hover {
border-color: var(--primary);
transform: translateY(-1px);
}
.preset-title, .history-title {
font-size: 0.85rem;
font-weight: 700;
color: var(--primary);
margin-bottom: 0.25rem;
}
.preset-law {
font-size: 0.72rem;
color: var(--emerald);
margin-bottom: 0.35rem;
}
.preset-snippet, .history-snippet {
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.35;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* Central Content Area */
main {
flex: 1;
display: flex;
flex-direction: column;
height: 100%;
background: var(--bg);
overflow: hidden;
}
/* Input Workspace Header */
.input-workspace {
background: #0c1222;
border-bottom: 1px solid var(--border);
padding: 0.85rem 1.25rem;
display: flex;
flex-direction: column;
gap: 0.6rem;
flex-shrink: 0;
}
.input-header-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.field-group {
display: flex;
align-items: center;
gap: 0.5rem;
}
.field-label {
font-size: 0.75rem;
font-weight: 700;
color: var(--text-muted);
text-transform: uppercase;
}
input[type="text"], select {
background: #050811;
border: 1px solid var(--border);
color: var(--text);
padding: 0.35rem 0.6rem;
border-radius: 4px;
font-size: 0.82rem;
font-family: var(--font-mono);
outline: none;
}
input[type="text"]:focus, select:focus, textarea:focus {
border-color: var(--primary);
box-shadow: 0 0 0 1px rgba(56, 189, 248, 0.3);
}
.textarea-wrapper {
position: relative;
}
textarea {
width: 100%;
height: 95px;
min-height: 80px;
max-height: 220px;
background: #050811;
border: 1px solid var(--border);
color: #e2e8f0;
padding: 0.65rem;
border-radius: 6px;
font-family: Georgia, serif;
font-size: 0.95rem;
line-height: 1.45;
resize: vertical;
outline: none;
}
.input-actions-row {
display: flex;
align-items: center;
justify-content: space-between;
}
.input-counters {
font-size: 0.75rem;
color: var(--text-muted);
}
/* Scrollable Timeline Stream */
.timeline-stream {
flex: 1;
overflow-y: auto;
padding: 1.25rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
/* Execution Card in Stream */
.timeline-card {
background: var(--bg-panel);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
display: flex;
flex-direction: column;
overflow: hidden;
animation: fadeIn 0.25s ease-out;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
.card-top {
background: #0d1527;
border-bottom: 1px solid var(--border);
padding: 0.65rem 1rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.card-doc-info {
display: flex;
align-items: center;
gap: 0.6rem;
}
.card-doc-id {
font-size: 0.95rem;
font-weight: 800;
color: var(--primary);
font-family: var(--font-mono);
}
.card-source-panel {
padding: 0.75rem 1rem;
background: rgba(15, 23, 42, 0.6);
border-bottom: 1px solid var(--border);
font-size: 0.85rem;
line-height: 1.5;
color: #cbd5e1;
font-family: Georgia, serif;
}
/* Diagram Panel */
.diagram-panel {
background: #080d1a;
border-bottom: 1px solid var(--border);
padding: 1rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.4rem;
}
.panel-title {
font-size: 0.82rem;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--emerald);
display: flex;
align-items: center;
gap: 0.4rem;
}
.mermaid-box {
background: #040711;
border: 1px solid #1e293b;
border-radius: 6px;
padding: 1rem;
overflow-x: auto;
text-align: center;
min-height: 140px;
}
/* Dual-Column or Single-Column Output Grid */
.columns-container {
display: grid;
gap: 1px;
background: var(--border);
}
.columns-container.dual {
grid-template-columns: 1fr 1fr;
}
.columns-container.single {
grid-template-columns: 1fr;
}
.output-column {
background: var(--bg-panel);
display: flex;
flex-direction: column;
min-width: 0;
}
.column-header {
background: #0c1424;
border-bottom: 1px solid var(--border);
padding: 0.5rem 0.85rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.column-title {
font-size: 0.8rem;
font-weight: 700;
color: #93c5fd;
font-family: var(--font-mono);
}
.code-container {
background: var(--bg-code);
padding: 0.85rem;
font-family: var(--font-mono);
font-size: 0.82rem;
line-height: 1.45;
color: #7dd3fc;
overflow-x: auto;
max-height: 380px;
overflow-y: auto;
white-space: pre;
}
/* Artifacts / Direct Links Footer */
.artifacts-bar {
background: #080d19;
border-top: 1px solid var(--border);
padding: 0.6rem 1rem;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
font-size: 0.78rem;
}
.artifact-links {
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.art-link {
color: var(--primary);
text-decoration: none;
display: inline-flex;
align-items: center;
gap: 0.3rem;
font-weight: 600;
cursor: pointer;
}
.art-link:hover { text-decoration: underline; color: #fff; }
/* Welcome / Empty State Card */
.welcome-card {
background: linear-gradient(135deg, rgba(14, 165, 233, 0.08), rgba(16, 185, 129, 0.05));
border: 1px solid rgba(56, 189, 248, 0.25);
border-radius: 8px;
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.welcome-title {
font-size: 1.25rem;
font-weight: 800;
color: var(--primary);
}
.welcome-desc {
font-size: 0.88rem;
line-height: 1.5;
color: #cbd5e1;
}
.pipeline-steps {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 0.75rem;
margin-top: 0.5rem;
}
.step-box {
background: rgba(15, 23, 42, 0.8);
border: 1px solid var(--border);
border-radius: 6px;
padding: 0.75rem;
}
.step-name {
font-size: 0.8rem;
font-weight: 800;
color: var(--primary);
margin-bottom: 0.25rem;
}
.step-detail {
font-size: 0.72rem;
color: var(--text-muted);
line-height: 1.35;
}
</style>
</head>
<body>
<!-- Top Configuration and Status Bar -->
<header>
<div class="brand">
<div class="brand-title">AST-CATALA-GEN STUDIO</div>
<div class="brand-sub">MudraForge Formal Legal Engine v6.1.0</div>
</div>
<div class="top-controls">
<span class="badge green" id="badge-device">Device: CUDA (RTX 3060)</span>
<span class="badge blue" id="badge-memory">Memory: Episodic ON</span>
<span class="badge guard" id="badge-guard">isAuthorizedToDisburse: false</span>
<span class="badge amber" id="badge-regex">0 Regex Verified</span>
<button class="btn" id="btn-toggle-layout" onclick="toggleLayout()">Layout: Dual Columns</button>
</div>
</header>
<!-- Main Body Layout -->
<div class="app-body">
<!-- Left Sidebar: Tasks, Presets, History -->
<aside>
<div class="sidebar-tabs">
<div class="sidebar-tab active" id="tab-presets-btn" onclick="switchSidebarTab('presets')">Benchmark Tasks</div>
<div class="sidebar-tab" id="tab-history-btn" onclick="switchSidebarTab('history')">Run History (<span id="history-badge">0</span>)</div>
</div>
<div class="sidebar-content" id="sidebar-content">
<!-- Rendered by JS -->
</div>
</aside>
<!-- Central Workspace & Timeline Stream -->
<main>
<!-- Input Workspace Area -->
<section class="input-workspace">
<div class="input-header-row">
<div class="field-group">
<span class="field-label">Document ID:</span>
<input type="text" id="input-doc-id" value="US_IRC_68_B" style="width: 170px;" />
</div>
<div class="field-group">
<span class="field-label">Stage Range:</span>
<select id="select-start-stage">
<option value="stage1" selected>Start: Stage 1 (Raw Text)</option>
<option value="stage1_5">Start: Stage 1.5 (Operands)</option>
<option value="stage2">Start: Stage 2 (Clauses)</option>
</select>
<select id="select-end-stage">
<option value="stage2b" selected>End: Stage 2B + Stage 3 Emitter</option>
<option value="stage2">End: Stage 2 Scopes</option>
<option value="stage1_5">End: Stage 1.5 Operands</option>
</select>
</div>
<div class="field-group">
<label style="font-size: 0.75rem; font-weight: 600; color: var(--emerald); cursor: pointer; display: flex; align-items: center; gap: 0.35rem;">
<input type="checkbox" id="check-memory" checked /> Continual Memory
</label>
</div>
</div>
<div class="textarea-wrapper">
<textarea id="input-statute-text" placeholder="Enter or paste statutory text here (e.g. US Internal Revenue Code, India Tax Act, GST rules)..."></textarea>
</div>
<div class="input-actions-row">
<div class="input-counters">
<span id="char-count">0 chars</span> | <span id="word-count">0 words</span> | <span id="token-est">~0 tokens</span>
</div>
<div style="display: flex; gap: 0.5rem;">
<button class="btn" onclick="clearInput()">Clear</button>
<button class="btn" onclick="loadRandomPreset()">Load Random Preset</button>
<button class="btn btn-primary" id="btn-compile" onclick="compileStatute()">
Compile to AST & Catala (Ctrl+Enter)
</button>
</div>
</div>
</section>
<!-- Scrollable Execution Timeline Stream -->
<section class="timeline-stream" id="timeline-stream">
<!-- Initial Welcome Card -->
<div class="welcome-card" id="welcome-card">
<div class="welcome-title">Welcome to AST-CatalaGen Studio</div>
<div class="welcome-desc">
This interactive studio compiles raw statutory text into formal, deterministic <strong>Statutory AST (.ast.json)</strong>,
executable <strong>Literate INRIA Catala (.catala_en)</strong> specifications, and visual <strong>Rule Lifecycle Flowcharts</strong>
via the MudraForge 4-stage neural pipeline.
</div>
<div class="pipeline-steps">
<div class="step-box">
<div class="step-name">Stage 1: Non-Operand Atoms</div>
<div class="step-detail">37-tag Hierarchical Tree + Fast Memory M1 + CRF (MONEY, RATE, DATE, XREF, ACTOR).</div>
</div>
<div class="step-box">
<div class="step-name">Stage 1.5: Catala Operands</div>
<div class="step-detail">17-tag Leaf Router + Continual Learning (Leaves, Entities, Metrics, Dates).</div>
</div>
<div class="step-box">
<div class="step-name">Stage 2: Clause Scopes</div>
<div class="step-detail">COND, EXCEPTION, RULE_EFFECT, INLINE_DEF boundaries + Fast Memory M2.</div>
</div>
<div class="step-box">
<div class="step-name">Stage 3: AST & Catala Emitter</div>
<div class="step-detail">Reflexion Critic, case tables, multi-slab brackets, min combinators, and statutory guard.</div>
</div>
</div>
</div>
</section>
</main>
</div>
<script>
mermaid.initialize({
startOnLoad: false,
theme: 'dark',
themeVariables: {
darkMode: true,
background: '#040711',
primaryColor: '#0f172a',
primaryTextColor: '#f8fafc',
primaryBorderColor: '#38bdf8',
lineColor: '#64748b'
}
});
let currentLayout = 'dual'; // 'dual' or 'single'
let currentTab = 'presets'; // 'presets' or 'history'
let presetsData = [];
let historyData = [];
// Initialize Studio
window.addEventListener('DOMContentLoaded', async () => {
await loadPresets();
await loadHistory();
setupInputListeners();
// Preload first preset
if (presetsData.length > 0) {
selectPreset(presetsData[4].id); // IRC 68(b)
}
});
function setupInputListeners() {
const txt = document.getElementById('input-statute-text');
txt.addEventListener('input', updateCounters);
txt.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
compileStatute();
}
});
updateCounters();
}
function updateCounters() {
const val = document.getElementById('input-statute-text').value;
const chars = val.length;
const words = val.trim() ? val.trim().split(/\s+/).length : 0;
const tokens = Math.round(words * 1.3);
document.getElementById('char-count').innerText = `${chars} chars`;
document.getElementById('word-count').innerText = `${words} words`;
document.getElementById('token-est').innerText = `~${tokens} tokens`;
}
async function loadPresets() {
try {
const resp = await fetch('/api/presets');
presetsData = await resp.json();
renderPresets();
} catch (e) {
console.error('Failed to load presets:', e);
}
}
async function loadHistory() {
try {
const resp = await fetch('/api/history');
historyData = await resp.json();
document.getElementById('history-badge').innerText = historyData.length;
if (currentTab === 'history') renderHistory();
} catch (e) {
console.error('Failed to load history:', e);
}
}
function switchSidebarTab(tab) {
currentTab = tab;
document.getElementById('tab-presets-btn').classList.toggle('active', tab === 'presets');
document.getElementById('tab-history-btn').classList.toggle('active', tab === 'history');
if (tab === 'presets') renderPresets();
else renderHistory();
}
function renderPresets() {
const container = document.getElementById('sidebar-content');
container.innerHTML = presetsData.map(p => `
<div class="preset-card" onclick="selectPreset('${p.id}')">
<div class="preset-title">${p.id}</div>
<div class="preset-law">${p.title}</div>
<div class="preset-snippet">${p.text}</div>
</div>
`).join('');
}
function renderHistory() {
const container = document.getElementById('sidebar-content');
if (historyData.length === 0) {
container.innerHTML = '<div style="color: var(--text-muted); font-size: 0.8rem; padding: 1rem; text-align: center;">No compilations yet. Run a statute to see history.</div>';
return;
}
container.innerHTML = historyData.map(h => `
<div class="history-card" onclick="scrollToCard('${h.run_id}')">
<div class="history-title">${h.doc_id} (${h.latency_ms} ms)</div>
<div style="font-size: 0.7rem; color: var(--emerald);">${h.timestamp_utc || 'just now'}</div>
<div class="history-snippet">${h.text}</div>
</div>
`).join('');
}
function selectPreset(id) {
const p = presetsData.find(x => x.id === id);
if (!p) return;
document.getElementById('input-doc-id').value = p.id;
document.getElementById('input-statute-text').value = p.text;
updateCounters();
}
function loadRandomPreset() {
if (presetsData.length === 0) return;
const idx = Math.floor(Math.random() * presetsData.length);
selectPreset(presetsData[idx].id);
}
function clearInput() {
document.getElementById('input-statute-text').value = '';
updateCounters();
}
function toggleLayout() {
currentLayout = (currentLayout === 'dual') ? 'single' : 'dual';
document.getElementById('btn-toggle-layout').innerText = `Layout: ${currentLayout === 'dual' ? 'Dual Columns' : 'Single Column'}`;
document.querySelectorAll('.columns-container').forEach(el => {
el.className = `columns-container ${currentLayout}`;
});
}
async function compileStatute() {
const text = document.getElementById('input-statute-text').value.trim();
const doc_id = document.getElementById('input-doc-id').value.trim() || 'STATUTE_001';
const start_stage = document.getElementById('select-start-stage').value;
const end_stage = document.getElementById('select-end-stage').value;
const use_memory = document.getElementById('check-memory').checked;
if (!text) {
alert('Please enter statutory text to compile.');
return;
}
const btn = document.getElementById('btn-compile');
const originalText = btn.innerText;
btn.innerText = 'Compiling Neural Pipeline...';
btn.disabled = true;
try {
const resp = await fetch('/api/compile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text,
doc_id,
start_stage,
end_stage,
use_memory,
})
});
if (!resp.ok) {
const err = await resp.json();
alert(`Compilation failed: ${err.error || resp.statusText}`);
return;
}
const data = await resp.json();
appendCardToStream(data);
await loadHistory();
} catch (exc) {
console.error('Error during compilation:', exc);
alert(`Compilation error: ${exc.message}`);
} finally {
btn.innerText = originalText;
btn.disabled = false;
}
}
function appendCardToStream(data) {
const stream = document.getElementById('timeline-stream');
const card = document.createElement('div');
card.className = 'timeline-card';
card.id = `card-${data.run_id}`;
const astStr = JSON.stringify(data.ast, null, 2);
const mermaidId = `mermaid-${data.run_id}`;
card.innerHTML = `
<div class="card-top">
<div class="card-doc-info">
<span class="card-doc-id">${data.doc_id}</span>
<span class="badge blue">Run: ${data.run_id}</span>
<span class="badge green">${data.latency_ms} ms</span>
<span class="badge amber">${data.token_count} tokens</span>
<span class="badge guard">${data.statutory_guard}</span>
</div>
<div style="display: flex; gap: 0.4rem;">
<button class="btn" onclick="openArtifact('${data.written_artifacts?.html_report}')">View HTML/PDF Report</button>
<button class="btn" onclick="openArtifact('${data.written_artifacts?.ast_json}')">Open .ast.json</button>
<button class="btn" onclick="openArtifact('${data.written_artifacts?.catala_en}')">Open .catala_en</button>
</div>
</div>
<div class="card-source-panel">
<strong>Statutory Source Text:</strong><br/>
${escapeHtml(data.text)}
</div>
<!-- Rule Lifecycle Diagram Panel -->
<div class="diagram-panel">
<div class="panel-header">
<div class="panel-title">
Top-to-Bottom Statutory Rule Lifecycle Flowchart
</div>
<button class="btn" onclick="copyText('${escapeAttr(data.diagram?.mermaid || '')}')">Copy Mermaid</button>
</div>
<div class="mermaid-box" id="${mermaidId}">
<pre class="mermaid">${data.diagram?.mermaid || ''}</pre>
</div>
</div>
<!-- Dual / Single Column Outputs -->
<div class="columns-container ${currentLayout}">
<div class="output-column">
<div class="column-header">
<div class="column-title">Formal Statutory AST (.ast.json)</div>
<div style="display: flex; gap: 0.35rem;">
<button class="btn" onclick="copyText('${escapeAttr(astStr)}')">Copy JSON</button>
<button class="btn" onclick="downloadFile('${data.doc_id}.ast.json', '${escapeAttr(astStr)}')">Download</button>
</div>
</div>
<div class="code-container">${escapeHtml(astStr)}</div>
</div>
<div class="output-column">
<div class="column-header">
<div class="column-title">Literate INRIA Catala (.catala_en)</div>
<div style="display: flex; gap: 0.35rem;">
<button class="btn" onclick="copyText('${escapeAttr(data.catala || '')}')">Copy Catala</button>
<button class="btn" onclick="downloadFile('${data.doc_id}.catala_en', '${escapeAttr(data.catala || '')}')">Download</button>
</div>
</div>
<div class="code-container" style="color: #a7f3d0;">${escapeHtml(data.catala || '')}</div>
</div>
</div>
<!-- Direct Artifacts Links -->
<div class="artifacts-bar">
<div class="artifact-links">
<span>Disk Artifacts:</span>
<span class="art-link" onclick="openArtifact('${data.written_artifacts?.ast_json}')">
📄 ${data.written_artifacts?.ast_json || ''}
</span>
<span class="art-link" onclick="openArtifact('${data.written_artifacts?.catala_en}')">
📄 ${data.written_artifacts?.catala_en || ''}
</span>
</div>
<div style="color: var(--text-muted); font-size: 0.72rem;">
Click links to open natively in cursor/OS.
</div>
</div>
`;
stream.insertBefore(card, stream.children[1] || null);
// Render Mermaid diagram
try {
mermaid.run({
nodes: card.querySelectorAll('.mermaid')
});
} catch (mErr) {
console.warn('Mermaid render issue:', mErr);
}
card.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function scrollToCard(run_id) {
const el = document.getElementById(`card-${run_id}`);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
async function openArtifact(path) {
if (!path) return;
try {
const resp = await fetch(`/api/open?file=${encodeURIComponent(path)}`);
const json = await resp.json();
if (json.error) alert(json.error);
} catch (e) {
alert(`Failed to open artifact: ${e.message}`);
}
}
function copyText(str) {
navigator.clipboard.writeText(str).then(() => {
alert('Copied to clipboard.');
}).catch(err => {
console.error('Copy failed:', err);
});
}
function downloadFile(filename, content) {
const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
function escapeHtml(text) {
if (!text) return '';
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function escapeAttr(text) {
if (!text) return '';
return text
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/"/g, '"')
.replace(/\\n/g, '\\n')
.replace(/\\r/g, '');
}
</script>
</body>
</html>
"""
def run_studio_server(
host: str = "127.0.0.1",
port: int = DEFAULT_PORT,
auto_open: bool = True,
pipeline: MudraForgeCanonicalPipeline | None = None,
) -> None:
"""
Starts the threaded AST-CatalaGen Studio web server and optionally opens
the browser automatically.
"""
StudioRequestHandler.pipeline_ref = pipeline
server_address = (host, port)
max_retries = 10
httpd: ThreadingHTTPServer | None = None
for p in range(port, port + max_retries):
try:
httpd = ThreadingHTTPServer((host, p), StudioRequestHandler)
port = p
break
except OSError:
continue
if httpd is None:
raise RuntimeError(f"Could not bind to {host} on ports {port}-{port + max_retries}")
url = f"http://{host}:{port}/"
print("=" * 80)
print(f"AST-CATALA-GEN STUDIO v6.1.0 (PROD)")
print(f"Server Running at : {url}")
print(f"Statutory Guard : isAuthorizedToDisburse: false")
print(f"Zero-Regex Safety : 100% Audited")
print("=" * 80)
if auto_open:
try:
webbrowser.open(url)
except Exception:
pass
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\n[Studio] Shutting down server gracefully...")
finally:
httpd.server_close()
|