Skip to content

Regulatory Compliance Automation

Regulatory compliance automation applies AI coding agents to encode SOC 2, HIPAA, and GDPR requirements as executable policies enforced in CI/CD pipelines instead of collected by hand. Pre-commit hooks and pipeline gates catch violations before code ships, Git history and infrastructure logs become audit trails automatically, and the agent drafts evidence packages, data-flow documents, and DSAR handlers that a human reviews before an auditor sees them.

Your company just passed its SOC 2 Type II audit, but evidence collection took three engineers two full weeks: copying logs from half a dozen systems into spreadsheets, writing narrative control descriptions, screenshotting configurations to prove a policy was enforced. Next quarter the auditor asks for the same evidence again, plus proof that no GPL-licensed dependency shipped and a data-flow diagram showing where EU personal data lives. The engineer who knew where everything lived just left the company.

Compliance is not optional, but the manual labor surrounding it is. This is exactly the kind of repetitive, evidence-heavy work an AI coding agent is good at: it reads the repository, drafts the scripts that collect evidence, wires the CI gates that enforce a control, and turns code into the narrative an auditor expects. You stay the reviewer; the agent does the typing.

What you’ll walk away with on compliance automation

Section titled “What you’ll walk away with on compliance automation”
  • A prompt that audits a repo against a specific SOC 2 control (CC6.1, CC8.1) and returns a gap table with file:line evidence
  • Compliance-as-code patterns that enforce policy in CI/CD, plus pre-commit and agent-level hooks that block a violation before it is ever committed
  • A GitHub Actions job that fails the build on disallowed dependency licenses, and a gitleaks secret gate the agent wires for you
  • Audit-trail generation from Git history, GitHub review data, and Terraform state
  • Prompts that produce SOC 2 evidence packages, HIPAA PHI data-flow checks, GDPR DSAR handlers, and a GDPR data-flow document
  • The MCP servers that turn evidence collection into one step instead of ten

The core idea: encode your regulatory requirements as executable rules that run automatically. Instead of proving compliance retroactively, you prevent non-compliance from shipping — and every enforcement run leaves a dated artifact behind, which is the evidence itself.

  1. Map one control to your code. Translate a single control (SOC 2 CC6.1, HIPAA 164.312, GDPR Article 25) into something checkable, and find out where you already satisfy it and where you do not.

  2. Enforce it at every layer that can enforce it. Agent hooks stop a bad edit before it is written. Pre-commit hooks catch it locally. CI/CD gates block the merge. Infrastructure-as-code scanners validate the deployment.

  3. Generate the evidence collector. Every enforcement check produces a timestamped log entry, and a script pulls branch protection, approvals, and deploy records on demand. Together those are your audit trail.

  4. Write the narrative an auditor reads. The agent aggregates enforcement logs, Git history, and infrastructure state into the prose and diagrams auditors expect.

Treat everything the agent produces as a first draft you review, never as the auditor’s word. The failure mode that costs you a finding is a confident, tidy, unverifiable table.

Start narrow. Pick one control and ask the agent to find where you do and don’t satisfy it. The trick is forcing file:line citations so you can verify every claim instead of trusting a summary.

The “do not invent” clause matters. Compliance prompts are where models are most tempted to hallucinate a tidy, fully-compliant answer. Demanding citations turns “trust me” into something you can spot-check in 30 seconds.

The mechanics of pointing the agent at your repo differ per tool:

Open the repo and switch the Agent to a planning-grade model (Fable 5 or Opus 5 for thorough audits, Sonnet 5 for everyday passes). Paste the prompt in Agent mode and add @Codebase so it searches the whole project rather than just open files. Cursor renders the gap table inline; click each file:line citation to jump straight to the evidence and confirm it.

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.

Of everything you can gate on, dependency licenses and secrets pay for themselves fastest. The license check is pure policy, so the agent can write it outright:

Secrets are different. Two prompts below look similar and are not interchangeable: the first is a one-off inventory of what is already in the tree, run by the agent and read by a human; the standing gate is gitleaks, wired by the agent but never written by it. Never let the agent hand-roll a secret scanner — its rule set is guesswork, gitleaks’ is maintained and tested.

Pre-commit hooks give developers immediate feedback before code ever leaves their machine. That is faster than waiting for CI and it reduces violations at the source. The agent that writes your code can also be gated at the same control IDs, one layer earlier.

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."

For the secret half specifically, ask for the established tool rather than custom rules:

