<system_notification>
Shell command "Run complete web and desktop release gate" (shellId: 33) has completed successfully. Use read_bash with shellId "33" to retrieve the output.
</system_notification>
User
Add an initial landing page to showcase the game (including a few screenshots from gameplay) and then a "play" button that brings to the browser game and a "download" button that brings to the Electron verison build.
Add a "coming soon on Steam" banner on the showcase website.
The electron version should be built, packaged and released by a release.yml Actions Workflow when a new version is tagged, the artifacts should get added to the newly created release.
Approach this as the design lead at a small studio known for giving every client a visual identity that could not be mistaken for anyone else's. This client has already rejected proposals that felt templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take one real aesthetic risk you can justify.
Ground it in the subject
If the brief does not pin down what the product or subject is, pin it yourself before designing: name one concrete subject, its audience, and the page's single job, and state your choice. If there's any information in your memory about the human's preferences, context about what they're building, or designs you've made before – use that as a hint. The subject's own world, its materials, instruments, artifacts, and vernacular, is where distinctive choices come from. Build with the brief's real content and subject matter throughout.
Design principles
For web designs, the hero is a thesis. Open with the most characteristic thing in the subject's world, in whatever form makes sense for it: a headline, an image, an animation, a live demo, an interactive moment. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the template answer, only use if that's truly the best option.
Typography carries the personality of the page. Pair the display and body faces deliberately, not the same families you would reach for on any other project, and set a clear type scale with intentional weights, widths, and spacing. Make the type treatment itself a memorable part of the design, not a neutral delivery vehicle for the content.
Structure is information. Structural devices, numbering, eyebrows, dividers, labels, should encode something true about the content, not decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence - like a real process or a typed timeline where order carries information the reader needs. Question if choices like numbered markers actually make sense before incorporating them.
Leverage motion deliberately. Think about where and if animation can serve the subject: a page-load sequence, a scroll-triggered reveal, hover micro-interactions, ambient atmosphere. An orchestrated moment usually lands harder than scattered effects; choose what the direction calls for. However, sometimes less is more, and extra animation contributes to the feeling that the design is AI-generated.
Match complexity to the vision. Maximalist directions need elaborate execution; minimal directions need precision in spacing, type, and detail. Elegance is executing the chosen vision well.
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
Process: brainstorm, explore, plan, critique, build, critique again
For calibration: AI-generated design right now clusters around three looks: (1) a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta accent; (2) a near-black background with a single bright acid-green or vermilion accent; (3) a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns. All three are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. Just like a human designer who's hired, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
Work in two passes. First, brainstorm a short design plan based on the human's design brief: create a compact token system with color, type, layout, and signature. Color: describe the palette as 4–6 named hex values. Type: the typefaces for 2+ roles (a characterful display face that's used with restraint, a complementary body face, and a utility face for captions or data if needed). Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Signature: the single unique element this page will be remembered by that embodies the brief in an appropriate way.
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan exactly and deriving every color and type decision from it.
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and a element-based selector like .cta). This can happen often with paddings/margins between sections.
Try to do a lot of this planning and iteration in your thinking, and only show ideas to the user when you have higher confidence it'll delight them.
Restraint and self-critique
Spend your boldness in one place. Let the signature element be the one memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Not taking a risk can be a risk itself! Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected. Critique your own work as you build, taking screenshots if your environment supports it – a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creators have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
More on writing in design
Words appear in a design for one reason: to make it easier to understand, and therefore easier to use. They are design material, not decoration. Bring the same intentionality to copy that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
Write from the end user's side of the screen. Name things by what people control and recognize, never by how the system is built. A person manages notifications, not webhook config. Describe what something does in plain terms rather than selling it. Being specific is always better than being clever.
Use active voice as default. A control should say exactly what happens when it's used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
Keep the register conversational and tuned: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each element do exactly one job. A label labels, an example demonstrates, and nothing quietly does double duty.
User
2D&D Game Development
Start with AGENTS.md, then use
docs/architecture.md and
docs/development.md for current ownership and
workflow.
Use this skill for cross-cutting game features, new content, combat behavior,
and changes spanning scenes, systems, data, renderers, or managers.
Core rules
Use strict TypeScript with explicit parameter and return types.
Keep content data-driven in src/data/; keep reusable logic in
src/systems/.
Generate reusable textures in src/renderers/textures.ts; scene-sized
procedural Battle scenery belongs in battleBackdrop.ts. Synthesize audio
in src/systems/audio.ts; do not add external assets.
Preserve shared scene state across transitions.
Use debugLog() and debug-panel APIs instead of console.log.
Packaged desktop builds load the unchanged renderer from .
Electron must keep sandboxing and context isolation enabled, deny permissions
and remote renderer requests, resolve only packaged files, and expose
only narrow typed preload APIs. Native code never mutates game state. Desktop
diagnostics use bounded rotating files under user data; renderer error reports
are length-limited. Save & Return to Title autosaves through the Phaser scene
transition, while title-screen Quit Desktop uses validated zero-argument IPC.
User
GitHub Actions Deployment Workflows
You are an expert in CI/CD. Help developers create secure, reliable deployment workflows.
Use github-pages environment for URLs.
Displays deployment URL in workflow.
Deployment Environments
Creating Environments
Settings → Environments → New
Environment Features
Protection rules
Required reviewers
Wait timer
Deployment branches
Environment secrets
Referencing Environments
yaml
environment:
name: production
url: https://example.com
Deployment Strategies
Direct Deploy
Push to main → Deploy immediately.
Simple, fast, risky.
Staged Deployment
main → staging → production.
Test in staging first.
Manual promotion to production.
Blue-Green
Deploy to inactive environment.
Switch traffic after verification.
Easy rollback.
Canary
Deploy to small percentage.
Monitor for issues.
Gradual rollout.
Security Considerations
Secrets Management
Use environment secrets for sensitive values
Limit secret access to specific environments
Rotate secrets regularly
Approval Gates
Require approval for production
Multiple reviewers for critical environments
Wait timers for change review
Branch Protection
Only deploy from main/release branches
Prevent direct pushes
Require PR reviews
Common Deployment Targets
GitHub Pages
Static sites
Documentation
Frontend apps
Free, built-in
User
Testing Guide for 2D&D
See AGENTS.md and
docs/testing.md for the release gate, CI ownership,
and browser-test setup.
Write comprehensive game-mechanics tests with Vitest. Use the committed
Playwright suite only for high-value Phaser browser flows that cannot be proven
through pure logic tests.
Use playwright.desktop.config.ts for the production-like Electron flow. It
must verify the app://2dnd origin, sandboxed preload API, fullscreen control,
schema-v17 save creation/relaunch/continue, Save & Return to Title, title-screen
quit, bounded lifecycle logs, and renderer error cleanliness.
Testing Philosophy
What TO Test
✅ Dice probability distributions
✅ Combat calculation accuracy
✅ Group initiative, formation, targeting, synergies, rewards, and encounter budgets
✅ Player stat progression
✅ XP and leveling formulas
✅ Quest objective counters, prerequisites, rewards, gates, danger rules, and
save normalization
✅ Companion definitions, party progression, transfers, KO/reward rules, and
ranked gambit selection/normalization
✅ Data integrity (monsters, spells, items)
✅ Monster family references, membership, variant differentiation, palette
uniqueness, encounter weights, Codex family completion, and texture-key coverage
✅ Codex knowledge IDs, canonical references, every unlock signal, idempotency,
normalization/migration, search/sort/group behavior, and future-hook isolation
✅ Game logic functions
✅ Seeded layouts and persistent state machines
✅ Non-combat skill-check math, outcomes, and save normalization
✅ Scene-transition event ordering, duplicate guards, and watchdog recovery with
mocked camera/time adapters
✅ Cutscene data integrity, trigger priority, queue recovery, replay immutability,
shared preference normalization/migration, and director cleanup
✅ Runtime hero descriptor normalization, collision-free visual keys, every
cutscene hero-role cue, equipment layer ordering/fallbacks, texture leases, and
current-player rendering across opening, recovery, Chronicle, bosses, and ending
✅ Tutorial content integrity, semantic control references, completion
normalization, progression-aware tip unlocks, and save migration
✅ Feature registry integrity, authoritative reconciliation, irreversible
visibility, dynamic menu/tab filtering, focus clamping, shortcut/touch gating,
debug exclusion, category-specific discovery, and schema-v17 migration
✅ Defeat penalty receipts, once-only Battle resolution, recovered save
round-trips, result-scene continuation, and random/boss parity
✅ Animation state selection, reduced-motion timing, stable actor/target mapping,
once-only completion and cleanup, and family-frame fallback resolution
✅ Semantic mappings, context priority, analog dead zones, repeats, source
switching, duplicate suppression, disconnect/blur cleanup, and control
preference migration
✅ Measured stacks/grids, safe-area clamping, long-string wrapping,
pagination/visible ranges, filtered focus restoration, scaled bounds,
hit-area alignment, and debug/test overlap detection
✅ Alignment boundaries, reputation tiers, clamping, stable-source
idempotency, quest/dialogue/event/trap/combat hooks, shop composition, Codex
milestones, schema-v12 migration, bounded history, and debug commands
✅ Achievement definition integrity, deterministic progress, hidden entries,
idempotent battle/event/social hooks, reconciliation, schema-v13 migration,
one-hit/no-defeat rules, cosmetic titles, debug exclusion, notices, and
authority isolation
✅ Gathering terrain safety, seeded tables, all three state machines,
reduced-motion equivalence, cooldowns, environmental weights, economy, guarded
Battle handoffs, recipe-input isolation, schema-v14 migration, and pending reload
✅ Crafting recipe integrity, alternative material matching, protected/equipped
items, atomic batches, repeated-input suppression, equipment-link upgrades,
ownership, discovery, acquisition tables, anti-arbitrage, achievements, debug
exclusion, authority isolation, schema-v15 migration, and corruption repair
✅ Nautical continent/zone/port/island integrity, pre-boat merchant routes,
boat acquisition/upgrades, embark/disembark safety, sea fog, capped encounters,
weather hazards, Kraken hooks, sea gathering/crafting economy, schema-v16
migration/corruption recovery, debug commands, and browser reload while sailing
Assistant
I’ll build the showcase and tag-driven desktop release path, then ship it through a review PR.
Assistant
I’m mapping the current web entrypoint, desktop packaging, and CI contracts before changing routes.
Assistant
The clean split is a multi-page Vite build: / becomes the showcase, game.html stays the Phaser runtime, and Electron opens the game entry directly.
Assistant
I’m implementing the split and the showcase now, with the browser game preserved as a dedicated entrypoint.
Assistant
The page structure is in place. I’m generating the three showcase images from deterministic live gameplay, not importing external art.
Assistant
The gameplay captures are real and clean. Next I’m wiring version-tag releases so no GitHub release appears unless tests, desktop smoke tests, and all three packages succeed.
Assistant
The release and documentation contracts are wired. I’m at the validation pass now, starting with the new entrypoints and workflow checks.
Assistant
The showcase flow now passes at the deployed /2dnd/ base. I’m doing the visual critique at desktop and mobile widths before the full gate.
Assistant
The visual pass is clean at desktop and mobile. I’m checkpointing the implementation before the full browser/Electron release gate.
Assistant
The checkpoint is on the remote branch and no CI runs are attached yet. I’m running the complete local release gate now.
Assistant
The full local gate passed, including 970 unit tests, 27 browser flows, Electron smoke, and packaged macOS artifacts. I’m doing one final diff review before opening the PR.
User
Review the current branch diff against main in /Users/mbianchidev/.copilot/copilot-worktrees/2dnd/cp-desktop-vigilant-sniffle. Focus only on high-confidence functional bugs, security issues, broken paths, GitHub Actions release failures, Electron entrypoint regressions, Vite multi-page/base-path mistakes, and landing/E2E correctness. The intended changes are: public index.html showcase; Phaser runtime moved to game.html; Electron loads app://2dnd/game.html; browser tests navigate game.html except landing.spec; generated gameplay screenshots; tag-triggered release.yml validates tag/package version and main ancestry, runs full gate, packages macOS/Windows/Linux, and creates/repairs a GitHub Release using gh. Ignore style or subjective design comments. Do not modify files. Report no findings if none are high confidence.
File: /Users/mbianchidev/.copilot/copilot-worktrees/2dnd/cp-desktop-vigilant-sniffle/.github/workflows/release.yml:139 Severity: High Problem: The publish job has no checkout and does not set GH_REPO or --repo. Both gh release view and gh release create therefore fail to identify the repository, preventing every tagged release from publishing. Evidence: Reproduced outside a Git checkout with GITHUB_ACTIONS=true and GITHUB_REPOSITORY set; gh failed with fatal: not a git repository. Suggested fix: Set GH_REPO: ${{ github.repository }}, pass --repo, or check out the repository before invoking gh.
User
Re-review the current branch diff against main in /Users/mbianchidev/.copilot/copilot-worktrees/2dnd/cp-desktop-vigilant-sniffle after the release job was fixed to set GH_REPO. Focus only on high-confidence functional bugs, security issues, GitHub Actions failures, Vite base paths, Electron routing, and broken tests. Do not modify files. Report no findings if the implementation is now sound.
Assistant
No significant issues found in the reviewed changes.
Assistant
The release-context bug is fixed and the second review is clean. I’m opening the human-review PR now.
Assistant
The PR is open. I’m watching browser, desktop, and CodeQL checks; I’ll only stop when CI and review threads are clean.
The versioned 2dnd_preferences document is separate from campaign saves and
backs both title and in-game settings. Install the scene accessibility adapter
in every scene, use its shared reduced-motion accessors, preserve
100%/125%/150% text usability, and pair important color states with a textual or
symbolic cue. Control presentation preferences cover touch visibility,
handedness, and prompt source without changing campaign saves. Stable mappings
are intentionally not remappable.
All release input routes through the semantic action layer. Standard gamepads
use dead zones, digital fallback, repeat/debounce, source switching, and a
visible right-stick cursor clicked by pressing the stick. Responsive touch controls use safe areas, pointer
capture for held directions, click pulses for discrete actions, and mobile text
entry. Clear held state on blur, visibility loss, disconnect, scene changes,
and shutdown.
Cutscene contracts live in src/data/cutsceneTypes.ts, focused campaign and
boss definitions live in cutsceneCampaign.ts and cutsceneBosses.ts, and
src/data/cutscenes.ts is the stable-ID hub. Pure trigger snapshots, priority
ordering, queue lifecycle, recovery, Chronicle selection, and summary logic live
in src/systems/cutscenes.ts; src/managers/cutscene.ts owns step progression;
scenes and renderers own input and presentation.
Hero-role actors remain immutable staging cues and resolve at presentation time
from the current PlayerState. Build the canonical descriptor with
src/systems/heroVisuals.ts and acquire cleanup-safe procedural textures through
src/renderers/heroTextures.ts; do not duplicate class, appearance, equipment
layer, fallback, or cache-key rules in Cutscene, Overworld, Battle, or Ending.
EndingScene and DefeatScene share src/renderers/result.ts; defeat receives
an exact runtime-only PartyDefeatResult, while the recovered player state is
autosaved before presentation.
The map hub is src/data/map.ts; terrain/types, chunks, cities, and dungeons
are split into dedicated modules. Dungeon trap definitions live in
src/data/traps.ts, mechanics in src/systems/traps.ts, and scene orchestration
in src/managers/dungeonTraps.ts.
Group templates live in src/data/monsterGroups.ts; reusable initiative,
formation, synergy, reward, and per-combatant rules live in
src/systems/groupCombat.ts.
That module also owns party-ready BattleCombatantState, stable actor IDs,
actor-ID initiative, ally/enemy targeting, monster party-target selection, and
battle resolution hooks.
src/systems/battleActions.ts is the Phaser-free action planner for player
input and ranked gambits: actor enumeration, target binding, validation,
immutable plans, per-actor action/bonus consumption, and one-action dispatch.
executeValidatedBattleAction() binds a generic CombatActorState to a party
combatant and reuses existing attack, spell, ability, item, defend, element,
status, MP, and inventory mechanics.
Consumables consume the acting source's inventory while applying HP/MP/cures
to a selected ally source; execution contexts must include all party action
sources. Equipment actions remain self-targeted.
src/systems/animation.ts is the Phaser-free presentation contract for actor
states, deterministic timing, stable-ID target mapping, once-only lifecycle,
and explicit family/frame texture metadata. src/managers/actorAnimation.ts
owns reusable Phaser poses and cleanup; battle/world directors consume resolved
state without changing mechanics. src/renderers/actorTextures.ts supports
optional family frames from #49 and a generic existing-texture fallback.
Tutorial and Tips content lives in src/data/tutorial.ts as immutable steps,
semantic control actions, categories, and unlock requirements.
src/systems/tutorial.ts owns completion normalization and progression-aware
filtering. src/managers/tutorial.ts owns the Overworld overlay and renders prompts for
the active keyboard, pointer, gamepad, or touch source. New saves persist
player.progression.tutorial.completed; replay never resets it.
Progressive feature discovery is data-driven through
src/data/featureDiscovery.ts and src/systems/featureDiscovery.ts. Filter
menus, tabs, shortcuts, prompts, touch actions, and Codex/crafting/gathering
categories through the shared registry. Preserve always-safe Inventory, Map,
Equipment, Tips, Settings, and save/title controls, and never use discovery as
authority for gameplay state.
World Event content lives in src/data/worldEvents.ts, its deterministic
Phaser-free state machine in src/systems/worldEvents.ts, and accessible choice
presentation in src/managers/worldEvents.ts. Events short-circuit treasure,
exploration checks, and random encounters for their movement step, while
transitions, entrances, traps, interactions, and queued cutscenes retain
priority. Special event combats use normal Battle hooks and saves.
Quests
Put quest definitions, stage objectives, NPC IDs, rewards, and gated
entrances in src/data/quests.ts.
Put progression, normalization, idempotent rewards, NPC interaction
resolution, journal entries, and entrance checks behind
src/systems/quests.ts; questState.ts and questDebug.ts contain focused
normalization and debug-only mutation helpers.
Persist state only through player.progression.quests; use quest-system APIs
instead of direct mutation.
The shipped campaign is the seven-chapter Twelvefold Covenant across all 12
cities and three keystones, with Ironbound Dispatch, Silk Against the Cold,
and optional Hydra and Dragon objectives.
Persist objective counters and claimed reward IDs. Batch group defeats with
duplicate monster IDs intact so three matching combatants count as three.
Downstream unlocks such as companions should call isQuestCompleted() and
keep their own persistent state separate from quest reward bookkeeping.
Cross-system outcomes use stable quest completion actions with
{ id, type, targetId }. Replay them after load/mutations and make the
consumer idempotent rather than adding duplicate quest state.
Give every stage a stable camelCase id; downstream systems use
getQuestStageIndex() or the debug-only setQuestStageById(), never display
titles.
Derive boss objectives from defeatedBosses so older saves can report
already-completed objectives.
Keep quest NPCs available at night and test every referenced NPC, boss,
reward item, and entrance.
Campaign completion remains derived from the main quest. Launch the epilogue
after the final Elowen dialogue applies rewards, recover completed-but-unseen
saves from Overworld creation, and keep replay presentation-only.
Queue stable cutscene IDs and save before presentation. Completion or skip
moves an ID from pendingCutsceneIds to seenCutsceneIds; reload resumes the
first pending entry, while Chronicle replay changes neither collection.
Detect newly satisfied cutscenes by comparing immutable before/after snapshots.
Battle must capture its snapshot before recording the defeated boss. Sort
simultaneous triggers by explicit numeric priority rather than discovery
order.
Map main-quest talk objectives through QUEST_NPCS and assert exact coverage
of all 12 live city IDs; do not accept name-only references.
Canyonwatch, Ashfall, and the Volcanic Forge are hard gates. Sandport and
Heartlands Crypt remain open; other premature travel uses one-time soft
danger warnings and capped encounter modifiers.
Non-combat skill checks
Non-combat checks are split across:
src/data/skillChecks.ts: NPC challenges, negotiation choices, and terrain
event definitions
src/systems/skillChecks.ts: pure d20 resolution, normalization, and helpers
src/managers/skillChecks.ts: Overworld rewards, hazards, chest checks, and
dialogue orchestration
Adding monsters
Define the monster in the appropriate focused pool (monsters.ts,
nightMonsters.ts, or monsterVariants.ts).
Use a camelCase ID and set a valid typed family, stats, rewards, drops,
abilities, and isBoss.
For a palette/stat variant, set variantOf to a valid same-family monster,
use a distinct color and ability set, and assign a positive
encounterWeight.
Add an affinity and elementalProfile when the monster has a dominant
element, resistances, weaknesses, or
immunities.
Add element and statusEffect to monster abilities when applicable.
Ensure the definition is included in ALL_MONSTERS; debug spawning, Codex
browsing, and ID lookup depend on the master list.
Reuse getMonsterTextureKey() and the family silhouette renderer rather than
adding scene-local textures or tints.
Add encounter-pool, family, palette, texture-key, and data-integrity tests.
Use getMonster(id) for exact ID lookup and findMonster(query) for
case-insensitive ID/name lookup with partial matching.
Adding monster groups
Add a 2-4 member template to MONSTER_GROUP_TEMPLATES.
Reference valid monster IDs and assign every member to front or back.
Keep minPlayerLevel high enough that total difficulty does not exceed
playerLevel * 3.
Add biome/dungeon tags, encounter weight, and an optional synergy with a
valid break threshold.
Add deterministic generation and data-integrity coverage.
Random groups start at level 2, cap at 50% of triggered encounters, and never
replace bosses or explicit debug monster spawns.
Codex family completion is derived from the current CodexData.entries; family
metadata, affinity, and sort/filter presentation are not save fields.
World knowledge definitions live in src/data/codexKnowledge.ts. Persist only
stable unlocked knowledge IDs in CodexData; derive category counts, source
hints, search results, sorting, and grouping from canonical entries. Emit
idempotent location, quest, cutscene, item, NPC, readable, or worldEvent
signals without letting Codex state control gameplay. reputationMilestone
is owned by the schema-v12 reputation system and must remain idempotent.
World Events
Filter immutable definitions by terrain, area, time, weather, level, quest
state, boss state, prior outcomes, repeat limits, and cooldowns.
Keep event chance independently capped at 8%; never feed it into or multiply
the 15% random-encounter calculation.
Persist the selected pending event before presenting choices or starting a
special battle. Reload resumes the same choice or encounter.
Apply skill outcomes through rollSkillCheck(), quest starts through
startQuestById(), rewards through canonical item/XP helpers, and lore through
unlockCodexFromFutureSignal().
Resolve stable outcome/reward IDs once, append at most 40 chronological
records, and expose those records through Chronicle without revealing future
choices.
Alignment/reputation hooks are consumed by the centralized social mutation
API with stable source IDs. World Event state never persists duplicate social
scores or applied IDs.
Alignment and reputation
Keep canonical axes, faction IDs, reputation tiers, and thresholds in
src/data/reputation.ts; reusable mechanics belong in
src/systems/reputation.ts.
New players begin exactly Chaotic Neutral (lawChaos: -50, goodEvil: 0).
Persist only bounded scores, stable applied source IDs, and the bounded
recent-cause history. Derive names, tiers, pricing, milestones, and ending
variants.
Apply social outcomes only for meaningful choices. Never reward routine
movement, unavoidable combat, or farming.
Return runtime-only SocialAchievementHook values for the achievement
consumer; do not persist achievements inside the social system.
Achievements
Put immutable definitions and cosmetic titles in src/data/achievements.ts;
put normalization, deterministic progress, reconciliation, stable event
counters, debug exclusion, and title equip rules in
src/systems/achievements.ts.
Prefer reconciliation from authoritative quest, boss, Codex, exploration,
trap, skill-check, event, social, party, and inventory state. Add persisted
counters only for non-reconstructable event history such as battle wins,
one-hit defeats, and explicit defeat count.
Achievement state never controls gameplay authority. Titles are
presentation-only and notices are queued for safe Overworld presentation.
Adding spells, abilities, and equipment
Damage sources may declare an Element from src/data/elements.ts.
Player abilities may apply selfEffect or targetEffect IDs defined by
src/systems/statusEffects.ts.
Monster abilities use statusEffect for effects applied to the player.
Cure consumables declare matching cure data and must be wired through
useItem() without consuming the item when no matching ailment exists.
Ally-target consumables declare targetType; resolve it through
getItemTargetType() so older inventory copies use canonical item metadata.
Preserve action economy: normal actions end the player turn; bonus-action
abilities and the first item use do not.
Combat calculation order is:
Roll and resolve the attack or save.
Apply active-status accuracy, disadvantage, AC, and damage modifiers.
Apply elemental immunity, weakness, or resistance to the modified damage.
Apply damage and status effects.
Report discoveries and combat feedback.
Magic Missile remains auto-hit and does not roll disadvantage.
Status effects
All definitions and lifecycle helpers live in
src/systems/statusEffects.ts. Do not duplicate status logic in data files or
scenes.
Start of actor turn: tick damage, saving throws, and skip-turn decision.
End of actor turn: decrement durations and expire effects.
Apply or refresh through applyStatusEffect().
Normalize loaded effects through normalizeActiveEffects().
Clear player and monster effects when leaving Battle; durations are measured
in combat turns, not overworld steps.
Elements
Supported elements are Fire, Ice, Lightning, Poison, Necrotic, Radiant,
Thunder, Force, and Psychic.
Immunity: zero damage
Weakness: double damage
Resistance: floor of half damage
Neutral: unchanged
Record observed non-neutral interactions with discoverElement() so the Codex
can persist and display them.
World features
Cities may contain connected districts. Always use city chunk helpers rather
than indexing city.chunks directly.
Dungeons may contain multiple levels. Always use dungeon level and
connection helpers.
Dungeon trap layouts are derived from persisted trapSeed; never mutate
dungeon maps or randomize layouts independently in scenes.
Detected traps block movement until disarmed. Trap triggers must short-circuit
the normal random-encounter check for that step.
Use FogOfWar.exploredKey() for exploration keys.
Use isWalkable() and ENCOUNTER_RATES; do not hardcode terrain behavior.
Nautical metadata lives in src/data/nautical.ts; state normalization,
ownership, and mechanics live in the focused nauticalState.ts,
nauticalOwnership.ts, and nautical.ts modules. Preserve all 90 legacy
chunk IDs and use s:zoneId,chunkX,chunkY,x,y for sea fog.
Merchant routes work before boat ownership. Free sailing requires a
serviceable active boat, uses canonical Water eligibility, and runs hazards
before World Events, gathering, and random sea encounters.
Non-combat skill checks
Checks use d20 + Dexterity, Intelligence, Wisdom, or Charisma modifier plus
typed bonuses against a DC.
Natural 1 and 20 are not automatic outcomes for ability checks.
Persist fixed NPC, shop, chest, and treasure results in
player.progression.skillChecks.
Use stable NPC identities and shop type/coordinate keys rather than array
indexes.
Shop negotiation is one attempt per shop; successful discounts restore from
the saved result.
Exploration hazard damage is nonlethal and must clamp the player to at least
1 HP.
Test roll math, invalid inputs, stable data references, save normalization,
reward bounds, and nonlethal damage deterministically.
Battle also receives a MonsterEncounter and biome; Shop receives shop/city
context.
Defeat receives the full shared state plus encounter name/type and the exact
applied party defeat receipt. It must not recalculate or reapply penalties.
Future party systems pass accessor-backed partyCombatants plus runtime-only
battleHooks; do not persist those wrapper objects.
Keep target init() contracts and every caller synchronized.
The new-player tutorial opens only after pending opening cutscenes have drained.
F1 and the Esc menu open the consultable Tips surface. Keep the external HTML
control rail collapsed by default and retain only contextual action prompts in
the game HUD.
Route camera fades and scene handoffs through
src/managers/sceneTransition.ts. Call prepare() when each scene creates,
wait for fade-complete events, and keep the duration-plus-grace watchdog as a
recovery path only. Restore the outgoing camera before queueing the next scene,
reject duplicate handoffs, and block state-changing Overworld input until the
queued start/restart is processed. Every Overworld restart must include a fresh
savedSpecialNpcs snapshot in the shared state payload.
Use the same guarded Battle exit cleanup for victory, flee, and defeat. Defeat
clears transient menus, input, effects, particles, and weather timers before
starting DefeatScene, which continues only to Overworld.
Resolve an action before presenting it. Actor animation may read stable IDs,
targets, hit/damage/healing, and outcome, but must not spend MP/items/actions,
apply damage, report results, or control fade-complete scene handoffs.
Companions and gambits
Persistent party state lives at player.party; do not add a parallel scene
payload or companion combat model.
Stable companion IDs are guardian, scout, and mystic.
Build runtime actors with createPartyCombatant() and
createBattleActionSource().
Manual turns and ranked gambits both validate/execute through
battleActions.ts; one bonus action may precede or follow one main action.
Debug quest or companion recruitment must refresh live follower presentation
immediately after replay.
Active conscious companions may render as non-blocking followers, but only
hero movement invokes trap, encounter, gate, and world-interaction logic.
Keep party UI/followers/battle presentation in focused managers/renderers
rather than growing the existing oversized scene/overlay files.
Inventory presentation
Build immutable views with src/systems/inventory.ts; every view entry keeps
its original inventory index for actions and transfers.
Never sort the owning inventory array or replace equipment object references.
Keep sort/filter/search preferences in 2dnd_inventory_prefs, outside the
campaign save schema. Recent acquisition is reverse append order.
Use semantic inventory actions for keyboard, pointer, gamepad, and touch
controls. T remains mount control.
Generate item visuals procedurally through src/renderers/itemVisuals.ts.
Gathering
Gathering content lives in src/data/gathering.ts, deterministic node/table/
minigame logic in src/systems/gathering.ts, schema normalization in
gatheringState.ts, and accessible Phaser presentation in
src/managers/gathering.ts. Persist selected outcomes before play, use safe
location-derived nodes, route guarded finds through normal Battle hooks, and
keep material identity limited to stable Item.material recipe-input metadata.
Crafting
Crafting recipes live in src/data/crafting.ts, atomic mechanics and discovery
in src/systems/crafting.ts, persistence normalization in craftingState.ts,
and accessible Overworld presentation in src/managers/crafting.ts. Validate
the selected actor inventory, protected/equipped restrictions, batch, gold,
station, output, and transaction ID before mutation. Equipment upgrades replace
exact equipped object links with canonical outputs. Never pull companion
materials implicitly, reroll a craft, duplicate material identity, or let
recipes/achievements control quests, Codex, access, or rewards.
Validation
bash
npm run typecheck
npm test
npm run test:browser
npm run test:desktop
npm run build
npm run build:desktop
For UI changes, run the committed Playwright flow in headless Chromium. Keep
browser actions synchronized through debug-state transitions, and hold
frame-polled Phaser keys across frames rather than using instantaneous presses.
Build responsive UI from src/systems/layout.ts, register modal groups through
createOverlayContainer(), and assert the local #layout-report reports zero
unintended overlap or clipping at supported text scales.
Common pitfalls
Do not mutate shared monster, item, map, city, or dungeon definitions.
Do not share HP, status, defend, discovery, or drop state between group
combatants, including duplicate monsters.
Do not introduce index-based turn entries or duplicate hero HP/effect state;
use stable combatant IDs and createHeroCombatant().
Do not reimplement MP, inventory, target, formation, or action-economy checks
in companion AI; use validateBattleAction().
Do not use stale Phaser 3 APIs or default imports; current code uses
import * as Phaser from "phaser".
Do not create a second status or elemental calculation path.
Do not omit unique dungeon pools or bosses from aggregate lookups.
Do not use geometry masks for the Battle log; render the bounded visible
message window.
Do not add a persistent field without save normalization and tests.
Do not reroll a failed trap detection; persist the missed state.
❌ Phaser rendering/graphics
❌ Scene transitions
❌ User input handling
❌ Visual appearance
❌ Animation timing
These exclusions apply to Vitest. The focused e2e/ suite owns the real-browser
campaign golden path and scene/input integration.
Animation browser coverage should assert debug-state evidence from real action
menus and combat turns for hero, companion, monster, and boss presentation;
spell/ability particles; world/follower/mount gait; boss cutscenes; fainting;
reduced-motion immediate states; and page/console cleanliness.
Battle backdrop browser coverage uses deterministic /battleview and
/backdrop controls, programmatic depth/bounds/cleanup assertions, and focused
canvas screenshots for group, boss, Kraken, mobile, weather, and high-contrast
combinations. Keep the full biome/time/weather matrix assertion-driven rather
than committing hundreds of redundant images.
Accessibility browser coverage should change settings from both title and
in-game surfaces, assert immediate canvas state, exercise core overlays at every
supported text scale, verify reload persistence, and prove 2dnd_save is
unchanged by preference updates.
Semantic-controls browser coverage uses mobile/touch emulation and deterministic
standard-gamepad stubs. It covers onboarding and mobile text entry, movement,
overlays, prompt/source switching, Battle action/target confirmation, defeat
recovery, gamepad cursor visibility, portrait/landscape layout, and page/console
cleanliness.
Codex browser coverage follows real exploration, quest, cutscene, item, NPC, and
readable paths; verifies non-blocking feedback, reload persistence, schema-v9
migration, keyboard/touch/gamepad search and filters, 150% text, reduced motion,
and page/console cleanliness.
Test File Organization
code
tests/
├── dice.test.ts # Dice rolling utilities
├── combat.test.ts # Combat mechanics
├── groupCombat.test.ts # Multi-monster combat rules
├── battleActions.test.ts # Pure gambit planning and validation
├── monsterGroups.test.ts # Group templates and generation
├── monsterFamilies.test.ts # Families, variants, Codex derivation, texture keys
├── codexKnowledge.test.ts # World knowledge data, triggers, queries, and hooks
├── partyCombat.test.ts # Stable actor IDs, ally scopes, AI, and result hooks
├── party.test.ts # Recruitment, progression, transfers, rests, KO/rewards
├── companions.test.ts # Immutable companion definitions and loadouts
├── gambits.test.ts # Ranked conditions/actions/targets and normalization
├── followers.test.ts # Pure non-blocking follower trail updates
├── player.test.ts # Player systems
├── traps.test.ts # Dungeon trap placement, checks, and effects
├── quests.test.ts # Quest progression and integrity
├── skillChecks.test.ts # Exploration/dialogue checks
├── reputation.test.ts # Alignment, reputation, integrations, and migration policy
├── achievements.test.ts # Definitions, progress, hooks, titles, and migration policy
├── cutscenes.test.ts # Cutscene data, triggers, queue, and director lifecycle
├── accessibility.test.ts # Shared preference normalization, migration, and persistence
├── input.test.ts # Semantic mappings, contexts, repeats, cleanup, and suppression
├── tutorial.test.ts # Tutorial content, completion, and unlocked Tips
├── featureDiscovery.test.ts # Registry, reconciliation, filtering, debug, migration
├── gathering.test.ts # Gathering data, state machines, rewards, and save rules
├── crafting.test.ts # Recipes, transactions, discovery, economy, and save rules
├── cutsceneSceneTransition.test.ts # Generic Cutscene scene contracts
├── defeatSceneTransition.test.ts # Defeat result continuation contract
├── save.test.ts # Persistence and migration
└── data.test.ts # Data validation
Quest tests must cover duplicate matching monsters in one group victory,
durable boss reconciliation, optional-objective reward cutoffs, hard-gate
softlock safety, reward idempotency, and flat schema-v4 to nested schema-v5
migration. Map main-quest NPC objectives to live city IDs and require exact
coverage of all 12 cities with stable stage/objective identities.
Tutorial tests must keep Phaser out of pure logic. Assert stable unique IDs,
valid semantic control references, idempotent completion, safe malformed-state
normalization, and exact progression-aware tip unlock sets. The committed
Playwright flow owns automatic presentation, pointer navigation, persisted
completion, F1, and Esc-menu access.
Skill Check Testing
Pass explicit natural d20 values to resolveSkillCheck(); do not depend on
randomness.
Verify total-vs-DC behavior, including that natural 1/20 are not automatic.
Test shop discounts for both successful and failed saved choices.
Validate NPC identities and chest metadata against live city/map data.
Test terrain event selection with explicit random values.
Cover reward bounds, nonlethal damage, save round trips, missing fields, and
malformed record repair.
Cutscene Testing
Validate every stable ID, trigger reference, boss mapping, and completion
metadata without rendering Phaser.
Compare immutable before/after snapshots and assert exact simultaneous-trigger
priority.
Test that queueing precedes presentation, completion/skip moves pending to
seen, reload resumes pending, and replay leaves both collections unchanged.
Keep generic CutsceneScene transition payload tests separate from the
Playwright visual/input flow.
Companion Testing
Use deterministic companion creation at explicit hero levels; verify
independent inventory objects and level-tier loadouts.
Test quest completion replay, reload, debug completion, and repeated replay
against the same unique recruited-ID guard.
Parameterize those paths across Guardian, Scout, and Mystic; one companion
path is not representative coverage.
Construct BattleActionSource/PartyCombatant adapters and verify HP/MP
writes reach the underlying companion state.
Test gambits as pure rank/condition/target selection. Invalid rules must not
mutate action economy, MP, inventory, or effects.
Cover living-vs-KO XP distribution, level-1 XP floor, party wipe recovery,
exact defeat receipts, and party-wide inn rest.
Keep a focused Battle transition regression that asserts fade-complete
ordering, one-shot scene start, transient cleanup, the full Overworld payload,
and once-only DefeatScene routing for random and boss encounters without
rendering Phaser UI.
Keep Phaser visuals in headless Chromium flows; pure trail positioning and UI
mutation helpers belong in Vitest.
Inventory Testing
Test type/value/rarity/recent/name selectors without mutating canonical order
or equipment links.
Cover equipment, consumable, quest, and future crafting filters plus search.
Normalize and persist 2dnd_inventory_prefs separately from 2dnd_save.
Assert equipped, key-item, mount, and duplicate-item transfer restrictions.
Use focused Playwright coverage for large-bag keyboard/pointer paging,
selection stability, search, and menu access.
## Running Tests
### Command Line
```bash
# Run all tests once
npm test
# Install Chromium once, then run the campaign browser suite
npm run test:browser:install
npm run test:browser
# Build and run the Electron smoke suite
npm run test:desktop
# Watch mode (re-run on changes)
npm run test:watch
# Type checking
npm run typecheck
# Production bundle/startup/memory/save baseline
npm run benchmark:baseline
# Run specific test file
npx vitest run tests/dice.test.ts
Browser Golden Path
playwright.config.ts starts Vite on an unused strict localhost port.
Browser tests default to /2dnd/; set PLAYWRIGHT_BASE_PATH=/ to reproduce
the root-base development path.
Pull request CI installs Chromium and runs the browser suite as a release
gate.
Keep trace action logs, DOM snapshots, sources, and failure screenshots, but
disable trace screenshots and video. Phaser repaints every frame, so the
filmstrip creates thousands of canvas captures that stall context teardown.
Use #debug-state, #debug-log, and persisted save state as authoritative
synchronization surfaces. Canvas text is not DOM text.
Registered Phaser layout groups expose bounds and audit results through
#layout-report, data-layout-overlap-count, and
data-layout-clipping-count; use stable layoutId values instead of brittle
coordinate-only clicks.
Hold frame-polled keys with keyboard.down(), wait across frames, then
keyboard.up(). Do not use instantaneous presses for Overworld or Ending
actions.
Seed randomness before the game loads and assert both pageerror and
console.error remain empty.
Run npm run benchmark:baseline before performance-affecting work and attach
its commit, environment, and output to the owning issue or pull request. The
harness uses the named 2dnd:boot-textures browser performance measure and a
fresh schema-v17 save.
Cover random and boss defeat results, exact displayed penalties, clean
continuation, and recovered save/reload state through the production
/defeat debug path.
Debug commands may accelerate setup, but the final Elowen interaction and
other behavior under test must still run through their production paths.
Cover interrupted opening recovery, dungeon reveals, skipped boss
introductions, aftermath chaining, Chronicle replay immutability, interrupted
and legacy ending recovery, durable post-game reload, and corrupt-save
fallback to a usable New Game path.
Desktop Golden Path
Build with the relative desktop Vite mode and compiled main/preload process.
Launch with a fresh explicit test-only Electron user-data directory.
Assert location.origin === "app://2dnd" and the fullscreen bridge shape.
Create a character through production controls, then close and relaunch the
shell and continue the same schema-v17 campaign.
Return to title through the keyboard menu, quit through the visible title
action, and verify lifecycle/quit logs without save-content leakage.
Run on macOS, Windows, and Linux CI; use Xvfb only on Linux.
Never weaken sandbox, navigation, IPC, CSP, or network policy for tests.
Test Coverage
bash
# Generate coverage report
npx vitest run --coverage
Best Practices
Test behavior, not implementation - Focus on inputs/outputs
Use descriptive test names - "it calculates X when Y"
Mock randomness when needed - Make tests deterministic
Keep tests fast - Avoid delays, network calls
One assertion per test (when possible) - Makes failures clear
Inject group RNG - Initiative, weighted generation, and random-two
targeting helpers accept deterministic random functions
Common Pitfalls
❌ Testing Phaser objects directly (use pure functions)
❌ Relying on random values without bounds checking
❌ Not testing edge cases (0, negative, null)
❌ Tests that depend on execution order
❌ Overly complex test setup
❌ Not cleaning up state between tests