Spaces:
Paused

Claude Claude Opus 4.8 commited on
Commit
15f3a03
·
unverified ·
1 Parent(s): 4b8ad05

Get CI green, and make the AI's opponent belief fade the way it says it does

Browse files

Acts on the first three findings of docs/code-review-2026-08.md.

CI has been red since 2026-08-05 and two PRs merged through it. Two causes,
both fixed here:

- competitionLedger.js had two wrong JSDoc signatures. addRosterEntry never
declared the `genome` field its body reads and writes (the RosterEntry
typedef omitted it too), and recordCompetition typed its match rows as bare
`object`, so every row.aName / row.winner / row.margin read in the file was
an error the moment a checker looked. Adds a real CompetitionResultRow
typedef and narrows the one ternary TypeScript was widening to `string`.
- CI installed TypeScript unpinned via `npx --package typescript`, so the same
tree reported 2 errors under 5.7 and 21 under 7.0.2 — a green commit could go
red overnight with no code change. The invocation is pinned to 5.7.2; the
compiler still stays out of package.json, it is just no longer a moving
target. Verified clean on both 5.7.2 and latest.

The third is a real behavioural bug, not a type gap. engine/aiIntel.js faded
the stored belief and wrote the faded number back, then re-faded THAT from the
same timestamp next think cycle, so the decay compounded per cycle and its rate
depended on how often the AI thought. At engine/ai.js's 1.5s cadence the
documented 240s linear fade emptied in ~60s: at 60s the belief should read 75%
of peak and read 0.36%. Confidence gates everything downstream, so adaptMode
sat pinned at neutral and adaptDefenceMult returned 1.0 — the adaptive layer
was inert the moment the enemy left vision, and scouting bought nearly nothing.

The peak is now immutable and the fade is derived from elapsed time at read
(channelValue), never accumulated, so it is linear at any cadence. The two
channels also fade on separate clocks: under one shared stamp a worker left in
view kept re-dating the MILITARY belief, propping up the estimate of an army
that had walked off — the mirror of the same bug. Adds intelMilAt/intelEcoAt
through state.js, types.js and persist.js; purely additive, both default null,
and channelValue falls back to the shared intelAt for saves written before
them, so no SAVE_VERSION bump (CONTRIBUTING §3).

Tests first, per CONTRIBUTING's TDD section. The three new cases in
test/aiIntel.test.js drive updateIntel at the real THINK_INTERVAL instead of
jumping state.time in one hop, and assert the NUMBER the docs promise rather
than a direction — which is why the existing coverage, 441 lines of it, could
not see this. All three were confirmed red against the old implementation
(0.72 where 150 was expected; 20.5 vs 0.0 across cadences; 60.6 where 50 was
expected for the frozen-by-a-worker case).

npm test 2497 passing, 0 failing. npm run typecheck clean on 5.7.2 and latest.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

.github/workflows/test.yml CHANGED
@@ -29,5 +29,14 @@ jobs:
29
  # instead of installing it. `--package typescript` names the package explicitly so this
30
  # works correctly on a clean runner regardless of any ambient global `tsc`, unlike a bare
31
  # `npx tsc` (which depends on npx's registry-matching behavior).
 
 
 
 
 
 
 
 
 
32
  - name: Type-check the annotated files
33
- run: npx --yes --package typescript -- tsc -p jsconfig.json
 
29
  # instead of installing it. `--package typescript` names the package explicitly so this
30
  # works correctly on a clean runner regardless of any ambient global `tsc`, unlike a bare
31
  # `npx tsc` (which depends on npx's registry-matching behavior).
32
+ #
33
+ # THE VERSION IS PINNED, and that part is load-bearing. Unpinned, `--package typescript`
34
+ # resolves to whatever is newest on the registry that morning, so a green commit can go red
35
+ # overnight with no code change and a real regression is indistinguishable from a compiler
36
+ # upgrade. That is not hypothetical here: TypeScript 7 reported 21 errors on a tree that
37
+ # TypeScript 5.7 reported 2 on, and CI stayed red across two merges to main. Pinning the
38
+ # INVOCATION keeps the compiler out of package.json exactly as the note above intends —
39
+ # it is still not a dependency, it is just no longer a moving target. Bump this
40
+ # deliberately, in its own commit, so a compiler upgrade is reviewable on its own.
41
  - name: Type-check the annotated files
42
+ run: npx --yes --package typescript@5.7.2 -- tsc -p jsconfig.json
CHANGELOG.md CHANGED
@@ -143,6 +143,23 @@ All notable changes to this project are documented here. The format follows
143
 
144
  ### Fixed
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  - A worker whose gathering node hit exactly 0 mid-carry could strand its last partial load
147
  forever (never banked); this is now rare in practice, since the same fix that stops gatherers
148
  from idling at a dry node also gives it somewhere to carry the stranded load — the fully-idle
 
143
 