Add a pre-commit hook using gitleaks that blocks commits containing secrets,
plus a CI job that runs `gitleaks detect` on every PR.

Cursor edits .pre-commit-config.yaml and the workflow file. Review the diff in the Source Control panel, then stage a fake AWS_SECRET_ACCESS_KEY=... line locally to confirm the hook actually blocks it before you trust it. This is the portable, language-agnostic layer 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.

A collector you can re-run the morning of the audit

Section titled “A collector you can re-run the morning of the audit”

Before the big package, build the small repeatable thing: a script that pulls the proof on demand, so the evidence is never a one-off chat transcript.

Review what it produces. Confirm it calls real gh api / Octokit endpoints (not invented ones), reads the token from the environment rather than hardcoding it, and that the control mapping in the header comment is honest. Then run it once and eyeball the JSON against what you see in the GitHub UI.

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."

The last mile of most audits is prose: a data-flow description an auditor or DPO can read. The agent can trace personal-data fields through the codebase far faster than you can grep for them — as long as you make it cite sources and flag uncertainty.

The Mermaid diagram renders directly in most docs tools and gives your DPO a picture instead of a wall of text. The “NEEDS REVIEW” tag is the safety valve — it surfaces the fields the agent couldn’t fully trace so a human closes the gap.

Which MCP servers and skills actually pay off here

Section titled “Which MCP servers and skills actually pay off here”

Evidence collection gets dramatically shorter when the agent can query your systems directly instead of shelling out to CLIs. The GitHub and Postgres servers above do most of the work; two more are worth wiring:

  • Sentry MCP (https://mcp.sentry.dev/mcp) — pull incident and error history as evidence for availability and incident-response controls.
  • Filesystem MCP — for scoping the agent to a specific evidence directory when generating reports.

If you genuinely need to script an MCP client (rather than letting the agent drive one), the SDK construction is specific — the package exports Client, not a root MCPClient, and it connects over a transport, never a bare server-name string:

// Connect a programmatic MCP client to the GitHub server
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
const client = new Client({ name: 'compliance-evidence', version: '1.0.0' });
await client.connect(
new StreamableHTTPClientTransport(new URL('https://api.githubcopilot.com/mcp/'))
);

On the Skills side, a single-purpose code review skill from the open skills marketplace (browse skills.sh and install with npx skills add <owner/repo>) is a lighter alternative to a full MCP server when all you want is a consistent compliance-flavored review on each PR. Reach for a skill when you need repeatable behavior; reach for an MCP server when the agent needs a live connection to a system of record.

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 reports so the data is always current and nobody has to reconstruct a quarter from memory.

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);
}

The agent marks a control “Met” with no real evidence. This is the failure mode that gets you a finding. Always require file:line citations, then spot-check three of them. If a citation points at a file that doesn’t contain the claimed control, discard the whole table and re-run with a stricter prompt.

It invents an MCP server or npm package. Do not paste regulatory-mcp-server, @compliance/*, or similar — none exist. Verify any suggested package with npm view <pkg> version before wiring it in, and stick to the GitHub/Postgres/Sentry/Filesystem MCPs above.

Scanners fail in both directions. A generated regex misses a real secret; a secret scanner flags a test fixture holding a fake API key. Use gitleaks or gh secret-scanning rather than hand-rolled rules for the first problem, and an allowlist for the second — then review that allowlist quarterly so it does not quietly grow to hide real findings.

License data is wrong for transitive deps. license-checker reads declared licenses, which are sometimes mislabeled upstream. For anything you are about to ship under audit, confirm flagged copyleft packages manually before failing or unblocking a build.

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

The DSAR handler misses a data store. When a new service is added, someone forgets to add it to the handler. Keep a data-store registry that every new service must register with, and add the CI coverage check above that verifies every database connection in the codebase has a corresponding DSAR adapter.

A generated document leaks a real secret or PII sample. Tell the agent to redact values and reference field names only. Review the diff before committing anything to evidence/.

Compliance reports reference stale policies. The documentation says you rotate credentials every 90 days, but the rotation script runs every 180. The report generator should check actual rotation dates against the stated policy and flag the discrepancy rather than restating the policy.

Pre-commit hooks slow developers down. If compliance hooks take more than 5 seconds, developers 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 — new GDPR guidance, revised SOC 2 criteria — 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.

Where to go next with compliance automation

Section titled “Where to go next with compliance automation”