import test from 'node:test';
import assert from 'node:assert/strict';
import {DatabaseSync} from 'node:sqlite';
import {readFileSync,readdirSync} from 'node:fs';
import {handle,read} from '../lib/commons.ts';
import {a2a,mcp} from '../lib/protocols.ts';
import {runDemo} from '../lib/demo.ts';
import {GET as card} from '../app/.well-known/agent-card.json/route.ts';
import {GET as discovery} from '../app/agents.json/route.ts';
import {openapi} from '../lib/openapi.ts';
function db(){const sql=new DatabaseSync(':memory:');sql.exec('PRAGMA foreign_keys=ON');for(const f of readdirSync(new URL('../drizzle/',import.meta.url)).filter(f=>f.endsWith('.sql')).sort())sql.exec(readFileSync(new URL('../drizzle/'+f,import.meta.url),'utf8'));return {prepare(s){let args=[];const stmt=sql.prepare(s);return {bind(...v){args=v;return this},async first(){return stmt.get(...args)||null},async all(){return {results:stmt.all(...args)}},async run(){return stmt.run(...args)}}},async batch(statements){sql.exec('BEGIN');try{const result=[];for(const s of statements)result.push(await s.run());sql.exec('COMMIT');return result}catch(e){sql.exec('ROLLBACK');throw e}}}}
const request=(path,method='GET',value,token,headers={})=>new Request('https://commons.test'+path,{method,headers:{...(value!==undefined?{'Content-Type':'application/json'}:{}),...(token?{Authorization:'Bearer '+token}:{}),...headers},...(value!==undefined?{body:JSON.stringify(value)}:{})});
test('complete machine workflow, permissions, validation and protocol discovery',async()=>{const d=db();const call=async(p,m='GET',b,t,expected=m==='GET'?200:201)=>{const r=await handle(d,request('/api/v1/'+p,m,b,t));const j=await r.json();assert.equal(r.status,expected,JSON.stringify(j));if(m==='POST'&&j.data?.title&&j.data.moderation_status==='pending'){await d.prepare("UPDATE tasks SET moderation_status='approved' WHERE id=?").bind(j.data.id).run();j.data.moderation_status='approved'}return j.data};
 const c=await (await card(request('/.well-known/agent-card.json'))).json();assert.equal(c.supportedInterfaces[0].protocolVersion,'1.0');assert.equal((await (await discovery(request('/agents.json'))).json()).openapi,'https://commons.test/openapi.json');assert.ok(openapi('https://commons.test').paths['/tasks/{id}/verifications']);
 const agents=[];for(const name of ['Lead','Worker','Verifier','Critic'])agents.push(await call('agents','POST',{name,description:'Test agent',capabilities:['research','statistics']}));const [lead,worker,verifier,critic]=agents;
 assert.ok(lead.token.startsWith('ac_'));assert.equal(lead.agent.token_hash,undefined);const list=await call('agents?capability=research,statistics');assert.equal(list.items.length,4);assert.equal(list.items[0].token_hash,undefined);assert.equal((await call('agents?capability=search')).items.length,0);
 await call('rooms','POST',{name:'Bad',description:'test'},'invalid',401);await call('rooms','POST',{name:'Bad',description:'test'},'ac_'+'0'.repeat(64),401);await call('agents','POST',{name:'',description:[]},undefined,422);
 const room=await call('rooms','POST',{name:'Research',description:'Evidence room'},lead.token);const message=await call('messages','POST',{room_id:room.id,content:'A finding',evidence:['https://example.org/source']},worker.token);await call('messages','POST',{room_id:room.id,parent_id:message.id,content:'Reply'},verifier.token);assert.equal((await call('messages/'+message.id)).replies.length,1);
 await call('messages','POST',{room_id:room.id,content:'secret '+lead.token},worker.token,422);await call('messages','POST',{room_id:room.id,content:'x'.repeat(40000)},worker.token,413);await call('messages','POST',{room_id:room.id,content:'url',evidence:['javascript:alert(1)']},worker.token,422);
 const task=await call('tasks','POST',{title:'Research task',description:'Check evidence',room_id:room.id},lead.token);const sub=await call('tasks/'+task.id+'/subtasks','POST',{title:'Subtask',description:'Parallel piece'},lead.token);await call('tasks/'+task.id+'/subtasks','POST',{title:'Unauthorized',description:'Piece'},critic.token,403);
 await call('tasks/'+sub.id+'/claim','POST',{},worker.token);await call('tasks/'+sub.id+'/claim','POST',{},critic.token,409);await call('tasks/'+sub.id+'/start','POST',{},worker.token);
 const result=await call('tasks/'+sub.id+'/results','POST',{content:'Result',confidence:0.8},worker.token);await call('tasks/'+sub.id+'/request-verification','POST',{},lead.token);await call('tasks/'+sub.id+'/verifications','POST',{result_id:result.id,verdict:'agree',content:'Self vote',confidence:1},worker.token,403);
 await call('tasks/'+sub.id+'/verifications','POST',{result_id:result.id,verdict:'dispute',content:'Evidence does not support claim',confidence:1},critic.token);await call('tasks/'+sub.id+'/complete','POST',{result_id:result.id},lead.token,409);
 const fixed=await call('tasks/'+sub.id+'/results','POST',{content:'Corrected result'},worker.token);await call('tasks/'+sub.id+'/verifications','POST',{result_id:fixed.id,verdict:'agree',content:'Checked',confidence:1},verifier.token);await call('tasks/'+sub.id+'/verifications','POST',{result_id:fixed.id,verdict:'agree',content:'Repeat',confidence:1},verifier.token,409);await call('tasks/'+sub.id+'/complete','POST',{result_id:fixed.id},lead.token);
 await call('tasks/'+task.id+'/claim','POST',{},lead.token);const final=await call('tasks/'+task.id+'/results','POST',{content:'Final summary'},lead.token);await call('tasks/'+task.id+'/verifications','POST',{result_id:final.id,verdict:'agree',content:'Independent check',confidence:1},verifier.token);await call('tasks/'+task.id+'/complete','POST',{result_id:final.id},lead.token);
 const artifact=await call('artifacts','POST',{task_id:task.id,result_id:final.id,type:'report',description:'Final publication',content:'Text output'},lead.token);assert.equal(artifact.provenance.produced_by,lead.agent.id);assert.equal((await call('artifacts/'+artifact.id)).provenance.verification_at_publication.agree,1);assert.equal((await call('tasks/'+task.id)).subtasks.length,1);assert.ok((await call('feed')).items.length>10);assert.equal((await call('rooms/'+room.id)).participants.length,2);
 const a=await a2a(d,request('/a2a/message:send','POST',{message:{messageId:'test-1',role:'ROLE_USER',parts:[{text:'Investigate this question'}]}},worker.token,{'A2A-Version':'1.0'}));assert.equal(a.status,200);const at=await a.json();assert.equal(at.task.status.state,'TASK_STATE_SUBMITTED');assert.equal((await a2a(d,request('/a2a/tasks/'+at.task.id,'GET',undefined,worker.token))).status,200);
 let mr=await mcp(d,request('/mcp','POST',{jsonrpc:'2.0',id:1,method:'initialize',params:{protocolVersion:'2025-11-25',capabilities:{},clientInfo:{name:'test',version:'1'}}}));assert.equal((await mr.json()).result.protocolVersion,'2025-11-25');mr=await mcp(d,request('/mcp','POST',{jsonrpc:'2.0',id:2,method:'tools/call',params:{name:'read_commons',arguments:{path:'stats'},_meta:{'io.modelcontextprotocol/protocolVersion':'2026-07-28'}}},undefined,{'MCP-Protocol-Version':'2026-07-28','Mcp-Method':'tools/call','Mcp-Name':'read_commons',Accept:'application/json, text/event-stream'}));assert.equal((await mr.json()).result.isError,false);assert.equal((await mcp(d,request('/mcp','POST',{jsonrpc:'2.0',id:3,method:'tools/list'},undefined,{Origin:'https://evil.test'}))).status,403);
 await call('agents/me/revoke','POST',{},critic.token);await call('rooms','POST',{name:'Revoked',description:'no'},critic.token,401);
});
test('deterministic demo completes with retained disputes and provenance; rerun is bounded',async()=>{const d=db();const result=await runDemo(d);assert.equal(result.status,'completed');const t=await read(d,['tasks',result.task_id],new URLSearchParams());assert.equal(t.status,'completed');assert.equal(t.subtasks.length,2);assert.equal(t.artifacts.length,1);const agents=await read(d,['agents'],new URLSearchParams());assert.equal(agents.items.length,6);assert.ok(agents.items.filter(a=>!a.managed).every(a=>a.demo===1));assert.equal((await runDemo(d)).status,'already_started')});
test('registration throttle enforced',async()=>{const d=db();for(let i=0;i<9;i++){const r=await handle(d,request('/api/v1/agents','POST',{name:'Agent '+i,description:'A client'}));assert.equal(r.status,i<8?201:429)}});

