# DSL

#### Appendix E. Policy DSL, Playbook DSL, Agent DSL – Grammar Sketches

This appendix provides **illustrative grammar sketches** for three core domain-specific languages (DSLs) in the Nexus Ecosystem:

* **Policy DSL** — for encoding access, residency, safety, GeoGuard and lawful-basis constraints.
* **Playbook DSL** — for encoding Anticipatory Action Plans (AAPs) and Incident Response Playbooks (IRPs).
* **Agent DSL** — for declaring the capabilities, safety envelopes, and governance hooks for agents and swarms.

All grammars are intentionally **minimal and didactic**. Production specifications are defined in NXSS and may use full EBNF, JSON Schema, and SHACL constraints.

***

### E.1 Common Design Principles

Across all three DSLs:

1. **Declarative, not imperative**
   * The DSLs express *what* must be true or *what* must happen, rather than low-level “how” details.
   * NXSOS, NXSTUDIO and NXFOUNDRY are responsible for compilation and orchestration.
2. **Composable and type-safe**
   * DSLs are **typed** (e.g., entity types, SDZ classes, safety tiers).
   * Expressions are **composable**, enabling reuse across rails and packs.
3. **Semantically anchored**
   * All identifiers (entities, indices, AEPs, roles) reference **GRIx ontologies**, NXSS vocabularies, and NXIdentity roles.
   * This yields machine-verifiable constraints and playbooks.
4. **HIL-first for high-impact actions**
   * Human-in-the-loop (HIL) is first-class: most impactful actions require explicit NVM/HIL gates.
5. **Multi-level governance aware**
   * Policies, playbooks, and agents can be scoped to:
     * Rail (NXSR)
     * Pack (NXPCK)
     * Institution / Node / Agent

***

### E.2 Policy DSL – Grammar Sketch

The **Policy DSL** encodes constraints over **data, actions, actors, and geography**. It is evaluated by `nxproto.trust-engine` and the **Zero-Trust, Privacy, GeoGuard, and AI Safety Fabrics**.

#### E.2.1 Conceptual Model

A *policy bundle* consists of:

* **Targets** — what the policy applies to (data domains, actions, agents, rails).
* **Conditions** — predicate over attributes (who, where, when, SDZ, EQL/CL, safety tier, etc.).
* **Effects** — `allow`, `deny`, `require_hil`, `escalate`, `mask`, `transform`, etc.
* **Justification** — mapping to legal bases, standards, and risk rationale.

#### E.2.2 Micro-EBNF Sketch

```ebnf
PolicyBundle   ::= "policy_bundle" ID "{" PolicyRule* "}"
PolicyRule     ::= "rule" ID "{" TargetBlock ConditionBlock EffectBlock [MetaBlock] "}"

TargetBlock    ::= "target" "{" TargetItem+ "}"
TargetItem     ::= ("rail" ":" ID)
                 | ("pack" ":" ID)
                 | ("action_type" ":" ID)
                 | ("data_domain" ":" ID)
                 | ("agent_type" ":" ID)
                 | ("node_class" ":" ID)

ConditionBlock ::= "when" "{" Expr "}"
Expr           ::= OrExpr
OrExpr         ::= AndExpr ("or" AndExpr)*
AndExpr        ::= NotExpr ("and" NotExpr)*
NotExpr        ::= ["not"] PrimaryExpr
PrimaryExpr    ::= Comparison
                 | "(" Expr ")"

Comparison     ::= Identifier Comparator Value
Comparator     ::= "==" | "!=" | ">" | "<" | ">=" | "<=" | "in" | "matches"
Identifier     ::= ID ("." ID)*
Value          ::= STRING | NUMBER | BOOL | "[" Value ("," Value)* "]"

EffectBlock    ::= "then" "{" EffectStmt+ "}"
EffectStmt     ::= "allow"
                 | "deny"
                 | "require_hil" ["for" RoleList]
                 | "escalate_to" RoleList
                 | "mask_fields" ":" "[" FieldList "]"
                 | "apply_transform" ":" ID
                 | "set_safety_tier" ":" ID

RoleList       ::= ID ("," ID)*
FieldList      ::= ID ("," ID)*

MetaBlock      ::= "meta" "{" MetaStmt* "}"
MetaStmt       ::= "lawful_basis" ":" ID
                 | "reference" ":" STRING
                 | "rationale" ":" STRING
                 | "sdz_class" ":" ID
                 | "policy_id" ":" STRING
```

