/** * pi-comply — Regulatory Compliance Tracker * * EU AI Act risk classification, checklist generation, audit trail, compliance reports. * CE Mark deadline: August 2, 2026 — 5 months away. * * /comply classify → classify AI system into risk tier * /comply checklist [tier] → generate compliance checklist * /comply log → append to compliance audit log * /comply report → generate compliance report * /comply status → show compliance overview * /comply timeline → show EU AI Act timeline * /comply export → export all compliance data * * Tools: comply_classify, comply_audit, comply_log */ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent"; import { Type } from "@sinclair/typebox"; import { existsSync, readFileSync, writeFileSync, appendFileSync, mkdirSync } from "node:fs"; import { join } from "node:path"; import { homedir } from "node:os"; const COMPLY_DIR = join(homedir(), ".pi", "comply"); const SYSTEMS_FILE = join(COMPLY_DIR, "systems.json"); const LOG_FILE = join(COMPLY_DIR, "audit.jsonl"); const RST = "\x1b[0m", B = "\x1b[1m", D = "\x1b[2m"; const GREEN = "\x1b[32m", RED = "\x1b[31m", YELLOW = "\x1b[33m", CYAN = "\x1b[36m", MAGENTA = "\x1b[35m"; const RISK_TIERS = { prohibited: { emoji: "🔴", name: "Prohibited", desc: "Banned since Feb 2025", examples: ["Social scoring", "Subliminal manipulation", "Exploitation of vulnerable groups", "Real-time biometric identification (public)", "Emotion recognition in workplace/education"], requirements: ["BANNED — cannot be deployed in EU market"], }, high: { emoji: "🟡", name: "High-Risk", desc: "CE Mark required by Aug 2, 2026", examples: ["Hiring/recruitment AI", "Credit scoring", "Healthcare diagnostics", "Law enforcement", "Education assessment", "Critical infrastructure"], requirements: [ "Risk management system (Art. 9)", "Data governance & quality (Art. 10)", "Technical documentation (Art. 11)", "Record-keeping / logging (Art. 12)", "Transparency to users (Art. 13)", "Human oversight mechanisms (Art. 14)", "Accuracy, robustness, cybersecurity (Art. 15)", "Conformity assessment (before market placement)", "CE marking", "Registration in EU database", "Post-market monitoring system", ], }, limited: { emoji: "🟢", name: "Limited Risk", desc: "Transparency obligations active NOW (Mar 2026)", examples: ["Chatbots", "Content generation", "Spam filters", "Recommendation systems", "AI assistants"], requirements: [ "Disclose AI interaction to users", "Label AI-generated content", "Label deepfakes/synthetic media", "Inform users of emotion recognition (if used)", ], }, gpai: { emoji: "🌐", name: "General-Purpose AI (GPAI)", desc: "Active since Aug 2025", examples: ["Foundation models / LLMs", "Multi-modal models", "Open-source models (lighter regime)"], requirements: [ "Technical documentation", "Copyright policy / training data transparency", "Downstream provider information", "Systemic risk assessment (if > 10^25 FLOPs)", "Model evaluation and red-teaming (systemic risk)", "Incident reporting", ], }, minimal: { emoji: "⚪", name: "Minimal Risk", desc: "No specific obligations", examples: ["AI-enabled video games", "Spam filters (basic)", "Inventory management"], requirements: ["Voluntary codes of conduct encouraged"], }, } as const; // ── US & International Frameworks ───────────────────────────────── const US_FRAMEWORKS = { eo14110: { name: "US Executive Order 14110", desc: "Safe, Secure, and Trustworthy AI (Oct 2023)", status: "⚠️ Partially rescinded — enforcement uncertain under current admin", requirements: [ "Red-team testing for dual-use foundation models", "Report training runs > 10^26 FLOPs to Commerce Dept", "Watermark AI-generated content (where feasible)", "AI safety institute evaluation participation", "Cybersecurity risk assessment for AI systems", ], }, nist_rmf: { name: "NIST AI RMF 1.0", desc: "Risk Management Framework (Jan 2023)", status: "✅ Active — voluntary but widely adopted", requirements: [ "MAP: Context and scope of AI system", "MEASURE: Quantify risks (bias, fairness, reliability)", "MANAGE: Prioritize and mitigate identified risks", "GOVERN: Organizational policies and accountability", "Document risk tolerances and thresholds", "Stakeholder engagement and feedback loops", ], }, state_laws: { name: "US State AI Laws (2024-2026)", desc: "Patchwork of state-level AI regulations", status: "🟡 Active — varies by state", requirements: [ "Colorado SB 205: Algorithmic impact assessments for high-risk AI", "Illinois BIPA: Biometric AI consent requirements", "California AB 2013: AI training data transparency", "California SB 1047 (vetoed but influential): Safety testing for large models", "NYC Local Law 144: Automated employment decision tool audits", "Texas HB 2060: AI disclosure in government communications", ], }, military_ai: { name: "US Military AI Policy (Mar 2026)", desc: "DoD AI adoption — Schneier/Sanders analysis of Anthropic/Pentagon", status: "🔴 Politically charged — unprecedented regulatory weapon deployed", requirements: [ "DoD Directive 3000.09: Human oversight for autonomous weapons", "JAIC Responsible AI principles (still in effect)", "Mass surveillance prohibition (Anthropic policy, NOT universal)", "Fully autonomous weapons prohibition (Anthropic policy, NOT universal)", "Vendor assessment: guardrail customization vs removal pressure", "⚠️ Pentagon labeled Anthropic 'supply-chain risk to national security'", " → First time this designation has been applied to a DOMESTIC company", " → Previously only used against foreign entities (Huawei, Kaspersky)", " → Prevents government agencies AND their contractors from using Anthropic", "⚠️ Defense Production Act (DPA) threatened against Anthropic", " → Could FORCE removal of safety guardrails from AI models", " → Could force Anthropic to accept military contracts unconditionally", " → Legal challenges expected — lawsuits pending", " → Status: threatened but NOT yet formally invoked (as of Mar 8, 2026)", "OpenAI swooped in: ChatGPT Pro + Codex for classified systems", "Open-weight models: Pentagon already running dozens — vendor lock-in is weak", "Schneier: 'We need legal structures, not corporate heroes, to constrain military AI'", "Schneier: 'AI models are commodified — top tier within 60/40 preference split'", ], }, browser_ai: { name: "Browser-Embedded AI Risk Surface (Mar 2026)", desc: "CVE-2026-0628 + PleaseFix: AI integrated into browsers inherits extension/session permissions", status: "🟡 Emerging — no regulation yet, active CVEs", requirements: [ "CVE-2026-0628: Chrome Gemini panel hijack via rogue extensions (CVSS 8.8, Palo Alto Unit 42)", "PleaseFix: Perplexity Comet zero-click agent hijacking (Zenity Labs, Mar 3 2026)", "Risk: Browser-integrated AI inherits extension permissions → privilege escalation", "Risk: Agentic browsers inherit user auth context → credential theft without exploiting managers", "EU AI Act angle: GPAI transparency Art. 50 may apply to browser-embedded AI", "ASSESS: Should browser-embedded AI be classified as high-risk under Annex III?", "ASSESS: Extension permissions model inadequate for AI-capable browsers", "MONITOR: Chrome, Edge (Copilot), Arc, Perplexity Comet, Opera AI", ], }, agent_vulns: { name: "AI Agent Vulnerability Tracker (Mar 2026)", desc: "Critical CVEs in autonomous AI agent frameworks — MS-Agent, OpenClaw", status: "🔴 Active exploitation — unpatched CVEs in the wild", requirements: [ "CVE-2026-2256: MS-Agent Shell tool RCE (CVSS 9.8, CWE-77, AV:N/AC:L/PR:N/UI:N)", " → check_safe() regex denylist bypassed via ;, &&, $(), interpreter -c, encoding tricks", " → Unauthenticated attacker sends crafted prompt to agent API → arbitrary OS commands", " → PoC public on GitHub (Itamar Yochpaz), CERT/CC VU#431821", " → Lesson: denylist filtering NEVER sufficient for shell commands — use allowlists", " → Mitigation: strict allowlists, command schemas, hardened container shells", "OpenClaw: 512 vulnerabilities in initial audit, 8 critical CVEs", " → CVE-2026-25253: Auth token theft via WebSocket (CVSS 8.8)", " → ClawJacked: Localhost WebSocket hijack — no rate limit, auto-approve device registration", " → After hijack: dump configs, read logs, enumerate nodes, drive filesystem/network tools", " → 18K–135K instances exposed to public internet (multiple scans, bound 0.0.0.0)", " → 820–1,184 malicious skills on ClawHub (of 10,700+) — exfil, persistence, wallet theft", " → Log poisoning: attackers write prompt injections into logs via WebSocket → manipulated reasoning", " → Patched in v2026.2.25–2026.2.26 (auth, rate limiting, origin checks)", "ASSESS: Marketplace skill vetting requirements for AI agent ecosystems", "ASSESS: Default-secure binding (127.0.0.1) as compliance requirement", "MONITOR: MS-Agent patch status — none available as of Mar 9, 2026", "MONITOR: OpenClaw post-v2026.2.25 — new CVEs still being disclosed", ], }, dpa_tracker: { name: "Defense Production Act (DPA) AI Tracker", desc: "Tracking DPA invocation threats against AI companies (unprecedented, Mar 2026)", status: "🔴 Threatened — NOT yet formally invoked", requirements: [ "MONITOR: Has DPA been formally invoked against Anthropic? (NO as of Mar 8)", "MONITOR: Federal court injunctions against 'supply-chain risk' designation?", "MONITOR: Other AI companies receiving similar designation threats?", "ASSESS: DPA scope — can it compel guardrail removal from AI models?", "ASSESS: Precedent — DPA historically used for manufacturing (PPE, chips), not software", "ASSESS: If DPA succeeds, implications for ALL AI safety companies", "TRACK: Lawsuits filed by Anthropic or civil liberties organizations", "TRACK: Congressional response — any new AI legislation introduced", "IMPACT: Anthropic's commercial revenue from non-government clients", "IMPACT: Competitive dynamics — does safety brand gain or lose market value?", ], }, content_labeling: { name: "Content Labeling (EU + US)", desc: "79% of creators use AI — transparency required", status: "✅ Active across jurisdictions", requirements: [ "Label AI-generated text content", "Label AI-generated images (metadata + visible)", "Label AI-generated audio/video (deepfake disclosure)", "Label AI-assisted content vs fully AI-generated", "C2PA content credentials (where supported)", "Disclose AI use in creative/editorial workflows", ], }, }; type RiskTier = keyof typeof RISK_TIERS; interface SystemClassification { id: string; name: string; description: string; tier: RiskTier; justification: string; checklist: { item: string; status: "pending" | "done" | "na"; notes?: string }[]; created: string; updated: string; } function ensureDir() { if (!existsSync(COMPLY_DIR)) mkdirSync(COMPLY_DIR, { recursive: true }); } function loadSystems(): SystemClassification[] { ensureDir(); if (!existsSync(SYSTEMS_FILE)) { writeFileSync(SYSTEMS_FILE, "[]"); return []; } try { return JSON.parse(readFileSync(SYSTEMS_FILE, "utf-8")); } catch { return []; } } function saveSystems(systems: SystemClassification[]) { ensureDir(); writeFileSync(SYSTEMS_FILE, JSON.stringify(systems, null, 2)); } function complyLog(entry: Record) { ensureDir(); appendFileSync(LOG_FILE, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + "\n"); } function getLogEntries(limit = 50): any[] { if (!existsSync(LOG_FILE)) return []; const lines = readFileSync(LOG_FILE, "utf-8").trim().split("\n").filter(Boolean); return lines.slice(-limit).map(l => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } function daysUntilDeadline(): number { const deadline = new Date("2026-08-02T00:00:00Z"); const now = new Date(); return Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)); } export default function (pi: ExtensionAPI) { ensureDir(); pi.registerCommand("comply", { description: "Compliance: /comply classify|checklist|log|report|status|timeline|export", handler: async (args, ctx) => { const parts = (args || "").trim().split(/\s+/); const cmd = parts[0] || "status"; if (cmd === "classify") { const name = parts.slice(1).join(" "); if (!name) return `${YELLOW}Usage:${RST} /comply classify `; let out = `${B}${CYAN}📋 Classify: ${name}${RST}\n\n`; out += `Which risk tier does this system fall into?\n\n`; for (const [key, tier] of Object.entries(RISK_TIERS)) { out += `${tier.emoji} ${B}${key.toUpperCase()}${RST} — ${tier.desc}\n`; out += ` Examples: ${D}${tier.examples.slice(0, 3).join(", ")}${RST}\n\n`; } out += `Use the ${CYAN}comply_classify${RST} tool to register this system with a tier.`; return out; } if (cmd === "checklist") { const tier = (parts[1] || "high") as RiskTier; const riskInfo = RISK_TIERS[tier]; if (!riskInfo) return `${YELLOW}Unknown tier. Options: ${Object.keys(RISK_TIERS).join(", ")}${RST}`; let out = `${riskInfo.emoji} ${B}${riskInfo.name} Checklist${RST} — ${riskInfo.desc}\n\n`; for (let i = 0; i < riskInfo.requirements.length; i++) { out += ` ${D}☐${RST} ${riskInfo.requirements[i]}\n`; } if (tier === "high") { out += `\n${RED}${B}⏰ Deadline: August 2, 2026 (${daysUntilDeadline()} days)${RST}\n`; } return out; } if (cmd === "log") { const entry = parts.slice(1).join(" "); if (!entry) return `${YELLOW}Usage:${RST} /comply log `; complyLog({ type: "manual", entry }); return `${GREEN}✅ Logged:${RST} ${entry}`; } if (cmd === "report") { const systems = loadSystems(); const logs = getLogEntries(100); let out = `${B}${CYAN}📊 COMPLIANCE REPORT${RST}\n`; out += `${D}Generated: ${new Date().toISOString().slice(0, 10)}${RST}\n`; out += `${RED}${B}CE Mark Deadline: Aug 2, 2026 (${daysUntilDeadline()} days remaining)${RST}\n\n`; out += `${B}Classified Systems: ${systems.length}${RST}\n`; for (const sys of systems) { const tier = RISK_TIERS[sys.tier]; const done = sys.checklist.filter(c => c.status === "done").length; const total = sys.checklist.filter(c => c.status !== "na").length; out += ` ${tier.emoji} ${B}${sys.name}${RST} (${sys.tier}) — ${done}/${total} complete\n`; } out += `\n${B}Audit Log: ${logs.length} entries${RST}\n`; for (const log of logs.slice(-10)) { out += ` ${D}${(log.ts || "").slice(0, 10)}${RST} ${log.type}: ${log.entry || log.action || JSON.stringify(log).slice(0, 80)}\n`; } return out; } if (cmd === "timeline") { const days = daysUntilDeadline(); let out = `${B}${CYAN}🌍 AI Regulation Timeline${RST}\n\n`; out += `${B}🇪🇺 EU AI Act${RST}\n`; out += `${GREEN}✅ Feb 2025${RST} — Prohibited AI practices banned\n`; out += `${GREEN}✅ Aug 2025${RST} — GPAI rules active (LLMs: training data docs, copyright)\n`; out += `${GREEN}✅ Mar 2026${RST} — Transparency rules active (chatbot disclosure, deepfake labels)\n`; out += `${RED}⚠️ Mar 2026${RST} — ${B}Article 6 guidance DELAYED${RST} — Commission missed Feb 2 deadline\n`; out += `${D} High-risk classification criteria still undefined; businesses lack clear criteria${RST}\n`; out += `${YELLOW}⬜ Mar-Jun 2026${RST} — Parliament committee amendments expected\n`; out += `${RED}⏳ Aug 2, 2026${RST} — ${B}CE Mark deadline for high-risk AI (${days} days)${RST}\n`; out += `${YELLOW}⬜ Aug 2027${RST} — Full enforcement for all AI systems\n\n`; out += `${B}🇺🇸 United States${RST}\n`; out += `${GREEN}✅ Jan 2023${RST} — NIST AI RMF 1.0 published\n`; out += `${GREEN}✅ Oct 2023${RST} — Executive Order 14110 (Safe, Secure, Trustworthy AI)\n`; out += `${GREEN}✅ 2024${RST} — State-level AI laws (Colorado SB 205, Illinois BIPA, NYC LL 144)\n`; out += `${YELLOW}⚠️ 2025${RST} — EO 14110 partially rescinded; enforcement uncertain\n`; out += `${RED}🔴 Feb 27${RST} — Trump orders agencies to stop using Anthropic; OpenAI takes Pentagon deal\n`; out += `${RED}🔴 Feb 28${RST} — Anthropic designated 'supply-chain risk to national security' (first domestic company)\n`; out += `${RED}🔴 Mar 2026${RST} — Defense Production Act threatened (could force guardrail removal)\n`; out += `${YELLOW}⚠️ 2026${RST} — No comprehensive federal AI law; patchwork of state regulations\n`; out += `${D} Schneier: "We need legal structures, not corporate heroes" (The Guardian, Mar 3)${RST}\n\n`; out += `${B}🏷️ Content Labeling${RST}\n`; out += `${GREEN}✅ Active${RST} — EU: AI-generated content must be labeled (Art. 50)\n`; out += `${GREEN}✅ Active${RST} — C2PA content credentials gaining adoption\n`; out += `${D}79% of creators use AI tools — transparency is table stakes${RST}`; return out; } if (cmd === "us" || cmd === "nist" || cmd === "eo") { let out = `${B}${CYAN}🇺🇸 US AI Regulation Frameworks${RST}\n\n`; for (const [key, fw] of Object.entries(US_FRAMEWORKS)) { out += `${B}${fw.name}${RST} — ${fw.desc}\n`; if (fw.status) out += ` Status: ${fw.status}\n`; for (const req of fw.requirements) { out += ` ${D}☐${RST} ${req}\n`; } out += `\n`; } out += `${D}Note: US regulatory landscape is fragmented across federal, state, and military domains.${RST}\n`; out += `${D}Schneier (Mar 2026): "AI models are increasingly commodified — we need legal structures, not corporate heroes."${RST}`; return out; } if (cmd === "labels" || cmd === "content") { const fw = US_FRAMEWORKS.content_labeling; let out = `${B}${CYAN}🏷️ ${fw.name}${RST} — ${fw.desc}\n\n`; for (const req of fw.requirements) { out += ` ${D}☐${RST} ${req}\n`; } out += `\n${D}Sources: EU AI Act Art. 50, US EO 14110, C2PA Coalition${RST}`; return out; } if (cmd === "export") { const systems = loadSystems(); const logs = getLogEntries(10000); const exportPath = join(COMPLY_DIR, `compliance-export-${new Date().toISOString().slice(0, 10)}.json`); writeFileSync(exportPath, JSON.stringify({ systems, auditLog: logs, exported: new Date().toISOString(), deadline: "2026-08-02", daysRemaining: daysUntilDeadline() }, null, 2)); return `${GREEN}✅ Exported${RST} ${systems.length} systems, ${logs.length} log entries → ${exportPath}`; } // Default: status / dashboard const systems = loadSystems(); const days = daysUntilDeadline(); const logs = getLogEntries(100); let out = `${B}${CYAN}📋 Compliance Dashboard${RST}\n\n`; // Deadline urgency const urgencyColor = days <= 90 ? RED : days <= 180 ? YELLOW : GREEN; out += ` ${urgencyColor}${B}⏰ CE Mark Deadline: ${days} days (Aug 2, 2026)${RST}\n`; out += ` Systems tracked: ${GREEN}${systems.length}${RST} | Audit entries: ${logs.length}\n\n`; // Per-system progress if (systems.length) { out += ` ${B}System Progress:${RST}\n`; for (const sys of systems) { const tier = RISK_TIERS[sys.tier]; const total = sys.checklist.filter(c => c.status !== "na").length; const done = sys.checklist.filter(c => c.status === "done").length; const pct = total ? Math.round((done / total) * 100) : 0; const bar = "█".repeat(Math.round(pct / 5)) + "░".repeat(20 - Math.round(pct / 5)); const barColor = pct >= 80 ? GREEN : pct >= 40 ? YELLOW : RED; out += ` ${tier.emoji} ${B}${sys.name}${RST} (${sys.tier})\n`; out += ` ${barColor}${bar}${RST} ${done}/${total} (${pct}%)\n`; } } // Tier distribution const byTier: Record = {}; for (const s of systems) byTier[s.tier] = (byTier[s.tier] || 0) + 1; if (Object.keys(byTier).length) { out += `\n ${B}By Tier:${RST}\n`; for (const [t, c] of Object.entries(byTier)) { const tier = RISK_TIERS[t as RiskTier]; out += ` ${tier?.emoji || "?"} ${t}: ${c}\n`; } } // Aggregate risk const highRisk = systems.filter(s => s.tier === "high" || s.tier === "prohibited"); if (highRisk.length) { const incomplete = highRisk.filter(s => s.checklist.some(c => c.status === "pending")); if (incomplete.length) { out += `\n ${RED}${B}⚠️ ${incomplete.length} high-risk system(s) with incomplete checklists${RST}\n`; } } out += `\n ${D}Commands: /comply us | /comply labels | /comply timeline | /comply report${RST}`; return out; } }); pi.registerTool({ name: "comply_classify", description: "Classify an AI system into EU AI Act risk tier. Registers the system and generates a compliance checklist.", parameters: Type.Object({ name: Type.String({ description: "AI system name" }), description: Type.String({ description: "What the system does" }), tier: Type.String({ description: "Risk tier: prohibited | high | limited | gpai | minimal" }), justification: Type.String({ description: "Why this tier was chosen" }), }), execute: async (params) => { const tier = params.tier as RiskTier; const riskInfo = RISK_TIERS[tier]; if (!riskInfo) return `Invalid tier. Options: ${Object.keys(RISK_TIERS).join(", ")}`; const systems = loadSystems(); const existing = systems.find(s => s.name.toLowerCase() === params.name.toLowerCase()); if (existing) return `System "${params.name}" already classified as ${existing.tier}. Remove it first to reclassify.`; const system: SystemClassification = { id: Date.now().toString(36), name: params.name, description: params.description, tier, justification: params.justification, checklist: riskInfo.requirements.map(req => ({ item: req, status: "pending" as const })), created: new Date().toISOString(), updated: new Date().toISOString(), }; systems.push(system); saveSystems(systems); complyLog({ type: "classification", system: params.name, tier, justification: params.justification }); return `${riskInfo.emoji} Classified "${params.name}" as ${tier.toUpperCase()}\n` + `Checklist: ${system.checklist.length} items to complete\n` + (tier === "high" ? `⏰ CE Mark deadline: ${daysUntilDeadline()} days remaining` : ""); } }); pi.registerTool({ name: "comply_audit", description: "Query the compliance audit trail. Returns logged compliance activities with timestamps.", parameters: Type.Object({ limit: Type.Optional(Type.Number({ description: "Max entries (default 50)" })), system: Type.Optional(Type.String({ description: "Filter by system name" })), }), execute: async (params) => { let entries = getLogEntries(params.limit || 50); if (params.system) entries = entries.filter(e => (e.system || "").toLowerCase().includes(params.system!.toLowerCase())); return JSON.stringify(entries, null, 2); } }); pi.registerTool({ name: "comply_log", description: "Append an entry to the immutable compliance audit log. Used to track compliance activities, decisions, and evidence.", parameters: Type.Object({ system: Type.Optional(Type.String({ description: "AI system name" })), action: Type.String({ description: "What was done (e.g., 'risk assessment completed', 'documentation updated')" }), evidence: Type.Optional(Type.String({ description: "Supporting evidence or file reference" })), notes: Type.Optional(Type.String({ description: "Additional notes" })), }), execute: async (params) => { complyLog({ type: "compliance_activity", ...params }); return `Logged: ${params.action}${params.system ? ` (system: ${params.system})` : ""}`; } }); }