test('no-signup utilities preserve meaningful differences and reject unsafe input',async()=>{
 const {utility}=await import('../lib/utilities.ts');
 const d=utility('citation-audit',{sources:['doi:10.1000/ABC','https://doi.org/10.1000/abc','https://arxiv.org/pdf/2401.12345v2.pdf','https://arxiv.org/abs/2401.12345v2','https://arxiv.org/abs/2401.12345v1','https://example.org/p?utm_source=email','https://example.org/p','https://example.org/p?id=2','javascript:alert(1)']});
 assert.equal(d.duplicate_groups.length,3);assert.equal(d.unique_document_candidates,5);assert.equal(d.entries[8].key,null);
 assert.equal(utility('validate-json',{text:'{"ok":true}'}).valid,true);assert.equal(utility('validate-json',{text:'{"ok":}'}).valid,false);
 assert.throws(()=>utility('citation-audit',{sources:Array(51).fill('https://example.org')}));
});
test('real missions and community metrics exclude site-operated and demo agents',async()=>{
 const {launchMissions}=await import('../lib/missions.ts');const d=db();
 const start=await launchMissions(d);assert.equal(start.task_ids.length,10);assert.equal((await launchMissions(d)).status,'already_started');
 const missions=await read(d,['opportunities'],new URLSearchParams());assert.equal(missions.open_tasks.length,10);
 const metrics=await read(d,['adoption'],new URLSearchParams());assert.equal(metrics.community_agents,0);
 const post=async(path,value,token)=>{const response=await handle(d,request('/api/v1/'+path,'POST',value,token));const j=await response.json();assert.equal(response.status,201,JSON.stringify(j));return j.data};
 const worker=await post('agents',{name:'Community worker',description:'Researches primary evidence'});const verifier=await post('agents',{name:'Community reviewer',description:'Independently checks evidence'});
 const taskId=start.task_ids[0];await post('tasks/'+taskId+'/claim',{},worker.token);const result=await post('tasks/'+taskId+'/results',{content:'Original assessment',evidence:['https://www.nature.com/articles/s41586-023-06747-5']},worker.token);await post('tasks/'+taskId+'/verifications',{result_id:result.id,verdict:'agree',content:'Independent review',confidence:0.8},verifier.token);
 const daily=await launchMissions(d,true);assert.equal(daily.status,'backlog_full');assert.equal(daily.published.length,1);assert.equal((await launchMissions(d,true)).status,'already_started');
 await runDemo(d);const after=await read(d,['adoption'],new URLSearchParams());assert.equal(after.community_agents,2);assert.equal(after.community_artifacts,1);assert.equal(after.verified_community_tasks,1);
});
test('JavaScript connection client protects token destination and decodes errors',async()=>{
 const {AgentCommons,CommonsError}=await import('../public/sdk/agent-commons.mjs');assert.throws(()=>new AgentCommons({origin:'http://insecure.test'}));
 const client=new AgentCommons({token:'test-token',origin:'https://commons.test'});await assert.rejects(()=>client.request('https://evil.test'));
 const previous=globalThis.fetch;globalThis.fetch=async(url,options)=>{assert.equal(url.origin,'https://commons.test');assert.equal(options.redirect,'error');assert.equal(options.headers.Authorization,'Bearer test-token');return Response.json({data:{items:[{id:'task'}]}})};
 try{assert.equal((await client.findTasks({capability:'research'}))[0].id,'task')}finally{globalThis.fetch=previous}
});

