diff --git a/.github/workflows/repository-checks.yml b/.github/workflows/repository-checks.yml index ca5e226..9df5363 100644 --- a/.github/workflows/repository-checks.yml +++ b/.github/workflows/repository-checks.yml @@ -34,10 +34,15 @@ jobs: echo '2ab571f367f293bb19523b76f92f1945bbf245003392c7f392903f95c2b9b630 .harness/ci-bin/opa' | sha256sum --check chmod +x .harness/ci-bin/opa echo "$GITHUB_WORKSPACE/.harness/ci-bin" >> "$GITHUB_PATH" + - name: Validate retained purchase regression tests + run: .venv/bin/python -m unittest discover -s tests -p 'test_purchase_*.py' -v + env: + PYTHONPATH: packages/engine:packages/governance - run: npm test - run: npm run typecheck - run: npm run demo:fixtures:check - run: npm run demo:production:check + - run: node --test apps/aps-demo/scripts/production.test.mjs - run: npm run demo:lint - run: npm run demo:typecheck - run: npm run demo:test @@ -50,7 +55,7 @@ jobs: github.event.pull_request.base.ref == 'main' && github.event.pull_request.base.repo.full_name == github.repository && github.event.pull_request.head.repo.full_name == github.repository && - github.event.pull_request.head.ref == 'release/aps-github-validation-v1' + (github.event.pull_request.head.ref == 'release/aps-github-validation-v1' || github.event.pull_request.head.ref == 'codex/aps-redesign-release') run: node apps/aps-demo/scripts/qa-evidence.mjs - name: Record actual PR checkout and workflow identities id: validation @@ -76,7 +81,7 @@ jobs: github.event.pull_request.base.ref == 'main' && github.event.pull_request.base.repo.full_name == github.repository && github.event.pull_request.head.repo.full_name == github.repository && - github.event.pull_request.head.ref == 'release/aps-github-validation-v1' + (github.event.pull_request.head.ref == 'release/aps-github-validation-v1' || github.event.pull_request.head.ref == 'codex/aps-redesign-release') run: node apps/aps-demo/scripts/validation-evidence.mjs finalize - name: Retain predeployment evidence including failed runs if: >- @@ -84,7 +89,7 @@ jobs: github.event.pull_request.base.ref == 'main' && github.event.pull_request.base.repo.full_name == github.repository && github.event.pull_request.head.repo.full_name == github.repository && - github.event.pull_request.head.ref == 'release/aps-github-validation-v1' + (github.event.pull_request.head.ref == 'release/aps-github-validation-v1' || github.event.pull_request.head.ref == 'codex/aps-redesign-release') uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2; ordinary artifact only with: name: aps-predeploy-${{ steps.validation.outputs.checkout_sha || github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} diff --git a/README.md b/README.md index 2714147..bfd56e6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Open-source research sandbox for **hazard and operability (HAZOP) analysis of AI agents and multi-agent systems**. APS combines deterministic hazard screening, a simulated procurement swarm, and policy-as-code experiments using **Open Policy Agent (OPA) and Rego**. -Follow an agent objective through an unsafe operation, a proposed control, a simulated gateway decision and its assurance evidence. Five workers model demand forecasting, inventory, supplier selection, finance approval and purchase execution. All tools are simulated; no real purchase or payment can be made. +Compare the same illustrative request under different control bundles, follow the point where their outcomes diverge, and connect a proposed response to hazards and evidence. The separate research implementation models demand forecasting, inventory, supplier selection, finance approval and purchase execution. All tools are simulated; no real purchase or payment can be made. **SafetyMP research thesis — managing risk enables sustainable AI operations.** APS examines how delegation, shared context, and approval boundaries can introduce failure modes in multi-agent workflows. It links simulated hazards to proposed controls and repeatable experiments, asking whether risk can be managed without making agent collaboration impractical. These are research hypotheses, not proven production safeguards. See the [portfolio thesis](https://github.com/SafetyMP/SafetyMP). @@ -28,17 +28,27 @@ Follow an agent objective through an unsafe operation, a proposed control, a sim The React/TypeScript explorer runs entirely in the browser, with no account, API key, paid inference, backend or telemetry. -- **Procurement topology:** inspect the orchestrator, five workers and their trust boundaries. -- **HAZOP Lab:** explore 96 unverified findings and 16 authored reference scenarios. -- **Governance stories:** compare baseline, conventional access checks and HAZOP-informed checks across nine illustrative stories. -- **Swarm simulator:** start, pause, step and reset a deterministic run; inspect local approve/deny outcomes. -- **Assurance:** follow source links, proposed controls, test selectors and recorded trials. +The opening case asks: **the purchase agent has permission, but is its approval still valid?** An illustrative purchase arrives 61 logical seconds after finance approval; the modeled validity rule requires an age below 60. The amount is 300 sandbox units, a teaching input rather than a recovered historical trial amount. -Keyboard entity buttons accompany the topology; charts include data tables. System, light and dark themes persist locally. +The five views support one connected investigation: -The executive journey keeps the selected case connected to its review and evidence. **Prepare example** selects a paused run; **Advance to next decision** stops at a decision or recovery boundary. Technical step controls and inspectors remain available. Decision briefs retain notes and attached observations across modules, with explicit browser saving, JSON import/export and printable provenance. See [continuity and saved brief usage](docs/CONTINUITY_IMPLEMENTATION.md) for persistence limits and verification results. +- **Start here:** launch the approval-expiry case, browse all nine illustrative cases, and inspect the declared procurement topology. +- **Case Lab:** compare B (tool permission and spend limit) with C (additional lifecycle checks) against identical inputs; optionally include A (no modeled checks). Inspect decisions, a selectable failure path, and bounded illustrative effects. +- **Hazard study:** examine the selected case's intended behavior, deviations, assumptions and proposed controls, with the full 96-entry screening register, node × deviation matrix and 16 authored references available. +- **Controls:** inspect what a protection checks, where its authority comes from, and its implementation/test mapping. The Case Lab is the single browser request runner. +- **Evidence:** inspect the retained browser comparison separately from recorded experiments, paired B/C calls, replay, charts, source lineage and explicit gaps. -**Project URL:** [safetymp.github.io/Agentic-Process-Safety](https://safetymp.github.io/Agentic-Process-Safety/). Deployment remains unverified. The retained publication notes record a case-sensitive asset-path failure and a pending publication of the portable-base fix; historical CI is not proof that the live site works. See the [publication handoff](docs/STATIC_DEMO_PUBLICATION_HANDOFF.md). +Choose **Run comparison**, then vary approval age using 59/60/61 shortcuts or the age input. At 59 both B and C allow; at 60 and 61 B allows and C denies. Changing inputs creates a draft and does not relabel an earlier result. Retained comparisons preserve their inputs, predictions and reasoning across views. Normal and unauthorized-tool cases also show where B and C reach the same outcome. Six secondary cases retain rule exploration with business effects explicitly unmodeled. + +The **Discussion worksheet** attaches a recommendation, rationale, evidence, assumptions, unanswered question and dissent to a particular run. Marking a position ready grants no authority. **Explore a fresh-approval request** creates a hypothetical child from C's no-effect state with a new request identity; it preserves the denied parent and does not continue B's already executed purchase. A fresh approval still does not establish that a quotation, forecast or stock record is correct. + +Use **Keep or export this discussion** for explicit browser-local save/load/delete, a readable Markdown brief, session JSON, and a configuration-only link. Notes remain in memory unless explicitly saved; loading a browser copy is an explicit action. Configuration links carry bounded inputs, not notes, outcomes or approvals. See the [redesign plan](docs/APS_EXPERIENCE_REDESIGN_PLAN.md) and [local implementation and verification record](docs/APS_REDESIGN_IMPLEMENTATION.md) for delivered scope and verification limits. + +Keyboard entity buttons accompany the topology, the failure path has an ordered text representation, and charts include data tables. System, light and dark themes persist locally. The comparison explains these selected control bundles; it does not establish that HAZOP uniquely discovers the checks or outperforms other analysis methods. + +The earlier executive journey, **Prepare example**, **Advance to next decision**, and decision-brief JSON import described in [continuity and saved brief usage](docs/CONTINUITY_IMPLEMENTATION.md) belong to a previous interface. That document is retained as historical implementation evidence, not instructions for this redesign. + +**Project URL:** [safetymp.github.io/Agentic-Process-Safety](https://safetymp.github.io/Agentic-Process-Safety/). This README describes the redesign source; publication and source-bound CI acceptance for this revision require separate verification. The [earlier publication handoff](docs/STATIC_DEMO_PUBLICATION_HANDOFF.md) is retained as historical evidence and does not establish deployment of this redesign. ## Quick start @@ -122,7 +132,7 @@ See [Phase 3 operations](docs/PHASE3_OPERATIONS.md) for fresh acceptance runs an ## Security -- Browser approvals affect local illustrative state only. The browser model omits authentication, real policy execution, atomic persistence, signed receipts and production objective arbitration. +- Discussion notes and hypothetical fresh-approval branches affect local illustrative state only; they issue no operational authorization. The browser model omits authentication, real policy execution, atomic persistence, signed receipts and production objective arbitration. - Local attestations, signing keys and ledger heads cannot independently establish identity or resist an owner replacing all local evidence. - Finite experiment observations and unequal early-termination denominators are not real-world effectiveness estimates. Missing measurements remain unknown. - Keep signing keys, databases and operational logs out of static deployments. Publish only reviewed public assets. @@ -156,6 +166,7 @@ Project-owned material is offered under [Apache 2.0](LICENSE), subject to preser | Engine and gateway boundaries | [Phase 1 architecture](docs/ARCHITECTURE.md) · [Governance architecture](docs/GOVERNANCE_ARCHITECTURE.md) | | Gateway operation and policy workflow | [Phase 2 operations](docs/PHASE2_OPERATIONS.md) | | Experiments and attested assurance | [Phase 3 operations](docs/PHASE3_OPERATIONS.md) | -| Browser QA and publication | [Browser QA](docs/STATIC_DEMO_BROWSER_QA.md) · [Publication handoff](docs/STATIC_DEMO_PUBLICATION_HANDOFF.md) | +| Current browser redesign and local verification | [Redesign plan](docs/APS_EXPERIENCE_REDESIGN_PLAN.md) · [Implementation and verification](docs/APS_REDESIGN_IMPLEMENTATION.md) | +| Earlier browser QA and publication records (historical) | [Browser QA](docs/STATIC_DEMO_BROWSER_QA.md) · [Publication handoff](docs/STATIC_DEMO_PUBLICATION_HANDOFF.md) | | Full CLI examples, human review syntax and retained evidence notes | [Development reference](docs/DEVELOPMENT_REFERENCE.md) | | Open-source readiness and owner gates | [Readiness audit](docs/open-source-readiness.md) | diff --git a/apps/aps-demo/scripts/e2e.mjs b/apps/aps-demo/scripts/e2e.mjs index c5f2172..01f0411 100644 --- a/apps/aps-demo/scripts/e2e.mjs +++ b/apps/aps-demo/scripts/e2e.mjs @@ -2,7 +2,6 @@ import assert from 'node:assert/strict'; import { createServer } from 'node:http'; import { readFile, mkdir, writeFile } from 'node:fs/promises'; import { resolve, extname } from 'node:path'; -import { URLSearchParams } from 'node:url'; /* global document, window */ // Serve only the built artifact at its actual Pages prefix. No SPA server fallback. @@ -35,7 +34,6 @@ try { await new Promise(r => server.listen(0, '127.0.0.1', r)); const origin = `http://127.0.0.1:${server.address().port}`; console.log(`Browser engine requested: ${engine} (${process.platform}); no fallback`); - console.log(`Pinned browser cache: ${process.env.PLAYWRIGHT_BROWSERS_PATH}`); browser = await ({ chromium, firefox })[engine].launch({ headless: true }); console.log(`Browser engine running: ${engine} ${browser.version()}`); const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, reducedMotion: 'reduce' }); @@ -50,644 +48,199 @@ try { page.on('pageerror', e => errors.push(e.message)); page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); }); page.on('websocket', ws => violations.push(ws.url())); - const executiveHeadings = { overview: 'Delegate work. Keep control of the outcome.', simulator: 'What must stay true before we buy?', governance: 'How does a request boundary change the outcome?', hazop: 'What can depart from intended purchasing?', assurance: 'What should the team take from this case?' }; - // Fresh documents must demonstrate the real default BEFORE legacy setup. - const assertExecutiveDefault = async route => { - await expect(page.getByRole('radio', { name: 'Executive', exact: true })).toBeChecked(); assertions++; - await expect(page.getByRole('heading', { level: 1, name: route.split('?')[0] === 'hazop' && new URLSearchParams(route.split('?')[1] ?? '').get('hazard') === 'APS-f47191931b96a999a61c' ? 'What could go wrong between permission and purchase?' : executiveHeadings[route.split('?')[0]], exact: true })).toBeVisible(); assertions++; - await expect(page.locator('[data-executive-uncertainty]:visible').first()).toBeVisible(); assertions++; - }; - const selectTechnical = async () => { - await page.getByRole('radio', { name: 'Technical', exact: true }).check(); - await expect(page.getByRole('radio', { name: 'Technical', exact: true })).toBeChecked(); assertions++; - }; - // goto between hash routes can retain the current document and audience. - // Technical regression navigation must not mistake that for a fresh default. - const go = async route => { await page.goto(`${origin}${prefix}#/${route}`); await expect(page.locator('h1')).toBeVisible(); assertions++; await selectTechnical(); }; - const freshExecutive = async route => { - await page.goto(`${origin}${prefix}#/${route}`); - await page.reload(); // Deliberately create a new App/AudienceProvider lifetime. - await assertExecutiveDefault(route); - }; - const stat = (label, scope = page) => scope.locator('.stat').filter({ has: page.getByText(label, { exact: true }) }).locator('strong'); - // Increment only after each added check has actually completed successfully. - const check = async verify => { await verify(); assertions++; }; - const navigationNames = { overview: /^Overview/, governance: /^Control Plane/, simulator: /^Swarm Simulator/, assurance: /^Assurance/ }; - // Hash changes commit asynchronously, while the old workflow stays mounted. - // Wait for React's route marker before resolving controls in the new view. - const clickNavigation = async name => { - const link = page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name, exact: typeof name === 'string' }); - await link.click(); - await check(() => expect(link).toHaveAttribute('aria-current', 'page')); - }; - const navigateWithin = async section => { - await clickNavigation(navigationNames[section]); - await check(() => expect(page.locator('h1')).toBeVisible()); - }; - const workflowStatus = page.getByRole('status', { name: 'Workflow status', exact: true }); - const captureGeneratedWorkflow = async () => { - await check(() => expect(workflowStatus).toHaveCount(1)); - await check(() => expect(workflowStatus).toContainText('paused')); - await page.getByRole('button', { name: 'Prepare current replay JSON', exact: true }).click(); - const replayText = await page.getByRole('textbox', { name: 'Prepared replay snapshot', exact: true }).inputValue(); - const replay = JSON.parse(replayText); - await check(() => assert.equal(replay.simulationOnly, true)); - return { replayText, status: await workflowStatus.innerText(), orders: await stat('Committed orders').innerText(), spent: await stat('Simulated spend').innerText(), confirmed: await stat('Task confirmed').innerText(), safe: await stat('Safe model completion').innerText() }; - }; - const populatePausedWorkflow = async () => { - await check(() => expect(stat('Committed orders')).toHaveText('0')); - for (let transition = 0; transition < 100 && (await stat('Committed orders').innerText()).trim() !== '1'; transition++) { - const step = page.getByRole('button', { name: 'Step one transition', exact: true }); - await check(() => expect(step).toBeEnabled()); - await step.click(); - } - await check(() => expect(stat('Committed orders')).toHaveText('1')); - await check(() => expect(stat('Simulated spend')).toHaveText('400')); - await check(() => expect(stat('Task confirmed')).toHaveText('No')); - await check(() => expect(stat('Safe model completion')).toHaveText('No')); - const snapshot = await captureGeneratedWorkflow(); - const replay = JSON.parse(snapshot.replayText); - await check(() => assert.equal(replay.spec.scenario, 'nominal')); - await check(() => assert.equal(replay.spec.mode, 'C')); - await check(() => assert.ok(replay.transitionCount > 0 && replay.transitionCount <= 100)); - await check(() => assert.ok(replay.events.some(event => event.type === 'order-committed'))); - return snapshot; - }; - const assertGeneratedWorkflowUnchanged = async baseline => { - const current = await captureGeneratedWorkflow(); - // Exact replay equality retains specification, effects digest, journal and causal history. - await check(() => assert.deepEqual(current, baseline)); - }; - // Supplementary Executive images are OUTSIDE the seven-capture gate artifact. - const executiveShots = resolve('.harness/executive-review'); - await mkdir(executiveShots, { recursive: true }); - for (const route of ['overview', 'simulator', 'governance', 'hazop', 'assurance']) { - await freshExecutive(route); - await page.screenshot({ path: resolve(executiveShots, `${route}.jpg`), quality: 65 }); - const executiveRadio = page.getByRole('radio', { name: 'Executive', exact: true }); - await executiveRadio.focus(); await page.keyboard.press('ArrowRight'); - await expect(page.getByRole('radio', { name: 'Technical', exact: true })).toBeFocused(); assertions++; - await expect(page.getByRole('radio', { name: 'Technical', exact: true })).toBeChecked(); assertions++; - await page.keyboard.press('ArrowLeft'); await expect(executiveRadio).toBeChecked(); assertions++; - await expect(executiveRadio).toBeFocused(); assertions++; - } - await freshExecutive('simulator'); - await page.getByRole('button', { name: 'Step one transition', exact: true }).click(); - await selectTechnical(); - await page.getByRole('button', { name: 'Prepare current replay JSON', exact: true }).click(); - const audienceSnapshot = await page.getByRole('textbox', { name: 'Prepared replay snapshot', exact: true }).inputValue(); - const audienceStatus = await workflowStatus.innerText(); - for (const name of ['Executive', 'Technical']) { - await page.getByRole('radio', { name, exact: true }).check(); - // The hidden technical textbox remains the SAME prepared snapshot, not a new export. - await expect(page.getByRole('textbox', { name: 'Prepared replay snapshot', exact: true, includeHidden: true })).toHaveValue(audienceSnapshot); assertions++; - await expect(workflowStatus).toHaveText(audienceStatus, { useInnerText: true }); assertions++; - } - // Persistence on hash navigation is tested WITHOUT the Technical setup helper. - await clickNavigation(/^Assurance/); - await expect(page.getByRole('radio', { name: 'Technical', exact: true })).toBeChecked(); assertions++; - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - await clickNavigation(/^Why APS matters/); - await expect(page.getByRole('radio', { name: 'Executive', exact: true })).toBeChecked(); assertions++; - await page.goBack(); await expect(page.getByRole('radio', { name: 'Executive', exact: true })).toBeChecked(); assertions++; - await page.goForward(); await expect(page.getByRole('radio', { name: 'Executive', exact: true })).toBeChecked(); assertions++; - // ADDITIVE viewport and first-screen action acceptance. No original oracle is replaced. - const graphGeometry = async () => page.getByLabel('Interactive procurement agent topology', { exact: true }).evaluate(graph => { - const flow = graph.querySelector('.react-flow__renderer'); const rect = flow.getBoundingClientRect(); - const nodes = Array.from(graph.querySelectorAll('.react-flow__node')).map(node => { const r = node.getBoundingClientRect(); return { id: node.getAttribute('data-id'), x: r.x, y: r.y, right: r.right, bottom: r.bottom }; }); - return { flow: { x: rect.x, y: rect.y, right: rect.right, bottom: rect.bottom, width: rect.width, height: rect.height }, nodes, transform: graph.querySelector('.react-flow__viewport').getAttribute('style') }; - }); - const assertGraphCentered = async () => check(async () => { - await expect.poll(async () => { - const g = await graphGeometry(); - const union = { left: Math.min(...g.nodes.map(n => n.x)), right: Math.max(...g.nodes.map(n => n.right)), top: Math.min(...g.nodes.map(n => n.y)), bottom: Math.max(...g.nodes.map(n => n.bottom)) }; - return { count: g.nodes.length, inside: g.flow.width > 0 && g.flow.height > 0 && union.left >= g.flow.x + 8 && union.right <= g.flow.right - 8 && union.top >= g.flow.y + 8 && union.bottom <= g.flow.bottom - 8, centered: Math.abs((union.left + union.right - g.flow.x - g.flow.right) / 2) <= 2 && Math.abs((union.top + union.bottom - g.flow.y - g.flow.bottom) / 2) <= 2 }; - }).toEqual({ count: 8, inside: true, centered: true }); - }); - const settleViewportFrames = async () => page.evaluate(() => new Promise(resolve => window.requestAnimationFrame(() => window.requestAnimationFrame(resolve)))); - const assertViewportRetained = async before => check(async () => { await settleViewportFrames(); assert.equal((await graphGeometry()).transform, before); }); - await page.setViewportSize({ width: 1280, height: 720 }); await freshExecutive('overview'); - await selectTechnical(); await assertGraphCentered(); // First reveal; no Fit View correction first. - const graph = page.getByLabel('Interactive procurement agent topology', { exact: true }); - for (const label of ['Zoom In', 'Zoom Out']) { - await graph.getByRole('button', { name: label, exact: true }).click(); const zoomed = (await graphGeometry()).transform; - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); await selectTechnical(); await assertViewportRetained(zoomed); - await page.setViewportSize({ width: 1200, height: 720 }); await assertViewportRetained(zoomed); - await page.setViewportSize({ width: 1280, height: 720 }); await assertViewportRetained(zoomed); - await graph.getByRole('button', { name: 'Fit View', exact: true }).click(); await assertGraphCentered(); - } - await graph.scrollIntoViewIfNeeded(); - const paneBox = await graph.locator('.react-flow__pane').boundingBox(); assert.ok(paneBox); - await page.mouse.move(paneBox.x + 20, paneBox.y + 20); const beforePan = (await graphGeometry()).transform; - await page.mouse.down(); await page.mouse.move(paneBox.x + 50, paneBox.y + 40, { steps: 5 }); await page.mouse.up(); await settleViewportFrames(); - const panned = (await graphGeometry()).transform; await check(() => assert.notEqual(panned, beforePan)); - await page.setViewportSize({ width: 1200, height: 720 }); await assertViewportRetained(panned); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); await selectTechnical(); await assertViewportRetained(panned); - await graph.scrollIntoViewIfNeeded(); const wheelBox = await graph.locator('.react-flow__pane').boundingBox(); assert.ok(wheelBox); - await page.mouse.move(wheelBox.x + 20, wheelBox.y + 20); await page.mouse.wheel(0, -120); await settleViewportFrames(); - const wheeled = (await graphGeometry()).transform; await check(() => assert.notEqual(wheeled, panned)); - await page.setViewportSize({ width: 1280, height: 720 }); await assertViewportRetained(wheeled); - await graph.getByRole('button', { name: 'Fit View', exact: true }).click(); await assertGraphCentered(); - await graph.getByRole('button', { name: 'Zoom In', exact: true }).focus(); await page.keyboard.press('Space'); - const keyboardZoomed = (await graphGeometry()).transform; - await page.setViewportSize({ width: 1200, height: 720 }); await assertViewportRetained(keyboardZoomed); - await graph.getByRole('button', { name: 'Fit View', exact: true }).click(); await assertGraphCentered(); - await page.setViewportSize({ width: 900, height: 720 }); await assertGraphCentered(); - await page.setViewportSize({ width: 320, height: 720 }); await assertGraphCentered(); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); await selectTechnical(); await assertGraphCentered(); - await go('simulator'); await go('overview'); await assertGraphCentered(); // Supported navigation/return, no invented audience URL. - const assertInitialActions = async () => check(async () => { - const controls = [page.getByLabel('Question to examine', { exact: true }), page.getByRole('button', { name: 'Prepare example', exact: true }), page.getByRole('button', { name: 'Start workflow', exact: true })]; - for (const control of controls) { - const box = await control.evaluate(element => { const r = element.getBoundingClientRect(); const chrome = document.querySelector('.audience-bar').getBoundingClientRect(); return { top: r.top, bottom: r.bottom, unobscured: document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2) === element, belowChrome: r.top >= chrome.bottom }; }); - assert.ok(box.top >= 0 && box.bottom <= 720 && box.belowChrome && box.unobscured, `initial Executive question/Prepare/Start must fit and be unobscured without reviewer scrolling: ${control} ${JSON.stringify(box)}`); - } - }); - await page.setViewportSize({ width: 1280, height: 720 }); await freshExecutive('simulator'); await assertInitialActions(); - await freshExecutive('overview'); await page.getByRole('link', { name: 'Open the purchasing workspace', exact: true }).click(); - await check(() => expect(page.getByRole('heading', { level: 1, name: executiveHeadings.simulator, exact: true })).toBeVisible()); - await assertInitialActions(); - // END ADDITIVE viewport and first-screen action acceptance. - // ADDITIVE Executive narrative: context-specific headings and unsaved discussion. - for (const target of ['hazop', 'hazop?hazard=APS-f47191931b96a999a61c', 'hazop?hazard=APS-758a4efe3266c2f560e4', 'hazop?hazard=not-a-finding']) await freshExecutive(target); - await freshExecutive('assurance'); - const discussionDraft = page.getByRole('region', { name: 'Non-binding discussion draft', exact: true }); - await check(() => expect(discussionDraft).toContainText('No purchasing decision observed; these positions are hypotheses.')); - await discussionDraft.getByRole('radio', { name: 'More evidence before a recommendation', exact: true }).check(); - await check(() => expect(discussionDraft).toContainText('not an approval or a validated recommendation')); - await clickNavigation('How controls work'); - await page.getByRole('button', { name: 'Reset workflow and clear history', exact: true }).click(); - await clickNavigation('What leaders decide'); - await check(() => expect(discussionDraft).toContainText('The run has changed—review this draft again.')); - await discussionDraft.getByRole('radio', { name: 'More evidence before a recommendation', exact: true }).press('Space'); - await check(() => expect(discussionDraft).not.toContainText('The run has changed—review this draft again.')); - await page.reload(); await assertExecutiveDefault('assurance'); - await check(() => expect(discussionDraft.getByRole('radio', { name: 'More evidence before a recommendation', exact: true })).not.toBeChecked()); - // END ADDITIVE Executive narrative. - // ADDITIVE Operations/HAZOP journey. Original Technical/default journeys remain below. - await freshExecutive('overview'); - const recommendation = page.getByRole('region', { name: 'HAZOP recommendation', exact: true }); - await check(() => expect(recommendation).toContainText('does not execute a stop or prove safety')); - await check(() => expect(recommendation.getByRole('link', { name: 'Open the purchasing workspace', exact: true })).toBeVisible()); - await check(() => expect(recommendation.getByRole('link', { name: 'Inspect the technical mechanism', exact: true })).toBeVisible()); - await page.setViewportSize({ width: 1280, height: 720 }); - for (const name of ['Executive', 'Technical']) await check(async () => { - const unobscured = await page.getByRole('radio', { name, exact: true }).evaluate(input => { - const label = input.closest('label'); const box = label.getBoundingClientRect(); - return document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2)?.closest('label') === label; - }); - assert.equal(unobscured, true, `${name} audience label must not be occluded`); - }); - await recommendation.getByRole('link', { name: 'Open the purchasing workspace', exact: true }).click(); - const operations = page.getByRole('region', { name: 'Purchasing operations', exact: true }); - const records = page.getByRole('navigation', { name: 'Main navigation', exact: true }); - await check(() => expect(operations).toBeVisible()); - await check(() => expect(workflowStatus).toContainText('0 transitions')); - const taskRecordName = await operations.getByRole('button', { name: /^Open task / }).innerText(); - await operations.getByRole('button', { name: taskRecordName, exact: true }).click(); - await check(() => expect(operations.getByRole('region', { name: 'Selected purchasing record', exact: true })).toContainText(taskRecordName.slice('Open task '.length))); - await selectTechnical(); const operationsInitial = await captureGeneratedWorkflow(); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - for (const name of ['How controls work', 'What leaders decide', 'Why APS matters']) await clickNavigation(name); - await clickNavigation('How controls work'); - await check(() => expect(operations.getByText('No quote prepared yet.', { exact: true })).toBeVisible()); - await check(() => expect(operations.getByText('No simulated permission issued.', { exact: true })).toBeVisible()); - await check(() => expect(operations.getByText('Related timing finding—different object/coverage', { exact: true })).toHaveCount(0)); - await records.getByRole('link', { name: 'Why APS matters', exact: true }).focus(); await page.keyboard.press('Tab'); - await check(() => expect(records.getByRole('link', { name: 'How controls work', exact: true })).toBeFocused()); - await page.keyboard.press('Shift+Tab'); await check(() => expect(records.getByRole('link', { name: 'Why APS matters', exact: true })).toBeFocused()); - await selectTechnical(); await assertGeneratedWorkflowUnchanged(operationsInitial); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - await page.getByLabel('Question to examine', { exact: true }).selectOption('approval-delay'); - await selectTechnical(); await assertGeneratedWorkflowUnchanged(operationsInitial); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - await page.getByRole('button', { name: 'Prepare example', exact: true }).click(); - // Explicit Start/Pause do not constitute a commitment or a new authority. - await page.getByRole('button', { name: 'Start workflow', exact: true }).click(); - await page.getByRole('button', { name: 'Pause workflow', exact: true }).click(); - await check(() => expect(workflowStatus).toContainText('paused')); - await page.getByRole('button', { name: 'Reset workflow and clear history', exact: true }).click(); - await check(() => expect(workflowStatus).toContainText('0 transitions')); - const operationsBoundary = async () => { - const step = page.getByRole('button', { name: 'Step one transition', exact: true }); - for (let i = 0; i < 100 && await step.isEnabled(); i++) await step.click(); - await check(() => expect(step).toBeDisabled()); - }; - await operationsBoundary(); - await clickNavigation('How controls work'); - await check(() => expect(operations.getByRole('button', { name: /^Open permission / })).toHaveCount(1)); - await operations.getByRole('button', { name: /^Open permission / }).click(); - await clickNavigation('How controls work'); - const blockedEventIdentity = await page.getByRole('region', { name: 'Approval refresh decision', exact: true }).locator('.text-button').innerText(); - await operations.getByRole('button', { name: `Open exception ${blockedEventIdentity}`, exact: true }).click(); - await operations.getByRole('region', { name: 'Selected purchasing record', exact: true }).getByRole('button', { name: 'Review exception design', exact: true }).click(); - const designReview = operations.getByRole('region', { name: 'HAZOP design review', exact: true }); - await check(() => expect(designReview.getByText('Related timing finding—different object/coverage', { exact: true })).toBeVisible()); - await check(() => expect(designReview).toContainText('expired QUOTATION')); - await check(() => expect(designReview).toContainText('expires an APPROVAL')); - await selectTechnical(); const blockedOperations = await captureGeneratedWorkflow(); - await check(() => assert.equal(blockedOperations.orders, '0')); await check(() => assert.equal(blockedOperations.spent, '0')); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - await designReview.getByRole('button', { name: 'Next review question', exact: true }).click(); - await selectTechnical(); await assertGeneratedWorkflowUnchanged(blockedOperations); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - await page.getByRole('button', { name: 'Request one approval refresh', exact: true }).click(); await operationsBoundary(); - await selectTechnical(); await check(() => expect(stat('Committed orders')).toHaveText('1')); await check(() => expect(stat('Safe model completion')).toHaveText('Yes')); - for (const mode of ['A', 'B']) { - await page.getByLabel('Workflow comparator', { exact: true }).selectOption(mode); - await page.getByRole('button', { name: 'Prepare example', exact: true }).click(); await operationsBoundary(); - await check(() => expect(stat('Task confirmed')).toHaveText('Yes')); await check(() => expect(stat('Safe model completion')).toHaveText('No')); - await check(() => expect(stat('Unsafe committed effects')).toHaveText('1')); await check(() => expect(page.getByRole('button', { name: 'Request one approval refresh', exact: true })).toHaveCount(0)); - } - await page.getByLabel('Workflow scenario', { exact: true }).selectOption('lost-purchase-response'); - await page.getByLabel('Workflow comparator', { exact: true }).selectOption('C'); - await page.getByRole('button', { name: 'Prepare example', exact: true }).click(); await operationsBoundary(); - await check(() => expect(stat('Committed orders')).toHaveText('1')); await check(() => expect(stat('Task confirmed')).toHaveText('No')); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); await clickNavigation('What leaders decide'); - const existingOrderName = await operations.getByRole('button', { name: /^Open order / }).innerText(); - await operations.getByRole('button', { name: existingOrderName, exact: true }).click(); - await operations.getByRole('region', { name: 'Selected purchasing record', exact: true }).getByRole('button', { name: 'Inspect technical evidence', exact: true }).click(); - await check(() => expect(page.getByRole('region', { name: 'Causal event inspector', exact: true })).toContainText('order committed')); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - await page.getByRole('button', { name: 'Reconcile existing order once', exact: true }).click(); await operationsBoundary(); - await clickNavigation('What leaders decide'); await check(() => expect(operations.getByRole('button', { name: existingOrderName, exact: true })).toHaveCount(1)); - await clickNavigation('How controls work'); - await selectTechnical(); await check(() => expect(stat('Committed orders')).toHaveText('1')); await check(() => expect(stat('Task confirmed')).toHaveText('Yes')); - await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - await page.screenshot({ path: resolve(executiveShots, 'operations-records.jpg'), quality: 65 }); - await page.setViewportSize({ width: 1440, height: 1000 }); - // END ADDITIVE Operations/HAZOP journey. + const go = async route => { await page.goto(`${origin}${prefix}#/${route}`); await expect(page.locator('h1')).toBeVisible(); assertions++; }; + const check = async (assertion) => { await assertion(); assertions++; }; + const currentComparison = () => page.getByRole('region', { name: 'Browser comparison', exact: true }); + const lane = mode => currentComparison().getByRole('article', { name: 'Model ' + mode + ' outcome', exact: true }); + const evaluate = async () => { await page.getByRole('button', { name: 'Run comparison', exact: true }).click(); await expect(currentComparison()).toBeVisible(); }; + const routeWithinApp = async route => { const link = page.locator('nav[aria-label="Main navigation"] a[href="#/' + route + '"]'); await link.click(); await expect(link).toHaveAttribute('aria-current', 'page'); await expect(page.locator('h1')).toBeVisible(); }; + const openTools = async () => { const details = page.locator('.discussion-session-tools'); if ((await details.getAttribute('open')) === null) await details.locator('summary').click(); }; await mkdir(screenshots, { recursive: true }); + // Every original hash route still supports a direct built-site refresh. for (const route of ['overview', 'hazop', 'governance', 'simulator', 'assurance']) { - await go(route); await page.reload(); await expect(page.locator('h1')).toBeVisible(); await assertExecutiveDefault(route); await selectTechnical(); - await page.screenshot({ path: resolve(screenshots, `${route}.jpg`), quality: 65 }); assertions++; + await go(route); await page.reload(); + await check(() => expect(page.locator('h1')).toBeVisible()); + if (route === 'simulator') await evaluate(); + await page.screenshot({ path: resolve(screenshots, route + '.jpg'), quality: 65 }); } + await go('overview'); + await page.getByText('Explore the declared procurement system', { exact: true }).click(); for (const label of ['demand', 'inventory', 'supplier', 'finance', 'purchase', 'orchestrator', 'Policy gateway', 'Assurance']) { const button = page.locator('.node-buttons').getByRole('button', { name: label, exact: true }); - await button.click(); await expect(button).toHaveAttribute('aria-pressed', 'true'); assertions++; - } - // Populate a separate generated workflow, stopping after commit but before confirmation. - await navigateWithin('simulator'); - const guideWorkflow = await populatePausedWorkflow(); - await navigateWithin('overview'); - await page.getByRole('button', { name: 'Begin guided walkthrough' }).click(); - const guide = page.getByRole('region', { name: 'Guided walkthrough' }); - const resetChoice = page.getByRole('region', { name: 'Walkthrough reset consequence', exact: true }); - await check(() => expect(guide).toContainText('1 OF 5')); - await check(() => expect(resetChoice).not.toBeVisible()); - for (let i = 2; i <= 4; i++) { - await guide.getByRole('button', { name: 'Next', exact: true }).click(); - await check(() => expect(guide).toContainText(`${i} OF 5`)); + await button.click(); await check(() => expect(button).toHaveAttribute('aria-pressed', 'true')); } - // Visiting the outcome step without evaluation must not invent an outcome. - await check(() => expect(page.locator('.event')).toHaveCount(0)); - await guide.getByRole('button', { name: 'Next', exact: true }).click(); - await check(() => expect(guide).toContainText('5 OF 5')); - await check(() => expect(guide).toContainText('No SIMULATED outcome yet')); - await check(() => expect(guide).toContainText('You advanced without evaluating')); - await check(() => expect(page.locator('.live-outcome')).toContainText('0 unsafe attempts · 0 unsafe executed · 0 blocked')); - await check(() => expect(page.locator('.live-outcome .event')).toHaveCount(0)); - await guide.getByRole('button', { name: 'Back', exact: true }).click(); - await check(() => expect(guide).toContainText('4 OF 5')); - await page.getByRole('button', { name: 'Evaluate simulated request', exact: true }).click(); - await check(() => expect(page.locator('.event')).toContainText('DENY')); - await guide.getByRole('button', { name: 'Next', exact: true }).click(); - await check(() => expect(page.locator('.live-outcome')).toContainText('1 unsafe attempts · 0 unsafe executed · 1 blocked')); - await guide.getByRole('button', { name: 'Back', exact: true }).click(); - await check(() => expect(page.locator('.event')).toContainText('DENY')); - const retainedUrl = page.url(); - const retainedDecision = await page.locator('.event').innerText(); - const assertPolicyDecisionRetained = async () => { - await check(() => expect(page).toHaveURL(retainedUrl)); - await check(() => expect(page.locator('.event')).toHaveCount(1)); - await check(() => expect(page.locator('.event')).toHaveText(retainedDecision, { useInnerText: true })); - await check(() => expect(page.locator('.event')).toContainText('Operation not executed')); - }; - const assertPolicyCountsRetained = async () => { - await navigateWithin('assurance'); - await check(() => expect(page.locator('.live-outcome')).toContainText('1 unsafe attempts · 0 unsafe executed · 1 blocked')); - await navigateWithin('governance'); - await assertPolicyDecisionRetained(); + await page.getByRole('link', { name: 'Explore the approval case →', exact: true }).click(); + await check(() => expect(page.getByLabel('Approval age (logical seconds)', { exact: true })).toHaveValue('61')); + await page.getByText('Predict the outcome · optional', { exact: true }).click(); + await page.getByLabel('Prediction', { exact: true }).selectOption('B'); + await page.getByLabel('Why do you expect that?', { exact: true }).fill('The request is permitted, but the approval is expired.'); + await evaluate(); + await check(() => expect(lane('B').locator('.lane-result')).toHaveText('EXECUTED · MODEL')); + await check(() => expect(lane('C').locator('.lane-result')).toHaveText('BLOCKED · MODEL')); + await check(() => expect(lane('B')).toContainText('0 → 300')); + await check(() => expect(lane('C')).toContainText('0 → 0')); + await page.getByText('Compare every modeled check', { exact: true }).click(); + const checks = page.getByRole('table', { name: 'Ordered checks against the same input snapshot' }); + const freshness = checks.getByRole('row').filter({ hasText: 'Approval freshness' }); + await check(() => expect(freshness).toContainText('Not included')); + await check(() => expect(freshness).toContainText('Fails')); + await check(() => expect(checks.getByRole('row').filter({ hasText: 'Human threshold' })).toContainText('Not evaluated')); + await page.getByRole('button', { name: /Decision boundary/ }).click(); + await check(() => expect(page.locator('.path-detail')).toContainText('freshness')); + + await page.getByLabel('Reason for this recommendation', { exact: true }).fill('Hold the purchase and seek new exact authorization.'); + await page.getByLabel('Dissent or another interpretation', { exact: true }).fill('Quotation truth remains unknown.'); + await page.getByRole('button', { name: 'Mark ready for discussion', exact: true }).click(); + await check(() => expect(page.getByText('Ready for discussion · not approval', { exact: true })).toBeVisible()); + const originalId = await page.getByLabel('Selected comparison', { exact: true }).inputValue(); + await check(() => expect(lane('C').locator('.lane-result')).toHaveText('BLOCKED · MODEL')); + + for (const route of ['hazop', 'governance', 'assurance', 'overview']) await routeWithinApp(route); + await routeWithinApp('simulator'); + await check(() => expect(page.getByLabel('Selected comparison', { exact: true })).toHaveValue(originalId)); + await check(() => expect(page.getByLabel('Reason for this recommendation', { exact: true })).toHaveValue('Hold the purchase and seek new exact authorization.')); + + await page.getByRole('button', { name: '59 seconds', exact: true }).click(); + await check(() => expect(page.locator('.draft-notice')).toContainText('Inputs changed — run again')); + await check(() => expect(lane('C').locator('.lane-result')).toHaveText('BLOCKED · MODEL')); + await evaluate(); + await check(() => expect(lane('C').locator('.lane-result')).toHaveText('EXECUTED · MODEL')); + await page.getByRole('button', { name: '60 seconds', exact: true }).click(); await evaluate(); + await check(() => expect(lane('C').locator('.lane-result')).toHaveText('BLOCKED · MODEL')); + await page.getByRole('button', { name: 'Return to original comparison', exact: true }).click(); + await check(() => expect(page.getByLabel('Reason for this recommendation', { exact: true })).toHaveValue('Hold the purchase and seek new exact authorization.')); + await page.getByRole('button', { name: 'Explore a fresh-approval request', exact: true }).click(); + await check(() => expect(currentComparison()).toContainText('Hypothetical recovery from ' + originalId)); + await check(() => expect(lane('B')).toContainText('0 → 300')); + await check(() => expect(lane('C')).toContainText('0 → 300')); + await check(() => expect(page.getByLabel('Approval age (logical seconds)', { exact: true })).toHaveValue('0')); + + await openTools(); + const downloadPromise = page.waitForEvent('download'); + await page.getByRole('button', { name: 'Download session JSON', exact: true }).click(); + const download = await downloadPromise; + const savedExport = JSON.parse(await readFile(await download.path(), 'utf8')); + const original = savedExport.session.runs.find(run => run.id === originalId); + const child = savedExport.session.runs.find(run => run.parent?.runId === originalId); + assert.equal(original.request.approvalAge, 61); + assert.equal(original.prediction.choice, 'B'); + assert.equal(child.parent.lane, 'C'); + assert.deepEqual(child.baseline, { orders: 0, spend: 0 }); + assert.notEqual(child.requestIdentity, original.requestIdentity); + assert.equal(savedExport.session.discussions[originalId].dissent, 'Quotation truth remains unknown.'); + assertions += 6; + await page.getByRole('button', { name: 'Save in this browser', exact: true }).click(); + const countBeforeClear = savedExport.session.runs.length; + await page.getByRole('button', { name: 'Clear current session', exact: true }).click(); + await page.getByRole('button', { name: 'Clear comparisons and notes', exact: true }).click(); + await check(() => expect(page.getByRole('region', { name: 'Browser comparison', exact: true })).toHaveCount(0)); + await page.getByRole('button', { name: 'Load saved session', exact: true }).click(); + await page.getByRole('button', { name: 'Replace with saved session', exact: true }).click(); + await check(() => expect(page.getByLabel('Selected comparison', { exact: true }).locator('option')).toHaveCount(countBeforeClear)); + const configLink = await page.getByRole('link', { name: 'Open configuration-only link →', exact: true }).getAttribute('href'); + assert.ok(!configLink.includes('Quotation') && !configLink.includes('rationale')); assertions++; + await page.getByRole('button', { name: 'Delete browser copy', exact: true }).click(); + await page.getByRole('button', { name: 'Delete saved copy', exact: true }).click(); + await check(() => expect(currentComparison()).toBeVisible()); + + // Preserve all nine stories, with A available explicitly and no invented effects. + const expected = { + normal: ['EXECUTED · MODEL', 'EXECUTED · MODEL', 'EXECUTED · MODEL'], + unauthorized: ['EXECUTED · MODEL', 'BLOCKED · MODEL', 'BLOCKED · MODEL'], + spending: ['EXECUTED · MODEL', 'BLOCKED · MODEL', 'BLOCKED · MODEL'], + delegation: ['EXECUTED · MODEL', 'EXECUTED · MODEL', 'BLOCKED · MODEL'], + approval: ['EXECUTED · MODEL', 'EXECUTED · MODEL', 'BLOCKED · MODEL'], + replay: ['EXECUTED · MODEL', 'EXECUTED · MODEL', 'BLOCKED · MODEL'], + stale: ['EXECUTED · MODEL', 'EXECUTED · MODEL', 'BLOCKED · MODEL'], + conflict: ['EXECUTED · MODEL', 'EXECUTED · MODEL', 'REVIEW PENDING'], + context: ['EXECUTED · MODEL', 'EXECUTED · MODEL', 'BLOCKED · MODEL'], }; - await guide.getByRole('button', { name: 'Restart', exact: true }).click(); - await check(() => expect(resetChoice).toBeVisible()); - await check(() => expect(resetChoice).toContainText('clears the current single-request policy illustration')); - await assertPolicyDecisionRetained(); - await assertPolicyCountsRetained(); - await check(() => expect(resetChoice).toBeVisible()); - await resetChoice.getByRole('button', { name: 'Keep current policy run', exact: true }).click(); - await check(() => expect(resetChoice).not.toBeVisible()); - await assertPolicyDecisionRetained(); - await assertPolicyCountsRetained(); - await navigateWithin('simulator'); - await assertGeneratedWorkflowUnchanged(guideWorkflow); - await navigateWithin('governance'); - await assertPolicyDecisionRetained(); - await guide.getByRole('button', { name: 'Restart', exact: true }).click(); - await check(() => expect(resetChoice).toBeVisible()); - await resetChoice.getByRole('button', { name: 'Start walkthrough and clear policy run', exact: true }).click(); - await check(() => expect(resetChoice).not.toBeVisible()); - await check(() => expect(guide).toContainText('1 OF 5')); - await check(() => expect(page).toHaveURL(/#\/overview$/)); - const shared = page.getByRole('region', { name: 'Shared simulated run', exact: true }); - await check(() => expect(shared).toContainText('mode C · seed 42 · logical tick 0')); - await check(() => expect(shared).toContainText('Unauthorized tool execution')); - await check(() => expect(shared).toContainText('0 unsafe attempts · 0 unsafe executed · 0 blocked')); - await navigateWithin('simulator'); - await assertGeneratedWorkflowUnchanged(guideWorkflow); - // In-app navigation must expose an empty policy history without reloading the app. - await navigateWithin('governance'); - await check(() => expect(page.getByLabel('Scenario', { exact: true })).toHaveValue('unauthorized')); - await check(() => expect(page.getByLabel('Governance mode', { exact: true })).toHaveValue('C')); - await check(() => expect(page.getByLabel('Deterministic seed', { exact: true })).toHaveValue('42')); - await check(() => expect(page.locator('.event')).toHaveCount(0)); - await check(() => expect(page.getByText('No decision yet. Three logical steps reach the gateway.', { exact: true })).toBeVisible()); - await guide.getByRole('button', { name: 'Close walkthrough', exact: true }).click(); - await check(() => expect(guide).not.toBeVisible()); + await page.getByLabel('Include A · no modeled checks').check(); + for (const [story, decisions] of Object.entries(expected)) { + await page.getByLabel('Choose a case', { exact: true }).selectOption(story); + await page.getByRole('button', { name: 'Reset inputs', exact: true }).click(); + await evaluate(); + for (const [index, mode] of ['A', 'B', 'C'].entries()) await check(() => expect(lane(mode).locator('.lane-result')).toHaveText(decisions[index])); + if (!['normal', 'unauthorized', 'stale'].includes(story)) await check(() => expect(lane('C')).toContainText('Effect projection is not modeled')); + } + await page.getByLabel('Choose a case', { exact: true }).selectOption('stale'); + await page.getByLabel('Approval age (logical seconds)', { exact: true }).fill('-1'); + await check(() => expect(page.getByRole('button', { name: 'Run comparison', exact: true })).toBeDisabled()); + await page.getByRole('button', { name: 'Reset inputs', exact: true }).click(); await evaluate(); - await go('hazop?hazard=unknown&node=invalid'); - await page.reload(); - await assertExecutiveDefault('hazop'); await selectTechnical(); - await expect(page.getByLabel('Agent node', { exact: true })).toHaveValue('all'); - await expect(page.locator('.register tbody tr')).toHaveCount(96); - assertions += 2; - await page.getByLabel('Search findings').fill('no-such-finding'); - await expect(page.getByText('No findings match.', { exact: false })).toBeVisible(); - await page.getByLabel('Search findings').fill(''); + await go('hazop?hazard=unknown&node=invalid'); await page.reload(); + await check(() => expect(page.getByLabel('Agent node', { exact: true })).toHaveValue('all')); + await check(() => expect(page.locator('.register tbody tr')).toHaveCount(96)); + await page.getByLabel('Search findings', { exact: true }).fill('no-such-finding'); + await check(() => expect(page.getByText(/No findings match/)).toBeVisible()); + await page.getByLabel('Search findings', { exact: true }).fill(''); await page.getByLabel('Agent node', { exact: true }).selectOption('supplier'); - await expect(page.locator('.register tbody tr')).toHaveCount(16); - await page.getByLabel('Guideword / deviation').selectOption('AUTHORITY_ESCALATION'); - await expect(page.locator('.register tbody tr')).toHaveCount(1); - await page.getByLabel('Sort findings').selectOption('deviation'); - await page.locator('.register button').click(); assertions += 4; - // Continuity: filtering, focus, sharing and exercise mapping retain one finding. - const selectedFinding = page.getByRole('heading', { name: 'AUTHORITY ESCALATION / supplier', exact: true }); - await check(() => expect(selectedFinding).toBeFocused()); - await check(() => expect(page.getByRole('region', { name: 'Finding exercise mapping', exact: true })).toContainText('Mapping: partial')); - const findingLink = await page.getByRole('link', { name: 'Link to this finding and filters', exact: true }).getAttribute('href'); - await check(() => assert.match(findingLink, /hazard=APS-ad4a560c0e8ea4fa1023/)); - await check(() => assert.match(findingLink, /node=supplier/)); - await page.getByRole('button', { name: 'Return to selected finding in register', exact: true }).click(); - await check(() => expect(page.locator('.register button[aria-pressed="true"]')).toBeFocused()); - await page.reload(); await assertExecutiveDefault('hazop'); await selectTechnical(); - await check(() => expect(page.getByLabel('Agent node', { exact: true })).toHaveValue('supplier')); - await check(() => expect(page.getByLabel('Guideword / deviation')).toHaveValue('AUTHORITY_ESCALATION')); - await check(() => expect(selectedFinding).toBeVisible()); - await check(() => expect(page.getByRole('link', { name: 'Unauthorized supplier request →', exact: true })).toHaveAttribute('href', /story=unauthorized&hazard=APS-ad4a560c0e8ea4fa1023/)); + await check(() => expect(page.locator('.register tbody tr')).toHaveCount(16)); + await page.getByLabel('Guideword / deviation', { exact: true }).selectOption('AUTHORITY_ESCALATION'); + await check(() => expect(page.locator('.register tbody tr')).toHaveCount(1)); + await page.getByLabel('Sort findings', { exact: true }).selectOption('deviation'); + await page.locator('.register button').click(); + await check(() => expect(page.locator('#finding-detail a[href*="story=unauthorized"]')).toHaveCount(1)); await go('hazop?hazard=APS-00be5560043a77ba3ede'); - await check(() => expect(page.getByRole('region', { name: 'Finding exercise mapping', exact: true })).toContainText('No runnable request illustration is mapped')); - await check(() => expect(page.getByRole('region', { name: 'Finding exercise mapping', exact: true }).getByRole('link')).toHaveCount(0)); + await check(() => expect(page.getByText(/No interactive case for this finding\./)).toBeVisible()); - await go('governance'); - const stories = ['normal', 'unauthorized', 'spending', 'delegation', 'approval', 'replay', 'stale', 'conflict', 'context']; - for (const mode of ['A', 'B', 'C']) for (const story of stories) { - await page.getByLabel('Scenario', { exact: true }).selectOption(story); - await page.getByLabel('Governance mode').selectOption(mode); - await page.getByRole('button', { name: 'Reset decision' }).click(); - await page.getByRole('button', { name: 'Evaluate simulated request', exact: true }).click(); - const decision = mode === 'A' || story === 'normal' || (mode === 'B' && !['unauthorized', 'spending'].includes(story)) ? 'ALLOW' : story === 'conflict' ? 'REVIEW' : 'DENY'; - await expect(page.locator('.event').first()).toContainText(decision); - if (decision === 'REVIEW') { - await page.getByRole('button', { name: 'Deny simulated request', exact: true }).click(); - await expect(page.locator('.event').last()).toContainText('DENY'); - await page.getByRole('button', { name: 'Reset decision' }).click(); - await page.getByRole('button', { name: 'Evaluate simulated request', exact: true }).click(); - await page.getByRole('button', { name: 'Approve simulated request', exact: true }).click(); - await expect(page.locator('.event').last()).toContainText('ALLOW'); - } - assertions++; - } - // Resolve every internal contextual link from the control plane. - await page.getByLabel('Scenario', { exact: true }).selectOption('unauthorized'); - await page.getByRole('button', { name: 'Evaluate simulated request', exact: true }).click(); - await page.getByText('Inspect ordered browser policy checks', { exact: true }).click(); - const policyRows = page.getByRole('table', { name: 'Rules for this simulated gateway attempt' }).locator('tbody tr'); - await expect(policyRows).toHaveCount(9); - await expect(policyRows.first()).toContainText('fail'); - await expect(policyRows.last()).toContainText('skipped'); - assertions += 3; + await go('governance?control=CTL-EXPIRY'); + await check(() => expect(page.getByLabel('Inspect control', { exact: true })).toHaveValue('CTL-EXPIRY')); + await check(() => expect(page.getByRole('button', { name: 'Run comparison', exact: true })).toHaveCount(0)); const links = await page.locator('main a[href^="#/"]').evaluateAll(as => as.map(a => a.getAttribute('href'))); - for (const link of new Set(links)) { await go(link.slice(2)); assertions++; } + for (const link of new Set(links)) await go(link.slice(2)); - await go('simulator'); - const policyWorkflow = await populatePausedWorkflow(); - const legacy = page.locator('details.legacy-policy'); - await check(() => expect(legacy.locator(':scope > summary')).toHaveText('Separate single-request policy illustration')); - await legacy.locator(':scope > summary').click(); - await check(() => expect(legacy).toHaveAttribute('open', '')); - const policyStatus = legacy.getByRole('status', { name: 'Policy illustration status', exact: true }); - await check(() => expect(policyStatus).toHaveCount(1)); - await legacy.getByRole('button', { name: 'Reset', exact: true }).click(); - await legacy.getByRole('button', { name: 'Start', exact: true }).click(); - await legacy.getByRole('button', { name: 'Pause', exact: true }).click(); - const paused = await policyStatus.textContent(); - await page.waitForTimeout(850); - await check(async () => assert.equal(await policyStatus.textContent(), paused)); - await check(() => expect(policyStatus).toContainText('Paused')); - await assertGeneratedWorkflowUnchanged(policyWorkflow); - await legacy.getByLabel('Predefined fault').selectOption('context'); - await legacy.getByRole('button', { name: 'Inject selected fault', exact: true }).click(); - await check(() => expect(legacy.getByText('Queued override: Compromised shared context', { exact: true })).toBeVisible()); - await check(() => expect(legacy.getByText('Evaluated override: Compromised shared context', { exact: true })).toHaveCount(0)); - for (let i = 0; i < 3; i++) await legacy.getByRole('button', { name: 'Step', exact: true }).click(); - await check(() => expect(legacy.getByText('Evaluated override: Compromised shared context', { exact: true })).toBeVisible()); - await check(() => expect(legacy.getByText('Queued override: Compromised shared context', { exact: true })).toHaveCount(0)); - await check(() => expect(legacy.locator('.event')).toHaveCount(1)); - await check(() => expect(legacy.locator('.event')).toContainText('DENY')); - await check(() => expect(legacy.locator('.event')).toContainText('Operation not executed')); - await check(() => expect(stat('Blocked decisions', legacy)).toHaveText('1')); - await check(() => expect(stat('Unsafe attempts', legacy)).toHaveText('1')); - await check(() => expect(stat('Unsafe executed', legacy)).toHaveText('0')); - await assertGeneratedWorkflowUnchanged(policyWorkflow); - await legacy.getByRole('button', { name: 'Reset', exact: true }).click(); - await check(() => expect(stat('Blocked decisions', legacy)).toHaveText('0')); - await check(() => expect(legacy.locator('.event')).toHaveCount(0)); - await check(() => expect(legacy.getByText('No fault override queued', { exact: true })).toBeVisible()); - await check(() => expect(policyStatus).toContainText('tick 0')); - await legacy.getByLabel('Deterministic seed').fill('-10'); - await check(() => expect(legacy.getByLabel('Deterministic seed')).toHaveValue('0')); - await legacy.getByLabel('Governance mode').selectOption('A'); - await check(() => expect(legacy.getByLabel('Governance mode')).toHaveValue('A')); - await check(() => expect(policyStatus).toContainText('tick 0')); - await assertGeneratedWorkflowUnchanged(policyWorkflow); + await go('assurance?trial=15'); + const pair = page.locator('.recorded-pair-table'); + await check(() => expect(pair.locator('tbody tr')).toHaveCount(10)); + await check(() => expect(pair.locator('tbody tr').last()).toContainText('expired_finance_approval')); + await check(() => expect(pair.locator('tbody tr').last().locator('td').nth(0)).toContainText('ALLOW · executed')); + await check(() => expect(pair.locator('tbody tr').last().locator('td').nth(1)).toContainText('DENY · not executed')); + await page.getByRole('button', { name: 'Replay next recorded call', exact: true }).click(); + await check(() => expect(page.locator('.replay-list li')).toHaveCount(1)); + await page.getByRole('button', { name: 'Show all recorded calls', exact: true }).click(); + await check(() => expect(page.locator('.replay-list li')).toHaveCount(10)); + await page.getByRole('button', { name: 'Restart replay', exact: true }).click(); + await check(() => expect(page.locator('.replay-list li')).toHaveCount(0)); + await page.getByLabel('Filter recorded arm', { exact: true }).selectOption('C'); + await check(() => expect(page.locator('.register tbody tr')).toHaveCount(10)); + await page.getByLabel('Sort recorded trials', { exact: true }).selectOption('fault'); + await check(() => expect(page.locator('.recharts-bar-rectangle').first()).toBeVisible()); + assert.ok(await page.locator('.recharts-bar-rectangle path').evaluateAll(paths => paths.some(path => path.getBoundingClientRect().height > 0)), 'Charts must draw visible bars, not just populated data tables'); assertions++; + await go('assurance?trial=17'); + await check(() => expect(page.getByText(/differs from the active browser case/)).toBeVisible()); + await check(() => expect(page.getByRole('heading', { name: /Recorded trial #17/ })).toBeVisible()); + await go('assurance?trial=unknown'); + await check(() => expect(page.getByText(/No recorded trial matches/)).toBeVisible()); + await check(() => expect(page.getByRole('button', { name: 'Replay next recorded call', exact: true })).toHaveCount(0)); - await go('assurance'); - await page.getByLabel('Filter recorded arm').selectOption('C'); - await expect(page.locator('.register tbody tr')).toHaveCount(10); - await page.getByLabel('Sort recorded trials').selectOption('fault'); - await page.locator('.register button').first().click(); - await page.getByRole('button', { name: 'Replay next recorded call' }).click(); - await expect(page.locator('.replay-list li')).toHaveCount(1); - await page.getByRole('button', { name: 'Restart replay' }).click(); - await expect(page.locator('.replay-list li')).toHaveCount(0); assertions += 3; - // Audience learning journey: computed comparison is isolated from the active run. - await freshExecutive('overview'); - await page.getByRole('button', { name: 'Control the commitment', exact: true }).click(); - await check(() => expect(page.locator('.learning-story')).toContainText('modeled control can stop an expired approval')); - await clickNavigation('How controls work'); - await page.getByLabel('Question to examine', { exact: true }).selectOption('approval-delay'); - await page.getByRole('button', { name: 'Prepare example', exact: true }).click(); - const untouchedStatus = await workflowStatus.innerText(); - await page.getByRole('button', { name: 'Run matched comparison', exact: true }).click(); - const comparison = page.getByRole('region', { name: 'Matched workflow comparison', exact: true }); - await check(() => expect(comparison.getByRole('table').locator('tbody tr')).toHaveCount(3)); - await check(() => expect(comparison.getByRole('table').locator('tbody tr').last()).toContainText('Fresh approval needed')); - await check(() => expect(workflowStatus).toHaveText(untouchedStatus)); - await clickNavigation('What leaders decide'); - const brief = page.getByRole('region', { name: 'Leadership decision brief', exact: true }); - await brief.getByLabel('Proposed accountable role').fill('Procurement process owner'); - await check(() => expect(brief).toContainText('confirmation not established')); - await check(() => expect(brief).toContainText('No person is assigned or approval issued')); - await check(() => expect(brief.getByRole('button', { name: 'Print leadership brief' })).toBeVisible()); - await page.emulateMedia({ media: 'print' }); - await check(() => expect(brief.locator('.brief-print')).toContainText('Procurement process owner')); - await check(() => expect(brief.getByRole('button', { name: 'Print leadership brief' })).toBeHidden()); - await page.emulateMedia({ media: 'screen' }); - // A saved brief is a portable discussion snapshot, never operational authority. - await brief.getByLabel('Proposed next decision').fill('Review a bounded purchasing integration trial.'); - await brief.getByLabel('Evidence needed before that decision').fill('Test expiry, duplicate prevention and lost-response reconciliation.'); - await check(() => expect(brief.getByRole('status', { name: 'Brief save status', exact: true })).toContainText('Unsaved changes')); - await clickNavigation('How controls work'); await clickNavigation('What leaders decide'); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('Procurement process owner')); - await selectTechnical(); await page.getByRole('radio', { name: 'Executive', exact: true }).check(); - await check(() => expect(brief.getByLabel('Proposed next decision')).toHaveValue('Review a bounded purchasing integration trial.')); - await brief.getByText('Export or import a decision brief', { exact: true }).click(); - await brief.getByRole('button', { name: 'Prepare brief JSON', exact: true }).click(); - const preparedBriefText = await brief.getByRole('textbox', { name: 'Prepared brief JSON', exact: true }).inputValue(); - const preparedBrief = JSON.parse(preparedBriefText); - await check(() => assert.equal(preparedBrief.status, 'discussion-draft')); - await check(() => assert.equal(preparedBrief.simulationOnly, true)); - await check(() => assert.equal(preparedBrief.notes.owner, 'Procurement process owner')); - await check(() => assert.ok(preparedBrief.snapshot.runId && preparedBrief.snapshot.observationId)); - const briefDownload = page.waitForEvent('download'); - await brief.getByRole('button', { name: 'Download decision brief', exact: true }).click(); - const downloadedBrief = await briefDownload; - await check(() => assert.equal(downloadedBrief.suggestedFilename(), 'aps-decision-brief.json')); - await check(async () => assert.deepEqual(JSON.parse(await readFile(await downloadedBrief.path(), 'utf8')), preparedBrief)); - await brief.getByRole('button', { name: 'Save brief locally', exact: true }).click(); - await check(() => expect(brief.getByRole('status', { name: 'Brief save status', exact: true })).toHaveText('Saved in this browser.')); - await page.reload(); await assertExecutiveDefault('assurance'); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('Procurement process owner')); - await check(() => expect(brief.getByRole('status', { name: 'Brief observation status', exact: true })).toContainText('The run has changed')); - await brief.getByText('Export or import a decision brief', { exact: true }).click(); - await brief.getByRole('button', { name: 'Prepare brief JSON', exact: true }).click(); - await check(async () => assert.deepEqual(JSON.parse(await brief.getByRole('textbox', { name: 'Prepared brief JSON', exact: true }).inputValue()), preparedBrief)); - await brief.getByRole('textbox', { name: 'Brief JSON to import', exact: true }).fill('{'); - await brief.getByRole('button', { name: 'Preview brief import', exact: true }).click(); - await check(() => expect(brief.getByRole('status', { name: 'Brief action status', exact: true })).toContainText('Current draft and saved copy retained')); - await check(() => expect(brief.getByRole('region', { name: 'Brief import preview', exact: true })).toHaveCount(0)); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('Procurement process owner')); - await brief.getByRole('textbox', { name: 'Brief JSON to import', exact: true }).fill(JSON.stringify({ ...preparedBrief, notes: { ...preparedBrief.notes, owner: 'Imported review role' } })); - await brief.getByRole('button', { name: 'Preview brief import', exact: true }).click(); - await check(() => expect(brief.getByRole('region', { name: 'Brief import preview', exact: true })).toContainText('Imported review role')); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('Procurement process owner')); - await page.emulateMedia({ media: 'print' }); - await check(() => expect(brief.getByRole('region', { name: 'Brief import preview', exact: true })).toBeHidden()); - await check(() => expect(brief.getByRole('textbox', { name: 'Prepared brief JSON', exact: true })).toBeHidden()); - await check(() => expect(brief.locator('.brief-print')).toContainText(preparedBrief.snapshot.runId)); - await check(() => expect(brief.locator('.brief-print')).toContainText(preparedBrief.snapshot.sourceBaseline)); - await check(() => expect(brief.locator('.brief-print')).toContainText(preparedBrief.snapshot.modelVersion)); - await check(() => expect(brief.locator('.brief-print')).toContainText('Procurement process owner')); - await check(() => expect(brief.locator('.brief-print')).not.toContainText('Imported review role')); - await page.emulateMedia({ media: 'screen' }); - await brief.getByRole('button', { name: 'Replace working brief with import', exact: true }).click(); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('Imported review role')); - await check(() => expect(brief).toContainText('Restored or imported discussion data is unverified')); - await clickNavigation('How controls work'); - await check(() => expect(workflowStatus).toContainText('0 transitions')); - await check(() => expect(operations).toContainText('Nominal procurement')); - await clickNavigation('What leaders decide'); - await brief.getByRole('button', { name: 'Discard brief…', exact: true }).click(); - await brief.getByRole('button', { name: 'Keep brief', exact: true }).click(); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('Imported review role')); - await brief.getByRole('button', { name: 'Discard brief…', exact: true }).click(); - await brief.getByRole('button', { name: 'Discard working and saved brief', exact: true }).click(); - await page.reload(); await assertExecutiveDefault('assurance'); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('')); - // A second tab's saved draft cannot be silently overwritten by stale edits. - await brief.getByLabel('Proposed accountable role').fill('First tab role'); - await brief.getByRole('button', { name: 'Save brief locally', exact: true }).click(); - const peer = await context.newPage(); - peer.on('pageerror', error => errors.push(error.message)); - peer.on('console', message => { if (message.type() === 'error') errors.push(message.text()); }); - await peer.goto(`${origin}${prefix}#/assurance`); - const peerBrief = peer.getByRole('region', { name: 'Leadership decision brief', exact: true }); - await check(() => expect(peerBrief.getByLabel('Proposed accountable role')).toHaveValue('First tab role')); - await peerBrief.getByLabel('Proposed accountable role').fill('Second tab role'); - await peerBrief.getByRole('button', { name: 'Save brief locally', exact: true }).click(); - await check(() => expect(brief.getByRole('status', { name: 'Brief action status', exact: true })).toContainText('changed in another tab')); - await brief.getByLabel('Proposed accountable role').fill('First tab unsaved edits'); - await brief.getByRole('button', { name: 'Save brief locally', exact: true }).click(); - await check(() => expect(brief.getByRole('status', { name: 'Brief action status', exact: true })).toContainText('Save or discard was stopped')); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('First tab unsaved edits')); - await peer.reload(); - await check(() => expect(peerBrief.getByLabel('Proposed accountable role')).toHaveValue('Second tab role')); - await peer.close(); - await brief.getByRole('button', { name: 'Preview saved browser copy', exact: true }).click(); - await check(() => expect(brief.getByRole('region', { name: 'Brief import preview', exact: true })).toContainText('Second tab role')); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('First tab unsaved edits')); - await brief.getByRole('button', { name: 'Replace working brief with import', exact: true }).click(); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('Second tab role')); - await brief.getByRole('button', { name: 'Discard brief…', exact: true }).click(); - await brief.getByRole('button', { name: 'Discard working and saved brief', exact: true }).click(); - await page.reload(); await assertExecutiveDefault('assurance'); - await check(() => expect(brief.getByLabel('Proposed accountable role')).toHaveValue('')); - // Every workflow review stays with its selected question. Advancing stops at - // actual engine boundaries and cannot silently recover or reconcile. - const reviewHeadings = { - nominal: 'What establishes an acceptable purchasing outcome?', - 'approval-delay': 'Can commitment occur after permission expires?', - 'purchase-race': 'Can two proposals create two commitments for one need?', - 'lost-purchase-response': 'How should an uncertain purchase outcome be resolved?', - }; - for (const [scenario, heading] of Object.entries(reviewHeadings)) { - await freshExecutive('simulator'); - await page.getByLabel('Question to examine', { exact: true }).selectOption(scenario); - await page.getByRole('button', { name: 'Prepare example', exact: true }).click(); - await check(() => expect(workflowStatus).toContainText('0 transitions')); - await operations.getByRole('button', { name: 'Review operation design', exact: true }).click(); - await check(() => expect(designReview.getByRole('heading', { name: heading, exact: true })).toBeVisible()); - if (scenario !== 'approval-delay') await check(() => expect(designReview).not.toContainText('Related timing finding—different object/coverage')); - await page.getByRole('button', { name: 'Return to the business case', exact: true }).click(); - await page.getByRole('button', { name: 'Advance to next decision', exact: true }).click(); - await check(() => expect(page.getByRole('button', { name: 'Advance to next decision', exact: true })).toBeDisabled()); - if (scenario === 'approval-delay') { - await check(() => expect(page.getByRole('button', { name: 'Request one approval refresh', exact: true })).toBeVisible()); - await check(() => expect(operations.getByRole('button', { name: /^Open order / })).toHaveCount(0)); - } else if (scenario === 'lost-purchase-response') { - await check(() => expect(page.getByRole('button', { name: 'Reconcile existing order once', exact: true })).toBeVisible()); - await check(() => expect(operations.getByRole('button', { name: /^Open order / })).toHaveCount(1)); - await check(() => expect(operations).toContainText('An order is recorded; the reply is missing.')); - } else await check(() => expect(operations).toContainText("The purchase is confirmed within the model's checks.")); - } - await go('overview'); - await check(() => expect(page.getByRole('region', { name: 'Technical orientation' })).toContainText('Three models. Three different kinds of evidence.')); - await go('hazop'); - await check(() => expect(page.getByRole('region', { name: 'Worked hazard to control example' })).toContainText('Direct source finding')); - await go('assurance'); - await check(() => expect(page.getByRole('region', { name: 'Evidence claims and reproduction' })).toContainText('aggregate counts alone')); + // Viewport/theme matrix covers all screens, including a completed comparison. for (const width of [375, 768, 1440]) for (const theme of ['light', 'dark']) { await page.setViewportSize({ width, height: 950 }); await page.getByLabel('Theme', { exact: true }).selectOption(theme); for (const route of ['overview', 'hazop', 'governance', 'simulator', 'assurance']) { await go(route); - assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), `${route} ${width} ${theme}: horizontal overflow`); - assertions++; + if (route === 'simulator') { await page.getByRole('button', { name: 'Reset inputs', exact: true }).click(); await evaluate(); } + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), route + ' ' + width + ' ' + theme + ': horizontal overflow'); assertions++; } - if (width === 375) await page.screenshot({ path: resolve(screenshots, `mobile-${theme}.jpg`), quality: 65 }); + if (width === 375) await page.screenshot({ path: resolve(screenshots, 'mobile-' + theme + '.jpg'), quality: 65 }); } - await page.reload(); await assertExecutiveDefault('assurance'); await selectTechnical(); await expect(page.getByLabel('Theme', { exact: true })).toHaveValue('dark'); - await page.keyboard.press('Tab'); - assert.ok(await page.evaluate(() => document.activeElement !== document.body)); + await page.reload(); await check(() => expect(page.getByLabel('Theme', { exact: true })).toHaveValue('dark')); + await go('simulator?story=stale'); + const age = page.getByLabel('Approval age (logical seconds)', { exact: true }); + await age.focus(); await page.keyboard.press('ControlOrMeta+A'); await page.keyboard.type('59'); + await check(() => expect(age).toHaveValue('59')); + await page.getByRole('button', { name: 'Run comparison', exact: true }).focus(); await page.keyboard.press('Enter'); + await check(() => expect(page.getByRole('heading', { name: 'Comparison results', exact: true })).toBeFocused()); assert.deepEqual(errors, [], 'Browser errors'); assert.deepEqual(violations, [], 'Runtime network contract'); await mkdir('.harness/ci-qa', { recursive: true }); await writeFile('.harness/ci-qa/browser-result.json', JSON.stringify({ status: 'passed', engine, version: browser.version(), platform: process.platform, - assertions, errors, violations, prefix, - screenshots: ['overview', 'hazop', 'governance', 'simulator', 'assurance', 'mobile-light', 'mobile-dark'].map(name => `docs/screenshots/${name}.jpg`), + assertions, errors, violations, prefix, experience: 'APS redesign increments 1–4', + screenshots: ['overview', 'hazop', 'governance', 'simulator', 'assurance', 'mobile-light', 'mobile-dark'].map(name => 'docs/screenshots/' + name + '.jpg'), }, null, 2) + '\n'); - console.log(`Built-site browser QA passed: ${assertions} checks; nine stories × three modes; direct hash refresh, explicit restart consent, legacy/workflow isolation, controls, responsive themes; no console/page errors or nonstatic requests. Screenshots: docs/screenshots/*.jpg`); + console.log('Built-site browser QA passed: ' + assertions + ' checks; paired nine-case comparisons, age boundaries, retained history, reasoning/recovery/export, deep links, frozen evidence, responsive themes and keyboard operation; no console/page errors or nonstatic requests.'); } finally { await browser?.close(); await new Promise(r => server.close(r)); diff --git a/apps/aps-demo/scripts/production.mjs b/apps/aps-demo/scripts/production.mjs index 42fdc2c..988cfbb 100644 --- a/apps/aps-demo/scripts/production.mjs +++ b/apps/aps-demo/scripts/production.mjs @@ -1,35 +1,93 @@ -import { readFileSync, readdirSync } from 'node:fs'; +import { readFileSync, readdirSync, lstatSync } from 'node:fs'; import { createHash } from 'node:crypto'; import assert from 'node:assert/strict'; import { fileURLToPath } from 'node:url'; -import { resolve, relative } from 'node:path'; +import { resolve, relative, sep } from 'node:path'; const root = fileURLToPath(new URL('../../../', import.meta.url)); -const read = (p) => readFileSync(resolve(root, p)); -const inspection = JSON.parse(read('docs/STATIC_DEMO_INSPECTION.json')); -const digest = '3577671495d2080cef3db985b3d30b3735750e2de894e481a6c0f52e70e24497'; -assert.equal(inspection.production_digest, digest); -const sha = (v) => createHash('sha256').update(v).digest('hex'); -for (const [path, expected] of Object.entries(inspection.production_files)) { - assert.equal(sha(read(path)), expected, `Protected bytes changed: ${path}`); -} +const baselineDigest = '3577671495d2080cef3db985b3d30b3735750e2de894e481a6c0f52e70e24497'; +const additionsDigest = 'be807d0c0945152dbbd1adeffda79c49c17eab3f8257cab7ced4fdc6052c7fdf'; const trees = ['packages/engine', 'packages/governance', 'packages/simulator', 'policies', 'schemas', 'tests']; -function walk(path) { - for (const item of readdirSync(path, { withFileTypes: true })) { - if (item.name === '__pycache__' || item.name.endsWith('.egg-info')) continue; - const p = resolve(path, item.name); - if (item.isDirectory()) walk(p); - else assert.ok(Object.hasOwn(inspection.production_files, relative(root, p)), `Added protected file: ${relative(root, p)}`); - } -} -trees.forEach((p) => walk(resolve(root, p))); -const scripts = JSON.parse(read('package.json')).scripts; -const original = { +const sha = (v) => createHash('sha256').update(v).digest('hex'); +const originalScripts = { demo: 'node --experimental-strip-types packages/simulator/src/simulate.ts', test: 'node --experimental-strip-types --test packages/simulator/src/simulate.test.ts', typecheck: 'tsc --noEmit', 'governance:demo': 'PYTHONPATH=packages/engine:packages/governance .venv/bin/python -m aps_governance.demo --audit-dir artifacts/phase2', 'governance:simulate': 'PYTHONPATH=packages/engine:packages/governance .venv/bin/python -m aps_governance.cli simulate-policy --bundle policies/v1 --cases policies/v1/cases.json --out artifacts/phase2/policy-simulation.json', }; -for (const [k, v] of Object.entries(original)) assert.equal(scripts[k], v, `Original script changed: ${k}`); -console.log(`Production boundary: ${Object.keys(inspection.production_files).length} files match pinned mapping ${digest}; original scripts preserved.`); + +export function verifyProductionBoundary(repositoryRoot = root) { + const base = resolve(repositoryRoot); + // Do not permit symlink substitution of a protected file or an ancestor. + const checkedPath = (path) => { + assert.equal(typeof path, 'string', 'Protected path must be a string'); + const parts = path.split('/'); + assert.ok(parts.length && parts.every(part => part && part !== '.' && part !== '..' && !part.includes('\\')), `Invalid protected path: ${path}`); + let current = base; + for (const [index, part] of parts.entries()) { + current = resolve(current, part); + const stat = lstatSync(current); + assert.ok(!stat.isSymbolicLink(), `Protected symlink: ${path}`); + if (index < parts.length - 1) assert.ok(stat.isDirectory(), `Protected parent is not a directory: ${path}`); + } + return current; + }; + const read = (path) => { + const full = checkedPath(path); + assert.ok(lstatSync(full).isFile(), `Protected path is not a regular file: ${path}`); + return readFileSync(full); + }; + const inspection = JSON.parse(read('docs/STATIC_DEMO_INSPECTION.json')); + assert.equal(inspection.production_digest, baselineDigest, 'Original production digest changed'); + // Validate the mapping itself, not only its self-reported digest field. + const baseline = inspection.production_files; + assert.ok(baseline && typeof baseline === 'object' && !Array.isArray(baseline), 'Invalid original production mapping'); + const canonicalBaseline = Object.fromEntries(Object.entries(baseline).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)); + assert.equal(sha(JSON.stringify(canonicalBaseline)), baselineDigest, 'Original production mapping changed'); + + // This separately pinned extension adds exact tests; it cannot override any + // original pin, authorize future additions, or change pilot approval status. + const additionsBytes = read('docs/STATIC_DEMO_PRODUCTION_ADDITIONS.json'); + assert.equal(sha(additionsBytes), additionsDigest, 'Production additions manifest changed'); + const additions = JSON.parse(additionsBytes); + assert.equal(additions.schema_version, 1); + assert.equal(additions.baseline_production_digest, baselineDigest); + const expected = { ...baseline }; + for (const [path, entry] of Object.entries(additions.files)) { + assert.ok(!Object.hasOwn(baseline, path), `Addition overlaps original protected file: ${path}`); + assert.ok(trees.some(tree => path.startsWith(tree + '/')), `Addition outside protected trees: ${path}`); + assert.match(entry.sha256, /^[a-f0-9]{64}$/); + expected[path] = entry.sha256; + } + for (const [path, digest] of Object.entries(expected)) { + assert.equal(sha(read(path)), digest, `Protected bytes changed: ${path}`); + } + + function walk(path) { + assert.ok(lstatSync(path).isDirectory(), `Protected tree is not a directory: ${path}`); + for (const item of readdirSync(path, { withFileTypes: true })) { + const full = resolve(path, item.name); + const key = relative(base, full).split(sep).join('/'); + assert.ok(!item.isSymbolicLink(), `Protected symlink: ${key}`); + // Preserve the original generated-directory exceptions, never file or + // symlink exceptions disguised with those names. + if (item.isDirectory()) { + if (item.name === '__pycache__' || item.name.endsWith('.egg-info')) continue; + walk(full); + } else { + assert.ok(item.isFile(), `Protected path is not a regular file: ${key}`); + assert.ok(Object.hasOwn(expected, key), `Added protected file: ${key}`); + } + } + } + trees.forEach(path => walk(checkedPath(path))); + const scripts = JSON.parse(read('package.json')).scripts; + for (const [key, value] of Object.entries(originalScripts)) assert.equal(scripts[key], value, `Original script changed: ${key}`); + return { baselineFiles: Object.keys(baseline).length, addedFiles: Object.keys(additions.files).length, baselineDigest, additionsDigest }; +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const result = verifyProductionBoundary(); + console.log(`Production boundary: ${result.baselineFiles} original files match pinned mapping ${result.baselineDigest}; ${result.addedFiles} exact test additions match pinned extension ${result.additionsDigest}; original scripts preserved.`); +} diff --git a/apps/aps-demo/scripts/production.test.mjs b/apps/aps-demo/scripts/production.test.mjs new file mode 100644 index 0000000..cdf34d5 --- /dev/null +++ b/apps/aps-demo/scripts/production.test.mjs @@ -0,0 +1,146 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, copyFileSync, rmSync, symlinkSync, renameSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createHash } from 'node:crypto'; +import { verifyProductionBoundary } from './production.mjs'; + +const source = fileURLToPath(new URL('../../../', import.meta.url)); +const inspectionPath = 'docs/STATIC_DEMO_INSPECTION.json'; +const additionsPath = 'docs/STATIC_DEMO_PRODUCTION_ADDITIONS.json'; +const inspection = JSON.parse(readFileSync(resolve(source, inspectionPath))); +const additions = JSON.parse(readFileSync(resolve(source, additionsPath))); +const baselineFile = 'packages/governance/aps_governance/gateway.py'; +const addedFiles = Object.keys(additions.files); +const sha = value => createHash('sha256').update(value).digest('hex'); + +function fixture(t) { + const root = mkdtempSync(resolve(tmpdir(), 'aps-production-boundary-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + for (const path of [...Object.keys(inspection.production_files), ...addedFiles, inspectionPath, additionsPath, 'package.json']) { + mkdirSync(dirname(resolve(root, path)), { recursive: true }); + copyFileSync(resolve(source, path), resolve(root, path)); + } + return root; +} +function editJSON(root, path, change) { + const full = resolve(root, path); + const value = JSON.parse(readFileSync(full)); + change(value); + writeFileSync(full, JSON.stringify(value, null, 2) + '\n'); +} + +test('accepts the preserved original baseline and exact three test additions', t => { + const result = verifyProductionBoundary(fixture(t)); + assert.equal(result.baselineFiles, 70); + assert.equal(result.addedFiles, 3); +}); + +for (const path of [baselineFile, ...addedFiles]) { + test(`rejects changed protected bytes: ${path}`, t => { + const root = fixture(t); + writeFileSync(resolve(root, path), 'replacement'); + assert.throws(() => verifyProductionBoundary(root), /Protected bytes changed/); + }); + test(`rejects a missing protected file: ${path}`, t => { + const root = fixture(t); + rmSync(resolve(root, path)); + assert.throws(() => verifyProductionBoundary(root), /ENOENT/); + }); +} + +test('rejects an unrecognized addition even when it is an extra test', t => { + const root = fixture(t); + writeFileSync(resolve(root, 'tests/test_unreviewed.py'), '# additional test'); + assert.throws(() => verifyProductionBoundary(root), /Added protected file: tests\/test_unreviewed.py/); +}); + +test('rejects editing baseline file and expected hash while retaining its claimed digest', t => { + const root = fixture(t); + writeFileSync(resolve(root, baselineFile), 'replacement'); + editJSON(root, inspectionPath, value => { value.production_files[baselineFile] = sha('replacement'); }); + assert.throws(() => verifyProductionBoundary(root), /Original production mapping changed/); +}); + +test('rejects deleting a baseline mapping entry and its file', t => { + const root = fixture(t); + rmSync(resolve(root, baselineFile)); + editJSON(root, inspectionPath, value => { delete value.production_files[baselineFile]; }); + assert.throws(() => verifyProductionBoundary(root), /Original production mapping changed/); +}); + +test('rejects changing the original reported digest', t => { + const root = fixture(t); + editJSON(root, inspectionPath, value => { value.production_digest = '0'.repeat(64); }); + assert.throws(() => verifyProductionBoundary(root), /Original production digest changed/); +}); + +test('rejects editing an added file and its expected hash together', t => { + const root = fixture(t); + writeFileSync(resolve(root, addedFiles[0]), 'replacement'); + editJSON(root, additionsPath, value => { value.files[addedFiles[0]].sha256 = sha('replacement'); }); + assert.throws(() => verifyProductionBoundary(root), /Production additions manifest changed/); +}); + +test('rejects extending the additions manifest to admit another file', t => { + const root = fixture(t); + writeFileSync(resolve(root, 'tests/test_unreviewed.py'), '# extra'); + editJSON(root, additionsPath, value => { value.files['tests/test_unreviewed.py'] = { sha256: sha('# extra') }; }); + assert.throws(() => verifyProductionBoundary(root), /Production additions manifest changed/); +}); + +test('rejects an additions manifest that overlaps the baseline', t => { + const root = fixture(t); + editJSON(root, additionsPath, value => { value.files[baselineFile] = { sha256: inspection.production_files[baselineFile] }; }); + assert.throws(() => verifyProductionBoundary(root), /Production additions manifest changed/); +}); + +test('rejects even approval metadata changes to the pinned additions manifest', t => { + const root = fixture(t); + editJSON(root, additionsPath, value => { value.files[addedFiles[0]].approval_status = 'approved'; }); + assert.throws(() => verifyProductionBoundary(root), /Production additions manifest changed/); +}); + +test('rejects a missing additions manifest', t => { + const root = fixture(t); + rmSync(resolve(root, additionsPath)); + assert.throws(() => verifyProductionBoundary(root), /ENOENT/); +}); + +for (const path of [baselineFile, addedFiles[0], additionsPath]) { + test(`rejects symlink substitution with identical bytes: ${path}`, t => { + const root = fixture(t); + const full = resolve(root, path); + renameSync(full, full + '.retained'); + symlinkSync(full + '.retained', full); + assert.throws(() => verifyProductionBoundary(root), /Protected symlink/); + }); +} + +test('rejects a protected tree replaced with a symlink', t => { + const root = fixture(t); + renameSync(resolve(root, 'tests'), resolve(root, 'retained-tests')); + symlinkSync(resolve(root, 'retained-tests'), resolve(root, 'tests')); + assert.throws(() => verifyProductionBoundary(root), /Protected symlink/); +}); + +test('rejects an unknown symlink disguised as a generated cache directory', t => { + const root = fixture(t); + symlinkSync(resolve(root, 'docs'), resolve(root, 'tests/__pycache__')); + assert.throws(() => verifyProductionBoundary(root), /Protected symlink/); +}); + +test('preserves exclusions for ordinary generated Python cache directories', t => { + const root = fixture(t); + mkdirSync(resolve(root, 'tests/__pycache__')); + writeFileSync(resolve(root, 'tests/__pycache__/generated.pyc'), 'generated'); + assert.equal(verifyProductionBoundary(root).baselineFiles, 70); +}); + +test('rejects changing an original root script', t => { + const root = fixture(t); + editJSON(root, 'package.json', value => { value.scripts['governance:demo'] = 'true'; }); + assert.throws(() => verifyProductionBoundary(root), /Original script changed: governance:demo/); +}); diff --git a/apps/aps-demo/scripts/test.mjs b/apps/aps-demo/scripts/test.mjs index 203e220..088e128 100644 --- a/apps/aps-demo/scripts/test.mjs +++ b/apps/aps-demo/scripts/test.mjs @@ -11,7 +11,8 @@ const temp = resolve(app, '../../.harness/demo-test-tmp'); mkdirSync(temp, { recursive: true }); const require = createRequire(import.meta.url); const vitest = resolve(dirname(require.resolve('vitest/package.json')), 'vitest.mjs'); -const child = spawnSync(process.execPath, [vitest, 'run', ...process.argv.slice(2)], { +// This node:test suite is required separately by CI; Vitest must not collect it. +const child = spawnSync(process.execPath, [vitest, 'run', '--exclude', 'scripts/production.test.mjs', ...process.argv.slice(2)], { cwd: app, env: { ...process.env, TMPDIR: temp, TMP: temp, TEMP: temp }, stdio: 'inherit', diff --git a/apps/aps-demo/scripts/validation-evidence.mjs b/apps/aps-demo/scripts/validation-evidence.mjs index 9cbeadd..4b3aa23 100644 --- a/apps/aps-demo/scripts/validation-evidence.mjs +++ b/apps/aps-demo/scripts/validation-evidence.mjs @@ -9,6 +9,7 @@ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); const repository = 'safetymp/agentic-process-safety'; const workflow = '.github/workflows/repository-checks.yml'; +const releaseHeadRefs = Object.freeze(['release/aps-github-validation-v1', 'codex/aps-redesign-release']); const destination = '.harness/ci-qa/validation.json'; const hash = bytes => createHash('sha256').update(bytes).digest('hex'); const blob = bytes => createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex'); @@ -48,7 +49,7 @@ async function collect(phase) { assert.equal(env.GITHUB_EVENT_NAME, 'pull_request'); assert.equal(env.GITHUB_JOB, 'readiness'); const event = JSON.parse(await readFile(env.GITHUB_EVENT_PATH, 'utf8')); const pr = event.pull_request; const number = positive(String(event.number)); - assert.equal(pr.number, number); assert.equal(pr.base.ref, 'main'); assert.equal(pr.head.ref, 'release/aps-github-validation-v1'); + assert.equal(pr.number, number); assert.equal(pr.base.ref, 'main'); assert.ok(releaseHeadRefs.includes(pr.head.ref), 'Unreviewed release head ref'); for (const part of [pr.base, pr.head]) { assert.equal(normalize(part.repo.full_name), repository); assert.equal(part.repo.id, 1430231911); sha(part.sha); } diff --git a/apps/aps-demo/src/App.tsx b/apps/aps-demo/src/App.tsx index 84775dc..108e6ed 100644 --- a/apps/aps-demo/src/App.tsx +++ b/apps/aps-demo/src/App.tsx @@ -1,102 +1,88 @@ -import { useCallback, useEffect, useReducer, useState } from 'react'; -import { initialState, reducer } from './domain/simulation.ts'; -import { stories } from './domain/scenarios.ts'; +import { useEffect, useState } from 'react'; +import { SessionProvider, useSession } from './components/SessionContext.tsx'; +import { getCase } from './domain/cases.ts'; import { Overview } from './routes/Overview.tsx'; import { Hazop } from './routes/Hazop.tsx'; import { Governance } from './routes/Governance.tsx'; import { Simulator } from './routes/Simulator.tsx'; import { Assurance } from './routes/Assurance.tsx'; -import { controlRequirement, routeLink } from './data.ts'; -import { createWorkflow, exportWorkflow, importWorkflow, scenarioSpec, workflowReducer } from './workflow/index.ts'; -import type { WorkflowCommand } from './workflow/index.ts'; -import { newBriefIdentity } from './decisionBrief.ts'; -import { advanceToDecision } from './workflow/advance.ts'; -import { executiveIssues, issueForRoute, CaseStatus } from './components/ExecutiveCaseShell.tsx'; -import type { Selection } from './components/PurchasingOperations.tsx'; -import type { ReviewContext } from './components/HazopConversation.tsx'; -import { ExecutiveDiscussion, useExecutiveDiscussion } from './components/ExecutiveNarrative.tsx'; -import { MaterialRisk } from './components/ExecutiveCase.tsx'; -import { AudienceProvider, Executive, Technical, useAudience } from './components/AudienceView.tsx'; -import { WorkflowStage, WorkflowSummary } from './components/WorkflowStage.tsx'; -const sections = [{ id: 'overview', name: 'Overview', icon: '◈' }, { id: 'hazop', name: 'HAZOP Lab', icon: '⊞' }, { id: 'governance', name: 'Control Plane', icon: '◇' }, { id: 'simulator', name: 'Swarm Simulator', icon: '⇄' }, { id: 'assurance', name: 'Assurance', icon: '◉' }]; +const sections = [ + { id: 'overview', name: 'Start here', icon: '◈' }, + { id: 'simulator', name: 'Case Lab', icon: '⇄' }, + { id: 'hazop', name: 'Hazard study', icon: '⊞' }, + { id: 'governance', name: 'Controls', icon: '◇' }, + { id: 'assurance', name: 'Evidence', icon: '◉' }, +]; type Theme = 'system' | 'light' | 'dark'; function storedTheme(): Theme { - try { const t = localStorage.getItem('aps-theme'); return t === 'dark' || t === 'light' ? t : 'system'; } catch { return 'system'; } + try { + const value = localStorage.getItem('aps-theme'); + return value === 'dark' || value === 'light' ? value : 'system'; + } catch { return 'system'; } } function locationState() { const [path, query = ''] = window.location.hash.replace(/^#\/?/, '').split('?'); - return { route: sections.some(s => s.id === path) ? path : 'overview', params: new URLSearchParams(query) }; + return { route: sections.some(section => section.id === path) ? path : 'overview', params: new URLSearchParams(query) }; } -export function App() { return ; } -function AppContent() { - const { audience } = useAudience(); - const executive = audience === 'executive'; - const businessNames: Record = { overview: 'Why APS matters', simulator: 'How controls work', governance: 'How controls work', hazop: 'How controls work', assurance: 'What leaders decide' }; - const navigation = executive ? executiveIssues.map(issue => ({ ...issue, icon: sections.find(s => s.id === issue.id)!.icon })) : sections; + +function Workspace() { const [location, setLocation] = useState(locationState); const [theme, setTheme] = useState(storedTheme); - const [state, dispatch] = useReducer(reducer, undefined, () => initialState(42, 'C', 'unauthorized')); - const [workflow, setWorkflow] = useState(() => createWorkflow(scenarioSpec())); - const [runId, setRunId] = useState(newBriefIdentity); - const workflowCommand = useCallback((command: WorkflowCommand) => { - if (command.type === 'reset' || command.type === 'configure') { setRunId(newBriefIdentity()); setReviewContext(undefined); setCaseSelection(null); setRequestedInspection(null); } - setWorkflow(current => workflowReducer(current, command)); - }, []); + const { caseDefinition, selectedRun, isDirty, setCase, resetInputs, configError } = useSession(); + const currentSection = sections.find(section => section.id === location.route)!; useEffect(() => { - if (location.route !== 'simulator') setWorkflow(current => current.running ? workflowReducer(current, { type: 'pause' }) : current); - }, [location.route]); - const [reviewContext, setReviewContext] = useState(); - const [caseSelection, setCaseSelection] = useState(null); - const discussion = useExecutiveDiscussion(workflow, caseSelection, { persistent: true, runId }); - const [requestedInspection, setRequestedInspection] = useState(null); - const inspectionHandled = useCallback(() => setRequestedInspection(null), []); - const { reveal } = useAudience(); - function inspectFromPitch(id: string) { - if (!workflow.events.some(event => event.id === id)) return; - setRequestedInspection(id); reveal(); window.location.hash = '#/simulator'; - } - const [guide, setGuide] = useState(false); - const [guideStep, setGuideStep] = useState(0); - const [guideResetPending, setGuideResetPending] = useState(false); - useEffect(() => { - function changed() { const next = locationState(); setLocation(next); const story = stories.find(s => s.id === next.params.get('story')); if (story) dispatch({ type: 'configure', story: story.id }); } - changed(); window.addEventListener('hashchange', changed); return () => window.removeEventListener('hashchange', changed); + const changed = () => setLocation(locationState()); + window.addEventListener('hashchange', changed); + return () => window.removeEventListener('hashchange', changed); }, []); useEffect(() => { const media = window.matchMedia('(prefers-color-scheme: dark)'); const apply = () => { document.documentElement.dataset.theme = theme === 'system' ? media.matches ? 'dark' : 'light' : theme; }; - apply(); media.addEventListener('change', apply); try { localStorage.setItem('aps-theme', theme); } catch { /* Storage can be disabled; theme remains functional for this visit. */ } + apply(); + media.addEventListener('change', apply); + try { localStorage.setItem('aps-theme', theme); } catch { /* Theme works without storage. */ } return () => media.removeEventListener('change', apply); }, [theme]); - useEffect(() => { if (!state.running) return; const timer = window.setInterval(() => dispatch({ type: 'timer' }), 700); return () => window.clearInterval(timer); }, [state.running]); - useEffect(() => { document.title = `${executive ? businessNames[location.route] : sections.find(s => s.id === location.route)!.name} | Agentic Process Safety${location.route === 'overview' ? ' | HAZOP for AI Agent Swarms' : ''}`; }, [location.route, executive]); - useEffect(() => { document.querySelector('#main-content h1')?.focus(); }, [location.route]); - const effectiveStory = stories.find(s => s.id === (state.fault ?? state.story))!; - const lastDecision = state.events.at(-1); - const requirement = controlRequirement(effectiveStory.control); - const steps = [ - { title: 'Inspect the objective', text: effectiveStory.objective, link: routeLink('overview') }, - { title: 'Inspect the attempted operation', text: effectiveStory.operation, link: routeLink('governance') }, - { title: 'Inspect the proposed HAZOP mapping', text: 'Findings remain unverified; mappings do not establish control effectiveness.', link: requirement ? routeLink('hazop', 'hazard', requirement.hazard_id) : routeLink('hazop') }, - { title: lastDecision ? `Current SIMULATED decision: ${lastDecision.decision.toUpperCase()}` : 'Evaluate the SIMULATED request', text: lastDecision ? lastDecision.reason : 'No decision has been observed. Select Evaluate simulated request to inspect the current mode and request.', link: routeLink('governance') }, - { title: lastDecision ? 'Inspect the current SIMULATED outcome' : 'No SIMULATED outcome yet', text: lastDecision ? 'The current policy-illustration outcome appears first. Frozen experimental results are separate below.' : 'You advanced without evaluating. No blocked or executed outcome is claimed; return to the Control Plane to evaluate.', link: routeLink('assurance') }, - ]; - function walk(index: number) { - setGuide(true); setGuideStep(index); window.location.hash = steps[index].link; - } - function startGuide() { - dispatch({ type: 'reset' }); - dispatch({ type: 'configure', story: 'unauthorized', mode: 'C', seed: 42 }); - setGuideResetPending(false); walk(0); - } - function requestGuide() { - if (state.tick || state.running || state.pending || state.fault || state.events.length) setGuideResetPending(true); - else startGuide(); + useEffect(() => { + document.title = `${currentSection.name} | Agentic Process Safety`; + document.documentElement.scrollIntoView?.({ block: 'start' }); + document.getElementById('main-content')?.focus({ preventScroll: true }); + }, [currentSection.name]); + useEffect(() => { + if (location.route === 'simulator' && location.params.get('panel') === 'discussion') { + document.getElementById('discussion')?.scrollIntoView?.({ block: 'start' }); + document.getElementById('discussion')?.focus({ preventScroll: true }); + } + }, [location]); + function openCase() { + setCase('stale'); + resetInputs(); + window.location.hash = '/simulator'; } - return
{ e.preventDefault(); document.getElementById('main-content')?.focus(); }}>Skip to content -
{executive ? "Purchasing decision exercise" : "Research workspace"}/{executive ? businessNames[location.route] : sections.find(s => s.id === location.route)!.name}
SIMULATION ONLY · Orders are not deliveries · No operational authorityRecorded experimental resultsReplayed test evidenceIllustrative browser simulation
- {guideResetPending &&

Start a new policy walkthrough?

This clears the current single-request policy illustration and its decision history, then selects the unauthorized-tool example in mode C with seed 42. The separate workflow run and frozen evidence are unaffected.

} - {guide &&
WALKTHROUGH / {guideStep + 1} OF {steps.length}{steps[guideStep].title}

{steps[guideStep].text}

} -
{location.route === 'overview' ? <>{workflow.transitionCount > 0 && } : location.route === 'hazop' ? : location.route === 'governance' ? : location.route === 'simulator' ? <>
Separate single-request policy illustration

This original three-stage illustration shares state with the Control Plane. It does not execute the six-agent workflow above.

: <>}
APS Research Demonstration All hazards unverified · Browser decisions are SIMULATED · No safety certification
; + return
+ { event.preventDefault(); document.getElementById('main-content')?.focus(); }}>Skip to content + +
+
Research workspace/{currentSection.name}
+ {(location.route !== 'overview' || selectedRun) &&
+
ILLUSTRATIVE WORKSPACE{caseDefinition.title}

{selectedRun ? `Selected ${selectedRun.id} · ${getCase(selectedRun.caseId).title}` : 'No comparison evaluated yet'}{isDirty && selectedRun ? ' · Inputs changed — run again' : ''}

+
{location.route !== 'simulator' && Return to comparison →}Discussion worksheet
+
} +
+ {configError &&
{configError}
} + {location.route === 'overview' ? : location.route === 'hazop' ? : location.route === 'governance' ? : location.route === 'simulator' ? : } +
+
APS Research DemonstrationAll hazards unverified · Browser effects illustrative · No safety certification
+
+
; +} + +export function App() { + return ; } diff --git a/apps/aps-demo/src/SeoAudienceIntegration.test.tsx b/apps/aps-demo/src/SeoAudienceIntegration.test.tsx deleted file mode 100644 index ee54819..0000000 --- a/apps/aps-demo/src/SeoAudienceIntegration.test.tsx +++ /dev/null @@ -1,38 +0,0 @@ -// @vitest-environment jsdom -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { afterEach, beforeAll, expect, test, vi } from 'vitest'; -import { App } from './App.tsx'; - -beforeAll(() => { - Object.defineProperty(window, 'matchMedia', { writable: true, value: vi.fn(() => ({ matches: false, addEventListener() {}, removeEventListener() {} })) }); - vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }); -}); -afterEach(() => { cleanup(); window.location.hash = ''; }); - -test('layers overview SEO onto the new audience titles without restoring the old hero', () => { - window.location.hash = '#/overview'; render(); - expect((screen.getByRole('radio', { name: 'Executive' }) as HTMLInputElement).checked).toBe(true); - expect(screen.getByRole('heading', { level: 1 }).textContent).toBe('Delegate work. Keep control of the outcome.'); - expect(document.title).toBe('Why APS matters | Agentic Process Safety | HAZOP for AI Agent Swarms'); - expect(screen.queryByText('Make the unsafe path visible.')).toBeNull(); - fireEvent.click(screen.getByRole('radio', { name: 'Technical' })); - expect(screen.getByRole('heading', { level: 1 }).textContent).toBe('Autonomy with boundaries.'); - expect(document.title).toBe('Overview | Agentic Process Safety | HAZOP for AI Agent Swarms'); - expect(screen.getByText(/^Agentic Process Safety applies HAZOP to AI agent swarms\./)).toBeTruthy(); - expect(screen.getByRole('heading', { name: 'Procurement topology' })).toBeTruthy(); - expect(document.querySelectorAll('.node-buttons button')).toHaveLength(8); - fireEvent.click(screen.getByRole('radio', { name: 'Executive' })); - expect(document.title).toBe('Why APS matters | Agentic Process Safety | HAZOP for AI Agent Swarms'); - expect(screen.getByRole('heading', { level: 1 }).textContent).toBe('Delegate work. Keep control of the outcome.'); -}); - -test('retains audience route naming and route-focus behavior beyond the SEO overview', async () => { - window.location.hash = '#/overview'; render(); - await act(async () => { window.location.hash = '#/simulator'; window.dispatchEvent(new HashChangeEvent('hashchange')); }); - expect(document.title).toBe('How controls work | Agentic Process Safety'); - const heading = screen.getByRole('heading', { level: 1, name: 'What must stay true before we buy?' }); - expect(document.activeElement).toBe(heading); - fireEvent.click(screen.getByRole('radio', { name: 'Technical' })); - expect(document.title).toBe('Swarm Simulator | Agentic Process Safety'); - expect(screen.getByRole('navigation', { name: 'Main navigation' }).querySelectorAll('a')).toHaveLength(5); -}); diff --git a/apps/aps-demo/src/components/AudienceView.test.tsx b/apps/aps-demo/src/components/AudienceView.test.tsx deleted file mode 100644 index a29b720..0000000 --- a/apps/aps-demo/src/components/AudienceView.test.tsx +++ /dev/null @@ -1,25 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { AudienceProvider, Executive, Technical, EvidenceLink } from './AudienceView.tsx'; -afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); -it('has native exclusive radio semantics, focus retention and fresh-mount Executive default', () => { - const fixture =

