Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions components/Releases/AssessmentEvidenceSelection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import type { CompanyAssessmentSnapshot } from "@/lib/releases/assessmentTypes";
import { getAssessmentEvidenceChoices } from "@/lib/releases/assessmentEvidence/getAssessmentEvidenceChoices";
import { captureAssessmentEvidence } from "@/lib/releases/assessmentEvidence/captureAssessmentEvidence";
import { parseCapturedAssessmentEvidence } from "@/lib/releases/assessmentEvidence/parseCapturedAssessmentEvidence";

export default function AssessmentEvidenceSelection({
snapshot,
Expand All @@ -24,6 +25,8 @@ export default function AssessmentEvidenceSelection({
const [captured, setCaptured] =
useState<ReturnType<typeof captureAssessmentEvidence>>(null);
const [unavailable, setUnavailable] = useState(false);
const [recoveryText, setRecoveryText] = useState("");
const [recoveryError, setRecoveryError] = useState(false);
const validation = useAssessmentEvidenceValidation(
organizationId,
getAccessToken,
Expand Down Expand Up @@ -171,6 +174,69 @@ export default function AssessmentEvidenceSelection({
/>
</label>
)}
<details>
<summary className="cursor-pointer font-medium">
Recover a captured selection
</summary>
<p className="mt-2 text-muted-foreground">
Reopen the original saved assessment, then paste its captured
references. Recovery checks current access and the exact evidence
versions. It does not save a working view or send a follow-up to chat.
</p>
<label className="mt-2 block">
References to recover
<textarea
value={recoveryText}
maxLength={65536}
disabled={busy}
onChange={(event) => {
validation.invalidate();
setCaptured(null);
setRecoveryError(false);
setRecoveryText(event.target.value);
}}
className="mt-2 min-h-32 w-full rounded-lg border border-border bg-background p-3 font-mono text-xs"
/>
</label>
<Button
variant="outline"
className="min-h-11"
disabled={
disabled ||
!recoveryText.trim() ||
validation.status.state === "pending"
}
onClick={() => {
validation.invalidate();
setCaptured(null);
const recovered = parseCapturedAssessmentEvidence(recoveryText);
if (
!snapshot ||
!isCurrentSnapshot(snapshot) ||
!recovered ||
recovered.brief_id !== snapshot.id
) {
setRecoveryError(true);
return;
}
setRecoveryError(false);
setUnavailable(false);
setSelectedIds(
recovered.selected_evidence.map((row) => row.documentId),
);
setCaptured(recovered);
void validation.validate(recovered);
}}
>
Recover and check exact evidence
</Button>
{recoveryError && (
<p role="status">
References could not be recovered. Use the original captured
references and reopen their saved assessment.
</p>
)}
</details>
</section>
);
}
196 changes: 196 additions & 0 deletions components/Releases/__tests__/CompanyAssessmentRecovery.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
// @vitest-environment jsdom
import React from "react";
import {
act,
fireEvent,
render,
screen,
waitFor,
} from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import CompanyAssessment from "../CompanyAssessment";
import { captureAssessmentEvidence } from "@/lib/releases/assessmentEvidence/captureAssessmentEvidence";
import {
id,
snapshot,
} from "@/lib/releases/assessmentEvidence/__tests__/assessmentFixture";
const props = {
requestId: id(999),
organizationId: id(998),
getAccessToken: async () => "synthetic",
};
const reference = captureAssessmentEvidence(snapshot, [id(10)])!;
const available = {
snapshot,
evidence_validation: {
state: "available",
documents: [
{
documentId: id(10),
subjectId: id(50),
sourceVersionIds: [id(70)],
kind: "material",
identityConfirmed: true,
},
],
},
};
afterEach(() => vi.unstubAllGlobals());
async function open() {
const view = render(<CompanyAssessment {...props} />);
fireEvent.change(screen.getByLabelText("Saved assessment ID"), {
target: { value: snapshot.id },
});
fireEvent.click(
screen.getByRole("button", { name: "Open saved assessment" }),
);
await screen.findByText("Saved assessment reopened.");
return view;
}
function recover(value = JSON.stringify(reference)) {
fireEvent.change(screen.getByLabelText("References to recover"), {
target: { value },
});
fireEvent.click(
screen.getByRole("button", { name: "Recover and check exact evidence" }),
);
}
it("recovers serialized capture after unmount and rechecks exact versions with current authority", async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async (_url, init) => {
const body = JSON.parse(init!.body as string);
return Response.json(body.selected_evidence ? available : { snapshot });
});
vi.stubGlobal("fetch", fetcher);
const first = await open();
fireEvent.click(screen.getAllByRole("checkbox")[0]);
fireEvent.click(
screen.getByRole("button", { name: "Capture selection locally" }),
);
const serialized = (
screen.getByLabelText("Captured evidence references") as HTMLTextAreaElement
).value;
first.unmount();
await open();
expect(screen.queryByRole("list", { name: "Checked evidence" })).toBeNull();
recover(serialized);
await screen.findByRole("list", { name: "Checked evidence" });
expect(JSON.parse(fetcher.mock.calls[2][1]!.body as string)).toEqual({
action: "read_brief",
...reference,
explain_evidence_validation: true,
organization_id: props.organizationId,
});
expect(fetcher.mock.calls[2][1]).toMatchObject({
cache: "no-store",
headers: { Authorization: "Bearer synthetic" },
});
expect(fetcher).toHaveBeenCalledTimes(3);
});
it.each(["malformed", "other-brief", "extra-field", "missing-version"])(
"rejects %s without a lookup",
async (mode) => {
const fetcher = vi.fn<typeof fetch>(async () =>
Response.json({ snapshot }),
);
vi.stubGlobal("fetch", fetcher);
await open();
const value = structuredClone(reference);
if (mode === "other-brief") value.brief_id = id(800);
if (mode === "missing-version")
delete (
value.selected_evidence[0] as Partial<
(typeof value.selected_evidence)[0]
>
).version;
recover(
mode === "malformed"
? "{"
: JSON.stringify(
mode === "extra-field"
? { ...value, url: "https://example.invalid" }
: value,
),
);
await screen.findByText(/References could not be recovered/);
expect(fetcher).toHaveBeenCalledTimes(1);
expect(screen.queryByRole("list", { name: "Checked evidence" })).toBeNull();
},
);
it.each(["denied", "revoked", "superseded", "mismatched", "malformed"])(
"withholds recovered evidence on %s without fallback",
async (mode) => {
const response =
mode === "denied"
? new Response(null, { status: 403 })
: Response.json(
mode === "revoked"
? {
snapshot,
evidence_validation: {
state: "unavailable",
reason: "current_evidence_unavailable",
},
}
: mode === "malformed"
? { snapshot }
: {
...available,
snapshot: {
...snapshot,
...(mode === "superseded"
? { superseded: true }
: { id: id(800) }),
},
},
);
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ snapshot }))
.mockResolvedValueOnce(response);
vi.stubGlobal("fetch", fetcher);
await open();
recover();
await screen.findByText(
mode === "revoked"
? /could not be matched to current evidence/
: /Could not verify captured evidence/,
);
expect(screen.queryByRole("list", { name: "Checked evidence" })).toBeNull();
expect(fetcher).toHaveBeenCalledTimes(2);
expect(fetcher.mock.calls.every(([url]) => url === "/api/context")).toBe(
true,
);
},
);
it.each(["edit", "workspace"])(
"discards delayed recovery after %s",
async (mode) => {
let finish!: (response: Response) => void;
vi.stubGlobal(
"fetch",
vi
.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ snapshot }))
.mockImplementationOnce(
() =>
new Promise((resolve) => {
finish = resolve;
}),
),
);
const view = await open();
recover();
await waitFor(() => expect(finish).toBeTypeOf("function"));
if (mode === "edit")
fireEvent.change(screen.getByLabelText("References to recover"), {
target: { value: "{" },
});
else
view.rerender(<CompanyAssessment {...props} organizationId={id(997)} />);
await act(async () => finish(Response.json(available)));
expect(screen.queryByRole("list", { name: "Checked evidence" })).toBeNull();
expect(screen.queryByText(/Captured evidence was available/)).toBeNull();
},
);
30 changes: 30 additions & 0 deletions lib/releases/assessment-verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,33 @@ pnpm lint
A feature PR, local fixture, CI result or automatic preview build does not complete
hosted web/MCP acceptance. No manual deployment, production write, credential
rotation, paid action, client import or merge is part of this change.

