Skip to Content
Developer DocsServicesCompliance Monitor

Compliance Monitor

This service currently implements the RRC oil & gas vertical and is not yet packified. The surrounding runtime is domain-neutral; RRC is the first installed vertical.

The Compliance Monitor tracks regulatory deadlines, detects rule changes, monitors production data for violations, and computes risk scores for wells across an operator’s portfolio. It queries the knowledge graph service for entity data and applies domain-specific compliance logic.

Unlike the compliance dashboard and workspace surfaces (which the orchestration engine serves from installable packs), this monitor still hardcodes RRC oil & gas logic — deadline windows, GOR/allowable checks, R-32 flaring exposure. It has not been packified; its thresholds are config-keyed (E0.5) but its check logic is domain-specific Python.

Overview

Oil and gas operators must track dozens of regulatory deadlines, production allowables, and evolving rules. The compliance monitor provides four capabilities:

  1. Deadline tracking — Scans permits, flaring authorizations, and filing deadlines for approaching or expired dates, categorizing alerts as critical, warning, or informational
  2. Production monitoring — Checks well production data against allowable limits, flags gas-oil ratio (GOR) anomalies, identifies zero-production active wells, and detects unauthorized flaring
  3. Rule change detection — Maps recent statewide and field-specific rule changes to affected wells and operations
  4. Risk scoring — Computes a 0-100 compliance risk score per well based on deadline proximity, active issues, violation history, and flaring exposure, then ranks the portfolio

The service also provides a portfolio dashboard endpoint that aggregates all four capabilities for a given operator.

Port & Language

PropertyValue
Port8006
LanguagePython 3.12
FrameworkFastAPI
Entry pointsrc/compliance/main.py

Key Endpoints

