Skip to content

Regulatory Compliance Automation

Your company just passed its SOC 2 Type II audit, but the evidence collection took three engineers two full weeks. Half the work was copying logs from various systems into spreadsheets, writing narrative descriptions of controls, and screenshotting configurations that proved policies were enforced. Next quarter the auditor will ask for the same evidence again, and the engineer who knew where everything lived just left the company.

Compliance is not optional, but the manual labor surrounding it is. AI coding tools can automate policy enforcement at the code level, generate audit trails from your existing infrastructure, and produce compliance documentation that stays current without dedicated headcount.

  • Automated compliance-as-code patterns that enforce policies in CI/CD pipelines
  • Pre-commit hooks that catch compliance violations before code reaches production
  • AI-driven audit trail generation from Git history, infrastructure logs, and deployment records
  • Prompts for generating SOC 2, HIPAA, and GDPR compliance evidence packages
  • Security scanning automation integrated into your daily development workflow

The core idea: encode your regulatory requirements as executable rules that run automatically. Instead of proving compliance retroactively, you prevent non-compliance from shipping.

  1. Define your compliance requirements as machine-readable policies. Translate each control (SOC 2 CC6.1, HIPAA 164.312, GDPR Article 25) into a rule that can be checked programmatically.

  2. Implement enforcement at multiple layers. Pre-commit hooks catch issues locally. CI/CD gates block non-compliant code from merging. Infrastructure-as-code scanners validate deployment configurations.

  3. Generate audit evidence automatically. Every enforcement check produces a timestamped log entry. These logs become your audit trail.

  4. Produce compliance reports on demand. AI aggregates enforcement logs, Git history, and infrastructure state into narrative reports that auditors expect.

The most reliable compliance enforcement happens in your CI/CD pipeline. Code that violates a policy never reaches production because the pipeline rejects it.

Generate the pipeline in agent mode, then use Cursor’s checkpoint and diff review to vet every generated rule. Compliance rules are exact-match by nature, so the visual review step matters more here than in most workflows.

@codebase "Create a GitHub Actions workflow that enforces the following compliance
policies before any code can be merged to main:
1. All secrets must be stored in environment variables, never hardcoded
(scan for patterns like API keys, passwords, tokens)
2. All database queries must use parameterized statements
(no string concatenation in SQL)
3. All user-facing endpoints must have authentication middleware
4. All PII fields must be encrypted at rest (check schema definitions)
5. All changes to auth-related files require two approvals
For each check, log the result to a compliance-evidence.json artifact
with timestamp, check name, result (pass/fail), and affected files.
Generate the workflow file and any helper scripts needed."

Before accepting the diff, set a Cursor checkpoint and walk each generated rule against your actual control language. A regex that is slightly too broad will flag every PR; one that is too narrow silently passes violations. The checkpoint lets you revert a single bad rule without regenerating the whole workflow.

Pre-commit hooks give developers immediate feedback before code ever leaves their machine. This is faster than waiting for CI and reduces compliance violations at the source.

Generate the standard .pre-commit-config.yaml, then use agent mode to add the project-specific rules and review each one in the diff before committing.

"Generate a pre-commit hook configuration (.pre-commit-config.yaml) that
enforces these compliance rules locally:
1. No secrets in committed files (use detect-secrets or gitleaks)
2. No TODO/FIXME comments in files under src/security/
3. All TypeScript files must have 'use strict' or strict mode enabled
4. Database migration files must include a rollback step
5. API route files must import from the auth middleware module
For each rule that fails, print a clear message explaining the violation
and how to fix it. Also create a COMPLIANCE.md that documents each hook
and the regulatory requirement it addresses."

This is the portable, language-agnostic layer (the pre-commit framework) that every contributor gets regardless of which editor they use.

Auditors need evidence that controls were enforced over time, not just at the moment of the audit. An automated audit trail captures enforcement data continuously.