## Captured-reference recovery — November 18, 2026

This recovery flow builds on the exact saved-ID readback check merged separately
in [App #2406](https://github.com/recoupable/app/pull/2406). That safety fix is
already on main; this change adds only local reference recovery and validation.

The evidence selection panel now accepts the exact JSON emitted by **Captured
evidence references** after the user reopens its original saved assessment.
Recovery parses only `brief_id` and the existing `selected_evidence` tuple, rejects
extra fields/malformed input and a different brief ID, then calls the existing
current-auth/current-organization `read_brief` validation. It preserves document,
result, subject, topic, document version and source-version identities without
reconstructing them from labels. Checked evidence is withheld until the exact
server response passes `readAssessmentEvidenceValidation`; editing the recovery
input or changing the assessment/workspace invalidates pending validation.

This is an explicit local reference roundtrip through the existing private Context
brief destination. Copying references is not a server save acknowledgement. The
historical assessment summary remains distinct from checked selection results.
There is no new working-surface store, generic artifact reference, model dispatch,
public upload, provider call or Files/path-move support. Unsupported/superseded
snapshots cannot enter this selection path. #2207 durable surface saves and #2231
broad artifact/destination acceptance remain incomplete.

`CompanyAssessmentRecovery.test.tsx` exercises capture → unmount → reopen → paste →
server revalidation, exact request fields/current organization, no-store, malformed
and foreign references, access denial, unavailable evidence, superseded/mismatched
responses, and delayed edit/workspace invalidation. These are synthetic mounted
component tests, not authenticated runtime or cross-host acceptance.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { z } from "zod/v4";
import { selectedBriefEvidenceSchema } from "./vendor/selectedBriefEvidenceSchema";

/** Parse the existing capture output only; this never grants evidence access. */
export function parseCapturedAssessmentEvidence(text: string) {
if (text.length > 65536) return null;
try {
const result = z
.strictObject({
brief_id: z.uuid(),
selected_evidence: selectedBriefEvidenceSchema,
})
.safeParse(JSON.parse(text));
return result.success ? result.data : null;
} catch {
return null;
}
}
Loading