# IEA Central Enterprise Server (`CES.Api`) — Comprehensive API Reference & AI Developer Agent Integration Blueprint

**Platform Release:** `v1.0.54` (73 Production Epics)  
**Target Enterprise Server (Purdue L4):** `http://192.168.5.102:5050` (HTTP) | `https://192.168.5.102:5444` (HTTPS / TLS 1.3)  
**Site Relay Server (Purdue L3):** `http://<srs-ip>:5051` (HTTP) | `https://<srs-ip>:5443` (HTTPS / mTLS)  
**PLC / SoftPLC Modbus TCP Server (Purdue L2/L3):** `<srs-ip>:502` (or `1502`)  
**CrowdCompatibility Cloud API:** `https://us-central1-studio-4863129343-87305.cloudfunctions.net/api`  
**OpenAPI / Swagger Specification:** `https://192.168.5.102:5444/swagger/v1/swagger.json`

---

## 🤖 1. Master System Prompt for AI Coding Agents (Copy-Paste Into Cursor / Claude Code / Antigravity / Copilot)

> **Instructions for Developers:** Copy the block below into your AI agent's context file (`AGENTS.md`, `CLAUDE.md`, `.cursorrules`, or chat prompt) to give your AI coding assistant zero-shot mastery of the CES API, authentication model, and OT safety guardrails.

```markdown
# SYSTEM CONTEXT: IEA Central Enterprise Server (CES.Api v1.0.54) Integration Rules

You are integrating an external enterprise system (ServiceNow ITSM/CMDB/VR, SIEM/SOAR, SCADA HMI, Hypervisor Orchestrator, or custom Python/C#/TypeScript automation) with the **IEA Central Enterprise Server (`CES.Api`)**.

## 1. Base URLs & Network Topology (Purdue Levels 1–4)
- **Central Enterprise Server (CES - L4):** `https://192.168.5.102:5444` (or `http://192.168.5.102:5050`)
- **Site Relay Server (SRS - L3 DMZ):** `https://<srs-host>:5443` (or `http://<srs-host>:5051`)
- **NEVER hardcode `localhost`** for production or multi-node testbed integrations; always parameterize `CES_BASE_URL` (defaulting to `https://192.168.5.102:5444`).
- **Root CA Trust Bootstrap:** Download the DER/PEM Root CA from `GET {CES_BASE_URL}/certs/root.cer` (or `/deploy/root.cer`) to verify TLS 1.3 connections without disabling certificate verification.

## 2. Unified Dual-Authentication & Industrial Safety Guardrail Headers
1. **Headless Northbound API Key (Recommended for ServiceNow, SIEM/SOAR, CI/CD):**
   - Header: `X-Api-Key: <your-northbound-api-key>`
   - Grants `CallerRole = "Admin"`, `CallerType = "ServiceNowServiceAccount"`, `IsHeadless = true`.
   - Validated via constant-time SHA-256 comparison against `/api/settings/keys`.
2. **Interactive Operator Bearer Session Token (For Custom Portals & Web Apps):**
   - Obtain via `POST /api/auth/login` with `{ "email": "...", "password": "..." }`.
   - Header: `Authorization: Bearer <token>`
   - Enforces RBAC role (`Admin`, `SiteAdmin`, `Operator`, `Viewer`/`User`), `ManagedSites`, and `AssignedCredentialIds` (including Hybrid On-Premises Active Directory LDAP/LDAPS & Azure Entra ID group inheritance).
3. **Mandatory Change Request Header for Headless Mutating/Destructive Actions (`IndustrialSafetyGuardrail`):**
   - Header: `X-Change-Ticket: CHG-<AlphanumericId>` (Regex: `^CHG-[A-Za-z0-9_-]+$`, e.g., `CHG-104920`, or query param `?ticketId=CHG-104920`).
   - **CRITICAL OT SAFETY RULE:** When calling destructive or state-changing endpoints (patch dispatch, reboot orchestration, remote script execution) using `X-Api-Key` (`IsHeadless == true`), CES automatically verifies:
     (a) `X-Change-Ticket` matches `^CHG-[A-Za-z0-9_-]+$`, AND
     (b) The target endpoint's Maintenance Zone (`GroupId`) is currently **INSIDE an active Cron Maintenance Window** (unless `bypassMaintenanceWindow: true` is explicitly passed on non-disruptive scheduled/interactive jobs via `/api/jobs/run` or `/api/jobs/schedules`).
     If called outside an active window without bypass, CES returns `HTTP 403 Forbidden` / `409 Conflict` with a structured `SafetyEvaluationResult` payload (`requiresTicket`, `requiresWindow`, `isInsideWindow: false`). To stage payloads outside a window without executing, use **Pre-Staging (`STAGE_PATCH`)**.

## 3. Core Data Sovereignty & Operational Invariants
- **No Uncoordinated Reboots:** Never trigger OS restarts outside a released Maintenance Window (`windowReleaseState == "Released"`).
- **CMDB Manual Override Lock (`🔒`):** When updating asset attributes via `PUT /api/cmdb/inventory/{machineId}/hardware`, CES sets `hardwareManualOverride = true` so background WMI telemetry and IEEE MAC OUI sweeps never overwrite human/ITSM-curated asset specs unless `"resetToAuto": true` is passed.
- **Sovereign Service Desk Queues:**
  - `INC` (`targetScope: "Asset"`) and `REQ` (`targetScope: "Asset" | "Site"`) are locked to `SiteQueue` (`neverLeavesPremises: true`).
  - Only `Admin` / `SiteAdmin` can promote an incident or feature request to `PLATFORM_INC` (`POST /api/tickets/{id}/promote-to-platform-inc`) or `DEV_REQ` (`POST /api/tickets/{id}/promote`), which automatically strips all hostnames, IPs, and OS usernames via `SanitizeForCloud()`.
- **Core Industrial IPAM & Dynamic Cisco/Stratix Physical + VLAN Connectivity (`/api/ipam/sites/{siteId}/*` — `v1.0.54`):**
  - Enqueue Purdue L3 `SRS.Service` Cisco/Stratix crawls (`CDP`, per-VLAN `SNMPv2c` `@<vlanId>` / `SNMPv3` `contextName="vlan-<id>"` CAM tables, Switch ARP caches, and IOS XE `RESTCONF`) via `POST /api/ipam/sites/{siteId}/crawl` (honoring `DiscoveryExcludedAddresses` fragile OT exclusions).
  - Query `/24` & `/16` paginated subnet heatmaps via `GET /api/ipam/sites/{siteId}/subnets/{subnetId}/grid?page=1&pageSize=256`, render live `physical` or `vlan` connectivity topologies via `GET /api/ipam/sites/{siteId}/topology?mode=physical|vlan`, pin Known-Good Cabling Baselines via `POST /api/ipam/sites/{siteId}/baseline/pin`, quarantine rogue cabling drift at `Seq=500` via `POST /api/ipam/sites/{siteId}/drifts/{driftId}/quarantine`, and synchronize ServiceNow `cmdb_ci_ip_network` / `cmdb_ci_ip_address` records via `POST /api/ipam/sites/{siteId}/servicenow-sync`.
- **Cryptographic Rolling mTLS & ECDSA P-256 Canonical Signing (`v1.0.52`–`v1.0.53`):**
  - Southbound `MtlsNode` identity cannot be spoofed via Bearer JWTs; remote PowerShell jobs and `.ieaupgrade` manifests are canonically signed with asymmetric **ECDSA P-256 (`SHA-256`)** verified against `iea_signing_public.pem`.
```

---

## 🔐 2. Authentication, Security & Rate-Limiting Architecture

### 2.1 Authentication Header Matrix

| Integration Scenario | HTTP Header(s) | Identity & RBAC Scope | Special Constraints |
| :--- | :--- | :--- | :--- |
| **ServiceNow / SIEM / SOAR / Headless Automation (Read-Only)** | `X-Api-Key: <api-key>` | `ServiceNowServiceAccount` (`Admin` scope across all sites) | Constant-time SHA-256 verification. |
| **ServiceNow / Headless Automation (Mutating / Patch / Reboot)** | `X-Api-Key: <api-key>`<br>`X-Change-Ticket: CHG-104920` | `ServiceNowServiceAccount` (`Admin` scope) | Evaluated by `IndustrialSafetyGuardrail`: requires valid `CHG-*` ticket **and** active Cron Maintenance Window on the target group. |
| **Custom Web Portal / Operator UI** | `Authorization: Bearer <token>` | `InteractiveUser` (`Admin`, `SiteAdmin`, `Operator`, `Viewer`/`User`) | Scoped to user's `ManagedSites` and `AssignedCredentialIds` (supports On-Prem AD & Azure Entra ID multi-group union). |
| **ESP32 Panel SmartKey Hardware Interlock** | `X-SmartKey-Signature: <hmac-sha256-hex>` | Physical Zone Interlock (`LOCKED`, `RELEASED`, `VALIDATE`, `ROLLBACK`) | HMAC-SHA256 computed over `"{keyUid}|{zoneId}|{state}|{timestampUtc}"`. |
| **Southbound Agent / SRS Telemetry & Pull** | Client mTLS Certificate + `X-Asap-Wakeup` | `IEA.Agent` / `SRS.Service` | Sliding-window rate limit: `120 req / 60s` for `/api/ingest`, `10 req / 60s` for `/api/certs/sign`. |

### 2.2 Standard Error & Guardrail Response Envelope

When an API call is rejected by `IndustrialSafetyGuardrail` or rate limiting, `CES.Api` returns deterministic JSON so AI agents and orchestrators can branch cleanly:

```json
{
  "isPermitted": false,
  "actionName": "DispatchPatchJob",
  "reason": "Target group 'grp-packaging-line-a' is currently OUTSIDE all active Maintenance Windows. Headless execution prohibited to protect continuous plant operations.",
  "requiresChangeTicket": true,
  "providedChangeTicket": "CHG-104920",
  "requiresMaintenanceWindow": true,
  "isInsideMaintenanceWindow": false,
  "targetSiteId": "SITE-DETROIT-01",
  "targetGroupId": "grp-packaging-line-a"
}
```

---

## 📚 3. Complete REST, Fieldbus & Hardware API Reference (`v1.0.54`)

### 3.1 Authentication, Users, Console Groups & Hybrid Directory Services (`AuthController`, `SettingsController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `POST` | `/api/auth/login` | Public | Authenticates `{ "email", "password" }` and returns `{ "token", "role", "email", "userId", "managedSiteIds", "assignedCredentialIds" }`. |
| `GET` | `/api/users` | `Admin` | Lists all console users including `inheritFromAdGroup`, `authProvider` (`Local`, `OnPremAd`, `AzureAd`), `adSamAccountName`, `azureObjectId`. |
| `POST` | `/api/users` | `Admin` | Creates a user or maps an AD/Entra user (`{ "email", "role", "inheritFromAdGroup", "consoleGroupIds" }`). |
| `POST` | `/api/users/sync-ad-groups` | `Admin` | Evaluates multi-group union (highest privilege role + union of `assignedSiteIds` and `assignedCredentialIds`) across On-Prem AD and Azure Entra ID. |
| `GET` | `/api/groups` | `Admin` | Lists Console Access & AD/Azure Security Permission Profiles (`DirectorySource`: `OnPremAd` \| `AzureAd` \| `Hybrid`, `AdGroupName`, `AdDistinguishedName`, `AdSecurityIdentifier`, `AzureGroupObjectId`). |
| `POST` | `/api/groups` | `Admin` | Creates a Console Access Group / AD Security Profile with `role`, `siteIds`, and `credentialIds`. |
| `GET / POST` | `/api/settings/auth` | `Admin` | Gets or updates Directory Services config (`enableAdGroupInheritance`, `directoryMode`, `ldapServerHost`, `ldapPort`, `useLdaps`, `baseDn`, `azureTenantId`, `azureClientId`). |
| `POST` | `/api/settings/auth/test-directory` | `Admin` | Tests live LDAP/LDAPS and Azure Entra ID connectivity and schema bindings. |
| `GET / POST / DELETE` | `/api/settings/keys` | `Admin` | Lists, generates (`{ "providerName", "description" }`), or revokes SHA-256 Northbound API keys. |

