Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(memory): carry everything a store holds when switching engines

Shanu33d2efdde6e3
diff --git a/app/src/components/settings/panels/MemoryEnginePanel.test.tsx b/app/src/components/settings/panels/MemoryEnginePanel.test.tsx
index 94dfade024..add403aa4e 100644
--- a/app/src/components/settings/panels/MemoryEnginePanel.test.tsx
+++ b/app/src/components/settings/panels/MemoryEnginePanel.test.tsx
@@ -15,6 +15,7 @@ import { resetMemoryEngineCacheForTests } from '../../intelligence/useMemoryEngi
import MemoryEnginePanel, {
MIGRATE_JOB_STORAGE_KEY,
MIGRATE_POLL_INTERVAL_MS,
+ stepsLeftBehind,
} from './MemoryEnginePanel';
const hoisted = vi.hoisted(() => ({
@@ -209,11 +210,10 @@ describe('MemoryEnginePanel', () => {
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
- expect(hoisted.migrate).toHaveBeenCalledWith({
- driver: 'mem0',
- endpoint: 'https://api.mem0.ai',
- deployment: 'cloud',
- });
+ expect(hoisted.migrate).toHaveBeenCalledWith(
+ { driver: 'mem0', endpoint: 'https://api.mem0.ai', deployment: 'cloud' },
+ { replayContent: true }
+ );
expect(screen.getByTestId('memory-engine-progress')).toBeInTheDocument();
await act(async () => {
@@ -371,4 +371,136 @@ describe('MemoryEnginePanel', () => {
fireEvent.click(await screen.findByTestId('memory-engine-copy-switch'));
await waitFor(() => expect(hoisted.storage.get(MIGRATE_JOB_STORAGE_KEY)).toContain('job-p'));
});
+
+ test('the copy can leave synced content behind, and the hint shows for hosted engines', async () => {
+ vi.useFakeTimers();
+ hoisted.migrate.mockResolvedValue({ job_id: 'job-h' });
+ hoisted.status.mockResolvedValue({ state: 'running', copied: 0, total: null, error: null });
+ renderWithProviders(<MemoryEnginePanel />);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ pick('tinyhumans');
+ fireEvent.click(screen.getByTestId('memory-engine-switch'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ const dialog = screen.getByTestId('memory-engine-switch-dialog');
+ expect(dialog).toHaveTextContent('conversation history');
+ expect(dialog).toHaveTextContent('OpenHuman credits');
+ const replay = screen.getByTestId('memory-engine-replay-content');
+ expect(replay).toBeChecked();
+ fireEvent.click(replay);
+ expect(replay).not.toBeChecked();
+ fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(hoisted.migrate).toHaveBeenCalledWith(
+ { driver: 'tinyhumans' },
+ { replayContent: false }
+ );
+ });
+
+ test('the progress line names the step under way', async () => {
+ vi.useFakeTimers();
+ hoisted.migrate.mockResolvedValue({ job_id: 'job-s' });
+ hoisted.status.mockResolvedValue({
+ state: 'running',
+ copied: 12,
+ total: null,
+ error: null,
+ step: 'episodic',
+ step_read: 40,
+ step_written: 38,
+ steps: [],
+ });
+ renderWithProviders(<MemoryEnginePanel />);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ pick('mem0');
+ fireEvent.click(screen.getByTestId('memory-engine-switch'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);
+ });
+ expect(screen.getByTestId('memory-engine-progress-line')).toHaveTextContent(
+ 'Copying conversation history… 40 so far'
+ );
+ });
+
+ test('after the switch, what the new engine could not take is named', async () => {
+ vi.useFakeTimers();
+ hoisted.migrate.mockResolvedValue({ job_id: 'job-l' });
+ const skipped = (step: string) => ({
+ step,
+ skipped_because: 'the target does not serve it',
+ read: 0,
+ written: 0,
+ unchanged: 0,
+ failed: 0,
+ errors: [],
+ });
+ hoisted.status.mockResolvedValue({
+ state: 'done',
+ copied: 4,
+ total: null,
+ error: null,
+ steps: [skipped('goals'), skipped('profile')],
+ });
+ renderWithProviders(<MemoryEnginePanel />);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ pick('mem0');
+ fireEvent.click(screen.getByTestId('memory-engine-switch'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ hoisted.get.mockResolvedValue(state({ driver: 'mem0', endpoint: 'https://api.mem0.ai' }));
+ fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(screen.getByTestId('memory-engine-left-behind')).toHaveTextContent(
+ 'goals, learned profile'
+ );
+ });
+});
+
+describe('stepsLeftBehind', () => {
+ const step = (name: 'content' | 'goals', skipped: string | null) => ({
+ step: name,
+ skipped_because: skipped,
+ read: 0,
+ written: 0,
+ unchanged: 0,
+ failed: 0,
+ errors: [],
+ });
+
+ test('content the user chose not to re-send is not left behind', () => {
+ const status = {
+ state: 'done' as const,
+ copied: 0,
+ total: null,
+ error: null,
+ steps: [step('content', 'the caller chose not to re-send content'), step('goals', null)],
+ };
+ expect(stepsLeftBehind(status, false)).toEqual([]);
+ expect(stepsLeftBehind(status, true)).toEqual(['content']);
+ });
});
diff --git a/app/src/components/settings/panels/MemoryEnginePanel.tsx b/app/src/components/settings/panels/MemoryEnginePanel.tsx
index 6df095de3d..1603a48914 100644
--- a/app/src/components/settings/panels/MemoryEnginePanel.tsx
+++ b/app/src/components/settings/panels/MemoryEnginePanel.tsx
@@ -22,6 +22,7 @@ import {
memoryEngineMigrateCancel,
memoryEngineMigrateStatus,
type MemoryEngineMigrateStatus,
+ type MemoryEngineMigrateStep,
memoryEngineSet,
type MemoryEngineState,
type MemoryEngineTarget,
@@ -45,6 +46,21 @@ import {
const log = debug('settings:memory-engine');
+/**
+ * The steps a finished copy skipped because the new engine (or the old one)
+ * does not serve them. Content the user chose not to re-send is not "left
+ * behind": they asked for that.
+ */
+export function stepsLeftBehind(
+ status: MemoryEngineMigrateStatus,
+ replayContent: boolean
+): MemoryEngineMigrateStep[] {
+ return (status.steps ?? [])
+ .filter(step => step.skipped_because !== null)
+ .filter(step => replayContent || step.step !== 'content')
+ .map(step => step.step);
+}
+
/** How often a running migration is polled. */
export const MIGRATE_POLL_INTERVAL_MS = 1000;
@@ -110,6 +126,12 @@ export default function MemoryEnginePanel() {
const [confirming, setConfirming] = useState(false);
const [jobId, setJobId] = useState<string | null>(null);
const [migration, setMigration] = useState<MemoryEngineMigrateStatus | null>(null);
+ // Re-send synced content with the copy (the content step); on unless the user opts out.
+ const [replayContent, setReplayContent] = useState(true);
+ // What a finished copy could not carry, shown once the switch is done.
+ const [leftBehind, setLeftBehind] = useState<MemoryEngineMigrateStep[]>([]);
+ // The replay choice the running job was started with (polling outlives the toggle).
+ const replayRequestedRef = useRef(true);
const mounted = useRef(true);
// Driver the running migration is copying into (finishSwitch needs it after polling).
const targetDriverRef = useRef<string>('');
@@ -250,8 +272,15 @@ export default function MemoryEnginePanel() {
setError(null);
try {
targetDriverRef.current = target.driver;
- const { job_id } = await memoryEngineMigrate(target);
- log('migrate started job=%s driver=%s', job_id, target.driver);
+ setLeftBehind([]);
+ replayRequestedRef.current = replayContent;
+ const { job_id } = await memoryEngineMigrate(target, { replayContent });
+ log(
+ 'migrate started job=%s driver=%s replay_content=%s',
+ job_id,
+ target.driver,
+ replayContent
+ );
if (!mounted.current) return;
setMigration({ state: 'running', copied: 0, total: null, error: null });
setJobId(job_id);
@@ -285,6 +314,7 @@ export default function MemoryEnginePanel() {
log('migrate done job=%s copied=%d', jobId, status.copied);
invalidateMemoryEngine();
await finishSwitch(targetDriverRef.current);
+ if (mounted.current) setLeftBehind(stepsLeftBehind(status, replayRequestedRef.current));
} else if (status.state === 'cancelled') {
log('migrate cancelled job=%s', jobId);
void clearStoredJob();
@@ -355,6 +385,17 @@ export default function MemoryEnginePanel() {
</Alert>
) : null}
+ {leftBehind.length > 0 ? (
+ <Alert variant="info" data-testid="memory-engine-left-behind">
+ <AlertDescription>
+ {t('memoryEngine.notCopied').replace(
+ '{items}',
+ leftBehind.map(step => t(`memoryEngine.step.${step}`)).join(', ')
+ )}
+ </AlertDescription>
+ </Alert>
+ ) : null}
+
{error ? (
<MemoryEngineErrorAlert error={error.message} kind={error.kind} />
) : loadError ? (
@@ -405,6 +446,9 @@ export default function MemoryEnginePanel() {
lacking={lacking}
migration={migration}
busy={saving}
+ hosted={Boolean(selected.hosted)}
+ replayContent={replayContent}
+ onReplayContentChange={setReplayContent}
onCopy={() => void doMigrate()}
onSkipCopy={() => void doSet()}
onCancel={() => setConfirming(false)}
diff --git a/app/src/components/settings/panels/MemoryEngineSwitchDialog.tsx b/app/src/components/settings/panels/MemoryEngineSwitchDialog.tsx
index be0f13d5aa..92a8e2a8e6 100644
--- a/app/src/components/settings/panels/MemoryEngineSwitchDialog.tsx
+++ b/app/src/components/settings/panels/MemoryEngineSwitchDialog.tsx
@@ -1,6 +1,6 @@
import { useT } from '../../../lib/i18n/I18nContext';
import type { MemoryEngineMigrateStatus } from '../../../utils/tauriCommands/memoryEngine';
-import { Button, ModalShell, Progress } from '../../ui';
+import { Button, Checkbox, ModalShell, Progress } from '../../ui';
interface MemoryEngineSwitchDialogProps {
targetLabel: string;
@@ -9,6 +9,11 @@ interface MemoryEngineSwitchDialogProps {
/** Set once "Copy & switch" started; swaps the choices for a progress view. */
migration: MemoryEngineMigrateStatus | null;
busy: boolean;
+ /** Whether the target bills for what it reads (TinyHumans memory). */
+ hosted: boolean;
+ /** Re-send synced content with the copy, so the new engine rebuilds its summaries. */
+ replayContent: boolean;
+ onReplayContentChange: (next: boolean) => void;
onCopy: () => void;
onSkipCopy: () => void;
onCancel: () => void;
@@ -22,6 +27,9 @@ export default function MemoryEngineSwitchDialog({
lacking,
migration,
busy,
+ hosted,
+ replayContent,
+ onReplayContentChange,
onCopy,
onSkipCopy,
onCancel,
@@ -91,20 +99,43 @@ export default function MemoryEngineSwitchDialog({
<div data-testid="memory-engine-progress" className="space-y-2">
<p>{t('memoryEngine.dialog.copying')}</p>
<Progress value={percent} aria-label={t('memoryEngine.dialog.copying')} />
- <p className="text-xs text-content-muted">
- {migration.total !== null
- ? t('memoryEngine.dialog.progress')
- .replace('{copied}', String(migration.copied))
- .replace('{total}', String(migration.total))
- : t('memoryEngine.dialog.progressUnknown').replace(
- '{copied}',
- String(migration.copied)
- )}
+ <p className="text-xs text-content-muted" data-testid="memory-engine-progress-line">
+ {migration.step && migration.step !== 'records'
+ ? t('memoryEngine.dialog.stepProgress')
+ .replace('{step}', t(`memoryEngine.step.${migration.step}`))
+ .replace('{count}', String(migration.step_read ?? 0))
+ : migration.total !== null
+ ? t('memoryEngine.dialog.progress')
+ .replace('{copied}', String(migration.copied))
+ .replace('{total}', String(migration.total))
+ : t('memoryEngine.dialog.progressUnknown').replace(
+ '{copied}',
+ String(migration.copied)
+ )}
</p>
</div>
) : (
<>
<p>{t('memoryEngine.dialog.body')}</p>
+ <p className="text-xs text-content-muted">{t('memoryEngine.dialog.copies')}</p>
+ <label className="flex items-start gap-2" htmlFor="memory-engine-replay-content">
+ <Checkbox
+ id="memory-engine-replay-content"
+ data-testid="memory-engine-replay-content"
+ checked={replayContent}
+ disabled={busy}
+ onCheckedChange={onReplayContentChange}
+ className="mt-0.5"
+ />
+ <span>
+ <span className="text-content">{t('memoryEngine.dialog.replayContent')}</span>
+ {hosted ? (
+ <span className="block text-xs text-content-muted">
+ {t('memoryEngine.dialog.replayContentHint')}
+ </span>
+ ) : null}
+ </span>
+ </label>
{lacking.length > 0 ? (
<div data-testid="memory-engine-lacking">
<p className="font-medium text-content">{t('memoryEngine.dialog.lacking')}</p>
diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts
index 4d63cc62b1..17571eaf41 100644
--- a/app/src/lib/i18n/ar.ts
+++ b/app/src/lib/i18n/ar.ts
@@ -7132,6 +7132,19 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'جارٍ نسخ ذكرياتك…',
'memoryEngine.dialog.progress': 'تم نسخ {copied} من {total}',
'memoryEngine.dialog.progressUnknown': 'تم نسخ {copied} ذكرى حتى الآن',
+ 'memoryEngine.dialog.copies':
+ 'ينسخ ذكرياتك وعناوين المستندات ووسومها وأهدافك وملفك الشخصي المُتعلَّم وسجل محادثاتك.',
+ 'memoryEngine.dialog.replayContent':
+ 'أعد أيضًا إرسال المحتوى المُزامَن ليعيد المحرك الجديد بناء ملخصاته',
+ 'memoryEngine.dialog.replayContentHint': 'إعادة قراءة المحتوى تستهلك رصيد OpenHuman.',
+ 'memoryEngine.dialog.stepProgress': 'جارٍ نسخ {step}… {count} حتى الآن',
+ 'memoryEngine.step.records': 'الذكريات',
+ 'memoryEngine.step.documents': 'عناوين المستندات ووسومها',
+ 'memoryEngine.step.goals': 'الأهداف',
+ 'memoryEngine.step.profile': 'الملف الشخصي المُتعلَّم',
+ 'memoryEngine.step.episodic': 'سجل المحادثات',
+ 'memoryEngine.step.content': 'المحتوى المُزامَن',
+ 'memoryEngine.notCopied': 'تم التبديل. لا يدعم المحرك الجديد ما يلي، لذلك لم يُنسخ: {items}.',
'memoryEngine.dialog.lacking': 'لا يدعم المحرك الجديد هذه الميزات الموجودة في محركك الحالي:',
'memoryEngine.error.insufficientCredits':
'نفد رصيد OpenHuman لديك. أضف رصيدًا لاستخدام هذا المحرك.',
diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts
index 810bd76ae8..90b6e9d771 100644
--- a/app/src/lib/i18n/bn.ts
+++ b/app/src/lib/i18n/bn.ts
@@ -7283,6 +7283,20 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'আপনার স্মৃতি কপি হচ্ছে…',
'memoryEngine.dialog.progress': '{total}টির মধ্যে {copied}টি কপি হয়েছে',
'memoryEngine.dialog.progressUnknown': 'এখন পর্যন্ত {copied}টি স্মৃতি কপি হয়েছে',
+ 'memoryEngine.dialog.copies':
+ 'আপনার স্মৃতি, ডকুমেন্টের শিরোনাম ও ট্যাগ, লক্ষ্য, শেখা প্রোফাইল এবং কথোপকথনের ইতিহাস কপি করে।',
+ 'memoryEngine.dialog.replayContent':
+ 'সিঙ্ক করা কনটেন্টও আবার পাঠান, যাতে নতুন ইঞ্জিন তার সারাংশ নতুন করে তৈরি করে',
+ 'memoryEngine.dialog.replayContentHint': 'কনটেন্ট আবার পড়তে OpenHuman ক্রেডিট খরচ হয়।',
+ 'memoryEngine.dialog.stepProgress': '{step} কপি হচ্ছে… এখন পর্যন্ত {count}',
+ 'memoryEngine.step.records': 'স্মৃতি',
+ 'memoryEngine.step.documents': 'ডকুমেন্টের শিরোনাম ও ট্যাগ',
+ 'memoryEngine.step.goals': 'লক্ষ্য',
+ 'memoryEngine.step.profile': 'শেখা প্রোফাইল',
+ 'memoryEngine.step.episodic': 'কথোপকথনের ইতিহাস',
+ 'memoryEngine.step.content': 'সিঙ্ক করা কনটেন্ট',
+ 'memoryEngine.notCopied':
+ 'পরিবর্তন হয়েছে। নতুন ইঞ্জিন এগুলো সমর্থন করে না, তাই কপি করা হয়নি: {items}।',
'memoryEngine.dialog.lacking':
'নতুন ইঞ্জিন আপনার বর্তমান ইঞ্জিনের এই বৈশিষ্ট্যগুলো সমর্থন করে না:',
'memoryEngine.error.insufficientCredits':
diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts
index db5c5aac6d..315b28e936 100644
--- a/app/src/lib/i18n/de.ts
+++ b/app/src/lib/i18n/de.ts
@@ -7481,6 +7481,21 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'Deine Erinnerungen werden kopiert…',
'memoryEngine.dialog.progress': '{copied} von {total} kopiert',
'memoryEngine.dialog.progressUnknown': 'Bisher {copied} Erinnerungen kopiert',
+ 'memoryEngine.dialog.copies':
+ 'Kopiert deine Erinnerungen, Dokumenttitel und Tags, Ziele, dein gelerntes Profil und deinen Gesprächsverlauf.',
+ 'memoryEngine.dialog.replayContent':
+ 'Synchronisierte Inhalte erneut senden, damit die neue Engine ihre Zusammenfassungen neu aufbaut',
+ 'memoryEngine.dialog.replayContentHint':
+ 'Das erneute Lesen von Inhalten verbraucht OpenHuman-Credits.',
+ 'memoryEngine.dialog.stepProgress': '{step} wird kopiert … bisher {count}',
+ 'memoryEngine.step.records': 'Erinnerungen',
+ 'memoryEngine.step.documents': 'Dokumenttitel und Tags',
+ 'memoryEngine.step.goals': 'Ziele',
+ 'memoryEngine.step.profile': 'gelerntes Profil',
+ 'memoryEngine.step.episodic': 'Gesprächsverlauf',
+ 'memoryEngine.step.content': 'synchronisierte Inhalte',
+ 'memoryEngine.notCopied':
+ 'Gewechselt. Die neue Engine unterstützt Folgendes nicht, daher wurde es nicht kopiert: {items}.',
'memoryEngine.dialog.lacking':
'Die neue Engine unterstützt diese Funktionen deiner aktuellen Engine nicht:',
'memoryEngine.error.insufficientCredits':
diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts
index ae4789d462..57e2bdfd0d 100644
--- a/app/src/lib/i18n/en.ts
+++ b/app/src/lib/i18n/en.ts
@@ -7590,6 +7590,20 @@ const en: TranslationMap = {
'memoryEngine.dialog.copying': 'Copying your memories…',
'memoryEngine.dialog.progress': 'Copied {copied} of {total}',
'memoryEngine.dialog.progressUnknown': 'Copied {copied} memories so far',
+ 'memoryEngine.dialog.copies':
+ 'Copies your memories, document titles and tags, goals, learned profile and conversation history.',
+ 'memoryEngine.dialog.replayContent':
+ 'Also re-send synced content so the new engine rebuilds its summaries',
+ 'memoryEngine.dialog.replayContentHint': 'Re-reading content uses OpenHuman credits.',
+ 'memoryEngine.dialog.stepProgress': 'Copying {step}… {count} so far',
+ 'memoryEngine.step.records': 'memories',
+ 'memoryEngine.step.documents': 'document titles and tags',
+ 'memoryEngine.step.goals': 'goals',
+ 'memoryEngine.step.profile': 'learned profile',
+ 'memoryEngine.step.episodic': 'conversation history',
+ 'memoryEngine.step.content': 'synced content',
+ 'memoryEngine.notCopied':
+ 'Switched. The new engine does not support these, so they were not copied: {items}.',
'memoryEngine.dialog.lacking':
'The new engine does not support these features of your current engine:',
'memoryEngine.error.insufficientCredits':
diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts
index 9c5110ee09..4701c1a834 100644
--- a/app/src/lib/i18n/es.ts
+++ b/app/src/lib/i18n/es.ts
@@ -7435,6 +7435,21 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'Copiando tus recuerdos…',
'memoryEngine.dialog.progress': '{copied} de {total} copiados',
'memoryEngine.dialog.progressUnknown': '{copied} recuerdos copiados hasta ahora',
+ 'memoryEngine.dialog.copies':
+ 'Copia tus recuerdos, los títulos y etiquetas de documentos, tus objetivos, tu perfil aprendido y tu historial de conversaciones.',
+ 'memoryEngine.dialog.replayContent':
+ 'Reenviar también el contenido sincronizado para que el nuevo motor reconstruya sus resúmenes',
+ 'memoryEngine.dialog.replayContentHint':
+ 'Volver a leer el contenido consume créditos de OpenHuman.',
+ 'memoryEngine.dialog.stepProgress': 'Copiando {step}… {count} hasta ahora',
+ 'memoryEngine.step.records': 'recuerdos',
+ 'memoryEngine.step.documents': 'títulos y etiquetas de documentos',
+ 'memoryEngine.step.goals': 'objetivos',
+ 'memoryEngine.step.profile': 'perfil aprendido',
+ 'memoryEngine.step.episodic': 'historial de conversaciones',
+ 'memoryEngine.step.content': 'contenido sincronizado',
+ 'memoryEngine.notCopied':
+ 'Cambio hecho. El nuevo motor no admite lo siguiente, así que no se copió: {items}.',
'memoryEngine.dialog.lacking': 'El nuevo motor no admite estas funciones de tu motor actual:',
'memoryEngine.error.insufficientCredits':
'Te has quedado sin créditos de OpenHuman. Añade créditos para usar este motor.',
diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts
index 2de145619c..c8d1e87869 100644
--- a/app/src/lib/i18n/fr.ts
+++ b/app/src/lib/i18n/fr.ts
@@ -7464,6 +7464,20 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'Copie de vos souvenirs en cours…',
'memoryEngine.dialog.progress': '{copied} sur {total} copiés',
'memoryEngine.dialog.progressUnknown': "{copied} souvenirs copiés jusqu'ici",
+ 'memoryEngine.dialog.copies':
+ "Copie vos souvenirs, les titres et étiquettes des documents, vos objectifs, votre profil appris et l'historique de vos conversations.",
+ 'memoryEngine.dialog.replayContent':
+ 'Renvoyer aussi le contenu synchronisé pour que le nouveau moteur reconstruise ses résumés',
+ 'memoryEngine.dialog.replayContentHint': 'Relire le contenu consomme des crédits OpenHuman.',
+ 'memoryEngine.dialog.stepProgress': 'Copie de {step}… {count} pour le moment',
+ 'memoryEngine.step.records': 'souvenirs',
+ 'memoryEngine.step.documents': 'titres et étiquettes des documents',
+ 'memoryEngine.step.goals': 'objectifs',
+ 'memoryEngine.step.profile': 'profil appris',
+ 'memoryEngine.step.episodic': 'historique des conversations',
+ 'memoryEngine.step.content': 'contenu synchronisé',
+ 'memoryEngine.notCopied':
+ "Changement effectué. Le nouveau moteur ne prend pas en charge ces éléments, ils n'ont donc pas été copiés : {items}.",
'memoryEngine.dialog.lacking':
'Le nouveau moteur ne prend pas en charge ces fonctionnalités de votre moteur actuel :',
'memoryEngine.error.insufficientCredits':
diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts
index 00154d9e59..4a5f96e4e7 100644
--- a/app/src/lib/i18n/hi.ts
+++ b/app/src/lib/i18n/hi.ts
@@ -7286,6 +7286,20 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'आपकी यादें कॉपी हो रही हैं…',
'memoryEngine.dialog.progress': '{total} में से {copied} कॉपी हुईं',
'memoryEngine.dialog.progressUnknown': 'अब तक {copied} यादें कॉपी हुईं',
+ 'memoryEngine.dialog.copies':
+ 'आपकी यादें, दस्तावेज़ों के शीर्षक और टैग, लक्ष्य, सीखी गई प्रोफ़ाइल और बातचीत का इतिहास कॉपी करता है।',
+ 'memoryEngine.dialog.replayContent':
+ 'सिंक की गई सामग्री भी दोबारा भेजें ताकि नया इंजन अपने सारांश फिर से बनाए',
+ 'memoryEngine.dialog.replayContentHint': 'सामग्री दोबारा पढ़ने में OpenHuman क्रेडिट लगते हैं।',
+ 'memoryEngine.dialog.stepProgress': '{step} कॉपी हो रहा है… अब तक {count}',
+ 'memoryEngine.step.records': 'यादें',
+ 'memoryEngine.step.documents': 'दस्तावेज़ों के शीर्षक और टैग',
+ 'memoryEngine.step.goals': 'लक्ष्य',
+ 'memoryEngine.step.profile': 'सीखी गई प्रोफ़ाइल',
+ 'memoryEngine.step.episodic': 'बातचीत का इतिहास',
+ 'memoryEngine.step.content': 'सिंक की गई सामग्री',
+ 'memoryEngine.notCopied':
+ 'स्विच हो गया। नया इंजन इनका समर्थन नहीं करता, इसलिए ये कॉपी नहीं हुए: {items}।',
'memoryEngine.dialog.lacking': 'नया इंजन आपके मौजूदा इंजन की इन सुविधाओं का समर्थन नहीं करता:',
'memoryEngine.error.insufficientCredits':
'आपके OpenHuman क्रेडिट खत्म हो गए हैं। इस इंजन का उपयोग करने के लिए क्रेडिट जोड़ें।',
diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts
index 24a03fe6dd..506f930432 100644
--- a/app/src/lib/i18n/id.ts
+++ b/app/src/lib/i18n/id.ts
@@ -7332,6 +7332,20 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'Menyalin memori Anda…',
'memoryEngine.dialog.progress': '{copied} dari {total} disalin',
'memoryEngine.dialog.progressUnknown': '{copied} memori disalin sejauh ini',
+ 'memoryEngine.dialog.copies':
+ 'Menyalin memori, judul dan tag dokumen, tujuan, profil yang dipelajari, dan riwayat percakapan Anda.',
+ 'memoryEngine.dialog.replayContent':
+ 'Kirim ulang juga konten yang disinkronkan agar mesin baru menyusun ulang ringkasannya',
+ 'memoryEngine.dialog.replayContentHint': 'Membaca ulang konten menggunakan kredit OpenHuman.',
+ 'memoryEngine.dialog.stepProgress': 'Menyalin {step}… {count} sejauh ini',
+ 'memoryEngine.step.records': 'memori',
+ 'memoryEngine.step.documents': 'judul dan tag dokumen',
+ 'memoryEngine.step.goals': 'tujuan',
+ 'memoryEngine.step.profile': 'profil yang dipelajari',
+ 'memoryEngine.step.episodic': 'riwayat percakapan',
+ 'memoryEngine.step.content': 'konten yang disinkronkan',
+ 'memoryEngine.notCopied':
+ 'Sudah beralih. Mesin baru tidak mendukung hal berikut, jadi tidak disalin: {items}.',
'memoryEngine.dialog.lacking': 'Mesin baru tidak mendukung fitur mesin Anda saat ini berikut:',
'memoryEngine.error.insufficientCredits':
'Kredit OpenHuman Anda habis. Tambahkan kredit untuk menggunakan mesin ini.',
diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts
index d0327c9e33..3c4152a4e7 100644
--- a/app/src/lib/i18n/it.ts
+++ b/app/src/lib/i18n/it.ts
@@ -7412,6 +7412,20 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'Copia dei tuoi ricordi in corso…',
'memoryEngine.dialog.progress': 'Copiati {copied} di {total}',
'memoryEngine.dialog.progressUnknown': 'Finora copiati {copied} ricordi',
+ 'memoryEngine.dialog.copies':
+ 'Copia i tuoi ricordi, i titoli e i tag dei documenti, gli obiettivi, il profilo appreso e la cronologia delle conversazioni.',
+ 'memoryEngine.dialog.replayContent':
+ 'Invia di nuovo anche i contenuti sincronizzati, così il nuovo motore ricostruisce i suoi riassunti',
+ 'memoryEngine.dialog.replayContentHint': 'Rileggere i contenuti consuma crediti OpenHuman.',
+ 'memoryEngine.dialog.stepProgress': 'Copia di {step}… finora {count}',
+ 'memoryEngine.step.records': 'ricordi',
+ 'memoryEngine.step.documents': 'titoli e tag dei documenti',
+ 'memoryEngine.step.goals': 'obiettivi',
+ 'memoryEngine.step.profile': 'profilo appreso',
+ 'memoryEngine.step.episodic': 'cronologia delle conversazioni',
+ 'memoryEngine.step.content': 'contenuti sincronizzati',
+ 'memoryEngine.notCopied':
+ 'Passaggio completato. Il nuovo motore non supporta questi elementi, quindi non sono stati copiati: {items}.',
'memoryEngine.dialog.lacking':
'Il nuovo motore non supporta queste funzioni del tuo motore attuale:',
'memoryEngine.error.insufficientCredits':
diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts
index 9eb1aa722e..7950721f18 100644
--- a/app/src/lib/i18n/ko.ts
+++ b/app/src/lib/i18n/ko.ts
@@ -7204,6 +7204,20 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': '기억을 복사하는 중…',
'memoryEngine.dialog.progress': '{total}개 중 {copied}개 복사됨',
'memoryEngine.dialog.progressUnknown': '지금까지 기억 {copied}개 복사됨',
+ 'memoryEngine.dialog.copies':
+ '기억, 문서 제목과 태그, 목표, 학습된 프로필, 대화 기록을 복사합니다.',
+ 'memoryEngine.dialog.replayContent':
+ '동기화된 콘텐츠도 다시 보내 새 엔진이 요약을 다시 만들도록 하기',
+ 'memoryEngine.dialog.replayContentHint': '콘텐츠를 다시 읽는 데 OpenHuman 크레딧이 사용됩니다.',
+ 'memoryEngine.dialog.stepProgress': '{step} 복사 중… 지금까지 {count}개',
+ 'memoryEngine.step.records': '기억',
+ 'memoryEngine.step.documents': '문서 제목과 태그',
+ 'memoryEngine.step.goals': '목표',
+ 'memoryEngine.step.profile': '학습된 프로필',
+ 'memoryEngine.step.episodic': '대화 기록',
+ 'memoryEngine.step.content': '동기화된 콘텐츠',
+ 'memoryEngine.notCopied':
+ '전환했습니다. 새 엔진이 다음 항목을 지원하지 않아 복사하지 않았습니다: {items}.',
'memoryEngine.dialog.lacking': '새 엔진은 현재 엔진의 다음 기능을 지원하지 않습니다:',
'memoryEngine.error.insufficientCredits':
'OpenHuman 크레딧이 모두 소진되었습니다. 이 엔진을 사용하려면 크레딧을 추가하세요.',
diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts
index ae56aecc07..76b6358780 100644
--- a/app/src/lib/i18n/pl.ts
+++ b/app/src/lib/i18n/pl.ts
@@ -7392,6 +7392,20 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'Kopiowanie Twoich wspomnień…',
'memoryEngine.dialog.progress': 'Skopiowano {copied} z {total}',
'memoryEngine.dialog.progressUnknown': 'Skopiowano dotąd wspomnień: {copied}',
+ 'memoryEngine.dialog.copies':
+ 'Kopiuje Twoje wspomnienia, tytuły i tagi dokumentów, cele, wyuczony profil oraz historię rozmów.',
+ 'memoryEngine.dialog.replayContent':
+ 'Wyślij też ponownie zsynchronizowane treści, aby nowy silnik odbudował swoje podsumowania',
+ 'memoryEngine.dialog.replayContentHint': 'Ponowne odczytanie treści zużywa kredyty OpenHuman.',
+ 'memoryEngine.dialog.stepProgress': 'Kopiowanie: {step}… dotąd {count}',
+ 'memoryEngine.step.records': 'wspomnienia',
+ 'memoryEngine.step.documents': 'tytuły i tagi dokumentów',
+ 'memoryEngine.step.goals': 'cele',
+ 'memoryEngine.step.profile': 'wyuczony profil',
+ 'memoryEngine.step.episodic': 'historia rozmów',
+ 'memoryEngine.step.content': 'zsynchronizowane treści',
+ 'memoryEngine.notCopied':
+ 'Przełączono. Nowy silnik nie obsługuje poniższych elementów, więc nie zostały skopiowane: {items}.',
'memoryEngine.dialog.lacking': 'Nowy silnik nie obsługuje tych funkcji Twojego obecnego silnika:',
'memoryEngine.error.insufficientCredits':
'Skończyły Ci się kredyty OpenHuman. Dodaj kredyty, aby użyć tego silnika.',
diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts
index fb14af9b86..0332eecfa5 100644
--- a/app/src/lib/i18n/pt.ts
+++ b/app/src/lib/i18n/pt.ts
@@ -7402,6 +7402,20 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'Copiando suas memórias…',
'memoryEngine.dialog.progress': '{copied} de {total} copiadas',
'memoryEngine.dialog.progressUnknown': '{copied} memórias copiadas até agora',
+ 'memoryEngine.dialog.copies':
+ 'Copia suas memórias, os títulos e tags dos documentos, seus objetivos, seu perfil aprendido e seu histórico de conversas.',
+ 'memoryEngine.dialog.replayContent':
+ 'Reenviar também o conteúdo sincronizado para que o novo mecanismo reconstrua seus resumos',
+ 'memoryEngine.dialog.replayContentHint': 'Reler o conteúdo consome créditos do OpenHuman.',
+ 'memoryEngine.dialog.stepProgress': 'Copiando {step}… {count} até agora',
+ 'memoryEngine.step.records': 'memórias',
+ 'memoryEngine.step.documents': 'títulos e tags dos documentos',
+ 'memoryEngine.step.goals': 'objetivos',
+ 'memoryEngine.step.profile': 'perfil aprendido',
+ 'memoryEngine.step.episodic': 'histórico de conversas',
+ 'memoryEngine.step.content': 'conteúdo sincronizado',
+ 'memoryEngine.notCopied':
+ 'Troca concluída. O novo mecanismo não oferece suporte a estes itens, então eles não foram copiados: {items}.',
'memoryEngine.dialog.lacking':
'O novo mecanismo não oferece suporte a estes recursos do seu mecanismo atual:',
'memoryEngine.error.insufficientCredits':
diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts
index 590d271b59..24732250cd 100644
--- a/app/src/lib/i18n/ru.ts
+++ b/app/src/lib/i18n/ru.ts
@@ -7358,6 +7358,21 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': 'Копирование ваших воспоминаний…',
'memoryEngine.dialog.progress': 'Скопировано {copied} из {total}',
'memoryEngine.dialog.progressUnknown': 'Скопировано воспоминаний: {copied}',
+ 'memoryEngine.dialog.copies':
+ 'Копирует ваши воспоминания, названия и теги документов, цели, изученный профиль и историю разговоров.',
+ 'memoryEngine.dialog.replayContent':
+ 'Также заново отправить синхронизированные материалы, чтобы новый движок пересобрал свои сводки',
+ 'memoryEngine.dialog.replayContentHint':
+ 'Повторное чтение материалов расходует кредиты OpenHuman.',
+ 'memoryEngine.dialog.stepProgress': 'Копирование: {step}… пока {count}',
+ 'memoryEngine.step.records': 'воспоминания',
+ 'memoryEngine.step.documents': 'названия и теги документов',
+ 'memoryEngine.step.goals': 'цели',
+ 'memoryEngine.step.profile': 'изученный профиль',
+ 'memoryEngine.step.episodic': 'история разговоров',
+ 'memoryEngine.step.content': 'синхронизированные материалы',
+ 'memoryEngine.notCopied':
+ 'Переключено. Новый движок не поддерживает следующее, поэтому это не скопировано: {items}.',
'memoryEngine.dialog.lacking': 'Новый движок не поддерживает эти функции вашего текущего движка:',
'memoryEngine.error.insufficientCredits':
'Кредиты OpenHuman закончились. Пополните кредиты, чтобы использовать этот движок.',
diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts
index ed324b79eb..5cbe70ed04 100644
--- a/app/src/lib/i18n/zh-CN.ts
+++ b/app/src/lib/i18n/zh-CN.ts
@@ -6907,6 +6907,18 @@ const messages: TranslationMap = {
'memoryEngine.dialog.copying': '正在复制你的记忆…',
'memoryEngine.dialog.progress': '已复制 {copied} / {total}',
'memoryEngine.dialog.progressUnknown': '已复制 {copied} 条记忆',
+ 'memoryEngine.dialog.copies':
+ '会复制你的记忆、文档标题和标签、目标、学到的个人资料以及对话历史。',
+ 'memoryEngine.dialog.replayContent': '同时重新发送已同步的内容,让新引擎重建摘要',
+ 'memoryEngine.dialog.replayContentHint': '重新读取内容会消耗 OpenHuman 额度。',
+ 'memoryEngine.dialog.stepProgress': '正在复制{step}… 目前 {count} 条',
+ 'memoryEngine.step.records': '记忆',
+ 'memoryEngine.step.documents': '文档标题和标签',
+ 'memoryEngine.step.goals': '目标',
+ 'memoryEngine.step.profile': '学到的个人资料',
+ 'memoryEngine.step.episodic': '对话历史',
+ 'memoryEngine.step.content': '已同步的内容',
+ 'memoryEngine.notCopied': '已切换。新引擎不支持以下内容,因此未复制:{items}。',
'memoryEngine.dialog.lacking': '新引擎不支持当前引擎的以下功能:',
'memoryEngine.error.insufficientCredits': '你的 OpenHuman 额度已用完。请充值后再使用此引擎。',
'memoryEngine.error.sessionExpired': '会话已过期。请重新登录以继续。',
diff --git a/app/src/utils/tauriCommands/memoryEngine.ts b/app/src/utils/tauriCommands/memoryEngine.ts
index 33084ace10..1497b8ef0c 100644
--- a/app/src/utils/tauriCommands/memoryEngine.ts
+++ b/app/src/utils/tauriCommands/memoryEngine.ts
@@ -47,6 +47,27 @@ export interface MemoryEngineTarget {
export type MemoryEngineMigrateState = 'running' | 'done' | 'failed' | 'cancelled';
+/** What a migration copies, in the order it copies it. */
+export type MemoryEngineMigrateStep =
+ | 'records'
+ | 'documents'
+ | 'goals'
+ | 'profile'
+ | 'episodic'
+ | 'content';
+
+/** What one step after the stored memories did, once the copy finished. */
+export interface MemoryEngineMigrateStepStatus {
+ step: Exclude<MemoryEngineMigrateStep, 'records'>;
+ /** Why the step did not run; null when it ran. */
+ skipped_because: string | null;
+ read: number;
+ written: number;
+ unchanged: number;
+ failed: number;
+ errors: string[];
+}
+
export interface MemoryEngineMigrateStatus {
state: MemoryEngineMigrateState;
copied: number;
@@ -54,6 +75,14 @@ export interface MemoryEngineMigrateStatus {
error: string | null;
/** Caveat on a finished job (writes made while the copy ran); absent otherwise. */
note?: string | null;
+ /** The step under way, or the last one once the copy ended. */
+ step?: MemoryEngineMigrateStep | null;
+ /** Items the step under way has read so far. */
+ step_read?: number;
+ /** Items the step under way has written so far. */
+ step_written?: number;
+ /** What each step after the stored memories did, once the copy finished. */
+ steps?: MemoryEngineMigrateStepStatus[];
}
export async function memoryEnginesList(): Promise<MemoryEnginesList> {
@@ -71,11 +100,18 @@ export async function memoryEngineSet(target: MemoryEngineTarget): Promise<Memor
});
}
-/** Copies every memory from the active engine into `to`, then switches to it. */
-export async function memoryEngineMigrate(to: MemoryEngineTarget): Promise<{ job_id: string }> {
+/**
+ * Copies every memory from the active engine into `to`, then switches to it.
+ * `replayContent` re-sends ingested content so the new engine rebuilds its
+ * summaries; it defaults to true.
+ */
+export async function memoryEngineMigrate(
+ to: MemoryEngineTarget,
+ options: { replayContent?: boolean } = {}
+): Promise<{ job_id: string }> {
return await callCoreRpc<{ job_id: string }>({
method: CORE_RPC_METHODS.memoryEngineMigrate,
- params: { to },
+ params: { to, replay_content: options.replayContent ?? true },
});
}
diff --git a/crates/openhuman-core/src/core/all_tests.rs b/crates/openhuman-core/src/core/all_tests.rs
index a3ea1d73e0..e1d779cad2 100644
--- a/crates/openhuman-core/src/core/all_tests.rs
+++ b/crates/openhuman-core/src/core/all_tests.rs
@@ -1863,6 +1863,10 @@ fn every_capability_family_is_accounted_for_in_the_rpc_surface() {
| Capability::LearningIngest
| Capability::EventIngest
| Capability::Answer => false,
+ // The engine switch reaches it through `memory.engine_migrate`,
+ // which copies whatever both engines serve; no controller is
+ // gated on it.
+ Capability::EpisodicPortability => false,
// Folded into `Tree`: the tree registry's ~25 methods span tree,
// entities, graph and maintenance and are tagged as ONE family.
// See the push site in `all.rs` for why that trade was chosen.
diff --git a/crates/openhuman-core/src/memory/ops/engine_migrate.rs b/crates/openhuman-core/src/memory/ops/engine_migrate.rs
index cd7fc6e45e..5c6436c0e3 100644
--- a/crates/openhuman-core/src/memory/ops/engine_migrate.rs
+++ b/crates/openhuman-core/src/memory/ops/engine_migrate.rs
@@ -1,11 +1,21 @@
//! `memory.engine_migrate` / `memory.engine_migrate_status` — copy everything
//! from the active engine into another, then switch to it.
//!
-//! The copy is `tinymemory::migrate::copy`: engine-neutral, at-least-once and
-//! non-destructive (the source keeps its data, and the target skips records it
-//! recognises), so a failed or repeated migration is safe and the previous
-//! engine stays usable. The switch is committed only after the copy finished
-//! with no failed records; on any failure the active engine is untouched.
+//! The copy is `tinymemory::migrate::copy_all`: the keyed records, then each
+//! family both engines serve — document details, goals, the learned profile,
+//! the conversation history — and, when the caller asks, the ingested content,
+//! re-sent raw so the new engine rebuilds its summary tree. It is engine-neutral,
+//! at-least-once and non-destructive (the source keeps its data, and the target
+//! skips what it already holds), so a failed or repeated migration is safe and
+//! the previous engine stays usable. The switch is committed only after the copy
+//! finished with nothing failed; on any failure the active engine is untouched.
+//! Re-sent content is the exception: it stays in the previous engine and the
+//! sync that produced it can bring it again, so a piece the new engine refuses
+//! is reported in the job's note rather than holding the switch back.
+//!
+//! The host decides what the replay leaves out. A target the host syncs sources
+//! into itself gets every reader-based source again from scratch (see
+//! `memory::sources::hosted_sync`), so their chunks are not re-sent.
//!
//! Jobs live in an in-process map (one at a time). They do not survive a
//! restart: an interrupted migration is simply run again.
@@ -47,6 +57,41 @@ const MAX_FINISHED_JOBS: usize = 16;
#[derive(Clone, Deserialize)]
pub struct MigrateParams {
pub to: EngineTargetParams,
+ /// Whether to re-send ingested content so the new engine rebuilds its
+ /// summary tree from it. Hosted memory bills for the content it reads
+ /// again, which is why it is a choice. Defaults to `true`.
+ #[serde(default = "replay_by_default")]
+ pub replay_content: bool,
+}
+
+fn replay_by_default() -> bool {
+ true
+}
+
+/// The prefix of a reader-based source's chunk ids, `mem_src:<source>:<item>`
+/// (see `tinymemory_api::sync_events::extract_mem_src_id`).
+const READER_SOURCE_PREFIX: &str = "mem_src:";
+
+/// What a copy carries beyond the keyed records, as the host decides it.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+struct CopyChoices {
+ replay_content: bool,
+ skip_source_prefixes: Vec<String>,
+}
+
+/// The choices for a copy into a target: one the host syncs sources into
+/// itself (`host_synced`) gets every reader-based source again from scratch,
+/// so the replay leaves those out rather than send them twice.
+fn copy_choices(replay_content: bool, host_synced: bool) -> CopyChoices {
+ let skip_source_prefixes = if host_synced {
+ vec![READER_SOURCE_PREFIX.to_string()]
+ } else {
+ Vec::new()
+ };
+ CopyChoices {
+ replay_content,
+ skip_source_prefixes,
+ }
}
/// Parameters of `memory.engine_migrate_cancel`.
@@ -100,6 +145,33 @@ pub struct MigrateStatus {
/// A caveat on a finished job (see the module docs on writes during the
/// copy); `None` otherwise.
pub note: Option<String>,
+ /// The step under way — `records`, `documents`, `goals`, `profile`,
+ /// `episodic` or `content` — or the last one once the copy ended. `None`
+ /// before the first step reports.
+ pub step: Option<String>,
+ /// Items the step under way has read so far.
+ pub step_read: usize,
+ /// Items the step under way has written so far.
+ pub step_written: usize,
+ /// What each step after the records did, once the copy finished.
+ pub steps: Vec<MigrateStepStatus>,
+}
+
+/// What one step after the keyed records did.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct MigrateStepStatus {
+ /// `documents`, `goals`, `profile`, `episodic` or `content`.
+ pub step: String,
+ /// Why the step did not run — an engine does not serve what it needs, or
+ /// the caller chose not to re-send content. `None` when it ran.
+ pub skipped_because: Option<String>,
+ pub read: usize,
+ pub written: usize,
+ /// Items the new engine already held as the old one has them.
+ pub unchanged: usize,
+ pub failed: usize,
+ /// Why items failed, naming them and never their content; at most 20.
+ pub errors: Vec<String>,
}
/// Cancel signals of the jobs in [`JOBS`].
@@ -167,6 +239,10 @@ fn start_job() -> Result<String, String> {
total: None,
error: None,
note: None,
+ step: None,
+ step_read: 0,
+ step_written: 0,
+ steps: Vec::new(),
},
);
cancels().insert(
@@ -186,22 +262,57 @@ struct CopyReport {
skipped: usize,
failed: usize,
errors: Vec<String>,
+ steps: Vec<MigrateStepStatus>,
+}
+
+/// One progress report from the copy: the step under way and its counts.
+#[derive(Clone, Copy, Debug)]
+struct CopyTick {
+ step: &'static str,
+ read: usize,
+ written: usize,
}
#[cfg(feature = "memory-remote")]
async fn run_copy(
source: &dyn crate::memory::api::provider::MemoryProvider,
target: &dyn crate::memory::api::provider::MemoryProvider,
- on_progress: impl FnMut(usize),
+ choices: &CopyChoices,
+ on_progress: impl FnMut(CopyTick),
) -> anyhow::Result<CopyReport> {
let mut on_progress = on_progress;
- let report = tinymemory::migrate::copy(source, target, |p| on_progress(p.records)).await?;
+ let options = tinymemory::migrate::CopyOptions {
+ replay_content: choices.replay_content,
+ skip_source_prefixes: choices.skip_source_prefixes.clone(),
+ ..tinymemory::migrate::CopyOptions::default()
+ };
+ let report = tinymemory::migrate::copy_all(source, target, &options, |p| {
+ on_progress(CopyTick {
+ step: p.step.as_str(),
+ read: p.read,
+ written: p.written,
+ });
+ })
+ .await?;
Ok(CopyReport {
- records: report.records,
- imported: report.imported,
- skipped: report.skipped,
- failed: report.failed,
- errors: report.errors,
+ records: report.records.records,
+ imported: report.records.imported,
+ skipped: report.records.skipped,
+ failed: report.records.failed,
+ errors: report.records.errors,
+ steps: report
+ .steps
+ .into_iter()
+ .map(|step| MigrateStepStatus {
+ step: step.step.as_str().to_string(),
+ skipped_because: step.skipped_because,
+ read: step.read,
+ written: step.written,
+ unchanged: step.unchanged,
+ failed: step.failed,
+ errors: step.errors,
+ })
+ .collect(),
})
}
@@ -209,11 +320,36 @@ async fn run_copy(
async fn run_copy(
_source: &dyn crate::memory::api::provider::MemoryProvider,
_target: &dyn crate::memory::api::provider::MemoryProvider,
- _on_progress: impl FnMut(usize),
+ _choices: &CopyChoices,
+ _on_progress: impl FnMut(CopyTick),
) -> anyhow::Result<CopyReport> {
anyhow::bail!("memory engine migration is not compiled into this build")
}
+/// The step whose failures hold the switch back, if any: every step but the
+/// content replay, which only re-sends what the previous engine keeps.
+fn blocking_failure(steps: &[MigrateStepStatus]) -> Option<&MigrateStepStatus> {
+ steps
+ .iter()
+ .find(|step| step.step != "content" && step.failed > 0)
+}
+
+/// The caveats on a finished copy: writes made while it ran, and re-sent
+/// content the new engine refused.
+fn finished_note(steps: &[MigrateStepStatus]) -> String {
+ let mut note = WRITES_DURING_COPY_NOTE.to_string();
+ if let Some(content) = steps
+ .iter()
+ .find(|step| step.step == "content" && step.failed > 0)
+ {
+ note.push_str(&format!(
+ " {} pieces of synced content could not be re-sent; the previous engine still holds them, and their next sync can bring them again.",
+ content.failed
+ ));
+ }
+ note
+}
+
/// How the copy phase ended.
enum CopyEnd {
Finished(anyhow::Result<CopyReport>),
@@ -228,6 +364,7 @@ async fn run_job<F, Fut>(
job_id: String,
source: Arc<dyn crate::memory::api::provider::MemoryProvider>,
target: Arc<dyn crate::memory::api::provider::MemoryProvider>,
+ choices: CopyChoices,
timeout: Duration,
commit: F,
) where
@@ -239,8 +376,18 @@ async fn run_job<F, Fut>(
.map(|slot| Arc::clone(&slot.notify))
.unwrap_or_default();
let progress_id = job_id.clone();
- let copy = run_copy(source.as_ref(), target.as_ref(), move |records| {
- update_job(&progress_id, |j| j.copied = records);
+ let copy = run_copy(source.as_ref(), target.as_ref(), &choices, move |tick| {
+ update_job(&progress_id, |j| {
+ if j.step.as_deref() != Some(tick.step) {
+ log::info!("{LOG_PREFIX} job={progress_id} step={} started", tick.step);
+ }
+ if tick.step == "records" {
+ j.copied = tick.read;
+ }
+ j.step = Some(tick.step.to_string());
+ j.step_read = tick.read;
+ j.step_written = tick.written;
+ });
});
// Dropping the copy future on cancel/timeout stops it at its next await,
// i.e. between export/import pages.
@@ -275,6 +422,30 @@ async fn run_job<F, Fut>(
);
}
CopyEnd::Finished(Ok(report)) => {
+ let steps = report.steps.clone();
+ update_job(&job_id, |j| j.steps = steps);
+ for step in &report.steps {
+ log::info!(
+ "{LOG_PREFIX} job={job_id} step={} read={} written={} unchanged={} failed={} skipped_because={:?}",
+ step.step,
+ step.read,
+ step.written,
+ step.unchanged,
+ step.failed,
+ step.skipped_because
+ );
+ }
+ if let Some(step) = blocking_failure(&report.steps) {
+ let first = step.errors.first().map_or("", String::as_str);
+ fail_job(
+ &job_id,
+ classify_engine_message(&format!(
+ "{} of {} {} items could not be copied; the active engine was not changed. {first}",
+ step.failed, step.read, step.step
+ )),
+ );
+ return;
+ }
// The copy is past its cancellation point. Removing the signal
// makes concurrent cancel requests report `cancelled: false`.
if cancels().remove(&job_id).is_some_and(|slot| slot.requested) {
@@ -290,9 +461,10 @@ async fn run_job<F, Fut>(
report.imported,
report.skipped
);
+ let note = finished_note(&report.steps);
update_job(&job_id, |j| {
j.state = "done".to_string();
- j.note = Some(WRITES_DURING_COPY_NOTE.to_string());
+ j.note = Some(note);
});
}
Err(error) => fail_job(&job_id, classify_engine_message(&error)),
@@ -311,6 +483,7 @@ fn spawn_job<F, Fut>(
job_id: String,
source: Arc<dyn crate::memory::api::provider::MemoryProvider>,
target: Arc<dyn crate::memory::api::provider::MemoryProvider>,
+ choices: CopyChoices,
timeout: Duration,
commit: F,
) where
@@ -319,7 +492,7 @@ fn spawn_job<F, Fut>(
{
let worker_id = job_id.clone();
let worker = tokio::spawn(CoreContext::propagate(run_job(
- worker_id, source, target, timeout, commit,
+ worker_id, source, target, choices, timeout, commit,
)));
tokio::spawn(async move {
if let Err(join_error) = worker.await {
@@ -365,16 +538,23 @@ pub async fn memory_engine_migrate(
let _switch = SWITCH_LOCK.lock().await;
start_job()?
};
+ let choices = copy_choices(
+ params.replay_content,
+ crate::memory::sources::hosted_sync::host_synced(target.as_ref()),
+ );
log::info!(
- "{LOG_PREFIX} job={job_id} started source='{}' target='{}'",
+ "{LOG_PREFIX} job={job_id} started source='{}' target='{}' replay_content={} skip_sources={:?}",
source_binding.driver_id(),
- prepared.id
+ prepared.id,
+ choices.replay_content,
+ choices.skip_source_prefixes
);
spawn_job(
job_id.clone(),
source,
target,
+ choices,
migrate_timeout(),
move || async move { commit_engine(&prepared).await.map(|_| ()) },
);
diff --git a/crates/openhuman-core/src/memory/ops/engine_migrate_tests.rs b/crates/openhuman-core/src/memory/ops/engine_migrate_tests.rs
index 5b1a162d37..9628f80a36 100644
--- a/crates/openhuman-core/src/memory/ops/engine_migrate_tests.rs
+++ b/crates/openhuman-core/src/memory/ops/engine_migrate_tests.rs
@@ -89,6 +89,9 @@ async fn status_reports_the_bare_shape() {
assert_eq!(json["copied"], 7);
assert!(json["total"].is_null());
assert!(json["error"].is_null());
+ assert!(json["step"].is_null(), "no step has reported yet");
+ assert_eq!(json["step_read"], 0);
+ assert_eq!(json["steps"], serde_json::json!([]));
let _guard = lock();
clear();
}
@@ -139,6 +142,7 @@ async fn a_failed_import_fails_the_job_and_the_engine_does_not_switch() {
id.clone(),
as_provider(&source),
as_provider(&target),
+ CopyChoices::default(),
Duration::from_secs(30),
move || async move {
seen.store(true, Ordering::SeqCst);
@@ -171,6 +175,7 @@ async fn a_clean_copy_commits_the_switch_and_records_the_writes_note() {
id.clone(),
as_provider(&source),
as_provider(&target),
+ CopyChoices::default(),
Duration::from_secs(30),
move || async move {
seen.store(true, Ordering::SeqCst);
@@ -203,6 +208,7 @@ async fn a_failing_commit_fails_the_job() {
id.clone(),
as_provider(&source),
as_provider(&target),
+ CopyChoices::default(),
Duration::from_secs(30),
|| async { Err("the switch was saved but could not be applied".to_string()) },
)
@@ -226,6 +232,7 @@ async fn cancel_stops_the_copy_without_switching() {
id.clone(),
as_provider(&source),
as_provider(&target),
+ CopyChoices::default(),
Duration::from_secs(30),
move || async move {
seen.store(true, Ordering::SeqCst);
@@ -271,6 +278,7 @@ async fn the_overall_timeout_fails_the_job() {
id.clone(),
as_provider(&source),
as_provider(&target),
+ CopyChoices::default(),
Duration::from_millis(50),
|| async { Ok(()) },
);
@@ -293,6 +301,7 @@ async fn a_panicking_task_marks_the_job_failed() {
id.clone(),
as_provider(&source),
as_provider(&target),
+ CopyChoices::default(),
Duration::from_secs(30),
|| async { Ok(()) },
);
@@ -338,3 +347,63 @@ async fn switches_are_serialised_on_one_lock() {
);
drop(held);
}
+
+// ── What the copy carries, and what holds the switch back ───────────────────
+
+fn step(name: &str, failed: usize) -> MigrateStepStatus {
+ MigrateStepStatus {
+ step: name.to_string(),
+ skipped_because: None,
+ read: 10,
+ written: 10 - failed,
+ unchanged: 0,
+ failed,
+ errors: vec![format!("{name} item refused")],
+ }
+}
+
+#[test]
+fn a_host_synced_target_leaves_reader_sources_out_of_the_replay() {
+ let hosted = copy_choices(true, true);
+ assert!(hosted.replay_content);
+ assert_eq!(hosted.skip_source_prefixes, vec!["mem_src:".to_string()]);
+ let local = copy_choices(false, false);
+ assert!(!local.replay_content);
+ assert!(local.skip_source_prefixes.is_empty());
+}
+
+#[test]
+fn the_replay_defaults_on_for_callers_that_do_not_say() {
+ let params: MigrateParams =
+ serde_json::from_value(serde_json::json!({ "to": { "driver": "tinycortex" } }))
+ .expect("params");
+ assert!(params.replay_content);
+ let params: MigrateParams = serde_json::from_value(
+ serde_json::json!({ "to": { "driver": "tinycortex" }, "replay_content": false }),
+ )
+ .expect("params");
+ assert!(!params.replay_content);
+}
+
+#[test]
+fn only_re_sent_content_may_fail_without_holding_the_switch_back() {
+ assert!(blocking_failure(&[step("content", 3)]).is_none());
+ let steps = [
+ step("documents", 0),
+ step("episodic", 2),
+ step("content", 1),
+ ];
+ assert_eq!(
+ blocking_failure(&steps).map(|s| s.step.as_str()),
+ Some("episodic")
+ );
+}
+
+#[test]
+fn the_note_names_content_the_new_engine_refused() {
+ let clean = finished_note(&[step("content", 0)]);
+ assert_eq!(clean, WRITES_DURING_COPY_NOTE);
+ let refused = finished_note(&[step("documents", 0), step("content", 4)]);
+ assert!(refused.starts_with(WRITES_DURING_COPY_NOTE));
+ assert!(refused.contains("4 pieces of synced content"), "{refused}");
+}
diff --git a/crates/openhuman-core/src/memory/schemas/engine.rs b/crates/openhuman-core/src/memory/schemas/engine.rs
index 8d51d3bded..d25ce5c44c 100644
--- a/crates/openhuman-core/src/memory/schemas/engine.rs
+++ b/crates/openhuman-core/src/memory/schemas/engine.rs
@@ -170,13 +170,21 @@ pub(super) fn schema(function: &str) -> Option<ControllerSchema> {
"engine_migrate" => ControllerSchema {
namespace: "memory",
function: "engine_migrate",
- description: "Copy every memory from the active engine into another, then switch to it. Returns a job id; poll engine_migrate_status.",
- inputs: vec![field(
- "to",
- TypeSchema::Json,
- "The target engine: { driver, endpoint?, deployment?, api_key? }.",
- true,
- )],
+ description: "Copy every memory from the active engine into another, then switch to it: the stored memories, document titles and tags, goals, the learned profile, the conversation history and, unless replay_content is false, the ingested content, re-sent so the new engine rebuilds its summaries. Returns a job id; poll engine_migrate_status.",
+ inputs: vec![
+ field(
+ "to",
+ TypeSchema::Json,
+ "The target engine: { driver, endpoint?, deployment?, api_key? }.",
+ true,
+ ),
+ field(
+ "replay_content",
+ TypeSchema::Bool,
+ "Re-send ingested content so the new engine rebuilds its summary tree; hosted memory bills for the content it reads again. Default true.",
+ false,
+ ),
+ ],
outputs: vec![field("job_id", TypeSchema::String, "Migration job id.", true)],
},
"engine_migrate_status" => ControllerSchema {
@@ -185,10 +193,15 @@ pub(super) fn schema(function: &str) -> Option<ControllerSchema> {
description: "Progress of an engine migration job.",
inputs: vec![field("job_id", TypeSchema::String, "Id returned by engine_migrate.", true)],
outputs: vec![
- field("state", TypeSchema::String, "running | done | failed.", true),
+ field("state", TypeSchema::String, "running | done | failed | cancelled.", true),
field("copied", TypeSchema::U64, "Records copied so far.", true),
field("total", TypeSchema::Option(Box::new(TypeSchema::U64)), "Total records when known; null otherwise.", false),
field("error", opt_string(), "Failure reason; null unless failed.", false),
+ field("note", opt_string(), "Caveat on a finished job; null otherwise.", false),
+ field("step", opt_string(), "The step under way, or the last one: records | documents | goals | profile | episodic | content.", false),
+ field("step_read", TypeSchema::U64, "Items the step under way has read.", true),
+ field("step_written", TypeSchema::U64, "Items the step under way has written.", true),
+ field("steps", TypeSchema::Json, "What each step after the records did, once the copy finished: [{ step, skipped_because, read, written, unchanged, failed, errors }].", true),
],
},
"engine_migrate_cancel" => ControllerSchema {
diff --git a/crates/openhuman-core/src/modules/memory/core_provider.rs b/crates/openhuman-core/src/modules/memory/core_provider.rs
index c8e9da07e3..5496d40ee1 100644
--- a/crates/openhuman-core/src/modules/memory/core_provider.rs
+++ b/crates/openhuman-core/src/modules/memory/core_provider.rs
@@ -183,6 +183,12 @@ impl MemoryProvider for ModuleMemoryProvider {
fn as_answer(&self) -> Option<&dyn MemoryAnswer> {
artifact_serves(Capability::Answer).then_some(self as &dyn MemoryAnswer)
}
+ fn as_episodic_portability(
+ &self,
+ ) -> Option<&dyn tinymemory_api::provider::MemoryEpisodicPortability> {
+ artifact_serves(Capability::EpisodicPortability)
+ .then_some(self as &dyn tinymemory_api::provider::MemoryEpisodicPortability)
+ }
}
#[async_trait]
diff --git a/crates/openhuman-core/src/modules/memory/provider.rs b/crates/openhuman-core/src/modules/memory/provider.rs
index 5394a223cb..e031250df1 100644
--- a/crates/openhuman-core/src/modules/memory/provider.rs
+++ b/crates/openhuman-core/src/modules/memory/provider.rs
@@ -120,6 +120,8 @@ const BOUNDED_READ_OPERATIONS: &[&str] = &[
"entities",
"entity_chunk_ids",
"entity_edges",
+ // tinymemory#178: one page of the episodic record, for an engine switch.
+ "export_episodic",
"estimate_sync_cost_usd",
"export_page",
"extract_entities",
diff --git a/crates/openhuman-core/src/modules/memory/sync_sessions_episodic.rs b/crates/openhuman-core/src/modules/memory/sync_sessions_episodic.rs
index 281bdf7f89..4f514b7143 100644
--- a/crates/openhuman-core/src/modules/memory/sync_sessions_episodic.rs
+++ b/crates/openhuman-core/src/modules/memory/sync_sessions_episodic.rs
@@ -11,12 +11,13 @@ use tinymemory_api::provider::sync::{
SyncRunOutcome,
};
use tinymemory_api::provider::{
- ConversationSegment, EpisodicEvent, EpisodicTurn, MemoryCodingSessions, MemoryEpisodic,
+ ConversationSegment, EpisodicEvent, EpisodicExportPage, EpisodicImportOutcome, EpisodicPart,
+ EpisodicRecords, EpisodicTurn, MemoryCodingSessions, MemoryEpisodic, MemoryEpisodicPortability,
MemorySourceSync,
};
use tinymemory_bus::names::methods;
-use super::provider::{from_bus, module_call, ModuleMemoryProvider};
+use super::provider::{from_bus, module_call, module_call_slow, ModuleMemoryProvider};
/// Bus deadline for the three calls that run a whole source sync inside the
/// module: `RunConnectionSync`, `RunSourceSync` and `BootstrapConnection`.
@@ -314,3 +315,36 @@ impl MemoryEpisodic for ModuleMemoryProvider {
)
}
}
+
+/// The episodic record moving between engines (tinymemory#178). An export page
+/// is request-shaped; an import writes a whole page of rows, so it gets the
+/// bulk deadline.
+#[async_trait]
+impl MemoryEpisodicPortability for ModuleMemoryProvider {
+ async fn export_episodic(
+ &self,
+ part: EpisodicPart,
+ cursor: Option<&str>,
+ limit: usize,
+ ) -> Result<EpisodicExportPage, MemoryError> {
+ let limit = u32::try_from(limit).unwrap_or(u32::MAX);
+ module_call!(
+ self,
+ "export_episodic",
+ methods::EXPORT_EPISODIC,
+ (part, cursor.map(str::to_string), limit)
+ )
+ }
+
+ async fn import_episodic(
+ &self,
+ records: EpisodicRecords,
+ ) -> Result<EpisodicImportOutcome, MemoryError> {
+ module_call_slow!(
+ self,
+ "import_episodic",
+ methods::IMPORT_EPISODIC,
+ (records,)
+ )
+ }
+}
diff --git a/crates/openhuman-core/src/modules/memory_capability_and_dispatch_tests.rs b/crates/openhuman-core/src/modules/memory_capability_and_dispatch_tests.rs
index 4e4a5a422f..1056e04a95 100644
--- a/crates/openhuman-core/src/modules/memory_capability_and_dispatch_tests.rs
+++ b/crates/openhuman-core/src/modules/memory_capability_and_dispatch_tests.rs
@@ -238,6 +238,9 @@ fn every_operation_label_is_classified_and_no_mutation_is_a_read() {
"flush_pending",
"flush_source_tree",
"forget",
+ // tinymemory#178: writes a page of the episodic record into the
+ // engine a switch is copying to.
+ "import_episodic",
"forget_matching",
"forget_source",
"import_records",
diff --git a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs
index aedab426c2..2f148d941b 100644
--- a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs
+++ b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs
@@ -347,7 +347,7 @@ Capability {
name: "Memory Engine",
domain: "intelligence",
category: CapabilityCategory::Intelligence,
- description: "Choose which engine stores and recalls the assistant's memory: the built-in local TinyCortex (default), CortexDB hosted by TinyHumans (billed in credits, uses your signed-in session), or your own Supermemory, Mem0, Cognee, CortexDB or AgentMemory service. Switching applies immediately without a restart, and existing memories can be copied to the new engine first. Keys live in the OS keychain, never in config. Hosted memory also keeps documents, goals, tool rules, the learned profile and episodic memory, takes connector and local-folder syncs, and draws the Brain graph from what the server understood; the local chunk store and its tools (vault, pipeline status, tree rebuild) are only available on the local engine, and other remote engines keep the core memory only.",
+ description: "Choose which engine stores and recalls the assistant's memory: the built-in local TinyCortex (default), CortexDB hosted by TinyHumans (billed in credits, uses your signed-in session), or your own Supermemory, Mem0, Cognee, CortexDB or AgentMemory service. Switching applies immediately without a restart, and existing memories can be copied to the new engine first, with their document titles and tags, goals, the learned profile and conversation history; synced content can be re-sent so the new engine rebuilds its summaries (hosted memory bills for what it reads again). Keys live in the OS keychain, never in config. Hosted memory also keeps documents, goals, tool rules, the learned profile and episodic memory, takes connector and local-folder syncs, and draws the Brain graph from what the server understood; the local chunk store and its tools (vault, pipeline status, tree rebuild) are only available on the local engine, and other remote engines keep the core memory only.",
how_to: "Settings > Memory Engine. Pick an engine, enter its endpoint and key if it needs them, then switch or migrate.",
status: CapabilityStatus::Beta,
privacy: MEMORY_TO_REMOTE_ENGINE,
diff --git a/gitbooks/developing/engines.md b/gitbooks/developing/engines.md
index 747bf4ef6e..a493b5eb7b 100644
--- a/gitbooks/developing/engines.md
+++ b/gitbooks/developing/engines.md
@@ -66,7 +66,10 @@ lists the providers; `factory.rs` builds the client; `schemas.rs` defines the
The memory contract (`tinymemory-api`, vendored at `vendor/tinymemory/`)
defines a driver-neutral `MemoryProvider` trait. Engines are built by
`tinymemory::factory` (`list_engines`, `build_provider`), and
-`tinymemory::migrate::copy` moves every record between two of them.
+`tinymemory::migrate::copy_all` copies a store from one to another: the keyed
+records, then whatever families both engines serve (document titles and tags,
+goals, the learned profile, the conversation history) and the ingested
+content, re-sent raw so the new engine rebuilds its own summaries.
What the user can pick (Settings > Memory Engine, or `openhuman.memory_engine_*`
over RPC):
@@ -91,7 +94,15 @@ config share its binding handle, so they follow a switch; one with its own
lock, `engine_set` is refused while a migration runs, and the commit reloads the
config fresh and patches only `[subsystems.memory]`. Migration (`engine_migrate`) copies first and
switches only after a clean copy; the source is never modified, and a failed
-run leaves the active engine alone. A running copy can be cancelled (`engine_migrate_cancel`, between pages), is
+run leaves the active engine alone. The job reports each step it runs
+(`step`, `steps`), and a step one engine cannot serve is skipped and named
+rather than failed. Re-sending content is the user's choice
+(`replay_content`, on by default, since hosted memory bills for what it reads
+again); a piece the new engine refuses is reported in the job's `note` instead
+of holding the switch back, because the old engine keeps it and its sync can
+bring it again. When the host syncs sources into the new engine itself (hosted
+memory), reader-based sources (`mem_src:` ids) are left out of the replay: the
+host's own sync sends them from scratch. A running copy can be cancelled (`engine_migrate_cancel`, between pages), is
bounded by `OPENHUMAN_MEMORY_MIGRATE_TIMEOUT_SECS` (default 2 hours) and fails, not
hangs, if its task panics. Records written while a copy runs may be missing from
the new engine; the job result carries a `note` saying so, and this migration does not provide a second-pass delta copy. `OPENHUMAN_MEMORY_DRIVER` pins the engine and makes the switch RPCs
diff --git a/tests/memory_engine_migrate_e2e.rs b/tests/memory_engine_migrate_e2e.rs
index 6118e9926b..d3094534c8 100644
--- a/tests/memory_engine_migrate_e2e.rs
+++ b/tests/memory_engine_migrate_e2e.rs
@@ -50,6 +50,37 @@ fn engine_migrate_copies_the_module_into_the_hosted_engine_then_switches() {
.is_some_and(|t| t.contains("canary fact carried across engines"))),
"the migrated record must exist in the hosted engine"
);
+ // Past the keyed records, every step reports, in order. The pinned
+ // module serves documents, goals and the profile, so those ran; what it
+ // does not serve is named rather than failed.
+ let steps = status["steps"].as_array().expect("steps");
+ let names: Vec<&str> = steps.iter().filter_map(|s| s["step"].as_str()).collect();
+ assert_eq!(
+ names,
+ ["documents", "goals", "profile", "episodic", "content"],
+ "{status}"
+ );
+ for step in steps {
+ assert_eq!(step["failed"], 0, "{step}");
+ }
+ let documents = &steps[0];
+ assert!(documents["skipped_because"].is_null(), "{documents}");
+ assert!(
+ documents["written"].as_u64().unwrap_or(0) >= 1,
+ "the canary's title and source type are not the defaults, so its details move: {documents}"
+ );
+ assert!(
+ fx.hosted.events.lock().unwrap().iter().any(|e| {
+ e["scope"]
+ .as_str()
+ .is_some_and(|scope| scope.starts_with("tmi:documents"))
+ && e["content"]["text"]
+ .as_str()
+ .is_some_and(|t| t.contains("migrate-canary"))
+ }),
+ "the canary's details must be recorded in hosted memory"
+ );
+
let state = fx.state().await;
assert_eq!(
state["driver"], "tinyhumans",
diff --git a/vendor/tinymemory b/vendor/tinymemory
index d8f0688df4..bc3d70de91 160000
--- a/vendor/tinymemory
+++ b/vendor/tinymemory
@@ -1 +1 @@
-Subproject commit d8f0688df4792cbeb84a8b2b645d2a926ee0b29f
+Subproject commit bc3d70de918e765657abd73958ede99d6471156a