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): persist peer documents before publishing references

[._.]/ Adam Eivy9dd9f305838f
diff --git a/server/services/digital-twin-publication.test.js b/server/services/digital-twin-publication.test.js
index 622ad5803b..fb519ddc36 100644
--- a/server/services/digital-twin-publication.test.js
+++ b/server/services/digital-twin-publication.test.js
@@ -90,7 +90,7 @@ describe('enrichment document publication', () => {
});
describe('peer document sync publication', () => {
- it('drains the meta-first merge through the missing markdown copy', async () => {
+ it('drains the missing markdown copy through the metadata merge', async () => {
const reached = deferred(); const finish = deferred();
state.beforeWrite = async path => { if (path.endsWith('EXAMPLE.md')) { reached.resolve(); await finish.promise; } };
const work = applyDigitalTwinRemote({ meta: { documents: [document('EXAMPLE.md')] }, documents: { 'EXAMPLE.md': '# Example body' } });
@@ -100,6 +100,46 @@ describe('peer document sync publication', () => {
});
});
+ it('leaves old metadata and tombstoned bytes intact when a peer document write fails, then retries', async () => {
+ await seed({ documents: [document('OLD.md')] });
+ await writeFile(join(root, 'OLD.md'), '# Old body');
+ const deletedAt = new Date().toISOString();
+ const remote = { meta: { documents: [document('NEW.md')], deletedDocuments: [{ filename: 'OLD.md', deletedAt }] },
+ documents: { 'NEW.md': '# New body' } };
+ state.beforeWrite = async path => { if (path.endsWith('NEW.md')) throw new Error('injected markdown failure'); };
+ await expect(applyDigitalTwinRemote(remote)).rejects.toThrow('injected markdown failure');
+ const release = await acquireBackupSnapshotCut();
+ try {
+ const { files, meta } = await snapshot();
+ expect(meta.documents.map(doc => doc.filename)).toEqual(['OLD.md']);
+ expect(meta.deletedDocuments).toEqual([]);
+ expect(files['OLD.md']).toBe('# Old body');
+ expect(files['NEW.md']).toBeUndefined();
+ } finally { release(); }
+ state.beforeWrite = null;
+ await applyDigitalTwinRemote(remote);
+ const { files, meta } = await snapshot();
+ expect(meta.documents.map(doc => doc.filename)).toEqual(['NEW.md']);
+ expect(meta.deletedDocuments).toEqual([{ filename: 'OLD.md', deletedAt }]);
+ expect(files['NEW.md']).toBe('# New body');
+ expect(files['OLD.md']).toBeUndefined();
+ });
+
+ it('does not reap existing bytes when merged metadata persistence fails', async () => {
+ await seed({ documents: [document('OLD.md')] });
+ await writeFile(join(root, 'OLD.md'), '# Old body');
+ state.beforeWrite = async path => { if (path.endsWith('meta.json')) throw new Error('injected meta failure'); };
+ await expect(applyDigitalTwinRemote({ meta: { documents: [document('NEW.md')],
+ deletedDocuments: [{ filename: 'OLD.md', deletedAt: new Date().toISOString() }] },
+ documents: { 'NEW.md': '# New body' } })).rejects.toThrow('injected meta failure');
+ const release = await acquireBackupSnapshotCut();
+ try {
+ const { files, meta } = await snapshot();
+ expect(meta.documents.map(doc => doc.filename)).toEqual(['OLD.md']);
+ expect(files['OLD.md']).toBe('# Old body');
+ } finally { release(); }
+ });
+
it('keeps the merged tombstone and reaping in the same drained cut', async () => {
await seed({ documents: [document('EXAMPLE.md')] });
await writeFile(join(root, 'EXAMPLE.md'), '# Old example');
diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.js
index e5d7d6a476..24c4d63406 100644
--- a/server/services/digital-twin-sync.js
+++ b/server/services/digital-twin-sync.js
@@ -803,21 +803,8 @@ async function applyMerge(path, remote, mergeFn, { dir } = {}) {
return 1;
}
-/**
- * The set of document filenames a delete tombstone currently suppresses (#3530).
- *
- * Read straight off META_FILE rather than through `loadMeta()`: loadMeta's
- * missing-file path REBUILDS meta from a disk scan and saves it, which is
- * exactly the side effect the meta-before-documents ordering below exists to
- * avoid. applyMeta has already written the merged tombstones, so the file is
- * current.
- *
- * A filename that survived the merge as a live document entry is never
- * suppressed — that is the re-created-after-delete case, where the document's
- * `createdAt` superseded the tombstone.
- */
-async function readSuppressedDocuments() {
- const meta = await readJSONFile(META_FILE, null, { strict: true });
+// Compute suppression from the prepared merge before publishing references.
+function suppressedDocuments(meta) {
if (!isPlainObject(meta)) return new Set();
const live = new Set(
(Array.isArray(meta.documents) ? meta.documents : [])
@@ -932,19 +919,18 @@ export async function applyDigitalTwinRemote(remoteData) {
count += await applyMerge(TASTE_OBSERVED_FILE, remoteData.tasteObserved, mergeTasteObserved);
count += await applyMerge(CHRONOTYPE_OBSERVED_FILE, remoteData.chronotypeObserved, mergeChronotypeObserved);
count += await withBackupAssetPublication(async () => {
- // Meta BEFORE documents: applyMeta()'s loadMeta() rebuilds meta from a disk
- // .md scan when no meta.json exists, creating DEFAULT document entries. If the
- // peer's .md files were written first, that rebuild would manufacture default
- // entries and mergeMeta's add-only policy would then keep them, discarding the
- // sender's real document metadata (title/category/priority/weight). Merging
- // meta first preserves the sender's entries; the files are written after.
- let documentCount = await applyMeta(remoteData.meta);
- // Delete tombstones (#3530) gate both directions of the document apply: reap
- // local files a peer's delete covers, and skip re-writing anything this
- // machine deleted. Read AFTER applyMeta so the merged tombstone list is on disk.
- const suppressed = await readSuppressedDocuments();
- documentCount += await reapTombstonedDocuments(suppressed);
- documentCount += await applyDocuments(remoteData.documents, suppressed);
+ // Load before copying: a missing meta file is rebuilt from local markdown,
+ // and must not manufacture defaults for the peer's not-yet-published files.
+ const { loadMeta } = await import('./digital-twin-meta.js');
+ const local = await loadMeta();
+ const prepared = isPlainObject(remoteData.meta) ? mergeMeta(local, remoteData.meta).merged : local;
+ // A failed file write must leave the durable metadata unchanged. Re-merge
+ // after the I/O so concurrent local metadata updates are retained. Persist
+ // tombstones before removing their bytes, so failure cannot strand a live
+ // document reference pointing at an already-reaped file.
+ let documentCount = await applyDocuments(remoteData.documents, suppressedDocuments(prepared));
+ documentCount += await applyMeta(remoteData.meta);
+ documentCount += await reapTombstonedDocuments(suppressedDocuments(await loadMeta()));
return documentCount;
});
@@ -957,8 +943,7 @@ export async function applyDigitalTwinRemote(remoteData) {
count += await applySocialAccounts(remoteData.socialAccounts);
- // Meta is saved before document files land. Reconcile again only after the
- // complete sync so status cannot remain at the pre-document count.
+ // Refresh status after the complete document and metadata publication.
if (count > 0) {
const { digitalTwinEvents } = await import('./digital-twin-meta.js');
digitalTwinEvents.emit('sync:completed');