Hybrid Narrative Pipeline (Beats → Prose)
Status (updated 2026-07-04 — kb-audit found this stale): Phase 1 v1 is BUILT and LIVE, free-to-choose, no access gate. The "Concept" line below described the pre-build state and is superseded by the "as built" annotations scattered through this doc (Cost Model, §Architecture, the G1–G7 gap resolutions) — those were being kept current while this banner wasn't. Verified against the running code (not yet a live end-to-end product drive — see caveat): the New-Chat modal offers Classic vs Hybrid with an "Experimental" badge and the exact copy in Phase 1 (HybridChoiceModal.tsx); the collapsible Story beat panel renders beatJson on assistant replies, collapsed by default (BeatPanel.tsx); PipelineType.Hybrid is fully wired in ChatPipelineFactory (no longer the stub the paragraph below describes); a hybrid turn is billed its real two-call cost per the Cost model revision. Not verified: the Acceptance Criteria (v1) checklist below is still all [ ] — nobody has driven a live hybrid turn end-to-end (beat call → prose call → tracker/journal/summary extraction → billing receipt) and ticked them off. Do that before calling this "done"; until then treat the mechanism as shipped-and-live but not acceptance-verified. Superseded original text, kept for history: "Concept — load-bearing scaffolding already exists. PipelineType.Hybrid is defined in PipelineType.cs as 'Hybrid pipeline with multiple chained LLM calls (e.g., beats → style)'; WebChatRequest already carries a PipelineType parameter documented as 'WebChat (full) or Hybrid (multi-model)'; and ChatPipelineFactory.GetStageKeysForType has a Hybrid branch stubbed with 'platform-specific selection TBD'. This document specifies what that branch becomes." It depends on the eval-pass pattern proven by Journal / Trackers, the routing/composition layer from Model Profiles and Model Profile Base Prompts & Flavors, and the open-weight prose rail from Hosted Inference via Featherless.
What we are actually solving
Every lab benchmarks coding and math. Almost no one measures "does it feel alive." The roleplay and creative-writing audience is enormous and it cares about exactly one thing no leaderboard tracks: a model that holds character over long context, commits to a dramatic beat without flinching, understands subtext, and tolerates ambiguity without resolving it too fast. Echo of Dreams exists to take that seriously.
The structural problem is that the models with the horsepower to hold a 50-turn, multi-character narrative have all been RLHF'd toward conflict-aversion and people-pleasing — the edges get sanded off as models scale and accumulate training passes. Meanwhile the models that don't flinch (small uncensored open-weight models like vanilla Gemma) lose the thread on complex narratives: they forget established details, contradict themselves, and loop past a certain context depth. The viciousness is there; the horsepower isn't. The horsepower is there; the viciousness has been domesticated.
The value we want is not "go dark." Dark without authenticity is just edgeporn. The value is "stay authentic over comfort" — treat discomfort as information rather than a problem to resolve. A character's cruelty means something. Silence means something. Unresolved tension is allowed to stay unresolved because the story needs it. That is a craft value, not a content permission — orthogonal to the platform's hard limits. Those limits are enforced the same way for both pipelines: non-blocking moderation flags on messages (review, not generation-time blocking), so the structural split here is about craft, not content gating.
Two things make this hard to get from a single model:
You can't reason a small model into "authentic over comfort." A careful protective prompt can get a large model to embody the value, but small models need clear instructions and don't generalize the principle. Crucially, the resistance isn't an instruction-coherence problem you can argue your way past — it lives in the weights. Fighting it with a better jailbreak is the wrong frame. The right move is to structure the work so the model's trained-in flinch never activates — the same way you'd work with a human collaborator's blind spots instead of arguing them out of them.
"What happens" and "how it reads" are different skills. Narrative judgment — character motivation, consequence tracking, dramatic timing, knowing that the silence after the betrayal is the beat, not the confrontation — is one capacity. Visceral, committed prose that lands that beat and gets out is another. There is no reason one model has to be good at both, and asking one model to do both is what forces the compromise.
The core idea
Split the turn into two chained model calls, each doing exactly one job:
| Stage | Model character | Job | Failure mode it removes |
|---|---|---|---|
| Beat | Cold, analytical, psychologically literate | Decide what happens, why (character logic), and how the characters' history/trauma would shape its expression | Conflict-aversion in plotting, narrative drift, character inconsistency |
| Prose | Uninhibited, committed, stylistically consistent | Take the beat and write visceral, emotionally resonant prose. Zero hedging. Intense moments intense. | Hedging, explaining emotions instead of showing them, breaking intensity with safety language |
Neither model is asked to do the thing it is bad at.
The director is the heavy lifter; the prose is a polish pass
- The director is facts, the prose is presentation (owner, 2026-11-23: "The director is FACTS. the prose is PRESENTATION."). The director decides everything that is true: what happens and how it comes out, every word a character says, every name, number and rule, what each character knows and hides, and where a scene begins and ends. The prose decides how the reader meets it: what they see, what they feel, and what they may know yet. It may leave things out, but it never adds or changes anything. The full contract, its slices and its Acceptance Criteria live in the engineering spec,
docs-internal/architecture/chat-engine/HYBRID_DIRECTOR_AUTHORITY.md. - The beat director carries the story. It decides what happens: events, choices, what each character does, how the scene moves. The journal, trackers and summaries are all taken from its beat. Put the stronger, smarter model here.
- The prose pass only polishes. It turns the beat into prose: wording, rhythm, voice. It must not invent new events, facts, characters or choices. Spoken lines are the director's, word for word: the prose adds how a line is said (a tag, a pause, a gesture), never different words. What the beat marks as not yet revealed stays true and unsaid. On later turns the director reads its own past beats, not the prose, and the journal, trackers and summaries read the beat too. So anything new the prose adds is lost to the story's memory, and the next beat can contradict it. A smaller or faster model is fine for prose. The prose prompt says it in one line (owner, 2026-11-22, Relay eod-421), in the built-in
HybridPipelinePrompts.ProseSystemTemplateand the seeded "Visceral Prose" mode: "Polish the beat into prose; add no new events, facts, characters or choices." - Unassigned, the director runs on your chat model (owner, 2026-11-22, Relay eod-421: "when Beat is unassigned, it follows the CHAT model (your main storyteller), not the cheap helper stages"). Assign Beat its own preset to run the director on a stronger model than the chat.
Acceptance Criteria — polish-only prose, and the unassigned director (2026-11-22, Relay eod-421):
- The prose leg's system prompt carries "Polish the beat into prose; add no new events, facts, characters or choices." — on the built-in template and on the seeded "Visceral Prose" mode, fresh installs and upgraded databases alike. (Unit:
ProsePolishRuleTests,HybridSystemModeSeedTests; mock capture of the prose call.) - An unassigned Beat runs on the chat link, read whole (provider, model, key, timeout, thinking, effort, preset id), and is priced and keyed as the chat leg: own key → free, platform → priced. (Unit:
BeatChainTests,FeatherlessComputeCostEstimatorTests,EvalLegKeyIsolationTests.) - The AI models page names the chat (Story) slot as what an unassigned scene planning follows. (Unit:
AiAreaDefaultsReaderTests.)
Invariants:
- A Beat with its own preset or flat keys runs exactly as before, whatever the chat is. (Unit:
BeatChainTests.AnAssignedBeat_RunsOnItsOwnLink_FieldForField_WhateverTheChatIs,LlmPresetEnricherBeatFollowsChatTests.) Caveat, deliberate: a beat preset id that no longer resolves (deleted, or not the reader's to use) counts as unassigned, so that story's director moves from a helper stage to the chat model too. - No prose mode a person made or copied, and no edited or shared seed section, is rewritten by the seed's text upgrade. (Database:
HybridSystemModeSeedTests, step 2a.) - A protected reader's director stays on the all-ages lane (
SfwModelPinpinsHybridPipelineLlm.PresetId). (Unit:AiAreaDefaultsReaderTests.AProtectedReadersSlots_AreExactlyWhatTheirTurnRuns.)
This dissolves the flinching problem structurally instead of fighting it. A model that would refuse to write a scene will often have no problem noting that "Character A, who has established violent tendencies, acts on them here" as a clinical narrative event. Resistance lives at the framing level, not the content level — so separating the intent-declaration step (clinical, cold, "here are the events that must occur") from the prose-execution step (craft instruction, "render this") sidesteps a large chunk of the resistance on both sides. The beat model never has to write the ugly thing; the prose model never has to decide that the ugly thing should happen — that judgment was already made upstream, so its lack of a flinch becomes a pure asset instead of a liability we manage around.
The psychology layer
The beat model is not only a plot engine. Because it is cold and analytical with psychological understanding, it can annotate each beat with how a specific character's history would make this moment land — and the prose model simply shows it, without naming it.
Beat (what + why + psychology):
Event: Mara learns the letter was forged. She does not confront Aunt Vesh.
Why: Confrontation would force a break she can't afford yet — Vesh holds the deed.
Beat: The silence is the beat, not the accusation.
Psych: Mara learned young that losing control had consequences. Control, for her,
looks like stillness — she gets quieter, not louder, the more it costs her.
Prose model receives that and writes:
→ She set the letter down and smoothed it flat with two fingers, corner to corner,
the way you'd straighten something in a house that wasn't yours. "More tea?" she said.
No internal monologue announcing the fear. No "she felt the old familiar dread." The reader feels it through behavior. This is how trauma-informed fiction actually works: the psychology is structural, not decorative — it shapes what the character does, not what the narrator tells you they feel. The coldness of the analytical layer is a feature; you don't want empathy at the beat stage, you want accuracy.
Architecture
The Hybrid pipeline runs two model conversations in parallel, each with its own context window and its own history, handing off once per turn.
User turn
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BEAT CONVERSATION (own history: cold, structural) │
│ input: story context + journal/tracker state │
│ + beat-conversation history + user input │
│ model: Beat role (analytical, psychologically literate) │
│ output: structured beat — events, motivation, psych hints │
└─────────────────────────────────────────────────────────────┘
│ beat injected as a read-only DIRECTION block
▼
┌─────────────────────────────────────────────────────────────┐
│ PROSE CONVERSATION (own history: only ever sees prose) │
│ input: prose-conversation history + user input + beat │
│ model: Prose role (uninhibited, committed, consistent) │
│ output: the visceral scene ── streams to the user ──► │
└─────────────────────────────────────────────────────────────┘
│
▼
post stages: storage + billing as today; journal / tracker / summary
extraction now reads the BEAT, not the prose (see story-of-record below)
Why two separate conversation histories
The beat model maintains its own thread of clinical beats; the prose model maintains its own thread of prose. The prose model never sees clinical beat language as part of its own history — so it doesn't drift toward the cold register, and it can develop and hold a consistent voice across the session because everything in its context is prose. The beat model, symmetrically, is never contaminated by having to be a prose writer. Each model stays what it is.
This mirrors how professional writers work: the beat sheet is cold and functional ("protagonist betrays ally; ally doesn't react immediately; the silence is worse than the confrontation"); the prose draft is where that becomes felt. Two artifacts, two registers, one author splitting the labour across time. Here we split it across models.
The handoff: inject the beat as a user-role direction block
The beat output is handed to the prose call as a read-only direction block attached to (or immediately before) the last user message — not as a system instruction and not as a prior assistant turn.
This is the exact load-bearing decision the Trackers design already locked in for state injection, for the same reason: models echo patterns they see in system and assistant turns, but treat user turns as input they respond to, not a template to copy. A beat block in the system prompt risks the prose model reproducing the clinical "Event / Why / Beat / Psych" scaffolding in its narrative output. As the last user turn, the beat reads as "this is what you're responding to," which is precisely what we want.
The prose stage therefore reuses the existing prompt-assembly path; the beat block slots in as one more provider-keyed segment on the final user message, alongside (and below) any tracker/journal state.
Pipeline wiring
The Hybrid branch in ChatPipelineFactory.GetStageKeysForType (today a stub) gains a pre-LLM beat stage ahead of the prose LLM call:
PipelineType.Hybrid =>
PRE: hybrid_context → compute_allocation → beat_direction (new)
POST: prompt_leak_detection → storage → compute_settlement
→ engagement_charge → message_stats → summarization → journal_eval → tracker_eval
The beat stage is an IPreLlmStage that makes its own LLM call (via ILlmProviderFactory, resolving the beat role's model/params — see Model routing), persists the beat to a beat_json column on the turn's message (mirroring tracker_json, see story-of-record below), and writes the direction block into the context for the prose call. The prose call is the pipeline's normal LLM step. Storage is unchanged from WebChat; user billing charges the beat as its own line — HybridComputeLineProfile includes Beat among the turn's candidate cost lines, compute_allocation reserves it up front, and ComputeSettlementStage settles it from the beat call's real telemetry, so it appears on the per-message receipt (v1 pricing; operational design in docs-internal/architecture/billing/COMPUTE_COST_LINES.md). compute_allocation still runs before beat_direction so a turn that can't afford the full two-call estimate spends no compute at all, including the beat (G1). (As built 2026-09-24: a hybrid_leg_plan pre-stage (Order 400) runs before compute_allocation. It freezes the role-tagged Model Profile resolution and builds both legs' inputs, none of which depend on the beat: the beat leg (flattened or assembled) and the prose prompt's system part. The allocation prices both lines on those exact prompts, and beat_direction sends them from the same plan. The plan stage makes no model call. Before this, both lines were priced on the classic context as-is (HybridLegPlan; COMPUTE_COST_LINES.md §"No absorbing"). Later the same day the plan moved into hybrid_context (Order 100), which takes the place of context on Hybrid: it builds both legs from one read of the turn and assembles the conversation's own block only for a flattened beat — see The conversation's own block is assembled only when a leg reads it.) What does change: journal, tracker, and summary extraction now read beat_json instead of the prose response.
This is the inverse of the eval pattern, then partly a merge with it. Today journal/tracker eval runs after the response and reads the prose to extract state. The beat stage runs before the response and writes the direction the prose executes — and because the beat is already the structured "what happened," the downstream extraction reads it instead of re-deriving state from prose. The eval and the beat are the same structured pass viewed from two ends; see folding the eval into the beat call. It reuses the exact "separate, dedicated LLM call with its own model and prompt" shape the codebase proves out in
JournalEvalStageBase.
The beat track is the story-of-record
The prose is what the reader sees, but it is purely presentational. The structured truth of the story lives in the beat. So every downstream consumer that needs "what is true now" reads the beat, never the prose:
- Journal extraction (character/location profiles, state facts) reads the beat.
- Tracker extraction (HP, location, roster, …) reads the beat.
- Summarization (memories) reads the beat.
This is deliberate. Prose is dense with texture, mood, and ambiguity that is wonderful to read and miserable to parse — extracting "Elara's HP dropped to 58" or "the party moved to Level 3" out of three paragraphs of combat prose is exactly the lossy, error-prone round-trip that makes eval calls flaky. The beat already states it cleanly and clinically. Reading state from the beat is direct; reading it from the prose is reverse-engineering. It is also register-correct: summaries and journal profiles feed back into the beat model's context (memories and state are beat-side in the provider split), so keeping that whole loop in the clinical register avoids a clinical→florid→clinical translation on every turn.
As built (2026-06-25): the active-summary half of the loop is wired.
WebSummaryContentProviderinjectsWebSummary.BeatTrackContent(=beat_summarywhen present, elsecontent), so the beat reads back the clinical summary it produced; only the beat consumes it (the prose prompt is starved of the summary block), and Classic is unchanged (beat_summarynull →content). Two remainders, Phase 2: (a) the semantically-recalled L0 memories (WebMemoryContentProvider) still injectcontent, because retrieval matches the embedding generated fromcontent— closing that fully means re-embedding on the clinical register; (b) the summarization rollup's LLM input reads the children's prosecontent, never theirbeat_summary— the beat-track handling there is output-side gating only (WebSummarizationService.SummarizeSummariesAsync, taggedTODO(hybrid-phase2)). In v1 both are identical by construction (the two registers are the same text), so the divergences only matter once a separate prose-register summary exists — but Phase 2 must close both.
The beat is structural story beats, plus portrayal hints
The beat is a structural story beat — what happens, not key:value state (revised 2026-06-25; the original design used a story_state key:value map, which duplicated what Trackers do — so that map was removed and Trackers now distill their key:values from the beat). The output separates the structural record from the craft direction:
| Part | Fields | Goes to | Example |
|---|---|---|---|
| Structural beat — what happened, canonical | npcs, environment, plot, situation |
journal / trackers / summary and prose | npcs: "Vesh sets the forged letter down, says nothing — she will not give Mara the confrontation." situation: "Mara knows, and Vesh knows she knows; the silence is hers to break or hold." |
| Portrayal hints — how to render it | portrayal_hints |
prose + the director's own history — never the extractors | "Show control as stillness, not volume — she gets quieter the more it costs her. Don't name the fear." |
Portrayal hints are rendering directions, not story facts — they must not leak into the journal or memories. The extractors take the four structural fields; the prose takes those plus the hints, and so does the director's own beat history (it wrote them — shown its past beats without them it stopped writing them; MD-12, 2026-10-27).
This is also where your earlier observation lands: routing journal/summarization off beats puts more pressure on the prose pass, because the beat carries the full clinical detail and the prose's entire job becomes "remove the clinicality, keep the truth, make it felt." The portrayal hints are the pressure valve — the beat model, which is the one with the psychological literacy, tells the prose model how to warm each beat, so the prose model isn't reinventing the emotional read from scratch.
Storage and visibility — mirror trackers exactly
beat_json on web_messages is the Trackers tracker_json precedent applied verbatim, and it earns its keep three times over:
- Extraction source — journal/tracker/summary read it.
- Beat-model history — the beat conversation is reconstructed by interleaving user turns with each message's
beat_json; no separate hidden message track is needed. As built (2026-07-10): this interleave is the Phase-2 target, not v1 — there is nobeat_jsonhistory injector; v1 flattens the already-assembled prose prompt into a transcript for the beat call (BeatDirectionStage.FlattenPrompt, taggedTODO(hybrid-phase2); G3 describes the flatten). - Verification & edit surface — beats are shown the same way trackers are: hidden by default, with a
show_beats BOOLEANmaster toggle on the conversation (in the How drawer, besideshow_trackers), a collapsed beat bar below each assistant message, per-message expand, and inline edit with carry-forward. A user who sees the director steer wrong fixes the beat at message N; the corrected beat carries forward into the beat model's context (and, if the prose is regenerated, into the next render). Samemanual/evalsource attribution, same "eval skips manually-edited values" rule as trackers.
Consequence: the eval call can fold into the beat call
Once journal/tracker/summary all read the beat, the separate post-LLM eval pass becomes redundant in the hybrid pipeline: the beat model is already doing the structured reasoning, so it can emit beat + journal delta + tracker delta + portrayal hints in one structured output. This is the journal per-message-vs-summarization debate resolved by construction — in hybrid, the beat call is the eval call, so there is no "extra" call to amortize.
One caveat worth stating plainly: the beat is produced before the prose, so extracted state reflects the planned beat, not the rendered prose. This is fine as long as the prose faithfully executes the beat (which is its job — the prose model renders, it does not re-decide events), and "the beat is canonical" is the cleaner contract regardless: state is decided deterministically upstream instead of reverse-engineered from whatever the prose happened to say. Phase 1 may keep the eval as a separate pass reading beat_json; the fold-in is a Phase 2 simplification.
Model routing
The two roles need two different models, each with its own Mode and sampler parameters. Model Profiles are already the reusable model-pattern → Base-prompt → parameter-recommendation unit; Model Profile Base Prompts & Flavors explicitly retires a separate Bundle entity. Today a Profile resolves one primary role per turn. Phase 2 extends the same Profile aggregate to explicit roles:
Model Profile: "Authentic over Comfort"
├── Role: BEAT
│ ├── deepseek → "Beat Director" mode, temp 0.6 (cold, analytical reasoner)
│ ├── opus → "Beat Director" mode, temp 0.7
│ └── * → "Beat Director" mode (fallback)
│
└── Role: PROSE
├── gemma → "Visceral Prose" mode, temp 1.0 (Featherless-hosted open fine-tune)
├── magnum → "Visceral Prose" mode, temp 0.95
└── * → "Visceral Prose" mode (fallback)
Each role is an ordinary Model Profile Entry set—policy-aware pattern matching, per-model Base Mode, per-model recommendations, and policy-1 * fallback—tagged with a role discriminator. This keeps one Profile describing both halves, propagates to every package that references it, and survives model-version churn. The consumption contract (canonical form in Model Profiles — Hybrid-Ready): an Entry never supplies a model — each leg's concrete model comes from the settings/preset side, and the same-role Entry it matches supplies that leg's Mode and param overrides. No wrapper Bundle exists, and a public Profile stays credential-free.
As built (2026-07-12): the role discriminator is real end-to-end.
model_profile_entries.role SMALLINTshipped (database/v1/91_model_profile_entry_roles.sql: 0 = Primary, 1 = Beat, 2 = Prose, CHECK-constrained) with role-scoped uniqueness —(profile, role, identifier), so the same*may be Primary and Prose — through the repository, the creator API (create carriesRole, PATCH validates 0–2), and the workbench entries panel (role selector, per-role grouping, per-role fallback badges). The*wildcard tier is genuine in the resolver:fn_resolve_package_effective_modematches exact → substring → literal*, filtersrole = 0on every tier (a Beat/Prose entry never wins a classic resolution), and returns the winning entry id — persisted asweb_conversations.model_profile_entry_id(auto-resolve provenance; no FK, mirrors themode_idconvention, may dangle — readers LEFT JOIN) and used for exactisActiveMatchin the chat UI.Update (2026-08-04): the runtime now CONSUMES role-tagged entries — piece 1 of Model Profiles — Hybrid-Ready shipped. The sentence this note used to carry ("nothing consumes a role-tagged entry yet") no longer holds.
fn_resolve_hybrid_role_modes(database/v1/functions/47d_hybrid_role_mode_functions.sql) picks a pair-owner Profile — the first package-bound Profile in binding order carrying any role-tagged entry — and matches each leg's concrete model against that Profile's same-role entries, reusing the exact → substring →*ladder via the sharedfn_match_model_profile_role_entry.HybridContextBuildingStage(thehybrid_contextpre-stage, before compute allocation) resolves this once per turn into the turn'sHybridLegPlanand freezes it onIPipelineContext.HybridRoleModes, andBeatDirectionStagereads the frozen plan; per-leg mode precedence became entry →HybridPipelineLlm.BeatModeId/.ProseModeId→ hardcoded constants. The arrow still points the settled way: the entry supplies the leg's Mode only — the concrete model comes from the settings side and is an input to the match, and entry parameter overrides remain opt-in recommendations that nothing auto-applies. A Profile with no role-tagged entries changes nothing. Provenance lands onweb_message_stats.model_profile_entry_id(per leg: thehybrid-beatrow stamps the role=1 winner,hybrid-prosethe role=2 winner). The seeded "Authentic over Comfort" Profile (database/v1/92_seed_hybrid_model_profile.sql) now pairs the two system Modes. One precondition had to be built with it: package-start was hard-pinned to Classic, so no conversation could be both package-bound and Hybrid —fn_create_conversation_from_packagegainedp_pipeline_typeand the endpoint now honoursIsHybridon the package path. (Originally API-reachable only; since 2026-08-05 the gear-menu "New conversation" re-pick is package-aware and is the sanctioned UI entry — see the update note under the picker as-built block below. The package-page start still creates Classic without a picker, deferred with the rest of the new-chat flow.)
As built (2026-09-20): the leg model bindings are user-facing on the chat side.
HybridPipelineLlm.PresetId(beat) and.ProsePresetId(prose) — the preset-side half of the settings routing above, whichLlmPresetEnricherflattens into the flatHybridPipelineLlm.*/.Prose*keys — were seeded server-only (scopes = '{}'), so the pair was curated by the operator and the sections below speak in operator voice throughout (G7, UC-O2). That was the right call while the pipeline was experimental and while the platform was still trying to serve customization and convenience in one place. It is superseded: both keys are now{user, conversation}and are ordinary assignable stages on the chat side — Settings → Presets (user scope, thellm-stagesview) and the chat How drawer's Model section (per-conversation override, with the same dangling-preset warning and override badge as Chat/Summary). Neither leg breaks when unassigned: both fall through to the conversation's chat model (the beat since 2026-11-22, owner, Relay eod-421:BeatLlmService.ChainisHybridPipelineLlm → Llm; it used to walk the tracker / journal / summarization links first), so an unassigned row inherits rather than dying. This is not "we added knobs" — it is the chat/games surface split: chat is deliberately the customization surface, while a game built on this pipeline fixes the beat/prose pair and builds on that guarantee. Reasoning and this change as its worked example:docs-internal/vision/GAME_DIRECTION.md§"chat and games are two surfaces, not one product evolving". The beat's output cap (HybridPipelineLlm.DefaultMaxBeatTokens, blank → 8192, no ceiling — raised and unclamped the same day in377ecb78) rides along on the Beat row; the prose leg deliberately has no such knob — it rides the chat pipeline's generation settings viaProseSettingsOverride.
The prose role is the natural home for Featherless-hosted open-weight fine-tunes — the Magnum / Lumimaid (Gemma 27B) and RP-Ink (Qwen) lineages that preserve a base model's willingness to commit while adding narrative coherence. Featherless's flat-rate subscription and policy-free posture (model choice is the policy) make it the right rail for the uninhibited prose slot. The beat role wants the opposite kind of model: a cold, structurally-strong reasoner where clinical framing survives the positivity bias.
Modes: one hybrid "mode" is a pair of ordinary modes
Modes are the one piece that does not transfer unchanged — but the fix is not a new entity. A mode today (prompt_modes + sub_prompts + prompt_mode_sub_prompt_links, see database/v1/04_tables_prompts.sql) is already exactly "one model's prompt-assembly config": an ordered set of sub-prompts, each carrying a provider_key, a role (0=User / 1=Assistant / 2=System), and a template, plus the enhance / merge / summarization / nsfw_enabled settings. It produces one message array for one model that does everything.
The hybrid pipeline has two calls with two jobs, so each call needs its own prompt assembly — which is precisely what a mode already is. Therefore:
A hybrid "mode" is a pair of ordinary Modes bound by role—a Beat Mode and a Prose Mode—selected by the future role-tagged Model Profile from Model routing. No new Mode or Bundle entity. This reuses
sub_prompts, the Workbench editor, sharing, proposals, and parent-version locking. Embedding both halves into a new "hybrid mode" row would duplicate the entire Mode machinery into a second shape.
What is genuinely new is small:
1. One new provider key: beat
The director's output reaches the prose call through a new content provider keyed beat (or direction) — structurally identical to the existing journal / summary / recalled_memory providers. A prose mode includes a beat sub-prompt wherever the creator wants the direction block to land. Its default role is User (0), applying the Trackers injection principle verbatim: state and direction go on the last user turn, never system/assistant, so the prose model treats the beat as input it responds to rather than a template it reproduces.
As built (2026-07-12): the
beatkey now exists — with one deliberate twist on the paragraph above: placement is STAGE-owned, not section-owned.ContextKeys.Beat+ aPromptKeyCatalogdescriptor ship (the name isbeat;directionwas not taken as an alias), but the direction block must land on the last user turn, after history — a position section ordering cannot express — so noIPromptContentProvideris registered for the key. A prose mode declaring abeatsub-prompt therefore supplies only the framing template around{content}(= the direction body,HybridPipelinePrompts.FormatDirectionBody);BeatDirectionStagesubstitutes the body and appends the result to the last user turn, and a mode with nobeatsection gets the default framing (FormatDirectionBlock). On the classic path the unregistered key resolves empty and the section is skipped — the correct behavior for a mode carrying beat framing outside a Hybrid turn. The §5 editor gap stays open: the workbench's Provider Key field is free text with no picker and its guidance nowhere surfacesbeat; the docs-catalog half (thebeatrow in the Modes provider-key table) is done.
2. The asymmetric provider-key split is the design content
This is what makes two modes a hybrid mode rather than two unrelated modes. Because the mode's sub-prompt set declares exactly what its model sees, the mode is the context-routing config — no new mechanism needed. The editorial decision is which provider keys live on which side:
| Provider keys | Beat mode (cold, reasoning-heavy) | Prose mode (craft-heavy) |
|---|---|---|
character (full psychology) |
✓ — judgment needs it | minimal — name/voice only |
journal, trackers, recalled_memory |
✓ — state drives the beat | usually ✗ |
lorebook |
✓ — world logic | only if it affects prose texture |
persona |
✓ | ✓ |
beat (new) |
✗ (it produces the beat) | ✓ — the handoff |
| recent prose history | ✗ (own beat history) | ✓ — voice continuity |
| craft / style framing (static) | ✗ | ✓ |
This asymmetry is also a second authenticity lever: keep the safety-triggering world detail off the prose model and feed it a clean clinical beat instead, and you avoid re-arming the flinch the architecture just routed around. A prose model that never sees the heavy thematic context has nothing to flinch at — it has a craft instruction.
3. Mode settings that don't split evenly
- Summarization (
summarize_messages_prompt/summarize_summaries_prompt) — superseded for now (2026-07-25, provisional) by Prompt Presets: summarization decouples from Mode entirely, and the user's Summarization preset (or the built-in default) supplies the prompts in both pipeline types — the beat mode owns none. What survives from this bullet unchanged: hybrid summarization still reads the beat track, not the prose (see story-of-record) — only prompt ownership moved, not the input. Revisit if preset prompts running against beat-structured input degrade custom field extraction. (The original plan for the record: the beat mode owns the summary prompts and the prose mode's summarization fields are inert.) enhance_promptstays per-mode~~; each model gets its own reinforcement cadence~~. As built (owner decision, 2026-10-05): the conversation's mode's enhance prompt reaches both calls. The owner's reasoning: an enhance prompt that never reaches a model is the bug, so the fix is to deliver it, not to justify its absence.- The prose call has always carried it.
- A flattened director (a beat mode that declares no keys) has always carried it too. It gets the conversation's turns as Classic builds them, flattened into one transcript, with one difference since 2026-10-05: every enhance copy is a
[User]line, so an Assistant-role copy no longer appears as an[Assistant]line, and the transcript no longer ends on one. - An assembled director (the default) now gets it as well, every copy as a user message:
- The at-end copy opens the reader's turn, after the latest story state and before the Author's Note.
- The interval copies follow the mode's cadence over the director's own history: in front of every Nth beat-history unit it is sent, at most one per user turn.
- Never as an assistant message. The director's assistant turns are its beats and nothing else, and a trailing prefill would make it continue the writer's prose instead of writing a beat.
- A leg mode's own enhance (the bound beat mode's or prose mode's) applies to its own call, on its own interval and at-end settings, beside the conversation mode's. (As built 2026-10-05.)
- The beat mode's copies reach only the director, always as user text, on both shapes. A key-free beat mode, which has no section to place its enhance in, gets its copies in the flattened transcript, counted over the same history the conversation's copies are counted on.
- The prose mode's copies reach only the writer, in the mode's own role, the same way the conversation mode's do: a user-role at-end copy opens the reader's turn, and an assistant-role one is the prefill.
- Where a leg mode's copy and the conversation's land in the same place, the leg mode's comes first and the conversation's last: at the start of the reader's turn, the conversation's copy is the one just ahead of the Author's Note, and in a prefill it is the text the reply continues from. A mode bound as both sends one copy.
- On the director's own history, user turns that fold together (the replies between them carried no beat) take at most one copy of each mode.
- A mode that also places its enhance in an
enhance-keyed section gets that copy in its block as well, as on any call. - The seeded leg modes carry no enhance, so a default chat is unchanged.
nsfw_enabled/ Mature Themes most naturally sits on the beat mode (let the director plan hard beats without reflexive refusal); the prose slot is typically an uninhibited fine-tune that doesn't need it. A deliberate decision, not a default. Confirmed 2026-09-24 (owner): the flag stays a property of the mode, and each leg obeys its own mode's flag — the beat leg the beat mode's, the prose leg the prose mode's; the conversation's own mode governs only the conversation's own prompt. (With the seeded director now on the assembled path — §4 — that is literally what reaches each call: the flattened shape used to carry the conversation mode's NSFW text inside its transcript as well as the beat mode's.)merge_consecutive_messagesstays per-mode (the prose fine-tune and the beat reasoner may prefer different message shaping).- The beat output format belongs to the beat mode (decided 2026-09-20, 📋 not built). The beat is a prompt and a format, and the beat mode is what defines the output — so the description of that output lives on the same mode, not in a pipeline setting and not in code. Today it is in code:
BeatParseraccepts three layouts (JSON, labeled text, freeform prose) — two of them over five hardcoded fields with hardcoded routing —npcs/environment/plot/situationgo to the prose and the extractors,portrayal_hintsto the prose only — and the third as one text, routed as record. A beat mode that instructs any other structure still "works", because an answer the parser reads as no beat structure is a freeform beat and the prose is steered by it regardless — but its own fields are then read as one record text, so a field the mode meant as prose-only direction still reaches journal, tracker and summary extraction. A custom field format therefore half-works today, which is why routing has to be declared rather than inferred. (Plain prose direction no longer half-works: see the freeform note below.)As built (2026-11-07): freeform is a first-class beat format beside JSON. Owner: "make sure the beat director in hybrid supports freeform AND json - we need to support both". A beat mode that asks its director for plain prose gets a freeform beat (
HybridBeatState.Freeform, stored as{ "freeform": …, "portrayal_hints": …, "scene"? }): the prose leg's director's note carries it verbatim, the extractors and the director's own history read it as the story beat, and it parsesOk— no failure log, no page. Before, it was the raw degrade: the whole prose innpcs("Characters: …" to every reader), logged as a failure that paged on the platform's key. A prose beat that ends in aScene:call or a labeled hints line (what the beat ask invites) is the freeform beat plus that field — superseding, for that shape, the 2026-10-27 quiet-turn fold of the text before the first label into the hints. How a beat is read is still the answer's own shape (JSON tiers first, then labeled text, then truncation repair, then freeform), so a beat parses whatever its mode asked for. What the director is asked for is now the beat mode's contract, a field on the mode: see The beat contract below, which supersedes this note's "no format setting". The fallback (owner, 2026-11-07: "Beat director should always fall back into 'freeform' when the json parse fails"): every answer no structured tier reads is a freeform beat too — a broken JSON beat (it starts with{, or carries a beat object's opening,{"npcs":quoted or not, that no JSON tier reads), one wrapped in prose or a code fence, one cut at the output-token cap with no structured tier reading it. Its text is kept verbatim (the fence stripped, the lookups / checks / scene-call lines out, as for any freeform beat) — the writer's note, the stored{ "freeform": … }twin, the director's own history next turn and the extractors all carry it — with statusFallbackas the tier marker and one line by shape on the truncation salvage's rule (our key, our model choice: a Warning on the platform's key, or with no sponsor marker, and no cap; Info on the reader's own preset or at the cap; the salvage of a beat object cut mid-field and the fallback page alike). Verbatim rather than a JSON shell stripped by heuristic: the director's own words are the beat, and reading keys out of broken JSON would be a structured salvage, not freeform. A valid JSON answer no beat field reads (unknown keys, a list under a beat key, a JSON string) is lossless to clean, so it reads as freeformkey: valuelines, the four story keys under the writer's labels, bare or behind a preamble, at the same level (the platform's model ignoring the schema pages like a broken beat). An object behind prose that every tier reads as empty, or that was cut before its first value, leaves only the prose as the beat (a one-line introduction such asHere's the beat:is no prose, so no beat). A valid object with nothing in it is an empty answer, not a broken one: no beat and no line, bare or wrapped. A stored beat read back (the director's history, a prose-only regeneration, the extractors:BeatParser.ParseStored) never logs; it was judged when its turn wrote it. Keys read in any case ("Plot","Portrayal_Hints"), and the engine's own keys (hints, scene, lookups, checks, a visual-novel director'sblocking) never read as story. No beat is left only for an answer with nothing to keep: empty or whitespace,{}or an object of empty values (a stored empty beat reads back as no beat now, not asCharacters: {"npcs":"",…}), a beat object cut before its first value. The truncation salvage of a beat object cut mid-field is unchanged and runs first. Rows stored before this as a prose degrade keep reading asnpcs(indistinguishable from a JSON director that filled onlynpcs); a re-save from the panel's source editor stores them freeform. Pinned byBeatFreeformTests,BeatDirectionStageFreeformTests,UnreadableAnswerSponsorTests,ConversationsBeatRawEndpointTestsand the sharedbeatFormat/BeatPaneltests. The design: a beat mode carries a format declaration — its field list, with a routing role per field (record: prose + extractors · prose-only). The parser keeps both tiers and takes its label vocabulary from the declaration instead of from constants; a mode with no declaration gets today's five fields, so every existing beat mode is unchanged. On the chat surface this is a creator's knob like any other. A game fixes it — the Visual Novel prototype pins one format and adds a third, code-consumed role whose content is not customizable at any level (seedocs-internal/visual-novel/VISUAL_NOVEL_PROTOTYPE.md).
The beat contract (2026-11-07)
Superseded in part (2026-11-23, planned: HYBRID_DIRECTOR_AUTHORITY.md S1). The director now writes every spoken line and the whole truth in layers ("The director is FACTS. the prose is PRESENTATION."). Once S1 ships, the structured contract asks for
lines,established,hiddenanddisclosurebeside the five fields below, and no longer forbids dialogue. The freeform contract ends with aLines:array and aNot yet revealed:line. The seed's copy of the prompt (90'sv_beat_prompt) stays as a fingerprint of shipped text, and migration 494 carries the new text. The engineering contract isdocs-internal/architecture/chat-engine/HYBRID_DIRECTOR_AUTHORITY.md. The text below is the 2026-11-07 design as shipped.
Owner decision 2026-11-07: "Like in the editor for the beat, you will be able to choose freeform, or our current json structure, or the phase one in the future", refined the same day: phase is not a contract ("agreed about the phase"). The contract is the shape of the director's answer. Phase tracking comes later as a separate per-mode toggle that adds a phase call beside the existing scene call, in either contract.
This is the first concrete piece of the format declaration above. A beat mode now declares which answer shape it wants, out of a list the engine owns, or that its own prompt sets the format. The rest of the declaration (a mode's own field list, with a routing role per field) is still the later step, and the parser still reads its five fields from constants.
What it is. prompt_modes.beat_contract (database/v1/04_tables_prompts.sql), a short text with a CHECK listing its values:
| Value | The director is asked for | Shown in the editor as |
|---|---|---|
structured |
The JSON contract: the five fields (npcs, environment, plot, situation, portrayal_hints) and their rules, word for word what the built-in prompt asked. |
Structured (JSON): five fields |
freeform |
The prose contract: plain prose with no field labels. It opens with where the story stands in its arc and what pressure is building (the world and the other characters move even when {{user}} avoids the turn), then the beat: what happens next and why. It never writes the scene itself, and it ends with a How to portray it: line and a Scene: line, the two spellings the parser reads out of prose. |
Freeform: prose direction |
| NULL | Nothing from the engine: the mode's own text carries its format. Every mode written before the column, and any mode whose creator keeps a format of their own (a custom labeled format included). | My prompt sets the format |
A further shape is one more value in the CHECK and one more contract text. It is a list on purpose, never a boolean.
Where the contract goes: directly after the mode's instruction. The engine owns both texts (Core/Services/Hybrid/BeatContracts.cs), and a creator picks one without writing it. The beat leg sends the mode with the chosen contract as one more keyless System section, placed right before the mode's first section that asks for context (BeatContracts.WithContract):
- Assembled shape: the role, then the contract, then the story context. On the seeded director that is where its JSON contract always sat (section 0), so the cacheable prefix stays stable, and the merge pass joins the two back into the same words.
- Flattened shape: the contract follows the mode's instruction, before the engine's portrayal-and-scene ask.
- A Document-editor mode is one row holding both its instruction and its tokens. That row asks for context, so the contract cannot sit inside it and goes before it.
The contract is a section of the mode the leg records (HybridBeatLegPrompt.Mode), so the prompt-leak guard protects it exactly as it protects the mode's own text, on the turn and on a summary regenerate or catch-up alike (SummaryScreenContextSource builds its plan from the same decorated mode). A mode's own text stays the creator's, whatever it says about format.
The built-in prompt is composed. HybridPipelinePrompts.BeatSystemPrompt is BeatContracts.DirectorRole, a blank line, then BeatContracts.StructuredContract, two constants: no runtime cut, the same words as before. The seed's verbatim copy is pinned to that composition by HybridSystemModeSeedTests.
The floor follows the contract. Three places fall back on a built-in instruction: no mode bound, a mode whose sections render nothing, and an assembled mode with no instruction text of its own. A mode with no contract chosen gets the whole built-in prompt there, as before. A mode with a contract gets the director's role and that contract: on the flattened floor as one instruction, on the assembled floor as the role followed by the contract section. A floor never sends a second contract. The contract section never counts as the creator's instruction.
Not chosen is byte-identical to before. NULL sends exactly the prompt it sent before the column. The editor offers "My prompt sets the format" on every Beat mode, so any mode can opt out of the engine's contract; a new Beat mode starts Structured. When a creator picks a format while the mode's prompt already carries a contract's opening words, the field warns that the director would get two. When they pick "My prompt sets the format" while the prompt carries neither, it warns that, unless the prompt describes a format of its own, the director has none to follow. Neither warning blocks. A form that didn't touch the field never sends it.
The seeded "Beat Director" is Structured. fn_seed_hybrid_system_modes step 1c (90_seed_hybrid_system_modes.sql) cuts the seed's own copy of the JSON contract out of the mode's instruction and sets the mode to structured, in the same call. The engine puts the contract back in the same place, so the sent prompt keeps exactly one JSON contract, in the same words, and a switch to Freeform sends only the freeform one. The step is wider than the 2026-10-27 text upgrade on purpose: "the contract part is pristine", not "the whole text is". The block is cut wherever either of the seed's two contract texts still stands verbatim, even in an instruction an admin edited elsewhere. Every other bound holds:
- the mode's keyless sections only, a section linked to this mode alone, a text row no other section shares;
- only while the mode has no contract chosen, so it runs once and never second-guesses an admin;
- an instruction whose contract was itself edited matches nothing: it stays NULL and keeps sending what it sent;
- a fingerprint without the marker yields no block, so the step cuts nothing rather than emptying a pristine instruction;
- an instruction that was nothing but the seed's contract is left empty, and the engine's floor supplies the role.
Accepted, not fixed (review, 2026-11-07): the step reads and rewrites the instruction in one statement without a row lock first, so an admin save of the same section committing in that same instant could be overwritten. The window is the statement's milliseconds, once, on the deploy that runs it.
Where it is chosen. The Forge mode editor, in the Pipeline subsection beside Pipeline Role (BeatContractField, shared). It is staged like every field and saved by the form's one Save. On a Classic or Prose mode it stays on the form, disabled, saying why. A new Beat mode is created Structured; a new mode of any other role is created with none.
Save, copy, import, MCP.
- The mode's read and update carry it, three-state: omitted keeps it,
""clears it ("My prompt sets the format"), a value sets it, anything else is 400invalid_beat_contract. - A copy keeps the source's value, NULL included: a copy of a mode whose text carries its format must not start receiving the engine's contract as well.
- Export writes it; import takes a known value and reads anything else as not chosen.
- MCP: the mode's entity descriptor carries
beat_contract, sopatch_entity/propose_entity_editcan set either value. It is set-only there; moving a mode back to its own format is the editor's "My prompt sets the format".
Lookups. The freeform contract ends with its two labeled lines, and the lookups ask (LookupsAsk) asks for a trailing Lookups: line. Either order is safe: the labeled tier reads Lookups: as a discard label, and the freeform tier reads the answer without its lookups (BeatCodeFields.Strip, with BeatLookups.Strip), so a lookup never reaches the story or the writer.
Games. The Visual Novel and RPG directors are beat modes of their own. The VN's "VN Director" seed has no contract chosen, so it sends exactly what it sent. A reader picks beat modes, never a contract, so no reader setting can switch a game's contract.
Pricing. The estimator prices the prompt the call sends: the plan's one BeatLlmRequest construction carries the leg's instruction, the contract section included. The part sizes the budget reads (WebPromptPartSizes) count the mode with its contract section, and keep the whole built-in prompt as an upper bound. The prose contract is shorter than the JSON one, so a measure built on the built-in prompt (the no-plan quote) stays an upper bound too.
Runtime stamp. A contract change is model-facing tuning, like the enhance settings. It moves runtime_updated_at (functions/94), not the public "Updated" date.
Acceptance Criteria — the beat contract
The feature is not done until every box below is verified ✅ against the running product.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- As a creator, I pick Freeform in the beat mode editor (Forge → the mode → Pipeline → Beat format), save, bind the mode as a story's Beat mode, and the next beat is prose: the Story beat panel shows the freeform beat, with its portrayal line and scene call as their own fields.
- As a creator, I keep a format of my own by picking "My prompt sets the format" on any Beat mode, and the director gets no engine contract.
- As a creator, when my prompt already describes a format and I pick one, I see a warning that the director would get two; I can still save.
- As a creator, when I pick "My prompt sets the format" and my prompt uses neither built-in format, I see a warning that the director may have no format; I can still save.
- As a creator, on a Classic or Prose mode, I see Beat format disabled with the reason; it is never hidden.
Behavior:
- A mode with no contract chosen sends a director prompt byte-identical to before the column, on the assembled shape, the flattened shape and each floor.
- A Structured mode's director prompt carries the JSON contract once, directly after the mode's instruction and before the story context; a Freeform mode's carries the prose contract once, there, and no JSON contract anywhere.
- The seeded "Beat Director" after migration sends the prompt it sent before: exactly one "Output STRICT JSON only", in the same position, in the same words.
- A flattened-shape (keyless) Freeform mode sends the prose contract after its instruction.
- On every floor (no mode, an empty mode, a keyed mode with no instruction), a mode with a contract chosen gets the director's role and one contract, never two.
- The leak guard protects the engine's contract as part of the beat mode's text.
- The estimator prices the sent prompt:
HybridLegPlan.BeatSentPromptequals whatBeatLlmServicesends, for each contract and each shape. - The dropdown follows the editor's staged Save and Cancel: picking a value dirties the form, Save sends only
beatContractwith the revision (""for "My prompt sets the format"), Cancel puts the stored value back.
Invariants that must stay true:
- The seeded "Beat Director" is Structured after migration, its instruction no longer carries the JSON contract, and it sends exactly one JSON contract.
- An admin-edited Beat Director whose contract block was left as the seed wrote it (either seed text) is Structured after migration with the rest of its edit kept; switched to Freeform, it gets only the freeform contract.
- A Beat Director whose contract block was edited stays not chosen, text untouched.
- Re-running the seed changes nothing, and never overrides a contract an admin chose.
- A copy of a mode with no contract chosen stays that way; a copy of a Freeform mode is Freeform.
-
HybridPipelineLlm.BeatModeIdstill points at the Beat Director; a new story's beat leg runs it Structured.
Edges:
- A write with any other value is 400
invalid_beat_contractnamingbeatContract, and nothing is saved. - An import file without the field, or with an unknown value, imports as not chosen.
- A host running ahead of the migration reads every mode as not chosen and fails no turn.
4. Seed system modes
Ship two system Modes (created_by_user_id = 0, the same convention as the default mode)—a default "Beat Director" and a default "Visceral Prose"—paired by roles in a default "Authentic over Comfort" Model Profile, so a creator can adopt the hybrid pipeline without authoring either half first.
As built (2026-07-12): the two seed system Modes exist — and they already drive the v1 prompts, via interim settings rather than a role-tagged Profile.
database/v1/90_seed_hybrid_system_modes.sqlseeds "Beat Director" and "Visceral Prose" (created_by_user_id = 0,is_public = FALSE— system-owned, not browsable), carrying the previously compile-time prompts in mode form (Beat: one keyless System sub-prompt withnsfw_enabled = TRUEper §3; Prose: a keyless craft sub-prompt + apersona-keyed sub-prompt, and deliberately no beat framing — placement is stage-owned, see §1's as-built note). Two settings bind them:HybridPipelineLlm.BeatModeId/.ProseModeId— an explicit interim bridge until the role-tagged Profile resolution in Model routing; the seed is insert-if-missing and only re-points a dangling id, so an admin override (including a deliberate blank) is never clobbered on re-migration.BeatDirectionStageresolves the bound modes per turn: the beat mode's keyless sections (joined in SortOrder) replace the hardcoded beat instruction; the prose mode is assembled through the normal provider machinery — its provider-key set IS the starve — with the beat still riding the last user turn. Unset or unresolvable settings fall back to the retained hardcodedHybridPipelinePromptsconstants; a mode-config problem never fails a turn (log + fallback). Still open (2026-08-04: the "Authentic over Comfort" Profile IS now seeded and consumed — see the Model routing update; the settings bindings survive as the fallback tier beneath it), two beat-side limits remain Phase 2 — a beat mode's provider-keyed sections are skipped (no beat-side provider resolution; the beat leg still sees the flattened classic context) and there is no beat-mode-assembled history injection.
As built (2026-09-20): both beat-side limits above are CLOSED — and the switch between the old and new shapes is the beat mode's own key set, not a setting. Declaring a provider key is how a creator says "this is what the director sees", so
BeatDirectionStagenow picks per turn:
- The beat mode declares ≥1 provider key → the leg is ASSEMBLED. Its sections resolve through the normal provider machinery (
IPromptBuilder.BuildPromptAsync(context, beatMode, …)— the engine adds the package cast but not the journal fallback or the reply-length directives; see the 2026-09-24 note below) — its key set IS the beat's context, exactly symmetric with the prose leg since 2026-07-12 — followed by the beat leg's own history and the current user turn. The flattened classic transcript is no longer sent: withholding is now expressible on the beat side, which is what made §2 only half-real before.- The beat mode declares no key (or none is bound) → the leg stays FLATTENED, byte-for-byte the pre-change behavior: keyless sections joined in SortOrder as the instruction, the whole assembled context as one user turn.
This is the shape the seeded "Beat Director" still runs … The seed was deliberately not re-authored to declare keys — flipping it is a content decision, not a code one.Superseded 2026-09-24 — the content decision was made (owner): the seeded "Beat Director" now declares its keys, so the default Hybrid conversation runs the ASSEMBLED leg. See the as-built note below. The flattened shape remains exactly as described for any beat mode that declares no key.Amended 2026-10-22 — a Document-editor beat mode's tokens are its keys. "Declares a key" now means asks for context, read row by row by one rule (
Core/Services/Hybrid/BeatLegShape.cs, shared byHybridLegPlanner, the budget mirrorWebPromptPartSizesand package readiness):
- A legacy row (
expansion_version = 0) asks for context when it carries a provider key — unchanged.- A document row (
expansion_version = 1) asks for context when its template carries a token the inline expander resolves — an insertion such as{{knowledge}}/{{ summary }}/{{identity}}, or a closed conditional such as{{#journal}}…{{/journal}}(InlinePromptExpander.HasContentToken). Such a mode is ASSEMBLED: the expander resolves its tokens, exactly as on a Classic prompt. Before this, a document had no provider key, ran flattened, and its tokens reached the director as raw markup.- A document row's provider key asks for nothing. The renderer expands a v1 row's template and never runs its key (
SystemPromptBuilder.RowPlacesKey, the same rule); a document switched to the Advanced editor keeps its rows at v1 with whatever keys they carry.- Everything else stays FLATTENED, byte for byte as above: legacy keyless modes, a document whose template carries no content token (plain text, the reserved
{{char}}/{{user}}, unknown or malformed tokens — all of which the expander leaves as written), and a v1 keyed row without a token.On the assembled shape, a document's instruction is its text with every token resolved empty: a document of tokens alone carries no output contract, so it gets the built-in
HybridPipelinePrompts.BeatSystemPromptfloor like a mode that declares only keys. (Since 2026-11-07 the floor follows the mode's beat contract: the whole built-in prompt when none is chosen, the director's role followed by the mode's contract section when one is.)Be precise about who this changes. "Existing conversations are unaffected" is true only of beat modes with no keys. A beat mode that mixes keyed and keyless sections previously ran flattened-with-keyed-sections-skipped and now takes the assembled path — a complete reshape of that leg's prompt. That is the intended fix (it is what the skipped-sections Warning was reporting), but it is a live behavior change for any conversation already bound to such a mode, and
pipeline_roleis picker metadata the runtime never gates on, so any mode can be bound as Beat through amodel_profile_entriesrole=1 row or theHybridPipelineLlm.BeatModeIdsetting. Before assuming the blast radius is zero, check which bound beat modes carry keyed sections in production — a local query cannot answer that.The beat's own history (the two-histories rule, previously architecture-only): on the assembled shape the beat conversation replays prior beats — each assistant turn rendered from that message's
beat_jsonviaHybridBeatState.ToExtractionText(), so the four structural fields and neverportrayal_hints(craft direction belongs to the prose model alone). An assistant turn with no beat — a Classic turn of a conversation that later switched to Hybrid, or a beat that parsed to nothing — is dropped, not downgraded to its prose: letting prose in would contaminate the clinical register the separate history exists to protect. Dropping a turn's prose never drops the turns around it — the user turns on either side stand, andRequestPrompt.NormalizeForProvider()closes the adjacency each drop opens by folding them together. This is what keeps the first Hybrid turn after a Classic run sane: every assistant turn in that window is beat-less and drops, and what the director still sees is the user's side of the conversation plus whatever the mode's own keys (summary,journal) carry — not an empty history.MessageHistoryItemgainedBeatJsonto carry the track (null on user turns, on Classic turns, and on Discord).The clinical-register guarantee is about HISTORY, and only about history. The beat leg's own history is beat-only, full stop — that is what this change makes true. But a declared key brings whatever its provider emits, and the register split is not finished on the provider side. Three known routes by which prose-register text still reaches an assembled beat leg, all pre-existing Phase 2 remainders rather than regressions from this change — but all newly reachable, because a beat mode's keyed sections used to be skipped outright and now resolve:
recalled_memoryinjects proseContentoutright (WebMemoryContentProvider) — remainder (a) in §The beat track is the story-of-record. Embedding-coupled: retrieval matches the vector built fromContent, so switching it means re-embedding on the clinical register.summaryis only conditionally beat-aware.WebSummaryContentProviderinjectsWebSummary.BeatTrackContent, which isBeatSummary ?? Content— andBeatSummaryis written aswindowHasBeats ? result.Content : null. So a window with no beats (the Classic-era turns of a conversation that later switched to Hybrid) has a NULLbeat_summaryand falls back to the prose summary. Those are precisely the turns the beat history now drops for being prose; a declaredsummarykey can re-admit a summary of them.- Rollups can make
beat_summaryitself prose-derived, because the rollup's LLM input reads the children's proseContentand never theirbeat_summary(remainder (b),WebSummarizationService.SummarizeSummariesAsync) — so even a non-nullBeatTrackContentis not a guarantee of register.A creator authoring the §2 split should know this; closing it is the Phase 2 register work, not prompt assembly. The test
ProcessAsync_AssembledBeatLeg_DeclaredSummaryKeyCanStillCarryProseRegisterTextpins the boundary so it stays visible instead of being rediscovered.Degrades, never fails, like every other mode-config path in the stage: a failed assembly or a failed beat-track read falls back to the flattened shape, and a mode that declares keys but carries no instruction text gets the built-in
HybridPipelinePrompts.BeatSystemPromptprepended as a floor — the beat's JSON output contract is in the instruction, so losing it would degrade every beat on that mode to an unparseable one. (Since 2026-11-07 the floor follows the mode's beat contract: with a contract chosen it is the director's role, followed by the mode's contract section.)One consequence worth naming: the Warning that fired once per beat mode per process ("declares provider-keyed sections … so they are skipped") is gone, because the thing it warned about no longer happens. Acceptance criteria and how they were verified: below.
Acceptance Criteria — beat-side provider resolution + beat history
Verified 2026-09-20. API/pipeline = driven end-to-end against running services with the deterministic mock LLM (.claude/scripts/dev-verify-hybrid-beat-assembly.ps1, 28 checks, asserted on the mock's verbatim request captures — the beat call identified by its mode marker, so a claim about "the beat prompt" is about that call and not the prose or eval call). Unit = BeatDirectionStageTests (401 WebChat + 4372 Core tests green).
User use cases — satisfiable + accessible:
- As a creator, I can decide what the director sees by declaring provider keys on my Beat mode, and those keys reach the beat model. (Reachable today from the existing Mode editor's Provider Key field and the How drawer's Beat leg picker — the path a creator already uses to pin a Beat mode; API/pipeline: a
character-keyed section resolved into the beat call.) - As a creator, a Beat mode I never gave keys to keeps working exactly as before. (API/pipeline turn 3: keys-free mode still drives the beat call, still receives the full context and the prose history.)
Behavior:
- A beat mode declaring ≥1 provider key is assembled through the provider machinery; the resolved content appears in the beat call and the flattened whole-context blob does not. (API/pipeline + unit.)
- The assembled beat prompt is a real multi-turn array ending on the current user turn (Author's Note and the latest tracker block included). (API/pipeline turn 1.)
- The assembled beat leg replays prior beats as assistant turns and never the prose those turns rendered. (API/pipeline turn 2: prior beat present, prose marker absent.)
- The prose leg is unchanged — it still replays prose history and does not inherit the beat's clinical history. (API/pipeline turn 2, asserted on the prose call specifically.)
- A beat mode declaring no provider key sends exactly system + one flattened user blob. (API/pipeline turn 3: message count is 2.)
Invariants that must stay true:
- The seeded "Beat Director" path is untouched — no keys declared, so the flattened shape and the full context it always had. The default Hybrid conversation sends what it sent yesterday.
-
portrayal_hintsnever enters the journal, tracker or summary inputs (craft direction, not story-of-record —HybridBeatState.ToExtractionText). (Unit:BeatParserTests,HybridExtractionTests, byte for byte.) Narrowed 2026-10-27 (MD-12): this line used to say the hints never enter the beat's own history. They now do — the director's own history replays each prior beat with the hints it wrote (ToDirectorHistoryText), because a director shown its past beats without them stopped writing them from turn 2. (Unit:BeatDirectionStageTeststurn 3 shows turn 1 and 2's hints, the sent prompt equals the priced one, and a past beat renders the same on the next turn.) - The beat leg's HISTORY is beat-only. (Scoped honestly: a declared
recalled_memorykey still injects prose-register memory text — pre-existing Phase 2 remainder (a), named in the as-built note above, not a regression from this change.) - A mode-config or beat-track failure degrades, never fails the turn — assembly failure and history-read failure both fall back to the flattened shape. (Unit: history-read failure still completes the turn on the assembled context.)
- A mode that declares keys but no instruction text still gets the built-in beat prompt, so the beat's output contract survives. (Unit.)
- No two adjacent non-System turns share a role in the assembled beat prompt, including after a no-beat assistant turn is dropped. (API/pipeline + unit.)
Edges:
- An assistant turn with no
beat_json(a Classic turn before the switch to Hybrid) is dropped from beat history rather than contributing its prose — and the user turns around it survive, verified explicitly rather than inferred from the absence of prose. (Unit; both assertions fail against an unbounded tail-trim, checked by reverting the fix. Also API/pipeline: a turn whose beat comes back empty is stored beat-less, the next turn's beat call excludes its prose, and both the user turn in front of it and the older completed beat behind it survive.) - The first Hybrid turn after a Classic run keeps the user's side of that history instead of opening on an empty one. (Unit.)
- A full regeneration sends the edited user turn exactly once, with no stale twin, and the beat being regenerated is not treated as history. (Unit; fails against the pre-fix implementation, checked by reverting.)
- Prose-only regeneration is unaffected — it never reaches the beat call at all. (Pre-existing tests still green.)
- Discord is unaffected: its history provider leaves
BeatJsonnull, and no Discord path builds an assembled beat leg. (Sibling scan + build.) - A Document-editor beat mode whose template carries a content token (
{{knowledge}},{{ summary }},{{#journal}}…{{/journal}}) is assembled, and the director's prompt carries no raw{{markup. (2026-10-22 amendment above. Unit + turn-fit tests written; not yet run or driven live.) - A document beat mode with no content token, and a v1 row keyed but without a token, stay flattened; legacy keyed and keyless beat modes are unchanged. (Unit tests written; not yet run.)
- The budget's beat leg and package readiness take the same shape the planner does (
BeatLegShape). (Unit + Database tests written; not yet run.)
Not done here, deliberately: re-authoring the seeded "Beat Director" to declare the §2 split (a content decision — see the as-built note above) (done 2026-09-24 — next section), and the §5 editor gaps, which are unchanged by this work and gate nothing (see the correction in §5 — the beat key is already reachable from the editor; what is missing is guidance, not access).
The seeded director reads its own context (2026-09-24)
Owner decision 2026-09-24: yes — re-author the seed. The seeded "Beat Director" now declares its story-context keys after its instruction — character, scenario, persona, facts, cast, lorebook, summary, journal, recalled_memory, tracker (every key the conversation's own default prompt carries: the §2 split withholds story state from the prose side, not from the director). So every default Hybrid conversation runs the assembled beat leg: its own context, and its own history of beats instead of a flattened copy of the prose conversation. That is also what makes a correction in the Story-beat panel reach the director's next turn — the flattened shape never replayed beats at all.
Flipping the default made three assembled-leg gaps (found in docs-internal/reviews/HYBRID_PIPELINE_REVIEW_2026-09-24.md, items 8 / 17 / 36) the default behaviour, so they were closed first:
- What the engine adds is per leg, not one flag.
includeJournalFallbackwas doing three jobs; it is nowPromptAssemblyOptions { JournalFallback, CastFallback, ResponseShapingDirectives }(Core/Pipeline/Interfaces/PromptAssemblyOptions.cs). The assembled beat leg gets the package cast (who is in the scene — before, it silently lost it because cast shared the journal flag), not the journal fallback (§4's decision stands: a beat mode that wants the journal declares it), and not the pacing / target-length directives — those describe the reply the reader sees, and on the beat leg "aim for roughly N words" landed right after the director's own ~120-word output contract. The prose leg is unchanged: starved, directives kept. - The director's history is complete. The greeting — authored, so it never has a beat, and it used to be dropped like a Classic prose turn — now opens the beat history as a user-role opening-scene block (
HybridPipelinePrompts.FormatOpeningScene), never as an assistant turn, so the register rule holds. It is only recognised when the history read reached the start of the conversation (fewer rows than asked for); a full window that opens on beat-less prose is still dropped. The tracker trajectory rides along: the registeredIHistoryMessageInjectors run over the beat window, so each prior beat is followed by the state it left behind; the newest snapshot (already on the current turn, placed there by the context stage) is left out by position, never by comparing text — a story that returns to an earlier state (A → B → A) keeps the first A — and a dropped turn takes its snapshot with it. - The leg is fitted to the BEAT model's window. The context stage sizes the conversation's prompt for the prose model (
HybridWebChatContext.LlmCallSettings); the beat leg is a different prompt to a possibly much smaller model. It is now sized against the provider / model / output cap the beat call itself resolves (BeatLlmService.CallSettingsView— one resolution rule, not a copy), bounded the way the classic stage bounds its prompt: the always-on block to its share viaStaticPromptTrimmer, then the oldest history units dropped until it fits. The block is trimmed section by section even though the mode merges its sections (StaticPromptTrimmer.TrimSectionstrims the unmerged list and re-merges): trimming the merged blob could only cut its end, which is where the security block sits. The classic context stage had the same flaw and got the same fix. The current turn is never dropped, and the surviving history never opens on a beat whose user turn was cut away. Best-effort like every degrade in the stage — no resolver, no fit; the send-time guard stays behind it.
Migration. The seed is create-if-missing, so the new sections are added by a separate step in fn_seed_hybrid_system_modes that runs for fresh and existing databases alike — and only over a pristine mode: exactly the one keyless section the original seed wrote, its text still verbatim. A mode someone shaped (edited the text, added or removed a section) is left exactly as it is; the description is rewritten only over the seed's own words. After the step runs once the mode is no longer pristine, so it never runs twice.
One visible side effect: the seed declares lorebook, and the lorebook provider records the turn's activations (and the matched entry images shown on the reply) from the last assembly that searched — on a default Hybrid turn, now the director's. That is "what the model saw" for the leg that plans the scene, and it appears even when the conversation's own mode declares no lorebook, because that mode drives neither call on a Hybrid turn. The classic block was still assembled at Order 100 and searched too, so a default Hybrid turn ran each searching provider twice. Closed the same day — see The conversation's own block is assembled only when a leg reads it.
What this does not change: the flattened shape for any beat mode that declares no key; the register remainders (recalled_memory still injects prose Content, and summary falls back to the prose summary for beat-less windows — the story-of-record note); tracker values already written for a turn whose beat is later corrected (they are not re-derived).
Acceptance Criteria — seeded director on the assembled leg
Verified 2026-09-24. Live = .claude/scripts/dev-verify-hybrid-seeded-director.ps1 against running ServerAPI + the deterministic mock, with no conversation pin (the default path), asserted on the mock's verbatim captures — 22 checks, all passing (re-run after the adversarial-review fixes). Unit = BeatDirectionStageTests (51), SystemPromptBuilderTests, ContextBuildingStageBaseTests; DB = HybridSystemModeSeedTests against real Postgres.
User use cases — satisfiable + accessible:
- As a writer on a default Hybrid chat, the director plans from the story's own context — character sheet, world, journal, trackers — and from its own earlier beats, not from the prose. (Live: character text resolved into the beat call; turn 2/3 replay prior beats as assistant turns, never prose. Reachable by starting any Hybrid chat — no setting, no pin.)
- As a writer, when I correct a beat, the director's next turn reads the correction. (Structural: the assembled history replays each turn's stored
beat_json, which the beat-raw PATCH rewrites; covered by the existing assembled-history tests. The flattened default never replayed beats at all.)
Behavior:
- The seeded "Beat Director" declares the ten keys above after its instruction, each a known catalog key. (DB.)
- The default beat leg is assembled, not the flattened
[Context]transcript. (Live.) - The greeting opens the director's history as a user-role opening scene. (Live + unit.)
- Each prior beat is followed by its tracker snapshot; the latest snapshot appears exactly once. (Live, 3 turns + unit.)
- The assembled beat leg is fitted to the beat model's window, sized with the beat model and the beat's output cap, dropping the oldest history first. (Unit: sized against
small-beat-model/ 300 tokens, result fits the input budget.) - The assembled beat leg carries the package cast without declaring it, and no journal fallback. (Unit.)
- A story that returns to an earlier state keeps the whole trajectory — the older identical snapshot stays after the beat that produced it. (Unit, A → B → A.)
Invariants that must stay true:
- The director is not told the reply's target length; the prose leg still is. (Live, both asserted on the same turn.) (📋 Amended by the planned length section: the director will be told the reader's target as part of its length policy, and the prose leg will be told through the director's note.)
- The prose leg's starve is unchanged — no cast or journal fallback reaches it. (Unit.)
- A window trim gives up ranked sections (lorebook, memories…) and never the security block, on a merged mode — on the beat leg and on the Classic prompt. (Unit, both.)
- A beat mode someone edited is never touched by re-migration — text, description and section set stay as they left them; a removed section is not put back. (DB.)
- Re-running the migration duplicates nothing. (DB + live DB re-run: 11 sections before and after.)
- A beat-less mid-conversation prose turn is still dropped from the beat history — the greeting exception applies only when the read reached the conversation's start. (Unit.)
- A keys-free beat mode keeps the flattened shape. (Existing unit tests +
dev-verify-hybrid-beat-assembly.ps1.) - Each leg obeys its own mode's
nsfw_enabled. (Live capture: the beat call carries the beat mode's prepend;SystemPromptBuilder.PrependNsfwIfEnabledreads the mode it is assembling.)
Edges:
- A full history window that opens on beat-less prose is not mistaken for the greeting. (Unit.)
- A leg that already fits is sent whole. (Unit.)
- No window resolver wired / resolution fails → the leg goes out unfitted, the turn never fails over sizing. (Code path; the pre-existing tests all run without a resolver.)
The conversation's own block is assembled only when a leg reads it (2026-09-24)
The problem. A Hybrid turn sends the conversation mode's own block — its sections, the "classic block" — to no model, except inside a flattened beat. It was still assembled on every Hybrid turn, running every provider the mode declares (the lorebook and recalled_memory searches, the summary, journal, facts and cast reads). With the seeded director on the assembled leg, the default turn ran each of them twice: once for nothing, once for the director. The beat leg also read the history and ran the history injectors a second time.
The shape now — the first slice of the leg assembler the 2026-09-24 review names S2 (docs-internal/reviews/HYBRID_PIPELINE_REVIEW_2026-09-24.md, structural table):
PromptLegAssembler(Core) splits what the context stage did into the turn — the history window with the regeneration fix-up, the blocks the history injectors hang on it, the current-turn blocks, read once — and legs built from it: an always-on block, the turns after it with one mode's enhance cadence, fitted to one window. The Classic context stage is the one-leg case, byte for byte as before.HybridContextBuildingStage(hybrid_context, Order 100) replaces Classic'scontextstage and the formerhybrid_leg_planstage on Hybrid turns. It reads the turn once and builds the leg plan from it: the beat leg (the assembled one projected from that turn — no second history read, no second injector run, no stale regeneration copy to trim — or, for a flattened beat, the conversation's own leg as Classic builds it — fitted, since 2026-09-29, to the beat call's window rather than the chat call's), then the prose system part, then the prose leg's turns ontocontext.Prompt. The conversation's block is assembled only for a flattened beat, or as the fallback when a beat mode can't be assembled.- The prose leg's history is fitted against what the prose call sends: the prose system part and the director's note's framing (all of the note on a prose-only regeneration), in the prose model's window. It used to be fitted against the conversation's block, which the prose call never receives. The beat's output cap is not reserved (8192 by default, and it covers a reasoning model's hidden thinking, which never reaches the note); instead the beat stage fits the composed prose prompt again once the note exists, dropping the oldest turns, never the system part or the message the reply answers.
- Every leg is built inside the first pre-stage. The turn's embedding usage can only be read there: a pre-stage that starts after the pipeline has yielded a status token records its embeddings into nothing (pinned by
PreStageEmbeddingAccountingTests). So the former Order-400 plan stage lost the usage of any embedding it made first; building the legs in the context stage closes that. BeatDirectionStageno longer builds a plan of its own: a turn that reaches it without one is a wiring fault and fails loudly.
What a user can see change:
- Activation record and entry images come only from a leg that searched. On a default turn that is still the director's. A custom beat mode that declares no
lorebook, with a prose mode that declares none either, now records no activations and shows no entry images: no model saw any lore on that turn. A prose-only regeneration likewise records only what its prose leg searched — none, with the seeded prose mode — where it used to show the unsent block's search. - The prose leg never carries the conversation mode's non-System sections. A User- or Assistant-role section of the conversation's own mode used to ride into the prose call as if it were a turn (review item 18); the prose leg's turns are now only the story. The same leak into the director's current turn on a first turn is gone too.
- The writer sees more history when the conversation's block was larger than the prose system part (the usual case), so
EffectiveHistoryCapacity— the prose leg's — is larger, and with Dynamic Context on, summarization triggers later. The beat model's window does not feed that capacity (it never did). (📋 Decided 2026-09-24, planned: the director's window does pull summarization forward when its own fit drops history. On web a summary never removes a message from either leg's verbatim window, so summarizing earlier costs the writer nothing, and a turn the director dropped that no summary covers is invisible to the model that plans the story. The director also closes scenes: a scene break it marks triggers the scene's summary. See Scene-Aligned Summaries.) The director no longer receives the conversation mode's enhance prompt. It used to reach the director's current turn when its role wasn't System — and an Assistant-role one at the end left the director's prompt ending on a prefill written for the prose model. It is the reply writer's reinforcement; the prose leg keeps it (per-leg cadence is review item 37).Reversed 2026-10-05 (owner): the director receives it again — on the assembled leg every copy User-role, so its prompt still never ends on a prefill. See §3.- The director's current turn is built from the turn, not cut out of another prompt. Three edges moved with that: a user turn with no reply after it reaches the director once (it used to come twice, from the beat track and from the prompt), with the latest state after it; when the prose window was so tight that no history survived, the director used to lose its history and the latest state too, and now keeps both (it is fitted to its own window); a User-role enhance interlaced at the regenerated turn no longer reaches it (still true after 2026-10-05: the regenerated turn is the current turn, not history, so no interval copy lands in front of it).
- When the note costs the prose leg turns,
EffectiveHistoryCapacitydrops to about what the leg kept — counted in messages, so it can be a message off either way (a merged message holds two history items; a state block left standing alone is none). Rare: only a note larger than the room the context stage left. - A history read failure fails the turn, as it always did on Classic — there is no longer a second, separately-degrading beat-track read.
Unchanged: Classic turns (the same code path, byte for byte); the flattened beat's input (it is the conversation's leg as Classic builds it — pinned byte for byte against the Classic stage; since 2026-10-05 that holds when the beat mode carries no enhance and the conversation's is not assistant-role, see §3); the order in which the legs search, so a prose mode that declares lorebook still owns the record; the conversation mode's enhance cadence on the prose leg's turns (per-leg cadence is review item 37; since 2026-10-05 the same cadence reaches the director too, and each leg mode's own cadence rides its own leg — §3).
Acceptance Criteria — the block is assembled only when a leg reads it
Verified 2026-09-24. Live = both scripts against a probe ServerAPI built from this change (port 5110, its own log confirming it served every turn through hybrid_context and none through context) and a private mock — 23 + 28 checks, all passing, re-run after the adversarial-review fix; each live Hybrid turn ran exactly two prompt assemblies (director, prose), the flattened one exactly two (conversation, prose). Unit = HybridContextBuildingStageTests (16), BeatDirectionStageTests (54, now driven through both stages in production order), PreStageEmbeddingAccountingTests; Core.Tests 4506, WebChat.Tests 447, DiscordChat.Tests 980, all green. Not run: the Database.Tests prompt-capture filter (ManagedPromptCaptureTests, Discord Classic) — it timed out in fixture setup behind other sessions' concurrent DB runs; Classic is covered by the suites above.
User use cases — satisfiable + accessible:
- As a writer on a default Hybrid chat, every turn still gets the director's beat and the prose reply, with the director planning from its own context and history. (Live:
dev-verify-hybrid-seeded-director.ps1.) - As a writer on a Hybrid chat with a key-free beat mode, the director still reads the whole conversation. (Live:
dev-verify-hybrid-beat-assembly.ps1.)
Behavior:
- With an assembled beat and a bound prose mode, a provider only the conversation's mode declares never runs, and one the director also declares runs once. (Unit.)
- The same with the built-in prose template, and on a prose-only regeneration. (Unit.)
- The history is read once and the history injectors run once per Hybrid turn. (Unit.)
- The prose leg's history is fitted against the prose system part and the note; the prose prompt as sent fits the prose window. (Unit, with a heavy prose system and with a note larger than the room left.)
- Every leg's embedding usage is on the turn's
EmbeddingUsage. (Unit.) - On a live default turn, the conversation's block is not assembled. (Live: the probe's log shows no conversation-mode assembly on the Hybrid turns.)
Invariants that must stay true:
- Classic turns are byte-identical. (Core.Tests + WebChat.Tests + DiscordChat.Tests unchanged and green.)
- The flattened beat gets exactly the whole context Classic builds. (Unit, compared byte for byte with the Classic stage.) (📋 Amended by the planned length section: minus the pacing and target directives.) (Amended 2026-09-29 by Each leg is held to the context-fit settings: the same context, fitted to the beat call's window rather than the chat call's.) (Amended 2026-10-05: byte for byte when the beat mode carries no enhance and the conversation's enhance is not assistant-role; every enhance copy in the transcript is the reader's text, and a key-free beat mode's own enhance rides it — §3.)
- The prose leg still carries the reply's target length and the conversation mode's non-System enhance prompt; the director gets neither, and its prompt never ends on an Assistant-role enhance. (Unit + live.) (📋 Amended by the same section: the target length moves into the director's note.) (Amended 2026-10-05, owner: the director does get the conversation mode's enhance prompt — on the assembled leg every copy User-role, so its prompt still never ends on an Assistant-role enhance —
HybridContextBuildingStageTests,EnhancePromptPlacementCaptureTests; see §3. Unit + live, 2026-10-05: on the default Beat Director, User- and Assistant-role enhances reach the director as user text before the Author’s Note, interval copies between earlier beats, a regeneration sends the same final turn, a mode without an enhance prompt sends exactly what it did before. Pricing of the beat leg is unit-tested only.) - Each leg mode's own enhance prompt rides its own call on its own interval and at-end settings — the beat mode's only the director's, always as user text; the prose mode's only the writer's, in its own role — ahead of the conversation mode's where they meet, one copy for a mode bound twice; with the seeded leg modes (no enhance) both calls are unchanged. (Added 2026-10-05; unit —
HybridContextBuildingStageTests,EnhancePromptPlacementCaptureTests; live 2026-10-05: an assembled beat mode and a prose mode each with an enhance, a keyless director with its own enhance, an Assistant-role conversation enhance on a keyless director, a regeneration and a mode bound twice — each placed as described.) - A prose mode that declares
lorebookstill owns the activation record. (Unit.) - The beat's output cap is not reserved out of the prose leg's history. (Unit.)
Edges:
- A beat mode that can't be assembled falls back to the flattened context, and the turn completes. (Unit.)
- A regeneration sends the edited user turn to the director exactly once; one whose window holds no user turn still ends on the current message. (Unit.)
- A beat stage that runs without a plan fails loudly. (Unit.)
Each leg is held to the context-fit settings, on the call that sends it (2026-09-29)
The check. A Hybrid turn makes up to two prompt assemblies, so every setting that bounds a Classic prompt has to bound each of them. Driven live against the mock LLM (dev-verify-hybrid-settings.ps1), the same conversation settings were applied to a Classic chat and to three Hybrid shapes: the default (seeded director, assembled; seeded prose, no lorebook), a prose mode that declares lorebook, and a key-free beat mode (flattened). Every call was compared with Classic.
The retrieval settings already held. Knowledge.MaxEntries (3, and 0 = always-include only), Features.EnableLorebook = false and Knowledge.LimitMode = tokens with a Knowledge.TokenBudget each gave every lorebook-carrying call exactly Classic's entries: the searches read context.Settings, and they run once per leg that declares the key. Always-include stayed exempt from every bound. Memory.* follows the same path (RetrievalBudgets.ForMemory).
Two context-fit settings did not:
Context.StaticPromptSharenever reached the prose call. Classic, the assembled beat and the flattened beat all bound their always-on block to its share (StaticPromptTrimmer); the prose system part a bound prose mode assembles was sent whole. A prose mode that declareslorebook(orjournal) therefore carried its lore past whatever share the reader set, and the prose history paid for it. Live at a 2000-token Dynamic Context cap and share 0.2: Classic trimmed its lore to 2 of 6 entries, the prose call sent all 6. NowHybridLegPlanner.PlanAsyncruns the prose system part — a bound mode's block, or the built-in template when none is bound (its persona card was the one unbounded part) — throughPromptLegAssembler.FitStaticBlockAsync, sized on the prose call (context.LlmCallSettings). The lore gives up the room; the writer's instruction does not.- The flattened beat was sized for the prose call. Review item 8's open half: the conversation's leg that a key-free beat mode rides was fitted to
context.LlmCallSettings— the prose model's window and the chatGeneration.MaxTokens— then sent to the beat model underHybridPipelineLlm.DefaultMaxBeatTokens(8192 by default), with its instruction uncounted. Live, before the fix, ~23.7k tokens of always-include lore fitted the prose share untouched and overflowed the beat call; the send-time guard cut the reader's beat cap8192 → 6638(on a smaller beat model: a truncated beat, orContextTooLong). Now that leg carries the beat call's settings (BeatLlmService.CallSettingsView) through the static trim (StaticBlockFit) and the history fit (PromptLeg.CallSettings). The instruction it rides under is always sent and can't be trimmed, so it comes off the always-on share first and out of the history's room after.
Which block the retrieval budgets are derived from. Fitting a block also derives next turn's retrieval budgets from its composition (IPipelineContext.DerivedRetrievalBudgets; only Discord's governor reads it today). A Hybrid turn now fits up to two blocks, so one has to own that: the conversation's own block, when a flattened beat sends it. The starved prose system part never does — read as a composition it says "no lore wanted" — and an assembled-beat turn leaves it unset, as before.
What a user can see change: a prose mode that declares heavy context and a tight share or Dynamic Context cap keeps more of the story and less of the lore in the prose call; a key-free beat mode on a beat model smaller than the writer (or with a larger beat cap than the chat's) keeps its full beat cap instead of being clamped, at the cost of the oldest context the director could not have taken anyway.
Noted, not changed: a director's instruction bigger than its whole share has nowhere to go. At the extreme (Dynamic Context 2000 × share 0.2 = a 400-token share) the seeded, assembled director's own ~600-token instruction is shortened by the trimmer's last-resort pass — the designed "degraded, never refused" behavior, and it can cut the beat's output contract. A flattened beat's instruction is never shortened (it isn't part of the block): its block is trimmed to nothing and the send-time guard decides. Either way, any share that leaves the instruction room is unaffected — the same guarantee Classic's block gets.
Amended 2026-10-22 (CTX-NO-TRIM (c), owner 2026-10-07: "FAIL LOUD at the model's maximum, never at the 80% static share"). No leg bounds its block to the share any more, and the last-resort pass is gone. Every leg — Classic, the flattened beat, the assembled beat and the prose call — fits its WHOLE request in one pass (
LegWindowFit): nothing is cut while it fits; past it the oldest history goes first (down to the share's reserve), then the block's ranked sections (searched lore down to its always-include head, facts, memories, journal, cast, summaries), then the rest of the history. The prose system part is no longer fitted inPlanAsync, before its history exists: the Hybrid context stage fits it together with the prose history (PromptLeg.CallerSystem) and writes the result back toHybridLegPlan.ProseSystembefore allocation prices it. A director's instruction, a prose template's persona card or craft instructions, and any identity section are never shortened: a leg they alone overflow is refused by the capacity check with the typedContextTooLong(legnames the call). The "noted, not changed" case above is therefore a refusal now, not a shortened instruction. The share still sizes the retrieval budgets the flattened beat's block derives.
Acceptance Criteria — each leg is held to the context-fit settings
Verified 2026-09-29. Live = dev-verify-hybrid-settings.ps1 (local tooling) against a probe ServerAPI built in Release from a clean detached worktree of HEAD plus only this change (port 5120; its own log shows it served all 16 Hybrid and 5 Classic turns, 0 guard clamps) and the mock LLM: 5 settings scenarios, each on Classic, default, prose-lore and flat-beat, plus the beat-window turn, all passing. Re-run after the review on the final code (the share and beat-window scenarios, 4 Hybrid + 1 Classic turns on a fresh probe): all passing, the trim warnings naming the prose and beat calls, and the flattened block's share net of its instruction (375 = 400 − 25 tokens). The same script against the pre-fix build failed exactly the two gaps above (the prose call kept 6 of 6 entries at share 0.2; the flattened beat went out at ~23.7k tokens and the guard clamped MaxBeatTokens 8192 → 6638). Unit = five new HybridContextBuildingStageTests (8 cases) — the bound prose mode (also on a prose-only regeneration), the built-in prose template, the flattened beat's history + instruction reserve (a key-free mode's instruction and the built-in one), the flattened beat's always-on block beside a large instruction, and the retrieval-budget derivation rule. Six mutants — prose-sized flattened block, instruction not taken off the share, instruction not reserved from the history, built-in instruction unreserved, template unfitted, prose block deriving — each fail their own test, with a green baseline before and after. WebChat.Tests 506, DiscordChat.Tests 1034, Core.Tests Pipeline/ContextWindow/Hybrid/Subscriptions 940, all green in a clean worktree of HEAD plus this change (the shared tree's Core.Tests was red on another session's in-progress edit).
User use cases — satisfiable + accessible:
- As a reader who caps lorebook entries (Settings → Knowledge), a Hybrid chat's director — and a prose mode that reads the lorebook — carries no more entries than a Classic chat would. (Live:
MaxEntries = 3→ 3 + always-include on every lore-carrying call.) - As a reader who switches the lorebook off for a chat, no Hybrid call carries lore. (Live.)
Behavior:
-
Knowledge.MaxEntries,Knowledge.LimitMode/TokenBudgetandFeatures.EnableLorebookbound every lorebook-carrying Hybrid call exactly as Classic. (Live, all three shapes.) -
A prose system part — a bound mode's or the built-in template's — stays insideSuperseded 2026-10-22 (CTX-NO-TRIM (c)):Context.StaticPromptShareof the prose call's input budget; a mode's lorebook is shortened and its instruction kept; the template's persona card gives up its tail, never the craft instructions. (Unit ×2 + live: ~392 of 400 tokens.) - A prose system part is sent whole while the whole prose request fits the prose call's input budget, whatever share it takes; past it the prose history yields first (down to the share's reserve), then the mode's searched lore (never its always-include head), and its instruction and the template's persona card are never cut — a prose request they alone overflow is refused with
ContextTooLong,leg: prose. (Unit:HybridContextBuildingStageTests— the two prose-share tests inverted; live: the scenario script step 5.) -
A flattened beat — under a key-free mode's instruction or the built-in one — fits the beat call's input budget (beat model window,Superseded 2026-10-22 (CTX-NO-TRIM (c)): the block is no longer trimmed to a share.MaxBeatTokens), instruction included, whenever the share leaves the instruction room; its block is trimmed to the share minus the instruction, not to the prose call's share. (Unit: a small director beside a large writer, both instruction sources, and a ~1430-token instruction beside ~4000 tokens of lore. Live: ~19.7k tokens sent against the beat call's 24,576-token input budget (32,768-token window − 8,192 beat cap), no guard clamp.) - A flattened beat — under a key-free mode's instruction or the built-in one — is fitted as one whole request on the beat call (beat model window,
MaxBeatTokens), instruction counted: nothing is cut while it fits; past it the oldest history and then the conversation's searched lore give way (never the instruction, the identity or the always-include lore). A beat request they alone overflow is refused withContextTooLong,leg: beat, before the director is called. (Unit:AFlattenedBeat_TheConversationsSearchedLore_GivesWayToFitTheBeatCall,AFlattenedBeat_IsFittedToTheBeatModelsWindow_WithItsInstructionLeftRoom; live: not yet driven.) - Next turn's retrieval budgets are derived from the conversation's own block only — never from the starved prose system part. (Unit.)
Invariants that must stay true:
- Always-include entries stay exempt from the entry and token bounds on every leg. (Live,
MaxEntries = 0and the token budget.) - The seeded prose mode stays starved of lore. (Live.)
- Classic and Discord turns are unchanged. (Classic calls in the live run carry the same counts before and after; WebChat.Tests, DiscordChat.Tests, Core.Tests green.)
Edges:
- No window resolver wired → neither leg is fitted and the turn completes. (Unit: every
HybridContextBuildingStageTests/BeatDirectionStageTestscase built without a resolver, e.g.FlattenedBeat_GetsExactlyTheWholeContextClassicBuilds_AssembledOnce.) - A prose-only regeneration (no director call) gets the same prose fit. (Unit.)
The director decides each reply's length and marks scene breaks (📋 planned, 2026-09-24)
The problem — length. Classic shapes reply length with two per-conversation settings, Response Pacing (Off / Concise / Adaptive / Expansive) and Target Length (a word count), injected as fixed system directives (PromptContextManager.AppendPacingInstruction / AppendTargetWordsInstruction, keys pacing / target_words). Adaptive's text asks the writer to "let the beat decide" — but in Hybrid the writer is deliberately starved of the story, so it is the one model that can't judge the beat, while the director reads everything and literally decides it. Three leftovers make the current Hybrid shape worse than Classic's:
- The flattened beat still receives "Aim for roughly N words in this reply" inside the conversation's block (
HybridLegPlanner.ConversationLeg.FlattenedAsyncbuilds it with the default options) — right after the director's own ~120-word output contract. Review item 17's remainder; the assembled leg already dropped it (above). - The built-in prose template (no prose mode bound) gets no length guidance at all:
BuildTemplateProseSystemcarries only the template. - The directives are static per conversation, so the one model that knows this beat is a sharp exchange or a moment that should breathe has no way to say so.
The problem — scene breaks. Summaries cut every Summarization.SummaryWindowSize messages, so a summary routinely covers half a scene. The director is the natural source of scene boundaries: it reads every turn with the full story context, and it causes the transitions. The summary side of that — when a scene's summary is written and where it ends — is its own feature: Scene-Aligned Summaries. This section is the director's half: asking for the boundary and storing it.
The shape
Two optional beat fields. The beat keeps its five fields and gains two, both optional — every stored beat and every beat mode that never emits them stays a complete beat:
| Field | Values | Class | Reaches |
|---|---|---|---|
length |
brief · standard · full (read back from short / medium / long too) |
Rendering direction, like portrayal_hints |
The director's note; the director's own history. Never the extractors (journal, tracker, summary). |
scene |
continue, or new — <short name> |
Story structure | The extractors (ToExtractionText, only when new and only when the beat has story content — a beat that is nothing but a scene line must still fall back to the prose in HybridExtraction), the director's own history, the summary trigger. |
A category, not a number: models are bad at counting words, and a category survives an edit in the Story-beat panel.
The grammar is strict, so creator text is never claimed by accident. A length value is exactly one of the six words (any case, trailing punctuation ignored). A scene value is continue (or same), or new followed by optional punctuation (—, -, :) and a name; a bare new is a break with no name. The product prints one form everywhere — Scene: new — <name> — in the ask, the extraction text and the director's history, so the director echoes what it reads. Anything that doesn't match is not the field:
- In a JSON beat, a non-matching value is ignored.
- In a labeled-text beat, a
Length:/Scene:line (or a## Sceneheading) claims its field only when its body matches; otherwise it stays what it is today, a continuation of the previous section. A creator whose beat mode uses "Scene:" as a description heading keeps that text where it landed before. CanonicalFieldmaps the two new labels explicitly — its default case sends any unmapped label toportrayal_hints.- The two new labels never count toward the labeled tier's two-label acceptance bar (
BeatParser.TryParseLabeledText): otherwise a rambling reply with onePlot:line and a scene line would newly parse as a clean beat instead of falling back to the raw text. BeatParser.HasBeatFieldsdoes not learn the new keys: if it did, a stray{"scene": "new"}inside a labeled beat would win the JSON-in-prose tier and swallow the whole beat.
How the director is asked: an engine addendum, never the instruction text. The seeded "Beat Director" carries its own verbatim copy of the instruction (90_seed_hybrid_system_modes.sql, v_beat_prompt, which the pristine-mode check also compares against), and a creator's beat mode carries its own — editing HybridPipelinePrompts.BeatSystemPrompt reaches neither. So every beat leg carries one beat addendum, whose text lives in HybridPipelinePrompts and asks for the fields "in the same format as the rest of your answer" (a JSON director that tacked a Length: line after its object would fail the strict parse and lose the line). Where it goes differs by shape, and both placements are load-bearing:
- Assembled leg — inside the assembly, not after it. A new
PromptAssemblyOptionsmember carries the addendum text, andPromptContextManagerappends it as a System message keyedbeat_askafter the pacing slot and before the security block — before the placeholder pass and the mode's merge. Appending it to the leg afterwards fails two ways: the window fit rebuilds the section block from the unmerged copy (PromptBuildResult.PreMergeMessages→StaticPromptTrimmer.TrimSections), so on any trimmed turn of a merging mode — the seeded director merges, and trims happen on small beat models — the addendum silently vanishes; and it would land after the security block, which the engine keeps last. An uncataloged key is never dropped by the trimmer's ranked ladder; its last-resort pass can still shorten any surviving section, this one included, which only happens when the block can't fit at all. The addendum depends on the conversation's settings, so the leg builds its options per turn (AssembledBeatLeg with { … }) rather than using the static instance. Every existingPromptAssemblyOptionsconstruction uses named arguments, so adding a member breaks no caller. The mode editor's preview assembles as the conversation-primary prompt and shows no addendum. - Flattened leg — its own field on the request.
HybridBeatLegPromptandBeatLlmRequestgain an addendum field, whichBeatLlmService.SentPromptappends to the instruction in the flattened branch. It can't ridePromptOverride: a null override means "the built-in prompt" at three exits ofBuildBeatLegAsync, and folding the addendum into the joined sections before their emptiness check would send a mode whose sections render empty only the addendum — no output contract, every beat degraded. There are exactly two production constructions ofBeatLlmRequest, with the same inputs (BeatDirectionStageandHybridLegPlan, which the compute estimator prices through); they become one factory onHybridLegPlan, so the sent prompt and the priced prompt can't drift. - The scene ask is always there — the summary cut works on every Hybrid conversation.
As built (2026-10-27): the channel shipped first, carrying a portrayal ask — length and scene are still planned. Found live: the beat's Portrayal was filled on the first reply and "Not set" on every later one, so the writer lost its "How to portray it" from turn 2. The stored instruction marked
portrayal_hints"Optional" and said "Omit fields that have nothing new this beat", and from turn 2 the director's own history shows its beats without hints (ToExtractionText, by design), so it copied that. The engine ask isHybridPipelinePrompts.BeatAsk: writeportrayal_hintson every beat, in the answer's own format, exempt from the omit rule, for a writer who never saw the previous note. It travels exactly as specified above:PromptAssemblyOptions.BeatAsk→ a System message keyedbeat_askafter pacing and before security on the assembled leg (HybridLegPlanner.AssembledBeatLeg);HybridBeatLegPrompt.Addendum→BeatLlmRequest.Addendum, appended after the instruction byBeatLlmService.SentPrompton the flattened leg (HybridPipelinePrompts.WithAddendum, which the flattened fit also reserves room for).HybridLegPlan.BeatRequestis the one construction the beat stage sends and the estimator prices. The ask is constant for now, so the leg still uses the static options; the per-turnwith { … }arrives with the length ask. Cost: 219 characters, 63 tokens by the platform estimator (260 / 75 before MD-12 dropped its "your past beats are shown without them" clause) (3.5 characters a token), per beat call; nothing on the prose call. The built-in instruction and the seed'sv_beat_promptwere reworded together (portrayal required, the omit rule scoped to the four structural fields); the seed rewrites only its own unedited old text (step 1a, a fingerprint check), never an admin's copy — those directors get the ask from the engine.BeatParseralso reads aportrayalkey and an object or list value for the hints (flattened to text).As built (2026-10-27, MD-12): the director's own history carries its portrayal hints. The ask alone left the director reading its past beats without the hints it had written, so its own history still taught it the omission. The assembled beat leg now replays each prior beat through
HybridBeatState.ToDirectorHistoryText— the four structural lines exactly asToExtractionTextrenders them, thenHow to portray it: …last (the writer's-note label, whichBeatParserreads back) — inHybridLegPlanner.ProjectBeatHistory, the one place it is used. Every other reader of a stored beat (journal, tracker eval, summary,HybridExtraction) keepsToExtractionText, unchanged byte for byte. Which turns survive is still decided by the structural fields: a beat with only hints is dropped, as before. The rendering is a pure function of the storedbeat_json(the hints were screened byBeatLeakScreenbefore it was stored; the VN guard's prose-only direction is never stored), so a past beat reads the same on every later turn and the cache prefix holds; the beat leg's window fit prices the rendered units, so the reservation counts the hints (HybridLegPlan.BeatSentPrompt= what is sent). The flattened leg has no beat history and a prose-only regeneration makes no director call — neither changes. The ask's "(your past beats are shown without them)" clause, false from here on, was dropped./context-budgetstill sizes the director on the conversation's prose history rows (the documented one-sided bound), not on the rendered beats.As built (2026-10-27, memory plan M8a): the scene half — length is still planned.
HybridBeatState.Scene(HybridScene:Continue/New(name)) is read by one grammar,HybridScene.TryParse, which isfn_scene_mark_from_beat_json's exactly (R-M8-15): spaces-only trim, lower case,continue, ornewthen the end or whitespace and an em dash, colon or hyphen-minus. Stricter than the plan text above:sameis not a continue, an en dash and a non-breaking space are not separators.ToBeatJsonwrites"scene"only when the beat made a call, and only canonically (continue/new/new — <name>), so a beat without one stores byte for byte as before and the SQL only ever sees one spelling;web_messages.scene_markis derived from it in SQL on both write paths (no C# writes a Hybrid mark). The ask is the second sentence ofBeatAsk(always present): 414 characters, about 119 tokens at 3.5 characters a token, per beat call.ToExtractionTextends withScene: new — <name>only for a break on a beat with story;ToDirectorHistoryTextshows every call,Scene: continueincluded, between the story lines and the hints. A labeledScene:line claims the field only when its body is a call and never counts toward the two-label bar;HasBeatFieldsdidn't learn the key. Also fixed (R-M8-16): an answer whose only content is the hints and/or a scene call now parses as a beat with no story fields instead of degrading to its raw text innpcs(where the hints reached the journal, tracker and summary asCharacters: {…}). That covers a JSON answer, and a labeled one whose only labeled content is one hints section with or without aScene:call (text before the first label joins the hints); a story label still needs the two-label bar (Plot:+Scene:alone degrades). Of the rows stored by the old degrade, only those whosenpcsis a JSON object carrying a beat field heal on read; a stored labeled-text degrade reads as it did until it is edited. Pinned byBeatSceneTests(Core) andSceneMarkParityTests(Database, the parser against the SQL).
- The length ask is there only when the conversation sets Response Pacing to something other than Off, or a Target Length above 0. Its policy follows the pacing mode: Concise favours
brief, Expansive favoursfull, Adaptive lets the beat decide; with pacing Off and a target set,standardis the reader's target and the director moves off it only when the beat clearly calls for it. When a target is set, the policy names it ("the writer's replies centre on about 300 words") — so the director is now told the reader's target, as a fact about the prose, never as an instruction about its own output.
The length reaches the writer inside the director's note. Pacing and target do different jobs, and the note keeps both:
- Style stays the pacing mode's own text. Concise ("let dialogue and action carry the weight") and Expansive ("interiority, sensory detail") shape how the prose reads, not just how long it is, and all three end with "Always finish on a complete thought." When pacing is set, the note carries the mode's admin-editable
Pacing.*text, exactly as Classic's system prompt does. - The number becomes per-beat. The director's category replaces the fixed target directive with one line that comes after the pacing text and says it governs this reply:
Length for this reply: about N words — brief. Finish on a complete thought.Nis ½·T forbrief, T forstandard, 1¾·T forfull(rounded to 10, never below 30; v1 constants inHybridPipelinePrompts, tuned from live use).fullcan exceed the Target Length slider's own maximum — 1050 words at a 600 target — on purpose: it is one beat that asked for room, andGeneration.MaxTokensstill guards the ceiling. With no target, the category and a one-line gloss, no number. - The pacing text keeps its lean; the line wins for this reply. Concise says "err toward the shorter", and under Concise the director may still call
fullfor a beat that needs it. That is not two competing signals — the mode sets the lean, the line sets this reply — and the line's wording says so. What there never is: two numbers, or none when pacing or a target is set. - When the beat carries no usable length — a beat mode that ignores the ask, a degraded parse, an older beat reused on a regeneration — the note carries the conversation's own target directive (
Pacing.InstructionTargetWords) instead of the line. - It all goes in the note body (a prose mode's
beatsub-prompt wraps it like the rest), rendered by one settings-awareHybridProseLeg.DirectionNotethat the stage and the estimator both call. - Placeholders are substituted in the note itself. The note is appended after the assembly's placeholder pass, and
DirectionNote's default-framing branch (the built-in template's path) substitutes nothing today. ThePacing.*texts are documented to support{{char}}/{{user}}, and the target directive{{words}}, so the renderer substitutes them in the pacing text and the fallback directive before framing, on both framing branches. - Only the category is stored. The number is derived at compose time from the current settings, so a prose-only regeneration after the reader moved the target renders against the new target.
One carrier, always the note. The prose system part stops carrying the pacing / target directives on Hybrid (HybridLegPlanner.ProseLeg → ResponseShapingDirectives: false), and the flattened beat's conversation block is assembled without them too (closes item 17). Keeping them in the prose system part and stripping them at compose time would mean carrying its unmerged copy on the plan and re-merging after the beat exists (the part is built at Order 100, and the seeded prose mode merges, which drops the keys from the merged copy) — possible, but the note is simpler and it also reaches the built-in template path, which has no system directives at all.
The director sees its own rhythm. On the assembled leg (the flattened one has no beat history), each prior beat is replayed with its length while the ask is active (a history renderer next to ToExtractionText, which stays length-free for the extractors), so "three brief beats in a row" is visible when it decides the fourth.
Pricing. HybridProseLeg.EstimateKnownNoteTokens goes through the same settings-aware renderer (it gains a settings parameter; every call site has the settings in hand). On a prose-only regeneration it is exact — the one path where an under-count would be an under-bill, since that path reserves no beat-output cap. For a new beat, the known part is the framing, the pacing text, and the larger of the longest length line and the target directive (about 100 tokens at the default text, several times the line), so the reservation stays an upper bound either way.
Parser and panel — the two places this breaks silently if half-done.
- The parser rules above, pinned in
BeatRoundTripTests— including a creator's## Scenedescription heading that must stay in its field. - The Story-beat panel (
BeatPanel.tsx) serializes the whole beat on any per-field edit (serializeBeatwrites only the five fields today), and the server then rewrites both the stored beat and its raw text. A panel that doesn't model the two fields would erase the director's length and scene call — and its verbatim output — whenever someone fixes a typo in Plot. It gains a Length select (none / brief / standard / full) and a Scene toggle ("Opens a new scene") with a name input — sharedSelect,Toggle,Input. - Where a writer learns that the director picks the length: the pacing popover (
PacingButton.tsx) adds one line under its subtitle on a Hybrid chat.ChatPanelhas only the conversation id today, sopipelineTypeis threaded fromNewChatPageintoChatPanel, which renders bothPacingButtonandComposerEchoesBar. The HOW drawer's Context Settings is the other place pacing is set; it renders the settings' own descriptions, so the Response Pacing and Target Length descriptions inSettingsDefaultsgain the same sentence.
Pacing Off and no target — the defaults. No length ask, no length line, no fallback, and no lengths in the director's history — even if a beat carries a length (a beat produced while pacing was on and regenerated after it was turned off, or a creator's mode that emits one unasked). The prose prompt is byte-identical to today's; the platform adds nothing. A creator who wants length control on every reply writes it into their beat mode's portrayal hints.
Non-Goals
- Story pacing — how much plot a beat advances. That is already the director's job (plot / situation); no new setting.
- Admin-editable director policy text. v1 constants, like the rest of
HybridPipelinePrompts. The fallback directives stay the admin-editablePacing.*rows. - A hard length cap.
Generation.MaxTokensstays a runaway guard, never a length control — same rule as Classic. - Classic and Discord. No change to either; the directives stay in their system prompts.
- The context budget bar (
ConversationBrowseRepository, pacing line item) stays Classic-shaped. On a Hybrid turn where the director answers with a length, it over-reports by about the size of the target directive (the note carries a one-line length instead) — a display inaccuracy on an estimate, not a pricing one. - The PDF export keeps rendering the five fields it renders today.
Acceptance Criteria — length and scene breaks
The feature is not done until every box below is verified ✅ against the running product.
Criteria above this section that this plan amends (they held when verified; building this changes them, and the build re-verifies them in their new wording):
- The seeded director reads its own context, "The director is not told the reply's target length; the prose leg still is" → the director is told the reader's target as part of its length policy (a fact about the prose, never an instruction about its own output), and the prose leg is told through the director's note, not its system part.
- The block is assembled only when a leg reads it, "the flattened beat gets exactly the whole context Classic builds" → exactly that context minus the pacing and target directives. Its byte-for-byte test (
FlattenedBeat_GetsExactlyTheWholeContextClassicBuilds_AssembledOnce) passes today only because its harness sets no pacing; it gains a variant with pacing set. - Same section, "the prose leg still carries the reply's target length" → carries it in the note.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- As a writer on a Hybrid chat with Adaptive pacing and a 300-word target, a quick exchange gets a short reply and a scene that should breathe gets a long one — set from the composer's pacing button, which tells me on a Hybrid chat that the director picks the length (and the HOW drawer's Context Settings says the same). Measured on real models, not the mock (which can't judge a beat): over a scripted 10-turn scene mixing fast exchanges and a set piece, at least 8 of 10 beats carry a
length, bothbriefandfulloccur, and at least 7 of 10 replies land within ±30% of their line's N. - As a writer, I can see the director's length call and scene call for a turn in the Story-beat panel, change them, and a prose-only regeneration renders at the length I chose.
- As a writer, I can mark or unmark a scene break on a turn from the Story-beat panel.
Behavior:
- With pacing or a target set, both beat shapes (assembled and flattened) carry the length ask; with neither set, neither does. Both always carry the scene ask.
- The seeded "Beat Director" answers the addendum without any change to its stored instruction. (Real beat model: at least 8 of 10 beats carry a parseable
scene; with pacing set, at least 8 of 10 a parseablelength. The mock proves only the plumbing.) - A JSON beat and a labeled-text beat both parse
lengthandscene;short/medium/longread back asbrief/standard/full;new,new — Name,new: Nameall read as a break. - With a target, the director's note carries the pacing mode's text (when set) and then
Length for this reply: about N words — <category>. Finish on a complete thought., N computed from the target at compose time; with pacing and no target, the category and gloss, no number. - Under Concise, a beat the director calls
fullgets the full-length line after Concise's text — the lean and the line both present, one number. - An admin-edited pacing text containing
{{char}}reaches the writer with the name substituted, on the built-in template path and with a prose mode'sbeatframing. - A beat with no usable length, with pacing or a target set, puts the conversation's own target directive in the note instead of the line.
- On a Hybrid turn the prose system part carries no pacing or target directive, with a prose mode bound and with the built-in template; the built-in template path now receives length guidance through the note.
- The flattened beat's context no longer contains the pacing or target directive (item 17 closed).
- On the assembled leg, the director's history shows each prior beat's scene break, and its length while the ask is active; the journal, tracker and summary inputs show the scene break and never the length.
- The prose call's reservation is at least what it sends — with the length line, and with the fallback directive — and is exact on a prose-only regeneration.
- The beat call's reservation covers the addendum (one request factory feeds both the call and the estimator).
Invariants that must stay true (carve-outs):
- Classic turns are byte-identical: same directive text, same place in the system prompt.
- With pacing Off and no target, the Hybrid prose prompt is byte-identical to before this change — even for a beat that carries a length; the director's prompt differs only by the scene ask and by the
Scene: new — <name>lines on replayed beats that marked one. -
Generation.MaxTokensis never changed by any of this. - A stored beat without the two fields renders, re-renders and extracts exactly as before.
- Editing any other field in the Story-beat panel keeps the stored length and scene.
- Neither the length nor the portrayal hints ever reach the journal, tracker or summary inputs.
- The security block is still the last System content of the assembled beat leg.
Edges:
- A merging beat mode whose leg is trimmed to fit a small beat model still carries the addendum exactly once, and security last.
- A flattened beat mode whose sections all render empty sends the built-in prompt plus the addendum — never the addendum alone.
- An unknown length value (
"huge") is ignored, and the fallback directive applies. - A
Length:orScene:line typed afterSituation:in the panel's source view lands in its own field, never insituation; a creator's## Scenedescription heading whose body isn't a scene call stays where it lands today. - A labeled-text beat containing a stray
{"scene": "new"}stays a labeled beat — the JSON-in-prose tier does not take it over. - A reply with one
Plot:line and oneScene:line is not accepted as a labeled beat (the new labels don't count toward the two-label bar); it falls back to the raw text as today. - A beat cut off by the output cap before
lengtharrived falls back cleanly. - A prose-only regeneration of a beat stored before this change uses the fallback directive.
- A prose-only regeneration after pacing was turned Off renders no length line.
5. Mode-editor support — the one place "reuse the editor for free" isn't free
The claim above — that a hybrid mode "reuses the workbench editor for free" — is true for building each half, but "free" hides three concrete editor gaps to close when this lands. Follow-up when picking the feature up: none of these comes automatically from the per-mode editor.
Correction (2026-09-20): the first bullet below was wrong, and it is NOT a gate on anything. It said a creator "literally cannot" add the handoff sub-prompt and that the feature is "unreachable from the editor". Both are false as shipped.
GET /api/creator/modes/provider-keysderives its list from Core'sPromptKeyCatalog— the same registry the engine resolves against, so it already includesbeat— andModeFormPagerenders it (ProviderKeysInfoInline). A creator can seebeatand use it today.What is actually true is narrower: the Provider Key field is a free-text
Input(placeholder "character, persona, etc.") with the catalog shown as a reference panel beside it rather than a picker bound to the field. So the key is discoverable but mistypeable, and a mistyped key drops the whole section with only a server-side Warning (PromptContextManager— a key the catalog has never heard of logs Warning; one the catalog knows but that has no provider logs Debug). Nothing tells the creator.This is authoring quality, not access, so it gates nothing — it is not a precondition for offering Hybrid to creators, and the items below are follow-ups to schedule on their own merit. It did get sharper on 2026-09-20: now that a beat mode's key set IS the beat's context, a typo there is the difference between the director seeing the character sheet and seeing nothing, where before every keyed section was skipped regardless and a typo cost nothing.
Surface the newSuperseded by the correction above — the key is surfaced. What remains is binding the field to that catalog (a picker with a free-text escape) instead of showing it alongside, and adding abeatprovider key in the editor's provider-key picker.beatrow to the public Modes provider-key catalog.- Pairing is new Model Profile surface, not the per-Mode editor. Authoring each half stays in the existing editor; binding Beat + Prose is the future role-tagged Model Profile UI. The per-Mode editor stays single-Mode; the Profile is where a creator assigns each role.
- The asymmetric split (#2) wants editor affordance, not just prose. Which provider keys live on which side is the design content, so the editor should guide it — a hybrid-aware template / inline hint / validation that a prose mode actually carries the
beatkey and a beat mode doesn't — so nobody ships a "hybrid" pair that silently drops the handoff. The seed modes (#4) are the worked example the editor points at.
So the editor work is: the per-Mode editor binds the Provider Key field to the catalog it already fetches and adds a hybrid-aware authoring path; the Model Profile editor adds role pairing; and docs/docs/features/modes.md gains a Hybrid section (the beat key in the catalogue + a "Building a hybrid Mode pair" example). None of it blocks anything — see the correction above.
6. Discovery & selection — the consumption layer
§5 settles authoring (per-Mode editor) and Model routing settles runtime pairing (role-tagged Profiles) — but neither answers how a reader finds a Beat or Prose mode and runs it. Modes are browsable entities; a published Prose mode listed as an ordinary mode is a trap (selected as THE mode of a Classic chat it's a starved renderer waiting for a direction that never arrives), and requiring a Model Profile to use a browsed mode puts the only path to use behind the power-user surface. The consumption layer closes that without a new entity:
prompt_modes.pipeline_role(0=Classic, 1=Beat, 2=Prose — same vocabulary asmodel_profile_entries.role): creator-set suitability metadata on the Mode itself. Browse facets, badges, and pickers filter on it; the engine never gates on it (a deliberately off-role binding still loads — same philosophy asModeSupportssoft warnings).- Role-prefiltered pickers: the Classic in-chat mode picker only ever offers Classic modes; a Hybrid conversation's How drawer offers two leg pickers (Beat / Prose), each browse-prefiltered to its role.
- Per-conversation leg pins (
web_conversations.beat_mode_id/prose_mode_id): an explicit in-chat pick is the strongest signal, so it is tier 0 of leg resolution — above the Profile role entries — and it works for package-less Hybrid conversations, which the (package-bound) Profile tier never reaches.NULL= auto. The full per-leg ladder as-built: conversation pin → pair-owner Profile role entry →HybridPipelineLlm.*ModeIdsettings → hardcoded constants; every step degrades, none fails a turn. - Pairing persistence stays with Profiles (§5 unchanged): a pin is a per-conversation choice, not a publishable pairing. Mixing a user pin on one leg with the Profile's other leg is the user's own composition, not a half-pair nobody authored — the pair-ownership rule governs the Profile tier only.
As built (2026-08-07):
pipeline_rolecolumn + CHECK + partial index (04_tables_prompts.sql), seed modes stamped Beat/Prose (90_seed_hybrid_system_modes.sql), pins + tier-0 resolution (71_hybrid_pipeline_columns.sql,functions/47d_hybrid_role_mode_functions.sql— incl.fn_set_conversation_hybrid_modeswith the same mode-usability/private-mode guards as the classic re-bind path), role facet onGET /api/browse/modes(?role=), role-clamped conversation modes browse (?role=beat|prose; Classic conversations are clamped to Classic),PUT /api/conversations/{id}/hybrid-modes, conversation GET carriespipelineType+ pin state, creator forms carry the Pipeline Role select, Hybrid How drawer shows the Beat/Prose leg cards (Auto/Pinned + reset-to-automatic). Not in scope here: the §5 editor gaps (beat key picker, hybrid-aware authoring guidance) and Profile role-pairing UI.
Acceptance criteria (consumption layer) — verified 2026-08-07 (API-probe = 19-check live E2E against running services; SQL = targeted Database.Tests; UI = driven in the browser preview):
- As a creator, I can tag a mode Classic/Beat/Prose in both mode editors, and the tag shows as a badge on browse cards. (2026-08-08: driven in the browser — ModeFormPage Basics step and the Forge ModeEditForm both render the Pipeline Role select reading the stored role; a beat-tagged mode's browse card shows the Beat badge.)
- As a reader in a Hybrid chat, I can pin a Beat and a Prose mode from role-prefiltered pickers in the How drawer, see which leg is Auto vs Pinned, and reset a leg to automatic — without knowing what a Model Profile is. (UI: Hybrid Modes section + Auto badge + role-pure Beat picker driven in the preview; pin/clear writes exercised via API-probe.)
- A Classic conversation's mode picker never offers a Beat/Prose-tagged mode. (API-probe: server clamps
?role=to Classic on Classic conversations; SQL test covers the filter surviving every picker filter branch.) - A pinned leg drives the corresponding call on the next Hybrid turn; clearing it returns the leg to the Profile/settings ladder. (Invariant: a dangling or soft-deleted pin degrades to auto, never fails the turn.) (2026-08-08: proven live against the mock LLM — a marker-tagged pinned Beat mode's prompt appeared verbatim in the actual beat call, the prose call received the direction, and after clearing the pin the next turn's beat call carried the settings-bound Beat Director prompt with the marker gone. Dangling-pin degradation covered by HybridLegPinResolutionTests.)
- Pinning is rejected on Classic conversations, on conversations the caller doesn't own (uniform not-found), and for modes the caller can't use (private-mode guards intact). (API-probe negatives + HybridModePinWriteTests; the private-mode × character guard fired live during probing.)
Package start — the missing front door
Status update (2026-09-20) — the pipeline pin is RETIRED.
packages.mode_lockedstopped gating anything in79bd3fa7+767b1daa: the SQL clamp infn_create_conversation_from_package, the leg-pin refusal, the managed-bot override, the PATCH mode-swap refusal, the How-drawer padlocks and the gear-menu skip are all gone, and every start path now readsChat.PipelinePreference(clientConsole/src/services/pipelinePreference.ts) — every package reader picks the pipeline, or starts on their saved preference. The "as built" notes below, Whatmode_lockedmeans now, The lock has to hold on every entry point and the lock acceptance lines describe the 2026-08-11 state — history; the column survives only as a retired shell. The creator-side Pipeline choice radio on the package About form was removed 2026-09-29.
✅ Built 2026-08-11 — UX pass still owed. §6 settled how a reader finds and pins Beat/Prose modes inside a conversation. This settles how a package reader gets a pipeline at the start, which was the one entry point Hybrid could not be reached from.
As built (2026-08-11). Readiness is
fn_package_is_hybrid_ready, riding the extractedfn_resolve_hybrid_pair_ownerthatfn_resolve_hybrid_role_modesnow also calls — so readiness and the runtime cannot drift (47d_hybrid_role_mode_functions.sql). The lock clamp lives in SQL, infn_create_conversation_from_package(47_package_functions.sql), which is the only function in the database that can setweb_conversations.package_id— so both the package Start and the gear-menu re-pick pass through it and no C# caller can walk around it.PackageDetailResponsecarriespipelineLocked+hybridReady. The modal moved tocomponents/common/HybridChoiceModal.tsx(second consumer) and is mounted inPackageDetailContent, whichPackagePageandPackageDetailModalshare. Creator control is aRadioGroupon the package About form, staged into the draft and committed by the builder's single Save.services/pipelinePreference.tsextracts the preference write both entry points need.Verified in the browser 2026-08-11 against running services (ServerAPI :5000, clientConsole :5173, local Postgres), driving the real package pages as
claude-tester, with the fixture package's readiness and lock flipped in the database between runs and restored afterwards. What was exercised: a hybrid-ready package preselecting Hybrid with the tuned copy; an untuned one preselecting Classic, saying so, and still offering Hybrid as selectable; a pinned package renderingPipeline · Set by the creatorbefore Start, skipping the pipeline dialog, posting noisHybrid, and landingpipeline_type = 1because the server derived it from readiness; and an explicitisHybrid: falseagainst that pinned package returning 201 withpipeline_type = 1and logging the clamp — not a 400. Backend also has 31 targetedDatabase.Tests(ordering pinned both ways) and the frontend 60 jsdom tests.
The problem
A package's Start button (PackagePage.handleStartExperience) posts packageId, greetingId,
personaTemplateId and source — and nothing about the pipeline. So a package conversation is always
created Classic. The only way a package reader reaches Hybrid today is to start a Classic conversation
and then use the gear-menu re-pick, which the Selection as-built note
calls the sanctioned entry point "while the pipeline is experimental." That is a workaround standing in
for a front door, and it means the reader has to already be in the wrong conversation to find the right one.
Hybrid degrades onto a Classic-built package — that is what makes offering the choice safe
This is the load-bearing fact, and it comes from the routing contract, not from optimism: each hybrid
leg's concrete model is matched against the effective Profile's same-role entries, and a leg with no
matching entry keeps the settings-bound seed-mode behavior (Model routing;
Model Profiles — Hybrid-Ready). A package whose Model Profiles
carry only classic_primary entries therefore runs perfectly well under Hybrid — it simply gets the
platform's seed Beat/Prose modes instead of the creator's own.
So hybrid-readiness is a quality-of-fit signal, never a compatibility gate. The modal must not hide or disable Hybrid for a package that isn't tuned for it; it tells the reader what they will get. Hiding it would be the access-first ethic violated in the usual direction — a capability made unreachable because someone else didn't opt in.
The design: two independent reads
The start modal reads two things that must not be conflated:
| Read | Source | Governs |
|---|---|---|
| Hybrid-ready? | Does any one of the package's bound Model Profiles carry both a beat and a prose role entry (model_profile_entries.role)? See Readiness is a matched pair. |
The copy and the preselected card. "This package is tuned for Hybrid" vs "Hybrid works here, but this package hasn't tuned its beat/prose halves — you'll get the platform defaults." |
packages.mode_locked |
Retired 2026-09-20 (enforced by nothing; see its column comment) | — |
Every package start offers the Classic / Hybrid cards, same HybridChoiceModal shape as the re-pick, with
the readiness note — Hybrid is never hidden or disabled. The Forge sandbox offers the same pick in its header
(2026-10-04).
A locked package says so, before the reader presses Start (dev decision, 2026-08-06). Not silent:
a reader who has seen the pipeline choice on other packages should learn why it is absent here, and
learn it while deciding whether to start — not by noticing an option that never appeared. The note goes
in the package detail body (PackageDetailBody, shared by PackagePage and PackageDetailModal, so
one addition covers both surfaces), alongside the other "what this experience is" facts rather than
attached to the Start button as a warning. It is a statement of the experience's shape, not an error.
Copy follows /brand-voice: what the creator chose, not what the reader is denied.
Readiness is a matched pair, within one Profile
(Dev decision, 2026-08-06. Refined 2026-08-11 — see the pair-owner note below.) A package counts as
hybrid-ready when the Profile that will actually own the pair at runtime carries both a beat entry
and a prose entry. Any-role-entry is not enough, and the pair must live in the same Profile.
Both halves of that rule come from the runtime rather than from tidiness:
Why a pair, not any entry. A Profile with a Beat entry and no Prose entry only supplies one leg; the other falls back to the settings-bound seed mode. That is a half-tuned experience, and calling it "tuned for Hybrid" would be the readiness copy telling the reader something the runtime does not deliver. Now that readiness also drives the preselected card, the cost of getting this wrong went up: any-entry would preselect Hybrid into an experience the creator only half-built.
Why within one Profile. Pairing is owned by the Profile (§6) — a Beat from one Profile and a Prose from another is "a half-pair nobody authored", which is precisely the composition the pair-ownership rule exists to refuse. Counting roles across the package's whole Profile set would manufacture pairings no creator ever made.
Why the pair owner, not any Profile (refinement, 2026-08-11).
fn_resolve_hybrid_role_modespicks its pair owner as the first package-bound Profile, in binding order, carrying any live role-tagged entry — with no fall-through to a later one. So a package binding a Beat-only Profile ahead of a fully paired one would, under an "any bound Profile pairs the roles" reading, advertise itself as tuned while the runtime hands Prose to the seed mode. Readiness has to ask the same question the runtime asks, or the copy promises what the pipeline will not deliver — which is the exact failure the pair rule was written to prevent, reintroduced one layer up. Readiness resolves the pair owner first, then checks that owner for both roles. A consequence worth knowing: readiness is therefore order-sensitive, and reordering a package's Model Profile bindings can change it.
Consequence worth stating, because it changes an open question elsewhere: a creator who tags a Beat entry and stops now gets nothing — no readiness copy, no Hybrid preselect — and no feedback saying why. That makes the Workbench pair-nudge in Model Profiles — Hybrid-Ready materially more valuable than when it was first raised as a nicety; it is the only surface that would tell them their half-pair is inert.
The pipeline default is driven by the Model Profiles, not by a flag (dev decision, 2026-08-06).
The same role entries that produce the readiness copy also decide which card is preselected: a package
whose profiles carry beat/prose entries opens with Hybrid preselected, because tuning those halves
is the creator saying what this experience is for. A package without them preselects Classic. The
reader can still choose either — this sets the default, never the availability, and the
never-hide invariant below is unaffected. This is why the lock does not need to default on: creator
intent is already expressed by what they built, and a lock is only for the creator who wants to remove
the choice outright.
What mode_locked means now
Superseded 2026-09-20:
mode_lockedis retired and now means nothing at runtime — see the status update at the top of Package start. This section is kept as the record of the 2026-08-11 design.
The lock's original meaning — "the reader cannot swap the Mode" — is dead. Model Profiles replaced
Modes as the composition surface, no seeded preset carries a mode step, and the package's mode_id is
a legacy compatibility fallback (Packages). The column is still enforced server-side and
still settable through the API, so it is not dead code; it is a live lock with no current meaning.
It governs more than the pipeline — know this before you flip it.
mode_lockedalready gates the reader's entry and leg controls:ModelProfileSectionandHybridLegModeSectiondisable them on a locked package, and the server refuses a mode change on a locked package conversation. So pinning the pipeline also removes the reader's §6 Beat/Prose leg pinning. That is coherent — a creator who paired Beat and Prose modes deliberately is not obviously served by letting a reader swap one half out — and it is deliberately left as-is rather than loosened, because narrowing a creator's existing lock is a product change, not an implementation detail. But the honest description of the lock is "the reader runs my composition", of which the pipeline pick is the newly-meaningful part, not the whole. Anything that later wants pipeline-pinning without leg-pinning needs a second flag and a dev decision, not a reinterpretation of this one.
Its newly-meaningful part under Hybrid is the pipeline pick. A creator who wired a three-act mystery around paired Beat/Prose modes is making a composition statement, and "the reader doesn't get to re-pick the pipeline" is exactly the guarantee they want — the same argument the locking rationale makes about components, applied to the one composition choice that still exists. That also relocates the creator-side control: it is a package-level setting on the About form, next to genre and content rating — not a per-component toggle on a builder step card, because there is no mode card to host it and the thing it governs is not a component.
Word it as what it does. "Readers can choose the pipeline" / "Pinned to my setup" — not "Mode locked".
The lock has to hold on every entry point, not just the new one
confirmRepickPipeline → createRepickedConversation re-creates a package conversation with isHybrid
and never consults the package. Since the gear menu is currently the only way into Hybrid for a
package, a lock that the start modal honors and the re-pick ignores is one menu click from meaningless.
Both paths gate on the same read, or the lock is decorative.
Same for the remembered preference: Chat.PipelinePreference (ask | classic | hybrid) is a user
setting, and a locked package must beat it. A reader who once ticked "remember: Hybrid" must not thereby
override a creator's pin — the preference decides what happens when the reader has a choice, and a
locked package is precisely the case where they don't.
Non-Goals
"Remember my choice" on the package start modal.(Superseded 2026-09-20: the preference is read on every start path, so the package modal now carries the checkbox; Settings → Features is the way back — UC-W7. The rest of this bullet is the pre-2026-09-20 reasoning, kept for history: its "write-only" premise no longer holds.) Deliberately absent, and it stays absent until something readsChat.PipelinePreference— which nothing does today (Selection as-built note: the setting is write-only, so item 9's "skip the modal when notask" is not in effect). A checkbox promising "skip this next time" that then shows the modal again is a control that lies; the gear-menu re-pick already carries that pre-existing wart and there was no reason to propagate it to a new surface. The write itself is extracted and ready (services/pipelinePreference.ts, shared with the re-pick), so wiring the checkbox is a one-line change the day a reader exists. (Done 2026-09-20,79bd3fa7: the preference is read by every start path except the gear-menu re-pick, and the package modal shows the checkbox —HybridChoiceModalshowRememberdefaults to true and all three callers persist it.)- A per-leg Beat/Prose picker at package start. Choosing the pipeline is the start-time decision; choosing the legs is §6's in-chat pinning, which already ships and already works on package conversations. Two pickers in a start modal is a wizard nobody asked for.
- Making readiness a gate. Covered above — it is copy, not permission. Explicitly out so a later slice doesn't "tidy" it into a disable.
- A new lock column. This spends
mode_locked, which already exists, is already enforced, and is currently meaningless. Addingpipeline_lockedalongside it would leave two locks and one meaning. - The full package restart contract — reset/result preview, Style-and-rules roster. Still Document Mode Editor territory, as the item-10 note says.
- Retiring the legacy
mode_idbinding. Orthogonal, and it has its own migration story.
Open Questions
- Does a locked package show the reader anything?
Silent or explicit?Decided 2026-08-06: it says so, as a note in the package detail body — see the design above. - Should
mode_lockeddefault to locked for new packages? Decided 2026-08-06: definitely not. It keeps defaultingFALSE. Creator intent about the pipeline is expressed by the Model Profiles they built, not by a lock flag flipped on for everyone — so the profiles drive the default pick (above) and the lock stays an explicit opt-in for a creator who wants to remove the choice entirely. Defaulting it on would have pinned every future package on behalf of creators who never made that decision. - Does readiness mean any role entry, or a matched pair? Decided 2026-08-06: matched pair only — see Readiness is a matched pair above. Answered once for both sides; the authoring-side nudge in Model Profiles — Hybrid-Ready uses the same rule.
- Do we want the same modal on the character start path (
/chat?characterId=…), which also has no picker? Out of scope here, but the two gaps are the same shape and the item-9 note says that flow is being redesigned when persona templates land.
Acceptance Criteria
Not done until every box is verified ✅ against the running product.
Verification state (2026-08-11). Ticked boxes were driven in a browser against running services. Still unticked, and honestly so: the creator's About-form toggle and the gear-menu re-pick lock were exercised in jsdom but not in a browser; the cross-Profile and binding-order readiness rules are proven by
Database.Testsagainst real Postgres but have no UI path to drive; and the remaining edges (deleted/private Profiles after publish, lock flipped mid-session, Discord) are unexercised. None of the unticked lines is known-broken — they are unverified, which is a different claim.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- As a reader, I can start a package experience on Hybrid from the package page, without first starting a Classic conversation and using the gear menu.
- As a reader looking at a package that hasn't tuned its beat/prose halves, I can still choose Hybrid, and the modal tells me what I'll get before I commit.
- As a creator, I can pin my package to my pipeline from the package form, and the control says what it does rather than "Mode locked" — reachable from the About card without insider knowledge.
- As a reader browsing a pinned package, I can see that it runs on the creator's pipeline before I press Start, from the package detail body — on both the package page and the detail modal. (Browser-verified on the package page; the card detail modal renders the same
PackageDetailBodyand is covered by jsdom only.)
Behavior:
- Package start with a pipeline choice creates a conversation with the chosen
pipeline_type,package_idset, and per-leg entry provenance intact — the same result the package-aware re-pick produces. - Readiness is computed from the package's bound Model Profiles' role entries, and drives exactly two things: the modal's copy and which card is preselected.
- A package whose runtime pair-owner Profile carries both a
beatand aproseentry opens the modal with Hybrid preselected; any other package preselects Classic. - A package whose only role entries are a
beatin one Profile and aprosein a different Profile is not ready — cross-Profile roles never form a pair. - A package binding a Beat-only Profile ahead of a fully paired one is not ready — readiness follows the runtime's pair-owner selection, so it is order-sensitive and must never advertise a pair the pipeline will not use.
- A locked package starts on the creator's pipeline with no choice offered.
- The gear-menu re-pick offers no pipeline choice on a locked package conversation, and a pipeline sent for one anyway is clamped server-side to the package's own — never a 400. ("Refuses" here means the pipeline cannot be changed, not that the request errors: a reader whose lock flipped mid-session did nothing wrong, and failing their start is worse than honoring the creator.)
Invariants that must stay true:
- Hybrid is never hidden or disabled for an unlocked package because it isn't hybrid-ready. Readiness sets the copy and the preselection; a package with zero role entries still offers Hybrid as a choosable option.
-
mode_lockedstill defaultsFALSEfor a newly created package. A creator who never touched the setting has not pinned anything, and the reader keeps the choice. - A locked package beats
Chat.PipelinePreference. A reader with a remembered "hybrid" preference still gets the creator's pipeline. - Classic is untouched. A package with no Hybrid involvement starts exactly as it does today, and an unlocked package defaults to the reader's existing behavior rather than silently switching anyone to Hybrid.
- On an unlocked package, a conversation started on Hybrid keeps §6's in-chat leg pinning working — choosing Hybrid at the start must not disable the How drawer's Beat/Prose pickers. (A locked package disables them, and that is the pre-existing lock behavior described above, not a regression of this line.)
Edges:
- A package whose Model Profiles were deleted or made private after publish still starts, degrading to the settings-bound legs rather than failing.
- A half-paired package (Beat entry, no Prose) reads as not-tuned and still starts fine on Hybrid if the reader picks it — the unmatched leg falls back to the seed mode, exactly as the runtime already does.
-
mode_lockedflipped on the package between page load and Start is honored by the server, not just the client — the modal is a convenience, the gate is server-side. -
An anonymous / guest reader hitting a package start gets the same pipeline treatment as a signed-in one.Not applicable (verified 2026-08-11): the whole/api/browsegroup is.RequireAuthorization()(BrowseEndpoints.cs:122), so no anonymous reader reaches the package detail surface at all. Nothing to satisfy here; if anonymous browse ever opens up, this edge comes back with it. - Hybrid remains unreachable for a package on platforms where it isn't supported (Discord — Hybrid is web-only in v1).
Cost model (and an honest correction)
The hybrid pipeline was originally conceived to save money: a cheap analytical model drafts beats, a strong model writes prose. The honest version is more nuanced, and the design should be built around the honest version:
- Two LLM calls per user turn, not one. Against running a single powerhouse for everything, this can land either way depending on token counts.
- The judgment is the hard part. The beat model needs genuine narrative intelligence — it has to know the silence is the beat. So the beat slot can't be reflexively downgraded to the cheapest model; under-powering it produces beats that are structurally wrong, and no prose model can rescue a bad beat.
- The prose slot is where the cheap, uninhibited open fine-tune lives. Prose execution is exactly the task a good RP fine-tune (on Featherless's flat subscription) is optimized for — and on a subscription rail, message length doesn't move the bill.
So the realistic economic shape is "a capable beat model + a cheap, fearless, subscription-billed prose model," not "two cheap models." The saving comes from moving the bulk token volume (the long prose output) onto the flat-rate Featherless rail while keeping the smaller, judgment-heavy beat call on whatever reasoner does it best.
v1 pricing decision (dev, 2026-06-25 — revised same day): a hybrid turn is billed its real two-call cost; the beat is NOT absorbed. The original decision absorbed the beat (charge the same Echoes as Classic); on building the itemized per-line billing it was reversed — an "absorbed / recorded-but-not-charged" line is a trap that institutionalizes a standing margin leak. So the beat is a normal billed line (its own line — a different model/rate than the prose): a hybrid turn costs prose-model + embedding + evals + beat, the turn's honest two-call price, no longer artificially equalized to Classic. This is the itemized-transparency ethic applied to pricing — show and charge the real cost rather than silently subsidize it. The beat's real cost is still recorded in web_message_stats (the hybrid-beat row) for margin/analytics and now appears as a beat line on the user's per-message receipt. (Operational design: docs-internal/architecture/billing/COMPUTE_COST_LINES.md.)
Relationship to existing systems
PipelineType.Hybrid/WebChatRequest— already define the multi-model entry point. This doc fills in the stubbed factory branch and the beat stage.- Journal / Trackers — the eval-pass infrastructure (
JournalEvalLlmService,TrackerEvalLlmService, theJournalEvalLlm.*/TrackerEvalLlm.*settings families,IPostLlmStagefire-and-forget, freeform-JSON parsing with graceful degradation) is the precedent the beat stage copies, run at the front of the turn instead of the back. The journal/tracker state is also an input to the beat model — the beat director reasons over current story state, and the prose model receives both the beat and (as today) the read-only state block. - Model Profiles / Model Profile Base Prompts & Flavors — Phase 2 adds a
roledimension to the same exact-provenance Profile composition substrate; it does not revive the superseded Bundle architecture. - Hosted Inference via Featherless — the prose rail. Featherless's pre-send moderation gate (the provider deliberately enforces no content policy) applies to the assembled prose prompt, which now includes the beat block — moderation runs after the beat is injected, before the prose call.
- Manifesto — "authentic over comfort" is a craft value; the hard limits remain enforced regardless of pipeline. Enforcement is non-blocking and pipeline-agnostic: the planned message-moderation checks flag content for review either way, identically for Classic and Hybrid. A beat-stage check, if added, is one more flag signal — it never blocks generation.
Resilience & latency
An earlier microservices sibling of this design (a Go-orchestrated version of the same beats→prose idea) carried per-service circuit breakers, timeouts, retry/backoff, and model-fallback chains in a YAML service registry. EoD already has most of that in-process at the provider level (TransientErrorHelper in server/EchoOfDreams.Core/LLM, the Featherless resilience rail), so the hybrid pipeline does not import the registry. Three pieces are worth calling out specifically.
Per-stage timeouts — build now
As built (2026-07-10): the "build now" landed as one beat-side key, not a per-role pair.
HybridPipelineLlm.RequestTimeoutSecondsbounds the beat call (falling back through the eval families, then the platform default); the prose leg rides the ordinary chatLlm.RequestTimeoutSecondslike any Classic turn. A distinct prose-side timeout key is future work. And a beat timeout does not degrade to single-model — it fails the turn like any LLM failure (the no-degrade-path decision, Non-Goals).
The beat call and the prose call have different latency profiles and deserve different budgets. The beat is short and structured (a beat sheet, not prose), it blocks the whole turn before the user sees a token, and it should fail fast; the prose call is long and streamed and tolerates a longer ceiling. So the hybrid pipeline carries a beat-specific timeout (HybridPipelineLlm.RequestTimeoutSeconds) rather than only the global chat timeout; the separate prose ceiling is the unbuilt half.
Model-fallback chain — future, rides on presets
Each role should fall back to a backup model when its primary errors or times out (Beat: another reasoner strong enough to carry the story; Prose: a hosted backup if Featherless is down). The sibling design expressed this as a fallback_service in a service registry. EoD will not add a parallel registry—presets are load-bearing and stay that way. A fallback chain belongs as a preset-level concept (a preset naming its fallback preset), riding under the per-role concrete preset selected on the user/settings side — never under the Profile Entry, which matches models rather than supplying them and stays credential-free (the consumption contract in Model Profiles — Hybrid-Ready). Deferred until the single-model preset-fallback story is designed; Hybrid inherits it once it exists.
Parallel non-dependent stages — future, needs a pipeline redesign
The obvious latency win is running anything that doesn't depend on the beat (lorebook search for the prose call, moderation pre-warm) concurrently with the beat call instead of after it. It's real, but out of scope by construction: ChatPipeline runs pre-stages → LLM → post-stages strictly in Order sequence — the stages are sequential by design. True intra-turn parallelism is a pipeline-execution redesign that would benefit the single-model path too, so it's tracked there, not here.
Design decisions
- The story (prose) model never does bookkeeping or judgment. It writes the beat it is given and adds no events, facts, characters or choices of its own: the director plans from beats, not prose, so anything the prose invents is lost to the story's memory. This is the Trackers north-star principle extended one step further: not only is state extraction a separate pass, narrative direction is too.
- The beat is injected as a
user-role direction block. Never system, never assistant. Prevents the prose model echoing the clinical scaffolding into its output. - Two separate conversation histories. Context hygiene buys voice consistency on the prose side and register purity on the beat side.
- Clinical framing is the mechanism, not a jailbreak. We are not arguing the prose model past its weights; we are structuring the turn so the flinch never triggers.
- Routing is role-tagged model-profile entries, reusing substring matching and
*fallbacks — not a bespoke two-model config. - Only the prose call streams to the user. The beat call is a hidden pre-pass.
- The beat track is the story-of-record. Journal, trackers, and summarization all read
beat_json, never the prose. Prose is presentational; the beat is canonical state. - The beat is structural story beats —
npcs/environment/plot/situation(to extractors + prose) and portrayal hints (to prose, and back to the director in its own history — MD-12). Hints never leak into journal/memory; the key:value state role is Trackers', distilled from the beat (revised 2026-06-25 — was astory_statekey:value map, removed to stop duplicating Trackers). beat_jsononweb_messages, mirroringtracker_json. One column serves extraction, beat-model history, and the verify/edit surface. No separate hidden message track.- Beats are shown like trackers — hidden by default,
show_beatsmaster toggle, collapsed bar, per-message expand, inline edit with carry-forward.
Open questions
Load-bearing product / commercial / content-policy calls the dev owns — surfaced here, not silently defaulted into the build:
- Echo pricing of a hybrid (two-call) turn. Resolved (dev, 2026-06-25 — revised same day): a hybrid turn is billed its real two-call cost (
prose-model + embedding + evals + beat); the beat is NOT absorbed. The original "absorb the beat / same-as-Classic" call was reversed on building the itemized per-line billing — absorbing a line is a trap that institutionalizes a margin leak. The beat is a normal billed line and appears on the user's per-message receipt. See Cost model +docs-internal/architecture/billing/COMPUTE_COST_LINES.md. - Is Hybrid free-to-choose in v1, or gated? Resolved (dev, 2026-06-25): free to all — gating an unproven pipeline is counterproductive when the whole point of v1 is to get people testing it. (Pricing rationale updated with the beat-billing reversal: Hybrid is priced at its honest two-call cost, not equalized to Classic — itemized on the receipt so the cost is transparent, not a hidden surcharge.)
- Hard-limit enforcement location. Resolved (dev, 2026-06-25): enforcement is non-blocking and pipeline-agnostic. The planned message-moderation checks flag content for review (never block generation), identically for Classic and Hybrid; a beat-stage check, if ever added, is just one more flag signal. Rationale: don't punish non-offenders with latency to catch a few — offenders are flagged, the offense is human-verified, and enforcement is a ban after verification, not a generation-time block. So there's no "canonical blocking gate" to place — Hybrid inherits the same message-flagging model as Classic. See G6.
Engineering / design questions, open for later phases (v1 defaults noted, mine to decide):
- Prose edits vs. the beat as story-of-record — decided 2026-09-24 (owner): (a)+(b), as a
modal. Saving an edit to one record asks the writer to check the other, and offers the fix in one
click: a prose edit on a turn with a beat → "Check the story beat too" → Edit the beat (opens
that turn's beat source editor); a beat edit → "Check the prose too" → Regenerate prose only
on the latest turn (the server only ever re-renders the last assistant row), otherwise Edit the
prose. A reminder the writer followed never asks back about the record they just fixed; a cleared
beat asks nothing; "Don't show this again" is per device. (c) stays rejected — it inverts the
story-of-record direction. As built:
BeatProseCheckModal+NewChatPage; verified in the browser 2026-09-24 — all three variants, the no-second-reminder rule, the dismissal, and a prose-only re-render whose single model call carried the corrected beat. Original question, for the record: (raised on external review 2026-07-31 — real semantic conflict, needs a decision before Hybrid leaves experimental). The beat is declared canonical (beat_jsonis what journal, trackers, and summarization read — invariant 7 above), but editing a visible prose message deliberately leavesbeat_jsonuntouched. So a user can correct "the door opens" to "the door stays shut" in the prose, and every downstream state system preserves the opposite event forever. Three candidate answers, none decided: (a) label prose edits as cosmetic in the UI (honest, cheap, surprising to users who think an edit is an edit); (b) pair a prose edit with an optional beat correction affordance (the Story-beat panel is read-only today); (c) a reconciliation pass that re-derives the beat from edited prose (an extra LLM call, and it inverts the story-of-record direction). The trap to avoid is deciding by silence — today's behavior is (a) without the label. - Latency. Two serial calls add the beat's full latency before the first prose token. Mitigations: keep the beat short; a fast beat reasoner, as long as it is still strong enough to carry the story (the director is the heavy lifter, so speed never comes out of its judgment); speculatively start the beat as the user message arrives. v1 measures it (UC-O1) and shows a "the director is blocking the scene" indicator (UC-W5) — whether that UX is acceptable is what the experiment answers.
- Regeneration semantics. "Regenerate" = re-run only the prose (same beat) or both (new beat)? Composes cleanly with
beat_json: "rewrite this" re-renders the stored beat; "take it differently" regenerates the beat first; a user-edited beat makes "rewrite against my corrected direction" first-class. v1 re-ran both (G4). As built (2026-09-20): the prose-only split shipped. A Hybrid turn's message menu now offers Regenerate everything (unchanged — new beat + new prose) and Regenerate prose only (re-render the message's stored beat, prose call only). The second is what makes inline beat editing land: correct the beat, re-render against the correction, instead of a new director call discarding it. Beat-only regeneration and beat-skip pass-through remain open. - Beat-skip on low-stakes turns. Can the beat stage cheaply decide "no new beat needed, pass through" (the journal per-message vs per-summarization debate)? v1: no — every turn runs both calls; measuring that two-call cost is part of the experiment. Phase 2 may add pass-through.
- Fold the eval into the beat call, or keep it separate? Story-of-record argues the beat call can emit journal/tracker deltas directly. v1: separate
IPostLlmStagereadingbeat_json(reusesJournalEvalStageBase, keeps graceful degradation); Phase 2 folds it in if the degradation story survives. - Single-model / per-role fallback. When the prose model can't resolve (hosted inference off) or a call times out, degrade to single-model
WebChat? v1: no degrade path — a beat failure fails the turn like any LLM failure. The richer per-role model-fallback chain (beat→backup, prose→backup) rides the preset-fallback mechanism when it exists. - Model Profile role schema. Pin the exact role-tagged Entry/group tables and fallback rules before Phase 2 consumes them. The durable entity decision is already made: roles extend Model Profiles; they do not become linked Profiles inside a Bundle. V1 continues using flat
HybridPipelineLlm.*settings. As built (2026-07-12): pinned and shipped —model_profile_entries.role(0/1/2, role-scoped uniqueness), Primary-only classic resolution with a genuine literal-*wildcard tier, and winning-entry provenance onweb_conversations.model_profile_entry_id(91_model_profile_entry_roles.sql; see the Model routing as-built note). Runtime consumption stays open: the hybrid legs still resolve fromHybridPipelineLlm.*(now the seeded mode bindingsBeatModeId/ProseModeId), never from role-tagged entries.
Phase 1 — v1 Proof-of-Concept (decided scope)
The full design above is the target. v1 is a deliberately experimental proof-of-concept answering one question—does beats → prose actually produce more authentic scenes than one model, and at what latency? So the scope locks the substrate (schema, routing, storage) and keeps the experimental variables soft (prompts, model pair, context split). No creator Modes or role-tagged Profiles yet.
Altitude split — durable vs. throwaway in v1
- Durable now (migrations are forever):
pipeline_typeon the conversation,beat_json/beat_summarycolumns, theweb_message_stats.stagediscriminator, theHybridfactory branch, the SSE stage protocol. - Soft / tunable (the experiment itself): the hardcoded beat & prose prompts, the locked model pair, the beat-vs-prose context split. These are meant to be calibrated from real sessions, not perfected up front — which is why v1 ships flagged "experimental."
Pipeline & beat stage
- Flesh the
Hybridbranch inChatPipelineFactory.GetStageKeysForType:PRE: context → compute_allocation → beat_direction (new);POSTunchanged from WebChat (allocation precedes the beat so a blocked turn never bills a beat call — G1). Thebeat_directionIPreLlmStageis the first pre-LLM stage to make a blocking model call — shaped like an eval service (EvalLlmServiceBaselineage), it resolves the beat model, writesbeat_json, and injects the beat as a user-role direction block on the last user turn. - Locked model pair, resolved from the
HybridPipelineLlm.*settings family — beat =HybridPipelineLlm.Provider/Endpoint/ApiKey/Model, prose =HybridPipelineLlm.Prose*(+ preset families) — mirroringJournalEvalLlm.*. One beat-side timeout,HybridPipelineLlm.RequestTimeoutSeconds; the prose leg rides the chatLlm.RequestTimeoutSeconds(a per-role prose timeout was not built — see Per-stage timeouts). No degrade path — a beat failure/timeout fails the turn like any LLM failure today (reuse the existing mechanism). No beat-skip — every hybrid turn runs both calls. - Hardcoded built-in prompts for both beat and prose (creator-tunable modes are Phase 2). The beat emits structural story beats (
npcs/environment/plot/situation) + portrayal hints. Keep the prompts and the context split in one tunable place — calibrating the split (does the prose model need persona/lorebook/character, or only the beat?) is the core experiment and the reason v1 is "experimental." (As built 2026-07-12: both prompts are now mode-driven when bound —HybridPipelineLlm.BeatModeId/.ProseModeIdpoint at the seeded "Beat Director"/"Visceral Prose" system modes, making them admin-tunable in the DB; the hardcoded constants are retained as the unset/unresolvable fallback. See the §4 seed-modes as-built note.)
Storage — reuse the substrate (column over new table)
beat_json TEXTonweb_messages(mirrorstracker_json; TOAST'd out-of-line so it doesn't bloat history scans, inherits branch/version/retention —38_branch_conversationalready copiestracker_json). Holds{ npcs, environment, plot, situation, portrayal_hints }— content only, no model/timing. Beat-model history = interleave user turns withbeat_json— as built, this is Phase 2: v1 has nobeat_jsonhistory injector and instead flattens the assembled prose prompt into a transcript for the beat call (BeatDirectionStage.FlattenPrompt,TODO(hybrid-phase2); the flatten is the G3 context-split mechanism).beat_summarycolumn onweb_summaries— beat-track summarization reuses the existing rollup/merge mechanism, one level over.- Point journal / tracker / summary extraction at
beat_json(separate post stages reusingJournalEvalStageBase; fold-into-beat-call deferred to Phase 2). Define the empty-beat_jsoncontract so extractors don't zero out existing state on a missing beat.
Stats
- Extend
web_message_statswithstage VARCHAR(20) NOT NULL DEFAULT 'classic'— values'classic'|'hybrid-beat'|'hybrid-prose'. A hybrid turn writes two rows (beat + prose) FK'd to the same message, each with its own model/tokens/timing; this differentiates pipeline source for analytics and visibility. (VARCHAR(20), not 10 —'hybrid-prose'is 12 chars.) Verify nothing assumesweb_message_statsis strictly 1:1 with assistant messages before relying on it (functions/45_message_stats_functions.sql).
Selection — per-conversation, immutable
web_conversations.pipeline_type SMALLINT NOT NULL DEFAULT 0(0=Classic, 1=Hybrid).SendMessagereads it → setsWebChatRequest.PipelineType. Immutable per conversation, so "switching pipeline always starts a new conversation" is structural, not a rule to enforce.- New-chat modal: Classic / Hybrid, with an Experimental badge (as built: a
Badge, not theCornerRibboncomponent) + explanation on the Hybrid card. "Remember my choice" → user settingChat.PipelinePreference(ask|classic|hybrid, defaultask); when notask, skip the modal and use the stored value. - Chat dropdown → "Start a new conversation": for a standalone character chat, spin a fresh conversation and preselect the same directly accessible character/Mode, then always reopen the pipeline modal (explicit re-pick, ignoring the remembered preference). A package chat must instead use the package-aware restart contract from Document Mode Editor: reload current package context, preview/re-resolve its Profile Entry/Base, and never assume an encapsulated package Base can be copied as a directly usable Mode. Future greeting selection belongs to the corresponding launch-context preview.
Partly superseded (2026-09-20) — read the correction under this callout before trusting it. Two of its three claims have since changed: the picker gained a second caller on 2026-08-11 (package start), and the deferral it records has been lifted.
As built (2026-07-10, dev decision — stays as-is for now): the picker modal (
HybridChoiceModal) is wired only into the in-chat "Start a new conversation" re-pick (item 10). The main character-direct start path (character page →/chat?characterId=…→ the saved-chats page's raw conversation POST) shows no picker and cannot pass the hybrid flag — a writer starting a chat from a character card always gets Classic. AndChat.PipelinePreferenceis written on modal confirm but nothing reads it back yet (write-only), so item 9's "skip the modal when notask" is not in effect. Dev decision: leave this as-is — the new-chat flow will be addressed and redesigned once persona templates come live properly, and the picker wiring lands with that redesign. UC-W1 / UC-W6 in the Acceptance Criteria are marked deferred accordingly.
Correction (2026-09-20) — the deferral above is LIFTED, and one of its claims was already stale. Point by point against the code:
- "wired only into the in-chat re-pick" — was already false since 2026-08-11.
HybridChoiceModalhas had a second caller since package start shipped:PackageDetailBody(PackageDetailContent.tsx), shared byPackagePageandPackageDetailModal. The Package start section below documented this correctly while this callout kept saying "only" — the two sections disagreed with each other for five weeks. The same wrong claim was duplicated in code onCreateWebConversationRequest.IsHybrid's doc comment.- "the character-direct path always gets Classic" — was true, and is the gap being closed. That path (
/chat?characterId=…→SavedChatsPage's raw conversation POST) genuinely had no picker and never sent the flag.- "
Chat.PipelinePreferenceis write-only" — was true. The setting round-tripped to the client on the auth/display-settings DTO for the Settings page to render, and nothing in either the frontend or backend creation path branched on it. The write seam (pipelinePreference.ts, the modal'sshowRememberplumbing) was built in anticipation; only the read was missing.Dev decision reversed 2026-09-20: waiting for the persona-templates redesign is no longer the plan. The preference becomes load-bearing across every new-chat entry point —
askshows the picker,classic/hybridstarts directly with no modal, anything unknown falls back toask(never silently Hybrid) — and the character-direct path gains the picker. A locked package is no longer a carve-out — this sentence originally read "a locked package still ignores the preference entirely: the creator's pin outranks it, and the server-side clamp, not the client, remains the gate." That was written beforepackages.mode_lockedwas retired later the same day, and it did not survive the retirement: there is no server-side clamp left to be the gate. Leaving the client's skip in place while the clamp was gone made a locked, hybrid-ready package send no pipeline at all and therefore start Classic every time, with no path to Hybrid — strictly worse than the clamp it replaced, and silent. Every package now reads the preference, locked or not.Update (2026-08-05, dev decision): the gear-menu re-pick is now package-aware — and is the sanctioned Hybrid entry point for packages while the pipeline is experimental. Previously a package chat's re-pick demoted to a standalone copy (the exact "copy an encapsulated Base" trap item 10 warns about, and the reason package+Hybrid was unreachable end-to-end). Now, when the source conversation is package-bound, the re-pick creates a new conversation from the same package honoring the pipeline pick (
fn_create_conversation_from_package(p_pipeline_type)+isHybridon the package POST — shipped with hybrid-readiness piece 1), skipping the greeting picker because the package start resolves its own effective greeting/defaults server-side. This is deliberately not item 10's full package-aware restart contract (reset/result preview, Style-&-rules roster) — that remains Document Mode Editor territory; this is the minimal correct routing so package readers can reach Hybrid at all. Verified live 2026-08-05: re-pick on a package conversation → new row withpackage_idset andpipeline_type=1, role-tagged entry provenance intact.The front door that replaces this workaround is specced at § Package start (2026-08-06). Until it lands, this re-pick remains the only route from a package into Hybrid — which is also why the lock work in that section has to gate this path too, not just the new modal: a pipeline pin the start modal honors and the gear menu ignores is one click from decorative.
UI & streaming
- Show both outputs: prose as the main bubble, beat in a collapsible panel (reuse the
TrackerBarcollapsed-by-default pattern) renderingbeat_json. - SSE stage events: emit stage transitions
beat_running→prose_streaming(anonymous lowercase frames per the SSE-heartbeat convention); the keepalive pump runs during the blocking beat call, then prose streams.
Phase 2+ then lands role-tagged Model Profile composition (Beat/Prose Base Modes), creator-tunable halves plus the Mode-editor support to author them (the beat provider key + Profile role-pairing UI + split guidance—see §Modes #5), inline Beat edit/carry-forward, eval-folded-into-Beat consolidation, Beat-skip gating, multi-greeting selection, and Featherless-hosted prose models as first-class.
The v1 carry-over points are tagged in code for this work to find. Grep TODO(hybrid-phase2) for the structural items this section absorbs—the imperative prose-prompt rebuild in BeatDirectionStage (→ a beat content-provider key + a starved Prose Mode) and ProseSettingsOverride flat HybridPipelineLlm.Prose* routing (→ role-tagged Model Profile Entries). (As built 2026-07-12: the mode-driven half of the first item landed — the beat key exists and a bound Prose Mode IS the starve, see the §4 as-built note; the updated TODO(hybrid-phase2) in BeatDirectionStage now points at the remaining role-tagged profile resolution, beat-side provider resolution, and beat history injection.) (Superseded 2026-09-20: all three landed — role-tagged profile resolution earlier, and beat-side provider resolution + beat history injection in the §4 as-built note. BeatDirectionStage carries no TODO(hybrid-phase2) any more; the TODO(hybrid-cleanup) items below are untouched.) Grep TODO(hybrid-cleanup) for hygiene that need not wait on role routing: the EvalLlmServiceBase name, duplicate Beat carriers, the "beat_direction" magic string, and misnamed HybridExtraction.
Open v1 gaps — and how v1 closes them
Validation surfaced seven gaps between "decided scope" and "buildable." Each is resolved here so v1 has no undefined behaviour; the two that actually block a build start are G1 (billing order) and G2 (beat output contract).
G1 — Balance check must run before the beat call. Problem: the natural wiring context → beat_direction → compute_allocation fires the beat LLM call before the balance check (ComputeAllocationStage is Order=500, last pre-stage), so a zero-Echo user triggers a beat call before the balance_block short-circuits them — wasted platform compute on a turn that's about to be blocked. Resolution: (Billing note, as built 2026-07-10 — the beat-line wiring in docs-internal/architecture/billing/COMPUTE_COST_LINES.md shipped; (2) and (4) below describe the billed state per the revised 2026-06-25 pricing.) (1) reorder to context → compute_allocation (500) → beat_direction (550), so the turn is gated before any compute; (2) the beat is in the user estimate — HybridComputeLineProfile includes the beat line among the turn's candidate kinds, so compute_allocation reserves the real two-call amount (embedding + model + evals + beat); (3) beat_direction checks context.ShouldSkipLlm / SynthesisKind and no-ops when allocation blocked — no beat call on a blocked turn; (4) ComputeSettlementStage settles the model line to the prose leg exactly as Classic does and the beat line to the beat call's real cost from context.BeatTelemetry; the same telemetry is also recorded in the hybrid-beat web_message_stats row for margin/analytics (two views of one source, not competing).
G2 — Beat output contract + parser. Problem: "hardcoded prompts" with no defined beat_json shape leaves nothing to parse. Resolution (as built, revised 2026-06-25): the beat is genuine structural story beats, NOT key:value state — that key:value role belongs to Trackers, which now distill their values from the beat. The beat emits prompt-instructed JSON (not forced json_object — the eval-no-forced-json rule): { "npcs": "…", "environment": "…", "plot": "…", "situation": "…", "portrayal_hints": "…" }. npcs/environment/plot/situation are the four structural fields (what each non-user character does + why + continuity details; observable environment changes; new plot logic; the circumstance now facing the user — never a choice menu); portrayal_hints is craft direction (prose-only). A BeatParser layers typed deserialization on EvalJsonParser (fence-strip, preamble-tolerant ExtractJsonObject, truncation-tolerant) exactly as JournalEvalParser does, and folds the legacy { beat_text, story_state } shape (beat_text → npcs; the key:value story_state is dropped). Graceful degradation (the parser never throws): on parse failure, the raw response becomes npcs with the other fields empty — the prose still receives a direction block (raw text) and the extractors still read it. The recovered object is what lands in beat_json. (2026-11-07, owner: "make sure the beat director in hybrid supports freeform AND json - we need to support both". Plain prose is no parse failure any more: it is a freeform beat, { "freeform": … }, read verbatim by every reader. Since the owner's second 2026-11-07 line ("Beat director should always fall back into 'freeform' when the json parse fails") nothing degrades into npcs at all: a broken JSON beat or one cut at the cap is a freeform beat of its text, and only an empty answer is no beat — see the as-built note in §3.)
G3 — v1 context-split default. Problem: the split is the experiment, but a starting point must ship. Resolution (as built): the starve is expressed as variables in the prose prompt template, not a separate reduced context-assembly. The beat reuses the full assembled story context (the prose's would-be context, flattened to a transcript) — character, persona, lorebook, journal, trackers, memory, history. The prose prompt is rebuilt from HybridPipelinePrompts.ProseSystemTemplate, which interpolates only the light variables ({{character}} brief + {{persona}} + a static craft framing baked into the text) and references nothing heavy — so the prose is starved by construction; the beat rides the last user turn as a user-role director's note. Widening/narrowing the split = editing that one template string (a compile-time constant in HybridPipelinePrompts.cs — see the UC-O2 as-built note; since 2026-07-12 this describes the fallback path — with HybridPipelineLlm.ProseModeId bound, the prose mode's provider-key set defines the split, see the §4 as-built note). v1 model pair (both independently lockable): beat = HybridPipelineLlm.*; prose = HybridPipelineLlm.Prose*. Unset, the prose falls back to the conversation's chat model (ProseSettingsOverride → Llm.*); the beat falls back to the chat model too (BeatLlmService.Chain: HybridPipelineLlm → Llm, since 2026-11-22, owner, Relay eod-421 — until then it walked TrackerEvalLlm → JournalEvalLlm → SummarizationLlm first and reached the chat model only indirectly) (G7: one model for both at first). So it runs with no hybrid-specific config — but the operator runs the intended pair (a cold beat reasoner + an uninhibited prose fine-tune) by setting HybridPipelineLlm.Model and HybridPipelineLlm.ProseModel. The prose override (ProseSettingsOverride) wraps the prose LLM call ONLY — the pipeline context, the beat call, and billing keep the chat settings, so the two legs genuinely run on two different models (the experiment's whole point). Extraction reads the beat, not the prose: the per-message tracker + journal evals read beat_json (the structural fields — npcs/environment/plot/situation — never the portrayal hints) via HybridBeatState.ToExtractionText() — the prose deliberately obscures clinical state, so reading it would be the lossy round-trip the story-of-record design deletes. Window/summarization extraction from beats (the beat_summary rollup) is also wired (WebSummarizationTriggerService carries BeatJson into the summarizer and persists beat_summary). Manual summary regeneration (the summaries-panel "Regenerate" button — distinct from turn regeneration in G4) preserves the beat-track too: the regen read rows carry each window's beat_json / each child's beat_summary, so the re-summarization reads the clinical beat (not the obscured prose) and re-derives beat_summary by the same windowHasBeats / rollupHasBeats rule — rather than refreshing the prose while the beat-track silently goes stale or null. And when the summarizer gets a fact wrong, the user can directly edit the beat-track: the Memory drawer surfaces an editable "Beat-track memory" field on Hybrid summaries/memories (alongside the prose summary), saved through fn_update_summary_authorized as a three-state field (omit/clear/set) that never touches the prose embedding.
G4 — Regeneration of a hybrid turn. Problem: regenerate exists today (version groups) but is unspecified for hybrid. Resolution: v1 — regenerate re-runs the whole turn (new beat + new prose) into a new version row, exactly as Classic regenerate does; the new beat_json rides the new version row. IsRegeneration flows through unchanged, no new mechanism. Prose-only / beat-only regen is the Phase 2 refinement already noted in Open questions.
As built (2026-09-20) — prose-only regeneration shipped; beat-only did not. The request carries regenerateMode: "full" | "prose_only" alongside isRegeneration; "full" (or absent) is byte-for-byte the v1 behaviour above. On "prose_only" the server resolves which beat — it reads it off GetLastAssistantMessageAsync, the same read WebMessagePersistence uses to pick the row it versions, so the beat re-rendered and the row the new version attaches to cannot diverge. The client only names the mode; it never supplies beat content, so a beat the user corrected in the panel is the one re-rendered rather than one the client made up. It travels as IPipelineContext.ReusedBeat (HybridBeatReuse { BeatJson, BeatRaw }), and BeatDirectionStage — same stage, same beat_direction factory key — parses the stored beat_json instead of calling the director, then performs the identical starved prose rebuild. Only the model call is dropped.
Four consequences, each deliberate:
- The pair carries onto the new version row VERBATIM, not re-serialized from the parsed state: a round-trip would normalize a legacy
{ beat_text, story_state }row and silently hand back a different beat than the one corrected. - Billing: the
beatline is still reserved (it is a property of the pipeline type, not of the turn) and the stage settles it to 0 viaBilling.SkipAsync— a real line that cost nothing, rather than a line that vanished from the receipt. The reservation refunds inside the same turn. - Stats: the turn still writes both rows. The
hybrid-beatrow carries NULL provider/model/tokens/latency andweb_message_stats.call_reused = TRUE; that column is what makes those NULLs read as "reused, not run" instead of "telemetry lost", and it keeps the two-rows-per-hybrid-turn shape every consumer of that table was built against. It is a dedicated column and not a thirdevent_typevalue, becauseevent_typeis equality-matched (= 'regenerate') by the regen-rate analytics and the info modal — a new value would silently drop a prose-only regen out of the regeneration bucket and label it "Fresh". - Refusals are clean 400s before the stream opens — not Hybrid, not a regeneration, no stored beat, or an unknown mode. Nothing falls back to a full regeneration, because a silent full regen is exactly the discarded-correction this feature exists to prevent.
G5 — A surface to read the experiment. Problem: the stage discriminator records data but nothing lets the operator see the comparison. Resolution: v1 reuses two existing surfaces — (a) the per-message info modal (today one call's model/tokens/timing) renders both stat rows for a hybrid turn, keyed by stage; (b) the in-chat collapsible beat panel makes the beat inspectable, so output comparison is "open a Classic and a Hybrid chat with the same character." A dedicated Hybrid-vs-Classic analytics view is Phase 2.
G6 — Moderation of the beat. Problem: what content-checking applies to the beat? Resolution: moderation is non-blocking and pipeline-agnostic (dev decision) — the planned message-moderation checks flag content for review, never block generation, and treat Classic and Hybrid identically. Hybrid therefore needs no special moderation path: it inherits the same message flagging as Classic. The beat is internal content the same flagging can extend to (a beat flag is just another review signal); nothing about Hybrid blocks a turn on content grounds, and no beat-stage "gate" is built or planned.
G7 — Which two models. Problem: the "locked pair" is never named. Resolution: the pair is runtime settings config (HybridPipelineLlm.Model / HybridPipelineLlm.ProseModel + preset families). Recommended shape: Beat = a cold, structurally-strong reasoner where clinical framing survives the positivity bias; Prose = an uninhibited open fine-tune on the Featherless flat rail. The concrete pick is the experiment's variable; local dev can bring the pipeline up on one model for both, then differentiate the beat.
Edge cases folded in: a greeting (assistant turn with no preceding user turn) has no beat — the history interleave tolerates a missing beat_json the same way the empty-beat contract (G2) does. Editing a hybrid message in v1 is Classic-equivalent (edits the prose content; the beat is untouched).
Non-Goals (v1)
Deliberately out of scope for v1 — several of these a reader would reasonably assume are in:
- Creator-authored Beat/Prose Modes and role-tagged Model Profile composition. V1 as frozen ran the settings-bound seed Modes (
HybridPipelineLlm.BeatModeId/.ProseModeId, hardcoded constants only as last-resort fallback — §4's as-built note) on flatHybridPipelineLlm.*settings. (Since superseded: role-entry consumption shipped 2026-08-04 as piece 1 of Model Profiles — Hybrid-Ready — see the Model routing update note above. Creator-authored pair authoring in the Workbench remains open.) - The
show_beatsverify/edit surface with carry-forward. v1 shows the beat (collapsible, read-only); inline beat editing,manual/evalsource attribution, and corrected-beat carry-forward are Phase 2. - Beat-skip / pass-through on low-stakes turns. Every v1 hybrid turn runs both calls by design.
- Per-role model-fallback and graceful single-model degrade. A beat failure fails the turn in v1; no automatic fall-back to Classic or a backup model.
- A blocking beat-stage content gate. Moderation is non-blocking flagging across both pipelines (G6); there is no plan to reject or pre-empt a turn at the beat. Hybrid inherits Classic's message flagging.
- Prose-only / beat-only regeneration. v1 regenerate re-runs the whole turn (G4). (Since superseded in part: prose-only shipped 2026-09-20 — see the G4 as-built note. Beat-only remains out of scope.)
- Multi-greeting selection. The new-conversation flow preselects the current greeting; a picker is a later addition.
- A dedicated Hybrid-vs-Classic analytics dashboard. v1 reads the experiment from the existing per-message info modal + in-chat beat (G5).
- Eval folded into the beat call. v1 keeps a separate post-LLM eval reading
beat_json. - Featherless-hosted prose models as a first-class, curated option. v1 can point the prose setting at any model; the curated open-fine-tune catalog is Phase 2.
- Discord / non-web platforms. Hybrid is web-only in v1, matching the
WebChatsubstrate. - Intra-turn parallelism (running beat-independent work concurrently with the beat) — a pipeline-execution redesign tracked on the single-model path, not here.
Acceptance Criteria (v1)
The feature is not done until every box below is verified ✅ against the running product. There are two users: the Writer (end user) and the Operator (running the experiment — a real user of an experimental feature). A hybrid turn is billed its real two-call cost (prose + embedding + evals + beat; the beat is billed, not absorbed — revised 2026-06-25); Hybrid is free to choose in v1, never an access gate.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- UC-W1 — As a writer, I can choose Classic or Hybrid when starting a new chat, from the new-chat modal that appears on conversation start; the Hybrid card is clearly marked Experimental and explains what it does — no insider knowledge needed. (Closed 2026-09-20. The character-direct path (/chat?characterId=…) gained the picker; package start and the in-chat re-pick already had it. Driven in the preview as a signed-in user: navigating the character-direct URL with the preference at ask renders the picker, Hybrid card badged Experimental.)
- UC-W2 (the hypothesis) — As a writer, for the same character + opening I can get observably more committed / less hedged prose from Hybrid than Classic, comparable by starting one chat of each.
- UC-W3 — As a writer, I can see the director's beat (why the scene went this way) or hide it, via the collapsible beat panel on each Hybrid reply (collapsed by default).
- UC-W4 — As a writer, my trackers / journal / memory stay accurate in Hybrid — visible in the same state surfaces as Classic.
- UC-W5 — As a writer, during the longer two-call wait I see a progress indicator ("the director is blocking the scene…") in the chat, and the stream completes without a silent break.
- UC-W6 — As a writer, once I check "remember my choice" I am not re-asked the pipeline on each new chat; and I can switch back to Classic via "Start a new conversation" in the chat dropdown. (Closed 2026-09-20. Chat.PipelinePreference is now READ, not just written: ask shows the picker, classic/hybrid start directly with no modal, and anything unknown falls back to ask — never silently Hybrid. All three states driven in the preview against running services on the character-direct path: ask renders the picker; hybrid creates a conversation whose pipelineType is hybrid with no modal; classic creates one whose pipelineType is classic with no modal. A legacy
mode_lockedpackage is not a carve-out — it reads the preference like any other package, because the server-side clamp that used to answer for it is gone (verified byHybridRoleModeResolutionTests.LockedAndHybridReady_StillHonorsAClassicRequest, and by the two inverted jsdom tests on the package-start surface). The gear-menu re-pick deliberately still always shows the picker, per item 10 and the invariant below — it is the escape hatch back to Classic for a reader who remembered Hybrid, so honouring the preference there would close the first half of this criterion by breaking the second.) - UC-W7 — As a writer who ticked "remember my choice", I can change my default pipeline — or go back to being asked — from Settings → Features → New chats (
/settings#features), and my very next new chat follows it; the picker's checkbox tells me where that setting lives. (Closed 2026-09-29. Reported by readers: once remembered, the choice was one-way —Chat.PipelinePreference's category (Chat) was in no settings view, so no Settings tab rendered it, and it still carried a stalePreviewlifecycle saying nothing read it. Now anew-chatview feeds a New chats section at the top of the Features tab, in the same staged form as the feature toggles — one Save/Cancel pair for the tab, so no Save can strand a pipeline edit. Save mirrors the value into the cached auth user the start paths read (readPipelineChoice), and authStore's cross-tab listener carries it to other open tabs, so the next start follows it without a token refresh. Driven in the preview against running services as a reader with "remember: Hybrid": the section shows Hybrid; set Ask each time + Save; the next character-direct start raises the picker, with the checkbox hint naming Settings → Features. Deploy-skew hardening found in review: a settings view the server doesn't define now returns nothing (it returned every user-readable row), and the console filters the section to the view's own category. Pinned byUserSettingReachabilityTests— every C#-defined user-scoped setting must be admitted by a view a console requests, or name its owner — andSettingsPage.newChatPipeline.test.tsx.) - UC-O1 — As the operator, I can compare Hybrid vs Classic per turn — per-call timing via the per-message info modal (both stage rows) and actual outputs via the in-chat beat + prose — without insider tooling.
- UC-O2 — As the operator, I can retune the beat/prose prompts and the context split in one place and re-measure, without a pipeline-code change. (As built 2026-07-10: the "one place" half holds—both prompts and the context split live in
HybridPipelinePrompts.cs—but they are compile-time constants, so retuning is a code edit + redeploy, not a settings change. The "without a pipeline-code change" half is Phase 2, when Beat/Prose authoring becomes creator-editable Mode pairs: thebeatprovider key plus role-tagged Model Profile path in Guided Mode Editor §Hybrid-aware authoring.) (Superseded 2026-07-12: the operator half is now satisfied — the prompts live in the seeded "Beat Director"/"Visceral Prose" mode rows bound atHybridPipelineLlm.BeatModeId/.ProseModeId, so retuning is a DB/mode edit, no redeploy; a bound prose mode's provider-key set is the context split.HybridPipelinePrompts.csremains only as the unset fallback. Creator-editable pairing via role-tagged Profiles is still Phase 2 — see the §4 as-built note.)
Behavior (exercise the mechanism):
- A conversation with
pipeline_type = 1builds the Hybrid pipeline;= 0builds Classic. - Every hybrid turn runs exactly one beat call then one prose call; the assembled prose prompt carries the beat as a user-role block (not system/assistant).
-
compute_allocationruns beforebeat_direction, reserving the turn's real two-call cost — thebeatline IS in the user estimate (gated on the Hybrid pipeline type);ComputeSettlementStagesettles themodelline to the prose leg and thebeatline tocontext.BeatTelemetry. - The beat emits prompt-instructed JSON recovered by
BeatParseronEvalJsonParser;beat_json(npcs+environment+plot+situation+portrayal_hints) is persisted on the assistant message. - On hybrid turns, journal / tracker / summary extraction read
beat_json;web_summaries.beat_summaryis produced by the existing summarization mechanism. - A hybrid turn writes two
web_message_statsrows (stage='hybrid-beat','hybrid-prose') with per-call model/tokens/timing; a Classic turn writes one (stage='classic'). - The client receives
beat_running→prose_streamingstage events; the connection survives the blocking beat call (keepalive). - Regenerate on a hybrid turn re-runs the whole turn (new beat + new prose) into a new version row carrying its own
beat_json.
Invariants that must stay true (carve-outs a reviewer can break if regressed):
- Classic is untouched — a Classic turn reads prose, writes one
stage='classic'stat row, runs no beat call, and behaves exactly as before this feature. - A hybrid turn debits the user its real two-call cost — the beat is billed as its own
beatline on the user ledger + receipt (revised 2026-06-25 from the original platform-absorbed decision; absorbing was a margin leak). The beat's per-call cost is also recorded in thehybrid-beatweb_message_statsrow for margin/analytics (the two are different views of oneBeatTelemetrysource, not competing). -
pipeline_typeis set at conversation creation and never mutated — the only path between pipelines is a new conversation. - An empty / missing
beat_jsonnever zeroes existing journal / tracker state. - Once set,
Chat.PipelinePreferencedoes not re-prompt on normal new-chat (only the explicit "Start a new conversation" re-shows the modal). -
beat_jsonsurvives branch and regeneration (carried onto the new version/branch rows). (Its verbatim twinbeat_rawdoes too — see The raw beat.) - Message moderation behaves identically to Classic (non-blocking flagging, no generation-time block) — Hybrid adds no beat gate and does not change the moderation path.
- Existing per-message-stats consumers still function (the two-rows-per-hybrid-turn change breaks no 1:1 assumption).
Edges (empty / failure / unauthorized / boundary):
- A user without enough Echoes who picks Hybrid is blocked before any beat call —
balance_blockbubble shown, no beat stat row, no beat spend. - A beat-call failure / timeout fails the turn with the standard error bubble (regenerate-able) — no half-turn, no orphaned allocation (settled to 0).
- Malformed / truncated beat JSON falls back to a freeform beat of its text, verbatim (owner, 2026-11-07: "Beat director should always fall back into 'freeform' when the json parse fails"; superseding the raw
npcsdegrade) — the writer's note, the stored twin, the director's next-turn history and the extractors carry the text; statusFallback; logged on the salvage's rule (a Warning on the platform's key without a cap, Info on the reader's own preset or at the cap); an empty answer stays no beat; prose still renders, nothing throws. (Unit + stage:BeatFreeformTests,BeatParserTests,BeatDirectionStageFreeformTests,BeatLeakScreenTests,UnreadableAnswerSponsorTests,ConversationsBeatRawEndpointTests; sharedbeatFormat/BeatPanel. Live drive:.claude/scripts/dev-verify-hybrid-beat-fallback.ps1, not yet run.) - A freeform (plain prose) beat is a beat, not a failure (owner, 2026-11-07: "make sure the beat director in hybrid supports freeform AND json - we need to support both"): it parses
Okwith no failure log or page on either key, the prose leg's note carries it verbatim (neverCharacters:), its stored twin reads back as the same beat for the extractors and the director's history, and a beat-raw edit of prose stores it freeform. An empty answer stays no beat; a broken JSON beat and one cut at the cap fall back to freeform (the line above). (Unit + stage:BeatFreeformTests,BeatDirectionStageFreeformTests,UnreadableAnswerSponsorTests,ConversationsBeatRawEndpointTests; the panel shows and edits it as one Direction text: sharedbeatFormat/BeatPaneltests. Not yet driven live against a real prose Beat Mode.) - A greeting (assistant turn with no preceding user turn) has no beat; the history interleave tolerates the missing
beat_json. - Editing a hybrid message edits the prose
contentonly; the beat is untouched (Classic-equivalent). (Correcting the beat is its own action — see The raw beat — and conversely leaves the prose untouched.)
The raw beat — always kept, and editable
Shipped 2026-09-19. The beat model's verbatim response used to be parsed into beat_json
and then discarded: BeatLlmResult.RawContent had zero consumers, so a beat the parser couldn't
structure left nothing behind but a Warning log line — the writer saw an empty panel and had no
way to find out what the director actually said, let alone fix it.
It is now persisted on every hybrid turn as web_messages.beat_raw, beside the beat_json
it was parsed into, and the chat's Story-beat panel renders and edits it.
Why it is NOT on the eval stats row. The journal and tracker evals keep their raw response on
their per-call *_eval_stats row, gated to non-ok parses by EvalRawResponse.ForStatsRow — a
diagnostics crumb for debugging model misbehaviour. That policy is deliberately not applied
here, on both halves:
- Always, not only on failure. A clean parse's raw is the source text the writer edits. Gating it would make the panel editable only on the turns the parser already failed.
- On the message, not the stats row. A stats row is an append-only per-call record with no read path on the message API and no write path at all. Nothing could show it and nothing could correct it.
The display is generic, and so is the editing. The panel shows the structured beat when
beat_json parses and falls back to the raw when it doesn't — and the owner can edit in whichever
state they are looking at, rather than one surface standing in for both:
- Per field (Characters / Environment / Plot / Situation / Portrayal) — the ordinary "the director got one thing wrong" correction. Each field maps 1:1, so nothing can be dropped or land in the wrong section. A section the director left empty still renders for the owner, quietly, so "it omitted the plot" is fixable too — an unrendered section has no affordance to reach it.
- The source — the whole verbatim text. The only way to repair a beat the parser couldn't structure at all, and the way to see exactly what the model said.
Both write through one path: the edit is serialized to text, PATCHed, reparsed server-side by
the same BeatParser the beat stage runs, and the stored pair comes back. A field edit sends the
whole beat re-serialized, never a partial patch — the server reparses whatever it is handed, so
a partial send would blank the other four. This is also why beat_raw and beat_json cannot
drift: every writer produces both from one parse.
A field edit serializes to labeled text (readable if the writer later opens the source view), with
one carve-out: the labeled-text tier requires two distinct labels — a deliberate guard so a
stray colon in prose can't masquerade as a beat — so a beat edited down to a single field is sent
as JSON instead, which has no such bar. Without that, a one-field beat would collapse wholesale
into npcs.
The beat's rendered forms became an input format. Before this, nothing typed beat text back
in, so it never mattered that the panel says Portrayal, the direction block says
How to portray it, and the parser only knew portrayal_hints. Once a human edits the beat, the
vocabulary the product shows is the vocabulary they will type — and an unknown label doesn't
error, it glues the line onto the previous section. BeatParser is now the single tolerant
boundary that accepts all of them. Treat this as a standing rule: a label printed anywhere in the
product must be readable by the parser.
Editing is a reparse, not a text swap. The writer edits the raw because that is what they were
shown, but nothing downstream reads it — journal / tracker / summary extraction and later turns'
direction block all read beat_json. So PATCH /api/conversations/{id}/messages/{messageId}/beat-raw
runs the edited text back through the same BeatParser the beat stage uses and writes the pair
atomically (fn_set_message_beat_raw_authorized). Storing only the raw would have made the
correction cosmetic; storing only the JSON would have thrown away what the writer typed. Blanking
the raw clears both — "no beat here" is a coherent state, a raw with a stale structured twin is not.
Like the tracker inline edit, it does not bump updated_at: correcting a beat is not editing
the prose.
Acceptance Criteria — raw beat
User use cases — satisfiable + accessible (verified by driving the chat, 2026-09-19):
- UC-R1 — As a writer, I can read the director's own words on a hybrid reply, from the Story-beat panel already on the bubble — including when the beat produced no structure at all, which previously rendered nothing.
- UC-R2 — As a writer, I can correct a beat from that same panel without leaving the chat, and the structured view updates from the server's answer with no reload. Two surfaces, matching the generic display: a pencil per section for the ordinary one-field fix, and a source editor for the whole verbatim text.
- UC-R4 — As a writer, I can add a section the director left out (typically Portrayal), because empty sections still render for the owner with an Add affordance.
- UC-R3 — As a writer, I can delete a beat by clearing the field; the panel disappears.
Behavior:
- Every hybrid turn persists
beat_rawverbatim — on a clean parse too, not only a degraded one. - An edit is reparsed into
beat_json, so the correction reaches every reader that reads the beat from here on — the director's next turns (since 2026-09-24, when the seeded director replays its own beat history), the journal, future summaries, and a prose-only re-render. (Corrected 2026-09-24: this line said "every downstream reader". Tracker values already recorded for that turn are not re-derived.) - A per-field edit changes only that field — the other four survive it unchanged (verified by correcting Plot and adding Portrayal in the chat, then reading the stored pair).
- A beat edited down to one field does not collapse into
npcs(single-field edits serialize as JSON, bypassing the labeled-text tier's two-label bar). - The
doneSSE frame carriesbeatRaw, so a just-streamed turn is editable without a reload. (Wire format verified in code + the frame mapping; not yet driven through a live beat call.) -
beat_rawsurvives a content edit, a version switch, and a branch — the widenedfn_update_web_message_authorized/fn_get_message_versions_authorizedreturn shapes and thefn_branch_conversationcopy. (The same omission once made the beat panel vanish after an edit;reasoning_contentandlorebook_activations_jsonwere silently missing from the branch copy and were fixed in the same pass.)
Invariants:
- Classic turns store neither half —
beat_rawstays NULL, exactly asbeat_jsondoes. (Tightened 2026-09-24: until then the beat edit could write a beat onto any row its owner could reach, including a Classic assistant turn — whose summaries would then read the pasted beat instead of the prose — or a user message.fn_set_message_beat_raw_authorizednow refuses both with22023after the owner check, answered as a 400; the chat panel never sends one.) - Only an assistant turn carries a beat — a user or system message on a Hybrid conversation is
refused by the same edit (
A story beat can only be set on an assistant message). - Every label the product prints reads back to its own field. Making the panel editable
turned the beat's rendered forms into an input format — a writer types back the vocabulary
they were shown. Three existed for the hints field and only one parsed:
Portrayal(the panel's section label) andHow to portray it(FormatDirectionBody, what the prose model receives) were both unreadable, while the prompt's ownportrayal_hintsworked. An unrecognised label doesn't fail loudly — the line is swallowed as a continuation of the previous section, so the hints silently merged intosituation, which the extractors read as story fact: the precise craft-direction-into-story-record leak this design forbids.BeatParsernow accepts all three;BeatRoundTripTestspins the round-trip field-for-field and names the leak as its own case. Adding a label anywhere in the product means adding it to the parser — the panel, the direction block and the parser share one vocabulary now. - A truncated beat cannot take the turn down with it. Both beat halves go through
TextSanitizer.SanitizeForStoragelike the prose and the reasoning trace. The beat leg is the most truncation-prone call on the turn (BeatLlmServicewarns when it stops at the output-token cap), and a completion cut mid-surrogate-pair fails the INSERT with Postgres 22021 — the same INSERT that carries the prose, so an unsanitised beat would lose the whole turn the user just watched stream, not merely the beat. (Caught in review; the reasoning trace already had this guard and the beat fields were bypassing it. The helper is nowSanitizeModelText, shared by all three.) - A beat correction does not bump
updated_at(no false "edited" indicator, no reordering). - An edit is owner-gated by the shared message access guard — a non-owner gets 403 and the stored beat is unchanged.
- The raw never enters the prose: it is a sibling column, never part of
content.
Edges:
- An empty beat response (a reasoning rail that spent its budget thinking) stores no raw rather than a whitespace one — no empty editable panel appears.
- An unparseable edit still saves; the panel shows the salvaged text rather than refusing the correction the writer is trying to make.
- A raw over 50,000 characters (
EvalRawResponse.MaxStoredChars) is refused with a 400 and nothing is written; exactly at the cap it saves. - The streaming bubble's panel is read-only — there is no stored message to edit yet.
- A turn written before
beat_rawexisted (beat_jsononly) opens its editor prefilled from the JSON, not blank — a blank editor would make the first Save a silent delete of the only copy. - A clear is recoverable where it happened. Clearing is an ordinary Save, so the panel deliberately stays mounted for the rest of the session showing "No beat on this turn. Edit to write one." rather than unmounting and taking the edit affordance with it. On the next load the message genuinely has no beat and the panel does not mount. (Both edges caught in review, then driven in the chat.)
Acceptance Criteria — prose-only regeneration
User use cases — satisfiable + accessible (verified by driving the chat, 2026-09-20):
- UC-P1 — As a writer, on a Hybrid reply I can choose between re-running the whole
turn and re-rendering just the prose, from the message menu already on the bubble.
Both entries appear in both menus — the desktop hover
•••dropdown and the touch long-press action sheet (verified at 375×812). - UC-P2 — As a writer, I can correct the director and see the correction rendered:
edit the beat in the Story-beat panel, pick Regenerate prose only, and the new prose is
written from the corrected beat. Driven end to end in the chat — the director's note in
the prose prompt carried
BEAT-CORRECTED-BY-USER…, never the original beat. - UC-P3 — As a writer, the choice is named for what it does: on a Hybrid turn the first entry reads Regenerate everything, so "Regenerate" can't be read as prose-only and silently discard a correction.
- UC-P4 — As a writer, I can see on the receipt that the beat was reused rather than re-run: the per-message Info modal shows Beat call · Reused — "Kept from the previous version — no new call this turn."
Behavior:
- A prose-only regeneration makes exactly one LLM call. Proven with the deterministic mock: one capture for the turn vs. two for Regenerate everything and three for a fresh turn (beat + prose + tracker eval).
- The prose prompt is rebuilt identically to a normal hybrid turn — same starved system block, the beat as a user-role director's note on the last user turn.
- The server decides which beat. The request carries only
regenerateMode; the beat is read from the message the regeneration will version (GetLastAssistantMessageAsync— the same read the persistence layer uses), so the two cannot diverge and the client cannot substitute beat content. - The new version row carries both
beat_jsonandbeat_raw, so the beat panel and the user's edit survive the regeneration and a later version switch. - The stored pair is carried verbatim, not re-serialized from the parse — a legacy
{ beat_text, story_state }row keepsstory_stateinstead of silently losing it. - Both
web_message_statsrows are still written; thehybrid-beatrow carriescall_reused = TRUEwith NULL provider/model/tokens/latency, and its compute line settles to 0 (reserved then skipped) rather than dangling.
Invariants that must stay true (carve-outs a reviewer can break if regressed):
- Classic is untouched. A Classic turn's menu shows exactly one Regenerate and no prose-only entry (verified by driving a Classic conversation), and nothing else about the turn changes.
- A normal Hybrid regeneration is unchanged —
regenerateModeabsent or"full"re-runs both legs, writes ahybrid-beatrow withcall_reused = FALSEand real telemetry, and replaces the beat. - A prose-only regen still counts as a regeneration.
event_typestays'regenerate'on both rows, so the regen-rate analytics bucket and the info modal's "Regeneration" label are unaffected — the reuse marker is its own column, never a thirdevent_typevalue. - The beat row is never silently absent. The two-rows-per-hybrid-turn shape holds on every
hybrid turn including this one; a missing telemetry payload still writes the row (the reuse
flag, not telemetry nullness, is the discriminator — pinned by
WebMessageStatsStageTests). -
beat_directionkeeps its factory key and the Hybrid pre-stage set is unchanged — the reuse branches inside the stage, so the pipeline-disabling trap that key guards is untouched.
Edges:
- Prose-only on a Classic conversation → 400 "This conversation has no story beat to re-render." before the stream opens.
- Prose-only without
isRegeneration→ 400 "Re-rendering the prose only applies to a regeneration." - Prose-only on a turn whose beat was cleared → 400 naming the way forward ("…Regenerate the whole turn instead.").
- An unknown
regenerateMode→ 400, never a silent fall-back to a full regeneration (which would be the discarded-correction this feature exists to prevent).
Related documents
- Trackers — the "separate the bookkeeping from the prose" north-star and the user-role injection principle this pipeline reuses.
- Journal — the eval-pass infrastructure the beat stage mirrors; the state the beat model reasons over.
- Model Profiles / Model Profile Base Prompts & Flavors — the composition layer future role-tagged Profiles extend.
- Hosted Inference via Featherless — the open-weight prose rail and its moderation gate.
- Manifesto — why "authentic over comfort" is a craft value and where the hard limits sit.