# Agent Guidelines ## Rules - Update `AGENTS.md` after each task by editing current guidance directly. Keep only project standards and durable architecture references; do not retain investigation evidence, task histories, completed plans, or implementation snapshots. - Write documentation and code comments in English, except for the Chinese sections of bilingual changelogs. - Inspect the original DSP game DLL, never the stripped publicized copy in `AssemblyFromGame/`, when method bodies are required. Locate DSP using the Steam registry and `steamapps/libraryfolders.vdf` as `UpdateGameDlls.ps1` does, then decompile `/DSPGAME_Data/Managed/Assembly-CSharp.dll`. - Resolve in-game terminology from `/Locale/`: `Names` contains keys, `1033` is English, and `2052` is Simplified Chinese. ## Project - This repository contains independent BepInEx 5.x C# mods for Dyson Sphere Program. HarmonyLib patches game methods at runtime; `UXAssist` (User eXperience Assistant) is the shared library used directly by `CheatEnabler` and `UniverseGenTweaks`. - Projects target `net472` or `netstandard2.1` with SDK-style `.csproj` files. Compile-time game references live in `AssemblyFromGame/`. - `DustbinPreloader` and `LabOptPreloader` are Mono.Cecil preloaders; their main mods consume the injected fields without reflection. - LiveStreamAssist: [WebSocket architecture, transport migration, and validation](LiveStreamAssist/docs/WebSocketDesign.md). Overlay JS client: [LiveStreamAssist/js/README.md](LiveStreamAssist/js/README.md). - LiveStreamAssist JS clients keep `Client` as the JSON-RPC transport, `GameQuery` as the overlay data layer, and `GameText`/`GameIcons` offline from generated locale/proto dictionaries and extracted game icons. Do not have the offline layers call the WebSocket API. Edit `js/src/` and rebuild the bundle with `python LiveStreamAssist/js/scripts/pack_js.py`; refresh `js/generated/dsp-text.js` and `js/generated/dsp-icons.js` with `python LiveStreamAssist/js/scripts/generate_text.py` and `generate_icons.py` from a local DSP install. Run the JS and Python checks documented in `LiveStreamAssist/js/README.md`. ## Build - `Directory.Build.props` supplies common frameworks, BepInEx packages, game references, warning policy, and the `UpdateGameDlls` dependency. `Directory.Build.targets` defines `ZipMod` and `CopyToParentPackage`. - Normal validation: `dotnet build /.csproj -c Release --no-restore`. If NuGet assets are missing, run `dotnet restore /.csproj` before retrying the build. - Keep temporary verification projects under the mod's excluded root `obj/` directory. Remove abandoned generated outputs when their source project is gone so the SDK source glob cannot compile them into the mod. - Refresh game references explicitly with `dotnet build UpdateGameDlls/UpdateGameDlls.csproj`; the script publicizes installed DLLs in staging and compares generated content hashes so checkout timestamps cannot hide game updates. Missing DSP or the publicizer is a warning, not a build failure. If `assembly-publicizer` requires an unavailable .NET runtime, retry with process-local `DOTNET_ROLL_FORWARD=Major` rather than changing global runtime settings. Verify discovery warnings against the actual configured library directories and original managed DLLs; absence from the VDF `apps` list alone does not establish that DSP is uninstalled. - Package main mods with `dotnet build -t:ZipMod -c Release`; package preloaders with `dotnet build -t:CopyToParentPackage -c Release`. The mod `.csproj` `` is the single version source and packaging synchronizes `package/manifest.json`. Keep the latest English and Chinese `CHANGELOG.md` release headings and notes aligned with ``. Group user-visible changes by feature, state relevant triggers for fixes, and omit implementation-only details. Carry forward existing unreleased notes; document fixes to released regressions under the new version without rewriting historical entries. - Treat warnings as errors except the intentional obsolete API warning `0618`; do not weaken this policy to hide new warnings. - Export Thunderstore package icons as 256x256 PNG files and verify their format and dimensions. For circular exports, apply an antialiased alpha mask to the approved artwork instead of regenerating it; preserve RGB pixels and make the exterior fully transparent. Convey the mod's function through familiar, conventionally oriented symbols rather than lettering. Preserve DSP motifs and consistent materials across related mod icons. During localized edits, preserve all unrequested geometry, placement and styling from the chosen reference; do not redesign surrounding structures to produce an overlap. Use clear foreground occlusion for intersecting forms without losing the main symbol's silhouette, and check contrast in 64x64 and 32x32 side-by-side previews. Keep unselected icon candidates under `artifacts/`, outside release package directories. ## Architecture - UXAssist Dark Fog buy-out belt signals keep each item ID, per-Metaverse rate, localization key, and embedded icon path in one definition. Name embedded icon files after the current English item names and synchronize resource includes and loader paths when renaming them. Preserve the legacy signal and saved-stock order. Rates represent equivalent single-material value: a native bundle of 10 Silicon-based Neurons, 10 Negentropy Singularities, and 10 Matter Recombinators per Metaverse corresponds to 30 of any one selected material per Metaverse. - CheatEnabler's tech upgrade / downgrade feature lives under `Patches/Tech`; `TechTweaksPatch` owns the config (reusing `General/UnlockTech`), the `[ModFeature]` lifecycle, the `UITechTree` UI patches and the `UITechNode.OnPointerDown` transpiler, while the click decision, key-modifier decoding, downgrade recursion, UI and the per-function inverse of `GameHistoryData.UnlockTechFunction` stay in their own classes. Per-frame input goes through the registry's `OnInputUpdate`, so no separate `VFInput.OnUpdate` patch is added. `TechFuncRevert` must keep covering every `UnlockTechFunction` case: functions without a drift-free inverse are recomputed from the `Configs.freeMode` base values plus the levels still applied across all techs, never by replaying the whole tech tree, because a replay would re-apply the `func 30/31` station rescaling and the `func 5/38` package resize instead of restoring them. - CheatEnabler's custom critical-warning texts are a single string behind two gates, and every feature that wants one takes part in both priority chains: `WarningSystem_hasCriticalWarning_Transpiler` (an OR chain deciding whether the banner appears at all) and `WarningSystem_UpdateCriticalWarningText_Transpiler` (deciding which text it shows). Tech downgrade mode is first in both so it displays on its own, without either build toggle being on; previously the banner could only appear while `Build without condition` or `No collision` was enabled. Extend the chains instead of overwriting `criticalWarningTexts` from another patch. - `ModFeatureRegistry` discovers dependent-mod features during `Awake`; feature initialization is eager, while UXAssist alone drives the deferred start, input, update, and uninitialization lifecycle. Keep dispatchers internal and idempotent. - Apply config-controlled patches from their owning feature's `Start` and `SettingChanged` handlers. Shared lifecycle helpers must only manage always-on patches and must not override saved option states. - Proto-dependent features must tolerate calls before preload completes and retry via `UXAssist.Common.GameLogic.OnDataLoaded`. Mark changes applied only after capturing valid originals and successfully mutating the proto. - Architect-mode virtual stock applies only to player inventory and construction previews, including logistics bots, drones, and vessels. Keep cached package statistics consistent for inlined getters, preserve physical capacity and native ref/out contracts, and restore native statistics on disable. - Dispatch UXAssist shortcuts from the postfix of `VFInput.OnUpdate`, after DSP refreshes modifier and UI state. Keep typing/menu guards and per-frame registry guards; do not poll from an independent `Update()` or logic-tick callback. - Register localization keys through each project registration class and use `.Translate()` with keys. Do not add Chinese literals at call sites. - Prefer `UXAssist/Common/GameConstants` for item, tech, logistics, and Dyson sphere constants instead of inline literals. - Persist mod data through `IModCanSave` from DSPModSave. - Use `ModCompatHelper` for external plugin/type/member resolution and preserve legacy public type identities when refactoring reflection targets. Use `DysonSphereReflection` for DSPOptimizations-compatible Dyson sphere fields. - Use `nameof` for members exposed by the publicized compile-time game assemblies, even when the corresponding methods are private in the original game DLL; use string member names only when the publicized reference truly omits them. - Performance-sensitive Harmony transpilers must include the standard target/fallback header and use `TranspilerGuard` when a matcher can fail; returning original instructions is the fallback. Match named enum members and semantic calls or fields instead of hard-coded enum values or local-variable slots. Validate injected stack operand types and branch destinations, not just successful matching. - `PatchImpl.Enable(true)` must remain fail-soft: log, unpatch, and leave the patch unset if Harmony application fails so config delegate chains remain consistent. - Overlay UI state must converge from actual game state on periodic updates, not depend only on one-shot event or patch callbacks. Treat replacement of a planet transport as a lifecycle boundary and clear its dependent overlays once. Station IDs are reusable indices, and a stable planet ID or factory reference does not imply stable transport ownership. Cloned controls must reset runtime state while retaining source styles; use `UXAssist.UI.Util.GetPreferredWidth` for dynamic text and `ResetButton` for cloned buttons. Preserve the source tip settings when resetting cloned help buttons so the game's native tips work; do not replace them with separate dialogs. Shared button sizing must use anchor-relative child positions so text and icons remain aligned after a button pivot changes. - Bulk planet resets must unregister entity markers through `DigitalSystem.RemoveMarkerComponent` before replacing entity pools or the digital system; `GalacticDigitalSystem` retains shared marker references across planets. - Logistics station overlays must refresh through the native UI lifecycle, independently of typing guards. Reconcile cached tips against live station/entity identities and recycle local tips when stations are removed. - Planet vein utilization counters belong before resource labels, not beside native icons or highlight controls. Keep resource labels in their native layout and preserve the counters' row-based vertical position when rows are reused. - UI-only options must preserve native progression, statistics, and event delivery. Suppress presentation handlers rather than bypassing authoritative game-state setters. - Expanded terraform brushes must raise both the input-size limit and the operation-local clamps in `PrepareFlattenPoints` and `PrepareRestorePoints`, with buffers sized before either preparation path runs. - Space-scene rendering suppression must require the native in-game hide-UI state and exclude menu demos and combat cutscenes. A hidden player model alone does not imply hidden scenery; use the same eligibility check for drawing and planet-simulator visibility. - LiveStreamAssist browser overlays must use single-flight polling and discard stale work after connection changes. Compound queries must reject mixed session IDs; cache only positive production indices so newly tracked items remain discoverable. - LiveStreamAssist production reads must schedule the native extra-info calculator for queried factories independently of the statistics UI. Deduplicate and throttle refreshes, let active native batches finish, and clear pending factory indices and deadlines at session boundaries. - LiveStreamAssist `ReflectionReader` caches bounded per-type member metadata and clears it during API uninitialization; do not cache mutable game values or arbitrary request results. ## Automation Architecture ### Auto-construct - `AutoConstructEnabled` controls patch activation; `AutoConstructButtonEnabled` controls only button visibility. Never couple them. - Keep planning bounded and allocation-free. Follow native construction eligibility and planet-local surface movement semantics. - The planner owns only its generated `MoveTo` orders. Clear an active auto order before resetting planner state on disable or planet changes, without clearing user orders. Recovery detours must return control to the construction route. - Keep obstacle recovery at the current flight altitude. Validate lateral detour and escape waypoints against physics before issuing them, and retain recovery state to retry broader routes instead of treating an exhausted candidate list as success. - Let native flight control settle altitude after construction arrival; do not force a target altitude from auto-construct. The native non-gas flight baseline is 15f, while gas planets use a different lower bound. ### Auto-cruise - `PlayerPatch.AutoNavigation` is the only auto-cruise implementation. Its Harmony patches follow `AutoCruiseEnabled`; use auto-cruise terminology in user-facing text rather than the game's native autopilot terminology. Keep persistent status and the current configured shortcut on the auto-cruise button, without a separate HUD label; fix its left edge so adaptive width grows rightward without overlapping the auto-construct button. - Use one navigation lifecycle path for target state and reusable obstacle data. Require a resolvable target, yield to `player.navigation.navigating`, and reject an active native autopilot before reporting that auto-cruise started. - Preserve native movement and braking conventions; manual warp input takes precedence. - Use `MySideSlider` consistently for auto-cruise numeric settings. Align slider starts to the widest localized row label and size tracks so their value labels sit nearby. Keep each slider and its value label on a shared vertical center with explicit anchors and pivots, without additional row offsets. ## Review Standard - Fix root causes with minimal focused changes. Do not alter unrelated behavior, add copyright headers, commit changes, push branches, or create branches unless requested. Stage and commit only explicitly named task-related files, leaving unrelated working-tree changes untouched. Use normal pushes; do not rewrite remote history unless explicitly requested. - Before handoff, run the narrowest relevant build or test, then `git diff --check`. Mention unrelated pre-existing failures instead of changing them. - For game updates, also check Harmony target resolution and affected IL patterns against the original game DLL; compilation alone does not validate runtime patches.