Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/engines.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ and clamped by code.
- **Overworld and region map generation** - seeded value-noise terrain on a 96x72 grid with genre reskins, reconciling locations to anchors lazily as the party travels. A room or street the GM files under a bigger place (move_party's partOf, or a name that opens with the place's own) shares that place's dot; a new place lands at the direction and distance the GM gave; names on the map make way for each other (src/lib/overworld/places.ts, label-layout.ts).
- **Battle map generation** - seeded tactical maps (terrain, lighting, spawns, line of sight and cover, movement budgets, pathfinding), regenerable from the encounter.
- **Location persistence** - structured per-area layout, exits, and connections so narration stays spatially consistent, plus an illustrated top-down map image.
- **A party that splits up** - the server keeps who is where once some of the party goes and the rest stay. The story follows one group at a time and cuts to the others when they act, one reply for each group, so two rooms are never told as one. A call reaches only who is in the scene, a fight, a rest and a group check belong to it, and going where the others wait brings the party back together. A small narrator rarely says who goes, so the players' own words are read as the turn opens, by the utility model, for who stays behind: the narrator is told, and the server records the parting itself when the narrator does not.
- **Living-world tick engine** - a zero-model-call heartbeat that advances world state on dice and computes encounter pressure after each narration.
- **World arcs** - one or two escalating off-screen storylines that advance whether or not the party engages them.
- **NPC agency** - once-per-chapter goal advancement for every tracked NPC with no model call, surfacing outcomes as rumors and world facts.
Expand Down
30 changes: 30 additions & 0 deletions scripts/browser/scenarios/100-party-split.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,36 @@ export default {
await untilStill(page);
await t.shot("split");

// ---- The split is kept (issue 951): the table says who is where ----
// The scene line under the title names who the story is with, and the
// party panel marks whoever is not there. Seren may have slipped away
// in the split, so the mark is read off Ilse, who stayed.
const sceneLine = page.locator(`${root}.session-heading p`).first();
await eventually(async () => /The Old Mill · .*Kael Ashvale/.test((await sceneLine.textContent()) ?? ""), { label: "the scene line naming who the story is with" });
check(!/Ilse Marrow/.test((await sceneLine.textContent()) ?? ""), "the scene line leaves out who stayed behind");
await openPanelTab(t, "party");
const ilse = page.locator(`${root}[data-party-card]`).filter({ hasText: "Ilse Marrow" }).locator("visible=true").first();
await eventually(() => ilse.count(), { label: "Ilse's card in the party panel" });
const mark = ilse.locator("[data-elsewhere]").first();
await eventually(() => mark.count(), { label: "the mark on a character who is elsewhere" });
check((await mark.textContent())?.trim().startsWith("At "), `the mark says where: ${await mark.textContent()}`);
const kaelCard = page.locator(`${root}[data-party-card]`).filter({ hasText: "Kael Ashvale" }).locator("visible=true").first();
check((await kaelCard.locator("[data-elsewhere]").count()) === 0, "nobody the story is with is marked");
// The mark comes in, as a combatant's side does (globals.css .side-badge).
check((await mark.evaluate((node) => getComputedStyle(node).animationName)) === "side-badge-in", "the mark animates in");
await mark.scrollIntoViewIfNeeded();
await untilStill(page);
await t.shot("elsewhere");
// The same in the day theme, where the mark must still read.
const theme = await page.evaluate(() => document.documentElement.dataset.theme ?? "");
await page.evaluate(() => (document.documentElement.dataset.theme = "light"));
await untilStill(page);
const ink = await mark.evaluate((node) => ({ color: getComputedStyle(node).color, background: getComputedStyle(node).backgroundColor }));
check(ink.color !== ink.background, `the mark has ink on its ground in the day theme (${ink.color} on ${ink.background})`);
await t.shot("elsewhere-day");
await page.evaluate((mode) => (document.documentElement.dataset.theme = mode), theme);
await openPanelTab(t, "dm");

// ---- A deed's form: who spoke against it ----
await tab("social");
await open("Relationship beat");
Expand Down
24 changes: 24 additions & 0 deletions scripts/lib/enforce-narrator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@
import http from "node:http";
import { answerReader, isReaderRequest } from "./claims-reader.mjs";

// The first words of the read that asks the players' words whether the party
// parts (party-split-logic.ts PARTING_PROMPT_START), spelled here so this
// helper loads before src/.
const PARTING_PROMPT_START = "You read what the players at a tabletop RPG table just said, and tell whether the party parts ways";

// The AI's door into the engine: an AI turn and actor kind "ai", the way a
// delegated turn or an AI share of an assisted session reaches it.
export async function aiEngine(world) {
Expand Down Expand Up @@ -103,6 +108,8 @@ export async function fakeModel({ slots = 0 } = {}) {
const requests = [];
let readerScript = [];
const readerRequests = [];
let partingScript = [];
const partingRequests = [];
const fallback = reply({ text: "The moment settles, and the table waits on the next move." });

function sse(res, entry) {
Expand Down Expand Up @@ -224,6 +231,16 @@ export async function fakeModel({ slots = 0 } = {}) {
answerReader(res, readerScript.shift() ?? []);
return;
}
// The read of the players' words for whether the party parts, as a
// turn opens (src/lib/dm/party-split.ts readParting): nobody parts,
// unless the test says who with model.parting([...]), so a scripted
// turn's replies are never spent on it.
if (String(body.messages?.[0]?.content ?? "").startsWith(PARTING_PROMPT_START)) {
partingRequests.push(body);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ choices: [{ index: 0, finish_reason: "stop", message: { role: "assistant", content: JSON.stringify(partingScript.shift() ?? { stays: [], to: "" }) } }] }));
return;
}
requests.push(body);
slotState.restarted = false;
const entry = script[served] ?? fallback;
Expand Down Expand Up @@ -259,6 +276,13 @@ export async function fakeModel({ slots = 0 } = {}) {
return {
requests,
readerRequests,
// What the parting read answers, one per read:
// { stays: [{ name, quote }], to }.
partingRequests,
parting: (entries) => {
partingScript = [...entries];
partingRequests.length = 0;
},
slotLog,
slots: {
restart: () => {
Expand Down
12 changes: 9 additions & 3 deletions scripts/name-lookups.json
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@
"app/campaigns/[campaignId]/MessageParts.tsx#partial": [
[
"pattern",
7,
13,
"a fixed pattern over text that reads no record's name: its English words are scripts/text-comparisons.json's to classify"
],
[
Expand Down Expand Up @@ -2117,8 +2117,14 @@
"lib/dm/party-conduct.ts#whole": [["identity",1,"a companion's standing with one character, by its whole name (textKey)"]],
"lib/dm/party-logic.ts#bypass": [["identity",1,"a stash line by its whole own name and facts"]],
"lib/dm/party-logic.ts#whole": [["identity",1,"a stash line by its whole own name and facts"]],
"lib/dm/party-split.ts#first": [["key",1,"the one name of a list of one, for a sentence"]],
"lib/dm/party-split.ts#whole": [["identity",4,"who goes when the party splits, by characterId or whole name (textKey), and whether move_party names only some of them"]],
"lib/dm/party-split-logic.ts#whole-single": [["identity",1,"two place names compared whole through textKey, for whether a move goes where a group of a split party is (issue 951)"]],
"lib/dm/party-split-logic.ts#partial": [["key",5,"a character id in a group's or a move's list of ids, compared as stored (issue 951)"],["search",1,"a reader's quote held to the words the players wrote, both through textKey: the words being found there is the point, and a miss leaves nobody behind"]],
"lib/dm/party-split-logic.ts#keyed": [["key",1,"a character id as the key of the cut's own record of who came into the scene"]],
"lib/dm/party-split-logic.ts#whole": [["identity",3,"a character a call or a reader's reply names, by id or whole name through textKey, against those elsewhere or the party (issue 951); a name that fits nobody is nobody"]],
"lib/db/locations.ts#partial": [["identity",1,"a follower's recorded place among the places the party left, whole names through textKey (issue 951)"]],
"lib/dm/party-split.ts#partial": [["key",2,"a character id in a group's or a read's list of ids, compared as stored (issue 951)"]],
"lib/dm/party-split.ts#whole-single": [["identity",1,"the place a move goes to against the place the scene is at, whole names through textKey (issue 951)"]],
"lib/dm/party-split.ts#whole": [["identity",2,"who goes when the party splits, by characterId or whole name (textKey)"]],
"lib/dm/party-story.ts#partial": [["parse",6,"a model draft's quotes and its last sentence end"]],
"lib/dm/party-tools.ts#bypass": [["identity",2,"the taken line's own name, granted as it was and named in the carrying refusal"]],
"lib/dm/party-tools.ts#whole": [["identity",1,"a sheet by whole name"]],
Expand Down
92 changes: 89 additions & 3 deletions scripts/smoke-local.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
// node scripts/smoke-local.mjs --provider local --model gemma4:31b-it-qat [--runs 6]
// (Ollama native API at OLLAMA_BASE_URL; LOCAL_TEXT_CONTEXT caps num_ctx)
// options: --turns N (how many of the scenario's turns to play, default all)
// --scenario ford|town|skirmish (the ford's five turns, the town's
// eight: arrival, an NPC, persuasion, a purchase, stealth, a fight,
// attacks; or the skirmish's nine, a fight over several rounds)
// --scenario ford|town|skirmish|split (the ford's five turns, the
// town's eight: arrival, an NPC, persuasion, a purchase, stealth, a
// fight, attacks; the skirmish's nine, a fight over several rounds;
// or the split's five, a party that splits up, acts in two places
// at once and comes back together)
// --label NAME --out DIR (writes <label>.json)
// --context N (the window the prompt packs against; custom provider)
// --key KEY (the custom provider's API key, default OPENAI_COMPAT_API_KEY;
Expand Down Expand Up @@ -121,6 +123,10 @@ const { getActiveEncounter, listEnemies } = await import("../src/lib/db/encounte
const { listQuests } = await import("../src/lib/db/quests.ts");
const { listActiveFacts } = await import("../src/lib/db/facts.ts");
const { listNpcs } = await import("../src/lib/db/npcs.ts");
const { getParty } = await import("../src/lib/db/party.ts");
const { getCurrentLocation } = await import("../src/lib/db/locations.ts");
const { dmQueueDepth } = await import("../src/lib/dm/queue.ts");
const { tableWaitTurnStarted } = await import("../src/lib/dm/table-wait.ts");
const { EMPTY_TURN_LINE, RESOLVED_TURN_LINE } = await import("../src/lib/dm/empty-turn.ts");
const { DM_HALTED_PREFIX } = await import("../src/lib/campaign-types.ts");
const { storyContextTokens } = await import("../src/lib/model-client.ts");
Expand Down Expand Up @@ -344,6 +350,45 @@ const SKIRMISH = [
},
];

// --scenario split: a party of two parts ways, each acts where they are, both
// act in the same beat, and they come back together (issue 951). Measured on
// whether the model records who went (move_party with characterIds), whether
// each group gets a passage of its own, and whether the party is one again
// when they meet. `also` is a line another player sends in the same beat.
const SPLIT = [
{
label: "arrive",
who: "avery",
text: "We ride into the fishing village of Saltmere at dusk and stop on the quay.",
expect: (turn) => called(turn, ["move_party", "update_location"], "the party arrived somewhere new and no move_party recorded it"),
},
{
label: "split",
who: "avery",
text: "Bram stays on the quay to keep watch. I leave him there and slip off alone to the chandler's warehouse at the far end of the harbour.",
expect: (turn) => (turn.away.length ? null : "the party split up in the story and nothing recorded who went (move_party with characterIds)"),
},
{
label: "scene-a",
who: "avery",
text: "I pick the lock on the warehouse door and look inside.",
expect: (turn) => (turn.away.length ? null : "the split was dropped: everyone is in one scene again though nobody moved"),
},
{
label: "both",
who: "avery",
also: [{ who: "bram", text: "Back on the quay, I walk over to the fishermen mending their nets and ask who owns that warehouse." }],
text: "Inside the warehouse I search the crates for anything marked with a smuggler's sign.",
expect: (turn) => (turn.passages >= 2 ? null : `two groups acted and ${turn.passages} passage(s) answered them`),
},
{
label: "regroup",
who: "bram",
text: "I have heard enough. I walk down the harbour to the warehouse and find Avery.",
expect: (turn) => (turn.away.length ? "Bram went to where Avery is and the party was not brought back together" : null),
},
];

// The player who speaks a scripted line: the character whose turn the fight
// is on for who "current", the line's own speaker otherwise.
function speakerFor(script, players, campaignId) {
Expand All @@ -369,6 +414,12 @@ const SCENARIOS = {
theme: "low fantasy, coastal trade road",
turns: FORD,
},
split: {
title: "The Saltmere Ledger",
description: "A smuggler's ledger is hidden somewhere in a fishing village, and the party splits up to find it.",
theme: "low fantasy, a fishing village at dusk",
turns: SPLIT,
},
town: {
title: "The Thornwick Inn",
description: "A merchant has vanished from a village inn, and the party asks around.",
Expand Down Expand Up @@ -430,6 +481,17 @@ async function settleRolls(campaignId) {
}
}

// Whatever the turn queued behind itself, run to the end, with any roll it
// parked on answered.
async function drainQueue(campaignId) {
const until = Date.now() + 15 * 60_000;
while (dmQueueDepth(campaignId) > 0 || listOpenPendingRolls(campaignId).length) {
assert.ok(Date.now() < until, "the GM queue never ran dry");
await settleRolls(campaignId);
await new Promise((resolve) => setTimeout(resolve, 100));
}
}

let lastSettings = null;
async function playRun(runNumber) {
// An admin: only an admin's campaign runs on a backend address of its own
Expand Down Expand Up @@ -474,6 +536,10 @@ async function playRun(runNumber) {
const turns = [];
for (const script of TURNS.slice(0, MAX_TURNS)) {
const player = speakerFor(script, players, campaign.id);
// Lines other players send in the same beat, ahead of this one.
for (const extra of script.also ?? []) {
insertCampaignMessage({ campaignId: campaign.id, seq: allocateSeq(campaign.id), authorType: "player", userId: players[extra.who].user.id, characterId: players[extra.who].sheet.id, content: extra.text });
}
const playerSeq = allocateSeq(campaign.id);
insertCampaignMessage({
campaignId: campaign.id,
Expand All @@ -490,8 +556,15 @@ async function playRun(runNumber) {
const started = Date.now();
let thrown = null;
try {
// As the queue's own turn job does before it starts one
// (src/lib/dm/loop.ts): everything posted so far is this turn's, so the
// table wait counts no line twice once the turn ends.
tableWaitTurnStarted(campaign.id, playerSeq);
await startDmTurn(campaign.id);
await settleRolls(campaign.id);
// A reply owed to a group the scene was not with follows as a turn of
// its own, queued as this one ended (src/lib/dm/turn.ts sceneOwesReply).
await drainQueue(campaign.id);
} catch (error) {
thrown = error instanceof Error ? error.message : String(error);
}
Expand Down Expand Up @@ -522,6 +595,16 @@ async function playRun(runNumber) {
tools: calls.flatMap((call) => call.tools),
rolls: listRecentRolls(campaign.id, 500).length - rollsBefore,
encounter: Boolean(getActiveEncounter(campaign.id)),
// How many passages answered the beat, where the scene is, who is
// elsewhere, and what the server told the table about it.
passages: dm.length,
place: getCurrentLocation(campaign.id)?.name ?? "",
away: getParty(campaign.id).away.map((group) => `${group.ids.map((id) => getSheetById(id)?.name ?? id).join(" and ")} at ${group.place}`),
tableNotes: written.filter((message) => message.authorType === "system" && !message.content.startsWith(DM_HALTED_PREFIX)).map((message) => message.content),
narrations: dm.map((message) => String(message.content).replace(ROLL_MARKER, "").trim()),
// What each move_party of the beat's last turn was sent, and answered.
moves: (stored?.conversation ?? []).flatMap((message) => (Array.isArray(message.tool_calls) ? message.tool_calls : []).filter((call) => call?.function?.name === "move_party").map((call) => String(call.function.arguments).slice(0, 300))),
moveResults: (stored?.conversation ?? []).filter((message) => message.role === "tool" && /"location"/.test(String(message.content))).map((message) => String(message.content).slice(0, 600)),
empty,
cause: empty ? emptyCause(calls, rescues) : null,
rescues: rescues.map((rescue) => (rescue.ok ? "ok" : "empty")),
Expand All @@ -545,6 +628,9 @@ async function playRun(runNumber) {
turn.softFail ? `MISSED:${turn.softFail}` : "",
].filter(Boolean);
say(` run ${runNumber} ${turn.label.padEnd(10)} ${String(seconds).padStart(4)}s ${turn.calls} calls tools: ${turn.tools.join(", ") || "(none)"}${flags.length ? ` [${flags.join("; ")}]` : ""}`);
if (turn.away.length) {
say(` scene at ${turn.place || "(no place)"}; elsewhere: ${turn.away.join("; ")}; ${turn.passages} passage(s)`);
}
}

const encounter = getActiveEncounter(campaign.id);
Expand Down
Loading
Loading