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

address codex review: LWW gate on tombstone path + await producedByVersion

[._.]/ Adam Eivy2e97a74e5dc8
diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.js
index 177f348bbe..c3ebcb8dca 100644
--- a/server/services/mediaAnnotations.js
+++ b/server/services/mediaAnnotations.js
@@ -36,23 +36,17 @@ function emitLocalChange(key) {
const isValidIsoTimestamp = (v) => typeof v === 'string' && !Number.isNaN(Date.parse(v));
-function sanitizeAuthorEntry(raw, { clampUpdatedAtTo = null } = {}) {
+function sanitizeAuthorEntry(raw) {
if (!raw || typeof raw !== 'object') return null;
const starred = raw.starred === true;
const note = typeof raw.note === 'string' ? raw.note.slice(0, NOTE_MAX_LENGTH) : '';
if (!starred && !note) return null;
// Read-path callers (legacy migration, on-disk hydration) tolerate a missing
// updatedAt and stamp `now` so the entry is still usable. The merge path
- // pre-rejects malformed payloads in `mergePeerAnnotations` before calling
- // here, so a peer record with a missing updatedAt never reaches this fallback.
- let updatedAt = isValidIsoTimestamp(raw.updatedAt) ? raw.updatedAt : new Date().toISOString();
- // Merge path clamps a future-skewed peer timestamp to local-now: a peer
- // whose clock is years ahead would otherwise dominate every subsequent LWW
- // round on the same key. Clamping caps the upper bound at local-now without
- // disturbing reasonable timestamps.
- if (clampUpdatedAtTo && Date.parse(updatedAt) > clampUpdatedAtTo) {
- updatedAt = new Date(clampUpdatedAtTo).toISOString();
- }
+ // pre-validates AND clamps `updatedAt` in `mergePeerAnnotations` before
+ // calling here so the LWW gate sees the clamped value for both content
+ // entries and tombstones.
+ const updatedAt = isValidIsoTimestamp(raw.updatedAt) ? raw.updatedAt : new Date().toISOString();
const authorName = typeof raw.authorName === 'string' && raw.authorName.trim()
? raw.authorName.trim().slice(0, 120)
: '';
@@ -173,12 +167,23 @@ export async function mergePeerAnnotations(payload) {
// null for BOTH "empty tombstone" and "malformed", and the tombstone branch
// would otherwise delete the prior peer entry on any garbage payload.
if (!isValidIsoTimestamp(rawEntry?.updatedAt)) continue;
+ // Clamp the incoming timestamp here so BOTH content entries AND tombstones
+ // go through the same LWW gate (sanitize returns null for tombstones, so
+ // we lose access to the timestamp downstream). A future-skewed peer can't
+ // dominate forever — its clamped tombstone competes fairly against a
+ // newer-prior peer entry.
+ const incomingMs = Math.min(Date.parse(rawEntry.updatedAt), clampUpdatedAtTo);
+ const incomingUpdatedAt = new Date(incomingMs).toISOString();
+ const prior = all[key]?.authors?.[peerInstanceId] ?? null;
+ // LWW gate applies to both content writes and tombstone deletes. Without
+ // the gate, an older tombstone (or a stale replay of an old delete) would
+ // erase a newer prior peer entry.
+ if (prior && (prior.updatedAt || '') >= incomingUpdatedAt) continue;
const sane = sanitizeAuthorEntry(
- { ...rawEntry, authorName: rawEntry?.authorName || payload.authorName },
- { clampUpdatedAtTo },
+ { ...rawEntry, authorName: rawEntry?.authorName || payload.authorName, updatedAt: incomingUpdatedAt },
);
- const prior = all[key]?.authors?.[peerInstanceId] ?? null;
if (!sane) {
+ // Tombstone wins LWW — delete the prior peer entry.
if (prior) {
delete all[key].authors[peerInstanceId];
if (Object.keys(all[key].authors).length === 0) delete all[key];
@@ -186,7 +191,6 @@ export async function mergePeerAnnotations(payload) {
}
continue;
}
- if (prior && (prior.updatedAt || '') >= sane.updatedAt) continue;
if (!all[key]) all[key] = { authors: {} };
all[key].authors[peerInstanceId] = sane;
changed.push(key);
diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.js
index 4b782475b7..cd186226a9 100644
--- a/server/services/mediaAnnotations.test.js
+++ b/server/services/mediaAnnotations.test.js
@@ -109,6 +109,55 @@ describe('mediaAnnotations service (multi-author)', () => {
expect(all['image:a.png'].others[0].note).toBe('newer');
});
+ it('mergePeerAnnotations refuses an older tombstone (tombstones go through LWW)', async () => {
+ // Critical correctness invariant: a stale or replayed tombstone must NOT
+ // erase a newer prior peer entry. Without the LWW gate on the tombstone
+ // branch, any garbage-collected delete from the past would clobber live
+ // state.
+ fileStore.set(STATE_PATH, {
+ annotations: {
+ 'image:a.png': {
+ authors: {
+ 'peer-1': { authorName: 'Sam', starred: true, note: 'live', updatedAt: '2026-02-01T00:00:00.000Z' },
+ },
+ },
+ },
+ });
+ const result = await svc.mergePeerAnnotations({
+ instanceId: 'peer-1',
+ authorName: 'Sam',
+ annotations: {
+ // Tombstone (starred:false, note:'') with an older timestamp.
+ 'image:a.png': { starred: false, note: '', updatedAt: '2026-01-01T00:00:00.000Z' },
+ },
+ });
+ expect(result.changed).toEqual([]);
+ const all = await svc.listAnnotations();
+ expect(all['image:a.png'].others[0].note).toBe('live');
+ });
+
+ it('mergePeerAnnotations applies a newer tombstone (tombstones win when fresher)', async () => {
+ fileStore.set(STATE_PATH, {
+ annotations: {
+ 'image:a.png': {
+ authors: {
+ 'peer-1': { authorName: 'Sam', starred: true, note: 'stale', updatedAt: '2026-01-01T00:00:00.000Z' },
+ },
+ },
+ },
+ });
+ const result = await svc.mergePeerAnnotations({
+ instanceId: 'peer-1',
+ authorName: 'Sam',
+ annotations: {
+ 'image:a.png': { starred: false, note: '', updatedAt: '2026-02-01T00:00:00.000Z' },
+ },
+ });
+ expect(result.changed).toEqual(['image:a.png']);
+ const all = await svc.listAnnotations();
+ expect(all['image:a.png']).toBeUndefined();
+ });
+
it('mergePeerAnnotations refuses to write under local instanceId', async () => {
const result = await svc.mergePeerAnnotations({
instanceId: LOCAL_INSTANCE,
diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.js
index 373b1a1529..aaeb8d467f 100644
--- a/server/services/sharing/annotationsSync.js
+++ b/server/services/sharing/annotationsSync.js
@@ -119,18 +119,8 @@ export async function exportAnnotationsToBucket(bucket, localAnnotations, sender
annotations: filtered,
};
await atomicWrite(recordPath, record);
- const manifest = buildManifestForAnnotations({
- senderInstanceId,
- sourceName,
- bucket,
- recordId,
- });
- const filename = await writeManifest(bucket.path, manifest);
- return { skipped: false, filename, entryCount: Object.keys(filtered).length };
-}
-
-function buildManifestForAnnotations({ senderInstanceId, sourceName, bucket, recordId }) {
- return buildManifest({
+ const producedByVersion = await getProducedByVersion();
+ const manifest = buildManifest({
kind: 'media-annotations',
senderInstanceId,
source: sourceName,
@@ -139,8 +129,10 @@ function buildManifestForAnnotations({ senderInstanceId, sourceName, bucket, rec
assetRefs: [],
bucketId: bucket.id,
bucketName: bucket.name,
- producedByVersion: getProducedByVersion(),
+ producedByVersion,
});
+ const filename = await writeManifest(bucket.path, manifest);
+ return { skipped: false, filename, entryCount: Object.keys(filtered).length };
}
async function flushAll() {
diff --git a/server/services/sharing/annotationsSync.test.js b/server/services/sharing/annotationsSync.test.js
index 4d2d4db592..0343cc42c6 100644
--- a/server/services/sharing/annotationsSync.test.js
+++ b/server/services/sharing/annotationsSync.test.js
@@ -132,7 +132,7 @@ describe('sharing/annotationsSync.exportAnnotationsToBucket', () => {
expect(written.authorName).toBe('Global Name');
});
- it('honors per-bucket displayNameOverride in the written record', async () => {
+ it('honors per-bucket displayNameOverride in both the written record AND the manifest envelope', async () => {
await stubBucketAssets('/mock/bucket', ['image:a.png']);
await svc.exportAnnotationsToBucket(
@@ -140,7 +140,17 @@ describe('sharing/annotationsSync.exportAnnotationsToBucket', () => {
{ 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } },
'local-instance',
);
+ // Record's authorName carries the per-bucket alias.
expect(writeCalls[0].data.authorName).toBe('Per-Bucket Alias');
+ // Manifest envelope's `source` (the field consumed by peers when
+ // attributing the bucket's authorship) carries the same alias — this is
+ // the surface that previously regressed by stamping the global name.
+ expect(writeManifestMock).toHaveBeenCalledTimes(1);
+ const manifest = writeManifestMock.mock.calls[0][1];
+ expect(manifest.source).toBe('Per-Bucket Alias');
+ // producedByVersion must be a string, not an unawaited Promise.
+ expect(typeof manifest.producedByVersion).toBe('string');
+ expect(manifest.producedByVersion).toBe('1.0.0-test');
});
it('emits tombstones for keys that were previously published but no longer applicable', async () => {