---

### 3.2 CMDB Asset Inventory, Editable Hardware Overrides (`🔒`), Offline IEEE MAC OUI & ServiceNow Firewall CIs (`CmdbController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `GET` | `/api/cmdb/inventory` | `Viewer`+ / `X-Api-Key` | Query params: `?siteId=&groupId=&includeUnmanaged=true`. Returns flattened 50+ attribute CMDB records (`machineId`, `hostname`, `customLabel`, `ipAddress`, `macAddress`, `manufacturer`, `model`, `serialNumber`, `biosUuid`, `cpuName`, `cpuCores`, `ramTotalGb`, `diskTotalGb`, `diskFreeGb`, `osName`, `osVersion`, `esuStatus`, `iec62443Score`, `patchComplianceState`, `hardwareManualOverride`, `customAttributes`). |
| `PUT / PATCH` | `/api/cmdb/inventory/{machineId}/hardware` | `Operator`+ / `X-Api-Key` | Updates any subset of hardware/asset fields (`manufacturer`, `model`, `serialNumber`, `biosUuid`, `cpuName`, `cpuCores`, `ramTotalGb`, `diskTotalGb`, `diskFreeGb`, `macAddress`, `osName`, `osVersion`, `assetClass`, `operationalRole`, `businessCriticality`, `purdueLevel`, `department`, `locationCode`, `supportGroup`, `hostname`, `customLabel`). Sets `hardwareManualOverride = true` (`🔒`). Pass `"resetToAuto": true` to unlock and revert to automatic WMI/OUI discovery. |
| `GET` | `/api/cmdb/mac-oui/status` | `Viewer`+ | Returns metadata for the 100% offline IEEE MAC OUI database (`CES.Api/Data/mac-oui-vendors.json`, 38,600+ prefixes). |
| `GET` | `/api/cmdb/mac-oui/lookup?mac={mac}` | `Viewer`+ | Resolves a MAC address to `{ "mac", "ouiPrefix", "vendor", "isLocallyAdministered" }` completely offline. |
| `POST` | `/api/cmdb/mac-oui/evaluate` | `SiteAdmin`+ | Bulk-evaluates and backfills `Manufacturer` across all endpoints with a MAC address (skipping endpoints where `hardwareManualOverride == true`). |
| `GET` | `/api/cmdb/ci-suggestions?siteId={siteId}&q={query}` | `Viewer`+ | Fast site-isolated CI autocomplete catalog (`customLabel`, `hostname`, `machineId`, `ipAddress`, `macAddress`, `osVersion`, `ciClass`, `isManaged`, `isOnline`). |
| `GET / POST / PUT / DELETE` | `/api/cmdb/relationships` | `SiteAdmin`+ | Manages CMDB Parent-Child communication flows (`parentMachineId`, `childMachineId`, `protocol`, `port`, `relationshipType`, `isAuthorized`, `isExternalNetworkOverride`, `externalIpOrCidr`, `businessApplicationCiId`). Automatically compiles switch ACLs, endpoint firewall exceptions, and ServiceNow firewall policy CIs. |
| `GET` | `/api/cmdb/firewall-policies` | `Viewer`+ | Lists `CmdbSynchronizedFirewallPolicy` records (`u_cmdb_ci_firewall_policy` linked via `Governed by::Governs` to `cmdb_ci_appl`). |
| `POST` | `/api/cmdb/firewall-policies/sync-servicenow` | `SiteAdmin`+ | Bi-directionally synchronizes `u_cmdb_ci_firewall_policy` CIs and `cmdb_rel_ci` relationships with ServiceNow CMDB. |

---

### 3.3 Fleet Management, Endpoint Telemetry & Ad-Hoc Active Session Screenshots (`FleetController`, `IngestController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `GET` | `/api/fleet/endpoints` | `Viewer`+ | Lists all endpoints with real-time compliance, reboot state, relay affinity, and maintenance window status. |
| `GET` | `/api/fleet/endpoints/{machineId}/inventory` | `Viewer`+ | Returns discovered software packages, services, hotfixes, and matched compatibility matrix records. |
| `GET` | `/api/fleet/endpoints/{machineId}/configuration` | `Viewer`+ | Returns deep OS configuration, local users, shares, firewall profiles, and security posture. |
| `POST` | `/api/fleet/endpoints/{machineId}/rescan` | `Operator`+ | Signals the endpoint (`X-ASAP-Wakeup: true`) to perform an immediate full inventory and WMI hardware scan. |
| `POST` | `/api/fleet/endpoints/{machineId}/screenshot` | `Operator`+ | Requests an on-demand 1-slot active user session desktop screenshot (`X-Require-Screenshot: true`). Retaking overwrites the single slot for that endpoint. |
| `GET` | `/api/fleet/endpoints/{machineId}/screenshot` | `Viewer`+ | Returns screenshot metadata (`status`: `Captured` \| `Pending` \| `NoActiveInteractiveSession` \| `ScreenLocked`, `capturedAtUtc`, `sessionUsername`, `width`, `height`). |
| `GET` | `/api/fleet/endpoints/{machineId}/screenshot/image` | Public / Token | Streams the captured PNG/WebP desktop screenshot image for the endpoint. |
| `POST` | `/api/fleet/endpoints/{machineId}/switch-relay` | `SiteAdmin`+ | Reassigns an endpoint to a specific `SRS` relay or triggers automatic latency-based rebalancing (`/auto-rebalance`). |

---

### 3.4 Patch Rollout, Pre-Staging, Maintenance Windows & Release Gates (`PatchingController`, `MaintenancePortalController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `GET` | `/api/patching/groups` | `Viewer`+ | Lists all Maintenance Zones (`EndpointGroup`) with Cron schedules, `requireWindowRelease`, `releaseMechanism` (`CesConsole`, `TrayGui`, `SmartKey`), `preUpdateSnapshotEnabled`, and `assignedHypervisorClusterId`. |
| `PUT` | `/api/patching/groups/{groupId}` | `SiteAdmin`+ | Updates or renames a Maintenance Zone (`{ "name": "Line 2 Packaging Zone", "description": "...", "cronMaintenanceWindow": "...", "durationMinutes": 120 }`). |
| `POST` | `/api/patching/groups/{groupId}/windows` | `SiteAdmin`+ | Adds a recurring or one-off Maintenance Window (`{ "cronExpression": "0 2 * * 0", "durationMinutes": 120, "isActive": true }`). |
| `DELETE` | `/api/patching/windows/{windowId}` | `SiteAdmin`+ | Removes a Maintenance Window schedule. When all schedules on a zone are removed, immediately clears `CronMaintenanceWindow` on member endpoints, resets `InMaintenanceWindow = false`, and signals `WakeupTracker` (`updateWakeupRequested: true`) for immediate agent sync. |
| `GET` | `/api/patching/endpoints/{machineId}/window-state` | `Viewer`+ / Agent | Returns live window state: `{ "inMaintenanceWindow", "requireWindowRelease", "windowReleaseState", "activeWindowRunId", "nextWindowStartUtc", "nextWindowEndUtc", "cronExpression" }`. |
| `POST` | `/api/patching/groups/{groupId}/release-window` | `Operator`+ | Releases the active maintenance window (`{ "releasedBy": "...", "releaseChannel": "CesConsole" | "TrayGui" | "SmartKey", "notes": "..." }`). Returns `409 Conflict` with `nextWindowStartUtc` if called outside the active window. |
| `POST` | `/api/patching/dispatch` | `Operator`+ + `X-Change-Ticket` | Dispatches a patch job (`{ "machineId", "kbNumber", "stageOnly": false, "autoReboot": false }`). When `stageOnly: true`, dispatches `STAGE_PATCH` immediately (allowed 24/7 outside windows). |
| `POST` | `/api/patching/campaign` | `SiteAdmin`+ + `X-Change-Ticket` | Launches a multi-endpoint or zone-wide patch rollout campaign with sequential reboot ordering. |
| `GET` | `/api/patching/groups/{groupId}/window-history` | `Viewer`+ | Lists historical Maintenance Window runs (`MaintenanceWindowRun`), including pre/post desktop screenshots, system delta diffs, and VM snapshot IDs. |
| `POST` | `/api/patching/window-history/{runId}/validate` | `Operator`+ | Submits post-maintenance validation sign-off (`{ "status": "Validated" | "ValidationFailed", "validatedBy": "...", "notes": "..." }`). **`Validated`** arms the 24h VM snapshot auto-delete timer; **`ValidationFailed`** freezes snapshot deletion and auto-creates a high-priority on-premises `Asset INC`. |
| `GET / POST / DELETE` | `/api/patching/excluded-kbs` | `Admin` | Manages Global Admin platform-wide KB exclusions (`{ "kbNumber": "KB5034441", "reason": "WinRE partition size conflict on legacy HMIs" }`). Immediately omits excluded KBs from compliance calculations and purges pending jobs. |

---

### 3.5 Dynamic NAC & Multi-Vendor Switch Enforcement (`SwitchEnforcementController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `GET / PUT` | `/api/nac/config` | `Admin` | Configures the Dynamic NAC Bolt-On (`isEnabled`, `scopeMode`: `Global` \| `SelectedSites` \| `SelectedZones`, `autoEnrollNewMaintenanceWindowsInSite`, `enableAgentHostFirewallNac`, `enableSwitchHardwareNac`, `restrictHostOutboundTraffic`). |
| `GET / POST` | `/api/nac/sites/{siteId}/allow-all-bypass` | `SiteAdmin`+ | Toggles the **1-Click "Allow-All" Emergency Diagnostic Bypass** (`{ "enable": true, "durationMinutes": 60, "reason": "Emergency PLC troubleshooting" }`). Injects hardware sequence `10 permit ip any any` and suspends agent host firewall blocks with automatic countdown revert. |
| `GET / POST / PUT / DELETE` | `/api/switches` | `SiteAdmin`+ | Onboards and manages industrial switches: **Cisco Catalyst IE3x00/9300 (`CiscoIosXeRestconf`)**, **Rockwell Stratix 5800 (`RockwellStratixRestconf`) & 5700/5400 (`RockwellStratixSsh`)**, **Dell PowerSwitch (`DellOs10Restconf`, `DellDnos6Ssh`)**, and **Belden Hirschmann (`HirschmannHiosSnmpSsh`)**. |
| `POST` | `/api/switches/{id}/reconcile` | `SiteAdmin`+ | Compiles authorized CMDB relationships into deterministic TCAM sequences (`10000–49999`, forward `2k` + return `2k+1`) with Anti-Lockout protection (`192.168.5.152`, SRS IPs, PTP `UDP 319/320`, CIP `UDP 2222`) and commits in `<400ms`. |
| `GET` | `/api/switches/telemetry` | `Viewer`+ | Returns real-time switch commit latency metrics (`lastCommitLatencyMs` vs `400ms` SLA, success rate, verbatim RESTCONF/CLI/SNMPv3 audit payloads). |
| `POST` | `/api/switches/{id}/backup` | `SiteAdmin`+ | Captures a running-config / startup-config backup (`SwitchConfigBackupRecord`) with optional `POST /api/switches/{id}/commit-nvram` (`write memory`). |
| `GET` | `/api/nac/endpoint-exceptions` | `Viewer`+ | Lists per-endpoint cross-network firewall exceptions (`EndpointFirewallExceptionRecord`) generated from external-IP CMDB relationships. |

---

### 3.6 Multi-Hypervisor Virtualization & Pre-Update VM Snapshots (`VirtualizationController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `GET / PUT` | `/api/virtualization/config` | `SiteAdmin`+ | Configures the Virtualization Bolt-On (`isEnabled`, `defaultPreUpdateSnapshotEnabled`, `defaultIncludeMemoryState: false`, `defaultQuiesceGuestVss: true`, `postValidationDeleteDelayHours: 24`, `freezeDeletionOnValidationFailureOrPending: true`). |
| `GET / POST / PUT / DELETE` | `/api/virtualization/credential-sets` | `SiteAdmin`+ | Manages AES-256-GCM **Shared Credential Sets** (`name`, `username`, `secret`, `domain`, `grantedUserIds`, `grantedConsoleGroupIds`) and syncs to SRS DPAPI/`SecretStore` via `POST /api/virtualization/credential-sets/{id}/sync-srs`. |
| `GET / POST / PUT / DELETE` | `/api/virtualization/clusters` | `SiteAdmin`+ | Registers Global (CES) or Local (SRS L3) hypervisor clusters across **`VMwareVsphere`**, **`MicrosoftHyperV`**, **`ProxmoxVe`**, **`ScaleComputingHc3`**, **`HpeVmEssentials`**, and **`NutanixAhv`**. |
| `POST` | `/api/virtualization/clusters/{id}/test-connection` | `SiteAdmin`+ | Verifies API/WMI/WinRM connectivity and credential permissions against the hypervisor cluster. |
| `GET` | `/api/virtualization/snapshots` | `Viewer`+ | Lists VM snapshots (`VmSnapshotRecord`) with `status` (`Active`, `ScheduledForDeletion`, `FrozenOnFailure`, `Reverted`, `Deleted`), `scheduledDeleteAtUtc`, and `validationState`. |
| `POST` | `/api/virtualization/snapshots/take` | `Operator`+ | Resolves the guest VM (`SMBIOS UUID` -> `MAC` -> `IP`) and takes a **Disk-Only + Guest VSS Quiesce (`includeMemoryState: false`)** snapshot (`{ "machineId": "...", "clusterId": "...", "windowRunId": "...", "reason": "Pre-Patch Safety Snapshot" }`). |
| `POST` | `/api/virtualization/snapshots/{id}/revert` | `SiteAdmin`+ | Executes a **1-Click Hypervisor Revert** to the pre-update snapshot and logs a high-priority audit event. |
| `DELETE` | `/api/virtualization/snapshots/{id}` | `SiteAdmin`+ | Immediately deletes the snapshot on the hypervisor (also runs automatically 24h after window validation sign-off). |

---

### 3.7 OT Privileged Access Management (OT PAM) & External Device Vault (`OtPamController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `GET` | `/api/otpam/overview` | `Viewer`+ | Returns OT PAM configuration, managed endpoint local admin accounts, external device vault entries, active checkouts, and rotation compliance. |
| `PUT` | `/api/otpam/config` & `/scope-policy` | `SiteAdmin`+ | Configures rotation intervals (`30`/`60`/`90` days), default checkout gate (`Instant`, `RequireTicket`, `RequireApproval`), and `autoCreateReqForExternalRotation` (default `false`). |
| `POST / PUT / DELETE` | `/api/otpam/entries` | `SiteAdmin`+ | Creates or updates a **`ManagedEndpointAdmin`** entry (guarded by HMI Winlogon Auto-Logon & Service Account safety checks) or an **`ExternalAccount`** entry (`label`, `comments`, `username`, `newPassword`, `linkedMachineId`). **Note:** Providing `newPassword` on an `ExternalAccount` automatically resolves any open `PendingRotationReqTicketId` (`Status = "Resolved"`). |
| `POST` | `/api/otpam/entries/{id}/raise-rotation-req` | `SiteAdmin`+ | Raises (or returns an existing deduplicated) on-premises `SiteQueue` Service Request (`ticketType: "REQ"`, `neverLeavesPremises: true`, `rotationStatus: "PendingManualRotationReq"`) for manual external device password rotation while keeping the current password active for checkouts. |
| `POST` | `/api/otpam/entries/{id}/checkout` | Vault-Granted User | Requests a credential lease (`{ "durationMinutes": 60, "ticketNumber": "INC-10042", "reason": "PLC ladder logic maintenance" }`). |
| `POST` | `/api/otpam/checkouts/{checkoutId}/approve` | `SiteAdmin`+ | Approves a pending `RequireApproval` checkout request. |
| `POST` | `/api/otpam/checkouts/{checkoutId}/reveal` | Checked-Out User | Decrypts and returns the plaintext password for an active, approved checkout lease. |
| `POST` | `/api/otpam/checkouts/{checkoutId}/checkin` | Checked-Out User | Checks in the credential lease and immediately triggers automatic post-checkout password rotation (`rotateOnCheckIn: true`). |
| `POST` | `/api/otpam/entries/{id}/rotate` | `SiteAdmin`+ | Forces immediate password rotation and updates the encrypted `PasswordHistoryJson` ring buffer. |

---

### 3.8 ISA/IEC 62443-3-3 Hybrid Compliance Engine, Multi-Tier Patch Windows & ESU Vault (`ComplianceController`, `EsuController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `GET / PUT` | `/api/compliance/patch-window-policy` | `Viewer`+ (GET) / `Admin` (PUT) | Configures the **Multi-Tier Windows Patch Compliance Window Policy** (`scopeMode`: `All` [`MaintenanceZone -> Site -> Global`], `Site` [`Site -> Global`], or `Global`; `globalWindowDays`: `7 | 14 | 30 | 60 | 90 | 180`, plus per-site and per-zone overrides). Classifies pending updates into **`ToBeScheduled` (Compliant)**, **`Scheduled` (Compliant)**, and **`Missing` (Overdue / Non-Compliant)**. |
| `GET` | `/api/compliance/iec62443/overview` | `Viewer`+ | Computes `FR 1`–`FR 7` scores (70% automated telemetry + 30% signed-off compensating controls; Windows Updates weighted at 35% of `FR 3` using the Multi-Tier Patch Compliance Window Policy), `SL-A vs. SL-T`, Enterprise/Site/Zone averages, **Single Lowest & Single Highest Outlier Hosts**, and 30-day velocity $\Delta\%$. |
| `GET / POST` | `/api/compliance/iec62443/quiz` & `/quiz/submit` | `SiteAdmin`+ | Retrieves and submits the 14-question Missing Telemetry Interview Quiz (`FR1_Q1`–`FR7_Q2`) scoped strictly to `Site` or `MaintenanceZone`. |
| `POST` | `/api/compliance/iec62443/compensating-factors/{id}/sign-off` | `Admin` | Electronically signs off a compensating control (or batch sign-off via `/batch-sign-off`). |
| `GET` | `/api/compliance/iec62443/export-pdf?siteId={siteId}` | `Viewer`+ | Streams the customizable multi-page Vector PDF 1.4 compliance report with the 7-spoke heptagonal Polar Radar chart. |
| `GET / POST / PUT / DELETE` | `/api/compliance/custom-attributes` | `SiteAdmin`+ | Manages rule-driven Global (`1..6`) and Site (`1..6`) Custom Compliance Attributes (`Registry`, `Software`, `Service`, `File` -> `Compliant` / `GreyArea` / `NonCompliant`). |
| `GET` | `/api/esu/summary` | `Viewer`+ | Returns Windows 10 22H2 / Windows Server 2012 ESU eligibility, licensed Year 1/2/3 status, `offlineInstallationId` (`IID`), and masked AES-256-GCM key pools (`*****-XXXXX`). |
| `POST / PUT / DELETE` | `/api/esu/keys` | `SiteAdmin`+ | Registers or updates Global or Site-scoped 25-character ESU MAK keys in the AES-256-GCM vault. |
| `POST` | `/api/esu/endpoints/{machineId}/activate` | `SiteAdmin`+ | Dispatches zero-reboot `system-esu-activate` jobs in `OnlineOrKms`, `InstallKeyOnly` (air-gap IID harvest), or `ApplyConfirmationId` (`confirmationId` `/atp`) mode. |

---

### 3.9 Sovereign Service Desk (`INC` / `REQ` / `PLATFORM_INC` / `DEV_REQ`), Remote Jobs & Lifecycle Upgrades (`TicketsController`, `JobsController`, `UpgradeController`)

| Method | Route | Auth | Purpose & Key Payload Fields |
| :--- | :--- | :--- | :--- |
| `GET` | `/api/tickets` & `/api/tickets/site/{siteId}` | `User`+ / `Viewer`+ | Lists tickets filtered by `siteId`, `ticketType` (`INC`, `REQ`, `DEV_REQ`), `targetScope` (`Asset`, `Site`, `Platform`), and `status`. |
| `POST` | `/api/tickets` | `User`+ / Agent | Creates a ticket. Agent submissions are strictly locked to `ticketType: "INC"`, `targetScope: "Asset"`, `neverLeavesPremises: true`. Portal submissions (`/support/:siteId`) require `User`+ auth and capture hybrid operator identity (`reporterIdentification` badge/name + system context). |
| `POST` | `/api/tickets/{id}/promote-to-platform-inc` | `SiteAdmin`+ | Escalates a local incident to a sanitized `PLATFORM_INC` (`CrowdCompatibilityIncQueue`), stripping all hostnames, IPs, and usernames via `SanitizeForCloud()`. |
| `POST` | `/api/tickets/{id}/promote` | `SiteAdmin`+ | Promotes a ticket to a sanitized `DEV_REQ` (`CrowdCompatibilityDevQueue`) and syncs to `customer_wishlist/`. |
| `POST` | `/api/tickets/{id}/forensics/execute` | `Operator`+ | Dispatches an automated diagnostic forensics script for the ticket's affected endpoint and attaches structured output. |
| `POST` | `/api/jobs/run` & `/api/jobs/bulk` | `SiteAdmin`+ / `X-Api-Key` + `X-Change-Ticket` | Dispatches or schedules an HMAC-SHA256 signed PowerShell job or built-in interactive action (`scriptId` or `scriptBody`, `arguments`, `timeoutSecs`, `captureImpactSnapshot`, `scheduledForUtc`, `cronExpression`, `bypassMaintenanceWindow`). Built-in interactive templates: `system-popup-msgbox` (`Title|Message|TimeoutSeconds` via Win32 `WTSSendMessageW`) and `system-start-interactive-app` (`ExecutablePath|Arguments|WorkingDirectory` via WTS `CreateProcessAsUserW` into `winsta0\default`). |
| `GET / POST / PUT / DELETE` | `/api/jobs/schedules` & `/api/jobs/schedules/{id}` | `SiteAdmin`+ / `X-Api-Key` | Lists, creates, updates, toggles (`isEnabled`), or deletes `ScheduledJobDefinition` records targeting an `Endpoint` or `MaintenanceZone` (`OneTime` via `scheduledForUtc` or `RecurringCron` via `cronExpression`, with `bypassMaintenanceWindow` support). |
| `POST` | `/api/jobs/schedules/{id}/trigger` | `SiteAdmin`+ / `X-Api-Key` | Immediately materializes and dispatches pending `RemoteJob` instances for the specified schedule and signals `WakeupTracker.RequestWakeup(machineId)` for instant agent execution. |
| `GET` | `/api/jobs/{id}/impact-snapshot` | `Viewer`+ | Returns Pre/Post desktop screenshot URLs (with automatic fallback to the endpoint's latest Baseline Desktop Screenshot `EndpointDesktopScreenshots`) and PID-tree system delta forensics (added/stopped processes, services, external sockets, modified files). |
| `GET / POST` | `/api/upgrade/status`, `/upload`, `/preflight`, `/execute`, `/rollback` | `Admin` | Manages cryptographic `.ieaupgrade` bundles, component hash change detection (`CES`, `SRS`, `IEA.Agent`), and 1-click rollback. |

---

### 3.10 Cyber-Physical ESP32 SmartKey, SCADA HMI Web Views & PLC Modbus TCP Interface

| Interface | Endpoint / Register | Auth / Protocol | Purpose & Payload Details |
| :--- | :--- | :--- | :--- |
| **ESP32 Panel SmartKey** | `POST /api/maintenance-portal/smartkeys/{keyUid}/signal` | HMAC-SHA256 | Payload: `{ "zoneId": "...", "state": "LOCKED" | "RELEASED" | "VALIDATE" | "ROLLBACK", "timestampUtc": 1761850000, "signature": "<hmac-hex>" }`. Evaluates Series (`AND`), Parallel (`OR`), or Series-Parallel physical rotary key-switch interlocks. |
| **SCADA HMI Control View** | `GET /scada/maintenance-control` (on SRS `:5051`/`:5443`) | Local L2/L3 | Framing-friendly (`<iframe>` / WebView) HMI widget for Siemens WinCC, Inductive Automation Ignition, Rockwell FactoryTalk, and AVEVA Wonderware. |
| **SCADA Deterministic Tag Feed** | `GET /api/maintenance-portal/scada/upcoming-windows.txt` | Public / Token | Deterministic pipe-delimited plain-text feed (`ZoneId|ZoneName|NextStartUtc|DurationMin|WindowState|ReleaseState`) for SCADA tag parsers. |
| **PLC Modbus TCP Coils** | `Coil 0001 + (Z * 10)`: `CMD_RELEASE_ZONE`<br>`Coil 0002 + (Z * 10)`: `CMD_VALIDATE_OK`<br>`Coil 0003 + (Z * 10)`: `CMD_ROLLBACK` | Modbus TCP (`:502` / `:1502`) | Write `1` from a PLC / SoftPLC ladder rung to release a maintenance window, validate deployment, or trigger emergency rollback for Zone index $Z$. |
| **PLC Modbus TCP Inputs** | `Discrete 1001 + (Z * 10)`: `STS_PATCHING_ACTIVE`<br>`Discrete 1002 + (Z * 10)`: `STS_SRS_HEALTHY`<br>`Input Reg 3001 + (Z * 10)`: `REG_ZONE_PROGRESS` | Modbus TCP (`:502` / `:1502`) | Read real-time zone patching state (`0`/`1`), SRS northbound link health (`0`/`1`), and batch completion percentage (`0–100`). |

---

## 🧠 4. Eight End-to-End Enterprise Use Cases & AI-Agent Pseudocode Blueprints

Each blueprint below contains:
1. **An AI Agent Prompt** you can paste directly into your coding assistant.
2. **Complete, Production-Grade Pseudocode** with exact routes, headers, state transitions, and error handling.

---

### Use Case 1: ServiceNow ITSM / CMDB Bi-Directional Sync, Offline MAC OUI Resolution & Change-Gated Patch Dispatch

#### 📋 Prompt to Feed Your AI Dev Agent
> *"Write a ServiceNow Integration / Python orchestration module against `CES.Api` (`https://192.168.5.152:5444`) using `X-Api-Key`. It must: (1) trigger an offline IEEE MAC OUI vendor evaluation on CES, (2) pull the flattened 50+ attribute CMDB inventory from `GET /api/cmdb/inventory`, (3) push curated asset metadata back to `PUT /api/cmdb/inventory/{machineId}/hardware` so CES locks `hardwareManualOverride = true`, (4) synchronize authorized cross-network firewall policy CIs via `POST /api/cmdb/firewall-policies/sync-servicenow`, and (5) dispatch an approved Windows KB patch via `POST /api/patching/dispatch` with `X-Change-Ticket: CHG-104920`, automatically falling back to `stageOnly: true` (`STAGE_PATCH`) if the target zone is currently outside its maintenance window."*

#### 💻 Complete AI-Ready Pseudocode Blueprint
```python
# ============================================================================
# MODULE 1: ServiceNow CMDB Bi-Directional Sync & Change-Gated Patching
# Target API: IEA Central Enterprise Server (CES.Api v1.0.32)
# ============================================================================

CONFIG = {
    "CES_BASE_URL": "https://192.168.5.152:5444",
    "API_KEY": env("CES_NORTHBOUND_API_KEY"),
    "CA_CERT_PATH": "./certs/ces_root_ca.cer"
}

HEADERS_BASE = {
    "X-Api-Key": CONFIG["API_KEY"],
    "Content-Type": "application/json",
    "Accept": "application/json"
}

function sync_cmdb_and_dispatch_patch(site_id, target_machine_id, kb_number, snow_change_ticket):
    # STEP 1: Trigger 100% Offline IEEE MAC OUI Vendor Resolution on CES
    # Ensures newly discovered OT assets have Manufacturer populated from mac-oui-vendors.json
    # without overwriting any asset that has hardwareManualOverride == true.
    HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/cmdb/mac-oui/evaluate",
        headers = HEADERS_BASE,
        verify = CONFIG.CA_CERT_PATH
    )

    # STEP 2: Pull Flattened 50+ Attribute CMDB Inventory for the Site
    inventory_resp = HTTP.GET(
        url = f"{CONFIG.CES_BASE_URL}/api/cmdb/inventory?siteId={site_id}&includeUnmanaged=true",
        headers = HEADERS_BASE,
        verify = CONFIG.CA_CERT_PATH
    )
    assert inventory_resp.status == 200
    cmdb_assets = inventory_resp.json()

    for asset in cmdb_assets:
        upsert_servicenow_cmdb_ci(
            machine_id          = asset.machineId,
            hostname            = asset.hostname,
            custom_label        = asset.customLabel,
            ip_address          = asset.ipAddress,
            mac_address         = asset.macAddress,
            manufacturer        = asset.manufacturer,
            model               = asset.model,
            serial_number       = asset.serialNumber,
            bios_uuid           = asset.biosUuid,
            os_name             = asset.osName,
            esu_status          = asset.esuStatus,
            iec62443_sl_score   = asset.iec62443Score,
            patch_window_status = asset.patchComplianceState, # "ToBeScheduled" | "Scheduled" | "Missing"
            is_manual_override  = asset.hardwareManualOverride
        )

    # STEP 3: Curate & Lock Hardware Metadata from Master Asset Registry (🔒 Manual Override)
    # Setting fields via PUT /api/cmdb/inventory/{machineId}/hardware sets hardwareManualOverride = true
    # so subsequent WMI or network scans never overwrite curated OT engineering metadata.
    curated_payload = {
        "customLabel": "PLC-PACKAGING-HMI-01",
        "manufacturer": "Rockwell Automation / Allen-Bradley",
        "model": "VersaView 6300B Industrial Box PC",
        "serialNumber": "RA-6300B-994812",
        "assetClass": "HMI",
        "operationalRole": "Primary Packaging Line Operator Station",
        "businessCriticality": " Tier-1 Mission Critical",
        "purdueLevel": "Level 2",
        "department": "Body & Stamping Assembly",
        "locationCode": "BLDG-4-BAY-12",
        "supportGroup": "OT-Controls-Engineering",
        "resetToAuto": false  # Keep true ONLY if unlocking back to automatic WMI telemetry
    }
    HTTP.PUT(
        url = f"{CONFIG.CES_BASE_URL}/api/cmdb/inventory/{target_machine_id}/hardware",
        headers = HEADERS_BASE,
        json = curated_payload
    )

    # STEP 4: Bi-Directionally Synchronize Authorized Cross-Network Firewall Policies
    # Syncs u_cmdb_ci_firewall_policy records linked via 'Governed by::Governs' to cmdb_ci_appl
    fw_sync_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/cmdb/firewall-policies/sync-servicenow",
        headers = HEADERS_BASE,
        json = { "siteId": site_id, "pushPendingToServiceNow": true }
    )
    log_info(f"Synchronized {fw_sync_resp.json().syncedCount} firewall policy CIs.")

    # STEP 5: Dispatch Change-Gated Patch (With Automatic Pre-Staging Fallback)
    # IndustrialSafetyGuardrail requires X-Change-Ticket matching ^CHG-[A-Za-z0-9_-]+$
    mutation_headers = {
        **HEADERS_BASE,
        "X-Change-Ticket": snow_change_ticket  # e.g., "CHG-104920"
    }

    dispatch_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/patching/dispatch",
        headers = mutation_headers,
        json = {
            "machineId": target_machine_id,
            "kbNumber": kb_number,
            "stageOnly": false,
            "autoReboot": false
        }
    )

    if dispatch_resp.status in [403, 409]:
        guardrail = dispatch_resp.json()
        if guardrail.requiresMaintenanceWindow and not guardrail.isInsideMaintenanceWindow:
            log_warn(f"Outside active window for group {guardrail.targetGroupId}. Pre-staging payload instead...")
            # Pre-stage binary to C:\IEA_Staging\Patches immediately with zero plant impact
            stage_resp = HTTP.POST(
                url = f"{CONFIG.CES_BASE_URL}/api/patching/dispatch",
                headers = mutation_headers,
                json = {
                    "machineId": target_machine_id,
                    "kbNumber": kb_number,
                    "stageOnly": true,
                    "autoReboot": false
                }
            )
            return { "status": "PRE_STAGED_FOR_NEXT_WINDOW", "job": stage_resp.json() }

    return { "status": "DISPATCHED_IN_ACTIVE_WINDOW", "job": dispatch_resp.json() }
```

---

### Use Case 2: Closed-Loop Zero-Downtime OT Patch Rollout with 6-Hypervisor Pre-Update VM Snapshot & Post-Window Validation

#### 📋 Prompt to Feed Your AI Dev Agent
> *"Build an automated Maintenance Window orchestrator for `CES.Api` that executes a closed-loop OT patch rollout for a Maintenance Zone (`groupId`). It must: (1) verify the maintenance window is open via `GET /api/patching/endpoints/{machineId}/window-state`, (2) take a Disk-Only + Guest VSS Quiesce hypervisor snapshot (`includeMemoryState: false`) via `POST /api/virtualization/snapshots/take`, (3) release the maintenance window gate via `POST /api/patching/groups/{groupId}/release-window`, (4) poll reboot SLA health and pre/post desktop screenshots, and (5) submit post-maintenance validation via `POST /api/patching/window-history/{runId}/validate`—automatically reverting the VM snapshot via `POST /api/virtualization/snapshots/{id}/revert` if post-maintenance validation fails."*

#### 💻 Complete AI-Ready Pseudocode Blueprint
```python
# ============================================================================
# MODULE 2: Closed-Loop Maintenance Window, 6-Hypervisor Snapshot & Rollback
# Supports: VMware vSphere, Hyper-V, Proxmox VE, Scale HC3, HPE VME, Nutanix AHV
# ============================================================================

function execute_guarded_zone_maintenance(group_id, primary_machine_id, cluster_id, change_ticket):
    headers = {
        "X-Api-Key": CONFIG["API_KEY"],
        "X-Change-Ticket": change_ticket,
        "Content-Type": "application/json"
    }

    # 1. Check Maintenance Window State & Release Gate Requirement
    win_state = HTTP.GET(
        f"{CONFIG.CES_BASE_URL}/api/patching/endpoints/{primary_machine_id}/window-state",
        headers = headers
    ).json()

    if not win_state.inMaintenanceWindow:
        raise WindowClosedException(
            f"Window closed. Next window opens at {win_state.nextWindowStartUtc} (Cron: {win_state.cronExpression})"
        )

    active_run_id = win_state.activeWindowRunId

    # 2. Take Pre-Update Hypervisor Snapshot (Disk-Only + Guest VSS Quiesce)
    # CRITICAL OT GUARDRAIL: includeMemoryState MUST be false for AD/SQL/Historian VMs
    # to prevent USN rollbacks and split-brain cluster quorum faults.
    snap_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/virtualization/snapshots/take",
        headers = headers,
        json = {
            "machineId": primary_machine_id,
            "clusterId": cluster_id,
            "windowRunId": active_run_id,
            "includeMemoryState": false,
            "quiesceGuestVss": true,
            "reason": f"Pre-Update Safety Snapshot ({change_ticket})"
        }
    )
    assert snap_resp.status == 200
    snapshot_id = snap_resp.json().id

    # 3. Release the Maintenance Window Gate (Allows Staged Patches to Install)
    if win_state.requireWindowRelease and win_state.windowReleaseState != "Released":
        release_resp = HTTP.POST(
            url = f"{CONFIG.CES_BASE_URL}/api/patching/groups/{group_id}/release-window",
            headers = headers,
            json = {
                "releasedBy": "Automated-Shift-Supervisor-Integration",
                "releaseChannel": "CesConsole",
                "notes": f"Pre-update snapshot {snapshot_id} verified. Releasing zone for {change_ticket}."
            }
        )
        assert release_resp.status == 200

    # 4. Trigger Sequential Zone Reboot & Monitor Recovery SLA (Default 15m)
    HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/patching/groups/{group_id}/reboot-start",
        headers = headers
    )

    while true:
        sla_check = HTTP.POST(
            url = f"{CONFIG.CES_BASE_URL}/api/ingest/reboot/check-sla",
            headers = headers
        ).json()

        history = HTTP.GET(
            url = f"{CONFIG.CES_BASE_URL}/api/patching/groups/{group_id}/window-history",
            headers = headers
        ).json()
        current_run = find(history, lambda r: r.id == active_run_id)

        if current_run.rebootTimedOutCount > 0:
            # 5A. EMERGENCY ROLLBACK PATH: Revert VM Snapshot & Freeze Deletion
            log_error("Endpoint exceeded Reboot Recovery SLA! Executing 1-Click Hypervisor Revert...")
            HTTP.POST(
                url = f"{CONFIG.CES_BASE_URL}/api/virtualization/snapshots/{snapshot_id}/revert",
                headers = headers,
                json = { "reason": "Automated rollback due to Reboot Recovery SLA timeout" }
            )
            # Record ValidationFailed -> freezes snapshot deletion & raises high-priority Site Asset INC
            HTTP.POST(
                url = f"{CONFIG.CES_BASE_URL}/api/patching/window-history/{active_run_id}/validate",
                headers = headers,
                json = {
                    "status": "ValidationFailed",
                    "validatedBy": "Automated-SLA-Watchdog",
                    "notes": "Host failed to return online within SLA; reverted to pre-patch VSS snapshot."
                }
            )
            return { "outcome": "ROLLED_BACK_TO_SNAPSHOT", "snapshotId": snapshot_id }

        if current_run.allJobsCompleted and current_run.postScreenshotCaptured:
            break
        sleep(30)

    # 5B. SUCCESS PATH: Validate Post-Maintenance State
    # Signing off as 'Validated' automatically arms the 24-hour snapshot auto-delete countdown
    # (ScheduledDeleteAtUtc = ValidatedAtUtc + 24h).
    val_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/patching/window-history/{active_run_id}/validate",
        headers = headers,
        json = {
            "status": "Validated",
            "validatedBy": "Automated-SCADA-Health-Verifier",
            "notes": "All HMI services running, post-patch desktop screenshot verified."
        }
    )
    return {
        "outcome": "VALIDATED_AND_24H_CLEANUP_ARMED",
        "snapshotId": snapshot_id,
        "validationResult": val_resp.json()
    }
```

---

### Use Case 3: SIEM / SOAR Sub-400ms Dynamic Switch Quarantine & Emergency 1-Click "Allow-All" Diagnostic Bypass

#### 📋 Prompt to Feed Your AI Dev Agent
> *"Create a SOAR playbook integration for `CES.Api` Dynamic NAC (`/api/nac/*` and `/api/switches/*`). Provide two functions: (1) `quarantine_unauthorized_flow()`, which audits unapproved network flows via `GET /api/cmdb/relationships/flow-compliance`, injects or revokes switch ACL rules on a managed Cisco IOS XE / Rockwell Stratix / Dell OS10 / Belden Hirschmann switch, triggers `POST /api/switches/{id}/reconcile`, and asserts that hardware TCAM commit latency is under `400ms` via `GET /api/switches/telemetry`; and (2) `engage_emergency_site_bypass()`, which activates the 1-Click 'Allow-All' Diagnostic Bypass at hardware sequence `10` (`POST /api/nac/sites/{siteId}/allow-all-bypass`) with a 60-minute auto-revert timer."*

#### 💻 Complete AI-Ready Pseudocode Blueprint
```python
# ============================================================================
# MODULE 3: SIEM/SOAR Sub-400ms Switch Quarantine & 1-Click Allow-All Bypass
# Supported Switches: Cisco IOS XE, Rockwell Stratix, Dell OS10/DNOS, Hirschmann HiOS
# ============================================================================

function enforce_zero_trust_switch_acl(site_id, switch_id, compromised_ip, change_ticket):
    headers = {
        "X-Api-Key": CONFIG["API_KEY"],
        "X-Change-Ticket": change_ticket,
        "Content-Type": "application/json"
    }

    # 1. Inspect Unauthorized Network Flows Detected Against CMDB Relationships
    flow_audit = HTTP.GET(
        url = f"{CONFIG.CES_BASE_URL}/api/cmdb/relationships/flow-compliance?siteId={site_id}",
        headers = headers
    ).json()

    # 2. Inject High-Priority Deny Rule on Target Industrial Switch
    # Note: CES Anti-Lockout engine automatically protects 192.168.5.152 (CES), SRS IPs,
    # IEEE 1588 PTP (UDP 319/320), and EtherNet/IP CIP Implicit I/O (UDP 2222).
    rule_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/switches/{switch_id}/rules",
        headers = headers,
        json = {
            "sequenceNumber": 10050,
            "action": "Deny",
            "protocol": "ip",
            "sourceIp": compromised_ip,
            "sourceWildcard": "0.0.0.0",
            "destinationIp": "any",
            "destinationPort": "any",
            "description": f"SOAR Quarantine for {compromised_ip} ({change_ticket})"
        }
    )
    assert rule_resp.status == 200

    # 3. Reconcile & Commit Hardware TCAM ACLs + Sync Agent Host Firewall Policy
    reconcile_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/switches/{switch_id}/reconcile",
        headers = headers
    ).json()

    # 4. Verify Sub-400ms Hardware Commit Latency SLA
    telemetry = HTTP.GET(
        url = f"{CONFIG.CES_BASE_URL}/api/switches/telemetry?siteId={site_id}",
        headers = headers
    ).json()

     commit_ms = reconcile_resp.commitLatencyMs
    if commit_ms > 400:
        log_warn(f"Switch {switch_id} commit took {commit_ms}ms (exceeds 400ms SLA target)")

    return {
        "quarantinedIp": compromised_ip,
        "switchId": switch_id,
        "commitLatencyMs": commit_ms,
        "within400msSla": commit_ms <= 400
    }

function engage_emergency_site_bypass(site_id, duration_minutes = 60, reason = "Plant Floor Troubleshooting"):
    # Injects sequence '10 permit ip any any' across all switches in the site and suspends
    # IEA.Agent Windows Firewall blocks for duration_minutes before automatically reverting.
    bypass_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/nac/sites/{site_id}/allow-all-bypass",
        headers = HEADERS_BASE,
        json = {
            "isBypassActive": true,
            "autoRevertMinutes": duration_minutes,
            "reason": reason
        }
    )
    assert bypass_resp.status == 200
    return bypass_resp.json()
```

---

### Use Case 4: OT Privileged Access Management (OT PAM) Just-In-Time Checkout & External Device Rotation `REQ` Loop

#### 📋 Prompt to Feed Your AI Dev Agent
> *"Write an integration script for `CES.Api` OT Privileged Access Management (`/api/otpam/*`). Implement two workflows: (1) Just-In-Time (JIT) checkout of a managed endpoint local admin credential (`POST /api/otpam/entries/{id}/checkout`), approval (`POST /api/otpam/checkouts/{checkoutId}/approve`), plaintext secret retrieval (`/reveal`), and check-in (`/checkin`) which triggers automatic post-lease password rotation while respecting Winlogon HMI Auto-Logon guards; and (2) raising an on-premises `SiteQueue` rotation `REQ` ticket for an external OT device (`POST /api/otpam/entries/{id}/raise-rotation-req`) and subsequently updating its password via `PUT /api/otpam/entries/{id}`, which automatically resolves the linked `REQ` ticket."*

#### 💻 Complete AI-Ready Pseudocode Blueprint
```python
# ============================================================================
# MODULE 4: OT PAM Just-In-Time Credential Lease & External Rotation REQ Loop
# ============================================================================

function jit_checkout_and_rotate_managed_admin(entry_id, operator_bearer_token, support_ticket_id):
    user_headers = {
        "Authorization": f"Bearer {operator_bearer_token}",
        "Content-Type": "application/json"
    }

    # 1. Operator Requests Credential Checkout (Enforces Instant / RequireTicket / RequireApproval gate)
    checkout_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/otpam/entries/{entry_id}/checkout",
        headers = user_headers,
        json = {
            "durationMinutes": 60,
            "ticketNumber": support_ticket_id,
            "reason": "Scheduled PLC communication driver reconfiguration"
        }
    ).json()

    checkout_id = checkout_resp.checkoutId

    # 2. If Entry Requires Supervisor Approval, Admin Approves the Lease
    if checkout_resp.status == "PendingApproval":
        HTTP.POST(
            url = f"{CONFIG.CES_BASE_URL}/api/otpam/checkouts/{checkout_id}/approve",
            headers = HEADERS_BASE,
            json = { "approvedBy": "OT-Security-Supervisor", "notes": "Verified active maintenance window" }
        )

    # 3. Reveal Ephemeral Plaintext Password for Active Lease
    secret_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/otpam/checkouts/{checkout_id}/reveal",
        headers = user_headers
    ).json()
    ephemeral_password = secret_resp.password

    # ... [Operator performs maintenance using ephemeral_password] ...

    # 4. Check In Credential Lease -> Triggers Automatic Post-Checkout Rotation on Endpoint
    # Note: IEA.Agent automatically checks HKLM\...\Winlogon\AutoAdminLogon and Windows Service
    # logon accounts so HMI Auto-Logon accounts are NEVER broken by rotation.
    checkin_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/otpam/checkouts/{checkout_id}/checkin",
        headers = user_headers,
        json = { "notes": "Maintenance completed; trigger immediate password rotation." }
    ).json()

    return checkin_resp

function rotate_external_ot_device_with_sovereign_req(external_entry_id, new_device_password):
    # 1. Raise (or retrieve existing deduplicated) on-premises SiteQueue Service Request (REQ)
    # Ticket has TicketType = "REQ", TargetScope = "Site", NeverLeavesPremises = true.
    # Current password remains active for checkouts while RotationStatus == "PendingManualRotationReq".
    req_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/otpam/entries/{external_entry_id}/raise-rotation-req",
        headers = HEADERS_BASE,
        json = { "requestedBy": "OT-Compliance-Scheduler" }
    ).json()

    req_ticket_id = req_resp.ticketId
    log_info(f"On-premises rotation REQ active: {req_resp.ticketNumber} (ID: {req_ticket_id})")

    # 2. After technician updates password on the physical PLC/RTU/VFD, commit NewPassword to OT PAM Vault
    # Updating newPassword on an ExternalAccount AUTOMATICALLY transitions the linked REQ ticket
    # to Status = "Resolved" and resets RotationStatus = "Healthy".
    update_resp = HTTP.PUT(
        url = f"{CONFIG.CES_BASE_URL}/api/otpam/entries/{external_entry_id}",
        headers = HEADERS_BASE,
        json = {
            "newPassword": new_device_password,
            "comments": f"Rotated on physical device and synchronized under {req_resp.ticketNumber}"
        }
    ).json()

    assert update_resp.rotationStatus == "Healthy"
    assert update_resp.pendingRotationReqTicketId == null
    return update_resp
```

---

### Use Case 5: Cyber-Physical ESP32 Panel SmartKey, SCADA HMI Feed & PLC Modbus TCP Interlock Integration

#### 📋 Prompt to Feed Your AI Dev Agent
> *"Write a cyber-physical plant-floor integration module that interfaces with `CES.Api` and `SRS.Service`. Include: (1) a SCADA script that parses the deterministic upcoming windows feed (`GET /api/maintenance-portal/scada/upcoming-windows.txt`), (2) an ESP32 / edge gateway client that signs rotary key-switch assertions (`LOCKED`, `RELEASED`, `VALIDATE`, `ROLLBACK`) using `HMAC-SHA256` and posts to `POST /api/maintenance-portal/smartkeys/{keyUid}/signal`, and (3) a PLC / SoftPLC Modbus TCP client (`port 502/1502`) that reads Zone $Z$'s patching status and progress (`Discrete Input 1001 + Z*10`, `Input Register 3001 + Z*10`) and pulses `Coil 0001 + Z*10` (`CMD_RELEASE_ZONE`) or `Coil 0003 + Z*10` (`CMD_ROLLBACK`)."*

#### 💻 Complete AI-Ready Pseudocode Blueprint
```python
# ============================================================================
# MODULE 5: ESP32 SmartKey HMAC Interlock, SCADA Feed & PLC Modbus TCP Bridge
# ============================================================================

import hmac, hashlib, time

function send_esp32_smartkey_assertion(key_uid, zone_id, switch_state, shared_hmac_secret):
    # switch_state: "LOCKED" | "RELEASED" | "VALIDATE" | "ROLLBACK"
    # Supports Series (AND), Parallel (OR), and Series-Parallel multi-key topologies
    timestamp_utc = int(time.time())
    canonical_payload = f"{key_uid}|{zone_id}|{switch_state}|{timestamp_utc}"
    signature_hex = hmac.new(
        key = shared_hmac_secret.encode("utf-8"),
        msg = canonical_payload.encode("utf-8"),
        digestmod = hashlib.sha256
    ).hexdigest().lower()

    resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/maintenance-portal/smartkeys/{key_uid}/signal",
        headers = { "Content-Type": "application/json" },
        json = {
            "keyUid": key_uid,
            "zoneId": zone_id,
            "state": switch_state,
            "timestampUtc": timestamp_utc,
            "signature": signature_hex
        }
    )
    assert resp.status == 200
    # Returns composite gate evaluation across all SmartKeys bound to the zone
    return resp.json()

function plc_modbus_tcp_zone_controller(srs_ip, modbus_port = 502, zone_index_z = 1, line_is_safe_for_patching = true):
    # Per-Zone Address Offset: offset = Z * 10
    offset = zone_index_z * 10
    COIL_RELEASE_ZONE = 1 + offset    # 0001 + offset
    COIL_VALIDATE_OK  = 2 + offset    # 0002 + offset
    COIL_ROLLBACK     = 3 + offset    # 0003 + offset
    DI_PATCH_ACTIVE   = 1001 + offset # 1001 + offset
    DI_SRS_HEALTHY    = 1002 + offset # 1002 + offset
    IR_ZONE_PROGRESS  = 3001 + offset # 3001 + offset (0..100%)

    modbus = ModbusTcpClient(host = srs_ip, port = modbus_port)
    modbus.connect()

    srs_healthy = modbus.read_discrete_inputs(address = DI_SRS_HEALTHY, count = 1).bits[0]
    if not srs_healthy:
        log_warn("SRS Northbound link degraded; holding local store-and-forward queue.")

    if line_is_safe_for_patching:
        # Pulse CMD_RELEASE_ZONE coil to authorize maintenance window execution
        modbus.write_coil(address = COIL_RELEASE_ZONE, value = true)
    else:
        # Emergency abort & rollback signal from PLC safety rung
        modbus.write_coil(address = COIL_ROLLBACK, value = true)
        return { "status": "PLC_EMERGENCY_ROLLBACK_SIGNALED" }

    # Poll progress register (0-100%) while patching is active
    while modbus.read_discrete_inputs(address = DI_PATCH_ACTIVE, count = 1).bits[0]:
        pct = modbus.read_input_registers(address = IR_ZONE_PROGRESS, count = 1).registers[0]
        update_hmi_progress_bar(zone_index_z, pct)
        sleep(5)

    # Pulse CMD_VALIDATE_OK once line PLC confirms normal post-patch interlock loop
    modbus.write_coil(address = COIL_VALIDATE_OK, value = true)
    modbus.close()
    return { "status": "PLC_VALIDATED_COMPLETE", "zoneIndex": zone_index_z }
```

---

### Use Case 6: Continuous ISA/IEC 62443-3-3 Compliance Auditing, Multi-Tier Patch Windows & Vector PDF Export

#### 📋 Prompt to Feed Your AI Dev Agent
> *"Write a compliance automation client for `CES.Api` (`/api/compliance/*`) that: (1) configures the hierarchical Multi-Tier Windows Patch Compliance Window Policy (`MaintenanceZone -> Site -> Global`) via `PUT /api/compliance/patch-window-policy`, (2) fetches the ISA/IEC 62443-3-3 hybrid report (`GET /api/compliance/iec62443/overview`) including `FR 1`–`FR 7` scores, `SL-A vs. SL-T`, Single Lowest/Highest Outlier Hosts, and 30-day velocity $\Delta\%$, (3) batch signs off pending compensating controls (`POST /api/compliance/iec62443/compensating-factors/batch-sign-off`), and (4) downloads the Vector PDF 1.4 compliance report (`GET /api/compliance/iec62443/export-pdf`)."*

#### 💻 Complete AI-Ready Pseudocode Blueprint
```python
# ============================================================================
# MODULE 6: ISA/IEC 62443-3-3 Hybrid Engine, Patch Windows & Vector PDF Export
# ============================================================================

function configure_patch_windows_and_export_iec62443_pdf(site_id, zone_id, output_pdf_path):
    # 1. Configure Multi-Tier Patch Compliance Window Policy (Global Admin)
    # Hierarchy: MaintenanceZone -> Site -> Global (Allowed windows: 7, 14, 30, 60, 90, 180 days)
    # Classifies pending KBs into:
    #   - ToBeScheduled (Compliant: within window, not yet scheduled)
    #   - Scheduled     (Compliant: assigned to an upcoming maintenance window)
    #   - Missing       (Overdue / Non-Compliant: age > effective window days)
    policy_resp = HTTP.PUT(
        url = f"{CONFIG.CES_BASE_URL}/api/compliance/patch-window-policy",
        headers = HEADERS_BASE,
        json = {
            "scopeMode": "All",          # "All" (Zone->Site->Global) | "Site" (Site->Global) | "Global"
            "globalWindowDays": 30,
            "siteOverrides": {
                site_id: 60              # 60-day grace window for continuous process plant site
            },
            "zoneOverrides": {
                zone_id: 14              # 14-day strict window for DMZ / L3.5 jump hosts
            }
        }
    )
    assert policy_resp.status == 200

    # 2. Sign Off Verified Compensating Controls (30% Weight in Hybrid 70/30 Engine)
    HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/compliance/iec62443/compensating-factors/batch-sign-off",
        headers = HEADERS_BASE,
        json = {
            "siteId": site_id,
            "signedOffBy": "Chief-OT-Security-Officer",
            "reviewNotes": "Verified physical cabinet locks and unidirectional gateway controls."
        }
    )

    # 3. Query Full ISA/IEC 62443-3-3 Hybrid Report
    report = HTTP.GET(
        url = f"{CONFIG.CES_BASE_URL}/api/compliance/iec62443/overview?siteId={site_id}",
        headers = HEADERS_BASE
    ).json()

    log_info(f"Site Achieved Security Level (SL-A): {report.achievedSl} vs Target (SL-T): {report.targetSl}")
    log_info(f"Overall Score: {report.overallScore}% (30d Delta: {report.thirtyDayDeltaPercent}%)")
    log_info(f"Lowest Outlier Host:  {report.lowestOutlierHost.hostname} ({report.lowestOutlierHost.score}%)")
    log_info(f"Highest Outlier Host: {report.highestOutlierHost.hostname} ({report.highestOutlierHost.score}%)")

    # 4. Download Multi-Page Vector PDF 1.4 Executive Report (with 7-Spoke Polar Radar Chart)
    pdf_stream = HTTP.GET(
        url = f"{CONFIG.CES_BASE_URL}/api/compliance/iec62443/export-pdf?siteId={site_id}&includeOutliers=true&includeQuizBreakdown=true",
        headers = HEADERS_BASE
    )
    write_binary_file(output_pdf_path, pdf_stream.bytes())
    return report
```

---

### Use Case 7: Air-Gapped Windows 10 / Server 2012 ESU MAK Key Vault & Zero-Reboot Offline Activation

#### 📋 Prompt to Feed Your AI Dev Agent
> *"Write an air-gapped Extended Security Updates (ESU) licensing automation script for `CES.Api` (`/api/esu/*`). It must: (1) register a site-scoped 25-character ESU MAK key into the AES-256-GCM vault (`POST /api/esu/keys`), (2) trigger `InstallKeyOnly` on an air-gapped Windows 10 22H2 / Server 2012 endpoint to harvest its `OfflineInstallationId` (`IID`), and (3) apply the Microsoft Confirmation ID (`CID`) via `POST /api/esu/endpoints/{machineId}/activate` (`ApplyConfirmationId` mode) with zero reboot."*

#### 💻 Complete AI-Ready Pseudocode Blueprint
```python
# ============================================================================
# MODULE 7: Air-Gapped Win10 / Server 2012 ESU MAK Key Vault & CID Activation
# ============================================================================

function activate_airgapped_esu_endpoint(site_id, machine_id, esu_mak_key, program_year = 2):
    # 1. Register Site-Scoped ESU MAK Key in AES-256-GCM Vault (Displayed as *****-XXXXX in UI)
    key_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/esu/keys",
        headers = HEADERS_BASE,
        json = {
            "label": f"Site {site_id} Win10 ESU Year {program_year} MAK",
            "keyValue": esu_mak_key,       # 25-charXXXXX-XXXXX-XXXXX-XXXXX-XXXXX
            "targetOs": "Windows 10",
            "esuYear": program_year,       # 1, 2, or 3
            "scope": "Site",               # "Global" | "Site"
            "siteId": site_id,
            "maxActivations": 500
        }
    ).json()

    # 2. Step A for Air-Gapped Host: Install ESU Key & Harvest Offline Installation ID (IID)
    # Executes slmgr.vbs //B /ipk <Key> and reads OfflineInstallationId via WMI SoftwareLicensingProduct
    HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/esu/endpoints/{machine_id}/activate",
        headers = HEADERS_BASE,
        json = {
            "keyId": key_resp.id,
            "esuYear": program_year,
            "activationMode": "InstallKeyOnly"  # "OnlineOrKms" | "InstallKeyOnly" | "ApplyConfirmationId"
        }
    )

    # Poll /api/esu/summary until the agent reports its OfflineInstallationId (IID)
    iid = null
    while iid is null:
        summary = HTTP.GET(f"{CONFIG.CES_BASE_URL}/api/esu/summary?siteId={site_id}", headers = HEADERS_BASE).json()
        ep_esu = find(summary.endpoints, lambda e: e.machineId == machine_id)
        if ep_esu and ep_esu.offlineInstallationId:
            iid = ep_esu.offlineInstallationId
            break
        sleep(10)

    # 3. Exchange IID for Confirmation ID (CID) via Enterprise Volume Licensing Gateway
    cid = request_microsoft_vlsc_confirmation_id(installation_id = iid)

    # 4. Step B for Air-Gapped Host: Apply Confirmation ID (slmgr.vbs //B /atp <CID> <ActivationGuid>)
    # Zero reboot required!
    activate_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/esu/endpoints/{machine_id}/activate",
        headers = HEADERS_BASE,
        json = {
            "keyId": key_resp.id,
            "esuYear": program_year,
            "activationMode": "ApplyConfirmationId",
            "confirmationId": cid
        }
    ).json()

    return { "machineId": machine_id, "iid": iid, "cidApplied": true, "job": activate_resp }
```

---

### Use Case 8: Sovereign Helpdesk Triage, Ad-Hoc Desktop Screenshot, Remote Forensics & Sanitized Cloud Escalation

#### 📋 Prompt to Feed Your AI Dev Agent
> *"Write an automated incident triage workflow for `CES.Api` (`/api/tickets/*` and `/api/fleet/*`). When a new `Asset INC` arrives in `SiteQueue` (`GET /api/tickets/site/{siteId}`), automatically: (1) trigger an on-demand 1-slot active user session desktop screenshot on the affected endpoint (`POST /api/fleet/endpoints/{machineId}/screenshot`), (2) execute the ticket forensics collector (`POST /api/tickets/{id}/forensics/execute`), and (3) if the root cause is an IEA platform defect, escalate it via `POST /api/tickets/{id}/promote-to-platform-inc` so CES sanitizes all PII/IPs/hostnames (`SanitizeForCloud()`) before forwarding to `CrowdCompatibilityIncQueue`."*

#### 💻 Complete AI-Ready Pseudocode Blueprint
```python
# ============================================================================
# MODULE 8: Sovereign Helpdesk Triage, Ad-Hoc Screenshot & Sanitized Escalation
# ============================================================================

function triage_site_incident_and_escalate_if_platform_bug(site_id, ticket_id):
    # 1. Fetch Sovereign Site Queue Tickets (Asset INCs & Site REQs never leave premises)
    tickets = HTTP.GET(
        url = f"{CONFIG.CES_BASE_URL}/api/tickets/site/{site_id}",
        headers = HEADERS_BASE
    ).json()
    ticket = find(tickets, lambda t: t.id == ticket_id)
    assert ticket.neverLeavesPremises == true

    machine_id = ticket.machineId

    # 2. Request 1-Slot Ad-Hoc Active User Session Desktop Screenshot
    # Signals X-Require-Screenshot: true + X-ASAP-Wakeup: true to InteractiveTrayLauncher
    if machine_id:
        HTTP.POST(
            url = f"{CONFIG.CES_BASE_URL}/api/fleet/endpoints/{machine_id}/screenshot",
            headers = HEADERS_BASE,
            json = { "requestedBy": "Automated-Incident-Triage" }
        )

    # 3. Execute Automated Endpoint Forensics Package for the Ticket
    forensics_resp = HTTP.POST(
        url = f"{CONFIG.CES_BASE_URL}/api/tickets/{ticket_id}/forensics/execute",
        headers = HEADERS_BASE
    ).json()

    # 4. Evaluate if Issue is a Platform Defect Requiring Sanitized Escalation to CrowdCompatibility
    if is_platform_defect(forensics_resp):
        # Admin-only promotion: SanitizeForCloud() strips all internal IPv4/IPv6 addresses,
        # hostnames, domain names, and OS usernames before pushing to CrowdCompatibilityIncQueue.
        promoted = HTTP.POST(
            url = f"{CONFIG.CES_BASE_URL}/api/tickets/{ticket_id}/promote-to-platform-inc",
            headers = HEADERS_BASE,
            json = {
                "escalatedBy": "Senior-OT-Platform-Admin",
                "sanitizedSummaryNotes": "Relay cache convergence timeout observed on large >2GB CAB payload."
            }
        ).json()
        return { "triageOutcome": "PROMOTED_TO_SANITIZED_PLATFORM_INC", "ticket": promoted }

    return {
        "triageOutcome": "RETAINED_ON_PREMISES_SITE_QUEUE",
        "screenshotImageUrl": f"{CONFIG.CES_BASE_URL}/api/fleet/endpoints/{machine_id}/screenshot/image",
        "forensics": forensics_resp
    }
```

---

## ☁️ 5. CrowdCompatibility Cloud <-> CES Cross-Project Sync Contract (`v1.0.54`)

For developers building custom cloud connectors or inspecting the northbound HTTPS boundary between `CES.Api` and **CrowdCompatibility Cloud** (`https://us-central1-studio-4863129343-87305.cloudfunctions.net/api`), the following endpoints govern catalog, profile, KB, and release synchronization using header `x-api-key: <crowdcompatibility-api-key>`:

| Method & Cloud Route | CES Consumer Service | Purpose |
| :--- | :--- | :--- |
| `GET /software` | `CrowdCompatibilityService.SyncGlobalCatalogAsync` | Pulls the global vendor-verified OT software catalog (`lastUpdated` delta timestamp + `vendor`, `product`, `version`, `platforms`). |
| `GET /v1/profiles` | `CrowdCompatibilityService.ImportCloudProfilesToLocalAsync` | Imports machine profiles created on CrowdCompatibility by the tenant owner or invited organization members into local `MachineProfiles`. |
| `POST /profile` | `CrowdCompatibilityService.SyncMachineProfileToCloudAsync` | Registers/updates a non-generic machine profile (`name`, `os_base`, `software[]`) and returns `profileId`. |
| `GET /profile/{profileId}/evaluation` | `CrowdCompatibilityService.SyncMachineProfileToCloudAsync` | Retrieves per-KB compatibility matrix evaluations (`Compatible`, `Incompatible`, `Unknown`) for the profile. |
| `GET /os-kb-status?os={os}&build={build}` | `CrowdCompatibilityService.SyncOsKbStatusAsync` | Fetches the latest Microsoft-published KB (`latestKb`, `latestKbTitle`, `latestKbDate`, `updates[]`) for each distinct OS build in the fleet. |
| `GET /v1/tenant/info` & `POST /v1/tenant/invitations` | `SettingsController.GetCrowdTenant` / `InviteCrowdUser` | Manages multi-user organization team invitations and shared profile entitlements linked to the CES tenant. |
| `GET /v1/updates/iea-enterprise` | `UpgradeService.CheckCloudUpdatesAsync` | Retrieves cryptographic `.ieaupgrade` and full suite `.zip` release metadata (`version`, `sha256`, `sizeBytes`, `components` source hashes, and custom tenant split-branch channels). |


---

### Use Case 8: Hierarchical DNS Governance, Timed Real-Time ETW Capture, Known External Destinations & OT Name-Resolution Hardening (`v1.0.48`)

- **`GET /api/fleet/dns/policy?siteId={siteId}&machineId={machineId}`** & **`PUT /api/fleet/dns/policy`**: Configure DNS collection (`PeriodicCache` [Method 1 default], `ContinuousEtw` [Method 2], `Disabled`, or `TimedCaptureDurationMinutes` for timed real-time captures) across `Global`, `Site`, or `Endpoint` scopes.
- **`GET /api/fleet/endpoints/{id}/dns`**: Retrieve DNS settings, protocol hardening posture (**LLMNR**, **NetBIOS**, **mDNS**, **WPAD**, **DoH**), `etc\hosts` static entries, deduplicated internal/external DNS query rollup with process attribution, and the consolidated **Known External Destinations** list.
- **`POST /api/fleet/endpoints/{id}/dns/remediate`**: Dispatch active remediation jobs (`ApplyHardeningBaseline`, `DisableLlmnr`, `DisableNetbios`, `DisableMdns`, `DisableWpad`, `FlushDnsCache`, `AddHostsEntry`, `RemoveHostsEntry`, `RestoreDefaultHosts`).

---

### Use Case 9: Core Industrial IPAM, Cisco/Stratix Physical + VLAN Connectivity, Cabling Drift Quarantine & ServiceNow IP Sync (`v1.0.54`)

- **`GET /api/ipam/sites/{siteId}/overview`** (`Viewer`+): Retrieve site-wide IPAM KPIs, `SiteVlanRecords`, `IpamSubnets`, `IpamConflictEvents`, `CablingDriftAlerts`, and `DiscoveredSwitchNodes`.
- **`GET|PUT /api/ipam/sites/{siteId}/crawl-config`** & **`POST /api/ipam/sites/{siteId}/crawl`**: Configure Cisco/Stratix crawl depth, `ShadowSwitchDiscoveryMode` (`PassiveLeaf` | `AutoCrawlWithSiteReadOnlyCred`), `SnmpVersion` (`v2c` | `v3`), `PreferRestconf`, and `AutoCreateSiteIncOnCriticalDrift`, or enqueue an immediate Level 3 `CISCO_TOPOLOGY_CRAWL` relay directive.
- **`POST /api/ipam/sites/{siteId}/ingest-snapshot`** (`MtlsNode` relay or `SiteAdmin`+): Ingest `SwitchTopologySnapshotDto` payloads (VLANs, SVI subnets, CDP neighbor links, Switch ARP caches, and per-VLAN CAM MAC tables) with trunk-excluded edge-port binding and Fragile OT Exclusion enforcement.
- **`POST|PUT|DELETE /api/ipam/sites/{siteId}/subnets/{subnetId?}`** & **`GET /api/ipam/sites/{siteId}/subnets/{subnetId}/grid?page=1&pageSize=256`**: Manage IPv4 `/16`–`/30` subnets and query paginated `256`-tile `/24` or `/16` (`65,536`-IP) allocation heatmaps.
- **`POST /api/ipam/sites/{siteId}/reservations`**, **`DELETE /api/ipam/sites/{siteId}/reservations/{entryId}`**, & **`POST /api/ipam/sites/{siteId}/conflicts/{conflictId}/resolve`**: Reserve static industrial IPs (with optional CMDB CI pre-creation) and resolve duplicate-IP / rogue-static-in-DHCP conflicts.
- **`GET /api/ipam/sites/{siteId}/export-csv`**, **`POST /api/ipam/sites/{siteId}/import-csv`** (`DryRun: true|false`), & **`POST /api/ipam/sites/{siteId}/servicenow-sync`**: Export/import bulk IPAM allocations with dry-run validation and synchronize `cmdb_ci_ip_network` / `cmdb_ci_ip_address` CIs with ServiceNow CMDB.
- **`GET /api/ipam/sites/{siteId}/topology?mode={physical|vlan}&vlanId={id}`**, **`POST /api/ipam/sites/{siteId}/shadow-switches/{nodeId}/onboard`**, **`POST /api/ipam/sites/{siteId}/baseline/pin`**, **`POST /api/ipam/sites/{siteId}/drifts/{driftId}/approve`**, & **`POST /api/ipam/sites/{siteId}/drifts/{driftId}/quarantine`**: Render live Physical L2 and Logical VLAN graphs, onboard CDP-discovered Shadow Switches, pin Known-Good Cabling Baselines, approve authorized moves, or push an immediate **1-Click `DynamicQuarantine` (`DENY` ACL at `Seq=500`)**.
