8000 fix: spell saves, rests, strategy conquest and migrations, from the engine audit (part 4) by Mnehmos · Pull Request #117 · Mnehmos/mnehmos.rpg.mcp · GitHub
[go: up one dir, main page]

Skip to content

fix: spell saves, rests, strategy conquest and migrations, from the engine audit (part 4) - #117

Merged
Mnehmos merged 25 commits into
mainfrom
claude/practical-cannon-cel9je
Nov 10, 2026
Merged

Mnehmos merged 25 commits into
mainfrom
claude/practical-cannon-cel9je

Conversation

@Mnehmos
@Mnehmos Mnehmos commented Nov 10, 2026
Copy link
Copy Markdown
Owner

Audit pass over the parts of the engine not covered before: spell rules, rests, strategy, migrations and world generation. Every fix was written test-first.

Spells

  • Saves were rolled twice. The resolver rolled one generic save and baked it into the damage; the handler then had every target roll its own on top. When the hidden roll passed, Fireball did quarter damage to a target that saved and half to one that failed, and a save-for-none spell (Sacred Flame) was cancelled for everyone before any target rolled. Targets now save once, against the dice as rolled.
  • Wrong save DC. The handler's fallback DC assumed Intelligence and +2 proficiency for every class, and an operator-precedence slip could make it fractional. It now uses the caster's real DC (a level 5 cleric with WIS 18 was DC 10, is now DC 15).
  • Healing used Wisdom for every class. A bard with WIS 8 healed 1d8 - 1. It now uses the caster's own spellcasting ability.
  • Single-target spells could hit any number of creatures by passing several targetIds (or a comma-separated targetId). They now take one target, plus one per upcast slot level for leveled spells.
  • Spell attacks: a natural 1 always misses and a natural 20 always hits.

Rests

  • Hit dice were not tracked. A short rest could spend up to 20 dice, as often as you liked: free unlimited healing, always on a d8. A character now has one hit die per level in resourcePools.hit_dice, sized by class; spent dice stay spent and a long rest returns half (at least one).
  • travel_manage party long rest restored hit points only, leaving casters without spell slots. It now restores slots and hit dice, as rest_manage does.

Strategy

  • Conquest broke the control scale. A lopsided victory left the conqueror with control in the tens of thousands (the scale is 0-100; reproduced at 24,901), and one that landed exactly on zero left the region with no owner. Conquest now always transfers the region with control between 10 and 100.
  • Duplicate claims. A nation that claimed a region several times was entered once per claim: it could fight itself to farm control, and got extra rolls in a real contest. Claimants are counted once.
  • The conflict result now reports battle winner and region owner as separate fields; the processor no longer searches the log text for "conquered".
  • A nation can no longer propose an alliance with itself.

Migrations

  • A backfill ran on every database open. The statement that gives legacy parties a map position was not guarded, so a party deliberately left off the map was moved to (50, 50) by the next restart, deploy or pool eviction. It now runs only when the column is first added.
  • migrate() runs in one transaction, so a failure part-way leaves the database as it was.

World generation

No bugs found. Generation is deterministic for a seed, took 1.5 s end to end at the 1000x1000 maximum, and a fuzz of 336 runs across odd sizes, seeds and extreme options found no out-of-bounds or non-finite output.

