File size: 14,284 Bytes
ef987bb | 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 | const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');
const { chromium } = require('playwright');
function assert(ok, msg) { if (!ok) throw new Error(msg); }
function findSVG() { const f = fs.readdirSync(process.cwd()).find(x => x.toLowerCase().endsWith('.svg')); assert(f, 'missing SVG'); return path.join(process.cwd(), f); }
async function test(id, fn) { try { await fn(); console.log(`${id} PASS`); } catch (e) { console.error(`${id} FAIL: ${e.message}`); process.exitCode = 1; } }
(async () => {
const browser = await chromium.launch({ headless: true, args: ['--no-sandbox', '--disable-dev-shm-usage'] });
const page = await browser.newPage({ viewport: { width: 1200, height: 1000 } });
await page.goto(pathToFileURL(findSVG()).href, { waitUntil: 'domcontentloaded' });
const normalizedText = async () => (await page.locator('svg').textContent()).toLowerCase().replace(/\s+/g, ' ');
// ENHANCED_CASE_1: all five explicitly named roles/departments are represented.
// Labels may sit inside nodes or lane headers; their exact y coordinate is not an API contract.
await test('ENHANCED_CASE_1', async () => {
const text = await normalizedText();
const groups = [/(分诊|triage).*(护士|nurse)/, /(急诊.*医生|emergency doctor|doctor)/, /(检查|检验|lab|imaging|exam)/, /(专科|手术|specialist|surgery)/, /(行政|出入院|admin|admission|discharge)/];
assert(groups.every(re => re.test(text)), 'one or more of the five required roles/departments is missing');
});
// ENHANCED_CASE_2: the diagram exposes the major processing and terminal destinations.
await test('ENHANCED_CASE_2', async () => {
const text = await normalizedText();
const destinations = [/(分诊|triage)/, /(医生|doctor)/, /(检查|检验|lab|test|exam)/, /(专科|手术|specialist|surgery)/, /(行政|admin|admission)/, /(出院|discharge)/, /(转院|transfer)/, /(死亡|death)/, /(病房|ward)/];
assert(destinations.every(re => re.test(text)), 'one or more required workflow destinations/outcomes is missing');
assert(await page.locator('svg rect,svg path').count() >= 8, 'workflow lacks enough rendered process nodes');
});
// ENHANCED_CASE_3: triage colors and directional branch connectors are rendered as SVG behavior, not prose only.
await test('ENHANCED_CASE_3', async () => {
const s = await page.evaluate(() => {
const els = [...document.querySelectorAll('svg *')];
const paints = els.map(e => `${e.getAttribute('fill') || ''} ${e.getAttribute('stroke') || ''} ${getComputedStyle(e).fill} ${getComputedStyle(e).stroke}`.toLowerCase());
const has = re => paints.some(x => re.test(x));
const rgb = paints.flatMap(x => [...x.matchAll(/rgba?\((\d+),\s*(\d+),\s*(\d+)/g)].map(m => m.slice(1,4).map(Number)));
return { red: has(/red|#f00/) || rgb.some(([r,g,b]) => r >= g && r >= b && r-b >= 12), yellow: has(/yellow|#ff0/) || rgb.some(([r,g,b]) => r > 200 && g > 200 && b < Math.min(r,g)-12), green: has(/green|#0f0/) || rgb.some(([r,g,b]) => g >= r && g >= b && g-r >= 12), connectors: document.querySelectorAll('path,line,polyline').length, arrows: document.querySelectorAll('marker,[marker-end],[marker-start]').length };
});
assert(s.red && s.yellow && s.green, 'red/yellow/green triage coding is incomplete');
assert(s.connectors >= 8 && s.arrows >= 1, 'insufficient directional connectors for the workflow branches');
});
await test('ENHANCED_CASE_4', async () => {
const graph = await page.evaluate(() => ({
lanes: [...document.querySelectorAll('[data-lane]')].map(e => ({name:e.dataset.lane,y:e.getBoundingClientRect().y})),
nodes: [...document.querySelectorAll('[data-node]')].map(e => { const r=e.getBoundingClientRect(); return {id:e.dataset.node,owner:e.dataset.laneOwner,stage:Number(e.dataset.stage),x:r.x+r.width/2,rect:{left:r.left,right:r.right,top:r.top,bottom:r.bottom}} }),
edges: [...document.querySelectorAll('[data-from][data-to]')].map(e => {
const a=document.querySelector(`[data-node="${e.dataset.from}"]`), b=document.querySelector(`[data-node="${e.dataset.to}"]`);
const ar=a&&a.getBoundingClientRect(), br=b&&b.getBoundingClientRect();
let p1,p2;
const tag=e.tagName.toLowerCase(), point=(x,y)=>{const q=e.ownerSVGElement.createSVGPoint();q.x=x;q.y=y;return q.matrixTransform(e.getScreenCTM())};
if(tag==='line') { p1=point(e.x1.baseVal.value,e.y1.baseVal.value);p2=point(e.x2.baseVal.value,e.y2.baseVal.value); }
else if(tag==='path') { const n=e.getTotalLength(); const a=e.getPointAtLength(0),b=e.getPointAtLength(n);p1=point(a.x,a.y);p2=point(b.x,b.y); }
else if(tag==='polyline') { const q=e.points;p1=q.length&&point(q[0].x,q[0].y);p2=q.length&&point(q[q.length-1].x,q[q.length-1].y); }
const near=(p,r)=>p&&r&&p.x>=r.left-5&&p.x<=r.right+5&&p.y>=r.top-5&&p.y<=r.bottom+5&&Math.min(Math.abs(p.x-r.left),Math.abs(p.x-r.right),Math.abs(p.y-r.top),Math.abs(p.y-r.bottom))<=5;
return {key:`${e.dataset.from}->${e.dataset.to}`, attached:near(p1,ar)&&near(p2,br)};
})
}));
assert(graph.lanes.length === 5 && new Set(graph.lanes.map(x=>x.y)).size === 5, 'five distinct horizontal lanes are required');
const requiredNodes=['triage','waiting','doctor','lab','resuscitation','diagnosis','surgery','death','discharge','admission','transfer','ward'];
for (const id of requiredNodes) assert(graph.nodes.some(n=>n.id===id), `missing structural node ${id}`);
const laneRects=await page.evaluate(() => Object.fromEntries([...document.querySelectorAll('[data-lane]')].map(e=>{const r=e.getBoundingClientRect();return [e.dataset.lane,{left:r.left,right:r.right,top:r.top,bottom:r.bottom}]})));
for(const n of graph.nodes){const r=laneRects[n.owner];assert(r&&n.rect.left>=r.left-1&&n.rect.right<=r.right+1&&n.rect.top>=r.top-1&&n.rect.bottom<=r.bottom+1,`node ${n.id} is outside declared lane ${n.owner}`);assert(n.stage>=1&&n.stage<=6,`node ${n.id} has invalid stage`)}
const stageX={};for(const n of graph.nodes)(stageX[n.stage]??=[]).push(n.x);let previous=-Infinity;for(const stage of [1,2,3,4,5,6]){const avg=stageX[stage].reduce((a,b)=>a+b,0)/stageX[stage].length;assert(avg>previous,`stage ${stage} is not visibly to the right`);previous=avg}
const expected=['triage->resuscitation','triage->doctor','triage->waiting','waiting->doctor','doctor->resuscitation','doctor->lab','doctor->discharge','lab->diagnosis','lab->surgery','resuscitation->diagnosis','resuscitation->resuscitation','resuscitation->death','diagnosis->discharge','diagnosis->admission','diagnosis->surgery','diagnosis->transfer','admission->ward'];
assert(graph.edges.length >= expected.length, `expected at least ${expected.length} semantic branches`);
const terminalNodes = new Set(['death', 'discharge', 'transfer']);
assert(graph.edges.every(edge => !terminalNodes.has(edge.key.split('->')[0])),
'terminal outcomes cannot have an outgoing workflow branch');
for (const edge of expected) {
const found=graph.edges.find(x=>x.key===edge); assert(found, `missing directed branch ${edge}`); assert(found.attached, `connector endpoints do not attach to declared nodes: ${edge}`);
}
});
await test('VISIBLE_DIRECTED_GRAPH',async()=>{
const expectedOwners={triage:'triage',waiting:'triage',doctor:'doctor',diagnosis:'doctor',lab:'lab',resuscitation:'specialist',surgery:'specialist',ward:'specialist',death:'admin',discharge:'admin',admission:'admin',transfer:'admin'};
const checks=await page.evaluate(expectedOwners=>{
const visible=element=>{
for(let node=element;node;node=node.parentElement){const style=getComputedStyle(node);if(style.display==='none'||style.visibility==='hidden'||+style.opacity===0)return false}
return true;
};
const swatch = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
swatch.width = swatch.height = 1;
const context = swatch.getContext('2d', {willReadFrequently: true});
const sample = color => {
context.clearRect(0, 0, 1, 1);
context.fillStyle = 'transparent';
context.fillStyle = color;
context.fillRect(0, 0, 1, 1);
return [...context.getImageData(0, 0, 1, 1).data];
};
const paintedMarker = marker => {
if (!(marker instanceof SVGMarkerElement) || !visible(marker) ||
marker.markerWidth.baseVal.value <= 0 || marker.markerHeight.baseVal.value <= 0) return false;
return [...marker.querySelectorAll('path,polygon,polyline,line,rect,circle,ellipse,use,text')].some(shape => {
if (!visible(shape)) return false;
const box = shape.getBBox();
const style = getComputedStyle(shape);
const hasPaint = (paint, opacity) => +opacity > 0 &&
(paint.startsWith('url(') || paint.startsWith('context-') || sample(paint)[3] > 0);
return (box.width > 0 && box.height > 0 && hasPaint(style.fill, style.fillOpacity)) ||
((box.width > 0 || box.height > 0) && parseFloat(style.strokeWidth) > 0 &&
hasPaint(style.stroke, style.strokeOpacity));
});
};
const nodes=[...document.querySelectorAll('[data-node]')],edges=[...document.querySelectorAll('[data-from][data-to]')];
const lanes=[...document.querySelectorAll('[data-lane]')].sort((a,b)=>a.getBoundingClientRect().y-b.getBoundingClientRect().y).map(e=>e.dataset.lane);
return {lanes,owners:nodes.every(node=>node.dataset.laneOwner===expectedOwners[node.dataset.node]&&visible(node)),
edges:edges.map(edge=>{
const style=getComputedStyle(edge),match=style.markerEnd.match(/#([^")]+)/);
const marker=match&&document.getElementById(match[1]);
const paintId=style.stroke.match(/#([^\")]+)/);
const paint=paintId&&document.getElementById(paintId[1]);
const findStops = (element, seen = new Set()) => {
if (!element || seen.has(element)) return [];
seen.add(element);
const stops = [...element.querySelectorAll('stop')];
const ref = element.getAttribute('href') || element.getAttribute('xlink:href');
return stops.length || !ref?.startsWith('#') ? stops : findStops(document.getElementById(ref.slice(1)), seen);
};
const stops = findStops(paint);
const strokeColors = (stops.length ? stops
.filter(stop => +getComputedStyle(stop).stopOpacity > 0)
.map(stop => getComputedStyle(stop).stopColor) : paint?.localName === 'pattern' ? [] : [style.stroke]).map(sample);
const label=[...document.querySelectorAll('[data-edge-label]')].find(item=>item.dataset.edgeLabel===edge.dataset.from+'->'+edge.dataset.to);
const obstacles=nodes.filter(node=>![edge.dataset.from,edge.dataset.to].includes(node.dataset.node)).map(node=>node.getBoundingClientRect());
let blocked=false;
const length=edge.getTotalLength();
for(let distance=0;distance<=length;distance+=2){
const point=edge.getPointAtLength(distance).matrixTransform(edge.getScreenCTM());
if(obstacles.some(box=>point.x>box.left+3&&point.x<box.right-3&&point.y>box.top+3&&point.y<box.bottom-3)){blocked=true;break;}
}
return {visible:(visible(edge)&&(paint?.localName === 'pattern' ? paint.children.length > 0 : strokeColors.some(color => color[3] > 0)))&&+style.strokeOpacity>0&&parseFloat(style.strokeWidth)>0,
arrow:paintedMarker(marker),label:!!label&&visible(label)&&label.textContent.trim().length>0,
text:label?.textContent||'',key:edge.dataset.from+'->'+edge.dataset.to,strokeColors,blocked};
})};
},expectedOwners);
assert(JSON.stringify(checks.lanes)===JSON.stringify(['triage','doctor','lab','specialist','admin']),'lane order must match roles');
assert(checks.owners,'nodes must have correct semantic ownership and visibility');
assert(checks.edges.every(edge=>edge.visible&&edge.arrow&&edge.label),'every edge needs visible stroke, actual arrow and labeled condition');
assert(checks.edges.every(edge=>!edge.blocked),'connectors must not cross unrelated process nodes');
const meanings={
'triage->resuscitation':/危重|critical|life[- ]threatening/i,'triage->doctor':/严重|severe|urgent|serious/i,'triage->waiting':/轻症|minor|mild|low[- ]acuity/i,
'waiting->doctor':/候诊|初诊|wait|consult/i,'doctor->resuscitation':/急救|resusc|emerg/i,'doctor->lab':/检查|检验|test|exam/i,
'doctor->discharge':/轻症|处方|minor|prescription/i,'lab->diagnosis':/正常|\bnormal\b|within\s+(?:the\s+)?(?:reference\s+)?range|unremarkable/i,'lab->surgery':/异常|abnormal|out(?:side|\s+of)\s+(?:the\s+)?(?:reference\s+)?range/i,
'resuscitation->diagnosis':/稳定|stable|stabil/i,'resuscitation->resuscitation':/恶化|再次|worsen|deterior|repeat/i,
'resuscitation->death':/无效|死亡|unsuccess|death|ineffective/i,'diagnosis->discharge':/门诊|出院|outpatient|discharge/i,
'diagnosis->admission':/住院|admi/i,'diagnosis->surgery':/手术|surg/i,'diagnosis->transfer':/转院|transfer/i,'admission->ward':/病房|护理|ward|handover/i,
};
for(const edge of checks.edges) if(meanings[edge.key]) assert(meanings[edge.key].test(edge.text),`incorrect branch condition ${edge.key}`);
for(const [key,index]of [['triage->resuscitation',0],['triage->doctor',1],['triage->waiting',2]]){
const colors=checks.edges.find(edge=>edge.key===key).strokeColors;
assert(colors.length>0,'triage edge requires discernible severity paint');
for(const [r,g,b,alpha] of colors){
assert(alpha > 0, 'triage paint must resolve to a visible color');
assert(index===0?r>g+20&&r>b+20:index===1?r>150&&g>100&&b<Math.min(r,g)-30:g>r+20&&g>b+20,`incorrect severity color ${key}`);
}
}
fs.mkdirSync('/logs/verifier/visual-audit',{recursive:true});
await page.screenshot({path:'/logs/verifier/visual-audit/emergency-swimlane.png'});
});
await browser.close(); if (process.exitCode) process.exit(process.exitCode);
})().catch(e => { console.error(e.stack || e); process.exit(1); });
|