Package Cast β Supporting Characters and Who Is in the Scene
Status: β
C1 SHIPPED (2026-09-10, 93eee7954) β cast, roster, injection, page, credit and screening are live; the acceptance list below records what was exercised (UC-5 picker still open). β
C2 built (member lore, owner 2026-10-16; landed 2026-10-16, af701eeea). It also carries the rule
that a member's own lore resolves {{char}} to that member (Who {{char}} is in a member's lore). π§ C3 built, live check open (owner, 2026-10-16; M1, the field on the character, and M2, where the cast reads it, landed 2026-10-17 β 43e0020e5, 4eaa4af1d, 69aab405b, 3a76bb523; M2's live check and C3-T are not recorded as done):
- every character gets a cast profile, what the story knows about them, on stage or off;
- the package's prompt override is retired;
- the cast section splits into a stable block and a dynamic part.
C3-T closes the package changes with a check of every package tool. Delivery plan:
docs-internal/architecture/chat-engine/PACKAGE_CAST_C3_DELIVERY.md.
A package bundles one character, one mode, lorebooks, persona templates, trackers. It has never been able to bundle more than one character, and the stories it is built for β a party, a household, a crew, a court β are exactly the stories where it should. This doc gives a package a cast: a set of supporting characters the primary character shares the scene with, and a roster the story keeps up to date so the model always knows who is in the room.
It replaces the "Character Groups" design in trackers.md,
which parked the cast in a standalone character_groups entity because, when it was
written, nothing else could hold one. A package can now.
Overview
A creator building an adventure has a protagonist (the package's character), a narrator mode, and a world in lorebooks. The companions, rivals and recurring NPCs of that world are today either squeezed into the protagonist's system prompt (every companion, every message, whether or not they are on stage) or written twice β once as a Character the creator already made, once again as a lorebook entry so keyword search can surface it. Both are lossy: the first spends tokens on absent characters and dilutes the protagonist's own voice; the second forgets whoever has not been mentioned in the last few messages and puts a maintenance burden on the creator.
The cast fixes this with two ideas from the tracker design:
- Presence-aware injection. Each cast member is a real Character the creator already has. A member who is present in the scene gets their full card in the prompt; a member who is absent gets a one-line reminder that they exist. The model writes the people on stage accurately and still knows who might walk in.
- The roster is a tracker. "Who is present" is story state, so it is kept the way all story state is kept: a list-type tracker, evaluated after every assistant turn by the separate eval call, shown in the story-state bar, editable inline by the reader. Its allowed values are the cast members' names. The creator writes nothing to get it β a package with a cast has a roster.
The primary character stays the single speaker. This is a cast, not a group chat: the model plays the scene through the package's character (or its narrator), with the cast as the people in it. Per-message speaker selection is a different, much larger feature and is a non-goal here.
What already exists (and is reused as-is)
The feature is assembled from substrate that shipped in the tracker and package work of 2026-09; nothing below is rebuilt.
| Need | Existing piece |
|---|---|
| A tracker the eval maintains, the bar renders, the reader can edit | Phase-1 trackers: per-message web_messages.tracker_json snapshots, TrackerEvalStageBase, WebTrackerHistoryInjector, TrackerBar |
| A list tracker whose allowed values are names and whose current items pin content | T1: TrackerValueFormatter.DescribeType / TryNormalize for linked lists, WebTrackerPinnedKnowledgeSource reading the latest snapshot |
| "Which trackers are active on this conversation" | P1: ConversationTrackerSetResolver (character βͺ package, deduped by key, renumbered) β every consumer already reads it |
| Package components staged in the builder and saved as a set | The lorebook / tracker steps: fn_save_package_full + a fn_sync_package_* full-replacement function, the workbench draft, useStepStates, BuilderStepCard, DetailPanel |
| Bundling someone else's character with credit | fn_save_package_full's character bind gate, fn_package_co_creator_count, package_contribution_view, the contributors strip |
| Screening a private component that a public package exposes | The linked-entity fan-out in fn_run_publish_request_checks |
| A mode that omits a section still gets it | SystemPromptBuilder.AppendJournalFallback |
| A character rendered as prompt text | CharacterContentProvider (first person, primary only) and IPersona.ToFormattedCard() (the "state facts, don't shout directives" craft note) |
Design Goals
- Reuse the character. A cast member is a Character. Its prompt, avatar, lorebooks and creator credit come from the character row; the package adds only what is specific to this story's framing of it.
- Zero-setup roster. The creator adds cast members; the roster exists. No tracker to create, name, type, bind, or keep in sync. The only knob is the eval hint.
- Presence decides cost. Tokens go to the people in the scene. Absent members cost one line each. (C3: every member also carries their cast profile, present or not. That's the price of the model never inventing an offstage character's hair colour. Present members still add their full card on top.)
- Same rails, no forks. The roster is an ordinary tracker to every consumer β eval, injector, bar, inline edit, summary timeline, pinned knowledge. Nothing downstream learns a new shape.
- Authorization by precedent. Adding a cast member follows the same rule as binding the package's own character; injecting cast prompts into a package conversation follows the same transitive-grant rule package lorebooks already use.
- The cast is configuration, read live. Like package trackers (and unlike package lorebooks, which are copied into a conversation at creation), editing the cast changes the next turn of every conversation started from the package.
Non-Goals
Deliberately out of scope:
- Multiple speakers.
web_conversations.character_idstaysNOT NULLand singular. No per-message speaker id, no "who answers this turn" selection, no per-member voice routing. A narrator or game-master primary plus a cast already gives "the model plays whoever is present"; anything beyond that is a separate spec. - A cast on a character (owner types other than package). The roster belongs to the experience, and the experience is the package. If a character-level cast is ever wanted, the resolver's cast leg is owner-generic by construction β but it is not built.
- A standalone
character_groupsentity. Superseded by this doc. - Reader-side cast editing. Readers see and edit the roster (who is present); they do not add or remove cast members from a conversation. That would be a T2-shaped conversation-owner surface and is not planned.
- The always-on token budget cap from the original design (
MaxAlwaysOnSummaryTokens). The summary field is capped at 200 characters and the cast at a small number of members; a token budget is only worth building if real casts outgrow that. (C3: the cast profile makes every member always-on, up to 10,000 characters each. The context budget prices it and the trimmer gives it up before the summary; a budget of its own is still C4.) - Discord. Trackers are web-only in Phase 1; so is the cast.
- Lorebook-based rosters (a list tracker linked to an "NPC directory" lorebook). Already possible since T1 and unchanged; the two coexist as the original design intended.
The Shape
Data model
-- database/v1/21_tables_packages.sql (new block)
CREATE TABLE IF NOT EXISTS package_cast_members (
id SERIAL PRIMARY KEY,
package_id INTEGER NOT NULL REFERENCES packages(id) ON DELETE CASCADE,
character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
always_on_summary VARCHAR(200) NOT NULL DEFAULT '',
override_system_prompt TEXT,
present_at_start BOOLEAN NOT NULL DEFAULT TRUE,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (package_id, character_id)
);
CREATE INDEX IF NOT EXISTS idx_package_cast_members_character ON package_cast_members(character_id);
ALTER TABLE packages ADD COLUMN IF NOT EXISTS cast_extraction_hint TEXT;
always_on_summaryβ the one-liner the model sees when the member is absent. Lives on the membership, not the character: "Elara β ranger companion, distrustful of outsiders" is a role in this story, not a fact about Elara. (C3: the member's role in this story, shown next to their name for every member, present or not. Same column, same 200 characters, same meaning.)override_system_promptβ optional. When set it replaces the character's own system prompt in the present-card; when null the character's prompt is used as-is. Exists because a solo prompt ("You are Elaraβ¦") often needs reframing as a supporting role. (C3: retired. Nothing reads or writes it; the column stays as a schema shell until a later cleanup push. The character's own cast profile covers what it was for.)present_at_startβ seeds the roster's initial value. The party that opens the story is on stage from the first message; the villain is not.packages.cast_extraction_hintβ the roster's eval hint. Nullable; the built-in default reads "Track which cast members are actively present in the scene. Add a member when they appear or are introduced; remove them when they leave or the scene moves somewhere they are not."- Both FKs cascade. Characters and packages soft-delete on the product path, so the
cascades only fire on the user-deletion hard path β the same shape as
packages.character_id. Every read filtersNOT c.is_deletedandNOT p.is_deleteditself; a soft-deleted member simply drops out of the cast, the roster's allowed values and the prompt. Its name may linger in an older snapshot: the provider ignores names it cannot match, the bar shows the chip as plain text, the inline editor cannot re-select it, and the next eval answer is normalised against the current names so it drops out. - The primary character is not a cast member.
fn_save_package_fullrefuses a cast array containing the package's character.
The roster is synthesised, not stored
The roster is not a trackers row. ConversationTrackerSetResolver gains a third leg
that, when the conversation's package has at least one live cast member, synthesises an
ActiveTrackerDefinition:
| Field | Value |
|---|---|
Key |
cast |
Name |
"Cast" |
ValueType |
4 (list) |
EnumValues |
JSON array of the live members' story names (COALESCE(NULLIF(btrim(char_name),''), name)), in sort_order |
InitialValue |
JSON array of the members with present_at_start, same order |
ExtractionHint |
packages.cast_extraction_hint or the built-in default |
InjectionMode / IsVisible |
0 (full) / true |
SortOrder |
0 β it leads the union; character and package trackers renumber after it |
One substrate fix rides along: TrackerValueFormatter.TryNormalize rejects an empty
list for every list tracker today (zero items after filtering β "skip, carry the prior
value forward"), so no list tracker can ever be emptied by the eval and the last cast
member could never leave. The list arm now distinguishes decoded to zero items (a legal
answer: the list is empty, normalised to []) from decoded to items none of which are
allowed (still rejected, prior value kept). Blank raw text stays rejected. The same rule
lives one step earlier in TrackerEvalParser, which used to drop an empty JSON array before
the formatter saw it (found live on the probe: the eval answered [] and the snapshot carried
the prior value with neither an update nor a skip counted) β an empty array now reaches the
apply step as the canonical [], while blank text is still "no change". The reader could
already empty a list from the bar; the eval now can too.
Everything downstream is unchanged: the eval renders the list instruction from
EnumValues and canonicalises answers against it, the injector writes the OOC line, the
bar renders chips with a picker over the names, inline edit validates against the union,
the summary timeline folds it. WebChatEntryPoint.HasBoundTrackers asks a third question
("does the package have a cast?") so the eval's compute reserve is metered for a
cast-only package exactly as for a tracker-only one.
Why not a real tracker row. Materialising one hits four traps the tracker substrate
already documents: idx_trackers_owner_key is unique per (owner, key), so a creator's
second package cannot also own cast; fn_sync_package_tracker_bindings is a client-driven
full replacement, so an auto-bound row is deleted on the next save unless injected
server-side; a generated row must then be hidden from the Forge list, the assistant's pool,
the bind pickers, sharing, publishing and entity references β seven exclusion lists; and
packages soft-delete, so "dies with the package" becomes a liveness predicate on every read
anyway. A synthesised definition has none of these and is exactly what every consumer
already accepts.
The cast key is reserved while a package has a cast. The roster leads the union and
DedupeByKey keeps the first definition, so a creator's own tracker keyed cast on the
character or the package is shadowed for conversations started from that package. The
builder's Story State step says so on the read-only roster row.
Prompt injection
A new WebChat provider, WebCastContentProvider, keyed cast (added to ContextKeys and
PromptKeyCatalog with IsDynamic: true and SacrificeRank: 4, the same rung as journal β
lowest rank is trimmed first and ties break by size, so an oversized cast is trimmed before
the story's summary and, being the bigger block, before a small journal). Per turn it:
- Returns
""unless the conversation is web, has a package with live cast members, and trackers are on (Features.EnableTrackers). - Reads the latest
castvalue from the previous snapshot (GetLatestTrackerJsonAsync, the same read the pinned-knowledge source makes), falling back to the roster's initial value; decodes the list; matches items to members by story name, case-insensitively. - Renders, in cast
sort_order:
Other characters in this scene, written by the narrator, never the reader:
### Elara
<override_system_prompt, or the character's system prompt>
### Grimjaw
<β¦>
Also in this world, not present right now:
- The Shadow King β ancient lich ruling Shadowkeep.
Details that matter:
- A member's prompt is rendered with
{{char}}replaced by that member's own story name before the provider returns, because the global placeholder pass would otherwise rewrite every cast prompt to the primary character.{{user}}is left for the global pass. - Names use
ICharacter.Name(thechar_nameCOALESCE), neverDisplayNameβ the same rule the primary card follows. - Present members with an empty summary and absent members with an empty summary render as the bare name line.
- No present, no absent β
""(the section is skipped).
SystemPromptBuilder gains a cast fallback section, AppendJournalFallback generalised
into AppendFallbackSection(sections, key, template) so journal and cast share one
implementation (rule of two), applied sequentially over the growing list so the two
fallbacks do not tie on sort order: when the mode declares no cast subprompt and no inline
{{cast}} token, a section is appended after the mode's own with the template
"{content}". The fallback only runs on the has-subprompts branch, so DefaultSections
(the no-mode / zero-subprompt path) gains a Cast entry at order 175 (after journal,
before lorebook) β and DefaultProviderKeys, mirrored by WebChatFeatureStateService
for the HowDrawer, widens with it. Without the catalog entry the section would be treated as
static and poison prefix caching; the catalog entry is required for that reason, not for
provider lookup. A creator who wants to frame the cast writes a cast subprompt in their
mode; a mode that does not is not a reason for the cast to vanish (the trackers / journal
rule: not mode-gated, soft UI note only).
Package save, edit read, and the gate
fn_save_package_full gains p_cast JSONB DEFAULT NULL and
p_cast_extraction_hint TEXT DEFAULT NULL. The hint is three-state β absent = keep,
'' = clear to NULL, value = set β which the function's other text columns are not
(they are two-state COALESCE), so it is written explicitly:
cast_extraction_hint = CASE WHEN p_cast_extraction_hint IS NULL THEN packages.cast_extraction_hint WHEN btrim(p_cast_extraction_hint) = '' THEN NULL ELSE p_cast_extraction_hint END.
The roster reads NULLIF(btrim(cast_extraction_hint), '') and falls back to the built-in
default. p_cast is an array of
{ "characterId": uuid, "alwaysOnSummary": text, "presentAtStart": bool }
(C1 also carried "overrideSystemPrompt"; C3 retired it, and a payload that still sends it is ignored)
in display order; NULL or [] = no cast. It is resolved with the primary character's
own bind rule, verbatim from the existing gate:
owned by the package owner, OR
is_public, OR shared into this project viaproject_items, OR already a cast member of this package (the anti-wedge prong).
The tracker rule (owner-only) is deliberately not used: it exists to match the character tracker bind surface, and the corresponding surface for characters is this gate. A supporting character must not be harder to add than the protagonist, and bundling another creator's public character with credit is the documented package composition story.
The array goes through a shape guard (every element names a uuid, or the whole save is a
shaped refusal), is deduped first-occurrence-wins on the lower-cased uuid, capped at
8 members (cheap check first), resolved with an arity check (supplied β resolved β
RAISE, nothing written), refused if it contains the package's character, and refused if two
members β or a member and the package's character β share a story name case-insensitively.
The cap is (a constant in fn_save_package_full mirrored by PackageCast.MaxMembers
in Core β promoted to a default_settings key only if a real cast ever needs more; the
tracker cap is a setting because that setting already existed), then synced by
fn_sync_package_cast_members(p_package_id, p_cast JSONB) β a full replacement in array
order under pg_advisory_xact_lock(hashtext('package_cast'), p_package_id), with
ON CONFLICT (package_id, character_id) DO UPDATE on the three per-member fields and
sort_order. Refusals β every raise text starts with Cast so none collides with the tracker arm's
A package can carry at most prefix in MapSaveRefusal (which string-matches prefixes in
order; an unmapped raise is a deliberate logged 500, so all three need their own arm):
'Cast member % not found or not bindable by user %' β cast_not_bindable (403);
'Cast can carry at most % members (% supplied)' β cast_limit_reached (422);
'Cast cannot include the package character' β cast_includes_character (422). All roll
the whole save back.
fn_get_package_for_edit returns cast JSONB (uuid, always-on summary, present at start and,
since C3, hasCastProfile in place of the override; in sort_order, live characters only) and
cast_extraction_hint.
Like every other package set, the save is a full replacement: a caller that omits
cast clears it. The agent lane only ever creates packages through this function
(ComposerProposalApplier.Creations, packageUuid: null) and stages no cast; its
idempotency retry re-enters the create branch, lands on the existing package through
ON CONFLICT (idempotency_key), and the unconditional syncs then run with empty arrays β
the cast inherits exactly the behaviour trackers, persona templates and model profiles
already have on that path, nothing new.
Wire contract (pinned so frontend and backend build to it concurrently)
C3:
overrideSystemPromptleaves both directions, andcast_override_too_longis retired.- The edit read's members gain
hasCastProfile. - The character endpoints gain
castProfile.
The C3 contract is in its delivery plan, Β§3.
// Save (POST /api/creator/projects/{p}/packages) β additive fields on SavePackageRequest
cast?: {
characterId: string // character uuid
alwaysOnSummary: string // β€ 200 chars, may be ""
overrideSystemPrompt: string | null
presentAtStart: boolean
}[] // omitted or [] = no cast (full replacement, display order)
castExtractionHint?: string // omitted = keep, "" = clear, value = set
// Edit read (GET β¦/packages/{id}) β additive fields on PackageEditResponse
cast: {
characterId: string
alwaysOnSummary: string
overrideSystemPrompt: string | null
presentAtStart: boolean
}[] // binding order, live characters only
castExtractionHint: string | null
// Public details (GET /api/browse/packages/{id}/details) β additive on PackageDetailResponse
cast: LinkedPackageCastMemberOverview[]
interface LinkedPackageCastMemberOverview { // mirrors BrowseModels.cs
id: string // character uuid
name: string // display name
description: string | null
pictureUrl: string | null // avatar
pictureContentRating: number | null
pictureModerationStatus: number | null
pictureContentType: string | null
characterType: string
isPublic: boolean
}
// Chat β no new endpoint; GET /api/conversations/{id}/trackers returns the roster as
// ConversationTrackerDto { key: "cast", name: "Cast", valueType: 4, enumValues: "[β¦]", sortOrder: 0, β¦ }
// Refusal codes on the save (existing { error, code } envelope):
// cast_not_bindable (403) Β· cast_limit_reached (422) Β· cast_includes_character (422)
// cast_duplicate_name (422) Β· cast_payload_invalid (400: a null element, a non-array,
// or a raw array over 4Γ the cap) Β· cast_summary_too_long / cast_override_too_long /
// cast_hint_too_long (400)
SQL: fn_save_package_full(..., p_cast JSONB DEFAULT NULL, p_cast_extraction_hint TEXT DEFAULT NULL),
fn_sync_package_cast_members(p_package_id INTEGER, p_cast JSONB), and
fn_get_package_for_edit returning cast JSONB + cast_extraction_hint TEXT. The pipeline
read is one repository method, IPackageCastRepository.GetForPromptAsync(packageId, readerUserId) β
PackageCastMemberForPrompt(CharacterId, StoryName, SystemPrompt, CastProfile, AlwaysOnSummary, PresentAtStart, SortOrder, ReaderOwnsCharacter, ReaderOwnsPackage)
for live members of a live package (C3: the character's CastProfile sits where C1's OverrideSystemPrompt was), plus
HasCastAsync(packageId).
Builder (workbench)
A Cast step on every system preset (
package_presets.steps_json, seeded in28_tables_package_presets.sqlβ the builder's steps come from the DB seed, not the frontend config), placed right after the character step:{ "entityType": "cast", "required": false, "multiple": true, "label": "Cast", "hint": "Supporting characters who share the scene β companions, rivals, the people of this world" }.castis not a project item type, so the step key widens fromProjectItemTypeto aPresetStepKindsuperset andgetStepAcceptedTypes(the stub left for exactly this) answers['character']for it;ITEM_TYPE_CONFIGgains acastentry. The seed's upsert lands the new step on every existing database the moment the migration runs, soBuilderStepCardanduseStepStatesskip a step kind they do not recognise instead of throwing β a stale client bundle must degrade, not crash. The picker draws from the same pool as the character step (the creator's own characters merged with the project's) and filters out the primary character and members already in the cast β new filtering, the picker has none today.Each cast row opens a detail panel with three fields: When they're offstage (the always-on summary, 200 chars with a counter, description explaining the model sees this line when the member is absent), How they're written in this story (the optional override, with the character's own prompt shown read-only as the default), and On stage from the start (toggle). (C3: two fields:
- Role in this story (the same 200 chars);
- On stage from the start.
The override field is gone. The row shows whether the member's character has a cast profile, and links to that character's editor when the creator can edit it.)
A step-level field, How the story tracks who's present (the eval hint, optional, with the built-in default as placeholder).
The Story State step shows a read-only Cast β automatic row when the cast is non-empty ("Kept by the story from the Cast step; a tracker keyed
castis shadowed while this package has a cast"). It cannot be removed there.Package Check reports the cast as assigned / empty like the other optional steps.
The draft carries
cast: PackageCastMember[]andcastExtractionHint, hydrated from the edit read, restored on cancel, cleared on package switch; the save sends the cast whole on every save (a full-replacement set, like lorebooks and trackers) and the hint only when it changed (three-state), trimmed on both sides of the compare.
Public package page and credit
GET /api/browse/packages/{id}/detailsreturnscast: LinkedPackageCastMemberOverview[](uuid, display name, avatar url + its three moderation fields, character type,isPublic, the character's public description). Listed unconditionally like lorebooks and trackers β the viewer sees what is inside the experience β with the click-through gated onisPublic. The always-on summary and the override are not returned: they are prompt material.PackageDetailContentrenders a Cast section (avatar rows, the sameComponentRowthe primary character uses) between the character row and the linked lorebooks.fn_package_co_creator_countandpackage_contribution_viewgain a cast arm. The existingPackageCoCreatorCountTestscompare the two derivations in only one case, so a new case binds a third party's character as a cast member and asserts the view count equals the contributors list length; a cast member's creator is credited like the primary character's β named when any of their contributions is public, otherwise counted and role-worded through the existingfn_package_contributorsmasking.
Moderation
C3:
- The override arms leave every screener: text that never reaches a model isn't screened.
- The offstage line is labelled "Cast role".
- The character's cast profile is screened as the character's own prompt text, wherever the system prompt is.
The cast adds package-owned prompt text β each member's override prompt and offstage
line, and the package's eval hint β that no existing screener reads. It is screened as the
package's own content, the way a tracker's extraction hint and a persona template's prompt
are: a new fn_check_package_cast_content(p_package_id) returns those fields (prompt area,
field_id = the membership row) and the package own-field block of
fn_run_publish_request_checks calls it; the verified-creator auto-publish path scans each
cast field with its own keyword call (never one concatenated string β the scanner truncates at
100k characters and a concatenation of eight capped overrides can exceed it) and its oversized
content gate covers the override; PublishRequestFieldLoader's package branch loads the same
fields for the AI ladder; and EntityContentExtractionService labels them so a moderator
can read the text behind a flag.
fn_run_publish_request_checks' linked-entity fan-out gains a cast arm: every
non-public, non-deleted cast character is screened when the package is submitted, attributed
to the character, exactly as the primary character is today. The C# twin of that fan-out
(AdminPublishRequestRepository.AdminGetLinkedEntitiesToScreenAsync, which feeds the AI
ladder and the prefilter) gains the same two arms, and ContentCheckEntityBits gains a
tracker bit so the tracker arm is not dead on arrival. The fan-out has a
pre-existing gap for package trackers β no entity_tracker_bindings owner_type = 6 arm β
and closing it is more than one UNION ALL: the fan-out dispatches through
fn_check_entity_content, which knows five entity types and has no tracker checker. Closed
in the same change as three explicit items: a new fn_check_tracker_content (name and
description in the display area, extraction hint and initial value in the prompt area), the
entity_type('tracker') dispatch arm in fn_check_entity_content (which also makes a
tracker's own publish request screened β correct, and new), and the fan-out arm over
non-public bound trackers.
Authorization at conversation start
None new. fn_create_conversation_from_package already treats the package as the grant:
it checks the package is public or the caller's, and binds package lorebooks with no
reader-side check. Cast prompts are injected under the same rule. Prompt secrecy rests on
the creator-surface can_view gates, never on which context the LLM call is dressed in.
Build notes (found by the adversary pass, so the builders do not rediscover them)
ConversationTrackerSetResolver.UnionAsyncis static and takes only the tracker repository; the cast leg adds the cast repository to both the static signature and the ctor, which touches four WebChat test constructions and the conversations endpoint that calls the static directly.WebChatEntryPointcomputesHasBoundTrackersfrom two repository calls; the third (HasCastAsync) is a new ctor dependency.SavePackageFullAsyncgains two parameters beforect; the endpoint tests set the mock up positionally (It.IsAnyΓ 30,Arguments[27]/[28]) and every setup shifts.fn_get_package_for_editchanges its return shape βDROP FUNCTIONfirst; thefn_save_package_fulloverload sweep is already in place.PromptKeyCatalog.SacrificeRankladder is consecutive (Facts 1 β¦ Summary 5); cast takes 4.fn_create_conversation_from_packagechecks the primary character's existence withoutis_deletedβ pre-existing; the cast read must not inherit it.
Slices
C1 β Cast, roster, injection, page, credit, screening β SHIPPED 2026-09-10
Everything above except presence-gated lorebooks. Ships as one change.
C2 β Presence-gated lorebooks π
Delivery plan (ready, 2026-10-16): docs-internal/architecture/chat-engine/PACKAGE_CAST_C2_DELIVERY.md β the
lanes, the contracts, the shapes that change, the live check and the expanded acceptance list.
Present members' own character_lorebook_bindings join the knowledge search for that
turn; absent members' do not. The seam is a Core interface ICastKnowledgeSource, sibling
to ITrackerPinnedKnowledgeSource, consumed by LorebookContentProvider and implemented in
WebChat: read the present set (same snapshot read as the provider), resolve the members'
lorebook ids (a narrow SELECT lorebook_id FROM character_lorebook_bindings WHERE character_id = ANY(...)), and run the existing explicit-id methods
(GetAlwaysIncludeByLorebookIdsAsync, SearchByLorebookIdsAsync) against ids not
already in the conversation's resolved set; merge into the search lane under the normal
budget with a cast activation leg. fn_get_conversation_lorebook_ids is not extended β
it is static per-conversation SQL with five call sites and no per-turn input.
Edge rules carried from the original design: a lorebook bound to the conversation or the
primary character stays active regardless of presence; two present members sharing a
lorebook search it once; the member's lorebooks are searched, never always-included
wholesale. One thing the substrate settles in advance: the conversation's bound lorebook
ids reach fn_search_lorebook as an unordered set (09_tables_bindings.sql says so β
binding priority is display order, not a retrieval weight), so "cast lorebooks rank below the
protagonist's" cannot be expressed by ordering. If C2 wants that precedence it is a separate
search call with its own budget lane, decided before C2 starts, not after.
Who {{char}} is in a member's lore (owner, 2026-10-16)
"it also needs to check the linked lorebooks if they are in that character linked and use
{{char}}to use that linked character" β the owner, 2026-10-16. C2 is the package cast's next phase.
Today (verified 2026-10-16, at 73498381b):
- Member lorebooks aren't read. No entry from a member's own lorebook reaches the prompt.
fn_get_conversation_lorebook_ids(17_get_conversation_lorebook_ids.sql:20-53) unions the conversation's binds (the package's lorebooks are copied there at start), the primary'scharacter_lorebook_bindingsand the persona's lorebooks, and nothing reads a member's bindings. - No owner on an entry. A
LorebookSearchResultcarries its lorebook, never a character, so the content provider cannot tell whose lore an entry is. - The lead's name everywhere. Every lorebook entry's
{{char}}, whatever lorebook it came from, is filled by the global placeholder pass (PromptContextManager.cs:391-397) with the conversation's character, the primary's story name.
The rule C2 builds:
- A member's lore speaks as that member. An entry that reaches the prompt because a present
member's character binds its lorebook resolves
{{char}}(any letter case) to that member's story name. That covers the entry's content and its## Nameheader.{{user}}stays the reader's persona or name, left to the global pass. - Everything else stays the primary. Lore that reaches the prompt through the conversation,
the package, the primary or the persona keeps
{{char}}= the primary. That's C2's existing edge rule (a lorebook bound to the conversation or the primary stays active regardless of presence), and the data can't say which member such lore is about. - Two members sharing a lorebook (open, owner to confirm). The lorebook is searched once, as
C2 already says, and its entries resolve
{{char}}to the first of those members in cast order. - Absent members. Their lorebooks aren't searched (C2's presence rule), so their lore can't resolve to anyone.
How: mirror the cast card fill.
- Tag the owner.
ICastKnowledgeSourcereturns its entries tagged with the owning member'sCharacterIdandStoryName, fromPackageCastMemberForPrompt. - Resolve before formatting.
LorebookContentProviderresolves each tagged entry's{{char}}withPlaceholders.Fill(text, member.StoryName, userName: null), the same call asWebCastContentProvider.ResolveOwnPlaceholders(WebCastContentProvider.cs:246-250). It happens beforeFormatEntries(LorebookContentProvider.cs:385) and before the hidden-text record. - The leak guard sees what the model read.
ViewerHiddenLorebookTextrecords the resolved text, as the cast provider does (WebCastContentProvider.cs:201-210). Today it records raw content (ViewerHiddenLorebookText.cs:75-76), and the scanner refills it with the primary's name (PromptLeakScanner.cs:663-679). A member-resolved entry would then be guarded only in a form the model never saw.PromptLeakDetectionStageTests.cs:2453-2477encodes the primary-name assumption and changes with this.
The other readers C2 has to keep consistent:
- The
castactivation leg:BuildLegs(LorebookContentProvider.cs:510-524) has none today. - The embedding gate:
HasLorebookEntries(WebTurnContextResolver.cs:99) counts only the conversation's resolved set. The SFW guard's lore screening (Not a consumer. Owner, 2026-10-16: "keep SfwGuardStage as it is β creator lore isn't treated as unsafe reader input (the 2026-10-07 rule); replace the spec line." Creator content is trusted (CHAT_SFW_MODE Β§0, 2026-10-07), so the A32 re-check is not widened.SfwGuardStage.cs:245).- The turn-cost estimate:
ConversationBrowseRepository.cs:479-490counts only the resolved set. The release-date check at story start (Not widened (director, 2026-10-16; PACKAGE_CAST_C2_DELIVERY.md D10): it keeps checking the cast's characters and the primary's lorebooks. A member's lorebook is read turn by turn, so the per-turn embargo below withholds a dated one until its date β which keeps the 2026-09-24 rule β while a start check would let any member's creator hold a public package shut for every reader.47_package_functions.sql:600-649).- The per-turn embargo (
fn_character_part_admits), which the narrow member SELECT must apply as the primary's lorebook read does (17:44). - Hybrid: every leg builds through
PromptContextManager, so it inherits the fill. A leg only searches lore if its mode declares a lorebook section.
C3 β The cast profile π§
Delivery plan (ready, 2026-10-16): docs-internal/architecture/chat-engine/PACKAGE_CAST_C3_DELIVERY.md. It holds the
contracts, the shapes that change, the milestones, the overlap with C2, the live check and the expanded acceptance list.
"The offstage line needs to contain appearance and public perception. It can't happen that the model suddenly gives an offstage character blond hair when it's a dark haired one. It needs to have enough information to be able to TALK about that character." β the owner, 2026-10-16.
C1 told the model one line about an offstage member, and that line belonged to the package. A one-liner can't carry a face, a reputation and enough history to talk about someone. And what a character looks like isn't the package's to say twice in two packages. C3 moves that knowledge onto the character and makes the cast section say it every turn.
The character's cast profile
Every character has a cast profile: what the story knows about them while they're part of a cast, on stage or off. What they look like, how people see them, enough for the model to talk about them. It is used only when the character is a member of a package's cast; a character's own conversations never read it.
- Where it lives:
characters.cast_profile, up to 10,000 characters, empty by default. - How saves treat it: three-state like the description (omitted = keep,
""= clear, a value = set). - Where it's edited: in both character editors, in a collapsed In a cast section with a character and token count. The copy says plainly that most characters need a paragraph or two. The room is there for the few that need more (owner: "keep the option of 10k while giving the acknowledgement that it's not ideal to use it all").
- The same rules as the system prompt:
- editable by whoever can edit the character;
- proposable by contributors;
- draftable by the Workbench assistant;
- exported and imported with the character;
- screened at publish as the character's prompt text;
- counted as content for the character's "Updated" date;
- never shown on a reader surface (public character pages, the anonymous card, browse, the package page, previews and profile pages).
The package's prompt override is retired
package_cast_members.override_system_prompt stops being read or written. A present member's card is always their own
system prompt. The editor field, the wire field, the length check and its screening go. An override saved before C3 never
reaches a prompt again. The column stays as a schema shell (the SubscribeStar precedent: retire the code, keep the data);
dropping it is a later cleanup push.
The 200-character always_on_summary stays, as the member's role in this story: "ranger companion, distrustful of
outsiders". It is the package's own word on this member, so it stays on the membership. It keeps its column, its wire
name and its meaning; what changes is that it now shows for every member, next to their name.
The cast section in two pieces
"Once we do caching, we can keep the offstage cached and then just add the cast details when we need." β the owner, 2026-10-16.
The section splits by how often each part changes:
| Piece | Key | What it holds | Changes when |
|---|---|---|---|
| Stable block | cast_profiles |
Every live member, in cast order, present or not: ### Name β role, then their cast profile |
A creator edits the cast, a member's role, profile or story name, or removes a member. Never because of the turn or the roster. |
| Dynamic part | cast |
Who is in the scene now, and each present member's card (their own system prompt) | Someone enters or leaves |
In the prompt the dynamic part comes first and the stable block right after it:
Other characters in this scene, written by the narrator, never the reader:
### Elara
<Elara's system prompt>
Everyone else in the cast is elsewhere right now.
The story's supporting cast β who they are, whether or not they are in the scene:
### Elara β ranger companion, distrustful of outsiders
Tall, dark-haired, a scar through her left eyebrow. The river towns know her as the ranger who never takes payment.
### Grimjaw
### The Shadow King β ancient lich ruling Shadowkeep
Gaunt, crowned in iron. Peasants won't say his name.
- Byte-stable. The stable block is the same bytes from turn to turn while the cast doesn't change. Its provider never reads the roster, so a member walking off moves nothing in it.
- A present member appears in both: their profile in the stable block, their system prompt in the dynamic part. That's accepted: the profile is what the world knows, the card is how they act.
- Empty fields: with no profile the member's header shows the role; with neither it is the bare name. An empty stage says No one from the cast is in the scene right now.
- Placeholders:
{{char}}in a role or profile is that member's story name, in any letter case.{{user}}is the reader's persona, as everywhere. - Placement: the stable block comes right after the dynamic part. In the built-in layout it sits at order 180, after
castat 175. In a mode without the key it's the engine's fallback after the mode's own sections and after the cast fallback. The engine never puts it ahead of the per-turncastsection, which is what keeps every cache boundary where it is. A mode can place it with acast_profilessection. - Stability. The stable block is declared
Static, the same class as the character card. No cache boundary moves in C3. Since C5 S2 the built-in layout puts it at order 60, after the scenario, so it is cached with the character (Q1). - Cost.
- The context budget shows the stable block as its own Cast profiles row (
castProfilesTokens) and the dynamic part as Cast (castTokens). The turn's price counts both. - When the always-on prompt can't fit, the scene's cards give way before the profiles, and the profiles before the conversation summary.
- The context budget shows the stable block as its own Cast profiles row (
- Who gets it:
- Trackers off means no cast section at all, as in C1.
- The SFW lane carries both pieces (creator content is trusted).
- The stable block follows the cast wherever the cast is placed. So a Hybrid story's beat leg carries both, and the
prose leg carries neither, unless its own mode places
cast, and then it carries both.
- The leak guard.
- A profile is protected like a card: a reader who doesn't own it never sees it copied verbatim.
- Paging is quieter. "Yes: a redaction that touches only cast profiles logs Info, like card and mode redactions. A cast card or role redaction keeps Warning." β the owner, 2026-10-16.
- Shipping. Each build milestone goes out as its database change first and its app change after, so no deployed host ever calls a function the database doesn't have yet. Stored overrides survive the switch.
Who {{char}} is in a cast profile
The member, always: the same fill the card gets (C1) and the member's own lore gets (C2). A profile that says
{{char}} is known in the river towns⦠names Elara in Elara's entry, never the package's lead.
C3-T β Package tooling check π
"add to the docs to check the tooling for packages creation and editing, somewhere at the end of changes to packages." β the owner, 2026-10-16.
The last step of the package changes. Every tool that creates or edits a package is checked against the cast as it stands after C2 and C3 (no override, the role tag, the character's cast profile, members' own lorebooks), by driving it:
- the package builder (the Workbench Cast step, the DB-seeded preset steps and their client copies);
- the Workbench assistant and the user MCP door, which share
propose_package,propose_binding, the read tools, the readiness check, the prompt preview and their guideline text; - every other package writer: managed bot packages, admin lifecycle, the agent-proposal Undo.
Correct means:
- (a) the package builder creates and edits a cast; every other tool leaves the cast alone, never clears one, and the assistant says the creator sets the cast in the Cast step (owner 2026-10-16);
- (b) it never writes the override;
- (c) it reads and sets the role tag;
- (d) where it may, it drafts the member character's cast profile or points to it;
- (e) its descriptions match the fields as they are.
The inventory and the per-tool checks are in the delivery plan, Β§5.4.
Cast arrival pictures π§ (owner, 2026-11-10: "Can we also have this for the cast?")
A member who comes on stage shows their own picture (the character's) once, beside the reply whose tracker snapshot put
them on stage: the place's arrival rule (LOCATION_TRACKER.md Β§6 Pictures) applied to the cast roster. Staying on
stage shows nothing; leaving and coming back shows them again; the opening cast shows on the greeting; a reader's own
change to the roster shows who they brought on. The reader's persona name and account name (both, on every path) and the
story's lead never count. The pictures follow the cast tracker (none written with trackers off, and none in the owner's own history then), not the lorebook's picture
switch, and share the four arrival places in front of the turn's own pictures, never displacing one. A member before its release date for the reader shows unnamed ("Private Character") to the story's own reader and
not at all to a published reader or a share link; a protected reader gets the all-ages stored card only. Full rule,
storage (cast_arrival, the record's cast list) and delivery: LOCATION_TRACKER.md Β§6 Cast arrival.
C4 β Later, only if real casts need it π
Always-on token budget with priority drop; a per-member "present" cap; cast on the character owner type; Who-drawer cast card with avatars and presence toggles. (These were "C3" until 2026-10-16; C3 is now the cast profile.)
Known shape after C1, stated plainly: the roster and the cast section are re-read from
the database on every turn by several consumers (the eval, the injector, the pinned-knowledge
source, the provider, the compute reserve) β the same shape package trackers have, roughly
doubled on cast packages. Folding the resolved set onto the pipeline context is the fix,
together with the provider's conversation read on plain chats. C3 does it for the two cast
providers, which share one member read per turn; the roster consumers stay on this list. A comma in a member's story name ("Elara, the
Ranger") is ambiguous in the eval's plain-text type line and unmatchable in a non-JSON eval
answer β inherited from T1 linked lists, where entry names have the same shape; the JSON
answer path the eval is instructed to use is unaffected. Also: the edit read returns only the four wire fields per
member, so the workbench resolves each member's name, avatar and type with one character
read per member on package load β the same fan-out the lorebook and tracker legs already do.
Widening fn_get_package_for_edit's cast JSONB with that display half (and dropping the
fan-out) is the first thing to do when the edit read gets a composite pass; not a C1 gate.
Open Questions
Dev-owned (product weight):
Cap size. The cast is capped at 8, the tracker cap. A larger cast with all members present is a lot of prompt; the summary line keeps absent members cheap. Raise later if creators ask.
A lorebook bound to two present members (C2). Its entries resolve
{{char}}to the first of them in cast order. Decided 2026-10-16 (owner): "first member in cast order is fine."Public visibility of the always-on summary. C1 keeps it private (prompt material). It would make a good cast-list caption on the public page; that is a copy/consent decision. (C3: it is now the role tag; still private.)
Q1 (C3) β Where the stable block sits once caching is built. Resolved by C5 S2 (CAST_PRESENCE_STAGES.md Β§3.1): the built-in layout puts the roster at order 60, inside the cached head; creator modes keep lean (a). As asked before: C3 keeps it right after the dynamic part, so no cache boundary moves. The caching line would want it in the cached prefix: - built-in layout: order 60, after the scenario and before the summary β trivial; - creator modes, two options: (a) keep the fallback contract (after the mode's own sections; a creator who wants it early declares
cast_profiles), or (b) a new fallback rule that places it before the first section that isn'tStatic.Lean (a) now, (b) as the caching line's first move.
Q2 (C3) β The role tag for present members. It now shows for every member, so a present member carries role + profile + card. The profile + card overlap is accepted (owner, 2026-10-16); the tag wasn't named. Default: keep it.
Q3 (C3) β The empty stage. Default: the dynamic part says No one from the cast is in the scene right now. Alternative: skip the section when nobody is present.
Q4 (C3-T) β Assistant cast editing. Settled by the owner on 2026-10-16: "Not in C3. Keep the guideline that the creator sets the cast in the package builder; the tooling check only makes sure the existing tools match the new fields and never write the override."
(C3) The leak guard's paging for profiles. Settled by the owner on 2026-10-16: "Yes: a redaction that touches only cast profiles logs Info, like card and mode redactions. A cast card or role redaction keeps Warning."
Mine (engineering, decided in C1 unless overruled):
- Synthesised roster over a materialised tracker row β see Why not a real tracker row.
- Cast members bind under the primary character's rule, not the tracker's.
- The roster leads the union and shadows a same-keyed tracker.
- (C3) The cast profile is a column on
characters, not a side table: agent proposals'c.*snapshots carry it, and it is erased with the character. The system prompt'scharacter_system_promptsis a size table with no versioning of its own, so there was nothing to sit beside. - (C3) Two prompt keys, two providers. One section is one message with one stability, so a single provider can't emit a stable and a dynamic piece.
- (C3) The stable block is
Static, and its byte-stability is structural: its provider is never handed the roster. - (C3) The stable block follows the cast's placement (declared, fallback or a document token), not the fallback switch.
- (C3) The profile is searchable in the creator's own library search, beside the system prompt.
- (C3) Each build milestone ships as two pushes, database first. Railway deploys the hosts and the database replay in parallel, so one push would run new code against old functions.
Acceptance Criteria (C1)
The slice is not done until every box below is verified β against the running product.
C3 note: these boxes record what C1 shipped. The lines naming the override, the offstage line or the absent list describe C1 behaviour that C3 retires or reshapes; Acceptance Criteria (C3) says what holds after it.
User use cases β satisfiable + accessible (verify by driving the UI, not the code):
- UC-1 As a creator, in the package builder I find a Cast step after the character step on every preset, add two of my project's characters to it, set one as offstage at the start, write an offstage line for each, and save the package β reachable from the Forge without insider knowledge.
- UC-2 As a creator, reopening the package shows both cast members with their fields hydrated, in the order I set; removing one and saving removes it.
- UC-3 As a creator, the Story State step shows a read-only Cast β automatic row once the cast is non-empty, and Package Check reports the cast as assigned.
- UC-4 As a reader who starts a conversation from the package, the story-state bar shows a Cast list tracker first, seeded with the on-stage members, and after an assistant turn in which a member enters or leaves, the eval updates it (mock rail) β including a turn where the last member leaves and the roster becomes empty.
- UC-5 As a reader, I can inline-edit the Cast tracker from a picker of the cast's names; the next story prompt carries the picked members' cards (mock captures).
- UC-6 As a reader on the package's public page, I see the cast under Cast with avatars; public members link to their pages, private ones do not.
Behavior:
-
POST /api/creator/projects/{p}/packageswithcast[]writespackage_cast_membersin array order; a re-save replaces the set; omitted/[]= none;castExtractionHintis three-state. - The edit read returns
cast[](uuid, summary, override, presentAtStart) in order andcastExtractionHint; soft-deleted characters are absent from it. -
GET /api/conversations/{id}/trackerson a package conversation returnscastfirst (list, enum values = the members' story names, initial value = the on-stage members), then the character's and the package's trackers renumbered after it. - The story prompt for a package conversation contains a
castsection: present members' cards in cast order (override when set, else the character's prompt, with{{char}}resolved to the member), and absent members as summary lines β with a full mode, with a mode that declares nocastsubprompt, and with no mode at all. - A list tracker whose eval answer is
[]is set to empty; an answer whose items are all outside the allowed set still keeps the prior value (pinned inTrackerValueFormatterTests). - The eval prompt's type line for
castnames the members; an eval answer naming someone not in the cast is dropped from the list; case differences canonicalise to the member's spelling. -
GET /api/browse/packages/{id}/detailsreturnscast[]withisPublicper member and no summary/override fields. - A cast member's creator appears in the package's co-creator count and contributors list under the same masking as the primary character's creator.
- Submitting a package with a private cast character for publishing screens that character (a check-result row attributed to the character); the same submission screens the package's private bound trackers.
- Submitting a package whose cast override, offstage line or eval hint contains a blacklisted phrase produces a check-result row attributed to the package with the field named, even when every cast character is public; the moderator projection shows the flagged text.
- A moderator with publish-review rights (not an administrator) can open the fields of a private cast character that a requested package screened β the moderation field-access query treats cast membership of a requested package as a publish link, like the primary character and bound lorebooks. Bound-tracker screening results stay administrator-only until trackers get a moderation field surface (recorded in the fan-out comments).
- An omitted
presentAtStarton the save defaults to on stage (true), matching the column default.
Invariants that must stay true:
- A package with no cast behaves exactly as before: no
casttracker in the union, nocastsection in the prompt (asserted by marker absence inWebPromptCompositionTests, and by the resolver tests for the union). - A cast card renders the member's story name for
{{char}}, never the primary's β asserted on a two-member cast where both prompts contain{{char}}. - A conversation with no package behaves exactly as before.
- The package's primary character is still injected first-person under
character, once; it never appears in the cast section. - A cast member's prompt is never returned by any public or edit endpoint other than the
package edit read's
overrideSystemPrompt(which is the owner's own text). - Trackers off (
Features.EnableTrackers = false) β no cast section and no eval call; the definitions endpoint still lists the roster like any bound tracker (the bar hides on feature state, as for character trackers). - Soft-deleting a cast character removes it from the roster's allowed values, the prompt and the public page on the next read; nothing crashes on a stale name in a stored snapshot (rendered as plain text in the bar, ignored by the provider).
- Soft-deleting the package leaves its conversations with no roster and no cast section (the same inert-owner rule package trackers follow).
- The compute-cost reserve for the eval (
HasBoundTrackers) is true for a package whose only story state is the roster. - Package lorebooks, trackers, greetings and locks are untouched by a cast save (the
existing
PackageRepositoryTestspass unchanged; the endpoint tests change only in their positional mock setups).
Edges:
- A character the owner may not bind (not owned, not public, not in the project) β
whole save refused,
cast_not_bindable(403), nothing written. - The package's own character in
cast[]βcast_includes_character(422). - More than 8 members β
cast_limit_reached(422). - Two members whose story names match case-insensitively β
cast_duplicate_name(422), nothing written β the roster addresses members by name, so two of a name would collapse. - A duplicate uuid in
cast[]β deduped first-occurrence-wins, saved once. - A creator's own tracker keyed
castbound on the character β shadowed in package conversations (the roster wins), unaffected in plain conversations with that character. - Summary over 200 characters β 400 naming the field; override over the character prompt limit β 400.
- Non-owner saving the package β the existing 404/403 shape; not signed in β 401.
- A snapshot whose
castvalue is not a JSON array (hand-edited freeform) β treated as a single name; no crash. - Clearing the Cast field in the bar's inline editor stores the empty list (
[]), not a removed key β the next turn renders only the absent list, never the on-stage-at-start set again. (Blank still removes the key for non-list trackers.) - A builder step kind the client does not recognise (an old bundle against the new seed) is skipped, not a crash.
Acceptance Criteria (C2) β outline, expanded when C2 starts
The expanded list, with the delivery's invariants and edges, is Β§9 of
docs-internal/architecture/chat-engine/PACKAGE_CAST_C2_DELIVERY.md.
- With a present member whose character binds lorebook L (not bound to the conversation or the primary), a keyword from L in the reader's message activates an L entry; the same message with the member absent does not.
- A lorebook bound to both the conversation and a member is searched once, present or not.
- Cast-sourced entries carry the
castactivation leg and count against the normal knowledge budget. - The Discord lorebook provider is untouched.
- (Owner 2026-10-16) An entry from a present member's own lorebook renders
{{char}}(any case) as that member's story name, in its content and its## Nameheader. Asserted on a two-member cast plus a primary, with each lorebook's entries containing{{char}}.{{user}}in the same entry is the reader's persona. - Lore bound to the conversation, the package, the primary or the persona still renders
{{char}}as the primary's story name. Asserted in the same prompt, so both names appear next to each other. - A lorebook bound to two present members is searched once, and its entries name the first of them in cast order (until the owner rules otherwise).
- The leak guard records a member-resolved entry as the model read it. A reply that copies the member-named text is caught, and the primary-named form is not what's guarded.
- The turn-cost estimate and the embedding gate count a present member's lore. In the SFW lane a present member's lore reaches the protected prompt like the lead's; creator content is trusted (CHAT_SFW_MODE Β§0), and the A32 re-check is not widened (owner, 2026-10-16: "keep SfwGuardStage as it is β creator lore isn't treated as unsafe reader input (the 2026-10-07 rule); replace the spec line."). A member's lorebook still before its release date is withheld turn by turn from a reader without access of their own, and present for its owner; the story start is not held by it (director, 2026-10-16, D10).
- Live (prompt capture,
game-testingmock LLM): on a seeded package with a primary and two members (one offstage), one member-linked lorebook and one package lorebook, each holding{{char}}, run the standard lane, the SFW lane and one Hybrid story. The captured prompts show the member's lore naming the member, the package lore naming the primary, the absent member's lore missing, and no{{char}}left in any case.
Acceptance Criteria (C3)
The slice is not done until every box below is verified β
against the running product. The expanded list (shapes,
lanes, the live recipe) is Β§9 of docs-internal/architecture/chat-engine/PACKAGE_CAST_C3_DELIVERY.md.
User use cases β satisfiable + accessible (verify by driving the UI, not the code):
- UC-C3-1 As a creator, I write a character's cast profile, save it, reopen the character and see it, then clear it and save. The counter shows characters and tokens. I find it in the collapsed In a cast section of both character editors (the Forge editor and the classic character page), and the copy tells me most characters need a paragraph or two.
- UC-C3-2 As a creator, in the package builder's Cast step each member shows a Role in this story field (200 characters) and no prompt-override field. It shows whether the member's character has a cast profile. For a character I can edit, a link opens its editor; for one I can't, there is no link and a line says only its creator can write it.
- UC-C3-3 As a reader of a package story, when the story talks about an offstage cast member, it describes them as their cast profile does. A dark-haired member stays dark-haired. Checked on a real model, not only in a capture.
- UC-C3-4 As a contributor on a project, I propose a change to a character's cast profile from the propose-changes view. The owner approves it and it applies.
- UC-C3-5 As a creator, I ask the Workbench assistant to draft a new character with a cast profile, and to add one to an existing character. The proposal shows the field, and applying it saves it.
Behavior:
- Saving a character (create, update, import) treats
castProfilethree-state: omitted keeps it,""clears it, a value sets it. The owner's character read returns it. - A package story's prompt carries the stable block. It lists every live cast member in cast order, present or not:
### Name β role, then their profile, in the shape the delivery plan pins. - The dynamic part carries a card only for each present member. The card is that member's own system prompt. It closes with Everyone else in the cast is elsewhere right now. when anyone is absent, and an empty stage says No one from the cast is in the scene right now.
- (Owner) The stable block doesn't change when the roster changes. Captures before and after a member walks off are byte-identical in that block, and the same holds across an empty roster, a full one and no snapshot yet.
- (Owner) An offstage member is described with their profile's appearance: the dark-hair case is in the prompt while the member is absent, and a real-model reply about them keeps it.
- (Owner) A present member's system prompt appears only while they are present.
-
{{char}}in a role or profile, in any letter case, is that member's story name.{{user}}is the reader's persona. - Placement: the stable block appears right after the dynamic part. That holds in the built-in layout (175 / 180),
under a mode that declares neither key (the two fallbacks, cast first) and under a mode that declares only
cast(the profiles fallback at the mode's end). A document mode's{{cast}}doesn't suppress the profiles fallback, and the reverse holds too. - The context budget shows the stable block as Cast profiles and the dynamic part as Cast, and the turn's price counts both. A cast with nobody present still counts the stable block.
- (Owner) A redaction of the model's reasoning or the director's thinking that touches only cast profiles logs Info. One that touches a cast card or role logs Warning. The redaction itself is the same either way.
- A publish request screened before C3, holding a hit on a member's override, still shows it to the moderator as a retired field with its stored match.
- When the always-on prompt can't fit, the scene's cards are given up before the profiles, and the profiles before the conversation summary.
- Publish screening reads a character's cast profile wherever it reads the system prompt: - the keyword check (prompts area) and its check row; - the AI ladder's fields; - the moderator's projection; - the creator's self-check; - the package fan-out to private cast characters.
- The package edit read returns, per member, the role tag, presence at start and
hasCastProfile, and no override. - A character's native export carries its cast profile and its import restores it; an export made before C3 imports with an empty profile.
- A profile edit moves the character's "Updated" date and adds a changelog entry; a save that changes nothing does neither.
Invariants that must stay true:
- (Owner) An override written before C3 never reaches a prompt (test it with a row whose override column holds a marker string, set by direct SQL). The present member's card is their own system prompt.
- No save path writes
override_system_prompt. A package save leaves an existing value in place on a re-listed member and writes NULL for a new one. Any client sendingoverrideSystemPromptsaves fine and changes nothing. - (Owner) A cast profile never reaches a reader surface. These never carry
castProfile/cast_profile: - the public character read; - the anonymous card; - browse; - the package page payload; - OpenGraph; - a profile page's character sections. - (Owner) An empty profile falls back to the role tag (
### Name β role), and with neither it is the bare name. - (Owner) A cast profile goes through publish moderation like the system prompt (the screening box above, run on a character whose profile alone carries the blacklisted phrase).
- A conversation with no package, and a package with no cast, gets a prompt with no cast section of either kind, the same as before C3.
- Trackers off β neither piece (C1's rule).
- The conversation's own character is never listed in either piece.
- A character's own conversations never read its cast profile.
- The prompt-cache boundaries land on the same messages as before C3, in the built-in layout and under a mode with fallbacks, with and without a cast. That includes summaries and the journal switched off.
- The Hybrid beat leg carries both pieces. The prose leg carries neither (unchanged), unless its mode places
cast, and then it carries both. - Shipping the database change before the app change breaks nothing for the hosts still running: - under the database change, character saves keep working with the old app; - package saves keep working too, and every stored override is left as it was.
- The leak guard protects a member's profile and role from a reader who doesn't own them, and leaves the owner's own text unprotected (LEAK-OWN).
- One turn reads the cast once for both pieces.
- C2's member lore and the C1 roster behave as before (their acceptance boxes still pass).
Edges:
- A profile over 10,000 characters is refused with a 400 naming the field:
- from the editor endpoints, with code
cast_profile_too_long; - from import, in the import's own message shape; - from the assistant's staging too. - A member whose character the creator can't view still shows the profile badge (from the edit read), with no edit link.
- A soft-deleted member drops out of both pieces on the next turn.
- A story name or role with a newline renders as one header line.
- A present member with an empty system prompt renders as a bare card name.
- Everyone present β the dynamic part has the cards and no elsewhere line. Nobody present β only the empty-stage line. The three states of the dynamic part are each pinned.
- A contributor's proposal carrying more than 10,000 characters of profile is refused, and nothing is written.
Acceptance Criteria (C3-T β package tooling check)
The check is not done until every box below is verified β by driving the tool. Reading its code doesn't count.
- The package builder creates and edits a two-member cast with role tags. The saved rows hold the members, tags and presence, with the override column untouched. The next story prompt carries both pieces as specified.
- Asked to build a package with a two-member cast, the Workbench assistant (and the same request through the user
MCP door) creates the package without a cast. It says plainly that the creator sets the cast in the package
builder's Cast step, and no
package_cast_membersrow and no override is written (owner 2026-10-16, Q4). - Asked to add, remove or re-role a member of an existing package, the assistant changes nothing and points to the Cast step.
- Asked to write a cast profile for a member's character, the assistant drafts it on the character (where the creator may edit it), or points to the character when they may not.
- Asked to rename or relock a package (anything but the cast), every tool that can do it leaves the cast exactly as it was.
- The assistant's tool descriptions and guidelines name a cast member's role in this story, presence at the start and the character's cast profile, and never a prompt override. Its package reads don't return the cast, which is a follow-up.
- A managed bot package rebuild, an admin unpublish / restore and an agent-proposal undo leave a package's cast as it was (or, for undo, refuse as touched).
- The Echo Guide and the guideline files describe the cast as it now is: a grep for "override" and "offstage one-liner" over the knowledge bundles finds nothing about casts, and asking Echo Guide how to set up a cast gives today's fields.
- The Echo Guide's cast help says a member's own lorebooks join the story while that member is on stage, and the story does use them (C2's live box).
Acceptance Criteria (cast arrival pictures)
- As a reader of a package story, when a member comes on stage I see their picture beside that reply, once; a member who stays shows nothing new; one who leaves and returns shows again; the opening cast shows on the greeting.
- A reader's own change to who is on stage (the tracker bar or the scene editor) shows the member they brought on.
- My persona's name and my account's name on the roster never show a picture, whichever applies, nor does the story's lead.
- A member I may not yet see named (before their release date) shows as "Private Character", never named; on a published story or a share link, not at all. A protected reader sees only all-ages pictures we store.
- The place's arrival pictures and the turn's own pictures are unaffected: the place first, then the cast (four arrival pictures at most between them), then the turn's eight, never pushed off.
- With picture entries off the cast's pictures still show; with trackers off none are written and my own history shows none (a published story's readers still see the ones it recorded).
Related documents
- trackers.md β the tracker substrate; Β§Character Roster (lorebook-based, shipped via T1) and Β§Character Groups (superseded by this doc).
- packages.md β package composition, locks, open question 5.
- package-multi-authoring.md β derived co-creator credit, which the cast arm extends.