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
address review: canon additions ledger so concurrent deletions aren't reverted; normalize keys when folding retired characters bucket; fileURLToPath for path safety; corrected vitest glob comment
[._.]/ Adam Eivy28d88dc1ea7a
diff --git a/PLAN.md b/PLAN.mdindex f8c619b41c..e58dce75df 100644--- a/PLAN.md+++ b/PLAN.md@@ -83,7 +83,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]- [ ] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.- [x] ~~**Auto-save after expand can clobber concurrent canon edits.**~~ **Fixed in Phase B Copilot iteration 13** — both `handleExpand`'s auto-save and `handleSave`'s manual-save (when `canonDirty`) now refetch the server's canon via `getUniverse(selectedId)` and merge local additions with `mergeCanonByName` before the update payload is sent. Concurrent edits from NounsStage/other tabs are preserved on identity collision.-- [ ] **Canon-merge can revert concurrent deletions/renames.** `UniverseBuilder.jsx` (handleSave + handleExpand auto-save) currently merges the FULL stale draft canon onto the refetched server canon — which protects against losing local additions but ALSO re-adds entries another tab deleted (because `mergeCanonByName` dedupes by name, the deleted entry is "preserved" from the stale draft). Real fix: track JUST the merged-from-expand additions in a sidecar set, merge only those onto the refetched server canon. Deferred from Phase B Copilot iteration 14 — needs a per-expand additions ledger.+- [x] ~~**Canon-merge can revert concurrent deletions/renames.**~~ **Fixed in Phase B Copilot iteration 15** — handleExpand records each merge's NEW canon entries in a `pendingCanonAdditionsRef` sidecar; handleSave + handleExpand auto-save + handleCanonChange now merge ONLY that ledger onto the refetched server canon (not the full stale draft). Concurrent deletions in other tabs/surfaces are preserved because the deleted entry isn't in the ledger, so the server response (which already lacks it) wins.- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`.** `MediaLightbox` swipe nav; clipboard inlined across 8+ call sites. Clipboard can move now.- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.- [ ] **`useAsyncAction` post-unmount setState guard.** Add `mountedRef` to gate `setRunning(false)`. YAGNI today; do at 4th consumer.diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 8b0164eb00..19b489692a 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -330,6 +330,17 @@ export default function UniverseBuilder() {// merged entries actually persist. Cleared on successful save and on// universe-switch (the new draft's canon is loaded from server, in sync).const [canonDirty, setCanonDirty] = useState(false);+ // Sidecar ledger of the EXACT canon entries the last expand merged into+ // the draft but haven't been persisted yet. On save, only these entries+ // are merged onto the refetched server canon — NOT the full stale draft.+ // That avoids resurrecting entries another tab/surface deleted: a deletion+ // wins because our ledger doesn't contain it, so the refetched canon+ // (which already lacks the deleted entry) is the final state. Cleared on+ // successful save and on universe-switch.+ const pendingCanonAdditionsRef = useRef({ characters: [], settings: [], objects: [] });+ const clearPendingCanonAdditions = () => {+ pendingCanonAdditionsRef.current = { characters: [], settings: [], objects: [] };+ };// Per-page render knobs. Persisted to localStorage so the user's// preferred batch size sticks across visits.@@ -403,6 +414,7 @@ export default function UniverseBuilder() {setPendingDeleteId(null);resetRefinePanel();setCanonDirty(false);+ clearPendingCanonAdditions();if (!selectedId) {setDraft(emptyTemplate());setRuns([]);@@ -492,14 +504,19 @@ export default function UniverseBuilder() {const needsCanonInPayload = !selectedId || canonDirty;let payload = basePayload;if (needsCanonInPayload) {+ // For create: send the draft's canon as-is (the new universe starts empty).+ // For update with canonDirty: refetch + merge ONLY the pending-additions+ // ledger (not the full stale draft) so concurrent deletions in other+ // tabs aren't resurrected.let baseCanon = { characters: draft.characters || [], settings: draft.settings || [], objects: draft.objects || [] };if (selectedId) {const fresh = await getUniverse(selectedId).catch(() => null);if (fresh) {+ const additions = pendingCanonAdditionsRef.current;baseCanon = {- characters: mergeCanonByName(fresh.characters || [], draft.characters || [], 'character'),- settings: mergeCanonByName(fresh.settings || [], draft.settings || [], 'setting'),- objects: mergeCanonByName(fresh.objects || [], draft.objects || [], 'object'),+ characters: mergeCanonByName(fresh.characters || [], additions.characters, 'character'),+ settings: mergeCanonByName(fresh.settings || [], additions.settings, 'setting'),+ objects: mergeCanonByName(fresh.objects || [], additions.objects, 'object'),};}}@@ -512,8 +529,12 @@ export default function UniverseBuilder() {if (result) {// Save persisted whatever canon was in the payload; clear the dirty// flag so the next save can resume the "skip canon to avoid clobber"- // path. No-op if it was already false.- if (needsCanonInPayload) setCanonDirty(false);+ // path. No-op if it was already false. Also drain the pending-additions+ // ledger since those entries are now on the server.+ if (needsCanonInPayload) {+ setCanonDirty(false);+ clearPendingCanonAdditions();+ }toast.success(selectedId ? 'World updated' : 'World created');setWorlds((prev) => {const without = prev.filter((w) => w.id !== result.id);@@ -675,7 +696,27 @@ export default function UniverseBuilder() {setDraft(expandedDraft);// Flag the merged-but-not-yet-persisted canon so a subsequent manual// Save (if auto-save fails or is bypassed) includes the new entries.- if (addedCanonCount > 0) setCanonDirty(true);+ // Record exactly which entries we added (vs. what was already in the+ // draft) so the save-time merge only re-applies the new ones, not the+ // full stale draft.+ if (addedCanonCount > 0) {+ setCanonDirty(true);+ const computeAdditions = (existing, merged) => {+ const norm = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');+ const existingNames = new Set((existing || []).map((e) => norm(e?.name)).filter(Boolean));+ const existingSluglines = new Set((existing || []).map((e) => norm(e?.slugline)).filter(Boolean));+ return (merged || []).filter((e) => {+ const n = norm(e?.name);+ const s = norm(e?.slugline);+ return !(n && existingNames.has(n)) && !(s && existingSluglines.has(s));+ });+ };+ pendingCanonAdditionsRef.current = {+ characters: [...pendingCanonAdditionsRef.current.characters, ...computeAdditions(draft.characters, mergedCharacters)],+ settings: [...pendingCanonAdditionsRef.current.settings, ...computeAdditions(draft.settings, mergedSettings)],+ objects: [...pendingCanonAdditionsRef.current.objects, ...computeAdditions(draft.objects, mergedObjects)],+ };+ }const lockedKeys = Object.keys(locks).filter((k) => locks[k]);if (lockedKeys.length) {console.log(`🔒 Universe Builder expand preserved ${lockedKeys.length} locked field(s): ${lockedKeys.join(', ')}`);@@ -711,9 +752,13 @@ export default function UniverseBuilder() {const fresh = await getUniverse(selectedId).catch(() => null);if (fresh) {canonForPayload = {- characters: mergeCanonByName(fresh.characters || [], expandedDraft.characters || [], 'character'),- settings: mergeCanonByName(fresh.settings || [], expandedDraft.settings || [], 'setting'),- objects: mergeCanonByName(fresh.objects || [], expandedDraft.objects || [], 'object'),+ // Merge ONLY pending additions onto refetched server canon+ // (not the full stale draft). Without this, concurrent canon+ // deletions in other tabs/surfaces get resurrected because the+ // deleted entry is still present in the stale draft.+ characters: mergeCanonByName(fresh.characters || [], pendingCanonAdditionsRef.current.characters, 'character'),+ settings: mergeCanonByName(fresh.settings || [], pendingCanonAdditionsRef.current.settings, 'setting'),+ objects: mergeCanonByName(fresh.objects || [], pendingCanonAdditionsRef.current.objects, 'object'),};}}@@ -744,8 +789,10 @@ export default function UniverseBuilder() {});// Auto-save succeeded — server now has the merged canon, so a// subsequent manual Save shouldn't re-send it (avoids the- // concurrent-edit clobber).+ // concurrent-edit clobber). Drain the additions ledger too since+ // those entries are now on the server.setCanonDirty(false);+ clearPendingCanonAdditions();// New record: route to its id so the canon section gates flip and// subsequent draft state reflects the persisted record.if (!selectedId) goToWorld(saved.id);@@ -937,17 +984,17 @@ export default function UniverseBuilder() {if (!updated) return;setDraft((d) => {// If a prior expand merged canon that hasn't been persisted yet,- // mergeCanonByName the local entries against the server's response so- // those pending additions aren't wholesale-replaced when a canon UI- // action lands. mergeCanonByName preserves identity dedupe (name +- // slugline + aliases) so a duplicate isn't created if the server- // happens to already have one.+ // mergeCanonByName ONLY the pending additions (not the full stale+ // draft) against the server's response. Using the additions ledger+ // means concurrent canon deletions (which the server's response+ // already reflects) win — pending additions are still preserved.if (canonDirty) {+ const additions = pendingCanonAdditionsRef.current;return {...d,- characters: mergeCanonByName(updated.characters || [], d.characters || [], 'character'),- settings: mergeCanonByName(updated.settings || [], d.settings || [], 'setting'),- objects: mergeCanonByName(updated.objects || [], d.objects || [], 'object'),+ characters: mergeCanonByName(updated.characters || [], additions.characters, 'character'),+ settings: mergeCanonByName(updated.settings || [], additions.settings, 'setting'),+ objects: mergeCanonByName(updated.objects || [], additions.objects, 'object'),updatedAt: updated.updatedAt,};}diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.test.js b/scripts/migrations/019-arc-volume-prompts-canon-context.test.jsindex cdd6c38ae9..9ee6ad1263 100644--- a/scripts/migrations/019-arc-volume-prompts-canon-context.test.js+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.test.js@@ -8,7 +8,8 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';import { tmpdir } from 'os';-import { join } from 'path';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';import { createHash } from 'crypto';import migration, { applyMigration } from './019-arc-volume-prompts-canon-context.js';@@ -46,7 +47,9 @@ const NEW_SHIPPED_MD5 = {// Lookup the real data.sample file for a given prompt; used to seed// fixtures and to compute "current" file bodies for round-trip checks.-const repoRoot = join(import.meta.dirname || new URL('.', import.meta.url).pathname, '..', '..');+// Use fileURLToPath rather than `new URL(...).pathname` so a checkout under+// a path with spaces (or other URL-escapable chars) decodes correctly.+const repoRoot = join(import.meta.dirname || dirname(fileURLToPath(import.meta.url)), '..', '..');const sampleBody = (filename) =>readFileSync(join(repoRoot, 'data.sample', 'prompts', 'stages', filename), 'utf-8');diff --git a/scripts/run-migrations.js b/scripts/run-migrations.jsindex feb24f15cd..f8d5343711 100644--- a/scripts/run-migrations.js+++ b/scripts/run-migrations.js@@ -49,7 +49,8 @@ export async function runMigrations({// Scan for migration files (*.js, sorted by filename). Co-located vitest// files (*.test.js) are excluded — they don't export `up()` and would// throw the runner if imported as migrations. The vitest config picks- // them up via its own glob (`../scripts/migrations/**\/*.test.js`).+ // them up via its own glob (`../scripts/**/*.test.js` in+ // server/vitest.config.js).const files = (await readdir(migrationsDir)).filter(f => f.endsWith('.js') && !f.endsWith('.test.js')).sort();diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 2f99d71145..db315dfbca 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -449,12 +449,22 @@ function foldRetiredCharactersBucket(raw, canon) {const categories = raw && raw.categories && typeof raw.categories === 'object'? raw.categories: {};- const charBucket = categories.characters;- const variations = Array.isArray(charBucket)- ? charBucket- : Array.isArray(charBucket?.variations)- ? charBucket.variations- : null;+ // Match ANY key that normalizes to `characters` — sanitizeCategories runs+ // normalizeCategoryKey on each key before dropping retired buckets, so a+ // payload using `Characters` or `character variations` would otherwise+ // slip past the literal `categories.characters` lookup and have its+ // variations silently dropped on save instead of folded into canon.+ let variations = null;+ for (const [rawKey, value] of Object.entries(categories)) {+ if (normalizeCategoryKey(rawKey) !== 'characters') continue;+ const fromKey = Array.isArray(value)+ ? value+ : Array.isArray(value?.variations)+ ? value.variations+ : null;+ if (!fromKey) continue;+ variations = variations ? [...variations, ...fromKey] : fromKey;+ }if (!variations) return canon;const next = {characters: Array.isArray(canon.characters) ? [...canon.characters] : [],diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.jsindex 52388d015c..8e22e83c9a 100644--- a/server/services/universeBuilderExpand.js+++ b/server/services/universeBuilderExpand.js@@ -24,6 +24,7 @@ import {PREMISE_MAX,STYLE_NOTES_MAX,isInfluenceLockField,+ normalizeCategoryKey,sanitizeCategories,sanitizeCompositeSheets,sanitizeInfluences,@@ -433,29 +434,39 @@ export async function expandWorldTemplate({// characters[] return before normalizing, so the entries land in canon// instead of being silently dropped on auto-save round-trip.const rawCategories = parsed.categories && typeof parsed.categories === 'object' ? parsed.categories : {};- const retiredCharBucket = rawCategories.characters;let rawCharacters = Array.isArray(parsed.characters) ? [...parsed.characters] : [];- // Accept both shapes normalizeCategories accepts: object with `variations`- // OR raw array. Without the raw-array branch, an LLM emitting- // `categories: { characters: ["Ash", ...] }` would have its entries dropped- // by sanitizeCategories on save instead of folding into canon.- const retiredVariations = Array.isArray(retiredCharBucket)- ? retiredCharBucket- : Array.isArray(retiredCharBucket?.variations)- ? retiredCharBucket.variations- : null;- if (retiredVariations) {- for (const v of retiredVariations) {- if (typeof v === 'string') {- const trimmed = v.trim();- if (trimmed) rawCharacters.push({ name: trimmed });- continue;+ // Match ANY raw key that normalizes to `characters` (e.g. "Characters",+ // "character variations", "Character_Variations"). Without this, an LLM+ // emitting a slightly different key would slip past the literal lookup+ // and have its entries dropped by sanitizeCategories on save instead of+ // folding into canon.+ const survivingCategories = {};+ let foldedAnything = false;+ for (const [rawKey, value] of Object.entries(rawCategories)) {+ if (normalizeCategoryKey(rawKey) === 'characters') {+ const variations = Array.isArray(value)+ ? value+ : Array.isArray(value?.variations)+ ? value.variations+ : null;+ if (variations) {+ for (const v of variations) {+ if (typeof v === 'string') {+ const trimmed = v.trim();+ if (trimmed) rawCharacters.push({ name: trimmed });+ continue;+ }+ if (!v || typeof v !== 'object' || !v.label) continue;+ rawCharacters.push({ name: v.label, prompt: v.prompt });+ }+ foldedAnything = true;+ continue; // drop the bucket from the surviving categories}- if (!v || typeof v !== 'object' || !v.label) continue;- rawCharacters.push({ name: v.label, prompt: v.prompt });}- const { characters: _drop, ...rest } = rawCategories;- parsed.categories = rest;+ survivingCategories[rawKey] = value;+ }+ if (foldedAnything) {+ parsed.categories = survivingCategories;}const categories = normalizeCategories(parsed.categories || {});const compositeSheets = normalizeCompositeSheets(