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: rebuild a corrupt time-capsule index from snapshot files (#7010)

[._.]/ Adam Eivyb259cf4eafe1
diff --git a/server/services/timeCapsule.js b/server/services/timeCapsule.js
index d8d8b189cf..31fb3ec136 100644
--- a/server/services/timeCapsule.js
+++ b/server/services/timeCapsule.js
@@ -9,7 +9,7 @@ import { unlink, readdir } from 'fs/promises';
import { join } from 'path';
import { createHash } from 'crypto';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { atomicWrite, ensureDir, PATHS, readJSONFile, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, ensureDir, PATHS, readJSONFile, readJSONFileStrict, tryReadFile } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
const DIGITAL_TWIN_DIR = PATHS.digitalTwin;
@@ -28,20 +28,43 @@ async function ensureSnapshotsDir() {
await ensureDir(SNAPSHOTS_DIR);
}
-function normalizeIndex(parsed) {
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
- return { snapshots: [] };
+function indexEntryFromSnapshotFile(parsed) {
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || !parsed.id) return null;
+ const meta = { ...parsed };
+ delete meta.data;
+ return meta;
+}
+
+async function recoverIndexFromSnapshotFiles(reason) {
+ const entries = await readdir(SNAPSHOTS_DIR).catch(() => []);
+ const metas = await Promise.all(
+ entries
+ .filter(name => name.endsWith('.json') && name !== 'index.json')
+ .map(async name => indexEntryFromSnapshotFile(
+ await readJSONFile(join(SNAPSHOTS_DIR, name), null)
+ ))
+ );
+ const snapshots = metas
+ .filter(Boolean)
+ .sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')));
+ if (reason || snapshots.length > 0) {
+ console.warn(`⚠️ Time-capsule index ${reason || 'missing'} — rebuilt listing of ${snapshots.length} snapshot file(s)`);
}
- return {
- snapshots: Array.isArray(parsed.snapshots) ? parsed.snapshots : [],
- };
+ return { snapshots };
+}
+
+function isUsableIndex(parsed) {
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) && Array.isArray(parsed.snapshots);
}
async function loadIndex() {
await ensureSnapshotsDir();
- // Missing, empty, or corrupt index recovers as empty rather than throwing —
- // a truncated index.json used to disable every snapshot operation.
- return normalizeIndex(await readJSONFile(INDEX_FILE, null));
+ const { ok, value } = await readJSONFileStrict(INDEX_FILE, null);
+ if (ok && isUsableIndex(value)) return { snapshots: value.snapshots };
+ // Missing, empty, corrupt, or wrong-shaped index must not throw (that used
+ // to disable every snapshot op). Rebuild from on-disk snapshot files so a
+ // later save does not orphan listings that the bytes still hold.
+ return recoverIndexFromSnapshotFiles(ok ? (value == null ? null : 'malformed') : 'unreadable');
}
async function saveIndex(index) {
@@ -136,12 +159,13 @@ export async function createSnapshot(label, description = '') {
summary: buildSummary(data)
};
- // Save snapshot data
- const snapshotFile = join(SNAPSHOTS_DIR, `${snapshot.id}.json`);
- await atomicWrite(snapshotFile, { ...snapshot, data });
-
return queueIndexWrite(async () => {
+ // Load (and maybe rebuild) the index BEFORE writing this snapshot file so
+ // a recovery scan cannot pick up the file we are about to add, then
+ // unshift a duplicate of it.
const index = await loadIndex();
+ const snapshotFile = join(SNAPSHOTS_DIR, `${snapshot.id}.json`);
+ await atomicWrite(snapshotFile, { ...snapshot, data });
index.snapshots.unshift(snapshot);
await saveIndex(index);
console.log(`📸 Time capsule created: "${label}" (${snapshot.id.slice(0, 8)})`);
diff --git a/server/services/timeCapsule.test.js b/server/services/timeCapsule.test.js
index 851b37f924..ca9f43d423 100644
--- a/server/services/timeCapsule.test.js
+++ b/server/services/timeCapsule.test.js
@@ -66,6 +66,25 @@ describe('listSnapshots', () => {
writeFileSync(indexPath(), JSON.stringify({ snapshots: 'nope' }));
await expect(listSnapshots()).resolves.toEqual([]);
});
+
+ it('rebuilds the listing from on-disk snapshot files when the index is corrupt', async () => {
+ mkdirSync(snapshotsDir(), { recursive: true });
+ const kept = {
+ id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
+ label: 'kept',
+ createdAt: '2026-01-02T00:00:00.000Z',
+ data: { 'identity.json': { name: 'Example Twin' } },
+ };
+ writeFileSync(join(snapshotsDir(), `${kept.id}.json`), JSON.stringify(kept));
+ writeFileSync(indexPath(), '{truncated');
+
+ const listed = await listSnapshots();
+ expect(listed).toEqual([{
+ id: kept.id,
+ label: 'kept',
+ createdAt: kept.createdAt,
+ }]);
+ });
});
describe('createSnapshot', () => {
@@ -98,6 +117,22 @@ describe('createSnapshot', () => {
expect(readIndex().snapshots.map(s => s.id)).toEqual([snapshot.id]);
});
+ it('keeps prior snapshot files in the index when creating after corruption', async () => {
+ mkdirSync(snapshotsDir(), { recursive: true });
+ const kept = {
+ id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
+ label: 'kept',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ data: { 'identity.json': { name: 'Example Twin' } },
+ };
+ writeFileSync(join(snapshotsDir(), `${kept.id}.json`), JSON.stringify(kept));
+ writeFileSync(indexPath(), '{truncated');
+ writeTwinJson('identity.json', { name: 'Example Twin' });
+
+ const snapshot = await createSnapshot('after-corrupt');
+ expect(readIndex().snapshots.map(s => s.id).sort()).toEqual([kept.id, snapshot.id].sort());
+ });
+
it('skips a markdown directory that would fail a TOCTOU stat-then-read', async () => {
mkdirSync(join(twinDir(), 'journal.md'), { recursive: true });
writeTwinJson('identity.json', { name: 'Example Twin' });