--- name: gum-cli description: GumCli — headless CLI for Gum projects. Triggers: gumcli commands (new, add-forms, check, edit, diff-standards, codegen, codegen-init, fonts, screenshot, svg), Gum.ProjectServices, ProjectEditService, HeadlessErrorChecker, ProjectLoader, HeadlessCodeGenerationService, CodeGenerationAutoSetupService, FormsTemplateCreator, DiffStandardsService. --- # GumCli Reference ## What It Is **GumCli** (`gumcli`) is a cross-platform .NET 8.0 console app that lets developers create, validate, and generate code for Gum projects without the editor. Primary use cases: CI pipelines, scripting, editor integrations. **Location:** `Tools/Gum.Cli/` **Depends on:** `Gum.ProjectServices` → `GumCommon` ## Commands | Command | Purpose | |---------|---------| | `gumcli new [--template] [--theme ] [--platform monogame\|kni\|kniskia\|raylib\|stride\|silknet\|brutal] [--source-linked] [--no-restore] [--canvas WxH] [--demo]` | Create a new project. `--demo` keeps the Forms template's demo screen; without it `GumProjectTemplateWriter` removes the screen, its sidecars and its reference after writing, so a `--platform` host names no screen (`NewProjectRequest.IncludeDemoScreen` defaults to true for other callers; the tool dialog keeps it and removes it itself). `--canvas` sets `DefaultCanvasWidth`/`DefaultCanvasHeight` after the template is written (`NewProjectDefaults.ApplyCanvasSizeToFile`). Templates: `forms` (default, includes all Forms UI controls) or `empty` (minimal). `--platform` makes `` a project folder holding a runnable NuGet-referencing host project (`PlatformProjectScaffolder`; templates embedded under `Templates/Platforms/`) with the Gum project at `Content/GumProject/` and codegen settings written for it, then runs `dotnet restore` (`--no-restore` skips). `--theme` (forms template only) starts from a bundled Forms theme such as Meadow; `FormsThemeLocator` finds them in the release layout's `Content/FormsThemes`, in a checkout's `Templates/FormsThemes`, or in `Content/FormsThemes` beside `gumcli.dll` in the `dotnet tool` package (`Gum.Cli.csproj` packs the themes and `Templates/FormsBehaviors` there as pack-only items; `ToolPackageThemeLayoutTests` builds that layout from the pack items), and `FormsTemplateCreator.CreateFromTheme` copies one in with its shared behaviors staged into `Behaviors/`. `Standard` is the plain template. `Tests/Gum.Cli.Tests/ThemeCodegenTests` runs `new --theme` plus `codegen` over every theme. `--source-linked` swaps the Gum `PackageReference` (the `{{GumReference}}` placeholder in each `Host.csproj.template`) for a `ProjectReference` to that platform's runtime csproj in the checkout `GumSourceLocator` finds by walking up from the gumcli binary, then the cwd. `silknet` (alias `silk.net`) scaffolds Gum.SilkNet + `Silk.NET.Windowing.Sdl` + `Silk.NET.Input.Sdl` on desktop OpenGL 3.3 core, deliberately without ANGLE so SDL and Skia natives all come from NuGet on Windows/macOS/Linux; `kniskia` is refused on the Stable channel (`NoStablePackage`; Gum.KniSkia has only preview versions on NuGet, so it needs `--preview` or `--source-linked`; the flag lives in `HostPlatformInfo.HasStablePackage`) and scaffolds Gum.KniSkia (which brings `SkiaGameRendering.Kni.DesktopGL`), with the shared XNA `Game1.cs` and `Program.cs` (`Draw()` takes no canvas; `GumService` owns the Skia render target); `fna` is rejected (not on NuGet). The valid names live in one table in `NewCommand`, which the help text and the unknown-platform error both read. The folders and main files a new project gets are one rule set, `NewProjectLayout`, read by the creators and the New Project dialog; `NewProjectLayoutTests` pins it against the real creation for every platform, so a folder a template starts writing must be added there. A failed or canceled `NewProjectService.CreateFilesAsync` deletes only what the run created (`NewProjectJournal`); a file it overwrote stays as written. | | `gumcli add-forms [--behaviors-only] [--overwrite-behaviors]` | Merge the Forms template's Components/Standards/Behaviors/Fonts/FontCache/UISpriteSheet.png into an already-existing project, skipping anything already referenced. `--behaviors-only` merges only behaviors; `--overwrite-behaviors` rewrites a project behavior with the template's when the two serialize differently, so formatting alone never counts (`AddFormsOptions`, `AddFormsResult.ReplacedBehaviors`). Refuses (exit 2) when the target project is older than the template, via `ImportVersionGate`, the same check the tool's imports use. Backed by `AddFormsToProjectService`, which reuses `FormsTemplateCreator` against a throwaway temp project rather than duplicating its embedded-resource extraction. | | `gumcli check [--json]` | Validate all elements (.gusx, .gutx, .gucx) that belong to the project. Human-readable or JSON output. Pass the project file, not an element file (an element file exits 2). Use it for post-write validation of the elements you edited. | | `gumcli check-references [--json] [--fix]` | Detect (and optionally fix) `VariableReferences` rows whose left-hand-side scalars are not materialized into the state's `Variables` — the inconsistent shape commonly produced by AI agents and hand edits that bypass the Gum tool's author-time propagation. `--fix` runs `ApplyVariableReferences` on affected states and saves the modified element files. Scans Screens and Components only (StandardElements have known default-evaluating refs whose missing scalars are correct on-disk state — see [gum-tool-variable-references](../gum-tool-variable-references/SKILL.md) for the model). Exits 1 if anything is unpropagated. | | `gumcli diff-standards [--json]` | Compare the project's Standards against `StandardElementsManager.Self`'s programmatic defaults (the same source the Gum tool's File → New uses) and report variable-level drift. Exits 1 on drift, 0 on clean. Theme authors and CI use it to enforce the "Standards must match Default" invariant. | | `gumcli convert-to-json ` | Write a `.gumj` sibling plus a JSON sibling for every referenced element/behavior/animation file, leaving the XML untouched. Required for Native AOT / `PublishTrimmed`. Backed by `ConvertProjectToJsonService`. | | `gumcli resave [--raw]` | Load and save with no edits. Default loads like the tool (runs the standard-element back-fill in `GumProjectSave.Initialize`); `--raw` skips it so only the serializers run. `Tools/project-sweep.ps1` uses both to sweep real projects. | | `gumcli edit [--json]` | Apply an operations file (`{ "version": 1, "operations": [ { "op": ... } ] }`; ops `addScreen`, `addComponent`, `addInstance`, `addVariable`, `setVariable`, `addCategory`, `addState`, `exposeVariable`, `addBehavior`, `removeBehavior`, `moveInstance`, `moveState`, `removeScreen`, `removeComponent`, `duplicateComponent`, `removeInstance`, `removeState`, `removeCategory`, `removeVariable`, `unexposeVariable`, `clearVariable`, `extractToComponent`, `setVariableReferences`, `setBaseType`, `setInstanceProperty`, `setProjectProperty`, `renameElement`, `renameInstance`, `renameState`, `renameCategory`, `renameVariable`, `renameBehavior`, and the animation ops `addAnimation`, `removeAnimation`, `setAnimationLoops`, `addKeyframe`, `removeKeyframe`, defined in `ProjectEditService`, which delegates the animation ones to `AnimationEditOperations`; animations live in the element's `.ganx`/`.ganj` sidecar, so `PendingAnimationEdits` holds the changed sidecars, lets the error check and name checks see them, and `EditCommand` writes them before the project saves (rolling back if a write fails); only state keyframes are editable, sub-animation references and named events are not) and save like `resave`. `setProjectProperty` sets only the names declared in `ProjectPropertySetter` (`Version`, which only rises and reruns `GumProjectSave.Initialize` so the standard back-fill adds the new version's variables like the tool's load after a hand edit; `describe` omits and `setVariable` refuses, naming the version, a standard variable `StandardVariableVersionGate` says the project's version hides; canvas, `TextureFilter`, localization, font ranges/generator/spacing, `EngineProfile`, `SinglePixelTexture*`: the Project Properties a game or `gumcli fonts` reads), each validated like the tool (`BmfcSave.GetIfIsValidRange` for `FontRanges`, paths stored project-relative with `ProjectRelativePaths`, shared with `ProjectPropertiesChangeLogic`). `UseFontCharacterFile` and `FontRangeEntries` are refused with a message; `SinglePixelTexture*` is read only by the tool's canvas (`EditorTabPluginBase`), not the runtime, though `pack` bundles the file (`GumProjectDependencyWalker`). A new property goes in that one table and shows up in `edit --schema` (`GetProjectPropertySchemas()`) automatically. The rename ops call `ProjectRenamer`, which uses `RenameReferenceApplier` (the same class the tool's `RenameLogic` and Edit Variable use) for the references; the files that follow a rename (the element's animation file, its `.codsj`, a behavior file) are recorded in `PendingFileChanges` and written by `EditCommand` after the save. A file mixing animation ops with element, instance, state or category renames is refused. All or nothing: an invalid file exits 2, an op that cannot apply exits 1, and an error `check` finds only after the edit is reported as `check` reports it and exits 1; nothing is written in any of these cases. A removed element's file is deleted only after the save, and only if no remaining element writes to that path. `addBehavior`/`removeBehavior` (Components only) go through `ComponentBehaviorLogic`, which `ElementCommands.AddBehaviorTo` also uses; they refuse an unknown behavior, a duplicate, a Screen and a missing reference, and add no required instances (`check` reports those). `removeComponent` also drops the name from `FavoriteComponents` (`ElementRemovalLogic` via `FavoriteComponentList`, shared with `FavoriteComponentManager`). `removeComponent` has no refusal of its own: removing a component still used as an instance type (GUM0035) or base type (GUM0030) fails through that new-errors check. Ops take a Screen, Component or standard element (`ProjectElementFinder.Find`, also used by `describe`); only `addState`, `addCategory`, `setVariable`, `clearVariable`, `setVariableReferences` (no `instance`), `removeState` and `removeCategory` accept a standard one (`OperationSpec.StandardElements`, reported by `edit --schema`), and the rest are refused in `ProjectEditService.RefuseStandardElement` before they run. The CLI sorts state variables only for Screens and Components; a standard's variables are already in the order the tool writes. `setVariable` accepts only names `IVariableDefinedByTypeLogic` says the type defines (`Instance.Var` for an instance's variable), which includes the FormsProperties of the type's behavior chain (`FormsBehaviorChain.GetFormsPropertyDeclarations`, last in `GetCandidates` so a visual name wins); `VariableValueConverter.ResolveType` types them from the declaration (the tool's `StateVariableWriter` is untouched, so its saved shape stays), so the value converts and is stored with that type. `addComponent`, `addInstance`, `removeInstance`, `setBaseType` and `extractToComponent` keep derived components in sync through `IInheritanceSync` (`Editing/InheritanceSync.cs`), the same class the tool's `InheritanceLogic` calls; an op that changes instances or a base type must call it too, and a new tool inheritance reaction goes there, not in `InheritanceLogic`. `moveInstance` and `moveState` live in `ReorderEditOperations` and use `ListMover` (`Editing/ListMover.cs`), the same list move the tool's `ReorderLogic`, `MoveStateInDirection` and `MoveToCategory` call; exactly one position field is accepted and anything ambiguous is refused; `moveInstance`'s `index` is turned into a before/after of a sibling (`GetPlacementForIndex`). `duplicateComponent` uses `ElementDuplication` (`Editing/ElementDuplication.cs`), the copy the tool's `EditCommands.DuplicateSelectedElement` makes, and `PendingFileChanges.ElementDuplicated` copies the animation and `.codsj` (via `CodeOutputElementSettingsManager.CopySettings`, the tool's copy) after the save. `edit --schema [--json]` prints the op table from `ProjectEditService.GetOperationSchemas()`, so a new op shows up there with no CLI change. Each field in that table is an `EditField` with its JSON type (`string`, `bool`, `int`, `any`, `string[]`), and `ValidateOperation` checks values against the same table, so a field's type is declared only there; `DescribeCommandTests` checks that every reported type is enforced. | | `gumcli describe [] [--instance ] [--json]` | List the variables `setVariable` accepts (name, type, allowed values for enums and state selectors) plus the element's states and categories, via `ElementDescriptionService`; an element (not an instance) also reads back its base type, behaviors, instances (parent, `DefinedByBase`, `Locked`), exposed variables and variable reference lines, additive in `--json`. With no element it lists the project's elements and behaviors (`ProjectElementFinder.List`). The names come from `IVariableDefinedByTypeLogic.GetVariablesDefinedByType`, which the yes/no `GetIfVariableIsDefinedByType` is an `Any` over, so a new kind of variable is added in one place (`GetCandidates`) and both agree; `DescribeCommandTests` pins that every listed name applies. | | `gumcli codegen [--element ...] [--prune]` | Generate C# code. Requires `ProjectCodeSettings.codsj`. Per-element error check gates generation. `--prune` additionally deletes generated files with no matching element, plus their custom `.cs` when `CustomCodeStubDetector` (the tool delete dialog's rule) calls it an untouched stub; edited custom `.cs` and `.codsj` files are only listed. | | `gumcli codegen-init [--force] [--csproj ]` | Auto-detect `.csproj`, derive namespace and output library, write `ProjectCodeSettings.codsj`. `--csproj` also records the path as `CsprojPath`, which detection then reads ahead of the search. A Unity csproj (`Assembly-CSharp.csproj` beside `Assets/`) sets `GeneratedCodeFolder = Assets/`. | | `gumcli fonts [--font --size ... [--bold] [--italic] [--outline ]]` | Generate missing bitmap font files (.fnt + .png). `--font`/`--size` also bakes fonts no element uses (BBCode runs, oversampled sizes) through `ExtraFontRequest`; one style per run, invalid combinations exit 2. bmfont.exe is Windows-only; other OSes use KernSmith. | | `gumcli screenshot [--output] [--width] [--height] [--backend monogame\|raylib\|skia] [--background hex] [--scale n] [--set Name=Value]...` | Render a Screen or Component to a PNG via MonoGame DesktopGL (default), raylib, or SkiaGum on a CPU raster (no window). Pixel-accurate; cross-platform. `--background` clears to an opaque RRGGBB/RRGGBBAA hex color instead of the default transparent, for a more representative visual comparison. `--scale` enlarges the finished PNG (`PngUpscaler`, nearest-neighbor) after any backend renders at canvas or `--width`/`--height` size. `--set` (`ScreenshotVariableOverride`) applies through `GraphicalUiElement.SetProperty` after load and before layout in every backend, so live variable references follow; names resolve (`ResolveNestedVariable`, so `Hud.Bar.Visible` walks nested instances; `edit setVariable`'s `ResolveVariable` refuses such paths) and values convert through `VariableValueConverter`, the class `edit setVariable` uses (JSON-looking text first, then as a string), and a state name its category lacks fails instead of rendering unchanged. It never generates fonts: a font missing from the project's `FontCache/` renders as the default font (logged as "No usable font could be resolved"). `ScreenshotCommand` collects missing-font reports through `MissingFontHint` (fed by the runtime's `PropertyAssignmentError` events) and ends with one `hint:` line naming the files and `gumcli fonts`; a font only a `--set` override needs is not covered by plain `gumcli fonts` (the hint says to use `--font`/`--size`). | | `gumcli svg [--output] [--width] [--height]` | Render a Screen or Component to a vector SVG via SkiaGum's `SKSvgCanvas`. Bitmaps embed as base64. | | `gumcli diff-screenshots ` | Render every Screen and Component through both MonoGame and raylib and report pixel-level mismatches. | | `gumcli pack [--include] [--shake] [--roots ] [--keep ] [--roots-assembly ] [--skip-debug-only]` | Pack a project into a `.gumpkg` bundle. `--skip-debug-only` (opt-in, independent of `--shake`) passes the Debug Only elements (`DebugOnlyElementLogic`, includes derived components) to `GumElementReachability.Compute` as excluded; without `--shake` every other element is a root. A kept element that has an instance of or derives from an excluded one exits 2. `--shake` (opt-in) keeps only the Screens and Components that `GumElementReachability` (`GumCommon/Bundle`) reaches from every Screen plus the roots, and drops the files only trimmed elements use; Standards and behaviors are always kept. `--roots-assembly` reads the `[assembly: GumElementRoot]` attributes that the `GumElementRootGenerator` in `Tools/Gum.Analyzers` writes into a game assembly. A root that names no element exits 2. | | `gumcli stage-forms-behaviors ` | Resolve a Forms theme's behaviors (following shared-file links and overrides) and write them flat into a destination folder. | **Exit codes:** 0 = success, 1 = errors found / generation blocked, 2 = load failure, bad args, or non-Windows (fonts). **Docs:** Every user-visible gumcli change (a new command, option, op or behavior) updates its page under `docs/cli/` in the same PR. ## Architecture ``` Program.cs ├── NewCommand → ProjectCreator / FormsTemplateCreator ├── AddFormsCommand → AddFormsToProjectService (loads target, extracts FormsTemplateCreator into a throwaway temp project, merges in anything not already referenced) ├── CheckCommand → ProjectLoader → HeadlessErrorChecker ├── EditCommand → ProjectLoader → HeadlessErrorChecker (before) → ProjectEditService → HeadlessErrorChecker (after, diffed) → GumProjectSave.Save ├── CheckReferencesCommand → ProjectLoader → ReferencePropagationService (Detect / PropagateReferences). Sets ObjectFinder.Self.GumProjectSave so cross-element refs resolve. ├── DiffStandardsCommand → ProjectLoader → DiffStandardsService (project Standards vs StandardElementsManager.Self defaults) ├── CodegenCommand → ProjectLoader → HeadlessErrorChecker (gates) → HeadlessCodeGenerationService ├── CodegenInitCommand → CodeGenerationAutoSetupService ├── FontsCommand → ProjectLoader → HeadlessFontGenerationService (Windows-gated) ├── ScreenshotCommand → MonoGame/Raylib/SkiaGumScreenshotService (Gum.ProjectServices.MonoGame/.Raylib/.SkiaGum); shared request steps (ResolveSize, FindElement, PrepareOutputPath) live on ScreenshotRequest └── SvgCommand → SkiaGumSvgExportService (Gum.ProjectServices.SkiaGum) ``` Each command class has a static `Create()` returning a `System.CommandLine` `Command` with handler, then a static `Execute()` doing the work. **CLI-specific adapters:** - `ConsoleCodeGenLogger` — implements `ICodeGenLogger`, writes to stdout/stderr ## Gum.ProjectServices The headless service library GumCli depends on. All logic lives here; the CLI just wires it together. **Key types:** | Type | Role | |------|------| | `ProjectLoader` / `IProjectLoader` | Loads `.gumx`; detects malformed XML; returns `ProjectLoadResult` with fatal errors and non-fatal `LoadErrors` | | `NameRules` | Pure name-validation rules shared by the tool's `NameVerifier` and the CLI | | `HeadlessErrorChecker` / `IHeadlessErrorChecker` | Validates base types, behaviors, parent refs, variable types. Delegates from tool's `ErrorChecker`. | | `ProjectCreator` / `IProjectCreator` | Creates blank projects with subfolder structure | | `FormsTemplateCreator` / `IFormsTemplateCreator` | Extracts embedded Forms template resources | | `AddFormsToProjectService` / `IAddFormsToProjectService` | Merges Components/Standards/Behaviors/Fonts/FontCache/UISpriteSheet.png from a `FormsTemplateCreator` extraction into an already-loaded project, skipping anything already referenced by name | | `HeadlessCodeGenerationService` | The single orchestrator for per-element and batch code file generation (`GenerateCodeForElements`); shared by the CLI and the tool | | `CodeGenerationAutoSetupService` | Walks up to find `.csproj`, derives `CodeProjectRoot`, namespace, output library | | `CodeOutputProjectSettingsManager` | Loads/saves `ProjectCodeSettings.codsj` | | `ErrorResult` | POCO: `ElementName`, `Message`, `Severity` (`Warning`/`Error`), `Code` (e.g. `GUM0006`, may be null), `FilePath`. `check --json` emits `code`; scripts should match on it, not message text | | `DiffStandardsService` / `IDiffStandardsService` | Compares a loaded project's Standards against `StandardElementsManager.Self`'s programmatic defaults. Returns `DiffStandardsResult` with `Differences`, `MissingFromProject`, `ProjectOnlyStandards`. | | `ReferencePropagationService` / `IReferencePropagationService` | Detects states where a `VariableReferences` row exists without the corresponding materialized scalars in `Variables`, and propagates them on demand. `Detect` returns `DetectUnpropagatedReferencesResult`. `PropagateReferences` mutates the project (runs the static `ElementSaveExtensions.ApplyVariableReferences` per offending state) and returns the modified elements; the caller persists. Walks Screens + Components only; Standards are intentionally skipped (their default-evaluating refs would produce false positives). Expression evaluation depends on whoever wires `ElementSaveExtensions.CustomEvaluateExpression` — gumcli wires it in `Program.Main`. | **Non-obvious:** `HeadlessErrorChecker` is not a duplicate of the tool's `ErrorChecker` — the tool's `ErrorChecker` **delegates to** `HeadlessErrorChecker`. Zero duplication by design. `Program.Main` calls `GumExpressionService.Initialize()` once for every command, so `check`, `edit`, `codegen` and the render commands (`screenshot`, `svg`, `diff-screenshots`) evaluate references the way the tool does; a command never calls it itself. GUM0002 evaluates cross-element reference right-hand sides through it and silently reports nothing when it is unwired. Tests that cover this reset `ElementSaveExtensions.CustomEvaluateExpression = null` first, because other commands in the same test process leave it wired. **`Editing/` holds the tool's edit logic, not a copy of it.** Each `gumcli edit` op calls the same class the tool calls (`ElementCreationLogic`, `InstanceCreationLogic`, `InstanceAddRules`, `StateCreationLogic`, `CategoryVariablePropagator`, `CustomVariableLogic`, `ExposeVariableLogic`, `StateVariableWriter`, `ElementNameValidator`, `VariableDefinedByTypeLogic`, and for removes `ElementRemovalLogic`, `InstanceRemovalLogic`, `InstanceChildDetacher`, `StateRemovalLogic`, `VariableRemovalLogic`, `VariableOverrideRemover`, `VariableClearLogic`, which return what they removed from other elements, and for `extractToComponent` `ComponentExtractionLogic` plus `MovedInstanceReferenceDropLogic`, whose Find/Drop split lets the tool record undo between the two, and for `setBaseType` `BaseTypeChangeLogic` (the rules plus the change; the variable removal is `BaseTypeVariableRemover`, which the tool's `BaseTypeVariablePruner` wraps with undo recording, and an instance retype also runs `InstanceAddRules`), for `setInstanceProperty` `InstancePropertyLogic`, and for `setVariableReferences` `VariableReferenceValidator` (the tool's line checks) plus `VariableReferenceCascade.ReactToEdit` (the tool's whole reaction to an edit: the state's rows, `BehaviorToolOnlyReferencesApplier` for the behaviors' tool-only lines, other states, cross-element readers and instance internals; the tool's Variables tab and `setVariable`, `clearVariable` and `setVariableReferences` all call it, so an op that changes a value another row can read must too), which needs `Gum.Expressions` (Roslyn) and is why `Gum.ProjectServices` references it); the tool wraps them with undo, selection, plugin events and saving. `ReferenceFinder` and its result types live here too, under the `Gum.Logic` namespace. A new op extracts the tool's data change into `Editing/` first and switches the tool to it. The animation edits share `AnimationNameRules`, `AnimationKeyframeOrder`, `AnimationTopLevelNames`, `AnimationStateLookup` and `ElementAnimationFiles` (sidecar path, write-or-delete) with the Animations tab. `HeadlessErrorChecker` accepts a second constructor overload taking `IEnumerable` for extensibility; the CLI uses the single-argument overload. `NameRules` holds the name rules that need no tool service (common name check, C# name and keywords, Windows reserved file names, Android file names, `Standardize`, duplicate behavior names). The tool's `NameVerifier` delegates to it and keeps only the checks that need tool services; `CodegenCommand` passes a `NameRules` straight to `CodeGenerationNameVerifier`. A new name rule that needs only the name (or a list of existing names) goes in `NameRules` so the tool and the CLI cannot disagree. `ProjectLoader` runs `DetectSilentlyDroppedContent` after deserialization to catch incorrect XML element names (e.g., `` instead of ``, `` instead of ``) that `XmlSerializer` silently ignores. Without this, AI-generated files with wrong structure load as empty elements with no error. `CodeGenerationAutoSetupService` does not detect the output library: it leaves `OutputLibrary` at the `GumForms` default (Gum Forms, correct for every runtime) and always uses `ObjectInstantiationType.FindByName`. Namespace falls back to the `.csproj` filename (dots/dashes/spaces replaced with underscores) when `` is absent. `codegen` fails fast with exit code 1 if the resolved settings request an unsupported combination (currently: `OutputLibrary.Raylib` + `ObjectInstantiationType.FullyInCode`) — `CodeGenerator.AssertSupportedCombination` throws `NotSupportedException`, and `CodegenCommand` catches it before touching the file system. `CodeGenerationAutoSetupService` has two `Run` overloads: `Run(gumxFilePath)` for auto-detection, and `Run(gumxFilePath, explicitCsprojPath)` for when the caller already knows the `.csproj` path. The explicit overload validates the file exists and skips directory walking entirely; all namespace/OutputLibrary derivation logic is shared via the private `BuildResultFromCsprojDirectory` helper. `DiffStandardsService` compares the loaded project against a fresh reference built by `StandardElementsManager.Self.PopulateProjectWithDefaultStandards(...)` — the same path the tool's File → New uses. The CLI matches the tool's import-dialog drift detection by construction. `gumcli new --template empty`'s `Standards/*.gutx` files are generated from that same call at creation time (#4676) rather than extracted from a baked resource, so a fresh empty project is drift-free by construction, not by convention. Font files are named like `Font18Arial.fnt` and `Font18Arial_0.png` (size+name convention, zero-indexed). Always use `gumcli fonts ` to generate missing bitmap fonts — never create `.fnt` files manually. **Every template ships the fonts its own content uses, baked, in its `FontCache`** (Standard Forms and the empty template are extracted by `EmbeddedFontCache`, themes are copied whole), because a new project has no runtime font creator unless KernSmith is added. A template edit that adds a font, size or style must rebake it with `gumcli fonts` on a copy using KernSmith and copy the files in; `NewProjectThemeTests` and `FormsThemesTemplateTests.FontCache_ShouldContainEveryFontTheTemplateUses` fail otherwise. The checked-in `Templates/FormsTemplate/GumProject.gumx` carries `BehaviorReference.SourcePath` on most shared behaviors (e.g. `"../FormsBehaviors/ButtonBehavior.behx"`), meant only for `Gum.FormsStaging`'s build-time flattening into the shipped tool's `Content/FormsThemes` folder. `FormsTemplateCreator.Create` always extracts every manifest-listed `.behx` locally into the new project's own `Behaviors/` folder, so a `SourcePath` surviving into the extracted `.gumx` is stale the moment a real project exists (`BehaviorReference.GetRelativeFilePath` prefers `SourcePath` when set, and it never resolves relative to a real project — `ToBehaviorSave` then silently returns an empty `IsSourceFileMissing` stub with no error). `FormsTemplateCreator.StripStaleBehaviorSourcePaths` clears `SourcePath` on every extracted `BehaviorReference` right after extraction to prevent this. **A shaken bundle's project file is rewritten.** `GumProjectSave.Load` fails on a reference whose file is missing, so `pack --shake` saves the project without the trimmed references and lists them in `GumProjectSave.TrimmedElements`. The runtime reads that list to tell a trimmed element from a misspelled one: `ObjectFinder.GetRequiredElementSave` (used by generated code from syntax version 7) and the variable-reference error both name `--keep`. `ObjectFinder.GetElementSave` still returns null, because Gum probes it internally. ## Codegen Flow (non-obvious details) - `codegen` and the tool's Generate All both go through `HeadlessCodeGenerationService.GenerateCodeForElements`, the one batch orchestrator: it skips `NeverGenerate` elements, runs an optional gate (the CLI's per-element error check), generates the rest, and writes the fallback file only when `Elements` is null (whole project). New batch-level steps belong there, not in `CodegenCommand` or the tool handler. The tool passes its own `ElementGenerator` (popups, missing-file prompt) and an `ICodeFileWriter` that retries. - Only Screens and Components are generated; StandardElements are intentionally excluded (the per-project `StandardElements.Generated.cs` fallback registration is the exception: written on a full run, skipped when `--element` is given) - Errors (`ErrorSeverity.Error`) block generation for that element; warnings print to stderr but do not block - A file `HeadlessCodeGenerationService` can't write (unreachable `CodeProjectRoot`) is logged, not thrown; `codegen` gives the service its own `ConsoleCodeGenLogger` and exits 1 when that logger's `ErrorCount` is non-zero - `codegen` warns on stderr (never blocks) when the csproj's `PackageReference` runtime version is newer than the CLI's own version: `StaleCliWarning.GetMessage` compares them, `SyntaxVersionDetectionService.FindRuntimePackageVersion` reads the package version. ProjectReference, HintPath, and unresolvable floating or range versions stay silent. - `ObjectFinder.Self` cache is managed at the CLI level (enabled before the loop, disabled in `finally`) - If `ProjectCodeSettings.codsj` is missing, `codegen` attempts `CodeGenerationAutoSetupService` auto-detection first and writes the settings file before continuing; exit code 2 only if auto-detection also fails. A `.codsj` that exists but cannot be parsed (including an empty file) is reported with the parser message, left untouched, and exits 2; it is never replaced by auto-detected defaults. A readable `.codsj` with a blank `CodeProjectRoot` gets only that key filled in and written back (other keys, unknown ones included, are kept) - When `--element` is specified, `checkForMissing: true` is passed so `GenerateCodeForElement` auto-generates any referenced elements whose code files do not yet exist; full-run mode skips that check - `codegen-init` exits with code 2 (not 1) if settings already exist and `--force` is absent ## Key Files | File | Purpose | |------|---------| | `Tools/Gum.Cli/Program.cs` | Entry point, assembles RootCommand | | `Tools/Gum.Cli/Commands/` | One file per command | | `Gum.ProjectServices/ProjectLoader.cs` | Headless project loading | | `Gum.ProjectServices/HeadlessErrorChecker.cs` | All headless error checks | | `Gum.ProjectServices/CodeGeneration/HeadlessCodeGenerationService.cs` | Headless codegen orchestration | | `Gum.ProjectServices/CodeGeneration/CodeGenerator.cs` | Main codegen engine (~5400 lines) | | `Tests/Gum.Cli.Tests/` | CLI command tests | | `Tests/Gum.ProjectServices.Tests/` | Service layer tests (36 tests) | ## Testing Notes - `ObjectFinder` is a singleton — tests disable parallel execution (`TestAssemblyInitialize`) - `BaseTestClass` pre-populates `GumProjectSave` with standard elements and handles `ObjectFinder.Self` cleanup