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([issue-901]): legacy identity export bundle (server foundation)
[._.]/ Adam Eivye5d08e7d8400
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ea2456dfb2..fe4ab6f394 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[issue-901] Legacy Export — download your whole identity as a portable bundle (server foundation).** A new `POST /api/legacy-export` endpoint gathers your identity across every PortOS domain — digital-twin prompt, autobiography, brain notes, memories, goals + milestones, key decisions, and a health summary — into a single self-contained `.zip` of human-readable Markdown plus machine-readable JSON and a SHA-256 `manifest.json`. The bundle is readable with **zero PortOS running** (plain files, no database), opens with a privacy banner, and degrades gracefully when a domain is empty. Secrets accidentally pasted into notes are redacted before anything leaves the box. `GET /api/legacy-export/preview` reports which sections are present and the estimated size without building the file. This is the server core of the Knowledge Legacy export; PDF rendering and a one-click UI are tracked as follow-ups. (#901)+- **[issue-899] Knowledge Graph now includes Goals and Daily Log entries.** The Brain Graph 3D view (Brain → Graph) extends from the five brain entity types to a full knowledge graph: active Goals and Daily Log journal entries now appear as colored nodes (orange for Goals, teal for Journal) and connect to related entities via semantic similarity and tag overlap. Goals show a progress bar, horizon, and target date in the detail panel; journals link by shared vocabulary in their embedded content. (#899)- **[issue-898] Goal Decomposition Engine — auto-decompose a goal into milestones pre-populated with tasks.** Goals already had AI phase-planning, but `Generate Plan` only produced flat milestones with *no* tasks — you then hand-added every todo. A new **Decompose into Tasks** action (Goals → a goal's Plan section) turns a high-level goal into 3–7 ordered milestones, each carrying 2–5 concrete, estimated tasks (priority + minute estimate), in a single LLM pass. The proposal is fully reviewable before accept — reorder milestones, edit titles/descriptions, drop tasks or whole milestones — and only `Accept Tasks` persists it, normalizing each task with its own id and `pending` status (mirrors the existing generate→accept-phases review flow). Accepted tasks render nested under their milestone with check-off, and unlike phase-planning, decomposition works **without** a goal target date (relative ordering only). Server adds `decomposeGoal` / `acceptGoalDecomposition` / `completeMilestoneTask` (file-backed in `goals.json`, mirrored to MortalLoom iCloud — no Postgres migration) with three new validated routes; existing goals lazily gain `milestone.tasks = []` on load with no data loss. (`server/services/identity/goals.js`, `server/lib/identityValidation.js`, `server/routes/identity.js`, `client/src/hooks/useGoalDetail.js`, `client/src/components/goals/{GoalPlanSection,GoalMilestones}.jsx`, #898)diff --git a/server/index.js b/server/index.jsindex 05b0b5d4e2..222ff852f3 100644--- a/server/index.js+++ b/server/index.js@@ -71,6 +71,7 @@ import dataManagerRoutes from './routes/dataManager.js';import jiraRoutes from './routes/jira.js';import autobiographyRoutes from './routes/autobiography.js';import backupRoutes from './routes/backup.js';+import legacyExportRoutes from './routes/legacyExport.js';import cityRoutes from './routes/cityRoutes.js';import databaseRoutes from './routes/database.js';import localLlmRoutes from './routes/localLlm.js';@@ -453,6 +454,7 @@ app.use('/api/media/annotations', mediaAnnotationsRoutes);app.use('/api/attachments', attachmentsRoutes);app.use('/api/client-errors', clientErrorsRoutes);app.use('/api/backup', backupRoutes);+app.use('/api/legacy-export', legacyExportRoutes);app.use('/api/city', cityRoutes);app.use('/api/database', databaseRoutes);app.use('/api/uploads', uploadsRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex b19b2b20bb..8ed7f5b7cd 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -112,6 +112,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. || `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. || `zipStream.js` | Streaming ZIP parser (`parseZip`, unzipper-style); `extractZipEntryToBuffer(path, match)` cracks one member out to a Buffer. |+| `zipWriter.js` | Minimal ZIP writer — `createZip(entries)` builds a stored (uncompressed) archive Buffer that round-trips through `parseZip`; `crc32(buf)` is the dependency-free checksum it uses. || `assetHash.js` | Cross-transport SHA-256 cache for `data/images/*` — persists hashes in the asset's `.metadata.json` sidecar so the share-bucket exporter and the federated peer-sync push pipeline reuse the same value. `sidecarGenParamsHash` canonically hashes a sidecar's gen-params (excludes the machine-local `sha256` cache block) for cross-machine sidecar-convergence comparisons. |## Process executiondiff --git a/server/lib/index.js b/server/lib/index.jsindex 6f6b022885..ff39a0cc3c 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -107,6 +107,7 @@ export * from './safetensors.js';export * from './assetHash.js';export * from './pdfImageEmbed.js';export * from './zipStream.js';+export * from './zipWriter.js';// === Process execution ===export * from './bashResolver.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex ff77856fca..cf3048c23f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1739,6 +1739,16 @@ export const documentUpdateSchema = z.object({commitMessage: z.string().max(200).optional()});+// Legacy Export (issue #901) — portable identity bundle. `sections` optionally+// narrows the bundle to a subset of domains; omitted/empty means "all present+// sections". The enum is kept in sync with `legacyExport.js#getSectionKeys()`+// (asserted in legacyExport's tests) — validation.js must not import from+// services (cycle), so the keys are inlined here.+export const LEGACY_EXPORT_SECTIONS = ['identity', 'autobiography', 'brain', 'goals', 'decisions', 'health'];+export const legacyExportSchema = z.object({+ sections: z.array(z.enum(LEGACY_EXPORT_SECTIONS)).optional()+});+// =============================================================================// TRANSITIONAL RE-EXPORTS (issue #1151 split)// =============================================================================diff --git a/server/lib/zipWriter.js b/server/lib/zipWriter.jsnew file mode 100644index 0000000000..31bfc4a67e--- /dev/null+++ b/server/lib/zipWriter.js@@ -0,0 +1,139 @@+/**+ * Minimal ZIP writer — the counterpart to the parser in `zipStream.js`.+ *+ * Writes **stored (method 0, uncompressed)** entries only: local file headers,+ * a central directory, and the EOCD record. No new dependency — CRC-32 is a+ * small in-file table (Node's `zlib.crc32` only landed in v22, so we don't rely+ * on it). Output is deterministic (fixed DOS timestamp) so round-trip tests and+ * manifest hashes are stable.+ *+ * Usage:+ * const buf = createZip([+ * { name: 'README.md', data: '# Hello' },+ * { name: 'data/manifest.json', data: Buffer.from('{}') },+ * ]);+ * // buf round-trips through parseZip() in zipStream.js+ *+ * Stored entries are the simplest correct format: every standard tool (`unzip`,+ * macOS Archive Utility, `parseZip`) reads them, and there is no compression+ * state to get wrong. Add a deflate path here only if bundle size becomes a+ * concern (see issue #901 open question 5).+ */++// CRC-32 lookup table (IEEE 802.3 polynomial 0xEDB88320), built once at load.+const CRC_TABLE = (() => {+ const table = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) {+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ }+ table[n] = c >>> 0;+ }+ return table;+})();++/** CRC-32 of a Buffer, returned as an unsigned 32-bit integer. */+export function crc32(buf) {+ let crc = 0xffffffff;+ for (let i = 0; i < buf.length; i++) {+ crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);+ }+ return (crc ^ 0xffffffff) >>> 0;+}++// Fixed DOS date/time (1980-01-01 00:00:00) for deterministic output.+const DOS_TIME = 0;+const DOS_DATE = 0x21; // (1980-1980)<<9 | 1<<5 | 1 = 0b0000000_0001_00001++const LOCAL_SIG = 0x04034b50;+const CENTRAL_SIG = 0x02014b50;+const EOCD_SIG = 0x06054b50;+const VERSION = 20; // 2.0 — minimum that supports the fields we write+const UTF8_FLAG = 0x0800; // language-encoding (EFS) bit: names are UTF-8++function toBuffer(data) {+ return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf-8');+}++/**+ * Build a ZIP archive (as a single Buffer) from a list of `{ name, data }`+ * entries. `name` is the in-archive path (forward slashes); `data` is a Buffer+ * or string. Duplicate or empty names throw — a malformed bundle is worse than+ * a loud failure.+ */+export function createZip(entries) {+ if (!Array.isArray(entries)) throw new Error('createZip: entries must be an array');++ const seen = new Set();+ const chunks = [];+ const central = [];+ let offset = 0;++ for (const entry of entries) {+ const name = entry?.name;+ if (!name || typeof name !== 'string') throw new Error('createZip: every entry needs a non-empty string name');+ const normalized = name.replace(/\\/g, '/').replace(/^\/+/, '');+ if (seen.has(normalized)) throw new Error(`createZip: duplicate entry name "${normalized}"`);+ seen.add(normalized);++ const nameBuf = Buffer.from(normalized, 'utf-8');+ const dataBuf = toBuffer(entry.data ?? '');+ const crc = crc32(dataBuf);+ const size = dataBuf.length;++ // Local file header (30 bytes fixed + name).+ const local = Buffer.alloc(30);+ local.writeUInt32LE(LOCAL_SIG, 0);+ local.writeUInt16LE(VERSION, 4);+ local.writeUInt16LE(UTF8_FLAG, 6);+ local.writeUInt16LE(0, 8); // method 0 (stored)+ local.writeUInt16LE(DOS_TIME, 10);+ local.writeUInt16LE(DOS_DATE, 12);+ local.writeUInt32LE(crc, 14);+ local.writeUInt32LE(size, 18); // compressed size == size (stored)+ local.writeUInt32LE(size, 22); // uncompressed size+ local.writeUInt16LE(nameBuf.length, 26);+ local.writeUInt16LE(0, 28); // extra length++ chunks.push(local, nameBuf, dataBuf);++ // Central directory header (46 bytes fixed + name).+ const cd = Buffer.alloc(46);+ cd.writeUInt32LE(CENTRAL_SIG, 0);+ cd.writeUInt16LE(VERSION, 4); // version made by+ cd.writeUInt16LE(VERSION, 6); // version needed+ cd.writeUInt16LE(UTF8_FLAG, 8);+ cd.writeUInt16LE(0, 10); // method+ cd.writeUInt16LE(DOS_TIME, 12);+ cd.writeUInt16LE(DOS_DATE, 14);+ cd.writeUInt32LE(crc, 16);+ cd.writeUInt32LE(size, 20);+ cd.writeUInt32LE(size, 24);+ cd.writeUInt16LE(nameBuf.length, 28);+ cd.writeUInt16LE(0, 30); // extra length+ cd.writeUInt16LE(0, 32); // comment length+ cd.writeUInt16LE(0, 34); // disk number start+ cd.writeUInt16LE(0, 36); // internal attrs+ cd.writeUInt32LE(0, 38); // external attrs+ cd.writeUInt32LE(offset, 42); // local header offset+ central.push(Buffer.concat([cd, nameBuf]));++ offset += local.length + nameBuf.length + dataBuf.length;+ }++ const centralBuf = Buffer.concat(central);+ const centralOffset = offset;++ const eocd = Buffer.alloc(22);+ eocd.writeUInt32LE(EOCD_SIG, 0);+ eocd.writeUInt16LE(0, 4); // disk number+ eocd.writeUInt16LE(0, 6); // disk with central dir+ eocd.writeUInt16LE(entries.length, 8); // entries on this disk+ eocd.writeUInt16LE(entries.length, 10); // total entries+ eocd.writeUInt32LE(centralBuf.length, 12); // central dir size+ eocd.writeUInt32LE(centralOffset, 16); // central dir offset+ eocd.writeUInt16LE(0, 20); // comment length++ return Buffer.concat([...chunks, centralBuf, eocd]);+}diff --git a/server/lib/zipWriter.test.js b/server/lib/zipWriter.test.jsnew file mode 100644index 0000000000..102ab75a11--- /dev/null+++ b/server/lib/zipWriter.test.js@@ -0,0 +1,120 @@+import { describe, it, expect } from 'vitest';+import { Readable, Writable } from 'stream';+import { execFileSync } from 'child_process';+import { writeFileSync, mkdtempSync, rmSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import { createZip, crc32 } from './zipWriter.js';+import { parseZip } from './zipStream.js';++// Read a zip Buffer back through the production parser — proves the writer's+// output is consumable by PortOS's own reader.+function collectEntries(zipBuf) {+ return new Promise((resolve, reject) => {+ const entryPromises = [];+ const parser = parseZip();+ parser.on('entry', (entry) => {+ entryPromises.push(new Promise((res) => {+ const chunks = [];+ const sink = new Writable({ write(chunk, _, cb) { chunks.push(chunk); cb(); } });+ sink.on('finish', () => res({ path: entry.path, data: Buffer.concat(chunks) }));+ entry.pipe(sink);+ }));+ });+ parser.on('close', () => Promise.all(entryPromises).then(resolve, reject));+ parser.on('error', reject);+ Readable.from([zipBuf]).pipe(parser);+ });+}++describe('crc32', () => {+ it('matches the known CRC-32 of "123456789"', () => {+ // Canonical IEEE 802.3 check value.+ expect(crc32(Buffer.from('123456789'))).toBe(0xcbf43926);+ });++ it('is 0 for empty input', () => {+ expect(crc32(Buffer.alloc(0))).toBe(0);+ });+});++describe('createZip', () => {+ it('round-trips a single entry through parseZip', async () => {+ const zip = createZip([{ name: 'hello.txt', data: 'hello world' }]);+ const entries = await collectEntries(zip);+ expect(entries).toHaveLength(1);+ expect(entries[0].path).toBe('hello.txt');+ expect(entries[0].data.toString()).toBe('hello world');+ });++ it('round-trips multiple entries with nested paths in order', async () => {+ const zip = createZip([+ { name: 'README.md', data: '# Front door' },+ { name: 'identity/prompt.md', data: 'twin prompt' },+ { name: 'data/manifest.json', data: Buffer.from('{"kind":"x"}') },+ ]);+ const entries = await collectEntries(zip);+ expect(entries.map(e => e.path)).toEqual(['README.md', 'identity/prompt.md', 'data/manifest.json']);+ expect(entries[1].data.toString()).toBe('twin prompt');+ expect(JSON.parse(entries[2].data.toString())).toEqual({ kind: 'x' });+ });++ it('preserves binary payloads byte-for-byte', async () => {+ const bin = Buffer.from([0x00, 0xff, 0x10, 0x80, 0x7f, 0x00, 0xab]);+ const zip = createZip([{ name: 'blob.bin', data: bin }]);+ const entries = await collectEntries(zip);+ expect(Buffer.compare(entries[0].data, bin)).toBe(0);+ });++ it('handles an empty-data entry', async () => {+ const zip = createZip([{ name: 'empty.txt', data: '' }]);+ const entries = await collectEntries(zip);+ expect(entries[0].data.length).toBe(0);+ });++ it('is deterministic across calls', () => {+ const a = createZip([{ name: 'a.txt', data: 'same' }]);+ const b = createZip([{ name: 'a.txt', data: 'same' }]);+ expect(Buffer.compare(a, b)).toBe(0);+ });++ it('rejects duplicate entry names', () => {+ expect(() => createZip([+ { name: 'dup.txt', data: 'one' },+ { name: 'dup.txt', data: 'two' },+ ])).toThrow(/duplicate/i);+ });++ it('rejects entries without a name', () => {+ expect(() => createZip([{ data: 'no name' }])).toThrow(/name/i);+ });++ it('rejects a non-array argument', () => {+ expect(() => createZip('nope')).toThrow(/array/i);+ });++ it('produces an archive the system unzip tool can extract', () => {+ // Guards against subtle header-field mistakes that parseZip (which ignores+ // the central directory) would tolerate but a real tool would reject.+ let unzipPath;+ try {+ unzipPath = execFileSync('which', ['unzip']).toString().trim();+ } catch {+ return; // no unzip on this host — skip rather than fail+ }+ if (!unzipPath) return;+ const dir = mkdtempSync(join(tmpdir(), 'zipwriter-'));+ try {+ const zipPath = join(dir, 'bundle.zip');+ writeFileSync(zipPath, createZip([+ { name: 'README.md', data: '# Legacy' },+ { name: 'data/manifest.json', data: '{"kind":"portos-legacy-export"}' },+ ]));+ // -t tests integrity against the central directory + CRCs.+ const out = execFileSync(unzipPath, ['-t', zipPath]).toString();+ expect(out).toMatch(/No errors detected/i);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/server/routes/legacyExport.js b/server/routes/legacyExport.jsnew file mode 100644index 0000000000..96776c2375--- /dev/null+++ b/server/routes/legacyExport.js@@ -0,0 +1,30 @@+import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest, legacyExportSchema } from '../lib/validation.js';+import { buildLegacyZip, previewLegacyExport } from '../services/legacyExport.js';++const router = Router();++// GET /api/legacy-export/preview — section presence + counts + estimated size,+// without building the zip. Cheap enough to call on page load.+router.get('/preview', asyncHandler(async (req, res) => {+ const preview = await previewLegacyExport();+ res.json(preview);+}));++// POST /api/legacy-export — build and stream the identity bundle as a zip+// attachment. `sections` (optional) narrows the bundle; omitted means "all".+router.post('/', asyncHandler(async (req, res) => {+ const { sections } = validateRequest(legacyExportSchema, req.body || {});+ const io = req.app.get('io');+ const { buffer } = await buildLegacyZip({ sections: sections || null, io });++ // Date-stamped filename, mirroring the catalog download pattern.+ const date = new Date().toISOString().slice(0, 10);+ res.setHeader('Content-Type', 'application/zip');+ res.setHeader('Content-Disposition', `attachment; filename="legacy-export-${date}.zip"`);+ res.setHeader('Content-Length', String(buffer.length));+ res.send(buffer);+}));++export default router;diff --git a/server/routes/legacyExport.test.js b/server/routes/legacyExport.test.jsnew file mode 100644index 0000000000..5ccfcf3ad0--- /dev/null+++ b/server/routes/legacyExport.test.js@@ -0,0 +1,72 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { LEGACY_EXPORT_SECTIONS } from '../lib/validation.js';+import { getSectionKeys } from '../services/legacyExport.js';++// Mock the service so the route test stays fast and binary-free — the bundle+// itself is covered by legacyExport.test.js.+const buildLegacyZip = vi.fn(async () => ({ buffer: Buffer.from('PK-fake-zip'), manifest: { fileCount: 1 } }));+const previewLegacyExport = vi.fn(async () => ({ sections: { goals: { present: true } }, fileCount: 4, estimatedBytes: 1234 }));+vi.mock('../services/legacyExport.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, buildLegacyZip: (...a) => buildLegacyZip(...a), previewLegacyExport: (...a) => previewLegacyExport(...a) };+});++function makeApp() {+ const app = express();+ app.use(express.json());+ return import('./legacyExport.js').then(({ default: router }) => {+ app.use('/api/legacy-export', router);+ app.use(errorMiddleware);+ return app;+ });+}++beforeEach(() => {+ buildLegacyZip.mockClear();+ previewLegacyExport.mockClear();+});++describe('GET /api/legacy-export/preview', () => {+ it('returns the section preview', async () => {+ const app = await makeApp();+ const res = await request(app).get('/api/legacy-export/preview');+ expect(res.status).toBe(200);+ expect(res.body.sections).toBeDefined();+ expect(res.body.estimatedBytes).toBe(1234);+ expect(previewLegacyExport).toHaveBeenCalledOnce();+ });+});++describe('POST /api/legacy-export', () => {+ it('streams a zip attachment with a date-stamped filename', async () => {+ const app = await makeApp();+ const res = await request(app).post('/api/legacy-export').send({});+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toContain('application/zip');+ expect(res.headers['content-disposition']).toMatch(/attachment; filename="legacy-export-\d{4}-\d{2}-\d{2}\.zip"/);+ expect(buildLegacyZip).toHaveBeenCalledWith(expect.objectContaining({ sections: null }));+ });++ it('passes a section filter through to the service', async () => {+ const app = await makeApp();+ const res = await request(app).post('/api/legacy-export').send({ sections: ['goals', 'health'] });+ expect(res.status).toBe(200);+ expect(buildLegacyZip).toHaveBeenCalledWith(expect.objectContaining({ sections: ['goals', 'health'] }));+ });++ it('rejects an unknown section with 400', async () => {+ const app = await makeApp();+ const res = await request(app).post('/api/legacy-export').send({ sections: ['not-a-section'] });+ expect(res.status).toBe(400);+ expect(buildLegacyZip).not.toHaveBeenCalled();+ });+});++describe('schema/service section parity', () => {+ it('LEGACY_EXPORT_SECTIONS matches the service section keys', () => {+ expect(LEGACY_EXPORT_SECTIONS).toEqual(getSectionKeys());+ });+});diff --git a/server/services/legacyExport.js b/server/services/legacyExport.jsnew file mode 100644index 0000000000..f83c68030a--- /dev/null+++ b/server/services/legacyExport.js@@ -0,0 +1,491 @@+/**+ * Legacy Export — a portable, self-contained identity bundle.+ *+ * Gathers identity across every PortOS domain (digital twin, autobiography,+ * brain, memories, goals, health) into a zip of Markdown + machine-readable+ * JSON + a SHA-256 `manifest.json`. The bundle is readable with **zero PortOS+ * running** — plain Markdown/JSON, no database. Closes the GOALS "Knowledge+ * Legacy" gap (issue #901).+ *+ * Modeled after `backup.js`: gather data (each source degrades to a fallback so+ * one missing domain never fails the export), build per-section Markdown + JSON,+ * compute a SHA-256 manifest, emit `legacy-export:*` socket events, and return a+ * single zip Buffer via the dependency-free `zipWriter.js`.+ *+ * Phase 1 (this file): server-side zip bundle, no PDF, no client UI. PDF+ * rendering and the export UI are tracked as follow-up issues.+ */++import { createHash } from 'crypto';+import { hostname } from 'os';+import { createZip } from '../lib/zipWriter.js';+import { getCurrentVersion } from './updateChecker.js';+import { exportDigitalTwin } from './digital-twin-export.js';+import { getStories } from './autobiography.js';+import { getGenomeSummary } from './genome.js';+import { getTasteProfile } from './taste-questionnaire.js';+import { getChronotype, getLongevity } from './identity.js';+import { getTraits } from './digital-twin-analysis.js';+import { getAll as getBrainAll } from './brainStorage.js';+import { getMemories } from './memory.js';+import { getGoalsTree } from './identity/goals.js';+import { getLatestMetricValues } from './appleHealthQuery.js';++const MACHINE_HOST = hostname().toLowerCase().replace(/[^\w.\-]/g, '_') || 'unknown';++// Brain entity stores that belong in a personal legacy bundle. We deliberately+// skip operational stores (`admin`, `buckets`, `inbox`) — they're workflow+// scaffolding, not identity.+const BRAIN_LEGACY_TYPES = ['people', 'projects', 'ideas', 'journals', 'links'];++// Health metrics surfaced in the summary, with the human label used in Markdown.+// Each value carries its own freshness date (last sync) as the source caveat.+const HEALTH_METRICS = [+ ['resting_heart_rate', 'Resting heart rate', 'bpm'],+ ['heart_rate_variability', 'Heart rate variability', 'ms'],+ ['weight_body_mass', 'Body mass', ''],+ ['step_count', 'Daily steps', ''],+ ['sleep_analysis', 'Sleep', ''],+ ['vo2_max', 'VO₂ max', ''],+];++const HEALTH_CAVEAT =+ '> ⚠️ **Source caveat:** the figures below are device-reported (Apple Health / manual lab entry) ' ++ 'and unvalidated. They are a personal-tracking snapshot, **not a verified medical record**, and ' ++ 'each line states its own source and freshness.';++/**+ * Mask obvious secrets that may have been pasted into free-text identity+ * content (brain notes, journals, autobiography). Defense-in-depth: the bundle+ * leaves the machine, so a stray API key in a note must not ride along. Pure,+ * conservative — only high-confidence token shapes are touched so prose is never+ * mangled.+ */+export function redactSecrets(text) {+ if (typeof text !== 'string' || !text) return text;+ return text+ // OpenAI / Anthropic style: sk-..., sk-ant-...+ .replace(/\bsk-(?:ant-)?[A-Za-z0-9_-]{20,}\b/g, '[REDACTED]')+ // GitHub tokens: ghp_, gho_, ghu_, ghs_, ghr_, github_pat_+ .replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g, '[REDACTED]')+ // AWS access key id+ .replace(/\bAKIA[0-9A-Z]{16}\b/g, '[REDACTED]')+ // Slack tokens+ .replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, '[REDACTED]')+ // Bearer tokens in headers+ .replace(/\bBearer\s+[A-Za-z0-9._-]{20,}\b/g, 'Bearer [REDACTED]')+ // "password": "...", password=..., api_key: ...+ .replace(/("?(?:password|passwd|secret|api[_-]?key|token)"?\s*[:=]\s*"?)([^"\s,}]{6,})/gi, '$1[REDACTED]');+}++const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);++/**+ * Gather identity data across every domain. Each source is independently+ * `.catch`-guarded so a single unavailable backend (e.g. Postgres-backed brain+ * when running file-only) degrades to an empty section instead of failing the+ * whole export.+ */+export async function gatherLegacyData() {+ const brainEntries = {};+ await Promise.all(BRAIN_LEGACY_TYPES.map(async (type) => {+ brainEntries[type] = await getBrainAll(type).catch(() => []);+ }));++ const [+ twinPrompt, claudeMd, stories, genome, taste, chronotype, longevity, traits,+ memoriesResult, goalsTree, healthValues,+ ] = await Promise.all([+ exportDigitalTwin('system_prompt').then(r => r?.content || '').catch(() => ''),+ exportDigitalTwin('claude_md').then(r => r?.content || '').catch(() => ''),+ getStories().catch(() => []),+ getGenomeSummary().catch(() => ({ uploaded: false })),+ getTasteProfile().catch(() => ({ sections: [] })),+ getChronotype().catch(() => null),+ getLongevity().catch(() => null),+ getTraits().catch(() => null),+ getMemories({ limit: 100000 }).catch(() => ({ total: 0, memories: [] })),+ getGoalsTree().catch(() => ({ roots: [], flat: [] })),+ getLatestMetricValues(HEALTH_METRICS.map(m => m[0])).catch(() => ({})),+ ]);++ return {+ twinPrompt,+ claudeMd,+ stories: Array.isArray(stories) ? stories : [],+ genome: genome || { uploaded: false },+ taste: taste || { sections: [] },+ chronotype: chronotype || null,+ longevity: longevity || null,+ traits: traits || null,+ brain: brainEntries,+ memories: Array.isArray(memoriesResult?.memories) ? memoriesResult.memories : [],+ goals: Array.isArray(goalsTree?.flat) ? goalsTree.flat : [],+ health: healthValues || {},+ };+}++// === Section descriptors ===+// Each section is self-describing: how to detect presence, count records, and+// render Markdown + machine-readable JSON. The route's section-filter and the+// manifest both iterate this one list, so adding a domain is a single entry.++const SECTIONS = [+ {+ key: 'identity',+ dir: 'identity',+ label: 'Identity & Values',+ present: (d) => !!(d.twinPrompt || d.claudeMd || d.traits || d.chronotype || d.longevity || d.taste?.sections?.length),+ counts: (d) => ({ hasTwinPrompt: !!d.twinPrompt, traits: d.traits?.dimensions ? Object.keys(d.traits.dimensions).length : 0 }),+ files: (d) => {+ const out = [];+ if (d.twinPrompt) out.push({ name: 'identity/digital-twin-prompt.md', data: redactSecrets(d.twinPrompt) });+ if (d.claudeMd) out.push({ name: 'identity/claude.md', data: redactSecrets(d.claudeMd) });+ out.push({ name: 'identity/profile.md', data: buildIdentityProfileMd(d) });+ out.push({ name: 'data/identity.json', data: jsonFile({+ traits: d.traits || null,+ chronotype: d.chronotype || null,+ longevity: d.longevity || null,+ taste: d.taste || null,+ genome: d.genome || null,+ }) });+ return out;+ },+ },+ {+ key: 'autobiography',+ dir: 'autobiography',+ label: 'Life Stories',+ present: (d) => d.stories.length > 0,+ counts: (d) => ({ stories: d.stories.length }),+ files: (d) => [+ { name: 'autobiography/autobiography.md', data: buildAutobiographyMd(d.stories) },+ { name: 'data/autobiography.json', data: jsonFile(d.stories) },+ ],+ },+ {+ key: 'brain',+ dir: 'brain',+ label: 'Brain & Memories',+ present: (d) => d.memories.length > 0 || BRAIN_LEGACY_TYPES.some(t => (d.brain[t] || []).length > 0),+ counts: (d) => ({+ memories: d.memories.length,+ ...Object.fromEntries(BRAIN_LEGACY_TYPES.map(t => [t, (d.brain[t] || []).length])),+ }),+ files: (d) => {+ const out = [];+ for (const type of BRAIN_LEGACY_TYPES) {+ const records = d.brain[type] || [];+ if (records.length === 0) continue;+ out.push({ name: `brain/${type}.md`, data: buildBrainTypeMd(type, records) });+ }+ if (d.memories.length > 0) {+ out.push({ name: 'brain/memories.md', data: buildMemoriesMd(d.memories) });+ }+ out.push({ name: 'data/brain.json', data: jsonFile({ ...d.brain, memories: d.memories }) });+ return out;+ },+ },+ {+ key: 'goals',+ dir: 'goals',+ label: 'Goals & Milestones',+ present: (d) => d.goals.length > 0,+ counts: (d) => ({ goals: d.goals.length }),+ files: (d) => [+ { name: 'goals/goals.md', data: buildGoalsMd(d.goals) },+ { name: 'data/goals.json', data: jsonFile(d.goals) },+ ],+ },+ {+ key: 'decisions',+ dir: 'decisions',+ label: 'Key Decisions',+ // v1 source: completed goal milestones. PortOS has no first-class life+ // "decisions" store (decisionLog.js is CoS task scheduling), so the manifest+ // documents this provenance. Tracked for a richer source in a follow-up.+ present: (d) => collectMilestones(d.goals).length > 0,+ counts: (d) => ({ milestones: collectMilestones(d.goals).length }),+ files: (d) => [+ { name: 'decisions/key-decisions.md', data: buildDecisionsMd(d.goals) },+ ],+ source: 'Derived from completed goal milestones (PortOS has no dedicated life-decisions store in v1).',+ },+ {+ key: 'health',+ dir: 'health',+ label: 'Health Summary',+ present: (d) => HEALTH_METRICS.some(([metric]) => d.health[metric]),+ counts: (d) => ({ metrics: HEALTH_METRICS.filter(([m]) => d.health[m]).length }),+ files: (d) => [+ { name: 'health/health-summary.md', data: buildHealthMd(d.health) },+ { name: 'data/health.json', data: jsonFile(d.health) },+ ],+ source: 'Device-reported (Apple Health) and manual lab entry — unvalidated, not a medical record.',+ },+];++export function getSectionKeys() {+ return SECTIONS.map(s => s.key);+}++// === Markdown builders (pure) ===++function mdHeader(title, subtitle) {+ return `# ${title}\n\n*${subtitle}*\n`;+}++function buildIdentityProfileMd(d) {+ const out = [mdHeader('Identity Profile', 'Personality, chronotype, taste, genome, and longevity')];+ if (d.traits?.dimensions) {+ out.push('## Personality Traits\n');+ const lines = Object.entries(d.traits.dimensions)+ .filter(([, v]) => v?.score != null)+ .map(([k, v]) => `- **${titleize(k)}**: ${v.score}/100${v.label ? ` (${v.label})` : ''}`);+ if (lines.length) out.push(lines.join('\n'));+ if (d.traits.summary) out.push(`\n${redactSecrets(d.traits.summary)}`);+ }+ if (d.chronotype?.type) {+ out.push('## Chronotype\n');+ out.push(`**Type**: ${d.chronotype.type}${d.chronotype.confidence ? ` (${Math.round(d.chronotype.confidence * 100)}% confidence)` : ''}`);+ }+ const completed = (d.taste?.sections || []).filter(s => s.status === 'complete');+ if (completed.length) {+ out.push('## Taste Profile\n');+ for (const s of completed) {+ out.push(`### ${s.label}\n`);+ if (s.summary) out.push(redactSecrets(s.summary));+ }+ }+ if (d.genome?.uploaded) {+ out.push('## Genome\n');+ const g = [`- **SNPs analyzed**: ${num(d.genome.snpCount)?.toLocaleString() || 'unknown'}`];+ if (d.genome.markerCount) g.push(`- **Markers tracked**: ${d.genome.markerCount}`);+ out.push(g.join('\n'));+ }+ if (d.longevity?.estimatedLifeExpectancy) {+ out.push('## Longevity\n');+ out.push(`- **Estimated life expectancy**: ${d.longevity.estimatedLifeExpectancy} years`);+ }+ return out.join('\n\n');+}++function buildAutobiographyMd(stories) {+ const out = [mdHeader('Autobiography', `${stories.length} life ${stories.length === 1 ? 'story' : 'stories'}`)];+ const sorted = [...stories].sort((a, b) =>+ (a.themeId || '').localeCompare(b.themeId || '') ||+ String(a.createdAt || '').localeCompare(String(b.createdAt || '')));+ let theme = null;+ for (const story of sorted) {+ if (story.themeId !== theme) {+ theme = story.themeId;+ out.push(`## ${theme ? titleize(theme) : 'Miscellaneous'}\n`);+ }+ if (story.prompt) out.push(`> *${redactSecrets(story.prompt)}*\n`);+ if (story.content) out.push(redactSecrets(story.content));+ }+ return out.join('\n\n');+}++function buildBrainTypeMd(type, records) {+ const out = [mdHeader(titleize(type), `${records.length} ${records.length === 1 ? 'entry' : 'entries'} from the Brain`)];+ for (const r of records) {+ const title = r.title || r.name || r.label || r.id;+ out.push(`## ${redactSecrets(String(title))}`);+ const body = r.content || r.body || r.text || r.notes || r.description || '';+ if (body) out.push(redactSecrets(String(body)));+ if (Array.isArray(r.tags) && r.tags.length) out.push(`*Tags: ${r.tags.join(', ')}*`);+ }+ return out.join('\n\n');+}++function buildMemoriesMd(memories) {+ const out = [mdHeader('Memories', `${memories.length} ${memories.length === 1 ? 'memory' : 'memories'}`)];+ const byCategory = {};+ for (const m of memories) {+ const cat = m.category || 'uncategorized';+ (byCategory[cat] ||= []).push(m);+ }+ for (const [cat, items] of Object.entries(byCategory)) {+ out.push(`## ${titleize(cat)}\n`);+ for (const m of items) {+ const text = m.summary || m.content || '';+ if (text) out.push(`- ${redactSecrets(String(text))}`);+ }+ }+ return out.join('\n\n');+}++function buildGoalsMd(goals) {+ const out = [mdHeader('Goals & Milestones', `${goals.length} ${goals.length === 1 ? 'goal' : 'goals'}`)];+ const active = goals.filter(g => g.status !== 'abandoned');+ for (const g of active) {+ const status = g.status === 'completed' ? ' [completed]' : num(g.progress) != null ? ` (${g.progress}%)` : '';+ out.push(`## ${redactSecrets(String(g.title || 'Untitled'))}${status}`);+ if (g.description) out.push(redactSecrets(String(g.description)));+ const ms = Array.isArray(g.milestones) ? g.milestones : [];+ if (ms.length) {+ out.push(ms.map(m => `- [${m.completedAt ? 'x' : ' '}] ${redactSecrets(String(m.title || m.description || ''))}`).join('\n'));+ }+ }+ return out.join('\n\n');+}++function collectMilestones(goals) {+ const out = [];+ for (const g of goals) {+ for (const m of (Array.isArray(g.milestones) ? g.milestones : [])) {+ if (m.completedAt) out.push({ goal: g.title, ...m });+ }+ }+ return out;+}++function buildDecisionsMd(goals) {+ const milestones = collectMilestones(goals);+ const out = [mdHeader('Key Decisions', 'Derived from completed goal milestones')];+ out.push('> *Source note:* PortOS has no dedicated life-decisions store in v1, so this section is derived from completed milestones across goals.');+ for (const m of milestones) {+ const when = m.completedAt ? ` _(completed ${String(m.completedAt).slice(0, 10)})_` : '';+ out.push(`- **${redactSecrets(String(m.goal || 'Goal'))}** — ${redactSecrets(String(m.title || m.description || ''))}${when}`);+ }+ return out.join('\n\n');+}++function buildHealthMd(health) {+ const out = [mdHeader('Health Summary', 'Self-tracked vitals'), HEALTH_CAVEAT];+ const lines = [];+ for (const [metric, label, unit] of HEALTH_METRICS) {+ const v = health[metric];+ if (!v) continue;+ const value = v.value != null ? v.value : v;+ const date = v.date ? ` (last sync ${String(v.date).slice(0, 10)})` : '';+ lines.push(`- **${label}**: ${value}${unit ? ` ${unit}` : ''} — Apple Health${date}`);+ }+ out.push(lines.length ? lines.join('\n') : '_No health metrics available._');+ return out.join('\n\n');+}++function titleize(s) {+ return String(s || '')+ .replace(/([A-Z])/g, ' $1')+ .replace(/[_-]+/g, ' ')+ .replace(/\s+/g, ' ')+ .trim()+ .replace(/^./, c => c.toUpperCase());+}++function jsonFile(obj) {+ return JSON.stringify(obj, null, 2);+}++// === Bundle assembly ===++const README_PRIVACY_BANNER =+ '# PortOS Legacy Export\n\n' ++ '> ⚠️ **Privacy notice:** this bundle contains your full plaintext identity — autobiography, ' ++ 'brain notes, memories, goals, and health/genome summaries. It was generated on your machine, ' ++ 'at your request, and is **not** uploaded anywhere by PortOS. Treat the file as sensitive: anyone ' ++ 'who opens it can read everything inside.\n\n' ++ 'This is a self-contained portrait of your identity, knowledge, and life story — readable with no ' ++ 'PortOS running. Open any `.md` file for the human-readable record; the `data/` folder mirrors each ' ++ 'section as machine-readable JSON, and `manifest.json` indexes every file with a SHA-256 checksum.\n';++function sha256(buf) {+ return createHash('sha256').update(buf).digest('hex');+}++/**+ * Build the list of bundle files for the selected sections. Pure over gathered+ * `data` — no I/O. Returns `{ files, sections }` where `files` is the+ * `{ name, data }` list ready for `createZip` and `sections` is the manifest's+ * per-section presence/counts metadata.+ */+export function buildBundleFiles(data, { sections: selected = null } = {}) {+ const wanted = Array.isArray(selected) && selected.length+ ? SECTIONS.filter(s => selected.includes(s.key))+ : SECTIONS;++ const files = [];+ const sectionMeta = {};++ for (const section of SECTIONS) {+ const present = section.present(data);+ const included = wanted.includes(section);+ sectionMeta[section.key] = {+ present,+ included: included && present,+ ...(present ? section.counts(data) : {}),+ ...(section.source ? { source: section.source } : {}),+ };+ if (included && present) {+ for (const f of section.files(data)) {+ files.push({ name: f.name, data: Buffer.isBuffer(f.data) ? f.data : Buffer.from(String(f.data), 'utf-8') });+ }+ }+ }++ return { files, sections: sectionMeta };+}++/**+ * Build the manifest object (SHA-256 per file). `kind`/`schemaVersion` let a+ * future reader (or `parseZip` round-trip verifier) validate the bundle.+ */+export function buildManifest(files, { sections, portosVersion, generatedAt }) {+ const fileHashes = {};+ for (const f of files) fileHashes[f.name] = sha256(f.data);+ return {+ schemaVersion: 1,+ kind: 'portos-legacy-export',+ generatedAt,+ portosVersion,+ host: MACHINE_HOST,+ sections,+ files: fileHashes,+ fileCount: files.length,+ pdf: { included: false }, // PDF is a follow-up (Phase 2)+ };+}++/**+ * Build the full legacy-export zip. Returns `{ buffer, manifest }`.+ * `io` (optional) receives `legacy-export:*` progress events.+ */+export async function buildLegacyZip({ sections = null, io = null } = {}) {+ emit(io, 'legacy-export:started', { sections });+ const data = await gatherLegacyData();+ emit(io, 'legacy-export:progress', { phase: 'gathered' });++ const { files, sections: sectionMeta } = buildBundleFiles(data, { sections });+ const portosVersion = await getCurrentVersion().catch(() => '0.0.0');+ const generatedAt = new Date().toISOString();++ // README first, then content files, then the manifest (which hashes the+ // content files — build it before adding manifest.json so it doesn't hash+ // itself).+ const readme = { name: 'README.md', data: Buffer.from(README_PRIVACY_BANNER, 'utf-8') };+ const contentFiles = [readme, ...files];+ const manifest = buildManifest(contentFiles, { sections: sectionMeta, portosVersion, generatedAt });+ const manifestFile = { name: 'manifest.json', data: Buffer.from(jsonFile(manifest), 'utf-8') };++ const buffer = createZip([...contentFiles, manifestFile]);+ console.log(`📦 Legacy export: ${manifest.fileCount} files, ${(buffer.length / 1024).toFixed(1)} KB`);+ emit(io, 'legacy-export:completed', { fileCount: manifest.fileCount, bytes: buffer.length });+ return { buffer, manifest };+}++/**+ * Lightweight preview — section presence + counts + an estimated byte size,+ * WITHOUT building the zip. Used by `GET /api/legacy-export/preview`.+ */+export async function previewLegacyExport() {+ const data = await gatherLegacyData();+ const { files, sections } = buildBundleFiles(data, { sections: null });+ const estimatedBytes = files.reduce((sum, f) => sum + f.data.length, 0);+ return { sections, fileCount: files.length + 2 /* README + manifest */, estimatedBytes };+}++function emit(io, event, payload) {+ if (io && typeof io.emit === 'function') io.emit(event, payload);+}diff --git a/server/services/legacyExport.test.js b/server/services/legacyExport.test.jsnew file mode 100644index 0000000000..adcdfcc29d--- /dev/null+++ b/server/services/legacyExport.test.js@@ -0,0 +1,186 @@+import { describe, it, expect } from 'vitest';+import { Readable, Writable } from 'stream';+import {+ redactSecrets,+ buildBundleFiles,+ buildManifest,+ buildLegacyZip,+ previewLegacyExport,+ getSectionKeys,+} from './legacyExport.js';+import { parseZip } from '../lib/zipStream.js';++// Round-trip a zip Buffer through the production parser → { path: Buffer }.+function unzip(zipBuf) {+ return new Promise((resolve, reject) => {+ const entryPromises = [];+ const parser = parseZip();+ parser.on('entry', (entry) => {+ entryPromises.push(new Promise((res) => {+ const chunks = [];+ const sink = new Writable({ write(chunk, _, cb) { chunks.push(chunk); cb(); } });+ sink.on('finish', () => res({ path: entry.path, data: Buffer.concat(chunks) }));+ entry.pipe(sink);+ }));+ });+ parser.on('close', () => Promise.all(entryPromises).then(+ (entries) => resolve(Object.fromEntries(entries.map(e => [e.path, e.data]))),+ reject,+ ));+ parser.on('error', reject);+ Readable.from([zipBuf]).pipe(parser);+ });+}++// A representative gathered-data object — exercises every section.+function sampleData() {+ return {+ twinPrompt: '# Twin\nYou are helping someone.',+ claudeMd: '# Soul\n',+ stories: [{ id: 's1', themeId: 'childhood', prompt: 'Earliest memory?', content: 'A summer.', createdAt: '2020-01-01' }],+ genome: { uploaded: true, snpCount: 600000, markerCount: 42 },+ taste: { sections: [{ label: 'Music', status: 'complete', summary: 'Loves jazz.' }] },+ chronotype: { type: 'Lion', confidence: 0.8 },+ longevity: { estimatedLifeExpectancy: 90 },+ traits: { dimensions: { openness: { score: 80, label: 'High' } }, summary: 'Curious.' },+ brain: {+ people: [{ id: 'p1', name: 'Ada', content: 'A friend.' }],+ projects: [{ id: 'pr1', title: 'PortOS', content: 'Personal OS.', tags: ['code'] }],+ ideas: [], journals: [{ id: 'j1', title: 'Day 1', content: 'Started.' }], links: [],+ },+ memories: [{ id: 'm1', category: 'work', summary: 'Shipped a feature.' }],+ goals: [{ id: 'g1', title: 'Write a book', status: 'active', progress: 30, description: 'A novel.',+ milestones: [{ id: 'ms1', title: 'Outline', completedAt: '2024-05-01T00:00:00Z' }] }],+ health: { resting_heart_rate: { value: 58, date: '2026-06-10' } },+ };+}++describe('redactSecrets', () => {+ it('masks an OpenAI-style key', () => {+ expect(redactSecrets('key sk-abcdefghijklmnopqrstuvwxyz012345')).toContain('[REDACTED]');+ });+ it('masks a GitHub PAT', () => {+ expect(redactSecrets('ghp_0123456789abcdefghijklmnopqrstuvwx')).toBe('[REDACTED]');+ });+ it('masks a password assignment', () => {+ expect(redactSecrets('"password": "hunter2hunter2"')).toContain('[REDACTED]');+ expect(redactSecrets('"password": "hunter2hunter2"')).not.toContain('hunter2');+ });+ it('leaves ordinary prose untouched', () => {+ const prose = 'I grew up near the ocean and loved skateboarding.';+ expect(redactSecrets(prose)).toBe(prose);+ });+ it('passes through non-strings', () => {+ expect(redactSecrets(null)).toBe(null);+ expect(redactSecrets(42)).toBe(42);+ });+});++describe('buildBundleFiles', () => {+ it('includes every present section with no filter', () => {+ const { files, sections } = buildBundleFiles(sampleData());+ const names = files.map(f => f.name);+ expect(names).toContain('identity/digital-twin-prompt.md');+ expect(names).toContain('autobiography/autobiography.md');+ expect(names).toContain('brain/people.md');+ expect(names).toContain('brain/memories.md');+ expect(names).toContain('goals/goals.md');+ expect(names).toContain('decisions/key-decisions.md');+ expect(names).toContain('health/health-summary.md');+ expect(sections.health.present).toBe(true);+ expect(sections.brain.memories).toBe(1);+ });++ it('honors a section filter', () => {+ const { files, sections } = buildBundleFiles(sampleData(), { sections: ['goals'] });+ const names = files.map(f => f.name);+ expect(names).toContain('goals/goals.md');+ expect(names.some(n => n.startsWith('autobiography/'))).toBe(false);+ // present is still reported true even when excluded from this bundle+ expect(sections.autobiography.present).toBe(true);+ expect(sections.autobiography.included).toBe(false);+ expect(sections.goals.included).toBe(true);+ });++ 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,+ brain: { people: [], projects: [], ideas: [], journals: [], links: [] },+ memories: [], goals: [], health: {} };+ const { files, sections } = buildBundleFiles(empty);+ expect(sections.autobiography.present).toBe(false);+ expect(sections.health.present).toBe(false);+ expect(files.some(f => f.name.startsWith('autobiography/'))).toBe(false);+ });++ it('redacts secrets pasted into brain content', () => {+ const d = sampleData();+ d.brain.journals[0].content = 'token ghp_0123456789abcdefghijklmnopqrstuvwx end';+ const { files } = buildBundleFiles(d);+ const journal = files.find(f => f.name === 'brain/journals.md');+ expect(journal.data.toString()).toContain('[REDACTED]');+ expect(journal.data.toString()).not.toContain('ghp_0123');+ });++ it('includes a health source caveat', () => {+ const { files } = buildBundleFiles(sampleData());+ const health = files.find(f => f.name === 'health/health-summary.md');+ expect(health.data.toString()).toMatch(/not a verified medical record/i);+ expect(health.data.toString()).toContain('last sync 2026-06-10');+ });+});++describe('buildManifest', () => {+ it('hashes every file with a SHA-256 and stamps kind/schemaVersion', () => {+ const { files, sections } = buildBundleFiles(sampleData());+ const manifest = buildManifest(files, { sections, portosVersion: '1.2.3', generatedAt: '2026-06-18T00:00:00Z' });+ expect(manifest.kind).toBe('portos-legacy-export');+ expect(manifest.schemaVersion).toBe(1);+ expect(manifest.fileCount).toBe(files.length);+ for (const name of Object.keys(manifest.files)) {+ expect(manifest.files[name]).toMatch(/^[0-9a-f]{64}$/);+ }+ });+});++describe('buildLegacyZip', () => {+ it('produces a valid zip that unzips to README + manifest + section files', async () => {+ // gatherLegacyData runs against the live (test) backends; each source is+ // catch-guarded, so the bundle is built regardless of what data exists.+ const { buffer, manifest } = await buildLegacyZip({});+ const entries = await unzip(buffer);+ expect(entries['README.md'].toString()).toMatch(/Privacy notice/);+ expect(entries['manifest.json']).toBeDefined();+ const parsed = JSON.parse(entries['manifest.json'].toString());+ expect(parsed.kind).toBe('portos-legacy-export');+ expect(parsed.fileCount).toBe(manifest.fileCount);+ // Every manifest-listed file (except manifest.json itself) is in the zip.+ for (const name of Object.keys(parsed.files)) {+ expect(entries[name]).toBeDefined();+ }+ });++ it('emits legacy-export socket events when io is provided', async () => {+ const events = [];+ const io = { emit: (e, p) => events.push([e, p]) };+ await buildLegacyZip({ io });+ expect(events.map(e => e[0])).toEqual(+ expect.arrayContaining(['legacy-export:started', 'legacy-export:progress', 'legacy-export:completed']),+ );+ });+});++describe('previewLegacyExport', () => {+ it('returns section metadata and an estimated size without throwing', async () => {+ const preview = await previewLegacyExport();+ expect(preview).toHaveProperty('sections');+ expect(typeof preview.estimatedBytes).toBe('number');+ expect(preview.fileCount).toBeGreaterThanOrEqual(2); // README + manifest at minimum+ });+});++describe('getSectionKeys', () => {+ it('lists the known sections', () => {+ expect(getSectionKeys()).toEqual(['identity', 'autobiography', 'brain', 'goals', 'decisions', 'health']);+ });+});