Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: Legacy Bundle UI — preview, select, generate & download (#1432)
Adam Eivy16eaded2ec13
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d9f1cb8d80..853df94dab 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,8 @@- **Enrich a Universe noun — and refine a Universe style — from a reference image.** The Universe Bible's "Describe from image" modal now takes reference images from your **gallery** as well as uploads, and for **characters** it can do more than write the descriptor paragraph: a new **Build character details** action has a vision model read the reference image(s) and *propose* values for the character's still-blank structured fields (pronouns, age, visual notes, color palette, expressions, …). The proposals are shown for review — uncheck any, edit the text inline — and applied through the normal entry-patch path, so existing values are never overwritten (no-clobber, characters-only). Separately, the **Refine Prompts** form gains an optional **style-reference image**: pick one from the gallery and the refiner runs through a vision-capable provider, folding the image's palette/lighting/mood into the universe's `influences` + `styleNotes`. Both vision paths require an API provider with a vision model and reject a silent fallback to a non-vision provider rather than hallucinating from text alone; the vision provider/model pickers scope local (Ollama/LM Studio) backends to vision-capable models. Relatedly, a **model-not-found error no longer benches the whole provider** — that's a bad model id in one request, not a provider outage, so (like a content refusal) the single call still falls back but the provider stays available for its other working models (previously one bad model id could take Ollama offline for 30 minutes). (`server/services/universeVisionExpand.js`, `server/services/universeBuilderRefine.js`, `server/routes/universeBuilder.js`, `server/lib/promptRunner.js`, `client/src/components/universe/VisionDescribeModal.jsx`, `client/src/pages/UniverseBuilder.jsx`)- **[issue-1431] Legacy Export can now include a rendered PDF portrait.** Phase 2 of the Legacy Export (#901) bundle: pass `includePdf: true` to `POST /api/legacy-export` and the `.zip` gains a `legacy-portrait.pdf` rendered from the same per-section Markdown the bundle already produces — title page, per-section pages, heading sizing, word-wrapped body, and bullet/quote handling. It uses the already-present `pdf-lib` dependency (the same primitives as the comic-pages PDF — no new package) and degrades non-ASCII glyphs (VO₂, smart quotes, em-dashes, ⚠️) to WinAnsi-safe text so a stray Unicode character can't fail the render. The PDF is hashed into `manifest.json` like every other file and the manifest's `pdf.included` flag (previously hard-false) now reflects it, with the file name recorded under `pdf.file`. Default `includePdf` is **false** — the Markdown/JSON bundle stays the primary artifact. (`server/services/legacyExport.js`, `server/routes/legacyExport.js`, `server/lib/validation.js`, #1431)+- **[issue-1432] Generate and download your Legacy Bundle from the UI.** Phase 3 of Legacy Export (#901): a new **Legacy** tab under Digital Twin (`/digital-twin/legacy`, reachable via ⌘K / voice as "legacy bundle") puts a user-facing surface on top of the Phase 1 server endpoints. It previews each identity section (with record counts and an estimated bundle size from `GET /api/legacy-export/preview`), lets you check/uncheck which sections to include — present sections default to selected — and on **Generate & Download** streams the `.zip` from `POST /api/legacy-export` straight to a browser download with a date-stamped filename and a success toast. Selecting *all* present sections sends no filter (so a future section is included by default); a subset sends the explicit list. Per-section build progress arrives over the existing `legacy-export:progress` / `:completed` socket events. The bundle preview now stamps each section with its human `label` so the UI need not duplicate a key→label map. A small shared `downloadBlob()` helper (`client/src/lib/downloadBlob.js`) collapses the inline object-URL + `<a download>` dance (also adopted by the soul ExportTab). (`client/src/components/digital-twin/tabs/LegacyExportTab.jsx`, `client/src/services/apiDigitalTwin.js`, `server/lib/navManifest.js`, `server/services/legacyExport.js`, #1432)+- **[issue-1300] Editorial checks flag five prose anti-patterns (weak openings, mirror self-description, empty pleasantries, italic thoughts, darlings).** A bundle of line/scene-level checks (Create → Editorial Checks) for the well-known tells that pull readers out. Four are LLM checks over the drafted manuscript: **Weak opening** flags clichéd or mis-placed openers — "he wakes up" / alarm-clock / dream starts, weather-and-scenery preambles, and scenes that begin before the interesting moment; **Mirror self-description** catches the tired trick of a character studying their reflection so the prose can catalog their looks, while leaving reflections that do real story work alone; **Empty greeting / small-talk openings** flags scenes that open on greeting rituals or logistical filler that carry no tension or information, while sparing pleasantries laced with subtext; **Kill your darlings** surfaces precious, self-indulgent passages — showpiece descriptions, digressions, over-explaining, favorite lines that stop the scene — as cut candidates, judged by story need rather than quality (complementing the dead-metaphor check, which targets stock rather than precious prose). The fifth, **Italicized internal thoughts**, is a deterministic, high-precision scan that flags multi-word `*…*` / `_…_` italic thought runs (the prose is already in the character's perspective, so italicizing a thought is a tell) while leaving single-word emphasis, bold, and `snake_case` alone, with a configurable word threshold. All findings anchor a verbatim quote + issue number; the LLM checks ship four new stage prompts (`pipeline-editorial-{opening-start,mirror-description,dialogue-pleasantries,kill-your-darlings}`) that migrate for existing installs (103–106), the deterministic check needs no model. (`server/lib/editorial/{italicThoughts,checkRegistry}.js`) (#1300)- **[issue-1309] Editorial checks flag thin sensory writing and ungrounded "white-room" scenes.** Two new prose checks (Create → Editorial Checks) target two of the most common reader gripes about flat scene writing. **Sensory balance** reads your drafted manuscript and flags scenes that lean almost entirely on sight while sound, smell, touch, and taste go neglected, plus sensory-bare scenes with almost no concrete grounding at all — naming exactly which sense is missing and suggesting a grounding detail to add. **White-room / ungrounded scene** flags "talking heads in a void": dialogue and action playing out with no setting, no physical blocking, and no spatial grounding the reader can stand in — distinct from sensory balance (which is about *senses*) and scene-component balance (narrative/action/dialogue mix) in that the gap here is specifically *place*. Both read your reverse-outline scene segmentation as context (using each scene's recorded setting as a white-room signal) and **degrade gracefully** to a whole-issue manuscript scan when no outline has been generated yet. Each finding anchors a verbatim quote + issue number so you can jump straight to the spot. Two new stage prompts (`pipeline-editorial-sensory-balance`, `pipeline-editorial-white-room`) ship + migrate for existing installs. (#1309)diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.jsindex e6647f6a53..358676cc94 100644--- a/client/src/components/digital-twin/constants.js+++ b/client/src/components/digital-twin/constants.js@@ -28,7 +28,8 @@ import {Archive,Drama,Mic,- Camera+ Camera,+ Package} from 'lucide-react';// Main navigation tabs@@ -48,6 +49,7 @@ export const TABS = [{ id: 'autobiography', label: 'Autobiography', icon: PenLine },{ id: 'import', label: 'Import', icon: Upload },{ id: 'export', label: 'Export', icon: Download },+ { id: 'legacy', label: 'Legacy', icon: Package },{ id: 'time-capsule', label: 'Time Capsule', icon: Archive }];diff --git a/client/src/components/digital-twin/tabs/ExportTab.jsx b/client/src/components/digital-twin/tabs/ExportTab.jsxindex 184bae8d00..d0a599cd32 100644--- a/client/src/components/digital-twin/tabs/ExportTab.jsx+++ b/client/src/components/digital-twin/tabs/ExportTab.jsx@@ -12,6 +12,7 @@ import BrailleSpinner from '../../BrailleSpinner';import * as api from '../../../services/api';import toast from '../../ui/Toast';import { copyToClipboard } from '../../../lib/clipboard';+import { downloadBlob } from '../../../lib/downloadBlob';import { DOCUMENT_CATEGORIES } from '../constants';@@ -92,15 +93,7 @@ export default function ExportTab({ onRefresh: _onRefresh }) {? `legacy-portrait-${new Date().toISOString().slice(0, 10)}.md`: `soul-export.${extension}`;- const blob = new Blob([content], { type: 'text/plain' });- const url = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url;- a.download = filename;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(url);+ downloadBlob(content, filename, 'text/plain');toast.success(`Downloaded ${filename}`);};diff --git a/client/src/components/digital-twin/tabs/LegacyExportTab.jsx b/client/src/components/digital-twin/tabs/LegacyExportTab.jsxnew file mode 100644index 0000000000..a5a1c73ce0--- /dev/null+++ b/client/src/components/digital-twin/tabs/LegacyExportTab.jsx@@ -0,0 +1,190 @@+import { useState, useEffect, useCallback } from 'react';+import { Download, Archive, RefreshCw, Package } from 'lucide-react';+import BrailleSpinner from '../../BrailleSpinner';+import socket from '../../../services/socket';+import * as api from '../../../services/api';+import toast from '../../ui/Toast';+import { downloadBlob } from '../../../lib/downloadBlob';+import { formatBytes } from '../../../utils/formatters';++// Legacy Bundle surface (#1432) — pick sections, preview stats, generate, and+// download the portable identity zip. The server foundation (#901 Phase 1)+// streams `Content-Disposition: attachment` and emits `legacy-export:*` socket+// events for per-section progress.++// Build the count summary line for a section's preview metadata. The server+// stamps each section with `{ label, present, included, ...counts }`; the+// counts are the remaining numeric keys (memories, stories, goals, …).+const META_KEYS = new Set(['label', 'present', 'included', 'source']);+function describeCounts(meta) {+ const parts = Object.entries(meta)+ .filter(([k, v]) => !META_KEYS.has(k) && typeof v === 'number' && v > 0)+ .map(([k, v]) => `${v} ${k}`);+ return parts.join(' · ');+}++export default function LegacyExportTab() {+ const [preview, setPreview] = useState(null);+ const [loading, setLoading] = useState(true);+ const [selected, setSelected] = useState([]);+ const [generating, setGenerating] = useState(false);+ const [progress, setProgress] = useState(null);++ const loadPreview = useCallback(async () => {+ setLoading(true);+ // ExportTab-style: tolerate a failed preview with a falsy fallback so the+ // tab still renders an empty state instead of throwing.+ const data = await api.getLegacyExportPreview({ silent: true }).catch(() => null);+ setPreview(data);+ // Default selection: every present section.+ if (data?.sections) {+ setSelected(Object.entries(data.sections).filter(([, m]) => m.present).map(([k]) => k));+ }+ setLoading(false);+ }, []);++ useEffect(() => { loadPreview(); }, [loadPreview]);++ // Per-section progress from the server-side bundle build.+ useEffect(() => {+ const onProgress = (payload) => setProgress(payload || null);+ const onCompleted = () => setProgress(null);+ socket.on('legacy-export:progress', onProgress);+ socket.on('legacy-export:completed', onCompleted);+ return () => {+ socket.off('legacy-export:progress', onProgress);+ socket.off('legacy-export:completed', onCompleted);+ };+ }, []);++ const toggleSection = (key) => {+ setSelected(prev => prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]);+ };++ const sections = preview?.sections ? Object.entries(preview.sections) : [];+ const presentSections = sections.filter(([, m]) => m.present);+ const selectedPresent = selected.filter(k => preview?.sections?.[k]?.present);+ const canGenerate = !generating && selectedPresent.length > 0;++ const handleGenerate = async () => {+ setGenerating(true);+ setProgress(null);+ // If every present section is selected, send no filter (server treats+ // omitted `sections` as "all") so a future section is included by default.+ const allPresent = selectedPresent.length === presentSections.length;+ const buffer = await api+ .downloadLegacyExport({ sections: allPresent ? null : selectedPresent }, { silent: true })+ .catch(() => null);+ setGenerating(false);+ setProgress(null);+ if (!buffer) {+ toast.error('Failed to build legacy bundle');+ return;+ }+ const date = new Date().toISOString().slice(0, 10);+ downloadBlob(buffer, `legacy-export-${date}.zip`, 'application/zip');+ toast.success('Legacy bundle downloaded');+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center h-64">+ <BrailleSpinner text="Loading" />+ </div>+ );+ }++ return (+ <div className="max-w-2xl mx-auto space-y-4 sm:space-y-6">+ {/* Intro */}+ <div className="bg-port-card rounded-lg border border-port-border p-4">+ <div className="flex items-start gap-3">+ <Archive className="w-6 h-6 text-port-accent shrink-0 mt-0.5" />+ <div>+ <h3 className="font-semibold text-white">Legacy Bundle</h3>+ <p className="text-sm text-gray-400 mt-1">+ A portable, human-readable archive of your identity — Markdown + JSON for each+ section, zipped with a manifest. Pick what to include and download a time capsule+ you can keep, share, or hand on.+ </p>+ </div>+ </div>+ </div>++ {/* Section picker */}+ <div className="bg-port-card rounded-lg border border-port-border p-4">+ <div className="flex items-center justify-between mb-4">+ <h3 className="font-semibold text-white">Sections ({selectedPresent.length})</h3>+ <button+ onClick={loadPreview}+ className="flex items-center gap-1.5 text-xs py-1 px-2 min-h-[32px] text-gray-400 hover:text-white"+ title="Re-scan sections"+ >+ <RefreshCw size={14} /> Refresh+ </button>+ </div>++ {presentSections.length === 0 ? (+ <p className="text-sm text-gray-500 py-4 text-center">+ No identity data available yet — build out your Digital Twin to populate the bundle.+ </p>+ ) : (+ <div className="space-y-1">+ {presentSections.map(([key, meta]) => {+ const counts = describeCounts(meta);+ return (+ <label+ key={key}+ htmlFor={`legacy-section-${key}`}+ className="flex items-center gap-3 p-2 min-h-[44px] rounded hover:bg-port-border cursor-pointer"+ >+ <input+ id={`legacy-section-${key}`}+ type="checkbox"+ checked={selected.includes(key)}+ onChange={() => toggleSection(key)}+ className="w-5 h-5 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white">{meta.label || key}</div>+ {counts && <div className="text-xs text-gray-500">{counts}</div>}+ </div>+ </label>+ );+ })}+ </div>+ )}++ {/* Estimated size */}+ {preview && (+ <div className="mt-4 pt-4 border-t border-port-border flex items-center gap-2 text-xs text-gray-500">+ <Package size={14} />+ <span>+ ~{preview.fileCount} files+ {preview.estimatedBytes != null && ` · ${formatBytes(preview.estimatedBytes)} (full bundle)`}+ </span>+ </div>+ )}+ </div>++ {/* Generate */}+ <button+ onClick={handleGenerate}+ disabled={!canGenerate}+ className="w-full flex items-center justify-center gap-2 px-6 py-3 min-h-[48px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {generating ? (+ <>+ <BrailleSpinner />+ {progress ? 'Building bundle…' : 'Generating…'}+ </>+ ) : (+ <>+ <Download className="w-5 h-5" />+ Generate & Download+ </>+ )}+ </button>+ </div>+ );+}diff --git a/client/src/components/digital-twin/tabs/LegacyExportTab.test.jsx b/client/src/components/digital-twin/tabs/LegacyExportTab.test.jsxnew file mode 100644index 0000000000..a056ba9dfa--- /dev/null+++ b/client/src/components/digital-twin/tabs/LegacyExportTab.test.jsx@@ -0,0 +1,105 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../../services/api', () => ({+ getLegacyExportPreview: vi.fn(),+ downloadLegacyExport: vi.fn(),+}));+vi.mock('../../../services/socket', () => ({+ default: { on: vi.fn(), off: vi.fn() },+}));+vi.mock('../../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn() },+}));+vi.mock('../../../lib/downloadBlob', () => ({+ downloadBlob: vi.fn(),+}));++import LegacyExportTab from './LegacyExportTab';+import { getLegacyExportPreview, downloadLegacyExport } from '../../../services/api';+import { downloadBlob } from '../../../lib/downloadBlob';+import toast from '../../ui/Toast';++const PREVIEW = {+ fileCount: 6,+ estimatedBytes: 4096,+ sections: {+ identity: { label: 'Identity & Values', present: true, included: true, traits: 5 },+ goals: { label: 'Goals & Milestones', present: true, included: true, goals: 3 },+ health: { label: 'Health Summary', present: false, included: false },+ },+};++beforeEach(() => {+ vi.clearAllMocks();+ getLegacyExportPreview.mockResolvedValue(PREVIEW);+});++describe('LegacyExportTab', () => {+ it('renders only present sections, defaulted to selected', async () => {+ render(<LegacyExportTab />);+ expect(await screen.findByText('Identity & Values')).toBeInTheDocument();+ expect(screen.getByText('Goals & Milestones')).toBeInTheDocument();+ // Absent section is not offered.+ expect(screen.queryByText('Health Summary')).not.toBeInTheDocument();+ // Both present sections checked by default.+ const boxes = screen.getAllByRole('checkbox');+ expect(boxes).toHaveLength(2);+ expect(boxes.every(b => b.checked)).toBe(true);+ // Count summary surfaces.+ expect(screen.getByText(/5 traits/)).toBeInTheDocument();+ });++ it('sends no section filter when all present sections are selected', async () => {+ downloadLegacyExport.mockResolvedValue(new ArrayBuffer(8));+ const user = userEvent.setup();+ render(<LegacyExportTab />);+ await screen.findByText('Identity & Values');++ await user.click(screen.getByRole('button', { name: /generate & download/i }));++ await waitFor(() => expect(downloadLegacyExport).toHaveBeenCalledOnce());+ expect(downloadLegacyExport).toHaveBeenCalledWith({ sections: null }, { silent: true });+ expect(downloadBlob).toHaveBeenCalledOnce();+ expect(toast.success).toHaveBeenCalled();+ });++ it('sends the explicit subset when only some sections are selected', async () => {+ downloadLegacyExport.mockResolvedValue(new ArrayBuffer(8));+ const user = userEvent.setup();+ render(<LegacyExportTab />);+ await screen.findByText('Goals & Milestones');++ // Deselect identity (first checkbox), leaving only goals.+ const identityBox = document.getElementById('legacy-section-identity');+ await user.click(identityBox);+ await user.click(screen.getByRole('button', { name: /generate & download/i }));++ await waitFor(() => expect(downloadLegacyExport).toHaveBeenCalledOnce());+ expect(downloadLegacyExport).toHaveBeenCalledWith({ sections: ['goals'] }, { silent: true });+ });++ it('toasts an error and skips download when the build fails', async () => {+ downloadLegacyExport.mockResolvedValue(null);+ const user = userEvent.setup();+ render(<LegacyExportTab />);+ await screen.findByText('Identity & Values');++ await user.click(screen.getByRole('button', { name: /generate & download/i }));++ await waitFor(() => expect(toast.error).toHaveBeenCalled());+ expect(downloadBlob).not.toHaveBeenCalled();+ });++ it('shows an empty state and disables generate when no data is present', async () => {+ getLegacyExportPreview.mockResolvedValue({+ fileCount: 2,+ estimatedBytes: 0,+ sections: { identity: { label: 'Identity & Values', present: false, included: false } },+ });+ render(<LegacyExportTab />);+ expect(await screen.findByText(/no identity data available/i)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /generate & download/i })).toBeDisabled();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex ec275ccfc8..9cef06c331 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -74,6 +74,7 @@ grep -i "what you want to do" client/src/lib/README.md| `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. || `diffLines.js` | `diffLineBlocks(oldText, newText)` → `{ blocks }` (`{ type: 'same', lines }` / `{ type: 'change', oldLines, newLines }`) — line-level Myers LCS with common prefix/suffix trim and a 4M-cell `LINE_DIFF_CELL_CAP` guard. The structural layer behind `HunkDiff` (collapse same-blocks to context, word-diff each change-block). || `diffWords.js` | `diffWords(oldText, newText)` → `{ tooLarge, oldRuns, newRuns }` — word-level Myers LCS core (tokenize on whitespace, common prefix/suffix trim, collapse to `{ text, changed }` runs, 4M-cell `DIFF_CELL_CAP` guard on the trimmed middle). Shared by `InlineDiff` (stacked), `SideBySideDiff` (columnar), and `HunkDiff`'s change blocks. |+| `downloadBlob.js` | `downloadBlob(data, filename, type?)` — trigger a browser "Save as…" for a Blob / ArrayBuffer / typed array / string, with object-URL + temporary `<a>` cleanup. Use instead of inlining `URL.createObjectURL` + `<a download>`. || `genUtils.js` | Shared bits between Image Gen and Video Gen pages. || `healthProvenance.js` | `PROVENANCE_LEVELS` / `getProvenanceLevel(level)` — the `data-backed`/`inferred`/`experimental`/`speculative` trust taxonomy (label, tone, description, "what would change this?" copy) behind the `ProvenanceChip` source-style chips on MeatSpace / genome / death-clock / longevity views. Pure data; the chip component maps tone→color and id→icon. || `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. |diff --git a/client/src/lib/downloadBlob.js b/client/src/lib/downloadBlob.jsnew file mode 100644index 0000000000..b9bf538d0e--- /dev/null+++ b/client/src/lib/downloadBlob.js@@ -0,0 +1,20 @@+// Trigger a browser "Save as…" for in-memory data without leaking the object+// URL or the temporary <a>. Accepts a Blob, ArrayBuffer, typed array, or string+// — anything the Blob constructor takes. Pass `type` to set the MIME type when+// the data isn't already a Blob (defaults to application/octet-stream).+//+// Collapses the inline `URL.createObjectURL` + `<a download>` + `revokeObjectURL`+// dance (e.g. the soul ExportTab). Data-URL downloads (CityPhotoOverlay) don't+// fit — they have no object URL to revoke, and a data-URL string would get+// re-wrapped in a Blob here.+export function downloadBlob(data, filename, type = 'application/octet-stream') {+ const blob = data instanceof Blob ? data : new Blob([data], { type });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+}diff --git a/client/src/lib/downloadBlob.test.js b/client/src/lib/downloadBlob.test.jsnew file mode 100644index 0000000000..d3426160ff--- /dev/null+++ b/client/src/lib/downloadBlob.test.js@@ -0,0 +1,61 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { downloadBlob } from './downloadBlob.js';++describe('downloadBlob', () => {+ let createObjectURL;+ let revokeObjectURL;+ let clickSpy;+ // jsdom doesn't implement object URLs, so we assign them directly rather than+ // spy. `vi.restoreAllMocks()` won't undo a plain property assignment — save+ // and restore the originals ourselves so the mocks don't leak into later tests.+ let originalCreate;+ let originalRevoke;++ beforeEach(() => {+ createObjectURL = vi.fn(() => 'blob:mock-url');+ revokeObjectURL = vi.fn();+ originalCreate = URL.createObjectURL;+ originalRevoke = URL.revokeObjectURL;+ URL.createObjectURL = createObjectURL;+ URL.revokeObjectURL = revokeObjectURL;+ clickSpy = vi.spyOn(window.HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});+ vi.spyOn(document.body, 'appendChild');+ vi.spyOn(document.body, 'removeChild');+ });++ afterEach(() => {+ URL.createObjectURL = originalCreate;+ URL.revokeObjectURL = originalRevoke;+ vi.restoreAllMocks();+ });++ it('creates an object URL, clicks a download anchor, and cleans up', () => {+ downloadBlob('hello', 'note.txt', 'text/plain');+ expect(createObjectURL).toHaveBeenCalledOnce();+ const blob = createObjectURL.mock.calls[0][0];+ expect(blob).toBeInstanceOf(Blob);+ expect(blob.type).toBe('text/plain');+ expect(clickSpy).toHaveBeenCalledOnce();+ // The anchor carried the requested filename + the object URL.+ const anchor = document.body.appendChild.mock.calls[0][0];+ expect(anchor.tagName).toBe('A');+ expect(anchor.download).toBe('note.txt');+ expect(anchor.href).toContain('blob:mock-url');+ // Cleanup: anchor removed and URL revoked.+ expect(document.body.removeChild).toHaveBeenCalledWith(anchor);+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-url');+ });++ it('passes a Blob through without re-wrapping it', () => {+ const original = new Blob(['x'], { type: 'application/zip' });+ downloadBlob(original, 'bundle.zip');+ expect(createObjectURL).toHaveBeenCalledWith(original);+ });++ it('wraps an ArrayBuffer with the given MIME type', () => {+ downloadBlob(new ArrayBuffer(4), 'data.bin', 'application/zip');+ const blob = createObjectURL.mock.calls[0][0];+ expect(blob.type).toBe('application/zip');+ expect(blob.size).toBe(4);+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex afda301779..a302a6fed7 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -45,6 +45,7 @@ export * from './compareHelpers.js';export * from './consoleFilters.js';export * from './diffLines.js';export * from './diffWords.js';+export * from './downloadBlob.js';export * from './genUtils.js';export * from './healthProvenance.js';export * from './joinInfluenceList.js';diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsxindex 9f8bc00edd..7e4eea9e0a 100644--- a/client/src/pages/DigitalTwin.jsx+++ b/client/src/pages/DigitalTwin.jsx@@ -24,6 +24,7 @@ import GoalsTab from '../components/digital-twin/tabs/GoalsTab';import AutobiographyTab from '../components/digital-twin/tabs/AutobiographyTab';import ImportTab from '../components/digital-twin/tabs/ImportTab';import ExportTab from '../components/digital-twin/tabs/ExportTab';+import LegacyExportTab from '../components/digital-twin/tabs/LegacyExportTab';import TimeCapsuleTab from '../components/digital-twin/tabs/TimeCapsuleTab';export default function DigitalTwin() {@@ -84,6 +85,8 @@ export default function DigitalTwin() {return <ImportTab onRefresh={refetch} />;case 'export':return <ExportTab onRefresh={refetch} />;+ case 'legacy':+ return <LegacyExportTab />;case 'time-capsule':return <TimeCapsuleTab onRefresh={refetch} />;default:diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.jsindex 4256c4c5d4..cc4f042df8 100644--- a/client/src/services/apiDigitalTwin.js+++ b/client/src/services/apiDigitalTwin.js@@ -74,6 +74,18 @@ export const exportDigitalTwin = (format, documentIds = null, includeDisabled =body: JSON.stringify({ format, documentIds, includeDisabled })});+// Legacy Export (portable identity bundle) — #901 Phase 1 server foundation:+// `GET /api/legacy-export/preview` + `POST /api/legacy-export`. The preview is+// cheap enough to call on page load; the bundle build streams a zip attachment.+export const getLegacyExportPreview = (options) => request('/legacy-export/preview', options);+export const downloadLegacyExport = ({ sections = null, includePdf = false } = {}, options = {}) =>+ request('/legacy-export', {+ method: 'POST',+ body: JSON.stringify({ ...(sections ? { sections } : {}), ...(includePdf ? { includePdf } : {}) }),+ responseType: 'arraybuffer',+ ...options,+ });+// Digital Twin - Settingsexport const getDigitalTwinSettings = (options) => request('/digital-twin/settings', options);export const updateDigitalTwinSettings = (settings) => request('/digital-twin/settings', {diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 2b677b66da..2aac26d8f9 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -116,6 +116,7 @@ export const NAV_COMMANDS = [{ id: 'nav.twin.documents', path: '/digital-twin/documents', label: 'Documents', section: 'Identity', aliases: ['twin-documents'] },{ id: 'nav.twin.enrich', path: '/digital-twin/enrich', label: 'Enrich', section: 'Identity', aliases: ['twin-enrich'] },{ id: 'nav.twin.export', path: '/digital-twin/export', label: 'Export', section: 'Identity', aliases: ['twin-export'] },+ { id: 'nav.twin.legacy', path: '/digital-twin/legacy', label: 'Legacy Bundle', section: 'Identity', aliases: ['legacy-export', 'legacy-bundle', 'legacy'], keywords: ['legacy', 'bundle', 'backup', 'portable', 'pdf', 'archive', 'time capsule', 'export'] },{ id: 'nav.goals', path: '/goals/list', label: 'Goals', section: 'Goals', aliases: ['goals'] },{ id: 'nav.goals.tree', path: '/goals/tree', label: 'Goals Tree', section: 'Goals', aliases: ['goals-tree', 'goal-tree'], keywords: ['hierarchy', 'decomposition', 'subgoals', 'breakdown'] },{ id: 'nav.twin.goals', path: '/digital-twin/goals', label: 'Twin Goals', section: 'Identity', aliases: ['twin-goals'] },diff --git a/server/services/legacyExport.js b/server/services/legacyExport.jsindex 1605bf989e..bdc2a5dbe7 100644--- a/server/services/legacyExport.js+++ b/server/services/legacyExport.js@@ -428,6 +428,7 @@ export function buildBundleFiles(data, { sections: selected = null } = {}) {const present = section.present(data);const included = wanted.includes(section);sectionMeta[section.key] = {+ label: section.label,present,included: included && present,...(present ? section.counts(data) : {}),diff --git a/server/services/legacyExport.test.js b/server/services/legacyExport.test.jsindex 2582dbad84..f0f122a437 100644--- a/server/services/legacyExport.test.js+++ b/server/services/legacyExport.test.js@@ -119,6 +119,18 @@ describe('buildBundleFiles', () => {expect(sections.goals.included).toBe(true);});+ it('stamps each section with its human label so the UI need not duplicate a key→label map', () => {+ const { sections } = buildBundleFiles(sampleData());+ expect(sections.identity.label).toBe('Identity & Values');+ expect(sections.goals.label).toBe('Goals & Milestones');+ // Labels are present even for absent sections (driven off the descriptor, not data).+ const empty = { twinPrompt: '', claudeMd: '', stories: [], genome: { uploaded: false },+ taste: { sections: [] }, chronotype: null, longevity: null, traits: null,+ brain: { people: [], projects: [], ideas: [], journals: [], links: [] },+ memories: [], goals: [], health: {} };+ expect(buildBundleFiles(empty).sections.health.label).toBe('Health Summary');+ });+it('marks absent sections present:false and emits no files for them', () => {const empty = { twinPrompt: '', claudeMd: '', stories: [], genome: { uploaded: false },taste: { sections: [] }, chronotype: null, longevity: null, traits: null,