Document Mode Editor
Status: Core substrate SHIPPED as a thin slice (2026-08-09, 9a57273c); Rows → Document conversion with preview shipped 2026-08-25 (1e4444e1); the guided surface remains design. Rebased against the tree on 2026-07-11, including the shipped agent tool-pack family, project reads, experience dry-run, sub-entity proposals, the current Workbench creation flow, and the live Hybrid v1 pipeline.
Caching (2026-10-15): for the mode / model-profile redesign, §Caching tradeoff ("a Document row with any dynamic token is non-static as a whole") and the non-goal "Static-prefix auto-splitting/cache optimization" are superseded by
docs-internal/architecture/chat-engine/MODEL_PROFILE_CACHING_REQUIREMENTS.md. There, splitting a mode's static part from its dynamic part is a requirement, not a later optimization.
As built (2026-08-09) — the "compose with variables" slice. The decided storage/runtime contract from this doc is now live, deliberately WITHOUT the rest of the program:
- Schema:
prompt_modes.editor_kind('advanced'|'document') +sub_prompts.expansion_version(0|1), exactly as specified (§The model). v0 rows stay byte-identical;editor_kindnever gates runtime.- Runtime:
InlinePromptExpander(Core/Pipeline/Providers) —{{key}}+ non-nested{{#key}}…{{/key}}, whitespace-tolerant keys, unknown/malformed stays literal, alias canonicalization viaPromptKeyCatalog, per-build memoized resolution through the SAME content providers (PromptContextManager.ResolveInlineKeyAsync), reserved{{char}}/{{user}}untouched for the global pass.identityis inline-only vocabulary inside the expander, NOT a catalogue alias — the §identity carve-out (a legacy v0 row free-keyedidentitystays skipped) is preserved. Two knowing divergences from §Grammar: whitespace inside braces is tolerated ({{ knowledge }}works), and the key charset is[A-Za-z0-9_]+(leading digits/underscores accepted).- Switch:
fn_set_mode_editor_kind+PUT /api/creator/modes/{id}/editor-kind. → document: creates (empty mode) or v1-flips (single keyless System row, unshared only — no COW in this slice) the document row; anything else 400s with the reason. → advanced: lossless flag flip. Row POST/DELETE and provider-key/role changes are endpoint-blocked whileeditor_kind='document'; content edits ride the ordinary row PUT (no aggregate writer needed at one row).- Row → document conversion (added 2026-08-25): the piece that makes the offer gate below actually useful.
ModeDocumentConverter(Core, pure) translates a mode's ordered System rows into one inline-token document: a keyless row contributes its text verbatim, and a keyed row becomes{{#key}}…{{key}}…{{/key}}— its{content}slot replaced by the canonical inline token, the whole row wrapped in its own conditional. The wrapper is the behaviour-preserving part, not decoration: a legacy keyed row is dropped WHOLE when its provider is empty (SystemPromptBuilder: "If provider returns empty, the entire section is skipped"), so a bare{{key}}would strand the row's framing prose over nothing. Each block after the first carries its leading blank line inside its conditional, so a quiet row takes its separator with it and the surviving text keeps today's exact spacing — the spec's own insertion contract. Golden tests expand the produced document through the realInlinePromptExpanderand assert byte-equality with the legacy row assembly, with every provider populated, some quiet, and all quiet. Blocking conditions (each naming its row): a non-System row, an unrecognized provider key,{content}with no provider. Identity coverage is a note, never a blocker — the document inherits exactly the coverage the Advanced mode already had, so blocking would refuse modes that work today.GET/POST /api/creator/modes/{id}/document-conversionare preview and commit; the server re-derives the document on both and the POST 409s when the caller's approved text no longer matches (rows edited in between).fn_convert_mode_to_documentdoes the atomic write: new document row, unlink the old rows, and reclaim only those now orphaned AND private AND actor-owned — a row another mode still links, a published row, or someone else's row survives untouched. One-way, since Document → Advanced is a flag flip; the modal says so and points at Export.- Offer gate (added 2026-08-25): the switch is now offered only when it would succeed, as §Copy, import/export, and editor switching requires.
fn_get_mode_document_eligibility(read-only mirror of the writer's→ documentbranch, in the same SQL file so the two rule sets can't drift) +GET /api/creator/modes/{id}/editor-kindreportcanSwitchToDocumentplus adocumentBlockCode—multiple_rows|keyed_row|non_system_role|shared_row— and the facts the copy needs (rowCount,providerKey).ModeCompositionPaneldisables Compose as document and renders the creator-facing explanation of the blocking condition; the PUT's 400 remains the backstop for a shape that changed between the read and the click, and a failed eligibility read leaves the button enabled. Row mutations in the Advanced editor re-read eligibility, so the affordance tracks the rows live. This does not add conversion: a multi-row mode still cannot become a document — see §Not built.- Editor: Workbench third column is now
ModeCompositionPanel— the switch + either the existingModePromptsPanelor the newModeDocumentPanel(textarea + catalogue-served token palette with caret insertion). Plain textarea, not the CodeMirrorTokenTextEditor(still design).GET /modes/provider-keysnow derives its key list fromPromptKeyCatalog(the stale hand-maintained list — missingbeat, advertising dead{charname}/{date}/{time}— is gone) and documents the inline syntax.- Testing surface: the Workbench sandbox is the test-drive rail (per the 2026-08-08 direction): classic modes prefill
modeId; Beat/Prose-tagged modes create a Hybrid sandbox conversation with that leg pinned and the partner leg on the seeded reference — no in-editor pseudo-runtime.- NOT built (still this doc's open program): Flavors/base composition, aggregate CAS writer + row-set tokens, per-row "Enable inline tokens" upgrades + COW for shared rows, TokenTextEditor/CodeMirror, span-based lint + golden grammar fixtures, Core-backed Sample endpoint, templates/guided onboarding,
identitytype-specific coverage validation.
Problem statement
Modes are the hardest creator entity to author:
- The mechanics are abstract. To place world knowledge in the prompt, a creator adds a sub-prompt, chooses the
lorebookprovider key, places{content}, chooses a role, and orders the row. None of those concepts maps cleanly to “let the model know my world.” - Assembly is invisible. The creator cannot see where provider output lands or what the final message sequence looks like without starting a chat.
- The current editor is still valuable. Multiple roles, provider-specific framing, and cache-aware sectioning are real power-user controls. The new surface must reveal that power progressively, not replace it or create a second runtime model.
The Document editor addresses the common case with one document, inline tokens, contextual lint, and a sample assembly produced by the real prompt-building rules.
Design intent (north star)
- One mode engine, two editors. “Document” and “Advanced” are authoring surfaces over the existing
prompt_modes/sub_promptsmodel, not separate mode kinds at runtime. - Version expansion explicitly. Existing sub-prompts preserve legacy role/content/order/name behavior (with the separately named journal staticness correction). New inline-token behavior is enabled per sub-prompt with an explicit expansion version; it is never inferred from token-looking text.
- Document-first for the common case. The Document editor owns one keyless System sub-prompt whose content is freeform prose with inline tokens.
- Advanced remains fully capable. Advanced rows can remain legacy or opt into inline expansion individually. Switching a Document-authored mode to Advanced never rewrites its prompt.
- Comprehension is built in. The prompt field's Preview resolves the authored Mode prompt with clearly recognizable example token values and no pipeline metadata. A project/package-context lint pass names missing bindings; Test drive closes the behavioral loop.
- Pick-and-tweak beats blank-page. New Document modes start from production-safe behavior templates, with teaching copy outside the prompt.
- Create in context. The editor is embeddable in the Workbench and preserves project/model-profile-entry-draft context, atomically creating/project-linking the mode and returning its selection to the parent draft. The standalone Creator Hub route uses the same component.
- Separate model adaptation from optional flavor. A winning Model Profile Entry selects the always-on base mode for that model; optional profile-wide flavor fragments layer over it without becoming rows of that mode. Existing profiles have no flavor links and assemble exactly as before.
- The engine is shared substrate. Token expansion, mode introspection/lint, and assembly are Core services consumed immediately by chat, browse/budget reads, the shipped agent tool packs, the Workbench, and moderation.
- Core craft stays accessible. Document and Advanced editing, lint, and mock/sample preview are rights/count-based creator features; they spend no Echoes and require no subscription tier.
This is the design-principles progressive-disclosure doctrine applied to mode authoring, and it follows the project direction that Packages are the primary creative unit while individual modes remain legitimate reusable deliverables.
Roadmap position: this is generic authoring/introspection substrate that makes Package and Luna-assisted construction safer; it does not replace the prescriptive resolution/conditions layer identified as the game-direction bottleneck. “Implementation-ready” describes design completeness, not priority over that work.
The model — existing sub-prompts with versioned expansion
Two independent discriminators
| Field | Lives on | Meaning | Default for existing data |
|---|---|---|---|
editor_kind |
prompt_modes |
Authoring contract/surface: 'document' or 'advanced' |
'advanced' |
expansion_version |
sub_prompts |
How this authored template expands: 0 legacy, 1 inline tokens |
0 |
The separation is load-bearing:
editor_kindaffects authoring routing, presentation, and structural validation. The prompt builder never gates assembly/expansion semantics on it.expansion_versionis a property of the sub-prompt content.sub_promptsare reusable through the N:M link table, so the same row must not mean different things in different modes.- A mode may contain legacy and inline-enabled rows together in the Advanced editor.
- A Document-authored mode is structurally one System row with no provider key and
expansion_version = 1.
Legacy expansion (expansion_version = 0)
The current content path remains byte-identical:
- Resolve the row’s single
provider_key(if any). - Skip the row when that provider resolves empty.
- Replace
{content}and{username}in the template. - After all provider insertion, apply the existing global
{{char}}/{{user}}display-name substitution.
No new token parser runs. Existing modes, SillyTavern/TavernAI imports, old exports, copied legacy rows, and literal {{persona}} / {{scenario}}-style text retain today’s role/content/order/name behavior. Correcting journal.IsStatic is the one intentional legacy message-metadata change.
Inline expansion (expansion_version = 1)
An inline-enabled row may use both:
- its ordinary
provider_key+{content}slot (useful in Advanced); and - any number of inline
{{content_token}}references in the authored template.
The Document editor always uses a keyless row; all content arrives through inline tokens:
{{identity}}
Write an immersive response in this character's voice.
{{#persona}}The other participant:
{{persona}}{{/persona}}
{{#knowledge}}Relevant world knowledge:
{{knowledge}}{{/knowledge}}
This remains one stored sub-prompt and one creator-authored document.
Resolution rules
- Expansion is gated per sub-prompt by
expansion_version = 1. Never by editor surface and never by shape inference. - Resolution is non-recursive. Tokenize the authored template before any provider output is inserted. Substituted character, persona, lorebook, journal, or memory content is opaque to the inline-token parser.
- Provider output keeps today’s global name behavior. The existing final
{{char}}/{{user}}pass still runs after assembly, including over provider output. This is the only intentional post-insertion substitution and is pinned as a compatibility invariant. - Unknown
{{tokens}}stay literal and produce a lint warning. A typo is visible; content never silently disappears. - Known tokens require an exact, fully delimited match.
{{char}}and{{character}}are distinct exact tokens; the current.Replace("{{char}}", …)does not collide with{{character}}. Conditional open/close names are compared after alias canonicalization, so{{#knowledge}}…{{/lorebook}}is balanced even though the palette always emits one consistent spelling. A tokenizer is required for conditionals, positions, non-recursion, and lint — not to solve a nonexistent substring collision. - Resolve each canonical version-1 dependency at most once per prompt build. Parse all inline-enabled rows, canonicalize their ordinary row providers plus inline dependencies, and resolve through a build-scoped cache. The cached terminal result is the first non-whitespace candidate preserved exactly, or normalized
""after all candidates throw/return blank. A v1 row provider and{{token}}for the same canonical key share that result. Repeating{{knowledge}}must not repeat lorebook/vector work or yield inconsistent text. Version-0 rows keep today’s per-row provider calls. - Feature gates apply once at provider resolution. A gated-off provider resolves empty; conditional segments then drop normally.
- Legacy row placeholders remain authored-template nodes in version 1.
{content}lets an Advanced row combine its primary provider with inline references, and{username}still resolves in authored text. V0 keeps today’s sequential.Replace("{content}", value).Replace("{username}", …)order, including replacing{username}that arrived inside ordinary provider output. V1 tokenizes authored{content}/{username}positions before insertion; ordinary and inline provider values are opaque to both placeholders. The only v1 post-insertion substitution remains exact-lowercase global{{char}}/{{user}}. Golden fixtures pin this intentional version boundary. - An ordinary row provider remains the row gate. When a version-1 Advanced row has a
provider_key, platform/feature unavailability skips the complete row. Otherwise the existing ordered provider chain is preserved: log an individual exception, continue through later candidates, and use the first nonempty result. Only when all registered candidates throw/return empty does the complete row skip; static prose and other inline values in that row do not survive. A keyless inline row has no such gate.
Macro vocabulary (v1)
The catalogue extends PromptKeyCatalog; ordinary provider descriptors and inline-token descriptors share aliases/gates/platform metadata without requiring every token to be a legacy provider key. Each inline descriptor also carries MayResolveEmpty and an exact RecommendedInsertSnippet, so the palette, autocomplete, teaching copy, and tests do not invent different framing rules.
| Token | Canonical dependency | Kind | Document palette behavior |
|---|---|---|---|
{{identity}} |
identity (new inline semantic) |
identity | Primary identity; returns the selected character's definition for standard, System, and Assistant character types |
{{character}} |
character |
identity/type-specific | Type-specific identity; resolves only for standard characters (existing provider semantics) |
{{rules}} |
rules |
identity/type-specific | Type-specific identity; resolves only for System characters (existing provider semantics) |
{{assistant}} |
assistant |
identity/type-specific | Type-specific identity; resolves only for Assistant-type characters (existing provider semantics) |
{{persona}} |
persona |
context / Web-only | Reader persona / package persona-template context |
{{scenario}} |
scenario |
context / Web-only | Greeting scenario context; optional and conditional |
{{knowledge}} |
lorebook |
dynamic | Alias presented to humans; resolves the merged lorebook set |
{{summary}} |
summary |
dynamic | Conversation summary; often empty early in chat |
{{recalled_memory}} |
recalled_memory |
dynamic | Semantically recalled memories |
{{journal}} |
journal |
dynamic / Web-only | Story journal; suppresses the builder’s journal fallback because it is declared explicitly |
identity is an inline-v1-only resolver semantic, not a globally registered ordinary provider key. A pre-feature version-0 row whose free-text provider_key happens to be identity therefore remains unknown/skipped exactly as today. Refactor the duplicated character loading/DisplayName + SystemPrompt formatting into a byte-pinned helper first; the inline resolver and the existing mutually exclusive character / rules / assistant providers then share it without changing those legacy provider results. The Document palette exposes identity as the universal default plus the three type-specific tokens in a separate Type-specific identity group, so a creator can cover each character type separately instead of using one universal Identity; Advanced inline autocomplete exposes the same four.
The table above, its catalogue aliases, and the reserved display-name nodes below are the exhaustive v1 inline vocabulary. Ordinary catalogue keys such as facts and tracker, preview-only greeting, and any other provider key not listed as an inline descriptor remain row-provider-only; typing {{facts}}, {{tracker}}, or {{greeting}} inline leaves the text literal and produces unknown_token.
The Document insertion contract is exact. identity has MayResolveEmpty=false and inserts bare {{identity}}. The three type-specific identity tokens stand in identity position, so they insert bare inside their own matching conditional with no framing label. Every other Document token may resolve empty and inserts its whole leading separator inside a conditional:
| Token | RecommendedInsertSnippet |
|---|---|
character |
{{#character}}{{character}}{{/character}} |
assistant |
{{#assistant}}{{assistant}}{{/assistant}} |
rules |
{{#rules}}{{rules}}{{/rules}} |
persona |
{{#persona}}\n\nParticipant context:\n{{persona}}{{/persona}} |
scenario |
{{#scenario}}\n\nCurrent scenario:\n{{scenario}}{{/scenario}} |
knowledge |
{{#knowledge}}\n\nRelevant world knowledge:\n{{knowledge}}{{/knowledge}} |
summary |
{{#summary}}\n\nConversation so far:\n{{summary}}{{/summary}} |
recalled_memory |
{{#recalled_memory}}\n\nRelevant memories:\n{{recalled_memory}}{{/recalled_memory}} |
journal |
{{#journal}}\n\nEstablished continuity:\n{{journal}}{{/journal}} |
The snippets are catalogue data consumed verbatim, not strings reconstructed by the TypeScript client. A creator may still hand-author different framing; the renderer never cleans it up.
Exact lowercase {{char}} / {{user}} are reserved display-name nodes: the inline parser recognizes them without warnings, leaves them for the unchanged exact-lowercase final name pass, and never adds them to declared dependencies. Case variants such as {{CHAR}} remain literal with unknown_token; v1 does not broaden legacy name substitution. {username} remains the existing row-template placeholder in both expansion versions. The ambiguous legacy provider alias memory → summary remains accepted but is not shown in the palette; hand-typing it produces an informational lint note. facts stays Discord-scoped. tracker and Hybrid’s future beat handoff remain role-specific Advanced concerns.
{{date}} and {{time}} are not v1 tokens. The current provider catalogue stops advertising its unimplemented {date} / {time} placeholders. A future wall-clock token needs an actual use case, a specified format/clock abstraction, and explicit cache semantics.
Parser, empty values, and conditionals
- Identifiers match
[A-Za-z][A-Za-z0-9_]*with no inner whitespace; catalogue lookup is case-insensitive and canonical keys are lowercase. Palette output is always canonical lowercase.{{ knowledge }}is an unknown literal token, not a forgiving alias. - A known simple provider token and each valid known conditional marker contribute their canonical dependency. Reserved
{{char}}/{{user}}, unknown simple tokens, and opaque malformed spans contribute none. Document identity validation requires every character type to be covered exactly once: one top-level/unconditional simple{{identity}}value node, or complete type-specific coverage from{{character}}/{{assistant}}/{{rules}}value nodes that sit top-level or inside their own matching conditional. Conditional markers, identity nodes inside conditional bodies, and type-specific nodes inside unrelated conditionals satisfy nothing. - Provider candidate
null, empty, or whitespace-only values normalize to empty while the resolver continues to later candidates; the first nonblank provider value is preserved byte-for-byte, including its leading/trailing whitespace. A resolved simple token is replaced by that exact value. Empty means""; the renderer performs no punctuation, indentation, or newline cleanup. Exact examples:"A {{persona}}, B" → "A , B";"A\n {{persona}}\n\nB" → "A\n \n\nB". {{#token}}…{{/token}}emits its body exactly when the canonical value is nonempty and emits""otherwise. Open and close names must resolve to the same canonical entry. Thus"A\n{{#persona}}Persona: {{persona}}{{/persona}}\nB" → "A\n\nB"when persona is empty. Palette templates own clean framing; the engine never rewrites authored whitespace.- Conditionals do not nest in v1. Recovery boundaries are deterministic and golden-tested:
- a stray close marker is literal for that marker only, then parsing resumes;
- an unclosed opener makes the opener through EOF one opaque literal span;
- a nested opener makes the complete outer construct through its matching outer close one opaque literal span;
- a mismatched closer makes the opener through the first conditional close marker one opaque literal span, then parsing resumes (or through EOF when no closer exists); and
- a balanced unknown conditional makes that complete block one opaque literal span.
Nothing inside an opaque span participates in inline content expansion or contributes dependencies. The unchanged final global
{{char}}/{{user}}pass still applies to all rendered text. In particular,{{#unknown}}{{journal}}{{/unknown}}stays wholly literal and does not suppress the journal fallback.
- A keyless version-1 row containing
{content}receivescontent_without_provider; it blocks Document Save because{content}would otherwise become empty.{username}remains valid. - Parser/lint spans are zero-based UTF-16
[start,end)offsets, matching .NET strings, TypeScript, and CodeMirror. Golden fixtures include astral Unicode before/inside tokens. SQL parity covers descriptor/key extraction only and returns no source spans.
Identity safety
A nonempty custom mode suppresses the platform’s default character section. Therefore a Document mode must guarantee every character type exactly one identity injection. Two shapes satisfy that: exactly one top-level, unconditional simple {{identity}} value node (its inline resolver works for every current character type), or complete type-specific coverage — {{character}}, {{assistant}}, and {{rules}} each present exactly once, top-level or inside their own matching conditional, so whichever character type is bound receives exactly one definition and the mode can frame each type differently. An identity-family value nested inside an unrelated conditional satisfies neither shape, because the surrounding value can disappear.
missing_identityis a blocking Document-editor finding when no identity-family value node exists.conditional_identityblocks an identity value nested inside a conditional and points to moving it top-level.partial_identity_coverageblocks type-specific coverage that leaves any character type without a definition, naming the uncovered types and their missing tokens; this replaces the earlieradvanced_only_tokenrule and keeps a type-specific template from looking valid while resolving empty under another binding.misplaced_type_identityblocks a type-specific token inside an unrelated conditional, where its character type could still be skipped.duplicate_identityblocks a second simple identity value — including{{identity}}mixed with a type-specific token — so no character type receives its definition twice.- The editor’s one-click Insert Identity changes the visible draft. The shared Save persists it; Cancel restores the last server state.
- There is no hidden runtime character append. Stored text, sample assembly, moderation, and inference remain one source of truth.
- Advanced modes retain the right to omit identity providers intentionally.
- Universal inline
identityrenders/counts for standard, System, and Assistant character types. Ordinary or inlinecharacter,rules, andassistantrender/count only for standard, System, and Assistant respectively; a concrete Sample context and the no-mode default path must preserve those type gates rather than displaying/counting a generic mock that runtime would skip.
Open follow-up (knowledge review, 2026-09-29). Fixed: the no-mode default layout carried only
character, so a System or Assistant character in a conversation with no mode (or a zero-row mode) reached the model with no definition —DefaultSectionsnow carriescharacter/rules/assistant, each type-gated, so exactly one fills (SystemPromptBuilder.cs, pinned byWebPromptCompositionTests.NoMode_EveryCharacterType_GetsItsDefinitionExactlyOnce). Still open, by this section's design: an Advanced mode with only acharactersub-prompt drops a System/Assistant character entirely, and nothing tells the creator — thepartial_identity_coveragelint exists only in the Document editor, and there is deliberately no runtime append (above). The platform's own default is exposed: the Discord main bot's default character is the Echo Guide (anassistant), run underBotBehavior.ModeId's default mode ("1", whatever row that is in production); if that mode has noassistantsub-prompt, the Echo Guide runs with no definition. Fix shape (owner's call): an advisory, non-blockingpartial_identity_coveragewarning in the Advanced editor and on a character-type switch, plus a platform default mode that carries all three identity keys (or{{identity}}). A runtime fallback section — the journal/cast pattern — is the rejected alternative here.
Hybrid-aware authoring
Trackers inject/evaluate per-message independently of mode rows; a tracker row supplies explanatory prose only. The Document palette does not expose it, and omission must never lock the tracker toggle or disable bound tracker injection. When a selected context has an active bound tracker but its assembled mode has no ordinary tracker explanation row/hook, lint emits informational tracker_without_explanation; that finding never gates injection, the toggle, Save, or publish. Hybrid’s future authored beat handoff is User-role and also stays out of the single-System-block palette. Advanced rows retain the existing provider-key/role model and can opt into expansion version 1 independently.
Classic sends the assembled Document Mode to the response model directly. In shipped Hybrid v1, the assembled Base informs the beat-planning stage, then BeatDirectionStage rebuilds the prose prompt from the prose Mode resolved per leg — the winning Model Profile's role-tagged entry first, the settings-bound Mode (HybridPipelineLlm.ProseModeId, seeded "Visceral Prose") next, the hardcoded template only as last resort (see Hybrid Pipeline §4's as-built note and Model Profiles — Hybrid-Ready); Document prose instructions therefore influence planning but are not a direct prose-stage contract. The field Preview deliberately shows only the current Mode prompt; Test drive labels the full-pipeline boundary and defaults Mode craft testing to Classic. Creator-authored Beat/Prose pairs remain Hybrid Phase 2: Advanced authors each Mode, while a future role-tagged Model Profile binds them.
Caching tradeoff
An inline-enabled row containing any dynamic token is non-static as a whole. A large Document prompt containing {{knowledge}} therefore loses prefix-cache eligibility. This is an honest simplicity tradeoff. Advanced can split static and dynamic concerns into separate rows; automatic static-prefix splitting remains future optimization.
Current-tree constraints (verified 2026-07-11)
- The old preview rail is not a real mode preview.
BuildPreviewAsyncconstructs aPreviewPipelineContextwhoseGetModeAsync()returns null, while the production GET endpoint hand-merges stored content and never invokes providers. Preview also skips runtime merge behavior to preserve section metadata. The replacement must return both source sections and final assembled messages. PromptKeyCatalogis the substrate. Alias, dynamic/static, gate, status, and mock knowledge already live there. Extend it with inline-token metadata; do not create a second catalogue.- The HTTP provider catalogue is stale. It hand-maintains provider data and advertises unimplemented
{charname},{date}, and{time}placeholders. Rewire it to the catalogue and expose legacy placeholders separately from inline tokens. journalis incorrectly marked static. It carries eval-maintained state and must be dynamic.sub_prompts.provider_keyis free-text. Lint/validation is the authority for invalid keys; database lowercase enforcement remains.- Runtime mode/sub-prompt loading has multiple paths. Web uses
fn_get_conversation_mode+fn_get_mode_subprompts; direct/Discord paths usePromptModeRepositoryandPromptModeService. Expansion version must flow through everyISubPromptimplementation. Core does not needIPromptMode.EditorKind. - Three human mode surfaces exist.
ModeFormPage, WorkbenchEntityDetailView/ModeEditForm, andStandaloneEditorPagemust route/render consistently. Mode forms currently use hand-rolled dirty snapshots; the new shared surface adoptsuseFormDraft. - Workbench mode creation bypasses
/creator/modes/new, and ordinary package Save currently sendsmodeId:nullinto direct-assignment SQL.QuickCreateFormcreates an empty Mode directly, thenEntityDrawerlinks it. New packages no longer author a direct Mode choice: effective Bases come frompackage_model_profiles → model_profile_entries, with pre-existingpackages.mode_idread-only legacy fallback only. Ordinary Save must hydrate/omit that legacy value rather than clearing it; removal is a separate reverse-impact action. Contextual creation targets a project item and, when invoked from a Model Profile Entry, that exact Entry—never a fictional package Mode slot. - Characters have a shipped mode fallback. Runtime uses
characters.default_mode_idwhen the conversation/package supplies no mode. A package with no matching Entry and no legacypackages.mode_idtherefore falls through to its bound (or BYOC-selected) character’s default mode before built-in DefaultSections. Every effective-variant, moderation, and reverse-dependency contract must include this seam. - Web currently loads soft-deleted modes.
fn_get_conversation_modedoes not filterprompt_modes.is_deleted, and stale conversation/package/default FKs can therefore keep a deleted mode active. This feature intentionally fixes that safety bug across Web/direct/Discord; it is separate from version-0 content compatibility. - A package-template gallery already exists. Reuse/extract its accessible Card-grid pattern rather than building a second bespoke gallery.
- CodeMirror 6 is already a dependency and implementation pattern. Refactor the reusable editor substrate from
RichContentCodeEditorbefore adding token highlighting/autocomplete; do not build a textarea/highlight-backdrop duplicate. ResizablePanelhas real consumers elsewhere, but not in this field-local editor. Keep the resolved authored Mode prompt inside the field's Preview view across breakpoints rather than introducing a page-level split pane.- The agent tool packs are shipped, not vision-stage.
package_authoring.propose_mode,experience_dry_run.preview_prompt_assembly, and project reads/readiness all inspect raw sub-prompt keys today and would misread a Document row. - An atomic mode-draft function exists.
fn_apply_mode_draftcreates a mode + prompts + project link for the agent tool packs. Extract its generic mode aggregate write before adding a second human-document orchestration. - Identity providers are currently type-exclusive.
characterresolves only standard characters, whilerulesandassistanthandle their matching types. The universal inlineidentityresolver must be additive and expansion-v1-only; changing or globally aliasingcharacterwould break legacy semantics. - Sub-prompts are genuinely N:M. Current child PUT can mutate a row through one parent even when other modes link it. Every new aggregate/compatibility mutation needs copy-on-write isolation and parent-version concurrency; permission-checking only the requested parent is insufficient.
- Mode sub-prompt proposals are shipped. The Document editor must preserve contributor proposal/review behavior rather than declaring document content non-proposable.
- Modes are reusable and packages have effective variants. Project membership is N:M grouping, not a runtime binding. Contextual lint, readiness, dry-run, moderation, and Test drive target a concrete package + selected character, with separately labeled profile Entry, package fallback, character default, or built-in result; they never union several modes into one fictitious package result.
- The old bundle document contains the remembered base/flavor intent, but not a usable implementation. Mode & Model Profile Bundles separates always-on base behavior from optional flavor sub-prompts, but its
is_bundle, profilebase_mode_id, intrinsicsub_prompts.is_flavor, sort-first resolver, and backend audit predate the shipped tree. This plan absorbs the intent into ordinary Model Profiles instead of creating a second bundle entity or fallback. - The resolver loses winning-profile provenance. It persists/returns a scalar mode id, and the How drawer infers the active Entry from that id. Two profiles may legitimately point at the same mode, so base/flavor composition requires an exact typed winner (
profileId,entryId, base mode/version), not reverse inference frommode_id. - Model-profile Entry parameter values are opt-in recommendations, not automatic resolution/package-start overrides. Entries store/display temperature, max tokens, top-p, and penalty recommendations. The shipped Apply settings UI exists, but it sends unknown
Llm.*keys instead of canonicalGeneration.*keys through several non-atomic requests; generic settings correctly rejects them. Replace that path with the atomic profile-plan selection transaction below. The same server transaction must enforcemode_enforcement='mandatory', which the generic conversation-mode update currently does not. Automatic Entry-parameter application during package/resolver creation is not part of this feature, and packagesettings_overrides_jsonmust use the exact allowlist in Packages §Package-safe settings defaults, which rejects everyGeneration.*/*Llm.*key so it cannot become an alternate silent-precedence path. - Workbench cannot reliably hydrate a reusable bound profile. Package save deliberately accepts owner, public, or project-available Model Profiles, but the profile-detail endpoint is owner-only and Workbench calls it directly, then silently falls back to an empty Entry list. Base/flavor UI needs a capability-scoped package/project-context read that proves the binding/context, returns safe Entry/flavor metadata and capability flags, and redacts prompt source independently; it must not broaden the owner edit endpoint.
- Public mode documentation is row-first and partly stale. The feature includes docs/knowledge migration; default creator guidance must teach Document authoring first and Advanced mechanics second.
Shared introspection semantics
One Core service parses saved modes or unsaved drafts and returns four distinct products. Its dependency identity is a catalogue descriptor id, not a bare string: ordinary row-provider descriptors and inline-token descriptors are separate namespaces even when their spelling matches. This is what lets inline {{identity}} be known while a legacy free-text provider_key='identity' remains unregistered and budget-inert.
- Declared dependencies — typed descriptors/raw-unknown records with canonical key, source kind(s), platform availability, and source spans for every nonempty row provider plus tokens found only in
expansion_version = 1templates. A v1 row provider and matching inline token can point to the same ordinary descriptor/cache entry; inline-only identity has its own descriptor. - Assembled dependencies — what the builder actually attempts:
- no mode or zero sub-prompts →
SystemPromptBuilder.DefaultProviderKeys; - nonempty mode → declared keys plus the automatic
journalfallback whenjournalis undeclared. - A nonempty keyless legacy row is not equivalent to zero rows; it gets its static text + journal fallback, not all defaults. This fixes an existing feature-state/budget bug.
- no mode or zero sub-prompts →
- Implied bindings — character identity/type/default mode, greeting scenario, every knowable lorebook source (package + selected character, while reader-persona lorebooks remain runtime-dependent), persona, platform/door availability, and the selected effective package variant.
- Findings — syntax, structural, compatibility, and contextual diagnostics with stable codes and source spans.
Effective package variant resolution
Step 0 is wider than "no usable preset model" today (knowledge review, 2026-09-29). The shipped resolver reads the model only from a preset the reader owns (
47_package_functions.sql:357-360), so a reader on a platform built-in — the default — lands on step 0 too, even when a matching Entry exists. Tracked with its fix shape in Model Profile Hybrid readiness § Open follow-ups; account for it when implementing this section.
The shipped * Entry-form fallback is currently unreachable, and the SQL substring branch accidentally treats %, _, and \ in an identifier as pattern metacharacters. Keep the two runtime seams explicit. Policy-aware fn_resolve_package_effective_mode resolves only the package layer:
- no usable preset model → nullable legacy
packages.mode_id(a wildcard means “any model,” not “no model”); - case-sensitive exact
model_identifier = preset.modelmatch (unchanged); - case-insensitive literal entry-identifier-contained-in-preset-model match (
position(lower(model_identifier) in lower(preset.model)) > 0), longest identifier first (same direction, without treating%,_, or\as hidden wildcards); - wildcard
*for a usable model; - nullable legacy
packages.mode_idwhen no bound entry matches.
The final conversation effective-mode resolver then applies the shipped outer chain using only existent, nondeleted candidates: valid conversation/package-layer mode → valid selected-character default_mode_id → built-in DefaultSections. Broken/deleted links produce a typed finding and are skipped, not served. The resolver accepts the concrete selected character because the SQL package-layer function cannot resolve a BYOC runtime choice. Readiness, dry-run, Test drive, moderation, and every Web/direct/Discord loader call this outer resolver (or a parity projection), never reimplement half of either chain.
Preset re-resolution has a separate shipped trap: a null package-layer result currently leaves the conversation’s previous auto-resolved Mode in place, so the outer fallback never runs. Policy 0 preserves that behavior for a valid nondeleted Base by recording policy0_retained_base: still automatic, Base-only, no selected Profile/Entry/Flavors, and eligible to attach an exact winner on a later relevant invalidation. The global deleted-Mode safety barrier is the explicit exception. Policy 1 adds a discriminated package-layer result (resolved with Mode/Entry/source, or valid_null; lookup/authorization/error are distinct failures). fn_reresolve_package_conversation_mode may set web_conversations.mode_id = NULL for policy-1 valid_null while retaining mode_is_auto_resolved=true, and for the explicit deleted-Mode invalidation path; errors/no-package never masquerade as a valid fallback or clear state. Golden transactions cover Entry → policy-0 retained Base → later Entry, and policy-1 Entry → package fallback → character default → DefaultSections and back, including deletion and rollback on lookup/error.
policy0_retained_base is emitted only from a previously automatic Entry-selected valid Base (or the rollout’s trusted old auto flag) whose winner can no longer be proved. A still-valid named package/character/built-in fallback keeps its own source. Follow selected model from a manual/legacy source performs fresh initial-style resolution and never relabels the arbitrary manual Base as auto-retained.
Within equal specificity, package_model_profiles.sort_order, model_profile_entries.sort_order, then their stable integer ids win; duplicate order values can never make the result nondeterministic. Multiple wildcards follow the same tie-breakers. Reads return every configured/fallback candidate with reachable/shadowed, source (profile_entry|package_fallback|character_default|built_in_default), and the model/preset/context that reaches it; only reachable candidates are called effective variants. The built-in fallback is explicit as entryId=null, modeId=null, modeVersion=null, usesDefaultSections=true. A bound character default is knowable; a BYOC character default is a runtime slot until a test/user character is selected. A shadowed duplicate or a package/character fallback shadowed for model-bearing resolution remains visible rather than being silently unioned or tested. The package-layer resolver and outer conversation resolver, readiness, dry-run, moderation labels, and mapped Sandbox test share golden cases for no-model, deleted/broken candidates, package/character/built-in fallbacks, BYOC context, %/_/\ literals, exact, overlapping substring, wildcard, duplicate order, and fallback ordering. Policy-0 packages retain the shipped profile matching/null-preservation rules for valid nondeleted candidates indefinitely, unless and until the owner explicitly opts the package into policy 1; consumers always expose which resolver-policy version produced a result.
Creator Workbench § “Model profile versioning — Pin on link, explicit upgrade” describes the intended future pin-on-link model, but the shipped schema/runtime still uses live profile links. This feature preserves those live links and uses reverse-package invalidation as the safety bridge. It does not pretend pinning exists. When snapshot pinning lands, pinned packages stop participating in live reverse invalidation until an explicit upgrade; that upgrade itself runs diff, Test drive, and publication review. That later migration supersedes this temporary live-link policy rather than contradicting it.
Model-selected base prompts and flavor overlays
The historical Mode & Model Profile Bundles proposal had the right product distinction but overloaded the word “base.” This plan pins three separate concepts:
- Base prompt — the existing
prompt_modeselected by an automatic winning Model Profile Entry or an explicitly selected compatible Entry. It is always active, owns identity and required behavior, and may be Document or Advanced with legacy/v1 rows.model_profile_entries.mode_idremains the DB/API compatibility field; creator UI labels it Base prompt — always-on instructions optimized for this model. This is a relational role, not a newprompt_modes.kind. - Flavor overlay — one optional, user-toggleable, profile-owned keyless System
sub_prompt. It adds style, tone, or genuinely optional rules compatible with every Entry/base in that profile. New flavors use expansion v1. Importing accessible legacy/v1 prompt text makes a private clone inside the profile aggregate; V1 never attaches an arbitrary row owned by another Mode/Profile. - Fallback — package-policy resolution followed by package → selected-character → built-in outer fallback. It is not a base prompt. Do not add the old proposal’s
model_profiles.base_mode_id. A*Entry is catch-all only under policy 1 after the package owner opts in; policy 0 deliberately keeps no wildcard.
Existing profiles have zero flavors and remain byte-identical. There is no is_bundle pseudo-type and no intrinsic sub_prompts.is_flavor: Flavor meaning/default/order belongs to its profile link, while the linked content row is structurally exclusive to that Flavor in V1. Reuse across packages comes from reusing the Model Profile; reuse from another prompt is explicit copy/import, not a hidden cross-parent reference.
Flavor validity and ownership
- The Base owns the one effective identity. A Flavor has
provider_key=NULL, fixed System role, andtarget_stage='classic_primary'. Inlineidentityand every current/future identity-family token are blocked; context lint validates the selected Base + character type exactly once. An imported row qualifies only when it is keyless System v0/v1, the caller may view/copy its source, and the server clones it before linking. V0 keeps legacy literal behavior plus the unchanged final lowercase{{char}}/{{user}}display-name substitution; V1 may use the supported non-identity inline-token catalogue. - Required mechanics, safety/policy, package correctness, Mature/NSFW behavior, merge behavior, enhance prompts, and summarization prompts belong in the base (summarization: transitional — per-Mode summary prompts are legacy until the Prompt Presets decoupling ships; see §Summary prompts below). Because arbitrary prose cannot be classified perfectly, these semantic rules are author guidance plus content-check/moderator findings—not deterministic save blockers. Structural identity/provider/role/stage rules are server-blocking. A platform safety filter is never a Flavor. If content needs several rows/roles or mode-level settings, create another Base variant.
- V1 allows at most 12 active Flavors, 4,000 characters per Flavor, and 20,000 characters across all active Flavor source in one Profile. Independent Flavors render as checkboxes. Mutually exclusive alternatives reference a Profile-owned group entity with stable UUID/key, user-facing label, and order; the drawer renders an accessible nullable radio group whose first choice is None — Base only. At most one group member defaults on, and enabling one atomically disables its peer. Every Flavor remains disableable.
- V1 Flavor runtime is deliberately Web + Classic only. Direct/Discord and Hybrid assemble the Base exactly as before and report the Flavor layer unsupported; they never apply a default-on Flavor without a control surface. Hybrid UI says Style & rules are available in Classic chats rather than promising a prose change the hardcoded v1 prose stage cannot honor. Future Beat/Prose/door-specific overlays extend
target_stageexplicitly. This is the natural point to also make Model Profiles hybrid-ready, not just Flavor-ready: Hybrid Pipeline's Model routing §as-built note shippedmodel_profile_entries.role(0=Primary/1=Beat/2=Prose) end to end through repo/API/Workbench, and since 2026-08-04 the hybrid runtime consumes role-tagged entries —fn_resolve_hybrid_role_modesresolves the pair-owner Profile once per turn, both legs take their Mode from its role-tagged entries (an entry matches a leg's settings-side concrete model and supplies that leg's Mode — it never supplies the model itself, so the contract phrasing here still holds), and a seeded "Authentic over Comfort" Profile pairs the two roles. See Model Profiles — Hybrid-Ready for the shipped contract. What remains for this doc's scope: extendingtarget_stagetobeat_direction/proseso Flavors can ride the same rail — that stays in-scope for the Prompt Presets implementation, with the companion doc owning the slicing and dependency ordering. - A profile gains Mode-style
allow_view_promptsgoverning its exclusive Flavor rows; each Base retains its independent Mode gate. Import requires source prompt-view/copy rights and creates a private clone, so profile visibility can never re-delegate another parent’s hidden prompt. Public cards/toggles expose Flavor label/description/default, never source text unless that layer’s own gate permits it.
Effective prompt plan and assembly
The package resolver returns a typed effective prompt plan, not just a scalar mode:
source (auto_profile_entry | manual_profile_entry | policy0_retained_base |
manual_mode | legacy_unprovenanced | package_fallback |
character_default | built_in_default | sandbox)
generationStatus (ready | ready_legacy_grandfathered | mandatory_no_match)
selectionVersion + resolverPolicyVersion
selectedProfileId? + profileVersion?
governingProfileId? + governingEnforcement?
entryId?
baseModeId? + baseModeVersion?
profileSnapshotId?
availableFlavors[] { linkId, rowId, enabled, effectiveOrder, groupSnapshot }
compositionFingerprint
presetId? + presetConfigFingerprint? + provider/model
effectiveGenerationSettings[] { key, value, source }
executionFingerprint
composition_source is a closed persisted enum, not a free-text diagnostic. Its nullable-field and compatibility projection contract is:
| Source | Required provenance | Flavors | mode_is_auto_resolved |
Preset/model change |
|---|---|---|---|---|
auto_profile_entry |
selected Profile + Entry + Base; Profile snapshot additionally required only on Web Classic | Exact selected Profile on Web Classic; none on unsupported surfaces | true |
Re-resolve automatically |
manual_profile_entry |
selected Profile + Entry + Base; Profile snapshot additionally required only on Web Classic | Exact selected Profile on Web Classic; none on unsupported surfaces | false |
Revalidate; mismatch returns to automatic resolution |
policy0_retained_base |
valid Base retained after a policy-0 automatic null/ambiguous result; no selected Profile/Entry | None | true |
Re-resolve on every relevant invalidation; attach a winner when one returns, otherwise keep the retained Base |
manual_mode |
nondeleted Base; no selected Profile/Entry | None | false |
Base stays sticky only where current lock/enforcement allows |
legacy_unprovenanced |
valid retained Base; no selected Profile/Entry | None | false |
Never guesses a Profile; follows the rollout grandfather rules below |
package_fallback |
valid legacy package Base; no selected Profile/Entry | None | true |
Re-resolve automatically |
character_default |
valid selected-character default Base + character provenance; no selected Profile/Entry | None | true |
Re-resolve automatically |
built_in_default |
baseModeId=null, usesDefaultSections=true; no selected Profile/Entry |
None | true |
Re-resolve automatically |
sandbox |
authorized forced Base + immutable Sandbox payload; no production Profile/Entry FKs | None, except a separately stored/labeled hypothetical draft set | false |
Frozen test selection; production resolver triggers ignore it |
governingProfileId is separate from selectedProfileId: a normalized default Profile can govern a no-winner fallback without becoming selected or donating Flavors. generationStatus=mandatory_no_match keeps the diagnostic outer fallback provenance visible but makes the plan non-runnable. A migrated compatibility exception instead persists ready_legacy_grandfathered, so its generation permission is unambiguous. Lookup/authorization failures are typed operation failures and are never persisted as a source/status.
resolution_stale=true is the sole transient relaxation of the live-id invariants after a selected parent/preset is soft- or hard-invalidated. Copied UUID provenance remains, nullable live ids may be absent/deleted, and no caller may treat the stored source/status as runnable. Every plan read, branch, or Send resolves that one conversation under lock first and either writes a valid closed state or returns a typed failure; it never serves stale prompt/settings data.
Only an automatic winner or deliberate manual_profile_entry on Web Classic contributes its exact selected profile’s snapshotted Flavors. The same two sources on Direct, Discord, or Hybrid retain exact selected Profile/Entry/Base provenance but require profileSnapshotId=null and availableFlavors=[]; an unsupported surface never creates a Flavor snapshot merely to prove provenance. Two profiles may select the same Base and still produce different Web Classic plans. Policy-0 retained Base, manual Mode, legacy-unprovenanced, package/character/built-in fallbacks, unsupported doors, and Hybrid have no active Flavors. Disabled, package-unavailable, deleted, or unsnapshotted Flavors contribute no parsing, provider calls, dependencies, feature support, or budget.
Composition is structural; {{flavor}} is not an inline macro and inserted content is never recursively parsed. Resolve the Base layer before looking at Flavors: a zero-row Base expands to the full existing DefaultSections, even when a Flavor is enabled. The composer then builds one explicit ordered stream:
- Base Mature/NSFW prelude, then the Base’s contiguous leading System rows;
- enabled Flavor System rows in effective order (current profile order for a draft/new snapshot; snapshotted order for an existing conversation);
- the remaining Base rows in their unchanged local order;
- one journal fallback only when the resolved Base + enabled Flavors declare none;
- unchanged global name substitution; then
- the Base’s
merge_consecutive_messagesbehavior.
Flavor insertion is immediately before the first non-System Base row, so the feature never manufactures a late System message in an Advanced multi-role plan; an all-System/Document Base therefore remains simply Base → Flavors. The composer assigns a composite ordinal and the downstream builder consumes that order without globally re-sorting raw SortOrder; normalized Base/Flavor local orders and stable link ids are final tie-breakers. Resolver ties likewise end with package_model_profiles.id, then model_profile_entries.id.
Base enhance/summarization configuration remains out-of-band exactly as specified for Sample assembly (summarization: transitional — legacy per-Mode fields until the Prompt Presets decoupling ships; see §Summary prompts). Version-1 provider memoization spans Base + enabled Flavors; version-0 Flavor text retains legacy behavior. Document shape remains exactly one mode-linked row because profile Flavors live outside prompt_mode_sub_prompt_links.
All introspection is plan-aware: saved/draft Sample assembly, feature state, budget, readiness, dry-run, moderation, Test drive, agent reads, and conversation stats use the same Base + enabled-Flavor plan. A default-off Flavor is still screened because a user can enable it. Redaction is per source: hidden Base/Flavor text is omitted while typed dependency/readiness data remains.
Four hashes/tokens remain distinct. compositionFingerprint is a pure structural-equivalence key: lowercase SHA-256 of RFC-8785 canonical JSON with fingerprintSchemaVersion=1 and an explicitly bumped promptAssemblyRevision over pipeline/door; the resolved fallback marker; Base assembly-affecting settings; the effective ordered template stream (role, provider key, expansion version, authored-content hash, composite ordinal); and the content hash/revision of every actually inserted code-defined synthetic section (Mature/NSFW prelude, zero-row DefaultSections, journal fallback framing). Row, Mode, Profile, Entry, and Flavor-link ids are deliberately excluded: two authorized cloned sources that produce the same structural stream hash the same, while their separate provenance fields remain distinct. The revision bumps for tokenizer/composer/name-substitution/merge semantic changes that source hashes alone cannot see. Conversation/snapshot ids, selectionVersion, automatic/manual/Profile provenance, group/default/display metadata that cannot change the already-enabled message stream, parent versions that changed only metadata, provider output, names, and other turn-dynamic values are also excluded. Thus the same effective composition hashes the same across conversations and after toggle-away/toggle-back, while a code-defined prompt change changes the hash. Expected source ids/parent versions remain separate CAS and audit inputs.
executionFingerprint hashes the composition fingerprint plus the accepted nonsecret LLM execution configuration: concrete preset id/config fingerprint, provider, model, generation values with their effective source, and pipeline allocation inputs. Secret/API-key material is never hashed, logged, or persisted. selectionVersion is the conversation CAS counter used by plan/toggle mutations. The reverse-impact fingerprint separately covers dependent entities/publication state and is never a turn cache key.
Stored conversation composition/execution fingerprints are last-materialized audit caches, never authority. At accepted turn start one database read transaction locks/validates the conversation, any stale selection, selected parents, concrete preset row, and effective user/conversation settings, then materializes one immutable execution plan: ordered Base/Flavor templates, provider/model/preset config, effective Generation values, allocation inputs, and a protected ephemeral credential value/handle. The transaction then releases; dynamic prompt providers fill that frozen structure, but no later settings/preset lookup may change routing or generation for that turn. Builder, eligibility/allocation, LLM client, budget, leak detection, and stats receive the same object/fingerprints, so a later Mode/Profile/preset/setting edit or preset hard-delete cannot produce “Base for model A, request to model B.” Stats copy scalar UUID/provenance values from the accepted object and have no live FK. A toggle returns a new selection version; the client includes its latest acknowledged version on Send, and the server freezes no older plan, so “next message” has a race-free meaning. Hide/delete takes effect at the acceptance boundary: every turn accepted after that commit omits the source, while a turn already accepted with a valid frozen plan may finish; V1 does not pretend it can revoke bytes already handed to provider work.
Defaults, overrides, and conversation state
model_profile_flavorsowns profile defaults. A sparse package-link override may hide a Flavor or change its initial default, but never mutate the profile or force the toggle on. Package overrides are surgical dirty fields in the Package Workbench’s one always-visible Cancel/Save form, never per-row immediate writes.- The first time a Web Classic conversation activates a given profile—including creation when it wins—the transaction inserts a profile-snapshot header even when the effective roster is empty, then materializes every then-available link including off states after package overrides. Child rows snapshot effective order, initial effective default, group UUID/key/label, target stage, and enabled bit; uniqueness is
(conversation_id, flavor_link_id). Direct, Discord, and Hybrid selection rows preserve the same Profile/Entry/Base provenance with no snapshot header or children; if a conversation later enters supported Web Classic through an allowed door transition, that first supported activation creates the snapshot then. - Flavor prompt content remains live-linked under the current reverse-impact bridge until profile/package pinning lands. A later hide or soft-delete suppresses a snapshotted link for every subsequently accepted turn; restoring/unhiding that same snapshotted link restores its prior state. A link absent from the snapshot never becomes toggleable by guessing its UUID.
- A model switch that resolves to another Entry in the same profile preserves choices by flavor-link id. The first visit to a different winning profile snapshots that profile’s then-current package-effective roster/defaults; per-profile snapshots are retained if the user switches back. Names never transfer state.
- Existing snapshots never silently absorb later additions/unhides/default/order/group edits.
effectiveRosterFingerprintis lowercase SHA-256/RFC-8785 over the currently package-available active Flavor link UUIDs plus effective initial default, normalized order, target stage, and group UUID/key/label. It deliberately excludes Flavor content, Flavor label/description, Entry recommendations, and other Profile/package metadata. Parent versions only invalidate the computed projection; they never trigger the notice by themselves. The drawer compares the current projection to the snapshot children: a newly available unsnapshotted link or changed default/order/group/stage on an available snapshotted link shows New or updated Style & rules choices are available — start a new conversation to use them. Hide/delete only suppresses and does not advertise a new choice. Restore/unhide of a previously snapshotted link with unchanged roster metadata restores its prior state without a notice; changed roster metadata still counts as an update. V1 has no in-place roster refresh. - That action is a package-aware Start new conversation flow, not the generic standalone New chat path or a branch. It starts from the package’s current bound character/greeting/persona/lorebooks/instructions/pipeline/locks, rechecks access/publication/enforcement, follows automatic model resolution, and creates a fresh Profile roster snapshot. The only conversation-scoped value offered for carry-over is the current concrete preset when it is still accessible/allowed; the confirmation previews the resulting preset → Profile/Entry → Base plus package character/greeting/persona and explicitly lists the reset state. Messages, manual Entry/Mode selection, Generation overrides, previously applied Entry recommendations, custom/user-added unlocked components or instructions, feature toggles, and old Flavor choices/snapshots do not carry. V1 does not carry a swapped/BYOC character through this action: it uses the current package-bound character and explains the change; when the package has none, the action is unavailable until the separate public-BYOC package-start contract exists. If the package is no longer usable, the action is disabled with the reason; generic New chat explicitly detaches package context and cannot be offered as the roster-upgrade action.
- Explicit normal-Mode selection records
manual_mode, detaches active profile/Entry/Flavors, and retains inactive per-profile snapshots for a later switch-back. A deliberate bound Entry selection recordsmanual_profile_entry; it is not misreported as the automatic resolver winner. - Replace the current mode-switch + invalid per-key settings loop with one atomic discriminated endpoint: Follow selected model re-runs and attaches the automatic winner; Use profile Entry validates a bound Entry plus a concrete owned/available preset whose actual model matches that Entry (and switches that preset atomically when needed); Use Mode detaches. If the current preset already matches, Just switch Base changes no preset or Generation rows—including any prior recommendation-sourced rows. If another preset is selected, Use model & Base selects it, removes only prior
profile_recommendationrows amongGeneration.Temperature,Generation.MaxTokens,Generation.TopP,Generation.FrequencyPenalty, andGeneration.PresencePenalty, and preserves user-authored conversation overrides; therefore preset values become effective only for keys without a surviving user override. Confirmation shows those effective values and which user overrides remain. Apply Entry recommendations performs that same cleanup, then upserts the Entry’s explicitly listed canonical keys asprofile_recommendation; it removes previously recommendation-sourced canonical keys now omitted, preserves user-authored keys not listed, and overwrites a listed user key only after the displayed confirmation. A later ordinary user edit changes that row’s source back touser. Partial preset/Base/provenance/override/Flavor application is impossible. - Explicit Entry compatibility uses the package’s exact policy predicate. Policy 0 accepts case-sensitive
identifier = preset.modelor the shipped case-insensitive PostgreSQLpreset.model ILIKE '%' || identifier || '%'expression—including its%,_, and\pattern behavior and no special*. Policy 1 accepts the same case-sensitive exact branch, then case-insensitive literal containment, while an identifier equal to*matches any nonblank usable model. An active, bound, accessible Entry that matches this predicate may be deliberately selected even when a different Entry shadows it in automatic ordering; Mandatory additionally requires it to belong to the governing Profile. Blank/unusable models, deleted rows, and merely similar nonmatches fail atomically. - The exact winning Profile supplies enforcement; when no Entry wins, the package’s single normalized default Profile supplies it (and no bound Profile means no Profile enforcement).
mandatorymeans generation requires a matching Entry from that governing Profile, arbitrary Mode detachment is forbidden, and an untested/no-winner model is blocked rather than silently using an outer fallback. A deliberate Entry under Mandatory must belong to that governing Profile and match the selected preset.recommendedrequires confirmation to detach;optionalpermits it.packages.mode_lockedhas higher precedence over manual Entry/Base/detach overrides, but it does not block creator-defined automatic re-resolution when the user changes model/preset, optional Flavor toggles, or applying settings to the unchanged active Entry. Enforce oneis_defaultpackage-profile link in SQL. - Conversation-level preset/plan changes use the same atomic transaction and may reject an invalid explicit request. User/conversation
Llm.PresetIdor model-setting insert/update/delete,llm_presetsmodel/config update/hard delete, preset-reference cleanup, and Profile/Entry invalidation must not be rolled back because one dormant package chat has no Mandatory winner: replace the shipped per-row resolver loops and best-effort post-commit sweeps with set-basedresolution_stale=truemarking inside the authoritative mutation transaction. The setting/preset edit commits, the active conversation is re-resolved after commit, and every stale conversation resolves under its own lock on next open/Send before allocation. Automatic sources—includingpolicy0_retained_base—re-resolve; an invalidmanual_profile_entryreturns to automatic resolution; a Mandatory no-winner persistsgenerationStatus=mandatory_no_matchand blocks only that conversation; no conversation preset override is invented. A policy-0 null keeps a valid automatic Base aspolicy0_retained_baseand can attach a later winner. A stale client selection version refreshes with no charge.manual_mode,legacy_unprovenanced, andsandboxfollow their table/grandfather rules. Follow selected model is the accessible reattachment path. - Selection creation/invalidation shares one
SelectionGraphTransactionfence;resolution_staleis an optimization signal, never the safety boundary. Branch, package restart/create, plan switch, toggle, turn acceptance, and every user/preset/package/Profile/Entry/Mode/character invalidator run atSERIALIZABLEwith retry on40001. Transaction-scoped advisory locks usepg_advisory_xact_lock(kindRank, internalId)and one global(kindRank,id)order: user, preset, package, Profile/Entry (including copied inactive snapshots), Base Mode, character, then conversation. A child/selection creator first reads candidate ids without row locks, restarts, acquires the complete source/candidate root set in that order, re-reads, then locks the conversation last; a changed set/winner rolls back and retries. An invalidator acquires only its known mutated root fence(s), already sorted, before scanning affected conversations and locks those conversations by id; it never later acquires a lower-rank fence. Thus a concurrent child must wait at a root fence and cannot commit outside the invalidator’s set. Open/branch/restart/Send still unconditionally revalidate source ↔ current model/preset/live parents even whenresolution_stale=false. This closes the child-insert/parent-delete phantom rather than hoping the stale marker catches it. - The discriminated writer is the only authority for selection fields. Every public compatibility path that can currently carry
ModeIdis retired or delegated: package conversation creation rejects a caller-supplied Mode and follows the package resolver; standalone creation may accept an accessible Mode but recordsmanual_mode; generic conversationPUTtranslatesModeIdto Use Mode withselectionVersion(or rejects the deprecated shape); and Send rejects its old per-messageModeIdoverride because a message cannot bypass the frozen plan. Drop/delegate obsoletefn_upsert_conversationsignatures; the migration-only variant is revoked from application roles and, when used by controlled import, must populate/backfill the closed state before the row becomes runnable. Preset compatibility writes only mark/re-resolve through the policy above. Repository/SQL permissions and guarded functions prevent any endpoint, trigger, old client, test primitive, or migration function from directly updatingmode_id, provenance, preset, or Flavor state as a partial runnable selection. - The How drawer shows the active Base/provenance read-only plus Style & rules for Web Classic. Independent choices are checkboxes; each group is a nullable radio group with None — Base only. Owner toggles are group-atomic and selection-version guarded, spend no Echoes, await the server before changing UI state, and say Changes apply to the next message. A 409 refreshes/announces the current plan with no partial visual flip. Read-only conversation viewers see active labels/state but no controls/source. No winner shows why styles are unavailable; zero/all-hidden rosters render a small EmptyState rather than a blank panel.
- A Mandatory no-match fails before allocation/LLM work and spends no Echoes. The How drawer/send surface shows This experience requires a supported model, lists the governing Profile’s supported Entry patterns, and opens Choose supported model (or Add/select a matching preset when none exists). Package-locked manual Entry/Mode actions remain visible disabled with Locked by this package explanation instead of disappearing.
Rollout never guesses old provenance from mode_id. Before Flavor writes are enabled, each existing mode_is_auto_resolved=true package conversation is recomputed under its stored package policy and current preset. A unique deterministic Entry result whose Base equals the stored Mode attaches as auto_profile_entry; only a Web Classic conversation also receives a Profile-snapshot header, even when the roster is empty. Direct, Discord, and Hybrid retain the exact Profile/Entry/Base provenance with a null snapshot and empty Flavor state. Otherwise, a provably equal live legacy-package/selected-character/built-in fallback receives that named source; only a still-valid old automatic Base whose policy-0 provenance cannot be proved (null, Base mismatch, or duplicate-Base ambiguity) becomes Base-only policy0_retained_base, preserving automatic re-resolution without inventing Flavors. A later preset/model/Profile invalidation may attach a then-current winner. Lookup/authorization/database errors leave the row unmigrated and retryable rather than being mislabeled as a valid source. Existing mode_is_auto_resolved=false rows with a valid stored Mode become manual_mode; a null/deleted stored Mode is classified by the valid outer fallback actually retained (character_default or built_in_default) rather than violating the source contract. legacy_unprovenanced is reserved for genuinely nonautomatic imported/old selections whose manual provenance cannot be proved. This compatibility backfill never changes the selected valid Mode, generation settings, publication state, or package resolver policy; deleted candidates remain the named global safety exception.
Deployment is two-gate and idempotent: add source/status/live+copied-id columns nullable with Flavor writes/runtime reads disabled; run and retry the set-based backfill until every nondeleted conversation has a valid closed tuple and zero migration errors; validate constraints; then set required fields NOT NULL/CHECK and enable the new readers/writers. There is no generic database default that can silently label a new runnable conversation—the guarded creation transaction supplies its exact source/status. A failed/unclassified row remains on the legacy reader during the gate and cannot partially acquire Flavors.
When a migrated policy0_retained_base, legacy_unprovenanced, or manual_mode state would be rejected immediately by the package’s then-current Mandatory enforcement or Mode lock, the backfill sets selection_enforcement_grandfathered=true and generationStatus=ready_legacy_grandfathered. Grandfathering permits only the retained, valid, nondeleted Base to keep generating Base-only; it grants no Profile/Entry claim, Flavors, recommendations, or ability to change Mode/Entry/conversation preset in defiance of current rules. User-global preset edits do not silently clear it. Every package lock/enforcement invalidation and each open/Send recomputes whether the exception is still needed: if a real winner attaches or the retained state is now normally allowed, clear the flag and set ready while retaining the appropriate automatic/manual provenance; never create a new grandfather after rollout. The first deliberate conversation plan/preset change must pass current enforcement and atomically clears the flag on success; Follow selected model is the primary recovery. A deleted/broken Base still crosses the global safety barrier and re-resolves/blocks. New/package-restarted conversations never receive the flag; a branch copies it only when normalization says it is still required for the same existing story fork.
mode_is_auto_resolved remains only a compatibility projection and is written in the same transaction as composition_source: true for auto_profile_entry, policy0_retained_base, package_fallback, character_default, and built_in_default; false for manual_profile_entry, manual_mode, legacy_unprovenanced, and sandbox. No endpoint/trigger may update one without the other. Preset/profile triggers branch on the typed source—not the old boolean alone—so a policy-0 retained Base remains automatic, a manual Entry can be revalidated, and a detached Mode stays sticky where allowed.
Branching first locks the source and resolves any resolution_stale state plus no-longer-needed grandfather flag; an unresolvable source fails without creating a child. It then copies package_id and package launch context, normalized selection source/version, still-required grandfather state, exact copied/live Profile/Entry/Base provenance, every Profile-snapshot header/child state, and the last materialized fingerprint in the same transaction, setting the child resolution_stale=false. The child recomputes its own authoritative fingerprints before its first turn. A package branch remains a package conversation and preserves the frozen roster; a standalone branch remains standalone. Sandbox conversations are explicitly non-branchable. The function never silently detaches, adopts newly added Flavors, or copies Profile state into a context that cannot support it.
V1 findings:
| Code | Severity / blocking | Meaning |
|---|---|---|
empty_document |
error / block | Document row contains no meaningful text |
missing_identity |
error / block in Document editor | No identity-family value node at all |
duplicate_identity |
error / block in Document editor | A character type would receive its definition more than once (second identity, or identity mixed with a type-specific token) |
conditional_identity |
error / block in Document editor | Identity value is conditional rather than top-level/unconditional |
partial_identity_coverage |
error / block in Document editor | Type-specific identity coverage leaves at least one character type without a definition |
misplaced_type_identity |
error / block in Document editor | A type-specific identity token sits inside an unrelated conditional and counts for nothing |
content_without_provider |
error / block in Document; warning in Advanced | {content} has no ordinary row provider |
unknown_token |
warning | Unknown token remains literal |
unbalanced_conditional |
error / block | Conditional renders literal |
mismatched_conditional |
error / block | Open/close names resolve to different canonical descriptors |
nested_conditional |
error / block | Nested conditional renders literal |
unknown_conditional |
warning | Unknown conditional renders literal |
legacy_alias |
info | Accepted alias such as memory; canonical spelling suggested |
legacy_token_in_upgrade |
warning / confirmation | A version-0 row contains new inline-token-looking text (excluding already-active char/user) before explicit upgrade |
unknown_provider_key |
warning (Advanced); block in agent staging | Ordinary free-text key is absent from the selected door’s registry; existing/imported v0 rows remain savable |
identity_without_character |
contextual error / Test-drive blocker | Package has no character while character_locked=true, or its stored character binding is deleted/broken; package access may legitimately encapsulate a creator-private bound character |
test_character_required |
contextual info / action | Package has no character and character_locked=false; valid BYOC remains publishable, while Sample/Test drive asks for a conversation-only test character |
identity_type_mismatch |
contextual warning (Advanced) | Type-specific identity token does not match the selected character type |
knowledge_without_lorebook |
contextual nudge | Selected package + selected character supply no lorebook; reader-persona lorebooks may still appear at runtime |
persona_without_source |
contextual info | Selected package has no persona template; reader persona may still resolve at runtime |
scenario_without_greeting |
contextual nudge | Selected Web package has no greeting/scenario |
platform_unavailable |
contextual info | Token has no provider on the selected door (v1: persona/scenario/journal on Discord) and will resolve empty |
tracker_without_explanation |
contextual info | Selected context has an active bound tracker, but the mode has no ordinary tracker explanation row/hook; tracker runtime remains enabled |
shadowed_model_mapping |
contextual warning | Model-profile entry can never win under exact/substring/wildcard priority |
model_bearing_fallback_shadowed |
contextual info | A reachable wildcard shadows the outer fallback chain (package mode → selected-character default → built-in) only for usable-model resolution; no-model still follows that chain |
broken_mode_binding |
contextual error | An Entry/package/character/conversation points to a missing or soft-deleted mode; resolvers skip it and surface the next valid fallback |
flavor_identity_forbidden |
error / block | Optional flavor declares an identity-family provider/token; identity must stay in the always-on base |
flavor_shape_forbidden |
error / block | V1 Flavor row is provider-keyed, non-System, outside classic_primary, cross-parent linked, or tries to own mode-level settings |
flavor_group_default_conflict |
error / block | More than one flavor in an exclusivity group would default on after package overrides |
broken_flavor_binding |
contextual error | Flavor link or referenced row is inaccessible, missing, deleted, or invalid; it is never assembled |
flavor_limit_exceeded |
error / block | Profile exceeds 12 active Flavors |
flavor_size_exceeded |
error / block | One Flavor exceeds 4,000 characters or active Profile Flavor source exceeds 20,000 characters |
flavor_required_behavior_suspected |
warning / publish-review signal | Content appears to carry required mechanics/safety that would be unsafe to toggle; move it to Base. This semantic classifier never substitutes for structural checks or moderation |
flavor_unsupported_surface |
contextual info | Flavors do not execute on this door/pipeline in V1 (Direct, Discord, or Hybrid) |
profile_flavors_without_winner |
contextual info | No Entry from this profile wins, so none of its Flavors apply; under policy 1 a * Entry can supply catch-all after owner opt-in |
manual_entry_model_mismatch |
contextual error / block | Explicit Entry does not match the selected concrete preset/model |
mandatory_profile_no_match |
contextual error / generation blocker | Governing Mandatory profile has no matching Entry for the selected model |
profile_flavor_snapshot_stale |
contextual info | The conversation keeps its frozen roster; a new conversation is required to receive later choices |
Server-side save, import, copy, agent staging, and proposal apply all use the same parser/validator. UI lint is never the only guard.
Introspection seam roster
| Consumer | Current failure | Required integration |
|---|---|---|
SystemPromptBuilder / PromptContextManager |
Inline {{journal}} duplicates fallback; zero-row Base fallback can disappear when Flavor makes the composite nonempty; downstream global SortOrder can interleave layers |
Resolve Base authored-vs-DefaultSections first, insert Flavors at the leading-System boundary with composite ordinals, decide journal over the composite, and consume that final order without a second raw-order sort |
WebChatFeatureStateService |
Empty raw key set is mistaken for zero prompts; tracker is incorrectly mode-locked; enabled flavors are invisible | Consume plan-assembled known descriptors + explicit prompt-count/layer state, but derive tracker availability from bindings/toggle and expose row prose separately |
ConversationBrowseRepository |
Budget/feature flags read only base rows and always count character/scenario/persona | SQL/C# projection of typed effective-plan dependencies: enabled flavors count, disabled flavors do not; universal identity counts for every character type; character/rules/assistant only for their matching type; unknown legacy identity stays inert |
prompt_mode_view and API projections |
Cards/workbench/model-profile picker show no inline dependencies | Add typed dependency DTO; retain derived provider_keys only as compatibility display data |
| Mode copy/export/import | Editor/expansion versions are lost; copy can read hidden prompts; writes are non-atomic | Enforce prompt-content access, preserve both discriminators, validate, and write through the aggregate transaction |
Package resolver / fn_get_conversation_model_profiles |
Returns/infers scalar mode id, so duplicate base ids can select the wrong profile/Entry | Return/store exact winner provenance + ordered flavor plan and composition fingerprint; never reverse-infer Entry from mode id |
| How drawer Entry selection | Switches mode, then writes invalid Llm.* keys through several requests |
One atomic select-plan transaction; optional overrides use canonical Generation.*, and direct Mode selection detaches profile flavors |
| Workbench bound-profile hydration | Package/project may legitimately reuse a non-owned profile, but owner-only GET /creator/model-profiles/{id} fails and the client substitutes entries=[] |
Add a context-bound read DTO authorized through the requested package/project relation. Return Entry/base labels, flavor descriptions/defaults/effective package overrides, exact versions, and capability flags; include raw prompt source only under its own prompt-view grant |
ProjectPoolReadService |
Reads only the stale direct package mode | Enumerate every Model Profile Entry, bounded Flavor default/maximum envelope, and package/selected-character/built-in fallback; label each plan/context and introspect separately rather than expanding an exponential combination set |
ExperienceDryRunService |
Reads only the stale direct package mode/raw keys; package can_view can expose prompt-hidden content |
Assemble each effective base + enabled-flavor plan separately and never union candidates. Gate each raw source; otherwise return typed readiness with contentRedacted=true. Admin moderation is the privileged exception |
package_authoring.propose_mode / IComposerStaging |
Agent staging only takes row-shaped legacy drafts | Carry editor kind + per-row expansion version; validate with the shared service |
| Share and sub-entity proposal apply | Can mutate shared/reviewed rows through one parent | Move mode-proposal apply to a C# transaction: lock proposal+parent, project, Core-validate, COW-write, publication transition, version bump, mark applied |
| Character/profile/package moderation/check fan-out | Profiles screen metadata only; character/package checks omit default/profile/flavor prompt dependencies | Include every configured base and every user-enableable flavor (default-off included), plus package/character fallbacks. BYOC user-selected private components stay user context |
| Saved preview/copy access | Generic can_view can reveal hidden prompt text |
Reuse the prompt-content visibility gate (allow_view_prompts or explicit grant/owner), not entity visibility alone |
PromptLeakDetectionStage / message stats |
Cache/telemetry identifies character + scalar mode only | Key leak sources and telemetry by composition fingerprint; include enabled creator flavor text, exact profile/Entry, and flavor ids |
| Web/direct/Discord sub-prompt loaders | Expansion version is absent and a naïve shared loader could apply default-on Flavors where no controls exist | Add ExpansionVersion everywhere; only the Web Classic immutable turn-plan wraps contextual layer=base|flavor. Direct/Discord and Hybrid deliberately load the Base-only plan in V1 |
fn_mode_assembled_dependencies(mode_id) remains the context-free base-mode grammar projection and returns descriptor id/canonical key/source mask/known state rather than an ambiguous string set. Effective-plan introspection composes that result with only the enabled flavor rows, then decides journal fallback once over the combined set. A parity suite pins namespaces, aliases, disabled-flavor absence, zero-row behavior, fallback, and version gating against C#.
Engine implementation (Core)
- Extend
ISubPromptwithExpansionVersionand extendPromptKeyCatalogwith palette/token metadata. - Extract the duplicated identity formatter, then add an inline-only universal identity resolver. Extract the current row-provider logic into a resolver that composes catalogue alias/gate/status/mock/platform behavior; version-1 row providers and inline dependencies share memoization while version 0 does not.
- Leave the version-0 content/role/order branch structurally unchanged, including unknown
identityremaining skipped. The sole intentional legacy metadata change isjournal.IsStatic: true → false; regression tests pin all other fields. - For version-1 rows, tokenize the authored template into text/token/conditional nodes, collect canonical dependencies, resolve each once, then render without rescanning inserted values.
- Derive
IsStaticfrom the row provider plus parsed inline dependencies. Any dynamic dependency makes the complete row non-static. Fixjournal.IsDynamicin the same pass. - Apply the unchanged global
{{char}}/{{user}}replacement after row rendering. - Add a plan composer that first resolves authored Base rows vs zero-row
DefaultSections, then inserts Web Classic Flavor rows at the leading-System boundary with composite ordinals, emits layer provenance, shares v1 provider memoization, and decides journal/merge once. It never mutates the Base aggregate, globally re-sorts raw local orders, or invents aflavorinline token. - Expose parsing/introspection/composition behind narrow Core interfaces so WebChat, Database services, ServerAPI, AuthService’s MCP door, and future engine hosts share behavior without referencing endpoints.
- Implement a TypeScript syntax parser/key extractor for CodeMirror/local lint using the catalogue DTO, with the same golden grammar/span fixtures as C#. SQL key extraction runs the deterministic subset of that corpus.
The red/green seam fixture covers four different states:
- no mode / zero rows → default keys;
- a nonempty keyless legacy row → static + journal only;
- an inline Document row containing identity/knowledge/summary/journal → exactly those assembled descriptors, journal once;
- a mixed Advanced mode with one legacy row and one inline row → both semantics coexist.
- zero-row Base + enabled Flavor → full
DefaultSectionsfirst, then the Flavor with no lost identity/dependencies; an Advanced System→User→Assistant Base inserts Flavor before the first non-System row; zero/enabled/disabled/grouped/deleted Flavor fixtures pin exact composite ordinals/dependencies/fingerprint, and zero Flavors equals the pre-feature assembly.
Sample assembly and lint
This assembly contract remains backend substrate for lint, diagnostics, and Test drive. It is not rendered inside the Mode prompt field: that Preview shows only the resolved content of the currently authored prompt row.
One Core result, two representations
The assembly service returns:
- Source sections — per authored sub-prompt, with
layer=base|flavor, flavor link/label when applicable, role, order, provider key, expansion version, and rendered sample content; and finalMessages[]— the canonical ordered role/content/staticness sequence aftermerge_consecutive_messages.
The existing systemPrompt + injectedMessages fields remain temporarily as explicitly lossy compatibility projections for old modals; they cannot represent an interleaved System → User → System sequence and are never the new editor’s source of truth.
This pane is deliberately prompt-plan assembly, not a claim to show the complete provider request. With no profile context it shows the base mode alone; with a concrete winning Entry it includes the base Mature/NSFW prelude, base rows, selected enabled flavors, inline/provider mocks, composite journal fallback, global names, and base merge behavior. Because Enhance Prompt placement depends on message history, the response exposes the base’s separate typed enhancePlan, not a fabricated position in finalMessages[]. Summarization prompts run in separate model calls and are labeled out-of-band. Conversation custom instructions, pacing, target-word directives, security directives, tracker history, live retrieval, and Hybrid’s hardcoded prose-stage rebuild are excluded. The field Preview itself contains only the resolved authored prompt; boundary guidance belongs with Test drive and does not add a toolbar hint or banner inside Preview.
Endpoints
GET /api/creator/modes/{id}/preview— saved mode, real mode-assembly rules, catalogue mocks,finalMessages[], typed source sections, and the compatibility projection. It requires the same prompt-content gate as/prompts/view; generic entitycan_viewis insufficient when prompt text is hidden.POST /api/creator/modes/preview-draft— unsavededitorKind, rows,nsfwEnabled,mergeConsecutiveMessages, and enhance fields, plus optionalmodeIdfor authorization/context only, sample names, platform door, Classic/Hybrid label, and one of two mutually exclusive context shapes:- a persisted package effective-variant reference; or
- an
entryDraftContextcontaining authorized package/profile ids plus the staged model identifier, sort order, parameters not automatically applied by resolution, base selection (currentDraftor a saved mode id), complete staged flavor links, and selected enabled flavor ids. This simulates plan reachability without persisting it, returnsentryRecommendationsApplied=false, and labels results Hypothetical — Entry/profile not saved.
Saved-mode draft preview requires mode edit/prompt rights. Either context independently requires package/project visibility and validates package/profile membership (or an authorized parent draft that is staging that binding); a saved mode selection also requires can_use. Inaccessible, mismatched, nonexistent, and inaccessible-private identifiers collapse to the established non-leaking 403/404. The endpoint returns the same assembly DTO, enhancePlan, and findings. A draft Entry can drive Sample lint and, after Mode Save, the explicitly isolated package-context test; it is never eligible for mapped Test drive until Entry Save makes the mapping real.
POST /api/creator/model-profiles/preview-draft— complete staged profile flavor aggregate + one staged/saved Entry, concrete model/package/character context, and enabled flavor ids. It uses the same plan composer, returns the exact winner/provenance/fingerprint, and never persists. Profile edit plus prompt-content capabilities are enforced per referenced base/flavor source.
The Mode prompt field labels the alternate view Preview and renders only the resolved authored prompt text using example values. It contains no nested tabs, headings, cards, role/status badges, source metadata, Mature prelude, journal fallback, Prose voice row, or Beat handoff. Actual pipeline behavior belongs to the separate post-save Test drive action.
Draft preview constraints:
- 10,000-character document maximum, matching mode import limits.
- Debounce around 400–500 ms; cancel the prior request and ignore stale sequence numbers.
- Pure assembly only — no LLM, embedding, Echo spend, or persistence.
- Rate-limited like other creator reads.
- The TypeScript parser continues syntax highlighting/source-span lint during a network failure; provider/context findings remain last-known and visibly stale. Failure never blocks typing.
- With a concrete character context, mocks obey the same character-type gates as runtime. A valid BYOC context accepts a permitted
testCharacterIdfor preview only, setstest_character_requireduntil selected, and never mutates the package.
Aggregate lifecycle and structural safety
Shared atomic write substrate
Extract a generic aggregate mode writer from fn_apply_mode_draft before adding the human flow. It must support:
- create/update mode metadata + an arbitrary ordered linked-row aggregate in one transaction, with Document shape as the one-row specialization;
- presence-based/surgical field semantics (omit = preserve, empty = clear);
- an omitted row collection preserving current rows, while a present complete collection is authoritative for row create/update/unlink/order and updates only changed records;
- optional controlled comment settings in the same transaction; create defaults apply only when that field is omitted;
- optional project-item link in the same Workbench orchestration;
- rollback of all rows/links when validation or any write fails.
Both Document and Advanced UI Save use that aggregate operation, so the shared shell has one atomic Save/Cancel contract. Existing child-row endpoints remain compatibility surfaces for share/proposal and other sub-entity flows; they become editor/expansion-aware and delegate to the same structural validator instead of defining a second mutation policy. The existing generic PUT /api/entities/modes/{id}/comment-settings also delegates to this parent-lock/CAS transaction for modes, requires expectedVersion, bumps once, and retains its owner-only authorization; it cannot race or overwrite an aggregate Save.
Concurrency, retries, and row identity
- Create requires a caller-generated draft UUID in
Idempotency-Key, scoped to user + mode-create operation and retained across response-loss retries. After authorization, an exact replay is returned before mutable quota checks; the same key with a different canonical payload returns 409. - Update requires
expectedVersion. The writer locksprompt_modes, compares the current version, returns 409 with fresh version metadata on drift, and bumps the parent once on success. Every child/share/proposal/agent compatibility mutation uses the same lock and bump so it races safely with aggregate Save. - Existing row UUIDs in a submitted aggregate must already be linked to the target mode. New rows carry unique client temporary IDs and no server UUID. Duplicate IDs, foreign/unlinked UUIDs, and repeated links are rejected; the JSON array order is authoritative and the server normalizes link order to
0..n-1. V1 has no “attach arbitrary existing prompt” operation. - Semantic edits (content, name, role, provider key, or expansion version) to a row with another parent are copy-on-write: clone the row/content for this mode and relink atomically. Unlink/delete never destroys another consumer; an unlinked row is physically removed only when it is private, actor-owned, and has zero links. Document rows are always exclusively linked, cloning during Advanced → Document conversion when necessary.
Current prompt reads are paginated, so they cannot be the source for an authoritative replacement list. GET /api/creator/modes/{id}/edit-aggregate returns the complete ordered linked-row set, parent version, and an opaque rowSetToken bound to the mode id/version and every linked row id/order. The share edit-context returns the same complete permitted row set/token. An update with rows present must include the matching token; a token from another mode/capability, or any difference between the current server row set/order and the set/order encoded by that token, returns 409 without mutation. When the token still matches, omission from the submitted authoritative list is an intentional unlink/delete. Metadata-only updates omit rows and need no row token; creates have no pre-existing token. Tests include an Advanced mode beyond the legacy page size so unseen rows can never be deleted accidentally while explicit deletion still works.
Model Profile Flavor editing follows the same complete-set rule. Its edit aggregate returns parent version + complete Entries + groups + Flavor links/exclusive rows + profileSetToken; the profile form stages metadata/groups/Flavors under one always-visible Save/Cancel pair. Entry forms may remain their separate parent-owned Save, but every Entry/group/Flavor/Base/link mutation locks and bumps model_profiles.version once. Aggregate writes send both complete active groups[] and flavors[] or neither; metadata-only writes omit both. restoreGroupUuids[] / restoreFlavorUuids[] are explicit, and an omitted persisted active UUID under the matching token means soft-delete. New/imported Flavor rows are created inside this transaction and must have exactly one active model_profile_flavors parent and zero Mode/other-profile parents; import copies authorized text/version rather than attaching the source row.
Create idempotency adds immutable prompt_modes.create_payload_hash CHAR(64) beside the existing scoped idempotency_key. It stores lowercase SHA-256 of RFC 8785-canonical JSON projected from the validated create DTO: field presence is preserved, object keys canonicalize, row array order remains significant, and controlled comments + project link are included; headers, authorization context, and other transport-only data are excluded. The hash is retained with the soft-deletable mode. An exact replay returns the same resource id with its current authorized representation; it does not promise a byte-identical historical response after later edits. A different hash always returns 409, so comparison never depends on the now-mutable aggregate.
Model Profile aggregate creation and Entry creation use the same caller-retained Idempotency-Key + immutable canonical payload-hash rule, scoped respectively to owner/profile-create and profile/Entry-create. New group/Flavor client temporary UUIDs are part of the canonical create payload and persisted as their public UUIDs, so an exact replay returns the original aggregate without duplicating children; same key/different payload is 409. Profile/Entry updates use parent version CAS rather than pretending a stale post-commit retry is a second success—the client refetches the aggregate after an ambiguous response.
The writer invokes the existing authorization, creator-count limit, review-lock, publication/scheduling, visibility, automatic publish-content checks, project membership, and comment-default rules; extracting the transaction does not bypass or reimplement those gates. Authorization is field-scoped: a forbidden field that is present fails, while omitting owner-only comment fields or any other ungranted field does not block an otherwise permitted prompt/metadata edit. Existing can_edit rights to visibility/scheduling/allow_view_prompts remain intact. The creator-facing Content pre-check remains advisory over the last-saved entity and never gates ordinary Save. While dirty it is disabled as Save to check and focuses the footer Save; any edit clears the prior result, and a completed result is displayed only while its returned mode version still matches the saved aggregate. A changed effective prompt is a significant publication mutation: pending review remains locked until withdrawal; a public mode is atomically unpublished/approval-invalidated and its owner notified when the initiating actor is not the mode owner. Only an owner-authored save may enter that owner’s existing verified auto-publish flow, and only after the changed aggregate passes it again. Share/proposal/agent/child endpoints cannot silently change reviewed live text.
Publication impact follows reverse dependencies through one shared EffectiveModeDependencyImpactService, not endpoint-specific fan-out. It classifies and fingerprints dependent characters and packages that are already publication-bound: public, pending review, approved for later publication, or scheduled. Draft-private dependents are reported but need no immediate transition; their next publish check must use the current effective fingerprint.
The service runs for every mutation that can change a character/package runtime winner or previously screened material:
- behavior-significant mode changes: row membership/content/provider/role/order/expansion, Mature/NSFW behavior, merge settings, enhance text/role/interval/at-end, and summarization prompts (the last a transitional trigger — it drops out of this list when the Prompt Presets decoupling retires per-Mode summary prompts; see §Summary prompts); plus mode name/description because package reads and package moderation expose/screen linked private-mode metadata;
- mode soft-delete/restore;
- Model Profile Entry create/delete/reorder or update of its model identifier / selected Base. Parameter-only Entry edits still use Profile CAS and are offered through Apply Entry recommendations, but are not automatic reverse-dependency changes until explicitly applied;
- model-profile Flavor create/import/edit/delete/restore/reorder/default/group/stage changes, plus its exclusive row content/expansion changes;
- model-profile name/description, prompt visibility,
mode_enforcement, and soft-delete/restore; - package flavor availability/default overrides;
- package↔profile bind/unbind/reorder;
- legacy
packages.mode_id, boundpackages.character_id, orcharacter_lockedchanges that alter fallback reachability; and characters.default_mode_idchanges plus character soft-delete/restore when that default can feed the character itself or a bound package.
Comments, tags, editor_kind, and row display-name-only changes are not reverse-dependency changes because character/package runtime/read/moderation does not consume them. Public mode tags/visibility and other public metadata still follow the mode’s own existing publication-review policy; that direct-mode classification is separate from consumer invalidation. Admin hard-delete/cascade is blocked while publication-bound dependents exist unless it explicitly executes the same impact transaction.
Each guarded mutation returns categorized counts by entity type + publication state + same/cross-owner, plus a dependency fingerprint. Save requires explicit acknowledgement, locks the mutated aggregate and affected characters/packages, recomputes the fingerprint, and returns 409 on drift. This impact fingerprint covers Mode/character/package/Profile parent versions, exact winner provenance, selected-character default link, ordered mappings/Flavor/group ids/package overrides, resolver policy, and sorted dependent ids + moderation/publication states; it is not the runtime composition hash. The same transaction withdraws stale review/approval/schedule state, unpublishes live dependents, and notifies owners. A cross-owner dependent is never auto-republished by the initiating actor’s verification; its owner must inspect the deterministic diff/check results, acknowledge, and publish again. Test drive is strongly offered but never a restoration gate. Same-owner dependents may use the existing explicitly acknowledged verified-creator recheck/auto-publish path after all checks pass.
Model Profile Entry/group/Flavor writes use expectedProfileVersion and bump the parent once. Under the lock, Entry Base references require fresh can_use (prompt visibility is independent because an encapsulated Base may remain usable); inaccessible/nonexistent UUIDs collapse to the normal non-leaking response. Flavor rows are created exclusively inside the aggregate; import requires source prompt view/copy and clones, so a leaked private row UUID can never be wired into a Profile. Profile saves re-resolve affected automatic/invalid-manual-Entry conversations, invalidate cached composition hashes, and leave authoritative turn fingerprints to the frozen-plan composer; failures roll back the Profile mutation.
Character create/default-mode changes similarly resolve the target under the character write/lock and require fresh mode can_use; inaccessible and nonexistent UUIDs share the same non-leaking failure. Publication audit treats an existing inaccessible/deleted default link as broken and withholds publication until the owner selects an authorized mode or clears it. Consumers of an otherwise valid public character need only character/package access—not separate prompt visibility for its encapsulated default mode.
Mode soft-delete is a guarded impact transaction, then a read-side correctness barrier: every resolver/loader excludes the deleted row for every turn accepted after commit even if an FK remains; an already accepted immutable turn may finish its frozen valid plan. Auto-resolved Web conversations currently holding that Mode are recomputed through their package policy and outer character/default chain; an explicit/direct conversation reference is cleared to let the outer fallback run. Direct/Discord persisted selections are invalidated equivalently. Lookup/error rolls back rather than being treated as fallback. Restore is also impact-guarded and becomes eligible only through normal resolution; it never resurrects a cleared explicit conversation selection. Tests cover Entry, package fallback, character default, explicit conversation, acceptance-boundary delete, restore, and failure rollback.
Resolver-correction rollout (no retroactive re-audit)
The corrected extractor adds character default modes and every profile-entry mode to what automated checks/moderator views can see, closing a gap where that content never fed a check dimension. That gap is not the same as "unscreened," and it is not treated as one here: the manifesto guarantee that every public character is reviewed by a human already covers every publication-bound character and package live today, including whichever mode it currently resolves to. A retroactive mass audit or unpublish of existing content is not needed. Extending the extractor is forward-looking coverage for future review cycles, not a correction of an unsafe backlog.
packages.mode_resolution_policy_version SMALLINT NOT NULL DEFAULT 0 exists solely for resolver-behavior compatibility, independent of moderation: fixing the substring/wildcard bug can change which entry wins for a package whose owner never asked for wildcard matching. Policy 0 preserves the shipped resolver indefinitely for existing packages — no expiry, no forced transition, no review gate. New packages create at policy 1. An owner who wants wildcard/longest-literal matching opts a package into policy 1 through a normal Workbench edit; that opt-in is just another mode-affecting mutation and flows through the existing ongoing EffectiveModeDependencyImpactService like any other change, with no separate audit workflow. There is no characters.mode_dependency_policy_version field — nothing needs to be marked as audited.
Deploying the corrected extractor, reverse-impact service, and policy-aware resolver needs no migration choreography: existing entities keep policy 0 and their current behavior unchanged; nothing is unpublished, queued for re-review, or monitored as part of shipping this feature.
Mode proposal apply moves out of the monolithic SQL branch into a C# transaction: lock proposal + parent aggregate, verify expected version and actor rights, project the proposed result, run Core validation, perform COW aggregate mutation + publication transition, mark the proposal applied, then commit. Pre-validating outside the transaction is not sufficient.
Enforced Document shape
For editor_kind = 'document', the server enforces exactly one linked sub-prompt:
- role = System;
- provider key = null/empty;
- expansion version = 1;
- nonempty, valid content;
- complete identity coverage (exactly one top-level/unconditional simple universal
identityvalue node, or exactly-once type-specific coverage fromcharacter/assistant/rules) and no{content}; - an exclusively linked row.
Generic prompt POST/DELETE refuses structural mutation of a Document mode. PUT may update the existing document only through shared validation. Share-token edits and approved sub-entity proposals use the same rule.
Copy, import/export, and editor switching
- Copy preserves
editor_kindand each row’sexpansion_version. - Copy first enforces source access: the caller is an owner/entity editor, or has entity view plus prompt-content visibility through
allow_view_prompts/an explicit grant. V1 adds no separate copy flag. Knowing a private UUID or viewing a public card with hidden prompts is never enough. - Copy deep-clones mode/row content but initializes the caller’s normal comment defaults; it never copies another creator’s private comment filters/blacklists.
- Copy starts private, unscheduled, and
allow_view_prompts=false; it never inherits publication/review state. - Export uses the same prompt-content visibility gate as preview/copy. Its envelope increments to v2 and carries both discriminators. Import accepts v1 and v2; v1/absent fields become
advanced+ expansion0. - A v2 Document import must satisfy the one-row invariant or return a field-specific 400 without creating anything.
- Copy and import both validate and write through the aggregate transaction; injected mid-row failure leaves no partial mode/content/link.
- Document → Advanced changes only
editor_kind. No materialization, splitting, or prompt rewrite occurs. - Advanced → Document is offered only when the mode already has exactly one keyless System row at expansion version 1 and passes Document lint. Otherwise the UI explains which structural conditions prevent the switch.
- In Advanced, a legacy row has an explicit Enable inline tokens action. It runs compatibility lint and requires confirmation when token-looking literal text exists. The staged upgrade changes only
expansion_versionon Save (with COW when shared); Cancel restores version 0. It is one-way in v1.
Editor experience (clientConsole)
Shared host and complete lifecycle
Build a reusable ModeEditorShell containing the complete existing lifecycle:
- name and description;
- Document or Advanced content surface;
- Mature Themes, enhance/merge/summarization settings;
- tags, visibility, scheduled publication, allow-view-prompts;
- content pre-check, comment settings, review lock/withdraw;
- one standard Cancel/Save pair, always visible and disabled when clean;
- surgical dirty-field save and
useFormDraftrestoration.
Refactor CommentSettingsSection into controlled reusable CommentSettingsFields plus its existing standalone wrapper; the mode shell stages those fields and never renders their separate Save button. Editor switching, inline-token upgrades, reordering, publication fields, and comment fields all participate in the one draft. Content pre-check stays a clearly labeled last-saved advisory action outside dirty-field commit semantics; while dirty it reads Save to check, focuses the ordinary footer Save, clears stale results on edit, and displays a result only for its matching saved mode version. No creator must visit a second editor to publish or fully configure a Document-authored mode.
Progressive disclosure is explicit: a new Document initially shows template/name, the document with its content-only Preview, essential visibility/Mature Themes status, and the standard footer. Description/tags/publication live in a visible Details & publishing disclosure; enhance/merge/summarization and comment controls start collapsed under Mode settings. Turning Enhance prompt on reveals its actual 3,000-character prompt editor plus message role, repeat interval, and append-at-end controls; the UI-only disclosure state serializes only the existing enhancePrompt/enhancePromptRole/enhanceInterval/enhanceAtEnd fields. Turning it off stages interval 0 and enhanceAtEnd=false, so preserved draft text cannot run accidentally. An enabled but blank prompt, or an enabled prompt with neither cadence, blocks Save with a field-specific explanation. The message role is User (the default) or Assistant: System was retired in 2026-10 (it was a system turn in a position the open models' chat templates don't expect), and the picker's description says where the selected role puts the reminder. In Hybrid, Beat and Prose stage these settings independently. UC-1 can complete without entering either power-settings group, while every lifecycle control remains reachable on the same page.
Routes and Workbench context
/creator/modes/newhosts the shared template gallery/create flow without project context./creator/modes/:idloads the mode and renders its preferred editor in the shared shell; no separate/guidedroute is required.- Project Quick Create embeds the same flow and adds/selects the created mode as a project item.
- Model Profile Entries’ Base prompt picker gains Create mode…. Its context carries project id, the preserved Entry-form draft, and optional package id for lint. Mode Save atomically creates the Mode + project item, returns/selects its id inside the still-dirty Entry draft, and shows “Base prompt created — save this Model Profile Entry to use it.” Entry Cancel restores the old selection without deleting the Mode; Entry Save separately persists pattern/parameter/Base mapping and runs impact review when reachability/Base changed. Stored parameter-only edits CAS/bump the Profile and are offered through Apply Entry recommendations, but are not automatically applied by mapped launch. It never writes a package Mode slot or partially commits the parent form.
- An owner who wants to opt a package into resolver policy 1 does so from the affected Package entity in the existing Project Workbench: a non-blocking action shows policy 0 vs policy 1 winners/patterns for review, then commits through the standard reverse-impact acknowledgement flow like any other mode-affecting edit. There is no forced migration banner and no unpublish — policy 0 keeps working indefinitely and the package is never moved without the owner asking.
- Characters carry no resolver policy field and need no equivalent action; default-mode priority is unchanged by this feature.
- Standalone editing remains valid for individually published modes, while contextual nudges encourage adding/testing through a Package.
Model Profile base/flavor editor and chat controls
Reuse the same token-editor substrate inside the existing Model Profile surface; do not turn a flavor into a miniature Mode form.
- Entries rename the human-facing Mode column/field to Base prompt, with “Always-on instructions optimized for this model.” API compatibility remains
modeId. - A profile-level Flavors panel follows Entries: “Optional Style & rules choices that work with every Base prompt in this profile (Web Classic).” It stages at most 12 rows with label, user-facing description, default, order, one keyless System document, and optional membership in a separately named/ordered exclusivity group. The profile form has one Save/Cancel pair for metadata, groups, and the complete Flavor aggregate.
- The Flavor editor uses Document highlighting/palette but a Flavor-specific validator: identity insertion is absent/blocked, System/
classic_primary/no row provider are fixed, and no Mode settings appear. New content is expansion 1. Import prompt text… accepts only an authorized keyless System v0/v1 source and creates a private clone. Examples use safe optional craft choices such as Lyrical prose vs Concise replies, never platform filters or required game rules; suspected semantic misuse warns and enters publish review rather than pretending a parser can prove intent. - An imported v0 Flavor shows a persistent Legacy expansion notice: inline-token-looking text is literal except final lowercase
{{char}}/{{user}}, and palette/autocomplete is disabled. Enable inline tokens stages the same one-way compatibility lint/confirmation used by Advanced rows (excluding already-activechar/userfrom the warning), changes onlyexpansion_versionunder the Profile Save, and is fully reverted by Cancel. After upgrade, the Flavor palette exposes only supported non-identity inline tokens. - Resolution preview requires a concrete Entry/model and Flavor selection. It labels Base prompt and each Flavor and shows the exact composite assembly/fingerprint. Publication validation is bounded rather than exponential: structurally test every enableable Flavor alone against every Entry/Base, every package-effective default set, and the maximum envelope (all independent choices plus the largest member of each group); verify insertion/final role order and budget. Creator-selected combinations remain previewable, and moderation screens every row regardless of default.
- A reused profile opened through Package Workbench is hydrated through the authorized package/project-context DTO, not the owner edit API. A package editor may inspect safe mappings/descriptions and stage only package overrides; profile/base/flavor editing controls appear solely when their separate capabilities allow them. Prompt-hidden source stays redacted even when the package itself is editable.
- Package profile cards show Base mappings plus Flavors. Sparse package controls stage hide/initial-default changes into the Package form’s single Cancel/Save pair; they never expose hidden source, mutate the shared profile, or remove the user’s ability to switch an available Flavor off.
- The How drawer keeps active Base/provenance in the Model Profile card and adds the Web Classic Style & rules controls/empty/error/read-only/update states defined above. Hybrid shows the Classic-only notice; Direct/Discord expose no false toggle promise. Toggling itself never charges.
- Follow selected model, Use profile Entry, Use Mode, and optional Apply Entry recommendations use the discriminated atomic endpoint. When a chosen Entry needs another concrete preset, the picker includes that preset choice and labels actions Use model & Base / Use model, Base & Entry recommendations; when the current preset already matches, copy may shorten to Just switch Base. Package lock and effective enforcement are shown before selection and rechecked server-side.
Layout
Across breakpoints, the Mode prompt textarea itself is a field-local Raw / Preview editor: the token palette and prompt checks stay outside that field, while Preview replaces only the textarea with the resolved content of that Mode prompt. The box contains no nested tabs, headings, cards, labels, role/status badges, source sections, pipeline rows, Test-drive actions, or boundary notices. Below lg, the token palette remains horizontally scrollable above the raw editor. Save/Cancel remain anchored at the bottom-right of the form area; Test drive appears separately only after a clean Save.
Token editor
Refactor the existing CodeMirror 6 setup into a generic substrate in shared/src/components/common/, where RichContentCodeEditor already lives. Keep TokenTextEditor’s catalogue grammar/autocomplete/Document configuration app-scoped until another app consumes it:
value,onChange, label/description/maxLength/character-count parity with shared inputs;- token decorations by catalogue kind;
- cursor-aware palette insertion;
{{autocomplete, keyboard navigation, Escape, screen-reader labels;- source spans for lint jump-to-position;
- IME-safe input and mobile suggestion row.
Add the generic substrate and app-scoped TokenTextEditor configuration to /dev/components.
Template gallery
Extract/reuse the accessible preset-card gallery pattern already used by the package Workbench. Templates are versioned typed fixtures (id, version, recommendedCharacterType, exact content) with golden assembly snapshots. The v1 canon is four behavior templates, typed by recommended character type — each card is badged with the character type it expects (Character / Assistant / System / Any type), so a creator picks by what they're building rather than by prose genre. The interactive mockup at /dev/mode-editor (ModeEditorMockupPage + modeEditorMockupData.ts) is the living reference for this flow; its fixture-hash test pins this canon (MODE_TEMPLATE_VERSION), so canon changes must land in the doc and the fixtures together:
Roleplay v1 — recommended character type: Character
{{identity}}
Write the next turn as this character in an immersive roleplay. Stay true to the voice, motives, knowledge, and limits established above — including what this character does not know or would not do. React to the latest message before advancing anything new, then move the scene forward through concrete action, sensory detail, and dialogue. Leave the other participant's words, decisions, and feelings entirely to them.{{#persona}}
The other participant:
{{persona}}{{/persona}}{{#scenario}}
Current scenario:
{{scenario}}{{/scenario}}{{#knowledge}}
Relevant world knowledge:
{{knowledge}}{{/knowledge}}{{#summary}}
Conversation so far:
{{summary}}{{/summary}}{{#recalled_memory}}
Relevant memories:
{{recalled_memory}}{{/recalled_memory}}{{#journal}}
Established story state:
{{journal}}{{/journal}}
Practical Assistant v1 — recommended character type: Assistant
{{identity}}
Act as a practical, attentive assistant. Answer the latest request directly and completely before offering anything beyond it. Build on what the user is making instead of replacing their choices with generic output, and keep every suggestion specific enough to act on. When a needed detail is missing, make a sensible assumption and state it in one line instead of stalling on questions.{{#persona}}
Who you're assisting:
{{persona}}{{/persona}}{{#knowledge}}
Relevant reference:
{{knowledge}}{{/knowledge}}{{#summary}}
Conversation so far:
{{summary}}{{/summary}}{{#recalled_memory}}
Relevant memories:
{{recalled_memory}}{{/recalled_memory}}{{#journal}}
Established project state:
{{journal}}{{/journal}}
Rules & Game System v1 — recommended character type: System
{{identity}}
Run the world and its rules as a fair, impartial game system. Apply established mechanics consistently — the same action faces the same odds every time — and let consequences follow from player choices, not from a preferred outcome. Present each situation concretely: what the player perceives, what has changed, and what is at stake. Whenever the outcome depends on the player's choice, stop and ask for their decision. Never choose the player's action for them.{{#persona}}
Player context:
{{persona}}{{/persona}}{{#scenario}}
Current scenario:
{{scenario}}{{/scenario}}{{#knowledge}}
Setting and rules reference:
{{knowledge}}{{/knowledge}}{{#summary}}
Campaign so far:
{{summary}}{{/summary}}{{#recalled_memory}}
Relevant memories:
{{recalled_memory}}{{/recalled_memory}}{{#journal}}
Established campaign state:
{{journal}}{{/journal}}
General Purpose v1 — recommended character type: Any type
{{identity}}
Follow the role, voice, and intent established above without assuming any fixed format. Respond naturally to the latest message, keep continuity with everything established so far, and match your reply's length and depth to what the request actually needs — brief when brief serves it, detailed when detail matters.{{#persona}}
The other participant:
{{persona}}{{/persona}}{{#knowledge}}
Relevant reference:
{{knowledge}}{{/knowledge}}{{#summary}}
Conversation so far:
{{summary}}{{/summary}}{{#recalled_memory}}
Relevant memories:
{{recalled_memory}}{{/recalled_memory}}{{#journal}}
Established state:
{{journal}}{{/journal}}
Blank canvas v1 is intentionally minimal but valid:
{{identity}}
All four behavior templates deliberately declare knowledge, summary, recalled_memory, and journal; Blank canvas declares only identity and therefore receives only the existing automatic journal fallback beyond it. Persona/scenario/journal are optional Web-only values and render away with their entire leading separator inside the conditional, so unsupported/empty blocks leave no blank run. Template snapshot tests cover every-empty, alternating, and every-filled combinations. Gallery also offers Advanced editor. Teaching notes and “try changing this” copy live in Card descriptions/Notices, never inside the prompt. Customer-facing copy receives the brand-voice pass before fixture freeze.
Before fixture freeze, a small product eval runs three fixed Classic conversations per behavior template at the pinned eval model/settings; at least two of three must meet every named property:
| Template | Behavioral rubric |
|---|---|
| Roleplay | identity-consistent voice; reacts to the latest message before advancing; concrete scene advance; never decides the other participant’s words or actions |
| Practical Assistant | answers the request directly; specific, actionable suggestions that build on stated intent; states an assumption instead of stalling on questions |
| Rules & Game System | applies mechanics consistently; consequences follow choices; stops for a player-dependent decision; never chooses the player action |
| General Purpose | follows the identity’s role and voice; assumes no fixed format; depth matches the request |
These rubric runs validate copy quality and can trigger a fixture-version bump. Deterministic assembly snapshots and mock-pipeline delivery remain the code-level acceptance gate.
Palette and lint
Palette/autocomplete data comes from the catalogue-backed endpoint and is filtered by editor surface. Document exposes universal identity, the three type-specific identity tokens as a separate Type-specific identity group, and the six optional context tokens; Advanced exposes the same inline vocabulary. Identity inserts its mandatory simple node; each type-specific identity token inserts bare inside its own matching conditional. Every optional context token—including static persona/scenario—uses its catalogue-provided conditional RecommendedInsertSnippet, with the leading separator inside the block. Because v1 forbids nested conditionals, palette/autocomplete insertion is disabled while the cursor is inside any conditional and announces why; an accessible Move after current block action places the cursor after its closing marker. Identity-family insertion is likewise top-level-only. The field Preview resolves identity-family tokens for one selected sample character type at a time (an accessible Preview character type control, defaulting to a standard character), so a type-specific draft shows exactly what one binding would receive rather than a union no runtime produces. Hand-typing remains visible to local lint. Findings appear below the editor and in the sample pane; blocking findings disable Save and link to the source span.
Context selection has three explicit states:
- invoked from a specific package section → inherit that package/Entry draft and Web;
- profile/entity editing with exactly one bound accessible package → auto-select it and Web, visibly;
- standalone/profile editing with zero or several bound packages → General + Web; offer a compact Preview context disclosure for Web/Discord and an explicit accessible package/effective-variant choice, never guess among several.
Portability badges are always visible. Clearing context returns to General. Contextual findings never appear without a concrete selection, and shadowed entries are selectable only for diagnosis, not labeled effective/Test-drive candidates.
Test drive
- Test drive never saves and never appears inside the prompt Preview. It is exposed with the post-save actions only when the latest version is clean and valid; editing hides it while dirty, Cancel restores readiness for the exact previously tested saved version, and saving a new version requires a new Test drive, so no stale prompt is tested accidentally.
- Mapped prompt-plan resolution chooses a concrete package and a reachable
profile_entry, nonnullpackage_fallback, orcharacter_defaultcandidate whose Base id is the saved Mode currently being tested. It then chooses an owned preset/model, concrete Web Classic enabled-Flavor set, and bound/BYOC-test character. Requests carry expected source, exact Profile/Entry, Base/Profile versions, ordered Flavor link ids + enabled/snapshot bits, selected character/default link when relevant, package/selection token, and Sandbox-onlypresetId. One transaction validates the outer resolver and composition fingerprint, stores preset/character/provenance/empty-or-populated Profile snapshot, and rolls the complete create back with 409 on any different winner/parent version. The response reports the exact plan andentryRecommendationsApplied=falseunless the user explicitly chose Apply Entry recommendations. Package/character fallback plans have no Profile Flavors. Built-in DefaultSections is diagnostic-only from a Mode editor; no-preset readiness cannot generate. If no matching preset exists, offer create/select preset or isolated testing. - Isolated mode in package context uses
composition_source=sandboxplusforcedModeId/version. It requires Mode edit/prompt rights, package edit rights, and that the Mode is in the same project pool; adding it first is a separate project-item mutation requiring projectcan_edit. Package character, greeting, lorebooks, persona templates, and custom instructions are materialized normally, then production Profile resolution is bypassed (mode_is_auto_resolved=false). By default this has no Profile Flavors. An authorized staged Entry/Profile context may add a clearly labeled hypothetical Web Classic Flavor set for composition testing, but mapped testing remains disabled until Entry/Profile Save. Creation copies the exact Base + hypothetical Flavor templates/settings into the bounded immutable Sandbox manifest; later turns never attempt to reconstruct an unsaved draft. The private Test-drive conversation is nonshareable/nonpublic/nonbranchable and blocks if its forced live Base is later deleted. The UI says this tests an isolated plan, not the package’s audience mapping. - Standalone Quick test chooses an owned/accessible character and starts the existing direct Sandbox path with the saved mode. If no character exists, Create character to test carries a signed return context back to the mode; adding the mode to a package instead routes through project → bound model profile → entry assignment with the mode id preserved.
- A valid bound package character is used automatically under package encapsulation; the tester does not need separate visibility to the creator-private component. A null + unlocked (
character_locked=false) BYOC package is valid and asks for a directly accessibletestCharacterId; Sandbox stores that identity on the conversation only, does not import the test character’s greetings, and never mutates the package. Null + locked or deleted/broken bindings block asidentity_without_character. Standalone/General asks for its test character only at launch. This Sandbox override does not implement normal public BYOC package start, whose greeting/character-ownership unification remains in the Packages plan. - Multiple effective variants/characters/Flavor combinations always require a choice. Each launch fingerprints Base + Flavor rows + package + selected-character/default-link + exact profile/Entry/preset and starts fresh.
- Classic is the default and the only V1 Flavor-capable Test drive. Hybrid Test drive runs Base-only and explains that the Mode guides beat planning while the per-leg-resolved prose Mode (role-tagged Model Profile entry → settings-bound Mode, seeded "Visceral Prose" → hardcoded constants as last resort) owns final prose instructions; it never presents a Flavor toggle as prose styling.
- Opening Test drive is not subscription-gated, but each generated turn follows ordinary chat eligibility, conversation limits, BYOK/Echo charging, preflight, and error handling. It is not a free LLM path.
Collaboration and moderation
Add a capability-scoped share edit-context read alongside the existing share prompt API. It returns only editorKind, parent version, the complete permitted row set + rowSetToken, capability flags, and coarse categorized publicationImpact + fingerprint; it never returns owner-only metadata/comment/publication fields or package identities. The client renders the shell variant from those flags rather than attempting the owner getMode call. Any actor whose save would invalidate publication-bound work sees a pre-Save banner/confirmation, and a changed impact fingerprint produces 409 instead of an unacknowledged consequence.
| Capability | Surface and mutations |
|---|---|
| Owner | Full shared shell; metadata, editor kind, rows/settings, publication lifecycle, owner-only comments; direct aggregate Save |
Non-owner entity editor (can_edit) |
Every metadata/prompt/publication field already granted by existing entity/project policy (including visibility/schedule/allow-view-prompts); aggregate Save omits owner-only comments and any other ungranted field rather than fetching or overwriting them |
| Share collaborator with prompt edit | Prompt-aggregate-only surface: Document is content-only because its structure is fixed; Advanced preserves current name/content/provider/role/order/create/delete and may stage expansion version, all under COW/shape/CAS guards. No mode metadata, editor-kind, publication, or comments |
| Project contributor without entity edit | Proposal presentation; preserves shipped Advanced row proposal create/update/delete/disable behavior and adds Document content-update proposals for its sole row. May propose other already-allowed metadata, never direct-save/publish/switch editor kind; manager apply runs the locked Core-validation transaction |
| Prompt viewer | Read-only authored text/content Preview only when prompt-content visibility permits it |
| Moderator/admin reviewer | Read-only raw text, canonical ordered sample, keys/findings/effective variants, plus existing moderation actions; no creator Save |
Character/profile/package moderation extraction, automated checks, and admin review include every distinct default/base/package-fallback mode plus every profile flavor row a user could enable, including default-off, package-default-off, private, and shadowed sources. A package-hidden flavor is still screened with its public profile; BYOC user-selected private content remains user context. Any base/flavor/default link or prompt mutation follows shared reverse impact regardless of owner Save, profile aggregate, Entry Save, share/proposal/agent, delete/restore, or compatibility endpoint.
Shipped agent tool-pack integration
This feature does not create a separate mode_authoring pack. It upgrades the tools that already exist:
package_authoring.propose_modecarries expliciteditorKindand per-rowexpansionVersion. Absent fields remainadvanced/0; neither the tool schema nor staging infers Document from one System row. Updated pack instructions may deliberately emit a valid Document/inline aggregate with complete identity coverage (one top-level universal identity token or the exactly-once type-specific set). Agent staging blocks invented/unknown provider keys.package_authoring.propose_model_wiringcalls Entries’ Modes Base prompts and may stage new exclusive Flavor drafts/defaults/groups/package overrides. It structurally enforces keyless System/Classic/identity-free shape, emits semantic optionality warnings for review, and writes through the Profile aggregate/impact transaction; it cannot attach an arbitrary existing row.experience_dry_run.preview_prompt_assemblydelegates to the same plan composer and returns canonical filled/dangling/runtime slots per labeled Web Classic Base + enabled-Flavor plan, with Base-only projections for unsupported surfaces. It returns each source/final sample only with prompt visibility; otherwise typed readiness usescontentRedacted=true. Package visibility never upgrades Base/Profile prompt visibility; Admin moderation is privileged.project_readsMode/Profile details and readiness enumerate fallback + every exact Entry/Base, each individual Flavor, defaults, and maximum envelope and report per-model results rather than unioning keys or exploding all combinations.- Agent proposal apply uses the shared aggregate mode writer, so human and agent creation produce structurally identical modes.
The Core ports remain door-agnostic; AuthService MCP and the in-app Workbench Assistant wrap the same behavior. No new tool surface is required merely to expose the token catalogue in v1; pack instructions and proposal validation consume it internally.
Storage and SQL
Add
prompt_modes.editor_kind VARCHAR(16) NOT NULL DEFAULT 'advanced'with a CHECK foradvanced|document, plus idempotent ALTER/comment and view/model plumbing.Add
sub_prompts.expansion_version SMALLINT NOT NULL DEFAULT 0with a CHECK for0|1, plus idempotent ALTER/comment and all loader/result plumbing.Add
model_profiles.version INTEGER NOT NULL DEFAULT 0,allow_view_prompts BOOLEAN NOT NULL DEFAULT FALSE, and immutable create-payload hash. Addmodel_profile_entries.is_deleted BOOLEAN NOT NULL DEFAULT FALSE; replace the current hard-delete/whole-table uniqueness with Profile-locked soft-delete/explicit restore and an active-row partial unique constraint. This preserves accepted-turn/history provenance while every resolver excludes deleted Entries. The profile flag governs its exclusive Flavor source only; referenced Base source remains under that Mode’s independent gate. Metadata, Entry, group, Flavor, visibility, and reorder writes lock the parent, requireexpectedProfileVersion, and bump once. Existing profiles start with no Flavors and hidden Flavor content. Entry create gets the same immutable idempotency payload hash.Add
model_profile_flavor_groups(id,uuid,model_profile_id, immutable-after-creategroup_key VARCHAR(50),display_name VARCHAR(60),sort_order,is_deleted, timestamps) andmodel_profile_flavors(id,uuid,model_profile_id, exclusivesub_prompt_id,display_name VARCHAR(60),description VARCHAR(200),default_enabled, nullablegroup_id,target_stage='classic_primary',sort_order,is_deleted, timestamps). Enforce ≤12 active Flavors, 4,000 characters per row/20,000 active characters per Profile in the aggregate validator, normalized local order, one active group key/name per Profile, at most one group default, and exactly one active Flavor parent/zero Mode or other-Profile parents for each Flavor row.profileSetTokencovers the complete persisted group + Flavor identity/order/membership set; Save sends both complete activegroups[]andflavors[]or neither, so omission of an active UUID under an unchanged token is an intentional soft-delete,restoreGroupUuids[]/restoreFlavorUuids[]are explicit, and partial panel payloads are rejected. Deleting a group requires the same aggregate to ungroup/reassign every active member; existing conversation snapshots retain their copied group semantics. Flavor rows are keyless System v0/v1; semantic edits bump the Profile parent, so no nonexistentsub_prompts.versionis referenced. Creation/import stamps the exclusivesub_prompts.created_by_user_idfrom the Profile owner and creates a privatesub_prompt_contentsrow referenced by no other sub-prompt. Account merge atomically transfers the Profile and every active or soft-deleted exclusive Flavor row to the surviving owner. Hard Profile/account deletion first collects those exclusive row/content ids, suppresses and detaches live conversation references under the shared fence, deletes the Profile aggregate, then deletes the now-parentlesssub_promptsandsub_prompt_contents; it aborts rather than deleting payload that unexpectedly has a Mode/second-Profile parent or shared content row.Add sparse
package_model_profile_flavor_overrideskeyed bypackage_model_profiles.id + model_profile_flavor_id, withis_availableand nullabledefault_enabled. Validate same-profile membership and at-most-one effective default per group; an override cannot force a Flavor non-toggleable. Normalize legacy bindings by assigning the lowest(sort_order,id)active binding when a nonempty package has no default and retaining only that winner when it has several. A partial unique index enforces at-most-one, while the only binding-set writer plus aDEFERRABLE INITIALLY DEFERREDconstraint trigger enforce exactly one active default when the active set is nonempty, none when empty after inserts, deletes/unlinks, reorder, soft-delete/restore, and sync.Add conversation selection state: closed checked
composition_sourceincludingpolicy0_retained_base, checkedgeneration_status,selection_version,resolver_policy_version,resolution_stale,selection_enforcement_grandfathered, copied selected/governing Profile/Entry/Base UUID provenance plus nullable live ids, and last-materialized composition/execution fingerprints; maintain legacymode_is_auto_resolvedas the same-transaction derived projection. User-owned live-entity FKs are nullableON DELETE SET NULL, never restrictive/cascading from snapshots. A Profile/Entry/Flavor hard-delete (account deletion only; account merge transfers ownership instead) first marks affected conversations stale/suppressed in the same deletion transaction; copied UUIDs retain audit history, turn acceptance rejects a missing live parent, and the nullable FK remains a nonblocking final safeguard.Add Web-Classic-only
web_conversation_profile_snapshots(unique conversation + copied Profile UUID, nullable live Profile FK, first-activation Profile version, scalarpackage_model_profile_link_id_at_activationwith no FK to the live junction,effective_roster_fingerprint, timestamps) even for an empty roster, plusweb_conversation_flavor_states(unique conversation + copied Flavor-link UUID, nullable live Flavor FK, snapshot FK, copied Profile UUID/default/order/stage/group UUID/key/label, enabled bit). Composite copied-identity keys prove that child conversation + Profile match the header; the aggregate writer verifies any nonnull live Flavor belongs to that Profile. Account deletion nulls live refs, scrubs copied user-authored labels to a neutral unavailable marker while retaining opaque UUID audit identity, and suppresses the source without blocking GDPR deletion; account merge instead transfers live ownership and preserves those references. Unlink/rebind never deletes snapshot history. Retain inactive-Profile snapshots for switch-back. Current hide/delete suppresses a row at the turn-acceptance boundary; later additions/unhides/default/order/group edits do not alter the frozen roster.Extend
web_conversation_settingswith checkedvalue_source='user'|'profile_recommendation', copied nullablesource_profile_entry_uuid, andsource_profile_version. Existing rows backfill touser; ordinary user writes always setuser/clear source provenance. The atomic Entry action alone writes recommendation provenance and may delete only prior recommendation-sourced canonical Generation rows.Add one owner-only
web_conversation_sandbox_plansrow forcomposition_source=sandbox: conversation PK/FK cascade,manifest_schema_version, forced Base copied UUID + required live id/version, package/project/character authorization provenance, required live preset id + copied UUID/config fingerprint, and immutable JSONB containing copied ordered Base templates/settings, copied nonsecret preset provider/model/Generation config, plus any authorized hypothetical Flavor templates/order. Hypothetical rows receive deterministic manifest-local UUIDs derived inside the idempotent creation transaction so composition/audit hashes remain closed without fake live links. Enforce the normal Mode/Flavor content limits plus a 1 MiB manifest ceiling; it lives exactly as long as the private Test-drive conversation, is nonpublic/nonshareable/nonbranchable, and every later turn rechecks owner + nondeleted forced Base + accessible live preset, then resolves current secret credentials without adopting later nonsecret preset edits. Unsaved hypothetical text is never reconstructed from a fake Profile/Entry FK.Add
packages.mode_resolution_policy_version SMALLINT NOT NULL DEFAULT 0with a0|1CHECK, purely for resolver-behavior compatibility. New packages create at 1; existing packages stay at 0 indefinitely and move only by explicit owner opt-in through ordinary reverse impact. No character policy field exists.Add immutable nullable
prompt_modes.create_payload_hash CHAR(64)beside scoped idempotency uniqueness; Mode/Profile/Entry creates write their specified RFC-8785/SHA-256 hash, later updates never change it.Extend every loader/projection/changelog/copy/proposal/agent payload with expansion version and, where contextual, Base/Flavor layer provenance. Project Mode/Profile versions through edit/share DTOs.
Keep context-free
fn_mode_assembled_dependencies(mode_id)for Base grammar. Add Web Classic effective-plan dependency projection over exact enabled Flavor states;ConversationBrowseRepositoryapplies character-type identity filtering after composition. Pin SQL/C# parity, including zero-row Base + Flavor and Base-only Direct/Discord/Hybrid.Extract the atomic aggregate Mode writer from
fn_apply_mode_draft; route both editors, copy/import/proposals/agent/comments/COW/project links through it. Add the complete Profile group/Flavor exclusive-row aggregate writer/token; Entry Save remains a separate parent-form transaction sharing the same Profile lock/impact boundary.Replace scalar-only package resolution with a discriminated result containing exact selection source, governing enforcement, Profile/Entry/Base provenance, and parameter recommendations. Policy 0 preserves shipped matching/null retention for nondeleted candidates and emits Base-only
policy0_retained_basewhen an automatic Base survives a null; policy 1 implements exact → longest literal substring →*→ nullable package fallback, with stable id tie-breakers. Automatic resolution composes only a current winner’s snapshotted Web Classic Flavors; retained/explicit Entry/Mode sources follow their separate rules.Add the shared retrying
SelectionGraphTransactionhelper (serializable isolation, fixed(kindRank,id)advisory-lock order, re-read-after-fence). Routefn_reresolve_package_conversation_modeplus user/conversation setting insert/update/delete, preset update/hard-delete/reference-cleanup, Profile/Entry/Flavor/unlink/delete, package restart/branch/create, and all plan/toggle/turn mutations through it. Valid-null/deleted paths, all automatic sources, and invalid manual-Entry plans recompute atomically per conversation; lookup/error never masquerades as fallback. Replace user-setting/preset row-loop triggers and best-effort sweeps with fenced set-basedresolution_stalemarking inside the authoritative mutation transaction so one dormant Mandatory conflict cannot roll back a global setting edit or miss a concurrent child. Conversation open/Send unconditionally revalidates and performs isolated authoritative re-resolution. Turn acceptance freezes one immutable prompt + LLM execution plan before provider/allocation work.Add one discriminated conversation transaction/endpoint for Follow-model / explicit policy-matching Entry+preset / arbitrary Mode, applying package lock + effective enforcement, creating an empty-or-populated Profile snapshot only for Web Classic (null snapshot/empty Flavors on Direct, Discord, and Hybrid), clearing any grandfather flag on a valid deliberate change, bumping selection CAS, and applying the pinned user-vs-recommendation Generation-row cleanup/upsert rules. Remove the invalid
Llm.*per-key loop. Route create/update compatibility Mode writes through it; drop/delegate productionfn_upsert_conversation, revoke the migration primitive from application roles, reject the Send-time Mode override, and guard direct repository/SQL selection writes. Package Save and Start Experience atomically validate the exact typed package-safe settings allowlist and rejectGeneration.*,*Llm.*, secrets/default/admin keys, or unknowns rather than smuggling automatic Entry parameters through package JSON. Toggle and Send use the returned selection version.Add a package/project-context Model Profile read projection beside the owner aggregate read. It verifies the requested relationship and caller context, returns safe Entry/Base/Flavor/override metadata plus version/capability fields, applies prompt-source redaction per layer, and uses established non-leaking 403/404 behavior. Workbench stops substituting an empty profile after owner-only reads fail.
Add set-based reverse dependency primitives used by
EffectiveModeDependencyImpactService; impact fingerprints include exact winner, Base/Profile/Flavor/override parent versions and publication states but remain distinct from turn composition hashes.Extend message stats/leak-source data with scalar copied selection source/version, resolver policy, Profile/Entry UUIDs, enabled Flavor UUIDs, concrete preset/provider/model config fingerprint, effective Generation values/sources, and the exact frozen turn composition/execution fingerprints. These audit columns have no live entity FKs, so an accepted turn can finish and persist exact provenance after a later soft/hard delete.
Backfill existing conversations into exact automatic, policy-0 retained automatic, manual Mode, or truly legacy-unprovenanced state without changing behavior, applying the narrow enforcement-grandfather flag/status where required. Update
fn_branch_conversationto resolve stale/normalize grandfather state, then copypackage_id, package context, Profile snapshot headers/children, and copied/live provenance atomically. Extend package-aware conversation creation for the fresh-roster action; the generic standalone flow does not substitute for it. New Workbench packages keeppackages.mode_id=null, while ordinary saves preserve a pre-existing read-only legacy fallback and only an explicit reverse-impact action removes it.Export v2 carries
editorKindand promptexpansionVersion; v1 import defaults preserve legacy behavior. Templates remain typed client constants; no template table/admin UI.
Every schema change is idempotent and wired through v1_run_all.sql.
Adjacent design moves
Summary prompts
Superseded (2026-07-25) by Prompt Presets: summarization decouples from Mode entirely — a user-selected Summarization preset (or the built-in default) supplies the prompts, in both pipeline types. The per-mode summarize_* fields remain in the Advanced disclosure only as legacy until that ships; this feature does not depend on either state.
Hybrid authoring
Hybrid v1 is already live with hardcoded beat/prose prompts. Phase 2’s beat handoff is a User-role concern and therefore stays out of the Document palette. The Advanced editor’s existing row/role model—now optionally inline-enabled per row—is the correct per-Mode authoring surface; future Beat/Prose pairing extends Model Profiles with explicit role-tagged Base mappings, not a Bundle entity. V1 Flavors stay Web Classic-only.
Decisions (resolved)
- Inline expansion is per sub-prompt, explicitly versioned, and never inferred.
editor_kindcontrols the authoring surface/shape contract, never runtime expansion; Document → Advanced is lossless and performs no prompt rewrite.- Existing/imported rows default to legacy expansion and keep role/content/order/name behavior; journal staticness is the named metadata correction.
- Resolution is non-recursive; only version-1 inline dependencies are memoized once per canonical key per build. An ordinary row provider still gates the complete row.
- C# and TypeScript share tokenizer/AST/findings/dependency/span fixtures; C# alone owns rendering/no-cleanup output fixtures, while SQL mirrors descriptor extraction only.
- Document modes require every character type to receive exactly one identity injection — one visible top-level/unconditional simple
{{identity}}value node, or complete type-specific coverage via{{character}}/{{assistant}}/{{rules}};identityis inline-v1-only and there is no hidden character fallback. - Existing
character/rules/assistantsemantics remain unchanged; the Document palette exposes them as a type-specific identity group whose per-type coverage lint stands in for the universal{{identity}}requirement. - An automatic winning Entry or explicit compatible
manual_profile_entryuses its existingmode_idas the always-on Base prompt; only that exact attached profile contributes optional Flavors. There is no new Mode kind, Bundle entity, profile Base fallback, intrinsic row Flavor flag, or{{flavor}}macro. - Flavor semantics live on profile links/groups, while each V1 Flavor content row is exclusive to its profile aggregate. Base owns identity/settings/required behavior; Flavors are optional Web Classic keyless System overlays, grouped/orderable/defaultable, inserted at the Base’s leading-System boundary before one composite journal fallback/merge.
- N:M Mode-row semantic edits are copy-on-write; Document and Profile Flavor rows are exclusive. Aggregate replacement starts from a complete edit read and uses set token + parent-version CAS; Mode/Profile/Entry create idempotency stores canonical payload hashes.
{{date}}/{{time}}are deferred; the catalogue stops advertising them.- The field-local Preview contains only the resolved current Mode prompt text. Assembly sources, base/flavor provenance, settings projections, and pipeline rows stay in diagnostics/Test drive; the endpoint still returns canonical ordered
finalMessages[], while old DTO fields remain lossy compatibility only. - The editor reuses CodeMirror and the existing gallery/shared form vocabulary; its field-local Preview does not use
ResizablePanel. - Workbench creation stays in context through project items and preserved model-profile Entry drafts; the parent Entry Save owns mapping persistence. Packages have no normal direct Mode slot; nullable
packages.mode_idremains only the legacy outer fallback. - Full publication/owner-comment/versioned-pre-check lifecycle is present in the field-scoped shared shell.
- Package readiness/dry-run/Test drive operate on exact labeled Base + enabled-Flavor Web Classic plans and Base-only unsupported-door plans, never unioned candidates; hidden Base/Flavor prompts redact independently. Policy-0 resolver behavior is preserved indefinitely unless the owner opts into policy 1. Tracker injection remains Mode-independent.
- Automatic/manual/legacy selection provenance is stored, not inferred from a possibly duplicated Base id. Follow-model, compatible Entry+preset selection, optional canonical
Generation.*application, package lock/effective enforcement, empty-or-populated Flavor snapshot, and direct-Mode detachment share one discriminated conversation transaction. - Agent tool fields are explicit (absent = Advanced/0); current project-read/dry-run consumers migrate in this build.
- Collaboration proposals, shared reverse-impact handling for every screened/runtime dependency mutation, and profile-referenced package moderation are in scope; retroactive mass re-audit of already-published characters/packages is explicitly not (see Non-goals) — existing publication-bound content was already human-reviewed.
- Both editors, lint, and sample preview are subscription- and Echo-free.
- Test-drive access is free, while generated turns use ordinary chat/BYOK/Echo rules.
Non-goals
- Automatic migration of existing legacy rows or modes to inline expansion.
- Recursive inline expansion inside provider output, personas, greetings, lorebooks, or custom instructions.
- Static-prefix auto-splitting/cache optimization.
- Date/time/wall-clock tokens.
- Per-lorebook targeting (
{{knowledge}}stays the merged set); see Mode-Specific Lorebook Injection. - Trackers/Hybrid
beatas Document tokens; role-specific injection stays Advanced. - User-level summary prompt storage.
- Template database/admin UI.
- A standalone sandbox separate from the Workbench.
- Automatic Model Profile Entry parameter precedence during package/resolver launch. Explicit Apply Entry recommendations remains opt-in; this feature replaces the currently broken/non-atomic Apply settings path.
- Flavor ownership of identity, required mechanics/safety, row providers, Mode-level settings, generation parameters, multiple roles, or Hybrid Beat/Prose stages. Those require the Base or a future role-specific composition phase; prose-intent detection remains advisory/review-assisted rather than a fake deterministic parser guarantee.
- Flavor execution/control on Direct, Discord, Hybrid, or standalone non-package profile application. V1 is Web Classic package conversations; unsupported surfaces are Base-only. Public profiles remain reusable through packages, and standalone Flavor application needs its own context/enforcement/toggle spec.
- In-place adoption of newly added/unhidden Flavors by an existing profile snapshot. V1 preserves the frozen roster and sends the writer to a new conversation.
- Normal public BYOC package conversation start/greeting ownership; this feature adds only the authorized conversation-level character override needed to Sample/Test drive an unlocked BYOC package.
- A new assistant tool pack solely for mode authoring.
- A UI for intentionally editing one reusable sub-prompt globally across all parent modes; v1 isolates mode edits with COW.
- A retroactive mass audit/re-review of already-published characters and packages against the corrected extractor, and any resulting forced unpublish. Existing publication-bound content already satisfies the manifesto's human-review requirement; the corrected extractor is forward-looking coverage for future review cycles, not a backlog correction.
packages.mode_resolution_policy_versionexists only so an owner can opt in to the fixed resolver — it never triggers on its own.
Slice plan
- Schema and runtime plumbing.
editor_kind, per-rowexpansion_version, Profile version/prompt visibility/create hashes + Entry soft-delete, Flavor groups + exclusive rows, package overrides, exact-one default guard, copied/null-live empty-capable Profile snapshots + roster fingerprint, closed selection source/status/version/stale/grandfather state, recommendation-setting provenance, Sandbox manifest, scalar audit provenance, package-preserving branch/backfill, constraints, loaders/changelog/export; no existing-row or zero-Flavor behavior change. - Core/grammar/composition substrate. Identity formatter + inline resolver; legacy harness; tokenizer/conditionals/cache/staticness; catalogue metadata; Base-fallback-first + leading-System Web Classic Flavor composer; immutable turn plan/fingerprints; composite dependencies/journal/merge; shared C#/TS/SQL fixtures.
- Atomic lifecycle and mutation guards. Complete Mode/Profile aggregate reads + tokens; CAS/create idempotency/COW/exclusive-row rules, immutable group keys, snapshot-parent constraints, field rights/publication policy, project/copy/import/proposal paths; Entry/Flavor/group/package-override mutations share access and reverse impact.
- Assembly and current consumers. Ordered Base/Flavor saved/draft Sample endpoints; exact automatic/policy0-retained/manual/legacy provenance; immutable prompt + preset/provider/model/Generation execution object; feature/budget/leak/stats/readiness/DryRun/agent consumers; discriminated plan-selection/Entry-recommendation/package-lock/Mandatory enforcement; replacement of direct create/update/Send/upsert Mode bypasses and looping preset triggers; isolated stale re-resolution, package-aware fresh-roster start, and race-free toggle→Send.
- Reusable UI substrate. Shared CodeMirror extraction; app token editor + TS local parser/showcase; accessible gallery extraction; controlled comment fields; shared
ModeEditorShell+useFormDraft; canonicalize duplicate preview API clients. - Document/Profile editors and Workbench flow. Templates/palette/responsive Sample, staged lifecycle/switching, Entry Base prompt creation, profile Flavors panel, package overrides, How-drawer Style & rules, collaboration UI.
- Test drive, moderation, and docs. Exact Entry/base/flavor + fallback/forced/BYOC plans, chat switching, Classic/Hybrid labeling, character/profile/package prompt fan-out (forward-looking; no retro audit), Admin sample, resolver opt-in, old bundle-doc absorption, public/Echo Guide migration.
- Definition of Done. Targeted backend/DB/frontend tests, game-testing pipeline proof, browser-auth UX pass across every acceptance criterion,
/full-review, and adversarial review.
Testing and Definition of Done
- Legacy regression: representative version-0 rows preserve role/content/order/name substitution and per-row provider calls; imported inline-looking text and unknown legacy
identitystay literal/skipped. Journal’s correctedIsStatic=falseis the sole expected metadata diff. - Grammar/engine: one syntax corpus runs through C# + TypeScript (and SQL’s key-only subset): case/aliases, exhaustive vocabulary, exact-lowercase reserved names, UTF-16 spans/astral text, and every pinned malformed-recovery boundary. Separate C# renderer/engine fixtures pin provider whitespace, exact empty output, conditional rendering, multi-provider fallthrough/whole-row skip, non-recursion, mixed rows, v1 memoization, platform gates, and identity exact-once.
- Introspection/budget: Base-only, zero-row Base + Flavor, each Flavor alone per Base, package defaults, grouped/null choice, and maximum envelope cover composite journal fallback, role-safe insertion, type-aware identity, feature capability, and exact token cost; disabled/unavailable/unsupported-surface Flavors contribute nothing and C#/SQL agree.
- Atomicity/concurrency: Mode/Profile complete aggregates, Entry soft-delete/restore, Base/group/Flavor/package-override mutations, create replay, selection/recommendation-sourced settings/toggles, exact-one defaults, Web-Classic-only empty snapshot headers, null snapshots on unsupported surfaces, copied/null-live snapshot constraints, effective-roster deltas, exclusive Flavor rows, row-set tokens, package restart/branch/backfill, all setting/preset insert-update-delete stale invalidation, branch/restart × parent-update/delete serializable-fence races/retries, impact drift, toggle→Send races, and injected failures are covered.
- Lifecycle/security: copy/import/proposals preserve versions and prompt visibility; Base links recheck
can_use; Flavor import requires source view/copy then clones; hidden Flavor text redacts; package lock/effective Mandatory enforcement is server-side; migrated grandfathering is narrow and normalizes when no longer needed; manual Entry and direct Mode provenance transition atomically; compatibility create/update/Send/upsert/migration paths cannot bypass the discriminated writer; account merge transfers exclusive Flavor prompt ownership, account deletion removes its exclusive prompt/content payload after suppressing live references, neither flow is blocked by snapshot FKs, and hide/delete plus preset/settings edits are tested on both sides of immutable turn acceptance. - Preview: saved/draft/persisted/hypothetical paths return ordered interleaved base/flavor messages, carry unsaved base settings + flavor states, preserve layered sources, obey character/BYOC context, redact per source, ignore stale responses, and cover limits/errors/unauthorized access.
- Characters/profiles/packages/agent/moderation: exact Entry/base/flavor plans + outer fallbacks are labeled in reads/readiness/dry-run; mapped tests cover duplicate-base profiles and flavor sets; forced Sandbox covers hypothetical Entry/flavors/BYOC. Default-off flavors are screened; redaction leaks no source/final text; delete/restore skips broken base/flavor sources across hosts.
- Reverse-impact coverage: every guarded mode/profile/package-binding mutation, publication-bound state, same/cross-owner path, fingerprint drift, delete/restore, replay, and unchanged policy-0 package behavior has integration coverage, plus the owner-initiated 0→1 opt-in path. No test exercises a forced or deployment-triggered migration/unpublish, because none exists.
- Frontend: typecheck/lint/tests; one-Save forms; versioned pre-check; keyboard/IME/mobile; Mode templates; Profile Base prompt/Flavors editor; package overrides; How-drawer groups; legacy/grandfather + Mandatory recovery; package-aware new-roster action; atomic Apply Entry recommendations; capability/share routes; Classic/Hybrid/charging copy.
- Pipeline proof: deterministic Web Classic chat demonstrates Base + enabled v1 Flavor + journal exactly once; a zero-row Base retains all DefaultSections; disabled Flavor makes no call; Direct/Discord/Hybrid are Base-only with no default-on Flavor; automatic/policy0-retained/manual/Profile switching preserves the specified state; an accepted turn keeps one Base/preset/provider/model/Generation/allocation tuple across concurrent edits/deletes; persisted Sandbox hypothetical rows replay exactly; trackers still inject.
Acceptance Criteria
The feature is not done until every box below is verified ✅ against the running product.
User use cases — satisfiable + accessible (drive the UI):
- UC-1 — From Creator Hub → New Mode, a first-time creator can choose a behavior template, name/edit one document, inspect its resolved content-only Preview, and save a working mode without seeing provider keys/roles/sort order or opening Details & publishing / Mode settings.
- UC-2 — From a Workbench Model Profile Entry’s Base prompt picker, Create mode… stays in context; Mode Save creates/project-links/selects it in the unchanged Entry draft. Entry Cancel restores the old base without deleting it; Entry Save later persists pattern/parameters/base mapping and refreshes affected plans. Neither writes
packages.mode_id. - UC-3 — Palette click and
{{autocomplete insert exactly the catalogue snippet for every Document-supported token: one bare mandatory identity node, a bare-in-own-conditional node for each type-specific identity token, and a production-safe conditional (including its leading separator) for each optional context token. Inside a conditional, insertion is refused with an accessible explanation and Move after current block, so the palette cannot manufacture invalid nesting. - UC-4 — A creator can cover identity universally with one
{{identity}}or separately per character type with{{character}}/{{assistant}}/{{rules}}. Removing coverage, moving an identity-family value inside an unrelated conditional, duplicating coverage for a type (including mixing{{identity}}with a type token), or leaving a type uncovered blocks Save with the affected types named. Insert Identity updates only the draft; Save persists and Cancel restores. Standard, System, and Assistant character chats each receive exactly one identity — through the universal token or their matching type token — and the field Preview shows each type's resolution via the Preview character type control. - UC-5 — Document → Advanced and a compatible Advanced → Document change are staged under the one Save/Cancel pair. Document → Advanced rewrites no row/content and preserves assembly; converting a shared Advanced row isolates it with COW.
- UC-6 — In Advanced, a creator can stage Enable inline tokens on one row while other legacy rows remain version 0; Cancel restores it and Save does not alter another mode sharing the original row.
- UC-7 — Workbench lint inherits its persisted or hypothetical Entry/base/flavor plan + Web door; standalone defaults General + Web and can choose context. It distinguishes lorebook/persona/character/BYOC/platform sources and labels base/flavor candidates reachable, shadowed, enabled, or unavailable without unioning them.
- UC-8 — A project contributor can propose Document content changes and a manager can review/apply them without breaking the one-row shape; the existing Advanced row create/update/delete/disable proposal journeys remain reachable and working.
- UC-9 — Document and Advanced expose the same description/tags/Mature Themes/publish scheduling/prompt visibility/pre-check/comments/review-lock lifecycle and commit all staged changes through one always-visible Cancel/Save pair. Mode settings lets the creator enable and actually author an Enhance prompt with role, interval, and append-at-end behavior; blank or unscheduled enabled configuration blocks Save, turning it off disables delivery without destroying staged text, and Beat/Prose settings remain independent. Editing clears a pre-check result; while dirty the action says Save to check, and a displayed result names the matching saved version.
- UC-10 — The complete create/edit/sample/save flow works at phone width with keyboard and screen-reader navigation.
- UC-11 — Test drive is not offered while dirty and never saves. After Save, the creator chooses a reachable Entry/base + exact flavor set, outer fallback, isolated hypothetical plan, or Quick test. BYOC requests a conversation-only character. The created conversation reports the expected source/profile/Entry/base/flavors/package/character/fingerprint; an unsaved Entry/Profile never claims mapped behavior. Canceling back to the exact previously tested saved version restores its readiness without a redundant Save.
- UC-12 — Every frozen v1 template, including identity-only Blank canvas, matches exact every-empty/mixed/every-filled assembly snapshots and completes one deterministic mock-LLM Classic pipeline turn. Optional persona/scenario/journal blocks drop with no separator residue on Discord; Hybrid copy explains the planning/prose boundary. Stochastic prose quality is evaluated by the separate named rubric, not guessed by this binary criterion.
- UC-13 — From the existing share entry point, a prompt-edit collaborator can open the capability-scoped Document/Advanced aggregate, edit only permitted prompt fields with one Cancel/Save pair, and acknowledge coarse publication impact without seeing owner-only fields/package identities. A prompt viewer instead receives a read-only content Preview when prompt visibility permits it.
- UC-14 — A package owner who wants wildcard/longest-literal model matching can find and use an explicit "opt into corrected resolver" action in the Package Workbench, see policy 0 vs policy 1 winners before committing, and acknowledge impact through the standard reverse-impact flow. No character or package is ever moved, re-reviewed, or unpublished without the owner initiating it.
- UC-15 — In a Model Profile, a creator sees Entries as Base prompts and, with one Profile Cancel/Save pair, authors/import-clones up to 12 optional Web Classic Flavors (4,000 characters each/20,000 active total) plus named exclusivity groups. Structural identity/provider/role/stage/settings/size violations block; suspected required/safety prose warns and enters review. Preview tests every user-enableable Flavor against every Base plus default/maximum envelopes without an exponential combination gate.
- UC-16 — In a Web Classic package chat, the How drawer shows exact Base/provenance plus accessible Style & rules checkboxes and nullable groups with None — Base only. An acknowledged toggle changes the next accepted turn, spends no Echoes, and survives same-profile/switch-back rules. Empty/all-hidden/no-winner/read-only/stale-conflict/new-choice states are understandable and non-leaking. Hybrid says the choices require Classic; Direct/Discord never silently apply them.
- UC-17 — From Package Workbench, an authorized package/project editor can inspect a bound public/project-reused Profile’s Base mappings and Flavor descriptions and stage only this package’s hide/initial-default overrides in the package form’s one Cancel/Save pair without owning the Profile. Profile editing and hidden prompt source remain unavailable unless separately granted; the UI never degrades the valid binding to an unexplained empty Profile. A pre-existing
packages.mode_idis shown read-only and survives unrelated Save; a new package has no direct Mode picker, and removal is an explicit owner/reverse-impact action. - UC-18 — In a package chat, Follow selected model attaches the automatic winner; Use profile Entry requires/selects a concrete matching preset and records manual-Entry provenance; Use Mode detaches only when effective enforcement
and package Mode lockallow it (the package Mode lock was retired 2026-09-20). Just switch Base preserves all Generation rows. Use model & Base clears only prior recommendation-sourced rows, preserves/lists user-authored overrides, and applies preset values to unset keys. Apply Entry recommendations then replaces the complete prior recommendation-sourced canonical set with the new sparse recommendations while preserving unlisted user rows. A user can always see effective values and how to return to automatic selection. - UC-19 — A Mandatory no-match blocks before allocation/LLM/Echo spend, explains that a supported model is required, lists supported patterns, and opens the matching preset/Entry picker or preset-creation path. Package-locked manual actions remain visible disabled with a lock explanation.
- UC-20 — Importing authorized keyless System v0 text creates an exclusive Flavor with a visible Legacy notice and no inline palette; token-looking text stays literal except
{{char}}/{{user}}. Enable inline tokens is one-way/staged, warns compatibly, Save upgrades only that Flavor, and Cancel restores v0. - UC-21 — A new-roster notice previews and starts the current package definition—not generic standalone New chat—with an optional still-valid preset carry-over and an explicit reset list for messages, manual plan, Generation rows/recommendations, custom/user additions, feature toggles, and Flavor state. It uses the current bound character (never silently carries BYOC) and receives the current roster. Branching instead keeps package context and the exact frozen roster.
- UC-22 — A migrated conversation that needs compatibility grandfathering visibly says Legacy selection — continue as-is or choose a supported model, persists
ready_legacy_grandfathered, and can keep using its retained valid Base-only plan. Relaxing enforcement/lock clears only the no-longer-needed exception/status while retaining provenance; a deliberate plan/conversation-preset change passes current rules, and Follow selected model exits accessibly.
Behavior:
- Across breakpoints, Raw/Preview belongs to the Mode prompt field: the token palette and prompt checks stay outside; Preview replaces only the raw textarea with exactly the resolved current Mode prompt text and contains no nested tabs, headings, cards, labels, badges, source metadata, pipeline rows, Test-drive actions, or notices; the raw source/caret stays mounted, and any caret-targeting action returns the field to Raw before focusing it.
- Enhance prompt enablement reveals and stages prompt text, role, repeat interval, and append-at-end through the Mode form’s one Save/Cancel pair. The UI-only toggle never becomes an API field: off projects interval
0plusenhanceAtEnd=false; enabled blank text or zero interval plus no at-end blocks Save; the authored Enhance prompt remains out of the Mode prompt field’s content-only Preview. System role displays the model-compatibility warning and exact automatic User-role[System instruction: …]conversion marker; User and Assistant do not. - Version-0 rows run the legacy expansion path; version-1 rows support row
{content}plus any number of inline tokens; both coexist in one mode. - V0 retains sequential
{content}then{username}replacement, including inside inserted ordinary-provider output. V1 expands only authored{content}/{username}nodes before insertion; inserted ordinary/inline values remain opaque except for the unchanged final lowercase{{char}}/{{user}}pass. - A version-1 ordinary row provider skips the complete row when gated/unavailable or only after all ordered candidates throw/return blank; a later nonblank candidate survives. Version-1 dependencies are canonicalized/non-recursive/resolved once, while version-0 repeated keys remain per-row.
- Inline-only
identityresolves every supported character type without registering a legacyprovider_key=identityprovider or changingcharacter/rules/assistantresults; a legacy ordinaryidentityrow neither injects nor activates identity budget/features. - C# and TypeScript golden fixtures agree on AST shape, dependencies/findings, aliases, exact-lowercase display-name nodes, pinned malformed recovery, UTF-16 spans, and astral Unicode. C# renderer fixtures alone pin conditional/value/no-cleanup output; SQL’s subset agrees on descriptors/keys only.
- A dynamic inline dependency makes the whole row non-static; journal is dynamic.
- Declared and assembled dependencies distinguish descriptor namespaces, zero rows from a nonempty keyless row, and include the journal fallback exactly when runtime does.
- A zero-Flavor profile assembles byte-identically to its pre-feature Base. A zero-row Base still expands all
DefaultSectionswhen a Flavor is enabled. Composite order is Base NSFW + leading System → enabled effective-order Flavors → remaining Base → one journal fallback → names → Base merge; downstream code never re-sorts layers by raw local order. Disabled/unavailable/unsupported-surface Flavors perform no parse/provider/dependency/budget work. - Only the exact automatic winner or explicit compatible
manual_profile_entryon Web Classic contributes its snapshotted Profile Flavors. The same sources on Direct, Discord, and Hybrid retain exact Profile/Entry/Base provenance withprofileSnapshotId=nulland an empty Flavor list. Policy-0 retained Base, manual Mode, legacy-unprovenanced, and package/character/built-in fallback get none. Two Profiles pointing at the same Base retain distinct provenance and, on Web Classic, distinct snapshots, but intentionally share a composition fingerprint when their exact enabled structural message stream is identical; differing enabled Flavors/order/content change it. - Every persisted plan uses one closed
composition_sourcevalue with the specified nullable provenance,generationStatus, auto-resolution projection, and preset-change behavior. Governing Profile is distinct from selected Profile, so a no-winner default can enforce Mandatory without donating Flavors. -
compositionFingerprintis stable for the same effective structural composition across conversations and toggle-away/back; conversation/snapshot ids, selection CAS, provenance, and metadata-only parent changes do not perturb it. Its schema version and actual synthetic DefaultSections/NSFW/journal hashes make code-defined prompt changes visible. The execution fingerprint additionally pins nonsecret preset/provider/model/effective Generation/allocation inputs; selection CAS and reverse-impact hashes remain separate. - Saved GET and draft POST return layered source sections + canonical merge-correct
finalMessages[]; draft base NSFW/merge + flavor changes update before Save, and the UI states excluded pipeline calls. - Catalogue endpoints expose implemented legacy placeholders and inline tokens with platform/surface metadata only.
- Copy, export v2/import v1+v2, mode projections, and editor routing preserve editor/expansion semantics.
- Feature state, budget, mode projections, project reads/readiness, and dry-run consume canonical results: universal identity counts for all character types while
character/rules/assistantcount only for their matching selected type; scenario/persona count only when assembled; tracker capability comes from bindings/toggle while missing explanation is informational; every profile Entry plus package/selected-character/built-in fallback is reported, but only reachable candidates are effective variants. - The inline catalogue is exhaustive and exposes
MayResolveEmpty+ exact recommended snippets;facts,tracker,greeting, and other ordinary-only keys typed inline remain literalunknown_tokenfindings. - Resolver policy 0 preserves shipped package-layer matching and null-preservation for valid nondeleted candidates. Policy 1 package layer uses no-model → nullable package fallback, otherwise case-sensitive exact → case-insensitive longest literal entry-contained-in-model →
*→ nullable package fallback, then profile/entry sort order;valid_nullclears an auto-resolved conversation mode so the outer selected-character/default chain runs. All policies skip deleted/broken modes. Readiness, mapped Test drive, public model-profile docs, Echo Guide, and Entry helper/shadow copy agree on both seams, BYOC, preset transitions, no-preset, special-character, and shadowed cases. - Resolution returns exact typed automatic/manual/legacy/fallback provenance. Turn acceptance freezes one immutable authoritative composition and its canonical fingerprint; runtime builder, Sample/Test drive parity fixtures, leak detection, budget, and message stats consume that exact plan, while impact and selection-CAS fingerprints remain distinct. No consumer guesses Entry from Base
mode_idor trusts a stale stored hash. - A Profile snapshot header is written on first Web Classic activation even for zero/all-hidden Flavors; child roster/order/group/default state is materialized atomically. Direct, Discord, and Hybrid Profile selections create no snapshot or Flavor state until a later supported Web Classic activation. Same-profile switches preserve link-id choices; a different Profile’s first supported use takes its then-current package-effective roster/defaults; switch-back restores them; later additions/unhides/default/order/group edits do not change the snapshot; current hide/delete suppresses a link; direct Mode selection detaches active composition without erasing retained snapshots.
- One discriminated transaction enforces
package Mode lock plusgoverning Profile enforcement (package Mode lock retired 2026-09-20), validates automatic winner or explicit Entry+matching preset, updates preset/Base/provenance/selection version and the surface-appropriate nullable snapshot, and optionally writes canonicalGeneration.*settings. Invalid/unknown keys, mismatched model, no Mandatory winner, stale CAS, or any write failure changes nothing. - Package Save/Start accepts only the versioned exact package-safe setting keys and canonical values listed in the Packages plan. Any
Generation.*,*Llm.*, secret/default/admin/entitlement, duplicate, unknown, or malformed setting rejects the whole mutation; package launch never auto-applies Entry recommendations or grants unavailable features. - Web, direct, and Discord never assemble a soft-deleted mode from an explicit conversation, profile Entry, package fallback, or character default. Guarded delete recomputes auto-resolved selections and clears explicit ones to the outer fallback; restore re-enters only through normal resolution and never resurrects a cleared explicit selection.
- Deployment performs no retroactive audit of existing publication-bound characters/packages: no stale review/approval/schedule is withdrawn, no live publication is removed, and no owner is queued or notified, for content that was already published under the prior extractor. New packages create at resolver policy 1; existing packages stay at policy 0 and move to 1 only through an explicit owner-initiated opt-in, atomically/replay-safely, without requiring Test drive.
- Mode/Profile updates use parent-version CAS + complete-set tokens; Mode/Profile/Entry creates use scoped idempotency keys + immutable canonical payload hashes. Base references recheck
can_use; Flavor imports require source view/copy then create an exclusive private row; Entry/Base/group/Flavor/package-override writes bump the Profile once and return the separate reverse-impact fingerprint. - Every specified mode/default-link/profile/base/flavor/package-override mutation routes through one reverse-impact service, locks/rechecks the composition/dependent fingerprint, and 409s on drift. Publication-bound dependents transition under the existing same/cross-owner policy.
- Agent-tool absent fields remain Advanced/0, explicit valid Document proposals work, and staging refuses invented provider keys; human and agent apply create the same aggregate shape.
- Character/profile/package extraction, checks, and moderator review include private defaults, every configured Entry base (reachable or shadowed), every user-enableable Flavor including default-off, package overrides/fallback, and the ordered outer graph; authorized review shows layered text/findings/Sample while BYOC private context is excluded.
Invariants that must stay true:
- Existing content semantics are untouched: every pre-feature row defaults to expansion 0 and preserves role/content/order/name substitution, imported token-looking text, unknown
identity, and per-row provider calls. Only journalIsStaticintentionally changes. -
{{char}}/{{user}}substitution behaves exactly as today, including inside provider output. - Provider output is never scanned for new inline content tokens.
- A missing Mode or zero-row Mode still receives the platform
DefaultSections, including when a Flavor is enabled; a nonempty keyless legacy Mode does not incorrectly receive them. - The platform
DefaultSectionsgive every character type (Character, System, Assistant) exactly one identity definition; an Advanced mode missing the matching identity key surfaces an advisory warning to its creator instead of silently dropping the character, and the Discord main bot's default mode covers the Echo Guide'sassistanttype. - Existing Advanced create/edit flow, multi-role rows, provider keys, caching controls, Discord behavior, and contributor row create/update/delete/disable proposals remain available.
- Existing Model Profile Entries remain
modeId-compatible and zero-Flavor Profiles produce the same prompt. Entry parameter fields remain recommendations; ordinary user Generation rows carryuserprovenance, while Apply Entry recommendations atomically replaces only the complete recommendation-sourced canonical set. Merely switching Base writes none; selecting another preset removes prior recommendation rows, preserves/lists user overrides, and uses preset values for unset keys. - Imported v0 Flavor rows retain legacy literal/global-name semantics until an explicit confirmed upgrade; no editor ever highlights/offers v1 inline tokens while still saving expansion 0.
- Existing creator limits, field-scoped permissions, review locks, scheduling/visibility, automatic publication checks, project/model-profile membership, owner-only comment settings, and comment defaults govern every aggregate/compatibility write; advisory Content pre-check does not block ordinary Save, and no in-scope mode aggregate or effective-mode mapping mutation silently stays live on publication-bound work.
- Existing preview modals continue working against the compatible typed DTO.
- Prompt confidentiality governs Base and Flavor sources independently across preview/copy/export/Sample/dry-run. A Flavor row is exclusive to its Profile; importing another prompt requires source view/copy and clones privately, so Profile visibility never re-delegates hidden source. Cards/toggles may show allowed descriptions, while Admin moderation is the explicit exception for source text.
- Reusing or editing a package/project does not imply ownership of, edit access to, or prompt-source visibility for a bound Model Profile/base/flavor. The context read proves the requested relationship and returns independently computed capabilities/redaction for each layer.
- Share editors remain prompt-aggregate-only (Document content-only; Advanced row CRUD/expansion as currently granted), contributors proposal-only, viewers read-only, and moderators review-only according to the capability matrix.
- Editing a Mode row never mutates another Mode consumer; editing a Profile’s exclusive Flavor row has no other content consumer. Import/copy creates a new row, and unlink/delete never destroys an unrelated source.
- Flavor is contextual link/group state, never an intrinsic sub-prompt flag or inline macro. Base owns identity and all required/safety/settings behavior; structural Flavor constraints block server-side, semantic optionality is guidance/review, and users can always choose off/None — Base only.
- Governing Mandatory enforcement is authoritative server-side for supported-model/Entry/Base selection;
(retired 2026-09-20), while creator-defined automatic model re-resolution remains allowed. Neither turns optional Flavors into requirements, and a no-match Mandatory plan cannot generate through an outer fallback.packages.mode_lockedhas higher precedence over manual plan overrides - Conversation create/update/Send and preset compatibility paths cannot write
ModeIdor any selection field around the discriminated transaction: create records a typed source, generic update delegates/rejects, Send rejects its old per-message Mode override, productionfn_upsert_conversationis dropped/delegated, the migration primitive is application-revoked/backfills before runnable use, and guarded repository/SQL writers prevent partial state. - Bound trackers still inject/evaluate and their toggle remains writable under a Document mode with no tracker row; missing explanatory prose is only a separate warning.
- Policy-0 exact/SQL-pattern-substring/no-wildcard and stale-null preservation stay compatible for valid nondeleted candidates indefinitely, unless the owner explicitly opts the package into policy 1; policy 1 intentionally adds literal
%/_/\,*, and discriminated-null clearing. The deleted-mode safety barrier applies to both. Only the authorized forced Sandbox path bypasses the active production resolver and labels that fact. Live profile links remain v1 behavior until the Workbench’s planned snapshot-pinning migration supersedes them. - Document/Advanced/Profile editing, Flavor/default/package-override changes, plan switching, Flavor toggles, lint, and Sample preview spend no Echoes and require no subscription; only a generated Test-drive/chat turn follows ordinary charging.
- Test-drive generated turns obey ordinary conversation limits and BYOK/Echo charging.
Edges:
- Unknown simple tokens remain literal. A stray closer is literal for one marker; an unclosed opener is opaque through EOF; nested syntax is opaque through the matching outer close; a mismatched opener is opaque through the first closer then parsing resumes; and a balanced unknown block is wholly opaque. Inner dependencies do not declare, the final lowercase
char/userpass still applies, and specified findings block. - Empty Document content, missing/conditional-only/duplicate identity,
{content}without a provider, and Advanced-only identity tokens block with source-specific spans. - Unknown ordinary provider keys warn but do not make existing/imported Advanced v0 rows unsavable; agent-created unknown keys block.
- Repeated dynamic tokens trigger one provider resolution and render the same value at each occurrence.
- A v1 export with no new fields imports as Advanced/legacy; an invalid v2 Document aggregate returns 400 and writes nothing.
- Copying a Document mode yields another Document mode with inline expansion intact.
- Copying/previewing/exporting a private or prompt-hidden source without prompt rights is rejected without leaking text or existence details; a valid copy starts private, unscheduled, and prompt-hidden.
- Generic prompt POST/DELETE, the generic mode comment endpoint, and malformed share/proposal writes cannot violate Document structure or race the parent; proposal validation/approval and owner-only comment changes occur under the same transaction/parent lock.
- A stale
expectedVersion, row-set token whose encoded set/order no longer matches the server, concurrent compatibility mutation, immutable idempotency-hash mismatch, and foreign/unlinked/duplicate row identity return deterministic 409/4xx responses without partial writes. An unchanged token permits intentional omission/deletion; modes beyond the old page size retain unseen rows. - A post-commit response-loss replay with the same create key/hash returns the same resource id and current authorized aggregate even if the creator is now at their count limit; a different canonical payload never reuses it.
- Draft-preview failure/stale response never blocks typing or replaces newer content; local syntax lint remains and server/context findings are marked stale.
- Draft preview rejects an inaccessible/mismatched private package/profile/Entry-draft context independently of mode authorization, without leaking bindings; a valid unsaved Entry is labeled hypothetical and cannot launch mapped behavior before Entry Save.
- A guessed profile id, mismatched package/project relation, removed binding, or inaccessible private profile receives the established indistinguishable 403/404 response; no Entry, flavor, override, version, or prompt-source detail leaks.
- Flavor identity-family content, provider-keyed/non-System/unsupported-stage rows, cross-parent attachment, >12 active rows, per-row/aggregate size excess, duplicate links/group keys, multiple group defaults, and package overrides that create a group conflict fail with field/span-specific errors and no partial write. Import without source prompt-view/copy returns the non-leaking denial and creates no row.
- Profile aggregate Save requires complete token-guarded
groups[]+flavors[]; omitted active members are intentional soft-deletes only under the matching full-set token, group keys never mutate, restore is explicit, and a partial/stale panel cannot delete or orphan rows. - Every package with active Profile bindings has exactly one active normalized default after migration and after every link/unlink/delete/restore/reorder transaction; an empty binding set has none. Conversation snapshot history survives live package-Profile unlink/rebind, and deferred constraints reject any child whose conversation/Profile/Flavor parent identities disagree.
- No winning Entry means no Profile Flavors and emits
profile_flavors_without_winner; only policy 1 after owner opt-in lets*provide catch-all. A package/character/built-in fallback can never inherit the last Profile’s Flavors; governing Mandatory instead blocks generation on no match. - A Flavor added, newly unhidden, defaulted, reordered, regrouped, or moved stage after that Profile’s conversation snapshot does not appear or change its roster/choice/order/group; the narrow effective-roster comparison shows the new/updated-choice notice. Content/label/description/Entry/metadata edits and hide/delete alone do not falsely show it. A later hide/delete suppresses a snapshotted link; unchanged restore/unhide revives only a link already in that snapshot. An unavailable or unsnapshotted Flavor UUID cannot be toggled by guessing it.
- V1 package UI labels Profile/Base content as live-linked and the Flavor roster as the one frozen slice. Without package/component version snapshots it offers no Update, Keep current, or “version you started on” claim; roster changes use the specified package-aware new-conversation flow.
- Deleting a Flavor group without ungrouping/reassigning all active members fails atomically; a valid group edit affects new snapshots while existing snapshots keep their copied group key/label/nullable-selection behavior.
- A null+locked or deleted/broken bound character blocks package Test drive; a creator-private bound character remains usable through package encapsulation. A null+unlocked BYOC package remains valid and accepts a directly accessible conversation-only
testCharacterIdwithout package mutation or implicit greeting import. Missing greeting and unavailable Web-only tokens produce the specified contextual result and Discord still assembles the remaining document. - Normal public Start Experience remains unavailable for a null-character package until the separate greeting-ownership/BYOC launch contract exists; only the labeled creator Sandbox accepts its conversation-local test character.
-
Package Plan lock blocks manual Entry/Mode selection but not creator-defined automatic resolution or available Web Classic Flavor toggles. “Zero customization” is shown only when no Flavor or other unlocked control actually remains.Withdrawn 2026-09-29: the package mode/plan lock (packages.mode_locked) was retired 2026-09-20 (79bd3fa7b,767b1daaa) — Model Profiles answer which mode runs where, and the reader keeps manual Entry/Mode selection. See packages § locks. - Multiple eligible plans/characters/Flavor sets require explicit Test-drive choice; mapped creation locks expected source/profile/Entry/Base/Profile versions/Flavor snapshot/package/character/fingerprint and rolls back on any different winner or parent state. Outer fallbacks remain testable only when matching the edited Base; forced plans cannot silently attach another Profile’s Flavors.
- Entry create/update and Character default-mode create/change revalidate referenced Base
can_useunder the parent write/lock and give inaccessible/nonexistent private UUIDs the same non-leaking failure. Flavor create/import/edit validates exclusive ownership and import source-view/copy without exposing the source. - Atomic plan/Entry-recommendation failure—including one invalid setting, Entry/model mismatch,
package Mode lock(retired 2026-09-20), governing Mandatory violation, stale selection version, or Flavor-group conflict—leaves preset, Base, provenance, settings, snapshot headers, and every Flavor state unchanged. - Backfill attaches a Profile/Entry only when the policy-specific current result is unambiguous and Base-equal; a valid nonattachable old automatic policy-0 Base becomes auto-resolving
policy0_retained_base, while genuinely nonautomatic unknown/manual rows use legacy/manual sources, all with no Flavors. Lookup/error remains retryable. A narrow grandfather flag/status preserves a then-invalid Mandatory/locked retained Base and never survives a fresh package conversation or deliberate plan change. Branch first resolves stale/normalizes the flag; failure rolls back, while success preserves package context and frozen roster withresolution_stale=false. - Toggle acknowledged before Send is included in that next turn’s immutable plan; a concurrent later toggle or Mode/Profile edit cannot leak into or split an already accepted turn. Stale toggle/Send versions return/refresh deterministically with no Echo charge or partial UI flip.
- Web Classic no-winner, zero-Flavor, all-hidden, read-only, removed-link, stale-conflict, and new-choice states render the specified accessible notice/EmptyState/action. Direct/Discord/Hybrid never apply or advertise an uncontrollable Flavor.
- User/conversation preset/model setting insert/update/delete, preset config update/hard-delete, and preset-reference cleanup succeed even when a dormant Mandatory conversation has no winner; affected conversations are marked stale in the authoritative transaction and individually become ready/retained/grandfathered/
mandatory_no_matchon open/Send without invented overrides, cross-conversation rollback, allocation, or Echo spend. - Branch/restart/create racing preset/Profile/Entry/Mode/character mutation or hard-delete serializes/retries through the shared ordered fence. The child either validates against the post-mutation graph or is not created; no runnable child commits copied old state with
resolution_stale=false, and unconditional Send revalidation catches any independently corrupted marker. - Turn acceptance freezes one concrete prompt + LLM execution object. A later preset/settings/model edit or hard-delete may affect only later turns; the accepted turn’s Base, provider/model, Generation values, allocation, call, and scalar no-FK stats remain internally identical.
- Entry removal is a Profile-locked soft delete with explicit restore; all resolvers exclude it, stale conversations transition before their next turn, and accepted stats keep copied UUID provenance. Account merge transfers the Profile plus every active/soft-deleted exclusive Flavor
sub_promptto the surviving owner. Account deletion first suppresses/nulls live conversation and snapshot refs, then removes the Profile, its exclusivesub_prompts, and theirsub_prompt_contentswithout being blocked or leaking/orphaning prompt source; an unexpected second parent aborts deletion. - A Sandbox Test-drive conversation persists its bounded immutable Base/hypothetical-Flavor/nonsecret-preset manifest, is owner-only/nonpublic/nonshareable/nonbranchable, never fabricates Profile/Entry FKs, ignores later nonsecret preset edits, resolves current secrets, and blocks later turns when the forced Base or required preset is deleted/inaccessible.
- Mode/Flavor hide/delete and conversation re-resolution are atomic: injected lookup/re-resolution failure leaves the source and every explicit/auto selection unchanged; success makes every turn accepted after commit omit the source and never revives a cleared explicit selection on restore. A turn accepted before commit may finish only its already materialized valid plan.
- Preview and mutation endpoints return the established 403/404/409 behavior for inaccessible, prompt-hidden, review-locked, or concurrency-conflicted modes.
- Any injected mode-aggregate failure rolls back mode metadata, comments, prompt/content, links/clones, project item, character/package publication transitions, and proposal state; any injected Entry-Save failure rolls back its mapping and dependent review transitions without deleting the already-created mode.
Anticipated file map
- Core: expansion-aware parser/catalogue/identity helper; Base-fallback-first, leading-System Web Classic Flavor composer; immutable prompt + concrete LLM execution plan with composition/execution fingerprints; composite introspection/cache/journal/staticness/merge; golden grammar/composition fixtures.
- Database C#: complete Mode/Profile aggregate reads/tokens; CAS/COW/exclusive-row/create-idempotency writers;
EffectiveModeDependencyImpactService; exact/policy-0-retained/manual/legacy plan resolver/provenance; atomic conversation preset/plan/recommendation-setting/toggle service; stale invalidation + accepted settings materialization; budget/feature/leak/scalar-audit-stats/ProjectRead/redacting DryRun; character/Profile/package moderation; agent tools. - Database SQL: Mode/Profile version/idempotency + Entry soft-delete columns; Flavor groups/exclusive links, package overrides, one-default binding guard, copied UUID/nullable-live selection state + empty-capable Profile snapshot headers/children, recommendation-setting provenance, Sandbox manifests; expansion loaders; context-free Base dependencies + Web Classic effective-plan projection; discriminated resolver/re-resolution/backfill/branch/package-restart functions; all setting/preset delete invalidations; guarded default/Entry/Flavor/package mutations; legacy package-Mode preservation; retired/revoked direct conversation Mode writers; moderation/check fan-out; changelog and
v1_run_all.sql. - ServerAPI/AuthService/Discord: Mode/Profile aggregate endpoints plus capability-scoped package/project Profile reads; layered preview + hypothetical Entry/Flavor context; prompt gates; atomic discriminated plan/Entry-recommendation/toggle/package-restart APIs; rejected Send-time Mode bypass; secure copy/export/import; mapped/forced/BYOC Test drive; exact agent/read consumers; Base-only unsupported-door loaders.
- AdminAPI/adminConsole: Base/Flavor effective-plan Sample endpoint/DTO/DI, dependencies/lint/fingerprint, and layered moderation presentation including default-off Flavors.
- shared/clientConsole: shared CodeMirror/Comment fields; Mode shell/Token editor/templates; Model Profile Base prompt Entries + Flavors panel/resolution preview; package overrides + read-only legacy fallback; How-drawer Style & rules/exclusivity, provenance/status, effective-setting confirmation, and package-aware restart preview; corrected atomic Apply Entry recommendations; Test drive/shadow helpers/collaboration/resolver opt-in. Consolidate preview clients.
- Docs/knowledge: rewrite Mode & Model Profile Bundles as the historical intent absorbed here; update public Modes/Creating Modes/provider/Model Profiles/Characters, Feature Flags, Packages/Workbench, Hybrid Phase-2 boundary, and Echo Guide Mode/Profile/package/character help. Teach exact resolver semantics, Base vs Flavor, optional Entry recommendations, and type-specific legacy identity accurately.
Related
- Design Principles — progressive disclosure and Packages as the creator/user bridge.
- Packages / Creator Workbench — primary creative unit and create-in-context host.
- Workbench Assistant — shipped tool-pack consumers this engine upgrades.
- Model Profile Base Prompts & Flavors — original Bundle-era product intent, reconciled with this implementation contract.
- Mode-Specific Lorebook Injection — Advanced per-lorebook targeting.
- Trackers — separate User-role state injection.
- Hybrid Narrative Pipeline — live v1 and future Advanced role-pair authoring.
- Manifesto — creative-writing purpose and human review contract.