// Scoped Story Elements reads and Context palette controls. 'use strict'; const assert = require('node:assert/strict'); const {open} = require('./dev-acceptance.cjs'); let session, stage = 'login'; (async () => { try { session = await open(); const project = await session.project(); const book = await session.create('Books', '?projectId='+project, {BookTitle:'Intent palette acceptance',BookNumber:1}); const chapter = await session.create('Chapters', '?bookId='+book, {ChapterTitle:'Empty chapter palette',ChapterNumber:1}); const otherBook = await session.create('Books', '?projectId='+project, {BookTitle:'Other scoped book',BookNumber:2}); const otherChapter = await session.create('Chapters', '?bookId='+otherBook, {ChapterTitle:'Other chapter',ChapterNumber:1}); const base = {bookID:book, chapterID:chapter}; async function read(query={}, expected=200) { const url = '/Writing/Context/Intent/Palette?'+new URLSearchParams({...base,...query}); const result = await session.page.evaluate(async url => { const response = await fetch(url, {credentials:'same-origin'}); const json=(response.headers.get('content-type')||'').includes('application/json'); return {status:response.status,redirected:response.redirected,path:new URL(response.url).pathname, data:response.status===200&&json?await response.json():null}; }, url); if(result.status!==expected) console.error(JSON.stringify({stage,expected,status:result.status,redirected:result.redirected,path:result.path})); assert.equal(result.status, expected); return result.data; } stage='chapter-only/no-prose read'; assert.deepEqual((await read()).entries, []); const chapterUrl = '/Writing/Context?' + new URLSearchParams({ projectId:project, bookId:book, chapterId:chapter, pinned:true }); stage='chapter checklist without a scene or manuscript'; await session.goto(chapterUrl); await session.page.locator('[data-context-tab]').first().selectOption('intent'); const checklist = session.page.locator('[data-intent-checklist]'); const items = checklist.locator('[data-checklist-items] > li'); const getChecklist = () => session.page.evaluate(async ({bookID,chapterID}) => (await fetch('/Writing/Context/Intent/Checklist?' + new URLSearchParams({bookID,chapterID}))).json(), base); await checklist.getByText('Paste a checklist', {exact:true}).click(); await checklist.getByLabel('Checklist text').fill('- [ ] Reveal the promise\n- [ ] Establish the setting'); await checklist.getByRole('button',{name:'Preview',exact:true}).click(); const review = checklist.locator('[data-checklist-preview-items]'); await review.getByLabel('Item').first().fill('Keep the promise'); await checklist.getByRole('button',{name:'Add reviewed items'}).click(); await items.nth(1).getByRole('button',{name:'Up',exact:true}).click(); await items.nth(1).getByLabel('Complete',{exact:true}).check(); await items.nth(1).getByLabel('Changed',{exact:true}).check(); await items.nth(1).getByLabel('Notes',{exact:true}).fill('Author note survives a fresh login'); const original = await getChecklist(); await checklist.getByRole('button',{name:'Save checklist'}).click(); await checklist.getByRole('button',{name:'Save checklist'}).waitFor({state:'visible'}); await session.page.waitForFunction(() => document.querySelector('[data-checklist-save]').disabled && !document.querySelector('[data-checklist-items]').inert); const saved = await getChecklist(); assert.deepEqual(saved.items.map(item => [item.text,item.completed,item.changed]), [ ['Establish the setting',false,false], ['Keep the promise',true,true] ]); assert.equal(saved.items[1].notes,'Author note survives a fresh login'); const stale = await checklist.evaluate(async (element, {base,original}) => { const response = await fetch(element.dataset.url, { method:'POST', headers:{ 'Content-Type':'application/json', RequestVerificationToken:element.querySelector('[name=__RequestVerificationToken]').value }, body:JSON.stringify({...base,version:original.version,items:[]}) }); return response.status; }, {base,original}); assert.equal(stale,409,'A stale save cannot delete the new checklist'); await session.page.reload(); await session.page.locator('[data-context-tab]').first().selectOption('intent'); await items.nth(1).getByLabel('Complete',{exact:true}).waitFor(); assert.equal(await items.nth(1).getByLabel('Complete',{exact:true}).isChecked(),true); stage='canonical equal-label fixtures'; const name='Palette shared name'; const person = await session.create('Characters','?projectId='+project,{CharacterName:name},async page=>{ const sex=page.locator('[name=CustomSex]'); if(await sex.isEnabled() && await sex.getAttribute('required')!==null) await sex.fill('Unspecified'); }); const place = await session.create('Locations','?projectId='+project,{LocationName:name}); const literal = await session.create('Locations','?projectId='+project,{LocationName:'Palette literal %'}); stage='wider story identity and literal search'; const wider = await read({widerStory:true, search:'SHARED NAME'}); assert.deepEqual(new Set(wider.entries.map(e=>e.key)), new Set(['character:'+person,'location:'+place])); assert(wider.entries.every(e=>e.possiblyAmbiguous && !e.isCandidate && !e.inScope)); assert.equal(wider.hasMore,false); assert.deepEqual((await read({widerStory:true,search:'%'})).entries.map(e=>e.key),['location:'+literal]); assert.deepEqual((await read()).entries, []); async function scene(location, title) { await session.goto('/Scenes/Create?chapterId='+chapter); const page=session.page; await page.locator('#SceneTitle').fill(title); await page.locator('#PrimaryLocationID').selectOption(String(location)); await page.getByRole('button',{name:'Create scene',exact:true}).click(); await page.waitForURL('**/Scenes/Edit/*'); return Number(new URL(page.url()).pathname.split('/').at(-1)); } stage='recorded chapter/scene associations'; const first=await scene(place,'Palette first scene'), second=await scene(literal,'Palette second scene'); let scoped=await read({sceneID:first}); assert.deepEqual(scoped.entries.map(e=>e.key),['location:'+place]); assert(scoped.entries[0].inScope && scoped.entries[0].possiblyAmbiguous); assert.deepEqual(scoped.entries[0].sources,[{sceneID:first,provenance:'Scene location'}]); assert.deepEqual((await read({sceneID:second})).entries.map(e=>e.key),['location:'+literal]); assert.deepEqual(new Set((await read()).entries.map(e=>e.key)),new Set(['location:'+place,'location:'+literal])); stage='Context palette chapter and scene browsing'; const contextUrl = '/Writing/Context?' + new URLSearchParams({ projectId:project, bookId:book, chapterId:chapter, sceneId:first, pinned:true }); assert.equal((await session.goto(contextUrl)).status(),200); await session.page.locator('[data-context-tab]').first().selectOption('intent'); const panel=session.page.locator('[data-context-intent]'); await panel.locator('[data-entity-key="location:'+literal+'"]').waitFor(); await panel.locator('[data-intent-palette]').getByLabel('Current scene only').check(); const search=panel.getByRole('searchbox',{name:'Search story'}); await panel.getByText('Scene location',{exact:false}).first().waitFor(); await panel.locator('[data-entity-key="location:'+literal+'"]').waitFor({state:'detached'}); await search.fill('SHARED NAME'); await panel.locator('[data-entity-key="character:'+person+'"]').waitFor(); assert.equal(await search.evaluate(input=>input===document.activeElement),true); assert.equal(session.page.url().endsWith(contextUrl),true,'Palette browsing preserves Context position'); stage='held checklist Story Element link and coverage'; await panel.locator('[data-entity-key="character:'+person+'"]').getByRole('button',{name:'Select Palette shared name to link'}).click(); await items.first().getByRole('button',{name:'Link Palette shared name'}).click(); assert.equal(await items.first().getByLabel('Complete',{exact:true}).isChecked(),false); await items.first().getByLabel('Palette shared name covered').check(); assert.equal(await items.first().getByLabel('Complete',{exact:true}).isChecked(),false); await checklist.getByRole('button',{name:'Save checklist'}).click(); await session.page.waitForFunction(() => document.querySelector('[data-checklist-save]').disabled && !document.querySelector('[data-checklist-items]').inert); assert.deepEqual((await getChecklist()).items[0].links,[{key:'character:'+person,name,covered:true}]); await checklist.getByLabel('Scene checklist').check(); await checklist.getByText('No checklist items',{exact:true}).waitFor(); await checklist.getByLabel('Scene checklist').uncheck(); await items.first().getByLabel('Palette shared name covered').waitFor(); await panel.getByText('Story Elements',{exact:true}).click(); assert.equal(await panel.locator('[data-intent-palette]').evaluate(details=>details.open),false); stage='invalid and mismatched scope denial'; stage='chapter/book mismatch denial';await read({chapterID:otherChapter},403); stage='book/chapter mismatch denial';await read({bookID:otherBook},403); stage='scene/chapter mismatch denial';await read({chapterID:otherChapter,bookID:otherBook,sceneID:first},403); stage='invalid scene rejection';await read({sceneID:0},400); stage='oversized search rejection';await read({search:'x'.repeat(201)},400); stage='fresh login persistence and read-only source'; await session.close(); session=await open(); await session.goto(chapterUrl); await session.page.locator('[data-context-tab]').first().selectOption('intent'); await session.page.locator('[data-intent-checklist] [data-checklist-items] > li').first().waitFor(); const reloaded = await getChecklist(); assert.equal(reloaded.items[0].links[0].key,'character:'+person); assert.equal(reloaded.items[1].notes,'Author note survives a fresh login'); scoped=await read({sceneID:first}); assert.equal(scoped.entries[0].key,'location:'+place,'Fresh palette identity'); // Independently reload the normal authorised source form from the server. This // endpoint is the same partial loaded by the existing scene-details editor. assert.equal((await session.goto('/Scenes/SceneDetailsEditor?sceneId='+first)).status(),200); const editor=session.page.locator('form[data-scene-editor-form]'); assert.equal(await editor.locator('[name=PrimaryLocationID]').inputValue(),String(place),'Source location'); assert.equal(await editor.locator('[name=SceneTitle]').inputValue(),'Palette first scene','Source title'); console.log(JSON.stringify({passed:true,milestone:'Context Intent and Story Elements',checks:[ 'chapter without prose or scenes, paste preview, order, flags and notes', 'stale checklist write denial and independent link coverage', 'canonical identity separation and hidden-label ambiguity', 'case-insensitive wider search and literal percent','chapter and optional scene associations/provenance', 'Context chapter and scene browsing, search, collapse and focus', 'book/chapter/scene mismatch denial and query limits','fresh login reads authoritative saved sources' ],featureUrl:'https://dev.plotdirector.com/Writing/Context/Intent/Palette?'+new URLSearchParams(base), limitations:['Docked Writer, Word evidence and review candidate fixtures are outside this script']})); } catch(error) { console.error('Intent palette acceptance failed at '+stage+' ('+error.name+'). No credentials logged.'); if(error.name==='AssertionError') console.error(error.message); process.exitCode=1; } finally { if(session) { try { await session.cleanup(); console.log('PASS disposable Intent palette project cleanup'); } catch { console.error('Intent palette cleanup needs documented resume.'); process.exitCode=1; } finally { await session.close(); } } } })().catch(()=>{console.error('Intent palette session failed; preserve run journal.');process.exitCode=1;});