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.
three gameplay bugs,these are possible repeats so they'll need a more careful eye.
throwing shop items out of the shop is NOT supposed to create a shop debt -- we were intentionally trying to allow the player to exploit systems BUT track the fact for future use.
pay bill in shops does not work despite having money
3.thrown potions took a regression
applying potion to weapon shows no targets
focus on ONE of these so I can publish quickly - I'm on a short train ride.
Q: do we have access to GH issues?
Assistant
We have the GitHub plugin available in this session, so I can inspect issues/PRs if the connector is authorized for this repo. I’ll first verify the local game context and pick the quickest high-confidence bug to fix.
Assistant
The first shop debt bug looks like the fastest publishable target because the search already points to a single claim/debt utility. I’m narrowing that path and checking the existing tests so I can change behavior without disturbing the shop enforcement flow.
User
you answerd the question -- move onto the first item.
Assistant
Understood. I’m on item 1 only: thrown shop stock should leave a claim/incident trail, but no payable debt.
Assistant
I found the regression: onItemThrown delegates to recordUnpaidExtraction, whose default is to create payable debt. I’m changing only that thrown-out path to record the claim/incident with createsDebt: false; consumption theft and carried-out behavior stay unchanged.
Assistant
The implementation change is in. I’m updating the focused tests to lock the intended exploit behavior: claim/incident yes, payable debt no.
Assistant
The tests now encode the distinction explicitly. I’m running the shop-law test first, then a small commerce-adjacent subset if it passes.
Assistant
The focused test exposed a test detail, not a behavior failure: persisted ShopClaim stores claimKind rather than a separate reason field. I’m aligning that assertion with the component shape.
Assistant
The assertion is fixed. I’m rerunning the focused test now.
Assistant
The focused regression test is green. I’m running nearby shop claim/debt/enforcement tests to catch any unintended commerce fallout before I stop.
Assistant
The adjacent shop tests are clean. I’m checking the final diff so I can give you the exact publishable scope.
Assistant
Fixed item 1.
Thrown unpaid shop stock now records the shop claim/incident but does not create payable debt: shopLaw.js.
Updated tests to lock that behavior for single items and stack units: shopLaw.test.mjs.
Verification passed:
deno test --allow-read tests/shopLaw.test.mjsdeno test --allow-read tests/shopClaim.test.mjs tests/shopDebt.test.mjs tests/shopEnforcement.test.mjs tests/shopkeeperSystem.test.mjs
User
and how does the shopkeeper react?
Assistant
For thrown unpaid stock out of the shop, the shopkeeper still reacts through the law/incident path:
A ShopClaim is recorded with claimKind: "thrown_out".
A ShopIncident is recorded with reason: "thrown_out" and evidence: "seen".
shop:theft-escaped still emits.
shop:pursuit-requested still emits for the tested 250g item because the severity is high enough.
What changed is only this: the claim has debtId: 0, and calculateShopDebt(...) stays 0, so “pay bill” has nothing new to pay from that throw.
User
and the player wiill be let out?
Assistant
Yes, for the thrown item case itself.
After a single unpaid shop item is thrown out:
the item is no longer carried by the player
no shop debt is created
shopkeeperSystem only blocks on carried unpaid goods or existing debt
so the player should be allowed to walk out, unless they still carry other unpaid goods or already have prior debt
One caveat: for a stack, throwing one unit leaves the remaining stack in inventory. The player would still be blocked/billed for the remaining unpaid stack, but not for the unit they threw out.
User
easy enough -- next item?
Assistant
I’ll move to item 2: “pay bill” in shops. I’m going to trace the checkout action from UI/event payload into the rules utility and add a focused test around “has enough money, debt clears.”
Assistant
There is already a checkout regression test, so this is likely a mismatch between the test fixture and the real UI/session path. I’m reading shopWiring around payment and the existing checkout test to find the missing condition.
Assistant
The payment handler itself allows checkout even when the shopkeeper is no longer adjacent, and the existing fixture passes. The likely weak spot is the UI event detail: the Pay button sends state.shopkeeperId, so if overlay state did not carry that field in checkout mode, the handler gets 0 and silently does nothing. I’m checking the overlay state wiring next.
Assistant
The overlay state is populated by ui:openShop, but shopWiring dispatches ui:shopData before ui:openShop on checkout. That means the first checkout render can have invoice data but state.shopkeeperId === 0, so Pay Bill dispatches an unusable event. I’m going to make the shop overlay prefer data.shopkeeperId with state as fallback.
Assistant
One more check before editing: the closure references the mutable state object, so the dispatch order may not be enough to explain it. I’m checking the currency component shape, because “has money” can still fail if shop wiring only counts one currency type.
Assistant
Currency shape is consistent. I’m going to add a regression that exercises the actual display button path with checkout data rendered before open state, because that is the fragile path most likely to produce “button does nothing.” If it reproduces, the fix will be small and display-only.
Assistant
A cleaner reproduction is in the rules/main handler: if ui:payBill arrives without a valid shopkeeperId, it currently treats that as no nearby shopkeeper and bails. I’m making checkout payment fall back to the active checkout session’s shopkeeper, then adding a test that dispatches the same kind of incomplete UI event.
Assistant
The handler now uses the active checkout session if the UI event omits the shopkeeper id. I’m adding the regression test beside the existing checkout tests.
Assistant
The regression test is in. I’m running checkout and nearby shop tests now.
Assistant
The checkout regression and adjacent shop tests pass. I’m doing one final diff check so I can keep the handoff tight.
Assistant
One note: the current worktree now only shows the checkout fix files. Your earlier shop-law change is no longer in the local diff, so I’m verifying whether that file already contains the intended behavior before I close this out.
Assistant
Fixed item 2.
ui:payBill now falls back to the active checkout session’s shopkeeper when the UI event omits shopkeeperId, so Pay Bill can complete even from the blocked-exit checkout popup: shopWiring.js.
Added a regression test for that exact incomplete UI event path: shopWiringCheckout.test.mjs.
Verification passed:
deno test --allow-read tests/shopWiringCheckout.test.mjs tests/shopkeeperSystem.test.mjs tests/shopEnforcement.test.mjsdeno test --allow-read tests/shopLaw.test.mjs
User
FAILURE: clicking "pay bill" does nothing, clicking "return item" does work.
Assistant
That narrows it: the display button path is still suspect, because the rules handler path works under direct event tests. I’m going to inspect the checkout renderer more carefully and reproduce the button click shape rather than the raw ui:payBill event.
Assistant
I found the actual bug. Checkout render calls setSel(0) before setSel exists; that throws during render after the row Return buttons are wired but before the Pay Bill button is wired. That exactly matches “Return Item works, Pay Bill does nothing.” I’m moving selection initialization after createSimpleSel.
Assistant
I’m also making the checkout buttons use data.shopkeeperId as the first source, so they do not depend on overlay state update order. That keeps the UI path robust.
Assistant
The render-order bug is patched. I’m checking remaining shop button dispatches and adding a regression guard for the checkout renderer so this specific failure cannot come back silently.
Assistant
The remaining state.shopkeeperId uses are in browse buy/sell/appraise actions, not the checkout block. I’m adding a focused source-level regression test for the checkout initialization order because the project test environment does not provide a real DOM.
Assistant
The regression guard is in. I’m running the new overlay guard plus the checkout payment tests.
Assistant
The runtime checkout tests pass; the new source guard was slicing too narrowly for the shared shopkeeperId constant. I’m correcting that assertion.
Assistant
The source guard is fixed. I’m rerunning the checkout group.
Assistant
The button-path issue is fixed and the checkout suite is green. I’m checking the diff and status for a concise handoff.
Assistant
Found the real reason: checkout render was throwing before wiring the Pay Bill button.
Return Item worked because row return buttons were attached before the throw. Pay Bill did nothing because its click listener was attached after the bad setSel(0) call.
Fixed in shopOverlay.js:
selection init now happens after createSimpleSel(...)
checkout actions use data.shopkeeperId first, then state fallback
Kept the prior backend fallback in shopWiring.js, so incomplete UI events still resolve through the active checkout session.
Added guards/tests:
shopOverlayCheckout.test.mjs
shopWiringCheckout.test.mjs
Verification passed:
deno test --allow-read tests/shopOverlayCheckout.test.mjs tests/shopWiringCheckout.test.mjs tests/shopkeeperSystem.test.mjs tests/shopEnforcement.test.mjs