Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(memory): expose backup history and checksum-bound verification receipts
Rahman10c2fb74c5f5
diff --git a/app/api/v1/sys/memory-backup/route.test.ts b/app/api/v1/sys/memory-backup/route.test.tsindex 25025849..3e0f4d22 100644--- a/app/api/v1/sys/memory-backup/route.test.ts+++ b/app/api/v1/sys/memory-backup/route.test.ts@@ -1,11 +1,11 @@import { beforeEach, describe, expect, it, vi } from "vitest";-const mocks = vi.hoisted(() => ({ role: "owner", preview: vi.fn(async () => ({ files: 0 })), create: vi.fn(async () => ({ id: "snapshot" })), verify: vi.fn(async () => ({ id: "snapshot", integrity: true })) }));+const mocks = vi.hoisted(() => ({ role: "owner", history: vi.fn(async (_options?: unknown) => ({ items: [], nextOffset: null })), preview: vi.fn(async () => ({ files: 0 })), create: vi.fn(async () => ({ id: "snapshot" })), verify: vi.fn(async () => ({ id: "snapshot", integrity: true })) }));vi.mock("@/lib/agent/server", () => ({ verifyAuth: async () => true }));vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: async () => ({ role: mocks.role, session: { device_id: "owner" } }) }));vi.mock("@/lib/host/request-api", () => ({ readJson: (req: Request) => req.json(), apiError: (_: string, error: Error) => Response.json({ error: error.message }, { status: 400 }) }));vi.mock("@/lib/host/audit-api", () => ({ audit: async () => undefined }));vi.mock("@/lib/host/limits-api", () => ({ rateLimited: () => false }));-vi.mock("@/lib/host/memory-backup-api", () => ({ previewMemoryBackup: mocks.preview, createMemoryBackup: mocks.create, verifyMemoryBackup: mocks.verify }));+vi.mock("@/lib/host/memory-backup-api", () => ({ previewMemoryBackup: mocks.preview, createMemoryBackup: mocks.create, verifyMemoryBackup: mocks.verify, listMemoryBackups: mocks.history }));import { GET, POST } from "./route";const req = (body: unknown) => new Request("http://localhost/api/v1/sys/memory-backup", { method: "POST", body: JSON.stringify(body) });beforeEach(() => { mocks.role = "owner"; vi.clearAllMocks(); });@@ -21,3 +21,27 @@ describe("server memory backup owner API", () => {expect(mocks.verify).toHaveBeenCalledWith("backup-id", "a".repeat(64));});});++describe("owner backup history API", () => {+ const history = (query = "") => new Request(`http://localhost/api/v1/sys/memory-backup?view=history${query}`);+ it.each(["viewer", "operator"])("denies %s history access", async role => {+ mocks.role = role; expect((await GET(history())).status).toBe(403); expect(mocks.history).not.toHaveBeenCalled();+ });+ it("reads only metadata with no-store and explicit pagination", async () => {+ const response = await GET(history(`&offset=12&revision=${"a".repeat(64)}&source=/etc`));+ expect(response.status).toBe(200); expect(response.headers.get("cache-control")).toBe("private, no-store");+ expect(mocks.history).toHaveBeenCalledWith({ offset: 12, revision: "a".repeat(64) });+ expect(mocks.preview).not.toHaveBeenCalled(); expect(mocks.create).not.toHaveBeenCalled();+ });+ it("rejects malformed offsets and unknown views", async () => {+ for (const offset of ["-1", "1.5", "100000", "abc"]) expect((await GET(history(`&offset=${offset}`))).status).toBe(400);+ expect((await GET(new Request("http://localhost/api/v1/sys/memory-backup?view=other"))).status).toBe(400);+ expect(mocks.history).not.toHaveBeenCalled();+ });+ it("does not hide history failures as empty data", async () => {+ mocks.history.mockRejectedValueOnce(new Error("history changed; refresh"));+ const response = await GET(history()); expect(response.status).toBe(400);+ expect(response.headers.get("cache-control")).toBe("private, no-store");+ expect(await response.json()).toEqual({ error: "history changed; refresh" });+ });+});diff --git a/app/api/v1/sys/memory-backup/route.ts b/app/api/v1/sys/memory-backup/route.tsindex 8122ea5d..a4ce50d3 100644--- a/app/api/v1/sys/memory-backup/route.ts+++ b/app/api/v1/sys/memory-backup/route.ts@@ -4,10 +4,15 @@ import { getSessionContext } from "@/lib/auth/require-session";import { readJson, apiError } from "@/lib/host/request-api";import { audit } from "@/lib/host/audit-api";import { rateLimited } from "@/lib/host/limits-api";-import { previewMemoryBackup, createMemoryBackup, verifyMemoryBackup } from "@/lib/host/memory-backup-api";+import { previewMemoryBackup, createMemoryBackup, verifyMemoryBackup, listMemoryBackups } from "@/lib/host/memory-backup-api";export const runtime = "nodejs";export const dynamic = "force-dynamic";const headers = { "Cache-Control": "private, no-store" };+function failure(error: unknown) {+ const response = apiError("sys/memory-backup", error);+ response.headers.set("Cache-Control", headers["Cache-Control"]);+ return response;+}async function owner(req: Request) {if (!(await verifyAuth(req))) return null;const context = await getSessionContext();@@ -15,8 +20,17 @@ async function owner(req: Request) {}export async function GET(req: Request) {if (!(await owner(req))) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });- try { return NextResponse.json(await previewMemoryBackup(), { headers }); }- catch (error) { return apiError("sys/memory-backup", error); }+ try {+ const query = new URL(req.url).searchParams;+ if (query.get("view") === "history") {+ const offset = query.get("offset") ?? "0";+ if (!/^\d{1,5}$/.test(offset)) return NextResponse.json({ error: "invalid_history_offset" }, { status: 400, headers });+ return NextResponse.json(await listMemoryBackups({ offset: Number(offset), revision: query.get("revision") ?? undefined }), { headers });+ }+ if (query.has("view")) return NextResponse.json({ error: "unknown_view" }, { status: 400, headers });+ return NextResponse.json(await previewMemoryBackup(), { headers });+ }+ catch (error) { return failure(error); }}export async function POST(req: Request) {const context = await owner(req);@@ -29,5 +43,5 @@ export async function POST(req: Request) {const result = body.action === "create" ? await createMemoryBackup() : await verifyMemoryBackup(String(body.id ?? ""), String(body.manifest_sha256 ?? ""));await audit({ action: "sys.memory-backup", target: result.id, ok: true, detail: String(body.action) });return NextResponse.json(result, { headers });- } catch (error) { return apiError("sys/memory-backup", error); }+ } catch (error) { return failure(error); }}diff --git a/bin/mso b/bin/msoindex d7707b02..1d28f484 100755--- a/bin/mso+++ b/bin/mso@@ -40,7 +40,7 @@# unit * logs | start | stop | restart for exact allowlisted units# packages Cached package-update visibility (never applies updates)# cleanup [--run] Preview categories; writes require preview_id, confirm and selected ids-# memory-backup * Local memory snapshot: preview | create | verify (memory-backup --help)+# memory-backup * Local memory snapshot: preview | history | create | verify (memory-backup --help)# status Public service status (no session needed)# health Is this CLI's session valid?# doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issuesdiff --git a/docs/CLI.md b/docs/CLI.mdindex a2032c40..e9fa9ae2 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -80,7 +80,7 @@ Commands:unit * logs | start | stop | restart for exact allowlisted unitspackages Cached package-update visibility (never applies updates)cleanup [--run] Preview categories; writes require preview_id, confirm and selected ids- memory-backup * Local memory snapshot: preview | create | verify (memory-backup --help)+ memory-backup * Local memory snapshot: preview | history | create | verify (memory-backup --help)status Public service status (no session needed)health Is this CLI's session valid?doctor [--fix] Check deps, HTTPS/login origin, service, session, device; --fix repairs safe local issuesdiff --git a/docs/MEMORY-SAFETY.md b/docs/MEMORY-SAFETY.mdindex 3c170043..6d08ffe8 100644--- a/docs/MEMORY-SAFETY.md+++ b/docs/MEMORY-SAFETY.md@@ -35,6 +35,8 @@ destination paths and never returns backed-up contents.```bashmso memory-backup preview+mso memory-backup history+mso memory-backup history <offset> <revision>mso memory-backup create --confirmmso memory-backup verify <id> <manifest-sha256> --confirm```@@ -54,7 +56,22 @@ restore. Concurrent input files can change; this is a per-file verified copy,not a transactional point-in-time snapshot, and it is not offsite protection.Limits: 10,000 files, 40,000 scan entries, 1 GiB input, 32 MiB/file and a 45-second-scan budget. Full resumable inventory/backup and snapshot-history UI remain open.+scan budget. Full resumable inventory/backup remains open. History pagination+continues the saved-snapshot listing only; it does not resume backup copying.++Settings > Backup > Load saved server snapshots reads metadata in bounded pages+of 12 snapshots, at most 200 directory entries and five seconds per request.+Continuation uses a directory revision; changes require refreshing the first page.+The listing is directory order, not a promise of chronological ordering. Corrupt+metadata is shown as unreadable rather than hidden as empty. Manifest validation+requires file and byte totals to match its entries before accepting coverage.++New successful restore rehearsals write an immutable receipt bound to the manifest+checksum. History reports integrity at that recorded time, not a fresh integrity+check. Older snapshots without receipts remain "not recorded"; they are not+silently promoted or invalidated. A partial snapshot stays partial after a passing+restore. Selecting history metadata never starts restore automatically. Receipt+write failures surface as errors and preserve the isolated restore evidence.No backup result grants deletion permission.## Visibility and accessdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 00b39d09..632a1623 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,20 @@+## 2026-09-26 — Backup history and checksum-bound verification records++Extended the existing owner-only server-memory backup, without creating another+backup authority. Settings and CLI can page saved metadata, select an old snapshot+for an explicit isolated restore check, distinguish partial coverage from recorded+integrity, and show unreadable/error states instead of false empty or complete+results. Manifest coverage totals are validated by one shared reader. Successful+rehearsals retain an immutable checksum-bound receipt; old snapshots may lack one.++Targeted synthetic manifest/history/receipt/API/CLI/transport tests pass. The+mandatory release journey now includes the actual Settings backup UI at desktop,+phone and landscape sizes, error/retry and accessibility checks, synthetic backup+transport, and real API role refusals before any private backup access. Full gate+and production evidence remain release obligations, not assertions made here.+History pagination is not resumable copying. Source-release review, complete and+offsite backup, learning coverage and Jev admission remain separate open work.+## 2026-09-26 — Memory safety and second-brain visibilityImplemented fail-closed session-source preservation, preview/confirmation-firstdiff --git a/frontend/slices/os-settings/components/server-backup-history.tsx b/frontend/slices/os-settings/components/server-backup-history.tsxnew file mode 100644index 00000000..e1a337ce--- /dev/null+++ b/frontend/slices/os-settings/components/server-backup-history.tsx@@ -0,0 +1,43 @@+"use client";+import { Fragment, useState } from "react";+import { Archive, RefreshCw } from "lucide-react";+import { SettingsActionRow, SettingsValueRow, SettingsBlock } from "@/features/shell-settings";+import type { MemoryBackupHistory, MemoryBackupHistoryItem, MemoryBackupSummary } from "@/lib/contracts/memory-backup";+import { requestBackup } from "./server-backup-request";++export function backupHistoryLabel(item: MemoryBackupHistoryItem): string {+ if (item.status === "unreadable") return "Snapshot metadata unreadable — not an empty backup";+ const coverage = item.snapshot.state === "partial" ? "Partial snapshot" : "Captured allowlist complete";+ const integrity = item.integrity === "verified-at-recorded-time" ? `Integrity recorded ${item.verifiedAt}`+ : item.integrity === "receipt-invalid" ? "Invalid integrity receipt — recheck required" : "No saved integrity receipt";+ return `${coverage} · ${item.snapshot.scan.files} files · ${integrity}`;+}+export function ServerBackupHistory({ disabled, onSelect }: { disabled: boolean; onSelect: (snapshot: MemoryBackupSummary) => void }) {+ const [page, setPage] = useState<MemoryBackupHistory | null>(null);+ const [items, setItems] = useState<MemoryBackupHistoryItem[]>([]);+ const [busy, setBusy] = useState(false), [error, setError] = useState("");+ const load = async (more = false) => {+ setBusy(true); setError("");+ try {+ const query: Record<string, string> = { view: "history" };+ if (more && page?.nextOffset != null) { query.offset = String(page.nextOffset); query.revision = page.revision; }+ const next = await requestBackup<MemoryBackupHistory>(undefined, query);+ setPage(next);+ setItems((current) => more ? [...current, ...next.items.filter(row => !current.some(old => old.id === row.id))] : next.items);+ } catch (cause) { setError(cause instanceof Error ? cause.message : "Snapshot history unavailable"); }+ finally { setBusy(false); }+ };+ return <>+ <SettingsActionRow label={page ? "Refresh saved server snapshots" : "Load saved server snapshots"} icon={<RefreshCw />} busy={busy} disabled={disabled || busy} onClick={() => void load()} />+ {page && items.length === 0 && !error ? <SettingsValueRow label="Saved snapshots" value={page.nextOffset === null ? "No saved snapshots" : "No snapshots in this page — load more"} /> : null}+ {items.map(item => item.status === "readable"+ ? <Fragment key={item.id}>+ <SettingsActionRow label={`${item.snapshot.createdAt} · ${item.id.slice(0, 8)}`} icon={<Archive />} disabled={disabled || busy} onClick={() => onSelect(item.snapshot)} />+ <SettingsBlock><p className="break-words text-xs text-muted-foreground">{backupHistoryLabel(item)}</p></SettingsBlock>+ </Fragment>+ : <SettingsBlock key={item.id}><p className="break-words text-xs text-muted-foreground">{item.id.slice(0, 8)}: {backupHistoryLabel(item)}</p></SettingsBlock>)}+ {page?.nextOffset != null ? <SettingsActionRow label="Load more saved snapshots" busy={busy} disabled={disabled || busy} onClick={() => void load(true)} /> : null}+ {page ? <SettingsBlock><p className="text-xs text-muted-foreground">Saved metadata in directory order, not a new integrity check. Same-server copies only; no offsite or point-in-time guarantee. Old snapshots may predate persistent integrity receipts. Select one to run a new isolated restore check.</p></SettingsBlock> : null}+ {error ? <SettingsBlock><p role="alert" className="text-xs text-destructive-text">{error}</p></SettingsBlock> : null}+ </>;+}diff --git a/frontend/slices/os-settings/components/server-backup-request.test.ts b/frontend/slices/os-settings/components/server-backup-request.test.tsnew file mode 100644index 00000000..d53f4de7--- /dev/null+++ b/frontend/slices/os-settings/components/server-backup-request.test.ts@@ -0,0 +1,19 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { requestBackup } from "./server-backup-request";+afterEach(() => vi.unstubAllGlobals());+describe("server backup request", () => {+ it("encodes pagination and disables caching", async () => {+ const fetcher = vi.fn(async () => Response.json({ items: [] })); vi.stubGlobal("fetch", fetcher);+ await expect(requestBackup(undefined, { view: "history", offset: "12", revision: "a&b" })).resolves.toEqual({ items: [] });+ expect(fetcher).toHaveBeenCalledWith("/api/v1/sys/memory-backup?view=history&offset=12&revision=a%26b", { cache: "no-store" });+ });+ it("surfaces errors rather than returning an empty history", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: "history_changed" }, { status: 409 })));+ await expect(requestBackup()).rejects.toThrow("history_changed");+ });+ it("keeps explicit confirmation in the existing POST transport", async () => {+ const fetcher = vi.fn(async () => Response.json({ id: "test" })); vi.stubGlobal("fetch", fetcher);+ await requestBackup({ action: "verify", confirm: true });+ expect(fetcher).toHaveBeenCalledWith("/api/v1/sys/memory-backup", expect.objectContaining({ method: "POST", body: '{"action":"verify","confirm":true}' }));+ });+});diff --git a/frontend/slices/os-settings/components/server-backup-request.ts b/frontend/slices/os-settings/components/server-backup-request.tsnew file mode 100644index 00000000..45f425dd--- /dev/null+++ b/frontend/slices/os-settings/components/server-backup-request.ts@@ -0,0 +1,9 @@+export async function requestBackup<T>(body?: Record<string, unknown>, query?: Record<string, string>): Promise<T> {+ const suffix = query ? `?${new URLSearchParams(query)}` : "";+ const response = await fetch(`/api/v1/sys/memory-backup${suffix}`, {+ cache: "no-store", ...(body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}),+ });+ const value = await response.json();+ if (!response.ok) throw new Error(value.error || `Memory backup failed (${response.status})`);+ return value;+}diff --git a/frontend/slices/os-settings/components/server-backup-section.tsx b/frontend/slices/os-settings/components/server-backup-section.tsxindex fa2b638f..82965199 100644--- a/frontend/slices/os-settings/components/server-backup-section.tsx+++ b/frontend/slices/os-settings/components/server-backup-section.tsx@@ -5,15 +5,10 @@ import { DatabaseBackup, ShieldCheck, Search } from "lucide-react";import { SettingsSection, SettingsActionRow, SettingsValueRow, SettingsBlock } from "@/features/shell-settings";import type { MemoryBackupSummary, MemoryBackupVerification, MemoryBackupScan } from "@/lib/contracts/memory-backup";+import { requestBackup as request } from "./server-backup-request";+import { ServerBackupHistory } from "./server-backup-history";+type Preview = { scan: MemoryBackupScan; sourceDiscoveryTruncated: boolean; sourceCount: number; scope: string; directory: string };-async function request<T>(body?: Record<string, unknown>): Promise<T> {- const response = await fetch("/api/v1/sys/memory-backup", {- cache: "no-store", ...(body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}),- });- const value = await response.json();- if (!response.ok) throw new Error(value.error || `Memory backup failed (${response.status})`);- return value;-}const size = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(1)} MiB`;export function ServerBackupSection() {@@ -41,6 +36,7 @@ export function ServerBackupSection() {<SettingsActionRow label="Verify checksum and rehearse restore" icon={<ShieldCheck />} busy={busy === "verify"} disabled={busy !== null} onClick={() => void perform("verify", async () => setVerification(await request<MemoryBackupVerification>({ action: "verify", id: snapshot.id, manifest_sha256: snapshot.manifestSha256, confirm: true })))} /></> : null}{verification ? <SettingsValueRow label="Restore verification" value={`${verification.restoredFiles} files verified · ${verification.complete ? "captured scope complete" : "partial snapshot only"} · source writes: ${verification.sourceWritesPerformed}`} /> : null}+ <ServerBackupHistory disabled={busy !== null} onSelect={(saved) => { setSnapshot(saved); setVerification(null); setError(""); }} />{error ? <SettingsBlock><p role="alert" className="text-xs text-destructive-text">{error}</p></SettingsBlock> : null}</SettingsSection>;}diff --git a/lib/contracts/memory-backup.ts b/lib/contracts/memory-backup.tsindex a17b101c..fae7effb 100644--- a/lib/contracts/memory-backup.ts+++ b/lib/contracts/memory-backup.ts@@ -5,3 +5,10 @@ export type MemoryBackupSummary = {consistency: "per-file-verified-not-point-in-time"; offsite: false;};export type MemoryBackupVerification = { id: string; integrity: boolean; restoredFiles: number; restoreDirectory: string; complete: boolean; sourceWritesPerformed: 0 };++export type MemoryBackupHistoryItem =+ | { id: string; status: "readable"; snapshot: MemoryBackupSummary; integrity: "not-recorded" | "verified-at-recorded-time" | "receipt-invalid"; verifiedAt?: string }+ | { id: string; status: "unreadable"; error: "snapshot-unreadable" };+export type MemoryBackupHistory = {+ items: MemoryBackupHistoryItem[]; nextOffset: number | null; revision: string; order: "directory"; scannedEntries: number;+};diff --git a/lib/host/memory-backup-api.ts b/lib/host/memory-backup-api.tsindex b5fe31c3..3830ed56 100644--- a/lib/host/memory-backup-api.ts+++ b/lib/host/memory-backup-api.ts@@ -1 +1,4 @@export { previewMemoryBackup, createMemoryBackup, verifyMemoryBackup } from "@/lib/memory-backup/service";+import { memoryBackupRoot } from "@/lib/memory-backup/service";+import { listSnapshots } from "@/lib/memory-backup/history";+export const listMemoryBackups = (options: { offset?: number; revision?: string }) => listSnapshots(memoryBackupRoot(), options);diff --git a/lib/memory-backup/history.test.ts b/lib/memory-backup/history.test.tsnew file mode 100644index 00000000..a15e34cc--- /dev/null+++ b/lib/memory-backup/history.test.ts@@ -0,0 +1,86 @@+import { afterEach, describe, expect, it } from "vitest";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { createSnapshot, verifySnapshot } from "./service";+import { listSnapshots } from "./history";+import { readManifest } from "./manifest";+import { readVerification } from "./verification-receipt";+const roots: string[] = [];+async function fixture() {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-history-test-")); roots.push(root);+ const source = path.join(root, "source"), backups = path.join(root, "backups");+ await fs.mkdir(source, { mode: 0o700 });+ await fs.writeFile(path.join(source, "note.md"), "Synthetic backup evidence", { mode: 0o600 });+ const make = (partial = false) => createSnapshot([{ key: "memory", path: source }], backups, partial);+ return { root, source, backups, make };+}+afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });+describe("bounded server backup history", () => {+ it("reports an absent history without creating it", async () => {+ const f = await fixture();+ expect(await listSnapshots(f.backups)).toMatchObject({ items: [], nextOffset: null });+ await expect(fs.stat(f.backups)).rejects.toMatchObject({ code: "ENOENT" });+ });+ it("continues directory pages without duplication or returning source contents", async () => {+ const f = await fixture(), saved = [await f.make(), await f.make(), await f.make()];+ const ids: string[] = []; let offset = 0, revision: string | undefined;+ for (let page = 0; page < 5; page++) {+ const result = await listSnapshots(f.backups, { offset, revision, limit: 1 });+ ids.push(...result.items.map(item => item.id));+ expect(JSON.stringify(result)).not.toContain("Synthetic backup evidence");+ if (result.nextOffset === null) break;+ offset = result.nextOffset; revision = result.revision;+ }+ expect(ids.sort()).toEqual(saved.map(s => s.id).sort()); expect(new Set(ids).size).toBe(3);+ });+ it("refuses stale cursors after the snapshot root changes", async () => {+ const f = await fixture(); await f.make(); await f.make();+ const first = await listSnapshots(f.backups, { limit: 1 });+ await f.make();+ await expect(listSnapshots(f.backups, { offset: first.nextOffset!, revision: first.revision })).rejects.toThrow("changed");+ });+ it.each([{ offset: -1 }, { offset: 1 }, { offset: 32769 }, { limit: 0 }, { limit: 21 }])("rejects invalid cursor %j", async options => {+ const f = await fixture(); await expect(listSnapshots(f.backups, options)).rejects.toThrow("cursor");+ });+ it("reports corrupt metadata and symlink entries as unreadable, not empty", async () => {+ const f = await fixture(), saved = await f.make();+ const manifestPath = path.join(saved.directory, "manifest.json");+ const m = JSON.parse(await fs.readFile(manifestPath, "utf8")); m.scan.files++;+ await fs.writeFile(manifestPath, JSON.stringify(m));+ const alias = "22222222-2222-4222-8222-222222222222";+ await fs.symlink(saved.directory, path.join(f.backups, alias));+ const history = await listSnapshots(f.backups);+ expect(history.items).toHaveLength(2);+ expect(history.items.every(item => item.status === "unreadable")).toBe(true);+ });+ it("distinguishes partial coverage from recorded integrity and preserves sources", async () => {+ const f = await fixture(), saved = await f.make(true);+ const before = await fs.readFile(path.join(f.source, "note.md"));+ const initial = await listSnapshots(f.backups);+ expect(initial.items[0]).toMatchObject({ status: "readable", integrity: "not-recorded", snapshot: { state: "partial" } });+ const verified = await verifySnapshot(f.backups, saved.id, saved.manifestSha256);+ expect(verified).toMatchObject({ complete: false, integrity: true, sourceWritesPerformed: 0 });+ const after = await listSnapshots(f.backups);+ expect(after.items[0]).toMatchObject({ status: "readable", integrity: "verified-at-recorded-time", snapshot: { state: "partial" } });+ expect(await fs.readFile(path.join(f.source, "note.md"))).toEqual(before);+ });+ it("retains the first immutable receipt while later restores use new directories", async () => {+ const f = await fixture(), saved = await f.make();+ const first = await verifySnapshot(f.backups, saved.id, saved.manifestSha256);+ const receipt = path.join(saved.directory, `verification-${saved.manifestSha256}.json`);+ const before = await fs.readFile(receipt);+ const second = await verifySnapshot(f.backups, saved.id, saved.manifestSha256);+ expect(second.restoreDirectory).not.toBe(first.restoreDirectory);+ expect(await fs.readFile(receipt)).toEqual(before);+ });+ it("does not turn malformed or manifest-mismatched receipts into an integrity pass", async () => {+ const f = await fixture(), saved = await f.make();+ const receipt = path.join(saved.directory, `verification-${saved.manifestSha256}.json`);+ await fs.writeFile(receipt, "{}", { mode: 0o600 });+ const { manifest } = await readManifest(f.backups, saved.id);+ expect(await readVerification(saved.directory, saved.manifestSha256, manifest)).toEqual({ integrity: "receipt-invalid" });+ await expect(verifySnapshot(f.backups, saved.id, saved.manifestSha256)).rejects.toThrow("existing verification receipt");+ expect((await listSnapshots(f.backups)).items[0]).toMatchObject({ status: "readable", integrity: "receipt-invalid" });+ });+});diff --git a/lib/memory-backup/history.ts b/lib/memory-backup/history.tsnew file mode 100644index 00000000..5dff7d7f--- /dev/null+++ b/lib/memory-backup/history.ts@@ -0,0 +1,52 @@+import { promises as fs } from "node:fs";+import path from "node:path";+import { pinSecurityStorePath } from "@/lib/security-store-path";+import { digest, existing } from "./io";+import { BACKUP_ID, readManifest, snapshotSummary } from "./manifest";+import { readVerification } from "./verification-receipt";+import type { MemoryBackupHistory } from "@/lib/contracts/memory-backup";++type Options = { offset?: number; revision?: string; limit?: number };+const stamp = (stat: { dev: number; ino: number; mtimeMs: number; ctimeMs: number }) =>+ digest(Buffer.from(JSON.stringify([stat.dev, stat.ino, stat.mtimeMs, stat.ctimeMs])));+/** Metadata only. Cursor is a bounded directory position, invalidated by root changes. */+export async function listSnapshots(root: string, options: Options = {}): Promise<MemoryBackupHistory> {+ const offset = options.offset ?? 0, limit = options.limit ?? 12;+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > 32768 || !Number.isSafeInteger(limit) || limit < 1 || limit > 20 ||+ (offset > 0 && !/^[a-f0-9]{64}$/.test(options.revision ?? ""))) throw new Error("invalid backup history cursor");+ try { await existing(root); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && offset === 0) return { items: [], nextOffset: null, revision: "", order: "directory", scannedEntries: 0 };+ throw error;+ }+ const pin = await pinSecurityStorePath(path.join(root, ".history-index"));+ let dir;+ try {+ const revision = stamp(await pin.directory.stat());+ if (offset > 0 && revision !== options.revision) throw new Error("backup history changed; refresh the first page");+ dir = await fs.opendir(path.dirname(pin.file));+ const items: MemoryBackupHistory["items"] = [];+ const deadline = Date.now() + 5000;+ let position = 0, scannedEntries = 0, finished = false;+ while (position < offset) {+ if (Date.now() > deadline) throw new Error("backup history cursor exceeded read budget; refresh");+ if (!await dir.read()) throw new Error("backup history cursor no longer exists; refresh");+ position++;+ }+ while (items.length < limit && scannedEntries < 200 && Date.now() <= deadline) {+ const entry = await dir.read();+ if (!entry) { finished = true; break; }+ position++; scannedEntries++;+ if (!BACKUP_ID.test(entry.name)) continue;+ if (!entry.isDirectory()) { items.push({ id: entry.name, status: "unreadable", error: "snapshot-unreadable" }); continue; }+ try {+ const value = await readManifest(root, entry.name);+ items.push({ id: entry.name, status: "readable", snapshot: snapshotSummary(value.directory, value.manifestSha256, value.manifest),+ ...await readVerification(value.directory, value.manifestSha256, value.manifest) });+ } catch { items.push({ id: entry.name, status: "unreadable", error: "snapshot-unreadable" }); }+ }+ if (stamp(await pin.directory.stat()) !== revision) throw new Error("backup history changed; refresh the first page");+ if (!finished && position >= 32768) throw new Error("backup history enumeration limit reached; snapshots preserved");+ return { items, nextOffset: finished ? null : position, revision, order: "directory", scannedEntries };+ } finally { await dir?.close(); await pin.directory.close(); }+}diff --git a/lib/memory-backup/manifest.test.ts b/lib/memory-backup/manifest.test.tsnew file mode 100644index 00000000..8197c3e3--- /dev/null+++ b/lib/memory-backup/manifest.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";+import { validateManifest, snapshotComplete, type Manifest } from "./manifest";+const id = "11111111-1111-4111-8111-111111111111";+const fixture = (): Manifest => ({ version: 1, id, createdAt: "2026-01-01T00:00:00.000Z", sourceDiscoveryTruncated: false,+ scan: { files: 1, bytes: 3, missing: 2, rejected: 0, excluded: 1, truncated: false },+ entries: [{ name: "memory/note.md", bytes: 3, sha256: "a".repeat(64), compressedBytes: 23, compressedSha256: "b".repeat(64) }] });+describe("backup manifest coverage", () => {+ it("accepts captured scope with explicitly counted optional missing sources", () => {+ expect(snapshotComplete(validateManifest(fixture(), id))).toBe(true);+ });+ it.each(["files", "bytes"] as const)("rejects inconsistent %s totals", (key) => {+ const m = fixture(); m.scan[key]++;+ expect(() => validateManifest(m, id)).toThrow("coverage totals");+ });+ it("rejects duplicate entries, unsafe names and negative sizes", () => {+ const duplicate = fixture(); duplicate.entries.push(duplicate.entries[0]);+ expect(() => validateManifest(duplicate, id)).toThrow("unsafe backup entry");+ for (const name of ["../escape", "/absolute", "memory/../../escape"]) {+ const m = fixture(); m.entries[0].name = name;+ expect(() => validateManifest(m, id)).toThrow("unsafe backup entry");+ }+ const m = fixture(); m.entries[0].bytes = -1;+ expect(() => validateManifest(m, id)).toThrow("unsafe backup entry");+ });+ it("keeps truncated, rejected, empty and discovery-incomplete captures partial", () => {+ for (const key of ["truncated", "rejected"] as const) {+ const m = fixture(); Object.assign(m.scan, { [key]: key === "truncated" ? true : 1 });+ expect(snapshotComplete(validateManifest(m, id))).toBe(false);+ }+ const m = fixture(); m.sourceDiscoveryTruncated = true;+ expect(snapshotComplete(m)).toBe(false);+ m.entries = []; m.scan.files = 0; m.scan.bytes = 0;+ expect(snapshotComplete(validateManifest(m, id))).toBe(false);+ });+ it("rejects malformed metadata before accepting a snapshot", () => {+ for (const patch of [{ createdAt: "invalid" }, { version: 2 }, { sourceDiscoveryTruncated: "false" }, { scan: {} }]) {+ expect(() => validateManifest({ ...fixture(), ...patch }, id)).toThrow("invalid backup manifest");+ }+ });+});diff --git a/lib/memory-backup/manifest.ts b/lib/memory-backup/manifest.tsnew file mode 100644index 00000000..cca0b934--- /dev/null+++ b/lib/memory-backup/manifest.ts@@ -0,0 +1,52 @@+import path from "node:path";+import { digest, readBytes, safeRelative } from "./io";+import { LIMITS, type Scan } from "./scan";+import type { MemoryBackupSummary } from "@/lib/contracts/memory-backup";++export const BACKUP_ID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;+export const SHA256 = /^[a-f0-9]{64}$/;+export const MANIFEST_BYTES = 8 * 1024 * 1024;+export type Entry = { name: string; bytes: number; sha256: string; compressedBytes: number; compressedSha256: string };+export type Manifest = { version: 1; id: string; createdAt: string; scan: Scan; sourceDiscoveryTruncated: boolean; entries: Entry[] };+export function backupTarget(root: string, id: string) {+ if (!BACKUP_ID.test(id)) throw new Error("invalid memory backup id");+ return path.join(root, id);+}+const count = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;+export function validateManifest(value: unknown, id: string): Manifest {+ const m = value as Manifest;+ if (!m || m.version !== 1 || m.id !== id || !Array.isArray(m.entries) || m.entries.length > LIMITS.files ||+ typeof m.createdAt !== "string" || !Number.isFinite(Date.parse(m.createdAt)) || typeof m.sourceDiscoveryTruncated !== "boolean" ||+ !m.scan || typeof m.scan.truncated !== "boolean" || ![m.scan.files, m.scan.bytes, m.scan.missing, m.scan.rejected, m.scan.excluded].every(count)) {+ throw new Error("invalid backup manifest");+ }+ const names = new Set<string>();+ let total = 0;+ for (const row of m.entries) {+ if (!row || typeof row.name !== "string" || !safeRelative(row.name) || names.has(row.name) ||+ !count(row.bytes) || row.bytes > LIMITS.fileBytes || !count(row.compressedBytes) || row.compressedBytes > LIMITS.fileBytes + 65536 ||+ typeof row.sha256 !== "string" || !SHA256.test(row.sha256) || typeof row.compressedSha256 !== "string" || !SHA256.test(row.compressedSha256)) {+ throw new Error("unsafe backup entry");+ }+ names.add(row.name); total += row.bytes;+ if (total > LIMITS.bytes) throw new Error("restore size limit exceeded");+ }+ if (m.scan.files !== m.entries.length || m.scan.bytes !== total) throw new Error("backup coverage totals mismatch");+ return m;+}+export async function readManifest(root: string, id: string, expectedSha?: string) {+ const directory = backupTarget(root, id);+ if (expectedSha !== undefined && !SHA256.test(expectedSha)) throw new Error("manifest checksum required");+ const bytes = await readBytes(path.join(directory, "manifest.json"), MANIFEST_BYTES);+ const manifestSha256 = digest(bytes);+ if (expectedSha !== undefined && manifestSha256 !== expectedSha) throw new Error("backup manifest checksum mismatch");+ return { directory, manifestSha256, manifest: validateManifest(JSON.parse(bytes.toString("utf8")), id) };+}+export function snapshotComplete(manifest: Manifest) {+ return manifest.entries.length > 0 && !manifest.scan.truncated && !manifest.scan.rejected && !manifest.sourceDiscoveryTruncated;+}+export function snapshotSummary(directory: string, manifestSha256: string, m: Manifest): MemoryBackupSummary {+ return { id: m.id, createdAt: m.createdAt, directory, manifestSha256, scan: m.scan,+ compressedBytes: m.entries.reduce((sum, e) => sum + e.compressedBytes, 0), sourceDiscoveryTruncated: m.sourceDiscoveryTruncated,+ state: snapshotComplete(m) ? "snapshot" : "partial", consistency: "per-file-verified-not-point-in-time", offsite: false };+}diff --git a/lib/memory-backup/service.ts b/lib/memory-backup/service.tsindex 0eb0f14f..84805289 100644--- a/lib/memory-backup/service.ts+++ b/lib/memory-backup/service.ts@@ -5,19 +5,14 @@ import { randomUUID } from "node:crypto";import { gzip, gunzipSync } from "node:zlib";import { promisify } from "node:util";import { memorySources, type Source } from "./sources";-import { scanSources, LIMITS, type Limits, type Scan } from "./scan";-import { digest, readBytes, safeRelative, writeExclusive } from "./io";+import { scanSources, LIMITS, type Limits } from "./scan";+import { digest, readBytes, writeExclusive } from "./io";+import { backupTarget as target, readManifest, snapshotComplete, type Entry, type Manifest } from "./manifest";+import { recordVerification } from "./verification-receipt";import type { MemoryBackupSummary, MemoryBackupVerification } from "@/lib/contracts/memory-backup";const compress = promisify(gzip);-const ID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;-type Entry = { name: string; bytes: number; sha256: string; compressedBytes: number; compressedSha256: string };-type Manifest = { version: 1; id: string; createdAt: string; scan: Scan; sourceDiscoveryTruncated: boolean; entries: Entry[] };export const memoryBackupRoot = () => path.join(os.homedir(), ".mso", "backups", "memory");-function target(root: string, id: string) {- if (!ID.test(id)) throw new Error("invalid memory backup id");- return path.join(root, id);-}export async function previewMemoryBackup() {const inventory = await memorySources();@@ -63,18 +58,7 @@ export async function createMemoryBackup() {/** Restore rehearsal writes a NEW isolated tree only; never restore over source. */export async function verifySnapshot(root: string, id: string, expectedManifestSha256: string): Promise<MemoryBackupVerification> {- if (!/^[a-f0-9]{64}$/.test(expectedManifestSha256)) throw new Error("manifest checksum required");- const directory = target(root, id), bytes = await readBytes(path.join(directory, "manifest.json"), 8 * 1024 * 1024);- if (digest(bytes) !== expectedManifestSha256) throw new Error("backup manifest checksum mismatch");- const manifest = JSON.parse(bytes.toString("utf8")) as Manifest;- if (manifest.version !== 1 || manifest.id !== id || !Array.isArray(manifest.entries) || manifest.entries.length > LIMITS.files || !manifest.scan) throw new Error("invalid backup manifest");- const names = new Set<string>();- let total = 0;- for (const row of manifest.entries) {- if (!row || !safeRelative(row.name) || names.has(row.name) || !Number.isSafeInteger(row.bytes) || row.bytes < 0 || row.bytes > LIMITS.fileBytes || !Number.isSafeInteger(row.compressedBytes) || row.compressedBytes < 0 || row.compressedBytes > LIMITS.fileBytes + 65536 || !/^[a-f0-9]{64}$/.test(row.sha256) || !/^[a-f0-9]{64}$/.test(row.compressedSha256)) throw new Error("unsafe backup entry");- names.add(row.name); total += row.bytes;- if (total > LIMITS.bytes) throw new Error("restore size limit exceeded");- }+ const { directory, manifest } = await readManifest(root, id, expectedManifestSha256);const restoreDirectory = path.join(directory, `restore-check-${randomUUID()}`);let restoredFiles = 0;for (const row of manifest.entries) {@@ -88,9 +72,10 @@ export async function verifySnapshot(root: string, id: string, expectedManifestSrestoredFiles++;}const result = { id, integrity: true, restoredFiles, restoreDirectory,- complete: restoredFiles > 0 && !manifest.scan.truncated && !manifest.scan.rejected && !manifest.sourceDiscoveryTruncated,+ complete: snapshotComplete(manifest),sourceWritesPerformed: 0 as const };await writeExclusive(path.join(restoreDirectory, "verification.json"), Buffer.from(JSON.stringify(result)));+ await recordVerification(directory, expectedManifestSha256, result);return result;}diff --git a/lib/memory-backup/verification-receipt.ts b/lib/memory-backup/verification-receipt.tsnew file mode 100644index 00000000..0376f82f--- /dev/null+++ b/lib/memory-backup/verification-receipt.ts@@ -0,0 +1,39 @@+import path from "node:path";+import { readBytes, writeExclusive } from "./io";+import { BACKUP_ID, type Manifest, snapshotComplete } from "./manifest";+import type { MemoryBackupVerification } from "@/lib/contracts/memory-backup";++type Receipt = { version: 1; manifestSha256: string; verifiedAt: string; result: MemoryBackupVerification };+export type IntegrityRecord = { integrity: "not-recorded" | "verified-at-recorded-time" | "receipt-invalid"; verifiedAt?: string };+const receiptPath = (directory: string, sha: string) => path.join(directory, `verification-${sha}.json`);+function valid(value: unknown, directory: string, sha: string, manifest?: Manifest): value is Receipt {+ const r = value as Receipt, v = r?.result;+ return !!r && r.version === 1 && r.manifestSha256 === sha && typeof r.verifiedAt === "string" && Number.isFinite(Date.parse(r.verifiedAt)) &&+ !!v && v.id === path.basename(directory) && v.integrity === true && v.sourceWritesPerformed === 0 && typeof v.complete === "boolean" &&+ Number.isSafeInteger(v.restoredFiles) && v.restoredFiles >= 0 && typeof v.restoreDirectory === "string" &&+ path.dirname(v.restoreDirectory) === directory && path.basename(v.restoreDirectory).startsWith("restore-check-") &&+ BACKUP_ID.test(path.basename(v.restoreDirectory).slice("restore-check-".length)) &&+ (!manifest || (v.restoredFiles === manifest.entries.length && v.complete === snapshotComplete(manifest)));+}+/** Immutable receipt of a completed rehearsal; never a claim of current re-verification. */+export async function recordVerification(directory: string, sha: string, result: MemoryBackupVerification) {+ const receipt: Receipt = { version: 1, manifestSha256: sha, verifiedAt: new Date().toISOString(), result };+ try { await writeExclusive(receiptPath(directory, sha), Buffer.from(JSON.stringify(receipt))); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;+ const prior: unknown = JSON.parse((await readBytes(receiptPath(directory, sha), 4096)).toString("utf8"));+ if (!valid(prior, directory, sha) || prior.result.restoredFiles !== result.restoredFiles || prior.result.complete !== result.complete) {+ throw new Error("invalid existing verification receipt; restore evidence preserved");+ }+ }+}+export async function readVerification(directory: string, sha: string, manifest: Manifest): Promise<IntegrityRecord> {+ try {+ const receipt: unknown = JSON.parse((await readBytes(receiptPath(directory, sha), 4096)).toString("utf8"));+ return valid(receipt, directory, sha, manifest)+ ? { integrity: "verified-at-recorded-time", verifiedAt: receipt.verifiedAt }+ : { integrity: "receipt-invalid" };+ } catch (error) {+ return { integrity: (error as NodeJS.ErrnoException).code === "ENOENT" ? "not-recorded" : "receipt-invalid" };+ }+}diff --git a/scripts/cli/memory-backup.sh b/scripts/cli/memory-backup.shindex d510d020..973828f3 100644--- a/scripts/cli/memory-backup.sh+++ b/scripts/cli/memory-backup.sh@@ -2,8 +2,15 @@# Owner-only memory snapshots; uses the existing authenticated transport.mso_memory_backup() {case "${1:-preview}" in- -h|--help|help) printf '%s\n' 'Usage: mso memory-backup preview | create --confirm | verify <id> <manifest-sha256> --confirm' 'Local allowlisted memory snapshot, not a full VPS/database or offsite backup. Verify restores only into a new isolated directory.' ;;+ -h|--help|help) printf '%s\n' 'Usage: mso memory-backup preview | history [offset revision] | create --confirm | verify <id> <manifest-sha256> --confirm' 'Local allowlisted memory snapshot, not a full VPS/database or offsite backup. Verify restores only into a new isolated directory.' ;;preview) jget "/api/v1/sys/memory-backup" ;;+ history)+ [ "$#" -eq 1 ] || [ "$#" -eq 3 ] || die "memory-backup history accepts [offset revision]"+ if [ "$#" -eq 1 ]; then jget "/api/v1/sys/memory-backup?view=history"+ else+ [[ "$2" =~ ^[0-9]{1,5}$ ]] && [[ "$3" =~ ^[a-f0-9]{64}$ ]] || die "invalid backup history cursor"+ jget "/api/v1/sys/memory-backup?view=history&offset=$2&revision=$3"+ fi ;;create)[ "${2-}" = "--confirm" ] && [ "$#" -eq 2 ] || die "memory-backup create requires --confirm"jpost "/api/v1/sys/memory-backup" '{"action":"create","confirm":true}' ;;diff --git a/scripts/cli/memory-backup.test.ts b/scripts/cli/memory-backup.test.tsnew file mode 100644index 00000000..6667beaa--- /dev/null+++ b/scripts/cli/memory-backup.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";+import { spawnSync } from "node:child_process";+import path from "node:path";+const script = path.resolve("scripts/cli/memory-backup.sh");+function run(...args: string[]) {+ return spawnSync("bash", ["-c", 'source "$1"; shift; jget() { printf "%s" "$1"; }; jpost() { printf "%s" "$2"; }; die() { exit 2; }; mso_memory_backup "$@"', "test", script, ...args], { encoding: "utf8" });+}+describe("memory backup history CLI", () => {+ it("reads the first and subsequent pages using the existing transport", () => {+ expect(run("history").stdout).toBe("/api/v1/sys/memory-backup?view=history");+ const sha = "a".repeat(64);+ expect(run("history", "12", sha).stdout).toBe(`/api/v1/sys/memory-backup?view=history&offset=12&revision=${sha}`);+ });+ it("rejects malformed pagination and requires explicit mutation confirmation", () => {+ for (const args of [["history", "1"], ["history", "-1", "a".repeat(64)], ["history", "1", "not-a-revision"], ["create"], ["verify", "id", "sha"]]) expect(run(...args).status).not.toBe(0);+ });+ it("describes history and local-only limitations in help", () => {+ const result = run("--help"); expect(result.status).toBe(0); expect(result.stdout).toContain("history [offset revision]"); expect(result.stdout).toContain("not a full VPS/database or offsite backup");+ });+});diff --git a/scripts/e2e/memory-backup-history.mjs b/scripts/e2e/memory-backup-history.mjsnew file mode 100644index 00000000..0a951abd--- /dev/null+++ b/scripts/e2e/memory-backup-history.mjs@@ -0,0 +1,80 @@+// Actual Settings UI; backup transport is intercepted so no host memory is read or copied.+import { expect } from "@playwright/test";+import AxeBuilder from "@axe-core/playwright";+import { mkdir, writeFile } from "node:fs/promises";+import path from "node:path";+const id = "11111111-1111-4111-8111-111111111111", revision = "a".repeat(64);+const snapshot = { id, state: "partial", createdAt: "2026-01-01T00:00:00.000Z", directory: "/synthetic/backups/" + id,+ manifestSha256: "b".repeat(64), scan: { files: 2, bytes: 10, missing: 1, rejected: 0, excluded: 1, truncated: true },+ compressedBytes: 30, sourceDiscoveryTruncated: false, consistency: "per-file-verified-not-point-in-time", offsite: false };+export async function memoryBackupHistoryJourney(page, fixture) {+ const pattern = "**/api/v1/sys/memory-backup**", checks = [], screenshots = [], errors = [];+ const onError = error => errors.push(error.message); page.on("pageerror", onError);+ let fail = false, posts = [], queries = [];+ await page.route(pattern, async route => {+ const req = route.request(), url = new URL(req.url());+ if (req.method() === "POST") {+ const body = req.postDataJSON(); posts.push(body);+ if (body.action !== "verify" || body.confirm !== true || body.id !== id || body.manifest_sha256 !== snapshot.manifestSha256)+ return route.fulfill({ status: 400, json: { error: "Unexpected synthetic mutation" } });+ return route.fulfill({ json: { id, integrity: true, complete: false, restoredFiles: 2, sourceWritesPerformed: 0, restoreDirectory: "/synthetic/restore" } });+ }+ queries.push(Object.fromEntries(url.searchParams));+ if (fail) return route.fulfill({ status: 503, json: { error: "Snapshot history unavailable — retry" } });+ if (url.searchParams.get("view") !== "history") return route.fulfill({ status: 400, json: { error: "No source scans in this UI fixture" } });+ const more = url.searchParams.has("offset");+ return route.fulfill({ json: { items: more+ ? [{ id: "22222222-2222-4222-8222-222222222222", status: "unreadable", error: "snapshot-unreadable" }]+ : [{ id, status: "readable", snapshot, integrity: "not-recorded" }], nextOffset: more ? null : 12, revision, order: "directory", scannedEntries: 12 } });+ });+ const out = process.env.MSO_SCREENSHOT_DIR;+ try {+ for (const viewport of [{ width: 1363, height: 936 }, { width: 390, height: 844 }, { width: 844, height: 390 }]) {+ await page.setViewportSize(viewport); posts = []; queries = []; fail = false;+ await page.goto(fixture.base + "/settings?section=backup");+ await expect(page.getByText("Server memory backup", { exact: true })).toBeVisible();+ await expect(page.getByText("Browser backup", { exact: true })).toBeVisible();+ expect(queries).toHaveLength(0); expect(posts).toHaveLength(0);+ await page.getByRole("button", { name: "Load saved server snapshots", exact: true }).click();+ await expect(page.getByText(/Partial snapshot · 2 files · No saved integrity receipt/)).toBeVisible();+ await page.getByRole("button", { name: "Load more saved snapshots", exact: true }).click();+ await expect(page.getByText(/Snapshot metadata unreadable — not an empty backup/)).toBeVisible();+ expect(queries.some(q => q.offset === "12" && q.revision === revision)).toBe(true);+ await page.getByRole("button", { name: `${snapshot.createdAt} · ${id.slice(0, 8)}`, exact: true }).click();+ expect(posts).toHaveLength(0);+ await page.getByRole("button", { name: "Verify checksum and rehearse restore", exact: true }).click();+ await expect(page.getByText("2 files verified · partial snapshot only · source writes: 0", { exact: true })).toBeVisible();+ expect(posts).toHaveLength(1); expect(posts[0]).toMatchObject({ action: "verify", confirm: true, id });+ for (const theme of ["light", "dark"]) {+ await page.evaluate(value => document.documentElement.dataset.theme = value, theme);+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);+ const accessibility = await new AxeBuilder({ page }).include('section:has([data-slot="settings-section-title"])').withTags(["wcag2a", "wcag2aa", "wcag21aa"]).analyze();+ expect(accessibility.violations.map(v => ({ id: v.id, targets: v.nodes.map(n => n.target) }))).toEqual([]);+ checks.push(`backup history/reflow/accessibility ${viewport.width}x${viewport.height} ${theme}`);+ if (out) {+ await mkdir(out, { recursive: true, mode: 0o700 });+ const file = path.join(out, `memory-backup-history-${viewport.width}-${theme}.png`);+ await page.getByText("Server memory backup", { exact: true }).scrollIntoViewIfNeeded();+ await page.screenshot({ path: file }); screenshots.push(file);+ }+ }+ fail = true; await page.getByRole("button", { name: "Refresh saved server snapshots", exact: true }).click();+ await expect(page.getByRole("alert").filter({ hasText: "Snapshot history unavailable" })).toBeVisible();+ await expect(page.getByText("No saved snapshots", { exact: true })).toHaveCount(0);+ fail = false; await page.getByRole("button", { name: "Refresh saved server snapshots", exact: true }).click();+ await expect(page.getByRole("alert").filter({ hasText: "Snapshot history unavailable" })).toHaveCount(0);+ checks.push(`pagination, explicit restore and error/retry ${viewport.width}`);+ }+ await page.unroute(pattern);+ for (const role of ["operator", "viewer"]) {+ await fixture.setRole(role);+ const status = await page.evaluate(async () => (await fetch("/api/v1/sys/memory-backup?view=history")).status);+ expect(status).toBe(403); checks.push(`real API refuses ${role} before private backup access`);+ }+ expect(errors).toEqual([]);+ } finally {+ await fixture.setRole("owner"); await page.unroute(pattern); page.off("pageerror", onError);+ if (out) await writeFile(path.join(out, "memory-backup-history-receipt.json"), JSON.stringify({ at: new Date().toISOString(), environment: "isolated built Settings UI; synthetic backup transport; real role denials", checks, errors, screenshots }, null, 2), { mode: 0o600 });+ }+ console.log(`PASS memory backup history: ${checks.length} viewport/accessibility/pagination/role checks; no host snapshots accessed`);+}diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjsindex f50b8528..0e036d6a 100644--- a/scripts/e2e/release.mjs+++ b/scripts/e2e/release.mjs@@ -10,6 +10,7 @@ import { workflowCanvasJourney } from "./workflow-canvas.mjs";import { storeExtensionsJourney } from "./store-extensions.mjs";import { releaseFixture } from "./release-fixture.mjs";import { camoufoxConnectionJourney } from "./camoufox-connection.mjs";+import { memoryBackupHistoryJourney } from "./memory-backup-history.mjs";import { aiProviderSwitchJourney } from "./ai-provider-switch.mjs";execFileSync(process.execPath, ["scripts/e2e/mcp-page.mjs"], { stdio: "inherit" });@@ -130,6 +131,7 @@ try {await organizationJourney(page, fixture);await workflowCanvasJourney(page, fixture);await aiProviderSwitchJourney(page, fixture);+ await memoryBackupHistoryJourney(page, fixture);await fixture.setRole("viewer");expect((await call("/api/v1/agent-sessions?view=monitor")).status).toBe(403);expect((await call("/api/v1/integrations")).status).toBe(403);