Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {resolve} from "node:path";
import {createInterface} from "node:readline";
import {resolveTestPython} from "../../../../scripts/test-python.mjs";
import {launchBrowser, loadPlaywright} from "../../../../examples/dashboard-browser-smoke-support.mjs";
import {verifyResearchAcceptanceReadback} from "./research-verification-readback.mjs";

const repo = resolve(import.meta.dirname, "../../../..");
const root = await mkdtemp(resolve(tmpdir(), "loopx-evidence-version-"));
Expand Down Expand Up @@ -395,6 +396,7 @@ try {
assert.deepEqual(caseHistoryReads, [], "Explicit case links do not read the case's research history");
assert.equal(afterRecovery.mutation_attempts, beforeRecovery.mutation_attempts);
assert.equal(afterRecovery.source_unchanged, true);
await verifyResearchAcceptanceReadback(browser, start);
console.log("research evidence version: study and history navigation, saved excerpts and chapter position restored");
} finally {
releaseOriginal?.();
Expand Down
108 changes: 108 additions & 0 deletions apps/presentation/dashboard/smoke/research-verification-fixture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""Produce canonical synthetic events for the packaged Research readback."""
import hashlib
import json

from loopx.capabilities.explore.result_log import build_explore_finding_event, build_explore_node_event

GOAL = "research-verification-fixture"
BASELINE_REF = "artifact:baseline"
REJECTED_REF = "artifact:rejected-variant"
RESULT_REF = "artifact:result"
RECEIPT_REF = "receipt:external-verifier"
BASELINE_SHA = "a" * 64
RESULT_SHA = "b" * 64
EXACT = {
"metric": "loss", "unit": "points", "higher_is_better": False,
"comparison_scope": "scope:matched", "input_revision": "input-v1", "evaluation_ref": "check:exact",
}
PROXY = {**EXACT, "metric": "cost", "evaluation_ref": "check:proxy"}


def measurements(sha, ref, exact, proxy):
return [{**profile, "candidate_ref": f"sha256:{sha}", "evidence_ref": ref, "value": value}
for profile, value in ((EXACT, exact), (PROXY, proxy))]


def add_case(events, label, node_id, *, baseline_author="worker", late=False, revise=False, refuted=False, attempt=None):
if attempt in (None, 0):
events.append(build_explore_node_event(
goal_id=GOAL, node_id=node_id, title=label, agent_id="worker", recorded_at="2026-11-21T11:00:00Z",
))
case_id = node_id if attempt is None else f"{node_id}-{attempt}"
baseline_ref = BASELINE_REF if attempt is None else f"{BASELINE_REF}-{attempt}"
# A normal retained description makes repeated whole-row transport exceed
# the inline Effect frame on the 151-event pagination regression.
summary = "" if attempt is None else ("Measured on the same retained input and evaluation scope. " * 27).strip()
control = {
"goal_id": GOAL, "node_id": node_id, "finding_id": f"{case_id}-baseline",
"title": "Reference measurements", "status": "confirmed", "agent_id": baseline_author, "summary": summary,
"evidence_refs": [baseline_ref],
}
reference = build_explore_finding_event(
**control, recorded_at="2026-11-21T11:10:00Z",
measurements=measurements(BASELINE_SHA, baseline_ref, 9, 4),
)
if not late:
events.append(reference)
decision_refs = [baseline_ref]
if refuted:
events.append(build_explore_finding_event(
goal_id=GOAL, node_id=node_id, finding_id=f"{case_id}-refuted",
title="Rejected reference variant", status="refuted", agent_id="worker",
recorded_at="2026-11-21T11:20:00Z", evidence_refs=[REJECTED_REF],
))
decision_refs.append(REJECTED_REF)
ids = json.dumps([event["event_id"] for event in events], ensure_ascii=False, separators=(",", ":"))
binding = {"goal_id": GOAL, "agent_id": "worker", "todo_id": f"todo_{case_id}", "turn_instance_id": "turn-1"}
refs = [RESULT_REF, RECEIPT_REF, *decision_refs]
events.append(build_explore_finding_event(
goal_id=GOAL, node_id=node_id, finding_id=f"{case_id}-candidate",
title=label, summary=summary, status="confirmed", agent_id="worker", evidence_refs=refs,
recorded_at="2026-11-21T12:00:00Z",
execution_observation={
"schema_version": "explore_execution_observation_v0",
"candidate_sha256": RESULT_SHA, "result_candidate_sha256": RESULT_SHA, "result_ref": RESULT_REF,
"input_revision": "input-v1", "planned_method_id": "verify", "executed_method_id": "verify",
"change_reason": None, "elapsed_seconds": 1, "limit_seconds": None, "search_iterations": None,
"stop_reason": None, "evidence_refs": refs,
"verification_evidence": {
"host": "local-cli", "baseline": {"ref": baseline_ref, "sha256": BASELINE_SHA},
"proofs": {"external_verifier": {"criterion_id": "verify", "ref": RECEIPT_REF, "sha256": "c" * 64}},
},
},
work_binding=binding,
work_yardstick={
"binding": binding,
"decision": {
"schema_version": "work_yardstick_decision_v0",
"target": {"summary": "Reduce loss", "scope": "Frozen input", "acceptance_ref": "check:exact"},
"authoritative": EXACT, "proxy": PROXY, "counterevidence_refs": decision_refs, "prior_finding_id": None,
"next_action": {"method_id": "verify", "reason": "Compare fixed inputs", "cost_bound": "One evaluation"},
},
"source_snapshot": {"event_count": len(events), "event_ids_sha256": hashlib.sha256(ids.encode()).hexdigest()},
},
measurements=measurements(RESULT_SHA, RESULT_REF, 5, 8),
))
if late:
events.append(reference)
if revise:
events.append(build_explore_finding_event(
**control, recorded_at="2026-11-21T12:10:00Z",
measurements=measurements(BASELINE_SHA, baseline_ref, 2, 10),
))


def populated_history():
events = []
for attempt in range(75):
add_case(events, f"Comparison {attempt}", "same-question", attempt=attempt,
baseline_author="other-worker" if attempt == 31 else "worker")
return events


if __name__ == "__main__":
events = []
add_case(events, "Original matched measurements", "matched", revise=True)
add_case(events, "Reference from another worker", "foreign", baseline_author="other-worker", refuted=True)
add_case(events, "Reference received later", "late", late=True)
print(json.dumps({"goal_id": GOAL, "display_name": "Candidate verification", "events": events}))
168 changes: 168 additions & 0 deletions apps/presentation/dashboard/smoke/research-verification-readback.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
import assert from "node:assert/strict";
import {execFileSync} from "node:child_process";
import {fileURLToPath} from "node:url";
import {resolveTestPython} from "../../../../scripts/test-python.mjs";

const goalId = "research-verification-fixture";
const result = {ref: "artifact:result", sha256: "b".repeat(64)};
const proof = {ref: "receipt:external-verifier", sha256: "c".repeat(64)};
const refs = [result.ref, proof.ref];
const contract = {
goal_ref: {goal_id: goalId, goal_instance_id: "verification-original-instance"},
revision: 1, digest: "a".repeat(64), objective: "Read candidate verification", status: "accepted",
tasks: [], non_goals: [], held_todo_ids: [],
criteria: [{id: "verify", description: "Inspect the candidate result", oracle: {
kind: "owner_pinned_oracle", source_id: "fixture-oracle", source_digest: "d".repeat(64),
input_refs: [], output_refs: refs, state: "current",
}}],
verification: {operation_id: "saved-receipt", contract_revision: 1, contract_digest: "a".repeat(64), todo_id: null,
results: [{criterion_id: "verify", passed: true, exit_code: 0, oracle_evidence: {
source_id: "fixture-oracle", source_digest: "d".repeat(64), checked_at: "2026-11-21T13:00:00Z",
input_versions: [], output_versions: [result, proof],
}}]},
};
const saved = {
schema_version: "goal_acceptance_observation_projection_v0", goal_id: goalId, read_only: true,
acceptance_assessed: false, coverage: "partial", missing_sources: [], truncated: false,
historical_progress: [], acceptance_gaps: [], guards: [], next_action: null, next_action_source: null,
goal_acceptance_contract: contract,
};
export async function verifyResearchAcceptanceReadback(browser, start) {
const repoRoot = fileURLToPath(new URL("../../../..", import.meta.url));
const builder = fileURLToPath(new URL("./research-verification-fixture.py", import.meta.url));
const fixture = JSON.parse(execFileSync(resolveTestPython({repoRoot}), [builder], {cwd: repoRoot, encoding: "utf8",
env: {...process.env, PYTHONPATH: repoRoot}}));
const url = await start("verification", fixture);
const historyUrl = new URL("/api/chat/explore-results", url);
historyUrl.search = new URLSearchParams({goal_id: goalId, view: "history"});
const historyResponse = await fetch(historyUrl);
assert.equal(historyResponse.status, 200);
const history = (await historyResponse.json()).items;
const matched = history.find(row => row.result_id === "matched-candidate");
assert.deepEqual(matched.yardstick_measurements.map(row => row.value), [9, 5, 4, 8]);
assert.equal(matched.work_yardstick.source_snapshot, undefined);
const revision = history.filter(row => row.result_id === "matched-baseline").at(-1);
assert.deepEqual(revision.measurements.map(row => row.value), [2, 10], "The later measurement exists in history");
for (const id of ["foreign-candidate", "late-candidate"]) {
const record = history.find(row => row.result_id === id);
assert.equal(record.yardstick_measurements, undefined);
assert.equal(record.work_yardstick.decision.authoritative.metric, "loss");
}
const page = await browser.newPage({locale: "en-US", viewport: {width: 1200, height: 900}});
let mode = "unavailable";
let mutations = 0;
let suppliedHistoricalPass = false;
const reads = [];
try {
await page.addInitScript(() => localStorage.setItem("loopx-pw-locale", "en"));
page.on("request", request => {if (request.method() !== "GET") mutations++;});
await page.route(/\/status\.json(?:\?|$)/, async route => {
const response = await route.fetch();
const data = await response.json();
const goal = data.run_history?.goals?.find(row => row.id === goalId);
if (goal) {
goal.acceptance_observation = saved;
suppliedHistoricalPass = true;
}
await route.fulfill({response, json: data});
});
await page.route(/\/api\/chat\/goal-acceptance\?/, async route => {
const query = new URL(route.request().url()).searchParams;
assert.equal(query.get("goal_id"), goalId);
assert.equal(route.request().method(), "GET");
reads.push(mode);
if (mode === "unavailable") return route.fulfill({status: 503, json: {ok: false}});
const live = structuredClone(contract);
if (mode === "other-instance") live.goal_ref.goal_instance_id = "verification-new-instance";
if (mode === "unrelated-result") {
live.criteria[0].oracle.output_refs[0] = "artifact:other-result";
live.verification.results[0].oracle_evidence.output_versions[0].ref = "artifact:other-result";
}
return route.fulfill({json: {ok: true, goal_id: goalId, provider_revision: "fixture-revision",
goal_acceptance_contract: live}});
});
const entry = page.locator(".goal-verification-entry > summary");
const panel = page.locator(".goal-verification-body");
const verified = panel.getByText("Authoritative check includes this artifact", {exact: true});
const retry = panel.getByRole("button", {name: "Retry verifier read", exact: true});
const tier = panel.locator("dl > div").filter({has: page.getByText("Verified tier", {exact: true})}).locator("dd");
const unknown = async () => {
await tier.getByText("Unknown", {exact: true}).waitFor();
assert.equal(await verified.count(), 0);
assert.equal(await panel.getByText("Artifact checks passed", {exact: true}).count(), 0);
};

const read = async activate => {
const response = page.waitForResponse(item => new URL(item.url()).pathname === "/api/chat/goal-acceptance");
await activate();
await response;
await page.locator('.goal-verification-body[aria-busy="false"]').waitFor();
};

await page.goto(url);
await entry.waitFor();
assert(suppliedHistoricalPass, "The case must include a passing historical receipt");
assert.deepEqual(reads, [], "The collapsed packet must leave the live acceptance service idle");
await read(() => entry.press("Enter"));
await retry.waitFor();
await unknown();
const originalCandidate = panel.getByText(result.sha256, {exact: true});
await originalCandidate.waitFor();
assert.equal(await originalCandidate.count(), 1, "Keep the original candidate readable");
mode = "other-instance";
await read(() => retry.press("Enter"));
await retry.waitFor();
await unknown();
mode = "current";
await read(() => retry.press("Enter"));
await verified.waitFor();
assert.equal(await tier.textContent(), "L0");
const selected = panel.getByRole("combobox", {name: "Research record"});
const fidelity = panel.locator("dl > div").filter({has: page.getByText("Proxy fidelity", {exact: true})}).locator("dd");
const negative = panel.locator("section").filter({
has: page.getByRole("heading", {name: "Refuted alternatives", exact: true}),
});
const decisionRefs = panel.locator("dl > div").filter({has: page.getByText("Decision references", {exact: true})});
const confirmedBaseline = "artifact:baseline";
const refutedEvidence = "artifact:rejected-variant";
await selected.selectOption({label: "Original matched measurements"});
assert.equal(await fidelity.textContent(), "Different ordering on the matched pair");
assert.equal(await panel.getByText("9 → 5 points", {exact: false}).count(), 1);
assert.equal(await panel.getByText("4 → 8 points", {exact: false}).count(), 1);
assert.equal(await negative.getByText("Unknown", {exact: true}).count(), 1);
assert.equal(await negative.getByText(confirmedBaseline, {exact: true}).count(), 0);
assert.equal(await decisionRefs.getByText(confirmedBaseline, {exact: true}).count(), 1);

await page.setViewportSize({width: 390, height: 900});
await selected.selectOption({label: "Reference from another worker"});
assert.equal(await negative.getByText("Rejected reference variant", {exact: true}).count(), 1);
assert.equal(await negative.getByText(refutedEvidence, {exact: true}).count(), 1);
assert.equal(await negative.getByText(confirmedBaseline, {exact: true}).count(), 0);
assert.equal(await decisionRefs.getByText(confirmedBaseline, {exact: true}).count(), 1);
assert.equal(await decisionRefs.getByText(refutedEvidence, {exact: true}).count(), 0);
for (const label of ["Reference from another worker", "Reference received later"]) {
await selected.selectOption({label});
assert.equal(await fidelity.textContent(), "Unknown");
assert.equal(await panel.getByText("9 → 5 points", {exact: false}).count(), 0);
assert.equal(await verified.count(), 1, "The separate authoritative proof remains available");
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
}
assert.equal(await negative.getByText(refutedEvidence, {exact: true}).count(), 0,
"Another research question's refuted finding does not cross into the selected one");
mode = "unrelated-result";
await page.goto(url);
await entry.waitFor();
await read(() => entry.press("Enter"));
await panel.getByText("Authoritative receipt for this candidate is unknown", {exact: true}).waitFor();
await unknown();
assert.equal(await retry.count(), 0, "A readable check of another result is a scope mismatch");
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
assert.deepEqual(reads, ["unavailable", "other-instance", "current", "unrelated-result"]);
assert.equal(mutations, 0);
const backend = await (await fetch(new URL("/fixture/readback", url))).json();
assert(backend.history_reads > 0 && backend.source_unchanged && backend.mutation_attempts === 0);
console.log("research verification: original pair survives revision; foreign and delayed measurements stay unknown; verifier retry restores proof");
} finally {
await page.close();
}
}
10 changes: 10 additions & 0 deletions apps/presentation/dashboard/src/data/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,17 @@ export const runRecordSchema = z.object({
project_map: projectMapSchema.optional().nullable(),
});

const goalArtifactLifecycleSchema = z.object({
schema_version: z.literal("goal_artifact_lifecycle_projection_v0"),
goal_id: z.string(),
guards: z.array(z.object({
id: z.string(), kind: z.string(), owner: z.string(), blocked: z.boolean(),
})),
});
export type GoalArtifactLifecycle = z.infer<typeof goalArtifactLifecycleSchema>;

export const runGoalSchema = z.object({
artifact_lifecycle: goalArtifactLifecycleSchema.optional().nullable().catch(null),
source_access: z.object({namespace: z.string(), label: z.string(), read_only: z.literal(true), original_goal_id: z.string().optional()}).optional(),
parent_goal_id: z.string().nullable().optional().catch(null),
goal_objective: z.string().nullable().optional().catch(null),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ function relativeLookLabel(iso: string, locale: string): string {
return new Intl.DateTimeFormat(locale === "zh-CN" ? "zh-CN" : "en", { month: "short", day: "numeric" }).format(then);
}

export function GoalOverview({ active, goal, items, userTodos, readOnly, onOpenDetails, onSelect, onView, selectedTodoId, board, proposals, onPreview, historyRefreshRevision, review, digest, railOpen, onCloseRail, onOpenAgentConversation, sinceYouLooked, onMarkSeen }: {
export function GoalOverview({ active, goal, items, userTodos, readOnly, onOpenDetails, onSelect, onView, onOpenVerification, selectedTodoId, board, proposals, onPreview, historyRefreshRevision, review, digest, railOpen, onCloseRail, onOpenAgentConversation, sinceYouLooked, onMarkSeen }: {
onOpenVerification: () => void;
onOpenAgentConversation?: (agentId: string) => void;
/** Material changes since the owner's last acknowledged look; null when none. */
sinceYouLooked?: SinceYouLookedDelta | null; onMarkSeen?: () => void;
Expand Down Expand Up @@ -109,8 +110,14 @@ export function GoalOverview({ active, goal, items, userTodos, readOnly, onOpenD
{moreAttention ? <button className="goal-overview-more" type="button" onClick={() => onView("tasks")}>{copy.tasks}{totalAttention !== null ? ` (${totalAttention})` : ""}<ArrowRight aria-hidden size={14} /></button> : null}
</section> : null}
map={readOnly ? <ContextHelp label={locale === "zh-CN" ? "来源读取范围" : "Source reading scope"} icon={CircleHelp}><p className="goal-work-scope">{copy.remote}</p></ContextHelp> : <DeliveryWorkMap goal={goal} userTodos={userTodos} review={review} onSelect={onSelect} selectedTodoId={selectedTodoId}/>}/>
{readOnly ? <GoalAcceptanceObservationCard goal={goal} overview />
{readOnly ? <><GoalAcceptanceObservationCard goal={goal} overview />
{goal.sourceAccess ? <button className="goal-overview-more" type="button" onClick={onOpenVerification}>
{locale === "zh-CN" ? "在研究中查看验证证据" : "Read verification evidence in Research"}<ArrowRight size={14} aria-hidden />
</button> : null}</>
: <OverviewDeliveryEvidence key={`delivery:${goal.goalId}`} review={review} zh={locale === "zh-CN"}>
<button className="goal-overview-more" type="button" onClick={onOpenVerification}>
{locale === "zh-CN" ? "在研究中查看验证证据" : "Read verification evidence in Research"}<ArrowRight size={14} aria-hidden />
</button>
<DeliveryReviewContent review={review} hideWorkMap hideAcceptanceContract active={active} goal={goal} items={items} userTodos={userTodos} onSelect={onSelect} />
</OverviewDeliveryEvidence>}
</section>;
Expand Down
Loading
Loading