astral-genesis
CLAUDE.md3 starsChanged 52 days agoMITView on GitHub
Guidance for Claude Code (claude.ai/code) when working in this repository. Open the linked doc when you start working on that area — that is where the mechanics, invariants and rationale live. Adding knowledge: the summary and the link go here, the explanation goes in the doc. Any section here that grows past a few lines belongs in docs/astral-genesis/ instead. Keeping docs and code comments true to the code is the docs-sync skill's job. Astral Genesis — a third-person roguelike dungeon-crawler…
In this repository5 other files it gives its agents.
- commit-messageSkill
- docs-syncSkill
- gameplay-testingSkill
- project-statusSkill
- shipSkill
The file
Files
CLAUDE.md
Guidance for Claude Code (claude.ai/code) when working in this repository.
How to use this file
Open the linked doc when you start working on that area — that is where the mechanics, invariants and rationale live.
Adding knowledge: the summary and the link go here, the explanation goes in the doc. Any section here that grows past a few lines belongs in docs/astral-genesis/ instead. Keeping docs and code comments true to the code is the docs-sync skill's job.
Working rules
- Research the topic on the internet before starting a task. Before planning or writing code, gather what is known about the subject — Godot docs for the APIs involved, established practices, known pitfalls — with web search, and only then propose the plan. Memory of an engine that moves this fast is not a source.
Project
Astral Genesis — a third-person roguelike dungeon-crawler set in a post-apocalyptic underground complex. Each run is a procedurally generated graph of rooms rather than a linear level, and the core mechanic is possessing bodies: the player cannot survive on their own for long and stays alive by taking over the bodies they find. Grim, muted sci-fi look.
The project language is Russian. Documentation, code comments and commit messages are written in Russian — match that language.
Engine specifics (project.godot): Godot 4.7.2, Forward+, Jolt Physics (3D) with physics on a separate thread.
Running, testing & building
- Running the game: play the project from the Godot editor, or play a scene directly (F6) to skip straight into it. Zed launch configs:
.zed/debug.json(adaptergodot). - Testing and debugging is the
gameplay-testingskill's job — it writes and runs the headless checks indev/(godot --headless <scene>, they exit nonzero on failure) and carries the manual-playtest checklist. Invoke it rather than reinventing a run command; there is no third-party test framework (GUT/gdUnit) in this project, the checks are plain Godot scenes on a shared harness (dev/check_harness.gd), all of them run bydev/run_checks.ps1locally and by the «Headless-проверки» job in CI. For what headless cannot judge — timings, sound, feel — the state for a live run is set up by the debug overlay (dev/debug_overlay.tscn, F1): the skill screen anywhere, layer teleport, decay off, and in its debug menu (`) skill points, Architect essence and teleport to unique rooms. It lives indev/and is loaded by path, neverpreload, becausedev/*is excluded from export — no file must mean «no cheats», not a broken build. Отладочный оверлей. - The polygon (
dev/polygon/polygon.tscn, F6) is where one mechanic is worked on in isolation: it inheritsworld.tscn, so systems are the game's own, but there is no run — a flat arena with a station per mechanic (first: hound animations — clip stand, treadmill puppet driven by the realS_BodyAnimation, a body to possess; Blender re-exports compared fromdev/polygon/clips/). A new mechanic is a new station, not a new scene. Полигон. - Releases are a button, not a merge.
project.godotholds the version being developed: it is bumped once at the start of a cycle withbash .github/scripts/set_version.sh X.Y.Zin a PR and never edited by hand; Actions → «Релиз» → Run workflow tags master and publishes it. Every other build — each PR, each push to master,dev/release.ps1→dist/— is numberedX.Y.Z-dev.N+hash, shown in the main-menu corner and the debug overlay, so a bug screenshot names its commit. Details: Релизы и сборка. - Cloud sessions (Claude Code on the web) are set up by the SessionStart hook
.claude/hooks/session-start.sh— git-lfs and LFS objects, the GECS submodule, tags, Godot, pwsh, a cold import; it does nothing on a local machine. Re-import after asset changes withbash dev/import.sh, never baregodot --import: multithreaded import hangs headless. Релизы и сборка → Облачная сессия Claude. - Assets (
.glb,.svg, images) are tracked via Git LFS — see Конвенции проекта. - The Blender side of the asset pipeline is an add-on whose source lives in
tools/blender/— it exports one.glbper collection and turns collision settings into real physics nodes on import. It is linked into Blender's extensions folder rather than copied (tools/blender/install.ps1), because two diverging copies is the failure mode that folder exists to prevent; tests:tools/blender/tests/run_addon_tests.ps1.tools/carries a.gdignoreso Godot never scans it. tools/blender/README.md.
Code style
- Hard tabs, LF line endings, UTF-8. Otherwise the official GDScript style guide:
snake_casemembers and functions,PascalCaseclasses,CONSTANT_CASEconstants,_prefix for private members and unused parameters. - Typed GDScript: annotate parameters and returns, prefer inferred
:=for locals. - Every script opens with a short class-level comment saying why it exists — one to three lines plus a link to its wiki section, as a
##block afterextends(it reaches Godot's built-in docs) or a#header aboveclass_name. Two blank lines between top-level functions. - Code documents itself; comments only mark what a reader would trip over — an engine trap, a non-obvious constraint, a workaround — in one to three lines at the line they concern. How a mechanic works, its history and rejected alternatives live in the wiki, never duplicated in code; move unique knowledge to the wiki before deleting a comment. Rules and the audit script: the
docs-syncskill. Comments are in Russian. - New scripts go through the templates in
src/script_templates/so the base-class conventions hold. - Scenes hold the structure, scripts hold only the logic. A UI's node tree, layout, styles, materials and static text are authored in a
.tscn; the script finds its nodes (%UniqueName,@onready) and drives them — it does not assemble the tree withNode.new()/add_child()or build materials and gradients in code. Elements whose count is known only at runtime (list rows, map labels) are instanced from their ownPackedScene, not put together node by node._draw()is drawing, not tree-building, and stays in scripts. The HUD and the menus are migrated (15.10): a UI element made with.new()comes out without its children — create it withinstantiate()of its scene. Layouts flex with the window: every screen fits the 1280×720 base and stretches beyond it — edges by anchors, side-by-side columns sharing width through containers and stretch ratios, never a column at a fixed x. Конвенции проекта §7, migration: Меню — сцены вместо сборки кодом.
Git conventions
- Branches — everything merges via PR into
master, nothing is committed straight to it. Feature/fix/docs work (feat/kebab-case,fix/kebab-case,docs/kebab-case, …) branches frommasterand merges back into it; there are no release branches — the changelog of a version is the PRs between two tags (--generate-notes). Branch protection is deliberately off: the release workflow may push a version bump tomaster. Why this shape: Работа в master и релизы тегами. - Commit subject:
Область: что сделано— Russian, area capitalized, no trailing period. E.g.Двери: запечённый меш вместо процедурного бокса. This is not Conventional Commits — do not writefeat:/fix:. - Commit body: Russian prose explaining why, grouped in paragraphs by area when a change spans several. Do not list changed files — the diff already does that.
- Drafting the actual message — reading a diff and writing it in this project's voice (diagnosis-first for fixes, rejected-alternatives-first for design decisions) is the
commit-messageskill's job. Unrelated changes go into separate commits. - Local git work — PR flow (
--base master, PR state viagh pr view, never inferred fromgh pr list), staging only your own files because other sessions work in parallel worktrees, and GPG-signed commits: a non-interactive shell cannot reach pinentry, so checkecho test | "$(git config gpg.program || echo gpg)" --clearsign >/dev/nullbefore the first commit — with git's own gpg, never the first one onPATH: Git Bash's/usr/bin/gpghas an empty keyring and fails even when signing works — and ask the user if it hangs — never retry silently or bypass signing. A stalled LFS push has its own diagnosis order. Релизы и сборка → Работа с git.
Known environment traps
- GDScript and Python are edited with Edit/Write, never through bash heredocs — a heredoc silently collapses backslash line continuations.
- Headless checks lie in two ways: a runner that exits zero on failure, and a check that leaves the player's real save changed. Both are covered in the
gameplay-testingskill, «Как писать проверку» (sound in headless is already host-mixed byAudioManager). - Windows host: run Python as
pythonorpy, neverpython3—python3resolves to the Microsoft Store stub inWindowsAppsand fails with «Python was not found». Anything from PATH or a.ps1goes through the PowerShell tool; Bash is for POSIX scripts only. A CLI that is missing from PATH (e.g.pdftoppmfrom poppler) is an install job for the user (winget install poppler) — say so instead of retrying. - Blender is not on PATH; its path, MCP-vs-
--background, and «grep the addon's source before claiming Ucupaint can't do something»: tools/blender/README.md → Blender из агента. - Kit dimensions are taken from the doc, never from memory, and the kit build scripts /
level_kit.blendplaceholders are not restructured unasked: Метрики и кит §3.
Architecture at a glance
Each area below is one paragraph of orientation. Read the linked doc before reworking that area.
ECS — the whole game is built on GECS (addons/gecs/), a git submodule pinned to release-v9.2.0; never edit files under it, they are upstream (git submodule update --init after cloning). Components (C_*) are pure data, systems (S_*) hold all behavior, entities (E_*) are containers, observers (O_*) react to component changes. The frame loop is driven manually in src/world/main.gd over named system groups. Three rules that cause silent breakage when violated: order between systems is declared only through deps() — GECS topologically sorts each group and moves a dependent system to the end, so scene node order guarantees nothing (dev/system_order_check guards the result); raycasting systems must live in the "physics" group (Jolt is threaded, space-state is only safe from _physics_process), and structural changes — adding/removing components or entities — must go through the cmd buffer, never directly inside process() (systems iterate archetypes zero-copy, so a direct change skips entities); writing component fields is unrestricted. Everything else — the full model, «Правило v9» in detail, ECS patterns and pitfalls: GECS и правила движка.
World generation & run flow — a run is a deterministic graph of rooms and corridor branches generated from a seed, streamed a whole layer at a time by the RunManager autoload; the save holds the seed, a snapshot of the generation knobs (data/world_gen_config.tres), the generator version (a run saved on another version restarts at the entrance — bump RS_LevelGraph.GENERATOR_VERSION whenever a change alters the world for the same seed) and progress, never the rooms, which are regenerated. A room's scene is chosen before its edges — it gets exactly as many edges as it has doors: its scene's, or, for a room assembled by socket mask (C_RoomShell on the scene root carries its footprint and wall kit), a per-node roll in its preset's range, never more than its sockets. Which branch a door opens into is decided by the layout, not the graph: the planner runs inside graph generation, builds one corridor network per floor and cuts it into corridors at junctions — every corridor, the stretch between two junctions, is its own graph node — and the graph records those nodes and edges and keeps the layer plan (RS_LevelGraph.layer_plan) — pre-assigning doors to branches made layouts unplannable and forced corridors to wrap rooms. Corridors are assembled at spawn from a tile kit; the current node changes by the player's presence, not by pressing a door. Layout never sees the world: the planner works in cells and sides of the grid in src/grid/ (topology, embedding, router, and the GridView node that draws it — no game dependencies), and the cell size lives only in the layer plan's embedding — never write metres or a cell-size constant into layout code. Physical doors are bound to graph edges at spawn time rather than authored. What fills a room at spawn — roster enemies on EnemySpawn* markers, essence finds on EssenceSpot*, caches in dead ends, prop dressing (any node with dress(rng), RoomDressing) — is rolled from its own hash([run_seed, depth, node_id, marker]) RNG, never the graph's shared rng: a draw from the shared one would shift the whole graph for the same seed; the enemy navmesh is baked per layer at spawn (geometry parsed on the main thread, baked in a thread). Floors of a layer are joined by a two-level stairs room whose box declares its door sockets (C_RoomShell.door_sockets), layers by portals — so a portal edge is recognized by its type (RS_LevelConnection.is_portal), never by a floor or depth difference: the stairs' upper door reaches the floor above through an ordinary corridor edge. Which room scene lands on a node is decided by two independent axes that must never be merged: structural tags («what the room can do» — a hard subset filter) and room_type («what kind of place it is» — a soft preference from data/room_type_catalog.tres, with per-depth ranges). Putting a type into tags turns it into a hard requirement — that is what once stopped lab_room from ever appearing. What each tag means is written down in a descriptive-only dictionary (data/room_tag_catalog.tres): the selector never reads it, so a tag missing from it still works — making it authoritative would turn «add a tag» in the editor tools into a silent break. Цикл забега.
Interaction — an interactable needs a C_Interactable component, a collider on the interactives layer, and an interact() method or interaction-action resources. A raycast drives highlighting and the on-screen prompt — not from the camera but from the form's eyes towards the point under the crosshair (AimRay), so range counts from the body and walls cut it. Взаимодействие.
Third-person camera — the camera hangs over the shoulder on a top_level rig of two SpringArm3Ds sized from the worn form; the mouse turns the camera; walking, the body keeps the camera's facing and strafes on walk/back/side clips blended by local velocity, running turns it towards where it moves (S_BodyTurn). Aim is two rays: one from the camera through the screen centre finds the point (S_CameraAim), the second from the eyes to that point decides range and walls (AimRay, shared by interaction, capture and attack) — never aim gameplay from the camera itself, it sees round corners the body cannot. The camera passes exactly what the form passes: the arms' mask is the rig's live mask cut to geometry, so phasing lets it through grates, and whatever it passes fades near it on copied materials. Physics interpolation is on project-wide: a teleport calls reset_physics_interpolation(), a node moved in _process turns interpolation off. Камера от третьего лица.
Body-snatching & decay — the core mechanic. A body's characteristics are separate components in its scene, not fields on a stat sheet, so capture and expulsion move them generically — and its collision shape, eye level and facing come from that same scene, never from numbers in code (the eye level places the rig's Eyes marker — where aim rays start and enemies look — and the camera's pivot, no longer the camera itself); the player's lifespan is one resource held in two pockets (their own and the worn body's). An ability is a component and each ability is its own system: a legless body carries no C_Jump and never enters the jump system's query, so movement contains no branch on «what am I wearing» anywhere; the soul's own abilities (C_Flight, C_Phasing) mirror that with C_SoulTrait and sleep while embodied. Slot abilities (keys 1–4) are C_Ability traits; on a clean exit the soul keeps copies in C_AbilityLoadout, and a body's ability overrides the soul's in the same slot — the copy sleeps, because an entity holds one component per class. Skills reach mechanics through one rule: a mechanic reads a computed stat — the author's base plus the soul's modifiers (C_StatModifiers) — never the raw field, so the base is never overwritten and a new skill is a line of data in data/skill_tree.tres rather than a patch to the mechanic. Захват тела.
Звук — идёт через byProd, событийный аудиодвижок: механика просит событие (event:/sfx/walk), а что прозвучит — решает проект, собранный в редакторе byProd. Подключён GDExtension-биндингом addons/byprod (godot-byprod, MIT). Четыре вещи, нарушение которых ломает всё тихо или фатально: нативный рантайм не входит в репозиторий (лицензия Madrigal) и его отсутствие обязано означать «нет звука», а не «не запускается» — поэтому AudioManager называет классы расширения только строкой через ClassDB, никогда идентификатором; менеджер ровно один на процесс — второй роняет рантайм segfault'ом, поэтому его владелец автолоад AudioManager, а не тот, кому он понадобился; пауза идёт уровнем тика, и подписку на неё ставит AudioManager — в рантайме она выключена по умолчанию, а разовый звук после release_when_finished() игра уже не держит и остановить не может, так что подписать его позже неоткуда; в репозитории лежит только ВЫГРУЗКА проекта звука — assets/sound/*.byprod и *.bybank; редакторский проект и волны-исходники живут вне репозитория, а выгрузка обязана быть в git и в include_filter экспорта, иначе сборка молча выходит без звука. Первый потребитель — шаги: C_Footsteps это характеристика тела (лежит в его сцене, переносится при захвате), а S_Footsteps озвучивает ходьбу тем способом, каким собрано событие: разовым звуком на каждый отмеренный ПУТЁМ, а не временем шаг — либо одной петлёй с параметром темпа. Звук.
Editor tooling — addons/game_design_tool is the single designer-facing plugin: a main-screen tab «Геймдизайн» holding «Шаблоны» (entity templates), «Редактор пресетов» (room presets and the tag dictionary) and «Генератор мира» (3D layer preview plus the seed sweep), with several non-obvious traps around @tool resources, lazy tab building, inspector labels and Label tooltips. Редакторские инструменты.
Source layout & naming
src/ folders are colored in the editor (project.godot [file_customization]) and files are prefixed by role:
| Prefix | Class | Folder | Role |
c_ | C_* | components/ | data components |
s_ | S_* | systems/ | behavior systems |
e_ | E_* | entities/ | entity scenes/scripts |
o_ | O_* | observers/ | component observers |
a_ | A_* | resources/interaction/, entity dirs | interaction actions (RS_InteractionAction) |
rs_ | RS_* | resources/ | data resources (configs, graph, presets, skills) |
Autoloads (src/autoloads/), in declaration order: GameConfig, SettingsManager, SkillManager, ArchitectManager, UIManager, WorldSave, RunManager, RunStats, AudioManager, ECS — declaration order in [autoload] is _ready() order, and RunStats subscribes to RunManager's signals, so it must stay after it. Tunable game data lives as .tres under data/ and is edited in-editor, not hardcoded. Player-facing text goes through translation keys (assets/locale/ui.csv, tr(); data stores the key, never the finished string; headless checks never assert on keys or translated text) — all player-facing text is migrated; designer-only labels (room type display_name, tag dictionary, preset names) stay plain strings on purpose, and a player-facing name gets its own key field (map_name). Autoload responsibilities, physics layers, the project-wide UI theme, the localization convention and the key-rebinding codec: Конвенции проекта.
Документация — карта
docs/astral-genesis/ is an Obsidian vault (Russian, [[wikilinks]]).
| Area | Doc |
| What is actually implemented, subsystem by subsystem | Состояние проекта |
| ECS model, «Правило v9», FSM/pattern knowledge | GECS и правила движка |
| World gen, layer streaming, doors, travel, save/load, run summary | Цикл забега |
| Interactables, raycast, prompts, screen messages | Взаимодействие |
| Third-person camera rig, two-ray aim, body turn, near-camera fade, physics interpolation | Камера от третьего лица |
Capture/expel, body traits, decay model, E_Body contract | Захват тела |
| Editor tooling traps, template authoring | Редакторские инструменты |
| byProd, единственность менеджера, пауза, шаги | Звук |
| Physics and render layers, UI theme and color tokens, prefixes, rebinding codec | Конвенции проекта |
| Blender→Godot: раскладка assets, бюджет карт, ORM, подмена материалов | Blender-Godot пайплайн |
| Масштаб (клетка vs тело), контракт клетки-куба 8 м, сокеты, кит P и стили поверх него, двустворчатая дверь и её карман | Метрики и кит |
| Раскраска по классам ассетов: палитра, детальный слой, декали, трим-лист | Визуальный стиль и текстуры |
| Debug cheats for a live run, and which tool checks what | Отладочный оверлей |
| Polygon: one mechanic in isolation, stations, clip versions | Полигон |
| CI, build numbers, releases, cloud-session setup | Релизы и сборка |
| Controls, player-facing | Управление |
| Lore | История |
| Roadmap, task cards | docs/astral-genesis/Задачи/ |
Four skills maintain and exercise all of the above: docs-sync (keep docs, code comments and this map true to the code), gameplay-testing (write and run the headless checks, plus the playtest checklist), commit-message (draft commit messages in the project's actual voice), and project-status (what's in progress, what's planned, what loose ends remain — calls docs-sync for the documentation side).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

