diff --git a/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs b/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs index 9f4c5e879f..cc9f993f6f 100644 --- a/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs +++ b/apps/presentation/dashboard/smoke/research-evidence-version-browser-smoke.mjs @@ -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-")); @@ -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?.(); diff --git a/apps/presentation/dashboard/smoke/research-verification-fixture.py b/apps/presentation/dashboard/smoke/research-verification-fixture.py new file mode 100644 index 0000000000..f476d96f23 --- /dev/null +++ b/apps/presentation/dashboard/smoke/research-verification-fixture.py @@ -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})) diff --git a/apps/presentation/dashboard/smoke/research-verification-readback.mjs b/apps/presentation/dashboard/smoke/research-verification-readback.mjs new file mode 100644 index 0000000000..7d0d533d7c --- /dev/null +++ b/apps/presentation/dashboard/smoke/research-verification-readback.mjs @@ -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(); + } +} diff --git a/apps/presentation/dashboard/src/data/status.ts b/apps/presentation/dashboard/src/data/status.ts index 72d8d1e663..f845086950 100644 --- a/apps/presentation/dashboard/src/data/status.ts +++ b/apps/presentation/dashboard/src/data/status.ts @@ -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; + 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), diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-overview.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-overview.tsx index 6eb7aee809..6208614545 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-overview.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-overview.tsx @@ -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; @@ -109,8 +110,14 @@ export function GoalOverview({ active, goal, items, userTodos, readOnly, onOpenD {moreAttention ? : null} : null} map={readOnly ?

{copy.remote}

: }/> - {readOnly ? + {readOnly ? <> + {goal.sourceAccess ? : null} : + } ; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx index bdd016c0b9..7c164bd284 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-research-history.tsx @@ -2,6 +2,7 @@ import {ExecutionObservationReadback, WorkYardstickReadback} from "./work-yardst import {GoalSourceStrategies, useGoalStrategyLocation} from "./goal-source-strategies"; import {exploreFindingCopy} from "./explore-finding-copy"; import {AlertCircle, ArrowLeft, ArrowRight, Circle, CircleHelp, FlaskConical, GitBranch, RefreshCw, Search} from "lucide-react"; +import {GoalVerificationWorkbench, type GoalVerificationSources} from "./goal-verification-workbench"; import {Fragment, useEffect, useId, useLayoutEffect, useMemo, useRef, useState} from "react"; import {defaultParseSearch} from "@tanstack/react-router"; import {ResearchRecordSearch, useResearchRecordsLocation} from "./research-record-browser"; @@ -53,9 +54,11 @@ const viewFromUrl = (goal: string) => { /** An effect-free history consumer. Its source is Explore, not raw sessions or * a judge. All recorded updates survive; unsupported analysis stays unavailable. */ -export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHistory = false, active, zh, refreshRevision = 0, readSourceUrl, onOpenSourceTasks}: { +export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHistory = false, active, zh, refreshRevision = 0, readSourceUrl, onOpenSourceTasks, verification, showVerification}: { goalId: string; originalGoalId?: string; preferHistory?: boolean; active: boolean; zh: boolean; refreshRevision?: number; readSourceUrl?: string; onOpenSourceTasks?: () => void; + verification?: GoalVerificationSources; + showVerification?: number; }) { const strategies = useGoalStrategyLocation(goalId, readSourceUrl); const analysis = useResearchAnalysis(goalId, active, zh, readSourceUrl); @@ -74,7 +77,15 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist const deferHistory = requestedCase === true && caseViewAvailable; const historySource = JSON.stringify([goalId, originalGoalId, readSourceUrl]); const [openedHistorySource, setOpenedHistorySource] = useState(null); - const readHistory = active && (!deferHistory || openedHistorySource === historySource); + const [openVerificationSource, setOpenVerificationSource] = useState(null); + const verificationOpen = openVerificationSource === historySource; + const verificationEntry = useRef(null); + useEffect(() => { + if (!active || !showVerification) return; + setOpenVerificationSource(historySource); + verificationEntry.current?.querySelector("summary")?.focus(); + }, [active, showVerification, historySource]); + const readHistory = active && (verificationOpen || !deferHistory || openedHistorySource === historySource); useEffect(() => { const changed = () => setCaseReading(readCaseMode()); changed(); window.addEventListener("popstate", changed); @@ -302,6 +313,11 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist ? findingVersions.find(finding => finding.event_id === selection.event && (!selection.finding || finding.result_id === selection.finding)) : selection.finding ? selected.findings.find(finding => finding.result_id === selection.finding) : defaultFinding(selected)); + const verificationFinding = selectedFinding + ? history.canonical?.events.find(item => item.event_id === selectedFinding.event_id) + : !selection.nodes.length && selection.day === null + ? history.canonical?.findings.filter(item => item.status === "confirmed" && (item.work_yardstick || item.execution_observation)).at(-1) + : undefined; const hasSeparateQuestion = Boolean(selected?.findings.length && selectedFinding?.title !== selected.latest.title); const selectedGroup = selection.day !== null ? grouped.groups.find(group => group.day === selection.day) : undefined; const selectedMembers = selectedGroup?.nodes ?? (selection.nodes.length > 1 ? value?.nodes.filter(node => selection.nodes.includes(node.id)) : undefined); @@ -528,6 +544,13 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist sourceUrl={readSourceUrl} zh={zh} selection={selectedStrategy} onSelect={strategies.choose} onClose={() => strategies.choose(null)}/> : null; return <> + {verification ?
setOpenVerificationSource(event.currentTarget.open ? historySource : null)}> + {zh ? "验证证据包" : "Verification evidence packet"} + {verificationOpen ? : null} +
: null} {caseViewAvailable ?
: null}{p?.decision ? {p.decision.authoritative.evaluation_ref} : null} + {p?.candidate && configured ? {checked.length ? labels.included : labels.unbound} : null} + {fidelity} + {gaps.length ? <>{labels.sourceGaps}
    {gaps.map(item =>
  • {item}
  • )}
: null} + {guards?.length ?
    {guards.map((item, index) =>
  • {item.id} · {item.owner}
  • )}
: null} + {!gaps.length && !guards?.length ? guards ? labels.noOpenGuards : unknown : null}
+ +
+

{labels.baseline}

+ {p?.evidence?.host ?? unknown} + {depth === null ? unknown : `L${depth}`} + + + + {p?.candidate ? {p.candidate} : unknown} +
+

{labels.negative}

+ {p?.alternatives.length ?
    {p.alternatives.map(row =>
  • {row.title} + {row.summary ?
    {row.summary}
    : null} + {row.evidence_refs.length ? row.evidence_refs.map(ref => {ref}) : unknown}
  • )}
:

{unknown}

} +
+

{labels.comparison}

+ {([["proxy", labels.proxy], ["authoritative", labels.final]] as const).map(([key, label]) => { + const pair = p?.[key]; + return {pair ? <> + {format.format(pair.before.value!)} → {format.format(pair.after.value!)} {pair.after.unit} + {pair.before.evidence_ref} → {pair.after.evidence_ref} + : unknown}; + })} + {decisionRefs.length ? + {decisionRefs.map(ref => {ref})} + : null} +
{p?.authoritative && p.proxy ?

{labels.relation}

: null} + {checked.map(({evidence, criterionId}) => )} +
+

{labels.costs}

