Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

33.3 KB
Raw Blame
import test from 'node:test';
import assert from 'node:assert/strict';
import {createCompletionAssurance, promisesExecution, researchRequested, executionContext} from '../plugin/completion-assurance.mjs';
import {createToolLoopGuard} from '../plugin/tool-loop-guard.mjs';

test('file readback and download delivery are not requests to read web sources', () => {
  const final = 'Pronto. Criei exatamente os dois arquivos, li ambos de volta e publiquei para download com os nomes exatos.\n\n**despesas.csv** (lido de volta):\n```\ncategoria,valor\nHospedagem,120\nDomínio,40\n```\n\n**resumo.md** (lido de volta):\n```\n# Resumo de despesas\n\nTotal: R$ 160,00\n\n## Gastos\n\n- Hospedagem: R$ 120,00\n- Domínio: R$ 40,00\n```\n\nOs dois downloads verificados estão anexados acima. Nenhuma dependência foi instalada, nenhum site foi criado e nenhum preview foi publicado.';
  for (const prompt of [
    'Crie em Playground/ods-qa-delivery-final-20260930-1449 exatamente dois arquivos: despesas.csv com cabeçalho categoria,valor e linhas Hospedagem,120 e Domínio,40; e resumo.md com o total de R$ 160,00 e a lista dos dois gastos. Leia os dois arquivos de volta e entregue links para baixá-los com esses nomes exatos. Não instale dependências, não crie site e não publique preview.',
    'Create two files, read the files back, and provide download links.',
    'Leia os arquivos criados e entregue URLs para download.',
    'Read the files back and return links to download them.',
    'Ler os arquivos antes de fornecer links para download.',
  ]) {
    const guard = createCompletionAssurance(); guard.begin(prompt);
    guard.observe('write', {result:{content:[{type:'text',text:'Files written'}]}});
    guard.observe('read', {result:{content:[{type:'text',text:'categoria,valor\nHospedagem,120\nDomínio,40'}]}});
    assert.equal(guard.finalize(final), undefined, prompt);
    assert.equal(guard.terminal, undefined);
  }
});

test('mixed file delivery and real source reads retain research and citation gates', () => {
  for (const prompt of [
    'Leia os arquivos e depois leia as fontes e entregue links para baixar os arquivos.',
    'Read the files, then open the source pages and provide download links.',
    'Read the files and sources before producing the downloads.',
    'Leia os arquivos e as fontes antes de entregar links para download.',
    'Open the links and save the files.',
    'Leia as páginas e crie os arquivos.',
  ]) {
    const guard = createCompletionAssurance(); guard.begin(prompt);
    guard.observe('read', {result:{content:[{type:'text',text:'Local file content'}]}});
    assert.equal(guard.finalize('Done.')?.action, 'revise', prompt);
    guard.observe('web_search', {result:{details:{results:[{url:'https://example.org/source'}]}}});
    assert.equal(guard.finalize('Evidence: https://example.org/source')?.action, 'revise', prompt);
    guard.observe('web_fetch', {result:{details:{status:200,url:'https://example.org/source',text:'Evidence'}}});
    assert.equal(guard.finalize('Evidence: https://example.org/source'), undefined, prompt);
  }
});

test('screenshot research request requires evidence, not an answer from memory', () => {
  const guard = createCompletionAssurance();
  guard.begin('queria saber notícias de hoje sobre o stf dia 15/09/2026');
  assert.equal(guard.finalize('As notícias são estas.')?.action, 'revise');
});

const mixedDocsPrompt = 'Use web search to find the official Python documentation for csv.DictReader. Then create sales.csv in the workspace and read it back. Give me the direct CSV download, row count, total, and official documentation link.';
const docsUrl = 'https://docs.python.org/3/library/csv.html';
const searchReceipt = {details:{results:[{url:docsUrl}]},content:[{type:'text',text:'Python csv documentation'}]};
const docsReceipt = {details:{status:200,url:docsUrl,text:'csv.DictReader reads CSV rows as dictionaries.'},content:[{type:'text',text:'csv.DictReader reads CSV rows as dictionaries.'}]};

