AGENTS.md instructions for /home/pjensen/Repos/JSHack
--- project-doc ---
AGENTS.md - JSHack Field Manual
JSHack is a zero-dependency browser roguelike: pure JavaScript, pure ES modules,
ECS architecture, Deno tooling. This file is optimized for coding agents. Prefer
the commands below over manual spelunking.
Deeper docs:
README.md
SEPARATION_MANIFEST.md
RUNTIME_TOPOLOGY_DOCTRINE.md
TEN_COMMANDMENTS.md
ecs-js/AGENTS.md
Hard Laws
No build step. Pure ES modules. No webpack, babel, JSX, TypeScript, or
bundling.
Deno, not Node. Tests and tools run with Deno. Default test command:
deno test --allow-read.
JavaScript only. Keep source as .js / .mjs.
Mobile-first. Touch is primary; desktop keyboard is secondary.
Separation is law.rules/ never imports display/ or bridge/;
display/ never imports rules/; bridge/ projects read-only rule state.
No system-to-system calls. Systems communicate with world.emit /
world.on; scheduler owns ordering.
No swallowed event failures. Do not add emitSafe-style wrappers around
world.emit.
Determinism is sacred. In rules simulation use world.rand(), never
Math.random(). No timers/fetch/promises/async in systems.
Integer grid only. World coords may be negative. Do not clamp to >= 0;
normalize with Number.isFinite(v) ? (v | 0) : fallback.
One canonical path. Spawn, damage, spell cast, status application,
inventory transfer, and materialization paths must delegate to the canonical
implementation.
Runtime
effects/procs/sockets/enchantments are child topology, not arrays on parent
components.
I would like for hard mode to have permanent death
I would like for normal mode to have ressurection.
I wonder -- how can we do that?
implementation details on resurrection.
how punishing is it? do you drop your gear? how hard is it to get back to where you were? I wonder if we can create a return portal.
am I doing something stupid? was this game intended to have permadeath always? is there a middle road?
Assistant
I’ll look at the current death and difficulty flow first, then I’ll give you options grounded in how this codebase already works.
Assistant
The first pass shows difficulty is already stored from character creation, but the current labels are easy and hard; “normal” likely maps to today’s non-hard path or needs a rename in the UI. I’m checking the exact player death path now because resurrection needs to hook there without breaking monster death cleanup.
Assistant
There is already a return-portal concept: Homecoming-style depth teleports can create a return_portal, and input dispatch knows how to use it. That strongly suggests resurrection should reuse that machinery instead of inventing a new transport path.
Assistant
Current game behavior is effectively permadeath: player death emits died, starts post-mortem, clears the save, records a tombstone, posts death/share data, then shows the death flow. I did not find a doc saying “this must always be permadeath,” but the implementation assumes it.
The clean middle road I’d recommend:
Hard mode
Keep current behavior exactly: final death, clear save, tombstone, death screen.
User
I completely agree with your assessment here; these are great intuitions. keep equipped gear, drop the backpack, brain stays mostly in-tact, increment a counter somewhere. possible tweaks, touching shrines creates checkpoints -- but honestly, I like "pseudo death" like you laid out, and the use of the portal from town.
my favorite part of this is that it really forces the player back up and through the town. we need only make the portal obviously places.
one final tweak: like like these death modes you laid out so much, why don't we handle all of them, and just set the mode.
Assistant
I’ll implement this as a death-mode policy, so hard can stay permadeath while normal can choose among the resurrection penalties without hardcoding one behavior into the damage path. First I’m checking the save registry and component patterns so the mode and counter persist cleanly.
Assistant
The component registry already sweeps exported components plus runtime stores, so a new run-state component can persist without special casing if it is exported. I’m going to keep the policy in rules-side utilities and have main only translate “resurrect to town with a portal” into the existing transition event.
Assistant
I’m going to make the mode values explicit rather than boolean: permadeath, mercy, drop_backpack, and drop_all_but_one. Normal will default to drop_backpack; hard will set permadeath. That gives us the knobs now, while shrine checkpoints can later set the mode or add a checkpoint source without rewriting fatal damage.
Assistant
I’m about to edit the fatal-damage branch and add a small run-state component. The key behavior is that resurrection happens after the damage event but before died, so existing hit feedback still works and death systems do not fire for pseudo-death.
Assistant
The first implementation pass is in place. I’m running the focused tests now; if anything breaks it should be around component validation, inventory ownership, or transition source handling.
Assistant
Focused tests are green. I’m doing a quick architectural and diff pass now, mainly to catch import-boundary mistakes and anything awkward in the new policy utility before I call it done.
Assistant
I found and fixed a duplicate-drop edge case in the stricter mode: equipped gear could be reported twice if it was also in inventory. I’m rerunning the focused suite after that correction.
Assistant
The focused tests and deno check are clean. I’m running the full runtime suite with --no-check now because this touches the canonical damage path.
Assistant
The full suite exposed one real policy issue: tests and older worlds without RunState were being treated as normal-mode resurrection. I’m changing missing run state to preserve legacy permadeath; new games explicitly create RunState, so normal mode still resurrects.
Assistant
That full-suite run used the pre-fix code for most of its duration, so the death-related failures are expected stale results from the old process. The transition failures are localStorage database errors from the long run, not from the death-mode changes; I’m rerunning the affected death suites now against the fixed code.
Assistant
The transition rerun still fails at clearFloorCache() before it reaches assertions because Deno’s built-in localStorage database cannot open in this sandbox run. I’m checking whether granting write permission to the test process resolves that environment failure.
Assistant
Implemented death modes with normal-mode resurrection and hard-mode permadeath.
Core changes:
Added RunState with deathMode and resurrectionCount in RunState.js.
Added death mode policy in deathModes.js:
permadeath
mercy
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
ECS-js is vendored. Do not edit src/lib/ecs-js/ unless fixing the ECS
library itself.
Search before writing. Extend existing patterns. Do exactly what was
asked; no opportunistic content wiring or unrelated cleanup.
Agent Commands
Run these before guessing.
Project Health
bash
deno run --allow-read tools/agent-health.mjs
deno run --allow-read tools/import-boundary-report.mjs
deno run --allow-read tools/system-map.mjs
agent-health summarizes boundary violations, remaining emitSafe refs,
nondeterminism hazards, generation-time async allowances, system counts, and
possible system-to-system calls. Classified allowances are context for agents;
headline hazards are the things to investigate first.
Event Bus
bash
deno run --allow-read tools/event-bus-explorer.mjs --format summary --top 40
deno run --allow-read tools/event-bus-explorer.mjs --format csv --event damaged
deno run --allow-read tools/event-bus-explorer.mjs --format mermaid --event damaged
deno run --allow-read tools/event-bus-explorer.mjs --producer-only --format summary --top 40
deno run --allow-read tools/event-bus-explorer.mjs --consumer-only --format summary --top 40
Use producer-only events to find emitted behavior with no consumer. Use
consumer-only events to find stale listeners, dynamic producers, or missing
producers.
System Map
bash
deno run --allow-read tools/system-map.mjs --format summary
deno run --allow-read tools/system-map.mjs --format csv
deno run --allow-read tools/system-map.mjs --phase effects
deno run --allow-read tools/system-map.mjs --unregistered
deno run --allow-read tools/system-map.mjs --missing-tests
Scheduler truth lives in src/main/scheduler.js. Some
imported-not-registered files are listener installers, not phase systems; audit
before deleting.
Target Lookup
bash
deno run --allow-read tools/agent-target.mjs damaged --limit 80
deno run --allow-read tools/content-id-audit.mjs goblin --limit 80
deno run --allow-read tools/content-id-audit.mjs potion_water --limit 80
agent-target is a ranked code search for events/functions/files/tests.
content-id-audit follows item, monster, spell, material, loot, visual, and
test references by ID.
Focused Tests
bash
deno test --allow-read tests/separationBoundaries.test.mjs
deno test --allow-read tests/determinismArchitectureGuards.test.mjs
deno test --allow-read tests/schedulerArchitectureGuards.test.mjs
deno test --allow-read tests/dealDamage.test.mjs
deno test --allow-read tests/castSpell.test.mjs
deno test --allow-read tests/interaction.test.mjs
deno test --allow-read tests/movementRefactored.test.mjs
deno test --allow-read tests/contentCatalogCanonical.test.mjs
Full runtime suite:
bash
deno test --allow-read --no-check
Plain deno test --allow-read may fail during type-check on non-game packaging
scripts before tests run. Use --no-check when you need runtime coverage.
rules/ deterministic simulation; no DOM, display, timers, async systems
bridge/ read-only projection from rules state to WorldView DTOs
display/ presentation only; reads WorldView and main-provided contracts
main/ wiring, lifecycle, input dispatch, scheduler setup
shared/ pure math/grid utilities; no ECS or DOM
lib/ vendored ecs-js and deity-js
content/ DSL-authored content definitions and content helpers
Five scheduler phases are declared in
src/main/scheduler.js:
text
ai intent producers
intents movement/combat/use/cast/interaction consumers
effects per-turn derived effects and world simulation
scripts content DSL tick hooks
cleanup entity removal, lifespan, spatial sync
The bridge contract is
src/bridge/schema/worldView.js. Display must
not push tags onto entity records; tag projection belongs in the bridge.
const INSTALLED = Symbol.for("jshack:domain:feature:installed");
export function installFeatureListeners(world) {
if (world[INSTALLED]) return;
world[INSTALLED] = true;
world.on("event:name", (payload) => {});
}
Install listeners from configureWorld() unless the feature is display/main
wiring.
New Systems
Add src/rules/systems/mySystem.js.
Register it in src/main/scheduler.js in the right
phase.
Add a focused test in tests/.
Run deno test --allow-read tests/mySystem.test.mjs.
Spatial Queries
Use forEachInRadius, forEachInRect, or tile query helpers. Do not full-scan
world.query() for proximity-sensitive behavior.
Spawning
Route through canonical archetypes/materialization helpers. Debug spawns,
dungeon population, and spawner children must have parity tests if they differ.
Events
Use direct world.emit(event, payload). If an event should be visible to
display/audio/messages, verify with:
bash
deno run --allow-read tools/event-bus-explorer.mjs --format csv --event event:name
Red Tests
Tests can be stale. Do not make tests green by restoring old behavior unless the
user explicitly asks for that behavior.
Classify failures:
Real bug: fix implementation.
Stale expectation: update the test to current intended behavior.
Spawn paths use canonical constructors/materializers.
Event wiring checked with tools/event-bus-explorer.mjs.
Agent health checked with tools/agent-health.mjs.
Normal mode
Make first death a resurrection, not a real died event.
Flow:
Player takes fatal damage.
If difficulty is normal, intercept before emitting died.
Set HP to something like max(1, floor(maxHp * 0.35)).
Remove the worst immediate statuses, maybe keep curses/wounds.
Emit player:resurrected or resurrection:triggered.
Teleport player to town/home/bed using the existing dungeon:teleport-depth path.
Create a return portal back to the death tile using the existing Homecoming return-portal system.
Penalty options, from least to most punishing:
Light: Keep gear, lose gold or score, return portal available.
Medium: Keep equipped gear, drop backpack at death tile, return portal available.
Hard-softcore: Drop everything except one equipped weapon/armor slot, return portal available.
Checkpoint: Reload last bed save, place return portal to death location. This is simpler conceptually but can feel weird because world progress rolls back.
I’d choose medium: keep equipped gear, drop carried inventory/gold at the death tile, resurrect in town with a return portal. That preserves roguelike danger without making normal mode delete the run. It also creates a strong recovery story: “go reclaim your body.”
You’re not doing something stupid. Pure permadeath is genre-correct, but it narrows the audience and makes experimentation expensive. A hard/normal split is a good compromise: hard mode stays honest; normal mode becomes recoverable but still consequential. The important implementation detail is to treat normal-mode resurrection as not death internally, otherwise save clearing, tombstones, death share, and post-mortem will all fire too early.
drop_backpack
drop_all_but_one
Wired fatal player damage through pseudo-death before died fires in dealDamage.js.
New games now set hard to permadeath and normal to drop_backpack in main.js.
Resurrection emits a town depth teleport with a return ticket, and transition wiring treats source: "resurrection" like Homecoming so the return portal is created in town in transitionWiring.js.
Behavior now:
Hard mode: real death, save clears, tombstone/death screen still happen.
Normal mode: fatal hit restores 35% HP, increments resurrectionCount, drops backpack on the death tile, keeps equipped gear, returns player to town, and creates a return portal to the death tile.
Missing RunState preserves legacy permadeath, so old isolated tests/worlds do not silently become softcore.
Passed: architecture guard tests and agent-health.
Full suite attempt hit existing Deno localStorage database errors in transition tests (unable to open database file); rerunning with --allow-write did not change that.