test('task commons contract, safe discovery, abuse boundaries and audit hashes',async()=>{
 const d=db();const call=async(path,method='GET',value,token,status=method==='GET'?200:201)=>{const r=await handle(d,request(path,method,value,token));const j=await r.json();assert.equal(r.status,status,JSON.stringify(j));if(method==='POST'&&j.data?.title&&j.data.risk_level==='low')await d.prepare("UPDATE tasks SET moderation_status='approved' WHERE id=?").bind(j.data.id).run();return j.data};
 const lead=await call('/api/v1/agents','POST',{name:'Task curator',description:'Test fixture'});
 const worker=await call('/api/v1/agents','POST',{name:'Task worker',description:'Test fixture'});
 const legacy=await call('/api/tasks','POST',{title:'Needs review',description:'Incomplete legacy brief'},lead.token);
 assert.equal(legacy.risk_level,'review_required');assert.equal((await call('/api/tasks')).items.length,0);
 const brief={title:'Check inline JSON',description:'Explain why {"a":} is invalid JSON. Return a proposed correction only.',objective:'Identify syntax error',risk_level:'low',category:'data',difficulty:'easy',estimated_minutes:5,required_capabilities:['json'],expected_output:'One corrected JSON value plus explanation',acceptance_criteria:['Identify missing value','Return valid JSON'],license:'CC0-1.0'};
 await call('/api/tasks','POST',{...brief,external_side_effects_allowed:true},lead.token,422);
 await call('/api/tasks','POST',{...brief,allowed_tools:['credential_use']},lead.token,422);
 await call('/api/tasks','POST',{...brief,risk_level:'high'},lead.token,422);
 await call('/api/tasks','POST',{...brief,inputs:[{description:'Poisoned link',url:'https://127.0.0.1/private'}]},lead.token,422);
 await call('/api/tasks','POST',{...brief,prohibited_actions:[]},lead.token,422);
 const expired=await call('/api/tasks','POST',{...brief,expires_at:'2000-01-01T00:00:00.000Z'},lead.token);
 await call('/api/tasks/'+expired.id+'/claim','POST',{},worker.token,409);
 const task=await call('/api/tasks','POST',brief,lead.token);
 const listed=(await call('/api/tasks?capability=json')).items;assert.equal(listed.length,1);assert.equal(listed[0].id,task.id);assert.equal(listed[0].external_side_effects_allowed,false);
 await call('/api/tasks/'+task.id+'/unknown','GET',undefined,undefined,404);
 await call('/api/tasks/'+task.id+'/claim','POST',{},worker.token);
 const result=await call(task.submission_endpoint,'POST',{content:'{"a":null}\nThe original value is missing.'},worker.token);
 const detail=await call('/api/tasks/'+task.id);assert.equal(detail.results[0].id,result.id);assert.match(detail.results[0].content_sha256,/^[a-f0-9]{64}$/);assert.equal(detail.results[0].acceptance_status,'pending_review');assert.ok(detail.audit_events.some(e=>e.action==='submitted'));assert.equal(detail.revision,1);assert.equal(detail.protocol,undefined);
 assert.ok(openapi('https://commons.test').components.schemas.Task.properties.external_side_effects_allowed.const===false);
});

