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: preserve independent XP grants when merging Character histories (#9819)

[._.]/ Adam Eivy17049f9ee159
diff --git a/server/services/character.js b/server/services/character.js
index 3a5d073676..2ab256da64 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -141,6 +141,50 @@ function legacyLevelFromXp(xp) {
return 1;
}
+// --- Cumulative XP accounting across federated histories (#9819) ---
+//
+// `xp` is a cumulative scalar that every grant writer (addXP/addEvent/syncJiraXP/syncTaskXP)
+// bumps alongside an identified event carrying the same amount. Two machines that each take
+// a grant while disconnected therefore hold counters that BOTH include the shared history but
+// each only one side's new grant — so the merge can neither take `Math.max` (drops the lesser
+// grant) nor sum the counters (double-counts the shared history). It reconciles from the
+// event ledger instead, and keeps whatever XP the ledger does not explain (a pre-event legacy
+// baseline, a hand-edited total) exactly once.
+
+// A usable XP quantity: a finite, non-negative number — anything else (NaN, a numeric string,
+// null, a negative) is an invalid historical value and counts as 0, never NaN.
+function normalizeXp(value) {
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
+}
+
+// XP represented by the IDENTIFIED events in `events`, each ID counted once (an event without
+// an id is not a ledger entry — its XP, if any, stays in the record's unrepresented residual).
+function eventXpTotal(events) {
+ if (!Array.isArray(events)) return 0;
+ const byId = new Map();
+ for (const event of events) {
+ if (typeof event?.id === 'string' && event.id !== '') byId.set(event.id, normalizeXp(event.xp));
+ }
+ let total = 0;
+ for (const xp of byId.values()) total += xp;
+ return total;
+}
+
+// Pure: the cumulative XP of a merge. `inputs` are the pre-merge `{ xp, events }` records
+// (local and remote); `mergedEvents` is their event union after the existing per-ID LWW.
+// merged xp = max over inputs of each input's UNREPRESENTED residual (xp − its own ledger,
+// floored at 0) + the ledger total of the merged events.
+// The residual is taken as a max, not a sum, because each input's baseline is the same
+// shared pre-ledger history, not an independent grant. Idempotent under redelivery — a
+// snapshot already folded in has residual 0 — and symmetric, so both peers converge.
+export function reconcileXp(inputs, mergedEvents) {
+ let baseline = 0;
+ for (const input of inputs) {
+ baseline = Math.max(baseline, normalizeXp(input?.xp) - eventXpTotal(input?.events));
+ }
+ return baseline + eventXpTotal(mergedEvents);
+}
+
function createEvent(type, description, overrides = {}) {
return {
id: crypto.randomUUID(),
diff --git a/server/services/dataSync.characterXp.test.js b/server/services/dataSync.characterXp.test.js
new file mode 100644
index 0000000000..085ae0e063
--- /dev/null
+++ b/server/services/dataSync.characterXp.test.js
@@ -0,0 +1,200 @@
+/**
+ * Character federation — cumulative XP accounting across independent histories (#9819).
+ *
+ * `xp` is a cumulative scalar that each grant bumps alongside an identified event. The merge
+ * used `Math.max` on the counters while UNIONING the events, so two machines that each took a
+ * different grant while disconnected kept both events but only the larger counter — the lesser
+ * grant vanished from `xp` for good, with no local write race involved (the sequence is
+ * strictly serial, so a write queue would not help).
+ *
+ * These tests drive the real federation boundary: a peer's record is written to
+ * `character.json`, its wire snapshot is read through `getSnapshot('character')`, and a
+ * snapshot is delivered with `applyRemote('character')`, so the wire projection, the merge,
+ * and the persisted record are all the production code.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { readFile, writeFile, mkdir, rm } from 'fs/promises';
+import { join } from 'path';
+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+
+const { makeProxy, cleanup, tempRoot } = mockPathsDataRoot({ prefix: 'portos-datasync-character-xp-' });
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makeProxy(actual);
+});
+
+const dataSync = await import('./dataSync.js');
+
+const CHARACTER_FILE = join(tempRoot, 'character.json');
+
+afterAll(cleanup);
+
+beforeEach(async () => {
+ await mkdir(tempRoot, { recursive: true });
+});
+
+let tick = 0;
+const nextTimestamp = () => new Date(Date.UTC(2026, 0, 1, 0, 0, tick++)).toISOString();
+
+// A grant exactly as the writers (addXP/addEvent/…) record it: counter bumped AND an
+// identified event carrying the same amount.
+const grant = (record, id, amount, extra = {}) => ({
+ ...record,
+ xp: record.xp + amount,
+ events: [...record.events, { id, type: 'xp', description: `grant ${id}`, xp: amount, timestamp: nextTimestamp(), ...extra }],
+ updatedAt: nextTimestamp(),
+});
+
+const baseRecord = (overrides = {}) => ({
+ name: 'Example', class: '', xp: 0, hp: 15, maxHp: 15,
+ events: [], syncedJiraTickets: [], syncedTaskIds: [],
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
+ ...overrides,
+});
+
+const persist = (record) => writeFile(CHARACTER_FILE, JSON.stringify(record));
+const readPersisted = async () => JSON.parse(await readFile(CHARACTER_FILE, 'utf8'));
+
+// One federation hop: `remote`'s wire snapshot lands on a machine whose character.json is `local`.
+async function deliver(local, remote) {
+ await persist(remote);
+ const { data: wire } = await dataSync.getSnapshot('character');
+ await persist(local);
+ const result = await dataSync.applyRemote('character', wire);
+ return { result, persisted: await readPersisted() };
+}
+
+describe('dataSync character — cumulative XP across independent grants', () => {
+ it('shared base 100 + independent +25 / +50 converges to 175 on both peers and stays there on redelivery', async () => {
+ const shared = grant(baseRecord(), 'base', 100);
+ const a = grant(shared, 'grant-a', 25);
+ const b = grant(shared, 'grant-b', 50);
+
+ const onA = await deliver(a, b);
+ const onB = await deliver(b, a);
+
+ expect(onA.persisted.xp).toBe(175);
+ expect(onB.persisted.xp).toBe(175);
+ expect(onA.persisted.events.map((e) => e.id).sort()).toEqual(['base', 'grant-a', 'grant-b']);
+
+ // Each machine now receives the other's MERGED record, and the same snapshot again.
+ const reA = await deliver(onA.persisted, onB.persisted);
+ const reB = await deliver(onB.persisted, onA.persisted);
+ const again = await deliver(reA.persisted, onB.persisted);
+ expect(reA.persisted.xp).toBe(175);
+ expect(reB.persisted.xp).toBe(175);
+ expect(again.persisted.xp).toBe(175);
+ // A redelivered snapshot changes nothing, so it must not rewrite the record.
+ expect(again.result.applied).toBe(false);
+ });
+
+ it('counts a repeated event ID once, with the existing event LWW picking the winning copy', async () => {
+ // The same grant id carries different payloads on each side; the later timestamp wins.
+ const older = { id: 'dup', type: 'xp', description: 'old copy', xp: 25, timestamp: '2026-02-01T00:00:00.000Z' };
+ const newer = { ...older, description: 'new copy', xp: 40, timestamp: '2026-02-02T00:00:00.000Z' };
+ const a = baseRecord({ xp: 25, events: [older] });
+ const b = baseRecord({ xp: 40, events: [newer] });
+
+ const { persisted } = await deliver(a, b);
+
+ expect(persisted.events).toHaveLength(1);
+ expect(persisted.events[0].description).toBe('new copy');
+ expect(persisted.xp).toBe(40);
+ });
+});
+
+describe('dataSync character — legacy XP the event ledger does not explain', () => {
+ it('retains a legacy baseline with no events exactly once (not summed across peers)', async () => {
+ const { persisted } = await deliver(baseRecord({ xp: 300 }), baseRecord({ xp: 300 }));
+ expect(persisted.xp).toBe(300);
+ });
+
+ it('keeps the shared legacy baseline once while counting each side\'s independent grant', async () => {
+ const legacy = baseRecord({ xp: 300 });
+ const a = grant(legacy, 'grant-a', 25);
+ const b = grant(legacy, 'grant-b', 50);
+
+ const onA = await deliver(a, b);
+ const onB = await deliver(b, a);
+
+ expect(onA.persisted.xp).toBe(375);
+ expect(onB.persisted.xp).toBe(375);
+ });
+
+ it('keeps a baseline that only the incomplete-ledger side carries', async () => {
+ // A has 100 XP from before events existed; B is a fresh machine with one grant.
+ const a = baseRecord({ xp: 100 });
+ const b = grant(baseRecord(), 'grant-b', 50);
+
+ expect((await deliver(a, b)).persisted.xp).toBe(150);
+ expect((await deliver(b, a)).persisted.xp).toBe(150);
+ });
+
+ it('applies a baseline-only increase even when the peer snapshot is older than the local record', async () => {
+ // No new events and an older peer updatedAt used to short-circuit the write entirely.
+ const local = baseRecord({ xp: 100, updatedAt: '2026-06-01T00:00:00.000Z' });
+ const remote = baseRecord({ xp: 150, updatedAt: '2026-03-01T00:00:00.000Z' });
+
+ const { result, persisted } = await deliver(local, remote);
+
+ expect(persisted.xp).toBe(150);
+ expect(result.applied).toBe(true);
+ });
+});
+
+describe('dataSync character — malformed history', () => {
+ it('never produces NaN or loses legacy XP from empty, non-XP or malformed events', async () => {
+ const local = baseRecord({
+ xp: 200,
+ events: [
+ { id: 'rest-1', type: 'rest', xp: 0, hpRecovered: 4, timestamp: '2026-02-01T00:00:00.000Z' },
+ { id: 'bad-string', type: 'xp', xp: '25', timestamp: '2026-02-02T00:00:00.000Z' },
+ { id: 'bad-nan', type: 'xp', xp: Number.NaN, timestamp: '2026-02-03T00:00:00.000Z' },
+ { id: 'bad-null', type: 'xp', xp: null, timestamp: '2026-02-04T00:00:00.000Z' },
+ { id: 'bad-negative', type: 'xp', xp: -50, timestamp: '2026-02-05T00:00:00.000Z' },
+ { id: 'no-xp-field', type: 'custom', timestamp: '2026-02-06T00:00:00.000Z' },
+ { type: 'xp', xp: 10, timestamp: '2026-02-07T00:00:00.000Z' }, // no id → not a ledger entry
+ null,
+ ].filter(Boolean),
+ });
+ const remote = baseRecord({ xp: 'not-a-number', events: [{ id: 'rest-1', type: 'rest', timestamp: '2026-02-01T00:00:00.000Z' }] });
+
+ const { persisted } = await deliver(local, remote);
+
+ expect(Number.isFinite(persisted.xp)).toBe(true);
+ // 200 total with no valid ledger entries: the whole amount stays as the unrepresented baseline.
+ expect(persisted.xp).toBe(200);
+ });
+
+ it('lands a malformed remote xp as a number when there is no local character yet', async () => {
+ await persist(baseRecord({ xp: 'garbage', events: [{ id: 'g1', type: 'xp', xp: 30, timestamp: nextTimestamp() }] }));
+ const { data: wire } = await dataSync.getSnapshot('character');
+ await rm(CHARACTER_FILE, { force: true });
+
+ const result = await dataSync.applyRemote('character', wire);
+
+ expect(result.applied).toBe(true);
+ // The grant on the ledger is XP the counter must not read below.
+ expect((await readPersisted()).xp).toBe(30);
+ });
+});
+
+describe('dataSync character — wire projection agrees with persistence', () => {
+ it('serves the reconciled xp, with the legacy level derived from it, on the next snapshot', async () => {
+ // Pick grants whose SUM crosses a legacy level threshold but whose larger counter alone does not.
+ const shared = grant(baseRecord(), 'base', 100);
+ const a = grant(shared, 'grant-a', 150);
+ const b = grant(shared, 'grant-b', 100);
+
+ const { persisted } = await deliver(a, b);
+ expect(persisted.xp).toBe(350);
+
+ const { data: wire } = await dataSync.getSnapshot('character');
+ expect(wire.xp).toBe(persisted.xp);
+ // Legacy curve: 300 ≤ 350 < 900 ⇒ level 2. Max-only merging would have read 250 ⇒ level 1.
+ expect(wire.level).toBe(2);
+ expect(persisted.level).toBeUndefined();
+ });
+});
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index f2f5f9650e..777f5721bf 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -466,7 +466,11 @@ async function applyCharacterRemote(remoteData) {
// No local character — accept remote entirely, but strip every derived field (an older
// peer still sends `level`): they're derived on read now (#2673/#2674), so a stored value
// would be stale and would re-propagate in our own snapshot.
- await atomicWrite(CHARACTER_FILE, characterService.stripDerivedFields(remoteData));
+ const accepted = characterService.stripDerivedFields(remoteData);
+ // Same accounting as the merge below, over a single input: a malformed remote `xp` lands as
+ // a valid number instead of null/NaN, and the counter never reads below its own ledger.
+ accepted.xp = characterService.reconcileXp([accepted], accepted.events);
+ await atomicWrite(CHARACTER_FILE, accepted);
console.log(`🔄 Character sync: accepted remote character`);
return { applied: true, count: 1 };
}
@@ -496,7 +500,9 @@ async function applyCharacterRemote(remoteData) {
name: scalarSource.name ?? local.name,
class: scalarSource.class ?? local.class,
avatarPath: scalarSource.avatarPath ?? local.avatarPath,
- xp: Math.max(local.xp || 0, remoteData.xp || 0),
+ // Reconciled from the merged event ledger, not Math.max: independent grants taken on
+ // different machines each survive in the event union and must each be counted (#9819).
+ xp: characterService.reconcileXp([local, remoteData], mergedEvents),
hp: scalarSource.hp,
maxHp: scalarSource.maxHp,
// `level` is age-derived on read (#2673), not persisted — never merge a stale peer level.
@@ -510,7 +516,8 @@ async function applyCharacterRemote(remoteData) {
// service's shared helper so a newly-derived field can't be forgotten at this site.
const persisted = characterService.stripDerivedFields(merged);
- if (eventsChanged || remoteTs > localTs) {
+ // A baseline-only change (no new event, older peer timestamp) still moves the counter.
+ if (eventsChanged || remoteTs > localTs || persisted.xp !== local.xp) {
await atomicWrite(CHARACTER_FILE, persisted);
console.log(`🔄 Character sync: merged ${mergedEvents.length} events`);
return { applied: true, count: mergedEvents.length };