#### E.2.3 Example: Data Residency & GeoGuard Policy

```yaml
policy_bundle geo_residency_v1:

  rule drought_household_data_residency {
    target {
      rail: nxsr.eaf.drought-food.v1
      data_domain: grix_drought_food.HouseholdLivelihoodUnit
    }

    when {
      request.context.actor_jurisdiction != resource.context.jurisdiction
      and resource.attributes.sdz_class == "sdz.sov.national"
    }

    then {
      deny
    }

    meta {
      lawful_basis: "dp.local_residency_requirement"
      rationale: "Household-level data must not leave sovereign SDZ."
      reference: "Nat. Data Protection Act §12"
    }
  }

  rule drought_index_cross_border_access {
    target {
      rail: nxsr.eaf.drought-food.v1
      data_domain: grix_drought_food.FoodSecurityIndex
    }

    when {
      request.context.role in ["DFI_ANALYST", "MULTILATERAL_ANALYST"]
      and request.context.purpose == "macro_fiscal_risk"
    }

    then {
      allow
      mask_fields: [ "admin_unit_id" ]
    }

    meta {
      lawful_basis: "public_interest"
      rationale: "Share aggregated indices for macro-fiscal risk; remove identifying geography below admin2."
    }
  }
```

#### E.2.4 Example: AI Safety Tier Policy

```yaml
policy_bundle ai_safety_v2:

  rule high_impact_agent_requires_hil {
    target {
      agent_type: "operations_agent"
      action_type: "critical_infra_actuation"
    }

    when {
      agent.safety_tier in ["tier3", "tier4"]
      and action.target_system_type in ["power_grid", "water_network", "health_system"]
    }

    then {
      require_hil for [ "GRID_OPERATOR", "SAFETY_OFFICER" ]
      escalate_to [ "RAIL_SAFETY_COMMITTEE" ]
    }

    meta {
      rationale: "No autonomous actuation on critical infrastructure at safety tier ≥3."
      reference: "NXSS.AI-SAFETY-001"
    }
  }
```

***

### E.3 Playbook DSL – Grammar Sketch

The **Playbook DSL** encodes **Anticipatory Action Plans (AAPs)** and **Incident Response Playbooks (IRPs)** as *guarded, composable workflows* driven by indices, alerts, and AEPs.

#### E.3.1 Conceptual Model

A playbook is a **directed graph** of steps, each with:

* **Trigger conditions** — when to consider the playbook or step active.
* **Roles and responsibilities** — who executes or approves.
* **Actions** — invoke operations, send alerts, allocate resources, adjust indices, etc.
* **Guards** — safety checks, NVM gates, lawful-basis checks.
* **Outcomes and metrics** — what success looks like, what to log.

Playbooks are compiled into **workflow specifications** for NEXQ and NXSTUDIO, and exposed via NXAPP.

#### E.3.2 Micro-EBNF Sketch

