8000 fix(combat): surface off-turn advisory when actorId isn't on turn by Mnehmos · Pull Request #59 · Mnehmos/mnehmos.rpg.mcp · GitHub
[go: up one dir, main page]

Skip to content

Navigation Menu

Merged
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
5 changes: 4 additions & 1 deletion src/schema/encounter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,10 @@ export const TokenSchema = z.object({
// Combat Stats for Auto-Resolution
ac: z.number().optional().describe('Armor Class for auto-resolution'),
attackDamage: z.string().optional().describe('Default attack damage (e.g., "1d6+2")'),
attackBonus: z.number().optional().describe('Default attack bonus')
attackBonus: z.number().optional().describe('Default attack bonus'),
// Lair-action ownership — must be persisted so loadState can rebuild the
// LAIR slot in turnOrder (see encounter.repo.ts loadState lookup).
hasLairActions: z.boolean().optional().describe('Whether this token owns lair actions')
});

export type Token = z.infer<typeof TokenSchema>;
Expand Down
38 changes: 38 additions & 0 deletions src/server/handlers/combat-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,8 @@ Example (use real UUID from context for player character!):
hp: z.number().int().nonnegative(), // Allow 0 HP for dying characters
maxHp: z.number().int().positive(),
isEnemy: z.boolean().optional().describe('Whether this is an enemy (auto-detected if not set)'),
hasLairActions: z.boolean().optional()
.describe('Adds a LAIR slot at initiative 20 to the turn order'),
conditions: z.array(z.string()).default([]),
position: z.object({ x: z.number(), y: z.number(), z: z.number().optional() }).optional()
.describe('CRIT-003: Spatial position for movement (x, y coordinates)'),
Expand Down Expand Up @@ -1094,6 +1096,7 @@ export async function handleCreateEncounter(args: unknown, ctx: SessionContext)
initiative: 0, // Will be rolled
initiativeBonus: p.initiativeBonus ?? 0,
isEnemy: p.isEnemy ?? false,
hasLairActions: p.hasLairActions ?? false,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locate encounter repository implementation:"
fd -i 'encounter.repo.ts' src

echo
echo "Inspect create/load/save mappings for lair-related fields:"
rg -n -C4 'create\\(|loadState\\(|saveState\\(|hasLairActions|lairOwnerId|turnOrder|activeTokenId|tokens' src/server src/storage

Repository: Mnehmos/mnehmos.rpg.mcp

Length of output: 402


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# First, check the file size and read lines around 1099 and 1131-1145
echo "=== Reading combat-handlers.ts around line 1099 ==="
wc -l src/server/handlers/combat-handlers.ts

echo
echo "=== Context around line 1099 ==="
sed -n '1090,1110p' src/server/handlers/combat-handlers.ts

echo
echo "=== Context around lines 1131-1145 (persistence mapping) ==="
sed -n '1125,1150p' src/server/handlers/combat-handlers.ts

Repository: Mnehmos/mnehmos.rpg.mcp

Length of output: 2048


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read the encounter repository to understand persistence
echo "=== Reading encounter.repo.ts ==="
wc -l src/storage/repos/encounter.repo.ts

echo
echo "=== Search for create method and persistence mappings ==="
rg -n "create\(" src/storage/repos/encounter.repo.ts -A 20

echo
echo "=== Search for loadState method ==="
rg -n "loadState" src/storage/repos/encounter.repo.ts -A 15

echo
echo "=== Search for hasLairActions in storage layer ==="
rg -n "hasLairActions" src/storage src/server

Repository: Mnehmos/mnehmos.rpg.mcp

Length of output: 3477


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Full loadState method in encounter.repo.ts ==="
sed -n '130,190p' src/storage/repos/encounter.repo.ts

echo
echo "=== Check token schema/interface definition ==="
rg -n "interface.*Token|type.*Token" src/storage src/server --type-list | head -20
rg -n "tokens:" src/storage/repos/encounter.repo.ts -B5 -A5

Repository: Mnehmos/mnehmos.rpg.mcp

Length of output: 2904


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Verify what token fields are actually expected in schema ==="
rg -n "EncounterSchema\|TokenSchema" src/storage -A 30 | head -60

Repository: Mnehmos/mnehmos.rpg.mcp

Length of output: 131


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Search for token/encounter schema definitions ==="
rg -n "type.*Token|interface.*Token|Encounter.*=" src --type ts -A 10 | head -80

echo
echo "=== Look for Zod schema definitions ==="
rg -n "z\.object|EncounterSchema\|TokenSchema" src/storage -A 20 | head -100

