'use strict'; const test=require('node:test'),assert=require('node:assert/strict'); const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs'); const principal={user:{username:'admin',role:'admin'},sessionId:'responsiveness-test'}; function fixture(t){ const records=new Map(),connection={id:'c1',owner:'admin',status:'connected'}; let processingEnabled=true,transactionDepth=0,snapshots=0; const store={ all:kind=>[...(records.get(kind)?.values()||[])].map(item=>structuredClone(item)), get:(kind,id)=>structuredClone(records.get(kind)?.get(id)||null), put(kind,item){if(!records.has(kind))records.set(kind,new Map());records.get(kind).set(item.id,structuredClone(item));return item;}, transaction(work){transactionDepth++;try{return work();}finally{transactionDepth--; }}, settings:()=>({processingEnabled,processingSince:null}), now:()=> '2026-10-23T02:00:00.000Z',clock:()=>new Date('2026-10-23T02:00:00Z'), schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[],intakeWindow:()=>null, snapshot(){snapshots++;return {window:{start:'2026-10-23T00:00:00Z',end:'2026-10-23T03:00:00Z',available:false}};}, executionRule:record=>record?.draft, fields:()=>({samples:[],processes:[]}),discoveryBlockers:()=>[], }; const provider={capabilities:async()=>({liveTodo:true,pdfExport:true}),scan:async()=>{throw Error('Unexpected live scan');},capture:async()=>{throw Error('Synthetic capture unavailable');}}; const execution=new OrderExecutionCoordinator({store,systemPrincipal:principal,clock:()=>new Date('2026-10-23T02:00:00Z'), workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},provider, archive:{capabilities:async()=>({automaticArchive:true,pdfExport:true})},onException:async()=>{}, }); t.after(()=>execution.stop()); return {store,execution,provider,connection,setProcessing:value=>{processingEnabled=value;},get snapshots(){return snapshots;},get inTransaction(){return transactionDepth!==0;}}; } test('one discovery set resolves its window once and registers every row before external work',async t=>{ const f=fixture(t),rows=Array.from({length:17},(_,index)=>({source:'todo',portalSource:'portal-v4',taskId:String(index+1),instanceId:'i'+index,processName:'Synthetic process',nodeName:'Notification',receivedAt:'2026-10-23T01:00:00Z',title:'订单号:TEST-'+index})); f.store.put('rules',{id:'r',draft:{id:'r',categoryId:'r',processNames:['Synthetic process'],scopes:[{processName:'Synthetic process',nodeName:'Notification'}]}}); let firstProbe; f.provider.capabilities=async()=>{ firstProbe||={snapshots:f.snapshots,inTransaction:f.inTransaction,tasks:f.store.all('execution-tasks'),targetCount:f.store.get('execution-scans','c1').targetCount}; return {liveTodo:true,pdfExport:true}; }; await f.execution.scan({connectionId:'c1',idempotencyKey:'complete-discovery'},principal,{rows}); assert.equal(firstProbe.snapshots,0,'discovery resolves its window without building a full store snapshot'); assert.equal(new Set(firstProbe.tasks.map(task=>JSON.stringify(task.intakeWindow))).size,1,'all tasks must share the window resolved at scan start'); assert.equal(firstProbe.tasks[0].intakeWindow.end,'2026-10-23T03:00:00.000Z'); assert.equal(firstProbe.inTransaction,false,'external work must start after the discovery transaction'); assert.equal(firstProbe.tasks.length,17,'all task rows must be committed before any probe or capture'); assert.equal(firstProbe.targetCount,17);assert.equal(f.store.all('execution-tasks').length,17); assert.equal(f.snapshots,0,'capture absence checks and execution views must not assemble unrelated store snapshots'); }); for(const action of ['pause','stop'])test(`historical delivery drain yields before the second hint so an event-loop ${action} preserves pending work`,async t=>{ const f=fixture(t); for(let index=0;index<20;index++)f.execution.notifyDiscovery({connectionId:'c1',runId:'run-'+index,rows:[],startedAt:new Date(Date.parse('2026-10-23T01:00:00Z')+index*1000).toISOString(),finishedAt:new Date(Date.parse('2026-10-23T01:00:01Z')+index*1000).toISOString()}); let completedAtSignal; const signal=new Promise(resolve=>setImmediate(()=>{ completedAtSignal=f.store.all('execution-discovery-runs').filter(item=>item.status==='complete').length; if(action==='pause')f.setProcessing(false);else void f.execution.stop(); resolve(); })); await f.execution.background();await signal; assert.equal(completedAtSignal,1,'an independent event-loop callback must run before consuming a second historical hint'); const hints=f.store.all('execution-discovery-runs'); assert.equal(hints.filter(item=>item.status==='complete').length,1); assert.equal(hints.filter(item=>item.status==='pending').length,19); assert.deepEqual(hints.filter(item=>item.status==='pending').map(item=>item.runId),Array.from({length:19},(_,index)=>'run-'+(index+1))); assert.equal(f.store.get('execution-discoveries','c1').status,'pending'); if(action==='pause'){ f.setProcessing(true);await f.execution.background(); assert.equal(f.store.all('execution-discovery-runs').filter(item=>item.status==='complete').length,20); assert.equal(f.store.get('execution-discoveries','c1').status,'complete'); assert.equal(f.snapshots,0,'background freshness checks must resolve only the schedule window'); } });