// Standalone sample acceptance. Uses the existing secure Skill entry; no identity creation. import fs from 'node:fs'; import path from 'node:path'; import {fileURLToPath} from 'node:url'; import {spawnSync} from 'node:child_process'; export const TASK_KEY='KSF-查重实测-20261102-01'; const fail=code=>{throw Object.assign(Error(code),{code});}; const check=(ok,code='DEDUP_ACCEPTANCE_MISMATCH')=>{if(!ok)fail(code);}; const safeCode=e=>/^[A-Z][A-Z0-9_]+$/.test(e?.code||'')?e.code:'DEDUP_ACCEPTANCE_FAILED'; export function validateDedupContext(c){ check(c&&typeof c==='object'&&!Array.isArray(c),'INVALID_DEDUP_CONTEXT'); check(Object.keys(c).length===3&&Object.keys(c).every(k=>['version','taskKey','agentProfileKey'].includes(k)),'INVALID_DEDUP_CONTEXT'); check(c.version==='ksf.dedup-acceptance.v1'&&c.taskKey===TASK_KEY,'INVALID_DEDUP_CONTEXT'); check(typeof c.agentProfileKey==='string'&&/^agent-account:[a-f0-9]{64}$/.test(c.agentProfileKey),'TRUSTED_AGENT_PROFILE_REQUIRED'); return c; } export function dedupTask(round){ check(round==='a'||round==='b','INVALID_DEDUP_ROUND'); return { source:{title:'【样例】原料查重验收 '+TASK_KEY,sourceKind:'dataset',dataMode:'sample',rawText:TASK_KEY+'。本段为人工构造的查重样例,不来自真实平台或供应商。原料:演练面粉占位;类型:配料;规格、供应商、价格和用量均未知。只用于验证相同资料跨批次复用,不构成配方或采购建议。'}, records:[{itemKey:'material',className:'KfMaterial',externalKey:TASK_KEY+':material:'+round,data:{dataMode:'sample',name:'【样例】查重演练面粉 '+TASK_KEY,materialType:'ingredient',specification:'未知;无供应商或检测依据',function:'仅验证相同原料跨批次复用;不用于真实配方'}}] }; } function preflight(p){ check(p?.readOnly===true&&p.schema==='ksf.ingest-dedup.v1'&&p.items?.length===1&&p.items[0].itemKey==='material','DEDUP_PREFLIGHT_MISMATCH'); return p.items[0]; } function imported(r){ check(r?.status==='succeeded'&&r.dataMode==='sample'&&r.formalReportPublished===false&&r.deduplication?.schema==='ksf.ingest-dedup.v1'&&r.deduplication.checked===1,'DEDUP_IMPORT_MISMATCH'); check(typeof r.sourceId==='string'&&r.sourceId&&r.items?.length===1&&r.items[0].itemKey==='material'&&r.items[0].className==='KfMaterial'&&r.items[0].status==='succeeded'&&typeof r.items[0].objectId==='string'&&r.items[0].objectId,'DEDUP_IMPORT_MISMATCH'); return {sourceId:r.sourceId,materialId:r.items[0].objectId,jobId:r.items[0].jobId,sourceOperation:r.sourceOperation,operation:r.items[0].operation,created:r.counts?.created,unchanged:r.counts?.unchanged}; } export async function runDedupAcceptance({context,invoke,checkpoint=()=>{}}){ validateDedupContext(context); const rounds={},run=async(command,task,suffix)=>{ const requestId=TASK_KEY+':'+suffix; checkpoint({status:'in-flight',command,requestId,rounds:structuredClone(rounds)}); const result=await invoke(command,task,requestId); checkpoint({status:'received',command,requestId,result,rounds:structuredClone(rounds)}); return result; }; const contract=await run('workshop-contract',{},'contract'); check(contract?.deduplication?.schema==='ksf.ingest-dedup.v1'&&contract.deduplication.preflightFunction==='ksfCheckDuplicates','DEDUP_CAPABILITY_UNAVAILABLE'); const a=dedupTask('a'),b=dedupTask('b'); const beforeA=await run('workshop-dedup',a,'preflight-a'); const first=preflight(beforeA); check(beforeA.source?.operation==='no-exact-match'&&['deferred','no-exact-match'].includes(first.decision),'DEDUP_HISTORY_EXISTS'); rounds.a=imported(await run('workshop-import',a,'batch-a')); checkpoint({status:'round-a-recorded',rounds:structuredClone(rounds)}); check(rounds.a.sourceOperation==='created'&&rounds.a.operation==='created'&&rounds.a.created===1&&rounds.a.unchanged===0,'DEDUP_FIRST_IMPORT_MISMATCH'); const beforeB=await run('workshop-dedup',b,'preflight-b'); const second=preflight(beforeB); check(beforeB.source?.operation==='unchanged'&&beforeB.source.sourceId===rounds.a.sourceId&&second.decision==='reuse'&&second.objectId===rounds.a.materialId,'DEDUP_REUSE_PREFLIGHT_MISMATCH'); rounds.b=imported(await run('workshop-import',b,'batch-b')); checkpoint({status:'round-b-recorded',rounds:structuredClone(rounds)}); check(rounds.b.sourceId===rounds.a.sourceId&&rounds.b.materialId===rounds.a.materialId,'DEDUP_ID_MISMATCH'); check(rounds.b.sourceOperation==='unchanged'&&rounds.b.operation==='unchanged'&&rounds.b.created===0&&rounds.b.unchanged===1,'DEDUP_SECOND_IMPORT_MISMATCH'); check(rounds.a.jobId&&rounds.b.jobId&&rounds.a.jobId!==rounds.b.jobId,'DEDUP_BATCH_JOB_MISMATCH'); const {record}=await run('workshop-read',{className:'KfMaterial',objectId:rounds.a.materialId},'read-material'); check(record?.objectId===rounds.a.materialId&&record.dataMode==='sample'&&record.sourceRef?.objectId===rounds.a.sourceId,'DEDUP_READBACK_MISMATCH'); for(const [k,v]of Object.entries(a.records[0].data))check(record[k]===v,'DEDUP_READBACK_MISMATCH'); const receipt={ok:true,operation:'sample-material-dedup-verified',taskKey:TASK_KEY,dataMode:'sample',rounds,sameSourceId:true,sameMaterialId:true,secondCreated:0,secondUnchanged:1,secondReused:1,reusedMeaning:'unchanged',materialReadbackVerified:true,formalReportPublished:false,actualPlatformCollectionPerformed:false,auditRecordsRetained:true}; checkpoint({status:'complete',receipt});return receipt; } if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){ try{ const a=process.argv.slice(2); check(a.length===5&&a[0]==='--input'&&a[2]==='--state-dir'&&a[4]==='--execute','USAGE'); check(process.platform==='linux'&&process.geteuid()===10000,'HERMES_UID_REQUIRED'); check(path.isAbsolute(a[1])&&path.isAbsolute(a[3]),'ABSOLUTE_PATH_REQUIRED'); const parent=path.dirname(a[3]); for(const file of [a[1],parent])check(fs.realpathSync(file)===file,'UNSAFE_DEDUP_PATH'); const st=fs.lstatSync(a[1]),pt=fs.lstatSync(parent); check(st.isFile()&&st.uid===process.geteuid()&&(st.mode&0o777)===0o600,'PRIVATE_CONTEXT_REQUIRED'); check(pt.isDirectory()&&pt.uid===process.geteuid()&&(pt.mode&0o777)===0o700,'PRIVATE_PARENT_REQUIRED'); const context=validateDedupContext(JSON.parse(fs.readFileSync(a[1],'utf8'))); const worker='/opt/data/skills/ksf-workshop-runtime/scripts/ksf-secure.mjs'; check(fs.statSync(worker).isFile(),'SECURE_ENTRY_UNAVAILABLE'); check(!fs.existsSync(a[3]),'DEDUP_STATE_EXISTS'); fs.mkdirSync(a[3],{mode:0o700}); check(fs.realpathSync(a[3])===a[3],'UNSAFE_DEDUP_PATH'); const journal={version:'ksf.dedup-journal.v1',taskKey:TASK_KEY,at:new Date().toISOString(),status:'running',steps:[]}; const persist=()=>fs.writeFileSync(path.join(a[3],'journal.json'),JSON.stringify(journal,null,2),{mode:0o600});persist(); let sequence=0;const invocations=[]; const invoke=async(command,task,requestId)=>{ check(['workshop-contract','workshop-dedup','workshop-import','workshop-read'].includes(command),'COMMAND_NOT_ALLOWED'); const name=String(++sequence).padStart(2,'0')+'-'+command,input=path.join(a[3],name+'.input.json'); fs.writeFileSync(input,JSON.stringify(task,null,2),{flag:'wx',mode:0o600}); const args=[worker,command,...(command==='workshop-import'?['--agent-profile',context.agentProfileKey]:[]),'--input',input,'--request-id',requestId]; // No retry: timeout/transport errors can occur after a remote write has committed. const p=spawnSync(process.execPath,args,{encoding:'utf8',timeout:660000,maxBuffer:4*1024*1024,windowsHide:true}); fs.writeFileSync(path.join(a[3],name+'.transport.json'),JSON.stringify({exitCode:p.status,signal:p.signal,stdout:p.stdout||'',stderr:p.stderr||'',spawnFailed:!!p.error}),{flag:'wx',mode:0o600}); if(p.error||p.signal)fail('DEDUP_REQUEST_UNCERTAIN'); // executeSecure writes a valid ok=false child envelope to stdout with exit 1; // wrapper-level failures use stderr. Preserve either envelope before stopping. let receipt;try{receipt=JSON.parse(p.stdout?.trim()?p.stdout:p.stderr);}catch{fail('DEDUP_RECEIPT_INVALID');} fs.writeFileSync(path.join(a[3],name+'.receipt.json'),JSON.stringify(receipt,null,2),{flag:'wx',mode:0o600}); if(!(p.status===0&&receipt?.ok===true&&receipt.entryResult?.ok===true)){ const code=receipt?.entryResult?.error?.code||receipt?.error?.code; fail(/^[A-Z][A-Z0-9_]+$/.test(code||'')?code:'DEDUP_COMMAND_FAILED'); } check(receipt.command===command&&receipt.requestId===requestId&&receipt.entryResult.command===command&&receipt.entryResult.requestId===requestId,'DEDUP_RECEIPT_BINDING_MISMATCH'); invocations.push({command,requestId,invocationId:receipt.invocationId,entryInvocationId:receipt.entryResult.invocationId}); return receipt.entryResult.result; }; try{ const receipt=await runDedupAcceptance({context,invoke,checkpoint:event=>{journal.steps.push(event);journal.status=event.status;persist();}}); receipt.importInvocations=invocations.filter(x=>x.command==='workshop-import'); fs.writeFileSync(path.join(a[3],'summary.json'),JSON.stringify(receipt,null,2),{flag:'wx',mode:0o600}); console.log(JSON.stringify(receipt,null,2)); }catch(e){journal.status='stopped';journal.error={code:safeCode(e),message:'保留原键、已返回编号和全部回执;不重试、不删目录、不换键。'};persist();throw e;} }catch(e){console.error(JSON.stringify({ok:false,error:{code:safeCode(e),message:'查重验收停止;保留现场与回执,不输出账号或凭据。'}}));process.exitCode=1;} }