Your Git history already contains a rich audit trail. AI can extract compliance-relevant events from it.

Infrastructure changes also need audit trails. If you use Terraform, CloudFormation, or Pulumi, every change is already versioned.

Run this interactively in agent mode when you are preparing for an audit window and want to read the findings as they come, then drill into specific Terraform diffs in the editor.

@codebase "Generate an infrastructure compliance report by analyzing:
1. All Terraform state changes in the past quarter
2. Security group modifications (who changed what, when)
3. IAM policy changes and their justifications from PR descriptions
4. Encryption configuration status for all data stores
5. Network access control changes
Cross-reference each change against our SOC 2 CC6.1 (logical access)
and CC6.6 (boundary protection / network controls) requirements. Flag
any changes that lack a corresponding approval in the PR process.
Output as a structured report with evidence links to specific commits."

Cursor links each finding to the commit, so you can open the diff inline and eyeball whether the change really matches its PR justification before the report goes to the auditor.

SOC 2 Type II audits require evidence that controls operated effectively over a period (usually 6-12 months). Generating this evidence manually is the most time-consuming part of the audit.

Assemble the package interactively so you can correct scope as the agent works — open the identity-provider export or a Terraform file inline and confirm the evidence matches before it lands in the document.

"Generate a complete SOC 2 Type II evidence package for the past quarter.
For each Trust Service Criteria, collect the following:
CC6.1 (Logical Access Controls):
- User access reviews (export from our identity provider)
- Role-based access control documentation
- MFA enforcement evidence (percentage of users with MFA enabled)
- Privileged access inventory
CC6.2 (System Account Management):
- Service account inventory with last rotation dates
- Automated credential rotation evidence from CI/CD logs
- Account lifecycle documentation (creation, modification, termination)
CC6.6 (Boundary Protection) and CC6.7 (Data Classification / Transmission):
- Network architecture diagram (generate from Terraform)
- Data classification matrix
- Data flow diagrams for PII (encryption in transit)
CC8.1 (Change Management):
- All PRs merged to main with approval status
- CI/CD pipeline pass rates
- Deployment logs with rollback instances
- Change advisory board meeting notes (if applicable)
For each control, provide:
1. Control description
2. Evidence collected
3. Testing results (effective/deficiency)
4. Recommendations for improvement
Output as a structured document that an auditor can review directly."

HIPAA compliance requires specific technical safeguards for protected health information (PHI). AI tools can enforce these safeguards in code.

// Example: AI-generated PHI access logging middleware
import { auditLogger } from '~/lib/compliance/audit';
import { classifyData } from '~/lib/compliance/data-classification';
export async function phiAccessMiddleware(request: Request, next: Function) {
const classification = await classifyData(request);
if (classification.containsPHI) {
await auditLogger.log({
timestamp: new Date().toISOString(),
userId: request.auth.userId,
action: request.method,
resource: request.url,
dataClassification: 'PHI',
justification: request.headers.get('X-Access-Justification'),
ipAddress: request.headers.get('X-Forwarded-For'),
});
}
return next(request);
}

GDPR requires specific capabilities: data subject access requests (DSARs), right to erasure, consent management, and data processing records.

Build the handler in agent mode and set a checkpoint before accepting each data-store adapter — the erasure path is destructive, so you want to review the delete/anonymize logic in the diff rather than trust it blind.

"Generate a DSAR (Data Subject Access Request) handler that:
1. Accepts a user identifier (email or user ID)
2. Searches all data stores for records associated with that user:
- PostgreSQL (users, orders, payments, support_tickets)
- Redis cache (session data, preferences)
- S3 (uploaded documents, profile images)
- Analytics events (PostHog)
- Email service (Resend delivery logs)
3. Compiles all data into a structured JSON export
4. Generates a human-readable PDF summary
5. Logs the DSAR fulfillment for our processing records
6. Can also handle right-to-erasure by deleting/anonymizing all records
Include proper error handling for partial failures (e.g., one data store
is unreachable). The response should indicate which sources were
successfully queried and which failed, so we can retry."

