Google Sign-In Required

Use your company Google account to access the BetterFleet private content.

Back to private home

BetterFleet Support Private
Skip to content
BetterFleet Dev Wiki
Microgrid
Initializing search
    bf-dev
    • Home
    • Product Capabilities
    • Process
    • Current Work
    • System Design
    • Software Reference
    • Operations
    bf-dev
    • Home
      • Overview
      • Manage
      • Overview
      • Product Engineering Workflow
      • Product Engineering Delivery
      • Product Engineering Workflow in Linear
        • GitLab Feature Flags
        • In-App Docs Authoring
        • Release Notes
      • Templates
      • Publishing
      • Workflow Companions
      • Overview
      • Active Artifacts
      • Backlog Artifacts
      • Archived Artifacts
      • Overview
      • Microgrid
        • Solution Summary
        • 1. Summary
          • Problem
          • Goal
          • Design Outcomes
          • System Capabilities
          • Scope (In)
          • Scope (Out)
          • Architectural Guardrails
        • 2. Users and Use Cases
          • Primary Personas
          • High-Level Use Cases (Capability Scale)
          • Edge Cases and Failure Modes
        • 3. Conceptual Model Terms and Decisions
          • Key Terms
          • Decision Ledger
        • 4. Domain Model and Eventstorming (Conceptual)
          • Bounded Context and Ubiquitous Language
          • Primary Access Patterns
          • Aggregates and Entities (Conceptual)
          • Invariants and Business Rules (Normative)
          • Effective Demand Resolution Rules (Normative)
          • Model Relationships
            • Abstract Class Relationships
            • Illustrative Topology Example
          • Contract Definitions
            • Microgrid
            • MicrogridNode
            • CapabilityControlPoint
            • CapabilityStatusEvent
            • CapabilityStatusProjection
            • NodeLimit
            • OperatingEnvelope
            • OperatingEnvelopeBlock
            • Operating-Envelope Compatibility Policy
            • Capability Type Semantics
          • Public Interfaces (Conceptual)
            • Operator-Facing and Core API Shape
            • Error and Status Semantics (Conceptual)
          • Compatibility Matrix
          • Rebalance and Breach Response Semantics
            • Cycle Result Payload (Conceptual)
            • Breach Payload (Conceptual)
            • Capability Status Event Payload (Conceptual)
            • Capability Status Latest-Read-State Payload (Conceptual Read Model)
            • Deterministic Reason-Code Precedence
          • Interaction Flow
          • Event Timeline
          • Sequence Diagram: Operating Envelope Compatibility Lifecycle
          • Event Dictionary
        • 5. Requirements and Constraints
          • Functional Requirements
          • Non-Functional Requirements
          • Constraints and Assumptions
        • 6. Interaction and Flow
          • User Journey
          • Sequence Diagram: Rebalance with Compatibility Alias
          • Flowchart: Topology Update Guardrails
        • 7. Design Extensibility
        • 8. Appendix A: Compatibility Reason Codes
      • OSCP
        • Challenge
        • Specification
        • Spec
        • Architecture
        • Overview
        • Script Runtime Model
        • Compose Profiles and Modes
        • Repo Topology
        • CI and Release Integration
        • Overview
        • Internal Application Diagrams
          • Overview
          • Web Model
          • Core Model
        • Service Interaction Flows
        • Data and State
          • Index
          • bf-manage-web
          • bf-manage-core
          • bf-manage-connect
          • bf-manage-sitepwrmon
          • bf-manage-incidents
          • bf-telematics
          • bf-depot-sim
          • bf-manage-roaming
          • bf-support-microsite
          • bf-digital-twin
          • bf-schedule-creator
        • Overview
        • Internal Application Diagrams
        • Migration and Flags
        • Simulation Request Lifecycle
          • Index
          • bf-bnl-ui
          • bf-bnl-settings
          • bf-bnl-schedule-analysis-compute
          • bf-route-modelling
          • bf-schedule-creator
          • bf-digital-twin
        • Overview
        • Secrets and Env Strategy
        • Vendors and Local Dependencies
        • ADRs
        • Service Matrix
        • Cloud Dependencies
        • Ports and URLs
      • Onboarding
      • Daily Operations Runbook
        • Overview
        • Staging Hotfix Release
        • Production Hotfix Release
        • Terraform Plan Dry Runs
      • Troubleshooting
      • Testing Guide
    • Solution Summary
    • 1. Summary
      • Problem
      • Goal
      • Design Outcomes
      • System Capabilities
      • Scope (In)
      • Scope (Out)
      • Architectural Guardrails
    • 2. Users and Use Cases
      • Primary Personas
      • High-Level Use Cases (Capability Scale)
      • Edge Cases and Failure Modes
    • 3. Conceptual Model Terms and Decisions
      • Key Terms
      • Decision Ledger
    • 4. Domain Model and Eventstorming (Conceptual)
      • Bounded Context and Ubiquitous Language
      • Primary Access Patterns
      • Aggregates and Entities (Conceptual)
      • Invariants and Business Rules (Normative)
      • Effective Demand Resolution Rules (Normative)
      • Model Relationships
        • Abstract Class Relationships
        • Illustrative Topology Example
      • Contract Definitions
        • Microgrid
        • MicrogridNode
        • CapabilityControlPoint
        • CapabilityStatusEvent
        • CapabilityStatusProjection
        • NodeLimit
        • OperatingEnvelope
        • OperatingEnvelopeBlock
        • Operating-Envelope Compatibility Policy
        • Capability Type Semantics
      • Public Interfaces (Conceptual)
        • Operator-Facing and Core API Shape
        • Error and Status Semantics (Conceptual)
      • Compatibility Matrix
      • Rebalance and Breach Response Semantics
        • Cycle Result Payload (Conceptual)
        • Breach Payload (Conceptual)
        • Capability Status Event Payload (Conceptual)
        • Capability Status Latest-Read-State Payload (Conceptual Read Model)
        • Deterministic Reason-Code Precedence
      • Interaction Flow
      • Event Timeline
      • Sequence Diagram: Operating Envelope Compatibility Lifecycle
      • Event Dictionary
    • 5. Requirements and Constraints
      • Functional Requirements
      • Non-Functional Requirements
      • Constraints and Assumptions
    • 6. Interaction and Flow
      • User Journey
      • Sequence Diagram: Rebalance with Compatibility Alias
      • Flowchart: Topology Update Guardrails
    • 7. Design Extensibility
    • 8. Appendix A: Compatibility Reason Codes

    System Design: Microgrid Energy Orchestration¶

    Solution Summary¶

    Microgrid models a site's electrical system as a rooted electrical-node tree with node-linked source assets. It supports load management, energy management, optimisation, and operational visibility. Load balancing and hierarchical limit enforcement run on top of this model. circuit contracts remain compatibility aliases into Microgrid behavior.

    This document defines the system design and reference contracts for the microgrid solution.

    • Microgrid model: define microgrid_id as the primary identifier. Microgrid is the site root. MicrogridNode records form the child tree. The model must work across API, domain, and UI.
    • Node Limit and Envelope model: define baseline node caps, operating envelopes, aggregate caps, and fallback demand rules. Use one deterministic constraint evaluation path.
    • Capability Control Point model: define capability type, enablement state, control source, target node, and external configuration references for each control point. Load balancing and hierarchical limits remain the enforced runtime behavior. The capability taxonomy can grow without changing topology.
    • Capability Status model: define append-only capability status domain events and a derived latest-status read model. Keep configuration separate from live state.
    • Capacity Constraint Policy: define feeder-circuit compatibility projection, synchronous get_effective_circuit_capacity reconciliation, and policy-driven fallback behavior. Operator surfaces and legacy load-balancing paths read the same constraint state.
    • Balancing Cycle: define cycle inputs, outputs, reason-code precedence, and audit fields. Execution must stay deterministic and debuggable.
    • Depot Simulator updates: add microgrid-node topologies, telemetry degradation patterns, and compatibility-path triggers. This supports system-level validation.
    • Compatibility Matrix: map circuit-centric APIs, events, and jobs to Microgrid contracts. Circuit consumers keep working without changing Microgrid ownership.

    1. Summary¶

    Problem¶

    The product needs a Microgrid-based representation of the site electrical system. It must support hierarchical limits, broader energy capability coverage, operator visibility, and compatibility with circuit-centric consumers.

    Goal¶

    • Define the conceptual system design for microgrid topology, balancing, limits, compatibility behavior, and operator visibility.
    • Use microgrid_id as the primary identifier across Microgrid contracts, while preserving circuit-driven compatibility entry points where they remain part of the product surface.
    • Specify deterministic balancing decisions and auditable breach behavior.

    Design Outcomes¶

    • Balancing interfaces are microgrid-scoped, with optional subtree scope where a specific node boundary is required.
    • Depot-scoped operator APIs may resolve the Microgrid through depot_id when depot identity is the operational locator.
    • Legacy circuit flows have explicit translation and compatibility-projection behavior.
    • Operating envelopes are Microgrid state. Legacy circuit capacity is a derived compatibility effect for managed feeder circuits.
    • Operating-envelope lifecycle transitions are scheduler-driven. Synchronous get_effective_circuit_capacity reconciliation protects rebalance-time correctness.
    • Requirement-to-verification mapping is complete and test-plannable.
    • Depot simulator coverage supports end-to-end system testing of topology, limits, fallback, envelope lifecycle, and compatibility paths.

    System Capabilities¶

    • Microgrid domain model: introduce Microgrid, MicrogridNode, CapabilityControlPoint, CapabilityStatusEvent, CapabilityStatusProjection, NodeLimit, and OperatingEnvelope. Use one model across API, domain, and UI.
    • Topology rules: define electrical tree authority, cycle/orphan protections, and versioned edits.
    • Balancing contract: define a validate-before-allocate cycle with deterministic precedence and reason codes.
    • Capability map: define a multi-capability vocabulary with load balancing as the enforced runtime scope in this design.
    • OperatingEnvelope: define a protocol-agnostic inbound envelope model, lifecycle audit model, and active-envelope visibility. External protocol adapters must constrain Microgrid behavior without storing protocol-specific identifiers or foreign keys in Microgrid.
    • Compatibility: define API, event, and scheduler translation from circuit_id to microgrid_id + node_id, plus projection into legacy circuit capacity.
    • Depot Simulator: extend simulator scenarios for microgrid-node structures, limit policies, and degraded telemetry.
    • Operator Visibility: define cycle status, breach payload semantics, and effective circuit-capacity visibility.

    Scope (In)¶

    • Ubiquitous language and conceptual model updates for microgrid-centric balancing.
    • Public interface and event contract definitions (conceptual).
    • Compatibility behavior for circuit-centric contracts.
    • Deterministic policy invariants and verification mapping.
    • Depot simulator enhancements needed for system-level tests.

    Scope (Out)¶

    • DB schema and low-level storage design.
    • Low-level power electronics/control-loop implementation details.
    • Final UI wireframes and visual design system specifics.

    Architectural Guardrails¶

    • The design must support one microgrid containing multiple grid connections and multiple independently managed subtrees without reshaping the core microgrid boundary.
    • Capability taxonomy must allow adding peak shaving and optimization without changing core topology contracts.
    • Compatibility behavior must remain removable without changing Microgrid ownership or contract semantics.
    • External capability configuration owned by other bounded contexts must stay outside the microgrid write model and be referenced opaquely rather than linked by relational foreign keys.

    2. Users and Use Cases¶

    Primary Personas¶

    Persona Primary Job Why this spec matters
    Energy Operations Engineer Configure limits and diagnose constraint breaches. Needs deterministic topology and breach semantics.
    Product/Platform Engineer Build APIs, domain flows, and compatibility adapters. Needs clear contracts and translation rules.
    Site Integrator Integrate telemetry and legacy control paths. Needs explicit compatibility and failure behavior.
    Support/Troubleshooting Explain why a cycle curtailed or rejected. Needs reason-code and audit contract clarity.
    QA/System Test Engineer Validate cross-service behavior in simulation before production use. Needs simulator scenarios that mirror microgrid behavior and compatibility paths.

    High-Level Use Cases (Capability Scale)¶

    • As an operator, I can configure one microgrid with a node hierarchy and node-linked source assets without creating invalid topology states.
    • As a scheduler/system actor, I can run one balancing cycle per microgrid and receive deterministic outcomes.
    • As an integration client, I can continue using circuit APIs through compatibility aliases and receive equivalent microgrid behavior.
    • As an observer, I can inspect cycle and breach outputs with deterministic reason codes and audit metadata.
    • As a test engineer, I can run system-level simulator scenarios that validate microgrid topology rules, limit enforcement, and compatibility translation.

    Edge Cases and Failure Modes¶

    • Reparent operation introduces a topology cycle.
    • Node is detached from root (orphan).
    • Aggregate cap breached while all individual nodes remain below local caps.
    • Telemetry missing/stale for one or more nodes.
    • Legacy circuit ID has no resolvable microgrid alias.
    • Concurrent topology edits produce version conflict.

    3. Conceptual Model Terms and Decisions¶

    Key Terms¶

    Term Definition Notes
    Microgrid Root aggregate for one depot-level electrical system. One depot resolves to one microgrid in this design.
    Grid Connection External supply connection for a microgrid. This spec uses it as the supply-side term. Managed scope anchors are represented by GRID_CONNECTION nodes.
    Microgrid Node Electrical node in the microgrid tree where enforceable limits may apply. Node tree is authoritative physical topology.
    Node Limit Constraint applied to a node/subtree demand envelope. Includes hard-cap semantics and policy references.
    Capability Control Point Microgrid binding for one capability at one microgrid scope, including ownership, state, and any opaque external configuration reference needed to resolve capability-owned config. Uses microgrid_id + node_id as its targeting boundary.
    Capability Status Event Immutable runtime status record appended for one capability control point. History stream source of truth for runtime status changes.
    Capability Status Projection Derived latest runtime status per capability control point. Read-model concept for UI/status cards; it may be materialized or reconstructed from authoritative status events.
    Operating Envelope Protocol-agnostic, time-bounded operating constraint accepted by microgrid for one node subtree. Used by OSCP and other protocol adapters without making microgrid protocol-aware.
    Effective Circuit Capacity Feeder-circuit capacity value used by legacy load balancing after reconciling any active microgrid operating envelope for the mapped GRID_CONNECTION node. Resolved synchronously by get_effective_circuit_capacity before TOU and allocation logic run.
    Fallback Forecast Protocol-agnostic operating envelope retained for use when the primary forecast source is stale or offline. Follows the same validity rules as other operating envelopes but is only eligible through fallback policy.
    Effective Demand Demand value used for enforcement checks: measured demand if fresh and valid, otherwise deterministic derived fallback. Must include source mode and be auditable.
    Balancing Cycle Single microgrid-level pass that evaluates constraints then allocates power. Validate-before-allocate invariant.
    Breach Condition where active node or aggregate constraints are exceeded. Must include deterministic reason code.

    Decision Ledger¶

    ID Decision Rationale Alternatives Rejected Implications
    D-001 Execute balancing at the microgrid boundary, with optional node-scoped context inside that boundary when a specific subtree must be targeted. Aligns runtime behavior with product intent and avoids split control loops while still allowing targeted control and compatibility paths. Per-circuit balancing boundary. Rebalance requests and status contracts become microgrid-keyed, with optional node_id context.
    D-002 Use Grid Connection as the supply-side term. Keeps terminology unambiguous for delivery and operations. Multiple interchangeable supply terms. UI, API, and docs use one consistent term.
    D-003 Model topology as Microgrid root plus electrical child-node tree where each node references its source asset where applicable. Keeps the aggregate root explicit while preserving a concrete electrical hierarchy for enforcement and visibility. Separate synthetic root node or fully generic typed node graph. Microgrid is the site root; child nodes enforce limits and carry source asset references for circuits, chargers, connectors, or power sources.
    D-004 Keep the enforced runtime scope to load balancing and hierarchical limits. Keeps the design focused while defining an extensible capability taxonomy. Full multi-capability runtime scope now. Peak shaving, DER, and optimisation remain part of the model without changing topology or ownership boundaries.
    D-005 Use microgrid_id as the primary identifier; circuit_id remains an alias-only compatibility reference. Keeps the model single-sourced while allowing circuit-facing consumers to resolve into Microgrid operations. Keep circuit as the primary identifier; dual primary IDs. Requires an explicit translation matrix and compatibility policy.
    D-006 Supported cardinality is 1 depot = 1 microgrid, with one or more GRID_CONNECTION child nodes inside that microgrid. Keeps the electrical system boundary stable while allowing single- and multi-grid-connection depots. 1 depot = many microgrids. Site-wide capability state and aggregate constraints stay on one microgrid while control and integration can target scoped subtrees.
    D-019 Represent scoped control as microgrid_id + node_id references, not as separate scope entities or extra microgrid identities. Keeps OSCP, legacy circuit aliasing, and additional subsite control boundaries within one microgrid without adding an unnecessary extra entity. Encode scopes as extra microgrids or protocol-specific routing fields in microgrid. External integrations and compatibility layers can target part of a microgrid without duplicating the microgrid aggregate.
    D-007 Enforce ancestor node-cap precedence over descendant allocations. Guarantees safety in hierarchical limits. Local-only node checks. Allocation planner must validate ancestry constraints first.
    D-008 Validate constraints before allocation application. Prevents infeasible charging profile updates. Apply then rollback on breach. Cycle may return REJECTED/CURTAILED without apply step.
    D-009 Use topology versioning and expose it as the concurrency boundary for authored topology mutation. Prevents hidden race conditions in node edits and keeps topology state auditable. Last-write-wins topology edits. version is part of the Microgrid contract and gates topology mutation.
    D-010 Emit deterministic reason-code ordering in cycle outputs. Enables reproducible debugging and support workflows. Unordered or implementation-defined reasons. The reason-code precedence table is part of the contract.
    D-011 Preserve compatibility paths for legacy events and scheduled jobs through translation. Keeps circuit-facing consumers compatible while Microgrid remains the source of truth. Big-bang replacement. Compatibility adapters must translate rather than becoming alternate sources of truth.
    D-012 Fail safe toward lower allowed allocation under uncertainty. Safety-first behavior under partial telemetry or policy ambiguity. Best-effort optimistic allocation. Potential throughput reduction in degraded telemetry scenarios.
    D-013 Treat depot simulator coverage as part of the enduring microgrid design. Reduces operational risk by validating behavior in full-stack scenarios. Unit/integration tests only without simulator parity. Requires simulator model and scenario updates alongside microgrid evolution.
    D-014 Separate configured capability control points from runtime capability status. Prevents config/live-state coupling and supports external status ingest cleanly. Single mixed capability object. Requires a latest-status read model and API shape for operational visibility.
    D-015 schedule_ref is allowed only for LOCAL capabilities. Avoids ambiguity for externally controlled capabilities. Shared schedule semantics for local and external control. External capabilities expose status only until a distinct external schedule contract exists.
    D-016 Link capability status records to CapabilityControlPoint by reference from status record to control point. Control points are the stable configuration master; statuses are mutable runtime observations. Use microgrid_id + node_id + capability_type as the only event key. Supports one-to-many historical status records without control-point churn.
    D-017 Model runtime capability status as append-only domain events with a derived latest read model. Matches event-sourced patterns and preserves full operational history. Mutable single-row status table. Requires immutable event append semantics and read-model reconstruction or projection rebuild support.
    D-018 Model externally sourced aggregate constraints as a protocol-agnostic OperatingEnvelope owned by the microgrid domain. Allows OSCP and other external protocols to constrain microgrid behavior without leaking protocol identity into microgrid. Protocol-specific commands or identifiers stored directly in microgrid. External adapters must translate into the envelope contract before microgrid evaluation.
    D-020 Do not model a separate runtime mode for feeder-circuit compatibility. If an active envelope exists for a managed GRID_CONNECTION node, it always participates in compatibility; adding a second policy switch only duplicates business intent. Persisted mode flags or hidden version-based behavior. Operating-envelope presence is the compatibility trigger, and no operator-facing mode toggle is required.
    D-021 Treat operating envelopes as the source of constraint state and legacy circuit capacity as a derived compatibility output. Keeps microgrid as the owner of constraint semantics while still serving existing circuit-centric consumers. Make legacy circuit capacity the source of truth. Effective circuit capacity is recomputed from active forecast state plus circuit policy inputs, not restored from persisted projection baseline.
    D-022 Restrict compatibility projection to envelopes targeting a managed GRID_CONNECTION node that maps to exactly one feeder circuit. Keeps the compatibility seam explicit and deterministic while envelopes remain node-scoped. Implicit subtree aggregation or ambiguous many-circuit projection. Ambiguous or unmapped scopes must fail deterministically instead of guessing.
    D-023 Own envelope activation, block-boundary transitions, expiry, and fallback-policy application through scheduled lifecycle evaluation, with synchronous pre-rebalance reconciliation as a correctness guard. Keeps envelope state transitions deterministic while ensuring rebalance can reconcile drift at now without waiting for background processing. Read-time mutation without persistence or rebalance-only lazy evaluation without projection updates. get_effective_circuit_capacity must recompute and update effective circuit capacity without recursively requesting another rebalance.
    D-024 Link capability configuration owned by other bounded contexts through opaque external reference fields on CapabilityControlPoint, not relational foreign keys across contexts. Preserves bounded-context ownership while keeping node-scoped capability identity in Microgrid. Cross-context foreign keys from OSCP/VDV/etc. config tables to microgrid control points; opaque JSON blobs as the only linkage contract. Requires explicit external reference fields and adapter-level resolution logic.
    D-025 Audit capability runtime status and enforceable operating bounds through separate event streams. Status and bounds are related but not the same concern; operators need independent history for both. Reuse capability-status events as the only receipt/audit trail for operating envelopes. Requires first-class operating-envelope lifecycle events and read/query support that do not depend on capability-status payload parsing.

    4. Domain Model and Eventstorming (Conceptual)¶

    Bounded Context and Ubiquitous Language¶

    • Bounded context: Microgrid Energy Orchestration.
    • Core actors: Operator, Scheduler, Telemetry Ingest, External Protocol Adapter, Compatibility Adapter.
    • Core commands: update topology, update node limits, update capability control point, append capability status event, submit operating envelope, request rebalance.
    • Core events: topology updated, node limit updated, capability control point updated, capability status recorded, operating envelope received, operating envelope lifecycle evaluated, legacy capacity projected, cycle evaluated, breach detected, allocation applied.

    Primary Access Patterns¶

    • Physical Topology View (Tree)
      • Uses the node hierarchy to validate and enforce electrical flow constraints, such as fuse and grid-connection envelopes.
      • Evaluates all enforceable node limits and ancestor constraints.
    • Operational Collection View (Resource Sets)
      • Uses collection-based queries, such as all BESS assets and charge points in a subtree or logical group, for energy-management calculations and optimization.
      • Can generate candidate strategies without depending on tree traversal mechanics.
      • Any candidate action that affects power allocation must still pass physical topology and node-limit validation before apply.

    Aggregates and Entities (Conceptual)¶

    • MicrogridAggregate:
      • Owns child node tree, capability control points, active node limits, and active operating-envelope references.
      • Owns balancing-cycle execution boundary.
    • MicrogridNode:
      • Represents electrical structure and node-level policy assignment.
      • Supports reparenting with cycle/orphan protections.
    • NodeLimit:
      • Defines baseline node constraints and fallback behavior.
    • CapabilityControlPoint:
      • Defines capability identity, control ownership, target node context, and any opaque external configuration reference needed to resolve capability-owned config outside the microgrid boundary.
    • CapabilityStatusEvent:
      • Immutable runtime status event reported by local or external control paths.
    • CapabilityStatusProjection:
      • Latest runtime status read model derived from status events for read-side consumers.
      • May be materialized directly or reconstructed from authoritative status events.
    • OperatingEnvelope:
      • Represents a protocol-agnostic operating constraint for one node subtree within a microgrid.
      • Owns normalized effective window, envelope blocks, generic source reference metadata, active lifecycle state, target scope, and optional origin control-point reference for traceability.

    Invariants and Business Rules (Normative)¶

    1. Node hierarchy must form a single rooted acyclic tree, with Microgrid as the implicit root and one or more first-level GRID_CONNECTION child nodes beneath it.
    2. Each node belongs to exactly one microgrid.
    3. A source asset may be referenced by at most one node in the same microgrid.
    4. Only nodes carry enforceable physical-limit constraints.
    5. Balancing cycle must evaluate ancestor and aggregate constraints before allocation apply.
    6. Effective demand source order is deterministic: measured, then fallback.
    7. Cycle output reason codes must follow fixed precedence ordering.
    8. Legacy circuit_id commands must resolve to exactly one microgrid_id and one target node_id.
    9. Collection-view optimization outputs must be validated against node-limit constraints before apply.
    10. Capability control point state is enabled or disabled; runtime operational status is represented as a free-form string in status events.
    11. schedule_ref must be null for capability control points where control_source=EXTERNAL.
    12. Each capability status event must reference an existing capability control point for the same microgrid.
    13. Capability control points may target either the whole microgrid (node_id=null) or one node subtree.
    14. At most one active capability control point may exist for the same microgrid_id + node_id + capability_type.
    15. At most one active baseline node limit may exist for the same node_id + constraint_type.
    16. Capability status events are append-only and immutable once accepted.
    17. Latest capability status read state is derived from ordered status events and may be rebuilt from stream history.
    18. Operating-envelope ingress must remain protocol-agnostic and must not require OSCP or other protocol-specific identifiers or cross-context foreign keys in the microgrid domain model.
    19. Operating envelopes target one node subtree and must reference a valid node in the owning microgrid.
    20. Active operating envelopes must be evaluated as effective constraints before allocation apply.
    21. When a baseline NodeLimit and one or more active OperatingEnvelope records apply to the same node and constraint type, the effective constraint used for balancing must be the most restrictive active value.
    22. Active operating envelopes for a managed GRID_CONNECTION node must project the effective envelope constraint to the mapped feeder circuit and must restore the non-envelope baseline deterministically when the envelope no longer applies.
    23. Operating-envelope lifecycle transitions must be driven by scheduled evaluation at block boundaries and envelope expiry, while rebalance-time compatibility must be protected by synchronous get_effective_circuit_capacity reconciliation.
    24. Capability control points may store opaque external configuration references for capability config owned outside microgrid, but microgrid must not require relational write-time foreign keys to those external config tables.
    25. Capability status history and operating-envelope lifecycle history are separate audit concerns and must not be collapsed into one payload contract.

    Effective Demand Resolution Rules (Normative)¶

    For each checked scope (node or aggregate): 1. Use measured_demand_watts if telemetry is present, valid, and within freshness threshold. 2. Otherwise derive fallback_demand_watts from configured fallback policy inputs. 3. Set source_mode to MEASURED or FALLBACK_DERIVED. 4. Persist audit fields identifying source inputs and thresholds used.

    Model Relationships¶

    Abstract Class Relationships¶

    classDiagram
        direction LR
    
        class Depot {
            +UUID depot_id
        }
    
        class Microgrid {
            +UUID microgrid_id
            +UUID depot_id
            +int version
        }
    
        class MicrogridNode {
            +UUID node_id
            +UUID microgrid_id
            +UUID? parent_node_id
            +string name
            +NodeType node_type
            +AssetType? attached_asset_type
            +UUID? attached_asset_id
            +NodeStatus status
            +int display_order
        }
    
        class CapabilityControlPoint {
            +UUID control_point_id
            +UUID microgrid_id
            +UUID? node_id
            +CapabilityType capability_type
            +CapabilityState state
            +ControlSource control_source
            +string? external_config_type
            +string? external_config_ref
            +object? local_config
        }
    
        class CapabilityStatusEvent {
            +UUID status_event_id
            +UUID microgrid_id
            +UUID control_point_id
            +UUID? node_id
            +string operational_status
            +datetime observed_at
        }
    
        class CapabilityStatusProjection {
            +UUID microgrid_id
            +UUID control_point_id
            +UUID? node_id
            +string latest_operational_status
            +datetime last_observed_at
            +ReadModel only
        }
    
        class NodeLimit {
            +UUID node_limit_id
            +UUID microgrid_id
            +UUID node_id
            +ConstraintType constraint_type
            +int limit_watts
            +LimitSourceType source_type
        }
    
        class OperatingEnvelope {
            +UUID envelope_id
            +UUID microgrid_id
            +UUID node_id
            +UUID? origin_control_point_id
            +EnvelopeType envelope_type
            +ConstraintType constraint_type
            +EnvelopeStatus status
        }
    
        Depot "1" --> "1" Microgrid : owns
        Microgrid "1" *-- "0..*" MicrogridNode : child nodes
        MicrogridNode "1" --> "0..*" MicrogridNode : child nodes
        Microgrid "1" --> "0..*" CapabilityControlPoint : defines
        CapabilityControlPoint "1" --> "0..*" CapabilityStatusEvent : records
        CapabilityControlPoint "1" --> "1" CapabilityStatusProjection : projects
        MicrogridNode "1" --> "0..*" NodeLimit : constrained by
        MicrogridNode "1" --> "0..*" OperatingEnvelope : receives
        CapabilityControlPoint --> MicrogridNode : targets 0..1 node
        CapabilityStatusEvent --> MicrogridNode : cached 0..1 node
        CapabilityStatusProjection --> MicrogridNode : cached 0..1 node
        NodeLimit --> MicrogridNode : targets 1 node
        OperatingEnvelope --> MicrogridNode : targets 1 node
        OperatingEnvelope --> CapabilityControlPoint : optional origin 0..1

    MicrogridScope is not a first-class entity. Scope is represented everywhere as microgrid_id + node_id, where node_id identifies the subtree root for the command, envelope, projection, or compatibility mapping being evaluated.

    Illustrative Topology Example¶

    flowchart TD
        Depot[Depot] --> Microgrid[Microgrid<br/>microgrid_id<br/>depot_id]
    
        Microgrid --> GC1[MicrogridNode<br/>node_type=GRID_CONNECTION]
        Microgrid --> GC2[MicrogridNode<br/>node_type=GRID_CONNECTION]
        GC1 --> C1[MicrogridNode<br/>node_type=CIRCUIT]
        C1 --> CP1[MicrogridNode<br/>node_type=CHARGE_POINT]
        CP1 --> CON1[MicrogridNode<br/>node_type=CONNECTOR]
    
        GC1 -. attached_asset .-> CircuitAssetA[(Circuit)]
        GC2 -. attached_asset .-> CircuitAssetB[(Circuit)]
        C1 -. attached_asset .-> SubCircuitAsset[(Circuit)]
        CP1 -. attached_asset .-> ChargePointAsset[(Charge Point)]
        CON1 -. attached_asset .-> ConnectorAsset[(Connector)]
    
        Microgrid --> SiteCP[CapabilityControlPoint<br/>node_id=null]
        GC1 --> ScopedCP[CapabilityControlPoint<br/>node_id=grid_connection_node]
        SiteCP --> StatusEvent[CapabilityStatusEvent<br/>append-only history]
        SiteCP --> StatusProjection[CapabilityStatusProjection<br/>latest read model]
        ScopedCP --> StatusEvent
        ScopedCP --> StatusProjection
    
        GC1 --> NodeLimit[NodeLimit]
        GC1 --> OperatingEnvelope[OperatingEnvelope]
        C1 --> BranchLimit[NodeLimit]

    Contract Definitions¶

    Microgrid¶

    Field Type Description
    microgrid_id UUID Microgrid identifier.
    depot_id UUID Depot identity for the one-to-one depot mapping.
    version integer Persisted change marker and optimistic-concurrency token for authored topology mutation.
    • Microgrid is the site root.
    • First-level child nodes are represented by MicrogridNode rows with parent_node_id = null.
    • Row-level audit fields are intentionally omitted.
    • Audit history is derived from domain events, compatibility streams, and audit streams.
    • version is the row-level change marker used for deterministic mutation ordering.

    MicrogridNode¶

    Field Type Description
    node_id UUID Node identity.
    microgrid_id UUID Owning microgrid identifier.
    parent_node_id UUID | null Parent node; null only for first-level children beneath the microgrid root.
    name string Operator-facing node name.
    node_type enum GRID_CONNECTION, CIRCUIT, CHARGE_POINT, CONNECTOR, POWER_SOURCE, VIRTUAL.
    attached_asset_type enum | null CIRCUIT, CHARGE_POINT, CONNECTOR, POWER_SOURCE, or null for virtual nodes.
    attached_asset_id UUID | null Source-domain asset id referenced by this node.
    status enum ACTIVE, MAINTENANCE, UNAVAILABLE.
    display_order integer Stable ordering for API and UI rendering.
    • MicrogridNode is both the topology node and the attachment point for source-domain assets.
    • A separate attached-asset entity is not part of the design.
    • Managed compatibility scopes are anchored at first-level GRID_CONNECTION nodes.
    • Deeper child structure, such as circuits, charge points, connectors, power sources, and virtual nodes, may participate in topology and visibility.

    CapabilityControlPoint¶

    Field Type Description
    control_point_id UUID Control-point identifier.
    microgrid_id UUID Owning microgrid identifier.
    node_id UUID | null Null means whole-microgrid control point; otherwise target subtree root node.
    capability_type enum LOAD_BALANCING, PEAK_SHAVING, DER, ENERGY_OPTIMISATION.
    state enum enabled, disabled.
    control_source enum LOCAL, EXTERNAL.
    description string Human-readable description of intent.
    local_config object Optional microgrid-owned static configuration payload for capabilities whose authored config lives inside the microgrid boundary.
    external_config_type string | null Optional namespace for capability configuration owned by another bounded context, such as OSCP_CONFIGURATION.
    external_config_ref string | null Optional opaque identifier for capability configuration owned by another bounded context.
    schedule_ref string | null Optional schedule identifier; valid only for LOCAL.

    Recommended uniqueness: one active control point per microgrid_id + node_id + capability_type.

    • CapabilityControlPoint links node scope to capability identity.
    • When another bounded context owns capability configuration, the control point stores an opaque external reference instead of a relational foreign key across contexts.

    CapabilityStatusEvent¶

    Field Type Description
    status_event_id UUID Unique immutable status-event identifier.
    microgrid_id UUID Microgrid identifier.
    control_point_id UUID Reference to owning CapabilityControlPoint.
    node_id UUID | null Cached target node for read/query efficiency; null means whole-microgrid status.
    capability_type enum Same capability-type enum as CapabilityControlPoint.
    operational_status string Free-form runtime status text from local/external controller.
    reported_by enum LOCAL, EXTERNAL.
    observed_at datetime (UTC) Source-system observation timestamp for this event.
    ingested_at datetime (UTC) Ingestion timestamp for this event.
    source_event_ref string | null Optional upstream event identity retained for audit, correlation, and shared inbox/idempotency workflows.
    status_detail object | null Optional capability-specific live detail payload (including raw external fields such as boolean controller values before UI-friendly normalization).
    • control_point_id is the stable link for status history.
    • microgrid_id, node_id, and capability_type are retained for query efficiency and audit readability.

    CapabilityStatusProjection¶

    Field Type Description
    microgrid_id UUID Microgrid identifier.
    control_point_id UUID Reference to owning CapabilityControlPoint.
    node_id UUID | null Cached target node for read/query efficiency; null means whole-microgrid status.
    capability_type enum Same capability-type enum as CapabilityControlPoint.
    latest_operational_status string Latest derived free-form runtime status text.
    reported_by enum LOCAL, EXTERNAL for latest derived status.
    last_observed_at datetime (UTC) Latest source observation timestamp used in projection.
    last_ingested_at datetime (UTC) Latest ingestion timestamp used in projection.
    freshness_seconds int Age of latest status used for UI freshness indicators.
    status_detail object | null Latest detail payload for status-card and debug views.
    • CapabilityStatusProjection is a read model, not a required writable microgrid-domain table.
    • It may be materialized directly or reconstructed from authoritative status events.
    • External-controller integrations may ingest boolean raw values and normalize them into stable operational-status strings such as ON and OFF, while retaining the raw source value in status_detail.

    NodeLimit¶

    Field Type Description
    node_limit_id UUID Node-limit identifier.
    microgrid_id UUID Owning microgrid identifier.
    node_id UUID Target node identifier.
    constraint_type enum CONSUMPTION_CAP, GENERATION_CAP, NET_CAP.
    limit_watts int Baseline limit value applied to the node subtree.
    source_type enum PHYSICAL_DERIVED, MANUAL, FAIL_SAFE, STATIC_POLICY.
    status enum ACTIVE, INACTIVE.
    updated_at datetime (UTC) Last change timestamp.

    NodeLimit is the baseline structural constraint for a node. Time-bounded or externally sourced overrides belong in OperatingEnvelope.

    OperatingEnvelope¶

    Field Type Description
    envelope_id UUID Microgrid envelope identifier.
    microgrid_id UUID Microgrid identifier.
    origin_control_point_id UUID | null Optional reference to the control point whose configured capability path originated this bound.
    node_id UUID Referenced node subtree root for the envelope.
    envelope_type enum TOU_LIMIT, FORECAST, FALLBACK, OVERRIDE. Source-specific inputs such as OSCP forecasts or demand-response signals are normalized to these Microgrid types at the boundary.
    constraint_type enum CONSUMPTION_CAP, GENERATION_CAP, NET_CAP. NET_CAP applies to the resulting net exchange across the node boundary after offsetting simultaneous consumption and generation.
    effective_from datetime (UTC) Inclusive start time for the envelope.
    effective_to datetime (UTC) Exclusive end time for the envelope.
    source_ref string Opaque upstream control reference retained for audit and idempotency.
    status enum PENDING, ACTIVE, EXPIRED, WITHDRAWN, REJECTED.
    received_at datetime (UTC) Ingestion timestamp for the envelope.
    • OperatingEnvelope represents scheduled or externally sourced effective constraints applied on top of baseline NodeLimit values.
    • Envelope receipt, withdrawal, expiry, and other lifecycle changes are audited independently from capability-status history.

    OperatingEnvelopeBlock¶

    Field Type Description
    envelope_id UUID Owning operating-envelope identifier.
    block_from datetime (UTC) Inclusive block start time.
    block_to datetime (UTC) Exclusive block end time.
    min_limit_watts int | null Optional minimum bound for the block.
    max_limit_watts int | null Optional maximum bound for the block.
    target_watts int | null Optional target value for the block. The current compatibility projection uses target_watts as the circuit-facing effective value.

    Operating-Envelope Compatibility Policy¶

    • OperatingEnvelope holds time-bounded externally sourced or operator-authored constraint state.
    • Compatibility projection is permitted only when the envelope targets a managed first-level GRID_CONNECTION node that maps to exactly one feeder circuit.
    • Active primary forecast envelopes determine the forecast-side limit while the source is healthy.
    • If the forecast source is stale or offline, a valid FALLBACK envelope determines the forecast-side limit. If no valid fallback forecast exists, the circuit fail-safe capacity applies.
    • If the source is healthy but the current primary forecast has no active block, the configured gap policy determines the forecast-side limit. The current implementation defaults to circuit default capacity.
    • Active non-forecast envelopes such as overrides or TOU limits can further tighten the resolved forecast-side limit; the most restrictive active limit wins.
    • Envelope receipt, withdrawal, and scheduled lifecycle evaluation are compatibility projection triggers. They may update the mapped feeder-circuit capacity and request legacy rebalance when the effective value changes.
    • get_effective_circuit_capacity(circuit_id, occurred_at) is a synchronous rebalance-time guard. It may reconcile the mapped feeder-circuit capacity before TOU and allocation logic run, but it must update the circuit-facing effective value without requesting another rebalance.
    • Compatibility projection trigger values are ENVELOPE_CHANGE, ENVELOPE_LIFECYCLE, and REBALANCE_GUARD.

    Capability Type Semantics¶

    Capability Type Intended Role Runtime Scope in This Design
    LOAD_BALANCING Local balancing mode and strategy configuration for enforceable allocation control. Enforced in this design. It is typically microgrid-wide, but node-scoped use remains possible.
    PEAK_SHAVING Peak-management mode sourced from external controller status and integration config. Included in the capability taxonomy and visible in status interfaces. It is not part of balancing semantics in this design.
    DER Distributed energy resource coordination mode sourced from external controller status and integration config. Included in the capability taxonomy and visible in status interfaces. It is not part of balancing semantics in this design.
    ENERGY_OPTIMISATION Strategy/advisory optimization intent over resource collections (cost/carbon/efficiency targets). Candidate/advisory outputs only; must pass physical-limit validation before apply.

    Public Interfaces (Conceptual)¶

    • microgrid_id is the primary entity identifier.
    • Depot-scoped operator routes may resolve the Microgrid through depot_id when depot identity is the operational locator.
    • Circuit-facing routes remain compatibility aliases only.

    Operating-envelope ingestion is not a public microgrid HTTP concern in this design. External interfaces such as OSCP and future protocol adapters translate source payloads and submit OperatingEnvelope records through the internal MicrogridOperatingEnvelopeWritePort, targeted by microgrid_id + node_id. Operator-facing microgrid routes remain read and management oriented.

    Operator-Facing and Core API Shape¶

    Endpoint Purpose ID Rules
    GET /api/depot/{depot_id}/microgrid Retrieve the depot Microgrid for operator visibility, including active envelopes and effective circuit-capacity state. Depot-scoped locator alias for the Microgrid.
    POST /api/depot/{depot_id}/microgrid/resync Rebuild managed first-level GRID_CONNECTION nodes from the depot's authoritative top-level feeder circuits. Depot-scoped reconciliation entry point for the Microgrid.
    POST /api/depot/{depot_id}/microgrid/capability-status-events Record whole-microgrid capability status changes for the Microgrid resolved from the depot. Depot-scoped ingest alias for the Microgrid.
    GET /api/microgrid/{microgrid_id}/topology Retrieve the Microgrid node tree and node-linked source asset references. Uses microgrid_id only.
    GET /api/microgrid/{microgrid_id}/control-points Retrieve capability control points with optional latest runtime status projection. Supports optional capability_type query and node_id query for targeted reads.
    POST /api/microgrid/{microgrid_id}/topology Replace or patch topology with version check. Requires version for optimistic concurrency.
    POST /api/microgrid/{microgrid_id}/control-points/{control_point_id} Update one capability control-point config record. Enforces control_source, schedule_ref, and target-node invariants.
    POST /api/microgrid/{microgrid_id}/control-points/{control_point_id}/status-events Append one immutable capability status event. Requires valid control-point reference and idempotency fields for safe ingest.
    GET /api/microgrid/{microgrid_id}/control-points/{control_point_id}/status-events Retrieve capability status-event history. Supports time-range and pagination filters.
    GET /api/microgrid/{microgrid_id}/node-limits Retrieve active node limits. Supports optional node_id query.
    POST /api/microgrid/{microgrid_id}/node-limits Create or update node limits. Validation rejects duplicates and unsupported node types.
    GET /api/microgrid/{microgrid_id}/status Retrieve latest cycle, breach status, active operating-envelope summary, and capability status projection. Includes deterministic reason code ordering.
    POST /api/microgrid/{microgrid_id}/rebalance Trigger one microgrid balancing cycle. Idempotent request correlation key and optional node_id context supported.

    Error and Status Semantics (Conceptual)¶

    Status Meaning Required response fields
    200 Request accepted/completed. microgrid_id, timestamp, result.
    409 Topology/policy version conflict or alias ambiguity. reason_code, expected_version, actual_version.
    422 Validation failure (cycle/orphan/policy invariant). reason_code, violated_rule, details.
    503 Insufficient telemetry with no valid fallback. reason_code, missing_inputs, safe_action_taken.

    Compatibility Matrix¶

    Legacy Contract Target Contract Translation Rule Failure Behavior
    POST /api/circuit/{circuit_id}/rebalance_load POST /api/microgrid/{microgrid_id}/rebalance Resolve legacy circuit alias to microgrid_id + node_id, execute one microgrid cycle with that scoped context, map response IDs. 409 CIRCUIT_ALIAS_NOT_RESOLVABLE if no mapping.
    GET/POST /api/circuit/{circuit_id}/tou_limits OperatingEnvelope write/read boundary on microgrid_id + node_id Map circuit_id schedule scope to the target managed node and preserve schedule semantics through the Microgrid write boundary. 422 LIMIT_SCOPE_TRANSLATION_FAILED for invalid mapping.
    load_balancer.rebalance_requested(circuit_id) microgrid.rebalance_requested(microgrid_id) Compatibility adapter translates and emits the Microgrid event. Emit a failure event with CIRCUIT_ALIAS_NOT_RESOLVABLE.
    ScheduledEventRebalancePeriodic{circuit_id} ScheduledEventRebalancePeriodic{microgrid_id} Scheduler resolves alias at dispatch time. Skip cycle and publish auditable scheduler error with reason code.
    TOU payload circuit_id Operating-envelope payload microgrid_id + node_id Map scheduled circuit scope to the target managed node where possible. 422 LEGACY_POLICY_SCOPE_AMBIGUOUS.

    Rebalance and Breach Response Semantics¶

    Cycle Result Payload (Conceptual)¶

    Field Description
    cycle_id Unique cycle execution identifier.
    microgrid_id Microgrid execution boundary.
    node_id Optional scoped-subtree boundary used by compatibility or external-control paths.
    topology_version Version used for the cycle.
    started_at / ended_at Cycle execution timestamps (UTC).
    outcome APPLIED, CURTAILED, or REJECTED.
    reason_codes Deterministically ordered reason codes.
    allocation_summary Aggregate allocation result and by-node summary.
    breaches Zero or more active breach descriptors.
    audit Actor/source, correlation_id, policy_version refs.

    Breach Payload (Conceptual)¶

    Field Description
    breach_id Unique breach record id.
    microgrid_id Microgrid identifier.
    node_id Optional node identity for node breach.
    constraint_ref node_limit_id or envelope_id that triggered the breach.
    reason_code Deterministic reason code.
    effective_demand_watts Evaluated demand at breach time.
    resolved_limit_watts Active effective value used by compatibility projection or breach evaluation.
    source_mode MEASURED or FALLBACK_DERIVED.
    detected_at UTC timestamp.

    Capability Status Event Payload (Conceptual)¶

    Field Description
    status_event_id Immutable event identifier.
    microgrid_id Microgrid identifier.
    control_point_id Control-point reference for deterministic linkage and joins.
    capability_type Capability identity, for example LOAD_BALANCING, PEAK_SHAVING, or DER.
    operational_status Free-form runtime status text from local/external controller.
    reported_by LOCAL or EXTERNAL.
    observed_at Source timestamp for this status event (UTC).
    ingested_at Platform ingestion timestamp (UTC).
    source_event_ref Optional upstream event identity retained for audit, correlation, and shared inbox/idempotency workflows.
    status_detail Optional detail object for capability-specific telemetry/state fields.

    Capability Status Latest-Read-State Payload (Conceptual Read Model)¶

    Field Description
    microgrid_id Microgrid identifier.
    control_point_id Control-point reference for deterministic linkage and joins.
    capability_type Capability identity, for example LOAD_BALANCING, PEAK_SHAVING, or DER.
    latest_operational_status Latest derived free-form runtime status text.
    reported_by LOCAL or EXTERNAL for latest derived status.
    last_observed_at Source timestamp used by the latest derived read state (UTC).
    last_ingested_at Ingestion timestamp used by the latest derived read state (UTC).
    freshness_seconds Age of latest status used for UI freshness indicators.
    status_detail Optional typed detail object for capability-specific cards.

    Deterministic Reason-Code Precedence¶

    1. TOPOLOGY_INVALID
    2. TOPOLOGY_VERSION_CONFLICT
    3. ANCESTOR_CAP_EXCEEDED
    4. AGGREGATE_CAP_EXCEEDED
    5. NODE_CAP_EXCEEDED
    6. TELEMETRY_STALE_FALLBACK_USED
    7. LEGACY_ALIAS_TRANSLATION_APPLIED

    Interaction Flow¶

    flowchart LR
      A[Operator or Scheduler] --> B[Command: Update Topology / Limits / Rebalance]
      B --> C[Policy Checks: Topology + Version + Limit Consistency]
      C -->|valid| D[Resolve Effective Demand]
      C -->|invalid| E[Reject Command with Deterministic Reason Code]
      D --> F[Evaluate Ancestor and Aggregate Constraints]
      F --> G{Feasible Allocation?}
      G -->|Yes| H[Apply Allocations]
      G -->|No| I[Apply Curtailment or Reject]
      H --> J[Publish Cycle Summary + Audit]
      I --> K[Publish Breach + Cycle Summary + Audit]

    Event Timeline¶

    timeline
      title Microgrid Balancing Event Timeline
      Topology Updated: Versioned topology accepted
      Node Limit Updated: Baseline node constraint changed
      Cycle Requested: Rebalance command accepted
      Demand Resolved: Measured or fallback demand selected
      Constraints Evaluated: Ancestor, node, and aggregate checks
      Allocation Applied or Rejected: Deterministic outcome generated
      Audit Published: Cycle summary and breach details emitted

    Sequence Diagram: Operating Envelope Compatibility Lifecycle¶

    sequenceDiagram
      participant Source as External Adapter or Operator
      participant API as Microgrid API
      participant Domain as Microgrid Domain
      participant Scheduler as Envelope Lifecycle Scheduler
      participant Compat as Legacy Circuit Compatibility
    
      Source->>API: Submit OperatingEnvelope(microgrid_id + node_id)
      API->>Domain: Validate envelope, target node, and blocks
      Domain->>Domain: Persist OperatingEnvelope
      Domain->>Compat: Project effective CONSUMPTION_CAP target to mapped feeder circuit when active
      Compat->>Compat: Update circuit capacity and trigger rebalance when the effective value changes
      Domain->>Scheduler: Schedule block-boundary and expiry refresh events
      Scheduler->>Domain: Evaluate lifecycle at boundary or expiry
      Domain->>Compat: Recompute projection or restore baseline
      Note over Compat: Rebalance-time get_effective_circuit_capacity may reconcile drift for now but must not trigger another rebalance

    Event Dictionary¶

    Event Trigger Key Payload Downstream Trigger
    microgrid.topology_updated Topology mutation accepted. microgrid_id, version, updated_by. Refresh status projections and UI tree models.
    microgrid.node_limit_updated Baseline node-limit record updated. microgrid_id, node_limit_id, node_id, constraint_type. Re-evaluate pending cycles and status summaries.
    microgrid.capability_control_point_updated Capability control-point record updated. microgrid_id, control_point_id, node_id, capability_type, state, control_source. Refresh capability config views and policy projections.
    microgrid.capability_status.recorded Capability status stored as a domain event. microgrid_id, control_point_id, node_id, capability_type, operational_status, source_event_ref, observed_at. Reconstruct latest capability status read models and support audit/history views.
    microgrid.operating_envelope_received Operating envelope accepted. envelope_id, microgrid_id, origin_control_point_id, node_id, constraint_type, effective_from, effective_to. Update active-envelope views and balancing inputs.
    microgrid.operating_envelope_lifecycle_evaluated Operating envelope reaches a scheduled boundary, expires, or is withdrawn. envelope_id, microgrid_id, origin_control_point_id, node_id, status, evaluated_at. Update active-envelope views and effective-capacity evaluation inputs.
    compatibility.effective_circuit_capacity_changed Effective feeder-circuit capacity changes after envelope receipt, withdrawal, or scheduled lifecycle evaluation for a managed GRID_CONNECTION node. microgrid_id, node_id, circuit_id, effective_capacity_watts, projection_trigger. Rebalance legacy load-balancing path and refresh operator views.
    compatibility.effective_circuit_capacity_reconciled Effective feeder-circuit capacity is corrected during synchronous get_effective_circuit_capacity reconciliation for a managed GRID_CONNECTION node. microgrid_id, node_id, circuit_id, effective_capacity_watts, projection_trigger. Refresh operator views and compatibility observability only.
    microgrid.rebalance_requested Rebalance command accepted (HTTP/scheduler/alias). microgrid_id, node_id, source, correlation_id. Start balancing-cycle execution.
    microgrid.demand_resolved Demand resolution step completed. microgrid_id, source_mode, inputs_used. Constraint evaluation policy execution.
    microgrid.constraint_breach_detected Any active policy breach detected. microgrid_id, node_id, reason_code, resolved_limit_watts. Curtailment policy and operator alerting.
    microgrid.cycle_completed Cycle reaches final state. cycle_id, outcome, reason_codes, allocation_summary. UI updates, audit trails, and analytics.
    compatibility.circuit_alias_applied Legacy circuit request translated. circuit_id, microgrid_id, node_id, path. Compatibility observability.

    5. Requirements and Constraints¶

    Functional Requirements¶

    • FR-001: System must execute load balancing at the microgrid boundary, with optional subtree scope where a specific node boundary is required.
    • FR-002: System must support hierarchical nodes with cycle-safe and orphan-safe topology edits.
    • FR-003: System must enforce node limits and aggregate microgrid limits in the same balancing cycle.
    • FR-004: System must compute effective demand using measured-first, derived fallback behavior.
    • FR-005: System must validate all active limits before allocation apply.
    • FR-006: System must publish breach and cycle-summary visibility for operators.
    • FR-007: System must provide tree-based topology configuration and status visibility for nodes and their linked source assets.
    • FR-008: System must preserve compatibility with circuit-centric integrations through explicit alias translation and projection policy.
    • FR-009: Public contracts must use microgrid_id as the primary identifier.
    • FR-010: Source-domain assets must be represented by node-linked asset references and not as topology parents outside the node tree.
    • FR-011: Topology mutation APIs must enforce optimistic concurrency via topology version.
    • FR-012: Cycle outputs must include deterministically ordered reason codes.
    • FR-013: System must define capability types including load balancing, peak shaving, DER, and optimization.
    • FR-014: Runtime enforcement in this design must be limited to load balancing and hierarchical limits.
    • FR-015: Legacy circuit_id requests/events must translate to exactly one microgrid cycle.
    • FR-016: Alias translation failures must return explicit reason codes and auditable records.
    • FR-017: Depot simulator must support microgrid-node topology, policy, and degraded telemetry scenarios for system-level testing.
    • FR-018: System must support two access patterns: physical topology view and operational collection view.
    • FR-019: Collection-view optimization outputs must be validated against physical node-limit constraints before apply.
    • FR-020: System must separate capability configuration (CapabilityControlPoint) from runtime status contracts (CapabilityStatusEvent and CapabilityStatusProjection) in public interfaces.
    • FR-021: System must ingest and expose external runtime capability status for externally controlled capabilities.
    • FR-022: schedule_ref in capability control points is valid only when control_source=LOCAL.
    • FR-023: Capability status events must reference capability control points (CapabilityStatusEvent -> CapabilityControlPoint) for referential integrity.
    • FR-024: Runtime capability status must be persisted as an append-only history stream of immutable status events.
    • FR-025: System must expose a derived latest capability status read model for low-latency UI status-card reads.
    • FR-026: System must provide a protocol-agnostic OperatingEnvelope write/read contract keyed by microgrid_id + node_id for externally sourced constraints.
    • FR-027: Active operating envelopes must be validated and applied as node-scoped effective constraints during balancing and status evaluation.
    • FR-028: System must synchronously resolve effective feeder-circuit capacity through get_effective_circuit_capacity before rebalance-time TOU and allocation logic run.
    • FR-029: An active CONSUMPTION_CAP operating envelope for a managed GRID_CONNECTION node must project to exactly one mapped feeder circuit.
    • FR-030: When the primary forecast source is stale or offline, system must use a valid fallback forecast if one is active, otherwise circuit fail-safe capacity.
    • FR-031: When the primary forecast source is healthy but there is no active primary forecast value for now, system must apply the configured gap policy.
    • FR-032: Operating-envelope lifecycle transitions must be evaluated by scheduled boundary processing rather than read-time mutation.
    • FR-033: Operator reads must expose active operating envelopes and effective feeder-circuit capacity for managed nodes.

    Non-Functional Requirements¶

    • NFR-001: Balancing outcomes must be deterministic for identical inputs and topology version.
    • NFR-002: Enforcement must continue under partial telemetry when fallback policy conditions are met.
    • NFR-003: Breaches and cycle outcomes must be auditable with actor/source and timestamps.
    • NFR-004: Uncertain states must fail safe toward lower allowable allocation.
    • NFR-005: Compatibility translation behavior must be observable and idempotent per request.
    • NFR-006: Compatibility behavior must follow published reason-code governance and keep Microgrid as the source of truth.
    • NFR-007: Simulator scenarios must be reproducible and deterministic for regression runs.
    • NFR-008: Capability runtime status must be timestamped and freshness-visible for operational use.
    • NFR-009: Capability status-event ingest must support idempotency and deterministic projection behavior under duplicate/replayed inputs.
    • NFR-010: Operating-envelope ingest must be auditable and idempotent by source reference.
    • NFR-011: Scheduled operating-envelope lifecycle evaluation must be deterministic for identical envelope blocks and scheduled timestamps.

    Constraints and Assumptions¶

    • A-001: Supported cardinality is 1 depot = 1 microgrid.
    • A-002: The primary contract key is microgrid_id; circuit_id is a compatibility alias only.
    • A-003: Topology is an electrical tree of MicrogridNode records with node-linked source assets, not a fully generic arbitrary graph.
    • A-004: Only node entities carry enforceable physical-limit constraints.
    • A-005: Capability taxonomy is comprehensive, but the enforced runtime scope in this design is load balancing and hierarchical limits. Other capability types are status-visible placeholders.
    • A-006: This specification defines domain contracts while leaving storage, framework wiring, and deployment details out of scope.

    6. Interaction and Flow¶

    User Journey¶

    1. Operator configures topology and node limit policies for one microgrid and submits with the supplied topology version.
    2. System validates structural and policy invariants.
    3. Scheduler or operator requests rebalance for the microgrid.
    4. System resolves effective demand, evaluates constraints, and determines feasible outcome.
    5. System applies allocation or curtailment/rejection and returns deterministic reason codes.
    6. System publishes cycle summary, breaches, and compatibility telemetry (if alias path used).
    7. If operating-envelope or fallback-policy evaluation affects a managed GRID_CONNECTION node, envelope-change and scheduled lifecycle paths may project a new effective feeder-circuit capacity and trigger the legacy rebalance seam, while rebalance-time get_effective_circuit_capacity only reconciles drift for correctness and must not trigger another rebalance.

    Sequence Diagram: Rebalance with Compatibility Alias¶

    sequenceDiagram
      participant Client as Legacy or Microgrid Client
      participant API as Manage Core API
      participant Alias as Compatibility Adapter
      participant Domain as Microgrid Domain
      participant Alloc as Allocation Engine
      participant Audit as Event/Audit Stream
    
      Client->>API: POST /api/circuit/{circuit_id}/rebalance_load
      API->>Alias: Resolve circuit_id -> microgrid_id
      Alias-->>API: microgrid_id + alias_metadata
      API->>Domain: Request rebalance(microgrid_id)
      Domain->>Alloc: Evaluate demand + constraints + allocation
      Alloc-->>Domain: outcome + reason_codes + summaries
      Domain->>Audit: Publish cycle_completed + alias_applied (if used)
      Domain-->>API: cycle_result
      API-->>Client: 200 with mapped identifiers and reason codes

    Flowchart: Topology Update Guardrails¶

    flowchart TD
      A[Topology Update Request] --> B{Version matches?}
      B -->|No| C[409 TOPOLOGY_VERSION_CONFLICT]
      B -->|Yes| D{Cycle/Orphan Safe?}
      D -->|No| E[422 TOPOLOGY_INVALID]
      D -->|Yes| F[Apply Topology Version +1]
      F --> G[Publish microgrid.topology_updated]

    7. Design Extensibility¶

    • One microgrid may contain multiple GRID_CONNECTION child nodes and multiple independently managed scopes without changing the microgrid_id boundary defined here.
    • Capability taxonomy is intentionally broader than the enforced runtime scope in this design, so PEAK_SHAVING, DER, and ENERGY_OPTIMISATION can become enforced later without reshaping topology contracts.
    • Circuit-centric compatibility paths are removable adapters rather than part of the Microgrid ownership model.
    • Storage schema, framework wiring, and deployment topology remain implementation concerns outside this system-design document.

    8. Appendix A: Compatibility Reason Codes¶

    Reason Code Meaning
    CIRCUIT_ALIAS_NOT_RESOLVABLE Legacy circuit identifier did not map to exactly one microgrid.
    LIMIT_SCOPE_TRANSLATION_FAILED Legacy policy scope could not be translated to the Microgrid or node target defined by this model.
    LEGACY_POLICY_SCOPE_AMBIGUOUS Legacy limit target maps to multiple possible Microgrid or node scopes.
    TOPOLOGY_INVALID Active topology violates the tree constraints defined by this model.
    TELEMETRY_STALE_FALLBACK_USED Cycle executed using deterministic fallback demand due to stale telemetry.
    Made with Material for MkDocs