# Scripted Alarms > ⚠️ **Correction (2026-07-28): `GenericDriverNodeManager` is NOT a production dispatch path.** It is test > scaffolding — its own source says so (`Core/OpcUa/GenericDriverNodeManager.cs:71`, "verified 07/#10: zero > production references"). The production chain is `OpcUaPublishActor` → `IOpcUaAddressSpaceSink` > (`SdkAddressSpaceSink`) → `OtOpcUaNodeManager`, materialising the **two v3 namespaces** (`.../raw` and > `.../uns`). Sections below that describe per-node dispatch, rediscovery re-walks, or alarm-sink capture > *through that class* describe a design, not the running server. The same correction is already carried by > `AddressSpace.md` and `IncrementalSync.md`; this file was missed in that pass. `Core.ScriptedAlarms` is the Phase 7 subsystem that raises OPC UA Part 9 alarms from operator-authored C# predicates rather than from driver-native alarm streams. Scripted alarms are additive: Galaxy, AB CIP, FOCAS, and OPC UA Client drivers keep their native `IAlarmSource` implementations unchanged, and a `ScriptedAlarmSource` simply registers as another source in the same fan-out. Predicates read tags from any source (driver tags or virtual tags) through the shared `ITagUpstreamSource` and emit condition transitions through the engine's Part 9 state machine. This file covers the engine internals — predicate evaluation, state machine, persistence, and the engine-to-`IAlarmSource` adapter. The server-side plumbing that turns those emissions into OPC UA `AlarmConditionState` nodes, applies retries, persists alarm transitions to the Historian, and routes operator acks through the session's `AlarmAck` permission lives in [AlarmTracking.md](AlarmTracking.md) and is not repeated here. ## Authoring (AdminUI) Scripted-alarm definitions are created and edited per-equipment on the **`/uns/equipment/{id}`** page's **Alarms** tab; the standalone `/scripted-alarms` management pages were retired in favour of this equipment-scoped surface. The **`/alerts`** page remains the live runtime view — it is where operators acknowledge, confirm, and shelve active alarm instances. ## Definition shape `ScriptedAlarmDefinition` (`src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmDefinition.cs`) is the runtime contract the engine consumes. The generation-publish path materialises these from the `ScriptedAlarm` + `Script` config tables via `AddressSpaceComposer.Compose` + the driver-role host actor startup path. | Field | Notes | |---|---| | `AlarmId` | Stable identity. Also the OPC UA `ConditionId` and the key in `IAlarmStateStore`. Convention: `{EquipmentPath}::{AlarmName}`. | | `EquipmentPath` | UNS path the alarm hangs under in the address space. ACL scope inherits from the equipment node. | | `AlarmName` | Browse-tree display name. | | `Kind` | `AlarmKind` — `AlarmCondition`, `LimitAlarm`, `DiscreteAlarm`, or `OffNormalAlarm`. Controls only the OPC UA ObjectType the node surfaces as; the internal state machine is identical for all four. | | `Severity` | `AlarmSeverity` enum (`Low` / `Medium` / `High` / `Critical`), defined in `Core.Abstractions/IAlarmSource.cs`. Static per decision #13 — the predicate does not compute severity. The publish path bands the configured value into this four-value enum before materialising the `ScriptedAlarmDefinition`. | | `MessageTemplate` | String with `{TagPath}` placeholders, resolved at emission time. See below. | | `PredicateScriptSource` | Roslyn C# script returning `bool`. `true` = condition active; `false` = cleared. | | `HistorizeToAveva` | Per-alarm opt-out of **durable** historization. When `false`, `HistorianAdapterActor` skips the `IAlarmHistorianSink` write for this alarm's transitions; the live `/alerts` fan-out is unaffected (the UI still shows every transition). Default true. Galaxy-native alarms default false since Galaxy historises them directly. | | `Retain` | Part 9 retain flag — keep the condition visible after clear while un-acked/un-confirmed transitions remain. Default true. | Illustrative definition: ```csharp new ScriptedAlarmDefinition( AlarmId: "Plant/Line1/Oven::OverTemp", EquipmentPath: "Plant/Line1/Oven", AlarmName: "OverTemp", Kind: AlarmKind.LimitAlarm, Severity: AlarmSeverity.High, MessageTemplate: "Oven {Plant/Line1/Oven/Temp} exceeds limit {Plant/Line1/Oven/TempLimit}", PredicateScriptSource: "return GetTag(\"Plant/Line1/Oven/Temp\").AsDouble() > GetTag(\"Plant/Line1/Oven/TempLimit\").AsDouble();"); ``` ## Predicate evaluation Alarm predicates reuse the same Roslyn sandbox as virtual tags — `ScriptEvaluator` compiles the source, `ScriptRunGuard` runs it with the node's `Scripting:RunTimeout` budget (default 2 s — the same budget virtual tags get; before lmxopcua#779 the host built the engine without a budget and every predicate silently ran on `TimedScriptEvaluator.DefaultTimeout`, 250 ms), and `DependencyExtractor` statically harvests the tag paths the script reads. The sandbox rules (forbidden types, cancellation, logging sinks) are documented in [VirtualTags.md](VirtualTags.md); ScriptedAlarms does not redefine them. The known resource limits — unbounded script-side memory and the orphan-thread CPU-budget caveat — are documented in that file as well; per-publish assembly accretion was resolved by the Core.Scripting-008 collectible-`AssemblyLoadContext` rewrite and no longer requires periodic server restarts. **Out of process (opt-in, lmxopcua#780).** With `Scripting:Runner=OutOfProcess` **and** `ScriptedAlarm` listed in `Scripting:Runner:Seams` (an unset list leaves alarms in process — they go last in the rollout), the predicates run in the pre-emptible `ScriptWorker` pool. `LoadAsync` still compiles every predicate, to PE bytes only, so a broken predicate fails the load exactly as before; the worker compiles and runs it. Each re-evaluation pass (and the startup-recovery pass) submits every dirty alarm's predicate in **one batch** and applies the results — Part 9 transition, persist-before-update, emissions — in the serial order under the engine's gate, so the transition sequence is the in-process one and a large engine pays one round trip per pass, not one per alarm. Failure semantics (design §9): a predicate that times out, is killed at its hard deadline or is quarantined freezes its condition with a `BadInternalError` quality annotation, as in process; one whose worker restarted under it, or that found no worker ready, freezes with **`BadResourceUnavailable`** (`0x80040000`) and is re-evaluated by itself when the worker is back. No outcome but a completed `bool` reaches the state machine, so a dead worker never clears an alarm. Quarantines (`ScriptedAlarmEngine.QuarantinedAlarmIds`) lift on a reload. See [VirtualTags.md](VirtualTags.md) §"Out-of-process runner". `AlarmPredicateContext` (`AlarmPredicateContext.cs`) is the script's `ScriptContext` subclass: - `GetTag(path)` returns a `DataValueSnapshot` from the engine-maintained read cache. Missing path → `DataValueSnapshot(null, 0x80340000u, null, now)` (`BadNodeIdUnknown`). An empty path returns the same. - `SetVirtualTag(path, value)` throws `InvalidOperationException`. Predicates must be side-effect free per plan decision #6; writes would couple alarm state to virtual-tag state in ways that are near-impossible to reason about. Operators see the rejection in `scripts-*.log`. - `Now` and `Logger` are provided by the engine. Evaluation cadence: - On every upstream tag change that any alarm's input set references (`OnUpstreamChange` → the dirty set → `DrainDirtyAsync` → `ReevaluateAsync`). The engine maintains an inverse index `tag path → alarm ids` (`_alarmsReferencing`); only affected alarms re-run. - On a 5-second shelving-check timer (`_shelvingTimer`) for timed-shelve expiry. This is **not** routed through the dirty set — it remains an independent producer contending for the same evaluation gate. - At `LoadAsync` for every alarm, to re-derive `ActiveState` per plan decision #14 (startup recovery). If a predicate throws or times out, the engine logs the failure and leaves the prior `ActiveState` intact — it does not synthesise a clear. Operators investigating a broken predicate should never see a phantom clear preceding the error. A predicate that times out, is refused behind its own still-running previous run, or is **quarantined** by `ScriptRunGuard` also freezes the condition and annotates it with `BadInternalError` quality, the same code virtual tags and Calculation tags use for a script fault. There is no quarantine-specific status code; the reasoning, and where a quarantine is visible instead (log line naming the script, `otopcua.script.quarantined`, `/script-log`), is in [VirtualTags.md](VirtualTags.md) §"Quarantine: what a client sees". ### Dirty-set coalescing Every upstream push used to spawn its **own** fire-and-forget re-evaluation, each allocating a fresh array of affected alarm ids and each queueing on the single non-reentrant evaluation gate. N pushes arriving during one slow evaluation meant **N serialized re-evaluations**, every one of them re-reading the same latest values and every one paying the per-predicate timeout machinery again. A push now unions the affected alarm ids into a `HashSet _dirtyAlarmIds` under a short leaf lock and, if no drain is already scheduled, starts one. The drain loops: take the set, swap in an empty one, release the lock, evaluate that batch, repeat until the set is empty. Exactly one drainer runs at a time. - **There is no timer and no wall-clock window.** A push landing on an idle engine is evaluated immediately; the coalescing window is exactly "whatever queued while the gate was busy". - **"Latest values win" is structural, not a heuristic.** No per-push value snapshot is carried into the drain. Every push writes the newest value into `_valueCache` synchronously, and the surviving evaluation refills its scratch read-cache from `_valueCache` *at drain time, inside the gate* — so it reads whatever the newest push wrote. The collapse is loss-free by construction. - **Transition semantics are unchanged**, because evaluation was already level-triggered: the old code never read the pushed value either, it always re-read the cache. All N of those serialized passes already saw the same latest values, so the dirty set removes redundant work, not information. - **An alarm is evaluated at most once per pass** even when ten of its input tags changed — the fan-in across inputs dedups, not just repeat pushes of one tag. - ⚠️ **What can still be collapsed away** (and always could be) is an intermediate state the engine would have transited had it evaluated between pushes. With a slow predicate or a blocked store, a value that crosses a threshold and crosses back before the drain reaches it produces **no transition and no event**; the alarm settles on the latest value. The #478 quality-bucket tracking sees only the coalesced-latest bucket for the same reason. - **Batch order is unordered** — the batch comes out of a `HashSet`, so alarms within a pass are no longer evaluated in push order. Emissions still fire strictly after the gate is released. #### Why the store write was NOT moved behind a write-behind queue The review that prompted this work suggested a write-behind queue for `IAlarmStateStore.SaveAsync` — deferring the Part 9 condition-state persist (`LocalDbAlarmConditionStateStore`, the replicated `alarm_condition_state` table) out of the evaluation gate. It was **deliberately rejected**, and the rationale is recorded in the engine's class doc so it is not re-proposed: 1. **It trades away a real crash-consistency property.** The store write stays *inside* the gate and *before* the in-memory update, so a store failure leaves the in-memory condition and the persisted one both at the prior state rather than diverging. That ordering is pinned by `Store_save_failure_leaves_in_memory_state_unchanged`. 2. **The throughput it would buy is no longer needed.** After coalescing, a `SaveAsync` happens only on a genuine Part 9 transition, which is rare relative to the push rate — so the gate-held store call is not on the hot path any more. Write-behind would trade a correctness property for latency the dirty set already removed. ## Part 9 state machine `Part9StateMachine` (`Part9StateMachine.cs`) is a pure `static` function set. Every transition takes the current `AlarmConditionState` plus the event, returns a new record and an `EmissionKind`. No I/O, no mutation, trivially unit-testable. Transitions map to OPC UA Part 9: - `ApplyPredicate(current, predicateTrue, nowUtc)` — predicate re-evaluation. `Inactive → Active` sets `Acked = Unacknowledged` and `Confirmed = Unconfirmed`; `Active → Inactive` updates `LastClearedUtc` and consumes `OneShot` shelving. Disabled alarms no-op. - `ApplyAcknowledge` / `ApplyConfirm` — operator ack/confirm. Require a non-empty user string (audit requirement). Each appends an `AlarmComment` with `Kind = "Acknowledge"` / `"Confirm"`. - `ApplyOneShotShelve` / `ApplyTimedShelve(unshelveAtUtc)` / `ApplyUnshelve` — shelving transitions. `Timed` requires `unshelveAtUtc > nowUtc`. - `ApplyEnable` / `ApplyDisable` — operator enable/disable. Disabled alarms ignore predicate results until re-enabled; on enable, `ActiveState` is re-derived from the next evaluation. - `ApplyAddComment(text)` — append-only audit entry, no state change. - `ApplyShelvingCheck(nowUtc)` — called by the 5s timer; promotes expired `Timed` shelving to `Unshelved` with a `system / AutoUnshelve` audit entry. The sole owner of timed-shelve expiry — the OPC UA node's own SDK timer does nothing. - `ApplyAcknowledge` on an already-acknowledged alarm is a no-op **unless it carries a comment**, which is recorded as an `AddComment` (emission `CommentAdded`; `LastAck*` untouched) — the OPC UA node reports a commented re-ack, so the system of record must hold the comment too. Two invariants the machine enforces: 1. **Disabled** alarms ignore every predicate evaluation — they never transition `ActiveState` / `AckedState` / `ConfirmedState` until re-enabled. 2. **Shelved** alarms still advance their internal state but emit `EmissionKind.Suppressed` instead of `Activated` / `Cleared`. The engine advances the state record (so startup recovery reflects reality) but `ScriptedAlarmSource` does not publish the suppressed transition to subscribers. `OneShot` expires on the next clear; `Timed` expires at `ShelvingState.UnshelveAtUtc`. `EmissionKind` values: `None`, `Suppressed`, `Activated`, `Cleared`, `Acknowledged`, `Confirmed`, `Shelved`, `Unshelved`, `Enabled`, `Disabled`, `CommentAdded`. ## Message templates `MessageTemplate` (`MessageTemplate.cs`) resolves `{path}` placeholders in the configured message at emission time. Syntax: - `{path/with/slashes}` — brace-stripped contents are looked up via the engine's tag cache. - No escaping. Literal braces in messages are not currently supported. - `ExtractTokenPaths(template)` is called at `LoadAsync` so the engine subscribes to every referenced path (ensuring the value cache is populated before the first resolve). Fallback rules: a resolved `DataValueSnapshot` with a non-zero `StatusCode`, a `null` `Value`, or an unknown path becomes `{?}`. The event still fires — the operator sees where the reference broke rather than having the alarm swallowed. ## Input-quality policy Predicate evaluation and message-template resolution deliberately treat tag-input quality differently: | Surface | Quality bar | Rationale | |---|---|---| | `ScriptedAlarmEngine.AreInputsReady` (predicate gate) | **Bad rejected** (`StatusCode` bit 31 set). `Good` and `Uncertain` are both accepted. | Uncertain quality still carries a value the predicate can inspect; rejecting it would mask a transitional alarm condition. Predicate evaluation is a state-machine input — operators want it to track reality as closely as the quality allows. | | `MessageTemplate.Resolve` (operator-facing message) | **Any non-zero `StatusCode` rejected** — only `Good` substitutes; `Uncertain` / Bad / unknown all render as `{?}`. | The message is a human-readable signal; substituting an Uncertain value would let operators act on a questionable reading without seeing the qualifier. Rendering `{?}` makes the doubt explicit. | `AlarmPredicateContext.GetTag` returns a `BadNodeIdUnknown` (`0x80340000`) snapshot for missing or empty paths, so a typo in the predicate flows through `AreInputsReady` (Bad → predicate skipped, prior state held) and `MessageTemplate.Resolve` (non-Good → `{?}`) without crashing the engine. (Core.ScriptedAlarms-010) ## State persistence `IAlarmStateStore` (`IAlarmStateStore.cs`) is the persistence contract: `LoadAsync(alarmId)`, `LoadAllAsync`, `SaveAsync(state)`, `RemoveAsync(alarmId)`. `InMemoryAlarmStateStore` in the same file is the default for tests and dev deployments without a SQL backend. The production implementation is `LocalDbAlarmConditionStateStore` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/LocalDbAlarmConditionStateStore.cs`), which persists to the node's replicated LocalDb (condition row + one row per comment) and mirrors to the redundant pair peer last-writer-wins. It replaced the config-DB `EfAlarmActorStateStore` / `ScriptedAlarmState` table, which no longer exist. Persisted scope per plan decision #14: `Enabled`, `Acked`, `Confirmed`, `Shelving`, `LastTransitionUtc`, the `LastAck*` / `LastConfirm*` audit fields, and the append-only `Comments` list. `Active` is **not** trusted across restart (the production `LocalDbAlarmConditionStateStore` has no column for it — a loaded row is `Inactive`) — the engine re-runs the predicate at `LoadAsync`, so alarms whose condition cleared during downtime settle to `Inactive` without a spurious clear-event, and the ack/confirm audit trail survives. For a **new engine incarnation** an alarm whose predicate is still true is therefore a new occurrence: `Activated`, `Unacknowledged`, `LastTransitionUtc` = the load instant — the operator re-acks once. A new incarnation is a process restart **or a supervision restart of `ScriptedAlarmHostActor`** (its Props factory builds a fresh engine, which then re-applies), and the same holds for the first good load after a failed one (below). ### A redeploy is a restatement (#935) `LoadAsync` runs on **every deploy** (`ScriptedAlarmHostActor.ApplyScriptedAlarms`), not just at startup. Seeding every alarm from the store made each deploy the restart case above for every still-active alarm: an operator-acknowledged alarm came back `Unacknowledged`, an `Activated` emission reached the `alerts` topic (a duplicate historian / AVEVA row per deploy), the condition `Time` moved to the deploy instant, and the origin's activation marker bumped (gRPC data consumers minted new EventIds). The seed is now **`previous ?? persisted ?? Fresh`**: before it clears its alarm table, `LoadAsync` captures the last **completed** generation's in-memory condition for every alarm, under the engine's `_evalGate`, and an alarm id that survives the reload starts from it. A still-true predicate then yields no transition — no emission, `Acked` / `Confirmed` / `LastTransitionUtc` unchanged, so the activation marker does not advance either. The #487 re-assert below still restores the node after a full rebuild, carrying the unchanged `LastTransitionUtc`. Decisions: - **Identity is the alarm id.** An edited predicate, severity, message template or equipment placement on the same id is the same alarm. Its condition carries over, the new predicate decides the next transition (a predicate that is now false is a real `Cleared`), and the next projection carries the new severity and message. - **Removed and re-added in one deploy** is the same id in both generations, so it carries over. An alarm **removed or disabled** (the host does not load a disabled plan) by one deploy and re-added by a later one is absent from the previous generation, so it is seeded from the store like a restart: the engine stopped evaluating it, so it is a new occurrence. - **Shelving** (including a timed shelve's expiry instant), `Confirmed`, an operator `Disable` and the comment trail carry verbatim; the shelving timer restarts with the load. - **A failed load** (compile error, store fault) **ends the generation** (review round 1, S3). From then until the next good load the engine is unsubscribed with its timer stopped — blind — so, by the same rule as a removed or disabled alarm, the next good load does not carry anything over: it reads the store like a new engine incarnation, and a still-true alarm is a new occurrence (`Activated`, `Unacknowledged`). Restating the pre-failure snapshot instead would hide an alarm that cleared and re-fired inside the window. While blind, an operator command is **rejected** with `ScriptedAlarmCommandRejectedException` (nothing is persisted — applying it to the half-built Fresh entry would overwrite the real row), and queued re-evaluations and shelving checks are dropped. **Since #937 an OPC UA Part 9 method (and a remote gRPC-data condition method) on a scripted condition reports this**: while the last load failed the node manager refuses the call `BadInvalidState` before the SDK applies anything (no event, nothing routed); a call that passed that pre-check and then met a rejection (it was queued behind a load that failed) also returns `BadInvalidState` — see [Operator command verdicts](#operator-command-verdicts-937). The AdminUI `/alerts` buttons still publish fire-and-forget ("Ack sent"), so for them the only record remains the host's Warning `… NOT applied — …`. The next good load re-asserts every node from the store. **Accepted trade-off:** because the next good load after a failed one reads the store (which has no `Active` column), each alarm whose predicate is still true is a new occurrence — **one transient failed deploy costs one duplicate activation (`Activated` + `Unacknowledged`, one `alerts` row) per still-true alarm** on the next good deploy. - **Concurrency.** The capture happens under `_evalGate`, so it includes every evaluation and operator command that completed before the load. An operator command looks its alarm up only once it holds the gate (review S1 — it used to look up first, so a command racing a load could save the load's interim `Fresh` entry over the carried Active condition), so a command queued behind a load applies **after** it, to the generation it produced (or is refused as an unknown alarm if the deploy removed it). A command whose result equals the current condition (an uncommented re-ack) writes nothing. - **A restatement writes nothing** (review S2). A load persists an alarm only if the load changed it; a carried or persisted seed left value-equal is not re-saved, and neither is a re-evaluation that left the condition unchanged. The row replicates last-writer-wins, so re-saving would push a node's stale carried state over the converged row on every deploy (and every push), and cost one replicated write per alarm per deploy. - **A timed shelve that expired before the load** is unshelved through the shelving check at the load (an `AutoUnshelve` comment and an `Unshelved` emission, review N5). Before, the predicate's own expiry unshelved it silently. - **Inputs not ready at the reload** (Bad / never-pushed, cold-start guard) hold the *carried* condition. Before the change they held the store's `Inactive`, which silently de-activated the engine and re-fired `Activated` on the next push. - **Out-of-process runner** (`Scripting:Runner` with the `ScriptedAlarm` seam): the batch startup pass seeds the same way. A runner that is not up at the reload freezes the carried condition (`BadResourceUnavailable`), not the store's `Inactive`. - **Warm standby.** Each node's engine receives every operator command (the `alarm-commands` topic is a cluster broadcast), so its in-memory condition is what that node already serves. A deploy no longer re-reads the replicated store row for a surviving alarm, so it does not repair a command this node missed; because a restatement is not written back, the converged row is not overwritten either, and the next engine incarnation reads it. Accepted divergence: a later **real** transition on that node (its predicate flips, or another command) still saves the node's whole condition, stale fields included, and that write replicates. - **Known state (A1) is unchanged.** Every reload still clears the established set and re-raises `OnInputsEstablished` after the first completed evaluation. The host holds it until the post-load re-assert. Every state change the engine makes is persisted inside the engine's `_evalGate` semaphore **before** the in-memory update (a store failure leaves both at the prior state), and a change that alters nothing is not written. On one node the row therefore matches the engine except where a command was rejected or missed; across the redundant pair the row is last-writer-wins and can lag a node that missed a command (warm standby, above). ### Post-(re)load condition-node re-assert (#487) A deploy that triggers a **full address-space rebuild** clears `_alarmConditions` and re-materialises every condition node fresh — inactive, acked, confirmed, unshelved. The engine, reloading in parallel, restates each surviving alarm from its previous in-memory condition (#935; persisted state only for an alarm new to the engine incarnation) and re-derives `Active` from the predicate, so it ends up *correct*; but a still-active alarm has **no transition to report**, so `LoadAsync` yields `EmissionKind.None` and `OnEngineEmission` drops it. Nothing then writes the node. Before this fix, an active alarm with static dependencies read **normal** to every OPC UA client after such a deploy, until its next real transition — which for a static-dependency alarm may never come. `ScriptedAlarmHostActor.ReassertConditionNodes` closes it. After each load completes it reads `ScriptedAlarmEngine.GetProjections()` — a plain read returning `ScriptedAlarmProjection` (condition state + the definition's severity + the resolved message template + last-observed worst-input quality) — and sends one `OpcUaPublishActor.AlarmStateUpdate` per alarm that is **not** in the Part 9 no-event position. Four properties are load-bearing: - **Node-only.** It sends `AlarmStateUpdate` and nothing else — never the `alerts` topic, never the telemetry hub. `alerts` is the historization path, so an alerts row per alarm per deploy would append a duplicate historian / AVEVA record every time anyone deploys. This is why the re-assert reads a projection instead of re-emitting: `ScriptedAlarmProjection` carries no `EmissionKind`, so there is nothing for the emission machinery — or a future refactor — to mistake for a transition. - **Only non-normal alarms.** An alarm in the no-event position (enabled, inactive, acked, confirmed, unshelved) already matches what the materialise built, so it is skipped. That keeps a never-fired alarm byte-identical to a deploy without this pass — including its Message, which the materialise seeds with the alarm's display name — and writes nothing at all on the common all-normal deploy. - **Ordering.** `DriverHostActor` tells `RebuildAddressSpace` to the publish actor *before* it tells `ApplyScriptedAlarms` to the host, and the re-assert runs later still (after an awaited `LoadAsync` pipes back). Both are local `Tell`s, which enqueue synchronously, so the re-materialise is already queued ahead of these writes. - **No duplicate Part 9 events.** `WriteAlarmCondition`'s delta-gate compares the incoming snapshot against the node's *current* state: a re-assert onto a freshly materialised (normal) node is a genuine delta and fires exactly one condition event — correct, since the rebuild reset what clients see — while a re-assert onto a surgically-preserved node that already holds the same state is suppressed. The write is ungated by redundancy role, like every other node write here; the Secondary keeps its address space warm for failover. The timestamp carried is the condition's own `LastTransitionUtc`, **not** the deploy instant, so a client reading `Time` / `ReceiveTime` after a rebuild still sees when the alarm actually went active. ## Source integration `ScriptedAlarmSource` (`ScriptedAlarmSource.cs`) adapts the engine to the driver-agnostic `IAlarmSource` interface. The existing `AlarmSurfaceInvoker` + `GenericDriverNodeManager` fan-out consumes it the same way it consumes Galaxy / AB CIP / FOCAS sources — there is no scripted-alarm-specific code path in the server plumbing. From that point on, the flow into `AlarmConditionState` nodes, the `AlarmAck` session check, and the Historian sink is shared — see [AlarmTracking.md](AlarmTracking.md). Two mapping notes specific to this adapter: - `SubscribeAlarmsAsync` accepts a list of source-node-id filters, interpreted as Equipment-path prefixes. Empty list matches every alarm. Each emission is matched against every live subscription — the adapter keeps no per-subscription cursor. - `IAlarmSource.AcknowledgeAsync` accepts an `AlarmAcknowledgeRequest` list; the `OperatorUser` field carries the authenticated principal when available. The adapter passes `OperatorUser` through to the engine's `AcknowledgeAsync`; when `OperatorUser` is null (non-OPC-UA callers using the raw interface) it falls back to `"opcua-client"` so callers still produce an audit entry. The server's Part 9 method handlers call the engine's richer `AcknowledgeAsync` / `ConfirmAsync` / `OneShotShelveAsync` / `TimedShelveAsync` / `UnshelveAsync` / `AddCommentAsync` directly with the authenticated principal instead of going through this adapter. ## Native driver alarms (equipment-tag path) > Design reference: [docs/plans/2026-06-14-galaxy-phase-b-native-alarms-design.md](plans/2026-06-14-galaxy-phase-b-native-alarms-design.md) A native driver alarm is an authored equipment `Tag` bound to an `IAlarmSource` driver (today: Galaxy `GalaxyMxGateway`) whose `TagConfig` carries an `"alarm"` object alongside the usual `"FullName"`: ```json { "FullName": "TestMachine_002.HiAlarm", "alarm": { "alarmType": "OffNormalAlarm", "severity": 700 } } ``` `"alarm"` **absent** → the tag materialises as an ordinary value variable (unchanged behaviour). `"alarm"` **present** → the tag materialises as a Part 9 `AlarmConditionState` under its equipment folder **instead of** a value variable. No EF/schema change is required; the intent rides in the schemaless `TagConfig` blob and is parsed byte-parity in both the compose (`AddressSpaceComposer`) and deploy (`DeploymentArtifact`) paths. > **v3 Batch 4 — multi-notifier fan-out.** The `"alarm"` object now rides on a **raw > tag** authored in `/raw` (referenced into equipment), and the Part 9 condition > materializes **once at the raw tag** — its `ConditionId` is the tag's **RawPath**, its > parent notifier is the raw device/group folder. For **each referencing equipment**, the > node manager (`WireAlarmNotifiers`) wires the SDK `AddNotifier` pattern > (`alarm.AddNotifier(equipFolder, isInverse:true)` + `equipFolder.AddNotifier(alarm)` + > `EnsureFolderIsEventNotifier(equipFolder)`) so the single condition fans to the raw device > folder AND every equipment folder. A **single** `ReportEvent` fans to all notifier roots — > a Server-object subscriber sees **exactly one** copy (the Part 9 shared-snapshot dedup), > never one-per-root. Teardown is symmetric (`RemoveNotifier(..., bidirectional:true)` on > rebuild / reference removal) so inverse-notifier entries never leak across redeploys. > Ack/confirm/shelve route on **`ConditionId = RawPath`** (never `SourceNodeId`), and the > `/alerts` row lists the referencing equipment paths. The equipment gets the condition > **only**: no UNS value variable is created for a reference to an alarm-bearing tag (#896), > matching the raw side, which has no value variable either. See > [AlarmTracking.md](AlarmTracking.md) and the WP4 section of > `docs/plans/2026-07-15-v3-batch4-address-space-plan.md`. ### TagConfig alarm fields | Field | Values | Default | |---|---|---| | `alarmType` | `"AlarmCondition"`, `"OffNormalAlarm"`, `"DiscreteAlarm"`, `"LimitAlarm"` | `"AlarmCondition"` | | `severity` | OPC UA 1–1000 scale | `500` | | `historizeToAveva` | `true` / `false` / absent | absent (historize) | An unknown `alarmType` string falls back to the base `AlarmCondition` OPC UA ObjectType. `severity` seeds the condition's initial severity at materialisation; the driver's live alarm events may carry a different severity that overrides it at runtime. **`historizeToAveva`** is a `bool?` opt-out for the AVEVA Historian durable write. Set it to `false` to suppress writing this alarm's transitions to AVEVA Historian; absent or `true` historizes as usual. The live `/alerts` feed and OPC UA condition events are always unaffected regardless of this flag. The field is gated in `HistorianAdapterActor` with `is not false` semantics — a missing field (e.g. from an older config) defaults to historizing rather than silently dropping an audit row during a rolling restart. On the Tag modal, the **"Historize to AVEVA"** checkbox (in the alarm section) controls this field. The **Galaxy address picker** pre-fills a default `alarm` object (`{"alarmType":"OffNormalAlarm","severity":700}`) when it detects that the selected attribute is itself an alarm (`IsAlarm == true`); the pre-fill never overwrites an already-authored alarm section. > **Distinct from tag-value historization.** `alarm.historizeToAveva` controls > alarm-transition AVEVA writes only. Tag-value history is controlled by the > top-level `isHistorized` field (see [Historian.md](Historian.md)). #### Severity mapping The authored `severity` (1–1000) seeds the OPC UA condition node at materialisation time. Every native transition replaces it from the first transition onward. A source with a finer scale supplies the exact Part 9 severity (`AlarmEventArgs.OpcUaSeverity`, e.g. MTConnect Fault = 800, #626); otherwise `NativeAlarmProjector.MapSeverity` maps the driver's `AlarmSeverity` to one of four fixed values: | `AlarmSeverity` enum | Projected value | |---|---| | `Low` | 200 | | `Medium` | 500 | | `High` | 700 | | `Critical` | 900 | | *(default/unspecified)* | 500 | The condition node carries that projected integer **verbatim** (clamped to 1–1000), on a direct Read and on every event. It used to be re-bucketed onto the SDK's five `EventSeverity` points (< 200 → 100, < 400 → 300, < 600 → 500, < 800 → 700, else 900) by the node manager — so an MTConnect Fault read and evented as 900, a `Low` native alarm as 300, and a scripted alarm the engine graded 1000 published 900 while its `/alerts` row said 1000. That re-bucketing is gone (the `EventSeverity` enum merely names points on the 1–1000 scale; any value is valid). ### Runtime flow The driver's live `IAlarmSource.OnAlarmEvent` is the sole input. Transition kinds (`Raise`, `Clear`, `Acknowledge`, `Retrigger`, `ActiveAcknowledged`) drive the condition's Active / Acknowledged / Severity / Message fields via `NativeAlarmProjector`, a pure per-condition state projector. The projected `AlarmConditionSnapshot` is forwarded through `DriverHostActor` → `OpcUaPublishActor.AlarmStateUpdate` → `OtOpcUaNodeManager.WriteAlarmCondition` — the same delta-gated Part 9 condition-event path that scripted alarms use, reused verbatim. The same `AlarmTransitionEvent` that scripted alarms publish is emitted to the cluster `alerts` topic, so the AdminUI `/alerts` page and the Historian sink see native alarm transitions identically. Publication to the `alerts` topic is **Primary-gated** (only the redundancy Primary publishes cluster-wide transitions); the OPC UA condition-node write is ungated on all nodes so a Secondary stays warm for failover. The alarm is authored on the **raw tag** in `/raw` by including the `"alarm"` object in the tag's `TagConfig` JSON (v3 Batch 4 — equipment no longer authors tags; it references raw tags). No other configuration is required: any equipment that references the raw tag automatically receives the alarm at its equipment folder via the multi-notifier fan-out above. ### Native-alarm OPC UA operator operations An OPC UA client can **Acknowledge** a native (e.g. Galaxy) condition and the ack now propagates to the device. The `OnAcknowledge` handler on a native condition routes through a separate `NativeAlarmAckRouter` seam (instead of the scripted `AlarmCommandRouter`) → `DriverHostActor` (a condition NodeId → `(DriverInstanceId, FullName)` inverse map, Primary-gated) → the owning driver's `IAlarmSource.AcknowledgeAsync` → Galaxy gateway → AVEVA. The call carries the authenticated operator's display name via the `AlarmAcknowledgeRequest.OperatorUser` field. The actor route back to OPC UA is fire-and-forget; a failed or refused upstream ack reverts the condition to unacknowledged (#760), and one the driver can refuse without I/O fails the call synchronously with `BadUserAccessDenied`. The Galaxy adapter awaits its correlated RPC; this does not establish delivery to AVEVA event history. Galaxy value writes use a separate correlated write-outcome path. See [AlarmTracking.md §Native alarm acknowledge → AVEVA](AlarmTracking.md#native-alarm-acknowledge--aveva) for the full routing diagram. **Enable/Disable** on a native condition returns `BadNotSupported` — the driver backing a native alarm has no enable/disable surface distinct from OPC UA; the Part 9 enable/disable concept maps to the scripted-alarm engine only. ## Inbound operator ack/shelve Operators interact with active scripted alarms through two surfaces — both converge on the same `alarm-commands` DPS topic consumed by `ScriptedAlarmHostActor`. ### AlarmAck gate (OPC UA method path) `OtOpcUaNodeManager` wires the OPC UA Part 9 condition methods (Acknowledge / Confirm / AddComment / OneShotShelve / TimedShelve / Unshelve / Enable / Disable) on each `AlarmConditionState` node. Every method call is gated on the `AlarmAck` role — fail-closed: a session with no resolved roles or no `AlarmAck`-conferring grant on its API-key principal (`NodeAcl`; LDAP is AdminUI-only, see `docs/security.md`) receives `BadUserAccessDenied` immediately without reaching the engine. The role is carried on the session by `RoleCarryingUserIdentity` (a `UserIdentity` subclass that preserves the API-key-resolved role set past `OpcUaApplicationHost`). On allow, the handler publishes a `Commons.OpcUa.AlarmCommand` (containing command kind, condition id, comment, and operator principal) onto the `alarm-commands` DPS topic. The node manager itself stays Akka-free: the dispatch action is a settable `Action` injected at boot by the hosted service. **Scripted vs native conditions — Enable/Disable and Acknowledge:** - **Scripted conditions** — all eight Part 9 operations (including Enable/Disable) route through `AlarmCommandRouter` onto the `alarm-commands` topic, which `ScriptedAlarmHostActor` dispatches to the engine (`EnableAsync` / `DisableAsync` / `AcknowledgeAsync` / …). On enable, `ActiveState` is re-derived from the next predicate evaluation. - **Native (driver-fed) conditions** — `OnAcknowledge` branches to `NativeAlarmAckRouter` and routes the ack to the owning driver rather than the scripted engine (see §[Native-alarm OPC UA operator operations](#native-alarm-opc-ua-operator-operations) above). `OnEnableDisable`, `OnConfirm` and `OnShelve` return `BadNotSupported` immediately — a native condition supports Acknowledge and AddComment only (no engine-side surface, no upstream path, and the driver projection owns its Confirmed/Shelving; Gitea #587 review). ### Operator command verdicts (#937) A scripted condition's Part 9 method no longer returns Good merely because the command was published. Two layers, neither of which blocks under the node manager's `Lock`: 1. **Pre-check** — `ScriptedAlarmCommandReadinessView` (Runtime singleton) holds the outcome of the host's latest completed load; the handler reads it (one volatile read) after the role/ACL gate and the Warm-standby check. While the last load failed it returns `BadInvalidState` and nothing is applied, routed or reported. It never refuses before the first load. 2. **Bounded ask** — inside the Call service (`OtOpcUaNodeManager.CallAsync`, which the SDK invokes off `Lock`), each local request runs through the SDK's `base.Call` on its own; the handler, under `Lock`, only *starts* the ask (`AlarmCommandAsker`): the hosted service broadcasts the command on `alarm-commands` for the redundant peer (as before) and asks **this node's** `ScriptedAlarmHostActor` (via `DriverHostActor`, `ExecuteAlarmCommand`) for its verdict, with a fresh `CommandId` so the local host applies whichever copy reaches it first, once. The SDK applies its node state and reports the one method event exactly as before; then the Call awaits the verdict with no lock held. | Engine verdict | Method status | |---|---| | applied (incl. an idempotent no-op) | `Good` | | refused — last load failed, alarm not loaded on this node, malformed command, no engine on this node | `BadInvalidState` | | no answer within min(5 s, request deadline − 250 ms), or the engine op timed out / failed in the store | `BadTimeout` / `BadInternalError`, diagnostic "OutcomeUnknown" — the command **may still apply**, never reported as refused | `BadInvalidState` is Part 4's general "object … uninitialized or in some other invalid state" code; Part 9's method result codes (bad EventId, already acked/confirmed/shelved, disabled, shelving time out of range) do not cover "the state owner cannot act", and the server already uses `BadInvalidState` for a native ack off-Primary. The status is the contract: a plain SDK client sees only the code (the reason text travels in diagnostics, returned only when requested). **Redundancy.** The verdict is the LOCAL engine's — the one that projects this node's condition node. The peer still applies its broadcast copy independently (and both engines' saves converge through the replicated LocalDb row). A remote gRPC-data `CallConditionMethod` on a scripted condition carries the same verdict (`ExecuteConditionMethodAsync`): applied ⇒ `DriverConfirmedSuccess`, refused after dispatch ⇒ `DriverConfirmedFailure`, no answer ⇒ `OutcomeUnknown`. **Residual.** Only the pre-check stops the SDK from applying the node change. A refusal that arrives through the ask (a load in flight when the command queued behind it, which then failed) leaves the node showing the change — and its one event reported — until the next good deploy re-asserts the node from the store; the caller gets `BadInvalidState`. **Not covered:** the AdminUI `/alerts` buttons are still fire-and-forget across the central→node transport (they report "Ack sent", not "applied"). `OnTimedUnshelve` (the SDK's internal auto-unshelve timer, armed for the real remaining time since Gitea #597) is a **no-op**: the engine owns timed-shelve expiry via `ApplyShelvingCheck` (`system / AutoUnshelve`), and routing an `Unshelve` from the timer pre-empted that on every expiry as an operator-style unshelve from both pair nodes (review R1 M2). ### Delta-gate de-duplication `WriteAlarmCondition` fires a Part 9 condition event only when the incoming state differs from the node's current live state. For an OPC UA method call (Acknowledge, Confirm, AddComment, the shelve methods, Enable/Disable) the SDK applies the new state to the node, and the node manager then reports **the one** condition event for it from the method path (Gitea #587 — the SDK reports none of its own, since `AutoReportStateChanges` stays false; the shelve methods' state is applied by the node manager, because the SDK's never applies it; a call that changed nothing — e.g. an uncommented re-ack — reports nothing; a re-ack carrying a comment reports that comment once, Gitea #597, and the engine records it as an `AddComment` so it is persisted and replicated, review R1 m1). Native (driver-fed) conditions support only Acknowledge and AddComment; their Confirm, shelve and Enable/Disable methods return `BadNotSupported`, and their Acknowledge is refused with `BadInvalidState` on a node that is not the redundancy Primary (Gitea #597). A timed shelve's `UnshelveTime` counts down to the engine's expiry (the projection carries `UnshelveAtUtc`). The engine's later re-projection of the same transition finds the node already in that state and is suppressed, so each accepted call yields exactly one event. See `docs/AlarmTracking.md` §"One condition event per method call". ### AdminUI path The AdminUI `/alerts` page (`Alerts.razor`) shows per-row **Acknowledge / Shelve / Unshelve** buttons. These are gated by the `DriverOperator` AdminUI policy and routed through the `AdminOperationsActor` cluster singleton (`AcknowledgeAlarmCommand` / `ShelveAlarmCommand`), which publishes onto the same `alarm-commands` topic. Cross-node routing is handled by the cluster singleton — the command always reaches the driver-role node hosting the engine that owns the alarm regardless of which AdminUI instance the operator is connected to. The Shelve button accepts a duration (minutes) and passes it to `ShelveAlarmAsync(Timed, unshelveAtUtc)`; result chips auto-clear after ~8 s. The `/alerts` and `/script-log` live-status pills reflect real feed health driven by the SignalR bridge actors' DPS subscription state. Under redundancy, the `alerts` topic rows are deduplicated to the Primary node — see [Redundancy.md §Primary-gated alarm emission and historization](Redundancy.md#primary-gated-alarm-emission-and-historization). ### Client.CLI path The Client.CLI supports `ack`, `confirm`, and `shelve` commands that call the Part 9 condition methods directly on the OPC UA server: ```bash dotnet run --project src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI -- ack -u opc.tcp://localhost:4840 -c "ns=2;s=Plant/Line1/Oven::OverTemp" -m "Acknowledged by ops" dotnet run --project src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI -- confirm -u opc.tcp://localhost:4840 -c "ns=2;s=Plant/Line1/Oven::OverTemp" -m "Confirmed" dotnet run --project src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI -- shelve -u opc.tcp://localhost:4840 -c "ns=2;s=Plant/Line1/Oven::OverTemp" --timed 300000 ``` TimedShelve duration is sent as OPC UA `Duration` (milliseconds). The CLI uses `IOpcUaClientService.ConfirmAlarmAsync` / `ShelveAlarmAsync`. ### ScriptedAlarmHostActor dispatch `ScriptedAlarmHostActor` subscribes to the `alarm-commands` DPS topic, ownership-filters each command (each node only acts on the alarms it owns), and dispatches to the matching `ScriptedAlarmEngine` operation (`AcknowledgeAsync` / `ConfirmAsync` / `OneShotShelveAsync` / `TimedShelveAsync` / `UnshelveAsync` / `EnableAsync` / `DisableAsync` / `AddCommentAsync`). No explicit re-projection is needed — the engine's existing `OnEvent` callback updates the OPC UA node after the transition. Emissions map into `AlarmEventArgs` as `AlarmType = Kind.ToString()`, `SourceNodeId = EquipmentPath`, `ConditionId = AlarmId`, `Message = resolved template string`, `Severity` carried verbatim, `SourceTimestampUtc = emission time`. ## Composition `AddressSpaceComposer` (`src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceComposer.cs`) is a pure data composer; it has no knowledge of `ScriptedAlarmEngine`. It maps `ScriptedAlarm` config-DB rows into `ScriptedAlarmPlan` records that the driver-role host actor startup path consumes. In the v2 actor system, scripted-alarm engine composition is owned by the driver-role host: 1. The host reads the generation's `ScriptedAlarm` + `Script` rows and resolves each row's `PredicateScriptId` to produce a `ScriptedAlarmDefinition` list. Unknown or disabled scripts fail fast — the DB publish guarantees referential integrity but this is a belt-and-braces check. 2. A `ScriptedAlarmEngine` is constructed with the upstream-tag source, an `IAlarmStateStore` (production: `LocalDbAlarmConditionStateStore`), a shared `ScriptLoggerFactory` keyed to `scripts-*.log`, and the root Serilog logger. 3. `alarmEngine.OnEvent` is wired to the historian sink. Fire-and-forget — the SQLite store-and-forward sink is already non-blocking. 4. `LoadAsync(alarmDefs)` runs on startup and on every deploy: it compiles every predicate, subscribes to the union of predicate inputs and message-template tokens, seeds the value cache, seeds each alarm's condition (`previous ?? persisted ?? Fresh`, #935), re-derives `ActiveState` from a fresh predicate evaluation, and starts the 5s shelving timer. Compile failures are aggregated into one `InvalidOperationException` so operators see every bad predicate in one startup log line rather than one at a time. 5. A `ScriptedAlarmSource` is created for the event stream. The v2 `ScriptedAlarmActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmActor.cs`) owns the active-state surface for OPC UA variable reads on the alarm's condition-state node — unknown alarm ids return `BadNodeIdUnknown` rather than silently reading `false`. Both engine and source are disposed on server shutdown via the driver-role host teardown path. ## Forwarding over a data connection An origin can stream its scripted conditions to another cluster over a gRPC data connection ([DataConnections.md](DataConnections.md#condition-forwarding-end-to-end-a1a3)). The consumer projects them as imported conditions ([AlarmTracking.md](AlarmTracking.md#imported-conditions-grpc-data-connections)). Two scripted-specific rules apply. **A scripted condition becomes *known* only after its first completed evaluation.** - `Active` is not persisted. After a load, the engine re-derives it from a value cache that `ReadTag` seeds before any driver has published, so "loaded" is not "known". - The engine raises `OnInputsEstablished(alarmId, Established: true)` only after the first predicate evaluation that **completes** since the load or the last revert (`ScriptedAlarmEngine.NoteEvaluationCompleted`). Completes means: no input still never-pushed, valid evidence, and the predicate returned a bool. - A Bad input, a script runner that is not up, or a predicate that timed out, was refused or threw establishes nothing. - The flag is queued as the last of that evaluation's emissions, so the Active projection is dispatched first. `ScriptedAlarmHostActor` then sends `MarkConditionsKnown` on the same chain as its `AlarmStateUpdate`s. - During a load the host holds the flags until the post-load re-assert of non-normal (#487) conditions has been queued. This keeps a freshly re-materialised, inactive node from being declared known ahead of its persisted active state. - An input that reverts to never-pushed (`NoteInputsReverted`, e.g. a tag re-created by a deploy) withdraws "known". Every reload clears the established set and re-raises the flag for each alarm as it evaluates again. - Until then the origin streams the condition with `state_known = false`, and the consumer shows it `Quality = UncertainInitialValue` and never as "known inactive". A scripted alarm whose inputs never arrive stays unknown, which is honest: the origin cannot know its state either. - A projection alone never marks a scripted condition known. That includes a restored-unacked re-assert and an early ack; only native projections do that (A1 review B1). **What forwards.** - Scripted conditions are listed at their `ScriptedAlarmId` in the **UNS** realm, under the equipment that owns them. A UNS mapping whose remote root covers that equipment imports them; a Raw mapping does not. - They advertise Acknowledge, AddComment **and Confirm** (`supported_methods` = all three), gated by the export, connection and mapping bits `AlarmAcknowledge` (128) and `AlarmConfirm` (256). - A remote call is dispatched through the same wrapped handler as a local OPC UA call, so the engine receives the same, unchanged `AlarmCommand` (`User` = the connection's service principal). The consumer answers `Good` once the origin's handler has applied the call (`DriverConfirmedSuccess`; native conditions answer `AcceptedUnconfirmed` instead, see DataConnections.md). The consumer's node changes only when the resulting record arrives. - Shelve/Unshelve/Enable/Disable are not forwarded (`BadNotSupported` on the consumer; bit 512 reserved). Operators shelve at the origin, where `/alerts` and the shelving timers live. - The activation marker survives a rebuild for scripted conditions, so the engine's re-assert of a still-active alarm is not a new occurrence. Consumer EventIds stay ackable across that re-assert. ## Key source files - `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs` — orchestrator, cascade wiring, shelving timer, `OnEvent` emission - `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmSource.cs` — `IAlarmSource` adapter over the engine - `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmDefinition.cs` — runtime definition record - `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs` — pure-function state machine + `TransitionResult` / `EmissionKind` - `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/AlarmConditionState.cs` — persisted state record + `AlarmComment` audit entry + `ShelvingState` - `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/AlarmPredicateContext.cs` — script-side `ScriptContext` (read-only, write rejected) - `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/AlarmTypes.cs` — `AlarmKind` + `ShelvingKind` + four Part 9 state enums (`AlarmEnabledState`, `AlarmActiveState`, `AlarmAckedState`, `AlarmConfirmedState`); `AlarmSeverity` (`Low`/`Medium`/`High`/`Critical`) lives in `src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmSource.cs` - `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/MessageTemplate.cs` — `{path}` placeholder resolver - `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/IAlarmStateStore.cs` — persistence contract + `InMemoryAlarmStateStore` default - `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceComposer.cs` — pure data composer: config-DB entities → `AddressSpaceComposition` (UNS topology + raw subtree + driver/alarm plans) - `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs` — applies the composed plan into the SDK node manager - `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmActor.cs` — actor that owns the per-alarm state machine; publishes `AlarmTransitionEvent` on the cluster `alerts` DPS topic - `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/LocalDbAlarmConditionStateStore.cs` — production `IAlarmStateStore` backed by the node's replicated LocalDb - `src/Server/ZB.MOM.WW.OtOpcUa.Host/Engines/RoslynScriptedAlarmEvaluator.cs` — production Roslyn predicate evaluator