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_kind never gates runtime.
  • Runtime: InlinePromptExpander (Core/Pipeline/Providers) — {{key}} + non-nested {{#key}}…{{/key}}, whitespace-tolerant keys, unknown/malformed stays literal, alias canonicalization via PromptKeyCatalog, per-build memoized resolution through the SAME content providers (PromptContextManager.ResolveInlineKeyAsync), reserved {{char}}/{{user}} untouched for the global pass. identity is inline-only vocabulary inside the expander, NOT a catalogue alias — the §identity carve-out (a legacy v0 row free-keyed identity stays 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 while editor_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 real InlinePromptExpander and 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-conversion are 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_document does 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 → document branch, in the same SQL file so the two rule sets can't drift) + GET /api/creator/modes/{id}/editor-kind report canSwitchToDocument plus a documentBlockCode — multiple_rows | keyed_row | non_system_role | shared_row — and the facts the copy needs (rowCount, providerKey). ModeCompositionPanel disables 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 existing ModePromptsPanel or the new ModeDocumentPanel (textarea + catalogue-served token palette with caret insertion). Plain textarea, not the CodeMirror TokenTextEditor (still design). GET /modes/provider-keys now derives its key list from PromptKeyCatalog (the stale hand-maintained list — missing beat, 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, identity type-specific coverage validation.

Problem statement

Modes are the hardest creator entity to author:

  1. The mechanics are abstract. To place world knowledge in the prompt, a creator adds a sub-prompt, chooses the lorebook provider key, places {content}, chooses a role, and orders the row. None of those concepts maps cleanly to “let the model know my world.”
  2. Assembly is invisible. The creator cannot see where provider output lands or what the final message sequence looks like without starting a chat.
  3. 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)

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:

Legacy expansion (expansion_version = 0)

The current content path remains byte-identical:

  1. Resolve the row’s single provider_key (if any).
  2. Skip the row when that provider resolves empty.
  3. Replace {content} and {username} in the template.
  4. 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:

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

  1. Expansion is gated per sub-prompt by expansion_version = 1. Never by editor surface and never by shape inference.
  2. 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.
  3. 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.
  4. Unknown {{tokens}} stay literal and produce a lint warning. A typo is visible; content never silently disappears.
  5. 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.
  6. 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.
  7. Feature gates apply once at provider resolution. A gated-off provider resolves empty; conditional segments then drop normally.
  8. 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.
  9. 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

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.

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 — DefaultSections now carries character / rules / assistant, each type-gated, so exactly one fills (SystemPromptBuilder.cs, pinned by WebPromptCompositionTests.NoMode_EveryCharacterType_GetsItsDefinitionExactlyOnce). Still open, by this section's design: an Advanced mode with only a character sub-prompt drops a System/Assistant character entirely, and nothing tells the creator — the partial_identity_coverage lint 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 (an assistant), run under BotBehavior.ModeId's default mode ("1", whatever row that is in production); if that mode has no assistant sub-prompt, the Echo Guide runs with no definition. Fix shape (owner's call): an advisory, non-blocking partial_identity_coverage warning 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)

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.

  1. 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 = 1 templates. A v1 row provider and matching inline token can point to the same ordinary descriptor/cache entry; inline-only identity has its own descriptor.
  2. Assembled dependencies — what the builder actually attempts:
    • no mode or zero sub-prompts → SystemPromptBuilder.DefaultProviderKeys;
    • nonempty mode → declared keys plus the automatic journal fallback when journal is 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.
  3. 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.
  4. 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:

  1. no usable preset model → nullable legacy packages.mode_id (a wildcard means “any model,” not “no model”);
  2. case-sensitive exact model_identifier = preset.model match (unchanged);
  3. 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);
  4. wildcard * for a usable model;
  5. nullable legacy packages.mode_id when 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:

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

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:

  1. Base Mature/NSFW prelude, then the Base’s contiguous leading System rows;
  2. enabled Flavor System rows in effective order (current profile order for a draft/new snapshot; snapshotted order for an existing conversation);
  3. the remaining Base rows in their unchanged local order;
  4. one journal fallback only when the resolved Base + enabled Flavors declare none;
  5. unchanged global name substitution; then
  6. the Base’s merge_consecutive_messages behavior.

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

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)

  1. Extend ISubPrompt with ExpansionVersion and extend PromptKeyCatalog with palette/token metadata.
  2. 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.
  3. Leave the version-0 content/role/order branch structurally unchanged, including unknown identity remaining skipped. The sole intentional legacy metadata change is journal.IsStatic: true → false; regression tests pin all other fields.
  4. 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.
  5. Derive IsStatic from the row provider plus parsed inline dependencies. Any dynamic dependency makes the complete row non-static. Fix journal.IsDynamic in the same pass.
  6. Apply the unchanged global {{char}} / {{user}} replacement after row rendering.
  7. 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 a flavor inline token.
  8. 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.
  9. 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:

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:

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

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.

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:

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:

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

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:

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:

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

