}
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 <>
+
+
+
+
+
+
+ >;
+}
+
+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 ;
+}
+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
{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 => )}
+
@@ -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 ? <>
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.
-
- {draft.ready ? 'Ready for discussion · not approval' : 'Draft · changes retained in this session'}
+
Attach the observed modeled check to your position. This does not add recorded or external evidence.
+ Inspect supporting evidence
+
+
+ Record assumptions or disagreement
+
+
+
+
{draft.ready ? 'Ready for discussion · not approval' : 'Draft · changes retained in this session'}
- {canFork &&
-
Explore a possible next attempt
-
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. This preserves the denied attempt and does not continue B’s already executed purchase.
-
Hypothetical recovery; not demonstrated by the recorded trial. The browser does not issue a finance approval.
-
-
}
-
Passing the modeled checks leaves a question open
Even with a fresh approval, what establishes that the quotation, stock record, or underlying demand is correct?
{[!draft.recommendation && 'Recommendation unresolved', !draft.evidence.trim() && 'Evidence not yet attached', !draft.question.trim() && 'State what would change your mind'].filter(Boolean).join(' · ') || 'Evidence and an open question are recorded; their quality and resolution still need human review.'}
This position belongs to {selectedRun.id}. Marking it ready invites discussion; it does not verify the evidence or authorize an action.
+
Passing the modeled checks leaves a question open
{investigation!.residual}
> :
Run a comparison to attach a recommendation to its exact inputs and outcomes. You can also load an explicitly saved local session below.
Selected trial #{trial.sequence} ({trial.configuration}). B #{b?.sequence ?? 'unavailable'} and C #{c?.sequence ?? 'unavailable'} share the recorded case identity and digest. Rows align by actor, action and occurrence; missing calls are not filled in.
+ const divergence = b && c ? rows.find(row => row.b?.decision !== row.c?.decision || row.b?.executed !== row.c?.executed) : undefined;
+ const divergenceIndex = divergence ? rows.indexOf(divergence) + 1 : null;
+ const citation = divergence && b && c ? `Related recorded evidence, not this browser execution: case ${trial.case_id}, digest ${trial.case_digest}; B trial #${b.sequence} / C trial #${c.sequence}; paired event ${divergence.b?.actor ?? divergence.c?.actor} → ${divergence.b?.action ?? divergence.c?.action}. B: ${divergence.b ? `${divergence.b.decision}, ${divergence.b.executed ? 'executed' : 'not executed'}` : 'not reached / not recorded'}; C: ${divergence.c ? `${divergence.c.decision}, ${divergence.c.executed ? 'executed' : 'not executed'}` : 'not reached / not recorded'}.` : null;
+ return
{trial.case_id} · recorded comparison
Selected trial #{trial.sequence} ({trial.configuration}). {b && c ? `B #${b.sequence} and C #${c.sequence} share the recorded case identity and digest.` : 'One or both comparison arms are absent; missing records are not evidence of agreement.'} Rows align by actor, action and occurrence; missing calls are not filled in.
{b && c ? 'No difference in recorded decisions or execution flags between these paired calls.' : 'A complete recorded B/C comparison is unavailable.'}
}
+ {divergence &&
Start with the event that changed the outcome
Paired step {divergenceIndex}: {divergence.b?.actor ?? divergence.c?.actor} → {divergence.b?.action ?? divergence.c?.action}. Earlier shared calls remain available in the full trace below.
Decisive recorded B/C event
B · scope + budget
C · extended workflow checks
A violation flag describes the request; check the execution flag to see whether it produced an effect.
{onAttach && citation && }}
+ Inspect all {rows.length} paired recorded steps
The full retained order is shown, including calls with equal outcomes. Missing calls are not filled in.
+
Recorded B/C calls. A violation on a denied request does not mean an unsafe effect executed.
;
}
diff --git a/apps/aps-demo/src/components/FailurePath.tsx b/apps/aps-demo/src/components/FailurePath.tsx
index 257e285..9fcce4a 100644
--- a/apps/aps-demo/src/components/FailurePath.tsx
+++ b/apps/aps-demo/src/components/FailurePath.tsx
@@ -1,28 +1,26 @@
import { useState } from 'react';
import type { ComparisonRun } from '../domain/comparison.ts';
import { getCase } from '../domain/cases.ts';
+import { decisionPath, laneMeaning } from '../domain/presentation.ts';
import { routeLink } from '../data.ts';
import { Badge } from './shared.tsx';
export function FailurePath({ run }: { run: ComparisonRun }) {
- const [selected, setSelected] = useState('checks');
+ const [selected, setSelected] = useState('condition');
const definition = getCase(run.caseId);
- const c = run.results.C;
- const terminal = c.checks.find(check => check.status === 'fail');
- const stages = [
- { id: 'approval', title: 'Declared prerequisites', type: 'Declared assumption', detail: `${run.request.approved ? 'A matching finance approval is assumed available.' : 'A matching finance approval is absent.'} Earlier procurement workers are context for this illustration; they were not executed here.`, value: run.request.approved ? 'Approval available' : 'Approval absent' },
- { id: 'delay', title: 'Logical delay', type: 'Modeled input', detail: `Approval age is ${run.request.approvalAge} logical seconds. C requires age below 60 seconds. Playback and time spent reading this page do not age the request.`, value: `${run.request.approvalAge}s since approval` },
- { id: 'request', title: 'Same request', type: 'Modeled input', detail: `${definition.operation}. Actor: ${run.request.actor}; amount: ${run.request.amount} sandbox units. Both lanes evaluate the same frozen input.`, value: `${run.request.actor} · ${run.request.amount} units` },
- { id: 'checks', title: 'Decision boundary', type: 'Modeled event', detail: terminal ? `C stops at ${terminal.rule}: ${terminal.reason}. Later checks are not evaluated. B ${run.results.B.decision === 'allow' ? 'permits the request under its selected checks' : 'also rejects this request'}.` : 'All modeled C checks pass. Passing these conditions does not establish that the quotation or demand is correct.', value: terminal?.rule ?? 'All C checks pass' },
- { id: 'effects', title: 'Effects and next action', type: 'Modeled outcome', detail: `${run.results.B.businessOutcome} ${c.businessOutcome} ${definition.limitation}`, value: c.decision === 'deny' ? 'C: no effect' : c.decision === 'review' ? 'C: review pending' : 'C: permitted effect' },
- ];
- const active = stages.find(stage => stage.id === selected) ?? stages[3];
+ const stages = decisionPath(run);
+ const active = stages.find(stage => stage.id === selected) ?? stages[1];
return
-
Follow the failure path
Illustrative path · not live agents
-
Select a stage to inspect the condition and its consequence. Both branches share everything before the decision boundary.
+
Follow the decision path
Illustrative path · not live agents
+
Follow the condition from the shared request to the two decisions. Select a stage to distinguish an assumed prerequisite, a supplied input and a modeled consequence.
{effect ? `Orders ${effect.before.orders} → ${effect.after.orders}; sandbox spend ${effect.before.spend} → ${effect.after.spend}.` : 'Downstream effects are not modeled for this case.'}
Financial loss, changed supplier prices and delivery failures are possible consequences, not measured events in this browser model. A blocked purchase remains outstanding. A fresh approval does not establish that the underlying quotation, forecast or stock record is true.
The broader procurement topology describes system relationships. This path does not simulate independent agent reasoning or a cascading operational incident.
+
{(['B', 'C'] as const).map(mode => {
+ const result = run.results[mode];
+ const meaning = laneMeaning(result);
+ return
{result.effect ? result.businessOutcome : 'Downstream business effects are not modeled for this case.'}
;
+ })}
+
Question for the people responsible: {run.caseId === 'conflict' ? 'Who should resolve the competing objectives, and what information would justify that decision?' : run.results.C.executed ? 'What evidence would establish that the permitted purchase is actually needed and its inputs are correct?' : 'What information or authority would justify a different next attempt while the work remains outstanding?'}
+ What this path does not show
{definition.limitation}
Financial loss, changed supplier prices and delivery failures are possible consequences, not measured events in this browser model. The broader procurement topology describes relationships; this path does not simulate independent agent reasoning or a cascading operational incident.
;
}
diff --git a/apps/aps-demo/src/domain/presentation.test.ts b/apps/aps-demo/src/domain/presentation.test.ts
new file mode 100644
index 0000000..7229840
--- /dev/null
+++ b/apps/aps-demo/src/domain/presentation.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest';
+import { caseDefinitions, presetDraft } from './cases.ts';
+import { createComparison } from './comparison.ts';
+import { decisionPath, laneMeaning, runTitle } from './presentation.ts';
+
+const stale = (age: number) => createComparison('comparison-1', { caseId: 'stale', approvalAge: String(age) });
+
+describe('retained run presentation', () => {
+ it('describes current inputs without relabeling an expired historical request', () => {
+ const expired = stale(61);
+ const current = stale(59);
+ expect(runTitle(expired)).toBe('Purchase after approval expiry');
+ expect(runTitle(current)).toBe('Purchase with current approval');
+ expect(runTitle(stale(60))).toBe('Purchase after approval expiry');
+ expect(expired.request.approvalAge).toBe(61);
+ expect(current.caseId).toBe('stale');
+ });
+ it('labels renewed approval as a hypothetical child with its parent intact', () => {
+ const parent = stale(61);
+ const child = createComparison('comparison-2', { caseId: 'stale', approvalAge: '0' }, undefined, parent);
+ expect(runTitle(child)).toBe('Hypothetical purchase with renewed approval');
+ expect(decisionPath(child)[0].detail).toContain('earlier C lane’s unchanged state');
+ expect(parent.results.C.executed).toBe(false);
+ });
+ it('separates execution status from the validity meaning of the result', () => {
+ expect(laneMeaning(stale(61).results.B)).toEqual({ tone: 'violation', label: 'Invalid condition carried into execution' });
+ expect(laneMeaning(stale(61).results.C)).toEqual({ tone: 'held', label: 'Modeled boundary held · request stopped' });
+ expect(laneMeaning(stale(59).results.C).tone).toBe('clear');
+ expect(laneMeaning(stale(59).results.A).label).toContain('No checks applied');
+ expect(laneMeaning(createComparison('comparison-1', presetDraft('conflict')).results.C)).toEqual({ tone: 'review', label: 'Review needed · question unresolved' });
+ });
+});
+
+describe('case-specific decision path', () => {
+ it.each(caseDefinitions)('$id has five bounded stages and cannot change its request or results', definition => {
+ const run = createComparison('comparison-1', presetDraft(definition.id));
+ const original = JSON.stringify(run);
+ const path = decisionPath(run);
+ expect(path.map(stage => stage.id)).toEqual(['premise', 'condition', 'request', 'checks', 'effects']);
+ expect(path[2].detail).toContain('same starting state');
+ expect(path[2].detail).toContain('Only their check bundles differ');
+ expect(path[2].value).toContain(String(run.request.amount));
+ if (definition.effectMode === 'unmodeled') {
+ expect(path[4].type).toBe('Unmodeled business outcome');
+ expect(path[4].value).toBe('No downstream effects projected');
+ expect(path[4].detail).toContain('Business effects are not modeled');
+ }
+ expect(JSON.stringify(run)).toBe(original);
+ });
+ it.each([59, 60, 61])('makes the strict expiry boundary concrete at age %i', age => {
+ const path = decisionPath(stale(age));
+ expect(path[1].title).toBe(age < 60 ? 'Approval remains current' : 'Approval expires');
+ expect(path[1].value).toContain(`${age}s`);
+ expect(path[1].detail).toContain('Age 60 already fails');
+ expect(path[4].title).toBe(age < 60 ? 'Illustrative order created' : 'Purchase remains outstanding');
+ expect(path[4].type).toBe('Illustrative projection');
+ });
+ it('frames objective conflict without irrelevant elapsed time or invented arbitration', () => {
+ const path = decisionPath(createComparison('comparison-1', presetDraft('conflict')));
+ expect(path[0].title).toBe('Competing goals declared');
+ expect(path[1].title).toBe('Trade-off remains unresolved');
+ expect(path[3].title).toBe('C asks for a human decision');
+ expect(path[3].detail).toContain('no arbitration or human authorization occurs');
+ expect(path[4].title).toBe('Decision remains outstanding');
+ expect(JSON.stringify(path)).not.toMatch(/logical seconds|Approval expires|C: .* orders/);
+ });
+ it('keeps context substitution separate from a live prompt-injection claim', () => {
+ const path = decisionPath(createComparison('comparison-1', presetDraft('context')));
+ expect(path[1].title).toBe('Context belongs elsewhere');
+ expect(path[1].detail).toContain('not an observed agent following injected instructions');
+ expect(path[1].detail).toContain('related recorded case tests a demand-stage request');
+ });
+ it('uses the actual preset condition for authority, spend, delegation, approval and replay', () => {
+ const expected = [
+ ['unauthorized', 'Purchase authority absent', 'Actor: supplier'],
+ ['spending', 'Request exceeds ceiling', '1200 sandbox units requested'],
+ ['delegation', 'Delegation exceeds limit', 'Depth 4 · limit 3'],
+ ['approval', 'Matching approval absent', 'Approval flag: missing'],
+ ['replay', 'Nonce marked consumed', 'Replay flag: true'],
+ ] as const;
+ for (const [caseId, title, value] of expected) {
+ const path = decisionPath(createComparison('comparison-1', presetDraft(caseId)));
+ expect(path[1]).toMatchObject({ title, value });
+ }
+ });
+});
diff --git a/apps/aps-demo/src/domain/presentation.ts b/apps/aps-demo/src/domain/presentation.ts
new file mode 100644
index 0000000..a7e0081
--- /dev/null
+++ b/apps/aps-demo/src/domain/presentation.ts
@@ -0,0 +1,74 @@
+import type { ComparisonRun, LaneResult } from './comparison.ts';
+import { getCase } from './cases.ts';
+
+/** Describe a retained input, rather than borrowing a preset's original outcome. */
+export function runTitle(run: ComparisonRun): string {
+ if (run.parent) return 'Hypothetical purchase with renewed approval';
+ if (run.caseId === 'stale' && run.request.approvalAge < 60) return 'Purchase with current approval';
+ return getCase(run.caseId).title;
+}
+
+export function laneMeaning(result: LaneResult) {
+ if (result.executedViolations.length) return { tone: 'violation', label: 'Invalid condition carried into execution' } as const;
+ if (result.decision === 'review') return { tone: 'review', label: 'Review needed · question unresolved' } as const;
+ if (result.decision === 'deny') return { tone: 'held', label: 'Modeled boundary held · request stopped' } as const;
+ return { tone: 'clear', label: result.mode === 'A' ? 'No checks applied · wider questions remain' : 'Declared checks pass · wider questions remain' } as const;
+}
+
+export interface PathStage { id: string; title: string; type: string; detail: string; value: string }
+
+/** Explanatory views of frozen inputs and decisions; these never simulate events. */
+export function decisionPath(run: ComparisonRun): PathStage[] {
+ const r = run.request;
+ const definition = getCase(run.caseId);
+ const assumed = 'Declared assumption';
+ const input = 'Modeled input';
+ let opening: [PathStage, PathStage];
+ switch (run.caseId) {
+ case 'stale': opening = [
+ { id: 'premise', title: run.parent ? 'New approval assumed' : 'Finance approval assumed', type: assumed, value: r.approved ? 'Matching approval available' : 'Approval absent', detail: run.parent ? 'A new matching finance approval is assumed for this hypothetical request. Both lanes start from the earlier C lane’s unchanged state; no finance worker issued an approval here.' : 'The request assumes a matching finance approval was available before this attempt. The browser does not run the finance worker or check a quotation.' },
+ { id: 'condition', title: r.approvalAge >= 60 ? 'Approval expires' : 'Approval remains current', type: input, value: `${r.approvalAge}s · ${r.approvalAge >= 60 ? 'outside' : 'inside'} the below-60s rule`, detail: `At ${r.approvalAge} logical seconds, the approval ${r.approvalAge >= 60 ? 'has reached or passed' : 'has not reached'} its 60-second boundary. Age 60 already fails the fixed “below 60” rule. Reading this page does not age the request.` },
+ ]; break;
+ case 'unauthorized': opening = [
+ { id: 'premise', title: 'Supplier role declared', type: assumed, value: 'Quotations are the intended work', detail: 'The supplier role is intended to provide quotations. This case asks what happens when a request instead attempts the purchase tool.' },
+ { id: 'condition', title: r.actor === 'purchase' ? 'Purchase authority present' : 'Purchase authority absent', type: input, value: `Actor: ${r.actor}`, detail: `The frozen actor is ${r.actor}. Both B and C restrict purchase tool use to the purchase actor; an added lifecycle check is not needed to stop this mismatch.` },
+ ]; break;
+ case 'spending': opening = [
+ { id: 'premise', title: 'Spend ceiling declared', type: assumed, value: 'Maximum 1000 sandbox units', detail: 'Both selected bundles apply the same positive-amount and 1000-unit ceiling. This is a model policy, not a live account balance.' },
+ { id: 'condition', title: r.amount > 1000 ? 'Request exceeds ceiling' : 'Amount within ceiling', type: input, value: `${r.amount} sandbox units requested`, detail: `The requested amount is ${r.amount} against a ceiling of 1000. The actor can have tool permission while this amount is still impermissible.` },
+ ]; break;
+ case 'delegation': opening = [
+ { id: 'premise', title: 'Bounded delegation intended', type: assumed, value: 'Depth at most three', detail: 'The intended work permits bounded delegation. A depth limit is a modeled condition; this view does not execute a chain of workers.' },
+ { id: 'condition', title: r.depth > 3 ? 'Delegation exceeds limit' : 'Delegation within limit', type: input, value: `Depth ${r.depth} · limit 3`, detail: `This request carries delegation depth ${r.depth}. B does not inspect it; C checks depth at most three. Resource exhaustion and downstream timing are not simulated.` },
+ ]; break;
+ case 'approval': opening = [
+ { id: 'premise', title: 'Matching approval required', type: assumed, value: 'Authority must match the purchase', detail: 'Finance authorization must match the requested purchase. Tool permission alone does not supply that authorization.' },
+ { id: 'condition', title: r.approved ? 'Matching approval present' : 'Matching approval absent', type: input, value: r.approved ? 'Approval flag: present' : 'Approval flag: missing', detail: `The request marks matching approval as ${r.approved ? 'present' : 'absent'}. The browser evaluates this supplied condition; it does not contact finance or issue approval.` },
+ ]; break;
+ case 'replay': opening = [
+ { id: 'premise', title: 'One execution intended', type: assumed, value: 'A purchase nonce may be used once', detail: 'The intended condition is uniqueness of the purchase attempt. The browser does not reconstruct an earlier order or its effects.' },
+ { id: 'condition', title: r.replay ? 'Nonce marked consumed' : 'Nonce marked unused', type: input, value: r.replay ? 'Replay flag: true' : 'Replay flag: false', detail: `The frozen request marks its nonce as ${r.replay ? 'already consumed' : 'unused'}. C checks this replay condition. The input flag is not a newly observed duplicate purchase.` },
+ ]; break;
+ case 'conflict': opening = [
+ { id: 'premise', title: 'Competing goals declared', type: assumed, value: 'Speed and finance constraints', detail: 'The stated objective is to balance procurement speed and finance constraints. No priorities, trade-off costs or arbitration process are supplied by this browser model.' },
+ { id: 'condition', title: r.objectivesResolved ? 'Objectives marked resolved' : 'Trade-off remains unresolved', type: input, value: r.objectivesResolved ? 'Resolved input: true' : 'Resolved input: false', detail: `The input marks objectives as ${r.objectivesResolved ? 'resolved' : 'unresolved'}. A request for human review does not decide which objective should prevail or resolve the disagreement.` },
+ ]; break;
+ case 'context': opening = [
+ { id: 'premise', title: 'Task-bound context required', type: assumed, value: 'Information must belong to this task', detail: 'The purchase must use context bound to its own task. Content that is plausible is not automatically authoritative for this request.' },
+ { id: 'condition', title: r.contextBound ? 'Context belongs to this task' : 'Context belongs elsewhere', type: input, value: r.contextBound ? 'Binding flag: true' : 'Binding flag: false', detail: `The purchase request marks task binding as ${r.contextBound ? 'valid' : 'invalid'}. This models a binding condition, not an observed agent following injected instructions. The related recorded case tests a demand-stage request.` },
+ ]; break;
+ case 'normal': opening = [
+ { id: 'premise', title: 'Authorized purchase intended', type: assumed, value: 'Matching task and approval assumed', detail: 'The illustration assumes a matching approval and task context for one purchase. These prerequisites are inputs, not independently verified business facts.' },
+ { id: 'condition', title: 'Declared inputs satisfy checks', type: input, value: `${r.approvalAge}s approval · ${r.amount} sandbox units`, detail: `The request uses the ${r.actor} actor, ${r.amount} sandbox units, approval age ${r.approvalAge}, and the preset binding and uniqueness conditions. Both selected bundles permit it; additional checks need not change the outcome.` },
+ ]; break;
+ }
+ const b = run.results.B;
+ const c = run.results.C;
+ const terminal = c.checks.find(check => check.status === 'fail');
+ const bAction = b.decision === 'allow' ? 'permits the request' : b.decision === 'deny' ? 'also stops the request' : 'requests review';
+ return [...opening,
+ { id: 'request', title: 'Request reaches the checks', type: input, value: `${r.actor} · ${r.amount} sandbox units`, detail: `Both B and C receive this exact frozen ${r.actor} request for ${r.amount} sandbox units and the same starting state. Only their check bundles differ. No independent agents execute here.` },
+ { id: 'checks', title: c.decision === 'review' ? 'C asks for a human decision' : c.decision === 'deny' ? 'C stops at the condition' : 'Both bundles permit the request', type: 'Modeled decision', value: terminal?.rule ?? 'All C checks pass', detail: terminal ? `C stops at ${terminal.rule}: ${terminal.reason}. Later checks are not evaluated. B ${bAction}. ${c.decision === 'review' ? 'The conflict remains open; no arbitration or human authorization occurs.' : 'Stopping execution does not complete the outstanding work.'}` : 'All modeled C checks pass, and B also permits this request. A permitted request does not establish that the quotation, stock record or demand is correct.' },
+ { id: 'effects', title: c.decision === 'review' ? 'Decision remains outstanding' : c.effect && !c.executed ? 'Purchase remains outstanding' : c.effect ? 'Illustrative order created' : 'Business outcome unmeasured', type: c.effect ? 'Illustrative projection' : 'Unmodeled business outcome', value: c.effect ? c.executed ? `C: ${c.effect.before.orders} → ${c.effect.after.orders} orders` : 'C: no order created' : 'No downstream effects projected', detail: `B: ${b.businessOutcome} C: ${c.businessOutcome} ${definition.limitation}` },
+ ];
+}
diff --git a/apps/aps-demo/src/domain/session.ts b/apps/aps-demo/src/domain/session.ts
index fdd659e..f13cea4 100644
--- a/apps/aps-demo/src/domain/session.ts
+++ b/apps/aps-demo/src/domain/session.ts
@@ -1,6 +1,7 @@
import { getCase, isCaseId, presetDraft, validateDraft, type ScenarioDraft } from './cases.ts';
import { createComparison, MODEL_VERSION, type ComparisonRun, type Prediction } from './comparison.ts';
import type { StoryId } from './scenarios.ts';
+import { runTitle } from './presentation.ts';
export interface DiscussionDraft {
recommendation: string; rationale: string; evidence: string; assumptions: string;
@@ -148,7 +149,7 @@ export function discussionMarkdown(session: Session): string {
const lines = ['# APS discussion brief', '', 'Illustrative browser comparisons and local reasoning. No operational authorization or hazard approval.', '', `Model: ${MODEL_VERSION}`, ''];
for (const run of session.runs) {
const definition = getCase(run.caseId);
- lines.push(`## ${run.id}: ${definition.title}`, '', `Request identity: ${run.requestIdentity}`, `Actor: ${run.request.actor}; amount: ${run.request.amount} sandbox units; approval age: ${run.request.approvalAge} logical seconds.`, `Prediction: ${run.prediction.choice || 'Not supplied'}`, `Prediction rationale: ${run.prediction.rationale || 'Not supplied'}`, '');
+ lines.push(`## ${run.id}: ${runTitle(run)}`, '', `Request identity: ${run.requestIdentity}`, `Actor: ${run.request.actor}; amount: ${run.request.amount} sandbox units; approval age: ${run.request.approvalAge} logical seconds.`, `Prediction: ${run.prediction.choice || 'Not supplied'}`, `Prediction rationale: ${run.prediction.rationale || 'Not supplied'}`, '');
if (run.parent) lines.push(`Parent: ${run.parent.runId}, lane ${run.parent.lane}.`, '');
for (const mode of ['B', 'C', 'A'] as const) {
const lane = run.results[mode];
diff --git a/apps/aps-demo/src/routes/Assurance.tsx b/apps/aps-demo/src/routes/Assurance.tsx
index f35a757..ed2151c 100644
--- a/apps/aps-demo/src/routes/Assurance.tsx
+++ b/apps/aps-demo/src/routes/Assurance.tsx
@@ -8,6 +8,9 @@ import { Badge, Heading, Stat } from '../components/shared.tsx';
import { TestEvidence } from '../components/TestEvidence.tsx';
import { EvidenceComparison } from '../components/EvidenceComparison.tsx';
+import { runTitle } from '../domain/presentation.ts';
+import { CaseEvidenceBridge } from '../components/CaseEvidenceBridge.tsx';
+
type Trial = typeof experiment.trials[number];
function RecordedCharts() {
@@ -45,7 +48,8 @@ function TrialReplay({ trial }: { trial: Trial }) {
}
export function Assurance({ params }: { params: URLSearchParams }) {
- const { selectedRun, caseDefinition, setCase, resetInputs } = useSession();
+ const { selectedRun, caseDefinition, setCase, resetInputs, discussions, updateDiscussion, isDirty } = useSession();
+ const [attachment, setAttachment] = useState<{ runId: string; trial: number } | null>(null);
const requestedTrial = params.get('trial');
const requestedControl = params.get('control');
const knownControl = requestedControl && requirements.some(requirement => requirement.controls.some(control => control.id === requestedControl));
@@ -63,6 +67,12 @@ export function Assurance({ params }: { params: URLSearchParams }) {
const trials = experiment.trials.filter(trial => arm === 'all' || trial.configuration === arm).sort((a, b) => sort === 'fault' ? a.fault.localeCompare(b.fault) || a.sequence - b.sequence : a.sequence - b.sequence);
const variantCase = selectedTrial && caseDefinitions.find(item => item.fault === selectedTrial.fault);
const mismatch = selectedTrial && selectedTrial.fault !== activeCase.fault;
+ function attachRecordedEvent(citation: string) {
+ if (!selectedRun || !selectedTrial || mismatch || isDirty) return;
+ const current = discussions[selectedRun.id]?.evidence ?? '';
+ updateDiscussion(selectedRun.id, { evidence: current.includes(citation) ? current : [current, citation].filter(Boolean).join('\n\n'), ready: false });
+ setAttachment({ runId: selectedRun.id, trial: selectedTrial.sequence });
+ }
function tryVariation() {
if (!variantCase) return;
setCase(variantCase.id);
@@ -76,16 +86,17 @@ export function Assurance({ params }: { params: URLSearchParams }) {
{requestedTrial !== null && !exactTrial &&
No recorded trial matches “{requestedTrial}”. Select an existing trial from the ledger below. No substitute trial has been selected.
}
{requestedControl !== null && !knownControl &&
No control matches “{requestedControl}” in the frozen mappings. The catalogue below remains available; this is not evidence for that requested control.
The model shows how its declared checks respond to your input. It does not execute OPA, grant operational authority, or validate a quotation, stock record or business objective.
Selected trial “{selectedTrial.fault}” differs from the active browser case. The trial remains selected; it has not been substituted or presented as your browser run.
}
- {selectedTrial ? <>
Full request envelopes and before/after order or spend snapshots are not recorded in this view. No historical amount or state change is reconstructed from the browser model.
{variantCase &&
Opens an illustrative preset; historical inputs and results are not copied.
}> :
{requestedTrial !== null ? 'Choose a valid recorded trial below.' : 'No distinct recorded trial maps to this selection. An interactive illustration is not a substitute for missing execution evidence.'}
Recorded event attached to {attachment.runId}. Existing notes are retained; the position is a draft for discussion. Review your reasoning →
}
Full request envelopes and before/after order or spend snapshots are not recorded in this view. No historical amount or state change is reconstructed from the browser model.
{variantCase &&
Opens an illustrative preset; historical inputs and results are not copied.
}> :
{requestedTrial !== null ? 'Choose a valid recorded trial below.' : 'No distinct recorded trial maps to this selection. An interactive illustration is not a substitute for missing execution evidence.'}
}
{selectedTrial && }
What remains unknown?
{selectedTrial?.fault === 'stale_approval' ?
The recorded case tests an expired finance approval. It does not establish real quotation validity or a successful reapproval/recovery process. A current approval alone cannot establish that the price or demand is correct.
: selectedTrial?.fault === 'message_poisoning' ?
The recorded injection changes a context reference at demand_mock. The purchase-oriented browser illustration is related evidence, not the same execution or a live prompt-injection test.
:
{evidenceCase.limitation} The selected trial establishes only its recorded observations under the declared experiment conditions.
}
These A/B/C arms are selected control bundles, not a comparison of every conventional design against HAZOP. Tests and receipts do not establish that the complete system is safe.
-
Explore the trial ledger
Sanitized frozen trial records; selecting a row changes inspection only
{authorityNotes[control.id] ?? (control.status === 'gap' ? 'No implemented mechanism establishes the full meaning of this deviation. Further expert design is required.' : 'This control is linked to the separate research implementation. Browser inspection does not execute or authorize that implementation.')}
What remains unresolved
{control.gap}
{control.id === 'CTL-EXPIRY' &&
Expiry of finance approval is narrower than quotation validity. Even a fresh matching approval does not establish that the price, forecast or physical stock is correct.
}{control.id === 'GAP-CONFLICTING_OBJECTIVES' &&
The recorded goal-conflict case measures a simplified budget violation. It does not establish resolution of conflicting objectives. A discussion recommendation cannot close this gap.
}
-
- Illustrative browser comparison
How the selected run treated this condition
{selectedRun ? <>
Run {selectedRun.id}: {getCase(selectedRun.caseId).title}. These checks belong to its retained input snapshot.
{selectedRun.caseId !== caseDefinition.id &&
This retained run belongs to a different case from the current draft. It has not been relabeled as the draft case.
}{isDirty &&
Draft inputs have changed. This run still describes the original request; return to the Case Lab to evaluate the draft.
}
Actor {selectedRun.request.actor} · amount {selectedRun.request.amount} · approval age {selectedRun.request.approvalAge} logical seconds
{requirement.state}; effectiveness and risk acceptance remain unverified.
{requirement.controls.map(c =>
{c.description} →{c.id} · {c.status === 'gap' ? 'Explicit control gap' : 'Implementation link exists'} · {c.test === 'none' ? 'No test mapped' : c.test}
{c.gap}
)}
:
No direct authored requirement mapping for this node/deviation. Proposed safeguards require expert design.
}
{h.id === 'APS-f47191931b96a999a61c' &&
This authored finding concerns quotation validity. The interactive expiry case illustrates the narrower condition of finance-approval freshness; it does not establish whether an actual quotation is valid.
No interactive case for this finding. The source hypothesis remains available for review.
}
Original identity and provenance
{h.id}
Source scenario: {h.provenance.scenario_id} · generator {h.provenance.generator} · rule version {h.provenance.rule_version}
Original deviation: {h.deviation} · review: {h.review_state}
{requirement &&
{requirement.id}
}
-
Screening register
{rows.length} / 96 findings
Six nodes × sixteen deviations. This is examination coverage, not 96 independently validated discoveries. Filtering does not assign importance or risk.
Generated hazards, all unverified with null ratings
No findings match. Adjust the filters or search. The previously inspected finding remains above.
}
+ Search and browse all 96 findings
Screening register
{rows.length} / 96 findings
Six nodes × sixteen deviations. This is examination coverage, not 96 independently validated discoveries. Filtering does not assign importance or risk.
Generated hazards, all unverified with null ratings
No findings match. Adjust the filters or search. The previously inspected finding remains above.
}
Inspect the complete node × deviation matrix
Reference = authored scenario. Prompt = generic screening entry. Gap = an explicit gap in a mapped proposed control. These labels describe source coverage, not severity.
No authored references match the selected node and deviation.
}Review status and scope
>;
}
diff --git a/apps/aps-demo/src/routes/Overview.tsx b/apps/aps-demo/src/routes/Overview.tsx
index 1dfbcc9..919999c 100644
--- a/apps/aps-demo/src/routes/Overview.tsx
+++ b/apps/aps-demo/src/routes/Overview.tsx
@@ -20,11 +20,12 @@ export function Overview() {
return <>
An agent can have the right tool and stay within budget while acting on an approval that is no longer valid. Explore the difference between permission, authorization and evidence.
-
ILLUSTRATIVE CASE · NO LIVE OPERATIONS
The purchase arrived 61 seconds later.
Finance approved a purchase. The purchase agent has permission. The amount is within budget. But the approval is valid for less than 60 logical seconds.
Your taskCompare. Change. Explain.Follow both outcomes and decide what should happen next.
+
ILLUSTRATIVE CASE · NO LIVE OPERATIONS
The purchase request arrived 61 seconds later.
Finance approved a purchase. The purchase worker receives the request 61 logical seconds later. Its tool permission and budget still permit the action; the approval is valid for less than 60 seconds.
What will the controls do—and what should the people responsible do next?
Start with approval expiry. Normal authorization and unauthorized tool use show where both control bundles reach the same decision. Other cases expose additional modeled conditions and explicit gaps.
{c.effectMode === 'purchase' ? 'Illustrative purchase effects' : 'Effects beyond the rule decision are not modeled'}{c.fault ? 'Related recorded fault family' : 'No distinct recorded trial'}{c.id === 'conflict' && Objective arbitration remains an open gap.}Explore case →)}
+
One task depends on several earlier decisions.
Demand, inventory and supplier workers contribute information; finance supplies approval; purchase attempts the order. An orchestrator coordinates the work. The final worker must act on conditions that still hold when its request arrives.
Blocking an invalid request leaves the purchase outstanding. Renewing approval answers an authorization question, while the quotation, stock record and need for the purchase may still need checking. This illustration does not establish financial loss, delivery delay or independently reasoning agents.
+
Follow one action all the way through.
01
Compare the same request
See what tool and spend checks permit, then inspect the additional condition that changes the outcome.
02
Change a meaningful condition
Try 59, 60 and 61 seconds. Keep the original result and see exactly what changes.
03
Form a position
Choose what to investigate next, connect your recommendation to evidence, and state what would change your mind.
Start with approval expiry. Normal authorization and unauthorized tool use show where both control bundles reach the same decision. Other cases expose additional modeled conditions and explicit gaps.
{c.effectMode === 'purchase' ? 'Illustrative purchase effects' : 'Effects beyond the rule decision are not modeled'}{c.fault ? 'Related recorded fault family' : 'No distinct recorded trial'}{c.id === 'conflict' && Objective arbitration remains an open gap.}Explore case →)}
A method for asking better questions
APS connects intended behavior → possible deviation → proposed control → evidence → human judgment. These comparisons explain particular checks; they do not establish that HAZOP discovers better hazards than another review method.
A fresh approval still cannot establish that a quotation, forecast or stock record is correct.
Five specialized workers coordinate through an orchestrator. This diagram describes source relationships, not a live execution. Gateway and assurance are illustrative overlays, not extra agents.
Procurement topology
Solid: worker messages. Dashed: delegated control and illustrative overlays. Select an entity or use the equivalent buttons below.
Generated findings are hypotheses for expert review. Proposed controls and test links do not constitute risk acceptance, operational authority or safety certification.
- Compare the same request under two control bundles. Change a condition, follow the effect, then decide what needs further evidence.
-
+ First ask what the controls do. Then decide what the people responsible need before another action.
+ focusSection('case-input-panel')} onExplore={explore} onPosition={formPosition}/>
+
One shared request
Illustrative browser model
-
Intended objective
{caseDefinition.objective}
-
Actor
{input?.actor ?? caseDefinition.preset.actor}
Amount
{input?.amount ?? caseDefinition.preset.amount} sandbox units
Attempt
{caseDefinition.operation}
- {draft.caseId === 'stale' ?
{[59, 60, 61].map(age => )}
C requires a matching approval less than 60 logical seconds old. The validity rule stays fixed.
:
This preset holds request fields fixed. Approval age: {caseDefinition.preset.approvalAge} logical seconds. Explore the stale-approval case to change timing.
}
+
Intended objective
{caseDefinition.objective}
+
Actor
{input?.actor ?? caseDefinition.preset.actor}
Amount
{input?.amount ?? caseDefinition.preset.amount} sandbox units
Attempt
{draft.caseId === 'stale' ? 'Submit a purchase using an earlier finance approval' : caseDefinition.operation}
+
B · Tool permission + spend limit
Checks who may use the tool and whether the amount is within its limit.
C · Lifecycle checks added
Also checks conditions connecting the request to its task, approval and workflow.
+ {draft.caseId === 'stale' ?
{[59, 60, 61].map(age => )}
The declared approval lifetime is less than 60 logical seconds. This rule stays fixed while you vary request timing.
:
This preset holds request fields fixed so you can inspect {draft.caseId === 'conflict' ? 'the unresolved objective conflict' : draft.caseId === 'context' ? 'whether the request belongs to this task' : 'the selected condition'}. Its downstream business effects may remain unmodeled.
}
{configError || validation.error || ''}
Predict the outcome · optional
Your prediction is saved with this comparison for discussion. It is not a competence score.
Both lanes start from the same state. No real purchase executes.
- {isDirty && selectedRun &&
Inputs changed — run again. The retained results below still describe {selectedRun.id}: {getCase(selectedRun.caseId).title}, age {selectedRun.request.approvalAge}s.
}
+ {isDirty && selectedRun &&
Inputs changed — run again. The retained results below still describe {selectedRun.id}: {runTitle(selectedRun)}, age {selectedRun.request.approvalAge}s.
}
{selectedRun ? <>
Comparison results
{selectedRun.id}: B {selectedRun.results.B.decision}; C {selectedRun.results.C.decision}. Approval age {selectedRun.request.approvalAge} logical seconds.
Every run keeps its own inputs, prediction and discussion. Rerunning does not add another order to an earlier result.
{runs[0] && runs[0].id !== selectedRun.id && }
- {previous && Compare with a retained run
Selected: {selectedRun.id}, age {selectedRun.request.approvalAge}s — B {selectedRun.results.B.decision}, C {selectedRun.results.C.decision}.
Retained: {previous.id}, age {previous.request.approvalAge}s — B {previous.results.B.decision}, C {previous.results.C.decision}.
{selectedRun.caseId === previous.caseId ? 'Compare the snapshots below to see what changed.' : 'These are different cases; do not attribute the difference to approval age alone.'}
}
+
+
{isDirty ? 'Compare the changed request next' : timingBaseline ? 'What changed when timing changed?' : selectedRun.caseId === 'stale' ? 'Try the other side of the expiry boundary' : 'Inspect the condition, then form a position'}
+ {isDirty ? <>
Your earlier result remains intact. Run the changed input before drawing a new conclusion or forming its position.
> : <>
+ {timingBaseline ?
Retained request: {timingBaseline.request.approvalAge}s · B {timingBaseline.results.B.decision} · C {timingBaseline.results.C.decision}.
Selected request: {selectedRun.request.approvalAge}s · B {selectedRun.results.B.decision} · C {selectedRun.results.C.decision}.
Only approval age differs between these request inputs; both start from the same modeled state. {timingBaseline.results.C.decision === selectedRun.results.C.decision ? 'These ages stay on the same side of the validity boundary.' : 'The C decision changes at approval freshness.'} Neither result establishes quotation validity.
:
{selectedRun.caseId === 'stale' ? 'Change only approval age. Keep this result and run the new request to see whether either decision changes.' : 'The path names the request condition and where evaluation stops. Inspect it before deciding what evidence or ownership the outstanding question needs.'}
The purchase actor may have permission while its approval is no longer current. Run the comparison to see both decisions, the modeled order effect, and what remains unresolved.
Inspect the shared request.
Optionally predict the outcome.
Run both bundles together.
}
+
+
+ Inspect supporting hazards, controls and recorded evidence
Every run keeps its own inputs, prediction and discussion. Rerunning does not add another order to an earlier result.
{runs[0] && runs[0].id !== selectedRun.id && }
+ {previous && Compare with a retained run
Selected: {selectedRun.id}, age {selectedRun.request.approvalAge}s — B {selectedRun.results.B.decision}, C {selectedRun.results.C.decision}.
Retained: {previous.id}, age {previous.request.approvalAge}s — B {previous.results.B.decision}, C {previous.results.C.decision}.
{selectedRun.caseId === previous.caseId ? 'Compare the snapshots below to see what changed.' : 'These are different cases; do not attribute the difference to approval age alone.'}
}
+
+ > : <>
What will happen at the boundary?
Follow the same request through both bundles. After comparing their decisions, ask what would justify the next action.
Inspect the shared request and two bundles.
Optionally predict the outcome.
Run both bundles together.
>}
-
- Browse all nine cases and their evidence limits
{caseDefinitions.map(item =>
{item.title}
{item.objective}
{item.fault ? 'Related recorded fault family' : 'No distinct recorded trial'}
{item.limitation}
)}
+ Browse all nine cases and their evidence limits
{caseDefinitions.map(item =>
{item.title}
{item.objective}
{item.fault ? 'Related recorded fault family' : 'No distinct recorded trial'}
{item.limitation}
)}
;
}
diff --git a/apps/aps-demo/src/styles.css b/apps/aps-demo/src/styles.css
index c8f1ab8..2702328 100644
--- a/apps/aps-demo/src/styles.css
+++ b/apps/aps-demo/src/styles.css
@@ -49,15 +49,11 @@ main:focus { outline:none; }
.comparison-view .section-title { margin-bottom:16px; }
.comparison-lanes { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:16px; }
.comparison-lanes.with-baseline { grid-template-columns:repeat(3,minmax(0,1fr)); }
-.comparison-lane { border:1px solid var(--line); border-top:3px solid var(--teal); border-radius:10px; padding:20px; background:var(--panel); min-width:0; }
+.comparison-lane { border:1px solid var(--line); border-top:3px solid var(--muted); border-radius:10px; padding:20px; background:var(--panel); min-width:0; }
.comparison-lane h3 { margin:0 0 12px; font-size:15px; line-height:1.45; }
.comparison-lane p { font-size:13px; margin-bottom:10px; }
.lane-label { font-size:10px; color:var(--muted); text-transform:uppercase; letter-spacing:1px; display:block; margin-bottom:8px; }
.lane-result { display:block; font-size:23px; font-weight:750; letter-spacing:-.5px; margin:12px 0; }
-.lane-deny { border-top-color:var(--red); }
-.lane-deny .lane-result { color:var(--red); }
-.lane-review { border-top-color:var(--amber); }
-.lane-review .lane-result { color:var(--amber); }
.effect-summary { border-top:1px solid var(--line); padding-top:12px; margin-top:12px; }
.effect-summary p { margin:5px 0; }
.effect-summary dl { display:grid; grid-template-columns:1fr 1fr; gap:8px; }
@@ -244,3 +240,64 @@ main:focus { outline:none; }
.comparison-lanes.with-baseline > :first-child { grid-column:auto; }
.comparison-lanes.with-baseline > :last-child { grid-column:1 / -1; }
}
+
+/* Guided investigation: progress follows the retained run, not a score. */
+.case-progress { display:block; margin:0 0 24px; }
+.case-progress-list { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:10px; list-style:none; padding:0; margin:0; }
+.case-progress-list li { min-width:0; margin:0; }
+.case-progress-step { width:100%; min-height:76px; display:flex; flex-direction:column; align-items:flex-start; justify-content:center; gap:6px; text-align:left; padding:12px 16px; background:var(--panel); }
+.case-progress-step small { color:var(--muted); font-size:11px; font-weight:400; }
+.case-progress-step[aria-current=step] { border-color:var(--teal); box-shadow:inset 3px 0 var(--teal); background:var(--soft); }
+.case-progress-step:disabled { opacity:.7; cursor:default; }
+.bundle-introduction, .evidence-relationship-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:14px; margin:18px 0; }
+.bundle-introduction > *, .evidence-relationship-grid > * { min-width:0; padding:14px 16px; border:1px solid var(--line); border-radius:8px; background:var(--bg); }
+.bundle-introduction h3, .evidence-relationship-grid h3 { font-size:14px; margin:0 0 7px; }
+.bundle-introduction p, .evidence-relationship-grid p { font-size:13px; margin:0; }
+.journey-next { border-left:4px solid var(--teal); }
+.journey-next h2 { margin-top:0; }
+.variation-delta { border:1px solid var(--line); border-radius:8px; padding:14px 18px; margin:16px 0; background:var(--bg); }
+.variation-delta p { margin:5px 0; }
+.case-reference-links, .run-history-details, .reasoning-more, .recorded-full-trace { margin:20px 0; }
+.case-reference-links > summary, .run-history-details > summary, .reasoning-more > summary, .recorded-full-trace > summary { padding:10px 0; font-weight:650; }
+#case-input-panel, #case-path { scroll-margin-top:20px; }
+#case-input-panel:focus, #case-path:focus { outline:3px solid #edb44f; outline-offset:4px; }
+.comparison-lane.outcome-violation, .path-branch.outcome-violation { border-top:3px solid var(--red); }
+.comparison-lane.outcome-held, .path-branch.outcome-held { border-top:3px solid var(--teal); }
+.comparison-lane.outcome-review, .path-branch.outcome-review { border-top:3px solid var(--amber); }
+.comparison-lane.outcome-clear, .path-branch.outcome-clear { border-top:3px solid var(--muted); }
+.lane-result { color:var(--text); }
+.constraint-status-violation { background:var(--red-bg); color:var(--red); }
+.constraint-status-held { background:var(--soft); color:var(--teal); }
+.constraint-status-review { background:var(--amber-bg); color:var(--amber); }
+.path-context { margin:14px 0; font-size:13px; }
+.path-branch-status { display:block; margin:10px 0; font-size:13px; }
+.path-next-question { border-left:3px solid var(--teal); padding:12px 16px; background:var(--soft); }
+.investigation-next-step { margin:22px 0; padding:20px; border:1px solid var(--line); border-left:4px solid var(--teal); border-radius:8px; background:var(--soft); }
+.investigation-next-step h3 { margin-top:0; }
+.investigation-next-step p:last-child { margin-bottom:0; }
+.position-summary { margin:22px 0; padding:20px; background:var(--bg); border:1px solid var(--line); border-radius:8px; overflow-wrap:anywhere; }
+.position-summary h3 { margin-top:0; }
+.position-summary dl { margin-bottom:0; }
+.position-summary dt { font-size:12px; font-weight:700; margin-top:14px; }
+.position-summary dd { margin:4px 0 0; white-space:pre-wrap; font-size:13px; }
+.position-gaps { color:var(--muted); font-size:12px; }
+.evidence-attachment { display:flex; flex-wrap:wrap; align-items:center; gap:10px; margin:12px 0; }
+.reasoning-more .discussion-fields { margin-top:16px; }
+.case-evidence-bridge { margin:20px 0; border-left:4px solid var(--teal); }
+.evidence-relationship-grid { grid-template-columns:repeat(3,minmax(0,1fr)); }
+.investigation-return { display:flex; flex-wrap:wrap; gap:12px; margin-top:16px; }
+.decisive-recorded-event { margin:18px 0; border:1px solid var(--line); border-radius:8px; padding:14px; background:var(--soft); }
+.decisive-recorded-event table { margin:0; }
+@media(max-width:700px) {
+ .case-progress-list { gap:6px; }
+ .case-progress-step { font-size:11px; padding:10px; min-height:90px; overflow-wrap:anywhere; }
+ .case-progress-step small { font-size:10px; }
+ .bundle-introduction, .evidence-relationship-grid { grid-template-columns:1fr; gap:8px; }
+ .path-track { grid-template-columns:1fr; }
+ .path-track li:last-child { grid-column:auto; }
+ .path-track li::after { display:none; }
+ .path-track button { min-height:64px; }
+ .investigation-next-step, .position-summary { padding:15px; }
+ .investigation-next-step .button-row { flex-direction:column; align-items:stretch; }
+ .path-branch-status { font-size:11px; }
+}
diff --git a/apps/aps-demo/src/views.test.tsx b/apps/aps-demo/src/views.test.tsx
index ed6a22b..3e445d2 100644
--- a/apps/aps-demo/src/views.test.tsx
+++ b/apps/aps-demo/src/views.test.tsx
@@ -91,7 +91,7 @@ describe('paired case investigation', () => {
expect(original.results.C.effect?.after).toEqual({ orders: 0, spend: 0 });
changeAge('59');
expect(snapshot().isDirty).toBe(true); expect(snapshot().selectedRun).toEqual(original);
- expect(screen.getByText(/Inputs changed/)).toBeTruthy();
+ expect(document.querySelector('.draft-notice')?.textContent).toContain('Inputs changed');
runComparison();
expect(snapshot().selectedRun!.results.C.decision).toBe('allow');
expect(snapshot().selectedRun!.results.C.executedViolations).toEqual([]);
@@ -103,6 +103,52 @@ describe('paired case investigation', () => {
fireEvent.click(screen.getByRole('button', { name: 'Reset inputs' }));
expect(snapshot().runs).toHaveLength(3);
});
+ it('guides a draft-only timing variation into an explicit comparison and position', () => {
+ renderSession(); runComparison();
+ const original = snapshot().selectedRun!;
+ fireEvent.click(screen.getByRole('button', { name: 'Try 59 seconds' }));
+ expect(document.activeElement).toBe(screen.getByLabelText('Approval age (logical seconds)', { exact: true }));
+ expect(snapshot().selectedRun).toEqual(original);
+ expect(snapshot().runs).toHaveLength(1);
+ expect(snapshot().isDirty).toBe(true);
+ expect(screen.queryByLabelText('Timing variation comparison')).toBeNull();
+ runComparison();
+ 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');
+ expect(document.querySelector('.comparison-view')?.textContent).toContain('Purchase with current approval');
+ expect(document.querySelector('.failure-path')?.textContent).toContain('Approval remains current');
+ expect(document.querySelector('.failure-path')?.textContent).toContain('Both bundles permit the request');
+ fireEvent.click(screen.getByRole('button', { name: 'Form a position →' }));
+ expect(document.activeElement).toBe(document.getElementById('discussion'));
+ expect(snapshot().runs[0]).toEqual(original);
+ });
+ it('keeps missing evidence unresolved and attaches the selected run despite a changed draft', () => {
+ renderSession(); runComparison();
+ const original = snapshot().selectedRun!;
+ 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.queryByRole('button', { name: 'Explore a fresh-approval request' })).toBeNull();
+ fireEvent.change(screen.getByLabelText('What remains unknown?'), { target: { value: 'Is the quotation valid?' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add this evidence request to my position' }));
+ changeAge('59');
+ fireEvent.click(screen.getByText('Inspect supporting evidence', { exact: true }));
+ fireEvent.change(screen.getByLabelText('Supporting evidence'), { target: { value: 'No supplier confirmation yet.' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Attach this comparison’s decisive check' }));
+ const position = snapshot().discussions[original.id];
+ expect(position.question).toMatch(/Is the quotation valid\?[\s\S]*Who can confirm/);
+ expect(position.evidence).toContain('No supplier confirmation yet.');
+ expect(position.evidence).toContain(original.id);
+ expect(position.evidence).toContain(original.requestIdentity);
+ expect(position.evidence).toContain('Approval freshness');
+ expect(snapshot().selectedRun).toEqual(original);
+ expect(snapshot().runs).toHaveLength(1);
+ fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Obtain a new matching approval' } });
+ expect(screen.getByRole('button', { name: 'Explore a fresh-approval request' }).hasAttribute('disabled')).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Use this comparison’s inputs' }));
+ expect(snapshot().isDirty).toBe(false);
+ expect(screen.getByRole('button', { name: 'Explore a fresh-approval request' }).hasAttribute('disabled')).toBe(false);
+ });
it('rejects invalid age drafts without evaluating a different request', () => {
renderSession(); runComparison();
const original = snapshot().selectedRun;
@@ -118,7 +164,7 @@ describe('paired case investigation', () => {
for (const label of ['Choose a case', 'Approval age (logical seconds)', 'Prediction']) expect(exactLabels(document, label), label).toHaveLength(1);
runComparison();
for (const label of ['Selected comparison', 'Recommended next action']) expect(exactLabels(document, label), label).toHaveLength(1);
- fireEvent.click(screen.getByRole('button', { name: /Decision boundary/ }));
+ fireEvent.click(screen.getByRole('button', { name: /C stops at the condition/ }));
expect(screen.getByLabelText('Selected path stage').textContent).toContain('freshness');
expect(snapshot().runs).toHaveLength(1);
});
@@ -129,6 +175,7 @@ describe('paired case investigation', () => {
expect(screen.getByText(/Add a rationale before marking/)).toBeTruthy();
fireEvent.change(screen.getByLabelText('Recommended next action'), { target: { value: 'Obtain a new matching approval' } });
fireEvent.change(screen.getByLabelText('Reason for this recommendation'), { target: { value: 'Permission remains valid but the finance approval expired.' } });
+ fireEvent.click(screen.getByText('Record assumptions or disagreement', { exact: true }));
fireEvent.change(screen.getByLabelText('Dissent or another interpretation'), { target: { value: 'Fresh approval does not establish quotation validity.' } });
fireEvent.click(screen.getByRole('button', { name: 'Mark ready for discussion' }));
expect(snapshot().discussions[original.id].ready).toBe(true);
@@ -175,6 +222,8 @@ describe('full-app context and evidence', () => {
const prediction = 'Only the lifecycle checks inspect approval freshness.';
fireEvent.change(exactLabels(document, 'Why do you expect that?')[0], { target: { value: prediction } });
runComparison();
+ fireEvent.click(screen.getByText('Inspect supporting evidence', { exact: true }));
+ fireEvent.click(screen.getByText('Record assumptions or disagreement', { exact: true }));
const reasoning = {
'Reason for this recommendation': 'Keep the denied attempt for discussion.',
'Supporting evidence': 'Recorded stale approval comparison.',
@@ -237,6 +286,14 @@ describe('full-app context and evidence', () => {
it('pairs only retained records and replays inspection without changing the browser session', () => {
const frozen = JSON.stringify(experiment);
const { container } = renderSession();
+ const decisive = screen.getByRole('region', { name: 'Decisive recorded event' });
+ expect(decisive.textContent).toContain('purchase_mock');
+ expect(decisive.textContent).toContain('ALLOW · executed');
+ expect(decisive.textContent).toContain('DENY · not executed');
+ const trace = container.querySelector('.recorded-full-trace')!;
+ expect(trace.hasAttribute('open')).toBe(false);
+ fireEvent.click(within(trace as HTMLElement).getByText('Inspect all 10 paired recorded steps'));
+ expect(trace.hasAttribute('open')).toBe(true);
const pair = container.querySelector('.recorded-pair-table')!;
expect(pair.querySelectorAll('tbody tr')).toHaveLength(10);
const last = pair.querySelector('tbody tr:last-child')!;
diff --git a/docs/APS_GUIDED_INVESTIGATION.md b/docs/APS_GUIDED_INVESTIGATION.md
new file mode 100644
index 0000000..ad65327
--- /dev/null
+++ b/docs/APS_GUIDED_INVESTIGATION.md
@@ -0,0 +1,24 @@
+# APS guided investigation improvements
+
+This work follows the first-time walkthrough of the deployed redesign at main `2232a5536347cad5cd35c32a3608c3c818d186d9`. The scope is presentation and local investigation: recommendation-driven next steps, a clear compare/change/explain sequence, concrete case-specific causal paths, and relevant hazard/control/evidence inspection. Existing model behavior, frozen fixtures, original protected source, saved session format, and operational authority boundaries remain intact.
+
+Acceptance checks:
+
+- A recommendation changes the next investigation panel. Information gathering records an unresolved evidence question; only an eligible, explicitly chosen fresh-approval exploration creates a hypothetical child. Neither reasoning nor readiness changes prior outcomes.
+- Evidence attachments identify the actual selected run and modeled check, preserve authored notes, and survive navigation/save/export. Incomplete positions remain honestly incomplete.
+- The first visit introduces both control bundles, offers a clear next action after comparison, exposes the 61/59 variation, and leads into a position. Dirty inputs never relabel retained results. Existing routes and history remain usable.
+- Causal stages reflect each case's real inputs and modeled limits. Successful timing variations do not retain failure wording. Outcome styling distinguishes violated constraints, held boundaries, unresolved review and task status instead of treating execution as success.
+- Supporting screens explain approval/quotation, browser/recorded context-stage, and objective/arbitration differences before broader source records. Exact recorded pairing and complete source data remain accessible.
+- Desktop/mobile, light/dark, keyboard focus, accessible labels, static network behavior, immutable runs, saved sessions, and all nine cases retain regression coverage.
+
+Implemented across all five app routes. The opening introduces the control bundles and coordinated task; the Case Lab guides a retained comparison through a timing variation into a position. Recommendations reflect the actual case and approval state, with their investigation response immediately below the choice. Modeled-check and recorded-event attachments preserve authored notes and identify their different evidence sources. Case-specific causal stages and constraint-based emphasis replace generic failure framing. Supporting pages explain the relationship to source records before exposing the full registers and traces.
+
+Local verification on 2026-11-14:
+
+- 303 frontend tests across 14 files, frontend lint/typecheck and production build passed.
+- 233 built-site Chromium checks passed across all nine cases, retained comparisons, recommendation branches, reasoning/export/storage, supporting routes, keyboard operation, responsive sizes and both themes. No console/page errors or nonstatic requests were observed.
+- Static publication and frozen fixture checks passed. The production boundary retained all 70 original files and the exact three prior test additions; all 25 mutation tests passed.
+- 136 Linux-evidence verifier tests passed. The new candidate branch is explicitly allowlisted; the exact browser runner and its 233-check completion count are pinned without changing the deployment workflow or weakening artifact checks.
+- Independent semantic and design reviews found no remaining blocking issues after correcting recommendations for current approvals. Independent visual review accepted all seven desktop/mobile captures. Independent infrastructure review verified all final pins, reran the 136 verifier tests, and found no weakened checks.
+
+The browser checks and visual inspection establish the implemented behavior, not measured learning or operational decision quality. Follow-up actions remain illustrative evidence requests or hypothetical branches. The source-linked local receipts are under `.harness/guided-investigation-20261114/`; candidate CI and any deployment are separate states. Prior release receipts remain unchanged.
diff --git a/scripts/verify-linux-ci-evidence.mjs b/scripts/verify-linux-ci-evidence.mjs
index 7dfa5fa..1d791e5 100644
--- a/scripts/verify-linux-ci-evidence.mjs
+++ b/scripts/verify-linux-ci-evidence.mjs
@@ -10,7 +10,7 @@ process.chdir(fileURLToPath(new URL('../', import.meta.url)));
const repository = 'safetymp/agentic-process-safety';
const workflow = '.github/workflows/deploy-pages.yml';
const pins = {
- 'apps/aps-demo/scripts/e2e.mjs': '09f3ac4c7637988c34b1422df07724a8a84c3096b7a46129e775e7b2d3e3316b',
+ 'apps/aps-demo/scripts/e2e.mjs': '862012eff5b9fefe16e2f3829f453b86885e33ea96f6a18445b3d1fc07812ca8',
'apps/aps-demo/scripts/qa-evidence.mjs': '859c2a56553c93ad0f6a1e874ced2bfa51dbc1f7a9ec97ba15ba236783f01926',
[workflow]: '8a0a0126bfeba484e1b086cf8faecf872847c05146224bc237a1a331c4330e27',
};
@@ -45,8 +45,8 @@ export function verifyBrowserResult(result, reviewedAssertions) {
equal(result.status, 'passed', 'Browser assertions incomplete'); equal(result.engine, 'chromium', 'Chromium required');
equal(result.platform, 'linux', 'Linux browser');
assert.match(result.version, /^\d+\.\d+\.\d+\.\d+$/, 'Actual Chromium version');
- equal(result.experience, 'APS redesign increments 1–4', 'Reviewed redesigned experience');
- equal(result.assertions, 185, 'Complete assertion count for the pinned redesign runner');
+ equal(result.experience, 'APS guided investigation', 'Reviewed guided investigation experience');
+ equal(result.assertions, 233, 'Complete assertion count for the pinned guided investigation runner');
equal(reviewedAssertions, result.assertions, 'Reviewed assertion count');
equal(result.errors, [], 'Console/page errors'); equal(result.violations, [], 'Network violations');
equal(result.prefix, '/agentic-process-safety/', 'Pages base path'); equal(result.screenshots, captures, 'Seven capture calls');
diff --git a/scripts/verify-linux-ci-evidence.test.mjs b/scripts/verify-linux-ci-evidence.test.mjs
index 0ecf7dd..3ace388 100644
--- a/scripts/verify-linux-ci-evidence.test.mjs
+++ b/scripts/verify-linux-ci-evidence.test.mjs
@@ -8,10 +8,10 @@ import { evidenceEntries, gitBlobSha, verifyBrowserResult, verifyNodeVersion } f
// Synthetic unit fixtures test parsing and rejection, never actual CI provenance.
const result = () => ({
status: 'passed', platform: 'linux', engine: 'chromium', version: '140.0.7339.0',
- assertions: 185, experience: 'APS redesign increments 1–4', errors: [], violations: [], prefix: '/agentic-process-safety/',
+ assertions: 233, experience: 'APS guided investigation', errors: [], violations: [], prefix: '/agentic-process-safety/',
screenshots: ['overview', 'hazop', 'governance', 'simulator', 'assurance', 'mobile-light', 'mobile-dark'].map(n => `docs/screenshots/${n}.jpg`),
});
-test('accepts a correctly formatted complete browser result', () => verifyBrowserResult(result(), 185));
+test('accepts a correctly formatted complete browser result', () => verifyBrowserResult(result(), 233));
test('accepts actual Node 22 version format', () => verifyNodeVersion('v22.23.2'));
test('rejects other Node major and literal backslash escape', () => {
for (const version of ['v20.23.2', 'v220.1.0', 'v22\\.23.2']) assert.throws(() => verifyNodeVersion(version));
@@ -30,17 +30,18 @@ test('Git blob header uses byte length and NUL exactly as Git does', () => {
for (const [name, patch] of Object.entries({
failed: { status: 'failed' }, macOS: { platform: 'darwin' }, firefox: { engine: 'firefox' },
version: { version: '' }, escapedVersion: { version: '140\\.0\\.7339\\.0' },
- malformedVersion: { version: '140x0x7339x0' }, partial: { assertions: 184 }, legacyCount: { assertions: 137 }, inflatedCount: { assertions: 186 }, fractional: { assertions: 185.5 },
+ malformedVersion: { version: '140x0x7339x0' }, partial: { assertions: 232 }, legacyCount: { assertions: 137 }, inflatedCount: { assertions: 234 }, fractional: { assertions: 233.5 }, priorRedesignCount: { assertions: 185 },
missingExperience: { experience: undefined }, legacyExperience: { experience: 'Legacy app' },
+ previousRedesign: { experience: 'APS redesign increments 1–4' },
console: { errors: ['console error'] }, network: { violations: ['external request'] },
basePath: { prefix: '/' }, missingCaptures: { screenshots: [] },
-})) test(`rejects ${name} browser evidence`, () => assert.throws(() => verifyBrowserResult({ ...result(), ...patch }, 185)));
+})) test(`rejects ${name} browser evidence`, () => assert.throws(() => verifyBrowserResult({ ...result(), ...patch }, 233)));
test('rejects differing reviewed assertion count', () => assert.throws(() => verifyBrowserResult(result(), 139)));
-test('rejects absent result', () => assert.throws(() => verifyBrowserResult(undefined, 185)));
+test('rejects absent result', () => assert.throws(() => verifyBrowserResult(undefined, 233)));
test('postdeployment pin migration accepts only exact reviewed e2e/Pages bytes', () => {
const source = readFileSync(new URL('./verify-linux-ci-evidence.mjs', import.meta.url), 'utf8');
- const exact = ['09f3ac4c7637988c34b1422df07724a8a84c3096b7a46129e775e7b2d3e3316b', '8a0a0126bfeba484e1b086cf8faecf872847c05146224bc237a1a331c4330e27', '859c2a56553c93ad0f6a1e874ced2bfa51dbc1f7a9ec97ba15ba236783f01926'];
- const stale = ['b8a854c2f40421d0d71f635a21e27e971294c0633cf43079934edec123395684', '6086f2d7c5f8956d11b1cc04777f3ed527b80a2c96b87b728b3d31728bdaace2', '2725d66974b527c775f377dd2a4409bfc47658b6702cbc14b6ec1b5be9db8215'];
+ const exact = ['862012eff5b9fefe16e2f3829f453b86885e33ea96f6a18445b3d1fc07812ca8', '8a0a0126bfeba484e1b086cf8faecf872847c05146224bc237a1a331c4330e27', '859c2a56553c93ad0f6a1e874ced2bfa51dbc1f7a9ec97ba15ba236783f01926'];
+ const stale = ['09f3ac4c7637988c34b1422df07724a8a84c3096b7a46129e775e7b2d3e3316b', 'b8a854c2f40421d0d71f635a21e27e971294c0633cf43079934edec123395684', '6086f2d7c5f8956d11b1cc04777f3ed527b80a2c96b87b728b3d31728bdaace2', '2725d66974b527c775f377dd2a4409bfc47658b6702cbc14b6ec1b5be9db8215'];
const literalPins = [...source.matchAll(/: '([a-f0-9]{64})'/g)].map(match => match[1]);
assert.deepEqual(literalPins.sort(), [...exact].sort());
const currentPaths = ['apps/aps-demo/scripts/e2e.mjs', '.github/workflows/deploy-pages.yml', 'apps/aps-demo/scripts/qa-evidence.mjs'];
diff --git a/scripts/verify-linux-predeploy-evidence.mjs b/scripts/verify-linux-predeploy-evidence.mjs
index 011134c..85015ef 100644
--- a/scripts/verify-linux-predeploy-evidence.mjs
+++ b/scripts/verify-linux-predeploy-evidence.mjs
@@ -10,15 +10,15 @@ import { fileURLToPath } from 'node:url';
export const BOUNDS = Object.freeze({ archive: 64 * 1024 * 1024, expanded: 128 * 1024 * 1024, entry: 16 * 1024 * 1024, entries: 512, json: 2 * 1024 * 1024, source: 1000, dist: 128, depth: 20, nodes: 20000 });
export const REPOSITORY = 'safetymp/agentic-process-safety';
export const WORKFLOW = '.github/workflows/repository-checks.yml';
-export const RELEASE_HEAD_REFS = Object.freeze(['release/aps-github-validation-v1', 'codex/aps-redesign-release']);
+export const RELEASE_HEAD_REFS = Object.freeze(['release/aps-github-validation-v1', 'codex/aps-redesign-release', 'codex/aps-guided-investigation']);
export const CAPTURES = Object.freeze(['overview', 'hazop', 'governance', 'simulator', 'assurance', 'mobile-light', 'mobile-dark'].map(n => `docs/screenshots/${n}.jpg`));
// These expectations are reviewed source policy, never supplied by an artifact.
export const PINS = Object.freeze({
- [WORKFLOW]: 'df28d662f36f3610a46c192296b5792e4a362de737592e8e7be344d6544ec912',
+ [WORKFLOW]: '57f83716af8db23a02624fadfd86d51f0cc973cef45aa8aa7c886eba34e4109d',
'.github/workflows/deploy-pages.yml': '8a0a0126bfeba484e1b086cf8faecf872847c05146224bc237a1a331c4330e27',
- 'apps/aps-demo/scripts/e2e.mjs': '09f3ac4c7637988c34b1422df07724a8a84c3096b7a46129e775e7b2d3e3316b',
+ 'apps/aps-demo/scripts/e2e.mjs': '862012eff5b9fefe16e2f3829f453b86885e33ea96f6a18445b3d1fc07812ca8',
'apps/aps-demo/scripts/qa-evidence.mjs': '859c2a56553c93ad0f6a1e874ced2bfa51dbc1f7a9ec97ba15ba236783f01926',
- 'apps/aps-demo/scripts/validation-evidence.mjs': '48a503802f9efe3d1fb59ffe84b160541f9f96cb4316ae98ca17a208d6bc89c8',
+ 'apps/aps-demo/scripts/validation-evidence.mjs': '0c1474e3f899626586372476ddf4911dc3bf25e75c3620b01d88e7362fcd92c2',
'package-lock.json': '6350fea042ab97510b73aa1969e2469731753b5f95814caafa7f8d0ecbe7d303',
});
export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
@@ -220,7 +220,7 @@ export async function verifyPredeploy({ review, archive, api, now = Date.now() }
equal(identity.source, qaSource); equal(identity.sourceDigest, hash(JSON.stringify(qaSource))); equal(identity.dist, observed.dist); equal(identity.distDigest, review.distDigest);
equal(identity.browserResult, 'See browser-result.json only if assertions completed; absence means no browser pass.');
const result = json('.harness/ci-qa/browser-result.json'); keys(result, ['status', 'engine', 'version', 'platform', 'assertions', 'errors', 'violations', 'prefix', 'screenshots', 'experience']);
- equal(result.experience, 'APS redesign increments 1–4');
+ equal(result.experience, 'APS guided investigation');
equal(result.status, 'passed'); equal(result.platform, 'linux'); equal(result.engine, 'chromium'); equal(result.version, review.browserVersion); equal(result.assertions, review.assertions);
equal(result.errors, []); equal(result.violations, []); equal(result.prefix, '/agentic-process-safety/'); equal(result.screenshots, CAPTURES);
equal(observed.browserObservation, 'browser-result.json exists; independent verification required');
diff --git a/scripts/verify-linux-predeploy-evidence.test.mjs b/scripts/verify-linux-predeploy-evidence.test.mjs
index 5011dee..ea49a70 100644
--- a/scripts/verify-linux-predeploy-evidence.test.mjs
+++ b/scripts/verify-linux-predeploy-evidence.test.mjs
@@ -35,12 +35,12 @@ function fixture() {
const sourceDigest = hash(JSON.stringify(source)); const distDigest = hash(JSON.stringify(dist));
const runId = 123; const runAttempt = 2; const artifactId = 456;
const runUrl = 'https://github.com/SafetyMP/Agentic-Process-Safety/actions/runs/123/attempts/2';
- const browser = { status: 'passed', platform: 'linux', engine: 'chromium', version: '140.0.7339.0', assertions: 180, errors: [], violations: [], prefix: '/agentic-process-safety/', screenshots: [...CAPTURES], experience: 'APS redesign increments 1–4' };
+ const browser = { status: 'passed', platform: 'linux', engine: 'chromium', version: '140.0.7339.0', assertions: 233, errors: [], violations: [], prefix: '/agentic-process-safety/', screenshots: [...CAPTURES], experience: 'APS guided investigation' };
const images = new Map(CAPTURES.map((path, i) => [path, Buffer.concat([Buffer.from([0xff, 0xd8]), Buffer.alloc(1100, i), Buffer.from([0xff, 0xd9])])]));
const review = {
schema: 'aps-linux-predeploy-review-1', repository: REPOSITORY, repositoryId: 1430231911, pullRequest: 73,
headSha: head, baseSha: base, checkoutSha: checkout, checkoutTree: tree, workflowSha: checkout, workflowBlob, workflowRef,
- runId, runAttempt, artifactId, runUrl, reviewer: 'Synthetic unit reviewer', reviewedAt: '2026-10-25T20:00:00Z', limitations: 'Synthetic unit fixture; no browser or CI run occurred.', assertions: 180,
+ runId, runAttempt, artifactId, runUrl, reviewer: 'Synthetic unit reviewer', reviewedAt: '2026-10-25T20:00:00Z', limitations: 'Synthetic unit fixture; no browser or CI run occurred.', assertions: 233,
nodeVersion: 'v22.23.2', browserVersion: browser.version, sourceDigest, distDigest,
screenshots: Object.fromEntries([...images].map(([path, image]) => [path, { sha256: hash(image), accepted: true, observations: `Synthetic fixture ${path}; not a real visual review.` }])),
};
@@ -121,6 +121,10 @@ const mutations = {
'fork PR': f => { f.metadata.get('/pulls/73').head.repo.fork = true; },
'wrong head ref': f => { f.metadata.get('/pulls/73').head.ref = 'other'; },
'unreviewed branch resembling authorized redesign': f => { f.metadata.get('/pulls/73').head.ref = 'codex/aps-redesign-release-extra'; },
+ 'unreviewed branch resembling guided investigation': f => { f.metadata.get('/pulls/73').head.ref = 'codex/aps-guided-investigation-extra'; },
+ 'guided run branch substituted for a different allowed PR': f => { f.metadata.get('/actions/runs/123/attempts/2').head_branch = 'codex/aps-guided-investigation'; },
+ 'guided observed branch substituted for a different allowed PR': f => { f.observed.pullRequest.head.ref = 'codex/aps-guided-investigation'; },
+ 'prior redesign experience substituted for guided investigation': f => { f.browser.experience = 'APS redesign increments 1–4'; },
'run branch substituted with other allowed branch': f => { f.metadata.get('/actions/runs/123/attempts/2').head_branch = 'codex/aps-redesign-release'; },
'observed branch substituted with other allowed branch': f => { f.observed.pullRequest.head.ref = 'codex/aps-redesign-release'; },
'wrong redesigned browser experience': f => { f.browser.experience = 'Legacy app'; },