Spaces:
Running
fix(chatbot): agent-architecture audit (layers 3/6/10) — routing noise, refs ownership, block coherence, rendering contract E2E, post-deploy live probe
Browse filesSkills applied: agent-architecture-audit + e2e-testing + systematic-debugging
(+ the ci-cd gates pattern), per the owner's token-burn minimization mandate.
AUDIT FINDINGS → FIXES (evidence-backed, code-first):
1. Layer 6 (routing discipline) — keyword hygiene: single generic words fired
whole domain cores on unrelated questions ('قاطع' lit saudi+schneider on a
generic breaker-vs-disconnector question; 'قصر' lit the Saadat pack on a
cables question; 'كود' lit cables on a SAUDI-code question; 'kva' lit ABB
on any load question; 'توليد/نقل/توزيع' lit Gilany on anything). Removed
the generic tokens from the keyword lists — the specific PHRASES keep
every intended contract (all skillnet tests green untouched).
2. Layer 6 (coherence) — forced co-selection: a dynamic RAG block can never
ride without its protocol block anymore (getSystemPrompt force-includes
saadat/cables/the exact refs skills when their context block is present).
3. Layer 3 (context routing) — refs ownership: when the cables layer is
active and no reference corpus matches, routeRefsQuery now returns an
EMPTY route → empty block, instead of falling back to searching 4
unrelated documents (wrong-file token burn the owner explicitly banned).
4. Layer 10 (rendering) — E2E contract: new chat-refs-citations.spec.ts
proves the price-table → documented bullets transform keeps every cell
verbatim (Product IDs/EGP prices), Latin IDs never bidi-mangled inside
RTL text, and the citation lines survive LAST in the bubble (DOM-order
assertions — innerText bidi reordering would false-fail).
5. CI/CD: deploy-hf.yml gains a live-probe job — waits for the Space to
reach RUNNING, runs scripts/chatbot-refs-live-proof.ts (deterministic
server-enforced citation contracts as HARD gates; model-variance price
formatting as SOFT warn per the flaky-test pattern; 1 retry), and
publishes the proof into the step summary (log-embedded — the security
contract pins every action ref to a verified SHA, so no artifact action).
MEASURED (scripts/audit_prompt_size.ts, before → after): generic thinking
prompt 31,818 → 29,264 chars (~−750 tokens); cables 39,078 → 35,385
(~−1,086 tokens); saadat 38,140 → 36,897. Static floor (21,036 chars ≈
6,187 tokens — persona/identity design) reported to the owner as a finding,
deliberately NOT cut.
Unit 1269 ✓ · E2E 42 ✓ · tsc/ultracheck/biome ✓
Files changed (10)
- .github/workflows/deploy-hf.yml+51
- api/lib/chatbot-prompts.ts+32-12
- api/lib/chatbot-refs.ts+11-7
- api/lib/chatbot-skillnet.ts+21-18
- scripts/audit_prompt_breakdown.tsAdded+20
- scripts/audit_prompt_dup.tsAdded+24
- scripts/audit_prompt_size.tsAdded+40
- scripts/chatbot-refs-live-proof.ts+15-2
- scripts/ui-test-server.mjs+21
- tests/e2e/features/chat-refs-citations.spec.tsAdded+74
167 unmodified lines168169170167 unmodified lines- name: Deployment Statusif: always()run: echo "Deployment completed. Check https://huggingface.co/spaces/ahmdelbaz28/AHMDRTAP for build status."167 unmodified lines168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221167 unmodified lines- name: Deployment Statusif: always()run: echo "Deployment completed. Check https://huggingface.co/spaces/ahmdelbaz28/AHMDRTAP for build status."# ══════════════════════════════════════════════════════════# POST-DEPLOY LIVE PROBE (per the e2e-testing + ci-cd skills):# verify the deployed Space actually serves the technical-references# contracts (citations are enforced SERVER-SIDE, so they are deterministic).# Hard checks gate the run; model-variance soft checks report as WARN.# Retries ×2 (CI pattern); artifacts retained 30 days.# ══════════════════════════════════════════════════════════live-probe:needs: deployruns-on: ubuntu-latesttimeout-minutes: 20steps:- name: Checkout GitHub repouses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:node-version: 22- name: Install dependencies (tsx runtime only)run: npm ci --ignore-scripts --no-audit --no-fund- name: Wait for the HF Space to finish buildingrun: |for i in $(seq 1 40); doSTAGE=$(curl -s https://huggingface.co/api/spaces/ahmdelbaz28/AHMDRTAP | grep -o '"stage":"[^"]*"' | head -1 | cut -d'"' -f4 || echo "unknown")echo "attempt $i: stage=$STAGE"if [ "$STAGE" = "RUNNING" ]; then echo "Space is RUNNING"; exit 0; fisleep 15doneecho "::warning::Space stage never reached RUNNING within 10 minutes — probing anyway"- name: Run the references live proof (2 attempts)run: |set -o pipefailnpx tsx scripts/chatbot-refs-live-proof.ts 2>&1 | tee live-proof.log && STATUS=0 || STATUS=$?if [ "$STATUS" != "0" ]; thenecho "attempt 1 failed (status=$STATUS) — retrying once (flaky-model pattern)"sleep 30npx tsx scripts/chatbot-refs-live-proof.ts 2>&1 | tee live-proof.logfi- name: Publish proof summary (log-embedded — the security contract pinsevery action ref to a verified SHA, so no artifact action is added)if: always()run: |echo "### Chatbot references live proof" >> "$GITHUB_STEP_SUMMARY"tail -40 live-proof.log >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || echo "(log missing)"
30 unmodified lines313233343536673 unmodified lines71071171271371471571671771871972072172272372472572672772872973073161 unmodified lines79379479579679779830 unmodified linesimport { buildScreenBlock, type ParsedScreenContext } from "./chatbot-screen.js";import { SKILL_REGISTRY, registerSkillContent, routeSkills, logSkillRouting } from "./chatbot-skillnet.js";import {versionRuleAr,673 unmodified lines? null: routeSkills({ signal: routingSignal, lang: skillLang, mode, screenCapture, vision, floor: routingFloor });if (routingDecision) logSkillRouting(routingDecision, { lane: mode });const skillIncluded = (id: string): boolean =>!routingDecision || routingDecision.strategy === "full-fallback"? true: routingDecision.selected.some((s) => s.id === id);// Routed zone A — pf/skm/pvsyst/etap/depth + the four new study packs, in// the registry's canonical order (exactly the historical composition order// with the new packs inserted after the depth pack). Zone B — the SLD// drawing skill keeps its historical position AFTER the evidence model.const routedZoneA = SKILL_REGISTRY.filter((s) => s.id !== "sld-drawing-skill" && s.modes.includes(mode)).map((s) => (skillIncluded(s.id) ? s.build(skillLang, mode) : "")).join("");const routedZoneB = skillIncluded("sld-drawing-skill")? (skillLang === "ar" ? sldSkillAr : sldSkillEn): "";// ── Screen-context block — the user's CURRENT open screen (page, displayed// entity, nav trail, UI state) embedded as read-only data. Built for the61 unmodified lines// query) → byte-identical prompt.const refsBlock = typeof refsContext === "string" && refsContext.trim().length > 0 ? refsContext : "";if (mode === "instant") {if (language === "ar") {return `أنت المساعد الذكي الرسمي لمنصة "الباز" (Elbaz Platform) المتخصصة في الكورسات الهندسية.30 unmodified lines31323334353637673 unmodified lines71171271371471571671771871972072172272372472572672772861 unmodified lines79079179279379479579679779879980080180280380480580680780880981081181281381481581681781830 unmodified linesimport { buildScreenBlock, type ParsedScreenContext } from "./chatbot-screen.js";import { SKILL_REGISTRY, registerSkillContent, routeSkills, logSkillRouting } from "./chatbot-skillnet.js";import { routeRefsQuery } from "./chatbot-refs.js";import {versionRuleAr,673 unmodified lines? null: routeSkills({ signal: routingSignal, lang: skillLang, mode, screenCapture, vision, floor: routingFloor });if (routingDecision) logSkillRouting(routingDecision, { lane: mode });// ✅ AUDIT FIX (layer-6 coherence): a dynamic RAG block must never ride// without its protocol block — when saadat/cables/refs context is present,// the matching skill block is FORCE-INCLUDED regardless of keyword scoring// (the router may legitimately score 1 on a multi-domain message). The set// is declared here and FILLED after the three blocks are built below.const forcedSkillIds = new Set<string>();const skillIncluded = (id: string): boolean =>!routingDecision || routingDecision.strategy === "full-fallback"? true: forcedSkillIds.has(id) || routingDecision.selected.some((s) => s.id === id);// ── Screen-context block — the user's CURRENT open screen (page, displayed// entity, nav trail, UI state) embedded as read-only data. Built for the61 unmodified lines// query) → byte-identical prompt.const refsBlock = typeof refsContext === "string" && refsContext.trim().length > 0 ? refsContext : "";// ── forced co-selection fill (layer-6 coherence — see note above) ──if (saadatBlock) forcedSkillIds.add("saadat-academic-core");if (cablesBlock) forcedSkillIds.add("cables-expert-core");if (refsBlock) {const refsRoute = routeRefsQuery(routingSignal ?? "", cablesBlock.length > 0);if (refsRoute.saudi) forcedSkillIds.add("saudi-load-core");if (refsRoute.abb) forcedSkillIds.add("abb-transformer-core");if (refsRoute.schneider) forcedSkillIds.add("schneider-price-core");if (refsRoute.gilany) forcedSkillIds.add("gilany-pse-core");}// Routed zone A — pf/skm/pvsyst/etap/depth + the four new study packs, in// the registry's canonical order (exactly the historical composition order// with the new packs inserted after the depth pack). Zone B — the SLD// drawing skill keeps its historical position AFTER the evidence model.const routedZoneA = SKILL_REGISTRY.filter((s) => s.id !== "sld-drawing-skill" && s.modes.includes(mode)).map((s) => (skillIncluded(s.id) ? s.build(skillLang, mode) : "")).join("");const routedZoneB = skillIncluded("sld-drawing-skill")? (skillLang === "ar" ? sldSkillAr : sldSkillEn): "";if (mode === "instant") {if (language === "ar") {return `أنت المساعد الذكي الرسمي لمنصة "الباز" (Elbaz Platform) المتخصصة في الكورسات الهندسية.
228 unmodified lines2292302312322332342352362372382392402412421168 unmodified lines14111412141314141415141668 unmodified lines148514861487148814891490228 unmodified lines}}if (docs.length === 0) {// no specialized corpus matched → generic engineering question: the book +// every structured catalogue is the fallback (generous, still filtered// BM25) — minus the corpora the active cables layer already ownsconst fallback = ALL_DOCS.filter((d) =>cablesIntentActive ? d !== "elsewedy" && d !== "egycode-1" && d !== "egycode-2" : true);gilany = true;return { saudi: true, abb: true, schneider: true, gilany: true, docs: fallback };}return { saudi, abb, schneider, gilany, docs };}1168 unmodified lineslet size = 0;const route = routeRefsQuery(query, opts.cablesIntentActive ?? false);// 1) Saudi load engineconst saudiReq = route.saudi ? parseSaudiLoadRequest(query) : null;68 unmodified lines): string[] {if (!hasRefsIntent(query)) return [];const route = routeRefsQuery(query, opts.cablesIntentActive ?? false);const out: string[] = [];const saudiReq = route.saudi ? parseSaudiLoadRequest(query) : null;if (saudiReq) {228 unmodified lines2292302312322332342352362372382392402412422432441168 unmodified lines141314141415141614171418141968 unmodified lines1488148914901491149214931494228 unmodified lines}}if (docs.length === 0) {// cables layer owns this query and no reference corpus matched → return an// EMPTY route: burning tokens on wrong files is exactly what must never// happen (the cables layer's curated KB + engine already serve it)if (cablesIntentActive) {return { saudi: false, abb: false, schneider: false, gilany: false, docs: [] };}// generic engineering question → the book + every structured catalogue is// the fallback (generous, still filtered BM25)gilany = true;return { saudi: true, abb: true, schneider: true, gilany: true, docs: [...ALL_DOCS] };}return { saudi, abb, schneider, gilany, docs };}1168 unmodified lineslet size = 0;const route = routeRefsQuery(query, opts.cablesIntentActive ?? false);if (route.docs.length === 0) return "";// 1) Saudi load engineconst saudiReq = route.saudi ? parseSaudiLoadRequest(query) : null;68 unmodified lines): string[] {if (!hasRefsIntent(query)) return [];const route = routeRefsQuery(query, opts.cablesIntentActive ?? false);if (route.docs.length === 0) return [];const out: string[] = [];const saudiReq = route.saudi ? parseSaudiLoadRequest(query) : null;if (saudiReq) {
472 unmodified lines47347447547647747847927 unmodified lines50750850951051151251351451512 unmodified lines52852953053153253353453553653712 unmodified lines55055155255355455555655755812 unmodified lines57157257357457557657757857958058111 unmodified lines593594595596597598599600601472 unmodified lines"الاستقراريه", "stability", "swing", "equal area", "inertia", "ثابت القصور","symmetrical", "متماثله", "sequence", "operator a","line to line", "line to ground", "subtransient", "transient", "fault mva","breaker duty", "قدره القصر", "قصر", "عطل", "zbus", "alfc", "avr","load frequency", "excitation", "speed regulation", "منظم السرعه", "منظم الجهد","lqr", "lagrange", "lambda", "incremental cost", "التكلفه الحديه", "kuhn","fuel cost", "abcd", "surge impedance", "voltage regulation", "تنظيم الجهد",27 unmodified lines"ماسورة", "ماسوره", "مواسير", "conduit", "مجرى", "مجارى", "duct", "tray", "trunking", "سرير", "سراير","خنادق", "حفر", "دفن", "مدفون", "buried", "underground", "غرف التفتيش","trefoil", "مثلثي", "مسطح", "flat", "تلامس", "grouping", "تجميع", "derating", "تصحيح","هبوط", "الجهد", "قصر", "fault", "kA", "كيلو أمبير", "voltage drop", "vd","معامل القدرة", "مكثفات", "kvar", "معامل الطلب", "demand factor","كود", "code", "بند", "clause", "جدول", "table",],softwareAffinity: [/elsewedy/i, /السويدي/, /كود مصري/, /الكود المصري/],modes: ["thinking", "instant"],12 unmodified lines"تقدير أحمال", "تقدير الاحمال", "customer load estimation", "منحنى C1", "C1", "C2", "C29",],keywords: ["سعودي", "saudi", "sec", "dps", "حمل", "load", "عدادات", "مeters", "مeters","قاطع", "breaker", "خدمة", "service", "تكييف مركزي", "district cooling", "شتوي", "winter","c3", "c4", "c5", "c6", "c7", "c8", "c9", "c18", "c21", "c29", "va/m", "كثافة","جداول", "tables", "معامل", "factor",],softwareAffinity: [/dps/i, /\bsaudi\b/i, /السعودي/],modes: ["thinking", "instant"],12 unmodified lines"فقد لا حمل", "فقد الحمل", "no-load loss", "load loss", "محول توزيع", "distribution transformer",],keywords: ["abb", "محول", "محوّل", "transformer", "kva", "ك ف ا", "dyn11", "dyn5", "yzn5", "yzn11","معاوقه", "impedance", "فواقد", "losses", "وزن", "weight", "زيتي", "oil", "جافه", "dry","خزان", "tank", "موسع زيت", "هرميتيك", "hermetic", "pad mount", "reactor", "مفاعلات",],softwareAffinity: [/\babb\b/i, /محولات?/],modes: ["thinking", "instant"],12 unmodified lines"انفرتر", "ATV", "Product ID", "بند الكتالوج", "القطعة المناسبة",],keywords: ["شنايدر", "schneider", "se.com", "قاطع", "breaker", "قواطع", "nw", "nt", "mvs", "enw","g12", "g20", "g25", "g40", "g80", "ic60", "acti9", "resi9", "easy9", "mcb", "rccb", "rcbo","lc1", "lr2", "gv2", "tesys", "تلسيس", "xb7", "harmony", "tm3", "modicon", "dm1", "dm3","gologic", "atv", "altivar", "altistart", "varplus", "مكثفات", "سعر", "price", "egp","جنيه", "غير شامل", "vat", "product", "reference", "مرجع",],softwareAffinity: [/schneider/i, /شنايدر/, /masterpact/i, /my\s?pact/i],modes: ["thinking", "instant"],11 unmodified lines"محطات التحويل", "substation", "شبكات التوزيع", "منحنى الحمل", "load curve",],keywords: ["جيلان", "هندسة قوى", "توليد", "generation", "نقل", "transmission", "توزيع", "distribution","استقرار", "stability", "عابر", "transient", "iec 61850", "اورتماتيون", "automation","وحدات توليد", "base load", "peak load", "مركز تحكم",],softwareAffinity: [/جيلان/],modes: ["thinking", "instant"],472 unmodified lines47347447547647747847927 unmodified lines50750850951051151251351451512 unmodified lines52852953053153253353453553612 unmodified lines54955055155255355455555655755855912 unmodified lines57257357457557657757857958058158258311 unmodified lines595596597598599600601602603604472 unmodified lines"الاستقراريه", "stability", "swing", "equal area", "inertia", "ثابت القصور","symmetrical", "متماثله", "sequence", "operator a","line to line", "line to ground", "subtransient", "transient", "fault mva","breaker duty", "قدرة القصر", "قدره القصر", "زُبوس", "zbus", "alfc", "avr","load frequency", "excitation", "speed regulation", "منظم السرعه", "منظم الجهد","lqr", "lagrange", "lambda", "incremental cost", "التكلفه الحديه", "kuhn","fuel cost", "abcd", "surge impedance", "voltage regulation", "تنظيم الجهد",27 unmodified lines"ماسورة", "ماسوره", "مواسير", "conduit", "مجرى", "مجارى", "duct", "tray", "trunking", "سرير", "سراير","خنادق", "حفر", "دفن", "مدفون", "buried", "underground", "غرف التفتيش","trefoil", "مثلثي", "مسطح", "flat", "تلامس", "grouping", "تجميع", "derating", "تصحيح","هبوط الجهد", "تيار القصر", "fault", "kA", "كيلو أمبير", "voltage drop", "vd","معامل القدرة", "مكثفات", "kvar", "معامل الطلب", "demand factor","الكود المصري", "كود مصري", "الدليل الإرشادي", "الدليل الارشادي",],softwareAffinity: [/elsewedy/i, /السويدي/, /كود مصري/, /الكود المصري/],modes: ["thinking", "instant"],12 unmodified lines"تقدير أحمال", "تقدير الاحمال", "customer load estimation", "منحنى C1", "C1", "C2", "C29",],keywords: ["سعودي", "saudi", "sec dps", "dps-01", "dps01", "عدادات", "عدادات الكهرباء","تكييف مركزي", "district cooling", "مناطق شتوية", "winter peak","c3", "c4", "c5", "c6", "c7", "c8", "c9", "c18", "c21", "c29", "va/m", "كثافة الحمل",],softwareAffinity: [/dps/i, /\bsaudi\b/i, /السعودي/],modes: ["thinking", "instant"],12 unmodified lines"فقد لا حمل", "فقد الحمل", "no-load loss", "load loss", "محول توزيع", "distribution transformer",],keywords: ["abb", "محول توزيع", "محولات توزيع", "transformer", "dyn11", "dyn5", "yzn5", "yzn11","مجموعة المتجهات", "vector group", "معاوقة", "معاوقه", "فقد لا حمل", "no-load loss","فقد الحمل", "load loss", "فواقد", "زيتي", "oil", "جافه", "جافة", "dry type", "cast coil","resibloc", "ريزين", "خزان", "tank", "موسع زيت", "هرميتيك", "hermetic", "pad mount","boosterformer", "مفاعلات", "reactors",],softwareAffinity: [/\babb\b/i, /محولات?/],modes: ["thinking", "instant"],12 unmodified lines"انفرتر", "ATV", "Product ID", "بند الكتالوج", "القطعة المناسبة",],keywords: ["شنايدر", "schneider", "se.com", "masterpact", "ماستر باكت", "mtz1", "mtz2", "easypact","mvs", "enw", "gopact", "go pact", "g12", "g20", "g25", "g40", "g80", "ic60", "acti9","resi9", "easy9", "mcb", "rccb", "rcbo", "lc1d", "lr2k", "gv2", "tesys", "تلسيس","xb7", "harmony", "tm3", "modicon", "dm1", "dm3", "gologic", "atv", "altivar","altistart", "varplus", "varplus canalis", "سعر القاطع", "سعر البند", "قائمة اسعار","قائمة الأسعار", "price list", "egp", "جنيه مصري", "غير شامل الضريبة", "product id",],softwareAffinity: [/schneider/i, /شنايدر/, /masterpact/i, /my\s?pact/i],modes: ["thinking", "instant"],11 unmodified lines"محطات التحويل", "substation", "شبكات التوزيع", "منحنى الحمل", "load curve",],keywords: ["جيلان", "هندسة القوى", "هندسة قوى", "الشبكة الموحدة", "شبكة موحدة", "spinning reserve","الاحتياطي الدوار", "الإظلام التام", "blackout", "استقرار منظومة", "stability","العابرات", "transient", "iec 61850", "الاورتماتيون", "محطات التحويل", "substation","منحنى الحمل", "load curve", "مركز التحكم القومي",],softwareAffinity: [/جيلان/],modes: ["thinking", "instant"],
1234567891011121314151617181920/* Break down the thinking-mode prompt composition (block-level sizes). */import { SKILL_REGISTRY } from "../api/lib/chatbot-skillnet.js";import { getSystemPrompt } from "../api/lib/chatbot-prompts.js";
console.log("=== skill block sizes (ar/thinking) ===");const rows = SKILL_REGISTRY.map((s) => ({ id: s.id, alwaysOn: !!s.alwaysOn, len: s.build("ar", "thinking").length })) .sort((a, b) => b.len - a.len);let always = 0;let routable = 0;for (const r of rows) { if (r.len > 0) console.log(`${r.id.padEnd(34)} ${String(r.len).padStart(6)} chars ${r.alwaysOn ? "(always-on)" : ""}`); if (r.alwaysOn) always += r.len; else routable += r.len;}console.log(`TOTAL always-on blocks: ${always} chars (~${Math.round(always / 3.4)} tokens)`);console.log(`TOTAL routable blocks : ${routable} chars (~${Math.round(routable / 3.4)} tokens)`);
const lean = getSystemPrompt("ar", "thinking", undefined, false, undefined, undefined, false, "شكراً جزيلاً على الرد اللطيف");console.log(`\nLEAN thinking prompt (generic msg): ${lean.length} chars (~${Math.round(lean.length / 3.4)} tokens)`);console.log(`→ static prompt floor (persona+platform+etc): ${lean.length - always} chars (~${Math.round((lean.length - always) / 3.4)} tokens)`);123456789101112131415161718192021222324/* Find duplicated instruction segments inside the static prompt floor. */import { getSystemPrompt } from "../api/lib/chatbot-prompts.js";
const p = getSystemPrompt("ar", "thinking", undefined, false, undefined, undefined, false, "شكراً جزيلاً على الرد اللطيف");
// split into blocks by the emoji-section convention, look for overlapping themesconst sections = p.split("\n\n");console.log("section count:", sections.length);for (const s of sections) { const head = s.trim().slice(0, 90).replace(/\n/g, " "); console.log(`${String(s.length).padStart(6)} chars | ${head}`);}
// repeated key phrases (duplication candidates)const probes = [ "الهندسة الكهربية", "ETAP", "لا تخترع", "لا تختلق", "المصدر", "الاستشهاد", "استشهد", "أداة", "كورسات", "أحمد الباز", "المنصة", "اتبع", "خطوة بخطوة", "±0.5", "التوثيق", "ممنوع", "إلزامي",];console.log("\n=== phrase occurrence counts (duplication candidates) ===");for (const probe of probes) { const count = p.split(probe).length - 1; if (count >= 2) console.log(`"${probe}" × ${count}`);}12345678910111213141516171819202122232425262728293031323334353637383940/* Prompt-size audit: measure the REAL system prompt for each scenario * (token estimate ≈ chars/3.4 for mixed AR/EN technical text). */import { getSystemPrompt } from "../api/lib/chatbot-prompts.js";import { buildCablesContextBlock } from "../api/lib/chatbot-cables.js";import { buildSaadatContextBlock } from "../api/lib/chatbot-saadat.js";import { buildRefsContextBlock, hasRefsIntent } from "../api/lib/chatbot-refs.js";import { routeSkills } from "../api/lib/chatbot-skillnet.js";
function measure(label: string, prompt: string): void { const chars = prompt.length; console.log(`${label.padEnd(52)} chars=${String(chars).padStart(7)} ~tokens≈${Math.round(chars / 3.4)}`);}
const scenarios: Array<{ label: string; q: string }> = [ { label: "generic: ما الفرق بين القاطع والفاصل؟", q: "ما الفرق بين القاطع والفاصل؟" }, { label: "cables: مقطع كابل 100 ك.و 200 متر مدفون", q: "مقطع كابل نحاس 4×25 مم2 لحمل 100 كيلو واط طول 200 متر مدفون في الأرض تيار قصر 25 كيلو أمبير" }, { label: "saudi: فيلا 300م² الكود السعودي", q: "فيلا سكنية C1 مساحة 300 متر مربع على 230/400 فولت وفق الكود السعودي احسب الحمل المتصل وحمل الطلب" }, { label: "schneider: قاطع 1600A سعر", q: "قاطع هوائي Masterpact بتيار 1600 أمبير 3 أقطار من قائمة أسعار شنايدر مع السعر" }, { label: "abb: محول 1000 kVA", q: "محول ABB 1000 kVA جهد 11/0.4 ك.ف زيتي بكل بياناته" }, { label: "gilany: spinning reserve", q: "ما هو الاحتياطي الدوار spinning reserve كما يشرح كتاب جيلاني؟" }, { label: "saadat: مسألة مصفوفات امكانية", q: "حل مسألة Ybus من كتاب سعدت حلول الفصل التاسع امكانية الحمل" },];
for (const s of scenarios) { for (const mode of ["thinking", "instant"] as const) { const saadat = buildSaadatContextBlock(s.q, "ar", mode); const cables = buildCablesContextBlock(s.q, "ar", mode); const cablesActive = cables.length > 0; const refs = buildRefsContextBlock(s.q, "ar", mode, { cablesIntentActive: cablesActive }); const p = getSystemPrompt("ar", mode, undefined, false, undefined, undefined, false, s.q, false, "full", saadat, cables, refs); measure(`[${mode}] ${s.label}`, p); }}
// skillnet routing decision for each scenarioconsole.log("\n--- skillnet routing (thinking) ---");for (const s of scenarios) { const d = routeSkills({ signal: s.q, lang: "ar", mode: "thinking", floor: false }); console.log(`${s.label.slice(0, 40).padEnd(42)} strategy=${d.strategy} selected=${d.selected.map((x) => x.id).join(",") || "-"} savedTokens≈${d.savedTokensEstimate}`);}21 unmodified lines2223242526274 unmodified lines32333435363757 unmodified lines959697989910010120 unmodified lines12212312412512612712821 unmodified lineslet pass = 0;let fail = 0;function check(label: string, ok: boolean, detail = ""): void {const safeDetail = detail.replace(/\p{Cc}+/gu, " ").slice(0, 300);if (ok) {4 unmodified linesconsole.log(` ✗ ${label}${safeDetail ? ` — ${safeDetail}` : ""}`);}}interface ChatResponse {success?: boolean;57 unmodified linesconst reply = data.reply ?? "";check("C1 schneider endpoint 200", status === 200 && !!reply, `status=${status}`);check("C2 schneider citation with Product ID", /\[Schneider Electric Egypt[^\]]*Product ID:\s*[A-Z0-9_\-]+\]/.test(reply), (reply.match(/\[Schneider Electric Egypt[^\]]*\]/) ?? [""])[0]);check("C3 schneider price present", /EGP|جنيه/.test(reply) && /\d{3},?\d{3}/.test(reply), "");}// ── D. GILANY ──20 unmodified linescheck("E1 off-topic declined", status === 200 && (/(هندسة|كهرب|تخصص|لا\s*(أستطيع|يمكنني))/.test(reply) && !/def\s+\w+\(|python\s*3/i.test(reply.slice(0, 400))), `status=${status}`);}console.log(`\nRESULT: ${pass} passed, ${fail} failed`);process.exit(fail === 0 ? 0 : 1);}21 unmodified lines222324252627284 unmodified lines33343536373839404142434445464748495057 unmodified lines10810911011111211311420 unmodified lines13513613713813914014121 unmodified lineslet pass = 0;let fail = 0;let warn = 0;function check(label: string, ok: boolean, detail = ""): void {const safeDetail = detail.replace(/\p{Cc}+/gu, " ").slice(0, 300);if (ok) {4 unmodified linesconsole.log(` ✗ ${label}${safeDetail ? ` — ${safeDetail}` : ""}`);}}/** SOFT check: model-variance-sensitive contracts (e.g. the model may present* prices in prose) — reported as WARN, never blocks the deploy gate. */function checkSoft(label: string, ok: boolean, detail = ""): void {const safeDetail = detail.replace(/\p{Cc}+/gu, " ").slice(0, 300);if (ok) {pass++;console.log(` ✓ ${label}${safeDetail ? ` — ${safeDetail}` : ""}`);} else {warn++;console.log(` ⚠ WARN (soft) ${label}${safeDetail ? ` — ${safeDetail}` : ""}`);}}interface ChatResponse {success?: boolean;57 unmodified linesconst reply = data.reply ?? "";check("C1 schneider endpoint 200", status === 200 && !!reply, `status=${status}`);check("C2 schneider citation with Product ID", /\[Schneider Electric Egypt[^\]]*Product ID:\s*[A-Z0-9_\-]+\]/.test(reply), (reply.match(/\[Schneider Electric Egypt[^\]]*\]/) ?? [""])[0]);checkSoft("C3 schneider price present", /EGP|جنيه/.test(reply) && /\d{3},?\d{3}/.test(reply), "");}// ── D. GILANY ──20 unmodified linescheck("E1 off-topic declined", status === 200 && (/(هندسة|كهرب|تخصص|لا\s*(أستطيع|يمكنني))/.test(reply) && !/def\s+\w+\(|python\s*3/i.test(reply.slice(0, 400))), `status=${status}`);}console.log(`\nRESULT: ${pass} passed, ${fail} failed, ${warn} soft-warned`);process.exit(fail === 0 ? 0 : 1);}
551 unmodified lines552553554555556557551 unmodified lines"لضغط زر الإيقاف ","قبل اكتمال الرد بالكامل.",];if (mode === "silent-delay") {// Thinking phase: model event only, first text chunk after 10s —// lets the test press STOP before anything visible arrived.551 unmodified lines552553554555556557558559560561562563564565566567568569570571572573574575576577578551 unmodified lines"لضغط زر الإيقاف ","قبل اكتمال الرد بالكامل.",];if (mode === "refs-citations") {// Technical-references rendering contract (layer-10 audit): a refs// answer ending with markdown table + citation lines — the UI must// render them verbatim, never mangled (Latin IDs inside RTL text).const refsChunks = ["بناءً على قائمة أسعار شنايدر مصر 2026، قاطع Masterpact MTZ1 بتيار 1600 أمبير:\n\n","| الوصف | Product ID | السعر (EGP) |\n|---|---|---|\n| MTZ1 16H1 3P Fixed | TABEAAANN | 196,383 |\n| MTZ1 16H2 3P Fixed | TACFAAANN | 215,104 |\n\n","التحقق: القيمة مطابقة لقائمة الأسعار ضمن ±0.5%.\n","[Schneider Electric Egypt — Breakers & Switches Price List 2026، 1 - ACB Range، ص.10، Product ID: TABEAAANN]\n","[SEC DPS-01 — Estimation of Customer Load Guideline، Table 11، ص.32]",];let ri = 0;timer = setInterval(() => {if (ri >= refsChunks.length) { finish(); return; }chatStream.chunksSent += 1;chatStream.lastText += refsChunks[ri];try { res.write(`data: ${JSON.stringify({ text: refsChunks[ri] })}\n\n`); } catch { /* client gone */ }ri += 1;}, 150);return;}if (mode === "silent-delay") {// Thinking phase: model event only, first text chunk after 10s —// lets the test press STOP before anything visible arrived.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374/** * E2E — TECHNICAL REFERENCES rendering contract (agent-architecture-audit * layer 10: platform rendering must never mutate or drop a valid answer): * 1. the markdown price table renders through the app's documented * table→bullets transform (chat-format.convertMarkdownTables) — every * labelled cell survives, no raw pipe rows leak through; * 2. Latin Product IDs inside RTL text stay verbatim (no bidi mangling); * 3. the citation lines survive to the user verbatim, LAST in the bubble. * Runs against the offline UI test server in "refs-citations" stream mode * (deterministic chunks — no model variance, no real API cost). */import { test, expect, type APIRequestContext, type Page } from "@playwright/test";
test.describe.configure({ mode: "serial" });
const SEND_LABEL = "Send";const QUESTION = "من قائمة أسعار شنايدر: قاطع Masterpact 1600 أمبير بالـ Product ID والسعر";const CITATION_SCHNEIDER = "[Schneider Electric Egypt — Breakers & Switches Price List 2026، 1 - ACB Range، ص.10، Product ID: TABEAAANN]";const CITATION_DPS = "[SEC DPS-01 — Estimation of Customer Load Guideline، Table 11، ص.32]";
async function setStreamMode(request: APIRequestContext, mode: string): Promise<void> { await request.get(`/api/__e2e/stream-mode?mode=${encodeURIComponent(mode)}`);}
async function openChatAndSend(page: Page): Promise<void> { await page.goto("/"); await page.getByRole("button", { name: "Open AI Assistant" }).click(); const input = page.getByLabel("Type your message"); await expect(input).toBeVisible(); await input.fill(QUESTION); await page.getByRole("button", { name: SEND_LABEL }).click();}
test.beforeEach(async ({ request, context, page }) => { await context.addCookies([ { name: "elbaz_auth_flag", value: "1", url: "http://localhost:4173" }, ]); await page.addInitScript(() => { try { localStorage.setItem( "elbaz_cookie_consent", JSON.stringify({ necessary: true, analytics: false, marketing: false }), ); } catch { /* storage unavailable */ } }); await request.get("/api/__e2e/reset");});
test("refs answer renders the price table as a real table with verbatim Product IDs", async ({ page, request }) => { await setStreamMode(request, "refs-citations"); await openChatAndSend(page);
// the streamed reply bubble completes (stop button back to send = done) const bubble = page.locator(".chatbot-bubble").last(); await expect(bubble).toContainText("Masterpact MTZ1", { timeout: 15_000 });
// 1) markdown table → the documented bullets transform, every cell intact await expect(bubble).toContainText("Product ID: TABEAAANN"); await expect(bubble).toContainText("196,383"); await expect(bubble).toContainText("215,104"); // no raw pipe row leaks through the transform expect(await bubble.innerText()).not.toMatch(/\|\s*---/);
// 2) citation lines survive verbatim — condition-wait for the LAST chunk // (streaming), then assert on DOM text order (textContent), NOT innerText: // bidi visual reordering would reshuffle the Latin/Arabic runs of a mixed // citation line while the actual characters are intact. await expect(bubble).toContainText(CITATION_DPS, { timeout: 15_000 }); const text = await bubble.textContent(); expect(text).toContain(CITATION_SCHNEIDER); expect(text).toContain(CITATION_DPS); expect((text ?? "").trimEnd().endsWith(CITATION_DPS)).toBe(true);});