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
87 changes: 87 additions & 0 deletions scripts/test-enforce-ai-gates.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,93 @@ await test("damage_enemy from a hazard takes dice from the AI, never a bare numb
assert.equal(kit.enemy(enemy.id).currentHp, 88);
});

// The two calls the tools offer for a hazard's harm: request_roll, then the
// total. The gate stamped the paying roll with the creature's id, the mark of
// a blow the server had landed there, and the double-apply guard answered
// the very call the roll paid for with "already applied".
await test("A total the AI rolled for a hazard and then sent for a creature lands on it once: it loses the hit points, and the same number sent again is refused.", async () => {
const enemy = await stage();
const turn = createDmTurn(world.campaignId, []);
const call = (name, args) => invokeEngine(world.campaign(), { kind: "ai", turnId: turn.id }, { name, args });
world.dice(5);
const rolled = await call("request_roll", { kind: "damage", expression: "1d8", reason: "burning oil" });
world.clearDice();
assert.equal(rolled.ok, true, rolled.error);
const oil = { enemyId: enemy.id, amount: 5, type: "fire", source: "hazard", reason: "burning oil" };
const first = await call("apply_damage", oil);
assert.equal(first.ok, true, first.error);
assert.doesNotMatch(JSON.stringify(first), /already applied/, "the hazard's own total was taken for a blow already landed");
assert.equal(kit.enemy(enemy.id).currentHp, 95, "the oil's 5 did not land");
const [paid] = getDmTurn(turn.id).rollIds.map((id) => getRoll(id));
assert.equal(paid.applied, true, "the total is still unspent");
assert.equal(paid.targetEnemyId, null, "a total that paid for a number reads as a blow the server landed");
const again = await call("apply_damage", oil);
assert.equal(again.ok, false, "one roll paid for two hits");
assert.match(String(again.error), /rolled by the server, never written/, "refused, but not by the number gate");
assert.equal(kit.enemy(enemy.id).currentHp, 95);
});

await test("A total the AI rolled and then sent for a character is no blow that character dealt: the fight's card counts nothing for the poison that hurt them.", async () => {
await stage();
const call = aiTurn();
world.dice(5);
const rolled = await call("request_roll", { characterId: hero.id, kind: "damage", expression: "1d8", reason: "poison" });
world.clearDice();
assert.equal(rolled.ok, true, rolled.error);
const poison = await call("apply_damage", { characterId: hero.id, amount: 5, type: "poison" });
assert.equal(poison.ok, true, poison.error);
assert.equal(hp(), 35);
const ended = await world.invoke("end_encounter", { outcome: "victory" });
assert.equal(ended.ok, true, ended.error);
const line = getLatestEndedEncounter(world.campaignId).summaryCard.fighters.find((fighter) => fighter.characterId === hero.id);
assert.ok(line, "the hero has no line on the card");
assert.equal(line.taken, 5);
assert.equal(line.dealt, 0, "the poison's 5 reads as damage the hero dealt");
});

// The guard reads as it did: the stamp of a blow the server landed. That
// blow's own number sent bare never reaches it on an AI's turn, since the
// number gate refuses it first. What reaches it is harm the server rolled
// that comes to the same total for the same creature, sent here as dice (a
// total rolled with request_roll that comes to the same reaches it too).
// Pinned as it is on both sides of the fix, not judged.
await test("The double-apply guard reads as it did: after a blow the server landed, its number sent bare is refused by the number gate, and dice sent for the same creature that come to the same total are answered as already applied.", async () => {
await kit.endFight();
world.patch(hero.id, { currentHp: 40, tempHp: 0, conditions: [], conditionMeta: {}, equipment: [{ name: "Longsword", qty: 1, equipped: true }] });
try {
await kit.fight(1, { heroFaces: { [hero.id]: 19 } });
const [enemy] = world.enemies();
kit.setEnemy(enemy.id, { maxHp: 100, currentHp: 100, ac: 10 });
kit.place(hero.id, 5, 5);
kit.place(enemy.id, 5, 6);
world.say("player", "I swing at the goblin.", world.sheet(hero.id));
const turn = createDmTurn(world.campaignId, []);
const call = (name, args) => invokeEngine(world.campaign(), { kind: "ai", turnId: turn.id }, { name, args });
// The d20 (a hit on AC 10), then the sword's d8.
world.dice(15, 4);
const swing = await call("pc_attack", { characterId: hero.id, targetEnemyId: enemy.id });
world.clearDice();
assert.equal(swing.ok, true, swing.error);
const blow = getDmTurn(turn.id).rollIds.map((id) => getRoll(id)).find((roll) => roll?.kind === "damage" && roll.applied && roll.targetEnemyId === enemy.id);
assert.ok(blow, "the swing landed no damage the server stamped on the creature");
const before = kit.enemy(enemy.id).currentHp;
assert.equal(before, 100 - blow.total);
const cut = { enemyId: enemy.id, type: "slashing", source: "hazard", reason: "the same cut, sent again" };
const bare = await call("apply_damage", { ...cut, amount: blow.total });
assert.equal(bare.ok, false, "the blow's number paid for a second hit");
assert.match(String(bare.error), /rolled by the server, never written/, "refused, but not by the number gate");
world.dice(4);
const dice = await call("apply_damage", { ...cut, dice: blow.expression });
world.clearDice();
assert.equal(dice.ok, true, dice.error);
assert.match(JSON.stringify(dice), /already applied/, "the call was not answered that the damage had landed");
assert.equal(kit.enemy(enemy.id).currentHp, before, `the blow of ${blow.total} landed a second time`);
} finally {
world.clearDice();
world.patch(hero.id, { equipment: [] });
}
});

