Packages (Full Experience Bundles)
Status: In Progress.
Shipped today: package CRUD via fn_save_package_full (single-call upsert with project-membership gate, returns publish-flow result columns is_public / was_auto_published / was_flagged), per-component locks, lorebook + model-profile + persona-template bindings, deliverables (one project → many publishable outputs), publish unification — packages.is_public is the single source of truth, gated by the publish_requests moderation pipeline and fn_verified_creator_auto_publish (the old project_deliverables.is_published / published_at columns were dropped by 47c_collapse_deliverable_publish_into_package.sql), curated greeting sets (package_greeting_bindings N:M + packages.greeting_id as the default — the staged slice of greeting-ownership unification; see that section's status callout), browse + public detail with ?contentRating= and ?includeMature= filters, admin moderation (publish / unpublish / soft-delete / restore + bulk variants, audited), package-level bookmarks (favorite + list, via user_package_bookmarks), package reports (generic via EntityType.Package = 6), OpenGraph endpoint (GET /og/package/{id}) with cf-worker bot rewrite, gallery-FK cover image pattern (cover_image_id → gallery_images, resolved through package_view), package presets (package_presets + GET /api/creator/package-presets), profile-page packages sections, hub statistics, conversation-from-package with auto-bound lorebooks. Maturity gating helper (fn_is_mature_rating) is wired through every read path; the per-user opt-in setting that flips its default is the next piece.
Also shipped since: derived co-creator credit (slices 1–3, c5f98bfa / 64cffd95, 2026-08-17), package tracker sets (P1, 3aa0275e, 2026-09-04), the cast (C1, 93eee7954, 2026-09-10), deliberate role pick at start (5419bad5, 2026-07-24), journal seeding as the package's Starting cast (M12d, 5744a0201, 2026-11-01: people and places set in the Forge's package editor, screened at publish, and put into a new story's Cast & places when it starts, if the story has the Journal on and isn't an all-ages story). mode_locked was retired 2026-09-20 (79bd3fa7) — see the lock table.
Forward-design (covered below but not yet shipped): chapters & events, greeting ownership unification (its curated-N:M slice shipped 2026-08-31 — the table-rename/FK-inversion half remains), update / re-sync notifications, detach-from-package, package templates, forking, premium tiers, paid-experience hooks (see paid-experiences.md), share-token endpoint (column lives, no endpoint yet).
Known constraint: fn_create_conversation_from_package currently raises if character_id IS NULL — BYOC packages can be saved and listed, but cannot yet be used to start a conversation. Lifting this is part of the greeting-ownership unification work below.
Overview
A Package is a curated, self-contained experience that bundles a character, model-aware Base-prompt mappings, lorebooks, trackers, greetings, and configuration into a single publishable unit. Where individual entities (characters, Modes, lorebooks) are building blocks, a package is the finished product—a complete, opinionated experience that users can start with one click.
Packages can lock or limit their components, preventing manual Entry/Mode detachment or incompatible lorebook additions while still allowing creator-defined automatic model resolution. Web Classic’s optional Profile Flavor controls remain available unless those choices are hidden/unavailable; the plan lock does not silently turn an optional style choice into required Base behavior. (Note: the manual plan/mode lock — mode_locked — was retired 2026-09-20; see the lock table below. Readers keep manual Entry/Mode selection; only Profile resolution and the lorebook lock constrain a package conversation today.) This lets creators deliver a specific experience exactly as intended, rather than a bag of parts.
Critically, packages are the bridge between creator complexity and user simplicity. Features like trackers, journal, mode-lorebook injection, and evaluation LLM configuration give creators powerful tools -- but exposing all of this to end users in the chat interface is overwhelming. Packages let creators pre-configure everything and ship a polished experience where the complexity is invisible. See Design Principles: User vs. Creator Experience for the full rationale.
Problem
Current experience
Today, starting a conversation requires assembling pieces:
- Pick a character
- (Optional) Pick a mode, or use the character's default
- (Optional) Attach lorebooks
- (Optional) Set up a persona
- (Optional) Choose a greeting/scenario
- (Optional) Configure trackers, custom instructions, settings
This flexibility is powerful for experienced users but creates friction for new users, and makes it impossible for creators to guarantee a specific experience.
What creators can't do today
- Ship a complete RPG: A character + tested model→combat-Base mappings + world lorebook + bestiary lorebook + HP tracker + starter scenario, all pre-configured. Today, users have to find and assemble these separately.
- Lock the experience: A creator builds mystery Base prompts that only work with their detective character and case-file lorebook. Users can currently detach to an incompatible Mode and break the experience.
- Coordinate updates: When a creator updates their character, lorebook, or reachable Base Mode, there's no way to push a coordinated update to users. Components version independently, so an updated Base might break with the old lorebook.
- Distribute a genre template: A "Slice of Life High School" package with a setting lorebook, tested model→Base mappings, and preset trackers that works with any character the user brings.
Proposed Design
Package Entity
Package
├── Name "The Crystal of Dawn - A Fantasy RPG"
├── Description "A complete tabletop-style fantasy adventure..."
├── OwnerId FK to user
│
├── Components
│ ├── SystemPromptId FK (the "identity" — or null for "bring your own")
│ │ └── character_type 'character' | 'system' | 'assistant' (see Character Types)
│ ├── ModeId FK (read-only legacy fallback; new packages null)
│ ├── ModelProfiles[] N:M via package_model_profiles (see Model Profiles)
│ ├── LorebookIds[] N:M via package_lorebook_bindings
│ ├── TrackerIds[] N:M (when tracker entities exist)
│ ├── Greetings[] 1:N owned by package (see Greeting Ownership below)
│ ├── DefaultGreetingId FK (which greeting to use by default)
│ └── PersonaTemplateId FK (optional suggested persona)
│
├── Locks
│ ├── CharacterLocked true → user cannot swap character
│ ├── ModeLocked RETIRED 2026-09-20 — enforced by nothing (see the lock table)
│ ├── LorebooksLocked true → user cannot remove/add lorebooks
│ └── TrackersLocked true → user cannot modify tracker set
│ -- InstructionsLocked retired (2026-07-22): Custom Instructions is purely
│ user-driven now — a package can never lock it. The `instructions_locked`
│ column is kept (permanently inert) for the other historical readers of
│ the packages table; see prompt-presets.md "What we are actually solving"
│ for the retirement decision.
│
├── Defaults
│ ├── CustomInstructions Pre-filled custom instructions text
│ ├── SettingsOverrides JSON of setting key→value overrides
│ └── JournalSeed[] Starter journal entries (if journal feature exists)
│
├── Metadata
│ ├── CoverImageUrl
│ ├── Tags[]
│ ├── Genre
│ ├── EstimatedLength "one-shot" | "short" | "campaign" | "open-ended"
│ ├── ContentRating
│ ├── Version Semver string
│ └── Changelog Per-version notes
│
├── Chapters[] 1:N (configuration overlays, see Chapters and Events)
│ ├── Chapter 1 "Prologue" (is_starting = true)
│ │ ├── SystemPromptModifier, CustomInstructions, SettingsOverrides
│ │ ├── LorebookBindings[] / AdditiveLorebooks[]
│ │ ├── TrackerModifications
│ │ └── TransitionMessage
│ └── Chapter 2 "The Journey"
│ └── ...
│
├── Events[] 1:N (trigger + action pairs, see Chapters and Events)
│ ├── Event "journey_begins"
│ │ ├── Trigger { tracker: "story_arc", operator: "equals", value: "journey" }
│ │ └── Action { chapter_transition → Chapter 2 }
│ └── ...
│
├── Visibility
│ ├── IsPublic
│ ├── IsListed (public but not in browse/hub)
│ └── ShareToken
│
└── Timestamps
Component Locking
Locks control what users can customize after starting a package conversation.
Status column is load-bearing — read it before designing against this table. Two of
the five original locks are not enforcement today (and a third, mode_locked, was retired 2026-09-20), and two prompt-bearing surfaces cannot
be locked at all (see What a lock cannot reach below).
| Lock | Column | Status | When locked | When unlocked |
|---|---|---|---|---|
| Character | character_locked |
Discord only — enforced for managed bot instances (BotInstanceConfig); on web the flag is reported to the client in PackageLockDto but nothing consumes or enforces it |
User must use the packaged character. Swap button hidden. | User can switch to any character. Package provides a default. |
| Mode / Entry selection | mode_locked |
Retired 2026-09-20 (79bd3fa7, 767b1daaa) — enforced by nothing. The server refusal of a mode swap (PATCH /api/conversations), the Hybrid package-start clamp, the Beat/Prose leg-pin refusal and the Discord managed-bot mode pin were all removed; Model Profiles are the one answer to which mode runs. The column is kept for historical rows and the workbench round-trips it untouched; it is no longer sent on the conversation payload (PackageLockDto dropped it). The About form's "Pipeline choice" radio that wrote it was removed 2026-09-29 because it promised a pin nothing honours (see Hybrid Pipeline § Package start, which records the reversal) |
— | Readers always choose Classic/Hybrid and may pick Entries/legs as Model Profile resolution allows. |
| Lorebooks | lorebooks_locked |
Enforced — server refuses attach/detach on a locked package conversation | Lorebook list is fixed. Add/remove disabled. | User can attach additional lorebooks. Package lorebooks always present. |
| Trackers | trackers_locked |
Not enforced — the column, the package view and the changelog trigger exist, it round-trips through fn_save_package_full since package tracker sets shipped (P1, 3aa0275e, 2026-09-04), and the value is surfaced in the Composer pool read projection (IProjectPoolReads.TrackersLocked), but nothing acts on it in a conversation |
Tracker set is fixed. Toggle disabled. | User can add/remove trackers. Package provides defaults. |
| Instructions | instructions_locked |
Retired 2026-07-22 — permanently FALSE. Removed from the request contract so creators cannot set it; the column is kept for history only |
— | Custom Instructions is purely user-driven. A package can no longer lock it. |
Why locks exist: protecting experience integrity.
Locks are not anti-user — they're pro-experience. A creator who spent weeks wiring up a three-act mystery with precise lorebook gating, tracker-driven chapter transitions, and tuned evaluation prompts should be able to say "this is the experience, play it as designed." Letting a user rip out the combat mode and swap in a slice-of-life mode isn't "user freedom" — it's breaking the product.
This is especially true for creators who monetize their work. A premium RPG campaign package is a product with a specific design intent. Locks protect that intent the same way a game protects its core systems. Even games that embrace modding have boundaries — unguided modification of tightly coupled systems doesn't produce "creative freedom," it produces broken experiences and false bug reports.
The unlock spectrum exists for creators who want to offer flexibility. A BYOC genre template with everything unlocked is a valid authoring shape, although normal public BYOC Start Experience remains unavailable until greeting ownership is unified. A locked cinematic experience is equally valid. The creator decides, not the platform — and that's the correct default. Users who want full tinkering freedom can build their own experiences from individual components; packages serve users who want a curated, coherent experience that works out of the box.
What a lock cannot reach
The argument above is about components. It does not extend to the prompt itself. Two user-controlled surfaces feed the prompt and are not lockable by any package:
- Custom Instructions — was lockable; retired 2026-07-22 (see the table).
- Author's Notes — never had a lock. There is no
author_note_lockedcolumn, andPUT /api/conversations/{id}/author-notegates on ownership and the publish-review edit lock only — it never looks at the package. A user in a fully locked package conversation can set, change and clear an Author's Note freely.
Both are prompt-bearing steering text, and the Author's Note deliberately lands adjacent to the newest messages — the highest-attention slot in the whole prompt, which is why it runs the same prompt-injection similarity check Custom Instructions does. So a locked package guarantees which components are loaded, not what the model is finally told. A creator can pin the character, the mode and the lorebook set, and the reader can still steer the scene from the strongest position in the context window.
Treat that as the intended boundary rather than a gap to close. Steering your own
conversation belongs to the reader, and a creator's lock should not be able to take away
someone's ability to redirect their own story — that is the same line the manifesto draws
everywhere else. What the spec must not claim is that locks make an experience immutable:
they don't, no planned lock changes it, and a creator who needs guarantees about the final
prompt is asking a genuinely new design question, not for an author_note_locked flag.
Partial locks (future consideration):
- "Locked but extendable" -- user can't remove package lorebooks but CAN add more
"Locked with overrides" -- user sees package instructions but can append to them— moot since the Instructions lock was retired; Custom Instructions is always the user's.
For the initial implementation, binary locked/unlocked is sufficient. "Locked but extendable" can come as an iteration -- it's backward compatible since loosening a lock doesn't break anything.
"Bring Your Own" Components
Not every package needs to bundle everything. Some useful patterns:
The "manual plan lock" in this table is the retired mode_locked — read those cells as "Profile Entries" only.
| Pattern | Character | Prompt-plan policy | Lorebooks | Use case |
|---|---|---|---|---|
| Full experience | Locked | Profile Entries + manual plan lock | Locked | Complete RPG, mystery game, etc. |
| Genre template | None (future public BYOC) | Profile Entries + manual plan lock | Locked | “Fantasy RPG template” — user picks their character |
| Character showcase | Locked | Optional Profile / manual Mode allowed | Locked | Character creator's intended experience, user picks writing style |
| World setting | None (future public BYOC) | No Profile enforcement; user chooses Mode | Locked | “Cyberpunk 2087 setting” — world lorebooks, user brings character and prompt style |
| Starter kit | Unlocked | Recommended Profile Entries | Unlocked | Recommended defaults, user can customize everything |
Character/lorebook nullability represents “bring your own” where the corresponding lock allows it, but the current public start function still rejects a null package character. Until greeting ownership is unified, only the creator-only Sandbox may supply its isolated test character; normal Start Experience cannot. Prompt-plan selection is not a nullable new-package Mode component: a Profile Entry wins by model, then the read-only legacy package fallback (old rows only), selected-character default, and built-in defaults form the outer chain.
Character Types in Packages
With character_type, packages can bundle multiple "characters" that serve different roles without colliding in the pipeline. Each type injects content under a different provider key:
| Example Package | Character (persona) | System (rules) | Assistant (helper) |
|---|---|---|---|
| D&D Campaign | "Elara the Narrator" | "D&D 5e Core Rules" | "DM's Rules Reference" |
| Mystery Game | "Detective Morgan" | "Investigation Rules" | "Clue Tracker Assistant" |
| Writing Workshop | None (future public BYOC) | "Workshop Guidelines" | "Writing Coach" |
The character entity infrastructure (system prompt, greetings, scenarios, lorebooks) is reused for all types -- only the injection point differs. A "system" character's greeting becomes a game initialization message; its system prompt becomes the rules text.
Conversation Flow
Starting a Package
- User finds package in Hub/Browse
- Clicks "Start Experience" (or "Continue" if resuming)
- System creates a conversation pre-configured with:
- Character from package; after the separate greeting-ownership/BYOC work lands, a null unlocked package may instead prompt for an accessible character
- Effective prompt plan: the winning Profile Entry’s Base when one matches; otherwise exact read-only legacy-package / selected-character / built-in fallback provenance
- Lorebooks auto-bound to conversation
- Trackers auto-activated with initial values
- Greeting/scenario applied
- Custom instructions pre-filled
- Validated package-safe settings defaults applied
- Journal seeded (if applicable)
- Locked components show lock icon in chat settings
- Unlocked components show as normal (editable)
Package Conversation vs. Regular Conversation
A package conversation is a regular WebConversation with an additional package_id FK. The package ID:
- Determines which components are locked (checked at API level)
- Links back to the package for metadata/display
- Allows "re-sync" if the package creator updates components
The conversation itself is a standard conversation -- all existing chat features work. The package just sets initial state and enforces locks.
WebConversation
├── ... existing fields ...
├── PackageId (optional) FK to packages table
└── PackageVersion Version string at time of creation
Detaching from a Package
Users should be able to "detach" a conversation from its package, removing all locks and making it a normal conversation. This is a one-way operation (can't re-attach). Useful when:
- User wants to take the story in a different direction
- Package creator deleted the package
- User wants to experiment with different modes/lorebooks
Package Updates and Versioning
Current V1 behavior is explicit:
- Package/Profile/Base references are live and participate in reverse-impact invalidation/review. Saved Base or existing Flavor-content edits affect turns accepted after revalidation.
- A conversation’s Web Classic Flavor roster is the one frozen slice: later additions, unhide, default, order, group, or stage changes require the package-aware Start new conversation action. Current hide/delete suppression still applies at turn acceptance.
- Entry recommendations remain opt-in and are never written into existing conversations merely because a Profile changed.
- New conversations resolve against the package’s current live graph. There is no user-facing claim that an old graph can be restored.
Future snapshot-based version strategy
The desired product remains explicit package upgrades: metadata-only changes can flow immediately; component/breaking changes can announce a changelog; users can choose a tested new version while preserving messages, journal entries, tracker history, and allowed user additions. That workflow is not implementation-ready in this document. It first requires package/component snapshot identities, stored diffs, retention/deprecation policy, an atomic upgrade transaction, and an explicit decision for each frozen conversation slice—especially whether a Flavor-roster change forces the already-specified new-conversation flow. Until that substrate and its own acceptance criteria land, no UI may offer Update, Keep current, or “version you started on.”
Database Schema
Implemented in
database/v1/. See source files for full details.
Packages (core)
File: 21_tables_packages.sql
The shipped schema reuses existing entity tables rather than introducing a separate system_prompts or package-owned greetings table. The package row still holds nullable FKs to characters, legacy prompt_modes, character_greetings, and personas, but new authoring uses package_model_profiles → model_profile_entries.mode_id; packages.mode_id is preserved only for old fallback rows. Greeting unification (greetings owned by packages instead of characters) is documented under Greeting Ownership and remains forward-design.
CREATE TABLE packages (
id SERIAL PRIMARY KEY,
uuid UUID NOT NULL DEFAULT gen_random_uuid(),
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(200) NOT NULL,
description TEXT,
-- Components (all optional for "bring your own" patterns)
character_id INTEGER REFERENCES characters(id) ON DELETE SET NULL,
mode_id INTEGER REFERENCES prompt_modes(id) ON DELETE SET NULL,
greeting_id INTEGER REFERENCES character_greetings(id) ON DELETE SET NULL,
persona_template_id INTEGER REFERENCES personas(id) ON DELETE SET NULL,
-- Builder preset used to create this package
preset_id INTEGER REFERENCES package_presets(id) ON DELETE SET NULL,
-- Locks
character_locked BOOLEAN NOT NULL DEFAULT FALSE,
mode_locked BOOLEAN NOT NULL DEFAULT FALSE,
lorebooks_locked BOOLEAN NOT NULL DEFAULT FALSE,
trackers_locked BOOLEAN NOT NULL DEFAULT FALSE, -- reserved; tracker bindings still WIP
instructions_locked BOOLEAN NOT NULL DEFAULT FALSE, -- retired 2026-07-22, permanently inert (kept for legacy readers)
-- Defaults
custom_instructions TEXT,
settings_overrides_json TEXT, -- exact package-safe allowlist only; never Generation/LLM/secrets
journal_seed_json TEXT, -- the Starting cast (seed v1, M12d); read at story start
-- Metadata
cover_image_url VARCHAR(500), -- legacy; superseded by cover_image_id (gallery FK)
cover_image_id INTEGER REFERENCES gallery_images(id), -- added by 31d_entity_avatar_image_links.sql
tags_json TEXT, -- reserved; tag wiring still WIP
genre VARCHAR(100),
estimated_length VARCHAR(50), -- one-shot | short | campaign | open-ended
content_rating VARCHAR(20),
version VARCHAR(50) NOT NULL DEFAULT '1.0.0',
changelog TEXT, -- reserved; per-version notes still WIP
-- Visibility
is_public BOOLEAN NOT NULL DEFAULT FALSE,
is_listed BOOLEAN NOT NULL DEFAULT FALSE, -- public but not in browse/hub
share_token VARCHAR(100), -- column + index live; share endpoint not shipped
-- State
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Indexes
CREATE UNIQUE INDEX idx_packages_uuid ON packages(uuid);
CREATE INDEX idx_packages_owner ON packages(owner_id) WHERE NOT is_deleted;
CREATE INDEX idx_packages_public_listed ON packages(is_public, is_listed) WHERE NOT is_deleted AND is_public;
CREATE INDEX idx_packages_character ON packages(character_id) WHERE character_id IS NOT NULL AND NOT is_deleted;
CREATE INDEX idx_packages_genre ON packages(genre) WHERE genre IS NOT NULL AND NOT is_deleted;
CREATE INDEX idx_packages_share_token ON packages(share_token) WHERE share_token IS NOT NULL;
CREATE INDEX idx_packages_updated_at ON packages(updated_at DESC) WHERE NOT is_deleted;
CREATE INDEX idx_packages_content_rating ON packages(content_rating) WHERE content_rating IS NOT NULL AND NOT is_deleted;
-- N:M lorebook bindings (ordered)
CREATE TABLE package_lorebook_bindings (
id SERIAL PRIMARY KEY,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
lorebook_id INTEGER NOT NULL REFERENCES lorebooks(id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE(package_id, lorebook_id)
);
-- N:M model profile bindings (ordered, first profile is default)
CREATE TABLE package_model_profiles (
id SERIAL PRIMARY KEY,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
model_profile_id INTEGER NOT NULL REFERENCES model_profiles(id) ON DELETE CASCADE,
is_default BOOLEAN NOT NULL DEFAULT FALSE, -- exactly one active binding when set is nonempty
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE(package_id, model_profile_id)
);
-- N:M persona template bindings
CREATE TABLE package_persona_template_bindings (
id SERIAL PRIMARY KEY,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
persona_template_id INTEGER NOT NULL REFERENCES persona_templates(id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE(package_id, persona_template_id)
);
-- Conversation link
ALTER TABLE web_conversations
ADD COLUMN IF NOT EXISTS package_id INTEGER REFERENCES packages(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS package_version VARCHAR(50);
CREATE INDEX idx_web_conversations_package_active ON web_conversations(package_id)
WHERE package_id IS NOT NULL AND NOT is_deleted;
Project Deliverables (publishable outputs)
File: 25_tables_projects.sql (deliverables live alongside projects, not packages)
A package by itself isn't user-facing — it's a project_deliverables row that connects a package to a project and exposes it as a publishable output. One project can produce multiple deliverables (full RPG package, individual lorebook, individual mode), all sharing the same sub-items. See package-workbench.md for the deliverables workflow in full.
CREATE TABLE project_deliverables (
id SERIAL PRIMARY KEY,
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
description TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Publish state lives on
packages, not deliverables. An earlier revision of this table carriedis_published BOOLEANandpublished_at TIMESTAMPTZ— both columns were dropped by47c_collapse_deliverable_publish_into_package.sql. The publish flow goes throughpublish_requests→fn_handle_publish_request→packages.is_public, andfn_list_project_deliverablesrecomputesis_published/published_atfor the client from the package row. Treat the deliverable as a presentation envelope; the package row is the state machine.
Save orchestration — fn_save_package_full
File: functions/47_package_functions.sql
The single-call upsert function used by every production save. Resolves component UUIDs to int IDs, gates on project owner OR member with can_contribute, upserts the package, syncs lorebook + model-profile + persona-template bindings, upserts the deliverable — all in one transaction. Every nullable text field uses COALESCE(p_field, packages.field) on UPDATE so omitting a field preserves the existing value (three-state semantics: omit / empty / value). Auto-bumps the patch version on every update.
Returns three publish-flow result columns alongside the saved row: is_public (whether the package is currently published), was_auto_published (true when this save tripped fn_verified_creator_auto_publish), and was_flagged (true when the save was routed into the moderation queue).
The cover image rides the same call: p_cover_image_uuid takes a gallery_images.uuid and is resolved, validated and written before the publish/moderation decision. It is three-state like p_mode_uuid — SQL NULL preserves the current cover, the nil UUID clears it, any other value sets it — and an image the caller doesn't own rejects the whole save. (The raw p_cover_image_url is long gone; the post-save SetCoverImageAsync setter that replaced it was folded back in here, because a second write let a cover land after a verified creator's package had already auto-published — WORKBENCH_PROJECTS_REVIEW_2026-07-24 WP-29.)
Component bindings are full replacement, and an unbindable one is a refusal. The five component params — p_character_uuid, p_greeting_uuid, p_lorebook_uuids, p_model_profile_uuids, p_persona_template_uuids — are not three-state like the mode and cover above. Each save carries the package's whole binding state, so SQL NULL (and, for the arrays, an empty array) means "no binding" and clears; that is what lets the workbench unpick a character or drop the last lorebook. Any UUID that is supplied must pass the binding gate — caller owns it, it is public, or it is shared into this project — and one that doesn't raises and aborts the save whole.
That last part is the fix for a data-loss bug, not a new restriction. Because the write is a full replacement, resolving an unbindable UUID to NULL (or dropping it out of the array) turned "I can't bind what you asked for" into "I cleared what you already had": a component that had been un-shared, made private, or deleted came back as a 200 with the binding silently gone, an unrelated rename in the same save committed on top of it, and the package that went to moderation was not the package the creator saved. Every refusal now maps to its own client code — character_not_bindable, greeting_not_bindable, lorebooks_not_bindable, model_profiles_not_bindable, persona_templates_not_bindable — and the endpoint answers 403.
A component the package already holds passes the gate even after it stops qualifying, so the owner keeps what they had and can still save. That includes a character or legacy mode its owner deletes later: the edit read still shows both, the next save sends them back, and they stay bound (an admin restore brings them back whole). A new bind to a deleted component is refused like one that doesn't exist.
Three more fail-closed rules: a supplied p_deliverable_id must belong to this package (not merely to the project), an explicit p_mode_uuid the caller can't bind raises rather than resolving to NULL, and a p_idempotency_key already held by a different owner raises rather than adopting that owner's package row (409 idempotency_key_conflict). All abort the transaction whole.
Create idempotency over HTTP. POST /api/creator/projects/{id}/packages accepts an optional Idempotency-Key request header (≤48 chars, [A-Za-z0-9_-]). Send the same value on a retry of a package create and the original package + deliverable come back instead of duplicates; omit it and every save is its own create, which is what an interactive click means. The header value is namespaced with the caller's user id before it reaches the function, because the underlying unique index is platform-wide rather than per owner.
The narrower per-table primitives (fn_save_package, fn_sync_package_lorebook_bindings, fn_sync_package_model_profile_bindings, fn_save_project_deliverable) still exist and are called by fn_save_package_full internally for the sync steps, but are otherwise reserved for tests — production code must use fn_save_package_full.
Maturity helper
File: 21_tables_packages.sql
CREATE FUNCTION fn_is_mature_rating(p_rating VARCHAR) RETURNS BOOLEAN
LANGUAGE sql IMMUTABLE
AS $$
SELECT p_rating IS NOT NULL
AND LOWER(p_rating) IN ('mature', 'nsfw', 'adult', 'explicit');
$$;
Single source of truth for "is this rating mature?". Both package_view and admin_packages_view expose is_mature as a column. The browse path applies fn_is_mature_rating(p.content_rating) as a gate when BrowseQuery.IncludeMature is false; owners always see their own packages regardless. The per-user opt-in setting that flips the default is the next piece.
Views
package_view (public read path) and admin_packages_view (admin moderation) currently join packages with creator + character + legacy-mode info and compute lorebook_count / conversation_count via LEFT JOIN LATERAL aggregates rather than correlated subqueries — single hash-aggregate pass instead of one subquery per row. Plan-aware reads additionally project Profile Entry/Base variants rather than presenting that legacy join as the package’s one Mode. Both views also expose is_mature so the gate can be applied without re-evaluating the rating string in every caller.
Character Types
File: 03a_add_character_type.sql
Characters now have a character_type column that determines their role in the pipeline:
| Type | Pipeline Provider Key | Purpose |
|---|---|---|
character |
character |
AI persona -- who the AI is (default, backward compatible) |
system |
rules |
Rules/mechanics -- D&D systems, combat rules, game constraints |
assistant |
assistant |
Utility/helper -- DM assistant, writing coach, rules reference |
All types reuse the same infrastructure (system prompt, greetings, scenarios, lorebooks). The type determines which content provider key is used for pipeline injection, so a package can bundle a character (persona) + system (rules) + assistant (helper) without them colliding in the prompt.
ALTER TABLE characters
ADD COLUMN character_type VARCHAR(20) NOT NULL DEFAULT 'character';
ALTER TABLE characters
ADD CONSTRAINT check_character_type
CHECK (character_type IN ('character', 'system', 'assistant'));
The fn_upsert_character function accepts an optional p_character_type parameter (defaults to 'character' for backward compatibility). fn_get_conversation_character returns character_type so the pipeline can route content to the correct provider.
Model Profiles
File: 23_tables_model_profiles.sql
Model profiles are standalone, shareable configurations that map specific LLM models to always-on Base-prompt Modes, optional parameter recommendations, and (in the Document Mode Editor plan) optional Profile-wide Flavors. They are the indirection layer between packages and per-model prompt selection; the current V1 package link is live, so Profile changes participate in reverse-impact invalidation for every package that references it.
model_profiles -- Named, owned, shareable
└── model_profile_entries -- Per model: "for model X, use Base Mode Y" + optional recommendations
└── mode_id → prompt_modes (which already have sub-prompts via N:M)
packages ──► package_model_profiles (N:M) ──► model_profiles
Why standalone? Creators frequently update model configurations as models are released and behavior changes. Without this indirection, every package would need duplicate mappings. With live V1 Profile links, one update is visible to all bound packages under the reverse-impact/review rules; Entry recommendations remain opt-in and are never silently written into conversations.
CREATE TABLE model_profiles (
id SERIAL PRIMARY KEY,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(100) NOT NULL,
description VARCHAR(500) NOT NULL DEFAULT '',
is_public BOOLEAN NOT NULL DEFAULT FALSE,
published_at TIMESTAMP WITH TIME ZONE,
-- How strictly mode mappings are enforced in packages:
-- 'optional' — User can switch to any mode freely
-- 'recommended' — UI encourages profile modes but doesn't lock
-- 'mandatory' — Selected model must match an Entry and use its Base; no arbitrary Mode
mode_enforcement VARCHAR(20) NOT NULL DEFAULT 'optional',
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE model_profile_entries (
id SERIAL PRIMARY KEY,
uuid UUID NOT NULL DEFAULT gen_random_uuid(),
model_profile_id INTEGER NOT NULL REFERENCES model_profiles(id) ON DELETE CASCADE,
model_identifier VARCHAR(255) NOT NULL, -- e.g., "anthropic/claude-3.5-sonnet"
mode_id INTEGER NOT NULL REFERENCES prompt_modes(id) ON DELETE CASCADE,
-- Optional per-model parameter recommendations (NULL = no recommendation;
-- never applied merely because this Entry wins resolution)
temperature DECIMAL(4,3),
max_tokens INTEGER,
top_p DECIMAL(4,3),
frequency_penalty DECIMAL(4,3),
presence_penalty DECIMAL(4,3),
sort_order INTEGER NOT NULL DEFAULT 0,
is_deleted BOOLEAN NOT NULL DEFAULT FALSE
);
-- Active identifiers are unique; Entry removal is a Profile-locked soft delete so
-- conversation/audit provenance survives. Restore is explicit.
CREATE UNIQUE INDEX ... ON model_profile_entries(model_profile_id, model_identifier)
WHERE is_deleted = FALSE;
-- N:M: packages reference model profiles
CREATE TABLE package_model_profiles (
id SERIAL PRIMARY KEY,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
model_profile_id INTEGER NOT NULL REFERENCES model_profiles(id) ON DELETE CASCADE,
is_default BOOLEAN NOT NULL DEFAULT FALSE, -- exactly one active binding when set is nonempty
sort_order INTEGER NOT NULL DEFAULT 0,
UNIQUE(package_id, model_profile_id)
);
Relationship to packages.mode_id: This nullable column is read-only legacy compatibility, not a newly authorable package component. Existing nonnull values remain the package-layer fallback after no Profile Entry matches; new packages store null, so the outer resolver continues through selected-character default Mode → built-in DefaultSections. Ordinary Workbench Save must preserve an existing value rather than sending the current modeId: null shape into the direct-assignment SQL writer. Removal is an explicit owner/reverse-impact action, and a corrected policy-1 * Entry is the supported way to author new catch-all Base behavior.
UI Considerations
Creator Side (Forge)
Status (2026-08-06): this section is target state, not a description of the shipped Forge. Marked per line below because several of these have store actions wired with no reachable UI, which reads as "shipped" to anyone grepping. The Workbench's own spec — Creator Workbench — is the authority on what the builder actually renders today; where the two disagree, that one wins for the Forge surface.
Package Editor:
- ✅ Select/create components (character, Model Profile Entries/Base prompts, lorebooks, greetings) — preset-step driven; trackers are Phase 2. Greetings persist as a full curated set since 2026-08-31 (
package_greeting_bindings) with first-position default + "Make default"; before that the builder showed a multi-greeting step but silently saved only the first - ❌ Show an existing legacy package Mode read-only — the binding is preserved correctly, but no preset carries a
modestep, so no card renders and the "Remove legacy fallback" action does not exist - ❌ Set locks per component (toggle switches) —
toggleLockexists in the store with no UI caller. Locks are written to the DB on every save and nothing can change them. (Knowledge review 2026-09-29: the one caller that briefly existed — the About form's "Pipeline choice" radio, writing the retiredmode_locked— was removed because it promised a pin nothing honours. Still no control forcharacter_locked/lorebooks_locked/trackers_locked, yet the builder honours a stored lock on the creator's own drops:ResolvedEntityCard.tsx:42-50toasts "That slot is locked — unlock it to change the binding." andworkbenchStore.assignEntityToSlotsilently no-ops, with no unlock anywhere in the UI. A lock set over the API/agent tools therefore traps the creator. Fix shape: a Locks row on the About form (sharedToggleper live lock, staged into the draft, single Save), labelled by the reader-facing consequence and marked "not enforced yet" where the status column above says so.modemust leave both builder lock maps —ResolvedEntityCard's went 2026-09-29;workbenchStore.assignEntityToSlot'slockMapfollowed the same day, so a storedmode_locked = TRUE(legacy rows, MCPmode_locked=true, managed-bot packages) no longer refuses dropped Mode items.) - ⚠️ Preview the assembled experience — Sandbox exists, but it gates on a selected character, not a package deliverable
- ✅ Write description, set metadata (genre, length, rating)
- ❌ Version management: bump version, write changelog — version is display-only in the About form; the server bumps it on save
- ✅ Test mode: start a conversation with your own package to verify the experience (Sandbox; the conversation carries
packageIdso locks apply server-side)
Dashboard: ❌ Not started. No usage stats, no per-version conversation counts, no "push updates with changelogs" surface. The nearest shipped thing is the deliverables list on the Workbench landing view, which shows name, character and published state only.
Hub / Browse
Package Cards:
- Cover image, name, creator, genre tags
- Component icons showing what's included (character, Model Profile/Base mappings, lorebooks, trackers; legacy fallback only when present)
- Lock icons showing what's customizable
- "Start Experience" button
- Rating, favorites, conversation count
Package Detail Page:
- Full description and changelog
- Component breakdown (which character, reachable Base mappings/fallbacks, lorebooks)
- User reviews/comments
- "Start Experience" and "Customize" (if unlocked components exist) buttons; a null-character package shows Start unavailable with the greeting-ownership/BYOC reason until that separate launch flow exists
Chat Side
Package indicator:
- Package name/icon in conversation header
- Lock icons on locked settings (tooltip explains why locked)
- "Detach from package" option in conversation settings (with confirmation)
- Future, after package-version snapshots: "Package updated" notification bar with changelog and a specified upgrade/restart action; V1 live-linked chats do not show a fictional Update/Keep-current control
Integration with Other Planned Features
Model Profiles
Packages reference model profiles via the package_model_profiles junction table. A creator who has tested their experience across multiple models can ship per-model mode configurations -- use a verbose mode for Claude, a concise mode for GPT-4, etc. -- and users get the optimized experience for whichever model they're using, without any configuration.
Because Model Profiles are standalone entities, a creator can add a model mapping or revise a recommendation once and every live-linked package sees the updated Profile through reverse-impact invalidation. Existing conversation Flavor rosters stay frozen by their own snapshots, and recommendation changes are not auto-applied to generation settings. Future package pinning/explicit upgrade is a separate Workbench migration, not current behavior.
Mode enforcement controls how strictly the profile's mode assignments are enforced within a package:
- Optional (default) — The profile's mode mappings are suggestions. Users can switch to another Mode (the package Plan lock that could forbid it was retired 2026-09-20); available Web Classic Flavor toggles are unaffected.
- Recommended — The UI encourages using the profile's modes (shows a recommendation when the user tries to switch away) but does not lock them out (the package’s separate Plan lock was retired 2026-09-20); available Flavor toggles are unaffected.
- Mandatory — The selected model must match an Entry in the governing Profile and the conversation must use that Entry’s Base. An untested/no-match model cannot generate through an outer fallback, and arbitrary Mode detachment is unavailable. With several bound Profiles, the exact winner governs; when none wins, the package’s single normalized default Profile governs.
A package-level Mode lock additionally forbids manual Entry/Mode overrides, while creator-defined automatic re-resolution remains allowed.(The package Mode lock was retired 2026-09-20.)
This is a per-profile setting (model_profiles.mode_enforcement), not per-package-link. The creator decides the enforcement level when authoring the profile based on how critical the mode assignments are to the experience.
Character Types and Pipeline Injection
With character types (character, system, assistant), packages can compose multiple "characters" that serve fundamentally different roles. Each type maps to a different content provider key in the pipeline, so content doesn't collide:
- A character (persona) injects via
characterkey -- who the AI is - A system (rules) injects via
ruleskey -- how the world works - An assistant (helper) injects via
assistantkey -- utility/coaching support
This means a package can bundle a character + a rule set + a helper assistant and have them all active simultaneously, each injected at the correct point in the prompt.
Trackers and Conditional Entries
Packages can bundle tracker definitions. When a user starts a package conversation, trackers are auto-activated with initial values from the package (or tracker defaults). The creator tunes extraction hints so the evaluation call works well out of the box.
Packages are the ideal delivery mechanism for conditional entries. A package bundles trackers + lorebooks with pre-wired conditions, so a "Fantasy RPG" package can ship with a story_arc enum tracker and lorebook entries that unlock per act -- the entire progression system works without any user configuration.
Mode-Specific Lorebook Injection
Packages whose reachable Base Modes use specific lorebook targeting get the full benefit. Each Base’s sub-prompts can reference specific lorebooks by ID, and the package ensures those lorebooks are present.
Journal
Packages can seed the journal with initial state facts, character profiles, and location profiles via journal_seed_json. This gives the story a running start -- the user begins with pre-populated NPC cards and location knowledge rather than an empty journal that takes 20 messages to fill.
Package-safe settings defaults
settings_overrides_json is not an arbitrary settings back door. Package Save and Start Experience validate one versioned, server-owned exact-key allowlist; V1 permits only:
Context.ResponsePacing,Context.ResponseTargetWords;Features.EnableSummaries,Features.EnableMemories,Features.EnableLorebook,Features.EnableLorebookImages,Features.EnableJournal,Features.EnableTrackers;Journal.EvalCadence,Journal.MaxEntries; andTracker.EvalCadence.
Values use the canonical setting metadata/type/range validation, and the complete package save fails atomically on an unknown, duplicate, malformed, or non-allowlisted key. Generation.*, every chat/evaluation *Llm.* provider/model/preset/API-key field, *.Default*, secrets, admin-only settings, and subscription/entitlement controls are rejected. In particular, a package cannot bypass Model Profile Entry’s opt-in recommendations by writing generation parameters here. The editor is a typed picker over this allowlist, not a free-text key/value form. Feature availability and paid eligibility still gate the effective result; package defaults do not grant capabilities. Adding an evaluation-preset binding later requires a separate accessible-preset/ownership contract rather than a raw model string in this JSON.
Greeting Ownership
Current model: Greetings are children of characters (character_greetings.character_id, ON DELETE CASCADE). A package holds a curated N:M set of its character's greetings (package_greeting_bindings) plus a single default FK (packages.greeting_id, always in the set). This means:
- Greetings are tightly coupled to a specific character
- A package can only bind greetings that belong to its character
- The same character identity in two different packages shares one greeting pool, but each package curates and orders its own subset of it
- "Bring your own character" packages can't have greetings at all (no character = no greetings to reference)
Unified model: Greetings become direct children of packages (1:N), not characters. The package owns its greetings and has a default_greeting_id to pick one:
-- Greetings are owned by packages, not characters
greetings (renamed from character_greetings)
├── package_id FK → packages (NOT NULL, ON DELETE CASCADE)
├── name, description
├── greeting_content_id FK → greeting_contents (public text)
├── scenario_content_id FK → scenario_contents (private text)
└── ...
packages
├── system_prompt_id FK (the "identity" — nullable for BYOC)
├── default_greeting_id FK → greetings (nullable)
└── ...
What this unlocks:
- Same identity, different greetings. A creator writes one system prompt ("Elara the Bard") and packages it twice: a "Tavern Encounter" package with tavern-themed greetings and a "Dungeon Crawl" package with dungeon greetings. Today this requires duplicating the entire character.
- BYOC packages with greetings. A "Fantasy RPG Template" package with no system prompt can still have greetings that set the scene ("You awaken in a forest clearing..."). Today, no character = no greetings.
- System-type greetings. A rules-type package ("D&D 5e Core") can have a greeting that serves as the game initialization message without needing a persona character.
Migration path:
- Rename tables:
character_greetings→greetings,character_greeting_contents→greeting_contents,character_scenario_contents→scenario_contents. Drop thecharacter_prefix since greetings are no longer character-specific. - Replace FK: Change
character_id→package_idon the greetings table. Every existing character becomes a package first, so existing greetings point to the migrated package. - Move
default_greeting_idfrom thecharacterstable to thepackagestable. - Drop
packages.greeting_id— the relationship inverts. Instead of a package pointing to one greeting, the package owns multiple greetings and picks a default. - Update conversation references:
web_conversations.greeting_idstill works — it points to a greeting row. The greeting just lives under a package now instead of a character.
Greetings / Scenarios
Packages own their greetings directly, so every package naturally includes its opening scenes. Combined with journal seeding and tracker initialization, the first message drops the user into a fully realized starting state. For system-type packages, the greeting serves as a game initialization message (e.g., "Welcome to D&D 5e! Let's create your character...").
User vs. Creator Experience
Packages are the primary solution to the user vs. creator experience split. They let creators absorb all the configuration complexity and ship a clean experience where:
- Model profiles ensure optimal per-model settings without user configuration
- Character types compose persona + rules + helpers into a single coherent experience
- Trackers are pre-configured with good extraction hints
- Journal profiles appear as polished character/location cards
- Evaluation settings are tuned to work with the package content
- The chat interface shows only what the user needs to see
- Advanced settings are either locked or hidden behind progressive disclosure
Chapters and Events
Overview
Packages can define chapters — named configuration overlays that activate during a conversation when an event fires. A chapter transition seamlessly shifts the "background" of the experience: different lorebooks become active, the system prompt gains new context, tracker values change, custom instructions shift — all without interrupting the conversation.
This enables story progression as a first-class feature. A mystery package can move from "Investigation" to "Confrontation" to "Resolution", each chapter surfacing different lorebook entries, different rules emphasis, and different narrative context. The user doesn't configure anything — the package creator pre-wires the progression, and tracker state drives the transitions.
Relationship to Conditional Entries
Conditional entries and chapters are complementary, operating at different granularities:
| Conditional Entries | Chapters | |
|---|---|---|
| Scope | Individual lorebook entry | Entire package configuration |
| Granularity | Fine — one entry appears/disappears | Coarse — lorebooks, prompt context, instructions all shift together |
| Activation | Continuous — re-evaluated every message | Discrete — fires once on transition |
| Use case | "Show Elara's secret when trust >= 7" | "Switch to Act 2 when the crystals are destroyed" |
| Reversibility | Naturally reversible (condition becomes false → entry disappears) | Directed by events (can go back if another event targets the previous chapter) |
Both are driven by tracker state. Within a chapter, conditional entries still gate individual lorebook entries. Chapters change which lorebooks are bound in the first place.
Chapter Entity
A chapter is a delta on the base package state — it only specifies what differs from the package defaults. Unspecified fields inherit from the base package.
Chapter
├── PackageId FK to parent package (NOT NULL)
├── Name "Act 2 — The Shadow King Awakens"
├── Description "The world shifts to a darker tone..."
├── SortOrder Display ordering in creator UI
├── IsStarting true = active when conversation begins (exactly one per package)
│
├── Overrides (all optional — null means inherit from base package)
│ ├── SystemPromptModifier TEXT appended to base system prompt
│ ├── CustomInstructions Replaces base package instructions
│ ├── SettingsOverrides Merged on top of base package settings
│ └── TrackerModifications JSON: tracker key → new value (applied on transition)
│
├── Lorebook Overrides
│ ├── LorebookBindings[] If present, replaces package-level bindings for this chapter
│ └── AdditiveLorebooks[] Additional lorebooks activated alongside base package bindings
│
├── TransitionMessage Narrative bridge shown when entering this chapter
│ (e.g., "As the crystals shatter, darkness sweeps across the land...")
│ Injected as a system message or the next AI response preamble
│
└── Timestamps
Design choice: delta vs. snapshot. Chapters are deltas (overrides only) rather than full snapshots of every package field. This means:
- Creators only specify what changes per chapter, not redundantly copying the base state
- Updates to the base package automatically apply to all chapters (unless overridden)
- A chapter with zero overrides is valid — it could exist purely as a named waypoint with a transition message
The IsStarting chapter is active when a conversation begins. If a package has no chapters, the entire chapter system is bypassed — the package works exactly as it does today with no overhead.
Event Entity
An event is a trigger + action pair owned by a package. When the trigger condition is met, the action executes.
Event
├── PackageId FK to parent package (NOT NULL)
├── Name "shadow_king_awakens"
├── Description "Fires when 3+ crystals have been destroyed"
│
├── Trigger
│ ├── Type 'tracker' | 'eval' | 'manual'
│ ├── TrackerKey (if tracker) which tracker to watch
│ ├── Operator (if tracker) 'equals' | 'gte' | 'lte' | 'contains' | 'not_contains'
│ ├── Value (if tracker) expected value or threshold
│ └── EvalPrompt (if eval) LLM prompt that returns true/false
│
├── Action
│ ├── Type 'chapter_transition' (primary, extensible later)
│ └── TargetChapterId FK to chapter
│
├── Constraints
│ ├── SourceChapterId (optional) only fires when in this chapter (null = any chapter)
│ ├── IsRepeatable can this event fire more than once? (default: false)
│ └── Cooldown (optional) minimum messages between re-fires
│
└── Timestamps
Trigger types:
| Type | How it fires | Use case |
|---|---|---|
tracker |
Tracker evaluation updates a value that matches the condition | "When story_arc changes to act_2" or "When crystals_destroyed >= 3" |
eval |
The evaluation LLM is given the event's EvalPrompt and the recent conversation context, returns true/false |
"When the player has discovered the traitor's identity" — fuzzy narrative conditions that can't be reduced to a tracker value |
manual |
Creator defines a trigger button visible in the chat UI (or the system can fire it via API) | "Start boss fight" button for the GM, or a debug/testing trigger |
Tracker triggers are evaluated after every tracker evaluation cycle. If the tracker update changes a value such that an event's condition transitions from false → true, the event fires. The event does NOT fire if the condition was already true before the update (prevents re-firing on every message).
Eval triggers run as part of the post-response evaluation cycle (alongside tracker extraction). They use the same evaluation LLM config (TrackerLlm). To avoid cost, eval triggers should only be checked when in the event's SourceChapterId (or always, if null). The eval prompt is kept short — the LLM gets the recent conversation context and a focused yes/no question.
Event Evaluation Flow
User sends message
↓
Story LLM streams response → user sees response immediately
↓
Response complete, stored in DB
↓
Post-response evaluation (async):
├── Tracker extraction → updated tracker values
├── Journal update (if enabled)
└── Event evaluation:
1. Filter events: only those in scope (current chapter matches SourceChapterId or SourceChapterId is null)
2. For each tracker-type event: check if condition is newly satisfied
3. For each eval-type event: send eval prompt to LLM, check result
4. First event that fires wins (priority by sort order if multiple fire simultaneously)
5. Execute action → chapter transition
6. Store event firing in conversation state
↓
UI updates: tracker sidebar refreshes, chapter transition message appears
Priority when multiple events fire: If tracker updates cause multiple events to fire in the same evaluation cycle, the event with the lowest sort order wins. The remaining events are not suppressed — they'll be re-evaluated on the next message. This prevents "skipping" chapters when the story moves fast.
Chapter Transition Mechanics
When a chapter transition fires:
- Conversation state updates:
current_chapter_idon the conversation record changes to the target chapter - Lorebook bindings shift: If the new chapter has
LorebookBindings, they replace the active set. If it only hasAdditiveLorebooks, those are added to the base bindings - System prompt modifier applies: The chapter's
SystemPromptModifieris appended to the base system prompt for all subsequent messages - Custom instructions swap: If the chapter specifies
CustomInstructions, they replace the current instructions - Tracker modifications apply: Any
TrackerModificationsare applied to current tracker values (e.g., setstory_arc = "act_2") - Transition message appears: If the chapter has a
TransitionMessage, it's injected into the conversation. Options:- As a system message between the current response and the next user message
- As a preamble to the next AI response
- As a standalone narrative beat (shown as a card/divider in the chat UI)
- Settings-default merge: New chapter defaults are merged on top of base package settings, but both layers use the same exact package-safe allowlist and canonical validation; a chapter cannot introduce
Generation.*,*Llm.*, secret, default/admin, or unknown keys
What does NOT change: Messages already sent, journal entries, tracker history. The chapter transition only affects future context injection. The conversation history is continuous — no "loading screen" or break.
Sticky and Locked Chapters (use case)
Some narratives need a point of no return — a chapter the story can enter but can't leave, or can only leave under tightly defined conditions. Examples:
- Failure / bad-end branch. The user mistreats a character past a threshold; the package transitions into a permanently hostile chapter. No event in that chapter targets a recovery — it's a one-way door. The conversation continues, but the tone is locked.
- Endgame / climax lock. Once the user reaches the final act, they shouldn't be able to drift back to slice-of-life pacing. The endgame chapter has no outbound events.
- Consequence chapters. A character dies, a city falls — the world state has changed and the previous chapters are no longer reachable.
This is achievable today with the existing model — there's nothing structurally new — but it's worth calling out so creators (and the editor UX) treat it as a first-class pattern:
- One-way doors are just a chapter that no event targets-out-of. The chapter timeline editor should make this readable at a glance (e.g. the chapter has no outbound arrows).
- Hard locks can be modeled by giving outbound events impossible conditions, or by simply not authoring any.
- Soft locks (recoverable but only via a specific event) compose naturally — e.g. an
evalevent "Has the player sincerely apologized?" gating the recovery transition.
Editor affordance to add later: a per-chapter IsTerminal flag that's purely a UX hint — the editor warns when an event targets a terminal chapter from somewhere it shouldn't be reachable, and visually marks terminal chapters in the timeline. Runtime behavior is unchanged; this just helps creators reason about flow.
Future: per-chapter reply formatting (deferred)
Some advanced character prompts force a strict per-turn output template — e.g. prose body, then an internal-monologue block, then a side-character commentary block, then a hidden state footer. This isn't a feature we're committing to, but if it ever lands, the natural home is here: a per-chapter (or per-package-base) ReplyTemplate setting that injects an output-shape directive into the system prompt. Deferred until there's clear demand — most creators express this kind of structure through prose conventions and tracker UI, and a formal schema risks fighting the model rather than guiding it.
Database Schema
-- Package chapters (configuration overlays)
CREATE TABLE package_chapters (
id SERIAL PRIMARY KEY,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
name VARCHAR(200) NOT NULL,
description TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
is_starting BOOLEAN NOT NULL DEFAULT FALSE,
-- Overrides (null = inherit from base package)
system_prompt_modifier TEXT,
custom_instructions TEXT,
settings_overrides_json TEXT, -- same exact package-safe allowlist as the parent package
tracker_modifications_json TEXT, -- JSON: { "story_arc": "act_2", "hp": 100 }
-- Transition
transition_message TEXT,
-- State
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Only one starting chapter per package
CREATE UNIQUE INDEX idx_package_chapters_starting
ON package_chapters(package_id) WHERE is_starting = TRUE AND NOT is_deleted;
-- Chapter-specific lorebook bindings (override package-level)
CREATE TABLE chapter_lorebook_bindings (
id SERIAL PRIMARY KEY,
chapter_id INTEGER NOT NULL REFERENCES package_chapters(id) ON DELETE CASCADE,
lorebook_id INTEGER NOT NULL REFERENCES lorebooks(id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
is_additive BOOLEAN NOT NULL DEFAULT FALSE, -- true = add to base, false = replace base
UNIQUE(chapter_id, lorebook_id)
);
-- Package events (trigger + action)
CREATE TABLE package_events (
id SERIAL PRIMARY KEY,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
name VARCHAR(100) NOT NULL,
description TEXT,
sort_order INTEGER NOT NULL DEFAULT 0,
-- Trigger
trigger_type VARCHAR(20) NOT NULL, -- 'tracker', 'eval', 'manual'
trigger_tracker_key VARCHAR(50), -- for tracker triggers
trigger_operator VARCHAR(20), -- 'equals', 'gte', 'lte', 'contains', 'not_contains'
trigger_value TEXT, -- expected value or threshold
trigger_eval_prompt TEXT, -- for eval triggers
-- Action
action_type VARCHAR(30) NOT NULL DEFAULT 'chapter_transition',
target_chapter_id INTEGER REFERENCES package_chapters(id) ON DELETE CASCADE,
-- Constraints
source_chapter_id INTEGER REFERENCES package_chapters(id) ON DELETE SET NULL,
is_repeatable BOOLEAN NOT NULL DEFAULT FALSE,
cooldown_messages INTEGER, -- minimum messages between re-fires
-- State
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Track chapter state on conversations
ALTER TABLE web_conversations
ADD COLUMN IF NOT EXISTS current_chapter_id INTEGER REFERENCES package_chapters(id) ON DELETE SET NULL;
-- Track which events have fired per conversation
CREATE TABLE conversation_event_log (
id SERIAL PRIMARY KEY,
conversation_id INTEGER NOT NULL REFERENCES web_conversations(id) ON DELETE CASCADE,
event_id INTEGER NOT NULL REFERENCES package_events(id) ON DELETE CASCADE,
fired_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
trigger_message_id INTEGER, -- which message's evaluation triggered this
from_chapter_id INTEGER, -- chapter before transition
to_chapter_id INTEGER -- chapter after transition
);
CREATE INDEX idx_conversation_event_log_conversation
ON conversation_event_log(conversation_id);
Example: A Three-Act Fantasy RPG
Package: "The Crystal of Dawn"
├── Base state:
│ ├── SystemPrompt: "Elara the Narrator" (fantasy narrator persona)
│ ├── Model Profile: "Fantasy RPG Models"
│ │ ├── sonnet → Base "Fantasy RPG Mode"
│ │ └── * → Base "Fantasy RPG Mode" (policy 1)
│ ├── Lorebooks: [World Geography, NPC Directory, Item Catalog]
│ ├── Trackers: [gametime, location, hp, roster, story_arc, crystals_destroyed]
│ └── Greeting: "You awaken in the village of Millhaven..."
│
├── Chapter 1: "The Gathering" (is_starting = true)
│ ├── AdditiveLorebooks: [Act 1 - Quest Hooks, Village of Millhaven]
│ ├── TrackerModifications: { story_arc: "act_1", crystals_destroyed: 0 }
│ └── No transition message (this is the starting state)
│
├── Chapter 2: "The Shadow War"
│ ├── SystemPromptModifier: "The tone is darker now. The Shadow King has awakened.
│ │ NPCs are fearful. Undead roam the wilderness between towns."
│ ├── AdditiveLorebooks: [Act 2 - Shadow King Lore, Undead Bestiary]
│ ├── TrackerModifications: { story_arc: "act_2" }
│ └── TransitionMessage: "As the third crystal shatters, a tremor shakes the earth.
│ The sky darkens to a sickly purple. In the distance, the spires of Shadowkeep
│ pulse with unholy light. The Shadow King has awakened."
│
├── Chapter 3: "The Final Dawn"
│ ├── SystemPromptModifier: "This is the climax. The stakes are ultimate.
│ │ Every NPC the player has befriended may appear to help or hinder."
│ ├── LorebookBindings: [World Geography, NPC Directory, Act 3 - Final Confrontation]
│ │ (replaces base — drops Item Catalog, adds Act 3 content)
│ ├── TrackerModifications: { story_arc: "act_3" }
│ └── TransitionMessage: "The Crystal of Dawn glows in your hands, warm as a sunrise.
│ The path to Shadowkeep lies open. There is no turning back."
│
├── Event: "shadow_king_awakens"
│ ├── Trigger: tracker "crystals_destroyed" >= 3
│ ├── Action: transition to Chapter 2
│ └── SourceChapter: Chapter 1 (only fires during Act 1)
│
├── Event: "crystal_of_dawn_found"
│ ├── Trigger: eval "Has the player obtained the Crystal of Dawn?"
│ ├── Action: transition to Chapter 3
│ └── SourceChapter: Chapter 2 (only fires during Act 2)
│
└── Event: "dm_override" (manual)
├── Trigger: manual (button in chat UI)
├── Action: transition to any chapter (target selected on trigger)
└── SourceChapter: null (available from any chapter)
UI Considerations
Creator Side (Forge):
- Chapter timeline/flowchart editor: visual representation of chapters and the events that connect them
- Per-chapter lorebook and override editors
- Event builder: select trigger type, configure condition, select target chapter
- Test mode: manually fire events to preview transitions
Chat Side:
- Subtle chapter indicator (current chapter name in conversation header or sidebar)
- Transition message appears as a narrative card/divider in the chat flow
- Manual event buttons (if any) in the chat controls
- Chapter history: user can see which chapters they've been through
No "chapter select" for users. Chapter transitions are driven by events, not user choice. The user experiences the story — the package controls the progression. If a creator wants user-driven chapter selection, they can use manual events with descriptive names.
Open Questions
Forking packages: Should users be able to "fork" a public package (copy all components into their own account for modification)? Powerful for derivative works, but raises attribution questions.
Component ownership: If a package references another creator's public system prompt, what happens if that system prompt becomes private? The package breaks. Options: snapshot components at package creation, or require all referenced components to be owned by the package creator.
Revenue / premium packages: Future consideration. Could packages have pricing tiers? Free to start, paid for "premium" content packs? Out of scope for initial implementation but worth considering in the data model.
Package templates: Should there be system-provided package templates ("RPG Template", "Mystery Template") that creators can start from? Reduces blank-page anxiety.
Multi-character packages:
Some experiences involve multiple characters (e.g., a group roleplay setting). Should packages support multiple characters with a selection screen? Or is that a separate "World" concept?Answered 2026-09-05: neither a selection screen nor a World — a cast on the package, with a roster tracker the story keeps. See package-cast.md.Package discovery: How does the Hub surface packages vs. individual characters/modes? Dedicated "Experiences" section? Mixed into the main feed with a filter?
Chapter transition messages: Should transition messages be injected as system messages (invisible to AI in future context?), as the AI's next response preamble (AI continues from there), or as a standalone narrative card (pure UI, not in conversation history)? Each has different implications for how the AI perceives the transition.
Eval trigger cost: Eval-type events require an LLM call per event per message. With many eval events, this adds up. Should eval triggers have a "check frequency" (every N messages) to reduce cost? Or should they only be evaluated when in the correct source chapter?
Chapter rollback: Can events target previous chapters (go back to Act 1)? This enables non-linear stories but complicates the "which lorebooks are active" question if chapters have replaced bindings. Should rollback re-apply the previous chapter's overrides cleanly?
Compound events: Should an event be able to trigger multiple actions (chapter transition + tracker modification + notification)? Or should actions stay simple (one event = one action) and compound effects be achieved through chapter overrides (the chapter applies tracker modifications on entry)?
Event chains: If a chapter transition causes tracker modifications, and those modifications satisfy another event's trigger, should that event fire immediately (cascade) or wait for the next message? Cascading is powerful but risks infinite loops. Waiting is safer but means multi-step transitions take multiple messages.
Acceptance Criteria
Scope note (2026-08-06). This document spans shipped substrate and multi-phase forward design (chapters, events, revenue, multi-character worlds). Only the shipped package save/lock contract gets boxes here — pinning criteria on unbuilt phases would turn vision into commitment, which is the opposite of what those sections are for. Each future phase writes its own criteria at its slice 0.
The criteria below exist mainly to keep the carve-outs from being traded away: the lock table now has honest per-row status, and the "what a lock cannot reach" boundary is a deliberate product decision that a future slice could erode without noticing.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
As a creator, I can lock the mode on my package and a reader of that package cannot switch it.Withdrawn:mode_lockedwas retired 2026-09-20 (dev decision — Model Profiles govern which mode runs); see the lock table.- As a creator, I can set my package's character / lorebook / tracker locks from the package builder — reachable without insider knowledge, and a lock whose status above is "not enforced" says so where it is set. (Currently ❌: no control exists — see Creator Side (Forge) → "Set locks per component", knowledge review 2026-09-29.)
- As a creator whose package carries a lock set outside the builder, I can still see it and clear it in the builder — a stored lock never silently blocks my own drops.
- As a reader in a fully locked package conversation, I can still set an Author's Note and still edit my own Custom Instructions.
Behavior:
Withdrawn with the retirement (2026-09-20). Replacement invariant: nothing readsmode_lockedrefuses a mode change on a package conversation server-side.mode_lockedto gate behaviour, and no creator surface offers to set it.-
lorebooks_lockedrefuses lorebook attach/detach on a package conversation server-side. -
character_lockedis honored by managed Discord bot instances. - Package save is one transaction: an unbindable component refuses the whole save rather than silently clearing the binding, and an unchanged cover/mode is never re-sent.
Invariants that must stay true (the carve-outs):
- Author's Notes are never package-lockable. No
author_note_lockedcolumn, no package check on the author-note route. A reader's ability to steer their own conversation survives every lock a creator can set. - Custom Instructions stay user-driven.
instructions_lockedremains permanentlyFALSEand absent from the request contract; a creator cannot re-acquire the ability to set it. - A lock that is not enforced is documented as not enforced.
trackers_lockedis readable in projections but must not be described as working until something acts on it. - Loosening a lock never breaks an existing conversation.
Edges:
- Setting
trackers_lockedhas no effect and is not reported to users as if it did. - A package conversation whose packaged character was deleted or made private degrades without destroying the conversation.
- A non-owner who guesses a conversation UUID gets the same not-found shape as a conversation that does not exist — no existence leak on the author-note route.