echo
echo "=== Check what CombatParticipant interface includes ==="
rg -n "interface CombatParticipant|type CombatParticipant" src -A 20

Repository: Mnehmos/mnehmos.rpg.mcp

Length of output: 6078


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Read full TokenSchema definition ==="
sed -n '80,120p' src/schema/encounter.ts

echo
echo "=== Read full EncounterSchema ==="
sed -n '140,165p' src/schema/encounter.ts

echo
echo "=== Check if hasLairActions is in TokenSchema ==="
rg -n "hasLairActions" src/schema/encounter.ts

Repository: Mnehmos/mnehmos.rpg.mcp

Length of output: 2470


Add hasLairActions to token persistence mapping.

Line 1099 sets hasLairActions on in-memory participants, but the TokenSchema (src/schema/encounter.ts) does not define this field, and the create-time persistence mapping (lines 1131–1145) omits it. When loadState() reloads the encounter, it searches for participants.find((p: any) => p.hasLairActions) (encounter.repo.ts:160), which will always be undefined since the field was never persisted. This causes lair turn order to be lost across session reloads, breaking lair action functionality.

Add hasLairActions: z.boolean().optional() to TokenSchema and include it in the token persistence mapping in the repo.create() call.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/server/handlers/combat-handlers.ts` at line 1099, The TokenSchema is
missing hasLairActions and the repo.create() token mapping omits it, so persists
never store that flag; add hasLairActions: z.boolean().optional() to the
TokenSchema definition and include hasLairActions in the token fields passed to
repo.create() (the same object where other token props are mapped) so that
participants loaded later can be found by the existing participants.find((p:
any) => p.hasLairActions) lookup and lair action turn order is preserved.

conditions: p.conditions || [],
position: p.position,
resistances: p.resistances,
Expand Down Expand Up @@ -1131,6 +1134,7 @@ export async function handleCreateEncounter(args: unknown, ctx: SessionContext)
initiativeBonus: p.initiativeBonus,
initiative: p.initiative, // Store rolled initiative
isEnemy: p.isEnemy, // Store enemy flag
hasLairActions: p.hasLairActions, // PR #59 follow-up: persist lair flag so loadState can rebuild the LAIR slot
hp: p.hp,
maxHp: p.maxHp,
conditions: p.conditions,
Expand Down Expand Up @@ -1239,6 +1243,36 @@ export async function handleExecuteCombatAction(args: unknown, ctx: SessionConte
getCombatManager().create(`${ctx.sessionId}:${parsed.encounterId}`, engine);
}

// Turn-identity advisory (issue #49). Every action routed through this
// handler (attack / cast_spell / move / dash / dodge / help / heal /
// disengage / ready) is an on-turn action. If actorId doesn't match the
// active participant, surface a warning so the caller can see the
// misuse — we don't throw because reactions aren't modeled yet and
// some legitimate flows could be disrupted. A stricter mode can be
// layered on top later.
let turnWarning: string | undefined;
{
const liveState = engine.getState();
if (liveState) {
const activeId = liveState.turnOrder[liveState.currentTurnIndex];
if (
activeId &&
parsed.actorId !== activeId &&
// Ignore if the supplied actorId isn't a real participant —
// the action handler will produce a clearer error downstream.
liveState.participants.some((p) => p.id === parsed.actorId)
) {
// LAIR turns are still off-turn for participant actions: only
// the lair_action tool may resolve during initiative-20 LAIR.
const isLair = activeId === 'LAIR';
const activeLabel = isLair
? 'LAIR action'
: (liveState.participants.find((p) => p.id === activeId)?.name ?? activeId);
turnWarning = `off_turn_action: ${parsed.actorId} acting during ${activeLabel}'s turn`;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

let result: CombatActionResult | undefined;
let output = '';

Expand Down Expand Up @@ -2025,6 +2059,10 @@ export async function handleExecuteCombatAction(args: unknown, ctx: SessionConte
output += `\n\n<!-- STATE_JSON\n${JSON.stringify(stateJson)}\nSTATE_JSON -->`;
}

if (turnWarning) {
output += `\n\n⚠️ ${turnWarning}\n`;
}