+ {costRows.map(([key, label]) => { + const cost = p?.evidence?.costs?.[key]; + return {cost ? <>{format.format(cost.value)}{cost.evidence_ref} : unknown}; + })} +
+
+
; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts index 0d027bb271..7ef82fc5b7 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts @@ -7,7 +7,7 @@ import type { ActionReviewPlan } from "../../../../../../loopx/control_plane/pre import type { GoalAcceptanceObservation } from "../../data/goal-acceptance-observation"; import type { AttentionDetails } from "./attention-details"; import type { WorkspaceLoadError, WorkspaceReadScope } from "../../data/workspace-progressive-status"; -import type { RunRecord, TodoItem } from "../../data/status"; +import type { GoalArtifactLifecycle, RunRecord, TodoItem } from "../../data/status"; import type { TodoUpdateSourceBasis } from "../../data/action-source-basis"; import { goalWorkKind, type GoalHostThreadActivity, type WorkspaceGoalExecution } from "./goal-activity"; import { receiptRetryReadback } from "./monitor-readback"; @@ -176,6 +176,7 @@ export type WorkspaceGoal = { /** Bounded, safe text from this Goal's declared source document. */ objective?: string | null; acceptanceObservation?: GoalAcceptanceObservation | null; + artifactLifecycle?: GoalArtifactLifecycle | null; /** Driver readback only; it never changes Goal activation or grants work. */ workerObservations?: { read_status: "read" | "stale" | "unreadable"; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx index 6238ce5a63..ad9c7b0b24 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx @@ -983,6 +983,7 @@ export function PersonalWorkspacePage({ const managerChatOpen = selectedWorkspaceRef !== null || selectedGoalTab === "chat"; const workspaceUnavailable = selectedWorkspaceRef !== null && workspaceConversations?.projects != null && !selectedWorkspaceProject; const workspaceTitle = selectedWorkspaceRef ? selectedWorkspaceProject?.title ?? t("workspace.unknownTitle") : null; + const [verificationVisit, setVerificationVisit] = useState<{scope: string; count: number} | null>(null); function setSelectedGoalTab(view: WorkspaceGoalTab) { if (view === "chat" && originalConversation && workspaceConversations?.onOpenOriginal) { workspaceConversations.onOpenOriginal(originalConversation.target); @@ -2938,7 +2939,14 @@ export function PersonalWorkspacePage({ ? selectGoal(id, "research")} onOpenTasks={() => setSelectedGoalTab("tasks")} active={!settingsOpen && selectedGoalTab === "research"} zh={locale === "zh-CN"} refreshRevision={historyRefreshRevision} readSourceUrl={researchReadSourceUrl} - directoryReadSourceUrl={directoryReadSourceUrl} statusNotice={goalStatusNotice} /> + directoryReadSourceUrl={directoryReadSourceUrl} statusNotice={goalStatusNotice} + showVerification={verificationVisit?.scope === selectionScope ? verificationVisit.count : undefined} + verification={{ + acceptance: workspaceReview.usable ? workspaceReview.snapshot?.acceptance ?? selectedGoal.acceptanceObservation + : selectedGoal.acceptanceObservation, + lifecycle: selectedGoal.artifactLifecycle, + liveAcceptance: !readOnly && !selectedGoal.sourceAccess, + }} /> : goalStatusNotice ??

{locale === "zh-CN" ? "此来源尚未提供研究记录的读取入口。" : "This source does not provide a research history endpoint."}

