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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(sharing): harden annotation-merge LWW + per-bucket display name
[._.]/ Adam Eivye1ebb4946f20
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c8a7bf67c7..3ef93f3edb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,8 @@## Fixed+- **Sharing/annotation-merge hardening — 5 v2.1.0 residue items.** Outgoing annotation manifests now honor per-bucket `displayNameOverride` (previously all buckets got the global name); peer payloads with missing/invalid `updatedAt` are dropped on import instead of winning LWW via a `now`-fallback; future-skewed peer timestamps are clamped to local-now to stop one bad clock from ratcheting every subsequent merge; `peerInstanceId === 'unknown'` (or empty) is refused on import to match the existing outgoing-path guard; and `exportAnnotationsToBucket` now skips both the asset-dir scan AND the record write when local has no annotations and no prior record exists, so a fresh-install annotation edit doesn't fan an empty manifest into every auto-merge bucket.+## Removed- **`CODEX5.5_REVIEW.md`** at repo root — obsolete now that the concrete bugs are shipped and the strategic items are tracked in PLAN.md.diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.jsindex 27a2971211..177f348bbe 100644--- a/server/services/mediaAnnotations.js+++ b/server/services/mediaAnnotations.js@@ -34,14 +34,25 @@ function emitLocalChange(key) {}}-function sanitizeAuthorEntry(raw) {+const isValidIsoTimestamp = (v) => typeof v === 'string' && !Number.isNaN(Date.parse(v));++function sanitizeAuthorEntry(raw, { clampUpdatedAtTo = null } = {}) {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;- const updatedAt = typeof raw.updatedAt === 'string' && !Number.isNaN(Date.parse(raw.updatedAt))- ? raw.updatedAt- : new Date().toISOString();+ // 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();+ }const authorName = typeof raw.authorName === 'string' && raw.authorName.trim()? raw.authorName.trim().slice(0, 120): '';@@ -142,16 +153,30 @@ export async function listLocalAuthorAnnotations() {export async function mergePeerAnnotations(payload) {if (!payload || typeof payload !== 'object') return { changed: [], projections: new Map() };const peerInstanceId = typeof payload.instanceId === 'string' ? payload.instanceId : null;- if (!peerInstanceId) return { changed: [], projections: new Map() };+ // Reject empty or sentinel `'unknown'` peer ids on import. The outgoing path+ // already guards (`annotationsSync.flushAll` early-returns on `'unknown'`)+ // but a hand-crafted manifest or a peer in an inconsistent state could ship+ // one — without this guard, every such peer would alias into the same+ // `'unknown'` bucket and clobber each other on every merge.+ if (!peerInstanceId || peerInstanceId === 'unknown') return { changed: [], projections: new Map() };const localInstanceId = await getInstanceId().catch(() => null);if (peerInstanceId === localInstanceId) return { changed: [], projections: new Map() };const incoming = payload.annotations && typeof payload.annotations === 'object'? payload.annotations : {};const all = await readAll();const changed = [];+ const clampUpdatedAtTo = Date.now();for (const [key, rawEntry] of Object.entries(incoming)) {if (!isValidKey(key)) continue;- const sane = sanitizeAuthorEntry({ ...rawEntry, authorName: rawEntry?.authorName || payload.authorName });+ // A malformed payload (missing/invalid updatedAt) must be ignored entirely+ // rather than falling through to the tombstone branch — `sanitize` returns+ // 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;+ const sane = sanitizeAuthorEntry(+ { ...rawEntry, authorName: rawEntry?.authorName || payload.authorName },+ { clampUpdatedAtTo },+ );const prior = all[key]?.authors?.[peerInstanceId] ?? null;if (!sane) {if (prior) {diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.jsindex 0795a76f41..4b782475b7 100644--- a/server/services/mediaAnnotations.test.js+++ b/server/services/mediaAnnotations.test.js@@ -120,6 +120,82 @@ describe('mediaAnnotations service (multi-author)', () => {expect(result.changed).toEqual([]);});+ it('mergePeerAnnotations refuses peerInstanceId of "unknown"', async () => {+ const result = await svc.mergePeerAnnotations({+ instanceId: 'unknown',+ authorName: 'Anon',+ annotations: {+ 'image:a.png': { starred: true, note: 'note', updatedAt: '2026-01-01T00:00:00.000Z' },+ },+ });+ expect(result.changed).toEqual([]);+ });++ it('mergePeerAnnotations refuses empty peerInstanceId', async () => {+ const result = await svc.mergePeerAnnotations({+ instanceId: '',+ authorName: 'Anon',+ annotations: {+ 'image:a.png': { starred: true, note: 'note', updatedAt: '2026-01-01T00:00:00.000Z' },+ },+ });+ expect(result.changed).toEqual([]);+ });++ it('mergePeerAnnotations drops entries with missing updatedAt (strict on merge)', async () => {+ fileStore.set(STATE_PATH, {+ annotations: {+ 'image:a.png': {+ authors: {+ 'peer-1': { authorName: 'Sam', starred: true, note: 'existing', updatedAt: '2026-02-01T00:00:00.000Z' },+ },+ },+ },+ });+ const result = await svc.mergePeerAnnotations({+ instanceId: 'peer-1',+ authorName: 'Sam',+ annotations: {+ // No updatedAt — must NOT win LWW by getting a fresh `now` stamp.+ 'image:a.png': { starred: true, note: 'no-timestamp' },+ },+ });+ expect(result.changed).toEqual([]);+ const all = await svc.listAnnotations();+ expect(all['image:a.png'].others[0].note).toBe('existing');+ });++ it('mergePeerAnnotations drops entries with invalid updatedAt (strict on merge)', async () => {+ const result = await svc.mergePeerAnnotations({+ instanceId: 'peer-1',+ authorName: 'Sam',+ annotations: {+ 'image:a.png': { starred: true, note: 'malformed', updatedAt: 'not-a-date' },+ },+ });+ expect(result.changed).toEqual([]);+ });++ it('mergePeerAnnotations clamps future-skewed peer updatedAt to local-now', async () => {+ // Peer clock is years ahead. Without clamping, every subsequent LWW round+ // for the same key would defer to this peer forever.+ const futureTs = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString();+ const beforeMerge = Date.now();+ await svc.mergePeerAnnotations({+ instanceId: 'peer-1',+ authorName: 'Sam',+ annotations: {+ 'image:a.png': { starred: true, note: 'future-skewed', updatedAt: futureTs },+ },+ });+ const afterMerge = Date.now();+ const all = await svc.listAnnotations();+ const stored = all['image:a.png'].others[0];+ const storedMs = Date.parse(stored.updatedAt);+ expect(storedMs).toBeGreaterThanOrEqual(beforeMerge);+ expect(storedMs).toBeLessThanOrEqual(afterMerge);+ });+it('legacy single-author entries are lifted into the local author bucket on read', async () => {fileStore.set(STATE_PATH, {annotations: {diff --git a/server/services/sharing/annotationIdentity.js b/server/services/sharing/annotationIdentity.jsindex 9e580f4851..82f3f92e76 100644--- a/server/services/sharing/annotationIdentity.js+++ b/server/services/sharing/annotationIdentity.js@@ -6,8 +6,10 @@* entries stamp the *global* name (no per-bucket override) so the name is* consistent across every bucket the note flows into.*- * exporter.js#resolveSourceName layers a per-bucket `displayNameOverride`- * short-circuit on top of this for manifest envelopes.+ * `resolveBucketSourceName(bucket)` layers a per-bucket `displayNameOverride`+ * short-circuit on top of the global name for manifest envelopes. Used by+ * both the share-bucket exporter and the annotation-sync flush so every+ * outgoing manifest honors the same override.** Result is memoized for `CACHE_TTL_MS` so hot annotation paths (sync flush,* bucket export, every setAnnotation) don't re-read settings.json off disk@@ -63,3 +65,9 @@ export async function resolveGlobalDisplayName() {}export const resolveLocalAuthorName = resolveGlobalDisplayName;++/** Resolve the bucket-effective display name (per-bucket override → global identity). */+export async function resolveBucketSourceName(bucket) {+ if (bucket?.displayNameOverride) return bucket.displayNameOverride;+ return resolveGlobalDisplayName();+}diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.jsindex f05d4874ab..373b1a1529 100644--- a/server/services/sharing/annotationsSync.js+++ b/server/services/sharing/annotationsSync.js@@ -14,7 +14,7 @@ import { listBuckets } from './buckets.js';import { buildManifest, writeManifest, annotationManifestFilename, readManifest, listManifestFilenames } from './manifest.js';import { getProducedByVersion } from './version.js';import { getInstanceId } from '../instances.js';-import { resolveLocalAuthorName } from './annotationIdentity.js';+import { resolveBucketSourceName } from './annotationIdentity.js';import { onLocalAnnotationChange, listLocalAuthorAnnotations } from '../mediaAnnotations.js';const DEBOUNCE_MS = 2000;@@ -58,18 +58,27 @@ async function listBucketAssetKeys(bucketPath) {return keys;}-async function exportAnnotationsToBucket(bucket, localAnnotations, senderInstanceId, sourceName) {+export async function exportAnnotationsToBucket(bucket, localAnnotations, senderInstanceId) {if (bucket.mode !== 'auto-merge') return { skipped: true, reason: 'not-auto-merge' };+ const recordDir = join(bucket.path, 'records', 'media-annotations');+ const recordId = senderInstanceId;+ const recordPath = join(recordDir, `${recordId}.json`);+ // Cheap early-out: no local annotations AND no prior record means this+ // bucket has nothing to publish and never did. Skip the manifest+asset-dir+ // scan that `listBucketAssetKeys` does — for a fresh install the listener+ // fires for every set/clear on every auto-merge bucket, and most of them+ // hit this branch.+ if (Object.keys(localAnnotations).length === 0 && !existsSync(recordPath)) {+ return { skipped: true, reason: 'no-annotations-for-bucket' };+ }const assetKeys = await listBucketAssetKeys(bucket.path);if (assetKeys.size === 0) return { skipped: true, reason: 'no-bucket-assets' };const filtered = {};for (const [key, entry] of Object.entries(localAnnotations)) {if (assetKeys.has(key)) filtered[key] = entry;}- const recordDir = join(bucket.path, 'records', 'media-annotations');+ const sourceName = await resolveBucketSourceName(bucket);await ensureDir(recordDir);- const recordId = senderInstanceId;- const recordPath = join(recordDir, `${recordId}.json`);// Tombstone synthesis: peers only learn about deletions by seeing them. The// import-side merge (`mergePeerAnnotations`) iterates incoming keys and@@ -95,6 +104,13 @@ async function exportAnnotationsToBucket(bucket, localAnnotations, senderInstancfiltered[key] = { starred: false, note: '', updatedAt: tombstoneTs };}+ // Nothing to publish and nothing was ever published for this (bucket,+ // instance) — skip the record + manifest write so a local annotation edit+ // doesn't fan an empty record into every unrelated auto-merge bucket.+ if (Object.keys(filtered).length === 0 && priorKeys.length === 0) {+ return { skipped: true, reason: 'no-annotations-for-bucket' };+ }+const record = {id: recordId,instanceId: senderInstanceId,@@ -129,17 +145,19 @@ function buildManifestForAnnotations({ senderInstanceId, sourceName, bucket, recasync function flushAll() {// pendingTimer is already cleared by scheduleFlush's setTimeout callback.- const [buckets, senderInstanceId, sourceName, localAnnotations] = await Promise.all([+ // Each bucket resolves its own sourceName inside exportAnnotationsToBucket+ // so per-bucket displayNameOverride is honored (otherwise every bucket+ // would carry the global sharing display name in its annotation envelope).+ const [buckets, senderInstanceId, localAnnotations] = await Promise.all([listBuckets().catch(() => []),getInstanceId().catch(() => null),- resolveLocalAuthorName().catch(() => 'unknown'),listLocalAuthorAnnotations().catch(() => ({})),]);if (!senderInstanceId || senderInstanceId === 'unknown') return;const autoMerge = buckets.filter((b) => b.mode === 'auto-merge');if (autoMerge.length === 0) return;await Promise.all(autoMerge.map(async (bucket) => {- const res = await exportAnnotationsToBucket(bucket, localAnnotations, senderInstanceId, sourceName).catch((err) => {+ const res = await exportAnnotationsToBucket(bucket, localAnnotations, senderInstanceId).catch((err) => {console.error(`⚠️ sharing.annotations: export to bucket=${bucket.name} failed: ${err.message}`);return null;});diff --git a/server/services/sharing/annotationsSync.test.js b/server/services/sharing/annotationsSync.test.jsnew file mode 100644index 0000000000..4d2d4db592--- /dev/null+++ b/server/services/sharing/annotationsSync.test.js@@ -0,0 +1,180 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';++// Mock store for atomicWrite + readJSONFile so we can inspect record writes.+const fileStore = new Map();+const writeCalls = [];++vi.mock('../../lib/fileUtils.js', () => ({+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn(async (path, data) => {+ fileStore.set(path, data);+ writeCalls.push({ path, data });+ }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+ PATHS: { data: '/mock/data' },+}));++// Mock manifest module so we don't need real bucket directories.+const writeManifestMock = vi.fn(async (bucketPath, manifest) => `${manifest.kind}.manifest.json`);+vi.mock('./manifest.js', () => ({+ buildManifest: vi.fn((args) => ({ ...args })),+ writeManifest: writeManifestMock,+ readManifest: vi.fn(),+ listManifestFilenames: vi.fn(async () => []),+ annotationManifestFilename: vi.fn(),+}));++vi.mock('./version.js', () => ({ getProducedByVersion: vi.fn(async () => '1.0.0-test') }));++vi.mock('./buckets.js', () => ({+ listBuckets: vi.fn(async () => []),+}));++vi.mock('../instances.js', () => ({+ getInstanceId: vi.fn(async () => 'local-instance'),+}));++vi.mock('./annotationIdentity.js', () => ({+ // Honors `displayNameOverride`; mirrors the real helper's contract.+ resolveBucketSourceName: vi.fn(async (bucket) => bucket?.displayNameOverride || 'Global Name'),+}));++vi.mock('../mediaAnnotations.js', () => ({+ onLocalAnnotationChange: vi.fn(),+ listLocalAuthorAnnotations: vi.fn(async () => ({})),+}));++// Make existsSync return true for any assets dir so the legacy-v1 scan no-ops+// without touching the disk.+vi.mock('fs', async () => {+ const actual = await vi.importActual('fs');+ return { ...actual, existsSync: vi.fn(() => false) };+});++// Stub `assets/{images,videos}` readdir to return [] (legacy v1 fallback).+vi.mock('fs/promises', async () => {+ const actual = await vi.importActual('fs/promises');+ return { ...actual, readdir: vi.fn(async () => []) };+});++const svc = await import('./annotationsSync.js');++function bucket({ id = 'bkt-1', name = 'B1', path = '/mock/bucket', mode = 'auto-merge', displayNameOverride = null } = {}) {+ return { id, name, path, mode, displayNameOverride };+}++describe('sharing/annotationsSync.exportAnnotationsToBucket', () => {+ beforeEach(() => {+ fileStore.clear();+ writeCalls.length = 0;+ writeManifestMock.mockClear();+ });++ async function stubBucketAssets(bucketPath, keys) {+ // Simulate the bucket containing `keys` (each `${kind}:${ref}`).+ const { listManifestFilenames, readManifest } = await import('./manifest.js');+ listManifestFilenames.mockResolvedValue(['mock.manifest.json']);+ readManifest.mockResolvedValue({+ assetRefs: keys.map((k) => {+ const [kind, ref] = k.split(':');+ return { kind, ref };+ }),+ collection: null,+ });+ }++ it('skips without scanning bucket assets when local has zero annotations and no prior record', async () => {+ // Common fan-out case for a fresh install: every set/clear hits every+ // auto-merge bucket. Most have no prior record and no local annotation+ // matching their assets — this branch keeps them off the slow path.+ const { listManifestFilenames } = await import('./manifest.js');+ listManifestFilenames.mockClear();+ const res = await svc.exportAnnotationsToBucket(bucket(), {}, 'local-instance');+ expect(res).toEqual({ skipped: true, reason: 'no-annotations-for-bucket' });+ expect(listManifestFilenames).not.toHaveBeenCalled();+ });++ it('skips when bucket has no assets', async () => {+ const { listManifestFilenames } = await import('./manifest.js');+ listManifestFilenames.mockResolvedValue([]);++ const res = await svc.exportAnnotationsToBucket(bucket(), { 'image:a.png': { starred: true, note: '', updatedAt: '2026-01-01T00:00:00.000Z' } }, 'local-instance');+ expect(res).toEqual({ skipped: true, reason: 'no-bucket-assets' });+ expect(writeManifestMock).not.toHaveBeenCalled();+ });++ it('skips when no annotations apply to bucket and nothing was previously written', async () => {+ await stubBucketAssets('/mock/bucket', ['image:other.png']);++ const res = await svc.exportAnnotationsToBucket(+ bucket(),+ { 'image:a.png': { starred: true, note: '', updatedAt: '2026-01-01T00:00:00.000Z' } },+ 'local-instance',+ );+ expect(res.skipped).toBe(true);+ expect(res.reason).toBe('no-annotations-for-bucket');+ expect(writeManifestMock).not.toHaveBeenCalled();+ });++ it('writes record + manifest when the bucket holds a matching asset', async () => {+ await stubBucketAssets('/mock/bucket', ['image:a.png']);++ const res = await svc.exportAnnotationsToBucket(+ bucket(),+ { 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } },+ 'local-instance',+ );+ expect(res.skipped).toBe(false);+ expect(res.entryCount).toBe(1);+ expect(writeManifestMock).toHaveBeenCalledTimes(1);+ const written = writeCalls[0].data;+ expect(written.annotations['image:a.png']).toMatchObject({ starred: true, note: 'hi' });+ expect(written.authorName).toBe('Global Name');+ });++ it('honors per-bucket displayNameOverride in the written record', async () => {+ await stubBucketAssets('/mock/bucket', ['image:a.png']);++ await svc.exportAnnotationsToBucket(+ bucket({ displayNameOverride: 'Per-Bucket Alias' }),+ { 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } },+ 'local-instance',+ );+ expect(writeCalls[0].data.authorName).toBe('Per-Bucket Alias');+ });++ it('emits tombstones for keys that were previously published but no longer applicable', async () => {+ await stubBucketAssets('/mock/bucket', ['image:a.png', 'image:gone.png']);+ // Pre-seed a prior record where both keys had notes.+ fileStore.set('/mock/bucket/records/media-annotations/local-instance.json', {+ id: 'local-instance',+ instanceId: 'local-instance',+ authorName: 'Global Name',+ updatedAt: '2026-01-01T00:00:00.000Z',+ annotations: {+ 'image:a.png': { starred: true, note: 'old', updatedAt: '2026-01-01T00:00:00.000Z' },+ 'image:gone.png': { starred: true, note: 'will-tombstone', updatedAt: '2026-01-01T00:00:00.000Z' },+ },+ });++ // Local now only has `image:a.png`; `image:gone.png` should get tombstoned.+ const res = await svc.exportAnnotationsToBucket(+ bucket(),+ { 'image:a.png': { starred: true, note: 'still-here', updatedAt: '2026-02-01T00:00:00.000Z' } },+ 'local-instance',+ );+ expect(res.skipped).toBe(false);+ const written = writeCalls[0].data;+ expect(written.annotations['image:a.png']).toMatchObject({ note: 'still-here' });+ expect(written.annotations['image:gone.png']).toMatchObject({ starred: false, note: '' });+ });++ it('skips inbox-mode buckets', async () => {+ const res = await svc.exportAnnotationsToBucket(+ bucket({ mode: 'inbox' }),+ { 'image:a.png': { starred: true, note: 'hi', updatedAt: '2026-01-01T00:00:00.000Z' } },+ 'local-instance',+ );+ expect(res).toEqual({ skipped: true, reason: 'not-auto-merge' });+ });+});diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex edff714361..8779647642 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -30,13 +30,7 @@ import { getInstanceId } from '../instances.js';import { getSettings } from '../settings.js';import { getProducedByVersion } from './version.js';import { isStr } from '../../lib/storyBible.js';-import { resolveGlobalDisplayName } from './annotationIdentity.js';--/** Resolve the bucket-effective display name (per-bucket override → global identity). */-async function resolveSourceName(bucket) {- if (bucket.displayNameOverride) return bucket.displayNameOverride;- return resolveGlobalDisplayName();-}+import { resolveBucketSourceName as resolveSourceName } from './annotationIdentity.js';/*** Best-effort cap on the bucket's manifest directory after each export.