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 multiplicity is child entities. Runtime
effects/procs/sockets/enchantments are child topology, not arrays on parent
components.
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.
I just had a pit trap land me into void space well outsied of the map in the level below. please explain.
Assistant
I’ll trace the pit-trap descent path and the level transition placement logic, then line it up with map bounds handling so the failure mode is concrete.
Assistant
The relevant path is visible now: trap_pit emits trap:pit:fall, and transitionWiring handles the actual floor change. I’m reading those pieces plus the lookahead function that was supposed to reject bad pit placements.
Assistant
The likely bug is not in the damage or event itself; it is in how a fixed XY transition bypasses the normal stair landing selection. I’m checking whether transitionToDepth validates that fixed XY after the lower floor has been generated/restored.
Assistant
There are two important mismatches: pit placement checks a synthetic probe of the next floor, while the real transition may generate or restore a different floor state; then the transition accepts the pit’s XY without a final walkability check. I’m doing one quick confirmation pass against the tile APIs so the explanation is not just from reading comments.
Assistant
The pit trap path currently trusts a coordinate that is not revalidated after the lower level is generated.
Flow:
traps.js handles trap_pit.
It deals fall damage, then emits trap:pit:fall with the trap’s exact { x, y }.
transitionWiring.js listens for that event and queues currentDepth + 1 with targetPos: { x, y }.
transition.js sees targetPos and calls transitionToDepth directly with that fixed coordinate.
transition.js later sets the player position to that coordinate without checking isLoaded() or isWalkable() on the actual lower floor.
There is a preventive check during pit placement: floorPlan.js uses isPitLandingViable() to probe the next floor and require TILE_FLOOR. But that probe is only a synthetic lookahead. It does not validate against the final floor after transition generation/restoration, inherited stair placement, destroyed-tile replay, or floor snapshot restore.
So the likely failure is:
pit was allowed because the lookahead said same XY would be floor -> real lower floor did not actually have a loaded/walkable tile there -> transition still placed you there -> tileMap.getTile() treats unloaded space as TILE_VOID, so you appeared in void outside the map.
The fix should be a final landing guard in the transition path for pit falls: after the lower floor is generated/restored, check the requested XY with the real tile map. If not loaded/walkable, relocate to the nearest walkable tile or fall back to the generated spawn/up-stair.
User
it's odd -- I'm falling well outside of the map itself.
Assistant
That “well outside” detail points to a stronger failure than just “same XY was wall.” I’m checking whether pit viability is being tested in local chunk coordinates but the actual trap later uses world coordinates.
Assistant
That detail fits the code even better.
The pit-placement check calls isPitLandingViable(worldSeed, depth + 1, x, y), which uses probeFloorTile. That probe does this:
builds the next floor plan
directly generates the chunk containing the pit’s XY
checks whether that generated chunk has TILE_FLOOR at that coordinate
The missing part: it does not first verify that the chunk is inside the next floor’s planned extent.
So a pit can be on floor N at a coordinate that is valid for floor N, while floor N+1’s actual map does not include that chunk at all. The probe can still “pass” because generateChunk(...) can synthesize a chunk for arbitrary coordinates even outside the planned floor. Then the real transition generates only the planned chunks, and transition.js places you at the pit XY anyway.
That produces exactly what you saw: not just landing on a bad tile, but landing outside the loaded map footprint.
So the bug is:
isPitLandingViable() treats “this coordinate would be floor if we generated that chunk” as “this coordinate exists on the next map.”
It needs to also check that worldX/worldY maps to a chunk within generateFloorPlan(...).extent, and the transition should still have a final real-map isWalkable() guard before placing the player.
User
do it
Assistant
I’ll patch both layers: make pit placement reject coordinates outside the next floor’s planned extent, and add a final transition landing guard so any stale/cached edge case relocates to a real walkable tile.
Assistant
I found existing transition tests intentionally allow arbitrary fixed destinations, so I’ll keep that behavior by making walkable validation opt-in for pit falls. That gives the pit path the safety check without changing debug/portal semantics.
Assistant
I’m going to edit floorPlan, transitionWiring, and transition, then add focused tests for “outside extent is not viable” and “validated transition does not place the player in void.”
Assistant
The placement-side extent check is in, and pit falls now request validated landings. Next I’m adding the actual landing resolver inside the transition code, scoped to that opt-in flag.
Assistant
The tests now cover both halves: future pit placement cannot approve an off-map lower chunk, and a validated direct transition cannot leave the player on unloaded void. I’m running the focused suites now.
Assistant
Focused floor and transition tests are green. I’m also running the trap test because the event source stayed unchanged but it is the direct behavior around trap_pit.
Assistant
I tightened the regression test so it uses a coordinate that the old synthetic probe considered floor even though it is outside the planned floor extent. I’m doing one architecture health pass now because this touched generation and transition plumbing.
Assistant
Implemented.
Pit fixes:
floorPlan.js now rejects pit landings whose chunk is outside the next floor’s planned extent before probing synthetic tile data.
transitionWiring.js marks pit-fall depth transitions as requiring destination validation.
transition.js now validates those opt-in destinations against the real loaded lower floor and falls back to a nearby walkable tile, then generated spawn if needed.
Added regression coverage:
floor.test.mjs covers the exact old failure shape: a coordinate outside the planned floor extent that the old probe could still see as floor.
transition.test.mjs covers validated transitions refusing to leave the player in unloaded void.
Verification passed:
deno test --allow-read tests/floor.test.mjs
deno test --allow-read tests/transition.test.mjs
deno test --allow-read tests/trap.test.mjs
deno run --allow-read tools/agent-health.mjs
User
and this all happens while placing the trap? I almost feel like the trap should be placed oppertunistically almost as a lookback, or, something akin to looking at both floors at the same time when placing this type of trap.
(e.g)
wouldn't it be great if the trap worked perfectly. what you did seems a bit of a hack.
Assistant
You’re right to push on this. The runtime validation is a seatbelt, but the trap-authoring decision should be made against the lower floor that will actually exist after descent, including inherited stair positions from the current floor.
Assistant
I’m going to replace the placement-side check with the stronger version: precompute the current floor’s actual down-stair coordinates during generation, then use those as the inherited stair inputs when probing the lower floor for pit landings. The transition guard stays as a last-resort invariant, not the main behavior.
Assistant
I found the real weakness: current generation places and populates one chunk at a time, so pit placement only had a generic lower-floor probe, not the full actual stair-inherited lower-floor contract. I’m refactoring that path into “carve/place stairs for all chunks first, then populate,” which gives pit placement the real current-floor down-stair list before any traps are authored.
Assistant
The deeper placement path is now wired: generateFloor finishes stair placement for the entire floor before population, stores the actual down-stair positions on the floor plan, and pit trap viability uses those positions when probing the lower floor. I’m running the focused generation tests to catch any determinism/order fallout.
Assistant
The refactor passed floor, transition, and navigation tests. I’m doing one direct seed sweep now: generate a floor with pit traps, generate the exact lower floor using that floor’s actual down-stair positions, and assert every pit lands on a walkable tile.
Assistant
A reduced seed sweep checked 46 generated pit traps against the exact lower floors produced with inherited down-stair positions; all landed on walkable tiles. I’m running the trap suite and health pass again after the placement refactor.
Assistant
You were right. The first fix prevented the bad outcome, but the better fix is to make pit placement reason about the actual lower floor contract.
I changed generation so dungeon floors now place stairs for the whole floor before population. That gives trap placement the real downStairPositions for the current floor. Pit-trap viability now probes depth N+1 using those positions, matching the floor that will actually be generated when the player falls.
I kept the transition validation too, but it is now a final invariant guard, not the primary solution. If a cached/restored floor or future generation change breaks the placement guarantee, the player still won’t be placed in unloaded void.
Changed:
index.js: carve/place stairs across all chunks before population.
populate.js: pit trap placement uses lower-floor probing with actual inherited stair positions.
floorPlan.js: probe/viability accept inherited stair positions and reject outside-extent coordinates.
transition.js: validated transitions refuse unloaded/non-walkable destinations as a last line of defense.
Verified:
deno test --allow-read tests/floor.test.mjs
deno test --allow-read tests/transition.test.mjs
deno test --allow-read tests/nav.test.mjs
deno test --allow-read tests/trap.test.mjs
deno run --allow-read tools/agent-health.mjs
Direct seed sweep: 46 generated pit traps checked against their exact generated lower floors, all walkable.
User
and why the heck would stairs be involved at all? remember, pit traps are one-way. you understood that right?
Assistant
Yes, pit traps are one-way. I did not mean they should create stairs or behave like stairs.
Stairs are involved only because the existing lower-floor generator already uses “down stairs from floor N” as topology constraints when generating floor N+1. Those inherited positions carve/connect the lower floor and place up-stairs. So if pit placement wants to predict the actual floor N+1 the game will generate, it has to include those existing stair constraints or it is predicting the wrong floor.
But your instinct is correct: a pit landing should really be its own one-way landing constraint, not piggyback mentally on stair logic.
The clean model is:
Floor N places pit trap at (x, y).
That records a one-way landing anchor for floor N+1 at (x, y).
When floor N+1 is generated, it treats that anchor like “must be walkable and connected,” but does not create a stair or any return path.
The pit transition lands at that anchored tile.
What I implemented makes pit placement compare against the lower floor as currently generated. It does not turn pits into stairs, but it is still defensive rather than fully modeling “pit landing anchors” as first-class generation inputs.
The better next change is to add a forcedLandingPositions/pitLandingPositions generation input and have the lower floor carve/connect those locations without materializing stair entities. That would make pit traps work intentionally instead of merely selecting positions that already happen to work.