feat: collect BPM field evidence and equip ZCode mapping assistant
This commit is contained in:
1 parent
24dbbb74c3
commit
d4070e08f9
30 files changed
+453
-61
No files matched your search
@@ -7,6 +7,15 @@ const {FileArea}=require('../../src/modules/storage/files.cjs');
|
||||
const {MailStore}=require('../../src/modules/mail/store.cjs');
|
||||
const {loadData,loadForm}=require('../../src/modules/bpm/order-form.cjs');
|
||||
|
||||
test('historical fields use a distinct readonly chain and method; pending-task boundaries stay strict',async()=>{
|
||||
const {historyURL}=require('../../src/modules/bpm/order-form.cjs'),target='https://bpm.skyworthdigital.com/YZSoft/Forms/Read.aspx?tid=21',entry='https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl='+encodeURIComponent(target)+'&todo_token=fixture-secret&todo_account=fixture',final='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21';
|
||||
const calls=[],request={get:async url=>({status:()=>url===final?200:302,headers:()=>({location:url===entry?target:final}),body:async()=>Buffer.from('form')}),post:async(url,options)=>{calls.push(options.data);return {status:()=>200,body:async()=>Buffer.from('{"success":true,"Tables":[]}')};}};
|
||||
assert.equal((await loadForm(request,entry,historyURL,{history:true})).url.href,final);
|
||||
await loadData(request,new URL(final),{history:true});assert.match(calls[0],/<Method>GetFormReadData<\/Method><TID>21<\/TID>/);
|
||||
assert.throws(()=>detailURL(final));assert.throws(()=>historyURL(final+'&pid=99'));assert.throws(()=>historyURL(final+'&action=submit'));
|
||||
await assert.rejects(loadForm({...request,get:async()=>({status:()=>302,headers:()=>({location:final.replace('tid=21','tid=22')})})},entry,historyURL,{history:true}),/标识/);
|
||||
});
|
||||
|
||||
test('transient todo SSO entry follows only matching process and form and never persists its token',async()=>{
|
||||
const target='https://bpm.skyworthdigital.com/YZSoft/Forms/Process.aspx?tid=21&pid=11',entry='https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl='+encodeURIComponent(target)+'&todo_token=fixture-secret&todo_account=fixture';
|
||||
const final='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/test.aspx?tid=21&pid=11',calls=[];
|
||||
@@ -50,7 +59,7 @@ async function captureFixture(t,html,tables){
|
||||
const calls=[],server=http.createServer((req,res)=>{calls.push([req.method,req.url]);res.setHeader('Content-Type',req.method==='POST'?'application/json':'text/html');res.end(req.method==='POST'?JSON.stringify({success:true,Tables:tables}):html);});
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
|
||||
const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})};
|
||||
const provider=new BpmOrderProvider({manager,allowLocal:true}),capture=()=>provider.capture({id:'c'},{},{detailUrl:`http://127.0.0.1:${server.address().port}/form.aspx?tid=1&pid=2`,processVersion:'1.4',title:'订单号:123'});
|
||||
const provider=new BpmOrderProvider({manager,allowLocal:true}),capture=(fieldsOnly=false)=>provider[fieldsOnly?'captureFields':'capture']({id:'c'},{},{detailUrl:`http://127.0.0.1:${server.address().port}/form.aspx?tid=1&pid=2`,processVersion:'1.4',title:'订单号:123'});
|
||||
return {provider,capture,calls};
|
||||
}
|
||||
|
||||
@@ -64,6 +73,15 @@ test('detail snapshot preserves exact DOM row correspondence and indexed catalog
|
||||
assert.deepEqual(fixture.calls,[['GET','/form.aspx?tid=1&pid=2'],['POST','/YZSoft/BPM/XMLService/DataProvider.ashx']]);
|
||||
});
|
||||
|
||||
test('field-only evidence expands server data rows without claiming PDF layout readiness',async t=>{
|
||||
const f=await captureFixture(t,'<table><tr><td>订单号</td><td><input xdatabind="Order.Number"></td></tr><tr><td><input xdatabind="Lines.Qty"></td></tr></table>',[{TableName:'Order',FormTable:true,Rows:[{Number:'123'}]},{TableName:'Lines',FormTable:true,Rows:[{Qty:0},{Qty:9}]}]);
|
||||
const result=await f.capture(true);
|
||||
assert.equal(result.snapshot.purpose,'field-mapping');assert.equal(result.snapshot.html,undefined);
|
||||
assert.equal(result.sample.fields['Order.Number'],'123');assert.equal(result.sample.fields['Lines[0].Qty'],'0');
|
||||
assert.equal(result.sample.fields['Lines[1].Qty'],'9');assert.equal(f.provider.capabilities().pdfExport,false);
|
||||
await assert.rejects(f.capture(),/明细|多行/);
|
||||
});
|
||||
|
||||
test('capture blocks unsupported or ambiguous detail layouts instead of returning an archivable snapshot',async t=>{
|
||||
const input=key=>'<input xdatabind="Lines.'+key+'">',row=content=>'<tr><td>'+content+'</td></tr>',both=input('Item')+input('Qty');
|
||||
for(const [name,html,rows]of [
|
||||
|
||||
@@ -27,3 +27,15 @@ test('chat UI persists conversations, shows escaped messages and explicit fixed
|
||||
await page.getByLabel('发送给 ZCode',{exact:true}).fill('挂起诊断');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'停止回复',exact:true}).click();await page.getByText('已停止本轮回复。',{exact:true}).waitFor();
|
||||
await fs.mkdir('output/verification',{recursive:true});await page.screenshot({path:'output/verification/zcode-chat-desktop.png',fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
|
||||
test('a long action displays persisted sampling progress before its POST completes',{timeout:60000},async t=>{
|
||||
const {base,store}=await fixture(t);store.saveSettings({...store.settings(),enabled:true,runtimePath:process.execPath,apiBase:'https://models.example/v1',model:'fixture',apiKey:'PRIVATE_PROGRESS_KEY',allowActions:true});
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'),browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();page.setDefaultTimeout(8000);
|
||||
await page.goto(base+'/#assistant');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'新建对话',exact:true}).click();await page.getByLabel('发送给 ZCode',{exact:true}).fill('读取状态');await page.getByRole('button',{name:'发送',exact:true}).click();await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).waitFor();
|
||||
let started=false,finished=false,release;const gate=new Promise(resolve=>release=resolve);t.after(()=>release());
|
||||
await page.route('**/api/assistant/conversations/*',async route=>{const response=await route.fetch(),data=await response.json();if(started)for(const turn of data.turns)for(const action of turn.actions||[])Object.assign(action,{status:finished?'success':'running',progress:{completed:1,total:3,captured:1,failed:0}});await route.fulfill({json:data});});
|
||||
await page.route('**/api/assistant/conversations/*/actions/*/execute',async route=>{started=true;await gate;finished=true;await route.fulfill({json:{status:'success'}});});
|
||||
await page.getByRole('button',{name:'执行:检查存储连接',exact:true}).click();
|
||||
await page.getByText('采样进度 1 / 3,成功 1,受阻 0',{exact:true}).waitFor({timeout:4500});assert.equal(finished,false);
|
||||
release();await page.getByText('操作已完成',{exact:true}).waitFor();
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
|
||||
const principal={user:{id:'admin',username:'admin',role:'admin'},sessionId:'test-session'};
|
||||
function fixture(t){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'field-skill-')),store=new RuleStore(dir,{clock:()=>new Date('2026-10-20T02:00:00Z')});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const connection={id:'c1',owner:'admin',status:'connected'},workspace={getConnection:()=>connection,snapshot:()=>({connections:[connection]})};
|
||||
const row={source:'todo',instanceId:'1',taskId:'1',revision:'1',processName:'备损订单评审',processVersion:'2.0',nodeName:'订单专员(订单通知书)',receivedAt:'2026-10-01T02:00:00Z',title:'订单号:123机芯号:ABC客户简称:PRIVATE_CUSTOMER总数量:0',serialNum:'TEST'};
|
||||
let captures=0;const provider={scan:async()=>[row,{...row,taskId:'2',instanceId:'2'}],captureFields:async(c,p,r)=>{captures++;return {sample:{...r,connectionId:c.id,fields:{'Order.Number':'123','Order.Quantity':'0','Order.Amount':'999'}},snapshot:{purpose:'field-mapping',processVersion:r.processVersion,fields:[{path:'Order.Number',label:'订单号',value:'123'},{path:'Order.Quantity',label:'数量',value:'0'},{path:'Order.Amount',label:'总金额',value:'999'}]}};}};
|
||||
const execution=new OrderExecutionCoordinator({store,workspace,provider,archive:{},mail:{},clock:()=>new Date('2026-10-20T02:00:00Z')});
|
||||
return {deps:{workspace,orderRules:store,orderExecution:execution},store,connection,captures:()=>captures};
|
||||
}
|
||||
test('ZCode project skill collects one sample per missing version and only prepares checked drafts',async t=>{
|
||||
const skill=require('../../src/modules/assistant/field-skill.cjs'),f=fixture(t),progress=[];
|
||||
const report=await skill.collect(f.deps,'c1',principal,'action1',p=>progress.push(p));
|
||||
assert.equal(report.captured,1);assert.equal(f.captures(),1);assert.equal(progress.at(-1).completed,1);
|
||||
const sample=f.store.all('capture-samples')[0],guard=skill.guardMapping(f.deps,sample.id,principal.user);
|
||||
const result=await skill.prepare(f.deps,sample.id,principal,'prepare1',guard);
|
||||
assert.equal(result.status,'checked');assert.equal(f.store.all('field-mapping-drafts').length,1);
|
||||
assert.equal(f.store.all('field-adapters').length,0);assert.deepEqual(f.store.all('orders'),[]);assert.deepEqual(f.store.all('batches'),[]);
|
||||
const context=JSON.stringify(skill.coverage(f.deps,principal.user));assert.doesNotMatch(context,/PRIVATE_CUSTOMER|Order\.Number|999|订单号:123/);
|
||||
assert.equal((await skill.collect(f.deps,'c1',principal,'action2',()=>{})).captured,0);assert.equal(f.captures(),1);
|
||||
await assert.rejects(skill.prepare(f.deps,sample.id,principal,'stale',guard),e=>e.status===409);
|
||||
f.connection.status='disabled';assert.throws(()=>skill.guardMapping(f.deps,sample.id,principal.user),e=>e.status===403);
|
||||
});
|
||||
test('mapping recommendations keep ambiguous fields unresolved and never mix amount and quantity',()=>{
|
||||
const {recommend}=require('../../src/modules/assistant/field-skill.cjs');
|
||||
const r=recommend([{path:'A.Order',label:'订单号',value:'123'},{path:'B.Order',label:'订单号',value:'123'},{path:'Amount',label:'总金额',value:'10'},{path:'Qty',label:'数量',value:'0'}]);
|
||||
assert.equal(r.sources.orderNo,undefined);assert.equal(r.sources.quantity.path,'Qty');assert.equal(r.sources.totalAmount.path,'Amount');assert.ok(r.issues.length);
|
||||
assert.equal(recommend([{path:'ProductRequirement.Antennanum',label:'数量',value:'2'}]).sources.quantity,undefined);
|
||||
});
|
||||
test('application skill is versioned, injected into prompt and cannot enable native tools',()=>{
|
||||
const {projectSkills}=require('../../src/modules/assistant/skills.cjs'),{prompt,runtimeConfig}=require('../../src/modules/assistant/zcode-runtime.cjs');
|
||||
const skills=projectSkills();assert.equal(skills[0].id,'bpm-field-mapping');assert.match(skills[0].sha256,/^[a-f0-9]{64}$/);
|
||||
const input=prompt({text:'采集字段样本',history:[],context:{},config:{allowActions:true}});
|
||||
assert.match(input,/BPM 信息识别技能/);assert.match(input,/collect_field_samples/);assert.match(input,/HA/);
|
||||
const config=runtimeConfig({timeoutSeconds:30},'test');assert.equal(config.features.skill,false);assert.ok(config.permission.disallowedTools.includes('Skill'));
|
||||
});
|
||||
|
||||
test('historical evidence can check a mapping while real notification matching still rejects history',async t=>{
|
||||
const f=fixture(t),{recommend}=require('../../src/modules/assistant/field-skill.cjs'),row={source:'history',configurationOnly:true,instanceId:'1',taskId:'1',revision:0,connectionId:'c1',processName:'备损订单评审',processVersion:'2.0',nodeName:'历史查看(未提供办理节点)',receivedAt:'2026-10-01T00:00:00Z',timestampType:'process-start',serialNum:'TEST',title:'订单号:123机芯号:ABC',fields:{order:'123'}},snapshot={purpose:'field-mapping',processVersion:'2.0',fields:[{path:'order',label:'订单号',value:'123'}]};
|
||||
const sample=f.store.recordCapture({sample:row,snapshot,taskId:'h1'}),draft=f.store.saveMapping({processName:row.processName,processVersion:row.processVersion,sampleId:sample.id,sources:recommend(snapshot.fields).sources,version:0,idempotencyKey:'draft'},principal.user);
|
||||
const result=f.store.checkMapping({id:draft.id,version:draft.version,sampleId:sample.id,idempotencyKey:'check'},principal.user);
|
||||
assert.equal(result.valid,true);assert.equal(result.result.configurationOnly,true);assert.ok(result.result.warnings.length);
|
||||
assert.equal(f.store.capturedPreview(sample.id).valid,false);
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict');
|
||||
const {BpmHistoryClient,normalizeHistory,HISTORY_ROUTES}=require('../../src/modules/bpm/history-client.cjs');
|
||||
const raw=(version='1.4',id='21')=>({processName:'备损订单更改评审',processInstanceId:id,processVersion:version,startTime:'2026-10-20T10:00:00',serialNum:'TEST',subject:'订单号:123',businessKey:'https://bpm.skyworthdigital.com/sso/ssologin.aspx?ReturnUrl='+encodeURIComponent('https://bpm.skyworthdigital.com/YZSoft/Forms/Read.aspx?tid='+id)+'&todo_token=FIXTURE&todo_account=test'});
|
||||
test('history client queries only observed readonly sources and keeps latest version alternatives',async()=>{
|
||||
const calls=[];let disposed=false;
|
||||
const client=new BpmHistoryClient({requestFactory:async()=>({get:async(route,options)=>{calls.push({route,options});return {status:()=>200,body:async()=>Buffer.from(route==='/'?"Yiez.clientId='fixture';":JSON.stringify({total:4,children:[raw(),raw('1.3','22'),raw('1.4','23'),{...raw('1.5','24'),processName:'其他流程'}]}))};},dispose:async()=>{disposed=true;}})});
|
||||
const rows=await client.scan({},['备损订单更改评审']);assert.equal(rows.length,2);assert.equal(rows[0].source,'history');assert.equal(rows[0].configurationOnly,true);assert.equal(rows[0].timestampType,'process-start');assert.match(rows[0].nodeName,/未提供/);assert.equal(rows[0].receivedAt,'2026-10-20T02:00:00.000Z');
|
||||
assert.deepEqual(calls.map(c=>c.route),['/',HISTORY_ROUTES[0]]);assert.equal(calls[1].options.params.year,-1);assert.equal(calls[1].options.params.limit,100);assert.equal(disposed,true);
|
||||
assert.throws(()=>normalizeHistory({...raw(),processInstanceId:'22'}),e=>e.status===403);
|
||||
assert.throws(()=>normalizeHistory({...raw(),processVersion:''}),e=>e.status===502);
|
||||
});
|
||||
@@ -15,6 +15,30 @@ function fixture(t){
|
||||
}
|
||||
const list=f=>f.execution.listFieldSamples({connectionId:'c1',idempotencyKey:'list'},principal);
|
||||
const capture=(f,l,key='capture')=>f.execution.captureFieldSample({connectionId:'c1',listId:l.id,rowId:l.rows[0].id,idempotencyKey:key},principal);
|
||||
|
||||
test('configuration-only discovery can sample older pending tasks without executing historical orders',async t=>{
|
||||
const f=fixture(t);f.setRows([{...f.row,receivedAt:'2026-10-01T01:00:00Z'}, {...f.row,taskId:'wrong',nodeName:'其他节点'}]);
|
||||
const l=await f.execution.listFieldSamples({connectionId:'c1',scope:'configuration',idempotencyKey:'config-list'},principal);
|
||||
assert.equal(l.rows.length,2);assert.equal(l.scope,'configuration');
|
||||
const captured=await capture(f,l);assert.equal(captured.sample.taskId,'t1');
|
||||
for(const kind of ['execution-tasks','orders','batches'])assert.deepEqual(f.store.all(kind),[]);
|
||||
await assert.rejects(f.execution.listFieldSamples({connectionId:'c1',scope:'all-history',idempotencyKey:'bad'},principal),e=>e.status===400);
|
||||
await assert.rejects(f.execution.listFieldSamples({connectionId:'c1',idempotencyKey:'config-list'},principal),e=>e.status===409);
|
||||
});
|
||||
|
||||
test('history sampling keeps its source, rechecks the selected process and rejects changed or expired evidence',async t=>{
|
||||
for(const mode of ['valid','changed','expired']){
|
||||
const f=fixture(t),row={...f.row,source:'history',configurationOnly:true,timestampType:'process-start',nodeName:'历史查看(未提供办理节点)',receivedAt:'2025-10-01T01:00:00Z'};
|
||||
let historyCalls=0,fieldCalls=0;f.provider.scan=async()=>{throw Error('history must not use todo discovery');};
|
||||
f.provider.scanHistory=async(c,p,names)=>{historyCalls++;if(historyCalls>1)assert.deepEqual(names,[row.processName]);return [{...row,...(mode==='changed'&&historyCalls>1?{processVersion:'9.9'}:{})}];};
|
||||
f.provider.captureFields=async(c,p,r)=>{fieldCalls++;return {sample:{...r,connectionId:c.id,fields:{order:'SO-1'}},snapshot:{purpose:'field-mapping',processVersion:r.processVersion,fields:[{path:'order',value:'SO-1'}]}};};
|
||||
const listing=await f.execution.listFieldSamples({connectionId:'c1',scope:'history',idempotencyKey:'history'},principal);
|
||||
if(mode==='expired')f.setNow('2026-10-20T02:15:00Z');
|
||||
if(mode!=='valid'){await assert.rejects(capture(f,listing),e=>e.status===409);assert.equal(fieldCalls,0);assert.equal(f.store.all('capture-samples').length,0);continue;}
|
||||
const saved=await capture(f,listing);assert.equal(saved.sample.source,'history');assert.equal(saved.sample.configurationOnly,true);assert.equal(saved.sample.timestampType,'process-start');assert.equal(fieldCalls,1);assert.equal(f.counts().captures,0);
|
||||
for(const kind of ['execution-tasks','orders','batches'])assert.deepEqual(f.store.all(kind),[]);
|
||||
}
|
||||
});
|
||||
test('sample discovery filters historical, future, wrong scope and non-todo rows without execution writes',async t=>{
|
||||
const f=fixture(t),before=f.store.capabilities;
|
||||
f.setRows([f.row,{...f.row,taskId:'lower',receivedAt:f.store.snapshot().window.start},{...f.row,taskId:'now',receivedAt:'2026-10-20T02:00:00Z'},{...f.row,taskId:'old',receivedAt:'2026-10-18T01:00:00Z'},{...f.row,taskId:'future',receivedAt:'2026-10-20T02:00:01Z'},{...f.row,taskId:'wrong',nodeName:'其他节点'},{...f.row,taskId:'history',source:'history'},{...f.row,taskId:'invalid',receivedAt:'invalid'}]);
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
'use strict';
|
||||
const test=require('node:test'),assert=require('node:assert/strict'),{extractTitle}=require('../../src/modules/order-rules/title.cjs');
|
||||
test('order identifiers stop before unknown business text while summary keeps that text',()=>{
|
||||
for(const [tail,id]of [['123456 客户名称:测试公司','123456'],['123456|翻单| 总数:20000|','123456'],['123456产品线:测试平台方案:X','123456'],['123456参考订单:654321','123456'],['HA123456机芯号:ABC','HA123456']]){
|
||||
const r=extractTitle('订单号:'+tail);assert.equal(r.orders[0].orderNo,id);assert.equal(r.issues.length,0);assert.ok(r.brief.includes(tail));
|
||||
}
|
||||
const result=extractTitle('订单号:123456 原订单号:654321\n订单号:HA123456客户简称:测试');
|
||||
assert.deepEqual(result.orders.map(o=>o.orderNo),['123456','HA123456']);assert.match(result.brief,/654321/);
|
||||
});
|
||||
Reference in new issue
Block a user