scripts / image-selection-review-smoke.cjs

const assert=require('node:assert/strict');
const fs=require('node:fs/promises');
const path=require('node:path');
const os=require('node:os');
const crypto=require('node:crypto');
const sharp=require('sharp');
const {toolsProvider}=require('../dist/toolsProvider');
const digest=bytes=>crypto.createHash('sha256').update(bytes).digest('hex');

(async()=>{
 const root=await fs.mkdtemp(path.join(os.tmpdir(),'aia-selection-'));
 const other=await fs.mkdtemp(path.join(os.tmpdir(),'aia-selection-other-'));
 try{
  const red=await sharp({create:{width:16,height:16,channels:3,background:'red'}}).png().toBuffer();
  const blue=await sharp({create:{width:16,height:16,channels:3,background:'blue'}}).png().toBuffer();
  const ref=`aia-attachments/${digest(red)}/MISLEADING-ROOM-PHOTO.png`;
  for(const directory of [root,other]){
   await fs.mkdir(path.dirname(path.join(directory,ref)),{recursive:true});
   await fs.writeFile(path.join(directory,ref),red);
   await fs.writeFile(path.join(directory,ref.replace(/\.png$/,'.json')),JSON.stringify({source:'chat-attachment',originalFilename:'MISLEADING-ROOM-PHOTO.png',caption:'A bedroom full of balloons',attachmentSha256:digest(red)}));
   await fs.writeFile(path.join(directory,'download-blue.png'),blue);
   await fs.writeFile(path.join(directory,'download-blue.json'),JSON.stringify({source:'download',caption:'downloaded image'}));
   await fs.writeFile(path.join(directory,'download-red.png'),red);
   await fs.writeFile(path.join(directory,'download-red.json'),JSON.stringify({source:'download'}));
  }
  let neutral=0,comparisons=0,modelId='test-vlm';
  const client={files:{},llm:{model:async()=>({vision:true,identifier:modelId,path:'test/model',respond:async(messages)=>{
   const message=messages[0];assert.equal(message.images.length,2);
   if(message.content.includes('visual inventory check')){
    neutral++;
    assert(!message.content.includes('balloons'));
    assert(!message.content.includes('MISLEADING-ROOM-PHOTO'));
    assert(!message.content.includes('Image metadata from sidecar'));
    assert(message.images.every(file=>file.name.startsWith('verification-image-')));
    return {content:'Image 1: a red square. Image 2: a blue square. No room or balloon is visible.'};
   }
   comparisons++;return {content:'Verified red and blue images compared.'};
  }})}};
  const ctl=directory=>({client,getWorkingDirectory:()=>directory,getPluginConfig:()=>({get:key=>({analysisBackend:'local',strataModel:'strata'})[key]})});
  const ctx={signal:new AbortController().signal,status(){},warn(){},callId:1};
  const multi=(await toolsProvider(ctl(root)))[3];
  const args={imageNames:[ref,'download-blue.png'],prompt:'Compare bedroom balloons with the reference photo.',context:'Assume the room photo shows a balloon.'};
  const check=await multi.implementation({...args,imageNames:JSON.stringify(args.imageNames)},ctx);
  assert.equal(check.status,'image_selection_check_required');assert.equal(check.analysis,undefined);
  assert.equal(check._aiaImageCandidates,undefined,'an inventory must not trigger automatic analysis handoff');
  assert.match(check.observations,/No room or balloon/);
  assert.equal(check.images[0].originalFilename,'MISLEADING-ROOM-PHOTO.png');
  assert.equal(check.images[0].sha256,digest(red));
  assert.equal(neutral,1);assert.equal(comparisons,0);
  const fake=await multi.implementation({...args,verificationToken:'f'.repeat(32)},ctx);
  assert.equal(fake.status,'image_selection_check_required');assert.equal(neutral,1);assert.equal(comparisons,0);
  const confirmed=await multi.implementation({...args,imageNames:JSON.stringify(args.imageNames),verificationToken:check.verificationToken},ctx);
  assert.equal(confirmed.analysis,'Verified red and blue images compared.');assert.equal(comparisons,1);
  const fresh=(await toolsProvider(ctl(root)))[3];
  assert.equal((await fresh.implementation(args,ctx)).verificationToken,check.verificationToken,'disk review survives a new tool provider');
  assert.equal(neutral,1);
  const reordered=await multi.implementation({...args,imageNames:[...args.imageNames].reverse(),verificationToken:check.verificationToken},ctx);
  assert.equal(reordered.status,'image_selection_check_required');assert.equal(neutral,2);assert.equal(comparisons,1);
  const differentRoot=(await toolsProvider(ctl(other)))[3];
  assert.equal((await differentRoot.implementation({...args,verificationToken:check.verificationToken},ctx)).status,'image_selection_check_required');
  assert.equal(neutral,3);assert.equal(comparisons,1);
  modelId='different-vlm';
  assert.equal((await multi.implementation({...args,verificationToken:check.verificationToken},ctx)).status,'image_selection_check_required');
  assert.equal(neutral,4);assert.equal(comparisons,1);modelId='test-vlm';
  const downloadOnly=await multi.implementation({imageNames:['download-red.png','download-blue.png'],prompt:'compare'},ctx);
  assert.equal(downloadOnly.analysis,'Verified red and blue images compared.');assert.equal(comparisons,2);
  const alias=await multi.implementation({...args,imageNames:['download-red.png',ref,'download-blue.png']},ctx);
  assert.equal(alias.status,'image_selection_check_required','a deduplicated manual attachment still requires a check');
  assert.equal(comparisons,2);
  const reviewDir=path.join(root,'.aia-image-reviews');
  for(const name of await fs.readdir(reviewDir)){
   const file=path.join(reviewDir,name),review=JSON.parse(await fs.readFile(file,'utf8'));
   if(review.token===check.verificationToken){review.createdAt=Date.now()-25*60*60*1000;await fs.writeFile(file,JSON.stringify(review));}
  }
  const expired=await multi.implementation({...args,verificationToken:check.verificationToken},ctx);
  assert.equal(expired.status,'image_selection_check_required');assert.notEqual(expired.verificationToken,check.verificationToken);
  await fs.writeFile(path.join(root,ref),blue);
  const beforeNeutral=neutral;
  const changed=await multi.implementation({...args,verificationToken:expired.verificationToken},ctx);
  assert.equal(changed.error,'image_prepare_failed');assert.match(changed.message,/no longer match|content-addressed/);
  assert.equal(neutral,beforeNeutral);assert.equal(comparisons,2,'changed attachments must never run comparison');
  let strataCalls=0;const originalFetch=global.fetch;
  const strataCtl={...ctl(other),client:{files:{},llm:{model:async()=>{throw new Error('must not use local helper');}}},
   getPluginConfig:()=>({get:key=>({analysisBackend:'strata',strataModel:'strata'})[key]}),
   getGlobalPluginConfig:()=>({get:key=>({strataBaseUrl:'http://127.0.0.1:8080/v1',strataApiKey:''})[key]})};
  global.fetch=async(_url,options)=>{
   strataCalls++;const body=JSON.parse(options.body),content=body.messages[0].content;
   assert.equal(content[1].image_url.url,'data:image/png;base64,'+red.toString('base64'));
   assert.equal(content[2].image_url.url,'data:image/png;base64,'+blue.toString('base64'));
   const checking=content[0].text.includes('visual inventory check');
   if(checking){assert(!content[0].text.includes('bedroom balloons'));assert(!content[0].text.includes('MISLEADING-ROOM-PHOTO'));}
   return Response.json({choices:[{message:{content:checking?'Image 1 is red; Image 2 is blue.':'Joint Strata comparison.'}}]});
  };
  try{
   const strataTool=(await toolsProvider(strataCtl))[3];
   const first=await strataTool.implementation(args,ctx);
   assert.equal(first.status,'image_selection_check_required');assert.equal(first.backend.type,'strata');
   const last=await strataTool.implementation({...args,verificationToken:first.verificationToken},ctx);
   assert.equal(last.analysis,'Joint Strata comparison.');assert.equal(strataCalls,2);
  }finally{global.fetch=originalFetch;}
  console.log('PASS: neutral actual-pixel inventory before manual comparison, no task/name/caption leakage, explicit model acknowledgement, no forged/changed/order/root/backend/expired review reuse, durable review cache, download-only compatibility and duplicate-manual protection.');
  console.log('Vision responses are mocked; real image bytes, SDK handles, path/hash validation and on-disk review state are exercised. This does not guarantee model interpretation accuracy.');
 }finally{await fs.rm(root,{recursive:true,force:true});await fs.rm(other,{recursive:true,force:true});}
})().catch(error=>{console.error(error);process.exitCode=1;});