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

fix: address review (opencode) — refuse a hand-built bundle instead of importing part of it (#7622)

[._.]/ Adam Eivy99f96cb7b9e0
diff --git a/client/src/components/cos/PersistentMindImportPanel.jsx b/client/src/components/cos/PersistentMindImportPanel.jsx
index dd9fecd039..60bcbfd0ec 100644
--- a/client/src/components/cos/PersistentMindImportPanel.jsx
+++ b/client/src/components/cos/PersistentMindImportPanel.jsx
@@ -62,6 +62,10 @@ function GroupValue({ value, empty = 'Nothing set' }) {
export default function PersistentMindImportPanel() {
const idPrefix = useId();
const [file, setFile] = useState(null);
+ // Bumped after a successful apply to REMOUNT the file input. Clearing `file`
+ // only clears the label: the <input> keeps its DOM value, so re-picking the
+ // same file fires no change event and the panel looks stuck.
+ const [fileInputKey, setFileInputKey] = useState(0);
const [bundleText, setBundleText] = useState('');
const [passphrase, setPassphrase] = useState('');
const [preview, setPreview] = useState(null);
@@ -86,6 +90,9 @@ export default function PersistentMindImportPanel() {
setFile(picked);
setBundleText('');
if (!picked) return;
+ // `size` is bytes and the cap is characters. A bundle is base64 + JSON, so
+ // the two are equal in practice, and where they are not this errs toward
+ // rejecting early — the server bound is the authority either way.
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;
@@ -125,6 +132,7 @@ export default function PersistentMindImportPanel() {
setPassphrase('');
setBundleText('');
setFile(null);
+ setFileInputKey((current) => current + 1);
})
.catch((nextError) => setError(nextError?.message || 'Could not apply that bundle'))
.finally(() => setPending(null));
@@ -149,6 +157,7 @@ export default function PersistentMindImportPanel() {
<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
+ key={fileInputKey}
id={`${idPrefix}-file`}
type="file"
accept={MIND_BUNDLE_FILE_EXTENSION}
@@ -195,9 +204,11 @@ export default function PersistentMindImportPanel() {
<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 && '.'}
+ {/* `skipped` stands on its own: importing a bundle whose memories
+ you already hold adds nothing, and a bare "used the imported
+ memories" would read as though records had arrived. */}
+ {applied.memories.imported > 0 && ` Added ${formatCount(applied.memories.imported)} memories.`}
+ {applied.memories.skipped > 0 && ` ${formatCount(applied.memories.skipped)} were already here and were skipped.`}
</Banner>
</div>
)}
diff --git a/client/src/components/cos/PersistentMindImportPanel.test.jsx b/client/src/components/cos/PersistentMindImportPanel.test.jsx
index 6549164071..98ff0286a1 100644
--- a/client/src/components/cos/PersistentMindImportPanel.test.jsx
+++ b/client/src/components/cos/PersistentMindImportPanel.test.jsx
@@ -100,6 +100,20 @@ describe('PersistentMindImportPanel', () => {
expect(await screen.findByText(/Used the imported identity/)).toBeInTheDocument();
});
+ it('reports skipped memories even when nothing new was added', async () => {
+ api.applyPersistentMindBundle.mockResolvedValue({ applied: ['memories'], kept: [], memories: { imported: 0, skipped: 3 } });
+ const user = userEvent.setup();
+ render(<PersistentMindImportPanel />);
+ await openBundle(user);
+
+ await user.click(screen.getByRole('radio', { name: /Import them/ }));
+ await user.click(screen.getByRole('button', { name: /Apply these choices/ }));
+
+ // An all-duplicate import adds nothing; saying only "used the imported
+ // memories" would read as though records had arrived.
+ expect(await screen.findByText(/3 were already here and were skipped/)).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 />);
diff --git a/server/services/persistentMindBundle.js b/server/services/persistentMindBundle.js
index 42b43fb804..26ae3bf933 100644
--- a/server/services/persistentMindBundle.js
+++ b/server/services/persistentMindBundle.js
@@ -217,14 +217,20 @@ 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.
+ * gets. A bundle is a file from another machine, so its records are foreign
+ * input — but an unusable one REFUSES the bundle rather than vanishing from
+ * the set. Silently importing 9 of 10 memories is the same failure the export
+ * refuses to produce: the user believes they carried everything across, and
+ * finds out otherwise only once the source install is gone.
*/
-function normalizeImportedMemory(raw) {
- if (!isPlainRecord(raw)) return null;
+function normalizeImportedMemory(raw, index) {
+ if (!isPlainRecord(raw)) {
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, `Mind bundle memory #${index + 1} is not a record`);
+ }
const content = typeof raw.content === 'string' ? raw.content.trim().slice(0, IMPORTED_MEMORY_CONTENT_MAX) : '';
- if (!content) return null;
+ if (!content) {
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, `Mind bundle memory #${index + 1} carries no text`);
+ }
return {
type: typeof raw.type === 'string' && raw.type.trim() ? raw.type.trim().slice(0, IMPORTED_MEMORY_TYPE_MAX) : 'observation',
content,
@@ -255,6 +261,12 @@ function decodeBundleEntries({ header, entries }) {
if (!header.scopes.includes(scope)) {
throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.UNKNOWN_SCOPE, `Mind bundle carries a "${scope}" entry it never declared`);
}
+ if (decoded[scope]) {
+ // The sealer rejects duplicate names, so two entries for one scope means
+ // a hand-built file. "Last one wins" would let the winning copy be chosen
+ // by parse order rather than by anything the user can see.
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, `Mind bundle carries more than one "${entry.name}"`);
+ }
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`);
@@ -293,7 +305,9 @@ const refuse = (error) => new ServerError(
*/
const readBundle = ({ text, passphrase }) => Promise.resolve()
.then(() => openMindBundle({ text, passphrase }))
- .then((result) => ({ header: result.header, scopes: decodeBundleEntries(result) }))
+ // Group-building runs inside this chain, not after it: it validates the same
+ // foreign records, so its refusals need the same named translation.
+ .then((result) => ({ header: result.header, groups: incomingGroups(decodeBundleEntries(result)) }))
.catch((error) => { throw refuse(error); });
/** What this install currently holds, in the same shapes the bundle carries. */
@@ -338,19 +352,29 @@ function incomingGroups(scopeData) {
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,
- };
+ // Each of these is offered ONLY when the bundle carries the key. The
+ // normalizers turn an absent one into THIS build's shipped defaults, and a
+ // group presenting stock text as the other Mind's personality is how a
+ // confirm wipes an authored one with something nobody wrote.
+ if (isPlainRecord(profile.soul)) {
+ const soul = normalizePersistentMindPrompt(profile.soul);
+ groups.personality = { identity: soul.identity, instructions: soul.instructions };
+ }
+ if (isPlainRecord(profile.playbook)) {
+ const playbook = normalizePersistentMindPlaybook(profile.playbook);
+ groups.playbook = { mode: playbook.mode, customInstructions: playbook.customInstructions };
+ }
+ if (isPlainRecord(profile.modelPolicy)) {
+ // `enabled` is never read off a bundle: importing a Mind must not start one.
+ const policy = normalizePersistentMindProfile({ ...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;
@@ -358,7 +382,13 @@ function incomingGroups(scopeData) {
}
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);
+ if (raw.length > MIND_MEMORY_PAGE_LIMIT) {
+ // The exporter refuses rather than truncating, so an over-long set is a
+ // hand-built file. Importing its prefix would report a `total` that had
+ // already silently dropped the rest.
+ throw mindBundleRefusal(MIND_BUNDLE_REFUSALS.DAMAGED, `Mind bundle carries more memories than one bundle can hold (limit ${MIND_MEMORY_PAGE_LIMIT})`);
+ }
+ groups.memories = raw.map(normalizeImportedMemory);
}
return groups;
}
@@ -393,8 +423,7 @@ function planMemoryImport(incomingMemories, currentMemories, incomingName) {
* 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 { header, groups: incoming } = await readBundle({ text, passphrase });
const current = await readCurrentGroups();
const incomingName = incoming.identity?.chosenName || null;
@@ -437,8 +466,7 @@ export async function previewPersistentMindBundle({ text, passphrase }) {
* happened.
*/
export async function applyPersistentMindBundle({ text, passphrase, choices }) {
- const { scopes } = await readBundle({ text, passphrase });
- const incoming = incomingGroups(scopes);
+ const { groups: incoming } = await readBundle({ text, passphrase });
const selection = isPlainRecord(choices) ? choices : {};
const unknown = Object.keys(selection).filter((group) => incoming[group] === undefined);
diff --git a/server/services/persistentMindBundle.test.js b/server/services/persistentMindBundle.test.js
index 8762b3b9d9..9c7301a5d7 100644
--- a/server/services/persistentMindBundle.test.js
+++ b/server/services/persistentMindBundle.test.js
@@ -399,3 +399,63 @@ describe('persistentMindBundle apply', () => {
expect(createPersistentMindMemory.mock.calls.map(([input]) => input.content)).not.toContain(OTHER_MIND.chosenName);
});
});
+
+describe('persistentMindBundle import refuses a hand-built file rather than applying part of it', () => {
+ it('omits a profile group the bundle does not carry, instead of offering this build\'s defaults', async () => {
+ // Normalizing an absent `soul` yields the SHIPPED default identity. Offered
+ // as "use imported", a confirm would replace an authored personality with
+ // stock text presented as the other Mind's.
+ const text = await sealOther({ profile: { chosenName: 'Other Example Mind' }, scopes: ['profile'] });
+ const groups = (await previewPersistentMindBundle({ text, passphrase: PASSPHRASE })).groups.map(({ group }) => group);
+ expect(groups).toEqual(['identity']);
+
+ await expect(applyPersistentMindBundle({ text, passphrase: PASSPHRASE, choices: { personality: 'use-imported' } }))
+ .rejects.toMatchObject({ code: 'MIND_BUNDLE_UNKNOWN_GROUP' });
+ noWrites();
+ });
+
+ it('refuses an unusable memory record rather than importing the rest without it', async () => {
+ const text = await sealOther({ memories: [OTHER_MEMORIES[0], { type: 'fact', content: ' ' }], scopes: ['memories'] });
+ await expect(previewPersistentMindBundle({ text, passphrase: PASSPHRASE }))
+ .rejects.toMatchObject({ context: { reason: MIND_BUNDLE_REFUSALS.DAMAGED } });
+ await expect(applyPersistentMindBundle({ text, passphrase: PASSPHRASE, choices: { memories: 'use-imported' } }))
+ .rejects.toMatchObject({ context: { reason: MIND_BUNDLE_REFUSALS.DAMAGED } });
+ noWrites();
+ });
+
+ it('refuses more memories than one bundle can hold, rather than importing a silent prefix', async () => {
+ const memories = Array.from({ length: 101 }, (_unused, index) => ({
+ type: 'fact', content: `Example protected memory ${index}`, protection: 'important',
+ }));
+ await expect(previewPersistentMindBundle({ text: await sealOther({ memories, scopes: ['memories'] }), passphrase: PASSPHRASE }))
+ .rejects.toThrow(/more memories than one bundle can hold/);
+ noWrites();
+ });
+
+ it('refuses an entry for a scope the bundle never declared, rather than applying it anyway', async () => {
+ const text = await sealMindBundle({
+ scopes: ['profile'],
+ passphrase: PASSPHRASE,
+ entries: [
+ { name: 'profile.json', data: JSON.stringify(OTHER_MIND) },
+ // Sealed but undeclared: the cleartext header is what a destination
+ // refuses on, so an entry outside it must not sneak a group in.
+ { name: 'avatar.json', data: JSON.stringify({ style: 'svg' }) },
+ ],
+ });
+ await expect(previewPersistentMindBundle({ text, passphrase: PASSPHRASE }))
+ .rejects.toMatchObject({ context: { reason: MIND_BUNDLE_REFUSALS.UNKNOWN_SCOPE } });
+ noWrites();
+ });
+
+ it('refuses a declared scope whose entry is missing, rather than reading it as empty', async () => {
+ const text = await sealMindBundle({
+ scopes: ['profile', 'memories'],
+ passphrase: PASSPHRASE,
+ entries: [{ name: 'profile.json', data: JSON.stringify(OTHER_MIND) }],
+ });
+ await expect(previewPersistentMindBundle({ text, passphrase: PASSPHRASE }))
+ .rejects.toThrow(/declares the "memories" scope but carries no memories.json/);
+ noWrites();
+ });
+});