Skip to content

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

feat: import a Mind bundle with per-group keep-mine or use-imported choices (#7622)

[._.]/ Adam Eivy78f17d3b967b
diff --git a/client/src/components/cos/PersistentMindImportPanel.jsx b/client/src/components/cos/PersistentMindImportPanel.jsx
new file mode 100644
index 0000000000..837b91f16b
--- /dev/null
+++ b/client/src/components/cos/PersistentMindImportPanel.jsx
@@ -0,0 +1,271 @@
+import { useId, useState } from 'react';
+import { Brain, Check, Database, FileUp, Lock, Sparkles, Upload } from 'lucide-react';
+import {
+ MIND_BUNDLE_FILE_EXTENSION,
+ MIND_BUNDLE_MAX_CHARS,
+ MIND_BUNDLE_PASSPHRASE_MIN_CHARS,
+} from '../../lib/mindBundle.js';
+import * as api from '../../services/api';
+import { formatCount } from '../../utils/formatters.js';
+import Banner from '../ui/Banner';
+
+// Labels and the "what this group means" copy live here because they are UI
+// prose; the group IDS are contract and come off the preview response, which
+// orders them by `PERSISTENT_MIND_BUNDLE_GROUPS`.
+const GROUP_PRESENTATION = {
+ identity: { icon: Brain, label: 'Chosen name', detail: 'The name this Mind answers to.' },
+ personality: { icon: Sparkles, label: 'Personality', detail: 'Identity and operating instructions — one authored piece of text, taken whole or not at all.' },
+ playbook: { icon: Sparkles, label: 'Playbook', detail: 'The operating loop this Mind runs, and any custom instructions attached to it.' },
+ modelPolicy: { icon: Brain, label: 'Model policy', detail: 'Pinned provider, model, effort, and wake cadence. The destination decides whether that route exists here.' },
+ avatar: { icon: Sparkles, label: 'Appearance', detail: 'The avatar style this Mind wears.' },
+ memories: { icon: Database, label: 'Protected memories', detail: 'Appended as new records. Nothing you already hold is deleted, rewritten, or duplicated.' },
+};
+
+const KEEP_MINE = 'keep-mine';
+const USE_IMPORTED = 'use-imported';
+
+// `chosenName` reads as "Chosen name" rather than as a field id. The field
+// names come off the wire, so the split is generic instead of a lookup table
+// that would silently fall back to a camelCase id the day a group grows a field.
+const fieldLabel = (key) => key
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
+ .replace(/^./, (first) => first.toUpperCase());
+
+/** A group value rendered for comparison. Objects read as labelled lines. */
+function GroupValue({ value, empty = 'Nothing set' }) {
+ if (value === null || value === undefined) return <span className="text-port-text-muted">{empty}</span>;
+ if (typeof value !== 'object') return <span className="whitespace-pre-wrap break-words">{String(value)}</span>;
+ const rows = Object.entries(value).filter(([, entry]) => entry !== null && entry !== undefined && entry !== '');
+ if (rows.length === 0) return <span className="text-port-text-muted">{empty}</span>;
+ return (
+ <dl className="space-y-1">
+ {rows.map(([key, entry]) => (
+ <div key={key}>
+ <dt className="text-port-text-muted">{fieldLabel(key)}</dt>
+ <dd className="whitespace-pre-wrap break-words">{typeof entry === 'number' ? formatCount(entry) : String(entry)}</dd>
+ </div>
+ ))}
+ </dl>
+ );
+}
+
+/**
+ * Import a sealed Mind bundle (#7622).
+ *
+ * Two steps on purpose. **Open** decrypts and shows what the file carries
+ * beside what this install holds — the server writes nothing for it, so opening
+ * the wrong file costs nothing. **Apply** is the only write, and it takes one
+ * whole-group choice per group: keep mine, or use the imported one. There is no
+ * field-level merge anywhere in this flow, because half of one personality and
+ * half of another is a third personality nobody authored.
+ */
+export default function PersistentMindImportPanel() {
+ const idPrefix = useId();
+ const [file, setFile] = useState(null);
+ const [bundleText, setBundleText] = useState('');
+ const [passphrase, setPassphrase] = useState('');
+ const [preview, setPreview] = useState(null);
+ const [choices, setChoices] = useState({});
+ const [pending, setPending] = useState(null);
+ const [error, setError] = useState(null);
+ const [applied, setApplied] = useState(null);
+
+ // Any new file or passphrase invalidates the open bundle: the choices below
+ // describe THAT preview, and silently carrying them to another file is how a
+ // confirm applies something the user never looked at.
+ const resetPreview = () => {
+ setPreview(null);
+ setChoices({});
+ setApplied(null);
+ setError(null);
+ };
+
+ const pickFile = async (event) => {
+ const picked = event.target.files?.[0] || null;
+ resetPreview();
+ setFile(picked);
+ setBundleText('');
+ if (!picked) return;
+ if (picked.size > MIND_BUNDLE_MAX_CHARS) {
+ setError('That file is larger than a Mind bundle can be. Check that you picked the right file.');
+ return;
+ }
+ setBundleText(await picked.text());
+ };
+
+ const openBundle = async () => {
+ if (pending || !bundleText || passphrase.length < MIND_BUNDLE_PASSPHRASE_MIN_CHARS) return;
+ setPending('preview');
+ setError(null);
+ setApplied(null);
+ await api.previewPersistentMindBundle({ bundle: bundleText, passphrase })
+ .then((result) => {
+ setPreview(result);
+ // Default every group to "keep mine". An import must never be the
+ // thing that replaces a personality the user did not re-affirm.
+ setChoices(Object.fromEntries(result.groups.map(({ group }) => [group, KEEP_MINE])));
+ })
+ .catch((nextError) => {
+ setPreview(null);
+ setError(nextError?.message || 'Could not open that bundle');
+ })
+ .finally(() => setPending(null));
+ };
+
+ const applyBundle = async () => {
+ if (pending || !preview) return;
+ setPending('apply');
+ setError(null);
+ await api.applyPersistentMindBundle({ bundle: bundleText, passphrase, choices })
+ .then((result) => {
+ setApplied(result);
+ setPreview(null);
+ setChoices({});
+ // The secret has done its job; do not leave it sitting in the form.
+ setPassphrase('');
+ setBundleText('');
+ setFile(null);
+ })
+ .catch((nextError) => setError(nextError?.message || 'Could not apply that bundle'))
+ .finally(() => setPending(null));
+ };
+
+ const taking = Object.values(choices).filter((choice) => choice === USE_IMPORTED).length;
+ const canOpen = Boolean(bundleText) && passphrase.length >= MIND_BUNDLE_PASSPHRASE_MIN_CHARS;
+
+ return (
+ <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-import-heading">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h3 id="mind-import-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text">
+ <Upload size={17} aria-hidden="true" /> Open a Mind bundle
+ </h3>
+ <p className="mt-1 max-w-3xl text-xs text-port-text-muted">Bring a Mind here from another PortOS install. You see exactly what the file carries beside what this install already holds, and nothing is written until you confirm.</p>
+ </div>
+ <span className="rounded-full border border-port-border px-2.5 py-1 text-xs text-port-text-muted">Whole groups — never a merge</span>
+ </div>
+
+ <div className="mt-4 grid gap-3 sm:grid-cols-2">
+ <div>
+ <label htmlFor={`${idPrefix}-file`} className="flex items-center gap-2 text-xs font-medium text-port-text"><FileUp size={14} aria-hidden="true" /> Bundle file</label>
+ <input
+ id={`${idPrefix}-file`}
+ type="file"
+ accept={MIND_BUNDLE_FILE_EXTENSION}
+ disabled={Boolean(pending)}
+ onChange={pickFile}
+ className="mt-2 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text file:mr-3 file:rounded file:border-0 file:bg-port-accent/10 file:px-3 file:py-1 file:text-xs file:text-port-accent disabled:opacity-50"
+ />
+ <p className="mt-1 text-xs text-port-text-muted">{file ? `Ready: ${file.name}` : `The ${MIND_BUNDLE_FILE_EXTENSION} file you exported on the other install.`}</p>
+ </div>
+ <div>
+ <label htmlFor={`${idPrefix}-import-passphrase`} className="flex items-center gap-2 text-xs font-medium text-port-text"><Lock size={14} aria-hidden="true" /> Bundle passphrase</label>
+ <input
+ id={`${idPrefix}-import-passphrase`}
+ type="password"
+ value={passphrase}
+ disabled={Boolean(pending)}
+ autoComplete="off"
+ onChange={(event) => { setPassphrase(event.target.value); resetPreview(); }}
+ 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">The passphrase used when this bundle was sealed.</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">Opening a bundle only reads it — nothing on this install changes.</p>
+ <button
+ type="button"
+ onClick={openBundle}
+ disabled={Boolean(pending) || !canOpen}
+ className="inline-flex min-h-10 items-center justify-center gap-2 rounded border border-port-accent px-4 text-sm font-medium text-port-accent disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ <Upload size={16} className={pending === 'preview' ? 'animate-pulse' : ''} aria-hidden="true" /> {pending === 'preview' ? 'Opening…' : 'Open bundle'}
+ </button>
+ </div>
+
+ {error && (
+ <div className="mt-4">
+ <Banner tone="error" title="Bundle refused">{error}</Banner>
+ </div>
+ )}
+
+ {applied && (
+ <div className="mt-4">
+ <Banner tone="success" title="Bundle applied">
+ {applied.applied.length > 0 ? `Used the imported ${applied.applied.join(', ')}.` : 'Nothing was changed — every group kept this install\'s value.'}
+ {applied.memories.imported > 0 && ` Added ${formatCount(applied.memories.imported)} memories`}
+ {applied.memories.imported > 0 && applied.memories.skipped > 0 && ` (${formatCount(applied.memories.skipped)} already here)`}
+ {applied.memories.imported > 0 && '.'}
+ </Banner>
+ </div>
+ )}
+
+ {preview && (
+ <div className="mt-4 space-y-3">
+ <p className="text-xs text-port-text-muted">
+ Sealed {preview.createdAt ? new Date(preview.createdAt).toLocaleString() : 'at an unknown time'} · carries {preview.scopes.join(', ')}. Choose one side per group.
+ </p>
+
+ {preview.groups.map(({ group, identical, additive, incoming, current }) => {
+ const { icon: Icon, label, detail } = GROUP_PRESENTATION[group] || { icon: Brain, label: group, detail: '' };
+ const name = `${idPrefix}-choice-${group}`;
+ return (
+ <fieldset key={group} className="rounded border border-port-border bg-port-bg/30 p-3">
+ <legend className="flex items-center gap-2 px-1 text-sm font-medium text-port-text"><Icon size={15} aria-hidden="true" /> {label}</legend>
+ <p className="text-xs text-port-text-muted">{detail}</p>
+
+ <div className="mt-3 grid gap-3 lg:grid-cols-2">
+ <label htmlFor={`${name}-mine`} className={`cursor-pointer rounded border p-3 text-xs transition-colors ${choices[group] === KEEP_MINE ? 'border-port-accent bg-port-accent/5' : 'border-port-border'}`}>
+ <span className="flex items-center gap-2 font-medium text-port-text">
+ <input id={`${name}-mine`} type="radio" name={name} value={KEEP_MINE} checked={choices[group] === KEEP_MINE} disabled={Boolean(pending)} onChange={() => setChoices((prev) => ({ ...prev, [group]: KEEP_MINE }))} className="h-4 w-4 accent-port-accent" />
+ {additive ? 'Skip them' : 'Keep mine'}
+ </span>
+ <span className="mt-2 block text-port-text">
+ {additive
+ ? <>This install keeps its {formatCount(current.protectedCount, { fallback: '0' })} protected memories and adds nothing.</>
+ : <GroupValue value={current} />}
+ </span>
+ </label>
+
+ <label htmlFor={`${name}-theirs`} className={`cursor-pointer rounded border p-3 text-xs transition-colors ${choices[group] === USE_IMPORTED ? 'border-port-accent bg-port-accent/5' : 'border-port-border'}`}>
+ <span className="flex items-center gap-2 font-medium text-port-text">
+ <input id={`${name}-theirs`} type="radio" name={name} value={USE_IMPORTED} checked={choices[group] === USE_IMPORTED} disabled={Boolean(pending)} onChange={() => setChoices((prev) => ({ ...prev, [group]: USE_IMPORTED }))} className="h-4 w-4 accent-port-accent" />
+ {additive ? 'Import them' : 'Use imported'}
+ </span>
+ <span className="mt-2 block text-port-text">
+ {additive
+ ? <>Appends {formatCount(incoming.importable, { fallback: '0' })} new memories{incoming.alreadyHere > 0 ? ` (${formatCount(incoming.alreadyHere)} already here, skipped)` : ''}. Nothing you hold is removed.</>
+ : <GroupValue value={incoming} />}
+ </span>
+ </label>
+ </div>
+
+ {identical && (
+ <p className="mt-2 text-xs text-port-text-muted">{additive ? 'This bundle adds no memories you do not already have.' : 'Both sides are identical — either choice leaves this unchanged.'}</p>
+ )}
+ </fieldset>
+ );
+ })}
+
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
+ <p className="text-xs text-port-text-muted">
+ {taking === 0
+ ? 'Every group is set to keep this install\'s value — confirming would change nothing.'
+ : `Confirming replaces ${formatCount(taking)} group${taking === 1 ? '' : 's'} on this install. This cannot be undone from here.`}
+ </p>
+ <button
+ type="button"
+ onClick={applyBundle}
+ disabled={Boolean(pending) || taking === 0}
+ 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"
+ >
+ <Check size={16} className={pending === 'apply' ? 'animate-pulse' : ''} aria-hidden="true" /> {pending === 'apply' ? 'Applying…' : 'Apply these choices'}
+ </button>
+ </div>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/cos/PersistentMindImportPanel.test.jsx b/client/src/components/cos/PersistentMindImportPanel.test.jsx
new file mode 100644
index 0000000000..6549164071
--- /dev/null
+++ b/client/src/components/cos/PersistentMindImportPanel.test.jsx
@@ -0,0 +1,124 @@
+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(() => ({
+ previewPersistentMindBundle: vi.fn(),
+ applyPersistentMindBundle: vi.fn(),
+}));
+vi.mock('../../services/api', () => api);
+
+const PersistentMindImportPanel = (await import('./PersistentMindImportPanel.jsx')).default;
+
+const PASSPHRASE = 'an example bundle passphrase';
+const BUNDLE_TEXT = 'portos-mind-bundle/1\n{}\nAAAA\nBBBB\n';
+
+// An obviously-fake preview. Never a record read out of a live install.
+const PREVIEW = {
+ createdAt: '2026-09-18T14:05:06.789Z',
+ scopes: ['profile', 'memories'],
+ groups: [
+ {
+ group: 'identity',
+ scope: 'profile',
+ additive: false,
+ identical: false,
+ incoming: { chosenName: 'Other Example Mind' },
+ current: { chosenName: 'Example Mind' },
+ },
+ {
+ group: 'memories',
+ scope: 'memories',
+ additive: true,
+ identical: false,
+ incoming: { total: 3, importable: 2, alreadyHere: 1, memories: [] },
+ current: { protectedCount: 4 },
+ },
+ ],
+};
+
+const bundleFile = () => new File([BUNDLE_TEXT], 'example.portos-mind', { type: 'text/plain' });
+
+const openBundle = async (user) => {
+ await user.upload(screen.getByLabelText('Bundle file'), bundleFile());
+ await user.type(screen.getByLabelText('Bundle passphrase'), PASSPHRASE);
+ await user.click(screen.getByRole('button', { name: /Open bundle/ }));
+ await screen.findByRole('button', { name: /Apply these choices/ });
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.previewPersistentMindBundle.mockResolvedValue(PREVIEW);
+ api.applyPersistentMindBundle.mockResolvedValue({ applied: ['identity'], kept: ['memories'], memories: { imported: 0, skipped: 0 } });
+});
+
+describe('PersistentMindImportPanel', () => {
+ it('keeps the open action disabled until a file and a long-enough passphrase exist', async () => {
+ const user = userEvent.setup();
+ render(<PersistentMindImportPanel />);
+ const open = screen.getByRole('button', { name: /Open bundle/ });
+ expect(open).toBeDisabled();
+
+ await user.upload(screen.getByLabelText('Bundle file'), bundleFile());
+ await waitFor(() => expect(screen.getByText(/Ready: example\.portos-mind/)).toBeInTheDocument());
+ expect(open).toBeDisabled();
+
+ await user.type(screen.getByLabelText('Bundle passphrase'), 'too short');
+ expect(open).toBeDisabled();
+
+ await user.clear(screen.getByLabelText('Bundle passphrase'));
+ await user.type(screen.getByLabelText('Bundle passphrase'), PASSPHRASE);
+ expect(open).toBeEnabled();
+ });
+
+ it('defaults every group to keep-mine, so a confirm with no choices cannot overwrite anything', async () => {
+ const user = userEvent.setup();
+ render(<PersistentMindImportPanel />);
+ await openBundle(user);
+
+ expect(screen.getByRole('radio', { name: /Keep mine/ })).toBeChecked();
+ expect(screen.getByRole('radio', { name: /Use imported/ })).not.toBeChecked();
+ expect(screen.getByRole('radio', { name: /Skip them/ })).toBeChecked();
+ // Nothing to apply means the confirm is unavailable, not a silent no-op.
+ expect(screen.getByRole('button', { name: /Apply these choices/ })).toBeDisabled();
+ expect(api.applyPersistentMindBundle).not.toHaveBeenCalled();
+ });
+
+ it('sends exactly the per-group choices the user made', async () => {
+ const user = userEvent.setup();
+ render(<PersistentMindImportPanel />);
+ await openBundle(user);
+
+ await user.click(screen.getByRole('radio', { name: /Use imported/ }));
+ await user.click(screen.getByRole('button', { name: /Apply these choices/ }));
+
+ await waitFor(() => expect(api.applyPersistentMindBundle).toHaveBeenCalledWith({
+ bundle: BUNDLE_TEXT,
+ passphrase: PASSPHRASE,
+ choices: { identity: 'use-imported', memories: 'keep-mine' },
+ }));
+ expect(await screen.findByText(/Used the imported identity/)).toBeInTheDocument();
+ });
+
+ it('discards the open preview when the passphrase changes, so a confirm cannot apply a stale one', async () => {
+ const user = userEvent.setup();
+ render(<PersistentMindImportPanel />);
+ await openBundle(user);
+
+ await user.type(screen.getByLabelText('Bundle passphrase'), 'x');
+ expect(screen.queryByRole('button', { name: /Apply these choices/ })).not.toBeInTheDocument();
+ });
+
+ it('shows the server refusal instead of a generic failure, and offers nothing to apply', async () => {
+ api.previewPersistentMindBundle.mockRejectedValue(new Error('Mind bundle container version 99 is not supported by this install (expected 1)'));
+ const user = userEvent.setup();
+ render(<PersistentMindImportPanel />);
+
+ await user.upload(screen.getByLabelText('Bundle file'), bundleFile());
+ await user.type(screen.getByLabelText('Bundle passphrase'), PASSPHRASE);
+ await user.click(screen.getByRole('button', { name: /Open bundle/ }));
+
+ expect(await screen.findByText(/container version 99 is not supported/)).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Apply these choices/ })).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/cos/PersistentMindPortabilityPanel.jsx b/client/src/components/cos/PersistentMindPortabilityPanel.jsx
index f10041bdf0..140a05823b 100644
--- a/client/src/components/cos/PersistentMindPortabilityPanel.jsx
+++ b/client/src/components/cos/PersistentMindPortabilityPanel.jsx
@@ -1,13 +1,15 @@
import { useId, useState } from 'react';
import { Brain, Database, Download, Lock, ShieldCheck, Sparkles } from 'lucide-react';
import { downloadBlob } from '../../lib/downloadBlob.js';
+import { MIND_BUNDLE_FILE_EXTENSION, MIND_BUNDLE_PASSPHRASE_MIN_CHARS } from '../../lib/mindBundle.js';
import * as api from '../../services/api';
import Banner from '../ui/Banner';
+import PersistentMindImportPanel from './PersistentMindImportPanel.jsx';
-// 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;
+// Re-exported for this component's own test. The definition is the shared
+// format leaf — checked here so the user is told before a round trip, while the
+// server stays the authority and refuses a short passphrase on its own.
+export { MIND_BUNDLE_PASSPHRASE_MIN_CHARS };
// Protected memories quote private conversation, so that scope is opt-in —
// the decision is the epic's (#7620), not this panel's to soften.
@@ -44,7 +46,7 @@ const defaultScopes = () => new Set(EXPORT_SCOPES.filter(({ defaultOn }) => defa
* 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`;
+ `portos-mind-${now.toISOString().replace(/[:.]/g, '-').replace(/-\d{3}Z$/, 'Z')}${MIND_BUNDLE_FILE_EXTENSION}`;
/**
* Export the Persistent Mind as one passphrase-sealed file (#7621).
@@ -194,6 +196,8 @@ export default function PersistentMindPortabilityPanel() {
Saved {exported.filename} with {exported.scopes.join(', ')}. Store it alongside your other secrets — the passphrase is the only way back in.
</Banner>
)}
+
+ <PersistentMindImportPanel />
</div>
);
}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 37ef214514..1b452a826d 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -262,6 +262,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeMarkdownFilename.js` | `slugifyUniverseName` / `universeMarkdownFilename` — client-side safe filename helpers for Universe Markdown world-bible downloads, kept in step with the server attachment name. |
| `universeMarkdownFilename.cases.js` | Shared client/server filename contract cases used to keep the browser download name and server attachment name in lockstep. |
| `qrCode.js` | Deterministic SVG QR code generator for scoped mobile session join links (#5383). |
+| `mindBundle.js` | Persistent Mind portable-bundle format vocabulary, re-exported from the `server/lib/mindBundleFormat.js` leaf (never copied): file extension, passphrase floor, size cap, export scopes, and the import group ids / source scopes / choice values the import panel renders. The sealing code stays server-side — that module imports node `crypto`. |
| `publicGuestRoutes.js` | `isPublicGuestRoute` identifies standalone guest pages that skip private app bootstrap. |
| `riggingReasons.js` | Client mirror of the character-rigging readiness reason labels in `server/services/rigging/readiness.js`: `RIGGING_UNAVAILABLE_REASONS` (reason code -> user-facing label), `RIGGING_REASON_FALLBACK`, and `riggingReasonLabel(code, fallback?)`. Render these anywhere a `GET /api/rigging/readiness` reason is shown; never re-declare the codes. Parity + code coverage enforced by `server/services/rigging/unavailableReasons.parity.test.js`. |
| `usagePeriods.js` | The report windows every usage-cost surface offers — `USAGE_PERIOD_OPTIONS`, `DEFAULT_USAGE_PERIOD` (what a URL with no `?period` means) and `resolveUsagePeriod`. Shared because `?period` is a URL param the user carries between the Usage and Subscriptions pages; two copies had already disagreed on the default. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index dc8f6a1f30..b8d1db9a73 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -1,4 +1,5 @@
// Barrel for client/src/lib/ — discovery surface, not a forced import path.
+export * from './mindBundle.js';
export * from './publicGuestRoutes.js';
// See client/src/lib/README.md for the human-readable catalog and
// AGENTS.md "Module organization" for the maintenance convention.
diff --git a/client/src/lib/mindBundle.js b/client/src/lib/mindBundle.js
new file mode 100644
index 0000000000..62162d922c
--- /dev/null
+++ b/client/src/lib/mindBundle.js
@@ -0,0 +1,16 @@
+// Mind bundle format vocabulary, re-exported from the single server-side
+// definition (client/src/lib/README.md "One pure module, one definition").
+//
+// The client cannot import `server/lib/mindBundleCrypto.js` — that module pulls
+// node's `crypto` — so the format names live in a sibling leaf with no node
+// imports and both sides read THAT. A mirrored copy here would drift the first
+// time the container version or the passphrase floor moves.
+export {
+ MIND_BUNDLE_FILE_EXTENSION,
+ MIND_BUNDLE_GROUP_CHOICES,
+ MIND_BUNDLE_GROUP_SCOPES,
+ MIND_BUNDLE_MAX_CHARS,
+ MIND_BUNDLE_PASSPHRASE_MIN_CHARS,
+ PERSISTENT_MIND_BUNDLE_GROUPS,
+ PERSISTENT_MIND_BUNDLE_SCOPES,
+} from '../../../server/lib/mindBundleFormat.js';
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index cce4262464..c7dff9a6e6 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -137,6 +137,17 @@ export const exportPersistentMindBundle = (body, options = {}) => request('/cos/
method: 'POST', body: JSON.stringify(body), responseType: 'text', silent: true, ...options,
});
+// Open a bundle and see what it carries (#7622). Read-only on the server: this
+// never writes, so the panel can call it as soon as a file and passphrase exist.
+// `silent` because the refusal reason IS the result the user needs to read.
+export const previewPersistentMindBundle = (body, options = {}) => request('/cos/mind/bundle/preview', {
+ method: 'POST', body: JSON.stringify(body), silent: true, ...options,
+});
+// Apply a bundle under the user's per-group choices (#7622) — the single write.
+export const applyPersistentMindBundle = (body, options = {}) => request('/cos/mind/bundle/apply', {
+ method: 'POST', body: JSON.stringify(body), silent: true, ...options,
+});
+
// Chief of Staff
export const getCosStatus = () => request('/cos');
export const startCos = (options = {}) => request('/cos/start', { method: 'POST', ...options });
diff --git a/server/lib/README.md b/server/lib/README.md
index 81b12d8711..4ceec76f8c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -71,7 +71,8 @@ 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. |
+| `mindBundleCrypto.js` | Persistent Mind portable-bundle container (#7621) — `sealMindBundle` / `openMindBundle` / `readMindBundleHeader`, scrypt-from-passphrase + AES-256-GCM with the cleartext header as AAD. Passphrase-derived, never `PRIVACY_VAULT_KEY`: that key is machine-bound and a bundle sealed with it could not open on the destination install. Format names live in `mindBundleFormat.js`. |
+| `mindBundleFormat.js` | Mind bundle format vocabulary, free of node builtins so the browser reads the same definitions (`client/src/lib/mindBundle.js`) — magic/versions/extension, scrypt parameters, export scopes (`PERSISTENT_MIND_BUNDLE_SCOPES`), import groups and their source scopes (`PERSISTENT_MIND_BUNDLE_GROUPS`, `MIND_BUNDLE_GROUP_SCOPES`, `MIND_BUNDLE_GROUP_CHOICES`), size/passphrase bounds, and the named refusal reasons (`MIND_BUNDLE_REFUSALS`, `mindBundleRefusal`). |
| `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.js
index 34233d4783..a4ea211303 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -337,6 +337,7 @@ export * from './persistentMindPrompt.js';
export * from './persistentMindPlaybook.js';
export * from './persistentMindPlaybookPhase.js';
export * from './mindBundleCrypto.js';
+export * from './mindBundleFormat.js';
export * from './mindLocalContextClamp.js';
export * from './persistentMindPublic.js';
export * from './persistentMindThinkingPresets.js';
diff --git a/server/lib/mindBundleCrypto.js b/server/lib/mindBundleCrypto.js
index 1bc4832fe6..5717b34c2c 100644
--- a/server/lib/mindBundleCrypto.js
+++ b/server/lib/mindBundleCrypto.js
@@ -37,41 +37,27 @@
import { createCipheriv, createDecipheriv, createHash, randomBytes, scrypt, timingSafeEqual } from 'crypto';
import { promisify } from 'util';
+import {
+ MIND_BUNDLE_CONTAINER_VERSION,
+ MIND_BUNDLE_KDF,
+ MIND_BUNDLE_MAGIC,
+ MIND_BUNDLE_MAX_CHARS,
+ MIND_BUNDLE_PASSPHRASE_MAX_CHARS,
+ MIND_BUNDLE_PASSPHRASE_MIN_CHARS,
+ MIND_BUNDLE_PAYLOAD_VERSION,
+ MIND_BUNDLE_REFUSALS,
+ PERSISTENT_MIND_BUNDLE_SCOPES,
+ mindBundleRefusal,
+} from './mindBundleFormat.js';
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;
+const KEY_BYTES = MIND_BUNDLE_KDF.keyBytes;
-/**
- * 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
@@ -82,21 +68,21 @@ 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`);
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.PASSPHRASE_INVALID, `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`);
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.PASSPHRASE_INVALID, `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 (kdf.name !== 'scrypt') throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.KDF_UNSUPPORTED, `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');
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.KDF_UNSUPPORTED, '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,
@@ -174,40 +160,44 @@ const isPlainRecord = (value) => Boolean(value) && typeof value === 'object' &&
* 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');
+ if (typeof text !== 'string' || !text.trim()) throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.NOT_A_BUNDLE, 'Mind bundle is empty');
+ // Refuse by length before running scrypt over a file from somewhere else.
+ if (text.length > MIND_BUNDLE_MAX_CHARS) {
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.TOO_LARGE, `Mind bundle is larger than this install will open (limit ${MIND_BUNDLE_MAX_CHARS} characters)`);
+ }
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 (magic !== MIND_BUNDLE_MAGIC) throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.NOT_A_BUNDLE, '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})`);
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.VERSION_UNSUPPORTED, `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');
+ if (!headerLine || !ciphertextB64 || !tagB64) throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, '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');
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.NOT_A_BUNDLE, '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})`);
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.VERSION_UNSUPPORTED, `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');
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.UNKNOWN_SCOPE, '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');
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.CIPHER_UNSUPPORTED, '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');
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.KDF_UNSUPPORTED, 'Mind bundle is missing its key-derivation parameters');
}
- if (!Array.isArray(header.manifest)) throw new Error('Mind bundle is missing its entry manifest');
+ if (!Array.isArray(header.manifest)) throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, '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');
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, 'Mind bundle is truncated or damaged');
}
return { header, headerLine, ciphertext, tag, iv };
}
@@ -225,17 +215,26 @@ export async function openMindBundle({ text, passphrase }) {
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'));
+ // GCM cannot tell a wrong passphrase from a modified file, and neither may
+ // this refusal: naming which one it was would make the error an oracle for
+ // anyone holding the file. `final()` throws synchronously, so the
+ // translation rides a promise chain rather than a try/catch (AGENTS.md).
+ const plaintext = await Promise.resolve()
+ .then(() => Buffer.concat([decipher.update(ciphertext), decipher.final()]))
+ .catch(() => {
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.AUTH_FAILED, 'Could not open this Mind bundle: the passphrase is wrong, or the file changed after it was sealed.');
+ });
+ const payload = JSON.parse(plaintext.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');
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.PAYLOAD_UNSUPPORTED, '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`);
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.INTEGRITY_FAILED, `Mind bundle entry "${entry.name}" failed its integrity check`);
}
return { name: entry.name, data };
});
diff --git a/server/lib/mindBundleCrypto.test.js b/server/lib/mindBundleCrypto.test.js
index e7df55b2bb..b47ba11612 100644
--- a/server/lib/mindBundleCrypto.test.js
+++ b/server/lib/mindBundleCrypto.test.js
@@ -1,11 +1,6 @@
import { describe, it, expect } from 'vitest';
-import {
- MIND_BUNDLE_MAGIC,
- MIND_BUNDLE_PASSPHRASE_MIN_CHARS,
- openMindBundle,
- readMindBundleHeader,
- sealMindBundle,
-} from './mindBundleCrypto.js';
+import { openMindBundle, readMindBundleHeader, sealMindBundle } from './mindBundleCrypto.js';
+import { MIND_BUNDLE_MAGIC, MIND_BUNDLE_PASSPHRASE_MIN_CHARS } from './mindBundleFormat.js';
// Obviously-fake fixture. Never a record read out of a live install.
const PASSPHRASE = 'correct horse battery staple';
diff --git a/server/lib/mindBundleFormat.js b/server/lib/mindBundleFormat.js
new file mode 100644
index 0000000000..7cd49f5801
--- /dev/null
+++ b/server/lib/mindBundleFormat.js
@@ -0,0 +1,117 @@
+/**
+ * Mind bundle FORMAT vocabulary — the names, versions, scopes, groups, and
+ * refusal reasons that describe a portable Mind bundle (#7621, #7622; epic
+ * #7620).
+ *
+ * Deliberately separate from `mindBundleCrypto.js`, which seals and opens one:
+ * that module imports node's `crypto`, and the browser needs these same names
+ * to render the export scope list, the import group table, and the passphrase
+ * rule. Splitting the vocabulary out is what lets the client import ONE
+ * definition (`client/src/lib/mindBundle.js`) instead of mirroring constants
+ * that would then drift on the first version bump.
+ *
+ * Nothing here performs I/O or touches a key.
+ */
+
+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';
+
+/**
+ * Key length in bytes. Declared here rather than beside the cipher because the
+ * KDF parameters below travel inside the cleartext header, and a reader has to
+ * be able to check them against what this build will run.
+ */
+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 });
+
+/**
+ * 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']);
+
+/**
+ * The units an IMPORT applies, and the scope each one arrives in (#7622).
+ *
+ * A scope is what the exporter seals; a group is what the destination user
+ * chooses about. They are not one-to-one: the `profile` scope carries four
+ * independently-authored things, and offering them as one all-or-nothing
+ * switch would force a user who wants the incoming name to also take the
+ * incoming model policy. `playbook` is separate from `personality` for the
+ * same reason — a playbook is a product-supported loop with its own
+ * vocabulary, not free prose.
+ *
+ * The vocabulary lives beside the container contract because the cleartext
+ * header declares scopes: a reader must be able to say which groups a bundle
+ * could possibly offer before it decrypts anything.
+ */
+export const MIND_BUNDLE_GROUP_SCOPES = Object.freeze({
+ identity: 'profile',
+ personality: 'profile',
+ playbook: 'profile',
+ modelPolicy: 'profile',
+ avatar: 'avatar',
+ memories: 'memories',
+});
+
+/** Stable presentation order — the preview and the apply summary share it. */
+export const PERSISTENT_MIND_BUNDLE_GROUPS = Object.freeze(Object.keys(MIND_BUNDLE_GROUP_SCOPES));
+
+/**
+ * Whole-group choices, never a merge (#7622). `memories` reads these as
+ * "skip them" / "import them": that group is additive, appending and never
+ * replacing, so there is no "mine" that losing the choice would destroy.
+ */
+export const MIND_BUNDLE_GROUP_CHOICES = Object.freeze(['keep-mine', 'use-imported']);
+
+/**
+ * A bundle is a file from somewhere else. Cap what this install will even
+ * attempt to parse, far under the JSON body limit, so an oversized or hostile
+ * file is refused by length rather than by running scrypt over it.
+ */
+export const MIND_BUNDLE_MAX_CHARS = 8 * 1024 * 1024;
+
+/**
+ * Refusal reasons are NAMED, because "forward-compatible by refusal" only
+ * helps if the destination can tell the user WHICH refusal it hit. The code
+ * travels to the client; the message explains it in the user's terms.
+ *
+ * `AUTH_FAILED` deliberately covers both a wrong passphrase and a modified
+ * file: GCM cannot distinguish them, and guessing which one it was would tell
+ * a holder of the file whether their passphrase guess was close.
+ */
+export const MIND_BUNDLE_REFUSALS = Object.freeze({
+ NOT_A_BUNDLE: 'bundle_not_a_bundle',
+ VERSION_UNSUPPORTED: 'bundle_version_unsupported',
+ DAMAGED: 'bundle_damaged',
+ UNKNOWN_SCOPE: 'bundle_unknown_scope',
+ CIPHER_UNSUPPORTED: 'bundle_cipher_unsupported',
+ KDF_UNSUPPORTED: 'bundle_kdf_unsupported',
+ AUTH_FAILED: 'bundle_auth_failed',
+ INTEGRITY_FAILED: 'bundle_integrity_failed',
+ PAYLOAD_UNSUPPORTED: 'bundle_payload_unsupported',
+ PASSPHRASE_INVALID: 'bundle_passphrase_invalid',
+ TOO_LARGE: 'bundle_too_large',
+});
+
+/** Tag a refusal with its named reason so callers branch on the code, not the prose. */
+export function mindBundleRefusal(reason, message) {
+ return Object.assign(new Error(message), { mindBundleReason: reason });
+}
+
+/**
+ * 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;
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 2ee984e3e2..f948a57a66 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -31,7 +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';
+import { MIND_BUNDLE_GROUP_CHOICES, MIND_BUNDLE_MAX_CHARS, MIND_BUNDLE_PASSPHRASE_MAX_CHARS, MIND_BUNDLE_PASSPHRASE_MIN_CHARS, PERSISTENT_MIND_BUNDLE_GROUPS, PERSISTENT_MIND_BUNDLE_SCOPES } from './mindBundleFormat.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
@@ -2339,3 +2339,31 @@ export const mindBundleExportSchema = z.object({
.min(MIND_BUNDLE_PASSPHRASE_MIN_CHARS, `Passphrase must be at least ${MIND_BUNDLE_PASSPHRASE_MIN_CHARS} characters`)
.max(MIND_BUNDLE_PASSPHRASE_MAX_CHARS),
}).strict();
+
+const mindBundlePassphrase = 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);
+
+// The uploaded file, as text. Bounded here as well as in the container reader
+// so an oversized upload is refused before a key derivation runs over it.
+const mindBundleText = z.string().min(1).max(MIND_BUNDLE_MAX_CHARS);
+
+/** Open a bundle and report what it carries. Read-only — no choices, no writes (#7622). */
+export const mindBundlePreviewSchema = z.object({
+ bundle: mindBundleText,
+ passphrase: mindBundlePassphrase,
+}).strict();
+
+/**
+ * Apply a bundle under one whole-group choice per group. A group the caller
+ * omits keeps this install's value, so a partial payload can never overwrite a
+ * personality by accident; `.strict()` on the choice map means a group name
+ * this build does not know is a 400, not a silently ignored key.
+ */
+export const mindBundleApplySchema = z.object({
+ bundle: mindBundleText,
+ passphrase: mindBundlePassphrase,
+ choices: z.object(Object.fromEntries(
+ PERSISTENT_MIND_BUNDLE_GROUPS.map((group) => [group, z.enum(MIND_BUNDLE_GROUP_CHOICES).optional()]),
+ )).strict(),
+}).strict();
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index fe2c34e43c..8233b6c2f0 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -38,7 +38,7 @@ import { composePersistentMindInstructions, normalizePersistentMindPlaybook, PER
import { resolvePersistentMindPlaybookPhase } from '../services/persistentMindPlaybookSignals.js';
import { publicPersistentMindState } from '../lib/persistentMindPublic.js';
import { publicPersistentMindTurnExecutions } from '../lib/persistentMindTrajectory.js';
-import { mindBundleExportSchema, validateRequest } from '../lib/validation.js';
+import { mindBundleApplySchema, mindBundleExportSchema, mindBundlePreviewSchema, validateRequest } from '../lib/validation.js';
import { readPersistentMindEvents, readPersistentMindHistory } from '../services/agentRunEventLog.js';
import { loadState } from '../services/cosState.js';
import {
@@ -58,7 +58,11 @@ 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 {
+ applyPersistentMindBundle,
+ exportPersistentMindBundle,
+ previewPersistentMindBundle,
+} from '../services/persistentMindBundle.js';
import { resolvePersistentMindImageCapability } from '../services/persistentMindImageCapability.js';
import { readPersistentMindTaskCatalog } from '../services/persistentMindTaskCapability.js';
import { inspectPersistentMindRuntime } from '../services/persistentMindRuntime.js';
@@ -412,6 +416,31 @@ router.post('/mind/bundle/export', asyncHandler(async (req, res) => {
res.send(bundle);
}));
+/**
+ * Open a bundle and report what it carries beside what this install holds
+ * (#7622). **This route writes nothing** — it is the read that makes the apply
+ * below a decision rather than a leap, so it stays free of every side effect.
+ * The response is a diff, not a transcript: it is the user's own Mind, shown
+ * back to them on their own machine, and it is never logged or offered to a peer.
+ */
+router.post('/mind/bundle/preview', asyncHandler(async (req, res) => {
+ const { bundle, passphrase } = validateRequest(mindBundlePreviewSchema, req.body);
+ res.setHeader('Cache-Control', 'no-store');
+ res.json(await previewPersistentMindBundle({ text: bundle, passphrase }));
+}));
+
+/**
+ * Apply a bundle under one whole-group choice per group (#7622). The single
+ * write path. The bundle is re-opened here rather than carried over from the
+ * preview, so what is applied is what the file says — not a preview payload
+ * that made a round trip through the client.
+ */
+router.post('/mind/bundle/apply', asyncHandler(async (req, res) => {
+ const { bundle, passphrase, choices } = validateRequest(mindBundleApplySchema, req.body);
+ res.setHeader('Cache-Control', 'no-store');
+ res.json(await applyPersistentMindBundle({ text: bundle, passphrase, choices }));
+}));
+
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/services/persistentMindBundle.js b/server/services/persistentMindBundle.js
index 372206d885..42b43fb804 100644
--- a/server/services/persistentMindBundle.js
+++ b/server/services/persistentMindBundle.js
@@ -1,8 +1,22 @@
/**
- * 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.
+ * Persistent Mind bundle export and import — seal the Mind's *meaning* into
+ * one passphrase-encrypted file the user can carry to another install (#7621),
+ * and open one here under per-group choices (#7622); epic #7620. Machine-local
+ * and user-initiated end to end: nothing here runs on a schedule, calls a
+ * provider, or crosses the federation layer.
+ *
+ * The import half is deliberately two calls, not one. `previewPersistentMindBundle`
+ * decrypts and reports; it writes NOTHING, so a user can look inside a bundle
+ * (including one that turns out to be the wrong file) without consequence.
+ * `applyPersistentMindBundle` is the only write path, and it runs once, after
+ * the user has chosen per group.
+ *
+ * **Whole-group, never a merge.** Each group is taken from the bundle or kept
+ * from this install, entire. There is no field-level merge and no three-way
+ * text merge, because half of one personality and half of another is not a
+ * personality — it is a third one nobody authored. `memories` is the one
+ * additive group: it appends and never deletes or rewrites, so its choice
+ * reads "import them" / "skip them".
*
* What goes in is decided by scope, and every scope is deliberately narrow.
* The bundle carries no database ids, no `sourceTaskId`/`sourceAgentId`, no
@@ -35,14 +49,23 @@ 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 { openMindBundle, sealMindBundle } from '../lib/mindBundleCrypto.js';
import {
DEFAULT_PERSISTENT_MIND_BUNDLE_SCOPES,
MIND_BUNDLE_FILE_EXTENSION,
+ MIND_BUNDLE_GROUP_SCOPES,
+ MIND_BUNDLE_REFUSALS,
+ PERSISTENT_MIND_BUNDLE_GROUPS,
PERSISTENT_MIND_BUNDLE_SCOPES,
- sealMindBundle,
-} from '../lib/mindBundleCrypto.js';
+ mindBundleRefusal,
+} from '../lib/mindBundleFormat.js';
import { loadState } from './cosState.js';
-import { readPersistentMindMemories, readPersistentMindName } from './persistentMindContext.js';
+import {
+ choosePersistentMindName,
+ createPersistentMindMemory,
+ readPersistentMindMemories,
+ readPersistentMindName,
+} from './persistentMindContext.js';
export const MIND_BUNDLE_ENTRY_NAMES = Object.freeze({
profile: 'profile.json',
@@ -175,3 +198,314 @@ export async function exportPersistentMindBundle({ scopes, passphrase }) {
console.log(`🔐 Sealed Persistent Mind bundle (scopes: ${selected.join(', ')}; entries: ${entries.length}; bytes: ${bundle.length})`);
return { bundle, scopes: selected, filename: mindBundleFilename() };
}
+
+/* ------------------------------------------------------------------ import */
+
+/** The scope an entry name belongs to, so an unexpected entry is a refusal. */
+const SCOPE_BY_ENTRY_NAME = Object.freeze(Object.fromEntries(
+ Object.entries(MIND_BUNDLE_ENTRY_NAMES).map(([scope, name]) => [name, scope]),
+));
+
+// Same ceiling the memory reader pages at, and the same content bound a
+// mind-authored memory gets (`performAutomaticMemoryCreation`): an imported
+// record is held to what a local one would be.
+const IMPORTED_MEMORY_CONTENT_MAX = 10_240;
+const IMPORTED_MEMORY_TYPE_MAX = 64;
+
+const isPlainRecord = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+const sameValue = (a, b) => JSON.stringify(a) === JSON.stringify(b);
+
+/**
+ * Normalize one imported memory through the same bounds a locally-created one
+ * gets. A bundle is a file from another machine: its records are foreign input,
+ * not trusted rows, so anything that is not a usable record is dropped here
+ * rather than handed to the memory backend.
+ */
+function normalizeImportedMemory(raw) {
+ if (!isPlainRecord(raw)) return null;
+ const content = typeof raw.content === 'string' ? raw.content.trim().slice(0, IMPORTED_MEMORY_CONTENT_MAX) : '';
+ if (!content) return null;
+ return {
+ type: typeof raw.type === 'string' && raw.type.trim() ? raw.type.trim().slice(0, IMPORTED_MEMORY_TYPE_MAX) : 'observation',
+ content,
+ // Protection is preserved, but only within the tiers this export ships.
+ // Anything else lands on `important` rather than silently becoming
+ // `standard`, which the next bulk cleanup would delete.
+ protection: EXPORTABLE_PROTECTIONS.has(raw.protection) ? raw.protection : 'important',
+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : null,
+ };
+}
+
+/**
+ * Decode and structurally check the entries a bundle carries.
+ *
+ * Every declared scope must be present and parse; a bundle that declares
+ * `memories` and carries no `memories.json` is damaged, not "a bundle with no
+ * memories". An entry this build does not recognize is a refusal too — quietly
+ * ignoring it is the "apply the parts I happen to understand" behaviour the
+ * epic rules out.
+ */
+function decodeBundleEntries({ header, entries }) {
+ const decoded = {};
+ for (const entry of entries) {
+ const scope = SCOPE_BY_ENTRY_NAME[entry.name];
+ if (!scope) {
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.UNKNOWN_SCOPE, `Mind bundle carries an entry this install does not understand ("${entry.name}")`);
+ }
+ if (!header.scopes.includes(scope)) {
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.UNKNOWN_SCOPE, `Mind bundle carries a "${scope}" entry it never declared`);
+ }
+ const parsed = JSON.parse(entry.data.toString('utf8'));
+ if (!isPlainRecord(parsed)) {
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, `Mind bundle entry "${entry.name}" is not a record`);
+ }
+ decoded[scope] = parsed;
+ }
+ for (const scope of header.scopes) {
+ if (!decoded[scope]) {
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, `Mind bundle declares the "${scope}" scope but carries no ${MIND_BUNDLE_ENTRY_NAMES[scope]}`);
+ }
+ }
+ return decoded;
+}
+
+/**
+ * Translate any open-path failure into a named, user-readable refusal.
+ *
+ * The reason rides `context`, which is what reaches the client on the standard
+ * error envelope — so "refuse by name" survives the trip and the panel can say
+ * WHICH refusal it hit rather than "could not open". An untagged throw is a
+ * damaged file: every distinguishable failure above already carries its name.
+ */
+const refuse = (error) => new ServerError(
+ error?.message || 'Could not open this Mind bundle',
+ {
+ status: 400,
+ code: 'MIND_BUNDLE_REFUSED',
+ context: { reason: error?.mindBundleReason || MIND_BUNDLE_REFUSALS.DAMAGED },
+ },
+);
+
+/**
+ * Decrypt a bundle and decode it. Writes nothing — every caller, preview and
+ * apply alike, starts here, so apply never trusts a preview the client could
+ * have edited on its way back.
+ */
+const readBundle = ({ text, passphrase }) => Promise.resolve()
+ .then(() => openMindBundle({ text, passphrase }))
+ .then((result) => ({ header: result.header, scopes: decodeBundleEntries(result) }))
+ .catch((error) => { throw refuse(error); });
+
+/** What this install currently holds, in the same shapes the bundle carries. */
+async function readCurrentGroups() {
+ const root = await loadState();
+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
+ const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
+ const playbook = normalizePersistentMindPlaybook(root.config?.persistentMindPlaybook);
+ const style = root.config?.avatarStyle;
+ const [chosenName, memories] = await Promise.all([
+ readPersistentMindName(PERSISTENT_MIND_ID),
+ readPersistentMindMemories(PERSISTENT_MIND_ID),
+ ]);
+ return {
+ identity: { chosenName: chosenName || null },
+ personality: { identity: prompt.identity, instructions: prompt.instructions },
+ playbook: { mode: playbook.mode, customInstructions: playbook.customInstructions },
+ modelPolicy: {
+ providerId: profile.providerId || null,
+ model: profile.model || null,
+ effort: profile.effort || null,
+ thinkingInterface: profile.thinkingInterface,
+ wakeIntervalMinutes: profile.wakeIntervalMinutes,
+ },
+ avatar: { style: AVATAR_STYLE_IDS.includes(style) ? style : null },
+ memories,
+ };
+}
+
+/**
+ * The incoming value for each group, normalized through the same functions
+ * that guard a locally-saved one — so a hand-edited bundle cannot put a shape
+ * into config that the UI and the wake loop would then have to survive.
+ *
+ * A group whose bundle value carries nothing usable is simply absent: offering
+ * "use imported" for a name the bundle does not have would let a confirm wipe
+ * the destination's own name with nothing.
+ */
+function incomingGroups(scopeData) {
+ const groups = {};
+ const profile = scopeData.profile;
+ if (profile) {
+ const chosenName = typeof profile.chosenName === 'string' ? profile.chosenName.trim() : '';
+ if (chosenName) groups.identity = { chosenName };
+ const soul = normalizePersistentMindPrompt(profile.soul);
+ groups.personality = { identity: soul.identity, instructions: soul.instructions };
+ const playbook = normalizePersistentMindPlaybook(profile.playbook);
+ groups.playbook = { mode: playbook.mode, customInstructions: playbook.customInstructions };
+ // `enabled` is never read off a bundle: importing a Mind must not start one.
+ const policy = normalizePersistentMindProfile({ ...(isPlainRecord(profile.modelPolicy) ? profile.modelPolicy : {}), enabled: false });
+ groups.modelPolicy = {
+ providerId: policy.providerId || null,
+ model: policy.model || null,
+ effort: policy.effort || null,
+ thinkingInterface: policy.thinkingInterface,
+ wakeIntervalMinutes: policy.wakeIntervalMinutes,
+ };
+ }
+ if (scopeData.avatar) {
+ const style = scopeData.avatar.style;
+ if (AVATAR_STYLE_IDS.includes(style)) groups.avatar = { style };
+ }
+ if (scopeData.memories) {
+ const raw = Array.isArray(scopeData.memories.memories) ? scopeData.memories.memories : [];
+ groups.memories = raw.slice(0, MIND_MEMORY_PAGE_LIMIT).map(normalizeImportedMemory).filter(Boolean);
+ }
+ return groups;
+}
+
+/**
+ * The chosen name also travels as a protected memory record (the export ships
+ * every protected record, and the name is one). Importing both would plant a
+ * second, untagged copy of the name as an ordinary identity memory. The
+ * `identity` group owns the name, so the memories group skips it.
+ */
+const memoryIsTheChosenName = (memory, incomingName) => Boolean(incomingName) && memory.content === incomingName;
+
+function planMemoryImport(incomingMemories, currentMemories, incomingName) {
+ const existing = new Set((currentMemories || []).map((memory) => memory.content));
+ const seen = new Set();
+ const additions = [];
+ let duplicates = 0;
+ for (const memory of incomingMemories) {
+ if (memoryIsTheChosenName(memory, incomingName) || existing.has(memory.content) || seen.has(memory.content)) {
+ duplicates += 1;
+ continue;
+ }
+ seen.add(memory.content);
+ additions.push(memory);
+ }
+ return { additions, duplicates };
+}
+
+/**
+ * Open a bundle and report, group by group, what it carries beside what this
+ * install already holds. **Writes nothing.** The preview is what makes the
+ * apply step a decision rather than a leap.
+ */
+export async function previewPersistentMindBundle({ text, passphrase }) {
+ const { header, scopes } = await readBundle({ text, passphrase });
+ const incoming = incomingGroups(scopes);
+ const current = await readCurrentGroups();
+ const incomingName = incoming.identity?.chosenName || null;
+
+ const groups = PERSISTENT_MIND_BUNDLE_GROUPS
+ .filter((group) => incoming[group] !== undefined)
+ .map((group) => {
+ if (group === 'memories') {
+ const { additions, duplicates } = planMemoryImport(incoming.memories, current.memories, incomingName);
+ return {
+ group,
+ scope: MIND_BUNDLE_GROUP_SCOPES[group],
+ additive: true,
+ identical: additions.length === 0,
+ incoming: { total: incoming.memories.length, importable: additions.length, alreadyHere: duplicates, memories: additions },
+ current: { protectedCount: (current.memories || []).filter((memory) => EXPORTABLE_PROTECTIONS.has(memory.protection)).length },
+ };
+ }
+ return {
+ group,
+ scope: MIND_BUNDLE_GROUP_SCOPES[group],
+ additive: false,
+ identical: sameValue(incoming[group], current[group]),
+ incoming: incoming[group],
+ current: current[group],
+ };
+ });
+
+ console.log(`🔓 Previewed Persistent Mind bundle (scopes: ${header.scopes.join(', ')}; groups: ${groups.length})`);
+ return { createdAt: header.createdAt || null, scopes: header.scopes, groups };
+}
+
+/**
+ * Apply a bundle under the user's per-group choices. The ONLY write path.
+ *
+ * Everything is validated before the first write: a choice naming a group the
+ * bundle does not carry is a refusal, not an ignored key, so a client out of
+ * step with this build cannot half-apply. What it cannot promise is atomicity
+ * across a config file and Postgres, so the response names exactly which groups
+ * landed — a partial failure reports what it did rather than implying nothing
+ * happened.
+ */
+export async function applyPersistentMindBundle({ text, passphrase, choices }) {
+ const { scopes } = await readBundle({ text, passphrase });
+ const incoming = incomingGroups(scopes);
+ const selection = isPlainRecord(choices) ? choices : {};
+
+ const unknown = Object.keys(selection).filter((group) => incoming[group] === undefined);
+ if (unknown.length > 0) {
+ throw new ServerError(`This bundle does not carry ${unknown.join(', ')}. Nothing was applied — reopen the bundle and choose again.`, {
+ status: 409,
+ code: 'MIND_BUNDLE_UNKNOWN_GROUP',
+ });
+ }
+ // A group the user did not answer keeps this install's value. Silence is
+ // never consent to overwrite a personality.
+ const taking = PERSISTENT_MIND_BUNDLE_GROUPS.filter((group) => incoming[group] !== undefined && selection[group] === 'use-imported');
+ if (taking.length === 0) {
+ return { applied: [], kept: PERSISTENT_MIND_BUNDLE_GROUPS.filter((group) => incoming[group] !== undefined), memories: { imported: 0, skipped: 0 } };
+ }
+
+ const configPatch = {};
+ if (taking.includes('personality')) configPatch.persistentMindPrompt = incoming.personality;
+ if (taking.includes('playbook')) configPatch.persistentMindPlaybook = incoming.playbook;
+ if (taking.includes('modelPolicy')) {
+ const { providerId, model, effort, thinkingInterface, wakeIntervalMinutes } = incoming.modelPolicy;
+ // `enabled` is deliberately absent from the patch so the merge preserves
+ // whatever this install already decided about running its Mind.
+ configPatch.persistentMindProfile = {
+ providerId: providerId || '', model: model || '', effort: effort || '', thinkingInterface, wakeIntervalMinutes,
+ };
+ }
+ if (taking.includes('avatar')) configPatch.avatarStyle = incoming.avatar.style;
+
+ const applied = [];
+ if (Object.keys(configPatch).length > 0) {
+ // Lazily imported: applying a bundle is a rare, explicitly-clicked path,
+ // and `cos.js` is a heavy closure that every suite reaching this module
+ // would otherwise pay for (server/AGENTS.md "Import scoping").
+ const { updateConfig } = await import('./cos.js');
+ await updateConfig(configPatch);
+ applied.push(...taking.filter((group) => group !== 'identity' && group !== 'memories'));
+ }
+
+ if (taking.includes('identity')) {
+ await choosePersistentMindName({ name: incoming.identity.chosenName }, PERSISTENT_MIND_ID);
+ applied.push('identity');
+ }
+
+ let imported = 0;
+ let skipped = 0;
+ if (taking.includes('memories')) {
+ const current = await readPersistentMindMemories(PERSISTENT_MIND_ID);
+ const { additions, duplicates } = planMemoryImport(incoming.memories, current, incoming.identity?.chosenName || null);
+ skipped = duplicates;
+ for (const memory of additions) {
+ // Sequential, not `Promise.all`: these share one write queue, and a
+ // partial failure must leave a countable prefix rather than a scramble.
+ await createPersistentMindMemory({
+ mindId: PERSISTENT_MIND_ID,
+ type: memory.type,
+ content: memory.content,
+ category: 'other',
+ protection: memory.protection,
+ });
+ imported += 1;
+ }
+ applied.push('memories');
+ }
+ const memories = { imported, skipped };
+
+ const kept = PERSISTENT_MIND_BUNDLE_GROUPS.filter((group) => incoming[group] !== undefined && !applied.includes(group));
+ console.log(`📥 Applied Persistent Mind bundle (used: ${applied.join(', ') || 'none'}; kept: ${kept.join(', ') || 'none'}; memories: +${memories.imported})`);
+ return { applied, kept, memories };
+}
diff --git a/server/services/persistentMindBundle.test.js b/server/services/persistentMindBundle.test.js
index ada981d3f5..8762b3b9d9 100644
--- a/server/services/persistentMindBundle.test.js
+++ b/server/services/persistentMindBundle.test.js
@@ -1,21 +1,32 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
-import { openMindBundle, readMindBundleHeader } from '../lib/mindBundleCrypto.js';
+import { openMindBundle, readMindBundleHeader, sealMindBundle } from '../lib/mindBundleCrypto.js';
+import { MIND_BUNDLE_REFUSALS } from '../lib/mindBundleFormat.js';
const loadState = vi.fn();
const readPersistentMindMemories = vi.fn();
const readPersistentMindName = vi.fn();
+const choosePersistentMindName = vi.fn();
+const createPersistentMindMemory = vi.fn();
+const updateConfig = vi.fn();
vi.mock('./cosState.js', () => ({ loadState: (...args) => loadState(...args) }));
vi.mock('./persistentMindContext.js', () => ({
+ choosePersistentMindName: (...args) => choosePersistentMindName(...args),
+ createPersistentMindMemory: (...args) => createPersistentMindMemory(...args),
readPersistentMindMemories: (...args) => readPersistentMindMemories(...args),
readPersistentMindName: (...args) => readPersistentMindName(...args),
}));
+// `applyPersistentMindBundle` reaches `updateConfig` through a lazy
+// `await import()` (import scoping); vitest's mock registry covers that too.
+vi.mock('./cos.js', () => ({ updateConfig: (...args) => updateConfig(...args) }));
const {
+ applyPersistentMindBundle,
collectPersistentMindBundleEntries,
exportPersistentMindBundle,
mindBundleFilename,
normalizeMindBundleScopes,
+ previewPersistentMindBundle,
} = await import('./persistentMindBundle.js');
const PASSPHRASE = 'an example bundle passphrase';
@@ -184,3 +195,207 @@ describe('persistentMindBundle refusal', () => {
expect(header.manifest).toEqual([{ name: 'profile.json', bytes: expect.any(Number) }]);
});
});
+
+/* ------------------------------------------------------------------ import */
+
+// A bundle from an obviously-fake OTHER install. Built with the sealer rather
+// than by re-exporting this install, so an import assertion cannot pass just
+// because both sides happen to read the same mock.
+const OTHER_MIND = {
+ chosenName: 'Other Example Mind',
+ soul: { identity: 'I am a different example Mind.', instructions: 'Answer in one paragraph.' },
+ playbook: { mode: 'default', customInstructions: '' },
+ modelPolicy: { providerId: 'other-provider', model: 'other-model', effort: 'low', thinkingInterface: 'text', wakeIntervalMinutes: 90 },
+};
+const OTHER_MEMORIES = [
+ { type: 'fact', content: 'The other example user ships on Tuesdays.', protection: 'core-identity', createdAt: '2026-08-01T09:00:00.000Z' },
+ { type: 'observation', content: 'The other example user dislikes long meetings.', protection: 'important', createdAt: '2026-08-02T09:00:00.000Z' },
+];
+
+const sealOther = ({ profile = OTHER_MIND, avatar = { style: 'svg' }, memories = OTHER_MEMORIES, scopes = ['profile', 'avatar', 'memories'] } = {}) => {
+ const documents = { profile: ['profile.json', profile], avatar: ['avatar.json', avatar], memories: ['memories.json', { memories }] };
+ return sealMindBundle({
+ scopes,
+ passphrase: PASSPHRASE,
+ entries: scopes.map((scope) => ({ name: documents[scope][0], data: JSON.stringify(documents[scope][1]) })),
+ });
+};
+
+const noWrites = () => {
+ expect(updateConfig).not.toHaveBeenCalled();
+ expect(choosePersistentMindName).not.toHaveBeenCalled();
+ expect(createPersistentMindMemory).not.toHaveBeenCalled();
+};
+
+describe('persistentMindBundle preview', () => {
+ it('writes nothing, and reports each group beside what this install holds', async () => {
+ const preview = await previewPersistentMindBundle({ text: await sealOther(), passphrase: PASSPHRASE });
+ noWrites();
+
+ expect(preview.scopes).toEqual(['profile', 'avatar', 'memories']);
+ expect(preview.groups.map(({ group }) => group))
+ .toEqual(['identity', 'personality', 'playbook', 'modelPolicy', 'avatar', 'memories']);
+
+ const identity = preview.groups.find(({ group }) => group === 'identity');
+ expect(identity.incoming).toEqual({ chosenName: 'Other Example Mind' });
+ expect(identity.current).toEqual({ chosenName: 'Example Mind' });
+ expect(identity.identical).toBe(false);
+ });
+
+ it('marks a group whose two sides match, so a choice there is visibly a no-op', async () => {
+ const text = await sealOther({ profile: { ...OTHER_MIND, chosenName: 'Example Mind' }, scopes: ['profile'] });
+ const preview = await previewPersistentMindBundle({ text, passphrase: PASSPHRASE });
+ expect(preview.groups.find(({ group }) => group === 'identity').identical).toBe(true);
+ expect(preview.groups.find(({ group }) => group === 'personality').identical).toBe(false);
+ });
+
+ it('counts an incoming memory this install already holds as already-here, not importable', async () => {
+ const shared = { type: 'fact', content: 'The example user reviews plans on Friday afternoons.', protection: 'core-identity' };
+ const text = await sealOther({ memories: [shared, ...OTHER_MEMORIES], scopes: ['memories'] });
+ const { incoming } = (await previewPersistentMindBundle({ text, passphrase: PASSPHRASE }))
+ .groups.find(({ group }) => group === 'memories');
+ expect(incoming).toMatchObject({ total: 3, importable: 2, alreadyHere: 1 });
+ expect(incoming.memories.map(({ content }) => content)).not.toContain(shared.content);
+ });
+
+ it('omits a group the bundle carries nothing usable for, so no choice can clear it with nothing', async () => {
+ const text = await sealOther({ profile: { ...OTHER_MIND, chosenName: ' ' }, avatar: { style: 'not-a-shipped-style' } });
+ const groups = (await previewPersistentMindBundle({ text, passphrase: PASSPHRASE })).groups.map(({ group }) => group);
+ expect(groups).not.toContain('identity');
+ expect(groups).not.toContain('avatar');
+ expect(groups).toContain('personality');
+ });
+});
+
+describe('persistentMindBundle import refusal', () => {
+ it('refuses a newer container version by name, and applies nothing', async () => {
+ const sealed = await sealOther();
+ const [magicLine, ...rest] = sealed.split('\n');
+ const text = [magicLine.replace(/\/1$/, '/99'), ...rest].join('\n');
+
+ await expect(previewPersistentMindBundle({ text, passphrase: PASSPHRASE }))
+ .rejects.toMatchObject({ code: 'MIND_BUNDLE_REFUSED', context: { reason: MIND_BUNDLE_REFUSALS.VERSION_UNSUPPORTED } });
+ await expect(applyPersistentMindBundle({ text, passphrase: PASSPHRASE, choices: { personality: 'use-imported' } }))
+ .rejects.toMatchObject({ context: { reason: MIND_BUNDLE_REFUSALS.VERSION_UNSUPPORTED } });
+ noWrites();
+ });
+
+ it('fails a tampered bundle before any write, without saying which of the two went wrong', async () => {
+ const sealed = await sealOther();
+ const lines = sealed.split('\n');
+ // Flip one base64 character of the ciphertext.
+ lines[2] = (lines[2][0] === 'A' ? 'B' : 'A') + lines[2].slice(1);
+ const tampered = lines.join('\n');
+
+ const refusal = await applyPersistentMindBundle({ text: tampered, passphrase: PASSPHRASE, choices: { identity: 'use-imported' } })
+ .catch((error) => error);
+ expect(refusal.context.reason).toBe(MIND_BUNDLE_REFUSALS.AUTH_FAILED);
+ // One reason covers both causes on purpose: naming which would make the
+ // refusal an oracle for anyone holding the file.
+ expect(refusal.message).toMatch(/passphrase is wrong, or the file changed/);
+ noWrites();
+
+ const wrongPassphrase = await previewPersistentMindBundle({ text: sealed, passphrase: 'a different long passphrase' })
+ .catch((error) => error);
+ expect(wrongPassphrase.context.reason).toBe(MIND_BUNDLE_REFUSALS.AUTH_FAILED);
+ });
+
+ it('refuses a choice naming a group the bundle does not carry, rather than ignoring the key', async () => {
+ const text = await sealOther({ scopes: ['avatar'] });
+ await expect(applyPersistentMindBundle({ text, passphrase: PASSPHRASE, choices: { personality: 'use-imported' } }))
+ .rejects.toMatchObject({ code: 'MIND_BUNDLE_UNKNOWN_GROUP', status: 409 });
+ noWrites();
+ });
+});
+
+describe('persistentMindBundle apply', () => {
+ it('writes nothing when every group keeps this install\'s value', async () => {
+ const result = await applyPersistentMindBundle({
+ text: await sealOther(),
+ passphrase: PASSPHRASE,
+ choices: { identity: 'keep-mine', personality: 'keep-mine', playbook: 'keep-mine', modelPolicy: 'keep-mine', avatar: 'keep-mine', memories: 'keep-mine' },
+ });
+ expect(result.applied).toEqual([]);
+ noWrites();
+ });
+
+ it('treats an unanswered group as keep-mine — silence never overwrites a personality', async () => {
+ const result = await applyPersistentMindBundle({ text: await sealOther(), passphrase: PASSPHRASE, choices: {} });
+ expect(result.applied).toEqual([]);
+ noWrites();
+ });
+
+ it('replaces exactly the chosen group and no other', async () => {
+ const result = await applyPersistentMindBundle({
+ text: await sealOther(),
+ passphrase: PASSPHRASE,
+ choices: { personality: 'use-imported', identity: 'keep-mine', avatar: 'keep-mine' },
+ });
+
+ expect(result.applied).toEqual(['personality']);
+ expect(updateConfig).toHaveBeenCalledTimes(1);
+ // Only the personality key: taking one group must not carry the playbook,
+ // the model policy, or the avatar along with it.
+ expect(Object.keys(updateConfig.mock.calls[0][0])).toEqual(['persistentMindPrompt']);
+ expect(updateConfig.mock.calls[0][0].persistentMindPrompt).toEqual(OTHER_MIND.soul);
+ expect(choosePersistentMindName).not.toHaveBeenCalled();
+ expect(createPersistentMindMemory).not.toHaveBeenCalled();
+ });
+
+ it('never carries `enabled` in with a model policy — importing a Mind must not start one', async () => {
+ await applyPersistentMindBundle({
+ text: await sealOther({ profile: { ...OTHER_MIND, modelPolicy: { ...OTHER_MIND.modelPolicy, enabled: true } }, scopes: ['profile'] }),
+ passphrase: PASSPHRASE,
+ choices: { modelPolicy: 'use-imported' },
+ });
+ const patch = updateConfig.mock.calls[0][0].persistentMindProfile;
+ expect(patch).toEqual({ providerId: 'other-provider', model: 'other-model', effort: 'low', thinkingInterface: 'text', wakeIntervalMinutes: 90 });
+ expect(patch).not.toHaveProperty('enabled');
+ });
+
+ it('writes the chosen name through the name writer, not as a raw config key', async () => {
+ await applyPersistentMindBundle({ text: await sealOther({ scopes: ['profile'] }), passphrase: PASSPHRASE, choices: { identity: 'use-imported' } });
+ expect(choosePersistentMindName).toHaveBeenCalledWith({ name: 'Other Example Mind' }, 'cos-persistent-mind');
+ });
+
+ it('appends memories with their protection preserved, deleting and rewriting nothing', async () => {
+ const result = await applyPersistentMindBundle({
+ text: await sealOther({ scopes: ['memories'] }),
+ passphrase: PASSPHRASE,
+ choices: { memories: 'use-imported' },
+ });
+
+ expect(result.memories).toEqual({ imported: 2, skipped: 0 });
+ expect(createPersistentMindMemory).toHaveBeenCalledTimes(2);
+ expect(createPersistentMindMemory.mock.calls.map(([input]) => [input.content, input.protection])).toEqual([
+ ['The other example user ships on Tuesdays.', 'core-identity'],
+ ['The other example user dislikes long meetings.', 'important'],
+ ]);
+ // Additive only: no update/delete path exists for this group.
+ expect(updateConfig).not.toHaveBeenCalled();
+ });
+
+ it('skips a content-identical memory rather than duplicating it', async () => {
+ const shared = { type: 'fact', content: 'The example user reviews plans on Friday afternoons.', protection: 'core-identity' };
+ const result = await applyPersistentMindBundle({
+ text: await sealOther({ memories: [shared, ...OTHER_MEMORIES], scopes: ['memories'] }),
+ passphrase: PASSPHRASE,
+ choices: { memories: 'use-imported' },
+ });
+
+ expect(result.memories).toEqual({ imported: 2, skipped: 1 });
+ expect(createPersistentMindMemory.mock.calls.map(([input]) => input.content)).not.toContain(shared.content);
+ });
+
+ it('does not plant the chosen name a second time as an ordinary memory', async () => {
+ // The export ships every protected record, and the chosen name IS one, so
+ // a round trip carries it in both `identity` and `memories`.
+ const nameRecord = { type: 'fact', content: OTHER_MIND.chosenName, protection: 'core-identity' };
+ await applyPersistentMindBundle({
+ text: await sealOther({ memories: [nameRecord, ...OTHER_MEMORIES] }),
+ passphrase: PASSPHRASE,
+ choices: { identity: 'use-imported', memories: 'use-imported' },
+ });
+ expect(createPersistentMindMemory.mock.calls.map(([input]) => input.content)).not.toContain(OTHER_MIND.chosenName);
+ });
+});