// Explicit live Development protocol verification. Requires guarded synthetic account/snapshot files. // No AI calls, manuscript imports, Windows automation or real Word COM operations. const {chromium}=require('playwright'); const fs=require('node:fs'),crypto=require('node:crypto'),assert=require('node:assert/strict'); const base='https://dev.plotdirector.com';let step='validate fixture files'; (async()=>{ const [identityPath,scopePath]=process.argv.slice(2); assert.ok(identityPath?.startsWith('/tmp/pd-dev-browser-')&&scopePath?.startsWith('/tmp/pd-context-')); assert.equal(fs.statSync(identityPath).mode&0o077,0); const identity=JSON.parse(fs.readFileSync(identityPath)),scope=JSON.parse(fs.readFileSync(scopePath)); assert.equal(identity.Database,'PlotDirector_Development');assert.equal(identity.UserID,scope.User);assert.match(identity.Email,/^pwa-browser-.*@example\.invalid$/);assert.equal(scope.SceneStarts.length,2); const browser=await chromium.launch();let keepalive; try{ const context=await browser.newContext();await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')})); const page=await context.newPage();let navigationForm;page.on('request',request=>{if(request.url().endsWith('/Writing/Context/Navigate')&&request.method()==='POST')navigationForm=request.postData();});step='normal login';await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(identity.Email);await page.locator('[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]); step='browser-approved persistent pairing';const verifier=crypto.randomBytes(32).toString('base64url'),connectionId=crypto.randomUUID(); let response=await page.request.post(base+'/api/native-companion/pair',{data:{challenge:crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase(),persistent:true,connectionId,deviceName:'Atlas Context protocol verification'}});assert.equal(response.status(),200);const {code}=await response.json(); await page.goto(base+'/native-companion/authorize?code='+code);const csrf=await page.locator('[name=__RequestVerificationToken]').inputValue();response=await page.request.post(base+'/native-companion/authorize',{form:{code,retainImport:'true',__RequestVerificationToken:csrf}});assert.equal(response.status(),200); response=await page.request.post(base+'/api/native-companion/token',{data:{code,verifier}});assert.equal(response.status(),200);const tokens=await response.json();const headers={Authorization:'Bearer '+tokens.accessToken}; let sequence=0,cursor=scope.SceneStarts[0],revision=1;const commands=[]; const presencePath=(instance=scope.Instance,session=scope.Session)=>base+`/api/native-companion/instances/${instance}/documents/${session}/presence`; async function heartbeat(){const r=await page.request.post(presencePath(),{headers,data:{bookId:scope.Book,manuscriptId:scope.Manuscript,revision,sequence:++sequence,documentTitle:'Synthetic context manuscript.docx',wordRunning:true,wordAvailable:true,wordSaved:true,canCapture:true,canParagraphSync:true,active:true,cursorStart:cursor}});assert.equal(r.status(),200,'Native registration');const data=await r.json();if(data.navigation)commands.push(data.navigation);return data;} step='live paragraph cursor resolution';let presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[0]);assert.equal(presence.chapterId,scope.Chapters[0]); keepalive=setInterval(()=>void heartbeat().catch(()=>{}),10000); step='direct Context and compiled fragments';await page.goto(base+`/native-companion/workspace?bookId=${scope.Book}&instanceId=${scope.Instance}&sessionId=${scope.Session}&view=context`);await page.waitForURL(u=>u.pathname==='/Writing/Context');await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`);assert.equal(await page.locator('iframe').count(),0);assert.equal(await page.locator('.pd-ribbon,.pd-titlebar').count(),0);await page.evaluate(()=>window.originalContextShell=document.querySelector('[data-writing-context]')); await page.click('[data-writing-context-tab=people]'); step='passive cursor following across chapters';for(const next of [scope.SceneStarts[1],scope.SceneStarts[0]]){cursor=next;await heartbeat();await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${next===scope.SceneStarts[0]?scope.Scenes[0]:scope.Scenes[1]}"]`);}for(let i=0;i<5;i++)await heartbeat();assert.equal(commands.length,0,'Passive presence and scene changes cannot queue Word selection');await page.locator('[data-writing-context-scene-select]').press('End'); await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested')); step='existing native navigation command';await heartbeat();assert.equal(commands.length,1);assert.equal(commands[0].kind,'navigate');assert.equal(commands[0].sessionId.toLowerCase(),scope.Session.toLowerCase());assert.equal(commands[0].revision,1);assert.equal(commands[0].chapter.start,scope.SceneStarts[1]); assert.equal(commands[0].id,new URLSearchParams(navigationForm).get('navigationId'));const acceptedNavigationForm=navigationForm; cursor=commands[0].chapter.start;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);assert.equal(presence.chapterId,scope.Chapters[1]);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Following Word');assert.equal(commands.length,1,'Following a cursor must not command Word back');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible()); step='duplicate explicit request after acknowledgement';response=await page.request.post(base+'/Writing/Context/Navigate',{form:Object.fromEntries(new URLSearchParams(acceptedNavigationForm))});assert.equal(response.status(),200);assert.ok(!(await heartbeat()).navigation);assert.equal(commands.length,1,'Retried explicit navigation is not reexecuted'); step='stale Word revision refusal';revision=2;await heartbeat();const body={bookId:String(scope.Book),sceneId:String(scope.Scenes[0]),instanceId:scope.Instance,sessionId:scope.Session,__RequestVerificationToken:await page.locator('[data-writing-context] [name=__RequestVerificationToken]').inputValue()};response=await page.request.post(base+'/Writing/Context/Navigate',{form:body});assert.equal(response.status(),409);assert.match((await response.json()).message,/mapping|synchronise/i);assert.ok(!(await heartbeat()).navigation); revision=1;await page.request.delete(presencePath(),{headers});sequence=0;await heartbeat(); step='actual saved metrics and empty plot data';await page.click('[data-writing-context-tab=metrics]');await page.waitForSelector('[data-writing-component=metrics][data-loaded=true]');assert.ok(await page.locator('[data-context-metric-select] option').count()>0);await page.click('[data-writing-context-tab=plots]');await page.waitForSelector('[data-writing-component=plots][data-loaded=true]');assert.ok(await page.getByText('No saved plot-line developments are available for this book.').isVisible()); step='disconnect and saved navigation';clearInterval(keepalive);keepalive=null;await page.request.delete(presencePath(),{headers});await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'),null,{timeout:25000});await page.click('[data-writing-context-tab=people]');await page.locator('[data-writing-context-scene-select]').press('Home');await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[0]}"]`); step='reconnect actual cursor wins';cursor=scope.SceneStarts[1];sequence=0;presence=await heartbeat();assert.equal(presence.sceneId,scope.Scenes[1]);await page.waitForSelector(`[data-writing-context-fragment][data-scene-id="${scope.Scenes[1]}"]`);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.ok(await page.evaluate(()=>originalContextShell===document.querySelector('[data-writing-context]')));assert.equal(commands.length,1,'Reconnect cannot manufacture navigation commands'); step='direct existing synchronisation action and exact document selection';const syncToken=await page.locator('[data-word-sync-form] [name=__RequestVerificationToken]').inputValue(); response=await page.request.post(base+'/manuscript/paragraphs/snapshot',{headers:{'X-Requested-With':'XMLHttpRequest'},form:{bookId:String(scope.Book),instanceId:scope.Instance,sessionId:crypto.randomUUID(),__RequestVerificationToken:syncToken}});assert.equal(response.status(),409);assert.match((await response.json()).message,/selected Word document/i); await page.click('#native-companion-status');await page.locator('[data-word-sync-button]').waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-word-sync-button]').disabled); const submitted=page.waitForResponse(r=>r.url().endsWith('/manuscript/paragraphs/snapshot')&&r.request().method()==='POST');await page.click('[data-word-sync-button]');response=await submitted;assert.equal(response.status(),200);const requestedSnapshot=await response.json();assert.match(requestedSnapshot.requestId,/^[0-9a-f-]{36}$/i); const snapshotCommand=(await heartbeat()).navigation;assert.equal(snapshotCommand.kind,'paragraph-snapshot');assert.equal(snapshotCommand.id,requestedSnapshot.requestId);assert.equal(snapshotCommand.sessionId,scope.Session);assert.equal(commands.filter(c=>c.kind==='navigate').length,1);assert.ok(!(await page.locator('[data-word-sync-feedback]').textContent()).includes('accepted.'),'request alone is not acceptance'); await page.request.delete(base+'/api/native-companion/manuscript-capture/'+snapshotCommand.id,{headers});await page.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await page.waitForFunction(()=>document.querySelector('[data-word-sync-feedback]').textContent.includes('ended without an accepted snapshot'));await page.click('[data-close-word-details]'); step='anonymous and antiforgery refusal';const bare=await browser.newContext();const unauthorised=await bare.request.get(base+`/Writing/Context/Metrics?projectId=${scope.Project}&bookId=${scope.Book}`,{maxRedirects:0});assert.ok([302,401].includes(unauthorised.status()));await bare.close();response=await page.request.post(base+'/Writing/Context/Navigate',{form:{bookId:String(scope.Book),sceneId:String(scope.Scenes[0])}});assert.equal(response.status(),400); step='sign out test installation';await page.request.post(base+'/api/native-companion/revoke',{data:{installationId:tokens.installationId,credential:tokens.deviceSecret,connectionId,nextCredential:'',rotationId:crypto.randomUUID()}});response=await page.request.get(base+'/api/native-companion/books',{headers});assert.equal(response.status(),401); console.log('PASS live Development: normal browser approval, real native presence and persisted paragraph mapping, direct iframe-free Context, cross-chapter explicit command at exact saved position, cursor acknowledgement without loops, stable People tab/shell, stale revision refusal, read-only metrics/plots, disconnected browsing, reconnect precedence, authentication/antiforgery and revocation. Includes repeated passive cursor observations and duplicate explicit-request refusal after acknowledgement. Protocol client only; actual Word execution remains unverified.'); }finally{if(keepalive)clearInterval(keepalive);await browser.close();} })().catch(error=>{fs.writeFileSync('/tmp/pd-context-development-error.log',String(error.stack),{mode:0o600});console.error('FAIL Development Context verification at '+step+'; private diagnostic saved.');process.exit(1);});