Claude Claude Opus 5 commited on
Commit
0da037f
Β·
unverified Β·
1 Parent(s): 0974cb1

Tier 1, step 4a: five reproduced engine defects (A1-A4, A11)

Browse files

Every fix was preceded by a test verified red against the real behaviour,
and the two A1 tests were additionally re-run with the fix reverted to
prove they bite rather than passing incidentally.

A1 β€” keepFollowingLeader decided its leader was gone by hp alone. A
follow-leader order holds a live object REFERENCE, and two removal paths
delete a unit that is still at full hp: deployColonyShip and
updateUnitRecycle. Escorting a colony ship to a site and deploying it is
the canonical Odyssey play, and it left both escorts permanently pinned to
a ship no longer in state.units, orbiting its frozen last position. They
still accept new direct orders, so it read as "my units randomly stopped
obeying the formation". The check now asks the state, not the field.
(escort orders were always immune β€” escortSlot resolves through
state.units.get every tick.)

A2 β€” the squad-release loop spliced the array it was iterating. A for...of
iterator is index-based, so every splice skipped the next element:
dropping two ADJACENT followers released only the first, leaving the
second with squadLeader pointing at a leader whose own list no longer
contained it β€” the exact bidirectional invariant setSquadLeader's comment
promises. The existing test drops one follower, and the last one, which is
why it never caught this.

A3 β€” countLogistics reset the `servers` tally for a factory or a fuel
burner by re-listing those kinds by hand. inputNeedsOf later grew a third,
`def.ammo`, and the list wasn't updated: a Torpedo Battery is neither, and
has no store cap, so its tally only ever climbed. After one resupply run it
sat permanently above MAX_SERVERS and assignService rejected it forever β€”
the top-tier static defense silently became a hand-micro structure the
moment it first shot its magazine dry, with no event and no badge. This is
verbatim the bug already fixed and regression-tested for power stations
twenty lines above. It now resets from inputNeedsOf itself, so a future
fourth input-taking kind is covered automatically.

A4 β€” updateWonder clamped the CHARGE but not the SPEND, and nothing
returned early at full charge. A standalone endless game is masked by
checkEndlessWin ending the match, but a galaxy Gate is explicitly "a
milestone, never a win β€” play forever" while sim.js calls updateWonder
every tick, so a COMPLETED Gate kept eating its feed per sim-second
indefinitely β€” in the three scarcest goods in the game, on the winning
line of play, against a Leviathan that competes for the same three. Fixed
with an early return, plus capping the step at the charge remaining so the
final partial tick stops overpaying for charge it never banks.

A11 β€” cachedPowerThrottle keys on state.tick, so a state without one
stored `_powerCacheTick = undefined` and the test `undefined !== undefined`
was false forever: the first result froze for the life of the state. Such
a state now simply doesn't get a cache. Alongside it, buildingConcern's
factory branch called the buffer full at storeRoom <= 1e-6 while
updateProduction produces for ANY positive room, so the badge could read
"bufferFull" while the sim was still banking output β€” the precise
badge/sim disagreement its own comment promises cannot happen. Two
load-bearing comments that had become false are corrected in the same
pass, including the cache's own caller list, which claimed the HUD never
touches it while buildingConcern (ninety lines below, same file) calls it
and renderBuildings.js calls that every frame.

Suite: 1935 pass, 0 fail. typecheck clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XZ2MLqDX3grEPTJpwivWZX

engine/commands.js CHANGED
@@ -159,7 +159,11 @@ function dispatchFormation(units, x, y, formation, queue, makeLeaderOrder) {
159
  // isn't part of it this time is released β€” and actually stopped, not just unlinked, so a
160
  // dropped unit doesn't silently keep chasing a leader that no longer lists it.
161
  if (leader.squadFollowers) {
162
- for (const old of leader.squadFollowers) {
 
 
 
 
163
  if (!newFollowers.includes(old)) { setSquadLeader(old, null); old.order = null; }
164
  }
165
  }
 
159
  // isn't part of it this time is released β€” and actually stopped, not just unlinked, so a
160
  // dropped unit doesn't silently keep chasing a leader that no longer lists it.
161
  if (leader.squadFollowers) {
162
+ // Iterate a SNAPSHOT: setSquadLeader(old, null) splices `old` out of this very array, and a
163
+ // for...of iterator is index-based, so mutating in place skips the next element. Dropping two
164
+ // adjacent followers used to release only the first, leaving the second with squadLeader
165
+ // pointing at a leader whose own list no longer contained it.
166
+ for (const old of [...leader.squadFollowers]) {
167
  if (!newFollowers.includes(old)) { setSquadLeader(old, null); old.order = null; }
168
  }
169
  }
engine/haul.js CHANGED
@@ -145,6 +145,24 @@ export function payAIUpkeep(state, unit, dt) {
145
  // SINGLE-commodity size, so "larger capacity" falls out of the same def field its freight panel
146
  // already shows, no duplicated number to keep in sync.
147
  function tripCapacity(def) { return def.cargoCap ?? def.cargoHold ?? 0; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  /**
150
  * Tally, per building, how many workers are hauling from it (`haulers`) or servicing it
@@ -157,11 +175,13 @@ function tripCapacity(def) { return def.cargoCap ?? def.cargoHold ?? 0; }
157
  export function countLogistics(state) {
158
  for (const b of state.buildings.values()) {
159
  if (storeCapOf(b.type) > 0) b.haulers = 0;
160
- // A factory (recipeOf) OR a fuel-burning power station (BUILDINGS[type].combust) both take
161
- // SERVICE workers β€” see inputNeedsOf below β€” so both need this tally reset each tick too, or
162
- // a power station's `servers` count would only ever climb, permanently maxing out at
163
- // MAX_SERVERS after its first worker and locking out every one after.
164
- if (recipeOf(b) || BUILDINGS[b.type]?.combust) b.servers = 0;
 
 
165
  }
166
  for (const u of state.units.values()) {
167
  if (UNITS[u.type]?.cargoHold) u.ferriers = 0;
@@ -221,23 +241,6 @@ function loadFrom(store, unit, cargoCap) {
221
  return true;
222
  }
223
 
224
- // What a building needs hauled IN, as a commodity→"units per batch" map — a real recipe's `in`
225
- // (every key but "energy", a live Power draw never hauled/stored) for a factory, a synthesized
226
- // one (each accepted fuel weighted 1) for a fuel-burning power station (def.combust.fuels), or a
227
- // synthesized one (its single feed commodity weighted by its own perShot cost) for an ammo-fed
228
- // static defense (def.ammo β€” the Torpedo Battery): "a batch" there means "one shot's worth", so
229
- // neededInput's SUPPLY_BATCHES top-up target reads as "keep ~SUPPLY_BATCHES shots banked", the
230
- // same shape a factory's own per-batch ingredient count already gives it. Null for anything that
231
- // needs none of the three. The single place that unifies them so neededInput/assignService/
232
- // updateService don't need their own factory-vs-power-station-vs-battery branch.
233
- function inputNeedsOf(building) {
234
- const recipe = recipeOf(building);
235
- if (recipe) return recipe.in;
236
- const def = BUILDINGS[building.type];
237
- if (def?.combust) return Object.fromEntries(def.combust.fuels.map(f => [f, 1]));
238
- if (def?.ammo) return { [def.ammo.com]: def.ammo.perShot };
239
- return null;
240
- }
241
 
242
  // The input commodity a building most needs and the treasury can supply: the one with the fewest
243
  // batches buffered (below the top-up target) that the owner has in stock AND that still has room
 
145
  // SINGLE-commodity size, so "larger capacity" falls out of the same def field its freight panel
146
  // already shows, no duplicated number to keep in sync.
147
  function tripCapacity(def) { return def.cargoCap ?? def.cargoHold ?? 0; }
148
+ // What a building needs hauled IN, as a commodity→"units per batch" map — a real recipe's `in`
149
+ // (every key but "energy", a live Power draw never hauled/stored) for a factory, a synthesized
150
+ // one (each accepted fuel weighted 1) for a fuel-burning power station (def.combust.fuels), or a
151
+ // synthesized one (its single feed commodity weighted by its own perShot cost) for an ammo-fed
152
+ // static defense (def.ammo β€” the Torpedo Battery): "a batch" there means "one shot's worth", so
153
+ // neededInput's SUPPLY_BATCHES top-up target reads as "keep ~SUPPLY_BATCHES shots banked", the
154
+ // same shape a factory's own per-batch ingredient count already gives it. Null for anything that
155
+ // needs none of the three. The single place that unifies them so neededInput/assignService/
156
+ // updateService don't need their own factory-vs-power-station-vs-battery branch.
157
+ function inputNeedsOf(building) {
158
+ const recipe = recipeOf(building);
159
+ if (recipe) return recipe.in;
160
+ const def = BUILDINGS[building.type];
161
+ if (def?.combust) return Object.fromEntries(def.combust.fuels.map(f => [f, 1]));
162
+ if (def?.ammo) return { [def.ammo.com]: def.ammo.perShot };
163
+ return null;
164
+ }
165
+
166
 
167
  /**
168
  * Tally, per building, how many workers are hauling from it (`haulers`) or servicing it
 
175
  export function countLogistics(state) {
176
  for (const b of state.buildings.values()) {
177
  if (storeCapOf(b.type) > 0) b.haulers = 0;
178
+ // Reset from the SINGLE SOURCE OF TRUTH for "does this building take service workers".
179
+ // This used to re-list the kinds by hand (recipeOf || combust), and when inputNeedsOf grew a
180
+ // third β€” an ammo-fed Torpedo Battery β€” the list wasn't updated, so that one building's
181
+ // `servers` count could only ever climb: permanently past MAX_SERVERS after its first worker,
182
+ // locking out every one after, forever. Asking inputNeedsOf covers any future fourth kind
183
+ // automatically, which is the whole point of it existing.
184
+ if (inputNeedsOf(b)) b.servers = 0;
185
  }
186
  for (const u of state.units.values()) {
187
  if (UNITS[u.type]?.cargoHold) u.ferriers = 0;
 
241
  return true;
242
  }
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
  // The input commodity a building most needs and the treasury can supply: the one with the fewest
246
  // batches buffered (below the top-up target) that the owner has in stock AND that still has room
engine/industry.js CHANGED
@@ -297,9 +297,16 @@ export function powerThrottle(state, owner) {
297
  // sim.js's countMiners/countLogistics/countMenderTargets ("freeze it once per tick, reuse it"), the
298
  // real computation now runs at most once per owner per tick no matter how many factories/rigs ask.
299
  // Keyed on state.tick, so it self-invalidates the instant a real tick advances β€” and any caller that
300
- // never goes through updateProduction/updatePlasmaRig (powerThrottle itself, the HUD, repair.js,
301
- // aiIndustry.js, a direct test call…) never touches this cache and stays exactly as fresh as before.
 
 
302
  function ownerPowerCache(state) {
 
 
 
 
 
303
  if (!state._powerCache || state._powerCacheTick !== state.tick) {
304
  state._powerCache = Object.create(null);
305
  state._powerCacheTick = state.tick;
@@ -311,6 +318,7 @@ function ownerPowerCache(state) {
311
  * powerThrottle fresh β€” same formula, same inputs β€” just computed at most once per owner per tick. */
312
  export function cachedPowerThrottle(state, owner) {
313
  const cache = ownerPowerCache(state);
 
314
  const cached = cache[owner];
315
  if (cached !== undefined) return cached;
316
  return cache[owner] = powerThrottle(state, owner);
@@ -419,6 +427,10 @@ export function buildingConcern(state, b) {
419
  if (com === "energy") continue;
420
  if ((input[com] || 0) < recipe.in[com] * iceMult) return { level: "bad", code: "starved" };
421
  }
422
- if (storeRoom(b) <= 1e-6) return { level: "bad", code: "bufferFull" };
 
 
 
 
423
  return throttle < 0.995 ? { level: "warn", code: "throttled" } : null;
424
  }
 
297
  // sim.js's countMiners/countLogistics/countMenderTargets ("freeze it once per tick, reuse it"), the
298
  // real computation now runs at most once per owner per tick no matter how many factories/rigs ask.
299
  // Keyed on state.tick, so it self-invalidates the instant a real tick advances β€” and any caller that
300
+ // never goes through updateProduction/updatePlasmaRig (powerThrottle itself, repair.js,
301
+ // aiIndustry.js, a direct test call…) never touches this cache and stays exactly as fresh as
302
+ // before. NOTE: the HUD is NOT in that list β€” buildingConcern, ninety lines below in this very
303
+ // file, calls cachedPowerThrottle, and renderBuildings.js calls buildingConcern every frame.
304
  function ownerPowerCache(state) {
305
+ // A state with NO tick counter can't be keyed safely: storing `_powerCacheTick = undefined` makes
306
+ // the invalidation test `undefined !== undefined` false forever, freezing the very first result
307
+ // for the life of the state. That's reachable from the hand-built stubs in test/industry.test.js
308
+ // and from any caller that doesn't come through tick(). Such a state simply doesn't get a cache.
309
+ if (!Number.isFinite(state.tick)) return null;
310
  if (!state._powerCache || state._powerCacheTick !== state.tick) {
311
  state._powerCache = Object.create(null);
312
  state._powerCacheTick = state.tick;
 
318
  * powerThrottle fresh β€” same formula, same inputs β€” just computed at most once per owner per tick. */
319
  export function cachedPowerThrottle(state, owner) {
320
  const cache = ownerPowerCache(state);
321
+ if (!cache) return powerThrottle(state, owner);
322
  const cached = cache[owner];
323
  if (cached !== undefined) return cached;
324
  return cache[owner] = powerThrottle(state, owner);
 
427
  if (com === "energy") continue;
428
  if ((input[com] || 0) < recipe.in[com] * iceMult) return { level: "bad", code: "starved" };
429
  }
430
+ // Match updateProduction's own gate EXACTLY: it caps frac by storeRoom/outPerBatch and produces
431
+ // whenever `frac > 0`, i.e. for ANY positive room. A 1e-6 epsilon here read "bufferFull" while the
432
+ // sim was still banking output, which is precisely the badge/sim disagreement the comment above
433
+ // promises can't happen. (The rig branch's 1e-9 is right β€” it mirrors rig.js's own threshold.)
434
+ if (storeRoom(b) <= 0) return { level: "bad", code: "bufferFull" };
435
  return throttle < 0.995 ? { level: "warn", code: "throttled" } : null;
436
  }
engine/movement.js CHANGED
@@ -96,7 +96,13 @@ export function keepFormationStation(state, unit, speed, dt) {
96
  export function keepFollowingLeader(state, unit, speed, dt) {
97
  const o = unit.order;
98
  const leader = o.leader;
99
- if (!leader || leader.hp <= 0) { unit.order = null; return false; }
 
 
 
 
 
 
100
  stepToward(state, unit, leader.x + o.offsetX, leader.y + o.offsetY, speed, dt);
101
  return true;
102
  }
 
96
  export function keepFollowingLeader(state, unit, speed, dt) {
97
  const o = unit.order;
98
  const leader = o.leader;
99
+ // Ask the STATE whether the leader still exists, not just its hp. A follow-leader order holds a
100
+ // live object REFERENCE, and two removal paths delete a unit that is still at full hp β€”
101
+ // deployColonyShip (engine/colony.js) and updateUnitRecycle (engine/recycle.js). Escorting a
102
+ // colony ship and deploying it is the canonical Odyssey play, and an hp-only check left both
103
+ // escorts permanently pinned to a ship no longer in state.units, orbiting its frozen last
104
+ // position. (escort orders are immune: escortSlot resolves through state.units.get every tick.)
105
+ if (!leader || leader.hp <= 0 || !state.units.has(leader.id)) { unit.order = null; return false; }
106
  stepToward(state, unit, leader.x + o.offsetX, leader.y + o.offsetY, speed, dt);
107
  return true;
108
  }
engine/wonder.js CHANGED
@@ -40,7 +40,18 @@ export function updateWonder(state, building, dt) {
40
  // via powerDraw, but the charge itself isn't power-gated, so a sniped Reactor
41
  // can't stall it), clamped by the scarcest fed good in stock (measured in "full
42
  // charges' worth", so we never overspend).
43
- let p = dt / def.chargeTime;
 
 
 
 
 
 
 
 
 
 
 
44
  for (const com in feed) {
45
  const perCharge = feed[com] * def.chargeTime;
46
  if (perCharge > 0) p = Math.min(p, (res[com] || 0) / perCharge);
@@ -48,7 +59,7 @@ export function updateWonder(state, building, dt) {
48
  if (!(p > 0)) return;
49
 
50
  for (const com in feed) res[com] = (res[com] || 0) - p * feed[com] * def.chargeTime;
51
- building.charge = Math.min(1, (building.charge || 0) + p);
52
  state.events.push({ type: "wonderCharging", charge: building.charge, x: building.x, y: building.y, owner: building.owner });
53
  }
54
 
 
40
  // via powerDraw, but the charge itself isn't power-gated, so a sniped Reactor
41
  // can't stall it), clamped by the scarcest fed good in stock (measured in "full
42
  // charges' worth", so we never overspend).
43
+ // A FINISHED Gate consumes nothing. Nothing used to stop it: the charge clamped to 1 but the
44
+ // spend didn't, and while a standalone endless game is masked by checkEndlessWin ending the
45
+ // match, a galaxy Gate is explicitly "a milestone, never a win β€” play forever"
46
+ // (engine/victory.js) with sim.js calling this every tick. So a completed Gate went on burning
47
+ // its feed per sim-second forever, in the three scarcest goods in the game, on the winning line
48
+ // of play β€” and the Leviathan competes for exactly those three.
49
+ const charge = building.charge || 0;
50
+ if (charge >= 1) return;
51
+
52
+ // Cap the step at the charge actually REMAINING, so the final partial tick pays for what it
53
+ // banks rather than for a whole step it only partly used.
54
+ let p = Math.min(dt / def.chargeTime, 1 - charge);
55
  for (const com in feed) {
56
  const perCharge = feed[com] * def.chargeTime;
57
  if (perCharge > 0) p = Math.min(p, (res[com] || 0) / perCharge);
 
59
  if (!(p > 0)) return;
60
 
61
  for (const com in feed) res[com] = (res[com] || 0) - p * feed[com] * def.chargeTime;
62
+ building.charge = Math.min(1, charge + p);
63
  state.events.push({ type: "wonderCharging", charge: building.charge, x: building.x, y: building.y, owner: building.owner });
64
  }
65
 
test/colony.test.js CHANGED
@@ -2,12 +2,14 @@ import { test } from "node:test";
2
  import assert from "node:assert/strict";
3
  import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";
4
  import { deployColonyShip, hasColonyShip, COLONY_SHIP_WORKERS, packCommandCenter, PACK_COST } from "../engine/colony.js";
5
- import { canPlaceBuilding } from "../engine/colliders.js";
6
  import { queueProduction } from "../engine/production.js";
7
  import { checkEndlessLoss } from "../engine/victory.js";
8
  import { createGalaxy, activeState, checkDomination, galaxyStatus } from "../engine/galaxy.js";
9
  import { serializeGame, deserializeGame } from "../engine/persist.js";
10
  import { runAI } from "../engine/ai.js";
 
 
11
 
12
  const THINK = 1.5;
13
  const playerShip = s => [...s.units.values()].find(u => u.owner === "player" && u.type === "colonyship");
@@ -241,3 +243,33 @@ test("the AI keeps at most one colony ship in flight", () => {
241
  "no second ship is produced while one is in flight");
242
  assert.ok(!cc.queue.some(j => j.unitType === "colonyship"), "and none queued at the CC");
243
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import assert from "node:assert/strict";
3
  import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";
4
  import { deployColonyShip, hasColonyShip, COLONY_SHIP_WORKERS, packCommandCenter, PACK_COST } from "../engine/colony.js";
5
+ import { canPlaceBuilding, findPlacement } from "../engine/colliders.js";
6
  import { queueProduction } from "../engine/production.js";
7
  import { checkEndlessLoss } from "../engine/victory.js";
8
  import { createGalaxy, activeState, checkDomination, galaxyStatus } from "../engine/galaxy.js";
9
  import { serializeGame, deserializeGame } from "../engine/persist.js";
10
  import { runAI } from "../engine/ai.js";
11
+ import { issueMove } from "../engine/commands.js";
12
+ import { tick } from "../engine/sim.js";
13
 
14
  const THINK = 1.5;
15
  const playerShip = s => [...s.units.values()].find(u => u.owner === "player" && u.type === "colonyship");
 
243
  "no second ship is produced while one is in flight");
244
  assert.ok(!cc.queue.some(j => j.unitType === "colonyship"), "and none queued at the CC");
245
  });
246
+
247
+ test("escorts following a colony ship are released the moment it deploys β€” not left chasing a removed ship (A1)", () => {
248
+ // keepFollowingLeader decides its leader is gone by hp alone. Every combat/bomb death zeroes hp
249
+ // before removeEntity, so that holds there β€” but deployColonyShip removes the ship at FULL hp.
250
+ // Escorting a colony ship to a site and deploying it is the canonical Odyssey play, and it left
251
+ // both escorts permanently pinned to a unit no longer in state.units, orbiting its frozen last
252
+ // position. They still accept a new direct order, so it reads as "my units randomly stopped
253
+ // obeying the formation" rather than as a bug.
254
+ const st = createGameState({ planetId: "ferros", seed: 7 });
255
+ const spot = findPlacement(st, "command", st.map.width / 2, st.map.height / 2);
256
+ assert.ok(spot, "fixture sanity: an open deploy site exists");
257
+ const ship = makeUnit("colonyship", "player", spot.x, spot.y);
258
+ st.units.set(ship.id, ship);
259
+ const e1 = makeUnit("skiff", "player", ship.x + 20, ship.y);
260
+ const e2 = makeUnit("skiff", "player", ship.x - 20, ship.y);
261
+ st.units.set(e1.id, e1);
262
+ st.units.set(e2.id, e2);
263
+
264
+ issueMove([ship, e1, e2], ship.x + 120, ship.y + 80, false, { shape: "wedge" });
265
+ assert.equal(e1.order.type, "follow-leader", "fixture sanity: the escorts are following the ship");
266
+ assert.equal(e2.order.type, "follow-leader");
267
+
268
+ deployColonyShip(st, ship.id);
269
+ assert.ok(!st.units.has(ship.id), "fixture sanity: the ship is gone from the state");
270
+ assert.ok(ship.hp > 0, "fixture sanity: and it was removed ALIVE β€” which is why an hp check misses it");
271
+
272
+ tick(st, 0.1);
273
+ assert.equal(e1.order, null, "the escort must be released, not left chasing a removed ship");
274
+ assert.equal(e2.order, null);
275
+ });
test/formation.test.js CHANGED
@@ -477,6 +477,28 @@ test("redefining a leader's squad with a smaller group stops (not just unlinks)
477
  assert.equal(a.order.type, "follow-leader", "A is still following");
478
  });
479
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  // ---- click-and-drag facing (engine/commands.js applyFacing) ------------------
481
 
482
  test("issueMove with an explicit heading stamps every commanded unit's facing; a plain move clears it", () => {
 
477
  assert.equal(a.order.type, "follow-leader", "A is still following");
478
  });
479
 
480
+ test("redefining a squad that drops TWO followers releases both, not just the first (A2)", () => {
481
+ // The release loop splices the array it is iterating, and a for...of iterator is index-based, so
482
+ // every splice SKIPS the next element. The test above drops one follower β€” and the LAST one β€”
483
+ // which is exactly why the bug hid: you need two adjacent drops to see the skip. The survivor
484
+ // keeps squadLeader pointing at a leader whose own list no longer contains it, breaking the
485
+ // bidirectional invariant setSquadLeader's comment promises.
486
+ const leader = fakePlayerUnit("L", "skiff", 0, 0);
487
+ const a = fakePlayerUnit("A", "skiff", 0, 0);
488
+ const b = fakePlayerUnit("B", "skiff", 0, 0);
489
+ const c = fakePlayerUnit("C", "skiff", 0, 0);
490
+ issueHoldFormation([leader, a, b, c]);
491
+ assert.deepEqual(leader.squadFollowers, [a, b, c]);
492
+
493
+ issueMove([leader, c], 500, 0); // drops BOTH a and b, which are adjacent in the list
494
+
495
+ assert.deepEqual(leader.squadFollowers, [c], "only C remains in the squad");
496
+ assert.equal(a.squadLeader, undefined, "A was released");
497
+ assert.equal(a.order, null, "A is actually stopped");
498
+ assert.equal(b.squadLeader, undefined, "B was released too β€” not skipped by the splice");
499
+ assert.equal(b.order, null, "B is actually stopped, not left chasing a leader that dropped it");
500
+ });
501
+
502
  // ---- click-and-drag facing (engine/commands.js applyFacing) ------------------
503
 
504
  test("issueMove with an explicit heading stamps every commanded unit's facing; a plain move clears it", () => {
test/haul.test.js CHANGED
@@ -4,7 +4,7 @@ import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";
4
  import { tick } from "../engine/sim.js";
5
  import { updateHaul, assignHaul, updateService, assignService, countLogistics } from "../engine/haul.js";
6
  import { issueSetLogiPriority } from "../engine/commands.js";
7
- import { storeTotal, inputTotal, inputRoom, inputCapOf, UNITS } from "../engine/entities.js";
8
  import { serializeGame, deserializeGame } from "../engine/persist.js";
9
  import { mulberry32 } from "./_helpers.js";
10
 
@@ -630,6 +630,43 @@ test("countLogistics resets a power station's `servers` tally each tick, same as
630
  assert.equal(gen.servers, 1, "…and the tick after that");
631
  });
632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633
  test("a Combustion Generator's fuel larder is deterministic: two same-seed runs end up identically fuelled", () => {
634
  const run = () => {
635
  const { s, cc } = base(5);
 
4
  import { tick } from "../engine/sim.js";
5
  import { updateHaul, assignHaul, updateService, assignService, countLogistics } from "../engine/haul.js";
6
  import { issueSetLogiPriority } from "../engine/commands.js";
7
+ import { storeTotal, inputTotal, inputRoom, inputCapOf, UNITS, BUILDINGS } from "../engine/entities.js";
8
  import { serializeGame, deserializeGame } from "../engine/persist.js";
9
  import { mulberry32 } from "./_helpers.js";
10
 
 
630
  assert.equal(gen.servers, 1, "…and the tick after that");
631
  });
632
 
633
+ test("countLogistics resets an AMMO-fed battery's `servers` tally each tick too (A3)", () => {
634
+ // The same bug the power-station fix above closed, on the third input-taking kind. countLogistics
635
+ // resets `servers` for a factory (recipeOf) or a fuel burner (combust) β€” but inputNeedsOf later
636
+ // grew a `def.ammo` branch, and a Torpedo Battery is neither of those and has no store cap, so its
637
+ // tally only ever climbed. After one resupply run it sat permanently above MAX_SERVERS and
638
+ // assignService rejected it forever: the game's top-tier static defense silently became a
639
+ // hand-micro structure the moment it first shot its magazine dry.
640
+ const { s, cc, workers } = base(4);
641
+ const battery = plantGenerator(s, cc, "torpedobattery");
642
+ const w = workers[0];
643
+ w.order = { type: "service", buildingId: battery.id, phase: "plan" };
644
+
645
+ countLogistics(s);
646
+ assert.equal(battery.servers, 1, "re-tallied fresh from the one live order");
647
+ countLogistics(s);
648
+ assert.equal(battery.servers, 1, "still exactly 1 the next tick β€” the tally doesn't just keep growing");
649
+ countLogistics(s);
650
+ assert.equal(battery.servers, 1, "…and the tick after that");
651
+ });
652
+
653
+ test("a Torpedo Battery can be auto-resupplied a SECOND time, not just once (A3)", () => {
654
+ const { s, cc } = base(4);
655
+ const battery = plantGenerator(s, cc, "torpedobattery");
656
+ const ammo = BUILDINGS.torpedobattery.ammo.com;
657
+ s.players.player.resources[ammo] = 500;
658
+
659
+ for (let i = 0; i < 900; i++) tick(s, 0.1);
660
+ assert.ok((battery.input?.[ammo] || 0) > 0, "fixture sanity: the first resupply actually landed");
661
+
662
+ battery.input[ammo] = 0; // it shoots the magazine dry
663
+ for (const u of s.units.values()) if (u.order?.type === "service") u.order = null;
664
+ for (let i = 0; i < 900; i++) tick(s, 0.1);
665
+ assert.ok((battery.input?.[ammo] || 0) > 0,
666
+ "an idle worker must be re-offered the battery β€” after the first run its servers tally used to " +
667
+ "sit above MAX_SERVERS forever, so no worker was ever assigned to it again");
668
+ });
669
+
670
  test("a Combustion Generator's fuel larder is deterministic: two same-seed runs end up identically fuelled", () => {
671
  const run = () => {
672
  const { s, cc } = base(5);
test/industry.test.js CHANGED
@@ -1,12 +1,13 @@
1
  import { test } from "node:test";
2
  import assert from "node:assert/strict";
3
  import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";
4
- import { storeTotal } from "../engine/entities.js";
5
  import { tick } from "../engine/sim.js";
6
  import { createGalaxy, activeState, stepGalaxy } from "../engine/galaxy.js";
7
  import { sell } from "../engine/market.js";
8
- import { powerCap, powerDraw, powerThrottle, updateProduction, recipeOf, planetIndustryScale, powerEfficiency, POWER_TIERS, hasIceCoolant, iceCoolantMult, chargeIceUpkeep, buildingConcern, ELECTRIFY_POWER } from "../engine/industry.js";
9
  import { BUILDINGS } from "../engine/entities.js";
 
10
  import { deployColonyShip } from "../engine/colony.js";
11
 
12
  // The industry helpers read only state.buildings and state.players[owner].resources,
@@ -486,3 +487,48 @@ test("powerDraw: a linked Substation relay adds its own small flat grid draw (th
486
  const s = stub([reactor({ x: 0, y: 0 }), substation({ x: 50, y: 0 })]); // well within the linked band β†’ full efficiency
487
  assert.ok(near(powerDraw(s, "player"), ELECTRIFY_POWER), "a well-linked relay draws the flat relay amount at full (Γ—1.0) efficiency");
488
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import { test } from "node:test";
2
  import assert from "node:assert/strict";
3
  import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";
4
+ import { storeTotal, storeCapOf } from "../engine/entities.js";
5
  import { tick } from "../engine/sim.js";
6
  import { createGalaxy, activeState, stepGalaxy } from "../engine/galaxy.js";
7
  import { sell } from "../engine/market.js";
8
+ import { powerCap, powerDraw, powerThrottle, cachedPowerThrottle, updateProduction, recipeOf, planetIndustryScale, powerEfficiency, POWER_TIERS, hasIceCoolant, iceCoolantMult, chargeIceUpkeep, buildingConcern, ELECTRIFY_POWER } from "../engine/industry.js";
9
  import { BUILDINGS } from "../engine/entities.js";
10
+
11
  import { deployColonyShip } from "../engine/colony.js";
12
 
13
  // The industry helpers read only state.buildings and state.players[owner].resources,
 
487
  const s = stub([reactor({ x: 0, y: 0 }), substation({ x: 50, y: 0 })]); // well within the linked band β†’ full efficiency
488
  assert.ok(near(powerDraw(s, "player"), ELECTRIFY_POWER), "a well-linked relay draws the flat relay amount at full (Γ—1.0) efficiency");
489
  });
490
+
491
+ test("cachedPowerThrottle re-computes when the grid changes, even on a state with no tick counter (A11)", () => {
492
+ // The cache invalidates on state.tick. A state with no tick field β€” the hand-built stub idiom used
493
+ // throughout this file, and anything else that doesn't come from tick() β€” stored
494
+ // _powerCacheTick = undefined, and `undefined !== undefined` is false FOREVER, so the very first
495
+ // result was frozen for the life of the state.
496
+ const s = stub([{ id: "f1", type: "smelter" }]);
497
+ assert.equal(s.tick, undefined, "fixture sanity: this stub has no tick counter");
498
+
499
+ const first = cachedPowerThrottle(s, "player");
500
+ s.buildings.set("r1", { id: "r1", owner: "player", constructing: false, type: "reactor", powered: true });
501
+ const fresh = powerThrottle(s, "player");
502
+ assert.notEqual(fresh, first, "fixture sanity: the grid really did change");
503
+ assert.equal(cachedPowerThrottle(s, "player"), fresh,
504
+ "the cache must not hand back a stale throttle on a state it cannot key");
505
+ });
506
+
507
+ test("buildingConcern's bufferFull threshold agrees with updateProduction's own gate (A11)", () => {
508
+ // buildingConcern claims to mirror updateProduction's gating "exactly, so the badge never
509
+ // disagrees with what's actually happening in the sim". It didn't: the factory branch called it
510
+ // full at storeRoom <= 1e-6 while updateProduction produces for ANY positive room (`frac > 0`).
511
+ const s = createGameState({ planetId: "ferros", seed: 3 });
512
+ const sm = makeBuilding("smelter", "player", 700, 500);
513
+ sm.constructing = false;
514
+ sm.buildProgress = 1;
515
+ s.buildings.set(sm.id, sm);
516
+ const reactor = makeBuilding("reactor", "player", 660, 500);
517
+ reactor.constructing = false;
518
+ reactor.powered = true;
519
+ s.buildings.set(reactor.id, reactor);
520
+
521
+ const recipe = recipeOf(sm);
522
+ sm.input = sm.input || {};
523
+ sm.store = sm.store || {};
524
+ for (const com in recipe.in) if (com !== "energy") sm.input[com] = 1000;
525
+ sm.store[recipe.out] = storeCapOf("smelter") - 5e-7; // a sliver of room: tiny, but positive
526
+
527
+ // Read the badge FIRST, while the sliver is still open β€” production itself closes it.
528
+ const concern = buildingConcern(s, sm);
529
+ const before = sm.store[recipe.out];
530
+ updateProduction(s, sm, 0.1);
531
+ assert.ok(sm.store[recipe.out] > before, "fixture sanity: the sim really does still produce into that sliver");
532
+ assert.notEqual(concern && concern.code, "bufferFull",
533
+ "the badge must not read bufferFull while updateProduction is still banking output");
534
+ });
test/recycle.test.js CHANGED
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3
  import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";
4
  import { tick } from "../engine/sim.js";
5
  import { recycleFrac, recycleValue, canRecycle, beginRecycle, cancelRecycle, updateBuildingRecycle, updateUnitRecycle, RECYCLE_TECH } from "../engine/recycle.js";
6
- import { issueRecycle, issueCancelRecycle, issueStop } from "../engine/commands.js";
7
  import { UNITS, BUILDINGS } from "../engine/entities.js";
8
  import { serializeGame, deserializeGame } from "../engine/persist.js";
9
 
@@ -256,3 +256,25 @@ test("save hardening: a tampered recycling block is clamped instead of corruptin
256
  assert.ok(loadedRig.recycling.progress >= 0 && loadedRig.recycling.progress <= 1);
257
  assert.ok(loadedRig.recycling.time >= 1, "a non-positive time would otherwise divide-toward-nonsense next tick");
258
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import { createGameState, makeBuilding, makeUnit } from "../engine/state.js";
4
  import { tick } from "../engine/sim.js";
5
  import { recycleFrac, recycleValue, canRecycle, beginRecycle, cancelRecycle, updateBuildingRecycle, updateUnitRecycle, RECYCLE_TECH } from "../engine/recycle.js";
6
+ import { issueRecycle, issueCancelRecycle, issueStop, issueMove } from "../engine/commands.js";
7
  import { UNITS, BUILDINGS } from "../engine/entities.js";
8
  import { serializeGame, deserializeGame } from "../engine/persist.js";
9
 
 
256
  assert.ok(loadedRig.recycling.progress >= 0 && loadedRig.recycling.progress <= 1);
257
  assert.ok(loadedRig.recycling.time >= 1, "a non-positive time would otherwise divide-toward-nonsense next tick");
258
  });
259
+
260
+ test("recycling a formation leader releases its followers instead of stranding them (A1)", () => {
261
+ // The twin of the colony-ship case: updateUnitRecycle also removes a unit at full hp, so an
262
+ // hp-only liveness check in keepFollowingLeader leaves the squad chasing a ghost.
263
+ const st = createGameState({ planetId: "ferros", seed: 8 });
264
+ const leader = makeUnit("skiff", "player", 700, 500);
265
+ const a = makeUnit("skiff", "player", 720, 500);
266
+ const b = makeUnit("skiff", "player", 680, 500);
267
+ for (const u of [leader, a, b]) st.units.set(u.id, u);
268
+
269
+ issueMove([leader, a, b], 900, 500, false, { shape: "wedge" });
270
+ assert.equal(a.order.type, "follow-leader", "fixture sanity: the squad is following");
271
+
272
+ issueRecycle([leader]);
273
+ for (let i = 0; i < 400 && st.units.has(leader.id); i++) tick(st, 0.1);
274
+ assert.ok(!st.units.has(leader.id), "fixture sanity: the leader finished recycling and was removed");
275
+ assert.ok(leader.hp > 0, "fixture sanity: and it was removed ALIVE");
276
+
277
+ tick(st, 0.1);
278
+ assert.equal(a.order, null, "a follower must be released when its leader is recycled away");
279
+ assert.equal(b.order, null);
280
+ });
test/wonder.test.js CHANGED
@@ -153,3 +153,36 @@ test("a mid-charge Gate survives a save/load", () => {
153
  const rgate = [...activeState(restored).buildings.values()].find(b => b.type === "antimatter_gate");
154
  assert.ok(Math.abs(rgate.charge - mid) < 1e-9, "the charge round-trips exactly");
155
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  const rgate = [...activeState(restored).buildings.values()].find(b => b.type === "antimatter_gate");
154
  assert.ok(Math.abs(rgate.charge - mid) < 1e-9, "the charge round-trips exactly");
155
  });
156
+
157
+ test("a Gate at full charge stops consuming β€” it never keeps draining the Strategic tier (A4)", () => {
158
+ // updateWonder clamped the CHARGE but not the SPEND, and nothing returned early at charge >= 1.
159
+ // In a standalone endless state that's masked because checkEndlessWin finishes the game β€” but a
160
+ // GALAXY Gate is explicitly "a milestone, never a win β€” play forever" (engine/victory.js), and
161
+ // sim.js calls updateWonder unconditionally every tick. So a completed Gate went on eating its
162
+ // feed at feed[com] per sim-second, indefinitely, in the three scarcest goods in the game, on the
163
+ // winning line of play β€” and the Leviathan competes for exactly those three.
164
+ const { state, gate } = withGate();
165
+ gate.charge = 1;
166
+ const before = { ...state.players.player.resources };
167
+ for (let i = 0; i < 100; i++) updateWonder(state, gate, 0.1);
168
+ for (const com in BUILDINGS.antimatter_gate.feed)
169
+ assert.equal(state.players.player.resources[com], before[com],
170
+ `a finished Gate must not keep spending ${com}`);
171
+ });
172
+
173
+ test("a Gate's final partial tick pays only for the charge it actually banks (A4)", () => {
174
+ // The same off-by-a-clamp from the other side: charge clamps to 1 while the goods are debited for
175
+ // the whole of p, so the last tick overpays for charge it never received.
176
+ const { state, gate } = withGate();
177
+ const def = BUILDINGS.antimatter_gate;
178
+ gate.charge = 0.995;
179
+ const before = { ...state.players.player.resources };
180
+ updateWonder(state, gate, def.chargeTime); // a whole charge's worth of dt in one step
181
+ assert.equal(gate.charge, 1, "it completes");
182
+ for (const com in def.feed) {
183
+ const spent = before[com] - state.players.player.resources[com];
184
+ const owed = 0.005 * def.feed[com] * def.chargeTime;
185
+ assert.ok(spent <= owed + 1e-9,
186
+ `${com}: spent ${spent} for the last 0.5% of charge, which is only worth ${owed}`);
187
+ }
188
+ });