'use strict'; const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto'); const {RuleStore}=require('../../src/modules/order-rules/store.cjs'); const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs'); const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs'); const {activateFieldMapping}=require('../fixtures/activate-field-mapping.cjs'); const admin={username:'admin',role:'admin'},principal={user:admin,sessionId:'test-session'}; function fixture(t){ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'execution-'));const now=()=>new Date('2026-10-19T03:00:00Z'); const store=new RuleStore(dir,{clock:now});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]})}; let captures=0,exports=0,failCapture=false; const row={source:'todo',instanceId:'i1',taskId:'t1',revision:'1',processName:'备损订单更改评审',nodeName:'订单专员(订单通知书)',processVersion:'1.4',receivedAt:'2026-10-19T01:00:00Z',serialNum:'S1',title:'订单号:SO-1 客户简称:真实客户'}; const provider={capabilities:()=>({liveTodo:true,pdfExport:true,message:'actual probe'}),scan:async(c,p)=>{assert.equal(p.sessionId,'test-session');return [row];},capture:async()=>{captures++;if(failCapture)throw Error('capture unavailable');return {sample:{...row,connectionId:'c1',brief:'摘要',fields:{order:'SO-1',brief:'真实摘要'}},snapshot:{processVersion:'1.4',html:'

real fixture

