Automated Compliance Checking

Build continuous compliance monitoring against SOC 2, GDPR, HIPAA, PCI-DSS, and custom policies.


Architecture

%%{init: {'theme': 'base', 'themeVariables': { 
  'primaryColor': '#6366f1',
  'lineColor': '#94a3b8',
  'fontFamily': 'system-ui, sans-serif'
}}}%%
flowchart TB
    subgraph Policies["📋 Policy Sources"]
        direction LR
        P1["SOC 2"]
        P2["GDPR"]
        P3["HIPAA"]
        P4["Custom"]
    end
    
    subgraph Engine["⚙️ Compliance Engine"]
        direction TB
        KB["Policy KB"]
        Agent["Compliance Agent"]
        KB <--> Agent
    end
    
    subgraph Output["📊 Output"]
        direction LR
        Audit["Audit Trail"]
        Report["Reports"]
        Dash["Dashboard"]
    end
    
    Policies --> Engine --> Output
    
    style Policies fill:#dbeafe,stroke:#3b82f6
    style Engine fill:#f3e8ff,stroke:#9333ea
    style Output fill:#dcfce7,stroke:#22c55e

Step 1: Policy Knowledge Base

Structure your compliance policies for AI retrieval.

Folder Structure

compliance-policies/
├── frameworks/
│   ├── soc2/
│   │   ├── cc6-logical-access.md
│   │   └── cc7-monitoring.md
│   ├── gdpr/
│   │   └── article-25-privacy-by-design.md
│   └── hipaa/
│       └── 164.312-technical-safeguards.md
└── organizational/
    ├── secure-coding.md
    └── data-classification.md

Policy Document Format

# SOC 2 CC6.1 - Logical Access Controls

## Requirements
1. Authentication required for all access
2. MFA for privileged access
3. Password complexity enforcement
4. Session timeout after inactivity

## Violations to Detect
- Hardcoded credentials
- Missing authentication middleware
- Disabled CSRF protection

## Evidence Required
- Authentication config files
- Password policy code
- MFA implementation

Step 2: Compliance Agent

Create an AI agent that evaluates code against policies.

Setting Value
Name Compliance Auditor
KB Compliance Policies
Tools GitHub, Database
You are an expert compliance auditor for SOC 2, GDPR, HIPAA, and PCI-DSS.

For each evaluation:
1. Map code to specific controls
2. Status: COMPLIANT, NON_COMPLIANT, NEEDS_REVIEW
3. Cite exact policy references
4. Provide evidence (file, line, snippet)

Output:
{
  "framework": "SOC2|GDPR|HIPAA",
  "control_id": "CC6.1",
  "status": "COMPLIANT|NON_COMPLIANT|NEEDS_REVIEW",
  "finding": "Description",
  "evidence": {"file": "path", "line": N},
  "remediation": "How to fix",
  "severity": "CRITICAL|HIGH|MEDIUM|LOW"
}

Step 3: PR Validation Workflow

Validate every code change against policies.

%%{init: {'theme': 'base', 'themeVariables': {
  'actorTextColor': '#1e293b',
  'signalColor': '#6366f1'
}}}%%
sequenceDiagram
    participant Dev as Developer
    participant GH as GitHub
    participant WF as Workflow
    participant AI as Compliance Agent

    Dev->>GH: Open PR
    GH->>WF: Webhook
    WF->>GH: Fetch files
    WF->>AI: Evaluate vs policies
    AI-->>WF: Findings
    alt Non-compliant
        WF->>GH: Block PR
    else Compliant
        WF->>GH: Approve
    end

Key Steps

Parse Event
{
  "schemaVersion": "1.0",
  "stepId": "parse-pr",
  "type": "VARIABLE",
  "next": "fetch-files",
  "def": {
    "type": "VARIABLE",
    "vars": {
      "owner": {"expr": "{{input.repository.owner.login}}", "type": "STRING"},
      "repo": {"expr": "{{input.repository.name}}", "type": "STRING"},
      "prNumber": {"expr": "{{input.pull_request.number}}", "type": "NUMBER"}
    }
  }
}
Categorize Files
{
  "schemaVersion": "1.0",
  "stepId": "categorize",
  "type": "FUNCTION",
  "def": {
    "language": "PYTHON",
    "content": "def execute(ctx):\n    files = ctx.steps['fetch-files']['response']['files']\n    return {\n        'code': [f for f in files if f['filename'].endswith(('.js','.ts','.py','.java'))],\n        'config': [f for f in files if f['filename'].endswith(('.yml','.yaml','.json','.tf'))]\n    }"
  }
}
Evaluate Compliance
{
  "schemaVersion": "1.0",
  "stepId": "evaluate",
  "type": "AIAGENT",
  "parent": "code-loop",
  "def": {
    "agentId": "compliance-auditor",
    "input": "Evaluate for compliance:\n\nFile: {{loop.current.item.filename}}\n{{step.fetch-content.response.content | b64decode}}\n\nCheck: SOC2 CC6.1 (auth), GDPR Art.25 (encryption), SOC2 CC7.2 (logging)"
  }
}
Store Audit Record
{
  "schemaVersion": "1.0",
  "stepId": "store-audit",
  "type": "DATABASE",
  "def": {
    "connectionId": "{{connections.compliance-db}}",
    "operation": "EXECUTE",
    "query": "INSERT INTO compliance_audits (repo, pr, sha, findings, status, evaluated_at) VALUES (:repo, :pr, :sha, :findings, :status, NOW())",
    "parameters": {
      "repo": "{{variables.owner}}/{{variables.repo}}",
      "pr": "{{variables.prNumber}}",
      "sha": "{{variables.headSha}}",
      "findings": "{{step.aggregate.findings | tojson}}",
      "status": "{{step.aggregate.non_compliant_count > 0 ? 'FAILED' : 'PASSED'}}"
    }
  }
}

