Files
DSP_Mods/AGENTS.md
T

17 KiB

Agent Guidelines

Rules

  • Keep AGENTS.md concise: record important project standards, recurring pitfalls, and short durable architecture references. Add guidance only when useful for future work; omit details that can be read directly from code.
  • Keep investigation evidence, work history, completed plans, and implementation snapshots out of AGENTS.md. If work history needs to be retained, put it in a separate document and add only a brief link here.
  • Changelogs describe only user-visible changes relative to the previous release. Group changes by feature; omit implementation details, validation history, and fixes to defects introduced and corrected within the same version. Consolidate unreleased work into the feature's final behavior instead of listing its development iterations.
  • Unless the user explicitly requests a version bump, add changelog notes only to the latest existing version and do not change version numbers.
  • Write code comments and non-localized documentation in English. Keep English and Chinese sections of bilingual READMEs and changelogs synchronized; update README feature and usage descriptions when release changes affect them.
  • 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 <game_root>/DSPGAME_Data/Managed/Assembly-CSharp.dll.
  • Resolve in-game terminology from <game_root>/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. Overlay JS client: 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 <project>/<project>.csproj -c Release --no-restore. If NuGet assets are missing, run dotnet restore <project>/<project>.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 <Version> is the single version source and packaging synchronizes package/manifest.json. Keep the latest English and Chinese changelog headings and notes aligned with <Version>; preserve existing unreleased notes and historical entries. Describe relevant triggers when documenting fixes to previously released behavior.
  • 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

  • Fixed-building UXAssist power reports include each selected logistics station, distributor, or battle base at its captured configured charging maximum in watts, not its transient draw. Keep charging power separate from accumulator exchange and do not double-count advanced miners or gas collectors. Blueprint and prebuild capture use native stored settings or prefab defaults when no charging setting is applied.
  • UXAssist production calculations must use immutable snapshots captured from loaded Proto, PrefabDesc, and Cargo data on the game thread. Keep the planner and fixed-building analyzer pure-managed, express material rates in double items per minute and power in watts, and report unknown material and power results independently with structured diagnostics. Convert native ticks, fixed-point speeds, and per-second rates explicitly. Use native facility-specific production and power rules; keep generation, accumulator charging and discharging, and Dyson-sphere demand separate. Require explicit resource and operating settings when they cannot be captured, and never capture transient runtime throttles such as the miner output damper. Treat a stored sandbox boost mode as applied only through an explicit or live-captured BoostEnabled state. Verify native rules against the original DLL, compile affected mods, and keep the synthetic UXAssist/tools/ProductionCheck checks passing; leave in-game validation to a person rather than automated gameplay or save parsing. See production architecture.
  • Production catalog synthetic recipe IDs are calculation-only negative output item IDs; never pass them to native recipe lookups or setters. Rebuild the catalog on game begin after preload mutations, and invalidate derived caches on ProductionCatalogService.Changed, including catalog clearing. Preserve accumulator coating through exchange and bound spray reuse by same-item output and demand. Live-selection operating overrides use signed object IDs; blueprint overrides use blueprint indices. Keep renewable generation at ideal rated conditions and do not count gas collectors' self-fueling as grid consumption.
  • CheatEnabler belt-signal upstream statistics use the shared production planner's independent production and consumption ledgers. Cache per-item material results by catalog and spray settings, keep separate per-belt fractional accumulators, and never run the solver in the logic tick. Missing data must not interrupt item generation.
  • 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.
  • Tech downgrades must validate the full dependency cascade and capacity reductions before changing game state. Recompute non-invertible bonuses from native defaults and surviving levels; replaying unrelated unlock side effects can corrupt inventory geometry and station limits.
  • Custom critical-warning text must participate in both WarningSystem.hasCriticalWarning and WarningSystem.UpdateCriticalWarningText; preserve native warnings and use one shared display priority.
  • 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<T>.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.