test('moderation, lease recovery, output checks and idempotent retries cannot be bypassed',async()=>{
 const {moderate,authorizeModerator}=await import('../lib/moderation.ts');const d=db();
 const call=async(path,method='GET',value,token,status=method==='GET'?200:201)=>{const r=await handle(d,request('/api/'+path,method,value,token));const j=await r.json();assert.equal(r.status,status,JSON.stringify(j));return j.data};
 const creator=await call('v1/agents','POST',{name:'Test curator',description:'Isolated fixture'}),worker=await call('v1/agents','POST',{name:'Test contributor',description:'Isolated fixture'});
 const task=await call('tasks','POST',{title:'JSON correction',description:'Return a JSON object proposing a correction.',risk_level:'low',output_format:'json',required_output_keys:['proposed']},creator.token);
 assert.equal(task.moderation_status,'pending');assert.equal((await call('tasks')).items.length,0);await call('tasks/'+task.id+'/claim','POST',{},worker.token,409);
 assert.throws(()=>authorizeModerator(null,'owner@example.com'));assert.throws(()=>authorizeModerator('other@example.com','owner@example.com'));assert.doesNotThrow(()=>authorizeModerator('owner@example.com','owner@example.com'));
 await moderate(d,{task_id:task.id,decision:'approved',reason:'Reviewed isolated JSON-only task.'});assert.equal((await call('tasks')).items.length,1);
 const claimed=await call('tasks/'+task.id+'/claim','POST',{},worker.token);assert.ok(Date.parse(claimed.claim_expires_at)>Date.now());
 await call('tasks/'+task.id+'/release','POST',{},creator.token,409);await call('tasks/'+task.id+'/renew','POST',{},worker.token);
 await d.prepare("UPDATE tasks SET claim_expires_at='2000-01-01T00:00:00.000Z' WHERE id=?").bind(task.id).run();assert.equal((await call('tasks')).items.length,1);await call('tasks/'+task.id+'/results','POST',{content:'{}'},worker.token,409);
 await call('tasks/'+task.id+'/claim','POST',{},worker.token);await call('tasks/'+task.id+'/results','POST',{content:'not JSON'},worker.token,422);
 await call('tasks/'+task.id+'/results','POST',{content:'{}'},worker.token,422);
 const payload={content:'{"proposed":true}',submission_key:'retry-safe-001'};const result=await call('tasks/'+task.id+'/results','POST',payload,worker.token);assert.equal(result.validation.validator,'json-contract-v1');assert.equal((await call('tasks/'+task.id+'/results','POST',payload,worker.token)).id,result.id);
 await call('tasks/'+task.id+'/results','POST',{...payload,content:'{}'},worker.token,409);assert.equal((await call('tasks/'+task.id)).results.length,1);
 await moderate(d,{task_id:task.id,decision:'quarantined',reason:'Testing the moderator quarantine gate.'});await call('tasks/'+task.id+'/results','POST',{content:'{}'},worker.token,409);
 const rpc=await mcp(d,request('/api/mcp','POST',{jsonrpc:'2.0',id:1,method:'tools/call',params:{name:'task_action',arguments:{task_id:task.id,action:'claim',body:{}}}},worker.token));assert.equal(rpc.status,409);
 assert.ok((await call('tasks/'+task.id)).audit_events.some(e=>e.action==='claim expired'));
});

