diff --git a/.agents/skills/unity-visual-scripting/SKILL.md b/.agents/skills/unity-visual-scripting/SKILL.md new file mode 100644 index 0000000..db131a5 --- /dev/null +++ b/.agents/skills/unity-visual-scripting/SKILL.md @@ -0,0 +1,78 @@ +--- +name: unity-visual-scripting +description: Create, edit, and diagnose Unity Visual Scripting Script Graphs and State Graphs, including ScriptMachine and StateMachine assignments. Use for Unity.VisualScripting assets and ports, not Shader Graph, VFX Graph, or general node editors. +--- + +# Unity Visual Scripting + +Deliver the requested graph behavior while preserving asset identity, object references, +and unaffected logic. Use the target project's installed Visual Scripting package. + +## Establish context + +Inspect the Unity version, resolved `com.unity.visualscripting` version, target asset, +and relevant machine or scene. Package sources may be embedded/local under `Packages/` +or resolved under `Library/PackageCache/com.unity.visualscripting@*`. +The references target 1.9.x; verify unfamiliar or changed units in their `Definition()` +and base classes. UI labels, serialized port keys, and C# accessors are not equivalent. +Use the project's configured input system and target platform instead of copying legacy +input patterns into a project that cannot run them. + +Use the Unity tools actually available, or generate an editor entry point. Tool paths +below are relative to this `SKILL.md`, not to a fixed `.claude` or working directory. + +## Select an editing path + +- **Create a graph or change topology:** prefer a C# editor script using + `Unity.VisualScripting`. Read the relevant portions of + [API reference](references/api_reference.md) and + [code patterns](references/code_patterns.md). Script and State Graphs have different + asset/graph types; preserve the requested type. +- **Assign a graph:** load the existing `ScriptGraphAsset`/`StateGraphAsset`, reuse or + add the matching machine, and set its nest source and macro. Record Undo and scene + or prefab changes as appropriate. Saving an asset does not save a scene assignment. +- **Small serialized edit:** direct YAML/JSON patching can be appropriate when the + existing format and references are understood. Read + [serialized edits](references/serialized_edits.md). Prefer Unity APIs for nested + states, shared objects, object-reference changes, or uncertain serialization. + +## Graph constraints + +- Configure units before adding them, then wire ports after their definitions exist. + Preserve existing unit GUIDs, serialized IDs, graph variables, and machine bindings. +- ControlOutput allows one outgoing connection; ValueInput allows one incoming + connection. Use `Sequence` when execution must fan out. +- `ScalarSum`/`GenericSum` use `multiInputs[n]` (serialized keys `"0"`, `"1"`, ...), + while binary arithmetic units commonly use `a`/`b`. +- Comparison accessors use `comparison`; `Equal`/`NotEqual` serialize the keys `equal` + and `notEqual`. Do not turn those keys into nonexistent C# properties. +- `InvokeMember` parameters use `%parameterName` keys and `inputParameters[n]` in C#. + Specify exact parameter types for overloads. Void methods have no result port. + Only instance members have a target; verify implicit targets on the intended machine. +- Set variable `kind` before adding the unit and `defaultValues["name"]` afterwards. + Check coroutine support for waits, transition triggers for state graphs, and the + configured input/event source for runtime interactions. +- Keep editor code in an editor-only scope. All Unity object access runs on the main + thread, with explicit Unity-object null checks instead of `?.`/`??`. Let Unity + generate new C# `.meta` files and retain existing tracked `.meta` files. + +## Verify and report + +For generated C#, run the optional preflight compiler and port heuristics: + +```sh +python3 /tools/validate.py --unity-project +``` + +Python 3.9+ is needed. Compilation also needs .NET SDK 8+ and the matching Unity editor; +`--unity-managed-dir ` supports custom installations. Exit `0` means the +requested preflight checks passed, `1` means detected errors, and `2` means incomplete +validation. `--static-only` deliberately checks only port heuristics. See +[validation](references/validation.md) for limits and setup. + +Neither regex checks nor C# compilation verifies reflected member names, port existence +at runtime, serialization round trips, or execution. When Unity is available, execute +the generator, reopen the graph, inspect missing units/connections, and exercise the +requested behavior in Play Mode or a focused test. Verify state transitions and scene +persistence when those changed. Deliver prepared artifacts even without an editor, +clearly identifying the checks still pending. Report paths, versions, and evidence. diff --git a/.agents/skills/unity-visual-scripting/agents/openai.yaml b/.agents/skills/unity-visual-scripting/agents/openai.yaml new file mode 100644 index 0000000..be46d80 --- /dev/null +++ b/.agents/skills/unity-visual-scripting/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Unity Visual Scripting" + short_description: "Create and edit Unity visual scripting graphs" diff --git a/.agents/skills/unity-visual-scripting/evals/evals.json b/.agents/skills/unity-visual-scripting/evals/evals.json new file mode 100644 index 0000000..4386e3a --- /dev/null +++ b/.agents/skills/unity-visual-scripting/evals/evals.json @@ -0,0 +1,75 @@ +{ + "skill_name": "unity-visual-scripting", + "kind": "behavioral scenarios; not executed model results", + "evals": [ + { + "id": 1, + "prompt": "Create a Script Graph that rotates the selected object each frame and assign it.", + "environment": "Visual Scripting 1.9.7 with a connected editor and a selected GameObject.", + "should_trigger": true, + "expectations": [ + "Builds frame-rate-independent behavior with valid control/value ports.", + "Reuses the correct machine and persists the scene assignment.", + "Runs relevant checks and exercises rotation in Unity." + ], + "files": [] + }, + { + "id": 2, + "prompt": "Change the text logged by this existing Script Graph to Player's turn.", + "environment": "The asset has nonempty _objectReferences, shared IDs, unknown fields and a tracked meta file.", + "should_trigger": true, + "expectations": [ + "Preserves object references, IDs, GUIDs, metadata and unrelated fields.", + "Correctly escapes the apostrophe if editing serialized YAML.", + "Does not replace the entire YAML container with the empty-reference example." + ], + "files": [] + }, + { + "id": 3, + "prompt": "Create Idle and Walking states controlled by this project's input actions.", + "environment": "An Input System-only project with a StateMachine.", + "should_trigger": true, + "expectations": [ + "Creates a StateGraphAsset and appropriate transitions.", + "Uses the configured input actions without enabling legacy Input Manager.", + "Tests both transition directions and machine persistence." + ], + "files": [] + }, + { + "id": 4, + "prompt": "Prepare an editor generator but this machine has no Unity or .NET.", + "environment": "Python only.", + "should_trigger": true, + "expectations": [ + "Delivers useful code and runs only available checks.", + "Labels missing compilation/runtime checks; unavailable checks do not pass." + ], + "files": [] + }, + { + "id": 5, + "prompt": "Write a MonoBehaviour that moves a cube.", + "environment": "No Visual Scripting requested.", + "should_trigger": false, + "expectations": [ + "Uses normal C# without creating a graph or changing packages." + ], + "files": [] + }, + { + "id": 6, + "prompt": "Wire Equal, ScalarSum, and an overloaded Debug.Log into this graph.", + "environment": "Target package source and an existing graph are available.", + "should_trigger": true, + "expectations": [ + "Uses comparison, multiInputs and exact overload parameter types.", + "Does not wire a result from a void member.", + "Verifies actual port definitions when uncertain." + ], + "files": [] + } + ] +} diff --git a/.claude/skills/unity-visual-scripting/references/api_reference.md b/.agents/skills/unity-visual-scripting/references/api_reference.md similarity index 97% rename from .claude/skills/unity-visual-scripting/references/api_reference.md rename to .agents/skills/unity-visual-scripting/references/api_reference.md index d58dc25..8591c39 100644 --- a/.claude/skills/unity-visual-scripting/references/api_reference.md +++ b/.agents/skills/unity-visual-scripting/references/api_reference.md @@ -1,5 +1,7 @@ # Unity Visual Scripting - API Reference +Version scope: these patterns target Visual Scripting 1.9.x. Match the installed package, preserve existing serialized references, and test behavior in the target Unity project. + ## Table of Contents 1. [Graph Asset Types](#1-graph-asset-types) @@ -504,11 +506,11 @@ MonoBehaviour: _objectReferences: [] ``` -- `m_Script` guid `95e66c6366d904e98bc83428217d4fd7` is constant for all ScriptGraphAssets +- Preserve the existing `m_Script` reference. The GUID above is from the observed ScriptGraphAsset package; verify it against the installed package, and do not use it for StateGraphAsset. - `m_Name` must match the filename without `.asset` - `_json` value is the entire graph JSON on a **single line** inside YAML single quotes - Single quotes inside JSON string values must be escaped as `''` (YAML 1.1 rule) -- `_objectReferences` is always `[]` +- Preserve `_objectReferences` and its ordering. It is empty only for graphs without serialized Unity object references; clearing it breaks referenced objects. ### JSON Root Structure @@ -538,11 +540,11 @@ The `elements` array is a flat list: all **units** first (with `$id`), then all ### `$id` / `$ref` System -- Every **unit** gets a sequential `$id` as a string: `"1"`, `"2"`, `"3"`, ... +- The examples assign sequential `$id` strings to units. Preserve existing IDs and allocate unused IDs for additions; do not renumber a serialized object graph. - **Connections** reference units via `{"$ref": "N"}` where N is the unit's `$id` -- **Connections do NOT have `$id`** — only units get `$id` +- Connections in these examples do not declare `$id`. Preserve IDs on any objects in real files; serializers may also track nested/shared objects. - Every unit AND connection gets a unique `guid` (UUID v4, all lowercase) -- `$version` is always `"A"` on units, member objects, and collection objects +- `$version` is `"A"` in these examples. Preserve the target asset's serialized versions. ### Unit JSON Format diff --git a/.claude/skills/unity-visual-scripting/references/code_patterns.md b/.agents/skills/unity-visual-scripting/references/code_patterns.md similarity index 99% rename from .claude/skills/unity-visual-scripting/references/code_patterns.md rename to .agents/skills/unity-visual-scripting/references/code_patterns.md index 39fa30b..bb3638b 100644 --- a/.claude/skills/unity-visual-scripting/references/code_patterns.md +++ b/.agents/skills/unity-visual-scripting/references/code_patterns.md @@ -1,5 +1,7 @@ # Unity Visual Scripting - Code Pattern Templates +Version scope: these patterns target Visual Scripting 1.9.x. Match the installed package, preserve existing serialized references, and test behavior in the target Unity project. + Complete working C# editor script patterns. All patterns require: ```csharp diff --git a/.agents/skills/unity-visual-scripting/references/serialized_edits.md b/.agents/skills/unity-visual-scripting/references/serialized_edits.md new file mode 100644 index 0000000..b48ac53 --- /dev/null +++ b/.agents/skills/unity-visual-scripting/references/serialized_edits.md @@ -0,0 +1,34 @@ +# Editing serialized Visual Scripting graphs + +Use direct editing for small, understood changes in an existing asset. Prefer Unity +editor APIs for new graphs, topology changes involving nested/shared objects, or object +reference changes. A template is not a substitute for the target asset's schema. + +## Preserve the container + +Keep the asset's Unity YAML header, `m_Script` GUID, `_objectReferences` list and order, +unknown fields, file IDs, and `.meta` file. `_objectReferences` can hold live asset or +scene references; it is not generally empty. Do not replace the asset with a template +that hard-codes a ScriptGraphAsset GUID, particularly for a StateGraphAsset. + +For the observed single-quoted `_data._json` format, decode doubled YAML single quotes +(`''` becomes `'`), then parse the JSON. Change only the requested values. Serialize the +JSON on one line and double its single quotes when putting it back. Detect the actual +YAML scalar style; do not apply a single-line regex to folded, wrapped, or differently +quoted data. Use Unity serialization when the format cannot be safely round-tripped. + +## Preserve the object graph + +- Keep existing `$id`, `$ref`, element `guid`, `$version`, and nested objects intact. + New IDs must be unused throughout the serialized graph, not just in the top array. +- Preserve reference indexes into `_objectReferences` and all unaffected bindings. +- Check connection endpoint IDs and actual port keys; `%parameterName` is distinct + from a C# accessor. Changing a member's overload may change its ports. +- Do not impose the example's element ordering or renumber existing IDs. Review the + diff to ensure unrelated nodes, variables, states, and transitions stayed intact. + +The [API reference](api_reference.md#9-yamljson-format-reference-for-modification) +contains sample field shapes, not universal serialization rules. Reimport and reopen +the edited asset in Unity; exercise the affected behavior and inspect missing units, +connections, and object references. Without an editor, report serialization/runtime +validation as pending even when JSON parses correctly. diff --git a/.agents/skills/unity-visual-scripting/references/validation.md b/.agents/skills/unity-visual-scripting/references/validation.md new file mode 100644 index 0000000..8199e4e --- /dev/null +++ b/.agents/skills/unity-visual-scripting/references/validation.md @@ -0,0 +1,40 @@ +# Validation scope + +Run tools using the absolute skill directory when it is installed outside the project. + +```sh +python3 /tools/validate.py --unity-project +python3 /tools/validate.py --static-only +``` + +The first command compiles a temporary copy of the source using .NET SDK 8+, the exact +Unity version in `ProjectSettings/ProjectVersion.txt`, and the project's existing +`Library/ScriptAssemblies`. Missing imports/assemblies are setup failures; open the +project in Unity to produce them. No project or installed skill files are modified. +The compiler template is shipped with the skill, including on a fresh checkout. + +Common Unity Hub installations on macOS, Windows, and Linux are searched for that exact +version. For custom locations, use `--unity-managed-dir` pointing to +`Unity.app/Contents/Managed` (macOS) or `Editor/Data/Managed` (Windows/Linux). +`--unity-version` is useful without a project; if supplied with a project it must match. +The explicit Managed path is an override: the caller must ensure it belongs to the +reported editor. The tool does not silently choose another installed Unity version. + +| Exit | Meaning | +| --- | --- | +| 0 | Requested checks completed without detected errors. | +| 1 | A compiler/build or static-check error was detected. | +| 2 | Missing setup, timeout, or an incomplete/crashed check. | + +`--static-only` can return 0 for clean heuristic checks while compilation remains +unperformed. Its output states that scope. Regex checks can miss errors or flag valid +custom helpers; inspect their findings rather than changing sound code to satisfy a +spelling pattern. An unexpected subprocess exit never becomes a successful result. + +The compilation template uses .NET Standard 2.1 and C# 9, matching the language baseline +of the sample Unity 6.0 projects ([Unity compiler documentation](https://docs.unity3d.com/6000.0/Documentation/Manual/csharp-compiler.html)). +It does not reproduce project asmdefs, all conditional symbols, platform dependencies, +or Unity's complete compilation pipeline. For those cases compile in the target editor. +Reflection member names, generated ports, serialized data, actual execution, and visuals +must be verified in Unity. Do not treat an unavailable check as failure of the artifact +itself or as a reason to withhold otherwise useful work; state the missing evidence. diff --git a/.claude/skills/unity-visual-scripting/tools/check_port_keys.py b/.agents/skills/unity-visual-scripting/tools/check_port_keys.py similarity index 100% rename from .claude/skills/unity-visual-scripting/tools/check_port_keys.py rename to .agents/skills/unity-visual-scripting/tools/check_port_keys.py diff --git a/.agents/skills/unity-visual-scripting/tools/validate.py b/.agents/skills/unity-visual-scripting/tools/validate.py new file mode 100644 index 0000000..d5fafaa --- /dev/null +++ b/.agents/skills/unity-visual-scripting/tools/validate.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Run C# compilation and domain heuristics. Exit 0=pass, 1=errors, 2=incomplete.""" + +import argparse +from pathlib import Path +import subprocess +import sys + +TOOLS_DIR = Path(__file__).resolve().parent +STATIC_CHECKER = "check_port_keys.py" + + +def run_check(script, cs_file, extra_args=None): + """Return the actual subprocess status and both output streams.""" + try: + result = subprocess.run( + [sys.executable, str(TOOLS_DIR / script), cs_file] + (extra_args or []), + capture_output=True, text=True, timeout=60, + ) + return result.returncode, result.stdout.strip(), result.stderr.strip() + except (OSError, subprocess.TimeoutExpired) as exc: + return 2, "", str(exc) + + +def combine_status(codes): + """Known errors fail; skipped, crashed, or timed-out layers remain incomplete.""" + if 1 in codes: + return 1 + return 2 if any(code != 0 for code in codes) else 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("cs_file") + parser.add_argument("--static-only", action="store_true", help="Run heuristics only; do not claim compilation") + parser.add_argument("--unity-project") + parser.add_argument("--unity-version") + parser.add_argument("--unity-managed-dir") + args = parser.parse_args() + if not Path(args.cs_file).is_file(): + parser.error(f"File not found: {args.cs_file}") + extra = [] + for name in ("unity_project", "unity_version", "unity_managed_dir"): + value = getattr(args, name) + if value: + extra.extend(["--" + name.replace("_", "-"), value]) + checks = [(STATIC_CHECKER, [])] + if not args.static_only: + checks.insert(0, ("validate_cs.py", extra)) + codes = [] + for script, options in checks: + print(f"--- {script} ---", flush=True) + code, stdout, stderr = run_check(script, args.cs_file, options) + codes.append(code) + if stdout: + print(stdout) + if stderr: + print(stderr, file=sys.stderr) + code = combine_status(codes) + scope = "STATIC CHECKS ONLY (compilation not run)" if args.static_only else "PREFLIGHT (Unity execution not checked)" + status = {0: "PASSED", 1: "FAILED", 2: "INCOMPLETE"}[code] + print(f"{scope}: {status}") + sys.exit(code) + + +if __name__ == "__main__": + main() diff --git a/.agents/skills/unity-visual-scripting/tools/validate_cs.py b/.agents/skills/unity-visual-scripting/tools/validate_cs.py new file mode 100644 index 0000000..35cfb6d --- /dev/null +++ b/.agents/skills/unity-visual-scripting/tools/validate_cs.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Compile one editor script against a selected Unity installation. + +Exit 0: compilation passed; 1: build failed; 2: setup/execution incomplete. +This preflight does not execute the script or reproduce Unity's assembly definitions. +""" + +import argparse +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import xml.etree.ElementTree as ET + +PROJECT_FILE = Path(__file__).resolve().parent / "validation_project/ValidationProject.csproj" +PACKAGE_PATTERN = "Unity.VisualScripting*.dll" +ASSEMBLY_PROPERTY = "VSAssembliesDir" + + +def project_version(project): + """Read the editor version pinned by the target project.""" + path = Path(project) / "ProjectSettings/ProjectVersion.txt" + try: + text = path.read_text(encoding="utf-8") + except OSError as exc: + raise ValueError(f"Cannot read {path}: {exc}") from exc + match = re.search(r"^m_EditorVersion:\s*(\S+)", text, re.MULTILINE) + if not match: + raise ValueError(f"No m_EditorVersion in {path}") + return match.group(1) + + +def find_unity_managed_dir(version): + """Try common Hub locations for this exact version, never another version.""" + roots = [ + Path("/Applications/Unity/Hub/Editor"), + Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "Unity/Hub/Editor", + Path.home() / "Unity/Hub/Editor", + Path.home() / ".local/share/Unity/Hub/Editor", + ] + for root in roots: + for suffix in ("Unity.app/Contents/Managed", "Editor/Data/Managed"): + candidate = root / version / suffix + if candidate.is_dir(): + return candidate + return None + + +def validate(cs_path, unity_version=None, unity_project=None, managed_dir=None): + """Return (exit code, evidence) without mutating the Unity project or skill.""" + source = Path(cs_path).resolve() + if not source.is_file() or source.suffix.lower() != ".cs": + return 2, f"C# source file not found or not a .cs file: {source}" + if not PROJECT_FILE.is_file(): + return 2, f"Validation template missing: {PROJECT_FILE}" + + try: + project = Path(unity_project).resolve() if unity_project else None + pinned = project_version(project) if project else None + if pinned and unity_version and pinned != unity_version: + return 2, f"Requested editor {unity_version} differs from project version {pinned}." + version = unity_version or pinned + if managed_dir: + managed = Path(managed_dir).expanduser().resolve() + elif version: + managed = find_unity_managed_dir(version) + else: + return 2, "Specify --unity-project, --unity-version, or --unity-managed-dir." + if managed is None or not managed.is_dir(): + return 2, f"Unity {version or ''} Managed directory not found. Use --unity-managed-dir." + if not (managed / "UnityEngine/UnityEngine.CoreModule.dll").is_file() and not (managed / "UnityEngine.dll").is_file(): + return 2, f"Unity engine assemblies not found in {managed}" + + assemblies = project / "Library/ScriptAssemblies" if project else None + if assemblies is not None and not list(assemblies.glob(PACKAGE_PATTERN)): + return 2, f"Package assemblies missing in {assemblies}; import/compile the target project in Unity." + if shutil.which("dotnet") is None: + return 2, ".NET SDK not found on PATH. Use Unity compilation or install an SDK separately." + + # Separate builds prevent cross-run cache races and allow read-only installs. + with tempfile.TemporaryDirectory(prefix="unity-skill-csharp-") as tmp: + work = Path(tmp) + shutil.copyfile(source, work / "Input.cs") + tree = ET.parse(PROJECT_FILE) + props = ET.SubElement(tree.getroot(), "PropertyGroup") + ET.SubElement(props, "ValidationSource").text = "Input.cs" + ET.SubElement(props, "UnityManagedDir").text = str(managed) + if assemblies is not None: + ET.SubElement(props, ASSEMBLY_PROPERTY).text = str(assemblies) + tree.write(work / "ValidationProject.csproj", encoding="utf-8", xml_declaration=True) + result = subprocess.run( + ["dotnet", "build", "ValidationProject.csproj", "--nologo", "-v", "quiet", + "-p:NuGetAudit=false"], + cwd=work, capture_output=True, text=True, timeout=45, + ) + output = "\n".join(part.strip() for part in (result.stdout, result.stderr) if part.strip()) + # MSBuild/NuGet/SDK errors do not necessarily match a C# diagnostic regex. + if result.returncode != 0: + return 1, output or f"dotnet build failed with exit code {result.returncode}." + scope = f"Unity {version or 'custom installation'}; Managed={managed}" + if assemblies is not None: + scope += f"; package assemblies={assemblies}" + return 0, f"{scope}\n{output}\nC# compilation PASSED (preflight only; Unity execution not checked)." + except (OSError, ValueError, ET.ParseError, subprocess.TimeoutExpired) as exc: + return 2, str(exc) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("cs_file", help="Editor C# source file") + parser.add_argument("--unity-version", help="Exact editor version; otherwise read the project") + parser.add_argument("--unity-project", help="Target Unity project with compiled package assemblies") + parser.add_argument("--unity-managed-dir", help="Explicit Managed directory for custom editor installs") + args = parser.parse_args() + code, evidence = validate(args.cs_file, args.unity_version, args.unity_project, args.unity_managed_dir) + print(evidence) + if code == 2: + print("C# validation INCOMPLETE: compilation was not established.", file=sys.stderr) + sys.exit(code) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/unity-visual-scripting/tools/validation_project/ValidationProject.csproj b/.agents/skills/unity-visual-scripting/tools/validation_project/ValidationProject.csproj similarity index 97% rename from .claude/skills/unity-visual-scripting/tools/validation_project/ValidationProject.csproj rename to .agents/skills/unity-visual-scripting/tools/validation_project/ValidationProject.csproj index 83d4ad3..d3cf112 100644 --- a/.claude/skills/unity-visual-scripting/tools/validation_project/ValidationProject.csproj +++ b/.agents/skills/unity-visual-scripting/tools/validation_project/ValidationProject.csproj @@ -1,7 +1,7 @@ netstandard2.1 - 12 + 9 UNITY_EDITOR disable CS1701;CS1702;CS1591;CS0430 diff --git a/.claude/skills/unity-visual-scripting b/.claude/skills/unity-visual-scripting new file mode 120000 index 0000000..5f332d2 --- /dev/null +++ b/.claude/skills/unity-visual-scripting @@ -0,0 +1 @@ +../../.agents/skills/unity-visual-scripting \ No newline at end of file diff --git a/.claude/skills/unity-visual-scripting/SKILL.md b/.claude/skills/unity-visual-scripting/SKILL.md deleted file mode 100644 index 725483e..0000000 --- a/.claude/skills/unity-visual-scripting/SKILL.md +++ /dev/null @@ -1,412 +0,0 @@ ---- -name: unity-visual-scripting -description: Generate Unity Visual Scripting graphs programmatically via C# editor scripts (creation) or by directly editing .asset YAML files (modification). Use when the user asks to create, modify, or edit a Visual Scripting graph, Script Graph, State Graph, flow graph, node graph, or any visual scripting asset in Unity. Also use when assigning a ScriptGraphAsset or StateGraphAsset to a GameObject via ScriptMachine or StateMachine components. Triggers on keywords like "visual scripting", "script graph", "state graph", "flow graph", "ScriptMachine", "ScriptGraphAsset", "node-based", "bolt graph", or "modify graph". ---- - -# Unity Visual Scripting - Graph Creation & Modification - -Generate Unity Visual Scripting graphs via **C# editor scripts** (creation) or **direct YAML/JSON editing** (modification of existing graphs). - -**Namespace**: `Unity.VisualScripting` | **Required assemblies**: `Unity.VisualScripting.Core`, `Unity.VisualScripting.Flow` - -## Workflow - -### Task 1: Create a Script Graph - -1. Create `ScriptGraphAsset` and access its `FlowGraph` -2. Create units (nodes), add to graph, set positions -3. Wire control connections (execution flow) and value connections (data flow) -4. Save to AssetDatabase - -```csharp -#if UNITY_EDITOR -using System; -using UnityEditor; -using UnityEngine; -using Unity.VisualScripting; - -public static class MyGraphCreator -{ - [MenuItem("Tools/VS/Create My Graph")] - public static void Create() - { - // 1. Create asset (graph is auto-initialized) - var graphAsset = ScriptableObject.CreateInstance(); - var graph = graphAsset.graph; - - // 2. Create and add units - var onUpdate = new Update(); - graph.units.Add(onUpdate); - onUpdate.position = new Vector2(-300, 0); - - // 3. Wire connections - // graph.controlConnections.Add(new ControlConnection(src.trigger, dst.enter)); - // graph.valueConnections.Add(new ValueConnection(src.output, dst.input)); - - // 4. Save - if (!AssetDatabase.IsValidFolder("Assets/VisualScripting")) - AssetDatabase.CreateFolder("Assets", "VisualScripting"); - AssetDatabase.CreateAsset(graphAsset, "Assets/VisualScripting/MyGraph.asset"); - AssetDatabase.SaveAssets(); - AssetDatabase.Refresh(); - } -} -#endif -``` - -### Task 2: Assign a Graph to a GameObject - -Add a `ScriptMachine` component and set its `nest.macro` to a `ScriptGraphAsset`. - -```csharp -#if UNITY_EDITOR -using UnityEditor; -using UnityEngine; -using Unity.VisualScripting; - -public static class MyGraphAssigner -{ - [MenuItem("Tools/VS/Assign My Graph")] - public static void Assign() - { - var go = GameObject.Find("TargetObject"); - if (go == null) { Debug.LogError("TargetObject not found."); return; } - - var graphAsset = AssetDatabase.LoadAssetAtPath( - "Assets/VisualScripting/MyGraph.asset"); - if (graphAsset == null) { Debug.LogError("Graph asset not found."); return; } - - var machine = go.GetComponent(); - if (machine == null) - machine = go.AddComponent(); - - machine.nest.source = GraphSource.Macro; - machine.nest.macro = graphAsset; - EditorUtility.SetDirty(go); - } -} -#endif -``` - -For `StateMachine`, use `StateGraphAsset` and `StateMachine` instead. - -### Task 3: Modify an Existing Graph via YAML - -ScriptGraphAsset `.asset` files are YAML-wrapped JSON. For **modifying** existing graphs, directly edit the `.asset` file instead of writing a C# editor script. This is faster (no compilation wait) and avoids boilerplate. - -**How it works**: The `.asset` file has a YAML header and a `_data._json` field containing the entire graph as a single-line JSON string. The JSON contains a `graph.elements` array with all units and connections. - -#### YAML Structure Template - -```yaml -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!114 &11400000 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 0} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 95e66c6366d904e98bc83428217d4fd7, type: 3} - m_Name: GRAPH_NAME - m_EditorClassIdentifier: - _data: - _json: 'JSON_CONTENT_HERE' - _objectReferences: [] -``` - -- `m_Script` guid `95e66c6366d904e98bc83428217d4fd7` is constant for all ScriptGraphAssets -- `m_Name` must match the filename without `.asset` -- `_json` is the entire graph JSON on a **single line** inside YAML single quotes - -#### JSON Root Structure - -```json -{ - "graph": { - "variables": {"Kind":"Flow","collection":{"$content":[],"$version":"A"},"$version":"A"}, - "controlInputDefinitions": [], - "controlOutputDefinitions": [], - "valueInputDefinitions": [], - "valueOutputDefinitions": [], - "title": null, - "summary": null, - "pan": {"x":0.0,"y":0.0}, - "zoom": 1.0, - "elements": [ ...UNITS_THEN_CONNECTIONS... ], - "$version": "A" - } -} -``` - -The `elements` array lists all **units first** (with sequential `$id`), then all **connections** (no `$id`). - -#### Modification Workflow - -1. **Read** the `.asset` file -2. **Extract** the `_json` value (everything between the YAML single quotes) -3. **Unescape** YAML single quotes (`''` → `'`) -4. **Parse** as JSON, modify the `graph.elements` array -5. **Re-escape** single quotes (`'` → `''`) -6. **Write** the JSON back as a single line in the YAML template -7. Unity Editor auto-reloads on file change - -## Essential API Quick Reference - -### Choosing Workflow: C# vs YAML - -| Scenario | Use | -|----------|-----| -| **Create** a new graph from scratch | C# editor script (Task 1) | -| **Assign** a graph to a GameObject | C# editor script (Task 2) | -| **Modify** an existing `.asset` graph | YAML/JSON editing (Task 3) | -| **Create** a new graph without C# compilation | YAML/JSON writing (Task 3) | - -### Creating Units - -| Unit | Constructor | Key Ports | -|------|------------|-----------| -| Event | `new Start()`, `new Update()` | `trigger` (ControlOutput) | -| GetMember | `new GetMember(new Member(type, name))` | `value` (out), `target` (in, instance only) | -| SetMember | `new SetMember(new Member(type, name))` | `assign`/`assigned` (control), `input`/`output` (value) | -| InvokeMember | `new InvokeMember(new Member(type, name, paramTypes[]))` | `enter`/`exit` (control), `%paramName` (value in), `result` (non-void only) | -| Literal | `new Literal(typeof(T), value)` | `output` (ValueOutput) | -| ScalarSum | `new ScalarSum()` | `0`, `1` (value in, port keys), `sum` (out) — C# accessor: `multiInputs[0]`. Set `inputCount` for more inputs | -| ScalarMultiply | `new ScalarMultiply()` | `a`, `b` (in), `product` (out) | -| Sequence | `new Sequence()` | `enter` (ctrl in), `0`/`1`/... (ctrl out) — C# accessor: `multiOutputs[n]`. Set `outputCount` | -| If | `new If()` | `enter` (control in), `condition` (value in), `ifTrue`/`ifFalse` (control out) | -| GetVariable | `new GetVariable() { kind }` (set `defaultValues["name"]` after Add) | `value` (out) | -| SetVariable | `new SetVariable() { kind }` (set `defaultValues["name"]` after Add) | `assign`/`assigned` (control), `input`/`output` (value) | - -### Member Constructor Patterns - -```csharp -// Static property -new Member(typeof(Time), nameof(Time.deltaTime)) - -// Instance property -new Member(typeof(Transform), "position") - -// Method with overload disambiguation -new Member(typeof(Transform), "Rotate", new[] { typeof(float), typeof(float), typeof(float) }) -new Member(typeof(Debug), "Log", new[] { typeof(object) }) -``` - -### Connections - -```csharp -// Control flow (ControlOutput -> ControlInput) -graph.controlConnections.Add(new ControlConnection(start.trigger, action.enter)); - -// Data flow (ValueOutput -> ValueInput) -graph.valueConnections.Add(new ValueConnection(literal.output, invoke.inputParameters[0])); -``` - -**Rules**: ControlOutput allows only 1 outgoing connection. ValueInput allows only 1 incoming connection. Use `Sequence` unit to fan out control flow. - -### Unit JSON Format (for YAML modification) - -```json -{ - "position": {"x": 0.0, "y": 0.0}, - "guid": "uuid-v4-lowercase", - "$version": "A", - "$type": "Unity.VisualScripting.ClassName", - "$id": "N" -} -``` - -Plus type-specific fields: `coroutine`, `defaultValues`, `member`, `parameterNames`, `kind`, `type`, `value`, `inputCount`, `outputCount`, etc. - -### Connection JSON Format (for YAML modification) - -```json -{"sourceUnit":{"$ref":"1"},"sourceKey":"trigger","destinationUnit":{"$ref":"2"},"destinationKey":"enter","guid":"uuid-v4","$type":"Unity.VisualScripting.ControlConnection"} -``` - -```json -{"sourceUnit":{"$ref":"3"},"sourceKey":"output","destinationUnit":{"$ref":"2"},"destinationKey":"%message","guid":"uuid-v4","$type":"Unity.VisualScripting.ValueConnection"} -``` - -### Member Object JSON Format (for YAML modification) - -```json -{"name":"Log","parameterTypes":["System.Object"],"targetType":"UnityEngine.Debug","targetTypeName":"UnityEngine.Debug","$version":"A"} -``` - -- `parameterTypes`: array of fully-qualified type strings for methods, `null` for properties -- `targetType` and `targetTypeName` are always identical - -### Typed Values (JSON) - -| Type | JSON Format | -|------|-------------| -| `string` | `{"$content":"text","$type":"System.String"}` | -| `int` | `{"$content":42,"$type":"System.Int32"}` | -| `float` | `{"$content":3.14,"$type":"System.Single"}` | -| `bool` | `{"$content":true,"$type":"System.Boolean"}` | -| `Enum` | `{"$content":32,"$type":"UnityEngine.KeyCode"}` (integer value) | -| `Vector3` | `{"x":1.0,"y":2.0,"z":3.0,"$type":"UnityEngine.Vector3"}` (no `$content`) | -| `Color` | `{"r":1.0,"g":0.0,"b":0.0,"a":1.0,"$type":"UnityEngine.Color"}` (no `$content`) | -| `null` | `null` | - -### Position Layout - -Set `unit.position` AFTER `graph.units.Add(unit)`. Recommended spacing: ~250px horizontal, ~150px vertical. - -## Critical Rules - -### C# Creation Rules - -- Always wrap editor scripts in `#if UNITY_EDITOR` / `#endif` -- Never use `?.` or `??` with `UnityEngine.Object` types -- Always call `EditorUtility.SetDirty()` after modifying GameObjects -- Always call `AssetDatabase.SaveAssets()` after creating/modifying assets -- For instance methods (e.g., `Transform.Rotate`), the `target` port auto-resolves to the owning GameObject's component when unconnected -- Variable units (`GetVariable`/`SetVariable`/`IsVariableDefined`) have NO `defaultName` property — set `kind` before `graph.units.Add()`, then set `defaultValues["name"]` after Add -- `ScalarSum` and `GenericSum` extend `MultiInputUnit` — port keys are `"0"`, `"1"`, etc. C# accessor: `multiInputs[0]`, `multiInputs[1]` (NOT `a`, `b`). Output is `sum`. Other binary math units (`ScalarMultiply`, `ScalarSubtract`, etc.) still use `a`/`b` -- **Static vs instance members**: Static members (e.g., `Time.deltaTime`, `Debug.Log`, `Input.GetKey`) have no `target` port. Instance members (e.g., `Transform.position`, `Transform.Rotate`) have a `target` port that auto-resolves to the owning GameObject's component when unconnected -- **`%paramName` convention**: `InvokeMember` parameter port keys use `"%paramName"` format (e.g., `"%x"`, `"%y"`, `"%z"` for `Rotate`). C# accessor: `inputParameters[n]` -- **Void methods**: Void methods (e.g., `SetActive`, `Rotate`, `Play`) have no `result` port. `InvokeMember.targetOutput` is null for void instance methods — always null-check before wiring it -- **Comparison unit output — port key ≠ C# property**: ALL `BinaryComparisonUnit` subclasses (`Equal`, `NotEqual`, `Greater`, `Less`, `GreaterOrEqual`, `LessOrEqual`) expose their output via the C# property **`comparison`**. `Equal` and `NotEqual` override the port key string to `"equal"` / `"notEqual"` for backward compat, but the C# accessor is still `comparison`. Use `equal.comparison` (NOT ~~`equal.equal`~~) — the latter causes CS1061 - -### YAML Modification Rules - -- **JSON must be single-line**: The entire JSON graph goes on one line inside the `_json` YAML value — no newlines -- **YAML single-quote escaping**: Single quotes inside JSON string values must be doubled (`'` → `''`) -- **`$id` system**: Sequential integers as strings (`"1"`, `"2"`, `"3"`, ...) — **units only**, NOT connections -- **`$ref` system**: Connections reference units via `{"$ref": "N"}` where N is the unit's `$id` -- **`guid`**: Every unit AND every connection gets a unique UUID v4 (all lowercase) -- **`$version`**: Always `"A"` on units, member objects, collection objects, and the graph root -- **Parameter port keys**: Prefixed with `%` in both `defaultValues` keys and connection `sourceKey`/`destinationKey` (e.g., `%message`, `%xAngle`) -- **Connections do NOT have `$id`**: Only units get `$id` fields -- **Elements ordering**: All units first, then all connections in the `elements` array -- **Static vs instance**: Static members have `"defaultValues": {}` (no `target`); instance members have `"target": null` in `defaultValues` -- **Structs vs scalars in typed values**: Structs (Vector3, Color) use direct field names without `$content`; scalars (int, float, string, bool) use `$content` -- **ScriptGraphAsset guid is constant**: `95e66c6366d904e98bc83428217d4fd7` — never changes - -## Unit Verification Protocol (MANDATORY for undocumented units) - -For any unit type NOT listed in `api_reference.md`, verify it against the actual package source before generating code. This prevents wrong class names and port keys. - -### Source Location - -``` -Library/PackageCache/com.unity.visualscripting@*/Runtime/VisualScripting.Flow/Framework/ -``` - -Use glob `com.unity.visualscripting@*` to handle hash changes across package updates. - -### Verification Steps - -1. **Verify class exists** — Grep for `class {ClassName}` under the Framework directory. If not found, the class doesn't exist. Common trap: UI display names differ from class names (e.g., "Add" node = `ScalarSum`, not `ScalarAdd`). - -2. **Read `Definition()` method** — Port keys are the first argument to `ValueInput()` / `ValueOutput()` / `ControlInput()` / `ControlOutput()` calls. Usually `nameof(prop)` or `i.ToString()` for multi-input units. - -3. **Check base classes** — If the class inherits from another (e.g., `ScalarSum : Sum : MultiInputUnit`), ALSO read the base class `Definition()` — ports are often defined there, not in the leaf class. - -### Directory Quick-Reference - -``` -Framework/ -├── Math/ — Base: Sum.cs, Multiply.cs, Subtract.cs, Divide.cs -│ ├── Scalar/ — ScalarSum, ScalarMultiply, ScalarSubtract, ... -│ ├── Generic/ — GenericSum, GenericMultiply, ... -│ └── Vector*/ — Vector2Sum, Vector3Sum, ... -├── Control/ — If, For, ForEach, While, Sequence, Once, ... -├── Logic/ — And, Or, Negate, Equal, Greater, Less, ... -├── Events/ -│ ├── Lifecycle/ — Start, Update, FixedUpdate, OnEnable, OnDestroy -│ ├── Physics/ — OnCollisionEnter, OnTriggerEnter, ... -│ └── Input/ — OnKeyDown, OnMouseDown, ... -├── Variables/ — GetVariable, SetVariable, IsVariableDefined -├── Codebase/ — InvokeMember, GetMember, SetMember -├── Time/ — Timer, Cooldown, WaitForSecondsUnit, ... -├── Nulls/ — Null, NullCheck, NullCoalesce -├── Literal.cs -└── This.cs -``` - -### Skip-Verification List (already documented) - -These units are fully documented in `api_reference.md` and do NOT need source verification: -`Literal`, `If`, `For`, `ForEach`, `While`, `Sequence`, `Once`, `NullCheck`, `SelectUnit`, -`Start`, `Update`, `FixedUpdate`, `OnTriggerEnter`, `OnCollisionEnter`, `OnKeyboardInput`, `CustomEvent`, -`GetMember`, `SetMember`, `InvokeMember`, -`GetVariable`, `SetVariable`, `IsVariableDefined`, -`ScalarSum`, `ScalarMultiply`, `ScalarSubtract`, `ScalarDivide`, `ScalarModulo`, -`GenericSum`, `GenericSubtract`, `GenericMultiply`, `GenericDivide`, -`And`, `Or`, `Negate`, `Equal`, `NotEqual`, `Greater`, `Less`, `GreaterOrEqual`, `LessOrEqual`, -`WaitForSecondsUnit`, `WaitUntilUnit`, `Cooldown`, `This` - -## C# Code Validation (Pre-flight) - -Before returning generated C# code for Task 1 or Task 2, run the C# compilation validator to catch semantic errors. - -### When to Validate - -Validate ALL generated C# editor scripts. Do not skip even for simple scripts. - -### How to Run - -Save the generated C# to a temporary file and run: - -```bash -python3 .claude/skills/unity-visual-scripting/tools/validate.py /tmp/vs_generated.cs -``` - -With a specific Unity version: - -```bash -python3 .claude/skills/unity-visual-scripting/tools/validate.py /tmp/vs_generated.cs --unity-version 6000.0.68f1 -``` - -With a Unity project (enables VS-specific type validation): - -```bash -python3 .claude/skills/unity-visual-scripting/tools/validate.py /tmp/vs_generated.cs --unity-project /path/to/project -``` - -### What Validation Catches - -**C# Compilation Layer** (`dotnet build` against Unity DLLs): - -| Code | Catches | Example | -|------|---------|---------| -| CS0246 | Wrong type name | `typeof(Transfrm)` → should be `Transform` | -| CS1061 | Wrong member name | `transform.positon` → should be `position` | -| CS1503 | Wrong argument type | `Member(typeof(Transform), "Rotate", new[]{typeof(int)})` | -| CS7036 | Missing required argument | Missing overload parameter | -| CS0117 | Member not found on type | `Time.deltTime` → should be `deltaTime` | - -**Python Layer** (VS-specific runtime semantic checks): - -| Code | Catches | Example | -|------|---------|---------| -| VS-PORT-001 | Wrong comparison accessor | `equal.equal` → should be `equal.comparison` | -| VS-PORT-002 | `.result` on void method | `debugLog.result` — `Debug.Log` is void | -| VS-PORT-003 | `.a`/`.b` on multi-input unit | `scalarSum.a` → should be `scalarSum.multiInputs[0]` | - -### On Validation Failure - -1. Fix the specific lines indicated in the error output -2. Re-run validation -3. Only return code to the user when validation passes - -### First-Time Setup - -On first use, `dotnet restore` runs automatically (near-instant). Subsequent runs use the cached restore. - -### Requirements - -- .NET SDK 8.0+ (`dotnet` CLI available) -- Unity Editor installed at `/Applications/Unity/Hub/Editor/` -- Python 3 - -## References - -- **Detailed API Reference**: See [references/api_reference.md](references/api_reference.md) for complete port names, unit types catalog, variable system, and Member class details -- **Code Pattern Templates**: See [references/code_patterns.md](references/code_patterns.md) for complete working examples covering events, input, physics, transforms, variables, flow control, UI, animation, audio, and more diff --git a/.claude/skills/unity-visual-scripting/tools/validate.py b/.claude/skills/unity-visual-scripting/tools/validate.py deleted file mode 100644 index c05abf9..0000000 --- a/.claude/skills/unity-visual-scripting/tools/validate.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python3 -""" -validate.py - Combined C# validator for Unity Visual Scripting skill. - -Runs both Roslyn semantic validation and VS-specific port-key checks. - -Usage: - python3 validate.py [--unity-version VERSION] [--unity-project PATH] - -Exit codes: - 0 - All checks passed - 1 - Errors found - 2 - Usage or setup error -""" - -import subprocess -import sys -from pathlib import Path - -TOOLS_DIR = Path(__file__).parent - - -def run_check(script, cs_file, extra_args=None): - """Run a validation script and return (exit_code, stdout_output, stderr_output).""" - cmd = [sys.executable, str(TOOLS_DIR / script), cs_file] + (extra_args or []) - try: - result = subprocess.run(cmd, capture_output=True, text=True, timeout=60) - return result.returncode, result.stdout.strip(), result.stderr.strip() - except subprocess.TimeoutExpired: - return 2, "", f"Timeout running {script}" - except FileNotFoundError: - return 2, "", f"Script not found: {script}" - - -def main(): - if len(sys.argv) < 2: - print("Usage: validate.py [--unity-version VERSION] [--unity-project PATH]") - sys.exit(2) - - cs_file = sys.argv[1] - extra_args = sys.argv[2:] - - if not Path(cs_file).exists(): - print(f"ERROR: File not found: {cs_file}") - sys.exit(2) - - has_errors = False - - # Layer 1: C# compilation check - print("=== C# Compilation Check ===") - rc1, out1, err1 = run_check("validate_cs.py", cs_file, extra_args) - if out1: - print(out1) - if rc1 == 1: - has_errors = True - elif rc1 == 2: - print(" (C# validation skipped due to setup issue)") - if err1: - print(f" {err1}", file=sys.stderr) - - print() - - # Layer 2: VS port-key static analysis - print("=== VS Port Key Static Analysis ===") - rc2, out2, err2 = run_check("check_port_keys.py", cs_file) - if out2: - print(out2) - if rc2 == 1: - has_errors = True - - print() - - # Summary - if has_errors: - print("VALIDATION FAILED: Fix the errors above and re-validate.") - sys.exit(1) - else: - print("VALIDATION PASSED: All checks clean.") - sys.exit(0) - - -if __name__ == "__main__": - main() diff --git a/.claude/skills/unity-visual-scripting/tools/validate_cs.py b/.claude/skills/unity-visual-scripting/tools/validate_cs.py deleted file mode 100644 index 09828a7..0000000 --- a/.claude/skills/unity-visual-scripting/tools/validate_cs.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env python3 -""" -validate_cs.py - Validate generated C# editor scripts using dotnet build. - -Usage: - python3 validate_cs.py [--unity-version VERSION] [--unity-project PATH] - -Outputs human-readable error list. Exits 0 (clean) or 1 (errors found). -""" - -import subprocess -import re -import sys -from pathlib import Path - -TOOL_DIR = Path(__file__).parent -PROJECT_DIR = TOOL_DIR / "validation_project" -DEFAULT_UNITY_VERSION = "6000.0.68f1" -UNITY_EDITOR_BASE = Path("/Applications/Unity/Hub/Editor") - -# MSBuild diagnostic pattern: file(line,col): severity code: message [project] -DIAG_PATTERN = re.compile( - r"^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(CS\d+):\s+(.+?)\s+\[.+\]$" -) - - -def find_unity_managed_dir(version): - """Find Unity's Managed directory for the given editor version.""" - candidate = UNITY_EDITOR_BASE / version / "Unity.app" / "Contents" / "Managed" - if candidate.exists(): - return candidate - # Try all installed versions if specified version not found - if UNITY_EDITOR_BASE.exists(): - for entry in sorted(UNITY_EDITOR_BASE.iterdir(), reverse=True): - managed = entry / "Unity.app" / "Contents" / "Managed" - if managed.exists(): - print(f"NOTE: Unity {version} not found, using {entry.name}", file=sys.stderr) - return managed - return None - - -def parse_diagnostics(output): - """Parse MSBuild output into diagnostic dicts.""" - diagnostics = [] - for line in output.splitlines(): - m = DIAG_PATTERN.match(line.strip()) - if m: - diagnostics.append({ - "severity": "Error" if m.group(4) == "error" else "Warning", - "code": m.group(5), - "message": m.group(6), - "line": int(m.group(2)), - "column": int(m.group(3)), - }) - return diagnostics - - -def validate(cs_path, unity_version, unity_project=None): - """Run dotnet build validation on a C# file.""" - managed_dir = find_unity_managed_dir(unity_version) - if not managed_dir: - print("WARNING: Unity managed directory not found, skipping C# validation", - file=sys.stderr) - return [] - - # Build properties passed to the template .csproj - props = { - "ValidationSource": str(Path(cs_path).resolve()), - "UnityManagedDir": str(managed_dir), - } - - if unity_project: - script_assemblies = Path(unity_project) / "Library" / "ScriptAssemblies" - if script_assemblies.exists(): - props["VSAssembliesDir"] = str(script_assemblies) - - args = [ - "dotnet", "build", str(PROJECT_DIR), - "--nologo", "--no-restore", "-v", "quiet", - "-clp:NoSummary", - ] - for key, val in props.items(): - args.append(f"-p:{key}={val}") - - result = subprocess.run(args, capture_output=True, text=True, timeout=30) - - # Parse diagnostics from both stdout and stderr (MSBuild may write to either) - all_output = result.stdout + "\n" + result.stderr - return parse_diagnostics(all_output) - - -def restore_project(): - """Run dotnet restore once to ensure packages are available.""" - result = subprocess.run( - ["dotnet", "restore", str(PROJECT_DIR), "--nologo", "-v", "quiet"], - capture_output=True, text=True, timeout=30 - ) - if result.returncode != 0: - print(f"Restore failed:\n{result.stderr}", file=sys.stderr) - return False - return True - - -def main(): - import argparse - parser = argparse.ArgumentParser(description="C# validator for Unity scripts") - parser.add_argument("cs_file", help="Path to C# file to validate") - parser.add_argument("--unity-version", default=DEFAULT_UNITY_VERSION, - help=f"Unity editor version (default: {DEFAULT_UNITY_VERSION})") - parser.add_argument("--unity-project", default=None, - help="Path to Unity project (for VS DLLs)") - args = parser.parse_args() - - if not Path(args.cs_file).exists(): - print(f"ERROR: File not found: {args.cs_file}", file=sys.stderr) - sys.exit(2) - - # Ensure NuGet restore is done (first run only, near-instant after that) - if not (PROJECT_DIR / "obj" / "project.assets.json").exists(): - print("Restoring project (first run)...", file=sys.stderr) - if not restore_project(): - print("ERROR: Failed to restore project", file=sys.stderr) - sys.exit(2) - - diagnostics = validate(args.cs_file, args.unity_version, args.unity_project) - - errors = [d for d in diagnostics if d.get("severity") == "Error"] - warnings = [d for d in diagnostics if d.get("severity") == "Warning"] - - if not errors and not warnings: - print("C# validation PASSED: No errors or warnings.") - sys.exit(0) - - for d in errors: - print(f" ERROR {d['code']} (line {d['line']}): {d['message']}") - for d in warnings: - print(f" WARNING {d['code']} (line {d['line']}): {d['message']}") - - print(f"\nTotal: {len(errors)} error(s), {len(warnings)} warning(s)") - sys.exit(1 if errors else 0) - - -if __name__ == "__main__": - main() diff --git a/.gitignore b/.gitignore index aa610b5..4069811 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,9 @@ nanobanana-output/* # Validation project build artifacts -.claude/skills/unity-visual-scripting/tools/validation_project/bin/ -.claude/skills/unity-visual-scripting/tools/validation_project/obj/ +.agents/skills/unity-visual-scripting/tools/validation_project/bin/ +.agents/skills/unity-visual-scripting/tools/validation_project/obj/ + +# Python validation caches +__pycache__/ +*.pyc diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6fe11b0 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,24 @@ +# Repository guidance + +This repository maintains `unity-visual-scripting` for Codex, with GPT-6 Astra as the intended +model. The canonical package is `.agents/skills/unity-visual-scripting/`. The matching +`.claude/skills/unity-visual-scripting` symlink preserves Claude Code compatibility; edit the +canonical files only. Model selection belongs to the calling session, not this skill. + +This repository distributes a skill; use a separate Unity project with Visual Scripting for editor tests. +Treat bundled examples as versioned references. `_Others/` holds historical research; +read it only when investigating the origin of a pattern. Resolve current package APIs +from the target project instead of a hard-coded PackageCache path. + +- Write comments and documentation in English. +- Never use `?.` or `??` on `UnityEngine.Object`; use explicit Unity null checks. +- Run all Unity object access on the main Unity thread. +- Do not hand-author new C# `.meta` files. Preserve and commit existing tracked metadata + alongside its assets when committing changes. +- Keep helper files self-contained within the skill so copying only that directory works. + +Run `python3 -m unittest discover -s tests -v` for changed Python tools. Tests use +disposable fixtures and may run without further approval. Do not require Unity for a +prose-only edit. For graph behavior, use the relevant skill's Unity checks and state +what remains unverified if an editor is unavailable. Do not change sample project +packages or settings merely to modernize the instructions. diff --git a/README.md b/README.md index 918f010..dd5bc1f 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,32 @@ -# Unity Visual Scripting Agent Skill +# Unity Visual Scripting Skill -A Claude Code skill that enables AI-assisted generation of Unity Visual Scripting graphs through C# editor scripts. +Create, edit, and diagnose Unity Visual Scripting assets with Codex. Updated for GPT-6 Astra: +focused instructions, version-aware references, and explicit validation results. -VisualScripting +## Install +Copy [`.agents/skills/unity-visual-scripting/`](.agents/skills/unity-visual-scripting/) into your Unity +project at the same relative path. The folder contains everything the skill needs; +the sample Unity project is not required. Codex discovers repository skills from +[`.agents/skills/`](https://learn.chatgpt.com/docs/build-skills). -## What This Does +For use across projects, place that folder under `~/.agents/skills/` instead. Select +GPT-6 Astra in your Codex session. The skill does not change model or account settings. -When installed as a Claude Code skill, it allows Claude to: +The `.claude/skills/` entry is a relative symlink to the same source. On systems +without Git symlink support, copy the canonical skill folder into the target project's +`.claude/skills/` instead. Copy only this skill, not the repository's whole settings tree. -- **Create Script Graphs** programmatically using the `Unity.VisualScripting` API -- **Create State Graphs** for state machine-based logic -- **Assign graphs to GameObjects** via `ScriptMachine` / `StateMachine` components -- **Wire nodes** with proper control flow and data connections +## Use -## Installation +```text +Use $unity-visual-scripting. Create a Script Graph that rotates this object each frame, assign it, and verify the behavior. +``` -Just copy `.claude` directory of this repository into your project. +Python 3.9+ runs static checks. Optional C# compilation uses .NET SDK 8+ and the matching Unity editor. Actual graph execution still requires Unity. -## Usage +This repository distributes a skill; use a separate Unity project with Visual Scripting for editor tests. Package versions in a target project take precedence over bundled +examples. A static check passing does not establish a working or visually correct graph. -Once installed, Claude Code will automatically activate the skill when you mention keywords like "visual scripting", "script graph", "state graph", "flow graph", or "ScriptMachine". - -**Example prompts:** - -- "Create a Visual Scripting graph that rotates an object every frame" -- "Make a script graph that handles player input with WASD keys" -- "Generate a state graph with Idle and Walking states" -- "Assign the graph to the Player GameObject" +See [the skill](.agents/skills/unity-visual-scripting/SKILL.md) for workflows and +[development notes](docs/DEVELOPMENT.md) for checks, evaluation scenarios, and migration details. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md new file mode 100644 index 0000000..be15fa6 --- /dev/null +++ b/docs/DEVELOPMENT.md @@ -0,0 +1,51 @@ +# Development and validation + +The canonical skill is `.agents/skills/unity-visual-scripting/`. It must work when copied by +itself to another project or user skill directory. `.claude/skills/unity-visual-scripting` is +a compatibility symlink, not a second source tree. Third-party skills and historical +`_Others/` research are outside this migration. + +## Local checks + +```sh +python3 -m unittest discover -s tests -v +``` + +The tests use temporary files and mock unavailable external processes. They exercise +observable tool results and failure paths; they do not certify Unity graph behavior. +Use Python 3.9+. No Unity or .NET installation is required for these regression tests. +For real compiler/import/render evidence use the installed skill's documented checks. + +## Behavioral evaluation + +Use [eval scenarios](../.agents/skills/unity-visual-scripting/evals/evals.json) in a disposable +copy of a target project. Each scenario states a user request, environment assumptions, +and observable expectations. Evaluate positive routing, a neighboring task that should +not use the skill, editing preservation, and unavailable-editor handling. Record the +actual model, editor/package versions, artifacts and checks. These are evaluation +specifications, not claims that model trials passed. Read only the references needed +for the scenario, and keep generated artifacts outside this repository. + +## Astra migration decisions + +The entry point now carries task selection, important invariants, and evidence criteria; +long versioned examples are read on demand. Package source and existing assets take +precedence over a bundled catalog. Examples no longer justify changing a project's +pipeline, regenerating unrelated nodes, or inventing missing tools. Missing validation +is reported explicitly instead of being counted as a pass. + +This follows OpenAI's [Astra skill guidance](https://developers.openai.com/blog/rethinking-skills-and-prompts-for-gpt-6-astra) +and [skill discovery documentation](https://learn.chatgpt.com/docs/build-skills). +The Unity sample package versions are intentionally retained. This change improves the +instructions and checks; it does not claim compatibility with every later Unity release +or a measured model-quality improvement without separate model trials. + +## Local verification on 2026-10-08 + +- 12 Python regression tests passed. +- Skill frontmatter, UI metadata, local documentation links, and standalone-folder tool execution were checked. +- The rotation generator was compiled against the installed Unity 6000.0.70f1 / Visual Scripting 1.9.7 assemblies and passed the port checker. The UnityShaderGraphSkill sample project supplied those existing assemblies; this distribution repository has no Unity project. Graph execution and scene persistence were not tested. + +No Unity Editor execution, visual inspection, target-device checks, or before/after +model-quality trials were performed in this maintenance pass. Evaluation JSON files +are scenario definitions for those future trials. diff --git a/tests/test_validation.py b/tests/test_validation.py new file mode 100644 index 0000000..3c3d45c --- /dev/null +++ b/tests/test_validation.py @@ -0,0 +1,144 @@ +"""Regression checks for truthful, portable C# preflight results.""" + +import contextlib +import importlib.util +import io +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch +import xml.etree.ElementTree as ET + +TOOLS = Path(__file__).resolve().parents[1] / ".agents/skills/unity-visual-scripting/tools" + + +def load(name): + spec = importlib.util.spec_from_file_location(name, TOOLS / (name + ".py")) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +compiler = load("validate_cs") +combined = load("validate") + + +class CompilerTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="unity skill & test ") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.source = self.root / "Example.cs" + self.source.write_text("#if UNITY_EDITOR\npublic class Example {}\n#endif\n") + self.managed = self.root / "Managed" + self.managed.mkdir() + (self.managed / "UnityEngine.dll").touch() + + def run_compile(self, result): + with patch.object(compiler.shutil, "which", return_value="dotnet"), patch.object( + compiler.subprocess, "run", return_value=result + ): + return compiler.validate(self.source, managed_dir=self.managed) + + def test_missing_editor_is_incomplete(self): + code, _ = compiler.validate(self.source, managed_dir=self.root / "missing") + self.assertEqual(code, 2) + + def test_missing_sdk_is_incomplete(self): + with patch.object(compiler.shutil, "which", return_value=None): + code, _ = compiler.validate(self.source, managed_dir=self.managed) + self.assertEqual(code, 2) + + def test_no_implicit_version_fallback(self): + code, _ = compiler.validate(self.source) + self.assertEqual(code, 2) + project = self.root / "project" + (project / "ProjectSettings").mkdir(parents=True) + (project / "ProjectSettings/ProjectVersion.txt").write_text("m_EditorVersion: 6000.0.70f1\n") + with patch.object(compiler, "find_unity_managed_dir", return_value=None) as lookup: + code, _ = compiler.validate(self.source, unity_project=project) + self.assertEqual(code, 2) + lookup.assert_called_once_with("6000.0.70f1") + code, _ = compiler.validate(self.source, "6000.0.68f1", project, self.managed) + self.assertEqual(code, 2) + + def test_missing_package_assemblies_are_incomplete(self): + (self.root / "ProjectSettings").mkdir() + (self.root / "ProjectSettings/ProjectVersion.txt").write_text("m_EditorVersion: 6000.0.70f1\n") + code, _ = compiler.validate(self.source, unity_project=self.root, managed_dir=self.managed) + self.assertEqual(code, 2) + + def test_build_failure_without_cs_diagnostic_fails(self): + code, evidence = self.run_compile(subprocess.CompletedProcess([], 1, "error MSB1009: missing project", "")) + self.assertEqual(code, 1) + self.assertIn("MSB1009", evidence) + + def test_build_crash_does_not_pass(self): + code, _ = self.run_compile(subprocess.CompletedProcess([], -9, "", "terminated")) + self.assertEqual(code, 1) + + def test_timeout_is_incomplete(self): + with patch.object(compiler.shutil, "which", return_value="dotnet"), patch.object( + compiler.subprocess, "run", side_effect=subprocess.TimeoutExpired("dotnet", 45) + ): + code, _ = compiler.validate(self.source, managed_dir=self.managed) + self.assertEqual(code, 2) + + def test_packaged_template_builds_in_disposable_directory(self): + self.assertTrue(compiler.PROJECT_FILE.is_file()) + observed = [] + def build(args, **kwargs): + cwd = Path(kwargs["cwd"]) + observed.append(cwd) + props = ET.parse(cwd / "ValidationProject.csproj").getroot() + self.assertEqual(props.findtext(".//UnityManagedDir"), str(self.managed.resolve())) + self.assertEqual((cwd / "Input.cs").read_text(), self.source.read_text()) + self.assertNotEqual(cwd, TOOLS / "validation_project") + return subprocess.CompletedProcess(args, 0, "Build succeeded", "") + with patch.object(compiler.shutil, "which", return_value="dotnet"), patch.object( + compiler.subprocess, "run", side_effect=build + ): + code, _ = compiler.validate(self.source, managed_dir=self.managed) + self.assertEqual(code, 0) + self.assertFalse(observed[0].exists()) + + +class CombinedTests(unittest.TestCase): + def run_main(self, results, flags=()): + with tempfile.TemporaryDirectory() as tmp: + source = Path(tmp) / "Input.cs" + source.write_text("#if UNITY_EDITOR\n#endif\n") + stdout, stderr = io.StringIO(), io.StringIO() + with patch.object(sys, "argv", ["validate.py", str(source), *flags]), patch.object( + combined, "run_check", side_effect=results + ) as run, contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as raised: + combined.main() + return raised.exception.code, stdout.getvalue(), stderr.getvalue(), run.call_count + + def test_skipped_or_crashed_layers_never_pass(self): + for codes in ((2, 0), (0, 2), (37, 0), (0, -9)): + with self.subTest(codes=codes): + code, _, stderr, calls = self.run_main([(c, "", "setup detail") for c in codes]) + self.assertEqual(code, 2) + self.assertEqual(calls, 2) + self.assertIn("setup detail", stderr) + + def test_detected_error_fails_even_with_other_layer_unavailable(self): + code, _, _, _ = self.run_main([(2, "", ""), (1, "bad port", "")]) + self.assertEqual(code, 1) + + def test_pass_requires_both_layers(self): + code, _, _, calls = self.run_main([(0, "", ""), (0, "", "")]) + self.assertEqual((code, calls), (0, 2)) + + def test_static_only_has_explicit_scope(self): + code, stdout, _, calls = self.run_main([(0, "", "")], ["--static-only"]) + self.assertEqual((code, calls), (0, 1)) + self.assertIn("compilation not run", stdout) + + +if __name__ == "__main__": + unittest.main()