',fields:[{path:'order',label:'订单号',value:'SO-1'},{path:'brief',label:'摘要',value:'真实摘要'}]}};}}; const archive={read:async file=>fs.promises.readFile(file.path),probe:async()=>({automaticArchive:true,pdfExport:true,message:'runtime'}),capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{exports++;const content=Buffer.from('%PDF-1.7\nfixture');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);return {archivedAt:now().toISOString(),files:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]};}}; const execution=new OrderExecutionCoordinator({store,workspace,provider,archive,clock:now}); return {store,execution,row,provider,archive,principal,setFail:v=>{failCapture=v;},counts:()=>({captures,exports})}; } async function configure(f){ await f.execution.scan({connectionId:'c1',idempotencyKey:'first'},principal); const captured=f.store.fields().samples[0]; const adapter=activateFieldMapping(f.store,{sampleId:captured.id,processName:f.row.processName,processVersion:'1.4',fields:{orderNo:'order',brief:'brief'}},admin); const current=f.store.snapshot().rules.find(r=>r.id==='bs-change'); const saved=f.store.saveRule({...current,adapterIds:[adapter.id],to:['orders@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt'},'admin'); assert.equal(f.store.capturedPreview(captured.id).valid,true);f.store.publish(saved.id,{version:saved.version},'admin'); } test('scan prefilter uses complete process-node pairs without crossing their columns',async t=>{ const f=fixture(t),rule=f.store.get('rules','bs-change').draft; f.store.saveRule({...rule,scopes:[{processName:f.row.processName,nodeName:'另一个节点'},{processName:'另一个流程',nodeName:f.row.nodeName}]},'admin'); await f.execution.scan({connectionId:'c1',idempotencyKey:'paired-scope-scan'},principal); assert.equal(f.store.all('capture-samples').length,0);assert.equal(f.execution.snapshot().tasks.length,0);assert.deepEqual(f.counts(),{captures:0,exports:0});await f.execution.stop(); }); test('capture-backed dynamic binding recovers blocked task with stable identity and exports only once',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal); assert.equal(f.store.all('orders')[0].status,'pending');assert.equal(f.execution.snapshot().tasks.length,1);assert.equal(f.counts().exports,1); await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);assert.equal(f.counts().exports,1);assert.equal(f.execution.snapshot().capabilities.automaticArchive,true); assert.throws(()=>f.store.saveAdapter({sampleId:f.store.fields().samples[0].id,processName:f.row.processName,processVersion:'1.4',fields:{orderNo:'invented',brief:'brief'},version:1},admin),/字段/); }); test('capture failures block the entire category rather than silently omitting an order',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal); f.row.taskId='t2';f.row.instanceId='i2';f.setFail(true);await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal); assert.equal(f.execution.snapshot().tasks.filter(t=>t.status==='failed').length,1); assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,0); }); test('cold restart probes archived pending work and restores dispatch gates without exporting again',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive-before-restart'},principal); const before=f.counts();let captured=false,probed=false; const provider={scan:f.provider.scan,capabilities:()=>({liveTodo:true,pdfExport:captured}),capture:async(...args)=>{captured=true;return f.provider.capture(...args);}}; const archive={...f.archive,capabilities:()=>({automaticArchive:probed,pdfExport:probed}),probe:async rule=>{assert.equal(rule.id,'bs-change');probed=true;return {automaticArchive:true,pdfExport:true};}}; const execution=new OrderExecutionCoordinator({...f.execution,provider,archive}); assert.equal(execution.snapshot().capabilities.pdfExport,false); await execution.scan({connectionId:'c1',idempotencyKey:'cold-restart'},principal); assert.deepEqual(execution.snapshot().capabilities,{liveTodo:true,pdfExport:true,automaticArchive:true});assert.equal(captured,false);assert.equal(probed,true);assert.equal(f.counts().exports,before.exports);assert.equal(f.store.all('orders')[0].status,'pending'); await execution.stop(); f.store.prepare('2026-10-19T03:00:00Z','admin');captured=false;probed=false; const batchedRestart=new OrderExecutionCoordinator({...f.execution,provider,archive});await batchedRestart.scan({connectionId:'c1',idempotencyKey:'cold-batched-restart'},principal); assert.equal(batchedRestart.snapshot().tasks[0].status,'batched');assert.equal(f.store.providersReady(),true);assert.equal(f.counts().exports,before.exports);assert.equal(captured,false);assert.equal(probed,true);await batchedRestart.stop(); }); for(const supportsRecovery of [false,true])test(`committed archive receipt reconciles interrupted task before uncertainty classification (recovery=${supportsRecovery})`,async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archived'},principal); const task=f.store.all('execution-tasks')[0],order=f.store.get('orders',task.orderId),before=f.counts();task.status='archiving';task.step='archive';task.error=null;f.store.put('execution-tasks',task); const archive={...f.archive,supportsRecovery};const execution=new OrderExecutionCoordinator({...f.execution,archive}); assert.equal(execution.snapshot().tasks[0].status,'pending');assert.equal(execution.snapshot().tasks[0].step,'complete'); await execution.scan({connectionId:'c1',idempotencyKey:'reconciled'},principal);assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.get('orders',order.id).archive,order.archive);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,1); await execution.stop(); }); test('unavailable original source does not block valid archived receipts',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archived'},principal); const before=f.counts(),receipt=f.store.all('orders')[0].archive; const provider={scan:async()=>[],capabilities:()=>({liveTodo:true,pdfExport:false}),capture:async()=>{throw Error('原任务已不在已核验节点');}}; const execution=new OrderExecutionCoordinator({...f.execution,provider});await execution.scan({connectionId:'c1',idempotencyKey:'source-unavailable'},principal); assert.equal(f.store.providersReady(),true);assert.equal(execution.snapshot().tasks[0].runtimeCheck.status,'ready');assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.all('orders')[0].archive,receipt);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,1);await execution.stop(); }); test('failed frozen batch resend is versioned admin-only idempotent and cannot replay unknown',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal); f.store.saveSettings({...f.store.settings(),channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];f.store.finishSending(batch.id,'failed','SMTP verify failed'); let sends=0;const mail={exclusive:async(id,fn)=>fn(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'s',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sends++;assert.deepEqual(message.to,['orders@example.test']);return {accepted:message.to,rejected:[]};},close:()=>{}})}; const dispatcher=new OrderRuleDispatcher({store:f.store,mail,clock:()=>new Date('2026-10-21T00:00:00Z'),providersReady:()=>true}); const input={version:f.store.get('batches',batch.id).version,idempotencyKey:'resend1',note:'已检查SMTP已修复'}; await assert.rejects(dispatcher.resend(batch.id,input,{username:'op',role:'operator'}),{status:403}); const sent=await dispatcher.resend(batch.id,input,admin);assert.equal(sent.status,'sent');assert.equal(sent.parentBatchId,batch.id); assert.equal((await dispatcher.resend(batch.id,input,admin)).id,sent.id);assert.equal(sends,1); await assert.rejects(dispatcher.resend(batch.id,{...input,note:'与原请求不同的依据'},admin),{status:409}); await assert.rejects(dispatcher.resend(batch.id,{...input,idempotencyKey:'again'},admin),{status:409}); }); test('scope, calendar and pause gates survive actual persisted capture provenance',async t=>{ const f=fixture(t);await configure(f); assert.equal(f.execution.snapshot({user:{username:'other',role:'operator'},sessionId:'other'}).fields.samples.length,0); assert.equal(f.execution.snapshot({user:{username:'other',role:'operator'},sessionId:'other'}).tasks.length,0); await assert.rejects(f.execution.scan({connectionId:'c1',idempotencyKey:'foreign'}, {user:{username:'other',role:'operator'},sessionId:'other'}),{status:403}); let scans=0;const scan=f.provider.scan;f.provider.scan=async(...args)=>{scans++;return scan(...args);}; f.execution.systemPrincipal=principal;await f.execution.background();assert.equal(scans,0); f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');f.execution.settings=()=>({schedule:{times:['11:00','17:00'],weekends:false}});f.execution.calendar=()=>[{date:'2026-10-19',kind:'pause',scan:false,send:false}]; await f.execution.background();assert.equal(scans,0); f.execution.calendar=()=>[];f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});await f.execution.notifyDiscovery({connectionId:'c1',runId:'calendar-resume',rows:[f.row],startedAt:f.execution.now(),finishedAt:f.execution.now()});await f.execution.background();assert.equal(scans,0); const captured=f.store.fields().samples[0],adapter=f.store.fields().adapters.find(a=>a.sampleId===captured.id); activateFieldMapping(f.store,{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:adapter.fields,version:adapter.draftVersion},admin); assert.equal(f.store.get('rules','bs-change').published.status,'paused'); assert.throws(()=>f.store.publish('bs-change',{version:f.store.get('rules','bs-change').draft.version},'admin'),{status:409}); }); test('restart converts a never-sent manual attempt into a reachable failed attempt',async t=>{ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'resend-restart-'));let store=new RuleStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); store.put('orders',{id:'o1',status:'batched',batchId:'manual1'});store.put('batches',{id:'manual1',version:1,manual:true,status:'prepared',orderIds:['o1']}); store.close();store=new RuleStore(dir);assert.equal(store.get('batches','manual1').status,'failed');assert.equal(store.get('orders','o1').status,'pending'); store.put('batches',{id:'manual2',version:1,manual:true,status:'sending',orderIds:['o1']});store.put('orders',{id:'o1',status:'batched',batchId:'manual2'}); store.close();store=new RuleStore(dir);assert.equal(store.get('batches','manual2').status,'unknown');assert.equal(store.get('orders','o1').status,'unknown'); }); test('workspace exceptions deduplicate per task and recovery requests verification without claiming manual closure',async t=>{ const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const f=fixture(t),dir=fs.mkdtempSync(path.join(os.tmpdir(),'execution-exception-')),workspace=new WorkspaceStore(dir);t.after(()=>{workspace.close();fs.rmSync(dir,{recursive:true,force:true});}); const connection=f.execution.workspace.getConnection('c1');f.execution.workspace={getConnection:()=>connection,snapshot:()=>({...workspace.snapshot(),connections:[connection]}),createException:workspace.createException.bind(workspace),actOnException:workspace.actOnException.bind(workspace),record:workspace.record.bind(workspace)}; await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'recover'},principal);assert.equal(workspace.snapshot().exceptions.length,1);assert.equal(workspace.snapshot().exceptions[0].status,'verifying');assert.equal(f.execution.snapshot().tasks[0].recovery.status,'awaiting_verification'); connection.owner='';f.row.taskId='unassigned';f.row.instanceId='unassigned';f.setFail(true);await f.execution.scan({connectionId:'c1',idempotencyKey:'failed-unassigned'},principal); f.setFail(false);await f.execution.scan({connectionId:'c1',idempotencyKey:'recover-unassigned'},principal);const item=workspace.snapshot().exceptions.find(e=>!e.owner);assert.equal(item.status,'open');assert.equal(f.execution.snapshot().tasks.find(t=>t.row.taskId==='unassigned').recovery.status,'awaiting_verification');assert.equal(workspace.snapshot().exceptions.filter(e=>e.status==='resolved').length,0); }); test('interrupted archive recovery is explicitly retried and never silently replayed by scan',async t=>{ const f=fixture(t);await configure(f);f.archive.supportsRecovery=true; const archive=f.archive.archive;f.archive.archive=async()=>{throw Error('worker interrupted');}; await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal); const task=f.execution.snapshot().tasks[0];assert.equal(task.status,'failed');assert.equal(task.step,'archive'); f.archive.archive=archive;await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);assert.equal(f.counts().exports,0); await f.execution.retry(task.id,{version:task.version,idempotencyKey:'retry',note:'已核对归档幂等凭据'},principal); assert.equal(f.execution.snapshot().tasks[0].status,'pending');assert.equal(f.counts().exports,1); const running=f.store.get('execution-tasks',task.id);running.status='archiving';running.step='archive';f.store.put('execution-tasks',running); const restarted=new OrderExecutionCoordinator({...f.execution,store:f.store,workspace:f.execution.workspace,provider:f.provider,archive:f.archive}); assert.equal(restarted.snapshot().tasks[0].status,'pending');await restarted.stop(); }); test('unknown send first requires recorded verification; only then frozen manual resend is reachable',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal); f.store.saveSettings({...f.store.settings(),channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0]; f.store.beginSending(batch.id);f.store.finishSending(batch.id,'unknown','connection lost'); const dispatcher=new OrderRuleDispatcher({store:f.store,mail:{exclusive:async(id,fn)=>fn()},providersReady:()=>true}); await assert.rejects(dispatcher.resend(batch.id,{version:f.store.get('batches',batch.id).version,idempotencyKey:'bad',note:'尚未完成服务端核对'},admin),{status:409}); const resolveInput={version:f.store.get('batches',batch.id).version,idempotencyKey:'verified',resolution:'retry',note:'服务器确认未接受本次邮件'}; assert.throws(()=>f.store.resolve(batch.id,{...resolveInput,version:0},'admin',{controlled:true}),{status:409}); const resolved=f.store.resolve(batch.id,resolveInput,'admin',{controlled:true});assert.equal(resolved.status,'failed'); assert.equal(f.store.resolve(batch.id,resolveInput,'admin',{controlled:true}).status,'failed'); assert.throws(()=>f.store.resolve(batch.id,{...resolveInput,note:'与原来不同的核验结论'},'admin',{controlled:true}),{status:409}); assert.equal(f.store.prepare('2026-10-19T03:00:00Z','system').length,0); }); test('all fifteen categories capture actual fixture fields, archive to temporary files and send through real loopback SMTP',async t=>{ const {SMTPServer}=require('smtp-server'),nodemailer=require('nodemailer'),{simpleParser}=require('mailparser'); const f=fixture(t),rows=f.store.snapshot().rules.map((rule,i)=>({...f.row,instanceId:'i'+i,taskId:'t'+i,processName:rule.processNames[0],nodeName:rule.nodeNames[0],processVersion:'fixture-1',title:'订单号:SO-'+i,serialNum:'S'+i})); f.provider.scan=async()=>rows; f.provider.capture=async(connection,principal,row)=>({sample:{...row,connectionId:connection.id,fields:{'actual.order':'SO-'+row.taskId.slice(1),'actual.summary':'采集摘要'}},snapshot:{processVersion:row.processVersion,html:'

captured fixture

',fields:[{path:'actual.order',label:'订单号',value:'SO-'+row.taskId.slice(1)},{path:'actual.summary',label:'摘要',value:'采集摘要'}]}}); await f.execution.scan({connectionId:'c1',idempotencyKey:'capture15'},principal); for(const [index,current] of f.store.snapshot().rules.entries()){ const captured=f.store.fields().samples.find(s=>s.processName===rows[index].processName); const adapter=activateFieldMapping(f.store,{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:{orderNo:'actual.order',brief:'actual.summary'}},admin); const updated=f.store.snapshot().rules.find(r=>r.id===current.id); const saved=f.store.saveRule({...updated,processNames:[captured.processName],nodeNames:[rows[index].nodeName],adapterIds:[adapter.id],to:['orders@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt'},'admin'); assert.equal(f.store.capturedPreview(captured.id).valid,true);f.store.publish(saved.id,{version:saved.version},'admin'); } await f.execution.scan({connectionId:'c1',idempotencyKey:'archive15'},principal);assert.equal(f.store.all('orders').filter(o=>o.status==='pending').length,15); let messages=[];const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',chunk=>chunks.push(chunk));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}}); await new Promise(resolve=>smtp.listen(0,'127.0.0.1',resolve));t.after(()=>new Promise(resolve=>smtp.close(resolve))); const mail={exclusive:async(id,work)=>work(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'通知',smtp:{}}),guard:()=>{}},smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true})}; f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin'); let now=new Date('2026-10-19T02:59:00Z');const dispatcher=new OrderRuleDispatcher({store:f.store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:()=>now,providersReady:()=>true,templateResolver:()=>({id:'template',version:1,subject:'ignored',text:'模板{{订单列表}}',html:'
{{订单列表}}
',to:['intruder@example.test'],attachments:[]})}); await dispatcher.tick();now=new Date('2026-10-19T03:00:00Z');await dispatcher.tick();await dispatcher.stop(); assert.equal(messages.length,15);assert.equal(f.store.all('batches').filter(b=>b.status==='sent').length,15); for(const [index,raw] of messages.entries()){const message=await simpleParser(raw);assert.deepEqual(message.to.value.map(x=>x.address),['orders@example.test']);assert.match(message.text,/模板/);assert.match(message.text,/SO-/);assert.equal(message.attachments.length,f.store.all('batches').find(b=>b.subject===message.subject).ruleSnapshot.attachPdf?1:0);} assert.equal(f.counts().exports,15); }); for(const partial of [false,true])test(`real loopback SMTP ${partial?'partial refusal stays unknown':'complete envelope refusal is explicitly failed'}`,async t=>{ const {SMTPServer}=require('smtp-server'),nodemailer=require('nodemailer');const f=fixture(t);await configure(f); const current=f.store.snapshot().rules.find(r=>r.id==='bs-change'),saved=f.store.saveRule({...current,to:['accepted@example.test'],cc:['rejected@example.test']},'admin'); f.store.capturedPreview(f.store.fields().samples[0].id);f.store.publish(saved.id,{version:saved.version},'admin'); await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin'); let messages=0;const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onRcptTo(address,session,cb){if(!partial||address.address==='rejected@example.test'){const error=Error('Recipient refused');error.responseCode=550;return cb(error);}cb();},onData(stream,session,cb){stream.resume();stream.on('end',()=>{messages++;cb();});}}); await new Promise(resolve=>smtp.listen(0,'127.0.0.1',resolve));t.after(()=>new Promise(resolve=>smtp.close(resolve))); const mail={exclusive:async(id,work)=>work(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'通知',smtp:{}}),guard:()=>{}},smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true})}; let now=new Date('2026-10-19T02:59:00Z');const dispatcher=new OrderRuleDispatcher({store:f.store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:()=>now,providersReady:()=>true}); await dispatcher.tick();now=new Date('2026-10-19T03:00:00Z');await dispatcher.tick();await dispatcher.stop();assert.equal(f.store.all('batches')[0].status,partial?'unknown':'failed');assert.equal(messages,partial?1:0); assert.equal(f.store.prepare('2026-10-19T03:00:00Z','system').length,0); }); function deferred(){let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};} test('discovery barrier preserves frozen collection and explicitly blocks late same-window arrivals',async t=>{ const f=fixture(t);f.execution.clock=f.store.clock=()=>new Date('2026-10-19T03:00:00Z');await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal); const cutoff='2026-10-19T03:00:00Z',batch=f.store.prepare(cutoff,'admin')[0];assert.ok(batch); const discovery=deferred(),capture=deferred(),entered=deferred(),original={...f.row};let fail=true; f.provider.scan=()=>discovery.promise; f.provider.capture=async(c,p,row)=>{entered.resolve();await capture.promise;if(fail)throw Error('late capture failed');return {sample:{...row,connectionId:c.id,title:'订单号:'+row.taskId,brief:'摘要',fields:{order:row.taskId,brief:'真实摘要'}},snapshot:{processVersion:'1.4',html:'

fixture

',fields:[{path:'order',label:'订单号',value:row.taskId},{path:'brief',label:'摘要',value:'真实摘要'}]}};}; const scanning=f.execution.scan({connectionId:'c1',idempotencyKey:'gated'},principal); assert.throws(()=>f.store.beginSending(batch.id),/扫描|完整/,'even a just queued discovery blocks existing batch'); assert.equal(f.store.prepare(cutoff,'admin').length,0); discovery.resolve([original,{...original,taskId:'late1',instanceId:'late1'},{...original,taskId:'late2',instanceId:'late2'}]);await entered.promise; assert.equal(f.store.all('execution-tasks').length,3,'all relevant identities persisted before first awaited capture'); assert.equal(f.store.prepare(cutoff,'admin').length,0);capture.resolve();await scanning; assert.equal(f.store.prepare(cutoff,'admin').length,0); fail=false;await f.execution.scan({connectionId:'c1',idempotencyKey:'recovered'},principal); const replacement=f.store.prepare(cutoff,'admin');assert.equal(replacement.length,0);assert.equal(f.store.get('batches',batch.id).status,'prepared');assert.equal(f.store.get('batches',batch.id).orderIds.length,1);assert.equal(f.store.all('orders').filter(o=>o.blockedByBatchId===batch.id).length,2);assert.equal(f.store.all('business-issues').filter(i=>i.id.startsWith('late:')).length,2);assert.equal(f.store.beginSending(batch.id).status,'sending'); }); test('cutoff requires a successful post-cutoff discovery for every source and failed zero-row scans stay blocked',async t=>{ const f=fixture(t);f.execution.clock=f.store.clock=()=>new Date('2026-10-19T02:00:00Z');await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal); const cutoff='2026-10-19T03:00:00Z';assert.equal(f.store.prepare(cutoff,'admin').length,0,'pre-cutoff snapshot cannot certify all arrivals'); f.execution.clock=f.store.clock=()=>new Date(cutoff);const original=f.provider.scan;f.provider.scan=async()=>{throw Error('list unavailable');}; await assert.rejects(f.execution.scan({connectionId:'c1',idempotencyKey:'failed-list'},principal),/list unavailable/);assert.equal(f.store.prepare(cutoff,'admin').length,0);assert.equal(f.execution.snapshot().query.status,'failed'); f.provider.scan=original;await f.execution.scan({connectionId:'c1',idempotencyKey:'recovered-list'},principal);assert.equal(f.store.prepare(cutoff,'admin').length,1); }); test('dispatcher rechecks discovery after SMTP verification and keeps an unsent reservation recoverable',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal);f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0]; const verified=deferred(),verifyGate=deferred(),discovery=deferred();let sends=0;const mail={clients:new Set(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',smtp:{}}),guard(){}},smtpFactory:()=>({verify:async()=>{verified.resolve();await verifyGate.promise;},sendMail:async()=>{sends++;return {accepted:['orders@example.test']};},close(){}})}; const dispatcher=new OrderRuleDispatcher({store:f.store,mail,clock:f.execution.clock,providersReady:()=>true});const dispatch=dispatcher.dispatch(batch,f.store.settings());await verified.promise; f.provider.scan=()=>discovery.promise;const scan=f.execution.scan({connectionId:'c1',idempotencyKey:'during-verify'},principal);f.store.capabilities.pdfExport=false;verifyGate.resolve();assert.equal(await dispatch,false);assert.equal(sends,0);assert.equal(f.store.get('batches',batch.id).status,'prepared'); discovery.resolve([f.row]);await scan;await dispatcher.dispatch(batch,f.store.settings());assert.equal(sends,1);assert.equal(f.store.get('batches',batch.id).status,'sent');await dispatcher.stop(); }); test('all configured sources require independent complete cutoff discovery and task retry capability matches owner authorization',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal); const connections=[{id:'c1',owner:'admin',status:'connected'},{id:'c2',owner:'operator',status:'connected'}];f.execution.workspace={getConnection:id=>connections.find(c=>c.id===id),snapshot:()=>({connections})};const cutoff='2026-10-19T03:00:00Z';assert.equal(f.store.prepare(cutoff,'admin').length,0); f.provider.scan=async()=>[];await f.execution.scan({connectionId:'c2',idempotencyKey:'second-source'},principal);assert.equal(f.store.prepare(cutoff,'admin').length,1); const task=f.store.all('execution-tasks')[0];task.status='failed';task.step='archive';f.store.put('execution-tasks',task);const owner={user:{username:'admin',role:'operator'},sessionId:'owner'}; assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,true);assert.equal(f.execution.snapshot({user:{username:'admin',role:'viewer'},sessionId:'reader'}).tasks[0].canRetry,false); await assert.rejects(f.execution.retry(task.id,{version:task.version,note:'已经确认恢复条件',idempotencyKey:'denied'}, {user:{username:'operator',role:'operator'},sessionId:'other'}),{status:403}); task.conflict=true;f.store.put('execution-tasks',task);assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,false);task.conflict=false;task.status='unknown';f.store.put('execution-tasks',task);assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,false); }); test('trusted discovery persists while paused and is consumed without a second list read',async t=>{const f=fixture(t);await configure(f);let scans=0;f.provider.scan=async()=>{scans++;return [f.row];};f.execution.systemPrincipal=principal;await f.execution.notifyDiscovery({connectionId:'c1',runId:'watch1',rows:[f.row],startedAt:'2026-10-19T03:00:00Z',finishedAt:'2026-10-19T03:00:00Z'});await f.execution.background();assert.equal(scans,0);assert.equal(f.store.all('execution-discoveries')[0].status,'pending');assert.ok(f.store.discoveryBlockers('2026-10-19T03:00:00Z').length);f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});await f.execution.background();assert.equal(scans,0);assert.equal(f.counts().exports,1);assert.equal(f.store.all('execution-discoveries')[0].status,'complete');await f.execution.background();assert.equal(scans,0);}); test('archived todo disappearance uses receipt readback and never calls capture',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.archive.read=async file=>fs.promises.readFile(file.path);f.provider.scan=async()=>[];f.provider.capture=async()=>{throw Error('must not capture completed source');};await f.execution.scan({connectionId:'c1',idempotencyKey:'gone'},principal);assert.equal(f.execution.snapshot().tasks[0].runtimeCheck.status,'ready');assert.equal(f.counts().exports,1);}); test('published migration is atomic versioned idempotent and preserves distribution-only archive',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);const before=f.store.all('orders')[0],record=f.store.get('rules','bs-change');record.published={...record.published,version:record.published.version+1,to:['new@example.test']};f.store.put('rules',record);const input={version:record.published.version,idempotencyKey:'migration1',note:'更新分发范围依据'};const preview=f.store.previewMigration(record.id,input,'admin');assert.equal(preview.items[0].archiveChanged,false);f.store.applyMigration(record.id,input,'admin');assert.deepEqual(f.store.get('orders',before.id).archive,before.archive);assert.deepEqual(f.store.get('orders',before.id).ruleSnapshot.to,['new@example.test']);f.store.applyMigration(record.id,input,'admin');assert.throws(()=>f.store.applyMigration(record.id,{...input,note:'另一不同处理依据'},'admin'),{status:409});const changed=f.store.get('orders',before.id);changed.status='unknown';f.store.put('orders',changed);assert.equal(f.store.previewMigration(record.id,{...input,idempotencyKey:'m2'},'admin').excluded.length,1);}); test('revision resolution preserves identity, suppresses ignored repeat, blocks frozen orders',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.row.title='changed revision content';await f.execution.scan({connectionId:'c1',idempotencyKey:'conflict'},principal);let task=f.store.all('execution-tasks')[0];assert.equal(task.conflict,true);await f.execution.resolve(task.id,{version:task.version,idempotencyKey:'ignore1',resolution:'ignore',note:'人工比对确认忽略变化'},principal);await f.execution.scan({connectionId:'c1',idempotencyKey:'repeat'},principal);task=f.store.get('execution-tasks',task.id);assert.equal(task.conflict,false);const o=f.store.get('orders',task.orderId);o.status='unknown';f.store.put('orders',o);task.conflict=true;task.conflictRow={...task.row,title:'another'};f.store.put('execution-tasks',task);await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt1',resolution:'adopt',note:'人工确认采用新修订'},principal),{status:409});}); test('a new BPM revision is held against the prior identity and cannot bypass a frozen batch',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive-old'},principal);const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];f.row.revision='2';await f.execution.scan({connectionId:'c1',idempotencyKey:'revision2'},principal);const task=f.store.all('execution-tasks').find(t=>t.row.revision==='2');assert.equal(task.conflict,true);assert.equal(f.counts().exports,1);await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt',resolution:'adopt',note:'核对新修订仍不能重发'},principal),{status:409});assert.equal(f.store.get('batches',batch.id).status,'prepared');}); test('adopting a new unfrozen revision preserves original evidence and requires fresh archive',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'original'},principal);const original=f.store.all('orders')[0];f.row.revision='2';await f.execution.scan({connectionId:'c1',idempotencyKey:'changed'},principal);const task=f.store.all('execution-tasks').find(t=>t.row.revision==='2');await f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt2',resolution:'adopt',note:'人工确认新版业务修订'},principal);await f.execution.scan({connectionId:'c1',idempotencyKey:'process-new'},principal);const order=f.store.get('orders',original.id);assert.equal(order.sample.revision,'2');assert.equal(order.archiveHistory.length,1);assert.equal(f.counts().exports,2);assert.equal(f.store.all('execution-tasks').find(t=>t.row.revision==='1').status,'ignored');assert.equal(f.store.get('execution-tasks',task.id).conflict,false);});