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:

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

Non-Goals

Deliberately out of scope — several of these a reader would reasonably assume are in:

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:

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:

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:

  1. 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". LinkImageToEntityAsync uses ON CONFLICT DO NOTHING and UnlinkImageFromEntityAsync does an unconditional DELETE (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.
  2. 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:

  1. 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.

  2. Maturity is filtered against the viewer's server-resolved ceiling, not a caller-supplied parameter. ContentImage blur 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.Ceiling must be plumbed into the pipeline context before p_max_rating means 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:

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:

  1. Image keywords — columns on gallery_images. Travel with the image everywhere it is used. This is the common case: a portrait tagged angry, furious, snarl means that wherever it shows up.
  2. 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.

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:

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:

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

  1. Candidates = images in galleries linked to a source with use_in_chat ∪ images linked directly with an explicit grant carrying use_in_chat. Deleted, unavailable and non-moderation_status = 0 images are excluded at the query.
  2. 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.
  3. Fire when at least one trigger keyword matches and all include keywords match, or when trigger_regex matches. use_exact_keyword_match switches word-boundary vs substring for every keyword field on that config.
  4. 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.
  5. Never fire an image with no trigger keywords and no regex. Keywords are optional; an image without them is browsable, not silent-firing.
  6. 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.
  7. 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's sort_order, then image id. No tie is left to the planner.
  8. Bounded. p_limit caps returned rows (default 8); the top one renders, the rest are carried.
  9. 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:

So this feature makes the caption a first-class reader-facing field:

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.

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:

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:

Inline pagination uses the continuation token. No N+1: one read regardless of how many galleries are linked.

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:

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:

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:

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:

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 vanishing done in F-10 (1804fd269, 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:

Two things earlier drafts left open are now decided, because leaving them open was itself the inconsistency:

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):

Behavior (exercise the mechanism):

Invariants that must stay true (carve-outs a reviewer can break if regressed):

Slice 1 — shared UI substrate (checked 2026-11-07 against the local stack, Forge on its own Vite, user gls1-staff):

Grants, provenance and migration:

Media review:

API and concurrency:

Scale and bounds:

Free baseline and UX:

Edges (empty / failure / unauthorized / boundary):

Approved-media substrate:

Authority and consent:

Delivery and reporting:

Journeys (drive these end to end, not just the endpoints):

Package interaction (v1):

Ordering:

Reader-side accessibility (prove the text reaches the reader, not just the editor):

Captions: