A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Replays in the dev build, and the simulation's input as plain data
SandroMaglione68ec744f129d
diff --git a/.gitignore b/.gitignoreindex a020a51..28b7584 100644--- a/.gitignore+++ b/.gitignore@@ -11,3 +11,5 @@ output/mobile-review/output/upgrades/output/look-ui/output/look-readme/+# Replays saved during dev play (see PLAYTEST.md): debug artifacts, never committed.+.replays/diff --git a/PLAYTEST.md b/PLAYTEST.mdnew file mode 100644index 0000000..9a69614--- /dev/null+++ b/PLAYTEST.md@@ -0,0 +1,72 @@+# Playtesting with replays++While you play the dev build, the game keeps the last minute of play. When+something looks wrong, save it as a replay: a small file the agent opens+without a browser to see exactly what happened, step by step.++## 1. Start the dev build++```sh+pnpm install+pnpm dev+```++Open the address it prints (usually http://localhost:5173). Replays work in+`pnpm dev` only; a production build carries none of this.++## 2. Save a replay++Any of these saves the last minute of play:++- **The button.** Press `\` (backslash) or the "◉ monitor" button in the+ corner to open the bevy-ts monitor, then **Save replay**. Do it right after+ you see the problem: the replay holds the last 60 seconds before the press.+- **By itself, when a step fails.** If the simulation fails, a replay is+ saved without you doing anything.+- **By itself, when a rule breaks.** The dev build checks rules after every+ step (today: the treasury always holds a whole number of coins). The first+ time one breaks, a replay is saved.++To try the loop out on purpose, open the game with `?replay-demo` at the end+of the address (http://localhost:5173/?replay-demo). That adds a rule made+to be broken: "fewer than ten buildings". Build until the town has ten, and a+replay is saved.++## 3. Where the file lands++In the terminal running `pnpm dev` you see a line like:++```+[bevy-ts] replay saved: .replays/2026-10-17T12-04-09.512Z-tick-1412.json (1800 ticks): invariant fewer than ten buildings broke at tick 1412: ...+```++The file is in `.replays/` in this folder. It is ignored by git: it is a+debugging aid, not part of the game.++## 4. What to tell the agent++Tell it three things:++1. **The file:** for example `.replays/2026-10-17T12-04-09.512Z-tick-1412.json`.+2. **What you saw:** "the baker's cart walked through the river", "I placed+ a market and the coins did not go down".+3. **Roughly when, if you pressed the button late:** "about ten seconds before+ I saved".++The agent then runs `pnpm replay <file>` to replay it headless, checks that+it replays the same way twice, finds the cause with the journal, cuts the few+steps that show it into a test, fixes it, and deletes the replay.++## For the agent++- `pnpm replay <file>`: replays it, compares the recorded checkpoints, replays+ twice for determinism, and prints the session report.+- `pnpm replay <file> --journal <from>-<to>`: what happened in those ticks.+- `pnpm replay <file> --extract <from>-<to> <out.json>`: a small replay with+ its own start, for building a test. Prefer an ordinary `headless` test when+ the start is easy to rebuild (`test/homes-edit.test.ts` came from one).+- A replay recorded before a schema change fails with "replay recorded with+ an older schema": ask for a new one.+- The recorder is wired in `src/dev/devtools.ts`; the simulation's input is+ the `Edits` source (plain edits), and its messages to the page are the+ `Toast` and `Selection` events.diff --git a/package.json b/package.jsonindex 2f787eb..88ee0ce 100644--- a/package.json+++ b/package.json@@ -14,6 +14,7 @@"balance:furniture": "node scripts/furniture.ts","balance:model:check": "node --test test/balance-model.test.ts","lint:game": "bevy-ts-devtools lint src/sim/headless.ts",+ "replay": "node scripts/replay.ts","check": "pnpm lint && pnpm lint:game && node scripts/check.ts","check:browser": "node scripts/check-browser.ts","check:phone": "node scripts/check-phone.ts",diff --git a/scripts/replay.ts b/scripts/replay.tsnew file mode 100644index 0000000..8888d42--- /dev/null+++ b/scripts/replay.ts@@ -0,0 +1,61 @@+/**+ * Opens a replay saved in dev play (`.replays/<time>.json`, see PLAYTEST.md)+ * headless, for an agent:+ *+ * pnpm replay <file> replays it, checks the checkpoints, replays twice for determinism, prints the report+ * pnpm replay <file> --journal <from>-<to> what happened in those ticks (recorder tick numbers)+ * pnpm replay <file> --extract <from>-<to> <out.json>+ * cuts those ticks into a small replay with its own start, for a test+ *+ * A replay is a debug artifact: once the bug is in a test, delete the file.+ */+import { readFileSync, writeFileSync } from "node:fs"++import { Replay } from "@typeonce/bevy-ts-devtools"++import { replayTarget } from "../src/sim/headless.ts"++const [path, flag, range, out] = process.argv.slice(2)+if (path === undefined) {+ console.error("usage: pnpm replay <file> [--journal <from>-<to> | --extract <from>-<to> <out.json>]")+ process.exit(2)+}+const parsed = Replay.parse(JSON.parse(readFileSync(path, "utf8")))+if (!parsed.ok) {+ console.error(`${path}: ${parsed.error._tag === "InvalidReplay" ? parsed.error.message : parsed.error._tag}`)+ process.exit(1)+}+const file = parsed.value+const bounds = (text: string | undefined): { readonly from: number; readonly to: number } => {+ const [from, to] = (text ?? "").split("-").map(Number)+ if (from === undefined || to === undefined || !Number.isInteger(from) || !Number.isInteger(to)) throw new Error(`expected <from>-<to>, got ${text}`)+ return { from, to }+}++console.log(`${path}: ${file.reason}`)+console.log(`ticks ${file.start.tick + 1}-${file.ticks.at(-1)?.tick ?? file.start.tick} of ${file.schedule}, recorded with devtools ${file.library}${file.start.pendingCommands > 0 ? `, ${file.start.pendingCommands} commands pending at the start (may diverge)` : ""}`)++if (flag === "--extract") {+ const extracted = Replay.extract(replayTarget, file, bounds(range))+ if (!extracted.ok) throw new Error(JSON.stringify(extracted.error))+ if (out === undefined) throw new Error("--extract needs an output file")+ writeFileSync(out, `${JSON.stringify(extracted.value)}\n`)+ console.log(`wrote ${out}: ticks ${extracted.value.ticks[0]?.tick}-${extracted.value.ticks.at(-1)?.tick}, starting from the end of tick ${extracted.value.start.tick}`)+} else {+ const opened = Replay.session(replayTarget, file)+ if (!opened.ok) {+ console.error(opened.error._tag === "SchemaMismatch" ? opened.error.message : JSON.stringify(opened.error))+ process.exit(1)+ }+ if (flag === "--journal") {+ const { from, to } = bounds(range)+ opened.value.play({ to })+ const first = opened.value.session.frame() - (to - file.start.tick) + (from - file.start.tick)+ console.log(opened.value.session.journal({ frames: [first, opened.value.session.frame()] }).text)+ } else {+ console.log(opened.value.play().text)+ const verified = Replay.verify(replayTarget, file)+ console.log(verified.ok ? verified.value.text : JSON.stringify(verified.error))+ console.log(opened.value.session.report().text)+ }+}diff --git a/src/dev/devtools.ts b/src/dev/devtools.tsnew file mode 100644index 0000000..6b24acc--- /dev/null+++ b/src/dev/devtools.ts@@ -0,0 +1,57 @@+/**+ * Dev builds only (`main.ts` imports this behind `import.meta.env.DEV`): the+ * bevy-ts monitor, and a replay recorder that keeps the last minute of+ * `simulate` and saves it to `.replays/` (through the dev server, see+ * `vite.config.ts`) when a step fails, when an invariant breaks, or when the+ * monitor's "Save replay" button is pressed. See PLAYTEST.md.+ */+import { Invariant, Monitor, Replay } from "@typeonce/bevy-ts-devtools"+import * as ReplayViteSink from "@typeonce/bevy-ts-devtools/ReplayViteSink"++import { STEP_SECONDS } from "../content.ts"+import { present } from "../present.ts"+import { Building, Game, Root, Treasury } from "../schema.ts"+import { simulate } from "../sim/index.ts"++/** The treasury holds a whole number of coins: a NaN or a fraction means some sum went wrong. */+export const CoinsAreWhole = Invariant.fromInspector(Game.Inspector("coins are whole", {+ resources: { treasury: Game.System.readResource(Treasury) }+}, ({ resources }) => {+ const coins = resources.treasury.get().coins+ return Number.isInteger(coins) ? undefined : `the treasury holds ${coins} coins`+}))++/**+ * A rule made to be broken, for trying the replay loop out (`?replay-demo` in+ * the URL): it breaks as soon as the town has ten buildings.+ */+export const FewerThanTenBuildings = Invariant.fromInspector(Game.Inspector("fewer than ten buildings", {+ queries: { buildings: Game.Query({ selection: { building: Game.Query.read(Building) } }) }+}, ({ queries }) => {+ const count = queries.buildings.each().length+ return count < 10 ? undefined : `the town has ${count} buildings (a demo rule: ?replay-demo)`+}))++export interface DevtoolsHost {+ readonly runtime: Replay.Recordable<typeof Game.schema, typeof Root> & Monitor.Target<typeof Game.schema, typeof Root>+ /** Where the monitor's panel goes. */+ readonly mount: HTMLElement+ readonly fetch: ReplayViteSink.Options["fetch"]+ readonly now: () => number+ /** Breaks `FewerThanTenBuildings` on purpose, to try a replay out. */+ readonly demo: boolean+}++export const attachDevtools = (host: DevtoolsHost) => {+ const recorder = Replay.recorder(host.runtime, {+ schedule: simulate,+ name: "simulate",+ keep: 60,+ stepSeconds: STEP_SECONDS,+ sink: ReplayViteSink.make({ fetch: host.fetch, onError: (error) => console.warn("The replay could not reach the dev server", error) }),+ now: host.now,+ saveOn: { failure: true, invariants: host.demo ? [CoinsAreWhole, FewerThanTenBuildings] : [CoinsAreWhole] }+ })+ const monitor = Monitor.attach(host.runtime, { schedules: { simulate, present }, mount: host.mount, replay: recorder })+ return { recorder, monitor }+}diff --git a/src/main.ts b/src/main.tsindex 2295c82..a6ada61 100644--- a/src/main.ts+++ b/src/main.ts@@ -15,7 +15,8 @@ import { present } from "./present.ts"import { browserStorage, describe, fileOf, latest, loadLatest, loadText, save, Storage, World } from "./save.ts"import type { CameraView } from "./render3d/scene.ts"import { download, sharedId } from "./share/client.ts"-import { BuildingNodes, Clock, FieldNodes, Game, Rules, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"+import { BuildingNodes, Clock, Edits, FieldNodes, Game, Rules, HouseNodes, RockNodes, RuinNodes, StageService, TreeNodes, Ui, WalkerNodes } from "./schema.ts"+import { editsOf } from "./sim/headless.ts"import { blankResources, simulate } from "./sim/index.ts"/** Minutes of game time between autosaves. */@@ -61,6 +62,7 @@ const start = async () => {const made = Game.Runtime.make({services: Game.Runtime.services(Game.Runtime.service(Ui, ui),+ Game.Runtime.service(Edits, editsOf(ui)),Game.Runtime.service(Rules, resolveRules()),Game.Runtime.service(Clock, clock),Game.Runtime.service(StageService, stage),@@ -72,7 +74,9 @@ const start = async () => {Game.Runtime.service(FieldNodes, fieldNodes),Game.Runtime.service(RuinNodes, ruinNodes)),- resources: blankResources()+ resources: blankResources(),+ // Dev builds carry the debug handle, for the monitor and the replay recorder.+ debug: import.meta.env.DEV})if (!made.ok) {mount.textContent = `The town could not start: ${JSON.stringify(made.error)}`@@ -87,6 +91,11 @@ const start = async () => {for (let i = 0; i < Math.round(seconds / STEP_SECONDS); i++) runtime.tick(simulate)}Object.assign(window, { town: { ui, runtime, advance, view: stage } })+ if (runtime.debug !== undefined) {+ // Loaded in dev only: the production bundle never includes devtools.+ const { attachDevtools } = await import("./dev/devtools.ts")+ attachDevtools({ runtime: { ...runtime, debug: runtime.debug }, mount: document.body, fetch: (url, init) => fetch(url, init), now: () => Date.now(), demo: new URLSearchParams(location.search).has("replay-demo") })+ }}// Saves are Effect programs over the browser's storage and this town (see `save.ts`);diff --git a/src/present.ts b/src/present.tsindex 3e6a11e..04f4d7d 100644--- a/src/present.ts+++ b/src/present.ts@@ -21,6 +21,8 @@ import {Appeal,Building,BuildingNodes,+ Selection,+ Toast,Burning,Census,Charter,@@ -366,6 +368,24 @@ const needIcons = { food: "food", bread: "bread", cloth: "cloth", faith: "faith"const appealColor = (v: number) =>v >= home.tiers[3].appeal ? 0x1f4f8f : v >= home.tiers[2].appeal ? GOOD : v >= 0 ? 0xc6d4e4 : v > home.squalid ? 0xeaa26a : BAD+/** What the simulation told the page this step: toasts to show, and the panel's selection. */+export const ShowFeedback = Game.System(+ "Town/ShowFeedback",+ {+ events: { toast: Game.System.readEvent(Toast), selection: Game.System.readEvent(Selection) },+ services: { ui: Game.System.service(Ui) }+ },+ ({ events, services }) => {+ const ui = services.ui+ for (const message of events.toast.all()) ui.toast(message)+ for (const change of events.selection.all()) {+ if ("select" in change) ui.selected = change.select+ else if ("clear" in change) ui.selected = null+ else if (ui.selected === change.clearIf) ui.selected = null+ }+ }+)+export const Interact = Game.System("Town/Interact",{@@ -2061,6 +2081,7 @@ export const Stroll = Game.System()export const present = Game.Schedule(+ ShowFeedback,Interact,DrawLand,RenderBuildings,diff --git a/src/schema.ts b/src/schema.tsindex 8b233f7..4a4c602 100644--- a/src/schema.ts+++ b/src/schema.ts@@ -19,7 +19,7 @@ import type { BuildingView, FieldView, HouseView, RockView, RuinView, TreeView,import type { GameScene } from "./render3d/scene.ts"import { goodIds, groundIds, kindIds, landIds, propIds, serviceIds, sizeIds, type Amounts, type GoodId } from "./content.ts"import type { Rules as RuleInputs } from "./rules/config.ts"-import type { UiValue } from "./ui.ts"+import type { Edit, UiValue } from "./ui.ts"export const Root = Schema.defineRoot("Town")@@ -420,7 +420,20 @@ export const Handed = Descriptor.TransientResource<HandedValue>()("Town/Handed")// ── Host services ─────────────────────────────────────────────────────────export const Rules = Descriptor.Service<RuleInputs>()("Town/Rules")+/**+ * The page's input to the simulation: each step takes the edits queued since+ * the last one (plain data, so a replay can record and play it back).+ */+export const Edits = Descriptor.Service<{ readonly snapshot: () => ReadonlyArray<Edit> }>()("Town/Edits")+/** The page itself, for the views only: the simulation never reads it (it talks to the page through `Toast` and `Selection`). */export const Ui = Descriptor.Service<UiValue>()("Town/Ui")++// ── What the simulation tells the page ────────────────────────────────────++/** A message for the player (an edit refused: "No room there"). */+export const Toast = Descriptor.Event<string>()("Town/Toast")+/** The panel's selection, changed by an edit: open a new building, or let go of one that is gone. */+export const Selection = Descriptor.Event<{ readonly select: number } | { readonly clear: true } | { readonly clearIf: number }>()("Town/Selection")/** The frame's length, for animation only: the simulation runs on `Time`. */export const Clock = Descriptor.Service<{ deltaSeconds: number; elapsed: number }>()("Town/Clock")export const StageService = Descriptor.Service<GameScene>()("Town/Stage")@@ -442,6 +455,7 @@ export const Game = Schema.bind(Time, Rng, Treasury, Ledger, Census, Policy, Charter, Land, Market, Mood, Crown, Fate, History, Chronicle, Guide, Appeal, Pantry, Fires,Grid, Stock, Flow, Handed},+ events: { Toast, Selection },relations: { WalkerOf, FieldOf }}),Rootdiff --git a/src/sim/edits.ts b/src/sim/edits.tsindex 220ee5a..8e528d8 100644--- a/src/sim/edits.ts+++ b/src/sim/edits.ts@@ -12,7 +12,7 @@ import { amounts, anA, builtCost, costText, goodIds, nextUpgrade, RESERVE_MAX, Timport { 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, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Rock, Service, Site, Status, Stock, Storage, Time, TownHall, Treasury, Ui, Upgraded, Works } from "../schema.ts"+import { Appeal, Building, Census, Charter, Chronicle, Crown, Fate, Fires, Game, Guide, Rules, History, House, Inventory, Land, Ledger, Market, maybe, Mood, Pantry, Park, Paved, Paused, Policy, Rising, Rng, Rock, Service, Site, Status, Stock, Storage, Time, TownHall, Toast, Treasury, Upgraded, Works, Edits, Selection } from "../schema.ts"import { salvageOf, salvageText, withWorks } from "../rules/salvage.ts"import { elapsed, rollWinters, termTicks, TileRead, useOf, write } from "./shared.ts"import type { Rules as RuleInputs } from "../rules/config.ts"@@ -81,14 +81,15 @@ export const ApplyEdits = Game.System(pantry: Game.System.writeResource(Pantry),fires: Game.System.writeResource(Fires)},- services: { ui: Game.System.service(Ui), rules: Game.System.service(Rules) }+ events: { toast: Game.System.writeEvent(Toast), selection: Game.System.writeEvent(Selection) },+ services: { edits: Game.System.service(Edits), rules: Game.System.service(Rules) }},- ({ queries, resources, services, commands }) => {+ ({ queries, resources, events, services, commands }) => {const rules = services.rulesconst { kinds, home, goods, grounds, props, lands, sizes, trade, roadCost: ROAD_COST, paveCost: PAVE_COST } = rules- const ui = services.ui- if (ui.edits.length === 0) return+ const queued = services.edits.snapshot()+ if (queued.length === 0) returnconst grid = new GridBuilder(resources.land.get().mask)const rows = queries.tiles.each()type Id = (typeof rows)[number]["entity"]["id"]@@ -162,7 +163,7 @@ export const ApplyEdits = Game.System(const playing = () => resources.fate.get().state === "playing"const t = elapsed(resources.time.get(), resources.charter.get())- edits: for (const edit of ui.edits.splice(0)) {+ edits: for (const edit of queued) {if (edit.type !== "newTown" && edit.type !== "nextTerm" && !playing()) continueswitch (edit.type) {case "building": {@@ -170,22 +171,22 @@ export const ApplyEdits = Game.System(const tile = { ...edit.cell, size: kind.size }if (!kind.buildable) breakif (!unlocked(kind, resources.census.get())) {- ui.toast(`${kind.title} ${lockReason(kind, resources.census.get())}`)+ events.toast.emit(`${kind.title} ${lockReason(kind, resources.census.get())}`)break}if (!canPlace(grid.value(), tile)) {- ui.toast("No room there")+ events.toast.emit("No room there")break}const short = afford(kind.cost)if (short) {- ui.toast(short)+ events.toast.emit(short)break}pay(kind.cost)const id = spawn(buildingDraft(kind, edit.cell), tile, "building")commands.insert(id, startOf(kind), ...rolesOf(kind, rules))- if (edit.open) ui.selected = id+ if (edit.open) events.selection.emit({ select: id })break}case "homes": {@@ -199,7 +200,7 @@ export const ApplyEdits = Game.System(const id = spawn(houseDraft(cell), tile, "house")commands.insert(id, ...houseStart(rules))}- if (short) ui.toast(short)+ if (short) events.toast.emit(short)break}case "roads": {@@ -214,7 +215,7 @@ export const ApplyEdits = Game.System(coins -= ROAD_COSTspawn(roadDraft(cell), tile, "road")}- if (short) ui.toast("Not enough coins")+ if (short) events.toast.emit("Not enough coins")break}case "pave": {@@ -235,7 +236,7 @@ export const ApplyEdits = Game.System(commands.insert(road, Game.Command.entry(Paved, {}))}take({ stone })- if (short) ui.toast(short)+ if (short) events.toast.emit(short)break}case "ground": {@@ -256,26 +257,26 @@ export const ApplyEdits = Game.System(else spawn(parkDraft(cell, edit.ground), tile, "park")}take(spent)- if (short) ui.toast(short)+ if (short) events.toast.emit(short)break}case "prop": {const piece = props[edit.prop]if (!unlocked(piece, resources.census.get())) {- ui.toast(`${piece.title} needs a bigger town`)+ events.toast.emit(`${piece.title} needs a bigger town`)break}const row = useAt(grid.value(), edit.cell.x, edit.cell.y) === "park"? queries.parks.each().find((r) => r.entity.id === ownerAt(grid.value(), edit.cell.x, edit.cell.y)): undefinedif (!row) {- ui.toast("Lay park ground first")+ events.toast.emit("Lay park ground first")break}if (row.data.park.get().prop === edit.prop) breakconst short = afford(piece.cost)if (short) {- ui.toast(short)+ events.toast.emit(short)break}pay(piece.cost)@@ -292,12 +293,12 @@ export const ApplyEdits = Game.System(if (use === "rock") {const rock = queries.rocks.get(owner)if (!rock.ok || rock.value.data.rock.get().amount > 1) {- ui.toast("Quarry it down first: only a worked face can be cleared")+ events.toast.emit("Quarry it down first: only a worked face can be cleared")break}}if (halls.has(owner)) {- ui.toast("The town hall stays")+ events.toast.emit("The town hall stays")break}// A park's furnishing goes before its ground.@@ -313,13 +314,13 @@ export const ApplyEdits = Game.System(const own = salvageOf(b ? builtCost(kinds[b.kind], maybe(built.value.data.upgraded)?.level ?? 0) : home.cost, maybe(built.value.data.site)?.owed ?? null, rules)const s = b ? withWorks(own, kinds[b.kind], maybe(built.value.data.works), rules) : ownif (s.fee > 0 && coins < s.fee) {- ui.toast(`Pulling it down costs ${s.fee} coins`)+ events.toast.emit(`Pulling it down costs ${s.fee} coins`)break}coins -= s.feeconst lost = stash(s.back)const said = salvageText(s)- if (said !== "") ui.toast(`${built.value.data.site.present ? "Cancelled" : "Pulled down"} · ${said}${lost > 0 ? ` (${lost} found no room in storage)` : ""}`)+ if (said !== "") events.toast.emit(`${built.value.data.site.present ? "Cancelled" : "Pulled down"} · ${said}${lost > 0 ? ` (${lost} found no room in storage)` : ""}`)}// A building's walkers and a farm's fields are its children, and go with it.commands.despawn(owner)@@ -330,7 +331,7 @@ export const ApplyEdits = Game.System(grid.use[k] = "empty"}}- if (ui.selected === owner) ui.selected = null+ events.selection.emit({ clearIf: owner })break}case "tax":@@ -359,7 +360,7 @@ export const ApplyEdits = Game.System(const c = resources.crown.get()if (!c.open) breakif ((left[c.good] ?? 0) < c.amount) {- ui.toast(`Not enough ${goods[c.good].title}`)+ events.toast.emit(`Not enough ${goods[c.good].title}`)break}let owed = c.amount@@ -374,7 +375,7 @@ export const ApplyEdits = Game.System(coins += c.rewardresources.crown.set({ ...c, open: false, met: c.met + 1, streak: 0 })write(resources.chronicle, t, `Sent the crown ${c.amount} ${goods[c.good].title}, for ${c.reward} coins.`)- ui.toast(`Sent · +${c.reward} coins`)+ events.toast.emit(`Sent · +${c.reward} coins`)break}case "nextTerm": {@@ -413,11 +414,11 @@ export const ApplyEdits = Game.System(if (!up || data.works.present || begun.has(row.value.entity.id) || data.site.present || data.rising.present) breakconst blocked = upgradeBlock(up, resources.fate.get().rank, rules)if (blocked) {- ui.toast(`${up.title} ${blocked}`)+ events.toast.emit(`${up.title} ${blocked}`)break}if (coins < up.cost.coins) {- ui.toast("Not enough coins")+ events.toast.emit("Not enough coins")break}coins -= up.cost.coins@@ -426,7 +427,7 @@ export const ApplyEdits = Game.System(commands.insert(row.value.entity.id, Game.Command.entry(Works, { owed, total: total(owed), done: 0, level: (level + 1) as 1 | 2 }))const was = (upgradeAt(kind, level)?.title ?? kind.title).toLowerCase()write(resources.chronicle, t, `Works begin on the ${was}: it is to be ${anA(up.title.toLowerCase())}.`)- ui.toast(`${up.title} · −${up.cost.coins} coins · carriers bring ${costText({ coins: 0, materials: up.cost.materials })}`)+ events.toast.emit(`${up.title} · −${up.cost.coins} coins · carriers bring ${costText({ coins: 0, materials: up.cost.materials })}`)break}case "reserve":@@ -469,7 +470,7 @@ export const ApplyEdits = Game.System(lines: [{ tick: 0, text: `Founded on ${sizes[charter.size].title}, ${richness.title} land, for a term of ${charter.term} minutes.`, alarm: false, at: null }]})resources.rng.set(charter.seed)- ui.selected = null+ events.selection.emit({ clear: true })// Nothing else this step: the new land is not on the grid yet.break edits}diff --git a/src/sim/headless.ts b/src/sim/headless.tsindex a846bad..fe1aabc 100644--- a/src/sim/headless.ts+++ b/src/sim/headless.ts@@ -4,9 +4,11 @@* this, pushing the same edits the page does and reading the world through* the same snapshots it saves.*/+import type * as Replay from "@typeonce/bevy-ts-devtools/Replay"+import { STEP_SECONDS, type CharterValue } from "../content.ts"import { resolveRules, type Rules as RuleInputs } from "../rules/config.ts"-import { Game, Rules, Ui } from "../schema.ts"+import { Edits, Game, Rules, Toast } from "../schema.ts"import { emptyPreview, type Edit, type UiValue } from "../ui.ts"import { blankResources, simulate } from "./index.ts"@@ -31,6 +33,26 @@ const blankUi = (charter: CharterValue, toast: (message: string) => void): UiValconst lintCharter: CharterValue = { size: "small", term: 45, land: "fair", seed: 7 }+/** The simulation's input from a page: each step takes the edits queued since the last. */+export const editsOf = (ui: Pick<UiValue, "edits">) => ({ snapshot: (): ReadonlyArray<Edit> => ui.edits.splice(0) })++/** The toasts the last step emitted (an inspector: it reads, and does not hold, the stream). */+const Toasts = Game.Inspector("Town/Toasts", { events: { toast: Game.System.readEvent(Toast) } }, ({ events }) => events.toast.all())++/**+ * The simulation on a debug runtime fed by a replay (see `Replay.session` and+ * `pnpm replay`): the recorded edits instead of a page's.+ */+export const replayTarget = (playback: Replay.Playback) => {+ const made = Game.Runtime.make({+ services: Game.Runtime.services(Game.Runtime.service(Edits, playback.source(Edits)), Game.Runtime.service(Rules, resolveRules())),+ resources: blankResources(),+ debug: true+ })+ if (!made.ok) throw new Error(`The town could not start: ${JSON.stringify(made.error)}`)+ return { runtime: made.value, schedules: { simulate } }+}+/*** What `bevy-ts-devtools lint src/sim/headless.ts` checks (`pnpm lint:game`,* part of `pnpm check`): the simulation on a debug runtime, and the page's@@ -40,7 +62,7 @@ export const lintTarget = async () => {// Loaded here only: tests and bots that use `headless` never load the renderer.const { present } = await import("../present.ts")const made = Game.Runtime.make({- services: Game.Runtime.services(Game.Runtime.service(Ui, blankUi(lintCharter, () => {})), Game.Runtime.service(Rules, resolveRules())),+ services: Game.Runtime.services(Game.Runtime.service(Edits, editsOf(blankUi(lintCharter, () => {}))), Game.Runtime.service(Rules, resolveRules())),resources: blankResources(),debug: true})@@ -49,13 +71,15 @@ export const lintTarget = async () => {}export const headless = (charter: CharterValue, options: { readonly toast?: (message: string) => void; readonly rules?: RuleInputs } = {}) => {- const ui = blankUi(charter, options.toast ?? (() => {}))- const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Ui, ui), Game.Runtime.service(Rules, options.rules ?? resolveRules())), resources: blankResources() })+ const toast = options.toast ?? (() => {})+ const ui = blankUi(charter, toast)+ const made = Game.Runtime.make({ services: Game.Runtime.services(Game.Runtime.service(Edits, editsOf(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 = () => {const stepped = runtime.tick(simulate)if (!stepped.ok) throw new Error(`A step failed: ${JSON.stringify(stepped.error)}`)+ for (const message of runtime.inspect(Toasts)) toast(message)}const town = {ui,diff --git a/test/homes-edit.test.ts b/test/homes-edit.test.tsnew file mode 100644index 0000000..0828757--- /dev/null+++ b/test/homes-edit.test.ts@@ -0,0 +1,26 @@+/**+ * From a replay (the replay loop's dry run, see PLAYTEST.md): a homes edit+ * along a fresh road puts every cottage down in the same step, empty. The+ * replay showed ApplyEdits spawning all four in tick 2; this keeps it so+ * without the replay file.+ */+import assert from "node:assert/strict"+import { test } from "node:test"++import { STEP_SECONDS } from "../src/content.ts"+import { headless } from "../src/sim/headless.ts"++test("a homes edit along a fresh road raises every cottage in one step, empty", () => {+ const town = headless({ size: "small", term: 45, land: "fair", seed: 7 })+ const homes = [{ x: 35, y: 30 }, { x: 36, y: 30 }, { x: 37, y: 30 }, { x: 38, y: 30 }]+ town.edit(+ { type: "roads", cells: Array.from({ length: 9 }, (_, i) => ({ x: 34 + i, y: 31 })) },+ { type: "homes", cells: homes }+ )+ town.run(STEP_SECONDS)+ const houses = town.snapshot().entities.filter((entity) => entity.components["Town/House"] !== undefined)+ assert.deepEqual(+ houses.map((entity) => ({ tile: entity.components["Town/Tile"], residents: entity.components["Town/House"].residents })),+ homes.map((cell) => ({ tile: { ...cell, size: 1 }, residents: 0 }))+ )+})diff --git a/vite.config.ts b/vite.config.tsindex 86d678e..04c7704 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,9 +1,12 @@import { defineConfig } from "vite"+import * as ReplayVitePlugin from "@typeonce/bevy-ts-devtools/ReplayVitePlugin"+import { sharesInDev } from "./src/server/dev.ts"export default defineConfig({- plugins: [sharesInDev()],+ // In `pnpm dev`, replays saved in the page land in .replays/ (see PLAYTEST.md).+ plugins: [sharesInDev(), ReplayVitePlugin.plugin()],environments: {// The pages are the client's alone: on deploy, the Worker (src/server/worker.ts) builds as an environment of its own.client: {