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
train LoRAs for universe objects and places, not just characters
[._.]/ Adam Eivyeacc80b247e9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2ce83422ac..ae5459ae1c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Train a LoRA for any universe-bible subject — objects and places, not just characters** — LoRA training datasets were hardwired to a universe's `characters`; you couldn't build an adapter for a signature weapon, artifact, or location. Datasets now carry an **`entryKind`** (`characters` / `objects` / `places`) alongside the entry id, so the find-or-create / reassignment key is the full `(universeId, entryKind, entryId)` tuple — the same entry id can own one dataset per kind, and a run can't re-own a dataset that was reassigned to a different kind. The "New dataset" and "Reassign" dialogs gain a **Subject type** select (the picker reads `universe[entryKind]` and resets the entry when either the universe or the kind changes); the generate-batch dialog relabels its variation axes per kind (Expressions/Outfits for characters, Lighting/Settings for objects & places) and the prompt builder renders single-object / single-location training prompts (with kind-specific negative prompts) instead of the character figure layout. The record sanitizer defaults a missing `entryKind` to `characters`, so existing datasets and older clients keep working with no migration. (`server/lib/loraDataset.js`, `server/services/loraDatasets.js`, `server/services/loraDatasetGenerate.js`, `server/services/loraTraining/{index,sidecar}.js`, `server/routes/loraDatasets.js`, `client/src/components/loraTraining/{UniverseCharacterPicker,GenerateBatchDialog,TrainingPanel,CharacterLoraChip}.jsx`, `client/src/pages/{LoraTraining,LoraDatasetDetail}.jsx`, `client/src/services/apiLoraTraining.js`)+- **Choose your embedding provider + model in Brain config, and reprocess on demand** — Memory's semantic search (pgvector) was hardwired to LM Studio with a fixed embedding model name, so an install running **Ollama** got silent embedding failures — records imported/captured fine but landed with a NULL embedding (unsearchable), and there was no UI to point embeddings elsewhere. Brain → Config gains an **Embeddings (semantic search)** card: pick the embedding **provider** (any OpenAI-compatible backend — Ollama, LM Studio, …) and **model** (e.g. `nomic-embed-text` on Ollama, 768-dim — matches the `vector(768)` column), with a live reachability/model-present status line and a **Reprocess all embeddings** button that re-embeds every brain record (the existing `bridge-sync?refresh` path, which drains sequentially in the background). The embedding service is now **provider-aware**: the LM-Studio-only model discover/load dance (`/api/v0/models` + `/api/v1/models/load`) is skipped for other backends (which serve `/v1/embeddings` directly and don't implement those endpoints — previously it 404'd every call and never latched), and a non-LM-Studio provider's configured model id is authoritative instead of being guessed from a substring match. (`server/services/memoryEmbeddings.js`, `client/src/components/brain/tabs/ConfigTab.jsx`)- **Import your whole ChatGPT export — images, voice clips, and files included** — The Brain → Import ChatGPT wizard now takes the **entire export `.zip`** instead of just `conversations.json`, removing the old 50 MB upload cap (the JSON was parsed in the browser and POSTed as a body; the ZIP streams straight to your PortOS like the Apple Health importer, with no size limit). It handles the **modern multi-file export** (conversations split across `conversations-NNN.json` shards) and **extracts every asset** — the `.dat` image / voice-audio / PDF files — into a served directory, sniffing each file's real type from its magic bytes and naming it from the export's asset map. Each conversation's archived transcript is rendered as **markdown with inline images** (`image_asset_pointer` parts resolve to the extracted image), plus `🔊`/`🎙️` links for voice clips and `📎` links for attached files; assets ChatGPT omitted from the export degrade to a plain placeholder rather than a broken link. Imported conversations render rich in Brain → Memory with a **View full conversation** viewer (the Memory entry keeps a truncated preview; the full thread + assets live in the archive). A lone `conversations.json` still works as before (just without images). (`server/services/chatgptZipImport.js`, `server/services/chatgptImport.js`, `server/routes/brainImport.js`, `server/lib/fileUtils.js`, `server/index.js`, `client/src/components/brain/tabs/ImportTab.jsx`, `client/src/components/brain/tabs/MemoryTab.jsx`, `client/src/components/brain/ConversationViewer.jsx`, `client/src/components/cos/MarkdownOutput.jsx`, `client/src/services/apiBrain.js`)diff --git a/client/src/components/loraTraining/CharacterLoraChip.jsx b/client/src/components/loraTraining/CharacterLoraChip.jsxindex c875d870bc..2d744f0834 100644--- a/client/src/components/loraTraining/CharacterLoraChip.jsx+++ b/client/src/components/loraTraining/CharacterLoraChip.jsx@@ -29,7 +29,7 @@ export default function CharacterLoraChip({ entryId, ingredientId, universeId, sconst canCreate = !!(universeId && entryId);useEffect(() => {if (canCreate || (!entryId && !ingredientId)) return;- listLoraDatasets(entryId ? { entryId } : { ingredientId })+ listLoraDatasets(entryId ? { entryKind: 'characters', entryId } : { entryKind: 'characters', ingredientId }).then((list) => setExistingDataset(list?.[0] || null)).catch(() => {});}, [canCreate, entryId, ingredientId]);diff --git a/client/src/components/loraTraining/GenerateBatchDialog.jsx b/client/src/components/loraTraining/GenerateBatchDialog.jsxindex 99e08ee9e1..10524147c6 100644--- a/client/src/components/loraTraining/GenerateBatchDialog.jsx+++ b/client/src/components/loraTraining/GenerateBatchDialog.jsx@@ -1,6 +1,6 @@/*** Generate-batch dialog — count + optional variation-axis overrides- * (views/expressions/outfits prefilled from the character's canon when the+ * (views/expressions/outfits prefilled from the subject's canon when the* caller passes them). Submits to POST /api/lora-datasets/:id/generate.*/@@ -18,6 +18,7 @@ import { generateLoraDatasetImages } from '../../services/api';const RECOMMENDED_TRAINING_IMAGES = 20;const TRAINING_IMAGE_SWEET_SPOT_MAX = 30;const MAX_BATCH_IMAGES = 40;+const subjectKind = (dataset) => dataset?.character?.entryKind || 'characters';const ChipToggleList = ({ idPrefix, label, options, selected, onToggle }) => (<div>@@ -50,6 +51,7 @@ export default function GenerateBatchDialog({ dataset, expressionOptions = [], oconst [expressions, setExpressions] = useState(expressionOptions);const [outfits, setOutfits] = useState(outfitOptions);const [submitting, setSubmitting] = useState(false);+ const isCharacter = subjectKind(dataset) === 'characters';const toggle = (setter) => (value) =>setter((prev) => (prev.includes(value) ? prev.filter((v) => v !== value) : [...prev, value]));@@ -82,8 +84,8 @@ export default function GenerateBatchDialog({ dataset, expressionOptions = [], oGenerate reference images — {dataset.character?.name}</h2><p className="text-sm text-gray-400">- Renders single-subject training images from the character's canon, varying view, pose,- expression, and outfit. Renders queue on the image lane; results stream into the dataset.+ Renders single-subject training images from the universe bible, varying view, composition,+ lighting, and context. Renders queue on the image lane; results stream into the dataset.</p><div><label htmlFor="lt-gen-count" className="block text-sm text-gray-400 mb-1">Images ({count})</label>@@ -104,7 +106,7 @@ export default function GenerateBatchDialog({ dataset, expressionOptions = [], o{expressionOptions.length > 0 && (<ChipToggleListidPrefix="lt-exp"- label="Expressions"+ label={isCharacter ? 'Expressions' : 'Lighting'}options={expressionOptions}selected={expressions}onToggle={toggle(setExpressions)}@@ -113,7 +115,7 @@ export default function GenerateBatchDialog({ dataset, expressionOptions = [], o{outfitOptions.length > 0 && (<ChipToggleListidPrefix="lt-outfit"- label="Outfits"+ label={isCharacter ? 'Outfits' : 'Settings'}options={outfitOptions}selected={outfits}onToggle={toggle(setOutfits)}diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsxindex 0a3b8c8e23..3fea9e2c2e 100644--- a/client/src/components/loraTraining/TrainingPanel.jsx+++ b/client/src/components/loraTraining/TrainingPanel.jsx@@ -51,27 +51,29 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun}, []);// A reassigned dataset keeps its id but its old runs belong to the previous- // character. Re-fetch (and re-filter) whenever the character identity moves,+ // subject. Re-fetch (and re-filter) whenever the subject identity moves,// not just the id, and show only runs matching the current (universeId,// entryId) so the panel + checkpoint picker can't surface/promote a stale- // run from the prior character.+ // run from the prior subject.const charEntryId = dataset.character?.entryId;const charUniverseId = dataset.character?.universeId;+ const charEntryKind = dataset.character?.entryKind || 'characters';const refreshRuns = useCallback(() => {- // Filter by the current character on the SERVER (characterId = entryId) so- // the row limit applies to this character's runs — not to other-character- // runs left over on the same dataset id after a reassignment (which a- // client-side filter-after-limit would drop). The client guard then matches- // the full (universeId, entryId) key the dataset store uses, and tolerates- // a run missing its character snapshot.- listLoraTrainingRuns({ datasetId: dataset.id, characterId: charEntryId, limit: 5 }).then((runs) => {+ // Query by dataset id, then guard by the full subject identity. That covers+ // character/object/place reassignments without relying on the legacy+ // `character_id` mirror column.+ listLoraTrainingRuns({ datasetId: dataset.id, limit: 5 }).then((runs) => {const own = (Array.isArray(runs) ? runs : []).filter(- (r) => !r.character || (r.character.entryId === charEntryId && r.character.universeId === charUniverseId),+ (r) => !r.character || (+ r.character.entryId === charEntryId+ && r.character.universeId === charUniverseId+ && (r.character.entryKind || 'characters') === charEntryKind+ ),);setActiveRun(own.find(isActive) || null);setLastRun(own.find((r) => !isActive(r)) || null);}).catch(() => {});- }, [dataset.id, charEntryId, charUniverseId]);+ }, [dataset.id, charEntryId, charEntryKind, charUniverseId]);useEffect(() => { refreshRuns(); }, [refreshRuns]);const sseUrl = activeRun ? `/api/lora-training/runs/${activeRun.id}/events` : null;diff --git a/client/src/components/loraTraining/UniverseCharacterPicker.jsx b/client/src/components/loraTraining/UniverseCharacterPicker.jsxindex 8961d66463..4ad666b396 100644--- a/client/src/components/loraTraining/UniverseCharacterPicker.jsx+++ b/client/src/components/loraTraining/UniverseCharacterPicker.jsx@@ -1,27 +1,37 @@/**- * Universe → character cascading select. Shared by the "New dataset" dialog- * and the dataset-reassignment dialog so both pick a (universeId, entryId)+ * Universe → bible-subject cascading select. Shared by the "New dataset" dialog+ * and the dataset-reassignment dialog so both pick a (universeId, entryKind, entryId)* pair through identical loading/empty states. The parent owns the selected* ids; this just renders the two <select>s and loads the option lists.** When the universe changes the parent is responsible for clearing entryId- * (a stale character id from the previous universe must not survive) — the+ * (a stale subject id from the previous universe must not survive) — the* `onUniverseChange` handler should reset it.*/import { useState, useEffect } from 'react';import { listUniverses, getUniverse } from '../../services/api';+const ENTRY_KINDS = [+ { value: 'characters', label: 'Character', empty: 'No characters in this universe', pick: 'Pick a character' },+ { value: 'objects', label: 'Object', empty: 'No objects in this universe', pick: 'Pick an object' },+ { value: 'places', label: 'Place', empty: 'No places in this universe', pick: 'Pick a place' },+];+const kindConfig = (entryKind) => ENTRY_KINDS.find((k) => k.value === entryKind) || ENTRY_KINDS[0];+export default function UniverseCharacterPicker({universeId,+ entryKind = 'characters',entryId,onUniverseChange,+ onEntryKindChange = () => {},onEntryChange,idPrefix = 'ucp',disabledEntryIds = [],}) {const [universes, setUniverses] = useState(null);- const [characters, setCharacters] = useState(null);+ const [universe, setUniverse] = useState(null);+ const [entries, setEntries] = useState(null);useEffect(() => {listUniverses().then((list) => setUniverses(Array.isArray(list) ? list : []))@@ -29,14 +39,21 @@ export default function UniverseCharacterPicker({}, []);useEffect(() => {- if (!universeId) { setCharacters(null); return; }- setCharacters(null);+ if (!universeId) { setUniverse(null); setEntries(null); return; }+ setUniverse(null);+ setEntries(null);getUniverse(universeId, { silent: true })- .then((u) => setCharacters(Array.isArray(u?.characters) ? u.characters : []))- .catch(() => setCharacters([]));+ .then((u) => setUniverse(u || {}))+ .catch(() => setUniverse({}));}, [universeId]);+ useEffect(() => {+ if (!universeId || !universe) return;+ setEntries(Array.isArray(universe?.[entryKind]) ? universe[entryKind] : []);+ }, [universeId, universe, entryKind]);+const disabled = new Set(disabledEntryIds);+ const kind = kindConfig(entryKind);return (<>@@ -53,22 +70,35 @@ export default function UniverseCharacterPicker({</select></div>{universeId && (- <div>- <label htmlFor={`${idPrefix}-character`} className="block text-sm text-gray-400 mb-1">Character</label>- <select- id={`${idPrefix}-character`}- value={entryId}- onChange={(e) => onEntryChange(e.target.value)}- className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white"- >- <option value="">{characters === null ? 'Loading…' : characters.length ? 'Pick a character' : 'No characters in this universe'}</option>- {(characters || []).map((c) => (- <option key={c.id} value={c.id} disabled={disabled.has(c.id)}>- {c.name}{disabled.has(c.id) ? ' (current)' : ''}- </option>- ))}- </select>- </div>+ <>+ <div>+ <label htmlFor={`${idPrefix}-entry-kind`} className="block text-sm text-gray-400 mb-1">Subject type</label>+ <select+ id={`${idPrefix}-entry-kind`}+ value={entryKind}+ onChange={(e) => onEntryKindChange(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white"+ >+ {ENTRY_KINDS.map((k) => <option key={k.value} value={k.value}>{k.label}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor={`${idPrefix}-entry`} className="block text-sm text-gray-400 mb-1">{kind.label}</label>+ <select+ id={`${idPrefix}-entry`}+ value={entryId}+ onChange={(e) => onEntryChange(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-white"+ >+ <option value="">{entries === null ? 'Loading…' : entries.length ? kind.pick : kind.empty}</option>+ {(entries || []).map((entry) => (+ <option key={entry.id} value={entry.id} disabled={disabled.has(entry.id)}>+ {entry.name || entry.slugline || entry.id}{disabled.has(entry.id) ? ' (current)' : ''}+ </option>+ ))}+ </select>+ </div>+ </>)}</>);diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsxindex a0315b5d01..4f9dcb67b2 100644--- a/client/src/pages/LoraDatasetDetail.jsx+++ b/client/src/pages/LoraDatasetDetail.jsx@@ -1,7 +1,7 @@/*** LoRA dataset workbench (/media/training/:datasetId).*- * Build reference material for one character (generate via the image+ * Build reference material for one universe bible subject (generate via the image* queue, upload, slice the reference-sheet turnaround), caption it with* the vision model, then launch a training run. The dataset record is the* single source of truth; rendering images poll-refresh until they land.@@ -31,6 +31,8 @@ import {} from '../services/api';const TRIGGER_RE = /^[a-z0-9_]{2,64}$/;+const SUBJECT_TYPE_LABEL = { characters: 'Character', objects: 'Object', places: 'Place' };+const subjectKind = (dataset) => dataset?.character?.entryKind || 'characters';// Mirror of server/lib/loraDataset.js MIN_TRAINING_IMAGES + the token-boundary// caption match. Kept page-local (UX-advisory only — the server re-validates// authoritatively via validateDatasetReady at train time) so the readiness@@ -141,15 +143,16 @@ function SliceDialog({ dataset, onClose, onSliced }) {function ReassignDialog({ dataset, onClose, onReassigned }) {// Default to the current assignment so the picker opens on the dataset's- // own universe (characters pre-load) and the user only changes what they want.+ // own universe (subjects pre-load) and the user only changes what they want.const [universeId, setUniverseId] = useState(dataset.character.universeId);+ const [entryKind, setEntryKind] = useState(subjectKind(dataset));const [entryId, setEntryId] = useState(dataset.character.entryId);const [submitting, setSubmitting] = useState(false);const submit = async () => {setSubmitting(true);try {- const next = await patchLoraDataset(dataset.id, { universeId, entryId });+ const next = await patchLoraDataset(dataset.id, { universeId, entryKind, entryId });toast.success(`Reassigned to ${next.character.name}`);onReassigned(next);} finally {@@ -166,16 +169,18 @@ function ReassignDialog({ dataset, onClose, onReassigned }) {panelClassName="bg-port-card border border-port-border rounded-lg p-5"><div className="space-y-4">- <h2 id="lt-reassign-title" className="text-base font-semibold text-white">Reassign character</h2>+ <h2 id="lt-reassign-title" className="text-base font-semibold text-white">Reassign subject</h2><p className="text-sm text-gray-400">- Move this dataset's images and trigger word to a different universe character.- The trigger word stays the same — edit it separately if the new character needs its own token.+ Move this dataset's images and trigger word to a different universe bible subject.+ The trigger word stays the same — edit it separately if the new subject needs its own token.</p><UniverseCharacterPickeridPrefix="lt-reassign"universeId={universeId}+ entryKind={entryKind}entryId={entryId}onUniverseChange={(id) => { setUniverseId(id); setEntryId(''); }}+ onEntryKindChange={(kind) => { setEntryKind(kind); setEntryId(''); }}onEntryChange={setEntryId}/><div className="flex justify-end gap-2">@@ -199,7 +204,7 @@ export default function LoraDatasetDetail() {const { datasetId } = useParams();const [dataset, setDataset] = useState(null);const [loadError, setLoadError] = useState(null);- const [character, setCharacter] = useState(null);+ const [subject, setSubject] = useState(null);const [triggerDraft, setTriggerDraft] = useState(null);const [triggerSaving, setTriggerSaving] = useState(false);const [uploading, setUploading] = useState(false);@@ -221,14 +226,17 @@ export default function LoraDatasetDetail() {useEffect(() => { refresh(); }, [refresh]);- // Pull the live canon character once for variation-axis options + sheet link.+ // Pull the live canon subject once for variation-axis options + sheet link.useEffect(() => {if (!dataset?.character?.universeId) return;getUniverse(dataset.character.universeId, { silent: true })- .then((u) => setCharacter((u?.characters || []).find((c) => c.id === dataset.character.entryId) || null))+ .then((u) => {+ const entries = Array.isArray(u?.[subjectKind(dataset)]) ? u[subjectKind(dataset)] : [];+ setSubject(entries.find((entry) => entry.id === dataset.character.entryId) || null);+ }).catch(() => {});// eslint-disable-next-line react-hooks/exhaustive-deps- }, [dataset?.character?.universeId, dataset?.character?.entryId]);+ }, [dataset?.character?.universeId, dataset?.character?.entryKind, dataset?.character?.entryId]);// Readiness is derived from the live local images (not the server's snapshot// on `dataset.readiness`) so manual caption edits / deletes reflect in the@@ -345,15 +353,15 @@ export default function LoraDatasetDetail() {const recaptionAll = () => startCaption(true);const expressionOptions = useMemo(- () => (character?.expressions || []).map((e) => e?.name).filter(Boolean),- [character],+ () => (subjectKind(dataset) === 'characters' ? (subject?.expressions || []).map((e) => e?.name).filter(Boolean) : []),+ [dataset, subject],);const outfitOptions = useMemo(- () => (character?.wardrobes || []).map((w) => w?.name).filter(Boolean),- [character],+ () => (subjectKind(dataset) === 'characters' ? (subject?.wardrobes || []).map((w) => w?.name).filter(Boolean) : []),+ [dataset, subject],);- const hasReferenceSheet = !!(character?.referenceSheetImageRef- || Object.values(character?.referenceSheets || {}).some(Boolean));+ const hasReferenceSheet = !!(subject?.referenceSheetImageRef+ || Object.values(subject?.referenceSheets || {}).some(Boolean));if (loadError) {return (@@ -390,7 +398,7 @@ export default function LoraDatasetDetail() {disabled={dataset.status === 'training'}title={dataset.status === 'training'? 'Cancel the in-progress training run before reassigning'- : 'Reassign this dataset to a different universe character'}+ : 'Reassign this dataset to a different universe subject'}className="shrink-0 text-xs text-gray-500 hover:text-port-accent flex items-center gap-1 disabled:opacity-40 disabled:hover:text-gray-500"><Replace className="w-3.5 h-3.5" /> Reassign@@ -408,6 +416,9 @@ export default function LoraDatasetDetail() {/>{triggerSaving && <Loader2 className="w-3 h-3 animate-spin text-gray-400" />}</div>+ <div className="text-xs text-gray-500 mt-1">+ {SUBJECT_TYPE_LABEL[subjectKind(dataset)] || 'Subject'} from the universe bible+ </div></div><div className="text-right text-sm"><div className={readiness.quality === 'good' ? 'text-port-success' : readiness.quality === 'minimum' ? 'text-port-warning' : 'text-gray-400'}>@@ -492,7 +503,7 @@ export default function LoraDatasetDetail() {<details className="bg-port-card border border-port-border rounded-lg text-sm"><summary className="cursor-pointer select-none px-3 py-2 flex items-center gap-2 text-gray-300 hover:text-white"><Lightbulb className="w-4 h-4 text-port-warning shrink-0" />- <span className="font-medium">Tips for a strong character dataset</span>+ <span className="font-medium">Tips for a strong training dataset</span><span className="text-xs text-gray-500">target ~{RECOMMENDED_TRAINING_IMAGES}–{TRAINING_IMAGE_SWEET_SPOT_MAX} images · {MIN_TRAINING_IMAGES} minimum</span>@@ -501,14 +512,14 @@ export default function LoraDatasetDetail() {<p>Quality beats quantity. {MIN_TRAINING_IMAGES} images is the floor; ~{RECOMMENDED_TRAINING_IMAGES}–{TRAINING_IMAGE_SWEET_SPOT_MAX} sharp,varied shots is the sweet spot. Past ~50 you mostly add training time and overfitting risk —- near-duplicate frames teach the model to memorize a pose instead of learning the character.+ near-duplicate frames teach the model to memorize one setup instead of learning the subject.</p><ul className="list-disc pl-4 space-y-1"><li><span className="text-gray-300">Vary the angle</span> — front, three-quarter, profile, and a back view.</li><li><span className="text-gray-300">Vary the framing</span> — mix tight face close-ups (for likeness) with mid and full-body shots (for proportions).</li>- <li><span className="text-gray-300">Vary pose & expression</span> — standing, sitting, action; neutral, smiling, intense.</li>- <li><span className="text-gray-300">Vary outfit, lighting & background</span> — so the LoRA learns the character, not one costume, key light, or backdrop.</li>- <li><span className="text-gray-300">Keep it single-subject and on-model</span> — one clearly-visible character per image, consistent identity, no clutter or other people.</li>+ <li><span className="text-gray-300">Vary pose, presentation & expression</span> — action and rest for characters; display angles and use context for objects and places.</li>+ <li><span className="text-gray-300">Vary outfit, lighting & background</span> — so the LoRA learns the subject, not one costume, key light, or backdrop.</li>+ <li><span className="text-gray-300">Keep it single-subject and on-model</span> — one clearly-visible subject per image, consistent identity, no clutter.</li><li><span className="text-gray-300">Drop the weak ones</span> — blurry, occluded, or off-model frames hurt more than they help; avoid near-duplicates.</li></ul></div>diff --git a/client/src/pages/LoraTraining.jsx b/client/src/pages/LoraTraining.jsxindex de4e7723c5..4dd3d867bc 100644--- a/client/src/pages/LoraTraining.jsx+++ b/client/src/pages/LoraTraining.jsx@@ -1,7 +1,7 @@/*** LoRA Training — dataset list (/media/training).*- * One dataset per universe character. Cards show the character, a thumb+ * One dataset per universe bible subject. Cards show the subject, a thumb* strip, image/caption counts, and training status; "New dataset" walks* universe → character and lands on the dataset workbench.*/@@ -24,16 +24,18 @@ const STATUS_CHIP = {training: 'bg-port-warning/20 text-port-warning',trained: 'bg-port-success/20 text-port-success',};+const SUBJECT_TYPE_LABEL = { characters: 'Character', objects: 'Object', places: 'Place' };function NewDatasetDialog({ onClose, onCreated }) {const [universeId, setUniverseId] = useState('');+ const [entryKind, setEntryKind] = useState('characters');const [entryId, setEntryId] = useState('');const [creating, setCreating] = useState(false);const create = async () => {setCreating(true);try {- const dataset = await createLoraDataset({ universeId, entryId });+ const dataset = await createLoraDataset({ universeId, entryKind, entryId });onCreated(dataset);} finally {setCreating(false);@@ -53,8 +55,10 @@ function NewDatasetDialog({ onClose, onCreated }) {<UniverseCharacterPickeridPrefix="lt-new"universeId={universeId}+ entryKind={entryKind}entryId={entryId}onUniverseChange={(id) => { setUniverseId(id); setEntryId(''); }}+ onEntryKindChange={(kind) => { setEntryKind(kind); setEntryId(''); }}onEntryChange={setEntryId}/><div className="flex justify-end gap-2">@@ -103,7 +107,7 @@ export default function LoraTraining() {<div className="flex items-center justify-between mb-4 flex-wrap gap-2"><div className="flex items-center gap-2"><GraduationCap className="w-5 h-5 text-port-accent" />- <h2 className="text-lg font-semibold text-white">Character LoRA Training</h2>+ <h2 className="text-lg font-semibold text-white">LoRA Training</h2></div><buttontype="button"@@ -121,8 +125,8 @@ export default function LoraTraining() {{datasets?.length === 0 && (<div className="bg-port-card border border-port-border rounded-lg p-8 text-center text-gray-400"><Sparkles className="w-8 h-8 mx-auto mb-3 text-port-accent" />- <p className="mb-1 text-white">Train a LoRA for consistent character renders.</p>- <p className="text-sm">Pick a universe character, build reference material (generated renders, uploads, reference-sheet crops), caption it, and train a FLUX.1 or FLUX.2 adapter.</p>+ <p className="mb-1 text-white">Train a LoRA for consistent universe subjects.</p>+ <p className="text-sm">Pick a character, object, or place from a universe bible, build reference material, caption it, and train a FLUX adapter.</p></div>)}@@ -132,7 +136,11 @@ export default function LoraTraining() {<div className="flex items-start justify-between gap-2"><Link to={`/media/training/${d.id}`} className="min-w-0"><div className="text-white font-medium truncate">{d.character?.name || 'Unnamed'}</div>- <div className="text-xs text-gray-500 font-mono truncate">{d.triggerWord}</div>+ <div className="text-xs text-gray-500 truncate">+ <span className="font-mono">{d.triggerWord}</span>+ <span className="mx-1">·</span>+ {SUBJECT_TYPE_LABEL[d.character?.entryKind || 'characters'] || 'Subject'}+ </div></Link><span className={`text-xs px-2 py-0.5 rounded-full shrink-0 ${STATUS_CHIP[d.status] || STATUS_CHIP.draft}`}>{d.status}diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.jsindex 6ff4c475cf..485889cbc2 100644--- a/client/src/services/apiLoraTraining.js+++ b/client/src/services/apiLoraTraining.js@@ -1,5 +1,5 @@/**- * Character LoRA training API — datasets (/api/lora-datasets), training+ * LoRA training API — datasets (/api/lora-datasets), training* runs (/api/lora-training), and the character→LoRA link lookup* (/api/loras/by-character).*/@@ -10,17 +10,21 @@ import { request } from './apiCore.js';export const listLoraDatasets = (filters = {}) => {const params = new URLSearchParams();- for (const key of ['universeId', 'entryId', 'ingredientId']) {+ for (const key of ['universeId', 'entryKind', 'entryId', 'ingredientId']) {if (filters[key]) params.set(key, filters[key]);}const qs = params.toString();return request(`/lora-datasets${qs ? `?${qs}` : ''}`);};-export const createLoraDataset = ({ universeId, entryId, triggerWord }, { silent = false } = {}) =>+export const createLoraDataset = ({+ universeId, entryKind = 'characters', entryId, triggerWord,+}, { silent = false } = {}) =>request('/lora-datasets', {method: 'POST',- body: JSON.stringify({ universeId, entryId, ...(triggerWord ? { triggerWord } : {}) }),+ body: JSON.stringify({+ universeId, entryKind, entryId, ...(triggerWord ? { triggerWord } : {}),+ }),silent,});diff --git a/server/lib/loraDataset.js b/server/lib/loraDataset.jsindex 97a810044f..65b9ce431a 100644--- a/server/lib/loraDataset.js+++ b/server/lib/loraDataset.js@@ -2,7 +2,7 @@* LoRA training dataset — pure helpers (no I/O, no service imports).** A dataset is the curated set of captioned reference images for ONE- * universe character, stored machine-locally at+ * universe bible subject, stored machine-locally at* `data/lora-datasets/<id>/index.json` (+ `images/*.png`) via* collectionStore. These helpers cover the record sanitizer, trigger-word* derivation, caption prefixing, the generation variation matrix, and@@ -26,6 +26,7 @@ export const MIN_TRAINING_IMAGES = 10;export const RECOMMENDED_TRAINING_IMAGES = 20;export const TRAINING_IMAGE_SWEET_SPOT_MAX = 30;+export const LORA_DATASET_ENTRY_KINDS = Object.freeze(['characters', 'objects', 'places']);export const DATASET_IMAGE_SOURCES = Object.freeze(['generated', 'upload', 'refsheet-slice', 'gallery']);export const DATASET_IMAGE_STATUSES = Object.freeze(['rendering', 'ready', 'failed']);export const DATASET_STATUSES = Object.freeze(['draft', 'training', 'trained']);@@ -102,6 +103,7 @@ export function sanitizeLoraDataset(raw) {id,character: {entryId,+ entryKind: oneOf(character.entryKind, LORA_DATASET_ENTRY_KINDS, 'characters'),ingredientId: trim(character.ingredientId) || null,universeId,name: trim(character.name) || 'Unnamed',diff --git a/server/lib/loraDataset.test.js b/server/lib/loraDataset.test.jsindex c405f9c6cf..1ad5717c99 100644--- a/server/lib/loraDataset.test.js+++ b/server/lib/loraDataset.test.js@@ -28,13 +28,21 @@ describe('sanitizeLoraDataset', () => {const out = sanitizeLoraDataset(baseRecord());expect(out.schemaVersion).toBe(LORA_DATASET_SCHEMA_VERSION);expect(out.character).toEqual({- entryId: 'char-1', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa',+ entryId: 'char-1', entryKind: 'characters', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa',});expect(out.training).toEqual({lastJobId: null, lastRunId: null, loraFilename: null, completedAt: null,});});+ it('preserves object/place subject kind on the compatibility character snapshot', () => {+ const out = sanitizeLoraDataset({+ ...baseRecord(),+ character: { entryId: 'obj-1', entryKind: 'objects', universeId: 'uni-1', name: 'Truthbreaker' },+ });+ expect(out.character).toMatchObject({ entryId: 'obj-1', entryKind: 'objects', name: 'Truthbreaker' });+ });+it('rejects records missing identity', () => {expect(sanitizeLoraDataset(null)).toBeNull();expect(sanitizeLoraDataset({ id: 'x' })).toBeNull();diff --git a/server/routes/loraDatasets.js b/server/routes/loraDatasets.jsindex b59dbbf91b..6a71a97df1 100644--- a/server/routes/loraDatasets.js+++ b/server/routes/loraDatasets.js@@ -2,7 +2,7 @@* LoRA training dataset routes — `/api/lora-datasets`.** CRUD + image upload (multipart) + batch generation + reference-sheet- * slicing + vision captioning (SSE) for the per-character training+ * slicing + vision captioning (SSE) for the per-subject training* datasets behind /media/training. Training-run launch lives at* `/api/lora-training` (routes/loraTraining.js); this surface ends at* "dataset ready to train".@@ -27,15 +27,17 @@ import {} from '../services/loraDatasets.js';import { generateDatasetImages, sliceReferenceSheet } from '../services/loraDatasetGenerate.js';import { attachCaptionSseClient, startCaptionRun } from '../services/loraDatasetCaption.js';-import { computeDatasetReadiness } from '../lib/loraDataset.js';+import { LORA_DATASET_ENTRY_KINDS, computeDatasetReadiness } from '../lib/loraDataset.js';const router = Router();const triggerWordSchema = z.string().regex(/^[a-z0-9_]{2,64}$/, 'trigger word must be 2-64 chars of [a-z0-9_]');const idSchema = z.string().min(1).max(128);+const entryKindSchema = z.enum(LORA_DATASET_ENTRY_KINDS);const listQuerySchema = z.object({universeId: idSchema.optional(),+ entryKind: entryKindSchema.optional(),entryId: idSchema.optional(),ingredientId: idSchema.optional(),});@@ -46,6 +48,7 @@ router.get('/', asyncHandler(async (req, res) => {const createSchema = z.object({universeId: idSchema,+ entryKind: entryKindSchema.default('characters'),entryId: idSchema,triggerWord: triggerWordSchema.optional(),});@@ -64,10 +67,11 @@ router.get('/:id', asyncHandler(async (req, res) => {const patchSchema = z.object({triggerWord: triggerWordSchema.optional(),- // Reassign the dataset to a different universe character. Both must be- // present together; the service re-snapshots the character and refuses a- // collision with an existing dataset for that character.+ // Reassign the dataset to a different universe subject. Universe + entry id+ // must be present together; the service re-snapshots the subject and refuses+ // a collision with an existing dataset for that subject.universeId: idSchema.optional(),+ entryKind: entryKindSchema.optional(),entryId: idSchema.optional(),});router.patch('/:id', asyncHandler(async (req, res) => {diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.jsindex 2928dfc6de..892f7ceb70 100644--- a/server/services/loraDatasetGenerate.js+++ b/server/services/loraDatasetGenerate.js@@ -1,7 +1,7 @@/*** LoRA dataset generation — reference-material renders + sheet slicing.*- * Builds single-subject training prompts from a character's canon (the+ * Builds single-subject training prompts from a universe bible subject's canon (the* inverse of the dense reference-sheet layout: one clean figure on a* neutral background per image), enqueues them on the media-job queue, and* copies completed renders into the dataset. Also slices an existing@@ -46,6 +46,34 @@ import {const DATASET_IMAGE_SIZE = 1024;const trim = (s) => (typeof s === 'string' ? s.trim() : '');+const normalizeEntryKind = (entryKind) => (+ ['characters', 'objects', 'places'].includes(entryKind) ? entryKind : 'characters'+);+const subjectLabel = (entryKind) => {+ switch (normalizeEntryKind(entryKind)) {+ case 'objects': return 'Object';+ case 'places': return 'Place';+ default: return 'Character';+ }+};++const flattenValue = (value) => {+ if (typeof value === 'string') return trim(value);+ if (Array.isArray(value)) {+ return value.map((v) => {+ if (typeof v === 'string') return trim(v);+ if (v && typeof v === 'object') return trim(v.name || v.label || v.description || v.prompt || '');+ return '';+ }).filter(Boolean).join(', ');+ }+ if (value && typeof value === 'object') {+ return Object.entries(value)+ .map(([key, v]) => `${key}: ${typeof v === 'string' ? trim(v) : trim(v?.name || v?.label || '')}`)+ .filter((part) => !part.endsWith(': '))+ .join(', ');+ }+ return '';+};/*** Build the image-gen prompt + negative prompt for ONE dataset image.@@ -53,13 +81,66 @@ const trim = (s) => (typeof s === 'string' ? s.trim() : '');* the variation clause, and hard-bans collage/sheet/text artifacts.* Pure — exported for tests.*/-export function buildDatasetImagePrompt(universe, character, variation = {}) {+export function buildDatasetImagePrompt(universe, subject, variation = {}, entryKind = 'characters') {+ const kind = normalizeEntryKind(entryKind);const styleClause = buildStyleClause(universe || {});const styleBits = styleClause.startsWith('(none provided') ? '' : styleClause;+ if (kind !== 'characters') {+ const name = trim(subject?.name || subject?.slugline) || 'Unnamed';+ const description = flattenValue(subject?.description || subject?.prompt);+ const significance = flattenValue(subject?.significance);+ const palette = flattenValue(subject?.palette || subject?.colorPalette);+ const recurring = flattenValue(subject?.recurringDetails);+ const tags = Array.isArray(subject?.tags) && subject.tags.length ? subject.tags.join(', ') : '';+ const identityBits = [+ `${subjectLabel(kind)}: ${name}.`,+ description ? `Description: ${description}.` : '',+ significance ? `Significance: ${significance}.` : '',+ recurring ? `Recurring details: ${recurring}.` : '',+ palette ? `Palette: ${palette}.` : '',+ tags ? `Tags: ${tags}.` : '',+ ].filter(Boolean).join(' ');++ const view = trim(variation.view) || (kind === 'objects' ? 'three-quarter view' : 'wide establishing view');+ const composition = trim(variation.pose) || (kind === 'objects' ? 'centered presentation' : 'clear establishing composition');+ const lighting = trim(variation.expression) || 'natural lighting';+ const setting = trim(variation.outfit) || (kind === 'objects' ? 'plain studio plinth' : 'signature environment');+ const subjectBits = kind === 'objects'+ ? [+ 'Single object only',+ view,+ composition,+ lighting,+ `setting: ${setting}`,+ 'full object in frame',+ 'unobstructed silhouette',+ ]+ : [+ 'Single location focus',+ view,+ composition,+ lighting,+ `environment state: ${setting}`,+ 'no prominent characters',+ 'clear spatial layout',+ ];++ return {+ prompt: [+ styleBits || 'Style: contemporary illustrated fantasy design with confident line work and saturated, intentional color.',+ identityBits,+ `${subjectBits.filter(Boolean).join(', ')}, no text, no panels, no labels.`,+ ].filter(Boolean).join('\n\n'),+ negativePrompt: kind === 'objects'+ ? 'person, hands covering the object, multiple objects, duplicate object, reference sheet, panel borders, grid, collage, text, labels, watermark, signature, blurry, cropped object, deformed geometry'+ : 'prominent character, crowd, reference sheet, panel borders, grid, collage, text, labels, watermark, signature, blurry, distorted perspective, unreadable layout',+ };+ }+const {name, role, physical, silhouette, posture, special, visualIdentity,paletteLine, wardrobeLine, propsLine,- } = extractCharacterPromptCommon(character || {});+ } = extractCharacterPromptCommon(subject || {});const identityBits = [`Character: ${name}.`,@@ -103,6 +184,19 @@ export function buildDatasetImagePrompt(universe, character, variation = {}) {* Pure — exported for tests.*/export function deriveVariationAxes(character) {+ const kind = normalizeEntryKind(character?.entryKind);+ if (kind === 'objects') {+ return {+ expressions: ['soft studio lighting', 'warm firelight', 'cool moonlight', 'harsh desert sun', 'low dungeon torchlight'],+ outfits: ['plain studio plinth', 'weathered wooden table', 'snow-covered stone', 'sunlit desert sand', 'torchlit dungeon floor'],+ };+ }+ if (kind === 'places') {+ return {+ expressions: ['clear daylight', 'golden hour', 'moonlit night', 'stormy overcast', 'torchlit darkness'],+ outfits: ['signature environment', 'after rainfall', 'dusty dry season', 'busy lived-in state', 'abandoned quiet state'],+ };+ }const names = (list) => (Array.isArray(list)? list.map((e) => trim(e?.name)).filter(Boolean): []);@@ -114,20 +208,21 @@ export function deriveVariationAxes(character) {};}-// Load the dataset's live canon character (generation + slicing both need-// the current canon, not the dataset's snapshot). 409 when the character+// Load the dataset's live canon subject (generation + slicing both need+// the current canon, not the dataset's snapshot). 409 when the subject// was deleted from the universe after the dataset was created.-async function loadDatasetCharacter(dataset) {+async function loadDatasetSubject(dataset) {+ const entryKind = normalizeEntryKind(dataset.character.entryKind);const universe = await getUniverse(dataset.character.universeId);- const characters = Array.isArray(universe.characters) ? universe.characters : [];- const character = characters.find((c) => c.id === dataset.character.entryId);- if (!character) {+ const entries = Array.isArray(universe[entryKind]) ? universe[entryKind] : [];+ const subject = entries.find((entry) => entry.id === dataset.character.entryId);+ if (!subject) {throw new ServerError(- `Character ${dataset.character.entryId} no longer exists in universe ${dataset.character.universeId}`,+ `${subjectLabel(entryKind)} ${dataset.character.entryId} no longer exists in universe ${dataset.character.universeId}`,{ status: 409, code: 'UNIVERSE_CANON_NOT_FOUND' },);}- return { universe, character };+ return { universe, subject: { ...subject, entryKind }, entryKind };}// Single-dispatcher subscription on mediaJobEvents — same shape as@@ -220,7 +315,7 @@ async function resolveRenderParams({ modelId: modelOverride = null } = {}) {}/**- * Generate `count` reference images for the dataset's character. Appends a+ * Generate `count` reference images for the dataset's subject. Appends a* `rendering` image entry per variation, enqueues each render on the image* queue, and flips entries to `ready` (with the file copied in) as jobs* complete. Returns `{ images: [{ imageId, jobId, variation }], mode, modelId }`@@ -228,9 +323,9 @@ async function resolveRenderParams({ modelId: modelOverride = null } = {}) {*/export async function generateDatasetImages(datasetId, options = {}) {const dataset = await getDataset(datasetId);- const { universe, character } = await loadDatasetCharacter(dataset);+ const { universe, subject, entryKind } = await loadDatasetSubject(dataset);- const axes = deriveVariationAxes(character);+ const axes = deriveVariationAxes(subject);const variations = buildVariationMatrix({count: options.count,views: options.views,@@ -245,7 +340,7 @@ export async function generateDatasetImages(datasetId, options = {}) {for (const variation of variations) {const imageId = uuidv4();const file = `${imageId}.png`;- const { prompt, negativePrompt } = buildDatasetImagePrompt(universe, character, variation);+ const { prompt, negativePrompt } = buildDatasetImagePrompt(universe, subject, variation, entryKind);const queued = enqueueJob({ kind: 'image', params: { ...base, prompt, negativePrompt } });const jobId = queued.jobId;@@ -305,18 +400,18 @@ export async function generateDatasetImages(datasetId, options = {}) {}/**- * Slice the character's existing reference-sheet turnaround into a fixed+ * Slice the subject's existing reference-sheet turnaround into a fixed* `cols × rows` grid of training crops. Each crop lands as a `ready`* dataset image with source 'refsheet-slice' — the user prunes bad crops* (label strips, palette swatches) in the grid UI.*/export async function sliceReferenceSheet(datasetId, { variant = LEGACY_SHEET_VARIANT_ID, cols = 3, rows = 2 } = {}) {const dataset = await getDataset(datasetId);- const { character } = await loadDatasetCharacter(dataset);- const sheetFilename = readSheetPointer(character, variant);+ const { subject, entryKind } = await loadDatasetSubject(dataset);+ const sheetFilename = readSheetPointer(subject, variant);if (!sheetFilename) {throw new ServerError(- `Character "${character.name}" has no ${variant} reference sheet — render one first`,+ `${subjectLabel(entryKind)} "${subject.name || subject.slugline || dataset.character.entryId}" has no ${variant} reference sheet — render one first`,{ status: 409, code: 'LORA_DATASET_NO_SHEET' },);}diff --git a/server/services/loraDatasets.js b/server/services/loraDatasets.jsindex 5c01ef759d..f64ebc1421 100644--- a/server/services/loraDatasets.js+++ b/server/services/loraDatasets.js@@ -1,8 +1,8 @@/*** LoRA training datasets — collectionStore CRUD + image file management.*- * One dataset per universe character (find-or-create keyed on- * `(universeId, entryId)`), stored machine-locally at+ * One dataset per universe bible subject (find-or-create keyed on+ * `(universeId, entryKind, entryId)`), stored machine-locally at* `data/lora-datasets/<id>/index.json` with image bytes at* `data/lora-datasets/<id>/images/<imageId>.png`. Datasets never federate* — like `data/loras/` itself, they organize artifacts tied to this@@ -22,6 +22,7 @@ import { assertGalleryFilename } from './imageGen/local.js';import { createCollectionStore } from '../lib/collectionStore.js';import {LORA_DATASET_SCHEMA_VERSION,+ LORA_DATASET_ENTRY_KINDS,computeDatasetReadiness,deriveTriggerWord,isValidTriggerWord,@@ -44,6 +45,16 @@ export const datasetImagesDir = (datasetId) => join(loraDatasetStore.recordDir(dexport const datasetImagePath = (datasetId, file) => join(datasetImagesDir(datasetId), file);const nowIso = () => new Date().toISOString();+const normalizeEntryKind = (entryKind) => (+ LORA_DATASET_ENTRY_KINDS.includes(entryKind) ? entryKind : 'characters'+);+const subjectLabel = (entryKind) => {+ switch (normalizeEntryKind(entryKind)) {+ case 'objects': return 'object';+ case 'places': return 'place';+ default: return 'character';+ }+};const requireDataset = async (id) => {const dataset = await loraDatasetStore.loadOne(id);@@ -89,10 +100,14 @@ const summarize = (dataset) => ({updatedAt: dataset.updatedAt,});-export async function listDatasets({ universeId = null, entryId = null, ingredientId = null } = {}) {+export async function listDatasets({+ universeId = null, entryKind = null, entryId = null, ingredientId = null,+} = {}) {+ const normalizedKind = entryKind ? normalizeEntryKind(entryKind) : null;const all = await loraDatasetStore.loadAll();const filtered = all.filter((d) => {if (universeId && d.character.universeId !== universeId) return false;+ if (normalizedKind && normalizeEntryKind(d.character.entryKind) !== normalizedKind) return false;if (entryId && d.character.entryId !== entryId) return false;if (ingredientId && d.character.ingredientId !== ingredientId) return false;return true;@@ -108,44 +123,52 @@ export async function getDataset(id) {}/**- * Resolve a universe character and the identity snapshot a dataset stores for- * it. Validates the character exists in the universe (404 otherwise) and is the- * single source of truth for the snapshot shape — both createDataset and+ * Resolve a universe bible subject and the identity snapshot a dataset stores+ * for it. Validates the subject exists in the universe (404 otherwise) and is+ * the single source of truth for the snapshot shape — both createDataset and* patchDataset's reassignment go through here so the stored `character` fields- * can't drift between the two write paths. Returns `{ character, snapshot }`+ * can't drift between the two write paths. Returns `{ subject, snapshot }`* (the live canon entry plus the persisted shape).*/-async function resolveCharacterSnapshot(universeId, entryId) {+export async function resolveDatasetSubjectSnapshot(universeId, entryId, entryKind = 'characters') {+ const normalizedKind = normalizeEntryKind(entryKind);const universe = await getUniverse(universeId);- const characters = Array.isArray(universe.characters) ? universe.characters : [];- const character = characters.find((c) => c.id === entryId);- if (!character) {- throw new ServerError(`Character ${entryId} not found in universe`, {+ const subjects = Array.isArray(universe[normalizedKind]) ? universe[normalizedKind] : [];+ const subject = subjects.find((entry) => entry.id === entryId);+ if (!subject) {+ throw new ServerError(`${subjectLabel(normalizedKind)} ${entryId} not found in universe`, {status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',});}return {- character,+ universe,+ subject,snapshot: {entryId,- ingredientId: character.ingredientId || null,+ entryKind: normalizedKind,+ ingredientId: subject.ingredientId || null,universeId,- name: character.name,+ name: subject.name || subject.slugline || 'Unnamed',},};}/**- * Find-or-create the dataset for one universe character. Validates the- * character exists in the universe and snapshots its identity (entryId ++ * Find-or-create the dataset for one universe bible subject. Validates the+ * subject exists in the universe and snapshots its identity (entryId +* catalog ingredientId + name) into the record. Returns `{ dataset, created }`.*/-export async function createDataset({ universeId, entryId, triggerWord = null }) {- const { character, snapshot } = await resolveCharacterSnapshot(universeId, entryId);+export async function createDataset({+ universeId, entryId, entryKind = 'characters', triggerWord = null,+}) {+ const normalizedKind = normalizeEntryKind(entryKind);+ const { subject, snapshot } = await resolveDatasetSubjectSnapshot(universeId, entryId, normalizedKind);const existingAll = await loraDatasetStore.loadAll();const existing = existingAll.find(- (d) => d.character.universeId === universeId && d.character.entryId === entryId,+ (d) => d.character.universeId === universeId+ && normalizeEntryKind(d.character.entryKind) === normalizedKind+ && d.character.entryId === entryId,);if (existing) return { dataset: { ...existing, readiness: computeDatasetReadiness(existing) }, created: false };@@ -155,7 +178,7 @@ export async function createDataset({ universeId, entryId, triggerWord = null })});}const taken = existingAll.map((d) => d.triggerWord).filter(Boolean);- const resolvedTrigger = triggerWord || deriveTriggerWord(character.name, { taken });+ const resolvedTrigger = triggerWord || deriveTriggerWord(snapshot.name, { taken });const id = uuidv4();const record = sanitizeLoraDataset({@@ -171,19 +194,21 @@ export async function createDataset({ universeId, entryId, triggerWord = null })});await loraDatasetStore.saveOne(id, record);await ensureDir(datasetImagesDir(id));- console.log(`🧬 Created LoRA dataset ${id} for character "${character.name}" (trigger=${resolvedTrigger})`);+ console.log(`🧬 Created LoRA dataset ${id} for ${subjectLabel(normalizedKind)} "${subject.name || subject.slugline || entryId}" (trigger=${resolvedTrigger})`);return { dataset: { ...record, readiness: computeDatasetReadiness(record) }, created: true };}/*** Patch a dataset's trigger word and/or reassign it to a different- * universe character. `universeId` + `entryId` must travel together — a- * reassignment re-snapshots the character identity (entryId, universeId,+ * universe bible subject. `universeId` + `entryId` must travel together — a+ * reassignment re-snapshots the subject identity (entryId, entryKind, universeId,* ingredientId, name) exactly the way createDataset does, and is refused* if it would collide with another dataset already keyed on that- * (universeId, entryId) pair (the one-dataset-per-character invariant).+ * (universeId, entryKind, entryId) tuple (the one-dataset-per-subject invariant).*/-export async function patchDataset(id, { triggerWord, universeId, entryId } = {}) {+export async function patchDataset(id, {+ triggerWord, universeId, entryId, entryKind,+} = {}) {if (triggerWord !== undefined && !isValidTriggerWord(triggerWord)) {throw new ServerError('Trigger word must be 2-64 chars of [a-z0-9_]', {status: 400, code: 'VALIDATION_ERROR',@@ -191,8 +216,8 @@ export async function patchDataset(id, { triggerWord, universeId, entryId } = {}}// Reassignment is all-or-nothing: a half-specified target (universe but no- // character) can't resolve a character snapshot, so reject it up front.- const reassigning = universeId !== undefined || entryId !== undefined;+ // subject) can't resolve a subject snapshot, so reject it up front.+ const reassigning = universeId !== undefined || entryId !== undefined || entryKind !== undefined;let nextCharacter = null;if (reassigning) {if (!universeId || !entryId) {@@ -200,23 +225,27 @@ export async function patchDataset(id, { triggerWord, universeId, entryId } = {}status: 400, code: 'VALIDATION_ERROR',});}- // The character validation and the collision scan are independent reads —- // run them together. resolveCharacterSnapshot keeps the snapshot shape in+ const normalizedKind = normalizeEntryKind(entryKind);+ // The subject validation and the collision scan are independent reads —+ // run them together. resolveDatasetSubjectSnapshot keeps the snapshot shape in// lockstep with createDataset.- const [{ character, snapshot }, all] = await Promise.all([- resolveCharacterSnapshot(universeId, entryId),+ const [{ subject, snapshot }, all] = await Promise.all([+ resolveDatasetSubjectSnapshot(universeId, entryId, normalizedKind),loraDatasetStore.loadAll(),]);// (The in-flight-run guard moved into the write lock below — a pre-write// status snapshot races a concurrent startTrainingRun stamping 'training'.)// Enforce the same find-or-create key createDataset uses: at most one- // dataset per (universeId, entryId). Reassigning onto a character that+ // dataset per (universeId, entryKind, entryId). Reassigning onto a subject that// already owns a dataset would create a duplicate the list can't tell apart.const clash = all.find(- (d) => d.id !== id && d.character.universeId === universeId && d.character.entryId === entryId,+ (d) => d.id !== id+ && d.character.universeId === universeId+ && normalizeEntryKind(d.character.entryKind) === normalizedKind+ && d.character.entryId === entryId,);if (clash) {- throw new ServerError(`A dataset already exists for "${character.name}" in that universe`, {+ throw new ServerError(`A dataset already exists for "${subject.name || subject.slugline || entryId}" in that universe`, {status: 409, code: 'DATASET_EXISTS',});}@@ -227,6 +256,7 @@ export async function patchDataset(id, { triggerWord, universeId, entryId } = {}const triggerChanged = triggerWord !== undefined && triggerWord !== current.triggerWord;const characterChanged = nextCharacter && (nextCharacter.entryId !== current.character.entryId+ || nextCharacter.entryKind !== normalizeEntryKind(current.character.entryKind)|| nextCharacter.universeId !== current.character.universeId|| nextCharacter.ingredientId !== current.character.ingredientId|| nextCharacter.name !== current.character.name);diff --git a/server/services/loraDatasets.test.js b/server/services/loraDatasets.test.jsindex 66d1043571..ffaab688e4 100644--- a/server/services/loraDatasets.test.js+++ b/server/services/loraDatasets.test.js@@ -47,6 +47,12 @@ const UNIVERSE = {{ id: 'char-1', ingredientId: 'ing-1', name: 'Kessa Brightwater' },{ id: 'char-2', ingredientId: null, name: 'Moss' },],+ objects: [+ { id: 'obj-1', name: 'Northwind Truthbreaker', description: 'A rune-bitten greataxe.' },+ ],+ places: [+ { id: 'place-1', name: 'Moonsea Shore', description: 'Black water under cold stars.' },+ ],};const makePng = (path, size = 64) => sharp({@@ -68,11 +74,22 @@ describe('createDataset', () => {expect(created).toBe(true);expect(dataset.triggerWord).toBe('kessa_brightwater');expect(dataset.character).toEqual({- entryId: 'char-1', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa Brightwater',+ entryId: 'char-1', entryKind: 'characters', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa Brightwater',});expect(dataset.readiness.trainable).toBe(false);});+ it('creates an object dataset from the universe bible', async () => {+ const { dataset, created } = await createDataset({+ universeId: 'uni-1', entryKind: 'objects', entryId: 'obj-1',+ });+ expect(created).toBe(true);+ expect(dataset.triggerWord).toBe('northwind_truthbreaker');+ expect(dataset.character).toEqual({+ entryId: 'obj-1', entryKind: 'objects', ingredientId: null, universeId: 'uni-1', name: 'Northwind Truthbreaker',+ });+ });+it('is find-or-create per (universeId, entryId)', async () => {const first = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });const second = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });@@ -80,6 +97,19 @@ describe('createDataset', () => {expect(second.dataset.id).toBe(first.dataset.id);});+ it('allows the same entry id in different bible subject kinds', async () => {+ getUniverse.mockResolvedValue({+ ...UNIVERSE,+ characters: [...UNIVERSE.characters, { id: 'shared-1', name: 'Shared Character' }],+ objects: [...UNIVERSE.objects, { id: 'shared-1', name: 'Shared Object' }],+ });+ const character = await createDataset({ universeId: 'uni-1', entryKind: 'characters', entryId: 'shared-1' });+ const object = await createDataset({ universeId: 'uni-1', entryKind: 'objects', entryId: 'shared-1' });+ expect(character.dataset.id).not.toBe(object.dataset.id);+ expect(await listDatasets({ entryKind: 'characters', entryId: 'shared-1' })).toHaveLength(1);+ expect(await listDatasets({ entryKind: 'objects', entryId: 'shared-1' })).toHaveLength(1);+ });+it('avoids trigger-word collisions across datasets', async () => {await createDataset({ universeId: 'uni-1', entryId: 'char-1' });getUniverse.mockResolvedValue({@@ -132,7 +162,7 @@ describe('patchDataset / listDatasets', () => {const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });const next = await patchDataset(dataset.id, { universeId: 'uni-1', entryId: 'char-2' });expect(next.character).toEqual({- entryId: 'char-2', ingredientId: null, universeId: 'uni-1', name: 'Moss',+ entryId: 'char-2', entryKind: 'characters', ingredientId: null, universeId: 'uni-1', name: 'Moss',});// Trigger word is left alone — reassignment doesn't rename the token.expect(next.triggerWord).toBe('kessa_brightwater');@@ -141,6 +171,16 @@ describe('patchDataset / listDatasets', () => {expect(await listDatasets({ entryId: 'char-1' })).toHaveLength(0);});+ it('reassigns to an object, re-snapshotting kind and identity', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const next = await patchDataset(dataset.id, { universeId: 'uni-1', entryKind: 'objects', entryId: 'obj-1' });+ expect(next.character).toEqual({+ entryId: 'obj-1', entryKind: 'objects', ingredientId: null, universeId: 'uni-1', name: 'Northwind Truthbreaker',+ });+ expect(await listDatasets({ entryKind: 'objects', entryId: 'obj-1' })).toHaveLength(1);+ expect(await listDatasets({ entryKind: 'characters', entryId: 'char-1' })).toHaveLength(0);+ });+it('reassigns and renames the trigger word in one patch', async () => {const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });const next = await patchDataset(dataset.id, { universeId: 'uni-1', entryId: 'char-2', triggerWord: 'moss_v1' });diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex 4f93b6861b..d9ec150a2b 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -100,13 +100,15 @@ const mergeParams = (settings, requestParams = {}) => ({...requestParams,});-// A dataset belongs to a run only while it still points at the run's character.+// A dataset belongs to a run only while it still points at the run's subject.// Match the full (universeId, entryId) key the dataset store uses — a different// universe can reuse the same entryId, so entryId alone would falsely re-own a// reassigned dataset. (flipDatasetAfterRun keeps its own missing-entryId// fallthrough for pre-reassignment runs that predate the character snapshot.)const sameCharacter = (a, b) =>- a?.entryId === b?.entryId && a?.universeId === b?.universeId;+ a?.entryId === b?.entryId+ && a?.universeId === b?.universeId+ && (a?.entryKind || 'characters') === (b?.entryKind || 'characters');// Re-stamp a dataset as `training` with the run's new job/run ids, but only// while it still owns the dataset — the dataset can be reassigned to a different@@ -236,7 +238,7 @@ export async function resumeTrainingRun(runId) {// dataset may have been edited, deleted, or reassigned since the run failed.const { dataset } = await validateDatasetReady(run.datasetId);if (!sameCharacter(dataset.character, run.character)) {- throw new ServerError('Dataset was reassigned to a different character — start a fresh run.', {+ throw new ServerError('Dataset was reassigned to a different subject — start a fresh run.', {status: 409, code: 'DATASET_REASSIGNED',});}@@ -310,10 +312,12 @@ const flipDatasetAfterRun = (run, { trained, loraFilename = null }) => {// missing entryId falls through (flip).const runEntryId = run?.character?.entryId || null;const runUniverseId = run?.character?.universeId || null;+ const runEntryKind = run?.character?.entryKind || 'characters';return updateDataset(datasetId, (current) => {const mismatch = runEntryId && (current.character?.entryId !== runEntryId|| (runUniverseId && current.character?.universeId !== runUniverseId)+ || ((current.character?.entryKind || 'characters') !== runEntryKind));if (mismatch) return null;return {@@ -367,13 +371,13 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckreturn failBeforeSpawn(err.message);}// Stage-time ownership check: if the dataset was reassigned to a different- // character after this run was queued, the run no longer owns it. Bail out+ // subject after this run was queued, the run no longer owns it. Bail out// rather than training the moved dataset and registering a LoRA under the- // run's now-stale character. failBeforeSpawn's flipDatasetAfterRun is+ // run's now-stale subject. failBeforeSpawn's flipDatasetAfterRun is// character-guarded, so it won't disturb the reassigned dataset's state.// Match the full (universeId, entryId) key the dataset store uses elsewhere.if (!sameCharacter(dataset.character, run.character)) {- return failBeforeSpawn('Dataset was reassigned to a different character after this run was queued — cancel and retrain.');+ return failBeforeSpawn('Dataset was reassigned to a different subject after this run was queued — cancel and retrain.');}// Reclaim unified memory before a GPU-heavy run, then gate on real headroom.diff --git a/server/services/loraTraining/sidecar.js b/server/services/loraTraining/sidecar.jsindex e30be6014c..94c612ece7 100644--- a/server/services/loraTraining/sidecar.js+++ b/server/services/loraTraining/sidecar.js@@ -10,7 +10,7 @@ import { RUNNER_FAMILIES } from '../../lib/runners.js';/** `lora-trained-<slug>-<runId8>.safetensors` — runId suffix prevents collisions. */export function trainedLoraFilename({ name, characterName, runId }) {- const slug = slugifyForFilename(name || characterName || 'character');+ const slug = slugifyForFilename(name || characterName || 'subject');return `lora-trained-${slug}-${String(runId).replace(/-/g, '').slice(0, 8)}.safetensors`;}@@ -36,7 +36,7 @@ export function buildTrainedSidecar({: '';return {filename,- name: run.name || `${run.character?.name || 'Character'} (trained)`,+ name: run.name || `${run.character?.name || 'Subject'} (trained)`,description: `Trained in PortOS · ${params.steps ?? '?'} steps · rank ${params.rank ?? '?'}${ckptNote} · dataset ${run.datasetId}`,source: 'trained',character: run.character || null,