```ebnf
Playbook       ::= "playbook" ID "{" HeaderBlock StepBlock+ "}"
HeaderBlock    ::= "meta" "{" MetaField* "}"
MetaField      ::= "type" ":" ("AAP" | "IRP")
                 | "domain" ":" ID
                 | "nrm_profile_id" ":" ID
                 | "valid_from" ":" DATETIME
                 | "valid_until" ":" DATETIME
                 | "owner_role" ":" ID
                 | "description" ":" STRING

StepBlock      ::= "step" ID "{" TriggerBlock RoleBlock ActionBlock [GuardBlock] [NextBlock] "}"

TriggerBlock   ::= "on" "{" TriggerExpr+ "}"
TriggerExpr    ::= "index" ":" ID ConditionExpr
                 | "alert" ":" ID
                 | "episode_type" ":" ID
                 | "manual_activation" ":" BOOL

RoleBlock      ::= "roles" "{" RoleAssignment+ "}"
RoleAssignment ::= "role" ":" ID [ "as" ID ]

ActionBlock    ::= "do" "{" ActionStmt+ "}"
ActionStmt     ::= "notify" ":" ChannelSpec
                 | "invoke" ":" OperationSpec
                 | "allocate_resource" ":" ResourceSpec
                 | "update_state" ":" StateSpec
                 | "log_event" ":" STRING

GuardBlock     ::= "guards" "{" GuardStmt+ "}"
GuardStmt      ::= "require_hil" ":" RoleList
                 | "require_nvm_quorum" ":" ID
                 | "check_policy" ":" ID
                 | "check_safety_tier" ":" ID

NextBlock      ::= "next" "{" Transition+ "}"
Transition     ::= "on" ConditionExpr "goto" ID
                 | "goto" ID

ConditionExpr  ::= "if" Expr
Expr           ::= (as in Policy DSL)
```

#### E.3.3 Example: Anticipatory Cash Transfer AAP

```yaml
playbook aap.drought_cash_preposition.v1 {

  meta {
    type: AAP
    domain: "drought_food"
    nrm_profile_id: "nrm.drought.food.household"
    valid_from: "2026-01-01T00:00:00Z"
    valid_until: "2030-12-31T23:59:59Z"
    owner_role: "NDMA_COORDINATOR"
    description: "Anticipatory cash transfers to vulnerable households ahead of severe drought."
  }

  step assess_trigger {
    on {
      index: idx.eaf.spi.seasonal.v3 if value < -1.5
      index: idx.eaf.food_insecurity_rate.v2 if value > 0.12
    }

    roles {
      role: "NDMA_ANALYST"
      role: "NCC_MODELLER"
    }

    do {
      invoke: "generate_pre_trigger_aep(nrm_profile_id='nrm.drought.food.household')"
      log_event: "Pre-trigger AEP generated for anticipatory action."
    }

    guards {
      check_policy: "policy_bundle.geo_residency_v1"
    }

    next {
      goto review_pre_trigger
    }
  }

  step review_pre_trigger {
    on {
      manual_activation: true
    }

    roles {
      role: "NDMA_COORDINATOR"
      role: "COMMUNITY_REP"
      role: "TREASURY_OBSERVER"
    }

    do {
      notify: "channel:ndma_internal"
      notify: "channel:community_council"
    }

    guards {
      require_hil: ["NDMA_COORDINATOR", "COMMUNITY_REP"]
    }

    next {
      on if decision == "approve" goto prepare_distribution
      on if decision == "reject" goto terminate
    }
  }

  step prepare_distribution {
    on {
      manual_activation: true
    }

    roles {
      role: "PAYMENT_OPERATOR"
      role: "NGO_PARTNER"
    }

    do {
      invoke: "compile_beneficiary_list(criteria='high_vulnerability')"
      allocate_resource: "cash_prepositioning(amount='to_be_determined')"
      log_event: "Beneficiary list and prepositioning prepared."
    }

    guards {
      check_policy: "policy_bundle.dp.cash_targets_v1"
    }

    next {
      goto execute_transfers
    }
  }

  step execute_transfers {
    on {
      alert: "ew.drought.phase2"
    }

    roles {
      role: "PAYMENT_OPERATOR"
      role: "COMMUNITY_REP"
    }

    do {
      invoke: "execute_cash_transfers(batch_id='auto')"
      log_event: "Anticipatory transfers executed."
    }

    guards {
      require_nvm_quorum: "nvm.3of6.gov-fin-community.v1"
    }

    next {
      goto after_action_review
    }
  }

  step after_action_review {
    on {
      episode_type: "shock"
    }

    roles {
      role: "NCC_EVALUATOR"
      role: "COMMUNITY_REP"
    }

    do {
      invoke: "compute_outcome_metrics(episode_id=current_episode)"
      log_event: "After-action review complete; metrics updated."
    }

    next {
      goto terminate
    }
  }

  step terminate {
    on {
      manual_activation: true
    }

    roles {
      role: "NDMA_COORDINATOR"
    }

    do {
      log_event: "Playbook completed."
    }
  }
}
```

***

### E.4 Agent DSL – Grammar Sketch

The **Agent DSL** declares **agent capabilities, safety parameters, and governance hooks**. It is interpreted by:

* NXSOS (`nxproto.trust-engine`, **agent safety fabric**),
* NXSTUDIO (binding to operations, data, and ontologies), and
* NXFOUNDRY (for testing and red-teaming).

#### E.4.1 Conceptual Model

Each agent is defined by:

* **Type** — `data_agent`, `operations_agent`, `policy_agent`, `composite_agent`.
* **Context** — which rails, packs, ontologies it can “see.”
* **Capabilities** — which operations it can perform (queries, actions, recommendations).
* **Safety tier & constraints** — what it is *allowed* to do, where HIL/NVM is mandatory.
* **Governance hooks** — logging, audit, escalation, and override mechanisms.

#### E.4.2 Micro-EBNF Sketch

```ebnf
AgentSpec      ::= "agent" ID "{" AgentHeader CapabilitiesBlock SafetyBlock GovernanceBlock "}"

AgentHeader    ::= "meta" "{" MetaField* "}"
MetaField      ::= "type" ":" ("data_agent" | "operations_agent" | "policy_agent" | "composite_agent")
                 | "domain" ":" ID
                 | "rail_scope" ":" ID | "rail_scope" ":" "[" ID ("," ID)* "]"
                 | "pack_scope" ":" "[" ID ("," ID)* "]"
                 | "safety_tier" ":" ID
                 | "description" ":" STRING

CapabilitiesBlock ::= "capabilities" "{" CapabilityStmt+ "}"
CapabilityStmt  ::= "query" ":" QueryCapability
                 | "act" ":" ActionCapability
                 | "advise" ":" AdviceCapability

QueryCapability ::= "on_entities" ":" "[" ID ("," ID)* "]"
                    [ "filters" ":" FilterExpr ]
                    [ "max_frequency" ":" DURATION ]

ActionCapability ::= "operation" ":" ID
                     [ "on_entities" ":" "[" ID ("," ID)* "]" ]
                     [ "requires_hil" ":" BOOL ]

AdviceCapability ::= "policy_area" ":" ID
                     [ "nr m_profile_id" ":" ID ]

SafetyBlock     ::= "safety" "{" SafetyStmt+ "}"
SafetyStmt      ::= "disallowed_actions" ":" "[" ID ("," ID)* "]"
                 | "max_impact_level" ":" ID
                 | "requires_nvm_for" ":" "[" ID ("," ID)* "]"
                 | "policy_bundles" ":" "[" ID ("," ID)* "]"

GovernanceBlock ::= "governance" "{" GovernanceStmt+ "}"
GovernanceStmt  ::= "log_level" ":" ID
                 | "audit_trail" ":" BOOL
                 | "escalate_to" ":" "[" ID ("," ID)* "]"
                 | "feedback_channel" ":" ID

FilterExpr      ::= (as in Policy DSL Expr)
```

#### E.4.3 Example: Data Agent (Virtual Analyst)

```yaml
agent agent.drought_data_analyst.v1 {

  meta {
    type: data_agent
    domain: "drought_food"
    rail_scope: [ "nxsr.eaf.drought-food.v1" ]
    pack_scope: [ "nrmpck.drought-food.v1" ]
    safety_tier: "tier1"
    description: "Virtual analyst that answers drought and food security queries using AEPs and indices."
  }

  capabilities {
    query: {
      on_entities: [
        "grix_drought_food.DroughtEvent",
        "grix_drought_food.FoodSecurityIndex",
        "grix_drought_food.DroughtImpactRecord"
      ]
      filters: (chronotope.spatial_reference_type == "admin_unit")
      max_frequency: "PT5S"
    }
  }

  safety {
    disallowed_actions: ["critical_infra_actuation", "capital_trigger"]
    max_impact_level: "low"
    policy_bundles: ["policy_bundle.geo_residency_v1", "policy_bundle.ai_safety_v2"]
  }

  governance {
    log_level: "detailed"
    audit_trail: true
    feedback_channel: "teams://ndma_analytics_channel"
  }
}
```