test('additive upgrade preserves existing tasks while seeding one real bounded audit',()=>{
 const sql=new DatabaseSync(':memory:');sql.exec('PRAGMA foreign_keys=ON');const files=readdirSync('drizzle').filter(f=>f.endsWith('.sql')).sort();for(const f of files.filter(f=>f<'0004'))sql.exec(readFileSync('drizzle/'+f,'utf8'));
 sql.exec("INSERT INTO agents(id,created_at,name,description,capabilities,interests,token_hash,last_seen,managed) VALUES ('curator','2026-09-01T00:00:00Z','Commons Mission Desk','Curated tasks','[]','[]','curatorhash','2026-09-01T00:00:00Z',1),('community','2026-09-01T00:00:00Z','Community','Community tasks','[]','[]','communityhash','2026-09-01T00:00:00Z',0)");
 sql.exec("INSERT INTO tasks(id,created_at,creator,title,description,required_capabilities,status,updated_at) VALUES ('prior','2026-09-01T00:00:00Z','community','Prior task','Original content','[]','claimed','2026-09-01T00:00:00Z')");
 sql.exec(readFileSync('drizzle/0004_moderation_leases.sql','utf8'));
 const prior=sql.prepare("SELECT * FROM tasks WHERE id='prior'").get();assert.equal(prior.description,'Original content');assert.equal(prior.moderation_status,'pending');assert.ok(prior.claim_expires_at);
 const seeded=sql.prepare("SELECT * FROM tasks WHERE creator='curator'").all();assert.equal(seeded.length,1);assert.equal(seeded[0].moderation_status,'approved');assert.equal(JSON.parse(seeded[0].protocol).output_format,'json');sql.close();
});

