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):
|
||||
|
||||
@@ -586,3 +586,50 @@ def test_an_unknown_format_is_refused(client):
|
||||
r = _import(client, {"format": "ai-dnd-adventure-v3", "title": "From the future"})
|
||||
assert r.status_code == 400, r.text
|
||||
assert bundle.FORMAT in r.json()["detail"]
|
||||
|
||||
|
||||
# ------------------------------------------------------- the persona (Phase 18)
|
||||
|
||||
def test_the_persona_survives_the_round_trip(client):
|
||||
adv_id = client.adv_id
|
||||
assert client.patch(f"/api/adventures/{adv_id}", json={
|
||||
"persona_name": "Kaelen",
|
||||
"persona_pronouns": "he/him",
|
||||
"persona_desc": "A half-elf ranger, exiled from the northern holds.",
|
||||
}).status_code == 200
|
||||
|
||||
payload = _export(client, adv_id)
|
||||
assert payload["persona"] == {
|
||||
"name": "Kaelen",
|
||||
"pronouns": "he/him",
|
||||
"desc": "A half-elf ranger, exiled from the northern holds.",
|
||||
}
|
||||
|
||||
copy_id = _imported(client, payload)
|
||||
r = client.get(f"/api/adventures/{copy_id}")
|
||||
assert r.status_code == 200, r.text
|
||||
copy = r.json()
|
||||
assert copy["persona_name"] == "Kaelen"
|
||||
assert copy["persona_pronouns"] == "he/him"
|
||||
assert copy["persona_desc"].startswith("A half-elf ranger")
|
||||
|
||||
|
||||
def test_a_bundle_written_before_personas_still_imports(client):
|
||||
"""The key is read with `.get`, so a v2 file from before Phase 18 lands
|
||||
with an empty persona rather than failing. No FORMAT bump was needed."""
|
||||
payload = _export(client, client.adv_id)
|
||||
del payload["persona"]
|
||||
copy = client.get(f"/api/adventures/{_imported(client, payload)}").json()
|
||||
assert copy["persona_name"] == ""
|
||||
assert copy["persona_pronouns"] == ""
|
||||
assert copy["persona_desc"] == ""
|
||||
|
||||
|
||||
def test_an_over_long_persona_in_a_raw_bundle_is_truncated(client):
|
||||
"""A raw-dict import bypasses the schemas, so the widths the columns
|
||||
declare are enforced here instead. Postgres would reject the INSERT."""
|
||||
payload = _export(client, client.adv_id)
|
||||
payload["persona"] = {"name": "K" * 500, "pronouns": "p" * 500, "desc": "d"}
|
||||
copy = client.get(f"/api/adventures/{_imported(client, payload)}").json()
|
||||
assert len(copy["persona_name"]) == 80
|
||||
assert len(copy["persona_pronouns"]) == 40
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
"""Phase 18: the adventure's persona — who the player is playing as.
|
||||
|
||||
Before this existed the protagonist had no name anywhere in the prompt. The
|
||||
player's stat block rendered as `You: hp 100/100` and the summarizer was handed
|
||||
second-person prose with nothing to say who "you" was.
|
||||
|
||||
The rules this file holds in place:
|
||||
|
||||
* An empty `persona_name` behaves exactly as the app did before personas
|
||||
existed, so an adventure that predates the migration is not a special case.
|
||||
* The persona is in the **system** block. It is user-only, so it never changes
|
||||
during a story, and putting it in the cached prefix is what makes it free.
|
||||
* A persona works without an RPG layer. That is the case it was added for.
|
||||
* Naming the block does not rename the path. The model still writes
|
||||
`player.hp`, and a delta aimed at `persona.*` is refused.
|
||||
|
||||
python -m pytest tests/test_persona.py -v
|
||||
"""
|
||||
import pytest
|
||||
from fastapi import Depends
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import auth, limits, models, worldstate
|
||||
from app.context import builder
|
||||
from app.database import Base, SessionLocal, engine, get_db
|
||||
from app.main import app
|
||||
|
||||
SCHEMA = {
|
||||
"player": {"hp": {"min": 0, "max": 100, "initial": 100, "desc": "Health"}},
|
||||
"world": {"day": {"min": 1, "initial": 1, "desc": "Day"}},
|
||||
}
|
||||
|
||||
|
||||
def _persona(**kwargs) -> models.Adventure:
|
||||
"""An unsaved adventure carrying only the fields `render_persona` reads."""
|
||||
return models.Adventure(
|
||||
persona_name=kwargs.get("name", ""),
|
||||
persona_pronouns=kwargs.get("pronouns", ""),
|
||||
persona_desc=kwargs.get("desc", ""),
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------- the rendering
|
||||
|
||||
def test_no_persona_renders_nothing():
|
||||
assert builder.render_persona(_persona()) == ""
|
||||
|
||||
|
||||
def test_whitespace_only_is_the_same_as_empty():
|
||||
"""The columns default to '', but a player can clear a field to spaces."""
|
||||
assert builder.render_persona(_persona(name=" ", pronouns=" ", desc="\n")) == ""
|
||||
|
||||
|
||||
def test_name_and_pronouns_and_description():
|
||||
text = builder.render_persona(
|
||||
_persona(name="Kaelen", pronouns="he/him", desc="A half-elf ranger.")
|
||||
)
|
||||
assert text.startswith("Player character:\n")
|
||||
assert "You are Kaelen (he/him)." in text
|
||||
assert "A half-elf ranger." in text
|
||||
|
||||
|
||||
def test_name_alone_is_enough():
|
||||
text = builder.render_persona(_persona(name="Kaelen"))
|
||||
assert "You are Kaelen." in text
|
||||
assert "(" not in text, "no empty pronoun bracket"
|
||||
|
||||
|
||||
def test_description_alone_is_enough():
|
||||
"""A player who names no character still gets their description through."""
|
||||
text = builder.render_persona(_persona(desc="A nameless wanderer."))
|
||||
assert "A nameless wanderer." in text
|
||||
assert "You are" not in text
|
||||
|
||||
|
||||
# ---------------------------------------------------- the world-state labels
|
||||
|
||||
def test_state_section_labels_the_block_with_the_name():
|
||||
state = worldstate.instantiate(SCHEMA)
|
||||
block = worldstate.render_state_section(state, SCHEMA, {}, "Kaelen")
|
||||
# The path travels with the name. Without it the model reads "Kaelen" in
|
||||
# the prose and writes `kaelen.hp`, which `apply_delta` then refuses.
|
||||
assert "Kaelen (player): hp 100/100" in block
|
||||
|
||||
|
||||
def test_state_section_falls_back_to_you():
|
||||
state = worldstate.instantiate(SCHEMA)
|
||||
block = worldstate.render_state_section(state, SCHEMA, {}, "")
|
||||
assert "You: hp 100/100" in block
|
||||
assert "(player)" not in block
|
||||
|
||||
|
||||
def test_reference_ties_the_name_to_the_path():
|
||||
guide = worldstate.render_reference(SCHEMA, "Kaelen")
|
||||
assert "Protagonist Kaelen" in guide
|
||||
assert "player.<stat>" in guide
|
||||
|
||||
|
||||
def test_reference_without_a_persona_is_unchanged():
|
||||
assert "Protagonist" not in worldstate.render_reference(SCHEMA, "")
|
||||
|
||||
|
||||
def test_reference_does_not_repeat_the_description():
|
||||
"""The description has its own section. The guide is about paths."""
|
||||
guide = worldstate.render_reference(SCHEMA, "Kaelen")
|
||||
assert "half-elf" not in guide
|
||||
|
||||
|
||||
# ------------------------------------------------------ the assembled prompt
|
||||
|
||||
@pytest.fixture()
|
||||
def story():
|
||||
"""An adventure with an RPG layer, a persona, and a little history."""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
db = SessionLocal()
|
||||
user = models.User(is_guest=False, email="persona@example.com")
|
||||
db.add(user)
|
||||
db.flush()
|
||||
settings = models.Settings(user_id=user.id, api_key="enc:dummy", model="m")
|
||||
db.add(settings)
|
||||
scenario = models.Scenario(
|
||||
user_id=user.id, title="S", prompt="A road.", stat_schema=SCHEMA
|
||||
)
|
||||
db.add(scenario)
|
||||
db.flush()
|
||||
adventure = models.Adventure(
|
||||
user_id=user.id, title="A", scenario_id=scenario.id, script_state={},
|
||||
memory="The hero hunts bandits.",
|
||||
ai_instructions="Write in second person.",
|
||||
story_summary="The hero left the village.",
|
||||
world_state=worldstate.instantiate(SCHEMA),
|
||||
persona_name="Kaelen",
|
||||
persona_pronouns="he/him",
|
||||
persona_desc="A half-elf ranger, exiled from the northern holds.",
|
||||
)
|
||||
db.add(adventure)
|
||||
db.flush()
|
||||
for i in range(6):
|
||||
db.add(models.Action(adventure_id=adventure.id,
|
||||
type="ai" if i % 2 else "do",
|
||||
text=f"[{i}] The road bends onward past the treeline."))
|
||||
db.commit()
|
||||
db.expire_all()
|
||||
adventure = db.get(models.Adventure, adventure.id)
|
||||
settings = db.get(models.Settings, settings.id)
|
||||
try:
|
||||
yield db, adventure, settings
|
||||
finally:
|
||||
db.close()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
def test_persona_is_in_the_system_block(story):
|
||||
"""It is user-only, so it belongs in the cached prefix rather than below
|
||||
the history with the values that move."""
|
||||
db, adventure, settings = story
|
||||
system_text, story_text, _ = builder.build_context(adventure, settings)
|
||||
assert "You are Kaelen (he/him)." in system_text
|
||||
assert "A half-elf ranger" in system_text
|
||||
assert "Kaelen (he/him)" not in story_text
|
||||
|
||||
|
||||
def test_persona_does_not_move_between_turns(story):
|
||||
"""The static block has to be byte-identical across turns. A persona that
|
||||
changed with the world state would re-price the whole history."""
|
||||
db, adventure, settings = story
|
||||
before, _, _ = builder.build_context(adventure, settings)
|
||||
adventure.world_state = {**adventure.world_state, "player": {"hp": 40}}
|
||||
db.commit()
|
||||
after, story_text, _ = builder.build_context(adventure, settings)
|
||||
assert before == after
|
||||
assert "Kaelen (player): hp 40/100" in story_text
|
||||
|
||||
|
||||
def test_persona_sits_above_the_plot_essentials(story):
|
||||
db, adventure, settings = story
|
||||
_, _, report = builder.build_context(adventure, settings)
|
||||
labels = [s["label"] for s in report["sections"]]
|
||||
assert labels.index("persona") < labels.index("plot_essentials")
|
||||
|
||||
|
||||
def test_no_persona_section_when_the_fields_are_blank(story):
|
||||
db, adventure, settings = story
|
||||
adventure.persona_name = ""
|
||||
adventure.persona_pronouns = ""
|
||||
adventure.persona_desc = ""
|
||||
db.commit()
|
||||
system_text, story_text, report = builder.build_context(adventure, settings)
|
||||
assert "persona" not in [s["label"] for s in report["sections"]]
|
||||
assert "Player character" not in system_text
|
||||
assert "You: hp 100/100" in story_text
|
||||
|
||||
|
||||
def test_persona_is_charged_to_the_token_budget(story):
|
||||
"""It moved into `system_sections`, and everything there is counted in
|
||||
`reserved`. If it were not, the history would overrun the budget."""
|
||||
db, adventure, settings = story
|
||||
_, _, report = builder.build_context(adventure, settings)
|
||||
persona = next(s for s in report["sections"] if s["label"] == "persona")
|
||||
assert persona["tokens"] > 0
|
||||
assert report["tokens"]["total"] >= persona["tokens"]
|
||||
|
||||
|
||||
# --------------------------------------------- a persona with no RPG layer
|
||||
|
||||
@pytest.fixture()
|
||||
def plain():
|
||||
"""A blank adventure: no scenario, so no `stat_schema` at all."""
|
||||
Base.metadata.create_all(bind=engine)
|
||||
db = SessionLocal()
|
||||
user = models.User(is_guest=False, email="plain@example.com")
|
||||
db.add(user)
|
||||
db.flush()
|
||||
settings = models.Settings(user_id=user.id, api_key="enc:dummy", model="m")
|
||||
db.add(settings)
|
||||
adventure = models.Adventure(
|
||||
user_id=user.id, title="A", script_state={}, world_state={},
|
||||
persona_name="Wren", persona_pronouns="they/them",
|
||||
persona_desc="A courier who reads other people's letters.",
|
||||
)
|
||||
db.add(adventure)
|
||||
db.flush()
|
||||
db.add(models.Action(adventure_id=adventure.id, type="do", text="Walk east."))
|
||||
db.commit()
|
||||
db.expire_all()
|
||||
adventure = db.get(models.Adventure, adventure.id)
|
||||
settings = db.get(models.Settings, settings.id)
|
||||
try:
|
||||
yield db, adventure, settings
|
||||
finally:
|
||||
db.close()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
def test_persona_works_without_an_rpg_layer(plain):
|
||||
"""The case the persona exists for. It must not be gated behind `has_ws`."""
|
||||
db, adventure, settings = plain
|
||||
system_text, _, _ = builder.build_context(adventure, settings)
|
||||
assert "You are Wren (they/them)." in system_text
|
||||
assert "A courier who reads other people's letters." in system_text
|
||||
|
||||
|
||||
# ------------------------------------------------- the AI cannot rewrite it
|
||||
|
||||
@pytest.mark.parametrize("path", ["persona.name", "persona.desc", "persona"])
|
||||
def test_a_delta_aimed_at_the_persona_is_refused(path):
|
||||
"""Nothing was built for this: `_resolve` rejects unknown paths already.
|
||||
The test holds the behavior in place, because the persona sitting in the
|
||||
cached prefix depends on the model being unable to move it."""
|
||||
state = worldstate.instantiate(SCHEMA)
|
||||
_, report = worldstate.apply_delta(state, SCHEMA, {path: "Bob"}, 1)
|
||||
assert [r["path"] for r in report["rejected"]] == [path]
|
||||
assert not report["applied"]
|
||||
|
||||
|
||||
def test_the_player_path_still_works_with_a_persona_set():
|
||||
"""Naming the block does not rename the path."""
|
||||
state = worldstate.instantiate(SCHEMA)
|
||||
new_state, report = worldstate.apply_delta(state, SCHEMA, {"player.hp": -15}, 1)
|
||||
assert new_state["player"]["hp"] == 85
|
||||
assert [r["path"] for r in report["applied"]] == ["player.hp"]
|
||||
|
||||
|
||||
# ------------------------------------- setting it at the start, editing it later
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
setup = SessionLocal()
|
||||
user = models.User(is_guest=False, email="persona-api@example.com")
|
||||
setup.add(user)
|
||||
setup.flush()
|
||||
setup.add(models.Settings(user_id=user.id, api_key="enc:dummy", model="test-model"))
|
||||
setup.commit()
|
||||
user_id = user.id
|
||||
setup.close()
|
||||
|
||||
monkeypatch.setattr(limits, "rate_limit", lambda *a, **k: None)
|
||||
monkeypatch.setattr(limits, "check_row_cap", lambda *a, **k: None)
|
||||
|
||||
def _current_user(db=Depends(get_db)):
|
||||
return db.get(models.User, user_id)
|
||||
|
||||
app.dependency_overrides[auth.get_current_user] = _current_user
|
||||
c = TestClient(app)
|
||||
try:
|
||||
yield c
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
def test_a_persona_can_be_named_when_the_adventure_is_created(client):
|
||||
"""The modal that used to appear only for `${Placeholder}` scenarios now
|
||||
always opens, and this is what it posts."""
|
||||
r = client.post("/api/adventures", json={
|
||||
"title": "A", "persona_name": "Kaelen", "persona_pronouns": "he/him",
|
||||
"persona_desc": "A half-elf ranger.",
|
||||
})
|
||||
assert r.status_code == 201, r.text
|
||||
body = r.json()
|
||||
assert body["persona_name"] == "Kaelen"
|
||||
assert body["persona_pronouns"] == "he/him"
|
||||
assert body["persona_desc"] == "A half-elf ranger."
|
||||
|
||||
|
||||
def test_creating_without_a_persona_still_works(client):
|
||||
"""Every field is optional. A blank adventure is the old behavior."""
|
||||
r = client.post("/api/adventures", json={"title": "A"})
|
||||
assert r.status_code == 201, r.text
|
||||
assert r.json()["persona_name"] == ""
|
||||
|
||||
|
||||
def test_the_persona_is_stripped_on_the_way_in(client):
|
||||
r = client.post("/api/adventures", json={
|
||||
"title": "A", "persona_name": " Kaelen ", "persona_desc": " ranger \n",
|
||||
})
|
||||
assert r.json()["persona_name"] == "Kaelen"
|
||||
assert r.json()["persona_desc"] == "ranger"
|
||||
|
||||
|
||||
def test_the_persona_can_be_edited_later(client):
|
||||
"""A player renames their character mid-story; nothing else moves."""
|
||||
adv_id = client.post("/api/adventures", json={
|
||||
"title": "A", "persona_name": "Kaelen",
|
||||
}).json()["id"]
|
||||
r = client.patch(f"/api/adventures/{adv_id}", json={"persona_name": "Aria"})
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["persona_name"] == "Aria"
|
||||
assert client.get(f"/api/adventures/{adv_id}").json()["persona_name"] == "Aria"
|
||||
|
||||
|
||||
def test_an_over_long_name_is_refused_rather_than_truncated(client):
|
||||
"""The column is VARCHAR(80). A 422 here is a 500 at INSERT otherwise."""
|
||||
r = client.post("/api/adventures", json={"title": "A", "persona_name": "K" * 81})
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
def test_placeholders_and_the_persona_are_independent(client):
|
||||
"""A scenario asking for `${Name}` is asking its own question. Nothing
|
||||
fills it in from the persona, and nothing fills the persona from it."""
|
||||
db = SessionLocal()
|
||||
scenario = models.Scenario(
|
||||
user_id=db.query(models.User).first().id,
|
||||
title="S", prompt="A guard sneers at ${Name}.",
|
||||
)
|
||||
db.add(scenario)
|
||||
db.commit()
|
||||
scenario_id = scenario.id
|
||||
db.close()
|
||||
|
||||
adv = client.post("/api/adventures", json={
|
||||
"scenario_id": scenario_id,
|
||||
"persona_name": "Kaelen",
|
||||
"placeholders": {"Name": "Wren"},
|
||||
}).json()
|
||||
assert adv["persona_name"] == "Kaelen"
|
||||
opening = next(a for a in adv["actions"] if a["type"] == "start")
|
||||
assert "A guard sneers at Wren." == opening["text"]
|
||||
@@ -130,6 +130,12 @@ def story():
|
||||
ai_instructions="Write in second person.",
|
||||
story_summary="The hero left the village.",
|
||||
world_state=worldstate.instantiate(SCHEMA),
|
||||
# Phase 18. Set here so that every test in this file runs with a
|
||||
# persona present: it is user-only, so it belongs in the static block,
|
||||
# and this is the file that guards what may live there.
|
||||
persona_name="Kaelen",
|
||||
persona_pronouns="he/him",
|
||||
persona_desc="A half-elf ranger.",
|
||||
)
|
||||
db.add(adventure)
|
||||
db.flush()
|
||||
@@ -164,7 +170,8 @@ def test_changing_a_stat_leaves_the_static_block_untouched(story):
|
||||
def test_the_static_block_holds_the_things_that_do_not_move(story):
|
||||
db, adventure, settings = story
|
||||
system_text, story_text, _ = builder.build_context(adventure, settings)
|
||||
for fixed in ("Write in second person.", "The hero hunts bandits."):
|
||||
for fixed in ("Write in second person.", "The hero hunts bandits.",
|
||||
"You are Kaelen (he/him).", "A half-elf ranger."):
|
||||
assert fixed in system_text
|
||||
# The stat guide is derived from the schema, so it is fixed. The live
|
||||
# values it describes are not fixed, and belong to the story text.
|
||||
|
||||
@@ -154,6 +154,7 @@ Fixed (always included, whatever they cost):
|
||||
| `world_state` | Current values of every stat, plus NPCs in scene. |
|
||||
| `world_state_rule` | How to report changes. |
|
||||
| `ai_instructions` | Per-adventure steering. |
|
||||
| `persona` | Who the player is playing as: name, pronouns, description. Only the player edits it, so it never moves. |
|
||||
| `plot_essentials` | AI Dungeon's "Memory": the premise. |
|
||||
| `story_summary` | The auto-maintained running summary. |
|
||||
| `used_memories` | Top-K retrievals from the memory bank. |
|
||||
|
||||
@@ -199,30 +199,83 @@ export function extractPlaceholders(...texts) {
|
||||
return names
|
||||
}
|
||||
|
||||
export function PlaceholderModal({ title, names, onSubmit, onCancel }) {
|
||||
// The modal shown before an adventure begins. It always asks who the player is
|
||||
// playing as, and it also collects any `${Placeholder}` answers the scenario's
|
||||
// text asks for.
|
||||
//
|
||||
// The two sets of fields are independent on purpose. A scenario that writes
|
||||
// `${Name}` is asking its own question, and the persona does not answer it. No
|
||||
// scenario in the repo uses placeholders at all, so the overlap is hypothetical;
|
||||
// pre-filling one from the other is a small change here if it ever bites.
|
||||
//
|
||||
// `onSubmit` receives `{ persona, placeholders }`. Every persona field is
|
||||
// optional — submitting them all blank gives an adventure with no persona,
|
||||
// which behaves exactly as adventures did before personas existed.
|
||||
export function BeginAdventureModal({ title, names = [], onSubmit, onCancel }) {
|
||||
const [persona, setPersona] = useState({ name: '', pronouns: '', desc: '' })
|
||||
const [values, setValues] = useState(Object.fromEntries(names.map((n) => [n, ''])))
|
||||
|
||||
const setField = (field, value) => setPersona((p) => ({ ...p, [field]: value }))
|
||||
|
||||
const submit = (e) => {
|
||||
e.preventDefault()
|
||||
onSubmit(values)
|
||||
onSubmit({ persona, placeholders: values })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal-overlay" onClick={onCancel}>
|
||||
<form className="modal" onClick={(e) => e.stopPropagation()} onSubmit={submit}>
|
||||
<h2>{title}</h2>
|
||||
<p className="modal-hint">
|
||||
Who are you playing as? Leave these blank to play as an unnamed character.
|
||||
</p>
|
||||
<div className="modal-row">
|
||||
<label className="field">
|
||||
<span className="label">Name</span>
|
||||
<input
|
||||
type="text"
|
||||
autoFocus
|
||||
maxLength={80}
|
||||
placeholder="Kaelen"
|
||||
value={persona.name}
|
||||
onChange={(e) => setField('name', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="field field-narrow">
|
||||
<span className="label">Pronouns</span>
|
||||
<input
|
||||
type="text"
|
||||
maxLength={40}
|
||||
placeholder="they/them"
|
||||
value={persona.pronouns}
|
||||
onChange={(e) => setField('pronouns', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<label className="field">
|
||||
<span className="label">Description</span>
|
||||
<textarea
|
||||
rows={3}
|
||||
placeholder="A half-elf ranger, exiled from the northern holds. Wary of nobles, soft on strays."
|
||||
value={persona.desc}
|
||||
onChange={(e) => setField('desc', e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{names.length > 0 && (
|
||||
<>
|
||||
<p className="modal-hint">This scenario asks a few questions before you begin.</p>
|
||||
{names.map((name, i) => (
|
||||
{names.map((name) => (
|
||||
<label key={name} className="field">
|
||||
<span className="label">{name}</span>
|
||||
<input
|
||||
type="text"
|
||||
autoFocus={i === 0}
|
||||
value={values[name]}
|
||||
onChange={(e) => setValues({ ...values, [name]: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
<div className="modal-buttons">
|
||||
<button type="button" onClick={onCancel}>Cancel</button>
|
||||
<button type="submit" className="primary">Begin Adventure</button>
|
||||
@@ -354,14 +407,19 @@ export function AutoTextarea({ value, ...props }) {
|
||||
return <textarea ref={ref} value={value} {...props} />
|
||||
}
|
||||
|
||||
export function Field({ label, value, onChange, textarea, rows, placeholder }) {
|
||||
// `maxLength` mirrors the column width the server enforces. Without it an
|
||||
// over-long value is only rejected at save time, as a 422 the player sees as a
|
||||
// toast after the text is already typed.
|
||||
export function Field({ label, value, onChange, textarea, rows, placeholder, maxLength }) {
|
||||
return (
|
||||
<label className="field">
|
||||
<span className="label">{label}</span>
|
||||
{textarea ? (
|
||||
<textarea rows={rows || 3} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} />
|
||||
<textarea rows={rows || 3} value={value} placeholder={placeholder} maxLength={maxLength}
|
||||
onChange={(e) => onChange(e.target.value)} />
|
||||
) : (
|
||||
<input type="text" value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} />
|
||||
<input type="text" value={value} placeholder={placeholder} maxLength={maxLength}
|
||||
onChange={(e) => onChange(e.target.value)} />
|
||||
)}
|
||||
</label>
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ import { api } from '../api'
|
||||
import {
|
||||
CardSkeleton,
|
||||
extractPlaceholders,
|
||||
PlaceholderModal,
|
||||
BeginAdventureModal,
|
||||
ScenarioArt,
|
||||
useToast,
|
||||
} from '../components'
|
||||
@@ -61,9 +61,15 @@ export default function Home() {
|
||||
const ongoing = useMemo(() => (adventures || []).slice(0, CONTINUE_LIMIT), [adventures])
|
||||
const featured = useMemo(() => (scenarios || []).slice(0, SCENARIO_LIMIT), [scenarios])
|
||||
|
||||
const begin = async (scenarioId, placeholders = {}) => {
|
||||
const begin = async (scenarioId, { persona = {}, placeholders = {} } = {}) => {
|
||||
try {
|
||||
const adv = await api.createAdventure({ scenario_id: scenarioId, placeholders })
|
||||
const adv = await api.createAdventure({
|
||||
scenario_id: scenarioId,
|
||||
placeholders,
|
||||
persona_name: persona.name || '',
|
||||
persona_pronouns: persona.pronouns || '',
|
||||
persona_desc: persona.desc || '',
|
||||
})
|
||||
navigate(`/play/${adv.id}`)
|
||||
} catch (err) {
|
||||
toast(err.message, 'error')
|
||||
@@ -78,7 +84,8 @@ export default function Home() {
|
||||
scenario.prompt, scenario.memory, scenario.authors_note, scenario.ai_instructions,
|
||||
...scenario.story_cards.flatMap((c) => [c.keys, c.entry]),
|
||||
)
|
||||
if (names.length === 0) return begin(scenarioId)
|
||||
// Always open the modal, even with no placeholders: it is where the
|
||||
// player names their character.
|
||||
setPending({ scenario, names })
|
||||
} catch (err) {
|
||||
toast(err.message, 'error')
|
||||
@@ -218,11 +225,11 @@ export default function Home() {
|
||||
</section>
|
||||
|
||||
{pending && (
|
||||
<PlaceholderModal
|
||||
<BeginAdventureModal
|
||||
title={pending.scenario.title}
|
||||
names={pending.names}
|
||||
onCancel={() => setPending(null)}
|
||||
onSubmit={(values) => { setPending(null); begin(pending.scenario.id, values) }}
|
||||
onSubmit={(answers) => { setPending(null); begin(pending.scenario.id, answers) }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -139,7 +139,7 @@ function sliceDraft(draft, prefix) {
|
||||
// the adventure's scenario defines a stat_schema. An edit mode lets the
|
||||
// player/author directly override the live values (a manual correction, not
|
||||
// a turn) — it never adds new stats, only edits ones the schema already defines.
|
||||
function WorldStateDrawer({ advId, refreshKey }) {
|
||||
function WorldStateDrawer({ advId, refreshKey, personaName }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [data, setData] = useState(null) // { state, schema }
|
||||
const [failed, setFailed] = useState(false)
|
||||
@@ -209,7 +209,10 @@ function WorldStateDrawer({ advId, refreshKey }) {
|
||||
<StatGroup title={null} defs={schema.world} values={state.world}
|
||||
editing={editing} draft={sliceDraft(draft, 'world')}
|
||||
onEdit={(name, v) => setPath(`world.${name}`, v)} />
|
||||
<StatGroup title="You" defs={schema.player} values={state.player}
|
||||
{/* Named after the persona when there is one, matching the label
|
||||
the prompt uses. Read-only here — the name is edited in the
|
||||
Plot panel, so there is one place to change it. */}
|
||||
<StatGroup title={personaName || 'You'} defs={schema.player} values={state.player}
|
||||
editing={editing} draft={sliceDraft(draft, 'player')}
|
||||
onEdit={(name, v) => setPath(`player.${name}`, v)} />
|
||||
{npcs.length > 0 && (
|
||||
|
||||
@@ -514,7 +514,8 @@ export default function Play() {
|
||||
so neither can key on the story's length alone: switching between two
|
||||
branches whose windows are both full changes every number in here
|
||||
without changing `actions.length` by one. */}
|
||||
<WorldStateDrawer advId={id} refreshKey={`${actions.length}:${stateKey}`} />
|
||||
<WorldStateDrawer advId={id} refreshKey={`${actions.length}:${stateKey}`}
|
||||
personaName={adventure?.persona_name} />
|
||||
<StatusDrawer advId={id} refreshKey={`${actions.length}:${stateKey}`} />
|
||||
<div className="page play-page">
|
||||
<div className="page-header">
|
||||
|
||||
@@ -102,6 +102,25 @@ function PlotPanel({ adventure, setAdventure, onWorldStateChanged }) {
|
||||
<RefreshModal plan={plan} onConfirm={applyRefresh} onCancel={() => setPlan(null)} />
|
||||
)}
|
||||
|
||||
{/* Phase 18. The persona sits above the plot text because it is the one
|
||||
section that describes the player rather than the world, and because
|
||||
it is the first thing a reader looks for when they want to rename
|
||||
their character. It is edited only here: the world-state drawer shows
|
||||
the name as a heading but does not offer a second way to change it. */}
|
||||
<div className="persona-block">
|
||||
<div className="persona-row">
|
||||
<Field label="Character Name" value={adventure.persona_name}
|
||||
onChange={(v) => setField('persona_name', v)}
|
||||
maxLength={80} placeholder="Kaelen" />
|
||||
<Field label="Pronouns" value={adventure.persona_pronouns}
|
||||
onChange={(v) => setField('persona_pronouns', v)}
|
||||
maxLength={40} placeholder="they/them" />
|
||||
</div>
|
||||
<Field label="Character Description" value={adventure.persona_desc}
|
||||
onChange={(v) => setField('persona_desc', v)} textarea rows={3}
|
||||
placeholder="Who you are playing as. The AI never rewrites this — only you can." />
|
||||
</div>
|
||||
|
||||
<Field label="Plot Essentials (Memory)" value={adventure.memory}
|
||||
onChange={(v) => setField('memory', v)} textarea
|
||||
placeholder="Key facts the AI should always remember." />
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
CardSkeleton,
|
||||
extractPlaceholders,
|
||||
pickJSONFile,
|
||||
PlaceholderModal,
|
||||
BeginAdventureModal,
|
||||
ScenarioArt,
|
||||
useToast,
|
||||
} from '../components'
|
||||
@@ -49,8 +49,17 @@ export default function Scenarios() {
|
||||
navigate(`/scenarios/${scenario.id}`)
|
||||
}
|
||||
|
||||
const begin = async (scenarioId, placeholders = {}) => {
|
||||
const adv = await api.createAdventure({ scenario_id: scenarioId, placeholders })
|
||||
const begin = async (scenarioId, { persona = {}, placeholders = {} } = {}) => {
|
||||
const adv = await api.createAdventure({
|
||||
scenario_id: scenarioId,
|
||||
// A blank adventure has no scenario to take a title from, so name it here
|
||||
// exactly as the button that starts it did before the modal existed.
|
||||
title: scenarioId ? null : 'Blank Adventure',
|
||||
placeholders,
|
||||
persona_name: persona.name || '',
|
||||
persona_pronouns: persona.pronouns || '',
|
||||
persona_desc: persona.desc || '',
|
||||
})
|
||||
navigate(`/play/${adv.id}`)
|
||||
}
|
||||
|
||||
@@ -62,14 +71,15 @@ export default function Scenarios() {
|
||||
// Cards can carry ${placeholders} in trigger keys too, not just entries.
|
||||
...scenario.story_cards.flatMap((c) => [c.keys, c.entry]),
|
||||
)
|
||||
if (names.length === 0) return begin(scenarioId)
|
||||
// Always open the modal, even with no placeholders: it is where the
|
||||
// player names their character.
|
||||
setPending({ scenario, names })
|
||||
}
|
||||
|
||||
const startBlank = async () => {
|
||||
const adv = await api.createAdventure({ title: 'Blank Adventure' })
|
||||
navigate(`/play/${adv.id}`)
|
||||
}
|
||||
// A blank adventure has no scenario, so there are no placeholders to collect,
|
||||
// but the player still names their character. `pending.scenario` is null for
|
||||
// this path, and `begin` is called with no scenario id.
|
||||
const startBlank = () => setPending({ scenario: null, names: [] })
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
@@ -157,11 +167,14 @@ export default function Scenarios() {
|
||||
)}
|
||||
|
||||
{pending && (
|
||||
<PlaceholderModal
|
||||
title={pending.scenario.title}
|
||||
<BeginAdventureModal
|
||||
title={pending.scenario ? pending.scenario.title : 'Blank Adventure'}
|
||||
names={pending.names}
|
||||
onCancel={() => setPending(null)}
|
||||
onSubmit={(values) => { setPending(null); begin(pending.scenario.id, values) }}
|
||||
onSubmit={(answers) => {
|
||||
setPending(null)
|
||||
begin(pending.scenario ? pending.scenario.id : null, answers)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -54,4 +54,16 @@
|
||||
}
|
||||
.modal .modal-hint { margin: 0 0 18px; color: var(--text-dim); font-size: 0.88rem; }
|
||||
.modal .modal-buttons { display: flex; justify-content: flex-end; gap: 10px; margin-top: 18px; }
|
||||
/* The begin-adventure modal puts name and pronouns on one line. Pronouns need
|
||||
only a few characters, so the name takes the slack. Both stack on a narrow
|
||||
screen rather than shrinking the name field to nothing. */
|
||||
.modal .modal-row { display: flex; gap: 10px; }
|
||||
.modal .modal-row > .field { flex: 1 1 auto; min-width: 0; }
|
||||
.modal .modal-row > .field-narrow { flex: 0 1 9rem; }
|
||||
@media (max-width: 480px) {
|
||||
.modal .modal-row { display: block; }
|
||||
.modal .modal-row > .field-narrow { flex: none; }
|
||||
}
|
||||
/* A second hint, introducing the scenario's own questions below the persona. */
|
||||
.modal .modal-hint + .field, .modal .field + .modal-hint { margin-top: 4px; }
|
||||
|
||||
|
||||
@@ -63,3 +63,15 @@
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
|
||||
/* Phase 18: the persona block at the top of the Plot panel. The rule under it
|
||||
separates who the player is from what the world is, which are the two halves
|
||||
of that panel. */
|
||||
.persona-block { margin-bottom: 18px; padding-bottom: 4px; border-bottom: 1px solid var(--border); }
|
||||
.persona-block .persona-row { display: flex; gap: 10px; }
|
||||
.persona-block .persona-row > .field { flex: 1 1 auto; min-width: 0; }
|
||||
.persona-block .persona-row > .field:last-child { flex: 0 1 9rem; }
|
||||
@media (max-width: 480px) {
|
||||
.persona-block .persona-row { display: block; }
|
||||
.persona-block .persona-row > .field:last-child { flex: none; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
# The protagonist has no name, and the summarizer is told nothing
|
||||
|
||||
Two changes, in order. Phase 1 gives the adventure a persona. Phase 2 uses it,
|
||||
along with the cast, to fix the memories. Phase 1 is worth shipping on its own;
|
||||
Phase 2 depends on it and is much smaller once it lands.
|
||||
|
||||
**Phase 1 is built and green (593 backend tests, frontend builds). Phase 2 is
|
||||
not started.** Phase 1 has NOT been driven in a browser yet — see "Still to
|
||||
check by hand" at the end.
|
||||
|
||||
**Last updated: 2026-08-31.**
|
||||
|
||||
---
|
||||
|
||||
## The one sentence version
|
||||
|
||||
Memories come back inconsistent and vague because the summarizer is handed six
|
||||
actions of second-person prose and nothing else — no protagonist, no cast, no
|
||||
setting, no instruction about what person to write in — so it cannot say who
|
||||
"you" is or who "she" is, and neither can any memory it writes.
|
||||
|
||||
## The evidence
|
||||
|
||||
This is the entire prompt that writes a memory (`memorybank.py:391`):
|
||||
|
||||
```
|
||||
system: You compress interactive-fiction story excerpts into memories. Respond
|
||||
with 1-2 plain sentences in past tense stating the concrete facts and
|
||||
events (names, places, items, promises, injuries). No preamble, no
|
||||
commentary.
|
||||
|
||||
user: Story excerpt:
|
||||
|
||||
<6 actions, joined by blank lines, truncated to 2000 tokens>
|
||||
|
||||
Memory:
|
||||
```
|
||||
|
||||
Nothing else is passed. Not `adventure.memory` (the plot essentials), not the
|
||||
NPC names and descriptions the scenario already defines, not the world state,
|
||||
and not the protagonist — because until Phase 1 there is no protagonist to pass.
|
||||
|
||||
Two failures follow from that, and they are the two complaints:
|
||||
|
||||
**Inconsistent framing.** The prompt never says what person to write in. The
|
||||
model picks one per call. Across a single bank you get "You entered the crypt",
|
||||
"The player entered the crypt", and "He entered the crypt" describing the same
|
||||
kind of event.
|
||||
|
||||
**No idea who anyone is.** Given `You push the door open. She grabs your arm.`
|
||||
the only honest memory is *"You entered a room and she stopped you."* Retrieved
|
||||
forty turns later into a scene with three women in it, that memory is worse than
|
||||
nothing.
|
||||
|
||||
The summary inherits both problems, because `_update_story_summary` builds from
|
||||
the memory bullets.
|
||||
|
||||
---
|
||||
|
||||
# Phase 1 — the persona
|
||||
|
||||
## What already exists, and what does not
|
||||
|
||||
`stat_schema` already gives the player a stat block, and it is already
|
||||
namespaced beside the NPCs:
|
||||
|
||||
```
|
||||
world.day
|
||||
player.hp <- the player's stats, already sectioned
|
||||
npc.gwen.trust
|
||||
flags.alarm_raised
|
||||
milestones.escaped
|
||||
```
|
||||
|
||||
NPCs carry `name`, `keys`, and `desc` (`schema.py`, `render_reference`). The
|
||||
`player` section carries none of those. That asymmetry is the whole gap: the
|
||||
player has stats but no identity, so the block renders as `You: hp 100/100` and
|
||||
reads to the model as a floating global rather than a character.
|
||||
|
||||
## The paths do not change
|
||||
|
||||
`player.hp` stays `player.hp`. It does not become `kaelen.hp` or `user.hp`.
|
||||
|
||||
The reason is `_history_text()` in `context/builder.py`. It replays every past
|
||||
turn's stored delta back into the prompt, and those stored blobs contain literal
|
||||
strings like `{"player.hp": -15}`. A path that carries the persona's name breaks
|
||||
the moment a player renames their character: every replayed block in history
|
||||
then names a path the schema no longer defines, `applied_delta` renders it
|
||||
anyway, and the model copies the broken form. A rename would also require
|
||||
migrating every stored `world_state`, every seed scenario, and the `EMIT_RULE`
|
||||
example text, for no functional gain.
|
||||
|
||||
What changes is the **label**, using the trick NPCs already use — print the
|
||||
display name and the path together:
|
||||
|
||||
```
|
||||
before: You: hp 100/100, mana 30/50.
|
||||
after: Kaelen (player): hp 100/100, mana 30/50.
|
||||
```
|
||||
|
||||
The name is visible to the reader, the path stays copyable by the model.
|
||||
|
||||
## Where the persona lives
|
||||
|
||||
Three plain columns on `adventures`, alongside `memory` and `authors_note`:
|
||||
|
||||
```python
|
||||
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="")
|
||||
```
|
||||
|
||||
**Not in `stat_schema`.** Two reasons. It has to work for an adventure with no
|
||||
RPG layer at all, which is most of them, and `_initials()` in
|
||||
`worldstate/schema.py` treats every dict inside a section as a stat definition —
|
||||
a `persona` key dropped into `stat_schema.player` would be instantiated as a
|
||||
stat, rendered as a stat line in the guide, and handed an `initial` value.
|
||||
|
||||
**Adventure-level, not scenario-level.** Two people playing the same scenario
|
||||
are different characters. A scenario steers the protagonist through its plot
|
||||
essentials, which it already can. Keeping personas off `scenarios` also avoids
|
||||
having to decide what "Update from scenario" does to a persona the player has
|
||||
edited: the answer is nothing, because the scenario never had one.
|
||||
|
||||
**Not per-branch.** Branches are alternative futures within one adventure; the
|
||||
protagonist is the same person down all of them.
|
||||
|
||||
Empty `persona_name` means the feature is off and behavior is exactly what it is
|
||||
today. That is the entire backward-compatibility story — no backfill.
|
||||
|
||||
## Pronouns get their own field
|
||||
|
||||
One short string: `he/him`, `she/her`, `they/them`. It exists because Phase 2
|
||||
will tell the summarizer to write in third person. Without a stated pronoun the
|
||||
model infers one from the name, and once it infers wrong that error is baked
|
||||
into every memory it writes from then on and into the summary built from them.
|
||||
A field is cheaper than a wrong guess repeated forever.
|
||||
|
||||
Blank is a valid value. When it is blank nothing is rendered, and the Phase 2
|
||||
prompt tells the summarizer to use the name rather than a pronoun.
|
||||
|
||||
## Where it enters the prompt
|
||||
|
||||
A new static section in `build_context`, between `ai_instructions` and
|
||||
`plot_essentials`:
|
||||
|
||||
```
|
||||
Player character:
|
||||
You are Kaelen (he/him). A half-elf ranger, exiled from the northern holds.
|
||||
```
|
||||
|
||||
**It goes in the system block on purpose.** The description is user-only and
|
||||
never changes during a turn, so it sits inside the cached prefix and costs
|
||||
nothing after the first turn. This is why "only the user can change it" is not
|
||||
just a product choice — it is what keeps the section free. Anything the AI could
|
||||
rewrite would have to move below the history with the other live sections, and
|
||||
would re-price the prompt on every change.
|
||||
|
||||
It is emitted whether or not the adventure has an RPG layer. It is not gated
|
||||
behind `has_ws`.
|
||||
|
||||
## Where it enters the world state
|
||||
|
||||
`worldstate/render.py`, two edits:
|
||||
|
||||
- `render_state_section` takes the display name and prints
|
||||
`Kaelen (player): …` in place of the hardcoded `You: …`. Falls back to `You:`
|
||||
when no persona is set.
|
||||
- `render_reference` gains one line tying the name to the path, mirroring the
|
||||
NPC header it already writes:
|
||||
`- Protagonist Kaelen — stats are addressed as player.<stat>.`
|
||||
Without this the model reads "Kaelen" in the prose and invents `kaelen.hp`.
|
||||
|
||||
The persona description is **not** repeated in the stat guide. It already has
|
||||
its own section, and the guide is about paths.
|
||||
|
||||
## The AI cannot edit it
|
||||
|
||||
Nothing to build. `_resolve()` in `worldstate/apply.py` rejects any path it does
|
||||
not recognize, so a delta of `{"persona.name": "Bob"}` already falls through to
|
||||
"`persona.name` is not a tracked value", and that refusal already reaches the
|
||||
model through `render_refusals`. Worth one test to hold the behavior in place.
|
||||
|
||||
## Setting it, and changing it
|
||||
|
||||
**At the start.** `PlaceholderModal` (`components.jsx`) already exists and
|
||||
already opens before an adventure begins — but only when the scenario contains
|
||||
`${...}` tokens. It becomes a "Begin adventure" modal that always opens, with
|
||||
the three persona fields at the top and any placeholder fields below.
|
||||
|
||||
**Placeholders stay independent of the persona.** A scenario using `${Name}`
|
||||
will ask for a name twice. That is accepted: no scenario in the repo uses
|
||||
placeholders at all (grepped across `seed_data/` and `starter_data/` — zero
|
||||
occurrences), so the collision is hypothetical. If it ever shows up in practice,
|
||||
pre-filling the `Name` field from the persona is a few lines in the modal with
|
||||
no backend change.
|
||||
|
||||
**Later.** `AdventureUpdate` gains the three fields, and `PlotPanel` gets a
|
||||
Protagonist block at the top. The debounced-save wiring is already there.
|
||||
`WorldStateDrawer` shows the name as the character-sheet heading but does not
|
||||
edit it — one edit surface, not two.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `models.py` | three columns on `Adventure` |
|
||||
| `migrations.py` | 74, 75, 76 |
|
||||
| `schemas.py` | `AdventureCreate`, `AdventureUpdate`, `AdventureOut` |
|
||||
| `context/builder.py` | `persona` section after `plot_essentials` |
|
||||
| `worldstate/render.py` | state-section label, reference line |
|
||||
| `worldstate/__init__.py` | export whatever `render.py` newly exposes |
|
||||
| `routers/adventures/crud.py` | store persona at creation |
|
||||
| `bundle.py` | export key + import read |
|
||||
| `frontend/components.jsx` | modal gains persona fields |
|
||||
| `frontend/pages/Scenarios.jsx`, `Home.jsx` | always open the modal |
|
||||
| `frontend/pages/Play/panels/PlotPanel.jsx` | Protagonist block |
|
||||
| `frontend/pages/Play/drawers/WorldStateDrawer.jsx` | heading |
|
||||
| `frontend/api.js` | pass the fields through |
|
||||
|
||||
## Tests
|
||||
|
||||
| File | What |
|
||||
|---|---|
|
||||
| new `test_persona.py` | create with persona; update; renders in the system block; works with no `stat_schema`; empty name is a no-op; AI delta at `persona.*` refused |
|
||||
| `test_worldstate.py` | state line reads `Kaelen (player):`; `player.hp` still resolves |
|
||||
| `test_prompt_caching.py` | persona is in the static prefix, above history |
|
||||
| `test_bundle_v2.py` | round-trips; a bundle without the key still imports |
|
||||
|
||||
## Bundle format
|
||||
|
||||
No `FORMAT` bump. The export gains a `persona` key and the import reads it with
|
||||
`.get()`, so a v2 bundle written before this change imports with an empty
|
||||
persona — which is the same as not having one.
|
||||
|
||||
---
|
||||
|
||||
# Phase 2 — what the summarizer is told
|
||||
|
||||
Depends on Phase 1 only for the protagonist's name. Everything else it needs is
|
||||
already in the database and simply never passed.
|
||||
|
||||
## The cast brief
|
||||
|
||||
Build one short block and prepend it to both the memory prompt and the summary
|
||||
prompt:
|
||||
|
||||
```
|
||||
Cast:
|
||||
- Kaelen (he/him) — the protagonist. A half-elf ranger, exiled from the
|
||||
northern holds...
|
||||
- Gwen — a loyal ranger and Kaelen's ally. Quick with a bow, dry-humoured.
|
||||
|
||||
Setting:
|
||||
<adventure.memory, the plot essentials>
|
||||
```
|
||||
|
||||
Sources, in order:
|
||||
|
||||
1. **Protagonist** — the Phase 1 persona. Falls back to "the player" when unset,
|
||||
so the change still helps adventures with no persona.
|
||||
2. **NPCs** — `stat_schema.npcs`: `name` + `desc`. Already there, never used
|
||||
outside the turn prompt.
|
||||
3. **Story cards** — for adventures with no RPG layer, run the existing
|
||||
`_match_cards()` over the block being summarized and take the matched cards'
|
||||
names and entries. This reuses the trigger code and yields exactly the
|
||||
entities that appear in *that block*, not the whole world.
|
||||
|
||||
## Two rules for the brief
|
||||
|
||||
**Fixed descriptions only. No live stats.** It is tempting to include
|
||||
`Gwen: trust 40 (wary)`. Do not. It makes every memory prompt different, which
|
||||
loses prompt caching, and worse, it makes the same event summarized at two
|
||||
different times come out framed differently — which is the problem being fixed.
|
||||
|
||||
**The summary gets it for free.** `_update_story_summary` builds from the memory
|
||||
bullets, so better memories produce a better summary with no further change.
|
||||
Pass the brief there too, because that function falls back to raw story text
|
||||
when memory-writing has fallen behind.
|
||||
|
||||
## The prompt changes
|
||||
|
||||
`MEMORY_SYSTEM_PROMPT` gains an explicit framing rule:
|
||||
|
||||
- write in third person, never "you"
|
||||
- refer to the protagonist by name
|
||||
- name characters rather than using bare pronouns
|
||||
|
||||
Expected effect:
|
||||
|
||||
```
|
||||
before: You entered a room and she stopped you.
|
||||
after: Kaelen bribed Gwen with fifty silver to hold the north door while
|
||||
he went down alone.
|
||||
```
|
||||
|
||||
## Open questions for Phase 2
|
||||
|
||||
**Existing memories.** A bank written under the old prompt will sit alongside
|
||||
new ones, mixing "you" and "Kaelen" in the same context. Options: leave them and
|
||||
let eviction age them out at `memory_bank_capacity` (80), or clear
|
||||
`memory_cursor` and re-summarize from the start. Re-summarizing costs one AI
|
||||
call per 6 actions and duplicates whatever is still in the bank, since nothing
|
||||
deletes the old rows. **Leaning: leave them.** Decide when the framing change is
|
||||
measured, not before.
|
||||
|
||||
**Retrieval framing mismatch.** `retrieve_memories` embeds the last 4 actions
|
||||
raw — second person, "you". New memories will be third person and named.
|
||||
Embeddings handle paraphrase well, so this is probably minor, but if retrieval
|
||||
quality visibly dips after Phase 2 this is the first place to look. A fix would
|
||||
be to prepend the same cast brief to the query text.
|
||||
|
||||
**Token cost.** The brief adds roughly 100–200 tokens to one call per 6 actions
|
||||
and one per 15. Negligible against a turn.
|
||||
|
||||
---
|
||||
|
||||
# Phase 1 as built
|
||||
|
||||
Everything above describes what shipped. Three notes on where it differs from
|
||||
the sketch, and what has not been verified.
|
||||
|
||||
## Decisions taken during the build
|
||||
|
||||
**The section reads as one paragraph.** `render_persona` joins the sentence and
|
||||
the description with a space rather than `SEPARATOR`. A blank line inside a
|
||||
two-sentence section about one character reads as two unrelated notes.
|
||||
|
||||
**`Field` gained a `maxLength` prop.** The persona name is `VARCHAR(80)` and the
|
||||
schema rejects 81 characters with a 422. Without the attribute the player only
|
||||
learns that from a toast after typing, so the cap is now enforced in the input
|
||||
as well. Every other `Field` is unaffected — the prop is optional.
|
||||
|
||||
**The blank-adventure button opens the modal too.** It used to create the
|
||||
adventure immediately. It now collects a persona first, and passes
|
||||
`title: 'Blank Adventure'` explicitly, because there is no scenario to take a
|
||||
title from.
|
||||
|
||||
**`test_prompt_caching.py`'s fixture now sets a persona**, so every test in the
|
||||
file that guards the static block runs with one present.
|
||||
|
||||
## Verified
|
||||
|
||||
- Migration 73 → 76 on a real pre-existing SQLite database: columns added, the
|
||||
existing row preserved, persona empty, `render_persona` returns `""`.
|
||||
- 593 backend tests pass, including 26 new ones in `test_persona.py` and 3 in
|
||||
`test_bundle_v2.py`.
|
||||
- `npm run build` is clean.
|
||||
|
||||
## Still to check by hand
|
||||
|
||||
None of this was driven in a browser. Worth ten minutes before trusting it:
|
||||
|
||||
1. Start an adventure from a scenario. The modal should open even though no
|
||||
scenario in the repo uses `${...}` placeholders.
|
||||
2. Play one turn on the RPG scenario (seed 04) and open Insights. The `persona`
|
||||
section should be in the system block, and the world-state line should read
|
||||
`<name> (player): hp 100/100`.
|
||||
3. Rename the character in the Plot panel. The world-state drawer heading
|
||||
should follow it.
|
||||
4. Leave every persona field blank and confirm the prompt is byte-identical to
|
||||
what it was before this change.
|
||||
|
||||
## A note for whoever runs the tests
|
||||
|
||||
`tiktoken` downloads `cl100k_base` from `openaipublic.blob.core.windows.net` on
|
||||
first use, and 182 tests fail with a proxy error where that host is blocked.
|
||||
The encoding is reconstructable offline from the npm package `js-tiktoken`,
|
||||
whose `dist/ranks/cl100k_base.cjs` holds the same ranks in a compressed form —
|
||||
decode it, write `<base64> <rank>` per line sorted by rank, and the result
|
||||
matches the SHA-256 that `tiktoken_ext/openai_public.py` hardcodes, so the
|
||||
reconstruction is verifiable rather than trusted. Drop it at
|
||||
`$TIKTOKEN_CACHE_DIR/<sha1 of the URL>`.
|
||||
Reference in New Issue
Block a user