diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 55e07d6c9..2507a5a2f 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -498,6 +498,28 @@ the path is a normal string literal. An unresolved ref is left un-substituted (t validator rejects it first — substitution never throws). The two seams build the reference map identically, so their plans stay byte-parity. +**The paste is escaped (string-literal rule).** The path literal is a C# *regular* string +literal, so its content is source text, not the string value, and a RawPath segment may legally +hold `\`, `"`, braces, line breaks or non-ASCII text (`RawPaths.ValidateSegment` only forbids +`/` and edge whitespace). Substitution therefore treats the literal exactly as the compiler does: + +- the `` is **decoded** (C# escapes resolved) before the map lookup, so a reference named + `a\b` is written `{{equip}}/a\\b`, and one named `q"t` is written `{{equip}}/q\"t`; +- the resolved RawPath is **encoded** (`EquipmentScriptPaths.EscapeForRegularLiteral`: `\` and `"` + backslash-escaped; CR/LF/U+0085/U+2028/U+2029, other control characters and unpaired surrogates as + `\uXXXX`; braces and non-ASCII untouched) when it is pasted back, so `GetTag` receives the exact + RawPath — a device named `de\qv` neither breaks compilation nor, for `x\vy`, silently turns + `\v` into a vertical tab; +- `ExtractDependencyRefs` (the mux subscription keys) decodes the same way, so the dependency + ref is the runtime string value, not the escaped source text; +- the editor's `OTSCRIPT_EQUIPREF` diagnostic and completion use the same scan + (`EquipmentScriptPaths.FindEquipReferenceLiterals`), and completion inserts the escaped form. + +A `` with a malformed escape (`\e`) is left as written for the compiler to report. Only +regular `"…"` literals are path literals: a `{{equip}}/…` token inside a verbatim (`@"…"`), +interpolated (`$"…"`) or raw (`"""…"""`) literal is **not substituted** (and not checked) — keep the +token in a regular literal. + --- ## Input quality: what a script sees, and when it runs at all diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index d740c7e86..f2c93b3c3 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -55,7 +55,7 @@ The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type a The deploy gate compiles every script the deployment will run before the deployment is sealed (lmxopcua#971 follow-up), so **editor rejects ⇔ publish rejects** holds for deploys too — before this, `DraftValidator` never compiled a script, and a refused script surfaced only as a Bad tag or a failed alarm load after the deploy. - **What is checked** is what runs: **enabled** VirtualTags (as `VirtualTagContext → object?`), **enabled** scripted-alarm predicates (`DependencyExtractor` first, as the alarm load does, then `AlarmPredicateContext → bool`), and Calculation tags of **enabled** Calculation drivers (`VirtualTagContext → object?`). Disabled ones are skipped (they never compile at runtime); a passthrough mirror VirtualTag/Calculation body is skipped (the runtime never compiles it); orphan scripts are not checked. The same source can fail as one seam and pass as another — `return 1.5;` is a fine VirtualTag and a refused predicate. -- **`{{equip}}` is resolved first**, through the same `EquipmentReferenceMap` + RawPath resolver both compose seams use. When `EquipmentScriptPaths.SubstitutionPreservesCompilation` proves the substitution only rewrites escape-free string-literal text (it cannot change a compile), the template is compiled once for every equipment instead of once per equipment; otherwise the resolved source is compiled. That fallback is not theoretical: a RawPath segment may contain `\` or `"`, and substitution pastes it into a C# literal unescaped, so `{{equip}}/speed` over a device named `de\qv` does not compile — the gate reports it. +- **`{{equip}}` is resolved first**, through the same `EquipmentReferenceMap` + RawPath resolver both compose seams use. When `EquipmentScriptPaths.SubstitutionPreservesCompilation` proves the substitution cannot change a compile, the template is compiled once for every equipment instead of once per equipment; otherwise the resolved source is compiled. Substitution escapes what it pastes (`EscapeForRegularLiteral`: a RawPath segment may contain `\` or `"`), so a device named `de\qv` compiles and `GetTag` receives the exact RawPath; the check is a verified round trip, and the resolved-source fallback remains for any case it cannot prove. - **Same compile as the runtime.** `ScriptEvaluator.Verify` and `CompileToImage` share one private factory (wrap, injection guard, sandbox compile, `ForbiddenTypeAnalyzer`); `Verify` stops before the stack-guard rewrite and the emit. Problems carry the runtime's own text (`compile error: …`, `sandbox violation: …`, `dependency extraction rejected — …`). - **Shape.** ControlPlane (which owns the gate) is Roslyn-free: it depends on `IDeployScriptChecker` (`Core.Scripting.Abstractions`); the Host binds `RoslynDeployScriptChecker` on admin nodes. No checker registered ⇒ the gate is skipped. Verdicts are cached by (compile identity, source SHA-256) for the life of the process (VirtualTag and Calculation share an identity), and distinct uncached sources compile in parallel (half the cores, 1–8). The compose warms that cache from the `Script`/`VirtualTag`/`ScriptedAlarm` tables **before** opening its snapshot transaction and compose lock, then runs the authoritative check on the same snapshot it validates and composes (R03:3.2) — normally all cache hits. An internal checker failure skips the gate for that deploy (logged, noted in the accepted message), never blocks it. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentScriptPaths.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentScriptPaths.cs index 531c459d7..1420038af 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentScriptPaths.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentScriptPaths.cs @@ -26,9 +26,19 @@ public static class EquipmentScriptPaths /// The reserved equipment reference-relative prefix — the token stem plus the slash joint. public const string EquipTokenPrefix = "{{equip}}/"; - // ctx.GetTag("ref") — reads only; the dependency graph subscribes to exactly these. + // The CONTENT of one C# REGULAR string literal (the text between the quotes): any run of non-quote, + // non-backslash, non-line-break characters and backslash-escape pairs. Escape-aware on purpose — a naive + // [^"]* stops at the \" of an escaped quote and mis-reads the literal. + private const string RegularLiteralContent = @"(?:[^""\\\r\n]|\\.)"; + + // Whole-string check that text is nothing but well-formed regular-literal content (no raw quote / line break). + private static readonly Regex LiteralContentOnlyRegex = + new(@"\A" + RegularLiteralContent + @"*\z", RegexOptions.Compiled); + + // ctx.GetTag("ref") — reads only; the dependency graph subscribes to exactly these. The captured group is the + // literal's SOURCE text; ExtractDependencyRefs decodes it to the runtime string value. private static readonly Regex GetTagRefRegex = - new(@"ctx\s*\.\s*GetTag\s*\(\s*""([^""]+)""\s*\)", RegexOptions.Compiled); + new(@"ctx\s*\.\s*GetTag\s*\(\s*""(" + RegularLiteralContent + @"+)""\s*\)", RegexOptions.Compiled); // {TagPath} message-template token — a single-brace {…} run. The negative look-behind/-ahead // reject the reserved {{equip}} double-brace form (and any other doubled brace), so "{A.X}" @@ -40,7 +50,7 @@ public static class EquipmentScriptPaths // three parts (prefix, content, closing quote) so token substitution touches ONLY the // literal content (never a comment, Logger string, or other code). private static readonly Regex PathLiteralRegex = - new(@"(ctx\s*\.\s*(?:GetTag|SetVirtualTag)\s*\(\s*"")([^""]*)("")", RegexOptions.Compiled); + new(@"(ctx\s*\.\s*(?:GetTag|SetVirtualTag)\s*\(\s*"")(" + RegularLiteralContent + @"*)("")", RegexOptions.Compiled); // {{equip}}/ occurrence in FREE TEXT (message templates). runs until the next // delimiter that cannot appear in an intra-literal RawPath segment used inline in a template — @@ -73,6 +83,14 @@ public static class EquipmentScriptPaths /// or the token is absent (so every existing script — none of which use the token — is byte-unchanged). /// An <RefName> absent from the map is left un-substituted (never throws) — the validator /// rejects it first at deploy. + /// Literal escaping. The path literal is a C# regular string literal, so its content is + /// C# source text, not the string value. The <RefName> is therefore DECODED (C# escapes + /// resolved) before the lookup — a reference named a\b is written {{equip}}/a\\b — and the + /// resolved RawPath is ENCODED () when pasted back, so a RawPath segment + /// containing \, ", a line break or a control character reaches GetTag byte-for-byte + /// instead of breaking the literal or silently turning \v into a vertical tab. Only regular + /// "…" literals are recognised (verbatim @"…", interpolated $"…" and raw + /// """…""" literals are not path literals here and are never rewritten). /// /// The script source. /// The equipment's reference map: effective name → backing-tag RawPath. @@ -88,14 +106,15 @@ public static class EquipmentScriptPaths } /// - /// True when cannot change how COMPILES: every - /// path-literal content it would replace, and every replacement RawPath, is free of \, ", CR and LF. - /// Substitution only ever rewrites the content of a ctx.GetTag/ctx.SetVirtualTag string literal; - /// with no escape sequence, quote or line break on either side the literal stays one well-formed regular string - /// token of type string, and a C# compile (binding, overload resolution, the sandbox analyzer) never depends - /// on such a literal's characters. So the resolved source compiles exactly as the template does — which lets the - /// deploy-time script compile gate (lmxopcua#971 follow-up) compile a template once instead of once per - /// equipment. False ⇒ compile the resolved source itself. Identity cases (no token, empty map) are true. + /// True when cannot change how COMPILES. + /// Substitution only rewrites the content of a ctx.GetTag/ctx.SetVirtualTag regular string literal, + /// and the replacement is always encoded with , so the literal stays one + /// well-formed token of type string; a C# compile (binding, overload resolution, the sandbox analyzer) + /// never depends on such a literal's characters. So the resolved source compiles exactly as the template does — + /// which lets the deploy-time script compile gate (lmxopcua#971 follow-up) compile a template once instead of once + /// per equipment. That is verified, not assumed: each replacement must be well-formed literal content that + /// decodes back to the exact RawPath; false ⇒ compile the resolved source itself. Identity cases (no token, + /// empty map) are true. /// /// The template script source. /// The owning equipment's reference map: effective name → backing-tag RawPath. @@ -106,24 +125,172 @@ public static class EquipmentScriptPaths if (!source.Contains(EquipTokenPrefix, StringComparison.Ordinal)) return true; foreach (Match m in PathLiteralRegex.Matches(source)) { - var content = m.Groups[2].Value; - var replaced = SubstituteContent(content, referenceMap); - if (ReferenceEquals(replaced, content) || replaced == content) continue; - if (!IsPlainLiteralText(content) || !IsPlainLiteralText(replaced)) return false; + if (!TryResolveReference(m.Groups[2].Value, referenceMap, out var rawPath)) continue; + var encoded = EscapeForRegularLiteral(rawPath); + if (!LiteralContentOnlyRegex.IsMatch(encoded) + || !TryDecodeRegularLiteral(encoded, out var roundTrip) + || !string.Equals(roundTrip, rawPath, StringComparison.Ordinal)) + return false; } return true; } - private static bool IsPlainLiteralText(string text) => text.AsSpan().IndexOfAny("\\\"\r\n") < 0; + // Resolve one path-literal content (C# source text) to its backing RawPath. The content must start with the + // {{equip}}/ prefix; the remainder is DECODED to the reference-name string value before the lookup. An + // undecodable remainder (an invalid escape the compiler will itself reject) or an unknown name is unresolved. + private static bool TryResolveReference( + string content, IReadOnlyDictionary referenceMap, out string rawPath) + { + rawPath = string.Empty; + if (!content.StartsWith(EquipTokenPrefix, StringComparison.Ordinal)) return false; + var refSource = content.Substring(EquipTokenPrefix.Length); + if (refSource.Length == 0) return false; + if (!TryDecodeRegularLiteral(refSource, out var refName) || refName.Length == 0) return false; + if (!referenceMap.TryGetValue(refName, out var found)) return false; + rawPath = found; + return true; + } // Substitute the reference-relative token inside a single path-literal's content. The content is one // whole tag path; when it starts with the {{equip}}/ prefix the remainder is the reference name. - private static string SubstituteContent(string content, IReadOnlyDictionary referenceMap) + private static string SubstituteContent(string content, IReadOnlyDictionary referenceMap) => + TryResolveReference(content, referenceMap, out var rawPath) ? EscapeForRegularLiteral(rawPath) : content; + + /// + /// Encode as the CONTENT of a C# regular string literal (the text between the quotes) + /// so the literal's value is exactly : \ and " are backslash-escaped, the + /// C# line-break characters (CR, LF, U+0085, U+2028, U+2029), other control characters and unpaired surrogates + /// become \uXXXX. Everything else — including {/} and non-ASCII text — is left as is + /// (a regular literal is not interpolated). The inverse of . + /// + /// The string value to embed in a regular string literal. + /// The literal content that evaluates to . + public static string EscapeForRegularLiteral(string value) { - if (!content.StartsWith(EquipTokenPrefix, StringComparison.Ordinal)) return content; - var refName = content.Substring(EquipTokenPrefix.Length); - if (refName.Length == 0) return content; - return referenceMap.TryGetValue(refName, out var rawPath) ? rawPath : content; + if (string.IsNullOrEmpty(value)) return value; + System.Text.StringBuilder? sb = null; + for (var i = 0; i < value.Length; i++) + { + var c = value[i]; + string? rep = null; + if (c == '\\') rep = "\\\\"; + else if (c == '"') rep = "\\\""; + else if (c < ' ' || c == '\u007f' || c == '\u0085' || c == '\u2028' || c == '\u2029' + || (char.IsSurrogate(c) && !IsPairedSurrogate(value, i))) + rep = "\\u" + ((int)c).ToString("X4", System.Globalization.CultureInfo.InvariantCulture); + if (rep is null) + { + sb?.Append(c); + continue; + } + sb ??= new System.Text.StringBuilder(value.Length + 8).Append(value, 0, i); + sb.Append(rep); + } + return sb?.ToString() ?? value; + } + + private static bool IsPairedSurrogate(string s, int i) => + char.IsHighSurrogate(s[i]) ? i + 1 < s.Length && char.IsLowSurrogate(s[i + 1]) + : i > 0 && char.IsHighSurrogate(s[i - 1]); + + /// + /// Decode the CONTENT of a C# regular string literal to its string value: the simple escapes + /// (\' \" \\ \0 \a \b \f \n \r \t \v), \uXXXX, \UXXXXXXXX and \x + 1–4 hex digits. + /// Fails (false) on a malformed or unknown escape or a dangling backslash — the same inputs the C# compiler + /// rejects — so a caller can leave such a literal untouched and let the compile report it. + /// + /// The literal content (the text between the quotes). + /// The decoded value; the empty string when decoding fails. + /// True when every escape in is well-formed. + public static bool TryDecodeRegularLiteral(string content, out string value) + { + value = string.Empty; + if (content is null) return false; + if (content.IndexOf('\\') < 0) { value = content; return true; } + var sb = new System.Text.StringBuilder(content.Length); + for (var i = 0; i < content.Length; i++) + { + var c = content[i]; + if (c != '\\') { sb.Append(c); continue; } + if (++i >= content.Length) return false; + switch (content[i]) + { + case '\'': sb.Append('\''); break; + case '"': sb.Append('"'); break; + case '\\': sb.Append('\\'); break; + case '0': sb.Append('\0'); break; + case 'a': sb.Append('\a'); break; + case 'b': sb.Append('\b'); break; + case 'f': sb.Append('\f'); break; + case 'n': sb.Append('\n'); break; + case 'r': sb.Append('\r'); break; + case 't': sb.Append('\t'); break; + case 'v': sb.Append('\v'); break; + case 'u': + if (!TryHex(content, i + 1, 4, 4, out var u, out var uLen)) return false; + sb.Append((char)u); + i += uLen; + break; + case 'U': + if (!TryHex(content, i + 1, 8, 8, out var big, out var bigLen) + || big > 0x10FFFF || (big >= 0xD800 && big <= 0xDFFF)) return false; + sb.Append(char.ConvertFromUtf32((int)big)); + i += bigLen; + break; + case 'x': + if (!TryHex(content, i + 1, 1, 4, out var x, out var xLen)) return false; + sb.Append((char)x); + i += xLen; + break; + default: return false; + } + } + value = sb.ToString(); + return true; + } + + private static bool TryHex(string s, int start, int min, int max, out long value, out int length) + { + value = 0; + length = 0; + while (length < max && start + length < s.Length && Uri.IsHexDigit(s[start + length])) + { + value = (value << 4) | (long)Convert.ToInt32(s[start + length].ToString(), 16); + length++; + } + return length >= min; + } + + /// One {{equip}}/<RefName> path literal found by . + /// Offset of the literal content (just after the opening quote) in the scanned source. + /// Length of the literal content in source characters. + /// The decoded reference name (the string value after the {{equip}}/ prefix). + public readonly record struct EquipReferenceLiteral(int ContentIndex, int ContentLength, string RefName); + + /// + /// The {{equip}}/<RefName> path literals of , in source order, with + /// the reference name decoded — the single scan the extraction, the validator and the editor's + /// OTSCRIPT_EQUIPREF diagnostic share, so they agree on exactly which names a script uses. Literals with + /// an empty or undecodable remainder are skipped (the compiler reports a malformed escape itself). + /// + /// The script source. + /// The token literals in source order; empty when none. + public static IReadOnlyList FindEquipReferenceLiterals(string? scriptSource) + { + if (string.IsNullOrEmpty(scriptSource) + || !scriptSource.Contains(EquipTokenPrefix, StringComparison.Ordinal)) + return Array.Empty(); + var result = new List(); + foreach (Match m in PathLiteralRegex.Matches(scriptSource)) + { + var content = m.Groups[2].Value; + if (!content.StartsWith(EquipTokenPrefix, StringComparison.Ordinal)) continue; + var refSource = content.Substring(EquipTokenPrefix.Length); + if (refSource.Length == 0 || !TryDecodeRegularLiteral(refSource, out var refName) || refName.Length == 0) + continue; + result.Add(new EquipReferenceLiteral(m.Groups[2].Index, content.Length, refName)); + } + return result; } /// @@ -143,13 +310,8 @@ public static class EquipmentScriptPaths return Array.Empty(); var seen = new HashSet(StringComparer.Ordinal); var result = new List(); - foreach (Match m in PathLiteralRegex.Matches(scriptSource)) - { - var content = m.Groups[2].Value; - if (!content.StartsWith(EquipTokenPrefix, StringComparison.Ordinal)) continue; - var refName = content.Substring(EquipTokenPrefix.Length); - if (refName.Length > 0 && seen.Add(refName)) result.Add(refName); - } + foreach (var lit in FindEquipReferenceLiterals(scriptSource)) + if (seen.Add(lit.RefName)) result.Add(lit.RefName); return result; } @@ -193,7 +355,10 @@ public static class EquipmentScriptPaths var result = new List(); foreach (Match m in GetTagRefRegex.Matches(scriptSource)) { - var r = m.Groups[1].Value; + // The captured text is the literal's SOURCE; the runtime's GetTag receives its decoded VALUE, which is + // the key the dependency mux is registered under. A malformed escape (a compile error anyway) keeps + // the source text. + var r = TryDecodeRegularLiteral(m.Groups[1].Value, out var decoded) ? decoded : m.Groups[1].Value; if (seen.Add(r)) result.Add(r); } return result; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs index 7182324c4..c0402fb88 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs @@ -167,13 +167,6 @@ public sealed class ScriptAnalysisService } } - // ctx.GetTag("…") / ctx.SetVirtualTag("…") first-arg literal — three-part capture, mirroring - // EquipmentScriptPaths.PathLiteralRegex so the editor's {{equip}}/ diagnostic is scoped to the - // SAME path literals the compose seams substitute (never a comment / logger string). - private static readonly System.Text.RegularExpressions.Regex EquipPathLiteralRegex = - new(@"(ctx\s*\.\s*(?:GetTag|SetVirtualTag)\s*\(\s*"")([^""]*)("")", - System.Text.RegularExpressions.RegexOptions.Compiled); - /// Diagnostics plus the v3 equipment-relative {{equip}}/<RefName> resolution check. /// Runs the synchronous Roslyn/policy then, when an equipment context + catalog /// are present, appends a marker for each {{equip}}/<RefName> whose <RefName> is @@ -198,17 +191,16 @@ public sealed class ScriptAnalysisService var resolvable = new HashSet(names, StringComparer.Ordinal); var markers = new List(baseResp.Markers); - foreach (System.Text.RegularExpressions.Match m in EquipPathLiteralRegex.Matches(code)) + // The shared scan the compose seams + deploy gate use: same path literals, same C#-escape decoding of + // the reference name — so a name like a\\b (source) is compared as the string a\b, exactly as substitution does. + foreach (var lit in EquipmentScriptPaths.FindEquipReferenceLiterals(code)) { - var content = m.Groups[2].Value; - if (!content.StartsWith(EquipmentScriptPaths.EquipTokenPrefix, StringComparison.Ordinal)) continue; - var refName = content.Substring(EquipmentScriptPaths.EquipTokenPrefix.Length); - if (refName.Length == 0 || resolvable.Contains(refName)) continue; + if (resolvable.Contains(lit.RefName)) continue; // Mark the whole literal content span (the {{equip}}/ path). - var span = new Microsoft.CodeAnalysis.Text.TextSpan(m.Groups[2].Index, content.Length); + var span = new Microsoft.CodeAnalysis.Text.TextSpan(lit.ContentIndex, lit.ContentLength); markers.Add(ToUserMarker(code, span, - $"'{EquipmentScriptPaths.EquipTokenPrefix}{refName}' does not resolve — this equipment has no " + - $"reference named '{refName}'. Add a matching reference or correct the path.", + $"'{EquipmentScriptPaths.EquipTokenPrefix}{lit.RefName}' does not resolve — this equipment has no " + + $"reference named '{lit.RefName}'. Add a matching reference or correct the path.", "OTSCRIPT_EQUIPREF")); } return new DiagnoseResponse(Bound(markers)); @@ -308,13 +300,14 @@ public sealed class ScriptAnalysisService var names = await _catalog.GetEquipmentReferenceNamesAsync( req.EquipmentId, pathPrefix.Substring(equipPrefix.Length), ct); return new CompletionsResponse(names - .Select(n => new CompletionItem(equipPrefix + n, equipPrefix + n, "tag path", "Field")) + .Select(n => new CompletionItem( + equipPrefix + n, equipPrefix + EquipmentScriptPaths.EscapeForRegularLiteral(n), "tag path", "Field")) .ToList()); } var paths = await _catalog.GetPathsAsync(pathPrefix, ct); return new CompletionsResponse( - paths.Select(p => new CompletionItem(p, p, "tag path", "Field")).ToList()); + paths.Select(p => new CompletionItem(p, EquipmentScriptPaths.EscapeForRegularLiteral(p), "tag path", "Field")).ToList()); } var dot = TryGetDotMembers(token, model, ct); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/EquipmentScriptPathsTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/EquipmentScriptPathsTests.cs index a0ae6e865..1e1ac5589 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/EquipmentScriptPathsTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/EquipmentScriptPathsTests.cs @@ -264,26 +264,146 @@ public class EquipmentScriptPathsTests [InlineData("return ctx.GetTag(\"{{equip}}/Missing\").Value;")] // unresolved: unchanged [InlineData("ctx.SetVirtualTag(\"{{equip}}/Out\", 1); return ctx.GetTag(\"{{equip}}/A\").Value;")] [InlineData("")] - public void SubstitutionPreservesCompilation_true_when_only_escape_free_literal_text_changes(string src) + public void SubstitutionPreservesCompilation_true_for_plain_template_shapes(string src) { EquipmentScriptPaths.SubstitutionPreservesCompilation(src, RefMap).ShouldBeTrue(); } [Fact] - public void SubstitutionPreservesCompilation_false_when_a_replacement_carries_an_escape_character() + public void SubstitutionPreservesCompilation_true_when_a_replacement_carries_an_escape_character() { - // A backslash in a RawPath would become an escape sequence inside the literal — compile the resolved source. - var map = new Dictionary(StringComparer.Ordinal) { ["Speed"] = @"Cell1\Dev\Speed" }; + // A backslash / quote in a RawPath is escaped on the way in (EscapeForRegularLiteral), so the resolved source + // still compiles exactly as the template does — the gate may compile the template once. + var map = new Dictionary(StringComparer.Ordinal) { ["Speed"] = "Cell1\\de\\qv\"x/Speed" }; EquipmentScriptPaths.SubstitutionPreservesCompilation("return ctx.GetTag(\"{{equip}}/Speed\").Value;", map) - .ShouldBeFalse(); + .ShouldBeTrue(); } [Fact] - public void SubstitutionPreservesCompilation_false_when_the_replaced_text_carries_an_escape() + public void SubstitutionPreservesCompilation_true_when_the_reference_name_is_written_with_an_escape() { var map = new Dictionary(StringComparer.Ordinal) { [@"Sp\eed"] = "Cell1/Dev/Speed" }; - EquipmentScriptPaths.SubstitutionPreservesCompilation("return ctx.GetTag(\"{{equip}}/Sp\\eed\").Value;", map) - .ShouldBeFalse(); + // Written correctly (\\ for the backslash) the name decodes to Sp\eed and resolves. + EquipmentScriptPaths.SubstitutionPreservesCompilation("return ctx.GetTag(\"{{equip}}/Sp\\\\eed\").Value;", map) + .ShouldBeTrue(); + EquipmentScriptPaths.SubstituteEquipmentToken("return ctx.GetTag(\"{{equip}}/Sp\\\\eed\").Value;", map) + .ShouldBe("return ctx.GetTag(\"Cell1/Dev/Speed\").Value;"); + } + + [Fact] + public void SubstituteEquipmentToken_leaves_a_malformed_escape_in_the_reference_name_intact() + { + // \e is not a C# escape: the compiler reports it, the substitution must not guess (and never throws). + var map = new Dictionary(StringComparer.Ordinal) { [@"Sp\eed"] = "Cell1/Dev/Speed" }; + var source = "return ctx.GetTag(\"{{equip}}/Sp\\eed\").Value;"; + EquipmentScriptPaths.SubstituteEquipmentToken(source, map).ShouldBe(source); + EquipmentScriptPaths.ExtractEquipReferenceNames(source).ShouldBeEmpty(); + } + + [Theory] + [InlineData(@"de\qv", "de\\\\qv")] + [InlineData("a\"b", "a\\\"b")] + [InlineData(@"x\vy", "x\\\\vy")] // \v must NOT survive as an escape + [InlineData("br{ace}", "br{ace}")] // regular literal: braces untouched + [InlineData("ünï☃😀", "ünï☃😀")] // non-ASCII + valid surrogate pair untouched + [InlineData("a\nb", "a\\u000Ab")] + [InlineData("a\rb", "a\\u000Db")] + [InlineData("a\u2028b\u0085c", "a\\u2028b\\u0085c")] + [InlineData("tab\t", "tab\\u0009")] + [InlineData("", "")] + public void EscapeForRegularLiteral_encodes_exactly_and_round_trips(string value, string expectedLiteral) + { + var encoded = EquipmentScriptPaths.EscapeForRegularLiteral(value); + encoded.ShouldBe(expectedLiteral); + EquipmentScriptPaths.TryDecodeRegularLiteral(encoded, out var back).ShouldBeTrue(); + back.ShouldBe(value); + } + + [Fact] + public void EscapeForRegularLiteral_encodes_an_unpaired_surrogate_and_round_trips() + { + var value = "a\ud800b"; + var encoded = EquipmentScriptPaths.EscapeForRegularLiteral(value); + encoded.ShouldBe("a\\uD800b"); + EquipmentScriptPaths.TryDecodeRegularLiteral(encoded, out var back).ShouldBeTrue(); + back.ShouldBe(value); + } + + [Theory] + [InlineData("a\\qb")] // unknown escape + [InlineData("dangling\\")] // trailing backslash + [InlineData("\\u12")] // short \u + [InlineData("\\xZ")] // no hex digits + [InlineData("\\UFFFFFFFF")] // out of range + public void TryDecodeRegularLiteral_rejects_what_the_compiler_rejects(string content) + { + EquipmentScriptPaths.TryDecodeRegularLiteral(content, out var value).ShouldBeFalse(); + value.ShouldBe(string.Empty); + } + + [Theory] + [InlineData("\\u0041\\x42\\U00000043\\t\\0", "ABC\t\0")] + [InlineData("\\'\\\"\\\\", "'\"\\")] + public void TryDecodeRegularLiteral_decodes_the_c_sharp_escapes(string content, string expected) + { + EquipmentScriptPaths.TryDecodeRegularLiteral(content, out var value).ShouldBeTrue(); + value.ShouldBe(expected); + } + + [Theory] + [InlineData(@"de\qv")] + [InlineData("a\"b")] + [InlineData(@"x\vy")] + [InlineData("br{ace}{{x}}")] + [InlineData("ünï☃😀")] + [InlineData("a\nb\u2028c")] + public void SubstituteEquipmentToken_pastes_an_escaped_literal_whose_value_is_the_exact_RawPath(string device) + { + var rawPath = $"Cell1/{device}/Speed"; + var map = new Dictionary(StringComparer.Ordinal) { ["Speed"] = rawPath }; + var substituted = EquipmentScriptPaths.SubstituteEquipmentToken("return ctx.GetTag(\"{{equip}}/Speed\").Value;", map); + + // Re-reading the substituted source as the compiler would yields the RawPath, and the dependency + // extraction (what the mux subscribes to) agrees. + EquipmentScriptPaths.ExtractDependencyRefs(substituted).ShouldBe(new[] { rawPath }); + EquipmentScriptPaths.SubstitutionPreservesCompilation("return ctx.GetTag(\"{{equip}}/Speed\").Value;", map).ShouldBeTrue(); + } + + [Fact] + public void ExtractEquipReferenceNames_decodes_the_names_written_with_escapes() + { + var names = EquipmentScriptPaths.ExtractEquipReferenceNames( + "var a = ctx.GetTag(\"{{equip}}/a\\\\b\"); var q = ctx.GetTag(\"{{equip}}/q\\\"t\");"); + names.ShouldBe(new[] { "a\\b", "q\"t" }); + } + + [Fact] + public void FindEquipReferenceLiterals_reports_the_content_span_in_source_offsets() + { + const string src = "x = ctx.GetTag(\"{{equip}}/a\\\\b\");"; + var lit = EquipmentScriptPaths.FindEquipReferenceLiterals(src).ShouldHaveSingleItem(); + src.Substring(lit.ContentIndex, lit.ContentLength).ShouldBe("{{equip}}/a\\\\b"); + lit.RefName.ShouldBe("a\\b"); + } + + [Fact] + public void ExtractDependencyRefs_returns_the_decoded_runtime_key_not_the_escaped_source_text() + { + EquipmentScriptPaths.ExtractDependencyRefs("return ctx.GetTag(\"Plant/de\\\\qv/q\\\"t\").Value;") + .ShouldBe(new[] { "Plant/de\\qv/q\"t" }); + } + + [Fact] + public void SubstituteEquipmentToken_still_ignores_verbatim_interpolated_and_raw_literals() + { + // Only regular "…" literals are path literals; the other kinds are left exactly as written. + foreach (var src in new[] + { + "ctx.GetTag(@\"{{equip}}/Speed\")", + "ctx.GetTag($\"{{equip}}/Speed\")", + "ctx.GetTag(\"\"\"{{equip}}/Speed\"\"\")", + }) + EquipmentScriptPaths.SubstituteEquipmentToken(src, RefMap).ShouldBe(src); } [Fact] diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipTokenEditorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipTokenEditorTests.cs index 8be9c71d2..1a1c3a6fd 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipTokenEditorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipTokenEditorTests.cs @@ -98,3 +98,65 @@ public sealed class EquipTokenEditorTests resp.Markers.ShouldNotContain(m => m.Code == "OTSCRIPT_EQUIPREF"); } } + +/// +/// Reference names containing \ or " are written ESCAPED inside the script's regular string literal +/// ({{equip}}/a\\b for a reference named a\b). Substitution decodes the name before the lookup, so the +/// editor's OTSCRIPT_EQUIPREF diagnostic and completion must apply the same rule (editor accepts ⇔ publish +/// accepts). +/// +public sealed class EquipTokenEscapedNameEditorTests +{ + private sealed class Catalog : IScriptTagCatalog + { + public Task> GetPathsAsync(string? filter, CancellationToken ct) + => Task.FromResult>(new[] { "Cell1/de\\qv/Speed" }); + + public Task GetTagInfoAsync(string path, CancellationToken ct) + => Task.FromResult(null); + + public Task> GetEquipmentReferenceNamesAsync(string equipmentId, string? filter, CancellationToken ct) + { + IEnumerable names = new[] { "a\\b", "q\"t" }; + if (!string.IsNullOrEmpty(filter)) names = names.Where(n => n.StartsWith(filter, StringComparison.Ordinal)); + return Task.FromResult>(names.ToList()); + } + } + + private static readonly ScriptAnalysisService Svc = new(new Catalog()); + + [Theory] + [InlineData("return ctx.GetTag(\"{{equip}}/a\\\\b\").Value;")] // a\b written with an escaped backslash + [InlineData("return ctx.GetTag(\"{{equip}}/q\\\"t\").Value;")] // q"t written with an escaped quote + public async Task Diagnostic_resolves_names_written_with_escapes(string code) + { + var resp = await Svc.DiagnoseAsync(new DiagnoseRequest(code, "EQ-1"), TestContext.Current.CancellationToken); + resp.Markers.ShouldNotContain(m => m.Code == "OTSCRIPT_EQUIPREF"); + } + + [Fact] + public async Task Diagnostic_flags_a_name_written_without_the_escape() + { + // `a\b` unescaped is the string a: it does NOT resolve to the reference `a\b`, at publish or here. + var resp = await Svc.DiagnoseAsync( + new DiagnoseRequest("return ctx.GetTag(\"{{equip}}/a\\b\").Value;", "EQ-1"), TestContext.Current.CancellationToken); + resp.Markers.ShouldContain(m => m.Code == "OTSCRIPT_EQUIPREF"); + } + + [Fact] + public async Task Completion_inserts_the_name_escaped_for_the_literal() + { + var items = (await Svc.CompleteAsync(new CompletionsRequest( + "return ctx.GetTag(\"{{equip}}/\").Value;", 1, 30, "EQ-1"), TestContext.Current.CancellationToken)).Items; + items.Single(i => i.Label == "{{equip}}/a\\b").InsertText.ShouldBe("{{equip}}/a\\\\b"); + items.Single(i => i.Label == "{{equip}}/q\"t").InsertText.ShouldBe("{{equip}}/q\\\"t"); + } + + [Fact] + public async Task Path_completion_inserts_a_RawPath_escaped_for_the_literal() + { + var items = (await Svc.CompleteAsync(new CompletionsRequest( + "return ctx.GetTag(\"Cell1\").Value;", 1, 24, "EQ-1"), TestContext.Current.CancellationToken)).Items; + items.Single(i => i.Label == "Cell1/de\\qv/Speed").InsertText.ShouldBe("Cell1/de\\\\qv/Speed"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs index 940369c40..f6f41bf2e 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs @@ -238,7 +238,7 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct [Fact] public void Equip_tokens_resolve_before_compiling_and_a_template_is_sent_once_for_every_equipment() { - // Three equipments share one VT template: substitution only rewrites escape-free literal text, so the gate + // Three equipments share one VT template: substitution only rewrites literal text (escaped), so the gate // sends the template once per seam rather than three resolved copies. var checker = new RecordingChecker(); var reply = Deploy(SeedDraft(new Seed(Equipments: 3)), checker); @@ -275,20 +275,33 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct } /// - /// A RawPath segment may legally contain a backslash, and substitution pastes the RawPath into a C# string - /// literal — so {{equip}}/speed over a device named de\qv becomes an invalid escape the runtime - /// refuses to compile. The template compiles fine; only compiling the RESOLVED source (what the gate does - /// whenever substitution is not provably compile-neutral) catches it. + /// A RawPath segment may legally contain a backslash or a quote, and substitution pastes the RawPath into a C# + /// string literal. Substitution ESCAPES the paste (EquipmentScriptPaths.EscapeForRegularLiteral), so + /// {{equip}}/speed over a device named de\qv still compiles and still reads the exact RawPath + /// (EquipTokenLiteralEscapingTests in Runtime.Tests runs it end to end). It used to paste raw — an + /// invalid escape the runtime refused to compile, which only compiling the resolved source caught. Now the + /// substitution is provably compile-neutral, so the gate compiles the shared template once and the real + /// compiler accepts the draft; the resolved source itself is also compiled to prove it. /// - [Fact] - public void An_equip_substitution_that_breaks_the_literal_is_caught_by_compiling_the_resolved_source() + [Theory] + [InlineData(@"de\qv")] + [InlineData("a\"b")] + [InlineData(@"x\vy")] + public void An_equip_substitution_over_a_RawPath_with_escape_characters_compiles_and_is_sent_once(string deviceName) { - var reply = Deploy(SeedDraft(new Seed(DeviceName: @"de\qv")), new RoslynDeployScriptChecker(), expectDispatch: false); - reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); - reply.Message.ShouldNotBeNull(); - reply.Message.ShouldContain("script 's-vt' does not compile as a VirtualTag script"); - reply.Message.ShouldContain("compile error"); - reply.Message.ShouldContain("script 's-pred'"); // the predicate resolves through the same reference + var checker = new RoslynDeployScriptChecker(); + var reply = Deploy(SeedDraft(new Seed(DeviceName: deviceName, Equipments: 2)), checker); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + (reply.Message ?? string.Empty).ShouldNotContain("does not compile"); + + // The resolved source (what the seams will run) compiles too — the gate's dedupe is not hiding a failure. + var map = new Dictionary(StringComparer.Ordinal) { ["speed"] = $"plant/drv/{deviceName}/speed" }; + EquipmentScriptPaths.SubstitutionPreservesCompilation(Legit, map).ShouldBeTrue(); + var resolved = EquipmentScriptPaths.SubstituteEquipmentToken(Legit, map); + resolved.ShouldNotBe(Legit); + var verdict = new RoslynDeployScriptChecker() + .Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, resolved)], TestContext.Current.CancellationToken).Single(); + verdict.Problems.ShouldBeEmpty(); } [Fact] diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/EquipTokenLiteralEscapingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/EquipTokenLiteralEscapingTests.cs new file mode 100644 index 000000000..2d8d58212 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/EquipTokenLiteralEscapingTests.cs @@ -0,0 +1,166 @@ +using System.Text.Json; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; +using ZB.MOM.WW.OtOpcUa.Core.VirtualTags; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// {{equip}}/<RefName> substitution pastes the backing RawPath into a C# string literal. A RawPath +/// segment may legally hold \, ", braces, line breaks and non-ASCII text +/// ( only forbids / and edge whitespace), so an unescaped paste either +/// fails to compile (de\qv) or silently changes the tag path (\v becomes a vertical tab). These +/// tests drive BOTH compose seams (AddressSpaceComposer + DeploymentArtifact), COMPILE the +/// substituted script with the real evaluator and run it, so "GetTag receives the exact RawPath" is shown +/// end to end rather than by string comparison. +/// +public sealed class EquipTokenLiteralEscapingTests +{ + // (device name, tag name, how the reference name is WRITTEN in the script's string literal). The tag name is the + // reference's effective name, so a name with a backslash / quote is written escaped inside the literal. + public static TheoryData Cases => new() + { + { @"de\qv", "Speed", "Speed" }, // \q: invalid C# escape if pasted raw + { "a\"b", "Speed", "Speed" }, // embedded quote would close the literal + { @"x\vy", "Speed", "Speed" }, // \v: VALID escape — silently becomes a vertical tab + { @"trail\", "Speed", "Speed" }, // trailing backslash would escape the closing quote + { @"two\\slash", "Speed", "Speed" }, + { "br{ace}{{x}}", "Speed", "Speed" }, // braces (interpolation hazard) in a regular literal + { "ünï☃😀", "Speed", "Speed" }, // non-ASCII incl. a surrogate pair + { "line\nbreak\u2028sep", "Speed", "Speed" }, // raw LF / U+2028 would break a regular literal + { "tab\there", "Speed", "Speed" }, + { "Dev1", @"a\b", @"a\\b" }, // the reference NAME carries a backslash + { "Dev1", "q\"t", "q\\\"t" }, // ...or a quote + { @"de\qv", @"r\ef""x", @"r\\ef\""x" }, // both at once + { "Dev1", "Speed", "Speed" }, // positive control: nothing special + }; + + private static string ScriptFor(string literalRefSource) => + "return ctx.GetTag(\"{{equip}}/" + literalRefSource + "\").Value;"; + + private static object? Run(string source, string readKey) + { + var cache = new Dictionary(StringComparer.Ordinal) + { + [readKey] = new DataValueSnapshot("hit", 0u, DateTime.UtcNow, DateTime.UtcNow), + }; + using var evaluator = ScriptEvaluator.Compile(source); + return evaluator.RunAsync( + new VirtualTagContext(cache, static (_, _) => { }, Serilog.Core.Logger.None, () => DateTime.UtcNow), + TestContext.Current.CancellationToken) + .GetAwaiter().GetResult(); + } + + [Theory] + [MemberData(nameof(Cases))] + public void VirtualTag_script_compiles_and_GetTag_receives_the_exact_RawPath_at_both_seams( + string deviceName, string tagName, string literalRefSource) + { + var expectedRawPath = $"Modbus/{deviceName}/{tagName}"; + var vtScript = ScriptFor(literalRefSource); + + var driver = new DriverInstance + { + DriverInstanceId = "drv-1", ClusterId = "c1", Name = "Modbus", DriverType = "Modbus", + DriverConfig = "{}", RawFolderId = null, + }; + var device = new Device { DeviceId = "dev-1", DriverInstanceId = "drv-1", Name = deviceName, DeviceConfig = "{}" }; + var tag = new Tag + { + TagId = "tag-1", DeviceId = "dev-1", Name = tagName, DataType = "Float", + AccessLevel = TagAccessLevel.Read, TagConfig = "{}", + }; + // No DisplayNameOverride: the effective name IS the tag name. + var reference = new UnsTagReference { UnsTagReferenceId = "ref-1", EquipmentId = "eq-1", TagId = "tag-1" }; + var script = new Script { ScriptId = "s-1", Name = "n", SourceCode = vtScript, SourceHash = "h" }; + var vt = new VirtualTag + { + VirtualTagId = "vt-1", EquipmentId = "eq-1", Name = "Out", DataType = "String", ScriptId = "s-1", + }; + + var composed = AddressSpaceComposer.Compose( + Array.Empty(), Array.Empty(), Array.Empty(), + new[] { driver }, Array.Empty(), + virtualTags: new[] { vt }, scripts: new[] { script }, + unsTagReferences: new[] { reference }, tags: new[] { tag }, + rawFolders: Array.Empty(), devices: new[] { device }, tagGroups: Array.Empty()); + + var blob = JsonSerializer.SerializeToUtf8Bytes(new + { + DriverInstances = new[] { new { DriverInstanceId = "drv-1", DriverType = "Modbus", DriverConfig = "{}", Name = "Modbus", RawFolderId = (string?)null } }, + Devices = new[] { new { DeviceId = "dev-1", DriverInstanceId = "drv-1", Name = deviceName, DeviceConfig = "{}" } }, + Tags = new[] { new { TagId = "tag-1", DeviceId = "dev-1", Name = tagName, DataType = "Float", TagConfig = "{}" } }, + UnsTagReferences = new[] { new { UnsTagReferenceId = "ref-1", EquipmentId = "eq-1", TagId = "tag-1" } }, + Scripts = new[] { new { ScriptId = "s-1", SourceCode = vtScript } }, + VirtualTags = new[] { new { VirtualTagId = "vt-1", EquipmentId = "eq-1", Name = "Out", DataType = "String", ScriptId = "s-1" } }, + }); + var decoded = DeploymentArtifact.ParseComposition(blob); + + var cPlan = composed.EquipmentVirtualTags.ShouldHaveSingleItem(); + var dPlan = decoded.EquipmentVirtualTags.ShouldHaveSingleItem(); + + // Byte parity between the seams, the dependency the mux subscribes to is the EXACT RawPath… + dPlan.ShouldBe(cPlan); + cPlan.DependencyRefs.ShouldBe(new[] { expectedRawPath }); + cPlan.Expression.ShouldNotContain("{{equip}}"); + + // …and the substituted script compiles and reads exactly that key (a wrong path reads a miss, not "hit"). + Run(cPlan.Expression, expectedRawPath).ShouldBe("hit"); + Run(dPlan.Expression, expectedRawPath).ShouldBe("hit"); + } + + [Fact] + public void ScriptedAlarm_predicate_dependency_refs_are_the_exact_RawPath_at_both_seams() + { + const string deviceName = @"de\qv""x"; + const string predicate = "return ctx.GetTag(\"{{equip}}/MotorSpeed\").Value is int i && i > 5;"; + var expectedRawPath = $"Modbus/{deviceName}/Speed"; + + var driver = new DriverInstance { DriverInstanceId = "drv-1", ClusterId = "c1", Name = "Modbus", DriverType = "Modbus", DriverConfig = "{}", RawFolderId = null }; + var device = new Device { DeviceId = "dev-1", DriverInstanceId = "drv-1", Name = deviceName, DeviceConfig = "{}" }; + var tag = new Tag { TagId = "tag-1", DeviceId = "dev-1", Name = "Speed", DataType = "Float", AccessLevel = TagAccessLevel.Read, TagConfig = "{}" }; + var reference = new UnsTagReference { UnsTagReferenceId = "ref-1", EquipmentId = "eq-1", TagId = "tag-1", DisplayNameOverride = "MotorSpeed" }; + var script = new Script { ScriptId = "s-1", Name = "n", SourceCode = predicate, SourceHash = "h" }; + var alarm = new ScriptedAlarm + { + ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "Hot", AlarmType = "LimitAlarm", Severity = 700, + MessageTemplate = "hot", PredicateScriptId = "s-1", HistorizeToAveva = true, Retain = true, Enabled = true, + }; + + var composed = AddressSpaceComposer.Compose( + Array.Empty(), Array.Empty(), Array.Empty(), + new[] { driver }, new[] { alarm }, + virtualTags: Array.Empty(), scripts: new[] { script }, + unsTagReferences: new[] { reference }, tags: new[] { tag }, + rawFolders: Array.Empty(), devices: new[] { device }, tagGroups: Array.Empty()); + + var blob = JsonSerializer.SerializeToUtf8Bytes(new + { + DriverInstances = new[] { new { DriverInstanceId = "drv-1", DriverType = "Modbus", DriverConfig = "{}", Name = "Modbus", RawFolderId = (string?)null } }, + Devices = new[] { new { DeviceId = "dev-1", DriverInstanceId = "drv-1", Name = deviceName, DeviceConfig = "{}" } }, + Tags = new[] { new { TagId = "tag-1", DeviceId = "dev-1", Name = "Speed", DataType = "Float", TagConfig = "{}" } }, + UnsTagReferences = new[] { new { UnsTagReferenceId = "ref-1", EquipmentId = "eq-1", TagId = "tag-1", DisplayNameOverride = "MotorSpeed" } }, + Scripts = new[] { new { ScriptId = "s-1", SourceCode = predicate } }, + ScriptedAlarms = new[] + { + new { ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "Hot", AlarmType = "LimitAlarm", Severity = 700, MessageTemplate = "hot", PredicateScriptId = "s-1", HistorizeToAveva = true, Retain = true, Enabled = true }, + }, + }); + var decoded = DeploymentArtifact.ParseComposition(blob); + + var cPlan = composed.EquipmentScriptedAlarms.ShouldHaveSingleItem(); + var dPlan = decoded.EquipmentScriptedAlarms.ShouldHaveSingleItem(); + dPlan.ShouldBe(cPlan); + cPlan.DependencyRefs.ShouldBe(new[] { expectedRawPath }); + + // The substituted predicate really is a compilable script (a VirtualTag-shaped compile of the same source). + using var evaluator = ScriptEvaluator.Compile(cPlan.PredicateSource); + } +}