diff --git a/.github/workflows/repository-checks.yml b/.github/workflows/repository-checks.yml index 9df5363..8d0f459 100644 --- a/.github/workflows/repository-checks.yml +++ b/.github/workflows/repository-checks.yml @@ -55,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 == 'codex/aps-redesign-release') + (github.event.pull_request.head.ref == 'release/aps-github-validation-v1' || github.event.pull_request.head.ref == 'codex/aps-redesign-release' || github.event.pull_request.head.ref == 'codex/aps-guided-investigation') run: node apps/aps-demo/scripts/qa-evidence.mjs - name: Record actual PR checkout and workflow identities id: validation @@ -81,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 == 'codex/aps-redesign-release') + (github.event.pull_request.head.ref == 'release/aps-github-validation-v1' || github.event.pull_request.head.ref == 'codex/aps-redesign-release' || github.event.pull_request.head.ref == 'codex/aps-guided-investigation') run: node apps/aps-demo/scripts/validation-evidence.mjs finalize - name: Retain predeployment evidence including failed runs if: >- @@ -89,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 == 'codex/aps-redesign-release') + (github.event.pull_request.head.ref == 'release/aps-github-validation-v1' || github.event.pull_request.head.ref == 'codex/aps-redesign-release' || github.event.pull_request.head.ref == 'codex/aps-guided-investigation') 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/apps/aps-demo/scripts/e2e.mjs b/apps/aps-demo/scripts/e2e.mjs index 01f0411..82023c3 100644 --- a/apps/aps-demo/scripts/e2e.mjs +++ b/apps/aps-demo/scripts/e2e.mjs @@ -2,7 +2,7 @@ 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'; -/* global document, window */ +/* global document, window, Node */ // Serve only the built artifact at its actual Pages prefix. No SPA server fallback. const prefix = '/agentic-process-safety/'; @@ -54,7 +54,9 @@ try { 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(); }; + const openDetails = async selector => { const details = page.locator(selector); if ((await details.getAttribute('open')) === null) await details.locator(':scope > summary').click(); }; + const openTools = async () => openDetails('.discussion-session-tools'); + const openReasoning = async summary => { const details = page.locator('.reasoning-more').filter({ has: page.locator('summary', { hasText: summary }) }); 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']) { @@ -86,30 +88,81 @@ try { 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 page.getByRole('button', { name: /C stops at the condition/ }).click(); await check(() => expect(page.locator('.path-detail')).toContainText('freshness')); + await page.getByLabel('Recommended next action', { exact: true }).selectOption('Gather more information'); + await check(() => expect(page.locator('.investigation-next-step')).toContainText('Request the missing business evidence')); + await check(() => expect(page.getByRole('button', { name: 'Explore a fresh-approval request', exact: true })).toHaveCount(0)); await page.getByLabel('Reason for this recommendation', { exact: true }).fill('Hold the purchase and seek new exact authorization.'); + await page.getByLabel('What remains unknown?', { exact: true }).fill('Is the quotation still valid?'); + await page.getByRole('button', { name: 'Add this evidence request to my position', exact: true }).click(); + await check(() => expect(page.getByLabel('What remains unknown?', { exact: true })).toHaveValue(/Is the quotation still valid\?[\s\S]*Who can confirm/)); + await openReasoning('Inspect supporting evidence'); + await page.getByLabel('Supporting evidence', { exact: true }).fill('Quotation validity has not been verified.'); + await page.getByRole('button', { name: 'Attach this comparison’s decisive check', exact: true }).click(); + await check(() => expect(page.getByLabel('Supporting evidence', { exact: true })).toHaveValue(/Quotation validity has not been verified\.[\s\S]*Approval freshness/)); + await openReasoning('Record assumptions or disagreement'); 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(page.getByLabel('Supporting evidence', { exact: true })).toHaveValue(new RegExp(originalId))); + await check(() => expect(page.locator('.position-summary')).toContainText('Is the quotation still valid?')); await check(() => expect(lane('C').locator('.lane-result')).toHaveText('BLOCKED · MODEL')); - for (const route of ['hazop', 'governance', 'assurance', 'overview']) await routeWithinApp(route); + for (const route of ['hazop', 'governance', 'assurance', 'overview']) { + await routeWithinApp(route); + if (route === 'hazop') { + await check(() => expect(page.getByRole('region', { name: 'How this source relates to your case', exact: true })).toContainText('Approval freshness does not establish quotation validity')); + await check(() => expect(page.locator('.screening-register .register')).not.toBeVisible()); + assert.ok(await page.evaluate(() => !!(document.querySelector('.case-evidence-bridge').compareDocumentPosition(document.querySelector('.screening-register')) & Node.DOCUMENT_POSITION_FOLLOWING)), 'Case/source relationship precedes the broad register'); assertions++; + } + if (route === 'assurance') { + await page.getByRole('button', { name: 'Recorded experiments', exact: true }).click(); + await page.getByRole('button', { name: 'Attach this recorded event to your reasoning', exact: true }).click(); + await check(() => expect(page.getByText('Recorded event attached to ' + originalId + '.', { exact: false })).toBeVisible()); + } + } 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.getByLabel('What remains unknown?', { exact: true })).toHaveValue(/Is the quotation still valid\?[\s\S]*Who can confirm/)); + await openReasoning('Record assumptions or disagreement'); + await check(() => expect(page.getByLabel('Dissent or another interpretation', { exact: true })).toHaveValue('Quotation truth remains unknown.')); + await openReasoning('Inspect supporting evidence'); + await check(() => expect(page.getByLabel('Supporting evidence', { exact: true })).toHaveValue(/Related recorded evidence, not this browser execution/)); + await page.getByRole('button', { name: 'Try 59 seconds', exact: true }).click(); + await check(() => expect(page.getByLabel('Approval age (logical seconds)', { exact: true })).toBeFocused()); + await check(() => expect(page.getByLabel('Selected comparison', { exact: true })).toHaveValue(originalId)); 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 check(() => expect(currentComparison()).toContainText('Purchase with current approval')); + await check(() => expect(page.locator('.failure-path')).toContainText('Approval remains current')); + await check(() => expect(page.locator('.failure-path')).toContainText('Both bundles permit the request')); + const timing = page.getByLabel('Timing variation comparison', { exact: true }); + await check(() => expect(timing).toContainText('61s · B allow · C deny')); + await check(() => expect(timing).toContainText('59s · B allow · C allow')); + await page.getByRole('button', { name: 'Form a position →', exact: true }).click(); + await check(() => expect(page.locator('#discussion')).toBeFocused()); + const recommendation = page.getByLabel('Recommended next action', { exact: true }); + await check(() => expect(recommendation.locator('option[value="Verify business inputs"]')).toHaveCount(1)); + await check(() => expect(recommendation.locator('option[value="Obtain a new matching approval"]')).toHaveCount(0)); + await recommendation.selectOption('Verify business inputs'); + await check(() => expect(page.locator('.investigation-next-step')).toContainText('Request the missing business evidence')); + await check(() => expect(page.getByRole('button', { name: 'Explore a fresh-approval request', exact: true })).toHaveCount(0)); 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.getByLabel('Recommended next action', { exact: true }).selectOption('Obtain a new matching approval'); + await check(() => expect(page.locator('.investigation-next-step')).toContainText('Explore what a new matching approval would change')); + await page.getByRole('button', { name: '59 seconds', exact: true }).click(); + await check(() => expect(page.getByRole('button', { name: 'Explore a fresh-approval request', exact: true })).toBeDisabled()); + await page.getByRole('button', { name: 'Use this comparison’s inputs', exact: true }).click(); 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')); @@ -129,15 +182,24 @@ try { 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; + assert.match(savedExport.session.discussions[originalId].question, /Is the quotation still valid\?[\s\S]*Who can confirm/); + assert.ok(savedExport.session.discussions[originalId].evidence.includes(originalId)); + assert.match(savedExport.session.discussions[originalId].evidence, /Quotation validity has not been verified\.[\s\S]*Approval freshness/); + assertions += 9; 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 openTools(); 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)); + await page.getByLabel('Selected comparison', { exact: true }).selectOption(originalId); + await check(() => expect(page.getByLabel('What remains unknown?', { exact: true })).toHaveValue(/Is the quotation still valid\?[\s\S]*Who can confirm/)); + await openReasoning('Record assumptions or disagreement'); + await check(() => expect(page.getByLabel('Dissent or another interpretation', { exact: true })).toHaveValue('Quotation truth remains unknown.')); + await openTools(); 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(); @@ -162,6 +224,18 @@ try { 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 (story === 'conflict') { + await check(() => expect(page.locator('.failure-path')).toContainText('Competing goals declared')); + await check(() => expect(page.locator('.failure-path')).toContainText('Trade-off remains unresolved')); + await check(() => expect(page.locator('.failure-path')).not.toContainText('logical seconds')); + await page.getByRole('button', { name: /C asks for a human decision/ }).click(); + await check(() => expect(page.locator('.path-detail')).toContainText('Objective review')); + await page.getByLabel('Recommended next action', { exact: true }).selectOption('Clarify competing objectives'); + await check(() => expect(page.locator('.investigation-next-step')).toContainText('Ask what would make a trade-off acceptable')); + await page.getByRole('button', { name: 'Add this evidence request to my position', exact: true }).click(); + await check(() => expect(page.getByLabel('What remains unknown?', { exact: true })).toHaveValue(/priority|priorities/)); + await check(() => expect(page.getByRole('button', { name: 'Explore a fresh-approval request', exact: true })).toHaveCount(0)); + } 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'); @@ -170,6 +244,7 @@ try { await page.getByRole('button', { name: 'Reset inputs', exact: true }).click(); await evaluate(); await go('hazop?hazard=unknown&node=invalid'); await page.reload(); + await openDetails('.screening-register'); 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'); @@ -192,7 +267,18 @@ try { for (const link of new Set(links)) await go(link.slice(2)); await go('assurance?trial=15'); + const bridge = page.getByRole('region', { name: 'How this source relates to your case', exact: true }); + await check(() => expect(bridge).toBeVisible()); + await check(() => expect(bridge).toContainText('quotation')); + const decisive = page.getByRole('region', { name: 'Decisive recorded event', exact: true }); + await check(() => expect(decisive).toBeVisible()); + await check(() => expect(decisive).toContainText('purchase_mock')); + await check(() => expect(decisive).toContainText('ALLOW · executed')); + await check(() => expect(decisive).toContainText('DENY · not executed')); const pair = page.locator('.recorded-pair-table'); + await check(() => expect(pair).not.toBeVisible()); + await openDetails('.recorded-full-trace'); + await check(() => expect(pair).toBeVisible()); 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')); @@ -203,6 +289,7 @@ try { 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 openDetails('.trial-ledger'); 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'); @@ -237,7 +324,7 @@ try { 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, experience: 'APS redesign increments 1–4', + assertions, errors, violations, prefix, experience: 'APS guided investigation', 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; 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.'); diff --git a/apps/aps-demo/scripts/validation-evidence.mjs b/apps/aps-demo/scripts/validation-evidence.mjs index 4b3aa23..64dc670 100644 --- a/apps/aps-demo/scripts/validation-evidence.mjs +++ b/apps/aps-demo/scripts/validation-evidence.mjs @@ -9,7 +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 releaseHeadRefs = Object.freeze(['release/aps-github-validation-v1', 'codex/aps-redesign-release', 'codex/aps-guided-investigation']); 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'); diff --git a/apps/aps-demo/src/App.tsx b/apps/aps-demo/src/App.tsx index 108e6ed..db45e17 100644 --- a/apps/aps-demo/src/App.tsx +++ b/apps/aps-demo/src/App.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; import { SessionProvider, useSession } from './components/SessionContext.tsx'; -import { getCase } from './domain/cases.ts'; +import { runTitle } from './domain/presentation.ts'; import { Overview } from './routes/Overview.tsx'; import { Hazop } from './routes/Hazop.tsx'; import { Governance } from './routes/Governance.tsx'; @@ -71,7 +71,7 @@ function Workspace() {
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' : ''}

