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(backup): flag folder restores that predate applied migrations and convert restored quota-burn plans (#12355)

[._.]/ Adam Eivye1c7133591e3
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsx
index f9dbcd408d..93d09ae1c2 100644
--- a/client/src/components/BackupWidget.jsx
+++ b/client/src/components/BackupWidget.jsx
@@ -208,6 +208,14 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
Legacy snapshot: no integrity manifest is available. PortOS cannot verify these backup bytes before restore.
</p>
)}
+ {preview.ledgerGap?.count > 0 && (
+ <p className="mb-2 flex items-start gap-1.5 rounded border border-port-warning/40 bg-port-warning/10 p-2 text-xs text-port-warning" role="alert">
+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />
+ <span className="min-w-0 break-words">
+ This snapshot predates {pluralize(preview.ledgerGap.count, 'data migration')} this install has applied ({preview.ledgerGap.names.join(', ')}). A folder restore keeps this install&apos;s migration record, so restored files may stay in their older format. A full restore (leave the folder blank) re-runs the missing migrations on the next start.
+ </span>
+ </p>
+ )}
<p className="text-xs text-gray-500 mb-1">
{preview.changedFiles?.length ?? 0} file(s) would change:
</p>
diff --git a/client/src/components/BackupWidget.test.jsx b/client/src/components/BackupWidget.test.jsx
index 45467c5c91..9d1ec400fb 100644
--- a/client/src/components/BackupWidget.test.jsx
+++ b/client/src/components/BackupWidget.test.jsx
@@ -269,6 +269,38 @@ describe('BackupWidget snapshots', () => {
));
});
+ it('warns when a folder restore installs files older than the applied migrations', async () => {
+ mockRestoreBackup.mockResolvedValue({
+ dryRun: true,
+ changedFiles: ['cos/quota-burn.json'],
+ ledgerGap: { count: 1, names: ['359-example.js'] },
+ });
+ renderWidget();
+ const filter = await openRestorePanel();
+ fireEvent.change(filter, { target: { value: 'cos' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Preview changes' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ /predates 1 data migration this install has applied \(359-example\.js\).*full restore/,
+ );
+ // A warning, not a refusal: a folder no migration touched restores legitimately.
+ expect(screen.getByRole('button', { name: 'Restore 1 file(s)' })).toBeEnabled();
+ });
+
+ it('shows no migration warning for a gap that is empty or unknown', async () => {
+ mockRestoreBackup
+ .mockResolvedValueOnce({ changedFiles: ['cos/quota-burn.json'], ledgerGap: { count: 0, names: [] } })
+ .mockResolvedValueOnce({ changedFiles: ['cos/quota-burn.json'], ledgerGap: null });
+ renderWidget();
+ const filter = await openRestorePanel();
+ fireEvent.change(filter, { target: { value: 'cos' } });
+ for (let i = 0; i < 2; i += 1) {
+ fireEvent.click(screen.getByRole('button', { name: 'Preview changes' }));
+ await screen.findByRole('button', { name: 'Restore 1 file(s)' });
+ expect(screen.queryByRole('alert')).toBeNull();
+ }
+ });
+
it('reports execution verification even when the preview was verified', async () => {
mockRestoreBackup
.mockResolvedValueOnce({
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 84cd6d6c1c..80595bd910 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -509,6 +509,8 @@ After the preflight, rsync copies `<snapshot>/data/` back to `./data/`. Restore
File restore copies what the snapshot holds and leaves live files the snapshot lacks in place. One consequence is handled explicitly: a snapshot taken before the CoS config moved to its own file (#6182) carries its CoS settings inside `cos/state.json` and has no `cos/config.json`. When such a restore lands that legacy slice, the live `cos/config.json` (newer than the restore point) is moved aside to `cos/config.pre-restore-<timestamp>.json` and the settings are recovered from the restored `state.json`; otherwise the newer file would keep winning every read.
+A full restore also installs the snapshot's `migrations.applied.json`, so the next start re-runs every file migration the snapshot predates. A folder restore (`subdirFilter`) keeps the live ledger, so restored files can come back in a shape older than migrations no runner will revisit. Its preview and result therefore carry `ledgerGap`: `{ count, names }` listing the migrations the live ledger records and the snapshot's lacks, or `null` when either ledger is missing or unreadable. A full restore omits the field. The widget warns on a non-empty gap and recommends a full restore, but does not refuse: a folder no migration touched restores correctly. The quota-burn plan is converted on the spot: a restore covering `cos/quota-burn.json` (full, `cos`, or that file) runs any legacy `jobType` steps through the same conversion as migration 359 (`reconcileRestoredQuotaBurnPlan`), reusing each step's deterministic `job-burn-<family>-<step>` custom job, so a repeated restore creates no duplicates.
+
**Every nonzero rsync exit fails a restore, including 24.** A backup tolerates exit 24 ("some source files vanished") because it reads the live data tree, where a file deleted mid-scan is normal. A restore reads a snapshot that must not change under it, so a vanished source file means live data may now mix restored and older files: preview and execution both reject it. An execution failure is reported as a partial restore — the error says some files may already have been overwritten because file restore is not transactional — and caches (settings, Brain, media index) are reconciled before the error is returned, exactly as for any other failed transfer.
#### Database authority is not restored
diff --git a/server/services/backup.js b/server/services/backup.js
index 9ca8d5442c..dac4eeb687 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1396,6 +1396,15 @@ async function reconcileLiveFileRestore(subdirFilter) {
const { reconcileMediaAssets } = await import('./mediaAssetIndex/db.js');
await reconcileMediaAssets({ rebuild: true });
} }] : []),
+ // Migration 359 converts this plan once, at boot, so a plan restored from a
+ // pre-359 snapshot would otherwise stay legacy and unrunnable: a folder
+ // restore keeps the live ledger (359 never re-runs), and a full restore's
+ // ledger only re-runs it on the next boot.
+ ...(!subdirFilter || subdirFilter === 'cos' || subdirFilter === 'cos/quota-burn.json'
+ ? [{ label: 'quota-burn plan conversion', run: async () => {
+ const { reconcileRestoredQuotaBurnPlan } = await import('./quotaBurnConversion.js');
+ await reconcileRestoredQuotaBurnPlan();
+ } }] : []),
];
const results = await Promise.allSettled(
refreshes.map(({ run }) => Promise.resolve().then(run)),
@@ -1693,6 +1702,10 @@ async function restoreHeldSnapshot({ snapshotDir, currentSource }, snapshotId, {
// aid to confirmation, not an integrity lease: snapshot bytes may change
// between requests, especially on removable or network-backed destinations.
const verification = await verifySnapshotFiles(snapshotDir, srcDir, snapshotId, subdirFilter);
+ // A full restore installs the snapshot's ledger too, so the next boot re-runs
+ // whatever it lacks; only a folder restore can leave restored files behind
+ // migrations the live ledger already records.
+ const ledgerGap = subdirFilter ? await migrationLedgerGap(srcDir) : undefined;
// Restore must compare destination bytes even when size and mtime match.
// Rsync's default quick-check would otherwise report a successful no-op for
@@ -1745,7 +1758,7 @@ async function restoreHeldSnapshot({ snapshotDir, currentSource }, snapshotId, {
// A preview holds no owner, fences no identity and reconciles no cache.
if (dryRun) {
const changedFiles = await transferFiles();
- return { dryRun, snapshotId, subdirFilter, changedFiles, verification };
+ return { dryRun, snapshotId, subdirFilter, changedFiles, verification, ...(ledgerGap !== undefined && { ledgerGap }) };
}
const scope = subdirFilter;
@@ -1753,7 +1766,29 @@ async function restoreHeldSnapshot({ snapshotDir, currentSource }, snapshotId, {
subdirFilter,
transfer: () => transferWithIdentityFence({ scope, srcDir, transferFiles }),
}));
- return { dryRun, snapshotId, subdirFilter, changedFiles, verification };
+ return { dryRun, snapshotId, subdirFilter, changedFiles, verification, ...(ledgerGap !== undefined && { ledgerGap }) };
+}
+
+const MIGRATION_LEDGER_FILE = 'migrations.applied.json';
+
+async function readMigrationLedger(path) {
+ const { ok, value } = await readJSONFileStrict(path, null, { logError: false });
+ return ok && Array.isArray(value) ? value.filter(name => typeof name === 'string') : null;
+}
+
+/**
+ * Migrations the live install has applied that the snapshot's ledger lacks:
+ * files a folder restore installs from that snapshot may predate them, and no
+ * runner revisits a migration the live ledger already records. `null` means
+ * unknown — the snapshot (or the live install) has no readable ledger.
+ */
+async function migrationLedgerGap(srcDir) {
+ const snapshotLedger = await readMigrationLedger(join(srcDir, MIGRATION_LEDGER_FILE));
+ const liveLedger = snapshotLedger && await readMigrationLedger(join(PATHS.data, MIGRATION_LEDGER_FILE));
+ if (!snapshotLedger || !liveLedger) return null;
+ const recorded = new Set(snapshotLedger);
+ const names = liveLedger.filter(name => !recorded.has(name));
+ return { count: names.length, names };
}
const COS_RESTORE_SCOPES = ['cos', 'cos/config.json', 'cos/state.json', 'cos/agents'];
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index f7325c6d64..8e0f194743 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -2329,6 +2329,71 @@ describe('restoreSnapshot manifest verification', () => {
expect(withLiveCosRestore).toHaveBeenCalledWith(expect.any(Function), { snapshotLegacyConfig: expected });
});
+ describe('folder restore of an older snapshot (#12355)', () => {
+ const liveLedgerPath = () => joinPath(PATHS.data, 'migrations.applied.json');
+ const liveQuotaBurnPath = () => joinPath(PATHS.cos, 'quota-burn.json');
+ const liveJobsPath = () => joinPath(PATHS.cos, 'autonomous-jobs.json');
+ const legacyPlan = JSON.stringify({ families: { grok: { enabled: true, jobs: [{
+ id: 'step-1', enabled: true, label: 'Example pass', jobType: 'agent-prompt',
+ params: { appId: 'app-example', prompt: 'Rewrite the example copy.' },
+ }] } } });
+
+ afterEach(async () => {
+ for (const path of [liveLedgerPath(), liveQuotaBurnPath(), liveJobsPath()]) await realFs.rm(path, { force: true });
+ });
+
+ async function seedSnapshot({ ledger } = {}) {
+ const manifest = { 'cos/quota-burn.json': await writeSnapshotFile('cos/quota-burn.json', legacyPlan) };
+ if (ledger) manifest['migrations.applied.json'] = await writeSnapshotFile('migrations.applied.json', JSON.stringify(ledger));
+ await writeManifest(manifest);
+ }
+
+ it('reports the migrations the live ledger has applied that the snapshot lacks, in preview and execution', async () => {
+ await seedSnapshot({ ledger: ['001-example.js'] });
+ await realFs.writeFile(liveLedgerPath(), JSON.stringify(['001-example.js', '359-example.js']));
+ const gap = { count: 1, names: ['359-example.js'] };
+
+ await expect(finishRestore({ dryRun: true, subdirFilter: 'cos' })).resolves.toMatchObject({ ledgerGap: gap });
+ spawn.mockReset();
+ await expect(finishRestore({ dryRun: false, subdirFilter: 'cos' })).resolves.toMatchObject({ ledgerGap: gap });
+ });
+
+ it.each([
+ { name: 'matching ledger', ledger: ['001-example.js'], expected: { count: 0, names: [] } },
+ { name: 'snapshot without a ledger', ledger: undefined, expected: null },
+ ])('reports $name as $expected', async ({ ledger, expected }) => {
+ await seedSnapshot({ ledger });
+ await realFs.writeFile(liveLedgerPath(), JSON.stringify(['001-example.js']));
+ expect((await finishRestore({ dryRun: true, subdirFilter: 'cos' })).ledgerGap).toEqual(expected);
+ });
+
+ it('omits the gap from a full restore, which installs the snapshot ledger itself', async () => {
+ await seedSnapshot({ ledger: ['001-example.js'] });
+ await realFs.writeFile(liveLedgerPath(), JSON.stringify(['001-example.js', '359-example.js']));
+ expect(await finishRestore({ dryRun: true })).not.toHaveProperty('ledgerGap');
+ });
+
+ it('converts a restored legacy quota-burn plan to task references, once', async () => {
+ await seedSnapshot();
+ // rsync is faked, so stand in for its transfer of the snapshot plan.
+ await realFs.mkdir(PATHS.cos, { recursive: true });
+ await realFs.writeFile(liveQuotaBurnPath(), legacyPlan);
+
+ await finishRestore({ dryRun: false, subdirFilter: 'cos' });
+ const converted = JSON.parse(await realFs.readFile(liveQuotaBurnPath(), 'utf8')).families.grok.jobs[0];
+ expect(converted).toMatchObject({ jobType: null, taskRef: { kind: 'custom', jobId: 'job-burn-grok-step-1' } });
+
+ // A second restore of the same snapshot finds the job it created last time.
+ await realFs.writeFile(liveQuotaBurnPath(), legacyPlan);
+ spawn.mockReset();
+ await finishRestore({ dryRun: false, subdirFilter: 'cos' });
+ const jobs = JSON.parse(await realFs.readFile(liveJobsPath(), 'utf8')).jobs;
+ expect(jobs.filter(job => job.id === 'job-burn-grok-step-1')).toHaveLength(1);
+ expect(JSON.parse(await realFs.readFile(liveQuotaBurnPath(), 'utf8')).families.grok.jobs[0].taskRef)
+ .toEqual({ kind: 'custom', jobId: 'job-burn-grok-step-1' });
+ });
+ });
+
it('names the unmanifested file so the operator can act on it', async () => {
const relativePath = 'restore-integrity/example.json';
await writeManifest({ [relativePath]: await writeSnapshotFile(relativePath, 'trusted backup') });
diff --git a/server/services/quotaBurnConversion.js b/server/services/quotaBurnConversion.js
index 08481d3e48..315057ae5c 100644
--- a/server/services/quotaBurnConversion.js
+++ b/server/services/quotaBurnConversion.js
@@ -30,6 +30,7 @@ import {
planQuotaBurnStepConversion,
} from '../lib/quotaBurnLegacyConversion.js';
import { normalizeQuotaBurnJob } from '../lib/quotaBurnConfig.js';
+import { getQuotaBurnConfig, saveQuotaBurnConfig } from './quotaBurnStore.js';
/**
* Ensure the custom job a conversion needs exists, and say whether it did.
@@ -103,3 +104,16 @@ export async function convertLegacyQuotaBurnPatch(patch) {
}
return changed ? { ...patch, families: next } : patch;
}
+
+/**
+ * Convert the legacy steps in the plan on disk — the door for a plan a backup
+ * restore just installed. Migration 359 runs once per install, so a plan
+ * restored from a snapshot taken before it would otherwise stay legacy (and
+ * unrunnable) until the user happened to re-save it. An already converted plan
+ * is left untouched and nothing is written.
+ */
+export async function reconcileRestoredQuotaBurnPlan() {
+ const patch = { families: (await getQuotaBurnConfig()).families };
+ const converted = await convertLegacyQuotaBurnPatch(patch);
+ if (converted !== patch) await saveQuotaBurnConfig(converted);
+}