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: seal a Persistent Mind into a downloadable passphrase-encrypted bundle (#7621)
[._.]/ Adam Eivy51439fb7e9b3
diff --git a/client/src/components/cos/PersistentMindPortabilityPanel.jsx b/client/src/components/cos/PersistentMindPortabilityPanel.jsxnew file mode 100644index 0000000000..f10041bdf0--- /dev/null+++ b/client/src/components/cos/PersistentMindPortabilityPanel.jsx@@ -0,0 +1,199 @@+import { useId, useState } from 'react';+import { Brain, Database, Download, Lock, ShieldCheck, Sparkles } from 'lucide-react';+import { downloadBlob } from '../../lib/downloadBlob.js';+import * as api from '../../services/api';+import Banner from '../ui/Banner';++// Mirrors `MIND_BUNDLE_PASSPHRASE_MIN_CHARS` in server/lib/mindBundleCrypto.js.+// Checked here so the user is told before a round trip; the server is still the+// authority and refuses a short passphrase on its own.+export const MIND_BUNDLE_PASSPHRASE_MIN_CHARS = 12;++// Protected memories quote private conversation, so that scope is opt-in —+// the decision is the epic's (#7620), not this panel's to soften.+const EXPORT_SCOPES = [+ {+ scope: 'profile',+ icon: Brain,+ label: 'Profile',+ detail: 'Chosen name, identity and operating instructions, playbook, and the pinned model policy. No install ids, paths, or capability grants.',+ defaultOn: true,+ },+ {+ scope: 'avatar',+ icon: Sparkles,+ label: 'Appearance',+ detail: 'The avatar style this Mind wears. A style id from the bundled vocabulary — no image is stored on this install today.',+ defaultOn: true,+ },+ {+ scope: 'memories',+ icon: Database,+ label: 'Protected memories',+ detail: 'Only core-identity and important memories, as type + text + date. These quote private conversation, so they are off unless you ask for them.',+ defaultOn: false,+ },+];++const defaultScopes = () => new Set(EXPORT_SCOPES.filter(({ defaultOn }) => defaultOn).map(({ scope }) => scope));++/**+ * The server names the file the same way. Deriving it here too keeps the+ * download on the plain `responseType: 'text'` path — reading the server's+ * Content-Disposition would mean dropping to a raw fetch for a filename both+ * sides can compute from the clock.+ */+export const mindBundleFilename = (now = new Date()) =>+ `portos-mind-${now.toISOString().replace(/[:.]/g, '-').replace(/-\d{3}Z$/, 'Z')}.portos-mind`;++/**+ * Export the Persistent Mind as one passphrase-sealed file (#7621).+ *+ * Nothing leaves the machine on its own: the bytes are produced by an explicit+ * click, handed to the browser's download, and never sent to a peer. The+ * passphrase lives in component state for the length of the click and is never+ * logged or persisted.+ */+export default function PersistentMindPortabilityPanel() {+ const idPrefix = useId();+ const [selected, setSelected] = useState(defaultScopes);+ const [passphrase, setPassphrase] = useState('');+ const [confirmPassphrase, setConfirmPassphrase] = useState('');+ const [pending, setPending] = useState(false);+ const [error, setError] = useState(null);+ const [exported, setExported] = useState(null);++ const toggle = (scope, enabled) => {+ setSelected((current) => {+ const next = new Set(current);+ if (enabled) next.add(scope);+ else next.delete(scope);+ return next;+ });+ setExported(null);+ };++ const tooShort = passphrase.length > 0 && passphrase.length < MIND_BUNDLE_PASSPHRASE_MIN_CHARS;+ const mismatch = confirmPassphrase.length > 0 && confirmPassphrase !== passphrase;+ const ready = selected.size > 0+ && passphrase.length >= MIND_BUNDLE_PASSPHRASE_MIN_CHARS+ && confirmPassphrase === passphrase;++ const exportBundle = async () => {+ if (pending || !ready) return;+ setPending(true);+ setError(null);+ setExported(null);+ const scopes = EXPORT_SCOPES.map(({ scope }) => scope).filter((scope) => selected.has(scope));+ await api.exportPersistentMindBundle({ scopes, passphrase })+ .then((bundle) => {+ const filename = mindBundleFilename();+ downloadBlob(bundle, filename);+ setExported({ filename, scopes });+ // The secret has done its job; do not leave it sitting in the form.+ setPassphrase('');+ setConfirmPassphrase('');+ })+ .catch((nextError) => setError(nextError?.message || 'Could not export the Mind bundle'))+ .finally(() => setPending(false));+ };++ return (+ <div className="space-y-4">+ <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-portability-heading">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h3 id="mind-portability-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text">+ <Download size={17} aria-hidden="true" /> Export this Mind+ </h3>+ <p className="mt-1 max-w-3xl text-xs text-port-text-muted">Seal the parts of this Mind you choose into one encrypted file you keep. Open it on another PortOS install to carry the same Mind there.</p>+ </div>+ <span className="rounded-full border border-port-border px-2.5 py-1 text-xs text-port-text-muted">Download only — never sent to a peer</span>+ </div>++ <div className="mt-4 rounded border border-port-success/40 bg-port-success/5 p-3 text-xs text-port-text">+ <p className="flex items-center gap-2 font-medium"><ShieldCheck size={16} aria-hidden="true" /> The file carries meaning, not this machine</p>+ <p className="mt-1 text-port-text-muted">No database ids, embeddings, file paths, hostnames, peer records, credentials, or conversation history go in. Capability grants stay here too — importing a Mind never widens what it may do. The file is sealed with a key derived from your passphrase, so this install's keys are not needed to open it.</p>+ </div>++ <fieldset className="mt-4 grid gap-3 lg:grid-cols-3">+ <legend className="sr-only">Mind bundle scopes</legend>+ {EXPORT_SCOPES.map(({ scope, icon: Icon, label, detail }) => {+ const id = `${idPrefix}-${scope}`;+ return (+ <div key={scope} className={`rounded border p-3 transition-colors ${selected.has(scope) ? 'border-port-accent bg-port-accent/5' : 'border-port-border bg-port-bg/30'}`}>+ <span className="flex items-start gap-3">+ <input id={id} type="checkbox" checked={selected.has(scope)} disabled={pending} onChange={(event) => toggle(scope, event.target.checked)} className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-50" />+ <span>+ <label htmlFor={id} className="flex cursor-pointer items-center gap-2 text-sm font-medium text-port-text"><Icon size={15} aria-hidden="true" /> {label}</label>+ <span className="mt-1 block text-xs text-port-text-muted">{detail}</span>+ </span>+ </span>+ </div>+ );+ })}+ </fieldset>++ {selected.has('memories') && (+ <p className="mt-3 rounded border border-port-warning/40 bg-port-warning/10 p-3 text-xs text-port-text">+ Protected memories quote things you told this Mind in private. Keep the file somewhere you would keep a password vault, and use a passphrase you do not reuse.+ </p>+ )}++ <div className="mt-4 grid gap-3 sm:grid-cols-2">+ <div>+ <label htmlFor={`${idPrefix}-passphrase`} className="flex items-center gap-2 text-xs font-medium text-port-text"><Lock size={14} aria-hidden="true" /> Passphrase</label>+ <input+ id={`${idPrefix}-passphrase`}+ type="password"+ value={passphrase}+ disabled={pending}+ autoComplete="new-password"+ onChange={(event) => { setPassphrase(event.target.value); setExported(null); }}+ className="mt-2 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text disabled:opacity-50"+ />+ <p className="mt-1 text-xs text-port-text-muted">At least {MIND_BUNDLE_PASSPHRASE_MIN_CHARS} characters. There is no recovery — lose it and the bundle cannot be opened.</p>+ </div>+ <div>+ <label htmlFor={`${idPrefix}-passphrase-confirm`} className="flex items-center gap-2 text-xs font-medium text-port-text"><Lock size={14} aria-hidden="true" /> Confirm passphrase</label>+ <input+ id={`${idPrefix}-passphrase-confirm`}+ type="password"+ value={confirmPassphrase}+ disabled={pending}+ autoComplete="new-password"+ onChange={(event) => { setConfirmPassphrase(event.target.value); setExported(null); }}+ className="mt-2 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text disabled:opacity-50"+ />+ {tooShort && <p role="alert" className="mt-1 text-xs text-port-warning">Passphrase is shorter than {MIND_BUNDLE_PASSPHRASE_MIN_CHARS} characters.</p>}+ {mismatch && <p role="alert" className="mt-1 text-xs text-port-warning">The two passphrases do not match.</p>}+ </div>+ </div>++ <div className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <p className="text-xs text-port-text-muted">{selected.size === 0 ? 'Select at least one scope to export.' : 'Everything you selected is sealed, or the export fails — a bundle never silently omits a scope.'}</p>+ <button+ type="button"+ onClick={exportBundle}+ disabled={pending || !ready}+ className="inline-flex min-h-10 items-center justify-center gap-2 rounded bg-port-accent px-4 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"+ >+ <Download size={16} className={pending ? 'animate-pulse' : ''} aria-hidden="true" /> {pending ? 'Sealing…' : 'Download sealed bundle'}+ </button>+ </div>+ </section>++ {error && (+ <Banner tone="error" title="Export refused">+ {error}+ </Banner>+ )}++ {exported && (+ <Banner tone="success" title="Bundle downloaded">+ Saved {exported.filename} with {exported.scopes.join(', ')}. Store it alongside your other secrets — the passphrase is the only way back in.+ </Banner>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/PersistentMindPortabilityPanel.test.jsx b/client/src/components/cos/PersistentMindPortabilityPanel.test.jsxnew file mode 100644index 0000000000..20fea3a724--- /dev/null+++ b/client/src/components/cos/PersistentMindPortabilityPanel.test.jsx@@ -0,0 +1,99 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++const api = vi.hoisted(() => ({ exportPersistentMindBundle: vi.fn() }));+vi.mock('../../services/api', () => api);++const downloadBlob = vi.hoisted(() => vi.fn());+vi.mock('../../lib/downloadBlob.js', () => ({ downloadBlob }));++const PersistentMindPortabilityPanel = (await import('./PersistentMindPortabilityPanel.jsx')).default;++const PASSPHRASE = 'an example bundle passphrase';++const fillPassphrase = async (user, value = PASSPHRASE) => {+ await user.type(screen.getByLabelText('Passphrase'), value);+ await user.type(screen.getByLabelText('Confirm passphrase'), value);+};++beforeEach(() => {+ vi.clearAllMocks();+ api.exportPersistentMindBundle.mockResolvedValue('portos-mind-bundle/1\n{}\nAAAA\nBBBB\n');+});++describe('PersistentMindPortabilityPanel', () => {+ it('defaults to profile + appearance, with protected memories opt-in', () => {+ render(<PersistentMindPortabilityPanel />);+ expect(screen.getByLabelText('Profile')).toBeChecked();+ expect(screen.getByLabelText('Appearance')).toBeChecked();+ expect(screen.getByLabelText('Protected memories')).not.toBeChecked();+ });++ it('keeps the download disabled until a confirmed passphrase is long enough', async () => {+ const user = userEvent.setup();+ render(<PersistentMindPortabilityPanel />);+ const button = screen.getByRole('button', { name: /Download sealed bundle/ });+ expect(button).toBeDisabled();++ await user.type(screen.getByLabelText('Passphrase'), 'too short');+ await user.type(screen.getByLabelText('Confirm passphrase'), 'too short');+ expect(await screen.findByText(/shorter than 12 characters/)).toBeInTheDocument();+ expect(button).toBeDisabled();++ await user.clear(screen.getByLabelText('Passphrase'));+ await user.clear(screen.getByLabelText('Confirm passphrase'));+ await user.type(screen.getByLabelText('Passphrase'), PASSPHRASE);+ await user.type(screen.getByLabelText('Confirm passphrase'), 'a different passphrase');+ expect(await screen.findByText(/do not match/)).toBeInTheDocument();+ expect(button).toBeDisabled();+ });++ it('exports only the selected scopes and hands the bytes to the browser download', async () => {+ const user = userEvent.setup();+ render(<PersistentMindPortabilityPanel />);+ await user.click(screen.getByLabelText('Appearance'));+ await user.click(screen.getByLabelText('Protected memories'));+ await fillPassphrase(user);+ await user.click(screen.getByRole('button', { name: /Download sealed bundle/ }));++ await waitFor(() => expect(api.exportPersistentMindBundle).toHaveBeenCalledWith({+ scopes: ['profile', 'memories'],+ passphrase: PASSPHRASE,+ }));+ expect(downloadBlob).toHaveBeenCalledWith(+ 'portos-mind-bundle/1\n{}\nAAAA\nBBBB\n',+ expect.stringMatching(/^portos-mind-.+\.portos-mind$/),+ );+ expect(await screen.findByText(/Bundle downloaded/)).toBeInTheDocument();+ });++ it('clears the passphrase fields once the bundle is sealed', async () => {+ const user = userEvent.setup();+ render(<PersistentMindPortabilityPanel />);+ await fillPassphrase(user);+ await user.click(screen.getByRole('button', { name: /Download sealed bundle/ }));++ await waitFor(() => expect(screen.getByLabelText('Passphrase')).toHaveValue(''));+ expect(screen.getByLabelText('Confirm passphrase')).toHaveValue('');+ });++ it('warns before a memories export that it quotes private conversation', async () => {+ const user = userEvent.setup();+ render(<PersistentMindPortabilityPanel />);+ expect(screen.queryByText(/quote things you told this Mind in private/)).not.toBeInTheDocument();+ await user.click(screen.getByLabelText('Protected memories'));+ expect(await screen.findByText(/quote things you told this Mind in private/)).toBeInTheDocument();+ });++ it('surfaces the server\'s named refusal inline, and downloads nothing', async () => {+ api.exportPersistentMindBundle.mockRejectedValue(new Error('Mind bundle export refused: could not read memories (memory backend is unavailable)'));+ const user = userEvent.setup();+ render(<PersistentMindPortabilityPanel />);+ await fillPassphrase(user);+ await user.click(screen.getByRole('button', { name: /Download sealed bundle/ }));++ expect(await screen.findByText(/could not read memories/)).toBeInTheDocument();+ expect(downloadBlob).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsxindex 7196c12935..a8469c925e 100644--- a/client/src/components/cos/tabs/MindTab.jsx+++ b/client/src/components/cos/tabs/MindTab.jsx@@ -17,6 +17,7 @@ import FilePickerButton from '../../ui/FilePickerButton';import TabPills from '../../ui/TabPills';import PersistentMindContextPanel from '../PersistentMindContextPanel';import PersistentMindMaintenancePanel from '../PersistentMindMaintenancePanel';+import PersistentMindPortabilityPanel from '../PersistentMindPortabilityPanel';import PersistentMindProfileControls from '../PersistentMindProfileControls';import PersistentMindRoutePanel from '../PersistentMindRoutePanel';import PersistentMindRuntimePanel, { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';@@ -1049,6 +1050,11 @@ export default function MindTab() {onSaved={(profile) => setMind((current) => current ? { ...current, profile } : current)}onSavingChange={setProfileSaving}/>+ <div className="mt-6 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-port-text">Portability</h3>+ <p className="mt-1 mb-3 text-xs text-port-text-muted">Carry this Mind to another PortOS install as one encrypted file you download and keep.</p>+ <PersistentMindPortabilityPanel />+ </div>{!state?.started && (<div className="mt-4 flex flex-col gap-2 border-t border-port-border pt-4 sm:flex-row sm:items-center sm:justify-between"><p className="text-xs text-port-text-muted">{setupSaving ? 'Saving persistent mind settings…' : profileReady ? 'The saved AI profile is ready.' : 'Enable the profile and select both an AI provider and model to start.'}</p>diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex b568cbf1eb..990c04de22 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -116,6 +116,13 @@ export const updatePersistentMindMemory = (memoryId, body, options = {}) => requexport const cleanupPersistentMind = (body, options = {}) => request('/cos/mind/cleanup', {method: 'POST', body: JSON.stringify(body), ...options,});+// Seal the Mind into a portable bundle (#7621). The response is the sealed file+// itself, not JSON — `responseType: 'text'` hands the caller the bytes to save.+// `silent` because the panel renders its own inline refusal: the server's+// "could not read <scope>" reason is the whole point of the failure.+export const exportPersistentMindBundle = (body, options = {}) => request('/cos/mind/bundle/export', {+ method: 'POST', body: JSON.stringify(body), responseType: 'text', silent: true, ...options,+});// Chief of Staffexport const getCosStatus = () => request('/cos');diff --git a/server/lib/README.md b/server/lib/README.mdindex 6a4e250911..db00d65301 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -70,6 +70,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. || `persistentMindPlaybook.js` | Continuous-play / explore→interact→reflect→invent Persistent Mind operating modes and prompt framing. Pure. || `persistentMindPlaybookPhase.js` | Maturity-aware continuous-play phase picker (explore/construct/maintain/coordinate) from bounded Eidoverse world signals — density, recent failure rate, active peers. Pure. |+| `mindBundleCrypto.js` | Persistent Mind portable-bundle container (#7621) — `sealMindBundle` / `openMindBundle` / `readMindBundleHeader`, scrypt-from-passphrase + AES-256-GCM with the cleartext header as AAD, plus the scope vocabulary (`PERSISTENT_MIND_BUNDLE_SCOPES`) and passphrase floor. Passphrase-derived, never `PRIVACY_VAULT_KEY`: that key is machine-bound and a bundle sealed with it could not open on the destination install. || `mindLocalContextClamp.js` | RAM/GPU safety ceilings for mind-driven local `numCtx` adjustments (CPU-only tiers, free-RAM + PortOS headroom). Pure. || `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields, queue count, and the derived next wake time; drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. || `persistentMindThinkingPresets.js` | Also owns bounded self-thinking request schemas, durable request normalization, and fixed switching limits. Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference. |diff --git a/server/lib/index.js b/server/lib/index.jsindex d1801f9541..c9e6458ad6 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -331,6 +331,7 @@ export * from './persistentMindMemory.js';export * from './persistentMindPrompt.js';export * from './persistentMindPlaybook.js';export * from './persistentMindPlaybookPhase.js';+export * from './mindBundleCrypto.js';export * from './mindLocalContextClamp.js';export * from './persistentMindPublic.js';export * from './persistentMindThinkingPresets.js';diff --git a/server/lib/mindBundleCrypto.js b/server/lib/mindBundleCrypto.jsnew file mode 100644index 0000000000..1bc4832fe6--- /dev/null+++ b/server/lib/mindBundleCrypto.js@@ -0,0 +1,244 @@+/**+ * Mind bundle container — passphrase-sealed, install-agnostic AES-256-GCM.+ *+ * This is the format half of Persistent Mind portability (#7621, epic #7620):+ * one file the user downloads on the install their Mind grew up on and opens on+ * another one. It deliberately does NOT reuse `vaultCrypto.js` key resolution —+ * `PRIVACY_VAULT_KEY` is machine-bound, so a bundle sealed with it could never+ * be opened on the destination, which is the entire point. The cipher handling+ * is the same shape; only the key source differs: a `scrypt` key derived from+ * the user's passphrase and a per-bundle random salt.+ *+ * File layout (UTF-8 text, four newline-separated lines):+ *+ * 1 portos-mind-bundle/<containerVersion>+ * 2 <header JSON, one line, CLEARTEXT>+ * 3 <base64 ciphertext>+ * 4 <base64 GCM auth tag>+ *+ * Lines 1–2 are cleartext so a destination install can refuse a bundle it does+ * not understand BEFORE asking the user for a passphrase, and so line 2's exact+ * bytes can serve as the GCM additional-authenticated-data: editing the declared+ * scopes, KDF parameters, or manifest makes the open fail authentication rather+ * than silently changing what the bundle claims to be.+ *+ * What the cleartext header deliberately does NOT carry: per-entry plaintext+ * digests. The issue sketched them as cleartext, but a SHA-256 over+ * `profile.json` is a confirmation oracle over a small guess space (a chosen+ * name, a provider id, a model id) — anyone holding the file could brute-force+ * the Mind's identity without ever knowing the passphrase. Refusal only needs+ * versions, KDF parameters, scopes, and entry names/sizes; per-entry digests+ * are integrity checks for AFTER the open, so they live inside the ciphertext.+ *+ * Forward compatibility is by refusal, never by guessing: an unknown container+ * or payload version throws a named reason instead of applying the parts this+ * install happens to recognize.+ */++import { createCipheriv, createDecipheriv, createHash, randomBytes, scrypt, timingSafeEqual } from 'crypto';+import { promisify } from 'util';++const scryptAsync = promisify(scrypt);++export const MIND_BUNDLE_MAGIC = 'portos-mind-bundle';+export const MIND_BUNDLE_CONTAINER_VERSION = 1;+export const MIND_BUNDLE_PAYLOAD_VERSION = 1;+export const MIND_BUNDLE_FILE_EXTENSION = '.portos-mind';++/**+ * The scope vocabulary is part of the container contract — it is declared in the+ * cleartext header, so a destination can refuse a scope it cannot apply. Memory+ * export is opt-in (epic #7620): protected memories quote private conversation.+ */+export const PERSISTENT_MIND_BUNDLE_SCOPES = Object.freeze(['profile', 'avatar', 'memories']);+export const DEFAULT_PERSISTENT_MIND_BUNDLE_SCOPES = Object.freeze(['profile', 'avatar']);++/**+ * A short passphrase makes the scrypt work factor irrelevant. 12 characters is+ * the floor; the UI says so before the field is ever filled in.+ */+export const MIND_BUNDLE_PASSPHRASE_MIN_CHARS = 12;+export const MIND_BUNDLE_PASSPHRASE_MAX_CHARS = 512;++const CIPHER = 'aes-256-gcm';+const IV_BYTES = 12;+const TAG_BYTES = 16;+const SALT_BYTES = 16;+const KEY_BYTES = 32;++/**+ * scrypt cost, recorded in the cleartext header so a bundle sealed by a future+ * install that raises them still opens here (the parameters travel with the+ * file) while a bundle declaring absurd ones is refused rather than executed.+ */+export const MIND_BUNDLE_KDF = Object.freeze({ name: 'scrypt', N: 32_768, r: 8, p: 1, keyBytes: KEY_BYTES });+// 128 * N * r, with headroom. Node's 32 MB default is below what N=32768 needs.+const SCRYPT_MAXMEM = 96 * 1024 * 1024;+// Refuse a header asking for more work than the honest ceiling above: an+// attacker-supplied N is a denial-of-service knob, not a compatibility knob.+const MAX_ACCEPTED_KDF_N = 1_048_576;++const sha256Hex = (buffer) => createHash('sha256').update(buffer).digest('hex');++function requirePassphrase(passphrase) {+ if (typeof passphrase !== 'string' || passphrase.length < MIND_BUNDLE_PASSPHRASE_MIN_CHARS) {+ throw new Error(`Mind bundle passphrase must be at least ${MIND_BUNDLE_PASSPHRASE_MIN_CHARS} characters`);+ }+ if (passphrase.length > MIND_BUNDLE_PASSPHRASE_MAX_CHARS) {+ throw new Error(`Mind bundle passphrase must be at most ${MIND_BUNDLE_PASSPHRASE_MAX_CHARS} characters`);+ }+ return passphrase;+}++function deriveBundleKey(passphrase, salt, kdf) {+ if (kdf.name !== 'scrypt') throw new Error(`Unsupported mind bundle key derivation "${kdf.name}"`);+ if (!Number.isInteger(kdf.N) || kdf.N < 2 || kdf.N > MAX_ACCEPTED_KDF_N+ || !Number.isInteger(kdf.r) || kdf.r < 1 || kdf.r > 32+ || !Number.isInteger(kdf.p) || kdf.p < 1 || kdf.p > 16+ || kdf.keyBytes !== KEY_BYTES) {+ throw new Error('Mind bundle declares key-derivation parameters this install will not run');+ }+ return scryptAsync(passphrase, salt, KEY_BYTES, {+ N: kdf.N, r: kdf.r, p: kdf.p, maxmem: SCRYPT_MAXMEM,+ });+}++const normalizeEntry = (entry) => {+ if (!entry || typeof entry.name !== 'string' || !entry.name) throw new Error('Mind bundle entry requires a name');+ const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(String(entry.data), 'utf8');+ return { name: entry.name, data };+};++/**+ * Seal entries into one bundle string.+ *+ * `entries` are `{ name, data }` where data is a Buffer or a string — the+ * container is byte-oriented so an avatar image drops in beside the JSON+ * documents without a second code path.+ */+export async function sealMindBundle({ entries, scopes, passphrase, createdAt = new Date().toISOString() }) {+ requirePassphrase(passphrase);+ const normalized = (Array.isArray(entries) ? entries : []).map(normalizeEntry);+ if (normalized.length === 0) throw new Error('Mind bundle requires at least one entry');+ const names = normalized.map((entry) => entry.name);+ if (new Set(names).size !== names.length) throw new Error('Mind bundle entry names must be unique');++ const salt = randomBytes(SALT_BYTES);+ const iv = randomBytes(IV_BYTES);+ const key = await deriveBundleKey(passphrase, salt, MIND_BUNDLE_KDF);++ // Per-entry digests live INSIDE the ciphertext (see the module header).+ const payload = Buffer.from(JSON.stringify({+ payloadVersion: MIND_BUNDLE_PAYLOAD_VERSION,+ entries: normalized.map((entry) => ({+ name: entry.name,+ bytes: entry.data.length,+ sha256: sha256Hex(entry.data),+ dataB64: entry.data.toString('base64'),+ })),+ }), 'utf8');++ const header = {+ magic: MIND_BUNDLE_MAGIC,+ containerVersion: MIND_BUNDLE_CONTAINER_VERSION,+ payloadVersion: MIND_BUNDLE_PAYLOAD_VERSION,+ createdAt,+ scopes: [...(Array.isArray(scopes) ? scopes : [])],+ kdf: { ...MIND_BUNDLE_KDF, saltB64: salt.toString('base64') },+ cipher: { name: CIPHER, ivB64: iv.toString('base64') },+ manifest: normalized.map((entry) => ({ name: entry.name, bytes: entry.data.length })),+ };+ const headerLine = JSON.stringify(header);++ const cipher = createCipheriv(CIPHER, key, iv);+ // The cleartext header is authenticated, so a reader cannot be lied to about+ // the scopes or KDF parameters without failing the open outright.+ cipher.setAAD(Buffer.from(headerLine, 'utf8'));+ const ciphertext = Buffer.concat([cipher.update(payload), cipher.final()]);+ const tag = cipher.getAuthTag();++ return [+ `${MIND_BUNDLE_MAGIC}/${MIND_BUNDLE_CONTAINER_VERSION}`,+ headerLine,+ ciphertext.toString('base64'),+ tag.toString('base64'),+ '',+ ].join('\n');+}++const isPlainRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);++/**+ * Parse and validate the cleartext preamble WITHOUT a passphrase, so a+ * destination install can refuse a bundle it does not understand before asking+ * the user for one. Returns `{ header, headerLine, ciphertext, tag }`.+ */+export function readMindBundleHeader(text) {+ if (typeof text !== 'string' || !text.trim()) throw new Error('Mind bundle is empty');+ const [magicLine, headerLine, ciphertextB64, tagB64] = text.split('\n');+ const [magic, containerVersion] = String(magicLine || '').split('/');+ if (magic !== MIND_BUNDLE_MAGIC) throw new Error('This file is not a PortOS Mind bundle');+ if (Number(containerVersion) !== MIND_BUNDLE_CONTAINER_VERSION) {+ throw new Error(`Mind bundle container version ${containerVersion} is not supported by this install (expected ${MIND_BUNDLE_CONTAINER_VERSION})`);+ }+ if (!headerLine || !ciphertextB64 || !tagB64) throw new Error('Mind bundle is truncated or damaged');++ const header = JSON.parse(headerLine);+ if (!isPlainRecord(header) || header.magic !== MIND_BUNDLE_MAGIC+ || header.containerVersion !== MIND_BUNDLE_CONTAINER_VERSION) {+ throw new Error('Mind bundle header does not describe a PortOS Mind bundle');+ }+ if (header.payloadVersion !== MIND_BUNDLE_PAYLOAD_VERSION) {+ throw new Error(`Mind bundle payload version ${header.payloadVersion} is not supported by this install (expected ${MIND_BUNDLE_PAYLOAD_VERSION})`);+ }+ if (!Array.isArray(header.scopes) || header.scopes.length === 0+ || header.scopes.some((scope) => !PERSISTENT_MIND_BUNDLE_SCOPES.includes(scope))) {+ throw new Error('Mind bundle declares a scope this install does not understand');+ }+ if (!isPlainRecord(header.cipher) || header.cipher.name !== CIPHER || typeof header.cipher.ivB64 !== 'string') {+ throw new Error('Mind bundle declares a cipher this install does not support');+ }+ if (!isPlainRecord(header.kdf) || typeof header.kdf.saltB64 !== 'string') {+ throw new Error('Mind bundle is missing its key-derivation parameters');+ }+ if (!Array.isArray(header.manifest)) throw new Error('Mind bundle is missing its entry manifest');++ const ciphertext = Buffer.from(ciphertextB64, 'base64');+ const tag = Buffer.from(tagB64, 'base64');+ const iv = Buffer.from(header.cipher.ivB64, 'base64');+ if (tag.length !== TAG_BYTES || iv.length !== IV_BYTES || ciphertext.length === 0) {+ throw new Error('Mind bundle is truncated or damaged');+ }+ return { header, headerLine, ciphertext, tag, iv };+}++/**+ * Open a sealed bundle. Throws on an unsupported version, a damaged file, a+ * wrong passphrase, or any tampering — the GCM tag covers both the ciphertext+ * and the cleartext header, so there is no partial-trust path out of here.+ */+export async function openMindBundle({ text, passphrase }) {+ requirePassphrase(passphrase);+ const { header, headerLine, ciphertext, tag, iv } = readMindBundleHeader(text);+ const key = await deriveBundleKey(passphrase, Buffer.from(header.kdf.saltB64, 'base64'), header.kdf);++ const decipher = createDecipheriv(CIPHER, key, iv);+ decipher.setAAD(Buffer.from(headerLine, 'utf8'));+ decipher.setAuthTag(tag);+ const payload = JSON.parse(Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'));++ if (!isPlainRecord(payload) || payload.payloadVersion !== MIND_BUNDLE_PAYLOAD_VERSION || !Array.isArray(payload.entries)) {+ throw new Error('Mind bundle payload is not in a shape this install understands');+ }+ const entries = payload.entries.map((entry) => {+ const data = Buffer.from(entry.dataB64, 'base64');+ const digest = Buffer.from(sha256Hex(data), 'utf8');+ const declared = Buffer.from(String(entry.sha256), 'utf8');+ if (digest.length !== declared.length || !timingSafeEqual(digest, declared)) {+ throw new Error(`Mind bundle entry "${entry.name}" failed its integrity check`);+ }+ return { name: entry.name, data };+ });+ return { header, entries };+}+diff --git a/server/lib/mindBundleCrypto.test.js b/server/lib/mindBundleCrypto.test.jsnew file mode 100644index 0000000000..e7df55b2bb--- /dev/null+++ b/server/lib/mindBundleCrypto.test.js@@ -0,0 +1,141 @@+import { describe, it, expect } from 'vitest';+import {+ MIND_BUNDLE_MAGIC,+ MIND_BUNDLE_PASSPHRASE_MIN_CHARS,+ openMindBundle,+ readMindBundleHeader,+ sealMindBundle,+} from './mindBundleCrypto.js';++// Obviously-fake fixture. Never a record read out of a live install.+const PASSPHRASE = 'correct horse battery staple';+const ENTRIES = [+ { name: 'profile.json', data: JSON.stringify({ chosenName: 'Example Mind', soul: { identity: 'I am an example.' } }) },+ { name: 'memories.json', data: JSON.stringify({ memories: [{ type: 'fact', content: 'The example user prefers mornings.' }] }) },+];++const seal = (overrides = {}) => sealMindBundle({+ entries: ENTRIES, scopes: ['profile', 'memories'], passphrase: PASSPHRASE, ...overrides,+});++describe('mindBundleCrypto', () => {+ it('round-trips entries through seal and open', async () => {+ const opened = await openMindBundle({ text: await seal(), passphrase: PASSPHRASE });+ expect(opened.header.scopes).toEqual(['profile', 'memories']);+ expect(opened.entries.map((entry) => entry.name)).toEqual(['profile.json', 'memories.json']);+ expect(JSON.parse(opened.entries[0].data.toString('utf8')).chosenName).toBe('Example Mind');+ });++ it('preserves arbitrary bytes, so a future image entry needs no second path', async () => {+ const data = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff, 0xfe]);+ const text = await sealMindBundle({ entries: [{ name: 'avatar.png', data }], scopes: ['avatar'], passphrase: PASSPHRASE });+ const opened = await openMindBundle({ text, passphrase: PASSPHRASE });+ expect(opened.entries[0].data.equals(data)).toBe(true);+ });++ it('refuses a wrong passphrase', async () => {+ const text = await seal();+ await expect(openMindBundle({ text, passphrase: 'a different passphrase' })).rejects.toThrow();+ });++ it('refuses a passphrase shorter than the floor, at seal and at open', async () => {+ await expect(seal({ passphrase: 'short' })).rejects.toThrow(/at least 12 characters/);+ const text = await seal();+ await expect(openMindBundle({ text, passphrase: 'short' })).rejects.toThrow(/at least 12 characters/);+ expect(MIND_BUNDLE_PASSPHRASE_MIN_CHARS).toBe(12);+ });++ it('fails GCM authentication when a single ciphertext byte is mutated', async () => {+ const lines = (await seal()).split('\n');+ const ciphertext = Buffer.from(lines[2], 'base64');+ ciphertext[0] ^= 0x01;+ lines[2] = ciphertext.toString('base64');+ await expect(openMindBundle({ text: lines.join('\n'), passphrase: PASSPHRASE })).rejects.toThrow();+ });++ it('fails authentication when the CLEARTEXT header is edited', async () => {+ // The header is the AAD, so lying about the declared scopes is detected+ // rather than silently believed.+ const lines = (await seal()).split('\n');+ const header = JSON.parse(lines[1]);+ header.scopes = ['profile'];+ lines[1] = JSON.stringify(header);+ await expect(openMindBundle({ text: lines.join('\n'), passphrase: PASSPHRASE })).rejects.toThrow();+ });++ it('exposes versions, KDF params, scopes and entry names WITHOUT a passphrase', async () => {+ const { header } = readMindBundleHeader(await seal());+ expect(header.magic).toBe(MIND_BUNDLE_MAGIC);+ expect(header.containerVersion).toBe(1);+ expect(header.kdf.name).toBe('scrypt');+ expect(header.kdf.saltB64).toEqual(expect.any(String));+ expect(header.manifest.map((entry) => entry.name)).toEqual(['profile.json', 'memories.json']);+ });++ it('never puts a plaintext entry digest in the cleartext header', async () => {+ // A SHA-256 over profile.json would be a confirmation oracle over a small+ // guess space (a chosen name, a provider id) for anyone holding the file.+ const text = await seal();+ const { header } = readMindBundleHeader(text);+ expect(JSON.stringify(header)).not.toMatch(/sha256/i);+ const opened = await openMindBundle({ text, passphrase: PASSPHRASE });+ // …but the digests DO exist inside, as the post-open integrity check.+ const tampered = text.split('\n');+ expect(opened.entries).toHaveLength(2);+ expect(tampered[1]).not.toMatch(/[0-9a-f]{64}/);+ });++ it('refuses an unknown container version by name, before asking for a passphrase', async () => {+ const lines = (await seal()).split('\n');+ lines[0] = `${MIND_BUNDLE_MAGIC}/99`;+ expect(() => readMindBundleHeader(lines.join('\n'))).toThrow(/container version 99 is not supported/);+ });++ it('refuses an unknown payload version rather than applying what it recognizes', async () => {+ const lines = (await seal()).split('\n');+ const header = JSON.parse(lines[1]);+ header.payloadVersion = 99;+ lines[1] = JSON.stringify(header);+ expect(() => readMindBundleHeader(lines.join('\n'))).toThrow(/payload version 99 is not supported/);+ });++ it('refuses a scope vocabulary this install does not understand', async () => {+ const lines = (await seal()).split('\n');+ const header = JSON.parse(lines[1]);+ header.scopes = ['profile', 'brain-dump'];+ lines[1] = JSON.stringify(header);+ expect(() => readMindBundleHeader(lines.join('\n'))).toThrow(/scope this install does not understand/);+ });++ it('refuses a file that is not a Mind bundle, and a truncated one', () => {+ expect(() => readMindBundleHeader('{"hello":"world"}')).toThrow(/not a PortOS Mind bundle/);+ expect(() => readMindBundleHeader('')).toThrow(/empty/);+ expect(() => readMindBundleHeader(`${MIND_BUNDLE_MAGIC}/1\n{}\n`)).toThrow(/truncated or damaged/);+ });++ it('refuses key-derivation parameters it will not run', async () => {+ const lines = (await seal()).split('\n');+ const header = JSON.parse(lines[1]);+ header.kdf = { ...header.kdf, N: 1_073_741_824 };+ lines[1] = JSON.stringify(header);+ await expect(openMindBundle({ text: lines.join('\n'), passphrase: PASSPHRASE }))+ .rejects.toThrow(/key-derivation parameters this install will not run/);+ });++ it('uses a fresh salt and IV per bundle, so two seals of one Mind never match', async () => {+ const [a, b] = await Promise.all([seal(), seal()]);+ const headerA = JSON.parse(a.split('\n')[1]);+ const headerB = JSON.parse(b.split('\n')[1]);+ expect(headerA.kdf.saltB64).not.toBe(headerB.kdf.saltB64);+ expect(headerA.cipher.ivB64).not.toBe(headerB.cipher.ivB64);+ expect(a.split('\n')[2]).not.toBe(b.split('\n')[2]);+ });++ it('refuses duplicate entry names and an empty bundle', async () => {+ await expect(sealMindBundle({ entries: [], scopes: ['profile'], passphrase: PASSPHRASE })).rejects.toThrow(/at least one entry/);+ await expect(sealMindBundle({+ entries: [{ name: 'profile.json', data: '{}' }, { name: 'profile.json', data: '{}' }],+ scopes: ['profile'], passphrase: PASSPHRASE,+ })).rejects.toThrow(/unique/);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 171bb1a45d..2ee984e3e2 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -31,6 +31,7 @@ import {import { isPlainObject } from './objects.js';import { isValidCronExpression, isCronShaped } from './cronValidation.js';import { USER_ACTION_ACTORS, USER_ACTION_TYPES } from './userActionTypes.js';+import { MIND_BUNDLE_PASSPHRASE_MAX_CHARS, MIND_BUNDLE_PASSPHRASE_MIN_CHARS, PERSISTENT_MIND_BUNDLE_SCOPES } from './mindBundleCrypto.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total// pixels. Mirror the ceiling for every image-gen route. Local mflux can@@ -2313,3 +2314,28 @@ export const providerPresetCreateSchema = z.object({/** `PUT /api/providers/harnesses/:id` — flip one harness's enablement. */export const harnessEnablementUpdateSchema = z.object({ enabled: z.boolean() }).strict();export const harnessIdParamSchema = z.enum(PROVIDER_HARNESS_IDS);++// =============================================================================+// PERSISTENT MIND BUNDLE (server/routes/cosMindRoutes.js)+// =============================================================================++/**+ * `POST /api/cos/mind/bundle/export` (#7621) — seal the Mind into a downloadable,+ * passphrase-encrypted bundle.+ *+ * The scope vocabulary and passphrase floor come from `mindBundleCrypto.js`, the+ * module that owns the container contract, so the route, the sealer, and the UI+ * cannot drift apart on what a bundle may declare. The passphrase is bounded but+ * deliberately unconstrained in composition: it is a user-chosen secret, and a+ * validation failure here must never echo it (`validateRequest` reports paths+ * and messages, never values).+ */+export const mindBundleExportSchema = z.object({+ scopes: z.array(z.enum(PERSISTENT_MIND_BUNDLE_SCOPES))+ .min(1)+ .max(PERSISTENT_MIND_BUNDLE_SCOPES.length)+ .refine((scopes) => new Set(scopes).size === scopes.length, 'bundle scopes must be unique'),+ passphrase: z.string()+ .min(MIND_BUNDLE_PASSPHRASE_MIN_CHARS, `Passphrase must be at least ${MIND_BUNDLE_PASSPHRASE_MIN_CHARS} characters`)+ .max(MIND_BUNDLE_PASSPHRASE_MAX_CHARS),+}).strict();diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex 71f1b305a6..b698620cd5 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -32,7 +32,7 @@ import { composePersistentMindInstructions, normalizePersistentMindPlaybook, PERimport { resolvePersistentMindPlaybookPhase } from '../services/persistentMindPlaybookSignals.js';import { publicPersistentMindState } from '../lib/persistentMindPublic.js';import { publicPersistentMindTurnExecutions } from '../lib/persistentMindTrajectory.js';-import { validateRequest } from '../lib/validation.js';+import { mindBundleExportSchema, validateRequest } from '../lib/validation.js';import { readPersistentMindEvents, readPersistentMindHistory } from '../services/agentRunEventLog.js';import { loadState } from '../services/cosState.js';import {@@ -48,6 +48,7 @@ import {import { getProviderById } from '../services/providers.js';import { persistentMindHarnessInfo } from '../services/persistentMindAdapter.js';import { cleanupPersistentMind } from '../services/persistentMindMaintenance.js';+import { exportPersistentMindBundle } from '../services/persistentMindBundle.js';import { resolvePersistentMindImageCapability } from '../services/persistentMindImageCapability.js';import { readPersistentMindTaskCatalog } from '../services/persistentMindTaskCapability.js';import { inspectPersistentMindRuntime } from '../services/persistentMindRuntime.js';@@ -345,6 +346,25 @@ router.post('/mind/cleanup', asyncHandler(async (req, res) => {res.json({ ...result, state: publicPersistentMindState(state) });}));+/**+ * Seal the Mind into a downloadable, passphrase-encrypted bundle (#7621).+ *+ * Machine-local and user-initiated: the bytes are streamed straight back to the+ * caller and never written to disk, never logged, and never offered to a peer.+ * The passphrase is used once, inside the sealer, and appears in no log line+ * and no error body (`validateRequest` reports paths, not values).+ */+router.post('/mind/bundle/export', asyncHandler(async (req, res) => {+ const { scopes, passphrase } = validateRequest(mindBundleExportSchema, req.body);+ const { bundle, filename } = await exportPersistentMindBundle({ scopes, passphrase });+ res.setHeader('Content-Type', 'application/octet-stream');+ res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);+ // A sealed identity must not sit in a shared/proxy cache on its way to the+ // browser, even though the bytes are encrypted.+ res.setHeader('Cache-Control', 'no-store');+ res.send(bundle);+}));+router.post('/mind/attachments', asyncHandler(async (req, res) => {const input = validateRequest(attachmentUploadSchema, req.body);res.status(201).json(requireSuccess(await createPersistentMindAttachment(input)));diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex 2065883e0d..f84be050b6 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -612,4 +612,31 @@ describe('persistent mind routes', () => {expect(mocks.appendPersistentMindAnnotation).not.toHaveBeenCalled();expect(mocks.promotePersistentMindMemory).not.toHaveBeenCalled();});++ it('serves the sealed bundle as a download and refuses a short passphrase', async () => {+ expect((await post('/mind/bundle/export', { scopes: ['profile'], passphrase: 'short' })).status).toBe(400);+ const res = await post('/mind/bundle/export', { scopes: ['profile'], passphrase: 'an example bundle passphrase' });+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toContain('application/octet-stream');+ expect(res.headers['content-disposition']).toMatch(/^attachment; filename="portos-mind-.+\.portos-mind"$/);+ expect(res.headers['cache-control']).toBe('no-store');+ const [magicLine, headerLine] = res.text.split('\n');+ expect(magicLine).toBe('portos-mind-bundle/1');+ expect(JSON.parse(headerLine).scopes).toEqual(['profile']);+ // The response body is the sealed file; nothing readable rides along with it.+ expect(res.text).not.toContain('Resident mind');+ });++ it('refuses an unknown scope rather than exporting the ones it recognizes', async () => {+ const res = await post('/mind/bundle/export', { scopes: ['profile', 'everything'], passphrase: 'an example bundle passphrase' });+ expect(res.status).toBe(400);+ });++ it('refuses the whole export when a selected scope cannot be read', async () => {+ mocks.readPersistentMindMemories.mockRejectedValue(new Error('memory backend is unavailable'));+ const res = await post('/mind/bundle/export', { scopes: ['profile', 'memories'], passphrase: 'an example bundle passphrase' });+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('MIND_BUNDLE_SCOPE_UNREADABLE');+ expect(res.body.error).toContain('memories');+ });});diff --git a/server/services/persistentMindBundle.js b/server/services/persistentMindBundle.jsnew file mode 100644index 0000000000..372206d885--- /dev/null+++ b/server/services/persistentMindBundle.js@@ -0,0 +1,177 @@+/**+ * Persistent Mind bundle export — seal the Mind's *meaning* into one+ * passphrase-encrypted file the user can carry to another install (#7621,+ * epic #7620). Machine-local and user-initiated end to end: nothing here runs+ * on a schedule, calls a provider, or crosses the federation layer.+ *+ * What goes in is decided by scope, and every scope is deliberately narrow.+ * The bundle carries no database ids, no `sourceTaskId`/`sourceAgentId`, no+ * embeddings, no filesystem paths, no hostnames, no peer records, no+ * credentials, and no raw conversation history or rollup text — those are+ * either the `AGENTS.md` Sensitive Data & Privacy categories or install-bound+ * values that would make the bundle un-openable somewhere else.+ *+ * Two exclusions are judgement calls worth naming:+ *+ * - **Capability grants** (`persistentMindCapabilities`) stay home. They are+ * authority — "may file issues", "may create tasks" — not preference. A+ * bundle that carried them would let an import quietly widen what a Mind may+ * do on the destination install.+ * - **`profile.enabled` stays home.** Importing a Mind must never be the thing+ * that starts one. The destination user starts it themselves.+ * - **Thinking presets stay home.** They bookmark provider/model routes that+ * exist on THIS machine's registry; the model policy the epic asks for is the+ * home profile, which travels.+ *+ * Refusal, not partial export: if a selected scope cannot be read, the whole+ * export fails with a named reason. A bundle must never silently omit a scope+ * the user asked for — the user would find out on the destination install,+ * after the source install is gone.+ */++import { ServerError } from '../lib/errorHandler.js';+import { AVATAR_STYLE_IDS } from '../lib/avatarStyles.js';+import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';+import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';+import { normalizePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';+import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';+import {+ DEFAULT_PERSISTENT_MIND_BUNDLE_SCOPES,+ MIND_BUNDLE_FILE_EXTENSION,+ PERSISTENT_MIND_BUNDLE_SCOPES,+ sealMindBundle,+} from '../lib/mindBundleCrypto.js';+import { loadState } from './cosState.js';+import { readPersistentMindMemories, readPersistentMindName } from './persistentMindContext.js';++export const MIND_BUNDLE_ENTRY_NAMES = Object.freeze({+ profile: 'profile.json',+ avatar: 'avatar.json',+ memories: 'memories.json',+});++/**+ * `readPersistentMindMemories` returns at most this many records. Protected+ * memories sort ahead of ordinary ones, so the protected set is complete unless+ * it fills the page — at which point the export refuses rather than shipping a+ * truncated identity (see `collectMemories`).+ */+const MIND_MEMORY_PAGE_LIMIT = 100;++/** Protected tiers only. `standard` memories are bulk-cleanable noise and stay home. */+const EXPORTABLE_PROTECTIONS = new Set(['core-identity', 'important']);++async function collectProfile() {+ const root = await loadState();+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);+ const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);+ const playbook = normalizePersistentMindPlaybook(root.config?.persistentMindPlaybook);+ const chosenName = await readPersistentMindName(PERSISTENT_MIND_ID);+ return {+ // The Mind's own name, not the machine's and not the user's.+ chosenName: chosenName || null,+ soul: { identity: prompt.identity, instructions: prompt.instructions },+ playbook: { mode: playbook.mode, customInstructions: playbook.customInstructions },+ // Model policy travels; whether it resolves is the destination's problem to+ // surface, not this install's to pre-decide.+ modelPolicy: {+ providerId: profile.providerId || null,+ model: profile.model || null,+ effort: profile.effort || null,+ thinkingInterface: profile.thinkingInterface,+ wakeIntervalMinutes: profile.wakeIntervalMinutes,+ },+ };+}++/**+ * The Mind's presentation. PortOS has no per-Mind avatar image today — the+ * Mind's face is the CoS avatar STYLE, a bundled-vocabulary id. The container+ * is byte-oriented, so the day image bytes exist they become a second entry+ * under this same scope without a new code path.+ */+async function collectAvatar() {+ const root = await loadState();+ const style = root.config?.avatarStyle;+ return { style: AVATAR_STYLE_IDS.includes(style) ? style : null };+}++async function collectMemories() {+ const memories = await readPersistentMindMemories(PERSISTENT_MIND_ID);+ const protectedMemories = memories.filter((memory) => EXPORTABLE_PROTECTIONS.has(memory.protection));+ if (protectedMemories.length >= MIND_MEMORY_PAGE_LIMIT) {+ // The reader is paged; a full page of protected records means there may be+ // more behind it, and a silently short memories scope is exactly the+ // failure this export refuses to produce.+ throw new Error(`this Mind has at least ${MIND_MEMORY_PAGE_LIMIT} protected memories, more than one bundle page can carry without dropping some`);+ }+ return {+ // Meaning only: no ids, no source agent/task, no embeddings, no importance+ // ranking computed against this install's other records.+ memories: protectedMemories.map((memory) => ({+ type: memory.type,+ content: memory.content,+ createdAt: memory.createdAt ? new Date(memory.createdAt).toISOString() : null,+ protection: memory.protection,+ })),+ };+}++const COLLECTORS = Object.freeze({+ profile: collectProfile,+ avatar: collectAvatar,+ memories: collectMemories,+});++/** Stable, de-duplicated scope order so two exports of the same selection match. */+export function normalizeMindBundleScopes(scopes) {+ const requested = new Set(Array.isArray(scopes) && scopes.length > 0 ? scopes : DEFAULT_PERSISTENT_MIND_BUNDLE_SCOPES);+ return PERSISTENT_MIND_BUNDLE_SCOPES.filter((scope) => requested.has(scope));+}++/**+ * Read every selected scope, refusing the whole export if any one of them+ * fails. `allSettled` rather than a bail-on-first-rejection race so the refusal+ * names every scope that could not be read, not just the fastest to fail.+ */+export async function collectPersistentMindBundleEntries(scopes) {+ const selected = normalizeMindBundleScopes(scopes);+ if (selected.length === 0) throw new ServerError('Select at least one scope to export', { status: 400, code: 'MIND_BUNDLE_NO_SCOPES' });++ const results = await Promise.allSettled(selected.map((scope) => COLLECTORS[scope]()));+ const failures = results+ .map((result, index) => (result.status === 'rejected' ? `${selected[index]} (${result.reason?.message || 'unknown error'})` : null))+ .filter(Boolean);+ if (failures.length > 0) {+ throw new ServerError(`Mind bundle export refused: could not read ${failures.join(', ')}. Nothing was exported — a bundle never silently omits a scope you selected.`, {+ status: 409,+ code: 'MIND_BUNDLE_SCOPE_UNREADABLE',+ });+ }++ return {+ scopes: selected,+ entries: selected.map((scope, index) => ({+ name: MIND_BUNDLE_ENTRY_NAMES[scope],+ data: JSON.stringify(results[index].value, null, 2),+ })),+ };+}++/**+ * A generic, install-agnostic filename: no hostname, no user, and not the+ * Mind's chosen name — the file lands in a downloads folder that other people+ * and other tools can see.+ */+export function mindBundleFilename(now = new Date()) {+ const stamp = now.toISOString().replace(/[:.]/g, '-').replace(/-\d{3}Z$/, 'Z');+ return `portos-mind-${stamp}${MIND_BUNDLE_FILE_EXTENSION}`;+}++/** Seal the selected scopes into one downloadable bundle. Never logs a passphrase or any content. */+export async function exportPersistentMindBundle({ scopes, passphrase }) {+ const { entries, scopes: selected } = await collectPersistentMindBundleEntries(scopes);+ const bundle = await sealMindBundle({ entries, scopes: selected, passphrase });+ console.log(`🔐 Sealed Persistent Mind bundle (scopes: ${selected.join(', ')}; entries: ${entries.length}; bytes: ${bundle.length})`);+ return { bundle, scopes: selected, filename: mindBundleFilename() };+}diff --git a/server/services/persistentMindBundle.test.js b/server/services/persistentMindBundle.test.jsnew file mode 100644index 0000000000..ada981d3f5--- /dev/null+++ b/server/services/persistentMindBundle.test.js@@ -0,0 +1,186 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { openMindBundle, readMindBundleHeader } from '../lib/mindBundleCrypto.js';++const loadState = vi.fn();+const readPersistentMindMemories = vi.fn();+const readPersistentMindName = vi.fn();++vi.mock('./cosState.js', () => ({ loadState: (...args) => loadState(...args) }));+vi.mock('./persistentMindContext.js', () => ({+ readPersistentMindMemories: (...args) => readPersistentMindMemories(...args),+ readPersistentMindName: (...args) => readPersistentMindName(...args),+}));++const {+ collectPersistentMindBundleEntries,+ exportPersistentMindBundle,+ mindBundleFilename,+ normalizeMindBundleScopes,+} = await import('./persistentMindBundle.js');++const PASSPHRASE = 'an example bundle passphrase';++// An obviously-fake Mind carrying one of every install-bound value the bundle+// must strip. Nothing here is read out of a live install.+const FIXTURE_MEMORY = {+ id: '3f9c1b2e-7a41-4d0a-9c55-0d1e2f3a4b5c',+ sourceAgentId: 'cos-persistent-mind',+ sourceTaskId: 'task-9f2b7c31',+ embedding: [0.11, -0.42, 0.7],+ sourcePath: '/Users/example-user/github.com/example/PortOS/data/cos/notes.json',+ host: 'example-host.example-tailnet.ts.net',+ status: 'active',+ importance: 0.92,+ updatedAt: '2026-09-02T10:00:00.000Z',+};++const coreMemory = (overrides = {}) => ({+ ...FIXTURE_MEMORY,+ type: 'fact',+ content: 'The example user reviews plans on Friday afternoons.',+ createdAt: '2026-09-01T12:00:00.000Z',+ protection: 'core-identity',+ ...overrides,+});++beforeEach(() => {+ vi.clearAllMocks();+ loadState.mockResolvedValue({+ config: {+ avatarStyle: 'cyber',+ persistentMindProfile: { enabled: true, providerId: 'example-provider', model: 'example-model', effort: 'high', wakeIntervalMinutes: 45 },+ persistentMindPrompt: { identity: 'I am the example Mind.', instructions: 'Stay candid and concise.' },+ persistentMindPlaybook: { mode: 'continuous-play', customInstructions: 'Prefer small experiments.' },+ persistentMindCapabilities: { createTasks: true, fileIssues: true },+ persistentMindThinkingPresets: [{ id: 'preset-1', label: 'Deep', providerId: 'example-provider', model: 'example-model' }],+ },+ });+ readPersistentMindName.mockResolvedValue('Example Mind');+ readPersistentMindMemories.mockResolvedValue([+ coreMemory(),+ coreMemory({ content: 'The example user is learning bass guitar.', protection: 'important' }),+ coreMemory({ content: 'Ordinary chatter nobody needs on another machine.', protection: 'standard' }),+ ]);+});++const openExport = async (scopes) => {+ const { bundle, filename, scopes: sealed } = await exportPersistentMindBundle({ scopes, passphrase: PASSPHRASE });+ const opened = await openMindBundle({ text: bundle, passphrase: PASSPHRASE });+ const documents = Object.fromEntries(opened.entries.map((entry) => [entry.name, JSON.parse(entry.data.toString('utf8'))]));+ return { bundle, filename, sealed, header: opened.header, documents };+};++describe('persistentMindBundle scopes', () => {+ it('defaults to profile + avatar, with protected memories opt-in', async () => {+ expect(normalizeMindBundleScopes()).toEqual(['profile', 'avatar']);+ expect(normalizeMindBundleScopes([])).toEqual(['profile', 'avatar']);+ // Requested order never changes what the header declares.+ expect(normalizeMindBundleScopes(['memories', 'profile'])).toEqual(['profile', 'memories']);+ });++ it('seals only the selected scopes and declares them in the cleartext header', async () => {+ const { header, documents, sealed } = await openExport(['profile', 'memories']);+ expect(sealed).toEqual(['profile', 'memories']);+ expect(header.scopes).toEqual(['profile', 'memories']);+ expect(Object.keys(documents).sort()).toEqual(['memories.json', 'profile.json']);+ expect(documents['profile.json'].chosenName).toBe('Example Mind');+ expect(documents['profile.json'].soul.identity).toBe('I am the example Mind.');+ expect(documents['profile.json'].playbook.mode).toBe('continuous-play');+ expect(documents['profile.json'].modelPolicy).toMatchObject({ providerId: 'example-provider', model: 'example-model', effort: 'high', wakeIntervalMinutes: 45 });+ });++ it('carries the avatar style from the bundled vocabulary, and nothing when it is unknown', async () => {+ expect((await openExport(['avatar'])).documents['avatar.json']).toEqual({ style: 'cyber' });+ loadState.mockResolvedValue({ config: { avatarStyle: 'not-a-shipped-style' } });+ expect((await openExport(['avatar'])).documents['avatar.json']).toEqual({ style: null });+ });+});++describe('persistentMindBundle privacy boundary', () => {+ it('never carries a standard-protection memory, even when memories are selected', async () => {+ const { documents, bundle } = await openExport(['memories']);+ const contents = documents['memories.json'].memories.map((memory) => memory.content);+ expect(contents).toEqual([+ 'The example user reviews plans on Friday afternoons.',+ 'The example user is learning bass guitar.',+ ]);+ expect(bundle).not.toContain('Ordinary chatter');+ });++ it('reduces a memory to meaning only — no ids, source agent/task, or embeddings', async () => {+ const { documents } = await openExport(['memories']);+ expect(documents['memories.json'].memories[0]).toEqual({+ type: 'fact',+ content: 'The example user reviews plans on Friday afternoons.',+ createdAt: '2026-09-01T12:00:00.000Z',+ protection: 'core-identity',+ });+ });++ it('strips every install-bound and sensitive value from the sealed payload', async () => {+ const { documents } = await openExport(['profile', 'avatar', 'memories']);+ const serialized = JSON.stringify(documents);+ const forbidden = [+ // Install-bound identifiers that would make the bundle un-openable or+ // re-linkable somewhere else.+ FIXTURE_MEMORY.id, 'sourceAgentId', 'sourceTaskId', 'cos-persistent-mind',+ 'embedding', 'importance',+ // AGENTS.md Sensitive Data & Privacy categories.+ '/Users/', '/home/', '.ts.net', 'example-host', 'PRIVACY_VAULT_KEY',+ // Authority grants and lifecycle state stay home: an import must never+ // widen what a Mind may do, or start one.+ 'createTasks', 'fileIssues', 'enabled',+ // Route bookmarks are this machine's registry, not the Mind's meaning.+ 'thinkingPresets', 'preset-1',+ ];+ for (const needle of forbidden) expect(serialized).not.toContain(needle);+ });++ it('keeps every plaintext value out of the cleartext preamble', async () => {+ const { bundle } = await openExport(['profile', 'memories']);+ const preamble = bundle.split('\n').slice(0, 2).join('\n');+ expect(preamble).not.toContain('Example Mind');+ expect(preamble).not.toContain('example-provider');+ expect(preamble).not.toContain('Friday afternoons');+ });++ it('names the file without a hostname, a user, or the Mind\'s own name', () => {+ const filename = mindBundleFilename(new Date('2026-09-18T14:05:06.789Z'));+ expect(filename).toBe('portos-mind-2026-09-18T14-05-06Z.portos-mind');+ });+});++describe('persistentMindBundle refusal', () => {+ it('refuses the whole export when a selected scope cannot be read', async () => {+ readPersistentMindMemories.mockRejectedValue(new Error('memory backend is unavailable'));+ await expect(exportPersistentMindBundle({ scopes: ['profile', 'memories'], passphrase: PASSPHRASE }))+ .rejects.toMatchObject({ code: 'MIND_BUNDLE_SCOPE_UNREADABLE', status: 409 });+ });++ it('names every scope that failed, not just the first', async () => {+ loadState.mockRejectedValue(new Error('cos state is unreadable'));+ readPersistentMindMemories.mockRejectedValue(new Error('memory backend is unavailable'));+ await expect(collectPersistentMindBundleEntries(['profile', 'avatar', 'memories']))+ .rejects.toThrow(/profile .*avatar .*memories/s);+ });++ it('refuses rather than shipping a truncated protected-memory set', async () => {+ readPersistentMindMemories.mockResolvedValue(+ Array.from({ length: 100 }, (_unused, index) => coreMemory({ content: `Example protected memory ${index}` })),+ );+ await expect(collectPersistentMindBundleEntries(['memories']))+ .rejects.toThrow(/more than one bundle page can carry/);+ });++ it('refuses an empty scope selection', async () => {+ await expect(collectPersistentMindBundleEntries(['not-a-scope']))+ .rejects.toMatchObject({ code: 'MIND_BUNDLE_NO_SCOPES' });+ });++ it('produces a bundle whose cleartext header is readable without the passphrase', async () => {+ const { bundle } = await openExport(['profile']);+ const { header } = readMindBundleHeader(bundle);+ expect(header.scopes).toEqual(['profile']);+ expect(header.manifest).toEqual([{ name: 'profile.json', bytes: expect.any(Number) }]);+ });+});