diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 9ba13db..301a8c8 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -1,5 +1,14 @@
# 开发交接(2026-10-23)
+## 本轮:旧记录移除与隔离样例邮件验收(2026-10-23 16:18)
+
+- 按用户要求将唯一旧受阻订单软移出订单中心,原归档与规则快照哈希保持一致,防重数据保留;当前订单中心0条。未新增业务订单或业务批次。
+- 四个实时来源(v8/v4待办与知会)均成功完整分页,共16条,精确命中0条;多数停在生效节点,继续严格排除。已办通知任务补漏尚未实现,不能将实时分页完整表述为覆盖全部应通知订单。
+- 自动处理、计划发送及受限测试开关保持开启;PDF/归档现场能力检查尚未完成,自动链仍受阻。修复应用单类别时丢失其他类别未覆盖流程警告的问题,仍显示1个缺适配流程。
+- 两笔已核验历史订单按Excel同属试产类别,使用既有分类绑定模板合为1封样例邮件,隔离QQ收件、空Cc、无附件;16:17 SMTP已接受,实收待用户确认。另一笔历史订单因节点名称不符继续排除。本次没有生成PDF、归档回执或真实业务批次,不代表自动闭环验收。
+- 样例发送复用原邮件通道及发送记录,固定隔离信封,持久幂等;sending/unknown不自动重发,无新增HTTP发信入口。维护前备份两个相关数据库,更新后本机守护健康;正式服务机及BPM流程未操作。
+- 本轮仅运行邮件样例、Excel执行桥接和订单查询相关19项测试:19通过、0失败。未重跑旧全量。代码已覆盖本机原测试副本,具体版本以该目录code-revision.json为准;业务数据、预览、回执与备份位于忽略的output目录,不入Git。
+
## 当前:Excel规则已接入测试执行链
订单中心仅展示有分类匹配证据的订单和执行任务;未匹配候选、不带分类的识别失败记录不进入列表、统计或订单详情。已匹配但缺字段、归档失败或待核验的订单继续显示。原到达与候选数据保留,不删除或重做业务。本机14e48339目录保留为基础版本路径,后续视图补丁按当前分支提交覆盖,不再把目录名当成完整代码版本。默认核心测试另纳入10项订单查询回归;本次查询专项10项通过,不声称重跑旧全量。
diff --git a/package.json b/package.json
index 256e305..c202616 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,7 @@
"service:stop": "node scripts/service.cjs stop",
"service:restart": "node scripts/service.cjs restart",
"test": "npm run test:business",
- "test:business": "node --test --test-concurrency=1 tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs",
+ "test:business": "node --test --test-concurrency=1 tests/mail/sample-send.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs",
"test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\""
},
"engines": {
diff --git a/src/modules/mail/service.cjs b/src/modules/mail/service.cjs
index 41eb9b3..9dfcab4 100644
--- a/src/modules/mail/service.cjs
+++ b/src/modules/mail/service.cjs
@@ -1,11 +1,25 @@
'use strict';
-const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,MAX_MAIL}=require('./parser.cjs');
+const {ImapFlow}=require('imapflow');const nodemailer=require('nodemailer');const {parseTemplate,renderTemplate,escape,MAX_MAIL}=require('./parser.cjs');
const fail=(message,status=502)=>{throw Object.assign(new Error(message),{status});};
const safeError=(error,kind)=>error?.code==='EAUTH'||error?.authenticationFailed?`${kind} 登录失败,请检查账号和授权密码。`:/CERT|TLS|SSL|SELF_SIGNED/.test(error?.code||'')?`${kind} 加密连接失败,请检查服务器地址和证书。`:`${kind} 连接失败,请检查服务器、端口和网络后重试。`;
class MailService{
constructor({store,imapFactory,smtpFactory,interval=60000}){this.store=store;this.imapFactory=imapFactory||((c)=>new ImapFlow({host:c.host,port:c.port,secure:c.security==='tls',doSTARTTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,disableAutoIdle:true,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,maxLiteralSize:MAX_MAIL,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.smtpFactory=smtpFactory||((c)=>nodemailer.createTransport({host:c.host,port:c.port,secure:c.security==='tls',requireTLS:c.security==='starttls',auth:{user:c.user,pass:c.password},logger:false,debug:false,connectionTimeout:15000,greetingTimeout:15000,socketTimeout:30000,disableFileAccess:true,disableUrlAccess:true,tls:{rejectUnauthorized:true,minVersion:'TLSv1.2'}}));this.interval=interval;this.running=new Map();this.clients=new Set();this.stopped=false;}
busy(id){return this.running.has(id);}
async exclusive(id,work){if(this.stopped)fail('邮件服务正在停止。',503);if(this.busy(id))fail('此邮箱正在执行操作,请稍后重试。',409);const promise=Promise.resolve().then(work);this.running.set(id,promise);return promise.finally(()=>this.running.delete(id));}
+ sendSample(id,input){return this.exclusive(id,async()=>{
+ if(!input||Object.keys(input).some(k=>!['idempotencyKey','subject','text'].includes(k))||typeof input.idempotencyKey!=='string'||!/^[\w-]{1,80}$/.test(input.idempotencyKey)||typeof input.subject!=='string'||!input.subject.trim()||input.subject.length>250||/[\x00-\x1f]/.test(input.subject)||typeof input.text!=='string'||!input.text.trim()||input.text.length>20000||input.text.includes('\0'))fail('样例测试内容无效。',400);
+ const marker='sample:'+require('node:crypto').createHash('sha256').update(id+'\0'+input.idempotencyKey).digest('hex'),previous=this.store.findSampleSend(id,marker);
+ if(previous){if(previous.status==='sent')return {id:previous.id,status:'sent',to:'2639266652@qq.com',reused:true};fail('此样例发送已有结果待核实,不会自动重发。',409);}
+ const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发信。',409);
+ const text='本邮件仅用于样例测试,不表示BPM已处理或PDF已归档。\n\n'+input.text,transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;
+ try{
+ await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,marker);
+ const result=await transport.sendMail({from:{address:c.email,name:c.name},to:['2639266652@qq.com'],cc:[],subject:'[样例测试] '+input.subject,text,html:'
'+escape(text).replace(/\r?\n/g,'
')+'
',attachments:[],messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
+ if(result?.rejected?.length||!result?.accepted?.some(a=>String(a.address||a).toLowerCase()==='2639266652@qq.com'))throw Error('Sample recipient not fully accepted');
+ this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:'2639266652@qq.com',messageId:result.messageId};
+ }catch(error){if(sendId)this.store.finishSend(sendId,'unknown');if(error.status===409)throw error;fail(sendId?'样例发信结果待核实,禁止自动重发。':safeError(error,'SMTP'));}
+ finally{transport.close?.();this.clients.delete(transport);}
+ });}
async withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
history(id,input){return this.exclusive(id,async()=>{
const config=this.store.channelSecret(id);
diff --git a/src/modules/mail/store.cjs b/src/modules/mail/store.cjs
index a19c6a4..b2c96c7 100644
--- a/src/modules/mail/store.cjs
+++ b/src/modules/mail/store.cjs
@@ -82,6 +82,7 @@ class MailStore{
source(id){return Buffer.from(this.template(id).raw||'','base64');}
migrateLegacy(legacy){if(this.db.prepare("SELECT 1 FROM meta WHERE key='legacy'").get())return;this.transaction(()=>{if(legacy?.subject?.trim()&&legacy?.body?.trim()){const id=crypto.randomUUID(),payload={subject:legacy.subject,text:legacy.body,html:'',sender:'工作台旧草稿',sourceSubject:legacy.subject,attachments:[],notes:['从原模板草稿迁入,请选择托管邮箱后确认。']};this.db.prepare('INSERT INTO templates(id,channel_id,source_key,scope,status,version,base_id,payload,created_at,summary,notification_mode) VALUES(?,?,?,?,?,?,?,?,?,?,?)').run(id,'legacy','legacy','','pending',1,null,this.encode(id,payload),at(),this.summary(payload),'normal');}this.db.prepare("INSERT INTO meta VALUES('legacy','1')").run();});}
beginSend(channelId,templateId){const id=crypto.randomUUID();this.db.prepare('INSERT INTO sends VALUES(?,?,?,?,?)').run(id,channelId,templateId,'sending',at());return id;}
+ findSampleSend(channelId,key){return this.db.prepare('SELECT id,status FROM sends WHERE channel_id=? AND template_id=? ORDER BY at DESC LIMIT 1').get(channelId,key);}
finishSend(id,status){this.db.prepare('UPDATE sends SET status=? WHERE id=?').run(status,id);}
sends(){return this.db.prepare('SELECT * FROM sends ORDER BY at DESC LIMIT 50').all();}
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
diff --git a/src/modules/order-rules/query.cjs b/src/modules/order-rules/query.cjs
index 5b3d4e6..6b8c7a0 100644
--- a/src/modules/order-rules/query.cjs
+++ b/src/modules/order-rules/query.cjs
@@ -46,7 +46,7 @@ function orderRow(order,task){
function currentTasks(context,user){
const tasks=new Map();for(const task of records(context.orderRules).tasks){if(task.supersededBy||!task.orderId||!canReadConnection(context.workspace,user,task.connectionId))continue;const old=tasks.get(task.orderId);if(!old||Number(!!task.conflict)>Number(!!old.conflict)||!!task.conflict===!!old.conflict&&String(task.createdAt||'')>=String(old.createdAt||''))tasks.set(task.orderId,task);}return tasks;
}
-const classified=(order,task)=>!!(order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.length);
+const classified=(order,task)=>!order?.removedAt&&!!(order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.length);
function visibleOrders(context,user){
const data=records(context.orderRules),tasks=currentTasks(context,user);
const rows=data.orders.filter(o=>classified(o,tasks.get(o.id))&&canReadOrder(context.workspace,user,o)).map(o=>orderRow(o,tasks.get(o.id)));
diff --git a/src/modules/order-rules/restricted-test.cjs b/src/modules/order-rules/restricted-test.cjs
index 6221466..a27d1f2 100644
--- a/src/modules/order-rules/restricted-test.cjs
+++ b/src/modules/order-rules/restricted-test.cjs
@@ -23,7 +23,15 @@ function evidence(store,adapter){
const result=require('./field-mappings.cjs').evaluateMapping(store,{...adapter,version:adapter.version},captured,{relatedRules:[]});
return result.valid;
}
-function summary(store){const run=state(store);if(!run)return null;return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:run.uncovered};}
+function uncoveredFlows(store,run){
+ const adapters=store.adapters();
+ return run.rules.flatMap(rule=>{
+ const draft=store.get('rules',rule.id)?.draft;
+ const processes=draft?.version===rule.version?draft.processNames:[...rule.processNames,...(run.uncovered||[]).filter(row=>row.categoryId===rule.id).map(row=>row.processName)];
+ return [...new Set(processes)].filter(processName=>!adapters.some(a=>a.verified&&!a.reference&&rule.adapterIds.includes(a.id)&&a.processName===processName)).map(processName=>({categoryId:rule.id,processName}));
+ });
+}
+function summary(store){const run=state(store);if(!run)return null;return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:uncoveredFlows(store,run)};}
function validRule(store,rule,run){return run.enabled&&hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id)))===run.adapterHashes[rule.id];}
function executionRule(store,record){
const run=state(store);if(!run)return record?.published||null;
@@ -58,7 +66,7 @@ function applyDrafts(store,input,actor){
assertPath(store,rule.archiveDirectory,run);next.rules[index]=rule;next.adapterHashes[rule.id]=hash(rule.adapterIds.map(id=>adapters.find(a=>a.id===id)));
}
for(let i=0;irule.processNames.filter(p=>!adapters.some(a=>rule.adapterIds.includes(a.id)&&a.processName===p)).map(processName=>({categoryId:rule.id,processName})));
+ next.uncovered=uncoveredFlows(store,next);
// Keep the previous approved versions for existing tasks and frozen batches.
// The current execution snapshot alone changes; identities and baseline do not.
store.put('restricted-test-history',{id:run.id+':'+run.version,value:run});next.version++;
diff --git a/tests/mail/sample-send.test.cjs b/tests/mail/sample-send.test.cjs
new file mode 100644
index 0000000..fc84900
--- /dev/null
+++ b/tests/mail/sample-send.test.cjs
@@ -0,0 +1,18 @@
+'use strict';
+const test=require('node:test'),assert=require('node:assert/strict');
+const {MailService}=require('../../src/modules/mail/service.cjs');
+function fixture(unknown=false){
+ const rows=[],messages=[],store={channelSecret:()=>({id:'channel',version:1,email:'sender@example.test',name:'fixture',smtp:{}}),guard(){},findSampleSend:(id,key)=>rows.find(r=>r.channel_id===id&&r.template_id===key),beginSend:(id,key)=>{rows.push({id:'send-1',channel_id:id,template_id:key,status:'sending'});return 'send-1';},finishSend:(id,status)=>{rows.find(r=>r.id===id).status=status;}};
+ const service=new MailService({store,smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{messages.push(message);if(unknown)throw Error('fixture disconnected');return {accepted:['2639266652@qq.com'],rejected:[]};},close(){}})});
+ return {service,rows,messages,input:{idempotencyKey:'sample-once',subject:'分类汇总样例',text:'大家好:\n订单号:TEST-A\n订单号:TEST-B'}};
+}
+test('sample mail uses fixed isolated envelope, no attachments and a persistent no-repeat receipt',async()=>{
+ const f=fixture(),result=await f.service.sendSample('channel',f.input);assert.equal(result.status,'sent');assert.equal(f.messages.length,1);assert.deepEqual(f.messages[0].to,['2639266652@qq.com']);assert.deepEqual(f.messages[0].cc,[]);assert.deepEqual(f.messages[0].attachments,[]);assert.match(f.messages[0].subject,/样例测试/);assert.match(f.messages[0].text,/不表示.*PDF.*归档/);assert.match(f.messages[0].text,/订单号:TEST-A\n订单号:TEST-B/);
+ assert.equal((await f.service.sendSample('channel',f.input)).reused,true);assert.equal(f.messages.length,1);
+});
+test('unknown sample delivery is retained and never retried automatically',async()=>{
+ const f=fixture(true);await assert.rejects(()=>f.service.sendSample('channel',f.input),e=>e.status===502);assert.equal(f.rows[0].status,'unknown');await assert.rejects(()=>f.service.sendSample('channel',f.input),e=>e.status===409);assert.equal(f.messages.length,1);
+});
+test('sample requests cannot select other recipients, attachments or injected headers',async()=>{
+ const f=fixture();for(const patch of [{to:['other@example.test']},{attachments:[]},{subject:'bad\r\nBcc: other@example.test'},{idempotencyKey:''}])await assert.rejects(()=>f.service.sendSample('channel',{...f.input,...patch}),e=>e.status===400);assert.equal(f.messages.length,0);
+});
diff --git a/tests/order-rules/excel-execution-bridge.test.cjs b/tests/order-rules/excel-execution-bridge.test.cjs
index 6e562db..e119ab0 100644
--- a/tests/order-rules/excel-execution-bridge.test.cjs
+++ b/tests/order-rules/excel-execution-bridge.test.cjs
@@ -49,3 +49,9 @@ test('unusable imports roll back atomically and uncovered flows remain explicitl
assert(f.store.restrictedTest().uncovered.some(row=>row.processName==='未配置字段的流程'));
const blocked=f.store.ingest({...f.event('uncovered'),processName:'未配置字段的流程'},'fixture');assert.equal(blocked.status,'blocked');assert.equal(blocked.archive,null);
});
+test('applying one category retains missing-flow warnings for other categories',t=>{
+ const f=fixture(t);activateReferenceMapping(f.store,'overseas-change');const other=f.store.get('rules','overseas-change').draft;
+ f.store.saveRule({...other,to:['2639266652@qq.com'],cc:[],bodyTemplateId:'',archiveDirectory:f.root+'\\other',filenameDate:'receivedAt'},'admin');
+ f.store.put('restricted-test',{id:'main',value:null});const run=f.store.saveRestrictedTest({version:0,enabled:true,recipient:'2639266652@qq.com',archiveRoot:f.root,channelId:'fixture-mail',ruleIds:['bs-change','overseas-change']},admin);assert(run.uncovered.length>0);
+ const rule=f.store.get('rules','bs-change').draft;f.store.applyRestrictedDrafts({version:run.version,rules:[{id:rule.id,version:rule.version}]},admin);assert.deepEqual(f.store.restrictedTest().uncovered,run.uncovered);
+});
diff --git a/tests/order-rules/query.test.cjs b/tests/order-rules/query.test.cjs
index 71f4495..1bd6688 100644
--- a/tests/order-rules/query.test.cjs
+++ b/tests/order-rules/query.test.cjs
@@ -32,6 +32,10 @@ test('unmatched arrivals never enter order lists, counts or details while classi
for(const id of ['candidate:candidate-a','candidate:candidate-b','unmatched-order','task:unmatched-task'])assert.throws(()=>orderDetail(c,id,user),e=>e.status===404);
assert.equal(c.orderRules.all('execution-candidates').length,2);assert.equal(c.orderRules.get('orders','unmatched-order').status,'blocked');
});
+test('removed orders disappear from the center without erasing archive or dedup evidence',()=>{
+ const c=fixture(),order=c.orderRules.get('orders','o0');order.archive={files:[{name:'retained.pdf',sha256:'a'.repeat(64)}]};order.removedAt='2026-10-23T08:00:00Z';order.status='ignored';
+ assert.equal(queryOrders(c,{},user).total,82);assert.equal(summary(c,user).counts.orders,82);assert.throws(()=>orderDetail(c,'o0',user),e=>e.status===404);assert.equal(c.orderRules.get('orders','o0').archive.files[0].name,'retained.pdf');
+});
test('file endpoint reauthorizes and validates bytes against durable evidence',async()=>{
const c=fixture(),bytes=Buffer.from('%PDF-x');c.orderRules.get('orders','o0').archive={files:[{name:'a.pdf',path:'server-only',size:bytes.length,sha256:require('node:crypto').createHash('sha256').update(bytes).digest('hex')}]};
assert.deepEqual((await readOrderFile(c,'o0',0,user)).bytes,bytes);c.execution.archive.read=async()=>Buffer.from('tampered');await assert.rejects(()=>readOrderFile(c,'o0',0,user));await assert.rejects(()=>readOrderFile(c,'foreign',0,user));