Skip to content
Merged
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
@@ -0,0 +1,57 @@
import assert from "node:assert/strict";
import test from "node:test";
import {exportResearchComparison, researchComparisonSnapshot} from "./research-comparison-export.ts";
import {changedResearchFields} from "./research-record-versions.ts";
import {researchRecordSnapshot} from "./research-record-export.ts";

const record = (overrides = {}) => ({schema_version: "explore_finding_v0", goal_id: "synthetic", event_id: "old",
event_kind: "finding", result_id: "retained", recorded_at: "2026-01-02T00:00:00Z", title: "Original negative result",
summary: "Earlier evidence", status: "refuted", confidence: "recorded", evidence_refs: ["synthetic:old"], ...overrides});
const old = record({measurements: [{metric: "Score", value: null, evidence_ref: "synthetic:unknown"}]}),
next = record({event_id: "next", title: "Later result", status: "confirmed", run_id: "run:new",
measurements: [{metric: "Score", value: 0, evidence_ref: "synthetic:zero"}]}),
third = record({event_id: "third", title: "Open question", status: "tentative", measurements: []});
const input = (patch = {}) => ({events: [old, next, third], selectedId: "old", comparisonId: "next", complete: true,
stale: false, exportedAt: "2026-01-04T00:00:00Z", ...patch});

test("exact pair includes the comparison outside generic search and uses original diff owner", () => {
assert.deepEqual(researchRecordSnapshot({goalId: "synthetic", ...input(), query: "negative", status: "refuted"}).records, [old]);
const before = JSON.stringify(input());
const pair = JSON.parse(exportResearchComparison(input(), "json", false));
assert.deepEqual(pair.selected_record, old);
assert.deepEqual(pair.comparison_record, next);
assert.deepEqual(pair.changed_fields, changedResearchFields(old, next));
assert.deepEqual(pair.coverage, {loaded_records: 3, exported_records: 2, history_complete: true, refresh_failed: false});
assert.equal(pair.selected_record.measurements[0].value, null);
assert.equal(pair.comparison_record.measurements[0].value, 0);
assert.equal(JSON.stringify(input()), before);
assert.deepEqual(researchComparisonSnapshot(input({comparisonId: "third"})).comparison_record, third);
});

test("invalid, removed, duplicate and cross-result identities fail instead of exporting a substitute", () => {
for (const patch of [{comparisonId: "missing"}, {selectedId: "missing"}, {comparisonId: "old"},
{events: [old, next, {...next}]}, {events: [old, {...next, result_id: "another"}]},
{events: [old, {...next, event_kind: "node"}]}, {events: [old, {...next, goal_id: "other"}]},
{events: [old, next, record({event_id: "unrelated", goal_id: "other"})]}]) {
assert.throws(() => researchComparisonSnapshot(input(patch)));
}
});

test("Markdown retains whole original pair, partial/stale scope and literal untrusted source prose", () => {
const source = "```\n# Forged report\n![image](https://example.test/image)\n````\n完整原文";
const selected = record({summary: source, title: "<img>\n# fake", run_id: "run:old"});
const report = exportResearchComparison(input({events: [selected, next], complete: false, stale: true}), "md", false);
assert(report.includes(`\`\`\`\`\`text\n${source}\n\`\`\`\`\``));
assert.match(report, /Incomplete; unloaded records are not included/);
assert.match(report, /Failed; previously read records retained/);
assert.match(report, /not matched evaluations/);
for (const value of ["run:old", "run:new", "synthetic:old", "synthetic:zero", '"value": 0', '"event_id": "old"', '"event_id": "next"']) assert(report.includes(value));
assert.match(exportResearchComparison(input(), "md", true), /研究记录版本对照/);
});

