Give the adventure a persona, so the protagonist has a name
The player had stats but no identity. `stat_schema.player` carried hp and
mana beside `npc.gwen.trust`, but where an NPC has a name and a
description the player had neither, so the block rendered as
`You: hp 100/100` and nothing in the prompt said who "you" was.
Three columns on `adventures`: name, pronouns, description. All
user-only, all optional, and an empty name means the app behaves exactly
as it did before — no backfill, no special case for an adventure that
predates the migration.
They are adventure columns rather than part of `stat_schema` for two
reasons. An adventure with no RPG layer still has a protagonist, and
that is the case this was added for. And `worldstate.schema._initials`
treats every dict inside a stat section as a stat definition, so a
persona placed there would be instantiated, rendered in the guide, and
handed an `initial` value as though it were one.
The paths do not change. `player.hp` stays `player.hp`; only the label
moves, to `Kaelen (player): hp 100/100`, the same way NPC lines already
print a display name beside the id. A path carrying the persona's name
would break the moment a player renamed their character, because
`_history_text` replays every past turn's stored delta into the prompt
and those blobs hold literal `player.hp` strings.
The section sits in the system block. Only the user can edit it, so it
never changes mid-story and stays inside the cached prefix. That is what
makes it free, and it is why the AI must not be able to move it — a
delta aimed at `persona.*` is already refused by `_resolve`, and there
is now a test holding that in place.
The modal that used to appear only for scenarios with `${Placeholder}`
tokens now always opens, and is where the character is named. Persona
and placeholders stay independent: a scenario asking for `${Name}` is
asking its own question. No scenario in the repo uses placeholders at
all, so the overlap is hypothetical.
Phase 2, which feeds the persona and the cast to the summarizer, is
written up in plan/18 and not started. That is where the memory-quality
problem actually gets fixed; this change is what gives it a name to use.
Not yet driven in a browser — plan/18 lists what to check by hand.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NPyQN926gkZTAYfgugcaok
This commit is contained in:
@@ -101,6 +101,14 @@ def export(db: Session, adventure: models.Adventure) -> dict:
|
||||
"authorsNote": adventure.authors_note,
|
||||
"aiInstructions": adventure.ai_instructions,
|
||||
"storySummary": adventure.story_summary,
|
||||
# Phase 18. A bundle written before personas existed has no key here,
|
||||
# and the import below reads it with `.get`, so it lands with an empty
|
||||
# persona — which is the same as having none. No FORMAT bump needed.
|
||||
"persona": {
|
||||
"name": adventure.persona_name,
|
||||
"pronouns": adventure.persona_pronouns,
|
||||
"desc": adventure.persona_desc,
|
||||
},
|
||||
"scriptState": adventure.script_state,
|
||||
"worldState": adventure.world_state,
|
||||
"autoSummarize": adventure.auto_summarize,
|
||||
@@ -194,6 +202,24 @@ def _exported_memory(memory: models.Memory, local: dict[int, int]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _imported_persona(persona) -> dict:
|
||||
"""Reads a bundle's `persona` block into `Adventure` keyword arguments.
|
||||
|
||||
A raw-dict import bypasses the schemas, so the strings are truncated to the
|
||||
widths the columns declare, in the same way the rest of `_import` does. A
|
||||
bundle written before Phase 18 has no block at all, and an empty persona is
|
||||
the same as having none.
|
||||
"""
|
||||
if not isinstance(persona, dict):
|
||||
return {}
|
||||
return {
|
||||
"persona_name": str(persona.get("name") or "")[:schemas.PERSONA_NAME_MAX],
|
||||
"persona_pronouns":
|
||||
str(persona.get("pronouns") or "")[:schemas.PERSONA_PRONOUNS_MAX],
|
||||
"persona_desc": str(persona.get("desc") or ""),
|
||||
}
|
||||
|
||||
|
||||
def _exported_anchor(
|
||||
adventure: models.Adventure, cursor: cursors.Cursor, local: dict[int, int]
|
||||
) -> dict:
|
||||
@@ -632,6 +658,7 @@ def materialize(
|
||||
world_state=payload.get("worldState") or {},
|
||||
auto_summarize=bool(payload.get("autoSummarize", False)),
|
||||
memory_bank_enabled=bool(payload.get("memoryBankEnabled", False)),
|
||||
**_imported_persona(payload.get("persona")),
|
||||
)
|
||||
db.add(adventure)
|
||||
db.flush()
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from . import history
|
||||
from .builder import build_context, count_tokens, truncate_to_last_tokens
|
||||
from .builder import build_context, count_tokens, render_persona, truncate_to_last_tokens
|
||||
from .history import story_actions
|
||||
|
||||
__all__ = [
|
||||
"build_context",
|
||||
"count_tokens",
|
||||
"history",
|
||||
"render_persona",
|
||||
"story_actions",
|
||||
"truncate_to_last_tokens",
|
||||
]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
(help.aidungeon.com/faq/the-memory-system):
|
||||
|
||||
[AI Instructions] always included
|
||||
[Player Character] always included when the adventure has a persona
|
||||
[Plot Essentials] always included (classic "Memory")
|
||||
[Story Summary] always included (manual in Phase 3, auto in Phase 6)
|
||||
[Used Memories] top-K memory-bank retrievals (Phase 6, when enabled)
|
||||
@@ -130,6 +131,30 @@ def length_hint(max_output_tokens: int, *, has_ws: bool) -> str:
|
||||
)
|
||||
|
||||
|
||||
def render_persona(adventure: models.Adventure) -> str:
|
||||
"""Returns the Player Character section, or "" when there is no persona.
|
||||
|
||||
The three fields are independent. A name alone is enough, a description
|
||||
alone is enough, and the wording holds together for either. Pronouns are
|
||||
stated because the summarizer in `memorybank` writes about the protagonist
|
||||
in the third person, and a model that has to infer a pronoun from a name
|
||||
will sometimes infer wrongly and then repeat that error in every memory it
|
||||
writes.
|
||||
"""
|
||||
name = adventure.persona_name.strip()
|
||||
pronouns = adventure.persona_pronouns.strip()
|
||||
desc = adventure.persona_desc.strip()
|
||||
if not (name or desc):
|
||||
return ""
|
||||
head = f"You are {name}" if name else ""
|
||||
if head and pronouns:
|
||||
head += f" ({pronouns})"
|
||||
# Joined with a space, not `SEPARATOR`: this is one short paragraph about
|
||||
# one character, and a blank line inside it reads as two unrelated notes.
|
||||
body = " ".join(part for part in (f"{head}." if head else "", desc) if part)
|
||||
return f"Player character:\n{body}"
|
||||
|
||||
|
||||
def _script_memory(adventure: models.Adventure) -> dict:
|
||||
"""Script-provided memory overrides (populated by Phase 4 scripting)."""
|
||||
state = adventure.script_state if isinstance(adventure.script_state, dict) else {}
|
||||
@@ -228,8 +253,9 @@ def build_context(
|
||||
# schema and the emit rule do not change while the scenario is unchanged.
|
||||
stat_schema = adventure.scenario.stat_schema if adventure.scenario else None
|
||||
has_ws = worldstate.has_schema(stat_schema)
|
||||
persona_name = adventure.persona_name.strip()
|
||||
if has_ws:
|
||||
guide = worldstate.render_reference(stat_schema)
|
||||
guide = worldstate.render_reference(stat_schema, persona_name)
|
||||
if guide:
|
||||
system_sections.append(Section("world_state_guide", guide))
|
||||
system_sections.append(Section("world_state_rule", worldstate.EMIT_RULE))
|
||||
@@ -238,6 +264,14 @@ def build_context(
|
||||
system_sections.append(Section("script_context", script_mem["context"].strip()))
|
||||
if adventure.ai_instructions.strip():
|
||||
system_sections.append(Section("ai_instructions", adventure.ai_instructions.strip()))
|
||||
# Phase 18. This sits in the static block because only the user can edit it,
|
||||
# so it never changes mid-story and stays inside the cached prefix. It is
|
||||
# emitted whether or not the adventure has an RPG layer: an adventure with
|
||||
# no stats still has a protagonist, and that is the case the persona was
|
||||
# added for.
|
||||
persona_text = render_persona(adventure)
|
||||
if persona_text:
|
||||
system_sections.append(Section("persona", persona_text))
|
||||
if adventure.memory.strip():
|
||||
system_sections.append(
|
||||
Section("plot_essentials", f"Plot essentials:\n{adventure.memory.strip()}")
|
||||
@@ -267,6 +301,7 @@ def build_context(
|
||||
recent = history.tail(adventure, NPC_WINDOW, exclude_action_id)
|
||||
block = worldstate.render_state_section(
|
||||
adventure.world_state, stat_schema, _visible_npcs(recent, stat_schema),
|
||||
persona_name,
|
||||
)
|
||||
if block:
|
||||
world_state_section = Section("world_state", block)
|
||||
|
||||
@@ -332,6 +332,12 @@ MIGRATIONS: list[tuple[int, str | dict[str, str]]] = [
|
||||
(71, 'ALTER TABLE actions DROP COLUMN "index"'),
|
||||
(72, "ALTER TABLE adventures DROP COLUMN memory_cursor"),
|
||||
(73, "ALTER TABLE adventures DROP COLUMN summary_cursor"),
|
||||
# Phase 18: the persona. Defaulting to '' rather than NULL means every read
|
||||
# is a plain string test, and an adventure that predates the feature is
|
||||
# indistinguishable from one whose player left the fields blank.
|
||||
(74, "ALTER TABLE adventures ADD COLUMN persona_name VARCHAR(80) NOT NULL DEFAULT ''"),
|
||||
(75, "ALTER TABLE adventures ADD COLUMN persona_pronouns VARCHAR(40) NOT NULL DEFAULT ''"),
|
||||
(76, "ALTER TABLE adventures ADD COLUMN persona_desc TEXT NOT NULL DEFAULT ''"),
|
||||
]
|
||||
|
||||
LATEST_VERSION = max((v for v, _ in MIGRATIONS), default=1)
|
||||
|
||||
@@ -107,6 +107,20 @@ class Adventure(Base):
|
||||
authors_note: Mapped[str] = mapped_column(Text, default="")
|
||||
ai_instructions: Mapped[str] = mapped_column(Text, default="")
|
||||
story_summary: Mapped[str] = mapped_column(Text, default="")
|
||||
# Phase 18: who the player is playing as. The AI never writes these — they
|
||||
# are user-only, which is what lets them sit in the cached system block
|
||||
# rather than below the history with the values that change. An empty
|
||||
# `persona_name` means the adventure has no persona, and every read below
|
||||
# falls back to the wording used before this existed.
|
||||
#
|
||||
# These are adventure columns rather than part of the scenario's
|
||||
# `stat_schema`, for two reasons. An adventure with no RPG layer still has a
|
||||
# protagonist, and `worldstate.schema._initials` treats every dict inside a
|
||||
# stat section as a stat definition, so a persona placed there would be
|
||||
# instantiated, rendered and given an `initial` value as though it were one.
|
||||
persona_name: Mapped[str] = mapped_column(String(80), default="")
|
||||
persona_pronouns: Mapped[str] = mapped_column(String(40), default="")
|
||||
persona_desc: Mapped[str] = mapped_column(Text, default="")
|
||||
script_state: Mapped[dict] = mapped_column(JSON, default=dict)
|
||||
# Phase 12: live RPG world state (world/player/npc stats + milestones),
|
||||
# instantiated from the scenario's stat_schema. Empty when there's no RPG layer.
|
||||
|
||||
@@ -178,6 +178,12 @@ def create_adventure(
|
||||
# Stored so that a later "Update from scenario" fills the copied text
|
||||
# with the same answers instead of inserting literal `${...}` tokens.
|
||||
placeholders=dict(values),
|
||||
# Phase 18: the persona the player named before starting. It belongs to
|
||||
# the adventure rather than the scenario, so nothing is copied here and
|
||||
# "Update from scenario" never touches it.
|
||||
persona_name=payload.persona_name.strip(),
|
||||
persona_pronouns=payload.persona_pronouns.strip(),
|
||||
persona_desc=payload.persona_desc.strip(),
|
||||
)
|
||||
db.add(adventure)
|
||||
db.flush()
|
||||
|
||||
@@ -24,6 +24,8 @@ MEMORY_TEXT_MAX = 5_000
|
||||
IMAGE_MAX = 400_000
|
||||
ICON_MAX = 16 # One emoji or glyph. VARCHAR(16).
|
||||
BRANCH_NAME_MAX = 80 # What a player called one line of the story. VARCHAR(80).
|
||||
PERSONA_NAME_MAX = 80 # The protagonist's name. VARCHAR(80).
|
||||
PERSONA_PRONOUNS_MAX = 40 # "they/them" and the like. VARCHAR(40).
|
||||
|
||||
Name = Annotated[str, Field(max_length=NAME_MAX)]
|
||||
Tags = Annotated[str, Field(max_length=TAGS_MAX)]
|
||||
@@ -33,6 +35,8 @@ ScriptSource = Annotated[str, Field(max_length=SCRIPT_MAX)]
|
||||
ActionText = Annotated[str, Field(max_length=ACTION_MAX)]
|
||||
Image = Annotated[str, Field(max_length=IMAGE_MAX)]
|
||||
Icon = Annotated[str, Field(max_length=ICON_MAX)]
|
||||
PersonaName = Annotated[str, Field(max_length=PERSONA_NAME_MAX)]
|
||||
PersonaPronouns = Annotated[str, Field(max_length=PERSONA_PRONOUNS_MAX)]
|
||||
|
||||
|
||||
class ORMModel(BaseModel):
|
||||
@@ -141,6 +145,12 @@ class AdventureCreate(BaseModel):
|
||||
# The `${Placeholder}` values collected from the player at the start, which
|
||||
# is the AI Dungeon behavior.
|
||||
placeholders: dict[str, str] = {}
|
||||
# Phase 18: who the player is playing as, collected by the same modal. These
|
||||
# are independent of `placeholders`: a scenario that asks for `${Name}` is
|
||||
# asking its own question, and nothing here fills it in.
|
||||
persona_name: PersonaName = ""
|
||||
persona_pronouns: PersonaPronouns = ""
|
||||
persona_desc: Prose = ""
|
||||
|
||||
|
||||
class AdventureUpdate(BaseModel):
|
||||
@@ -151,6 +161,9 @@ class AdventureUpdate(BaseModel):
|
||||
story_summary: Prose | None = None
|
||||
auto_summarize: bool | None = None
|
||||
memory_bank_enabled: bool | None = None
|
||||
persona_name: PersonaName | None = None
|
||||
persona_pronouns: PersonaPronouns | None = None
|
||||
persona_desc: Prose | None = None
|
||||
|
||||
|
||||
class AdventureRefresh(BaseModel):
|
||||
@@ -297,6 +310,9 @@ class AdventureOut(ORMModel):
|
||||
story_summary: str
|
||||
auto_summarize: bool
|
||||
memory_bank_enabled: bool
|
||||
persona_name: str
|
||||
persona_pronouns: str
|
||||
persona_desc: str
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
story_cards: list[StoryCardOut] = []
|
||||
|
||||
@@ -25,11 +25,16 @@ def _stat_line(defs: dict, values: dict) -> str:
|
||||
|
||||
|
||||
def render_state_section(world_state: dict, stat_schema: dict,
|
||||
visible_npcs: dict[str, str]) -> str:
|
||||
visible_npcs: dict[str, str],
|
||||
player_name: str = "") -> str:
|
||||
"""Returns the compact context block that every turn includes.
|
||||
|
||||
`visible_npcs` maps a card id to a display name, for the NPCs currently in
|
||||
the scene.
|
||||
|
||||
`player_name` is the persona's name (Phase 18), used to label the player's
|
||||
stat block. It is empty for an adventure with no persona, and the block then
|
||||
reads `You:` as it did before personas existed.
|
||||
"""
|
||||
ws = world_state if isinstance(world_state, dict) else {}
|
||||
lines: list[str] = []
|
||||
@@ -42,7 +47,12 @@ def render_state_section(world_state: dict, stat_schema: dict,
|
||||
player_defs = stat_schema.get("player") or {}
|
||||
player_line = _stat_line(player_defs, ws.get("player") or {})
|
||||
if player_line:
|
||||
lines.append(f"You: {player_line}.")
|
||||
# Name the block after the persona, and show the path beside it exactly
|
||||
# as the NPC lines below do. The model reads the name in the narration,
|
||||
# so without the path in view it writes `kaelen.hp` and the delta is
|
||||
# refused as an unknown path.
|
||||
label = f"{player_name} (player)" if player_name else "You"
|
||||
lines.append(f"{label}: {player_line}.")
|
||||
|
||||
npcs = stat_schema.get("npcs") or {}
|
||||
npc_state = ws.get("npc") or {}
|
||||
@@ -122,14 +132,24 @@ def _describe_stat(name: str, d: dict) -> str | None:
|
||||
return f"{label} — {'; '.join(bits)}." if bits else None
|
||||
|
||||
|
||||
def render_reference(stat_schema: dict) -> str:
|
||||
def render_reference(stat_schema: dict, player_name: str = "") -> str:
|
||||
"""Returns a fixed, per-scenario legend for the stats.
|
||||
|
||||
Each line gives what a stat means, from its `desc`, and its band ladder. The
|
||||
legend does not change from turn to turn, and it is separate from the live
|
||||
values.
|
||||
|
||||
`player_name` names the persona, so that the guide ties the name the model
|
||||
reads in the story to the `player.` paths it has to write. The persona's
|
||||
description is deliberately not repeated here: it has its own section, and
|
||||
this guide is about paths.
|
||||
"""
|
||||
lines: list[str] = []
|
||||
if player_name:
|
||||
lines.append(
|
||||
f"Protagonist {player_name} — the player character; their stats are "
|
||||
f"addressed as player.<stat>."
|
||||
)
|
||||
for section in STAT_SECTIONS:
|
||||
for name, d in (stat_schema.get(section) or {}).items():
|
||||
if isinstance(d, dict):
|
||||
|
||||
Reference in New Issue
Block a user