return {
content: [
{
Expand Down
98 changes: 98 additions & 0 deletions tests/server/consolidated/combat-action.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,104 @@ describe('combat_action consolidated tool', () => {
});
});

// Regression for issue #49: off-turn actions used to succeed silently,
// letting a caller stack multiple attacks from different actors in one
// round. Now the response surfaces an off_turn_action warning.
describe('off-turn advisory', () => {
it('warns when actorId does not match the current-turn participant', async () => {
// Test setup gave hero-1 initiativeBonus 10 vs goblin-1's 1, so
// hero-1 is on turn. Fire an attack as the goblin instead.
const result = await handleCombatAction({
action: 'attack',
encounterId: testEncounterId,
actorId: 'goblin-1',
targetId: 'hero-1',
attackBonus: 3,
damage: 4
}, ctx);

expect(result.content[0].text).toMatch(/off_turn_action/);
});

it('does not warn when actorId is the current-turn participant', async () => {
const result = await handleCombatAction({
action: 'attack',
encounterId: testEncounterId,
actorId: 'hero-1',
targetId: 'goblin-1',
attackBonus: 5,
damage: 8
}, ctx);

expect(result.content[0].text).not.toMatch(/off_turn_action/);
});

// Reviewer follow-up on PR #59: hasLairActions wasn't being persisted,
// so loadState() couldn't rebuild the LAIR slot in turnOrder after a
// restart. The lair turn would silently disappear.
it('persists hasLairActions so LAIR survives a loadState round-trip', async () => {
const { handleCreateEncounter } = await import('../../../src/server/handlers/combat-handlers.js');
const { EncounterRepository } = await import('../../../src/storage/repos/encounter.repo.js');
const lairCtx = { sessionId: `lair-persist-${randomUUID()}` };

const create = await handleCreateEncounter({
seed: 'lair-persist-test',
participants: [
{ id: 'pc', name: 'Hero', initiativeBonus: 0, hp: 30, maxHp: 30, isEnemy: false, position: { x: 0, y: 0 } },
{ id: 'dragon', name: 'Dragon', initiativeBonus: 0, hp: 100, maxHp: 100, isEnemy: true, hasLairActions: true, position: { x: 5, y: 5 } }
]
}, lairCtx);
const eid = (create.content[0].text.match(/encounter-[\w-]+/) || [])[0]!;

const repo = new EncounterRepository(getDb(':memory:'));
const loaded = repo.loadState(eid);
expect(loaded).not.toBeNull();
expect(loaded.turnOrder).toContain('LAIR');
const dragon = loaded.participants.find((p: { id: string }) => p.id === 'dragon');
expect(dragon?.hasLairActions).toBe(true);
});

// Reviewer follow-up on PR #59: previously the warning was suppressed
// when the active turn slot was 'LAIR', so a participant could still
// act mid-LAIR-turn without any signal. The warning should fire.
it('warns when a participant acts during a LAIR turn', async () => {
const { handleCreateEncounter, handleExecuteCombatAction } =
await import('../../../src/server/handlers/combat-handlers.js');
const lairCtx = { sessionId: `lair-test-${randomUUID()}` };

// Construct an encounter with a LAIR-bearing creature so that the
// turn order includes a 'LAIR' slot at initiative 20.
const create = await handleCreateEncounter({
seed: 'lair-warning-test',
participants: [
{ id: 'pc', name: 'Hero', initiativeBonus: 0, hp: 30, maxHp: 30, isEnemy: false, position: { x: 0, y: 0 } },
{ id: 'dragon', name: 'Dragon', initiativeBonus: 0, hp: 100, maxHp: 100, isEnemy: true, hasLairActions: true, position: { x: 5, y: 5 } }
]
}, lairCtx);
const lairEncounterId = (create.content[0].text.match(/encounter-[\w-]+/) || [])[0]!;

// Force the active slot to LAIR by advancing turns until we hit it.
const { getCombatManager } = await import('../../../src/server/state/combat-manager.js');
const engine = getCombatManager().get(`${lairCtx.sessionId}:${lairEncounterId}`)!;
const state = engine.getState()!;
const lairIndex = state.turnOrder.indexOf('LAIR');
expect(lairIndex).toBeGreaterThanOrEqual(0);
state.currentTurnIndex = lairIndex;

// Now PC tries to act — should warn even though the active slot is LAIR.
const acted = await handleExecuteCombatAction({
encounterId: lairEncounterId,
action: 'attack',
actorId: 'pc',
targetId: 'dragon',
attackBonus: 3,
damage: 5
}, lairCtx);
expect(acted.content[0].text).toMatch(/off_turn_action/);
expect(acted.content[0].text).toMatch(/LAIR action/);
});
});

describe('attack action', () => {
it('should execute an attack', async () => {
const result = await handleCombatAction({
Expand Down
Loading
0