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: propagate deleted and date-moved meatspace drink/nicotine events across peers (#8154)
[._.]/ Adam Eivy356fbe0f678e
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 4c01ceef04..950969aa82 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -763,6 +763,24 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// Its content union still keeps an edited row beside the unedited copy (it// cannot read `replaces`) — the same double row an edit between two v0// peers has always produced, cleared once that peer upgrades.+ //+ // Still v1 after #8154, which added deletes and date moves for id'd events:+ // a top-level `eventTombstones: [{ id, deletedAt }]` list (unioned both ways)+ // and a whole-log pass that keeps one copy per id, on whichever date the+ // newest copy lives. That is additive, and a bump would make every older+ // receiver refuse ALL daily-log data, new drinks included. With a pre-#8154+ // peer in the federation:+ // - It keeps a deleted or moved-away copy (it cannot read tombstones and+ // merges ids per date) and sends it back each cycle. A current receiver+ // drops that copy again — it is not newer than the tombstone, and the+ // moved copy's newer stamp wins the id — so only the old peer+ // double-counts, until it upgrades.+ // - It cannot strip tombstones from a current peer: the list is unioned, and+ // the old peer's own writes keep unknown top-level fields. Its own copy of+ // the list only refreshes when its local file lacks the key, so it may+ // send a stale subset back, which a union ignores.+ // Rows without an `id` (logged before #8143) are still add-only: deleting+ // or moving one does not reach peers.// The key exists so the NEXT incompatible daily-log change can bump to 2 and// have v1 receivers reject it.meatspace: 1,diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex 8e350b489b..068a9343ae 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -12,6 +12,12 @@ import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';import { canonicalStringify, isEmptyScalar, isPlainObject } from '../lib/objects.js';import { snapshotChecksum } from '../lib/snapshotChecksum.js';import { parseTsMs } from '../lib/lwwTimestamp.js';+import { isTombstoned, mergeTombstones, pruneTombstones } from '../lib/tombstones.js';+import {+ DAILY_LOG_TOMBSTONES_KEY,+ dailyLogEventLiveStamp,+ queueDailyLogWrite,+} from './meatspaceDailyLog.js';import {PORTOS_SCHEMA_VERSIONS,RECORD_KIND_SCHEMA_CATEGORIES,@@ -112,7 +118,7 @@ const STORY_BUILDER_DIR = join(PATHS.data, 'story-builder');const STORY_BUILDER_EPOCH_KEY = '__storyBuilderEpoch';const MEATSPACE_FILES = {- 'daily-log.json': { arrayKey: 'entries', idField: 'date', mergeRecord: mergeMeatspaceDailyLogEntry },+ 'daily-log.json': { type: 'daily-log' }, // mergeDailyLogFile'blood-tests.json': { arrayKey: 'tests', idField: 'date' },'epigenetic-tests.json': { arrayKey: 'tests', idField: 'date' },'eyes.json': { arrayKey: 'exams', idField: 'date' },@@ -252,6 +258,95 @@ function mergeMeatspaceDailyLogEntry(local, remote) {return merged;}+const DAILY_LOG_EVENT_LISTS = [+ { category: 'alcohol', listKey: 'drinks', totalKey: 'standardDrinks', totalFor: standardDrinksFor },+ { category: 'nicotine', listKey: 'items', totalKey: 'totalMg', totalFor: nicotineMilligramsFor },+];++// Whole-log pass over identified alcohol/nicotine events (#8154), run after the+// per-date merge on entries already sorted by date:+// - A date move keeps the event's `id` and restamps it, so copies of one id on+// several dates collapse to the single copy `preferLogEventCopy` picks, on+// whichever date that copy lives. That order is total, so the result does not+// depend on which peer is local — no per-date tombstone is needed for a move.+// - A tombstoned id is dropped unless its live stamp (newer of createdAt /+// updatedAt) is strictly newer than the deletion, i.e. edited after it.+// Rows without an `id` are left alone: they have no identity to match.+// Returns the surviving tombstones (pruned of ones an edit superseded).+const reconcileDailyLogEvents = (entries, tombstones) => {+ const liveStamps = [];+ for (const { category, listKey, totalKey, totalFor } of DAILY_LOG_EVENT_LISTS) {+ const winners = new Map();+ for (const entry of entries) {+ for (const record of entry?.[category]?.[listKey] ?? []) {+ const id = logEventId(record);+ if (!id) continue;+ const current = winners.get(id);+ winners.set(id, current ? preferLogEventCopy(current, record) : record);+ }+ }+ for (const entry of entries) {+ const list = entry?.[category]?.[listKey];+ if (!Array.isArray(list)) continue;+ const kept = list.filter((record) => {+ const id = logEventId(record);+ if (!id) return true;+ if (winners.get(id) !== record) return false;+ return !isTombstoned(tombstones, id, dailyLogEventLiveStamp(record), 'id');+ });+ for (const record of kept) {+ const id = logEventId(record);+ if (id) liveStamps.push({ id, stamp: dailyLogEventLiveStamp(record) });+ }+ if (kept.length === list.length) continue;+ if (kept.length === 0) {+ delete entry[category];+ } else {+ entry[category] = {+ ...entry[category],+ [listKey]: kept,+ [totalKey]: roundToHundredth(kept.reduce((total, record) => total + totalFor(record), 0)),+ };+ }+ }+ }+ return pruneTombstones(tombstones, liveStamps, { keyField: 'id', timestampField: 'stamp' });+};++// Merge a peer's whole `daily-log.json` into the local one. Pure: returns the+// file to persist. Tombstones union in both directions (#8154) before the+// reconcile pass, so a deletion made on either side removes the event on both.+function mergeDailyLogFile(local, remote) {+ const localFile = isPlainObject(local) ? local : {};+ const remoteFile = isPlainObject(remote) ? remote : {};+ const { merged } = mergeArraysByKey(+ Array.isArray(localFile.entries) ? localFile.entries : [],+ Array.isArray(remoteFile.entries) ? remoteFile.entries : [],+ 'date',+ null,+ mergeMeatspaceDailyLogEntry,+ );+ // Shallow copies: the reconcile pass replaces or deletes a category on an+ // entry, and must not do that to the caller's local objects.+ const entries = merged.map((entry) => (isPlainObject(entry) ? { ...entry } : entry));+ entries.sort((a, b) => (a?.date || '').localeCompare(b?.date || ''));+ const { merged: unionTombstones } = mergeTombstones(+ localFile[DAILY_LOG_TOMBSTONES_KEY],+ remoteFile[DAILY_LOG_TOMBSTONES_KEY],+ { keyField: 'id' },+ );+ const tombstones = reconcileDailyLogEvents(entries, unionTombstones);+ const mergedFile = {+ ...remoteFile,+ ...localFile,+ entries,+ lastEntryDate: entries[entries.length - 1]?.date || null,+ };+ if (tombstones.length > 0) mergedFile[DAILY_LOG_TOMBSTONES_KEY] = tombstones;+ else delete mergedFile[DAILY_LOG_TOMBSTONES_KEY];+ return mergedFile;+}+/*** Merge two arrays of records by a key field. LWW by timestampField when both* sides have the same record. Records unique to either side are kept (union).@@ -445,6 +540,22 @@ async function applyMeatspaceRemote(remoteData) {if (!remoteFile) continue;const filePath = join(MEATSPACE_DIR, filename);++ if (config.type === 'daily-log') {+ // Through the same write queue as the local drink/nicotine/body writers,+ // so a sync cannot overwrite a delete (and its tombstone) made between+ // this read and write.+ const written = await queueDailyLogWrite(async () => {+ const local = await readJSONFile(filePath, null, { strict: true });+ const merged = mergeDailyLogFile(local, remoteFile);+ if (canonicalStringify(merged) === canonicalStringify(local)) return false;+ await atomicWrite(filePath, merged);+ return true;+ });+ if (written) totalApplied++;+ continue;+ }+const local = await readJSONFile(filePath, null, { strict: true });if (config.type === 'object-lww') {@@ -457,21 +568,12 @@ async function applyMeatspaceRemote(remoteData) {// Array mergeconst localArr = local?.[config.arrayKey] || [];const remoteArr = remoteFile[config.arrayKey] || [];- const { merged, changed } = mergeArraysByKey(- localArr,- remoteArr,- config.idField,- null,- config.mergeRecord,- );+ const { merged, changed } = mergeArraysByKey(localArr, remoteArr, config.idField);if (changed) {// Sort by idField (usually date)merged.sort((a, b) => (a[config.idField] || '').localeCompare(b[config.idField] || ''));const mergedFile = { ...(remoteFile || {}), ...(local || {}), [config.arrayKey]: merged };- if (filename === 'daily-log.json') {- mergedFile.lastEntryDate = merged[merged.length - 1]?.[config.idField] || null;- }await atomicWrite(filePath, mergedFile);totalApplied++;}diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.jsindex badd7fd0ee..2b36060099 100644--- a/server/services/meatspaceAlcohol.js+++ b/server/services/meatspaceAlcohol.js@@ -12,7 +12,8 @@ import {loadMeatspaceDailyLog,mutateDailyLog,newDailyLogEvent,- stampDailyLogEventEdit+ stampDailyLogEventEdit,+ tombstoneDailyLogEvent} from './meatspaceDailyLog.js';import {isMortalLoomEnabled,@@ -324,6 +325,7 @@ export async function removeDrink(date, index) {if (!entry?.alcohol?.drinks?.[index]) return null;const removed = entry.alcohol.drinks.splice(index, 1)[0];+ tombstoneDailyLogEvent(log, removed);if (entry.alcohol.drinks.length === 0) delete entry.alcohol;else recalcAlcoholTotal(entry);return removed;diff --git a/server/services/meatspaceDailyLog.js b/server/services/meatspaceDailyLog.jsindex ecd7887c4c..84ec834b67 100644--- a/server/services/meatspaceDailyLog.js+++ b/server/services/meatspaceDailyLog.js@@ -28,6 +28,8 @@ import { join } from 'path';import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../lib/fileUtils.js';import { readDailyLogIfEnabled } from './mortalLoomStore.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { parseTsMs, compareNewerWins } from '../lib/lwwTimestamp.js';+import { recordTombstone, supersedingTimestamp } from '../lib/tombstones.js';export const DAILY_LOG_FILE = join(PATHS.meatspace, 'daily-log.json');@@ -130,6 +132,34 @@ export function stampDailyLogEventEdit(event, now = new Date().toISOString()) {event.replaces = { ...event };event.id = randomUUID();}- event.updatedAt = now;+ // Step past the copy being edited even if a peer that last touched it ran a+ // clock ahead of ours; otherwise that stale copy would win the id merge.+ event.updatedAt = supersedingTimestamp(dailyLogEventLiveStamp(event), now);return event;}++/**+ * The newer of an event's `createdAt` and `updatedAt` — the instant a deletion+ * has to beat. Null for a legacy row with neither stamp.+ */+export function dailyLogEventLiveStamp(event) {+ const { createdAt, updatedAt } = event || {};+ if (compareNewerWins(createdAt, updatedAt)) return createdAt;+ return parseTsMs(updatedAt) === null ? null : updatedAt;+}++/** Top-level `daily-log.json` field holding `{ id, deletedAt }` event tombstones (#8154). */+export const DAILY_LOG_TOMBSTONES_KEY = 'eventTombstones';++/**+ * Record that a logged drink/nicotine event was deleted, so peers that still+ * hold it drop it on their next sync instead of sending it back (#8154). The+ * stamp is kept past the event's own live stamp so the deletion wins over the+ * copy the user was looking at even under clock skew. A legacy row without an+ * `id` has no identity a peer could match on, so its delete stays local.+ */+export function tombstoneDailyLogEvent(log, event, now = new Date().toISOString()) {+ if (typeof event?.id !== 'string' || !event.id) return;+ const deletedAt = supersedingTimestamp(dailyLogEventLiveStamp(event), now);+ log[DAILY_LOG_TOMBSTONES_KEY] = recordTombstone(log[DAILY_LOG_TOMBSTONES_KEY], event.id, { keyField: 'id', deletedAt });+}diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.jsindex acb5ae68b0..49b6cd4df9 100644--- a/server/services/meatspaceNicotine.js+++ b/server/services/meatspaceNicotine.js@@ -11,7 +11,8 @@ import {loadMeatspaceDailyLog,mutateDailyLog,newDailyLogEvent,- stampDailyLogEventEdit+ stampDailyLogEventEdit,+ tombstoneDailyLogEvent} from './meatspaceDailyLog.js';import {isMortalLoomEnabled,@@ -269,6 +270,7 @@ export async function removeNicotine(date, index) {if (!entry?.nicotine?.items?.[index]) return null;const removed = entry.nicotine.items.splice(index, 1)[0];+ tombstoneDailyLogEvent(log, removed);if (entry.nicotine.items.length === 0) delete entry.nicotine;else recalcDayTotal(entry);return removed;diff --git a/server/services/sharingDurability.test.js b/server/services/sharingDurability.test.jsindex bcf0ad69a9..5479187bdb 100644--- a/server/services/sharingDurability.test.js+++ b/server/services/sharingDurability.test.js@@ -268,6 +268,107 @@ describe('daily-log event identity (#8143)', () => {});});+// Deletes and date moves of identified events converge across peers (#8154).+// Peer A acts through the real services on a log both peers share; peer B+// still holds the original rows, as an offline (or pre-#8154) peer would.+describe('daily-log deletes and date moves (#8154)', () => {+ const date = '2026-01-03';+ const nextDate = '2026-01-04';+ const stamp = '2026-01-03T20:00:00.000Z';+ const path = () => join(PATHS.meatspace, 'daily-log.json');+ const lager = (id, extra = {}) => ({ id, name: 'Example Lager', oz: 12, abv: 5, count: 1, createdAt: stamp, updatedAt: stamp, ...extra });+ const pouch = { id: 'pouch-1', product: 'Example Pouch', mgPerUnit: 3, count: 1, createdAt: stamp, updatedAt: stamp };+ const shared = () => ({+ entries: [{+ date,+ alcohol: { drinks: [lager('drink-1'), lager('drink-2', { oz: 24 })], standardDrinks: 3 },+ nicotine: { items: [{ ...pouch }], totalMg: 3 },+ }],+ });+ const read = async () => JSON.parse(await readFile(path(), 'utf8'));+ const drinkIdsByDate = (log) => Object.fromEntries(+ log.entries.filter((e) => e.alcohol).map((e) => [e.date, e.alcohol.drinks.map((d) => d.id)]),+ );+ afterEach(() => vi.useRealTimers());++ const actOnPeerA = async (action, at = '2026-01-05T09:00:00.000Z') => {+ await seed(path(), shared());+ vi.useFakeTimers({ toFake: ['Date'], now: new Date(at) });+ await action();+ vi.useRealTimers();+ return read();+ };++ // Row order within a day follows whichever side is local; identity does not.+ const byId = (a, b) => (a.id < b.id ? -1 : 1);+ const unordered = (log) => log.entries.map((e) => ({+ ...e,+ ...(e.alcohol && { alcohol: { ...e.alcohol, drinks: [...e.alcohol.drinks].sort(byId) } }),+ ...(e.nicotine && { nicotine: { ...e.nicotine, items: [...e.nicotine.items].sort(byId) } }),+ }));++ // Merge in both directions; each side must reach the same log, and a replay+ // of the same snapshot must be a no-op.+ const syncBothWays = async (peerA, peerB) => {+ const results = [];+ for (const [local, remote] of [[peerA, peerB], [peerB, peerA]]) {+ await seed(path(), local);+ await dataSync.applyRemote('meatspace', { 'daily-log.json': remote });+ const merged = await read();+ expect(await dataSync.applyRemote('meatspace', { 'daily-log.json': remote })).toEqual({ applied: false, count: 0 });+ results.push(merged);+ }+ expect(unordered(results[1])).toEqual(unordered(results[0]));+ expect(results[1].eventTombstones).toEqual(results[0].eventTombstones);+ return results[0];+ };++ it('keeps a deleted drink and nicotine item deleted on both peers', async () => {+ const peerA = await actOnPeerA(async () => {+ await alcohol.removeDrink(date, 0);+ await nicotine.removeNicotine(date, 0);+ });+ const merged = await syncBothWays(peerA, shared());+ const day = merged.entries.find((e) => e.date === date);+ expect(day.alcohol.drinks.map((d) => d.id)).toEqual(['drink-2']);+ expect(day.alcohol.standardDrinks).toBe(2);+ expect(day.nicotine).toBeUndefined();+ // The receiving peer keeps the tombstones so it can pass the delete on.+ expect(merged.eventTombstones.map((t) => t.id).sort()).toEqual(['drink-1', 'pouch-1']);+ });++ it('leaves exactly one copy of a moved drink, on the new date', async () => {+ const peerA = await actOnPeerA(() => alcohol.updateDrink(date, 0, { date: nextDate }));+ const merged = await syncBothWays(peerA, shared());+ expect(drinkIdsByDate(merged)).toEqual({ [date]: ['drink-2'], [nextDate]: ['drink-1'] });+ expect(merged.entries.find((e) => e.date === date).alcohol.standardDrinks).toBe(2);+ expect(merged.entries.find((e) => e.date === nextDate).alcohol.standardDrinks).toBe(1);+ });++ it('does not suppress an identical drink logged again after the delete', async () => {+ const peerA = await actOnPeerA(async () => {+ await alcohol.removeDrink(date, 0);+ await alcohol.logDrink({ name: 'Example Lager', oz: 12, abv: 5, count: 1, date });+ });+ const merged = await syncBothWays(peerA, shared());+ const drinks = merged.entries.find((e) => e.date === date).alcohol.drinks;+ expect(drinks.map((d) => d.id)).not.toContain('drink-1');+ expect(drinks).toHaveLength(2);+ expect(merged.entries.find((e) => e.date === date).alcohol.standardDrinks).toBe(3);+ });++ it('keeps a drink a peer edited after the delete, and retires the tombstone', async () => {+ const peerA = await actOnPeerA(() => alcohol.removeDrink(date, 0));+ const peerB = shared();+ peerB.entries[0].alcohol.drinks[0].count = 2;+ peerB.entries[0].alcohol.drinks[0].updatedAt = '2026-01-06T09:00:00.000Z';+ const merged = await syncBothWays(peerA, peerB);+ const drinks = merged.entries.find((e) => e.date === date).alcohol.drinks;+ expect(drinks.find((d) => d.id === 'drink-1').count).toBe(2);+ expect(merged.eventTombstones).toBeUndefined();+ });+});+// An unreadable shared identity must not leave a new local registry entry.it('does not register a bucket whose existing identity cannot be read', async () => {const other = join(tempRoot, 'other');