A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Add shared-rule mathematical balance model and real-game verification
SandroMaglionea77cde78a984
diff --git a/.gitignore b/.gitignoreindex 3acec73..c781d0d 100644--- a/.gitignore+++ b/.gitignore@@ -5,3 +5,4 @@ dist.env.*snapshots/output/inkline-3d/+output/balance-model/diff --git a/docs/balance-model.md b/docs/balance-model.mdnew file mode 100644index 0000000..16981bd--- /dev/null+++ b/docs/balance-model.md@@ -0,0 +1,90 @@+# Offline balance model++The model reads the game's content and pure rules. It runs independently of the ECS and renderer. The game never imports `tools/balance/`. The verification layer deliberately starts the real headless game to check selected predictions.++No values in `src/content.ts` changed when this component was added. Private carrier/walker constants moved into shared configuration with their original values. `src/rules/` owns immutable inputs and the existing household, tax, trade, approval, production cadence, staffing, season, risk, road-choice and dispatch-priority functions. The simulation calls the same functions. Grid and desirability calculations retain their existing shared implementations.++## Run it++```sh+pnpm balance:model analyze --scenario zoned+pnpm balance:model analyze --snapshot snapshots/medium-fair-1000-30min.json+pnpm balance:model analyze --scenario zoned --winter hard --minutes 4.5+pnpm balance:model project --scenario bootstrap --seconds 600+pnpm balance:model search --homes 8+pnpm balance:model verify --seeds 32+pnpm balance:model report --seeds 32+pnpm balance:model:check+```++`report` writes `results.json`, `results.md` and a standalone `results.html` to `output/balance-model/`. `--out` chooses another directory. JSON preserves detailed capacities, household constraints, service probabilities, calibration errors and provenance. Reports always use the shipped parameters.++To reproduce the original bot-town analysis, first capture the PR's default sensible mayor:++```sh+pnpm balance --seeds 1 --term 60 --snapshot 30+pnpm balance:model report --snapshot snapshots/medium-fair-1000-30min.json --seeds 32+```++The original bot is used as an existing consumer for diagnosis and behavior-preservation evidence. It is not the mathematical solver.++## API and ownership++```ts+import { resolveRules } from "./src/rules/config.ts"+import { analyze, project, fromSnapshot, assessTransfers } from "./tools/balance/index.ts"++const rules = resolveRules()+const scenario = fromSnapshot(save.world, "my-town", rules)+const inputs = { rules, scenario }++const budgets = analyze(inputs, { minutes: 10 })+const forecast = project(inputs, { seconds: 600 })+const transport = assessTransfers(inputs, [+ { source: warehouseId, target: millId, good: "wheat", goodsPerMinute: 7.5 },+ { source: warehouseId, target: bakeryId, good: "tools", goodsPerMinute: 0.125 },+])+```++`Scenario` contains plain buildings, households, roads, land, reserves, policy and optional trade conditions. Counts and locations are scenario choices. Rule values come from `resolveRules()`; there is no second recipe table in the analyzer. Construction schedules use the same scenario and ordinary player edits in `verifyBuilds`.++`src/rules/` contains game behavior. `tools/balance/model/` contains mathematical transformations and approximations. `tools/balance/verify/` owns runtime adapters and controlled experiments. `catalog.ts` contains authored examples, not universal winning layouts.++## What is calculated++- Staffing uses the real commute graph, scarcity-first assignment, insertion-order tie breaks and apprenticeship pass.+- Workshop throughput integrates the actual periodic tick cadence. Apprentice and equipment factors can overlap, so multiplying average factors is insufficient.+- Resource flow is a pooled steady-state relaxation constrained by upstream recipes and accessible sources. Initial perishable stock supplies an instantaneous expected spoilage estimate. Food feasibility uses capacity before spoilage, so a large reserve does not create a false impossibility claim.+- Carrier budgets use real road distances, speed, load size and pools shared across goods. Specified transfers expose a necessary workload constraint. The live dispatch policy still has queues and finite inventory effects.+- Service analysis enumerates finite non-backtracking random-walk paths by dynamic programming. Path hitting probabilities are exact for uniform choices on fixed roads. Mean occupancy, independent-excursion gap estimates and unlimited goods baskets are explicit approximations.+- Desirability, tier eligibility, tax rounding, price changes, refunds, approval and seasonal timing use shared game functions.+- Local disaster deadlines use shared integer risk increments. Their inputs are held fixed; contagion and changing neighbourhoods require verification. Maintenance reports material demand and the repair-to-half-speed window.+- Progression evolves finite reserves, recipe rates, crop maturation, purchases, construction and household tiers in coarse time steps. It exposes construction conflicts, including farms planting over future workshop plots.++The prediction runner does not recreate 60 Hz entity execution. Its regular mean visits, pooled shelves/tools, construction completion and crop placement are approximations. It does not claim an exact joint distribution of fires, sickness, repairs or victories. Wild forest growth has a conservative maximum-rate allowance in static analysis; transient tree forecasts count only the supplied finite trees.++## Counterfactuals and tuning++`search` enumerates production packages and reports cost, material/tool capital, staffing and output constraints with unchanged rules. Its fixed geometry can make a large package unstaffable even if enough residents exist globally.++The optional immutable experiment API and CLI never write tuning changes to content:++```sh+pnpm balance:model sweep --path kinds.weaver.recipe.seconds --values 4,8,12+```++`searchParameters(inputs, candidates, score)` evaluates explicit candidate rule sets. Supply a score reflecting the desired resource or constraints. These are hypothetical results; they require runtime verification before adoption. The committed results use no such patches.++## Verification and interpreting results++`balance:model:check` checks module boundaries, immutable candidate inputs, staffing, inaccessible workplaces, resource conservation, desirability, carrier-pool accounting, configuration search and controlled real-game comparisons. A candidate weaver period is also executed by the game to verify that both consumers receive the same inputs.++The construction case starts on authored flat land with roads and homes charged against fair starting funds, then builds through ordinary edits. It demonstrates a reachable citizen district in that stated starting configuration. It does not establish victory from every generated charter.++Production comparisons allow one incomplete job; transport allows one in-flight load per carrier at the observation boundary. Service comparisons use independent fixed seeds and report their sample sizes and statistical tolerances. The coarse forecast's timing and cash errors remain visible. Passing the controlled checks does not turn an approximate forecast into an exact outcome prediction.++The original seed-1000 sensible mayor's entire minute-30 world is checked against the PR #3 reference SHA-256 `e759806fa37003f6215db219c3a784332afc2fc5c44d22845b71dc0fcdd78f87`. This checks the shared-rule extraction across production, transport, random streams, risks, economy and persistence. Refresh that reference only after an intentional gameplay or engine change has been reviewed.++Every report includes rule, content, source and scenario fingerprints. A rule change recomputes the analysis; a semantic change in the game must either update a shared function or fail the behavior/verification checks. Mathematical approximations also need calibration when their assumptions change.++See [the measured results](balance-model-results.md) for findings and their practical limits.diff --git a/package.json b/package.jsonindex f627426..295824b 100644--- a/package.json+++ b/package.json@@ -9,6 +9,8 @@"assets:build": "node scripts/ink-assets.ts","typecheck": "tsc -p tsconfig.json --pretty false","balance": "node scripts/balance.ts",+ "balance:model": "node tools/balance/cli.ts",+ "balance:model:check": "node --test test/balance-model.test.ts","check": "node scripts/check.ts","check:browser": "node scripts/check-browser.ts","check:models": "node scripts/check-town-models.ts",diff --git a/src/appeal.ts b/src/appeal.tsindex dc7540e..239b963 100644--- a/src/appeal.ts+++ b/src/appeal.ts@@ -1,3 +1,4 @@+import { shippedRules, type Rules } from "./rules/config.ts"/*** Desirability: how pleasant each cell is to live on. Buildings and the land* add to it or take from it, fading with distance (see `Kind.appeal` and@@ -8,7 +9,7 @@* shared by the simulation (which keeps the whole grid, see `Appraise`) and* the page (which explains one cell).*/-import { appeal, grounds, kinds, park, props, type GroundId, type KindId, type PropId } from "./content.ts"+import { type GroundId, type KindId, type PropId } from "./content.ts"import { cellOf, DIRS, key } from "./grid.ts"import { GRID, inside, type Point } from "./iso.ts"@@ -46,24 +47,24 @@ export const effectAt = (source: { readonly value: number; readonly reach: numbe}/** A building of a kind as a source, if it has any effect. */-export const buildingSource = (kind: KindId, tile: { readonly x: number; readonly y: number; readonly size: number }): AppealSource | null => {- const a = kinds[kind].appeal- return a ? { ...tile, value: a.value, reach: a.reach, label: kinds[kind].title.toLowerCase(), mode: "sum" } : null+export const buildingSource = (kind: KindId, tile: { readonly x: number; readonly y: number; readonly size: number }, rules: Rules = shippedRules): AppealSource | null => {+ const a = rules.kinds[kind].appeal+ return a ? { ...tile, value: a.value, reach: a.reach, label: rules.kinds[kind].title.toLowerCase(), mode: "sum" } : null}-export const landSource = (what: "water" | "forest" | "paved" | "ruin" | "worn", cell: { readonly x: number; readonly y: number; readonly size?: number }): AppealSource => ({+export const landSource = (what: "water" | "forest" | "paved" | "ruin" | "worn", cell: { readonly x: number; readonly y: number; readonly size?: number }, rules: Rules = shippedRules): AppealSource => ({x: cell.x,y: cell.y,size: cell.size ?? 1,- ...appeal[what],+ ...rules.appeal[what],label: what === "forest" ? "woods" : what === "paved" ? "paved street" : what === "worn" ? "a run-down home" : what,mode: what === "water" || what === "forest" ? "nature" : what === "paved" ? "paved" : "sum"})-const clamp = (n: number) => Math.max(appeal.floor, Math.min(appeal.ceiling, n))+const clamp = (n: number, rules: Rules) => Math.max(rules.appeal.floor, Math.min(rules.appeal.ceiling, n))/** Every cell's desirability, by `key`. */-export const appealGrid = (sources: ReadonlyArray<AppealSource>): Array<number> => {+export const appealGrid = (sources: ReadonlyArray<AppealSource>, rules: Rules = shippedRules): Array<number> => {const sum = new Int32Array(GRID * GRID)const nature = new Int32Array(GRID * GRID)const paved = new Int32Array(GRID * GRID)@@ -79,11 +80,11 @@ export const appealGrid = (sources: ReadonlyArray<AppealSource>): Array<number>}}}- return Array.from({ length: GRID * GRID }, (_, k) => clamp(sum[k]! + nature[k]! + paved[k]!))+ return Array.from({ length: GRID * GRID }, (_, k) => clamp(sum[k]! + nature[k]! + paved[k]!, rules))}/** One cell's desirability and what makes it, strongest first: "park +6", "bakery −4". */-export const appealParts = (sources: ReadonlyArray<AppealSource>, cell: { readonly x: number; readonly y: number }) => {+export const appealParts = (sources: ReadonlyArray<AppealSource>, cell: { readonly x: number; readonly y: number }, rules: Rules = shippedRules) => {const parts = new Map<string, number>()const best = { nature: { label: "", value: 0 }, paved: { label: "", value: 0 } }for (const s of sources) {@@ -95,7 +96,7 @@ export const appealParts = (sources: ReadonlyArray<AppealSource>, cell: { readonfor (const b of [best.nature, best.paved]) if (b.value !== 0) parts.set(b.label, (parts.get(b.label) ?? 0) + b.value)const list = [...parts].map(([label, value]) => ({ label, value })).filter((p) => p.value !== 0)list.sort((a, b) => Math.abs(b.value) - Math.abs(a.value))- return { value: clamp(list.reduce((n, p) => n + p.value, 0)), parts: list }+ return { value: clamp(list.reduce((n, p) => n + p.value, 0), rules), parts: list }}/** A cell's desirability from a reckoned grid (0 before the first reckoning). */@@ -135,7 +136,8 @@ const tenth = (n: number) => Math.round(n * 10) / 10* pleasant; a lawn with walks in from the street, lamps, and a statue is a* park.*/-export const parkValue = (cells: ReadonlyArray<ParkCell>, road: (x: number, y: number) => boolean = () => false): ParkValue => {+export const parkValue = (cells: ReadonlyArray<ParkCell>, road: (x: number, y: number) => boolean = () => false, rules: Rules = shippedRules): ParkValue => {+ const { grounds, props, park } = rulesconst groundRaw = cells.reduce((n, c) => n + grounds[c.ground].beauty, 0)const ground = Math.min(park.groundMost, groundRaw)const room = Math.ceil(cells.length / park.cellsPerProp)@@ -173,7 +175,7 @@ export const parkValue = (cells: ReadonlyArray<ParkCell>, road: (x: number, y: n}/** The town's parks: cells of park that touch (side by side) are one park. */-export const parksOf = (cells: ReadonlyArray<ParkCell>, road?: (x: number, y: number) => boolean): Array<ParkValue> => {+export const parksOf = (cells: ReadonlyArray<ParkCell>, road?: (x: number, y: number) => boolean, rules: Rules = shippedRules): Array<ParkValue> => {const at = new Map<number, ParkCell>()for (const c of cells) at.set(key(c.x, c.y), c)const seen = new Set<number>()@@ -195,14 +197,14 @@ export const parksOf = (cells: ReadonlyArray<ParkCell>, road?: (x: number, y: nuqueue.push(n)}}- out.push(parkValue(members, road))+ out.push(parkValue(members, road, rules))}return out}/** Each park as a desirability source, measured from its nearest cell. */-export const parkSources = (cells: ReadonlyArray<ParkCell>, road?: (x: number, y: number) => boolean): Array<AppealSource> =>- parksOf(cells, road)+export const parkSources = (cells: ReadonlyArray<ParkCell>, road?: (x: number, y: number) => boolean, rules: Rules = shippedRules): Array<AppealSource> =>+ parksOf(cells, road, rules).filter((p) => p.value > 0).map((p) => {const xs = p.cells.map((c) => c.x)@@ -212,3 +214,7 @@ export const parkSources = (cells: ReadonlyArray<ParkCell>, road?: (x: number, yconst size = Math.max(Math.max(...xs) - x, Math.max(...ys) - y) + 1return { x, y, size, value: p.value, reach: p.reach, label: "park", mode: "sum", cells: p.cells }})++/** Per-minute upkeep paid for a park cell, including its furnishing. */+export const parkUpkeep = (cell: Pick<ParkCell, "ground" | "prop">, rules: Rules = shippedRules) =>+ rules.grounds[cell.ground].upkeep + (cell.prop === "none" ? 0 : rules.props[cell.prop].upkeep)diff --git a/src/archetypes.ts b/src/archetypes.tsindex 476a6e7..7f1df65 100644--- a/src/archetypes.ts+++ b/src/archetypes.ts@@ -1,3 +1,4 @@+import { shippedRules, type Rules } from "./rules/config.ts"/*** Content to components: how each thing in `content.ts` is assembled from* the schema's components. A building is a `Tile`, a `Building`, a `Status`,@@ -5,12 +6,9 @@* costs materials starts as a `Site`, anything else starts `Rising`; the* land is a `Tile` and its own marker.*/-import { amounts, CONDITION_MAX, goodIds, home, total, type GroundId, type Kind } from "./content.ts"+import { amounts, goodIds, total, type GroundId, type Kind } from "./content.ts"import type { Point } from "./iso.ts"-import {- Building, Carriers, Condition, Field, Game, Gatherer, House, Inventory, Park, Planter, Recipe, Rising, Risk, Road, Rock, Ruin, Service, Site,- Staff, Status, Storage, Tile, Tree, Water-} from "./schema.ts"+import { Building, Carriers, Condition, Field, Game, Gatherer, House, Inventory, Park, Planter, Recipe, Rising, Risk, Road, Rock, Ruin, Service, Site, Staff, Status, Storage, Tile, Tree, Water } from "./schema.ts"import { ticks } from "./content.ts"const site = (cost: Kind["cost"]) => {@@ -28,16 +26,16 @@ export const buildingDraft = (kind: Kind, cell: Point) =>)/** What every home and every working building carries: its risks, and how well kept it is. */-export const wearOf = () => [+export const wearOf = (rules: Rules = shippedRules) => [Game.Command.entry(Risk, { fire: 0, health: 0, order: 0, thefts: 0 }),- Game.Command.entry(Condition, { value: CONDITION_MAX })+ Game.Command.entry(Condition, { value: rules.conditionMax })]/** How a new building starts: owed its materials, or rising straight away. */export const startOf = (kind: Kind) => site(kind.cost)/** The role components a kind's buildings carry, inserted after the building is spawned. */-export const rolesOf = (kind: Kind) => {+export const rolesOf = (kind: Kind, rules: Rules = shippedRules) => {const roles = []if (kind.recipe) {const r = kind.recipe@@ -66,7 +64,7 @@ export const rolesOf = (kind: Kind) => {roles.push(Game.Command.entry(Service, { service: s.service, interval: ticks(s.seconds), cooldown: 0, range: s.range }))}// The town hall neither burns nor wears.- if (kind.id !== "townhall") roles.push(...wearOf())+ if (kind.id !== "townhall") roles.push(...wearOf(rules))return roles}@@ -75,7 +73,7 @@ export const houseDraft = (cell: Point) =>[Tile, { x: cell.x, y: cell.y, size: 1 }],[House, { tier: 1, residents: 0, food: 0, bread: 0, cloth: 0, faith: 0, clock: 0 }])-export const houseStart = () => [site(home.cost), ...wearOf()]+export const houseStart = (rules: Rules = shippedRules) => [site(rules.home.cost), ...wearOf(rules)]export const ruinDraft = (tile: { readonly x: number; readonly y: number; readonly size: number }, cause: "burnt" | "collapsed" | "derelict") =>Game.Command.spawn([Tile, { x: tile.x, y: tile.y, size: tile.size }], [Ruin, { cause }])diff --git a/src/main.ts b/src/main.tsindex a5e2cea..f892ac8 100644--- a/src/main.ts+++ b/src/main.ts@@ -1,3 +1,4 @@+import { resolveRules } from "./rules/config.ts"/*** A town simulation of line-drawn buildings, homes, roads, and land, on the* bevy-ts ECS with a 3D view. The simulation runs on a fixed step;@@ -12,7 +13,7 @@ import { lands, sizes, STEP_SECONDS } from "./content.ts"import { createHost, type Persistence } from "./host.ts"import { present } from "./present.ts"import { browserStorage, describe, loadLatest, save, Storage, World } from "./save.ts"-import { BuildingNodes, Clock, FieldNodes, Game, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"+import { BuildingNodes, Clock, FieldNodes, Game, Rules, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"import { blankResources, simulate } from "./sim/index.ts"/** Minutes of game time between autosaves. */@@ -39,6 +40,7 @@ const start = async () => {const made = Game.Runtime.make({services: Game.Runtime.services(Game.Runtime.service(Ui, ui),+ Game.Runtime.service(Rules, resolveRules()),Game.Runtime.service(Clock, clock),Game.Runtime.service(StageService, stage),Game.Runtime.service(BuildingNodes, buildingNodes),diff --git a/src/mapgen.ts b/src/mapgen.tsindex 8c1593d..a8b840c 100644--- a/src/mapgen.ts+++ b/src/mapgen.ts@@ -1,3 +1,4 @@+import { shippedRules, type Rules } from "./rules/config.ts"/*** A new town's land, from its charter: an island-like stretch of land of* the charter's size, its coast wandering in and out and a few capes@@ -9,7 +10,7 @@*/import * as Random from "@typeonce/bevy-ts-math/Random"-import { GROWN, lands, sizes, type CharterValue } from "./content.ts"+import { GROWN, type CharterValue } from "./content.ts"import { DIRS, key } from "./grid.ts"import { GRID, inside, type Point } from "./iso.ts"@@ -93,10 +94,10 @@ const shape = (random: Random.Random, radius: number): Array<boolean> => {return land.map((_, k) => main.has(k) || !sea.has(k))}-export const generate = (charter: CharterValue): Land => {+export const generate = (charter: CharterValue, rules: Rules = shippedRules): Land => {const random = Random.make(charter.seed)- const richness = lands[charter.land]- const ground = shape(random, sizes[charter.size].radius)+ const richness = rules.lands[charter.land]+ const ground = shape(random, rules.sizes[charter.size].radius)const cells = ground.filter(Boolean).lengthconst per = (perThousand: number) => Math.max(1, Math.round((cells / 1000) * perThousand))diff --git a/src/rules/approval.ts b/src/rules/approval.tsnew file mode 100644index 0000000..61f8378--- /dev/null+++ b/src/rules/approval.ts@@ -0,0 +1,16 @@+import { shippedRules, type Rules } from "./config.ts"+import { satisfaction, type Needs, type Rates } from "./households.ts"++export const approvalTarget = (homes: ReadonlyArray<Needs & { readonly residents: number }>, policy: Rates, coins: number, snubs: number, winter: boolean, rules: Rules = shippedRules) => {+ const people = homes.reduce((n, h) => n + h.residents, 0)+ const pleased = homes.reduce((n, h) => n + h.residents * satisfaction(h, h.tier, rules), 0)+ const taxed = homes.reduce((n, h) => n + h.residents * (h.tier === 1 ? policy.settlers : policy.citizens), 0)+ const fed = homes.filter((h) => h.food > 0).length+ const share = people > 0 ? pleased / people : 0.5, rate = people > 0 ? taxed / people : 100+ const needs = Math.round(rules.mood.needs[0] + (rules.mood.needs[1] - rules.mood.needs[0]) * share)+ const taxes = Math.round((100 - rate) * rules.mood.perTaxPoint), debt = coins < 0 ? rules.mood.debt : 0+ const crown = snubs * rules.mood.snub, hunger = winter && homes.length > 0 && fed / homes.length < 0.5 ? rules.mood.winterHunger : 0+ return { target: Math.max(-100, Math.min(100, rules.mood.base + needs + taxes + debt + crown + hunger)), base: rules.mood.base, needs, taxes, debt, crown, winter: hunger }+}+export const nextApproval = (approval: number, target: number, rules: Rules = shippedRules) =>+ approval + Math.max(-rules.mood.step, Math.min(rules.mood.step, target - approval))diff --git a/src/rules/config.ts b/src/rules/config.tsnew file mode 100644index 0000000..f4dd527--- /dev/null+++ b/src/rules/config.ts@@ -0,0 +1,62 @@+/** Immutable inputs shared by the game and offline analysis. No tuning values live in the analyzer. */+import * as content from "../content.ts"++/** Formerly private execution constants, moved here without changing their values. */+export const transport = {+ cellSteps: 48, walk: 1, run: 3, basket: 10, active: 2, load: 4, dispatchTicks: 6+} as const++const inputs = () => ({+ kinds: content.kinds, home: content.home, goods: content.goods, lands: content.lands, sizes: content.sizes,+ appeal: content.appeal, grounds: content.grounds, props: content.props, park: content.park,+ risk: content.risk, condition: content.condition, winters: content.winters,+ admin: content.admin, mood: content.mood, crown: content.crown, market: content.market, fate: content.fate,+ spoils: content.spoils, trade: content.trade, tradeLoad: content.TRADE_LOAD, transport,+ stepSeconds: content.STEP_SECONDS, ledgerTicks: content.LEDGER_TICKS, spoilTicks: content.SPOIL_TICKS,+ commute: content.COMMUTE, apprentice: content.APPRENTICE, toolStock: content.TOOL_STOCK,+ conditionMax: content.CONDITION_MAX, riskMax: content.RISK_MAX, pausedUpkeep: content.PAUSED_UPKEEP,+ buildTicks: content.BUILD_TICKS, roadCost: content.ROAD_COST, paveCost: content.PAVE_COST,+ grown: content.GROWN, yearsPerTerm: content.YEARS_PER_TERM, staffTicks: content.ticks(0.5), riskTicks: 60,+ spreadTicks: content.ticks(1.5), growTicks: 10+})++type NumericData<T> = T extends number ? number : T extends object ? { readonly [K in keyof T]: NumericData<T[K]> } : T+export type Rules = Omit<NumericData<ReturnType<typeof inputs>>, "kinds"> & { readonly kinds: typeof content.kinds }+export interface RulePatch { readonly path: string; readonly value: number }++const freeze = <T>(value: T): T => {+ if (typeof value === "object" && value !== null) {+ for (const child of Object.values(value)) freeze(child)+ Object.freeze(value)+ }+ return value+}++/** Fresh copies also preserve the existing bot's --set-before-start workflow. */+export const resolveRules = (patches: ReadonlyArray<RulePatch> = []): Rules => {+ const copy = structuredClone(inputs()) as unknown as Record<string, unknown>+ for (const { path, value } of patches) {+ if (!Number.isFinite(value) || value < 0) throw new Error(`Invalid numeric rule: ${path}`)+ const parts = path.split(".")+ if (parts.some((p) => ["__proto__", "prototype", "constructor"].includes(p))) throw new Error(`Invalid rule path: ${path}`)+ let target = copy+ for (const part of parts.slice(0, -1)) {+ if (!Object.hasOwn(target, part) || typeof target[part] !== "object" || target[part] === null) throw new Error(`Unknown rule: ${path}`)+ target = target[part] as Record<string, unknown>+ }+ const key = parts.at(-1)!+ if (!Object.hasOwn(target, key) || typeof target[key] !== "number") throw new Error(`Unknown numeric rule: ${path}`)+ // Structural timing and identifier changes are outside numeric economy experiments.+ if (parts[0] === "transport" || ["size", "stories", "bays"].includes(key)) throw new Error(`Structural rule cannot be patched: ${path}`)+ if (["stepSeconds", "ledgerTicks", "spoilTicks", "yearsPerTerm", "staffTicks", "riskTicks", "spreadTicks", "growTicks"].includes(parts[0]!)) throw new Error(`Structural rule cannot be patched: ${path}`)+ if ((key === "seconds" || key === "growth" || key === "wear" || key === "every" || key === "lasts") && value === 0) throw new Error(`Rule must be positive: ${path}`)+ if ((path.startsWith("home.lasts.") || path.startsWith("spoils.")) && value === 0) throw new Error(`Rule must be positive: ${path}`)+ if ((["workers", "batch", "inputs", "cap", "carriers", "range", "residents", "settle"].includes(key) || path.includes(".cost.")) && !Number.isInteger(value)) throw new Error(`Rule must be an integer: ${path}`)+ if (path === "apprentice" && value > 1) throw new Error("Apprentice pace must be at most one")+ target[key] = value+ }+ return freeze(copy as unknown as Rules)+}++export const shippedRules = resolveRules()+export const ruleTicks = (seconds: number, rules: Rules = shippedRules) => Math.round(seconds / rules.stepSeconds)diff --git a/src/rules/decay.ts b/src/rules/decay.tsnew file mode 100644index 0000000..b556492--- /dev/null+++ b/src/rules/decay.ts@@ -0,0 +1,8 @@+import type { GoodId } from "../content.ts"+import { shippedRules, type Rules } from "./config.ts"++/** Expected loss before the runtime's seeded stochastic rounding. */+export const spoilExpectation = (stock: number, good: GoodId, keeps: number, rules: Rules = shippedRules): number => {+ const life = rules.spoils[good]+ return life === undefined || stock <= 0 ? 0 : stock * rules.spoilTicks * rules.stepSeconds / (life * keeps)+}diff --git a/src/rules/goals.ts b/src/rules/goals.tsnew file mode 100644index 0000000..bb711a4--- /dev/null+++ b/src/rules/goals.ts@@ -0,0 +1,24 @@+import { shippedRules, type Rules } from "./config.ts"++/** Food in storage: what would carry the town through a winter. */+export const larder = (stock: { readonly fish: number; readonly smoked: number; readonly bread: number }) => stock.fish + stock.smoked + stock.bread++/** Each goal the town must hold to be complete, met or not. */+export const goalsOf = (+ charter: { readonly size: keyof Rules["sizes"] },+ s: { readonly settlers: number; readonly citizens: number; readonly coins: number; readonly net: number; readonly approval: number },+ rules: Rules = shippedRules+) => {+ const goal = rules.sizes[charter.size].goal+ const residents = s.settlers + s.citizens+ return [+ { id: "residents", text: `${goal.residents} residents`, value: `${residents}`, met: residents >= goal.residents },+ { id: "citizens", text: `${Math.round(rules.fate.citizens * 100)}% of them citizens`, value: `${residents > 0 ? Math.round((s.citizens / residents) * 100) : 0}%`, met: residents > 0 && s.citizens >= residents * rules.fate.citizens },+ { id: "approval", text: `approval ${rules.fate.approval} or more`, value: `${s.approval}`, met: s.approval >= rules.fate.approval },+ { id: "coins", text: `${goal.coins} coins, not losing any`, value: `${s.coins}`, met: s.coins >= goal.coins && s.net >= 0 }+ ] as const+}++/** The town's score at the end of its term. */+export const scoreOf = (s: { readonly settlers: number; readonly citizens: number; readonly coins: number; readonly approval: number; readonly met: number; readonly missed: number }, won: boolean, minutesLeft: number) =>+ Math.max(0, Math.round(s.settlers + 3 * s.citizens + Math.max(0, s.coins) / 20 + 2 * s.approval + 40 * s.met - 40 * s.missed + (won ? 500 + 20 * minutesLeft : 0)))diff --git a/src/rules/households.ts b/src/rules/households.tsnew file mode 100644index 0000000..1b2d1e0--- /dev/null+++ b/src/rules/households.ts@@ -0,0 +1,101 @@+import type { GoodId, Need, Tier } from "../content.ts"+import { shippedRules, type Rules } from "./config.ts"++export interface Needs {+ readonly tier: Tier+ readonly food: number+ readonly bread: number+ readonly cloth: number+ readonly faith: number+}++export const met = (h: Needs, need: Need): boolean => h[need] > 0++/** The share of its tier's needs a home has met, 0 → 1. */+export const satisfaction = (h: Needs, tier: Tier = h.tier, rules: Rules = shippedRules): number => {+ const needs = rules.home.tiers[tier].needs+ return needs.filter((n) => met(h, n)).length / needs.length+}++export interface Rates {+ readonly settlers: number+ readonly citizens: number+}+const rateOf = (rates: Rates, tier: Tier) => (tier === 1 ? rates.settlers : rates.citizens)++/** How approval (-100 → 100) sits with a home: a third as many residents at its worst, half again at its best. */+export const appealOf = (approval: number): number => (approval < 0 ? 1 + approval / 150 : 1 + approval / 200)++/**+ * Residents a home holds at its tier and satisfaction: half when nothing is+ * met, all when everything is; fewer when the town disapproves of its+ * mayor, and up to all of them when it approves, needs or not. Nobody+ * wants to live where it is squalid (desirability `rules.home.squalid` or less):+ * such a home holds fewer.+ */+export const capacity = (h: Needs, approval: number, desirability = 0, rules: Rules = shippedRules): number => {+ const max = rules.home.tiers[h.tier].residents+ const squalor = desirability <= rules.home.squalid ? rules.home.crowded : 1+ return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h, h.tier, rules)) * appealOf(approval) * squalor)))+}++/** Whether every risk meter of a home is kept low: a service walker of each kind passes it. */+export const kept = (r: { readonly fire: number; readonly health: number; readonly order: number }, rules: Rules = shippedRules) =>+ r.fire < rules.risk.kept && r.health < rules.risk.kept && r.order < rules.risk.kept++/**+ * The tier a home settles into: settlers whose every citizens' need is met,+ * on a street desirable enough, become citizens; citizens with a street+ * nicer still and all three services calling become burghers in a+ * townhouse. A home that loses more than one of its needs, or whose street+ * falls below its tier, steps back down.+ */+export const tierFor = (h: Needs, desirability: number, r: { readonly fire: number; readonly health: number; readonly order: number }, rules: Rules = shippedRules): Tier => {+ const fits = (tier: Tier) => desirability >= rules.home.tiers[tier].appeal+ if (h.tier === 1) return satisfaction(h, 2, rules) === 1 && fits(2) ? 2 : 1+ if (satisfaction(h, h.tier, rules) < 2 / 3 || !fits(2)) return 1+ if (h.tier === 2) return satisfaction(h, 3, rules) === 1 && fits(3) && kept(r, rules) ? 3 : 2+ return fits(3) && kept(r, rules) ? 3 : 2+}++/** Coins a minute the town hall's administration costs for `homes` homes. */+export const adminOf = (homes: number, rules: Rules = shippedRules): number => Math.round(homes * (rules.admin.perHome + homes / rules.admin.growth))++/** What traders pay for one of a good now, and what they ask for one. */+export const priceOf = (good: GoodId, percent: number, rules: Rules = shippedRules) => (rules.goods[good].price * percent) / 100+export const askOf = (good: GoodId, percent: number, rules: Rules = shippedRules) => Math.ceil(priceOf(good, percent, rules) * rules.market.markup)++/** Coins a home pays a minute. */+export const taxOf = (h: Needs & { readonly residents: number }, rates: Rates, rules: Rules = shippedRules): number =>+ h.residents * rules.home.tiers[h.tier].tax * (rateOf(rates, h.tier) / 100) * (0.25 + 0.75 * satisfaction(h, h.tier, rules))++export const lowNeed = (left: number, need: Need, rules: Rules = shippedRules) => left < rules.home.lasts[need] / 2+export const mealDecay = (tick: number, winter: boolean) => winter && tick % 2 === 0 ? 2 : 1+type Mutable<T> = { -readonly [K in keyof T]: T[K] }+export const ageNeeds = <T extends Needs & { readonly clock: number }>(h: T, eat: number): Mutable<T> => ({+ ...h, clock: h.clock + 1, food: Math.max(0, h.food - eat), bread: Math.max(0, h.bread - eat),+ cloth: Math.max(0, h.cloth - 1), faith: Math.max(0, h.faith - 1)+})++/** One goods visit. Bread is preferred for food even at a settlers' home. */+export const serveGoods = <T extends Needs>(house: T, available: Readonly<Record<GoodId, number>>, rules: Rules = shippedRules) => {+ const h = { ...house } as Mutable<T>, basket = { ...available }+ let eaten = 0+ if ((lowNeed(h.food, "food", rules) || (h.tier >= 2 && lowNeed(h.bread, "bread", rules))) && basket.bread > 0) {+ basket.bread -= 1; h.food = rules.home.lasts.food; h.bread = rules.home.lasts.bread; eaten += 1+ } else if (lowNeed(h.food, "food", rules) && (basket.fish > 0 || basket.smoked > 0)) {+ const g = basket.fish > 0 ? "fish" : "smoked"+ basket[g] -= 1; h.food = rules.home.lasts.food; eaten += 1+ }+ if (lowNeed(h.cloth, "cloth", rules) && basket.cloth > 0) {+ basket.cloth -= 1; h.cloth = rules.home.lasts.cloth+ }+ return { house: h, basket, eaten }+}++/** Actual collection rounding, not rounded ledger display values. */+export const baseCollection = (taxes: number, upkeep: number, homes: number, rules: Rules = shippedRules) => {+ const share = rules.ledgerTicks * rules.stepSeconds / 60+ const admin = adminOf(homes, rules)+ return { admin, delta: Math.round(taxes * share) - Math.round((upkeep + admin) * share) }+}diff --git a/src/rules/land.ts b/src/rules/land.tsnew file mode 100644index 0000000..904e35a--- /dev/null+++ b/src/rules/land.ts@@ -0,0 +1,9 @@+import { DIRS, useAt } from "../grid.ts"+import type { GridValue } from "../schema.ts"+import type { Point } from "../iso.ts"++/** Keep unsuccessful candidates: the game picks first and checks fertility afterward. */+export const wildTreeSpots = (grid: GridValue, parent: Point): ReadonlyArray<Point> =>+ DIRS.map((d) => ({ x: parent.x + d.x, y: parent.y + d.y })).filter((c) => useAt(grid, c.x, c.y) === "empty")+export const canSeedTree = (grid: GridValue, spot: Point) =>+ DIRS.filter((d) => useAt(grid, spot.x + d.x, spot.y + d.y) === "tree").length >= 2diff --git a/src/rules/production.ts b/src/rules/production.tsnew file mode 100644index 0000000..3e6c9f7--- /dev/null+++ b/src/rules/production.ts@@ -0,0 +1,39 @@+import { shippedRules, type Rules } from "./config.ts"+import type { Kind } from "../content.ts"++/** Tick alignment is significant: keep effort and equipment cadence on the same clock. */+export const paced = (pace: number, tick: number): boolean => pace >= 1 || Math.floor((tick + 1) * pace) > Math.floor(tick * pace)+export const effort = (staff: { readonly assigned: number; readonly apprentices: number }, tick: number, rules: Rules = shippedRules) =>+ staff.assigned - staff.apprentices + (paced(rules.apprentice, tick) ? staff.apprentices : 0)+export const equipmentPace = (kind: Kind, tools: number, condition: number, fishing: number, rules: Rules = shippedRules) =>+ (kind.wear && tools === 0 ? 0.5 : 1) * (condition < rules.condition.worn ? 0.5 : 1) * (kind.gathers?.source === "water" ? fishing : 1)++export interface CrewHome { readonly id: number; readonly crew: "settlers" | "citizens"; readonly residents: number }+export interface Workplace {+ readonly id: number; readonly crew: "settlers" | "citizens"; readonly needed: number+ readonly within: ReadonlyArray<{ readonly home: number; readonly distance: number }>+}+export interface Assignment { readonly assigned: number; readonly apprentices: number; readonly nearby: number }++/** Same scarcity-first, insertion-order tie break and two-pass apprenticeship as AssignStaff. */+export const assignWorkers = (homes: ReadonlyArray<CrewHome>, workplaces: ReadonlyArray<Workplace>): Map<number, Assignment> => {+ const left = new Map(homes.map((h) => [h.id, { ...h, left: h.residents }]))+ const places = workplaces.map((w, index) => ({ ...w, index, assigned: 0, apprentices: 0,+ within: [...w.within].sort((a, b) => a.distance - b.distance),+ nearby: w.within.reduce((n, h) => n + (left.get(h.home)?.crew === w.crew ? left.get(h.home)!.residents : 0), 0)+ }))+ const order = [...places].sort((a, b) => a.nearby - b.nearby || a.index - b.index)+ const fill = (place: (typeof places)[number], crew: CrewHome["crew"]) => {+ for (const within of place.within) {+ if (place.assigned >= place.needed) break+ const h = left.get(within.home)+ if (!h || h.crew !== crew || h.left === 0) continue+ const take = Math.min(place.needed - place.assigned, h.left)+ h.left -= take; place.assigned += take+ if (crew !== place.crew) place.apprentices += take+ }+ }+ for (const p of order) fill(p, p.crew)+ for (const p of order) if (p.crew === "citizens") fill(p, "settlers")+ return new Map(places.map((p) => [p.id, { assigned: p.assigned, apprentices: p.apprentices, nearby: p.nearby }]))+}diff --git a/src/rules/risks.ts b/src/rules/risks.tsnew file mode 100644index 0000000..8bf01dd--- /dev/null+++ b/src/rules/risks.ts@@ -0,0 +1,35 @@+import type { KindId, Tier } from "../content.ts"+import type { TileLike } from "../grid.ts"+import { shippedRules, type Rules } from "./config.ts"++export const near = (a: TileLike, b: TileLike, r: number) =>+ Math.max(a.x - (b.x + b.size - 1), b.x - (a.x + a.size - 1), a.y - (b.y + b.size - 1), b.y - (a.y + a.size - 1)) <= r+const hash = (x: number, y: number) => {+ let h = (x * 374761393 + y * 668265263) >>> 0+ h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296+}+export const paceAt = (x: number, y: number, rules: Rules = shippedRules) => rules.risk.pace[0] + (rules.risk.pace[1] - rules.risk.pace[0]) * hash(x, y)+export interface RiskInputs {+ readonly tile: TileLike; readonly condition: number; readonly desirability: number; readonly approval: number+ readonly heating: boolean; readonly hotNearby: number; readonly dusty: boolean; readonly water: boolean+ readonly house?: { readonly tier: Tier; readonly residents: number; readonly food: number }+ readonly kind?: KindId+}+/** Integer meter increments at the game's one-second hazard checkpoint. */+export const riskIncrements = (input: RiskInputs, rules: Rules = shippedRules) => {+ const { risk, home } = rules, { house: h } = input+ const worn = input.condition < rules.condition.worn, squalid = input.desirability < 0+ let fire = 0, health = 0, order = 0+ if (h) {+ const max = home.tiers[h.tier].residents, crowded = h.residents >= max * 0.75+ fire = (h.tier === 1 ? risk.fire.wooden : risk.fire.stone) + Math.min(2, input.hotNearby) * risk.fire.near ++ (crowded ? risk.fire.crowded : 0) + (worn ? risk.fire.worn : 0) + (input.heating ? risk.fire.winter : 0)+ health = risk.health.base + (h.food <= 0 ? risk.health.hungry : 0) + (crowded ? risk.health.crowded : 0) ++ (squalid ? risk.health.squalid : 0) + (input.dusty ? risk.health.dust : 0) + (input.water ? risk.health.water : 0)+ order = risk.order.base + (input.approval < 0 ? Math.round((-input.approval / 50) * risk.order.unrest) : 0) ++ (squalid ? risk.order.squalid : 0) + (h.residents < max / 2 ? risk.order.vacant : 0) + (h.tier === 3 ? risk.order.wealth : 0)+ } else if (input.kind) fire = risk.fire.building + (rules.kinds[input.kind].hot ? risk.fire.hot : 0) + (worn ? risk.fire.worn : 0)+ const pace = paceAt(input.tile.x, input.tile.y, rules)+ return { fire: Math.round(fire * pace), health: Math.round(health * pace), order: Math.round(order * pace) }+}diff --git a/src/rules/seasons.ts b/src/rules/seasons.tsnew file mode 100644index 0000000..38737ef--- /dev/null+++ b/src/rules/seasons.ts@@ -0,0 +1,62 @@+import type { WinterId } from "../content.ts"+import { ruleTicks, shippedRules, type Rules } from "./config.ts"++// ── Time ──────────────────────────────────────────────────────────────────++/** Steps since the town was founded. */+export const elapsed = (time: { readonly tick: number }, charter: { readonly founded: number }) => time.tick - charter.founded+export const termTicks = (charter: { readonly term: number }, rules: Rules = shippedRules) => ruleTicks(charter.term * 60, rules)+export const yearTicks = (charter: { readonly term: number }, rules: Rules = shippedRules) => Math.round(termTicks(charter, rules) / rules.yearsPerTerm)++/** A charter's winters: the first year has none. */+export type Almanac = ReadonlyArray<WinterId | "none">+export interface Seasoned {+ readonly term: number+ readonly winters?: Almanac+}++/** The winter that ends year `year` (from 1), or `null` for none: the first year's, and any past the term. */+export const winterOf = (charter: Seasoned, year: number, rules: Rules = shippedRules): WinterId | null => {+ if (year <= 1 || year > rules.yearsPerTerm) return null+ const w = charter.winters?.[year - 1]+ return w === undefined ? "normal" : w === "none" ? null : w+}++/** Rolls each year's winter from a random number in 0 → 1 a year (the first year's is spared). */+export const rollWinters = (next: () => number, rules: Rules = shippedRules): Array<WinterId | "none"> =>+ Array.from({ length: rules.yearsPerTerm }, (_, i) => {+ if (i === 0) return "none"+ const r = next()+ return r < rules.winters.mild.chance ? "mild" : r < rules.winters.mild.chance + rules.winters.normal.chance ? "normal" : "hard"+ })++/**+ * The season `t` steps into a term: which year, whether it is winter (and+ * which), how long until that changes, and the next winter the almanac+ * foresees. The first year is spared its winter: a new town has a year to+ * find its feet. A hard winter starts earlier in its year and lasts half+ * as long again.+ */+export const seasonAt = (t: number, charter: Seasoned, rules: Rules = shippedRules) => {+ const year = yearTicks(charter, rules)+ const into = t % year+ const number = Math.floor(t / year) + 1+ const thawOf = (n: number) => {+ const w = winterOf(charter, n, rules)+ return w === null ? year : Math.round(year * (1 - rules.winters[w].share))+ }+ const thaw = thawOf(number)+ const winter = into >= thaw+ // The next winter to come: this year's, if it is still ahead, or the next's.+ const ahead = !winter && winterOf(charter, number, rules) !== null ? number : number + 1+ const left = winter ? year - into : ahead === number ? thaw - into : year - into + thawOf(number + 1)+ return {+ year: number,+ winter,+ /** This winter's severity, while it lasts. */+ severity: winter ? winterOf(charter, number, rules) : null,+ /** The coming winter's severity, or `null` when the term ends first. */+ coming: winterOf(charter, ahead, rules),+ left+ }+}diff --git a/src/rules/trade.ts b/src/rules/trade.tsnew file mode 100644index 0000000..e14bbd2--- /dev/null+++ b/src/rules/trade.ts@@ -0,0 +1,44 @@+import { goodIds, type Amounts, type GoodId } from "../content.ts"+import { askOf, priceOf } from "./households.ts"+import { shippedRules, type Rules } from "./config.ts"++export interface TradePolicy { readonly sells: ReadonlyArray<GoodId>; readonly buys: ReadonlyArray<GoodId>; readonly reserve: number }+export interface Shelf { readonly stock: Amounts; readonly accepts: ReadonlyArray<GoodId>; readonly cap: number }++/** Exact collection trade, including price drift and refunds. Shelves keep runtime insertion order. */+export const tradeCollection = (initial: ReadonlyArray<Shelf>, policy: TradePolicy, initialPrices: Amounts, startingCoins: number, rules: Rules = shippedRules) => {+ const stores = initial.map((s) => ({ ...s, stock: { ...s.stock } })), prices = { ...initialPrices }+ let coins = startingCoins, traded = 0+ for (const good of goodIds) {+ const held = stores.reduce((sum, s) => sum + s.stock[good], 0)+ if (policy.sells.includes(good)) {+ let surplus = Math.min(rules.tradeLoad, held - policy.reserve)+ if (surplus > 0) {+ const earned = Math.round(surplus * priceOf(good, prices[good], rules))+ coins += earned; traded += earned+ prices[good] = Math.max(rules.market.floor, prices[good] - surplus * rules.market.perUnit)+ for (const inv of [...stores].sort((a, b) => b.stock[good] - a.stock[good])) {+ if (surplus <= 0) break+ const take = Math.min(surplus, inv.stock[good]); inv.stock[good] -= take; surplus -= take+ }+ }+ } else if (policy.buys.includes(good)) {+ const ask = askOf(good, prices[good], rules)+ let wanted = Math.min(rules.tradeLoad, policy.reserve - held, Math.floor(coins / ask))+ if (wanted > 0) {+ coins -= wanted * ask; traded -= wanted * ask+ prices[good] = Math.min(rules.market.ceiling, prices[good] + wanted * rules.market.perUnit)+ for (const inv of [...stores].sort((a, b) => a.stock[good] - b.stock[good])) {+ if (wanted <= 0) break+ const put = inv.accepts.includes(good) ? Math.min(wanted, inv.cap - inv.stock[good]) : 0+ if (put <= 0) continue+ inv.stock[good] += put; wanted -= put+ }+ if (wanted > 0) { coins += wanted * ask; traded += wanted * ask }+ }+ }+ const gap = 100 - prices[good]+ prices[good] += gap === 0 ? 0 : Math.sign(gap) * Math.max(1, Math.round(Math.abs(gap) / 10))+ }+ return { stores, prices, coins, traded }+}diff --git a/src/rules/transport.ts b/src/rules/transport.tsnew file mode 100644index 0000000..b109798--- /dev/null+++ b/src/rules/transport.ts@@ -0,0 +1,15 @@+import { DIRS, isRoad } from "../grid.ts"+import type { GridValue } from "../schema.ts"+import type { Point } from "../iso.ts"++/** Shared candidate enumeration; Random.pick selects uniformly from this list in the runtime. */+export const onwardRoads = (grid: GridValue, cell: Point, previous: Point | null): ReadonlyArray<Point> =>+ DIRS.map((d) => ({ x: cell.x + d.x, y: cell.y + d.y }))+ .filter((c) => isRoad(grid, c.x, c.y) && !(previous && c.x === previous.x && c.y === previous.y))++export interface DeliveryCandidate {+ readonly site: boolean; readonly distance: number+}+/** Construction first, then nearest; exact ties keep the earlier candidate. */+export const preferDelivery = (candidate: DeliveryCandidate, best: DeliveryCandidate | null): boolean =>+ best === null || (candidate.site && !best.site) || (candidate.site === best.site && candidate.distance < best.distance)diff --git a/src/schema.ts b/src/schema.tsindex d6f4d19..43adadf 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -18,6 +18,7 @@ import type { NodeRegistry } from "@typeonce/bevy-ts-render"import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView, WalkerView } from "./render3d/views.ts"import type { GameScene } from "./render3d/scene.ts"import { goodIds, groundIds, kindIds, landIds, propIds, serviceIds, sizeIds, type Amounts } from "./content.ts"+import type { Rules as RuleInputs } from "./rules/config.ts"import type { UiValue } from "./ui.ts"export const Root = Schema.defineRoot("Town")@@ -323,6 +324,7 @@ export const Stock = Descriptor.TransientResource<Amounts>()("Town/Stock")// ── Host services ─────────────────────────────────────────────────────────+export const Rules = Descriptor.Service<RuleInputs>()("Town/Rules")export const Ui = Descriptor.Service<UiValue>()("Town/Ui")/** The frame's length, for animation only: the simulation runs on `Time`. */export const Clock = Descriptor.Service<{ deltaSeconds: number; elapsed: number }>()("Town/Clock")diff --git a/src/sim/decay.ts b/src/sim/decay.tsindex 0c96cb3..26102bc 100644--- a/src/sim/decay.ts+++ b/src/sim/decay.ts@@ -1,3 +1,4 @@+import { spoilExpectation } from "../rules/decay.ts"/*** What time does to the town: homes and buildings run down until a builder* mends them, and fall into ruin if none does; fish and bread rot on the@@ -7,11 +8,9 @@import * as Random from "@typeonce/bevy-ts-math/Random"import { ruinDraft } from "../archetypes.ts"-import { condition as wear, goodIds, kinds, SPOIL_TICKS, spoils, ticks } from "../content.ts"+import { goodIds, ticks } from "../content.ts"import { counted, placeName } from "../places.ts"-import {- Building, Burning, Charter, Chronicle, Condition, Game, House, Inventory, Pantry, Rising, Rng, Site, Tile, Time, maybe-} from "../schema.ts"+import { Building, Burning, Charter, Chronicle, Condition, Game, Rules, House, Inventory, Pantry, Rising, Rng, Site, Tile, Time, maybe } from "../schema.ts"import { elapsed, write } from "./shared.ts"/** The pantry warns of rotting food at most this often. */@@ -34,9 +33,13 @@ export const Decay = Game.System(rng: Game.System.writeResource(Rng),pantry: Game.System.writeResource(Pantry),chronicle: Game.System.writeResource(Chronicle)- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources, commands }) => {+ ({ queries, resources, commands, services }) => {+ const rules = services.rules+ const { kinds, condition: wear, spoils, spoilTicks: SPOIL_TICKS } = rules+const tick = resources.time.get().tickconst t = elapsed(resources.time.get(), resources.charter.get())@@ -73,7 +76,7 @@ export const Decay = Game.System(for (const g of goodIds) {const life = spoils[g]if (life === undefined || stock[g] <= 0) continue- const expected = (stock[g] * SPOIL_TICKS) / (life * 60 * keeps)+ const expected = spoilExpectation(stock[g], g, keeps, rules)const lose = Math.min(stock[g], Math.floor(expected) + (random.next() < expected % 1 ? 1 : 0))if (lose <= 0) continuestock = { ...stock, [g]: stock[g] - lose }diff --git a/src/sim/edits.ts b/src/sim/edits.tsindex 97a91c4..5ff4e76 100644--- a/src/sim/edits.ts+++ b/src/sim/edits.ts@@ -6,19 +6,13 @@* carried to the site afterwards. Once the term has ended, only a new town* (or carrying on after completing this one) is taken.*/-import {- buildingDraft, houseDraft, houseStart, parkDraft, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft-} from "../archetypes.ts"+import { buildingDraft, houseDraft, houseStart, parkDraft, roadDraft, rockDraft, rolesOf, startOf, treeDraft, waterDraft } from "../archetypes.ts"import * as Random from "@typeonce/bevy-ts-math/Random"--import { amounts, goodIds, goods, grounds, home, kinds, lands, PAVE_COST, props, ROAD_COST, sizes, trade, type Amounts, type Kind, type ParkPiece } from "../content.ts"+import { amounts, goodIds, type Amounts, type Kind, type ParkPiece } from "../content.ts"import { canPlace, cellsOf, GridBuilder, ownerAt, useAt } from "../grid.ts"import { inside } from "../iso.ts"import { generate } from "../mapgen.ts"-import {- Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, History, Inventory, Land, Ledger, Market, Mood, Pantry, Park, Paved, Paused,- Policy, Rng, Status, Stock, Storage, Time, TownHall, Treasury, Ui-} from "../schema.ts"+import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Rules, History, Inventory, Land, Ledger, Market, Mood, Pantry, Park, Paved, Paused, Policy, Rng, Status, Stock, Storage, Time, TownHall, Treasury, Ui } from "../schema.ts"import { elapsed, rollWinters, TileRead, useOf, write } from "./shared.ts"import { crownGap, foundedFate } from "./term.ts"@@ -56,9 +50,12 @@ export const ApplyEdits = Game.System(pantry: Game.System.writeResource(Pantry),fires: Game.System.writeResource(Fires)},- services: { ui: Game.System.service(Ui) }+ services: { ui: Game.System.service(Ui), rules: Game.System.service(Rules) }},({ queries, resources, services, commands }) => {+ const rules = services.rules+ const { kinds, home, goods, grounds, props, lands, sizes, trade, roadCost: ROAD_COST, paveCost: PAVE_COST } = rules+const ui = services.uiif (ui.edits.length === 0) returnconst grid = new GridBuilder(resources.land.get().mask)@@ -137,7 +134,7 @@ export const ApplyEdits = Game.System(}pay(kind.cost)const id = spawn(buildingDraft(kind, edit.cell), tile, "building")- commands.insert(id, startOf(kind), ...rolesOf(kind))+ commands.insert(id, startOf(kind), ...rolesOf(kind, rules))if (edit.open) ui.selected = idbreak}@@ -150,7 +147,7 @@ export const ApplyEdits = Game.System(if (short) breakpay(home.cost)const id = spawn(houseDraft(cell), tile, "house")- commands.insert(id, ...houseStart())+ commands.insert(id, ...houseStart(rules))}if (short) ui.toast(short)break@@ -318,21 +315,21 @@ export const ApplyEdits = Game.System(entities.clear()const charter = edit.charterconst richness = lands[charter.land]- const land = generate(charter)+ const land = generate(charter, rules)for (const c of land.water) commands.spawn(waterDraft(c))for (const tree of land.trees) commands.spawn(treeDraft(tree.cell, tree.growth))for (const r of land.rocks) commands.spawn(rockDraft(r.cell, r.ore, r.amount))for (const c of land.roads) commands.spawn(roadDraft(c))const hall = kinds.townhallconst id = commands.spawn(buildingDraft(hall, land.hall))- commands.insert(id, ...rolesOf(hall))+ commands.insert(id, ...rolesOf(hall, rules))const stock: Amounts = amounts(richness.stock)commands.insert(id, Game.Command.entry(TownHall, {}), Game.Command.entry(Status, "idle"), Game.Command.entry(Inventory, { stock, accepts: goodIds, cap: hall.holds?.cap ?? 60 }))coins = richness.coinsconst founded = resources.time.get().tick// The almanac: each year's winter, from the seed (on its own stream, so the land's randomness is untouched).const almanac = Random.make((charter.seed ^ 0x5a17c3) >>> 0)- resources.charter.set({ ...charter, founded, winters: rollWinters(() => almanac.next()) })+ resources.charter.set({ ...charter, founded, winters: rollWinters(() => almanac.next(), rules) })resources.appeal.set({ cells: [] })resources.pantry.set({ eaten: 0, rotted: 0, eatenLast: 0, rottedLast: 0, warned: -1_000_000 })resources.fires.set({ fires: [], next: 1 })@@ -341,7 +338,7 @@ export const ApplyEdits = Game.System(resources.policy.set({ settlers: 100, citizens: 100, sells: trade.sells, buys: [], reserve: trade.reserve })resources.market.set({ prices: amounts(Object.fromEntries(goodIds.map((g) => [g, 100]))) })resources.mood.set({ approval: 10, target: 10, base: 0, needs: 0, taxes: 0, debt: 0, crown: 0, winter: 0 })- resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter), met: 0, missed: 0, streak: 0, snubs: [] })+ resources.crown.set({ open: false, good: "wood", amount: 0, issued: 0, due: 0, reward: 0, next: crownGap(charter, rules), met: 0, missed: 0, streak: 0, snubs: [] })resources.fate.set(foundedFate())resources.history.set({ samples: [] })resources.chronicle.set({diff --git a/src/sim/hazards.ts b/src/sim/hazards.tsindex 602293a..e0dec0d 100644--- a/src/sim/hazards.ts+++ b/src/sim/hazards.ts@@ -1,3 +1,4 @@+import { near, riskIncrements } from "../rules/risks.ts"/*** The neighbourhood and its dangers. Every so often the town's desirability* is reckoned cell by cell (`Appraise`). Once a second every home's risk of@@ -12,14 +13,11 @@ import * as Random from "@typeonce/bevy-ts-math/Random"import { appealGrid, appealAt, buildingSource, landSource, parkSources, type AppealSource } from "../appeal.ts"import { ruinDraft } from "../archetypes.ts"-import { appeal, condition as wear, goodIds, goods, home, kinds, risk, RISK_MAX, winters, type GoodId } from "../content.ts"+import { goodIds, risk, type GoodId } from "../content.ts"import { doors, nearest, pathTo, reach, useAt } from "../grid.ts"import { counted, placeName, type Landmark } from "../places.ts"import type { Point } from "../iso.ts"-import {- Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Grid, House, Inventory, Mood, Park, Paved, Rescue, Rising, Risk, Rng,- Road, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Tree, Treasury, WalkerOf, Water, maybe-} from "../schema.ts"+import { Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Rules, Grid, House, Inventory, Mood, Park, Paved, Rescue, Rising, Risk, Rng, Road, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Tree, Treasury, WalkerOf, Water, maybe } from "../schema.ts"import { elapsed, seasonAt, write } from "./shared.ts"// ── Desirability ──────────────────────────────────────────────────────────@@ -38,23 +36,27 @@ export const Appraise = Game.System(ruins: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Ruin] }),homes: Game.Query({ selection: { tile: Game.Query.read(Tile), condition: Game.Query.read(Condition) }, with: [House], without: [Site, Rising] })},- resources: { time: Game.System.readResource(Time), appeal: Game.System.writeResource(Appeal) }+ resources: { time: Game.System.readResource(Time), appeal: Game.System.writeResource(Appeal) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources }) => {+ ({ queries, resources, services }) => {+ const rules = services.rules+ const { appeal, condition: wear } = rules+if (resources.time.get().tick % appeal.every !== 0 && resources.appeal.get().cells.length > 0) returnconst sources: Array<AppealSource> = []for (const { data } of queries.buildings.each()) {- const s = buildingSource(data.building.get().kind, data.tile.get())+ const s = buildingSource(data.building.get().kind, data.tile.get(), rules)if (s) sources.push(s)}- for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get()))- for (const { data } of queries.water.each()) sources.push(landSource("water", data.tile.get()))- for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get()))+ for (const { data } of queries.trees.each()) sources.push(landSource("forest", data.tile.get(), rules))+ for (const { data } of queries.water.each()) sources.push(landSource("water", data.tile.get(), rules))+ for (const { data } of queries.paved.each()) sources.push(landSource("paved", data.tile.get(), rules))const roads = new Set(queries.roads.each().map(({ data }) => `${data.tile.get().x},${data.tile.get().y}`))- sources.push(...parkSources(queries.parks.each().map(({ data }) => ({ ...data.tile.get(), ...data.park.get() })), (x, y) => roads.has(`${x},${y}`)))- for (const { data } of queries.ruins.each()) sources.push(landSource("ruin", data.tile.get()))- for (const { data } of queries.homes.each()) if (data.condition.get().value < wear.worn) sources.push(landSource("worn", data.tile.get()))- resources.appeal.set({ cells: appealGrid(sources) })+ sources.push(...parkSources(queries.parks.each().map(({ data }) => ({ ...data.tile.get(), ...data.park.get() })), (x, y) => roads.has(`${x},${y}`), rules))+ for (const { data } of queries.ruins.each()) sources.push(landSource("ruin", data.tile.get(), rules))+ for (const { data } of queries.homes.each()) if (data.condition.get().value < wear.worn) sources.push(landSource("worn", data.tile.get(), rules))+ resources.appeal.set({ cells: appealGrid(sources, rules) })})@@ -63,18 +65,7 @@ export const Appraise = Game.System(/** The risks are reckoned this often (once a second). */export const RISK_TICKS = 60-/** A stable number 0 → 1 for a cell. */-const hash = (x: number, y: number) => {- let h = (x * 374761393 + y * 668265263) >>> 0- h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0- return ((h ^ (h >>> 16)) >>> 0) / 4294967296-}-/** How fast the risks of whatever stands on a cell rise, against the usual. */-export const paceAt = (x: number, y: number) => risk.pace[0] + (risk.pace[1] - risk.pace[0]) * hash(x, y)--/** Within `r` rings of a footprint. */-const near = (a: { readonly x: number; readonly y: number; readonly size: number }, b: { readonly x: number; readonly y: number; readonly size: number }, r: number) =>- Math.max(a.x - (b.x + b.size - 1), b.x - (a.x + a.size - 1), a.y - (b.y + b.size - 1), b.y - (a.y + a.size - 1)) <= r+export { paceAt } from "../rules/risks.ts"export const Hazards = Game.System("Town/Hazards",@@ -112,9 +103,13 @@ export const Hazards = Game.System(treasury: Game.System.writeResource(Treasury),fires: Game.System.writeResource(Fires),chronicle: Game.System.writeResource(Chronicle)- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources, commands }) => {+ ({ queries, resources, commands, services }) => {+ const rules = services.rules+ const { kinds, goods, risk, winters, riskMax: RISK_MAX, riskTicks: RISK_TICKS } = rules+const tick = resources.time.get().tickif (tick % RISK_TICKS !== 0) returnconst charter = resources.charter.get()@@ -122,7 +117,7 @@ export const Hazards = Game.System(const grid = resources.grid.get()const cells = resources.appeal.get().cellsconst approval = resources.mood.get().approval- const season = seasonAt(t, charter)+ const season = seasonAt(t, charter, rules)const heating = season.severity !== null && winters[season.severity].heatingconst random = Random.make(resources.rng.get())const news = (text: string) => write(resources.chronicle, t, text, true)@@ -158,26 +153,17 @@ export const Hazards = Game.System(const h = maybe(data.house)const b = maybe(data.building)const r = { ...data.risk.get() }- const worn = data.condition.get().value < wear.worn- const desirability = appealAt(cells, tile.x, tile.y)- const squalid = desirability < 0- const pace = paceAt(tile.x, tile.y)- let fire = 0+ const increments = riskIncrements({+ tile, condition: data.condition.get().value, desirability: appealAt(cells, tile.x, tile.y), approval, heating,+ hotNearby: hot.filter((source) => near(source, tile, risk.fire.reach)).length,+ dusty: dusty.some((d) => near(d, tile, risk.health.reach)), water: waterNear(tile),+ ...(h ? { house: h } : {}), ...(b ? { kind: b.kind } : {})+ }, rules)if (h) {- const max = home.tiers[h.tier].residents- const crowded = h.residents >= max * 0.75- fire = (h.tier === 1 ? risk.fire.wooden : risk.fire.stone) +- Math.min(2, hot.filter((s) => near(s, tile, risk.fire.reach)).length) * risk.fire.near +- (crowded ? risk.fire.crowded : 0) + (worn ? risk.fire.worn : 0) + (heating ? risk.fire.winter : 0)- const health = risk.health.base + (h.food <= 0 ? risk.health.hungry : 0) + (crowded ? risk.health.crowded : 0) +- (squalid ? risk.health.squalid : 0) + (dusty.some((d) => near(d, tile, risk.health.reach)) ? risk.health.dust : 0) +- (waterNear(tile) ? risk.health.water : 0)- const order = risk.order.base + (approval < 0 ? Math.round((-approval / 50) * risk.order.unrest) : 0) + (squalid ? risk.order.squalid : 0) +- (h.residents < max / 2 ? risk.order.vacant : 0) + (h.tier === 3 ? risk.order.wealth : 0)- if (!data.sick.present) r.health = Math.min(RISK_MAX, r.health + Math.round(health * pace))- r.order = Math.min(RISK_MAX, r.order + Math.round(order * pace))- } else if (b) fire = risk.fire.building + (kinds[b.kind].hot ? risk.fire.hot : 0) + (worn ? risk.fire.worn : 0)- r.fire = Math.min(RISK_MAX, r.fire + Math.round(fire * pace))+ if (!data.sick.present) r.health = Math.min(RISK_MAX, r.health + increments.health)+ r.order = Math.min(RISK_MAX, r.order + increments.order)+ }+ r.fire = Math.min(RISK_MAX, r.fire + increments.fire)if (r.fire >= RISK_MAX) {// Fire!diff --git a/src/sim/headless.ts b/src/sim/headless.tsindex c246613..5806d78 100644--- a/src/sim/headless.ts+++ b/src/sim/headless.ts@@ -5,7 +5,8 @@* the same snapshots it saves.*/import { STEP_SECONDS, type CharterValue } from "../content.ts"-import { Game, Ui } from "../schema.ts"+import { resolveRules, type Rules as RuleInputs } from "../rules/config.ts"+import { Game, Rules, Ui } from "../schema.ts"import { emptyPreview, type Edit, type UiValue } from "../ui.ts"import { blankResources, simulate } from "./index.ts"@@ -19,7 +20,7 @@ export interface Snapshot {machines: Record<string, string>}-export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void } = {}) => {+export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void; readonly rules?: RuleInputs } = {}) => {const ui: UiValue = {tool: "select", placing: null, ground: "lawn", prop: "lamp", menu: null, pointer: null, dragFrom: null, selected: null, gestures: [],edits: [{ type: "newTown", charter }],@@ -27,7 +28,7 @@ export const headless = (charter: CharterValue, options: { readonly toast?: (mesview: "none", overlay: { key: "", cells: [] }, legend: null,toast: options.toast ?? (() => {})}- const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui)), resources: blankResources() })+ const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui), Game.Runtime.service(Rules, options.rules ?? resolveRules())), resources: blankResources() })if (!made.ok) throw new Error(`The town could not start: ${JSON.stringify(made.error)}`)const runtime = made.valueconst step = () => {diff --git a/src/sim/logistics.ts b/src/sim/logistics.tsindex 24b5e1c..c8deb28 100644--- a/src/sim/logistics.ts+++ b/src/sim/logistics.ts@@ -1,3 +1,5 @@+import { transport } from "../rules/config.ts"+import { preferDelivery } from "../rules/transport.ts"/*** Carriers: every good that moves walks along the roads in a carrier's* crate. What a building wants — a site's materials, a workshop's input, a@@ -6,19 +8,16 @@* storage sends what it holds to the nearest demands it can meet. Crates* already on their way count against a demand, so no one is sent twice.*/-import { goods, goodIds, provisions, spoils, TOOL_STOCK, type GoodId } from "../content.ts"+import { goodIds, provisions, type GoodId } from "../content.ts"import { doors, nearest, pathTo, reach, type Reach } from "../grid.ts"import type { Point } from "../iso.ts"-import {- Building, Burning, Carriers, Errand, Figure, Game, Grid, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, maybe-} from "../schema.ts"-import { kinds } from "../content.ts"+import { Building, Burning, Carriers, Errand, Figure, Game, Rules, Grid, Inventory, Recipe, Rising, Route, Service, Site, Storage, Tile, Time, WalkerOf, maybe } from "../schema.ts"import { CELL_STEPS } from "./shared.ts"/** The most a carrier takes at once. */-const LOAD = 4+const LOAD = transport.load/** Carriers are sent out this often: ten times a second, a delay no one sees, at a sixth of the work. */-const DISPATCH_TICKS = 6+const DISPATCH_TICKS = transport.dispatchTicksexport const Dispatch = Game.System("Town/Dispatch",@@ -49,9 +48,13 @@ export const Dispatch = Game.System(sites: Game.Query({ selection: { tile: Game.Query.read(Tile), site: Game.Query.read(Site) } }),errands: Game.Query({ selection: { errand: Game.Query.read(Errand), home: Game.Query.readRelation(WalkerOf) } })},- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) }+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources, commands }) => {+ ({ queries, resources, commands, services }) => {+ const rules = services.rules+ const { kinds, goods, spoils, toolStock: TOOL_STOCK } = rules+if (resources.time.get().tick % DISPATCH_TICKS !== 0) returnconst grid = resources.grid.get()const out = new Map<number, number>()@@ -141,7 +144,7 @@ export const Dispatch = Game.System(if (count <= 0) continueconst found = nearest(roads, w.doors)// Sites come first, then whoever is nearest.- if (found && (best === null || (w.site && !best.site) || (w.site === best.site && found.distance < best.distance))) best = { id: w.id, ...found, count, site: w.site }+ if (found && preferDelivery({ site: w.site, distance: found.distance }, best)) best = { id: w.id, ...found, count, site: w.site }}// Food that spoils goes to a granary if there is one in reach, before the nearest storage; a// storage that does not keep food sends it on to a granary that does.@@ -195,9 +198,13 @@ export const Deliver = Game.System(carriers: Game.Query({ selection: { route: Game.Query.write(Route), errand: Game.Query.write(Errand), home: Game.Query.readRelation(WalkerOf) } }),inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, without: [Site] }),sites: Game.Query({ selection: { site: Game.Query.write(Site) } })- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ queries, commands, lookup }) => {+ ({ queries, commands, lookup, services }) => {+ const rules = services.rules+ const { } = rules+for (const { entity, data } of queries.carriers.each()) {const route = data.route.get()const errand = data.errand.get()diff --git a/src/sim/shared.ts b/src/sim/shared.tsindex 5b7a868..30d7bae 100644--- a/src/sim/shared.ts+++ b/src/sim/shared.ts@@ -1,5 +1,4 @@/** Queries and small helpers the simulation's systems share. */-import { ticks, winters, YEARS_PER_TERM, type WinterId } from "../content.ts"import { doors, type TileLike, type Use } from "../grid.ts"import { Field, Game, House, Park, Road, Rock, Ruin, Tile, Tree, Water, type GridValue } from "../schema.ts"@@ -40,68 +39,9 @@ export const useOf = (data: {export const connected = (grid: GridValue, tile: TileLike): boolean => doors(grid, tile).length > 0-/** A walker's steps from one cell's centre to the next: three to a unit, so it moves on the lattice. */-export const CELL_STEPS = 48--// ── Time ──────────────────────────────────────────────────────────────────--/** Steps since the town was founded. */-export const elapsed = (time: { readonly tick: number }, charter: { readonly founded: number }) => time.tick - charter.founded-export const termTicks = (charter: { readonly term: number }) => ticks(charter.term * 60)-export const yearTicks = (charter: { readonly term: number }) => Math.round(termTicks(charter) / YEARS_PER_TERM)--/** A charter's winters: the first year has none. */-export type Almanac = ReadonlyArray<WinterId | "none">-interface Seasoned {- readonly term: number- readonly winters?: Almanac-}--/** The winter that ends year `year` (from 1), or `null` for none: the first year's, and any past the term. */-export const winterOf = (charter: Seasoned, year: number): WinterId | null => {- if (year <= 1 || year > YEARS_PER_TERM) return null- const w = charter.winters?.[year - 1]- return w === undefined ? "normal" : w === "none" ? null : w-}--/** Rolls each year's winter from a random number in 0 → 1 a year (the first year's is spared). */-export const rollWinters = (next: () => number): Array<WinterId | "none"> =>- Array.from({ length: YEARS_PER_TERM }, (_, i) => {- if (i === 0) return "none"- const r = next()- return r < winters.mild.chance ? "mild" : r < winters.mild.chance + winters.normal.chance ? "normal" : "hard"- })--/**- * The season `t` steps into a term: which year, whether it is winter (and- * which), how long until that changes, and the next winter the almanac- * foresees. The first year is spared its winter: a new town has a year to- * find its feet. A hard winter starts earlier in its year and lasts half- * as long again.- */-export const seasonAt = (t: number, charter: Seasoned) => {- const year = yearTicks(charter)- const into = t % year- const number = Math.floor(t / year) + 1- const thawOf = (n: number) => {- const w = winterOf(charter, n)- return w === null ? year : Math.round(year * (1 - winters[w].share))- }- const thaw = thawOf(number)- const winter = into >= thaw- // The next winter to come: this year's, if it is still ahead, or the next's.- const ahead = !winter && winterOf(charter, number) !== null ? number : number + 1- const left = winter ? year - into : ahead === number ? thaw - into : year - into + thawOf(number + 1)- return {- year: number,- winter,- /** This winter's severity, while it lasts. */- severity: winter ? winterOf(charter, number) : null,- /** The coming winter's severity, or `null` when the term ends first. */- coming: winterOf(charter, ahead),- left- }-}+import { transport } from "../rules/config.ts"+export const CELL_STEPS = transport.cellSteps+export { elapsed, termTicks, yearTicks, winterOf, rollWinters, seasonAt, type Almanac } from "../rules/seasons.ts"// ── The chronicle ─────────────────────────────────────────────────────────diff --git a/src/sim/term.ts b/src/sim/term.tsindex 62c5864..0ca8ff5 100644--- a/src/sim/term.ts+++ b/src/sim/term.ts@@ -1,18 +1,14 @@+import { approvalTarget, nextApproval } from "../rules/approval.ts"+import { shippedRules } from "../rules/config.ts"/*** The term in office: the seasons turn, the crown asks for goods, the* town's approval follows how it is treated, the town's history is kept,* and the term ends: complete, lost, or run out.*/-import {- crown, fate, goods, HISTORY_TICKS, mood, sizes, spoils, ticks, WINTER_WARNING, winters, type GoodId-} from "../content.ts"+import { crown, HISTORY_TICKS, ticks, WINTER_WARNING, type GoodId } from "../content.ts"import * as Random from "@typeonce/bevy-ts-math/Random"-import {- Building, Census, Charter, Chronicle, Crown, Fate, Game, History, House, Inventory, Ledger, Mood, Pantry, Policy, Recipe, Rising, Rng, Site,- Stock, Storage, Time, Treasury-} from "../schema.ts"+import { Building, Census, Charter, Chronicle, Crown, Fate, Game, Rules, History, House, Inventory, Ledger, Mood, Pantry, Policy, Recipe, Rising, Rng, Site, Stock, Storage, Time, Treasury } from "../schema.ts"import { elapsed, seasonAt, termTicks, write } from "./shared.ts"-import { satisfaction } from "./town.ts"// ── Time ──────────────────────────────────────────────────────────────────@@ -30,14 +26,18 @@ export const Seasons = Game.System(stock: Game.System.readResource(Stock),pantry: Game.System.readResource(Pantry),chronicle: Game.System.writeResource(Chronicle)- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ resources }) => {+ ({ resources, services }) => {+ const rules = services.rules+ const { winters } = rules+const charter = resources.charter.get()const t = elapsed(resources.time.get(), charter)if (t <= 0) return- const now = seasonAt(t, charter)- const before = seasonAt(t - 1, charter)+ const now = seasonAt(t, charter, rules)+ const before = seasonAt(t - 1, charter, rules)if (now.winter && !before.winter) {const w = now.severity ?? "normal"write(@@ -63,7 +63,7 @@ export const Seasons = Game.System(// ── The crown ─────────────────────────────────────────────────────────────/** Steps between the crown's requests. */-export const crownGap = (charter: { readonly term: number }) => Math.round(termTicks(charter) / (crown.perTerm + 1))+export const crownGap = (charter: { readonly term: number }, rules = shippedRules) => Math.round(termTicks(charter, rules) / (rules.crown.perTerm + 1))/*** Every so often the crown asks for something the town makes, and that@@ -87,9 +87,13 @@ export const Requests = Game.System(treasury: Game.System.writeResource(Treasury),rng: Game.System.writeResource(Rng),chronicle: Game.System.writeResource(Chronicle)- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources }) => {+ ({ queries, resources, services }) => {+ const rules = services.rules+ const { goods, crown, spoils } = rules+if (resources.fate.get().state !== "playing") returnconst charter = resources.charter.get()const t = elapsed(resources.time.get(), charter)@@ -119,14 +123,14 @@ export const Requests = Game.System(const random = Random.make(resources.rng.get())const good = random.pick(options)!resources.rng.set(random.state)- const progress = Math.min(1, t / termTicks(charter))- const window = (crownGap(charter) * crown.window) / 3600+ const progress = Math.min(1, t / termTicks(charter, rules))+ const window = (crownGap(charter, rules) * crown.window) / 3600const share = crown.share[0] + (crown.share[1] - crown.share[0]) * progress// Never more than the town could keep in store.const room = queries.stores.each().reduce((sum, { data }) => sum + data.inventory.get().cap, 0)const amount = Math.max(4, Math.min(Math.round(room * crown.room), Math.round(rates.get(good)! * window * share)))const reward = Math.round(amount * goods[good].price * crown.reward) + crown.bonus- const gap = crownGap(charter)+ const gap = crownGap(charter, rules)const due = t + Math.round(gap * crown.window)resources.crown.set({ ...c, snubs: remembered, open: true, good, amount, issued: t, due, reward, next: t + gap })write(resources.chronicle, t, `The crown asks for ${amount} ${goods[good].title} within ${Math.round(((due - t) / 3600) * 10) / 10} minutes, for ${reward} coins.`, true)@@ -151,37 +155,19 @@ export const Approve = Game.System(treasury: Game.System.readResource(Treasury),crown: Game.System.readResource(Crown),mood: Game.System.writeResource(Mood)- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources }) => {+ ({ queries, resources, services }) => {+ const rules = services.rules+const t = elapsed(resources.time.get(), resources.charter.get())if (t % ticks(10) !== 0) returnconst policy = resources.policy.get()- let people = 0- let pleased = 0- let taxed = 0- let fed = 0- let homes = 0- for (const { data } of queries.homes.each()) {- const h = data.house.get()- homes += 1- if (h.food > 0) fed += 1- people += h.residents- pleased += h.residents * satisfaction(h)- taxed += h.residents * (h.tier === 1 ? policy.settlers : policy.citizens)- }- const share = people > 0 ? pleased / people : 0.5- const rate = people > 0 ? taxed / people : 100- const needs = Math.round(mood.needs[0] + (mood.needs[1] - mood.needs[0]) * share)- const taxes = Math.round((100 - rate) * mood.perTaxPoint)- const debt = resources.treasury.get().coins < 0 ? mood.debt : 0- const crownPart = resources.crown.get().snubs.length * mood.snub- const winter = seasonAt(t, resources.charter.get()).winter && homes > 0 && fed / homes < 0.5 ? mood.winterHunger : 0- const target = Math.max(-100, Math.min(100, mood.base + needs + taxes + debt + crownPart + winter))- resources.mood.update((m) => {- const approval = m.approval + Math.max(-mood.step, Math.min(mood.step, target - m.approval))- return { approval, target, base: mood.base, needs, taxes, debt, crown: crownPart, winter }- })+ const parts = approvalTarget(queries.homes.each().map(({ data }) => data.house.get()), policy,+ resources.treasury.get().coins, resources.crown.get().snubs.length, seasonAt(t, resources.charter.get(), rules).winter, rules)+ resources.mood.update((m) => ({ approval: nextApproval(m.approval, parts.target, rules), ...parts }))+})@@ -201,27 +187,8 @@ export const foundedFate = () => ({score: 0})-/** Food in storage: what would carry the town through a winter. */-export const larder = (stock: { readonly fish: number; readonly smoked: number; readonly bread: number }) => stock.fish + stock.smoked + stock.bread--/** Each goal the town must hold to be complete, met or not. */-export const goalsOf = (- charter: { readonly size: keyof typeof sizes },- s: { readonly settlers: number; readonly citizens: number; readonly coins: number; readonly net: number; readonly approval: number }-) => {- const goal = sizes[charter.size].goal- const residents = s.settlers + s.citizens- return [- { id: "residents", text: `${goal.residents} residents`, value: `${residents}`, met: residents >= goal.residents },- { id: "citizens", text: `${Math.round(fate.citizens * 100)}% of them citizens`, value: `${residents > 0 ? Math.round((s.citizens / residents) * 100) : 0}%`, met: residents > 0 && s.citizens >= residents * fate.citizens },- { id: "approval", text: `approval ${fate.approval} or more`, value: `${s.approval}`, met: s.approval >= fate.approval },- { id: "coins", text: `${goal.coins} coins, not losing any`, value: `${s.coins}`, met: s.coins >= goal.coins && s.net >= 0 }- ] as const-}--/** The town's score at the end of its term. */-export const scoreOf = (s: { readonly settlers: number; readonly citizens: number; readonly coins: number; readonly approval: number; readonly met: number; readonly missed: number }, won: boolean, minutesLeft: number) =>- Math.max(0, Math.round(s.settlers + 3 * s.citizens + Math.max(0, s.coins) / 20 + 2 * s.approval + 40 * s.met - 40 * s.missed + (won ? 500 + 20 * minutesLeft : 0)))+import { goalsOf, larder, scoreOf } from "../rules/goals.ts"+export { goalsOf, larder, scoreOf } from "../rules/goals.ts"/*** Once a second: does the term end? It is lost to bankruptcy (in debt too@@ -243,9 +210,13 @@ export const Judge = Game.System(crown: Game.System.readResource(Crown),fate: Game.System.writeResource(Fate),chronicle: Game.System.writeResource(Chronicle)- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ resources }) => {+ ({ resources, services }) => {+ const rules = services.rules+ const { crown, fate } = rules+const charter = resources.charter.get()const t = elapsed(resources.time.get(), charter)if (t <= 0 || t % 60 !== 0) return@@ -260,7 +231,7 @@ export const Judge = Game.System(const net = ledger.taxes + ledger.trade - ledger.upkeep - ledger.adminconst note = (text: string, alarm = false) => write(resources.chronicle, t, text, alarm)const minutes = (n: number) => ticks(n * 60)- const left = Math.max(0, Math.round((termTicks(charter) - t) / 3600))+ const left = Math.max(0, Math.round((termTicks(charter, rules) - t) / 3600))const score = (won: boolean) => scoreOf({ ...census, coins, approval, met: crownNow.met, missed: crownNow.missed }, won, left)const next = { ...f, peak: Math.max(f.peak, residents) }@@ -284,13 +255,13 @@ export const Judge = Game.System(if (next.revoltSince >= 0 && t - next.revoltSince >= minutes(fate.revolt)) return end("lost", "Revolt: the town has turned the mayor out.")if (next.peak >= fate.peak && residents < next.peak * fate.abandon) return end("lost", "Abandoned: the people have left the town.")if (crownNow.streak >= crown.patience) return end("lost", `Dismissed: the crown has replaced a mayor who left ${crown.patience} of its requests unanswered.`)- if (t >= termTicks(charter)) {+ if (t >= termTicks(charter, rules)) {return end("over", f.governing ? "The term is over: the town stood complete to the end." : "The term is over.")}// Goals.if (!f.governing) {- const goals = goalsOf(charter, { ...census, coins, net, approval })+ const goals = goalsOf(charter, { ...census, coins, net, approval }, rules)if (goals.every((g) => g.met)) {if (f.goalSince < 0) note("Every goal is met: the town needs only to hold them.")next.goalSince = f.goalSince < 0 ? t : f.goalSincediff --git a/src/sim/town.ts b/src/sim/town.tsindex 8e972d3..7aa5295 100644--- a/src/sim/town.ts+++ b/src/sim/town.ts@@ -1,86 +1,16 @@+import { tradeCollection } from "../rules/trade.ts"/*** The town: homes grow, level up, or empty depending on what reaches them;* taxes are collected from homes connected to the town hall and upkeep paid* for every standing building and park; and the census counts it all.*/-import { appealAt } from "../appeal.ts"-import {- admin, goodIds, goods, grounds, home, kinds, LEDGER_TICKS, market, PAUSED_UPKEEP, props, risk, TRADE_LOAD, type GoodId, type Need, type Tier-} from "../content.ts"+import { appealAt, parkUpkeep } from "../appeal.ts"import { doors, key, reach } from "../grid.ts"-import {- Appeal, Building, Burning, Census, Charter, Game, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rising, Risk, Sick, Site,- Staff, Storage, Tile, Time, TownHall, Treasury, maybe-} from "../schema.ts"+import { Appeal, Building, Burning, Census, Charter, Game, Rules, Grid, House, Inventory, Ledger, Market, Mood, Park, Paused, Policy, Rising, Risk, Sick, Site, Staff, Storage, Tile, Time, TownHall, Treasury, maybe } from "../schema.ts"import { connected, elapsed, seasonAt } from "./shared.ts"-interface Needs {- readonly tier: Tier- readonly food: number- readonly bread: number- readonly cloth: number- readonly faith: number-}--export const met = (h: Needs, need: Need): boolean => h[need] > 0--/** The share of its tier's needs a home has met, 0 → 1. */-export const satisfaction = (h: Needs, tier: Tier = h.tier): number => {- const needs = home.tiers[tier].needs- return needs.filter((n) => met(h, n)).length / needs.length-}--export interface Rates {- readonly settlers: number- readonly citizens: number-}-const rateOf = (rates: Rates, tier: Tier) => (tier === 1 ? rates.settlers : rates.citizens)--/** How approval (-100 → 100) sits with a home: a third as many residents at its worst, half again at its best. */-export const appealOf = (approval: number): number => (approval < 0 ? 1 + approval / 150 : 1 + approval / 200)--/**- * Residents a home holds at its tier and satisfaction: half when nothing is- * met, all when everything is; fewer when the town disapproves of its- * mayor, and up to all of them when it approves, needs or not. Nobody- * wants to live where it is squalid (desirability `home.squalid` or less):- * such a home holds fewer.- */-export const capacity = (h: Needs, approval: number, desirability = 0): number => {- const max = home.tiers[h.tier].residents- const squalor = desirability <= home.squalid ? home.crowded : 1- return Math.max(1, Math.min(max, Math.round(max * (0.5 + 0.5 * satisfaction(h)) * appealOf(approval) * squalor)))-}--/** Whether every risk meter of a home is kept low: a service walker of each kind passes it. */-export const kept = (r: { readonly fire: number; readonly health: number; readonly order: number }) =>- r.fire < risk.kept && r.health < risk.kept && r.order < risk.kept--/**- * The tier a home settles into: settlers whose every citizens' need is met,- * on a street desirable enough, become citizens; citizens with a street- * nicer still and all three services calling become burghers in a- * townhouse. A home that loses more than one of its needs, or whose street- * falls below its tier, steps back down.- */-export const tierFor = (h: Needs, desirability: number, r: { readonly fire: number; readonly health: number; readonly order: number }): Tier => {- const fits = (tier: Tier) => desirability >= home.tiers[tier].appeal- if (h.tier === 1) return satisfaction(h, 2) === 1 && fits(2) ? 2 : 1- if (satisfaction(h) < 2 / 3 || !fits(2)) return 1- if (h.tier === 2) return satisfaction(h, 3) === 1 && fits(3) && kept(r) ? 3 : 2- return fits(3) && kept(r) ? 3 : 2-}--/** Coins a minute the town hall's administration costs for `homes` homes. */-export const adminOf = (homes: number): number => Math.round(homes * (admin.perHome + homes / admin.growth))--/** What traders pay for one of a good now, and what they ask for one. */-export const priceOf = (good: GoodId, percent: number) => (goods[good].price * percent) / 100-export const askOf = (good: GoodId, percent: number) => Math.ceil(priceOf(good, percent) * market.markup)--/** Coins a home pays a minute. */-export const taxOf = (h: Needs & { readonly residents: number }, rates: Rates): number =>- h.residents * home.tiers[h.tier].tax * (rateOf(rates, h.tier) / 100) * (0.25 + 0.75 * satisfaction(h))+import { ageNeeds, baseCollection, mealDecay, adminOf, capacity, met, taxOf, tierFor } from "../rules/households.ts"+export { adminOf, appealOf, askOf, capacity, kept, met, priceOf, satisfaction, taxOf, tierFor, type Rates } from "../rules/households.ts"/*** Needs wear off, food faster in winter. Every so often a home settles@@ -109,31 +39,28 @@ export const Households = Game.System(appeal: Game.System.readResource(Appeal),time: Game.System.readResource(Time),charter: Game.System.readResource(Charter)- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources }) => {+ ({ queries, resources, services }) => {+ const rules = services.rules+ const { home, risk } = rules+const grid = resources.grid.get()const approval = resources.mood.get().approvalconst cells = resources.appeal.get().cellsconst t = elapsed(resources.time.get(), resources.charter.get())// In winter a meal lasts two thirds as long.- const eat = seasonAt(t, resources.charter.get()).winter && t % 2 === 0 ? 2 : 1+ const eat = mealDecay(t, seasonAt(t, resources.charter.get(), rules).winter)for (const { data } of queries.homes.each()) {const h = data.house.get()- const next = {- ...h,- clock: h.clock + 1,- food: Math.max(0, h.food - eat),- bread: Math.max(0, h.bread - eat),- cloth: Math.max(0, h.cloth - 1),- faith: Math.max(0, h.faith - 1)- }+ const next = ageNeeds(h, eat)if (data.burning.present) next.residents = 0else if (next.clock % home.settle === 0) {const tile = data.tile.get()const desirability = appealAt(cells, tile.x, tile.y)- next.tier = tierFor(next, desirability, maybe(data.risk) ?? { fire: 0, health: 0, order: 0 })- const well = connected(grid, tile) ? capacity(next, approval, desirability) : 0+ next.tier = tierFor(next, desirability, maybe(data.risk) ?? { fire: 0, health: 0, order: 0 }, rules)+ const well = connected(grid, tile) ? capacity(next, approval, desirability, rules) : 0const cap = data.sick.present ? Math.floor(well * risk.health.sickly) : wellnext.residents = Math.min(next.residents, home.tiers[next.tier].residents)next.residents += Math.sign(cap - next.residents)@@ -169,9 +96,13 @@ export const Collect = Game.System(market: Game.System.writeResource(Market),treasury: Game.System.writeResource(Treasury),ledger: Game.System.writeResource(Ledger)- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources }) => {+ ({ queries, resources, services }) => {+ const rules = services.rules+ const { kinds, ledgerTicks: LEDGER_TICKS, pausedUpkeep: PAUSED_UPKEEP } = rules+if (resources.time.get().tick % LEDGER_TICKS !== 0) returnconst grid = resources.grid.get()const policy = resources.policy.get()@@ -183,67 +114,20 @@ export const Collect = Game.System(for (const { data } of queries.homes.each()) {homes += 1const reached = roads !== null && doors(grid, data.tile.get()).some((c) => roads.distance[key(c.x, c.y)]! >= 0)- if (reached) taxes += taxOf(data.house.get(), policy)+ if (reached) taxes += taxOf(data.house.get(), policy, rules)}let upkeep = 0for (const { data } of queries.buildings.each()) upkeep += kinds[data.building.get().kind].upkeep * (data.paused.present ? PAUSED_UPKEEP : 1)- for (const { data } of queries.parks.each()) {- const p = data.park.get()- upkeep += grounds[p.ground].upkeep + (p.prop === "none" ? 0 : props[p.prop].upkeep)- }- const admin = adminOf(homes)+ for (const { data } of queries.parks.each()) upkeep += parkUpkeep(data.park.get(), rules)+ const admin = adminOf(homes, rules)- // Trade.const stores = queries.stores.each()- const prices: Record<GoodId, number> = { ...resources.market.get().prices }- let coins = resources.treasury.get().coins + Math.round(taxes * share) - Math.round((upkeep + admin) * share)- let traded = 0- for (const good of goodIds) {- const held = stores.reduce((sum, { data }) => sum + data.inventory.get().stock[good], 0)- if (policy.sells.includes(good)) {- let surplus = Math.min(TRADE_LOAD, held - policy.reserve)- if (surplus > 0) {- const earned = Math.round(surplus * priceOf(good, prices[good]))- coins += earned- traded += earned- prices[good] = Math.max(market.floor, prices[good] - surplus * market.perUnit)- for (const { data } of [...stores].sort((a, b) => b.data.inventory.get().stock[good] - a.data.inventory.get().stock[good])) {- if (surplus <= 0) break- const inv = data.inventory.get()- const take = Math.min(surplus, inv.stock[good])- data.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] - take } })- surplus -= take- }- }- } else if (policy.buys.includes(good)) {- const ask = askOf(good, prices[good])- let wanted = Math.min(TRADE_LOAD, policy.reserve - held, Math.floor(coins / ask))- if (wanted > 0) {- coins -= wanted * ask- traded -= wanted * ask- prices[good] = Math.min(market.ceiling, prices[good] + wanted * market.perUnit)- for (const { data } of [...stores].sort((a, b) => a.data.inventory.get().stock[good] - b.data.inventory.get().stock[good])) {- if (wanted <= 0) break- const inv = data.inventory.get()- const put = inv.accepts.includes(good) ? Math.min(wanted, inv.cap - inv.stock[good]) : 0- if (put <= 0) continue- data.inventory.set({ ...inv, stock: { ...inv.stock, [good]: inv.stock[good] + put } })- wanted -= put- }- // What found no room is refunded.- if (wanted > 0) {- coins += wanted * ask- traded += wanted * ask- }- }- }- // Prices drift back towards the usual.- const gap = 100 - prices[good]- prices[good] += gap === 0 ? 0 : Math.sign(gap) * Math.max(1, Math.round(Math.abs(gap) / 10))- }- resources.market.set({ prices })- resources.treasury.set({ coins })- resources.ledger.set({ taxes: Math.round(taxes), trade: Math.round(traded / share), upkeep: Math.round(upkeep), admin })+ const traded = tradeCollection(stores.map(({ data }) => data.inventory.get()), policy, resources.market.get().prices,+ resources.treasury.get().coins + baseCollection(taxes, upkeep, homes, rules).delta, rules)+ for (const [i, row] of stores.entries()) row.data.inventory.set(traded.stores[i]!)+ resources.market.set({ prices: traded.prices })+ resources.treasury.set({ coins: traded.coins })+ resources.ledger.set({ taxes: Math.round(taxes), trade: Math.round(traded.traded / share), upkeep: Math.round(upkeep), admin })})diff --git a/src/sim/walkers.ts b/src/sim/walkers.tsindex 187f9b9..140b6b0 100644--- a/src/sim/walkers.ts+++ b/src/sim/walkers.ts@@ -1,3 +1,6 @@+import { serveGoods } from "../rules/households.ts"+import { transport } from "../rules/config.ts"+import { onwardRoads } from "../rules/transport.ts"/*** Walking: every walker steps along its route; service buildings send a* walker out now and then, who wanders the roads serving the homes beside@@ -8,26 +11,21 @@*/import * as Random from "@typeonce/bevy-ts-math/Random"-import {- amounts, APPRENTICE, categoryColor, condition as wear, CONDITION_MAX, each, home, kinds, provisions, total, type Amounts, type Need-} from "../content.ts"-import { DIRS, doors, isRoad, key, nearest, ownerAt, pathTo, reach, useAt } from "../grid.ts"+import { amounts, categoryColor, each, provisions, total, type Amounts } from "../content.ts"+import { DIRS, doors, isRoad, nearest, ownerAt, pathTo, reach, useAt } from "../grid.ts"import { inside, type Point } from "../iso.ts"-import {- Building, Burning, Condition, Figure, Game, Grid, House, Inventory, Pantry, Paused, Recipe, Rescue, Rising, Risk, Rng, Roam, Route, Service, Sick,- Site, Staff, Status, Tile, Time, WalkerOf, maybe, type Status as StatusValue-} from "../schema.ts"+import { Building, Burning, Condition, Figure, Game, Rules, Grid, House, Inventory, Pantry, Paused, Recipe, Rescue, Rising, Risk, Rng, Roam, Route, Service, Sick, Site, Staff, Status, Tile, Time, WalkerOf, maybe, type Status as StatusValue } from "../schema.ts"import { CELL_STEPS } from "./shared.ts"import { paced } from "./work.ts"/** Steps a walker takes each tick: 1.25 cells a second. */-const WALK = 1+const WALK = transport.walk/** Firefighters run to a blaze. */-const RUN = 3+const RUN = transport.run/** Of each provision, the most a walker's basket holds. */-const BASKET = 10+const BASKET = transport.basket/** Walkers a service building may have out on the roads at once. */-const OUT = 2+const OUT = transport.active/** Every walker steps along its route (a firefighter on the way to a blaze runs); one whose next cell is no longer road is lost. */export const Walk = Game.System(@@ -83,9 +81,13 @@ export const SendWalkers = Game.System(inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] }),walkers: Game.Query({ selection: { roam: Game.Query.read(Roam), home: Game.Query.readRelation(WalkerOf) } })},- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) }+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources, commands }) => {+ ({ queries, resources, commands, services }) => {+ const rules = services.rules+ const { kinds, apprentice: APPRENTICE } = rules+const grid = resources.grid.get()const tick = resources.time.get().tickconst out = new Map<number, number>()@@ -168,9 +170,13 @@ export const Wander = Game.System(buildings: Game.Query({ selection: { tile: Game.Query.read(Tile) }, with: [Service] }),inventories: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Service] })},- resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), pantry: Game.System.writeResource(Pantry) }+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), pantry: Game.System.writeResource(Pantry) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources, commands }) => {+ ({ queries, resources, commands, services }) => {+ const rules = services.rules+ const { home, condition: wear, conditionMax: CONDITION_MAX } = rules+const grid = resources.grid.get()const random = Random.make(resources.rng.get())const walkers = queries.walkers.each()@@ -179,7 +185,6 @@ export const Wander = Game.System(for (const row of queries.homes.each()) homes.set(row.entity.id, row)const cared = new Map<number, ReturnType<typeof queries.cared.each>[number]>()for (const row of queries.cared.each()) cared.set(row.entity.id, row)- const low = (left: number, need: Need) => left < home.lasts[need] / 2let eaten = 0for (const { entity, data } of walkers) {@@ -217,21 +222,10 @@ export const Wander = Game.System(const h = { ...row.data.house.get() }if (roam.service === "faith") h.faith = home.lasts.faithelse if (roam.service === "goods") {- if ((low(h.food, "food") || (h.tier >= 2 && low(h.bread, "bread"))) && (basket.bread ?? 0) > 0) {- basket.bread = (basket.bread ?? 0) - 1- h.food = home.lasts.food- h.bread = home.lasts.bread- eaten += 1- } else if (low(h.food, "food") && ((basket.fish ?? 0) > 0 || (basket.smoked ?? 0) > 0)) {- const g = (basket.fish ?? 0) > 0 ? "fish" : "smoked"- basket[g] = (basket[g] ?? 0) - 1- h.food = home.lasts.food- eaten += 1- }- if (low(h.cloth, "cloth") && (basket.cloth ?? 0) > 0) {- basket.cloth = (basket.cloth ?? 0) - 1- h.cloth = home.lasts.cloth- }+ const served = serveGoods(h, amounts(basket), rules)+ Object.assign(h, served.house)+ Object.assign(basket, served.basket)+ eaten += served.eaten}row.data.house.set(h)}@@ -258,9 +252,7 @@ export const Wander = Game.System(const keepsGoing = roam.service === "goods" ? total(carrying) > 0 : roam.service === "repair" ? carrying.planks > 0 : trueif (left > 0 && keepsGoing) {const previous = route.cells.length >= 2 ? route.cells[route.cells.length - 2]! : null- const onward = DIRS- .map((d) => ({ x: cell.x + d.x, y: cell.y + d.y }))- .filter((c) => isRoad(grid, c.x, c.y) && !(previous && c.x === previous.x && c.y === previous.y))+ const onward = onwardRoads(grid, cell, previous)const next = random.pick(onward) ?? previousif (next) {data.route.set({ cells: [cell, next], index: 0, step: 0 })diff --git a/src/sim/work.ts b/src/sim/work.tsindex 7cf15be..f16eb58 100644--- a/src/sim/work.ts+++ b/src/sim/work.ts@@ -1,3 +1,4 @@+import { wildTreeSpots, canSeedTree } from "../rules/land.ts"/*** Building and working: the grid and the town's stock are indexed, sites* whose materials are in start going up, workers are assigned, recipes@@ -7,22 +8,13 @@import * as Random from "@typeonce/bevy-ts-math/Random"import { fieldDraft, treeDraft } from "../archetypes.ts"-import {- amounts, APPRENTICE, BUILD_TICKS, COMMUTE, condition, crewOf, goodIds, GROWN, kinds, ticks, total, winters, type Amounts, type Crew-} from "../content.ts"-import { around, DIRS, doors, GridBuilder, key, ownerAt, reach, roadPrint, useAt } from "../grid.ts"-import {- Building, Burning, Charter, Condition, Field, FieldOf, Game, Gatherer, Grid, House, Inventory, Land, Paused, Planter, Recipe, Rising, Rng,- Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Tree, maybe, type Status as StatusValue-} from "../schema.ts"+import { amounts, crewOf, goodIds, ticks, total, type Amounts, type Crew } from "../content.ts"+import { around, doors, GridBuilder, key, ownerAt, reach, roadPrint, useAt } from "../grid.ts"+import { Building, Burning, Charter, Condition, Field, FieldOf, Game, Rules, Gatherer, Grid, House, Inventory, Land, Paused, Planter, Recipe, Rising, Rng, Rock, Site, Staff, Status, Stock, Storage, Tile, Time, Tree, maybe, type Status as StatusValue } from "../schema.ts"import { connected, elapsed, seasonAt, TileRead, useOf } from "./shared.ts"-/**- * Whether a building working at `pace` (a share of full speed, a sum of- * halves and quarters) gets its step in on step `tick`: at a half, every- * other step; at a quarter, every fourth.- */-export const paced = (pace: number, tick: number): boolean => pace >= 1 || Math.floor((tick + 1) * pace) > Math.floor(tick * pace)+import { assignWorkers, equipmentPace, effort, paced } from "../rules/production.ts"+export { effort, paced } from "../rules/production.ts"/*** What stands where on the land, for every system after it this step.@@ -80,9 +72,13 @@ export const Raise = Game.System(queries: {sites: Game.Query({ selection: { site: Game.Query.read(Site) } }),rising: Game.Query({ selection: { rising: Game.Query.write(Rising), status: Game.Query.optional(Status) } })- }+ },+ services: { rules: Game.System.service(Rules) }},- ({ queries, commands }) => {+ ({ queries, commands, services }) => {+ const rules = services.rules+ const { buildTicks: BUILD_TICKS } = rules+for (const { entity, data } of queries.sites.each()) {if (total(data.site.get().owed) > 0) continuecommands.remove(entity.id, Site)@@ -130,19 +126,24 @@ export const AssignStaff = Game.System(without: [Site, Rising]})},- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) }+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources }) => {+ ({ queries, resources, services }) => {+ const rules = services.rules+ const { kinds, commute: COMMUTE, staffTicks: STAFF_TICKS } = rules+if (resources.time.get().tick % STAFF_TICKS !== 0) returnconst grid = resources.grid.get()- const homes: Array<{ readonly crew: Crew; left: number; readonly doors: ReadonlyArray<{ readonly x: number; readonly y: number }> }> = []- for (const { data } of queries.homes.each()) {+ const homes: Array<{ readonly id: number; readonly crew: Crew; left: number; readonly doors: ReadonlyArray<{ readonly x: number; readonly y: number }> }> = []+ for (const { entity, data } of queries.homes.each()) {const h = data.house.get()const ds = doors(grid, data.tile.get())- if (h.residents > 0 && ds.length > 0) homes.push({ crew: crewOf(h.tier), left: h.residents, doors: ds })+ if (h.residents > 0 && ds.length > 0) homes.push({ id: entity.id, crew: crewOf(h.tier), left: h.residents, doors: ds })}type Row = ReturnType<typeof queries.workplaces.each>[number]const places: Array<{+ readonly id: number;readonly data: Row["data"]readonly staff: { readonly needed: number; readonly assigned: number; readonly apprentices: number; readonly nearby: number }readonly crew: Crew@@ -151,7 +152,7 @@ export const AssignStaff = Game.System(apprentices: numberreadonly nearby: number}> = []- for (const { data } of queries.workplaces.each()) {+ for (const { entity, data } of queries.workplaces.each()) {const staff = data.staff.get()if (staff.needed === 0) continueconst crew = kinds[data.building.get().kind].crew@@ -170,31 +171,20 @@ export const AssignStaff = Game.System(within.sort((a, b) => a.distance - b.distance)}const nearby = within.reduce((n, w) => n + (w.home.crew === crew ? w.home.left : 0), 0)- places.push({ data, staff, crew, within, assigned: 0, apprentices: 0, nearby })- }- const fill = (place: (typeof places)[number], from: Crew) => {- for (const { home } of place.within) {- if (place.assigned >= place.staff.needed) return- if (home.crew !== from || home.left === 0) continue- const take = Math.min(place.staff.needed - place.assigned, home.left)- home.left -= take- place.assigned += take- if (from !== place.crew) place.apprentices += take- }+ places.push({ id: entity.id, data, staff, crew, within, assigned: 0, apprentices: 0, nearby })}- const order = places.map((place, index) => ({ place, index })).sort((a, b) => a.place.nearby - b.place.nearby || a.index - b.index)- for (const { place } of order) fill(place, place.crew)- for (const { place } of order) if (place.crew === "citizens") fill(place, "settlers")- for (const { data, staff, assigned, apprentices, nearby } of places) {- if (staff.assigned !== assigned || staff.apprentices !== apprentices || staff.nearby !== nearby) data.staff.set({ ...staff, assigned, apprentices, nearby })+ const assigned = assignWorkers(+ homes.map((h) => ({ id: h.id, crew: h.crew, residents: h.left })),+ places.map((p) => ({ id: p.id, crew: p.crew, needed: p.staff.needed,+ within: p.within.map((w) => ({ home: w.home.id, distance: w.distance })) }))+ )+ for (const { id, data, staff } of places) {+ const next = assigned.get(id)!+ if (staff.assigned !== next.assigned || staff.apprentices !== next.apprentices || staff.nearby !== next.nearby) data.staff.set({ ...staff, ...next })}})-/** Worker-steps a crew puts in this step: apprentices only on their share of the steps (see `APPRENTICE`). */-export const effort = (staff: { readonly assigned: number; readonly apprentices: number }, tick: number) =>- staff.assigned - staff.apprentices + (paced(APPRENTICE, tick) ? staff.apprentices : 0)-// ── Recipes ───────────────────────────────────────────────────────────────/**@@ -228,13 +218,17 @@ export const Work = Game.System(rocks: Game.Query({ selection: { rock: Game.Query.write(Rock) } }),fields: Game.Query({ selection: { field: Game.Query.write(Field) } })},- resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) }+ resources: { grid: Game.System.readResource(Grid), time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources, commands }) => {+ ({ queries, resources, commands, services }) => {+ const rules = services.rules+ const { kinds, winters, grown: GROWN } = rules+const grid = resources.grid.get()const tick = resources.time.get().tickconst t = elapsed(resources.time.get(), resources.charter.get())- const season = seasonAt(t, resources.charter.get())+ const season = seasonAt(t, resources.charter.get(), rules)const fishing = season.severity ? winters[season.severity].fishing : 1// The land by entity, looked up only once some gatherer starts a job this step.const lazy = <T>(make: () => T) => {@@ -302,9 +296,9 @@ export const Work = Game.System(recipe = { ...recipe, progress: 1 }}}- const worn = (maybe(data.condition)?.value ?? Infinity) < condition.worn- const pace = (kind.wear && stock.tools === 0 ? 0.5 : 1) * (worn ? 0.5 : 1) * (gatherer?.source === "water" ? fishing : 1)- const put = effort(staff, tick)++ const pace = equipmentPace(kind, stock.tools, maybe(data.condition)?.value ?? Infinity, fishing, rules)+ const put = effort(staff, tick, rules)if (open && recipe.progress > 0 && put > 0 && paced(pace, tick)) {const progress = recipe.progress + putif (progress > recipe.period * staff.needed) {@@ -353,9 +347,13 @@ export const Plant = Game.System(without: [Site, Rising]})},- resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) }+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources, commands }) => {+ ({ queries, resources, commands, services }) => {+ const rules = services.rules+ const { staffTicks: STAFF_TICKS } = rules+const grid = resources.grid.get()const random = Random.make(resources.rng.get())const sown = new Set<number>()@@ -393,9 +391,6 @@ export const Plant = Game.System(})-/** How often a wild forest seeds a new tree. */-const SPREAD_TICKS = ticks(1.5)-/*** Wild forests regrow: now and then a grown tree seeds an empty cell beside* it, but only one that already has two trees around it, so forests fill@@ -406,9 +401,13 @@ export const Spread = Game.System("Town/Spread",{queries: { trees: Game.Query({ selection: { tile: Game.Query.read(Tile), tree: Game.Query.read(Tree) } }) },- resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) }+ resources: { grid: Game.System.readResource(Grid), rng: Game.System.writeResource(Rng), time: Game.System.readResource(Time) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources, commands }) => {+ ({ queries, resources, commands, services }) => {+ const rules = services.rules+ const { grown: GROWN, spreadTicks: SPREAD_TICKS } = rules+if (resources.time.get().tick % SPREAD_TICKS !== 0) returnconst grid = resources.grid.get()const random = Random.make(resources.rng.get())@@ -416,16 +415,13 @@ export const Spread = Game.System(const parent = random.pick(grown)if (parent) {const t = parent.data.tile.get()- const spot = random.pick(DIRS.map((d) => ({ x: t.x + d.x, y: t.y + d.y })).filter((c) => useAt(grid, c.x, c.y) === "empty"))- if (spot && DIRS.filter((d) => useAt(grid, spot.x + d.x, spot.y + d.y) === "tree").length >= 2) commands.spawn(treeDraft(spot, 0))+ const spot = random.pick(wildTreeSpots(grid, t))+ if (spot && canSeedTree(grid, spot)) commands.spawn(treeDraft(spot, 0))}resources.rng.set(random.state)})-/** Trees and fields grow this many steps at a time. */-const GROW_TICKS = 10-/** Trees and fields grow until they are ready; fields not in winter. */export const Grow = Game.System("Town/Grow",@@ -434,15 +430,19 @@ export const Grow = Game.System(trees: Game.Query({ selection: { tree: Game.Query.write(Tree) } }),fields: Game.Query({ selection: { field: Game.Query.write(Field) } })},- resources: { time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) }+ resources: { time: Game.System.readResource(Time), charter: Game.System.readResource(Charter) },+ services: { rules: Game.System.service(Rules) }},- ({ queries, resources }) => {+ ({ queries, resources, services }) => {+ const rules = services.rules+ const { grown: GROWN, growTicks: GROW_TICKS } = rules+if (resources.time.get().tick % GROW_TICKS !== 0) returnfor (const { data } of queries.trees.each()) {const growth = data.tree.get().growthif (growth < GROWN.tree) data.tree.set({ growth: Math.min(GROWN.tree, growth + GROW_TICKS) })}- if (seasonAt(elapsed(resources.time.get(), resources.charter.get()), resources.charter.get()).winter) return+ if (seasonAt(elapsed(resources.time.get(), resources.charter.get()), resources.charter.get(), rules).winter) returnfor (const { data } of queries.fields.each()) {const growth = data.field.get().growthif (growth < GROWN.field) data.field.set({ growth: Math.min(GROWN.field, growth + GROW_TICKS) })diff --git a/test/balance-model.test.ts b/test/balance-model.test.tsnew file mode 100644index 0000000..a389dd3--- /dev/null+++ b/test/balance-model.test.ts@@ -0,0 +1,128 @@+import assert from "node:assert/strict"+import { test } from "node:test"+import { readFileSync, readdirSync, mkdtempSync, rmSync } from "node:fs"+import { join } from "node:path"+import { tmpdir } from "node:os"+import { spawnSync } from "node:child_process"+import { createHash } from "node:crypto"+import { amounts, kinds } from "../src/content.ts"+import { resolveRules } from "../src/rules/config.ts"+import { analyze } from "../tools/balance/model/analyze.ts"+import { project } from "../tools/balance/model/project.ts"+import { searchParameters, searchDistricts } from "../tools/balance/model/search.ts"+import { citizensDistrict, buildScenario } from "../tools/balance/catalog.ts"+import { district, validateScenario } from "../tools/balance/scenario.ts"+import { verify, verifyProduction } from "../tools/balance/verify/checks.ts"+import { verifyBuilds } from "../tools/balance/verify/builds.ts"+import { provenance } from "../tools/balance/provenance.ts"+import { assessTransfers } from "../tools/balance/model/transport.ts"+import { fixture } from "../tools/balance/verify/fixture.ts"++test("candidate rules are immutable, isolated and also executed by the game", () => {+ const base = resolveRules(), original = kinds.weaver.recipe!.seconds+ const candidate = resolveRules([{ path: "kinds.weaver.recipe.seconds", value: 12 }])+ assert.equal(base.kinds.weaver.recipe!.seconds, original)+ assert.equal(kinds.weaver.recipe!.seconds, original)+ assert(Object.isFrozen(candidate.kinds.weaver.recipe))+ assert.throws(() => resolveRules([{ path: "kinds.fishery.size", value: 1 }]), /Structural/)+ assert.throws(() => resolveRules([{ path: "__proto__.polluted", value: 1 }]), /Invalid/)+ const result = verifyProduction(candidate, "weaver", false, true)+ assert(result.pass, JSON.stringify(result))+ assert.equal(result.expected, 5)+ assert.equal(kinds.weaver.recipe!.seconds, original)+})++test("the mathematical layer has no runtime or rendering value imports", () => {+ const paths = [...readdirSync("tools/balance/model").filter((f) => f.endsWith(".ts")).map((f) => `tools/balance/model/${f}`),+ ...readdirSync("src/rules").filter((f) => f.endsWith(".ts")).map((f) => `src/rules/${f}`), "tools/balance/scenario.ts"]+ for (const path of paths) {+ const text = readFileSync(path, "utf8").replace(/^import type [\s\S]*?from [^\n]+\n/gm, "")+ assert(!/import[^\n]*from ["'][^"']*(?:sim\/|schema\.ts|render3d|bevy-ts)[^"']*["']/.test(text), path)+ }+})++test("paused upkeep candidates are shared with the actual ledger", () => {+ const rules = resolveRules([{ path: "pausedUpkeep", value: 0.5 }])+ const base = district("paused-ledger", Array(4).fill(1), ["warehouse", "warehouse", "warehouse"])+ const scenario = { ...base, homes: base.homes.map((h) => ({ ...h, food: 10000000 })), buildings: base.buildings.map((b) => ({ ...b, stock: amounts({}), paused: b.kind !== "townhall" })) }+ const expected = analyze({ rules, scenario }, { services: false }).economy.roundedNetPerMinute+ const town = fixture(scenario, rules), before = town.snapshot().resources["Town/Treasury"].coins+ town.run(60)+ assert.equal(town.snapshot().resources["Town/Treasury"].coins - before, expected)+ assert.notEqual(expected, analyze({ rules: resolveRules(), scenario }, { services: false }).economy.roundedNetPerMinute)+})++test("desirability rejects an industrial citizen plan even with sufficient goods", () => {+ const rules = resolveRules(), industrial = analyze({ rules, scenario: citizensDistrict(rules, false) }), zoned = analyze({ rules, scenario: citizensDistrict(rules, true) })+ assert.equal(industrial.household.filter((h) => h.potentialTier >= 2).length, 0)+ assert(zoned.household.filter((h) => h.potentialTier >= 2).length > 0)+ assert(industrial.findings.some((f) => f.code === "appeal-blocks-citizens"))+})++test("isolated workplaces and citizen-only raw industry cannot borrow global workers", () => {+ const rules = resolveRules(), s = district("unreachable", [2, 2], ["fishery"])+ const a = analyze({ rules, scenario: s }, { services: false })+ assert.equal(a.recipes[0]!.staff.assigned, 0)+ const distant = { ...s, homes: s.homes.map((h) => ({ ...h, tier: 1 as const, residents: 4, tile: { ...h.tile, x: h.tile.x + 30 } })) }+ assert.equal(analyze({ rules, scenario: distant }, { services: false }).recipes[0]!.staff.assigned, 0)+})++test("finite raw-resource forecasts conserve material and never create negative goods", () => {+ const rules = resolveRules(), base = district("finite-quarry", Array(4).fill(1), ["quarry"]), q = base.buildings.find((b) => b.kind === "quarry")!+ const scenario = { ...base, land: [{ tile: { x: q.tile.x, y: q.tile.y + 2, size: 1 }, type: "stone" as const, amount: 2, growth: 0 }] }+ const result = project({ rules, scenario }, { seconds: 180 })+ assert(result.rows.at(-1)!.stock.stone <= rules.lands.fair.stock.stone + 2 + 1e-8)+ for (const row of result.rows) for (const count of Object.values(row.stock)) assert(count >= -1e-8)+})++test("invalid overlapping geometry is rejected before making mathematical claims", () => {+ const rules = resolveRules(), scenario = citizensDistrict(rules)+ assert.throws(() => validateScenario({ ...scenario, homes: scenario.homes.map((h, i) => i === 1 ? { ...h, tile: scenario.homes[0]!.tile } : h) }, rules), /overlapping/)+})++test("different goods share a storage's carrier time, and construction has dispatch priority", () => {+ const rules = resolveRules(), scenario = district("shared-pool", [1, 1], ["warehouse", "mill"])+ const hall = scenario.buildings[0]!, warehouse = scenario.buildings.find((b) => b.kind === "warehouse")!, mill = scenario.buildings.find((b) => b.kind === "mill")!+ const budget = assessTransfers({ rules, scenario }, [{ source: hall.id, target: mill.id, good: "wheat", goodsPerMinute: 100 }, { source: hall.id, target: warehouse.id, good: "stone", goodsPerMinute: 100, construction: true }])+ assert.equal(budget.pools.length, 1)+ assert.equal(budget.dispatchPriority[0]!.good, "stone")+ assert.equal(budget.pools[0]!.requiredCarrierSeconds, budget.routes.reduce((n, r) => n + r.carrierSecondsPerMinute!, 0))+})++test("steady-state search counts working tools separately and leaves shipped parameters untouched", () => {+ const rules = resolveRules(), result = searchDistricts(rules, 8)+ assert.equal(result.length, 27)+ assert.equal(result[0]!.cost, 870)+ assert.equal(result[0]!.materials.tools, 9)+ assert.equal(result[0]!.affordableAtFoundation, false)+ const score = (a: ReturnType<typeof analyze>) => a.availableAfterWorkshops.cloth+ const candidates = searchParameters({ rules, scenario: citizensDistrict(rules) }, [[{ path: "kinds.weaver.recipe.seconds", value: 12 }], []], score)+ assert.deepEqual(candidates[0]!.patches, [])+ assert.equal(provenance(rules, []).parametersChanged, false)+})++test("controlled production, ledger and stochastic service comparisons pass", () => {+ const comparisons = verify(resolveRules(), 12)+ for (const c of comparisons) assert(c.pass, JSON.stringify(c))+})++test("the mathematical plan reaches citizens through ordinary game construction", () => {+ const rules = resolveRules(), { scenario, builds } = buildScenario(rules)+ const r = verifyBuilds({ rules, scenario }, builds)+ assert.deepEqual(r.messages, [])+ assert.equal(r.actual.at(-1)!.citizens, 32)+ assert.equal(r.firstCitizenSecond, 336)+ assert.equal(r.prediction.rows.at(-1)!.citizens, 32)+ assert(r.prediction.assumptions.length > 0)+ assert.equal(r.errors.length, r.actual.length)+})++test("shared-rule extraction preserves the original PR's complete minute-30 world", { timeout: 90000 }, () => {+ const out = mkdtempSync(join(tmpdir(), "inkline-rule-parity-"))+ try {+ const child = spawnSync(process.execPath, ["scripts/balance.ts", "--seeds", "1", "--term", "60", "--snapshot", "30", "--out", out], { encoding: "utf8", timeout: 80000 })+ assert.equal(child.status, 0, child.stderr)+ const world = JSON.parse(readFileSync(join(out, "medium-fair-1000-30min.json"), "utf8")).world+ assert.equal(createHash("sha256").update(JSON.stringify(world)).digest("hex"), "e759806fa37003f6215db219c3a784332afc2fc5c44d22845b71dc0fcdd78f87")+ } finally { rmSync(out, { recursive: true, force: true }) }+})diff --git a/tools/balance/catalog.ts b/tools/balance/catalog.tsnew file mode 100644index 0000000..79c1f5f--- /dev/null+++ b/tools/balance/catalog.ts@@ -0,0 +1,28 @@+import { amounts, type KindId } from "../../src/content.ts"+import type { Rules } from "../../src/rules/config.ts"+import { district } from "./scenario.ts"+import type { BuildAction, Scenario } from "./types.ts"++export const citizensDistrict = (rules: Rules, gardens = true): Scenario => {+ const s = district(gardens ? "zoned-citizens" : "industrial-citizens", Array(12).fill(1), ["farm", "mill", "bakery", "sheep", "weaver", "market", "chapel"], false, rules)+ return gardens ? { ...s, buildings: [...s.buildings, ...s.homes.slice(0, 4).map((h, i) => ({ id: 300 + i, kind: "garden" as const,+ tile: { x: h.tile.x, y: h.tile.y - 1, size: 1 }, condition: rules.conditionMax, site: false, paused: false, stock: amounts({}) }))] } : s+}++/** Authored flat-land starting district. Roads/homes are charged; it is not a generated-map or human-win claim. */+export const buildScenario = (rules: Rules) => {+ const kinds: KindId[] = ["farm", "mill", "bakery", "sheep", "weaver", "market", "chapel", "lumberjack", "sawmill", "quarry", "fishery"]+ const template = district("authored-bootstrap", Array(12).fill(1), kinds, false, rules)+ const hall = template.buildings.find((b) => b.kind === "townhall")!+ const initial = { ...rules.lands.fair.stock, planks: rules.lands.fair.stock.planks - template.homes.length }+ const land: Scenario["land"][number][] = [...template.land.filter((l) => l.type === "water")]+ const lumber = template.buildings.find((b) => b.kind === "lumberjack")!, quarry = template.buildings.find((b) => b.kind === "quarry")!+ for (let x = lumber.tile.x - 3; x < lumber.tile.x + 3; x++) for (let y = 35; y < 39; y++) land.push({ tile: { x, y, size: 1 }, type: "tree", amount: 1, growth: rules.grown.tree })+ for (let x = quarry.tile.x; x < quarry.tile.x + 2; x++) land.push({ tile: { x, y: 34, size: 1 }, type: "stone", amount: rules.lands.fair.rock, growth: 0 })+ const scenario: Scenario = { ...template, land, name: "authored-bootstrap", coins: rules.lands.fair.coins - template.homes.length * rules.home.cost.coins - template.roads.length * rules.roadCost,+ buildings: [{ ...hall, stock: initial }], trade: { buys: ["tools"], sells: [], reserve: 10 } }+ const order: ReadonlyArray<readonly [KindId, number]> = [["sawmill", 0], ["lumberjack", 0], ["fishery", 0], ["quarry", 30], ["mill", 60], ["bakery", 90], ["farm", 120], ["sheep", 150], ["weaver", 180], ["market", 210], ["chapel", 240]]+ const builds: BuildAction[] = order.map(([kind, at]) => ({ kind, at, tile: template.buildings.find((b) => b.kind === kind)!.tile }))+ for (const h of scenario.homes.slice(0, 4)) builds.push({ kind: "garden", at: 0, tile: { x: h.tile.x, y: h.tile.y - 1, size: 1 } })+ return { scenario, builds }+}diff --git a/tools/balance/cli.ts b/tools/balance/cli.tsnew file mode 100644index 0000000..a632c32--- /dev/null+++ b/tools/balance/cli.ts@@ -0,0 +1,61 @@+import { mkdirSync, readFileSync, writeFileSync } from "node:fs"+import { resolve } from "node:path"+import { resolveRules, type RulePatch } from "../../src/rules/config.ts"+import { analyze } from "./model/analyze.ts"+import { project } from "./model/project.ts"+import { searchDistricts, searchParameters } from "./model/search.ts"+import { buildScenario, citizensDistrict } from "./catalog.ts"+import { fromSnapshot } from "./scenario.ts"+import { makeReport, markdownReport, htmlReport } from "./report.ts"+import type { Scenario } from "./types.ts"++const args = process.argv.slice(2), command = args[0] ?? "report"+const option = (name: string, fallback?: string) => { const at = args.indexOf(`--${name}`); if (at < 0) return fallback; if (args[at + 1] === undefined || args[at + 1]!.startsWith("--")) throw new Error(`Missing --${name} value`); return args[at + 1]! }+const number = (name: string, fallback: number) => { const n = Number(option(name, String(fallback))); if (!Number.isFinite(n) || n <= 0) throw new Error(`Invalid --${name}`); return n }+const rules = resolveRules()+const snapshot = option("snapshot")+const load = (): Scenario => {+ if (snapshot) { const save = JSON.parse(readFileSync(snapshot, "utf8")); return fromSnapshot(save.world ?? save, "pr3-bot-minute-30") }+ const name = option("scenario", "zoned")+ if (name === "bootstrap") return buildScenario(rules).scenario+ if (name === "industrial" || name === "zoned") return citizensDistrict(rules, name === "zoned")+ throw new Error(`Unknown scenario: ${name}`)+}+try {+ if (command === "help" || args.includes("--help")) {+ console.log(`Offline balance model\n\n pnpm balance:model analyze [--scenario zoned|industrial|bootstrap] [--snapshot save.json] [--minutes 10]\n pnpm balance:model project --scenario bootstrap [--seconds 600]\n pnpm balance:model search [--homes 8]\n pnpm balance:model sweep --path kinds.weaver.recipe.seconds --values 4,8,12\n pnpm balance:model verify [--seeds 16]\n pnpm balance:model report [--snapshot save.json] [--seeds 32] [--out output/balance-model]\n\nAll commands read shared game rules. Search varies district configurations. Sweep creates immutable hypothetical rules and never writes them to content. Report always uses unchanged shipped parameters.`)+ } else if (command === "analyze") {+ const winter = option("winter")+ if (winter && !["mild", "normal", "hard", "summer"].includes(winter)) throw new Error("Unknown winter")+ console.log(JSON.stringify(analyze({ rules, scenario: load() }, { minutes: number("minutes", 10), ...(winter ? { severity: winter === "summer" ? null : winter as "mild" | "normal" | "hard" } : {}) }), null, 2))+ } else if (command === "project") {+ const s = load(), build = buildScenario(rules)+ console.log(JSON.stringify(project({ rules, scenario: s }, { seconds: number("seconds", 600), ...(s.name === "authored-bootstrap" ? { builds: build.builds } : {}) }), null, 2))+ } else if (command === "search") {+ console.log(JSON.stringify(searchDistricts(rules, number("homes", 8)), null, 2))+ } else if (command === "sweep") {+ const path = option("path"), values = option("values")+ if (!path || !values) throw new Error("Sweep requires --path and --values")+ const candidates: RulePatch[][] = values.split(",").map((value) => [{ path, value: Number(value) }])+ const result = searchParameters({ rules, scenario: load() }, candidates, (a) => a.availableAfterWorkshops.cloth).map(({ patches, analysis, score }) => ({ patches, score, findings: analysis.findings }))+ console.log(JSON.stringify({ hypothetical: true, gameParametersWritten: false, result }, null, 2))+ } else if (command === "verify" || command === "report") {+ const seeds = number("seeds", command === "report" ? 32 : 16)+ if (!Number.isInteger(seeds)) throw new Error("Seeds must be an integer")+ const { verify } = await import("./verify/checks.ts"), { verifyBuilds } = await import("./verify/builds.ts")+ const checks = verify(rules, seeds), { scenario, builds } = buildScenario(rules), construction = verifyBuilds({ rules, scenario }, builds)+ const report = makeReport(rules, checks, construction, snapshot ? load() : undefined)+ const passed = checks.every((c) => c.pass) && construction.firstCitizenSecond !== null && construction.messages.length === 0+ if (command === "verify") console.log(JSON.stringify({ passed, checks, construction: { firstCitizenSecond: construction.firstCitizenSecond, final: construction.actual.at(-1), forecastFirstCitizenSecond: construction.prediction.firstCitizenSecond, errors: construction.errors } }, null, 2))+ else {+ const out = resolve(option("out", "output/balance-model")!)+ mkdirSync(out, { recursive: true })+ writeFileSync(resolve(out, "results.json"), JSON.stringify(report, null, 2) + "\n")+ writeFileSync(resolve(out, "results.md"), markdownReport(report))+ writeFileSync(resolve(out, "results.html"), htmlReport(report))+ console.log(JSON.stringify({ passed, out, rulesSha256: report.provenance.rulesSha256, parametersChanged: report.provenance.parametersChanged,+ analysisElapsedMs: report.analysisElapsedMs, checks: checks.length, firstCitizenSecond: construction.firstCitizenSecond, real: construction.actual.at(-1), predicted: construction.prediction.rows.at(-1) }, null, 2))+ }+ if (!passed) process.exitCode = 1+ } else throw new Error(`Unknown command: ${command}`)+} catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1 }diff --git a/tools/balance/index.ts b/tools/balance/index.tsnew file mode 100644index 0000000..3139e5b--- /dev/null+++ b/tools/balance/index.ts@@ -0,0 +1,9 @@+/** Public offline API. Runtime verification is a separate import under ./verify/. */+export { analyze, type Analysis, type AnalysisOptions } from "./model/analyze.ts"+export { project } from "./model/project.ts"+export { assessTransfers, type Transfer } from "./model/transport.ts"+export { recipeCapacity } from "./model/throughput.ts"+export { serviceProfile, missProbability } from "./model/services.ts"+export { searchParameters, searchDistricts } from "./model/search.ts"+export { fromSnapshot, scenarioGrid, validateScenario, district } from "./scenario.ts"+export type { Scenario, Inputs, Finding, Confidence, BuildAction, ProjectionOptions } from "./types.ts"diff --git a/tools/balance/model/analyze.ts b/tools/balance/model/analyze.tsnew file mode 100644index 0000000..6779aff--- /dev/null+++ b/tools/balance/model/analyze.ts@@ -0,0 +1,148 @@+import { amounts, goodIds, type GoodId, type WinterId } from "../../../src/content.ts"+import { appealAt, appealGrid, buildingSource, landSource } from "../../../src/appeal.ts"+import { doors, nearest, reach } from "../../../src/grid.ts"+import { assignWorkers, type Assignment } from "../../../src/rules/production.ts"+import { baseCollection, taxOf, tierFor } from "../../../src/rules/households.ts"+import { riskIncrements, near } from "../../../src/rules/risks.ts"+import { seasonAt } from "../../../src/rules/seasons.ts"+import { spoilExpectation } from "../../../src/rules/decay.ts"+import { goalsOf } from "../../../src/rules/goals.ts"+import { scenarioGrid, validateScenario } from "../scenario.ts"+import { recipeCapacity, sourceCeiling } from "./throughput.ts"+import { missProbability, serviceProfile } from "./services.ts"+import type { Inputs, Finding } from "../types.ts"++export interface AnalysisOptions { readonly minutes?: number; readonly severity?: WinterId | null; readonly services?: boolean }+export const analyze = ({ rules, scenario: s }: Inputs, options: AnalysisOptions = {}) => {+ validateScenario(s, rules)+ const started = performance.now(), grid = scenarioGrid(s, rules), g = grid.value(), minutes = options.minutes ?? 10+ if (!Number.isFinite(minutes) || minutes <= 0) throw new Error("Analysis horizon must be positive and finite")+ const severity = options.severity === undefined ? seasonAt(s.tick, s.charter, rules).severity : options.severity+ const homes = s.homes.map((h) => ({ id: h.id, crew: h.tier === 1 ? "settlers" as const : "citizens" as const, residents: h.residents }))+ const workplaces = s.buildings.filter((b) => !b.site).map((b) => {+ const starts = doors(g, b.tile), roads = reach(g, starts), kind = rules.kinds[b.kind]+ return { id: b.id, crew: kind.crew, needed: kind.workers,+ within: b.paused ? [] : s.homes.flatMap((h) => {+ const found = nearest(roads, doors(g, h.tile))+ return found && found.distance <= rules.commute ? [{ home: h.id, distance: found.distance }] : []+ }) }+ })+ const staff = assignWorkers(homes, workplaces)+ const zero: Assignment = { assigned: 0, apprentices: 0, nearby: 0 }+ const sources = s.buildings.filter((b) => !b.site).flatMap((b) => { const a = buildingSource(b.kind, b.tile, rules); return a ? [a] : [] })+ for (const l of s.land) if (l.type === "water" || l.type === "tree") sources.push(landSource(l.type === "tree" ? "forest" : "water", l.tile, rules))+ for (const r of s.roads) if (r.paved) sources.push(landSource("paved", r, rules))+ for (const r of s.ruins ?? []) sources.push(landSource("ruin", r, rules))+ for (const h of s.homes) if (h.condition < rules.condition.worn) sources.push(landSource("worn", h.tile, rules))+ const appeal = appealGrid(sources, rules), findings: Finding[] = []+ const recipes = s.buildings.filter((b) => !b.site && !b.paused && rules.kinds[b.kind].recipe).map((b) => {+ const kind = rules.kinds[b.kind], crew = staff.get(b.id) ?? zero+ const capacity = doors(g, b.tile).length === 0 ? recipeCapacity(kind, zero, 0, 0, severity, rules) : recipeCapacity(kind, crew, b.stock.tools, b.condition, severity, rules)+ const source = sourceCeiling(b, s, grid, severity, minutes, rules)+ const cap = Math.min(capacity.outputPerMinute, source * kind.recipe!.batch)+ if (crew.assigned < kind.workers) findings.push({ code: "staff-shortage", confidence: "exact", detail: `${b.kind} #${b.id}: ${crew.assigned}/${kind.workers} workers within ${rules.commute} road cells` })+ if (crew.apprentices > 0) findings.push({ code: "apprentices", confidence: "exact", detail: `${b.kind} #${b.id}: ${crew.apprentices} apprentices; cadence-aware capacity ${cap.toFixed(2)} ${kind.recipe!.output}/min` })+ if (kind.wear && b.stock.tools === 0) findings.push({ code: "no-tools", confidence: "exact", detail: `${b.kind} #${b.id} lacks its working tool` })+ if (source === 0) findings.push({ code: "source-unavailable", confidence: "upper-bound", detail: `${b.kind} #${b.id}: no accessible ${kind.gathers!.source} supply during this horizon` })+ return { id: b.id, kind: b.kind, staff: crew, capacity, sourceCeiling: source === Infinity ? null : source, outputCeiling: cap }+ })+ // A steady-state relaxation: throttle recipes against upstream resource budgets. The placement cuts below are necessary conditions, not an optimal dispatcher.+ const supply = { ...amounts({}) }, inputs = { ...amounts({}) }+ const rates = new Map(recipes.map((r) => [r.id, r.outputCeiling]))+ for (let iteration = 0; iteration < 64; iteration++) {+ for (const g of goodIds) { supply[g] = s.imports?.[g] ?? 0; inputs[g] = 0 }+ for (const row of recipes) {+ const recipe = rules.kinds[row.kind].recipe!, rate = rates.get(row.id)!+ supply[recipe.output] += rate+ if (recipe.input) inputs[recipe.input] += rate * recipe.inputs / recipe.batch+ }+ let changed = false+ for (const row of recipes) {+ const recipe = rules.kinds[row.kind].recipe!, rate = rates.get(row.id)!+ if (recipe.input && inputs[recipe.input] > supply[recipe.input] + 1e-8) {+ rates.set(row.id, rate * supply[recipe.input] / inputs[recipe.input]); changed = true+ }+ }+ if (!changed) break+ }+ for (const g of goodIds) { supply[g] = s.imports?.[g] ?? 0; inputs[g] = s.exports?.[g] ?? 0 }+ for (const row of recipes) {+ const r = rules.kinds[row.kind].recipe!, rate = rates.get(row.id)!+ supply[r.output] += rate+ if (r.input) inputs[r.input] += rate * r.inputs / r.batch+ if (rules.kinds[row.kind].wear) inputs.tools += rate / r.batch / rules.kinds[row.kind].wear!+ }+ const storage = s.buildings.filter((b) => !b.site && (rules.kinds[b.kind].holds?.accepts === "all" || rules.kinds[b.kind].keeps))+ const toolWorkplaces = s.buildings.filter((b) => !b.site && !b.paused && rules.kinds[b.kind].wear)+ const workingTools = toolWorkplaces.filter((b) => b.stock.tools > 0).length+ const heldTools = s.buildings.reduce((n, b) => n + b.stock.tools, 0)+ if (heldTools < toolWorkplaces.length) findings.push({ code: "working-tool-capital", confidence: "exact", detail: `${toolWorkplaces.length} wearing workplaces need ${toolWorkplaces.length} working tools; only ${heldTools} tools are held across all buildings` })+ const spoil = { ...amounts({}) }+ for (const b of s.buildings.filter((b) => !b.site)) for (const g of goodIds) spoil[g] += spoilExpectation(b.stock[g], g, rules.kinds[b.kind].keeps ?? 1, rules) * 60 / (rules.spoilTicks * rules.stepSeconds)+ const foodDecay = severity === null ? 1 : 1.5+ const needBounds = {+ food: { min: s.homes.length * foodDecay * 60 / (rules.home.lasts.food * rules.stepSeconds), frequent: s.homes.length * foodDecay * 120 / (rules.home.lasts.food * rules.stepSeconds) },+ cloth: { min: s.homes.length * 60 / (rules.home.lasts.cloth * rules.stepSeconds), frequent: s.homes.length * 120 / (rules.home.lasts.cloth * rules.stepSeconds) },+ citizenCloth: { min: s.homes.filter((h) => h.tier >= 2).length * 60 / (rules.home.lasts.cloth * rules.stepSeconds), frequent: s.homes.filter((h) => h.tier >= 2).length * 120 / (rules.home.lasts.cloth * rules.stepSeconds) }+ }+ const net = Object.fromEntries(goodIds.map((g) => [g, supply[g] - inputs[g] - spoil[g]])) as Record<GoodId, number>+ const foodCeiling = supply.fish + supply.smoked + supply.bread - inputs.fish - inputs.smoked - inputs.bread+ if (foodCeiling < needBounds.food.min) findings.push({ code: "food-impossible", confidence: "upper-bound", detail: `Even pooled food capacity ${foodCeiling.toFixed(2)}/min before spoilage is below the no-waste minimum ${needBounds.food.min.toFixed(2)}/min; existing reserves may bridge a finite interval` })+ if (net.cloth < needBounds.cloth.min) findings.push({ code: "cloth-spread", confidence: "upper-bound", detail: `Cloth capacity ${net.cloth.toFixed(2)}/min cannot keep ${s.homes.length} homes supplied; settlers also accept cloth` })+ const hall = s.buildings.find((b) => b.kind === "townhall"), hallRoads = hall ? reach(g, doors(g, hall.tile)) : null+ const taxes = s.homes.reduce((sum, h) => sum + (hallRoads && nearest(hallRoads, doors(g, h.tile)) ? taxOf(h, s.policy, rules) : 0), 0)+ const upkeep = s.buildings.filter((b) => !b.site).reduce((sum, b) => sum + rules.kinds[b.kind].upkeep * (b.paused ? rules.pausedUpkeep : 1), 0)+ const collection = baseCollection(taxes, upkeep, s.homes.length, rules), cashPerMinute = collection.delta * 60 / (rules.ledgerTicks * rules.stepSeconds)+ const profiles = options.services === false ? [] : s.buildings.flatMap((b) => { const p = serviceProfile(s, b, staff.get(b.id) ?? zero, rules); return p ? [p] : [] })+ const household = s.homes.map((h) => {+ const desirable = appealAt(appeal, h.tile.x, h.tile.y)+ const increments = riskIncrements({ tile: h.tile, house: h, condition: h.condition, desirability: desirable, approval: s.approval,+ heating: severity !== null && rules.winters[severity].heating,+ hotNearby: s.buildings.filter((b) => !b.site && rules.kinds[b.kind].hot && near(b.tile, h.tile, rules.risk.fire.reach)).length,+ dusty: s.buildings.some((b) => !b.site && rules.kinds[b.kind].dusty && near(b.tile, h.tile, rules.risk.health.reach)),+ water: s.land.some((l) => l.type === "water" && Math.abs(l.tile.x - h.tile.x) <= 2 && Math.abs(l.tile.y - h.tile.y) <= 2)+ }, rules)+ const deadline = (service: "fire" | "health" | "order") => service === "health" && h.sick ? null : increments[service] > 0 ? Math.ceil((rules.riskMax - h.meters[service]) / increments[service]) : null+ const eligible = tierFor({ ...h, bread: 1, cloth: 1, faith: 1 }, desirable, h.meters, rules)+ if (h.tier === 1 && eligible === 1) findings.push({ code: "appeal-blocks-citizens", confidence: "exact", detail: `Home #${h.id}: desirability ${desirable} below ${rules.home.tiers[2].appeal}, even with bread, cloth and faith` })+ const goods = profiles.filter((p) => p.service === "goods"), faith = profiles.filter((p) => p.service === "faith")+ return { id: h.id, desirability: desirable, potentialTier: eligible, increments,+ roadConnected: doors(g, h.tile).length > 0, taxConnected: hallRoads !== null && nearest(hallRoads, doors(g, h.tile)) !== null,+ foodMissEstimate: missProbability(goods, h.id, rules.home.lasts.food * rules.stepSeconds / foodDecay),+ faithMissEstimate: missProbability(faith, h.id, rules.home.lasts.faith * rules.stepSeconds),+ unvisitedDisasterSeconds: { fire: deadline("fire"), health: deadline("health"), order: deadline("order") } }+ })+ const citizenHousingCeiling = household.reduce((n, h) => n + (h.desirability >= rules.home.tiers[3].appeal ? rules.home.tiers[3].residents : h.desirability >= rules.home.tiers[2].appeal ? rules.home.tiers[2].residents : 0), 0)+ const requiredCitizensAtPopulationGoal = rules.sizes[s.charter.size].goal.residents * rules.fate.citizens+ if (citizenHousingCeiling < requiredCitizensAtPopulationGoal) findings.push({ code: "citizen-goal-housing-cut", confidence: "upper-bound", detail: `With this frozen neighbourhood even fully supplied citizen/burgher homes hold at most ${citizenHousingCeiling} citizens; the population goal requires at least ${requiredCitizensAtPopulationGoal}` })+ // Carrier time is shared across goods, not a separate full capacity for every commodity.+ const transport = s.buildings.filter((b) => !b.site && !b.paused && rules.kinds[b.kind].carriers).map((b) => {+ const kind = rules.kinds[b.kind], roads = reach(g, doors(g, b.tile)), row = recipes.find((r) => r.id === b.id)+ const destinations = s.buildings.filter((d) => d.id !== b.id && !d.site).flatMap((d) => {+ const found = nearest(roads, doors(g, d.tile)); if (!found) return []+ const target = rules.kinds[d.kind]+ if (row && !(target.recipe?.input === kind.recipe?.output || target.holds?.accepts === "all" || target.holds?.accepts.includes(kind.recipe!.output))) return []+ return [{ id: d.id, kind: d.kind, distance: found.distance }]+ }).sort((a, b) => a.distance - b.distance)+ const nearestTarget = destinations[0]+ const capacity = nearestTarget ? kind.carriers! * rules.transport.load * 60 / Math.max(rules.transport.dispatchTicks * rules.stepSeconds, 2 * nearestTarget.distance * rules.transport.cellSteps * rules.stepSeconds / rules.transport.walk) : 0+ if (row && (rates.get(row.id) ?? 0) > capacity + 1e-8) findings.push({ code: "carrier-cut", confidence: "upper-bound", detail: `${b.kind} #${b.id}: nearest-destination carrier ceiling ${capacity.toFixed(2)}/min is below production ${(rates.get(row.id) ?? 0).toFixed(2)}/min` })+ return { id: b.id, nearestTarget, sharedGoodsPerMinuteCeiling: capacity }+ })+ if (storage.length === 0) findings.push({ code: "no-storage", confidence: "exact", detail: "No completed storage accepts town reserves" })+ return { name: s.name, severity, minutes, elapsedMs: performance.now() - started,+ assumptions: ["Resource flow is a steady-state pooled relaxation; it is an upper bound before household demand and transport cuts.", "Transport ceilings assume full loads and available destinations; nearest-demand dispatch and construction can lower realized throughput.", "Service path probabilities are exact for the stated uniform-walk graph; renewal timing and unlimited baskets are estimates.", "Risk deadlines freeze hunger, approval, neighbourhood and condition; contagion and fire spread are excluded from these local deadlines."],+ staff: Object.fromEntries(staff), recipes: recipes.map((r) => ({ ...r, flowCeiling: rates.get(r.id)! })),+ supply, workshopDemand: inputs, spoilage: spoil, availableAfterWorkshops: net, needBounds,+ economy: { taxesPerMinute: taxes, upkeepPerMinute: upkeep, administrationPerMinute: collection.admin, roundedNetPerMinute: cashPerMinute,+ noTradeRunwayMinutes: cashPerMinute < 0 ? Math.max(0, s.coins) / -cashPerMinute : null },+ currentGoalsWithoutTrade: goalsOf(s.charter, { settlers: s.homes.filter((h) => h.tier === 1).reduce((n, h) => n + h.residents, 0), citizens: s.homes.filter((h) => h.tier >= 2).reduce((n, h) => n + h.residents, 0), coins: s.coins, net: cashPerMinute, approval: s.approval }, rules),+ tools: { wearingWorkplaces: toolWorkplaces.length, equippedWorkplaces: workingTools, held: heldTools },+ repair: { upkeepCycleMinutes: (rules.conditionMax - rules.condition.mend) * rules.condition.every * rules.stepSeconds / 60,+ planksPerMinute: (s.homes.length + s.buildings.filter((b) => !rules.kinds[b.kind].decor && b.kind !== "townhall").length) * 60 / ((rules.conditionMax - rules.condition.mend) * rules.condition.every * rules.stepSeconds),+ stonePerMinute: s.buildings.filter((b) => !rules.kinds[b.kind].decor && b.kind !== "townhall").length * 60 / ((rules.conditionMax - rules.condition.mend) * rules.condition.every * rules.stepSeconds),+ graceBeforeHalfSpeedSeconds: (rules.condition.mend - rules.condition.worn) * rules.condition.every * rules.stepSeconds },+ citizenGoal: { housingCeilingAtCurrentDesirability: citizenHousingCeiling, minimumAtPopulationGoal: requiredCitizensAtPopulationGoal, scope: "Existing homes and frozen neighbourhood; assumes every need/service could be supplied. Clearing ruins, repairs, new homes or amenities can change this ceiling." },+ household, transport, services: profiles, findings }+}+export type Analysis = ReturnType<typeof analyze>diff --git a/tools/balance/model/project.ts b/tools/balance/model/project.tsnew file mode 100644index 0000000..b1aa750--- /dev/null+++ b/tools/balance/model/project.ts@@ -0,0 +1,177 @@+import { amounts, goodIds, type Amounts } from "../../../src/content.ts"+import { ruleTicks } from "../../../src/rules/config.ts"+import { baseCollection, capacity, serveGoods, taxOf, tierFor } from "../../../src/rules/households.ts"+import { seasonAt } from "../../../src/rules/seasons.ts"+import { spoilExpectation } from "../../../src/rules/decay.ts"+import { tradeCollection } from "../../../src/rules/trade.ts"+import { approvalTarget, nextApproval } from "../../../src/rules/approval.ts"+import { analyze } from "./analyze.ts"+import { around, cellsOf, key, ownerAt } from "../../../src/grid.ts"+import { scenarioGrid } from "../scenario.ts"+import type { Inputs, ModelBuilding, ProjectionOptions, Scenario } from "../types.ts"++/** Rate-based forecast with explicit temporal assumptions. It never calls the game runtime. */+export const project = ({ rules, scenario }: Inputs, options: ProjectionOptions) => {+ const step = options.stepSeconds ?? 1+ if (!Number.isInteger(step) || step < 1 || step > 3 || !Number.isInteger(options.seconds) || options.seconds <= 0) throw new Error("Projection requires a 1..3 second step and a positive integer horizon")+ const stock = { ...amounts({}) }+ for (const b of scenario.buildings) if (!b.site) for (const g of goodIds) stock[g] += b.stock[g]+ let homes = scenario.homes.map((h) => ({ ...h, meters: { ...h.meters } })), buildings = [...scenario.buildings], coins = scenario.coins, approval = scenario.approval+ const events: Array<{ second: number; type: string; detail: string }> = [], rows: Array<{ second: number; coins: number; residents: number; citizens: number; approval: number; stock: Amounts }> = []+ const builds = [...options.builds ?? []].sort((a, b) => a.at - b.at), crown = [...options.crown ?? []].sort((a, b) => a.at - b.at)+ const pending: Array<{ ready: number; action: typeof builds[number] }> = []+ let nextId = Math.max(0, ...homes.map((h) => h.id), ...buildings.map((b) => b.id)) + 1+ let analysis = analyze({ rules, scenario }, { services: true }), cachedKey = "", firstCitizen: number | null = null+ let prices = scenario.trade?.prices ?? amounts(Object.fromEntries(goodIds.map((g) => [g, 100])))+ const snubs: number[] = []+ const land = scenario.land.map((l) => ({ ...l, remaining: l.type === "stone" || l.type === "ore" ? l.amount : 1 }))+ const fields = new Map<number, { credit: number; slots: number; planting: number; growing: Array<{ left: number; credit: number }> }>()+ const crop = (b: ModelBuilding) => {+ let state = fields.get(b.id)+ if (!state) {+ const grid = scenarioGrid({ ...scenario, buildings, homes }, rules).value()+ const k = rules.kinds[b.kind], ids = new Set(around(b.tile, k.gathers!.radius).map((p) => ownerAt(grid, p.x, p.y)))+ const existing = scenario.land.filter((l, i) => l.type === "field" && ids.has(-1 - i))+ state = { credit: existing.filter((l) => l.growth >= rules.grown.field).length, slots: existing.length, planting: 0,+ growing: existing.filter((l) => l.growth < rules.grown.field).map((l) => ({ left: (rules.grown.field - l.growth) * rules.stepSeconds, credit: 1 })) }+ fields.set(b.id, state)+ }+ return state+ }+ const goodsPeriods = new Map<number, number>(), faithPeriods = new Map<number, number>()+ const updatePeriods = () => {+ for (const h of homes) {+ const visitRate = (type: string) => analysis.services.filter((p) => p.service === type).reduce((n, p) => n + (p.contacts.find((c) => c.target === h.id)?.visitsPerMinute ?? 0), 0)+ const goods = visitRate("goods"), faith = visitRate("faith")+ goodsPeriods.set(h.id, options.visitSeconds ?? (goods > 0 ? Math.max(1, Math.round(60 / goods)) : Infinity))+ faithPeriods.set(h.id, options.faith === true ? options.visitSeconds ?? 20 : faith > 0 ? Math.max(1, Math.round(60 / faith)) : Infinity)+ }+ }+ updatePeriods()+ for (let second = 0; second <= options.seconds; second += step) {+ if (second % 60 === 0 || second === options.seconds) rows.push({ second, coins, residents: homes.reduce((n, h) => n + h.residents, 0), citizens: homes.filter((h) => h.tier >= 2).reduce((n, h) => n + h.residents, 0), approval, stock: { ...stock } })+ if (second === options.seconds) break+ const tick = scenario.tick + ruleTicks(second, rules), season = seasonAt(tick, scenario.charter, rules)+ while (builds.length > 0 && builds[0]!.at <= second) {+ const action = builds.shift()!, k = action.kind === "home" ? null : rules.kinds[action.kind], cost = k?.cost ?? rules.home.cost+ if (k?.plants?.what === "field") {+ const plantingCells = new Set(around(action.tile, k.plants.radius).map((p) => key(p.x, p.y)))+ for (const future of builds) if (cellsOf(future.tile).some((p) => plantingCells.has(key(p.x, p.y)))) events.push({ second, type: "crop-placement-risk", detail: `${future.kind}'s future plot is inside ${action.kind}'s planting area; construct it first or clear fields later` })+ }+ const people = homes.reduce((n, h) => n + h.residents, 0), citizens = homes.filter((h) => h.tier >= 2).reduce((n, h) => n + h.residents, 0)+ const equipped = buildings.filter((b) => rules.kinds[b.kind].wear && b.stock.tools > 0).length+ if ((k && (people < k.unlock.residents || citizens < k.unlock.citizens)) || coins < cost.coins || Object.entries(cost.materials).some(([g, n]) => stock[g as keyof Amounts] - (g === "tools" ? equipped : 0) < n!)) {+ events.push({ second, type: "build-blocked", detail: `${action.kind}: unlock, coins or materials unavailable` }); continue+ }+ coins -= cost.coins+ for (const [g, n] of Object.entries(cost.materials)) stock[g as keyof Amounts] -= n!+ pending.push({ ready: second + rules.buildTicks * rules.stepSeconds, action })+ events.push({ second, type: "build-paid", detail: `${action.kind}: ${cost.coins} coins` })+ }+ for (let i = pending.length - 1; i >= 0; i--) {+ const p = pending[i]!+ if (p.ready > second) continue+ const id = nextId+++ if (p.action.kind === "home") homes.push({ id, tile: p.action.tile, tier: 1, residents: 0, clock: 0, food: 0, bread: 0, cloth: 0, faith: 0, condition: rules.conditionMax, meters: { fire: 0, health: 0, order: 0 } })+ else buildings.push({ id, kind: p.action.kind, tile: p.action.tile, paused: false, site: false, condition: rules.conditionMax, stock: amounts({}) })+ pending.splice(i, 1)+ }+ let toolSlots = Math.floor(stock.tools)+ buildings = buildings.map((b) => rules.kinds[b.kind].wear ? { ...b, stock: { ...b.stock, tools: toolSlots-- > 0 ? 1 : 0 } } : b)+ const stateKey = JSON.stringify([homes.map((h) => [h.id, h.tier, h.residents]), buildings.map((b) => [b.id, b.stock.tools, b.condition < rules.condition.worn]), season.severity])+ if (stateKey !== cachedKey) {+ const current: Scenario = { ...scenario, tick, coins, approval, homes, buildings }+ analysis = analyze({ rules, scenario: current }, { minutes: Math.max(1 / 60, (options.seconds - second) / 60), services: true })+ updatePeriods()+ cachedKey = stateKey+ }+ const share = Math.min(step, options.seconds - second) / 60+ // Sources first, then workshops. This is an optimistic pool, explicitly not the live dispatcher.+ const recipeRows = [...analysis.recipes].sort((a, b) => Number(rules.kinds[a.kind].recipe!.input !== null) - Number(rules.kinds[b.kind].recipe!.input !== null))+ for (const row of recipeRows) {+ const k = rules.kinds[row.kind], r = k.recipe!, transport = analysis.transport.find((t) => t.id === row.id)?.sharedGoodsPerMinuteCeiling ?? Infinity+ let jobs = Math.min(row.capacity.outputPerMinute, transport) * share / r.batch+ if (r.input) jobs = Math.min(jobs, stock[r.input] / Math.max(1, r.inputs))+ if (k.gathers?.source === "water" && row.sourceCeiling === 0) jobs = 0+ if (k.gathers?.source === "field") {+ const b = buildings.find((b) => b.id === row.id)!, state = crop(b)+ if (!season.winter) {+ state.planting += step+ while (state.slots < k.plants!.max && state.planting >= k.plants!.seconds) { state.planting -= k.plants!.seconds; state.slots += 1; state.growing.push({ left: rules.grown.field * rules.stepSeconds, credit: 1 }) }+ for (let i = state.growing.length - 1; i >= 0; i--) { const q = state.growing[i]!; q.left -= step; if (q.left <= 0) { state.credit += q.credit; state.growing.splice(i, 1) } }+ }+ jobs = Math.min(jobs, state.credit); state.credit -= jobs+ if (jobs > 0) state.growing.push({ left: rules.grown.field * rules.stepSeconds, credit: jobs })+ } else if (k.gathers && k.gathers.source !== "water") {+ const b = buildings.find((b) => b.id === row.id)!, grid = scenarioGrid({ ...scenario, buildings, homes }, rules).value()+ const ids = new Set(around(b.tile, k.gathers.radius).map((p) => ownerAt(grid, p.x, p.y)))+ const sources = land.filter((l, i) => ids.has(-1 - i) && l.type === k.gathers!.source && (l.type !== "tree" || l.growth >= rules.grown.tree))+ jobs = Math.min(jobs, sources.reduce((n, l) => n + l.remaining, 0))+ let take = jobs+ for (const l of sources) { const n = Math.min(take, l.remaining); l.remaining -= n; take -= n }+ }+ if (r.input) stock[r.input] -= jobs * r.inputs+ stock[r.output] += jobs * r.batch+ if (k.wear) stock.tools = Math.max(0, stock.tools - jobs / k.wear)+ }+ for (const g of goodIds) stock[g] = Math.max(0, stock[g] + ((scenario.imports?.[g] ?? 0) - (scenario.exports?.[g] ?? 0)) * share)+ for (const l of land) if (l.type === "tree") l.growth += ruleTicks(step, rules)+ const oldTiers = homes.map((h) => h.tier)+ homes = homes.map((h) => {+ let next = { ...h, meters: { ...h.meters } }+ const goods = goodsPeriods.get(h.id) ?? Infinity, faith = faithPeriods.get(h.id) ?? Infinity+ if (Number.isFinite(goods) && Math.floor(second / goods) !== Math.floor((second + step) / goods)) {+ const basket = Object.fromEntries(goodIds.map((g) => [g, Math.max(0, Math.floor(stock[g]))])) as Record<keyof Amounts, number>+ if (options.feeding === "fish") basket.bread = 0+ const served = serveGoods(next, basket, rules)+ for (const g of goodIds) stock[g] -= basket[g] - served.basket[g]+ next = { ...served.house }+ }+ if (Number.isFinite(faith) && Math.floor(second / faith) !== Math.floor((second + step) / faith)) next.faith = rules.home.lasts.faith+ const dt = ruleTicks(step, rules), eat = season.winter ? dt * 1.5 : dt+ next.clock += dt; next.food = Math.max(0, next.food - eat); next.bread = Math.max(0, next.bread - eat); next.cloth = Math.max(0, next.cloth - dt); next.faith = Math.max(0, next.faith - dt)+ const settleCount = Math.floor(next.clock / rules.home.settle) - Math.floor(h.clock / rules.home.settle)+ const appeal = analysis.household.find((a) => a.id === h.id)?.desirability ?? 0+ for (let n = 0; n < settleCount; n++) {+ next.tier = tierFor(next, appeal, next.meters, rules)+ const cap = analysis.household.find((a) => a.id === h.id)?.roadConnected ? capacity(next, approval, appeal, rules) : 0+ next.residents = Math.min(next.residents, rules.home.tiers[next.tier].residents)+ next.residents += Math.sign(cap - next.residents)+ }+ next.condition = Math.max(0, h.condition - step / (rules.condition.every * rules.stepSeconds))+ return next+ })+ if (firstCitizen === null && homes.some((h) => h.tier >= 2 && h.residents > 0)) firstCitizen = second + step+ for (let i = 0; i < homes.length; i++) if (homes[i]!.tier !== oldTiers[i]) events.push({ second: second + step, type: "tier", detail: `Home #${homes[i]!.id}: ${oldTiers[i]} → ${homes[i]!.tier}` })+ buildings = buildings.map((b) => ({ ...b, condition: rules.kinds[b.kind].decor || b.kind === "townhall" ? b.condition : Math.max(0, b.condition - step / (rules.condition.every * rules.stepSeconds)) }))+ const elapsed = second + step+ if (Math.floor(elapsed / (rules.spoilTicks * rules.stepSeconds)) > Math.floor(second / (rules.spoilTicks * rules.stepSeconds))) {+ const keeps = buildings.some((b) => rules.kinds[b.kind].keeps) ? Math.max(...buildings.map((b) => rules.kinds[b.kind].keeps ?? 1)) : 1+ for (const g of goodIds) stock[g] = Math.max(0, stock[g] - spoilExpectation(stock[g], g, keeps, rules))+ }+ if (Math.floor(elapsed / (rules.ledgerTicks * rules.stepSeconds)) > Math.floor(second / (rules.ledgerTicks * rules.stepSeconds))) {+ const tax = homes.reduce((n, h) => n + (analysis.household.find((a) => a.id === h.id)?.taxConnected ? taxOf(h, scenario.policy, rules) : 0), 0), upkeep = buildings.reduce((n, b) => n + rules.kinds[b.kind].upkeep * (b.paused ? rules.pausedUpkeep : 1), 0)+ coins += baseCollection(tax, upkeep, homes.length, rules).delta+ if (scenario.trade) {+ const equipped = buildings.filter((b) => rules.kinds[b.kind].wear && b.stock.tools > 0).length+ const left = { ...stock, tools: Math.max(0, stock.tools - equipped) }, stores = buildings.filter((b) => rules.kinds[b.kind].holds?.accepts === "all" || rules.kinds[b.kind].keeps).map((b) => {+ const holds = rules.kinds[b.kind].holds!, accepts = holds.accepts === "all" ? goodIds : holds.accepts+ const stored = amounts(Object.fromEntries(goodIds.map((g) => { const n = accepts.includes(g) ? Math.max(0, Math.min(holds.cap, Math.floor(left[g]))) : 0; left[g] -= n; return [g, n] })))+ return { cap: holds.cap, accepts, stock: stored }+ })+ const traded = tradeCollection(stores, scenario.trade, prices, coins, rules)+ for (const g of goodIds) stock[g] += traded.stores.reduce((n, s) => n + s.stock[g], 0) - stores.reduce((n, s) => n + s.stock[g], 0)+ coins = traded.coins; prices = traded.prices+ }+ const recentSnubs = snubs.filter((at) => elapsed - at < rules.crown.memory * 60).length+ approval = nextApproval(approval, approvalTarget(homes, scenario.policy, coins, recentSnubs, season.winter, rules).target, rules)+ }+ while (crown.length > 0 && crown[0]!.at <= elapsed) {+ const c = crown.shift()!, met = stock[c.good] >= c.amount+ if (met) { stock[c.good] -= c.amount; coins += c.reward } else { coins -= c.fine; snubs.push(elapsed) }+ events.push({ second: elapsed, type: "crown", detail: `${c.good}: ${met ? "delivered" : "missed"}` })+ }+ }+ return { name: scenario.name, firstCitizenSecond: firstCitizen, rows, events,+ assumptions: ["One-second pooled rate model; integer recipe phases and local storage are approximated.", "Contacts are periodic mean visits unless explicitly supplied; faith has no goods cost. This understates long revisit gaps.", "Construction spends materials at placement and ignores carrier latency; completion is optimistic.", "Granary protection and tool availability are pooled; source accessibility is frozen between analysis updates.", "Market prices and collection rules are shared; shelf allocation is pooled and optimistic. No disaster losses, repair recovery or victory classification are predicted. Explicit imports/exports and crown events are scenario conditions."] }+}diff --git a/tools/balance/model/search.ts b/tools/balance/model/search.tsnew file mode 100644index 0000000..b932a4b--- /dev/null+++ b/tools/balance/model/search.ts@@ -0,0 +1,35 @@+import type { KindId } from "../../../src/content.ts"+import { amounts } from "../../../src/content.ts"+import { resolveRules, type RulePatch, type Rules } from "../../../src/rules/config.ts"+import { analyze } from "./analyze.ts"+import { district } from "../scenario.ts"+import type { Inputs } from "../types.ts"++/** Offline experiments only. Candidates are immutable and are never written to game content. */+export const searchParameters = (inputs: Inputs, candidates: ReadonlyArray<ReadonlyArray<RulePatch>>, score: (result: ReturnType<typeof analyze>) => number) =>+ candidates.map((patches) => {+ // Patches are relative to shipped content. Refuse silently mixing a different base configuration.+ if (JSON.stringify(inputs.rules) !== JSON.stringify(resolveRules())) throw new Error("Parameter search requires the shipped-rule base")+ const rules = resolveRules(patches), analysis = analyze({ rules, scenario: inputs.scenario }, { services: false })+ return { patches, rules, analysis, score: score(analysis) }+ }).sort((a, b) => b.score - a.score)++/** Enumerates affordable production packages at the unchanged game parameters. */+export const searchDistricts = (rules: Rules, homes = 8) => {+ const results: Array<{ buildings: ReadonlyArray<KindId>; cost: number; materials: Record<string, number>; foodPerMinute: number; clothPerMinute: number; workers: number; upkeep: number; affordableAtFoundation: boolean }> = []+ for (let bakeries = 1; bakeries <= 3; bakeries++) for (let weavers = 1; weavers <= 3; weavers++) for (let fisheries = 0; fisheries <= 2; fisheries++) {+ const kinds: KindId[] = ["chapel", ...Array.from({ length: bakeries }, () => ["farm", "mill", "bakery"] as const).flat(), ...Array.from({ length: weavers }, () => ["sheep", "weaver"] as const).flat(), ...Array<KindId>(fisheries).fill("fishery")]+ const base = district("candidate", Array(homes).fill(1), kinds, false, rules)+ const scenario = { ...base, buildings: base.buildings.map((b) => b.kind === "townhall" ? { ...b, stock: amounts({}) } : b) }+ const analysis = analyze({ rules, scenario }, { services: false, minutes: 1 })+ const materials: Record<string, number> = {}+ for (const k of kinds) for (const [g, n] of Object.entries(rules.kinds[k].cost.materials)) materials[g] = (materials[g] ?? 0) + n!+ materials.tools = (materials.tools ?? 0) + kinds.filter((k) => rules.kinds[k].wear).length+ const cost = kinds.reduce((n, k) => n + rules.kinds[k].cost.coins, 0)+ const workers = kinds.reduce((n, k) => n + rules.kinds[k].workers, 0), upkeep = kinds.reduce((n, k) => n + rules.kinds[k].upkeep, 0)+ results.push({ buildings: kinds, cost, materials, foodPerMinute: analysis.availableAfterWorkshops.bread + analysis.availableAfterWorkshops.fish,+ clothPerMinute: analysis.availableAfterWorkshops.cloth, workers, upkeep,+ affordableAtFoundation: cost <= rules.lands.fair.coins && Object.entries(materials).every(([g, n]) => n <= rules.lands.fair.stock[g as keyof typeof rules.lands.fair.stock]) })+ }+ return results.sort((a, b) => a.cost - b.cost)+}diff --git a/tools/balance/model/services.ts b/tools/balance/model/services.tsnew file mode 100644index 0000000..e954c20--- /dev/null+++ b/tools/balance/model/services.ts@@ -0,0 +1,93 @@+import { doors, key, reach, type TileLike } from "../../../src/grid.ts"+import { GRID } from "../../../src/iso.ts"+import { onwardRoads } from "../../../src/rules/transport.ts"+import type { Rules } from "../../../src/rules/config.ts"+import type { Assignment } from "../../../src/rules/production.ts"+import { scenarioGrid } from "../scenario.ts"+import type { ModelBuilding, Scenario } from "../types.ts"++export interface Contact {+ readonly target: number; readonly expectedVisitsPerTrip: number; readonly hitProbability: number+ readonly firstHitSeconds: number | null; readonly visitsPerMinute: number+}+export interface ServiceProfile {+ readonly source: number; readonly service: string; readonly tripsPerMinute: number+ readonly meanTripSeconds: number; readonly contacts: ReadonlyArray<Contact>+ readonly assumption: string+}+interface State { readonly previous: number; readonly cell: number; readonly probability: number }++/** Finite non-backtracking random-walk DP. No random samples or headless runtime are used. */+export const serviceProfile = (scenario: Scenario, building: ModelBuilding, staff: Assignment, rules: Rules): ServiceProfile | null => {+ const kind = rules.kinds[building.kind], service = kind.service+ if (!service || building.paused || building.site || (kind.workers > 0 && staff.assigned === 0)) return null+ const grid = scenarioGrid(scenario, rules).value(), starts = doors(grid, building.tile)+ if (starts.length === 0) return null+ const homeRoads = reach(grid, starts), secondsPerCell = rules.transport.cellSteps * rules.stepSeconds / rules.transport.walk+ const targets: ReadonlyArray<{ readonly id: number; readonly tile: TileLike }> = service.service === "fire" || service.service === "repair" ? [...scenario.homes, ...scenario.buildings.filter((b) => !b.site && !rules.kinds[b.kind].decor)] : scenario.homes+ const beside = new Map<number, Set<number>>()+ for (const t of targets) for (const d of doors(grid, t.tile)) {+ const k = key(d.x, d.y), set = beside.get(k) ?? new Set<number>(); set.add(t.id); beside.set(k, set)+ }+ const next = (state: State): ReadonlyArray<number> => {+ const cell = { x: state.cell % GRID, y: Math.floor(state.cell / GRID) }+ const previous = state.previous < 0 ? null : { x: state.previous % GRID, y: Math.floor(state.previous / GRID) }+ const candidates = onwardRoads(grid, cell, previous).map((p) => key(p.x, p.y))+ return candidates.length > 0 ? candidates : state.previous < 0 ? [] : [state.previous]+ }+ const advance = (states: ReadonlyArray<State>, avoid = -1): State[] => {+ const result = new Map<string, State>()+ for (const s of states) {+ if (beside.get(s.cell)?.has(avoid)) continue+ const choices = next(s)+ for (const cell of choices) {+ const id = `${s.cell}:${cell}`, probability = s.probability / choices.length+ const old = result.get(id)+ result.set(id, { previous: s.cell, cell, probability: probability + (old?.probability ?? 0) })+ }+ }+ return [...result.values()]+ }+ const initial: State[] = [{ previous: -1, cell: key(starts[0]!.x, starts[0]!.y), probability: 1 }]+ const expected = new Map<number, number>()+ let states = initial, meanTripSeconds = 0+ for (let step = 0; step < service.range; step++) {+ for (const state of states) {+ for (const id of beside.get(state.cell) ?? []) expected.set(id, (expected.get(id) ?? 0) + state.probability)+ if (step === service.range - 1 || next(state).length === 0) {+ const distance = homeRoads.distance[state.cell]!+ meanTripSeconds += state.probability * (step + Math.max(0, distance)) * secondsPerCell+ }+ }+ states = advance(states)+ }+ const apprenticed = staff.assigned > 0 && staff.assigned === staff.apprentices+ const launchSeconds = service.seconds / (apprenticed ? rules.apprentice : 1)+ const tripsPerMinute = Math.min(60 / launchSeconds, meanTripSeconds > 0 ? rules.transport.active * 60 / meanTripSeconds : Infinity)+ const contacts = targets.filter((t) => expected.has(t.id)).map((t): Contact => {+ let unhit = initial, hitProbability = 0, firstHit = 0+ for (let step = 0; step < service.range; step++) {+ const now = unhit.filter((s) => beside.get(s.cell)?.has(t.id)).reduce((sum, s) => sum + s.probability, 0)+ hitProbability += now; firstHit += now * step * secondsPerCell+ unhit = advance(unhit, t.id)+ }+ return { target: t.id, expectedVisitsPerTrip: expected.get(t.id)!, hitProbability,+ firstHitSeconds: hitProbability > 0 ? firstHit / hitProbability : null,+ visitsPerMinute: expected.get(t.id)! * tripsPerMinute }+ })+ return { source: building.id, service: service.service, tripsPerMinute, meanTripSeconds, contacts,+ assumption: "Exact finite-path probabilities for uniform choices on fixed roads; trip rate uses mean occupancy. Goods/repair profiles assume unlimited baskets. Revisit-gap estimates assume independent excursions." }+}++/** Excursion-level renewal approximation; avoids counting repeated visits on one trip as independent protection. */+export const missProbability = (profiles: ReadonlyArray<ServiceProfile>, target: number, seconds: number): number => {+ let log = 0+ for (const p of profiles) {+ const c = p.contacts.find((c) => c.target === target)+ if (!c || c.hitProbability === 0) continue+ const trips = p.tripsPerMinute * seconds / 60+ if (c.hitProbability >= 1 && trips >= 1) return 0+ log += trips * Math.log(Math.max(1e-12, 1 - c.hitProbability))+ }+ return Math.exp(log)+}diff --git a/tools/balance/model/throughput.ts b/tools/balance/model/throughput.tsnew file mode 100644index 0000000..4ab9fda--- /dev/null+++ b/tools/balance/model/throughput.ts@@ -0,0 +1,56 @@+import type { Kind, WinterId } from "../../../src/content.ts"+import { around, useAt, ownerAt, type GridBuilder } from "../../../src/grid.ts"+import { ruleTicks, type Rules } from "../../../src/rules/config.ts"+import { equipmentPace, effort, paced } from "../../../src/rules/production.ts"+import type { Assignment } from "../../../src/rules/production.ts"+import type { RecipeCapacity, Scenario, ModelBuilding } from "../types.ts"++/** Tiny periodic cadence calculation, not an ECS run. Products of average paces are insufficient. */+export const recipeCapacity = (kind: Kind, staff: Assignment, tools: number, condition: number, severity: WinterId | null, rules: Rules): RecipeCapacity => {+ const zero = { jobsPerMinute: 0, outputPerMinute: 0, inputPerMinute: 0, toolsPerMinute: 0, meanJobTicks: 0, cadenceTicks: 1 }+ if (!kind.recipe || staff.assigned === 0 || kind.workers === 0) return zero+ const pace = equipmentPace(kind, tools, condition, severity === null ? 1 : rules.winters[severity].fishing, rules)+ let period = 1+ while (period <= 4096 && (Math.abs(pace * period - Math.round(pace * period)) > 1e-9 || Math.abs(rules.apprentice * period - Math.round(rules.apprentice * period)) > 1e-9)) period += 1+ if (period > 4096) throw new Error("Cadence denominator exceeds 4096; choose a supported rational pace")+ const weights = Array.from({ length: period }, (_, tick) => paced(pace, tick) ? effort(staff, tick, rules) : 0)+ const total = weights.reduce((sum, n) => sum + n, 0)+ if (total === 0) return zero+ const required = ruleTicks(kind.recipe.seconds, rules) * kind.workers+ if (required <= 0) throw new Error("Recipe period must be positive")+ const duration = (phase: number) => {+ const cycles = Math.max(0, Math.ceil(required / total) - 1)+ let done = cycles * total, ticks = cycles * period+ while (done < required) { done += weights[(phase + ticks) % period]!; ticks += 1 }+ return ticks+ }+ const seen = new Map<number, { readonly ticks: number; readonly jobs: number }>()+ let phase = 0, ticks = 0, jobs = 0+ while (!seen.has(phase)) {+ seen.set(phase, { ticks, jobs })+ const d = duration(phase); ticks += d; jobs += 1; phase = (phase + d) % period+ }+ const start = seen.get(phase)!, meanJobTicks = (ticks - start.ticks) / (jobs - start.jobs)+ const jobsPerMinute = 60 / (meanJobTicks * rules.stepSeconds)+ return { jobsPerMinute, outputPerMinute: jobsPerMinute * kind.recipe.batch,+ inputPerMinute: jobsPerMinute * kind.recipe.inputs, toolsPerMinute: kind.wear ? jobsPerMinute / kind.wear : 0,+ meanJobTicks, cadenceTicks: period }+}++/** Accessible source ceiling over the specified horizon. Forestry overlaps are called out separately. */+export const sourceCeiling = (b: ModelBuilding, scenario: Scenario, grid: GridBuilder, severity: WinterId | null, minutes: number, rules: Rules): number => {+ const k = rules.kinds[b.kind], g = k.gathers+ if (!g) return Infinity+ const ids = new Set(around(b.tile, g.radius).filter((p) => useAt(grid.value(), p.x, p.y) === (g.source === "ore" || g.source === "stone" ? "rock" : g.source)).map((p) => ownerAt(grid.value(), p.x, p.y)))+ const sources = scenario.land.filter((l, i) => ids.has(-1 - i) && l.type === g.source)+ if (g.source === "water") return sources.length > 0 ? Infinity : 0+ if (g.source === "field") {+ const ripe = sources.filter((l) => l.growth >= rules.grown.field).length+ return severity === null ? Math.max(sources.length, k.plants?.max ?? 0) * 60 / (rules.grown.field * rules.stepSeconds) : ripe / Math.max(minutes, 1 / 60)+ }+ const finite = sources.reduce((sum, l) => sum + (g.source === "tree" ? Number(l.growth >= rules.grown.tree) : l.amount), 0)+ const planted = g.source === "tree" ? scenario.buildings.filter((p) => p.kind === "forester" && !p.paused && !p.site && Math.abs(p.tile.x - b.tile.x) <= g.radius + rules.kinds.forester.plants!.radius && Math.abs(p.tile.y - b.tile.y) <= g.radius + rules.kinds.forester.plants!.radius).length * 60 / rules.kinds.forester.plants!.seconds : 0+ // Wild spreading can add at most one tree per checkpoint globally. Ignoring it would make this falsely narrow.+ const wildUpper = g.source === "tree" && scenario.land.some((l) => l.type === "tree") ? 60 / (rules.spreadTicks * rules.stepSeconds) : 0+ return finite / Math.max(minutes, 1 / 60) + planted + wildUpper+}diff --git a/tools/balance/model/transport.ts b/tools/balance/model/transport.tsnew file mode 100644index 0000000..a4f87f9--- /dev/null+++ b/tools/balance/model/transport.ts@@ -0,0 +1,30 @@+import type { GoodId } from "../../../src/content.ts"+import { doors, nearest, reach } from "../../../src/grid.ts"+import { preferDelivery } from "../../../src/rules/transport.ts"+import { scenarioGrid } from "../scenario.ts"+import type { Inputs } from "../types.ts"++export interface Transfer { readonly source: number; readonly target: number; readonly good: GoodId; readonly goodsPerMinute: number; readonly construction?: boolean }++/** Necessary time-budget constraints for specified flows. All goods share each source's carrier pool. */+export const assessTransfers = ({ rules, scenario }: Inputs, transfers: ReadonlyArray<Transfer>) => {+ const grid = scenarioGrid(scenario, rules).value(), pools = new Map<number, { availableCarrierSeconds: number; requiredCarrierSeconds: number }>()+ const routes = transfers.map((transfer) => {+ if (!Number.isFinite(transfer.goodsPerMinute) || transfer.goodsPerMinute < 0) throw new Error("Transfer rate must be finite and nonnegative")+ const source = scenario.buildings.find((b) => b.id === transfer.source), target = scenario.buildings.find((b) => b.id === transfer.target)+ if (!source || !target) throw new Error("Transfer references an unknown building")+ if (source.id === target.id) throw new Error("A building does not dispatch carriers to itself")+ const found = nearest(reach(grid, doors(grid, source.tile)), doors(grid, target.tile))+ const carriers = source.site ? 0 : rules.kinds[source.kind].carriers ?? 0+ const pool = pools.get(source.id) ?? { availableCarrierSeconds: carriers * 60, requiredCarrierSeconds: 0 }+ const roundTripSeconds = found ? 2 * found.distance * rules.transport.cellSteps * rules.stepSeconds / rules.transport.walk : null+ const needed = roundTripSeconds === null ? transfer.goodsPerMinute > 0 ? Infinity : 0 : transfer.goodsPerMinute / rules.transport.load * Math.max(roundTripSeconds, rules.transport.dispatchTicks * rules.stepSeconds)+ pool.requiredCarrierSeconds += needed; pools.set(source.id, pool)+ return { ...transfer, distance: found?.distance ?? null, roundTripSeconds, carrierSecondsPerMinute: Number.isFinite(needed) ? needed : null }+ })+ // Use the runtime's exact construction/nearest ranking; throughput remains a full-load relaxation.+ const dispatchPriority = [...routes].sort((a, b) => a.source - b.source || (preferDelivery({ site: !!a.construction, distance: a.distance ?? Infinity }, { site: !!b.construction, distance: b.distance ?? Infinity }) ? -1 : preferDelivery({ site: !!b.construction, distance: b.distance ?? Infinity }, { site: !!a.construction, distance: a.distance ?? Infinity }) ? 1 : 0))+ return { routes, dispatchPriority, pools: [...pools].map(([source, p]) => ({ source, ...p, requiredCarrierSeconds: Number.isFinite(p.requiredCarrierSeconds) ? p.requiredCarrierSeconds : null,+ feasibleNecessaryCondition: p.requiredCarrierSeconds <= p.availableCarrierSeconds })),+ confidence: "Necessary full-load time budgets for caller-specified flows. They do not guarantee live greedy dispatch, avoid construction starvation, or remove inventory/basket constraints." }+}diff --git a/tools/balance/provenance.ts b/tools/balance/provenance.tsnew file mode 100644index 0000000..3da1523--- /dev/null+++ b/tools/balance/provenance.ts@@ -0,0 +1,14 @@+import { createHash } from "node:crypto"+import { readFileSync, readdirSync } from "node:fs"+import { resolveRules, type Rules } from "../../src/rules/config.ts"+import type { Scenario } from "./types.ts"++const stable = (value: unknown): unknown => Array.isArray(value) ? value.map(stable) : value !== null && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, stable(v)])) : value+export const fingerprint = (value: unknown) => createHash("sha256").update(JSON.stringify(stable(value))).digest("hex")+export const provenance = (rules: Rules, scenarios: ReadonlyArray<Scenario>) => {+ const paths = ["src/content.ts", "src/grid.ts", "src/appeal.ts", "tools/balance/catalog.ts", "tools/balance/scenario.ts", "tools/balance/types.ts", ...readdirSync("src/rules").filter((f) => f.endsWith(".ts")).map((f) => `src/rules/${f}`), ...readdirSync("src/sim").filter((f) => f.endsWith(".ts")).map((f) => `src/sim/${f}`), ...readdirSync("tools/balance/model").filter((f) => f.endsWith(".ts")).map((f) => `tools/balance/model/${f}`)].sort()+ return { modelVersion: 1, referencePr: "https://github.com/SandroMaglione/inkline-town/pull/3", referenceSha: "57cc83409f9526061d0a726b0299bb3348e8109d",+ rulesSha256: fingerprint(rules), contentSha256: createHash("sha256").update(readFileSync("src/content.ts")).digest("hex"),+ modelSourceSha256: fingerprint(paths.map((p) => [p, readFileSync(p, "utf8")])), scenarioSha256: scenarios.map((s) => ({ name: s.name, sha256: fingerprint(s) })),+ parametersChanged: fingerprint(rules) !== fingerprint(resolveRules()) }+}diff --git a/tools/balance/report.ts b/tools/balance/report.tsnew file mode 100644index 0000000..aec47d7--- /dev/null+++ b/tools/balance/report.ts@@ -0,0 +1,60 @@+import { amounts, type KindId } from "../../src/content.ts"+import type { Rules } from "../../src/rules/config.ts"+import { recipeCapacity } from "./model/throughput.ts"+import { analyze } from "./model/analyze.ts"+import { searchDistricts } from "./model/search.ts"+import { district } from "./scenario.ts"+import { citizensDistrict } from "./catalog.ts"+import { provenance } from "./provenance.ts"+import type { Scenario } from "./types.ts"+import type { Verification } from "./verify/checks.ts"+import type { verifyBuilds } from "./verify/builds.ts"++export const makeReport = (rules: Rules, verification: ReadonlyArray<Verification>, construction: ReturnType<typeof verifyBuilds>, saved?: Scenario) => {+ const started = performance.now(), industrial = citizensDistrict(rules, false), zoned = citizensDistrict(rules, true)+ const scenarios = [industrial, zoned, district("straight-faith", Array(10).fill(1), ["chapel"], false, rules), district("branched-faith", Array(10).fill(1), ["chapel"], true, rules), ...(saved ? [saved] : [])]+ const analyses = scenarios.map((scenario) => analyze({ rules, scenario }))+ const chain: KindId[] = ["farm", "mill", "bakery", "sheep", "weaver", "chapel"]+ const materials = { ...amounts({}) }+ for (const kind of chain) for (const [g, n] of Object.entries(rules.kinds[kind].cost.materials)) materials[g as keyof typeof materials] += n!+ const workingTools = chain.filter((k) => rules.kinds[k].wear).length+ const capacity = (["fishery", "farm", "mill", "bakery", "sheep", "weaver", "sawmill"] as const).map((kind) => ({ kind,+ staffed: recipeCapacity(rules.kinds[kind], { assigned: rules.kinds[kind].workers, apprentices: 0, nearby: 100 }, 1, rules.conditionMax, null, rules).outputPerMinute,+ apprentices: rules.kinds[kind].crew === "citizens" ? recipeCapacity(rules.kinds[kind], { assigned: rules.kinds[kind].workers, apprentices: rules.kinds[kind].workers, nearby: 0 }, 1, rules.conditionMax, null, rules).outputPerMinute : null,+ apprenticesWithoutTools: rules.kinds[kind].crew === "citizens" ? recipeCapacity(rules.kinds[kind], { assigned: rules.kinds[kind].workers, apprentices: rules.kinds[kind].workers, nearby: 0 }, 0, rules.conditionMax, null, rules).outputPerMinute : null }))+ const winter = (["mild", "normal", "hard"] as const).map((severity) => {+ const k = rules.kinds.fishery, perMinute = recipeCapacity(k, { assigned: k.workers, apprentices: 0, nearby: 100 }, 1, rules.conditionMax, severity, rules).outputPerMinute+ return { severity, durationMinutesIn60MinuteTerm: 60 / rules.yearsPerTerm * rules.winters[severity].share, fishPerMinute: perMinute, noWasteHomesPerFishery: perMinute / 1.5, frequentRefreshHomesPerFishery: perMinute / 3 }+ })+ const configurations = searchDistricts(rules, 8)+ return { provenance: provenance(rules, [...scenarios, construction.final]), generatedAt: new Date().toISOString(),+ analysisElapsedMs: performance.now() - started, capacity, winter,+ firstCitizenChain: { coins: chain.reduce((n, k) => n + rules.kinds[k].cost.coins, 0), upkeepPerMinute: chain.reduce((n, k) => n + rules.kinds[k].upkeep, 0), materials,+ workingTools, totalToolsIncludingConstruction: materials.tools + workingTools, fairStartingTools: rules.lands.fair.stock.tools,+ scope: "One of each chain building; excludes homes, roads, market, decorations, raw-material industry and risk services" },+ analyses, verification, construction: { ...construction, final: undefined },+ configurations: { evaluated: configurations.length, affordableAtFoundation: configurations.filter((c) => c.affordableAtFoundation).length, cheapest: configurations.slice(0, 5),+ scope: "Fixed-layout resource relaxation; affordability includes installed working tools but excludes initial homes, roads and services" },+ limits: ["Exact functions and finite-path probabilities are separated from steady-state ceilings and coarse forecasts.", "The construction fixture establishes first citizens on authored flat land, not victory on every generated seed.", "The forecast's revisit gaps, shelf allocation, field placement and equipment distribution are approximations. Calibration errors are reported, not hidden.", "Wild forest regeneration is bounded in steady-state analysis and excluded from the transient finite-tree forecast. Maintenance and disaster constraints are analyzed; stochastic disasters and repairs are verified in the real game, not reproduced as an exact joint distribution."] }+}+export type Report = ReturnType<typeof makeReport>+const n = (v: number | null) => v === null ? "n/a" : Number(v.toFixed(2)).toString()+export const markdownReport = (r: Report) => {+ const a = r.construction.actual.at(-1)!, p = r.construction.prediction.rows.at(-1)!+ const saved = r.analyses.find((a) => a.name === "pr3-bot-minute-30")+ return `# Balance model results\n\nGenerated from PR #3 at ${r.provenance.referenceSha}. No shipped parameter changes. Rules SHA-256: ${r.provenance.rulesSha256}.\n\n## First citizens, with unchanged rules\n\nAn authored starting district pays for its roads and homes, then uses ordinary construction edits and the UI-supported tool reserve of 10. The real game first reaches citizens at ${r.construction.firstCitizenSecond ?? "never"} seconds; the coarse model estimates ${r.construction.prediction.firstCitizenSecond ?? "never"}. At ten minutes the game has ${a.citizens} citizens, ${a.residents} residents and ${a.coins} coins. The forecast has ${p.citizens} citizens, ${p.residents} residents and ${p.coins} coins. This is a progression fixture, not a generated-map victory claim.\n\n## Production capacity\n\nOutputs per minute with full crews, sufficient inputs, output room and maintained condition. Apprentice rows deliberately include the actual tick alignment. These are workshop ceilings, not delivered food.\n\n| Building | Own crew + tool | Apprentices + tool | Apprentices, no tool |\n|---|---:|---:|---:|\n${r.capacity.map((c) => `| ${c.kind} | ${n(c.staffed)} | ${n(c.apprentices)} | ${n(c.apprenticesWithoutTools)} |`).join("\n")}\n\n## Useful constraints\n\n- The first citizen chain alone costs ${r.firstCitizenChain.coins} coins and ${r.firstCitizenChain.materials.tools} construction tools. Its ${r.firstCitizenChain.workingTools} wearing workshops also need working tools. Total ${r.firstCitizenChain.totalToolsIncludingConstruction}, versus ${r.firstCitizenChain.fairStartingTools} at a fair start. Raw industry adds more tool demand.\n- Settlers accept cloth, and bread is preferred for food. Supplying a broad settler district can consume goods intended for citizen upgrades.\n- Promotion changes the workforce: citizens cannot fill settlers' jobs. Keep raw-production households within commuting distance.\n- Build mills/bakeries before farms can plant on their future plots. A previous ordering failed with the real game's “No room there”; the revised verified schedule has ${r.construction.messages.length} rejected-action messages.\n- An unmaintained building loses half speed after about 33 minutes. After it crosses the repair threshold there are ${r.analyses[0]!.repair.graceBeforeHalfSpeedSeconds} seconds before half speed.\n${saved ? `- The original sensible bot's minute-30 town has ${saved.household.length} completed homes. Its pooled cloth capacity is ${n(saved.availableAfterWorkshops.cloth)}/min against ${n(saved.needBounds.cloth.min)}..${n(saved.needBounds.cloth.frequent)}/min to supply every home. ${saved.household.filter((h) => h.potentialTier >= 2).length} homes satisfy the desirability gate even if all citizen needs were supplied. Even granting burghers wherever desirability permits, citizen housing is capped at ${saved.citizenGoal.housingCeilingAtCurrentDesirability}, below the ${saved.citizenGoal.minimumAtPopulationGoal} citizens required at the population goal.\n` : ""}\n## Winters\n\nFully staffed, maintained fisheries; homes consume per household. Each figure excludes spoilage and delivery loss.\n\n| Winter | Duration in a 60-minute term | Fish/min/fishery | Homes supported, late refresh | Homes supported, frequent refresh |\n|---|---:|---:|---:|---:|\n${r.winter.map((w) => `| ${w.severity} | ${n(w.durationMinutesIn60MinuteTerm)} min | ${n(w.fishPerMinute)} | ${n(w.noWasteHomesPerFishery)} | ${n(w.frequentRefreshHomesPerFishery)} |`).join("\n")}\n\n## Verification\n\n${r.verification.filter((v) => v.pass).length}/${r.verification.length} controlled comparisons pass. Production tolerances allow one incomplete job at the window boundary; ledger rounding is exact. Service checks compare finite-path mathematics to actual game excursions.\n\n| Check | Expected | Actual | Allowed error | Pass |\n|---|---:|---:|---:|---|\n${r.verification.map((v) => `| ${v.name} | ${n(v.expected)} | ${n(v.actual)} | ${n(v.tolerance)} | ${v.pass} |`).join("\n")}\n\n## Practical suggestions\n\nConcentrate bread, cloth and faith in a small desirable district before scaling the whole town. Budget working tools separately from construction tools. Keep a settler workforce near farms and resource gatherers. Reserve workshop plots before agriculture expands. Size winter food capacity from household demand and storage losses, not resident count or summer fishing. Place repair services before condition crosses the half-speed threshold.\n\nUse static constraints and parameter/configuration search to reject weak designs quickly; verify promising designs and thresholds in the real game. Use the coarse forecast as an estimate with its measured timing and cash errors, not as a precise victory predictor.\n\n## Scope and limitations\n\n${r.limits.map((l) => `- ${l}`).join("\n")}\n`+}++const escape = (s: unknown) => String(s).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """)+export const htmlReport = (r: Report) => {+ const end = r.construction.actual.at(-1)!, predicted = r.construction.prediction.rows.at(-1)!+ const saved = r.analyses.find((a) => a.name === "pr3-bot-minute-30")+ const table = (headers: string[], rows: unknown[][]) => `<div class="scroll"><table><thead><tr>${headers.map((h) => `<th>${escape(h)}</th>`).join("")}</tr></thead><tbody>${rows.map((row) => `<tr>${row.map((c) => `<td>${escape(c)}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Unchanged-rule balance results</title><style>:root{color-scheme:light dark}body{margin:0;font:14px system-ui;color:var(--foreground,CanvasText)}h2{font-size:17px;font-weight:500;margin:24px 0 12px}h3{font-size:15px;font-weight:500}p{line-height:1.5}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}th,td{text-align:left;padding:10px 6px;border-bottom:1px solid var(--border,GrayText);font-size:12px}th{font-weight:500}.scroll{overflow-x:auto}.muted{color:var(--muted-foreground,GrayText)}details{margin:16px 0}summary{cursor:pointer}code{overflow-wrap:anywhere}ul{padding-left:20px;line-height:1.55}.lead{font-weight:500}</style></head><body><h2>First citizens with unchanged game parameters</h2><p class="lead">${end.citizens} citizens verified in the real game. First citizen at ${r.construction.firstCitizenSecond ?? "never"} seconds on the authored construction fixture.</p><p class="muted">PR #3 · shared game rules · ${r.verification.filter((v) => v.pass).length}/${r.verification.length} controlled comparisons passed. This establishes a working progression example, not a full-term victory.</p>+${table(["At 10 minutes", "Model estimate", "Real game"], [["Citizens", predicted.citizens, end.citizens], ["Residents", predicted.residents, end.residents], ["Coins", predicted.coins, end.coins], ["First citizen, seconds", r.construction.prediction.firstCitizenSecond ?? "none", r.construction.firstCitizenSecond ?? "none"]])}+<h2>Economic constraints worth acting on</h2><ul><li>First citizen chain: ${r.firstCitizenChain.coins} coins; ${r.firstCitizenChain.materials.tools} construction tools + ${r.firstCitizenChain.workingTools} working tools. Fair land starts with ${r.firstCitizenChain.fairStartingTools} tools.</li><li>Settlers also consume cloth and take bread preferentially for food. Start with a small, desirable district.</li><li>Promotions remove workers from settler jobs. Keep farms and gatherers staffed.</li><li>Place workshops before farms can plant over their future plots.</li><li>Repair services have a ${r.analyses[0]!.repair.graceBeforeHalfSpeedSeconds}-second window between the repair threshold and half speed.</li></ul>+${saved ? `<h2>Original bot town · minute 30</h2><p>Only ${saved.household.filter((h) => h.potentialTier >= 2).length} of ${saved.household.length} homes pass the current desirability gate. Even granting unlimited needs and services, those homes hold at most ${saved.citizenGoal.housingCeilingAtCurrentDesirability} citizens/burghers, versus ${saved.citizenGoal.minimumAtPopulationGoal} required at the population goal.</p><p>Cloth capacity is ${n(saved.availableAfterWorkshops.cloth)}/min; supplying every home needs at least ${n(saved.needBounds.cloth.min)}/min. The current layout and broad distribution are bottlenecks before any rate tuning.</p>` : ""}+<h2>Workshop ceilings · output per minute</h2>${table(["Building", "Own crew + tool", "Apprentices + tool", "Apprentices, no tool"], r.capacity.map((c) => [c.kind, n(c.staffed), n(c.apprentices), n(c.apprenticesWithoutTools)]))}+<h2>Winter fishing · household capacity before losses</h2>${table(["Winter", "Fish/min", "Homes, late refresh", "Homes, frequent refresh"], r.winter.map((w) => [w.severity, n(w.fishPerMinute), n(w.noWasteHomesPerFishery), n(w.frequentRefreshHomesPerFishery)]))}+<details><summary>Verification and limitations</summary>${table(["Check", "Expected", "Actual", "Pass"], r.verification.map((v) => [v.name, n(v.expected), n(v.actual), v.pass]))}<ul>${r.limits.map((l) => `<li>${escape(l)}</li>`).join("")}</ul></details><p class="muted">Rules SHA-256 <code>${r.provenance.rulesSha256}</code></p></body></html>`+}diff --git a/tools/balance/scenario.ts b/tools/balance/scenario.tsnew file mode 100644index 0000000..fdcd5fd--- /dev/null+++ b/tools/balance/scenario.ts@@ -0,0 +1,99 @@+import { amounts, goodIds, type KindId, type Tier } from "../../src/content.ts"+import { GridBuilder, canPlace, doors, nearest, reach, type Use, type TileLike } from "../../src/grid.ts"+import { GRID } from "../../src/iso.ts"+import { shippedRules, type Rules } from "../../src/rules/config.ts"+import type { Snapshot } from "../../src/sim/headless.ts"+import type { ModelBuilding, ModelHome, Scenario } from "./types.ts"++export const scenarioGrid = (s: Scenario, rules: Rules = shippedRules): GridBuilder => {+ const grid = new GridBuilder(s.mask)+ for (const [i, l] of s.land.entries()) grid.claim(l.tile, -1 - i, l.type === "stone" || l.type === "ore" ? "rock" : l.type)+ for (const [i, p] of s.roads.entries()) grid.claim({ ...p, size: 1 }, -100000 - i, "road")+ for (const h of s.homes) grid.claim(h.tile, h.id, "house")+ for (const b of s.buildings) grid.claim({ ...b.tile, size: rules.kinds[b.kind].size }, b.id, "building")+ for (const [i, r] of (s.ruins ?? []).entries()) grid.claim(r, -200000 - i, "ruin")+ return grid+}++export const validateScenario = (s: Scenario, rules: Rules = shippedRules) => {+ if (!Number.isFinite(s.coins) || !Number.isFinite(s.approval) || !Number.isInteger(s.tick) || s.tick < 0) throw new Error("Invalid scenario state")+ const ids = [...s.homes.map((h) => h.id), ...s.buildings.map((b) => b.id)]+ if (ids.some((id) => !Number.isSafeInteger(id) || id <= 0) || new Set(ids).size !== ids.length) throw new Error("Scenario ids must be unique positive integers")+ const grid = new GridBuilder(s.mask)+ const lay = (tile: { readonly x: number; readonly y: number; readonly size: number }, id: number, use: Use) => {+ if (![tile.x, tile.y, tile.size].every(Number.isInteger) || tile.x < 0 || tile.y < 0 || tile.x + tile.size > GRID || tile.y + tile.size > GRID || tile.size <= 0 || !canPlace(grid.value(), tile)) throw new Error(`Invalid or overlapping tile: ${id}`)+ grid.claim(tile, id, use)+ }+ // Roads and construction may intentionally replace natural resources; buildings may not overlap one another.+ for (const [i, r] of s.roads.entries()) lay({ ...r, size: 1 }, -100000 - i, "road")+ for (const h of s.homes) {+ if (h.tile.size !== 1 || ![1, 2, 3].includes(h.tier) || h.residents < 0 || h.residents > rules.home.tiers[h.tier].residents || !Number.isInteger(h.residents)) throw new Error(`Invalid home: ${h.id}`)+ lay(h.tile, h.id, "house")+ }+ for (const b of s.buildings) {+ if (!rules.kinds[b.kind]) throw new Error(`Unknown kind: ${b.kind}`)+ if (b.tile.size !== rules.kinds[b.kind].size) throw new Error(`Invalid footprint: ${b.id}`)+ for (const g of goodIds) if (!Number.isFinite(b.stock[g]) || b.stock[g] < 0) throw new Error(`Invalid stock: ${b.id}/${g}`)+ lay({ ...b.tile, size: rules.kinds[b.kind].size }, b.id, "building")+ }+ for (const [i, r] of (s.ruins ?? []).entries()) lay(r, -200000 - i, "ruin")+}++/** Read-only adapter; loading a snapshot never starts the runtime. */+export const fromSnapshot = (snapshot: Snapshot, name = "saved-town", rules: Rules = shippedRules): Scenario => {+ const r = snapshot.resources, homes: ModelHome[] = [], buildings: ModelBuilding[] = [], land: Scenario["land"][number][] = [], roads: Scenario["roads"][number][] = []+ const ruins: TileLike[] = []+ for (const { id, components: c } of snapshot.entities) {+ const tile = c["Town/Tile"]+ if (!tile) continue+ if (c["Town/Road"]) roads.push({ x: tile.x, y: tile.y, ...(c["Town/Paved"] ? { paved: true } : {}) })+ if (c["Town/Ruin"]) ruins.push(tile)+ if (c["Town/House"] && !c["Town/Site"] && !c["Town/Rising"] && !c["Town/Burning"]) homes.push({ id, tile, ...c["Town/House"], condition: c["Town/Condition"]?.value ?? rules.conditionMax, meters: c["Town/Risk"] ?? { fire: 0, health: 0, order: 0 }, ...(c["Town/Sick"] ? { sick: true } : {}) })+ if (c["Town/Building"] && !c["Town/Burning"]) buildings.push({ id, kind: c["Town/Building"].kind, tile, stock: amounts(c["Town/Inventory"]?.stock ?? {}), condition: c["Town/Condition"]?.value ?? rules.conditionMax, paused: !!c["Town/Paused"], site: !!c["Town/Site"] || !!c["Town/Rising"] })+ const type = c["Town/Tree"] ? "tree" : c["Town/Rock"] ? c["Town/Rock"].ore ? "ore" : "stone" : c["Town/Water"] ? "water" : c["Town/Field"] ? "field" : null+ if (type) land.push({ tile, type, amount: c["Town/Rock"]?.amount ?? 1, growth: c["Town/Tree"]?.growth ?? c["Town/Field"]?.growth ?? 0 })+ }+ const charter = r["Town/Charter"]+ return { name, charter, tick: r["Town/Time"].tick - charter.founded, coins: r["Town/Treasury"].coins, approval: r["Town/Mood"].approval,+ policy: r["Town/Policy"], trade: { ...r["Town/Policy"], prices: r["Town/Market"].prices }, homes, buildings, roads, land, ruins, mask: r["Town/Land"].mask }+}++/** Small authored districts. The same geometry is used by analysis and controlled runtime verification. */+export const district = (name: string, tiers: ReadonlyArray<Tier>, kinds: ReadonlyArray<KindId>, branch = false, rules: Rules = shippedRules): Scenario => {+ const roads: Array<{ x: number; y: number; paved?: boolean }> = []+ for (let x = 8; x <= 54; x++) roads.push({ x, y: 30 })+ if (branch) for (const x of [15, 23, 31, 39, 47]) for (let y = 24; y <= 36; y++) if (y !== 30) roads.push({ x, y })+ const homeCells = Array.from({ length: 44 }, (_, i) => ({ x: 9 + i, y: 29, size: 1 })).filter((p) => !roads.some((r) => r.x === p.x && r.y === p.y))+ const houses = tiers.map((tier, i): ModelHome => ({ id: i + 1, tile: homeCells[i]!, tier, residents: rules.home.tiers[tier].residents,+ food: rules.home.lasts.food, bread: tier >= 2 ? rules.home.lasts.bread : 0, cloth: tier >= 2 ? rules.home.lasts.cloth : 0, faith: tier >= 2 ? rules.home.lasts.faith : 0,+ clock: 0, condition: rules.conditionMax, meters: { fire: 0, health: 0, order: 0 } }))+ const buildings: ModelBuilding[] = [], grid = new GridBuilder()+ for (const p of roads) grid.claim({ ...p, size: 1 }, -1, "road")+ for (const h of houses) grid.claim(h.tile, h.id, "house")+ const all = ["townhall" as const, ...kinds]+ for (const [i, kind] of all.entries()) {+ const k = rules.kinds[kind]+ let tile: { x: number; y: number; size: number } | undefined+ for (let x = 8; x <= 54 - k.size; x++) {+ const candidate = { x, y: 31, size: k.size }+ if (canPlace(grid.value(), candidate) && doors(grid.value(), candidate).length > 0) { tile = candidate; break }+ }+ if (!tile) throw new Error("District has no room for another building")+ const id = 100 + i+ buildings.push({ id, kind, tile, condition: rules.conditionMax, paused: false, site: false,+ stock: amounts(kind === "townhall" ? rules.lands.fair.stock : { tools: k.wear ? 1 : 0 }) })+ grid.claim(tile, id, "building")+ }+ const land: Scenario["land"][number][] = []+ for (const b of buildings) if (b.kind === "fishery") for (let x = b.tile.x; x < b.tile.x + b.tile.size; x++) land.push({ tile: { x, y: b.tile.y + b.tile.size, size: 1 }, type: "water", amount: 1, growth: 0 })+ for (const b of buildings) if (b.kind === "farm") {+ for (let i = 0; i < rules.kinds.farm.plants!.max; i++) land.push({ tile: { x: b.tile.x + i % 4, y: b.tile.y + b.tile.size + Math.floor(i / 4), size: 1 }, type: "field", amount: 1, growth: rules.grown.field })+ }+ return { name, charter: { size: "medium", term: 60, land: "fair", seed: 1000 }, tick: 0, coins: rules.lands.fair.coins, approval: 40,+ policy: { settlers: 100, citizens: 100 }, homes: houses, buildings, roads, land }+}++export const roadDistance = (s: Scenario, from: ModelBuilding, to: ModelBuilding | ModelHome, rules: Rules): number | null => {+ const grid = scenarioGrid(s, rules).value(), found = nearest(reach(grid, doors(grid, from.tile)), doors(grid, to.tile))+ return found?.distance ?? null+}diff --git a/tools/balance/types.ts b/tools/balance/types.tsnew file mode 100644index 0000000..11ce139--- /dev/null+++ b/tools/balance/types.ts@@ -0,0 +1,40 @@+import type { Amounts, CharterValue, KindId } from "../../src/content.ts"+import type { TileLike } from "../../src/grid.ts"+import type { Rules } from "../../src/rules/config.ts"+import type { Needs, Rates } from "../../src/rules/households.ts"+import type { TradePolicy } from "../../src/rules/trade.ts"++export interface ModelHome extends Needs {+ readonly id: number; readonly tile: TileLike; readonly residents: number; readonly clock: number+ readonly condition: number; readonly meters: { readonly fire: number; readonly health: number; readonly order: number }+ readonly sick?: boolean+}+export interface ModelBuilding {+ readonly id: number; readonly kind: KindId; readonly tile: TileLike; readonly stock: Amounts+ readonly condition: number; readonly paused: boolean; readonly site: boolean+}+export interface LandResource { readonly tile: TileLike; readonly type: "tree" | "stone" | "ore" | "water" | "field"; readonly amount: number; readonly growth: number }+export interface Scenario {+ readonly name: string; readonly charter: CharterValue & { readonly winters?: ReadonlyArray<"none" | "mild" | "normal" | "hard"> }+ readonly tick: number; readonly coins: number; readonly approval: number; readonly policy: Rates+ readonly roads: ReadonlyArray<{ readonly x: number; readonly y: number; readonly paved?: boolean }>+ readonly homes: ReadonlyArray<ModelHome>; readonly buildings: ReadonlyArray<ModelBuilding>+ readonly land: ReadonlyArray<LandResource>; readonly mask?: string+ readonly ruins?: ReadonlyArray<TileLike>+ readonly imports?: Partial<Record<keyof Amounts, number>>+ readonly exports?: Partial<Record<keyof Amounts, number>>+ readonly trade?: TradePolicy & { readonly prices?: Amounts }+}+export type Confidence = "exact" | "upper-bound" | "estimate"+export interface Finding { readonly code: string; readonly confidence: Confidence; readonly detail: string }+export interface Inputs { readonly rules: Rules; readonly scenario: Scenario }+export interface RecipeCapacity {+ readonly jobsPerMinute: number; readonly outputPerMinute: number; readonly inputPerMinute: number+ readonly toolsPerMinute: number; readonly meanJobTicks: number; readonly cadenceTicks: number+}+export interface BuildAction { readonly at: number; readonly kind: KindId | "home"; readonly tile: TileLike }+export interface ProjectionOptions {+ readonly seconds: number; readonly stepSeconds?: number; readonly builds?: ReadonlyArray<BuildAction>+ readonly feeding?: "fish" | "bread"; readonly visitSeconds?: number; readonly faith?: boolean+ readonly crown?: ReadonlyArray<{ readonly at: number; readonly good: keyof Amounts; readonly amount: number; readonly reward: number; readonly fine: number }>+}diff --git a/tools/balance/verify/builds.ts b/tools/balance/verify/builds.tsnew file mode 100644index 0000000..6739e30--- /dev/null+++ b/tools/balance/verify/builds.ts@@ -0,0 +1,26 @@+import { project } from "../model/project.ts"+import { fromSnapshot } from "../scenario.ts"+import { fixture, pushBuild } from "./fixture.ts"+import type { BuildAction, Inputs } from "../types.ts"++/** All construction uses ordinary player edits and actual costs. No resource injections during the run. */+export const verifyBuilds = (inputs: Inputs, builds: ReadonlyArray<BuildAction>, seconds = 600) => {+ const started = performance.now(), prediction = project(inputs, { seconds, builds }), messages: string[] = []+ const town = fixture(inputs.scenario, inputs.rules)+ town.ui.toast = (message) => messages.push(message)+ const actions = [...builds].sort((a, b) => a.at - b.at)+ const actual: Array<{ second: number; coins: number; residents: number; citizens: number; completed: number }> = []+ let firstCitizenSecond: number | null = null+ for (let second = 0; second <= seconds; second++) {+ while (actions.length > 0 && actions[0]!.at <= second) pushBuild(town, actions.shift()!)+ const snapshot = town.snapshot(), s = fromSnapshot(snapshot)+ const citizens = s.homes.filter((h) => h.tier >= 2).reduce((n, h) => n + h.residents, 0)+ if (citizens > 0 && firstCitizenSecond === null) firstCitizenSecond = second+ if (second % 60 === 0 || second === seconds) actual.push({ second, coins: s.coins, residents: s.homes.reduce((n, h) => n + h.residents, 0), citizens, completed: s.buildings.filter((b) => !b.site).length })+ if (second < seconds) town.run(1)+ }+ return { prediction, actual, firstCitizenSecond, messages, elapsedMs: performance.now() - started,+ errors: actual.map((a) => { const p = prediction.rows.find((p) => p.second === a.second)!; return { second: a.second, coins: p.coins - a.coins, residents: p.residents - a.residents, citizens: p.citizens - a.citizens } }),+ final: fromSnapshot(town.snapshot(), "bootstrap-final"),+ scope: "Authored starting district with paid roads/homes; real construction, production, staffing, prices, service walks and hazards. This is not a generated-map victory test." }+}diff --git a/tools/balance/verify/checks.ts b/tools/balance/verify/checks.tsnew file mode 100644index 0000000..7c94732--- /dev/null+++ b/tools/balance/verify/checks.ts@@ -0,0 +1,117 @@+import { amounts, type KindId } from "../../../src/content.ts"+import { type Rules } from "../../../src/rules/config.ts"+import { analyze } from "../model/analyze.ts"+import { recipeCapacity } from "../model/throughput.ts"+import { project } from "../model/project.ts"+import { assessTransfers } from "../model/transport.ts"+import { district, fromSnapshot } from "../scenario.ts"+import { component, fixture } from "./fixture.ts"+import type { Inputs, ProjectionOptions } from "../types.ts"++export interface Verification { readonly name: string; readonly confidence: string; readonly expected: number; readonly actual: number; readonly absoluteError: number; readonly tolerance: number; readonly pass: boolean; readonly detail: string }+const compare = (name: string, confidence: string, expected: number, actual: number, tolerance: number, detail: string): Verification =>+ ({ name, confidence, expected, actual, absoluteError: Math.abs(expected - actual), tolerance, pass: Math.abs(expected - actual) <= tolerance, detail })++export const verifyProduction = (rules: Rules, kind: KindId, apprentices: boolean, tools: boolean, worn = false): Verification => {+ let scenario = district(`production-${kind}`, [apprentices ? 1 : 2, apprentices ? 1 : 2], [kind], false, rules)+ scenario = { ...scenario, buildings: [...scenario.buildings, ...scenario.homes.map((h, i) => ({ id: 200 + i, kind: "garden" as const, tile: { x: h.tile.x, y: h.tile.y - 1, size: 1 }, condition: rules.conditionMax, paused: false, site: false, stock: amounts({}) }))] }+ const producer = scenario.buildings.find((b) => b.kind === kind)!, recipe = rules.kinds[kind].recipe!+ scenario = { ...scenario, homes: scenario.homes.map((h) => ({ ...h, food: 10000000, bread: apprentices ? 0 : 10000000, cloth: apprentices ? 0 : 10000000, faith: apprentices ? 0 : 10000000 })),+ buildings: scenario.buildings.map((b) => ({ ...b, stock: amounts(b.id === producer.id ? { tools: tools ? 1 : 0 } : {}), condition: b.id === producer.id && worn ? rules.condition.worn - 1 : b.condition })) }+ const town = fixture(scenario, rules)+ const seconds = 60+ let made = 0+ for (let second = 0; second < seconds; second++) {+ town.change((s) => {+ const stock = component(s, producer.id, "Town/Inventory").stock+ stock[recipe.output] = 0+ if (recipe.input) stock[recipe.input] = 8+ stock.tools = tools ? 1 : 0+ })+ town.run(1)+ made = component(town.snapshot(), producer.id, "Town/Recipe").made+ }+ const snapshot = town.snapshot(), staff = component(snapshot, producer.id, "Town/Staff")+ const expected = recipeCapacity(rules.kinds[kind], staff, tools ? 1 : 0, worn ? rules.condition.worn - 1 : rules.conditionMax, null, rules).jobsPerMinute+ return compare(`${kind}/${apprentices ? "apprentices" : "citizens"}/${tools ? "tool" : "no-tool"}/${worn ? "worn" : "new"}`, "cadence capacity", expected, made, 1,+ "Isolated workshop; inputs replenished and outputs removed each second. This verifies production cadence, not a sustainable economy.")+}++export const verifyEconomy = (rules: Rules): Verification => {+ const scenario = district("ledger", [1, 1, 1, 1], [], false, rules)+ const stable = { ...scenario, homes: scenario.homes.map((h) => ({ ...h, food: 10000000 })), buildings: scenario.buildings.map((b) => ({ ...b, stock: amounts({}) })) }+ const predicted = analyze({ rules, scenario: stable }, { services: false }).economy.roundedNetPerMinute+ const town = fixture(stable, rules), before = town.snapshot().resources["Town/Treasury"].coins+ town.run(60)+ const actual = town.snapshot().resources["Town/Treasury"].coins - before+ return compare("collection-rounding", "exact", predicted, actual, 0, "Stable settlers, no trade, no crown deadline, six actual ledger collections")+}++export const verifyTransport = (rules: Rules): Verification => {+ const base = district("carrier-capacity", Array(4).fill(1), ["lumberjack", "warehouse"], false, rules)+ const producer = base.buildings.find((b) => b.kind === "lumberjack")!, destination = base.buildings.find((b) => b.kind === "warehouse")!+ const scenario = { ...base, homes: base.homes.map((h) => ({ ...h, food: 10000000 })), buildings: base.buildings.map((b) => b.kind === "warehouse" ? { ...b, tile: { ...b.tile, x: 33 }, stock: amounts({}) } : { ...b, stock: amounts(b.kind === "townhall" ? { wood: rules.kinds.townhall.holds!.cap } : { tools: 1 }) }) }+ const town = fixture(scenario, rules)+ let delivered = 0+ for (let second = 0; second < 120; second++) {+ town.change((s) => { component(s, producer.id, "Town/Inventory").stock.wood = 8 })+ town.run(1)+ delivered = component(town.snapshot(), destination.id, "Town/Inventory").stock.wood+ }+ const budget = assessTransfers({ rules, scenario }, [{ source: producer.id, target: destination.id, good: "wood", goodsPerMinute: 1 }])+ const expected = budget.pools[0]!.availableCarrierSeconds / budget.routes[0]!.carrierSecondsPerMinute! * 2+ return compare("shared-carrier-capacity", "full-load capacity", expected, delivered, rules.kinds.lumberjack.carriers! * rules.transport.load,+ "Real full-load trips to a distant warehouse; tolerance permits one in-flight load per carrier at the measurement boundary")+}++/** Independent runtime excursions, compared with finite-path DP rather than another mathematical sampler. */+export const verifyService = (rules: Rules, branched: boolean, seeds = 16): Verification => {+ const base = district(branched ? "branched-faith" : "straight-faith", Array(10).fill(1), ["chapel"], branched, rules)+ const scenario = { ...base, homes: base.homes.map((h) => ({ ...h, food: 10000000 })), buildings: base.buildings.map((b) => ({ ...b, stock: amounts({}) })) }+ const chapel = scenario.buildings.find((b) => b.kind === "chapel")!, target = scenario.homes[scenario.homes.length - 1]!+ const predicted = analyze({ rules, scenario }).services.find((p) => p.source === chapel.id)!.contacts.find((c) => c.target === target.id)?.hitProbability ?? 0+ let trips = 0, hits = 0+ for (let seed = 0; seed < seeds; seed++) {+ const town = fixture({ ...scenario, charter: { ...scenario.charter, seed: 1000 + seed * 7919 } }, rules)+ const seen = new Map<number, { hit: boolean; completed: boolean }>()+ for (let second = 0; second < 80; second += 0.4) {+ town.run(0.4)+ const snapshot = town.snapshot()+ const walkers = snapshot.entities.filter((e) => e.components["Town/Roam"]?.service === "faith")+ for (const e of walkers) {+ const roam = e.components["Town/Roam"], route = e.components["Town/Route"]+ const record = seen.get(e.id) ?? { hit: false, completed: false }+ const cell = roam.back ? route.cells[0] : route.cells[route.index]+ if (!record.completed && cell && Math.abs(cell.x - target.tile.x) + Math.abs(cell.y - target.tile.y) === 1) record.hit = true+ if (roam.back && !record.completed) { trips += 1; hits += Number(record.hit); record.completed = true }+ seen.set(e.id, record)+ }+ }+ }+ const actual = trips > 0 ? hits / trips : 0, tolerance = 3 * Math.sqrt(Math.max(0.01, predicted * (1 - predicted)) / Math.max(1, trips)) + 0.03+ return compare(branched ? "branched-service-hit" : "straight-service-hit", "finite-path probability", predicted, actual, tolerance,+ `${hits}/${trips} completed excursions across ${seeds} fixed seeds; tolerance is 3 standard errors plus 0.03 sampling allowance. No basket depletion in faith service.`)+}++export const verifyProjection = (inputs: Inputs, options: ProjectionOptions) => {+ if (options.builds?.length || options.crown?.length || inputs.scenario.imports || inputs.scenario.exports) throw new Error("Use a build/trade verifier for external schedules; controlled forecast comparison requires no external injections")+ const prediction = project(inputs, options), town = fixture(inputs.scenario, inputs.rules)+ let firstCitizen: number | null = null+ const actual: Array<{ second: number; coins: number; residents: number; citizens: number }> = []+ for (let second = 0; second <= options.seconds; second++) {+ const s = fromSnapshot(town.snapshot()), citizens = s.homes.filter((h) => h.tier >= 2).reduce((n, h) => n + h.residents, 0)+ if (citizens > 0 && firstCitizen === null) firstCitizen = second+ if (second % 60 === 0 || second === options.seconds) actual.push({ second, coins: s.coins, residents: s.homes.reduce((n, h) => n + h.residents, 0), citizens })+ if (second < options.seconds) town.run(1)+ }+ return { prediction, actual, firstCitizen, errors: actual.map((a) => {+ const p = prediction.rows.find((p) => p.second === a.second)!+ return { second: a.second, coins: p.coins - a.coins, residents: p.residents - a.residents, citizens: p.citizens - a.citizens }+ }), scope: "Diagnostic forecast comparison; no claim of exact equivalence, human success or full-term victory" }+}++export const verify = (rules: Rules, seeds = 16): Verification[] => [+ verifyEconomy(rules), verifyTransport(rules),+ ...(["bakery", "weaver"] as const).flatMap((kind) => [verifyProduction(rules, kind, false, true), verifyProduction(rules, kind, true, true), verifyProduction(rules, kind, true, false), verifyProduction(rules, kind, false, false, true)]),+ verifyService(rules, false, seeds), verifyService(rules, true, seeds)+]diff --git a/tools/balance/verify/fixture.ts b/tools/balance/verify/fixture.tsnew file mode 100644index 0000000..baef74d--- /dev/null+++ b/tools/balance/verify/fixture.ts@@ -0,0 +1,53 @@+/** This is the only layer that imports the ECS runtime. Model inputs stay plain data. */+import { GRID } from "../../../src/iso.ts"+import { ownerAt } from "../../../src/grid.ts"+import { rolesOf, wearOf } from "../../../src/archetypes.ts"+import { headless, type Headless, type Snapshot } from "../../../src/sim/headless.ts"+import type { Rules } from "../../../src/rules/config.ts"+import { scenarioGrid, validateScenario } from "../scenario.ts"+import type { BuildAction, Scenario } from "../types.ts"++export const fixture = (scenario: Scenario, rules: Rules): Headless => {+ validateScenario(scenario, rules)+ const town = headless(scenario.charter, { rules })+ town.change((s) => {+ s.entities = []; s.relations = {}; s.nextEntity = Math.max(0, ...scenario.homes.map((h) => h.id), ...scenario.buildings.map((b) => b.id)) + 1+ const add = (components: Record<string, unknown>, id = s.nextEntity++) => s.entities.push({ id, components })+ for (const h of scenario.homes) add({+ "Town/Tile": h.tile, "Town/House": { tier: h.tier, residents: h.residents, food: h.food, bread: h.bread, cloth: h.cloth, faith: h.faith, clock: h.clock },+ ...Object.fromEntries(wearOf(rules).map(([d, v]) => [d.name, structuredClone(v)])),+ "Town/Risk": { ...h.meters, thefts: 0 }, "Town/Condition": { value: h.condition }+ }, h.id)+ for (const b of scenario.buildings) {+ const kind = rules.kinds[b.kind]+ const components: Record<string, unknown> = {+ "Town/Tile": b.tile, "Town/Building": { kind: b.kind }, "Town/Status": "idle",+ "Town/Staff": { needed: kind.workers, assigned: 0, apprentices: 0, nearby: 0 },+ ...Object.fromEntries(rolesOf(kind, rules).map(([d, v]) => [d.name, structuredClone(v)])),+ ...(b.kind === "townhall" ? { "Town/TownHall": {} } : {}), ...(b.paused ? { "Town/Paused": {} } : {})+ }+ if (components["Town/Inventory"]) (components["Town/Inventory"] as { stock: unknown }).stock = structuredClone(b.stock)+ if (components["Town/Condition"]) components["Town/Condition"] = { value: b.condition }+ add(components, b.id)+ }+ for (const p of scenario.roads) add({ "Town/Tile": { x: p.x, y: p.y, size: 1 }, "Town/Road": {}, ...(p.paved ? { "Town/Paved": {} } : {}) })+ const grid = scenarioGrid(scenario, rules).value()+ for (const [i, l] of scenario.land.entries()) {+ if (ownerAt(grid, l.tile.x, l.tile.y) !== -1 - i) continue+ const component = l.type === "tree" ? { "Town/Tree": { growth: l.growth } } : l.type === "field" ? { "Town/Field": { growth: l.growth } } : l.type === "water" ? { "Town/Water": {} } : { "Town/Rock": { amount: l.amount, ore: l.type === "ore" } }+ add({ "Town/Tile": l.tile, ...component })+ }+ s.resources["Town/Land"] = { mask: scenario.mask ?? "1".repeat(GRID * GRID), cells: GRID * GRID }+ s.resources["Town/Time"] = { tick: scenario.tick + 1 }+ s.resources["Town/Charter"] = { ...scenario.charter, founded: 1, winters: scenario.charter.winters ?? s.resources["Town/Charter"].winters }+ s.resources["Town/Treasury"] = { coins: scenario.coins }+ s.resources["Town/Mood"] = { ...s.resources["Town/Mood"], approval: scenario.approval }+ s.resources["Town/Policy"] = { settlers: scenario.policy.settlers, citizens: scenario.policy.citizens, sells: scenario.trade?.sells ?? [], buys: scenario.trade?.buys ?? [], reserve: scenario.trade?.reserve ?? rules.trade.reserve }+ if (scenario.trade?.prices) s.resources["Town/Market"] = { prices: scenario.trade.prices }+ s.resources["Town/Appeal"] = { cells: [] }+ })+ return town+}++export const pushBuild = (town: Headless, action: BuildAction) => town.edit(action.kind === "home" ? { type: "homes", cells: [action.tile] } : { type: "building", kind: action.kind, cell: action.tile, open: false })+export const component = (snapshot: Snapshot, id: number, name: string): any => snapshot.entities.find((e) => e.id === id)?.components[name]diff --git a/tsconfig.json b/tsconfig.jsonindex b3e0360..84887ac 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -1,5 +1,5 @@{- "include": ["src/**/*.ts", "scripts/**/*.ts", "test/**/*.ts", "vite.config.ts"],+ "include": ["src/**/*.ts", "scripts/**/*.ts", "tools/**/*.ts", "test/**/*.ts", "vite.config.ts"],"compilerOptions": {"noEmit": true,"target": "ES2022",