Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
271f0b4
feat(render): port the Jev opponent decision modules from the spike
LightAxe Sep 18, 2026
65c6144
feat(render): add JevEnemyController, the Jev-driven enemy colony
LightAxe Sep 18, 2026
9031ca6
feat: wire the Jev opponent into boot, the game loop and Save/Continue
LightAxe Sep 18, 2026
922d859
feat: record the opponent in playtraces and proxy /api in dev
LightAxe Sep 18, 2026
c0726b5
feat(render): opponent-picker layout rects and pure picker state
LightAxe Sep 18, 2026
b06bdfc
feat(platform): persist the chosen opponent as a settings preference
LightAxe Sep 18, 2026
1e6e57b
feat(render): opponent picker on the difficulty-select overlay
LightAxe Sep 18, 2026
ac4e7a5
feat(render): Jev-opponent status label in the HUD
LightAxe Sep 18, 2026
52a6992
fix(render): internal-review fixes for the opponent picker
LightAxe Sep 18, 2026
d4b5bb1
test(e2e): cover the Jev opponent picker end-to-end
LightAxe Sep 18, 2026
c2c22a5
feat(jev): add readiness probe so a dead endpoint is caught before ha…
LightAxe Sep 18, 2026
cc1d3f9
fix(jev): decode the ratio answer under its candidate-set id
LightAxe Sep 19, 2026
15f901c
feat(jev): session-bound proxy client, minted by the readiness probe
LightAxe Sep 19, 2026
eb6d20d
docs(jev): the configured endpoint is a base path, not one route
LightAxe Sep 19, 2026
b9b683f
fix(jev): balanced preset carries tuned text; empty orders is a separ…
LightAxe Sep 19, 2026
a091d27
feat(jev): tournament-tuned presets — Balanced=boom-then-bust, Aggres…
LightAxe Sep 19, 2026
40652b7
feat(jev): plan the whole nest at tick 0, hand off on placement
LightAxe Sep 19, 2026
c8d22fd
test(jev): drop the retired resetAIControllerCache from the Jev tests…
LightAxe Sep 21, 2026
7f4ae7c
feat(jev): opponent picker inside the new-game screen — explicit choi…
LightAxe Sep 21, 2026
6c867a4
fix(jev): save-recovery fallbacks boot the persisted opponent, not St…
LightAxe Sep 22, 2026
9626d21
fix(jev): read food through the #290 facade after the rebase onto V70…
LightAxe Oct 2, 2026
bd57a42
fix(jev): call off Jev's spider priority once Jev stops asking, after…
LightAxe Oct 3, 2026
930d398
feat(jev): playtest 5 preset texts for V74
LightAxe Oct 9, 2026
f9f4402
fix(jev): workers_vs_ours is theirs ÷ ours, as the key reads (#436)
LightAxe Oct 9, 2026
4f5639c
fix(jev): ask about storage at three quarters, one at a time, under t…
LightAxe Oct 9, 2026
28cf8ed
fix(jev): muster the assault, send it as an Assault raid, fine bucket…
LightAxe Oct 9, 2026
c29938d
feat(jev): the counter-attack caption works against Jev (#436)
LightAxe Oct 9, 2026
75b9e9e
feat(jev): the beta defaults to Jev + Balanced; a Jev match hides the…
LightAxe Oct 9, 2026
0797662
fix(jev): internal-review fixes — routed-assault caption, rally call-…
LightAxe Oct 9, 2026
8998c58
fix(jev): a rally with no fighter behind it owes no counter-attack ca…
LightAxe Oct 9, 2026
2f9142a
test(jev): the dispatcher test passes main's armyWarning caption stat…
LightAxe Oct 9, 2026
c38b54e
fix(jev): visible muster, storage threshold 0.4, stalled assault come…
LightAxe Oct 9, 2026
10e32d7
fix(jev): review fixes — 60 s stall window at 20 Hz, retarget resets …
LightAxe Oct 9, 2026
72eff88
docs(jev): review nits — comment wraps and the fallback/engagement co…
LightAxe Oct 9, 2026
9d8356d
feat(jev): send our army, their army ratio, both queens' health and i…
LightAxe Oct 10, 2026
d41a595
fix(jev): mirror the server's P2 wording on the client; vocab-agreeme…
LightAxe Oct 10, 2026
cd3ae03
fix(jev): the mirrored assault description fits the proxy's 200-char cap
LightAxe Oct 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,16 @@
# Leave this commented out or empty to disable the survey overlay
# entirely (the open-source default).
# VITE_PLAYTRACE_ENDPOINT=/api/playtrace

# --- Jev opponent (beta) ---------------------------------------------------
# The enemy colony can be driven by TypeSafe's Jev model instead of the
# rule-based AI controller. The browser never holds an API key: it POSTs
# `{ state, questions }` to a SAME-ORIGIN proxy. Point it at the deployed
# proxy through the dev server's `/api` passthrough (see vite.config.ts):
#
# VITE_JEV_ENDPOINT=/api/jev npm run dev
#
# Leave this commented out or empty and the feature is off entirely: the
# enemy colony is always the rule-based AI, and a save that asks for Jev
# falls back to it silently.
# VITE_JEV_ENDPOINT=/api/jev
1 change: 1 addition & 0 deletions docs/phase-4-preflight.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ the Phase 4 WorldState reshape unless another issue owns them.
| Underground input hardcodes PLAYER_COLONY_ID (~10 sites) | `underground-input.ts` (cf. `surface-input.ts:354,449`) | two-colony logic | none | Phase 4 reshape |
| Input world dims branch on constants | `gesture-arbiter.ts:206-210`, `camera-input.ts:194` | constant-bounds (input) | none | Phase 4 reshape |
| Food store capacity = piles + MAX_COLONIES × (pool + physical FoodStorage bound) | `constants.ts` (`MAX_COLONIES`, `FOOD_STORAGE_CHAMBERS_PER_COLONY_BOUND`, `FOOD_STORE_CAPACITY`) | capacity / colony count | guard added (typed-const tripwires on the grid + footprint constants and on `FOOD_STORE_CAPACITY` itself, which must stay ≤ 32766 for the Int16 `surfacePileAt` tile index; `food-store.test.ts` re-derives the bound; the loader rejects > MAX_COLONIES colonies) | #290 PR 2 |
| Jev opening nest rows (spine to 13, Queen anchor 11, upper chambers 4) | `render/jev-opening.ts` (`JEV_QUEEN_ANCHOR_ROW` / `JEV_UPPER_CHAMBER_ROW`) | constant-bounds (render) | clamped to `grid.height`; an anchor that does not fit degrades to `findReachableChamberSpot` | Phase 4 reshape |
| SpiderState 28-field singleton mirrored 3× | types iface / `copyWorldState` / `save.ts` | predator model | none | Phase 4 reshape (5b) |

## Guard pattern
Expand Down
86 changes: 66 additions & 20 deletions playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ export default defineConfig({
// `touch-` (leading slash) so a hypothetical `retouch-*.spec.ts` can't
// sneak in, while future `touch-<feature>.spec.ts` (PR4 long-press, PR5
// hover) match without a config change.
testIgnore: /[\\/]touch-[^\\/]*\.spec\.ts$/,
// W3 adds jev-opponent.spec.ts, which needs a server WITH the Jev endpoint
// configured and therefore runs in the chromium-jev project below.
testIgnore: [/[\\/]touch-[^\\/]*\.spec\.ts$/, /[\\/]jev-opponent\.spec\.ts$/],
use: {
...devices['Desktop Chrome'],
// --disable-gpu prevents WebGL framebuffer errors in headless Chromium
Expand All @@ -52,6 +54,22 @@ export default defineConfig({
},
},
},
{
// W3 — the only project that boots with a Jev proxy endpoint configured, so
// the opponent picker's interactive path (the standing-orders presets and
// the DOM <textarea> mounted over the canvas) is reachable at all. It talks
// to `webServer[1]` on :5174; every other project keeps the open-source
// default (endpoint empty, Jev toggle disabled).
name: 'chromium-jev',
testMatch: /[\\/]jev-opponent\.spec\.ts$/,
use: {
...devices['Desktop Chrome'],
baseURL: 'http://localhost:5174',
launchOptions: {
args: ['--disable-gpu'],
},
},
},
{
// #254 — WebKit/JSC axis for the cross-engine determinism proof. The
// chromium project already covers Node↔V8; the actual Phase-6 target is
Expand All @@ -67,23 +85,51 @@ export default defineConfig({
},
},
],
webServer: {
command: 'npm run dev',
// Force the playtrace feature OFF for e2e regardless of a developer's
// .env.local (Vite gives an existing process.env var priority over .env
// files). Without this, a local VITE_PLAYTRACE_ENDPOINT adds the "Quit &
// feedback" pause-menu row, shifting the menu layout and breaking the
// coordinate-based menu tests on that machine but not in CI. Pinning it
// empty makes the suite match the open-source default everywhere. Set via
// `env` (not a `VAR= cmd` command prefix) so it works on Windows too — a
// POSIX-style prefix is parsed as part of the command by cmd/PowerShell.
env: { VITE_PLAYTRACE_ENDPOINT: '' },
port: 5173,
// Always launch our own server (never reuse). Reuse would silently skip the
// `env` pin above when a dev already has `npm run dev` running on :5173 with
// their own .env.local — reintroducing the non-determinism this config exists
// to remove. The small cold-start cost buys a deterministic playtrace-off run.
reuseExistingServer: false,
timeout: 30_000,
},
webServer: [
{
command: 'npm run dev',
// Force the playtrace feature OFF for e2e regardless of a developer's
// .env.local (Vite gives an existing process.env var priority over .env
// files). Without this, a local VITE_PLAYTRACE_ENDPOINT adds the "Quit &
// feedback" pause-menu row, shifting the menu layout and breaking the
// coordinate-based menu tests on that machine but not in CI. Pinning it
// empty makes the suite match the open-source default everywhere. Set via
// `env` (not a `VAR= cmd` command prefix) so it works on Windows too — a
// POSIX-style prefix is parsed as part of the command by cmd/PowerShell.
//
// VITE_JEV_ENDPOINT is pinned empty for the same reason (W3): a developer's
// .env.local would otherwise enable the Jev opponent, and the difficulty
// overlay grows a standing-orders section when it is available — a layout
// difference between that machine and CI. jev-opponent.spec.ts gets its own
// server below instead of flipping this one.
env: { VITE_PLAYTRACE_ENDPOINT: '', VITE_JEV_ENDPOINT: '' },
port: 5173,
// Always launch our own server (never reuse). Reuse would silently skip the
// `env` pin above when a dev already has `npm run dev` running on :5173 with
// their own .env.local — reintroducing the non-determinism this config exists
// to remove. The small cold-start cost buys a deterministic playtrace-off run.
reuseExistingServer: false,
timeout: 30_000,
},
{
// W3 — the chromium-jev project's server: same build, Jev endpoint SET, so
// `isJevAvailable()` is true and the opponent picker's standing-orders
// section actually renders. Without a second server the feature would have
// no E2E coverage at all, since ui-scene.ts is excluded from the unit
// coverage gate.
//
// The endpoint is the BASE path of the proxy (the client POSTs to
// `<base>/session` and `<base>/beat`), and it points at a path that does
// not exist AND is not under `/api` — vite.config proxies `/api` to the
// deployed site, and an E2E run must never reach it. Flipping the feature
// flag is the whole job; the controller's first request (the session mint)
// then 404s locally, three failures in it fall back to the rule-based AI,
// and that is a code path worth exercising anyway.
command: 'npm run dev -- --port 5174 --strictPort',
env: { VITE_PLAYTRACE_ENDPOINT: '', VITE_JEV_ENDPOINT: '/e2e-jev-stub-not-a-real-endpoint' },
port: 5174,
reuseExistingServer: false,
timeout: 30_000,
},
],
});
24 changes: 24 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,24 @@ export interface MountOptions {
* blocked until the server adds the appropriate CORS headers).
*/
playtraceEndpoint?: string;

/**
* Override the BASE URL of the Jev opponent proxy — the same-origin receiver
* that holds the TypeSafe API key, owns the prompt and forwards to the Jev
* model. The game POSTs to `<base>/session` (mint a session) and
* `<base>/beat` (one decision). When set to a non-empty string, a round can be
* played against the Jev opponent instead of the rule-based AI controller.
*
* Default: the build-time `VITE_JEV_ENDPOINT` env var, or `''` if unset. The
* empty-string convention mirrors `playtraceEndpoint`: a missing env var
* (typical for local dev and the open-source build) disables the feature
* entirely — the enemy colony is always the rule-based AI, no network
* traffic, and a save that asks for Jev falls back to rules silently.
*
* Must be same-origin (`npm run dev` proxies `/api` for local work); a
* cross-origin value is blocked until that deployment adds CORS headers.
*/
jevEndpoint?: string;
}

export interface MountedGame {
Expand Down Expand Up @@ -105,6 +123,11 @@ export function mount(target: HTMLElement, options?: MountOptions): MountedGame
(import.meta.env.VITE_PLAYTRACE_ENDPOINT as string | undefined) ??
'';
const playtraceEndpoint = playtraceEndpointRaw.trim();
// Jev opponent proxy endpoint — same resolution order and same empty-string
// "feature off" convention as playtraceEndpoint above.
const jevEndpointRaw =
options?.jevEndpoint ?? (import.meta.env.VITE_JEV_ENDPOINT as string | undefined) ?? '';
const jevEndpoint = jevEndpointRaw.trim();

const config: Phaser.Types.Core.GameConfig = {
type: Phaser.AUTO,
Expand Down Expand Up @@ -133,6 +156,7 @@ export function mount(target: HTMLElement, options?: MountOptions): MountedGame
preBoot: (game) => {
game.registry.set('assetsBase', assetsBase);
game.registry.set('playtraceEndpoint', playtraceEndpoint);
game.registry.set('jevEndpoint', jevEndpoint);
},
},
};
Expand Down
97 changes: 97 additions & 0 deletions src/platform/save.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
} from '../sim/constants.js';
import type { SimCommand } from '../sim/commands.js';
import type { ColonyId } from '../sim/colony/colony-store.js';
import { DEFAULT_OPPONENT, jevOpponent } from '../render/opponent-config.js';
import { ChamberType } from '../sim/enums.js';
import {
chamberStock,
Expand Down Expand Up @@ -809,6 +810,102 @@ describe('save.ts (SCEN-04 + SCEN-06)', () => {
localStorage.setItem(SAVE_KEY, '{ bad }');
expect(await loadSave()).toBeNull();
});
// --- OPTIONAL `opponent` field (Jev opponent beta) ---------------------
// Additive and non-replay-bearing: (seed, inputLog) already contains every
// command the opponent issued. Absent = the rule-based AI.
it('round-trips a jev opponent with its standing orders', async () => {
const w = createScenario(42);
const opponent = jevOpponent('Strike early and keep striking.');
expect(await manualSave(42, [], w, opponent)).toBe(true);
const loaded = await loadSave();
expect(loaded!.opponent).toEqual(opponent);
});

it('round-trips the rules opponent explicitly', async () => {
const w = createScenario(42);
expect(await manualSave(42, [], w, DEFAULT_OPPONENT)).toBe(true);
expect((await loadSave())!.opponent).toEqual({ kind: 'rules' });
});

it('omits the field entirely when no opponent is passed (pre-feature shape)', async () => {
const w = createScenario(42);
expect(await manualSave(42, [], w)).toBe(true);
const raw = JSON.parse(localStorage.getItem(SAVE_KEY)!) as Record<string, unknown>;
expect('opponent' in raw).toBe(false);
expect((await loadSave())!.opponent).toBeUndefined();
});

it('loads an envelope written before the field existed', async () => {
const w = createScenario(42);
localStorage.setItem(
SAVE_KEY,
JSON.stringify({
version: SAVE_FORMAT_VERSION,
seed: 42,
inputLog: [],
snapshot: serializeWorldState(w),
} satisfies SaveFile),
);
const loaded = await loadSave();
expect(loaded).not.toBeNull();
expect(loaded!.opponent).toBeUndefined();
});

it('tickAutosave carries the opponent through', async () => {
const w = createScenario(42);
const opponent = jevOpponent('turtle up');
await tickAutosave(42, [], w, 0, AUTOSAVE_INTERVAL_MS + 1, undefined, opponent);
expect((await loadSave())!.opponent).toEqual(opponent);
});

it('DROPS a malformed opponent instead of failing the load (it is a preference, not replay truth)', async () => {
const w = createScenario(42);
const snapshot = serializeWorldState(w);
const bad: unknown[] = [
'jev',
42,
null,
[],
{},
{ kind: 'llm' },
{ kind: 'jev' },
{ kind: 'jev', orders: 7 },
{ kind: 'jev', orders: 'x'.repeat(301) },
];
for (const opponent of bad) {
localStorage.setItem(
SAVE_KEY,
JSON.stringify({
version: SAVE_FORMAT_VERSION,
seed: 42,
inputLog: [],
snapshot,
opponent,
}),
);
const loaded = await loadSave();
expect(loaded).not.toBeNull();
expect(loaded!.opponent).toBeUndefined();
expect(loaded!.seed).toBe(42);
}
});

it('a tampered opponent still classifies as compatible', async () => {
const w = createScenario(42);
localStorage.setItem(
SAVE_KEY,
JSON.stringify({
version: SAVE_FORMAT_VERSION,
seed: 42,
inputLog: [],
snapshot: serializeWorldState(w),
opponent: { kind: 'wat' },
}),
);
await expect(classifySaveCompatibility()).resolves.toBe('compatible');
expect(parseSaveFile(localStorage.getItem(SAVE_KEY)!).opponent).toBeUndefined();
});

it('deleteSave removes the key and does not throw on missing', async () => {
localStorage.setItem(
SAVE_KEY,
Expand Down
Loading
Loading