await test("split_damage from the AI needs the server's roll.", async () => {
const enemy = await stage();
const out = await aiTurn()("split_damage", { amount: 20, type: "fire", targets: [{ enemyId: enemy.id, share: "full" }, { characterId: hero.id, share: "half" }] });
Expand Down
32 changes: 25 additions & 7 deletions src/lib/db/rolls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,13 @@ export type StoredRoll = {
breakdown: RollResult;
visibility: RollVisibility;
messageId: string | null;
// Damage rolls only: the enemy the server applied this roll's total to,
// set together with `applied` (the damage_enemy double-apply guard).
// Damage rolls only: the enemy the server itself landed this roll's total
// on, set together with `applied` (the damage_enemy double-apply guard).
// Nothing else is written here: a roll that is only used up names nobody.
targetEnemyId: string | null;
// Spent: the server applied its total, or the engine threw it inside a
// call of its own or as a roll card landed (markRollSpent), so it pays for
// no number sent later.
// Spent: the server applied its total, the engine threw it inside a call
// of its own or as a roll card landed (markRollSpent), or it paid for what
// an AI GM sent (markRollPaid), so it pays for no number sent later.
applied: boolean;
// Attack and damage rolls: who rolled. Null when nobody did (a fall), for
// the roll tools' rolls, and for rolls stored before it was recorded.
Expand Down Expand Up @@ -104,14 +105,31 @@ function mapRoll(row: RollRow): StoredRoll {
};
}

// Stamp a damage roll as server-applied to a specific enemy; the
// damage_enemy double-apply guard reads these.
// Stamp a damage roll as landed by the server on a specific enemy. The
// damage_enemy double-apply guard, the after-fight card, the evidence Ask
// reads (src/lib/dm/ask.ts) and the swarm's die taken back
// (authored-spend-more.ts swarmDieBack) read these. Only for a blow the
// server lands itself as its dice resolve: a roll that is used up some other
// way is stamped below, with no target.
export function markRollApplied(rollId: string, targetEnemyId: string) {
getDatabase()
.prepare(`UPDATE rolls SET applied = 1, target_enemy_id = ? WHERE id = ?`)
.run(targetEnemyId, rollId);
}

// Stamp a roll as having paid for what an AI GM sent: the total behind a
// bare damage or healing number, or the check behind a trap's hold lifted
// (src/lib/dm/ai-gate.ts). It names no target. The gate used to stamp a
// paying total with whatever its number was sent for, in the column that
// says where the server landed a blow. Sent for a creature by its id, the
// total then read to the damage_enemy guard as a blow already landed there,
// and the hazard it was rolled for did nothing. And whatever it was sent
// for, the after-fight card counted it as damage dealt by the character the
// roll was made for: poison a hero took read as damage that hero dealt.
export function markRollPaid(rollId: string) {
getDatabase().prepare(`UPDATE rolls SET applied = 1 WHERE id = ?`).run(rollId);
}

// Stamp a damage or custom roll the engine threw and used inside one of its
// own calls (a spell's damage, a hazard's, the dice a damage or healing tool
// was sent) as spent, so its total never pays for a number an AI GM sends
Expand Down
8 changes: 5 additions & 3 deletions src/lib/dm/ai-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { splitParts } from "@/lib/dm/action-parts-logic";
import type { Campaign } from "@/lib/db/campaigns";
import type { DmTurn } from "@/lib/db/dm-turns";
import { getActiveEncounter } from "@/lib/db/encounters";
import { getRoll, markRollApplied, markRollSpent } from "@/lib/db/rolls";
import { getRoll, markRollPaid, markRollSpent } from "@/lib/db/rolls";
import { awayRefusal, canCrossAway } from "@/lib/dm/fight-away-logic";
import { isValidExpression } from "@/lib/dice";
import { spellFactsFor } from "@/lib/content";
Expand Down Expand Up @@ -270,7 +270,9 @@ function number(ctx: GateContext, args: Record<string, unknown>, what: "damage"
if (!rolled) {
return { result: AI_NUMBER_REFUSAL(what) };
}
markRollApplied(rolled.id, targetId || "split");
// Paid, not landed: the call let through below is what lands it, and the
// stamp names no target (src/lib/db/rolls.ts markRollPaid).
markRollPaid(rolled.id);
return { args: JSON.stringify(args) };
}

Expand Down Expand Up @@ -344,6 +346,6 @@ function escapeRolled(ctx: GateContext, sheet: CharacterSheet, condition: string
if (!roll) {
return false;
}
markRollApplied(roll.id, `escape:${hold.trap}`.slice(0, 80));
markRollPaid(roll.id);
return true;
}
7 changes: 4 additions & 3 deletions src/lib/dm/encounter-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,10 @@ export function computeEncounterSummary(input: {
// never applied (a miss, a spell resisted) does not. Only a stamp that
// names what the total landed on says that: a roll the engine spent
// inside its own call (src/lib/db/rolls.ts markRollSpent: a fall, a
// trap, the dice an AI GM sent for a character's damage) is stamped with
// no target, and counted here it read as damage dealt by the character
// it hurt.
// trap, the dice an AI GM sent for a character's damage), or a total an
// AI GM rolled first and then sent (markRollPaid), is stamped with no
// target, and counted here it read as damage dealt by the character it
// hurt.
if (roll.kind === "damage" && roll.applied && roll.targetEnemyId) {
line.dealt += Math.max(0, roll.total);
}
Expand Down
Loading