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: ship photographic Reality starter and restore action (#13425)
[._.]/c6f7b84498c3
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsxindex efc0c12315..e31889f669 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx@@ -18,6 +18,8 @@ import InlineConfirmRow from '../ui/InlineConfirmRow';import toast from '../ui/Toast';import {exportUniverseMarkdown,+ getUniverse,+ restoreUniverseStarter,importUniverseMarkdown,waitForUniverseWrites,WORLD_CATEGORY_KEY_MAX,@@ -116,6 +118,9 @@ export default function UniverseBuilder() {const selectedId = params.universeId && params.universeId !== 'new' ? params.universeId : null;const selectedIdRef = useRef(selectedId);selectedIdRef.current = selectedId;+ const [restoringStarter, setRestoringStarter] = useState(false);+ const [confirmStarter, setConfirmStarter] = useState(false);+ const restoreBusyRef = useRef(false);const [exporting, setExporting] = useState(false);const [importing, setImporting] = useState(false);const [waitingForWrites, setWaitingForWrites] = useState(false);@@ -287,6 +292,37 @@ export default function UniverseBuilder() {toast.success(`Downloaded ${filename}`);}, [draft.name, draftRef, exporting, flushDraftIfDirty, saving, selectedId]);+ const handleRestoreStarter = async () => {+ if (restoreBusyRef.current || saving || importing || expanding || refine?.running || selectedId !== 'universe-reality') return;+ const isCurrent = () => mountedRef.current && selectedIdRef.current === selectedId+ && draftRef.current?.id === selectedId;+ if (!isCurrent()) return;+ restoreBusyRef.current = true;+ setRestoringStarter(true);+ setConfirmStarter(false);+ try {+ if (!await waitForUniverseWrites(selectedId)) throw new Error('Changes are still saving. Try again in a moment.');+ if (!isCurrent() || !await flushDraftIfDirty() || !isCurrent()) return;+ if (!await waitForUniverseWrites(selectedId)) throw new Error('Changes are still saving. Try again in a moment.');+ if (!isCurrent()) return;+ const latest = await getUniverse(selectedId, { silent: true });+ if (!isCurrent()) return;+ const result = await restoreUniverseStarter(selectedId, latest.updatedAt, { silent: true });+ if (!isCurrent()) return;+ const restored = { ...result, categories: ensureDraftCategories(result.categories) };+ draftRef.current = restored;+ setDraft(restored);+ markDraftSaved(restored);+ setWorlds(previous => [result, ...previous.filter(world => world.id !== result.id)]);+ toast.success('Latest Reality starter restored');+ } catch (error) {+ if (isCurrent()) toast.error(error?.message || 'Failed to restore starter');+ } finally {+ restoreBusyRef.current = false;+ if (mountedRef.current) setRestoringStarter(false);+ }+ };+const handleImportMarkdown = useCallback(async (event) => {const file = event.currentTarget.files?.[0];const importIsReady = () => mountedRef.current@@ -473,8 +509,9 @@ export default function UniverseBuilder() {}return (- <div className="flex flex-col h-full">- <section className="flex-1 flex flex-col gap-3 p-4 min-h-0 overflow-y-auto">+ <div className="flex flex-col h-full" aria-busy={restoringStarter}>+ {restoringStarter && <p role="status">Restoring latest Reality starter…</p>}+ <section inert={restoringStarter || undefined} className="flex-1 flex flex-col gap-3 p-4 min-h-0 overflow-y-auto">{/* Back to the universe index (list/table at /universes). */}<Linkto="/universes"@@ -532,6 +569,22 @@ export default function UniverseBuilder() {{exporting ? <Loader2 size={16} className="animate-spin" /> : <BookOpen size={16} />}{waitingForWrites ? 'Saving changes…' : exporting ? 'Exporting…' : 'Export .md'}</button>+ {selectedId === 'universe-reality' && (confirmStarter ? (+ <InlineConfirmRow+ question="Replace starter idea, logline, premise, style notes and positive/negative style with the latest shipped text? Characters, places, objects and images are kept."+ confirmText="Restore starter"+ tone="warning"+ autoFocus+ onConfirm={handleRestoreStarter}+ onCancel={() => setConfirmStarter(false)}+ />+ ) : (+ <button+ onClick={() => setConfirmStarter(true)}+ disabled={saving || importing || exporting || loading || expanding || refine?.running || draft.id !== selectedId}+ className="px-3 py-2 rounded min-h-[40px] border border-port-border hover:bg-port-card-hover disabled:opacity-50"+ >Restore latest starter</button>+ ))}<ShareToButton kind="universe" ids={[selectedId]} label="Share" /><SyncToPeerButton recordKind="universe" recordId={selectedId} label="Sync" />{draft.origin ? <OriginBadge origin={draft.origin} /> : null}diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.test.jsxindex b5e9332f44..e270f8fd94 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx@@ -4,6 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const apiMocks = vi.hoisted(() => ({exportUniverseMarkdown: vi.fn(),+ getUniverse: vi.fn(),+ restoreUniverseStarter: vi.fn(),importUniverseMarkdown: vi.fn(),waitForUniverseWrites: vi.fn(),}));@@ -33,7 +35,6 @@ vi.mock('../../hooks/useUniverseTabs', () => ({ default: hookMocks.useUniverseTavi.mock('../../hooks/useUniverseBucketActions', () => ({ default: hookMocks.useUniverseBucketActions }));vi.mock('../../hooks/useUniverseNav', () => ({ useUniverseNav: hookMocks.useUniverseNav }));vi.mock('../EntityCombobox', () => ({ default: () => null }));-vi.mock('../ui/InlineConfirmRow', () => ({ default: () => null }));vi.mock('../media/MediaPreview', () => ({ default: () => null }));vi.mock('../sharing/OriginBadge', () => ({ default: () => null }));vi.mock('../sharing/ShareToButton', () => ({ default: () => null }));@@ -300,3 +301,98 @@ describe('UniverseBuilderPage Markdown import', () => {expect(apiMocks.waitForUniverseWrites).not.toHaveBeenCalled();});});+++describe('Reality starter restore', () => {+ const mount = (id = 'universe-reality') => render(+ <MemoryRouter initialEntries={[`/universes/${id}`]}>+ <NavigationProbe />+ <Routes><Route path="/universes/:universeId" element={<UniverseBuilderPage />} /></Routes>+ </MemoryRouter>,+ );+ const confirm = () => {+ fireEvent.click(screen.getByRole('button', { name: 'Restore latest starter' }));+ fireEvent.click(screen.getByRole('button', { name: 'Restore starter' }));+ };++ it('offers restore only for shipped Reality and requires confirmation', () => {+ const view = mount('custom');+ expect(screen.queryByRole('button', { name: 'Restore latest starter' })).not.toBeInTheDocument();+ view.unmount();+ mount();+ fireEvent.click(screen.getByRole('button', { name: 'Restore latest starter' }));+ expect(screen.getByText(/Characters, places, objects and images are kept/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(apiMocks.restoreUniverseStarter).not.toHaveBeenCalled();+ });++ it.each(['expand', 'refine'])('blocks restore while %s is in flight, including an already-open confirmation', operation => {+ const expansion = hookMocks.useUniverseExpand();+ const view = mount();+ fireEvent.click(screen.getByRole('button', { name: 'Restore latest starter' }));+ hookMocks.useUniverseExpand.mockReturnValue({+ ...expansion,+ expanding: operation === 'expand',+ refine: { running: operation === 'refine' },+ });+ view.rerender(+ <MemoryRouter initialEntries={['/universes/universe-reality']}>+ <NavigationProbe />+ <Routes><Route path="/universes/:universeId" element={<UniverseBuilderPage />} /></Routes>+ </MemoryRouter>,+ );+ fireEvent.click(screen.getByRole('button', { name: 'Restore starter' }));+ expect(apiMocks.restoreUniverseStarter).not.toHaveBeenCalled();+ expect(apiMocks.waitForUniverseWrites).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(screen.getByRole('button', { name: 'Restore latest starter' })).toBeDisabled();+ });++ it('saves dirty edits before restoring and adopts the returned record', async () => {+ const state = hookMocks.useUniverseDraft({ selectedId: 'universe-reality' });+ hookMocks.useUniverseDraft.mockReturnValue(state);+ const result = { ...state.draft, premise: 'Latest shipped text' };+ apiMocks.getUniverse.mockResolvedValue({ updatedAt: '2026-01-01T00:00:00.000Z' });+ apiMocks.restoreUniverseStarter.mockResolvedValue(result);+ mount();+ confirm();+ await waitFor(() => expect(state.setDraft).toHaveBeenCalledWith(expect.objectContaining({ id: result.id, premise: result.premise })));+ expect(state.flushDraftIfDirty).toHaveBeenCalled();+ expect(apiMocks.restoreUniverseStarter).toHaveBeenCalledWith('universe-reality', '2026-01-01T00:00:00.000Z', { silent: true });+ expect(state.markDraftSaved).toHaveBeenCalledWith(state.setDraft.mock.calls[0][0]);+ });++ it('stops when dirty edits cannot save', async () => {+ const state = hookMocks.useUniverseDraft({ selectedId: 'universe-reality' });+ state.flushDraftIfDirty.mockResolvedValue(false);+ hookMocks.useUniverseDraft.mockReturnValue(state);+ mount();+ confirm();+ await waitFor(() => expect(state.flushDraftIfDirty).toHaveBeenCalled());+ expect(apiMocks.restoreUniverseStarter).not.toHaveBeenCalled();+ });++ it('keeps the draft and surfaces a concurrent-edit refusal', async () => {+ const state = hookMocks.useUniverseDraft({ selectedId: 'universe-reality' });+ hookMocks.useUniverseDraft.mockReturnValue(state);+ apiMocks.getUniverse.mockResolvedValue({ updatedAt: '2026-01-01T00:00:00.000Z' });+ apiMocks.restoreUniverseStarter.mockRejectedValue(new Error('Universe changed. Reload it.'));+ mount();+ confirm();+ await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith('Universe changed. Reload it.'));+ expect(state.setDraft).not.toHaveBeenCalled();+ });++ it('does not replace a different universe after navigation', async () => {+ let resolveRestore;+ apiMocks.getUniverse.mockResolvedValue({ updatedAt: '2026-01-01T00:00:00.000Z' });+ apiMocks.restoreUniverseStarter.mockImplementation(() => new Promise(resolve => { resolveRestore = resolve; }));+ mount();+ confirm();+ await waitFor(() => expect(resolveRestore).toBeTypeOf('function'));+ act(() => navigateRef.current('/universes/custom'));+ const state = hookMocks.useUniverseDraft.mock.results.at(-1).value;+ await act(async () => resolveRestore(makeDraft('universe-reality')));+ expect(state.setDraft).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex 4f23035a18..c7f9246f8e 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -498,3 +498,8 @@ export const autoSortBuckets = (universeId, { providerId, model } = {}, optionsexport const getCharacterReferenceSheet = (universeId, entryId, variant, options = {}) =>request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/reference-sheet?variant=${encodeURIComponent(variant)}`, options);++// Explicit text-only restore; record revision protects concurrent edits.+export const restoreUniverseStarter = (id, expectedUpdatedAt, options = {}) => trackUniverseWrite(id, request(`/universe-builder/${encodeURIComponent(id)}/restore-starter`, {+ method: 'POST', body: JSON.stringify({ expectedUpdatedAt }), ...options,+}));diff --git a/scripts/migrations/440-reality-text-starter.js b/scripts/migrations/440-reality-text-starter.jsnew file mode 100644index 0000000000..17f895a39a--- /dev/null+++ b/scripts/migrations/440-reality-text-starter.js@@ -0,0 +1,21 @@+/** Populate the blank Reality seeded by 395; preserve customization and tombstones. */+import { withTransaction } from '../../server/lib/db.js';+import { REALITY_STARTER_V1 } from '../../server/lib/realityStarterV1.js';++export default {+ async up() {+ await withTransaction(async (client) => {+ const { rows } = await client.query('SELECT data, deleted FROM universes WHERE id = $1 FOR UPDATE', ['universe-reality']);+ const row = rows[0];+ const record = row?.data;+ if (!record || row.deleted || record.deleted || record.name !== 'Reality' || record.factual !== true) return;+ const fields = ['starterPrompt', 'logline', 'premise', 'styleNotes', 'stylePrompt', 'negativePrompt'];+ if (fields.some(key => record[key]?.trim())+ || record.influences?.embrace?.length || record.influences?.avoid?.length+ || Object.values(record.locked || {}).some(Boolean)) return;+ const updatedAt = new Date(Math.max(Date.now(), (Date.parse(record.updatedAt) || 0) + 1)).toISOString();+ const next = { ...record, ...structuredClone(REALITY_STARTER_V1), updatedAt };+ await client.query('UPDATE universes SET data = $2::jsonb, updated_at = $3 WHERE id = $1', ['universe-reality', JSON.stringify(next), updatedAt]);+ });+ },+};diff --git a/scripts/migrations/440-reality-text-starter.test.js b/scripts/migrations/440-reality-text-starter.test.jsnew file mode 100644index 0000000000..97875693ce--- /dev/null+++ b/scripts/migrations/440-reality-text-starter.test.js@@ -0,0 +1,33 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { REALITY_STARTER_V1 } from '../../server/lib/realityStarterV1.js';++const { query } = vi.hoisted(() => ({ query: vi.fn() }));+vi.mock('../../server/lib/db.js', () => ({ withTransaction: fn => fn({ query }) }));+import migration from './440-reality-text-starter.js';+beforeEach(() => query.mockReset());++it('fills blank shipped text atomically while preserving local canon and media', async () => {+ const data = { id: 'universe-reality', name: 'Reality', starterPrompt: '', factual: true, characters: [{ id: 'local' }], styleImageRefs: ['local.jpg'] };+ query.mockResolvedValueOnce({ rows: [{ data, deleted: false }] }).mockResolvedValueOnce({});+ await migration.up();+ expect(query.mock.calls[0][0]).toContain('FOR UPDATE');+ const saved = JSON.parse(query.mock.calls[1][1][1]);+ expect(saved).toMatchObject({ ...data, ...REALITY_STARTER_V1 });+ expect(saved.updatedAt).toBe(query.mock.calls[1][1][2]);+});++it.each([+ undefined,+ { data: {}, deleted: true },+ { data: { deleted: true } },+ { data: { name: 'Personal world', factual: true } },+ { data: { name: 'Reality', factual: false } },+ { data: { premise: 'My own world' } },+ { data: { negativePrompt: 'My legacy style' } },+ { data: { influences: { embrace: ['personal style'] } } },+ { data: { locked: { premise: true } } },+])('preserves absent, deleted or customized Reality: %j', async row => {+ query.mockResolvedValue({ rows: row ? [{ ...row, data: { name: 'Reality', factual: true, ...row.data } }] : [] });+ await migration.up();+ expect(query).toHaveBeenCalledTimes(1);+});diff --git a/server/hostControlCoverage.test.js b/server/hostControlCoverage.test.jsindex f2871a33a6..04d0da77f9 100644--- a/server/hostControlCoverage.test.js+++ b/server/hostControlCoverage.test.js@@ -1231,6 +1231,7 @@ const REVIEWED_OPEN_MUTATIONS = [['POST /api/universe-builder/:id/characters/:entryId/augment/apply', RECORDS],['DELETE /api/universe-builder/:id/characters/:entryId/reference-sheet', REMOVES_RECORD],['POST /api/universe-builder/:id/import/markdown', RECORDS],+ ['POST /api/universe-builder/:id/restore-starter', 'Replaces record text with bundled defaults only; no agent, process or filesystem operation.'],['POST /api/universe-builder/:id/style-references', RECORDS],['DELETE /api/universe-builder/:id/style-references/:referenceId', REMOVES_RECORD],['PATCH /api/universe-builder/:id/variations/lock-all', RECORDS],diff --git a/server/lib/README.md b/server/lib/README.mdindex 57df4698d1..c1a8342deb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -983,3 +983,15 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `runwaySpecialVideoModels.js` | Aleph 2 video-edit and Act-Two character-performance capabilities, schema compatibility and request validation. || `codeReviewBatches.js` | File-boundary code-review batching with byte-exact diff hashes, candidate revision, reviewed/remaining file identifiers, bounded calls and one shared wall-clock budget. Preserves validated findings when coverage is incomplete and classifies explicit context-capacity refusals without retaining vendor event streams. |++| `realityStarterV1.js` | Frozen version 1 of the text-only photographic Reality starter; migration-safe. |+| `universeStarters.js` | Latest shipped universe starter text patches for explicit restoration. |++Reality starter updates: add a new frozen `realityStarterV<N>.js` text config and+point `universeStarters.js` at it. Do not change a version imported by an applied+migration. Universe Builder's **Restore latest starter** action uses that current+pointer; it replaces only starter idea, logline, premise, style notes and the+positive/negative influence lists. It preserves canon, media and local settings.+Automatic migration 440 fills only a blank, unlocked Reality; customized or+deleted records remain untouched. Future automatic upgrades need their own+migration with explicit recognition of the outgoing shipped defaults.diff --git a/server/lib/hostControlRoutes.test.js b/server/lib/hostControlRoutes.test.jsindex f821666801..bd7e354ad6 100644--- a/server/lib/hostControlRoutes.test.js+++ b/server/lib/hostControlRoutes.test.js@@ -75,6 +75,8 @@ describe('Universe Builder mutation inventory (#10669)', () => {'DELETE /api/universe-builder/:id','PATCH /api/universe-builder/:id/variations/lock-all','POST /api/universe-builder/:id/import/markdown',+ // Copies bundled text only; no provider, process or caller-selected file access.+ 'POST /api/universe-builder/:id/restore-starter','POST /api/universe-builder/:id/style-references','POST /api/universe-builder/:id/adopt-style','DELETE /api/universe-builder/:id/style-references/:referenceId',diff --git a/server/lib/index.js b/server/lib/index.jsindex 559f4e2678..b81474db66 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -970,3 +970,5 @@ export * from './runwaySpecialVideoModels.js';export * from './issueClaimEvidence.js';export * from './codeReviewBatches.js';+export * from './realityStarterV1.js';+export * from './universeStarters.js';diff --git a/server/lib/realityStarterV1.js b/server/lib/realityStarterV1.jsnew file mode 100644index 0000000000..02971462ba--- /dev/null+++ b/server/lib/realityStarterV1.js@@ -0,0 +1,11 @@+/** Frozen shipped text, version 1. Future revisions get a new versioned module. */+export const REALITY_STARTER_V1 = Object.freeze({+ starterPrompt: 'Our actual world: ordinary human lives, observed with the honesty of available-light photography and live-action cinema.',+ logline: 'Life on Earth as people actually experience it, captured with photographic honesty.',+ premise: 'This is the real world, governed by ordinary physics, biology, geography and human history. People have individual lives, cultures, relationships, limitations and contradictions. Bodies age; materials wear; spaces accumulate evidence of use. Weather, work, money, technology and social circumstances shape daily life. Establish the particular time and location for each story, then respect its clothing, architecture, equipment and customs. There is no invented cosmology, hidden supernatural system or alternate reality implied by this universe. Specific people, places and events belong to individual projects; this starter supplies no canon.',+ styleNotes: 'Aim for authentic photography and live-action cinematic realism: street photographs, documentary observation, candid family and party pictures, and dramatic scenes grounded in physical reality. Default to available light with imperfect practical sources, mixed color temperatures, uneven illumination and honest shadows. Use direct flash, harsh sunlight or staged lighting when the situation calls for it. People have natural proportions, skin texture, fine hair, asymmetry and age-specific detail. Expressions and gestures feel lived rather than posed. Materials, clothing and rooms show plausible texture, wear and clutter. Use believable lens perspective and depth of field. Let the camera and exposure have limitations: occasional motion blur, missed focus, clipped highlights or noisy shadows when motivated, without applying defects to every frame. Match capture format, grain, color response, equipment and photographic conventions to the scene’s era; avoid a decorative vintage filter. Dramatic framing and emotion should emerge from the observed scene. For video, preserve identity, physical contact, weight, spatial continuity and motivated lighting through motion.',+ influences: Object.freeze({+ embrace: Object.freeze(['authentic photography', 'live-action cinematic realism', 'candid human behavior', 'available light', 'imperfect practical lighting', 'natural skin texture and asymmetry', 'believable anatomy and aging', 'physically plausible materials', 'lived-in environments', 'credible camera optics and exposure', 'era-appropriate capture medium and color response', 'documentary observation']),+ avoid: Object.freeze(['illustration', 'cartoon or anime', 'CGI or game-engine appearance', 'plastic or waxy skin', 'beauty retouching and skin smoothing', 'doll-like faces or idealized anatomy', 'uncanny facial symmetry', 'synthetic HDR clarity', 'excessive sharpening', 'heavy cinematic color grading', 'unmotivated studio lighting', 'decorative film scratches and light leaks', 'fantasy or surreal worldbuilding', 'impossible optics and physical behavior']),+ }),+});diff --git a/server/lib/universeStarters.js b/server/lib/universeStarters.jsnew file mode 100644index 0000000000..d04a68a85b--- /dev/null+++ b/server/lib/universeStarters.js@@ -0,0 +1,7 @@+/** Current shipped starters. Only text fields are eligible for restoration. */+import { REALITY_STARTER_V1 } from './realityStarterV1.js';++export const REALITY_STARTER_ID = 'universe-reality';+export function universeStarterPatch(id) {+ return id === REALITY_STARTER_ID ? structuredClone(REALITY_STARTER_V1) : null;+}diff --git a/server/lib/universeStarters.test.js b/server/lib/universeStarters.test.jsnew file mode 100644index 0000000000..2911204d9c--- /dev/null+++ b/server/lib/universeStarters.test.js@@ -0,0 +1,17 @@+import { expect, it } from 'vitest';+import { universeStarterPatch, REALITY_STARTER_ID } from './universeStarters.js';+import { sanitizeTemplate } from '../services/universeBuilder/sanitize.js';+import { universeStylePreset } from './universeVisualStyle.js';++it('round trips shipped text and positive/negative style through the real universe schema and renderer', () => {+ const starter = universeStarterPatch(REALITY_STARTER_ID);+ const stored = sanitizeTemplate({ id: REALITY_STARTER_ID, name: 'Reality', factual: true, ...starter });+ expect(stored).toMatchObject(starter);+ const style = universeStylePreset(stored);+ expect(style.prompt).toBe(starter.influences.embrace.join(', '));+ expect(style.negativePrompt).toBe(starter.influences.avoid.join(', '));+ expect(stored.characters).toEqual([]);+ expect(stored.places).toEqual([]);+ expect(stored.objects).toEqual([]);+ expect(stored.styleImageRefs).toEqual([]);+});diff --git a/server/routes/universeBuilder/crud.js b/server/routes/universeBuilder/crud.jsindex 9a7d487957..577784aa0b 100644--- a/server/routes/universeBuilder/crud.js+++ b/server/routes/universeBuilder/crud.js@@ -9,7 +9,8 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler } from '../../lib/errorHandler.js';+import { universeStarterPatch } from '../../lib/universeStarters.js';+import { ServerError, asyncHandler } from '../../lib/errorHandler.js';import { validateRequest, llmSchema, isPaginationRequested, paginateArray } from '../../lib/validation.js';import { recordRenderPinFields } from '../../lib/sharedSchemas.js';import { pruneStaleReferenceSheets } from '../../lib/storyBible.js';@@ -145,6 +146,20 @@ router.get('/summaries', asyncHandler(async (_req, res) => {res.json(await svc.listUniverseSummaries());}));+// Revision check runs inside the record queue so a concurrent edit is preserved.+router.post('/:id/restore-starter', asyncHandler(async (req, res) => {+ const patch = universeStarterPatch(req.params.id);+ if (!patch) throw new ServerError('No shipped starter exists for this universe', { status: 404 });+ const { expectedUpdatedAt } = validateRequest(z.object({ expectedUpdatedAt: z.string().datetime() }), req.body ?? {});+ const restored = await svc.updateUniverse(req.params.id, (latest) => {+ if (latest.updatedAt !== expectedUpdatedAt) {+ throw new ServerError('Universe changed. Reload it before restoring the starter.', { status: 409 });+ }+ return patch;+ }, { touchesCanon: false }).catch(err => { throw mapServiceError(err); });+ res.json(restored);+}));+router.get('/:id', asyncHandler(async (req, res) => {// Read-by-id 404s are benign and high-volume: callers like LoraDatasetDetail// speculatively fetch a dataset's `character.universeId` ({ silent: true }),diff --git a/server/routes/universeBuilder/restoreStarter.test.js b/server/routes/universeBuilder/restoreStarter.test.jsnew file mode 100644index 0000000000..5ee7cc808f--- /dev/null+++ b/server/routes/universeBuilder/restoreStarter.test.js@@ -0,0 +1,52 @@+import { beforeEach, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import { errorMiddleware } from '../../lib/errorHandler.js';+import { REALITY_STARTER_V1 } from '../../lib/realityStarterV1.js';++let universe;+vi.mock('../../services/universeBuilder.js', async original => ({+ ...await original(),+ updateUniverse: vi.fn(async (_id, mutate) => {+ if (!universe || universe.deleted) throw Object.assign(new Error('Not found'), { code: 'NOT_FOUND' });+ universe = { ...universe, ...await mutate(universe) };+ return universe;+ }),+}));+import router from './crud.js';+const app = express();+app.use(express.json());+app.use('/universes', router);+app.use(errorMiddleware);+const stamp = '2026-01-01T00:00:00.000Z';+beforeEach(() => {+ universe = { id: 'universe-reality', updatedAt: stamp, premise: 'Custom', characters: [{ id: 'local' }], styleImageRefs: ['private.jpg'], factual: true };+});++it('restores shipped text without changing canon, media or settings', async () => {+ const response = await request(app).post('/universes/universe-reality/restore-starter').send({ expectedUpdatedAt: stamp });+ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({ ...REALITY_STARTER_V1, characters: [{ id: 'local' }], styleImageRefs: ['private.jpg'], factual: true });+ expect(Object.keys(REALITY_STARTER_V1).sort()).toEqual(['influences', 'logline', 'premise', 'starterPrompt', 'styleNotes']);+});+it('refuses a stale revision before replacing any text', async () => {+ universe.updatedAt = '2026-01-02T00:00:00.000Z';+ const response = await request(app).post('/universes/universe-reality/restore-starter').send({ expectedUpdatedAt: stamp });+ expect(response.status).toBe(409);+ expect(universe.premise).toBe('Custom');+});+it('does not offer restoration on user-created universes', async () => {+ const response = await request(app).post('/universes/custom/restore-starter').send({ expectedUpdatedAt: stamp });+ expect(response.status).toBe(404);+});+it('requires the revision', async () => {+ const response = await request(app).post('/universes/universe-reality/restore-starter').send({});+ expect(response.status).toBe(400);+});++it.each([null, { deleted: true }])('does not recreate a missing or deleted universe: %j', async record => {+ universe = record;+ const response = await request(app).post('/universes/universe-reality/restore-starter').send({ expectedUpdatedAt: stamp });+ expect(response.status).toBe(404);+ expect(universe).toEqual(record);+});