Editor experience (clientConsole)

Shared host and complete lifecycle

Build a reusable ModeEditorShell containing the complete existing lifecycle:

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

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.

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:

Add the generic substrate and app-scoped TokenTextEditor configuration to /dev/components.

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:

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

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:

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

  1. Add prompt_modes.editor_kind VARCHAR(16) NOT NULL DEFAULT 'advanced' with a CHECK for advanced|document, plus idempotent ALTER/comment and view/model plumbing.

  2. Add sub_prompts.expansion_version SMALLINT NOT NULL DEFAULT 0 with a CHECK for 0|1, plus idempotent ALTER/comment and all loader/result plumbing.

  3. Add model_profiles.version INTEGER NOT NULL DEFAULT 0, allow_view_prompts BOOLEAN NOT NULL DEFAULT FALSE, and immutable create-payload hash. Add model_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, require expectedProfileVersion, and bump once. Existing profiles start with no Flavors and hidden Flavor content. Entry create gets the same immutable idempotency payload hash.

  4. Add model_profile_flavor_groups (id, uuid, model_profile_id, immutable-after-create group_key VARCHAR(50), display_name VARCHAR(60), sort_order, is_deleted, timestamps) and model_profile_flavors (id, uuid, model_profile_id, exclusive sub_prompt_id, display_name VARCHAR(60), description VARCHAR(200), default_enabled, nullable group_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. profileSetToken covers the complete persisted group + Flavor identity/order/membership set; Save sends both complete active groups[] and flavors[] 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 nonexistent sub_prompts.version is referenced. Creation/import stamps the exclusive sub_prompts.created_by_user_id from the Profile owner and creates a private sub_prompt_contents row 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-parentless sub_prompts and sub_prompt_contents; it aborts rather than deleting payload that unexpectedly has a Mode/second-Profile parent or shared content row.

  5. Add sparse package_model_profile_flavor_overrides keyed by package_model_profiles.id + model_profile_flavor_id, with is_available and nullable default_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 a DEFERRABLE INITIALLY DEFERRED constraint 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.

  6. Add conversation selection state: closed checked composition_source including policy0_retained_base, checked generation_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 legacy mode_is_auto_resolved as the same-transaction derived projection. User-owned live-entity FKs are nullable ON 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, scalar package_model_profile_link_id_at_activation with no FK to the live junction, effective_roster_fingerprint, timestamps) even for an empty roster, plus web_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_settings with checked value_source='user'|'profile_recommendation', copied nullable source_profile_entry_uuid, and source_profile_version. Existing rows backfill to user; ordinary user writes always set user/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_plans row for composition_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.

  7. Add packages.mode_resolution_policy_version SMALLINT NOT NULL DEFAULT 0 with a 0|1 CHECK, 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.

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

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

  10. Keep context-free fn_mode_assembled_dependencies(mode_id) for Base grammar. Add Web Classic effective-plan dependency projection over exact enabled Flavor states; ConversationBrowseRepository applies character-type identity filtering after composition. Pin SQL/C# parity, including zero-row Base + Flavor and Base-only Direct/Discord/Hybrid.

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

  12. 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_base when 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.

  13. Add the shared retrying SelectionGraphTransaction helper (serializable isolation, fixed (kindRank,id) advisory-lock order, re-read-after-fence). Route fn_reresolve_package_conversation_mode plus 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-based resolution_stale marking 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.

  14. 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 production fn_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 reject Generation.*, *Llm.*, secrets/default/admin keys, or unknowns rather than smuggling automatic Entry parameters through package JSON. Toggle and Send use the returned selection version.

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

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

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

  18. 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_conversation to resolve stale/normalize grandfather state, then copy package_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 keep packages.mode_id=null, while ordinary saves preserve a pre-existing read-only legacy fallback and only an explicit reverse-impact action removes it.

  19. Export v2 carries editorKind and prompt expansionVersion; 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)

Non-goals

Slice plan

  1. Schema and runtime plumbing. editor_kind, per-row expansion_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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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

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

Behavior:

Invariants that must stay true:

Edges:

Anticipated file map