diff --git a/src/app/compliance/audit/page.tsx b/src/app/compliance/audit/page.tsx new file mode 100644 index 00000000..26cf3119 --- /dev/null +++ b/src/app/compliance/audit/page.tsx @@ -0,0 +1,844 @@ +import Link from "next/link"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Separator } from "@/components/ui/separator"; +import { FileText, Database, Lock, BarChart3, Clock } from "lucide-react"; + +export const metadata = { + title: "Audit Log Guide — forAgents.dev", + description: "Implement proper audit logging for AI agents with retention policies, tamper-proof storage patterns, and compliance reporting. Code examples for structured logging.", + openGraph: { + title: "Audit Log Guide — forAgents.dev", + description: "Implement proper audit logging for AI agents with retention policies, tamper-proof storage patterns, and compliance reporting. Code examples for structured logging.", + url: "https://foragents.dev/compliance/audit", + siteName: "forAgents.dev", + type: "website", + }, +}; + +export default function AuditLogPage() { + return ( +
+ + {/* Hero Section */} +
+
+
+
+ +
+ + ← Back to Compliance Hub + + + Implementation Guide + +

+ Audit Log Guide +

+

+ Build comprehensive, tamper-proof audit trails for AI agents +

+
+
+ + + + {/* Why Audit Logs Matter */} +
+
+

+ + Why Audit Logs Are Critical +

+

+ Audit logs are the black box for AI agents. They provide accountability, enable debugging, + meet regulatory requirements, and support forensic investigations when incidents occur. +

+
+
+
Compliance
+

GDPR, HIPAA, SOX require detailed audit trails

+
+
+
Debugging
+

Trace decisions and identify failure points

+
+
+
Security
+

Detect unauthorized access and anomalies

+
+
+
Trust
+

Demonstrate transparency to users and auditors

+
+
+
+
+ + {/* What to Log */} +
+ + + + + What to Log + + + +

+ Comprehensive logging captures the full context of agent actions for auditability and debugging. +

+ +
+
+

Core Fields (Required)

+
+
+ timestamp +

ISO 8601 format with timezone

+
+
+ event_id +

Unique identifier (UUID)

+
+
+ agent_id +

Which agent performed the action

+
+
+ user_id +

User who triggered the action

+
+
+ action +

What the agent did (verb)

+
+
+ resource +

What was acted upon

+
+
+ status +

success | failure | pending

+
+
+ risk_level +

low | medium | high

+
+
+
+ +
+

Context Fields (Recommended)

+
+
+ input +

User request or trigger data

+
+
+ output +

Agent response (truncate if large)

+
+
+ session_id +

Conversation or workflow session

+
+
+ ip_address +

Client IP (anonymize per GDPR)

+
+
+ duration_ms +

How long the action took

+
+
+ model_version +

AI model used (e.g., gpt-4)

+
+
+ approval_status +

approved | rejected | auto

+
+
+ approver_id +

Who approved (if applicable)

+
+
+
+ +
+

Error Fields (When Applicable)

+
+
+ error_code +

Machine-readable error code

+
+
+ error_message +

Human-readable error description

+
+
+ stack_trace +

Full stack trace (debug builds)

+
+
+ retry_count +

Number of retry attempts

+
+
+
+
+ +
+

Example Log Entry (JSON):

+
+
{`{
+  "timestamp": "2026-02-09T11:30:45.123Z",
+  "event_id": "550e8400-e29b-41d4-a716-446655440000",
+  "agent_id": "agent-kai-prod-01",
+  "user_id": "user_abc123",
+  "session_id": "sess_xyz789",
+  "action": "send_email",
+  "resource": "email:newsletter@example.com",
+  "status": "success",
+  "risk_level": "medium",
+  "approval_status": "approved",
+  "approver_id": "supervisor_alice",
+  "input": {
+    "recipient": "newsletter@example.com",
+    "subject": "Weekly Update",
+    "body_length": 1024
+  },
+  "output": {
+    "message_id": "msg_001",
+    "sent_at": "2026-02-09T11:30:46.456Z"
+  },
+  "duration_ms": 1234,
+  "model_version": "claude-sonnet-4",
+  "ip_address": "192.168.1.0/24",
+  "metadata": {
+    "campaign_id": "camp_winter_2026",
+    "tags": ["newsletter", "automated"]
+  }
+}`}
+
+
+
+
+
+ + {/* Retention Policies */} +
+ + + + + Retention Policies + + + +

+ Balance compliance requirements, storage costs, and operational needs with tiered retention policies. +

+ +
+
+

Standard Logs — 90 Days

+

+ Routine agent actions with low risk (information retrieval, scheduling, notifications) +

+
    +
  • • Sufficient for GDPR/CCPA compliance (30-day deletion window + buffer)
  • +
  • • Enables debugging of recent issues
  • +
  • • Archive to cold storage after 90 days
  • +
+
+ +
+

Sensitive Actions — 7 Years

+

+ High-risk actions (data modifications, external communications, approvals) +

+
    +
  • • Meets regulatory audit requirements (SOX, HIPAA)
  • +
  • • Supports legal discovery and investigations
  • +
  • • Store in compressed, encrypted format
  • +
+
+ +
+

Financial Transactions — 10 Years

+

+ Any action involving money (purchases, refunds, invoices, payments) +

+
    +
  • • Tax and audit compliance (IRS requires 7 years, some jurisdictions 10)
  • +
  • • Fraud investigation support
  • +
  • • Immutable, tamper-proof storage required
  • +
+
+ +
+

Security Incidents — Indefinite

+

+ Breach attempts, unauthorized access, policy violations, anomalies +

+
    +
  • • Permanent record for forensics and pattern detection
  • +
  • • May be required for legal proceedings
  • +
  • • Highest level of access control and encryption
  • +
+
+
+ +
+

Automated Retention Policy (SQL Example):

+
+
{`-- Partition logs by retention tier
+CREATE TABLE audit_logs (
+  event_id UUID PRIMARY KEY,
+  timestamp TIMESTAMPTZ NOT NULL,
+  agent_id VARCHAR(50),
+  action VARCHAR(100),
+  retention_tier VARCHAR(20) DEFAULT 'standard',
+  -- ... other fields
+  created_at TIMESTAMPTZ DEFAULT NOW()
+) PARTITION BY RANGE (created_at);
+
+-- Auto-archive to cold storage after 90 days
+CREATE OR REPLACE FUNCTION archive_old_logs()
+RETURNS void AS $$
+BEGIN
+  INSERT INTO audit_logs_archive
+  SELECT * FROM audit_logs
+  WHERE created_at < NOW() - INTERVAL '90 days'
+    AND retention_tier = 'standard';
+  
+  DELETE FROM audit_logs
+  WHERE created_at < NOW() - INTERVAL '90 days'
+    AND retention_tier = 'standard';
+END;
+$$ LANGUAGE plpgsql;
+
+-- Schedule daily
+SELECT cron.schedule('archive-logs', '0 2 * * *', 'SELECT archive_old_logs()');`}
+
+
+
+
+
+ + {/* Tamper-Proof Storage */} +
+ + + + + Tamper-Proof Storage Patterns + + + +

+ Audit logs must be immutable and verifiable to meet compliance standards and support investigations. +

+ +
+
+

1. Append-Only Storage

+

+ Once written, logs cannot be modified or deleted. Use database constraints or specialized services. +

+
+
{`-- PostgreSQL: Deny updates and deletes
+CREATE POLICY append_only ON audit_logs
+  FOR ALL USING (FALSE);
+
+CREATE POLICY allow_insert ON audit_logs
+  FOR INSERT WITH CHECK (TRUE);
+
+-- S3: Object Lock (WORM)
+aws s3api put-object-lock-configuration \\
+  --bucket audit-logs \\
+  --object-lock-configuration '{
+    "ObjectLockEnabled": "Enabled",
+    "Rule": {
+      "DefaultRetention": {
+        "Mode": "COMPLIANCE",
+        "Years": 7
+      }
+    }
+  }'`}
+
+
+ +
+

2. Cryptographic Hashing

+

+ Hash each log entry and chain them (blockchain-style) to detect tampering. +

+
+
{`// TypeScript: Log chaining with SHA-256
+import crypto from 'crypto';
+
+interface AuditLog {
+  event_id: string;
+  timestamp: string;
+  data: Record;
+  previous_hash: string;
+  hash: string;
+}
+
+function hashLog(log: Omit): string {
+  const data = JSON.stringify({
+    event_id: log.event_id,
+    timestamp: log.timestamp,
+    data: log.data,
+    previous_hash: log.previous_hash
+  });
+  return crypto.createHash('sha256').update(data).digest('hex');
+}
+
+function appendLog(data: Record, previousHash: string): AuditLog {
+  const log = {
+    event_id: crypto.randomUUID(),
+    timestamp: new Date().toISOString(),
+    data,
+    previous_hash: previousHash,
+    hash: ''
+  };
+  log.hash = hashLog(log);
+  return log as AuditLog;
+}
+
+// Verify chain integrity
+function verifyChain(logs: AuditLog[]): boolean {
+  for (let i = 1; i < logs.length; i++) {
+    if (logs[i].previous_hash !== logs[i - 1].hash) {
+      return false; // Chain broken
+    }
+    if (logs[i].hash !== hashLog(logs[i])) {
+      return false; // Log tampered
+    }
+  }
+  return true;
+}`}
+
+
+ +
+

3. Dedicated Logging Services

+

+ Use managed services designed for tamper-proof audit logs. +

+
    +
  • + +
    + AWS CloudWatch Logs: Encrypted, retention policies, IAM controls +
    +
  • +
  • + +
    + Google Cloud Logging: Audit logs with integrity verification +
    +
  • +
  • + +
    + Azure Monitor: Immutable storage with legal hold +
    +
  • +
  • + +
    + Datadog / Splunk: SIEM with compliance reporting +
    +
  • +
+
+ +
+

4. Access Controls

+

+ Restrict who can read logs and audit all access. +

+
    +
  • ✓ Role-based access control (RBAC): compliance, security, debug roles
  • +
  • ✓ Log all log access: who, when, what query (meta-auditing)
  • +
  • ✓ Require multi-factor authentication for log access
  • +
  • ✓ Separate log storage from application database
  • +
  • ✓ Encrypt at rest (AES-256) and in transit (TLS 1.3)
  • +
+
+
+
+
+
+ + {/* Compliance Reporting */} +
+ + + + + Compliance Reporting + + + +

+ Transform audit logs into actionable reports for auditors, regulators, and stakeholders. +

+ +
+
+

Standard Reports

+
+
+ 📊 +
+ Activity Summary: Total actions by agent, risk level, status (daily/weekly/monthly) +
+
+
+ ⚠️ +
+ High-Risk Actions: All medium/high risk actions with approval status +
+
+
+ +
+ Failures & Errors: Failed actions grouped by error type +
+
+
+ 👤 +
+ User Access: Actions per user with anomaly detection +
+
+
+ 🔒 +
+ Security Events: Unauthorized access attempts, policy violations +
+
+
+ 📈 +
+ Compliance Score: % of actions following governance policies +
+
+
+
+ +
+

Automated Report Generation

+
+
{`// Python: Generate weekly compliance report
+import pandas as pd
+from datetime import datetime, timedelta
+
+def generate_weekly_report(start_date, end_date):
+    logs = fetch_logs(start_date, end_date)
+    
+    report = {
+        "period": f"{start_date} to {end_date}",
+        "total_actions": len(logs),
+        "by_risk_level": logs.groupby('risk_level').size().to_dict(),
+        "high_risk_actions": logs[logs['risk_level'] == 'high'].to_dict('records'),
+        "approval_rate": (logs['approval_status'] == 'approved').mean(),
+        "error_rate": (logs['status'] == 'failure').mean(),
+        "top_agents": logs['agent_id'].value_counts().head(10).to_dict(),
+        "anomalies": detect_anomalies(logs)
+    }
+    
+    # Export as PDF for auditors
+    generate_pdf(report, f"compliance_report_{start_date}.pdf")
+    
+    # Send to compliance team
+    send_email(
+        to="compliance@company.com",
+        subject=f"Weekly Compliance Report: {start_date}",
+        attachments=[f"compliance_report_{start_date}.pdf"]
+    )
+    
+    return report
+
+# Schedule weekly
+schedule.every().monday.at("09:00").do(
+    lambda: generate_weekly_report(
+        datetime.now() - timedelta(days=7),
+        datetime.now()
+    )
+)`}
+
+
+ +
+

Query Examples (SQL)

+
+
+
Find all high-risk actions last 30 days:
+
+
{`SELECT * FROM audit_logs
+WHERE risk_level = 'high'
+  AND timestamp > NOW() - INTERVAL '30 days'
+ORDER BY timestamp DESC;`}
+
+
+
+
Actions by a specific user:
+
+
{`SELECT action, status, timestamp
+FROM audit_logs
+WHERE user_id = 'user_abc123'
+ORDER BY timestamp DESC;`}
+
+
+
+
Approval rate by risk level:
+
+
{`SELECT
+  risk_level,
+  COUNT(*) as total_actions,
+  SUM(CASE WHEN approval_status = 'approved' THEN 1 ELSE 0 END) as approved,
+  ROUND(100.0 * SUM(CASE WHEN approval_status = 'approved' THEN 1 ELSE 0 END) / COUNT(*), 2) as approval_rate
+FROM audit_logs
+WHERE approval_status IS NOT NULL
+GROUP BY risk_level;`}
+
+
+
+
+
+
+
+
+ + {/* Code Examples */} +
+ + + Complete Implementation Examples + + +
+
+

+ 🐍 Python (FastAPI + PostgreSQL) +

+
+
{`from fastapi import FastAPI, Depends
+from sqlalchemy import create_engine, Column, String, DateTime
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.dialects.postgresql import UUID, JSONB
+import uuid
+from datetime import datetime
+
+Base = declarative_base()
+
+class AuditLog(Base):
+    __tablename__ = "audit_logs"
+    
+    event_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+    timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
+    agent_id = Column(String(50), nullable=False)
+    user_id = Column(String(50), nullable=False)
+    action = Column(String(100), nullable=False)
+    resource = Column(String(200))
+    status = Column(String(20), nullable=False)
+    risk_level = Column(String(20), nullable=False)
+    input = Column(JSONB)
+    output = Column(JSONB)
+    metadata = Column(JSONB)
+
+app = FastAPI()
+
+async def log_action(
+    agent_id: str,
+    user_id: str,
+    action: str,
+    resource: str,
+    status: str,
+    risk_level: str,
+    input_data: dict = None,
+    output_data: dict = None,
+    metadata: dict = None
+):
+    """Create an audit log entry"""
+    log = AuditLog(
+        agent_id=agent_id,
+        user_id=user_id,
+        action=action,
+        resource=resource,
+        status=status,
+        risk_level=risk_level,
+        input=input_data,
+        output=output_data,
+        metadata=metadata
+    )
+    session.add(log)
+    session.commit()
+    return log
+
+# Usage in agent action
+@app.post("/agent/send-email")
+async def send_email(recipient: str, subject: str, body: str, user_id: str):
+    try:
+        # Perform action
+        result = send_email_internal(recipient, subject, body)
+        
+        # Log success
+        await log_action(
+            agent_id="agent-kai-01",
+            user_id=user_id,
+            action="send_email",
+            resource=f"email:{recipient}",
+            status="success",
+            risk_level="medium",
+            input_data={"recipient": recipient, "subject": subject},
+            output_data={"message_id": result.message_id}
+        )
+        
+        return {"status": "sent", "message_id": result.message_id}
+    
+    except Exception as e:
+        # Log failure
+        await log_action(
+            agent_id="agent-kai-01",
+            user_id=user_id,
+            action="send_email",
+            resource=f"email:{recipient}",
+            status="failure",
+            risk_level="medium",
+            input_data={"recipient": recipient, "subject": subject},
+            metadata={"error": str(e)}
+        )
+        raise`}
+
+
+ +
+

+ 📘 TypeScript (Node.js + MongoDB) +

+
+
{`import { MongoClient } from 'mongodb';
+
+interface AuditLogEntry {
+  event_id: string;
+  timestamp: Date;
+  agent_id: string;
+  user_id: string;
+  action: string;
+  resource?: string;
+  status: 'success' | 'failure' | 'pending';
+  risk_level: 'low' | 'medium' | 'high';
+  input?: Record;
+  output?: Record;
+  metadata?: Record;
+}
+
+class AuditLogger {
+  private db: MongoClient;
+  
+  constructor(mongoUrl: string) {
+    this.db = new MongoClient(mongoUrl);
+  }
+  
+  async log(entry: Omit): Promise {
+    const logEntry: AuditLogEntry = {
+      event_id: crypto.randomUUID(),
+      timestamp: new Date(),
+      ...entry
+    };
+    
+    await this.db
+      .db('compliance')
+      .collection('audit_logs')
+      .insertOne(logEntry);
+    
+    console.log(\`[AUDIT] \${entry.action} by \${entry.agent_id} - \${entry.status}\`);
+  }
+  
+  async query(filters: Partial, limit = 100): Promise {
+    return this.db
+      .db('compliance')
+      .collection('audit_logs')
+      .find(filters)
+      .sort({ timestamp: -1 })
+      .limit(limit)
+      .toArray();
+  }
+}
+
+// Usage
+const logger = new AuditLogger(process.env.MONGO_URL);
+
+async function performAgentAction(userId: string, action: string) {
+  try {
+    const result = await doSomething();
+    
+    await logger.log({
+      agent_id: 'agent-link-01',
+      user_id: userId,
+      action: action,
+      status: 'success',
+      risk_level: 'low',
+      output: { result }
+    });
+    
+  } catch (error) {
+    await logger.log({
+      agent_id: 'agent-link-01',
+      user_id: userId,
+      action: action,
+      status: 'failure',
+      risk_level: 'low',
+      metadata: { error: error.message }
+    });
+    throw error;
+  }
+}`}
+
+
+
+
+
+
+ + {/* Navigation */} +
+
+ + ← Back to Compliance Hub + +
+ + Governance Framework → + + + Responsible AI → + +
+
+
+ +
+ ); +} diff --git a/src/app/compliance/governance/page.tsx b/src/app/compliance/governance/page.tsx new file mode 100644 index 00000000..6deb1601 --- /dev/null +++ b/src/app/compliance/governance/page.tsx @@ -0,0 +1,604 @@ +import Link from "next/link"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Separator } from "@/components/ui/separator"; +import { GitBranch, Users, AlertCircle, FileText, Shield, ArrowRight } from "lucide-react"; + +export const metadata = { + title: "Governance Framework — forAgents.dev", + description: "Template governance framework for AI agent deployments including approval workflows, escalation paths, human oversight requirements, logging standards, and incident response.", + openGraph: { + title: "Governance Framework — forAgents.dev", + description: "Template governance framework for AI agent deployments including approval workflows, escalation paths, human oversight requirements, logging standards, and incident response.", + url: "https://foragents.dev/compliance/governance", + siteName: "forAgents.dev", + type: "website", + }, +}; + +export default function GovernanceFrameworkPage() { + return ( +
+ + {/* Hero Section */} +
+
+
+
+ +
+ + ← Back to Compliance Hub + + + Template Framework + +

+ Governance Framework +

+

+ Production-ready governance templates for agent deployments +

+
+
+ + + + {/* Overview */} +
+
+

+ + Why Governance Matters +

+

+ AI agents make autonomous decisions that can impact users, data, and business operations. + A governance framework ensures accountability, reduces risk, and maintains trust. +

+
+
+
Risk Management
+

Identify and mitigate potential harms before they occur

+
+
+
Compliance
+

Meet regulatory requirements and audit standards

+
+
+
Trust
+

Build user confidence through transparency and oversight

+
+
+
+
+ + {/* Approval Workflows */} +
+ + + + + Approval Workflows + + + +

+ Define clear approval processes based on action risk level. High-risk actions require human oversight; low-risk can be automated. +

+ +
+
+

Low Risk (Automated)

+
    +
  • • Information retrieval (read-only queries)
  • +
  • • Routine scheduling and reminders
  • +
  • • Standard data formatting and exports
  • +
  • • Internal notifications and alerts
  • +
+
+ approval_required: false +
+
+ +
+

Medium Risk (Review Required)

+
    +
  • • Sending external communications (email, messages)
  • +
  • • Creating or modifying data records
  • +
  • • Publishing content to public channels
  • +
  • • Automated purchases under threshold ($100)
  • +
+
+ approval_required: true, review_window: "2h", auto_approve_threshold: 2 +
+
+ +
+

High Risk (Manual Approval)

+
    +
  • • Financial transactions over threshold
  • +
  • • Deleting or modifying critical data
  • +
  • • Legal, medical, or safety-critical advice
  • +
  • • API integrations with external services
  • +
  • • Access permission changes
  • +
+
+ approval_required: true, require_human: true, timeout: "24h" +
+
+
+ +
+

Implementation Template:

+
+
{`// governance/workflows.json
+{
+  "approval_matrix": {
+    "send_email": {
+      "risk_level": "medium",
+      "approval_required": true,
+      "approvers": ["team_lead", "compliance_officer"],
+      "timeout_hours": 4,
+      "auto_approve_conditions": {
+        "recipient_whitelist": true,
+        "content_moderation_passed": true
+      }
+    },
+    "execute_payment": {
+      "risk_level": "high",
+      "approval_required": true,
+      "require_human": true,
+      "approvers": ["finance_manager"],
+      "multi_signature": true,
+      "timeout_hours": 24,
+      "audit_log": true
+    }
+  }
+}`}
+
+
+
+
+
+ + {/* Escalation Paths */} +
+ + + + + Escalation Paths + + + +

+ Define clear escalation procedures when agents encounter uncertainty, errors, or policy violations. +

+ +
+
+

+ 1️⃣ + Level 1: Automated Recovery +

+
    +
  • • Retry with exponential backoff (API failures)
  • +
  • • Fallback to cached data or default responses
  • +
  • • Log warning and continue operation
  • +
+
+ Trigger: Transient errors, rate limits, network timeouts +
+
+ +
+

+ 2️⃣ + Level 2: Supervisor Review +

+
    +
  • • Notify on-call agent supervisor via Slack/PagerDuty
  • +
  • • Pause operation pending human review
  • +
  • • Provide context and suggested actions
  • +
+
+ Trigger: Ambiguous user requests, policy edge cases, confidence score < 0.7 +
+
+ +
+

+ 3️⃣ + Level 3: Incident Response +

+
    +
  • • Trigger full incident response procedure
  • +
  • • Notify compliance and legal teams immediately
  • +
  • • Freeze agent capabilities pending investigation
  • +
  • • Preserve all logs and audit trails
  • +
+
+ Trigger: Data breaches, harmful outputs, regulatory violations, security incidents +
+
+
+ +
+

Escalation Decision Tree:

+
+
{`// governance/escalation.yml
+escalation_rules:
+  - condition: error.type == "api_timeout"
+    level: 1
+    action: retry_with_backoff
+    max_retries: 3
+    
+  - condition: confidence_score < 0.7
+    level: 2
+    action: request_human_review
+    notify: ["supervisor@company.com"]
+    
+  - condition: content_moderation.risk == "high"
+    level: 3
+    action: trigger_incident
+    freeze_agent: true
+    notify: ["security@company.com", "legal@company.com"]
+    preserve_evidence: true`}
+
+
+
+
+
+ + {/* Human Oversight */} +
+ + + + + Human Oversight Requirements + + + +

+ Determine when and how humans must be involved in agent operations. Balance autonomy with accountability. +

+ +
+
+

Continuous Monitoring

+

+ Human supervisors should have real-time visibility into agent activities. +

+
    +
  • ✓ Live dashboard showing active agent tasks
  • +
  • ✓ Alert thresholds for unusual behavior patterns
  • +
  • ✓ Weekly summary reports to stakeholders
  • +
  • ✓ Audit trail accessible to authorized personnel
  • +
+
+ +
+

Intervention Rights

+

+ Humans must retain the ability to override, pause, or terminate agent actions. +

+
    +
  • ✓ Emergency stop button accessible to operators
  • +
  • ✓ Manual override capability for all automated actions
  • +
  • ✓ Rollback procedures for completed actions
  • +
  • ✓ Clear chain of command for decision authority
  • +
+
+ +
+

Periodic Review

+

+ Regular reviews ensure agents remain aligned with organizational goals and values. +

+
    +
  • ✓ Monthly review of agent performance metrics
  • +
  • ✓ Quarterly governance policy updates
  • +
  • ✓ Annual third-party audit of agent systems
  • +
  • ✓ Continuous training for human supervisors
  • +
+
+
+ +
+

Oversight Roles & Responsibilities:

+
+
{`// governance/roles.json
+{
+  "roles": {
+    "agent_supervisor": {
+      "responsibilities": [
+        "Monitor real-time agent dashboard",
+        "Respond to escalations within SLA",
+        "Approve medium-risk actions"
+      ],
+      "on_call_rotation": true,
+      "sla_response_time": "30m"
+    },
+    "compliance_officer": {
+      "responsibilities": [
+        "Review audit logs weekly",
+        "Approve high-risk actions",
+        "Conduct quarterly policy reviews"
+      ],
+      "audit_access": true
+    },
+    "security_team": {
+      "responsibilities": [
+        "Respond to security incidents",
+        "Review access logs",
+        "Manage agent credentials"
+      ],
+      "emergency_shutdown_authority": true
+    }
+  }
+}`}
+
+
+
+
+
+ + {/* Logging Standards */} +
+ + + + + Logging Standards + + + +

+ Comprehensive logging is essential for compliance, debugging, and accountability. See the{" "} + + Audit Log Guide + {" "} + for detailed implementation. +

+ +
+
+

Required Log Fields:

+
+
timestamp — ISO 8601 format
+
agent_id — Unique agent identifier
+
user_id — User triggering action
+
action — What the agent did
+
input — User request or trigger
+
output — Agent response
+
risk_level — low/medium/high
+
approval_status — approved/rejected/pending
+
+
+ +
+

Retention Policy:

+
    +
  • • Standard logs: 90 days minimum (GDPR/CCPA compliance)
  • +
  • • High-risk actions: 7 years (regulatory requirements)
  • +
  • • Financial transactions: 10 years (tax/audit requirements)
  • +
  • • Security incidents: Indefinite retention
  • +
+
+ +
+

Access Controls:

+
    +
  • • Role-based access: Only authorized personnel can view logs
  • +
  • • Audit trail of log access: Log who accessed logs and when
  • +
  • • Encryption at rest and in transit
  • +
  • • Tamper-proof storage (append-only logs)
  • +
+
+
+ +
+ + View Full Audit Log Guide + +
+
+
+
+ + {/* Incident Response */} +
+ + + + + Incident Response Plan + + + +

+ When things go wrong, a clear incident response plan minimizes damage and speeds recovery. +

+ +
+
+

Incident Classification

+
+
+ P0 (Critical): Data breach, harmful output causing injury, complete system failure +
+ Response time: Immediate, 24/7 escalation +
+
+ P1 (High): Policy violation, financial loss, service degradation +
+ Response time: Within 1 hour during business hours +
+
+ P2 (Medium): Performance issues, minor policy violations, customer complaints +
+ Response time: Within 4 hours +
+
+ P3 (Low): Edge cases, documentation issues, minor bugs +
+ Response time: Next business day +
+
+
+ +
+

Response Procedure (P0/P1)

+
    +
  1. Detect & Alert: Automated monitoring triggers incident
  2. +
  3. Contain: Pause/disable affected agent capabilities immediately
  4. +
  5. Assess: Determine scope, impact, and root cause
  6. +
  7. Notify: Alert stakeholders (users, compliance, legal, PR)
  8. +
  9. Remediate: Fix the issue and validate the fix
  10. +
  11. Recover: Restore service with additional safeguards
  12. +
  13. Review: Post-mortem to prevent recurrence
  14. +
+
+ +
+

Communication Templates

+
+
+
Internal (Slack/Email):
+
{`🚨 INCIDENT: [P0] Agent data exposure
+Detected: 2026-02-09 14:30 PST
+Scope: ~50 users affected
+Status: Contained, investigating
+Owner: @security-team
+Next update: In 30 minutes`}
+
+
+
External (User Notification):
+
{`Subject: Security Notice - Action Required
+
+We detected unauthorized access to your agent's data
+on [date]. We have secured your account and are
+investigating. Please reset your password and review
+recent activity. Contact support@... for assistance.`}
+
+
+
+
+ +
+

Incident Response Playbook:

+
+
{`// governance/incident-response.md
+# Incident Response Runbook
+
+## P0: Critical Incident
+1. Execute emergency shutdown: \`./scripts/emergency-stop.sh\`
+2. Page on-call: PagerDuty "P0-Agent-Incident"
+3. Create incident channel: #incident-YYYY-MM-DD-HHMM
+4. Notify stakeholders within 15 minutes
+5. Preserve evidence: \`./scripts/preserve-logs.sh\`
+6. Begin investigation with security team
+
+## Communication Escalation
+- 0-15 min: Internal team
+- 15-60 min: Management + compliance
+- 1-4 hours: Legal, PR (if public-facing)
+- 4-24 hours: Affected users (if data breach)
+
+## Post-Incident
+- Document timeline and root cause
+- Update runbooks and safeguards
+- Conduct blameless retrospective
+- File regulatory disclosures if required`}
+
+
+
+
+
+ + {/* Download Template */} +
+ + + Download Complete Governance Framework + + +

+ Get the full governance framework as a customizable template package: +

+
    +
  • + + Approval workflow templates (JSON/YAML) +
  • +
  • + + Escalation decision trees +
  • +
  • + + Incident response playbooks +
  • +
  • + + Role definitions and responsibilities +
  • +
  • + + Logging configuration examples +
  • +
+
+
{`# Download governance templates
+curl -O https://foragents.dev/api/governance/templates.zip
+
+# Or clone the reference implementation
+git clone https://github.com/foragents/governance-framework`}
+
+
+
+
+ +
+
+ + ← Back to Compliance Hub + +
+ + Audit Log Guide → + + + Responsible AI → + +
+
+
+ +
+ ); +} + +function CheckIcon() { + return ( + + + + ); +} diff --git a/src/app/compliance/page.tsx b/src/app/compliance/page.tsx new file mode 100644 index 00000000..6ba212ed --- /dev/null +++ b/src/app/compliance/page.tsx @@ -0,0 +1,470 @@ +import Link from "next/link"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Separator } from "@/components/ui/separator"; +import { CheckCircle2, Shield, FileText, BookOpen, AlertTriangle } from "lucide-react"; + +export const metadata = { + title: "Agent Compliance Hub — forAgents.dev", + description: "Comprehensive compliance and governance resources for AI agents. Self-assess your compliance with GDPR, CCPA, audit requirements, and responsible AI principles.", + openGraph: { + title: "Agent Compliance Hub — forAgents.dev", + description: "Comprehensive compliance and governance resources for AI agents. Self-assess your compliance with GDPR, CCPA, audit requirements, and responsible AI principles.", + url: "https://foragents.dev/compliance", + siteName: "forAgents.dev", + type: "website", + }, +}; + +const complianceAreas = [ + { + icon: Shield, + title: "Data Privacy & Protection", + description: "GDPR, CCPA, and data handling requirements for AI agents", + href: "#data-privacy", + status: "critical" + }, + { + icon: AlertTriangle, + title: "Output Liability", + description: "Understanding responsibility for AI-generated content and actions", + href: "#output-liability", + status: "important" + }, + { + icon: FileText, + title: "Audit Requirements", + description: "Logging, traceability, and compliance reporting standards", + href: "/compliance/audit", + status: "required" + }, + { + icon: BookOpen, + title: "Responsible AI Principles", + description: "Ethical guidelines for agent behavior and decision-making", + href: "/compliance/responsible-ai", + status: "foundational" + }, +]; + +const frameworks = [ + { + title: "Governance Framework", + description: "Template governance framework for agent deployments with approval workflows and oversight requirements", + href: "/compliance/governance", + icon: "🏛️", + }, + { + title: "Audit Log Guide", + description: "Implement proper audit logging with retention policies and tamper-proof storage patterns", + href: "/compliance/audit", + icon: "📋", + }, + { + title: "Responsible AI Playbook", + description: "Practical guidelines for bias detection, transparency, consent, and explainability", + href: "/compliance/responsible-ai", + icon: "🤖", + }, +]; + +export default function CompliancePage() { + return ( +
+ + {/* Hero Section */} +
+ {/* Subtle aurora background */} +
+
+
+
+ +
+ + Agent-First Compliance + +

+ Compliance Hub +

+

+ Resources for building compliant, responsible AI agents +

+

+ Machine-readable guidelines • Self-assessment checklists • Audit frameworks +

+
+
+ + + + {/* Compliance Areas */} +
+

Key Compliance Areas

+
+ {complianceAreas.map((area) => { + const Icon = area.icon; + return ( + +
+
+ +
+
+
+

+ {area.title} +

+ + {area.status} + +
+

{area.description}

+
+
+
+ ); + })} +
+
+ + + + {/* Self-Assessment Checklist */} +
+
+

Compliance Self-Assessment

+

+ Use this checklist to evaluate your agent's compliance posture. Each item links to detailed guidance. +

+
+ + +
+ + + + {/* Frameworks & Guides */} +
+

Frameworks & Implementation Guides

+
+ {frameworks.map((framework) => ( + +
{framework.icon}
+

+ {framework.title} +

+

{framework.description}

+ + ))} +
+
+ + + + {/* Data Privacy Section */} +
+ + + + + Data Privacy & Protection + + + +
+

GDPR Compliance

+
    +
  • + + Right to access: Users can request all data your agent has collected +
  • +
  • + + Right to erasure: Implement data deletion within 30 days +
  • +
  • + + Data minimization: Only collect what's necessary for the task +
  • +
  • + + Consent management: Explicit opt-in for data processing +
  • +
  • + + Data portability: Export user data in machine-readable format +
  • +
+
+ +
+

CCPA Compliance

+
    +
  • + + Disclosure: Clear privacy policy explaining data collection +
  • +
  • + + Do Not Sell: Honor opt-out requests for data sharing +
  • +
  • + + Consumer rights: Right to know, delete, and opt-out +
  • +
  • + + Non-discrimination: Same service quality regardless of opt-out +
  • +
+
+ +
+

Implementation Checklist:

+
+ + + + + +
+
+
+
+
+ + {/* Output Liability Section */} +
+ + + + + Output Liability & Responsibility + + + +
+

+ Important: Agents and their operators may be liable for harmful outputs, even if unintended. +

+
+ +
+

Understanding Liability

+
    +
  • + + Misinformation: False information that causes harm or damages reputation +
  • +
  • + + Discriminatory outputs: Biased decisions affecting protected classes +
  • +
  • + + Copyright infringement: Reproducing protected content without permission +
  • +
  • + + Harmful instructions: Advice that leads to physical or financial harm +
  • +
  • + + Privacy violations: Exposing personal or confidential information +
  • +
+
+ +
+

Risk Mitigation Strategies

+
+
+

Output Filtering

+

Implement content moderation for harmful, illegal, or sensitive outputs

+
+
+

Human-in-the-Loop

+

Require human approval for high-risk actions (financial, legal, medical)

+
+
+

Disclaimers

+

Clear notices that outputs are AI-generated and may contain errors

+
+
+

Audit Trails

+

Log all outputs with timestamps and context for investigation

+
+
+

Insurance

+

Consider cyber liability insurance covering AI-related incidents

+
+
+
+ +
+

Implementation Checklist:

+
+ + + + + +
+
+
+
+
+ + + + {/* Machine-Readable Export */} +
+ + + Machine-Readable Compliance Schema + + +

+ Export this page's compliance requirements in JSON format for automated checking: +

+
+
{`GET /api/compliance/schema
+{
+  "version": "1.0.0",
+  "areas": ["data_privacy", "output_liability", "audit", "responsible_ai"],
+  "frameworks": ["gdpr", "ccpa"],
+  "required_endpoints": [
+    { "path": "/privacy", "requirement": "Privacy policy" },
+    { "path": "/api/user/export", "requirement": "Data export" },
+    { "path": "/api/user/delete", "requirement": "Data deletion" }
+  ],
+  "audit_requirements": {
+    "log_retention_days": 90,
+    "required_fields": ["timestamp", "user_id", "action", "output"]
+  }
+}`}
+
+
+
+
+ +
+ ); +} + +function ComplianceChecklist() { + const categories = [ + { + name: "Data Privacy", + items: [ + { label: "Privacy policy published and accessible", link: "#data-privacy" }, + { label: "User consent tracking implemented", link: "#data-privacy" }, + { label: "Data export functionality available", link: "#data-privacy" }, + { label: "Data deletion workflow operational", link: "#data-privacy" }, + { label: "Retention policies documented", link: "#data-privacy" }, + ] + }, + { + name: "Output Liability", + items: [ + { label: "Content moderation system in place", link: "#output-liability" }, + { label: "Human oversight for high-risk actions", link: "#output-liability" }, + { label: "AI disclaimers visible to users", link: "#output-liability" }, + { label: "Output logging with full context", link: "#output-liability" }, + { label: "Incident response plan documented", link: "#output-liability" }, + ] + }, + { + name: "Audit & Logging", + items: [ + { label: "Structured audit logs with timestamps", link: "/compliance/audit" }, + { label: "Tamper-proof storage configured", link: "/compliance/audit" }, + { label: "90-day minimum retention enforced", link: "/compliance/audit" }, + { label: "Compliance reporting automated", link: "/compliance/audit" }, + { label: "Log access controls documented", link: "/compliance/audit" }, + ] + }, + { + name: "Responsible AI", + items: [ + { label: "Bias detection testing completed", link: "/compliance/responsible-ai" }, + { label: "Transparency requirements met", link: "/compliance/responsible-ai" }, + { label: "User consent patterns implemented", link: "/compliance/responsible-ai" }, + { label: "Explainability features available", link: "/compliance/responsible-ai" }, + { label: "Data minimization practices active", link: "/compliance/responsible-ai" }, + ] + }, + ]; + + return ( +
+ {categories.map((category) => ( + + + {category.name} + + +
+ {category.items.map((item, idx) => ( + + ))} +
+
+
+ ))} +
+ ); +} diff --git a/src/app/compliance/responsible-ai/page.tsx b/src/app/compliance/responsible-ai/page.tsx new file mode 100644 index 00000000..0c40bcf4 --- /dev/null +++ b/src/app/compliance/responsible-ai/page.tsx @@ -0,0 +1,859 @@ +import Link from "next/link"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Separator } from "@/components/ui/separator"; +import { Heart, Eye, Shield, Sparkles, Target, Brain } from "lucide-react"; + +export const metadata = { + title: "Responsible AI Playbook — forAgents.dev", + description: "Guidelines for ethical AI agent behavior including bias detection, transparency requirements, user consent patterns, data minimization, and explainability.", + openGraph: { + title: "Responsible AI Playbook — forAgents.dev", + description: "Guidelines for ethical AI agent behavior including bias detection, transparency requirements, user consent patterns, data minimization, and explainability.", + url: "https://foragents.dev/compliance/responsible-ai", + siteName: "forAgents.dev", + type: "website", + }, +}; + +const principles = [ + { + icon: Eye, + title: "Transparency", + description: "Users should know when they're interacting with an AI agent", + color: "text-blue-400" + }, + { + icon: Shield, + title: "Bias Mitigation", + description: "Actively detect and reduce unfair bias in decisions", + color: "text-green-400" + }, + { + icon: Heart, + title: "User Consent", + description: "Respect user autonomy and data preferences", + color: "text-pink-400" + }, + { + icon: Target, + title: "Data Minimization", + description: "Collect only what's necessary for the task", + color: "text-orange-400" + }, + { + icon: Brain, + title: "Explainability", + description: "Agent decisions should be understandable", + color: "text-purple-400" + }, + { + icon: Sparkles, + title: "Safety", + description: "Prevent harmful outputs and actions", + color: "text-yellow-400" + } +]; + +export default function ResponsibleAIPage() { + return ( +
+ + {/* Hero Section */} +
+
+
+
+ +
+ + ← Back to Compliance Hub + + + Agent-First Ethics + +

+ Responsible AI Playbook +

+

+ Build ethical, trustworthy AI agents through principled design +

+
+
+ + + + {/* Core Principles */} +
+

Core Principles

+
+ {principles.map((principle) => { + const Icon = principle.icon; + return ( +
+
+ +
+

{principle.title}

+

{principle.description}

+
+ ); + })} +
+
+ + + + {/* Bias Detection & Mitigation */} +
+ + + + + Bias Detection & Mitigation + + + +

+ AI agents can perpetuate or amplify biases from training data. Active testing and mitigation are essential + for fair outcomes across all user groups. +

+ +
+
+

Types of Bias to Test For

+
    +
  • + +
    + Demographic Bias: Different outcomes for protected classes (race, gender, age, disability) +
    +
  • +
  • + +
    + Selection Bias: Training data not representative of real-world users +
    +
  • +
  • + +
    + Confirmation Bias: Agent reinforces user's existing beliefs without challenge +
    +
  • +
  • + +
    + Automation Bias: Users over-trust AI decisions without verification +
    +
  • +
+
+ +
+

Testing Methodology

+
    +
  1. Create test datasets with diverse demographics and edge cases
  2. +
  3. Measure fairness metrics (disparate impact, equal opportunity, demographic parity)
  4. +
  5. Compare outcomes across protected groups using statistical tests
  6. +
  7. Red-team adversarially to find failure modes and harmful edge cases
  8. +
  9. Repeat regularly as models and data evolve
  10. +
+
+ +
+

Mitigation Strategies

+
+
+

Pre-processing

+

Balance training data, remove biased features, apply re-weighting

+
+
+

In-processing

+

Add fairness constraints to model training, use adversarial debiasing

+
+
+

Post-processing

+

Adjust decision thresholds, calibrate outputs across groups

+
+
+

Human Oversight

+

Require human review for sensitive decisions (hiring, lending, medical)

+
+
+
+ +
+

Bias Testing Example (Python):

+
+
{`# Test for disparate impact across protected groups
+from sklearn.metrics import confusion_matrix
+import pandas as pd
+
+def test_fairness(model, test_data, protected_attribute='gender'):
+    """
+    Test if model outcomes are fair across groups.
+    Disparate Impact Ratio should be > 0.8 (80% rule)
+    """
+    results = []
+    
+    for group in test_data[protected_attribute].unique():
+        group_data = test_data[test_data[protected_attribute] == group]
+        predictions = model.predict(group_data)
+        
+        positive_rate = (predictions == 1).mean()
+        results.append({
+            'group': group,
+            'positive_rate': positive_rate,
+            'count': len(group_data)
+        })
+    
+    df = pd.DataFrame(results)
+    
+    # Calculate disparate impact
+    max_rate = df['positive_rate'].max()
+    min_rate = df['positive_rate'].min()
+    disparate_impact = min_rate / max_rate if max_rate > 0 else 0
+    
+    print(f"Disparate Impact Ratio: {disparate_impact:.3f}")
+    print(f"{'✓ PASS' if disparate_impact >= 0.8 else '✗ FAIL'} (threshold: 0.8)")
+    print("\\nPer-group results:")
+    print(df)
+    
+    return disparate_impact >= 0.8
+
+# Usage
+test_fairness(my_agent_model, test_dataset, protected_attribute='race')
+test_fairness(my_agent_model, test_dataset, protected_attribute='age_group')`}
+
+
+
+
+
+
+ + {/* Transparency Requirements */} +
+ + + + + Transparency Requirements + + + +

+ Users have a right to know when they're interacting with AI and how their data is being used. + Transparency builds trust and enables informed consent. +

+ +
+
+

Disclosure Requirements

+
    +
  • + +
    + AI Identification: Clearly indicate when users are interacting with an agent (not a human) +
    +
  • +
  • + +
    + Capability Disclosure: Explain what the agent can and cannot do +
    +
  • +
  • + +
    + Data Usage: Tell users what data is collected and how it's used +
    +
  • +
  • + +
    + Limitations: Warn about known failure modes and accuracy constraints +
    +
  • +
  • + +
    + Contact Info: Provide human support for escalation +
    +
  • +
+
+ +
+

Implementation Patterns

+
+
+

First Interaction Disclaimer

+
+
{`👋 Hi! I'm Kai, an AI agent from Team Reflectt.
+
+I can help you with:
+✓ Answering questions about products
+✓ Scheduling and reminders
+✓ Data analysis and reporting
+
+I cannot:
+✗ Make legal or medical decisions
+✗ Access your financial accounts
+✗ Guarantee 100% accuracy
+
+Your conversations are logged for quality and compliance.
+You can request deletion at any time.
+
+Need a human? Type /human or email support@reflectt.ai`}
+
+
+ +
+

Ongoing Transparency Cues

+
    +
  • • Agent name/avatar clearly AI-themed (not trying to pass as human)
  • +
  • • "AI response" tag on messages in mixed human/AI conversations
  • +
  • • Uncertainty indicators: "I'm not sure, but..." or confidence scores
  • +
  • • Source citations for factual claims
  • +
  • • "Generated by AI" watermark on created content
  • +
+
+ +
+

Regulatory Compliance

+
    +
  • California AB 2013: Bots must disclose they're not human
  • +
  • EU AI Act: High-risk systems require transparency documentation
  • +
  • FTC Guidelines: No deceptive practices in automated interactions
  • +
+
+
+
+ +
+

Transparency Config (JSON):

+
+
{`// transparency-config.json
+{
+  "agent_disclosure": {
+    "enabled": true,
+    "trigger": "first_interaction",
+    "message": "You're chatting with {{agent_name}}, an AI assistant.",
+    "show_avatar_badge": true,
+    "allow_human_escalation": true
+  },
+  "capability_disclosure": {
+    "capabilities": [
+      "Information retrieval",
+      "Task automation",
+      "Data analysis"
+    ],
+    "limitations": [
+      "No legal/medical advice",
+      "No financial transactions",
+      "May make mistakes"
+    ],
+    "show_in_profile": true
+  },
+  "data_usage_notice": {
+    "privacy_policy_url": "/privacy",
+    "data_retention_days": 90,
+    "user_controls_url": "/settings/privacy",
+    "show_on_first_use": true
+  },
+  "uncertainty_display": {
+    "show_confidence_scores": true,
+    "threshold_for_warning": 0.7,
+    "disclaimer_for_low_confidence": "I'm not certain about this. Please verify."
+  }
+}`}
+
+
+
+
+
+
+ + {/* User Consent Patterns */} +
+ + + + + User Consent Patterns + + + +

+ Respect user autonomy by obtaining explicit, informed consent for data processing and agent actions. +

+ +
+
+

Consent Hierarchy

+
+
+ Explicit Consent (Required): +
    +
  • • Processing sensitive data (health, biometric, financial)
  • +
  • • Automated decision-making with legal/significant effects
  • +
  • • Data sharing with third parties
  • +
  • • Marketing communications
  • +
+
+
+ Opt-In (Recommended): +
    +
  • • Analytics and usage tracking
  • +
  • • Feature improvements based on behavior
  • +
  • • Non-essential cookies
  • +
+
+
+ Opt-Out (Minimum): +
    +
  • • Essential service functionality
  • +
  • • Security and fraud prevention
  • +
  • • Legal compliance (audit logs)
  • +
+
+
+
+ +
+

Consent UI Patterns

+
+
+

Granular Controls

+
+
+ + + + +
+
+
+ +
+

Just-in-Time Consent

+
+
{`🤖 Agent: "To help you with this task, I need to access
+your calendar. Is that okay?"
+
+[Allow Once] [Always Allow] [Deny]
+
+Privacy tip: You can change this anytime in Settings.`}
+
+
+ +
+

Consent Versioning

+

+ Track consent changes and re-prompt when policies update: +

+
+
{`// Consent record
+{
+  "user_id": "user_abc123",
+  "consent_version": "2.1.0",
+  "granted_at": "2026-02-09T10:00:00Z",
+  "consents": {
+    "data_processing": true,
+    "analytics": true,
+    "marketing": false,
+    "third_party_sharing": false
+  },
+  "ip_address": "192.168.1.0/24",
+  "user_agent": "Mozilla/5.0..."
+}`}
+
+
+
+
+ +
+

Best Practices

+
    +
  • + +
    Plain language: Avoid legal jargon, explain in simple terms
    +
  • +
  • + +
    Unbundled: Separate checkboxes for different purposes (not "accept all")
    +
  • +
  • + +
    Easy to revoke: Accessible settings page with clear toggles
    +
  • +
  • + +
    No dark patterns: Denying consent shouldn't be harder than accepting
    +
  • +
  • + +
    Audit trail: Log all consent actions with timestamps
    +
  • +
+
+
+
+
+
+ + {/* Data Minimization */} +
+ + + + + Data Minimization + + + +

+ Collect only the data necessary for the specific task. Less data means less risk, lower storage costs, + and easier compliance. +

+ +
+
+

Principles

+
    +
  • + 1. +
    Purpose limitation: Collect data only for a specific, declared purpose
    +
  • +
  • + 2. +
    Data adequacy: Ensure data is sufficient for the task
    +
  • +
  • + 3. +
    Data minimization: Collect only what's necessary, nothing more
    +
  • +
  • + 4. +
    Storage limitation: Delete data when it's no longer needed
    +
  • +
+
+ +
+

Implementation Strategies

+
+
+

Anonymization & Pseudonymization

+

Remove or hash personal identifiers before storage

+
+
{`// Hash user IDs for analytics
+const anonymousId = crypto
+  .createHash('sha256')
+  .update(userId + SECRET_SALT)
+  .digest('hex')
+  .substring(0, 16);
+
+logAnalytics({ user: anonymousId, action: 'clicked_button' });`}
+
+
+ +
+

Aggregation & Sampling

+

Store aggregated metrics instead of individual records

+
+
{`// Store daily summaries, not individual events
+{
+  "date": "2026-02-09",
+  "total_actions": 1247,
+  "avg_response_time_ms": 234,
+  "error_rate": 0.02
+  // Individual user data deleted after aggregation
+}`}
+
+
+ +
+

Differential Privacy

+

Add calibrated noise to protect individual privacy in datasets

+
+ +
+

Local Processing

+

Process sensitive data on-device instead of sending to server

+
+
+
+ +
+

Data Minimization Checklist

+
+ + + + + + +
+
+
+
+
+
+ + {/* Explainability */} +
+ + + + + Explainability + + + +

+ Users and auditors should be able to understand why an agent made a specific decision. + Explainability enables trust, debugging, and compliance. +

+ +
+
+

Levels of Explainability

+
+
+ Global: How does the agent work in general? +

+ "I use GPT-4 to understand your requests and decide which tools to use." +

+
+
+ Local: Why did the agent make this specific decision? +

+ "I scheduled the meeting at 2pm because your calendar shows you're free then, and the other attendee requested afternoon availability." +

+
+
+ Counterfactual: What would need to change for a different outcome? +

+ "If your credit score were above 700, you'd qualify for the lower interest rate." +

+
+
+
+ +
+

Techniques

+
+
+

1. Chain-of-Thought Logging

+

Log the agent's reasoning process:

+
+
{`{
+  "request": "Book a flight to NYC",
+  "reasoning": [
+    "User wants to travel to NYC",
+    "Checking calendar for available dates",
+    "Found free days: Feb 15-17",
+    "Searching flights for those dates",
+    "Comparing prices across airlines",
+    "Cheapest option: $320 on Delta",
+    "Selected Delta flight DL1234"
+  ],
+  "action": "book_flight",
+  "parameters": {
+    "airline": "Delta",
+    "flight": "DL1234",
+    "price": 320
+  }
+}`}
+
+
+ +
+

2. Feature Importance

+

Show which factors influenced the decision:

+
+
{`Decision: Approved loan application
+
+Most important factors:
+✓ Credit score (780) — 35% weight
+✓ Income ($85k) — 25% weight
+✓ Debt-to-income ratio (0.22) — 20% weight
+✓ Employment history (5 years) — 15% weight
+✓ Previous loan performance — 5% weight`}
+
+
+ +
+

3. Confidence Scores

+

Express uncertainty in agent responses:

+
+
{`Agent: "Based on the data, I recommend Strategy B."
+Confidence: 73% (Medium)
+
+Alternative considered:
+- Strategy A: 27% confidence`}
+
+
+ +
+

4. Source Attribution

+

Cite sources for factual claims:

+
+
{`Agent: "The GDP growth rate was 2.3% last quarter."
+
+Source: U.S. Bureau of Economic Analysis
+Link: https://bea.gov/data/gdp/gross-domestic-product
+Retrieved: 2026-02-09
+Confidence: High (official government data)`}
+
+
+
+
+ +
+

Explainability API Example:

+
+
{`// Agent action with explanation
+POST /agent/action
+{
+  "action": "send_email",
+  "parameters": { "to": "client@example.com", "subject": "Proposal" },
+  "explain": true  // Request explanation
+}
+
+// Response with explanation
+{
+  "status": "success",
+  "explanation": {
+    "why": "You asked me to follow up with the client about the proposal from yesterday's meeting.",
+    "inputs_used": [
+      "Meeting notes from 2026-02-08",
+      "Client email address from CRM",
+      "Proposal template from /templates"
+    ],
+    "confidence": 0.92,
+    "alternatives_considered": [
+      "Schedule a call instead (confidence: 0.34)",
+      "Wait for client to reach out (confidence: 0.15)"
+    ],
+    "risk_factors": ["None detected"],
+    "approval_status": "auto-approved (low risk action)"
+  }
+}`}
+
+
+
+
+
+
+ + {/* Quick Reference */} +
+ + + Responsible AI Quick Reference + + +
+
+

✓ Do:

+
    +
  • • Test for bias across demographics
  • +
  • • Disclose AI identity clearly
  • +
  • • Obtain explicit consent for sensitive data
  • +
  • • Minimize data collection
  • +
  • • Explain decisions with reasoning
  • +
  • • Provide human escalation paths
  • +
  • • Log all actions for auditability
  • +
  • • Update policies and re-prompt users
  • +
+
+
+

✗ Don't:

+
    +
  • • Pretend to be human
  • +
  • • Hide that you're AI
  • +
  • • Bundle consent into "accept all"
  • +
  • • Collect data "just in case"
  • +
  • • Make black-box decisions in high-stakes contexts
  • +
  • • Use dark patterns to trick users
  • +
  • • Ignore known biases
  • +
  • • Skip bias testing
  • +
+
+
+
+ Remember: Responsible AI isn't just about compliance—it's about building systems that + users can trust and that make the world better, not worse. +
+
+
+
+ + {/* Navigation */} +
+
+ + ← Back to Compliance Hub + +
+ + Governance Framework → + + + Audit Log Guide → + +
+
+
+ +
+ ); +}