One fix to my own earlier change (#114): the world cache was bounded by world count only, and a maximum-size world is about 100 MB in memory. It is now also bounded by total tiles (RPG_MAX_CACHED_WORLD_TILES, default 2,000,000).

Contract changes for rpg-mcp-live

  • Short rests are limited. rest_manage short and travel_manage rest spend at most the hit dice a character has left; with none left they heal nothing. Responses add hitDiceRemaining (and hitDiceRestored on a long rest). hitDieSize now reflects the class (d10 for a fighter) instead of always d8.
  • Single-target spells reject multiple targets with isError: true.
  • Save-based spells do more damage on average than before, because the hidden second save 8000 is gone.
  • Conflict events in strategy list [battleWinner, loser].

Found but not changed

  • Spell, healing and save rolls use unseeded Math.random, so unlike weapon attacks they are not reproducible from the encounter seed.
  • resolve_turn takes the turn number from the caller and can be run twice for the same turn, applying the economy twice.
  • A 1000x1000 world stores a snapshot of about 26 MB per world, with no limit on worlds per campaign.
  • There is no schema version; migrations infer state from which columns exist.

Testing

  • New: tests/server/spell-rules.test.ts, tests/server/rest-rules.test.ts, tests/engine/strategy/strategy-integrity.test.ts, tests/storage/migrations-safety.test.ts, plus cases in tests/server/world-manager.test.ts.
  • One existing expectation updated: the rest fixture has no class set, which defaults to fighter, so its hit die is d10.
  • Full suite locally: 2409 passed, 7 skipped, 3 failed. The 3 are tests/server/websocket.test.ts, which cannot bind :: in the sandbox this ran in; they pass in CI.

Note on history

The branch could not be force-pushed after the earlier PRs were squash-merged, so their history is recorded with an ours merge that leaves the tree unchanged. The diff against main is only this change.


Generated by Claude Code

claude added 25 commits November 9, 2026 20:42
…e server

An exploding one-sided die (1d1!) never stopped exploding, and dice counts
were unbounded, so one math_manage call could freeze or kill the process
for every campaign. Dice are now capped at 1000 dice of 1000 sides at every
parser, exploding dice need at least 2 sides, and exact distributions are
refused when too large to compute.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
subscribe_to_events left a callback pointing at the per-request HTTP
transport. The next combat event in any campaign made it reject with
'Not connected'; the unhandled rejection shut the process down, and the
shutdown path exited 0, so the host never restarted it.

- Crashes now exit 1; requested stops still exit 0.
- A subscriber whose connection is gone is dropped, not left to reject.
- Subscribers only receive events from their own campaign.
- On the stateless HTTP transport, where nothing can be pushed after the
  response, subscribe_to_events makes no subscription and points the
  caller at poll_events.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
- Moves are validated (destination, path, remaining movement) before
  opportunity attacks resolve. A refused move used to cost the mover hit
  points and the attacker its reaction, then report success. It is now an
  error, so the call rolls back.
- Negative damage is rejected; it was subtracted as healing with no cap
  at max HP (a 7 HP goblin reached 107). Dice damage with a penalty
  floors at zero, and applyDamage/heal ignore negative amounts.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
npm audit fix: clears the advisories in @modelcontextprotocol/sdk and its
transitive dependencies. The remaining zod advisory needs a breaking move
to zod 4 and is left for a separate change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
- An attack outside the attacker's turn now resolves as its reaction, one
  per round, and no longer spends its action. It used to be a warning
  only, so a combatant could attack any number of times off turn.
- A target must be within reach: 5ft for melee, or the new optional
  `range` (feet) for ranged and reach attacks. Checked only when both
  combatants have a position.
- Caller-supplied attackBonus, dc and damage are bounded (-20..30, 1..40,
  1000 damage), so one call can no longer decide the outcome.
- Opportunity attacks use the attacker's attack bonus and the mover's AC
  when known instead of deriving both from initiative.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
…g call

Pool eviction closed the least recently used handle even when a call was
mid-transaction on it, and DELETE /campaign did the same. Eviction now
skips handles that are in use, and erasure waits for the call in flight.
The pool cap can be set with RPG_MAX_OPEN_DATABASES (default 64).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Cached worlds were keyed by a guessable id alone and never evicted, so one
campaign could read another's world by id and memory grew for the life of
the process. Entries are now keyed by the verified tenant too, and the
cache keeps the most recently used worlds (RPG_MAX_CACHED_WORLDS, default
32); the rest are restored from their database snapshot on demand.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
…ng it

A hosted campaign that failed its integrity check was quarantined and
swapped for an empty database, so the game looked deleted and play
continued into a second file. Campaign databases now fail to open and the
files are left untouched. Local single-user databases keep the
quarantine-and-recreate behaviour.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
audit_logs stored arguments and results for every tool call and was never
pruned. It now keeps the newest RPG_AUDIT_LOG_MAX_ROWS rows (default 5000).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
… URLs

better-sqlite3 12 requires Node 20+, so CI no longer tests 18 and
package.json declares the engine. The HTTP transport builds a server per
request and logged tool registration every time; it now logs once.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
The tool's outer input schema dropped the new range argument before it
reached the handler, so a ranged attack could not be made over MCP.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
The earlier commits on this branch were squash-merged as #113. This merge
keeps the current tree exactly as it is; it only records that history so
the branch can be pushed without rewriting it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
npm audit reported a memory-exhaustion advisory fixed only in zod 4.

- z.record() takes an explicit key schema.
- Object defaults that relied on inner defaults use .prefault(), which
  parses the default as zod 3 did (zod 4's .default() returns it as is).
- UUID fields use z.guid() to keep zod 3's lenient matching.
- load_tool_schema's summarizer read zod 3 internals; it now reads zod 4
  definitions and produces byte-identical output for all 36 tools.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Tree unchanged. The earlier commits on this branch were squash-merged as
#113 and #114.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
A missed spell attack returned a bare 'casts Fire Bolt!' with no attack
roll, no dice and no miss, so the caller could not tell a miss from a hit
for zero damage. It now uses the same formatter as a hit. The fire bolt
scaling test depended on three unseeded attacks all hitting and was
retried to hide that; it is now deterministic and the retry is gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
- Live replay took its model straight from the caller, so it bypassed the
  no-pro-model rule that invoke enforces. It now refuses a pro variant
  before calling the provider.
- timeoutMs had no upper limit. The provider call runs inside the
  campaign's unit of work, holding its lock and an open transaction, so a
  huge timeout could stall a campaign. New and updated agents are capped
  at 120s; rows stored earlier are clamped when used.
- An abort that landed while reading the response body escaped as a bare
  AbortError and was recorded as a generic error; it is now a timeout.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Tree unchanged. The earlier commits on this branch were squash-merged as
#113, #114 and #115.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
…bility

- Save-based spells were resolved twice: the resolver rolled a generic
  save and baked it into the damage, then every target rolled its own on
  top. Fireball did quarter damage to a target that saved whenever the
  hidden roll also passed, and a save-for-none spell could be cancelled
  for everyone before any target rolled. Targets now save once, against
  the dice as rolled.
- The handler's fallback save DC assumed Intelligence and +2 proficiency
  for every class and could be fractional; it now uses the caster's DC.
- Healing added the Wisdom modifier for every class; it now uses the
  caster's own spellcasting ability.
- A single-target spell could be aimed at any number of creatures.
- On a spell attack a natural 1 always misses and a natural 20 always hits.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
…claimant once

- A lopsided victory left the conqueror with control in the tens of
  thousands (the scale is 0-100), and one that landed exactly on zero
  left the region with no owner. Conquest now always transfers the region
  with control between 10 and 100.
- A nation that claimed a region several times was entered once per claim:
  it could fight itself to farm control, and got extra rolls in a real
  contest. Claimants are now counted once.
- The result says who won the battle and who holds the region as separate
  fields instead of the processor sniffing the log text for 'conquered'.
- A nation can no longer propose an alliance with itself.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
…hing

- The backfill that gives legacy parties a map position ran on every
  database open, not just when the column was added. A party left off the
  map was moved to (50, 50) by the next restart, deploy or pool eviction.
- migrate() now runs in one transaction, so a failure part-way leaves the
  database as it was instead of half-migrated.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
A maximum-size world is about 100 MB in memory, so a cap of 32 worlds
could still exhaust the heap. The cache now also limits total tiles
(RPG_MAX_CACHED_WORLD_TILES, default 2,000,000) and always keeps the
world just created.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
- Hit dice were not tracked: a short rest could spend up to 20 dice, as
  often as you liked, for free unlimited healing, always on a d8. A
  character now has one hit die per level in resourcePools.hit_dice, of
  its class's size; spent dice stay spent, and a long rest returns half.
- travel_manage's party long rest restored hit points only, leaving
  casters without their spell slots. It now does what rest_manage does.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Tree unchanged. The earlier commits on this branch were squash-merged as
#113 to #116.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
@coderabbitai
coderabbitai Bot commented Nov 10, 2026 •
Copy link
Copy Markdown

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@Mnehmos
Mnehmos marked this pull request as ready for review November 10, 2026 14:52
@Mnehmos
Mnehmos merged commit 8973a46 into main Nov 10, 2026
3 checks passed
@chatgpt-codex-connector
chatgpt-codex-connector Bot commented Nov 10, 2026 •
Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T14:54:23.602500Z 0fa9958 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0fa9958939

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1847 to +1849
if (spell.targetType === 'creature' || spell.targetType === 'self') {
const allowed = 1 + Math.max(0, spell.level > 0 ? effectiveSlotLevel - spell.level : 0);
if (allTargetIds.length > allowed) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Derive target limits from each spell's targeting rules

At their base slot levels, this rejects every multi-target cast of Scorching Ray and Magic Missile, even though both are registered as targetType: 'creature' and create three projectiles. In particular, Scorching Ray's description in spell-database.ts explicitly permits multiple targets. targetType describes the kind of target, not its count, so it cannot distinguish these spells from genuine single-target spells. Use spell-specific target limits rather than imposing one target on all creature-targeted spells.

Useful? React with 👍 / 👎.

Comment on lines +36 to +38
const max = Math.max(1, Math.trunc(character.level || 1));
const stored = character.resourcePools?.[HIT_DICE_POOL];
const current = stored ? Math.min(max, Math.max(0, Math.trunc(stored.current))) : max;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Add newly earned hit dice when the character levels up

Once a character has a persisted hit-dice pool, increasing their level raises max but never adds the newly earned dice to current. For example, a level-1 character who spends their die and then reaches level 2 still has zero dice available at their next short rest. handleLevelUp in character-manage.ts updates the character's level without updating this pool, so neither path grants the additional die. Account for the increase from the stored pool's maximum, or update the pool during level-up, while preserving previously spent dice.

Useful? React with 👍 / 👎.

Mnehmos pushed a commit that referenced this pull request Nov 10, 2026
Tree unchanged. The earlier commits on this branch were squash-merged as
#113 to #117.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0