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: warn + one-click strip for invariant identity leaking into character-LoRA captions (#1320)

[._.]/ Adam Eivy088f12d1aa54
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d968fe40e9..d7095577e1 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-1320] Character-LoRA caption lint — warn when identity leaks into captions, and strip it in one click.** When every caption for a character repeats the same invariant features ("white hair, circlet, tooth necklace"), the LoRA binds the look to those *phrases* instead of the trigger token — so the bare trigger renders a generic subject and only the full identity description reproduces the character (the exact failure that surfaced training Freydis). The dataset workbench now analyzes the captioned images, and when a descriptive fragment repeats across ≥80% of captions it shows an **advisory banner** listing the shared fragments (with their hit counts) and a **Strip shared identity from all captions** button that removes those fragments from every caption while preserving the trigger word and the per-shot detail (pose, framing, setting). The strip recomputes the shared set server-side (`POST /api/lora-datasets/:id/strip-shared-fragments`) so it never trusts a stale client list, and it's idempotent. The "Tips for a strong training dataset" panel gains the caption recipe — *describe what changes shot-to-shot, not who the subject is* — so the guidance is on the page before a caption ever drifts. The threshold is high on purpose: a *varying* attribute (a single view or pose) only appears in a slice of the set, so it separates baked-in identity from legitimate variation without flagging the latter. (`server/lib/loraDataset.js`, `server/services/loraDatasets.js`, `server/routes/loraDatasets.js`, `client/src/pages/LoraDatasetDetail.jsx`, `client/src/services/apiLoraTraining.js`) (#1320)
+
- **[issue-1303] Per-series style guide — one source of truth for tense, POV, audience, rating, and reading level.** Style used to live only in free-text notes, so generation could drift and nothing could check conformance. Each series now has a structured **style guide** on its bible: narrative **tense** (past/present), **POV person** (first / second / third-limited / third-omniscient), **target audience**, **content rating** + allowed **profanity**, a target **reading level**, **tone** words, and copy-edit **conventions** (Oxford comma, US/UK spelling, italicize-thoughts). The guide is woven into prose and arc generation so the AI writes in the right register from the start, and two new editorial checks audit the drafted manuscript against it: **Reading-level conformance** (measures the manuscript's grade level and flags it when it drifts from the target) and **Style-guide conformance** (an LLM scan for tense slips, POV-person drift, and content/profanity beyond the configured rating). Everything is optional and additive — a series without a style guide behaves exactly as before — and the field is version-gated for cross-machine sync so an older peer can't silently strip it. (#1303)
- **[issue-1354] Catalog cards show image thumbnails, generate art from a description, and a "Sync from Universes" button pulls in missing canon.** Three catalog gaps closed at once. (1) **Missing canon items** — characters/places/objects you add to a universe *after* the one-time setup never appeared in the Catalog, because canon→catalog promotion only ran once per install. A new **Sync from Universes** button on the Catalog page re-runs that promotion on demand (idempotent — already-catalogued items are skipped), so the catalog catches up to your universes in one click and the list refreshes with what was pulled in. (2) **Thumbnails** — each catalog card now shows the item's portrait (or its most recent reference image) as a thumbnail, falling back to a placeholder when there's no image, so the grid is scannable at a glance. (3) **Generate from description** — the catalog item editor's Media panel gets a **Generate** button that turns the item's description into an image via the same image-gen queue the universe canon uses; the first generated image becomes the item's portrait (and thumbnail), later ones attach as references. The button is disabled until the item has a description to render from. (#1354)
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index c4b37ea5cd..6cc9b17141 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -10,7 +10,7 @@
import { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import { useParams, Link } from 'react-router-dom';
import {
- ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, RefreshCw, AlertTriangle, Images, Replace, Lightbulb,
+ ArrowLeft, Loader2, Upload, Wand2, Scissors, Tags, RefreshCw, AlertTriangle, Images, Replace, Lightbulb, Eraser,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import Modal from '../components/ui/Modal';
@@ -28,6 +28,7 @@ import {
uploadLoraDatasetImages,
sliceLoraDatasetRefSheet,
startLoraCaptionRun,
+ stripLoraDatasetSharedCaptionFragments,
getUniverse,
} from '../services/api';
@@ -56,6 +57,50 @@ const captionHasTriggerWord = (caption, triggerWord) => {
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return new RegExp(`(?:^|[^a-z0-9_])${escaped}(?:[^a-z0-9_]|$)`, 'i').test(text);
};
+// Mirror of server/lib/loraDataset.js analyzeCaptionInvariants — flags the
+// identity fragments repeated across most captions (which bind the character to
+// the caption phrases instead of the trigger token, issue #1320). Page-local so
+// the advisory updates the instant a caption is edited, without a refetch; the
+// authoritative strip recomputes server-side. Port logic changes here when the
+// server helper changes.
+const INVARIANT_SHARE_THRESHOLD = 0.8;
+const MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS = 4;
+const captionBody = (caption, triggerWord) => {
+ const word = (triggerWord || '').trim();
+ let body = (caption || '').trim();
+ if (word) {
+ const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ body = body.replace(new RegExp(`^${escaped}(?=[\\s,]|$)\\s*,?\\s*`, 'i'), '');
+ }
+ return body;
+};
+const splitCaptionFragments = (caption, triggerWord) => captionBody(caption, triggerWord)
+ .split(',').map((f) => f.trim()).filter(Boolean);
+const normalizeFragment = (f) => (f || '').trim().toLowerCase().replace(/\s+/g, ' ');
+const analyzeCaptionInvariants = (images, triggerWord) => {
+ const list = Array.isArray(images) ? images : [];
+ const word = (triggerWord || '').trim();
+ const captioned = list.filter((img) => img?.status === 'ready' && captionHasTriggerWord(img.caption, word));
+ const total = captioned.length;
+ if (total < MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS) return { analyzable: false, total, sharedFragments: [] };
+ const counts = new Map();
+ for (const img of captioned) {
+ const seen = new Set();
+ for (const frag of splitCaptionFragments(img.caption, word)) {
+ const norm = normalizeFragment(frag);
+ if (!norm || seen.has(norm)) continue;
+ seen.add(norm);
+ const cur = counts.get(norm) || { fragment: frag, count: 0 };
+ cur.count += 1;
+ counts.set(norm, cur);
+ }
+ }
+ const sharedFragments = [...counts.entries()]
+ .filter(([, v]) => v.count >= 2 && v.count / total >= INVARIANT_SHARE_THRESHOLD)
+ .map(([normalized, v]) => ({ fragment: v.fragment, normalized, count: v.count, ratio: v.count / total }))
+ .sort((a, b) => b.count - a.count || a.fragment.localeCompare(b.fragment));
+ return { analyzable: true, total, sharedFragments };
+};
const deriveReadiness = (images, triggerWord) => {
const list = Array.isArray(images) ? images : [];
const word = (triggerWord || '').trim();
@@ -220,6 +265,7 @@ export default function LoraDatasetDetail() {
// server auto-pick a vision model". Lifted from CaptionModelPicker so caption
// runs pass the explicit selection.
const [captionModel, setCaptionModel] = useState({ providerId: null, model: null });
+ const [strippingFragments, setStrippingFragments] = useState(false);
const fileInputRef = useRef(null);
const refresh = useCallback(() => getLoraDataset(datasetId)
@@ -269,6 +315,29 @@ export default function LoraDatasetDetail() {
[dataset?.images, dataset?.triggerWord],
);
+ // Caption-lint advisory: identity fragments repeated across most captions
+ // (issue #1320). Derived live so it tracks manual caption edits without a
+ // refetch; the "Strip" action recomputes server-side.
+ const captionInvariants = useMemo(
+ () => analyzeCaptionInvariants(dataset?.images, dataset?.triggerWord),
+ [dataset?.images, dataset?.triggerWord],
+ );
+
+ const stripSharedFragments = async () => {
+ setStrippingFragments(true);
+ try {
+ const { dataset: next, removedFragments, updatedImages } = await stripLoraDatasetSharedCaptionFragments(datasetId);
+ setDataset(next);
+ if (removedFragments.length) {
+ toast.success(`Stripped ${removedFragments.length} shared identity fragment${removedFragments.length === 1 ? '' : 's'} from ${updatedImages} caption${updatedImages === 1 ? '' : 's'}`);
+ } else {
+ toast.success('No shared identity fragments to strip');
+ }
+ } finally {
+ setStrippingFragments(false);
+ }
+ };
+
// Poll while any image renders — the server heals stuck images on read.
const renderingCount = readiness.rendering;
useEffect(() => {
@@ -527,6 +596,48 @@ export default function LoraDatasetDetail() {
<CaptionModelPicker onChange={onCaptionModelChange} />
</div>
+ {captionInvariants.sharedFragments.length > 0 && (
+ <div className="bg-port-warning/10 border border-port-warning/40 rounded-lg p-3 text-sm">
+ <div className="flex items-start gap-2">
+ <AlertTriangle className="w-4 h-4 text-port-warning shrink-0 mt-0.5" />
+ <div className="min-w-0 flex-1 space-y-2">
+ <p className="text-gray-200">
+ <span className="font-medium text-port-warning">Identity is leaking into the captions.</span>
+ {' '}
+ These fragments repeat across most captions, so the model binds the look to the phrases instead of the
+ {' '}
+ <span className="font-mono text-gray-300">{dataset.triggerWord || 'trigger'}</span>
+ {' '}
+ token — the trigger then renders a generic subject. Keep only what changes shot-to-shot (pose, framing,
+ setting) and let the trigger absorb the fixed identity.
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ {captionInvariants.sharedFragments.map((f) => (
+ <span
+ key={f.normalized}
+ className="text-xs px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-gray-300 font-mono"
+ title={`in ${f.count} of ${captionInvariants.total} captions`}
+ >
+ {f.fragment}
+ <span className="text-gray-500"> ·{f.count}/{captionInvariants.total}</span>
+ </span>
+ ))}
+ </div>
+ <button
+ type="button"
+ onClick={stripSharedFragments}
+ disabled={strippingFragments || !!captionRun}
+ className="px-3 py-1.5 text-xs rounded bg-port-warning/20 text-port-warning hover:bg-port-warning/30 flex items-center gap-2 disabled:opacity-50"
+ title="Remove these shared fragments from every caption, keeping the trigger word and per-shot detail"
+ >
+ {strippingFragments ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Eraser className="w-3.5 h-3.5" />}
+ Strip shared identity from all captions
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
<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" />
@@ -549,6 +660,17 @@ export default function LoraDatasetDetail() {
<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>
+ <p className="pt-1 border-t border-port-border/60">
+ <span className="text-gray-300">Caption what changes shot-to-shot, not who the subject is.</span> The
+ {' '}
+ <span className="font-mono text-gray-400">{dataset.triggerWord || 'trigger word'}</span>
+ {' '}
+ token is what the LoRA binds the fixed identity to — describe pose, framing, expression, outfit, and setting
+ in each caption, and leave invariant features (hair, eyes, skin, signature items) out. Repeating the same
+ identity phrases in every caption teaches those words instead of the trigger, so the bare trigger then
+ renders a generic subject. Captions are auto-prefixed with the trigger; this page warns when identity
+ fragments repeat across most captions and offers a one-click strip.
+ </p>
</div>
</details>
diff --git a/client/src/services/apiLoraTraining.js b/client/src/services/apiLoraTraining.js
index 6fce734145..98fd02289f 100644
--- a/client/src/services/apiLoraTraining.js
+++ b/client/src/services/apiLoraTraining.js
@@ -73,6 +73,11 @@ export const updateLoraDatasetImageCaption = (id, imageId, caption) =>
export const deleteLoraDatasetImage = (id, imageId) =>
request(`/lora-datasets/${id}/images/${imageId}`, { method: 'DELETE' });
+// Strip the identity fragments shared across most captions so the trigger token
+// learns the character (issue #1320). Returns { dataset, removedFragments, updatedImages }.
+export const stripLoraDatasetSharedCaptionFragments = (id) =>
+ request(`/lora-datasets/${id}/strip-shared-fragments`, { method: 'POST' });
+
// ---- Training runs ----
export const getLoraTrainingStatus = () => request('/lora-training/status');
diff --git a/server/lib/README.md b/server/lib/README.md
index 535203ce5b..6f8a79105d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -185,7 +185,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection). |
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
-| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
+| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |
diff --git a/server/lib/loraDataset.js b/server/lib/loraDataset.js
index 65b9ce431a..44dd1be2a0 100644
--- a/server/lib/loraDataset.js
+++ b/server/lib/loraDataset.js
@@ -278,3 +278,99 @@ export function computeDatasetReadiness(dataset) {
quality: trainable ? datasetQualityTier(captioned.length) : 'insufficient',
};
}
+
+// A fragment shared by at least this fraction of the captioned images counts
+// as "invariant identity" the trigger token should absorb instead. Set high
+// (80%) on purpose: a *varying* attribute (pose, framing, a single view) shows
+// up in only a slice of the set, while baked-in identity (white hair, circlet,
+// tooth necklace) repeats in nearly every caption — so the threshold separates
+// "describe who she is" from "describe what changes shot-to-shot" without
+// flagging legitimate per-shot variation.
+export const INVARIANT_SHARE_THRESHOLD = 0.8;
+// Below this many captioned images "shared across most captions" is noise — a
+// 3-image dataset where 3/3 repeat a fragment proves nothing. Gate the analysis
+// so the warning only fires once there's enough signal to trust.
+export const MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS = 4;
+
+// Strip a single leading `"<triggerWord>"` token from a caption, returning the
+// descriptive body. Mirrors prefixCaption's own strip (same `(?=[\s,]|$)`
+// boundary so a trigger that prefixes a real word isn't amputated).
+const captionBody = (caption, triggerWord) => {
+ const word = trim(triggerWord);
+ let body = trim(caption);
+ if (word) {
+ body = body.replace(new RegExp(`^${escapeRe(word)}(?=[\\s,]|$)\\s*,?\\s*`, 'i'), '');
+ }
+ return body;
+};
+
+// Split a caption's descriptive body into comma-separated fragments. The
+// captioner (and the manual-caption convention) emit ONE comma-separated list,
+// so commas are the fragment boundary. Empty fragments are dropped.
+const splitCaptionFragments = (caption, triggerWord) => captionBody(caption, triggerWord)
+ .split(',')
+ .map((f) => f.trim())
+ .filter(Boolean);
+
+// Normalize a fragment for cross-caption comparison: lowercase, collapse
+// internal whitespace. "White Hair" and "white hair" are the same invariant.
+const normalizeFragment = (f) => trim(f).toLowerCase().replace(/\s+/g, ' ');
+
+/**
+ * Analyze the captioned images for invariant identity fragments — descriptive
+ * phrases (hair/eyes/skin/signature items) that repeat across most captions and
+ * therefore bind the character's identity to the caption PHRASES instead of the
+ * trigger token (the failure mode in issue #1320). Pure — callers pass the
+ * sanitized record's images.
+ *
+ * Counts each fragment once per caption (a caption repeating "white hair" twice
+ * still counts once) and flags fragments present in ≥`threshold` of the
+ * captioned images. Returns `{ analyzable, total, sharedFragments }` where each
+ * shared fragment is `{ fragment, normalized, count, ratio }`, ordered most-
+ * common first. `analyzable` is false (and `sharedFragments` empty) below
+ * `minCaptions` — not enough signal to trust.
+ */
+export function analyzeCaptionInvariants(images, triggerWord, {
+ threshold = INVARIANT_SHARE_THRESHOLD,
+ minCaptions = MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS,
+} = {}) {
+ const list = Array.isArray(images) ? images : [];
+ const word = trim(triggerWord);
+ const captioned = list.filter((img) => img?.status === 'ready' && captionHasTriggerWord(img.caption, word));
+ const total = captioned.length;
+ if (total < minCaptions) return { analyzable: false, total, sharedFragments: [] };
+ const counts = new Map(); // normalized → { fragment (first-seen display), count }
+ for (const img of captioned) {
+ const seen = new Set(); // de-dupe within one caption
+ for (const frag of splitCaptionFragments(img.caption, word)) {
+ const norm = normalizeFragment(frag);
+ if (!norm || seen.has(norm)) continue;
+ seen.add(norm);
+ const cur = counts.get(norm) || { fragment: frag, count: 0 };
+ cur.count += 1;
+ counts.set(norm, cur);
+ }
+ }
+ const sharedFragments = [...counts.entries()]
+ .filter(([, v]) => v.count >= 2 && v.count / total >= threshold)
+ .map(([normalized, v]) => ({ fragment: v.fragment, normalized, count: v.count, ratio: v.count / total }))
+ .sort((a, b) => b.count - a.count || a.fragment.localeCompare(b.fragment));
+ return { analyzable: true, total, sharedFragments };
+}
+
+/**
+ * Remove the given shared fragments from one caption, preserving the trigger
+ * prefix and the fragment order of everything kept. `fragmentsToStrip` is
+ * matched by normalized form, so case/whitespace differences still strip. A
+ * caption left with no descriptive body collapses to just the trigger word
+ * (still a valid binding-only caption). Idempotent — re-running strips nothing.
+ */
+export function stripSharedFragments(caption, fragmentsToStrip, triggerWord) {
+ const stripSet = new Set((Array.isArray(fragmentsToStrip) ? fragmentsToStrip : [])
+ .map(normalizeFragment)
+ .filter(Boolean));
+ if (!stripSet.size) return trim(caption);
+ const kept = splitCaptionFragments(caption, triggerWord)
+ .filter((frag) => !stripSet.has(normalizeFragment(frag)));
+ return prefixCaption(triggerWord, kept.join(', '));
+}
diff --git a/server/lib/loraDataset.test.js b/server/lib/loraDataset.test.js
index 1ad5717c99..03d78cc593 100644
--- a/server/lib/loraDataset.test.js
+++ b/server/lib/loraDataset.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
+ analyzeCaptionInvariants,
buildVariationMatrix,
captionHasTriggerWord,
computeDatasetReadiness,
@@ -11,6 +12,7 @@ import {
prefixCaption,
sanitizeDatasetImage,
sanitizeLoraDataset,
+ stripSharedFragments,
LORA_DATASET_SCHEMA_VERSION,
} from './loraDataset.js';
@@ -267,3 +269,106 @@ describe('captionHasTriggerWord', () => {
expect(captionHasTriggerWord('anything', '')).toBe(true);
});
});
+
+describe('analyzeCaptionInvariants', () => {
+ const trigger = 'freydis_of_quaervarr';
+ // Identity (white hair, circlet, tooth necklace) repeated in every caption;
+ // pose/view varies — the issue-#1320 failure mode.
+ const ready = (id, body) => ({ id, status: 'ready', caption: prefixCaption(trigger, body) });
+ const freydisImages = [
+ ready('a', 'white hair, circlet, tooth necklace, standing, front view'),
+ ready('b', 'white hair, circlet, tooth necklace, walking, side profile'),
+ ready('c', 'white hair, circlet, tooth necklace, sitting, three-quarter view'),
+ ready('d', 'white hair, circlet, tooth necklace, action pose, back view'),
+ ready('e', 'white hair, circlet, tooth necklace, arms crossed, front view'),
+ ];
+
+ it('flags identity fragments shared across most captions, not per-shot variation', () => {
+ const { analyzable, total, sharedFragments } = analyzeCaptionInvariants(freydisImages, trigger);
+ expect(analyzable).toBe(true);
+ expect(total).toBe(5);
+ const flagged = sharedFragments.map((f) => f.normalized);
+ expect(flagged).toContain('white hair');
+ expect(flagged).toContain('circlet');
+ expect(flagged).toContain('tooth necklace');
+ // Pose/view fragments appear in ≤2 captions → below the 0.8 threshold.
+ expect(flagged).not.toContain('standing');
+ expect(flagged).not.toContain('front view');
+ expect(flagged).not.toContain('walking');
+ });
+
+ it('is not analyzable below the minimum captioned count', () => {
+ const { analyzable, sharedFragments } = analyzeCaptionInvariants(freydisImages.slice(0, 3), trigger);
+ expect(analyzable).toBe(false);
+ expect(sharedFragments).toEqual([]);
+ });
+
+ it('only counts ready, trigger-bearing captions', () => {
+ const images = [
+ ...freydisImages,
+ { id: 'rendering', status: 'rendering', caption: '' },
+ { id: 'untriggered', status: 'ready', caption: 'white hair, circlet, tooth necklace, no trigger here' },
+ ];
+ const { total } = analyzeCaptionInvariants(images, trigger);
+ expect(total).toBe(5); // rendering + untriggered excluded
+ });
+
+ it('counts a duplicated fragment once per caption', () => {
+ const images = [
+ ready('a', 'white hair, white hair, circlet, pose1'),
+ ready('b', 'white hair, circlet, pose2'),
+ ready('c', 'white hair, circlet, pose3'),
+ ready('d', 'white hair, circlet, pose4'),
+ ];
+ const { sharedFragments } = analyzeCaptionInvariants(images, trigger);
+ const whiteHair = sharedFragments.find((f) => f.normalized === 'white hair');
+ expect(whiteHair.count).toBe(4); // not 5 despite the doubled fragment in 'a'
+ });
+
+ it('returns nothing for an empty or tiny image set', () => {
+ expect(analyzeCaptionInvariants([], trigger).sharedFragments).toEqual([]);
+ expect(analyzeCaptionInvariants(null, trigger).analyzable).toBe(false);
+ });
+});
+
+describe('stripSharedFragments', () => {
+ const trigger = 'freydis_of_quaervarr';
+
+ it('removes shared fragments and preserves the trigger + per-shot detail', () => {
+ const caption = prefixCaption(trigger, 'white hair, circlet, tooth necklace, standing, front view');
+ const out = stripSharedFragments(caption, ['white hair', 'circlet', 'tooth necklace'], trigger);
+ expect(out).toBe(`${trigger}, standing, front view`);
+ });
+
+ it('matches fragments case- and whitespace-insensitively', () => {
+ const caption = prefixCaption(trigger, 'White Hair, circlet, walking');
+ const out = stripSharedFragments(caption, ['white hair'], trigger);
+ expect(out).toBe(`${trigger}, circlet, walking`);
+ });
+
+ it('collapses to the bare trigger when only identity remained', () => {
+ const caption = prefixCaption(trigger, 'white hair, circlet');
+ const out = stripSharedFragments(caption, ['white hair', 'circlet'], trigger);
+ expect(out).toBe(trigger);
+ });
+
+ it('is idempotent and a no-op when nothing matches', () => {
+ const caption = prefixCaption(trigger, 'standing, front view');
+ expect(stripSharedFragments(caption, ['white hair'], trigger)).toBe(caption);
+ expect(stripSharedFragments(caption, [], trigger)).toBe(caption);
+ });
+
+ it('round-trips with analyzeCaptionInvariants — stripping clears the shared set', () => {
+ const ready = (id, body) => ({ id, status: 'ready', caption: prefixCaption(trigger, body) });
+ const images = [
+ ready('a', 'white hair, circlet, standing'),
+ ready('b', 'white hair, circlet, walking'),
+ ready('c', 'white hair, circlet, sitting'),
+ ready('d', 'white hair, circlet, action pose'),
+ ];
+ const { sharedFragments } = analyzeCaptionInvariants(images, trigger);
+ const toStrip = sharedFragments.map((f) => f.fragment);
+ const stripped = images.map((img) => ({ ...img, caption: stripSharedFragments(img.caption, toStrip, trigger) }));
+ expect(analyzeCaptionInvariants(stripped, trigger).sharedFragments).toEqual([]);
+ });
+});
diff --git a/server/routes/loraDatasets.js b/server/routes/loraDatasets.js
index 40918a523a..d68978d12a 100644
--- a/server/routes/loraDatasets.js
+++ b/server/routes/loraDatasets.js
@@ -23,6 +23,7 @@ import {
listDatasets,
patchDataset,
reconcileRenderingImages,
+ stripSharedCaptionFragments,
updateImageCaption,
} from '../services/loraDatasets.js';
import { generateDatasetImages, getDatasetVariationAxes, sliceReferenceSheet } from '../services/loraDatasetGenerate.js';
@@ -166,6 +167,13 @@ router.get('/:id/caption-runs/:runId/events', asyncHandler(async (req, res) => {
}
}));
+// Bulk caption lint — strip the identity fragments shared across most captions
+// so the trigger token (not the caption phrases) learns the character. The
+// server recomputes the shared set itself; no request body.
+router.post('/:id/strip-shared-fragments', asyncHandler(async (req, res) => {
+ res.json(await stripSharedCaptionFragments(req.params.id));
+}));
+
const imagePatchSchema = z.object({ caption: z.string().max(2000) });
router.patch('/:id/images/:imageId', asyncHandler(async (req, res) => {
const { caption } = validateRequest(imagePatchSchema, req.body);
diff --git a/server/services/loraDatasets.js b/server/services/loraDatasets.js
index b953db10ba..8f2dc98761 100644
--- a/server/services/loraDatasets.js
+++ b/server/services/loraDatasets.js
@@ -23,11 +23,13 @@ import { createCollectionStore } from '../lib/collectionStore.js';
import {
LORA_DATASET_SCHEMA_VERSION,
LORA_DATASET_ENTRY_KINDS,
+ analyzeCaptionInvariants,
computeDatasetReadiness,
deriveTriggerWord,
isValidTriggerWord,
prefixCaption,
sanitizeLoraDataset,
+ stripSharedFragments,
} from '../lib/loraDataset.js';
import { ServerError } from '../lib/errorHandler.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
@@ -427,6 +429,46 @@ export async function updateImageCaption(id, imageId, caption) {
return next.images.find((img) => img.id === imageId);
}
+/**
+ * Strip the invariant identity fragments shared across most captions (issue
+ * #1320) — phrases repeated in nearly every caption bind the character to the
+ * caption text instead of the trigger token. Recomputes the shared set
+ * server-side (never trusts a client-supplied fragment list) and rewrites every
+ * captioned image, leaving each caption with the trigger word + only what
+ * varies shot-to-shot. Returns `{ dataset, removedFragments, updatedImages }`;
+ * a no-op (nothing shared, or too few captions to analyze) leaves the record
+ * untouched and returns an empty `removedFragments`.
+ */
+export async function stripSharedCaptionFragments(id) {
+ const current = await requireDataset(id);
+ const { sharedFragments } = analyzeCaptionInvariants(current.images, current.triggerWord);
+ if (!sharedFragments.length) {
+ return {
+ dataset: { ...current, readiness: computeDatasetReadiness(current) },
+ removedFragments: [],
+ updatedImages: 0,
+ };
+ }
+ const toStrip = sharedFragments.map((f) => f.fragment);
+ let updatedImages = 0;
+ const next = await updateDataset(id, (record) => ({
+ ...record,
+ images: record.images.map((img) => {
+ if (img.status !== 'ready' || !img.caption) return img;
+ const stripped = stripSharedFragments(img.caption, toStrip, record.triggerWord);
+ if (stripped === img.caption) return img;
+ updatedImages += 1;
+ return { ...img, caption: stripped };
+ }),
+ }));
+ console.log(`🧹 Stripped ${sharedFragments.length} shared caption fragment(s) across ${updatedImages} image(s) — dataset=${id}`);
+ return {
+ dataset: { ...next, readiness: computeDatasetReadiness(next) },
+ removedFragments: sharedFragments,
+ updatedImages,
+ };
+}
+
export async function deleteImage(id, imageId) {
let removed = null;
await updateDataset(id, (current) => {
diff --git a/server/services/loraDatasets.test.js b/server/services/loraDatasets.test.js
index ffaab688e4..bdd8896d04 100644
--- a/server/services/loraDatasets.test.js
+++ b/server/services/loraDatasets.test.js
@@ -36,6 +36,7 @@ const {
listDatasets,
patchDataset,
reconcileRenderingImages,
+ stripSharedCaptionFragments,
updateDataset,
updateImageCaption,
} = await import('./loraDatasets.js');
@@ -404,3 +405,62 @@ describe('deleteDataset', () => {
await expect(getDataset(dataset.id)).rejects.toMatchObject({ status: 404 });
});
});
+
+describe('stripSharedCaptionFragments', () => {
+ // Build a captioned dataset where identity repeats and pose varies — the
+ // issue-#1320 failure mode. char-1's derived trigger is kessa_brightwater.
+ const seedFreydisDataset = async () => {
+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });
+ const captions = [
+ 'white hair, circlet, tooth necklace, standing',
+ 'white hair, circlet, tooth necklace, walking',
+ 'white hair, circlet, tooth necklace, sitting',
+ 'white hair, circlet, tooth necklace, action pose',
+ ];
+ for (let i = 0; i < captions.length; i += 1) {
+ const tmpPath = join(TEST_DATA_ROOT, `seed-${i}.png`);
+ await makePng(tmpPath);
+ const entry = await addUploadedImage(dataset.id, { tmpPath });
+ await updateImageCaption(dataset.id, entry.id, `kessa_brightwater, ${captions[i]}`);
+ }
+ return dataset.id;
+ };
+
+ it('strips shared identity fragments and keeps per-shot detail + the trigger', async () => {
+ const id = await seedFreydisDataset();
+ const { dataset, removedFragments, updatedImages } = await stripSharedCaptionFragments(id);
+ expect(updatedImages).toBe(4);
+ expect(removedFragments.map((f) => f.normalized).sort())
+ .toEqual(['circlet', 'tooth necklace', 'white hair']);
+ for (const img of dataset.images) {
+ expect(img.caption).toMatch(/^kessa_brightwater,/);
+ expect(img.caption).not.toContain('white hair');
+ expect(img.caption).not.toContain('circlet');
+ // The varying pose fragment survives.
+ expect(img.caption).toMatch(/standing|walking|sitting|action pose/);
+ }
+ // Every image still carries the trigger token → readiness unchanged on that axis.
+ expect(dataset.readiness.captioned).toBe(4);
+ });
+
+ it('is a no-op when no fragment is shared across most captions', async () => {
+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });
+ const tmpPath = join(TEST_DATA_ROOT, 'lonely.png');
+ await makePng(tmpPath);
+ const entry = await addUploadedImage(dataset.id, { tmpPath });
+ await updateImageCaption(dataset.id, entry.id, 'kessa_brightwater, unique pose');
+ const { removedFragments, updatedImages } = await stripSharedCaptionFragments(dataset.id);
+ expect(removedFragments).toEqual([]);
+ expect(updatedImages).toBe(0);
+ const after = await getDataset(dataset.id);
+ expect(after.images[0].caption).toBe('kessa_brightwater, unique pose');
+ });
+
+ it('is idempotent — a second strip removes nothing', async () => {
+ const id = await seedFreydisDataset();
+ await stripSharedCaptionFragments(id);
+ const second = await stripSharedCaptionFragments(id);
+ expect(second.removedFragments).toEqual([]);
+ expect(second.updatedImages).toBe(0);
+ });
+});