Spaces:
Running
Running
File size: 52,796 Bytes
7eeb78f | 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 | /* ==========================================================================
BeamBridge v2 Frontend Controller (Concise · Zero Emojis · Cohesive Palette)
========================================================================== */
function safeStorageGet(k, fallback) {
try {
return window.sessionStorage.getItem(k) || fallback;
} catch {
return fallback;
}
}
function safeStorageSet(k, v) {
try {
window.sessionStorage.setItem(k, v);
} catch {
/* sandboxed iframe fallback */
}
}
const STATE = {
lang: "en",
activeView: "dashboard",
selectedRepoId: "py_moneyed",
bootstrap: null,
repoBundles: {},
allParityCases: [],
provider: safeStorageGet("bb_provider", "openrouter"),
apiKey: safeStorageGet("bb_api_key", ""),
};
const I18N = {
en: {
nav_dashboard: "Dashboard",
nav_modernizer: "Modernizer",
nav_playground: "MCP Playground",
nav_parity: "Parity Suite",
nav_finops: "FinOps",
btn_engine: "Engine",
btn_connect_mcp: "Setup & /mcp",
hero_title: "Beam-1.0 Modernization Hub",
cap_parity: "Parity",
cap_tokens: "Cost Saved",
cap_naive_drift: "RAG Drift",
cap_regressions: "Regressions",
kpi_tests: "Verified Tests",
kpi_tools: "MCP Tools",
kpi_savings: "TCO Saved",
card_pipeline: "Pipeline",
card_estates: "GitHub Repositories",
card_matrix: "Parity Matrix",
card_finops_curve: "Inference Spend",
card_composition: "Cost Ratio",
guide_s1_title: "Paste a setup prompt into your AI",
guide_s1_desc: "Select your AI client and copy its prompt to connect BeamBridge's verified /mcp gateway.",
guide_paste_lbl: "You'll paste this",
guide_s2_title: "Verify SHA-256 parity",
guide_s2_desc: "Every tool passes 160/160 differential checks against its original GitHub library before going live.",
guide_master_lbl: "Master SHA-256:",
guide_s3_title: "Modernize or inspect live",
guide_s3_desc: "Clone any public GitHub repo in Modernizer Studio or compare outputs side-by-side in the Playground.",
guide_s4_title: "Run a verified task",
guide_s4_desc: "Click an example to copy it and test it live in the Playground.",
},
ar: {
nav_dashboard: "الرئيسية",
nav_modernizer: "المحوّل",
nav_playground: "مختبر MCP",
nav_parity: "الفحوصات",
nav_finops: "التكلفة",
btn_engine: "المحرك",
btn_connect_mcp: "الربط و /mcp",
hero_title: "منصة تحديث الأنظمة بـ Beam-1.0",
cap_parity: "التطابق",
cap_tokens: "وفر التكلفة",
cap_naive_drift: "أخطاء RAG",
cap_regressions: "تراجعات",
kpi_tests: "اختبار موثق",
kpi_tools: "أداة MCP",
kpi_savings: "وفر سنوي",
card_pipeline: "مراحل التحويل",
card_estates: "مستودعات GitHub",
card_matrix: "مصفوفة التطابق",
card_finops_curve: "تكلفة الاستدلال",
card_composition: "نسبة التوفير",
guide_s1_title: "الصق أمر الربط في وكيلك الذكي",
guide_s1_desc: "اختر المنصة وانسخ الأمر الجاهز لربط بوابة /mcp الموثقة.",
guide_paste_lbl: "النص الجاهز للنسخ",
guide_s2_title: "شهادات التطابق SHA-256",
guide_s2_desc: "جميع الأدوات تجتاز 160/160 فحصاً تفاضلياً ضد مكتبات GitHub الأصلية.",
guide_master_lbl: "البصمة الرئيسية:",
guide_s3_title: "حدّث مستودعك أو اختبره مباشرة",
guide_s3_desc: "استنسخ أي مستودع عام في المحوّل أو قارن المخرجات مباشرة في المختبر.",
guide_s4_title: "جرّب عملية موثقة",
guide_s4_desc: "اضغط على أي مثال لنسخه وتشغيله فوراً في المختبر.",
},
};
const REPO_CODES = {
py_moneyed: "MN",
price_parser: "PR",
schwifty: "SW",
python_stdnum: "ST",
};
const REAL_EDGE_PRESETS = {
py_moneyed: {
inspect_and_round_money: [
{ label: "USD Whole Round", args: { amount_str: "19.50", currency_code: "USD", ndigits: null } },
{ label: "BHD 3-Decimal", args: { amount_str: "45.6785", currency_code: "BHD", ndigits: 3 } },
{ label: "JPY 0-Decimal", args: { amount_str: "1500.9", currency_code: "JPY", ndigits: 0 } },
],
pro_rata_subunit_split: [
{ label: "$100 [1,1,1] Split", args: { amount_str: "100.00", currency_code: "USD", weights: [1, 1, 1] } },
{ label: "KWD 50 [5,3,2]", args: { amount_str: "50.000", currency_code: "KWD", weights: [5, 3, 2] } },
],
convert_and_sum_ledger: [
{
label: "USD + EUR → SAR",
args: {
entries: [{ amount: "100.00", currency: "USD" }, { amount: "250.00", currency: "EUR" }],
target_currency: "SAR",
rates_to_target: { USD: "3.75", EUR: "4.0625" },
},
},
],
},
price_parser: {
parse_procurement_price: [
{ label: "EU 1.299,95 €", args: { raw_text: "Total: 1.299,95 € (incl. VAT)", currency_hint: null, decimal_separator: null } },
{ label: "CHF 1'250.50", args: { raw_text: "CHF 1'250.50", currency_hint: null, decimal_separator: null } },
{ label: "Zero ('Free!')", args: { raw_text: "Free!", currency_hint: "USD", decimal_separator: null } },
],
compute_invoice_line_quote: [
{ label: "4× CHF 1'250.50 − 200", args: { raw_unit_price: "CHF 1'250.50", quantity: 4, raw_discount: "CHF 200.00" } },
],
audit_price_feed_batch: [
{ label: "Mixed Feed", args: { raw_items: ["$19.99", "€ 30,01", "Free!", "Contact sales"] } },
],
},
schwifty: {
validate_and_decompose_iban: [
{ label: "UK NatWest IBAN", args: { raw_iban: "GB29 NWBK 6016 1331 9268 19" } },
{ label: "FR BNP IBAN", args: { raw_iban: "FR76 3000 6000 0112 3456 7890 189" } },
{ label: "Invalid Checksum", args: { raw_iban: "GB99 NWBK 6016 1331 9268 19" } },
],
generate_iban_from_bban: [
{ label: "DE BBAN → IBAN", args: { country_code: "DE", bank_code: "37040044", account_code: "0532013000" } },
],
inspect_swift_bic: [
{ label: "DEUTDEFF500", args: { raw_bic: "DEUTDEFF500" } },
{ label: "Invalid Country", args: { raw_bic: "DEUTXXFF" } },
],
},
python_stdnum: {
validate_securities_id: [
{ label: "ISIN US0378331005", args: { scheme: "ISIN", raw_code: "US0378331005" } },
{ label: "SEDOL 0263494", args: { scheme: "SEDOL", raw_code: "0263494" } },
{ label: "FIGI BBG000BLNNH6", args: { scheme: "FIGI", raw_code: "BBG000BLNNH6" } },
],
validate_us_routing_or_ein: [
{ label: "JPM RTN 021000021", args: { id_type: "RTN", raw_number: "021000021" } },
{ label: "Invalid EIN 07-", args: { id_type: "EIN", raw_number: "07-1234567" } },
],
validate_eu_vat_number: [
{ label: "DE136695976", args: { raw_vat: "DE 136 695 976" } },
{ label: "FR40303265045", args: { raw_vat: "FR 40 303 265 045" } },
],
},
};
function fmtCurrency(num) {
const n = Number(num || 0);
if (n >= 1_000_000) return "$" + (n / 1_000_000).toFixed(2) + "M";
return "$" + Math.round(n).toLocaleString("en-US");
}
function fmtUsdExact(num) {
return "$" + Math.round(Number(num || 0)).toLocaleString("en-US");
}
function escapeHtml(str) {
return String(str ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
function switchView(viewId) {
STATE.activeView = viewId;
document.querySelectorAll(".nav-tab").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.view === viewId);
});
document.querySelectorAll(".view-section").forEach((sec) => {
sec.classList.toggle("active", sec.id === `view-${viewId}`);
});
}
function applyLanguage() {
const dict = I18N[STATE.lang];
document.getElementById("appShell").setAttribute("dir", STATE.lang === "ar" ? "rtl" : "ltr");
document.getElementById("langToggleBtn").textContent = STATE.lang === "ar" ? "EN" : "ع";
document.querySelectorAll("[data-i18n]").forEach((el) => {
const k = el.getAttribute("data-i18n");
if (dict[k]) el.textContent = dict[k];
});
}
/* ==========================================================================
Dashboard Renderers
========================================================================== */
function renderEstatesTable(filterText = "") {
if (!STATE.bootstrap) return;
const tbody = document.getElementById("estatesTableBody");
const q = filterText.trim().toLowerCase();
const rows = STATE.bootstrap.repositories.filter(
(r) =>
!q ||
r.name.toLowerCase().includes(q) ||
r.git_sha.toLowerCase().includes(q) ||
r.sector.toLowerCase().includes(q)
);
tbody.innerHTML = rows
.map((r) => {
const isSel = r.id === STATE.selectedRepoId;
const code = REPO_CODES[r.id] || "GH";
const v = r.verification;
return `
<tr class="${isSel ? "selected-row" : ""}" data-repoid="${r.id}">
<td><span class="row-check">•</span></td>
<td>
<div class="estate-name-cell">
<span class="sector-avatar">${code}</span>
<div>
<div style="font-weight:500;color:var(--ink-900);">${escapeHtml(r.name)} <code style="font-size:11px;color:var(--ink-500);">@${escapeHtml(r.git_sha)}</code></div>
<div style="font-size:11px;color:var(--ink-500);">${r.ast.estimated_beam_tokens.toLocaleString()} BPE tokens</div>
</div>
</div>
</td>
<td style="color:var(--ink-700);font-size:12px;">${escapeHtml(r.sector)}</td>
<td style="font-weight:500;font-size:12.5px;">
<span style="color:var(--ink-500);">${v.chunked_rag_parity_pct}%</span> → <strong style="color:var(--ink-900);">${v.beam_1m_parity_pct}%</strong>
</td>
<td>
<span class="status-pill grey">
<span class="dot"></span>${v.beam_1m_passed}/${v.total_cases}
</span>
</td>
</tr>
`;
})
.join("");
tbody.querySelectorAll("tr[data-repoid]").forEach((tr) => {
tr.addEventListener("click", async () => {
STATE.selectedRepoId = tr.dataset.repoid;
renderEstatesTable(document.getElementById("estateSearchInput").value);
document.getElementById("modRepoSelect").value = STATE.selectedRepoId;
document.getElementById("pgRepoSelect").value = STATE.selectedRepoId;
document.getElementById("liveGithubBox").style.display = "none";
await loadRepoBundle(STATE.selectedRepoId);
});
});
}
async function renderMatrixDots() {
await ensureAllBundlesLoaded();
const grid = document.getElementById("matrixDotGrid");
const hoverBar = document.getElementById("matrixHoverText");
const cliffs = STATE.allParityCases.filter((c) => !c.chunked_rag_parity);
const normals = STATE.allParityCases.filter((c) => c.chunked_rag_parity);
const sampled = [...cliffs.slice(0, 46), ...normals.slice(0, 26)].slice(0, 72);
grid.innerHTML = sampled
.map((d, idx) => {
const cls = !d.chunked_rag_parity ? "gold-cliff" : idx % 3 === 0 ? "verified-soft" : "";
return `<div class="matrix-dot ${cls}" data-idx="${idx}" title="${escapeHtml(d.case_id)}: ${escapeHtml(d.label)}"></div>`;
})
.join("");
grid.querySelectorAll(".matrix-dot").forEach((dot) => {
const item = sampled[Number(dot.dataset.idx)];
dot.addEventListener("mouseenter", () => {
const tag = !item.chunked_rag_parity ? "RAG Failed" : "Verified";
hoverBar.textContent = `${item.case_id} · ${item.label} (${item.mcp_latency_us} μs) — ${tag}`;
});
dot.addEventListener("click", () => {
document.getElementById("parityRepoFilter").value = item.repo_id;
switchView("parity");
renderParityTable();
});
});
}
function buildSmoothSvgPath(points) {
if (!points.length) return "";
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[i];
const p1 = points[i + 1];
const cx = (p0.x + p1.x) / 2;
d += ` C ${cx.toFixed(1)} ${p0.y.toFixed(1)}, ${cx.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
}
return d;
}
function renderFinOpsCurve(finops) {
const container = document.getElementById("finopsChartContainer");
const months = ["M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "M10", "M11", "M12"];
const rawSeries = finops.cumulative_monthly_series;
const qwenAnnual = finops.annual_inference_cost_usd.qwen_3_8_2_4t || 42000;
const beamAnnual = finops.annual_inference_cost_usd.beam_1_0_with_ast_pack || 5800;
const series = rawSeries
? rawSeries.map((r) => ({
month: r.month,
frontier_usd: r.qwen_cumulative_usd,
beam_usd: r.beam_cumulative_usd,
}))
: months.map((m, i) => ({
month: m,
frontier_usd: (qwenAnnual / 12) * (i + 1),
beam_usd: (beamAnnual / 12) * (i + 1),
}));
const W = 580;
const H = 180;
const padL = 46;
const padR = 18;
const padT = 26;
const padB = 30;
const plotW = W - padL - padR;
const plotH = H - padT - padB;
const maxVal = Math.max(...series.map((s) => s.frontier_usd), 100) * 1.16;
const frontPts = series.map((s, i) => ({
x: padL + (i / (series.length - 1)) * plotW,
y: padT + plotH - (s.frontier_usd / maxVal) * plotH,
}));
const beamPts = series.map((s, i) => ({
x: padL + (i / (series.length - 1)) * plotW,
y: padT + plotH - (s.beam_usd / maxVal) * plotH,
}));
const hi = 8;
const hiFront = frontPts[hi];
const hiBeam = beamPts[hi];
const savedPct = finops.annual_inference_cost_usd.token_cost_reduction_vs_qwen38_pct || 96.8;
const yTicks = [0.25, 0.55, 0.85].map((f) => ({
y: padT + plotH - f * plotH,
lbl: "$" + ((maxVal * f) / 1000).toFixed(0) + "k",
}));
container.innerHTML = `
<svg viewBox="0 0 ${W} ${H}" width="100%" height="100%" preserveAspectRatio="none">
${yTicks
.map(
(t) => `
<line x1="${padL}" y1="${t.y.toFixed(1)}" x2="${W - padR}" y2="${t.y.toFixed(1)}" stroke="rgba(36,36,38,0.06)" stroke-width="1"/>
<text x="4" y="${(t.y + 4).toFixed(1)}" fill="#9c9ca1" font-size="10" font-family="inherit">${t.lbl}</text>
`
)
.join("")}
<path d="${buildSmoothSvgPath(frontPts)}" fill="none" stroke="#242426" stroke-width="1.8" stroke-dasharray="4 4" />
<path d="${buildSmoothSvgPath(beamPts)}" fill="none" stroke="#e2ba36" stroke-width="2.4" />
<line x1="${hiFront.x.toFixed(1)}" y1="${hiFront.y.toFixed(1)}" x2="${hiFront.x.toFixed(1)}" y2="${H - padB}" stroke="#242426" stroke-width="1.2" />
<circle cx="${hiFront.x.toFixed(1)}" cy="${hiFront.y.toFixed(1)}" r="4" fill="#242426" />
<circle cx="${hiBeam.x.toFixed(1)}" cy="${hiBeam.y.toFixed(1)}" r="4.5" fill="#f5d665" stroke="#242426" stroke-width="1.3" />
<g transform="translate(${(hiFront.x - 46).toFixed(1)}, ${Math.max(4, hiFront.y - 30).toFixed(1)})">
<rect x="0" y="0" width="92" height="24" rx="12" fill="#242426" />
<text x="46" y="15.5" text-anchor="middle" fill="#ffffff" font-size="10.5" font-weight="500" font-family="inherit">−${savedPct}% Cost</text>
</g>
${series
.map((s, i) => {
const x = padL + (i / (series.length - 1)) * plotW;
const isPill = s.month === "M9";
return `
${isPill ? `<rect x="${(x - 15).toFixed(1)}" y="${H - 22}" width="30" height="18" rx="9" fill="rgba(255,255,255,0.92)" />` : ""}
<text x="${x.toFixed(1)}" y="${H - 9}" text-anchor="middle" fill="${isPill ? "#222224" : "#8b8b90"}" font-size="10.5" font-weight="${isPill ? "600" : "400"}" font-family="inherit">${s.month}</text>
`;
})
.join("")}
</svg>
`;
}
/* ==========================================================================
Modernizer Studio & Live GitHub Cloner
========================================================================== */
async function loadRepoBundle(repoId) {
if (!STATE.repoBundles[repoId]) {
const resp = await fetch(`/api/repos/${repoId}`);
STATE.repoBundles[repoId] = await resp.json();
}
const bundle = STATE.repoBundles[repoId];
renderModernizerOutput(bundle);
populatePlaygroundTools(repoId);
return bundle;
}
function renderModernizerOutput(bundle, liveSynthesis = null) {
const cat = bundle.catalog || {};
const ast = bundle.ast || {};
const ver = bundle.verification || {};
const audit = ver.synthesis_audit || {};
const packLine =
Number(ast.ast_finops_compression_pct || 0) > 0
? `${Number(ast.raw_disk_beam_tokens || 0).toLocaleString()} → <strong>${Number(ast.estimated_beam_tokens || 0).toLocaleString()} BPE tok</strong> (−${ast.ast_finops_compression_pct}%)`
: `<strong>${Number(ast.estimated_beam_tokens || 0).toLocaleString()} BPE tok</strong> (${ast.file_count || 0} files)`;
document.getElementById("modTelemetryBox").innerHTML = `
<div><strong>Repo:</strong> <a href="${escapeHtml(cat.github_url)}" target="_blank" rel="noreferrer" style="color:var(--ink-900);">${escapeHtml(cat.name)}</a> <code>@${escapeHtml(cat.git_sha)}</code></div>
<div><strong>Tokens:</strong> ${packLine}</div>
<div><strong>Parity:</strong> <strong>${ver.beam_1m_passed}/${ver.total_cases} (${ver.beam_1m_parity_pct}%)</strong> vs RAG ${ver.chunked_rag_parity_pct}%</div>
<div><strong>OpenRouter IDs:</strong> <code>${escapeHtml((audit.whole_repo_request_ids || []).join(", "))}</code></div>
`;
const turnsHtml = (audit.whole_repo_turns || [])
.map(
(t) => `
<div class="rule-card">
<div class="rule-card-head">
<strong style="font-size:12.5px;">Turn ${t.turn} · <code>${escapeHtml(t.model)}</code></strong>
<span class="status-pill ${t.passed === t.total ? "grey" : "amber"}"><span class="dot"></span>${t.passed}/${t.total} (${t.pass_rate_pct}%)</span>
</div>
<div style="font-size:11.5px;color:var(--ink-500);">
ID: <code>${escapeHtml(t.request_id)}</code> · ${(t.latency_ms / 1000).toFixed(1)}s · ${t.usage.total_tokens.toLocaleString()} tok · $${Number(t.usage.cost_usd || 0).toFixed(5)}
</div>
</div>
`
)
.join("");
const liveBanner = liveSynthesis
? `<div class="rule-card" style="background:var(--gold-soft);border-color:var(--gold);font-size:12px;">
<strong>Synthesis (${escapeHtml(liveSynthesis.mode)}):</strong> <code>${escapeHtml(liveSynthesis.model)}</code> · <code>${escapeHtml((liveSynthesis.request_ids || []).join(", "))}</code> · ${liveSynthesis.latency_ms} ms
</div>`
: "";
const reasoningTxt = (liveSynthesis && liveSynthesis.reasoning_content) || bundle.recorded_reasoning_trace || "";
document.getElementById("modTabRules").innerHTML = `
${liveBanner}
<div class="rule-card" style="background:#242426;color:#fff;border-color:#242426;">
<div class="rule-card-head">
<strong style="font-size:12px;color:var(--gold);">Reasoning Trace</strong>
<span style="font-size:11px;color:rgba(255,255,255,0.55);">SHA-256: ${escapeHtml((ver.certificate_sha256 || "").slice(0, 12))}…</span>
</div>
<div style="font-family:var(--font-mono);font-size:11.5px;line-height:1.55;white-space:pre-wrap;color:rgba(255,255,255,0.86);max-height:220px;overflow-y:auto;">${escapeHtml(reasoningTxt)}</div>
</div>
<div style="margin-top:10px;">${turnsHtml}</div>
`;
document.getElementById("modernMcpCodePre").textContent =
(liveSynthesis && liveSynthesis.synthesized_code) || bundle.modernized_mcp_code || "";
const packedStr = Object.entries(bundle.legacy_files || {})
.map(([fname, src]) => `/* === ${fname} === */\n${src}`)
.join("\n\n");
document.getElementById("legacyPackedCodePre").textContent = packedStr;
}
function renderLiveGithubCloneReport(ghReport) {
document.getElementById("modTelemetryBox").innerHTML = `
<div><strong>Cloned:</strong> <a href="${escapeHtml(ghReport.github_url)}" target="_blank" rel="noreferrer" style="color:var(--ink-900);">${escapeHtml(ghReport.repo)}</a> <code>@${escapeHtml(ghReport.git_sha)}</code></div>
<div><strong>Files:</strong> ${ghReport.files_analyzed} / ${ghReport.total_py_files_discovered} .py</div>
<div><strong>Beam-1.0 Tokens:</strong> <strong>${ghReport.exact_beam_bpe_tokens.toLocaleString()}</strong> (${ghReport.beam_1m_utilization_pct}% of 1M)</div>
<div><strong>Single-Pass Cost:</strong> <strong>$${ghReport.estimated_beam_single_pass_usd}</strong> (${ghReport.finops_cost_advantage_x}x cheaper)</div>
`;
document.getElementById("modTabRules").innerHTML = `
<div class="rule-card" style="background:var(--gold-soft);border-color:var(--gold);">
<strong>Cloned ${escapeHtml(ghReport.repo)}@${escapeHtml(ghReport.git_sha)}</strong> — ${ghReport.total_loc.toLocaleString()} LOC · ${ghReport.total_functions} functions · ${ghReport.cross_file_edge_count} cross-file edges.
</div>
${(ghReport.top_files || [])
.map(
(f) => `
<div class="rule-card">
<div class="rule-card-head">
<strong style="font-size:12px;"><code>${escapeHtml(f.file)}</code></strong>
<span class="status-pill grey">${f.estimated_tokens.toLocaleString()} tok</span>
</div>
<div style="font-size:11.5px;color:var(--ink-500);">${f.loc} LOC · ${f.function_count} functions</div>
</div>
`
)
.join("")}
`;
}
/* ==========================================================================
MCP Playground
========================================================================== */
function populatePlaygroundTools(repoId) {
const bundle = STATE.repoBundles[repoId];
if (!bundle) return;
const tools = bundle.catalog.mcp_tools || [];
const toolSelect = document.getElementById("pgToolSelect");
toolSelect.innerHTML = tools
.map((t) => `<option value="${t.name}">${t.name}</option>`)
.join("");
if (tools.length) renderPlaygroundForm(repoId, tools[0].name);
}
function renderPlaygroundForm(repoId, toolName, overrideArgs = null) {
const bundle = STATE.repoBundles[repoId];
if (!bundle) return;
const toolMeta = (bundle.catalog.mcp_tools || []).find((t) => t.name === toolName) || bundle.catalog.mcp_tools[0];
const sample = overrideArgs || toolMeta.sample_args || {};
const presets = (REAL_EDGE_PRESETS[repoId] && REAL_EDGE_PRESETS[repoId][toolMeta.name]) || [];
const presetsBar = document.getElementById("pgPresetsBar");
presetsBar.innerHTML = presets
.map(
(p, idx) =>
`<button type="button" class="btn-ghost-pill" style="font-size:11.5px;padding:5px 11px;" data-pidx="${idx}">${escapeHtml(p.label)}</button>`
)
.join("");
presetsBar.querySelectorAll("button[data-pidx]").forEach((btn) => {
btn.addEventListener("click", () => {
const chosen = presets[Number(btn.dataset.pidx)];
renderPlaygroundForm(repoId, toolMeta.name, chosen.args);
invokePlaygroundTool();
});
});
const formBox = document.getElementById("pgDynamicForm");
formBox.innerHTML = Object.entries(sample)
.map(([key, val]) => {
const isObj = val !== null && typeof val === "object";
const valType = val === null ? "null_or_str" : typeof val === "number" ? (Number.isInteger(val) ? "integer" : "number") : isObj ? "json" : "string";
const displayVal = val === null ? "" : isObj ? JSON.stringify(val) : String(val);
return `
<div class="form-field">
<label><code>${escapeHtml(key)}</code></label>
<input class="form-input" data-argkey="${escapeHtml(key)}" data-argtype="${valType}" placeholder="null" value="${escapeHtml(displayVal)}" />
</div>
`;
})
.join("");
invokePlaygroundTool();
}
async function invokePlaygroundTool() {
const repoId = document.getElementById("pgRepoSelect").value;
const toolName = document.getElementById("pgToolSelect").value;
const args = {};
document.querySelectorAll("#pgDynamicForm [data-argkey]").forEach((el) => {
const k = el.dataset.argkey;
const tp = el.dataset.argtype;
const raw = el.value.trim();
if (tp === "null_or_str") {
if (!raw) args[k] = null;
else if (/^-?\d+$/.test(raw)) args[k] = parseInt(raw, 10);
else args[k] = raw;
} else if (tp === "integer") {
args[k] = raw === "" ? null : parseInt(raw, 10);
} else if (tp === "number") {
args[k] = raw === "" ? null : parseFloat(raw);
} else if (tp === "json") {
try {
args[k] = JSON.parse(raw);
} catch {
args[k] = raw;
}
} else {
args[k] = el.value;
}
});
const resp = await fetch("/api/mcp/invoke", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ repo_id: repoId, tool_name: toolName, arguments: args }),
});
const data = await resp.json();
if (!resp.ok) {
document.getElementById("pgLegacyOutPre").textContent = data.detail || "Execution error";
return;
}
document.getElementById("pgLegacyTime").textContent = `${data.legacy_latency_us} μs`;
document.getElementById("pgModernTime").textContent = `${data.modern_latency_us} μs`;
document.getElementById("pgLegacyOutPre").textContent = JSON.stringify(data.legacy_output, null, 2);
document.getElementById("pgModernOutPre").textContent = JSON.stringify(data.modern_output, null, 2);
document.getElementById("pgJsonRpcPre").textContent = JSON.stringify(data.mcp_jsonrpc_response, null, 2);
const badge = document.getElementById("pgParityBadge");
if (data.parity_verified) {
badge.className = "status-pill grey";
badge.innerHTML = `<span class="dot"></span>100% Exact Match`;
} else {
badge.className = "status-pill amber";
badge.innerHTML = `<span class="dot"></span>Difference`;
}
}
/* ==========================================================================
Parity Suite Table
========================================================================== */
async function ensureAllBundlesLoaded() {
if (!STATE.bootstrap) return;
for (const r of STATE.bootstrap.repositories) {
if (!STATE.repoBundles[r.id]) {
const resp = await fetch(`/api/repos/${r.id}`);
STATE.repoBundles[r.id] = await resp.json();
}
}
STATE.allParityCases = [];
for (const r of STATE.bootstrap.repositories) {
const b = STATE.repoBundles[r.id];
for (const c of b.verification.cases) {
STATE.allParityCases.push({
...c,
case_id: `${r.id.toUpperCase()}-${String(c.case_index).padStart(2, "0")}`,
repo_id: r.id,
repo_name: r.name,
git_sha: r.git_sha,
});
}
}
}
async function renderParityTable() {
await ensureAllBundlesLoaded();
const repoF = document.getElementById("parityRepoFilter").value;
const cliffF = document.getElementById("parityCliffFilter").value;
const filtered = STATE.allParityCases.filter((c) => {
if (repoF !== "all" && c.repo_id !== repoF) return false;
if (cliffF === "cliffs" && c.chunked_rag_parity) return false;
return true;
});
const tbody = document.getElementById("parityCasesBody");
tbody.innerHTML = filtered
.map((c) => {
const digest = JSON.stringify(c.mcp_output).slice(0, 62) + "…";
return `
<tr>
<td style="font-family:var(--font-mono);font-size:12px;font-weight:600;">${escapeHtml(c.case_id)}</td>
<td>
<div style="font-weight:500;">${escapeHtml(c.label)}</div>
<div style="font-size:11px;color:var(--ink-500);">${escapeHtml(c.repo_name)}@${escapeHtml(c.git_sha)}</div>
</td>
<td style="font-family:var(--font-mono);font-size:11.5px;">${escapeHtml(c.tool_name)}</td>
<td style="font-family:var(--font-mono);font-size:11px;color:var(--ink-700);">${escapeHtml(digest)}</td>
<td>
<span class="status-pill ${c.chunked_rag_parity ? "grey" : "amber"}">
<span class="dot"></span>${c.chunked_rag_parity ? "Pass" : "Failed"}
</span>
</td>
<td>
<span class="status-pill grey">
<span class="dot"></span>100%
</span>
</td>
</tr>
`;
})
.join("");
}
/* ==========================================================================
FinOps & Benchmarks
========================================================================== */
function renderHeadToHeadTable(rows) {
const tbody = document.getElementById("h2hBenchmarkBody");
if (!tbody) return;
tbody.innerHTML = (rows || [])
.map((r) => {
const isBeam = r.model.includes("beam-1.0");
const pct = r.zero_shot_parity_pct ?? 0;
const pillTone = pct === 100 ? "grey" : pct >= 90 ? "grey" : "amber";
return `
<tr class="${isBeam ? "selected-row" : ""}">
<td>
<div style="font-weight:${isBeam ? "600" : "500"};color:var(--ink-900);">${escapeHtml(r.model)}</div>
<div style="font-size:11px;color:var(--ink-500);">${escapeHtml(r.provider || "OpenRouter")}</div>
</td>
<td style="font-family:var(--font-mono);font-size:11.5px;">${escapeHtml(r.request_id || "—")}</td>
<td style="font-family:var(--font-mono);font-size:11.5px;">
${Number(r.prompt_tokens || 0).toLocaleString()} / ${Number(r.completion_tokens || 0).toLocaleString()} / ${Number(r.reasoning_tokens || 0).toLocaleString()}
</td>
<td style="font-weight:500;">${((r.latency_ms || 0) / 1000).toFixed(1)}s</td>
<td style="font-family:var(--font-mono);font-size:12px;">$${Number(r.cost_usd || 0).toFixed(5)}</td>
<td>
<span class="status-pill ${pillTone}">
<span class="dot"></span>${r.zero_shot_passed}/${r.total_vectors} (${pct}%)
</span>
</td>
</tr>
`;
})
.join("");
}
async function updateRoiSimulator() {
const kloc = Number(document.getElementById("roiKlocRange").value);
const mods = Number(document.getElementById("roiModsRange").value);
const runs = Number(document.getElementById("roiCallsRange").value);
const eng = Number(document.getElementById("roiEngCostRange").value);
document.getElementById("lblKloc").textContent = `${kloc} KLOC`;
document.getElementById("lblMods").textContent = `${mods} Services`;
document.getElementById("lblCalls").textContent = `${runs} / day`;
document.getElementById("lblEngCost").textContent = `${fmtUsdExact(eng)} / yr`;
const resp = await fetch("/api/finops", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
legacy_kloc: kloc,
microservices_count: mods,
daily_agent_verification_runs: runs,
engineer_fully_loaded_annual_usd: eng,
}),
});
const roi = await resp.json();
document.getElementById("roiManualUsd").textContent = fmtUsdExact(roi.modernization_program_tco_usd.manual_rewrite_usd);
document.getElementById("roiManualWeeks").textContent = `${roi.schedule_impact.manual_months} months`;
document.getElementById("roiFrontierUsd").textContent = fmtUsdExact(roi.modernization_program_tco_usd.qwen38_agent_program_usd);
document.getElementById("roiFrontierTokens").textContent = `API: ${fmtUsdExact(roi.annual_inference_cost_usd.qwen_3_8_2_4t)}/yr`;
document.getElementById("roiBeamUsd").textContent = fmtUsdExact(roi.modernization_program_tco_usd.beambridge_1m_program_usd);
document.getElementById("roiBeamWeeks").textContent = `${roi.schedule_impact.beambridge_months} months · API: ${fmtUsdExact(roi.annual_inference_cost_usd.beam_1_0_with_ast_pack)}/yr`;
document.getElementById("roiNetSavingsBanner").textContent = `${fmtUsdExact(roi.modernization_program_tco_usd.net_enterprise_savings_usd)} Saved`;
document.getElementById("roiTokenBillSaved").textContent = `${roi.annual_inference_cost_usd.token_cost_reduction_vs_qwen38_pct}% Lower Cost`;
renderFinOpsCurve(roi);
}
function renderConsultingCards(citations) {
const box = document.getElementById("consultingCardsGrid");
box.innerHTML = (citations || [])
.map(
(c) => `
<div class="rule-card" style="margin-bottom:0;">
<div style="margin-bottom:6px;">
<span class="status-pill grey"><span class="dot"></span>${escapeHtml(c.firm)}</span>
</div>
<div style="font-size:12.5px;color:var(--ink-700);line-height:1.5;">${escapeHtml(c.finding)}</div>
</div>
`
)
.join("");
}
/* ==========================================================================
Bootstrap & Event Wiring
========================================================================== */
async function initApp() {
document.querySelectorAll(".nav-tab").forEach((btn) => {
btn.addEventListener("click", async () => {
switchView(btn.dataset.view);
if (btn.dataset.view === "parity") await renderParityTable();
});
});
document.getElementById("brandHomeBtn").addEventListener("click", () => switchView("dashboard"));
document.querySelectorAll("[data-goto]").forEach((el) => {
el.addEventListener("click", async () => {
const target = el.getAttribute("data-goto");
switchView(target);
if (target === "parity") await renderParityTable();
});
});
document.querySelectorAll("#stageStrip .stage-day-item").forEach((item) => {
item.addEventListener("click", () => {
document.querySelectorAll("#stageStrip .stage-day-item").forEach((x) => x.classList.remove("active"));
item.classList.add("active");
});
});
document.getElementById("langToggleBtn").addEventListener("click", () => {
STATE.lang = STATE.lang === "en" ? "ar" : "en";
applyLanguage();
});
document.getElementById("estateSearchInput").addEventListener("input", (e) => {
renderEstatesTable(e.target.value);
});
document.getElementById("modRepoSelect").addEventListener("change", async (e) => {
const val = e.target.value;
const isGhLive = val === "__github_live__";
document.getElementById("liveGithubBox").style.display = isGhLive ? "block" : "none";
document.getElementById("runModernizerBtnText").textContent = isGhLive
? "Clone & Analyze Repository"
: "Synthesize Whole-Repo MCP";
if (!isGhLive) {
STATE.selectedRepoId = val;
await loadRepoBundle(val);
}
});
document.querySelectorAll("#modSubTabs .sub-pill-btn").forEach((btn) => {
btn.addEventListener("click", () => {
document.querySelectorAll("#modSubTabs .sub-pill-btn").forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
const st = btn.dataset.subtab;
document.getElementById("modTabRules").style.display = st === "rules" ? "block" : "none";
document.getElementById("modTabMcpCode").style.display = st === "mcp_code" ? "block" : "none";
document.getElementById("modTabLegacyCode").style.display = st === "legacy_code" ? "block" : "none";
});
});
document.getElementById("runModernizerBtn").addEventListener("click", async () => {
const btn = document.getElementById("runModernizerBtn");
const repoSel = document.getElementById("modRepoSelect").value;
const effort = document.getElementById("modEffortSelect").value;
btn.disabled = true;
try {
if (repoSel === "__github_live__") {
btn.innerHTML = `<span>Cloning Repository...</span>`;
const ghUrl = document.getElementById("liveGithubUrlInput").value.trim();
const resp = await fetch("/api/github/ingest", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ github_url: ghUrl }),
});
const ghData = await resp.json();
if (!resp.ok) {
alert(ghData.detail || "GitHub clone failed");
} else {
renderLiveGithubCloneReport(ghData);
}
} else {
btn.innerHTML = `<span>Synthesizing...</span>`;
const bundle = await loadRepoBundle(repoSel);
const resp = await fetch("/api/beam/synthesize", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
repo_id: repoSel,
provider: STATE.provider,
api_key: STATE.apiKey || null,
reasoning_effort: effort,
}),
});
const syn = await resp.json();
if (resp.ok && syn.mode !== "live_api_error") {
renderModernizerOutput(bundle, syn);
} else {
alert(syn.error || syn.detail || "Synthesis error");
}
}
} finally {
btn.disabled = false;
btn.innerHTML = `<span id="runModernizerBtnText">${
repoSel === "__github_live__" ? "Clone & Analyze Repository" : "Synthesize Whole-Repo MCP"
}</span>`;
}
});
document.getElementById("copyMcpCodeBtn").addEventListener("click", () => {
navigator.clipboard.writeText(document.getElementById("modernMcpCodePre").textContent || "");
const b = document.getElementById("copyMcpCodeBtn");
b.textContent = "Copied";
setTimeout(() => (b.textContent = "Copy Code"), 1400);
});
document.getElementById("jumpToPlaygroundBtn").addEventListener("click", () => switchView("playground"));
document.getElementById("pgRepoSelect").addEventListener("change", async (e) => {
const rid = e.target.value;
await loadRepoBundle(rid);
populatePlaygroundTools(rid);
});
document.getElementById("pgToolSelect").addEventListener("change", (e) => {
renderPlaygroundForm(document.getElementById("pgRepoSelect").value, e.target.value);
});
document.getElementById("invokeMcpBtn").addEventListener("click", invokePlaygroundTool);
document.getElementById("parityRepoFilter").addEventListener("change", renderParityTable);
document.getElementById("parityCliffFilter").addEventListener("change", renderParityTable);
["roiKlocRange", "roiModsRange", "roiCallsRange", "roiEngCostRange"].forEach((id) => {
document.getElementById(id).addEventListener("input", updateRoiSimulator);
document.getElementById(id).addEventListener("change", updateRoiSimulator);
});
const engModal = document.getElementById("engineModal");
document.getElementById("openEngineModalBtn").addEventListener("click", () => {
document.getElementById("cfgProvider").value = STATE.provider;
document.getElementById("cfgApiKey").value = STATE.apiKey;
engModal.classList.add("open");
});
document.getElementById("closeEngineModalBtn").addEventListener("click", () => engModal.classList.remove("open"));
document.getElementById("saveEngineCfgBtn").addEventListener("click", () => {
STATE.provider = document.getElementById("cfgProvider").value;
STATE.apiKey = document.getElementById("cfgApiKey").value.trim();
safeStorageSet("bb_provider", STATE.provider);
safeStorageSet("bb_api_key", STATE.apiKey);
document.getElementById("engineStatusDot").classList.toggle("live", Boolean(STATE.apiKey));
engModal.classList.remove("open");
});
// Clean 01–04 Onboarding & SHA-256 Modal
const certModal = document.getElementById("certModal");
let activeGuideClient = "claude";
let activeGuideSubIndex = 0;
function buildGuideClients(origin) {
const mcpUrl = `${origin}/mcp`;
return {
claude: {
title: "Claude",
extLabel: "claude.ai ↗",
extHref: "https://claude.ai",
modes: [
{
label: "Claude",
copyLabel: "Copy for Claude",
helper:
STATE.lang === "ar"
? "يرشدك Claude لإضافة بوابة BeamBridge كموصل مخصص في الإعدادات."
: "Claude walks you through adding BeamBridge as a custom connector in settings.",
snippet: `Connect BeamBridge (${mcpUrl}) to Claude: open Settings › Connectors › Add custom connector, paste ${mcpUrl}, click Add, then list the 12 tools and test pro_rata_subunit_split on $100 USD across [1, 1, 1].`,
},
{
label: "Claude Code",
copyLabel: "Copy for Claude Code",
helper:
STATE.lang === "ar"
? "أمر واحد يربط خادم HTTP JSON-RPC 2.0 مباشرة في Claude Code."
: "Attach BeamBridge in one CLI command over HTTP JSON-RPC 2.0.",
snippet: `claude mcp add --transport http beambridge ${mcpUrl}`,
},
],
},
openai: {
title: "OpenAI",
extLabel: "chatgpt.com ↗",
extHref: "https://chatgpt.com",
modes: [
{
label: "ChatGPT",
copyLabel: "Copy for ChatGPT",
helper:
STATE.lang === "ar"
? "أضف البوابة كموصل MCP مخصص داخل إعدادات ChatGPT."
: "Attach BeamBridge via ChatGPT Custom MCP Connectors.",
snippet: `Connect custom MCP server ${mcpUrl}, list all 12 tools, and test validate_and_decompose_iban on "GB29 NWBK 6016 1331 9268 19".`,
},
{
label: "Codex",
copyLabel: "Copy for Codex",
helper:
STATE.lang === "ar"
? "أضف هذا المقطع إلى ملف إعدادات Codex CLI."
: "Add this block to ~/.codex/config.toml.",
snippet: `[mcp_servers.beambridge]\nurl = "${mcpUrl}"\ntransport = "streamable_http"`,
},
],
},
cursor: {
title: "Cursor",
extLabel: "cursor.com ↗",
extHref: "https://cursor.com",
modes: [
{
label: "Prompt",
copyLabel: "Copy for Cursor",
helper:
STATE.lang === "ar"
? "الصقه في محادثة Cursor ليضبط ملف .cursor/mcp.json تلقائياً."
: "Paste into Cursor Agent to configure .cursor/mcp.json automatically.",
snippet: `Add HTTP MCP server "beambridge" (${mcpUrl}) to .cursor/mcp.json and test parse_procurement_price on "1.299,95 €".`,
},
{
label: "mcp.json",
copyLabel: "Copy mcp.json",
helper:
STATE.lang === "ar"
? "أو ضعه مباشرة في ملف .cursor/mcp.json."
: "Or save directly into .cursor/mcp.json.",
snippet: JSON.stringify({ mcpServers: { beambridge: { url: mcpUrl, transport: "streamable-http" } } }, null, 2),
},
],
},
antigravity: {
title: "Antigravity",
extLabel: "idx.google.com ↗",
extHref: "https://idx.google.com",
modes: [
{
label: "Setup",
copyLabel: "Copy for Antigravity",
helper:
STATE.lang === "ar"
? "اربط بوابة BeamBridge داخل إعدادات MCP في Antigravity."
: "Register BeamBridge inside Antigravity MCP settings.",
snippet: `Register MCP server "beambridge" at ${mcpUrl} and run inspect_and_round_money("45.6785", "BHD", 3).`,
},
],
},
other: {
title: "Other",
extLabel: "modelcontextprotocol.io ↗",
extHref: "https://modelcontextprotocol.io",
modes: [
{
label: "JSON Config",
copyLabel: "Copy Config",
helper:
STATE.lang === "ar"
? "متوافق مع أي عميل يدعم بروتوكول MCP عبر HTTP."
: "Standard config for any HTTP JSON-RPC 2.0 MCP client.",
snippet: JSON.stringify({ mcpServers: { beambridge: { url: mcpUrl } } }, null, 2),
},
{
label: "cURL",
copyLabel: "Copy cURL",
helper:
STATE.lang === "ar"
? "اختبار مباشر من الطرفية."
: "Test directly from any terminal.",
snippet: `curl -sS -X POST ${mcpUrl} -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`,
},
],
},
};
}
function renderGuideClientCard() {
const clients = buildGuideClients(window.location.origin);
const cfg = clients[activeGuideClient] || clients.claude;
if (activeGuideSubIndex >= cfg.modes.length) activeGuideSubIndex = 0;
const mode = cfg.modes[activeGuideSubIndex];
document.querySelectorAll("#guideClientList .guide-client-btn").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.client === activeGuideClient);
});
document.getElementById("guideClientHeading").textContent = cfg.title;
const extEl = document.getElementById("guideClientExtLink");
extEl.textContent = cfg.extLabel;
extEl.href = cfg.extHref;
const pillsBox = document.getElementById("guideModePills");
if (cfg.modes.length > 1) {
pillsBox.style.display = "inline-flex";
pillsBox.innerHTML = cfg.modes
.map(
(m, idx) =>
`<button type="button" class="guide-mode-pill ${idx === activeGuideSubIndex ? "active" : ""}" data-mindex="${idx}">${escapeHtml(m.label)}</button>`
)
.join("");
pillsBox.querySelectorAll(".guide-mode-pill").forEach((pb) => {
pb.addEventListener("click", () => {
activeGuideSubIndex = Number(pb.dataset.mindex);
renderGuideClientCard();
});
});
} else {
pillsBox.style.display = "none";
pillsBox.innerHTML = "";
}
document.getElementById("guideClientHelper").textContent = mode.helper;
document.getElementById("mcpEndpointSnippet").textContent = mode.snippet;
document.getElementById("copyClientPromptLabel").textContent = mode.copyLabel;
}
function renderGuideCertificates() {
if (!STATE.bootstrap) return;
document.getElementById("certListBox").innerHTML = STATE.bootstrap.repositories
.map((r) => {
const firstId = (r.verification.synthesis_audit.whole_repo_request_ids || [])[0] || "";
const sha = r.verification.certificate_sha256 || "";
return `
<div class="guide-cert-card">
<div class="guide-cert-top">
<div class="guide-cert-repo">${escapeHtml(r.name)} <code style="color:#8e8e9a;font-size:11px;">@${escapeHtml(r.git_sha)}</code></div>
<span class="guide-cert-badge">${r.verification.beam_1m_passed}/${r.verification.total_cases}</span>
</div>
<div class="guide-cert-meta">
ID: ${escapeHtml(firstId)} · SHA: ${escapeHtml(sha.slice(0, 14))}…
</div>
</div>
`;
})
.join("");
}
document.querySelectorAll("#guideClientList .guide-client-btn").forEach((btn) => {
btn.addEventListener("click", () => {
activeGuideClient = btn.dataset.client;
activeGuideSubIndex = 0;
renderGuideClientCard();
});
});
document.getElementById("copyClientPromptBtn").addEventListener("click", () => {
const txt = document.getElementById("mcpEndpointSnippet").textContent || "";
navigator.clipboard.writeText(txt);
const lbl = document.getElementById("copyClientPromptLabel");
const prev = lbl.textContent;
lbl.textContent = "Copied";
setTimeout(() => {
lbl.textContent = prev;
}, 1400);
});
document.getElementById("copyMasterShaBtn").addEventListener("click", (e) => {
const masterSha =
(STATE.bootstrap && STATE.bootstrap.portfolio_totals && STATE.bootstrap.portfolio_totals.master_certificate_sha256) || "";
navigator.clipboard.writeText(masterSha);
const btn = e.currentTarget;
const prev = btn.textContent;
btn.textContent = "Copied";
setTimeout(() => {
btn.textContent = prev;
}, 1500);
});
document.getElementById("guideOpenEngineBtn").addEventListener("click", () => {
certModal.classList.remove("open");
document.getElementById("cfgProvider").value = STATE.provider;
document.getElementById("cfgApiKey").value = STATE.apiKey;
engModal.classList.add("open");
});
document.getElementById("guideJumpModernizerBtn").addEventListener("click", () => {
certModal.classList.remove("open");
switchView("modernizer");
});
document.getElementById("guideJumpPlaygroundBtn").addEventListener("click", () => {
certModal.classList.remove("open");
switchView("playground");
});
document.getElementById("guideJumpParityBtn").addEventListener("click", async () => {
certModal.classList.remove("open");
switchView("parity");
await renderParityTable();
});
const CHIP_ACTIONS = {
money: {
repo: "py_moneyed",
tool: "pro_rata_subunit_split",
args: { amount_str: "100.00", currency_code: "USD", weights: [1, 1, 1] },
},
iban: {
repo: "schwifty",
tool: "validate_and_decompose_iban",
args: { raw_iban: "GB29 NWBK 6016 1331 9268 19" },
},
vat: {
repo: "python_stdnum",
tool: "validate_eu_vat_number",
args: { raw_vat: "DE 136 695 976" },
},
};
document.querySelectorAll("#guideExampleChips .guide-prompt-chip").forEach((chip) => {
chip.addEventListener("click", async () => {
navigator.clipboard.writeText(chip.textContent.trim());
const act = CHIP_ACTIONS[chip.dataset.chip];
certModal.classList.remove("open");
if (act) {
switchView("playground");
document.getElementById("pgRepoSelect").value = act.repo;
await loadRepoBundle(act.repo);
populatePlaygroundTools(act.repo);
document.getElementById("pgToolSelect").value = act.tool;
renderPlaygroundForm(act.repo, act.tool, act.args);
}
});
});
document.getElementById("openCertModalBtn").addEventListener("click", () => {
renderGuideClientCard();
renderGuideCertificates();
certModal.classList.add("open");
});
document.getElementById("closeCertModalBtn").addEventListener("click", () => certModal.classList.remove("open"));
certModal.addEventListener("click", (e) => {
if (e.target === certModal) certModal.classList.remove("open");
});
window.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
certModal.classList.remove("open");
engModal.classList.remove("open");
}
});
// Bootstrap
const bootResp = await fetch("/api/bootstrap");
const boot = await bootResp.json();
STATE.bootstrap = boot;
const pt = boot.portfolio_totals;
const fin = boot.finops;
const savedPct = Math.round(fin.annual_inference_cost_usd.token_cost_reduction_vs_qwen38_pct || 97);
const driftPct = Math.round(100 - pt.chunked_rag_parity_pct);
document.getElementById("capParityVal").textContent = `${Math.round(pt.beam_1m_parity_pct)}%`;
document.getElementById("capTokenSavedVal").textContent = `${savedPct}%`;
document.getElementById("capDriftVal").textContent = `${driftPct}%`;
document.getElementById("capRegVal").textContent = "0%";
document.getElementById("kpiTestsNum").textContent = String(pt.total_verification_assertions);
document.getElementById("kpiToolsNum").textContent = String(pt.mcp_tools_exposed);
document.getElementById("kpiSavingsNum").textContent = fmtCurrency(fin.modernization_program_tco_usd.net_enterprise_savings_usd);
document.getElementById("tlPackSub").textContent = `${(pt.total_raw_beam_tokens / 1_000_000).toFixed(2)}M → ${pt.total_beam_tokens.toLocaleString()} tokens`;
const chunkFails = Math.round(pt.total_verification_assertions * (1 - pt.chunked_rag_parity_pct / 100));
document.getElementById("darkPassedNum").textContent = String(pt.total_verification_assertions);
document.getElementById("darkFailedNaiveNum").textContent = String(chunkFails);
const mult = (fin.annual_inference_cost_usd.qwen_3_8_2_4t / Math.max(1, fin.annual_inference_cost_usd.beam_1_0_with_ast_pack)).toFixed(1);
document.getElementById("donutCenterMult").textContent = `${mult}x`;
document.getElementById("donutSavedPct").textContent = `${savedPct}%`;
document.getElementById("donutUsedPct").textContent = `${100 - savedPct}%`;
renderEstatesTable();
renderFinOpsCurve(fin);
renderHeadToHeadTable(boot.head_to_head_benchmark);
renderConsultingCards(fin.citations);
await loadRepoBundle(STATE.selectedRepoId);
await renderMatrixDots();
await updateRoiSimulator();
}
window.addEventListener("DOMContentLoaded", initApp);
|