All /compliance/* routes require perimeter-stamped identity (aegis_shared.auth.get_current_user, R42d; mode-gated by AEGIS_AUTH_MODE).

MethodPathDescription
POST/compliance/deadlinesScan permits, authorizations, and filings for approaching deadlines.
POST/compliance/productionCheck production data for allowable exceedances and anomalies.
POST/compliance/rule-changesDetect rule changes affecting the given wells.
POST/compliance/risk-scoreRisk-rank wells based on compliance factors.
GET/compliance/dashboard/{operator_id}Full portfolio compliance dashboard for an operator.
GET/healthHealth check.

Architecture

Module Breakdown

src/compliance/ ├── main.py # FastAPI app, endpoint definitions, dashboard aggregation ├── config.py # Settings from environment variables ├── deadlines.py # Deadline scanning logic ├── production.py # Production compliance checking ├── rule_changes.py # Rule change detection └── risk_scoring.py # Risk scoring algorithm

Deadline Tracking (deadlines.py)

The scan_deadlines function processes three types of items:

Item TypeChecked FieldAlert Context
Permitsexpiration_datePermit type, permit number
Flaring authorizationsexpiration_dateR-32 authorization number, renewal urgency
Filingsdue_date or filed_dateFiling type, form number

Alert thresholds (configurable):

ThresholdDefaultAlert Level
Expired (days < 0)critical
Critical7 dayscritical
Warning14 dayswarning
Info30 daysinfo

Alerts are sorted by days remaining (most urgent first). The response includes aggregate counts of critical and warning alerts.

Production Monitoring (production.py)

The check_production_compliance function evaluates each well against four checks:

CheckConditionSeverity
Allowable exceedanceOil production exceeds allowable by more than 5%critical
GOR anomalyGas-oil ratio exceeds 2,000 MCF/BBLwarning
Zero productionActive well reporting zero oil and gas productionwarning
Unauthorized flaringFlaring volume > 0 without an active R-32 authorizationcritical

Rule Change Detection (rule_changes.py)

The rule registry is read from the rule_versions table (the shared source of truth, seeded by orchestration’s seed_rules.py) — one entry per latest active rule version. Each rule change is matched against wells based on:

  • Well type match: Does the rule declare applies_to well types in its rule_data? (Empty/absent = applies to all well types.)
  • Field match: Does the rule target a specific field (rule_data.field_number)? (If no field restriction, all wells match.)

If the table is missing or the database is unreachable, the endpoint returns an empty registry with a warning — it never fabricates demo rule changes. The legacy simulated registry (Rule 32 amendment / Spraberry amendment / EPA OOOOb) is kept for demos and tests behind the explicit COMPLIANCE_MOCK_RULE_CHANGES env flag.

Risk Scoring (risk_scoring.py)

The score_well_risk function computes a 0-100 risk score across four weighted factors:

FactorMax PointsScoring
Deadline proximity2525 = expired, 20 = critical, 10 = warning, 0 = clear
Active issues258 points per production issue (capped at 25)
Violation history2510 points per past violation (capped at 25)
Flaring exposure2525 = exceeded auth, 15 = approaching (80%+), 5 = active

Risk levels:

Score RangeLevel
70-100HIGH
40-69MEDIUM
1-39LOW
0MINIMAL

The score_portfolio function scores all wells, sorts by risk (descending), and returns distribution statistics.

Portfolio Dashboard

The GET /compliance/dashboard/{operator_id} endpoint aggregates all four capabilities:

  1. Fetch data from the knowledge graph service via Cypher queries:
    • Wells operated by the operator
    • Permits associated with the operator
    • Flaring authorizations on the operator’s leases
  2. Run all checks: deadlines, rule changes, production compliance, risk scoring
  3. Return summary with counts, alerts, and risk distribution
{ "operator_id": "op-permian-01", "summary": { "total_wells": 12, "total_permits": 5, "total_flaring_auths": 3, "critical_alerts": 2, "warning_alerts": 4, "average_risk_score": 35.2 }, "deadlines": { ... }, "rule_changes": { ... }, "production": { ... }, "risk_scores": { ... } }

Dependencies

Python Packages

PackageVersionPurpose
fastapi^0.115Web framework
uvicorn^0.34ASGI server
asyncpg^0.29PostgreSQL async driver
httpx^0.28HTTP client for knowledge graph queries
aegis-sharedlocalShared models and DB helpers

Service Dependencies

ServiceProtocolPurpose
Knowledge Graph Service (8003)HTTPCypher queries for operator wells, permits, authorizations

Configuration

Environment VariableDefaultDescription
COMPLIANCE_HOST0.0.0.0Bind address
COMPLIANCE_PORT8006Bind port
DATABASE_URLpostgresql://aegis:aegis_local@localhost:5432/aegisPostgreSQL connection
KNOWLEDGE_GRAPH_SERVICE_URLhttp://localhost:8003Knowledge graph service URL
DB_SCHEMAag_catalogDatabase schema prefix
COMPLIANCE_MOCK_RULE_CHANGESunsetServe the simulated rule-change registry instead of rule_versions (demo/tests only)

Config-keyed thresholds (E0.5): the runtime values are resolved from the rule_versions table (compliance/rule_params.py, latest active row per rule_identifier overlaid on defaults — same posture as orchestration’s resolve_rule_params). The constants in config.py are the fallback floor when the table is missing, empty, or unreachable:

Rule identifierKeysFloor (in config.py)
monitor_deadline_windowscritical_days / warning_days / info_days7 / 14 / 30 days
monitor_production_thresholdsgor_threshold_mcf_per_bbl / allowable_tolerance_pct2,000 MCF/BBL / 5%
monitor_risk_scoringhigh_score_threshold / medium_score_threshold / flaring_exceeded_pct / flaring_approaching_pct70 / 40 / 100% / 80%

No rows are seeded for these identifiers today, so the floors govern until an operator creates an active rule_versions row (which then wins without a code change).

Running Locally

cd services/compliance-monitor poetry install poetry run uvicorn compliance.main:app --reload --port 8006

The compliance monitor depends on the knowledge graph service for the dashboard endpoint. The individual check endpoints (/compliance/deadlines, /compliance/production, etc.) accept data directly in the request body and do not require the knowledge graph service.

Last updated on