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.
New events use concrete event classes. Any new event contract must define
a concrete EcsEvent class and emit an instance with
world.emit(new Event(...)). Do not introduce string-only events or parallel
string re-emits for new contracts.
Touched listener installers use canonical extensions. Any new listener
installer, or any existing listener installer touched during a task, must use
defineExtension(...) and world.install(...) for idempotent installation.
Do not add new bespoke symbol-guard installers.
No swallowed event failures. Do not add emitSafe-style wrappers around
world.emit.
there must be more to the performance discussion. I've attached an exported world-state from the session that save severly degraded.
Assistant
I’ll use the repo’s Entire guidance first so the investigation lines up with prior architecture intent, then I’ll inspect the exported save and trace the likely hot paths that scale with that state.
Assistant
The first search was too broad because it hit generated/docs content. I’m narrowing to the save/load and per-frame projection paths, then I’ll quantify the attached save rather than guessing from symptoms.
Assistant
The save is readable and is 1.6 MB, so this is large enough to be useful but not obviously “huge save file” territory. Next I’m counting component populations and looking for abnormal entity classes, because performance degradation usually comes from a few scaling paths rather than raw JSON size.
Assistant
This export uses the ECS serializer shape where entities are not under .world.entities; my first count hit the wrong path. I’m opening the serializer and registry now, then I’ll re-run the counts against the actual snapshot arrays.
Assistant
The save is a settings export (reason: settings_export), but it still contains a full serializeWorld snapshot under world. I’m now measuring the component tables directly and cross-checking that against scheduler/projection code.
Assistant
The standout signal is topology, not monsters: 2,544 alive entities, but 2,061 Sibling, 1,003 Parent, 920 AffixTopologyNode, and 464 ProcNode. That suggests runtime item/proc topology has ballooned and may be dragging any system that scans relationships. I’m checking which code touches those components per frame/per turn.
Assistant
The topology rows show many children under the same parent IDs, so I’m checking whether that’s normal inventory/equipment structure or duplicated affix children on items. I’m also going to run a local restore/projection timing pass from this save, which should turn the file into concrete hot-path evidence.
Assistant
The local Deno version wants permissions before eval, so that timing probe needs a corrected invocation. Meanwhile, the code confirms one expensive pattern: affix evaluation destroys and rebuilds equipped affix topology before evaluating, and hierarchy attach does index bumping through siblings.
Assistant
There’s also repeated call-site pressure: melee, ranged, and deal-damage paths all call ensureEquippedAffixTopology, and evaluateEquippedAffixProcs calls it again internally. If the topology is already bloated, those repeated destroy/rebuild passes compound badly during combat-heavy turns.
Assistant
I can’t pass --allow-read to this Deno build’s eval, so I’m switching that probe to plain deno eval and the project’s approved shell/JQ tooling for static counts. The code-level evidence is enough to keep narrowing without changing files yet.
Assistant
The save has a smoking gun: entity 409, an Iron Mace, has 918 direct children. That is not normal inventory shape; those children are almost all affix/proc topology. I’m checking why that item escaped the normal “destroy old affix children before rebuild” path.
Assistant
The root cause is now clear: destroyAffixChildren iterates the live linked-list from children(world, itemId) while destroySubtree detaches the yielded child. That invalidates the generator’s next pointer, so only the first old affix child is removed. Every rebuild then adds two new children and removes one, which matches the save: about 459 rebuilds of a two-affix mace. I’m going to patch that to snapshot child IDs before destroying, and add a regression test for repeated topology rebuilds.
Assistant
I’m making a small, targeted change: snapshot matching affix child IDs before destruction, then assert repeated ensureAffixTopology calls keep exactly one child per authored affix. This preserves the existing topology model and fixes the leak at the linked-list mutation point.
Assistant
The patch is in place. I’m running the focused topology test first; if that passes, I’ll run the relevant proc-affix test file because it exercises the combat paths that were repeatedly rebuilding this topology.
Assistant
Focused tests pass. One important operational detail remains: an already-bloated save will still load with the stale children; it will be pruned the next time ensureAffixTopology touches that item. I’m checking whether the bloated mace is equipped in this save and whether load-time cleanup should be added.
Assistant
The bloated item is equipped as the player weapon, so the fixed code collapses it from 917 affix children to 2 as soon as the normal equipped-affix path runs. I’m running the project guard check now to catch any architecture/test fallout.
Assistant
The full deno task check passed. I’m doing one final diff/status pass so I can summarize the exact cause, fix, and what the attached save proved.
Assistant
One more thing: the generation bug is fixed, but old saves would still load with stale topology until some combat path touched the item. Because the attached mace is equipped, that stale subtree can still tax derived-stat/proc traversals right after load. I’m adding a load-time normalization pass over item affix topology so existing saves are healed immediately.
User
<turn_aborted>
The user interrupted the previous turn on purpose. Any running unified exec processes may still be running in the background. If any tools/commands were aborted, they may have partially executed.
</turn_aborted>
User
dont bother -- we have no players. ;-)
Assistant
Fair. I stopped before adding load-time save normalization.
What’s currently changed is just the actual leak fix: destroyAffixChildren now snapshots affix child IDs before destroying them, so repeated ensureAffixTopology calls stop accumulating stale affix nodes. The attached save proved it: the equipped Iron Mace had 917 affix children, and the fixed path collapses that to 2.
Verified:
deno test --allow-read tests/enchantmentTopology.test.mjsdeno test --allow-read tests/procAffixes.test.mjsdeno task check
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
No new world-attached state. Do not attach simulation state to world
with symbol or property keys (world[...], ctx.world[...]). Use ECS
components for state; when the state is genuinely world-scoped, model it as an
explicit singleton entity/component and document the allowance. Existing
world-attached state is a ratcheted architecture debt tracked by
ratchets/worldStateAttachmentRatchet.test.mjs.
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.
Authoring discipline. Do not touch unrelated code. Do not make changes
that do nothing. Always match the formatting preferences that already exist;
be a chameleon.
Search before writing. Extend existing patterns. Do exactly what was
asked; no opportunistic content wiring or unrelated cleanup.
Agent Commands
Run these before guessing.
Guardrail Tasks
Prefer these Deno tasks over hand-assembled command strings:
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.
Install listeners with world.install(featureListeners) 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
New event contracts must be concrete EcsEvent classes: