Compare commits
5 Commits
651018f9fd
...
70e1bde90f
| Author | SHA1 | Date | |
|---|---|---|---|
| 70e1bde90f | |||
| 6f9e9c5c1b | |||
| ac3450d5f4 | |||
| 74aad3bc87 | |||
| e84f7a6e68 |
+15
-5
@@ -217,11 +217,21 @@ are bounded to 200 entries to keep the completion list responsive on large fleet
|
||||
`TryGetTagPathLiteral` identifies the tag-path context by climbing from the
|
||||
syntax token under the caret to: `LiteralExpressionSyntax` → `ArgumentSyntax`
|
||||
(first argument only) → `ArgumentListSyntax` → `InvocationExpressionSyntax` →
|
||||
`MemberAccessExpressionSyntax`. The method name check is
|
||||
`method is "GetTag" or "SetVirtualTag"` — it matches by method name only, not
|
||||
by receiver type, so `anything.GetTag("…")` would also trigger tag-path
|
||||
completion. This is harmless in the sandbox (no other `GetTag` methods exist in
|
||||
the allowed reference set) and keeps the detection simple.
|
||||
`MemberAccessExpressionSyntax`. It then requires (a) the method name is
|
||||
`GetTag` or `SetVirtualTag`, and (b) the **receiver is the identifier `ctx`** —
|
||||
a purely syntactic check that deliberately mirrors the runtime dependency
|
||||
harvest (`EquipmentScriptPaths.GetTagRefRegex` is `ctx`-anchored), so the editor
|
||||
offers tag-path completion/hover for exactly what `Phase7Composer` harvests at
|
||||
deploy time. An unrelated `anything.GetTag("…")` no longer triggers it.
|
||||
|
||||
**`SetVirtualTag` is a no-op in production.** The live single-tag evaluator
|
||||
(`RoslynVirtualTagEvaluator`) drops cross-tag `ctx.SetVirtualTag(...)` writes
|
||||
(logged); the cascade `VirtualTagEngine` that honours them is dormant (not wired
|
||||
into the host). So hover on a `ctx.SetVirtualTag("…")` path literal appends a
|
||||
note that the write is dropped in single-tag mode and will not take effect at
|
||||
runtime — the path completions still help author the literal, but the author is
|
||||
not misled into relying on a no-op. Making `SetVirtualTag` functional would
|
||||
require wiring the cascade engine into the host (out of scope).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# Script-editor `ctx` tag-completion correctness + truthfulness — Design
|
||||
|
||||
> Brainstormed 2026-06-18. Backlog item: stillpending.md §4 "Monaco `ctx.SetVirtualTag(...)`
|
||||
> write-target completions/hover are best-effort" (`AdminUI/ScriptAnalysis/IScriptTagCatalog.cs`,
|
||||
> `ScriptAnalysisService.cs`). Off master `651018f9`.
|
||||
|
||||
## Problem (verified in code)
|
||||
|
||||
The Monaco script editor's tag-path completion + hover (ScriptEdit page and the inline virtual-tag
|
||||
modal) route through one private gate, `ScriptAnalysisService.TryGetTagPathLiteral(token, …)`. Two
|
||||
defects:
|
||||
|
||||
1. **Receiver-blind gate.** `TryGetTagPathLiteral` accepts ANY `<expr>.GetTag("…")` /
|
||||
`<expr>.SetVirtualTag("…")` — it matches the member-access *method name* only
|
||||
(`method is not ("GetTag" or "SetVirtualTag")`) and never inspects the receiver. So a stray
|
||||
`someOtherObject.GetTag("…")` wrongly triggers tag-path completion/hover. This makes the editor
|
||||
**more permissive than the runtime**, whose dependency harvest is syntactically `ctx`-anchored
|
||||
(`Commons/Types/EquipmentScriptPaths.GetTagRefRegex` = `ctx\s*\.\s*(?:GetTag|SetVirtualTag)\s*\(`,
|
||||
consumed by `Phase7Composer` to build `EquipmentVirtualTagPlan.DependencyRefs`).
|
||||
|
||||
2. **`SetVirtualTag` advertises a no-op.** `IScriptTagCatalog`/`ScriptTagCatalog` emits a virtual
|
||||
tag's leaf `Name` as a `SetVirtualTag` write-target completion, documented as "best-effort … the
|
||||
live resolution of virtual-tag cascade/write targets is unconfirmed." It is now CONFIRMED:
|
||||
**`ctx.SetVirtualTag(...)` is a no-op in production.** The active evaluator binding
|
||||
`Host/Engines/RoslynVirtualTagEvaluator.cs` runs in **single-tag mode** and *drops* every
|
||||
cross-tag write (logged: "cross-tag write to {Path} dropped (single-tag adapter)"). The cross-tag
|
||||
cascade engine that DOES honor `SetVirtualTag` (`Core.VirtualTags.VirtualTagEngine`,
|
||||
`OnScriptSetVirtualTag` validating the target against registered vtags) is **dormant** — not wired
|
||||
into the host. So there is **no production write-target resolution** to be "authoritative" about.
|
||||
|
||||
## Scope decision
|
||||
|
||||
The original audit framed a fix sub-goal as "return *authoritative* `SetVirtualTag` write-target
|
||||
paths." Given finding (2), that goal is **moot and explicitly dropped** — the cascade feature is
|
||||
dormant; no authoritative production key exists. This phase ships the genuinely-fixable, fully
|
||||
live-verifiable core:
|
||||
|
||||
- **Component 1 — receiver-type guard** (correctness)
|
||||
- **Component 2 — truthful `SetVirtualTag` hover** (honesty)
|
||||
|
||||
Both AdminUI-only. **No runtime, Commons/wire/proto, or EF change. No bUnit.**
|
||||
|
||||
## Component 1 — receiver-type guard
|
||||
|
||||
In `TryGetTagPathLiteral`, after the member-access (`ma`) and method-name checks, require the
|
||||
receiver to be the identifier `ctx`:
|
||||
|
||||
```csharp
|
||||
if (ma.Expression is not IdentifierNameSyntax { Identifier.ValueText: "ctx" }) return false;
|
||||
```
|
||||
|
||||
This deliberately mirrors the runtime regex (syntactic `ctx` anchor) so the editor accepts EXACTLY
|
||||
what `Phase7Composer` harvests — not a semantic "is the receiver a `ScriptContext`" check, which
|
||||
could accept a differently-named local that the runtime regex would never harvest. The guard lives
|
||||
in the single shared gate, so it fixes both `Complete` and `Hover` at once. Effect: `foo.GetTag("…")`
|
||||
no longer offers tag completions/hover; only `ctx.GetTag(…)` / `ctx.SetVirtualTag(…)` do.
|
||||
|
||||
## Component 2 — truthful `SetVirtualTag`
|
||||
|
||||
`TryGetTagPathLiteral` surfaces WHICH method matched (a small out-param / enum, e.g.
|
||||
`ScriptTagMethod { GetTag, SetVirtualTag }`). The `Hover` path, when the matched method is
|
||||
`SetVirtualTag`, appends a clear note to the hover markdown:
|
||||
|
||||
> ⚠ Cross-tag `SetVirtualTag` writes are currently dropped in single-tag mode (the cascade engine is
|
||||
> not wired into the host); this write will not take effect at runtime.
|
||||
|
||||
So an author is no longer silently misled into relying on a no-op. The completion list still helps
|
||||
type a path (the truthfulness signal is the hover). Restricting `SetVirtualTag` *suggestions* to
|
||||
virtual-tag targets only is a possible refinement left to the implementation plan — NOT a hard
|
||||
requirement — because the dormant-engine write-target key is itself unverified (and the whole write
|
||||
is dropped), so over-engineering the suggestion set adds risk without runtime payoff.
|
||||
|
||||
## Error handling
|
||||
|
||||
Unchanged. `TryGetTagPathLiteral` already returns `false` cleanly on every non-match; the receiver
|
||||
guard is one more early `return false`. The method-match out-param is only read when the gate returns
|
||||
`true`.
|
||||
|
||||
## Testing
|
||||
|
||||
xUnit + Shouldly in the existing AdminUI test project, exercising `ScriptAnalysisService.Complete` /
|
||||
`Hover` directly (NO bUnit — these are service-level, not Razor):
|
||||
|
||||
- `ctx.GetTag("` → tag-path completions offered.
|
||||
- `foo.GetTag("` / `something.SetVirtualTag("` → tag-path completions NOT offered (receiver guard).
|
||||
- Hover on a `ctx.SetVirtualTag("…")` literal → markdown carries the single-tag-drop note.
|
||||
- Hover on a `ctx.GetTag("…")` literal → unchanged (no spurious note).
|
||||
|
||||
**Live `/run`** on the docker-dev rig (login-disabled; Chrome-driven against `http://localhost:9200`
|
||||
ScriptEdit page + inline vtag modal Monaco): confirm `ctx.GetTag("` shows completions, a non-`ctx`
|
||||
receiver does not, and the `SetVirtualTag` hover shows the truthful note.
|
||||
|
||||
## Deferred / out of scope
|
||||
|
||||
- "Authoritative `SetVirtualTag` write-target key" — moot (cascade engine dormant; production write
|
||||
is a no-op).
|
||||
- UNS browse-path as a non-inserted completion *detail* (the catalog's own documented discoverability
|
||||
follow-up) — not in this phase.
|
||||
- Wiring the cross-tag cascade engine into the host (the real fix for making `SetVirtualTag`
|
||||
functional) — a much larger, separate effort.
|
||||
|
||||
## Done =
|
||||
|
||||
Build clean + `dotnet test` (AdminUI) green + live `/run` confirms the three behaviors → merge to
|
||||
master + push.
|
||||
@@ -0,0 +1,263 @@
|
||||
# Script-editor `ctx` tag-completion correctness + truthfulness — Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:subagent-driven-development to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Make the Monaco script-editor's tag-path completion/hover fire only on `ctx.` receivers (matching the runtime harvest) and stop advertising `ctx.SetVirtualTag(...)` cross-tag writes as if they work (they are a no-op in the live single-tag engine).
|
||||
|
||||
**Architecture:** Both `ScriptAnalysisService.CompleteAsync` and `.Hover` route through one private syntactic gate, `TryGetTagPathLiteral`. Add a receiver guard (`ctx` identifier) there, and surface which method matched so `Hover` can append a truthful note for `SetVirtualTag`. AdminUI-only; no runtime/Commons/proto/EF change; no bUnit.
|
||||
|
||||
**Tech Stack:** C# / .NET 10, Roslyn syntax API (`Microsoft.CodeAnalysis.CSharp`), xUnit + Shouldly. Design: `docs/plans/2026-06-18-script-editor-ctx-completions-design.md` (committed `e84f7a6e`).
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Receiver-type guard + truthful `SetVirtualTag` hover
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** none
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs`
|
||||
- `TryGetTagPathLiteral` (currently ~line 213–229): add the `ctx` receiver guard + a new `out bool isSetVirtualTag`.
|
||||
- `CompleteAsync` call site (~line 164): pass `out _` for the new param.
|
||||
- `Hover` call site (~line 255) + the `tagMd` build (~line 268–272): pass `out var isSetVirtualTag`; append the single-tag-drop note when it is true.
|
||||
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/CtxCompletionGuardTests.cs` (create)
|
||||
|
||||
(The `Files:` block IS the contract — do not touch the runtime, Commons, or the catalog. `TryGetTagPathLiteral` is purely syntactic; keep it that way — do NOT introduce a semantic/type check on the receiver. The `ctx` identifier match is intentional: it mirrors `Commons/Types/EquipmentScriptPaths.GetTagRefRegex` = `ctx\s*\.\s*(?:GetTag|SetVirtualTag)`, so the editor accepts exactly what `Phase7Composer` harvests.)
|
||||
|
||||
**Context — current gate (verbatim):**
|
||||
```csharp
|
||||
private static bool TryGetTagPathLiteral(SyntaxToken token, out string prefix)
|
||||
{
|
||||
prefix = "";
|
||||
var literal = token.Parent as LiteralExpressionSyntax
|
||||
?? token.GetPreviousToken().Parent as LiteralExpressionSyntax;
|
||||
if (literal is null || !literal.IsKind(SyntaxKind.StringLiteralExpression)) return false;
|
||||
if (literal.Parent is not ArgumentSyntax arg) return false;
|
||||
if (arg.Parent is not ArgumentListSyntax argList) return false;
|
||||
if (argList.Parent is not InvocationExpressionSyntax inv) return false;
|
||||
if (inv.Expression is not MemberAccessExpressionSyntax ma) return false;
|
||||
var method = ma.Name.Identifier.ValueText;
|
||||
if (method is not ("GetTag" or "SetVirtualTag")) return false;
|
||||
// only the FIRST argument is the path
|
||||
if (argList.Arguments.Count > 0 && argList.Arguments[0] != arg) return false;
|
||||
prefix = literal.Token.ValueText ?? "";
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
The two callers today:
|
||||
- `CompleteAsync`: `if (_catalog != null && TryGetTagPathLiteral(token, out var pathPrefix))`
|
||||
- `Hover`: `if (_catalog is not null && TryGetTagPathLiteral(token, out var tagPath) && !string.IsNullOrEmpty(tagPath))`, which then builds:
|
||||
```csharp
|
||||
var info = await _catalog.GetTagInfoAsync(tagPath, CancellationToken.None);
|
||||
var tagMd = info is null
|
||||
? $"**Tag path** `{Code(tagPath)}`\n\n⚠ Not a known configured tag path."
|
||||
: $"**Tag path** `{Code(info.Path)}`\n\n{info.Kind} · Type **{info.DataType}**"
|
||||
+ (info.DriverInstanceId is null ? "" : $" · Driver `{Code(info.DriverInstanceId)}`");
|
||||
return new HoverResponse(tagMd);
|
||||
```
|
||||
|
||||
**Step 1: Write the failing tests**
|
||||
|
||||
Create `tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/CtxCompletionGuardTests.cs`:
|
||||
|
||||
```csharp
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis;
|
||||
|
||||
public sealed class CtxCompletionGuardTests
|
||||
{
|
||||
// Catalog that always offers one distinctive path + resolves a vtag, so the tag-path branch is
|
||||
// observable without a DB. The path "Line1.Speed" never appears in C# scoped/dot completions,
|
||||
// so its presence/absence cleanly distinguishes the tag-path branch from the fallback.
|
||||
private sealed class FakeCatalog : IScriptTagCatalog
|
||||
{
|
||||
public Task<IReadOnlyList<string>> GetPathsAsync(string? f, CancellationToken ct)
|
||||
=> Task.FromResult<IReadOnlyList<string>>(new[] { "Line1.Speed" });
|
||||
public Task<ScriptTagInfo?> GetTagInfoAsync(string path, CancellationToken ct)
|
||||
=> Task.FromResult<ScriptTagInfo?>(new ScriptTagInfo(path, "Virtual tag", "Double", null));
|
||||
public Task<IReadOnlyList<string>> GetEquipmentRelativeLeavesAsync(string? f, CancellationToken ct)
|
||||
=> Task.FromResult<IReadOnlyList<string>>(System.Array.Empty<string>());
|
||||
}
|
||||
|
||||
private static readonly ScriptAnalysisService Svc = new(new FakeCatalog());
|
||||
|
||||
// Caret column lands INSIDE the string literal (just after the opening quote). If a test does not
|
||||
// hit the tag-path branch, nudge the column to sit on a literal char and re-run — the gate keys off
|
||||
// the token under the caret. Columns are 1-based.
|
||||
|
||||
[Fact] public async Task Completion_on_ctx_GetTag_literal_offers_catalog_paths()
|
||||
{
|
||||
// return ctx.GetTag("| — caret just after the opening quote
|
||||
var res = await Svc.CompleteAsync(new CompletionsRequest("""return ctx.GetTag("""" + "\"", 1, 19));
|
||||
res.Items.ShouldContain(i => i.InsertText == "Line1.Speed");
|
||||
}
|
||||
|
||||
[Fact] public async Task Completion_on_non_ctx_receiver_does_NOT_offer_catalog_paths()
|
||||
{
|
||||
// foo.GetTag("| — receiver is not ctx, so the tag-path branch must NOT fire.
|
||||
var res = await Svc.CompleteAsync(new CompletionsRequest("""return foo.GetTag("""" + "\"", 1, 19));
|
||||
res.Items.ShouldNotContain(i => i.InsertText == "Line1.Speed");
|
||||
}
|
||||
|
||||
[Fact] public async Task Hover_on_ctx_SetVirtualTag_literal_warns_write_is_dropped()
|
||||
{
|
||||
// hover the path literal inside ctx.SetVirtualTag("V")
|
||||
var md = (await Svc.Hover(new HoverRequest("""return ctx.SetVirtualTag("V", 1);""", 1, 27))).Markdown;
|
||||
md.ShouldNotBeNull();
|
||||
md!.ShouldContain("single-tag mode");
|
||||
}
|
||||
|
||||
[Fact] public async Task Hover_on_ctx_GetTag_literal_has_no_dropped_write_note()
|
||||
{
|
||||
var md = (await Svc.Hover(new HoverRequest("""return ctx.GetTag("V").Value;""", 1, 20))).Markdown;
|
||||
md.ShouldNotBeNull();
|
||||
md!.ShouldNotContain("single-tag mode");
|
||||
}
|
||||
|
||||
[Fact] public async Task Hover_on_non_ctx_receiver_literal_is_not_treated_as_a_tag_path()
|
||||
{
|
||||
// bar.GetTag("V") — receiver not ctx; must not produce the "Tag path" hover.
|
||||
var md = (await Svc.Hover(new HoverRequest("""return bar.GetTag("V");""", 1, 20))).Markdown;
|
||||
(md is null || !md.Contains("Tag path")).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Run the tests; verify they FAIL**
|
||||
|
||||
Run: `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests --filter "FullyQualifiedName~CtxCompletionGuardTests"` (use `dangerouslyDisableSandbox: true`).
|
||||
Expected: the non-`ctx` tests FAIL (today the gate fires on any receiver) and the SetVirtualTag-note test FAILS (no note yet). The two positive `ctx.` tests may already pass. If a caret-column does not hit the literal branch, adjust the column and re-run until the positive cases hit the tag-path branch, THEN confirm the negatives still fail for the right reason.
|
||||
|
||||
**Step 3: Implement Component 1 (receiver guard) + Component 2 (method-discriminated note)**
|
||||
|
||||
In `TryGetTagPathLiteral`, change the signature and body:
|
||||
```csharp
|
||||
private static bool TryGetTagPathLiteral(SyntaxToken token, out string prefix, out bool isSetVirtualTag)
|
||||
{
|
||||
prefix = "";
|
||||
isSetVirtualTag = false;
|
||||
var literal = token.Parent as LiteralExpressionSyntax
|
||||
?? token.GetPreviousToken().Parent as LiteralExpressionSyntax;
|
||||
if (literal is null || !literal.IsKind(SyntaxKind.StringLiteralExpression)) return false;
|
||||
if (literal.Parent is not ArgumentSyntax arg) return false;
|
||||
if (arg.Parent is not ArgumentListSyntax argList) return false;
|
||||
if (argList.Parent is not InvocationExpressionSyntax inv) return false;
|
||||
if (inv.Expression is not MemberAccessExpressionSyntax ma) return false;
|
||||
// Receiver guard: only ctx.GetTag(...) / ctx.SetVirtualTag(...) are real tag-path calls. Mirrors the
|
||||
// runtime harvest (EquipmentScriptPaths.GetTagRefRegex is syntactically `ctx`-anchored), so the editor
|
||||
// offers tag completions/hover for exactly what Phase7Composer harvests — not an unrelated x.GetTag(...).
|
||||
if (ma.Expression is not IdentifierNameSyntax { Identifier.ValueText: "ctx" }) return false;
|
||||
var method = ma.Name.Identifier.ValueText;
|
||||
if (method is not ("GetTag" or "SetVirtualTag")) return false;
|
||||
// only the FIRST argument is the path
|
||||
if (argList.Arguments.Count > 0 && argList.Arguments[0] != arg) return false;
|
||||
prefix = literal.Token.ValueText ?? "";
|
||||
isSetVirtualTag = method == "SetVirtualTag";
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
Update `CompleteAsync` (the tag-path branch condition) to discard the new param:
|
||||
```csharp
|
||||
if (_catalog != null && TryGetTagPathLiteral(token, out var pathPrefix, out _))
|
||||
```
|
||||
|
||||
Update `Hover`'s condition + `tagMd` build:
|
||||
```csharp
|
||||
if (_catalog is not null && TryGetTagPathLiteral(token, out var tagPath, out var isSetVirtualTag) && !string.IsNullOrEmpty(tagPath))
|
||||
{
|
||||
...
|
||||
var info = await _catalog.GetTagInfoAsync(tagPath, CancellationToken.None);
|
||||
var tagMd = info is null
|
||||
? $"**Tag path** `{Code(tagPath)}`\n\n⚠ Not a known configured tag path."
|
||||
: $"**Tag path** `{Code(info.Path)}`\n\n{info.Kind} · Type **{info.DataType}**"
|
||||
+ (info.DriverInstanceId is null ? "" : $" · Driver `{Code(info.DriverInstanceId)}`");
|
||||
// Truthfulness: ctx.SetVirtualTag(...) is a no-op in the live single-tag evaluator
|
||||
// (RoslynVirtualTagEvaluator drops cross-tag writes; the cascade VirtualTagEngine is dormant).
|
||||
// Surface that so an author is not misled into relying on it.
|
||||
if (isSetVirtualTag)
|
||||
tagMd += "\n\n⚠ Cross-tag `SetVirtualTag` writes are currently dropped in single-tag mode " +
|
||||
"(the cascade engine is not wired into the host); this write will not take effect at runtime.";
|
||||
return new HoverResponse(tagMd);
|
||||
}
|
||||
```
|
||||
(Leave the `{{equip}}` short-circuit branch above this untouched — `SetVirtualTag("{{equip}}.x")` is a rare combination and out of scope.)
|
||||
|
||||
**Step 4: Run the tests; verify they PASS**
|
||||
|
||||
Run: `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests --filter "FullyQualifiedName~CtxCompletionGuardTests"`
|
||||
Expected: all 5 PASS.
|
||||
|
||||
**Step 5: Run the full AdminUI suite to confirm no regression**
|
||||
|
||||
Run: `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests` (use `dangerouslyDisableSandbox: true`).
|
||||
Expected: green. Existing tag-path tests (e.g. `HoverSignatureTests`) use `ctx.` receivers, so the guard does not affect them. If any pre-existing test used a non-`ctx` receiver on a tag-path literal, that is a real behavior change — surface it, do not weaken the guard.
|
||||
|
||||
**Step 6: Commit**
|
||||
```bash
|
||||
git add src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs \
|
||||
tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/CtxCompletionGuardTests.cs
|
||||
git commit -m "fix(adminui): ctx-receiver guard + truthful SetVirtualTag hover in script-editor completions"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Docs + full build/test + live `/run` + finish
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~4 min (excluding the live-rig step, which the controller drives)
|
||||
**Parallelizable with:** none (blocked by Task 1)
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/ScriptEditor.md` (the completions/hover section — note the `ctx`-receiver scoping and that `SetVirtualTag` cross-tag writes are dropped in single-tag mode, hover surfaces this).
|
||||
|
||||
**Step 1: Update docs**
|
||||
|
||||
In `docs/ScriptEditor.md`, find the section describing tag-path completions/hover and add a short, accurate note:
|
||||
- Tag-path completions/hover fire only on `ctx.GetTag(...)` / `ctx.SetVirtualTag(...)` (a non-`ctx` receiver is not treated as a tag call), matching the deploy-time dependency harvest.
|
||||
- `ctx.SetVirtualTag(...)` cross-tag writes are currently dropped by the live single-tag evaluator (the cascade engine is not wired into the host); the editor's hover surfaces this so it is not relied upon. Do NOT overclaim a fix to the cross-tag write path itself.
|
||||
|
||||
**Step 2: Full build**
|
||||
|
||||
Run: `dotnet build ZB.MOM.WW.OtOpcUa.slnx` (use `dangerouslyDisableSandbox: true`).
|
||||
Expected: 0 errors.
|
||||
|
||||
**Step 3: AdminUI tests**
|
||||
|
||||
Run: `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests` (use `dangerouslyDisableSandbox: true`).
|
||||
Expected: green.
|
||||
|
||||
**Step 4: Commit docs**
|
||||
```bash
|
||||
git add docs/ScriptEditor.md
|
||||
git commit -m "docs(scripteditor): ctx-receiver scoping + SetVirtualTag single-tag-drop note"
|
||||
```
|
||||
|
||||
**Step 5: Live `/run` verification (controller-driven, docker-dev)**
|
||||
|
||||
The docker-dev rig is LOCAL + login-disabled (no sign-in needed). Rebuild the AdminUI from the branch and drive the script editor via the Chrome tools against `http://localhost:9200`:
|
||||
- Open a virtual-tag's ScriptEdit page (or the inline vtag-modal Monaco).
|
||||
- Type `ctx.GetTag("` → tag-path completions appear.
|
||||
- Type a non-`ctx` receiver `foo.GetTag("` → tag-path completions do NOT appear (C# completions only).
|
||||
- Hover a `ctx.SetVirtualTag("…")` literal → the single-tag-drop note shows.
|
||||
|
||||
If the rig cannot exercise a step (e.g. Monaco completion timing), record it honestly as unit-proven + smoke-checked rather than overclaiming.
|
||||
|
||||
**Step 6: Finish — merge to master + push**
|
||||
|
||||
Use superpowers-extended-cc:finishing-a-development-branch: verify tests green, then merge `feat/script-editor-ctx-completions` to master (ff) and push. Stage by explicit path only; never `git add .`; never stage `stillpending.md` / `pending.md` / `docker-dev/docker-compose.yml` / `sql_login.txt` / `pki/`.
|
||||
|
||||
---
|
||||
|
||||
## Notes for the executor
|
||||
|
||||
- **Two tasks, sequential** (Task 2 blocked by Task 1) — both touch a tightly-coupled surface; no parallelism.
|
||||
- **Hard rules:** stage by path (never `git add .`); never stage the never-stage files; NO runtime/Commons/proto/EF change; NO bUnit; `dangerouslyDisableSandbox: true` for all build/test/rig commands.
|
||||
- **Done =** build 0 errors + AdminUI tests green + live `/run` confirms the three behaviors → merged to master + pushed.
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"planPath": "docs/plans/2026-06-18-script-editor-ctx-completions.md",
|
||||
"designPath": "docs/plans/2026-06-18-script-editor-ctx-completions-design.md",
|
||||
"designCommit": "e84f7a6e",
|
||||
"baseMaster": "651018f9",
|
||||
"branch": "feat/script-editor-ctx-completions",
|
||||
"scope": "AdminUI-only ScriptAnalysis fix. Component 1: ctx-receiver guard in ScriptAnalysisService.TryGetTagPathLiteral (mirror the runtime EquipmentScriptPaths.GetTagRefRegex `ctx`-anchor) so tag-path completion/hover fires only on ctx.GetTag/ctx.SetVirtualTag, not an unrelated x.GetTag(...). Component 2: surface which method matched; Hover appends a truthful note that ctx.SetVirtualTag cross-tag writes are dropped in single-tag mode (RoslynVirtualTagEvaluator drops them; cascade VirtualTagEngine dormant). The 'authoritative write-key' goal dropped as moot. NO runtime/Commons/proto/EF change; NO bUnit.",
|
||||
"dependencyGraph": "T1 -> T2",
|
||||
"tasks": [
|
||||
{"id": 1, "nativeId": 532, "subject": "ctx-receiver guard + truthful SetVirtualTag hover", "classification": "small", "status": "completed", "commit": "ac3450d5", "review": "code-review APPROVE WITH MINOR (haiku). The lone minor (negatives could pass spuriously) is mitigated by the differential design — 'Line1.Speed'/'Tag path' are catalog-only sentinels that can only come from the now-guarded branch, and tests form positive/negative pairs differing only in receiver/method. Purely syntactic guard (IdentifierNameSyntax ValueText==ctx); both call sites updated; hover note appended only for SetVirtualTag. 5 new tests; full AdminUI suite 477/477."},
|
||||
{"id": 2, "nativeId": 533, "subject": "Docs + build/test + live /run + finish", "classification": "small", "status": "completed", "commit": "6f9e9c5c", "review": "docs(ScriptEditor.md): rewrote the now-stale 'Literal gate' paragraph (it called the method-name-only match 'harmless') to describe the ctx-receiver guard + the SetVirtualTag single-tag-drop hover note; no overclaim (cascade-engine wiring stated out of scope). Build 0 errors (359 pre-existing warnings); AdminUI 477/477.",
|
||||
"live": "LIVE /run PASS (docker-dev, login-disabled, both central nodes rebuilt from branch). Drove the real /api/script-analysis/{completions,hover} endpoints against the live DB catalog: ctx.GetTag(\"cy\") x6 -> tag-path completion every time; foo.GetTag(\"cy\") x6 -> 0 tag-path (receiver guard) every time; foo.SetVirtualTag hover -> null (guard); ctx.SetVirtualTag hover -> the single-tag-drop note. KEY live-debug learning: an initial flicker (non-ctx receivers alternating 1/0) was root-caused to an INCOMPLETE DEPLOYMENT, not a code defect — Traefik round-robins :9200 across BOTH central-1 AND central-2, and only central-1 had been rebuilt; central-2 still ran the pre-branch code (no guard). After rebuilding central-2 too, the guard is deterministic on every request. Both nodes started healthy (0 exceptions, applied plan added=91 rebuild=True, full materialisation)."}
|
||||
],
|
||||
"executionState": "COMPLETE — merged to master + pushed. ctx-receiver guard + truthful SetVirtualTag hover in the script-editor completions. Build 0 errors; AdminUI 477/477; live /run PASS on docker-dev. NO runtime/Commons/proto/EF change; NO bUnit.",
|
||||
"reviewFollowUps": [
|
||||
"Pre-existing position-boundary fragility (NOT introduced by this change): for a DEGENERATE caret at the closing quote of an EMPTY string literal (e.g. ctx.GetTag(\"\") with the caret on the closing quote), the completion gate's FindToken can land inconsistently. Realistic carets (on content / just after the open quote) are deterministic and obey the guard. Orthogonal to the receiver guard; low value to chase.",
|
||||
"Live-rig deployment note: docker-dev :9200 is Traefik-load-balanced across central-1 AND central-2 — an AdminUI live-verify must rebuild BOTH central nodes (or hit a node directly) or requests round-robin between old and new code. Recorded so future AdminUI live-verifies don't repeat the half-deployed flicker."
|
||||
],
|
||||
"lastUpdated": "2026-06-18"
|
||||
}
|
||||
@@ -161,7 +161,7 @@ public sealed class ScriptAnalysisService
|
||||
// position is the offset just AFTER the caret; -1 finds the token the caret sits at/just-after (e.g. the dot in "ctx.").
|
||||
var token = root.FindToken(Math.Max(0, position - 1));
|
||||
|
||||
if (_catalog != null && TryGetTagPathLiteral(token, out var pathPrefix))
|
||||
if (_catalog != null && TryGetTagPathLiteral(token, out var pathPrefix, out _))
|
||||
{
|
||||
const string equipDot = EquipmentScriptPaths.EquipToken + "."; // "{{equip}}."
|
||||
if (pathPrefix.StartsWith(equipDot, StringComparison.Ordinal))
|
||||
@@ -210,9 +210,10 @@ public sealed class ScriptAnalysisService
|
||||
.Select(ToCompletionItem).Take(200).ToList();
|
||||
}
|
||||
|
||||
private static bool TryGetTagPathLiteral(SyntaxToken token, out string prefix)
|
||||
private static bool TryGetTagPathLiteral(SyntaxToken token, out string prefix, out bool isSetVirtualTag)
|
||||
{
|
||||
prefix = "";
|
||||
isSetVirtualTag = false;
|
||||
var literal = token.Parent as LiteralExpressionSyntax
|
||||
?? token.GetPreviousToken().Parent as LiteralExpressionSyntax;
|
||||
if (literal is null || !literal.IsKind(SyntaxKind.StringLiteralExpression)) return false;
|
||||
@@ -220,11 +221,16 @@ public sealed class ScriptAnalysisService
|
||||
if (arg.Parent is not ArgumentListSyntax argList) return false;
|
||||
if (argList.Parent is not InvocationExpressionSyntax inv) return false;
|
||||
if (inv.Expression is not MemberAccessExpressionSyntax ma) return false;
|
||||
// Receiver guard: only ctx.GetTag(...) / ctx.SetVirtualTag(...) are real tag-path calls. Mirrors the
|
||||
// runtime harvest (EquipmentScriptPaths.GetTagRefRegex is syntactically `ctx`-anchored), so the editor
|
||||
// offers tag completions/hover for exactly what Phase7Composer harvests — not an unrelated x.GetTag(...).
|
||||
if (ma.Expression is not IdentifierNameSyntax { Identifier.ValueText: "ctx" }) return false;
|
||||
var method = ma.Name.Identifier.ValueText;
|
||||
if (method is not ("GetTag" or "SetVirtualTag")) return false;
|
||||
// only the FIRST argument is the path
|
||||
if (argList.Arguments.Count > 0 && argList.Arguments[0] != arg) return false;
|
||||
prefix = literal.Token.ValueText ?? "";
|
||||
isSetVirtualTag = method == "SetVirtualTag";
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -252,7 +258,7 @@ public sealed class ScriptAnalysisService
|
||||
// Tag-path hover takes priority over C# symbol resolution: when the caret sits on a
|
||||
// ctx.GetTag("…")/ctx.SetVirtualTag("…") path literal, show the resolved tag's info
|
||||
// (or note it's not a known configured tag path) instead of the string-literal symbol.
|
||||
if (_catalog is not null && TryGetTagPathLiteral(token, out var tagPath) && !string.IsNullOrEmpty(tagPath))
|
||||
if (_catalog is not null && TryGetTagPathLiteral(token, out var tagPath, out var isSetVirtualTag) && !string.IsNullOrEmpty(tagPath))
|
||||
{
|
||||
static string Code(string s) => s.Replace("`", "\\`");
|
||||
// Equipment-relative literal (contains the {{equip}} token): it cannot resolve to a
|
||||
@@ -270,6 +276,11 @@ public sealed class ScriptAnalysisService
|
||||
? $"**Tag path** `{Code(tagPath)}`\n\n⚠ Not a known configured tag path."
|
||||
: $"**Tag path** `{Code(info.Path)}`\n\n{info.Kind} · Type **{info.DataType}**"
|
||||
+ (info.DriverInstanceId is null ? "" : $" · Driver `{Code(info.DriverInstanceId)}`");
|
||||
// Truthfulness: ctx.SetVirtualTag(...) is a no-op in the live single-tag evaluator
|
||||
// (RoslynVirtualTagEvaluator drops cross-tag writes; the cascade VirtualTagEngine is dormant).
|
||||
if (isSetVirtualTag)
|
||||
tagMd += "\n\n⚠ Cross-tag `SetVirtualTag` writes are currently dropped in single-tag mode " +
|
||||
"(the cascade engine is not wired into the host); this write will not take effect at runtime.";
|
||||
return new HoverResponse(tagMd);
|
||||
}
|
||||
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis;
|
||||
|
||||
public sealed class CtxCompletionGuardTests
|
||||
{
|
||||
private sealed class FakeCatalog : IScriptTagCatalog
|
||||
{
|
||||
public Task<IReadOnlyList<string>> GetPathsAsync(string? f, CancellationToken ct)
|
||||
=> Task.FromResult<IReadOnlyList<string>>(new[] { "Line1.Speed" });
|
||||
public Task<ScriptTagInfo?> GetTagInfoAsync(string path, CancellationToken ct)
|
||||
=> Task.FromResult<ScriptTagInfo?>(new ScriptTagInfo(path, "Virtual tag", "Double", null));
|
||||
public Task<IReadOnlyList<string>> GetEquipmentRelativeLeavesAsync(string? f, CancellationToken ct)
|
||||
=> Task.FromResult<IReadOnlyList<string>>(System.Array.Empty<string>());
|
||||
}
|
||||
|
||||
private static readonly ScriptAnalysisService Svc = new(new FakeCatalog());
|
||||
|
||||
[Fact] public async Task Completion_on_ctx_GetTag_literal_offers_catalog_paths()
|
||||
{
|
||||
// "return ctx.GetTag(" + '""' + ')' — col 20 lands on the closing quote of the empty string literal.
|
||||
var res = await Svc.CompleteAsync(new CompletionsRequest("return ctx.GetTag(\"\")", 1, 20));
|
||||
res.Items.ShouldContain(i => i.InsertText == "Line1.Speed");
|
||||
}
|
||||
|
||||
[Fact] public async Task Completion_on_non_ctx_receiver_does_NOT_offer_catalog_paths()
|
||||
{
|
||||
// Same shape but receiver is "foo" — must NOT offer catalog paths.
|
||||
var res = await Svc.CompleteAsync(new CompletionsRequest("return foo.GetTag(\"\")", 1, 20));
|
||||
res.Items.ShouldNotContain(i => i.InsertText == "Line1.Speed");
|
||||
}
|
||||
|
||||
[Fact] public async Task Hover_on_ctx_SetVirtualTag_literal_warns_write_is_dropped()
|
||||
{
|
||||
var md = (await Svc.Hover(new HoverRequest("return ctx.SetVirtualTag(\"V\", 1);", 1, 27))).Markdown;
|
||||
md.ShouldNotBeNull();
|
||||
md!.ShouldContain("single-tag mode");
|
||||
}
|
||||
|
||||
[Fact] public async Task Hover_on_ctx_GetTag_literal_has_no_dropped_write_note()
|
||||
{
|
||||
var md = (await Svc.Hover(new HoverRequest("return ctx.GetTag(\"V\").Value;", 1, 20))).Markdown;
|
||||
md.ShouldNotBeNull();
|
||||
md!.ShouldNotContain("single-tag mode");
|
||||
}
|
||||
|
||||
[Fact] public async Task Hover_on_non_ctx_receiver_literal_is_not_treated_as_a_tag_path()
|
||||
{
|
||||
var md = (await Svc.Hover(new HoverRequest("return bar.GetTag(\"V\");", 1, 20))).Markdown;
|
||||
(md is null || !md.Contains("Tag path")).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user