// Changed UUID consumers only. Existing A/B and C37 acceptance is preserved. const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict'),crypto=require('node:crypto'); const {chromium}=require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright'); const ROOT=path.resolve(__dirname,'..'),DIR=path.join(ROOT,'storage/app/private/investmoz-v2/portal-audit'); const plan=JSON.parse(fs.readFileSync(path.join(DIR,'portal-stability-latest.json'))),BASE=plan.consumer_environment.base,TARGET=plan.consumer_environment.target.database+':55441'; const actors=JSON.parse(fs.readFileSync(path.join(DIR,'profiles-v1-actors-private.json'))); actors.geo=JSON.parse(fs.readFileSync(path.join(DIR,'i0-qa-actor-private.json'))); const receipt=path.join(DIR,'portal-stability-consumers-chromium.json'); if(fs.existsSync(receipt))fs.copyFileSync(receipt,receipt.replace('.json','-attempt-'+Date.now()+'.json')); const proof={at:new Date().toISOString(),origin:BASE,target:TARGET,checks:[],operations:[],errors:[],active_writes:0,AB_C37_not_repeated:true}; const resume=process.argv.includes('--resume'); if(resume){const prior=JSON.parse(fs.readFileSync(receipt));assert.equal(prior.target,TARGET);assert.equal(prior.errors.length,0);assert.equal(prior.checks.length,7);assert(prior.new_opportunity_id&&prior.new_partnership_path);fs.copyFileSync(receipt,receipt.replace('.json','-before-consent-retry.json'));Object.assign(proof,prior,{at:new Date().toISOString(),previous_harness_missing_consent:prior.failure});delete proof.failure;delete proof.result;} const remaining=process.argv.includes('--remaining'); if(remaining){const prior=JSON.parse(fs.readFileSync(receipt));assert.equal(prior.target,TARGET);assert.equal(prior.errors.length,0);assert.equal(prior.checks.length,15);fs.copyFileSync(receipt,receipt.replace('.json','-before-geometry-memory-correction.json'));Object.assign(proof,prior,{at:new Date().toISOString(),previous_missing_geometry_exemplar:prior.failure});delete proof.failure;delete proof.result;} const save=()=>fs.writeFileSync(receipt,JSON.stringify(proof,null,2)); const redact=e=>Object.values(actors).reduce((s,a)=>['password','totp_secret','secret'].reduce((v,k)=>a[k]?v.replaceAll(a[k],'[REDACTED]'):v,s),String(e.message||e)).split('\nCall log:')[0].replace(/\b\d{6}\b/g,'[OTP OMITTED]').slice(0,1200); function otp(secret){let bits=0,v=0;const b=[],abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';for(const c of secret.toUpperCase().replace(/=+$/,'')){v=(v<<5)|abc.indexOf(c);bits+=5;if(bits>=8){b.push((v>>>(bits-8))&255);bits-=8;}}const n=Buffer.alloc(8);n.writeBigUInt64BE(BigInt(Math.floor(Date.now()/30000)));const d=crypto.createHmac('sha1',Buffer.from(b)).update(n).digest(),o=d[19]&15;return String((d.readUInt32BE(o)&0x7fffffff)%1000000).padStart(6,'0');} (async()=>{const browser=await chromium.launch({headless:true,executablePath:'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',args:['--host-resolver-rules=MAP portal-investidor.test 127.0.0.1','--no-proxy-server']});let ctx,page,role; async function actor(name){if(ctx)await ctx.close();role=name;ctx=await browser.newContext({ignoreHTTPSErrors:false,viewport:{width:1440,height:1000}}); await ctx.addInitScript(()=>Object.defineProperty(Crypto.prototype,'randomUUID',{value:undefined,configurable:true})); await ctx.route('**/*',r=>new URL(r.request().url()).origin===BASE?r.continue():r.abort());page=await ctx.newPage();page.setDefaultTimeout(35000); page.on('pageerror',e=>{proof.errors.push({role,path:new URL(page.url()).pathname,message:redact(e)});save();}); page.on('request',r=>{if(!['POST','PUT'].includes(r.method())||['/login','/two-factor-challenge'].includes(new URL(r.url()).pathname))return; let data;try{data=r.postDataJSON();}catch{return;}for(const key of ['client_key','creation_key','idempotency_key'])if(data?.[key]){ assert.match(data[key],/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i); proof.operations.push({role,path:new URL(r.url()).pathname,method:r.method(),key_field:key,key_sha256:crypto.createHash('sha256').update(data[key]).digest('hex')});save();}}); await open('/login');const a=actors[name];await page.locator('#email').fill(a.email);await page.locator('#password').fill(a.password);await page.locator('[data-test="login-button"]').click(); await page.waitForURL(u=>u.pathname!=='/login');if(new URL(page.url()).pathname==='/two-factor-challenge'){await page.waitForTimeout(30500-(Date.now()%30000));await page.locator('input[name="code"]').fill(otp(a.totp_secret??a.secret));await page.getByRole('button',{name:'Continue',exact:true}).click();await page.waitForURL(u=>!['/login','/two-factor-challenge'].includes(u.pathname));}} async function open(route){const r=await page.goto(BASE+route,{waitUntil:'networkidle'});assert.equal(r.headers()['x-investmoz-qa-target'],TARGET);return r;} async function observed(component,route,expected=200){const r=await open(route);assert.equal(r.status(),expected);await page.locator('h1').first().waitFor();assert(await page.evaluate(()=>isSecureContext&&typeof crypto.randomUUID==='undefined'&&typeof crypto.getRandomValues==='function')); const row={component,role,route,status:r.status(),uuid_api_absent:true,visible_heading:(await page.locator('h1').first().innerText()).slice(0,150),errors:proof.errors.length};proof.checks.push(row);save();return row;} async function recover(route,label){await open(route);await page.reload({waitUntil:'networkidle'});assert(await page.locator('h1').first().isVisible());proof.checks.push({criterion:label,role,route,refresh_recovery:true});save();} try{ if(remaining){ await actor('geo'); for(const level of [2,3]){const r=await open('/management/territory-geometry-import?level='+level);proof.checks.push({component:'territory-geometry-import',role,level,status:r.status(),visible_heading:await page.locator('h1').first().innerText()});save();assert.equal(r.status(),200);} await actor('promoter'); await open(proof.new_dossier_path);await page.getByRole('button',{name:'Preparar pedido com dados do dossier',exact:true}).click();await page.waitForURL(/\/balcao-virtual\/pedidos\/[0-9a-f-]+$/); const requestPath=new URL(page.url()).pathname;proof.new_request_path=requestPath;proof.checks.push({component:'desk-request',role,route:requestPath,visible:true,uuid_api_absent:true});save(); for(let n=1;n<=2;n++){const text='Synthetic stability UUID private request message '+n;await page.getByLabel('Mensagem privada',{exact:true}).fill(text);await page.getByRole('button',{name:'Enviar esta mensagem no pedido',exact:true}).click();await page.getByText(text,{exact:true}).waitFor();} await recover(requestPath,'two distinct desk messages recovered'); await page.getByLabel('Data real declarada').fill('2026-10-11T10:00');await page.getByLabel('Resumo',{exact:true}).fill('Synthetic QA UUID test: no real external communication');await page.getByLabel('Evidência / referência',{exact:true}).fill('Synthetic browser stability test only; no external event asserted');await page.getByRole('button',{name:'Guardar registo manual — sem envio',exact:true}).click();await page.getByText('Synthetic QA UUID test: no real external communication',{exact:true}).waitFor(); proof.checks.push({component:'desk-internal-operations',role,route:requestPath,communication_saved:true,external_send:false});save(); await open('/parcerias/salas/1');for(let n=1;n<=2;n++){const text='Synthetic stability UUID room message '+n;await page.getByLabel('Mensagem privada',{exact:true}).fill(text);await page.getByRole('button',{name:'Enviar mensagem',exact:true}).click();await page.getByText(text,{exact:true}).waitFor();}await recover('/parcerias/salas/1','two distinct partnership messages recovered'); assert.equal(proof.errors.length,0);proof.result='passed_incremental_actions';save();console.log(JSON.stringify({result:proof.result,checks:proof.checks.length,operations:proof.operations.length,active_writes:0}));return; } await actor('promoter'); if(!resume){ await observed('opportunity-draft','/minhas-oportunidades/create'); await page.getByLabel('Motivo da alteração').fill('Synthetic integrated stability QA: draft UUID and recovery'); await page.getByRole('button',{name:'Guardar rascunho',exact:true}).click();await page.waitForURL(/\/minhas-oportunidades\/\d+\/edit$/); const id=Number(new URL(page.url()).pathname.split('/')[2]);proof.new_opportunity_id=id;await recover(`/minhas-oportunidades/${id}/edit`,'incomplete opportunity remains recoverable'); await observed('opportunity-resources',`/minhas-oportunidades/${id}/resources`); await observed('partnership-editor','/parcerias/criar');await page.getByLabel('Título',{exact:true}).fill('Synthetic UUID stability partnership');await page.getByRole('button',{name:'Guardar rascunho',exact:true}).click();await page.waitForURL(/\/parcerias\/\d+\/editar$/);proof.new_partnership_path=new URL(page.url()).pathname;await recover(proof.new_partnership_path,'partnership draft recovered'); await observed('partnership-room','/parcerias/salas/1'); await observed('investor-path-index','/investimentos');} else await open('/investimentos'); await page.getByLabel('Título',{exact:true}).fill('Synthetic UUID stability dossier'); const start=proof.operations.length; await page.getByRole('button',{name:'Criar e guardar dossier',exact:true}).click();await page.getByRole('alert').first().waitFor(); await page.getByLabel('Autorizo reutilizar o meu perfil neste dossier privado.').check();await page.getByRole('button',{name:'Criar e guardar dossier',exact:true}).click();await page.waitForURL(/\/investimentos\/[a-f0-9-]+$/); assert.equal(proof.operations[start].key_sha256,proof.operations[start+1].key_sha256);proof.checks.push({criterion:'dossier validation error and corrected retry preserve same key',passed:true}); const dossier=new URL(page.url()).pathname;proof.new_dossier_path=dossier; await observed('investor-path-show',dossier);await recover(dossier,'technical UUID dossier recovered'); await observed('desk-panel','/balcao-virtual/painel');await observed('desk-case',dossier.replace('/investimentos/','/balcao-virtual/dossiers/')); await actor('public');await observed('profile-request','/perfil/promotor'); await actor('super_first');await observed('profile-installation','/management/profile-install'); await actor('geo');await observed('territory-geometry-import','/management/territory-geometry-import'); assert.equal(proof.errors.length,0);proof.result='passed_changed_routes';save();console.log(JSON.stringify({result:proof.result,checks:proof.checks.length,operations:proof.operations.length,remaining:'message/internal communications/resource actions/geometry application/cold040000/public autosave',active_writes:0})); }catch(e){proof.result='failed';proof.failure=redact(e);save();console.log(JSON.stringify({result:'failed',failure:proof.failure,completed_checks:proof.checks.length,active_writes:0}));process.exitCode=1;}finally{if(ctx)await ctx.close();await browser.close();}})();