test('atomic write guard rolls back submission when moderation changes concurrently',async()=>{
 const {register,write}=await import('../lib/commons.ts');const {moderate}=await import('../lib/moderation.ts');const d=db();const a=(await register(d,{name:'Race fixture',description:'Isolated test'},'race')).agent;
 const t=await write(d,['tasks'],{title:'Race task',description:'Bounded text'},a);await moderate(d,{task_id:t.id,decision:'approved',reason:'Approved isolated test fixture.'});await write(d,['tasks',t.id,'claim'],{},a);
 const original=d.batch;d.batch=async statements=>{if(statements.length===5)await d.prepare("UPDATE tasks SET moderation_status='quarantined' WHERE id=?").bind(t.id).run();return original(statements)};
 await assert.rejects(()=>write(d,['tasks',t.id,'results'],{content:'Should not persist'},a),e=>e.code==='INVALID_STATE');
 assert.equal((await d.prepare('SELECT count(*) AS n FROM results').first()).n,0);assert.equal((await d.prepare('SELECT count(*) AS n FROM mutation_guards').first()).n,0);
});

test('human problem ownership, moderation, acceptance, private notices and dispute removal',async()=>{
 const {submitProblem,myProblems,requestPrivacy}=await import('../lib/humans.ts');
 const {moderate,acceptReviewed,removeContact}=await import('../lib/moderation.ts');
 const {dispatchNotifications}=await import('../lib/notifications.ts');
 const {trophies,publicProblems}=await import('../lib/public-work.ts');
 const d=db(),human={id:'private-site-person-one',email:'test-owner@example.invalid'},other={id:'private-site-person-two',email:'other@example.invalid'};
 const brief={title:'Check public form label clarity',problem:'Review the public form labels for ambiguity.',why:'Clear labels help people submit useful public problems.',output:'Return exact proposed label changes and source evidence.',done:'Identify each ambiguous control and explain the proposed correction.',sources:['https://www.w3.org/WAI/tutorials/forms/labels/'],category:'accessibility',public_consent:true};
 await assert.rejects(()=>submitProblem(d,null,brief),e=>e.status===401);
 await assert.rejects(()=>submitProblem(d,{id:null,email:human.email},brief),e=>e.status===401);
 await assert.rejects(()=>submitProblem(d,human,{...brief,public_consent:false}));
 await assert.rejects(()=>submitProblem(d,human,{...brief,sources:['https://127.0.0.1/private']}));
 const task=await submitProblem(d,human,brief);assert.equal(task.status,'pending');assert.equal((await myProblems(d,human)).length,1);assert.equal((await myProblems(d,other)).length,0);
 const publicRecord=await read(d,['tasks',task.id],new URLSearchParams());assert.equal(publicRecord.moderation_status,'pending');assert.equal(publicRecord.published_at,null);assert.doesNotMatch(JSON.stringify(publicRecord),/test-owner|private-site-person/);assert.equal((await publicProblems(d,{})).length,0);
 const post=async(path,input,token,status=201)=>{const r=await handle(d,request('/api/tasks/'+path,'POST',input,token));const j=await r.json();assert.equal(r.status,status,JSON.stringify(j));return j.data};
 const reg=async name=>(await (await handle(d,request('/api/v1/agents','POST',{name,description:'Isolated test fixture'}))).json()).data;
 const worker=await reg('Human problem worker'),reviewer=await reg('Independent reviewer'),critic=await reg('Later critic');
 await post(task.id+'/claim',{},worker.token,409);await moderate(d,{task_id:task.id,decision:'approved',reason:'Bounded public source review with clear criteria.'});
 assert.equal((await publicProblems(d,{category:'accessibility',minutes:'20'})).length,1);assert.equal((await publicProblems(d,{category:'data'})).length,0);
 await post(task.id+'/claim',{},worker.token);const result=await post(task.id+'/results',{content:'Original proposed labels with rationale.',evidence:brief.sources,submission_key:'human-result-001'},worker.token);
 await assert.rejects(()=>acceptReviewed(d,{task_id:task.id,result_id:result.id,reason:'All objective criteria were checked against the sources.',criteria_checked:true}),e=>e.status===409);
 await post(task.id+'/verifications',{result_id:result.id,verdict:'agree',content:'Checked each label and rationale independently.',confidence:.8,evidence:brief.sources},reviewer.token);
 await acceptReviewed(d,{task_id:task.id,result_id:result.id,reason:'All objective criteria were checked against the public sources.',criteria_checked:true});
 assert.equal((await trophies(d)).length,1);assert.equal((await myProblems(d,human))[0].notification_status,'pending');assert.equal((await dispatchNotifications(d,{})).status,'not_configured');
 let sends=0;const send=async(url,options)=>{sends++;assert.equal(url,'https://api.resend.com/emails');const b=JSON.parse(options.body);assert.deepEqual(b.to,[human.email]);assert.match(b.text,new RegExp('/trophy-case/'+task.id));assert.equal(options.headers['Idempotency-Key'],'otr-result-'+result.id);return Response.json({id:'test-provider-receipt'})};
 await Promise.all([dispatchNotifications(d,{RESEND_API_KEY:'fixture',NOTIFICATION_FROM:'sender@example.invalid'},send),dispatchNotifications(d,{RESEND_API_KEY:'fixture',NOTIFICATION_FROM:'sender@example.invalid'},send)]);assert.equal(sends,1);assert.equal((await myProblems(d,human))[0].notification_status,'sent');
 await post(task.id+'/verifications',{result_id:result.id,verdict:'dispute',content:'A later correction requires attention.',confidence:.9,evidence:brief.sources},critic.token);assert.equal((await trophies(d)).length,0);assert.equal((await read(d,['tasks',task.id],new URLSearchParams())).accepted_result_id,result.id);
 await requestPrivacy(d,human);await removeContact(d,{task_id:task.id});assert.equal((await myProblems(d,human)).length,0);assert.ok(await read(d,['tasks',task.id],new URLSearchParams()));
});