; return ( <> @@ -3111,7 +3119,10 @@ export function PersonalWorkspacePage({ overview: null, tasks: null, research: researchPanel, files: null, chat: null, } : { overview: setRailScope(null)} digest={workspaceDigest} review={workspaceReview} active={!settingsOpen && selectedGoalTab === "overview"} goal={selectedGoal} items={items} userTodos={model.userTodos} readOnly={readOnly} - onOpenDetails={(openingControl) => setSelection({ kind: "goal", item: selectedGoal, openingControl })} onSelect={setSelection} onView={setSelectedGoalTab} + onOpenDetails={(openingControl) => setSelection({ kind: "goal", item: selectedGoal, openingControl })} onSelect={setSelection} onView={setSelectedGoalTab} onOpenVerification={() => { + setVerificationVisit(previous => ({scope: selectionScope, count: (previous?.count ?? 0) + 1})); + setSelectedGoalTab("research"); + }} selectedTodoId={drawerSelection?.kind === "todo" ? drawerSelection.item.todoId : null} board={taskBoard(!settingsOpen && selectedGoalTab === "overview")} historyRefreshRevision={historyRefreshRevision} proposals={proposals} onPreview={createPreview} />, diff --git a/apps/presentation/dashboard/src/views/dashboard-page.tsx b/apps/presentation/dashboard/src/views/dashboard-page.tsx index e95cd03497..87cfbf4443 100644 --- a/apps/presentation/dashboard/src/views/dashboard-page.tsx +++ b/apps/presentation/dashboard/src/views/dashboard-page.tsx @@ -1132,6 +1132,7 @@ function buildPersonalHomeModel( })), } : undefined, acceptanceObservation: goal.acceptance_observation, + artifactLifecycle: goal.artifact_lifecycle, workerObservations: !goal.host_worker_observations ? null : goal.host_worker_observations.goal_id === goal.id ? goal.host_worker_observations : {read_status: "unreadable", rows: []}, diff --git a/loopx/capabilities/explore/README.md b/loopx/capabilities/explore/README.md index c064baf7ba..b8f7ef69d7 100644 --- a/loopx/capabilities/explore/README.md +++ b/loopx/capabilities/explore/README.md @@ -16,6 +16,27 @@ When the observed execution used the finding's tested input revision, result attachments can bind it once and select the evidence to reuse. Readback and standalone observations keep the complete observation form. [Execution evidence authoring](../../../docs/reference/protocols/explore-result-from-path-delta-v0.md#execution-evidence-on-the-same-input) +An existing candidate execution observation can also carry optional +`verification_evidence`. Supply `baseline`, `environment` and `source` as +`{ref, sha256}` pairs. Use the actual observed `host` identifier. Each +`proofs` item (`external_verifier`, `warm_session_cache`, `white_box_hooks`, +`receipt_compaction`) adds its owning `criterion_id` to the versioned reference. In `costs`, +record measured `{value, evidence_ref}` for `warm_cache_tokens`, +`cold_cache_tokens`, `verifier_seconds`, `human_confirmations`, or +`tool_interceptions`. All references belong to the enclosing observation. +Omit an unmeasured field. A measured zero is a value. + +The **Verification evidence packet** on **Research** reads these records and +the Goal's existing acceptance and lifecycle projections. A current owner-pinned +check must attest the candidate's recorded result reference and SHA-256 +alongside the named criterion's receipt versions. Each proof role needs a +distinct receipt. If the current check cannot be read, the current tier is +unknown. Read-only snapshots label saved verification as archived. +L0 covers independent evaluation, L1 also covers the warm session, and L2 adds +tool hooks and receipt compaction. The reader works with opaque host names and +uses existing acceptance reads for local version freshness. Opening the packet +reads saved evidence without launching a verifier. + ## Read execution evidence in the App Open a Goal's **Research / 研究** view, select its question in the history, diff --git a/loopx/capabilities/explore/README.zh-CN.md b/loopx/capabilities/explore/README.zh-CN.md index 4669c3c51d..7806297ff6 100644 --- a/loopx/capabilities/explore/README.zh-CN.md +++ b/loopx/capabilities/explore/README.zh-CN.md @@ -9,6 +9,20 @@ 不认证执行真实性或收益;finding、replan 和既有研究历程详情保留相同信息,缺省仍兼容 旧事件。参见[本地探针生产路径](../../../benchmark/runtime/EXECUTION_OBSERVATIONS.md)。 +既有候选执行记录可选携带 `verification_evidence`。`baseline`、`environment`、 +`source` 使用 `{ref, sha256}`,`host` 填实际观测的宿主标识。`proofs` 中 +`external_verifier`、`warm_session_cache`、`white_box_hooks`、`receipt_compaction` +使用同一版本引用格式并携带对应验收项的 `criterion_id`。`costs` 用 `{value, evidence_ref}` 记录实测的 +`warm_cache_tokens`、`cold_cache_tokens`、`verifier_seconds`、 +`human_confirmations` 或 `tool_interceptions`。引用必须属于该执行记录。 +缺测省略对应字段,实测的零保留。 + +Goal 的**研究 → 验证证据包**使用这些记录及既有验收和产物生命周期投影。 +当前独立检查须核对已记录的候选结果引用及 SHA-256,以及对应验收项的回执版本。 +每种证明需要独立回执。当前检查不可读时档位为未知。只读快照将保存的检查标为存档。 +L0 覆盖独立终评,L1 加上温缓存,L2 再覆盖工具钩子与回执压缩。打开工作台只读取 +已保存的记录和当前产物版本。 + ## 量化结论 普通结果附件可附带 `measurements`,保存到既有节点所属的 finding。关系图和 diff --git a/loopx/capabilities/explore/result_log.py b/loopx/capabilities/explore/result_log.py index 7b98b51ad9..e13f77246a 100644 --- a/loopx/capabilities/explore/result_log.py +++ b/loopx/capabilities/explore/result_log.py @@ -835,7 +835,52 @@ def explore_history_rows(events: Sequence[Mapping[str, Any]], *, goal_id: str | from ...control_plane.work_items.yardstick_decision import project_work_yardstick_presentations return project_work_yardstick_presentations( - [{key: event[key] for key in fields if key in event} for event in events], goal_id=goal_id) + [{key: event[key] for key in fields if key in event} for event in events], + goal_id=goal_id, history_sources=_history_verification_sources(events), + ) + + +def _history_verification_sources(events: Sequence[Mapping[str, Any]]) -> dict[str, Any] | None: + """Send each canonical finding revision once for typed prefix replay.""" + questions: set[str] = set() + for order, event in enumerate(events): + capture = event.get("work_yardstick") or {} + snapshot = capture.get("source_snapshot") + verification = (event.get("execution_observation") or {}).get("verification_evidence") or {} + if snapshot and snapshot["event_count"] <= order and verification.get("baseline") and event.get("node_id"): + questions.add(event["node_id"]) + if not questions: + return None + source_events = [] + for order, event in enumerate(events): + source: dict[str, Any] = {"goal_id": event["goal_id"], "event_id": event["event_id"]} + if event["event_kind"] == EVENT_KIND_FINDING: + # Keep revisions without measurements so they can replace older + # measured rows, including revisions that changed question. + finding = {"finding_id": event["result_id"]} + if event.get("node_id") in questions: + view = _finding_view({**event, "_recorded_order": order}) + fields = ("node_id", "status", "agent_id", "evidence_refs", "measurements", + "work_binding", "work_yardstick", "execution_observation") + finding.update({key: view[key] for key in fields if key in view}) + source["finding"] = finding + source_events.append(source) + return {"source_events": source_events} + + +def _record_result_revision( + folded: dict[str, dict[str, Any]], event: Mapping[str, Any], recorded_order: int, +) -> None: + result_id = str(event.get("result_id") or "") + if not result_id: + return + prior = folded.get(result_id) + view = dict(event) + view["_recorded_order"] = recorded_order + view["first_recorded_at"] = prior["first_recorded_at"] if prior else str(event.get("recorded_at") or "") + view["last_updated_at"] = str(event.get("recorded_at") or "") + view["update_count"] = (prior["update_count"] + 1) if prior else 1 + folded[result_id] = view def _fold_by_result_id( @@ -843,20 +888,8 @@ def _fold_by_result_id( ) -> list[dict[str, Any]]: folded: dict[str, dict[str, Any]] = {} for recorded_order, event in enumerate(events): - if event.get("event_kind") != event_kind: - continue - result_id = str(event.get("result_id") or "") - if not result_id: - continue - prior = folded.get(result_id) - view = dict(event) - view["_recorded_order"] = recorded_order - view["first_recorded_at"] = ( - prior["first_recorded_at"] if prior else str(event.get("recorded_at") or "") - ) - view["last_updated_at"] = str(event.get("recorded_at") or "") - view["update_count"] = (prior["update_count"] + 1) if prior else 1 - folded[result_id] = view + if event.get("event_kind") == event_kind: + _record_result_revision(folded, event, recorded_order) return list(folded.values()) diff --git a/loopx/control_plane/capabilities/explore_execution_observation.ts b/loopx/control_plane/capabilities/explore_execution_observation.ts index bd77857053..4a99f83fff 100644 --- a/loopx/control_plane/capabilities/explore_execution_observation.ts +++ b/loopx/control_plane/capabilities/explore_execution_observation.ts @@ -5,18 +5,21 @@ import type {JsonObject} from "../runtime_decode.ts"; import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; import {requireJsonObject} from "../runtime_decode.ts"; import {BARE_SHA256_PATTERN} from "../content_digest.ts"; +import {normalizeCandidateVerificationEvidence, type CandidateVerificationEvidence} from "./explore_verification_evidence.ts"; import {isExploreEvidenceRef} from "./explore_evidence_ref.ts"; export const EXPLORE_EXECUTION_OBSERVATION_SCHEMA = "explore_execution_observation_v0"; -export function normalizeExploreExecutionObservation(params: JsonObject): JsonObject { +export type ExploreExecutionObservation = JsonObject & {verification_evidence?: CandidateVerificationEvidence}; + +export function normalizeExploreExecutionObservation(params: JsonObject): ExploreExecutionObservation { const row = requireJsonObject(params.observation, "execution observation"); const required = ["schema_version", "candidate_sha256", "input_revision", "planned_method_id", "executed_method_id", "change_reason", "elapsed_seconds", "limit_seconds", "search_iterations", "stop_reason", "evidence_refs"]; if (row.schema_version !== EXPLORE_EXECUTION_OBSERVATION_SCHEMA || required.some(key => !Object.hasOwn(row, key)) - || Object.keys(row).some(key => ![...required, "exit_code", "result_ref", "result_candidate_sha256"].includes(key))) { + || Object.keys(row).some(key => ![...required, "exit_code", "result_ref", "result_candidate_sha256", "verification_evidence"].includes(key))) { throw new EffectRuntimeRequestError("execution observation fields are missing or unsupported"); } const text = (value: unknown, field: string, max: number): string => { @@ -62,7 +65,7 @@ export function normalizeExploreExecutionObservation(params: JsonObject): JsonOb if (!Array.isArray(row.evidence_refs) || !row.evidence_refs.length || row.evidence_refs.length > 8) { throw new EffectRuntimeRequestError("execution observation requires one to eight evidence references"); } - const result: JsonObject = {schema_version: row.schema_version, + const result: ExploreExecutionObservation = {schema_version: row.schema_version, candidate_sha256: sha(row.candidate_sha256), input_revision: text(row.input_revision, "input_revision", 160), planned_method_id: planned, executed_method_id: executed, change_reason: change, elapsed_seconds: measured(row.elapsed_seconds, "elapsed_seconds"), @@ -84,5 +87,10 @@ export function normalizeExploreExecutionObservation(params: JsonObject): JsonOb throw new EffectRuntimeRequestError("result evidence must name this executed candidate and an included evidence reference"); } } + if (Object.hasOwn(row, "verification_evidence")) { + result.verification_evidence = normalizeCandidateVerificationEvidence( + row.verification_evidence, result.evidence_refs as string[], + ); + } return result; } diff --git a/loopx/control_plane/capabilities/explore_verification_evidence.ts b/loopx/control_plane/capabilities/explore_verification_evidence.ts new file mode 100644 index 0000000000..5035db50a3 --- /dev/null +++ b/loopx/control_plane/capabilities/explore_verification_evidence.ts @@ -0,0 +1,97 @@ +/** Optional source readback on the existing candidate execution observation. + * Host names are opaque. Each capability claim and cost belongs to this + * candidate and cites a retained source. Authority is resolved by the reader. + */ +import {BARE_SHA256_PATTERN} from "../content_digest.ts"; +import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; +import {requireJsonObject} from "../runtime_decode.ts"; +import {isExploreEvidenceRef} from "./explore_evidence_ref.ts"; + +export type VerificationEvidenceRef = {ref: string; sha256: string}; +export type VerificationProof = VerificationEvidenceRef & {criterion_id: string}; +const proofKeys = ["external_verifier", "warm_session_cache", "white_box_hooks", "receipt_compaction"] as const; +const costKeys = ["warm_cache_tokens", "cold_cache_tokens", "verifier_seconds", "human_confirmations", "tool_interceptions"] as const; +export type CandidateVerificationEvidence = { + baseline?: VerificationEvidenceRef; + environment?: VerificationEvidenceRef; + source?: VerificationEvidenceRef; + host?: string; + proofs?: Partial>; + costs?: Partial>; +}; + +function evidence(value: unknown, allowedRefs: ReadonlySet): VerificationEvidenceRef { + const row = requireJsonObject(value, "verification evidence reference"); + if (Object.keys(row).length !== 2 || typeof row.ref !== "string" || !allowedRefs.has(row.ref) + || typeof row.sha256 !== "string" || !BARE_SHA256_PATTERN.test(row.sha256)) { + throw new EffectRuntimeRequestError("verification evidence requires a captured reference and its exact SHA-256"); + } + return {ref: row.ref, sha256: row.sha256}; +} + +export function normalizeCandidateVerificationEvidence(value: unknown, evidenceRefs: readonly string[]): CandidateVerificationEvidence { + const row = requireJsonObject(value, "candidate verification evidence"); + const allowedRefs = new Set(evidenceRefs); + const result: CandidateVerificationEvidence = {}; + for (const key of Object.keys(row)) { + if (!["baseline", "environment", "source", "host", "proofs", "costs"].includes(key)) { + throw new EffectRuntimeRequestError("unsupported candidate verification evidence field"); + } + } + for (const key of ["baseline", "environment", "source"] as const) { + if (Object.hasOwn(row, key)) result[key] = evidence(row[key], allowedRefs); + } + if (Object.hasOwn(row, "host")) { + if (typeof row.host !== "string" || !isExploreEvidenceRef(row.host) || !/^[a-z0-9][a-z0-9_.-]{0,63}$/.test(row.host)) { + throw new EffectRuntimeRequestError("verification host requires an opaque identifier"); + } + result.host = row.host; + } + if (Object.hasOwn(row, "proofs")) { + const proofs = requireJsonObject(row.proofs, "verification proofs"); + result.proofs = {}; + for (const key of Object.keys(proofs)) { + const kind = proofKeys.find(item => item === key); + if (!kind) throw new EffectRuntimeRequestError("unsupported verification proof"); + const {criterion_id, ...version} = requireJsonObject(proofs[key], "verification proof"); + if (typeof criterion_id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(criterion_id)) { + throw new EffectRuntimeRequestError("verification proof requires its owning acceptance criterion"); + } + result.proofs[kind] = {...evidence(version, allowedRefs), criterion_id}; + } + } + if (Object.hasOwn(row, "costs")) { + const costs = requireJsonObject(row.costs, "verification costs"); + result.costs = {}; + for (const key of Object.keys(costs)) { + const kind = costKeys.find(item => item === key); + if (!kind) throw new EffectRuntimeRequestError("unsupported verification cost"); + const cost = requireJsonObject(costs[key], "verification cost"); + if (Object.keys(cost).length !== 2 || typeof cost.value !== "number" || !Number.isFinite(cost.value) || cost.value < 0 + || (kind !== "verifier_seconds" && !Number.isSafeInteger(cost.value)) + || typeof cost.evidence_ref !== "string" || !allowedRefs.has(cost.evidence_ref)) { + throw new EffectRuntimeRequestError("verification cost requires a nonnegative measurement and a captured reference"); + } + result.costs[kind] = {value: cost.value, evidence_ref: cost.evidence_ref}; + } + } + return result; +} + +/** Independent checks are attached by exact receipt ref and digest. A host name + * or the mere presence of a producer claim cannot upgrade the verified tier. */ +export function verifiedHostDepth(evidence: CandidateVerificationEvidence | undefined, checked: readonly VerificationProof[]) { + const proofs = evidence?.proofs; + if (!evidence?.host || !proofs) return null; + const used: VerificationProof[] = []; + const hasDistinctProof = (proof?: VerificationProof) => { + if (!proof || used.some(item => item.ref === proof.ref || item.sha256 === proof.sha256)) return false; + if (!checked.some(item => item.ref === proof.ref && item.sha256 === proof.sha256 + && item.criterion_id === proof.criterion_id)) return false; + used.push(proof); + return true; + }; + if (!hasDistinctProof(proofs.external_verifier)) return null; + if (!hasDistinctProof(proofs.warm_session_cache)) return 0; + return hasDistinctProof(proofs.white_box_hooks) && hasDistinctProof(proofs.receipt_compaction) ? 2 : 1; +} diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 0588049fad..277fcb5d78 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -846,7 +846,7 @@ export function createEffectRuntimeHandlers( ["work_item.replan_context.project", lazyHandler(() => import("./work_items/replan_context.ts"), ({projectReplanContext}) => projectReplanContext)], ["work_item.replan_context.project_snapshot", lazyHandler(() => import("./work_items/replan_context.ts"), ({projectReplanContextSnapshot}) => projectReplanContextSnapshot)], ["work_item.yardstick.capture", lazyHandler(() => import("./work_items/yardstick_decision.ts"), ({normalizeWorkYardstickCapture}) => normalizeWorkYardstickCapture)], - ["work_item.yardstick.presentation", lazyHandler(() => import("./work_items/yardstick_decision.ts"), ({projectWorkYardstickPresentations}) => projectWorkYardstickPresentations)], + ["work_item.yardstick.presentation", lazyHandler(() => import("./work_items/yardstick_source.ts"), ({projectWorkYardstickPresentations}) => projectWorkYardstickPresentations)], ["work_item.yardstick.sources", lazyHandler(() => import("./work_items/yardstick_source.ts"), ({projectWorkYardstickSourceRequests}) => projectWorkYardstickSourceRequests)], ["work_item.yardstick.continuation", lazyHandler(() => import("./work_items/yardstick_source.ts"), ({validateWorkYardstickContinuation}) => validateWorkYardstickContinuation)], ["explore.finding.admit", lazyHandler(() => import("./capabilities/explore_work_finding.ts"), ({admitExploreWorkFinding}) => admitExploreWorkFinding)], diff --git a/loopx/control_plane/effect_runtime_snapshot_methods.json b/loopx/control_plane/effect_runtime_snapshot_methods.json index f7317e563c..0c1d2bd0fe 100644 --- a/loopx/control_plane/effect_runtime_snapshot_methods.json +++ b/loopx/control_plane/effect_runtime_snapshot_methods.json @@ -14,6 +14,7 @@ "coordination.local_authority.todo_snapshot", "todo.context.page", "work_item.context.project", + "work_item.yardstick.presentation", "capability_hook.turn_context.project", "work_item.interaction_reads.project", "scheduler.hint.project", diff --git a/loopx/control_plane/presentation/explore_history.ts b/loopx/control_plane/presentation/explore_history.ts index c81f28017f..aeebf5f7bf 100644 --- a/loopx/control_plane/presentation/explore_history.ts +++ b/loopx/control_plane/presentation/explore_history.ts @@ -2,18 +2,18 @@ * Event kinds/statuses/relationships remain owned by Explore result_log.py. * Local display grouping must not turn parentage or time into supporting evidence. */ -import {normalizeExploreExecutionObservation} from "../capabilities/explore_execution_observation.ts"; +import {normalizeExploreExecutionObservation, type ExploreExecutionObservation} from "../capabilities/explore_execution_observation.ts"; import {normalizeExploreMeasurements, projectExploreMeasurementFeedback, type ExploreMeasurement} from "../capabilities/explore_measurements.ts"; import {normalizeWorkYardstickCapture, type WorkYardstickCapture} from "../work_items/yardstick_decision.ts"; -import type {JsonObject} from "../runtime_decode.ts"; export type ExploreHistoryEvent = { schema_version: string; event_id: string; goal_id: string; event_kind: string; result_id: string; recorded_at: string; title: string; summary: string; status: string; node_kind: string; blocked_reason: string; parent_id: string; node_id: string; from_node: string; to_node: string; edge_type: string; agent_id: string; run_id: string; evidence_refs: string[]; supersedes: string; confidence: number | null; - execution_observation?: JsonObject; + execution_observation?: ExploreExecutionObservation; measurements?: ExploreMeasurement[]; + yardstick_measurements?: ExploreMeasurement[]; work_yardstick?: WorkYardstickCapture; }; export type ExploreHistoryPage = {goal_id: string; items: ExploreHistoryEvent[]; total: number; next_cursor: string | null}; @@ -72,6 +72,9 @@ export function parseExploreHistoryPage(input: unknown, goalId: string): Explore capture: raw.work_yardstick, goal_id: goalId, agent_id: raw.agent_id ?? "", evidence_refs: raw.evidence_refs ?? [], })}), ...(raw.measurements === undefined ? {} : {measurements: normalizeExploreMeasurements(raw.measurements)}), + ...(raw.yardstick_measurements === undefined ? {} : { + yardstick_measurements: normalizeExploreMeasurements(raw.yardstick_measurements), + }), } as ExploreHistoryEvent; }); return {goal_id: goalId, items, total: page.total as number, next_cursor: page.next_cursor as string | null}; diff --git a/loopx/control_plane/presentation/verification_workbench.ts b/loopx/control_plane/presentation/verification_workbench.ts new file mode 100644 index 0000000000..dc08077b81 --- /dev/null +++ b/loopx/control_plane/presentation/verification_workbench.ts @@ -0,0 +1,30 @@ +/** A reader for existing Explore evidence. A matched pair reports observed + * ordering; the independent Goal receipt remains the acceptance source. */ +import {workYardstickObservedPair} from "../work_items/yardstick_decision.ts"; +import {BARE_SHA256_PATTERN} from "../content_digest.ts"; +import type {ExploreHistoryEvent} from "./explore_history.ts"; + +export function projectVerificationWorkbench( + finding: ExploreHistoryEvent | undefined, + findings: readonly ExploreHistoryEvent[], +) { + if (!finding || finding.event_kind !== "finding") return null; + const decision = finding.work_yardstick?.decision; + const execution = finding.execution_observation; + const evidence = execution?.verification_evidence; + const candidate = typeof execution?.candidate_sha256 === "string" && BARE_SHA256_PATTERN.test(execution.candidate_sha256) + ? execution.candidate_sha256 : null; + const alternatives = findings.filter(row => row.goal_id === finding.goal_id && row.node_id === finding.node_id + && row.event_kind === "finding" && row.event_id !== finding.event_id && row.status === "refuted" + && Boolean(finding.node_id)); + const measurements = finding.yardstick_measurements ?? []; + const exactBaseline = candidate && evidence?.baseline && evidence.baseline.sha256 !== candidate ? evidence.baseline : null; + const authoritative = candidate && exactBaseline && decision + ? workYardstickObservedPair(measurements, decision.authoritative, exactBaseline.sha256, candidate) : null; + const proxy = candidate && exactBaseline && decision?.proxy + ? workYardstickObservedPair(measurements, decision.proxy, exactBaseline.sha256, candidate) : null; + const fidelity = authoritative && proxy && decision?.authoritative.input_revision === decision?.proxy?.input_revision + ? Math.sign(authoritative.delta) === Math.sign(proxy.delta) ? "same_order" : "different_order" + : "unknown"; + return {decision, evidence, candidate, alternatives, authoritative, proxy, fidelity}; +} diff --git a/loopx/control_plane/work_items/yardstick_decision.py b/loopx/control_plane/work_items/yardstick_decision.py index ddfd99ed57..f169864e7f 100644 --- a/loopx/control_plane/work_items/yardstick_decision.py +++ b/loopx/control_plane/work_items/yardstick_decision.py @@ -5,7 +5,7 @@ import json from typing import Any, cast -from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result +from ..effect_runtime import EffectRuntimeRejected, effect_runtime_projection_result, effect_runtime_result from ..runtime.public_safety import validate_public_safe_value @@ -25,15 +25,23 @@ def normalize_work_yardstick_capture(capture: Any, *, goal_id: str, agent_id: st def project_work_yardstick_presentations( - rows: list[dict[str, Any]], *, goal_id: str | None = None, + rows: list[dict[str, Any]], *, goal_id: str | None = None, history_sources: dict[str, Any] | None = None, ) -> list[dict[str, Any]]: """One typed projection call for the captures in an entire read snapshot.""" requests = [{"capture": row["work_yardstick"], "goal_id": goal_id or row["goal_id"], - "agent_id": row.get("agent_id", ""), "evidence_refs": row.get("evidence_refs", [])} + "agent_id": row.get("agent_id", ""), "evidence_refs": row.get("evidence_refs", []), + **({"event_id": row["event_id"]} if history_sources else {})} for row in rows if "work_yardstick" in row] if not requests: return rows - params = {"captures": requests} + params = {"captures": requests, **({"history_sources": history_sources} if history_sources else {})} validate_public_safe_value(params, path="work_yardsticks") - projected = iter(effect_runtime_result("work_item.yardstick.presentation", params)["captures"]) - return [{**row, "work_yardstick": next(projected)} if "work_yardstick" in row else row for row in rows] + result = effect_runtime_projection_result("work_item.yardstick.presentation", params) + projected = iter(result["captures"]) + comparisons = result.get("comparisons", {}) + return [ + {**row, "work_yardstick": next(projected), + **({"yardstick_measurements": comparisons[row["event_id"]]} if row.get("event_id") in comparisons else {})} + if "work_yardstick" in row else row + for row in rows + ] diff --git a/loopx/control_plane/work_items/yardstick_decision.ts b/loopx/control_plane/work_items/yardstick_decision.ts index 52ae634939..b0f9f0fbeb 100644 --- a/loopx/control_plane/work_items/yardstick_decision.ts +++ b/loopx/control_plane/work_items/yardstick_decision.ts @@ -7,7 +7,7 @@ import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; import {jsonObject, requireJsonObject, requireStringArray, type JsonObject} from "../runtime_decode.ts"; import {isExploreEvidenceRef} from "../capabilities/explore_evidence_ref.ts"; import {projectExploreMeasurementFeedback, type ExploreMeasurementFeedback, - type ExploreMeasurementPoint} from "../capabilities/explore_measurements.ts"; + type ExploreMeasurement, type ExploreMeasurementPoint} from "../capabilities/explore_measurements.ts"; export const WORK_YARDSTICK_DECISION_SCHEMA = "work_yardstick_decision_v0"; export type WorkYardstickProfile = {metric: string; unit: string; higher_is_better: boolean; @@ -89,10 +89,6 @@ export function projectWorkYardstickPresentation(params: JsonObject): Pick projectWorkYardstickPresentation(requireJsonObject(row, "capture request")))}; -} export function normalizeWorkYardstickSourceSnapshot(value: unknown): NonNullable { const row = object(value, ["event_count", "event_ids_sha256"], "yardstick source snapshot"); if (!Number.isSafeInteger(row.event_count) || Number(row.event_count) < 0 @@ -155,10 +151,28 @@ function measuredPair(row: ExploreMeasurementFeedback | undefined) { return {previous_best: previous, latest: recent, preferred_candidate_ref: preferred}; } -function matchesProfile(row: ExploreMeasurementFeedback, profile: WorkYardstickProfile): boolean { +function matchesProfile(row: WorkYardstickProfile, profile: WorkYardstickProfile): boolean { return Object.entries(profile).every(([key, value]) => row[key as keyof WorkYardstickProfile] === value); } +/** A display pair has exactly one recorded point per artifact and profile. */ +export function workYardstickObservedPair( + measurements: readonly ExploreMeasurement[], + profile: WorkYardstickProfile, + baseline: string, + candidate: string, +) { + const matching = measurements.filter(row => matchesProfile(row, profile)); + const point = (sha: string) => { + const items = matching.filter(row => row.candidate_ref === `sha256:${sha}` && row.value !== null); + return items.length === 1 ? items[0] : undefined; + }; + const before = point(baseline), after = point(candidate); + if (!before || !after || before.value === null || after.value === null) return null; + const delta = (after.value - before.value) * (profile.higher_is_better ? 1 : -1); + return Number.isFinite(delta) ? {before, after, delta} : null; +} + /** Both declared pairs and first measurements support the same local choice. * This is advisory work context, never another review or evaluation gate. */ export function workYardstickChoiceGuidance(): string { @@ -194,6 +208,50 @@ function recordedBefore(row: JsonObject, sourceOrder: unknown): boolean { && typeof order === "number" && Number.isSafeInteger(order) && order >= 0 && order < sourceOrder; } +function sameDecisionScope(row: JsonObject, source: JsonObject, capture: WorkYardstickCapture, cited: ReadonlySet): boolean { + if (row.node_id !== source.node_id) return false; + const bound = jsonObject(row.work_binding) !== null; + if (bound && (!belongsToWork(row, capture.binding) || row.status !== "confirmed")) return false; + if (row.work_yardstick === undefined) { + if (bound) return true; + // An earlier unbound finding keeps its original Agent and visibility. + return recordedBefore(row, capture.source_snapshot?.event_count) + && row.agent_id === capture.binding.agent_id && Array.isArray(row.evidence_refs) + && row.evidence_refs.some(ref => typeof ref === "string" && cited.has(ref)); + } + const target = (row.work_yardstick as WorkYardstickCapture).decision?.target; + const decision = capture.decision.target; + return belongsToWork(row, capture.binding) && target !== undefined + && target.summary === decision.summary && target.scope === decision.scope + && target.acceptance_ref === decision.acceptance_ref; +} + +/** Select observations from the verified original prefix and the chosen event. */ +export function projectHistoricalYardstickMeasurements( + source: JsonObject, capture: WorkYardstickCapture, priorFindings: readonly JsonObject[], +): ExploreMeasurement[] { + const execution = jsonObject(source.execution_observation); + const verification = jsonObject(execution?.verification_evidence); + const baseline = jsonObject(verification?.baseline)?.sha256; + const candidate = execution?.candidate_sha256; + if (typeof baseline !== "string" || typeof candidate !== "string" || baseline === candidate) return []; + const cited = new Set([...(source.evidence_refs as string[]), ...(execution?.evidence_refs as string[] ?? [])]); + const counterevidence = new Set(capture.decision.counterevidence_refs); + const prior = priorFindings.filter(row => row.status === "confirmed" + && recordedBefore(row, capture.source_snapshot?.event_count) + && sameDecisionScope(row, source, capture, counterevidence)); + const measurements = [source, ...prior].flatMap(row => { + const bound = row === source || row.work_binding !== undefined || row.work_yardstick !== undefined; + return ((row.measurements ?? []) as ExploreMeasurement[]).filter(item => + cited.has(item.evidence_ref) && (bound || counterevidence.has(item.evidence_ref))); + }); + const {authoritative, proxy} = capture.decision; + return [authoritative, ...(proxy ? [proxy] : [])].flatMap(profile => { + const pair = workYardstickObservedPair(measurements, profile, baseline, candidate); + return pair ? [pair.before, pair.after] : []; + }); +} + function committedInWorkWindow(row: JsonObject, startOrder: number, decisionTime: bigint | null): boolean { const order = row.recorded_order; const committed = parseTodoTimestampMicros(String(row.last_updated_at ?? "")); @@ -307,23 +365,8 @@ export function projectWorkYardstickCue(params: JsonObject): JsonObject | null { const plainFindings = Array.isArray(priorSource?.findings) ? priorSource.findings as JsonObject[] : []; const scopedFindings = [...findings.filter(row => row.work_yardstick !== undefined || row.work_binding !== undefined && committedInWorkWindow(row, workObservationStart, decisionTime)), - ...plainFindings.filter(row => row.work_yardstick === undefined)].filter(row => { - if (row.node_id !== source.node_id) return false; - const bound = jsonObject(row.work_binding) !== null; - if (bound && (!belongsToWork(row, params) || row.status !== "confirmed")) return false; - // A decision can cite the agent's earlier measurements on this linked - // question without changing their provenance or assigning earlier work. - if (row.work_yardstick === undefined) { - if (bound) return true; - // A repeated reference appended later cannot change the decision's evidence. - return cited.size > 0 && recordedBefore(row, sourceOrder) - && row.agent_id === capture.binding.agent_id && Array.isArray(row.evidence_refs) - && row.evidence_refs.some(ref => typeof ref === "string" && cited.has(ref)); - } - const target = (row.work_yardstick as WorkYardstickCapture | undefined)?.decision?.target; - return belongsToWork(row, params) && target !== undefined && target.summary === decision.target.summary - && target.scope === decision.target.scope && target.acceptance_ref === decision.target.acceptance_ref; - }); + ...plainFindings.filter(row => row.work_yardstick === undefined)] + .filter(row => sameDecisionScope(row, source, capture, cited)); const searchComparison = measuredSearchComparison(scopedFindings, decision, cited, sourceOrder, workObservationStart, decisionTime); return {source_finding_id: source.finding_id, node_id: source.node_id, binding: capture.binding, ...decision, ...(capture.source_snapshot ? {source_snapshot: capture.source_snapshot} : {}), diff --git a/loopx/control_plane/work_items/yardstick_source.ts b/loopx/control_plane/work_items/yardstick_source.ts index f0be7da56d..eba5c3e16a 100644 --- a/loopx/control_plane/work_items/yardstick_source.ts +++ b/loopx/control_plane/work_items/yardstick_source.ts @@ -2,11 +2,11 @@ * share the pure decision/capture normalizers without importing Node hashing. */ import {createHash} from "node:crypto"; import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; -import {requireJsonObject, type JsonObject} from "../runtime_decode.ts"; +import {jsonObject, requireJsonObject, type JsonObject} from "../runtime_decode.ts"; import {parseTodoTimestampMicros} from "../runtime_timestamp.ts"; import {currentWorkYardstickFinding, normalizeWorkYardstickCapture, - normalizeWorkYardstickDecision, normalizeWorkYardstickSourceSnapshot, - workYardstickTodos} from "./yardstick_decision.ts"; + normalizeWorkYardstickDecision, normalizeWorkYardstickSourceSnapshot, projectHistoricalYardstickMeasurements, + workYardstickTodos, type WorkYardstickCapture} from "./yardstick_decision.ts"; /** The adapter supplies strictly validated canonical events, never attachment fields. * Event ids bind the complete event contents through the existing log validator. */ @@ -26,6 +26,66 @@ function committedSourceSnapshot(params: JsonObject, binding: JsonObject) { } return {event_count: count, event_ids_sha256: digest}; } + +/** Keep capture wire compatibility. Only graph history supplies candidate + * events and canonical, content-addressed prefix replay for display pairs. */ +export function projectWorkYardstickPresentations(params: JsonObject): JsonObject { + if (!Array.isArray(params.captures)) throw new EffectRuntimeRequestError("yardstick presentation requires capture requests"); + const requests = params.captures.map(value => { + const request = requireJsonObject(value, "capture request"); + return { + eventId: typeof request.event_id === "string" ? request.event_id : "", + capture: normalizeWorkYardstickCapture(request), + }; + }); + const captures = requests.map(({capture: {decision, binding}}) => ({decision, binding})); + const history = jsonObject(params.history_sources); + return {captures, ...(history ? {comparisons: historyComparisons(history.source_events, requests)} : {})}; +} + +function historyComparisons( + value: unknown, requests: ReadonlyArray<{eventId: string; capture: WorkYardstickCapture}>, +): JsonObject { + if (!Array.isArray(value)) return {}; + const events = value.map(jsonObject); + const goalId = events[0]?.goal_id; + if (typeof goalId !== "string" || events.some(row => row?.goal_id !== goalId || typeof row.event_id !== "string")) return {}; + const sources = new Map(); + const findings = events.map((row, order) => { + const finding = jsonObject(row?.finding); + if (!finding) return null; + const source: JsonObject = {...finding, recorded_order: order}; + if (!sources.has(row!.event_id)) sources.set(row!.event_id, source); + return source; + }); + const ordered = requests.flatMap(({eventId, capture}) => { + const source = sources.get(eventId); + const snapshot = capture.source_snapshot; + if (!source || !snapshot || capture.binding.goal_id !== goalId + || snapshot.event_count > Number(source.recorded_order)) return []; + return [{eventId, capture, source, snapshot}]; + }).sort((left, right) => left.snapshot.event_count - right.snapshot.event_count); + + // Reuse the same fold and hash across candidates while checking each + // original prefix independently. The hash is of the JSON event-id array. + const prefix = createHash("sha256").update("["); + const folded = new Map(); + const comparisons = new Map(); + let order = 0; + for (const {eventId, capture, source, snapshot} of ordered) { + while (order < snapshot.event_count) { + if (order) prefix.update(","); + prefix.update(JSON.stringify(events[order]!.event_id)); + const finding = findings[order++]; + if (finding) folded.set(finding.finding_id, finding); + } + if (prefix.copy().update("]").digest("hex") !== snapshot.event_ids_sha256) continue; + const measurements = projectHistoricalYardstickMeasurements(source, capture, [...folded.values()]); + if (measurements.length) comparisons.set(eventId, measurements); + } + return Object.fromEntries(comparisons); +} + /** Select only current captures; the transport replays their already-read log prefixes. */ export function projectWorkYardstickSourceRequests(params: JsonObject): JsonObject { const findings = (params.findings ?? []) as JsonObject[]; diff --git a/tests/control_plane_ts/content_digest_single_owner.test.ts b/tests/control_plane_ts/content_digest_single_owner.test.ts index c959f3f069..584b415dcf 100644 --- a/tests/control_plane_ts/content_digest_single_owner.test.ts +++ b/tests/control_plane_ts/content_digest_single_owner.test.ts @@ -107,6 +107,7 @@ const CANONICAL_CONSUMERS = [ "control_plane/capabilities/content_media_image.ts", "control_plane/capabilities/explore_execution_observation.ts", "control_plane/capabilities/explore_result_page.ts", + "control_plane/capabilities/explore_verification_evidence.ts", "control_plane/capabilities/external_evidence.ts", "control_plane/capabilities/goal_capability_organization.ts", "control_plane/capabilities/native_child_result_inbox.ts", @@ -161,6 +162,7 @@ const CANONICAL_CONSUMERS = [ "control_plane/presentation/action_review_plan.ts", "control_plane/presentation/goal_source_links.ts", "control_plane/presentation/report_review.ts", + "control_plane/presentation/verification_workbench.ts", "control_plane/quota/execution_loss_closeout_record.ts", "control_plane/quota/heartbeat_receipt_identity.ts", "control_plane/quota/refresh_external_delivery.ts", diff --git a/tests/control_plane_ts/verification_workbench.test.ts b/tests/control_plane_ts/verification_workbench.test.ts new file mode 100644 index 0000000000..0d6412600f --- /dev/null +++ b/tests/control_plane_ts/verification_workbench.test.ts @@ -0,0 +1,124 @@ +import assert from "node:assert/strict"; +import {createHash} from "node:crypto"; +import test from "node:test"; +import {normalizeExploreExecutionObservation} from "../../loopx/control_plane/capabilities/explore_execution_observation.ts"; +import {verifiedHostDepth} from "../../loopx/control_plane/capabilities/explore_verification_evidence.ts"; +import {parseExploreHistoryPage} from "../../loopx/control_plane/presentation/explore_history.ts"; +import {projectVerificationWorkbench} from "../../loopx/control_plane/presentation/verification_workbench.ts"; +import {projectWorkYardstickPresentations} from "../../loopx/control_plane/work_items/yardstick_source.ts"; + +const baseline = {ref: "fixtures:baseline", sha256: "a".repeat(64)}; +const candidate = "b".repeat(64); +const external = {criterion_id: "external", ref: "receipts:external", sha256: "c".repeat(64)}; +const warm = {criterion_id: "warm", ref: "receipts:warm", sha256: "d".repeat(64)}; +const hooks = {criterion_id: "hooks", ref: "receipts:hooks", sha256: "e".repeat(64)}; +const compaction = {criterion_id: "compaction", ref: "receipts:compaction", sha256: "f".repeat(64)}; +const receipts = [external, warm, hooks, compaction]; +const evidenceRefs = [baseline, ...receipts].map(item => item.ref); +const execution = { + schema_version: "explore_execution_observation_v0", candidate_sha256: candidate, input_revision: "inputs-v1", + planned_method_id: "screen", executed_method_id: "screen", change_reason: null, + elapsed_seconds: 10, limit_seconds: null, search_iterations: null, stop_reason: null, evidence_refs: evidenceRefs, +}; +const exact = {metric: "loss", unit: "points", higher_is_better: false, + comparison_scope: "scope:matched", input_revision: "inputs-v1", evaluation_ref: "check:exact"}; +const proxy = {...exact, metric: "cost", evaluation_ref: "check:proxy"}; +const measure = (profile: typeof exact, sha: string, value: number, ref: string) => + ({...profile, candidate_ref: `sha256:${sha}`, value, evidence_ref: ref}); +const finding = (id: string, fields: Record = {}) => parseExploreHistoryPage({ + ok: true, goal_id: "goal", total: 1, next_cursor: null, + items: [{schema_version: "loopx_explore_result_event_v0", event_kind: "finding", event_id: id, goal_id: "goal", + result_id: id, title: id, agent_id: "worker", recorded_at: "2026-11-21T12:00:00Z", node_id: "question", + status: "confirmed", ...fields}], +}, "goal").items[0]!; + +test("legacy execution and generic CLI retain unknown costs and tier, while measured zero survives", () => { + assert.equal(normalizeExploreExecutionObservation({observation: execution}).verification_evidence, undefined); + const readback = normalizeExploreExecutionObservation({observation: {...execution, + verification_evidence: {host: "generic-cli", costs: {human_confirmations: {value: 0, evidence_ref: external.ref}}}}}); + assert.equal(readback.verification_evidence?.costs?.warm_cache_tokens, undefined); + assert.equal(readback.verification_evidence?.costs?.human_confirmations?.value, 0); + assert.equal(verifiedHostDepth(readback.verification_evidence, receipts), null); +}); + +test("the same exact checked receipts qualify every host name; absent or changed proof caps the tier", () => { + for (const host of ["codex", "pi", "dsh", "generic-cli", "future-host"]) { + const record = normalizeExploreExecutionObservation({observation: {...execution, + verification_evidence: {host, proofs: {external_verifier: external, warm_session_cache: warm, + white_box_hooks: hooks, receipt_compaction: compaction}}}}).verification_evidence; + assert.equal(verifiedHostDepth(record, [warm, hooks, compaction]), null); + assert.equal(verifiedHostDepth(record, [external, {...warm, sha256: compaction.sha256}]), 0); + assert.equal(verifiedHostDepth(record, [external, warm, hooks]), 1); + assert.equal(verifiedHostDepth(record, [external, warm, hooks, {...compaction, criterion_id: "other"}]), 1); + assert.equal(verifiedHostDepth(record, receipts), 2); + } + assert.throws(() => normalizeExploreExecutionObservation({observation: {...execution, + verification_evidence: {baseline: {...baseline, ref: "uncaptured"}}}}), /captured reference/); + assert.throws(() => normalizeExploreExecutionObservation({observation: {...execution, + verification_evidence: {costs: {human_confirmations: {value: -1, evidence_ref: external.ref}}}}}), + /nonnegative/); +}); + +test("each tier requires a distinct verified receipt for the added capability", () => { + const claims = {external_verifier: external, warm_session_cache: warm, + white_box_hooks: hooks, receipt_compaction: compaction}; + const alias = {...warm, sha256: external.sha256}; + assert.equal(verifiedHostDepth({host: "generic-cli", proofs: {...claims, warm_session_cache: external}}, + receipts), 0); + assert.equal(verifiedHostDepth({host: "generic-cli", proofs: {...claims, warm_session_cache: alias}}, + [...receipts, alias]), 0); + assert.equal(verifiedHostDepth({host: "generic-cli", proofs: {...claims, receipt_compaction: warm}}, + receipts), 1); +}); + +test("Yardstick history pins its paired observations to the original work and event prefix", () => { + const selected = finding("selected", {evidence_refs: evidenceRefs, work_yardstick: { + binding: {goal_id: "goal", agent_id: "worker", todo_id: "todo_case", turn_instance_id: "turn-1"}, + decision: {schema_version: "work_yardstick_decision_v0", + target: {summary: "Reduce errors", scope: "Frozen input", acceptance_ref: "check:exact"}, + authoritative: exact, proxy, counterevidence_refs: [baseline.ref], prior_finding_id: null, + next_action: {method_id: "screen", reason: "Compare on fixed inputs", cost_bound: "One evaluation"}}, + }, execution_observation: {...execution, verification_evidence: {baseline}}, + measurements: [measure(exact, candidate, 5, external.ref), measure(proxy, candidate, 8, warm.ref)]}); + const control = finding("control", {evidence_refs: [baseline.ref], measurements: [ + measure(exact, baseline.sha256, 9, baseline.ref), measure(proxy, baseline.sha256, 4, baseline.ref), + ]}); + const negative = finding("negative", {status: "refuted", evidence_refs: [hooks.ref]}); + const foreign = {...control, goal_id: "other"}; + const nearby = {...negative, node_id: "nearby"}; + const binding = selected.work_yardstick!.binding; + const history = (rows: Record[], {count = rows.length, broken = false, legacy = false} = {}) => { + const events = [...rows, selected].map(row => ({goal_id: row.goal_id, event_id: row.event_id, finding: row})); + const digest = createHash("sha256").update(JSON.stringify(events.slice(0, count).map(event => event.event_id))).digest("hex"); + const capture = {...selected.work_yardstick, ...(legacy ? {} : {source_snapshot: { + event_count: count, event_ids_sha256: broken ? "0".repeat(64) : digest, + }})}; + const result = projectWorkYardstickPresentations({ + captures: [{capture, goal_id: "goal", agent_id: "worker", event_id: "selected", evidence_refs: evidenceRefs}], + history_sources: {source_events: events}, + }); + assert.deepEqual(result.captures, [selected.work_yardstick], "The original prefix stays on the server"); + return (result.comparisons as Record).selected; + }; + const earlier = {...control, finding_id: "original-control"}; + const projected = finding("selected", {...selected, yardstick_measurements: history([earlier])}); + const projection = projectVerificationWorkbench(projected, [projected, negative, nearby])!; + assert.equal(projection.fidelity, "different_order"); + assert.deepEqual([projection.authoritative?.delta, projection.proxy?.delta], [4, -4]); + assert.deepEqual(projection.alternatives.map(item => item.event_id), ["negative"]); + assert.equal(projectVerificationWorkbench(selected, [selected, control, foreign])?.fidelity, "unknown", + "Unqualified measurements in browser history cannot repair a missing pair"); + assert.deepEqual(history([{...earlier, work_binding: binding}]), projected.yardstick_measurements); + assert.equal(history([{...earlier, agent_id: "another-worker"}]), undefined); + assert.equal(history([{...earlier, work_binding: {...binding, todo_id: "todo_other"}}]), undefined); + assert.equal(history([foreign]), undefined); + assert.equal(history([earlier], {count: 2}), undefined); + assert.equal(history([earlier], {count: 0}), undefined); + assert.equal(history([earlier], {broken: true}), undefined); + assert.equal(history([earlier], {legacy: true}), undefined); + assert.equal(history([earlier, {...earlier, event_id: "duplicate", finding_id: "other-control"}]), undefined); + assert.equal(history([{...earlier, measurements: control.measurements?.map(row => ({...row, evidence_ref: "uncited"}))}]), undefined); + const revised = {...earlier, event_id: "revision", status: "refuted", measurements: undefined}; + assert.deepEqual(history([earlier, revised], {count: 1}), projected.yardstick_measurements); + assert.equal(history([earlier, revised]), undefined, "A later revision without measurements retires the measured row"); +}); diff --git a/tests/test_chat_explore_results.py b/tests/test_chat_explore_results.py index 6472f52c75..0ffbbbb0a0 100644 --- a/tests/test_chat_explore_results.py +++ b/tests/test_chat_explore_results.py @@ -1,5 +1,7 @@ """Real HTTP readback of saved Explore evidence without worker authority.""" import json +from pathlib import Path +from runpy import run_path import threading from urllib.error import HTTPError from urllib.parse import quote @@ -249,6 +251,86 @@ def read(): worker.join() +@pytest.mark.parametrize("use_local_snapshot", [False, True], ids=["inline", "local-snapshot"]) +def test_populated_history_preserves_pages_and_original_comparisons(tmp_path, monkeypatch, use_local_snapshot): + from tests.control_plane.canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + from loopx.control_plane import effect_runtime + from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection + from loopx.control_plane.work_items import yardstick_decision as transport + + fixture_path = Path(__file__).resolve().parents[1] / "apps/presentation/dashboard/smoke/research-verification-fixture.py" + fixture = run_path(str(fixture_path)) + goal_id = fixture["GOAL"] + isolate_sqlite_runtime(tmp_path, monkeypatch) + runtime, registry, state = (tmp_path / name for name in ("runtime", "registry.json", "active.md")) + state.write_text("# Synthetic research history\n") + registry.write_text(json.dumps({"common_runtime_root": str(runtime), "goals": [ + {"id": goal_id, "repo": str(tmp_path), "state_file": state.name, + "coordination": {"registered_agents": ["worker"]}}, + ]})) + initialize_canonical_authority(runtime, goal_id, + build_todo_runtime_shadow_projection(goal_id=goal_id, todos=[], handoff_mode="soft_claim"), + state_path=state, provider="sqlite") + events = fixture["populated_history"]() + log = explore_result_log_path(runtime, goal_id) + before = b"".join(json.dumps(event).encode() + b"\n" for event in events) + log.parent.mkdir(parents=True, exist_ok=True) + log.write_bytes(before) + + invoke, bytes_sent = transport.effect_runtime_projection_result, [] + + def observe(operation, params): + bytes_sent.append(len(json.dumps(params, ensure_ascii=False, separators=(",", ":")).encode())) + return invoke(operation, params) + + monkeypatch.setattr(transport, "effect_runtime_projection_result", observe) + invocations = [] + if use_local_snapshot: + invoke_effect = effect_runtime.effect_runtime_result + + def observe_effect(operation, params, **kwargs): + if operation == "work_item.yardstick.presentation": + invocations.append(kwargs.get("large_local_snapshot", False)) + return invoke_effect(operation, params, **kwargs) + + monkeypatch.setattr(effect_runtime, "MAX_REQUEST_BYTES", 128 * 1024) + monkeypatch.setattr(effect_runtime, "effect_runtime_result", observe_effect) + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.registry_path, server.runtime_root_override, server.runtime_root = registry, str(runtime), runtime + server.verbose = False + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + url = f"http://127.0.0.1:{server.server_port}/api/chat/explore-results?goal_id={goal_id}&view=history" + try: + cursor, items = "", [] + for size in (40, 40, 40, 31): + with urlopen(url + "&cursor=" + quote(cursor), timeout=20) as response: + page = json.load(response) + assert page["total"] == 151 and len(page["items"]) == size + items.extend(page["items"]) + cursor = page["next_cursor"] + assert bool(cursor) == (len(items) < 151) + assert [row["event_id"] for row in items] == [event["event_id"] for event in events] + assert len(bytes_sent) == 1 and bytes_sent[0] < 1024 * 1024 + if use_local_snapshot: + assert invocations == [False, True] + candidates = [row for row in items if "work_yardstick" in row] + assert len(candidates) == 75 + for attempt, row in enumerate(candidates): + assert set(row["work_yardstick"]) == {"decision", "binding"} + if attempt == 31: + assert "yardstick_measurements" not in row + continue + pair = row["yardstick_measurements"] + assert [item["value"] for item in pair] == [9, 5, 4, 8] + assert pair[0]["evidence_ref"] == pair[2]["evidence_ref"] == f"artifact:baseline-{attempt}" + assert log.read_bytes() == before + finally: + server.shutdown() + worker.join(timeout=5) + server.server_close() + + @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_server_source_snapshot_keeps_legacy_capture_wire_shape(tmp_path, provider, monkeypatch): from tests.control_plane.test_work_yardstick_cli import ( @@ -269,12 +351,12 @@ def test_server_source_snapshot_keeps_legacy_capture_wire_shape(tmp_path, provid title="Another captured declaration", evidence_refs=attachment()["evidence_refs"], work_yardstick=capture)) original = log.read_bytes() import loopx.control_plane.work_items.yardstick_decision as transport - invoke, batches = transport.effect_runtime_result, [] + invoke, batches = transport.effect_runtime_projection_result, [] def observe(operation, params): if operation == "work_item.yardstick.presentation": batches.append(len(params["captures"])) return invoke(operation, params) - monkeypatch.setattr(transport, "effect_runtime_result", observe) + monkeypatch.setattr(transport, "effect_runtime_projection_result", observe) server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) server.registry_path, server.runtime_root_override, server.runtime_root = registry, str(runtime), runtime server.verbose = False