test('mixed source and file task gets one early reminder, then real page reads satisfy attribution',()=>{
  const assurance=createCompletionAssurance();assurance.begin(mixedDocsPrompt);
  assert.equal(assurance.beforeWorkspaceMutation(),undefined,'no invented search leads');
  assurance.observe('web_search',{result:searchReceipt});
  assert.equal(assurance.beforeWorkspaceMutation()?.block,true);
  assert.equal(assurance.beforeWorkspaceMutation(),undefined,'bounded guidance, not a permanent write gate');
  assert.deepEqual(assurance.readPages,[],'reminder is not page evidence');
  assurance.observe('web_fetch',{result:docsReceipt});
  assurance.observe('write',{result:{content:[{type:'text',text:'Saved CSV'}]}});
  assert.equal(assurance.finalize(`The CSV has 3 rows and total 12. The Python documentation is at ${docsUrl}.`),undefined);
});

test('early reminder leaves citation checks intact when ignored or a source fails',()=>{
  for(const failed of [undefined,{isError:true,content:[{type:'text',text:'Denied'}]},
    {details:{status:403,url:docsUrl,text:'Forbidden'}}]) {
    const assurance=createCompletionAssurance();assurance.begin(mixedDocsPrompt);
    assurance.observe('web_search',{result:searchReceipt});
    if(failed) assurance.observe('web_fetch',{result:failed});
    assert.equal(assurance.beforeWorkspaceMutation()?.block,failed?undefined:true);
    assert.deepEqual(assurance.readPages,[]);
    assert.equal(assurance.finalize(`The CSV has 3 rows and total 12. Docs: ${docsUrl}`)?.action,'revise');
  }
});

test('page reads, explicit read opt-outs, cancellation and plain file tasks do not get early reminders',()=>{
  for(const prompt of ['Create sales.csv and give me a download link.',
    'Search for documentation without reading pages, then create sales.csv.',
    'Translate: open official source pages and create sales.csv.']) {
    const assurance=createCompletionAssurance();assurance.begin(prompt);
    assurance.observe('web_search',{result:searchReceipt});
    assert.equal(assurance.beforeWorkspaceMutation(),undefined,prompt);
  }
  for(const action of ['read','cancel']) {
    const assurance=createCompletionAssurance();assurance.begin(mixedDocsPrompt);
    assurance.observe('web_search',{result:searchReceipt});
    if(action==='read') assurance.observe('web_fetch',{result:docsReceipt});else assurance.cancel();
    assert.equal(assurance.beforeWorkspaceMutation(),undefined,action);
  }
});

for(const wrapped of [false,true]) for(const toolName of ['write','exec'])
test(`production guard reminds before mixed-task workspace work, ${toolName}, wrapped=${wrapped}`,()=>{
  const context={agentId:'pixel',trigger:'user',runId:'mixed-source-read',sessionId:'mixed-source-read',sessionKey:`agent:pixel:openai-user:ods-${'a'.repeat(64)}`};
  const guard=createToolLoopGuard();
  guard.observeRun(context,'pixel',{prompt:mixedDocsPrompt});
  guard.afterToolCall({toolName:'web_search',params:{query:'Python csv docs'},result:searchReceipt},context,'pixel');
  const args=toolName==='write'?{path:'sales.csv',content:'item,amount\napples,7'}:{command:'python3 make_csv.py'};
  const event={toolName:wrapped?'tool_call':toolName,params:wrapped?{id:toolName,args}:args,toolCallId:'first-workspace-call'};
  const reminder=guard.beforeToolCall(event,context,'pixel');
  assert.equal(reminder?.block,true);
  assert.match(reminder.blockReason,/Search results are leads/);
  guard.afterToolCall({toolName:'web_fetch',params:{url:docsUrl},result:docsReceipt},context,'pixel');
  assert.doesNotMatch(guard.beforeToolCall(event,context,'pixel')?.blockReason??'',/Search results are leads/);
});

