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

feat: ship a factual Reality universe and a federated factual flag on the universe record (#7616)

[._.]/ Adam Eivy3b8c7f507450
diff --git a/client/src/components/universeBuilder/UniverseBibleTab.jsx b/client/src/components/universeBuilder/UniverseBibleTab.jsx
index c202662e27..8ba30e1843 100644
--- a/client/src/components/universeBuilder/UniverseBibleTab.jsx
+++ b/client/src/components/universeBuilder/UniverseBibleTab.jsx
@@ -171,6 +171,27 @@ export default function BibleTab({
</div>
</div>
+ {/* Factual/fiction axis (#7616). Drives how the catalog extractor reads
+ material captured into this world — lived record vs invented story.
+ Part of the draft, so it saves with the normal Save action. */}
+ <div className="flex items-start gap-2">
+ <input
+ id="world-factual"
+ type="checkbox"
+ checked={draft.factual === true}
+ onChange={(e) => updateDraft({ factual: e.target.checked })}
+ className="mt-0.5 h-4 w-4 accent-port-accent"
+ />
+ <div className="min-w-0">
+ <label htmlFor="world-factual" className="text-xs text-gray-300">
+ This is a real-world universe
+ </label>
+ <p className="text-[11px] text-gray-500 mt-0.5">
+ Its people and places are real. Captured text is read as lived record, not invented story material.
+ </p>
+ </div>
+ </div>
+
{/* Persisted per-universe link (#4188): the pick lives on the record
(`moodBoardId`) and rides the normal draft Save — not localStorage —
so it survives reload, is per-universe, and syncs to peers. */}
diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.js
index fb72c46eef..adffe7137b 100644
--- a/client/src/hooks/useUniverseDraft.js
+++ b/client/src/hooks/useUniverseDraft.js
@@ -46,6 +46,8 @@ export const createEmptyUniverseDraft = () => ({
logline: '',
premise: '',
styleNotes: '',
+ // Factual/fiction axis (#7616) — true marks a real-world universe.
+ factual: false,
moodBoardId: null,
categories: ensureDraftCategories(),
compositeSheets: [],
@@ -64,6 +66,7 @@ export const universeDraftSnapshot = (draft = {}) => JSON.stringify({
logline: draft.logline || '',
premise: draft.premise || '',
styleNotes: draft.styleNotes || '',
+ factual: draft.factual === true,
moodBoardId: draft.moodBoardId || null,
categories: draft.categories || {},
compositeSheets: draft.compositeSheets || [],
@@ -256,6 +259,9 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
logline: universe.logline || '',
premise: universe.premise || '',
styleNotes: universe.styleNotes || '',
+ // Absent on the wire means fiction — normalize so the toggle is
+ // always a controlled boolean rather than undefined.
+ factual: universe.factual === true,
moodBoardId: universe.moodBoardId || null,
influences: ensureInfluences(universe.influences),
styleReferences: universe.styleReferences || [],
@@ -282,6 +288,9 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
logline: draft.logline || '',
premise: draft.premise || '',
styleNotes: draft.styleNotes || '',
+ // Factual/fiction axis (#7616). Always shipped, like the other scalars:
+ // the server drops a literal `false` back to absent, which is the clear.
+ factual: draft.factual === true,
// Linked mood board (#4188) — null clears server-side; the field always
// ships so Save carries the full intended state like other scalars.
moodBoardId: draft.moodBoardId || null,
diff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsx
index 0f6164d5db..0c60f4b861 100644
--- a/client/src/hooks/useUniverseDraft.test.jsx
+++ b/client/src/hooks/useUniverseDraft.test.jsx
@@ -238,6 +238,24 @@ describe('useUniverseDraft', () => {
expect(result.current.isDraftDirty()).toBe(false);
});
+ it('marks the draft dirty when the factual toggle flips and ships it with Save', async () => {
+ // The regression: omitting `factual` from universeDraftSnapshot leaves the
+ // draft looking clean after the toggle, so Save is a no-op and the world
+ // silently stays fiction.
+ const { result } = renderDraft();
+ await waitFor(() => expect(result.current.draft.id).toBe('u1'));
+ expect(result.current.draft.factual).toBe(false);
+
+ act(() => result.current.updateDraft({ factual: true }));
+ expect(result.current.isDraftDirty()).toBe(true);
+ await act(async () => { await result.current.handleSave(); });
+ expect(apiMocks.updateUniverse.mock.calls.at(-1)[1].factual).toBe(true);
+
+ act(() => result.current.updateDraft({ factual: false }));
+ await act(async () => { await result.current.handleSave(); });
+ expect(apiMocks.updateUniverse.mock.calls.at(-1)[1].factual).toBe(false);
+ });
+
// The render flow keys its per-row pending-job map on the id the SERVER
// stamped onto `entryJobs`. A board or variation created in this session has
// no id until a save mints one, so without adopting it the row can never match
@@ -1212,6 +1230,7 @@ describe('useUniverseDraft', () => {
logline: '',
premise: '',
styleNotes: '',
+ factual: false,
moodBoardId: null,
categories: seededCategories(),
compositeSheets: [],
diff --git a/client/src/pages/Universes.jsx b/client/src/pages/Universes.jsx
index eb639c8818..16bf08348a 100644
--- a/client/src/pages/Universes.jsx
+++ b/client/src/pages/Universes.jsx
@@ -10,7 +10,7 @@
import { useEffect, useMemo, useState, useCallback } from 'react';
import { Link, useNavigate } from 'react-router';
-import { Plus, Globe, Trash2, Users, Workflow as WorkflowIcon, Copy } from 'lucide-react';
+import { Plus, Globe, Trash2, Users, Workflow as WorkflowIcon, Copy, BadgeCheck } from 'lucide-react';
import toast from '../components/ui/Toast';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
import ImageThumb from '../components/ui/ImageThumb';
@@ -26,6 +26,19 @@ import { useSyncIntegrity, syncBadgeStatus } from '../hooks/useSyncIntegrity';
import { useRecordMerge } from '../hooks/useRecordMerge';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
+// Chip on a universe whose `factual` flag is set (#7616): its people and
+// places are real, so captured text is extracted as lived record rather than
+// as invented story material. Rendered beside the name in both list layouts.
+const FactualBadge = () => (
+ <span
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-port-accent/15 text-port-accent border border-port-accent/30"
+ title="Real-world universe — captured text is read as lived record, not invented story material"
+ >
+ <BadgeCheck size={10} />
+ Real
+ </span>
+);
+
// Build universeId → latest image filename from media collections. Mirrors
// resolveCover() in MediaCollections.jsx but trimmed: we only care about image
// items (videos don't render as a row thumbnail here) and the bucket is
@@ -275,6 +288,7 @@ export default function Universes() {
<div className="text-white font-medium flex items-center gap-2 flex-wrap group-hover:text-port-accent transition-colors">
<span>{u.name || '(untitled universe)'}</span>
{u.origin ? <OriginBadge origin={u.origin} compact /> : null}
+ {u.factual ? <FactualBadge /> : null}
</div>
{u.logline ? (
<div className="text-xs text-gray-500 mt-0.5 line-clamp-1 break-words">{u.logline}</div>
@@ -314,6 +328,7 @@ export default function Universes() {
<div className="text-white font-medium flex items-center gap-2 flex-wrap">
<span>{u.name || '(untitled universe)'}</span>
{u.origin ? <OriginBadge origin={u.origin} compact /> : null}
+ {u.factual ? <FactualBadge /> : null}
</div>
{u.logline ? (
<div className="text-xs text-gray-500 mt-0.5 break-words">{u.logline}</div>
diff --git a/client/src/pages/Universes.test.jsx b/client/src/pages/Universes.test.jsx
index 19f3f2a7ea..ff259f921b 100644
--- a/client/src/pages/Universes.test.jsx
+++ b/client/src/pages/Universes.test.jsx
@@ -151,3 +151,23 @@ describe('Universes page — row thumbnail', () => {
expect(img.getAttribute('src')).toContain('fallback.png');
});
});
+
+describe('Universes page — factual badge (#7616)', () => {
+ beforeEach(() => {
+ api.listUniverseDuplicates.mockResolvedValue({ groups: [] });
+ api.listMediaCollections.mockResolvedValue([]);
+ });
+
+ it('badges only the universes whose factual flag is set', async () => {
+ api.listUniverseSummaries.mockResolvedValue([
+ { id: 'universe-reality', name: 'Reality', factual: true, updatedAt: '2026-06-02T00:00:00Z', createdAt: '2026-06-02T00:00:00Z' },
+ { id: 'u-fiction', name: 'Example Universe', factual: false, updatedAt: '2026-06-01T00:00:00Z', createdAt: '2026-06-01T00:00:00Z' },
+ ]);
+ renderPage();
+ await waitFor(() => expect(screen.getAllByText('Example Universe').length).toBeGreaterThan(0));
+ // One badge per layout (desktop table + mobile cards), and none for the
+ // fiction world — the regression is a badge keyed on truthiness of a field
+ // the summary projection omits, which would mark every universe real.
+ expect(screen.getAllByText('Real')).toHaveLength(2);
+ });
+});
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 4481e3d5d6..17de807e16 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -37,7 +37,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `user_action_events` — the operator-action ledger (#5594, epic #5593): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings; phase 3 / #5596 also records event-only creative/Brain pointers, instance-feature toggles, and CoS schedule updates that skip `PUT /api/settings`). The leftover-branch idle detector is a **consumer** of this ledger (plus live git state), not a store of its own. `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and PII must not ride the federation layer (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).
- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
-- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.
+- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`. **One universe ships with the product:** `universe-reality` ("Reality"), seeded by `scripts/migrations/395-reality-universe-seed.js` — not by `data.reference/`, because universes are PG rows and `setup-data.js` only copies files. It carries the federated `factual: true` flag (#7616), which marks a world whose people and places are real so the catalog extractor reads captured text as lived record rather than invented story; `factual` is persisted ONLY when true, so every fiction universe keeps its exact on-disk shape and wire checksum, and `PORTOS_SCHEMA_VERSIONS.universes` is 12 so a `factual`-unaware peer cannot strip-then-LWW the flag away. The migration gates on the ABSENCE of any row with that id — tombstone included — so a Reality the user deleted is never resurrected by an upgrade.
- `voice_profiles` / `voice_profile_renders` — machine-local DB-primary records for approved `(universeId, characterId)` bindings and the latest rendered dialogue line per `(issueId, lineId)`. They store the promoted Kokoro/Piper preset, profile revision, route availability, benchmark provenance, and reproducible dialogue delivery details (engine/model revision, timing, controls, and mastering). The portable Universe character and federated pipeline issue keep only portable voice data and audio filenames; they never store a local profile id. Rendered benchmark WAVs, safe-basename source-asset metadata, and future local engine artifacts live under `data/voice-profiles/<profileId>/`. Both the PostgreSQL dump and that managed directory are included in normal backup, while peer sync intentionally carries neither. Adapter: `server/services/voice/profiles.js`.
- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. Adapter: `server/services/tribe.js`.
- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The brief/identity federates as `creativeCommission` so synced feedback can attach to the same commission; `schedule`, `runs`, `assignment`, `enabled`, and feedback view stay machine-local (the per-reaction `commissionFeedback` records federate separately). The opt-in Digital Twin music-taste configuration is bounded brief metadata; raw taste sources and per-run recipes never cross the wire. The file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).
diff --git a/scripts/migrations/395-reality-universe-seed.js b/scripts/migrations/395-reality-universe-seed.js
new file mode 100644
index 0000000000..d7b2be33e4
--- /dev/null
+++ b/scripts/migrations/395-reality-universe-seed.js
@@ -0,0 +1,72 @@
+/**
+ * Seed the shipped `Reality` universe (#7616, epic #7609).
+ *
+ * Factual/autobiographical capture had no home: every universe was fiction, so
+ * a voice memo or a journal entry got extracted through a story lens. Phase 2
+ * put a `factual` flag on the universe record; this migration gives every
+ * install one factual world from first boot, so the flag has something to be
+ * true of.
+ *
+ * Why a MIGRATION and not a `data.reference/` seed: universes are Postgres
+ * rows (`server/lib/db/schema/universes.js`), and `scripts/setup-data.js` only
+ * copies files into `data/`. There is no `data/universes/` file to seed on a
+ * PG install, so the seeding mechanism has to be code that writes a row. Note
+ * this is NOT the "derived from the install's own records" case that
+ * `scripts/lib/migrationOwnedPaths.js` governs — that list is about `data/`
+ * FILE paths, and this migration writes no file at all.
+ *
+ * Shape decisions:
+ * - **Deterministic id `universe-reality`** (matches `UNIVERSE_ID_RE`), not
+ * a `randomUUID()`. A user commonly federates several machines; each one
+ * runs this migration itself, and a random id would give them one Reality
+ * per install that then all sync to each other. One fixed id makes the
+ * copies converge on a single record under the normal LWW merge.
+ * - **Empty logline / premise / styleNotes.** Reality is the user's own
+ * life; inventing copy for it would be wrong, and generating copy is
+ * barred outright — AGENTS.md "No cold-bootstrap LLM calls" rules out an
+ * LLM call on a boot path.
+ * - **Not `ephemeral`**, so it federates like any other universe.
+ *
+ * Re-run safety: the applied-list already stops a second run, but the record
+ * check is the real guard — an install can also reach this code with the row
+ * already synced in from a peer.
+ *
+ * TOMBSTONE CONTRACT (the subtle part): the check is "does ANY row exist with
+ * this id", `deleted` true or false — not "is there a live row". A user who
+ * deleted Reality must not have it resurrected by the next upgrade, and a
+ * tombstone is exactly the record of that decision. `insertUniverseWithId`
+ * deliberately OVERWRITES a tombstone (its `wasResurrection` branch), which is
+ * right for a share-bucket re-import and wrong here, so the emptiness check
+ * lives here rather than as a `resurrect: false` option on the shared importer.
+ */
+
+import { store, insertUniverseWithId } from '../../server/services/universeBuilder.js';
+
+export const REALITY_UNIVERSE_ID = 'universe-reality';
+const REALITY_UNIVERSE_NAME = 'Reality';
+
+export default {
+ async up() {
+ // loadOneRaw, not loadOne: the raw read returns the stored row untouched,
+ // including a tombstone, which is the thing we must not write over.
+ const existing = await store().loadOneRaw(REALITY_UNIVERSE_ID);
+ if (existing) {
+ const why = existing.deleted ? 'deleted by the user' : 'already present';
+ console.log(`🌍 migration 395: Reality universe ${why} — leaving it alone`);
+ return { updated: 0, reason: existing.deleted ? 'tombstoned' : 'already-seeded' };
+ }
+
+ await insertUniverseWithId({
+ id: REALITY_UNIVERSE_ID,
+ name: REALITY_UNIVERSE_NAME,
+ factual: true,
+ // Left blank deliberately — see the header. The user fills these in.
+ starterPrompt: '',
+ logline: '',
+ premise: '',
+ styleNotes: '',
+ });
+ console.log(`🌍 migration 395: seeded the factual "${REALITY_UNIVERSE_NAME}" universe (${REALITY_UNIVERSE_ID})`);
+ return { updated: 1 };
+ },
+};
diff --git a/scripts/migrations/395-reality-universe-seed.test.js b/scripts/migrations/395-reality-universe-seed.test.js
new file mode 100644
index 0000000000..50ee1235d2
--- /dev/null
+++ b/scripts/migrations/395-reality-universe-seed.test.js
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// The migration writes a PostgreSQL row through the universe store, so the
+// store is the boundary to double. What these tests pin is the decision the
+// migration makes ABOUT that boundary — specifically that a tombstone is
+// treated as "the user deleted this", which `insertUniverseWithId` itself
+// would happily overwrite.
+const loadOneRaw = vi.fn();
+const insertUniverseWithId = vi.fn();
+vi.mock('../../server/services/universeBuilder.js', () => ({
+ store: () => ({ loadOneRaw }),
+ insertUniverseWithId: (...args) => insertUniverseWithId(...args),
+}));
+
+const { default: migration, REALITY_UNIVERSE_ID } = await import('./395-reality-universe-seed.js');
+
+describe('migration 395 — Reality universe seed', () => {
+ beforeEach(() => {
+ loadOneRaw.mockReset();
+ insertUniverseWithId.mockReset();
+ });
+
+ it('seeds one live factual Reality with the deterministic id and no invented copy', async () => {
+ loadOneRaw.mockResolvedValue(null);
+
+ await expect(migration.up({})).resolves.toEqual({ updated: 1 });
+
+ expect(insertUniverseWithId).toHaveBeenCalledTimes(1);
+ const seeded = insertUniverseWithId.mock.calls[0][0];
+ expect(seeded).toMatchObject({
+ id: REALITY_UNIVERSE_ID,
+ name: 'Reality',
+ factual: true,
+ logline: '',
+ premise: '',
+ styleNotes: '',
+ });
+ // Reality must federate like any other universe — an ephemeral seed would
+ // give each of the user's machines its own private copy.
+ expect(seeded.ephemeral).toBeUndefined();
+ });
+
+ it('does NOT resurrect a Reality the user deleted', async () => {
+ loadOneRaw.mockResolvedValue({ id: REALITY_UNIVERSE_ID, name: 'Reality', deleted: true });
+
+ await expect(migration.up({})).resolves.toEqual({ updated: 0, reason: 'tombstoned' });
+ expect(insertUniverseWithId).not.toHaveBeenCalled();
+ });
+
+ it('no-ops when the row is already present (re-run, or synced in from a peer)', async () => {
+ loadOneRaw.mockResolvedValue({ id: REALITY_UNIVERSE_ID, name: 'Reality', deleted: false });
+
+ await expect(migration.up({})).resolves.toEqual({ updated: 0, reason: 'already-seeded' });
+ expect(insertUniverseWithId).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 6a4e250911..cf734f34f6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -160,7 +160,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `seriesLlmOverride.js` | Pure `resolveSeriesLlmOverride(series, { overrideProvider, overrideModel })` → `{ provider, model, providerMatchesSeries }` — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches. |
| `catalogBulkParsers.js` | Dependency-free markdown/CSV/JSON parsers for `POST /api/catalog/bulk-import` and YAML/markdown serializers for `GET /api/catalog/export`. |
| `catalogChunking.js` | Pure lossless scrap-text chunker (`chunkRawText`, `CATALOG_CHUNK_MAX_CHARS`) — splits a long paste into ≤maxChars chunks on paragraph/newline/sentence/whitespace boundaries so the catalog extractor processes each child and unions results. |
-| `catalogSourceKinds.js` | Catalog scrap SOURCE-KIND registry — one `{ id, label, factual }` entry per ingest path that mints a `catalog_scraps` row. A pure leaf (no zod, no db) so the extractor can read a path's lens without pulling the validation layer in behind it. `SCRAP_SOURCE_KIND_IDS` is the id list `catalogValidation.js` builds its local-ingest Zod enum from; `isFactualSourceKind(id)` answers "is this lived material rather than invented fiction?" and gates the `{{#factual}}` sections in the four catalog extraction prompts — an unknown kind (including one a newer peer synced in) reads as non-factual, which is the pre-#7609 behavior. Declaring the lens beside the id is what stops a new ingest source silently extracting a memoir as fictional role tags. |
+| `catalogSourceKinds.js` | Catalog scrap SOURCE-KIND registry — one `{ id, label, factual }` entry per ingest path that mints a `catalog_scraps` row. A pure leaf (no zod, no db) so the extractor can read a path's lens without pulling the validation layer in behind it. `SCRAP_SOURCE_KIND_IDS` is the id list `catalogValidation.js` builds its local-ingest Zod enum from; `isFactualSourceKind(id)` answers "is this lived material rather than invented fiction?" and gates the `{{#factual}}` sections in the four catalog extraction prompts — an unknown kind (including one a newer peer synced in) reads as non-factual, which is the pre-#7609 behavior. The universe record carries its own federated `factual` flag (#7616, set on the shipped `universe-reality` world); it becomes the primary signal once ingest is bound to a universe (#7615). Declaring the lens beside the id is what stops a new ingest source silently extracting a memoir as fictional role tags. |
| `catalogTypes.js` | Shared catalog ingredient TYPE REGISTRY — one entry per type drives validation enum, ID prefix, FTS field set, extraction shape, per-record `payloadSchemaVersion` + upgraders, per-type `defaultTags`. Also exports the relation-kind registry and the tag-taxonomy helpers (`canonicalTagKey`, `tagIdForKey`, `defaultTagsForType`). The client projects its UI registry from this one (`client/src/lib/catalogTypes.js`) rather than copying it. |
| `catalogUniverseTags.js` | Pure transform that rewrites legacy machine universe tags (`from-universe`, `universe:<id>`) on backfilled catalog ingredients into friendly universe-NAME tags, preserving user tags + the structured `catalog_ingredient_refs` link. Used by the boot-time repair and the bible→catalog backfill. |
| `comicScriptParser.js` | Marvel/DC-format comic script parser. |
diff --git a/server/lib/catalogSourceKinds.js b/server/lib/catalogSourceKinds.js
index 1fbfadd73c..a58ea51e76 100644
--- a/server/lib/catalogSourceKinds.js
+++ b/server/lib/catalogSourceKinds.js
@@ -12,9 +12,11 @@
* `factual: true` means the path produces the user's own lived capture (a
* memoir, journal entry, or recorded thought about real people and places)
* rather than invented story material. It drives the `{{#factual}}` sections
- * in the four catalog extraction prompts. Phase 2 of #7609 binds ingest to a
- * universe whose own `factual` flag becomes the primary signal, with the
- * source kind as the fallback for a scrap catalogued into no universe.
+ * in the four catalog extraction prompts. The universe record now carries its
+ * own `factual` flag too (#7616, shipped on the seeded `universe-reality`
+ * world); once ingest is bound to a universe (#7615) that flag becomes the
+ * primary signal, with the source kind as the fallback for a scrap catalogued
+ * into no universe.
*/
export const SCRAP_SOURCE_KINDS = Object.freeze([
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index a863d5d721..2c2cb62e38 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -79,7 +79,13 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// `sanitizeCharacter` would strip the profile and last-writer-wins the loss
// back onto the newer peer. Per-category gate → only universe sync pauses
// with old peers.
- universes: 11,
+ // v12 = universe `factual` added (#7616) — the factual/fiction axis that
+ // tells the catalog extractor to read a world's material as lived record
+ // rather than invented story. Persisted only when true, but federated: a
+ // <=v11 peer would strip it in its `factual`-unaware `sanitizeTemplate`
+ // and last-writer-wins the loss back, silently reclassifying the user's
+ // Reality universe as fiction.
+ universes: 12,
// v1 = post-split. Migrations 035/036 introduced the pipeline collection
// layout for issues and series.
// v2 = `stages.audio.audioMode` + `stages.audio.cues[]` added (whole-episode
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index 248c2b92a0..0310796401 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -21,10 +21,11 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
// v6 = canon characters gained relationshipLinks[] (#1287); v7 = canon
// objects gained attachments[] (#1288); v8 adds styleReferences[]; v9 adds
// moodBoardId (#4188); v10 adds character production packages (#5378);
- // v11 adds the optional character psychology profile (#6414).
+ // v11 adds the optional character psychology profile (#6414);
+ // v12 adds the universe factual flag (#7616).
// These are additive + version-gated so an older peer
// cannot strip-then-LWW them.
- expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(11);
+ expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(12);
});
it('declares pipeline collection layout versions', () => {
@@ -61,14 +62,14 @@ describe('buildPortosMeta', () => {
it('returns { portosVersion, schemaVersions } with the live registry', async () => {
const meta = await buildPortosMeta();
expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);
- expect(meta.schemaVersions.universes).toBe(11);
+ expect(meta.schemaVersions.universes).toBe(12);
expect(meta.schemaVersions.pipelineIssues).toBe(3);
expect(meta.schemaVersions.pipelineSeries).toBe(14);
});
it('overrides merge into schemaVersions', async () => {
const meta = await buildPortosMeta({ schemaVersions: { future: 1 } });
- expect(meta.schemaVersions.universes).toBe(11);
+ expect(meta.schemaVersions.universes).toBe(12);
expect(meta.schemaVersions.future).toBe(1);
});
});
diff --git a/server/routes/universeBuilder/crud.js b/server/routes/universeBuilder/crud.js
index 4ad008d6b2..9a7d487957 100644
--- a/server/routes/universeBuilder/crud.js
+++ b/server/routes/universeBuilder/crud.js
@@ -60,6 +60,8 @@ const createSchema = z.object({
// Per-record render pin (#3231 Phase 3) — this universe's default image
// backend + cloud model.
...recordRenderPinFields,
+ // Factual/fiction axis (#7616) — true marks a real-world universe.
+ factual: z.boolean().optional(),
// Local-only "don't sync to peers" marker — see sanitizeRecordForWire.
ephemeral: z.boolean().optional(),
});
@@ -102,6 +104,9 @@ const patchSchema = z.object({
// Per-record render pin (#3231 Phase 3). Key-present with 'auto'/''/null
// clears; key-absent preserves.
...recordRenderPinFields,
+ // Factual/fiction axis (#7616). Only a literal `true` marks the universe
+ // factual; `false` clears it back to absent (see sanitizeTemplate).
+ factual: z.boolean().optional(),
ephemeral: z.boolean().optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 1502cf8332..e18611d469 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -163,19 +163,19 @@ describe('dataSync — universe category', () => {
const snap = await dataSync.getSnapshot('universe');
expect(snap.portosMeta).toBeDefined();
expect(typeof snap.portosMeta.portosVersion).toBe('string');
- expect(snap.portosMeta.schemaVersions.universes).toBe(11);
+ expect(snap.portosMeta.schemaVersions.universes).toBe(12);
});
it('applyRemote rejects when sender schemaVersions are AHEAD of local code', async () => {
writeUniverseState({ universes: [], runs: [] });
const result = await dataSync.applyRemote('universe', {
universes: [{ id: 'u-new', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }],
- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 12 } } });
+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 13 } } });
expect(result.applied).toBe(false);
expect(result.count).toBe(0);
expect(result.blockedBySchema).toBeDefined();
expect(result.blockedBySchema.ahead).toEqual([
- { category: 'universes', senderV: 12, receiverV: 11 },
+ { category: 'universes', senderV: 13, receiverV: 12 },
]);
expect(result.blockedBySchema.senderPortosVersion).toBe('99.0.0');
// Nothing was written.
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 2c77bbb1e4..31ba3f2263 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2362,7 +2362,7 @@ describe('sharing round-trip', () => {
const exp = await exporter.exportSeries(s.id, bucket.id);
const manifest = JSON.parse(readFileSync(join(tempBucket, 'manifests', exp.filename), 'utf-8'));
expect(manifest.portosSchemaVersions).toBeDefined();
- expect(manifest.portosSchemaVersions.universes).toBe(11);
+ expect(manifest.portosSchemaVersions.universes).toBe(12);
});
it('preserves character production packages when an older peer wins universe LWW', async () => {
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 38f422cda4..a3b8f26b11 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3788,17 +3788,17 @@ describe('peerSync', () => {
describe('receiver — applyIncomingPush', () => {
it('rejects when sender schemaVersions.universes is AHEAD of local code', async () => {
- // Local code is at universes:11 (see server/lib/schemaVersions.js).
- // A push from a sender on universes:12 must NOT touch local state.
+ // Local code is at universes:12 (see server/lib/schemaVersions.js).
+ // A push from a sender on universes:13 must NOT touch local state.
const rejection = await applyIncomingPush({
kind: 'universe',
record: { id: 'u1', name: 'Foo' },
assetManifest: [],
sourceInstanceId: 'peer-a',
- portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 12 } },
+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 13 } },
}).catch((err) => err);
expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');
- expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 12, receiverV: 11 }]);
+ expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 13, receiverV: 12 }]);
expect(rejection.details.senderPortosVersion).toBe('99.0.0');
// Receiver MUST stamp its OWN PortOS version so the sender can show
// the user "peer X is on PortOS vY" — without this, the sender would
@@ -4091,7 +4091,7 @@ describe('peerSync', () => {
expect(call).toBeDefined();
const body = JSON.parse(call[1].body);
expect(body.portosMeta).toBeDefined();
- expect(body.portosMeta.schemaVersions.universes).toBe(11);
+ expect(body.portosMeta.schemaVersions.universes).toBe(12);
expect(typeof body.portosMeta.portosVersion).toBe('string');
});
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index a7d22808bb..729dc59c05 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -183,6 +183,7 @@ describe("universeBuilder service", () => {
expect(summaries).toEqual(full.map((u) => ({
id: u.id, name: u.name, logline: u.logline, starterPrompt: u.starterPrompt.slice(0, svc.LOGLINE_MAX).trim(),
origin: u.origin, createdAt: u.createdAt, updatedAt: u.updatedAt,
+ factual: u.factual === true,
canonCount: u.characters.length + u.places.length + u.objects.length,
styleImageRef: u.styleImageRefs.at(-1) || null,
})));
@@ -2521,6 +2522,34 @@ describe("universeBuilder service", () => {
});
});
+ describe("factual flag (#7616)", () => {
+ it("persists `factual` only when true, leaving a fiction universe byte-identical", async () => {
+ const base = {
+ id: "w-factual", name: "Example Universe",
+ schemaVersion: svc.CURRENT_SCHEMA_VERSION, createdAt: "2024-01-01T00:00:00Z",
+ };
+ // The regression this catches: persisting `factual: false` would add a key
+ // to EVERY existing universe's record, changing the wire checksum that
+ // peer sync and the conflict journal both hash — so every untouched world
+ // would look edited on the next sync.
+ const fiction = svc.sanitizeTemplate(base);
+ expect("factual" in fiction).toBe(false);
+ expect(JSON.stringify(svc.sanitizeTemplate({ ...base, factual: false })))
+ .toBe(JSON.stringify(fiction));
+ expect(svc.sanitizeTemplate({ ...base, factual: true }).factual).toBe(true);
+ });
+
+ it("round-trips the flag through create and PATCH, and `false` clears it", async () => {
+ const u = await svc.createUniverse({ name: "Reality", factual: true });
+ expect(u.factual).toBe(true);
+ expect((await svc.getUniverse(u.id)).factual).toBe(true);
+
+ const cleared = await svc.updateUniverse(u.id, { factual: false });
+ expect("factual" in cleared).toBe(false);
+ expect(await svc.updateUniverse(u.id, { factual: true })).toMatchObject({ factual: true });
+ });
+ });
+
describe("entry ids + render history", () => {
it("sanitizeTemplate mints stable ids for variations + composite sheets", async () => {
const u = await svc.createUniverse({
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index 008f7e817c..ebafcb2ffd 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -89,6 +89,8 @@ export async function listUniverseSummaries() {
// Importer only needs a one-line subtitle, never the full starter treatment.
starterPrompt: trimTo(u.starterPrompt, LOGLINE_MAX).trim(),
origin: u.origin, createdAt: u.createdAt, updatedAt: u.updatedAt,
+ // Factual/fiction axis (#7616) — the list badges a real-world universe.
+ factual: u.factual === true,
canonCount: row.legacyRecord
? u.characters.length + u.places.length + u.objects.length
: row.canonCount,
@@ -290,6 +292,9 @@ export async function createUniverse(input = {}) {
ephemeral: input.ephemeral === true,
// Importer-orphan marker (issue #727) — see sanitizeTemplate.
importDraft: input.importDraft === true,
+ // Factual/fiction axis (#7616) — see sanitizeTemplate. Persisted only
+ // when true, so a fiction universe's on-disk shape is unchanged.
+ factual: input.factual === true,
});
// Persist through the facade (backend-agnostic). We're inside the per-id
// queue, and writeRecord does NOT re-queue, so this can't deadlock.
@@ -519,6 +524,11 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
// promotion via `{ importDraft: false }`; the sanitizer drops every
// non-`true` value back to absent, mirroring `ephemeral`.
'importDraft',
+ // Factual/fiction axis (#7616). Same one-directional sanitizer contract
+ // as `ephemeral`/`importDraft`: only a literal `true` marks the universe
+ // factual, and key-present-with-`false` clears it back to absent (which
+ // is exactly what the settings toggle sends when it is switched off).
+ 'factual',
];
const scalarPatch = Object.fromEntries(
PATCHABLE_SCALARS.filter((k) => k in patch).map((k) => [k, patch[k]]),
diff --git a/server/services/universeBuilder/db.js b/server/services/universeBuilder/db.js
index 70ca130f96..4a740cf6ef 100644
--- a/server/services/universeBuilder/db.js
+++ b/server/services/universeBuilder/db.js
@@ -105,6 +105,7 @@ export async function listSummaries() {
data->>'logline' AS logline,
left(btrim(data->>'starterPrompt'), $1) AS "starterPrompt",
data->'origin' AS origin,
+ (data->>'factual')::boolean AS factual,
data->>'createdAt' AS "createdAt",
data->>'updatedAt' AS "updatedAt",
data->'styleImageRefs'->>-1 AS "styleImageRef",
diff --git a/server/services/universeBuilder/sanitize.js b/server/services/universeBuilder/sanitize.js
index 12e04b7530..488dbb579f 100644
--- a/server/services/universeBuilder/sanitize.js
+++ b/server/services/universeBuilder/sanitize.js
@@ -753,6 +753,16 @@ export const sanitizeTemplate = (raw) => {
// existing universe keeps its on-disk shape) and kept ON the wire —
// `universes` v9 gates it against strip-then-LWW by older peers.
...(moodBoardId ? { moodBoardId } : {}),
+ // Factual/fiction axis (#7616). `true` means this world is the real one —
+ // the user's own life, people and places — so the catalog extractor reads
+ // its material as lived record rather than invented story material.
+ // Persisted ONLY when true (like `ephemeral`/`importDraft`) so every
+ // existing universe keeps its exact on-disk shape and wire checksum.
+ // Unlike those two this field IS federated: a world's factual nature is a
+ // property of the world, not of one machine. `universes` v12 gates it, or
+ // a ≤v11 peer would sanitize it away and LWW the loss back, silently
+ // reclassifying the user's Reality universe as fiction.
+ ...(raw.factual === true ? { factual: true } : {}),
// Base "style probe" renders — images generated from the raw style preset
// (influences embrace/avoid + styleNotes) with NO subject, so the user can
// see the world's base visual emphasis. Additive + regenerable; sanitized