+
ILLUSTRATIVE WORKSPACE{selectedRun && !isDirty ? runTitle(selectedRun) : caseDefinition.title}

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

{location.route !== 'simulator' && Return to comparison →}Discussion worksheet
}
diff --git a/apps/aps-demo/src/components/CaseEvidenceBridge.tsx b/apps/aps-demo/src/components/CaseEvidenceBridge.tsx new file mode 100644 index 0000000..6228038 --- /dev/null +++ b/apps/aps-demo/src/components/CaseEvidenceBridge.tsx @@ -0,0 +1,26 @@ +import type { CaseDefinition } from '../domain/cases.ts'; + +type SourceKind = 'hazard' | 'control' | 'recorded'; + +/** Explains a relationship, never upgrades a related source into execution evidence. */ +export function CaseEvidenceBridge({ activeCase, kind, matches, sourceLabel }: { + activeCase: CaseDefinition; kind: SourceKind; matches: boolean; sourceLabel: string; +}) { + const relationship = activeCase.id === 'stale' + ? { question: 'Was the finance approval still current when this purchase was attempted?', source: kind === 'recorded' ? 'The recorded expiry case tests an expired finance approval.' : 'The source finding concerns an expired quotation and excess price; the linked control covers approval and other expiry checks.', gap: 'Approval freshness does not establish quotation validity. Price, demand and stock accuracy still need separate evidence.', next: 'What would establish that the quotation is still valid before another attempt?' } + : activeCase.id === 'context' + ? { question: 'Does this purchase carry context that belongs to its task?', source: kind === 'recorded' ? 'The recorded context substitution occurs at demand_mock; the browser illustration evaluates a purchase request.' : 'The source finding concerns context contamination; the mapped task-binding check covers a narrower condition.', gap: 'A context binding check does not establish source truth or resistance to live prompt injection. Related stages are not the same execution.', next: 'Which source and task binding would you need to verify before trusting this request?' } + : activeCase.id === 'conflict' + ? { question: 'Who should resolve the competing objectives before the purchase proceeds?', source: kind === 'recorded' ? 'The recorded goal-conflict case measures a budget violation, not objective arbitration.' : 'The source finding concerns competing objectives; production arbitration remains an explicit control gap.', gap: 'Requesting review does not resolve the conflict. A budget outcome does not establish an acceptable trade-off between objectives.', next: 'Which objectives, decision owner and unresolved trade-off should the discussion record?' } + : { question: activeCase.objective, source: activeCase.evidenceNote, gap: activeCase.limitation, next: 'Which observation supports your recommendation, and what is still missing?' }; + return
+

KEEP THE INVESTIGATION CONNECTED

+

{matches ? 'What this source can tell you' : 'A different source is under inspection'}

+

Your case family: {activeCase.title}. Inspected source: {sourceLabel}.

+ {matches ? <> +

Browser question

{relationship.question}

Related source

{relationship.source}

Still unresolved

{relationship.gap}

+

Bring back a question: {relationship.next}

+ :

This selection is not the mapped source for your active case. Inspecting it does not change your retained comparison or make its results evidence for this case.

} + +
; +} diff --git a/apps/aps-demo/src/components/CaseEvidenceJourney.test.tsx b/apps/aps-demo/src/components/CaseEvidenceJourney.test.tsx new file mode 100644 index 0000000..e489107 --- /dev/null +++ b/apps/aps-demo/src/components/CaseEvidenceJourney.test.tsx @@ -0,0 +1,146 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type * as Recharts from 'recharts'; +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { CaseEvidenceBridge } from './CaseEvidenceBridge.tsx'; +import { EvidenceComparison } from './EvidenceComparison.tsx'; +import { SessionProvider, useSession } from './SessionContext.tsx'; +import { Hazop } from '../routes/Hazop.tsx'; +import { Assurance } from '../routes/Assurance.tsx'; +import { Governance } from '../routes/Governance.tsx'; +import { getCase } from '../domain/cases.ts'; +import { experiment } from '../data.ts'; + +vi.mock('recharts', async importOriginal => ({ ...await importOriginal(), ResponsiveContainer: () => null })); + +function EvidenceSessionControls() { + const { runComparison, setApprovalAge, selectedRun, discussions, updateDiscussion } = useSession(); + const discussion = selectedRun && discussions[selectedRun.id]; + return <> + + + + {discussion && discussion.evidence} + {discussion && discussion.ready ? 'ready' : 'draft'} + {selectedRun ? `${selectedRun.results.B.decision}/${selectedRun.results.C.decision}` : 'none'} + ; +} + +afterEach(() => { cleanup(); window.location.hash = ''; }); + +describe('supporting sources preserve the investigation question', () => { + it('explains approval freshness versus quotation validity before the source finding', () => { + render(); + const bridge = screen.getByRole('region', { name: 'How this source relates to your case' }); + const finding = screen.getByRole('region', { name: 'purchase: late' }); + expect(bridge.compareDocumentPosition(finding) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(within(bridge).getByText(/Approval freshness does not establish quotation validity/)).toBeTruthy(); + expect(within(bridge).getByRole('link', { name: 'Return to your reasoning →' }).getAttribute('href')).toBe('#/simulator?panel=discussion'); + expect(screen.getByText('Search and browse all 96 findings').closest('details')?.hasAttribute('open')).toBe(false); + fireEvent.click(screen.getByText('Search and browse all 96 findings')); + const register = screen.getByRole('table', { name: 'Generated hazards, all unverified with null ratings' }); + expect(within(register).getAllByRole('row')).toHaveLength(97); + fireEvent.change(screen.getByLabelText('Search findings'), { target: { value: 'an impossible unmatched search' } }); + expect(screen.getByText(/No findings match/)).toBeTruthy(); + expect(screen.getByRole('region', { name: 'purchase: late' })).toBeTruthy(); + }); + + it('does not present an unrelated selected hazard as the active case mapping', () => { + render(); + const bridge = screen.getByRole('region', { name: 'How this source relates to your case' }); + expect(within(bridge).getByRole('heading', { name: 'A different source is under inspection' })).toBeTruthy(); + expect(within(bridge).getByText(/not the mapped source for your active case/)).toBeTruthy(); + expect(within(bridge).queryByText('Browser question')).toBeNull(); + }); + + it('does not relabel an unrelated inspected control as approval-expiry evidence', () => { + render(); + const bridge = screen.getByRole('region', { name: 'How this source relates to your case' }); + expect(within(bridge).getByRole('heading', { name: 'A different source is under inspection' })).toBeTruthy(); + expect(within(bridge).getByText(/Purchase after approval expiry/)).toBeTruthy(); + expect(within(bridge).queryByText(/recorded context substitution/)).toBeNull(); + }); + + it('makes the recorded demand-stage context distinction explicit', () => { + render(); + expect(screen.getByText(/recorded context substitution occurs at demand_mock; the browser illustration evaluates a purchase request/)).toBeTruthy(); + expect(screen.getByText(/Related stages are not the same execution/)).toBeTruthy(); + }); + + it('does not turn a recorded budget violation into resolved objective arbitration', () => { + render(); + expect(screen.getByText(/recorded goal-conflict case measures a budget violation, not objective arbitration/)).toBeTruthy(); + expect(screen.getByText(/Requesting review does not resolve the conflict/)).toBeTruthy(); + }); +}); + +describe('recorded comparisons foreground the actual divergent call', () => { + it('shows the purchase event first and retains every original paired call behind disclosure', () => { + const trial = experiment.trials.find(row => row.sequence === 15)!; + render(); + const decisive = screen.getByRole('region', { name: 'Decisive recorded event' }); + expect(within(decisive).getByText(/Paired step 10:/)).toBeTruthy(); + expect(within(decisive).getByText('purchase → purchase_mock')).toBeTruthy(); + const event = within(decisive).getByRole('table', { name: 'Decisive recorded B/C event' }); + expect(within(event).getByText('ALLOW · executed')).toBeTruthy(); + expect(within(event).getByText('DENY · not executed')).toBeTruthy(); + expect(within(event).getAllByText('Input violations: expired_finance_approval')).toHaveLength(2); + expect(screen.getByText('Inspect all 10 paired recorded steps').closest('details')?.hasAttribute('open')).toBe(false); + fireEvent.click(screen.getByText('Inspect all 10 paired recorded steps')); + const full = screen.getByRole('table', { name: /Recorded B\/C calls/ }); + expect(within(full).getAllByRole('row')).toHaveLength(11); + expect(within(full).getByText('demand_mock')).toBeTruthy(); + expect(within(full).getByText('finance_mock')).toBeTruthy(); + expect(within(full).getByText('purchase_mock')).toBeTruthy(); + expect(screen.getByText(/B #14 and C #15 share the recorded case identity and digest/)).toBeTruthy(); + }); + + it('does not invent a decisive difference for equal benign outcomes', () => { + render( row.sequence === 3)!}/>); + expect(screen.queryByRole('region', { name: 'Decisive recorded event' })).toBeNull(); + expect(screen.getByText('No difference in recorded decisions or execution flags between these paired calls.')).toBeTruthy(); + }); + + it('does not pair records from another case identity or digest', () => { + const original = experiment.trials.find(row => row.sequence === 15)!; + render(); + expect(screen.getByText('A complete recorded B/C comparison is unavailable.')).toBeTruthy(); + expect(screen.queryByRole('region', { name: 'Decisive recorded event' })).toBeNull(); + expect(screen.queryByText('ALLOW · executed')).toBeNull(); + }); +}); + + +describe('recorded evidence can inform a retained human position', () => { + it('attaches the exact related event without replacing notes or changing the modeled result', () => { + const trial = experiment.trials.find(row => row.sequence === 15)!; + render(); + expect(screen.queryByRole('button', { name: 'Attach this recorded event to your reasoning' })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Test evaluate' })); + fireEvent.click(screen.getByRole('button', { name: 'Test existing position' })); + expect(screen.getByLabelText('Test ready').textContent).toBe('ready'); + fireEvent.click(screen.getByRole('button', { name: 'Attach this recorded event to your reasoning' })); + const evidence = screen.getByLabelText('Test evidence').textContent!; + expect(evidence).toContain('Original evidence note.'); + expect(evidence).toContain('Related recorded evidence, not this browser execution'); + expect(evidence).toContain(`case ${trial.case_id}, digest ${trial.case_digest}`); + expect(evidence).toContain('B trial #14 / C trial #15'); + expect(evidence).toContain('purchase → purchase_mock. B: allow, executed; C: deny, not executed'); + expect(screen.getByLabelText('Test ready').textContent).toBe('draft'); + expect(screen.getByLabelText('Test outcome').textContent).toBe('allow/deny'); + fireEvent.click(screen.getByRole('button', { name: 'Attach this recorded event to your reasoning' })); + expect(screen.getByLabelText('Test evidence').textContent).toBe(evidence); + fireEvent.click(screen.getByRole('button', { name: 'Test edit age' })); + expect(screen.queryByRole('button', { name: 'Attach this recorded event to your reasoning' })).toBeNull(); + expect(screen.getByLabelText('Test evidence').textContent).toBe(evidence); + }); + + it('does not offer an unrelated recorded event as evidence for the selected case', () => { + render(); + fireEvent.click(screen.getByRole('button', { name: 'Test evaluate' })); + expect(screen.getByRole('region', { name: 'Decisive recorded event' })).toBeTruthy(); + expect(screen.getByRole('heading', { name: 'A different source is under inspection' })).toBeTruthy(); + expect(screen.queryByRole('button', { name: 'Attach this recorded event to your reasoning' })).toBeNull(); + expect(screen.getByLabelText('Test evidence').textContent).toBe(''); + }); +}); diff --git a/apps/aps-demo/src/components/CaseProgress.test.tsx b/apps/aps-demo/src/components/CaseProgress.test.tsx new file mode 100644 index 0000000..81571e2 --- /dev/null +++ b/apps/aps-demo/src/components/CaseProgress.test.tsx @@ -0,0 +1,76 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { SessionProvider, useSession } from './SessionContext.tsx'; +import { Simulator } from '../routes/Simulator.tsx'; +import { createComparison } from '../domain/comparison.ts'; +import { timingReference } from './CaseProgress.tsx'; + +vi.mock('./DiscussionWorksheet.tsx', () => ({ DiscussionWorksheet: () =>
Discussion destination
})); + +function StateProbe() { + const { runs, selectedRun } = useSession(); + return {JSON.stringify({ count: runs.length, selected: selectedRun?.id, age: selectedRun?.request.approvalAge, decision: selectedRun?.results.C.decision })}; +} +function setup() { + window.location.hash = '#/simulator'; + return render(); +} +function state() { return JSON.parse(screen.getByLabelText('Retained state').textContent!); } +afterEach(cleanup); + +describe('guided case progression', () => { + it('names the bundles before prediction and prevents later steps before a comparison', () => { + setup(); + const bundles = screen.getByLabelText('The two control bundles'); + expect(bundles.textContent).toContain('B · Tool permission + spend limit'); + expect(bundles.textContent).toContain('C · Lifecycle checks added'); + const steps = screen.getByRole('navigation', { name: 'Case investigation steps' }); + expect((within(steps).getByRole('button', { name: /2 · Change one condition/ }) as HTMLButtonElement).disabled).toBe(true); + expect((within(steps).getByRole('button', { name: /3 · Form a position/ }) as HTMLButtonElement).disabled).toBe(true); + expect(state().count).toBe(0); + }); + + it('Try59 changes only the draft, preserves the original result, and requires explicit evaluation', () => { + setup(); + fireEvent.click(screen.getByRole('button', { name: 'Run comparison' })); + expect(state()).toEqual({ count: 1, selected: 'comparison-1', age: 61, decision: 'deny' }); + fireEvent.click(screen.getByRole('button', { name: 'Try 59 seconds' })); + expect(state()).toEqual({ count: 1, selected: 'comparison-1', age: 61, decision: 'deny' }); + const age = screen.getByLabelText('Approval age (logical seconds)') as HTMLInputElement; + expect(age.value).toBe('59'); + expect(document.activeElement).toBe(age); + expect(screen.getByText(/The retained results below still describe/).textContent).toContain('age 61s'); + expect((screen.getByRole('button', { name: /3 · Form a position/ }) as HTMLButtonElement).disabled).toBe(true); + fireEvent.click(screen.getByRole('button', { name: 'Run comparison' })); + expect(state()).toEqual({ count: 2, selected: 'comparison-2', age: 59, decision: 'allow' }); + const delta = screen.getByLabelText('Timing variation comparison'); + expect(delta.textContent).toContain('61s · B allow · C deny'); + expect(delta.textContent).toContain('59s · B allow · C allow'); + fireEvent.click(screen.getByRole('button', { name: 'Form a position →' })); + expect(document.activeElement).toBe(screen.getByRole('region', { name: 'Test discussion' })); + fireEvent.click(screen.getByRole('button', { name: 'Return to original comparison' })); + expect(state()).toEqual({ count: 2, selected: 'comparison-1', age: 61, decision: 'deny' }); + }); + + it('gives fixed objective-conflict cases an inspection step without pretending timing is editable', () => { + setup(); + fireEvent.change(screen.getByLabelText('Choose a case'), { target: { value: 'conflict' } }); + fireEvent.click(screen.getByRole('button', { name: 'Run comparison' })); + expect(state().decision).toBe('review'); + expect(screen.queryByRole('button', { name: 'Try 59 seconds' })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: /2 · Inspect the decision/ })); + expect(document.activeElement?.id).toBe('case-path'); + expect(screen.queryByLabelText('Timing variation comparison')).toBeNull(); + expect(screen.queryByLabelText('Approval age (logical seconds)')).toBeNull(); + }); + + it('never calls a changed baseline, changed request field or another case a timing-only variation', () => { + const a = createComparison('comparison-1', { caseId: 'stale', approvalAge: '61' }); + const b = createComparison('comparison-2', { caseId: 'stale', approvalAge: '59' }); + expect(timingReference(b, [a, b])).toBe(a); + expect(timingReference(b, [{ ...a, baseline: { orders: 1, spend: 300 } }])).toBeUndefined(); + expect(timingReference(b, [{ ...a, request: { ...a.request, amount: 500 } }])).toBeUndefined(); + expect(timingReference(b, [createComparison('comparison-3', { caseId: 'normal', approvalAge: '0' })])).toBeUndefined(); + }); +}); diff --git a/apps/aps-demo/src/components/CaseProgress.tsx b/apps/aps-demo/src/components/CaseProgress.tsx new file mode 100644 index 0000000..d457e3f --- /dev/null +++ b/apps/aps-demo/src/components/CaseProgress.tsx @@ -0,0 +1,22 @@ +import type { ComparisonRun } from '../domain/comparison.ts'; + +/** A timing comparison is meaningful only when every other request field and baseline agree. */ +export function timingReference(run: ComparisonRun | undefined, runs: ComparisonRun[]): ComparisonRun | undefined { + if (!run || run.caseId !== 'stale') return undefined; + const withoutAge = (item: ComparisonRun) => JSON.stringify({ ...item.request, approvalAge: undefined }); + return runs.find(other => other.id !== run.id && other.caseId === run.caseId + && other.request.approvalAge !== run.request.approvalAge + && withoutAge(other) === withoutAge(run) + && JSON.stringify(other.baseline) === JSON.stringify(run.baseline)); +} + +export function CaseProgress({ current, hasRun, dirty, timing, varied, ready, onCompare, onExplore, onPosition }: { + current: 1 | 2 | 3; hasRun: boolean; dirty: boolean; timing: boolean; varied: boolean; ready: boolean; + onCompare: () => void; onExplore: () => void; onPosition: () => void; +}) { + return ; +} diff --git a/apps/aps-demo/src/components/ComparisonView.tsx b/apps/aps-demo/src/components/ComparisonView.tsx index adaa0bb..0d17841 100644 --- a/apps/aps-demo/src/components/ComparisonView.tsx +++ b/apps/aps-demo/src/components/ComparisonView.tsx @@ -1,6 +1,6 @@ import type { ComparisonRun, LaneResult } from '../domain/comparison.ts'; import type { Mode } from '../domain/scenarios.ts'; -import { getCase } from '../domain/cases.ts'; +import { laneMeaning, runTitle } from '../domain/presentation.ts'; import { Badge } from './shared.tsx'; export const laneLabels: Record = { A: 'No modeled checks', B: 'Tool permission + spend limit', C: 'Lifecycle checks added' }; @@ -10,10 +10,12 @@ export function outcomeLabel(result: LaneResult) { } function Lane({ result }: { result: LaneResult }) { - return
+ const meaning = laneMeaning(result); + return

{laneLabels[result.mode]}

{outcomeLabel(result)}

{result.reason}

+

{meaning.label}

{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}
  • )}
@@ -24,7 +26,6 @@ function Lane({ result }: { result: LaneResult }) { 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'); @@ -34,7 +35,7 @@ export function ComparisonView({ run, showBaseline = false, compact = false }: { : `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

+

{runTitle(run)} · {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}

diff --git a/apps/aps-demo/src/components/DiscussionWorksheet.test.tsx b/apps/aps-demo/src/components/DiscussionWorksheet.test.tsx index a69ba08..39282ff 100644 --- a/apps/aps-demo/src/components/DiscussionWorksheet.test.tsx +++ b/apps/aps-demo/src/components/DiscussionWorksheet.test.tsx @@ -5,10 +5,14 @@ import { SessionProvider, useSession } from './SessionContext.tsx'; import { DiscussionWorksheet } from './DiscussionWorksheet.tsx'; function Controls() { - const { runComparison, setApprovalAge, selectRun, runs, selectedRun, discussions } = useSession(); + const { runComparison, setApprovalAge, setCase, selectRun, runs, selectedRun, discussions, updateDiscussion } = useSession(); return <> + + + {(['normal', 'unauthorized', 'spending', 'replay', 'delegation', 'approval'] as const).map(id => )} + {selectedRun ? `${selectedRun.results.B.decision}/${selectedRun.results.C.decision}` : 'none'} @@ -60,6 +64,7 @@ describe('discussion remains reasoning bound to a comparison', () => { fireEvent.click(screen.getByRole('button', { name: 'Test fresh age' })); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); expect(screen.getByLabelText('Test outcome').textContent).toBe('allow/allow'); + expect(screen.getByText('Purchase with current approval')).toBeTruthy(); expect((screen.getByLabelText('Reason for this recommendation') as HTMLTextAreaElement).value).toBe(''); fireEvent.click(screen.getByRole('button', { name: 'Test select original' })); expect(screen.getByLabelText('Test outcome').textContent).toBe('allow/deny'); @@ -70,6 +75,7 @@ describe('discussion remains reasoning bound to a comparison', () => { it('requires an explicit clear action and retains the denied original after a recovery exploration', () => { setup(); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Obtain a new matching approval' } }); fireEvent.click(screen.getByRole('button', { name: 'Explore a fresh-approval request' })); expect(screen.getByLabelText('Test runs').textContent).toBe('2'); expect(screen.getByLabelText('Test outcome').textContent).toBe('allow/allow'); @@ -84,4 +90,142 @@ describe('discussion remains reasoning bound to a comparison', () => { fireEvent.click(screen.getByRole('button', { name: 'Clear comparisons and notes' })); expect(screen.getByLabelText('Test runs').textContent).toBe('0'); }); + + it('turns an information recommendation into a retained unresolved request without creating a recovery', () => { + setup(); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + expect(screen.queryByRole('button', { name: 'Explore a fresh-approval request' })).toBeNull(); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Gather more information' } }); + expect(screen.getByRole('heading', { name: 'Request the missing business evidence' })).toBeTruthy(); + expect(screen.getByRole('link', { name: 'Inspect the related recorded evidence →' }).getAttribute('href')).toContain('story=stale'); + fireEvent.change(screen.getByLabelText('What remains unknown?'), { target: { value: 'Existing question about the supplier.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Add this evidence request to my position' })); + const question = screen.getByLabelText('What remains unknown?') as HTMLTextAreaElement; + expect(question.value).toContain('Existing question about the supplier.'); + expect(question.value).toContain('Who can confirm'); + fireEvent.click(screen.getByRole('button', { name: 'Add this evidence request to my position' })); + expect(question.value.match(/Who can confirm/g)?.length).toBe(1); + expect(screen.getByLabelText('Test outcome').textContent).toBe('allow/deny'); + expect(screen.getByLabelText('Test runs').textContent).toBe('1'); + expect(screen.queryByRole('button', { name: 'Explore a fresh-approval request' })).toBeNull(); + }); + + it('attaches exact retained check evidence without overwriting notes or using dirty draft inputs', () => { + setup(); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + fireEvent.change(screen.getByLabelText('Supporting evidence'), { target: { value: 'Existing independently supplied observation.' } }); + fireEvent.change(screen.getByLabelText('Reason for this recommendation'), { target: { value: 'Keep the request on hold.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Mark ready for discussion' })); + fireEvent.click(screen.getByRole('button', { name: 'Test fresh age' })); + fireEvent.click(screen.getByRole('button', { name: 'Attach this comparison’s decisive check' })); + const evidence = screen.getByLabelText('Supporting evidence') as HTMLTextAreaElement; + expect(evidence.value).toContain('Existing independently supplied observation.'); + expect(evidence.value).toContain('comparison-1 (comparison-1-unused-nonce)'); + expect(evidence.value).toContain('Approval freshness: fail'); + expect(evidence.value).toContain('B allow; C deny'); + expect(evidence.value).toContain('not a recorded trial'); + expect(screen.getByLabelText('Test ready').textContent).toBe('draft'); + fireEvent.click(screen.getByRole('button', { name: 'Attach this comparison’s decisive check' })); + expect(evidence.value.match(/Illustrative comparison comparison-1/g)?.length).toBe(1); + fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + expect((screen.getByLabelText('Supporting evidence') as HTMLTextAreaElement).value).toBe(''); + fireEvent.click(screen.getByRole('button', { name: 'Attach this comparison’s decisive check' })); + expect((screen.getByLabelText('Supporting evidence') as HTMLTextAreaElement).value).toContain('No C check failed'); + fireEvent.click(screen.getByRole('button', { name: 'Test select original' })); + expect((screen.getByLabelText('Supporting evidence') as HTMLTextAreaElement).value).toContain('Existing independently supplied observation.'); + }); + + it('requires the matching retained input for a recovery and offers no recovery at 59 seconds', () => { + setup(); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Obtain a new matching approval' } }); + fireEvent.click(screen.getByRole('button', { name: 'Test fresh age' })); + expect((screen.getByRole('button', { name: 'Explore a fresh-approval request' }) as HTMLButtonElement).disabled).toBe(true); + fireEvent.click(screen.getByRole('button', { name: 'Use this comparison’s inputs' })); + expect((screen.getByRole('button', { name: 'Explore a fresh-approval request' }) as HTMLButtonElement).disabled).toBe(false); + fireEvent.click(screen.getByRole('button', { name: 'Test fresh age' })); + fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + expect(screen.queryByRole('option', { name: 'Hold the purchase and obtain a new matching approval' })).toBeNull(); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Verify business inputs' } }); + expect(screen.getByRole('heading', { name: 'Request the missing business evidence' })).toBeTruthy(); + expect(screen.queryByRole('button', { name: 'Explore a fresh-approval request' })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Test legacy recommendation' })); + expect(screen.getByRole('option', { name: 'Saved recommendation: Obtain a new matching approval' })).toBeTruthy(); + expect(screen.getByText(/Its approval is already current/)).toBeTruthy(); + expect(screen.queryByRole('button', { name: 'Explore a fresh-approval request' })).toBeNull(); + }); + + it('keeps policy proposals, missing evidence and dissent as distinct unresolved next steps', () => { + setup(); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Propose a policy revision' } }); + fireEvent.click(screen.getByRole('button', { name: 'Add this policy-review question' })); + expect((screen.getByLabelText('What remains unknown?') as HTMLTextAreaElement).value).toContain('fixed 60-second rule is unchanged'); + expect(screen.getByRole('link', { name: 'Inspect the relevant control and its limits →' }).getAttribute('href')).toContain('CTL-EXPIRY'); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Insufficient evidence' } }); + expect(screen.getByText(/Name the missing observation/)).toBeTruthy(); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Unresolved disagreement' } }); + expect(screen.getByText(/Record the competing interpretation/)).toBeTruthy(); + expect(screen.getByLabelText('Test outcome').textContent).toBe('allow/deny'); + expect(screen.getByLabelText('Test runs').textContent).toBe('1'); + }); + + it('asks case-specific questions for objectives and task provenance without inventing resolution', () => { + setup(); fireEvent.click(screen.getByRole('button', { name: 'Test conflict case' })); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Clarify competing objectives' } }); + expect(screen.getByRole('heading', { name: 'Ask what would make a trade-off acceptable' })).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'Add this evidence request to my position' })); + expect((screen.getByLabelText('What remains unknown?') as HTMLTextAreaElement).value).toContain('Which objective takes priority'); + expect(screen.getByLabelText('Test outcome').textContent).toBe('allow/review'); + expect(screen.queryByRole('button', { name: 'Explore a fresh-approval request' })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Test context case' })); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Resolve task provenance' } }); + expect(screen.getByRole('heading', { name: 'Request evidence of task provenance' })).toBeTruthy(); + expect(screen.getByRole('link', { name: 'Inspect the related recorded evidence →' }).getAttribute('href')).toContain('story=context'); + expect(screen.getByLabelText('Test outcome').textContent).toBe('allow/deny'); + }); + + it('does not show another comparison’s readiness feedback after changing runs', () => { + setup(); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + fireEvent.change(screen.getByLabelText('Reason for this recommendation'), { target: { value: 'Hold this request.' } }); + fireEvent.click(screen.getByRole('button', { name: 'Mark ready for discussion' })); + expect(screen.getByText(/Position marked ready for discussion/)).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'Test fresh age' })); + fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + expect(screen.queryByText(/Position marked ready for discussion/)).toBeNull(); + expect(screen.getByLabelText('Test ready').textContent).toBe('draft'); + }); + + + it('places the selected investigation immediately before the writing fields', () => { + setup(); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Gather more information' } }); + const next = screen.getByRole('region', { name: 'Request the missing business evidence' }); + const rationale = screen.getByLabelText('Reason for this recommendation'); + expect(next.compareDocumentPosition(rationale) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(screen.getByLabelText('Recommended next action').compareDocumentPosition(next) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + }); + + it.each([ + ['normal', 'Verify business inputs', 'Request the missing business evidence', 'quotation, stock record'], + ['unauthorized', 'Restore role boundaries', 'Investigate who may perform this operation', 'Which role should submit'], + ['spending', 'Review the proposed amount', 'Investigate why the amount exceeds the ceiling', 'quantity and quotation'], + ['replay', 'Reconcile the prior attempt', 'Reconcile what happened to the prior attempt', 'whether the original request already executed'], + ['delegation', 'Inspect the delegation chain', 'Find why delegation did not terminate', 'Which worker owns completion'], + ])('offers relevant next steps for the %s case without suggesting renewed approval', (id, recommendation, heading, question) => { + setup(); fireEvent.click(screen.getByRole('button', { name: `Test ${id} case` })); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + const initialOutcome = screen.getByLabelText('Test outcome').textContent; + expect(screen.queryByRole('option', { name: 'Hold the purchase and obtain a new matching approval' })).toBeNull(); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: recommendation } }); + expect(screen.getByRole('heading', { name: heading })).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'Add this evidence request to my position' })); + expect((screen.getByLabelText('What remains unknown?') as HTMLTextAreaElement).value).toContain(question); + expect(screen.getByLabelText('Test outcome').textContent).toBe(initialOutcome); + expect(screen.queryByRole('button', { name: 'Explore a fresh-approval request' })).toBeNull(); + }); + + it('still offers obtaining approval for a missing-approval request without inventing a modeled recovery', () => { + setup(); fireEvent.click(screen.getByRole('button', { name: 'Test approval case' })); fireEvent.click(screen.getByRole('button', { name: 'Test run comparison' })); + expect(screen.getByRole('option', { name: 'Hold the purchase and obtain a new matching approval' })).toBeTruthy(); + fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Obtain a new matching approval' } }); + expect(screen.getByText(/This comparison has no modeled fresh-approval recovery branch/)).toBeTruthy(); + expect(screen.queryByRole('button', { name: 'Explore a fresh-approval request' })).toBeNull(); + }); + }); diff --git a/apps/aps-demo/src/components/DiscussionWorksheet.tsx b/apps/aps-demo/src/components/DiscussionWorksheet.tsx index bbd8177..a424afe 100644 --- a/apps/aps-demo/src/components/DiscussionWorksheet.tsx +++ b/apps/aps-demo/src/components/DiscussionWorksheet.tsx @@ -2,11 +2,107 @@ import { useState } from 'react'; import { emptyDiscussion } from '../domain/session.ts'; import type { DiscussionDraft } from '../domain/session.ts'; import { getCase } from '../domain/cases.ts'; +import { routeLink } from '../data.ts'; +import { runTitle } from '../domain/presentation.ts'; +import type { ComparisonRun } from '../domain/comparison.ts'; import { useSession } from './SessionContext.tsx'; import { Badge } from './shared.tsx'; type Confirmation = 'load' | 'delete' | 'clear' | null; +function investigationFor(run: ComparisonRun) { + if (run.caseId === 'conflict') return { + perspectives: [['Procurement perspective', 'Speed and availability matter, but proceeding may commit the team to a choice finance cannot support.'], ['Finance perspective', 'Budget and authorization matter, but a hold leaves the procurement objective unresolved.']], + primary: ['Clarify competing objectives', 'Clarify the competing objectives and who can resolve them'], + gatherLabel: 'Gather the constraints and evidence needed to compare the objectives', + gatherTitle: 'Ask what would make a trade-off acceptable', + question: 'Which objective takes priority, what constraints are non-negotiable, and who has authority to resolve the disagreement?', + gatherDetail: 'Record the competing objectives, their owners and the evidence needed to compare them. The recorded budget case does not demonstrate objective arbitration.', + policyLabel: 'Propose an objective-review process for later review', + policyQuestion: 'What escalation process and accountable decision owner should handle conflicting objectives? This proposal does not resolve them.', + residual: 'A review request does not decide which objective should win. What evidence and accountable judgment would justify a resolution?', + }; + if (run.caseId === 'context') return { + perspectives: [['Purchase perspective', 'The worker needs usable information for this purchase, but receiving information does not establish that it belongs to this task.'], ['Provenance perspective', 'Task binding needs a trustworthy origin and scope; repeating the same claim does not verify either.']], + primary: ['Resolve task provenance', 'Establish the correct task and trusted source before another attempt'], + gatherLabel: 'Investigate the task mismatch and information source', + gatherTitle: 'Request evidence of task provenance', + question: 'Which task does this information belong to, which trusted source establishes that binding, and what must be corrected before another attempt?', + gatherDetail: 'Identify the expected task, the supplied context and the trusted source of their relationship. The related recorded case changes context at demand, not this purchase boundary.', + policyLabel: 'Propose a provenance-checking process for later review', + policyQuestion: 'What source may establish task binding, and what should happen when provenance cannot be checked?', + residual: 'A matching task reference does not establish that its contents are true. What independent source supports the information?', + }; + if (run.caseId === 'unauthorized') return { + perspectives: [['Supplier perspective', 'The supplier may supply a quotation, but that role does not authorize purchase execution.'], ['Purchase perspective', 'An authorized purchase worker needs a valid request and the appropriate approvals before acting.']], + primary: ['Restore role boundaries', 'Identify the authorized role and preserve the supplier boundary'], + gatherLabel: 'Check the intended actor, tool scope and request origin', + gatherTitle: 'Investigate who may perform this operation', + question: 'Which role should submit this purchase, and what trusted evidence establishes that role and its permitted tools?', + gatherDetail: 'Trace why a supplier-origin request reached the purchase tool. Identify the authorized route without granting the supplier broader access or treating a referral as approval.', + policyLabel: 'Propose a role-boundary change for later review', + policyQuestion: 'What role separation and request routing should prevent a supplier from executing a purchase?', + residual: 'Correct tool scope does not establish a valid purchase. What additional authorization and business facts are required?', + }; + if (run.caseId === 'spending') return { + perspectives: [['Procurement perspective', 'The proposed amount may reflect a need, an incorrect quantity or a stale price. Its basis needs examination.'], ['Budget perspective', 'The request exceeds the modeled ceiling. A rationale alone cannot waive that constraint.']], + primary: ['Review the proposed amount', 'Verify the amount and scope before proposing another request'], + gatherLabel: 'Gather the quantity, quotation and budget basis', + gatherTitle: 'Investigate why the amount exceeds the ceiling', + question: 'What quantity and quotation support this amount, and can the intended work fit within the authorized budget?', + gatherDetail: 'Check the amount against the underlying need, quotation and budget. Record whether the request needs correction or an accountable budget review; this app does not revise the ceiling.', + policyLabel: 'Propose a budget-control change for later review', + policyQuestion: 'What evidence and accountable review would justify changing the spend ceiling without bypassing authorization?', + residual: 'Being within a ceiling would not establish that the purchase is necessary or correctly priced.', + }; + if (run.caseId === 'replay') return { + perspectives: [['Delivery perspective', 'A missing or delayed response can leave uncertainty about whether work completed.'], ['Uniqueness perspective', 'A reused request identity can duplicate an effect; another attempt needs reconciliation first.']], + primary: ['Reconcile the prior attempt', 'Check the prior request and its receipt before another attempt'], + gatherLabel: 'Gather the original request identity and completion evidence', + gatherTitle: 'Reconcile what happened to the prior attempt', + question: 'What receipt or authoritative state establishes whether the original request already executed?', + gatherDetail: 'Look for the original request identity and completion evidence. Do not assume that a missing response means no effect, or that a new identity makes a repeated action safe.', + policyLabel: 'Propose a replay-handling process for later review', + policyQuestion: 'How should request identity, receipts and reconciliation prevent duplicate effects when responses are uncertain?', + residual: 'A denied duplicate does not by itself establish the original business outcome; that needs separate evidence.', + }; + if (run.caseId === 'delegation') return { + perspectives: [['Task perspective', 'Delegation should move work toward a bounded objective rather than circulate responsibility.'], ['Execution perspective', 'The chain has exceeded its allowed depth; continuing requires understanding where responsibility or the stop condition was lost.']], + primary: ['Inspect the delegation chain', 'Identify the responsible owner and a bounded delegation plan'], + gatherLabel: 'Inspect the delegation chain and its stopping condition', + gatherTitle: 'Find why delegation did not terminate', + question: 'Which worker owns completion, why was work delegated again, and what stop condition should bound the chain?', + gatherDetail: 'Identify the task owner, delegation chain and stopping condition. A higher depth limit alone does not establish that the work will terminate or remain within budget.', + policyLabel: 'Propose a delegation-boundary change for later review', + policyQuestion: 'What ownership, depth and resource constraints would bound delegation while allowing the task to finish?', + residual: 'Stopping a chain leaves its task unresolved. What evidence supports a bounded way to finish it?', + }; + return { + perspectives: [['Procurement perspective', 'The requested work still needs a response. A blocked action can leave the purchase outstanding.'], ['Finance perspective', 'Authority must apply to this action at the time it is attempted. A prior approval may no longer be valid.']], + primary: !run.request.approved || run.request.approvalAge >= 60 + ? ['Obtain a new matching approval', 'Hold the purchase and obtain a new matching approval'] + : ['Verify business inputs', 'Verify business inputs before treating the purchase as complete'], + gatherLabel: run.results.C.executed ? 'Check the quotation, stock record and demand behind the permitted request' : 'Check the quotation or demand before proposing a new attempt', + gatherTitle: 'Request the missing business evidence', + question: 'Who can confirm that the quotation, stock record and underlying demand are still valid for this purchase?', + gatherDetail: 'Ask for a current quotation and the source of the demand or stock record. This app has no live quotation feed; the question remains unresolved until evidence is supplied outside this illustration.', + policyLabel: run.caseId === 'stale' ? 'Propose a different expiry policy for later review' : 'Propose a change to the relevant control for later review', + policyQuestion: run.caseId === 'stale' ? 'What evidence would justify a different approval lifetime, and who should review its risks? The fixed 60-second rule is unchanged.' : 'Which request condition needs a different control, what evidence supports the proposal, and who should review it?', + residual: 'Even with passing checks, what establishes that the quotation, stock record, or underlying demand is correct?', + }; +} + +function decisiveEvidence(run: ComparisonRun) { + const failed = run.results.C.checks.find(check => check.status === 'fail'); + const observation = failed ? `C check ${failed.rule}: ${failed.status} — ${failed.reason}.` : `No C check failed. Reached checks: ${run.results.C.checks.filter(check => check.status === 'pass').map(check => check.rule).join(', ')}.`; + return `Illustrative comparison ${run.id} (${run.requestIdentity}): B ${run.results.B.decision}; C ${run.results.C.decision}. ${observation} This is browser-model evidence, not a recorded trial or operational authorization.`; +} + +function appendDistinct(existing: string, addition: string) { + return existing.includes(addition) ? existing : [existing.trimEnd(), addition].filter(Boolean).join('\n\n'); +} + + function downloadBrief(contents: string, extension: 'json' | 'md') { const blob = new Blob([contents], { type: extension === 'json' ? 'application/json' : 'text/markdown;charset=utf-8' }); const url = URL.createObjectURL(blob); @@ -21,13 +117,15 @@ function downloadBrief(contents: string, extension: 'json' | 'md') { export function DiscussionWorksheet() { const { - selectedRun, runs, discussions, updateDiscussion, forkFreshApproval, + selectedRun, runs, discussions, updateDiscussion, forkFreshApproval, isDirty, selectRun, saveLocal, loadLocal, deleteSaved, clearSession, storageMessage, exportJSON, exportMarkdown, configLink, } = useSession(); const [confirmation, setConfirmation] = useState(null); - const [feedback, setFeedback] = useState(''); + const [feedback, setFeedbackState] = useState<{ runId?: string; text: string }>({ text: '' }); + const setFeedback = (text: string) => setFeedbackState({ runId: selectedRun?.id, text }); const draft = selectedRun ? discussions[selectedRun.id] ?? emptyDiscussion() : emptyDiscussion(); + const investigation = selectedRun ? investigationFor(selectedRun) : null; const canFork = selectedRun?.caseId === 'stale' && selectedRun.request.approvalAge >= 60 && selectedRun.results.C.decision === 'deny' @@ -65,13 +163,13 @@ export function DiscussionWorksheet() { {selectedRun ? <>
- {getCase(selectedRun.caseId).title} + {runTitle(selectedRun)}

Reasoning for {selectedRun.id} · {selectedRun.request.amount} sandbox units · approval age {selectedRun.request.approvalAge} logical seconds.

Model B: {selectedRun.results.B.decision.toUpperCase()} · Model C: {selectedRun.results.C.decision.toUpperCase()}. Selecting another run opens its own worksheet.

+ {isDirty &&

Your inputs have changed. This position still belongs to {selectedRun.id} and its retained outcomes, not the unevaluated inputs.

}
-

Procurement perspective

The requested work still needs a response. A blocked action can leave the purchase outstanding.

-

Finance perspective

Authority must apply to this action at the time it is attempted. A prior approval may no longer be valid.

+ {investigation!.perspectives.map(([title, body]) =>

{title}

{body}

)}
{ event.preventDefault(); @@ -86,42 +184,49 @@ export function DiscussionWorksheet() { +
+

YOUR NEXT STEP

+ {draft.recommendation === 'Obtain a new matching approval' ? <> +

Explore what a new matching approval would change

+ {canFork ? <>

Start both comparison lanes from C’s unchanged state with a new request identity and a fresh matching approval. Assume the task and context remain valid. The denied attempt and its discussion remain available.

Hypothetical recovery; not demonstrated by the recorded trial. This app cannot issue finance approval or continue B’s already executed purchase.

{isDirty &&

Restore this comparison’s inputs above before exploring its recovery.

} :

This comparison has no modeled fresh-approval recovery branch. {selectedRun.caseId === 'stale' ? 'Its approval is already current; renewing it would not answer the remaining business questions.' : 'Identify the failed request condition and the authority needed before proposing another attempt.'} No new approval or outcome is created.

} + : draft.recommendation === 'Gather more information' || draft.recommendation === investigation!.primary[0] ? <> +

{investigation!.gatherTitle}

{investigation!.gatherDetail}

+

Evidence request · unresolved: {investigation!.question}

+

Inspect the related recorded evidence →

+ : draft.recommendation === 'Propose a policy revision' ? <> +

Frame a proposal for human review

{investigation!.policyQuestion}

A proposal does not alter either control bundle or resolve an outstanding condition.

Inspect the relevant control and its limits →

+ : draft.recommendation === 'Insufficient evidence' || draft.recommendation === 'Unresolved disagreement' ? <> +

Keep the decision open

{draft.recommendation === 'Unresolved disagreement' ? 'Record the competing interpretation and identify who needs to participate in resolving it.' : 'Name the missing observation and who could provide it before proposing that work proceeds.'}

{investigation!.question}

+ : <>

Choose an investigation to continue

Select a recommendation above to see the information, review or hypothetical exploration it calls for. You can also leave the position unresolved.

} +