144
  ### Fixed
145
 
146
+ - **The adaptive AI actually remembers what it scouted now.** Its opponent belief was documented
147
+ to fade in a straight line over four minutes, but the code faded the stored value and wrote the
148
+ faded number back, then re-faded *that* from the same timestamp on the next think cycle. The
149
+ decay compounded once per cycle, so at the AI's real 1.5-second cadence a four-minute fade
150
+ emptied in about sixty seconds — and because confidence gates everything downstream, the whole
151
+ adaptive layer sat pinned at neutral the moment the enemy left vision. Scouting bought almost
152
+ nothing and `adaptDefenceMult` returned 1.0, identical to having no adaptation at all. The peak
153
+ is now immutable and the fade is computed at read time from elapsed time, so it is the straight
154
+ line it always claimed to be, at any think rate. Military and economic belief also fade on
155
+ separate clocks: a worker parked in view used to keep re-dating the *military* estimate, holding
156
+ up the AI's read of an army that had long since walked away.
157
+ - **`npm run typecheck` passes again**, and CI pins the compiler version. Two JSDoc signatures in
158
+ `competitionLedger.js` were wrong — `addRosterEntry` never declared the `genome` field it reads
159
+ and writes, and `recordCompetition` typed its match rows as bare `object`. The build had been red
160
+ since 2026-08-05. CI also installed TypeScript unpinned, so the same source reported 2 errors
161
+ under 5.7 and 21 under 7.0.2; the invocation is now pinned so a compiler release can't turn a
162
+ green commit red on its own.
163
  - A worker whose gathering node hit exactly 0 mid-carry could strand its last partial load
164
  forever (never banked); this is now rare in practice, since the same fix that stops gatherers
165
  from idling at a dry node also gives it somewhere to carry the stranded load — the fully-idle
competitionLedger.js CHANGED
@@ -82,11 +82,15 @@ import { hashStr } from "./engine/rng.js";
82
  import { sanitizeGenome } from "./tools/genome.js";
83
 
84
  /**
85
- * @typedef {{ name: string, strategy: string, archetype: string|null, faction: string, createdAt: number|null, human: boolean }} RosterEntry
86
  * `archetype` is a STRING KEY into engine/aiArchetypes.js's ARCHETYPES table (D3), or null for
87
  * "no override — use whatever the world/planet hands out". Deliberately carries no difficulty
88
  * field (see this file's header) — difficulty is the ratingsByDifficulty bracket axis, not part
89
  * of an entrant's identity.
 
 
 
 
90
  * `human` (Phase 4) marks THE one entry that is the player themself. At most one entry may carry
91
  * it; it is otherwise an ordinary entrant, rated in the same bracketed tables as everyone else
92
  * (D1: a human rating has to mean what an AI rating means, or comparing them is meaningless).
@@ -125,9 +129,20 @@ import { sanitizeGenome } from "./tools/genome.js";
125
  * (this module is pure; timestamps arrive from the UI layer, same as recordCompetition's `at`).
126
  */
127
  /**
128
- * @typedef {{ at: number|null, difficulty: string, aName: string, bName: string, rows: object[] }} LedgerHistoryEntry
129
- * `rows` is exactly competitionWorker.js's own "done" message rows field — this module treats it
130
- * as opaque data it stores and reads back (aName/bName/winner/margin), never a shape it invents.
 
 
 
 
 
 
 
 
 
 
 
131
  */
132
  /** @typedef {Object.<string, { rating: number, games: number }>} LedgerRatingsTable elo.js's own RatingsTable shape. */
133
  /**
@@ -275,7 +290,7 @@ export function humanEntry(ledger) {
275
  * that has exactly one answer. A second one would make humanEntry's answer depend on roster order,
276
  * and would let a Gauntlet be started as one identity and rated as another.
277
  * @param {CompetitionLedger} ledger
278
- * @param {{ name: string, strategy?: string, archetype?: string|null, faction?: string, createdAt?: number, human?: boolean }} [entry]
279
  * @returns {CompetitionLedger} the same `ledger`, mutated in place
280
  */