Continuous security scanning catches vulnerabilities before they reach production. The key is integrating scans into workflows developers already use, not adding separate security gates they learn to bypass.

.github/workflows/compliance-security.yml
name: Compliance Security Scan
on:
pull_request:
branches: [main]
schedule:
- cron: '0 6 * * 1' # Weekly Monday scan
jobs:
dependency-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run dependency audit
run: npm audit --json > audit-results.json
- name: Analyze results
run: |
node scripts/compliance/analyze-audit.js \
--input audit-results.json \
--severity high,critical \
--output compliance-evidence/dependency-scan-$(date +%Y%m%d).json
- name: Upload compliance evidence
uses: actions/upload-artifact@v4
with:
name: compliance-evidence-deps
path: compliance-evidence/
retention-days: 365

Author the ESLint rules in agent mode and test them against real files in the editor — paste a known-bad logging statement and confirm the rule actually fires before you trust it in CI.

"Create a static analysis configuration that checks for compliance-relevant
patterns in our codebase:
1. Data handling: PII must be logged with redaction, never raw values
2. Authentication: All API endpoints must check auth before processing
3. Encryption: Sensitive config values must use encrypted env vars
4. Logging: Security events must use the structured audit logger
5. Error handling: Error responses must not leak internal details
Use ESLint custom rules where possible. For checks ESLint cannot handle,
create standalone analysis scripts. Each rule should reference the
specific compliance requirement it enforces (e.g., SOC2-CC6.1, HIPAA-164.312)."

Automate weekly and quarterly compliance reports so the data is always current.

scripts/compliance/generate-weekly-report.ts
import { getGitActivity } from './sources/git';
import { getCIResults } from './sources/ci';
import { getSecurityScans } from './sources/security';
import { getAccessReviews } from './sources/access';
import { renderReport } from './templates/weekly';
async function generateWeeklyComplianceReport() {
const period = { start: sevenDaysAgo(), end: now() };
const data = {
gitActivity: await getGitActivity(period),
ciResults: await getCIResults(period),
securityScans: await getSecurityScans(period),
accessReviews: await getAccessReviews(period),
};
const report = renderReport({
...data,
controls: mapToControls(data),
deficiencies: findDeficiencies(data),
recommendations: generateRecommendations(data),
});
await saveReport(report, `weekly-${period.end.toISOString()}`);
await notifyComplianceTeam(report.summary);
}

Compliance rules produce false positives. A secret scanner flags a test fixture containing a fake API key. Add an allowlist for known false positives, but review the allowlist quarterly to ensure it has not grown to hide real issues.

Audit trail has gaps. If developers push directly to main bypassing the PR process, the audit trail misses approvals. Enforce branch protection rules at the repository level, not just in CI. GitHub and GitLab both support requiring PR approvals as a repository setting.

DSAR handler misses a data store. When a new service is added, someone forgets to add it to the DSAR handler. Include a “data store registry” that all new services must register with, and add a CI check that verifies every database connection in the codebase has a corresponding DSAR adapter.

Compliance reports reference stale policies. The compliance documentation says you rotate credentials every 90 days, but the actual rotation script runs every 180 days. Automate the policy verification: the report generator should check actual rotation dates against the stated policy and flag discrepancies.

Pre-commit hooks slow down developers. If compliance hooks take more than 5 seconds, developers will skip them with --no-verify. Keep pre-commit checks fast (secret scanning, lint rules) and move slower checks (full dependency audit, infrastructure scanning) to CI.

Regulatory requirements change. When a regulation updates (such as new GDPR guidance or SOC 2 criteria revisions), your encoded policies need to change too. Subscribe to regulatory update feeds and schedule quarterly reviews of your compliance-as-code rules against current requirements.