test('operator-disabled page reading does not trigger workspace read guidance',()=>{
  const context={agentId:'pixel',trigger:'user',runId:'disabled-page-reading',sessionId:'disabled-page-reading'};
  const guard=createToolLoopGuard({hostCitationVerifier:{allowed:()=>false}});
  guard.observeRun(context,'pixel',{prompt:mixedDocsPrompt});
  guard.afterToolCall({toolName:'web_search',result:searchReceipt},context,'pixel');
  const result=guard.beforeToolCall({toolName:'write',params:{path:'sales.csv',content:'item,amount'},toolCallId:'disabled-source-write'},context,'pixel');
  assert.doesNotMatch(result?.blockReason??'',/Search results are leads/);
});
test('two revisions then honest terminal outcome; discovery is not research', () => {
  const guard = createCompletionAssurance();
  guard.begin('ok consulte.');
  guard.observe('tool_search', {result:{content:[{text:'web_search'}]}});
  for (let n=0;n<2;n++) assert.equal(guard.finalize('Vou consultar agora as notícias sobre o STF.')?.action, 'revise');
  assert.equal(guard.finalize('Vou consultar agora.')?.action, 'finalize');
  assert.match(guard.terminal, /The task is incomplete/);
});
test('successful web receipt allows answer; failed/wrapped receipt cannot count', () => {
  const guard = createCompletionAssurance();
  guard.begin('Search the web for current news');
  for (const [name,result] of [['web_search',{isError:true}],['web_fetch',{details:{status:'blocked'}}],['tool_call',{content:[{text:'searched'}]}]]) {
    guard.observe(name,{result});
  }
  assert.equal(guard.finalize('Here are the headlines.')?.action, 'revise');
  guard.observe('web_search',{result:{details:{results:[{url:'https://example.org/news'}]}}});
  assert.equal(guard.finalize('Results: https://example.org/news'), undefined);
  assert.equal(guard.terminal, undefined);
});
test('candid limitations do not loop and state is run-local', () => {
  const a=createCompletionAssurance(),b=createCompletionAssurance();
  a.begin('Notícias de hoje');b.begin('Notícias de hoje');
  a.observe('web_search',{result:{details:{results:[{url:'https://example.org/news'}]}}});
  assert.equal(a.finalize('Results: https://example.org/news'),undefined);
  assert.equal(b.finalize('Results')?.action,'revise');
  assert.equal(b.finalize('Não consegui pesquisar: serviço indisponível.'),undefined);
});
test('greetings, translations, explanations and explicit offline requests are conversational', () => {
  for (const text of ['oi','Qual o seu nome?','Traduza: vou pesquisar notícias hoje','Explique como pesquisar na internet','Não consulte a internet; explique STF','Search algorithms explained']) {
    assert.equal(researchRequested(text),false,text);
    const guard=createCompletionAssurance();guard.begin(text);
    assert.equal(guard.finalize('Uma resposta normal.'),undefined);
  }
  assert.equal(promisesExecution('> Vou pesquisar agora.\nEsse é um exemplo.'),false);
  assert.equal(promisesExecution('```\nI will run the code.\n```'),false);
});
test('promise detection supports Portuguese and English without counting future discussion', () => {
  for (const text of ['Vou procurar as notícias de hoje.','Sim! Vou consultar agora.','I will search for sources.']) assert.equal(promisesExecution(text),true,text);
  for (const text of ['Você pode pesquisar online.','Posso pesquisar se você quiser.','I will be happy to help.']) assert.equal(promisesExecution(text),false,text);
});
test('actual guard wires bounded recovery and truthful delivery', () => {
  const guard=createToolLoopGuard();
  const context={agentId:'pixel',runId:'research-fixture',sessionId:'research-session'};
  guard.observeRun(context,'pixel',{prompt:'notícias de hoje'});
  const event={lastAssistantMessage:'Vou pesquisar agora.'};
  assert.equal(guard.beforeAgentFinalize(event,context)?.action,'revise');
  assert.equal(guard.beforeAgentFinalize(event,context)?.action,'revise');
  assert.equal(guard.beforeAgentFinalize(event,context)?.action,'finalize');
  assert.equal(guard.deliveryVerificationForRun(context.runId).status,'failed');
  assert.match(guard.deliveryVerificationForRun(context.runId).text,/The task is incomplete/);
  assert.equal(guard.beforeAgentFinalize(event,{...context,agentId:'other'}),undefined);
});

test('installation promises trigger bounded recovery rather than a successful empty turn', () => {
  for (const text of ['OK, vou começar a instalar o pacote agora mesmo.',
    'Sim, vou instalar a extensão.', 'Vou configurar o serviço.',
    'Okay, I will start to install the package.', "I'll download the source."]) {
    const guard = createCompletionAssurance();
    guard.begin('/extensions https://github.com/example/package pode começar a instalar.');
    assert.equal(guard.finalize(text)?.action, 'revise', text);
    assert.equal(guard.finalize(text)?.action, 'revise', text);
    assert.equal(guard.finalize(text)?.action, 'finalize', text);
    assert.equal(guard.terminalStatus, 'failed');
    assert.match(guard.terminal, /The task is incomplete/);
  }
});

