Gallery Links & Image Keywords — Design Document
Overview
A creator builds a gallery of images for a character — expressions, outfits, scenes. Today that gallery is a private organizational tool: the images can be picked into an avatar field one at a time, but nothing connects the set to the character.
This links them. Attach a gallery to a character and two things follow:
- In chat, the gallery's images become keyword-triggered — the same mechanism that already surfaces a lorebook entry's picture when its keywords fire, on the same rail, in the same panel.
- On the character's detail page, a granted gallery becomes browsable, so a reader can look through the art without opening the chat.
Keywords are optional. An image with none is browsable but never fires on its own.
V1 is character-only. The storage is entity-generic — entity_type + entity_id, the shape
gallery_image_entity_links already uses — but every workflow, endpoint, surface and acceptance
criterion in this document targets characters. See Why not lorebooks in
v1.
Design Goals
- Reuse the keyword machinery, don't clone it. The trigger/include/exclude semantics, the exact-match toggle, and the safe-regex path already exist and are already understood by creators who have written a lorebook. The same rules apply here, rendered by the same editor — which this work extracts, because that editor exists in three divergent copies today.
- Reuse the triggered-image rail — and finish it.
MatchedEntryImage→ pipeline context → SSE gate →TriggeredEntryImagesPanelis shipped. It is also transient: nothing persists which image fired, so a reload silently loses every picture in the history. Gallery images ride that rail, which means generalizing it and giving it persistence. - Two grant granularities, because creators work at both. A whole gallery is the unit for browsing; a single image is the unit for precision.
- Keywords belong wherever the creator needs them — on the image when they describe the image, on the grant when they are specific to one character.
- Capability, not visibility, decides exposure.
is_publicon a gallery is about standalone gallery discovery. What a grant does is decided by the grant — on gallery grants and image grants alike. See Visibility and capability. - A grant is a deliberate act, never an inference. Automatic bookkeeping rows are not grants, and no migration turns one into the other. See Why grants are a new table.
- No new anonymous exposure. The browse surface is authenticated-only until the platform's anonymous maturity gate exists.
Non-Goals
Deliberately out of scope — several of these a reader would reasonably assume are in:
- Lorebook and package sources in v1. Storage and the matcher's source-resolution step are written entity-generically so neither needs a rewrite, but only characters are wired.
- Vision injection (Side B). Triggered gallery images are shown to the reader, never sent to the LLM as multimodal content. Lorebook Side B has never shipped either; building gallery Side B first would put the expensive half of the feature in front of the cheap one.
- Assistant-output or tracker-driven image reactions. Reacting to what the model wrote is a post-LLM concern and belongs with Chat Scripts / Side B, not hidden inside a pre-LLM matcher.
- Typed asset roles (portrait / expression / outfit / background / scene). A real future need, and deliberately kept a separate axis from trigger keywords — a role is what an image is, a keyword is when it shows. Collapsing them would make both worse.
- Anonymous browsing of a granted gallery. See The anonymous blocker.
- Gallery-level keywords. A gallery is a container; keywords describe what an image depicts. Keywords on the container would fire every image in the folder on the same word, which is never what a creator means. See Why the gallery link carries no keywords.
- Superseding
recall_keyword. The single-keyword{{image:kw}}explicit-reference design ongallery_images.recall_keywordstays as-is (column shipped, resolution still unbuilt). It is a deliberate reference mechanism; this feature is automatic triggering. See Two mechanisms, deliberately. - Migrating lorebook entries onto the shared keyword table. The two tables coexist by design; convergence is a future consideration for when lorebook keywords are next touched, not a scheduled slice — see Built in parallel.
- A carousel. Same as lorebook Side A v1: the top match renders. The list is carried and persisted so the renderer can be swapped later without losing history.
Why not lorebooks in v1
The introduction to earlier drafts promised "character or lorebook". That promise was never designed. A lorebook gallery raises questions a character gallery does not:
- A conversation has many active lorebooks, not one character. Which sources contribute?
- Entry pictures already fire from lorebooks. A gallery linked to the same lorebook competes with them — what is the priority, and is it per-lorebook or global?
- Lorebooks are shared and forked far more than characters. Whose grant survives a fork?
- A lorebook detail page has no established media section to hang browse off.
None of those are hard; all of them are decisions, and none of them are needed to ship the character case. So v1 is character-only and honest about it, and the matcher resolves an abstract asset-source set for the conversation (today: one character) rather than hardcoding a character id — which is what keeps lorebook, package and multi-character sources from being a rewrite.
The three association kinds
The existing table is doing one job. This feature needs three, and conflating them is what an earlier draft got wrong.
| Automatic reference (exists) | Explicit grant (new) | Gallery grant (new) | |
|---|---|---|---|
| Table | gallery_image_entity_links |
gallery_image_entity_grants |
gallery_entity_grants |
| Written by | primary-image setters, package save, moderation plumbing | the creator, deliberately | the creator, deliberately |
| Means | "this image is referenced by this entity" | "this image is granted to this entity" | "this set is granted to this entity" |
| Drives | moderation cascade, usage tracking, picker filtering | trigger candidacy + browse, per capability | trigger candidacy + browse, per capability |
| Reader-visible | never | per capability | per capability |
| Keywords | — | optional, scoped to this pairing | none — see below |
A gallery grant and an image grant compose: granting a gallery makes its images candidates using each image's own keywords; adding an image grant on top overrides the keywords for one character without touching the image everywhere else.
Why grants are a new table, not a flag
gallery_image_entity_links is written from two very different places:
- Deliberately, by the link/unlink endpoints behind
EntityImagesSection. - Automatically, as bookkeeping, whenever a primary image is set —
SetAvatarImageAsync(CreatorCharacterRepository.cs:137), lorebook and entry pictures (LorebookRepository.cs:148,332), persona avatars (PersonaRepository.cs:193), persona template avatars (PersonaTemplateRepository.cs:132), project covers (ProjectRepository.cs:331), package save, and the legacy URL migration (38_migrate_legacy_image_urls.sql). These exist so moderation cascades and usage tracking can find the image — not because a creator granted anything.
And every one of those writers leaves stale rows on change. Each is an INSERT … ON CONFLICT DO NOTHING with no delete of the row it supersedes: swap a character's avatar, a persona's, a
template's or a project's cover and the old image's row stays behind. An earlier draft of this
document said PersonaRepository and LorebookRepository "clean up" — they do not. Persona deletes
only in ClearAvatarImageAsync (PersonaRepository.cs:204), and the lorebook delete
(LorebookRepository.cs:527) fires on entry deletion, not on picture replacement. Neither is a
change-path cleanup. ProjectRepositoryTests.cs:720 already documents the resulting pile-up.
That correction strengthens the case rather than weakening it: there is no writer whose rows can be
trusted as deliberate, so no heuristic over this table can separate intent from bookkeeping.
An earlier draft proposed a scalar link_source column on that table. That was wrong twice:
- A scalar cannot represent reality. The table has one row per (image, entity) composite key,
and a single row can legitimately mean both "current avatar bookkeeping" and "creator granted
this image".
LinkImageToEntityAsyncusesON CONFLICT DO NOTHINGandUnlinkImageFromEntityAsyncdoes an unconditionalDELETE(GalleryRepository.cs:539,552) — so with a scalar, "unlink the grant" would also delete the avatar's bookkeeping row, and "set the avatar" over an existing grant would silently do nothing. Every automatic↔explicit transition would have been undefined. - The proposed backfill was inverted. It read "is this image currently the entity's primary? → automatic, else → explicit". Stale avatars are by definition not current, so that rule labelled precisely the dangerous rows as explicit grants — reintroducing the exact bug it was written to prevent.
A separate table removes all of it. Grants start empty, so no legacy row becomes reader-visible or trigger-eligible by migration — the only way in is a creator deliberately granting. The automatic table keeps its current semantics, untouched, and the five repositories that write it are unaffected. Coexistence is the representation: an image can have a bookkeeping row, a grant row, both, or neither, and each is created and deleted independently.
The migration test that matters is a stale avatar row: after migrating, it must be trigger- ineligible and reader-invisible, and it must stay that way until someone deliberately grants it.
The two grant tables
Both are polymorphic on entity_type + entity_id, with no FK on the polymorphic reference — the
shape gallery_image_entity_links and entity_tracker_bindings already use.
CREATE TABLE IF NOT EXISTS gallery_entity_grants (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
gallery_id INTEGER NOT NULL REFERENCES galleries(id) ON DELETE CASCADE,
entity_type SMALLINT NOT NULL,
entity_id INTEGER NOT NULL,
use_in_chat BOOLEAN NOT NULL DEFAULT FALSE,
show_on_entity BOOLEAN NOT NULL DEFAULT FALSE,
sort_order INTEGER NOT NULL DEFAULT 0,
granted_by_user_id INTEGER NOT NULL REFERENCES users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (gallery_id, entity_type, entity_id),
CONSTRAINT ck_geg_entity_type CHECK (entity_type IN (0)), -- character only in v1
CONSTRAINT ck_geg_sort_order CHECK (sort_order >= 0),
CONSTRAINT ck_geg_entity_id CHECK (entity_id > 0)
);
CREATE TABLE IF NOT EXISTS gallery_image_entity_grants (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
gallery_image_id INTEGER NOT NULL REFERENCES gallery_images(id) ON DELETE CASCADE,
entity_type SMALLINT NOT NULL,
entity_id INTEGER NOT NULL,
use_in_chat BOOLEAN NOT NULL DEFAULT FALSE,
show_on_entity BOOLEAN NOT NULL DEFAULT FALSE,
keyword_mode SMALLINT NOT NULL DEFAULT 0,
keywords_json TEXT NOT NULL DEFAULT '[]',
include_keywords_json TEXT NOT NULL DEFAULT '[]',
exclude_keywords_json TEXT NOT NULL DEFAULT '[]',
trigger_regex TEXT NULL,
use_exact_keyword_match BOOLEAN NOT NULL DEFAULT TRUE,
sort_order INTEGER NOT NULL DEFAULT 0,
granted_by_user_id INTEGER NOT NULL REFERENCES users(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (gallery_image_id, entity_type, entity_id),
CONSTRAINT ck_gieg_entity_type CHECK (entity_type IN (0)),
CONSTRAINT ck_gieg_keyword_mode CHECK (keyword_mode IN (0, 1, 2)),
CONSTRAINT ck_gieg_sort_order CHECK (sort_order >= 0),
CONSTRAINT ck_gieg_entity_id CHECK (entity_id > 0),
CONSTRAINT ck_gieg_regex CHECK (trigger_regex IS NULL
OR (btrim(trigger_regex) <> '' AND length(trigger_regex) <= 500))
);
CREATE INDEX IF NOT EXISTS idx_gallery_entity_grants_target
ON gallery_entity_grants (entity_type, entity_id);
CREATE INDEX IF NOT EXISTS idx_gallery_image_entity_grants_target
ON gallery_image_entity_grants (entity_type, entity_id);
Four deliberate choices in that DDL:
The JSON arrays are the authoring state; keyword_bindings is the derived index. The grant
carries keywords_json / include_keywords_json / exclude_keywords_json exactly as
lorebook_entries and gallery_images do, and a sync trigger projects them into
keyword_bindings in the same transaction as the write. An earlier draft gave the grant a
keyword_mode and a regex but no arrays, which left the override mode with nothing to override
with. Authoring state round-trips through the API; the binding table is never edited directly.
Capabilities default FALSE. The database fails closed: a row written by an import, a migration or a direct SQL path discloses nothing until something explicitly turns a surface on. The endpoint always sets both explicitly from the creator's choice, and the UI offers sensible defaults — a public gallery proposes both surfaces, a private one proposes chat-only — but the default a non-UI writer inherits is "no exposure", not "both".
The entity_type CHECK is deliberately narrow, and widening it later is not a one-line
edit — an earlier draft said it was. CREATE TABLE IF NOT EXISTS does not touch an existing table,
so a changed constraint in the create block is a no-op on every database that already ran it.
Admitting a new entity type means an explicit idempotent ALTER TABLE … DROP CONSTRAINT … ADD CONSTRAINT, named so the next person doesn't ship a widening that silently never applied.
The surrogate id is the keyword owner. It lives here, on a new table, which means
gallery_image_entity_links needs no schema change at all — an earlier draft added a surrogate
column to that shipped table for exactly this, and it is no longer necessary.
Nesting interaction — checked against the shipped implementation
Granting a parent gallery does not implicitly grant its subfolders. That is the Gallery Folders organization-only invariant — nesting must never become a traversal rule anywhere else in the system. A creator who wants a subfolder's images to trigger grants the subfolder too.
The shipped nesting implementation holds that invariant on every path checked:
| Path | Behaviour |
|---|---|
| Public gallery read | returns a flat image list; PublicGalleryDetailResponse carries no child galleries at all |
vw_galleries.image_count |
counts gi.gallery_id = g.id only — no descent into children |
| Public response shape | no parent_uuid, so a public child does not disclose its parent |
fn_delete_gallery |
promotes children to roots and leaves their images untouched — grants on a promoted child survive, grants on the deleted parent cascade away with it |
fn_place_gallery |
moving a gallery changes parent_id only; grants key on the gallery, so nothing a reader sees changes |
Two consequences the design has to state, because the implementation makes them true and neither is obvious:
Visibility is per-gallery in both directions, and neither direction cascades. Each gallery's
is_public stands alone; the shipped code has no traversal either way. That gives two cases with very
different ergonomics:
| Case | Behaviour | Verdict |
|---|---|---|
| Private subfolder inside a public parent | the parent's public read returns only its own images (gallery_id = g.id), carries no child galleries, image_count does not descend, and a cover must be an image from that same gallery (SetCoverImageAsync enforces gi.gallery_id = g.id) |
works, and is safe — nothing about the child leaks through the parent |
| Public subfolder under a private parent | the child stays readable, anonymously | correct, but a surprise |
The first case is the useful one and it is already supported end to end — the visibility toggle lives on the gallery detail panel and applies to whichever gallery is selected, root or child. "Public parent for browsing, private subfolder for the variants I don't want browsable" is a real workflow and it needs no new capability.
The second case is GetPublicByUuidAsync filtering on the row's own is_public with no parent check
(GalleryRepository.cs:364). Organization-only makes it correct — a folder is not a permission
boundary — but "I made the parent private" reads to a creator as "I hid what's inside", and it does
not. It widens the first of the anonymous rails named in
docs-internal/architecture/trust-and-safety/APPROVED_MEDIA.md rather than adding a new one.
Both cases make the current toggle copy wrong. "Public galleries can be viewed by anyone. Private galleries are only visible to you" was written before nesting and says nothing about cascade. It needs to state that visibility does not inherit in either direction, and making a parent private needs to warn when it has public children.
Depth is capped at two, so the grant surface is bounded. Only a root may hold children, and a
gallery with children cannot itself be given a parent. "List subfolders as their own grantable rows"
therefore means exactly one extra level — never a tree the editor has to recurse. The editor reuses
GalleryTreeSelect, and a granted parent renders its subfolders visibly ungranted rather than
simply absent: absence reads as "there is nothing here", which is precisely the wrong conclusion.
Visibility and capability
Earlier drafts said three things that cannot all be true at once: the matcher takes every image in
a linked gallery, browse requires is_public, and a non-public gallery "renders to nobody but the
owner". Read together they imply a private gallery both does and does not reach a reader.
The resolution is to stop overloading is_public:
| Control | Decides |
|---|---|
galleries.is_public |
whether the gallery is discoverable as a gallery, on its own URL |
grant use_in_chat |
whether the granted images are trigger candidates in that entity's chats |
grant show_on_entity |
whether they render in the browsable section on the entity's detail page |
Both capabilities live on both grant tables. A creator can grant a single image chat-only without publishing it on the character page, and the reverse — which is the whole point of calling this a capability model rather than a visibility one. An earlier draft put the capabilities on gallery grants only and left direct image links driving both surfaces automatically, which contradicted its own stated principle.
A creator may deliberately grant a private gallery for chat use — a working folder of expressions they don't want browsable is a completely reasonable thing to want. The grant editor warns in plain language when it happens: "Readers chatting with this character will see images from this private gallery." That is a grant the creator makes knowingly, not a leak.
show_on_entity on a private gallery is likewise allowed, and warns harder, because browse is a
much wider disclosure than an occasional keyword hit.
Two rules apply to every reader-facing projection this feature adds — chat and browse alike:
Moderation is filtered positively at the query:
moderation_status = 0. Not<> 1. An allowlist fails closed when a status value is added later or a row carries something unexpected; a denylist of one silently admits everything new.Maturity is filtered against the viewer's server-resolved ceiling, not a caller-supplied parameter.
ContentImageblur is presentation; it is not access control, and a payload containing an NSFW image URL has already disclosed the image to anyone reading the network tab.For chat this is not free: the pipeline has no viewer ceiling on it today.
RequestAccess.Ceilingmust be plumbed into the pipeline context beforep_max_ratingmeans anything at the matcher, and that plumbing is part of the matcher slice, not an assumption it can make.
Three projections, not one
fn_get_entity_linked_images serves consumers with opposite requirements, and narrowing it
globally would break them. AdminPublicVisibilityRequestEndpoints calls it with
includeUnderReview: true specifically so an approver sees the complete evidence
(AdminPublicVisibilityRequestEndpoints.cs:197) — and its own code comment records that gallery
images being silently omitted from that projection was a previously-fixed bug, because "a
mislabeled gallery image ... was invisible to the human review this allowlist's fail-closed
guarantee depends on". Filtering it down to reader-visible explicit grants would re-break exactly
that fix.
So three contracts, deliberately separate:
| Projection | Contains |
|---|---|
| Owned / management | every association: automatic references and grants, with provenance, capabilities, keyword configuration and review state |
| Moderation | complete evidence — automatic rows, under-review images, pending revisions. Unchanged from today. |
Viewer (entityMedia) |
explicit grants only, capability-gated, moderation_status = 0, maturity-filtered |
fn_get_entity_linked_images stays exactly what it is — the reader for automatic-reference
evidence, unchanged in contract. It gets one strict bug fix and nothing else:
Done, F-10 (JOIN galleries g ON g.id = gi.gallery_idis an inner join1804fd269, 2026-10-27): the join is aLEFT JOINwith nullable gallery metadata, so a directly-linked unsorted image (gallery_images.gallery_idis NULL,31_tables_galleries.sql:82) now reaches the owner's linked-image list and the approver's evidence. Readers still never get it: an unsorted image is as private as a private-gallery one, and the C# public filter and the protected-reader rating gate are unchanged and pinned. The server-side withholding of mature images for an adult with mature content off is still not built.
All three projections are new functions. An earlier draft cast this function as the
management/moderation read with a LEFT JOIN repair, which it cannot be: management needs grants,
capabilities, keyword configuration, immutable asset versions and pending revisions, and moderation
needs revision diffs — none of which exist in a function that reads one association table. Repairing
a legacy evidence reader is not the same as building a management projection, and conflating them is
how the legacy reader ends up growing five optional flags.
So: the legacy reader keeps its job, and management, moderation and viewer each get their own purpose-built reader — the viewer one owned by the approved-media substrate, not by this feature.
Keywords: two homes, one precedence
Answering the "on the grant or on the image" question with both:
- Image keywords — columns on
gallery_images. Travel with the image everywhere it is used. This is the common case: a portrait taggedangry, furious, snarlmeans that wherever it shows up. - Grant keywords — on
gallery_image_entity_grants. Scoped to that one image-entity pairing.
An empty grant keyword set is ambiguous — it could mean "I haven't set any, use the image's" or "I want this image silent for this character". Those are different intents, and a nullable JSON column cannot express both. So the grant carries an explicit mode:
keyword_mode |
Meaning |
|---|---|
0 inherit (default) |
use the image's own keywords |
1 override |
use the grant's keywords instead of the image's — they do not merge |
2 disabled |
this image never fires for this entity, whatever the image says |
Override replaces rather than merges because merging makes "why did this fire?" unanswerable without reading two rows. Replacement is explainable in one sentence and is what a creator reaching for a per-character override actually wants. An override with an empty keyword set is legal and means "fires only via regex, if set" — it is not a silent fallback to inherit.
Each home carries the full lorebook set, because that is what "full featured" means here:
| Field | Semantics |
|---|---|
keywords_json |
OR — any match fires |
include_keywords_json |
AND — all must also appear |
exclude_keywords_json |
NOT — any appearance vetoes, globally (see matching) |
use_exact_keyword_match |
word-boundary (default) vs substring |
trigger_regex |
POSIX, matched through fn_safe_regex_match so an invalid pattern returns false instead of throwing |
Hard limits, enforced at the endpoint and mirrored in the editor: 64 keywords per field, 100
characters per keyword, 500 characters of trigger_regex, keywords trimmed and rejected when blank.
These are not defensive decoration — every one of them is a row that ends up in an index and a term
that ends up in a per-turn query.
Why the gallery link carries no keywords
A gallery is a container. Keywords describe what an image depicts. Putting keywords on the container means every image inside fires on the same word — so the panel shows an arbitrary one of them, and the creator has no way to say which. The two useful granularities are "this image, always" and "this image, for this character", and both are covered above.
Two mechanisms, deliberately
gallery_images.recall_keyword (single keyword, unique per gallery, ^[a-z0-9_]{3,50}$) is for
explicit references — a creator writes {{image:elara_happy}} in a mode or greeting and means
that image, there. This feature is automatic triggering — the image surfaces because the
conversation drifted onto its subject.
They are different intents and both are legitimate. To keep them from reading as two competing
keyword fields on one form, the image editor groups them separately with distinct copy: "Show this
image when the conversation mentions…" (triggers) versus "Reference this image directly with
{{image:…}}" (recall). Recall-keyword resolution remains unbuilt and out of scope here.
The keyword substrate
Lorebook entries already store keywords in a normalized table, kept in sync from the three JSON columns by a trigger:
lorebook_entry_keywords (lorebook_entry_id, keyword, keyword_type)
keyword_type: 0 = trigger (OR) | 1 = include (AND) | 2 = exclude (NOT)
synced by trg_sync_lorebook_entry_keywords, keywords stored pre-lowered and deduped
Two owners now need exactly this. The durable shape is one polymorphic table:
CREATE TABLE IF NOT EXISTS keyword_bindings (
owner_type SMALLINT NOT NULL,
owner_id BIGINT NOT NULL,
keyword TEXT NOT NULL,
keyword_type SMALLINT NOT NULL,
PRIMARY KEY (owner_type, owner_id, keyword, keyword_type),
CONSTRAINT ck_keyword_bindings_owner CHECK (owner_type IN (0, 1)),
CONSTRAINT ck_keyword_bindings_type CHECK (keyword_type IN (0, 1, 2)),
CONSTRAINT ck_keyword_bindings_value CHECK (keyword = btrim(keyword)
AND keyword = lower(keyword)
AND keyword <> ''
AND length(keyword) <= 100)
);
CREATE INDEX IF NOT EXISTS idx_keyword_bindings_lookup
ON keyword_bindings (keyword, keyword_type, owner_type);
owner_type: 0 = gallery_images.id, 1 = gallery_image_entity_grants.id. Both owners already
carry a single-column identity, so gallery_image_entity_links needs no schema change at all —
an earlier draft added a surrogate id to that shipped table purely to make it a keyword owner, and
moving grants to their own table removed the need.
The value CHECK also pins lower(keyword) = keyword, so a row that skipped the normalizer cannot
sit in the table matching nothing.
Lifecycle. keyword_bindings has no FK — it is polymorphic, so cascade cannot do this. It gets
cleanup triggers on both owner tables, and on the target entity so a removed character does not
leave orphaned grants and keywords behind.
The precedent is not entity_tracker_bindings: that file says so itself — "For OWNER deletion:
there are no orphan-cleanup triggers on this table today" (68_tables_trackers.sql:114), and
points at the proposal-orphan-cleanup family as the shape to copy. That is the real precedent
(25c_entity_proposal_orphan_cleanup.sql, 25l_project_item_proposal_orphan_cleanup.sql), and it
matters how it is copied: those files install both a soft-delete and a hard-delete trigger,
because fn_delete_character is a soft delete — it sets is_deleted, it does not remove the row
(06_character_migration_functions.sql:113). A DELETE trigger alone would never fire on the
normal deletion path, and the cleanup acceptance criterion would silently never be met.
The migration is idempotent, carries a rerun test, and repairs partial application — a rerun after an interrupted migration must converge, not fail on a half-created object.
Built in parallel; lorebook stays untouched
Rule-of-two says fold lorebook_entry_keywords into this table and delete it. This plan
deliberately does not, and does not schedule it either.
The reason is where the lorebook matcher lives: inside fn_search_lorebook, a large scoring query
that runs on every conversation turn. Re-pointing it at a new table is a hot-path change with
its own measurement burden and its own regression surface, and this feature gets nothing from it.
Scheduling that migration as a follow-up slice would only mean carrying a risky, low-value task on
a plan that does not need it — and half-done migrations rot.
So the two tables coexist by design:
lorebook_entry_keywords— untouched. Same shape, same sync trigger, same matcher, same performance envelope. Nothing about lorebook entries changes.keyword_bindings— the polymorphic table, carrying gallery images and image links.
Reuse a function; rewriting one is a different change
The rule this plan follows, stated once because it decides several things below: calling an existing function is free; changing one is a separate change with its own risk analysis and mitigation. A shared helper is only shared safely when adopting it is provably a no-op for the existing caller — and "provably" means reading the function, not assuming.
So fn_normalize_keywords(p_json TEXT) RETURNS TEXT[] is extracted verbatim from
fn_sync_lorebook_entry_keywords (05_tables_lorebooks.sql:346) — lower, dedupe, drop the empty
string. The gallery sync trigger calls it. The lorebook trigger is not modified in this feature;
its inline SQL stays exactly as it is, and the lorebook SQL diff for this work is zero lines.
A test asserts fn_normalize_keywords returns exactly the set the lorebook trigger writes for the
same input. That test has teeth precisely because the function was copied rather than improved: it
fails the moment either side drifts.
The keyword validation gap this uncovered
Extracting that function surfaced something worth writing down, because it is a real gap and it is not this feature's to fix.
The lorebook normalization does not trim. " elara " is stored with its spaces, and " "
survives the blank check because it is not equal to ''. That is not a keyword anybody meant to
create — it is whitespace that will match differently from the word the creator typed.
Tracing where it could come from:
| Layer | Trims? |
|---|---|
KeywordInput.addKeyword (the editor) |
yes — .map(p => p.trim()).filter(p => p.length > 0) |
| The lorebook entry endpoints | no — JsonSerializer.Serialize(request.Keywords), no validation at all |
fn_sync_lorebook_entry_keywords |
no |
So the UI is the only thing keeping that data clean, and every non-UI writer — a direct API client, an AI-generated entry from the lorebook assistant, a package import — can store a keyword the editor would have rejected. On the local development database the data is clean (0 untrimmed and 0 whitespace-only rows out of 2170), which is consistent with the editor being the only real-world path, but a development database is not proof about production; the same two counts should be run there before anyone acts on this.
Trim belongs at API validation, for both features. That is where the rule can be stated once,
returned as an error the caller can see, and applied uniformly to UI, AI and import writers. This
plan puts it there for the gallery — the endpoint rejects untrimmed and blank keywords, and
ck_keyword_bindings_value backstops it at the table. Closing the same gap on the lorebook endpoints
is a small, separate, validation-only change: no trigger rewrite, no matcher change, and (if the
production counts come back zero) no backfill either.
Two things follow for this feature:
- The shared function stays a verbatim copy. With inputs guaranteed trimmed before they reach it, whether it trims internally is unobservable — so the zero-risk version is also the sufficient one.
- Future convergence loses its blocker. Once the lorebook endpoints validate, the lorebook trigger swapping to the shared call is a genuine no-op, and there is no half-trimmed-table hazard to mitigate.
An earlier draft of this document had fn_normalize_keywords trimming and called the lorebook
trigger's adoption of it "behaviour-preserving by construction." That was wrong: it would have
silently re-normalized keywords on every re-saved entry while leaving untouched entries alone. The
fix is not to enshrine the untrimmed behaviour — it is to reject the bad input a layer earlier,
where the editor already does.
The match predicate is deliberately not extracted into a shared SQL function either, for a different reason: it is a set of counting filters inside a grouped CTE, and wrapping it in a per-row function call is exactly the shape that turns an index scan into a nested loop. It is re-expressed rather than shared, and the acceptance criteria pin both to identical observable semantics on the same inputs.
Matching
Gallery images need a much simpler matcher than lorebook entries — no token budget, no prompt ordering, no priority-weighted truncation. Just: given the conversation text and a conversation's asset sources, which linked images fire?
fn_match_entity_images(p_sources jsonb, p_text TEXT, p_max_rating SMALLINT, p_limit INTEGER)
p_sources is the resolved asset-source set — in v1 always a single character, but shaped as a
set so package, multi-character and active-lorebook sources are added without touching the
signature.
The scan window
The rail is pre-LLM. It reacts to the user's message and the recent conversation, not to the assistant reply the image will appear beneath. This is worth stating plainly because the UI implies otherwise: the picture renders under the reply, so it reads as "the model chose this", and it did not.
The window is the same one lorebook search already uses — BuildSearchQueryAsync(context, MessageScanDepth), default 5 recent messages. That builder is extracted as a shared
RecentTextWindow service so the two matchers cannot drift into different definitions of "recent",
which would produce the genuinely baffling bug of a lorebook entry firing while the gallery image
with the same keyword does not. Scan text is capped before it reaches the query.
Rules
- Candidates = images in galleries linked to a source with
use_in_chat∪ images linked directly with an explicit grant carryinguse_in_chat. Deleted, unavailable and non-moderation_status = 0images are excluded at the query. - Effective keyword config per (image, source) pair resolves by
keyword_mode:disabled→ the image is dropped;override→ the link's bindings, regex and exact-match flag;inherit→ the image's own. - Fire when at least one trigger keyword matches and all include keywords match, or
when
trigger_regexmatches.use_exact_keyword_matchswitches word-boundary vs substring for every keyword field on that config. - Exclude vetoes globally, including regex matches. This mirrors
fn_search_lorebook(15_search_lorebook.sql:429, "Global exclude veto: remove entries with any matched exclude keyword") — an exclude keyword is the creator saying "not in this context", and a regex hit is not an exemption from that. - Never fire an image with no trigger keywords and no regex. Keywords are optional; an image without them is browsable, not silent-firing.
- Dedupe by image id. An image reachable both through a linked gallery and through a direct link is one candidate, not two. Direct-link configuration wins on the merge — it is the more specific statement of intent.
- Total order, fully specified so the top match is stable across runs and across replicas:
source priority, then matched-term count desc (a regex hit counts as exactly one term), then the
gallery link's
sort_order, then the image'ssort_order, then image id. No tie is left to the planner. - Bounded.
p_limitcaps returned rows (default 8); the top one renders, the rest are carried. - A matcher failure never fails the turn. The call is wrapped the same way the rest of the pre-LLM providers are — an exception logs and yields no images, and the reply still streams.
Chat wiring
The existing rail carries this with two generalizations.
Generic model. MatchedEntryImage is renamed and widened to carry an explicit source kind,
because a gallery image is not an entry and EntryId cannot be meaningfully populated for one:
MatchedImage(
Source: LorebookEntry | GalleryGrant | ImageGrant,
SourceAssociationId, -- entry id, gallery-grant id, or image-grant id
ImageUuid, GalleryUuid?, -- gallery is null for an unsorted directly-granted image
Caption, AltText, -- the image's own, never a substituted label
ContentRating, ModerationStatus, MatchedTerms,
KeywordSource: Image | Grant, Rank)
Three kinds, not two: a Gallery discriminator cannot represent a direct grant on an unsorted
image, which has no gallery at all. GalleryUuid is nullable for the same reason. And
SourceAssociationId is what makes a report able to name what put the image on screen.
Captions reach the reader — which today they do not
gallery_images.caption already exists (VARCHAR(300), optional) and the image editor already
describes it as "Short label shown under the image in the UI." That is exactly the right field and
exactly the right intent. It just never arrives:
- In chat, it is substituted with the wrong string.
TriggeredEntryImagesPanelbuilds its lightbox payload withcaption: top.entryNameandfileName: top.entryName(TriggeredEntryImagesPanel.tsx:72) — the lorebook entry's name. The image's own caption is not onMatchedEntryImageat all, so there is nothing else it could use. A reader opening the lightbox reads the entry title where the caption belongs. - Under the thumbnail, nothing renders it. The panel shows the entry name in its header and no caption anywhere.
- In browse, it is carried and dropped.
LinkedImageResponsehasCaption; nothing consumes it, because nothing consumeslinkedImagesat all yet.
So this feature makes the caption a first-class reader-facing field:
MatchedImagecarriesCaptionandAltText, and the panel renders the caption with the image — under the thumbnail and in the lightbox caption bar — on every source, entry pictures included. The entry name stays where it belongs, in the header.- The browse projection renders it under each tile and in the lightbox.
- It stays optional: no caption, no caption line, no empty row reserving space.
AltTextfalls back toCaptionwhen unset, so the accessible path works without a second field to fill. See Approved Media (docs-internal/architecture/trust-and-safety/APPROVED_MEDIA.md).
Fixing the entry-name substitution is a lorebook-picture behaviour change, and a deliberate one:
it is named as an exception to the "entry pictures behave exactly as before" invariant, alongside
maturity filtering, persistence and the report target.
SourceAssociationId is what makes a report able to name what put the image on screen.
Its own stage. Gallery matching runs in a dedicated pre-LLM stage, not inside
LorebookContentProvider. That provider exists to build lorebook prompt content; gallery images are
not prompt content and do not come from a lorebook. Hanging them off it would make the feature
silently dependent on the lorebook provider being active — the "switched modes and my journal
silently stopped" trap, one layer down, and it would break in exactly the Classic/Hybrid mode
configurations that have no lorebook provider at all.
History persistence — the rail is currently transient
Earlier drafts claimed the toggle could be flipped back on "without a hole in the history". That claim was false, and checking why is what turned this into required work rather than a footnote.
triggeredEntryImages is attached to the in-memory Message object at SSE-Done time from
pendingImagesRef (NewChatPage.tsx:910). Nothing persists it. web_messages has
lorebook_activations_json, but that records which entries were injected and by which match legs
— not which images rendered. So today, every lorebook picture disappears from the history on
reload. That is a live bug, not a gap this feature introduces, and this feature cannot be built
correctly on top of it.
So the rail gets persistence, across three distinct models that an earlier draft ran together:
| Model | Lives | Carries |
|---|---|---|
| Match receipt (internal) | pipeline context | matched terms, provenance, ranking, which config won |
| Persisted reference (compact, versioned) | web_messages.image_activations_json |
image id, source, rank, schema version — nothing derivable |
| Reader DTO (hydrated) | the SSE frame and the history response | display + report fields only, never the creator's keyword rules |
The persisted reference carries delivered as a distinct fact from matched. The toggle
design deliberately keeps recording matches while the panel is off, so "an activation row exists"
proves the matcher fired — it does not prove the reader was shown anything. Only the frames actually
emitted, and the images actually hydrated into a response, are deliveries. That distinction is what
the report authorization below rests on, and conflating the two would let a reader file against an
image they never saw.
Persisted references also carry the source association — the gallery grant or image grant id, and for lorebook-sourced images the entry id — not only the image id. Without it a report cannot name what actually put the image on screen, and a moderator gets an image with no context for why it was there.
- References only, never URLs. Not because URLs expire — they do not, see below — but because a stored URL is a stored bypass of every later visibility, capability, rating and moderation change. The reference is re-resolved; the URL is re-minted.
- Hydration re-resolves capability, moderation and the viewer's maturity ceiling at read time. An image since revoked, removed from the gallery, re-rated or pulled into review does not reappear because a row remembers it fired.
- Hydration is batched per message page — one read for the whole page. Resolving up to 8 images for each of 200 messages independently is a 1600-query N+1, and it is the obvious way to write this if the contract does not say otherwise.
- Malformed or unknown-version activation JSON renders nothing and logs. It never throws the history read.
- Branch, fork, regenerate, version-switch and export preserve activations — both the new image
records and the existing
lorebook_activations_json. Any path that copies a message copies both. - Suppression is per audience, and applies to the live SSE frame and history hydration identically. Guest, anonymous and OG audiences get no images on either path. (Owner, 2026-10-30: a story's share link — the shared transcript, which has no live path — answers per reader instead: a signed-in adult gets the published reader's images with their ratings, blurred by their own Content Filter; anyone protected (signed out, a guest, under 18) only the all-ages, clear ones stored by us — an NSFW image is never in their answer. "Share-link picture should be depending on viewer … Blur per logged in user settings, not loaded for public if NSFW." See CHAT_PUBLISH_AND_SHARE.md.) Suppressing one but not the other produces the worst possible result: an image appears live and vanishes on reload, or the reverse — a difference a reader reads as a bug and a moderator cannot reproduce. One audience decision, two enforcement points, same answer.
This also makes the toggle's design honest: the match still runs and still records what fired, the toggle decides whether the panel renders, and flipping it back on genuinely does show the history.
Chat. builds this persistence as slice 4 M4 of its publish-and-share spec (docs-internal/architecture/consoles/CHAT_PUBLISH_AND_SHARE.md → Triggered pictures across reloads): the writer's own story and the published-story page hydrate it; the share link gets none.
Image URLs: what the substrate changes, and what stays true
ImageUrlSigner today mints stable, HMAC-signed, user-independent URLs with no expiry, signing
the logical image uuid — "No expiry, no userId — stability is the point" (ImageUrlSigner.cs:20).
An earlier draft of this document accepted that model as-is. It cannot survive contact with immutable
asset versions: replace an image and the same URL serves different bytes, so what a moderator
approved and what the URL serves diverge.
Approved Media owns the fix (docs-internal/architecture/trust-and-safety/APPROVED_MEDIA.md) and sequences it
first: the signed identity becomes the asset-version uuid, so an old URL always resolves to its
old immutable bytes, migrated through the central GalleryImageRef seam. This feature consumes that;
it does not implement or work around it.
What stays true regardless, and must stay in the creator-facing copy:
- Revoking a grant prevents rediscovery. It does not recall bytes a reader already downloaded. Origin state is immediate; the CDN revocation gate closes within its propagation SLO; a copy in someone's browser cache is gone from nobody's reach.
- So the private-gallery grant warning keeps saying so in the creator's language: "Readers who have already seen an image keep a working link to it even after you revoke access." A creator granting a private folder is entitled to know what the grant cannot take back.
Report target
TriggeredEntryImagesPanel used to report through the parent lorebook. A gallery image has no
parent lorebook to report through, so the dedicated GalleryImage target landed here, used by both
sources. Reporting the wrong entity is worse than a missing button.
A UUID is not authorization to report — the intended end state. A chat-delivered image may be from a private gallery the
reporter can see only because it was granted into their conversation. So the report carries the
issuance receipt the substrate wrote when the image was emitted — not a messageId + imageUuid
pair validated against message JSON. Two reasons the earlier shape was wrong: activation membership
records that the matcher fired, not that the reader was shown anything (the toggle deliberately
keeps recording while the panel is off), and a message id does not exist yet when the SSE frame goes
out. Receipt authority lives in Approved Media
(docs-internal/architecture/trust-and-safety/APPROVED_MEDIA.md); this feature consumes it and stores nothing of its
own. Accepting a bare UUID would turn the report endpoint into an oracle for private image existence.
Evidence is retained, not referenced. A report snapshots the image's owner, rating, caption and moderation status — and takes an immutable retained copy of the asset, or a reference-counted hold on it. A database row pointing at a bucket key does not survive a hard delete, and a creator who deletes a reported image must not be able to empty the moderator's queue item. Retention is released when the report closes, not when the creator acts.
Toggle
A new Features.EnableCharacterImages (Side A), dependency-locked on nothing — a user may want
lorebook pictures but not character art, or the reverse, so it does not cascade off
Features.EnableLorebookImages. Default on, matching lorebook Side A. The HowDrawer gains a row.
| Piece | Value |
|---|---|
| Settings key | Features.EnableCharacterImages |
| Conversation DTO | featureToggles.characterImages |
| HowDrawer row | "Character images", via characterImagesState() / characterImagesBody() in featureRowContent.tsx |
| Default | On |
Not mode-gated. modeSupports.lorebookImages exists because entry pictures ride the lorebook
subprompt. Gallery images do not come from the mode at all, so the row is always available — the
same call already made for trackers and journal.
Ordering when both fire. A turn can trigger both a lorebook entry picture and a character gallery image. v1 renders one: lorebook entry pictures win, because they are tied to an explicit piece of world-building the creator wrote, whereas a gallery image is ambient art. This priority applies after dedupe, so an image that is both a lorebook entry picture and a linked gallery image is one item that renders once, as the entry picture. The full list is carried and persisted so a later carousel shows both.
Turning the toggle off suppresses the panel entirely. It does not affect the browse section on the character detail page — that is a different surface with its own reason to exist.
Public browse
A gallery linked to a character with show_on_entity renders as a browsable section on the
character's detail page.
Most of the read path already exists and is currently dead: BrowseEndpoints already returns
linkedImages on character detail and BrowseLinkedImage is already declared in
types/entities.ts — nothing renders it. This feature gives that payload its first consumer,
adds the gallery-level grouping around it, and bounds it.
One projection, bounded
"Each gallery browsable inline" cannot mean "return every image". Galleries are deliberately unbounded — a creator with a 400-image reference folder is using the product correctly — and a character detail page that pulls all of them is a payload and a database problem at the same time.
So the two character-detail endpoints (GetCharacterDetails and GetPublicCharacter, which today
duplicate the same linked-image query and mapping verbatim, BrowseEndpoints.cs:661 and :1500)
both consume one viewer-filtered entityMedia projection built by one set-based read:
- Gallery summaries: uuid, name, image count, cover.
- A bounded preview per gallery (12 images), plus a continuation token.
- Deduplicated direct images, with nullable gallery metadata so unsorted images survive.
- Everything filtered by capability, moderation and the viewer's maturity ceiling before it leaves the database.
Inline pagination uses the continuation token. No N+1: one read regardless of how many galleries are linked.
- A gallery whose
show_on_entityis off renders nothing to readers, owner included — the creator's preview of ungranted media is the management UI, which shows it badged with its capabilities. No reader-surface owner exception. - Blur, content-rating badges and moderation containment come from
ContentImageexactly as they do everywhere else — on top of the query-level filtering, never instead of it.
The anonymous blocker
The browse surface is authenticated-only in this feature. For an anonymous viewer — including crawlers — a granted gallery renders nothing at all.
This is not caution for its own sake. Characters are in the anonymous type allowlist
(characters, packages, projects), per-instance gated by allow_anonymous_view, and /og/*
inherits that predicate — the crawler tier is documented "SFW, hard". Meanwhile the public gallery
read path has no maturity gate, and its maxRating is a caller-supplied filter with no
server-enforced ceiling, while image content ratings genuinely reach NSFW. That combination is
currently accepted risk only because no crawlable surface embeds a public gallery uuid.
Putting a browsable gallery on an allowlisted character's detail page is exactly that surface.
When it unblocks, it rides the character's approved projection — not a gallery allowlist entry. Earlier drafts wavered between the two; this settles it. Adding Gallery to the standalone anonymous type allowlist would make galleries independently crawlable, which is a much larger product decision that nobody asked for and that reopens the maturity-gate risk directly. Deriving anonymous media from the parent character's approved, versioned media projection reuses the review that already gates that character, and keeps galleries out of the crawler surface entirely.
So the remaining gates are two, not three: a platform-approved anonymous-exposure flag distinct from
is_public, and a server-enforced maturity ceiling. Until they land, the section is suppressed for
anon and guest tiers — and that suppression is an acceptance criterion, not a code comment.
Collaboration, revocation and re-review
A gallery and the character it is granted to can have different owners, and checking permissions once at grant time is not enough. The grant has to stay governed.
Three separate dimensions
The recurring bug in earlier drafts was collapsing these into one check. They are independent, and a grant needs all three:
| Dimension | Question | Answered by |
|---|---|---|
| Authorization | may this account write this grant? | can_edit on the entity and ownership of the gallery |
| Creator consent | does the entity's side agree to carry this media? | acceptance by a current entity editor |
| Public moderation | may readers outside the creator see it? | the approved-media projection |
Public moderation does not stand in for creator consent. A moderator approving media says "this is not harmful"; it does not say "the character's owner wanted this on their page".
Direct attachment requires can_edit, not can_contribute. An earlier draft said a
can_contribute collaborator could attach a gallery directly. They cannot and should not — the
permission table carries can_contribute, can_edit and can_manage as distinct columns
(13_tables_permissions.sql:39), and contributors already have a lane for proposing changes they
cannot make directly: entity_proposals. A media grant from a contributor is a proposal, reviewed
by an entity editor, exactly like every other contributor change.
Two independent revocation rights, and neither can be taken away:
- The gallery owner can always withdraw their asset grant, without needing any permission on the entity. It is their content.
- Anyone with
can_editon the entity can always revoke from the entity side. It is their character's presentation.
Those need two different endpoints. An entity-scoped media API cannot serve the gallery owner,
because by construction they may have no rights on that entity at all — so owner-side revocation
lives on the gallery: DELETE /api/galleries/{uuid}/grants/{grantId} and the image equivalent,
authorized by gallery ownership alone. An earlier draft asserted this right and then specified only
the entity-scoped route, which would have made its own use case unbuildable.
Losing access revokes the ability to change a grant, not the grant itself. A collaborator who
loses entity access can no longer add, revoke or reconfigure — but what they left stays, because
silently stripping a character's art when someone leaves a project is a worse surprise than a stale
grant. The entity's editors see who granted what (granted_by_user_id, surfaced as attribution) and
revoke deliberately.
Cross-owner grants keep their approved snapshot when the attacher loses access. What readers see does not change, because it was already approved and consented to. What stops is growth: new images entering that gallery, or keyword expansions, require acceptance by a current entity editor before they can even enter public moderation. Otherwise a removed collaborator keeps a live write channel into a character they no longer have any rights on — the gallery becomes a back door around the permission they lost.
Removals and revocations stay immediate in every one of these cases. No consent step, no review step. Taking something away is never gated.
Membership changes flow through — subject to the state machine below. Moving an image into a granted gallery makes it a candidate; moving it out stops it. A creator adding art to a granted folder expects it to start working — a grant that froze its contents would be a snapshot, not a library, and the whole feature is about the set.
The exposure state machine
"Membership is live" and "changes re-enter review" are the two halves of a contradiction an earlier draft left standing: it never said what a reader sees while a revision is pending, or after one is rejected. The resolution is that the two directions are not symmetric.
Reductions in exposure apply immediately, always. Revoking a grant, turning off a capability, removing an image from a granted gallery, deleting an image, raising a content rating, or an image entering moderation review — all take effect on the next read, with no review step. Taking something away is never gated on a queue.
Additions and replacements are creator-visible but reader-hidden until approved. Granting a new gallery or image to an already-public character, adding an image to a granted gallery, or replacing an image's asset produces a pending revision. The creator sees it immediately, badged. Readers do not.
Readers keep seeing the last approved projection while a revision is pending. Not an empty section, not the pending content — the previous approved state. This is why the projection is versioned rather than recomputed: there has to be a "last approved" to serve.
Rejection preserves the last approved projection and returns an actionable status to the entity's editors — which revision, which image, why. It does not silently drop the character's media, and it does not leave the creator guessing which of twelve additions was the problem.
A gallery mutation fans out — but the picture is reviewed once. One image added to a gallery
granted to six public characters produces one asset review plus six placement confirmations.
Asset approval attaches to the immutable asset version and is reusable across every placement;
placement approval attaches to an exact exposure generation — (association, asset version, surface) — because a grant carries many images across two independently reversible surfaces and
cannot be the unit of decision. An earlier draft of this document said placement attaches to the
grant and mostly auto-approves; both halves were wrong. The split lives in Approved Media
(docs-internal/architecture/trust-and-safety/APPROVED_MEDIA.md).
Three consequences worth stating here, because they change what a creator experiences:
- Uploading reviews nothing, and neither does sharing privately with a collaborator. A private
gallery is not a review surface. What triggers asset review is the first exposure to someone who
is not the owner or an authorized collaborator — not "the first grant". Grants are not the only
rail: public galleries,
g://andgi://already expose images anonymously with no grant at all. - Placement onto a public character is confirmed by a human, cheaply and batched — it changes that character's public projection, and a public revision needs a matching human decision. Placement onto a private entity needs no confirmation.
- Publication and image review are coupled exactly on required media. The avatar blocks: pending or rejected, the character does not publish. Optional pending media is omitted from the submitted ready-media snapshot and enters later through its own placement revision. An earlier draft called them fully independent.
What does and does not need review:
| Change | Needs review |
|---|---|
| Granting a gallery or image to a public entity | yes |
| Adding or replacing an image inside a granted gallery | yes |
| Raising a content rating, revoking, removing, disabling a capability | no — reduction, immediate |
| Lowering a content rating | yes — it widens the audience |
Keyword, keyword_mode and ordering changes |
no — they change when an approved image shows, not what is shown |
| Caption changes | yes — caption is reader-visible text |
External URLs are the hole in all of this. An image backed by external_url can change its
bytes on the remote host with no database mutation at all, so nothing marks the projection dirty and
the approved review is silently stale.
V1 makes import a precondition of granting, not a side effect of it: an externally-hosted image
must already be a canonical platform asset before a grant referencing it can be written. Granting an
unimported URL fails with a clear error. The import itself — SSRF controls, redirect caps, streamed
size limits, MIME sniffing, quota charging, partial cleanup — belongs to
Approved Media (docs-internal/architecture/trust-and-safety/APPROVED_MEDIA.md), because it is a retryable
network fetch and cannot sit inside a database-atomic save.
The approved-media substrate — a separate architecture prerequisite
The rules above are policy. Policy alone enforces nothing: if the matcher, the history hydration and the browse read all query live grants, then a pending addition is visible the instant it is written, and every "reader-hidden until approved" sentence above is decoration.
So the reads do not go to the grant tables. They go to an approved-media projection — and that
projection is not part of this feature. It is
Approved Media (docs-internal/architecture/trust-and-safety/APPROVED_MEDIA.md), its own architecture
document, and this feature is its first consumer.
That split is deliberate. What started as "mark the projection dirty on change" grew, under review, into generations, four independent revision domains, an audience matrix, a cross-owner consent workflow, an external-media import pipeline and issuance receipts. Package media, rich-content blocks and every future entity that shows creator-supplied images to a stranger need the same thing. Building it inside the gallery feature would make the platform's media-safety story gallery-shaped, and the second consumer would have to fork it or refactor it under pressure.
Three things from that document are load-bearing here, and are summarised rather than restated:
Reductions do not simply un-apply. Remove-then-re-add, disable-then-re-enable, raise-then-lower-rating and revoke-then-recreate all had to cost a fresh review — otherwise a "tombstone" that stops being true resurrects an old approval. Every association carries a generation; a reduction permanently suppresses that generation and any reversal mints a new one.
Private characters read a consented projection, not the public approved one. Otherwise a creator could not see their own images in their own draft chat, and collaborators on a private character would see nothing. Live safety filtering — moderation containment and the viewer's maturity ceiling — applies to every audience regardless.
Cross-owner consent is an object with a workflow, because "requires acceptance by a current entity editor" had no actor who could perform it: the attacher has lost entity rights, the editor has no gallery rights.
What this feature owes it: gallery grants are the first association type to register with the substrate, and slice 6 below is the integration, not the construction. If the substrate is not built
first, slices 7 and 8 have nothing safe to read.
API and bounds
The management API
Media is an optional aggregate inside the entity's existing update, not a resource with its own
Save. An earlier draft simultaneously promised a full-set PUT, surgical dirty-field updates,
three-state omission and lost-response idempotency — those are three different contracts and they
contradict each other on the same payload. One model instead:
- Omitted
mediameans untouched. That is the three-state rule, applied at the aggregate boundary where it is unambiguous, rather than per-field inside a set whose identity is the set. - Present
mediais the complete desired state — every grant, capability, keyword config and the full order. Not a patch. A set has no meaningful per-element "omitted". expectedMediaRevisionaccompanies it; a mismatch returns 412 with the current envelope.idempotencyKeyaccompanies it too, and a repeat returns the original result even if theidempotencyKeyaccompanies it too, scoped to the whole request, storing a hash of the body. An identical retry returns the original response even if the revision has since advanced; the same key with different content is rejected, not silently applied. Concurrency control and retry-safety are different problems: 412 handles "someone else changed this", the key handles "my response was lost", and the hash stops the key being reused as a way around 412.- Replacement is transactional within the aggregate — media lands entirely or not at all, along with the rest of the entity save.
| Method | Route | Purpose |
|---|---|---|
GET/PUT |
the entity's existing creator detail route | carries media as an optional aggregate |
GET |
/api/browse/characters/{uuid}/media?cursor= |
continuation pages of gallery sections |
GET |
/api/browse/characters/{uuid}/media/{sectionKey}/items?cursor= |
continuation pages inside one section |
DELETE |
/api/galleries/{uuid}/grants/{grantId} |
owner-side revocation, authorized by gallery ownership |
DELETE |
/api/galleries/images/{uuid}/grants/{grantId} |
owner-side revocation of a direct image grant |
Initial media rides the existing detail DTOs. The character detail response already carries
linkedImages; the viewer projection replaces that field. A separate first GET /media would
contradict the platform's one-call-per-page rule — those media routes are continuation only.
Both levels page. An earlier draft paginated items inside a section but not the sections themselves, which bounds nothing when a character grants thirty galleries.
Cursors bind to the effective projection epoch, not to the approved revision and not merely to the entity and section. The approved revision is the wrong anchor: a reorder changes what page 2 contains without advancing it, so an approved-revision cursor would happily stitch two orderings together. The epoch advances on approvals, removals, containment, rating changes and reorder — every change that alters a rendered sequence. When it moves mid-pagination the cursor is stale and the client restarts. Authorization is rechecked on every page; a cursor is a position, never a capability.
One total ordering across everything, so the same character always renders the same sequence:
gallery grants by sort_order then id, direct grants as their own section after them by their own
sort_order then id, and an image reachable by both paths appearing once, in its gallery position.
Direct grants order independently because they have no gallery to sit inside — an earlier draft
implicitly assumed every image hung off a gallery grant's order, which has no meaning for them.
Atomic reorder with compaction: order is submitted as the full sequence, applied in one
statement, sort_order compacted server-side. No client-computed gap arithmetic.
Legacy assignments are transitioned, not stranded. The old per-click linkImageToEntity /
unlinkImageFromEntity routes are retired — two live mechanisms for attaching an image to an entity
is exactly how the capability model gets bypassed, since the old one writes rows with no
capabilities and no review. But some existing rows in gallery_image_entity_links were deliberate
creator assignments, and they are what the planned entity filter chips and picker filtering read
(neither is built yet — today they drive the workbench Images section, "Used by", and the gallery
page's Linked / Not linked filter; see the Gallery status table).
Retiring the write path without a transition would strand them.
So:
- Ambiguous legacy rows surface in the management UI as "legacy assignment" — visible, non-exposing, and explicitly not a grant.
- A creator can convert one into a grant with chosen capabilities, in one action. That is the only path from legacy row to reader-visible, and it is deliberate by construction.
- Entity filter chips and picker filtering keep reading the association table — automatic references included. They are an authoring convenience about "where is this image used", not a disclosure surface, and narrowing them to grants would break the workbench for no safety gain.
EntityImagesSectionsplits: it is mounted by both character and lorebook forms today, while v1 grants are character-only. The lorebook mount keeps the legacy assignment behaviour; the character mount gains grants. One component serving two different capability models is how the narrowentity_typeCHECK gets discovered the hard way, at runtime.
The matcher stage
Registered as its own stage, ordered after context assembly and before hybrid beat processing, in both pipeline factories — so a mode running the hybrid path gets the same behaviour as one that does not. Exceptions are contained stage-locally: a failure logs, contributes no images, and the turn streams normally. "Twelve images per gallery preview" bounds a gallery, not a page. A character can grant many galleries and many direct images, so the caps have to be global or they are decorative. Numbers are pinned here because "verified at the caps" is not a testable criterion without them:
| Bound | Default | Hard max | Kind | Applies to |
|---|---|---|---|---|
| Gallery grants per entity | 24 | 48 | cardinality — rejected at write | management aggregate |
| Direct image grants per entity | 48 | 96 | cardinality — rejected at write | management aggregate |
| Gallery sections per page | 12 | 24 | page size | browse payload |
| Direct-grant images per page | 24 | 48 | page size | browse payload |
| Preview images per section | 12 | 24 | page size | browse payload |
| Total image URLs per response | 64 | 64 | hard ceiling | browse payload — the real disclosure unit |
| Asset sources per conversation | 4 | 8 | matcher input | matcher |
| Candidate images per match | 500 | 1000 | matcher input | matcher |
| Scan text characters | 4000 | 8000 | matcher input | matcher |
p_limit |
8 | 16 | matcher output | enforced in the endpoint and the function |
| Matched terms persisted per image | 8 | 8 | persistence | image_activations_json size |
Cardinality caps are enforced at write. The management aggregate is a full desired-state payload, so without a write-time limit on how many grants an entity may hold, "complete desired state" is an unbounded request body. Page-size caps do not bound it — they only bound what is read back.
The 64-URL ceiling is allocated deterministically, because 12 sections × 12 previews plus direct images overshoots it badly. Allocation, in order: each section gets a guaranteed 4 previews in section order until either sections or budget run out; leftover budget then tops sections up to their preview cap in the same order; direct grants take whatever remains, minimum 8 reserved for them when any exist. Every section therefore appears with something rather than the first five consuming the whole budget, and the sequence is a pure function of the ordering — no planner dependence, no per-request variance.
Candidates are capped before matching, and that is a real trade. Truncating after matching leaves
the scan unbounded, which is the shape that turns a large gallery into a per-turn latency cliff.
Truncating before matching means an image beyond the cap cannot fire — so the cap is applied in a
deterministic order (source order, then gallery sort_order, then image sort_order, then id),
never an arbitrary one, and crossing it is surfaced to the creator in the management UI as
"beyond the matching limit" rather than left as a silent cliff.
Direct grants order independently in the matcher too. The total order includes a gallery grant's
sort_order, which a direct grant does not have; direct grants sort as their own group after gallery
grants, by their own sort_order then id. An earlier draft named a single ordering key that half the
candidates do not possess.
Maturity maps explicitly, never by cast. MaturityCeiling is Sfw = 0 / Mature = 1
(RequestAccess.cs:29), while gallery_images.content_rating is 0=SFW, 1=Suggestive, 2=NSFW.
Casting the enum would silently cap age-assured users at Suggestive and hide every NSFW image from
exactly the audience entitled to see it. The mapping is written out: Sfw → max rating 0,
Mature → max rating 2.
The hard maxima are enforced server-side regardless of what a caller asks for; the defaults are what the UI requests. Anything truncated is reported as a count, never silently dropped: a creator who granted thirty galleries should see that the page shows twelve, not quietly wonder where the rest went.
Implementation Plan (Sliced)
The first two slices are refactor-first. Neither adds a feature; both exist because this work is the third consumer of something copy-pasted, or the second consumer of something half-built, and building on top of that anyway is how the "lift this to shared later" docstring becomes permanent.
| Slice | Scope | Status |
|---|---|---|
| 1 — Shared UI substrate | Extract KeywordRuleEditor (trigger / include / exclude / exact-match / regex / inheritance-mode) across the three existing consumers — LorebookEntriesPanel.tsx:403, EntryEditPanel.tsx:204, and LorebookEntryFields.tsx:48, which is not a KeywordInput at all but raw comma-separated Inputs. Reconcile the differences deliberately (the workbench editor lacks the assistant's exact-match toggle) rather than extracting one and leaving two. Upgrade KeywordInput: case-insensitive dedupe, length + count limits, blank rejection, validation messaging. Extract the gallery grid + lightbox used by browse. Built (2026-11-07, uncommitted lane gallery-links-s1): shared/src/components/creator/KeywordRuleEditor.tsx (+ the React-free model keywordRule.ts) — the five fields with the exact-match toggle reconciled in, limits / case-insensitivity / pattern error + warning as props (off by default: the lorebook endpoints cap nothing), and the link mode (inherit / override / disabled; inherit shows the inherited rule read-only with why, disabled keeps the rule visible read-only with why). Showcase rows in creatorEditorShowcase.tsx. KeywordInput already had case-insensitive dedupe, count + length caps and blank rejection; it now also says what it kept off the list ("“x” is already on the list."). Moved consumer: the Forge entry page's Triggers section (forgeConsole/.../lorebook/EntryEditor.tsx), words and save body unchanged. Since this row was written the three named consumers all became clientConsole (frozen 2026-10-31, not edited); the Forge page is their new-console port. Moved too (2026-11-07, director's call, rule of two): adminConsole's security-lorebook entry form (SecurityTab.tsx) — its five comma-separated Inputs are now the editor (noun "directive", commitOnBlur so a keyword typed and not added lands when the operator goes straight for Update); the form model (securityEntryForm.ts) holds string arrays and serializes them to the endpoint's keywordsJson strings only in the request. Labels are the editor's ("Trigger pattern", "Whole words only"), and a keyword already on a list is said rather than stored twice. Open: the gallery grid. The lightbox is already shared (ImageLightbox, ReportableImageLightbox, ReaderPictureViewer). The reader grid is clientConsole's EntityGallerySection; the chat door already draws a character's and a package's linkedImages as its details header carousel (chatConsole memberCharacterSlides). Whether Slice 9's browse section extends that carousel or needs a shared grid is a Slice 9 design question, so this half is proposed to fold into Slice 9 (owner's nod pending); until then the box below stays open. |
🟡 editor done, grid open |
| 2 — Repair the existing read path | fn_get_entity_linked_images gets its LEFT JOIN so unsorted images stop vanishing1804fd269, 2026-10-27) — the function keeps its contract as the legacy automatic-reference evidence reader. Still to do in this slice: centralize link/unlink writes in stored functions; normalize missing-vs-forbidden responses so neither leaks existence; drop EntityImagesSection's silent catch {} on load and split it so the lorebook mount keeps legacy assignment behaviour. |
📋 planned |
| 3 — Transactional character save | Refactor-first, and a hard prerequisite for slice 5. One unit of work across character fields, tags and avatar — today three separate awaits (CreatorCharacterEndpoints.cs:294,310,322) that can already leave a half-saved character. Request-scoped idempotency with a body hash: identical retry replays, same key with different content is rejected. EntityImagesSection stages into this form's Save/Cancel pair, not its own. |
📋 planned |
| 4 — Keyword substrate | keyword_bindings with full CHECK set (including lower(keyword) = keyword) and soft+hard-delete cleanup triggers on both owners and the target entity, fn_normalize_keywords extracted verbatim and called by the gallery trigger only, the convergence pointer comment next to lorebook_entry_keywords. Idempotent-rerun and partial-migration-repair tests. |
📋 planned |
| 5 — Keywords on images | Keyword + regex + exact-match columns on gallery_images, sync trigger, endpoint validation (trim, blank, length, count), KeywordRuleEditor in the image editor grouped separately from recall_keyword. The gallery page's list view (shipped 2026-08) expands each row into a lightweight quick-edit form (ImageListView.tsx) — mount KeywordRuleEditor there as well as in the detail drawer: bulk keyword cleanup across many images is exactly the workflow that view exists for. |
📋 planned |
| 6 — Approved-media substrate | Its own architecture document (docs-internal/architecture/trust-and-safety/APPROVED_MEDIA.md) with its own schema, APIs, moderator/editor UX and acceptance criteria: generations, four revision domains, the audience matrix, cross-owner consent workflow, external-media import, issuance receipts, the asset-vs-placement approval split, the per-image moderator review component, and one shared projection reader per audience. Gallery grants are its first consumer; it is a prerequisite for 8 and 9, not a step inside them. |
📋 planned |
| 7 — Grants | gallery_entity_grants + gallery_image_entity_grants with keyword arrays as authoring state and transactional keyword_bindings sync, capabilities on both, generations, granted_by_user_id; media as an aggregate in the transactional entity save with expectedMediaRevision + request idempotency; can_edit authorization, entity-editor consent, and both revocation routes plus the owner outgoing-grants list; write-time cardinality caps; legacy assignments surfaced and convertible. Workbench editor reusing GalleryTreeSelect, subfolders as their own rows, private-gallery grant warning including the stable-URL disclosure. Stale-avatar migration test. |
📋 planned |
| 8 — Matcher + rail | fn_match_entity_images reading the audience-appropriate projection, over a resolved asset-source set, with deterministic pre-match candidate capping and the full ordering contract; explicit MaturityCeiling → content_rating mapping; its own stage after context assembly and before hybrid beat processing in both pipeline factories, with stage-local containment; MatchedImage with three source kinds and a source-association id; image_activations_json + issuance receipts, batched re-resolving hydration, branch/fork/export preservation, identical SSE and history suppression; GalleryImage report target; Features.EnableCharacterImages + featureToggles.characterImages + HowDrawer row. |
📋 planned |
| 9 — Bounded browse (authenticated) | Viewer entityMedia from the substrate's projection reader, carried in the existing character-detail DTOs with the media routes as continuation-only; sections and items paginated, cursors bound to entity epoch + global safety epoch + audience + surface + ceiling, read from one snapshot, re-authorized per page; the pinned caps with deterministic URL-budget allocation; responsive / error / empty states; guest and shared-transcript suppression. |
📋 planned |
| 9b — Package media snapshot | Package publication pins a snapshot of the wrapped character's approved media and reviews its own manifest; later character-media changes require package-owner acceptance before reaching the published package. Consumes the substrate; no per-image configuration on the package side. | 📋 planned |
| 10 — Anonymous browse | Blocked on the platform anonymous-exposure flag and the server-enforced maturity ceiling. When it lands it derives from the character's approved projection — not a standalone gallery allowlist entry. | ⛔ blocked |
Slices 1–9b are the feature, and all of them are required. Slice 10 must not ship on this feature's gate.
Slice 6 is the one to watch: it is scoped and gated by its own document, and it is where this feature stops being a gallery feature. If it is skipped or inlined, slices 8 and 9 have nothing safe to read and every "reader-hidden until approved" line above becomes decoration.
Folding lorebook_entry_keywords into keyword_bindings is not a slice here — it is a future
consideration for whenever the lorebook keyword feature is next opened for its own reasons, with the
pointer comment from slice 4 sitting where that work would start.
Open Questions
The three that opened this design are settled: keywords live on both the image and the grant (grant mode decides inherit / override / disabled, per entity); browse operates on the whole gallery; and images remain separately grantable with their own keywords.
What remains open is genuinely external to this plan:
- Anonymous exposure (slice 10) belongs to the platform's anonymous-exposure work — and when it arrives it rides the character's approved projection, per the anonymous blocker, not a standalone gallery allowlist entry.
- Package as an asset source. Packages are the documented primary creative unit
(
CONTRIBUTING.md,package-workbench.md), and a package granting a gallery once rather than per-character is the obviously better creator flow. Not v1 — but the matcher takes a source set specifically so it lands as a new source resolver rather than a rewrite. Character-granted media inside a package conversation is already v1 behaviour and carries its own acceptance criterion; what is deferred is a package granting galleries of its own. - Lorebook as an asset source — the four questions in Why not lorebooks in v1.
Two things earlier drafts left open are now decided, because leaving them open was itself the inconsistency:
- Shared transcripts suppress triggered media in v1. A shared-conversation viewer is authenticated, so this was never part of the anonymous blocker — it is a product decision, and the decision is suppression, because it is the reversible direction and it has an acceptance criterion rather than a shrug.
- There is no owner exception on the reader surface.
show_on_entity = falsehides the section from everyone, owner included. The creator's preview of ungranted media is the management UI, which already shows exactly that, badged, with the capabilities visible. An earlier draft left this open while the acceptance criteria had already chosen — a reader-surface exception that only the owner can see is a second visibility rule to keep correct forever, for something the workbench already does properly.
Acceptance Criteria
The feature is not done until every box below is verified ✅ against the running product. Anonymous browse (slice 10) is excluded from this gate; its criteria live with the blocked slice.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- UC-1 — As a creator, I can link one of my galleries to a character I can edit, from the character's workbench, without insider knowledge.
- UC-2 — As a creator, I can give an image trigger / include / exclude keywords using the same editor I already know from lorebook entries.
- UC-3 — As a creator, I can give different keywords to the same image for one specific character, without changing what that image does elsewhere.
- UC-4 — As a creator, I can silence one image for one character without deleting its keywords.
- UC-5 — As a creator, I can link a single image to a character without linking its whole gallery.
- UC-6 — As a creator, I can link a subfolder independently of its parent, and see both offered as separate rows.
- UC-7 — As a creator, I can grant a private gallery for chat use and be told, in the UI, that readers will see those images.
- UC-8 — As a creator, I can grant chat use without granting browse, and the reverse.
- UC-9 — As a reader, when the conversation mentions a keyword, the matching image appears under the reply.
- UC-10 — As a reader, I can turn character images off from the chat How drawer and stop seeing them, without that touching lorebook pictures.
- UC-11 — As a reader, I can report a specific triggered image as itself, not as its parent lorebook.
- UC-12 — As a signed-in visitor to a character with a granted gallery, I can browse that gallery from the character detail page and page past the first screen.
- UC-13 — As a gallery owner, I can revoke my gallery from a character I have no permissions on.
- UC-14 — As a creator, I can tell at a glance which keyword field triggers automatically and which is the
{{image:…}}reference.
Behavior (exercise the mechanism):
- Linking a gallery makes every image inside a trigger candidate, using that image's own keywords.
-
keyword_mode= override uses the link's keywords instead of the image's; = inherit uses the image's; = disabled never fires, whatever the image says. - An image with no trigger keywords and no regex never fires, but still renders in the browse section.
- Include keywords are AND, exclude keywords veto, and
use_exact_keyword_matchswitches word-boundary vs substring — identical to the lorebook matcher on the same inputs. - An exclude keyword vetoes an image whose
trigger_regexmatched, matchingfn_search_lorebook's global veto. - Regex-only and exact-only override configurations both work.
- An invalid
trigger_regexyields no match rather than erroring the turn. - An image reachable via both a gallery link and a direct link yields one result, configured by the direct link.
- Adding, moving and removing an image in a granted gallery changes candidacy per the exposure state machine, with no re-grant.
- Granting a parent gallery does not make its subfolders' images candidates, and the editor shows those subfolders as visibly ungranted rather than omitting them.
- A private subfolder inside a public parent is fully hidden: its images, its count and its existence are all absent from the parent's public read, and the parent cannot use one of its images as a cover.
- A public subfolder under a private parent stays readable, and making a parent private warns the creator that its public children remain public.
- The visibility toggle copy states that visibility does not inherit in either direction.
- A subfolder can be granted independently of its parent, including a private subfolder granted chat-only.
- Deleting a granted parent folder promotes its children with their grants intact; grants on the deleted folder itself are gone.
- Moving a granted gallery to a different parent changes nothing a reader sees.
-
Features.EnableCharacterImagesoff suppresses the panel while the activation record still shows what matched. - Reload, regenerate and version-switch all preserve the rendered image; toggling off and back on restores the history rather than leaving a hole.
- An image unlinked, re-rated or pulled into moderation review after firing does not reappear on history hydration.
- When a lorebook entry picture and a character gallery image both fire, the entry picture renders — after dedupe, so a shared image renders once.
-
fn_normalize_keywordsreturns exactly the setfn_sync_lorebook_entry_keywordswrites for the same input, including the untrimmed cases — asserted by test, not by inspection. - Matching works in Classic and Hybrid modes, including modes with no lorebook provider at all.
- A matcher failure logs and yields no images; the turn still streams a reply.
Invariants that must stay true (carve-outs a reviewer can break if regressed):
- Anonymous and guest viewers see no granted-gallery section at all, on any character, including through
/og/*. - A shared transcript carries no triggered images — the v1 decision, verified by opening a share link on a conversation whose messages have delivered activations.
- A gallery or image renders on a detail page only when
show_on_entityis granted, independent ofis_public; it is a chat candidate only whenuse_in_chatis granted. Both capabilities apply to gallery grants and direct image grants alike. - The shared projection reader filters the viewer's server-resolved maturity ceiling at the query, for every consumer.
ContentImageblur is never the only thing between a reader and an image above their ceiling. - Reader surfaces admit
moderation_status = 0only — a positive allowlist, enforced at the query, not<> 1and not only atContentImage. - Automatic reference rows never trigger and never browse — a stale avatar reference fires nothing, on any surface.
- Persisted activations store references, never URLs, and hydration re-resolves capability, moderation and maturity rather than replaying what was stored.
- Nesting stays organization-only — a gallery link never traverses into subfolders.
-
recall_keywordis untouched — its column, its constraint, and its still-unbuilt resolution path all behave exactly as before. - Lorebook entry pictures keep their trigger selection, ordering, panel and toggle semantics — unchanged whether this feature is on or off, with
fn_sync_lorebook_entry_keywordsnot modified at all. Three behaviours do change, deliberately, and are named as exceptions rather than hidden under "as before": they gain maturity filtering, they gain history persistence (today they vanish on reload), they gain aGalleryImagereport target instead of reporting through the parent lorebook, and their lightbox stops showing the lorebook entry's name where the image's own caption belongs. - A character with no media grants is unchanged — gallery grants and direct image grants both absent: no new section, no layout shift, no extra query on the detail read.
- Linking is permission-checked on both halves — the gallery must be owned and the entity must be editable; neither is inferred from the other.
- Link and keyword configuration never appear in public DTOs — a reader sees images, not the creator's trigger rules.
- The whole feature is free — linking, keywords, matching, browse and display require no subscription tier, no feature commitment and no Echo debit.
-
lorebook_entry_keywordsis untouched — same table, byte-identicalfn_sync_lorebook_entry_keywords, same matcher, same rows for the same input, and per-turn search latency unchanged. The lorebook diff for this feature is zero lines of SQL.
Slice 1 — shared UI substrate (checked 2026-11-07 against the local stack, Forge on its own Vite, user gls1-staff):
- One shared
KeywordRuleEditoredits trigger / include / exclude keywords, whole words only and the trigger pattern, with the link mode (inherit / override / disabled) as an option that draws nothing when absent. Verified:KeywordRuleEditor.test.tsx10/10; showcase rows render (sections.keysFormInputsSection green). - The Forge lorebook entry page's Triggers section is that editor, with the same labels, descriptions, order and save body as before. Verified live at 1280 and 390: five fields in the page's words; adding keywords, an include, an exclude, a pattern and flipping whole words staged into one Save, which sent only those fields (
PUT …/entries/{id}withkeywords,includeKeywords,excludeKeywords,triggerRegex,useExactKeywordMatch,expectedRevision), and the server read back the same values; no horizontal scroll at 390. ForgeentryEditor/proposeMode/entriesSection77/77 unchanged, plusentryEditorKeywordRule.test.tsx3/3. - adminConsole's security-lorebook entry form edits its rule with that editor, a comma-separated paste still adds one keyword each, and its save stays surgical (only changed lists, as the endpoint's JSON strings;
"[]"empties one). Verified 2026-11-07 live on adminConsole's own Vite (:5191) against a probe AdminAPI (:5141), usersectab-lane(rights 3): on a stored["system prompt"]entry, "jailbreak" added with Enter, "bypass, override" pasted and added, "help, documentation" typed in Exclude and left by blur; one Update sentPUT …/entries/{id}with onlykeywordsJson["system prompt","jailbreak","bypass","override"]andexcludeKeywordsJson["help","documentation"], the read back matched, the reopened form showed the six chips with Update off, the duplicate "system prompt" was said, no horizontal scroll at 390. Typed-and-not-added text survives a direct click on the form's button: a new entry with "foo, bar" pending in Keywords and Create clicked straight away stored["foo","bar"]; an existing entry with only "baz" pending (Update grey) took one real mouse click on Update, which blurred the field, added the chip, and saved{"keywordsJson":"[\"foo\",\"bar\",\"baz\"]"}.SecurityTab.test.tsx22/22 (6 new keyword cases),securityEntryForm.test.ts,SecurityTab.addInPlace.test.tsx: adminConsolecomponents/admin160/160;KeywordRuleEditor.test.tsx+KeywordInput.test.tsx20/20. - A lorebook entry keeps no keyword cap and compares keywords exactly ("Salt" beside "salt"), as before the lift. Verified: Forge test sends
['salt', 'quay', 'Salt']; editor test adds a 71st keyword. - A keyword already on the list is said, not dropped in silence. Verified live ("“maren” is already on the list.") and in
KeywordInput.test.tsx. - With caps given (the gallery's 64 keywords / 100 characters / 500-character pattern), Add is disabled at the cap and says why, and the fields bound their length. Verified in
KeywordRuleEditor.test.tsxand the showcase's image row; the gallery consumer itself arrives in Slice 5. - A
\bin the pattern shows the backspace warning and the page's Save waits, as before. Verified: the warning live at 1280; Save waiting on it by the unchangedentryEditor.test.tsxpattern cases. - The reader gallery grid is shared (the lightbox already is). Open — the chat door already draws linked images as a header carousel; proposed to fold into Slice 9, see the Slice 1 row.
Grants, provenance and migration:
- After migration, a stale avatar row (an image that was once a character's avatar and no longer is) is trigger-ineligible and reader-invisible, and stays that way until someone grants it.
- No legacy
gallery_image_entity_linksrow becomes reader-visible or trigger-eligible by migration alone. - An image can hold an automatic reference and an explicit grant simultaneously; revoking the grant leaves the bookkeeping row, and clearing the avatar leaves the grant.
- Setting an avatar over an existing grant, and granting an image that is already the avatar, both succeed and leave both records correct.
- A grant row written by direct SQL with no capabilities set discloses nothing on either surface.
- A direct image grant can be chat-only, browse-only, both, or neither — each combination behaves as labelled.
Media review:
- Adding an image to a granted gallery on a public character is creator-visible immediately and reader-invisible until approved; readers keep seeing the last approved projection meanwhile.
- Rejecting a revision preserves the last approved projection and returns an actionable status naming the revision and image.
- Revoking, removing, disabling a capability and raising a rating all take effect on the next read with no review step.
- One image added to a gallery granted to six public characters produces one asset review, not six — the rest are placement checks.
- Uploading to a private gallery, and sharing privately with a collaborator, both trigger no review; the first exposure to a stranger triggers one asset review, and a later exposure of the same approved version triggers no second asset review — public placement confirmation still applies.
- An externally-hosted image cannot be granted until it has been imported; granting an unimported URL fails with a clear error rather than referencing remote bytes.
- Keyword and ordering changes do not enter review; caption and rating-lowering changes do.
API and concurrency:
- One Save applies grant additions, revocations, capabilities, keyword modes and order atomically — all or nothing.
- A stale
revisionreturns 412 with the current envelope; the client can re-apply on the new base. - Re-granting an existing grant and revoking an absent one both succeed; a retried
PUTdoes not double-apply. - Reorder is atomic and compacts
sort_order; direct-grant images order independently of any gallery. - An omitted
mediaaggregate leaves media untouched; a present one replaces it completely. There is no per-field three-state inside the aggregate — verified by saving an unrelated entity field and confirming media is unchanged.
Scale and bounds:
A character with many granted galleries and many direct images returns a globally bounded payload at the pinned numeric caps, not merely per-section bounds — sections page as well as items.
Section cursors bind to the entity, the section and the effective projection epoch, and re-authorize on every page; a grant revoked between pages stops pagination, and an approval or a reorder mid-pagination invalidates the cursor rather than stitching two states.
Anything truncated is reported as a count, never silently dropped.
Worst-case matcher latency is measured at the pinned hard maxima (8 sources, 1000 candidates, 8000 scan characters), not a two-image fixture.
Hydrating a full message page of activations is one batched read, verified by query count.
Malformed or unknown-version activation JSON renders nothing and logs, without failing the history read.
Branch, fork, regenerate, version-switch and export preserve both image and lorebook activations.
A report is authorized by the substrate's issuance receipt — not by a message id plus image uuid, and not by anything in message JSON. An image that matched while the panel was off cannot be reported.
A report filed against an image survives the image being revoked, removed and hard-deleted, with owner and evidence intact.
Free baseline and UX:
- The private-gallery grant warning states both the disclosure and that already-seen links keep working after revocation.
- Loading, save-failure and pagination-failure states all render; the section is keyboard-operable and responsive at the shared breakpoints.
- A granted gallery whose images are all filtered out by maturity or moderation renders as empty-for-you, with no count that leaks what was hidden.
Edges (empty / failure / unauthorized / boundary):
- Linking a gallery owned by someone else fails and leaks nothing about whether it exists; linking to a non-editable entity fails identically.
- A directly-granted unsorted image (no gallery) renders on the detail page and can trigger — it does not vanish into an inner join.
- Deleting a gallery removes its grants; deleting an image removes its grant keywords; soft-deleting the target character removes both — verified through
fn_delete_character, not a hardDELETE. - Unlinking a gallery leaves directly-linked images from it still linked.
- A granted gallery whose grant is later withdrawn disappears from the detail page without erroring.
- An empty granted gallery renders no section rather than an empty one.
- A 400-image gallery returns a bounded payload with a working continuation token, in one database read, with no N+1 — verified against timings, not by inspection.
- A turn matching many images renders one and carries the rest without a payload blowup.
- A contributor who loses entity access can no longer change grants, and the grants they made remain.
Approved-media substrate:
- Chat matching, history hydration and browse all read the same approved-projection reader — verified by there being one implementation, not three.
- A pending addition is invisible to the matcher, to history hydration and to browse until approved — checked on all three, not sampled on one.
- A second edit while a revision is pending marks the first
superseded, and the creator sees one pending revision rather than a queue of their own edits. - Approving a superseded revision does not resurrect it or move the active pointer backwards.
- Submitting the same revision twice returns the same revision, not two queue items.
- Publishing a character that already has media reviews the character and its initial media snapshot as one unit, not as a character plus a pending revision against nothing.
- An external image must complete platform import before it can be granted; the import is retryable and is not attempted inside the save transaction.
- A revoked or tombstoned image disappears from all three surfaces immediately, without waiting on any review.
Authority and consent:
- A
can_contributecollaborator cannot attach media directly; their attempt becomes a proposal for an entity editor. - A gallery owner with no rights on the entity can revoke their grant through the gallery-side route — UC-13 exercised end to end.
- After the attaching editor loses access, the approved snapshot still renders, but new gallery members and keyword expansions require a current entity editor's acceptance before entering moderation.
Delivery and reporting:
- With the display toggle off, a match is recorded but not marked delivered, and a report filed against it is rejected.
- A report names the source association — gallery grant, image grant, or lorebook entry — not just the image.
- A report survives hard deletion of the image with its retained evidence intact, and the retention is released when the report closes.
Journeys (drive these end to end, not just the endpoints):
- Moderator review — a pending media revision is reviewable as a diff against the approved one, approvable and rejectable, with the rejection reason reaching the entity's editors.
- Editor consent — an incoming cross-owner grant request appears somewhere an entity editor will actually find it, and accept/reject both work.
- Owner revocation — a gallery owner can list their outgoing grants and revoke one, on a character they have no rights to.
- Import failure — granting an external image whose import fails shows the creator what went wrong and leaves no grant and no partial asset.
- Accessibility — the grant editor and the browse section are keyboard-operable end to end, with focus order, labels and Escape behaviour matching the shared components.
Package interaction (v1):
- A character granted a gallery behaves identically inside a package conversation — matching, panel and toggle all work, with no package-side per-image configuration.
- Publishing a package pins a snapshot of the character's media at that moment; a later character-media change does not reach the published package until the package owner accepts it.
Ordering:
- The same character renders the same total sequence on every load: gallery grants by
sort_orderthen id, direct grants as their own section after them, an image reachable by both paths appearing once in its gallery position.
Related documents
- Gallery & Image Storage — the unified image system, and the
entity_linksclaims this corrects. - Gallery Folders — nesting, and the organization-only invariant this respects.
- Lorebook Entry Images — the Side A / Side B split and the triggered-image rail reused, generalized and given persistence here.
Reader-side accessibility (prove the text reaches the reader, not just the editor):
- Approved alt text reaches the rendered
<img>in chat, in the browse section, in the lightbox and in a package page — verified in the accessibility tree, not in the authoring form. - Reordering, paginating and opening the lightbox are all keyboard-operable, with focus returning where it started on close.
Captions:
- A creator can give an image a caption, leave it empty, and both render correctly — text with the picture, or no caption line at all rather than an empty reserved row.
- The caption shown with a triggered image in chat is that image's caption, not the lorebook entry's name — under the thumbnail and in the lightbox.
- The same caption renders in the browse section, under the tile and in the lightbox.
- Alt text falls back to the caption when unset, and a creator-supplied alt text overrides it.
- Changing a caption on a granted image goes through review before any reader sees the new text.
-
ai_descriptionnever appears on a reader-facing surface or as alt text.