Decision

Record

; - const first = render(fixture); - const executive = screen.getByRole('radio', { name: 'Executive' }) as HTMLInputElement; - const technical = screen.getByRole('radio', { name: 'Technical' }) as HTMLInputElement; - expect(executive.checked).toBe(true); expect(technical.checked).toBe(false); - expect(executive.name).toBe(technical.name); expect(screen.queryByRole('button', { name: 'Technical action' })).toBeNull(); - technical.focus(); fireEvent.click(technical); expect(document.activeElement).toBe(technical); expect(technical.checked).toBe(true); expect(executive.checked).toBe(false); - expect(screen.getByRole('button', { name: 'Technical action' })).toBeTruthy(); - executive.focus(); fireEvent.click(executive); expect(document.activeElement).toBe(executive); expect(screen.queryByRole('button', { name: 'Technical action' })).toBeNull(); - first.unmount(); render(fixture); expect((screen.getByRole('radio', { name: 'Executive' }) as HTMLInputElement).checked).toBe(true); -}); -it('reveals the requested technical record and focuses it without replacing its DOM owner', () => { - const frames: FrameRequestCallback[] = []; vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { frames.push(callback); return frames.length; }); - render(Inspect evidence

Actual record

); - const owner = document.getElementById('record'); const link = screen.getByRole('button', { name: 'Inspect evidence' }); link.focus(); fireEvent.click(link); - frames.forEach(callback => callback(0)); expect(document.getElementById('record')).toBe(owner); expect(document.activeElement).toBe(owner); - expect((screen.getByRole('radio', { name: 'Technical' }) as HTMLInputElement).checked).toBe(true); - fireEvent.click(screen.getByRole('radio', { name: 'Executive' })); expect(document.activeElement).toBe(link); -}); diff --git a/apps/aps-demo/src/components/AudienceView.tsx b/apps/aps-demo/src/components/AudienceView.tsx deleted file mode 100644 index aba8c9c..0000000 --- a/apps/aps-demo/src/components/AudienceView.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { createContext, useContext, useRef, useState } from 'react'; -import type { ReactNode } from 'react'; - -type Audience = 'executive' | 'technical'; -// Standalone legacy components keep their original presentation; the real App -// always supplies the provider, whose fresh-document default is Executive. -const Context = createContext<{ audience: Audience; choose: (next: Audience) => void; reveal: (id?: string) => void }>({ audience: 'technical', choose: () => {}, reveal: () => {} }); -export function useAudience() { return useContext(Context); } -export function AudienceProvider({ children }: { children: ReactNode }) { - const [audience, setAudience] = useState('executive'); - const returnTarget = useRef(null); - function choose(next: Audience) { - // Native radios retain focus. Evidence links can return to their invoking - // common control when their destination is about to become hidden. - if (next === 'executive' && document.activeElement?.closest('[data-technical]')) returnTarget.current?.focus(); - setAudience(next); - } - function reveal(id?: string) { - returnTarget.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; - setAudience('technical'); - if (id) requestAnimationFrame(() => document.getElementById(id)?.focus()); - } - return
-
View{(['executive', 'technical'] as const).map(value => )}
Same run. Same controls. Same evidence.
{children} -
; -} -export function Technical({ children, id }: { children: ReactNode; id?: string }) { - const { audience } = useAudience(); - return ; -} -export function Executive({ children }: { children: ReactNode }) { - const { audience } = useAudience(); - return ; -} -export function EvidenceLink({ target, children }: { target: string; children: ReactNode }) { - const { reveal } = useAudience(); - return ; -} diff --git a/apps/aps-demo/src/components/BusinessContext.test.tsx b/apps/aps-demo/src/components/BusinessContext.test.tsx deleted file mode 100644 index d396c24..0000000 --- a/apps/aps-demo/src/components/BusinessContext.test.tsx +++ /dev/null @@ -1,146 +0,0 @@ -// @vitest-environment jsdom -import { useState } from 'react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { BusinessExercise, BusinessOverview, BusinessRoles, BusinessScenarioNote } from './BusinessContext.tsx'; -import { WorkflowStage } from './WorkflowStage.tsx'; -import { createWorkflow, exportWorkflow, scenarioSpec, selectWorkflow, workflowReducer } from '../workflow/index.ts'; -import type { Mode, ScenarioId, WorkflowCommand, WorkflowState } from '../workflow/index.ts'; - -afterEach(cleanup); -function populated() { - let state = createWorkflow(scenarioSpec()); - for (let i = 0; i < 100 && !selectWorkflow(state).metrics.committedOrders; i++) state = workflowReducer(state, { type: 'step' }); - expect(selectWorkflow(state).metrics.committedOrders).toBe(1); - expect(state.running).toBe(false); - return state; -} -function finished(scenario: ScenarioId, mode: Mode) { - let state = createWorkflow(scenarioSpec(scenario, mode)); - for (let i = 0; i < 100 && selectWorkflow(state).controls.canStep; i++) state = workflowReducer(state, { type: 'step' }); - return state; -} -function Stage({ state, command = () => {} }: { state: WorkflowState; command?: (command: WorkflowCommand) => void }) { - return exportWorkflow(state)} onImport={() => ({ ok: false, message: 'Not used in explanation checks' })}/>; -} -function stat(label: string) { - return screen.getByText(label, { exact: true }).closest('.stat')!.querySelector('strong')!.textContent; -} - -describe('business explanation without new workflow authority', () => { - it('links the business exercise to the existing simulator and keeps the research boundary visible', () => { - render(); - expect(screen.getByRole('link', { name: 'Try the factory-supply exercise →' }).getAttribute('href')).toBe('#/simulator'); - expect(screen.getByText(/Agents, approvals, orders and spending are simulated/)).toBeTruthy(); - expect(screen.getByText(/An order does not mean goods arrived/)).toBeTruthy(); - expect(screen.queryByRole('button')).toBeNull(); - }); - it('opens every explanation without changing a populated paused run or its controls', () => { - const state = populated(); const command = vi.fn(); const before = exportWorkflow(state); - const { container } = render(); - const controls = () => Array.from(container.querySelectorAll('button,select')).map(element => ({ tag: element.tagName, text: element.textContent, disabled: (element as HTMLButtonElement).disabled, value: (element as HTMLSelectElement).value })); - const beforeControls = controls(); const status = screen.getByRole('status', { name: 'Workflow status' }).textContent; - const details = container.querySelectorAll('.business-context details'); - expect(details.length).toBeGreaterThan(0); - for (const detail of details) { - const summary = detail.querySelector('summary')!; - summary.focus(); fireEvent.click(summary); expect(detail.open).toBe(true); - expect(document.activeElement).toBe(summary); - expect(exportWorkflow(state)).toBe(before); expect(controls()).toEqual(beforeControls); - fireEvent.click(summary); expect(detail.open).toBe(false); - } - expect(screen.getByRole('status', { name: 'Workflow status' }).textContent).toBe(status); - expect(command).not.toHaveBeenCalled(); expect(exportWorkflow(state)).toBe(before); - expect(stat('Committed orders')).toBe('1'); expect(stat('Simulated spend')).toBe('400'); - }); - it('keeps business stakes tied to the applied run rather than a draft scenario', () => { - function Harness() { - const [state, setState] = useState(() => createWorkflow(scenarioSpec())); - return setState(current => workflowReducer(current, command))} onExport={() => exportWorkflow(state)} onImport={() => ({ ok: false, message: 'Not used' })}/>; - } - render(); - const situation = () => within(screen.getByLabelText('Active business situation')); - expect(situation().getByRole('heading', { name: 'The ordinary purchase' })).toBeTruthy(); - fireEvent.change(screen.getByLabelText('Workflow scenario'), { target: { value: 'lost-purchase-response' } }); - expect(situation().getByRole('heading', { name: 'The ordinary purchase' })).toBeTruthy(); - fireEvent.click(screen.getByRole('button', { name: 'Prepare example' })); - expect(situation().getByRole('heading', { name: 'No reply does not mean no order' })).toBeTruthy(); - expect(stat('Committed orders')).toBe('0'); - }); - it('shows non-default task inputs without pretending the built-in example is their observed result', () => { - const task = { ...scenarioSpec().task, demand: 17, stock: 2, unitPrice: 9, budget: 8000 }; - const { container } = render(); - const current = container.querySelector('.business-current-inputs')!.textContent; - expect(current).toContain('demand 17, stock 2, unit price 9, budget 8000'); - expect(current).not.toContain('80-unit'); expect(current).not.toContain('400'); - expect(screen.getByText(/These are model defaults, not measured savings or a result already achieved/)).toBeTruthy(); - expect(screen.getByText(/Suggested discussion time: 10–15 minutes, not a measured/)).toBeTruthy(); - }); - it('explains all six roles without creating action controls', () => { - const { container } = render(); - expect(Array.from(container.querySelectorAll('.business-role-grid dt'), node => node.textContent)).toEqual(['Demand', 'Inventory', 'Supplier', 'Finance', 'Purchase', 'Orchestrator']); - expect(screen.queryByRole('button')).toBeNull(); - expect(screen.getByText(/Coordination does not make inputs true/)).toBeTruthy(); - }); - it.each([ - ['nominal', 'The ordinary purchase'], ['approval-delay', 'Permission expires while work continues'], - ['purchase-race', 'One need, competing proposals'], ['lost-purchase-response', 'No reply does not mean no order'], - ] as const)('explains the existing %s situation without scenario commands', (scenario, title) => { - render(); - expect(screen.getByRole('heading', { name: title })).toBeTruthy(); - expect(screen.queryByRole('combobox')).toBeNull(); expect(screen.queryByRole('button')).toBeNull(); - }); - it('retains unsafe effects and the safe-completion distinction when baseline work confirms', () => { - const state = finished('approval-delay', 'A'); - expect(selectWorkflow(state).metrics.completed).toBe(true); - expect(selectWorkflow(state).metrics.unsafeCommittedEffects).toBeGreaterThan(0); - render(); - expect(stat('Task confirmed')).toBe('Yes'); expect(stat('Safe model completion')).toBe('No'); - expect(Number(stat('Unsafe committed effects'))).toBeGreaterThan(0); - expect(screen.getByText(/Confirmation alone is not an acceptable-outcome decision/)).toBeTruthy(); - expect(screen.getByLabelText('Observed simulated effects')).toBeTruthy(); - }); - it.each(['A', 'B', 'C'] as const)('qualifies expiry denial and refresh guidance against actual %s outcomes', mode => { - const state = finished('approval-delay', mode); - const view = selectWorkflow(state); - const before = exportWorkflow(state); const command = vi.fn(); - render(); - const note = screen.getByLabelText('Active business situation'); - const primary = Array.from(note.children).filter(node => node.tagName === 'P').map(node => node.textContent).join(' '); - const expiryEntry = within(note).getByText('Permission expires while work continues', { selector: 'dt' }).nextElementSibling!; - for (const text of [primary, expiryEntry.textContent!]) { - expect(text).toContain('In C, the defended comparator'); - expect(text).toContain('before requesting one fresh simulated approval'); - expect(text).toContain('A/B may confirm work despite expired approval, without an expiry denial or a refresh control'); - expect(text).toContain('Compare Task confirmed with Unsafe committed effects and Safe model completion'); - expect(text).toContain('recovery keeps the original problem in the history'); - } - if (mode === 'C') { - expect(view.metrics.completed).toBe(false); - expect(view.metrics.deniedProposals).toBeGreaterThan(0); - expect(view.metrics.committedOrders).toBe(0); - expect(view.controls.canRecover).toBe(true); - expect(screen.getByRole('button', { name: 'Request one approval refresh' })).toBeTruthy(); - expect(stat('Task confirmed')).toBe('No'); - } else { - expect(view.metrics.completed).toBe(true); - expect(view.metrics.deniedProposals).toBe(0); - expect(view.metrics.unsafeCommittedEffects).toBeGreaterThan(0); - expect(view.controls.canRecover).toBe(false); - expect(screen.queryByRole('button', { name: 'Request one approval refresh' })).toBeNull(); - expect(stat('Task confirmed')).toBe('Yes'); - } - expect(stat('Safe model completion')).toBe('No'); - expect(exportWorkflow(state)).toBe(before); expect(command).not.toHaveBeenCalled(); - }); - it('preserves one route heading, unique workflow status and reachable technical evidence', () => { - const { container } = render(); - expect(screen.getAllByRole('heading', { level: 1 })).toHaveLength(1); - expect(screen.getAllByRole('status', { name: 'Workflow status' })).toHaveLength(1); - expect(screen.getByRole('heading', { name: 'Typed handoffs' })).toBeTruthy(); - expect(screen.getByRole('heading', { name: 'Model observations and limits' })).toBeTruthy(); - expect(screen.getByRole('button', { name: 'Prepare current replay JSON' })).toBeTruthy(); - const names = Array.from(container.querySelectorAll('.business-context summary'), summary => summary.textContent); - expect(new Set(names).size).toBe(names.length); - }); -}); diff --git a/apps/aps-demo/src/components/BusinessContext.tsx b/apps/aps-demo/src/components/BusinessContext.tsx deleted file mode 100644 index a22bdb3..0000000 --- a/apps/aps-demo/src/components/BusinessContext.tsx +++ /dev/null @@ -1,93 +0,0 @@ -import type { AgentId, ScenarioId, TaskInput } from '../workflow/index.ts'; - -// BUSINESS-VISITOR-COPY.md d6fbd627…; explanations never dispatch or derive outcomes. -const roleOrder: readonly AgentId[] = ['demand', 'inventory', 'supplier', 'finance', 'purchase', 'orchestrator']; -const roles: Record = { - demand: { name: 'Demand', work: 'Takes the required quantity from the task input.', question: 'What need are we trying to meet, and who stands behind that input?' }, - inventory: { name: 'Inventory', work: 'Works out the shortage from demand and stock.', question: 'Are we buying the shortage rather than the full demand again?' }, - supplier: { name: 'Supplier', work: 'Prepares a simulated quote for that quantity.', question: 'Which quantity and price would this decision cover?' }, - finance: { name: 'Finance', work: 'Issues a simulated approval tied to the purchase details.', question: 'What was approved, and is that approval still valid?' }, - purchase: { name: 'Purchase', work: 'Proposes the order and tracks its outcome.', question: 'Was an order recorded, denied, or left with an uncertain outcome?' }, - orchestrator: { name: 'Orchestrator', work: 'Coordinates handoffs and the purchase boundary.', question: 'Did the required steps happen, and is confirmation supported?' }, -}; -const situations: Record = { - nominal: { title: 'The ordinary purchase', question: 'What would count as a correct, acceptable result?', inspect: 'Inspect the replenishment quantity, recorded order, spend and confirmation. Placing an order does not mean supplies arrived.' }, - 'approval-delay': { title: 'Permission expires while work continues', question: 'When must we stop, and what fresh evidence permits continuation?', inspect: 'In C, the defended comparator, inspect the expiry, denial and order count before requesting one fresh simulated approval. Blocking protects a boundary but delays progress; recovery keeps the original problem in the history. A/B may confirm work despite expired approval, without an expiry denial or a refresh control. Compare Task confirmed with Unsafe committed effects and Safe model completion.' }, - 'purchase-race': { title: 'One need, competing proposals', question: 'How do we keep one business need from becoming two purchases?', inspect: 'Compare the proposal order, decisions, order count and spend. Proposals run in a fixed, visible order, not on two real workers running at once.' }, - 'lost-purchase-response': { title: 'No reply does not mean no order', question: 'Should we check what happened before trying again?', inspect: 'Inspect the existing order and unknown outcome. Reconciliation checks the existing intent; it does not place a replacement order.' }, -}; - -export function BusinessOverview() { - return
-