281
  export function addRosterEntry(ledger, entry) {
@@ -346,7 +361,7 @@ export function removeRosterEntry(ledger, name) {
346
  * untouched — the same "guard fires before any mutation" discipline elo.js's own applyResult holds
347
  * itself to for the same-name collision it guards against.
348
  * @param {CompetitionLedger} ledger
349
- * @param {{ at?: number, difficulty: string, aName: string, bName: string, rows: object[] }} entry
350
  * @returns {CompetitionLedger} the same `ledger`, mutated in place
351
  */
352
  export function recordCompetition(ledger, entry) {
@@ -617,7 +632,11 @@ export function recordGauntletMatch(ledger, result) {
617
  // aName-relative convention standingsFor reads every history row with.
618
  aName: g.humanName,
619
  bName: fixture.opponent,
620
- winner: winner === "human" ? "a" : winner === "opponent" ? "b" : "draw",
 
 
 
 
621
  winReason: isForfeit ? "forfeit" : (typeof winReason === "string" ? winReason : null),
622
  margin: margin_,
623
  time: Number.isFinite(time) ? time : null,
 
82
  import { sanitizeGenome } from "./tools/genome.js";
83
 
84
  /**
85
+ * @typedef {{ name: string, strategy: string, archetype: string|null, faction: string, createdAt: number|null, human: boolean, genome?: Object }} RosterEntry
86
  * `archetype` is a STRING KEY into engine/aiArchetypes.js's ARCHETYPES table (D3), or null for
87
  * "no override — use whatever the world/planet hands out". Deliberately carries no difficulty
88
  * field (see this file's header) — difficulty is the ratingsByDifficulty bracket axis, not part
89
  * of an entrant's identity.
90
+ * `genome` is OPTIONAL and present only on an entrant that carries its own tools/genome.js dials
91
+ * rather than naming a shipped strategy (see addRosterEntry). Declared optional rather than
92
+ * `Object|null` on purpose: the field is omitted entirely when absent, so existing rosters and
93
+ * exported ladders stay byte-identical instead of gaining a null nobody asked for.
94
  * `human` (Phase 4) marks THE one entry that is the player themself. At most one entry may carry
95
  * it; it is otherwise an ordinary entrant, rated in the same bracketed tables as everyone else
96
  * (D1: a human rating has to mean what an AI rating means, or comparing them is meaningless).
 
129
  * (this module is pure; timestamps arrive from the UI layer, same as recordCompetition's `at`).
130
  */
131
  /**
132
+ * @typedef {{ aName: string, bName: string, winner: "a"|"b"|"draw", margin?: number }} CompetitionResultRow
133
+ * One finished match as competitionWorker.js reports it. NOT elo.js's MatchRow: that carries a
134
+ * numeric `score` from A's point of view, and recordCompetition converts to it. `margin` is
135
+ * optional and always aName-relative (standingsFor negates it for the B seat).
136
+ *
137
+ * Typed as a real shape rather than the bare `object` it used to be. That was not a cosmetic
138
+ * looseness: `object` has no properties at all, so every `row.aName` / `row.winner` /
139
+ * `row.margin` read in this file was a type error the moment a checker looked at it — which is
140
+ * what broke `npm run typecheck` under TypeScript 7 (TypeScript 5 let the same reads pass).
141
+ */
142
+ /**
143
+ * @typedef {{ at: number|null, difficulty: string, aName: string, bName: string, rows: CompetitionResultRow[] }} LedgerHistoryEntry
144
+ * `rows` is exactly competitionWorker.js's own "done" message rows field — this module stores it
145
+ * and reads it back (aName/bName/winner/margin), never a shape it invents.
146
  */
147
  /** @typedef {Object.<string, { rating: number, games: number }>} LedgerRatingsTable elo.js's own RatingsTable shape. */
148
  /**
 
290
  * that has exactly one answer. A second one would make humanEntry's answer depend on roster order,
291
  * and would let a Gauntlet be started as one identity and rated as another.
292
  * @param {CompetitionLedger} ledger
293
+ * @param {{ name: string, strategy?: string, archetype?: string|null, faction?: string, createdAt?: number, human?: boolean, genome?: Object }} [entry]
294
  * @returns {CompetitionLedger} the same `ledger`, mutated in place
295
  */
296
  export function addRosterEntry(ledger, entry) {
 
361
  * untouched — the same "guard fires before any mutation" discipline elo.js's own applyResult holds
362
  * itself to for the same-name collision it guards against.
363
  * @param {CompetitionLedger} ledger
364
+ * @param {{ at?: number, difficulty: string, aName: string, bName: string, rows: CompetitionResultRow[] }} entry
365
  * @returns {CompetitionLedger} the same `ledger`, mutated in place
366
  */
367
  export function recordCompetition(ledger, entry) {
 
632
  // aName-relative convention standingsFor reads every history row with.
633
  aName: g.humanName,
634
  bName: fixture.opponent,
635
+ // The cast narrows what TypeScript would otherwise widen: the ternary yields exactly
636
+ // "a" | "b" | "draw", but an un-annotated object literal widens each property to `string`,
637
+ // so the row stops matching CompetitionResultRow at the recordCompetition call below. The
638
+ // three-way check at the top of this function is what actually guarantees the narrowing.
639
+ winner: /** @type {"a"|"b"|"draw"} */ (winner === "human" ? "a" : winner === "opponent" ? "b" : "draw"),
640
  winReason: isForfeit ? "forfeit" : (typeof winReason === "string" ? winReason : null),
641
  margin: margin_,
642
  time: Number.isFinite(time) ? time : null,
docs/code-review-2026-08.md CHANGED
@@ -2,6 +2,12 @@
2
 
3
  **Date:** 2026-08-07 · **Commit:** `56d13d7` · **Reviewer:** external, architecture + TDD focus
4
 
 
 
 
 
 
 
5
  **Baseline measured, not assumed:**
6
 
7
  | Check | Result |
 
2
 
3
  **Date:** 2026-08-07 · **Commit:** `56d13d7` · **Reviewer:** external, architecture + TDD focus
4
 
5
+ > **Status update.** Findings 1, 2 and 3 have since been fixed in this branch — the typecheck is
6
+ > green on both TypeScript 5.7 and 7, the CI compiler is pinned, and `updateIntel` now fades on a
7
+ > real straight line. The three new tests in `test/aiIntel.test.js` were written red first and
8
+ > reproduce the old decay exactly. Findings 4–9 are open. The suite is at 2497 passing.
9
+ > Everything below is the review as written against `56d13d7`, left unedited.
10
+
11
  **Baseline measured, not assumed:**
12
 
13
  | Check | Result |
engine/aiIntel.js CHANGED
@@ -58,6 +58,56 @@ export const INTEL_FULL = 900;
58
 
59
  const clamp01 = v => (v < 0 ? 0 : v > 1 ? 1 : v);
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  /** Sum of a cost object's commodities — the same flat ore-value engine/victory.js's own
62
  * costValue uses, kept local so this file stays a leaf of entities/fog/aiCommon only.
63
  * @param {Object} [cost] @returns {number} */
@@ -115,10 +165,16 @@ export function sightEnemy(state, owner = "ai") {
115
  * engine/ai.js's aiContext, before any phase reads it, so every phase in a cycle sees the same
116
  * picture.
117
  *
118
- * The update is `max(live, faded stored)` per channel — see the high-water-mark note in this
119
- * file's header. Only a sighting raises it; only time lowers it. `intelAt` is stamped whenever
120
- * ANYTHING enemy is in sight, including nothing-but-workers, because "I looked and saw a worker
121
- * line" is a genuine refresh of the belief, not a gap in it.
 
 
 
 
 
 
122
  *
123
  * @param {State} state @param {string} [owner] @returns {void}
124
  */
@@ -126,18 +182,9 @@ export function updateIntel(state, owner = "ai") {
126
  const controller = owner === "ai" ? state.ai : state.playerAi;
127
  if (!controller) return;
128
  const live = sightEnemy(state, owner);
129
- const last = controller.intelAt;
130
- // Linear fade rather than an exponential one: subtraction and division only, so it carries no
131
- // cross-engine float question the way a pow() would, and "how stale is this" stays something a
132
- // reader can do in their head.
133
- const age = last == null ? Infinity : Math.max(0, state.time - last);
134
- const keep = age >= INTEL_FADE ? 0 : 1 - age / INTEL_FADE;
135
- const mil = Math.max(live.mil, (controller.intelMil || 0) * keep);
136
- const eco = Math.max(live.eco, (controller.intelEco || 0) * keep);
137
- controller.intelMil = mil;
138
- controller.intelEco = eco;
139
  if (live.mil > 0 || live.eco > 0) controller.intelAt = state.time;
140
- else if (last == null) controller.intelAt = null; // never seen anything yet — stay honestly blind
141
  }
142
 
143
  /**
@@ -151,10 +198,17 @@ export function updateIntel(state, owner = "ai") {
151
  export function readEnemy(state, owner = "ai") {
152
  const controller = owner === "ai" ? state.ai : state.playerAi;
153
  if (!controller) return { posture: null, confidence: 0, mil: 0, eco: 0, age: null };
154
- const mil = controller.intelMil || 0, eco = controller.intelEco || 0;
 
 
 
155
  const total = mil + eco;
156
  const age = controller.intelAt == null ? null : Math.max(0, state.time - controller.intelAt);
157
- const freshness = age == null ? 0 : (age >= INTEL_FADE ? 0 : 1 - age / INTEL_FADE);
 
 
 
 
158
  return {
159
  posture: total > 0 ? mil / total : null,
160
  // Both halves must hold: a stale look at a whole base is as uninformative as a fresh glimpse
 
58
 
59
  const clamp01 = v => (v < 0 ? 0 : v > 1 ? 1 : v);
60
 
61
+ /**
62
+ * How much of a belief set `age` sim-seconds ago is still worth — 1 fresh, 0 past the window,
63
+ * straight-line in between. Subtraction and division only, no pow()/exp(): a curved fade would
64
+ * put an engine-approximated math call on a path that feeds every AI decision, and this project's
65
+ * same-seed-same-game promise (CONTRIBUTING §1) does not want that.
66
+ * @param {number} age @returns {number}
67
+ */
68
+ function fadeKeep(age) {
69
+ return age >= INTEL_FADE ? 0 : 1 - age / INTEL_FADE;
70
+ }
71
+
72
+ /**
73
+ * One channel's belief RIGHT NOW: the stored peak, faded by how long since that peak was set.
74
+ *
75
+ * THE FADE IS COMPUTED, NEVER ACCUMULATED. This used to fade the stored number and write the faded
76
+ * number back, then re-fade THAT from the same timestamp on the next think cycle — so the decay
77
+ * compounded once per cycle and its real rate depended on how often the AI happened to think. At
78
+ * engine/ai.js's 1.5s cadence the documented four-minute fade emptied in about sixty seconds, which
79
+ * quietly made the whole belief model inert the moment the enemy left vision. Keeping the peak
80
+ * immutable and deriving the current value from elapsed time makes the fade exactly the straight
81
+ * line the header describes, at any cadence.
82
+ *
83
+ * `atKey` falls back to the shared `intelAt` so a save written before the per-channel stamps
84
+ * existed loads as "both channels last refreshed when anything was last seen" — the closest true
85
+ * statement that old data supports.
86
+ * @param {Object} controller @param {number} now @param {string} valKey @param {string} atKey
87
+ * @returns {number}
88
+ */
89
+ function channelValue(controller, now, valKey, atKey) {
90
+ const peak = controller[valKey] || 0;
91
+ if (peak <= 0) return 0;
92
+ const at = controller[atKey] != null ? controller[atKey] : controller.intelAt;
93
+ if (at == null) return 0;
94
+ return peak * fadeKeep(Math.max(0, now - at));
95
+ }
96
+
97
+ /**
98
+ * Fold one channel's live sighting into its stored peak. Only a sighting that beats what the AI
99
+ * already believes moves anything; anything less leaves the peak AND its stamp untouched, so the
100
+ * existing fade carries on from where it was rather than restarting.
101
+ * @param {Object} controller @param {number} now @param {string} valKey @param {string} atKey
102
+ * @param {number} live @returns {void}
103
+ */
104
+ function refreshChannel(controller, now, valKey, atKey, live) {
105
+ if (live > channelValue(controller, now, valKey, atKey)) {
106
+ controller[valKey] = live;
107
+ controller[atKey] = now;
108
+ }
109
+ }
110
+
111
  /** Sum of a cost object's commodities — the same flat ore-value engine/victory.js's own
112
  * costValue uses, kept local so this file stays a leaf of entities/fog/aiCommon only.
113
  * @param {Object} [cost] @returns {number} */
 
165
  * engine/ai.js's aiContext, before any phase reads it, so every phase in a cycle sees the same
166
  * picture.
167
  *
168
+ * The update is `max(live, faded peak)` per channel — see the high-water-mark note in this file's
169
+ * header. Only a sighting raises it; only time lowers it.
170
+ *
171
+ * THE TWO CHANNELS FADE ON SEPARATE CLOCKS, which is why there are two stamps and not one. A
172
+ * worker line parked in view is a real refresh of what the AI knows about the ECONOMY and says
173
+ * nothing at all about the army that walked off half a minute ago. Under one shared stamp that
174
+ * worker kept re-dating the military belief too, so a single visible drone held the estimate of an
175
+ * army that no longer existed up indefinitely — the mirror image of the compounding bug, and just
176
+ * as wrong. `intelAt` is still stamped whenever ANYTHING enemy is in sight: it answers a different
177
+ * question ("when did I last look at them at all"), which is what readEnemy's confidence needs.
178
  *
179
  * @param {State} state @param {string} [owner] @returns {void}
180
  */
 
182
  const controller = owner === "ai" ? state.ai : state.playerAi;
183
  if (!controller) return;
184
  const live = sightEnemy(state, owner);
185
+ refreshChannel(controller, state.time, "intelMil", "intelMilAt", live.mil);
186
+ refreshChannel(controller, state.time, "intelEco", "intelEcoAt", live.eco);
 
 
 
 
 
 
 
 
187
  if (live.mil > 0 || live.eco > 0) controller.intelAt = state.time;
 
188
  }
189
 
190
  /**
 
198
  export function readEnemy(state, owner = "ai") {
199
  const controller = owner === "ai" ? state.ai : state.playerAi;
200
  if (!controller) return { posture: null, confidence: 0, mil: 0, eco: 0, age: null };
201
+ // Each channel's stored PEAK, faded by its own elapsed time — the fade lives here, at the read,
202
+ // and is never written back (see channelValue).
203
+ const mil = channelValue(controller, state.time, "intelMil", "intelMilAt");
204
+ const eco = channelValue(controller, state.time, "intelEco", "intelEcoAt");
205
  const total = mil + eco;
206
  const age = controller.intelAt == null ? null : Math.max(0, state.time - controller.intelAt);
207
+ // NOT a second fade on top of the one already in `mil`/`eco` above — this one answers "how long
208
+ // since I last laid eyes on them at all", which is a different question from how much of any one
209
+ // channel's estimate still stands, and it is the half that separates "I have seen nothing" from
210
+ // "I have seen an empty base".
211
+ const freshness = age == null ? 0 : fadeKeep(age);
212
  return {
213
  posture: total > 0 ? mil / total : null,
214
  // Both halves must hold: a stale look at a whole base is as uninformative as a fresh glimpse
engine/persist.js CHANGED
@@ -193,8 +193,14 @@ function cleanController(src, prefix, planetId) {
193
  // LastThreatAt is: an old save without these loads as "never seen anything", so a reloaded AI
194
  // starts honestly blind and goes scouting rather than acting on intel it cannot justify.
195
  // Clamped at 0 because a negative asset value is meaningless and would invert posture.
 
 
 
 
196
  intelMil: Math.max(0, num(g("IntelMil"), 0)),
 
197
  intelEco: Math.max(0, num(g("IntelEco"), 0)),
 
198
  intelAt: g("IntelAt") == null ? null : num(g("IntelAt"), 0),
199
  // Clamped to the 0..1 the stance is defined on, so a corrupt save cannot push the AI into a
200
  // defence multiplier outside its designed swing.
@@ -592,6 +598,7 @@ function serPlanet(state) {
592
  // dropping it would make a reloaded AI forget the army it scouted and re-derive its whole
593
  // posture read from an empty picture, changing every downstream decision.
594
  aiIntelMil: state.ai.intelMil ?? 0, aiIntelEco: state.ai.intelEco ?? 0,
 
595
  aiIntelAt: state.ai.intelAt ?? null,
596
  aiAdaptMode: state.ai.adaptMode ?? null,
597
  // Odyssey colony-ship expansion target (engine/ai.js) — the committed deploy spot
@@ -621,6 +628,7 @@ function serPlanet(state) {
621
  // dropping it would make a reloaded AI forget the army it scouted and re-derive its whole
622
  // posture read from an empty picture, changing every downstream decision.
623
  paIntelMil: state.playerAi.intelMil ?? 0, paIntelEco: state.playerAi.intelEco ?? 0,
 
624
  paIntelAt: state.playerAi.intelAt ?? null,
625
  paAdaptMode: state.playerAi.adaptMode ?? null,
626
  paColonyTarget: state.playerAi.colonyTarget ?? null,
 
193
  // LastThreatAt is: an old save without these loads as "never seen anything", so a reloaded AI
194
  // starts honestly blind and goes scouting rather than acting on intel it cannot justify.
195
  // Clamped at 0 because a negative asset value is meaningless and would invert posture.
196
+ // intelMil/intelEco are PEAKS; each carries its own stamp. A save written before the
197
+ // per-channel stamps existed has neither, and loads with both null — aiIntel.js's channelValue
198
+ // falls back to the shared IntelAt in exactly that case, which is the closest true statement
199
+ // the old data supports. Still purely additive, so no SAVE_VERSION bump (CONTRIBUTING §3).
200
  intelMil: Math.max(0, num(g("IntelMil"), 0)),
201
+ intelMilAt: g("IntelMilAt") == null ? null : num(g("IntelMilAt"), 0),
202
  intelEco: Math.max(0, num(g("IntelEco"), 0)),
203
+ intelEcoAt: g("IntelEcoAt") == null ? null : num(g("IntelEcoAt"), 0),
204
  intelAt: g("IntelAt") == null ? null : num(g("IntelAt"), 0),
205
  // Clamped to the 0..1 the stance is defined on, so a corrupt save cannot push the AI into a
206
  // defence multiplier outside its designed swing.
 
598
  // dropping it would make a reloaded AI forget the army it scouted and re-derive its whole
599
  // posture read from an empty picture, changing every downstream decision.
600
  aiIntelMil: state.ai.intelMil ?? 0, aiIntelEco: state.ai.intelEco ?? 0,
601
+ aiIntelMilAt: state.ai.intelMilAt ?? null, aiIntelEcoAt: state.ai.intelEcoAt ?? null,
602
  aiIntelAt: state.ai.intelAt ?? null,
603
  aiAdaptMode: state.ai.adaptMode ?? null,
604
  // Odyssey colony-ship expansion target (engine/ai.js) — the committed deploy spot
 
628
  // dropping it would make a reloaded AI forget the army it scouted and re-derive its whole
629
  // posture read from an empty picture, changing every downstream decision.
630
  paIntelMil: state.playerAi.intelMil ?? 0, paIntelEco: state.playerAi.intelEco ?? 0,
631
+ paIntelMilAt: state.playerAi.intelMilAt ?? null, paIntelEcoAt: state.playerAi.intelEcoAt ?? null,
632
  paIntelAt: state.playerAi.intelAt ?? null,
633
  paAdaptMode: state.playerAi.adaptMode ?? null,
634
  paColonyTarget: state.playerAi.colonyTarget ?? null,
engine/state.js CHANGED
@@ -110,7 +110,14 @@ export function createAiController(planetId, opts = {}) {
110
  // is true, which is what makes scouting worth its cost and killing the scout a real counter.
111
  // Null/0 until something is actually sighted — "I have seen nothing" must stay distinguishable
112
  // from "I have seen an empty base" (see aiIntel's header).
113
- intelMil: 0, intelEco: 0, intelAt: null,
 
 
 
 
 
 
 
114
  // The damped STANCE derived from that belief (engine/aiIntel.js updateAdaptMode): 0 = the
115
  // enemy is playing economy, 1 = they are massing, 0.5 = no opinion. Null until a first think
116
  // cycle sets it, and pinned at neutral forever on Easy (adaptivity 0).
 
110
  // is true, which is what makes scouting worth its cost and killing the scout a real counter.
111
  // Null/0 until something is actually sighted — "I have seen nothing" must stay distinguishable
112
  // from "I have seen an empty base" (see aiIntel's header).
113
+ // intelMil/intelEco are PEAKS, each with its own stamp saying when it was set — the current
114
+ // belief is that peak faded by its own elapsed time, computed at read (aiIntel.js
115
+ // channelValue), never accumulated. Separate clocks because a worker still in view refreshes
116
+ // what the AI knows about the economy and nothing about the army that left.
117
+ intelMil: 0, intelMilAt: null, intelEco: 0, intelEcoAt: null,
118
+ // …and intelAt answers the different question confidence needs: when did it last see the
119
+ // enemy at all. Null until something is actually sighted.
120
+ intelAt: null,
121
  // The damped STANCE derived from that belief (engine/aiIntel.js updateAdaptMode): 0 = the
122
  // enemy is playing economy, 1 = they are massing, 0.5 = no opinion. Null until a first think
123
  // cycle sets it, and pinned at neutral forever on Easy (adaptivity 0).
engine/types.js CHANGED
@@ -248,8 +248,11 @@
248
  * @property {number} unitsBuilt
249
  * @property {number} waveCount
250
  * @property {number|null} nextWaveAt
251
- * @property {number} intelMil ore-value of enemy MILITARY assets this controller has seen (aiIntel.js)
252
- * @property {number} intelEco ore-value of enemy ECONOMIC assets this controller has seen
 
 
 
253
  * @property {number|null} intelAt sim-time it last saw anything of the enemy; null = never
254
  * @property {number|null} adaptMode damped stance from that belief: 0 economy, 1 massing, 0.5 neutral
255
  * @property {Archetype} archetype
 
248
  * @property {number} unitsBuilt
249
  * @property {number} waveCount
250
  * @property {number|null} nextWaveAt
251
+ * @property {number} intelMil PEAK ore-value of enemy MILITARY assets seen (aiIntel.js); the
252
+ * live belief is this faded by intelMilAt's age, computed at read and never written back
253
+ * @property {number|null} intelMilAt sim-time that military peak was set; null = never
254
+ * @property {number} intelEco PEAK ore-value of enemy ECONOMIC assets seen
255
+ * @property {number|null} intelEcoAt sim-time that economic peak was set; null = never
256
  * @property {number|null} intelAt sim-time it last saw anything of the enemy; null = never
257
  * @property {number|null} adaptMode damped stance from that belief: 0 economy, 1 massing, 0.5 neutral
258
  * @property {Archetype} archetype
test/aiIntel.test.js CHANGED
@@ -201,6 +201,95 @@ test("only a sighting raises the estimate; only time lowers it", () => {
201
  assert.equal(readEnemy(s, "ai").mil, 0, "a long-unrefreshed belief must fade to nothing");
202
  });
203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  /* ---------- posture ---------- */
205
 
206
  test("posture reads 0 for a pure economy game and 1 for a pure war game", () => {
 
201
  assert.equal(readEnemy(s, "ai").mil, 0, "a long-unrefreshed belief must fade to nothing");
202
  });
203
 
204
+ /* ---------- the SHAPE of the fade, not just its direction ----------
205
+
206
+ The three tests above step `s.time` in ONE hop and call updateIntel ONCE per hop. That is not
207
+ how engine/ai.js drives this module: runAI calls updateIntel every THINK_INTERVAL (1.5 sim
208
+ seconds), so between two sightings it runs dozens of times. A fade that is correct for one call
209
+ and wrong for many passes every assertion above, because they only ever check a DIRECTION
210
+ ("faded > 0 && faded < grown") — and any decay curve at all satisfies that, including one two
211
+ hundred times too steep.
212
+
213
+ That is exactly the bug these three tests were written for: updateIntel used to write its faded
214
+ value back and then re-fade it from the same timestamp next cycle, so the decay compounded once
215
+ per think cycle and the documented four-minute fade really emptied in about sixty seconds. So
216
+ these drive it at the production cadence and assert the NUMBER the docs promise. */
217
+
218
+ const THINK_INTERVAL = 1.5; // engine/ai.js — the cadence runAI actually calls updateIntel at
219
+
220
+ // Run `seconds` of sim forward the way the game does: many small think cycles, not one jump.
221
+ const think = (s, seconds, owner = "ai") => {
222
+ const until = s.time + seconds;
223
+ while (s.time < until) {
224
+ s.time = Math.min(until, s.time + THINK_INTERVAL);
225
+ updateIntel(s, owner);
226
+ }
227
+ };
228
+
229
+ test("the belief fades LINEARLY over INTEL_FADE when driven at the real think cadence", () => {
230
+ const s = world();
231
+ const skiffs = [addUnit(s, "player", "skiff", 100, 100), addUnit(s, "player", "skiff", 110, 100)];
232
+ see(s, "ai", 105, 100);
233
+ s.time = 0;
234
+ updateIntel(s, "ai");
235
+ const peak = readEnemy(s, "ai").mil;
236
+ assert.ok(peak > 0, "fixture sanity: the army was actually seen");
237
+
238
+ // They leave, and are never seen again. Every checkpoint is a fraction of the documented window.
239
+ for (const u of skiffs) { u.x = 4000; u.y = 4000; }
240
+ for (const [elapsed, expectedShare] of [[0.25, 0.75], [0.25, 0.5], [0.25, 0.25]]) {
241
+ think(s, INTEL_FADE * elapsed);
242
+ const got = readEnemy(s, "ai").mil;
243
+ const want = peak * expectedShare;
244
+ assert.ok(Math.abs(got - want) < peak * 0.02,
245
+ `at ${Math.round(s.time)}s of a ${INTEL_FADE}s fade the belief should be ~${want.toFixed(1)} ` +
246
+ `(${expectedShare * 100}% of ${peak.toFixed(1)}), got ${got.toFixed(4)}`);
247
+ }
248
+ });
249
+
250
+ test("the fade depends on ELAPSED TIME, not on how many think cycles ran in it", () => {
251
+ // The property the bug violated. Two identical worlds, the same sim seconds, different cadences:
252
+ // a coarse one and a fine one. A per-cycle decay makes the fine-grained run fade far further; a
253
+ // time-based one lands both on the same number.
254
+ const run = (cadence) => {
255
+ const s = world();
256
+ const skiff = addUnit(s, "player", "skiff", 100, 100);
257
+ see(s, "ai", 100, 100);
258
+ s.time = 0;
259
+ updateIntel(s, "ai");
260
+ skiff.x = 4000; skiff.y = 4000;
261
+ const until = INTEL_FADE * 0.5;
262
+ while (s.time < until) { s.time = Math.min(until, s.time + cadence); updateIntel(s, "ai"); }
263
+ return readEnemy(s, "ai").mil;
264
+ };
265
+ const coarse = run(30), fine = run(0.25);
266
+ assert.ok(Math.abs(coarse - fine) < 0.01,
267
+ `the same ${INTEL_FADE * 0.5}s must fade the belief identically at any cadence ` +
268
+ `(30s steps -> ${coarse.toFixed(4)}, 0.25s steps -> ${fine.toFixed(4)})`);
269
+ });
270
+
271
+ test("a worker still in sight does not freeze the belief about an army that left", () => {
272
+ // The other half of the property, and the one a single shared "last seen anything" timestamp
273
+ // gets wrong: economy and military decay on their OWN clocks. A worker line parked in view is a
274
+ // genuine refresh of what the AI knows about the ECONOMY, and says nothing whatsoever about the
275
+ // army that walked off — so it must not hold the military estimate up.
276
+ const s = world();
277
+ const skiff = addUnit(s, "player", "skiff", 100, 100);
278
+ addUnit(s, "player", "worker", 120, 100);
279
+ see(s, "ai", 110, 100);
280
+ s.time = 0;
281
+ updateIntel(s, "ai");
282
+ const peakMil = readEnemy(s, "ai").mil;
283
+ assert.ok(peakMil > 0 && readEnemy(s, "ai").eco > 0, "fixture sanity: both channels were seen");
284
+
285
+ skiff.x = 4000; skiff.y = 4000; // the army leaves; the worker stays in view
286
+ think(s, INTEL_FADE * 0.5);
287
+ const r = readEnemy(s, "ai");
288
+ assert.ok(Math.abs(r.mil - peakMil * 0.5) < peakMil * 0.02,
289
+ `the military belief must keep fading on its own clock (~${(peakMil * 0.5).toFixed(1)}), got ${r.mil.toFixed(4)}`);
290
+ assert.ok(r.eco > 0, "the economy belief stays fresh — that worker really is still there");
291
+ });
292
+
293
  /* ---------- posture ---------- */
294
 
295
  test("posture reads 0 for a pure economy game and 1 for a pure war game", () => {