Step 4: Framework Checks

SOC 2 Type II

Control Check In Code
CC6.1 Logical access Auth middleware, RBAC
CC6.6 Network boundaries Firewall rules
CC7.1 Intrusion detection Logging configs
CC7.2 Anomaly detection Alerting

GDPR

Article Requirement Check
Art. 5 Data minimization Unnecessary collection
Art. 17 Right to erasure Delete endpoints
Art. 25 Privacy by design Encryption
Art. 32 Security measures TLS, encryption

HIPAA

Section Safeguard Check
164.308 Admin Access controls
164.312(a) Access Unique IDs, auto-logoff
164.312(b) Audit PHI access logging
164.312(e) Transmission TLS enforcement

Step 5: Evidence Collection

Automated monthly evidence gathering.

{
  "schemaVersion": "1.0",
  "name": "Monthly Evidence",
  "trigger": {"type": "SCHEDULE", "cronExpression": "0 0 1 * *"},
  "beginStepId": "search-auth",
  "steps": {}
}
Search Authentication Evidence
{
  "stepId": "search-auth",
  "type": "CONNECTOR",
  "def": {
    "connectorName": "GitHub",
    "operation": {
      "operationType": "HTTP",
      "operationInput": {
        "baseUrl": "https://api.github.com",
        "query": {"q": "AuthMiddleware OR @RequiresAuth repo:{{input.repo}}"}
      }
    }
  }
}
Store Evidence
{
  "stepId": "store-evidence",
  "type": "DATABASE",
  "def": {
    "connectionId": "{{connections.compliance-db}}",
    "operation": "EXECUTE",
    "query": "INSERT INTO compliance_evidence (control_id, type, content, collected_at, valid_until) VALUES (:ctrl, :type, :content, NOW(), NOW() + INTERVAL '90 days')",
    "parameters": {
      "ctrl": "CC6.1",
      "type": "authentication",
      "content": "{{step.search-auth.response | tojson}}"
    }
  }
}

Step 6: Reporting

Weekly Summary

{
  "schemaVersion": "1.0",
  "stepId": "generate-report",
  "type": "AIAGENT",
  "def": {
    "agentId": "compliance-auditor",
    "input": "Generate weekly compliance summary:\n\nData: {{step.query-audits.results | tojson}}\n\nInclude:\n1. Executive Summary\n2. Score by Framework\n3. New Violations\n4. Violations Resolved\n5. Action Items"
  }
}

Dashboard Queries

-- Compliance Score
SELECT (SUM(CASE WHEN status='PASSED' THEN 1 ELSE 0 END) * 100.0 / COUNT(*)) as score
FROM compliance_audits WHERE evaluated_at > NOW() - INTERVAL '30 days';

-- By Framework
SELECT framework, COUNT(*) 
FROM compliance_findings WHERE status='NON_COMPLIANT' 
GROUP BY framework;

Step 7: Remediation

Human Approval for Critical

{
  "schemaVersion": "1.0",
  "stepId": "acknowledge",
  "type": "HUMAN_INTERACTION",
  "def": {
    "assignee": "{{step.get-owner.email}}",
    "title": "Compliance Violation",
    "form": {
      "fields": [
        {"name": "acknowledged", "type": "boolean", "required": true},
        {"name": "target_date", "type": "date"},
        {"name": "notes", "type": "textarea"}
      ]
    },
    "timeout": 86400
  }
}

Quick Reference

Condition Operators

Operator Usage
EQUALS Exact match
GREATER_THAN Numeric comparison
CONTAINS String contains
IS_EMPTY Check empty

Expression Syntax

Pattern Example
{{input.x}} {{input.repository.name}}
{{step.id.x}} {{step.fetch.response.files}}
{{variables.x}} {{variables.owner}}

Next Steps