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
feat: sync social accounts + analyzed personality traits in the Digital Twin dataset
[._.]/ Adam Eivy27baaabbf3fb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6cbdcaa45b..6b53cd3382 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,8 @@- **[issue-1315] Storyboard shots now record camera framing + screen direction, and a new editorial check catches film-grammar continuity errors before render.** Each storyboard shot gains two film-grammar fields — **shot type** (extreme-wide / wide / medium / close / extreme-close / over-the-shoulder / two-shot / POV) and **screen direction** (the side the subject faces or moves: left / right / neutral) — captured by the scene extractor (the teleplay→scenes prompt now asks the model to tag them) and carried on the shot record. A new deterministic **Storyboard shot continuity** check (Create → Editorial Checks) reads those fields and flags two classic film-grammar mistakes *before* you spend render time on a clip: a **180-degree-rule axis reversal** — a shot that continues from an earlier one but flips the subject to the opposite side of the screen, so they appear to jump sides across the cut — and **shot-type monotony**, a scene whose shots all share one framing and read as flat, slideshow coverage with no establishing wide or punch-in. Findings render as `Continuity` notes anchored to the offending issue + scene, and (being deterministic) need no LLM. Both fields are backward-compatible and default to "not captured," so older storyboards simply aren't flagged until re-extracted; the extraction-prompt change migrates for existing installs (114). Eyeline-match and appearance/prop continuity (which need a vision/LLM pass) and a hard pre-render render-gate are tracked as follow-ups. (`server/lib/shotGrammar.js`, `server/lib/sceneExtractor.js`, `server/lib/editorial/shotContinuity.js`, `server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `scripts/migrations/114-extract-scenes-shot-grammar.js`, #1315)- **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`)+- **Digital Twin federation now syncs your social accounts and analyzed personality traits too.** Two pieces of the identity dataset were still being left behind by peer sync. **Social accounts** (`data/digital-twin/social-accounts.json` — your own GitHub/X/LinkedIn/etc. accounts) were owned by an isolated service and never wired into the snapshot at all, so they never crossed between machines. They now sync as part of the `digitalTwin` category — accounts union by id with LWW on `updatedAt`, so an account added on either machine survives and the more-recently-edited copy wins a collision; the write routes through the owning service's cache-invalidate + change-event so the UI reflects synced accounts immediately. Separately, the **analyzed personality-trait confidence** block in `meta.json` (the Big-Five + values/communication/decision-making/boundaries/identity dimension scores, gaps, and `lastCalculated`) was present in the file but **`mergeMeta` never merged it** — so a machine that had run the trait analysis couldn't share it, and the receiving peer would have had to reprocess from scratch. The confidence block now merges **max-per-dimension** (the scores accumulate monotonically as enrichment answers are processed, so the max loses no analysis from either machine), recomputes `overall` as the mean of the merged dimensions, and carries `gaps`/`lastCalculated` from the more-recently-calculated side. Both merges are additive and key-presence-guarded, so an older peer that sends neither can't blank the local data. (`server/services/digital-twin-sync.js`)+- **[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-1313] Editorial check flags over-stuffed comic panels (lettering density / balloon load).** A new **Comic lettering density / balloon load** check (Create → Editorial Checks) reads each issue's comic script and counts the lettering load the art has to make room for — the #1 reader gripe in comics being a wall of text crammed into one panel. It flags **over-stuffed balloons** (a single balloon past ~25 words), **over-stuffed panels** (more than ~50 words of dialogue + caption + SFX, or more than ~3 balloons fighting for room), and **text-heavy pages** whose total lettering would overwhelm the illustration — all thresholds configurable, with severity scaled by how far over the limit a panel runs and a fix suggestion (split the balloon, move to a caption, or break into another panel). Findings render as `Lettering` notes in the manuscript editor anchored to the issue/page/panel; the same accounting also surfaces **inline in the comic-script stage**, so over-stuffed pages warn you as you edit without waiting for an editorial-checks run. The check is deterministic — no model needed. (`server/lib/editorial/letteringDensity.js`, `server/lib/editorial/checkRegistry.js`, `client/src/lib/letteringDensity.js`, `client/src/components/pipeline/stages/ComicScriptStage.jsx`, #1313)- **[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.jsxindex 3d53df5c62..924e9efd9e 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, taste, documents, autobiography, chronotype, longevity, feedback' },+ { key: 'digitalTwin', label: 'Digital Twin', icon: Fingerprint, description: 'Identity, taste, documents, autobiography, social accounts, personality traits, 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/digital-twin-sync.js b/server/services/digital-twin-sync.jsindex 668d22cc6d..67f8b70af5 100644--- a/server/services/digital-twin-sync.js+++ b/server/services/digital-twin-sync.js@@ -17,11 +17,14 @@* - 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+ * enrichment, fill-missing settings, and the analyzed+ * personality-trait confidence (max per dimension —+ * see mergeConfidence)* - *.md documents — content shipped by filename, ADD-ONLY on the* receiver (a local doc is never overwritten)* - autobiography/ — stories union by id (LWW); config (the prompt* schedule) is NOT synced — it's machine-local+ * - social-accounts.json — the user's own social accounts, union by id (LWW)** 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@@ -46,6 +49,7 @@ 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 SOCIAL_ACCOUNTS_FILE = join(DIR, 'social-accounts.json');// Paths whose fingerprints feed the dataSync checksum cache. The whole// digital-twin dir is watched (two levels deep — covers top-level files, the@@ -216,10 +220,57 @@ function mergeEnrichment(local, remote) {return { merged, changed: JSON.stringify(merged) !== JSON.stringify(l) };}+/**+ * Merge the analyzed personality-trait confidence block (meta.confidence). The+ * per-dimension scores accumulate monotonically as enrichment answers are+ * processed on a machine (digital-twin-enrichment.js boosts then clamps to 1),+ * so the union that loses no analysis is max-per-dimension — mirroring how+ * mergeEnrichment maxes questionsAnswered. `overall` is recomputed as the mean+ * of the merged dimensions (matching the enrichment formula), `lastCalculated`+ * takes the newer stamp, and `gaps` are carried from the more-recently-calculated+ * side (advisory only — a local enrichment answer regenerates them). Key-presence+ * guarded: a peer that sends no confidence can't blank the local analysis.+ */+export function mergeConfidence(local, remote) {+ if (!isPlainObject(remote)) return { merged: local, changed: false };+ if (!isPlainObject(local)) return { merged: remote, changed: true };++ const lDims = isPlainObject(local.dimensions) ? local.dimensions : {};+ const rDims = isPlainObject(remote.dimensions) ? remote.dimensions : {};+ const dimensions = { ...lDims };+ let changed = false;+ for (const [k, rv] of Object.entries(rDims)) {+ if (typeof rv !== 'number') continue;+ const lv = typeof dimensions[k] === 'number' ? dimensions[k] : -Infinity;+ if (rv > lv) { dimensions[k] = rv; changed = true; }+ }++ const dimValues = Object.values(dimensions).filter((v) => typeof v === 'number');+ const overall = dimValues.length+ ? Math.round((dimValues.reduce((a, b) => a + b, 0) / dimValues.length) * 100) / 100+ : 0;++ const localStamp = local.lastCalculated || '';+ const remoteStamp = remote.lastCalculated || '';+ const remoteNewer = remoteStamp > localStamp;+ const gaps = remoteNewer && Array.isArray(remote.gaps) ? remote.gaps+ : Array.isArray(local.gaps) ? local.gaps : [];+ const lastCalculated = remoteNewer ? remoteStamp : localStamp;++ const merged = { ...local, dimensions, overall, gaps, lastCalculated };+ // gaps are derived from dimensions, so the dimension/overall/stamp checks+ // already cover any real change — no separate gaps comparison needed.+ if (!changed) {+ changed = overall !== local.overall || lastCalculated !== (local.lastCalculated || '');+ }+ return { merged, changed };+}+/*** 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).+ * enrichment deep-unions, settings fill missing keys (local values win), and the+ * analyzed personality-trait confidence max-per-dimension.*/export function mergeMeta(local, remote) {if (!isPlainObject(remote)) return { merged: local, changed: false };@@ -251,9 +302,37 @@ export function mergeMeta(local, remote) {}}+ if (isPlainObject(remote.confidence)) {+ const c = mergeConfidence(local.confidence, remote.confidence);+ if (c.changed) { merged.confidence = c.merged; changed = true; }+ }+return { merged, changed };}+/**+ * Merge the user's own social accounts (social-accounts.json: `{ accounts: { id:+ * {...} } }`). Accounts union by id, LWW on updatedAt — an account added on+ * either machine survives, and the more-recently-edited copy wins a collision.+ * Key-presence guarded: a peer that sends no socialAccounts can't blank local.+ */+export function mergeSocialAccounts(local, remote) {+ if (!isPlainObject(remote)) return { merged: local, changed: false };+ if (!isPlainObject(local)) return { merged: remote, changed: true };++ const lAcc = isPlainObject(local.accounts) ? local.accounts : {};+ const rAcc = isPlainObject(remote.accounts) ? remote.accounts : {};+ const accounts = { ...lAcc };+ let changed = false;+ for (const [id, rv] of Object.entries(rAcc)) {+ if (!isPlainObject(rv)) continue;+ const lv = accounts[id];+ if (!isPlainObject(lv)) { accounts[id] = rv; changed = true; continue; }+ if ((rv.updatedAt || '') > (lv.updatedAt || '')) { accounts[id] = rv; changed = true; }+ }+ return { merged: { ...local, accounts }, changed };+}+/*** Merge autobiography stories: union by id (LWW on updatedAt||createdAt), union* usedPrompts. Both outputs are sorted by a stable key — this file feeds the@@ -323,7 +402,7 @@ export async function getDigitalTwinSnapshot() {// lastPromptAt) is deliberately NOT in the snapshot — it is machine-local// scheduling state, and a fresh peer must not inherit another machine's// cadence or have prompts enabled without local opt-in. Only the stories sync.- const [identity, chronotype, longevity, feedback, taste, meta, documents, stories] =+ const [identity, chronotype, longevity, feedback, taste, meta, documents, stories, socialAccounts] =await Promise.all([readJSONFile(IDENTITY_FILE, null),readJSONFile(CHRONOTYPE_FILE, null),@@ -333,8 +412,9 @@ export async function getDigitalTwinSnapshot() {readJSONFile(META_FILE, null),readMarkdownDocuments(),readJSONFile(AUTOBIO_STORIES_FILE, null),+ readJSONFile(SOCIAL_ACCOUNTS_FILE, null),]);- const data = { identity, chronotype, longevity, feedback, taste, meta, documents, autobiography: { stories } };+ const data = { identity, chronotype, longevity, feedback, taste, meta, documents, autobiography: { stories }, socialAccounts };return { data, checksum: computeChecksum(data) };}@@ -397,6 +477,21 @@ async function applyMeta(remoteMeta) {return 1;}+// Route through socialAccounts.js's own load/save (mirrors applyMeta) so the+// service's cache stays fresh — a raw write would leave the UI serving pre-sync+// data until the store's TTL lapses. saveAccounts updates the cache in place;+// notifyChanged emits the change event so the Digital Twin UI updates at once.+async function applySocialAccounts(remoteSocial) {+ if (!isPlainObject(remoteSocial)) return 0;+ const { loadAccounts, saveAccounts, notifyChanged } = await import('./socialAccounts.js');+ const local = await loadAccounts();+ const { merged, changed } = mergeSocialAccounts(local, remoteSocial);+ if (!changed) return 0;+ await saveAccounts(merged);+ notifyChanged('sync');+ return 1;+}+export async function applyDigitalTwinRemote(remoteData) {if (!isPlainObject(remoteData)) return { applied: false, count: 0 };@@ -420,6 +515,8 @@ export async function applyDigitalTwinRemote(remoteData) {count += await applyMerge(AUTOBIO_STORIES_FILE, remoteData.autobiography.stories, mergeAutobiographyStories, { dir: AUTOBIO_DIR });}+ count += await applySocialAccounts(remoteData.socialAccounts);+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.jsindex 8db75fdf2c..1655606d0b 100644--- a/server/services/digital-twin-sync.test.js+++ b/server/services/digital-twin-sync.test.js@@ -5,6 +5,8 @@ import {unionByKey,mergeTaste,mergeMeta,+ mergeConfidence,+ mergeSocialAccounts,mergeAutobiographyStories,safeMdName,} from './digital-twin-sync.js';@@ -214,6 +216,90 @@ describe('mergeAutobiographyStories', () => {});});+describe('mergeConfidence (analyzed personality traits)', () => {+ it('takes remote when local is missing/invalid', () => {+ const remote = { dimensions: { openness: 0.6 }, overall: 0.6, gaps: [], lastCalculated: '2026-02-01' };+ expect(mergeConfidence(null, remote)).toEqual({ merged: remote, changed: true });+ expect(mergeConfidence(undefined, remote).changed).toBe(true);+ });++ it('keeps local and reports no change when remote is missing/empty', () => {+ const local = { dimensions: { openness: 0.6 }, overall: 0.6, gaps: [], lastCalculated: '2026-02-01' };+ expect(mergeConfidence(local, null).changed).toBe(false);+ expect(mergeConfidence(local, undefined).merged).toBe(local);+ });++ it('maxes each dimension so no machine\'s analysis is lost', () => {+ const local = { dimensions: { openness: 0.8, extraversion: 0.2 }, overall: 0.5, gaps: [], lastCalculated: '2026-01-01' };+ const remote = { dimensions: { openness: 0.4, conscientiousness: 0.9 }, overall: 0.65, gaps: [], lastCalculated: '2026-02-01' };+ const { merged, changed } = mergeConfidence(local, remote);+ expect(merged.dimensions).toEqual({ openness: 0.8, extraversion: 0.2, conscientiousness: 0.9 });+ expect(changed).toBe(true);+ });++ it('recomputes overall as the mean of merged dimensions (2dp)', () => {+ const local = { dimensions: { a: 0.2 }, overall: 0.2, lastCalculated: '2026-01-01' };+ const remote = { dimensions: { a: 0.6, b: 0.9 }, overall: 0.75, lastCalculated: '2026-02-01' };+ const { merged } = mergeConfidence(local, remote);+ // dims merge to { a: 0.6, b: 0.9 } → mean 0.75+ expect(merged.overall).toBe(0.75);+ });++ it('carries gaps + lastCalculated from the more-recently-calculated side', () => {+ const local = { dimensions: { a: 0.5 }, gaps: [{ dimension: 'a' }], lastCalculated: '2026-01-01' };+ const remote = { dimensions: { a: 0.5 }, gaps: [{ dimension: 'b' }], lastCalculated: '2026-02-01' };+ const { merged } = mergeConfidence(local, remote);+ expect(merged.gaps).toEqual([{ dimension: 'b' }]);+ expect(merged.lastCalculated).toBe('2026-02-01');+ });+});++describe('mergeMeta wires confidence', () => {+ it('brings over a peer\'s analyzed traits into a fresh local meta', () => {+ const local = { documents: [], confidence: { dimensions: {}, overall: 0, gaps: [], lastCalculated: '' } };+ const remote = { documents: [], confidence: { dimensions: { openness: 0.7 }, overall: 0.7, gaps: [], lastCalculated: '2026-03-01' } };+ const { merged, changed } = mergeMeta(local, remote);+ expect(changed).toBe(true);+ expect(merged.confidence.dimensions.openness).toBe(0.7);+ expect(merged.confidence.lastCalculated).toBe('2026-03-01');+ });++ it('does not blank local confidence when the peer sends none', () => {+ const local = { documents: [], confidence: { dimensions: { openness: 0.7 }, overall: 0.7, lastCalculated: '2026-03-01' } };+ const { merged } = mergeMeta(local, { documents: [] });+ expect(merged.confidence.dimensions.openness).toBe(0.7);+ });+});++describe('mergeSocialAccounts', () => {+ it('takes remote when local is missing/invalid', () => {+ const remote = { accounts: { a1: { platform: 'github', updatedAt: '2026-01-01' } } };+ expect(mergeSocialAccounts(null, remote)).toEqual({ merged: remote, changed: true });+ });++ it('keeps local and reports no change when remote is missing', () => {+ const local = { accounts: { a1: { platform: 'github' } } };+ expect(mergeSocialAccounts(local, null).changed).toBe(false);+ });++ it('unions accounts by id, keeping each side\'s unique entries', () => {+ const local = { accounts: { a1: { platform: 'github', updatedAt: '2026-01-01' } } };+ const remote = { accounts: { a2: { platform: 'x', updatedAt: '2026-01-02' } } };+ const { merged, changed } = mergeSocialAccounts(local, remote);+ expect(Object.keys(merged.accounts).sort()).toEqual(['a1', 'a2']);+ expect(changed).toBe(true);+ });++ it('LWW on a shared account by updatedAt', () => {+ const local = { accounts: { a1: { username: 'old', updatedAt: '2026-01-01' } } };+ const remote = { accounts: { a1: { username: 'new', updatedAt: '2026-02-01' } } };+ expect(mergeSocialAccounts(local, remote).merged.accounts.a1.username).toBe('new');+ const older = { accounts: { a1: { username: 'older', updatedAt: '2025-12-01' } } };+ expect(mergeSocialAccounts(local, older).merged.accounts.a1.username).toBe('old');+ expect(mergeSocialAccounts(local, older).changed).toBe(false);+ });+});+describe('safeMdName (path-traversal guard)', () => {it('accepts a plain .md basename', () => {expect(safeMdName('SOUL.md')).toBe('SOUL.md');diff --git a/server/services/socialAccounts.js b/server/services/socialAccounts.jsindex 7bf32f1b5a..956781e54f 100644--- a/server/services/socialAccounts.js+++ b/server/services/socialAccounts.js@@ -121,8 +121,11 @@ export const PLATFORMS = {}};-const loadAccounts = store.load;-const saveAccounts = store.save;+// Exported so the digital-twin peer-sync (digital-twin-sync.js) can read/merge/+// write social accounts through the owning service — keeping the cache fresh and+// any future save hooks intact rather than writing the file out from under it.+export const loadAccounts = store.load;+export const saveAccounts = store.save;export const invalidateCache = store.invalidateCache;export function notifyChanged(action = 'update', accountId = null) {