diff --git a/.github/analyzers/README.md b/.github/analyzers/README.md index b39d9cd2b..cfc2b0717 100644 --- a/.github/analyzers/README.md +++ b/.github/analyzers/README.md @@ -26,7 +26,7 @@ The pinned set is: (`Apache-2.0`), using its Roslyn 3.8 payload. Native qualification is required when changing this pin. - [Microsoft.Unity.Analyzers 1.22.0](https://www.nuget.org/packages/Microsoft.Unity.Analyzers/1.22.0) - (`MIT`), the newest tested release that loads in Unity 2021's Roslyn 3.8 host. + (`MIT`), the pinned release for the Unity 2021 analyzer lane. - [SonarAnalyzer.CSharp 10.35.0.4138](https://www.nuget.org/packages/SonarAnalyzer.CSharp/10.35.0.4138) (`Sonar Source-Available License v1.0`). - [Microsoft.CodeAnalysis.NetAnalyzers 7.0.4](https://www.nuget.org/packages/Microsoft.CodeAnalysis.NetAnalyzers/7.0.4) @@ -39,7 +39,9 @@ Code-fix and Workspaces assemblies are excluded because Unity's compiler host does not need them. `manifest.json` is the text-only lock file for package URLs, versions, licenses, exact archive entries, hashes, and Unity metadata GUIDs. -The current package screen retains the Unity and .NET analyzer pins because their -newest binaries reference Roslyn 3.11, while Unity 2021 provides Roslyn 3.8. The -newer ErrorProne prerelease references Roslyn 4.13 and Immutable 8. These pins must -remain until supported-host qualification establishes a compatible replacement. +The newer Unity and .NET analyzer packages in the upgrade screen reference +Roslyn 3.11. The repository targets the +Roslyn 3.8 API. The Linux Unity 2021.3.45f1 archive contains a Roslyn 3.9 script +compiler and separate Roslyn 3.7 binaries for Mono/MSBuild. The newer ErrorProne +prerelease references Roslyn 4.13 and Immutable 8. Keep these pins until +supported-host qualification establishes a compatible replacement. diff --git a/.github/asset-store-listing.json b/.github/asset-store-listing.json index 597c353cd..473deac62 100644 --- a/.github/asset-store-listing.json +++ b/.github/asset-store-listing.json @@ -2,7 +2,7 @@ "schemaVersion": 2, "locale": "en-US", "title": "DxMessaging", - "description": "Connect gameplay systems without direct references between senders and receivers. DxMessaging provides synchronous, type-safe untargeted, targeted, and broadcast messages. Lifecycle-managed registration tokens pair subscriptions with components and dependency-injection scopes. Message Monitor, Flow Graph, Inspector overlays, and runtime diagnostics make routes visible while you develop. Optional samples cover Zenject, VContainer, and Reflex.\n\nDxMessaging is free and will remain free forever. No paid editions, paid upgrades, or feature charges.\n\nAI assistance disclosure: DxMessaging began as an original project around 2014 and remains actively developed and used today. Over the past two years, I (wallstop) have been using LLMs to help improve the library's quality and performance, expand its tests, and create user-facing documentation. There is always a human in the loop: I actively review all changes and read through all user-facing copy. I share this so you can make an informed decision about using the project.", + "description": "Connect gameplay systems without direct references between senders and receivers. DxMessaging provides synchronous, type-safe untargeted, targeted, and broadcast messages. Lifecycle-managed registration tokens pair subscriptions with components and dependency-injection scopes. Message Monitor, Flow Graph, Inspector overlays, and runtime diagnostics make routes visible while you develop. Optional samples cover Zenject, VContainer, and Reflex.\n\nDxMessaging includes collection pool code adapted from Unity Helpers under the MIT License. See Third Party Notices.md in the package.\n\nDxMessaging is free and will remain free forever. No paid editions, paid upgrades, or feature charges.\n\nAI assistance disclosure: DxMessaging began as an original project around 2014 and remains actively developed and used today. Over the past two years, I (wallstop) have been using LLMs to help improve the library's quality and performance, expand its tests, and create user-facing documentation. There is always a human in the loop: I actively review all changes and read through all user-facing copy. I share this so you can make an informed decision about using the project.", "aiDescription": "OpenAI models starting with GPT-5, used through Codex, and Anthropic models starting with Opus 4, used through Claude Code, have assisted with substantial portions of the code, tests, and documentation. I (wallstop) review all changes for accuracy and correctness and read all user-facing copy. Artwork is minimal and includes AI-generated SVGs. Product screenshots show the actual editor tooling.", "priceUsd": 0, "keywords": "unity message messaging event-bus decoupling type-safe diagnostics debugging performance zero-allocation architecture gameplay", diff --git a/.github/workflows/attributes-package.yml b/.github/workflows/attributes-package.yml index 3d4837d24..11870d81e 100644 --- a/.github/workflows/attributes-package.yml +++ b/.github/workflows/attributes-package.yml @@ -97,16 +97,23 @@ jobs: NUGET_PACKAGES: ${{ runner.temp }}/dxm-attributes-live-${{ github.run_id }}-${{ github.run_attempt }} run: | set -euo pipefail - dotnet restore .nuget-tests/DxMessaging.Attributes.Package.Tests.csproj -p:AttributesPackageVersion="$PACKAGE_VERSION" -p:RestoreAdditionalProjectSources=https://api.nuget.org/v3/index.json - dotnet test .nuget-tests/DxMessaging.Attributes.Package.Tests.csproj \ - --configuration Release --no-restore -p:AttributesPackageVersion="$PACKAGE_VERSION" \ - -p:RestoreAdditionalProjectSources=https://api.nuget.org/v3/index.json \ - --logger 'trx;LogFileName=live-package-consumer.trx' --results-directory .artifacts/nuget-live-tests + feed=https://api.nuget.org/v3/index.json + installed="$NUGET_PACKAGES/wallstopstudios.dxmessaging.attributes/$PACKAGE_VERSION" + dotnet restore .nuget-tests/DxMessaging.Attributes.Package.Tests.csproj \ + --source "$feed" --no-http-cache -p:RestoreAdditionalProjectSources= \ + -p:AttributesPackageVersion="$PACKAGE_VERSION" + if ! jq -e --arg feed "$feed" '.source == $feed' "$installed/.nupkg.metadata" > /dev/null; then + echo "::error::The restored attributes package does not record NuGet.org as its source." + exit 1 + fi package=".artifacts/nuget/WallstopStudios.DxMessaging.Attributes.${PACKAGE_VERSION}.nupkg" payloads="$(unzip -Z1 "$package" | grep -E '^(lib/|analyzers/|README.md$)')" while IFS= read -r payload; do - unzip -p "$package" "$payload" | cmp - "$NUGET_PACKAGES/wallstopstudios.dxmessaging.attributes/$PACKAGE_VERSION/$payload" + unzip -p "$package" "$payload" | cmp - "$installed/$payload" done <<< "$payloads" + dotnet test .nuget-tests/DxMessaging.Attributes.Package.Tests.csproj \ + --configuration Release --no-restore -p:AttributesPackageVersion="$PACKAGE_VERSION" \ + --logger 'trx;LogFileName=live-package-consumer.trx' --results-directory .artifacts/nuget-live-tests - name: Upload live package results if: ${{ always() && inputs.mode == 'verify' }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 44f840220..f9b72c45d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -158,7 +158,7 @@ jobs: "(\.md$|\.markdown$|^docs/|^\.lychee\.toml$|^\.github/scripts/check-markdown-links\.ps1$|^\.github/actions/install-pinned-lychee/action\.yml$|$ci_workflow)" # Each managed suite follows its actual inputs. Pure documentation must not run runtime retention matrices. set_output dotnet \ - "(^SourceGenerators/|^Runtime/Analyzers/|^Runtime/Attributes/|^\.net-attributes/|^\.nuget-tests/|\.csproj$|\.props$|\.targets$|(^|/)global\.json$|(^|/)\.editorconfig$|^\.config/dotnet-tools\.json$|^\.github/analyzers/|$ci_workflow)" + "(^SourceGenerators/|^Editor/Analyzers/(BaseCallIlInspector|BaseCallLogMessageParser|BaseCallReportAggregator|BaseCallTypeScannerCore)\.cs$|^Runtime/Analyzers/|^Runtime/Attributes/|^\.net-attributes/|^\.nuget-tests/|\.csproj$|\.props$|\.targets$|(^|/)global\.json$|(^|/)\.editorconfig$|^\.config/dotnet-tools\.json$|^\.github/analyzers/|$ci_workflow)" set_output runtime_dotnet \ "(^Runtime/|^Tests/|^Editor/Analyzers/BaseCallIlInspector\.cs$|^\.net[^/]*/|^SourceGenerators/|\.props$|\.targets$|(^|/)global\.json$|(^|/)\.editorconfig$|^\.github/analyzers/|$ci_workflow)" set_output docs_dotnet \ @@ -966,6 +966,14 @@ jobs: echo "::group::Unity editor heartbeat guards" cat "$heartbeat_log" echo "::endgroup::" + if [ "$RUNNER_OS" = "macOS" ] && [ "$script_status" -eq 0 ] && [ "$heartbeat_status" -eq 1 ] && + grep -Fxq "Isolated heartbeat comparison eligible." "$heartbeat_log"; then + # Keep the overlapping result as the gate. Capture an isolated comparison on the same runner. + isolated_status=0 + pwsh -NoLogo -NoProfile -File ./scripts/__tests__/test-editor-provisioning-heartbeat.ps1 \ + -VerboseOutput -ReportFiniteTiming || isolated_status=$? + echo "::notice::Isolated heartbeat diagnostic exited $isolated_status." + fi if [ "$script_status" -ne 0 ] || [ "$heartbeat_status" -ne 0 ]; then echo "::error::Script tests exited $script_status; heartbeat guards exited $heartbeat_status." exit 1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c9ee0908..44be83b9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,14 +43,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - **BREAKING:** Add a direct `WallstopStudios.DxMessaging.Attributes` reference to Unity assembly definitions that use public - DxMessaging attributes. Namespaces stay unchanged; see the [4.0 migration guide](docs/guides/migration-guide.md#reference-the-dedicated-attributes-assembly). + DxMessaging attributes. Namespaces stay unchanged; see the [4.0 migration guide](https://ambiguous-interactive.github.io/DxMessaging/guides/migration-guide/#reference-the-dedicated-attributes-assembly). - Correct IntelliSense summaries and references, including cache enumeration, bus reset behavior, global observer message and context parameters, empty-bus debug logging, and deregistration callback boundaries ([#503](https://github.com/Ambiguous-Interactive/DxMessaging/issues/503), [#575](https://github.com/Ambiguous-Interactive/DxMessaging/issues/575)). - **BREAKING:** Remove the test-only `DxMessagingRuntimeSettingsProvider.Override` API. Configure the runtime settings resource asset for application behavior and keep fixture configuration in - test assemblies; see the [4.0 migration guide](docs/guides/migration-guide.md#migrating-to-400). + test assemblies; see the [4.0 migration guide](https://ambiguous-interactive.github.io/DxMessaging/guides/migration-guide/#migrating-to-400). - Reduce recurring Unity correctness setup by installing only the locked Node.js runtime dependencies used to redact and seal test artifacts ([#572](https://github.com/Ambiguous-Interactive/DxMessaging/issues/572)). - Add disabled, missing-token, destroyed-receiver, stale-selection, and separate-bus visibility @@ -62,7 +62,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 materializing registrar sort keys once, and reduce package size by shipping only the optimized analyzer payload instead of its development sources ([#576](https://github.com/Ambiguous-Interactive/DxMessaging/issues/576), [#577](https://github.com/Ambiguous-Interactive/DxMessaging/issues/577)). - **BREAKING:** Fast handlers and post-processors now use readonly references; change callback - parameters from `ref` to `in` and follow the [4.0 migration guide](docs/guides/migration-guide.md#migrating-to-400) ([#486](https://github.com/Ambiguous-Interactive/DxMessaging/issues/486)). + parameters from `ref` to `in` and follow the [4.0 migration guide](https://ambiguous-interactive.github.io/DxMessaging/guides/migration-guide/#migrating-to-400) ([#486](https://github.com/Ambiguous-Interactive/DxMessaging/issues/486)). - Show `DXMSG006` through `DXMSG010` in MessageAwareComponent Inspector diagnostic titles so lifecycle failures and opt-outs remain distinguishable ([#314](https://github.com/Ambiguous-Interactive/DxMessaging/issues/314)). @@ -74,6 +74,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Fix Flow Graph compilation on early Unity 2021.3 patches + ([#575](https://github.com/Ambiguous-Interactive/DxMessaging/issues/575)). - Resolve message source links in the Flow Graph and Message Monitor against currently loaded assemblies in Unity 6.6 ([#813](https://github.com/Ambiguous-Interactive/DxMessaging/issues/813)). - Use Unity's loaded assembly path to verify the runtime in the 3.x upgrade preview on Unity 6.6 @@ -82,8 +84,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#810](https://github.com/Ambiguous-Interactive/DxMessaging/issues/810)). - Preserve `MessagingComponent` listener ownership during callbacks and report unresolved provider recursion during initial setup ([#805](https://github.com/Ambiguous-Interactive/DxMessaging/issues/805)). -- Reduce diagnostic scan buffering in the opt-in Editor Console bridge and release its Console - enumeration reliably ([#801](https://github.com/Ambiguous-Interactive/DxMessaging/issues/801)). +- Replace the opt-in Inspector scan of Unity's Console history with a compiler warning feed. + Existing settings carry forward, and compiler warnings keep their source locations + ([#801](https://github.com/Ambiguous-Interactive/DxMessaging/issues/801), + [#575](https://github.com/Ambiguous-Interactive/DxMessaging/issues/575)). - Preserve broken-base-chain warnings (`DXMSG010`) in the opt-in Editor compiler-message bridge ([#802](https://github.com/Ambiguous-Interactive/DxMessaging/issues/802)). - Remove stale compiler diagnostics from the Editor bridge when assemblies report the same type @@ -109,11 +113,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 DxMessaging namespace text ([#707](https://github.com/Ambiguous-Interactive/DxMessaging/issues/707)). - **BREAKING:** Reject record field constructors that replace the record copy constructor and can silently change `with` results. Choose a distinct construction API as described in the - [migration guide](docs/guides/migration-guide.md#preserve-record-copy-behavior) + [migration guide](https://ambiguous-interactive.github.io/DxMessaging/guides/migration-guide/#preserve-record-copy-behavior) ([#720](https://github.com/Ambiguous-Interactive/DxMessaging/issues/720)). - **BREAKING:** Order generated constructor parameters by source-file compilation order, then declaration order within each file. Check positional calls for split partial types in the - [migration guide](docs/guides/migration-guide.md#check-constructors-for-split-partial-types) + [migration guide](https://ambiguous-interactive.github.io/DxMessaging/guides/migration-guide/#check-constructors-for-split-partial-types) ([#723](https://github.com/Ambiguous-Interactive/DxMessaging/issues/723)). - Initialize excluded struct fields and auto-properties in generated constructors while preserving initializers and avoiding unintended constructor calls. Chain empty primary constructors and @@ -382,7 +386,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 components carry each one, and mark mixed enabled states so a missing or disabled handler stands out across a scene selection ([#297](https://github.com/Ambiguous-Interactive/DxMessaging/issues/297)). - See [Inspector Overlay](docs/guides/inspector-overlay.md#message-subscriptions). + See [Inspector Overlay](https://ambiguous-interactive.github.io/DxMessaging/guides/inspector-overlay/#message-subscriptions). ### Changed @@ -1042,7 +1046,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Mutation tests now exercise every messaging kind (Untargeted/Targeted/Broadcast) via a single parameterized fixture (`[ValueSource(MessageScenarios.AllKinds)]`) across `MutationDuringEmissionTests`, `MutationInterceptorTests`, and `MutationDestructionTests`. Users get tighter cross-kind parity guarantees; no runtime API change. (~720 lines of duplication removed; test count preserved.) - Renamed `UntargetedTests`, `TargetedTests`, `BroadcastTests` to `EmitUntargetedSpecificTests`, `EmitTargetedSpecificTests`, `EmitBroadcastSpecificTests` to clarify that kind-common tests live in `EmitTests` and kind-specific tests live in the renamed files. (Test-suite hardening is test-only; no `Runtime/` behavior was modified.) -- Documentation now warns up front that `MessageAwareComponent` subclasses must call `base.Awake()`, `base.OnEnable()`, `base.OnDisable()`, `base.OnDestroy()`, and `base.RegisterMessageHandlers()` from any override; admonitions added to the Quick Start, Getting Started Guide, Visual Guide, README, FAQ, and Troubleshooting pages all link to [`DXMSG006`](docs/reference/analyzers.md#dxmsg006-missing-base-call) (issue #195). +- Documentation now warns up front that `MessageAwareComponent` subclasses must call `base.Awake()`, `base.OnEnable()`, `base.OnDisable()`, `base.OnDestroy()`, and `base.RegisterMessageHandlers()` from any override; admonitions added to the Quick Start, Getting Started Guide, Visual Guide, README, FAQ, and Troubleshooting pages all link to [`DXMSG006`](https://ambiguous-interactive.github.io/DxMessaging/reference/analyzers/#dxmsg006-missing-base-call) (issue #195). ### Fixed diff --git a/Editor/Analyzers/BaseCallLogMessageParser.cs b/Editor/Analyzers/BaseCallLogMessageParser.cs index ff6b957bb..da8c1c5e2 100644 --- a/Editor/Analyzers/BaseCallLogMessageParser.cs +++ b/Editor/Analyzers/BaseCallLogMessageParser.cs @@ -179,9 +179,51 @@ correctly on this component. /// Rejects rows outside both supported diagnostic text shapes. internal static bool IsDiagnosticCandidate(string? logLine) { - // Bare bodies start with a quote. Location prefixes contain the uppercase diagnostic ID. - return !string.IsNullOrEmpty(logLine) - && (logLine[0] == '\'' || 0 <= logLine.IndexOf("DXMSG0", StringComparison.Ordinal)); + if (string.IsNullOrEmpty(logLine)) + { + return false; + } + + // A source path can start with an apostrophe, so check the diagnostic ID first. + if ( + 0 <= logLine.IndexOf("DXMSG0", StringComparison.Ordinal) + && PrefixRegex.IsMatch(logLine) + ) + { + return true; + } + + if (logLine[0] != '\'') + { + return false; + } + + int typeEnd = logLine.IndexOf('\'', 1); + if (typeEnd <= 1) + { + return false; + } + + int bodyStart = typeEnd + 1; + while (bodyStart < logLine.Length && char.IsWhiteSpace(logLine[bodyStart])) + { + ++bodyStart; + } + + // Keep the opening words of all five bare diagnostic formats above. + ReadOnlySpan body = logLine.AsSpan(bodyStart); + return StartsWithWord(body, "overrides") + || StartsWithWord(body, "hides") + || (StartsWithWord(body, "is") && StartsWithWord(body[2..].TrimStart(), "excluded")) + || StartsWithWord(body, "declares") + || StartsWithWord(body, "calls"); + } + + private static bool StartsWithWord(ReadOnlySpan body, string word) + { + return word.Length < body.Length + && char.IsWhiteSpace(body[word.Length]) + && body.StartsWith(word.AsSpan()); } /// @@ -301,27 +343,35 @@ public static Dictionary Aggregate(IEnumerable continue; } - if (!result.TryGetValue(entry.TypeFullName, out ParsedTypeReport? report)) - { - report = new ParsedTypeReport { TypeFullName = entry.TypeFullName }; - result[entry.TypeFullName] = report; - } + AddEntry(result, entry); + } - report.DiagnosticIds.Add(entry.DiagnosticId); + return result; + } - if (!string.IsNullOrEmpty(entry.MethodName)) - { - report.MissingBaseFor.Add(entry.MethodName); - } + internal static void AddEntry( + Dictionary result, + ParsedEntry entry + ) + { + if (!result.TryGetValue(entry.TypeFullName, out ParsedTypeReport? report)) + { + report = new ParsedTypeReport { TypeFullName = entry.TypeFullName }; + result[entry.TypeFullName] = report; + } - if (string.IsNullOrEmpty(report.FilePath) && !string.IsNullOrEmpty(entry.FilePath)) - { - report.FilePath = entry.FilePath; - report.Line = entry.Line; - } + report.DiagnosticIds.Add(entry.DiagnosticId); + + if (!string.IsNullOrEmpty(entry.MethodName)) + { + report.MissingBaseFor.Add(entry.MethodName); } - return result; + if (string.IsNullOrEmpty(report.FilePath) && !string.IsNullOrEmpty(entry.FilePath)) + { + report.FilePath = entry.FilePath; + report.Line = entry.Line; + } } } } diff --git a/Editor/Analyzers/DxMessagingConsoleHarvester.cs b/Editor/Analyzers/DxMessagingConsoleHarvester.cs index 1e35e846d..ed8b09b2c 100644 --- a/Editor/Analyzers/DxMessagingConsoleHarvester.cs +++ b/Editor/Analyzers/DxMessagingConsoleHarvester.cs @@ -6,7 +6,6 @@ namespace DxMessaging.Editor.Analyzers using System.Globalization; using System.IO; using System.Linq; - using System.Reflection; using DxMessaging.Editor.Settings; using UnityEditor; using UnityEditor.Compilation; @@ -58,8 +57,8 @@ internal sealed class BaseCallReportFile /// /// Builds the per-FQN snapshot consumed by the inspector overlay from a deterministic IL - /// reflection scanner () -- and, optionally, a legacy - /// console-scrape bridge for users who want the union of both data sources. + /// reflection scanner () and an optional compiler warning + /// feed. /// /// /// @@ -73,14 +72,10 @@ internal sealed class BaseCallReportFile /// ). /// /// - /// Secondary source (opt-in): legacy console-scrape bridge. When - /// is true, the harvester ALSO - /// reads warnings from UnityEditor.LogEntries via reflection and from - /// CompilationPipeline.assemblyCompilationFinished's per-assembly - /// CompilerMessage[] payloads. This path is non-deterministic on Unity 2021 (Bee/csc - /// cache hits cause Unity to skip surfacing analyzer warnings to either store) and is the - /// reason the IL-reflection scanner exists. Default off; available for users who want the - /// union of both data sources. + /// Secondary source (opt-in): compiler warnings. + /// adds diagnostics from the public + /// CompilationPipeline.assemblyCompilationFinished event to the IL scanner's report. + /// The event supplies messages from compilations observed in the current Editor session. /// /// /// The inspector overlay reads its snapshot from the unified per-FQN map populated here on @@ -90,8 +85,7 @@ internal sealed class BaseCallReportFile /// /// stays true as long as the static constructor itself does /// not throw -- the IL scanner is always wired, so the overlay never falls back to its - /// degraded "harvester unavailable" warning surface in normal operation. - /// continues to report whether the legacy reflection layer is bindable, for diagnostics only. + /// degraded "harvester unavailable" warning surface in normal operation. /// /// [InitializeOnLoad] @@ -101,12 +95,6 @@ public static class DxMessagingConsoleHarvester private const string ReportDirectoryName = "DxMessaging"; private const double PollIntervalSeconds = 0.25; - /* - Bound the initial buffer allocation. It can still grow when the console contains - more diagnostic candidates. - */ - private const int MaxLineListInitialCapacity = 1024; - private static readonly Dictionary SnapshotInternal = new( StringComparer.Ordinal ); @@ -130,27 +118,7 @@ private static readonly Dictionary< Dictionary > _pendingByAssembly = new(StringComparer.OrdinalIgnoreCase); - /* - True when the LogEntries reflection layer failed to bind. The harvester remains - available via the CompilerMessage path; this flag just gates the LogEntries-specific - code paths (Tick polling, RescanNow's reflection call). Renamed from `_disabled` so - the name reflects what it actually means. - */ - private static readonly bool _logEntriesDisabled; - - /* - Reflection handles. Resolved once in the static ctor; null when the running Unity version - does not expose the expected LogEntries shape. - */ - private static readonly Type _logEntryType; - private static readonly MethodInfo _startGettingEntries; - private static readonly MethodInfo _endGettingEntries; - private static readonly MethodInfo _getEntryInternal; - private static readonly MethodInfo _getCount; - private static readonly FieldInfo _messageField; - private static double _lastTickTime; - private static int _lastSeenCount; private static int _lastSettingsRevision = -1; /* @@ -219,20 +187,14 @@ public static bool TryGetEntry(string fullyQualifiedTypeName, out BaseCallReport /// The CompilationPipeline.assemblyCompilationFinished feed is wired /// unconditionally on every supported Unity version, so this property is effectively /// always true in normal operation; it only flips to false when the static - /// constructor itself throws (a hard initialization failure). The LogEntries reflection - /// layer is the optional source -- see for that flag. + /// constructor itself throws (a hard initialization failure). /// The inspector overlay reads this property to decide whether to render its degraded /// warning surface, so the contract here is "should the overlay attempt to render at all". /// public static bool IsAvailable { get; private set; } = true; - /// - /// true when the legacy UnityEditor.LogEntries reflection layer resolved - /// successfully on this Unity version. The harvester does not require this to be true to - /// function -- Unity 2021's analyzer warnings flow through the CompilerMessage feed - /// instead. Available for editor diagnostics. - /// - public static bool LogEntriesAvailable => !_logEntriesDisabled; + /// Reports false for the retired Console history bridge. + public static bool LogEntriesAvailable => false; /// /// true once the first of this Editor session has produced @@ -249,80 +211,13 @@ public static bool TryGetEntry(string fullyQualifiedTypeName, out BaseCallReport /// public static bool IsFreshThisSession => _isFreshThisSession; - /// Raised whenever the snapshot changes (post-compile, post-domain-reload, or polled console-count change). + /// Raised whenever the snapshot changes (after compilation, reload, or a settings change). public static event Action ReportUpdated; static DxMessagingConsoleHarvester() { try { - Type logEntriesType = Type.GetType("UnityEditor.LogEntries,UnityEditor.dll") - /* - S9: legacy / future-Unity probe. UnityEditorInternal.LogEntries doesn't - exist today, but documenting the fallback as a one-liner keeps us forward- - compatible at zero cost. - */ - ?? Type.GetType("UnityEditorInternal.LogEntries,UnityEditor.dll"); - _logEntryType = Type.GetType("UnityEditor.LogEntry,UnityEditor.dll") - ?? Type.GetType("UnityEditorInternal.LogEntry,UnityEditor.dll"); - - bool logEntriesBound = false; - if (logEntriesType is not null && _logEntryType is not null) - { - if (_logEntryType.IsValueType) - { - /* - S8: defensive value-type guard. If a future Unity version makes LogEntry - a struct, Activator.CreateInstance would hand us a boxed copy and the - GetEntry call would mutate that copy in-place; harvest would silently - report empty. Disable the LogEntries path rather than silently producing - a wrong result; the CompilerMessage feed still runs. - */ - LogOnce( - "logentry-is-struct", - "LogEntry is a value type on this Unity version; LogEntries scanning disabled. Falling back to the CompilerMessage feed." - ); - } - else - { - _startGettingEntries = SafeGetStaticMethod( - logEntriesType, - "StartGettingEntries" - ); - _endGettingEntries = SafeGetStaticMethod( - logEntriesType, - "EndGettingEntries" - ); - _getEntryInternal = SafeGetStaticMethod(logEntriesType, "GetEntryInternal"); - _getCount = SafeGetStaticMethod(logEntriesType, "GetCount"); - _messageField = SafeGetInstanceField(_logEntryType, "message"); - - logEntriesBound = - _startGettingEntries is not null - && _endGettingEntries is not null - && _getEntryInternal is not null - && _getCount is not null - && _messageField is not null; - } - } - - if (!logEntriesBound) - { - /* - The LogEntries reflection layer is unavailable. The IL-reflection scanner - is the primary data source so this is no longer a critical path; the - log-once is kept for diagnostic purposes (and only matters when the user - has enabled the legacy bridge via DxMessagingSettings.UseConsoleBridge). - */ - LogOnce( - "reflection-fallback", - "LogEntries reflection unavailable on this Unity version. The IL-reflection " - + "scanner remains the primary data source; the legacy console-scrape bridge " - + "(opt-in via DxMessagingSettings.UseConsoleBridge) cannot read LogEntries on this version." - ); - _logEntriesDisabled = true; - } - LoadFromDisk(); /* @@ -341,18 +236,17 @@ until Unity is idle so settings load doesn't fight a transitional asset-import "DxMessagingConsoleHarvester failed to initialize.", ex ); - _logEntriesDisabled = true; IsAvailable = false; } } /// - /// Force a re-read of the editor console and drain any pending CompilerMessage payloads. + /// Rescan loaded types and apply any pending compiler warnings. /// Called automatically on domain reload and compilation events; the menu entry exposes it /// for manual invocation. Settings setters (e.g. /// ) call this via /// so a re-enable repopulates the snapshot - /// without waiting for the next polled tick. + /// without waiting for the next settings check. /// [MenuItem("Tools/Wallstop Studios/DxMessaging/Rescan Base-Call Warnings")] public static void RescanNow() @@ -363,12 +257,8 @@ public static void RescanNow() } /* - Critical: NEVER touch LogEntries reflection or AssetDatabase while Unity is mid- - compile or mid-asset-update. Reading LogEntries during compilation contends with the - compiler's own log-buffer lock and can deadlock the editor. Touching AssetDatabase - during compilation risks importer reentrancy. Settings reads stay passive and - never create an asset. Defer to the post-compile state - and let the polled tick (or the explicit afterAssemblyReload hook) pick it up. + Defer until compilation and asset imports finish. Settings reads stay passive and + never create an asset. */ if (EditorApplication.isCompiling || EditorApplication.isUpdating) { @@ -387,7 +277,6 @@ and let the polled tick (or the explicit afterAssemblyReload hook) pick it up. { _pendingByAssembly.Clear(); } - _lastSeenCount = 0; PersistToDisk(); /* The "check disabled" path still represents a successful session-time decision @@ -406,8 +295,7 @@ check. Doing this BEFORE RaiseReportUpdated mirrors the main path's ordering. /* -- Primary source (always-on): IL-reflection scanner over loaded MessageAwareComponent subclasses. Deterministic across Unity 2021 cache hits and - incremental compiles; replaces the lossy console-scrape harvester as the - inspector overlay's source of truth. + incremental compiles. */ Dictionary scannerEntries; try @@ -425,7 +313,7 @@ inspector overlay's source of truth. /* The scanner produces a complete view of all loaded subclasses on every call, so it fully replaces the snapshot. Build the new map up-front from the scanner's output; - we'll union the legacy-bridge entries into it below if the user opted in. + we will add compiler warnings below if the user opted in. */ Dictionary nextSnapshot = new( scannerEntries, @@ -434,21 +322,8 @@ inspector overlay's source of truth. bool useBridge = settings != null && settings._useConsoleBridge; - int currentCount = 0; - bool logEntriesHarvested = false; if (useBridge) { - // -- Secondary source (opt-in): LogEntries reflection (Unity 2022+ reliable path). - Dictionary logEntriesAggregate = HarvestFromLogEntries( - out currentCount, - out logEntriesHarvested - ); - - /* - -- Secondary source (opt-in): pending CompilerMessage payloads (Unity 2021's - primary path under the legacy bridge). Drain the cross-thread channel - atomically. - */ Dictionary> drained; lock (_compilationFeedLock) { @@ -469,35 +344,28 @@ out logEntriesHarvested ApplyCompilerMessageDrain(drained); /* - Merge the bridge view (LogEntries + CompilerMessage) and union it INTO the - scanner-produced snapshot. The scanner is authoritative; the bridge can only - ADD methods/diagnostic ids it sees that the scanner missed (e.g. exotic IL - shapes the byte walker stepped past). Bridge entries never override the - scanner's classification. + The compiler feed can contribute methods or diagnostic IDs the scanner missed. + It cannot override the scanner's classification. */ try { Dictionary bridgeSnapshot = - _compilerReports.BuildMergedSnapshot( - logEntriesHarvested ? logEntriesAggregate : null - ); + _compilerReports.BuildMergedSnapshot(null); UnionBridgeIntoSnapshot(bridgeSnapshot, nextSnapshot); } catch (Exception ex) { LogExceptionOnce("aggregate", "Snapshot merge failed.", ex); /* - Fall through with the scanner-only snapshot; partial data is better than - wiping the snapshot when the bridge half misbehaves. + Keep the scanner snapshot if merging compiler warnings fails. */ } } else { /* - Bridge is disabled: drop any pending CompilerMessage entries the harvester may - have buffered (they would otherwise leak into the snapshot the next time the - user toggles the bridge on). The bridge bookkeeping is reset below as well. + Discard compiler messages when the bridge is disabled so stale warnings do + not appear when the user enables it later. */ lock (_compilationFeedLock) { @@ -517,10 +385,6 @@ have buffered (they would otherwise leak into the snapshot the next time the SnapshotInternal[kvp.Key] = kvp.Value; } - if (useBridge && logEntriesHarvested) - { - _lastSeenCount = currentCount; - } PersistToDisk(); /* Mark the snapshot as session-fresh AFTER the persist + before the event fires, so @@ -595,153 +459,6 @@ Dictionary scannerSnapshot } } - /* - Reads the editor console via LogEntries reflection. Returns the aggregated per-type - report, the current console count, and whether the harvest actually ran (false when - the LogEntries reflection layer is unavailable or threw). On Unity 2021 this returns - an empty aggregate every time; the analyzer warnings flow through the CompilerMessage - feed instead and arrive via ApplyCompilerMessageDrain. - */ - private static Dictionary HarvestFromLogEntries( - out int currentCount, - out bool harvested - ) - { - currentCount = 0; - harvested = false; - if (_logEntriesDisabled) - { - return new Dictionary(StringComparer.Ordinal); - } - - try - { - currentCount = (int)_getCount.Invoke(null, null); - } - catch (Exception ex) - { - LogExceptionOnce("getcount", "GetCount invocation failed.", ex); - return new Dictionary(StringComparer.Ordinal); - } - - /* - S4: console-clear handling. We always overwrite _lastSeenCount near the bottom of - RescanNow, so the only point of acting on a shrunken count here is to be explicit - about the semantic. The accumulator is rebuilt from scratch every rescan, so the - clear case is naturally consistent; even an empty log produces an empty aggregate - and a ReportUpdated fire that drops stale rows. - */ - - // Allocate before acquiring the Console enumeration so failure cannot skip its release. - List lines = new(Math.Min(currentCount, MaxLineListInitialCapacity)); - try - { - _startGettingEntries.Invoke(null, null); - } - catch (Exception ex) - { - LogExceptionOnce("start", "StartGettingEntries invocation failed.", ex); - return new Dictionary(StringComparer.Ordinal); - } - - int harvestedCount = currentCount; - try - { - if (_startGettingEntries.ReturnType == typeof(int)) - { - /* - The Invoke return value is intentionally discarded; we re-pull via GetCount - because the polled count is authoritative. - */ - try - { - harvestedCount = (int)_getCount.Invoke(null, null); - } - catch (Exception ex) - { - LogExceptionOnce( - "getcount-after-start", - "GetCount after StartGettingEntries failed.", - ex - ); - // Retain the previous count. - } - } - - object entryInstance = Activator.CreateInstance(_logEntryType); - object[] invokeArgs = new object[2]; - invokeArgs[1] = entryInstance; - for (int j = 0; j < harvestedCount; j++) - { - invokeArgs[0] = j; - try - { - _getEntryInternal.Invoke(null, invokeArgs); - } - catch (Exception ex) - { - LogExceptionOnce( - "getentry", - $"GetEntryInternal invocation failed at index {j}.", - ex - ); - continue; - } - - string message; - try - { - message = _messageField.GetValue(entryInstance) as string; - } - catch (Exception ex) - { - LogExceptionOnce( - "getmessage", - $"LogEntry.message read failed at index {j}.", - ex - ); - continue; - } - - if (BaseCallLogMessageParser.IsDiagnosticCandidate(message)) - { - lines.Add(message); - } - } - } - catch (Exception ex) - { - LogExceptionOnce("harvest", "Harvest loop failed.", ex); - } - finally - { - try - { - _endGettingEntries.Invoke(null, null); - } - catch (Exception ex) - { - LogExceptionOnce("end", "EndGettingEntries invocation failed.", ex); - } - } - - harvested = true; - try - { - return BaseCallLogMessageParser.Aggregate(lines); - } - catch (Exception ex) - { - LogExceptionOnce( - "aggregate-logentries", - "Aggregating LogEntries lines failed.", - ex - ); - return new Dictionary(StringComparer.Ordinal); - } - } - - // Apply each assembly's own latest report, including empty batches that retire it. private static void ApplyCompilerMessageDrain( Dictionary> drained ) @@ -757,12 +474,7 @@ Dictionary> drained } } - /// - /// Hint the harvester that something external changed (e.g., a settings toggle) and the - /// next polled tick should treat the console as fresh. Cheaper than a synchronous - /// when the caller is on a thread / context that may not be safe - /// to do reflection from. - /// + /// Schedules a rescan after compilation and asset imports finish. public static void RequestRescan() { ScheduleRescanWhenIdle(); @@ -770,22 +482,7 @@ public static void RequestRescan() private static void Tick() { - /* - Settings invalidation is observed even when the optional LogEntries bridge is - unavailable. Asset loading and rescans remain on the idle editor main thread. - */ - if (!IsAvailable) - { - return; - } - - /* - Defensive belt: never reflect into LogEntries while a compile or asset-import is - running. Even though RescanNow() itself bails on this state, we don't want to even - call GetCount(); the lock contention is the source of the freeze, and GetCount - touches the same buffer. - */ - if (EditorApplication.isCompiling || EditorApplication.isUpdating) + if (!IsAvailable || EditorApplication.isCompiling || EditorApplication.isUpdating) { return; } @@ -800,36 +497,6 @@ touches the same buffer. _lastTickTime = now; if (_lastSettingsRevision != DxMessagingSettings.SettingsRevision) - { - RescanNow(); - return; - } - if (_logEntriesDisabled) - { - return; - } - DxMessagingSettings settings = TryLoadSettings(); - if ( - settings == null - || !settings._baseCallCheckEnabled - || !settings._useConsoleBridge - ) - { - return; - } - - int currentCount; - try - { - currentCount = (int)_getCount.Invoke(null, null); - } - catch (Exception ex) - { - LogExceptionOnce("tick-count", "GetCount during Tick failed.", ex); - return; - } - - if (currentCount != _lastSeenCount) { RescanNow(); } @@ -846,38 +513,41 @@ CompilerMessage[] messages ) { /* - CRITICAL: this fires for EVERY assembly compiled (10s of times per build). Running - RescanNow synchronously here invokes LogEntries reflection while OTHER assemblies - are still compiling; the compiler holds its log-buffer lock and our reflection - call blocks waiting for it. Combined with AssetDatabase touches inside RescanNow, - this caused permanent script-compilation freezes on Unity startup. - We DO parse the per-assembly CompilerMessage payload here (cheap, pure-CPU work, - no AssetDatabase / LogEntries contact) and stash it in the cross-thread channel - without checking settings here. The settings gate requires AssetDatabase access, so - RescanNow applies it later after DrainScheduledRescan has requeued until Unity is - idle; if the bridge is disabled, RescanNow clears this pending buffer. This is the - primary bridge data path on Unity 2021, where Roslyn-analyzer warnings DO arrive in - CompilerMessage[] but do NOT reliably appear in the LogEntries store. + Each assembly supplies its own messages. Parse those messages here and defer + the settings check and report update until Unity is idle. */ try { if (!string.IsNullOrEmpty(assemblyPath) && messages != null) { - List lines = null; + Dictionary aggregated = new(StringComparer.Ordinal); foreach (CompilerMessage compilerMessage in messages) { string body = compilerMessage.message; - if (!BaseCallLogMessageParser.IsDiagnosticCandidate(body)) + if ( + !BaseCallLogMessageParser.IsDiagnosticCandidate(body) + || BaseCallLogMessageParser.ParseLine(body) is not ParsedEntry entry + ) { continue; } - lines ??= new List(); - lines.Add(body); - } - Dictionary aggregated = lines is null - ? new Dictionary(StringComparer.Ordinal) - : BaseCallLogMessageParser.Aggregate(lines); + if ( + string.IsNullOrEmpty(entry.FilePath) + && !string.IsNullOrEmpty(compilerMessage.file) + ) + { + entry = new ParsedEntry( + entry.DiagnosticId, + entry.TypeFullName, + entry.MethodName, + compilerMessage.file, + Math.Max(0, compilerMessage.line) + ); + } + + BaseCallLogMessageParser.AddEntry(aggregated, entry); + } lock (_compilationFeedLock) { @@ -969,49 +639,6 @@ exist yet (fresh project, first compile), the harvester treats the snapshot as } } - private static MethodInfo SafeGetStaticMethod(Type type, string name) - { - try - { - return type.GetMethod(name, BindingFlags.Public | BindingFlags.Static); - } - catch (Exception ex) - { - LogExceptionOnce( - $"resolve-{name}", - $"Failed to resolve static method '{name}' on {type.FullName}.", - ex - ); - return null; - } - } - - private static FieldInfo SafeGetInstanceField(Type type, string name) - { - try - { - return type.GetField(name, BindingFlags.Public | BindingFlags.Instance); - } - catch (Exception ex) - { - LogExceptionOnce( - $"resolve-field-{name}", - $"Failed to resolve instance field '{name}' on {type.FullName}.", - ex - ); - return null; - } - } - - private static void LogOnce(string key, string message) - { - if (!AlreadyWarned.Add(key)) - { - return; - } - Debug.LogWarning($"[DxMessaging] {message}"); - } - private static void LogExceptionOnce(string key, string message, Exception exception) { if (!AlreadyWarned.Add(key)) diff --git a/Editor/CustomEditors/MessageAwareComponentInspectorOverlay.cs b/Editor/CustomEditors/MessageAwareComponentInspectorOverlay.cs index 0f75fa26a..9e4f1158c 100644 --- a/Editor/CustomEditors/MessageAwareComponentInspectorOverlay.cs +++ b/Editor/CustomEditors/MessageAwareComponentInspectorOverlay.cs @@ -18,9 +18,8 @@ namespace DxMessaging.Editor.CustomEditors /// The package-owned fallback editor hosts the UI Toolkit warning view for subclasses without /// a more specific user editor. This header hook remains for user-defined custom editors, so /// they can keep their own Inspector body while still seeing DxMessaging base-call warnings. - /// The overlay reads its data from (which reflects - /// directly into Unity's UnityEditor.LogEntries console store) and from - /// (project-wide ignore list and master toggle). + /// The overlay reads diagnostics from and applies + /// the project-wide ignore list and master toggle from . /// /// /// Layout/Repaint control-count invariant. When the overlay renders from inside an diff --git a/Editor/Settings/DxMessagingSettings.cs b/Editor/Settings/DxMessagingSettings.cs index 79ec54c58..7926d13f3 100644 --- a/Editor/Settings/DxMessagingSettings.cs +++ b/Editor/Settings/DxMessagingSettings.cs @@ -212,9 +212,8 @@ setter is safe to invoke from any editor context (OnValidate, button click, } /// - /// Opt-in toggle for the legacy console-scrape bridge that augments the IL-reflection - /// scanner's snapshot with warnings harvested from UnityEditor.LogEntries and from - /// CompilationPipeline.assemblyCompilationFinished. + /// Adds base-call warnings from CompilationPipeline.assemblyCompilationFinished + /// to the IL scanner's snapshot when enabled. /// /// /// @@ -225,10 +224,8 @@ setter is safe to invoke from any editor context (OnValidate, button click, /// Unity 2021 cache hits, incremental compiles, and arbitrary domain-reload sequences. /// /// - /// The legacy bridge predates the IL scanner and was the source of the intermittent - /// "missing warnings" bug on Unity 2021. Enable it ONLY if you want the union of both - /// data sources -- for example, to surface a regression in the IL byte-walker that is - /// already correctly captured by the compile-time analyzer's console output. + /// Unity sends the warnings for compilations observed in this Editor session. + /// The property and serialized setting retain their original names for compatibility. /// /// /// Toggling this property is observable via a deferred diff --git a/Editor/Settings/DxMessagingSettingsProvider.cs b/Editor/Settings/DxMessagingSettingsProvider.cs index e4d7decba..4bba746c1 100644 --- a/Editor/Settings/DxMessagingSettingsProvider.cs +++ b/Editor/Settings/DxMessagingSettingsProvider.cs @@ -42,13 +42,13 @@ public sealed class DxMessagingSettingsProvider : SettingsProvider "Disable the warning shown when Enter Play Mode Options skips domain reload."; private const string InspectorChecksSectionTitle = "Inspector Checks"; private const string InspectorChecksSectionDescription = - "Controls Inspector warnings and the optional console bridge for base-call diagnostics."; + "Controls Inspector warnings and the optional compiler feed for base-call diagnostics."; private const string BaseCallCheckEnabledLabel = "Base-Call Check Enabled"; private const string BaseCallCheckEnabledTooltip = "Show Inspector warnings when MessageAwareComponent overrides omit base.RegisterMessageHandlers()."; - private const string UseConsoleBridgeLabel = "Use Console Bridge"; + private const string UseConsoleBridgeLabel = "Include Compiler Warnings"; private const string UseConsoleBridgeTooltip = - "Also harvest compiler/analyzer warnings from Unity's console in addition to the IL scanner."; + "Add base-call warnings from compilations observed in this Editor session."; private const string BaseCallIgnoredTypesLabel = "Ignored Base-Call Types"; private const string BaseCallIgnoredTypesTooltip = "Fully-qualified MessageAwareComponent type names excluded from the Inspector overlay and base-call analyzer."; @@ -455,6 +455,7 @@ public static SettingsProvider CreateDxMessagingSettingsProvider() InspectorChecksSectionTitle, BaseCallCheckEnabledLabel, UseConsoleBridgeLabel, + "Use Console Bridge", BaseCallIgnoredTypesLabel, "Wallstop", "Wallstop Studios", diff --git a/Editor/Windows/DxMessagingFlowGraphWindow.cs b/Editor/Windows/DxMessagingFlowGraphWindow.cs index 03a04d346..a5a7c2981 100644 --- a/Editor/Windows/DxMessagingFlowGraphWindow.cs +++ b/Editor/Windows/DxMessagingFlowGraphWindow.cs @@ -3379,7 +3379,11 @@ Label zoomLabel Vector2 viewportSize = Vector2.zero; void ApplyTransform() { - graphContent.style.translate = new Translate(canvasState.Pan.x, canvasState.Pan.y); + graphContent.style.translate = new Translate( + canvasState.Pan.x, + canvasState.Pan.y, + 0f + ); graphContent.style.scale = new Scale( new Vector3(canvasState.Zoom, canvasState.Zoom, 1f) ); diff --git a/README.md b/README.md index e61494d2d..d561c864d 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-f4a836.svg)](LICENSE.md)
[![OpenUPM](https://img.shields.io/npm/v/com.wallstop-studios.dxmessaging?label=OpenUPM®istry_uri=https://package.openupm.com)](https://openupm.com/packages/com.wallstop-studios.dxmessaging/)
[![Version](https://img.shields.io/npm/v/com.wallstop-studios.dxmessaging.svg)](https://www.npmjs.com/package/com.wallstop-studios.dxmessaging)
-[![Performance: Standalone (IL2CPP)]()](docs/architecture/performance.md)
+[![Performance: Standalone (IL2CPP)]()](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/)
[![Markdown Link Validity](https://github.com/Ambiguous-Interactive/DxMessaging/actions/workflows/markdown-link-validity.yml/badge.svg)](https://github.com/Ambiguous-Interactive/DxMessaging/actions/workflows/markdown-link-validity.yml) > **AI Assistance Disclosure:** @@ -37,7 +37,7 @@ openupm add com.wallstop-studios.dxmessaging The core taxonomy is small: **Untargeted** announcements, **Targeted** commands, and **Broadcast** facts from a source. Diagnostics mark them blue, purple, and green, respectively, and reserve red for problems. Message Monitor shows recent emissions and filters, Flow Graph shows loaded-scene `MessagingComponent` topology and trace evidence, and the Inspector overlay catches `MessageAwareComponent` lifecycle mistakes. Use bus logs or counters for direct bus/token registrations outside those components. -See the [Install Guide](docs/getting-started/install.md) for Git URL, scoped registry, and release tarball options. +See the [Install Guide](https://ambiguous-interactive.github.io/DxMessaging/getting-started/install/) for Git URL, scoped registry, and release tarball options. ## Table of Contents @@ -179,9 +179,9 @@ flowchart TD > - **Using Broadcast when you need Targeted** -- Broadcasts have no recipient, just an origin. Use Targeted when commanding a specific entity. > - **Missing `[Dx*Message]` attribute** -- The source generator won't process the struct without the marker attribute. > -> 📖 See [Troubleshooting](docs/reference/troubleshooting.md) for solutions to these and other issues. +> 📖 See [Troubleshooting](https://ambiguous-interactive.github.io/DxMessaging/reference/troubleshooting/) for solutions to these and other issues. -**Want more depth?** See the full [Mental Model documentation](docs/concepts/mental-model.md) for detailed examples, lifecycle patterns, and edge cases. +**Want more depth?** See the full [Mental Model documentation](https://ambiguous-interactive.github.io/DxMessaging/concepts/mental-model/) for detailed examples, lifecycle patterns, and edge cases. **Ready to code?** Jump to [Quick Start](#quick-start) to send your first message! @@ -191,7 +191,7 @@ flowchart TD -**New to messaging?** Start with the [Visual Guide](docs/getting-started/visual-guide.md) for a beginner-friendly introduction! +**New to messaging?** Start with the [Visual Guide](https://ambiguous-interactive.github.io/DxMessaging/getting-started/visual-guide/) for a beginner-friendly introduction! ### 1. Install @@ -208,13 +208,13 @@ openupm add com.wallstop-studios.dxmessaging https://github.com/Ambiguous-Interactive/DxMessaging.git ``` -See the [Install Guide](docs/getting-started/install.md) for all options including NPM scoped registries and local tarballs. +See the [Install Guide](https://ambiguous-interactive.github.io/DxMessaging/getting-started/install/) for all options including NPM scoped registries and local tarballs. ### 2. Define a Damage Command > **Handler version:** These examples use the 4.0 `in` signature. With a 3.x package, use > `ref DamageRequested message` for the receiver callback parameter instead. Keep the registration -> and emission calls unchanged. See the [4.0 migration guide](docs/guides/migration-guide.md#migrating-to-400). +> and emission calls unchanged. See the [4.0 migration guide](https://ambiguous-interactive.github.io/DxMessaging/guides/migration-guide/#migrating-to-400). ```csharp using DxMessaging.Core.Attributes; @@ -251,7 +251,7 @@ public sealed class DamageReceiver : MessageAwareComponent } ``` -> **Heads-up:** When you override `Awake`, `OnEnable`, `OnDisable`, `OnDestroy`, or `RegisterMessageHandlers`, call the base method first or handlers fail silently. See [DXMSG006](docs/reference/analyzers.md#dxmsg006-missing-base-call). +> **Heads-up:** When you override `Awake`, `OnEnable`, `OnDisable`, `OnDestroy`, or `RegisterMessageHandlers`, call the base method first or handlers fail silently. See [DXMSG006](https://ambiguous-interactive.github.io/DxMessaging/reference/analyzers/#dxmsg006-missing-base-call). ### 4. Add a Hazard @@ -276,10 +276,10 @@ On the hazard GameObject, enable **Is Trigger** on its collider and add a kinema GameObject. The hazard targets that exact object without knowing its concrete type. Registration cleanup follows the receiver's Unity lifecycle. -Follow the [Play Mode walkthrough](docs/getting-started/quick-start.md#try-it-in-play-mode) to +Follow the [Play Mode walkthrough](https://ambiguous-interactive.github.io/DxMessaging/getting-started/quick-start/#try-it-in-play-mode) to move the hazard into the target and find `Health: 75` in the Console. -**Stuck?** See [Troubleshooting](docs/reference/troubleshooting.md) or [FAQ](docs/reference/faq.md) +**Stuck?** See [Troubleshooting](https://ambiguous-interactive.github.io/DxMessaging/reference/troubleshooting/) or [FAQ](https://ambiguous-interactive.github.io/DxMessaging/reference/faq/) --- @@ -332,8 +332,8 @@ public sealed class PlayerService : IDisposable Call `Initialize()` when the service starts. Have the scope that owns the service call `Dispose()` when it ends. To start this service through a container, use the adapter for -[Zenject](docs/integrations/zenject.md#start-the-readme-service) or -[VContainer](docs/integrations/vcontainer.md#start-the-readme-service). For Reflex, call +[Zenject](https://ambiguous-interactive.github.io/DxMessaging/integrations/zenject/#start-the-readme-service) or +[VContainer](https://ambiguous-interactive.github.io/DxMessaging/integrations/vcontainer/#start-the-readme-service). For Reflex, call `Initialize()` explicitly from your scene bootstrap. ### Why use DI + Messaging? @@ -350,14 +350,14 @@ when it ends. To start this service through a container, use the adapter for ##### Get started -- [Zenject Integration Guide](docs/integrations/zenject.md) -- Complete setup with examples -- [VContainer Integration Guide](docs/integrations/vcontainer.md) -- Scoped buses for scene isolation -- [Reflex Integration Guide](docs/integrations/reflex.md) -- Minimal, lightweight patterns +- [Zenject Integration Guide](https://ambiguous-interactive.github.io/DxMessaging/integrations/zenject/) -- Complete setup with examples +- [VContainer Integration Guide](https://ambiguous-interactive.github.io/DxMessaging/integrations/vcontainer/) -- Scoped buses for scene isolation +- [Reflex Integration Guide](https://ambiguous-interactive.github.io/DxMessaging/integrations/reflex/) -- Minimal, lightweight patterns ##### Core DI concepts -- [Runtime Configuration](docs/advanced/runtime-configuration.md) -- Setting message buses at runtime, re-binding registrations -- [Message Bus Providers](docs/advanced/message-bus-providers.md) -- Provider system for design-time and runtime bus configuration +- [Runtime Configuration](https://ambiguous-interactive.github.io/DxMessaging/advanced/runtime-configuration/) -- Setting message buses at runtime, re-binding registrations +- [Message Bus Providers](https://ambiguous-interactive.github.io/DxMessaging/advanced/message-bus-providers/) -- Provider system for design-time and runtime bus configuration **Not using DI?** No problem. DxMessaging works standalone with zero dependencies. @@ -385,7 +385,7 @@ when it ends. To start this service through a container, use the adapter for ### Maybe Use DxMessaging (Start Small) -- **Existing large codebase** - Migrate incrementally: start with new features, refactor old code gradually (see [Migration Guide](docs/guides/migration-guide.md)) +- **Existing large codebase** - Migrate incrementally: start with new features, refactor old code gradually (see [Migration Guide](https://ambiguous-interactive.github.io/DxMessaging/guides/migration-guide/)) - **Small team learning** - Try it for one system (e.g., achievements) before going all-in - **Mid-size projects (5-20k lines)** - Evaluate after trying it for one complex interaction (e.g., combat or scene transitions) @@ -406,9 +406,9 @@ flowchart TD Q3 -->|NO| A4[" Keep it simple"] ``` -**Rule of thumb:** If decoupling, lifecycle leaks, or handler-ordering bugs match what you're hitting today, DxMessaging fits. If none of those describe your project, start with the [Visual Guide](docs/getting-started/visual-guide.md) or stick with simpler patterns. +**Rule of thumb:** If decoupling, lifecycle leaks, or handler-ordering bugs match what you're hitting today, DxMessaging fits. If none of those describe your project, start with the [Visual Guide](https://ambiguous-interactive.github.io/DxMessaging/getting-started/visual-guide/) or stick with simpler patterns. -Looking for hard numbers? See the Standalone IL2CPP dispatch and library-comparison [Performance Benchmarks](docs/architecture/performance.md). +Looking for hard numbers? See the Standalone IL2CPP dispatch and library-comparison [Performance Benchmarks](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/). ## Why DxMessaging @@ -753,7 +753,7 @@ and any `MessageAwareComponent` subclass for base-call warning surfaces. **No more:** Setting 50 breakpoints and stepping through code for 30 minutes. -See [Diagnostics](docs/guides/diagnostics.md) for the current editor tooling and +See [Diagnostics](https://ambiguous-interactive.github.io/DxMessaging/guides/diagnostics/) for the current editor tooling and trace-path semantics. The [Diagnostics Tooling Exerciser](Samples~/Diagnostics%20Tooling%20Exerciser/README.md) sample imports a deterministic scene that drives Message Monitor, Flow Graph, @@ -813,25 +813,25 @@ Unity messaging tests on the main thread and avoid concurrent access to that sha ### Learn -- **New here?** Start with [Getting Started Guide](docs/getting-started/getting-started.md) -- **Want patterns?** See [Common Patterns](docs/guides/patterns.md) -- **Deep dive?** Read [Design & Architecture](docs/architecture/design-and-architecture.md) +- **New here?** Start with [Getting Started Guide](https://ambiguous-interactive.github.io/DxMessaging/getting-started/getting-started/) +- **Want patterns?** See [Common Patterns](https://ambiguous-interactive.github.io/DxMessaging/guides/patterns/) +- **Deep dive?** Read [Design & Architecture](https://ambiguous-interactive.github.io/DxMessaging/architecture/design-and-architecture/) ### Core Concepts -- [Overview](docs/getting-started/overview.md) -- What and why -- [Quick Start](docs/getting-started/quick-start.md) -- Define, register, and emit your first message -- [Message Types](docs/concepts/message-types.md) -- When to use Untargeted/Targeted/Broadcast -- [Interceptors & Ordering](docs/concepts/interceptors-and-ordering.md) -- Control execution flow -- [Listening Patterns](docs/concepts/listening-patterns.md) -- All the ways to receive messages +- [Overview](https://ambiguous-interactive.github.io/DxMessaging/getting-started/overview/) -- What and why +- [Quick Start](https://ambiguous-interactive.github.io/DxMessaging/getting-started/quick-start/) -- Define, register, and emit your first message +- [Message Types](https://ambiguous-interactive.github.io/DxMessaging/concepts/message-types/) -- When to use Untargeted/Targeted/Broadcast +- [Interceptors & Ordering](https://ambiguous-interactive.github.io/DxMessaging/concepts/interceptors-and-ordering/) -- Control execution flow +- [Listening Patterns](https://ambiguous-interactive.github.io/DxMessaging/concepts/listening-patterns/) -- All the ways to receive messages ### Unity Integration -- [Unity Integration](docs/guides/unity-integration.md) -- MessagingComponent deep dive +- [Unity Integration](https://ambiguous-interactive.github.io/DxMessaging/guides/unity-integration/) -- MessagingComponent deep dive - [Subscription Ownership](https://github.com/Ambiguous-Interactive/DxMessaging/blob/master/docs/guides/subscription-ownership.md) -- groups, source moves, and static handlers with explicit state (4.0.0) -- [Targeting & Context](docs/concepts/targeting-and-context.md) -- GameObject vs Component -- [Diagnostics](docs/guides/diagnostics.md) -- editor tools, traces, and debugging -- [Memory Reclamation](docs/guides/memory-reclamation.md) -- idle eviction, explicit Trim, and tuning the runtime settings asset +- [Targeting & Context](https://ambiguous-interactive.github.io/DxMessaging/concepts/targeting-and-context/) -- GameObject vs Component +- [Diagnostics](https://ambiguous-interactive.github.io/DxMessaging/guides/diagnostics/) -- editor tools, traces, and debugging +- [Memory Reclamation](https://ambiguous-interactive.github.io/DxMessaging/guides/memory-reclamation/) -- idle eviction, explicit Trim, and tuning the runtime settings asset Important: Inheritance with MessageAwareComponent @@ -845,14 +845,14 @@ Important: Inheritance with MessageAwareComponent DxMessaging works standalone (zero dependencies) or with any major DI framework. For detailed setup guides and code examples: -- **[Zenject Integration Guide](docs/integrations/zenject.md)** -- Full-featured DI with extensive Unity support -- **[VContainer Integration Guide](docs/integrations/vcontainer.md)** -- Lightweight DI with scoped lifetimes for scene isolation -- **[Reflex Integration Guide](docs/integrations/reflex.md)** -- Minimal API, high-performance DI +- **[Zenject Integration Guide](https://ambiguous-interactive.github.io/DxMessaging/integrations/zenject/)** -- Full-featured DI with extensive Unity support +- **[VContainer Integration Guide](https://ambiguous-interactive.github.io/DxMessaging/integrations/vcontainer/)** -- Lightweight DI with scoped lifetimes for scene isolation +- **[Reflex Integration Guide](https://ambiguous-interactive.github.io/DxMessaging/integrations/reflex/)** -- Minimal API, high-performance DI #### Core DI concepts -- **[Runtime Configuration](docs/advanced/runtime-configuration.md)** -- Setting and overriding message buses at runtime, re-binding registrations -- **[Message Bus Providers](docs/advanced/message-bus-providers.md)** -- Provider system and MessageBusProviderHandle for flexible bus configuration +- **[Runtime Configuration](https://ambiguous-interactive.github.io/DxMessaging/advanced/runtime-configuration/)** -- Setting and overriding message buses at runtime, re-binding registrations +- **[Message Bus Providers](https://ambiguous-interactive.github.io/DxMessaging/advanced/message-bus-providers/)** -- Provider system and MessageBusProviderHandle for flexible bus configuration Each guide includes: @@ -865,18 +865,18 @@ See the [DI Compatible section](#dependency-injection-di-compatible) above for a ### Comparisons -- [Compare with Other Unity Messaging Frameworks](docs/architecture/comparisons.md) -- In-depth comparison with UniRx, MessagePipe, Zenject Signals, C# events, UnityEvents, and more -- [Scriptable Object Architecture (SOA) Compatibility](docs/guides/patterns.md#14-compatibility-with-scriptable-object-architecture-soa) -- Migration patterns and interoperability with SOA +- [Compare with Other Unity Messaging Frameworks](https://ambiguous-interactive.github.io/DxMessaging/architecture/comparisons/) -- In-depth comparison with UniRx, MessagePipe, Zenject Signals, C# events, UnityEvents, and more +- [Scriptable Object Architecture (SOA) Compatibility](https://ambiguous-interactive.github.io/DxMessaging/guides/patterns/#14-compatibility-with-scriptable-object-architecture-soa) -- Migration patterns and interoperability with SOA #### Quick Framework Comparison -| Framework | Best For | Key Strength | Unity Support | Learning Curve | -| ------------------- | --------------------------------- | ------------------------------------------------------------------------------------ | --------------- | -------------- | -| **DxMessaging** | Unity pub/sub with lifecycle mgmt | Visual diagnostics + control | Built for Unity | Moderate | -| **UniRx** | Complex event stream transforms | Reactive operators (LINQ) | Built for Unity | Easy | -| **MessagePipe** | High-performance DI messaging | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | Built for Unity | Steep | -| **Zenject Signals** | DI-integrated messaging | Zenject ecosystem | Built for Unity | Easy | -| **C# Events** | Simple, local communication | Minimal overhead | Native C# | Steepest | +| Framework | Best For | Key Strength | Unity Support | Learning Curve | +| ------------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------- | -------------- | +| **DxMessaging** | Unity pub/sub with lifecycle mgmt | Visual diagnostics + control | Built for Unity | Moderate | +| **UniRx** | Complex event stream transforms | Reactive operators (LINQ) | Built for Unity | Easy | +| **MessagePipe** | High-performance DI messaging | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | Built for Unity | Steep | +| **Zenject Signals** | DI-integrated messaging | Zenject ecosystem | Built for Unity | Easy | +| **C# Events** | Simple, local communication | Minimal overhead | Native C# | Steepest | ##### Choose DxMessaging when you want @@ -889,11 +889,11 @@ See the [DI Compatible section](#dependency-injection-di-compatible) above for a - Post-processing stage (analytics, logging after handlers) - No dependencies, plug-and-play setup -See [full comparison](docs/architecture/comparisons.md) for detailed analysis with code examples, performance benchmarks, and decision guides. +See [full comparison](https://ambiguous-interactive.github.io/DxMessaging/architecture/comparisons/) for detailed analysis with code examples, performance benchmarks, and decision guides. > **📦 Using Scriptable Object Architecture (SOA)?** > -> DxMessaging can work alongside or replace SOA patterns. See [SOA Compatibility Guide](docs/guides/patterns.md#14-compatibility-with-scriptable-object-architecture-soa) for: +> DxMessaging can work alongside or replace SOA patterns. See [SOA Compatibility Guide](https://ambiguous-interactive.github.io/DxMessaging/guides/patterns/#14-compatibility-with-scriptable-object-architecture-soa) for: > > - Fair comparison of SOA vs. DxMessaging > - Migration patterns from GameEvent/FloatVariable to DxMessaging @@ -902,17 +902,17 @@ See [full comparison](docs/architecture/comparisons.md) for detailed analysis wi ### Reference -- [Install Guide](docs/getting-started/install.md) -- All install options (OpenUPM, Git URL, scoped registry, tarball) -- [Glossary](docs/reference/glossary.md) -- All terms explained in plain English -- [Quick Reference](docs/reference/quick-reference.md) -- Cheat sheet -- [API Reference](docs/reference/reference.md) -- Complete API -- [Helpers](docs/reference/helpers.md) -- Source generators and utilities -- [FAQ](docs/reference/faq.md) -- Common questions -- [Troubleshooting](docs/reference/troubleshooting.md) +- [Install Guide](https://ambiguous-interactive.github.io/DxMessaging/getting-started/install/) -- All install options (OpenUPM, Git URL, scoped registry, tarball) +- [Glossary](https://ambiguous-interactive.github.io/DxMessaging/reference/glossary/) -- All terms explained in plain English +- [Quick Reference](https://ambiguous-interactive.github.io/DxMessaging/reference/quick-reference/) -- Cheat sheet +- [API Reference](https://ambiguous-interactive.github.io/DxMessaging/reference/reference/) -- Complete API +- [Helpers](https://ambiguous-interactive.github.io/DxMessaging/reference/helpers/) -- Source generators and utilities +- [FAQ](https://ambiguous-interactive.github.io/DxMessaging/reference/faq/) -- Common questions +- [Troubleshooting](https://ambiguous-interactive.github.io/DxMessaging/reference/troubleshooting/) ### Full Documentation -Browse all docs: [Documentation Hub](docs/getting-started/index.md) +Browse all docs: [Documentation Hub](https://ambiguous-interactive.github.io/DxMessaging/getting-started/) ## Real-World Examples @@ -961,68 +961,70 @@ public class AchievementTracker : MessageAwareComponent { ## Performance -- **Zero GC allocations** for ordinary typed steady-state struct dispatch; stack-trace diagnostics and struct global accept-all dispatch allocate ([details](docs/reference/faq.md#does-dxmessaging-allocate-memory-is-dispatch-zero-gc)) +- **Zero GC allocations** for ordinary typed steady-state struct dispatch; stack-trace diagnostics and struct global accept-all dispatch allocate ([details](https://ambiguous-interactive.github.io/DxMessaging/reference/faq/#does-dxmessaging-allocate-memory-is-dispatch-zero-gc)) - **CI-generated time/op and cross-library results** for the published runner - **Type-indexed caching** for O(1) lookups - **Optimized for hot paths** with aggressive inlining -See [Design & Architecture](docs/architecture/design-and-architecture.md#performance-optimizations) for details. +See [Design & Architecture](https://ambiguous-interactive.github.io/DxMessaging/architecture/design-and-architecture/#performance-optimizations) for details. -For live, CI-generated Standalone IL2CPP dispatch tables and a cross-library comparison matrix, see [Performance Benchmarks](docs/architecture/performance.md). Those numbers are auto-generated on every push with the .NET Standard 2.1 profile and a Release build; the comparison table below is a static summary, not the live data. +See [Performance Benchmarks](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/) for Standalone IL2CPP dispatch and comparisons. The workflow measures Release builds using the .NET Standard 2.1 profile. Nightly dispatches and manual runs on the default branch can refresh the published tables. ## Comparison Table ### Comparison with Unity Messaging Frameworks -| Feature | DxMessaging | UniRx | MessagePipe | Zenject Signals | -| ------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| **Unity Compatibility** | Built for Unity | Built for Unity | Built for Unity | Built for Unity | -| **Decoupling** | Full | Full | Full | Full | -| **Lifecycle Safety** | Auto | Manual | Manual | DI-managed | -| **Execution Order** | Priority | None | None | None | -| **Type Safety** | Strong | Strong | Strong | Strong | -| **Visual Diagnostics** | Built-in | No | No | No | -| **GameObject Targeting** | Yes | No | No | No | -| **Global Observers** | Yes | No | No | No | -| **Interceptors** | Pipeline | No | Filters | No | -| **Post-Processing** | Dedicated | No | Filters | No | -| **Stream Operators** | No | Extensive | No | With UniRx | -| **Performance** | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | -| **Dependencies** | None | UniTask | None | Zenject | +| Feature | DxMessaging | UniRx | MessagePipe | Zenject Signals | +| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| **Unity Compatibility** | Built for Unity | Built for Unity | Built for Unity | Built for Unity | +| **Decoupling** | Full | Full | Full | Full | +| **Lifecycle Safety** | Auto | Manual | Manual | DI-managed | +| **Execution Order** | Priority | None | None | None | +| **Type Safety** | Strong | Strong | Strong | Strong | +| **Visual Diagnostics** | Built-in | No | No | No | +| **GameObject Targeting** | Yes | No | No | No | +| **Global Observers** | Yes | No | No | No | +| **Interceptors** | Pipeline | No | Filters | No | +| **Post-Processing** | Dedicated | No | Filters | No | +| **Stream Operators** | No | Extensive | No | With UniRx | +| **Performance** | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | +| **Dependencies** | None | UniTask | None | Zenject | ### Comparison with Traditional Approaches -| Feature | DxMessaging | C# Events | UnityEvents | Static Event Bus | -| ---------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| **Decoupling** | Full | Tight | Hidden | Yes | -| **Lifecycle Safety** | Auto | Manual | Unity-only | Manual | -| **Execution Order** | Priority | Undefined | Undefined | Undefined | -| **Type Safety** | Strong | Strong | Weak | Weak | -| **Context (Who/What)** | Rich | None | None | None | -| **Interception** | Yes | No | No | No | -| **Observability** | Built-in | No | No | No | -| **Performance** | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | [Current CI results](docs/architecture/performance.md#latest-ci-performance-results) | +| Feature | DxMessaging | C# Events | UnityEvents | Static Event Bus | +| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| **Decoupling** | Full | Tight | Hidden | Yes | +| **Lifecycle Safety** | Auto | Manual | Unity-only | Manual | +| **Execution Order** | Priority | Undefined | Undefined | Undefined | +| **Type Safety** | Strong | Strong | Weak | Weak | +| **Context (Who/What)** | Rich | None | None | None | +| **Interception** | Yes | No | No | No | +| **Observability** | Built-in | No | No | No | +| **Performance** | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | [Current CI results](https://ambiguous-interactive.github.io/DxMessaging/architecture/performance/#latest-ci-performance-results) | ## Samples -Import samples from Package Manager: +For a UPM install, select **DxMessaging** in Package Manager and use its **Samples** tab. +For a classic `.unitypackage` import, open the samples under `Assets/WallstopStudios/DxMessaging/Samples`. - **[Mini Combat](Samples~/Mini%20Combat/README.md)** -- Simple combat with Heal/Damage messages - **[UI Buttons + Inspector](Samples~/UI%20Buttons%20%2B%20Inspector/README.md)** -- Interactive diagnostics demo - **[Diagnostics Tooling Exerciser](Samples~/Diagnostics%20Tooling%20Exerciser/README.md)** -- Deterministic scene for Message Monitor, Flow Graph, Inspector diagnostics, and Project Settings +- **[Dependency Injection](Samples~/DI/README.md)** -- Zenject, VContainer, and Reflex setup and disposal examples ## Requirements - Unity 2021.3 or later - .NET Standard 2.1 -- Works with all render pipelines (URP, HDRP, Built-in) +- Built-In Render Pipeline, URP, or HDRP -See [Compatibility](docs/reference/compatibility.md) for Unity details and the optional -[plain .NET source build](docs/reference/compatibility.md#plain-net-runtime). +See [Compatibility](https://ambiguous-interactive.github.io/DxMessaging/reference/compatibility/) for Unity details and the optional +[plain .NET source build](https://ambiguous-interactive.github.io/DxMessaging/reference/compatibility/#plain-net-runtime). ## Contributing -Contributions welcome! See [Contributing](CONTRIBUTING.md). +Contributions welcome! See [Contributing](https://github.com/Ambiguous-Interactive/DxMessaging/blob/master/CONTRIBUTING.md). ## License @@ -1041,13 +1043,13 @@ Created and maintained by [wallstop studios](https://wallstopstudios.com) ## AI Agent Integration -DxMessaging publishes machine-readable context for AI agents through [llms.txt](llms.txt), following the [llmstxt.org](https://llmstxt.org/) standard. The file collects the project overview, API surface, conventions, and links into one document. +DxMessaging publishes machine-readable context for AI agents through [llms.txt](https://github.com/Ambiguous-Interactive/DxMessaging/blob/master/llms.txt), following the [llmstxt.org](https://llmstxt.org/) standard. The file collects the project overview, API surface, conventions, and links into one document. ### For AI Agents -- **[llms.txt](llms.txt)** -- Complete project overview, API reference, and context in a single file -- **[Repository Guidelines](.llm/context.md)** -- Coding standards and development workflows -- **[AI Agent Skills](.llm/skills/)** -- 35+ specialized skills covering documentation, testing, GitHub Actions, and more +- **[llms.txt](https://github.com/Ambiguous-Interactive/DxMessaging/blob/master/llms.txt)** -- Complete project overview, API reference, and context in a single file +- **[Repository Guidelines](https://github.com/Ambiguous-Interactive/DxMessaging/blob/master/.llm/context.md)** -- Coding standards and development workflows +- **[AI Agent Skills](https://github.com/Ambiguous-Interactive/DxMessaging/tree/master/.llm/skills/)** -- 35+ specialized skills covering documentation, testing, GitHub Actions, and more The `llms.txt` file is automatically updated via CI/CD to stay current with project changes. It includes: diff --git a/Samples~/DI/README.md b/Samples~/DI/README.md index 784fa1e03..9096c4c90 100644 --- a/Samples~/DI/README.md +++ b/Samples~/DI/README.md @@ -9,11 +9,12 @@ These snippets illustrate how to consume `IMessageRegistrationBuilder` inside co - `ZENJECT_PRESENT` - `VCONTAINER_PRESENT` - `REFLEX_PRESENT` -1. Import the sample folder you need into your Unity project (`Assets/Samples/DxMessaging/*`). +1. For a UPM install, use **DxMessaging > Samples** in Package Manager to import **Dependency Injection**. + For a classic asset package, find the examples under `Assets/WallstopStudios/DxMessaging/Samples/DI`. Each sample shows: -- Registering `IMessageRegistrationBuilder` via the provided shim under [Runtime/Unity/Integrations](../../Runtime/Unity/Integrations/). +- Registering `IMessageRegistrationBuilder` via the provided shim under [Runtime/Unity/Integrations](https://github.com/Ambiguous-Interactive/DxMessaging/tree/master/Runtime/Unity/Integrations). - Constructing a `MessageRegistrationLease` in a container-managed service. - Activating and disposing the lease through the container lifecycle. @@ -27,10 +28,10 @@ Each sample shows: 1. **Hook up one container** - **Zenject**: - - Add `DxMessagingRegistrationInstaller` (from [Runtime/Unity/Integrations](../../Runtime/Unity/Integrations/)) to your ProjectContext or scene installer list. + - Add `DxMessagingRegistrationInstaller` (from [Runtime/Unity/Integrations](https://github.com/Ambiguous-Interactive/DxMessaging/tree/master/Runtime/Unity/Integrations)) to your ProjectContext or scene installer list. - Drop [SampleInstaller.cs](./Zenject/SampleInstaller.cs) into your project and register it alongside other installers. When the scene runs, the installer resolves `IMessageRegistrationBuilder`, stages a `PlayerSpawned` listener, and activates via the Zenject lifecycle. - **VContainer**: - - Define `VCONTAINER_PRESENT` and reference the optional extension under [VContainerRegistrationExtensions.cs](../../Runtime/Unity/Integrations/VContainer/VContainerRegistrationExtensions.cs). + - Define `VCONTAINER_PRESENT` and reference the optional extension under [VContainerRegistrationExtensions.cs](https://github.com/Ambiguous-Interactive/DxMessaging/blob/master/Runtime/Unity/Integrations/VContainer/VContainerRegistrationExtensions.cs). - Add [SampleLifetimeScope.cs](./VContainer/SampleLifetimeScope.cs) to the scene (or derive from it). The scope registers one `IMessageBus`, the builder resolves that scoped bus, and the entry point injects the same bus for one `ScoreUpdated` emission per second. - **Reflex**: - Install Reflex, then enable `REFLEX_PRESENT` for the imported sample assembly. diff --git a/Samples~/Diagnostics Tooling Exerciser/README.md b/Samples~/Diagnostics Tooling Exerciser/README.md index 9589d9686..c1e4221dc 100644 --- a/Samples~/Diagnostics Tooling Exerciser/README.md +++ b/Samples~/Diagnostics Tooling Exerciser/README.md @@ -19,7 +19,9 @@ the package editor tools. ## Run It -1. Import **Diagnostics Tooling Exerciser** from the Package Manager Samples tab. +For a UPM install, use **DxMessaging > Samples** in Package Manager to import **Diagnostics Tooling Exerciser**. +For a classic asset package, find the scene under `Assets/WallstopStudios/DxMessaging/Samples`. + 1. Open `DiagnosticsToolingExerciser.unity`. 1. Follow the **DxMessaging Guided Tour** window that opens with the scene. It starts Play Mode, emits deterministic traffic, opens Message Monitor and Flow diff --git a/Samples~/Mini Combat/README.md b/Samples~/Mini Combat/README.md index 90918ff47..5cc159de9 100644 --- a/Samples~/Mini Combat/README.md +++ b/Samples~/Mini Combat/README.md @@ -4,9 +4,10 @@ Run one scene to compare untargeted, targeted, and broadcast messages in a small ## Run the sample -1. Open **Window > Package Manager**. -1. Select **DxMessaging**, then import **Mini Combat**. -1. Open `MiniCombat.unity` from the imported sample folder. +For a UPM install, use **DxMessaging > Samples** in Package Manager to import **Mini Combat**. +For a classic asset package, find the scene under `Assets/WallstopStudios/DxMessaging/Samples`. + +1. Open `MiniCombat.unity`. 1. Enter Play Mode. Watch the combat feed in the Game view and the gameplay output in the Console. The scene is already wired. `Boot` emits three messages after every listener has registered: diff --git a/Samples~/Mini Combat/Walkthrough.md b/Samples~/Mini Combat/Walkthrough.md index 53f50866e..1407d6441 100644 --- a/Samples~/Mini Combat/Walkthrough.md +++ b/Samples~/Mini Combat/Walkthrough.md @@ -76,5 +76,5 @@ If a message does not arrive: 1. Check that every overridden lifecycle method calls its base implementation. 1. Enable diagnostics and inspect Message Monitor or Flow Graph. -See [Listening Patterns](../../docs/concepts/listening-patterns.md) for across-all listeners +See [Listening Patterns](https://ambiguous-interactive.github.io/DxMessaging/concepts/listening-patterns/) for across-all listeners and post-processors. diff --git a/Samples~/UI Buttons + Inspector/README.md b/Samples~/UI Buttons + Inspector/README.md index 981c14209..f38f195ac 100644 --- a/Samples~/UI Buttons + Inspector/README.md +++ b/Samples~/UI Buttons + Inspector/README.md @@ -5,9 +5,10 @@ diagnostics. ## Run the sample -1. Open **Window > Package Manager**. -1. Select **DxMessaging**, then import **UI Buttons + Inspector**. -1. Open `UIButtonsInspector.unity` from the imported sample folder. +For a UPM install, use **DxMessaging > Samples** in Package Manager to import **UI Buttons + Inspector**. +For a classic asset package, find the scene under `Assets/WallstopStudios/DxMessaging/Samples`. + +1. Open `UIButtonsInspector.unity`. 1. Enter Play Mode. 1. Click **Emit Play** in the Game view and inspect the Console or the live fields on the `Message Observer` component. diff --git a/SourceGenerators/WallstopStudios.DxMessaging.Analyzer/WallstopStudios.DxMessaging.Analyzer.csproj b/SourceGenerators/WallstopStudios.DxMessaging.Analyzer/WallstopStudios.DxMessaging.Analyzer.csproj index 712a06f6b..5782b1ac1 100644 --- a/SourceGenerators/WallstopStudios.DxMessaging.Analyzer/WallstopStudios.DxMessaging.Analyzer.csproj +++ b/SourceGenerators/WallstopStudios.DxMessaging.Analyzer/WallstopStudios.DxMessaging.Analyzer.csproj @@ -2,12 +2,9 @@ + 3.8.0 WallstopStudios.DxMessaging.SourceGenerators WallstopStudios.DxMessaging.Analyzer diff --git a/SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators.Tests/BaseCallLogMessageParserTests.cs b/SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators.Tests/BaseCallLogMessageParserTests.cs index 260d43f9b..cfe65ebb9 100644 --- a/SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators.Tests/BaseCallLogMessageParserTests.cs +++ b/SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators.Tests/BaseCallLogMessageParserTests.cs @@ -63,7 +63,10 @@ public void ConsoleCandidateScreenPreservesParsedDiagnostics() foreach ((string id, string body) in diagnostics) { string prefixed = $"Assets/Sample/Player.cs(12,9): warning {id}: {body}"; - foreach (string line in new[] { body, prefixed }) + int typeQuote = body.IndexOf('\'', 1); + string unicodeSpace = body.Insert(typeQuote + 1, "\t\u00a0"); + string quotedPath = $"'{prefixed}"; + foreach (string line in new[] { body, prefixed, unicodeSpace, quotedPath }) { Assert.That( BaseCallLogMessageParser.ParseLine(line)?.DiagnosticId, @@ -84,6 +87,17 @@ public void ConsoleCandidateScreenPreservesParsedDiagnostics() Is.False, "The Console buffer should skip ordinary unrelated warnings." ); + string[] unrelatedRows = + { + "'Tool output' row 000319.", + "'com.example.tool' is already installed.", + "Build note: see DXMSG006 documentation.", + "Assets/Build.cs(12,9): warning DXMSG099: Unrelated diagnostic.", + }; + foreach (string line in unrelatedRows) + { + Assert.That(BaseCallLogMessageParser.IsDiagnosticCandidate(line), Is.False, line); + } } [Test] diff --git a/SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators.csproj b/SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators.csproj index 5e4ab364e..3b2feea19 100644 --- a/SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators.csproj +++ b/SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators/WallstopStudios.DxMessaging.SourceGenerators.csproj @@ -2,11 +2,7 @@ netstandard2.0 true - + 3.8.0 $(Version) @@ -15,7 +11,7 @@ - all diff --git a/Tests/Editor/DxMessagingSettingsProviderTests.cs b/Tests/Editor/DxMessagingSettingsProviderTests.cs index 275b437c4..25eea2573 100644 --- a/Tests/Editor/DxMessagingSettingsProviderTests.cs +++ b/Tests/Editor/DxMessagingSettingsProviderTests.cs @@ -134,6 +134,7 @@ public void CreateProviderIncludesSectionAndInspectorCheckSearchKeywords() Assert.That(provider.keywords, Does.Contain("Editor Safety")); Assert.That(provider.keywords, Does.Contain("Inspector Checks")); Assert.That(provider.keywords, Does.Contain("Base-Call Check Enabled")); + Assert.That(provider.keywords, Does.Contain("Include Compiler Warnings")); Assert.That(provider.keywords, Does.Contain("Use Console Bridge")); Assert.That(provider.keywords, Does.Contain("Ignored Base-Call Types")); } diff --git a/docs/architecture/performance.md b/docs/architecture/performance.md index 5ad022280..6fe8127c4 100644 --- a/docs/architecture/performance.md +++ b/docs/architecture/performance.md @@ -75,19 +75,20 @@ Runner: 13th Gen Intel(R) Core(TM) i9-13900KF; execution profile highest-efficie Time per operation is the reciprocal of the measured rate. Allocation evidence uses measured counts when the selected scope exposes them; otherwise it reports the -steady-state contract and marks the count unmeasured. - -| Scenario | DxMessaging rate | Time / operation | GC allocation evidence | -| ------------------------------------- | ---------------- | ---------------- | ------------------------------------- | -| Global -> 1 subscriber | 44.66 M ops/sec | 22.39 ns/op | 0 per emit contract; count unmeasured | -| Global -> 16 subscribers | 21.66 M ops/sec | 46.17 ns/op | 0 per emit contract; count unmeasured | -| Keyed/targeted -> 1 of many | 14.52 M ops/sec | 68.89 ns/op | 0 per emit contract; count unmeasured | -| Priority-ordered dispatch | 36.70 M ops/sec | 27.25 ns/op | 0 per emit contract; count unmeasured | -| Filtered/intercepted dispatch | 35.45 M ops/sec | 28.21 ns/op | 0 per emit contract; count unmeasured | -| Post-processing dispatch | 30.39 M ops/sec | 32.91 ns/op | 0 per emit contract; count unmeasured | -| Intercepted + post-processed dispatch | 27.71 M ops/sec | 36.09 ns/op | 0 per emit contract; count unmeasured | -| Subscribe/unsubscribe churn | 1.11 M ops/sec | 901.52 ns/op | Allocates; count unmeasured | -| Struct message (no boxing) | 45.16 M ops/sec | 22.14 ns/op | 0 per emit contract; count unmeasured | +steady-state contract and marks the count unmeasured. The MessagePipe percentages +use matching commit and platform rows. Independent-build uncertainty is unmeasured. + +| Scenario | DxMessaging rate | Time / operation | GC allocation evidence | Share of MessagePipe rate | +| ------------------------------------- | ---------------- | ---------------- | ------------------------------------- | ------------------------- | +| Global -> 1 subscriber | 44.66 M ops/sec | 22.39 ns/op | 0 per emit contract; count unmeasured | 42.3% | +| Global -> 16 subscribers | 21.66 M ops/sec | 46.17 ns/op | 0 per emit contract; count unmeasured | 101.4% | +| Keyed/targeted -> 1 of many | 14.52 M ops/sec | 68.89 ns/op | 0 per emit contract; count unmeasured | 115.4% | +| Priority-ordered dispatch | 36.70 M ops/sec | 27.25 ns/op | 0 per emit contract; count unmeasured | N/A | +| Filtered/intercepted dispatch | 35.45 M ops/sec | 28.21 ns/op | 0 per emit contract; count unmeasured | 45.4% | +| Post-processing dispatch | 30.39 M ops/sec | 32.91 ns/op | 0 per emit contract; count unmeasured | 35.0% | +| Intercepted + post-processed dispatch | 27.71 M ops/sec | 36.09 ns/op | 0 per emit contract; count unmeasured | 38.4% | +| Subscribe/unsubscribe churn | 1.11 M ops/sec | 901.52 ns/op | Allocates; count unmeasured | 45.2% | +| Struct message (no boxing) | 45.16 M ops/sec | 22.14 ns/op | 0 per emit contract; count unmeasured | 35.7% | ### Library comparison - throughput (Standalone (IL2CPP)) diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index 349799db7..dfa6138cd 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -116,7 +116,9 @@ flowchart TD ### Unity Samples (Importable!) -**Located in `Samples~/` directory** - Import via Unity Package Manager! +For a UPM install, use the **Samples** tab on the DxMessaging package. For a classic asset +package, open `Assets/WallstopStudios/DxMessaging/Samples`. +See [installation instructions](install.md#from-releases) for both formats. - **[Mini Combat](https://github.com/Ambiguous-Interactive/DxMessaging/blob/master/Samples~/Mini%20Combat/README.md)** - Interactive combat demo with Heal/Damage messages - Perfect first example to understand message flow diff --git a/docs/getting-started/install.md b/docs/getting-started/install.md index eb49c1dcc..4dc4fb04e 100644 --- a/docs/getting-started/install.md +++ b/docs/getting-started/install.md @@ -1,6 +1,6 @@ -# Install (Unity UPM) +# Install DxMessaging -This page helps you install DxMessaging into a Unity 2021.3+ project using the Unity Package Manager (UPM). +Install DxMessaging into a Unity 2021.3+ project through Unity Package Manager (UPM) or from a classic asset package. ## Quick Reference @@ -9,7 +9,7 @@ This page helps you install DxMessaging into a Unity 2021.3+ project using the U | **OpenUPM** (Recommended) | `openupm add com.wallstop-studios.dxmessaging` | Select a version in UPM | | **Git URL** | `https://github.com/Ambiguous-Interactive/DxMessaging.git` | Reinstall at a chosen revision | | **npm Scoped Registry** | Add registry + resolve | Select a version in UPM | -| **From Releases** | Download npm `.tgz` | Download and import a new package | +| **From Releases** | Download `.tgz` or `.unitypackage` | Download and install a new release | | **From Source** | Clone/download zip | Update the embedded checkout | | **Manual** (not recommended) | Edit manifest.json | Edit the dependency in the manifest | @@ -66,6 +66,18 @@ Open the [latest package release](https://github.com/Ambiguous-Interactive/DxMes and download the npm `.tgz` package or classic `.unitypackage`, plus its matching `.sha256` checksum. Verify the download with `sha256sum -c .sha256`. +- For the `.tgz`, open **Window > Package Manager**, click **+**, and choose **Add package from tarball**. + Select the downloaded file. To copy a sample into your project, select **DxMessaging**, open + **Samples**, and choose **Import** next to that sample. + [Unity's tarball installation guide](https://docs.unity3d.com/2021.3/Documentation/Manual/upm-ui-tarball.html) +- For the `.unitypackage`, choose **Assets > Import Package > Custom Package**, select the file, + and click **Import** in the asset list. DxMessaging appears under + `Assets/WallstopStudios/DxMessaging`. Open the included scenes directly from its `Samples` folder. + [Unity's local asset import guide](https://docs.unity3d.com/2021.3/Documentation/Manual/AssetPackagesImport.html) + +If you already imported DxMessaging 3.3.0 as a classic package, follow the +[classic upgrade steps](../guides/migration-guide.md#replace-a-classic-330-import) before importing 4.0.0. + ### From Source Embed the package under your Unity project's `Packages` directory, preserving diff --git a/docs/getting-started/quick-start.md b/docs/getting-started/quick-start.md index 565ac25bd..0d4ffa320 100644 --- a/docs/getting-started/quick-start.md +++ b/docs/getting-started/quick-start.md @@ -22,7 +22,7 @@ Unity Package Manager -> Add package from git URL: https://github.com/Ambiguous-Interactive/DxMessaging.git ``` -**Requirements:** Unity 2021.3+ | .NET Standard 2.1 | All render pipelines supported +**Requirements:** Unity 2021.3+ | .NET Standard 2.1 | Built-In Render Pipeline, URP, or HDRP --- diff --git a/docs/guides/diagnostics.md b/docs/guides/diagnostics.md index 9bdd4c96d..7ad59ecdf 100644 --- a/docs/guides/diagnostics.md +++ b/docs/guides/diagnostics.md @@ -74,7 +74,7 @@ project-wide defaults without writing bootstrap code: - **Diagnostics Targets** -- the `DiagnosticsTarget` flags enum. - **Message Buffer Size** -- the default diagnostics ring-buffer size. - **Suppress Domain Reload Warning** -- editor-safety warning control. -- **Base-Call Check Enabled** and **Use Console Bridge** -- Inspector warning +- **Base-Call Check Enabled** and **Include Compiler Warnings** -- Inspector warning controls for missing `MessageAwareComponent` base calls. The ignore list for base-call warnings still lives on diff --git a/docs/guides/inspector-overlay.md b/docs/guides/inspector-overlay.md index b7e09e534..50233c182 100644 --- a/docs/guides/inspector-overlay.md +++ b/docs/guides/inspector-overlay.md @@ -180,8 +180,8 @@ fully-qualified type name is currently in the project ignore list. When the component is **not** ignored, you see two buttons: - **Open Script** -- opens the offending component's source file at the - top; when the legacy console bridge is enabled and a line number is - available, the file opens at that line. + line reported by the compiler when available. Otherwise it opens at + the top of the file. - **Ignore this type** -- appends the component's fully-qualified type name to the ignore list in `Assets/Editor/DxMessagingSettings.asset`; the generated sidecar is refreshed for the analyzer. The next @@ -294,8 +294,8 @@ split into three sections: overlay. When `false`, the overlay is silenced; the underlying analyzer still emits the Console warning unless `.editorconfig` says otherwise. -- **Use Console Bridge** -- opt-in legacy bridge that unions Unity - Console / compiler-message warnings into the IL-reflection scan. +- **Include Compiler Warnings** -- adds base-call warnings from + compilations observed during this Editor session to the IL scan. Default off. - **Ignored Base-Call Types** -- fully-qualified `MessageAwareComponent` type names excluded from the overlay and diff --git a/docs/guides/migration-guide.md b/docs/guides/migration-guide.md index 92784effc..8c1758880 100644 --- a/docs/guides/migration-guide.md +++ b/docs/guides/migration-guide.md @@ -4,9 +4,38 @@ This guide helps you introduce DxMessaging into an existing Unity project **grad ## Migrating to 4.0.0 +### Replace a classic 3.3.0 import + +If you imported DxMessaging 3.3.0 as a `.unitypackage`, replace its package folder before +importing 4.0.0. The runtime assembly definition and six attribute scripts moved with their +existing asset IDs. Leaving the old files in place can introduce duplicate assets and obsolete +scripts. + +1. Commit or back up your Unity project. If the project also has DxMessaging installed through + Package Manager, [remove that installation](https://docs.unity3d.com/2021.3/Documentation/Manual/upm-ui-remove.html) + before importing the classic package. +1. Close the Unity Editor. Move `Assets/WallstopStudios/DxMessaging` and the adjacent + `Assets/WallstopStudios/DxMessaging.meta` file to a backup outside the project. Keep the + folder and its metadata together so you can restore your original import. +1. Reopen Unity and [import the 4.0.0 classic archive](../getting-started/install.md#from-releases). +1. Restore project-owned assets from the backup with their original `.meta` files. If you + customized a shipped script, scene, or sample, compare your backup with the 4.0.0 asset and + reapply your changes to the new copy. Keep the new package layout. +1. Apply the assembly reference changes below. Check the Console for compilation errors and + open the scenes and prefabs that use DxMessaging to check their references. + +For a Package Manager upgrade, update the installed package and review any +[samples you previously copied into Assets](#update-samples-copied-into-assets). + +### Find the compiler warning setting + +**Use Console Bridge** is now **Include Compiler Warnings**. Your existing setting carries +forward. The Inspector still runs its IL scan and can add messages from new compilations. +Warnings already in Unity's Console history are no longer imported by the Inspector. + ### Reference the dedicated attributes assembly -The seven public attributes move to `WallstopStudios.DxMessaging.Attributes` with unchanged namespaces and names. Add that assembly reference to each Unity assembly definition that uses a DxMessaging attribute. Keep the `WallstopStudios.DxMessaging` reference when the same assembly also uses message interfaces or runtime APIs. Predefined assemblies receive both references automatically. +The six public attributes from 3.3.0 move to `WallstopStudios.DxMessaging.Attributes` with unchanged namespaces and names. The attributes assembly also contains the new `DxAotMessageAttribute`. Add that assembly reference to each Unity assembly definition that uses a DxMessaging attribute. Keep the `WallstopStudios.DxMessaging` reference when the same assembly also uses message interfaces or runtime APIs. Predefined assemblies receive both references automatically. A shared rules assembly that only uses `[DxAutoConstructor]` and `[DxOptionalParameter]` can reference just the attributes and set `noEngineReferences` to `true`. The generator applies to the attributes assembly and assemblies that reference it. Type forwarding preserves legacy attribute lookups. Add the direct assembly reference to compile code that uses the attributes. diff --git a/docs/guides/patterns.md b/docs/guides/patterns.md index 18d21c34c..66a51078e 100644 --- a/docs/guides/patterns.md +++ b/docs/guides/patterns.md @@ -745,7 +745,8 @@ Record subscriber fan-out and callback work alongside the message rate: Compare results within the scope recorded by the [performance benchmarks](../architecture/performance.md). Use the -[measurement methodology](../runbooks/perf-benchmark-methodology.md) when collecting new results. +[measurement methodology](https://github.com/Ambiguous-Interactive/DxMessaging/blob/master/docs/runbooks/perf-benchmark-methodology.md) +when collecting new results. diff --git a/docs/integrations/vcontainer.md b/docs/integrations/vcontainer.md index 549ba00f5..f957ca613 100644 --- a/docs/integrations/vcontainer.md +++ b/docs/integrations/vcontainer.md @@ -29,9 +29,10 @@ These examples require VContainer. DxMessaging's integration assembly uses from these framework-specific examples. If your application needs conditional code, configure [Version Defines on its own assembly](https://docs.unity3d.com/2021.3/Documentation/Manual/ScriptCompilationAssemblyDefinitionFiles.html#define-symbols). -For a custom application asmdef, reference `WallstopStudios.DxMessaging`, -`WallstopStudios.DxMessaging.Attributes`, `WallstopStudios.DxMessaging.VContainer`, `VContainer`, and `VContainer.Unity` for -these examples. +With VContainer 1.19.0, add these references to your custom application asmdef: +`WallstopStudios.DxMessaging`, `WallstopStudios.DxMessaging.Attributes`, +`WallstopStudios.DxMessaging.VContainer`, and `VContainer`. The `VContainer` assembly +contains the `VContainer.Unity` namespace. ### 1. Create a LifetimeScope with DxMessaging diff --git a/docs/reference/analyzers.md b/docs/reference/analyzers.md index 0c2c3cb6a..a29c4b58c 100644 --- a/docs/reference/analyzers.md +++ b/docs/reference/analyzers.md @@ -523,7 +523,11 @@ The Inspector overlay's data source is the **`BaseCallTypeScanner`** -- a determ **DXMSG009 classified as DXMSG007 in the cache.** The scanner's IL-only probe cannot distinguish DXMSG007 (`new` modifier) from DXMSG009 (missing `override` / CS0114) -- Roslyn emits the same IL for both. The cached snapshot conservatively classifies both as `DXMSG007`. The compile-time analyzer remains authoritative for the precise classification -- see the [DXMSG009: Editor inspector overlay subsection](#editor-inspector-overlay) above. -**Legacy console-scrape bridge (opt-in).** The `DxMessagingSettings.UseConsoleBridge` field on `Assets/Editor/DxMessagingSettings.asset` re-enables the old data sources (`UnityEditor.LogEntries` reflection + `CompilationPipeline.assemblyCompilationFinished` `CompilerMessage[]`) and unions them INTO the IL scanner's snapshot -- never overrides it. Default off. Enable only if you want the union of both data sources, e.g. to surface a regression in the IL byte-walker that is correctly captured by the compile-time analyzer's console output. +**Compiler warnings (opt-in).** Enable **Include Compiler Warnings** in Project Settings +to add analyzer warnings from `CompilationPipeline.assemblyCompilationFinished` to the IL scan. +The IL scanner remains the primary source. The feed only sees compilations observed during +the current Editor session. The saved value and the `DxMessagingSettings.UseConsoleBridge` +property keep their original names. The unified per-FQN snapshot is persisted to `Library/DxMessaging/baseCallReport.json` so the overlay has data to render before the first post-load rescan completes; it is rewritten on every successful rescan. A manual `Tools -> Wallstop Studios -> DxMessaging -> Rescan Base-Call Warnings` menu is available for force-rescan. @@ -536,7 +540,7 @@ The overlay itself uses two complementary editor-injection paths: Components that emit DXMSG006, DXMSG007, DXMSG009, or DXMSG010 show a warning surface at the top of their Inspector with three actions: -- **Open Script** -- opens the offending component's source file; when the legacy console bridge has a line number, it opens at that line. +- **Open Script** -- opens the offending component's source file; when the compiler provides a line number, it opens at that line. - **Ignore this type** -- appends the type's fully-qualified name to the ignore list in `Assets/Editor/DxMessagingSettings.asset`; the generated sidecar is refreshed for the analyzer. - **Stop ignoring** -- appears instead of "Ignore this type" when the type is already in the ignore list; removes it. @@ -603,11 +607,12 @@ a player build immediately after it in the same callback. ## Unity 2021 setup notes DxMessaging splits its compiler extensions into two DLLs: one analyzer and one source generator. -Both target Roslyn 3.8.0 for Unity 2021 compatibility: +Both target the Roslyn 3.8.0 API for Unity 2021 compatibility. The archived Linux Unity +2021.3.45f1 script compiler uses Roslyn 3.9. In a load check, it ran a 3.8-targeted analyzer +and reported CS8032 for the same analyzer built against Roslyn 4.8. - `WallstopStudios.DxMessaging.Analyzer.dll` contains the base-call analyzer - (DXMSG006/007/008/009/010/015). Unity 2021 rejects analyzers built against Roslyn 4.x; - Microsoft's `Microsoft.Unity.Analyzers` package pins Roslyn 3.8.0 for the same reason. + (DXMSG006/007/008/009/010/015). - `WallstopStudios.DxMessaging.SourceGenerators.dll` contains the source generators (DXMSG002/003/004/005/011/012/013/014/016). They use the classic `ISourceGenerator` API so Unity 2021 can instantiate them. diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md index 1d329408e..2f8a619ee 100644 --- a/docs/reference/compatibility.md +++ b/docs/reference/compatibility.md @@ -1,8 +1,10 @@ # Compatibility -DxMessaging is render-pipeline agnostic (pure C#) and targets Unity 2021.3+. The matrix below summarizes support by Unity version and Render Pipeline. +DxMessaging supports Unity 2021.3 or later with the Built-In Render Pipeline, +Universal Render Pipeline (URP), or High Definition Render Pipeline (HDRP). +The messaging runtime and Editor diagnostics use Unity APIs shared by these pipelines. -Unity Version vs Render Pipeline +## Unity versions and render pipelines | Unity | Built-In RP | URP | HDRP | | ---------- | ----------- | ---------- | ---------- | @@ -13,7 +15,11 @@ Unity Version vs Render Pipeline Notes -- RP-agnostic: DxMessaging does not depend on rendering APIs; it works equally across Built-In, URP, and HDRP. +- The package has no dependency on a render pipeline package. Mini Combat and UI Buttons + + Inspector draw their controls using Unity's `OnGUI`. The samples ship without pipeline-specific + shaders or materials. +- Native CI covers selected Unity versions and test scopes. Separate native sample rendering + checks in URP and HDRP remain pending. - Minimum version is governed by the package manifest (`unity`: 2021.3). Newer LTS versions are expected to work. - Unity 6 migrates object identity to `EntityId` and deprecates `Object.GetInstanceID()` (it becomes a compile error in Unity 6.5). DxMessaging handles this internally: on Unity 6.4+ the dispatch key reads the non-deprecated `EntityId.ToULong(...)` accessor (keeping the same 32-bit value), and older Unity keeps `GetInstanceID()`. The package keeps building across the supported range, including Unity 6.5+ where the old API is removed. diff --git a/docs/runbooks/iteration-speed.md b/docs/runbooks/iteration-speed.md index 8dc13aeb4..1dd158f6e 100644 --- a/docs/runbooks/iteration-speed.md +++ b/docs/runbooks/iteration-speed.md @@ -95,6 +95,33 @@ in this editor-free checkout. For command syntax and trial details, see the [.NET watch reference](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-watch) and the [experiment record](https://github.com/Ambiguous-Interactive/DxMessaging/issues/817). +A fixed-input Attributes experiment on `864fc5f8` reused a dedicated warm Roslyn compiler server +with SDK 10.0.404 and ran the same named NUnit assertion through VSTest after each save. It +alternated 20 broken and 20 fixed saves per assertion per compiler mode. For the null-type check, +nearest-rank p95 fell from 1.019 to 0.784 seconds. For the exact-type check, it fell from 1.042 to +0.785 seconds. All 80 shared-compiler saves produced the expected verdict in under one second with +the expected fresh binary. The cold server needed 0.062 seconds to accept requests, then 0.983 +seconds for its first compile and verdict. + +These measurements cover two edits of one Attributes constructor with a fixed SDK response in +the Linux devcontainer. Use the filtered `dotnet test` command above when project inputs change. +[Attributes shared compiler study](https://github.com/Ambiguous-Interactive/DxMessaging/issues/817#issuecomment-7098607883). + +A follow-up screened an edit to runtime registration-group cleanup and a generator diagnostic +edit. Six measured saves per compiler mode gave shared-compiler medians of 1.194 and 1.261 seconds, +down from 1.422 and 1.762 with the direct compiler. Both missed the one-second screen and stopped +before the 40-save confirmation. Every save produced the expected NUnit verdict and fresh binary. +The runtime, generator, and Editor targets remain open. + +With six extra verified compile-and-verdict warmup requests, the medians fell from 1.344 to +1.131 seconds for the runtime edit and from 1.534 to 1.205 seconds for the generator edit. +All six measured saves per warmed lane exceeded one second. Median compiler time fell to +0.224 and 0.251 seconds, while VSTest still took 0.883 and 0.963 seconds. The first cold verdict +and six warmup requests cost 10.339 and 11.602 seconds before measurement. These screens +stopped before the 40-save confirmation. +[Compiler warmup results](https://github.com/Ambiguous-Interactive/DxMessaging/issues/817#issuecomment-7113483433). +[Runtime and generator screen](https://github.com/Ambiguous-Interactive/DxMessaging/issues/817#issuecomment-7098746835). + ## Rolling PR latency Target p95 below 420 seconds from a PR update to the last required verdict, including queue @@ -217,6 +244,22 @@ trusted-skip shape. Consolidating it with the four-version matrix would require change or duplicated licensed jobs. Keep both gates' documentation allowlists synchronized until that upstream capability exists. Unknown paths and incomplete listings must not skip validation. +## Editor-free devcontainer + +Set `UNITY_MCP_ENABLED=false` in the checkout's ignored `.env.local`, run +`npm run unity:mcp:configure -- --offline`, and reconnect the MCP clients you have open. +Container creation, startup, and attachment honor this setting. It removes the Unity +connection from the seven generated client configs and skips host discovery and token creation. +A host outage alone leaves the selected mode in place. + +Use the two managed fast lanes under [local commands](#local-commands) for runtime changes. +Use `npm run test:unit` for script feedback and `npm test` before delivering script changes. +Record counts, failures, and durations for the lanes you ran. Mark EditMode, PlayMode, and +IL2CPP checks pending until a licensed host produces results for that revision. + +To reconnect, set `UNITY_MCP_ENABLED=true` or remove the setting. With the licensed host ready, +run `npm run unity:mcp:configure`, reconnect clients, and run `npm run unity:mcp:probe`. + ## Dedicated Unity package host From the host checkout, generate a package-only host with the existing runner. Container-generated diff --git a/scripts/__tests__/asset-store-submission.test.js b/scripts/__tests__/asset-store-submission.test.js index c16844ef8..c99677447 100644 --- a/scripts/__tests__/asset-store-submission.test.js +++ b/scripts/__tests__/asset-store-submission.test.js @@ -45,11 +45,14 @@ test("stageAssetStoreSubmission creates a verified operator artifact", (t) => { assert.equal(listing.priceUsd, 0); assert.equal(listing.aiDescription, sourceListing.aiDescription); assert.ok(listing.aiDescription.trim().length > 0); + assert.match(upm, /Submit for Unity review\.\n\n## After Publication[\s\S]*Package Manager Version History[\s\S]*compare its field values[\s\S]*Install the published package/); for (const checklist of [classic, upm]) { assert.match(checklist, /Set the price to Free \(USD 0\)/); assert.match(checklist, /AI description.*aiDescription/); - assert.match(checklist, /Verify the live listing.*free price.*disclosure/); + assert.match(checklist, /Submit for Unity review\.\n\n## After Publication\n\n1\. Verify the live listing.*free price.*disclosure/); + assert.match(checklist, /Install the published package in a clean project/); } + assert.doesNotMatch(classic, /Package Manager Version History/); for (const screenshot of listing.screenshots) { assert.ok(fs.existsSync(path.join(output, screenshot.file)), screenshot.file); assert.equal("source" in screenshot, false, screenshot.file); } diff --git a/scripts/__tests__/ci-aggregate-workflow.test.js b/scripts/__tests__/ci-aggregate-workflow.test.js index 1cc9123f8..e1366913b 100644 --- a/scripts/__tests__/ci-aggregate-workflow.test.js +++ b/scripts/__tests__/ci-aggregate-workflow.test.js @@ -819,7 +819,9 @@ test("managed suites follow their inputs and retain both validation tiers", (t) ["docs/architecture/performance.md", [false, false, false, false]], ["docs/guides/testing.md", [false, true, false, false]], ["SourceGenerators/Generator.cs", [true, true, true, false]], ["Runtime/Core/MessageBus/MessageBus.cs", [false, true, true, true]], ["Tests/Runtime/MemoryReclaim/DisabledTokenRetentionTests.cs", [false, false, true, true]], ["Tests/Runtime/Core/MessageRecorderTests.cs", [false, false, true, false]], - ["Editor/Analyzers/BaseCallIlInspector.cs", [false, true, true, false]], ["scripts/mcp/DxMcpTestRunner.cs.txt", [false, true, false, false]], + ["Editor/Analyzers/BaseCallIlInspector.cs", [true, true, true, false]], ["Editor/Analyzers/BaseCallLogMessageParser.cs", [true, true, false, false]], + ["Editor/Analyzers/BaseCallReportAggregator.cs", [true, true, false, false]], ["Editor/Analyzers/BaseCallTypeScannerCore.cs", [true, true, false, false]], + ["Editor/Analyzers/DxMessagingConsoleHarvester.cs", [false, true, false, false]], ["scripts/mcp/DxMcpTestRunner.cs.txt", [false, true, false, false]], ["Runtime/Core/Helper/MessageCache.cs", [false, true, true, true]], [".github/workflows/ci.yml", [true, true, true, true]] ]) { const output = path.join(root, "output"); fs.writeFileSync(output, ""); diff --git a/scripts/__tests__/perf-test-vectors.json b/scripts/__tests__/perf-test-vectors.json index 9554b7e4f..430b4e1e3 100644 --- a/scripts/__tests__/perf-test-vectors.json +++ b/scripts/__tests__/perf-test-vectors.json @@ -1829,6 +1829,15 @@ "FilteredPostProcess": 0.99, "StructNoBox": 1 }, + "comparisonRatioCases": [ + ["100000000.000", {}, "111.1%"], + ["30000000.000", {}, "33.3%"], + ["30000000.000", null, "N/A"], + ["30000000.000", { "commit": "different" }, "N/A"], + ["30000000.000", { "platform": "other" }, "N/A"], + ["30000000.000", { "emitsPerSecond": "0" }, "N/A"], + ["30000000.000", { "emitsPerSecond": "not a rate" }, "N/A"] + ], "scopeCases": [ ["Standalone IL2CPP x64 Release (WindowsPlayer; Unity 6000.3.16f1)", "Standalone"], ["Editor PlayMode Mono x64 Release (WindowsEditor; Unity 6000.3.16f1)", "PlayMode"], diff --git a/scripts/__tests__/test-editor-provisioning-heartbeat.ps1 b/scripts/__tests__/test-editor-provisioning-heartbeat.ps1 index c4ca2447e..3e09c5033 100644 --- a/scripts/__tests__/test-editor-provisioning-heartbeat.ps1 +++ b/scripts/__tests__/test-editor-provisioning-heartbeat.ps1 @@ -15,7 +15,8 @@ #> [CmdletBinding()] param( - [switch]$VerboseOutput + [switch]$VerboseOutput, + [switch]$ReportFiniteTiming ) Set-StrictMode -Version Latest @@ -267,23 +268,57 @@ try { $env:DXM_ENSURE_EDITOR_PROGRESS_NOTICE_INTERVAL_SECONDS = '1' $noisyFinite = @' +function Publish-Timestamp { + param([string]$Name) + $timestamp = [Diagnostics.Stopwatch]::GetTimestamp() + $path = Join-Path $env:DXM_TEST_HEARTBEAT_TIMING_DIR $Name + [IO.File]::WriteAllText("$path.tmp", [string]$timestamp) + [IO.File]::Move("$path.tmp", $path) +} +Publish-Timestamp 'entered' 1..7 | ForEach-Object { $line = '{"type":"progress","pct":50,"msg":"Installing Unity...","phase":"install"}' + if ($_ -eq 1) { + Publish-Timestamp 'before-first-write' + } if ($_ % 2 -eq 0) { [Console]::Error.WriteLine($line) } else { Write-Output $line } + if ($_ -eq 1) { + [Console]::Out.Flush() + Publish-Timestamp 'first-flushed' + } Start-Sleep -Milliseconds 500 } '@ $script:noisyFiniteResult = $null - $noticeOutput = @(& { - $script:noisyFiniteResult = Invoke-UnityCliCaptureWithTimeout ` - -Arguments @('-NoLogo', '-NoProfile', '-EncodedCommand', (ConvertTo-EncodedCommand $noisyFinite)) ` - -TimeoutSeconds 10 ` - -StallSeconds 3 - } 6>&1) + $parentTiming = [ordered]@{} + $childTiming = [ordered]@{} + $timingDirectory = [IO.Directory]::CreateTempSubdirectory('dxm-heartbeat-timing-') + $savedTimingDirectory = $env:DXM_TEST_HEARTBEAT_TIMING_DIR + try { + $env:DXM_TEST_HEARTBEAT_TIMING_DIR = $timingDirectory.FullName + $noticeOutput = @(& { + $script:noisyFiniteResult = Invoke-UnityCliCaptureWithTimeout ` + -Arguments @('-NoLogo', '-NoProfile', '-EncodedCommand', (ConvertTo-EncodedCommand $noisyFinite)) ` + -TimeoutSeconds 10 ` + -StallSeconds 3 ` + -HeartbeatTiming $parentTiming + } 6>&1) + foreach ($marker in @('entered', 'before-first-write', 'first-flushed')) { + $path = Join-Path $timingDirectory.FullName $marker + $childTiming[$marker] = if ([IO.File]::Exists($path)) { + [long][IO.File]::ReadAllText($path) + } else { + $null + } + } + } finally { + $env:DXM_TEST_HEARTBEAT_TIMING_DIR = $savedTimingDirectory + $timingDirectory.Delete($true) + } $result = $script:noisyFiniteResult $noticeText = (@($noticeOutput | ForEach-Object { [string]$_ }) -join "`n") Assert-That 'repeated stdout/stderr progress completes successfully' $result.Success @@ -293,12 +328,15 @@ try { Assert-That 'repeated stdout/stderr progress confirms direct child exit' $result.DirectChildExited Assert-That 'every repeated stdout/stderr progress line is captured' (@($result.Output).Count -eq 7) Assert-That 'periodic notice reports monotonic idle elapsed time' ($noticeText -match 'install heartbeat:.*idleElapsed=\d+s') + $finiteFailures = $failed + $finiteStartupStall = $result.StallKilled -and $result.DirectChildExited -and @($result.Output).Count -eq 0 - if ($failed -ne 0) { - # This first control captures stream 6 to assert the periodic notices. Print that - # captured evidence on failure so CI retains startup silence and later progress. - Write-Host '::group::Finite heartbeat control failure evidence' + if ($failed -ne 0 -or $ReportFiniteTiming) { + # Stream 6 is captured for the periodic-notice assertion. Retain it with the + # independent child markers when diagnosing startup silence or delayed capture. + Write-Host '::group::Finite heartbeat control evidence' Write-Host "PowerShell $($PSVersionTable.PSVersion); $([Runtime.InteropServices.RuntimeInformation]::FrameworkDescription); logical processors $([Environment]::ProcessorCount)" + Write-Host (@{ Parent = $parentTiming; Child = $childTiming } | ConvertTo-Json -Depth 4) Write-Host ($result | ConvertTo-Json -Depth 4) Write-Host $noticeText Write-Host '::endgroup::' @@ -559,5 +597,9 @@ Write-Output 'published' Write-Host "Unity editor heartbeat tests: $passed passed, $failed failed." if ($failed -gt 0) { + # A completed suite with only the startup-silence failure can safely run an isolated comparison. + if ($finiteStartupStall -and $failed -eq $finiteFailures) { + Write-Host 'Isolated heartbeat comparison eligible.' + } exit 1 } diff --git a/scripts/__tests__/test_create_unitypackage.py b/scripts/__tests__/test_create_unitypackage.py index bf26f78be..d2d8378b6 100644 --- a/scripts/__tests__/test_create_unitypackage.py +++ b/scripts/__tests__/test_create_unitypackage.py @@ -92,6 +92,14 @@ def test_existing_tarball_supplies_assets_and_must_match_checkout_identity(self) manifest = json.dumps(archived_package).encode() (packed / "package.json").write_bytes(manifest) (packed / "Samples~" / "Example.cs").write_text("class Example {}\n") + sample_doc = packed / "Samples~" / "Local Guide.md" + sample_doc.write_bytes(b"# Try it\r\n") + original_readme = ( + b"[Walkthrough](Samples~/Local%20Guide.md#try-it)\r\n" + b"[Online](https://example.com/Samples~/Local%20Guide.md)\r\n" + b"The UPM folder is `Samples~/`.\r\n" + ) + (packed / "README.md").write_bytes(original_readme) tarball = root / "release.tgz" with tarfile.open(tarball, "w:gz") as archive: archive.add(packed, arcname="package") @@ -102,6 +110,20 @@ def test_existing_tarball_supplies_assets_and_must_match_checkout_identity(self) staged = MODULE.stage_packed_payload(root, scratch, tarball) self.assertEqual((staged / "package.json").read_bytes(), manifest) self.assertTrue((staged / "Samples" / "Example.cs").is_file()) + self.assertEqual( + (staged / "Samples" / sample_doc.name).read_bytes(), + sample_doc.read_bytes(), + ) + self.assertEqual( + (staged / "README.md").read_bytes(), + b"[Walkthrough](Samples/Local%20Guide.md#try-it)\r\n" + b"[Online](https://example.com/Samples~/Local%20Guide.md)\r\n" + b"The UPM folder is `Samples~/`.\r\n", + ) + with tarfile.open(tarball, "r:gz") as archive: + archived_readme = archive.extractfile("package/README.md") + assert archived_readme is not None + self.assertEqual(archived_readme.read(), original_readme) else: with self.assertRaisesRegex(ValueError, "name or version"): MODULE.stage_packed_payload(root, scratch, tarball) diff --git a/scripts/__tests__/test_unity_validation_tiers.py b/scripts/__tests__/test_unity_validation_tiers.py index 039f16c1a..e83ac15a3 100644 --- a/scripts/__tests__/test_unity_validation_tiers.py +++ b/scripts/__tests__/test_unity_validation_tiers.py @@ -9,6 +9,7 @@ import subprocess import tempfile import unittest +from zipfile import ZipFile ROOT = Path(__file__).resolve().parents[2] @@ -297,6 +298,54 @@ def test_publication_requires_all_release_lanes(self): upload = next(step for step in workflow("unity-tests.yml")["jobs"]["unity-tests"]["steps"] if step.get("name") == "Upload EditMode test artifacts") self.assertIn("'consumer-install' || 'editmode'", upload["with"]["name"]) + @unittest.skipIf(os.name == "nt", "NuGet.org verification runs in Bash") + def test_attributes_verification_requires_public_source_and_matching_payload(self): + steps = workflow("attributes-package.yml")["jobs"]["package"]["steps"] + script = next(step["run"] for step in steps if step.get("name") == "Restore and verify the live package") + feed = "https://api.nuget.org/v3/index.json" + version = "4.0.0" + cases = [ + ("matching public package", feed, b"attribute assembly", True, True), + ("local cache", "/local-feed", b"attribute assembly", False, False), + ("missing source metadata", None, b"attribute assembly", False, False), + ("different public payload", feed, b"other assembly", False, False), + ] + dotnet = r""" +dotnet() { + case "$1" in + restore) printf '%s\n' "$@" > restore-args ;; + test) printf '%s\n' "$@" > test-args ;; + *) return 87 ;; + esac +} +""" + for name, source, payload, succeeds, runs_consumer in cases: + with self.subTest(name=name), tempfile.TemporaryDirectory(prefix="dxm-nuget-origin-") as tmp: + root = Path(tmp) + cache = root / "packages" + installed = cache / "wallstopstudios.dxmessaging.attributes" / version + library = "lib/netstandard2.0/WallstopStudios.DxMessaging.Attributes.dll" + (installed / library).parent.mkdir(parents=True) + (installed / library).write_bytes(payload) + if source is not None: + (installed / ".nupkg.metadata").write_text(json.dumps({"source": source})) + package = root / ".artifacts/nuget" / f"WallstopStudios.DxMessaging.Attributes.{version}.nupkg" + package.parent.mkdir(parents=True) + with ZipFile(package, "w") as archive: + archive.writestr(library, b"attribute assembly") + env = dict(os.environ, NUGET_PACKAGES=str(cache), PACKAGE_VERSION=version) + result = subprocess.run(["bash", "-c", dotnet + script], cwd=root, env=env, + capture_output=True, text=True) + self.assertEqual(result.returncode == 0, succeeds, result.stdout + result.stderr) + self.assertEqual((root / "test-args").exists(), runs_consumer) + restore = (root / "restore-args").read_text().splitlines() + self.assertEqual(restore.count("--source"), 1) + self.assertEqual(restore[restore.index("--source") + 1], feed) + self.assertIn("--no-http-cache", restore) + self.assertIn("-p:RestoreAdditionalProjectSources=", restore) + if runs_consumer: + self.assertIn("--no-restore", (root / "test-args").read_text().splitlines()) + @unittest.skipIf(os.name == "nt", "npm publication runs in Bash") def test_npm_retry_requires_matching_bytes_or_confirmed_absence(self): step = next(step for step in self.document["jobs"]["publish"]["steps"] diff --git a/scripts/__tests__/unity-mcp.test.js b/scripts/__tests__/unity-mcp.test.js index dc2ef6807..bae4abeeb 100644 --- a/scripts/__tests__/unity-mcp.test.js +++ b/scripts/__tests__/unity-mcp.test.js @@ -796,38 +796,27 @@ test("mergeCodexToml normalizes CRLF input so a second run is a no-op", () => { "configure converges on run 2, not run 3" ); }); +function failCommitAt(indexToFail) { + return (index) => { + if (index === indexToFail) throw new Error("commit failure"); + }; +} test("transactionalWrite commits every file or none", () => { const directory = temporaryDirectory(); const first = path.join(directory, "first.json"); const second = path.join(directory, "nested", "second.json"); fs.writeFileSync(first, "original\n"); - const written = mcp.transactionalWrite([ + const changes = [ [first, "updated\n"], [second, "created\n"] - ]); + ]; + const written = mcp.transactionalWrite(changes); assert.deepEqual(written.sort(), [first, second].sort()); assert.equal(fs.readFileSync(first, "utf8"), "updated\n"); assert.equal(fs.readFileSync(second, "utf8"), "created\n"); - assert.deepEqual( - mcp.transactionalWrite([[first, "updated\n"]]), - [], - "unchanged content is not rewritten" - ); - assert.throws( - () => - mcp.transactionalWrite( - [ - [first, "second-update\n"], - [second, "second-create\n"] - ], - (index) => { - if (index === 1) { - throw new Error("commit failure"); - } - } - ), - /commit failure/ - ); + assert.deepEqual(mcp.transactionalWrite(changes), [], "unchanged content is not rewritten"); + const updated = changes.map(([file, value]) => [file, value + "second update"]); + assert.throws(() => mcp.transactionalWrite(updated, failCommitAt(1)), /commit failure/); assert.equal(fs.readFileSync(first, "utf8"), "updated\n", "the committed file is rolled back"); assert.equal(fs.readFileSync(second, "utf8"), "created\n"); }); @@ -842,13 +831,9 @@ test("transactionalWrite removes files it created when a later commit fails", () [created, "new\n"], [other, "new\n"] ], - (index) => { - if (index === 1) { - throw new Error("boom"); - } - } + failCommitAt(1) ), - /boom/ + /commit failure/ ); assert.equal( fs.existsSync(created), @@ -879,11 +864,7 @@ test("transactionalWrite finishes rollback and rethrows the original error", () [second, "b\n"], [third, "c\n"] ], - (index) => { - if (index === 2) { - throw new Error("commit failure"); - } - } + failCommitAt(2) ); } catch (error) { thrown = error; @@ -935,13 +916,9 @@ test( [first, "a\n"], [second, "b\n"] ], - (index) => { - if (index === 1) { - throw new Error("boom"); - } - } + failCommitAt(1) ), - /boom/ + /commit failure/ ); assert.equal( fs.statSync(first).mode & 0o777, @@ -1487,8 +1464,12 @@ for (const [label, argv, expected] of [ }); } +function clientServerMap(client, raw) { + if (client === "codex") return { ...require("smol-toml").parse(raw).mcp_servers }; + const key = client === "vscode" ? "servers" : client === "openCode" ? "mcp" : "mcpServers"; + return JSON.parse(raw)[key]; +} test("ZAI credentials and local tools reach every client without losing user settings", async (t) => { - const { parse } = await import("smol-toml"); const repoRoot = temporaryDirectory(t); fs.writeFileSync(path.join(repoRoot, ".env.local"), "ZAI_API_KEY=file-key\n"); const options = mcp.resolveOptions({}, { Z_AI_API_KEY: "environment-key" }, undefined, repoRoot); @@ -1497,12 +1478,7 @@ test("ZAI credentials and local tools reach every client without losing user set mcp.configure(options, endpoint); for (const [client, file] of Object.entries(mcp.clientConfigPaths(repoRoot))) { const raw = fs.readFileSync(file, "utf8"); - const servers = - client === "codex" - ? parse(raw).mcp_servers - : JSON.parse(raw)[ - client === "vscode" ? "servers" : client === "openCode" ? "mcp" : "mcpServers" - ]; + const servers = clientServerMap(client, raw); for (const name of [ "unity-mcp", "github", @@ -1621,6 +1597,49 @@ test("bridge reports readiness only after a live editor answers and closes on SI await mcp.assertPortAvailable(port, "127.0.0.1"); }); +test("Editor-free mode removes stale Unity entries and can restore them", async (t) => { + const repoRoot = temporaryDirectory(t); + captureConsole(t, "log"); + const envFile = path.join(repoRoot, ".env.local"); + const disabledEnv = "UNITY_MCP_ENABLED=false\nUNITY_MCP_BRIDGE_PORT=stale\n"; + fs.writeFileSync(envFile, disabledEnv); + const options = mcp.resolveOptions({ command: "configure" }, {}, undefined, repoRoot); + const enabled = mcp.resolveOptions( + { offline: true, token: BRIDGE_TOKEN, port: "9020" }, + { UNITY_MCP_ENABLED: "true" }, + undefined, + repoRoot + ); + const clients = mcp.clientConfigPaths(repoRoot); + const paths = Object.values(clients); + const maps = () => + Object.entries(clients).map(([client, file]) => + clientServerMap(client, fs.readFileSync(file, "utf8")) + ); + const snapshot = () => paths.map((file) => fs.readFileSync(file, "utf8")); + fs.writeFileSync(paths[0], JSON.stringify({ mcpServers: { personal: { command: "my-tool" } } })); + await mcp.runConfigure(enabled); + const original = maps(); + assert.ok(original.every((servers) => servers["unity-mcp"])); + const noDiscovery = { + get candidates() { + assert.fail("Editor-free mode started discovery"); + } + }; + await mcp.runConfigure(options, noDiscovery); + const expected = original.map(({ ["unity-mcp"]: unity, ...others }) => others); + assert.ok(expected[0].personal); + assert.deepEqual(maps(), expected); + assert.equal(fs.readFileSync(envFile, "utf8"), disabledEnv); + assert.deepEqual(mcp.configure(options).written, []); + await assert.rejects(mcp.runProbe(options, noDiscovery), /UNITY_MCP_ENABLED=true/); + await mcp.runConfigure(enabled); + assert.deepEqual(maps(), original); + fs.writeFileSync(paths.at(-1), "{invalid"); + const malformed = snapshot(); + await assert.rejects(mcp.runConfigure(options, noDiscovery), /Invalid JSON/); + assert.deepEqual(snapshot(), malformed); +}); test("offline configuration never attempts a host connection", async (t) => { const repoRoot = temporaryDirectory(t); const options = mcp.resolveOptions({ offline: true }, {}, {}, repoRoot); diff --git a/scripts/__tests__/unity-perf.test.js b/scripts/__tests__/unity-perf.test.js index c6c242332..4f8aeb35f 100644 --- a/scripts/__tests__/unity-perf.test.js +++ b/scripts/__tests__/unity-perf.test.js @@ -517,6 +517,21 @@ test("generated performance block summarizes comparisons before internal dispatc assert.doesNotMatch(monoSummary, /Release player|\|.*count unmeasured.*\|/); }); +test("comparison ratios require matching positive rates on the same commit and platform", () => { + for (const [rate, reference, expected] of PERF_TEST_VECTORS.comparisonRatioCases) { + const entries = [["DxMessaging|GlobalToOne", comparisonRow(rate)]]; + if (reference) { + entries.push(["MessagePipe|GlobalToOne", { ...comparisonRow("90000000.000"), ...reference }]); + } + const [summary] = buildComparisonSections(standaloneRows(entries)); + const rendered = summary + .join("\n") + .split("\n") + .find((line) => line.startsWith("| Global -> 1 subscriber")); + assert.equal(rendered.split("|").at(-2).trim(), expected); + } +}); + test("deriveScope reads the execution scope from platform strings", () => { const cases = PERF_TEST_VECTORS.scopeCases; for (const [platform, expected] of cases) { diff --git a/scripts/mcp/README.md b/scripts/mcp/README.md index 46a6d1717..8929307c4 100644 --- a/scripts/mcp/README.md +++ b/scripts/mcp/README.md @@ -28,6 +28,14 @@ host bind mounts that do not support `chown`. Unwritable files must become writa after repair or startup fails with their path. Repair does not recursively change the host checkout. A host checkout that is itself read-only must be repaired on the host. +## Editor-free use + +Set `UNITY_MCP_ENABLED=false` in `.env.local` to omit Unity from the generated client configs. +Run `npm run unity:mcp:configure -- --offline` and reconnect open clients. +Re-enable Unity to validate and apply your saved endpoint settings again. +With Unity enabled (the default), `--offline` skips discovery and still configures the endpoint. +See the [Editor-free test workflow](../../docs/runbooks/iteration-speed.md#editor-free-devcontainer). + ## Credentials Create `.env.local` at the repository root. Values from the process environment take diff --git a/scripts/mcp/unity-mcp.mjs b/scripts/mcp/unity-mcp.mjs index 6d2592072..b6fa826bd 100644 --- a/scripts/mcp/unity-mcp.mjs +++ b/scripts/mcp/unity-mcp.mjs @@ -62,46 +62,25 @@ export const DEFAULTS = Object.freeze({ export const FALLBACK_PORTS = Object.freeze([9020, 9003]); // Docker Desktop and same-host defaults; discovery also checks WSL and Linux gateways. export const FALLBACK_HOSTS = Object.freeze(["host.docker.internal", "127.0.0.1"]); -const OPTION_NAMES = new Set([ - "bind", - "host", - "client-host", - "port", - "path", - "project", - "relay", - "backend", - "cli", - "request-timeout", - "session-timeout", - "timeout", - "connect-timeout", - "max-sessions", - "protocol-version", - "log-level", - "token", - "no-discover", - "offline" -]); const FLAG_NAMES = new Set(["no-discover", "offline"]); const ENV_KEYS = Object.freeze({ - bindHost: "UNITY_MCP_BIND_HOST", + bind: "UNITY_MCP_BIND_HOST", host: "UNITY_MCP_BRIDGE_HOST", - clientHost: "UNITY_MCP_CLIENT_HOST", + "client-host": "UNITY_MCP_CLIENT_HOST", port: "UNITY_MCP_BRIDGE_PORT", - endpointPath: "UNITY_MCP_BRIDGE_PATH", - projectPath: "UNITY_PROJECT_PATH", - relayPath: "UNITY_MCP_RELAY_PATH", + path: "UNITY_MCP_BRIDGE_PATH", + project: "UNITY_PROJECT_PATH", + relay: "UNITY_MCP_RELAY_PATH", backend: "UNITY_MCP_BACKEND", - cliPath: "UNITY_CLI_PATH", - requestTimeout: "UNITY_MCP_REQUEST_TIMEOUT", - sessionTimeout: "UNITY_MCP_SESSION_TIMEOUT", + cli: "UNITY_CLI_PATH", + "request-timeout": "UNITY_MCP_REQUEST_TIMEOUT", + "session-timeout": "UNITY_MCP_SESSION_TIMEOUT", timeout: "UNITY_MCP_PROBE_TIMEOUT", - connectTimeout: "UNITY_MCP_CONNECT_TIMEOUT", - maxSessions: "UNITY_MCP_MAX_SESSIONS", - protocolVersion: "UNITY_MCP_PROTOCOL_VERSION", - logLevel: "UNITY_MCP_LOG_LEVEL", - bearerToken: "UNITY_MCP_BEARER_TOKEN" + "connect-timeout": "UNITY_MCP_CONNECT_TIMEOUT", + "max-sessions": "UNITY_MCP_MAX_SESSIONS", + "protocol-version": "UNITY_MCP_PROTOCOL_VERSION", + "log-level": "UNITY_MCP_LOG_LEVEL", + token: "UNITY_MCP_BEARER_TOKEN" }); function fail(message) { throw new Error(message); @@ -120,7 +99,7 @@ export function parseArgs(argv) { } const separator = token.indexOf("="); const name = token.slice(2, separator === -1 ? undefined : separator); - if (!OPTION_NAMES.has(name)) fail(`Unknown option: --${name}`); + if (!FLAG_NAMES.has(name) && !Object.hasOwn(ENV_KEYS, name)) fail(`Unknown option: --${name}`); if (FLAG_NAMES.has(name)) { if (separator !== -1) fail(`--${name} does not take a value`); result[name] = true; @@ -247,48 +226,45 @@ export function defaultEndpointHost( // Host project paths are validated only by bridge; they do not exist in the container. export function resolveOptions(args, environment = process.env, localValues, repoRoot = REPO_ROOT) { const local = localValues ?? readLocalEnv(repoRoot); - const get = (argName, key, fallback) => - first(args[argName], environment[ENV_KEYS[key]], local[ENV_KEYS[key]], fallback); - + const enabled = first(environment.UNITY_MCP_ENABLED, local.UNITY_MCP_ENABLED, "true"); + if (!["true", "false"].includes(enabled)) fail("UNITY_MCP_ENABLED must be true or false"); + const useUnity = enabled === "true" || !["configure", "probe"].includes(args.command); + const get = (arg, fallback) => + useUnity + ? first(args[arg], environment[ENV_KEYS[arg]], local[ENV_KEYS[arg]], fallback) + : fallback; const number = (arg, key, max, fallback = DEFAULTS[key]) => { const label = arg[0].toUpperCase() + arg.slice(1).replaceAll("-", " "); - return integer(get(arg, key, fallback), label, 1, max); + return integer(get(arg, fallback), label, 1, max); }; - const explicitHost = first(args.host, environment[ENV_KEYS.host], local[ENV_KEYS.host]); - const explicitPort = first(args.port, environment[ENV_KEYS.port], local[ENV_KEYS.port]); - const projectPath = first( - args.project, - environment[ENV_KEYS.projectPath], - local[ENV_KEYS.projectPath] - ); - + const explicitHost = get("host"); + const explicitPort = get("port"); + const projectPath = get("project"); const options = { repoRoot, - bindHost: validateHost(get("bind", "bindHost", DEFAULTS.bindHost), "Bind host"), + unityEnabled: enabled === "true", + bindHost: validateHost(get("bind", DEFAULTS.bindHost), "Bind host"), host: validateHost(explicitHost ?? defaultEndpointHost()), - clientHost: - get("client-host", "clientHost") === undefined - ? undefined - : validateHost(get("client-host", "clientHost")), + clientHost: get("client-host") === undefined ? undefined : validateHost(get("client-host")), explicitHost: explicitHost === undefined ? undefined : validateHost(explicitHost), port: integer(explicitPort ?? DEFAULTS.port, "Port", 1, 65_535), explicitPort: explicitPort === undefined ? undefined : integer(explicitPort, "Port", 1, 65_535), - endpointPath: validateEndpointPath(get("path", "endpointPath", DEFAULTS.endpointPath)), + endpointPath: validateEndpointPath(get("path", DEFAULTS.endpointPath)), projectPath: projectPath === undefined ? undefined : path.resolve(projectPath), - backend: get("backend", "backend", "cli"), - cliPath: get("cli", "cliPath", "unity"), - relayPath: first(args.relay, environment[ENV_KEYS.relayPath], local[ENV_KEYS.relayPath]), + backend: get("backend", "cli"), + cliPath: get("cli", "unity"), + relayPath: get("relay"), requestTimeout: number("request-timeout", "requestTimeout", 86_400_000), sessionTimeout: number("session-timeout", "sessionTimeout", 86_400_000), timeout: number("timeout", "timeout", 300_000, DEFAULTS.probeTimeout), connectTimeout: number("connect-timeout", "connectTimeout", 60_000), maxSessions: number("max-sessions", "maxSessions", 1_024), protocolVersion: validateText( - get("protocol-version", "protocolVersion", DEFAULTS.protocolVersion), + get("protocol-version", DEFAULTS.protocolVersion), "Protocol version" ), - logLevel: get("log-level", "logLevel", "info"), - bearerToken: validateToken(get("token", "bearerToken", undefined)), + logLevel: get("log-level", "info"), + bearerToken: validateToken(get("token", undefined)), githubToken: githubToken(environment, local), zaiToken: first( environment.Z_AI_API_KEY, @@ -299,22 +275,19 @@ export function resolveOptions(args, environment = process.env, localValues, rep offline: args.offline === true, discover: args["no-discover"] !== true }; - if (!["cli", "relay"].includes(options.backend)) fail("Backend must be cli or relay"); if (options.zaiToken) validateText(options.zaiToken, "Z.AI key"); if (options.relayPath) options.relayPath = path.resolve(options.repoRoot, options.relayPath); - if (!/^(?:debug|info|none)$/.test(options.logLevel)) { + if (!/^(?:debug|info|none)$/.test(options.logLevel)) fail("Log level must be debug, info, or none"); - } - if (options.protocolVersion !== DEFAULTS.protocolVersion) { + if (options.protocolVersion !== DEFAULTS.protocolVersion) fail(`Protocol version must be ${DEFAULTS.protocolVersion}`); - } return options; } export function requireProjectPath(options) { if (!options.projectPath) { - fail(`Unity project path is required. Pass --project or set ${ENV_KEYS.projectPath}.`); + fail(`Unity project path is required. Pass --project or set ${ENV_KEYS.project}.`); } if (!fs.existsSync(options.projectPath) || !fs.statSync(options.projectPath).isDirectory()) { fail(`Unity project directory does not exist: ${options.projectPath}`); @@ -726,13 +699,13 @@ export function transactionalWrite(writes, beforeCommit = () => {}) { function ensureBearerToken(options) { if (options.bearerToken) return options; - const saved = readLocalEnv(options.repoRoot)[ENV_KEYS.bearerToken]; + const saved = readLocalEnv(options.repoRoot)[ENV_KEYS.token]; if (saved) return { ...options, bearerToken: validateToken(saved) }; const bearerToken = randomBytes(32).toString("hex"); const envPath = path.join(options.repoRoot, ".env.local"); const current = fs.existsSync(envPath) ? fs.readFileSync(envPath, "utf8") : ""; const prefix = current && !current.endsWith("\n") ? "\n" : ""; - atomicWrite(envPath, `${current}${prefix}${ENV_KEYS.bearerToken}=${bearerToken}\n`); + atomicWrite(envPath, `${current}${prefix}${ENV_KEYS.token}=${bearerToken}\n`); return { ...options, bearerToken }; } @@ -819,7 +792,7 @@ const ZAI_SERVERS = ["web-search-prime", "web-reader", "zread", "zai-mcp-server" // One catalog, rendered in each client's documented schema. function clientServers(kind, options, url) { const catalog = { - "unity-mcp": { url, token: options.bearerToken }, + ...(url && { "unity-mcp": { url, token: options.bearerToken } }), github: { url: GITHUB_MCP_URL, token: options.githubToken }, git: { command: "mcp-server-git", args: ["--repository", options.repoRoot] }, fetch: { command: "mcp-server-fetch", args: [] } @@ -879,10 +852,14 @@ function clientServers(kind, options, url) { ); } export function configure(inputOptions, endpoint, beforeCommit) { - const options = ensureBearerToken(inputOptions); - const url = endpointUrl({ ...endpoint, host: options.clientHost ?? endpoint.host }); + const disabled = inputOptions.unityEnabled === false; + const options = disabled ? inputOptions : ensureBearerToken(inputOptions); + const url = disabled + ? null + : endpointUrl({ ...endpoint, host: options.clientHost ?? endpoint.host }); const paths = clientConfigPaths(options.repoRoot); - const removed = options.zaiToken ? [] : ZAI_SERVERS; + const removed = options.zaiToken ? [] : [...ZAI_SERVERS]; + if (disabled) removed.push("unity-mcp"); const writes = Object.entries(paths).map(([kind, file]) => { const servers = clientServers(kind, options, url); if (kind === "codex") { @@ -1382,6 +1359,8 @@ async function resolveEndpoint(options, runtime = {}) { } export async function runProbe(options, runtime = {}) { + if (options.unityEnabled === false) + fail("Unity MCP is disabled. Set UNITY_MCP_ENABLED=true and reconfigure to probe the host."); const { found, attempts } = await resolveEndpoint(options, { ...runtime, readiness: "editor" }); if (!found) { fail( @@ -1396,23 +1375,24 @@ export async function runProbe(options, runtime = {}) { } export async function runConfigure(options, runtime = {}) { - const { endpoint, attempts, found } = options.offline + const skipDiscovery = options.offline || options.unityEnabled === false; + const { endpoint, attempts, found } = skipDiscovery ? { endpoint: options, attempts: [] } : await resolveEndpoint(options, runtime); // Never mint a replacement token when a running bridge rejected the current one. const unauthorized = found ? undefined : attempts.find((a) => a.status === "unauthorized"); if (unauthorized) { fail( - `Unity MCP at ${unauthorized.url} rejected the bearer token (${unauthorized.detail}). Nothing was written and no token was generated: copy ${ENV_KEYS.bearerToken} from the host's .env.local into ${path.join(options.repoRoot, ".env.local")}, or pass --token, then re-run configure.` + `Unity MCP at ${unauthorized.url} rejected the bearer token (${unauthorized.detail}). Nothing was written and no token was generated: copy ${ENV_KEYS.token} from the host's .env.local into ${path.join(options.repoRoot, ".env.local")}, or pass --token, then re-run configure.` ); } - if (!found && !options.offline && attempts.some((attempt) => attempt.status !== "unreachable")) { + if (!found && !skipDiscovery && attempts.some((attempt) => attempt.status !== "unreachable")) { fail( `A listener did not complete Unity MCP initialization. Nothing was written. Check the host bridge and port forwards, or use --offline to configure explicitly. Attempts:\n${describeAttempts(attempts)}` ); } const target = endpoint ?? options; - if (!found && !options.offline) { + if (!found && !skipDiscovery) { console.warn( `No Unity MCP endpoint completed initialization; configuring ${endpointUrl(target)} anyway. Attempts:\n${describeAttempts(attempts)}` ); @@ -1420,7 +1400,9 @@ export async function runConfigure(options, runtime = {}) { const { url, written } = configure(options, target); const summary = written.map((filePath) => path.relative(options.repoRoot, filePath)).join(", ") || "no changes"; - console.log(`Configured agent MCP servers; Unity endpoint ${url} (${summary}).`); + console.log( + `Configured agent MCP servers; ${url ? `Unity endpoint ${url}` : "Unity MCP disabled"} (${summary}).` + ); if (!options.zaiToken) console.log("Z.AI servers need Z_AI_API_KEY or ZAI_API_KEY in .env.local."); return url; @@ -1474,6 +1456,7 @@ function usage() { " --client-host HOST Address written to client configs (independent of discovery)", " --port PORT Endpoint port; the only port discovery probes", " --path PATH Streamable HTTP path (default: /mcp)", + " UNITY_MCP_ENABLED=false Omit Unity from client configs and disable host probes", " --offline Write configs without network access (configure only)", " --no-discover Probe only the configured host/port, not the fallbacks", " --bind HOST Bridge bind interface (default: 0.0.0.0)", @@ -1510,7 +1493,7 @@ export async function main(argv = process.argv.slice(2)) { if (args._.length) { fail(`Unexpected argument: ${args._[0]}`); } - const options = resolveOptions(args); + const options = resolveOptions({ ...args, command }); if (options.offline && command !== "configure") fail("--offline is only valid for configure"); await commands[command](options); } diff --git a/scripts/release/asset-store-submission.js b/scripts/release/asset-store-submission.js index d643c1b4e..09c1e59d7 100644 --- a/scripts/release/asset-store-submission.js +++ b/scripts/release/asset-store-submission.js @@ -163,9 +163,10 @@ function buildChecklist({ mode, pkg, tag, packageName, unitypackageName, changel 1. Open a clean project in an editor version supported by the installed official UPM publishing tool. 1. In \`Window > Package Manager\`, choose \`Add package from tarball...\` and select \`${packageName}\` from this artifact. 1. Open \`Window > Tools > Asset Store > Validator\`, select the UPM validation type, and validate the installed package. -1. Open \`Window > Tools > Asset Store > Uploader\`, select the \`UPM Packages\` tab, select ${pkg.name} ${pkg.version}, and upload it. -1. After Unity publishes the version, use a clean project where it is not installed. In Package Manager Version History, expand this version and confirm its notes match \`EXPECTED-UPM-FIELDS.json\`. -1. If supported Unity tooling exposes the version manifest, compare its field values with \`EXPECTED-UPM-FIELDS.json\`. Do not query undocumented endpoints.`; +1. Open \`Window > Tools > Asset Store > Uploader\`, select the \`UPM Packages\` tab, select ${pkg.name} ${pkg.version}, and upload it.`; + const upmPublicationChecks = isClassic ? "" : ` +1. In a clean project where the package is absent, expand this version in Package Manager Version History. Confirm its notes match \`EXPECTED-UPM-FIELDS.json\`. +1. If supported Unity tooling exposes the version manifest, compare its field values with \`EXPECTED-UPM-FIELDS.json\`.`; return `${heading} Package: ${pkg.displayName || pkg.name} (${pkg.name}) @@ -188,7 +189,11 @@ ${uploadSteps} 1. Read all listing copy, including the AI disclosure, and confirm it describes the submitted content accurately. 1. Paste the release notes from the changelog excerpt below. 1. Submit for Unity review. -1. Verify the live listing's version, free price, disclosure, links, screenshots, and downloadable package. + +## After Publication + +1. Verify the live listing's version, free price, disclosure, links, screenshots, and downloadable package.${upmPublicationChecks} +1. Install the published package in a clean project and confirm the reported version and a clean import. ## Changelog Excerpt diff --git a/scripts/unity/__tests__/editor-process-watchdog.test.ps1 b/scripts/unity/__tests__/editor-process-watchdog.test.ps1 index e2db2d78d..bac0ac967 100644 --- a/scripts/unity/__tests__/editor-process-watchdog.test.ps1 +++ b/scripts/unity/__tests__/editor-process-watchdog.test.ps1 @@ -55,6 +55,52 @@ try { } } + # Fault injection: the host stalls while forwarding the last line from an + # exited child. Its EOFs must win over the observer's expired deadline. + $forwardingScript = Join-Path $fixture 'slow-forwarding.ps1' + $forwardingLog = Join-Path $fixture 'slow-forwarding.log' + [IO.File]::WriteAllText($forwardingScript, @" +[Console]::Error.WriteLine('forwarding stderr retained') +[Console]::Out.WriteLine('$terminal') +[Console]::Out.WriteLine('forwarding stdout retained') +exit 7 +"@) + & { + $forwarding = @{ ChildId = 0; ExitConfirmed = $false } + function Write-Host { + param([Parameter(Position = 0, ValueFromRemainingArguments = $true)][object[]]$Object) + $line = $Object -join ' ' + if ($line -match '^::notice::slow forwarding process settings: pid=(\d+),') { + $forwarding.ChildId = [int]$Matches[1] + } + if ($line -ceq 'forwarding stdout retained') { + if ($forwarding.ChildId -le 0) { throw 'Slow forwarding lost the process ID.' } + $child = Get-Process -Id $forwarding.ChildId -ErrorAction SilentlyContinue + if ($child) { + try { + if (-not $child.WaitForExit(3000)) { throw 'Slow forwarding child did not exit.' } + } finally { $child.Dispose() } + } + $forwarding.ExitConfirmed = $true + $blockedOutput = [Threading.ManualResetEventSlim]::new($false) + try { [void]$blockedOutput.Wait(1250) } finally { $blockedOutput.Dispose() } + } + Microsoft.PowerShell.Utility\Write-Host $line + } + + $details = $null + $result = Invoke-UnityEditor -EditorPath $pwsh ` + -Arguments @('-NoLogo', '-NoProfile', '-File', $forwardingScript) ` + -Label 'slow forwarding' -LogPath $forwardingLog -TimeoutSeconds 15 -ShutdownTimeoutSeconds 1 ` + -ProcessResultRef ([ref]$details) + $text = Get-Content -LiteralPath $forwardingLog -Raw + if (-not $forwarding.ExitConfirmed -or $result -ne 7 -or $details.ExitCode -ne 7 -or + $details.TimedOut -or -not $details.CompletionObserved -or + $text -notmatch 'forwarding stdout retained' -or $text -notmatch 'forwarding stderr retained') { + throw "Slow forwarding lost a completed child or its output: $($details | ConvertTo-Json -Compress)" + } + } + $childScript = Join-Path $fixture 'child-tree.ps1' $treePidPath = Join-Path $fixture 'tree-child.pid' [System.IO.File]::WriteAllText($childScript, @' @@ -89,7 +135,8 @@ Wait-Event -Timeout 30 | Out-Null $childProcess = Get-Process -Id ([int]$Matches[1]) -ErrorAction SilentlyContinue if ($childProcess) { try { - if (-not $childProcess.HasExited) { throw 'Shutdown left its child process alive.' } + # Wait for the asynchronous tree termination before emergency cleanup can intervene. + if (-not $childProcess.WaitForExit(5000)) { throw 'Shutdown left its child process alive.' } } finally { $childProcess.Dispose() } } } finally { diff --git a/scripts/unity/create_unitypackage.py b/scripts/unity/create_unitypackage.py index 708a88328..62c580dda 100644 --- a/scripts/unity/create_unitypackage.py +++ b/scripts/unity/create_unitypackage.py @@ -263,6 +263,13 @@ def stage_packed_payload(repo_root: Path, scratch: Path, tarball: Path | None = shutil.copytree(source, destination) else: shutil.copy2(source, destination) + + # Keep the root README's local sample links aligned with the classic layout. + readme = staged_root / "README.md" + contents = readme.read_bytes() + updated = contents.replace(b"](Samples~/", b"](Samples/") + if updated != contents: + readme.write_bytes(updated) return staged_root diff --git a/scripts/unity/ensure-editor.ps1 b/scripts/unity/ensure-editor.ps1 index 57b692a6f..3f97646e3 100644 --- a/scripts/unity/ensure-editor.ps1 +++ b/scripts/unity/ensure-editor.ps1 @@ -1132,7 +1132,8 @@ function Invoke-UnityCliCaptureWithTimeout { [int]$TimeoutSeconds = 2700, [string]$TimeoutKnob = 'DXM_ENSURE_EDITOR_INSTALL_TIMEOUT_SECONDS', [int]$StallSeconds = -1, - [string]$StallKnob = 'DXM_ENSURE_EDITOR_PROGRESS_STALL_SECONDS' + [string]$StallKnob = 'DXM_ENSURE_EDITOR_PROGRESS_STALL_SECONDS', + [System.Collections.IDictionary]$HeartbeatTiming ) # Default the stall threshold from the env-aware helper when the caller did @@ -1207,8 +1208,16 @@ function Invoke-UnityCliCaptureWithTimeout { $proc = New-Object System.Diagnostics.Process $proc.StartInfo = $psi + # The heartbeat fixture compares shared monotonic timestamps without relying on either pipe. + if ($null -ne $HeartbeatTiming) { + $HeartbeatTiming['SpawnRequested'] = [Diagnostics.Stopwatch]::GetTimestamp() + } [void]$proc.Start() $clock = [System.Diagnostics.Stopwatch]::StartNew() + if ($null -ne $HeartbeatTiming) { + $HeartbeatTiming['ClockStart'] = [Diagnostics.Stopwatch]::GetTimestamp() + $HeartbeatTiming['Frequency'] = [Diagnostics.Stopwatch]::Frequency + } # Keep ONE outstanding async line read per stream and poll both from the # main thread. A completed read whose Result is $null means that stream @@ -1300,6 +1309,12 @@ function Invoke-UnityCliCaptureWithTimeout { # window. Tree-kills with the distinct stall sentinel so the failure # diagnostic can distinguish output silence from wall-clock expiry. if ($stallEnabled -and ($elapsedMs - $lastActivityMs) -ge ([int64]$StallSeconds * 1000)) { + if ($null -ne $HeartbeatTiming) { + $HeartbeatTiming['Cutoff'] = [Diagnostics.Stopwatch]::GetTimestamp() + $HeartbeatTiming['CutoffElapsedMs'] = $elapsedMs + $HeartbeatTiming['StdoutReadCompleted'] = $oTask.IsCompleted + $HeartbeatTiming['StderrReadCompleted'] = $eTask.IsCompleted + } $stalled = $true $timedOut = $true try { diff --git a/scripts/unity/render-perf-doc.js b/scripts/unity/render-perf-doc.js index 7c963f175..3c5c67eca 100644 --- a/scripts/unity/render-perf-doc.js +++ b/scripts/unity/render-perf-doc.js @@ -320,51 +320,8 @@ function isMeasuredInteger(value) { return Number.isFinite(parsed) && parsed >= 0; } -function preferredComparisonMetricScope(comparisonByScope, selectMetric) { - for (const scope of SCOPE_ORDER) { - const byCell = comparisonByScope.get(scope); - if (!byCell) { - continue; - } - for (const row of byCell.values()) { - if (isMeasuredInteger(selectMetric(row))) { - return scope; - } - } - } - return preferredComparisonScope(comparisonByScope); -} - -function anyScopeMeasures(comparisonByScope, selectMetric) { - return [...comparisonByScope.values()].some((byCell) => - [...byCell.values()].some((row) => isMeasuredInteger(selectMetric(row))) - ); -} - -function buildMetricComparison( - comparisonByScope, - throughputScope, - throughputByCell, - scope, - formatCell -) { - let selectedScope = scope; - let byCell = comparisonByScope.get(selectedScope); - let table = byCell ? buildComparisonMatrix(byCell, formatCell, { bold: false }) : null; - - // Defense-in-depth: never push a null metric table. - if (!table) { - selectedScope = throughputScope; - byCell = throughputByCell; - table = buildComparisonMatrix(byCell, formatCell, { bold: false }); - } - - const sample = byCell.values().next().value; - return { - scope: selectedScope, - platform: sample ? sample.platform : undefined, - table - }; +function measuresMetric(byCell, selectMetric) { + return [...(byCell?.values() ?? [])].some((row) => isMeasuredInteger(selectMetric(row))); } // Throughput matrices bold per-scenario display-precision winners. @@ -423,6 +380,18 @@ function buildComparisonMatrix(byCell, formatCell, { bold }) { return alignTable(dataRows); } +function formatMessagePipeRatio(row, reference) { + if (!row.commit || row.commit !== reference?.commit || row.platform !== reference.platform) { + return "N/A"; + } + const rate = Number(row.emitsPerSecond); + const referenceRate = Number(reference.emitsPerSecond); + const ratio = (rate / referenceRate) * 100; + return rate > 0 && referenceRate > 0 && Number.isFinite(referenceRate) && Number.isFinite(ratio) + ? `${ratio.toFixed(1)}%` + : "N/A"; +} + function buildComparisonSections(comparisonByScope) { const throughputScope = preferredComparisonScope(comparisonByScope); if (!throughputScope) { @@ -454,7 +423,8 @@ function buildComparisonSections(comparisonByScope) { ? `${formatMeasuredInteger(row.gcAllocations)} measured per 10k ops` : scenarioKey === "SubUnsub" ? "Allocates; count unmeasured" - : "0 per emit contract; count unmeasured" + : "0 per emit contract; count unmeasured", + formatMessagePipeRatio(row, throughputByCell.get(`MessagePipe|${scenarioKey}`)) ] ]; }); @@ -465,10 +435,17 @@ function buildComparisonSections(comparisonByScope) { "", "Time per operation is the reciprocal of the measured rate. Allocation evidence uses", "measured counts when the selected scope exposes them; otherwise it reports the", - "steady-state contract and marks the count unmeasured.", + "steady-state contract and marks the count unmeasured. The MessagePipe percentages", + "use matching commit and platform rows. Independent-build uncertainty is unmeasured.", "", alignTable([ - ["Scenario", "DxMessaging rate", "Time / operation", "GC allocation evidence"], + [ + "Scenario", + "DxMessaging rate", + "Time / operation", + "GC allocation evidence", + "Share of MessagePipe rate" + ], ...summaryRows ]) ]); @@ -484,20 +461,27 @@ function buildComparisonSections(comparisonByScope) { ["GC allocations", (row) => row.gcAllocations, formatRowAllocations], ["GC allocated bytes", (row) => row.gcAllocatedBytes, formatRowBytes] ]) { - if (!anyScopeMeasures(comparisonByScope, selectMetric)) { - continue; + const hasMetric = (byCell) => measuresMetric(byCell, selectMetric); + let scope = SCOPE_ORDER.find((candidate) => hasMetric(comparisonByScope.get(candidate))); + if (!scope) { + if (![...comparisonByScope.values()].some(hasMetric)) { + continue; + } + scope = throughputScope; } - const result = buildMetricComparison( - comparisonByScope, - throughputScope, - throughputByCell, - preferredComparisonMetricScope(comparisonByScope, selectMetric), - formatMetric - ); + let byCell = comparisonByScope.get(scope); + let table = buildComparisonMatrix(byCell, formatMetric, { bold: false }); + // A selected scope can contain no recognized comparison technology. + if (!table) { + scope = throughputScope; + byCell = throughputByCell; + table = buildComparisonMatrix(byCell, formatMetric, { bold: false }); + } + const platform = byCell.values().next().value?.platform; sections.push([ - `### Library comparison - ${metric} per 10k ops (${scopeLabel(result.scope, result.platform)})`, + `### Library comparison - ${metric} per 10k ops (${scopeLabel(scope, platform)})`, "", - result.table + table ]); } @@ -574,19 +558,6 @@ function firstSelectedCommit(selection) { return "unknown"; } -function countOccurrences(content, needle) { - let count = 0; - let from = 0; - for (;;) { - const at = content.indexOf(needle, from); - if (at === -1) { - return count; - } - count += 1; - from = at + needle.length; - } -} - function locateMarkers(content) { const beginIndex = content.indexOf(BEGIN_MARKER); const endIndex = content.indexOf(END_MARKER); @@ -597,8 +568,8 @@ function locateMarkers(content) { ); } // Refuse duplicate regions; first-match slicing would leave stale generated docs. - const beginCount = countOccurrences(content, BEGIN_MARKER); - const endCount = countOccurrences(content, END_MARKER); + const beginCount = content.split(BEGIN_MARKER).length - 1; + const endCount = content.split(END_MARKER).length - 1; if (beginCount !== 1 || endCount !== 1) { throw new Error( `Expected exactly one AUTOGENERATED dispatch-throughput marker pair, ` + diff --git a/scripts/unity/run-ci-tests.ps1 b/scripts/unity/run-ci-tests.ps1 index 25a49bb9a..dd1a8c512 100644 --- a/scripts/unity/run-ci-tests.ps1 +++ b/scripts/unity/run-ci-tests.ps1 @@ -5406,13 +5406,13 @@ function Invoke-ProcessWithTreeKillTimeout { if ($null -eq $line) { $oDone = $true } else { + $oTask = $outReader.ReadLineAsync() Write-Host $line $buffer.Add([string]$line) if (-not $completionObserved -and $CompletionPattern -and $line -cmatch $CompletionPattern) { $completionObserved = $true $shutdownDeadline = [DateTime]::UtcNow.AddSeconds($ShutdownTimeoutSeconds) } - $oTask = $outReader.ReadLineAsync() } $progressed = $true } @@ -5422,13 +5422,13 @@ function Invoke-ProcessWithTreeKillTimeout { if ($null -eq $line) { $eDone = $true } else { + $eTask = $errReader.ReadLineAsync() Write-Host $line $buffer.Add([string]$line) if (-not $completionObserved -and $CompletionPattern -and $line -cmatch $CompletionPattern) { $completionObserved = $true $shutdownDeadline = [DateTime]::UtcNow.AddSeconds($ShutdownTimeoutSeconds) } - $eTask = $errReader.ReadLineAsync() } $progressed = $true } @@ -5441,8 +5441,24 @@ function Invoke-ProcessWithTreeKillTimeout { # A quick-exit parent cannot identify a reparented descendant that # still holds a pipe. Mirror ensure-editor.ps1: preserve diagnostics # but never report this as confirmed tree cleanup or allow retry. + $parentExited = $proc.HasExited + if ($parentExited) { + # Forwarding output can block while the child and both + # pipes finish. Accept EOFs that are already available. + $stdoutClosed = $oDone -or ( + $oTask.Status -eq [Threading.Tasks.TaskStatus]::RanToCompletion -and $null -eq $oTask.Result + ) + $stderrClosed = $eDone -or ( + $eTask.Status -eq [Threading.Tasks.TaskStatus]::RanToCompletion -and $null -eq $eTask.Result + ) + if ($stdoutClosed -and $stderrClosed) { + $oDone = $true + $eDone = $true + break + } + } $timedOut = $true - $terminationUnconfirmed = [bool]$proc.HasExited + $terminationUnconfirmed = $parentExited if ($completionObserved -and $shutdownDeadline -le $deadline) { Write-Host "::warning::$Label did not close its process/output streams within $ShutdownTimeoutSeconds seconds of its terminal message; requesting process-tree termination. Results can be accepted only after confirmed cleanup." }