Files
uconsole_asw_game/AGENTS.md
T
db9979andClaude Opus 5.5 1fc5bedbd1 Phase 13: performance pass, closure record, release 1.1.0
Memoize the ELOKA emitter ranking per measured fingerprint (bounded, tied
to the runtime catalog): it was the largest single cost of a simulation
step. A 0.1 s substep now costs the same as in 1.0.0 on the ARM
development host (6.7 ms mean over three seeds).

docs/simulation-gaps.md becomes the closure record: every gap with the
model that closes it and the phase/commit, the calibration and anchoring
policy, and the few items kept out of scope with their reason.

Release 1.1.0: version bump, README EN/DE release notes (save v12, 1.0.0
v11 saves rejected), AGENTS.md (detrand, pure physics modules, calibrate
--check), resume notes for uConsole hardware acceptance and the merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 23:19:18 +02:00

18 KiB

Coding Agent Guide

Authority and scope

  • This is U-Jagd 1.1.0 (src/core/version.py); current saves are v12-only. Treat these as compatibility contracts, not changelog entries.
  • Resolve conflicts in this order: executable code and focused tests; packaged JSON/runtime resources; pyproject.toml and provenance/license notices; README.md; design/history documents under docs/. A plan or old comment is not an implementation contract.
  • Preserve explicit compatibility tests and user data unless a task intentionally changes the contract. Add a regression test for behavior changes.
  • Older phase/milestone labels under docs/GDD.md, docs/implementation-plan.md, docs/plan-0.1.6.md, and docs/plan-0.1.7.md are historical. Current resumable work is tracked in docs/plan-0.1.8.md and docs/resume.md.

Architecture

  • main.py: CLI and saved-preference/CLI override wiring.
  • src/core/game.py: composition root, event precedence, main loop, simulation orchestration, custom-mission runtime bridge, and save/load.
  • src/core/config.py: gameplay constants, units/conversions, scenarios, layout, and timing.
  • src/core/mission*.py, commands.py, station.py, preferences.py, i18n.py: mission models, shared commands, UI state, settings, and localization.
  • src/world/: coastline/bathymetry, real-sector loading, projection, terrain queries, weather/time.
  • src/sonar/ and src/sensors/: measurements, receiver/TMA, and persistent observation tracks.
  • src/ship/, src/enemies/, src/air/, src/weapons/: simulation entities and mechanics.
  • src/ui/: rendering, hit testing, viewport, tooltips, and editors. Views should consume game-facing observations, not discover hidden entity state.
  • src/audio/: bounded NumPy synthesis/analysis and non-blocking Pygame playback.
  • src/data/: packaged catalog loading, validation, fingerprints, and secure user-content persistence. data/ contains package resources; tests/ is the behavioral contract; tools/ contains validators/reproducible generators.

Simulation invariants

  • World position/range is nautical miles, speed is knots, simulation duration is seconds, depth is metres, frequency is Hz, and headings/bearings are nautical degrees: 0 north, clockwise; movement uses x += sin(course), y -= cos(course).
  • At 1x, one real second is one simulation second. Convert knots with kn / 3600; do not add hidden tactical compression. GAME_TIME_PER_SEC advances the 24-hour clock separately.
  • Time acceleration multiplies simulation time exactly once. Game.update() subdivides accelerated time to at most PHYS_SUBSTEP_S subject to PHYS_SUBSTEP_MAX; the main loop clamps wall-frame dt to 0.1 s. Preserve swept collision behavior and the update ordering in _update_sim().
  • Paused, menu, game-over, splash, editor, and administrative states must not accidentally advance simulation. Cosmetic/UI timers and audio cadence use wall time where the code says so.
  • Same seed, world mode, and input/update sequence must produce the same state. Use explicit local random.Random streams, stable hashes, stable iteration/order, and saved RNG states. Never introduce simulation dependence on global randomness, hash randomization, rendering frequency, audio availability, or wall clock.
  • Save/load must preserve deterministic continuation, entity ID progression, generated coastline/bathymetry snapshots, pending sensor/projectile state, and operator focus. When adding random draws, consider stream/order compatibility and update determinism and round-trip tests.
  • New random draws should use the stateless counter-based src/core/detrand.py (u01/normal keyed by seed, tag, entity and tick) so they need no saved stream and never shift existing random.Random sequences.
  • Physics lives in pure modules (src/physics/, src/sonar/equation.py/raytrace.py, src/sensors/radar.py/visual.py/hfdf.py, src/weapons/ciws.py) anchored so the 1.0.0 behaviour appears at its reference point. python tools/calibrate.py --check compares 77 gameplay metrics with tests/calibration/golden.json (recorded on 1.0.0); intentional deviations go in tests/calibration/deviations.json with a reason. Caches in these paths must be pure and bounded (results may never depend on call order).

Input ownership and precedence

  • Keep Game.handle_event() single-owner semantics: splash, editor, pinned-tooltip escape, administrative overlay, menu, numeric entry, then live global/station controls. Alt+Enter is intercepted before contextual confirmation; key-repeat KEYDOWN is ignored.
  • Only one administrative overlay owns input, clears held/joystick/drag/audio state, and blocks background devices and simulation. Focus loss clears controls and pauses; focus gain never auto-resumes.
  • Esc first clears a pinned tooltip, then cancels the active owner, then opens quit confirmation. Numeric entry is intentionally live while simulation runs, but held controls are cleared and invalid input remains editable.
  • Station keys are contextual and must not leak across stations. Clear held controls on station/pause/administration transitions. Trackball axes are station-specific; steering is Bridge-only. Map zoom/pan/follow only operate where a map is visible.
  • Transform display coordinates through _window_to_canvas() and reject letterbox space before hit testing. Keep draw and hit-test geometry aligned.

Observation boundary

  • The player has no general ground-truth access. Sonar exposes noisy bearing-only contacts unless a current ping/TMA/fused observation supplies range/depth/course; stale fixes decay or disappear. Radar, AIS, ESM, HFDF, and radio publish SensorTrack observations with age/quality.
  • Workstations, targeting, weapon guidance, tooltips, and logs must use contacts/tracks/datalink data, not live enemy x, y, depth, class, hostility, or object references. Do not put simulation objects into serialized/public tracks.
  • Legitimate truth is limited to own ship and commanded own assets, known geography/synthetic chart depth, authored/static preview data, and explicitly modeled friendly datalink truth. Physics, AI, collision, sensor generation, and terminal weapon seekers may use underlying entities internally.
  • Manual classification and NATO affiliation are operator annotations, not inferred truth. A sensor domain comes from the observation. Weapons require the modeled track/fix freshness and engagement envelope; pre-terminal torpedo guidance uses the commanded datum, not a hidden target.