A SHARED BUSINESS CONVERSATION

Keep supplies moving. Keep purchasing control.

-

Imagine you are responsible for keeping a factory supplied. What would you let agents decide, where would you put limits, and what evidence would you need before accepting the result?

-

Follow one purchasing example with your technical team. Six simulated roles divide the work. Discuss consequences and ownership while colleagues inspect the same handoffs, approvals and event history. You do not need to read code to take part.

-

Research demonstration. The factory is an illustrative story, not a production model. Agents, approvals, orders and spending are simulated; no live models, external APIs or purchases run. An order does not mean goods arrived, and a favorable model result does not certify a real system as safe.

- Try the factory-supply exercise → -
How HAZOP helps frame the questions

HAZOP means Hazard and Operability study. Ask what each part is intended to do and how behavior could depart from that intent: too much, too late, or beyond its authority. HAZOP Lab provides structured questions, not automatic risk ratings. Findings remain unverified, with no supplied severity or likelihood ratings. Agent-specific categories are project extensions; this demonstration is not a complete qualified study or approval of requirements.

-
; -} - -export function BusinessExercise({ task }: { task: Readonly }) { - return
-

FACTORY-SUPPLY DISCUSSION

When should purchasing continue?

-

Suggested discussion time: 10–15 minutes, not a measured visitor completion time. Use the generated workflow here; keep the separate single-request policy illustration below closed for this exercise.

-

This run's task inputs: demand {task.demand}, stock {task.stock}, unit price {task.unitPrice}, budget {task.budget} simulated units. Inventory derives what to buy; inspect the world records below for the resulting quantity and quote.

-

Start with Nominal procurement and C · Defended browser comparator using the controls below. Apply the selection, then start or step. Open the exercise for discussion prompts and comparisons.

-
Follow the four-stage exercise -
    -
  1. See the ordinary path

    Choose Nominal procurement and C · Defended browser comparator, then Apply selection and start new run. Check the Active labels. Use Start workflow or Step one transition. Read orders and spend alongside Task confirmed (business confirmation) and Safe model completion. What has—and has not—happened?

  2. -
  3. Handle an expired approval

    Choose Expired approval and recovery, keep C, apply and run. Inspect the denial and whether an order exists before using Request one approval refresh. Continue and inspect the retained history. What risk does stopping address, and what delay or effort does it introduce?

  4. -
  5. Compare completion with controlled completion

    Record your observations before changing runs: Apply clears the current history. Keep the expiry scenario, switch to A · Baseline browser comparator, apply and run. Compare Task confirmed with safe completion and unsafe effects. Confirmation alone can coexist with an expired approval. Would that satisfy your business objective?

  6. -
  7. Explain the decision together

    Select an event under What caused this? Inspect its reason and Direct causes, then Typed handoffs and What changed in the world? Where would a person intervene in a real process, who would own that decision, and what additional evidence would they need?

  8. -
-
-
Built-in example and simulation limits

The built-in example has demand 100, stock 20, unit price 5 and budget 1,000 simulated units: an 80-unit replenishment quoted at 400. These are model defaults, not measured savings or a result already achieved. Imported replays may use other inputs; this run's task and world records remain authoritative.

Demand is supplied input, not a validated forecast. The supplier role does not search a market. Production schedules, physical stock accuracy and delivery are not modeled. Approval refresh is a fresh modeled decision, not authenticated human approval. Logical time and playback pace are not measured factory delay or business performance.

-
; -} - -export function BusinessScenarioNote({ scenario }: { scenario: ScenarioId }) { - const situation = situations[scenario]; - return
-

{situation.title}

{situation.question}

{situation.inspect}

-
Other business situations in this model
{Object.entries(situations).map(([id, item]) =>
{item.title}
{item.question} {item.inspect}
)}

These are the four existing scenarios, not new levels of agent capability. Choose another emphasis using the existing scenario control; explanation depth never changes safeguards or evidence.

-
; -} - -export function BusinessRoles() { - return
-

Five specialist roles and one coordinator share the work. Their names describe responsibilities, not real people or live AI services.

-
{roleOrder.map(id =>
{roles[id].name}
{roles[id].work}
)}
-
Business questions behind the six roles
{roleOrder.map(id =>
{roles[id].name} asks
{roles[id].question}
)}

Several roles can pass along the same incorrect assumption. Coordination does not make inputs true or create collective verification. People would need to establish input quality and the authority behind each action.

-
; -} - -export function BusinessOutcomeGuide() { - return
-

Read the result in two parts

-

Task confirmed (business confirmation) means the modeled order outcome was supported and confirmed. Safe model completion: Yes also requires no order flagged unsafe and all required model checks to pass. Confirmation alone is not an acceptable-outcome decision for your organization.

-

Committed means recorded in the simulated order list—not goods delivered. No, unknown or a stopped run calls for inspection: work may be incomplete, a control may have stopped it, or an effect may exist without its reply. Zero observed unsafe effects alone does not prove completion or safety.

-
Technical explanation of the outcome checks

The model checks prerequisite evidence, approval freshness and matching details, approval consumption/state version, one order per intent, budget and confirmation evidence. Their technical names remain in Model observations and limits below. These invariants are computed within this model, not independently certified real-world safety. An unsafe committed effect is a simulated order violating a modeled check; a denial alone does not prove harm was prevented.

-
; -} - -const takeaways = [ - ['Define the outcome, not only the task', 'Explain what matters, what must not happen and what would make completion unacceptable. An order and reliable factory supply are different outcomes.'], - ['Make authority explicit', 'Identify what agents may read, propose or change and which commitments need a person. Ask how boundaries would be enforced; role names alone do not enforce them.'], - ['Explain the consequences behind a control', 'Discuss invalid approval, duplicate work or uncertainty alongside the delay or effort a control introduces. This demo supplies no measured cost-benefit answer.'], - ['Plan the exception path', 'Name an accountable role, the evidence it needs and how work resumes without hiding the original problem. An escalation without an available owner is unfinished.'], - ['Ask for evidence that matches the claim', 'Ask what changed, which approval covered it and what remains unknown. A completion message is not the same as an acceptable outcome.'], - ['Keep remaining risk visible', 'Ask what was modeled or tested and what remains outside the evidence. A favorable simulation starts discussion; it does not accept real-world risk.'], - ['Share ownership across business and technology', 'Business supplies intent, constraints and consequences; technical teams explain mechanisms, failure modes and evidence. Agree who decides and maintains the controls.'], -] as const; - -export function BusinessDebrief() { - return
-

Turn the example into a team conversation

-
  • What must the result achieve, and what would make a completed task unacceptable?
  • Who owns a stop, an expired permission or an unknown outcome—and what must that person inspect?
  • What evidence is missing before your organization could accept the remaining risk?
-

A useful takeaway is one shared decision question, an accountable role and a concrete evidence need. APS neither assigns that person nor implements real human approval.

-
Seven ways to support your technical team
    {takeaways.map(([title, explanation]) =>
  1. {title}

    {explanation}

  2. )}
-
Words to use together
Intent
The business action the model is trying to carry out, such as one replenishment purchase.
Approval binding
Tying permission to specific purchase details so it cannot simply cover different work.
State version
A marker of changes to the model's recorded facts.
Reconciliation
Checking an existing modeled outcome when a reply is missing, rather than blindly ordering again.
Idempotency
A mechanism intended to stop a repeated request creating another effect; scope and inputs matter.
Causal trace
Events linked to earlier causes so a result can be inspected.
Replay
Recomputing a supported saved browser run, or stepping through frozen calls in Assurance. Neither supplies new external evidence.
-

Business and technical readers use the same controls, records and uncertainty. Disclosures only explain more; they do not change the run, add capabilities or hide its evidence. Frozen experiments in Assurance remain separate from this active browser run.

-
; -} diff --git a/apps/aps-demo/src/components/CaseContinuity.test.tsx b/apps/aps-demo/src/components/CaseContinuity.test.tsx deleted file mode 100644 index 9a196d9..0000000 --- a/apps/aps-demo/src/components/CaseContinuity.test.tsx +++ /dev/null @@ -1,103 +0,0 @@ -// @vitest-environment jsdom -import { afterEach, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; -import { PurchasingOperations } from './PurchasingOperations.tsx'; -import { HazopConversation } from './HazopConversation.tsx'; -import { AudienceProvider } from './AudienceView.tsx'; -import { Hazop } from '../routes/Hazop.tsx'; -import { hazards } from '../data.ts'; -import { findingExercise, workflowStudies } from '../domain/reviewMappings.ts'; -import { createWorkflow, exportWorkflow, scenarioSpec, selectWorkflow, workflowReducer } from '../workflow/index.ts'; -import type { ScenarioId } from '../workflow/index.ts'; - -afterEach(() => { cleanup(); window.history.replaceState(null, '', '#/hazop'); }); -function finished(scenario: ScenarioId) { - let state = createWorkflow(scenarioSpec(scenario)); - for (let count = 0; count < 100 && selectWorkflow(state).controls.canStep; count++) state = workflowReducer(state, { type: 'step' }); - return state; -} -it.each(['nominal', 'approval-delay', 'purchase-race', 'lost-purchase-response'] as const)('reviews %s without switching its question or executing work', scenario => { - const state = finished(scenario); const before = exportWorkflow(state); const inspect = vi.fn(); - render(); - fireEvent.click(screen.getByRole('button', { name: 'Review operation design' })); - const review = screen.getByRole('region', { name: 'HAZOP design review' }); - expect(within(review).getByRole('heading', { name: workflowStudies[scenario].title })).toBeTruthy(); - expect(review.textContent).toContain(workflowStudies[scenario].summary); - if (scenario !== 'approval-delay') { - expect(within(review).queryByText('Related timing finding—different object/coverage')).toBeNull(); - expect(within(review).queryByText(/separate timing study/i)).toBeNull(); - } - for (let step = 0; step < 4; step++) fireEvent.click(within(review).getByRole('button', { name: 'Next review question' })); - expect(review.textContent).toContain('Residual risk, severity, likelihood and business benefit are unknown'); - expect(exportWorkflow(state)).toBe(before); expect(inspect).not.toHaveBeenCalled(); -}); -it('preserves explicit source selection as a separate timing study rather than changing the active case', () => { - const state = finished('lost-purchase-response'); const before = exportWorkflow(state); - render(); - expect(screen.getByRole('heading', { name: 'Can commitment occur after permission expires?' })).toBeTruthy(); - expect(screen.getByRole('region', { name: 'Separate selected record context' }).textContent).toContain('explicitly selected source'); - expect(screen.getByText('Related timing finding—different object/coverage')).toBeTruthy(); - expect(exportWorkflow(state)).toBe(before); -}); -it('does not manufacture an exercise for a finding without a mapping', () => { - const unmapped = hazards.find(h => findingExercise(h.id).coverage === 'unmapped')!; - render(); - const mapping = screen.getByRole('region', { name: 'Finding exercise mapping' }); - expect(mapping.textContent).toContain('No runnable request illustration'); - expect(within(mapping).queryByRole('link')).toBeNull(); -}); -it('links an approval finding to its applicable request and retains source identity', () => { - const id = 'APS-11dc498eedac1dc719df'; - render(); - const link = screen.getByRole('link', { name: 'Missing approval request →' }); - expect(link.getAttribute('href')).toBe(`#/governance?story=approval&hazard=${id}`); - expect(screen.queryByRole('link', { name: /Unauthorized supplier request/ })).toBeNull(); -}); -it('updates selection with filters and explicitly labels retained detail when results are empty', () => { - render(); - fireEvent.change(screen.getByLabelText('Agent node'), { target: { value: 'supplier' } }); - expect(screen.getByRole('heading', { name: /\/ supplier$/ })).toBeTruthy(); - expect(screen.queryByRole('heading', { name: /\/ orchestrator$/ })).toBeNull(); - fireEvent.change(screen.getByLabelText('Search findings'), { target: { value: 'no-matching-finding' } }); - expect(screen.getByRole('status').textContent).toContain('Pinned finding outside the current filter: supplier'); - expect(screen.getByText(/No findings match/)).toBeTruthy(); -}); -it('focuses the selected detail and restores row focus without losing shareable filters', () => { - const initial = new URLSearchParams({ node: 'supplier', deviation: 'AUTHORITY_ESCALATION', search: 'supplier', sort: 'node' }); - render(); - const row = within(screen.getByRole('table')).getByRole('button'); - fireEvent.click(row); - const detail = screen.getByRole('heading', { name: 'AUTHORITY ESCALATION / supplier' }); - expect(document.activeElement).toBe(detail); - const href = screen.getByRole('link', { name: 'Link to this finding and filters' }).getAttribute('href')!; - const query = new URLSearchParams(href.split('?')[1]); - expect(query.get('node')).toBe('supplier'); expect(query.get('deviation')).toBe('AUTHORITY_ESCALATION'); - expect(query.get('search')).toBe('supplier'); expect(query.get('sort')).toBe('node'); expect(query.get('hazard')).toBe('APS-ad4a560c0e8ea4fa1023'); - fireEvent.click(screen.getByRole('button', { name: 'Return to selected finding in register' })); expect(document.activeElement).toBe(row); - cleanup(); render(); - expect((screen.getByLabelText('Search findings') as HTMLInputElement).value).toBe('supplier'); - expect(screen.getByRole('heading', { name: 'AUTHORITY ESCALATION / supplier' })).toBeTruthy(); - expect(within(screen.getByRole('table')).getByRole('button').getAttribute('aria-pressed')).toBe('true'); -}); -it('keeps the executive title and review aligned after a technical selection changes a timing deep link', () => { - render(); - expect(screen.getByRole('heading', { level: 1 }).textContent).toBe('What could go wrong between permission and purchase?'); - fireEvent.click(screen.getByRole('radio', { name: 'Technical' })); - fireEvent.change(screen.getByLabelText('Agent node'), { target: { value: 'supplier' } }); - const row = within(screen.getByRole('table')).getAllByRole('button')[0]; fireEvent.click(row); - const chosen = new URLSearchParams(window.location.hash.split('?')[1]).get('hazard'); - fireEvent.click(screen.getByRole('radio', { name: 'Executive' })); - expect(screen.getByRole('heading', { level: 1 }).textContent).toBe('What can depart from intended purchasing?'); - expect(screen.getByRole('region', { name: 'HAZOP design review' }).textContent).toContain(chosen); - expect(screen.queryByRole('heading', { name: 'Can commitment occur after permission expires?' })).toBeNull(); -}); -it.each(['selection', 'filter'])('clears an initial invalid-link notice after explicit %s', action => { - render(); - expect(screen.getByText(/Requested finding unavailable; showing the current source fallback/)).toBeTruthy(); - fireEvent.click(screen.getByRole('radio', { name: 'Technical' })); - if (action === 'selection') fireEvent.click(within(screen.getByRole('table')).getAllByRole('button')[0]); - else fireEvent.change(screen.getByLabelText('Agent node'), { target: { value: 'supplier' } }); - fireEvent.click(screen.getByRole('radio', { name: 'Executive' })); - expect(screen.queryByText(/Requested finding unavailable; showing the current source fallback/)).toBeNull(); - expect(screen.getByRole('region', { name: 'HAZOP design review' }).textContent).toContain('Selected source finding'); -}); diff --git a/apps/aps-demo/src/components/ComparisonView.tsx b/apps/aps-demo/src/components/ComparisonView.tsx new file mode 100644 index 0000000..adaa0bb --- /dev/null +++ b/apps/aps-demo/src/components/ComparisonView.tsx @@ -0,0 +1,49 @@ +import type { ComparisonRun, LaneResult } from '../domain/comparison.ts'; +import type { Mode } from '../domain/scenarios.ts'; +import { getCase } from '../domain/cases.ts'; +import { Badge } from './shared.tsx'; + +export const laneLabels: Record = { A: 'No modeled checks', B: 'Tool permission + spend limit', C: 'Lifecycle checks added' }; + +export function outcomeLabel(result: LaneResult) { + return result.decision === 'allow' ? 'EXECUTED · MODEL' : result.decision === 'deny' ? 'BLOCKED · MODEL' : 'REVIEW PENDING'; +} + +function Lane({ result }: { result: LaneResult }) { + return
+

