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 ( +
+ Build comprehensive, tamper-proof audit trails for AI agents +
++ Audit logs are the black box for AI agents. They provide accountability, enable debugging, + meet regulatory requirements, and support forensic investigations when incidents occur. +
+GDPR, HIPAA, SOX require detailed audit trails
+Trace decisions and identify failure points
+Detect unauthorized access and anomalies
+Demonstrate transparency to users and auditors
++ Comprehensive logging captures the full context of agent actions for auditability and debugging. +
+ +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
+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_code
+ Machine-readable error code
+error_message
+ Human-readable error description
+stack_trace
+ Full stack trace (debug builds)
+retry_count
+ Number of retry attempts
+{`{
+ "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"]
+ }
+}`}
+ + Balance compliance requirements, storage costs, and operational needs with tiered retention policies. +
+ ++ Routine agent actions with low risk (information retrieval, scheduling, notifications) +
++ High-risk actions (data modifications, external communications, approvals) +
++ Any action involving money (purchases, refunds, invoices, payments) +
++ Breach attempts, unauthorized access, policy violations, anomalies +
+{`-- 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()');`}
+ + Audit logs must be immutable and verifiable to meet compliance standards and support investigations. +
+ ++ 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
+ }
+ }
+ }'`}
+ + 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;
+}`}
+ + Use managed services designed for tamper-proof audit logs. +
++ Restrict who can read logs and audit all access. +
++ Transform audit logs into actionable reports for auditors, regulators, and stakeholders. +
+ +{`// 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()
+ )
+)`}
+ {`SELECT * FROM audit_logs
+WHERE risk_level = 'high'
+ AND timestamp > NOW() - INTERVAL '30 days'
+ORDER BY timestamp DESC;`}
+ {`SELECT action, status, timestamp
+FROM audit_logs
+WHERE user_id = 'user_abc123'
+ORDER BY timestamp DESC;`}
+ {`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;`}
+ {`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`}
+ {`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;
+ }
+}`}
+ + Production-ready governance templates for agent deployments +
++ AI agents make autonomous decisions that can impact users, data, and business operations. + A governance framework ensures accountability, reduces risk, and maintains trust. +
+Identify and mitigate potential harms before they occur
+Meet regulatory requirements and audit standards
+Build user confidence through transparency and oversight
++ Define clear approval processes based on action risk level. High-risk actions require human oversight; low-risk can be automated. +
+ +{`// 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
+ }
+ }
+}`}
+ + Define clear escalation procedures when agents encounter uncertainty, errors, or policy violations. +
+ +{`// 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`}
+ + Determine when and how humans must be involved in agent operations. Balance autonomy with accountability. +
+ ++ Human supervisors should have real-time visibility into agent activities. +
++ Humans must retain the ability to override, pause, or terminate agent actions. +
++ Regular reviews ensure agents remain aligned with organizational goals and values. +
+{`// 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
+ }
+ }
+}`}
+ + Comprehensive logging is essential for compliance, debugging, and accountability. See the{" "} + + Audit Log Guide + {" "} + for detailed implementation. +
+ +timestamp — ISO 8601 formatagent_id — Unique agent identifieruser_id — User triggering actionaction — What the agent didinput — User request or triggeroutput — Agent responserisk_level — low/medium/highapproval_status — approved/rejected/pending+ When things go wrong, a clear incident response plan minimizes damage and speeds recovery. +
+ +{`🚨 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`}
+ {`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.`}
+ {`// 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`}
+ + Get the full governance framework as a customizable template package: +
+{`# 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`}
+ + Resources for building compliant, responsible AI agents +
++ Machine-readable guidelines • Self-assessment checklists • Audit frameworks +
+{area.description}
++ Use this checklist to evaluate your agent's compliance posture. Each item links to detailed guidance. +
+{framework.description}
+ + ))} ++ Important: Agents and their operators may be liable for harmful outputs, even if unintended. +
+Implement content moderation for harmful, illegal, or sensitive outputs
+Require human approval for high-risk actions (financial, legal, medical)
+Clear notices that outputs are AI-generated and may contain errors
+Log all outputs with timestamps and context for investigation
+Consider cyber liability insurance covering AI-related incidents
++ 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"]
+ }
+}`}
+ + Build ethical, trustworthy AI agents through principled design +
+{principle.description}
++ AI agents can perpetuate or amplify biases from training data. Active testing and mitigation are essential + for fair outcomes across all user groups. +
+ +Balance training data, remove biased features, apply re-weighting
+Add fairness constraints to model training, use adversarial debiasing
+Adjust decision thresholds, calibrate outputs across groups
+Require human review for sensitive decisions (hiring, lending, medical)
+{`# 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')`}
+ + 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. +
+ +{`👋 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`}
+ {`// 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."
+ }
+}`}
+ + Respect user autonomy by obtaining explicit, informed consent for data processing and agent actions. +
+ +{`🤖 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.`}
+ + 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..."
+}`}
+ + Collect only the data necessary for the specific task. Less data means less risk, lower storage costs, + and easier compliance. +
+ +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' });`}
+ 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
+}`}
+ Add calibrated noise to protect individual privacy in datasets
+Process sensitive data on-device instead of sending to server
++ Users and auditors should be able to understand why an agent made a specific decision. + Explainability enables trust, debugging, and compliance. +
+ ++ "I use GPT-4 to understand your requests and decide which tools to use." +
++ "I scheduled the meeting at 2pm because your calendar shows you're free then, and the other attendee requested afternoon availability." +
++ "If your credit score were above 700, you'd qualify for the lower interest rate." +
+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
+ }
+}`}
+ 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`}
+ Express uncertainty in agent responses:
+{`Agent: "Based on the data, I recommend Strategy B."
+Confidence: 73% (Medium)
+
+Alternative considered:
+- Strategy A: 27% confidence`}
+ 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)`}
+ {`// 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)"
+ }
+}`}
+