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: import Markdown into universe pages
[._.]/ Adam Eivy26fd41f87414
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsxindex 4a2e5b857d..d0fa0e424c 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx@@ -12,12 +12,13 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link, useLocation, useParams } from 'react-router';import {ArrowLeft, BookOpen, FolderTree, ImagePlus, Layers, Loader2,- MapPin, Network, Package, Plus, Save, Trash2, Users,+ MapPin, Network, Package, Plus, Save, Trash2, Upload, Users,} from 'lucide-react';import InlineConfirmRow from '../ui/InlineConfirmRow';import toast from '../ui/Toast';import {exportUniverseMarkdown,+ importUniverseMarkdown,waitForUniverseWrites,WORLD_CATEGORY_KEY_MAX,} from '../../services/api';@@ -29,6 +30,7 @@ import { useUniverseNav } from '../../hooks/useUniverseNav';import useUniverseRender from '../../hooks/useUniverseRender';import useUniverseTabs from '../../hooks/useUniverseTabs';import EntityCombobox from '../EntityCombobox';+import FilePickerButton from '../ui/FilePickerButton';import MediaPreview from '../media/MediaPreview';import OriginBadge from '../sharing/OriginBadge';import ShareToButton from '../sharing/ShareToButton';@@ -43,6 +45,8 @@ import { appendImageRefById } from '../../lib/bibleLimits';import { downloadBlob } from '../../lib/downloadBlob';import { totalVariationCount } from '../../lib/universeBuilderCounts';import { universeMarkdownFilename } from '../../lib/universeMarkdownFilename';+import { ensureDraftCategories } from '../../lib/universeBuilderShared';+import { parseUniverseMarkdown } from '../../../../server/lib/universeMarkdown.js';import {TAB_BIBLE,TAB_CAST,@@ -113,6 +117,7 @@ export default function UniverseBuilder() {const selectedIdRef = useRef(selectedId);selectedIdRef.current = selectedId;const [exporting, setExporting] = useState(false);+ const [importing, setImporting] = useState(false);const [waitingForWrites, setWaitingForWrites] = useState(false);// `goToWorld` preserves `location.search` (e.g. `?tab=&bucket=&series=`) so// the auto-save → create path doesn't snap the user back to the Bible tab@@ -277,6 +282,81 @@ export default function UniverseBuilder() {toast.success(`Downloaded ${filename}`);}, [draft.name, draftRef, exporting, flushDraftIfDirty, saving, selectedId]);+ const handleImportMarkdown = useCallback(async (event) => {+ const file = event.currentTarget.files?.[0];+ const importIsReady = () => mountedRef.current+ && selectedIdRef.current === selectedId+ && draftRef.current?.id === selectedId;+ if (!file || !selectedId || importing || saving || !importIsReady()) return;+ setImporting(true);+ try {+ if (file.size > 10_000_000) throw new Error('Markdown files must be 10 MB or smaller');+ const markdown = await file.text();+ // Validate before flushing a dirty draft so a wrong file never saves+ // unrelated edits as a side effect of a failed import.+ parseUniverseMarkdown(markdown);+ if (!importIsReady()) return;++ setWaitingForWrites(true);+ const writesReady = await waitForUniverseWrites(selectedId);+ setWaitingForWrites(false);+ if (!writesReady) {+ toast.error('Changes are still saving — try the import again in a moment');+ return;+ }+ if (!importIsReady()) return;++ const flushed = await flushDraftIfDirty();+ if (!flushed || !importIsReady()) return;+ setWaitingForWrites(true);+ const flushedWritesReady = await waitForUniverseWrites(selectedId);+ setWaitingForWrites(false);+ if (!flushedWritesReady) {+ toast.error('Changes are still saving — try the import again in a moment');+ return;+ }+ if (!importIsReady()) return;++ const result = await importUniverseMarkdown(selectedId, markdown, { silent: true });+ if (!importIsReady()) return;+ const importedDraft = {+ ...result,+ categories: ensureDraftCategories(result.categories),+ compositeSheets: result.compositeSheets || [],+ styleReferences: result.styleReferences || [],+ characters: result.characters || [],+ places: result.places || [],+ objects: result.objects || [],+ influences: result.influences || { embrace: [], avoid: [] },+ };+ setDraft(importedDraft);+ markDraftSaved(importedDraft);+ clearPendingCanonAdditions();+ setCanonDirty(false);+ setWorlds((previous) => [result, ...previous.filter((universe) => universe.id !== result.id)]);+ toast.success(`Imported Markdown into ${result.name}`);+ } catch (error) {+ if (mountedRef.current) toast.error(error?.message || 'Failed to import Markdown');+ } finally {+ if (mountedRef.current) {+ setWaitingForWrites(false);+ setImporting(false);+ }+ }+ }, [+ clearPendingCanonAdditions,+ draftRef,+ flushDraftIfDirty,+ importing,+ markDraftSaved,+ mountedRef,+ saving,+ selectedId,+ setCanonDirty,+ setDraft,+ setWorlds,+ ]);+// Page-level lightbox + gallery-metadata concern. A single MediaPreview at// this level covers EVERY thumb on the page: variations, composite sheets,// canon imageRefs, style probes, and character reference sheets — so clicking@@ -412,6 +492,16 @@ export default function UniverseBuilder() {</button>{selectedId && (<>+ <FilePickerButton+ accept=".md,.markdown,text/markdown,text/plain"+ disabled={importing || exporting || saving || loading || draft.id !== selectedId}+ onChange={handleImportMarkdown}+ title="Import Markdown and replace sections included in the file"+ className="px-3 py-2 rounded flex items-center gap-2 min-h-[40px] border border-port-border hover:bg-port-card-hover disabled:opacity-50"+ >+ {importing ? <Loader2 size={16} className="animate-spin" /> : <Upload size={16} />}+ {waitingForWrites ? 'Saving changes…' : importing ? 'Importing…' : 'Import .md'}+ </FilePickerButton><buttononClick={handleExportMarkdown}disabled={exporting || saving || draft.id !== selectedId}diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.test.jsxindex 5d017fc4c9..6cac02e233 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const apiMocks = vi.hoisted(() => ({exportUniverseMarkdown: vi.fn(),+ importUniverseMarkdown: vi.fn(),waitForUniverseWrites: vi.fn(),}));const downloadMock = vi.hoisted(() => ({ downloadBlob: vi.fn() }));@@ -49,7 +50,7 @@ vi.mock('lucide-react', () => {return {ArrowLeft: Icon, BookOpen: Icon, FolderTree: Icon, ImagePlus: Icon, Layers: Icon,Loader2: Icon, MapPin: Icon, Network: Icon, Package: Icon, Plus: Icon, Save: Icon,- Trash2: Icon, Users: Icon,+ Trash2: Icon, Upload: Icon, Users: Icon,};});@@ -221,3 +222,56 @@ describe('UniverseBuilderPage Markdown export', () => {expect(apiMocks.exportUniverseMarkdown).not.toHaveBeenCalled();});});++describe('UniverseBuilderPage Markdown import', () => {+ it('imports a selected Markdown file into the current universe', async () => {+ const markdown = '# Imported World\n\n**Premise:** A new story premise.';+ const file = new File([markdown], 'imported-world.md', { type: 'text/markdown' });+ file.text = vi.fn().mockResolvedValue(markdown);+ apiMocks.importUniverseMarkdown.mockResolvedValueOnce({+ id: 'u1',+ name: 'Imported World',+ categories: {},+ characters: [],+ places: [],+ objects: [],+ influences: { embrace: [], avoid: [] },+ });++ render(+ <MemoryRouter initialEntries={['/universes/u1']}>+ <NavigationProbe />+ <Routes>+ <Route path="/universes/:universeId" element={<UniverseBuilderPage />} />+ </Routes>+ </MemoryRouter>,+ );++ fireEvent.change(document.querySelector('input[type="file"]'), { target: { files: [file] } });+ await waitFor(() => expect(apiMocks.importUniverseMarkdown).toHaveBeenCalledWith(+ 'u1', markdown, { silent: true },+ ));+ expect(toastMock.success).toHaveBeenCalledWith('Imported Markdown into Imported World');+ });++ it('reports an invalid file without saving the existing draft or calling import', async () => {+ const file = new File(['## Characters\n\n### Mira'], 'not-a-universe.md', { type: 'text/markdown' });+ file.text = vi.fn().mockResolvedValue('## Characters\n\n### Mira');++ render(+ <MemoryRouter initialEntries={['/universes/u1']}>+ <NavigationProbe />+ <Routes>+ <Route path="/universes/:universeId" element={<UniverseBuilderPage />} />+ </Routes>+ </MemoryRouter>,+ );++ fireEvent.change(document.querySelector('input[type="file"]'), { target: { files: [file] } });+ await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith(+ 'Markdown must start with a top-level # universe title.',+ ));+ expect(apiMocks.importUniverseMarkdown).not.toHaveBeenCalled();+ expect(apiMocks.waitForUniverseWrites).not.toHaveBeenCalled();+ });+});diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.jsindex adffe7137b..e39a52eff1 100644--- a/client/src/hooks/useUniverseDraft.js+++ b/client/src/hooks/useUniverseDraft.js@@ -167,7 +167,8 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {const markDraftSaved = useCallback((snapshotSource) => {savedDraftSnapshotRef.current = universeDraftSnapshot(snapshotSource);savedStyleSnapshotRef.current = ensureInfluences(snapshotSource?.influences);- }, []);+ noteUniverseUpdated(snapshotSource?.id, snapshotSource?.updatedAt);+ }, [noteUniverseUpdated]);// Mark only the style-guide fields as saved after an atomic reference-adopt// PATCH. Replacing the entire baseline here would incorrectly clear dirtydiff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsxindex 0c60f4b861..64420e4bc1 100644--- a/client/src/hooks/useUniverseDraft.test.jsx+++ b/client/src/hooks/useUniverseDraft.test.jsx@@ -652,6 +652,40 @@ describe('useUniverseDraft', () => {await waitFor(() => expect(result.current.draft.premise).toBe('Saved premise'));});+ it('tracks a directly marked import response before a hydration GET can overwrite it', async () => {+ let serverUpdatedAt = universe.updatedAt;+ let u1Fetches = 0;+ let resolveStaleHydration;+ apiMocks.getUniverse.mockImplementation(async (id) => {+ if (id === 'u2') return universeTwo;+ u1Fetches += 1;+ if (u1Fetches === 2) return new Promise((resolve) => { resolveStaleHydration = resolve; });+ return { ...universe, premise: 'Imported premise', updatedAt: serverUpdatedAt };+ });++ const { result, rerender } = renderSelectable();+ await waitFor(() => expect(result.current.draft.id).toBe('u1'));+ const importedAt = tickServerClock();+ const imported = { ...universe, premise: 'Imported premise', updatedAt: importedAt };+ await act(async () => {+ serverUpdatedAt = importedAt;+ result.current.setDraft(imported);+ result.current.markDraftSaved(imported);+ });++ await act(async () => { rerender({ selectedId: 'u2' }); });+ await waitFor(() => expect(result.current.draft.id).toBe('u2'));+ await act(async () => { rerender({ selectedId: 'u1' }); });+ await waitFor(() => expect(resolveStaleHydration).toBeTypeOf('function'));+ await act(async () => {+ resolveStaleHydration({ ...universe, premise: 'Original premise', updatedAt: universe.updatedAt });+ await Promise.resolve();+ });++ await waitFor(() => expect(result.current.draft.premise).toBe('Imported premise'));+ expect(u1Fetches).toBe(3);+ });+it('lets an un-raced hydration carry a peer edit the client never wrote', async () => {// The mirror of the test above: with no mutation in flight, the GET is// authoritative — including for writers the client can't see (peer sync,diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex 5e7be6ebda..ed12c51ab8 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -68,6 +68,10 @@ export const exportUniverseMarkdown = (id, options = {}) => request(`/universe-builder/${encodeURIComponent(id)}/export/markdown`,{ responseType: 'text', ...options },);+export const importUniverseMarkdown = (id, markdown, options = {}) => trackUniverseWrite(id, request(+ `/universe-builder/${encodeURIComponent(id)}/import/markdown`,+ { method: 'POST', body: JSON.stringify({ markdown }), ...options },+));// `[{ id, name, influences: { embrace[], avoid[] } }]` for every live universe// that has style tokens. Use this instead of `listUniverses()` whenever adiff --git a/server/lib/README.md b/server/lib/README.mdindex 4f744320c4..8980227290 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -180,7 +180,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `creativeLatitude.js` | The IP-latitude clause every creative LLM request carries (`withCreativeLatitude`, `CREATIVE_LATITUDE_TOKENS`), plus the one creative-vs-operational table both stamp keys are matched against (`isCreativeStage` for stage names, `isCreativeRunSource` for run `source` tags). || `universeBibleCompleteness.js` | Is a universe bible entry actually described? The shared per-kind expand-field vocabulary (`BIBLE_EXPAND_FIELDS`, `BIBLE_CORE_FIELDS`) and the `core`/`full` completeness predicates the quota-burn describe job scans with. Pure. || `universeBibleLimits.js` | Universe bible field size limits shared between server (sanitizer, pipeline) and client (form inputs). |-| `universeMarkdown.js` | Pure deterministic Universe Builder world-bible export: `universeToMarkdown(record)` plus safe Markdown download filename helpers. |+| `universeMarkdown.js` | `universeToMarkdown(record)` / `parseUniverseMarkdown(text)` for the Universe Builder's Markdown world-bible export and import, plus safe download filename helpers. || `universePromptRenderers.js` | Renderers that turn a universe's `categories` map + canon into prompt context, including the authored character-engine block and the shared story canon digest. || `universeVisualStyle.js` | The style a universe contributes to an IMAGE prompt: `buildVisualStyleClause(universe, {override, mode})` (curated `influences.embrace` tokens + a series `stylePromptOverride`, NEVER the free-text `styleNotes`, which is writing-stage direction), `universeAestheticLine` (the labeled variant canon sheet/LoRA renders lead with), `universeVisualStyleTokens`, `splitPromptTokens`, `stripStyleClause(text, clause)` (removes the copy the browser already prefixed, so the compiler keeps the LEADING one — matched on the joined clause so a token with its own punctuation like `M.C. Escher` still matches) and `mergeNegativePromptTokens` (token-level union of comma-joined negatives). || `writersRoomPresets.js` | Writers Room enums (WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS). |diff --git a/server/lib/universeMarkdown.js b/server/lib/universeMarkdown.jsindex 24e799d1be..2d2d4865e0 100644--- a/server/lib/universeMarkdown.js+++ b/server/lib/universeMarkdown.js@@ -70,7 +70,11 @@ const formatInlineValue = (value) => {if (typeof value === 'string') return value.trim().replace(/\s*[\r\n]+\s*/g, ' ');if (typeof value === 'number' || typeof value === 'boolean') return String(value);if (Array.isArray(value)) {- return value.map(formatInlineValue).filter(Boolean).join(', ');+ return value+ .map(formatInlineValue)+ .filter(Boolean)+ .map((rendered) => rendered.replace(/\\/g, '\\\\').replace(/,/g, '\\,'))+ .join(', ');}if (typeof value === 'object') {return Object.entries(value)@@ -95,7 +99,7 @@ const formatBlockValue = (value) => {.map((line) => {const leading = line.match(/^\s*/u)?.[0] || '';const content = line.slice(leading.length);- return /^(?:#{1,6}\s|>\s?|[-*_]{3,}\s*$|=+\s*$|-+\s*$|`{3,})/u.test(content)+ return /^(?:#{1,6}\s|>\s?|[-*_]{3,}\s*$|=+\s*$|-+\s*$|`{3,}|\*\*[^*]+:\*\*)/u.test(content)? `${leading}\\${content}`: line;})@@ -236,7 +240,10 @@ export function universeToMarkdown(record) {const source = record && typeof record === 'object' ? record : {};const sections = [`# ${headingText(source.name, 'Untitled Universe')}`];const prose = ['logline', 'premise', 'styleNotes']- .map((key) => formatBlockValue(source[key]))+ .map((key) => {+ const value = formatBlockValue(source[key]);+ return value ? `**${formatFieldLabel(key)}:** ${value}` : '';+ }).filter(Boolean);if (prose.length) sections.push(prose.join('\n\n'));@@ -256,3 +263,226 @@ export function universeToMarkdown(record) {return `${sections.join('\n\n').trimEnd()}\n`;}++const STRING_FIELDS = Object.freeze({+ characters: new Set([+ 'role', 'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern',+ 'visualNotes', 'physicalDescription', 'personality', 'background',+ 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity',+ 'motivations', 'ghost', 'wound', 'lie', 'want', 'need', 'arcType',+ 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills', 'voiceId',+ 'prompt', 'notes', 'firstAppearance',+ ]),+ places: new Set([+ 'slugline', 'description', 'palette', 'era', 'weather', 'intExt',+ 'timeOfDay', 'recurringDetails', 'prompt', 'notes', 'firstAppearance',+ ]),+ objects: new Set([+ 'description', 'significance', 'prompt', 'notes', 'firstAppearance',+ ]),+});++const ARRAY_FIELDS = Object.freeze({+ characters: new Set(['aliases', 'tags', 'secrets', 'evidence', 'missingFromProse']),+ places: new Set(['tags', 'evidence', 'missingFromProse']),+ objects: new Set(['aliases', 'tags', 'evidence', 'missingFromProse']),+});+const UNIVERSE_FIELDS = new Map([+ ['logline', 'logline'],+ ['premise', 'premise'],+ ['styleNotes', 'styleNotes'],+]);+const SECTION_NAMES = new Map([+ ['characters', 'characters'],+ ['places', 'places'],+ ['objects', 'objects'],+ ['categories', 'categories'],+ ['influences', 'influences'],+]);++const unescapeMarkdownLine = (line) => line.replace(+ /^(\s*)\\(?=(?:#{1,6}\s|>\s?|[-*_]{3,}\s*$|`{3,}|\*\*[^*]+:\*\*))/u,+ '$1',+);++const fieldKey = (label) => label+ .trim()+ .toLowerCase()+ .split(/[^a-z0-9]+/u)+ .filter(Boolean)+ .map((part, index) => (index === 0 ? part : `${part[0].toUpperCase()}${part.slice(1)}`))+ .join('');++const FIELD_LINE = /^\*\*([^*]+):\*\*(?:\s+(.*))?$/u;++const readFieldBlocks = (lines, isKnownField) => {+ const fields = {};+ const free = [];+ let activeKey = null;+ let activeLines = [];+ let ignoringField = false;+ const flush = () => {+ if (activeKey) fields[activeKey] = activeLines.join('\n').trim();+ activeKey = null;+ activeLines = [];+ };++ for (const rawLine of lines) {+ const line = unescapeMarkdownLine(rawLine);+ const escapedFieldLine = /^\s*\\\*\*[^*]+:\*\*/u.test(rawLine);+ const match = escapedFieldLine ? null : line.match(FIELD_LINE);+ if (match) {+ flush();+ activeKey = fieldKey(match[1]);+ ignoringField = !isKnownField(activeKey);+ if (ignoringField) activeKey = null;+ else activeLines = [match[2] || ''];+ } else if (activeKey) {+ activeLines.push(line);+ } else if (!ignoringField) {+ free.push(line);+ }+ }+ flush();+ return { fields, freeText: free.join('\n').trim() };+};++const splitArrayValue = (value) => {+ const items = [];+ let item = '';+ for (let i = 0; i < value.length; i += 1) {+ if (value[i] === '\\' && (value[i + 1] === ',' || value[i + 1] === '\\')) {+ item += value[i + 1];+ i += 1;+ } else if (value[i] === ',') {+ if (item.trim()) items.push(item.trim());+ item = '';+ while (value[i + 1] === ' ') i += 1;+ } else {+ item += value[i];+ }+ }+ if (item.trim()) items.push(item.trim());+ return items;+};++const readSections = (lines) => {+ const sections = [];+ let current = null;+ const preamble = [];+ for (const line of lines) {+ const heading = line.match(/^##\s+(.+?)\s*#*\s*$/u);+ if (!heading) {+ if (current) current.lines.push(line);+ else preamble.push(line);+ continue;+ }+ current = { title: heading[1].trim().toLowerCase(), lines: [] };+ sections.push(current);+ }+ return { preamble, sections };+};++const splitSubsections = (lines) => {+ const subsections = [];+ let current = null;+ for (const line of lines) {+ const heading = line.match(/^###\s+(.+?)\s*#*\s*$/u);+ if (!heading) {+ if (current) current.lines.push(line);+ continue;+ }+ current = { title: unescapeMarkdownLine(heading[1]).trim(), lines: [] };+ subsections.push(current);+ }+ return subsections;+};++const parseCanonEntries = (kind, lines) => splitSubsections(lines).map(({ title, lines: entryLines }) => {+ const { fields, freeText } = readFieldBlocks(+ entryLines,+ (key) => STRING_FIELDS[kind].has(key) || ARRAY_FIELDS[kind].has(key),+ );+ const entry = { ...(kind === 'places' && /^(?:int\.?\s*\/\s*ext\.?|ext\.?|int\.?)(?:\s|\.)/iu.test(title)+ ? { slugline: title }+ : { name: title }) };+ for (const [key, value] of Object.entries(fields)) {+ if (STRING_FIELDS[kind].has(key)) entry[key] = value;+ else if (ARRAY_FIELDS[kind].has(key)) entry[key] = splitArrayValue(value);+ }+ if (freeText && !entry.notes) entry.notes = freeText;+ return entry;+});++const parseCategories = (lines) => Object.fromEntries(splitSubsections(lines).map(({ title, lines: categoryLines }) => {+ let kind;+ const variations = [];+ for (const rawLine of categoryLines) {+ const line = unescapeMarkdownLine(rawLine).trim();+ const kindMatch = line.match(/^\*\*kind:\*\*\s*(.+)$/iu);+ if (kindMatch) {+ kind = kindMatch[1].trim();+ continue;+ }+ const labeled = line.match(/^-\s+\*\*(.+?)\*\*\s+—\s+(.*)$/u);+ if (labeled) {+ variations.push({ label: labeled[1].trim(), prompt: labeled[2].trim() });+ continue;+ }+ const bullet = line.match(/^-\s+(.+)$/u);+ if (bullet) {+ const value = bullet[1].trim();+ if (value) variations.push({ label: value, prompt: value });+ }+ }+ return [title, { ...(kind ? { kind } : {}), variations }];+}));++const parseInfluences = (lines) => {+ const influences = { embrace: [], avoid: [] };+ for (const rawLine of lines) {+ const match = unescapeMarkdownLine(rawLine).trim().match(/^-\s+(embrace|avoid):\s*(.+)$/iu);+ if (!match) continue;+ const value = match[2].trim();+ if (value) influences[match[1].toLowerCase()].push(value);+ }+ return influences;+};++/**+ * Parse the editable world-bible fields represented by Universe Markdown.+ * Exported sections are treated as replacements; omitted sections are absent+ * from the patch. The parser intentionally skips local image pointers and+ * inventory-only Composite Sheets / Style References rows.+ *+ * @param {string} markdown - A Markdown document with a top-level universe title.+ * @returns {Record<string, unknown>} A partial universe patch.+ */+export function parseUniverseMarkdown(markdown) {+ if (typeof markdown !== 'string') throw new Error('Choose a Markdown file to import.');+ const lines = markdown.replace(/^\uFEFF/u, '').replace(/\r\n?/gu, '\n').split('\n');+ const titleIndex = lines.findIndex((line) => line.trim());+ const title = titleIndex >= 0 ? lines[titleIndex].match(/^#\s+(.+?)\s*#*\s*$/u) : null;+ if (!title?.[1]?.trim()) throw new Error('Markdown must start with a top-level # universe title.');++ const { preamble, sections } = readSections(lines.slice(titleIndex + 1));+ const { fields: topFields, freeText } = readFieldBlocks(+ preamble,+ (key) => UNIVERSE_FIELDS.has(key),+ );+ const patch = { name: title[1].trim() };+ for (const [key, value] of Object.entries(topFields)) patch[UNIVERSE_FIELDS.get(key)] = value;+ if (freeText && !('premise' in patch)) patch.premise = freeText;++ for (const section of sections) {+ const key = SECTION_NAMES.get(section.title);+ if (key === 'characters' || key === 'places' || key === 'objects') {+ patch[key] = parseCanonEntries(key, section.lines);+ } else if (key === 'categories') {+ patch.categories = parseCategories(section.lines);+ } else if (key === 'influences') {+ patch.influences = parseInfluences(section.lines);+ }+ }+ return patch;+}diff --git a/server/lib/universeMarkdown.test.js b/server/lib/universeMarkdown.test.jsindex cfcd764998..1081cb7c59 100644--- a/server/lib/universeMarkdown.test.js+++ b/server/lib/universeMarkdown.test.js@@ -1,5 +1,10 @@import { describe, expect, it } from 'vitest';-import { slugifyUniverseName, universeMarkdownFilename, universeToMarkdown } from './universeMarkdown.js';+import {+ parseUniverseMarkdown,+ slugifyUniverseName,+ universeMarkdownFilename,+ universeToMarkdown,+} from './universeMarkdown.js';import { UNIVERSE_MARKDOWN_FILENAME_CASES } from '../../client/src/lib/universeMarkdownFilename.cases.js';describe('universeToMarkdown', () => {@@ -22,7 +27,8 @@ describe('universeToMarkdown', () => {});expect(markdown).toContain('# The Bright World');- expect(markdown).toContain('A world beneath two suns.\n\nEvery map changes when the second sun rises.');+ expect(markdown).toContain('**Logline:** A world beneath two suns.');+ expect(markdown).toContain('**Premise:** Every map changes when the second sun rises.');expect(markdown).toContain('## Characters\n\n### Mira');expect(markdown).toContain('### Mira\n\n**Role:** Cartographer');expect(markdown).toContain('**Physical Description:** Patient and precise.');@@ -127,3 +133,50 @@ describe('universe markdown filenames', () => {expect(universeMarkdownFilename(name)).toBe(filename);});});++describe('parseUniverseMarkdown', () => {+ it('reads the exported editable fields, including multiline values and escaped headings', () => {+ const markdown = universeToMarkdown({+ name: 'The Bright World',+ logline: 'A world beneath two suns.',+ premise: 'Every map changes.\n## A heading inside the text.\n**Logline:** literal text, not a field.',+ styleNotes: 'Warm copper light.',+ characters: [{ name: 'Mira', aliases: ['The Mapper, Jr.', 'M.'], role: 'Cartographer', notes: 'Patient and precise.' }],+ places: [{ slugline: 'INT. THE ARCHIVE - DAY', description: 'A tower of living maps.' }],+ objects: [{ name: 'Sun Compass', description: 'Points toward the next dawn.' }],+ categories: {+ landscapes: { kind: 'places', variations: [{ label: 'Copper Flats', prompt: 'shimmering salt' }] },+ },+ influences: { embrace: ['copper', 'dust'], avoid: ['plastic'] },+ });++ expect(parseUniverseMarkdown(markdown)).toEqual({+ name: 'The Bright World',+ logline: 'A world beneath two suns.',+ premise: 'Every map changes.\n## A heading inside the text.\n**Logline:** literal text, not a field.',+ styleNotes: 'Warm copper light.',+ characters: [{+ name: 'Mira', aliases: ['The Mapper, Jr.', 'M.'], role: 'Cartographer', notes: 'Patient and precise.',+ }],+ places: [{ slugline: 'INT. THE ARCHIVE - DAY', description: 'A tower of living maps.' }],+ objects: [{ name: 'Sun Compass', description: 'Points toward the next dawn.' }],+ categories: {+ landscapes: { kind: 'places', variations: [{ label: 'Copper Flats', prompt: 'shimmering salt' }] },+ },+ influences: { embrace: ['copper', 'dust'], avoid: ['plastic'] },+ });+ });++ it('imports older and hand-authored Markdown prose as the premise', () => {+ expect(parseUniverseMarkdown('# Example Universe\n\nA concise premise.\n\nMore context.')).toEqual({+ name: 'Example Universe',+ premise: 'A concise premise.\n\nMore context.',+ });+ });++ it('rejects Markdown without a top-level universe title', () => {+ expect(() => parseUniverseMarkdown('## Characters\n\n### Mira')).toThrow(+ 'Markdown must start with a top-level # universe title.',+ );+ });+});diff --git a/server/routes/universeBuilder/export.js b/server/routes/universeBuilder/export.jsindex edbe520726..0e07970a87 100644--- a/server/routes/universeBuilder/export.js+++ b/server/routes/universeBuilder/export.js@@ -7,13 +7,78 @@*/import { Router } from 'express';-import { asyncHandler } from '../../lib/errorHandler.js';-import { universeMarkdownFilename, universeToMarkdown } from '../../lib/universeMarkdown.js';+import { z } from 'zod';+import { asyncHandler, failValidation, ServerError } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import { parseUniverseMarkdown, universeMarkdownFilename, universeToMarkdown } from '../../lib/universeMarkdown.js';import * as svc from '../../services/universeBuilder.js';-import { mapServiceError } from './shared.js';+import { findSameNameUniverses } from '../../services/duplicateDetection.js';+import { canonArrayField, categoriesSchema, influencesSchema, mapServiceError } from './shared.js';const router = Router();+const markdownImportSchema = z.object({+ markdown: z.string().trim().min(1).max(10_000_000),+}).strict();+const markdownUniversePatchSchema = z.object({+ name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH),+ logline: z.string().trim().max(svc.LOGLINE_MAX).optional(),+ premise: z.string().trim().max(svc.PREMISE_MAX).optional(),+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional(),+ categories: categoriesSchema.optional(),+ influences: influencesSchema.optional(),+ characters: canonArrayField,+ places: canonArrayField,+ objects: canonArrayField,+}).strict();++const categoryKey = (value) => String(value || '')+ .trim()+ .toLowerCase()+ .replace(/&/g, ' and ')+ .replace(/[^a-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '')+ .replace(/_{2,}/g, '_')+ .slice(0, svc.WORLD_CATEGORY_KEY_MAX);++const canonIdentities = (entry, kind) => {+ const values = kind === 'places'+ ? [entry?.slugline, entry?.name]+ : [entry?.name, ...(Array.isArray(entry?.aliases) ? entry.aliases : [])];+ return new Set(values+ .filter((value) => typeof value === 'string' && value.trim())+ .map((value) => value.trim().toLowerCase().replace(/\s+/g, ' ')));+};++const preserveCanonMetadata = (existing, imported, kind) => imported.map((entry) => {+ const identities = canonIdentities(entry, kind);+ const previous = (existing || []).find((candidate) =>+ [...canonIdentities(candidate, kind)].some((identity) => identities.has(identity)));+ return previous+ ? { ...previous, ...entry, id: previous.id, createdAt: previous.createdAt }+ : entry;+});++const preserveCategoryMetadata = (existingCategories, importedCategories) => {+ const existingByKey = new Map(Object.entries(existingCategories || {}).map(([key, value]) => [categoryKey(key), value]));+ return Object.fromEntries(Object.entries(importedCategories || {}).map(([key, incoming]) => {+ const normalizedKey = categoryKey(key);+ const previous = existingByKey.get(normalizedKey);+ const previousVariations = Array.isArray(previous?.variations) ? previous.variations : [];+ const variations = (incoming.variations || []).map((variation) => {+ const prior = previousVariations.find((candidate) =>+ candidate?.label?.trim().toLowerCase() === variation.label?.trim().toLowerCase());+ return prior ? { ...prior, ...variation, id: prior.id } : variation;+ });+ return [normalizedKey, {+ ...(previous || {}),+ ...incoming,+ kind: incoming.kind || previous?.kind,+ variations,+ }];+ }));+};+router.get('/:id/export/markdown', asyncHandler(async (req, res) => {const universe = await svc.getUniverse(req.params.id).catch((err) => {throw mapServiceError(err);@@ -23,4 +88,38 @@ router.get('/:id/export/markdown', asyncHandler(async (req, res) => {res.send(universeToMarkdown(universe));}));+router.post('/:id/import/markdown', asyncHandler(async (req, res) => {+ const { markdown } = validateRequest(markdownImportSchema, req.body ?? {});+ let patch;+ try {+ patch = parseUniverseMarkdown(markdown);+ } catch (error) {+ throw new ServerError(error.message || 'Unable to read this Markdown file.', {+ status: 400,+ code: 'VALIDATION_ERROR',+ });+ }+ const checkedPatch = markdownUniversePatchSchema.safeParse(patch);+ if (!checkedPatch.success) failValidation(checkedPatch);+ patch = checkedPatch.data;++ const universe = await svc.updateUniverse(req.params.id, (current) => {+ const next = { ...patch };+ for (const kind of ['characters', 'places', 'objects']) {+ if (Array.isArray(next[kind])) next[kind] = preserveCanonMetadata(current[kind], next[kind], kind);+ }+ if (next.categories) next.categories = preserveCategoryMetadata(current.categories, next.categories);+ return next;+ }, { replaceCategories: true }).catch((err) => { throw mapServiceError(err); });++ if ('name' in patch) {+ const duplicateName = await findSameNameUniverses(universe.name, { excludeId: req.params.id });+ if (duplicateName.length) {+ res.json({ ...universe, _warnings: { duplicateName } });+ return;+ }+ }+ res.json(universe);+}));+export default router;diff --git a/server/routes/universeBuilder/index.test.js b/server/routes/universeBuilder/index.test.jsindex 16eae97831..ddb9b311ba 100644--- a/server/routes/universeBuilder/index.test.js+++ b/server/routes/universeBuilder/index.test.js@@ -373,6 +373,104 @@ describe('universe-builder routes', () => {expect(missing.body.code).toBe('NOT_FOUND');});+ it('POST /:id/import/markdown replaces represented sections and preserves local entry metadata', async () => {+ const app = buildApp();+ const created = await request(app)+ .post('/api/universe-builder')+ .send({+ name: 'Original Markdown World',+ characters: [+ { name: 'Mira', role: 'Scout', notes: 'Local note to preserve.' },+ { name: 'Removed Character', role: 'Old role' },+ ],+ places: [{ name: 'The Archive', slugline: 'INT. THE ARCHIVE - DAY', description: 'Old location detail.' }],+ categories: {+ landscapes: {+ kind: 'places',+ variations: [{ label: 'Copper Flats', prompt: 'shimmering ground', imageRefs: ['local-ref.png'], locked: false }],+ },+ vehicles: { kind: 'objects', variations: [{ label: 'Old Skiff', prompt: 'a small boat' }] },+ },+ influences: { embrace: ['warm light'], avoid: ['plastic'] },+ });+ expect(created.status).toBe(201);+ const miraId = created.body.characters.find((entry) => entry.name === 'Mira').id;+ const archiveId = created.body.places[0].id;+ const variationId = created.body.categories.landscapes.variations[0].id;++ const imported = await request(app)+ .post(`/api/universe-builder/${created.body.id}/import/markdown`)+ .send({ markdown: [+ '# Imported Markdown World',+ '',+ '**Premise:** A new map changes the coast.',+ '',+ '## Characters',+ '',+ '### Mira',+ '',+ '**Role:** Guide',+ '',+ '### Rin',+ '',+ '**Role:** Navigator',+ '',+ '## Places',+ '',+ '### The Archive',+ '',+ '**Description:** A living tower of maps.',+ '',+ '## Categories',+ '',+ '### landscapes',+ '**Kind:** places',+ '- **Copper Flats** — salt plains beneath a red sunrise',+ '',+ '## Influences',+ '',+ '- Embrace: copper',+ ].join('\n') });++ expect(imported.status).toBe(200);+ expect(imported.body.name).toBe('Imported Markdown World');+ expect(imported.body.premise).toBe('A new map changes the coast.');+ expect(imported.body.characters.map((entry) => entry.name)).toEqual(['Mira', 'Rin']);+ expect(imported.body.characters[0]).toMatchObject({+ id: miraId,+ role: 'Guide',+ notes: 'Local note to preserve.',+ });+ expect(imported.body.places[0]).toMatchObject({+ id: archiveId,+ name: 'The Archive',+ slugline: 'INT. THE ARCHIVE - DAY',+ description: 'A living tower of maps.',+ });+ expect(imported.body.categories.landscapes.variations[0]).toMatchObject({+ id: variationId,+ label: 'Copper Flats',+ prompt: 'salt plains beneath a red sunrise',+ imageRefs: ['local-ref.png'],+ locked: false,+ });+ expect(imported.body.categories.vehicles.variations).toEqual([]);+ expect(imported.body.influences).toEqual({ embrace: ['copper'], avoid: [] });+ });++ it('POST /:id/import/markdown rejects a document without a universe title', async () => {+ const app = buildApp();+ const created = await request(app)+ .post('/api/universe-builder')+ .send({ name: 'Markdown Validation Target' });+ const response = await request(app)+ .post(`/api/universe-builder/${created.body.id}/import/markdown`)+ .send({ markdown: '## Characters\n\n### Mira' });++ expect(response.status).toBe(400);+ expect(response.body.code).toBe('VALIDATION_ERROR');+ });+it('POST / creates a universe', async () => {const res = await request(buildApp()).post('/api/universe-builder')