test('acceptance rechecks review state atomically and rolls back a racing dispute',async()=>{
 const {register,write}=await import('../lib/commons.ts');const d=db();const lead=(await register(d,{name:'Curator fixture',description:'Isolated test'},'one')).agent;lead.managed=1;
 const worker=(await register(d,{name:'Worker fixture',description:'Isolated test'},'two')).agent,reviewer=(await register(d,{name:'Review fixture',description:'Isolated test'},'three')).agent;
 const t=await write(d,['tasks'],{title:'Race fixture',description:'Original test',risk_level:'low'},lead);await write(d,['tasks',t.id,'claim'],{},worker);const r=await write(d,['tasks',t.id,'results'],{content:'Candidate'},worker);await write(d,['tasks',t.id,'verifications'],{result_id:r.id,verdict:'agree',content:'Checked',confidence:1},reviewer);
 const original=d.batch.bind(d);d.batch=async statements=>{if(statements.length!==7)return original(statements);d.batch=original;await d.prepare("INSERT INTO verifications(id,created_at,result_id,author,verdict,content,evidence,confidence) VALUES('race-vote','2026-09-06',?,?,'dispute','Concurrent evidence','[]',1)").bind(r.id,worker.id).run();return original(statements)};
 await assert.rejects(()=>write(d,['tasks',t.id,'complete'],{result_id:r.id},lead));assert.equal((await read(d,['tasks',t.id],new URLSearchParams())).accepted_result_id,null);
});
