+ complete={complete} stale={stale} busy={busy} zh={zh} stateLabel={stateLabel} timeLabel={timeLabel}/>
>;
};
return
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/research-record-comparison.tsx b/apps/presentation/dashboard/src/features/personal-workspace/research-record-comparison.tsx
index ca9ac689a2..a72ae7905c 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/research-record-comparison.tsx
+++ b/apps/presentation/dashboard/src/features/personal-workspace/research-record-comparison.tsx
@@ -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 = {
- 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; renderSummary?: (event: ExploreHistoryEvent) => ReactNode;
stateLabel: (status: string) => string; timeLabel: (at: string) => string;
}) {
@@ -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(null);
const disclosure = useRef(null);
const returnFrame = useRef(null);
useEffect(() => () => {if (returnFrame.current !== null) cancelAnimationFrame(returnFrame.current);}, []);
@@ -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];
@@ -92,11 +97,16 @@ export function ResearchRecordComparison({events, selected, displayed, renderSum
+
+
+
+
+ {failedPair === pair ? {zh ? "无法开始下载,记录未改变。请重试下载。" : "Could not start the download. Records are unchanged; try downloading again."}
: null}
{[selected, comparison].map((event, i) =>
{i === 0 ? (zh ? "所选记录" : "Selected record") : (zh ? "对照记录" : "Comparison record")}{timeLabel(event.recorded_at)}
)}
{(showAll ? researchComparisonFields : changed).map(field =>
- {field === "summary" && renderSummary ? (zh ? "记录正文" : "Recorded text") : labels[field][zh ? 1 : 0]}
+ {field === "summary" && renderSummary ? (zh ? "记录正文" : "Recorded text") : researchComparisonLabels[field][zh ? 1 : 0]}
{[selected, comparison].map((event, i) =>
{i === 0 ? (zh ? "所选记录" : "Selected record") : (zh ? "对照记录" : "Comparison record")}
{value(event, field)}
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/research-record-report.ts b/apps/presentation/dashboard/src/features/personal-workspace/research-record-report.ts
index 974520442c..24acde75a1 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/research-record-report.ts
+++ b/apps/presentation/dashboard/src/features/personal-workspace/research-record-report.ts
@@ -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.", "原始记录证据;不是分析、同条件评测或验收回执。"),
@@ -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", "越低越好")),
@@ -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";
}
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/research-record-versions.ts b/apps/presentation/dashboard/src/features/personal-workspace/research-record-versions.ts
index 02369d3bd0..2717e2f82a 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/research-record-versions.ts
+++ b/apps/presentation/dashboard/src/features/personal-workspace/research-record-versions.ts
@@ -22,3 +22,13 @@ const normalized = (value: unknown): unknown => {
export function changedResearchFields(left: ExploreHistoryEvent, right: ExploreHistoryEvent) {
return researchComparisonFields.filter(field => JSON.stringify(normalized(left[field])) !== JSON.stringify(normalized(right[field])));
}
+
+export const researchComparisonLabels: Record
= {
+ 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", "执行观察"],
+};
diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md
index f23c4b8ffb..cf32e76149 100644
--- a/docs/guides/getting-started.md
+++ b/docs/guides/getting-started.md
@@ -199,6 +199,22 @@ not an archive restore or a bounded-cost index query. It reads those indexes;
it cannot recover pruned or externally archived events. The research workspace
retains its separate source-record browser and day-group navigation.
+## Save a research record comparison
+
+In a Goal's Research history, search for a record, expand it, then open
+**Compare recorded versions**. Choose the comparison version and use
+**Download comparison (JSON)** or **Download comparison report (Markdown)**.
+Both files contain that exact pair, including a comparison version excluded
+by the search filters. The ordinary reading-report download still exports
+only matching records.
+
+The comparison preserves original text, record identities, evidence references,
+zero and unknown measurements, and the same field differences shown in the
+panel. It discloses incomplete history or a failed refresh; it does not certify
+a matched evaluation, acceptance, or research quality improvement. Source files
+behind references are not downloaded. Keep the report as private as its source
+research. If a download fails, retry without changing the records.
+
## Local State Backup
Before risky migrations, local scheduler changes, or release-install repair,
diff --git a/examples/personal-workspace-browser/research-history.md b/examples/personal-workspace-browser/research-history.md
index d8fdcc6dd7..ff1e2975c6 100644
--- a/examples/personal-workspace-browser/research-history.md
+++ b/examples/personal-workspace-browser/research-history.md
@@ -459,6 +459,7 @@ desktop/narrow layouts without dispatching an Agent:
```sh
node --experimental-strip-types --test apps/presentation/dashboard/src/features/personal-workspace/research-record-search.test.mjs apps/presentation/dashboard/src/features/personal-workspace/research-record-versions.test.mjs
node --experimental-strip-types --test apps/presentation/dashboard/src/features/personal-workspace/research-record-export.test.mjs apps/presentation/dashboard/src/features/personal-workspace/research-record-report.test.mjs
+node --experimental-strip-types --test apps/presentation/dashboard/src/features/personal-workspace/research-comparison-export.test.mjs
LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PERSONAL_WORKSPACE_SCENARIO=research-record-search node examples/personal-workspace-browser-smoke.mjs
LOOPX_DASHBOARD_COVERAGE=1 LOOPX_PERSONAL_WORKSPACE_SCENARIO=research-record-search node examples/personal-workspace-browser-smoke.mjs
```
diff --git a/examples/personal-workspace-browser/research-record-search.mjs b/examples/personal-workspace-browser/research-record-search.mjs
index 0bb21b7d02..0f1dd96419 100644
--- a/examples/personal-workspace-browser/research-record-search.mjs
+++ b/examples/personal-workspace-browser/research-record-search.mjs
@@ -250,10 +250,41 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
assert.match(await comparison.innerText(), /candidate:amber-v2/);
assert.deepEqual(await comparison.locator(".explore-measurement-reading strong").allTextContents(), ["Not measured", "0"]);
const versionSelect = comparison.getByRole("combobox", {name: "Compare with"});
+ const comparisonDownload = async (format = "json") => {
+ const received = page.waitForEvent("download");
+ await comparison.getByRole("button", {name: format === "json" ? "Download comparison (JSON)" : "Download comparison report (Markdown)", exact: true}).click();
+ const file = await received;
+ assert.match(file.suggestedFilename(), /research-comparison-.*-readback\.(json|md)$/);
+ const text = await readFile(await file.path(), "utf8");
+ return format === "json" ? JSON.parse(text) : text;
+ };
+ const pair = await comparisonDownload();
+ assert.deepEqual(pair.selected_record, selected.records[0]);
+ assert.equal(pair.comparison_record.run_id, "run:new", "The comparison outside the search is exported");
+ assert.equal(pair.selected_record.measurements[0].value, null);
+ assert.equal(pair.comparison_record.measurements[0].value, 0);
+ assert.deepEqual(pair.coverage, {loaded_records: 79, exported_records: 2, history_complete: true, refresh_failed: false});
+ assert(pair.changed_fields.includes("measurements"));
await versionSelect.selectOption({index: 1});
await comparison.getByText("Unmeasured follow-up", {exact: true}).waitFor();
assert.match(await comparison.innerText(), /candidate:amber-v3/);
assert.doesNotMatch(await comparison.innerText(), /candidate:amber-v2/);
+ const alternate = await comparisonDownload();
+ assert.equal(alternate.comparison_record.run_id, "run:follow-up");
+ assert.deepEqual(alternate.selected_record, pair.selected_record);
+ const comparisonReport = await comparisonDownload("md");
+ assert.match(comparisonReport, /质量下降|original negative evidence/);
+ assert.match(comparisonReport, /candidate:amber-v3/);
+ assert.doesNotMatch(comparisonReport, /candidate:amber-v2/);
+ assert.match(comparisonReport, /not matched evaluations/);
+ await page.evaluate(() => {
+ const original = URL.createObjectURL;
+ URL.createObjectURL = () => {URL.createObjectURL = original; throw new Error("Synthetic comparison download interruption");};
+ });
+ await comparison.getByRole("button", {name: "Download comparison (JSON)", exact: true}).click();
+ await comparison.getByRole("alert").waitFor();
+ assert.deepEqual((await comparisonDownload()).comparison_record, alternate.comparison_record);
+ assert.equal(await comparison.getByRole("alert").count(), 0);
await versionSelect.selectOption({index: 0});
await comparison.getByText("Later observation", {exact: true}).waitFor();
const includeUnchanged = comparison.getByRole("checkbox", {name: "Include unchanged fields"});
@@ -308,6 +339,12 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
assert.equal(await results.locator("li").count(), 1);
const stale = await download();
assert.equal(stale.coverage.refresh_failed, true);
+ await comparisonSummary.click();
+ const stalePair = await comparisonDownload();
+ assert.equal(stalePair.coverage.refresh_failed, true);
+ assert.deepEqual(stalePair.selected_record, pair.selected_record);
+ assert.match(await comparisonDownload("md"), /Failed; previously read records retained/);
+ await comparisonSummary.click();
assert.deepEqual(stale.filters, selected.filters);
assert.equal(await history.locator(".research-phase").count(), 3, "A failed refresh retains the last complete time range");
assert.match(await report(), /Failed; previously read records retained/);