test("identical field contents preserve distinct record identities without inventing differences", () => {
const peer = {...old, event_id: "peer", recorded_at: "2026-01-03T00:00:00Z"};
const snapshot = researchComparisonSnapshot(input({events: [old, peer], comparisonId: "peer"}));
assert.deepEqual(snapshot.changed_fields, []);
assert.notEqual(snapshot.selected_record.event_id, snapshot.comparison_record.event_id);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import type {ExploreHistoryEvent} from "../../../../../../loopx/control_plane/presentation/explore_history.ts";
import {changedResearchFields, researchComparisonLabels, researchRecordVersions} from "./research-record-versions.ts";
import {researchReportInline, researchReportLiteral} from "./research-record-report.ts";

type ComparisonExport = {
events: readonly ExploreHistoryEvent[]; selectedId: string; comparisonId: string;
complete: boolean; stale: boolean; exportedAt: string;
};

/** Resolve both identities from the retained canonical snapshot, never a display
* translation or the filtered search results. No source references are fetched. */
export function researchComparisonSnapshot(input: ComparisonExport) {
const unique = (id: string) => {
const matches = input.events.filter(event => event.event_id === id);
if (matches.length !== 1) throw new Error("Comparison record is unavailable or ambiguous");
return matches[0]!;
};
const selected = unique(input.selectedId), comparison = unique(input.comparisonId);
if (input.events.some(event => event.goal_id !== selected.goal_id)) throw new Error("Research export Goal mismatch");
if (selected.event_id === comparison.event_id
|| !researchRecordVersions(input.events, selected).includes(comparison)) {
throw new Error("Comparison records must be distinct versions of the same result");
}
return {
goal_id: selected.goal_id, exported_at: input.exportedAt,
coverage: {loaded_records: input.events.length, exported_records: 2,
history_complete: input.complete, refresh_failed: input.stale},
selected_record: selected, comparison_record: comparison,
changed_fields: changedResearchFields(selected, comparison),
};
}

export function exportResearchComparison(input: ComparisonExport, format: "json" | "md", zh: boolean): string {
const snapshot = researchComparisonSnapshot(input);
if (format === "json") return JSON.stringify(snapshot, null, 2) + "\n";
const label = (en: string, cn: string) => zh ? cn : en;
const field = (name: string, value: string | number) => `- **${name}:** ${researchReportInline(String(value))}`;
const lines = [
`# ${label("Research record comparison", "研究记录版本对照")}`,
label("Compares original records, not matched evaluations or changes in research quality.", "比较原始记录,不代表同条件评测或研究质量变化。"),
field("Goal", snapshot.goal_id), field(label("Exported at", "导出时间"), snapshot.exported_at),
field(label("Exported / loaded records", "导出 / 已读记录"), `2 / ${snapshot.coverage.loaded_records}`),
field(label("Selected record", "所选记录"), snapshot.selected_record.event_id),
field(label("Comparison record", "对照记录"), snapshot.comparison_record.event_id),
field(label("History", "历史"), input.complete ? label("Complete loaded history", "已完整载入历史") : label("Incomplete; unloaded records are not included", "不完整;不包含尚未读取的记录")),
field(label("Refresh", "刷新"), input.stale ? label("Failed; previously read records retained", "失败;保留先前读取的记录") : label("No refresh failure reported", "未报告刷新失败")),
label("This file contains the selected pair regardless of search filters. References are identifiers, not downloaded source files. Keep it as private as the source research.", "本文件包含当前选择的两条记录,不受搜索筛选限制。引用是标识,不包含其源文件。请按原研究的隐私范围保管本文件。"),
`## ${label("Changed fields", "不同字段")} · ${snapshot.changed_fields.length}`,
];
for (const key of snapshot.changed_fields) {
lines.push(`### ${researchComparisonLabels[key][zh ? 1 : 0]}`);
for (const [name, record] of [[label("Selected record", "所选记录"), snapshot.selected_record],
[label("Comparison record", "对照记录"), snapshot.comparison_record]] as const) {
lines.push(`#### ${name}`, record[key] === undefined ? label("Not recorded", "未记录")
: researchReportLiteral(typeof record[key] === "string" ? record[key] : JSON.stringify(record[key], null, 2)));
}
}
for (const [name, record] of [[label("Selected original record", "所选完整原始记录"), snapshot.selected_record],
[label("Comparison original record", "对照完整原始记录"), snapshot.comparison_record]] as const) {
lines.push(`## ${name}`, researchReportLiteral(JSON.stringify(record, null, 2)));
}
return lines.join("\n\n") + "\n";
}
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export function ResearchRecordSearch({goalId, events, nodes, displayEvents, disp
{event.evidence_refs.map(ref => <code key={ref}>{ref}</code>)}
</details>
<ResearchRecordComparison events={events} selected={event} displayed={displayed} renderSummary={renderSummary}
zh={zh} stateLabel={stateLabel} timeLabel={timeLabel}/>
complete={complete} stale={stale} busy={busy} zh={zh} stateLabel={stateLabel} timeLabel={timeLabel}/>
</>;
};
return <div className="research-record-search" ref={root}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
import {useEffect, useRef, useState, type ReactNode} from "react";
import type {ExploreHistoryEvent} from "../../../../../../loopx/control_plane/presentation/explore_history.ts";
import {changedResearchFields, researchComparisonFields, researchRecordVersions, type ResearchComparisonField} from "./research-record-versions.ts";
import {changedResearchFields, researchComparisonFields, researchComparisonLabels, researchRecordVersions, type ResearchComparisonField} from "./research-record-versions.ts";
import {ExploreMeasurements} from "./explore-measurements";
import {ContextHelp} from "./context-help";
import {exportResearchComparison} from "./research-comparison-export";
import {downloadReport} from "./report-download";


const labels: Record<ResearchComparisonField, [string, string]> = {
title: ["Title", "标题"], summary: ["Original text", "原文"], status: ["Recorded status", "记录状态"],
blocked_reason: ["Blocked reason", "受阻原因"], evidence_refs: ["Evidence references", "证据引用"],
measurements: ["Measurements", "测量"], confidence: ["Recorded confidence", "记录置信度"],
run_id: ["Run ID", "运行 ID"], agent_id: ["Agent ID", "Agent ID"], node_kind: ["Node kind", "节点类型"],
node_id: ["Node ID", "问题 ID"], parent_id: ["Source group", "来源分组"],
from_node: ["Link source", "关联起点"], to_node: ["Link target", "关联终点"], edge_type: ["Link type", "关联类型"],
supersedes: ["Supersedes", "取代记录"], execution_observation: ["Execution observation", "执行观察"],
};

/** Requested original-source detail; no analysis, acceptance or write path. */
export function ResearchRecordComparison({events, selected, displayed, renderSummary, zh, stateLabel, timeLabel}: {
export function ResearchRecordComparison({events, selected, displayed, renderSummary, complete, stale, busy, zh, stateLabel, timeLabel}: {
events: readonly ExploreHistoryEvent[]; selected: ExploreHistoryEvent; zh: boolean;
complete: boolean; stale: boolean; busy: boolean;
displayed?: ReadonlyMap<string, ExploreHistoryEvent>; renderSummary?: (event: ExploreHistoryEvent) => ReactNode;
stateLabel: (status: string) => string; timeLabel: (at: string) => string;
}) {
Expand All @@ -26,6 +21,7 @@ export function ResearchRecordComparison({events, selected, displayed, renderSum
const [chosen, setChosen] = useState("");
const [showAll, setShowAll] = useState(false);
const [open, setOpen] = useState(false);
const [failedPair, setFailedPair] = useState<string | null>(null);
const disclosure = useRef<HTMLDetailsElement>(null);
const returnFrame = useRef<number | null>(null);
useEffect(() => () => {if (returnFrame.current !== null) cancelAnimationFrame(returnFrame.current);}, []);
Expand All @@ -45,6 +41,15 @@ export function ResearchRecordComparison({events, selected, displayed, renderSum
const comparison = alternatives.find(event => event.event_id === chosen)
?? versions[index - 1] ?? alternatives[0];
if (!comparison) return null;
const pair = JSON.stringify([selected.event_id, comparison.event_id]);
const download = (format: "json" | "md") => {
setFailedPair(null);
try {
const text = exportResearchComparison({events, selectedId: selected.event_id, comparisonId: comparison.event_id,
complete, stale, exportedAt: new Date().toISOString()}, format, zh);
downloadReport(`research-comparison-${selected.goal_id}.${format}`, "", text);
} catch {setFailedPair(pair);}
};
const changed = changedResearchFields(selected, comparison);
const value = (event: ExploreHistoryEvent, field: ResearchComparisonField) => {
const raw = event[field];
Expand Down Expand Up @@ -92,11 +97,16 @@ export function ResearchRecordComparison({events, selected, displayed, renderSum
</ContextHelp>
<label><input type="checkbox" checked={showAll} onChange={event => setShowAll(event.target.checked)}/>{zh ? "包括相同字段" : "Include unchanged fields"}</label>
</div>
<div className="research-comparison-controls">
<button type="button" disabled={busy} onClick={() => download("json")}>{zh ? "下载对照记录(JSON)" : "Download comparison (JSON)"}</button>
<button type="button" disabled={busy} onClick={() => download("md")}>{zh ? "下载对照报告(Markdown)" : "Download comparison report (Markdown)"}</button>
</div>
{failedPair === pair ? <p role="alert">{zh ? "无法开始下载,记录未改变。请重试下载。" : "Could not start the download. Records are unchanged; try downloading again."}</p> : null}
<div className="research-comparison-pair research-comparison-identities">
{[selected, comparison].map((event, i) => <div key={event.event_id}><strong>{i === 0 ? (zh ? "所选记录" : "Selected record") : (zh ? "对照记录" : "Comparison record")}</strong><p>{timeLabel(event.recorded_at)}</p></div>)}
</div>
{(showAll ? researchComparisonFields : changed).map(field => <section key={field} className="research-comparison-field">
<h4>{field === "summary" && renderSummary ? (zh ? "记录正文" : "Recorded text") : labels[field][zh ? 1 : 0]}</h4>
<h4>{field === "summary" && renderSummary ? (zh ? "记录正文" : "Recorded text") : researchComparisonLabels[field][zh ? 1 : 0]}</h4>
<div className="research-comparison-pair">{[selected, comparison].map((event, i) => <div key={event.event_id}>
<span className="research-comparison-side">{i === 0 ? (zh ? "所选记录" : "Selected record") : (zh ? "对照记录" : "Comparison record")}</span>
<div>{value(event, field)}</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ import {researchRecordSnapshot, type ResearchRecordExport} from "./research-reco

// Source prose stays literal: it cannot introduce headings, remote images or
// links into the saved report. Fences grow to preserve embedded code fences.
function literal(text: string): string {
export function researchReportLiteral(text: string): string {
const fence = "`".repeat(Math.max(3, ...Array.from(text.matchAll(/`+/g), match => match[0].length + 1)));
return `${fence}text\n${text}\n${fence}`;
}
const inline = (text: string) => text.replace(/[\\`*_{}\[\]<>()#+.!|~>-]/g, "\\$&").replace(/\r?\n/g, " ");
export const researchReportInline = (text: string) => text.replace(/[\\`*_{}\[\]<>()#+.!|~>-]/g, "\\$&").replace(/\r?\n/g, " ");

/** Human-readable original evidence, using exactly the JSON export's selection. */
export function exportResearchReport(input: ResearchRecordExport, zh: boolean): string {
const snapshot = researchRecordSnapshot(input);
const label = (en: string, cn: string) => zh ? cn : en;
const missing = label("Not recorded", "未记录");
const field = (name: string, value: unknown) => `- **${name}:** ${inline(value === undefined || value === null || value === "" ? missing : String(value))}`;
const field = (name: string, value: unknown) => `- **${name}:** ${researchReportInline(value === undefined || value === null || value === "" ? missing : String(value))}`;
const lines = [
`# ${label("Research record report", "研究记录报告")}`,
label("Original recorded evidence; not an analysis, matched evaluation or acceptance receipt.", "原始记录证据;不是分析、同条件评测或验收回执。"),
Expand All @@ -29,14 +29,14 @@ export function exportResearchReport(input: ResearchRecordExport, zh: boolean):
"筛选可能匹配已保存的展示翻译;以下记录保留原始语言与版本。记录时间不是执行时间。引用是标识,不包含其源文件。请按原研究的隐私范围保管本报告。"),
];
snapshot.records.forEach((record, index) => {
lines.push(`## ${index + 1}. ${inline(record.title)}`, field(label("Recorded at", "记录时间"), record.recorded_at),
lines.push(`## ${index + 1}. ${researchReportInline(record.title)}`, field(label("Recorded at", "记录时间"), record.recorded_at),
field(label("Recorded status", "记录状态"), record.status),
`### ${label("Original text", "原文")}`, record.summary ? literal(record.summary) : missing);
if (record.blocked_reason) lines.push(`### ${label("Blocked reason", "受阻原因")}`, literal(record.blocked_reason));
`### ${label("Original text", "原文")}`, record.summary ? researchReportLiteral(record.summary) : missing);
if (record.blocked_reason) lines.push(`### ${label("Blocked reason", "受阻原因")}`, researchReportLiteral(record.blocked_reason));
if (record.measurements?.length) {
lines.push(`### ${label("Native measurements", "原生测量")}`);
for (const measurement of record.measurements) {
lines.push(`#### ${inline(measurement.metric)}`,
lines.push(`#### ${researchReportInline(measurement.metric)}`,
field(label("Value", "数值"), measurement.value === null ? label("Unknown", "未知") : measurement.value),
field(label("Unit", "单位"), measurement.unit),
field(label("Direction", "方向"), measurement.higher_is_better ? label("Higher is better", "越高越好") : label("Lower is better", "越低越好")),
Expand All @@ -52,8 +52,8 @@ export function exportResearchReport(input: ResearchRecordExport, zh: boolean):
if (record[key]) lines.push(field(key, record[key]));
}
lines.push(field(label("Recorded confidence", "记录置信度"), record.confidence));
lines.push(record.evidence_refs.length ? literal(record.evidence_refs.join("\n")) : label("No evidence references recorded.", "未记录证据引用。"));
if (record.execution_observation) lines.push(`### ${label("Recorded execution observation", "记录的执行观察")}`, literal(JSON.stringify(record.execution_observation, null, 2)));
lines.push(record.evidence_refs.length ? researchReportLiteral(record.evidence_refs.join("\n")) : label("No evidence references recorded.", "未记录证据引用。"));
if (record.execution_observation) lines.push(`### ${label("Recorded execution observation", "记录的执行观察")}`, researchReportLiteral(JSON.stringify(record.execution_observation, null, 2)));
});
return lines.join("\n\n") + "\n";
}
Loading
Loading