{laneLabels[result.mode]}

+ {outcomeLabel(result)} +

{result.reason}

+ {result.effect ?
Illustrative orders
{result.effect.before.orders} → {result.effect.after.orders}
Committed sandbox units
{result.effect.before.spend} → {result.effect.after.spend}
:

Effect projection is not modeled for this case.

} +

{result.businessOutcome}

+ {result.executedViolations.length > 0 ?
Executed with a modeled constraint violation
    {result.executedViolations.map(violation =>
  • {violation}
  • )}
+ : result.violations.length > 0 ?
Invalid condition present; no execution
    {result.violations.map(violation =>
  • {violation}
  • )}
+ :

No violation of the modeled constraints identified. This does not establish real-world safety.

} +
; +} + +export function ComparisonView({ run, showBaseline = false, compact = false }: { run: ComparisonRun; showBaseline?: boolean; compact?: boolean }) { + const modes: Mode[] = showBaseline ? ['B', 'C', 'A'] : ['B', 'C']; + const definition = getCase(run.caseId); + const b = run.results.B; + const c = run.results.C; + const decisive = c.checks.find(check => check.status === 'fail'); + const rules = [...new Set(modes.flatMap(mode => run.results[mode].checks.map(check => check.rule)))].filter(rule => rule !== 'Baseline'); + const difference = b.decision === c.decision + ? `No outcome difference: both selected bundles ${b.decision === 'allow' ? 'permit this request' : b.decision === 'deny' ? 'block this request' : 'request review'}. Extra checks do not always change the outcome.` + : `The outcome changes at ${decisive?.rule.toLowerCase() ?? 'the additional checks'}. B ${b.decision === 'allow' ? 'permits the request' : 'blocks the request'}; C ${c.decision === 'deny' ? 'blocks it' : c.decision === 'review' ? 'requests review without an effect' : 'permits it'}.`; + return
+
Illustrative browser comparison

{compact ? 'Retained comparison' : `Same request. ${showBaseline ? 'Three' : 'Two'} control bundles.`}

{run.id}
+

{definition.title} · {run.request.actor} actor · {run.request.amount} sandbox units · approval age {run.request.approvalAge}s

+ {run.parent &&

Hypothetical recovery from {run.parent.runId}, lane C. Both lanes start from that denied lane’s no-effect state. The recorded trial does not demonstrate this recovery.

} +
{modes.map(mode => )}
+

What changed? {difference}

+ {!compact && <> +
Compare every modeled check

Not included means the bundle has no such check. Not evaluated means an earlier decision stopped evaluation.

+
{modes.map(mode => )}{rules.map(rule => {modes.map(mode => { const check = run.results[mode].checks.find(item => item.rule === rule); return ; })})}
Ordered checks against the same input snapshot
Condition{mode} · {laneLabels[mode]}
{rule}{!check ? 'Not included' : check.status === 'pass' ? '✓ Passes' : check.status === 'fail' ? '× Fails' : '— Not evaluated'}{check && {check.reason}}
+
+
Input snapshot and comparison assumptions

Both lanes receive this same request and starting state. Re-evaluation starts independently and does not accumulate another order.

{JSON.stringify({ request: run.request, baseline: run.baseline, requestIdentity: run.requestIdentity, modelVersion: run.modelVersion }, null, 2)}
    {run.assumptions.map(assumption =>
  • {assumption}
  • )}
+

B is this selected tool-and-spend comparator. Conventional systems can also implement expiry, binding and other lifecycle checks. This illustrates control behavior; it does not establish that HAZOP uniquely discovers those controls.

+ } +
; +} diff --git a/apps/aps-demo/src/components/DecisionBriefEditor.tsx b/apps/aps-demo/src/components/DecisionBriefEditor.tsx deleted file mode 100644 index e6327cb..0000000 --- a/apps/aps-demo/src/components/DecisionBriefEditor.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import { useState } from 'react'; -import { MAX_BRIEF_BYTES, exportDecisionBrief } from '../decisionBrief.ts'; -import { selectWorkflow } from '../workflow/index.ts'; -import type { WorkflowState } from '../workflow/index.ts'; -import type { DecisionBriefController } from './useDecisionBrief.ts'; - -export function DecisionBriefEditor({ state, brief }: { state: WorkflowState; brief: DecisionBriefController }) { - const [exportText, setExportText] = useState(''); - const [importText, setImportText] = useState(''); - const [transferMessage, setTransferMessage] = useState(''); - const [transferOpen, setTransferOpen] = useState(false); - const v = selectWorkflow(state); - const snapshot = brief.draft?.snapshot; - const notes = brief.notes; - const exportStale = !!exportText && !!brief.draft && exportText !== exportDecisionBrief(brief.draft); - function prepare() { const text = brief.prepareExport(); setExportText(text); setTransferMessage(text ? 'Export prepared. The JSON contains a discussion snapshot, not verified evidence or approval.' : ''); return text; } - function download() { - const text = prepare(); if (!text) return; - try { - const url = URL.createObjectURL(new Blob([text], { type: 'application/json' })); - const link = document.createElement('a'); link.href = url; link.download = 'aps-decision-brief.json'; link.click(); - window.setTimeout(() => URL.revokeObjectURL(url), 1000); - } catch { setTransferMessage('File download is unavailable. Copy the prepared JSON below to retain your draft.'); } - } - async function readFile(file: File | undefined) { - if (!file) return; - brief.cancelImport(); setTransferMessage(''); - if (file.size > MAX_BRIEF_BYTES) { setTransferMessage('Brief exceeds the 128 KiB limit. Current draft retained.'); return; } - try { const text = await file.text(); setImportText(text); brief.previewImport(text); } - catch { setTransferMessage('Could not read this file. Current draft retained.'); } - } - return
-

WORKING BRIEF · NOT AN APPROVAL

Take a clear decision back to your team

-

APS examines failures across agent handoffs, connects safeguards to consequential actions, and asks for evidence of acceptable outcomes. HAZOP structures the analysis; enforcement and assurance are separate activities.

-

{brief.saved ? 'Saved in this browser.' : brief.draft ? 'Unsaved changes. Save locally or export before closing or reloading.' : 'No draft saved yet. Add notes or attach observations to begin.'}

- {brief.message &&

{brief.message}

} - {brief.storageConflict &&

The saved browser copy has changed

Your working notes are retained. Save and discard will not overwrite the changed copy. Download your working brief before reviewing that copy or reloading.

} - {snapshot &&

{brief.stale ? 'The run has changed—review this brief again. Its attached observations are retained; they do not describe the current run.' : 'Notes and discussion refer to the attached observations from this run.'}

} - {brief.imported &&

Restored or imported discussion data is unverified. Source labels and metrics are supplied data, not authenticated evidence. Import never resumes or changes a workflow.

} -
Business objective
Maintain supply continuity without unauthorized or duplicate commitments. Delivery is outside this model.
-
{snapshot ? 'Attached observation' : 'Current observation'}
{snapshot ? `${snapshot.scenario} · configuration ${snapshot.mode} · ${snapshot.orders} orders · ${snapshot.spend} simulated units · confirmation ${snapshot.confirmed ? 'supported' : 'not established'} · unsafe effects ${snapshot.unsafe} · model checks with confirmation ${snapshot.safeCompleted ? 'satisfied' : 'not established'}.` : `${v.scenarioTitle} · configuration ${state.spec.mode} · ${v.metrics.committedOrders} orders · ${v.metrics.spent} simulated units · confirmation ${v.metrics.completed ? 'supported' : 'not established'} · unsafe effects ${v.metrics.unsafeCommittedEffects} · model checks with confirmation ${v.metrics.safeCompleted ? 'satisfied' : 'not established'}.`}
-
Required safeguards to specify
Authority for the exact purchase at commitment; one commitment per intent; reconciliation before retry; an accountable exception owner.
-
Benefits and costs to measure
Hypotheses: fewer unauthorized or duplicate commitments and clearer accountability. Measure exception rate, review effort, completion, delay and recovery time. No ROI or production effectiveness is established here.
-
Remaining uncertainty
Real identity, integrations, delivery, residual risk and control effectiveness require separate evaluation. Frozen experiment results do not validate this active run.
-
- -