test('installation examples, permission questions and failures never authorize execution', () => {
  for (const [request, reply] of [
    ['Traduza: I will install the package.', 'Vou instalar o pacote.'],
    ['Explique a instalação.', 'OK, vou começar a instalar.'],
    ['Prepare a instalação.', 'Vou instalar. Posso confirmar?'],
    ['Instale a extensão.', 'Não consegui instalar: runtime indisponível.'],
    ['Mostre um exemplo.', '> OK, vou começar a instalar.'],
  ]) {
    const guard = createCompletionAssurance();
    guard.begin(request);
    assert.equal(guard.finalize(reply), undefined, reply);
  }
});
test('literal promise requests and approval questions must never initiate execution', () => {
  const guard=createCompletionAssurance();guard.begin('Repita exatamente: Vou pesquisar agora.');
  assert.equal(guard.finalize('Vou pesquisar agora.'),undefined);
  const approval=createCompletionAssurance();approval.begin('Prepare uma publicação.');
  assert.equal(approval.finalize('Vou enviar a publicação. Posso confirmar?'),undefined);
});
test('a promise after partial progress still needs a delivered result', () => {
  const guard=createCompletionAssurance();guard.begin('Pesquise na internet sobre o STF');
  guard.observe('web_search',{result:{content:[{text:'Sources'}]}});
  assert.equal(guard.finalize('Vou consultar as fontes agora.')?.action,'revise');
});
test('clock context is explicit, portable and preserves requested dates', () => {
  const value=executionContext();
  assert.match(value,/Today's date on the host is \w+, \d{4}-\d{2}-\d{2} \(time zone [^)]+\)/);
  assert.match(value,/owner's explicit date and timezone/);
  assert.match(value,/prefer write and verify the bytes with read/);
  assert.match(value,/portable printf/);
  assert.match(value,/Do not claim a match when readback differs/);
});
test('system-prompt execution context carries the date but no clock and is byte-stable within a day', async () => {
  const first=executionContext();
  await new Promise(resolve=>setTimeout(resolve,5));
  assert.equal(executionContext(),first);
  assert.doesNotMatch(first,/\d{2}:\d{2}/);
  // Portal owner messages carry no envelope timestamp, so the date must be here.
  const {hostDateContext}=await import('../plugin/completion-assurance.mjs');
  const zone=Intl.DateTimeFormat().resolvedOptions().timeZone;
  const noon=new Date('2026-09-25T12:00:00Z');
  const sameDay=[new Date(noon.getTime()-60*1000), new Date(noon.getTime()+60*1000)];
  for (const moment of sameDay) assert.equal(hostDateContext(moment), hostDateContext(noon), zone);
  assert.notEqual(hostDateContext(noon), hostDateContext(new Date('2026-09-27T12:00:00Z')));
  assert.match(executionContext(noon),/2026-09-2[456]/);
});
test('sources must come from structured tool evidence, not invented prose links', () => {
  const guard=createCompletionAssurance();guard.begin('Notícias de hoje');
  guard.observe('web_search',{result:{content:[{type:'text',text:JSON.stringify({results:[
    {url:'https://example.org/news'},{url:'javascript:alert(1)'},{url:'http://localhost/secret'},
    {url:'https://user:[email protected]/'},
  ]})}]}});
  for (let i=0;i<2;i++) assert.equal(guard.finalize('Resumo sem fontes.')?.action,'revise');
  assert.equal(guard.finalize('Resumo sem fontes.')?.action,'finalize');
  assert.doesNotMatch(guard.terminal,/https?:/);
  assert.equal(guard.terminalStatus,'failed');
  assert.doesNotMatch(guard.terminal,/javascript|localhost|password/);
  assert.equal(guard.finalize('Resumo: [fonte](https://example.org/news)'),undefined);
  assert.equal(guard.terminal,undefined);
});
test('empty search is an attempt, not evidence for news from memory', () => {
  const guard=createCompletionAssurance();guard.begin('Notícias de hoje');
  guard.observe('web_search',{result:{details:{count:0,results:[]}}});
  assert.equal(guard.finalize('Estas são as notícias de hoje.')?.action,'revise');
  assert.match(guard.terminal,/The task is incomplete/);
  assert.equal(guard.finalize('Não consegui encontrar fontes para essa data.'),undefined);
});
test('short continuation keeps research requirements from the preceding owner request', () => {
  const guard=createCompletionAssurance();
  guard.begin('ok consulte.',{prompt:'[Chat messages since your last reply - for context]\nUser: Pesquise notícias de hoje sobre o STF.\nAssistant: Vou procurar.\n\n[Current message - respond to this]\nUser: ok consulte.'});
  guard.observe('web_search',{result:{details:{count:0,results:[]}}});
  assert.equal(guard.finalize('Estas são as notícias.')?.action,'revise');
  const other=createCompletionAssurance();
  other.begin('continue',{messages:[{role:'user',content:'Notícias de hoje'},{role:'user',content:'Explique álgebra'},{role:'user',content:'continue'}]});
  assert.equal(other.finalize('Explicação de álgebra.'),undefined);
});

const pageReceipt = (url, status = 200) => ({result:{details:{url, finalUrl:url, status, text:'Returned page evidence.'}}});
function sourceReadGuard() {
  const guard = createCompletionAssurance();
  guard.begin('Search the web and open sources before citing findings.');
  return guard;
}

test('explicit source reads distinguish search leads from successfully opened pages', () => {
  const guard = sourceReadGuard(), url = 'https://example.org/event';
  guard.observe('web_search', {result:{details:{results:[{url}]}}});
  const answer = `The event is confirmed. [Source](${url})`;
  const correction = guard.finalize(answer);
  assert.equal(correction?.action, 'revise');
  assert.equal(correction.retry.maxAttempts, 1);
  assert.equal(guard.terminalStatus, 'failed');
  assert.doesNotMatch(guard.terminal, /event is confirmed/);
  guard.observe('web_fetch', pageReceipt(url));
  assert.equal(guard.finalize(answer), undefined);
  assert.equal(guard.terminal, undefined);
});

test('403, failed, empty and wrapped receipts cannot establish source reads', () => {
  for (const [tool, receipt] of [
    ['web_fetch', pageReceipt('https://example.org/page', 403)],
    ['web_fetch', {...pageReceipt('https://example.org/page'), error:'failed'}],
    ['web_fetch', {result:{...pageReceipt('https://example.org/page').result,isError:true}}],
    ['web_fetch', {result:{details:{url:'https://example.org/page',status:200,text:''}}}],
    ['tool_call', pageReceipt('https://example.org/page')],
  ]) {
    const guard = sourceReadGuard(); guard.observe(tool, receipt);
    assert.equal(guard.finalize('Verified: https://example.org/page')?.action, 'revise');
    assert.equal(guard.finalize('Verified: https://example.org/page')?.action, 'finalize');
    assert.equal(guard.terminalStatus, 'failed');
  }
});

test('honest local limitations do not repeat denied fetches', () => {
  for (const answer of [
    'I could not read the sources; the task remains incomplete.',
    'Unverified search lead: https://example.org/page',
    'https://example.org/page — not opened because the fetch returned HTTP 403.',
    '[Source not verified](https://example.org/page).',
  ]) {
    const guard = sourceReadGuard();
    guard.observe('web_search',{result:{details:{results:[{url:'https://example.org/page'}]}}});
    guard.observe('web_fetch',pageReceipt('https://example.org/page',403));
    assert.equal(guard.finalize(answer), undefined, answer);
  }
});

test('one valid source or unrelated limitation cannot cover an unread citation', () => {
  const guard = sourceReadGuard();
  guard.observe('web_fetch',pageReceipt('https://example.org/read'));
  for (const answer of [
    'Fact: https://example.org/read. Another fact: https://example.org/unread. Retail availability is unavailable.',
    'https://example.org/read — unavailable stock. Another fact: https://example.org/unread.',
  ]) assert.ok(guard.finalize(answer), answer);
  assert.equal(guard.finalize('Fact: https://example.org/read. Unverified lead: https://example.org/unread'), undefined);
  assert.equal(guard.terminal, undefined);
});

test('redirects and page anchors count; neighboring paths and guessed replacements do not', () => {
  const guard = sourceReadGuard();
  const receipt = pageReceipt('https://example.org/old');
  receipt.result.details.finalUrl = 'https://example.org/page_(topic)';
  guard.observe('web_fetch',receipt);
  assert.equal(guard.finalize('[Read](https://example.org/page_(topic)#section)'), undefined);
  assert.equal(guard.finalize('Original: https://example.org/old'), undefined);
  assert.equal(guard.finalize('Source: https://example.org/page_(topic)/other')?.action, 'revise');
});

test('targeted extraction requires returned evidence, not an unmatched query or recovered missing URL', () => {
  for (const [details, accepted] of [
    [{matched:true},true], [{matched:false,mode:'overview'},true], [{matched:false},false],
  ]) {
    const guard = sourceReadGuard();
    guard.observe('pixel_ods_web_extract',{result:{details:{boundary:'public-web-read-only',source_url:'https://example.org/read',...details},content:[{type:'text',text:'Evidence'}]}});
    // Ordinary citation presence must also recognize the exact extraction URL.
    const result = guard.finalize('Read: https://example.org/read');
    assert.equal(result?.action, accepted ? undefined : 'revise');
  }
});

test('source-read state is current-turn only and JSON citations remain subject to the check', () => {
  const first = sourceReadGuard(), second = sourceReadGuard();
  first.observe('web_fetch',pageReceipt('https://example.org/read'));
  const answer = '```json\n{"source":"https://example.org/read","value":42}\n```';
  assert.equal(first.finalize(answer),undefined);
  assert.equal(second.finalize(answer)?.action,'revise');
});

test('ordinary search, explicitly unread lists and translation requests retain their prior behavior', () => {
  for (const request of ['Search the web for sources.', 'Search the web; do not open sources.', 'Translate: open sources.']) {
    const guard = createCompletionAssurance(); guard.begin(request);
    guard.observe('web_search',{result:{details:{results:[{url:'https://example.org/lead'}]}}});
    assert.equal(guard.finalize('https://example.org/lead'),undefined,request);
  }
});

for (const name of ['web_fetch','pixel_ods_web_extract']) for (const deferred of [false,true]) {
  test(`actual guard preserves failed delivery until a successful read: ${name}, deferred=${deferred}`, () => {
    const guard = createToolLoopGuard();
    const context = {agentId:'pixel',runId:'source-read-run',sessionId:'source-read-session'};
    guard.observeRun(context,'pixel',{prompt:'Search the web and open sources before citing findings.'});
    const answer = {lastAssistantMessage:'Confirmed finding: https://example.org/page'};
    assert.equal(guard.beforeAgentFinalize(answer,context)?.action,'revise');
    assert.equal(guard.deliveryVerificationForRun(context.runId).status,'failed');
    const params = {url:'https://example.org/page'};
    const sourceName = name === 'web_fetch' ? 'core' : 'pixel-ods';
    const id = `openclaw:${sourceName}:${name}`;
    const toolName = deferred ? 'tool_call' : name;
    const args = deferred ? {id,args:params} : params;
    const call = {toolName,params:args,toolCallId:'read-call'};
    const ctx = {...context,toolName,toolCallId:'read-call'};
    assert.notEqual(guard.beforeToolCall(call,ctx)?.block,true);
    const result = name === 'web_fetch' ? pageReceipt(params.url).result : {
      details:{boundary:'public-web-read-only',source_url:params.url,matched:true},content:[{type:'text',text:'Page evidence'}],
    };
    const envelope = {tool:{id,source:'openclaw',sourceName,name},result};
    const observed = deferred ? {content:[{type:'text',text:JSON.stringify(envelope)}],details:envelope} : result;
    guard.afterToolCall({...call,result:observed},ctx);
    assert.equal(guard.beforeAgentFinalize(answer,context),undefined);
    assert.notEqual(guard.deliveryVerificationForRun(context.runId)?.status,'failed');
  });
}

test('short continuation carries the requested source-read boundary without trusting old receipts', () => {
  const guard = createCompletionAssurance();
  guard.begin('continue',{messages:[{role:'user',content:'Search the web and open sources.'},{role:'user',content:'continue'}]});
  assert.equal(guard.finalize('Verified https://example.org/source')?.action,'revise');
});

test('successful browser snapshot retains existing assurance; discovery, navigation and failures do not bypass', () => {
  const result = {details:{ok:true,url:'https://example.org/page'},content:[{type:'text',text:'Visible page snapshot'}]};
  for (const [tool, event, fallback] of [
    ['browser',{params:{action:'snapshot'},result},true],
    ['browser',{params:{action:'navigate'},result},false],
    ['tool_search',{params:{action:'snapshot'},result},false],
    ['browser',{params:{action:'snapshot'},result:{...result,isError:true}},false],
    ['browser',{params:{action:'snapshot'},result:{...result,details:{...result.details,ok:false}}},false],
    ['browser',{params:{action:'snapshot'},result:{...result,details:{...result.details,status:403}}},false],
    ['browser',{params:{action:'snapshot'},result:{details:result.details,content:[]}},false],
  ]) {
    const guard = sourceReadGuard(); guard.observe(tool,event);
    assert.equal(guard.finalize('Source: https://example.org/page')?.action, fallback ? undefined : 'revise');
  }
  const guard = sourceReadGuard();
  guard.observe('browser',{params:{action:'snapshot'},result});
  assert.equal(guard.finalize('A research answer without citations.')?.action,'revise','ordinary attribution check remains enabled');
  assert.equal(guard.finalize('Source: https://example.org/page. Other fact: https://example.org/unread')?.retry?.idempotencyKey,
    'ods-opened-source-attribution','snapshot of A cannot excuse an unread B');
});

test('actual source-reading request wording enables the boundary', () => {
  const guard = createCompletionAssurance();
  guard.begin('Search the live web for public events. Actually search and open sources. Give a direct official source URL. Explain any unavailable result honestly.');
  guard.observe('web_search',{result:{details:{results:[{url:'https://example.org/event'}]}}});
  assert.equal(guard.finalize('Verified: https://example.org/event')?.retry?.idempotencyKey,'ods-opened-source-attribution');
});

test('omitted citations cannot turn search-only leads into successful requested reads', () => {
  const guard = sourceReadGuard();
  guard.observe('web_search',{result:{details:{results:[{url:'https://example.org/lead'}]}}});
  for (let i = 0; i < 2; i++) assert.equal(guard.finalize('Here is a finding without a source link.')?.action,'revise');
  assert.equal(guard.finalize('Here is a finding without a source link.')?.action,'finalize');
  assert.equal(guard.terminalStatus,'failed');
  assert.doesNotMatch(guard.terminal,/finding|example.org/);
  assert.match(guard.terminal,/incomplete/);
  assert.equal(guard.finalize('Unverified lead, not opened: https://example.org/lead'),undefined);
  assert.equal(guard.terminal,undefined);
});

test('a failed read can be disclosed with its URL without first running search', () => {
  const guard = sourceReadGuard();
  guard.observe('web_fetch',{result:{...pageReceipt('https://example.org/page',403).result,isError:true}});
  assert.equal(guard.finalize('Not opened: https://example.org/page (HTTP 403). Research remains incomplete.'),undefined);
});

test('citation fallback after an actual read cannot append other unread search leads', () => {
  const guard = sourceReadGuard();
  guard.observe('web_search',{result:{details:{results:[{url:'https://example.org/lead'}]}}});
  guard.observe('web_fetch',pageReceipt('https://example.org/read'));
  for (let i=0;i<3;i++) guard.finalize('Finding without a citation.');
  assert.doesNotMatch(guard.terminal,/https?:/);
  assert.match(guard.terminal,/Attribution remains incomplete/);
  assert.doesNotMatch(guard.terminal,/https:\/\/example.org\/lead/);
});

// A live fleet reply fetched this exact page, then bolded its URL. The closing
// Markdown stars became part of the citation key and caused a false rejection.
test('successful page receipts survive directly emphasized citation URLs', () => {
  const url = 'https://docs.python.org/3/library/pathlib.html';
  for (const wrapper of ['**', '*', '__', '_', '***', '___', '~~']) {
    for (const suffix of ['', '.', ')']) {
      const guard = createCompletionAssurance();
      guard.begin('Search official sources and read them before citing the documentation.');
      guard.observe('web_fetch', {result:{details:{status:200, url, finalUrl:url,
        text:'Pathlib provides classes representing filesystem paths.'}}});
      const answer = `The official documentation is ${wrapper}${url}${wrapper}${suffix} and provides filesystem path classes.`;
      assert.deepEqual(guard.unverifiedCitations(answer), [], answer);
      assert.equal(guard.finalize(answer), undefined, answer);
      assert.equal(guard.terminal, undefined, answer);
    }
  }
});

test('citation formatting cannot grant custody of literal or unread URLs', () => {
  const url = 'https://docs.python.org/3/library/pathlib.html';
  const answers = [
    `${url}*`, `${url}**`, `${url}_`, `${url}__`, `${url}~~`,
    `\\**${url}**`, `\\_${url}_`,
    '`**' + url + '**`', '``**' + url + '**``',
    '```\n**' + url + '**\n```',
    '````\n```\n**' + url + '**\n````',
    '~~~text\n**' + url + '**\n~~~',
    '- ~~~\n  **' + url + '**\n  ~~~',
    '1. ~~~\n   **' + url + '**\n   ~~~',
    '> - ~~~\n>   **' + url + '**\n>   ~~~',
    '- > ~~~\n  > **' + url + '**\n  > ~~~',
    '~~~text\n- ~~~\n**' + url + '**\n~~~',
    '~~~text\n1. ~~~\n**' + url + '**\n~~~',
    '~~~text\n> ~~~\n**' + url + '**\n~~~',
    '> ```\n> **' + url + '**\n> ```',
    '    **' + url + '**',
    '-     **' + url + '**', '1.     **' + url + '**',
    `**${url}**/unread`, `**${url}?variant=unread**`,
    `**https://example.com/unread**`,
  ];
  for (const answer of answers) {
    const guard = createCompletionAssurance();
    guard.begin('Read the official sources before citing them.');
    guard.observe('web_fetch', {result:{details:{status:200, url, text:'Actual page evidence.'}}});
    assert.ok(guard.unverifiedCitations(answer).length, answer);
    assert.equal(guard.finalize(answer)?.action, 'revise', answer);
  }
});

test('formatting preserves literal URL punctuation and exact query identity', () => {
  for (const url of ['https://example.org/a*b', 'https://example.org/a_b',
    'https://example.org/a*', 'https://example.org/a_',
    'https://example.org/Foo_(bar)', 'https://example.org/page?x=1&y=2']) {
    const guard = createCompletionAssurance();
    guard.begin('Read the official sources before citing them.');
    guard.observe('web_fetch', {result:{details:{status:200, url, text:'Actual page evidence.'}}});
    for (const answer of [`Source: ${url}`, `[Source](${url})`, '`' + url + '`']) {
      assert.deepEqual(guard.unverifiedCitations(answer), [], answer);
    }
  }
});

test('closed code spans and fences do not hide a later emphasized citation', () => {
  const url = 'https://example.org/read';
  const guard = createCompletionAssurance();
  guard.begin('Read sources before citing them.');
  guard.observe('web_fetch', {result:{details:{status:200, url, text:'Actual page evidence.'}}});
  for (const prefix of ['`code` ', '``a ` b`` ', '```\ncode\n```\n', '~~~\ncode\n~~~\n',
    '- ~~~\n  code\n  ~~~\n', '1. ~~~\n   code\n   ~~~\n', '> ~~~\n> code\n> ~~~\n']) {
    assert.deepEqual(guard.unverifiedCitations(prefix + `**${url}**`), [], prefix);
  }
});


for (const condition of [
  'If a needed capability fails or is unavailable, I will state the concrete limitation and that the task is incomplete.',
  'If I cannot open a source, I will report the limitation.',
  'If the page is unverified, I will say so.',
  'I will explain what happens if the service is unavailable.',
  'Se a ferramenta estiver indisponivel, vou informar a limitacao.',
]) test(`hypothetical failure does not clear exhausted completion recovery: ${condition}`, () => {
  const guard=createCompletionAssurance();guard.begin('Use web search, read the official source pages, and create a tested Python project with a ZIP download.');
  assert.equal(guard.finalize('I will create the project.')?.action,'revise');
  assert.equal(guard.finalize('I will search the official documentation.')?.action,'revise');
  assert.equal(guard.finalize('I will search the documentation now. '+condition)?.action,'finalize');
  assert.match(guard.terminal,/task is incomplete/);
  assert.equal(guard.terminalStatus,'failed');
});

for (const answer of [
  'I cannot access the requested service. The task is incomplete.',
  'The service is unavailable. If it returns, I will try later.',
  'If a source fails, I will report it. The web service is unavailable now.',
  'I could not read the source. Its claims remain unverified.',
  'Nao consegui acessar o servico. Se voltar, vou tentar depois.',
  'Which site should I search?',
]) test(`actual limitation or clarification still ends without retry: ${answer}`, () => {
  const guard=createCompletionAssurance();guard.begin('Use web search and read the source pages.');
  assert.equal(guard.finalize(answer),undefined);
  assert.equal(guard.terminal,undefined);
});