Technical Memo
JSHack: Multi-Entrance Dungeon Pressure, Town Economy, and Player Jobs on top of ecs-js
Status
Draft for implementation planning.
Purpose
This memo proposes an implementation approach for a living town economy in JSHack where multiple dungeon entrances exert overlapping influence on a settlement, NPC labor emerges from real economic need, and the player can participate in all major jobs. The underlying runtime model assumes ecs-js as the substrate.
The core design goal is to preserve the value of a detailed simulation without forcing gameplay, dialogue, and quest logic to read directly from raw transactions. Instead, JSHack should treat the deep economy as a substrate, then derive a higher-order interpretation layer that produces visible consequences, social tension, and actionable play.
The intended result is a world in which:
- The town economy is not decorative.
- The dungeon is not a disconnected loot dispenser.
- Multiple entrances deform the town in distinct ways.
- NPCs speak coherently about conditions they experience locally.
- The player can work inside any part of the economic system.
- ecs-js remains the foundational architecture for entities, components, relationships, systems, and derived state.
1. Design Thesis
JSHack should treat the town, dungeon, and labor market as one continuous organism.
The dungeon is not merely a combat zone. It is a source of:
- materials
- instability
- disease
- corruption
- labor demand
- faction leverage
- rumor
- fear
- opportunity
The town is not merely a shop hub. It is the surface-side interpretation and redistribution mechanism for those pressures.
The player should not only delve. The player should be able to:
- mine
- haul
- smith
- heal
- guard
- bury
- brew
- cook
- trade
- appraise
- scavenge
- preach
- smuggle
- repair
- clean drains
- patrol roads
- and of course delve
This means the same underlying economy should be legible through many professions.
A smith sees the world through ore and repair queues.
A healer sees the world through wounds and reagent shortages.
A hauler sees the world through route safety and delivery backlog.
A grave worker sees the world through mortality, taboo, and temple influence.
A delver sees the source conditions that propagate outward into all the above.
The simulation must therefore be split into layers.
2. Architectural Principle: Substrate vs Interpretation
A common failure mode in simulation-heavy roguelikes is assuming that if the world simulates enough detail, gameplay will automatically become meaningful.
It will not.
Raw transaction detail is valuable, but mostly as substrate.
Substrate layer
This is the deep, mechanical world.
Examples:
- workers harvesting grain
- haulers moving sacks
- smiths consuming ore and charcoal
- households consuming food and fuel
- carts taking time to travel routes
- injuries generating treatment demand
- burial work consuming cloth, incense, and labor
- dungeons generating monster pressure, spoilage, rare materials, and hazard events
Interpretation layer
This is the layer that decides which patterns are visible, meaningful, and socially narratable.
Examples:
- ore shortage becoming a town concern
- east road becoming known as unsafe
- temple influence rising after graveyard disturbances
- repair demand outpacing smith capacity
- spoiled food causing sickness in a district
- guards being diverted to escort duty
- taverns filling with displaced miners
- players hearing coherent rumors about what changed
The design requirement for JSHack is simple:
Deep simulation should continue to exist, but nearly all player-facing systems should consume summarized, derived, thresholded state instead of raw transaction logs.
This is where ecs-js becomes especially useful.
3. Proposed World Model in ecs-js
JSHack should represent most important game facts as ECS entities with composable components. Relationships such as containment, assignment, district membership, route membership, and entrance influence should use hierarchical or relational patterns already aligned with ecs-js.
3.1 Major entity classes
At minimum, the world should contain entities for:
- entrances
- districts
- buildings
- workplaces
- resource nodes
- production sites
- routes
- factions
- households
- NPCs
- player
- jobs/contracts
- incidents
- rumors
- market sectors
- inventories/containers
- shipments
- dungeon strata/regions
3.2 Recommended component categories
Below is a suggested conceptual component breakdown.
Identity / topology
Name
Kind
Position
DistrictRef
FactionRef
RouteRef
EntranceRef
Parent / hierarchy linkage
Economic role
WorkRole
ProductionProfile
ConsumesResources
ProducesResources
Inventory
StorageCapacity
LaborCapacity
DemandProfile
SupplyProfile
Social / local state
Mood
Fear
Trust
Biases
ProfessionKnowledge
RumorAccess
Reputation
FactionStanding
Dungeon / entrance pressure
Pressure
Corruption
Traffic
ResourceYield
Accessibility
FactionControl
RecentIncidents
EntranceInfluenceField
Interpretation / summaries
DistrictSummary
SectorSummary
LocalConditions
CriticalShortages
RecentEventSummary
NarrativeState
TalkingPoints
Player capability / jobs
SkillSet
ToolAccess
JobEligibility
KnownTechniques
PerceptionTags
Exhaustion
Injury
SanctionedRoles
Event / incident
EconomicIncident
CauseChain
Severity
Spread
Visibility
Resolved
This does not imply that every component must be materialized as persistent storage. Some should be implemented as virtual components or memoized derived views.
That is one of the strongest fits with ecs-js.
4. Multiple Dungeon Entrances as Pressure Sources
JSHack should explicitly model multiple entrances, each with distinct economic signatures and social meaning.
Proposed initial entrances:
- North
- South
- East
- West
- Town
- Graveyard
Each entrance should not merely represent a map doorway. It should act as a regional pressure source.
4.1 Entrance state vector
Each entrance should expose a compact but expressive state vector:
pressure
resourceYield
corruption
traffic
knowledge
factionControl
accessibility
localFear
incidentRate
These values are intentionally small in number. The goal is not exhaustive realism. The goal is enough state to meaningfully deform districts, labor demand, faction behavior, and dialogue.
4.2 Suggested entrance signatures
North
Possible emphasis:
- ore
- stone
- cold
- mining camps
- tools
- disciplined enemies
- fortress ruins
Likely economic impact:
- smithing demand
- hauling demand
- guard escorts
- food support for workers
- equipment wear
South
Possible emphasis:
- rot
- fungi
- marsh goods
- disease vectors
- alchemy
- soft hazards
- smugglers
Likely impact:
- apothecary demand
- healer stress
- sanitation jobs
- burn crews
- reagent trade
East
Possible emphasis:
- roads
- caravans
- relic traffic
- bandits
- manufactured salvage
- toll politics
Likely impact:
- trade volatility
- appraiser demand
- escort contracts
- merchant faction influence
- tavern rumor density
West
Possible emphasis:
- woods
- beasts
- timber
- hunters
- shrines
- foraging
- old mounds
Likely impact:
- timber and trap goods
- guides and scouts
- beast products
- druidic or shrine tension
Town
Possible emphasis:
- sewers
- foundations
- cellars
- old wells
- rats
- hidden tunnels
- smugglers
- direct civic disruption
Likely impact:
- drain crews
- ratters
- masons
- sanitation work
- cellar collapses
- daily fear close to the player
Graveyard
Possible emphasis:
- necromancy
- burial disruption
- relics
- mourning
- temple authority
- taboo labor
- black-market bone trade
Likely impact:
- priests
- buriers
- incense makers
- wardens
- exorcists
- social panic
- moral conflict
4.3 Influence as overlapping fields
Each district should not belong to one entrance. Instead, districts should receive overlapping influence values from all nearby or culturally relevant entrances.
Example conceptual fields per district:
northInfluence
southInfluence
eastInfluence
westInfluence
townInfluence
graveyardInfluence
These do not need to be exposed directly to the player. They should drive derived world facts such as:
- atmosphere
- labor demand
- goods seen on streets
- prevalent rumors
- common injuries
- local shop stress
- faction posture
This gives the town a deformed, living geography rather than a set of arbitrary neighborhoods.
5. Jobs as First-Class World Verbs
The player must be able to do all jobs.
This is not a flavor request. It is a core systems requirement.
If only NPCs participate in the economy, then the economy remains spectacle. If the player can perform labor in every major sector, the player can inhabit the economy directly.
5.1 Jobs should not be isolated minigames
Each job must connect to at least three layers:
- resources
- relationships
- risk
Examples:
Mining
Touches:
- node depletion
- tool wear
- hauling demand
- cave hazard exposure
- ore supply
- route safety
Smithing
Touches:
- resource consumption
- repair economy
- military readiness
- faction allocation fights
- craftsmanship reputation
Hauling
Touches:
- logistics bottlenecks
- theft risk
- route knowledge
- visibility of shortages
- fatigue and scheduling
Healing
Touches:
- injury treatment
- disease monitoring
- reagent scarcity
- social trust
- temple/clinic coordination
Burial / Grave work
Touches:
- mortality processing
- taboo systems
- temple authority
- graveyard pressure
- necrotic contamination risk
Tavern work
Touches:
- rumor density
- traveler throughput
- debt
- class contact
- faction overhearing
Delving
Touches:
- source-side risk
- extraction
- suppression of pressure
- discovery
- salvage rights
- destabilization and profit
5.2 Job access tiers
The player should be able to do all jobs eventually, but access should not be flat.
Suggested tiers:
- Casual labor — anyone can do it badly.
- Skilled trade — requires tools, training, or space.
- Hazard labor — requires courage, fitness, or tolerance.
- Sanctioned labor — requires faction approval, ritual right, legal status, or trust.
This preserves progression and social texture without violating the design goal.
5.3 Jobs as perception filters
A major implementation opportunity is to let jobs alter what the player can perceive.
A smith can identify alloy quality.
A healer can classify wound origin and contamination.
A hauler can see packaging failures and route inefficiency.
A priest can detect desecration.
A gravedigger can spot disturbed soil.
A tavern worker can tell rumor density from ordinary chatter.
This turns job participation into a way of reading the world, not merely earning resources.
In ECS terms, these can be represented as skill-derived or profession-derived perception tags.
6. Event-Driven Economy with Derived Summaries
Even if JSHack simulates every transaction, the player-facing game should rarely care about transactions individually.
Instead, the world should continuously derive higher-order summaries.
6.1 Deep simulation is allowed
JSHack can absolutely model:
- every delivery
- every worker shift
- every consumption event
- every route travel step
- every inventory transfer
- every item transformation
That is not a flaw.
But direct game logic should generally not read those events one by one.
6.2 Promote patterns, not noise
A summary system should roll up raw activity over windows of time and produce derived facts such as:
- grain deliveries down 23%
- smith repair queue doubled
- east road traffic collapsed
- incense demand spiking
- healer stock depleted in south district
- burial labor backlog forming
- lamp oil consumption rising faster than supply
- monster remains entering market in unusual volume
Those are the socially visible truths the rest of the game should react to.
6.3 Storyworthy thresholds
Continuous values should be converted into discrete thresholds before they affect dialogue, questing, or town mood.
Example threshold bands:
- stable
- tight
- strained
- scarce
- panic
And for danger:
- safe
- uneasy
- dangerous
- closed
And for dungeon pressure:
- quiet
- rumbling
- active
- bleeding
This prevents microscopic noise from becoming constant social chatter.
6.4 Hysteresis
Threshold systems should include hysteresis so the town does not flip moods on tiny oscillations.
Example:
- a district may enter
scarce at 20% stock depth
- but only leave
scarce once stock depth rises back above 35%
This is essential for believable persistence.
7. Proposed Layer Stack for JSHack
The town-dungeon model should be implemented as a layered pipeline.
Layer 1 — Physical substrate
Raw ECS entities and systems handle:
- resource production
- hauling
- consumption
- work assignments
- route traversal
- crafting
- inventory changes
- disease spread
- pressure accumulation
Layer 2 — Analytic summaries
Systems derive:
- throughput
- shortages
- stock depth
- route failures
- unmet demand
- labor idleness
- repair backlog
- district stress
- entrance pressure outputs
Layer 3 — Narrative interpretation
Systems translate summaries into:
- local conditions
- rumors
- faction concerns
- job postings
- district mood
- visible shortages
- overheard complaints
- notable opportunities
Layer 4 — Player-facing consequences
Gameplay consumes interpretation data to drive:
- NPC dialogue
- prices or allocation priority
- job availability
- contracts
- quests
- access restrictions
- faction posture
- map atmosphere
- player opportunities
This separation should be treated as a hard architectural boundary where possible.
8. NPC Dialogue and Social Interpretation
NPCs should not speak directly from raw simulation values.
They should speak from role-local interpretations of the world.
8.1 NPC observables
Each profession should read a filtered subset of local summary state.
Examples:
Guard observes
- road incidents
- monster sightings
- curfew pressure
- escort demand
- patrol injuries
- staffing levels
Smith observes
- ore arrivals
- repair queue size
- military orders
- miners not showing up
- charcoal shortages
Healer observes
- wound categories
- infections
- reagent depletion
- district disease spikes
- burial overflow
Priest observes
- donation volume
- omens
- burial traffic
- desecration reports
- temple attendance
Tavern worker observes
- traveler volume
- rumor density
- tab defaults
- mercenary presence
- food complaints
8.2 NPC knowledge model
A practical dialogue model can separate speech material into:
- Facts — directly observed truths
- Suspicions — inferred from role bias
- Rumors — socially received, possibly wrong
- Angles — what the NPC wants from this conversation
- Voice rules — temperament, cadence, vocabulary
This allows NPCs to be coherent but not omniscient.
They should frequently be wrong.
That is a feature.
8.3 Talking points as structured output
Rather than generating dialogue directly from the entire simulation, each NPC should receive a small set of structured talking points.
Example:
{
role: "smith",
mood: "irritated",
trustPlayer: 0.45,
topConcerns: [
"ore_shortage",
"repair_backlog",
"miners_missing"
],
recentEvent: "east_caravan_late",
bias: "guild_is_weak",
playerRelevance: "player_sold_raw_iron_recently"
}
This can then render to voiced lines such as:
- "Four days late on the east road. You tell me that isn’t trouble."
- "Guard wants helms, farmers want tools, and I’m meant to hammer air?"
- "If you’ve got iron, sell it now. Tomorrow it’ll cost blood."
The important point is that line generation should consume structured concern state, not raw economics.
8.4 District bulletin model
A useful simplification is to maintain a local bulletin for each district:
- top shortages
- top dangers
- top opportunities
- top scandals
- unresolved incidents
- dominant rumors
NPCs in that district then sample from the bulletin according to profession and bias.
This dramatically increases apparent coherence at low implementation cost.
9. Factions and Political Economy
Factions should sit above sectors and below dialogue, acting as pressure multipliers and response mechanisms.
Likely factions:
- merchants
- temple
- watch
- delvers
- smugglers
- guilds
- landholders
- civic authority
Factions should respond to analytic thresholds.
Examples:
- if ore scarcity becomes severe, guild petitions for protected shipments
- if graveyard pressure rises, temple asserts burial authority
- if east route closes, merchants shift to black-market logistics
- if town entrance destabilizes, watch expands patrols and curfews
- if south contamination spreads, clinic and temple dispute treatment policy
This matters because the town should not merely reflect economics. It should interpret economics through institutions.
That is where social conflict comes from.
10. Virtual Components and Derived State in ecs-js
This proposal is a strong fit for virtual components or memoized derived views.
JSHack should avoid materializing every high-level interpretation value as manually maintained state if it can instead be derived efficiently and cached per tick.
Examples of excellent virtuals:
DistrictLocalConditions
EntrancePressureSummary
NPCObservables
JobDemandView
CriticalShortageView
FactionStressView
TalkingPointSet
PlayerOpportunityView
These virtuals should depend on:
- inventories
- route throughput
- incidents
- district membership
- nearby entrance influence
- profession
- recent event windows
This aligns well with ecs-js patterns where derived state is computed from authoritative data and invalidated per simulation step.
The memoized view approach is especially important because the interpretation layer will otherwise become brittle, duplicated, and difficult to maintain.
11. Suggested ECS System Breakdown
Below is a possible system grouping for implementation.
11.1 Substrate systems
- resource production system
- work assignment system
- hauling / route traversal system
- consumption system
- inventory transfer system
- crafting system
- injury / disease propagation system
- burial / remains handling system
- entrance pressure accumulation system
11.2 Analytic systems
- throughput aggregation system
- shortage detection system
- route failure detection system
- district stress system
- labor demand synthesis system
- backlog analysis system
- incident clustering system
- dependency chain analysis system
11.3 Interpretation systems
- district bulletin synthesis system
- faction response synthesis system
- rumor generation system
- NPC observables synthesis system
- dialogue talking point synthesis system
- player job opportunity synthesis system
- visible map atmosphere system
11.4 Player/world consequence systems
- job board update system
- price / allocation adjustment system
- quest emission system
- access restriction system
- district behavior modification system
- ambient chatter selection system
This is deliberately layered. It should be possible to disable, test, or inspect each band independently.
12. Dependency Chains as a First-Class Mechanic
One of the most powerful uses of the existing detailed economy is automatic dependency chain discovery.
Example:
No resin from lower caves
-> fewer torch bundles
-> less safe mine work
-> lower ore extraction
-> fewer tool repairs
-> weaker farm output
-> food anxiety rises
-> theft rises
-> guard fatigue rises
-> pressure to clear the relevant entrance increases
These are exactly the kinds of chains the player should be able to discover, exploit, or repair.
The system does not need to explain every chain explicitly. But it should be able to identify hot bottlenecks and propagate pressure causally across sectors.
Possible implementation approach:
- represent production dependencies as directed edges
- track recent edge weakness or failure
- compute delayed downstream impact estimates
- convert the strongest chains into incidents or summary tags
This can power:
- dialogue specificity
- faction demands
- urgent work contracts
- strategic dungeon objectives
- player planning
13. How Dungeon Delving Connects to the Economy
Delving should affect the economy in at least five ways.
13.1 Extraction
The player recovers scarce or impossible-to-produce inputs.
Examples:
- rare ore
- fungal reagents
- relic metal
- cursed gold
- machine parts
- map fragments
- sacred remains
- old-world texts
13.2 Suppression
The player reduces pressure sources that would otherwise destabilize routes, labor, and public safety.
Examples:
- monster nests
- contamination blooms
- necrotic seepage
- raiding bands
- blocked tunnel links
- cult activity
13.3 Discovery
The player learns things the surface does not yet know.
Examples:
- north shaft is flooded
- smugglers are using the town entrance
- graveyard corruption is linked to a relic below west shrines
- east bandit activity is being supplied from an abandoned forge level
13.4 Labor creation
Delving changes what jobs are in demand.
Examples:
- reopening a shaft creates mining and hauling jobs
- contamination creates burn crew and healer demand
- necrotic activity creates burial and temple labor demand
- relic recovery creates appraisal and ritual work
13.5 Political leverage
Recovered goods and revealed truths create faction conflict.
Examples:
- who gets first claim on relic metal
- whether holy remains belong to temple or delver
- whether townsfolk should know the true cause of a grave outbreak
- whether salvage rights supersede civic need
This means delving is not just combat. It is civic intervention, extraction, and destabilization all at once.
14. Player Doing All Jobs: Strategic Consequences
Allowing the player to do all jobs creates several system-level advantages.
14.1 Many interfaces into one world
The player can understand the same crisis from multiple sectors.
14.2 Natural arbitrage
The player can move between jobs to exploit or stabilize bottlenecks.
Example loop:
- mine ore
- haul it to town
- smith needed tools
- earn trust and coin
- fund a deeper expedition
- recover relic alloy
- have it blessed
- forge elite equipment
14.3 Identity through action
The player’s labor history should affect:
- standing
- perception
- dialogue options
- access rights
- faction posture
- skill growth
14.4 Non-combat progression
The game becomes structurally richer because progress is possible through:
- service
- infrastructure work
- trade
- burial duty
- logistics
- clinic support
- scouting
This is especially valuable for a simulation-heavy roguelike.
15. Minimum Viable Implementation Path
This can be staged.
Phase 1 — Entrances and district influence
Implement:
- 6 entrance entities
- compact entrance state vector
- district influence fields
- simple derived local conditions
Phase 2 — Job demand and sector summaries
Implement:
- sector entities or sector summaries
- district bulletins
- shortage and backlog thresholds
- job demand synthesis
Phase 3 — NPC observables and talking points
Implement:
- profession-specific observables
- structured talking point generation
- role-local chatter rendering
Phase 4 — Player jobs
Implement:
- casual and skilled versions of 3 to 5 core jobs
- job-specific perception benefits
- job gating by tools / trust / sanction
Phase 5 — Dependency chain analysis
Implement:
- directed production dependencies
- bottleneck propagation
- incident synthesis from upstream failures
Phase 6 — Faction responses
Implement:
- threshold-triggered faction actions
- reputation impact
- contracts and political contention
This ordering allows visible payoff early while preserving the larger design trajectory.
16. Guidance Specific to ecs-js
This proposal is particularly well suited to ecs-js if the following design choices are maintained.
16.1 Preserve authoritative low-level state
Inventories, assignments, locations, work relationships, incidents, and route traffic should remain authoritative.
16.2 Prefer derived views for high-level interpretation
District mood, shortages, local concerns, NPC observables, and player opportunities should be derived.
16.3 Use hierarchy for locality and containment
District membership, building containment, job site membership, and possibly social or civic groupings should exploit hierarchical helpers where useful.
16.4 Keep systems phase-ordered
A likely scheduler order:
- substrate mutation
- inventory/resource settlement
- incident emission
- analytic summary generation
- interpretation generation
- dialogue / quest / job consequence generation
- rendering / UI extraction
This avoids in-tick incoherence and keeps derived layers reading settled facts.
16.5 Make summaries inspectable
For debugging, there should be direct developer views for:
- district bulletins
- entrance state vectors
- current bottlenecks
- job demand
- faction stress
- NPC talking points
This is essential for tuning a layered sim.
17. Risks and Failure Modes
Failure mode 1 — Reading raw simulation directly everywhere
This creates noise, brittleness, and impossible tuning.
Failure mode 2 — Over-authoring dialogue
If dialogue is not generated from real observables, the economy becomes fake again.
Failure mode 3 — No thresholds
Without thresholds and hysteresis, every small fluctuation becomes chatter spam.
Failure mode 4 — Jobs reduced to isolated minigames
If jobs do not touch real resources, risk, and relationships, they become decorative.
Failure mode 5 — Entrances feel symmetric
Each entrance needs a clear signature and a distinct labor profile.
Failure mode 6 — Player remains an outsider
If the player cannot inhabit the labor system directly, the economy never fully lands.
18. Recommended Technical Direction
JSHack should proceed with the following assumptions:
- Keep the detailed economy if it already exists.
- Treat it as substrate, not direct narrative truth.
- Introduce multi-entrance influence with compact pressure vectors.
- Build a district-level interpretation layer.
- Make jobs first-class verbs for both NPCs and player.
- Use profession-local observables to generate dialogue.
- Use derived views and virtual components heavily inside ecs-js.
- Allow delving to reshape labor demand, faction stress, and district mood.
The resulting architecture can be summarized simply:
Entrances distort the town.
The town responds with labor.
Factions interpret and exploit that labor.
NPCs speak from their place inside that interpretation.
The player can put their hands into any part of the system.
That is the implementation target.
19. Appendix: Example Derived Views
Example: entrance pressure summary
{
entrance: "graveyard",
pressure: "active",
corruption: 0.72,
factionControl: "temple_contested",
laborDemand: ["burial", "warding", "incense"],
districtEffects: [
"mourner_traffic_up",
"night_fear_up",
"incense_prices_rising"
]
}
Example: district bulletin
{
district: "south_market",
shortages: ["lamp_oil", "bandages"],
dangers: ["spore_cough", "night_theft"],
opportunities: ["fungus_runs", "escort_work"],
scandals: ["clinic_turning_patients_away"],
rumors: [
"south goods are cursed",
"smugglers are moving through the old drains"
]
}
Example: player opportunity view
{
availableJobs: [
"night_hauling",
"graveyard_watch",
"ore_sorting",
"field_clinic_runner"
],
highLeverageActions: [
"clear_town_drain_access",
"recover_resin_from_lower_caves",
"escort_bandage_cart"
],
profitableSectors: [
"smith_repairs",
"incense_trade"
]
}
These examples illustrate the target level of abstraction for player-facing logic.
Final Note
This memo intentionally pushes JSHack toward a world where economy, dungeon, labor, and dialogue are one system expressed at different levels of resolution. That is exactly the kind of problem ecs-js can support well, provided the project leans into derived views, hierarchy, phase ordering, and profession-local interpretation rather than letting every feature couple itself directly to raw transactions.
Technical Memo
JSHack: Multi-Entrance Dungeon Pressure, Town Economy, and Player Jobs on top of ecs-js
Status
Draft for implementation planning.
Purpose
This memo proposes an implementation approach for a living town economy in JSHack where multiple dungeon entrances exert overlapping influence on a settlement, NPC labor emerges from real economic need, and the player can participate in all major jobs. The underlying runtime model assumes ecs-js as the substrate.
The core design goal is to preserve the value of a detailed simulation without forcing gameplay, dialogue, and quest logic to read directly from raw transactions. Instead, JSHack should treat the deep economy as a substrate, then derive a higher-order interpretation layer that produces visible consequences, social tension, and actionable play.
The intended result is a world in which:
1. Design Thesis
JSHack should treat the town, dungeon, and labor market as one continuous organism.
The dungeon is not merely a combat zone. It is a source of:
The town is not merely a shop hub. It is the surface-side interpretation and redistribution mechanism for those pressures.
The player should not only delve. The player should be able to:
This means the same underlying economy should be legible through many professions.
A smith sees the world through ore and repair queues.
A healer sees the world through wounds and reagent shortages.
A hauler sees the world through route safety and delivery backlog.
A grave worker sees the world through mortality, taboo, and temple influence.
A delver sees the source conditions that propagate outward into all the above.
The simulation must therefore be split into layers.
2. Architectural Principle: Substrate vs Interpretation
A common failure mode in simulation-heavy roguelikes is assuming that if the world simulates enough detail, gameplay will automatically become meaningful.
It will not.
Raw transaction detail is valuable, but mostly as substrate.
Substrate layer
This is the deep, mechanical world.
Examples:
Interpretation layer
This is the layer that decides which patterns are visible, meaningful, and socially narratable.
Examples:
The design requirement for JSHack is simple:
This is where ecs-js becomes especially useful.
3. Proposed World Model in ecs-js
JSHack should represent most important game facts as ECS entities with composable components. Relationships such as containment, assignment, district membership, route membership, and entrance influence should use hierarchical or relational patterns already aligned with ecs-js.
3.1 Major entity classes
At minimum, the world should contain entities for:
3.2 Recommended component categories
Below is a suggested conceptual component breakdown.
Identity / topology
NameKindPositionDistrictRefFactionRefRouteRefEntranceRefParent/ hierarchy linkageEconomic role
WorkRoleProductionProfileConsumesResourcesProducesResourcesInventoryStorageCapacityLaborCapacityDemandProfileSupplyProfileSocial / local state
MoodFearTrustBiasesProfessionKnowledgeRumorAccessReputationFactionStandingDungeon / entrance pressure
PressureCorruptionTrafficResourceYieldAccessibilityFactionControlRecentIncidentsEntranceInfluenceFieldInterpretation / summaries
DistrictSummarySectorSummaryLocalConditionsCriticalShortagesRecentEventSummaryNarrativeStateTalkingPointsPlayer capability / jobs
SkillSetToolAccessJobEligibilityKnownTechniquesPerceptionTagsExhaustionInjurySanctionedRolesEvent / incident
EconomicIncidentCauseChainSeveritySpreadVisibilityResolvedThis does not imply that every component must be materialized as persistent storage. Some should be implemented as virtual components or memoized derived views.
That is one of the strongest fits with ecs-js.
4. Multiple Dungeon Entrances as Pressure Sources
JSHack should explicitly model multiple entrances, each with distinct economic signatures and social meaning.
Proposed initial entrances:
Each entrance should not merely represent a map doorway. It should act as a regional pressure source.
4.1 Entrance state vector
Each entrance should expose a compact but expressive state vector:
pressureresourceYieldcorruptiontrafficknowledgefactionControlaccessibilitylocalFearincidentRateThese values are intentionally small in number. The goal is not exhaustive realism. The goal is enough state to meaningfully deform districts, labor demand, faction behavior, and dialogue.
4.2 Suggested entrance signatures
North
Possible emphasis:
Likely economic impact:
South
Possible emphasis:
Likely impact:
East
Possible emphasis:
Likely impact:
West
Possible emphasis:
Likely impact:
Town
Possible emphasis:
Likely impact:
Graveyard
Possible emphasis:
Likely impact:
4.3 Influence as overlapping fields
Each district should not belong to one entrance. Instead, districts should receive overlapping influence values from all nearby or culturally relevant entrances.
Example conceptual fields per district:
northInfluencesouthInfluenceeastInfluencewestInfluencetownInfluencegraveyardInfluenceThese do not need to be exposed directly to the player. They should drive derived world facts such as:
This gives the town a deformed, living geography rather than a set of arbitrary neighborhoods.
5. Jobs as First-Class World Verbs
The player must be able to do all jobs.
This is not a flavor request. It is a core systems requirement.
If only NPCs participate in the economy, then the economy remains spectacle. If the player can perform labor in every major sector, the player can inhabit the economy directly.
5.1 Jobs should not be isolated minigames
Each job must connect to at least three layers:
Examples:
Mining
Touches:
Smithing
Touches:
Hauling
Touches:
Healing
Touches:
Burial / Grave work
Touches:
Tavern work
Touches:
Delving
Touches:
5.2 Job access tiers
The player should be able to do all jobs eventually, but access should not be flat.
Suggested tiers:
This preserves progression and social texture without violating the design goal.
5.3 Jobs as perception filters
A major implementation opportunity is to let jobs alter what the player can perceive.
A smith can identify alloy quality.
A healer can classify wound origin and contamination.
A hauler can see packaging failures and route inefficiency.
A priest can detect desecration.
A gravedigger can spot disturbed soil.
A tavern worker can tell rumor density from ordinary chatter.
This turns job participation into a way of reading the world, not merely earning resources.
In ECS terms, these can be represented as skill-derived or profession-derived perception tags.
6. Event-Driven Economy with Derived Summaries
Even if JSHack simulates every transaction, the player-facing game should rarely care about transactions individually.
Instead, the world should continuously derive higher-order summaries.
6.1 Deep simulation is allowed
JSHack can absolutely model:
That is not a flaw.
But direct game logic should generally not read those events one by one.
6.2 Promote patterns, not noise
A summary system should roll up raw activity over windows of time and produce derived facts such as:
Those are the socially visible truths the rest of the game should react to.
6.3 Storyworthy thresholds
Continuous values should be converted into discrete thresholds before they affect dialogue, questing, or town mood.
Example threshold bands:
And for danger:
And for dungeon pressure:
This prevents microscopic noise from becoming constant social chatter.
6.4 Hysteresis
Threshold systems should include hysteresis so the town does not flip moods on tiny oscillations.
Example:
scarceat 20% stock depthscarceonce stock depth rises back above 35%This is essential for believable persistence.
7. Proposed Layer Stack for JSHack
The town-dungeon model should be implemented as a layered pipeline.
Layer 1 — Physical substrate
Raw ECS entities and systems handle:
Layer 2 — Analytic summaries
Systems derive:
Layer 3 — Narrative interpretation
Systems translate summaries into:
Layer 4 — Player-facing consequences
Gameplay consumes interpretation data to drive:
This separation should be treated as a hard architectural boundary where possible.
8. NPC Dialogue and Social Interpretation
NPCs should not speak directly from raw simulation values.
They should speak from role-local interpretations of the world.
8.1 NPC observables
Each profession should read a filtered subset of local summary state.
Examples:
Guard observes
Smith observes
Healer observes
Priest observes
Tavern worker observes
8.2 NPC knowledge model
A practical dialogue model can separate speech material into:
This allows NPCs to be coherent but not omniscient.
They should frequently be wrong.
That is a feature.
8.3 Talking points as structured output
Rather than generating dialogue directly from the entire simulation, each NPC should receive a small set of structured talking points.
Example:
This can then render to voiced lines such as:
The important point is that line generation should consume structured concern state, not raw economics.
8.4 District bulletin model
A useful simplification is to maintain a local bulletin for each district:
NPCs in that district then sample from the bulletin according to profession and bias.
This dramatically increases apparent coherence at low implementation cost.
9. Factions and Political Economy
Factions should sit above sectors and below dialogue, acting as pressure multipliers and response mechanisms.
Likely factions:
Factions should respond to analytic thresholds.
Examples:
This matters because the town should not merely reflect economics. It should interpret economics through institutions.
That is where social conflict comes from.
10. Virtual Components and Derived State in ecs-js
This proposal is a strong fit for virtual components or memoized derived views.
JSHack should avoid materializing every high-level interpretation value as manually maintained state if it can instead be derived efficiently and cached per tick.
Examples of excellent virtuals:
DistrictLocalConditionsEntrancePressureSummaryNPCObservablesJobDemandViewCriticalShortageViewFactionStressViewTalkingPointSetPlayerOpportunityViewThese virtuals should depend on:
This aligns well with ecs-js patterns where derived state is computed from authoritative data and invalidated per simulation step.
The memoized view approach is especially important because the interpretation layer will otherwise become brittle, duplicated, and difficult to maintain.
11. Suggested ECS System Breakdown
Below is a possible system grouping for implementation.
11.1 Substrate systems
11.2 Analytic systems
11.3 Interpretation systems
11.4 Player/world consequence systems
This is deliberately layered. It should be possible to disable, test, or inspect each band independently.
12. Dependency Chains as a First-Class Mechanic
One of the most powerful uses of the existing detailed economy is automatic dependency chain discovery.
Example:
These are exactly the kinds of chains the player should be able to discover, exploit, or repair.
The system does not need to explain every chain explicitly. But it should be able to identify hot bottlenecks and propagate pressure causally across sectors.
Possible implementation approach:
This can power:
13. How Dungeon Delving Connects to the Economy
Delving should affect the economy in at least five ways.
13.1 Extraction
The player recovers scarce or impossible-to-produce inputs.
Examples:
13.2 Suppression
The player reduces pressure sources that would otherwise destabilize routes, labor, and public safety.
Examples:
13.3 Discovery
The player learns things the surface does not yet know.
Examples:
13.4 Labor creation
Delving changes what jobs are in demand.
Examples:
13.5 Political leverage
Recovered goods and revealed truths create faction conflict.
Examples:
This means delving is not just combat. It is civic intervention, extraction, and destabilization all at once.
14. Player Doing All Jobs: Strategic Consequences
Allowing the player to do all jobs creates several system-level advantages.
14.1 Many interfaces into one world
The player can understand the same crisis from multiple sectors.
14.2 Natural arbitrage
The player can move between jobs to exploit or stabilize bottlenecks.
Example loop:
14.3 Identity through action
The player’s labor history should affect:
14.4 Non-combat progression
The game becomes structurally richer because progress is possible through:
This is especially valuable for a simulation-heavy roguelike.
15. Minimum Viable Implementation Path
This can be staged.
Phase 1 — Entrances and district influence
Implement:
Phase 2 — Job demand and sector summaries
Implement:
Phase 3 — NPC observables and talking points
Implement:
Phase 4 — Player jobs
Implement:
Phase 5 — Dependency chain analysis
Implement:
Phase 6 — Faction responses
Implement:
This ordering allows visible payoff early while preserving the larger design trajectory.
16. Guidance Specific to ecs-js
This proposal is particularly well suited to ecs-js if the following design choices are maintained.
16.1 Preserve authoritative low-level state
Inventories, assignments, locations, work relationships, incidents, and route traffic should remain authoritative.
16.2 Prefer derived views for high-level interpretation
District mood, shortages, local concerns, NPC observables, and player opportunities should be derived.
16.3 Use hierarchy for locality and containment
District membership, building containment, job site membership, and possibly social or civic groupings should exploit hierarchical helpers where useful.
16.4 Keep systems phase-ordered
A likely scheduler order:
This avoids in-tick incoherence and keeps derived layers reading settled facts.
16.5 Make summaries inspectable
For debugging, there should be direct developer views for:
This is essential for tuning a layered sim.
17. Risks and Failure Modes
Failure mode 1 — Reading raw simulation directly everywhere
This creates noise, brittleness, and impossible tuning.
Failure mode 2 — Over-authoring dialogue
If dialogue is not generated from real observables, the economy becomes fake again.
Failure mode 3 — No thresholds
Without thresholds and hysteresis, every small fluctuation becomes chatter spam.
Failure mode 4 — Jobs reduced to isolated minigames
If jobs do not touch real resources, risk, and relationships, they become decorative.
Failure mode 5 — Entrances feel symmetric
Each entrance needs a clear signature and a distinct labor profile.
Failure mode 6 — Player remains an outsider
If the player cannot inhabit the labor system directly, the economy never fully lands.
18. Recommended Technical Direction
JSHack should proceed with the following assumptions:
The resulting architecture can be summarized simply:
That is the implementation target.
19. Appendix: Example Derived Views
Example: entrance pressure summary
Example: district bulletin
Example: player opportunity view
These examples illustrate the target level of abstraction for player-facing logic.
Final Note
This memo intentionally pushes JSHack toward a world where economy, dungeon, labor, and dialogue are one system expressed at different levels of resolution. That is exactly the kind of problem ecs-js can support well, provided the project leans into derived views, hierarchy, phase ordering, and profession-local interpretation rather than letting every feature couple itself directly to raw transactions.