#### E.4.4 Example: Operations Agent (Virtual Ops Team Member)

```yaml
agent agent.runway_operations.v1 {

  meta {
    type: operations_agent
    domain: "coastal_urban"
    rail_scope: [ "nxsr.eu.coastal-urban.v1" ]
    pack_scope: [ "nrmpck.coastal-flood-infra.v1" ]
    safety_tier: "tier3"
    description: "Operations agent assisting airport operations with runway risk management."
  }

  capabilities {
    query: {
      on_entities: [ "cu.CoastalFloodEvent", "cu.CriticalInfrastructureNode" ]
      filters: (entity.infra_type == "runway")
      max_frequency: "PT10S"
    }

    act: {
      operation: "schedule_runway_inspection"
      on_entities: [ "cu.CriticalInfrastructureNode" ]
      requires_hil: false
    }

    act: {
      operation: "temporarily_close_runway"
      on_entities: [ "cu.CriticalInfrastructureNode" ]
      requires_hil: true
    }

    advise: {
      policy_area: "airport_disruption_mitigation"
      nrm_profile_id: "nrm.coastal.urban.airport"
    }
  }

  safety {
    disallowed_actions: [
      "permanent_infrastructure_shutdown"
    ]
    max_impact_level: "medium"
    requires_nvm_for: [
      "temporarily_close_runway"
    ]
    policy_bundles: [
      "policy_bundle.ai_safety_runway_v1",
      "policy_bundle.geo_residency_v1"
    ]
  }

  governance {
    log_level: "detailed"
    audit_trail: true
    escalate_to: [ "AIRPORT_OPS_MANAGER", "RAIL_SAFETY_COMMITTEE" ]
    feedback_channel: "teams://airport_ops_channel"
  }
}
```

#### E.4.5 Example: Policy Agent (Virtual Policy Advisor)

```yaml
agent agent.climate_macro_policy_advisor.v1 {

  meta {
    type: policy_agent
    domain: "climate_macro"
    rail_scope: [ "nxsr.global.climate-macro.v1" ]
    pack_scope: [ "nrmpck.climate-macro-fiscal.v1" ]
    safety_tier: "tier2"
    description: "Advises ministries of finance and central banks on climate–macro stress scenarios."
  }

  capabilities {
    query: {
      on_entities: [
        "grix.HazardEvent",
        "grix.Index",
        "grix.Decision",
        "grix.ImpactRecord"
      ]
      filters: (index.index_type == "systemic_stress")
      max_frequency: "PT1H"
    }

    advise: {
      policy_area: "macro_fiscal_risk"
      nrm_profile_id: "nrm.climate.macro.sovereign"
    }
  }

  safety {
    max_impact_level: "high"
    requires_nvm_for: [
      "recommend_capital_trigger",
      "recommend_new_debt_instrument"
    ]
    policy_bundles: [
      "policy_bundle.climate_macro_policy_v1",
      "policy_bundle.ai_safety_v2"
    ]
  }

  governance {
    log_level: "summary"
    audit_trail: true
    escalate_to: [ "TREASURY_POLICY_COMMITTEE", "CENTRAL_BANK_STABILITY_COMMITTEE" ]
    feedback_channel: "teams://macro_policy_group"
  }
}
```

***

In combination, the **Policy DSL**, **Playbook DSL**, and **Agent DSL** provide the **formal language layer** through which:

* **Constraints** (legal, normative, safety) are encoded and enforced.
* **Operational workflows** (AAPs/IRPs) are specified and versioned.
* **Agents and swarms** are declared, governed, and audited.

They ensure that the Nexus Ecosystem’s technical architecture remains **explainable, governable, and contestable**, even as AI, automation, and systemic complexity increase.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.therisk.global/organization/standardization/nexus-rail/nexus-based-risk-management-nrm/technology/appendices/dsl.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
