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

sync the full Digital Twin dataset between peers, not just the four core files

[._.]/ Adam Eivya9aec7ebd7f0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 787d916b0f..8a54964689 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Digital Twin federation now syncs your *whole* identity — taste profile, documents, and autobiography — not just the four core files.** The `digitalTwin` sync category only ever transferred `identity` / `chronotype` / `longevity` / `feedback`, so a peer could read **"Digital Twin: synced"** while your taste questionnaire, soul documents, and autobiography stories never crossed between machines (they were never wired into the snapshot at all). The snapshot now covers everything under `data/digital-twin/`: the **taste profile** (responses union per section by `questionId`, LWW — answers given on either machine survive), **meta.json** (documents/test-histories/personas union by id, enrichment deep-unioned, settings fill-missing), the **`.md` documents** themselves (shipped by filename, written **add-only** so a local doc is never overwritten — with a path-traversal guard on peer-supplied names), and the **autobiography** (stories union by id with LWW, prompt schedule stays machine-local). The merge is additive and key-presence-guarded, so an older peer that still sends only the four legacy keys can't blank out the new data, and no schemaVersions gate is needed (digitalTwin stays unversioned). The "Digital Twin" sync-category description in the Instances UI now reflects the full coverage. (`server/services/digital-twin-sync.js`, `server/services/dataSync.js`, `client/src/pages/Instances.jsx`)
+
- **[issue-1310] Editorial check flags plot-structure & momentum problems — passive protagonist, deus ex machina, idiot plot, flat stakes, sagging middle, dropped subplots.** A new **Plot structure & momentum** check (Create → Editorial Checks) reads your drafted manuscript and surfaces the macro pathologies a developmental editor flags at the arc level: a **passive protagonist** (events happen *to* them instead of being driven by their choices), a **deus ex machina / convenient coincidence** that resolves a problem by luck rather than setup, an **idiot plot** that only holds together because someone won't say the obvious, **flat or unclear stakes** that never escalate, a **sagging middle** with no try-fail rhythm, and **dropped subplots** — threads that open and then fizzle. It reconciles dropped threads against your reverse-outline plotline tags and your authored reader-map hooks/payoffs, and defers whole-arc judgments (a sagging middle, a never-resolved thread) until it has seen the whole manuscript so a long book reviewed in chunks isn't false-flagged. Findings render as `Plot structure` notes in the manuscript editor, anchored to the issue and (where one exists) a verbatim quote. Ships a new stage prompt (`pipeline-editorial-plot-structure`) that migrates for existing installs (111). (#1310)
- **[issue-1311] Editorial check flags head-hopping / POV-discipline breaks within a scene.** A new **Head-hopping / POV discipline** LLM check (Create → Editorial Checks) polices viewpoint discipline in limited-POV prose — distinct from the existing **POV justification** check (#1295, which asks whether each viewpoint *character* earns an arc). For each limited-POV scene it flags narration that enters another character's head (reports interior thoughts/feelings the POV character can't know), reports knowledge or perception the POV character couldn't have (offstage events, things behind them), or switches POV mid-scene with no break — and suggests re-anchoring to the POV character's perception or inserting a proper scene break. It reads your reverse-outline scene segmentation as context (each scene's anchored POV character + the other characters on-stage, the candidate heads a hop slips into) and **degrades gracefully** to a whole-issue manuscript scan when no outline exists yet. It **no-ops when the series style guide sets third-person omniscient** — there the roaming viewpoint is intentional — and surfaces the configured POV person (first / third-limited / second) to the model so it judges against the discipline actually in force. Each finding anchors a verbatim quote + issue number and names whose head was entered. Ships a new stage prompt (`pipeline-editorial-head-hopping`) that migrates for existing installs (112). (`server/lib/editorial/checkRegistry.js`, `scripts/migrations/112-editorial-head-hopping-stage.js`, #1311)
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 74b2b530b2..3d53df5c62 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -485,7 +485,7 @@ const SYNC_CATEGORY_META = [
{ key: 'memory', label: 'Memory', icon: Database, description: 'CoS agent memories (PostgreSQL)' },
{ key: 'goals', label: 'Goals', icon: Target, description: 'Life goals, milestones, progress tracking' },
{ key: 'character', label: 'Character', icon: Sword, description: 'XP, HP, level, events, character sheet' },
- { key: 'digitalTwin', label: 'Digital Twin', icon: Fingerprint, description: 'Identity, chronotype, longevity, feedback' },
+ { key: 'digitalTwin', label: 'Digital Twin', icon: Fingerprint, description: 'Identity, taste, documents, autobiography, chronotype, longevity, feedback' },
{ key: 'meatspace', label: 'Meatspace', icon: HeartPulse, description: 'Daily logs, blood tests, body metrics, eyes' },
{ key: 'universe', label: 'Universe', icon: Sparkles, description: 'Universe Builder canon: characters, places, objects' },
{ key: 'pipeline', label: 'Pipeline', icon: Film, description: 'Series + issues record state (no image/video blobs)' },
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 38e31475f3..81455484bc 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -28,15 +28,20 @@ import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './media
import { listSyncableSessionsForWire, mergeStorySessionsFromSync } from './storyBuilder.js';
import { getStoryBuilderMutationEpoch } from './storyBuilderStore/store.js';
import { sanitizeStateForWire } from '../lib/syncWire.js';
+import {
+ getDigitalTwinSnapshot,
+ applyDigitalTwinRemote,
+ DIGITAL_TWIN_CHECKSUM_PATHS,
+} from './digital-twin-sync.js';
// --- Category Definitions ---
const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');
const CHARACTER_FILE = join(PATHS.data, 'character.json');
-const IDENTITY_FILE = join(PATHS.digitalTwin, 'identity.json');
-const CHRONOTYPE_FILE = join(PATHS.digitalTwin, 'chronotype.json');
-const LONGEVITY_FILE = join(PATHS.digitalTwin, 'longevity.json');
-const FEEDBACK_FILE = join(PATHS.digitalTwin, 'feedback.json');
+// Digital Twin snapshot + merge lives in ./digital-twin-sync.js (it now covers
+// the FULL identity dataset — taste, documents, autobiography — not just the
+// four core JSON files). dataSync delegates to it the same way it delegates
+// universe/pipeline merges to their owning services.
const MEATSPACE_DIR = PATHS.meatspace;
// Pipeline series + issues used to live under data/pipeline-series/<id> and
// data/pipeline-issues/<id>; #1015 moved the RECORDS into PostgreSQL
@@ -317,44 +322,8 @@ async function applyCharacterRemote(remoteData) {
}
// --- Category: Digital Twin ---
-
-const DIGITAL_TWIN_FILES = {
- identity: { path: IDENTITY_FILE, timestampField: 'updatedAt', merge: 'lww' },
- chronotype: { path: CHRONOTYPE_FILE, timestampField: 'derivedAt', merge: 'deepUnion' },
- longevity: { path: LONGEVITY_FILE, timestampField: 'derivedAt', merge: 'deepUnion' },
- feedback: { path: FEEDBACK_FILE, timestampField: 'updatedAt', merge: 'lww' }
-};
-
-async function getDigitalTwinSnapshot() {
- const result = {};
- for (const [key, { path }] of Object.entries(DIGITAL_TWIN_FILES)) {
- result[key] = await readJSONFile(path, null);
- }
- return { data: result, checksum: computeChecksum(result) };
-}
-
-async function applyDigitalTwinRemote(remoteData) {
- if (!remoteData) return { applied: false, count: 0 };
-
- let totalApplied = 0;
- for (const [key, { path, timestampField, merge }] of Object.entries(DIGITAL_TWIN_FILES)) {
- const remoteFile = remoteData[key];
- if (!remoteFile) continue;
-
- const local = await readJSONFile(path, null);
- const mergeFn = merge === 'deepUnion' ? mergeDeepUnion : mergeObjectLWW;
- const { merged, changed } = mergeFn(local, remoteFile, timestampField);
- if (changed) {
- await atomicWrite(path, merged);
- totalApplied++;
- }
- }
-
- if (totalApplied > 0) {
- console.log(`🔄 Digital twin sync: updated ${totalApplied} files`);
- }
- return { applied: totalApplied > 0, count: totalApplied };
-}
+// getDigitalTwinSnapshot / applyDigitalTwinRemote are imported from
+// ./digital-twin-sync.js (see import block at top).
// --- Category: Meatspace ---
@@ -763,7 +732,9 @@ async function applyStoryBuilderRemote(remoteData) {
const CHECKSUM_PATHS = {
goals: [GOALS_FILE],
character: [CHARACTER_FILE],
- digitalTwin: Object.values(DIGITAL_TWIN_FILES).map((f) => f.path),
+ // The whole digital-twin dir is watched (taste, meta, .md documents,
+ // autobiography/) — see DIGITAL_TWIN_CHECKSUM_PATHS in digital-twin-sync.js.
+ digitalTwin: DIGITAL_TWIN_CHECKSUM_PATHS,
meatspace: Object.keys(MEATSPACE_FILES).map((f) => join(MEATSPACE_DIR, f)),
// PEER_SUBSCRIPTIONS_FILE is in the scoped categories' paths so a
// subscribe/unsubscribe invalidates the per-peer snapshot checksum cache —
diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.js
new file mode 100644
index 0000000000..958abbc291
--- /dev/null
+++ b/server/services/digital-twin-sync.js
@@ -0,0 +1,409 @@
+/**
+ * Digital Twin Sync
+ *
+ * Snapshot + merge for the FULL Digital Twin / identity dataset between PortOS
+ * peer instances. The `digitalTwin` snapshot category in `dataSync.js` delegates
+ * here (the same way the universe/pipeline categories delegate to their owning
+ * services).
+ *
+ * Historically only four files synced — identity, chronotype, longevity,
+ * feedback — so the "Digital Twin: synced" badge could read green while the
+ * documents, taste profile, and autobiography never crossed between peers. This
+ * module widens the snapshot to cover everything under `data/digital-twin/`:
+ *
+ * - identity.json — LWW on updatedAt
+ * - chronotype.json — deep union (derived markers, derivedAt tiebreak)
+ * - longevity.json — deep union (derived markers, derivedAt tiebreak)
+ * - feedback.json — LWW on updatedAt
+ * - taste-profile.json — per-section union of responses (never lose answers)
+ * - meta.json — union of documents/histories/personas, deep-union
+ * enrichment, fill-missing settings
+ * - *.md documents — content shipped by filename, ADD-ONLY on the
+ * receiver (a local doc is never overwritten)
+ * - autobiography/ — stories union by id (LWW), config stays local
+ *
+ * Merge philosophy mirrors the rest of dataSync: union semantics, no data is
+ * ever lost, and every field is key-presence guarded so an OLDER peer that only
+ * sends the four legacy keys can't blank out taste/documents/autobiography. The
+ * snapshot is additive and ignore-if-unknown, so it needs no schemaVersions gate
+ * (digitalTwin stays unversioned — see SNAPSHOT_CATEGORY_SCHEMA_KEYS).
+ */
+
+import crypto from 'crypto';
+import { join, basename } from 'path';
+import { readdir, readFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { atomicWrite, readJSONFile, ensureDir, PATHS } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
+
+const DIR = PATHS.digitalTwin;
+const IDENTITY_FILE = join(DIR, 'identity.json');
+const CHRONOTYPE_FILE = join(DIR, 'chronotype.json');
+const LONGEVITY_FILE = join(DIR, 'longevity.json');
+const FEEDBACK_FILE = join(DIR, 'feedback.json');
+const TASTE_FILE = join(DIR, 'taste-profile.json');
+const META_FILE = join(DIR, 'meta.json');
+const AUTOBIO_DIR = join(DIR, 'autobiography');
+const AUTOBIO_STORIES_FILE = join(AUTOBIO_DIR, 'stories.json');
+const AUTOBIO_CONFIG_FILE = join(AUTOBIO_DIR, 'config.json');
+
+// Paths whose fingerprints feed the dataSync checksum cache. The whole
+// digital-twin dir is watched (two levels deep — covers top-level files, the
+// .md documents, and autobiography/*) so any edit invalidates the snapshot.
+// goals.json also lives here under its own `goals` category — re-checksumming
+// on a goals edit is harmless over-invalidation (the snapshot omits goals, so
+// the checksum is unchanged and the orchestrator still skips the transfer).
+export const DIGITAL_TWIN_CHECKSUM_PATHS = [DIR];
+
+function computeChecksum(data) {
+ return crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
+}
+
+// --- Pure merge helpers (exported for unit tests) ---
+
+/** LWW for single objects — remote wins when its timestamp is strictly newer. */
+export function mergeObjectLWW(local, remote, timestampField = 'updatedAt') {
+ if (!isPlainObject(remote)) return { merged: local, changed: false };
+ if (!isPlainObject(local)) return { merged: remote, changed: true };
+ const localTs = local[timestampField] || '';
+ const remoteTs = remote[timestampField] || '';
+ if (remoteTs > localTs) return { merged: remote, changed: true };
+ return { merged: local, changed: false };
+}
+
+/**
+ * Deep union for derived files (chronotype, longevity) where timestamps are
+ * regenerated on every derivation: union nested marker objects (local wins
+ * per-key), take remote for locally-missing/default scalars, newer timestamp.
+ */
+export function mergeDeepUnion(local, remote, timestampField = 'derivedAt') {
+ if (!isPlainObject(remote)) return { merged: local, changed: false };
+ if (!isPlainObject(local)) return { merged: remote, changed: true };
+
+ const merged = { ...local };
+ let changed = false;
+
+ for (const [key, remoteVal] of Object.entries(remote)) {
+ if (key === timestampField) continue;
+ const localVal = local[key];
+
+ if (isPlainObject(remoteVal) && isPlainObject(localVal)) {
+ const mergedObj = { ...localVal };
+ for (const [k, v] of Object.entries(remoteVal)) {
+ if (!(k in mergedObj)) { mergedObj[k] = v; changed = true; }
+ }
+ merged[key] = mergedObj;
+ continue;
+ }
+ if (localVal === undefined || localVal === null) {
+ merged[key] = remoteVal; changed = true; continue;
+ }
+ if (localVal === 0 && remoteVal !== 0) { merged[key] = remoteVal; changed = true; }
+ }
+
+ const localTs = local[timestampField] || '';
+ const remoteTs = remote[timestampField] || '';
+ merged[timestampField] = remoteTs > localTs ? remoteTs : localTs;
+ return { merged, changed };
+}
+
+/**
+ * Union two arrays of records by a key field. Records unique to either side are
+ * kept; on a key collision the local record is kept (ADD-ONLY) unless a
+ * timestampField is given and remote's is strictly newer (LWW).
+ */
+export function unionByKey(localArr, remoteArr, keyField, timestampField = null) {
+ const local = Array.isArray(localArr) ? localArr : [];
+ const remote = Array.isArray(remoteArr) ? remoteArr : [];
+ const map = new Map();
+ for (const item of local) if (isPlainObject(item)) map.set(item[keyField], item);
+ let changed = false;
+ for (const item of remote) {
+ if (!isPlainObject(item)) continue;
+ const key = item[keyField];
+ const existing = map.get(key);
+ if (!existing) { map.set(key, item); changed = true; continue; }
+ if (timestampField) {
+ const lt = existing[timestampField] || '';
+ const rt = item[timestampField] || '';
+ if (rt > lt) { map.set(key, item); changed = true; }
+ }
+ }
+ return { merged: Array.from(map.values()), changed };
+}
+
+const TASTE_STATUS_RANK = { pending: 0, in_progress: 1, completed: 2 };
+function pickStatus(a, b) {
+ return (TASTE_STATUS_RANK[b] ?? -1) > (TASTE_STATUS_RANK[a] ?? -1) ? b : a;
+}
+
+/**
+ * Merge taste profiles. Within each section, responses union by questionId
+ * (LWW on updatedAt||answeredAt) so answers given on either machine survive;
+ * section status takes the more-complete value; a missing local summary is
+ * filled from remote. Top-level profileSummary/lastSessionAt are LWW on the
+ * file's updatedAt.
+ */
+export function mergeTaste(local, remote) {
+ if (!isPlainObject(remote)) return { merged: local, changed: false };
+ if (!isPlainObject(local)) return { merged: remote, changed: true };
+
+ let changed = false;
+ const sections = { ...(isPlainObject(local.sections) ? local.sections : {}) };
+
+ for (const [secId, remoteSec] of Object.entries(isPlainObject(remote.sections) ? remote.sections : {})) {
+ if (!isPlainObject(remoteSec)) continue;
+ const localSec = sections[secId];
+ if (!isPlainObject(localSec)) { sections[secId] = remoteSec; changed = true; continue; }
+
+ // Responses union by questionId, LWW on updatedAt||answeredAt — so an answer
+ // given on either machine survives (taste responses carry no single
+ // timestamp field, so resolve the tiebreak explicitly rather than via
+ // unionByKey).
+ const byId = new Map((Array.isArray(localSec.responses) ? localSec.responses : []).map((r) => [r.questionId, r]));
+ let secChanged = false;
+ for (const rr of Array.isArray(remoteSec.responses) ? remoteSec.responses : []) {
+ if (!isPlainObject(rr)) continue;
+ const lr = byId.get(rr.questionId);
+ if (!lr) { byId.set(rr.questionId, rr); secChanged = true; continue; }
+ const lt = lr.updatedAt || lr.answeredAt || '';
+ const rt = rr.updatedAt || rr.answeredAt || '';
+ if (rt > lt) { byId.set(rr.questionId, rr); secChanged = true; }
+ }
+ const mergedResponses = Array.from(byId.values());
+
+ const status = pickStatus(localSec.status, remoteSec.status);
+ const summary = localSec.summary ?? remoteSec.summary ?? null;
+ if (secChanged || status !== localSec.status || summary !== localSec.summary) {
+ sections[secId] = { ...localSec, responses: mergedResponses, status, summary };
+ changed = true;
+ }
+ }
+
+ const merged = { ...local, sections };
+ const localTs = local.updatedAt || '';
+ const remoteTs = remote.updatedAt || '';
+ if (remoteTs > localTs) {
+ if (remote.profileSummary != null && remote.profileSummary !== local.profileSummary) {
+ merged.profileSummary = remote.profileSummary; changed = true;
+ }
+ if ((remote.lastSessionAt || '') > (local.lastSessionAt || '')) {
+ merged.lastSessionAt = remote.lastSessionAt; changed = true;
+ }
+ merged.updatedAt = remote.updatedAt;
+ }
+ return { merged, changed };
+}
+
+function mergeEnrichment(local, remote) {
+ const l = isPlainObject(local) ? local : {};
+ const r = isPlainObject(remote) ? remote : {};
+ const completedCategories = [...new Set([
+ ...(Array.isArray(l.completedCategories) ? l.completedCategories : []),
+ ...(Array.isArray(r.completedCategories) ? r.completedCategories : []),
+ ])];
+ const lastSession = (r.lastSession || '') > (l.lastSession || '') ? r.lastSession : (l.lastSession ?? null);
+ const questionsAnswered = { ...(isPlainObject(l.questionsAnswered) ? l.questionsAnswered : {}) };
+ for (const [k, v] of Object.entries(isPlainObject(r.questionsAnswered) ? r.questionsAnswered : {})) {
+ questionsAnswered[k] = Math.max(questionsAnswered[k] || 0, v || 0);
+ }
+ const merged = { ...l, completedCategories, lastSession };
+ if (Object.keys(questionsAnswered).length) merged.questionsAnswered = questionsAnswered;
+ return { merged, changed: JSON.stringify(merged) !== JSON.stringify(l) };
+}
+
+/**
+ * Merge digital-twin meta.json: documents union by filename (ADD-ONLY — a local
+ * doc entry is never replaced), the four test histories + personas union by id,
+ * enrichment deep-unions, settings fill missing keys (local values win).
+ */
+export function mergeMeta(local, remote) {
+ if (!isPlainObject(remote)) return { merged: local, changed: false };
+ if (!isPlainObject(local)) return { merged: remote, changed: true };
+
+ let changed = false;
+ const merged = { ...local };
+
+ const docs = unionByKey(local.documents, remote.documents, 'filename');
+ if (docs.changed) { merged.documents = docs.merged; changed = true; }
+
+ for (const key of ['testHistory', 'valuesTestHistory', 'adversarialTestHistory', 'multiTurnTestHistory']) {
+ const u = unionByKey(local[key], remote[key], 'id');
+ if (u.changed) { merged[key] = u.merged; changed = true; }
+ }
+
+ const personas = unionByKey(local.personas, remote.personas, 'id');
+ if (personas.changed) { merged.personas = personas.merged; changed = true; }
+
+ if (isPlainObject(remote.enrichment)) {
+ const e = mergeEnrichment(local.enrichment, remote.enrichment);
+ if (e.changed) { merged.enrichment = e.merged; changed = true; }
+ }
+
+ if (isPlainObject(remote.settings)) {
+ const settings = { ...remote.settings, ...(isPlainObject(local.settings) ? local.settings : {}) };
+ if (JSON.stringify(settings) !== JSON.stringify(local.settings || {})) {
+ merged.settings = settings; changed = true;
+ }
+ }
+
+ return { merged, changed };
+}
+
+/** Merge autobiography stories: union by id (LWW on updatedAt||createdAt), union usedPrompts. */
+export function mergeAutobiographyStories(local, remote) {
+ if (!isPlainObject(remote)) return { merged: local, changed: false };
+ if (!isPlainObject(local)) return { merged: remote, changed: true };
+
+ const byId = new Map((Array.isArray(local.stories) ? local.stories : []).map((s) => [s.id, s]));
+ let changed = false;
+ for (const rs of Array.isArray(remote.stories) ? remote.stories : []) {
+ if (!isPlainObject(rs)) continue;
+ const ls = byId.get(rs.id);
+ if (!ls) { byId.set(rs.id, rs); changed = true; continue; }
+ const lt = ls.updatedAt || ls.createdAt || '';
+ const rt = rs.updatedAt || rs.createdAt || '';
+ if (rt > lt) { byId.set(rs.id, rs); changed = true; }
+ }
+
+ const localUsed = Array.isArray(local.usedPrompts) ? local.usedPrompts : [];
+ const usedPrompts = [...new Set([...localUsed, ...(Array.isArray(remote.usedPrompts) ? remote.usedPrompts : [])])];
+ if (usedPrompts.length !== localUsed.length) changed = true;
+
+ return { merged: { ...local, stories: Array.from(byId.values()), usedPrompts }, changed };
+}
+
+// Sanitize a peer-supplied document name down to a safe `*.md` basename so a
+// malformed/buggy payload can't write outside the digital-twin dir.
+export function safeMdName(name) {
+ if (typeof name !== 'string') return null;
+ const base = basename(name);
+ if (base !== name) return null;
+ if (!base.toLowerCase().endsWith('.md')) return null;
+ if (base.startsWith('.')) return null;
+ return base;
+}
+
+// --- Snapshot ---
+
+async function readMarkdownDocuments() {
+ const files = await readdir(DIR).catch(() => []);
+ const reads = await Promise.all(
+ files.filter((f) => safeMdName(f)).map((name) =>
+ readFile(join(DIR, name), 'utf-8').then((content) => [name, content], () => [name, null])
+ )
+ );
+ const out = {};
+ for (const [name, content] of reads) if (typeof content === 'string') out[name] = content;
+ return out;
+}
+
+export async function getDigitalTwinSnapshot() {
+ // The reads are independent — run them concurrently. The snapshot is
+ // re-materialized whenever the dir fingerprint changes (every sync cycle on a
+ // checksum-cache miss), so the parallelism is worth it.
+ const [identity, chronotype, longevity, feedback, taste, meta, documents, stories, config] =
+ await Promise.all([
+ readJSONFile(IDENTITY_FILE, null),
+ readJSONFile(CHRONOTYPE_FILE, null),
+ readJSONFile(LONGEVITY_FILE, null),
+ readJSONFile(FEEDBACK_FILE, null),
+ readJSONFile(TASTE_FILE, null),
+ readJSONFile(META_FILE, null),
+ readMarkdownDocuments(),
+ readJSONFile(AUTOBIO_STORIES_FILE, null),
+ readJSONFile(AUTOBIO_CONFIG_FILE, null),
+ ]);
+ const data = { identity, chronotype, longevity, feedback, taste, meta, documents, autobiography: { stories, config } };
+ return { data, checksum: computeChecksum(data) };
+}
+
+// --- Apply ---
+
+async function applyMerge(path, remote, mergeFn, { dir } = {}) {
+ if (remote === undefined || remote === null) return 0;
+ const local = await readJSONFile(path, null);
+ const { merged, changed } = mergeFn(local, remote);
+ if (!changed) return 0;
+ if (dir) await ensureDir(dir);
+ await atomicWrite(path, merged);
+ return 1;
+}
+
+// Documents are written ADD-ONLY: a local .md is never overwritten by a peer's
+// copy (we have no per-document timestamp to order edits). New documents the
+// receiver is missing are written verbatim. The meta.json merge separately
+// brings over each document's metadata entry so the UI lists them.
+async function applyDocuments(documents) {
+ if (!isPlainObject(documents)) return 0;
+ let count = 0;
+ for (const [rawName, content] of Object.entries(documents)) {
+ const name = safeMdName(rawName);
+ if (!name || typeof content !== 'string') continue;
+ const filePath = join(DIR, name);
+ if (existsSync(filePath)) continue;
+ await ensureDir(DIR);
+ await atomicWrite(filePath, content);
+ count++;
+ }
+ return count;
+}
+
+async function applyAutobiographyConfigIfAbsent(config) {
+ if (!isPlainObject(config)) return 0;
+ if (existsSync(AUTOBIO_CONFIG_FILE)) return 0; // prompt schedule stays machine-local
+ await ensureDir(AUTOBIO_DIR);
+ await atomicWrite(AUTOBIO_CONFIG_FILE, config);
+ return 1;
+}
+
+// taste-questionnaire and digital-twin-meta keep their own in-memory caches (the
+// taste cache has NO TTL), so a raw atomicWrite to their files would leave the UI
+// serving pre-sync data. Route those two through the owning services so the
+// cache invalidates (taste) and the cache refreshes + `meta:changed` fires
+// (meta). Dynamic import keeps those services — and taste's heavy digital-twin.js
+// barrel — out of this module's load path (mirrors dataSync's peerSync import).
+
+async function applyTaste(remoteTaste) {
+ if (!isPlainObject(remoteTaste)) return 0;
+ const local = await readJSONFile(TASTE_FILE, null);
+ const { merged, changed } = mergeTaste(local, remoteTaste);
+ if (!changed) return 0;
+ await atomicWrite(TASTE_FILE, merged);
+ const { invalidateTasteProfileCache } = await import('./taste-questionnaire.js');
+ invalidateTasteProfileCache();
+ return 1;
+}
+
+async function applyMeta(remoteMeta) {
+ if (!isPlainObject(remoteMeta)) return 0;
+ const { loadMeta, saveMeta } = await import('./digital-twin-meta.js');
+ const local = await loadMeta();
+ const { merged, changed } = mergeMeta(local, remoteMeta);
+ if (!changed) return 0;
+ await saveMeta(merged); // updates the meta cache + emits `meta:changed`
+ return 1;
+}
+
+export async function applyDigitalTwinRemote(remoteData) {
+ if (!isPlainObject(remoteData)) return { applied: false, count: 0 };
+
+ let count = 0;
+ count += await applyMerge(IDENTITY_FILE, remoteData.identity, (l, r) => mergeObjectLWW(l, r, 'updatedAt'));
+ count += await applyMerge(CHRONOTYPE_FILE, remoteData.chronotype, (l, r) => mergeDeepUnion(l, r, 'derivedAt'));
+ count += await applyMerge(LONGEVITY_FILE, remoteData.longevity, (l, r) => mergeDeepUnion(l, r, 'derivedAt'));
+ count += await applyMerge(FEEDBACK_FILE, remoteData.feedback, (l, r) => mergeObjectLWW(l, r, 'updatedAt'));
+ count += await applyTaste(remoteData.taste);
+ // Documents before meta: if loadMeta has to rebuild meta from a disk scan, the
+ // newly-written .md files should already be present to be catalogued.
+ count += await applyDocuments(remoteData.documents);
+ count += await applyMeta(remoteData.meta);
+
+ if (isPlainObject(remoteData.autobiography)) {
+ count += await applyMerge(AUTOBIO_STORIES_FILE, remoteData.autobiography.stories, mergeAutobiographyStories, { dir: AUTOBIO_DIR });
+ count += await applyAutobiographyConfigIfAbsent(remoteData.autobiography.config);
+ }
+
+ if (count > 0) console.log(`🔄 Digital twin sync: updated ${count} items`);
+ return { applied: count > 0, count };
+}
diff --git a/server/services/digital-twin-sync.test.js b/server/services/digital-twin-sync.test.js
new file mode 100644
index 0000000000..8fb02e2454
--- /dev/null
+++ b/server/services/digital-twin-sync.test.js
@@ -0,0 +1,215 @@
+import { describe, it, expect } from 'vitest';
+import {
+ mergeObjectLWW,
+ mergeDeepUnion,
+ unionByKey,
+ mergeTaste,
+ mergeMeta,
+ mergeAutobiographyStories,
+ safeMdName,
+} from './digital-twin-sync.js';
+
+describe('mergeObjectLWW', () => {
+ it('takes remote when local is missing', () => {
+ expect(mergeObjectLWW(null, { updatedAt: '2026-01-01' })).toEqual({
+ merged: { updatedAt: '2026-01-01' },
+ changed: true,
+ });
+ });
+ it('keeps local when remote is missing/invalid', () => {
+ expect(mergeObjectLWW({ updatedAt: '2026-01-01' }, null).changed).toBe(false);
+ });
+ it('remote wins only when strictly newer', () => {
+ const local = { v: 'L', updatedAt: '2026-01-02' };
+ expect(mergeObjectLWW(local, { v: 'R', updatedAt: '2026-01-01' }).merged.v).toBe('L');
+ expect(mergeObjectLWW(local, { v: 'R', updatedAt: '2026-01-03' }).merged.v).toBe('R');
+ expect(mergeObjectLWW(local, { v: 'R', updatedAt: '2026-01-02' }).changed).toBe(false);
+ });
+});
+
+describe('mergeDeepUnion', () => {
+ it('unions nested marker objects, local wins per-key', () => {
+ const local = { markers: { a: 1 }, derivedAt: '2026-01-01' };
+ const remote = { markers: { a: 9, b: 2 }, derivedAt: '2026-01-02' };
+ const { merged, changed } = mergeDeepUnion(local, remote, 'derivedAt');
+ expect(merged.markers).toEqual({ a: 1, b: 2 });
+ expect(merged.derivedAt).toBe('2026-01-02');
+ expect(changed).toBe(true);
+ });
+ it('fills locally-missing/default scalars from remote', () => {
+ const { merged } = mergeDeepUnion({ score: 0, derivedAt: '' }, { score: 5, age: 40, derivedAt: '' }, 'derivedAt');
+ expect(merged.score).toBe(5);
+ expect(merged.age).toBe(40);
+ });
+});
+
+describe('unionByKey', () => {
+ it('adds remote records not present locally; keeps local on conflict (add-only)', () => {
+ const { merged, changed } = unionByKey(
+ [{ id: 'a', v: 'L' }],
+ [{ id: 'a', v: 'R' }, { id: 'b', v: 'R' }],
+ 'id'
+ );
+ expect(merged).toHaveLength(2);
+ expect(merged.find((x) => x.id === 'a').v).toBe('L');
+ expect(changed).toBe(true);
+ });
+ it('LWW on conflict when a timestampField is provided', () => {
+ const { merged } = unionByKey(
+ [{ id: 'a', v: 'L', updatedAt: '2026-01-01' }],
+ [{ id: 'a', v: 'R', updatedAt: '2026-01-09' }],
+ 'id',
+ 'updatedAt'
+ );
+ expect(merged[0].v).toBe('R');
+ });
+ it('tolerates non-array inputs', () => {
+ expect(unionByKey(null, undefined, 'id')).toEqual({ merged: [], changed: false });
+ });
+});
+
+describe('mergeTaste', () => {
+ it('unions responses across machines so no answer is lost', () => {
+ const local = {
+ updatedAt: '2026-03-01',
+ sections: { movies: { status: 'in_progress', responses: [{ questionId: 'movies-core-1', answer: 'A', answeredAt: '2026-02-01' }], summary: null } },
+ };
+ const remote = {
+ updatedAt: '2026-03-02',
+ sections: { movies: { status: 'in_progress', responses: [{ questionId: 'movies-core-2', answer: 'B', answeredAt: '2026-02-02' }], summary: null } },
+ };
+ const { merged, changed } = mergeTaste(local, remote);
+ const ids = merged.sections.movies.responses.map((r) => r.questionId).sort();
+ expect(ids).toEqual(['movies-core-1', 'movies-core-2']);
+ expect(changed).toBe(true);
+ });
+
+ it('LWW per response by updatedAt||answeredAt', () => {
+ const local = { updatedAt: '2026-03-01', sections: { music: { status: 'in_progress', responses: [{ questionId: 'q', answer: 'old', answeredAt: '2026-01-01' }], summary: null } } };
+ const remote = { updatedAt: '2026-03-01', sections: { music: { status: 'in_progress', responses: [{ questionId: 'q', answer: 'new', updatedAt: '2026-02-01' }], summary: null } } };
+ const { merged } = mergeTaste(local, remote);
+ expect(merged.sections.music.responses[0].answer).toBe('new');
+ });
+
+ it('adds a whole section the local profile is missing', () => {
+ const local = { updatedAt: '2026-03-01', sections: { movies: { status: 'completed', responses: [], summary: 'm' } } };
+ const remote = { updatedAt: '2026-03-01', sections: { food: { status: 'in_progress', responses: [{ questionId: 'food-core-1', answer: 'x' }], summary: null } } };
+ const { merged, changed } = mergeTaste(local, remote);
+ expect(merged.sections.food).toBeDefined();
+ expect(merged.sections.movies).toBeDefined();
+ expect(changed).toBe(true);
+ });
+
+ it('takes the more-complete section status and fills a missing summary', () => {
+ const local = { updatedAt: '2026-03-01', sections: { art: { status: 'in_progress', responses: [], summary: null } } };
+ const remote = { updatedAt: '2026-03-01', sections: { art: { status: 'completed', responses: [], summary: 'done' } } };
+ const { merged } = mergeTaste(local, remote);
+ expect(merged.sections.art.status).toBe('completed');
+ expect(merged.sections.art.summary).toBe('done');
+ });
+
+ it('does not clobber a local summary with remote', () => {
+ const local = { updatedAt: '2026-03-01', sections: { art: { status: 'completed', responses: [], summary: 'mine' } } };
+ const remote = { updatedAt: '2026-03-09', sections: { art: { status: 'completed', responses: [], summary: 'theirs' } } };
+ const { merged } = mergeTaste(local, remote);
+ expect(merged.sections.art.summary).toBe('mine');
+ });
+
+ it('takes remote profileSummary only when the file is newer', () => {
+ const base = { sections: {} };
+ expect(mergeTaste({ ...base, updatedAt: '2026-03-09', profileSummary: 'L' }, { ...base, updatedAt: '2026-03-01', profileSummary: 'R' }).merged.profileSummary).toBe('L');
+ expect(mergeTaste({ ...base, updatedAt: '2026-03-01', profileSummary: 'L' }, { ...base, updatedAt: '2026-03-09', profileSummary: 'R' }).merged.profileSummary).toBe('R');
+ });
+
+ it('takes remote wholesale when local is absent', () => {
+ const remote = { updatedAt: '2026-03-01', sections: { movies: { status: 'in_progress', responses: [], summary: null } } };
+ expect(mergeTaste(null, remote)).toEqual({ merged: remote, changed: true });
+ });
+});
+
+describe('mergeMeta', () => {
+ it('unions documents by filename (add-only) and keeps local entry on conflict', () => {
+ const local = { documents: [{ id: '1', filename: 'SOUL.md', weight: 9 }] };
+ const remote = { documents: [{ id: '1', filename: 'SOUL.md', weight: 1 }, { id: '2', filename: 'FAVORITES.md', weight: 5 }] };
+ const { merged, changed } = mergeMeta(local, remote);
+ expect(merged.documents).toHaveLength(2);
+ expect(merged.documents.find((d) => d.filename === 'SOUL.md').weight).toBe(9);
+ expect(changed).toBe(true);
+ });
+
+ it('unions all four test histories and personas by id', () => {
+ const local = { testHistory: [{ id: 't1' }], personas: [{ id: 'p1' }] };
+ const remote = {
+ testHistory: [{ id: 't2' }],
+ valuesTestHistory: [{ id: 'v1' }],
+ adversarialTestHistory: [{ id: 'a1' }],
+ multiTurnTestHistory: [{ id: 'm1' }],
+ personas: [{ id: 'p2' }],
+ };
+ const { merged } = mergeMeta(local, remote);
+ expect(merged.testHistory.map((x) => x.id).sort()).toEqual(['t1', 't2']);
+ expect(merged.valuesTestHistory).toHaveLength(1);
+ expect(merged.adversarialTestHistory).toHaveLength(1);
+ expect(merged.multiTurnTestHistory).toHaveLength(1);
+ expect(merged.personas.map((x) => x.id).sort()).toEqual(['p1', 'p2']);
+ });
+
+ it('deep-unions enrichment (categories, max question counts, newest session)', () => {
+ const local = { enrichment: { completedCategories: ['core'], lastSession: '2026-01-01', questionsAnswered: { core: 3 } } };
+ const remote = { enrichment: { completedCategories: ['social'], lastSession: '2026-02-01', questionsAnswered: { core: 5, social: 2 } } };
+ const { merged } = mergeMeta(local, remote);
+ expect(merged.enrichment.completedCategories.sort()).toEqual(['core', 'social']);
+ expect(merged.enrichment.lastSession).toBe('2026-02-01');
+ expect(merged.enrichment.questionsAnswered).toEqual({ core: 5, social: 2 });
+ });
+
+ it('fills missing settings keys but keeps local values', () => {
+ const local = { settings: { autoInjectToCoS: false } };
+ const remote = { settings: { autoInjectToCoS: true, maxContextTokens: 4000 } };
+ const { merged } = mergeMeta(local, remote);
+ expect(merged.settings).toEqual({ autoInjectToCoS: false, maxContextTokens: 4000 });
+ });
+
+ it('takes remote wholesale when local meta is absent', () => {
+ const remote = { documents: [{ id: '1', filename: 'SOUL.md' }] };
+ expect(mergeMeta(null, remote)).toEqual({ merged: remote, changed: true });
+ });
+});
+
+describe('mergeAutobiographyStories', () => {
+ it('unions stories by id and unions usedPrompts', () => {
+ const local = { stories: [{ id: 's1', content: 'L', createdAt: '2026-01-01' }], usedPrompts: ['childhood-0'] };
+ const remote = { stories: [{ id: 's2', content: 'R', createdAt: '2026-01-02' }], usedPrompts: ['family-0'] };
+ const { merged, changed } = mergeAutobiographyStories(local, remote);
+ expect(merged.stories.map((s) => s.id).sort()).toEqual(['s1', 's2']);
+ expect(merged.usedPrompts.sort()).toEqual(['childhood-0', 'family-0']);
+ expect(changed).toBe(true);
+ });
+
+ it('LWW on a shared story by updatedAt||createdAt', () => {
+ const local = { stories: [{ id: 's1', content: 'old', createdAt: '2026-01-01' }] };
+ const remote = { stories: [{ id: 's1', content: 'new', createdAt: '2026-01-01', updatedAt: '2026-02-01' }] };
+ const { merged } = mergeAutobiographyStories(local, remote);
+ expect(merged.stories[0].content).toBe('new');
+ });
+
+ it('is a no-op when remote has nothing new', () => {
+ const local = { stories: [{ id: 's1', createdAt: '2026-01-01' }], usedPrompts: ['a'] };
+ expect(mergeAutobiographyStories(local, { stories: [{ id: 's1', createdAt: '2026-01-01' }], usedPrompts: ['a'] }).changed).toBe(false);
+ });
+});
+
+describe('safeMdName (path-traversal guard)', () => {
+ it('accepts a plain .md basename', () => {
+ expect(safeMdName('SOUL.md')).toBe('SOUL.md');
+ expect(safeMdName('My_Doc.MD')).toBe('My_Doc.MD');
+ });
+ it('rejects traversal, nested paths, dotfiles, and non-md', () => {
+ expect(safeMdName('../evil.md')).toBeNull();
+ expect(safeMdName('sub/dir/x.md')).toBeNull();
+ expect(safeMdName('/abs/x.md')).toBeNull();
+ expect(safeMdName('.hidden.md')).toBeNull();
+ expect(safeMdName('notes.txt')).toBeNull();
+ expect(safeMdName(42)).toBeNull();
+ });
+});
diff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.js
index dc504436ee..5ecc207865 100644
--- a/server/services/taste-questionnaire.js
+++ b/server/services/taste-questionnaire.js
@@ -376,6 +376,14 @@ export const TASTE_SECTIONS = {
let profileCache = null;
+// Invalidate the in-memory taste-profile cache. Federation sync writes
+// taste-profile.json directly (see digital-twin-sync.js applyDigitalTwinRemote);
+// without this the no-TTL cache would keep serving pre-sync data until the next
+// local save or a server restart — i.e. synced taste answers wouldn't appear.
+export function invalidateTasteProfileCache() {
+ profileCache = null;
+}
+
async function loadTasteProfile() {
if (profileCache) return profileCache;