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: keep identical drinks and nicotine logged on two machines as separate events (#8143)

[._.]/ Adam Eivy2f42b4419932
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 38b40a1e5c..522792b229 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -744,6 +744,25 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// a wrapper it cannot fully read) is worse, and a retraction that reaches
// nobody is still better than one that corrupts.
eidoverseFoundations: 3,
+ // v1 = identified daily-log events (#8143). The meatspace snapshot's
+ // `daily-log.json` alcohol drinks and nicotine items now carry `id` +
+ // `createdAt`/`updatedAt`; a v1 receiver merges them by id (newest copy wins)
+ // so identical independently-logged events stay distinct and a replay stays
+ // idempotent. NOT a record kind — it gates the 60s meatspace snapshot in
+ // dataSync `applyRemote` (SNAPSHOT_CATEGORY_SCHEMA_KEYS), so it rides
+ // NON_RECORD_SCHEMA_CATEGORIES below.
+ //
+ // Mixed versions are deliberately NOT blocked, because neither direction can
+ // corrupt the other and pausing would strand drinks logged meanwhile:
+ // - v0 → v1: a v0 payload is `behind` (never gated). Its rows without an `id`
+ // keep the old content-keyed dedupe; copies of an id'd row that the v0 peer
+ // bumped in place (it folds a same-product log into the existing row without
+ // restamping) resolve to the larger `count` on equal stamps.
+ // - v1 → v0: a v0 receiver scopes meatspace to no schema keys, so it cannot
+ // gate; it unions the id'd rows by content and keeps them verbatim.
+ // The key exists so the NEXT incompatible daily-log change can bump to 2 and
+ // have v1 receivers reject it.
+ meatspace: 1,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
@@ -831,11 +850,15 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({
* The repository file format is versioned separately (`appQualitySnapshotFormat.js`)
* and a file-schema change must not bump this wire version.
*
+ * `meatspace` (#8143): the daily-log snapshot category, gated by dataSync
+ * `applyRemote` through SNAPSHOT_CATEGORY_SCHEMA_KEYS; meatspace is never a
+ * per-record push.
+ *
* Do NOT add a real record-push category here to silence the guard — that would
* leave its push transfers ungated (silent cross-install corruption). Only
* genuinely non-push categories belong.
*/
-export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary', 'cosHistory', 'cosTasks', 'appQuality', 'eidoverseFoundations']));
+export const NON_RECORD_SCHEMA_CATEGORIES = Object.freeze(new Set(['mediaLibrary', 'cosHistory', 'cosTasks', 'appQuality', 'eidoverseFoundations', 'meatspace']));
/**
* Lazy-read the current PortOS version from the ROOT package.json so a
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index dfacac14d3..7e59938bc2 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -11,6 +11,7 @@ import { join } from 'path';
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 {
PORTOS_SCHEMA_VERSIONS,
RECORD_KIND_SCHEMA_CATEGORIES,
@@ -141,13 +142,49 @@ const mergeNonEmptyObject = (local, remote) => {
return merged;
};
-const mergeUniqueRecords = (local, remote) => {
+const logEventId = (record) => (
+ isPlainObject(record) && typeof record.id === 'string' && record.id ? record.id : null
+);
+
+const logEventStampMs = (record) => parseTsMs(record.updatedAt) ?? parseTsMs(record.createdAt) ?? -Infinity;
+
+// Pick one of two copies of the same logged event. The order is total, so the
+// winner is the same whichever copy is local and whichever peer syncs first.
+// Newer `updatedAt` wins. On equal stamps the larger `count` wins: a peer from
+// before #8143 adds a same-product log to an existing row in place without
+// restamping it, and that increment is a real drink/item. Then canonical text.
+const preferLogEventCopy = (a, b) => {
+ const stampDiff = logEventStampMs(a) - logEventStampMs(b);
+ if (stampDiff !== 0 && !Number.isNaN(stampDiff)) return stampDiff > 0 ? a : b;
+ const countDiff = (Number(a.count) || 1) - (Number(b.count) || 1);
+ if (countDiff !== 0) return countDiff > 0 ? a : b;
+ return canonicalStringify(a) >= canonicalStringify(b) ? a : b;
+};
+
+// Merge one day's alcohol drinks or nicotine items (#8143). A row with an `id` is
+// one logged event: copies of it collapse to the preferred copy, and two
+// identical rows with different ids stay two events. A row without an `id` was
+// logged before events had identity, so it keeps the old content-keyed dedupe —
+// its identical twin on a peer is the same row synced earlier, not a new event.
+const mergeDailyLogEvents = (local, remote) => {
const merged = [];
- const seen = new Set();
+ const indexById = new Map();
+ const seenLegacy = new Set();
for (const record of [...(Array.isArray(local) ? local : []), ...(Array.isArray(remote) ? remote : [])]) {
+ const id = logEventId(record);
+ if (id) {
+ const index = indexById.get(id);
+ if (index === undefined) {
+ indexById.set(id, merged.length);
+ merged.push(record);
+ } else {
+ merged[index] = preferLogEventCopy(merged[index], record);
+ }
+ continue;
+ }
const key = canonicalStringify(record);
- if (seen.has(key)) continue;
- seen.add(key);
+ if (seenLegacy.has(key)) continue;
+ seenLegacy.add(key);
merged.push(record);
}
return merged;
@@ -160,7 +197,7 @@ const mergeDailyLogCategory = (local, remote, listKey, totalKey, totalForItem) =
const hasList = Array.isArray(localCategory[listKey]) || Array.isArray(remoteCategory[listKey]);
if (!hasList) return merged;
- const records = mergeUniqueRecords(localCategory[listKey], remoteCategory[listKey]);
+ const records = mergeDailyLogEvents(localCategory[listKey], remoteCategory[listKey]);
merged[listKey] = records;
if (records.length > 0) {
merged[totalKey] = roundToHundredth(records.reduce((total, record) => total + totalForItem(record), 0));
@@ -906,7 +943,7 @@ const SNAPSHOT_CATEGORY_SCHEMA_KEYS = {
goals: [],
character: [],
digitalTwin: [],
- meatspace: [],
+ meatspace: ['meatspace'],
videoHistory: [],
storyBuilder: RECORD_KIND_SCHEMA_CATEGORIES.storyBuilder,
// Per-instance digests replaced whole under an LWW stamp, with every field
diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.js
index 99d20d0d2f..d528dc5d57 100644
--- a/server/services/meatspaceAlcohol.js
+++ b/server/services/meatspaceAlcohol.js
@@ -8,7 +8,12 @@
import { readFile } from 'fs/promises';
import { join } from 'path';
import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
-import { loadMeatspaceDailyLog, mutateDailyLog } from './meatspaceDailyLog.js';
+import {
+ loadMeatspaceDailyLog,
+ mutateDailyLog,
+ newDailyLogEvent,
+ stampDailyLogEventEdit
+} from './meatspaceDailyLog.js';
import {
isMortalLoomEnabled,
mlPush,
@@ -210,12 +215,14 @@ export async function logDrink({ name, oz, abv, count = 1, date }) {
if (!entry) { entry = { date: targetDate }; log.entries.push(entry); }
if (!entry.alcohol) entry.alcohol = { drinks: [], standardDrinks: 0 };
- const existing = entry.alcohol.drinks.find(d => d.name === drink.name && d.oz === drink.oz && d.abv === drink.abv);
- if (existing) existing.count = (existing.count || 1) + count;
- else entry.alcohol.drinks.push(drink);
+ // Every log is its own event — never fold it into a same-product row. Bumping
+ // an existing row's count in place loses one of two concurrent increments when
+ // peers merge that row by id (#8143).
+ const event = newDailyLogEvent(drink);
+ entry.alcohol.drinks.push(event);
recalcAlcoholTotal(entry);
- return { drink, standardDrinks, date: targetDate, dayTotal: entry.alcohol.standardDrinks };
+ return { drink: event, standardDrinks, date: targetDate, dayTotal: entry.alcohol.standardDrinks };
}, { label: 'Alcohol' });
averageCache = null;
@@ -258,6 +265,7 @@ export async function updateDrink(date, index, updates) {
if (updates.oz !== undefined) drink.oz = updates.oz;
if (updates.abv !== undefined) drink.abv = updates.abv;
if (updates.count !== undefined) drink.count = updates.count;
+ stampDailyLogEventEdit(drink);
// Move to different date if requested
const newDate = updates.date;
diff --git a/server/services/meatspaceDailyLog.js b/server/services/meatspaceDailyLog.js
index ace1010d16..1b613d02fb 100644
--- a/server/services/meatspaceDailyLog.js
+++ b/server/services/meatspaceDailyLog.js
@@ -23,6 +23,7 @@
* caller that COUNTS these entries can't report a fake 0 (#2726).
*/
+import { randomUUID } from 'crypto';
import { join } from 'path';
import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../lib/fileUtils.js';
import { readDailyLogIfEnabled } from './mortalLoomStore.js';
@@ -105,3 +106,25 @@ export async function mutateDailyLog(mutatorFn, { label = 'MeatSpace' } = {}) {
return result !== undefined ? result : log;
});
}
+
+/**
+ * Mint a logged alcohol drink or nicotine item as its own event (#8143).
+ *
+ * Peers merge these rows by `id`, so two machines that each log the same drink on
+ * the same day keep two events instead of collapsing byte-identical rows into one.
+ * `updatedAt` is the last-writer-wins stamp for edits. Rows logged before this
+ * existed carry no `id` and keep merging by their full content.
+ */
+export function newDailyLogEvent(fields, now = new Date().toISOString()) {
+ return { id: randomUUID(), ...fields, createdAt: now, updatedAt: now };
+}
+
+/**
+ * Restamp an edited event so the edit wins over a peer's older copy. A legacy row
+ * (no `id`) gets one here, so later edits to it merge by identity too.
+ */
+export function stampDailyLogEventEdit(event, now = new Date().toISOString()) {
+ if (typeof event.id !== 'string' || !event.id) event.id = randomUUID();
+ event.updatedAt = now;
+ return event;
+}
diff --git a/server/services/meatspaceDailyLog.test.js b/server/services/meatspaceDailyLog.test.js
index 79beeda799..a359e06f92 100644
--- a/server/services/meatspaceDailyLog.test.js
+++ b/server/services/meatspaceDailyLog.test.js
@@ -34,7 +34,7 @@ vi.mock('./mortalLoomStore.js', () => ({
import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';
import { readDailyLogIfEnabled } from './mortalLoomStore.js';
import { DAILY_LOG_FILE, readLocalDailyLog, loadMeatspaceDailyLog } from './meatspaceDailyLog.js';
-import { getAlcoholSummary, getDailyAlcohol, logDrink, updateDrink } from './meatspaceAlcohol.js';
+import { getAlcoholSummary, getDailyAlcohol, logDrink, removeDrink, updateDrink } from './meatspaceAlcohol.js';
import { getDailyNicotine, getNicotineSummary, logNicotine } from './meatspaceNicotine.js';
import { addBodyEntry, getBodyHistory } from './meatspaceHealth.js';
@@ -291,6 +291,46 @@ describe('serialized daily-log writes (#8032)', () => {
expect(current().entries.find((entry) => entry.date === '2024-06-01').alcohol.drinks).toHaveLength(2);
});
+ // Peers merge rows by id, so each log must be its own event (#8143).
+ it('logs a repeated drink as a separate event and edits/removes the one targeted', async () => {
+ const current = useLogStore({
+ entries: [{
+ date: '2024-06-01',
+ alcohol: { drinks: [{ name: 'Example Lager', oz: 12, abv: 5, count: 1 }], standardDrinks: 1 }
+ }],
+ lastEntryDate: '2024-06-01'
+ });
+ const first = await logDrink({ name: 'Example Lager', oz: 12, abv: 5, count: 1, date: '2024-06-01' });
+ const second = await logDrink({ name: 'Example Lager', oz: 12, abv: 5, count: 1, date: '2024-06-01' });
+ const drinks = () => current().entries[0].alcohol.drinks;
+
+ expect(first.drink.id).toEqual(expect.any(String));
+ expect(second.drink.id).not.toBe(first.drink.id);
+ expect(drinks().map((d) => d.count)).toEqual([1, 1, 1]);
+ expect(second.dayTotal).toBe(3);
+
+ await updateDrink('2024-06-01', 2, { count: 2 });
+ expect(drinks()[2]).toMatchObject({ id: second.drink.id, count: 2 });
+ expect(drinks()[1]).toEqual(first.drink);
+
+ // Editing a legacy row gives it an identity so later edits merge by id.
+ await updateDrink('2024-06-01', 0, { abv: 6 });
+ expect(drinks()[0]).toMatchObject({ id: expect.any(String), abv: 6, updatedAt: expect.any(String) });
+
+ await removeDrink('2024-06-01', 1);
+ expect(drinks().map((d) => d.id)).not.toContain(first.drink.id);
+ expect(current().entries[0].alcohol.standardDrinks).toBe(3.2);
+ });
+
+ it('logs a repeated nicotine product as a separate event and counts units for today', async () => {
+ const current = useLogStore({ entries: [], lastEntryDate: null });
+ await logNicotine({ product: 'Example Pouch', mgPerUnit: 3, count: 2, date: '2024-06-01' });
+ await logNicotine({ product: 'Example Pouch', mgPerUnit: 3, count: 1, date: '2024-06-01' });
+ const items = current().entries[0].nicotine.items;
+ expect(new Set(items.map((i) => i.id)).size).toBe(2);
+ expect(await getNicotineSummary()).toMatchObject({ today: 9, todayCount: 3 });
+ });
+
it('drops the nicotine summary cache after a local write', async () => {
useLogStore({ entries: [], lastEntryDate: null });
await logNicotine({ product: 'Example Pouch', mgPerUnit: 3, count: 1, date: '2024-06-01' });
diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.js
index 45e3624466..8e66e6e96d 100644
--- a/server/services/meatspaceNicotine.js
+++ b/server/services/meatspaceNicotine.js
@@ -7,7 +7,12 @@
import { join } from 'path';
import { atomicWrite, PATHS, ensureDir, readJSONFile, getDateString } from '../lib/fileUtils.js';
-import { loadMeatspaceDailyLog, mutateDailyLog } from './meatspaceDailyLog.js';
+import {
+ loadMeatspaceDailyLog,
+ mutateDailyLog,
+ newDailyLogEvent,
+ stampDailyLogEventEdit
+} from './meatspaceDailyLog.js';
import {
isMortalLoomEnabled,
mlPush,
@@ -42,7 +47,8 @@ export function computeRollingAverages(entries) {
// Today's total
const todayEntry = allEntries.find(e => e.date === today);
const todayMg = todayEntry?.nicotine?.totalMg ?? 0;
- const todayCount = todayEntry?.nicotine?.items?.length ?? 0;
+ // Units consumed, not rows: each log is a separate event row (#8143).
+ const todayCount = (todayEntry?.nicotine?.items ?? []).reduce((sum, i) => sum + (i?.count ?? 1), 0);
// Helper: average over last N days
const rollingAverage = (days) => {
@@ -164,12 +170,12 @@ export async function logNicotine({ product, mgPerUnit, count = 1, date }) {
if (!entry) { entry = { date: targetDate }; log.entries.push(entry); }
if (!entry.nicotine) entry.nicotine = { items: [], totalMg: 0 };
- const existing = entry.nicotine.items.find(i => i.product === item.product && i.mgPerUnit === item.mgPerUnit);
- if (existing) existing.count = (existing.count || 1) + count;
- else entry.nicotine.items.push(item);
+ // Every log is its own event (see logDrink, #8143).
+ const event = newDailyLogEvent(item);
+ entry.nicotine.items.push(event);
recalcDayTotal(entry);
- return { item, totalMg, date: targetDate, dayTotal: entry.nicotine.totalMg };
+ return { item: event, totalMg, date: targetDate, dayTotal: entry.nicotine.totalMg };
}, { label: 'Nicotine' });
averageCache = null;
@@ -204,6 +210,7 @@ export async function updateNicotine(date, index, updates) {
if (updates.product !== undefined) item.product = updates.product;
if (updates.mgPerUnit !== undefined) item.mgPerUnit = updates.mgPerUnit;
if (updates.count !== undefined) item.count = updates.count;
+ stampDailyLogEventEdit(item);
// Move to different date if requested
const newDate = updates.date;
diff --git a/server/services/sharingDurability.test.js b/server/services/sharingDurability.test.js
index 3497ae0424..e99189383e 100644
--- a/server/services/sharingDurability.test.js
+++ b/server/services/sharingDurability.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import { mkdir, readFile, writeFile, rm } from 'fs/promises';
import { dirname, join } from 'path';
import { mockPathsDataRoot, mockNoPeers, mockNoPeerSync, mockTestIdentity } from '../lib/mockPathsDataRoot.js';
@@ -41,6 +41,8 @@ const subscriptions = await import('./sharing/subscriptions.js');
const manifests = await import('./sharing/manifest.js');
const importer = await import('./sharing/importer.js');
const annotations = await import('./sharing/annotationsSync.js');
+const alcohol = await import('./meatspaceAlcohol.js');
+const nicotine = await import('./meatspaceNicotine.js');
const { PATHS } = await import('../lib/fileUtils.js');
const bucketPath = join(tempRoot, 'bucket');
let bucket;
@@ -173,6 +175,82 @@ it('merges same-date daily-log tenants without duplicating them on replay', asyn
expect(replayed.entries[0]).toEqual(entry);
});
+// Identified alcohol/nicotine events (#8143): identical rows logged on two peers
+// are two events, a replay adds nothing, and legacy/v0 payloads stay safe.
+describe('daily-log event identity (#8143)', () => {
+ const date = '2026-01-03';
+ const path = () => join(PATHS.meatspace, 'daily-log.json');
+ const stamp = '2026-01-03T20:00:00.000Z';
+ const lager = (id, extra = {}) => ({ id, name: 'Example Lager', oz: 12, abv: 5, count: 1, createdAt: stamp, updatedAt: stamp, ...extra });
+ const day = (drinks) => ({ date, alcohol: { drinks, standardDrinks: 0 } });
+ const snapshot = (...entries) => ({ 'daily-log.json': { entries } });
+ afterEach(() => vi.useRealTimers());
+ const savedDay = async () => JSON.parse(await readFile(path(), 'utf8')).entries.find((e) => e.date === date);
+
+ // Each "peer" logs through the real services onto an empty log at the same
+ // instant, so the rows are identical apart from their event identity.
+ const logOnFreshPeer = async () => {
+ await rm(path(), { force: true });
+ vi.useFakeTimers({ toFake: ['Date'], now: new Date(stamp) });
+ await alcohol.logDrink({ name: 'Example Lager', oz: 12, abv: 5, count: 1, date });
+ await nicotine.logNicotine({ product: 'Example Pouch', mgPerUnit: 3, count: 1, date });
+ return JSON.parse(await readFile(path(), 'utf8'));
+ };
+
+ it('keeps identical independent events from both peers in either sync order', async () => {
+ const peers = [await logOnFreshPeer(), await logOnFreshPeer()];
+ vi.useRealTimers();
+ for (const [local, remote] of [peers, [...peers].reverse()]) {
+ await seed(path(), local);
+ const peer = { 'daily-log.json': remote };
+ expect(await dataSync.applyRemote('meatspace', peer)).toEqual({ applied: true, count: 1 });
+ const merged = await savedDay();
+ expect(merged.alcohol.drinks).toHaveLength(2);
+ expect(merged.alcohol.standardDrinks).toBe(2);
+ expect(merged.nicotine.items).toHaveLength(2);
+ expect(merged.nicotine.totalMg).toBe(6);
+
+ expect(await dataSync.applyRemote('meatspace', peer)).toEqual({ applied: false, count: 0 });
+ expect(await savedDay()).toEqual(merged);
+ }
+ });
+
+ it('resolves copies of one event the same way whichever side holds which', async () => {
+ const legacy = { name: 'Example Stout', oz: 12, abv: 5, count: 1 };
+ const newerEdit = lager('drink-x', { count: 1, abv: 10, updatedAt: '2026-01-04T08:00:00.000Z' });
+ // A pre-#8143 peer folds a second log into the row in place, without restamping.
+ const bumpedInPlace = lager('drink-x', { count: 2 });
+ const cases = [
+ // Equal stamps: the in-place increment is a real drink, so the larger count wins.
+ [[lager('drink-x'), legacy], [legacy, lager('drink-x'), bumpedInPlace], 2, 3],
+ [[bumpedInPlace, legacy], [legacy, lager('drink-x')], 2, 3],
+ // A restamped edit wins over a stale copy regardless of its count.
+ [[bumpedInPlace, legacy], [newerEdit, legacy], 1, 3],
+ [[newerEdit, legacy], [bumpedInPlace, legacy], 1, 3],
+ ];
+ for (const [localDrinks, remoteDrinks, count, total] of cases) {
+ await seed(path(), { entries: [day(localDrinks)] });
+ await dataSync.applyRemote('meatspace', snapshot(day(remoteDrinks)));
+ const merged = await savedDay();
+ // The legacy row keeps content dedupe; the identified event is one row.
+ expect(merged.alcohol.drinks).toHaveLength(2);
+ expect(merged.alcohol.drinks.find((d) => d.id === 'drink-x').count).toBe(count);
+ expect(merged.alcohol.standardDrinks).toBe(total);
+ }
+ });
+
+ it('refuses a daily log from a peer on a newer meatspace schema', async () => {
+ await seed(path(), { entries: [day([lager('drink-a')])] });
+ const before = await readFile(path(), 'utf8');
+ const result = await dataSync.applyRemote('meatspace', snapshot(day([lager('drink-b')])), {
+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { meatspace: 2 } },
+ });
+ expect(result.applied).toBe(false);
+ expect(result.blockedBySchema.ahead).toEqual([{ category: 'meatspace', senderV: 2, receiverV: 1 }]);
+ expect(await readFile(path(), 'utf8')).toBe(before);
+ });
+});
+
// 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');