diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts index ecf9569884..ef833231a7 100644 --- a/apps/presentation/dashboard/src/data/chat.ts +++ b/apps/presentation/dashboard/src/data/chat.ts @@ -35,6 +35,21 @@ export function exportConfigurationBackup(goalIds?: string[]) { }); } +export type ConfigurationBackupComparison = { + ok: boolean; status: "compared"; before_sha256: string; after_sha256: string; + before_goal_ids: string[]; after_goal_ids: string[]; only_in_before: string[]; only_in_after: string[]; + before_machine_configuration_present: boolean; after_machine_configuration_present: boolean; + change_count: number; changes: {path: string; before_present: boolean; after_present: boolean; before?: unknown; after?: unknown}[]; +}; + +export function compareConfigurationSnapshots(before: Record, after: Record) { + const body = JSON.stringify({before, after}); + if (new TextEncoder().encode(body).byteLength > 64 * 1024 * 1024) { + throw new Error("Combined configuration snapshots exceed the 64 MiB comparison limit."); + } + return requestJson("/api/chat/configuration-backup/compare", {method: "POST", body}); +} + export function restoreConfigurationCheckpoint(backup: Record, execute: boolean) { return requestJson("/api/chat/configuration-backup/restore", { method: "POST", body: JSON.stringify({backup, expected_sha256: backup.sha256, execute}), diff --git a/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.css b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.css new file mode 100644 index 0000000000..73bfeca3bb --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.css @@ -0,0 +1,13 @@ +.personal-backup-comparison { display: grid; gap: 0.75rem; min-width: 0; margin-block: 1.25rem; } +.personal-backup-comparison h3, .personal-backup-comparison h4, .personal-backup-comparison p { margin: 0; overflow-wrap: anywhere; } +.personal-backup-files { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; } +.personal-backup-files > * { min-width: 0; } +.personal-backup-files label { display: grid; gap: 0.5rem; } +.personal-backup-files input { max-width: 100%; } +.personal-backup-comparison details { margin-block: 0.5rem; } +.personal-backup-comparison summary { overflow-wrap: anywhere; cursor: pointer; } +.personal-backup-comparison code { overflow-wrap: anywhere; white-space: pre-wrap; } +.personal-backup-comparison pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 20rem; overflow: auto; } +@media (max-width: 640px) { .personal-backup-files { grid-template-columns: minmax(0, 1fr); } } + +.personal-configuration-preview-digest { display: block; max-width: 100%; overflow-wrap: anywhere; white-space: normal; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.tsx b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.tsx new file mode 100644 index 0000000000..09b404bb5e --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-comparison.tsx @@ -0,0 +1,74 @@ +import {useEffect, useRef, useState} from "react"; +import {compareConfigurationSnapshots, type ConfigurationBackupComparison} from "../../data/chat"; +import {useWorkspaceI18n} from "./i18n"; +import "./configuration-backup-comparison.css"; + +type Snapshot = {name: string; data: Record}; +export function ConfigurationBackupComparisonSettings({disabled, onChange, onReview, onBusyChange}: { + disabled: boolean; onBusyChange: (busy: boolean) => void; onChange: () => void; onReview: (backup: Record) => void; +}) { + const zh = useWorkspaceI18n().locale === "zh-CN"; + const [snapshots, setSnapshots] = useState<[Snapshot | null, Snapshot | null]>([null, null]); + const [comparison, setComparison] = useState(null); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + const alive = useRef(true); + useEffect(() => {alive.current = true; return () => {alive.current = false;};}, []); + const labels = zh ? ["比较前文件", "比较后文件"] : ["Before snapshot", "After snapshot"]; + async function select(file: File | undefined, index: number) { + setComparison(null); setError(""); onChange(); + setSnapshots(previous => index === 0 ? [null, previous[1]] : [previous[0], null]); + if (!file) return; + setBusy(true); onBusyChange(true); + try { + if (file.size > 64 * 1024 * 1024) throw new Error(zh ? "文件超过 64 MiB 比较限制。" : "File exceeds the 64 MiB comparison limit."); + const data: unknown = JSON.parse(await file.text()); + if (!data || Array.isArray(data) || typeof data !== "object") throw new Error(zh ? "请选择配置快照 JSON 文件。" : "Select a configuration snapshot JSON object."); + if (!alive.current) return; + const selected = {name: file.name, data: data as Record}; + setSnapshots(previous => index === 0 ? [selected, previous[1]] : [previous[0], selected]); + } catch (failure) {if (alive.current) setError(String(failure));} finally {if (alive.current) {setBusy(false); onBusyChange(false);}} + } + async function compare() { + if (!snapshots[0] || !snapshots[1]) return; + setBusy(true); onBusyChange(true); setComparison(null); setError(""); onChange(); + try {const compared = await compareConfigurationSnapshots(snapshots[0].data, snapshots[1].data); if (alive.current) setComparison(compared);} + catch (failure) {if (alive.current) setError(String(failure));} finally {if (alive.current) {setBusy(false); onBusyChange(false);}} + } + return
+

{zh ? "比较配置快照" : "Compare configuration snapshots"}

+

{zh ? "先比较两个保存的文件,再选择要核对恢复的快照。比较不会修改当前设置;Goal 仅在某一文件出现可能是备份范围不同,不代表已新建或删除。" : "Compare two saved files before choosing a snapshot to review for recovery. Comparison changes no live settings. Goals present in only one file may reflect different backup cohorts, not creation or deletion."}

+

{zh ? "两文件请求合计最多 64 MiB;完整差异最多 56 MiB,超限时不返回部分结果。" : "Combined request limit: 64 MiB. Complete comparison limit: 56 MiB; oversized comparisons return no partial result."}

+
{labels.map((label, index) => )}
+ + {error ?

{error}

: null} + {comparison ? <> +

{zh ? `已比较:${comparison.change_count} 项差异。当前设置未改变。` : `Compared: ${comparison.change_count} differences. Live settings unchanged.`}

+
{snapshots.map((snapshot, index) => { + const before = index === 0; + const ids = before ? comparison.before_goal_ids : comparison.after_goal_ids; + const only = before ? comparison.only_in_before : comparison.only_in_after; + return
+

{labels[index]}: {snapshot?.name}

+

{ids.length} Goal · {(before ? comparison.before_machine_configuration_present : comparison.after_machine_configuration_present) ? (zh ? "包含设备配置" : "Includes device configuration") : (zh ? "设备配置缺省" : "Device configuration absent")}

+
{zh ? "散列与备份范围" : "Hash and cohort"} +

SHA-256: {before ? comparison.before_sha256 : comparison.after_sha256}

+

Goal: {ids.join(", ") || (zh ? "无" : "None")}

+

{zh ? "仅在此文件: " : "Only in this file: "}{only.join(", ") || (zh ? "无" : "None")}

+
+ +
; + })}
+ {comparison.changes.length === 0 ?

{zh ? "保存的配置内容一致。" : "Stored configuration contents are identical."}

:
{comparison.changes.map(change =>
+ {change.path} +
{[true, false].map(before =>

{labels[before ? 0 : 1]}

+
{(before ? change.before_present : change.after_present) ? JSON.stringify(before ? change.before : change.after, null, 2) : (zh ? "不存在" : "Absent")}
+
)}
+
)}
} + : null} +
; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-settings.tsx b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-settings.tsx index d5847f62ff..4dd4d4fb83 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-settings.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/configuration-backup-settings.tsx @@ -1,6 +1,7 @@ -import {useEffect, useState} from "react"; +import {useEffect, useRef, useState} from "react"; import {exportConfigurationBackup, restoreConfigurationCheckpoint, type ConfigurationBackupResult} from "../../data/chat"; import {useWorkspaceI18n} from "./i18n"; +import {ConfigurationBackupComparisonSettings} from "./configuration-backup-comparison"; import {StateRecoverySettings} from "./state-recovery-settings"; export function ConfigurationBackupSettings({goalId}: {goalId: string | null}) { @@ -11,43 +12,56 @@ export function ConfigurationBackupSettings({goalId}: {goalId: string | null}) { const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [kind, setKind] = useState<"configuration" | "state">("configuration"); - useEffect(() => {setBackup(null); setResult(null); setError(""); setKind("configuration");}, [goalId]); - async function perform(action: () => Promise) { + const generation = useRef(0); + useEffect(() => {generation.current++; setBusy(false); setBackup(null); setResult(null); setError(""); setKind("configuration"); return () => {generation.current++;};}, [goalId]); + async function perform(action: (current: () => boolean) => Promise) { + const request = generation.current; + const current = () => request === generation.current; setBusy(true); setError(""); - try {await action();} catch (failure) {setError(String(failure));} - finally {setBusy(false);} + try {await action(current);} catch (failure) {if (current()) setError(String(failure));} + finally {if (current()) setBusy(false);} } return
{zh ? "配置备份与恢复" : "Configuration backup and recovery"} {goalId === null ?
{zh ? "备份类型" : "Backup type"} - - + +
: null} {kind === "configuration" || goalId !== null ? <>

{zh ? "备份包含私有路径、Goal 设置及设备默认值,需自行保管和审查。凭据文件不包含在此组件中。恢复只建立隔离检查点;启用仍在原配置页面办理。" : "Keep and review this private backup: it includes Goal settings, paths and device defaults. Credential files are outside this component. Recovery creates an isolated checkpoint; activate settings through their existing editors."}

- + {setBackup(null); setResult(null); setError("");}} onReview={candidate => { + setBackup(null); setResult(null); + void perform(async current => { + const preview = await restoreConfigurationCheckpoint(candidate, false); + if (current()) {setBackup(candidate); setResult(preview);} + }); + }} /> - {backup && result?.status === "preview" ? : null} {result ?

{result.status === "restored" ? (zh ? "检查点已恢复并核对;当前设置及存储 provider 未改变。" : "Checkpoint restored and verified. Live settings and storage provider are unchanged.") : (zh ? "配置备份已核对" : "Configuration backup verified")}: {result.goal_count} Goal · {result.machine_configuration_present ? (zh ? "包含设备配置" : "includes device configuration") : (zh ? "设备配置缺省" : "device configuration absent")} + {result.status === "preview" ? SHA-256: {result.sha256} : null} {result.checkpoint_ref ? {result.checkpoint_ref} : null}

: null} {error ?

{error}

: null} : } diff --git a/docs/reference/assets/configuration-backup-comparison.png b/docs/reference/assets/configuration-backup-comparison.png new file mode 100644 index 0000000000..f8ce3213b8 Binary files /dev/null and b/docs/reference/assets/configuration-backup-comparison.png differ diff --git a/docs/reference/assets/configuration-backup-preview-mobile.png b/docs/reference/assets/configuration-backup-preview-mobile.png new file mode 100644 index 0000000000..73ff109bc0 Binary files /dev/null and b/docs/reference/assets/configuration-backup-preview-mobile.png differ diff --git a/docs/reference/configuration-backup.md b/docs/reference/configuration-backup.md index 893d182a61..998c4dc057 100644 --- a/docs/reference/configuration-backup.md +++ b/docs/reference/configuration-backup.md @@ -35,6 +35,81 @@ select several. Full `backup-state` captures its global discovery registry by default, or the selected project registry with `--current-project-only`. The private archive manifest reports configuration verification and presence separately. +### Compare configuration snapshots before recovery + +To review stored configuration changes across an upgrade or an operator edit, +export a snapshot before and after the change, then compare the two files: + +```sh +loopx configuration-backup compare --before before.json --after after.json +loopx --format json configuration-backup compare --before before.json --after after.json +``` + +Both complete envelopes and their digests must verify before any comparison is +returned. The result names `before_sha256`, `after_sha256`, each snapshot's Goal +IDs and machine-configuration presence, and every changed stored value. +`before_present`/`after_present` distinguish a missing field from explicit null, +false, zero or an empty value. Object-key and Goal declaration order do not +create differences; nested arrays retain order and are shown as whole values. +Paths use JSON Pointer escaping (`~0` for `~`, `~1` for `/`), with Goals keyed +by their verified ID under `/goals`, not by the original array offset. + +`only_in_before` and `only_in_after` describe snapshot scope. Since backups can +select different Goal cohorts, these are **not** claims that a live Goal was +created or deleted. Likewise, matching configuration values do not imply equal +snapshot hashes when Goal declaration order differs. No referenced source file +is followed, current settings are not read, and comparison neither writes a +checkpoint nor authorizes activation. The output contains private configuration +values and is not certified for publication. A missing or invalid input fails +without returning a partial comparison. + +Comparison uses the existing private local-snapshot transport when the two +inputs exceed the ordinary 8 MiB request frame. The combined serialized +parameters remain limited to 64 MiB. The complete comparison result is limited +to 56 MiB, reserving one 8 MiB frame for the response envelope within the +existing 64 MiB private-response limit. These are byte limits, not file-count or +change-count limits; no values are silently truncated. An oversized result is +rejected with a size error; export smaller, explicitly selected Goal cohorts +when appropriate. Capture, standalone verification and isolated restore retain +their existing transport behavior and limits. + +Private transport verifies the complete response's byte count and digest before +returning it. If readback cannot be verified, comparison fails rather than +presenting a partial report. Comparison is read-only: such an error does not +mean that settings were changed or that recovery was activated. The transport +owns its temporary files; the comparison accepts snapshots, not paths for the +runtime to follow. + +After review, use the existing `restore` command with the chosen snapshot's +reported digest and a new isolated destination, then inspect its readback. +Comparison does not replace that digest check or the normal configuration +editors. + +In **Settings → Configuration backup and recovery**, choose the before and after +JSON files and select **Compare files**. Open the hash/cohort and changed-value +details to inspect scope and exact values. Invalid files show an error without +enabling recovery from an unverified comparison. Choose **Review before snapshot +for recovery** or **Review after snapshot for recovery** to use the existing +recovery preview, then explicitly select **Restore isolated checkpoint**. The +comparison itself never performs this write, and the checkpoint still does not +activate settings. Replacing a comparison input clears the previous comparison +and recovery selection. + +![Settings comparison: hashes and Goal cohorts above the changed values and explicit recovery choices](assets/configuration-backup-comparison.png) + +The illustrated example uses synthetic snapshots: the after file includes an +additional Goal and a different stored default. Expand **Hash and cohort** to +check which Goals were captured, and expand a changed path to read both values. +The two recovery buttons select a snapshot for preflight; they do not apply the +displayed differences to live settings. The image shows the packaged browser +App, not an installed native desktop qualification. + +On a narrow screen, the recovery preview wraps the complete selected SHA-256 +inside the panel. Check it against the chosen snapshot before selecting +**Restore isolated checkpoint**; selecting a snapshot alone does not restore it. + +![Narrow Settings recovery preview with the complete selected digest and explicit restore button](assets/configuration-backup-preview-mobile.png) + For a reviewed cohort on a host with unreachable historical source registries, repeat `backup-state --configuration-goal-id example` to select the embedded configuration checkpoint. This uses the same strict source-owner capture as diff --git a/examples/personal-workspace-browser/configuration-backup-comparison.mjs b/examples/personal-workspace-browser/configuration-backup-comparison.mjs new file mode 100644 index 0000000000..d888ecd990 --- /dev/null +++ b/examples/personal-workspace-browser/configuration-backup-comparison.mjs @@ -0,0 +1,140 @@ +import assert from "node:assert/strict"; +import {readFile, access} from "node:fs/promises"; +import {join, resolve} from "node:path"; +import {outputDir} from "./fixture.mjs"; + +export async function exerciseConfigurationComparison({page, panel, beforeBytes, afterBytes, root}) { + const before = JSON.parse(beforeBytes), after = JSON.parse(afterBytes); + const registryBefore = await readFile(join(root, "registry.json")); + const machineBefore = await readFile(join(root, "runtime/machine/configuration.json")); + const comparison = () => panel.getByRole("region", {name: "比较配置快照", exact: true}); + const upload = (label, bytes, name) => comparison().getByLabel(label, {exact: true}).setInputFiles({name, mimeType: "application/json", buffer: bytes}); + const fill = async () => { + await upload("比较前文件", beforeBytes, "before.json"); + await upload("比较后文件", afterBytes, "after.json"); + }; + const compare = async () => { + await comparison().getByRole("button", {name: "比较两个文件", exact: true}).click(); + await comparison().getByRole("status").filter({hasText: "2 项差异"}).waitFor(); + }; + await fill(); + await upload("比较后文件", Buffer.from("invalid json"), "invalid.json"); + await comparison().getByRole("alert").waitFor(); + assert.equal(await comparison().getByRole("button", {name: "比较两个文件", exact: true}).isDisabled(), true); + await upload("比较后文件", Buffer.from(JSON.stringify({...after, sha256: "changed"})), "damaged.json"); + await comparison().getByRole("button", {name: "比较两个文件", exact: true}).click(); + await comparison().getByRole("alert").waitFor(); + assert.equal(await comparison().getByRole("button", {name: "核对比较后快照以恢复"}).count(), 0); + await upload("比较后文件", afterBytes, "after.json"); + const endpoint = "**/api/chat/configuration-backup/compare"; + await page.route(endpoint, route => route.fulfill({status: 503, contentType: "application/json", body: JSON.stringify({ok: false, error: "Synthetic comparison unavailable"})})); + await comparison().getByRole("button", {name: "比较两个文件", exact: true}).click(); + await comparison().getByRole("alert").waitFor(); + await page.unroute(endpoint); + const compareButton = comparison().getByRole("button", {name: "比较两个文件", exact: true}); + await compareButton.focus(); + await page.keyboard.press("Enter"); + await comparison().getByRole("status").filter({hasText: "2 项差异"}).waitFor(); + assert.equal(await panel.getByRole("button", {name: "恢复为隔离检查点"}).count(), 0, "Comparison alone must not select a restore candidate"); + await assert.rejects(access(join(root, "runtime/backups/configuration"))); + const hashes = comparison().locator("details").filter({has: page.getByText("散列与备份范围", {exact: true})}); + await hashes.nth(0).locator("summary").click(); + await hashes.nth(1).locator("summary").click(); + await comparison().getByText(before.sha256, {exact: false}).waitFor(); + await comparison().getByText(after.sha256, {exact: false}).waitFor(); + await hashes.nth(1).getByText("仅在此文件: synthetic-next", {exact: true}).waitFor(); + const differences = comparison().getByLabel("配置差异", {exact: true}); + await differences.locator("summary").filter({hasText: "/machine_configuration/namespaces/goal_storage/new_goal_provider"}).click(); + assert.match(await differences.innerText(), /sqlite/); + assert.match(await differences.innerText(), /file/); + await comparison().scrollIntoViewIfNeeded(); + await page.screenshot({path: resolve(outputDir, "configuration-comparison-desktop.png"), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); + await comparison().getByRole("status").scrollIntoViewIfNeeded(); + await page.screenshot({path: resolve(outputDir, "configuration-comparison-mobile.png"), animations: "disabled"}); + await comparison().getByRole("button", {name: "核对比较后快照以恢复"}).click(); + await panel.getByRole("button", {name: "恢复为隔离检查点"}).waitFor(); + async function assertPreviewFits(sha, name) { + const status = panel.getByRole("status").last(); + const digest = status.locator("code"); + assert.equal(await digest.textContent(), `SHA-256: ${sha}`, "The complete reviewed digest must remain available"); + await status.scrollIntoViewIfNeeded(); + const geometry = await digest.evaluate(element => { + const panel = element.closest(".personal-detail-card").getBoundingClientRect(); + const button = element.closest(".personal-detail-card").querySelector(".personal-primary-action").getBoundingClientRect(); + const glyphs = []; + const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + for (let text = walker.nextNode(); text; text = walker.nextNode()) { + for (let index = 0; index < text.textContent.length; index++) { + const range = document.createRange(); range.setStart(text, index); range.setEnd(text, index + 1); + for (const rect of range.getClientRects()) glyphs.push({left: rect.left, right: rect.right}); + } + } + return {width: innerWidth, panel: {left: panel.left, right: panel.right}, button: {left: button.left, right: button.right}, glyphs}; + }); + console.log(`configuration-preview-${name}=${JSON.stringify({width: geometry.width, panel: geometry.panel, button: geometry.button, glyphCount: geometry.glyphs.length, glyphLeft: Math.min(...geometry.glyphs.map(rect => rect.left)), glyphRight: Math.max(...geometry.glyphs.map(rect => rect.right))})}`); + await page.screenshot({path: resolve(outputDir, `configuration-preview-${name}-mobile.png`), animations: "disabled"}); + assert.equal(geometry.width, 390); + assert(geometry.panel.left >= 0 && geometry.panel.right <= geometry.width, "The preview must not widen its clipped settings panel"); + assert(geometry.button.left >= geometry.panel.left && geometry.button.right <= geometry.panel.right, "The restore action must fit the panel"); + assert.equal(geometry.glyphs.length, `SHA-256: ${sha}`.length); + assert(geometry.glyphs.every(rect => rect.left >= geometry.panel.left && rect.right <= Math.min(geometry.panel.right, geometry.width)), "Every digest glyph must be inside the visible content width"); + } + await assertPreviewFits(after.sha256, "after"); + await comparison().getByRole("button", {name: "核对比较前快照以恢复"}).click(); + await panel.getByRole("status").last().filter({hasText: before.sha256}).waitFor(); + await assertPreviewFits(before.sha256, "before"); + await upload("比较前文件", beforeBytes, "before-again.json"); + assert.equal(await panel.getByRole("button", {name: "恢复为隔离检查点"}).count(), 0, "Replacing either input invalidates the reviewed restore candidate"); + + // Leave the context before a real owner response is delivered; returning to + // the same scope must not resurrect old files, comparison or recovery review. + async function remountWhilePending(path, start) { + let release, entered; + const gate = new Promise(resolve => {release = resolve;}); + const requested = new Promise(resolve => {entered = resolve;}); + await page.route(path, async route => {entered(); await gate; await route.fallback();}); + await start(); await requested; + await page.getByRole("radio", {name: "Goal 设置", exact: true}).check(); + await page.getByRole("radio", {name: "本机设置", exact: true}).check(); + await panel.locator(":scope > summary").click(); + const response = page.waitForResponse(response => new URL(response.url()).pathname.endsWith(path.split("/").at(-1))); + release(); await response; + await page.unroute(path); + assert.equal(await comparison().getByRole("status").count(), 0); + assert.equal(await panel.getByRole("button", {name: "恢复为隔离检查点"}).count(), 0); + assert.equal(await comparison().getByText("尚未选择", {exact: true}).count(), 2); + } + await remountWhilePending(endpoint, () => comparison().getByRole("button", {name: "比较两个文件", exact: true}).click()); + await fill(); await compare(); + await remountWhilePending("**/api/chat/configuration-backup/restore", () => comparison().getByRole("button", {name: "核对比较后快照以恢复"}).click()); + await fill(); await compare(); + await comparison().getByRole("button", {name: "核对比较后快照以恢复"}).click(); + await panel.getByRole("button", {name: "恢复为隔离检查点"}).waitFor(); + await assertPreviewFits(after.sha256, "selected-after"); + await panel.getByRole("button", {name: "恢复为隔离检查点"}).click(); + await panel.getByText("检查点已恢复并核对;当前设置及存储 provider 未改变。", {exact: false}).waitFor(); + assert.deepEqual(JSON.parse(await readFile(join(root, "runtime/backups/configuration", after.sha256, "configuration-backup.json"))), after); + await page.setViewportSize({width: 1512, height: 982}); + await page.getByRole("button", {name: "语言", exact: true}).click(); + await page.getByRole("radio", {name: "English", exact: true}).check(); + await page.locator(".personal-settings-tabs").getByRole("button", {name: /Capabilit/}).click(); + const englishPanel = page.locator("details").filter({has: page.getByText("Configuration backup and recovery", {exact: true})}); + await englishPanel.locator(":scope > summary").click(); + const english = englishPanel.getByRole("region", {name: "Compare configuration snapshots", exact: true}); + await english.getByLabel("Before snapshot", {exact: true}).setInputFiles({name: "before.json", mimeType: "application/json", buffer: beforeBytes}); + await english.getByLabel("After snapshot", {exact: true}).setInputFiles({name: "after.json", mimeType: "application/json", buffer: afterBytes}); + await english.getByRole("button", {name: "Compare files", exact: true}).click(); + await english.getByRole("status").filter({hasText: "Compared: 2 differences"}).waitFor(); + for (const summary of await english.getByText("Hash and cohort", {exact: true}).all()) await summary.click(); + await english.locator("summary").filter({hasText: "/machine_configuration/namespaces/goal_storage/new_goal_provider"}).click(); + await english.scrollIntoViewIfNeeded(); + await page.screenshot({path: resolve(outputDir, "configuration-comparison-english.png"), animations: "disabled"}); + await page.getByRole("button", {name: "Language", exact: true}).click(); + await page.getByRole("radio", {name: "Simplified Chinese", exact: true}).check(); + await page.locator(".personal-settings-tabs").getByRole("button", {name: "能力中心", exact: true}).click(); + await panel.locator(":scope > summary").click(); + assert.deepEqual(await readFile(join(root, "registry.json")), registryBefore); + assert.deepEqual(await readFile(join(root, "runtime/machine/configuration.json")), machineBefore); +} diff --git a/examples/personal-workspace-browser/configuration-backup.mjs b/examples/personal-workspace-browser/configuration-backup.mjs index 61384612ab..af8f29c6bd 100644 --- a/examples/personal-workspace-browser/configuration-backup.mjs +++ b/examples/personal-workspace-browser/configuration-backup.mjs @@ -5,6 +5,7 @@ import {tmpdir} from "node:os"; import {join, resolve} from "node:path"; import {repoRoot, outputDir} from "./fixture.mjs"; import {fetchWorkspaceBackend, openWorkspacePage} from "./scenario-context.mjs"; +import {exerciseConfigurationComparison} from "./configuration-backup-comparison.mjs"; import {resolveTestPython} from "../../scripts/test-python.mjs"; // Only the backup routes use a real disposable server. Other workspace state @@ -18,6 +19,12 @@ r=pathlib.Path(sys.argv[1]); runtime=r/'runtime'; registry=r/'registry.json' registry.write_text(json.dumps({'common_runtime_root':str(runtime),'goals':[{'id':'fixture','repo':str(r),'control_plane':{'optional':{'context':'complete '*10000}}}]})) p=runtime/'machine/configuration.json';p.parent.mkdir(parents=True) p.write_text(json.dumps({'schema_version':'loopx_machine_configuration_v0','namespaces':{'goal_storage':{'schema_version':'loopx_goal_storage_defaults_v0','new_goal_provider':'sqlite'}}})) +from loopx.capabilities.configuration_backup import capture_configuration_backup +from loopx.control_plane.effect_runtime import effect_runtime_result +comparison_data=capture_configuration_backup(registry_path=registry,runtime_root=runtime)['data'] +comparison_data['machine_configuration']['namespaces']['goal_storage']['new_goal_provider']='file' +comparison_data['goals'].append({'goal_id':'synthetic-next','goal_configuration':{'id':'synthetic-next','name':'Reviewed next study'}}) +(r/'comparison-after.json').write_text(json.dumps(effect_runtime_result('configuration.backup',{'action':'capture','data':comparison_data}))) source_project=r/'source-project';source_project.mkdir() source_runtime=r/'source-runtime';source_registry=r/'source-registry.json' (source_project/'ACTIVE.md').write_text('# Original Goal\\n\\nPreserve every unfinished commitment.\\n') @@ -99,6 +106,7 @@ export const configurationBackupScenario = { const backup = JSON.parse(bytes); assert.equal(backup.data.machine_configuration.namespaces.goal_storage.new_goal_provider, "sqlite"); assert.equal(backup.data.goals[0].goal_configuration.control_plane.optional.context.length, 90000); + await exerciseConfigurationComparison({page, panel, beforeBytes: bytes, afterBytes: await readFile(join(root, "comparison-after.json")), root}); const input = panel.getByLabel("恢复备份文件"); await input.setInputFiles({name: "backup.json", mimeType: "application/json", buffer: bytes}); await panel.getByRole("button", {name: "恢复为隔离检查点"}).click(); diff --git a/loopx/capabilities/configuration_backup.py b/loopx/capabilities/configuration_backup.py index 54d6d2a295..e86a0a4f90 100644 --- a/loopx/capabilities/configuration_backup.py +++ b/loopx/capabilities/configuration_backup.py @@ -47,6 +47,13 @@ def verify_configuration_backup(backup: dict[str, Any]) -> dict[str, Any]: return result +def compare_configuration_backups(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]: + result: dict[str, Any] = effect_runtime_result("configuration.backup", { + "action": "compare", "before": before, "after": after, + }, large_local_snapshot=True) + return result + + def restore_configuration_backup( backup: dict[str, Any], *, destination: Path, expected_sha256: str, execute: bool = False, ) -> dict[str, Any]: diff --git a/loopx/cli_commands/configuration_backup.py b/loopx/cli_commands/configuration_backup.py index fa6f5719dc..6ebb9dc58d 100644 --- a/loopx/cli_commands/configuration_backup.py +++ b/loopx/cli_commands/configuration_backup.py @@ -5,7 +5,7 @@ import tempfile from pathlib import Path -from ..capabilities.configuration_backup import capture_configuration_backup, restore_configuration_backup, verify_configuration_backup +from ..capabilities.configuration_backup import capture_configuration_backup, compare_configuration_backups, restore_configuration_backup, verify_configuration_backup from ..history import load_registry from ..paths import resolve_runtime_root @@ -18,6 +18,10 @@ def register_configuration_backup(subparsers, add_format): export.add_argument("--goal-id", action="append", help="Select Goal ids; omit to capture all Goals in the invoked registry.") export.add_argument("--output", required=True) export.add_argument("--execute", action="store_true") + compare = commands.add_parser("compare", help="Compare two verified configuration snapshots without changing live settings.") + add_format(compare) + compare.add_argument("--before", required=True) + compare.add_argument("--after", required=True) for name in ("verify", "restore"): command = commands.add_parser(name) add_format(command) @@ -29,6 +33,9 @@ def register_configuration_backup(subparsers, add_format): def render_configuration_backup(payload): + if payload.get("status") == "compared": + from .configuration_backup_compare import render_configuration_comparison + return render_configuration_comparison(payload) return "\n".join(["# Configuration Backup", ""] + [f"- {key}: `{payload[key]}`" for key in ("ok", "status", "sha256", "goal_count", "machine_configuration_present", "written", "readback_verified", "activation_performed", "error") if key in payload]) + "\n" @@ -58,6 +65,10 @@ def handle_configuration_backup(args, *, registry_path, print_payload, output_fo if json.loads(path.read_text(encoding="utf-8")) != backup: raise RuntimeError("configuration backup export readback mismatch") payload.update(status="exported", written=True) + elif args.configuration_backup_command == "compare": + before = json.loads(Path(args.before).expanduser().read_text(encoding="utf-8")) + after = json.loads(Path(args.after).expanduser().read_text(encoding="utf-8")) + payload = compare_configuration_backups(before, after) else: backup = json.loads(Path(args.input).expanduser().read_text(encoding="utf-8")) payload = (verify_configuration_backup(backup) if args.configuration_backup_command == "verify" else diff --git a/loopx/cli_commands/configuration_backup_compare.py b/loopx/cli_commands/configuration_backup_compare.py new file mode 100644 index 0000000000..c4cec7fa6b --- /dev/null +++ b/loopx/cli_commands/configuration_backup_compare.py @@ -0,0 +1,44 @@ +"""Markdown presentation of the verified TypeScript comparison, never a diff owner.""" + +from __future__ import annotations + +import json +import re + + +def _literal(value: object) -> str: + text = json.dumps(value, ensure_ascii=False, indent=2) + # JSON can contain runs of backticks inside strings as well as whole lines. + fence = "`" * max( + [3, *(len(match.group()) + 1 for match in re.finditer(r"`+", text))] + ) + return f"{fence}json\n{text}\n{fence}" + + +def render_configuration_comparison(payload: dict[str, object]) -> str: + lines = [ + "# Configuration snapshot comparison", + "", + "Read-only comparison of stored snapshots. Goals present in only one snapshot may reflect a selected backup cohort, not a live creation or deletion.", + "Live settings and activation are unchanged. This output retains private configuration values.", + ] + for key in ( + "before_sha256", + "after_sha256", + "before_goal_ids", + "after_goal_ids", + "only_in_before", + "only_in_after", + "before_machine_configuration_present", + "after_machine_configuration_present", + "change_count", + ): + lines.extend([f"## {key}", _literal(payload[key])]) + changes = payload.get("changes") + for index, change in enumerate(changes if isinstance(changes, list) else []): + lines.extend([f"## Change {index + 1}", _literal(change)]) + if not changes: + lines.append( + "No stored configuration differences. Goal declaration order is ignored; array order is preserved." + ) + return "\n\n".join(lines) + "\n" diff --git a/loopx/control_plane/configuration_backup.ts b/loopx/control_plane/configuration_backup.ts index 0ee9e2b670..6443a3254c 100644 --- a/loopx/control_plane/configuration_backup.ts +++ b/loopx/control_plane/configuration_backup.ts @@ -3,12 +3,23 @@ import {lstat, mkdir, mkdtemp, readFile, rm} from "node:fs/promises"; import {dirname, isAbsolute, join, resolve} from "node:path"; import type {JsonObject} from "./effect_program.ts"; import {requireJsonObject, requireNonEmptyString} from "./runtime_decode.ts"; -import {canonicalAuthorityJson, canonicalAuthoritySha256, hasExactAuthorityKeys} from "./coordination/authority_store_codec.ts"; +import {authorityUnicodeCompare, canonicalAuthorityJson, canonicalAuthoritySha256, hasExactAuthorityKeys, isAuthorityJsonObject} from "./coordination/authority_store_codec.ts"; import {durableWriteJson, publishNewDirectory} from "./effect_runtime_io.ts"; import {EffectRuntimeConflictError, EffectRuntimeRequestError} from "./effect_runtime_errors.ts"; +import {MAX_INLINE_RESPONSE_BYTES, MAX_LOCAL_SNAPSHOT_BYTES} from "./effect_runtime_snapshot.ts"; const SCHEMA = "loopx_configuration_backup_v0"; +// Reserve a complete inline frame for the response envelope; the global +// transport ceilings and private-file validation remain unchanged. +export const MAX_CONFIGURATION_COMPARISON_BYTES = MAX_LOCAL_SNAPSHOT_BYTES - MAX_INLINE_RESPONSE_BYTES; + +export function requireConfigurationComparisonResultSize(byteCount: number): void { + if (byteCount > MAX_CONFIGURATION_COMPARISON_BYTES) { + throw new EffectRuntimeRequestError("configuration comparison exceeds the 56 MiB complete-result limit; compare smaller Goal cohorts", "request_too_large"); + } +} + function content(value: unknown): JsonObject { const data = requireJsonObject(canonicalAuthorityJson(value), "configuration backup data"); if (!hasExactAuthorityKeys(data, ["machine_configuration", "goals"])) throw new EffectRuntimeRequestError("configuration backup data fields are invalid"); @@ -47,6 +58,50 @@ export function verifyConfigurationBackup(value: unknown): JsonObject { privacy_certified: false, activation_performed: false, readback_verified: true}; } +/** An inert operator comparison, not an adoption plan. Goal cohorts may differ; + * presence in only one snapshot does not establish live creation or deletion. */ +export function compareConfigurationBackups(value: unknown): JsonObject { + const request = requireJsonObject(value, "configuration backup comparison"); + const before = requireJsonObject(request.before, "before configuration backup"); + const after = requireJsonObject(request.after, "after configuration backup"); + const beforeVerification = verifyConfigurationBackup(before); + const afterVerification = verifyConfigurationBackup(after); + const left = content(before.data), right = content(after.data); + const goals = (data: JsonObject) => new Map((data.goals as JsonObject[]).map(goal => + [goal.goal_id as string, goal.goal_configuration])); + const leftGoals = goals(left), rightGoals = goals(right); + const beforeIds = [...leftGoals.keys()].sort(authorityUnicodeCompare); + const afterIds = [...rightGoals.keys()].sort(authorityUnicodeCompare); + const changes: JsonObject[] = []; + const segment = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1"); + const compare = (a: unknown, b: unknown, path: string, aPresent: boolean, bPresent: boolean): void => { + if (aPresent && bPresent) { + if (isAuthorityJsonObject(a) && isAuthorityJsonObject(b)) { + for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort(authorityUnicodeCompare)) { + compare(a[key], b[key], `${path}/${segment(key)}`, Object.hasOwn(a, key), Object.hasOwn(b, key)); + } + return; + } + // Arrays retain order and are compared as a whole; no inferred item identity. + if (JSON.stringify(a) === JSON.stringify(b)) return; + } + changes.push({path, before_present: aPresent, after_present: bPresent, + ...(aPresent ? {before: a} : {}), ...(bPresent ? {after: b} : {})}); + }; + compare(left.machine_configuration, right.machine_configuration, "/machine_configuration", true, true); + for (const id of [...new Set([...beforeIds, ...afterIds])].sort(authorityUnicodeCompare)) { + compare(leftGoals.get(id), rightGoals.get(id), `/goals/${segment(id)}`, leftGoals.has(id), rightGoals.has(id)); + } + const result = {ok: true, status: "compared", before_sha256: beforeVerification.sha256, after_sha256: afterVerification.sha256, + before_goal_ids: beforeIds, after_goal_ids: afterIds, + only_in_before: beforeIds.filter(id => !rightGoals.has(id)), only_in_after: afterIds.filter(id => !leftGoals.has(id)), + before_machine_configuration_present: beforeVerification.machine_configuration_present, + after_machine_configuration_present: afterVerification.machine_configuration_present, + change_count: changes.length, changes, written: false, activation_performed: false, privacy_certified: false}; + requireConfigurationComparisonResultSize(Buffer.byteLength(JSON.stringify(result), "utf8")); + return result; +} + async function requirePhysicalParent(path: string): Promise { // Reject pre-existing symlink ancestors; do not silently follow another runtime. for (let current = path; ; current = dirname(current)) { @@ -97,6 +152,7 @@ export async function configurationBackupOperation(value: unknown): Promise dict[str, Callable[[], None]]: f"{storage_api.CHAT_GOAL_STORAGE_PATH}/import/apply": lambda: self._storage_import(action="apply"), f"{storage_api.CHAT_GOAL_STORAGE_PATH}/import/recover": lambda: self._storage_import(action="readback"), f"{backup_api.CONFIGURATION_BACKUP_PATH}/export": self._configuration_backup_export, + f"{backup_api.CONFIGURATION_BACKUP_PATH}/compare": self._configuration_backup_compare, f"{backup_api.CONFIGURATION_BACKUP_PATH}/restore": self._configuration_backup_restore, f"{recovery_api.STATE_RECOVERY_PATH}/archive": lambda: self._state_recovery_upload("archive"), f"{recovery_api.STATE_RECOVERY_PATH}/manifest": lambda: self._state_recovery_upload("manifest"), diff --git a/loopx/presentation/configuration_backup_api.py b/loopx/presentation/configuration_backup_api.py index d383957b97..6c543b9021 100644 --- a/loopx/presentation/configuration_backup_api.py +++ b/loopx/presentation/configuration_backup_api.py @@ -1,6 +1,9 @@ """Owner-local configuration download and isolated recovery; never activation.""" +from typing import TYPE_CHECKING, Any, Protocol, cast + from ..capabilities.configuration_backup import ( capture_configuration_backup, + compare_configuration_backups, restore_configuration_backup, verify_configuration_backup, ) @@ -9,6 +12,22 @@ CONFIGURATION_BACKUP_PATH = "/api/chat/configuration-backup" +class _ComparisonHTTP(Protocol): + """Operations supplied by the composed HTTP handler, not mixin overrides.""" + + def _read_json(self, *, max_bytes: int) -> dict[str, Any]: ... + + def _send_json(self, payload: dict[str, Any], *, status: int = 200) -> None: ... + + def _send_error(self, message: str, *, status: int, error_code: str) -> None: ... + + +if TYPE_CHECKING: + from ..chat_server import ChatRequestHandler + + _comparison_http_contract: type[_ComparisonHTTP] = ChatRequestHandler + + class ConfigurationBackupRequestMixin: def _configuration_backup_export(self): try: @@ -25,6 +44,17 @@ def _configuration_backup_export(self): self._send_error("Configuration backup could not be captured; inspect the source configuration.", status=400, error_code="configuration_backup_capture_failed") + def _configuration_backup_compare(self) -> None: + http = cast(_ComparisonHTTP, self) + try: + body = http._read_json(max_bytes=MAX_LOCAL_SNAPSHOT_BYTES) + if set(body) != {"before", "after"}: + raise ValueError("configuration comparison requires exactly two snapshots") + http._send_json(compare_configuration_backups(body["before"], body["after"])) + except Exception: + http._send_error("Configuration snapshots could not be compared. Check both files, their digests and the comparison size limit. No settings were changed.", + status=400, error_code="configuration_backup_compare_failed") + def _configuration_backup_restore(self): try: # A configuration checkpoint uses the existing local-snapshot byte diff --git a/tests/control_plane_ts/configuration_backup.test.ts b/tests/control_plane_ts/configuration_backup.test.ts index d3bcaf8391..b320a2115b 100644 --- a/tests/control_plane_ts/configuration_backup.test.ts +++ b/tests/control_plane_ts/configuration_backup.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import {mkdtemp, mkdir, readFile, readdir, realpath, rm, symlink} from "node:fs/promises"; import {tmpdir} from "node:os"; import {join} from "node:path"; -import {captureConfigurationBackup, restoreConfigurationBackup, verifyConfigurationBackup} from "../../loopx/control_plane/configuration_backup.ts"; +import {captureConfigurationBackup, compareConfigurationBackups, restoreConfigurationBackup, verifyConfigurationBackup, MAX_CONFIGURATION_COMPARISON_BYTES, requireConfigurationComparisonResultSize} from "../../loopx/control_plane/configuration_backup.ts"; import {EffectRuntimeConflictError, EffectRuntimeRequestError} from "../../loopx/control_plane/effect_runtime_errors.ts"; function snapshot() { @@ -78,3 +78,72 @@ test("absence remains absence rather than introducing a machine default", () => const backup = captureConfigurationBackup({data: {machine_configuration: null, goals: []}}); assert.equal(verifyConfigurationBackup(backup).machine_configuration_present, false); }); + +test("comparison preserves missing, null, false and array order while aligning Goal identities", () => { + const capture = (machine: unknown, goals: unknown[]) => captureConfigurationBackup({data: {machine_configuration: machine, goals}}); + const goal = (id: string, extra = {}) => ({goal_id: id, goal_configuration: {id, ...extra}}); + const before = capture({settings: {missing: null, enabled: false, zero: 0, ordered: [1, 2]}}, + [goal("shared", {"a/b~c": null}), goal("only-before")]); + const after = capture({settings: {enabled: null, zero: false, ordered: [2, 1], added: false}}, + [goal("only-after"), goal("shared", {"a/b~c": false})]); + const original = JSON.stringify([before, after]); + const result = compareConfigurationBackups({before, after}); + assert.equal(result.before_sha256, before.sha256); + assert.equal(result.after_sha256, after.sha256); + assert.deepEqual(result.only_in_before, ["only-before"]); + assert.deepEqual(result.only_in_after, ["only-after"]); + assert.equal(result.privacy_certified, false); + assert.equal(result.activation_performed, false); + assert.equal(result.written, false); + const changes = result.changes as Array>; + assert.deepEqual(changes.find(row => row.path === "/machine_configuration/settings/missing"), + {path: "/machine_configuration/settings/missing", before_present: true, after_present: false, before: null}); + assert.deepEqual(changes.find(row => row.path === "/machine_configuration/settings/added"), + {path: "/machine_configuration/settings/added", before_present: false, after_present: true, after: false}); + assert.deepEqual(changes.find(row => row.path === "/machine_configuration/settings/ordered")?.after, [2, 1]); + assert.deepEqual(changes.find(row => row.path === "/machine_configuration/settings/zero"), + {path: "/machine_configuration/settings/zero", before_present: true, after_present: true, before: 0, after: false}); + assert.deepEqual(changes.find(row => row.path === "/machine_configuration/settings/enabled"), + {path: "/machine_configuration/settings/enabled", before_present: true, after_present: true, before: false, after: null}); + assert.deepEqual(changes.find(row => row.path === "/goals/shared/a~1b~0c")?.before, null); + assert.deepEqual(changes.find(row => row.path === "/goals/shared/a~1b~0c")?.after, false); + assert.equal(JSON.stringify([before, after]), original); +}); + +test("reordered Goal declarations and object keys do not invent configuration changes", () => { + const a = {goal_id: "a", goal_configuration: {id: "a", values: {left: 1, right: 2}, array: [{left: 1, right: 2}]}}; + const b = {goal_id: "b", goal_configuration: {id: "b"}}; + const before = captureConfigurationBackup({data: {machine_configuration: null, goals: [a, b]}}); + const after = captureConfigurationBackup({data: {machine_configuration: null, + goals: [b, {...a, goal_configuration: {values: {right: 2, left: 1}, array: [{right: 2, left: 1}], id: "a"}}]}}); + assert.notEqual(before.sha256, after.sha256); + assert.equal(compareConfigurationBackups({before, after}).change_count, 0); +}); + +test("both snapshots must verify and machine absence is not an empty object", () => { + const before = captureConfigurationBackup({data: {machine_configuration: null, goals: []}}); + const after = captureConfigurationBackup({data: {machine_configuration: {}, goals: []}}); + const result = compareConfigurationBackups({before, after}); + assert.equal(result.before_machine_configuration_present, false); + assert.equal(result.after_machine_configuration_present, true); + assert.deepEqual(result.changes, [{path: "/machine_configuration", before_present: true, after_present: true, before: null, after: {}}]); + for (const request of [{before: {...before, sha256: "invalid"}, after}, {before, after: {...after, sha256: "invalid"}}, + {before: null, after}]) assert.throws(() => compareConfigurationBackups(request)); +}); + +test("complete comparison size is bounded before a successful result is returned", (context) => { + assert.equal(MAX_CONFIGURATION_COMPARISON_BYTES, 56 * 1024 * 1024); + assert.doesNotThrow(() => requireConfigurationComparisonResultSize(MAX_CONFIGURATION_COMPARISON_BYTES)); + assert.throws(() => requireConfigurationComparisonResultSize(MAX_CONFIGURATION_COMPARISON_BYTES + 1), + error => error instanceof EffectRuntimeRequestError && error.code === "request_too_large"); + const original = Buffer.byteLength; + // Exercise the actual owner preflight at its byte-count boundary without + // allocating a large fixture. Envelope verification still uses real bytes. + context.mock.method(Buffer, "byteLength", (value: string, encoding?: BufferEncoding) => + typeof value === "string" && value.startsWith('{"ok":true,"status":"compared"') + ? MAX_CONFIGURATION_COMPARISON_BYTES + 1 : original(value, encoding)); + const backup = snapshot(); + assert.throws(() => compareConfigurationBackups({before: backup, after: backup}), + error => error instanceof EffectRuntimeRequestError && error.code === "request_too_large" + && error.message.includes("56 MiB complete-result limit")); +}); diff --git a/tests/presentation/test_configuration_backup_compare_api.py b/tests/presentation/test_configuration_backup_compare_api.py new file mode 100644 index 0000000000..422cda9398 --- /dev/null +++ b/tests/presentation/test_configuration_backup_compare_api.py @@ -0,0 +1,58 @@ +"""Configuration Settings compares two snapshots through the existing owner.""" +import copy +import http.client +import json +import threading + +from loopx.capabilities.configuration_backup import compare_configuration_backups +from loopx.control_plane.effect_runtime import effect_runtime_result + + +def test_live_comparison_is_read_only_and_recovers_from_invalid_file(tmp_path): + from loopx.chat_server import ChatHTTPServer, ChatRequestHandler + + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.registry_path = tmp_path / "registry.json" + server.runtime_root = tmp_path / "runtime" + server.verbose = False + server.registry_path.write_text('{"goals":[]}') + before = effect_runtime_result("configuration.backup", {"action": "capture", "data": { + "machine_configuration": None, + "goals": [{"goal_id": "synthetic-before", "goal_configuration": {"id": "synthetic-before", "name": "Old scope"}}], + }}) + after = effect_runtime_result("configuration.backup", {"action": "capture", "data": { + "machine_configuration": None, + "goals": [{"goal_id": "synthetic-after", "goal_configuration": {"id": "synthetic-after", "name": "Reviewed scope"}}], + }}) + initial = server.registry_path.read_bytes() + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + + def post(body): + connection = http.client.HTTPConnection(*server.server_address, timeout=30) + try: + connection.request("POST", "/api/chat/configuration-backup/compare", json.dumps(body), {"Content-Type": "application/json"}) + response = connection.getresponse() + return response.status, json.loads(response.read()) + finally: + connection.close() + + try: + damaged = copy.deepcopy(after) + damaged["sha256"] = "changed" + assert post({"before": before, "after": damaged})[0] == 400 + assert post({"before": before, "after": after, "execute": True})[0] == 400 + assert post({"before": before})[0] == 400 + status, result = post({"before": before, "after": after}) + assert status == 200 + assert result == compare_configuration_backups(before, after) + assert result["only_in_before"] == ["synthetic-before"] + assert result["only_in_after"] == ["synthetic-after"] + assert result["written"] is False and result["activation_performed"] is False + assert server.registry_path.read_bytes() == initial + assert not (server.runtime_root / "backups").exists() + assert post({"before": after, "after": after})[1]["change_count"] == 0 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) diff --git a/tests/test_configuration_backup.py b/tests/test_configuration_backup.py index 8de807d72b..19d094f5d6 100644 --- a/tests/test_configuration_backup.py +++ b/tests/test_configuration_backup.py @@ -488,3 +488,58 @@ def test_browser_backup_reuses_selected_python_without_checkout_shadow(tmp_path) "PYTHONPATH": str(shadow)}, capture_output=True, text=True, timeout=45, ) assert result.returncode == 0, result.stdout + result.stderr + + +def test_cli_compare_exported_snapshots_then_restore_exact_after(environment, tmp_path): + source, runtime, registry, _ = environment + before_path, after_path = tmp_path / 'before.json', tmp_path / 'after.json' + arguments = ('--runtime-root', runtime, '--registry', registry, 'configuration-backup') + assert cli(*arguments, 'export', '--output', before_path, '--execute')[0] == 0 + state = json.loads(source.read_text()) + optional = state['goals'][0]['control_plane']['optional_provider'] + optional.pop('nullable') + optional.update(enabled=False, ordered=[2, 1], note='完整 ``` # not a heading') + source.write_text(json.dumps(state)) + assert cli(*arguments, 'export', '--output', after_path, '--execute')[0] == 0 + before, after = json.loads(before_path.read_text()), json.loads(after_path.read_text()) + paths = [source, runtime / 'machine/configuration.json', before_path, after_path] + unchanged = {path: path.read_bytes() for path in paths} + + def compare(format_name, left, right): + return subprocess.run([sys.executable, '-m', 'loopx.entrypoint', '--format', format_name, + 'configuration-backup', 'compare', '--before', str(left), '--after', str(right)], + env={**os.environ, 'LOOPX_USAGE_PING': '0'}, capture_output=True, text=True, encoding='utf-8', timeout=60) + + result = compare('json', before_path, after_path) + assert result.returncode == 0, result.stderr + payload = json.loads(result.stdout) + assert payload['before_sha256'] == before['sha256'] and payload['after_sha256'] == after['sha256'] + assert payload['before_goal_ids'] == payload['after_goal_ids'] == ['fixture'] + assert payload['activation_performed'] is False and payload['written'] is False + changes = {item['path']: item for item in payload['changes']} + missing = changes['/goals/fixture/control_plane/optional_provider/nullable'] + assert missing['before'] is None and missing['after_present'] is False and 'after' not in missing + assert changes['/goals/fixture/control_plane/optional_provider/enabled']['after'] is False + markdown = compare('markdown', before_path, after_path) + assert markdown.returncode == 0, markdown.stderr + assert before['sha256'] in markdown.stdout and after['sha256'] in markdown.stdout + assert 'not a live creation or deletion' in markdown.stdout + assert '"before_present": true' in markdown.stdout and '"after_present": false' in markdown.stdout + assert '````json' in markdown.stdout and '完整 ``` # not a heading' in markdown.stdout + same = compare('markdown', after_path, after_path) + assert same.returncode == 0 and 'No stored configuration differences' in same.stdout + assert {path: path.read_bytes() for path in paths} == unchanged + code, restored = cli(*arguments, 'restore', '--input', after_path, '--expected-sha256', after['sha256'], + '--destination', tmp_path / 'reviewed-checkpoint', '--execute') + assert code == 0 and restored['activation_performed'] is False + assert json.loads((tmp_path / 'reviewed-checkpoint/configuration-backup.json').read_text()) == after + restored_goals = list((tmp_path / 'reviewed-checkpoint/goals').glob('*.json')) + assert [json.loads(path.read_text()) for path in restored_goals] == [after['data']['goals'][0]['goal_configuration']] + assert {path: path.read_bytes() for path in paths} == unchanged + invalid = tmp_path / 'invalid.json' + invalid.write_text(json.dumps({**after, 'sha256': 'invalid'})) + for left, right in [(invalid, after_path), (before_path, invalid), (before_path, tmp_path / 'missing.json')]: + failure = compare('json', left, right) + rejected = json.loads(failure.stdout) + assert failure.returncode == 1 and rejected['ok'] is False + assert 'changes' not in rejected and 'change_count' not in rejected diff --git a/tests/test_configuration_backup_transport.py b/tests/test_configuration_backup_transport.py new file mode 100644 index 0000000000..321379bf1a --- /dev/null +++ b/tests/test_configuration_backup_transport.py @@ -0,0 +1,78 @@ +"""Large native exports must compare through the existing private transport.""" +import json + +import pytest + +from tests.test_configuration_backup import cli, environment as environment + + +@pytest.mark.parametrize('change_large_value', [False, True]) +def test_large_native_snapshots_compare_without_truncation(environment, tmp_path, change_large_value): + source, runtime, registry, _ = environment + state = json.loads(source.read_text()) + optional = state['goals'][0]['control_plane']['optional_provider'] + optional.update(text='x' * 4_500_000, enabled=True) + source.write_text(json.dumps(state)) + arguments = ('--runtime-root', runtime, '--registry', registry, 'configuration-backup') + before_path, after_path = tmp_path / 'large-before.json', tmp_path / 'large-after.json' + assert cli(*arguments, 'export', '--output', before_path, '--execute')[0] == 0 + optional['enabled'] = False + if change_large_value: + optional['text'] = 'y' * 4_500_000 + source.write_text(json.dumps(state)) + assert cli(*arguments, 'export', '--output', after_path, '--execute')[0] == 0 + for path in (before_path, after_path): + assert path.stat().st_size > 4_500_000 + assert cli(*arguments, 'verify', '--input', path)[0] == 0 + inputs = {path: path.read_bytes() for path in (source, before_path, after_path)} + code, compared = cli(*arguments, 'compare', '--before', before_path, '--after', after_path) + assert code == 0, compared + assert compared['change_count'] == (2 if change_large_value else 1) + assert compared['written'] is False and compared['activation_performed'] is False + changes = {row['path'].rsplit('/', 1)[-1]: row for row in compared['changes']} + assert changes['enabled']['before'] is True and changes['enabled']['after'] is False + if change_large_value: + assert changes['text']['before'] == 'x' * 4_500_000 + assert changes['text']['after'] == 'y' * 4_500_000 + assert {path: path.read_bytes() for path in inputs} == inputs + + +def test_comparison_private_response_failure_is_not_retried_or_returned_partial(environment, monkeypatch): + from loopx.capabilities.configuration_backup import capture_configuration_backup, compare_configuration_backups + from loopx.control_plane import effect_runtime + + source, runtime, registry, _ = environment + state = json.loads(source.read_text()) + optional = state['goals'][0]['control_plane']['optional_provider'] + optional['text'] = 'x' * 4_500_000 + source.write_text(json.dumps(state)) + before = capture_configuration_backup(registry_path=registry, runtime_root=runtime) + optional['text'] = 'y' * 4_500_000 + source.write_text(json.dumps(state)) + after = capture_configuration_backup(registry_path=registry, runtime_root=runtime) + original_source = source.read_bytes() + original_read = effect_runtime._read_local_snapshot_response + observed = [] + + def corrupt_readback(envelope, sink, **kwargs): + observed.append(sink) + assert kwargs['method'] == 'configuration.backup' + assert envelope['result_ref']['byte_count'] > 8 * 1024 * 1024 + return original_read({**envelope, 'result_ref': {**envelope['result_ref'], 'sha256': '0' * 64}}, sink, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(effect_runtime, '_read_local_snapshot_response', corrupt_readback) + with pytest.raises(effect_runtime.EffectRuntimeResponseAmbiguous): + compare_configuration_backups(before, after) + assert len(observed) == 1 # An ambiguous response must not replay the operation. + assert all(not path.exists() and not path.parent.exists() for path in observed) + assert source.read_bytes() == original_source + + # Exercise the unchanged aggregate request ceiling at a reduced fixture + # boundary; neither parameter truncation nor a partial result is allowed. + with monkeypatch.context() as patch: + patch.setattr(effect_runtime, 'MAX_LOCAL_SNAPSHOT_BYTES', 8 * 1024 * 1024) + with pytest.raises(effect_runtime.EffectRuntimeRejected, match='local snapshot is oversized') as failure: + compare_configuration_backups(before, after) + assert failure.value.diagnostic_code == 'request_too_large' + assert source.read_bytes() == original_source