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:lineevidence - 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 four moves of compliance-as-code
Section titled “The four moves of compliance-as-code”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.
-
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.
-
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.
-
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.
-
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.
Mapping one control to your codebase
Section titled “Mapping one control to your codebase”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.
From the repo root, run claude and paste the prompt. Claude Code reads files with Read, Glob, and Grep as it builds the table, so it cites real paths. To capture the result as an artifact for your audit folder, run it headless:
claude -p "Audit this repo against SOC 2 CC6.1 and output a markdown gap table with file:line evidence. Only mark Met with a citation." \ --output-format json > soc2-cc6.1-gap.jsonRun codex in the repo and paste the prompt. Keep approvals strict for a read-only audit so it never edits files:
codex --ask-for-approval untrusted --sandbox read-onlyread-only sandbox guarantees the agent can inspect everything but cannot touch the working tree while it builds the evidence table.
Policy enforcement in CI/CD
Section titled “Policy enforcement in CI/CD”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 compliancepolicies 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 middleware4. 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 artifactwith 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.
Claude Code’s edge here is that the same agent runs both interactively and headless, so the rules you generate locally are the rules that run in CI. Build them once, then invoke Claude headless inside the compliance job itself.
claude "Create a compliance enforcement system for our CI/CD pipeline.
Requirements:- GitHub Actions workflow that runs on every PR to main- Secret detection: scan for hardcoded API keys, passwords, and tokens- SQL injection prevention: verify parameterized queries- Authentication checks: ensure all public endpoints use auth middleware- PII protection: validate encryption on sensitive database fields- Approval gates: require 2 reviewers for changes to auth/ and security/ dirs
Each check should produce structured JSON output with: { timestamp, check_name, result, affected_files, evidence_hash }
Store results as workflow artifacts for audit trail.Generate all files needed: workflow YAML, scanning scripts, and acompliance-report-generator that summarizes results."Then run the analysis step itself in headless mode from the workflow, so the JSON evidence is produced by the same agent and parsed deterministically:
- name: Compliance review (headless) run: | claude -p "Review the diff in this PR against the rules in .compliance/policies.md. Emit one JSON object per violation: { control_id, file, line, severity, fix }. Emit [] if clean." \ --output-format json --allowedTools "Read,Grep,Bash" \ > compliance-evidence/review-$(date +%Y%m%d-%H%M%S).json--output-format json gives you a machine-parseable result you can gate the job on, and the timestamped artifact becomes audit evidence on its own.
Codex’s differentiator is the cloud task plus GitHub integration: the enforcement workflow can be authored and shipped as a PR without anyone running it locally. Open a cloud task that does the work and opens the PR for you.
From the terminal, kick off a cloud task and pull the diff back when it is done:
codex cloud exec --env prod-ci "Add a GitHub Actions compliance gate that runs onevery PR to main: secret scanning, parameterized-query check, auth-middlewarecheck on public endpoints, PII-encryption check on schemas, and a 2-reviewerrequirement for auth/ and security/. Emit structured JSON evidence per check andupload it as a workflow artifact. Open a PR with the workflow and scripts."codex apply # apply the task's diff to your local working tree to reviewOr skip the terminal entirely: comment @codex add the compliance gate described in our SOC 2 checklist on a tracking PR and Codex starts a cloud task using that PR as context, then pushes its changes back. Because the work lands as a reviewable PR, the generation of your compliance rules is itself captured in the change-management audit trail.
Two gates worth adding first
Section titled “Two gates worth adding first”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.
Blocking a violation before the commit
Section titled “Blocking a violation before the commit”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) thatenforces 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 enabled4. Database migration files must include a rollback step5. API route files must import from the auth middleware module
For each rule that fails, print a clear message explaining the violationand how to fix it. Also create a COMPLIANCE.md that documents each hookand 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.
Beyond the shared .pre-commit-config.yaml, Claude Code has its own native hooks that fire around the agent’s own actions. Use a PreToolUse hook so the agent itself is blocked from writing a secret or an unauthenticated route, not just blocked at commit time.
claude "Add a Claude Code PreToolUse hook in .claude/settings.json that runson Edit and Write. The hook should run scripts/compliance/guard.sh on thefile being written and exit non-zero (blocking the edit) if it detects ahardcoded secret or a new API route missing the auth middleware import.Print the violated control ID so the block message is audit-friendly.Also generate the shared .pre-commit-config.yaml for git-level enforcement."Gate the agent’s commits on gitleaks too, so a staged secret aborts the commit it was about to make:
{ "hooks": { "PreToolUse": [ { "matcher": "Bash(git commit:*)", "hooks": [{ "type": "command", "command": "gitleaks protect --staged --redact" }] } ] }}The pre-commit config catches what a human commits; the Claude Code hooks catch what the agent tries to write and commit in the first place. All three layers emit the same control IDs, so a violation is traceable to a specific SOC 2 / HIPAA clause no matter which one fires.
Treat the hook config as a small, reviewable change you can ship without local setup. Mention @codex on a tracking issue or PR and let the cloud task open the PR:
@codex add pre-commit compliance hooks: gitleaks for secret detection, acustom hook blocking TODO/FIXME in src/security/, a hook requiring a rollbackblock in every DB migration, and a hook checking API routes import the authmiddleware. Add .pre-commit-config.yaml plus the custom scripts and open a PR.To do it locally instead, let Codex edit files but keep command approval on so you see the gitleaks install:
codex --ask-for-approval on-request --sandbox workspace-writeThen have it run gitleaks detect --no-git once to prove the config parses. Either way the change lands through the same approval flow as any code, so adding the guardrail is itself logged as a change-management event.
Automated audit trail generation
Section titled “Automated audit trail generation”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.
Git-based audit trail
Section titled “Git-based audit trail”Your Git history already contains a rich audit trail. AI can extract compliance-relevant events from it.
Infrastructure audit trail
Section titled “Infrastructure audit trail”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 quarter2. Security group modifications (who changed what, when)3. IAM policy changes and their justifications from PR descriptions4. Encryption configuration status for all data stores5. Network access control changes
Cross-reference each change against our SOC 2 CC6.1 (logical access)and CC6.6 (boundary protection / network controls) requirements. Flagany 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.
Auditors want evidence collected continuously, not the night before. Claude Code’s headless mode lets you run this same audit on a schedule and drop the report straight into your evidence bucket — no human in the loop.
# scripts/compliance/infra-audit.sh — run from a weekly cron / scheduled CI jobclaude -p "Generate an infrastructure compliance audit report.Analyze Terraform state changes over the past 7 days. For each change extract:resource modified, Git author, PR number and approval status, and whether ittouches a security control (security groups, IAM, encryption, network ACLs).Map each finding to SOC 2 controls CC6.1 (logical access), CC6.6(boundary/network controls), and CC7.1 (detection of configuration changesand unauthorized components). Flag changes without proper PR approval." \ --output-format json --allowedTools "Read,Grep,Bash" \ > compliance-evidence/infra-audit-$(date +%Y%m%d).jsonBecause it is headless and emits JSON, you get a dated, tamper-evident artifact every week, and a downstream step can fail the job (or page the compliance channel) the moment an unapproved IAM change shows up.
Codex fits when the audit should live in the cloud and post itself to the team. Schedule a cloud task, or wire the GitHub Action so every infra PR gets an inline compliance review.
on: pull_request: paths: ['infra/**', '**/*.tf']jobs: audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - uses: openai/codex-action@v1 with: prompt-file: .github/codex/prompts/infra-audit.mdKeep the prompt in .github/codex/prompts/infra-audit.md (the same Terraform/IAM/encryption checks mapped to CC6.1, CC6.6, CC7.1). For an ad-hoc run, comment @codex audit the infra changes in this PR against our SOC 2 controls and Codex posts the findings as a PR review.
SOC 2 evidence package generation
Section titled “SOC 2 evidence package generation”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.
Assembling the full package
Section titled “Assembling the full package”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 description2. Evidence collected3. Testing results (effective/deficiency)4. Recommendations for improvement
Output as a structured document that an auditor can review directly."A full SOC 2 package spans several independent evidence domains, which maps cleanly onto sub-agents: ask Claude Code to fan each control family out to its own sub-agent so they collect in parallel and report back to a single coordinator.
claude "Generate a SOC 2 Type II evidence package for Q4. Use a separatesub-agent per control family so they run in parallel, then merge the results:
- Sub-agent A — CC6.1: logical access controls (user reviews, RBAC, MFA)- Sub-agent B — CC6.2: system accounts (service account inventory, rotation)- Sub-agent C — CC6.6/CC6.7: boundary protection and data classification (network diagrams, data-flow/PII encryption)- Sub-agent D — CC8.1: change management (PR approvals, CI/CD logs, deployments)
Each sub-agent: describe the evidence needed, pull what is available from Githistory and CI/CD artifacts, document gaps requiring manual evidence, and rateeffectiveness with any deficiencies. The coordinator merges everything into oneauditor-ready document with an executive summary."Sub-agents keep each control’s context window focused on its own evidence and cut wall-clock time on a package that would otherwise be one long serial pass.
Evidence collection is long-running and best handled async. Submit it as a cloud task that compiles the package and opens a PR adding it under compliance/evidence/, then review the diff locally.
codex cloud exec --env compliance "Generate a SOC 2 Type II evidence packagecovering CC6.1, CC6.2, CC6.6/CC6.7, and CC8.1. Pull evidence from Git history,CI/CD artifacts, and infrastructure configs. Flag gaps that require manualevidence. Write the result to compliance/evidence/soc2-q4.md and open a PR."codex apply # bring the task's diff into your working tree to reviewRunning it in the cloud means the package regenerates on the same cadence each quarter without tying up a local session, and landing it as a PR puts the evidence itself under change control.
HIPAA compliance patterns
Section titled “HIPAA compliance patterns”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 middlewareimport { 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 compliance automation
Section titled “GDPR compliance automation”GDPR requires specific capabilities: data subject access requests (DSARs), right to erasure, consent management, and data processing records.
Automating data subject requests
Section titled “Automating data subject requests”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 export4. Generates a human-readable PDF summary5. Logs the DSAR fulfillment for our processing records6. Can also handle right-to-erasure by deleting/anonymizing all records
Include proper error handling for partial failures (e.g., one data storeis unreachable). The response should indicate which sources weresuccessfully queried and which failed, so we can retry."Generate the handler with tests, then lean on headless mode to keep the DSAR coverage honest over time — a scheduled claude -p check that proves every data store still has an adapter is itself GDPR Article 30 evidence.
claude "Build a GDPR DSAR handler.
Given a user email or ID, it should:- Query all data stores (PostgreSQL, Redis, S3, analytics, email logs)- Compile user data into JSON export- Generate PDF summary for the data subject- Log the request for Article 30 processing records- Support right-to-erasure (delete/anonymize across all stores)- Handle partial failures gracefully
Create the handler, data store adapters, and the API endpoint.Include tests for the happy path and partial failure scenarios."Then add a coverage gate to CI that fails when a data store has no adapter:
claude -p "List every persistent data store referenced in the codebase(DB connections, Redis clients, S3 buckets, external logging clients). Foreach, state whether a DSAR adapter exists. Emit JSON: { store, has_adapter }." \ --output-format json --allowedTools "Read,Grep"A DSAR handler spans several adapters and is a natural async build. Submit it as a cloud task that opens a PR, and keep the prompt in the repo so the work is reproducible and reviewable.
@codex build a GDPR DSAR handler that queries PostgreSQL, Redis, S3, andanalytics for all of a user's data. Support data export (JSON + PDF) andright-to-erasure across every store, log all requests for Article 30 records,and handle partial failures with retry. Add tests and open a PR.Mentioning @codex on a tracking issue starts a cloud task with that issue as context and pushes the handler back as a PR — so the erasure logic gets human review before it can ever run against production data.
Drafting the GDPR data-flow narrative
Section titled “Drafting the GDPR data-flow narrative”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 serverimport { 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.
Security scanning automation
Section titled “Security scanning automation”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.
name: Compliance Security Scanon: 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: 365Static analysis for compliance
Section titled “Static analysis for compliance”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-relevantpatterns in our codebase:
1. Data handling: PII must be logged with redaction, never raw values2. Authentication: All API endpoints must check auth before processing3. Encryption: Sensitive config values must use encrypted env vars4. Logging: Security events must use the structured audit logger5. 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 thespecific compliance requirement it enforces (e.g., SOC2-CC6.1, HIPAA-164.312)."Some compliance patterns (“does this error response leak a stack trace?”) are semantic, not syntactic, and a static linter can’t see them. Use Claude Code headless as a semantic checker in CI alongside ESLint, emitting the same control-tagged JSON.
claude "Create compliance-focused static analysis rules.
Rules needed:- PII redaction in logs (no raw email, SSN, phone in log statements)- Auth middleware on all API routes- Encrypted env vars for sensitive config- Structured audit logging for security events- No internal details in error responses
Implement as ESLint custom rules where possible, standalone scriptsfor the rest. Tag each rule with its compliance requirement ID."For the rules ESLint can’t express, add a headless semantic pass to the PR job:
claude -p "Review changed files for compliance violations ESLint cannot catch:error responses leaking internal details, log statements with unredacted PII,endpoints missing an auth check. Emit JSON: { control_id, file, line, issue }." \ --output-format json --allowedTools "Read,Grep"Run the static-analysis pass as part of the Codex GitHub Action so every PR is checked in CI and findings post back as a review, with the prompt versioned in the repo.
# add to .github/workflows/compliance-security.yml- uses: openai/codex-action@v1 with: prompt-file: .github/codex/prompts/compliance-lint.mdKeep .github/codex/prompts/compliance-lint.md tagging each finding with its requirement ID (SOC2-CC6.1, HIPAA-164.312). For an ad-hoc scan, @codex review for compliance regressions on the PR runs the same checks as a cloud task.
Scheduled compliance reporting
Section titled “Scheduled compliance reporting”Automate weekly and quarterly reports so the data is always current and nobody has to reconstruct a quarter from memory.
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);}When compliance-as-code breaks down
Section titled “When compliance-as-code breaks down”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.