Data and localization

  • data/contacts/*.json is the single source of truth for built-in platform/acoustic/torpedo/decoy profile values. Load through src/data/catalog.py; do not duplicate JSON-owned values in Python. tools/gen_contacts.py is a strict validator despite its historical name; it never generates files.
  • data/editor_templates/*.json supplies editor templates, while Python validators define acceptance and runtime code defines effectiveness. Validation success does not imply runtime support.
  • All new user-visible prose needs matching keys in data/i18n/en.json and de.json. English is the reference/fallback; catalogs require exact key parity and identical named placeholders. Use named placeholders only.
  • Route rendering through Translator, localize, translation_scope, and bounded layout helpers. Do not add direct Font.render prose; the test allowlist is technical labels only. Verify English, German, large text where relevant, and the pseudolocale/layout tests.

Persistence and user content

  • Runtime root is ~/.u-jagd/: settings.json; slot1.json through slot5.json; editor files in missions/ and units/. Tests replace save paths with temporary directories; never write real user paths from tests. .u-jagd/, build products, caches, and egg metadata stay untracked.
  • Preferences persist language/fullscreen/audio/large text/tooltips in settings.json; v12 saves also retain the mission's tooltip state. CLI --windowed and --no-audio override saved values for one launch; no inverse fullscreen or CLI-language switch exists.
  • Write and load save v12 only. Require the exact u-jagd-save-v12 schema (exact key sets live in src/core/save_schema.py) and the complete current catalog, platform, ESM, ASW, AIS, and RNG state. Reject malformed, non-integer, older, newer, incomplete, or unknown schemas without migration.
  • Writes must stage beside the destination, flush and fsync, then atomically os.replace; failure leaves the prior file intact and save-and-quit quits only after success. Load into a candidate state and commit only after complete validation/restoration; failure must leave the live game and global ID counters unchanged.
  • Treat imported/editor JSON as hostile. Require finite typed/bounded values, strict schemas, user.<lowercase/digit/_/-> keys, confined destinations, and no symlinked root/file. Never interpret a logical reference as a filesystem path.
  • Bundle import validates every item and collision before the first visible write, stages all files, rechecks confinement/symlinks, and rolls back the whole commit on failure. Preserve backups if rollback itself fails. JSON output must reject NaN/Infinity.

Remote Crew multiplayer

  • Remote Crew is authoritative-host multiplayer for multiple authenticated browser clients. The uConsole process remains the sole simulation authority. Browsers never run simulation, advance time, resolve physics, read live entities, or mutate game state from transport threads.
  • Multiplayer protocol versions are independent of application and save versions. Remote Crew is protocol v2-only; every /api/v1/* route is retired and returns 404. Saves remain exact v12; credentials, clients, station leases, network queues, drafts, and unaccepted commands are transient and never enter saves or settings.
  • Support a hard-bounded client count. Each client has an independent cryptographic session, expiry, request namespace, and revocation state. The host explicitly grants one exclusive station role per client and can revoke or take over any role. Reconnect never inherits another client's authority.
  • Role capabilities are allowlisted. A granted browser may directly operate its station, including weapons when the host separately enables direct fire, but every action must pass the same observation freshness, damage, inventory, ROE, envelope, and readiness checks as local input. Save/load, reset, editors, options, quit, network administration, and credentials remain host-only, with one explicit exception: solo mode (below).
  • Transport handlers accept only strict, finite, size-bounded, versioned messages and enqueue detached envelopes. The main thread revalidates client, role, lease generation, world epoch, resource revision, freshness, and readiness immediately before applying each command. Never synthesize Pygame events or dispatch arbitrary method names from network data.
  • Apply accepted remote commands exactly once in deterministic station order and per-client FIFO order before Game.update(). Wall clock, packet scheduling, polling frequency, browser rendering, and hash iteration must not affect simulation results. Administrative transitions, pause, focus loss, role loss, disconnect, save/load, and world replacement reject unsafe queued commands and clear held remote controls.
  • Each normal role view receives only an allowlisted detached projection of own ship and commanded assets, published observations, annotations, and known geography. Never export simulation objects, hidden IDs, undiscovered positions, true hostile identity, RNG state, or save dumps through station state. The explicit host-granted SimLog capability is the sole diagnostic exception: its read-only history may include detached full-truth snapshots, but never simulation objects, RNG state, credentials, settings, or save dumps.
  • Solo mode is a per-launch, never-persisted host decision (--solo-crew or the F9 "Crew mode" row; changing it revokes every session and rotates the code). One paired session then holds all nine stations and may use the closed host command surface: pause/resume, time scale, save/load slots 1-5 and new game, sent as pseudo-role host over the normal command pipeline (same CSRF/Origin, exactly-once, phase and world-session checks; rejected in crew mode and while a host menu/overlay is open). Editors, options, quit, network administration and credentials stay host-only, saves stay exact v12, and a world replacement keeps the solo session but re-leases every station and drops queued commands. The browser runs on a desktop PC, so the web UI targets large screens; data/commander/ keeps the accessible single-column fallback for narrow windows only.
  • Browser sessions may use host-only HttpOnly SameSite cookies for reload recovery. Credentials never enter JavaScript, URLs, DOM, logs, settings, or saves. State-changing requests also require exact Origin and a separate CSRF token. Plain HTTP remains trusted-LAN-only; Internet-capable deployment requires a separately reviewed encrypted endpoint or reverse proxy.
  • Keep clients, histories, queues, projections, polling, and render work bounded for the uConsole. Cache immutable projections shared by clients with identical visibility, apply backpressure, and verify maximum-client CPU, memory, bandwidth, frame time, reconnect, and thermal behavior on real hardware.
  • New multiplayer prose uses exact EN/DE catalog parity and safe DOM insertion. Browser controls require keyboard and touch access, bounded responsive layouts, explicit stale/revoked states, and tests at desktop, mobile, large zoom, and pseudolocale where applicable.

Coastline provenance

  • data/coastlines/region.json is the hand-maintained stylized legacy map. data/coastlines/real_sectors.json.gz is a generated runtime artifact: exactly 128 distinct, validated 500 NM sectors selected by seed % 128.
  • Never hand-edit, casually recompress, or replace the generated catalog. tools/build_coastline_sectors.py is offline and deterministic (sorted JSON, gzip mtime=0) and accepts only the pinned Natural Earth and Wikidata snapshots with exact SHA-256 values embedded in the tool.
  • The source snapshots are not runtime assets. Regenerate only from rights-cleared pinned inputs, then verify embedded provenance, THIRD_PARTY_NOTICES.md, loader/integrity tests, package inclusion, deterministic seed mapping, and geographic disclaimers together. Gameplay roles and synthetic bathymetry are not claims about real states or real seabed.
  • Private WaveOps PDFs are non-distributable inspiration only. Do not add, quote, transcribe, imitate, or derive text, images, layouts, or data from them. New third-party assets require source, author, license, modification terms, attribution, and redistribution rights documented before release.

Current intentional limits

  • Editor authoring/validation is broader than runtime. Unit-editor profiles currently have no simulation effect.
  • A user mission starts only via F5 from the Mission Editor browser and only if it uses a 500 NM fixed world, clear weather, no events or random groups, exact built-in submarine/surface profiles, hostile submarines, and a sink or survive objective. For sink, targets must exactly equal all placed submarines.
  • Runtime-effective mission fields are seed/name, player pose/speed, sea state/start time/thermocline, exact-unit placement (fixed coordinates or authored sectors)/course/speed/sub depth, and objective/time limit. Reference worlds, alternate sizes, protect/reach, aircraft, animals, torpedoes, decoys, random groups, events, and user unit profiles are rejected, never silently ignored. Mission world definitions do not replace the packaged coastline dataset.
  • Audio is optional and synthesized at runtime; no device, disabled audio, or an incompatible shared mixer must degrade to silence without changing simulation. There are currently no external image/font/audio assets.

uConsole and performance

  • The canonical virtual canvas is 1280x720 at 60 FPS. Preserve semantic station layout and bounded text/tooltips at that size. Other windows use aspect-correct letterboxing (FILL_SCREEN=False); do not distort tactical geometry.
  • The uConsole is a low-power target. Keep render paths free of disk I/O and hidden simulation mutation; cache metadata/surfaces, cull by bounds before point transforms, bound histories/queues/caches, and use NumPy/vectorized processing for signal/waterfall work. Avoid per-frame synthesis and expensive full-world scans.
  • Audio updates at 0.25 s cadence. Engine and sonar streams generate short continuous blocks and retain at most the current plus one queued block. Preserve their phase/filter state, independent reserved channels, bounded queues, and an already initialized compatible shared mixer.
  • Headless CI is not hardware acceptance. Changes affecting frame time, display scaling, controls, mixer behavior, or readability still need testing on the real 1280x720 uConsole target when available.

Build and verification

Use Python 3.11+ from the repository root:

python -m pip install -e '.[dev]'
pytest
python tools/gen_contacts.py --check
python tools/calibrate.py --check
python tools/smoke_full.py
python -m build
  • pytest configures SDL dummy video/audio and isolates saves. Run focused tests while iterating, then the full suite for cross-system changes.
  • python -m build requires the build extra/package and produces both sdist and wheel. Packaging tests build/install artifacts and verify package resources.
  • For releases, verify src/core/version.py, save compatibility, README release statements, package metadata, wheel/sdist resources, notices/licenses, full tests, catalog check, smoke test, and a clean install. Do not include caches, local saves/settings, build trees, source snapshots, private references, or unlicensed assets.
  • Keep commits narrowly scoped; inspect status/diff before staging, never overwrite unrelated work, never commit secrets or local user data, and do not rewrite history or force-push without explicit approval. Generated artifacts must be reproducible and accompanied by their provenance updates.