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

address review: alias-aware characters-bucket fold; allow kind upgrade from other; abort save on refetch fail; import migration hash tables in test

[._.]/ Adam Eivy0cf2e87c1fdb
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 19b489692a..f8138100c6 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -508,19 +508,27 @@ export default function UniverseBuilder() {
// 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 the refetch fails for an existing universe, abort the save entirely:
+ // falling back to the stale draft would replace the server's canon wholesale
+ // and could undo concurrent canon edits/deletions in other tabs.
if (selectedId) {
const fresh = await getUniverse(selectedId).catch(() => null);
- if (fresh) {
- const additions = pendingCanonAdditionsRef.current;
- baseCanon = {
- characters: mergeCanonByName(fresh.characters || [], additions.characters, 'character'),
- settings: mergeCanonByName(fresh.settings || [], additions.settings, 'setting'),
- objects: mergeCanonByName(fresh.objects || [], additions.objects, 'object'),
- };
+ if (!fresh) {
+ setSaving(false);
+ toast.error('Save failed: could not fetch latest canon — please try again');
+ return;
}
+ const additions = pendingCanonAdditionsRef.current;
+ const baseCanon = {
+ characters: mergeCanonByName(fresh.characters || [], additions.characters, 'character'),
+ settings: mergeCanonByName(fresh.settings || [], additions.settings, 'setting'),
+ objects: mergeCanonByName(fresh.objects || [], additions.objects, 'object'),
+ };
+ payload = { ...basePayload, ...baseCanon };
+ } else {
+ const baseCanon = { characters: draft.characters || [], settings: draft.settings || [], objects: draft.objects || [] };
+ payload = { ...basePayload, ...baseCanon };
}
- payload = { ...basePayload, ...baseCanon };
}
const result = selectedId
? await updateUniverse(selectedId, payload).catch((e) => { toast.error(`Save failed: ${e.message}`); return null; })
@@ -629,12 +637,18 @@ export default function UniverseBuilder() {
const locked = preservedVariations[cat] || [];
const fresh = (llmCategories[cat]?.variations || []);
// Preserve the bucket's `kind` so the category-to-canon-trunk contract
- // survives the round-trip. Precedence: existing draft kind (the user
- // may have curated it) → LLM-returned kind for this bucket → undefined
- // (server's sanitizeCategory then falls back to the default-map / 'other').
+ // survives the round-trip. Precedence:
+ // - existing non-'other' draft kind (user curated it to a specific trunk)
+ // - LLM-returned kind for this expand round (fresh classification)
+ // - existing 'other' draft kind (Phase-B default for custom buckets)
+ // - undefined (server's sanitizeCategory falls back to default-map / 'other')
+ // Allowing a fresh LLM kind to supersede an existing 'other' is intentional:
+ // pre-Phase-B "factions" buckets saved as `other` can be promoted to
+ // `characters` by a re-expand without requiring the user to manually change
+ // the trunk. User-curated non-`other` kinds (e.g. `settings`) are preserved.
const existingKind = draft.categories?.[cat]?.kind;
const freshKind = llmCategories[cat]?.kind;
- const kind = existingKind || freshKind;
+ const kind = (existingKind && existingKind !== 'other') ? existingKind : (freshKind || existingKind);
mergedCategories[cat] = {
...(kind ? { kind } : {}),
variations: mergeVariations(locked, fresh),
@@ -740,9 +754,13 @@ export default function UniverseBuilder() {
// (both disabled on `saving`) can't double-fire during the
// getUniverse await window below.
setSaving(true);
- // For updates: refetch the server's canon and merge in the local
- // additions so a concurrent canon edit (Nouns stage, another tab)
- // landing during the LLM call isn't wholesale-clobbered.
+ // For updates: refetch the server's canon and merge in ONLY the local
+ // additions ledger so a concurrent canon edit (Nouns stage, another tab)
+ // landing during the LLM call isn't wholesale-clobbered. If the refetch
+ // fails for an existing record, skip the auto-save (mark canonDirty so
+ // the user can retry via manual Save) rather than falling back to the
+ // stale draft, which would replace the server's canon wholesale and undo
+ // any concurrent deletions/edits.
let canonForPayload = {
characters: expandedDraft.characters || [],
settings: expandedDraft.settings || [],
@@ -750,17 +768,29 @@ export default function UniverseBuilder() {
};
if (selectedId) {
const fresh = await getUniverse(selectedId).catch(() => null);
- if (fresh) {
- canonForPayload = {
- // 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'),
- };
+ if (!fresh) {
+ // Refetch failed — skip auto-save for this update to avoid a stale
+ // canon write. The new entries are already in the draft and the
+ // canonDirty flag is already set, so the user's manual Save will
+ // retry the refetch+merge path.
+ setSaving(false);
+ toast.success(expandToast({
+ variationCount: total,
+ sheetCount: expandedDraft.compositeSheets?.length || 0,
+ addedCanonCount,
+ saved: false,
+ }));
+ return;
}
+ canonForPayload = {
+ // 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'),
+ };
}
const payload = {
name: expandedDraft.name.trim(),
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.js
index ce6044f97a..c35fab86f2 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js
@@ -41,7 +41,9 @@ const md5 = (str) => {
// Hashes the file may have on disk pre-migration (per-file array — most
// recent shipped hash first, then older). Any match is treated as
// "unmodified by user → safe to replace."
-const ACCEPTED_OLD_MD5 = {
+// Exported so the test suite can import these tables and detect drift without
+// maintaining local copies that can silently fall out of sync.
+export const ACCEPTED_OLD_MD5 = {
'pipeline-arc-overview.md': [
'd34d72b8e49ba303d38607845dd87f1c', // current (pre-Phase B) shipped
'6a3ecab43d1f46b7ef9aab6c69ea0326', // pre-005 (shape-aware), still in setup-data.js OLD list
@@ -61,7 +63,9 @@ const ACCEPTED_OLD_MD5 = {
};
// New shipped hashes — what data.sample carries post-migration.
-const NEW_SHIPPED_MD5 = {
+// Exported so the test suite can import and assert against these tables
+// directly rather than maintaining local copies.
+export const NEW_SHIPPED_MD5 = {
'pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0',
'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c',
'pipeline-arc-resolve.md': '8e348f3d1894382889f9f0ee7d5c6792',
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.test.js b/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
index 9ee6ad1263..9fe60dcb07 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
@@ -12,39 +12,12 @@ import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { createHash } from 'crypto';
-import migration, { applyMigration } from './019-arc-volume-prompts-canon-context.js';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './019-arc-volume-prompts-canon-context.js';
const md5 = (str) => createHash('md5')
.update(str.replace(/\r\n/g, '\n').replace(/\r/g, '\n'))
.digest('hex');
-// Mirror of the migration's hash table — when these change the test fixtures
-// below need to mirror the change too.
-const ACCEPTED_OLD_MD5 = {
- 'pipeline-arc-overview.md': [
- 'd34d72b8e49ba303d38607845dd87f1c',
- '6a3ecab43d1f46b7ef9aab6c69ea0326',
- ],
- 'pipeline-arc-verify.md': [
- 'ff56d8387162017e08d5d0491060ddd6',
- '52e31abc93e3105176236fcaa5d1575a',
- ],
- 'pipeline-arc-resolve.md': [
- 'a8677bbe1eb38f871fb152a5b0fec7c6',
- '87bc5c01f1a8a97b681727a38b05edc6',
- ],
- 'pipeline-volume-verify.md': [
- '03f3c874cb80e1c98abcf03168fa7a92',
- 'c6ea28e972ad6e229bafb2d602b4dda3',
- ],
-};
-const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0',
- 'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c',
- 'pipeline-arc-resolve.md': '8e348f3d1894382889f9f0ee7d5c6792',
- 'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',
-};
-
// Lookup the real data.sample file for a given prompt; used to seed
// fixtures and to compute "current" file bodies for round-trip checks.
// Use fileURLToPath rather than `new URL(...).pathname` so a checkout under
@@ -95,7 +68,16 @@ describe('migration 019 — arc/volume prompt canon context', () => {
const before = Object.fromEntries(
Object.keys(NEW_SHIPPED_MD5).map((f) => [f, readFileSync(join(stagesDir, f), 'utf-8')]),
);
- await migration.up({ rootDir });
+ // Use applyMigration with the migration's real tables (imported, not local
+ // copies) so drift in the migration's hash constants is caught here — if
+ // NEW_SHIPPED_MD5 no longer matches data.sample, applyMigration reports
+ // skipped > 0 instead of alreadyCurrent, and this assertion fails.
+ const result = await applyMigration({ rootDir });
+ expect(result).toMatchObject({
+ updated: 0,
+ alreadyCurrent: Object.keys(NEW_SHIPPED_MD5).length,
+ skipped: 0,
+ });
for (const filename of Object.keys(NEW_SHIPPED_MD5)) {
const after = readFileSync(join(stagesDir, filename), 'utf-8');
expect(after).toBe(before[filename]); // unchanged
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index db315dfbca..6a1fb31884 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -449,14 +449,16 @@ function foldRetiredCharactersBucket(raw, canon) {
const categories = raw && raw.categories && typeof raw.categories === 'object'
? raw.categories
: {};
- // 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.
+ // Match ANY key whose first word is "character(s)" — covers exact match
+ // ("characters"), case variants ("Characters"), and multi-word aliases
+ // ("character variations", "Character_Variations") that normalizeCategoryKey
+ // encodes as "character_variations" (not equal to the literal "characters").
+ // Without this, a payload using those variant keys slips past the exact check
+ // and has its variations silently dropped on save instead of folded into canon.
+ const isCharactersBucket = (k) => /^characters?(_|$)/i.test(normalizeCategoryKey(k));
let variations = null;
for (const [rawKey, value] of Object.entries(categories)) {
- if (normalizeCategoryKey(rawKey) !== 'characters') continue;
+ if (!isCharactersBucket(rawKey)) continue;
const fromKey = Array.isArray(value)
? value
: Array.isArray(value?.variations)
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 8e22e83c9a..623c9161ae 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -435,15 +435,18 @@ export async function expandWorldTemplate({
// instead of being silently dropped on auto-save round-trip.
const rawCategories = parsed.categories && typeof parsed.categories === 'object' ? parsed.categories : {};
let rawCharacters = Array.isArray(parsed.characters) ? [...parsed.characters] : [];
- // 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.
+ // Match ANY raw key whose first word is "character(s)" — covers exact
+ // ("characters"), case variants ("Characters"), and multi-word aliases
+ // ("character variations", "Character_Variations") that normalizeCategoryKey
+ // encodes as "character_variations" (i.e. NOT equal to "characters").
+ // Without this, an LLM emitting a slightly renamed retired-characters key
+ // would slip past the exact-equality check and have its entries dropped by
+ // sanitizeCategories on save instead of folding into canon.
+ const isCharactersBucket = (rawKey) => /^characters?(_|$)/i.test(normalizeCategoryKey(rawKey));
const survivingCategories = {};
let foldedAnything = false;
for (const [rawKey, value] of Object.entries(rawCategories)) {
- if (normalizeCategoryKey(rawKey) === 'characters') {
+ if (isCharactersBucket(rawKey)) {
const variations = Array.isArray(value)
? value
: Array.isArray(value?.variations)