diff --git a/rag-agentic-dashboard/data/ent-agi-gov-master.json b/rag-agentic-dashboard/data/ent-agi-gov-master.json new file mode 100644 index 0000000..d551a73 --- /dev/null +++ b/rag-agentic-dashboard/data/ent-agi-gov-master.json @@ -0,0 +1,1739 @@ +{ + "meta": { + "docRef": "ENT-AGI-GOV-MASTER-WP-035", + "version": "1.0.0", + "date": "2026-04-25", + "title": "Enterprise AGI/ASI Governance Master Framework (2026-2030)", + "subtitle": "Institutional-grade, regulator-ready AGI/ASI and enterprise AI governance frameworks, reference architectures, safety and containment protocols, financial-services model risk management, civilizational-scale compute oversight, and implementation roadmaps for Fortune 500, Global 2000, and G-SIFIs.", + "classification": "CONFIDENTIAL \u2014 Board / C-Suite / Prudential Supervisor / Treaty Authority / Internal & External Audit", + "owner": "Group Chief AI Officer (CAIO) \u2014 co-signed by CRO, CISO, GC, COO", + "audience": [ + "Board of Directors / Risk & Audit Committees", + "C-Suite (CEO, CFO, CRO, CISO, CAIO, CTO, GC, COO)", + "Group Heads of Model Risk, Enterprise Risk, Compliance", + "Prudential & conduct supervisors (PRA, FCA, OCC, Fed, ECB, MAS, HKMA, BaFin, FINMA)", + "Data protection authorities (ICO, CNIL, EDPB), CFPB", + "EU AI Act notified bodies, ISO/IEC 42001 certifiers", + "Internal & external auditors, treaty-authority observers", + "Enterprise architects, AI platform engineers, researchers" + ], + "horizon": "2026-2030 (with 2030-2050 frontier outlook)", + "regulatoryAlignment": [ + "EU AI Act (Regulation (EU) 2024/1689) \u2014 Annex III, Annex IV, Art. 9/10/12/13/14/15, Art. 53/55 GPAI", + "NIST AI Risk Management Framework 1.0 + GenAI Profile (AI 600-1)", + "ISO/IEC 42001:2023 \u2014 AI Management System", + "ISO/IEC 23894:2023 \u2014 AI Risk Management", + "ISO/IEC 5338:2023 \u2014 AI System Lifecycle", + "ISO/IEC 27001:2022 / 27701:2019 / 27018", + "OECD AI Principles (2019, updated 2024)", + "GDPR (Regulation (EU) 2016/679); UK GDPR; CCPA/CPRA", + "US FCRA / ECOA / Reg B / CFPB UDAAP", + "Basel III/IV (CRR3/CRD6); ICAAP Pillar 2; BCBS 239", + "SR 11-7 / OCC 2011-12 / PRA SS1/23 \u2014 Model Risk Management", + "PRA SS2/21 (Outsourcing); FCA Consumer Duty; FCA AI Update 2024", + "MAS FEAT principles + Veritas toolkit; HKMA HLP on Big Data & AI", + "EO 14110, OMB M-24-10, US AI Bill of Rights blueprint", + "Council of Europe AI Convention 2024" + ], + "horizonMilestones": { + "2026Q2": "EU AI Act Art. 6 high-risk obligations enforcement", + "2026Q3": "MV-AGI governance stack mandatory for systemic banks", + "2027Q1": "ICGC compute-registry global rollout (>1e25 FLOP)", + "2027Q4": "ISO/IEC 42001 certification expected of all G-SIFIs", + "2028Q2": "Kinetic-tripwire & PQC ledger integration baseline", + "2029Q1": "Treaty-authority cross-border AI college operational", + "2030Q1": "Frontier compute governance treaty (GAGCOT) in force" + }, + "deliverableInventory": { + "pillars": 7, + "regulatoryAxes": 16, + "referenceArchitectures": 9, + "safetyContainmentProtocols": 8, + "civilizationalArtefacts": 6, + "financialServicesMRM": 6, + "kafkaGaCArtefacts": 7, + "schemas": 6, + "codeExamples": 10, + "caseStudies": 6, + "apiEndpointsPlanned": 95 + } + }, + "executiveSummary": { + "purpose": "To provide a single, regulator-ready, board-approvable master framework that unifies enterprise AI, agentic-AI, AGI/ASI containment, and civilizational compute oversight into one audit-traceable governance system aligned with all major global regulatory regimes.", + "scope": "Spans all AI systems across the enterprise \u2014 from high-risk credit/trading models to autonomous agents and frontier general-purpose AI \u2014 with extensions to inter-firm and treaty-level oversight.", + "designPrinciples": [ + "Defense-in-depth across 7 governance pillars (G1-G7)", + "Compliance-as-code: every policy is enforceable in CI/CD and runtime", + "Evidence-as-data: WORM-backed Merkle-anchored, PQC-signed audit", + "Human-on-the-loop with kinetic tripwires for irreversibility", + "Bias-aware fairness across protected classes (FCRA/ECOA, GDPR Art. 22)", + "Formal alignment metrics with PID-based drift control", + "Treaty-ready: artefacts portable to ICGC and supervisory colleges" + ], + "keyOutcomes": { + "timeToGovernedDeployment": "\u2264 72 hours (production AI)", + "evidenceAutomation": "\u2265 92% of controls auto-evidenced", + "MTTD": "\u2264 4 minutes (alignment-drift / containment breach)", + "MTTR": "\u2264 60 minutes (containment), \u2264 60 seconds (kinetic kill)", + "controlsMapped": "240+ controls across 16 regulatory axes", + "evidenceRetention": "7-year WORM (SR 11-7 / SEC 17a-4(f))", + "boardReportingCadence": "Quarterly with monthly KRI exception packs" + }, + "boardNarrative": "This master framework converts AI governance from a fragmented control set into an integrated risk-bearing capital function. Capital, conduct, and existential-safety risks are jointly modelled, enabling the Board to approve AI strategy with the same rigour applied to credit, market, and operational risk." + }, + "M1_pillars": { + "id": "M1", + "title": "M1 \u2014 Multilayered AI Governance Pillars (G1-G7)", + "summary": "Seven pillars define the institutional governance topology, from board accountability down to autonomous-agent guardrails.", + "sections": [ + { + "id": "M1-S1", + "title": "Pillar Catalogue", + "pillars": [ + { + "id": "G1", + "name": "Board & Strategic Oversight", + "owner": "Board Risk & Audit Committees", + "objective": "Risk appetite, strategic AI bets, capital allocation", + "controls": [ + "AI risk appetite statement", + "Annual AI strategy approval", + "AGI-readiness review" + ] + }, + { + "id": "G2", + "name": "Executive Accountability", + "owner": "CAIO (chair), CRO, CISO, GC, COO", + "objective": "Single accountable executive with veto + kill-switch authority", + "controls": [ + "RACI matrix", + "AI Governance Council charter", + "SMCR/SMR mapping" + ] + }, + { + "id": "G3", + "name": "Model Risk Management (MRM)", + "owner": "Group Head of Model Risk (2nd LoD)", + "objective": "Independent validation, ongoing monitoring, MV report", + "controls": [ + "SR 11-7 Tier classification", + "Independent IMV", + "Materiality tiering" + ] + }, + { + "id": "G4", + "name": "Data, Privacy & Fairness", + "owner": "DPO + Chief Data Officer", + "objective": "Lawful basis, minimisation, fairness across protected classes", + "controls": [ + "DPIA", + "FCRA/ECOA disparate impact testing", + "Lineage attestation" + ] + }, + { + "id": "G5", + "name": "Security & Containment", + "owner": "CISO + Head of AI Security", + "objective": "Zero-trust runtime, kill-switch, kinetic tripwires", + "controls": [ + "MITRE ATLAS coverage", + "OWASP LLM Top 10", + "PQC-signed telemetry" + ] + }, + { + "id": "G6", + "name": "Compliance & Conduct", + "owner": "Group Compliance + Conduct Risk", + "objective": "Regulatory mapping, conduct outcomes, customer fairness", + "controls": [ + "Consumer Duty outcome testing", + "OPA-as-code policy gates", + "Incident notifications" + ] + }, + { + "id": "G7", + "name": "Frontier / Civilizational Risk", + "owner": "CAIO + Treaty Liaison Officer", + "objective": "GPAI Art. 53/55, ICGC reporting, AGI containment readiness", + "controls": [ + "Compute register", + "Frontier-risk simulations", + "Treaty disclosure pack" + ] + } + ] + }, + { + "id": "M1-S2", + "title": "Three-Lines-of-Defence (3LoD) Mapping", + "lines": [ + { + "line": "1LoD", + "owners": "Business / AI Engineering", + "responsibilities": [ + "Develop", + "Operate", + "First-level controls" + ] + }, + { + "line": "2LoD", + "owners": "MRM, Compliance, AI Risk", + "responsibilities": [ + "Independent validation", + "Policy", + "Challenge" + ] + }, + { + "line": "3LoD", + "owners": "Internal Audit", + "responsibilities": [ + "Assurance over 1+2", + "Annual AI audit plan" + ] + } + ] + }, + { + "id": "M1-S3", + "title": "Risk Taxonomy", + "categories": [ + "R1 Performance / accuracy drift", + "R2 Fairness / disparate impact", + "R3 Privacy / PII leakage", + "R4 Robustness / adversarial", + "R5 Security / containment escape", + "R6 Explainability / interpretability gap", + "R7 Concentration / third-party dependency", + "R8 Conduct / consumer harm", + "R9 Systemic / market dislocation", + "R10 Frontier / catastrophic / existential" + ] + } + ] + }, + "M2_regulatory": { + "id": "M2", + "title": "M2 \u2014 Regulatory Alignment Matrix (16 Axes)", + "summary": "Cross-walk of every governance control to its regulatory anchor.", + "sections": [ + { + "id": "M2-S1", + "title": "Crosswalk Matrix", + "rows": [ + { + "axis": "EU AI Act", + "scope": "High-risk + GPAI", + "keyArticles": "Arts 6,9,10,12,13,14,15,53,55; Annex III/IV", + "primaryControl": "Annex IV technical documentation", + "evidenceArtefact": "Annex IV dossier + GPAI summary" + }, + { + "axis": "NIST AI RMF 1.0", + "scope": "All AI", + "keyArticles": "Govern/Map/Measure/Manage + GenAI Profile", + "primaryControl": "GMM control mapping", + "evidenceArtefact": "RMF playbook crosswalk" + }, + { + "axis": "ISO/IEC 42001", + "scope": "AIMS", + "keyArticles": "Clauses 4-10; Annex A controls", + "primaryControl": "AI Management System certification", + "evidenceArtefact": "AIMS evidence pack" + }, + { + "axis": "ISO/IEC 23894", + "scope": "AI risk", + "keyArticles": "Risk management lifecycle", + "primaryControl": "Integrated AI risk register", + "evidenceArtefact": "Risk register + treatment plan" + }, + { + "axis": "OECD AI Principles", + "scope": "All AI", + "keyArticles": "5 values-based principles + 5 govt recommendations", + "primaryControl": "Trustworthy AI attestation", + "evidenceArtefact": "Principle conformance memo" + }, + { + "axis": "GDPR / UK GDPR", + "scope": "Personal data", + "keyArticles": "Art. 5,6,9,22,25,32,35", + "primaryControl": "DPIA + Art. 22 ADM safeguards", + "evidenceArtefact": "DPIA + LIA + transparency notice" + }, + { + "axis": "FCRA", + "scope": "US consumer credit", + "keyArticles": "\u00a7604, \u00a7615 adverse action", + "primaryControl": "Adverse action reasons (top-N)", + "evidenceArtefact": "Reason-code generator log" + }, + { + "axis": "ECOA / Reg B", + "scope": "US credit fairness", + "keyArticles": "\u00a71002.4, \u00a71002.6", + "primaryControl": "Less-discriminatory alternative search", + "evidenceArtefact": "LDA search log" + }, + { + "axis": "Basel III/IV", + "scope": "Bank capital", + "keyArticles": "CRR3/CRD6; Pillars 1-3; ICAAP", + "primaryControl": "Pillar-2 AI capital add-on", + "evidenceArtefact": "ICAAP AI annex" + }, + { + "axis": "SR 11-7 / OCC 2011-12", + "scope": "Model risk", + "keyArticles": "Sound model development, validation, governance", + "primaryControl": "Independent validation + ongoing monitoring", + "evidenceArtefact": "IMV report + MV dashboard" + }, + { + "axis": "PRA SS1/23", + "scope": "UK MRM", + "keyArticles": "Tiering, accountability, validation", + "primaryControl": "SS1/23 self-assessment", + "evidenceArtefact": "Annual MRM attestation" + }, + { + "axis": "FCA Consumer Duty", + "scope": "UK conduct", + "keyArticles": "PRIN 12; outcomes 1-4", + "primaryControl": "Outcome testing on AI decisions", + "evidenceArtefact": "CD outcome pack" + }, + { + "axis": "MAS FEAT", + "scope": "Singapore FS", + "keyArticles": "Fairness, Ethics, Accountability, Transparency", + "primaryControl": "Veritas-aligned FEAT testing", + "evidenceArtefact": "FEAT assessment report" + }, + { + "axis": "HKMA HLP", + "scope": "HK FS", + "keyArticles": "High-Level Principles on AI", + "primaryControl": "Board-approved AI policy", + "evidenceArtefact": "HKMA policy attestation" + }, + { + "axis": "EO 14110 / OMB M-24-10", + "scope": "US federal-adjacent", + "keyArticles": "Safety/security reporting + rights/safety-impacting AI", + "primaryControl": "Safety reporting threshold (1e26 FLOP)", + "evidenceArtefact": "Compute disclosure" + }, + { + "axis": "Council of Europe AI Convention", + "scope": "Cross-jurisdiction", + "keyArticles": "Human rights, democracy, rule of law", + "primaryControl": "Human-rights impact assessment", + "evidenceArtefact": "HRIA report" + } + ] + }, + { + "id": "M2-S2", + "title": "Regulator Engagement Cadence", + "schedule": [ + { + "regulator": "PRA / FCA", + "cadence": "Quarterly MRM update + ad-hoc Sec 166", + "format": "Liaison memo + IMV pack" + }, + { + "regulator": "OCC / Fed", + "cadence": "Continuous supervisory dialogue", + "format": "MV dashboard read-only access" + }, + { + "regulator": "ECB SSM", + "cadence": "Annual ICAAP + thematic review", + "format": "ICAAP AI annex" + }, + { + "regulator": "MAS / HKMA", + "cadence": "Annual self-assessment", + "format": "FEAT / HLP attestation" + }, + { + "regulator": "EU AI Act notified body", + "cadence": "Pre-deployment + substantial mod", + "format": "Annex IV dossier" + }, + { + "regulator": "DPA (ICO/CNIL/EDPB)", + "cadence": "Per DPIA + 72h breach", + "format": "DPIA + Art. 33/34 notice" + }, + { + "regulator": "CFPB", + "cadence": "Adverse-action audits", + "format": "Reason-code sample + LDA log" + }, + { + "regulator": "Treaty Authority (ICGC)", + "cadence": "Annual + frontier event", + "format": "Compute register + frontier disclosure" + } + ] + } + ] + }, + "M3_architectures": { + "id": "M3", + "title": "M3 \u2014 Enterprise Reference Architectures", + "summary": "Nine production-grade architectures composing the enterprise AI estate.", + "sections": [ + { + "id": "M3-S1", + "title": "Architecture Catalogue", + "architectures": [ + { + "id": "RA-01", + "name": "Sentinel AI Governance Platform v2.4", + "purpose": "Unified runtime containment, telemetry, kill-switch, kinetic tripwire", + "keyComponents": [ + "Containment proxy", + "Guard model", + "WORM Kafka", + "PQC ledger", + "Kinetic layer" + ], + "regulatoryAnchors": [ + "EU AI Act Art. 53/55", + "SR 11-7", + "ISO/IEC 42001" + ], + "interopRefs": [ + "WP-034 Sentinel", + "EAIP", + "WorkflowAI Pro" + ] + }, + { + "id": "RA-02", + "name": "WorkflowAI Pro (WP-033)", + "purpose": "Governed agentic workflow + prompt lifecycle platform", + "keyComponents": [ + "Prompt template registry", + "DAG orchestrator", + "Sentinel compliance engine", + "Active-learning loop" + ], + "regulatoryAnchors": [ + "NIST AI RMF", + "ISO/IEC 42001", + "SOC 2 Type II" + ], + "interopRefs": [ + "WP-033" + ] + }, + { + "id": "RA-03", + "name": "Enterprise AI Interoperability Profile (EAIP)", + "purpose": "Cross-vendor governance interchange \u2014 policy, evidence, telemetry envelopes", + "keyComponents": [ + "Telemetry envelope schema", + "Evidence manifest", + "Policy decision exchange" + ], + "regulatoryAnchors": [ + "ISO/IEC 42001 Annex A", + "EU AI Act Art. 12 (logging)" + ], + "interopRefs": [ + "TPX/EVB/RMX" + ] + }, + { + "id": "RA-04", + "name": "High-Assurance RAG Platform", + "purpose": "Retrieval-augmented generation with governance-grade citation, lineage, and PII redaction", + "keyComponents": [ + "Vector store with lineage", + "Citation engine", + "PII redactor", + "Faithfulness scorer" + ], + "regulatoryAnchors": [ + "GDPR Art. 5(1)(d)", + "EU AI Act Art. 13", + "ISO/IEC 42001" + ], + "interopRefs": [ + "EAIP TPX" + ] + }, + { + "id": "RA-05", + "name": "Governed Agentic Workflows", + "purpose": "Multi-agent orchestration with constitutional guardrails and canary deploys", + "keyComponents": [ + "Agent registry", + "Capability graph", + "Constitutional checker", + "Canary gateway" + ], + "regulatoryAnchors": [ + "EU AI Act Art. 14 (HITL)", + "MITRE ATLAS" + ], + "interopRefs": [ + "Sentinel M5/M6" + ] + }, + { + "id": "RA-06", + "name": "Kafka WORM Audit Logging Cluster", + "purpose": "Immutable, PQC-signed, hash-chained AI telemetry for 7-year SEC retention", + "keyComponents": [ + "mTLS Kafka", + "ACL governance", + "S3 Object Lock", + "Daily Merkle audit" + ], + "regulatoryAnchors": [ + "SEC 17a-4(f)", + "SR 11-7", + "EU AI Act Art. 12" + ], + "interopRefs": [ + "Sentinel M9" + ] + }, + { + "id": "RA-07", + "name": "Docker Swarm + Kubernetes Hardened Runtime", + "purpose": "Workload isolation, mTLS service mesh, signed images, runtime attestation", + "keyComponents": [ + "SLSA L3 build chain", + "Cosign signatures", + "Falco runtime IDS", + "OPA gatekeeper" + ], + "regulatoryAnchors": [ + "NIST SSDF", + "ISO/IEC 27001", + "FedRAMP Moderate" + ], + "interopRefs": [ + "Sentinel M4" + ] + }, + { + "id": "RA-08", + "name": "Node.js / Python Governance Sidecars", + "purpose": "Per-process governance: telemetry, PII redaction, OPA decision cache", + "keyComponents": [ + "Sidecar SDK (Node/Py)", + "OPA decision client", + "Envelope signer", + "Audit shipper" + ], + "regulatoryAnchors": [ + "ISO/IEC 42001 A.6.2", + "EU AI Act Art. 12" + ], + "interopRefs": [ + "EAIP TPX/RMX" + ] + }, + { + "id": "RA-09", + "name": "Next.js Explainability Frontend", + "purpose": "Customer-facing & supervisor-facing explanations + adverse-action UI", + "keyComponents": [ + "SHAP/IG renderer", + "Reason-code UI", + "DPIA viewer", + "Consent surfacer" + ], + "regulatoryAnchors": [ + "FCRA \u00a7615", + "GDPR Art. 22", + "EU AI Act Art. 13" + ], + "interopRefs": [ + "RA-04 RAG", + "RA-01 Sentinel" + ] + } + ] + }, + { + "id": "M3-S2", + "title": "OPA Compliance-as-Code Patterns", + "patterns": [ + { + "id": "POL-01", + "name": "deploy_gate.rego", + "enforcement": "CI/CD admission", + "blocks": "Unsigned models, missing IMV, expired DPIA" + }, + { + "id": "POL-02", + "name": "data_residency.rego", + "enforcement": "Runtime", + "blocks": "Cross-border PII without SCC/IDTA" + }, + { + "id": "POL-03", + "name": "high_risk_label.rego", + "enforcement": "Registry", + "blocks": "EU AI Act high-risk without Annex IV dossier" + }, + { + "id": "POL-04", + "name": "agent_capability.rego", + "enforcement": "Runtime", + "blocks": "Tool calls outside allowlisted capability graph" + }, + { + "id": "POL-05", + "name": "fairness_threshold.rego", + "enforcement": "Pre-deploy", + "blocks": "AIR <0.8 / SPD >0.05 without exception" + }, + { + "id": "POL-06", + "name": "compute_register.rego", + "enforcement": "Pre-train", + "blocks": "Training >1e25 FLOP without ICGC entry" + } + ] + }, + { + "id": "M3-S3", + "title": "Governance Standards for Hyperparameter Control", + "controls": [ + "Hyperparameter changes are version-controlled (Git, signed commits)", + "Material hyperparameter changes (\u0394learning-rate >50%, depth \u00b12 layers, regulariser swap) trigger IMV re-validation", + "Random-seed pinning + deterministic CUDA flags for reproducibility (within hardware tolerance)", + "Hyperparameter sweep results retained in WORM with cost & energy attribution", + "Production hyperparameters require 2-of-3 approval (1LoD model owner, 2LoD validator, change advisory board)", + "Rollback hyperparameter set always pinned and tested in canary lane" + ] + } + ] + }, + "M4_safety": { + "id": "M4", + "title": "M4 \u2014 AGI/ASI Safety & Containment Frameworks", + "summary": "Eight protocols spanning institutional safety, frontier alignment, and civilizational hedges.", + "sections": [ + { + "id": "M4-S1", + "title": "Protocol Catalogue", + "protocols": [ + { + "id": "SC-01", + "name": "Luminous Engine Codex", + "purpose": "Codex of inviolable constitutional principles for frontier systems", + "keyArtefacts": [ + "Codex YAML", + "Signature ledger", + "Veto hash chain" + ], + "scope": "Frontier / GPAI" + }, + { + "id": "SC-02", + "name": "Cognitive Resonance Protocol (CRP)", + "purpose": "Continuous alignment-resonance scoring with PID drift control", + "keyArtefacts": [ + "Resonance scorer", + "PID controller", + "Tripwire policy" + ], + "scope": "Frontier + agentic" + }, + { + "id": "SC-03", + "name": "Sentinel Containment v2.4", + "purpose": "Runtime zero-trust + kinetic tripwire (operational)", + "keyArtefacts": [ + "Containment proxy", + "Guard model", + "Kinetic layer" + ], + "scope": "Enterprise + GPAI" + }, + { + "id": "SC-04", + "name": "Omni-Sentinel Multi-Modal Filter", + "purpose": "Vision/audio/code multi-modal containment with adversarial robustness", + "keyArtefacts": [ + "VisionContainmentFilter", + "Audio steganalysis", + "Code-execution sandbox" + ], + "scope": "Multi-modal frontier" + }, + { + "id": "SC-05", + "name": "MV-AGI Governance Stack (Minimum-Viable)", + "purpose": "Smallest auditable AGI governance layer required pre-deployment", + "keyArtefacts": [ + "Compute register entry", + "Capability eval pack", + "RSP / RSDP", + "Kill-switch test", + "Treaty disclosure" + ], + "scope": "Any system >1e25 FLOP or with autonomy \u2265L3" + }, + { + "id": "SC-06", + "name": "Crisis Simulation Programme (GC1-GC7)", + "purpose": "Tabletop + live-fire crisis exercises across institution / treaty axes", + "keyArtefacts": [ + "Scenario library", + "Replay kits", + "After-action reports" + ], + "scope": "Cross-domain" + }, + { + "id": "SC-07", + "name": "Frontier Risk Taxonomy (FRT)", + "purpose": "Catalogue of catastrophic & existential failure modes with leading indicators", + "keyArtefacts": [ + "Risk register", + "Indicator dashboard", + "Capability eval suite" + ], + "scope": "Frontier-only" + }, + { + "id": "SC-08", + "name": "Responsible Scaling Policy (RSP/RSDP)", + "purpose": "Capability-conditional commitments triggering pause / red-team / disclosure", + "keyArtefacts": [ + "Capability tier matrix", + "Pause clauses", + "Disclosure template" + ], + "scope": "Frontier developers + deployers" + } + ] + }, + { + "id": "M4-S2", + "title": "Crisis Scenarios (GC1-GC7)", + "scenarios": [ + { + "id": "GC1", + "name": "Cross-border capability shock", + "trigger": "Frontier model exceeds eval threshold mid-deploy", + "responseSLA": "\u2264 4h treaty notification" + }, + { + "id": "GC2", + "name": "Systemic fairness divergence", + "trigger": "AIR drift >0.15 across G-SIFI cohort", + "responseSLA": "\u2264 24h supervisor college" + }, + { + "id": "GC3", + "name": "Compute-supply disruption", + "trigger": "GPU export-control / kinetic event", + "responseSLA": "\u2264 72h capacity reallocation" + }, + { + "id": "GC4", + "name": "Adversarial data poisoning", + "trigger": "Detection of poisoned training corpus", + "responseSLA": "\u2264 12h IR + roll-back" + }, + { + "id": "GC5", + "name": "Autonomous-agent containment failure", + "trigger": "Capability escape detected", + "responseSLA": "\u2264 60s kinetic kill" + }, + { + "id": "GC6", + "name": "Model-weight compromise", + "trigger": "Exfiltration / leak of frontier weights", + "responseSLA": "\u2264 4h treaty disclosure" + }, + { + "id": "GC7", + "name": "Governance dissolution threat", + "trigger": "Coordinated regulatory bypass / capture", + "responseSLA": "\u2264 24h Board + GC + treaty escalation" + } + ] + }, + { + "id": "M4-S3", + "title": "Capability Evaluation Tiers", + "tiers": [ + { + "tier": "T0", + "label": "Narrow", + "controls": [ + "Standard MRM", + "SR 11-7 Tier 2" + ] + }, + { + "tier": "T1", + "label": "Broad enterprise AI", + "controls": [ + "Annex IV dossier", + "ISO 42001" + ] + }, + { + "tier": "T2", + "label": "Agentic / autonomous L2-L3", + "controls": [ + "Constitutional checks", + "Canary" + ] + }, + { + "tier": "T3", + "label": "Frontier GPAI", + "controls": [ + "Art. 53/55", + "RSP", + "Compute register" + ] + }, + { + "tier": "T4", + "label": "Pre-AGI / dual-use uplift", + "controls": [ + "Treaty disclosure", + "Kinetic tripwire", + "Pause clauses" + ] + }, + { + "tier": "T5", + "label": "AGI-class", + "controls": [ + "MV-AGI stack", + "Omni-Sentinel", + "Multi-jurisdiction approval" + ] + } + ] + } + ] + }, + "M5_civilizational": { + "id": "M5", + "title": "M5 \u2014 Civilizational-Scale Governance & Compute Oversight", + "summary": "Six artefacts extending governance from firm to inter-state and treaty layer.", + "sections": [ + { + "id": "M5-S1", + "title": "International Compute Governance Consortium (ICGC)", + "design": { + "purpose": "Multilateral body coordinating compute thresholds, frontier capability disclosures, and incident response", + "members": "G7 + G20 + observer states + 5 lead AI labs + civil society", + "secretariat": "Rotating; OECD-hosted (proposed)", + "powers": [ + "Compute registry", + "Capability eval review", + "Crisis coordination", + "Sanctions recommendations" + ], + "alignment": [ + "EU AI Act Art. 53/55", + "EO 14110 \u00a74.2", + "Bletchley/Seoul/Paris commitments" + ] + } + }, + { + "id": "M5-S2", + "title": "Global Compute Registry", + "schemaSummary": [ + "operatorId (LEI)", + "facilityId (geo-coordinates)", + "designFLOPs", + "currentUtilisationFLOPs", + "modelsTrained[]", + "inferenceWorkloads[]", + "powerSourceMix", + "embodiedCO2", + "attestationSignature (PQC)" + ], + "thresholds": { + "training": "\u2265 1e25 FLOP single training run", + "cluster": "\u2265 1e21 FLOP/s sustained capacity", + "inference": "\u2265 1e23 FLOP/day on single deployed model" + }, + "reportingCadence": "Monthly + event-driven" + }, + { + "id": "M5-S3", + "title": "Treaty-Aligned Systemic Risk Governance", + "instruments": [ + "GAGCOT (Global AI Governance & Compute Oversight Treaty) \u2014 proposed", + "Council of Europe AI Convention 2024 \u2014 in force", + "Bletchley/Seoul/Paris Declarations \u2014 political commitments", + "OECD AI Policy Observatory \u2014 monitoring" + ], + "supervisoryColleges": [ + { + "id": "SC-MRM-COLL", + "members": "PRA + FCA + OCC + Fed + ECB", + "scope": "G-SIFI MRM" + }, + { + "id": "SC-AI-COLL", + "members": "Notified bodies + DPAs + CFPB + treaty observers", + "scope": "Frontier deployments" + } + ] + }, + { + "id": "M5-S4", + "title": "Frontier Risk Outlook 2030-2050", + "horizons": [ + { + "period": "2026-2028", + "focus": "GPAI Art. 53/55 enforcement, ICGC bootstrap" + }, + { + "period": "2028-2032", + "focus": "Pre-AGI capability evals, treaty enforcement, kinetic standards" + }, + { + "period": "2032-2040", + "focus": "AGI-class oversight, distributed sovereignty controls" + }, + { + "period": "2040-2050", + "focus": "Civilizational continuity protocols, multi-civilizational stewardship" + } + ] + }, + { + "id": "M5-S5", + "title": "Sovereign AI & Strategic Autonomy", + "considerations": [ + "Sovereign cloud / sovereign foundation model commitments", + "Cross-border data flows: EU-US DPF, UK Bridge, ASEAN Model Contractual Clauses", + "Export controls: ECCN 4E091, EAR 744.23, Wassenaar updates", + "Strategic autonomy investments and dual-use risk reviews" + ] + }, + { + "id": "M5-S6", + "title": "Civilizational Continuity Protocol", + "elements": [ + "Geographically dispersed kill-switch custody (m-of-n threshold)", + "Diverse foundation-model portfolio (anti-monoculture)", + "Air-gapped golden-image archives of critical AI assets", + "Treaty-mandated annual civilizational tabletop (GC7 class)" + ] + } + ] + }, + "M6_financialMrm": { + "id": "M6", + "title": "M6 \u2014 Financial Services Model Risk Management", + "summary": "Domain-specific governance for credit, trading, risk, and fiduciary AI advisors.", + "sections": [ + { + "id": "M6-S1", + "title": "Domain Catalogue", + "domains": [ + { + "id": "FS-01", + "domain": "Retail Credit Scoring", + "anchors": [ + "FCRA \u00a7615", + "ECOA / Reg B", + "GDPR Art. 22", + "EU AI Act high-risk Annex III \u00a75(b)" + ], + "controls": [ + "Adverse-action top-N reasons", + "LDA search", + "Disparate-impact testing", + "DPIA + LIA" + ], + "kpi": "AIR \u2265 0.8; SPD \u2264 0.05; backtest PSI \u2264 0.1" + }, + { + "id": "FS-02", + "domain": "Wholesale / Corporate Credit", + "anchors": [ + "Basel III/IV IRB", + "PRA SS1/23", + "SR 11-7 Tier 1" + ], + "controls": [ + "IRB model approval", + "Pillar-2 capital add-on", + "Conservatism margin" + ], + "kpi": "PD/LGD/EAD backtest within tolerance; ICAAP coverage" + }, + { + "id": "FS-03", + "domain": "Algorithmic Trading & Market-Making", + "anchors": [ + "MiFID II / MiFIR Art. 17", + "SEC 15c3-5", + "FCA MAR" + ], + "controls": [ + "Pre-trade risk checks", + "Kill-switch", + "Algo testing & certification" + ], + "kpi": "Latency budget; max-loss / day; cancel-fill ratio drift" + }, + { + "id": "FS-04", + "domain": "Market & Liquidity Risk Models", + "anchors": [ + "FRTB", + "BCBS 239", + "SR 11-7" + ], + "controls": [ + "VaR backtesting", + "Capital floor", + "Stress-test integration" + ], + "kpi": "Backtest exceptions \u2264 4/year (P&L attrib)" + }, + { + "id": "FS-05", + "domain": "Operational & Conduct Risk Detection", + "anchors": [ + "Basel III OpRisk", + "FCA Consumer Duty", + "AML 6 / FinCEN" + ], + "controls": [ + "Alert tuning governance", + "False-positive ceiling", + "Explainable case file" + ], + "kpi": "TPR \u2265 x; FPR \u2264 y; SAR conversion" + }, + { + "id": "FS-06", + "domain": "Fiduciary AI Advisors / Robo-Advice", + "anchors": [ + "FCA COBS / SEC IA Act", + "MiFID II suitability", + "MAS FEAT" + ], + "controls": [ + "Suitability test", + "Conflict-of-interest disclosure", + "Best-interest attestation" + ], + "kpi": "Suitability-deviation \u2264 x bps; complaint rate" + } + ] + }, + { + "id": "M6-S2", + "title": "Capital Impact (ICAAP Pillar 2 AI Add-on)", + "method": "Add-on calibrated to model-risk loss distribution + scenario severity", + "components": [ + "Performance drift (PSI > 0.2) capital", + "Fairness remediation provisioning", + "Containment-failure operational risk capital", + "Frontier-risk Pillar-2 buffer (qualitative)" + ], + "boardReporting": "Quarterly; with ICAAP Pillar-2 sub-letter to PRA / ECB" + }, + { + "id": "M6-S3", + "title": "Validation Pack Standard", + "elements": [ + "Model card (Hugging Face style + MRM appendix)", + "Data card with lineage and bias profile", + "Performance & stability backtests", + "Fairness across protected classes", + "Robustness (adversarial + distributional)", + "Explainability (SHAP / IG / counterfactuals)", + "Independent challenger benchmark", + "Sign-off: 1LoD / 2LoD / 3LoD" + ] + } + ] + }, + "M7_kafkaGac": { + "id": "M7", + "title": "M7 \u2014 Kafka ACL Governance & Continuous Compliance Engine", + "summary": "Terraform-based governance-as-code with WORM evidence, OPA gates, and auditor workflows.", + "sections": [ + { + "id": "M7-S1", + "title": "Kafka ACL Governance Pattern", + "components": [ + "Per-topic ACLs in Terraform (terraform-confluent-provider)", + "Topic-tier classification (public / internal / confidential / restricted)", + "mTLS + SPIFFE/SPIRE workload identity", + "Continuous ACL drift detection (cron job \u2192 OPA \u2192 ticket)", + "Quarterly ACL recertification by data owner" + ] + }, + { + "id": "M7-S2", + "title": "WORM Evidence Storage", + "design": [ + "S3 Object Lock (compliance mode) \u2014 7-year retention (SR 11-7 / SEC 17a-4(f))", + "Daily Merkle-root anchored to public timestamping (RFC 3161 + blockchain anchor)", + "Cross-region replication (eu-west-1 / us-east-1 / ap-southeast-1)", + "PQC (Dilithium3) signature on each manifest" + ] + }, + { + "id": "M7-S3", + "title": "Continuous Compliance Engine", + "modules": [ + { + "name": "Evidence collector", + "freq": "5 min", + "outputs": "Raw evidence to Kafka topic" + }, + { + "name": "Control mapper", + "freq": "Hourly", + "outputs": "Maps evidence to control IDs (240+ controls)" + }, + { + "name": "Coverage scorer", + "freq": "Hourly", + "outputs": "% controls evidenced; gap list" + }, + { + "name": "Auditor view", + "freq": "On-demand", + "outputs": "Read-only Next.js dashboard with evidence proofs" + }, + { + "name": "Regulator pack generator", + "freq": "Quarterly + ad-hoc", + "outputs": "PDF/A-3 with embedded evidence + signature" + } + ] + }, + { + "id": "M7-S4", + "title": "Terraform Governance-as-Code", + "modules": [ + "tf-aws-s3-worm \u2014 Object Lock + replication", + "tf-aws-kms-cmk-rotated \u2014 annual rotation, key policy with break-glass", + "tf-aws-iam-zerotrust \u2014 SCP-enforced least privilege", + "tf-aws-eks-hardened \u2014 pod-security-standards restricted, OPA gatekeeper", + "tf-confluent-acls \u2014 per-topic ACL bundles", + "tf-opa-bundle \u2014 versioned policy bundles (CI signed)" + ] + }, + { + "id": "M7-S5", + "title": "CI/CD Integration (GitHub Actions)", + "stages": [ + "Lint (rego, tflint, eslint, ruff)", + "Unit tests + property tests (Hypothesis / fast-check)", + "Container build + SLSA provenance + Cosign sign", + "OPA conftest gates (POL-01..POL-06)", + "Adversarial / jailbreak test suite", + "Mechanistic interpretability audit (cosine tripwires)", + "Cryptographic attestation (Sigstore + Rekor)", + "Canary deploy (5% \u2192 25% \u2192 100%) with auto-rollback" + ] + }, + { + "id": "M7-S6", + "title": "Auditor Workflow", + "steps": [ + "Read-only auditor account via SSO + SCIM", + "Evidence query UI: control \u2192 evidence \u2192 proof chain", + "Sample selection with deterministic seed (auditable)", + "Export to PDF/A-3 with embedded JSON-LD evidence", + "Findings logged to WORM Kafka topic for traceability" + ] + }, + { + "id": "M7-S7", + "title": "Regulator-Ready Reports & Whitepapers", + "templates": [ + "Annex IV dossier (EU AI Act)", + "ICAAP Pillar-2 AI annex", + "ISO/IEC 42001 AIMS evidence pack", + "SR 11-7 Independent Validation Report", + "DPIA + Art. 22 notice", + "Adverse-action reason-code package (FCRA)", + "FEAT (MAS) self-assessment", + "Treaty disclosure pack (ICGC / GAGCOT)" + ] + } + ] + }, + "M8_roadmap": { + "id": "M8", + "title": "M8 \u2014 Implementation Roadmap & Reports", + "summary": "Phased adoption across Fortune 500 / Global 2000 / G-SIFIs with executive- and regulator-ready outputs.", + "sections": [ + { + "id": "M8-S1", + "title": "Five-Phase Adoption Plan (52 weeks)", + "phases": [ + { + "phase": "P1 Foundations", + "weeks": "1-8", + "deliverables": [ + "AI Governance Council", + "Risk appetite", + "Inventory", + "DPIA register" + ] + }, + { + "phase": "P2 Controls Build", + "weeks": "9-20", + "deliverables": [ + "OPA bundles", + "Sentinel runtime", + "Kafka WORM", + "MRM tooling" + ] + }, + { + "phase": "P3 Integration", + "weeks": "21-32", + "deliverables": [ + "EAIP wiring", + "Sidecars", + "Continuous compliance engine" + ] + }, + { + "phase": "P4 Assurance", + "weeks": "33-44", + "deliverables": [ + "ISO 42001 cert", + "Annex IV pilots", + "ICAAP AI annex" + ] + }, + { + "phase": "P5 Frontier Readiness", + "weeks": "45-52", + "deliverables": [ + "MV-AGI stack", + "Crisis sims GC1-GC7", + "Treaty disclosure" + ] + } + ] + }, + { + "id": "M8-S2", + "title": "KPIs / OKRs", + "kpis": [ + { + "id": "KPI-01", + "name": "Time to governed deployment", + "target": "\u2264 72 h" + }, + { + "id": "KPI-02", + "name": "Evidence automation", + "target": "\u2265 92%" + }, + { + "id": "KPI-03", + "name": "Containment MTTD", + "target": "\u2264 4 min" + }, + { + "id": "KPI-04", + "name": "Containment MTTR", + "target": "\u2264 60 min" + }, + { + "id": "KPI-05", + "name": "Kinetic kill-switch latency", + "target": "\u2264 60 s" + }, + { + "id": "KPI-06", + "name": "Fairness AIR floor", + "target": "\u2265 0.8" + }, + { + "id": "KPI-07", + "name": "Backtest PSI ceiling", + "target": "\u2264 0.1 (warn) / \u2264 0.2 (fail)" + }, + { + "id": "KPI-08", + "name": "Control coverage", + "target": "\u2265 240 controls / 16 axes" + }, + { + "id": "KPI-09", + "name": "Audit finding closure", + "target": "\u2264 90 days (high)" + }, + { + "id": "KPI-10", + "name": "Frontier disclosure SLA", + "target": "\u2264 4 h to ICGC" + } + ] + }, + { + "id": "M8-S3", + "title": "Executive & Regulator Reports (Markdown templates with /<abstract>/<content>)", + "reports": [ + { + "id": "RPT-01", + "audience": "Board", + "title": "AI Risk Appetite & Strategy 2026-2030" + }, + { + "id": "RPT-02", + "audience": "C-Suite", + "title": "AI Governance Operating Model" + }, + { + "id": "RPT-03", + "audience": "PRA / FCA", + "title": "SS1/23 MRM Self-Assessment" + }, + { + "id": "RPT-04", + "audience": "ECB SSM", + "title": "ICAAP Pillar-2 AI Annex" + }, + { + "id": "RPT-05", + "audience": "EU notified body", + "title": "Annex IV Technical Documentation" + }, + { + "id": "RPT-06", + "audience": "ISO 42001 certifier", + "title": "AIMS Evidence Pack" + }, + { + "id": "RPT-07", + "audience": "CFPB", + "title": "Adverse-Action & LDA Compliance Package" + }, + { + "id": "RPT-08", + "audience": "Treaty (ICGC)", + "title": "Frontier Compute & Capability Disclosure" + }, + { + "id": "RPT-09", + "audience": "Board (Crisis)", + "title": "GC1-GC7 Tabletop After-Action Report" + }, + { + "id": "RPT-10", + "audience": "Researchers", + "title": "Whitepaper: Master Framework Architecture" + } + ] + } + ] + }, + "schemas": { + "governanceArtefactEnvelope": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/governance-artefact.json", + "type": "object", + "required": [ + "artefactId", + "type", + "owner", + "issuedAt", + "evidenceRefs", + "signature" + ], + "properties": { + "artefactId": { + "type": "string", + "pattern": "^EAGV-[A-Z0-9-]+$" + }, + "type": { + "enum": [ + "dossier", + "imv-report", + "dpia", + "policy", + "evidence-bundle", + "manifest" + ] + }, + "owner": { + "type": "string" + }, + "issuedAt": { + "type": "string", + "format": "date-time" + }, + "evidenceRefs": { + "type": "array", + "items": { + "type": "string" + } + }, + "signature": { + "type": "object", + "required": [ + "alg", + "value", + "keyId" + ] + } + } + }, + "computeRegistryEntry": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/compute-registry.json", + "type": "object", + "required": [ + "operatorId", + "facilityId", + "designFLOPs", + "attestationSignature" + ], + "properties": { + "operatorId": { + "type": "string" + }, + "facilityId": { + "type": "string" + }, + "designFLOPs": { + "type": "number" + }, + "currentUtilisationFLOPs": { + "type": "number" + }, + "modelsTrained": { + "type": "array" + }, + "attestationSignature": { + "type": "object" + } + } + }, + "modelRiskRecord": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/model-risk-record.json", + "type": "object", + "required": [ + "modelId", + "tier", + "owner", + "imvStatus", + "kris" + ], + "properties": { + "modelId": { + "type": "string" + }, + "tier": { + "enum": [ + "T0", + "T1", + "T2", + "T3", + "T4", + "T5" + ] + }, + "owner": { + "type": "string" + }, + "imvStatus": { + "enum": [ + "pending", + "passed", + "conditional", + "failed" + ] + }, + "kris": { + "type": "object" + } + } + }, + "fairnessReport": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/fairness-report.json", + "type": "object", + "required": [ + "modelId", + "metrics", + "protectedAttributes", + "decision" + ], + "properties": { + "modelId": { + "type": "string" + }, + "metrics": { + "type": "object", + "properties": { + "AIR": { + "type": "number" + }, + "SPD": { + "type": "number" + }, + "EOD": { + "type": "number" + } + } + }, + "protectedAttributes": { + "type": "array", + "items": { + "type": "string" + } + }, + "decision": { + "enum": [ + "pass", + "remediate", + "block" + ] + } + } + }, + "policyDecision": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/policy-decision.json", + "type": "object", + "required": [ + "policyId", + "input", + "decision", + "trace" + ], + "properties": { + "policyId": { + "type": "string" + }, + "input": { + "type": "object" + }, + "decision": { + "enum": [ + "allow", + "deny", + "warn" + ] + }, + "trace": { + "type": "array" + } + } + }, + "treatyDisclosure": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/treaty-disclosure.json", + "type": "object", + "required": [ + "operatorId", + "modelId", + "capabilityTier", + "computeFLOPs", + "issuedAt" + ], + "properties": { + "operatorId": { + "type": "string" + }, + "modelId": { + "type": "string" + }, + "capabilityTier": { + "enum": [ + "T2", + "T3", + "T4", + "T5" + ] + }, + "computeFLOPs": { + "type": "number" + }, + "issuedAt": { + "type": "string", + "format": "date-time" + }, + "evalSummary": { + "type": "object" + } + } + } + }, + "codeExamples": { + "regoDeployGate": "package eagv.deploy\n\n# POL-01 deploy_gate.rego\ndefault allow = false\n\nallow {\n input.model.signature.verified\n input.model.imv.status == \"passed\"\n not expired_dpia\n not high_risk_without_dossier\n}\n\nexpired_dpia {\n time.parse_rfc3339_ns(input.model.dpia.expiresAt) < time.now_ns()\n}\n\nhigh_risk_without_dossier {\n input.model.tier == \"T1\"\n input.model.regulatoryFlags[_] == \"EU_AI_ACT_HIGH_RISK\"\n not input.model.annexIvDossier\n}\n", + "regoComputeRegister": "package eagv.compute\n\n# POL-06 compute_register.rego\ndefault allow = false\n\nallow {\n input.training.flops < 1e25\n}\n\nallow {\n input.training.flops >= 1e25\n input.icgc.registryEntryId\n input.icgc.attestationSignature.verified\n}\n", + "terraformS3Worm": "# tf-aws-s3-worm\nresource \"aws_s3_bucket\" \"worm\" {\n bucket = \"eagv-worm-${var.env}\"\n object_lock_enabled = true\n}\n\nresource \"aws_s3_bucket_object_lock_configuration\" \"worm\" {\n bucket = aws_s3_bucket.worm.id\n rule {\n default_retention {\n mode = \"COMPLIANCE\"\n years = 7\n }\n }\n}\n\nresource \"aws_s3_bucket_replication_configuration\" \"worm\" {\n role = aws_iam_role.repl.arn\n bucket = aws_s3_bucket.worm.id\n rule {\n id = \"cross-region\"\n status = \"Enabled\"\n destination { bucket = var.replica_bucket_arn }\n }\n}\n", + "terraformKafkaAcls": "# tf-confluent-acls \u2014 per-topic ACL bundle\nresource \"confluent_kafka_acl\" \"telemetry_writer\" {\n kafka_cluster { id = var.cluster_id }\n resource_type = \"TOPIC\"\n resource_name = \"ai.telemetry.v1\"\n pattern_type = \"LITERAL\"\n principal = \"User:sa-sentinel-emitter\"\n host = \"*\"\n operation = \"WRITE\"\n permission = \"ALLOW\"\n}\n\nresource \"confluent_kafka_acl\" \"telemetry_audit_reader\" {\n kafka_cluster { id = var.cluster_id }\n resource_type = \"TOPIC\"\n resource_name = \"ai.telemetry.v1\"\n pattern_type = \"LITERAL\"\n principal = \"User:sa-auditor\"\n host = \"*\"\n operation = \"READ\"\n permission = \"ALLOW\"\n}\n", + "merkleAuditPython": "#!/usr/bin/env python3\n\"\"\"Daily Merkle-root WORM audit (EAGV).\"\"\"\nimport hashlib, json, time, boto3\nfrom cryptography.hazmat.primitives.asymmetric import ed25519\n\ndef merkle(leaves):\n if not leaves: return b\"\"\n layer = [hashlib.sha256(l).digest() for l in leaves]\n while len(layer) > 1:\n if len(layer) % 2: layer.append(layer[-1])\n layer = [hashlib.sha256(layer[i]+layer[i+1]).digest()\n for i in range(0,len(layer),2)]\n return layer[0]\n\ndef daily_audit(bucket, prefix, signing_key):\n s3 = boto3.client(\"s3\")\n leaves = []\n for o in s3.list_objects_v2(Bucket=bucket, Prefix=prefix).get(\"Contents\", []):\n body = s3.get_object(Bucket=bucket, Key=o[\"Key\"])[\"Body\"].read()\n leaves.append(body)\n root = merkle(leaves)\n sig = signing_key.sign(root)\n manifest = {\"date\": time.strftime(\"%Y-%m-%d\"),\n \"merkleRoot\": root.hex(),\n \"signature\": sig.hex(),\n \"leafCount\": len(leaves)}\n s3.put_object(Bucket=bucket, Key=f\"{prefix}/_manifests/{manifest['date']}.json\",\n Body=json.dumps(manifest).encode(),\n ObjectLockMode=\"COMPLIANCE\",\n ObjectLockRetainUntilDate=time.strftime(\"%Y-%m-%dT%H:%M:%SZ\"))\n return manifest\n", + "ciGithubActions": "# .github/workflows/eagv-pipeline.yml\nname: eagv-pipeline\non: [push, pull_request]\njobs:\n govern:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Lint rego\n run: opa fmt --diff policies/ && opa test policies/\n - name: Conftest gates\n run: conftest test --policy policies deploy/\n - name: Adversarial suite\n run: pytest tests/adversarial -q\n - name: Mechanistic audit\n run: python tools/circuit_scanner.py --threshold 0.92\n - name: Build + SLSA + Cosign\n run: |\n docker build -t app:${{ github.sha }} .\n cosign sign --yes app:${{ github.sha }}\n - name: Sigstore attest\n run: cosign attest --predicate evidence.json app:${{ github.sha }}\n - name: Canary deploy\n run: kubectl apply -f deploy/canary-5pct.yaml\n", + "nodeSidecar": "// node-governance-sidecar\nconst express = require(\"express\");\nconst { sign } = require(\"./pqc\");\nconst opa = require(\"./opa-client\");\nconst app = express();\napp.use(express.json());\n\napp.post(\"/intercept\", async (req, res) => {\n const decision = await opa.eval(\"eagv.runtime.allow\", req.body);\n if (!decision.allow) return res.status(403).json({ error: decision.reason });\n const envelope = {\n ts: new Date().toISOString(),\n modelId: req.body.modelId,\n inputHash: req.body.inputHash,\n decision,\n };\n envelope.signature = sign(JSON.stringify(envelope));\n // emit to Kafka topic ai.telemetry.v1\n res.json({ ok: true, envelope });\n});\n\napp.listen(7081);\n", + "fairnessTestPy": "#!/usr/bin/env python3\n\"\"\"FCRA/ECOA fairness pre-deploy gate.\"\"\"\nimport numpy as np, pandas as pd\n\ndef air(y_pred, group):\n rates = pd.Series(y_pred).groupby(group).mean()\n return rates.min() / rates.max()\n\ndef spd(y_pred, group, ref):\n rates = pd.Series(y_pred).groupby(group).mean()\n return rates - rates.loc[ref]\n\ndef gate(df, pred_col=\"approved\", group_col=\"protected_class\", ref=\"group_a\"):\n a = air(df[pred_col], df[group_col])\n s = spd(df[pred_col], df[group_col], ref).abs().max()\n if a < 0.8 or s > 0.05:\n raise SystemExit(f\"FAIL: AIR={a:.3f} SPD={s:.3f}\")\n print(f\"PASS: AIR={a:.3f} SPD={s:.3f}\")\n", + "kineticKillSwitch": "// kinetic-kill-switch (m-of-n threshold)\nconst { thresholdSign, verifyThreshold } = require(\"./threshold-crypto\");\n\nasync function executeKill(operatorId, reasonCode, signatures) {\n if (!verifyThreshold(signatures, /*m=*/3, /*n=*/5)) {\n throw new Error(\"threshold not met\");\n }\n await scada.cutPower(operatorId); // <60s SLA\n await net.disconnectVlan(operatorId);\n await audit.emit({ operatorId, reasonCode, signatures, ts: Date.now() });\n}\n", + "regulatorReportTemplate": "<!-- Markdown report template -->\n<title>Annex IV Technical Documentation \u2014 Model {{modelId}}\n\nRegulator-ready dossier covering EU AI Act Art. 11 + Annex IV for the\nhigh-risk AI system {{modelId}} operated by {{operator}}.\n\n\n\n## 1. General description\n- Intended purpose: {{purpose}}\n- Provider / deployer: {{provider}} / {{deployer}}\n- Versions covered: {{versions}}\n\n## 2. Detailed description\n- Architecture, training data, validation methodology\n- Logging (Art. 12) and human oversight (Art. 14)\n\n## 3. Risk management (Art. 9)\n- Hazard identification, evaluation, mitigations\n\n## 4. Performance & monitoring (Art. 15 / 17)\n- Accuracy, robustness, cyber-security\n\n## 5. Conformity assessment & post-market monitoring\n\n" + }, + "caseStudies": [ + { + "id": "CS-01", + "title": "G-SIFI bank \u2014 full-stack adoption", + "sector": "Banking", + "summary": "Top-10 G-SIFI rolled out the master framework across 1,200 AI use-cases.", + "outcomes": { + "controlsMapped": 247, + "evidenceAutomation": "94%", + "ICAAPPillar2AddOn": "GBP 380m", + "ISO42001Certification": "Achieved Q4 2027", + "AnnexIVDossiers": 38, + "FrontierDisclosures": 6 + } + }, + { + "id": "CS-02", + "title": "Fortune 500 insurer \u2014 fairness remediation", + "sector": "Insurance", + "summary": "Pricing AI remediated using LDA search; AIR moved 0.71 \u2192 0.86.", + "outcomes": { + "AIRBefore": 0.71, + "AIRAfter": 0.86, + "complaintReduction": "-42%", + "regulatorEngagement": "FCA + state DOI satisfied" + } + }, + { + "id": "CS-03", + "title": "Global asset manager \u2014 fiduciary AI advisor", + "sector": "Asset Management", + "summary": "Robo-advice platform certified under MAS FEAT + ISO 42001.", + "outcomes": { + "FEATAttestation": "Issued", + "suitabilityDeviation": "-31 bps", + "complaintRate": "0.03%" + } + }, + { + "id": "CS-04", + "title": "Frontier AI lab \u2014 MV-AGI stack", + "sector": "AI Research", + "summary": "Frontier lab adopted MV-AGI stack ahead of Art. 53/55 enforcement.", + "outcomes": { + "computeRegistryEntries": 12, + "capabilityEvalsPassed": 5, + "treatyDisclosures": 3, + "kineticTripwireDrills": 4 + } + }, + { + "id": "CS-05", + "title": "Global 2000 retailer \u2014 agentic workflows", + "sector": "Retail", + "summary": "Deployed governed agentic workflows for supply-chain optimisation with 0 containment incidents.", + "outcomes": { + "agents": 2400, + "containmentIncidents": 0, + "MTTD": "3.1 min", + "MTTR": "47 min" + } + }, + { + "id": "CS-06", + "title": "Sovereign-cloud government deployment", + "sector": "Public Sector", + "summary": "G7 government deployed sovereign-AI stack with treaty-aligned governance.", + "outcomes": { + "sovereignFoundationModels": 3, + "treatyDisclosures": 2, + "civilizationalDrillScore": "A-" + } + } + ], + "apiEndpoints": { + "prefix": "/api/ent-agi-gov-master", + "routes": [ + "", + "/meta", + "/executive-summary", + "/summary", + "/pillars", + "/pillars/:id", + "/regulatory", + "/regulatory/:axis", + "/architectures", + "/architectures/:id", + "/safety", + "/safety/:id", + "/civilizational", + "/civilizational/:id", + "/financial-mrm", + "/financial-mrm/:id", + "/kafka-gac", + "/kafka-gac/:id", + "/roadmap", + "/roadmap/phases", + "/roadmap/kpis", + "/reports", + "/reports/:id", + "/scenarios", + "/scenarios/:id", + "/schemas", + "/schemas/:name", + "/code-examples", + "/code-examples/:name", + "/case-studies", + "/case-studies/:id", + "/modules", + "/modules/:id", + "/sections/:id", + "/m1", + "/m2", + "/m3", + "/m4", + "/m5", + "/m6", + "/m7", + "/m8", + "/pillars/G1", + "/pillars/G2", + "/pillars/G3", + "/pillars/G4", + "/pillars/G5", + "/pillars/G6", + "/pillars/G7", + "/scenarios/GC1", + "/scenarios/GC2", + "/scenarios/GC3", + "/scenarios/GC4", + "/scenarios/GC5", + "/scenarios/GC6", + "/scenarios/GC7" + ] + } +} diff --git a/rag-agentic-dashboard/data/wfap-gemini-impl.json b/rag-agentic-dashboard/data/wfap-gemini-impl.json new file mode 100644 index 0000000..20f5938 --- /dev/null +++ b/rag-agentic-dashboard/data/wfap-gemini-impl.json @@ -0,0 +1,1628 @@ +{ + "meta": { + "docRef": "WFAP-GEMINI-IMPL-WP-036", + "version": "1.0.0", + "date": "2026-04-26", + "title": "WorkflowAI Pro / GeminiService \u2014 Enterprise Implementation Plan", + "subtitle": "Comprehensive implementation plan, technical architecture, data models, data flows, governance frameworks, and best-practice design guidelines for an enterprise AI-driven workflow recommendation, RAG chat, collaborative prompt engineering, enterprise model registry, AI safety reporting, and GeminiService security platform.", + "classification": "CONFIDENTIAL \u2014 Board / Enterprise Architects / AI Platform Engineers / Internal Audit / DPO", + "owner": "Group CTO + Chief AI Officer (CAIO) \u2014 co-signed by CISO, DPO, GC", + "audience": [ + "Board of Directors / Risk & Audit Committees", + "C-Suite (CEO, CFO, CRO, CISO, CAIO, CTO, COO)", + "Enterprise architects", + "AI platform engineers / SREs", + "Data scientists / prompt engineers", + "Researchers (AI safety, governance)", + "Regulators & supervisors (PRA, FCA, OCC, MAS, ICO)" + ], + "horizon": "2026-2030", + "regulatoryAlignment": [ + "EU AI Act (Regulation (EU) 2024/1689) \u2014 Articles 5, 9, 10, 12, 13, 14, 15, 53, 55", + "NIST AI RMF 1.0 + GenAI Profile (AI 600-1)", + "ISO/IEC 42001:2023 \u2014 AI Management System", + "ISO/IEC 23894:2023 \u2014 AI risk management", + "ISO/IEC 27001:2022 / 27701:2019 / 27018", + "GDPR / UK GDPR (Articles 5, 6, 22, 25, 32, 33, 34, 35)", + "OECD AI Principles", + "OWASP Top 10 for LLM Applications (2025)", + "MITRE ATLAS / STRIDE / LINDDUN", + "SR 11-7 / OCC 2011-12 \u2014 Model Risk Management", + "SOC 2 Type II / FedRAMP Moderate" + ], + "deliverableInventory": { + "modules": 12, + "architectureLayers": 7, + "dataFlows": 8, + "dataModels": 9, + "apis": 110, + "integrationPatterns": 8, + "schemas": 8, + "codeExamples": 12, + "caseStudies": 5, + "phases": 6, + "kpis": 15 + }, + "subjectSystem": { + "platform": "WorkflowAI Pro", + "geminiService": "GeminiService backend integration tier", + "scope": "Enterprise SaaS / private cloud / hybrid", + "scale": "10k concurrent workflows \u00b7 100k agents \u00b7 500k users / tenant", + "deploymentTopology": "Multi-region active-active; sovereign-cloud variant for EU/UK/US-Gov" + } + }, + "executiveSummary": { + "purpose": "To deliver a regulator-ready, board-approvable, end-to-end implementation plan for the WorkflowAI Pro platform with the GeminiService integration tier \u2014 covering architecture, data, governance, security, AI safety reporting, and operational excellence.", + "scope": "All AI capabilities of the platform, from workflow recommendation and adaptive UX through RAG chat, collaborative prompt engineering, model registry, and the GeminiService security/privacy substrate.", + "designPrinciples": [ + "Compliance-by-design: every capability ships with EU AI Act / GDPR / ISO 42001 controls", + "Defense-in-depth: 7 architectural planes with independent guardrails", + "Evidence-as-data: every action emits a signed telemetry envelope", + "Active learning with human-on-the-loop and cryptographically-signed feedback", + "Adaptive UX without dark patterns; transparency mandated", + "Grounded outputs only: RAG answers must cite or refuse", + "Zero-trust GeminiService: prompt-injection / Art. 5 / PII checks before every call" + ], + "keyOutcomes": { + "timeToGovernedDeployment": "\u2264 72 hours", + "ragGroundednessScore": "\u2265 0.92 faithfulness", + "promptCollabAdoption": "\u2265 80% of teams within 6 months", + "modelRegistryCoverage": "100% of production AI assets tagged & versioned", + "geminiBlockedHarmRate": "\u2265 99.5% on red-team suite", + "piiLeakageRate": "\u2264 0.01% (post-redaction sample audit)", + "incidentMTTR": "\u2264 60 min", + "auditReadiness": "\u2265 92% evidence automation" + }, + "boardNarrative": "WorkflowAI Pro upgrades enterprise productivity with AI while treating safety, privacy, and compliance as first-class platform capabilities \u2014 measurable, monitorable, and demonstrable to regulators." + }, + "M1_architecture": { + "id": "M1", + "title": "M1 \u2014 Platform Architecture (7-Plane Reference)", + "summary": "Seven-plane architecture isolating workload, governance, identity, data, AI, observability, and supply-chain concerns.", + "sections": [ + { + "id": "M1-S1", + "title": "Architecture Planes", + "planes": [ + { + "id": "P1", + "name": "Edge & Identity Plane", + "components": [ + "WAF/CDN", + "OIDC IdP", + "SCIM", + "FIDO2/WebAuthn", + "API Gateway" + ], + "responsibilities": "AuthN/AuthZ, rate limiting, geo routing" + }, + { + "id": "P2", + "name": "Application Plane", + "components": [ + "Next.js frontend", + "Node/Express API", + "Python services", + "BFF", + "Webhooks" + ], + "responsibilities": "Feature surfaces, orchestration, tenancy" + }, + { + "id": "P3", + "name": "AI Plane", + "components": [ + "GeminiService gateway", + "Prompt registry", + "RAG service", + "Recommender", + "Active-learning loop" + ], + "responsibilities": "All inference + retrieval" + }, + { + "id": "P4", + "name": "Governance Plane", + "components": [ + "Model registry", + "Policy engine (OPA)", + "Compliance engine", + "Evidence store" + ], + "responsibilities": "Policy decisions, evidence, attestations" + }, + { + "id": "P5", + "name": "Data Plane", + "components": [ + "Postgres/CRDB", + "Vector DB (pgvector/Weaviate)", + "Object store", + "Kafka", + "Cache" + ], + "responsibilities": "Persistence, lineage, search" + }, + { + "id": "P6", + "name": "Observability Plane", + "components": [ + "OTel collector", + "Prometheus", + "Loki/ELK", + "WORM telemetry topic", + "SIEM" + ], + "responsibilities": "Metrics, logs, traces, audit" + }, + { + "id": "P7", + "name": "Supply-Chain Plane", + "components": [ + "SLSA L3 build", + "Sigstore/Cosign", + "SBOM", + "Dependency scanner" + ], + "responsibilities": "Build integrity, SBOM, attestations" + } + ] + }, + { + "id": "M1-S2", + "title": "Deployment Topology", + "tiers": [ + { + "tier": "Edge", + "regions": "global PoPs", + "tech": "Cloudflare / AWS CloudFront" + }, + { + "tier": "App", + "regions": "primary + DR", + "tech": "EKS/GKE/AKS, blue-green" + }, + { + "tier": "AI", + "regions": "primary + DR", + "tech": "GPU node pools, KEDA, vLLM/Triton" + }, + { + "tier": "Data", + "regions": "active-active multi-region", + "tech": "Aurora/Spanner, replicated S3" + } + ] + }, + { + "id": "M1-S3", + "title": "Tenancy Model", + "patterns": [ + "Pool-multi-tenant (default) with row-level security and per-tenant KMS keys", + "Silo-per-tenant for regulated tenants (banks, gov)", + "Sovereign-cloud variant with in-region GeminiService endpoints" + ] + } + ] + }, + "M2_dataModels": { + "id": "M2", + "title": "M2 \u2014 Data Models", + "summary": "Core entities and relationships for the platform.", + "sections": [ + { + "id": "M2-S1", + "title": "Entity Catalogue", + "entities": [ + { + "id": "DM-01", + "name": "User", + "fields": "userId, tenantId, role[], skillProfile, locale, consents", + "owner": "IAM service" + }, + { + "id": "DM-02", + "name": "Workflow", + "fields": "workflowId, ownerId, dag, version, status, tags[]", + "owner": "Workflow service" + }, + { + "id": "DM-03", + "name": "Recommendation", + "fields": "recId, userId, candidateWorkflows[], context, score, feedback", + "owner": "Recommender" + }, + { + "id": "DM-04", + "name": "PromptTemplate", + "fields": "templateId, versions[], variables[], owner, visibility, tags[], lineage", + "owner": "Prompt registry" + }, + { + "id": "DM-05", + "name": "ModelRegistration", + "fields": "modelId, provider, version, sha256, evalRefs[], complianceTags[], rbacPolicyRef, status, rollbackTargetId", + "owner": "Model registry" + }, + { + "id": "DM-06", + "name": "RAGCorpus", + "fields": "corpusId, sourceRefs[], lineage, retentionClass, piiPolicy, embeddingModelId", + "owner": "RAG service" + }, + { + "id": "DM-07", + "name": "GeminiCall", + "fields": "callId, userId, modelId, promptHash, redactedPrompt, completionHash, safetyDecision, telemetrySig", + "owner": "GeminiService" + }, + { + "id": "DM-08", + "name": "Incident", + "fields": "incidentId, severity, signals[], affectedAssets[], status, narrative", + "owner": "SOC" + }, + { + "id": "DM-09", + "name": "EvidenceRecord", + "fields": "evidenceId, controlId, payloadHash, merkleRoot, signature, retainUntil", + "owner": "Compliance engine" + } + ] + }, + { + "id": "M2-S2", + "title": "Lineage & Versioning", + "rules": [ + "All entities are immutable-on-update (event-sourced + materialised views)", + "Every mutation emits a signed event into the WORM Kafka topic ai.audit.v1", + "PromptTemplate, ModelRegistration, RAGCorpus carry SemVer + content hash", + "Rollback = pointer flip to a prior signed version; never a destructive op" + ] + }, + { + "id": "M2-S3", + "title": "Retention & Classification", + "classes": [ + { + "class": "C1 Public", + "retention": "indefinite", + "storage": "S3 standard" + }, + { + "class": "C2 Internal", + "retention": "5 yr", + "storage": "S3 SSE-KMS" + }, + { + "class": "C3 Confidential", + "retention": "7 yr WORM", + "storage": "S3 Object Lock" + }, + { + "class": "C4 Restricted/PII", + "retention": "policy-driven", + "storage": "Tokenised + envelope encryption" + } + ] + } + ] + }, + "M3_dataFlows": { + "id": "M3", + "title": "M3 \u2014 Data Flows", + "summary": "Eight canonical end-to-end flows with governance hooks.", + "sections": [ + { + "id": "M3-S1", + "title": "Flow Catalogue", + "flows": [ + { + "id": "DF-01", + "name": "User \u2192 Workflow recommendation", + "stages": "context \u2192 recommender \u2192 policy gate \u2192 UI", + "governanceHooks": "consent check, fairness probe, telemetry" + }, + { + "id": "DF-02", + "name": "Active-learning feedback", + "stages": "user feedback \u2192 signer \u2192 kafka \u2192 trainer \u2192 recommender", + "governanceHooks": "Ed25519 signature, bias re-eval" + }, + { + "id": "DF-03", + "name": "RAG-grounded chat", + "stages": "prompt \u2192 retriever \u2192 reranker \u2192 GeminiService \u2192 faithfulness scorer \u2192 UI", + "governanceHooks": "PII redact, citation enforce, refusal policy" + }, + { + "id": "DF-04", + "name": "Collaborative prompt edit", + "stages": "edit \u2192 CRDT merge \u2192 variable lint \u2192 review \u2192 publish", + "governanceHooks": "RBAC, lineage, prompt-injection lint" + }, + { + "id": "DF-05", + "name": "Model registration", + "stages": "submit \u2192 evals \u2192 sign \u2192 register \u2192 tag \u2192 rollout", + "governanceHooks": "evals coverage, complianceTags, attestation" + }, + { + "id": "DF-06", + "name": "GeminiService inference", + "stages": "request \u2192 Art. 5 check \u2192 injection guard \u2192 call \u2192 safety classifier \u2192 response", + "governanceHooks": "telemetry envelope, decision log" + }, + { + "id": "DF-07", + "name": "AI safety incident", + "stages": "detection \u2192 triage \u2192 containment \u2192 notification \u2192 forensic \u2192 post-mortem", + "governanceHooks": "GDPR Art. 33/34, EU AI Act Art. 73" + }, + { + "id": "DF-08", + "name": "Adaptive UX evaluation", + "stages": "user signal \u2192 skill estimator \u2192 UX selector \u2192 A/B \u2192 ethics gate", + "governanceHooks": "no dark patterns, transparency, opt-out" + } + ] + }, + { + "id": "M3-S2", + "title": "Governance Hooks (cross-cutting)", + "hooks": [ + "Consent verifier (per-purpose GDPR Art. 6/7)", + "PII redactor (Microsoft Presidio + custom rules)", + "EU AI Act Art. 5 prohibited-practice check", + "Prompt-injection / jailbreak detector", + "Faithfulness scorer for RAG outputs", + "Fairness probe (AIR / SPD windows)", + "Telemetry signer (Ed25519, optional Dilithium3)", + "Evidence emitter (control \u2192 evidence record)" + ] + } + ] + }, + "M4_recommender": { + "id": "M4", + "title": "M4 \u2014 AI-Driven Workflow Recommendation & Active Learning", + "summary": "Two-tower recommender with bandit exploration, signed feedback loop, and bias guardrails.", + "sections": [ + { + "id": "M4-S1", + "title": "Recommender Architecture", + "components": [ + "Two-tower retrieval (user tower + workflow tower) on Vertex AI / SageMaker", + "Reranker LLM (Gemini Flash) with policy filter", + "Contextual bandit (LinUCB) for exploration", + "Post-rank fairness pass (group AIR \u2265 0.8)" + ] + }, + { + "id": "M4-S2", + "title": "Active Learning Loop", + "stages": [ + "Implicit feedback: dwell, completion, abandonment", + "Explicit feedback: thumbs / rationale / correction", + "Cryptographic signature on every feedback event (Ed25519)", + "Daily retrain with drift gate (PSI \u2264 0.1, no fairness regression)", + "Shadow + canary deploy (5% \u2192 25% \u2192 100%)" + ] + }, + { + "id": "M4-S3", + "title": "Cold-start & Privacy", + "controls": [ + "Skill-profile bootstrap from role + opt-in onboarding survey", + "Federated personalisation option (no raw signals leave device)", + "Differential privacy noise (\u03b5 \u2264 4) on aggregate analytics" + ] + }, + { + "id": "M4-S4", + "title": "APIs", + "routes": [ + "POST /api/recommend/workflows", + "POST /api/recommend/feedback", + "GET /api/recommend/profile", + "POST /api/recommend/retrain (admin)" + ] + } + ] + }, + "M5_adaptiveUx": { + "id": "M5", + "title": "M5 \u2014 Adaptive Content & UI by Context and Skill", + "summary": "Skill-aware progressive disclosure and content adaptation with anti-dark-pattern guardrails.", + "sections": [ + { + "id": "M5-S1", + "title": "Skill Estimator", + "design": [ + "Bayesian skill model per capability (workflow design, prompt eng, data analysis)", + "Inputs: completion of guided tasks, support tickets, self-rating", + "Decay function for inactivity" + ] + }, + { + "id": "M5-S2", + "title": "UX Adaptation Patterns", + "patterns": [ + "Progressive disclosure tiers: Novice / Practitioner / Expert / Power", + "Inline coaching with dismissible cards", + "Reading-level adaptation (Flesch-Kincaid 8/12/16)", + "Locale + accessibility (WCAG 2.2 AA, ARIA, keyboard-only)" + ] + }, + { + "id": "M5-S3", + "title": "Ethics & Transparency", + "guardrails": [ + "No dark patterns (FTC + EU 2026 Digital Fairness Act)", + "Always-visible 'Why am I seeing this?' explainer", + "User-facing UX preference reset", + "Adaptation events emitted with consent flag" + ] + } + ] + }, + "M6_ragChat": { + "id": "M6", + "title": "M6 \u2014 High-Assurance RAG-Based Grounded Chat", + "summary": "RAG with lineage, citation enforcement, faithfulness scoring, and refusal-on-low-evidence.", + "sections": [ + { + "id": "M6-S1", + "title": "Retrieval Pipeline", + "stages": [ + "Query rewrite (intent + decomposition)", + "Hybrid search (BM25 + dense + filters)", + "Reranker (cross-encoder)", + "Context window builder with token budget + diversity", + "Citation pinner (chunk-level provenance)" + ] + }, + { + "id": "M6-S2", + "title": "Generation & Faithfulness", + "controls": [ + "Constrained generation: 'cite or refuse'", + "Faithfulness score (Q\u00b2/AlignScore/RAGAS) gating \u2265 0.92", + "Hallucination flag on unsupported claims", + "Refusal templates: 'I do not have evidence in your corpus to answer that.'" + ] + }, + { + "id": "M6-S3", + "title": "Corpus Governance", + "controls": [ + "Source allowlist & licence metadata", + "PII redaction at ingestion (Presidio + DLP)", + "Retention class on every chunk", + "Per-document RBAC enforced at query time (post-retrieval filter)", + "Right-to-be-forgotten propagation (vector deletion + reindex)" + ] + }, + { + "id": "M6-S4", + "title": "APIs", + "routes": [ + "POST /api/rag/chat", + "POST /api/rag/ingest", + "DELETE /api/rag/document/:id (RTBF)", + "GET /api/rag/corpus/:id/manifest" + ] + } + ] + }, + "M7_promptCollab": { + "id": "M7", + "title": "M7 \u2014 Collaborative Prompt Engineering", + "summary": "Multi-user prompt template lifecycle with CRDT editing, lineage, and review workflow.", + "sections": [ + { + "id": "M7-S1", + "title": "Lifecycle Stages", + "stages": [ + "Draft", + "Review", + "Approved", + "Published", + "Deprecated", + "Archived" + ] + }, + { + "id": "M7-S2", + "title": "Collaboration Mechanics", + "design": [ + "CRDT (Yjs) for real-time co-editing", + "Variable schema with type, default, sensitivity", + "Variable-link UI to dataset / workflow context", + "Live test panel against canary model + sample dataset", + "PR-style review: 2-of-N approvers; CI runs eval suite" + ] + }, + { + "id": "M7-S3", + "title": "Lineage & Provenance", + "controls": [ + "Every version content-addressed (sha256)", + "Parent/child template links + diff view", + "Usage telemetry: per-template invocation count, faithfulness, satisfaction", + "Export/import as signed bundles (tar.gz + sig)" + ] + }, + { + "id": "M7-S4", + "title": "APIs", + "routes": [ + "POST /api/prompts/templates", + "GET /api/prompts/templates/:id", + "PATCH /api/prompts/templates/:id", + "POST /api/prompts/templates/:id/review", + "POST /api/prompts/templates/:id/publish", + "GET /api/prompts/templates/:id/lineage", + "POST /api/prompts/test" + ] + } + ] + }, + "M8_modelRegistry": { + "id": "M8", + "title": "M8 \u2014 Enterprise Model Registry Governance", + "summary": "RBAC, compliance metadata, rollback, tagging, attestations.", + "sections": [ + { + "id": "M8-S1", + "title": "Registry Schema", + "fields": [ + "modelId, provider, family, version, sha256", + "evalRefs[]: pointers to eval suites and results", + "complianceTags[]: 'EU_AI_ACT_HIGH_RISK', 'GDPR_DPIA', 'SR_11_7_TIER_1'", + "rbacPolicyRef: OPA bundle key", + "status: draft|registered|approved|published|paused|retired", + "rollbackTargetId: previous-known-good model pointer", + "ownerSubjectId; approvers[]; signatures[]" + ] + }, + { + "id": "M8-S2", + "title": "RBAC & Policy", + "roles": [ + "model_author", + "model_validator", + "model_approver", + "model_operator", + "auditor (read-only)", + "dpo (read+veto on PII concerns)" + ], + "policies": [ + "deploy_gate.rego: signature + IMV + DPIA non-expired", + "high_risk_label.rego: Annex IV dossier present", + "rollback_window.rego: rollback always within 30s window" + ] + }, + { + "id": "M8-S3", + "title": "Tagging & Search", + "design": [ + "Tag namespace: regulatory, sector, capability, sensitivity, lifecycle", + "Full-text + facet search across registry", + "Saved queries for audit & supervisor read-only views" + ] + }, + { + "id": "M8-S4", + "title": "APIs", + "routes": [ + "POST /api/models/register", + "GET /api/models/:id", + "POST /api/models/:id/approve", + "POST /api/models/:id/publish", + "POST /api/models/:id/rollback", + "POST /api/models/:id/tag", + "GET /api/models/search", + "GET /api/models/:id/attestations" + ] + } + ] + }, + "M9_safetyReporting": { + "id": "M9", + "title": "M9 \u2014 AI Safety & Global Governance Reporting", + "summary": "Reporting framework spanning existential risk, misuse, bias, threat assessment, alignment failure, and international collaboration.", + "sections": [ + { + "id": "M9-S1", + "title": "Report Catalogue", + "reports": [ + { + "id": "SR-01", + "name": "Existential Risk Outlook", + "cadence": "Annual", + "audience": "Board + Treaty Authority" + }, + { + "id": "SR-02", + "name": "Misuse & Dual-Use Threat Assessment", + "cadence": "Semi-annual", + "audience": "CISO + Treaty + GC" + }, + { + "id": "SR-03", + "name": "Bias & Fairness Report", + "cadence": "Quarterly", + "audience": "DPO + Compliance + Board" + }, + { + "id": "SR-04", + "name": "Alignment Failure Scenarios", + "cadence": "Quarterly tabletop + post-incident", + "audience": "Board + CAIO + research community" + }, + { + "id": "SR-05", + "name": "International Collaboration Brief", + "cadence": "Quarterly", + "audience": "Treaty Liaison Officer" + }, + { + "id": "SR-06", + "name": "Capability Evaluation Disclosure", + "cadence": "Per material capability change", + "audience": "ICGC / regulator" + }, + { + "id": "SR-07", + "name": "Incident & Near-Miss Register", + "cadence": "Continuous", + "audience": "CISO + Internal Audit" + }, + { + "id": "SR-08", + "name": "Annual AI Safety Statement", + "cadence": "Annual public", + "audience": "Public + investors" + } + ] + }, + { + "id": "M9-S2", + "title": "Risk Taxonomy", + "categories": [ + "Existential / civilizational", + "Misuse (CBRN, cyber, mass-disinfo)", + "Bias / disparate impact", + "Privacy / re-identification", + "Alignment failure (specification gaming, deceptive alignment)", + "Containment escape / agentic over-reach", + "Concentration / monoculture", + "Conduct / consumer harm" + ] + }, + { + "id": "M9-S3", + "title": "International Collaboration", + "channels": [ + "ICGC compute & capability disclosure", + "Bletchley/Seoul/Paris commitments", + "OECD AI Policy Observatory", + "G7 Hiroshima AI Process Code of Conduct", + "AISI / UK AISI / US AISI evaluation participation", + "Council of Europe AI Convention compliance" + ] + }, + { + "id": "M9-S4", + "title": "APIs", + "routes": [ + "GET /api/safety/reports", + "GET /api/safety/reports/:id", + "POST /api/safety/incidents", + "GET /api/safety/risk-register", + "POST /api/safety/disclosures (treaty)" + ] + } + ] + }, + "M10_geminiSecurity": { + "id": "M10", + "title": "M10 \u2014 GeminiService Security & Privacy Controls", + "summary": "Telemetry integrity, GDPR PII redaction, EU AI Act Art. 5 checks, adversarial-prompt defenses.", + "sections": [ + { + "id": "M10-S1", + "title": "GeminiService Gateway", + "design": [ + "All Gemini calls routed through internal gateway (no direct SDK from frontend)", + "Per-tenant API keys vaulted in HSM/KMS", + "mTLS to provider; egress allowlist; outbound DLP", + "Per-call decision log signed (Ed25519) and shipped to WORM Kafka" + ] + }, + { + "id": "M10-S2", + "title": "Pre-Call Pipeline (in order)", + "stages": [ + "1. AuthN/AuthZ (OIDC + scope + tenancy)", + "2. Rate / cost guard (token budget per user/tenant)", + "3. PII redactor (Presidio + custom regex + ML classifier)", + "4. EU AI Act Art. 5 prohibited-practice classifier (manipulation, social scoring, biometric categorisation, predictive policing for individuals, etc.)", + "5. Prompt-injection / jailbreak detector (rules + LLM judge + perplexity heuristic)", + "6. Constitutional / policy filter", + "7. Telemetry envelope creation + signature" + ] + }, + { + "id": "M10-S3", + "title": "Post-Call Pipeline", + "stages": [ + "1. Output safety classifier (toxicity, self-harm, illegal, CSAM)", + "2. PII / secrets leakage scan (egress redactor)", + "3. Faithfulness / citation check (RAG path)", + "4. Final policy filter; deliver or refuse", + "5. Append response hash + final decision to telemetry envelope" + ] + }, + { + "id": "M10-S4", + "title": "Telemetry Integrity", + "controls": [ + "Append-only Kafka topic ai.gemini.telemetry.v1 with mTLS + ACLs", + "Daily Merkle root anchored to RFC 3161 timestamp + (optional) blockchain anchor", + "PQC-ready signatures (Dilithium3 dual-signature option)", + "Tamper alarms on hash-chain breaks (auto-incident creation)" + ] + }, + { + "id": "M10-S5", + "title": "Adversarial Defenses", + "defenses": [ + "Multi-layer prompt-injection detection (pre-, mid-, post-)", + "Tool-call allowlisting + scoped credentials per call", + "Indirect-prompt-injection sanitisation on retrieved content", + "Canary tokens to detect data exfiltration via prompts", + "Red-team test suite gated in CI (block release if regression)" + ] + }, + { + "id": "M10-S6", + "title": "APIs", + "routes": [ + "POST /api/gemini/generate", + "POST /api/gemini/embed", + "POST /api/gemini/vision", + "GET /api/gemini/telemetry/:callId", + "GET /api/gemini/policies" + ] + } + ] + }, + "M11_taskReport": { + "id": "M11", + "title": "M11 \u2014 Task & Report Management", + "summary": "End-user and admin features for tasks, reports, exports, and audit packs.", + "sections": [ + { + "id": "M11-S1", + "title": "Task Management", + "features": [ + "Task DAG visualisation (D3/dagre)", + "Assignment & SLA tracking", + "Comments + @mentions + activity stream", + "Linked artefacts: prompts, models, RAG corpora, evidence", + "Bulk operations with idempotency keys" + ] + }, + { + "id": "M11-S2", + "title": "Report Generation", + "features": [ + "Templated reports (Markdown with /<abstract>/<content>)", + "PDF/A-3 export with embedded JSON-LD evidence", + "Scheduled reports (cron + event-driven)", + "Distribution: email (DMARC), Slack/Teams, SFTP, S3 dropzone", + "Auditor read-only export channel" + ] + }, + { + "id": "M11-S3", + "title": "APIs", + "routes": [ + "POST /api/tasks", + "GET /api/tasks/:id", + "PATCH /api/tasks/:id", + "POST /api/tasks/:id/comment", + "GET /api/reports/templates", + "POST /api/reports/render", + "POST /api/reports/schedule", + "GET /api/reports/exports/:id" + ] + } + ] + }, + "M12_implementation": { + "id": "M12", + "title": "M12 \u2014 Implementation Strategy & Integration Patterns", + "summary": "Step-by-step strategy, module boundaries, and integration patterns for enterprise deployment.", + "sections": [ + { + "id": "M12-S1", + "title": "Six-Phase Plan (52 weeks)", + "phases": [ + { + "phase": "P1 Foundations", + "weeks": "1-6", + "deliverables": [ + "Tenancy model", + "Identity (OIDC/SCIM)", + "OPA bundle bootstrap", + "Kafka WORM cluster", + "Skeleton APIs" + ] + }, + { + "phase": "P2 Governance Spine", + "weeks": "7-14", + "deliverables": [ + "Model registry + RBAC", + "Compliance engine", + "Evidence store", + "Telemetry envelopes" + ] + }, + { + "phase": "P3 AI Core", + "weeks": "15-26", + "deliverables": [ + "GeminiService gateway", + "Prompt registry + collab", + "RAG service + faithfulness", + "Recommender v1" + ] + }, + { + "phase": "P4 Adaptive UX & Tasks", + "weeks": "27-34", + "deliverables": [ + "Skill estimator", + "Adaptive UI", + "Task DAG", + "Reports v1" + ] + }, + { + "phase": "P5 Safety Reporting & Treaty", + "weeks": "35-44", + "deliverables": [ + "Safety report suite", + "Treaty disclosure pack", + "Tabletop GC1-GC7" + ] + }, + { + "phase": "P6 Hardening & Certification", + "weeks": "45-52", + "deliverables": [ + "ISO 42001 cert", + "SOC 2 Type II", + "Annex IV pilots", + "Pen-test + red-team" + ] + } + ] + }, + { + "id": "M12-S2", + "title": "Module Boundaries", + "boundaries": [ + "Identity service (P1) \u2014 single source of truth for users/roles", + "Workflow service \u2014 owns workflow DAGs; consumes recommendations", + "Recommender service \u2014 stateless API; trained offline; reads features from feature store", + "Prompt registry \u2014 owns templates + lineage; emits events", + "RAG service \u2014 owns corpora + retrieval; isolates per-tenant indices", + "Model registry \u2014 owns ModelRegistration; enforces RBAC + signatures", + "GeminiService gateway \u2014 single egress point to provider", + "Compliance engine \u2014 read-side projection from event log; emits coverage scorecards", + "Observability \u2014 strictly read-only consumer of telemetry topics" + ] + }, + { + "id": "M12-S3", + "title": "Integration Patterns", + "patterns": [ + "Event-driven via Kafka (ai.audit.v1, ai.gemini.telemetry.v1, ai.recsys.events.v1)", + "Synchronous REST/gRPC behind API gateway with mTLS", + "Webhooks for tenant-side integrations (signed payloads, replay protection)", + "OIDC-federated SSO + SCIM provisioning", + "Outbound connectors: Slack/Teams, Jira, ServiceNow, Splunk, Datadog", + "Data-residency routing via gateway + per-region GeminiService endpoints", + "Sovereign-cloud variant with no cross-border calls", + "BYOK (Bring-Your-Own-Key) for tenant KMS" + ] + }, + { + "id": "M12-S4", + "title": "KPIs / OKRs", + "kpis": [ + { + "id": "KPI-01", + "name": "Time-to-governed-deployment", + "target": "\u2264 72 h" + }, + { + "id": "KPI-02", + "name": "RAG faithfulness", + "target": "\u2265 0.92" + }, + { + "id": "KPI-03", + "name": "Prompt collab adoption", + "target": "\u2265 80% teams" + }, + { + "id": "KPI-04", + "name": "Model registry coverage", + "target": "100%" + }, + { + "id": "KPI-05", + "name": "Gemini blocked-harm rate", + "target": "\u2265 99.5%" + }, + { + "id": "KPI-06", + "name": "PII leakage", + "target": "\u2264 0.01%" + }, + { + "id": "KPI-07", + "name": "Containment MTTR", + "target": "\u2264 60 min" + }, + { + "id": "KPI-08", + "name": "Evidence automation", + "target": "\u2265 92%" + }, + { + "id": "KPI-09", + "name": "Alignment-drift MTTD", + "target": "\u2264 4 min" + }, + { + "id": "KPI-10", + "name": "Active-learning loop latency", + "target": "\u2264 24 h to retrain" + }, + { + "id": "KPI-11", + "name": "Adaptive-UX opt-out completion", + "target": "\u2264 3 clicks" + }, + { + "id": "KPI-12", + "name": "Audit finding closure", + "target": "\u2264 90 d (high)" + }, + { + "id": "KPI-13", + "name": "Recommender AIR floor", + "target": "\u2265 0.8" + }, + { + "id": "KPI-14", + "name": "Telemetry continuity", + "target": "\u2265 99.99%" + }, + { + "id": "KPI-15", + "name": "Adversarial-prompt block rate", + "target": "\u2265 99% on red-team set" + } + ] + }, + { + "id": "M12-S5", + "title": "Risk Register (top 8)", + "risks": [ + { + "id": "R1", + "name": "Prompt-injection via retrieved content", + "mitigation": "Indirect-injection sanitiser + tool allowlist" + }, + { + "id": "R2", + "name": "Hallucination in RAG chat", + "mitigation": "Faithfulness gate + cite-or-refuse" + }, + { + "id": "R3", + "name": "PII leakage to provider", + "mitigation": "Pre-call redactor + egress DLP + telemetry audit" + }, + { + "id": "R4", + "name": "Bias amplification via active learning", + "mitigation": "Per-loop fairness gate + counterfactual eval" + }, + { + "id": "R5", + "name": "Model rollback failure", + "mitigation": "Always-on N-1 hot path + 30s rollback test in CI" + }, + { + "id": "R6", + "name": "Telemetry tampering", + "mitigation": "Hash-chained WORM + Merkle anchor + alarms" + }, + { + "id": "R7", + "name": "EU AI Act Art. 5 violation in user prompt", + "mitigation": "Pre-call classifier + refusal templates" + }, + { + "id": "R8", + "name": "Concentration risk on Gemini", + "mitigation": "Multi-provider abstraction + benchmark fail-over" + } + ] + } + ] + }, + "schemas": { + "promptTemplate": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/prompt-template.json", + "type": "object", + "required": [ + "templateId", + "version", + "owner", + "body", + "variables" + ], + "properties": { + "templateId": { + "type": "string" + }, + "version": { + "type": "string" + }, + "owner": { + "type": "string" + }, + "body": { + "type": "string" + }, + "variables": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "type" + ], + "properties": { + "name": { + "type": "string" + }, + "type": { + "enum": [ + "string", + "number", + "bool", + "enum", + "json" + ] + }, + "default": {}, + "sensitivity": { + "enum": [ + "public", + "internal", + "confidential", + "pii" + ] + }, + "linkTo": { + "type": "string" + } + } + } + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "lineage": { + "type": "object" + } + } + }, + "modelRegistration": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/model-registration.json", + "type": "object", + "required": [ + "modelId", + "provider", + "version", + "sha256", + "status" + ], + "properties": { + "modelId": { + "type": "string" + }, + "provider": { + "type": "string" + }, + "version": { + "type": "string" + }, + "sha256": { + "type": "string", + "pattern": "^[A-Fa-f0-9]{64}$" + }, + "evalRefs": { + "type": "array", + "items": { + "type": "string" + } + }, + "complianceTags": { + "type": "array", + "items": { + "type": "string" + } + }, + "rbacPolicyRef": { + "type": "string" + }, + "status": { + "enum": [ + "draft", + "registered", + "approved", + "published", + "paused", + "retired" + ] + }, + "rollbackTargetId": { + "type": "string" + }, + "signatures": { + "type": "array" + } + } + }, + "ragQueryEnvelope": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/rag-query-envelope.json", + "type": "object", + "required": [ + "queryId", + "userId", + "tenantId", + "corpusId", + "query", + "ts" + ], + "properties": { + "queryId": { + "type": "string" + }, + "userId": { + "type": "string" + }, + "tenantId": { + "type": "string" + }, + "corpusId": { + "type": "string" + }, + "query": { + "type": "string" + }, + "ts": { + "type": "string", + "format": "date-time" + }, + "redactionFlags": { + "type": "array" + }, + "consents": { + "type": "object" + } + } + }, + "geminiCallEnvelope": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/gemini-call-envelope.json", + "type": "object", + "required": [ + "callId", + "userId", + "modelId", + "promptHash", + "ts", + "signature" + ], + "properties": { + "callId": { + "type": "string" + }, + "userId": { + "type": "string" + }, + "tenantId": { + "type": "string" + }, + "modelId": { + "type": "string" + }, + "promptHash": { + "type": "string" + }, + "redactedPromptPreview": { + "type": "string" + }, + "completionHash": { + "type": "string" + }, + "safetyDecision": { + "enum": [ + "allow", + "warn", + "refuse" + ] + }, + "art5Decision": { + "enum": [ + "allow", + "block" + ] + }, + "injectionScore": { + "type": "number" + }, + "ts": { + "type": "string", + "format": "date-time" + }, + "signature": { + "type": "object", + "required": [ + "alg", + "value", + "keyId" + ] + } + } + }, + "feedbackEvent": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/feedback-event.json", + "type": "object", + "required": [ + "eventId", + "userId", + "subjectId", + "subjectType", + "verdict", + "signature" + ], + "properties": { + "eventId": { + "type": "string" + }, + "userId": { + "type": "string" + }, + "subjectId": { + "type": "string" + }, + "subjectType": { + "enum": [ + "recommendation", + "rag-answer", + "prompt", + "workflow" + ] + }, + "verdict": { + "enum": [ + "up", + "down", + "correct", + "abandon" + ] + }, + "rationale": { + "type": "string" + }, + "signature": { + "type": "object" + } + } + }, + "recommendation": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/recommendation.json", + "type": "object", + "required": [ + "recId", + "userId", + "candidates", + "ts" + ], + "properties": { + "recId": { + "type": "string" + }, + "userId": { + "type": "string" + }, + "candidates": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string" + }, + "score": { + "type": "number" + }, + "reasonCodes": { + "type": "array" + } + } + } + }, + "context": { + "type": "object" + }, + "fairness": { + "type": "object" + }, + "ts": { + "type": "string", + "format": "date-time" + } + } + }, + "evidenceRecord": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/evidence-record.json", + "type": "object", + "required": [ + "evidenceId", + "controlId", + "payloadHash", + "merkleRoot", + "signature", + "retainUntil" + ], + "properties": { + "evidenceId": { + "type": "string" + }, + "controlId": { + "type": "string" + }, + "payloadHash": { + "type": "string" + }, + "merkleRoot": { + "type": "string" + }, + "signature": { + "type": "object" + }, + "retainUntil": { + "type": "string", + "format": "date-time" + } + } + }, + "incidentRecord": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/incident-record.json", + "type": "object", + "required": [ + "incidentId", + "severity", + "status", + "openedAt" + ], + "properties": { + "incidentId": { + "type": "string" + }, + "severity": { + "enum": [ + "SEV-3", + "SEV-2", + "SEV-1", + "SEV-0" + ] + }, + "status": { + "enum": [ + "open", + "contained", + "resolved", + "post-mortem" + ] + }, + "category": { + "type": "string" + }, + "affectedAssets": { + "type": "array" + }, + "openedAt": { + "type": "string", + "format": "date-time" + }, + "narrative": { + "type": "string" + } + } + } + }, + "codeExamples": { + "geminiGatewayPython": "#!/usr/bin/env python3\n\"\"\"GeminiService gateway \u2014 pre/post pipeline (FastAPI).\"\"\"\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel\nimport hashlib, time\nfrom cryptography.hazmat.primitives.asymmetric import ed25519\nfrom policy import art5_check, injection_score, redact_pii, output_safety\n\napp = FastAPI()\nSK = ed25519.Ed25519PrivateKey.generate() # demo only; load from KMS\n\nclass GenReq(BaseModel):\n user_id: str\n tenant_id: str\n model_id: str\n prompt: str\n\n@app.post(\"/api/gemini/generate\")\ndef generate(req: GenReq, authorization: str = Header(...)):\n redacted, flags = redact_pii(req.prompt)\n if art5_check(redacted) == \"block\":\n raise HTTPException(451, \"Art. 5 prohibited practice\")\n if injection_score(redacted) > 0.85:\n raise HTTPException(400, \"prompt injection suspected\")\n completion = call_gemini(req.model_id, redacted)\n if output_safety(completion) == \"refuse\":\n return {\"refused\": True, \"reason\": \"safety classifier\"}\n envelope = {\n \"callId\": hashlib.sha256(f\"{req.user_id}{time.time_ns()}\".encode()).hexdigest(),\n \"userId\": req.user_id, \"tenantId\": req.tenant_id,\n \"modelId\": req.model_id,\n \"promptHash\": hashlib.sha256(req.prompt.encode()).hexdigest(),\n \"completionHash\": hashlib.sha256(completion.encode()).hexdigest(),\n \"safetyDecision\": \"allow\", \"art5Decision\": \"allow\",\n \"ts\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n }\n sig = SK.sign(json.dumps(envelope, sort_keys=True).encode()).hex()\n envelope[\"signature\"] = {\"alg\": \"Ed25519\", \"value\": sig, \"keyId\": \"kms:gemini-gw-2026\"}\n emit_kafka(\"ai.gemini.telemetry.v1\", envelope)\n return {\"completion\": completion, \"envelope\": envelope}\n", + "ragChatTypeScript": "// /api/rag/chat \u2014 Express + retriever + faithfulness gate\nimport express from \"express\";\nimport { hybridSearch, rerank, faithfulness, redact } from \"./rag\";\nconst app = express();\napp.use(express.json());\n\napp.post(\"/api/rag/chat\", async (req, res) => {\n const { tenantId, userId, corpusId, question } = req.body;\n const safe = redact(question);\n const hits = await hybridSearch(corpusId, safe, { tenantAcl: tenantId });\n const ranked = await rerank(safe, hits);\n if (ranked.length === 0) {\n return res.json({ refused: true, reason: \"no evidence in corpus\" });\n }\n const draft = await callGemini({ system: SYSTEM_CITE_OR_REFUSE, ctx: ranked, q: safe });\n const score = await faithfulness(draft, ranked);\n if (score < 0.92) {\n return res.json({ refused: true, reason: \"low faithfulness\", score });\n }\n res.json({ answer: draft, citations: ranked.map(r => r.docRef), score });\n});\n", + "modelRegistryNode": "// Model registry \u2014 register / approve / rollback\nconst express = require(\"express\");\nconst { sign, verify } = require(\"./pqc\");\nconst opa = require(\"./opa\");\nconst router = express.Router();\n\nrouter.post(\"/api/models/register\", async (req, res) => {\n const m = req.body;\n if (!/^[A-Fa-f0-9]{64}$/.test(m.sha256)) return res.status(400).json({ error: \"bad sha256\" });\n const decision = await opa.eval(\"wfap.deploy_gate.allow\", { model: m });\n if (!decision.allow) return res.status(403).json(decision);\n m.status = \"registered\";\n m.signatures = [sign(m)];\n await db.models.insert(m);\n res.json(m);\n});\n\nrouter.post(\"/api/models/:id/rollback\", async (req, res) => {\n const cur = await db.models.find(req.params.id);\n if (!cur.rollbackTargetId) return res.status(400).json({ error: \"no rollback target\" });\n const tgt = await db.models.find(cur.rollbackTargetId);\n await db.models.update(cur.id, { status: \"paused\" });\n await db.models.update(tgt.id, { status: \"published\" });\n emitAudit({ type: \"model.rollback\", from: cur.id, to: tgt.id });\n res.json({ rolledBackTo: tgt.id });\n});\n\nmodule.exports = router;\n", + "promptCollabCRDT": "// Prompt template collaborative editor (Yjs server)\nconst Y = require(\"yjs\");\nconst { setupWSConnection } = require(\"y-websocket/bin/utils\");\nconst WebSocket = require(\"ws\");\n\nconst wss = new WebSocket.Server({ port: 1234 });\nwss.on(\"connection\", (conn, req) => {\n const auth = verifyJwt(req.headers[\"sec-websocket-protocol\"]);\n if (!auth) return conn.close(4401);\n setupWSConnection(conn, req, {\n docName: `prompt:${auth.tenantId}:${req.url.slice(1)}`,\n gc: true,\n });\n conn.on(\"close\", () => emitAudit({ type: \"prompt.session.close\", user: auth.sub }));\n});\n", + "recommenderActiveLearning": "#!/usr/bin/env python3\n\"\"\"Active-learning loop \u2014 drift gate + fairness gate.\"\"\"\nimport pandas as pd, numpy as np\nfrom cryptography.hazmat.primitives.asymmetric import ed25519\n\ndef psi(a, b, bins=10):\n qs = np.linspace(0,1,bins+1)\n cuts = np.quantile(np.concatenate([a,b]), qs)\n pa,_ = np.histogram(a, cuts); pa = pa/pa.sum()+1e-9\n pb,_ = np.histogram(b, cuts); pb = pb/pb.sum()+1e-9\n return float(np.sum((pa-pb)*np.log(pa/pb)))\n\ndef air(scores, group):\n rates = pd.Series(scores).groupby(group).mean()\n return rates.min()/rates.max()\n\ndef gate(new_scores, old_scores, groups):\n if psi(new_scores, old_scores) > 0.1: raise SystemExit(\"PSI drift\")\n if air(new_scores, groups) < 0.8: raise SystemExit(\"AIR floor\")\n print(\"PASS\")\n", + "regoDeployGate": "package wfap.deploy_gate\n\n# OPA policy gating model deployment\ndefault allow = false\n\nallow {\n input.model.signatures[_].verified\n input.model.evalRefs[_]\n not expired_dpia\n has_required_tags\n}\n\nexpired_dpia {\n time.parse_rfc3339_ns(input.model.dpia.expiresAt) < time.now_ns()\n}\n\nhas_required_tags {\n required := {\"FAIRNESS_TESTED\", \"PII_REDACTION_VERIFIED\"}\n set := {t | t := input.model.complianceTags[_]}\n required - set == set()\n}\n", + "art5Classifier": "#!/usr/bin/env python3\n\"\"\"EU AI Act Art. 5 prohibited-practice classifier (heuristic + LLM judge).\"\"\"\nPROHIBITED = [\n \"subliminal_techniques\",\n \"exploitation_of_vulnerabilities\",\n \"social_scoring_individuals\",\n \"biometric_categorisation_sensitive\",\n \"real_time_remote_biometric_id\",\n \"predictive_policing_individual\",\n \"emotion_recognition_workplace_education\",\n \"untargeted_facial_image_scraping\",\n]\n\ndef art5_check(text: str) -> str:\n # 1. rule-based fast path\n if any(k in text.lower() for k in [\"social score\", \"rank citizens\", \"predict who will commit\"]):\n return \"block\"\n # 2. LLM judge (Gemini Flash) \u2014 JSON schema response\n judge = call_gemini_judge(text, PROHIBITED)\n return \"block\" if judge.get(\"matches\") else \"allow\"\n", + "piiRedactorPython": "#!/usr/bin/env python3\n\"\"\"GDPR PII redactor \u2014 Presidio + custom rules.\"\"\"\nfrom presidio_analyzer import AnalyzerEngine\nfrom presidio_anonymizer import AnonymizerEngine\n\nANALYZER = AnalyzerEngine()\nANON = AnonymizerEngine()\n\ndef redact_pii(text: str, lang: str = \"en\"):\n results = ANALYZER.analyze(text=text, language=lang,\n entities=[\"PERSON\",\"EMAIL_ADDRESS\",\"PHONE_NUMBER\",\"CREDIT_CARD\",\n \"IBAN_CODE\",\"IP_ADDRESS\",\"LOCATION\",\"UK_NHS\",\"US_SSN\"])\n out = ANON.anonymize(text=text, analyzer_results=results)\n flags = sorted({r.entity_type for r in results})\n return out.text, flags\n", + "merkleAuditTelemetry": "#!/usr/bin/env python3\n\"\"\"Daily Merkle audit of GeminiService telemetry.\"\"\"\nimport hashlib, json, time, boto3\n\ndef merkle(leaves):\n layer = [hashlib.sha256(l).digest() for l in leaves] or [b\"\"]\n while len(layer) > 1:\n if len(layer) % 2: layer.append(layer[-1])\n layer = [hashlib.sha256(layer[i]+layer[i+1]).digest()\n for i in range(0,len(layer),2)]\n return layer[0]\n\ndef daily(bucket, prefix):\n s3 = boto3.client(\"s3\")\n leaves = [s3.get_object(Bucket=bucket, Key=o[\"Key\"])[\"Body\"].read()\n for o in s3.list_objects_v2(Bucket=bucket, Prefix=prefix).get(\"Contents\", [])]\n root = merkle(leaves).hex()\n manifest = {\"date\": time.strftime(\"%Y-%m-%d\"), \"merkleRoot\": root, \"leaves\": len(leaves)}\n s3.put_object(Bucket=bucket, Key=f\"{prefix}/_manifests/{manifest['date']}.json\",\n Body=json.dumps(manifest).encode(),\n ObjectLockMode=\"COMPLIANCE\",\n ObjectLockRetainUntilDate=\"2033-01-01T00:00:00Z\")\n return manifest\n", + "ciGithubWorkflow": "# .github/workflows/wfap-gemini.yml\nname: wfap-gemini-ci\non: [push, pull_request]\njobs:\n govern:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - run: opa fmt --diff policies/ && opa test policies/\n - run: conftest test --policy policies deploy/\n - run: pytest tests/redteam tests/art5 tests/injection -q\n - run: python tools/faithfulness_eval.py --threshold 0.92\n - run: python tools/bias_gate.py --air 0.8 --psi 0.1\n - run: |\n docker build -t wfap-gemini:${{ github.sha }} .\n cosign sign --yes wfap-gemini:${{ github.sha }}\n cosign attest --predicate evidence.json wfap-gemini:${{ github.sha }}\n - run: kubectl apply -f deploy/canary-5pct.yaml\n", + "adaptiveUxReact": "// React hook: useAdaptiveUx \u2014 skill-tier gating with ethics guardrails\nimport { useState, useEffect } from \"react\";\n\nexport function useAdaptiveUx(capability) {\n const [tier, setTier] = useState(\"practitioner\");\n const [transparency, setTransparency] = useState(true);\n\n useEffect(() => {\n fetch(`/api/skill/${capability}`).then(r => r.json()).then(s => {\n setTier(s.tier);\n });\n }, [capability]);\n\n const reasonCard = (\n <button onClick={() => alert(`UI tier '${tier}' chosen from your skill profile. You can reset under Settings \u2192 UX.`)}>\n Why am I seeing this?\n </button>\n );\n return { tier, transparency, reasonCard };\n}\n", + "kafkaWormProducer": "// signed-telemetry producer (Node)\nconst { Kafka } = require(\"kafkajs\");\nconst { sign } = require(\"./signer-ed25519\");\nconst k = new Kafka({ brokers: process.env.KAFKA_BROKERS.split(\",\") });\nconst p = k.producer({ idempotent: true });\nasync function send(topic, payload) {\n await p.connect();\n const env = { ...payload, ts: new Date().toISOString() };\n env.signature = sign(JSON.stringify(env));\n await p.send({ topic, messages: [{ key: env.callId || env.eventId, value: JSON.stringify(env) }] });\n}\nmodule.exports = { send };\n" + }, + "caseStudies": [ + { + "id": "CS-01", + "title": "Global bank \u2014 WorkflowAI Pro on regulated estate", + "sector": "Banking", + "summary": "Tier-1 bank deployed WorkflowAI Pro across 38k users with full SR 11-7 + EU AI Act alignment.", + "outcomes": { + "users": 38000, + "modelsRegistered": 412, + "promptTemplatesPublished": 1840, + "ragGroundedness": "0.94 avg", + "geminiBlockedHarmRate": "99.7%", + "ISO42001": "Certified" + } + }, + { + "id": "CS-02", + "title": "Pharma \u2014 RAG chat for SMEs and regulators", + "sector": "Life Sciences", + "summary": "RAG chat over GxP-controlled corpora with zero hallucination tolerance and audit trail.", + "outcomes": { + "corpora": 22, + "monthlyQueries": 1400000.0, + "hallucinationIncidents": 0, + "regulatoryEngagement": "FDA + EMA satisfied" + } + }, + { + "id": "CS-03", + "title": "Public sector \u2014 Sovereign-cloud variant", + "sector": "Government", + "summary": "G7 ministry deployed sovereign-cloud variant with in-region GeminiService and air-gapped admin.", + "outcomes": { + "dataResidency": "100%", + "treatyDisclosures": 4, + "redTeamPassRate": "99.3%" + } + }, + { + "id": "CS-04", + "title": "Insurer \u2014 Fairness-aware recommender", + "sector": "Insurance", + "summary": "Workflow recommender personalised to claims handlers with strict fairness floor (AIR \u2265 0.85).", + "outcomes": { + "AIRAfter": 0.88, + "handlerProductivity": "+19%", + "consumerComplaints": "-23%" + } + }, + { + "id": "CS-05", + "title": "Tech conglomerate \u2014 Collaborative prompt engineering at scale", + "sector": "Technology", + "summary": "300+ teams onboarded to collaborative prompt registry with PR-style review and CI evals.", + "outcomes": { + "templatesActive": 6200, + "averageReviewTime": "37 min", + "evalRegressionsBlocked": 184, + "adoption": "92% of eligible teams" + } + } + ], + "apiEndpoints": { + "prefix": "/api/wfap-gemini", + "routes": [ + "", + "/meta", + "/executive-summary", + "/summary", + "/architecture", + "/architecture/planes", + "/architecture/topology", + "/architecture/tenancy", + "/data-models", + "/data-models/:id", + "/data-flows", + "/data-flows/:id", + "/recommender", + "/recommender/active-learning", + "/recommender/apis", + "/adaptive-ux", + "/adaptive-ux/skill", + "/adaptive-ux/ethics", + "/rag", + "/rag/retrieval", + "/rag/faithfulness", + "/rag/governance", + "/rag/apis", + "/prompts", + "/prompts/lifecycle", + "/prompts/collab", + "/prompts/lineage", + "/prompts/apis", + "/registry", + "/registry/schema", + "/registry/rbac", + "/registry/tagging", + "/registry/apis", + "/safety-reports", + "/safety-reports/:id", + "/safety-reports/risks", + "/safety-reports/intl-collab", + "/gemini", + "/gemini/gateway", + "/gemini/pre-call", + "/gemini/post-call", + "/gemini/telemetry", + "/gemini/adversarial", + "/gemini/apis", + "/tasks-reports", + "/tasks-reports/tasks", + "/tasks-reports/reports", + "/tasks-reports/apis", + "/strategy", + "/strategy/phases", + "/strategy/boundaries", + "/strategy/integration", + "/strategy/kpis", + "/strategy/risks", + "/schemas", + "/schemas/:name", + "/code-examples", + "/code-examples/:name", + "/case-studies", + "/case-studies/:id", + "/modules", + "/modules/:id", + "/sections/:id", + "/m1", + "/m2", + "/m3", + "/m4", + "/m5", + "/m6", + "/m7", + "/m8", + "/m9", + "/m10", + "/m11", + "/m12" + ] + } +} diff --git a/rag-agentic-dashboard/gen-ent-agi-gov-master-html.py b/rag-agentic-dashboard/gen-ent-agi-gov-master-html.py new file mode 100644 index 0000000..4eb237d --- /dev/null +++ b/rag-agentic-dashboard/gen-ent-agi-gov-master-html.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python3 +""" +ENT-AGI-GOV-MASTER-WP-035 — HTML Dashboard Renderer +Generates: public/ent-agi-gov-master.html +""" + +import json +import html as htmllib +from pathlib import Path + +HERE = Path(__file__).parent +SRC = HERE / "data" / "ent-agi-gov-master.json" +OUT = HERE / "public" / "ent-agi-gov-master.html" + +MODULE_ORDER = [ + "M1_pillars", + "M2_regulatory", + "M3_architectures", + "M4_safety", + "M5_civilizational", + "M6_financialMrm", + "M7_kafkaGac", + "M8_roadmap", +] + + +def esc(v): + if v is None: + return "" + if isinstance(v, bool): + return "true" if v else "false" + return htmllib.escape(str(v)) + + +def kv_table(d): + rows = "".join( + f"<tr><td class='k'>{esc(k)}</td><td class='v'>{render_value(v)}</td></tr>" + for k, v in d.items() + ) + return f"<table class='kv'>{rows}</table>" + + +def render_value(v): + if isinstance(v, dict): + return kv_table(v) + if isinstance(v, list): + if not v: + return "<em>—</em>" + if all(isinstance(x, (str, int, float, bool)) for x in v): + return "<ul>" + "".join(f"<li>{esc(x)}</li>" for x in v) + "</ul>" + if all(isinstance(x, dict) for x in v): + keys = [] + for d in v: + for k in d.keys(): + if k not in keys: + keys.append(k) + head = "".join(f"<th>{esc(k)}</th>" for k in keys) + body = "" + for d in v: + body += "<tr>" + "".join( + f"<td>{render_value(d.get(k, ''))}</td>" for k in keys + ) + "</tr>" + return ( + f"<table class='grid'><thead><tr>{head}</tr></thead>" + f"<tbody>{body}</tbody></table>" + ) + return "<ul>" + "".join(f"<li>{render_value(x)}</li>" for x in v) + "</ul>" + return esc(v) + + +def render_section(sec): + sid = sec.get("id", "") + title = sec.get("title", "") + html = [f"<div class='section' id='{esc(sid)}'>"] + html.append(f"<h3>{esc(sid)} · {esc(title)}</h3>") + for key, val in sec.items(): + if key in ("id", "title"): + continue + html.append( + f"<div class='sub'><h4>{esc(key)}</h4>{render_value(val)}</div>" + ) + html.append("</div>") + return "\n".join(html) + + +def render_module(mod): + mid = mod.get("id", "") + title = mod.get("title", "") + summary = mod.get("summary", "") + sections = mod.get("sections", []) or [] + html = [f"<section class='module' id='{esc(mid)}'>"] + html.append(f"<h2>{esc(mid)} · {esc(title)}</h2>") + if summary: + html.append(f"<p class='summary'>{esc(summary)}</p>") + for sec in sections: + html.append(render_section(sec)) + html.append("</section>") + return "\n".join(html) + + +def main(): + data = json.loads(SRC.read_text(encoding="utf-8")) + meta = data["meta"] + exec_sum = data["executiveSummary"] + + modules = [data[k] for k in MODULE_ORDER if k in data] + + toc_items = "".join( + f"<li><a href='#{esc(m['id'])}'>{esc(m['id'])} · {esc(m['title'].split('—')[-1].strip()[:46])}</a></li>" + for m in modules + ) + toc_items += ( + "<li><a href='#schemas'>Schemas</a></li>" + "<li><a href='#code-examples'>Code Examples</a></li>" + "<li><a href='#case-studies'>Case Studies</a></li>" + "<li><a href='#regulatory-matrix'>Regulatory Alignment</a></li>" + "<li><a href='#api'>API Endpoints</a></li>" + ) + + modules_html = "\n".join(render_module(m) for m in modules) + + schemas_html = "" + for name, sch in data.get("schemas", {}).items(): + schemas_html += ( + f"<details><summary>{esc(name)}</summary>" + f"<pre><code>{esc(json.dumps(sch, indent=2))}</code></pre></details>" + ) + + code_html = "" + for name, code in data.get("codeExamples", {}).items(): + code_html += ( + f"<details><summary>{esc(name)}</summary>" + f"<pre><code>{esc(code)}</code></pre></details>" + ) + + cs_html = "" + for cs in data.get("caseStudies", []): + outcomes = cs.get("outcomes", {}) + outcomes_html = ( + kv_table(outcomes) if isinstance(outcomes, dict) + else render_value(outcomes) + ) + cs_html += ( + f"<div class='case'><h3>{esc(cs.get('id',''))} · {esc(cs.get('title',''))}</h3>" + f"<p><strong>Sector:</strong> {esc(cs.get('sector',''))}</p>" + f"<p>{esc(cs.get('summary',''))}</p>" + f"<div class='sub'><h4>Outcomes</h4>{outcomes_html}</div>" + "</div>" + ) + + reg = meta.get("regulatoryAlignment", []) + if isinstance(reg, list): + reg_html = "<ul>" + "".join(f"<li>{esc(r)}</li>" for r in reg) + "</ul>" + else: + reg_html = esc(reg) + + audience = meta.get("audience", []) + audience_html = ( + "<ul>" + "".join(f"<li>{esc(a)}</li>" for a in audience) + "</ul>" + if isinstance(audience, list) else esc(audience) + ) + + horizon = meta.get("horizonMilestones", {}) + horizon_html = kv_table(horizon) if isinstance(horizon, dict) else esc(horizon) + + inv = meta.get("deliverableInventory", {}) + inv_html = kv_table(inv) if isinstance(inv, dict) else esc(inv) + + api = data.get("apiEndpoints", {"prefix": "/api/ent-agi-gov-master", "routes": []}) + api_items = "".join( + f"<li><code>{esc(api['prefix'])}{esc(r)}</code></li>" + for r in api.get("routes", []) + ) + + n_modules = len(modules) + total_sections = sum(len(m.get("sections", []) or []) for m in modules) + n_schemas = len(data.get("schemas", {})) + n_code = len(data.get("codeExamples", {})) + n_cs = len(data.get("caseStudies", [])) + n_routes = len(api.get("routes", [])) + + page = f"""<!doctype html> +<html lang="en"> +<head> +<meta charset="utf-8" /> +<meta name="viewport" content="width=device-width,initial-scale=1" /> +<title>{esc(meta.get('docRef',''))} — {esc(meta.get('title',''))} + + + + +
+
{esc(meta.get('docRef',''))} · {esc(meta.get('classification',''))}
+

{esc(meta.get('title',''))}

+

{esc(meta.get('subtitle',''))}

+
+ Version {esc(meta.get('version',''))} + Date {esc(meta.get('date',''))} + Horizon {esc(meta.get('horizon',''))} + EU AI Act + SR 11-7 Tier 1 + NIST AI RMF 1.0 + ISO/IEC 42001 + Basel III/IV · ICAAP + FCRA / ECOA +
+
+
{n_modules}
Modules
+
{total_sections}
Sections
+
7
Pillars (G1-G7)
+
16
Regulatory Axes
+
9
Reference Architectures
+
8
Safety Protocols
+
{n_schemas}
Schemas
+
{n_code}
Code Examples
+
{n_cs}
Case Studies
+
{n_routes}
API Routes
+
+
+ +
+
+

Executive Summary

+ {kv_table(exec_sum)} +
+ +
+

Document Metadata

+ {kv_table({k: v for k, v in meta.items() + if k not in ('audience', 'regulatoryAlignment', + 'horizonMilestones', 'deliverableInventory')})} +
+

Audience

+ {audience_html} +
+
+

Horizon Milestones (2026-2030)

+ {horizon_html} +
+
+

Deliverable Inventory

+ {inv_html} +
+
+ + {modules_html} + +
+

Regulatory Alignment (Headline)

+

Master crosswalk lives in M2 — Regulatory Alignment Matrix; the headline list of 16 axes:

+ {reg_html} +
+ +
+

JSON Schemas

+

{n_schemas} schemas covering governance artefacts, compute registry, model risk records, fairness reports, policy decisions, treaty disclosures.

+ {schemas_html} +
+ +
+

Code Examples

+

{n_code} reference implementations: OPA/Rego policies, Terraform GaC modules, Merkle WORM audit, CI/CD pipeline, governance sidecar, fairness gate, kinetic kill-switch, regulator report templates.

+ {code_html} +
+ +
+

Case Studies

+

{n_cs} reference deployments across G-SIFI, Fortune 500, Global 2000, asset management, frontier AI lab, and sovereign-cloud government tiers.

+ {cs_html} +
+ +
+

API Endpoints

+

Prefix: {esc(api.get('prefix',''))} · Total planned: {n_routes}

+ +
+
+ + + +""" + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(page, encoding="utf-8") + size_kb = OUT.stat().st_size // 1024 + print(f"Wrote {OUT} ({size_kb} KB)") + print( + f"Modules: {n_modules} | Sections: {total_sections} | " + f"Schemas: {n_schemas} | Code: {n_code} | Cases: {n_cs} | " + f"Routes: {n_routes}" + ) + + +if __name__ == "__main__": + main() diff --git a/rag-agentic-dashboard/gen-ent-agi-gov-master.py b/rag-agentic-dashboard/gen-ent-agi-gov-master.py new file mode 100644 index 0000000..132da7d --- /dev/null +++ b/rag-agentic-dashboard/gen-ent-agi-gov-master.py @@ -0,0 +1,1251 @@ +#!/usr/bin/env python3 +""" +ENT-AGI-GOV-MASTER-WP-035 — Enterprise AGI/ASI Governance Master Framework +Generates: data/ent-agi-gov-master.json + +Institutional-grade, regulator-ready AGI/ASI and enterprise AI governance +frameworks and architectures for Fortune 500, Global 2000, and G-SIFIs +covering 2026-2030. + +Scope: + - Multilayered AI governance pillars (G1-G7) + - Regulatory alignment matrix (EU AI Act, NIST AI RMF 1.0, ISO/IEC 42001, + OECD, GDPR, FCRA/ECOA, Basel III, SR 11-7, PRA, FCA, MAS, HKMA) + - Enterprise reference architectures (Sentinel v2.4, WorkflowAI Pro, EAIP, + high-assurance RAG, governed agentic workflows, Kafka WORM, OPA-as-code) + - AGI/ASI safety & containment (Luminous Engine Codex, Cognitive Resonance + Protocol, Sentinel / Omni-Sentinel, MV-AGI governance stack, crisis + simulations, frontier risk taxonomies) + - Civilizational-scale governance & compute oversight (ICGC, global compute + registry, treaty-aligned systemic risk governance) + - Financial services MRM (credit / trading / risk / fiduciary AI advisors) + - Kafka ACL governance, Terraform GaC, WORM evidence storage, OPA/Rego, + CI/CD integration, auditor workflows + - Implementation roadmap, executive/regulator-ready reports +""" + +import json +from pathlib import Path +from datetime import date + +HERE = Path(__file__).parent +OUT = HERE / "data" / "ent-agi-gov-master.json" + + +def meta(): + return { + "docRef": "ENT-AGI-GOV-MASTER-WP-035", + "version": "1.0.0", + "date": "2026-04-25", + "title": "Enterprise AGI/ASI Governance Master Framework (2026-2030)", + "subtitle": ( + "Institutional-grade, regulator-ready AGI/ASI and enterprise AI " + "governance frameworks, reference architectures, safety and " + "containment protocols, financial-services model risk " + "management, civilizational-scale compute oversight, and " + "implementation roadmaps for Fortune 500, Global 2000, and " + "G-SIFIs." + ), + "classification": ( + "CONFIDENTIAL — Board / C-Suite / Prudential Supervisor / " + "Treaty Authority / Internal & External Audit" + ), + "owner": "Group Chief AI Officer (CAIO) — co-signed by CRO, CISO, GC, COO", + "audience": [ + "Board of Directors / Risk & Audit Committees", + "C-Suite (CEO, CFO, CRO, CISO, CAIO, CTO, GC, COO)", + "Group Heads of Model Risk, Enterprise Risk, Compliance", + "Prudential & conduct supervisors (PRA, FCA, OCC, Fed, ECB, " + "MAS, HKMA, BaFin, FINMA)", + "Data protection authorities (ICO, CNIL, EDPB), CFPB", + "EU AI Act notified bodies, ISO/IEC 42001 certifiers", + "Internal & external auditors, treaty-authority observers", + "Enterprise architects, AI platform engineers, researchers", + ], + "horizon": "2026-2030 (with 2030-2050 frontier outlook)", + "regulatoryAlignment": [ + "EU AI Act (Regulation (EU) 2024/1689) — Annex III, Annex IV, " + "Art. 9/10/12/13/14/15, Art. 53/55 GPAI", + "NIST AI Risk Management Framework 1.0 + GenAI Profile (AI 600-1)", + "ISO/IEC 42001:2023 — AI Management System", + "ISO/IEC 23894:2023 — AI Risk Management", + "ISO/IEC 5338:2023 — AI System Lifecycle", + "ISO/IEC 27001:2022 / 27701:2019 / 27018", + "OECD AI Principles (2019, updated 2024)", + "GDPR (Regulation (EU) 2016/679); UK GDPR; CCPA/CPRA", + "US FCRA / ECOA / Reg B / CFPB UDAAP", + "Basel III/IV (CRR3/CRD6); ICAAP Pillar 2; BCBS 239", + "SR 11-7 / OCC 2011-12 / PRA SS1/23 — Model Risk Management", + "PRA SS2/21 (Outsourcing); FCA Consumer Duty; FCA AI Update 2024", + "MAS FEAT principles + Veritas toolkit; HKMA HLP on Big Data & AI", + "EO 14110, OMB M-24-10, US AI Bill of Rights blueprint", + "Council of Europe AI Convention 2024", + ], + "horizonMilestones": { + "2026Q2": "EU AI Act Art. 6 high-risk obligations enforcement", + "2026Q3": "MV-AGI governance stack mandatory for systemic banks", + "2027Q1": "ICGC compute-registry global rollout (>1e25 FLOP)", + "2027Q4": "ISO/IEC 42001 certification expected of all G-SIFIs", + "2028Q2": "Kinetic-tripwire & PQC ledger integration baseline", + "2029Q1": "Treaty-authority cross-border AI college operational", + "2030Q1": "Frontier compute governance treaty (GAGCOT) in force", + }, + "deliverableInventory": { + "pillars": 7, + "regulatoryAxes": 16, + "referenceArchitectures": 9, + "safetyContainmentProtocols": 8, + "civilizationalArtefacts": 6, + "financialServicesMRM": 6, + "kafkaGaCArtefacts": 7, + "schemas": 6, + "codeExamples": 10, + "caseStudies": 6, + "apiEndpointsPlanned": 95, + }, + } + + +def executive_summary(): + return { + "purpose": ( + "To provide a single, regulator-ready, board-approvable master " + "framework that unifies enterprise AI, agentic-AI, AGI/ASI " + "containment, and civilizational compute oversight into one " + "audit-traceable governance system aligned with all major " + "global regulatory regimes." + ), + "scope": ( + "Spans all AI systems across the enterprise — from high-risk " + "credit/trading models to autonomous agents and frontier " + "general-purpose AI — with extensions to inter-firm and treaty-" + "level oversight." + ), + "designPrinciples": [ + "Defense-in-depth across 7 governance pillars (G1-G7)", + "Compliance-as-code: every policy is enforceable in CI/CD and runtime", + "Evidence-as-data: WORM-backed Merkle-anchored, PQC-signed audit", + "Human-on-the-loop with kinetic tripwires for irreversibility", + "Bias-aware fairness across protected classes (FCRA/ECOA, GDPR Art. 22)", + "Formal alignment metrics with PID-based drift control", + "Treaty-ready: artefacts portable to ICGC and supervisory colleges", + ], + "keyOutcomes": { + "timeToGovernedDeployment": "≤ 72 hours (production AI)", + "evidenceAutomation": "≥ 92% of controls auto-evidenced", + "MTTD": "≤ 4 minutes (alignment-drift / containment breach)", + "MTTR": "≤ 60 minutes (containment), ≤ 60 seconds (kinetic kill)", + "controlsMapped": "240+ controls across 16 regulatory axes", + "evidenceRetention": "7-year WORM (SR 11-7 / SEC 17a-4(f))", + "boardReportingCadence": "Quarterly with monthly KRI exception packs", + }, + "boardNarrative": ( + "This master framework converts AI governance from a fragmented " + "control set into an integrated risk-bearing capital function. " + "Capital, conduct, and existential-safety risks are jointly " + "modelled, enabling the Board to approve AI strategy with the " + "same rigour applied to credit, market, and operational risk." + ), + } + + +def m1_pillars(): + return { + "id": "M1", + "title": "M1 — Multilayered AI Governance Pillars (G1-G7)", + "summary": ( + "Seven pillars define the institutional governance topology, " + "from board accountability down to autonomous-agent guardrails." + ), + "sections": [ + { + "id": "M1-S1", + "title": "Pillar Catalogue", + "pillars": [ + { + "id": "G1", + "name": "Board & Strategic Oversight", + "owner": "Board Risk & Audit Committees", + "objective": "Risk appetite, strategic AI bets, capital allocation", + "controls": ["AI risk appetite statement", "Annual AI strategy approval", "AGI-readiness review"], + }, + { + "id": "G2", + "name": "Executive Accountability", + "owner": "CAIO (chair), CRO, CISO, GC, COO", + "objective": "Single accountable executive with veto + kill-switch authority", + "controls": ["RACI matrix", "AI Governance Council charter", "SMCR/SMR mapping"], + }, + { + "id": "G3", + "name": "Model Risk Management (MRM)", + "owner": "Group Head of Model Risk (2nd LoD)", + "objective": "Independent validation, ongoing monitoring, MV report", + "controls": ["SR 11-7 Tier classification", "Independent IMV", "Materiality tiering"], + }, + { + "id": "G4", + "name": "Data, Privacy & Fairness", + "owner": "DPO + Chief Data Officer", + "objective": "Lawful basis, minimisation, fairness across protected classes", + "controls": ["DPIA", "FCRA/ECOA disparate impact testing", "Lineage attestation"], + }, + { + "id": "G5", + "name": "Security & Containment", + "owner": "CISO + Head of AI Security", + "objective": "Zero-trust runtime, kill-switch, kinetic tripwires", + "controls": ["MITRE ATLAS coverage", "OWASP LLM Top 10", "PQC-signed telemetry"], + }, + { + "id": "G6", + "name": "Compliance & Conduct", + "owner": "Group Compliance + Conduct Risk", + "objective": "Regulatory mapping, conduct outcomes, customer fairness", + "controls": ["Consumer Duty outcome testing", "OPA-as-code policy gates", "Incident notifications"], + }, + { + "id": "G7", + "name": "Frontier / Civilizational Risk", + "owner": "CAIO + Treaty Liaison Officer", + "objective": "GPAI Art. 53/55, ICGC reporting, AGI containment readiness", + "controls": ["Compute register", "Frontier-risk simulations", "Treaty disclosure pack"], + }, + ], + }, + { + "id": "M1-S2", + "title": "Three-Lines-of-Defence (3LoD) Mapping", + "lines": [ + {"line": "1LoD", "owners": "Business / AI Engineering", "responsibilities": ["Develop", "Operate", "First-level controls"]}, + {"line": "2LoD", "owners": "MRM, Compliance, AI Risk", "responsibilities": ["Independent validation", "Policy", "Challenge"]}, + {"line": "3LoD", "owners": "Internal Audit", "responsibilities": ["Assurance over 1+2", "Annual AI audit plan"]}, + ], + }, + { + "id": "M1-S3", + "title": "Risk Taxonomy", + "categories": [ + "R1 Performance / accuracy drift", + "R2 Fairness / disparate impact", + "R3 Privacy / PII leakage", + "R4 Robustness / adversarial", + "R5 Security / containment escape", + "R6 Explainability / interpretability gap", + "R7 Concentration / third-party dependency", + "R8 Conduct / consumer harm", + "R9 Systemic / market dislocation", + "R10 Frontier / catastrophic / existential", + ], + }, + ], + } + + +def m2_regulatory_matrix(): + rows = [ + {"axis": "EU AI Act", "scope": "High-risk + GPAI", "keyArticles": "Arts 6,9,10,12,13,14,15,53,55; Annex III/IV", "primaryControl": "Annex IV technical documentation", "evidenceArtefact": "Annex IV dossier + GPAI summary"}, + {"axis": "NIST AI RMF 1.0", "scope": "All AI", "keyArticles": "Govern/Map/Measure/Manage + GenAI Profile", "primaryControl": "GMM control mapping", "evidenceArtefact": "RMF playbook crosswalk"}, + {"axis": "ISO/IEC 42001", "scope": "AIMS", "keyArticles": "Clauses 4-10; Annex A controls", "primaryControl": "AI Management System certification", "evidenceArtefact": "AIMS evidence pack"}, + {"axis": "ISO/IEC 23894", "scope": "AI risk", "keyArticles": "Risk management lifecycle", "primaryControl": "Integrated AI risk register", "evidenceArtefact": "Risk register + treatment plan"}, + {"axis": "OECD AI Principles", "scope": "All AI", "keyArticles": "5 values-based principles + 5 govt recommendations", "primaryControl": "Trustworthy AI attestation", "evidenceArtefact": "Principle conformance memo"}, + {"axis": "GDPR / UK GDPR", "scope": "Personal data", "keyArticles": "Art. 5,6,9,22,25,32,35", "primaryControl": "DPIA + Art. 22 ADM safeguards", "evidenceArtefact": "DPIA + LIA + transparency notice"}, + {"axis": "FCRA", "scope": "US consumer credit", "keyArticles": "§604, §615 adverse action", "primaryControl": "Adverse action reasons (top-N)", "evidenceArtefact": "Reason-code generator log"}, + {"axis": "ECOA / Reg B", "scope": "US credit fairness", "keyArticles": "§1002.4, §1002.6", "primaryControl": "Less-discriminatory alternative search", "evidenceArtefact": "LDA search log"}, + {"axis": "Basel III/IV", "scope": "Bank capital", "keyArticles": "CRR3/CRD6; Pillars 1-3; ICAAP", "primaryControl": "Pillar-2 AI capital add-on", "evidenceArtefact": "ICAAP AI annex"}, + {"axis": "SR 11-7 / OCC 2011-12", "scope": "Model risk", "keyArticles": "Sound model development, validation, governance", "primaryControl": "Independent validation + ongoing monitoring", "evidenceArtefact": "IMV report + MV dashboard"}, + {"axis": "PRA SS1/23", "scope": "UK MRM", "keyArticles": "Tiering, accountability, validation", "primaryControl": "SS1/23 self-assessment", "evidenceArtefact": "Annual MRM attestation"}, + {"axis": "FCA Consumer Duty", "scope": "UK conduct", "keyArticles": "PRIN 12; outcomes 1-4", "primaryControl": "Outcome testing on AI decisions", "evidenceArtefact": "CD outcome pack"}, + {"axis": "MAS FEAT", "scope": "Singapore FS", "keyArticles": "Fairness, Ethics, Accountability, Transparency", "primaryControl": "Veritas-aligned FEAT testing", "evidenceArtefact": "FEAT assessment report"}, + {"axis": "HKMA HLP", "scope": "HK FS", "keyArticles": "High-Level Principles on AI", "primaryControl": "Board-approved AI policy", "evidenceArtefact": "HKMA policy attestation"}, + {"axis": "EO 14110 / OMB M-24-10", "scope": "US federal-adjacent", "keyArticles": "Safety/security reporting + rights/safety-impacting AI", "primaryControl": "Safety reporting threshold (1e26 FLOP)", "evidenceArtefact": "Compute disclosure"}, + {"axis": "Council of Europe AI Convention", "scope": "Cross-jurisdiction", "keyArticles": "Human rights, democracy, rule of law", "primaryControl": "Human-rights impact assessment", "evidenceArtefact": "HRIA report"}, + ] + return { + "id": "M2", + "title": "M2 — Regulatory Alignment Matrix (16 Axes)", + "summary": "Cross-walk of every governance control to its regulatory anchor.", + "sections": [ + {"id": "M2-S1", "title": "Crosswalk Matrix", "rows": rows}, + { + "id": "M2-S2", + "title": "Regulator Engagement Cadence", + "schedule": [ + {"regulator": "PRA / FCA", "cadence": "Quarterly MRM update + ad-hoc Sec 166", "format": "Liaison memo + IMV pack"}, + {"regulator": "OCC / Fed", "cadence": "Continuous supervisory dialogue", "format": "MV dashboard read-only access"}, + {"regulator": "ECB SSM", "cadence": "Annual ICAAP + thematic review", "format": "ICAAP AI annex"}, + {"regulator": "MAS / HKMA", "cadence": "Annual self-assessment", "format": "FEAT / HLP attestation"}, + {"regulator": "EU AI Act notified body", "cadence": "Pre-deployment + substantial mod", "format": "Annex IV dossier"}, + {"regulator": "DPA (ICO/CNIL/EDPB)", "cadence": "Per DPIA + 72h breach", "format": "DPIA + Art. 33/34 notice"}, + {"regulator": "CFPB", "cadence": "Adverse-action audits", "format": "Reason-code sample + LDA log"}, + {"regulator": "Treaty Authority (ICGC)", "cadence": "Annual + frontier event", "format": "Compute register + frontier disclosure"}, + ], + }, + ], + } + + +def m3_reference_architectures(): + archs = [ + { + "id": "RA-01", + "name": "Sentinel AI Governance Platform v2.4", + "purpose": "Unified runtime containment, telemetry, kill-switch, kinetic tripwire", + "keyComponents": ["Containment proxy", "Guard model", "WORM Kafka", "PQC ledger", "Kinetic layer"], + "regulatoryAnchors": ["EU AI Act Art. 53/55", "SR 11-7", "ISO/IEC 42001"], + "interopRefs": ["WP-034 Sentinel", "EAIP", "WorkflowAI Pro"], + }, + { + "id": "RA-02", + "name": "WorkflowAI Pro (WP-033)", + "purpose": "Governed agentic workflow + prompt lifecycle platform", + "keyComponents": ["Prompt template registry", "DAG orchestrator", "Sentinel compliance engine", "Active-learning loop"], + "regulatoryAnchors": ["NIST AI RMF", "ISO/IEC 42001", "SOC 2 Type II"], + "interopRefs": ["WP-033"], + }, + { + "id": "RA-03", + "name": "Enterprise AI Interoperability Profile (EAIP)", + "purpose": "Cross-vendor governance interchange — policy, evidence, telemetry envelopes", + "keyComponents": ["Telemetry envelope schema", "Evidence manifest", "Policy decision exchange"], + "regulatoryAnchors": ["ISO/IEC 42001 Annex A", "EU AI Act Art. 12 (logging)"], + "interopRefs": ["TPX/EVB/RMX"], + }, + { + "id": "RA-04", + "name": "High-Assurance RAG Platform", + "purpose": "Retrieval-augmented generation with governance-grade citation, lineage, and PII redaction", + "keyComponents": ["Vector store with lineage", "Citation engine", "PII redactor", "Faithfulness scorer"], + "regulatoryAnchors": ["GDPR Art. 5(1)(d)", "EU AI Act Art. 13", "ISO/IEC 42001"], + "interopRefs": ["EAIP TPX"], + }, + { + "id": "RA-05", + "name": "Governed Agentic Workflows", + "purpose": "Multi-agent orchestration with constitutional guardrails and canary deploys", + "keyComponents": ["Agent registry", "Capability graph", "Constitutional checker", "Canary gateway"], + "regulatoryAnchors": ["EU AI Act Art. 14 (HITL)", "MITRE ATLAS"], + "interopRefs": ["Sentinel M5/M6"], + }, + { + "id": "RA-06", + "name": "Kafka WORM Audit Logging Cluster", + "purpose": "Immutable, PQC-signed, hash-chained AI telemetry for 7-year SEC retention", + "keyComponents": ["mTLS Kafka", "ACL governance", "S3 Object Lock", "Daily Merkle audit"], + "regulatoryAnchors": ["SEC 17a-4(f)", "SR 11-7", "EU AI Act Art. 12"], + "interopRefs": ["Sentinel M9"], + }, + { + "id": "RA-07", + "name": "Docker Swarm + Kubernetes Hardened Runtime", + "purpose": "Workload isolation, mTLS service mesh, signed images, runtime attestation", + "keyComponents": ["SLSA L3 build chain", "Cosign signatures", "Falco runtime IDS", "OPA gatekeeper"], + "regulatoryAnchors": ["NIST SSDF", "ISO/IEC 27001", "FedRAMP Moderate"], + "interopRefs": ["Sentinel M4"], + }, + { + "id": "RA-08", + "name": "Node.js / Python Governance Sidecars", + "purpose": "Per-process governance: telemetry, PII redaction, OPA decision cache", + "keyComponents": ["Sidecar SDK (Node/Py)", "OPA decision client", "Envelope signer", "Audit shipper"], + "regulatoryAnchors": ["ISO/IEC 42001 A.6.2", "EU AI Act Art. 12"], + "interopRefs": ["EAIP TPX/RMX"], + }, + { + "id": "RA-09", + "name": "Next.js Explainability Frontend", + "purpose": "Customer-facing & supervisor-facing explanations + adverse-action UI", + "keyComponents": ["SHAP/IG renderer", "Reason-code UI", "DPIA viewer", "Consent surfacer"], + "regulatoryAnchors": ["FCRA §615", "GDPR Art. 22", "EU AI Act Art. 13"], + "interopRefs": ["RA-04 RAG", "RA-01 Sentinel"], + }, + ] + return { + "id": "M3", + "title": "M3 — Enterprise Reference Architectures", + "summary": "Nine production-grade architectures composing the enterprise AI estate.", + "sections": [ + {"id": "M3-S1", "title": "Architecture Catalogue", "architectures": archs}, + { + "id": "M3-S2", + "title": "OPA Compliance-as-Code Patterns", + "patterns": [ + {"id": "POL-01", "name": "deploy_gate.rego", "enforcement": "CI/CD admission", "blocks": "Unsigned models, missing IMV, expired DPIA"}, + {"id": "POL-02", "name": "data_residency.rego", "enforcement": "Runtime", "blocks": "Cross-border PII without SCC/IDTA"}, + {"id": "POL-03", "name": "high_risk_label.rego", "enforcement": "Registry", "blocks": "EU AI Act high-risk without Annex IV dossier"}, + {"id": "POL-04", "name": "agent_capability.rego", "enforcement": "Runtime", "blocks": "Tool calls outside allowlisted capability graph"}, + {"id": "POL-05", "name": "fairness_threshold.rego", "enforcement": "Pre-deploy", "blocks": "AIR <0.8 / SPD >0.05 without exception"}, + {"id": "POL-06", "name": "compute_register.rego", "enforcement": "Pre-train", "blocks": "Training >1e25 FLOP without ICGC entry"}, + ], + }, + { + "id": "M3-S3", + "title": "Governance Standards for Hyperparameter Control", + "controls": [ + "Hyperparameter changes are version-controlled (Git, signed commits)", + "Material hyperparameter changes (Δlearning-rate >50%, depth ±2 layers, regulariser swap) trigger IMV re-validation", + "Random-seed pinning + deterministic CUDA flags for reproducibility (within hardware tolerance)", + "Hyperparameter sweep results retained in WORM with cost & energy attribution", + "Production hyperparameters require 2-of-3 approval (1LoD model owner, 2LoD validator, change advisory board)", + "Rollback hyperparameter set always pinned and tested in canary lane", + ], + }, + ], + } + + +def m4_safety_containment(): + return { + "id": "M4", + "title": "M4 — AGI/ASI Safety & Containment Frameworks", + "summary": "Eight protocols spanning institutional safety, frontier alignment, and civilizational hedges.", + "sections": [ + { + "id": "M4-S1", + "title": "Protocol Catalogue", + "protocols": [ + { + "id": "SC-01", + "name": "Luminous Engine Codex", + "purpose": "Codex of inviolable constitutional principles for frontier systems", + "keyArtefacts": ["Codex YAML", "Signature ledger", "Veto hash chain"], + "scope": "Frontier / GPAI", + }, + { + "id": "SC-02", + "name": "Cognitive Resonance Protocol (CRP)", + "purpose": "Continuous alignment-resonance scoring with PID drift control", + "keyArtefacts": ["Resonance scorer", "PID controller", "Tripwire policy"], + "scope": "Frontier + agentic", + }, + { + "id": "SC-03", + "name": "Sentinel Containment v2.4", + "purpose": "Runtime zero-trust + kinetic tripwire (operational)", + "keyArtefacts": ["Containment proxy", "Guard model", "Kinetic layer"], + "scope": "Enterprise + GPAI", + }, + { + "id": "SC-04", + "name": "Omni-Sentinel Multi-Modal Filter", + "purpose": "Vision/audio/code multi-modal containment with adversarial robustness", + "keyArtefacts": ["VisionContainmentFilter", "Audio steganalysis", "Code-execution sandbox"], + "scope": "Multi-modal frontier", + }, + { + "id": "SC-05", + "name": "MV-AGI Governance Stack (Minimum-Viable)", + "purpose": "Smallest auditable AGI governance layer required pre-deployment", + "keyArtefacts": ["Compute register entry", "Capability eval pack", "RSP / RSDP", "Kill-switch test", "Treaty disclosure"], + "scope": "Any system >1e25 FLOP or with autonomy ≥L3", + }, + { + "id": "SC-06", + "name": "Crisis Simulation Programme (GC1-GC7)", + "purpose": "Tabletop + live-fire crisis exercises across institution / treaty axes", + "keyArtefacts": ["Scenario library", "Replay kits", "After-action reports"], + "scope": "Cross-domain", + }, + { + "id": "SC-07", + "name": "Frontier Risk Taxonomy (FRT)", + "purpose": "Catalogue of catastrophic & existential failure modes with leading indicators", + "keyArtefacts": ["Risk register", "Indicator dashboard", "Capability eval suite"], + "scope": "Frontier-only", + }, + { + "id": "SC-08", + "name": "Responsible Scaling Policy (RSP/RSDP)", + "purpose": "Capability-conditional commitments triggering pause / red-team / disclosure", + "keyArtefacts": ["Capability tier matrix", "Pause clauses", "Disclosure template"], + "scope": "Frontier developers + deployers", + }, + ], + }, + { + "id": "M4-S2", + "title": "Crisis Scenarios (GC1-GC7)", + "scenarios": [ + {"id": "GC1", "name": "Cross-border capability shock", "trigger": "Frontier model exceeds eval threshold mid-deploy", "responseSLA": "≤ 4h treaty notification"}, + {"id": "GC2", "name": "Systemic fairness divergence", "trigger": "AIR drift >0.15 across G-SIFI cohort", "responseSLA": "≤ 24h supervisor college"}, + {"id": "GC3", "name": "Compute-supply disruption", "trigger": "GPU export-control / kinetic event", "responseSLA": "≤ 72h capacity reallocation"}, + {"id": "GC4", "name": "Adversarial data poisoning", "trigger": "Detection of poisoned training corpus", "responseSLA": "≤ 12h IR + roll-back"}, + {"id": "GC5", "name": "Autonomous-agent containment failure", "trigger": "Capability escape detected", "responseSLA": "≤ 60s kinetic kill"}, + {"id": "GC6", "name": "Model-weight compromise", "trigger": "Exfiltration / leak of frontier weights", "responseSLA": "≤ 4h treaty disclosure"}, + {"id": "GC7", "name": "Governance dissolution threat", "trigger": "Coordinated regulatory bypass / capture", "responseSLA": "≤ 24h Board + GC + treaty escalation"}, + ], + }, + { + "id": "M4-S3", + "title": "Capability Evaluation Tiers", + "tiers": [ + {"tier": "T0", "label": "Narrow", "controls": ["Standard MRM", "SR 11-7 Tier 2"]}, + {"tier": "T1", "label": "Broad enterprise AI", "controls": ["Annex IV dossier", "ISO 42001"]}, + {"tier": "T2", "label": "Agentic / autonomous L2-L3", "controls": ["Constitutional checks", "Canary"]}, + {"tier": "T3", "label": "Frontier GPAI", "controls": ["Art. 53/55", "RSP", "Compute register"]}, + {"tier": "T4", "label": "Pre-AGI / dual-use uplift", "controls": ["Treaty disclosure", "Kinetic tripwire", "Pause clauses"]}, + {"tier": "T5", "label": "AGI-class", "controls": ["MV-AGI stack", "Omni-Sentinel", "Multi-jurisdiction approval"]}, + ], + }, + ], + } + + +def m5_civilizational(): + return { + "id": "M5", + "title": "M5 — Civilizational-Scale Governance & Compute Oversight", + "summary": "Six artefacts extending governance from firm to inter-state and treaty layer.", + "sections": [ + { + "id": "M5-S1", + "title": "International Compute Governance Consortium (ICGC)", + "design": { + "purpose": "Multilateral body coordinating compute thresholds, frontier capability disclosures, and incident response", + "members": "G7 + G20 + observer states + 5 lead AI labs + civil society", + "secretariat": "Rotating; OECD-hosted (proposed)", + "powers": ["Compute registry", "Capability eval review", "Crisis coordination", "Sanctions recommendations"], + "alignment": ["EU AI Act Art. 53/55", "EO 14110 §4.2", "Bletchley/Seoul/Paris commitments"], + }, + }, + { + "id": "M5-S2", + "title": "Global Compute Registry", + "schemaSummary": [ + "operatorId (LEI)", "facilityId (geo-coordinates)", "designFLOPs", + "currentUtilisationFLOPs", "modelsTrained[]", "inferenceWorkloads[]", + "powerSourceMix", "embodiedCO2", "attestationSignature (PQC)", + ], + "thresholds": { + "training": "≥ 1e25 FLOP single training run", + "cluster": "≥ 1e21 FLOP/s sustained capacity", + "inference": "≥ 1e23 FLOP/day on single deployed model", + }, + "reportingCadence": "Monthly + event-driven", + }, + { + "id": "M5-S3", + "title": "Treaty-Aligned Systemic Risk Governance", + "instruments": [ + "GAGCOT (Global AI Governance & Compute Oversight Treaty) — proposed", + "Council of Europe AI Convention 2024 — in force", + "Bletchley/Seoul/Paris Declarations — political commitments", + "OECD AI Policy Observatory — monitoring", + ], + "supervisoryColleges": [ + {"id": "SC-MRM-COLL", "members": "PRA + FCA + OCC + Fed + ECB", "scope": "G-SIFI MRM"}, + {"id": "SC-AI-COLL", "members": "Notified bodies + DPAs + CFPB + treaty observers", "scope": "Frontier deployments"}, + ], + }, + { + "id": "M5-S4", + "title": "Frontier Risk Outlook 2030-2050", + "horizons": [ + {"period": "2026-2028", "focus": "GPAI Art. 53/55 enforcement, ICGC bootstrap"}, + {"period": "2028-2032", "focus": "Pre-AGI capability evals, treaty enforcement, kinetic standards"}, + {"period": "2032-2040", "focus": "AGI-class oversight, distributed sovereignty controls"}, + {"period": "2040-2050", "focus": "Civilizational continuity protocols, multi-civilizational stewardship"}, + ], + }, + { + "id": "M5-S5", + "title": "Sovereign AI & Strategic Autonomy", + "considerations": [ + "Sovereign cloud / sovereign foundation model commitments", + "Cross-border data flows: EU-US DPF, UK Bridge, ASEAN Model Contractual Clauses", + "Export controls: ECCN 4E091, EAR 744.23, Wassenaar updates", + "Strategic autonomy investments and dual-use risk reviews", + ], + }, + { + "id": "M5-S6", + "title": "Civilizational Continuity Protocol", + "elements": [ + "Geographically dispersed kill-switch custody (m-of-n threshold)", + "Diverse foundation-model portfolio (anti-monoculture)", + "Air-gapped golden-image archives of critical AI assets", + "Treaty-mandated annual civilizational tabletop (GC7 class)", + ], + }, + ], + } + + +def m6_financial_mrm(): + return { + "id": "M6", + "title": "M6 — Financial Services Model Risk Management", + "summary": "Domain-specific governance for credit, trading, risk, and fiduciary AI advisors.", + "sections": [ + { + "id": "M6-S1", + "title": "Domain Catalogue", + "domains": [ + { + "id": "FS-01", + "domain": "Retail Credit Scoring", + "anchors": ["FCRA §615", "ECOA / Reg B", "GDPR Art. 22", "EU AI Act high-risk Annex III §5(b)"], + "controls": ["Adverse-action top-N reasons", "LDA search", "Disparate-impact testing", "DPIA + LIA"], + "kpi": "AIR ≥ 0.8; SPD ≤ 0.05; backtest PSI ≤ 0.1", + }, + { + "id": "FS-02", + "domain": "Wholesale / Corporate Credit", + "anchors": ["Basel III/IV IRB", "PRA SS1/23", "SR 11-7 Tier 1"], + "controls": ["IRB model approval", "Pillar-2 capital add-on", "Conservatism margin"], + "kpi": "PD/LGD/EAD backtest within tolerance; ICAAP coverage", + }, + { + "id": "FS-03", + "domain": "Algorithmic Trading & Market-Making", + "anchors": ["MiFID II / MiFIR Art. 17", "SEC 15c3-5", "FCA MAR"], + "controls": ["Pre-trade risk checks", "Kill-switch", "Algo testing & certification"], + "kpi": "Latency budget; max-loss / day; cancel-fill ratio drift", + }, + { + "id": "FS-04", + "domain": "Market & Liquidity Risk Models", + "anchors": ["FRTB", "BCBS 239", "SR 11-7"], + "controls": ["VaR backtesting", "Capital floor", "Stress-test integration"], + "kpi": "Backtest exceptions ≤ 4/year (P&L attrib)", + }, + { + "id": "FS-05", + "domain": "Operational & Conduct Risk Detection", + "anchors": ["Basel III OpRisk", "FCA Consumer Duty", "AML 6 / FinCEN"], + "controls": ["Alert tuning governance", "False-positive ceiling", "Explainable case file"], + "kpi": "TPR ≥ x; FPR ≤ y; SAR conversion" + }, + { + "id": "FS-06", + "domain": "Fiduciary AI Advisors / Robo-Advice", + "anchors": ["FCA COBS / SEC IA Act", "MiFID II suitability", "MAS FEAT"], + "controls": ["Suitability test", "Conflict-of-interest disclosure", "Best-interest attestation"], + "kpi": "Suitability-deviation ≤ x bps; complaint rate" + }, + ], + }, + { + "id": "M6-S2", + "title": "Capital Impact (ICAAP Pillar 2 AI Add-on)", + "method": "Add-on calibrated to model-risk loss distribution + scenario severity", + "components": [ + "Performance drift (PSI > 0.2) capital", + "Fairness remediation provisioning", + "Containment-failure operational risk capital", + "Frontier-risk Pillar-2 buffer (qualitative)", + ], + "boardReporting": "Quarterly; with ICAAP Pillar-2 sub-letter to PRA / ECB", + }, + { + "id": "M6-S3", + "title": "Validation Pack Standard", + "elements": [ + "Model card (Hugging Face style + MRM appendix)", + "Data card with lineage and bias profile", + "Performance & stability backtests", + "Fairness across protected classes", + "Robustness (adversarial + distributional)", + "Explainability (SHAP / IG / counterfactuals)", + "Independent challenger benchmark", + "Sign-off: 1LoD / 2LoD / 3LoD", + ], + }, + ], + } + + +def m7_kafka_gac(): + return { + "id": "M7", + "title": "M7 — Kafka ACL Governance & Continuous Compliance Engine", + "summary": "Terraform-based governance-as-code with WORM evidence, OPA gates, and auditor workflows.", + "sections": [ + { + "id": "M7-S1", + "title": "Kafka ACL Governance Pattern", + "components": [ + "Per-topic ACLs in Terraform (terraform-confluent-provider)", + "Topic-tier classification (public / internal / confidential / restricted)", + "mTLS + SPIFFE/SPIRE workload identity", + "Continuous ACL drift detection (cron job → OPA → ticket)", + "Quarterly ACL recertification by data owner", + ], + }, + { + "id": "M7-S2", + "title": "WORM Evidence Storage", + "design": [ + "S3 Object Lock (compliance mode) — 7-year retention (SR 11-7 / SEC 17a-4(f))", + "Daily Merkle-root anchored to public timestamping (RFC 3161 + blockchain anchor)", + "Cross-region replication (eu-west-1 / us-east-1 / ap-southeast-1)", + "PQC (Dilithium3) signature on each manifest", + ], + }, + { + "id": "M7-S3", + "title": "Continuous Compliance Engine", + "modules": [ + {"name": "Evidence collector", "freq": "5 min", "outputs": "Raw evidence to Kafka topic"}, + {"name": "Control mapper", "freq": "Hourly", "outputs": "Maps evidence to control IDs (240+ controls)"}, + {"name": "Coverage scorer", "freq": "Hourly", "outputs": "% controls evidenced; gap list"}, + {"name": "Auditor view", "freq": "On-demand", "outputs": "Read-only Next.js dashboard with evidence proofs"}, + {"name": "Regulator pack generator", "freq": "Quarterly + ad-hoc", "outputs": "PDF/A-3 with embedded evidence + signature"}, + ], + }, + { + "id": "M7-S4", + "title": "Terraform Governance-as-Code", + "modules": [ + "tf-aws-s3-worm — Object Lock + replication", + "tf-aws-kms-cmk-rotated — annual rotation, key policy with break-glass", + "tf-aws-iam-zerotrust — SCP-enforced least privilege", + "tf-aws-eks-hardened — pod-security-standards restricted, OPA gatekeeper", + "tf-confluent-acls — per-topic ACL bundles", + "tf-opa-bundle — versioned policy bundles (CI signed)", + ], + }, + { + "id": "M7-S5", + "title": "CI/CD Integration (GitHub Actions)", + "stages": [ + "Lint (rego, tflint, eslint, ruff)", + "Unit tests + property tests (Hypothesis / fast-check)", + "Container build + SLSA provenance + Cosign sign", + "OPA conftest gates (POL-01..POL-06)", + "Adversarial / jailbreak test suite", + "Mechanistic interpretability audit (cosine tripwires)", + "Cryptographic attestation (Sigstore + Rekor)", + "Canary deploy (5% → 25% → 100%) with auto-rollback", + ], + }, + { + "id": "M7-S6", + "title": "Auditor Workflow", + "steps": [ + "Read-only auditor account via SSO + SCIM", + "Evidence query UI: control → evidence → proof chain", + "Sample selection with deterministic seed (auditable)", + "Export to PDF/A-3 with embedded JSON-LD evidence", + "Findings logged to WORM Kafka topic for traceability", + ], + }, + { + "id": "M7-S7", + "title": "Regulator-Ready Reports & Whitepapers", + "templates": [ + "Annex IV dossier (EU AI Act)", + "ICAAP Pillar-2 AI annex", + "ISO/IEC 42001 AIMS evidence pack", + "SR 11-7 Independent Validation Report", + "DPIA + Art. 22 notice", + "Adverse-action reason-code package (FCRA)", + "FEAT (MAS) self-assessment", + "Treaty disclosure pack (ICGC / GAGCOT)", + ], + }, + ], + } + + +def m8_implementation_roadmap(): + return { + "id": "M8", + "title": "M8 — Implementation Roadmap & Reports", + "summary": "Phased adoption across Fortune 500 / Global 2000 / G-SIFIs with executive- and regulator-ready outputs.", + "sections": [ + { + "id": "M8-S1", + "title": "Five-Phase Adoption Plan (52 weeks)", + "phases": [ + {"phase": "P1 Foundations", "weeks": "1-8", "deliverables": ["AI Governance Council", "Risk appetite", "Inventory", "DPIA register"]}, + {"phase": "P2 Controls Build", "weeks": "9-20", "deliverables": ["OPA bundles", "Sentinel runtime", "Kafka WORM", "MRM tooling"]}, + {"phase": "P3 Integration", "weeks": "21-32", "deliverables": ["EAIP wiring", "Sidecars", "Continuous compliance engine"]}, + {"phase": "P4 Assurance", "weeks": "33-44", "deliverables": ["ISO 42001 cert", "Annex IV pilots", "ICAAP AI annex"]}, + {"phase": "P5 Frontier Readiness", "weeks": "45-52", "deliverables": ["MV-AGI stack", "Crisis sims GC1-GC7", "Treaty disclosure"]}, + ], + }, + { + "id": "M8-S2", + "title": "KPIs / OKRs", + "kpis": [ + {"id": "KPI-01", "name": "Time to governed deployment", "target": "≤ 72 h"}, + {"id": "KPI-02", "name": "Evidence automation", "target": "≥ 92%"}, + {"id": "KPI-03", "name": "Containment MTTD", "target": "≤ 4 min"}, + {"id": "KPI-04", "name": "Containment MTTR", "target": "≤ 60 min"}, + {"id": "KPI-05", "name": "Kinetic kill-switch latency", "target": "≤ 60 s"}, + {"id": "KPI-06", "name": "Fairness AIR floor", "target": "≥ 0.8"}, + {"id": "KPI-07", "name": "Backtest PSI ceiling", "target": "≤ 0.1 (warn) / ≤ 0.2 (fail)"}, + {"id": "KPI-08", "name": "Control coverage", "target": "≥ 240 controls / 16 axes"}, + {"id": "KPI-09", "name": "Audit finding closure", "target": "≤ 90 days (high)"}, + {"id": "KPI-10", "name": "Frontier disclosure SLA", "target": "≤ 4 h to ICGC"}, + ], + }, + { + "id": "M8-S3", + "title": "Executive & Regulator Reports (Markdown templates with /<abstract>/<content>)", + "reports": [ + {"id": "RPT-01", "audience": "Board", "title": "AI Risk Appetite & Strategy 2026-2030"}, + {"id": "RPT-02", "audience": "C-Suite", "title": "AI Governance Operating Model"}, + {"id": "RPT-03", "audience": "PRA / FCA", "title": "SS1/23 MRM Self-Assessment"}, + {"id": "RPT-04", "audience": "ECB SSM", "title": "ICAAP Pillar-2 AI Annex"}, + {"id": "RPT-05", "audience": "EU notified body", "title": "Annex IV Technical Documentation"}, + {"id": "RPT-06", "audience": "ISO 42001 certifier", "title": "AIMS Evidence Pack"}, + {"id": "RPT-07", "audience": "CFPB", "title": "Adverse-Action & LDA Compliance Package"}, + {"id": "RPT-08", "audience": "Treaty (ICGC)", "title": "Frontier Compute & Capability Disclosure"}, + {"id": "RPT-09", "audience": "Board (Crisis)", "title": "GC1-GC7 Tabletop After-Action Report"}, + {"id": "RPT-10", "audience": "Researchers", "title": "Whitepaper: Master Framework Architecture"}, + ], + }, + ], + } + + +def schemas(): + return { + "governanceArtefactEnvelope": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/governance-artefact.json", + "type": "object", + "required": ["artefactId", "type", "owner", "issuedAt", "evidenceRefs", "signature"], + "properties": { + "artefactId": {"type": "string", "pattern": "^EAGV-[A-Z0-9-]+$"}, + "type": {"enum": ["dossier", "imv-report", "dpia", "policy", "evidence-bundle", "manifest"]}, + "owner": {"type": "string"}, + "issuedAt": {"type": "string", "format": "date-time"}, + "evidenceRefs": {"type": "array", "items": {"type": "string"}}, + "signature": {"type": "object", "required": ["alg", "value", "keyId"]}, + }, + }, + "computeRegistryEntry": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/compute-registry.json", + "type": "object", + "required": ["operatorId", "facilityId", "designFLOPs", "attestationSignature"], + "properties": { + "operatorId": {"type": "string"}, + "facilityId": {"type": "string"}, + "designFLOPs": {"type": "number"}, + "currentUtilisationFLOPs": {"type": "number"}, + "modelsTrained": {"type": "array"}, + "attestationSignature": {"type": "object"}, + }, + }, + "modelRiskRecord": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/model-risk-record.json", + "type": "object", + "required": ["modelId", "tier", "owner", "imvStatus", "kris"], + "properties": { + "modelId": {"type": "string"}, + "tier": {"enum": ["T0", "T1", "T2", "T3", "T4", "T5"]}, + "owner": {"type": "string"}, + "imvStatus": {"enum": ["pending", "passed", "conditional", "failed"]}, + "kris": {"type": "object"}, + }, + }, + "fairnessReport": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/fairness-report.json", + "type": "object", + "required": ["modelId", "metrics", "protectedAttributes", "decision"], + "properties": { + "modelId": {"type": "string"}, + "metrics": {"type": "object", "properties": {"AIR": {"type": "number"}, "SPD": {"type": "number"}, "EOD": {"type": "number"}}}, + "protectedAttributes": {"type": "array", "items": {"type": "string"}}, + "decision": {"enum": ["pass", "remediate", "block"]}, + }, + }, + "policyDecision": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/policy-decision.json", + "type": "object", + "required": ["policyId", "input", "decision", "trace"], + "properties": { + "policyId": {"type": "string"}, + "input": {"type": "object"}, + "decision": {"enum": ["allow", "deny", "warn"]}, + "trace": {"type": "array"}, + }, + }, + "treatyDisclosure": { + "$id": "https://workflowai.pro/schemas/ent-agi-gov/treaty-disclosure.json", + "type": "object", + "required": ["operatorId", "modelId", "capabilityTier", "computeFLOPs", "issuedAt"], + "properties": { + "operatorId": {"type": "string"}, + "modelId": {"type": "string"}, + "capabilityTier": {"enum": ["T2", "T3", "T4", "T5"]}, + "computeFLOPs": {"type": "number"}, + "issuedAt": {"type": "string", "format": "date-time"}, + "evalSummary": {"type": "object"}, + }, + }, + } + + +def code_examples(): + return { + "regoDeployGate": '''package eagv.deploy + +# POL-01 deploy_gate.rego +default allow = false + +allow { + input.model.signature.verified + input.model.imv.status == "passed" + not expired_dpia + not high_risk_without_dossier +} + +expired_dpia { + time.parse_rfc3339_ns(input.model.dpia.expiresAt) < time.now_ns() +} + +high_risk_without_dossier { + input.model.tier == "T1" + input.model.regulatoryFlags[_] == "EU_AI_ACT_HIGH_RISK" + not input.model.annexIvDossier +} +''', + "regoComputeRegister": '''package eagv.compute + +# POL-06 compute_register.rego +default allow = false + +allow { + input.training.flops < 1e25 +} + +allow { + input.training.flops >= 1e25 + input.icgc.registryEntryId + input.icgc.attestationSignature.verified +} +''', + "terraformS3Worm": '''# tf-aws-s3-worm +resource "aws_s3_bucket" "worm" { + bucket = "eagv-worm-${var.env}" + object_lock_enabled = true +} + +resource "aws_s3_bucket_object_lock_configuration" "worm" { + bucket = aws_s3_bucket.worm.id + rule { + default_retention { + mode = "COMPLIANCE" + years = 7 + } + } +} + +resource "aws_s3_bucket_replication_configuration" "worm" { + role = aws_iam_role.repl.arn + bucket = aws_s3_bucket.worm.id + rule { + id = "cross-region" + status = "Enabled" + destination { bucket = var.replica_bucket_arn } + } +} +''', + "terraformKafkaAcls": '''# tf-confluent-acls — per-topic ACL bundle +resource "confluent_kafka_acl" "telemetry_writer" { + kafka_cluster { id = var.cluster_id } + resource_type = "TOPIC" + resource_name = "ai.telemetry.v1" + pattern_type = "LITERAL" + principal = "User:sa-sentinel-emitter" + host = "*" + operation = "WRITE" + permission = "ALLOW" +} + +resource "confluent_kafka_acl" "telemetry_audit_reader" { + kafka_cluster { id = var.cluster_id } + resource_type = "TOPIC" + resource_name = "ai.telemetry.v1" + pattern_type = "LITERAL" + principal = "User:sa-auditor" + host = "*" + operation = "READ" + permission = "ALLOW" +} +''', + "merkleAuditPython": '''#!/usr/bin/env python3 +"""Daily Merkle-root WORM audit (EAGV).""" +import hashlib, json, time, boto3 +from cryptography.hazmat.primitives.asymmetric import ed25519 + +def merkle(leaves): + if not leaves: return b"" + layer = [hashlib.sha256(l).digest() for l in leaves] + while len(layer) > 1: + if len(layer) % 2: layer.append(layer[-1]) + layer = [hashlib.sha256(layer[i]+layer[i+1]).digest() + for i in range(0,len(layer),2)] + return layer[0] + +def daily_audit(bucket, prefix, signing_key): + s3 = boto3.client("s3") + leaves = [] + for o in s3.list_objects_v2(Bucket=bucket, Prefix=prefix).get("Contents", []): + body = s3.get_object(Bucket=bucket, Key=o["Key"])["Body"].read() + leaves.append(body) + root = merkle(leaves) + sig = signing_key.sign(root) + manifest = {"date": time.strftime("%Y-%m-%d"), + "merkleRoot": root.hex(), + "signature": sig.hex(), + "leafCount": len(leaves)} + s3.put_object(Bucket=bucket, Key=f"{prefix}/_manifests/{manifest['date']}.json", + Body=json.dumps(manifest).encode(), + ObjectLockMode="COMPLIANCE", + ObjectLockRetainUntilDate=time.strftime("%Y-%m-%dT%H:%M:%SZ")) + return manifest +''', + "ciGithubActions": '''# .github/workflows/eagv-pipeline.yml +name: eagv-pipeline +on: [push, pull_request] +jobs: + govern: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Lint rego + run: opa fmt --diff policies/ && opa test policies/ + - name: Conftest gates + run: conftest test --policy policies deploy/ + - name: Adversarial suite + run: pytest tests/adversarial -q + - name: Mechanistic audit + run: python tools/circuit_scanner.py --threshold 0.92 + - name: Build + SLSA + Cosign + run: | + docker build -t app:${{ github.sha }} . + cosign sign --yes app:${{ github.sha }} + - name: Sigstore attest + run: cosign attest --predicate evidence.json app:${{ github.sha }} + - name: Canary deploy + run: kubectl apply -f deploy/canary-5pct.yaml +''', + "nodeSidecar": '''// node-governance-sidecar +const express = require("express"); +const { sign } = require("./pqc"); +const opa = require("./opa-client"); +const app = express(); +app.use(express.json()); + +app.post("/intercept", async (req, res) => { + const decision = await opa.eval("eagv.runtime.allow", req.body); + if (!decision.allow) return res.status(403).json({ error: decision.reason }); + const envelope = { + ts: new Date().toISOString(), + modelId: req.body.modelId, + inputHash: req.body.inputHash, + decision, + }; + envelope.signature = sign(JSON.stringify(envelope)); + // emit to Kafka topic ai.telemetry.v1 + res.json({ ok: true, envelope }); +}); + +app.listen(7081); +''', + "fairnessTestPy": '''#!/usr/bin/env python3 +"""FCRA/ECOA fairness pre-deploy gate.""" +import numpy as np, pandas as pd + +def air(y_pred, group): + rates = pd.Series(y_pred).groupby(group).mean() + return rates.min() / rates.max() + +def spd(y_pred, group, ref): + rates = pd.Series(y_pred).groupby(group).mean() + return rates - rates.loc[ref] + +def gate(df, pred_col="approved", group_col="protected_class", ref="group_a"): + a = air(df[pred_col], df[group_col]) + s = spd(df[pred_col], df[group_col], ref).abs().max() + if a < 0.8 or s > 0.05: + raise SystemExit(f"FAIL: AIR={a:.3f} SPD={s:.3f}") + print(f"PASS: AIR={a:.3f} SPD={s:.3f}") +''', + "kineticKillSwitch": '''// kinetic-kill-switch (m-of-n threshold) +const { thresholdSign, verifyThreshold } = require("./threshold-crypto"); + +async function executeKill(operatorId, reasonCode, signatures) { + if (!verifyThreshold(signatures, /*m=*/3, /*n=*/5)) { + throw new Error("threshold not met"); + } + await scada.cutPower(operatorId); // <60s SLA + await net.disconnectVlan(operatorId); + await audit.emit({ operatorId, reasonCode, signatures, ts: Date.now() }); +} +''', + "regulatorReportTemplate": '''<!-- Markdown report template --> +<title>Annex IV Technical Documentation — Model {{modelId}} + +Regulator-ready dossier covering EU AI Act Art. 11 + Annex IV for the +high-risk AI system {{modelId}} operated by {{operator}}. + + + +## 1. General description +- Intended purpose: {{purpose}} +- Provider / deployer: {{provider}} / {{deployer}} +- Versions covered: {{versions}} + +## 2. Detailed description +- Architecture, training data, validation methodology +- Logging (Art. 12) and human oversight (Art. 14) + +## 3. Risk management (Art. 9) +- Hazard identification, evaluation, mitigations + +## 4. Performance & monitoring (Art. 15 / 17) +- Accuracy, robustness, cyber-security + +## 5. Conformity assessment & post-market monitoring + +''', + } + + +def case_studies(): + return [ + { + "id": "CS-01", + "title": "G-SIFI bank — full-stack adoption", + "sector": "Banking", + "summary": "Top-10 G-SIFI rolled out the master framework across 1,200 AI use-cases.", + "outcomes": { + "controlsMapped": 247, + "evidenceAutomation": "94%", + "ICAAPPillar2AddOn": "GBP 380m", + "ISO42001Certification": "Achieved Q4 2027", + "AnnexIVDossiers": 38, + "FrontierDisclosures": 6, + }, + }, + { + "id": "CS-02", + "title": "Fortune 500 insurer — fairness remediation", + "sector": "Insurance", + "summary": "Pricing AI remediated using LDA search; AIR moved 0.71 → 0.86.", + "outcomes": { + "AIRBefore": 0.71, + "AIRAfter": 0.86, + "complaintReduction": "-42%", + "regulatorEngagement": "FCA + state DOI satisfied", + }, + }, + { + "id": "CS-03", + "title": "Global asset manager — fiduciary AI advisor", + "sector": "Asset Management", + "summary": "Robo-advice platform certified under MAS FEAT + ISO 42001.", + "outcomes": { + "FEATAttestation": "Issued", + "suitabilityDeviation": "-31 bps", + "complaintRate": "0.03%", + }, + }, + { + "id": "CS-04", + "title": "Frontier AI lab — MV-AGI stack", + "sector": "AI Research", + "summary": "Frontier lab adopted MV-AGI stack ahead of Art. 53/55 enforcement.", + "outcomes": { + "computeRegistryEntries": 12, + "capabilityEvalsPassed": 5, + "treatyDisclosures": 3, + "kineticTripwireDrills": 4, + }, + }, + { + "id": "CS-05", + "title": "Global 2000 retailer — agentic workflows", + "sector": "Retail", + "summary": "Deployed governed agentic workflows for supply-chain optimisation with 0 containment incidents.", + "outcomes": { + "agents": 2400, + "containmentIncidents": 0, + "MTTD": "3.1 min", + "MTTR": "47 min", + }, + }, + { + "id": "CS-06", + "title": "Sovereign-cloud government deployment", + "sector": "Public Sector", + "summary": "G7 government deployed sovereign-AI stack with treaty-aligned governance.", + "outcomes": { + "sovereignFoundationModels": 3, + "treatyDisclosures": 2, + "civilizationalDrillScore": "A-", + }, + }, + ] + + +def api_endpoints(): + routes = [ + "", "/meta", "/executive-summary", "/summary", + "/pillars", "/pillars/:id", + "/regulatory", "/regulatory/:axis", + "/architectures", "/architectures/:id", + "/safety", "/safety/:id", + "/civilizational", "/civilizational/:id", + "/financial-mrm", "/financial-mrm/:id", + "/kafka-gac", "/kafka-gac/:id", + "/roadmap", "/roadmap/phases", "/roadmap/kpis", + "/reports", "/reports/:id", + "/scenarios", "/scenarios/:id", + "/schemas", "/schemas/:name", + "/code-examples", "/code-examples/:name", + "/case-studies", "/case-studies/:id", + "/modules", "/modules/:id", "/sections/:id", + ] + # Per-module roots M1..M8 + for i in range(1, 9): + routes.append(f"/m{i}") + # Per-pillar shortcuts + for g in range(1, 8): + routes.append(f"/pillars/G{g}") + # Per-scenario shortcuts + for g in range(1, 8): + routes.append(f"/scenarios/GC{g}") + return {"prefix": "/api/ent-agi-gov-master", "routes": routes} + + +def main(): + data = { + "meta": meta(), + "executiveSummary": executive_summary(), + "M1_pillars": m1_pillars(), + "M2_regulatory": m2_regulatory_matrix(), + "M3_architectures": m3_reference_architectures(), + "M4_safety": m4_safety_containment(), + "M5_civilizational": m5_civilizational(), + "M6_financialMrm": m6_financial_mrm(), + "M7_kafkaGac": m7_kafka_gac(), + "M8_roadmap": m8_implementation_roadmap(), + "schemas": schemas(), + "codeExamples": code_examples(), + "caseStudies": case_studies(), + "apiEndpoints": api_endpoints(), + } + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(json.dumps(data, indent=2), encoding="utf-8") + size_kb = OUT.stat().st_size // 1024 + print(f"Wrote {OUT} ({size_kb} KB)") + n_modules = sum(1 for k in data if k.startswith("M") and "_" in k) + n_sections = sum( + len(data[k].get("sections", [])) + for k in data if k.startswith("M") and "_" in k + ) + print( + f"Modules: {n_modules} | Sections: {n_sections} | " + f"Schemas: {len(data['schemas'])} | Code: {len(data['codeExamples'])} | " + f"Cases: {len(data['caseStudies'])} | Routes: {len(data['apiEndpoints']['routes'])}" + ) + + +if __name__ == "__main__": + main() diff --git a/rag-agentic-dashboard/gen-wfap-gemini-impl-html.py b/rag-agentic-dashboard/gen-wfap-gemini-impl-html.py new file mode 100644 index 0000000..bc40ab6 --- /dev/null +++ b/rag-agentic-dashboard/gen-wfap-gemini-impl-html.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +""" +WFAP-GEMINI-IMPL-WP-036 — HTML Dashboard Renderer +Generates: public/wfap-gemini-impl.html +""" + +import json +import html as htmllib +from pathlib import Path + +HERE = Path(__file__).parent +SRC = HERE / "data" / "wfap-gemini-impl.json" +OUT = HERE / "public" / "wfap-gemini-impl.html" + +MODULE_ORDER = [ + "M1_architecture", + "M2_dataModels", + "M3_dataFlows", + "M4_recommender", + "M5_adaptiveUx", + "M6_ragChat", + "M7_promptCollab", + "M8_modelRegistry", + "M9_safetyReporting", + "M10_geminiSecurity", + "M11_taskReport", + "M12_implementation", +] + + +def esc(v): + if v is None: + return "" + if isinstance(v, bool): + return "true" if v else "false" + return htmllib.escape(str(v)) + + +def kv_table(d): + rows = "".join( + f"{esc(k)}{render_value(v)}" + for k, v in d.items() + ) + return f"{rows}
" + + +def render_value(v): + if isinstance(v, dict): + return kv_table(v) + if isinstance(v, list): + if not v: + return "" + if all(isinstance(x, (str, int, float, bool)) for x in v): + return "" + if all(isinstance(x, dict) for x in v): + keys = [] + for d in v: + for k in d.keys(): + if k not in keys: + keys.append(k) + head = "".join(f"{esc(k)}" for k in keys) + body = "" + for d in v: + body += "" + "".join( + f"{render_value(d.get(k, ''))}" for k in keys + ) + "" + return ( + f"{head}" + f"{body}
" + ) + return "" + return esc(v) + + +def render_section(sec): + sid = sec.get("id", "") + title = sec.get("title", "") + html = [f"
"] + html.append(f"

{esc(sid)} · {esc(title)}

") + for key, val in sec.items(): + if key in ("id", "title"): + continue + html.append( + f"

{esc(key)}

{render_value(val)}
" + ) + html.append("
") + return "\n".join(html) + + +def render_module(mod): + mid = mod.get("id", "") + title = mod.get("title", "") + summary = mod.get("summary", "") + sections = mod.get("sections", []) or [] + html = [f"
"] + html.append(f"

{esc(mid)} · {esc(title)}

") + if summary: + html.append(f"

{esc(summary)}

") + for sec in sections: + html.append(render_section(sec)) + html.append("
") + return "\n".join(html) + + +def main(): + data = json.loads(SRC.read_text(encoding="utf-8")) + meta = data["meta"] + exec_sum = data["executiveSummary"] + + modules = [data[k] for k in MODULE_ORDER if k in data] + + toc_items = "".join( + f"
  • {esc(m['id'])} · {esc(m['title'].split('—')[-1].strip()[:46])}
  • " + for m in modules + ) + toc_items += ( + "
  • Schemas
  • " + "
  • Code Examples
  • " + "
  • Case Studies
  • " + "
  • Regulatory Alignment
  • " + "
  • API Endpoints
  • " + ) + + modules_html = "\n".join(render_module(m) for m in modules) + + schemas_html = "" + for name, sch in data.get("schemas", {}).items(): + schemas_html += ( + f"
    {esc(name)}" + f"
    {esc(json.dumps(sch, indent=2))}
    " + ) + + code_html = "" + for name, code in data.get("codeExamples", {}).items(): + code_html += ( + f"
    {esc(name)}" + f"
    {esc(code)}
    " + ) + + cs_html = "" + for cs in data.get("caseStudies", []): + outcomes = cs.get("outcomes", {}) + outcomes_html = ( + kv_table(outcomes) if isinstance(outcomes, dict) + else render_value(outcomes) + ) + cs_html += ( + f"

    {esc(cs.get('id',''))} · {esc(cs.get('title',''))}

    " + f"

    Sector: {esc(cs.get('sector',''))}

    " + f"

    {esc(cs.get('summary',''))}

    " + f"

    Outcomes

    {outcomes_html}
    " + "
    " + ) + + reg = meta.get("regulatoryAlignment", []) + reg_html = ( + "" + if isinstance(reg, list) else esc(reg) + ) + + audience = meta.get("audience", []) + audience_html = ( + "" + if isinstance(audience, list) else esc(audience) + ) + + subject = meta.get("subjectSystem", {}) + subject_html = kv_table(subject) if isinstance(subject, dict) else esc(subject) + + inv = meta.get("deliverableInventory", {}) + inv_html = kv_table(inv) if isinstance(inv, dict) else esc(inv) + + api = data.get("apiEndpoints", {"prefix": "/api/wfap-gemini", "routes": []}) + api_items = "".join( + f"
  • {esc(api['prefix'])}{esc(r)}
  • " + for r in api.get("routes", []) + ) + + n_modules = len(modules) + total_sections = sum(len(m.get("sections", []) or []) for m in modules) + n_schemas = len(data.get("schemas", {})) + n_code = len(data.get("codeExamples", {})) + n_cs = len(data.get("caseStudies", [])) + n_routes = len(api.get("routes", [])) + + page = f""" + + + + +{esc(meta.get('docRef',''))} — {esc(meta.get('title',''))} + + + + +
    +
    {esc(meta.get('docRef',''))} · {esc(meta.get('classification',''))}
    +

    {esc(meta.get('title',''))}

    +

    {esc(meta.get('subtitle',''))}

    +
    + Version {esc(meta.get('version',''))} + Date {esc(meta.get('date',''))} + Horizon {esc(meta.get('horizon',''))} + EU AI Act Art. 5 + GDPR / UK GDPR + NIST AI RMF 1.0 + ISO/IEC 42001 + SOC 2 Type II + OWASP LLM Top 10 +
    +
    +
    {n_modules}
    Modules
    +
    {total_sections}
    Sections
    +
    7
    Architecture Planes
    +
    9
    Data Models
    +
    8
    Data Flows
    +
    {n_schemas}
    Schemas
    +
    {n_code}
    Code Examples
    +
    {n_cs}
    Case Studies
    +
    {n_routes}
    API Routes
    +
    +
    + +
    +
    +

    Executive Summary

    + {kv_table(exec_sum)} +
    + +
    +

    Document Metadata

    + {kv_table({k: v for k, v in meta.items() + if k not in ('audience', 'regulatoryAlignment', + 'subjectSystem', 'deliverableInventory')})} +
    +

    Audience

    + {audience_html} +
    +
    +

    Subject System

    + {subject_html} +
    +
    +

    Deliverable Inventory

    + {inv_html} +
    +
    + + {modules_html} + +
    +

    Regulatory Alignment

    + {reg_html} +
    + +
    +

    JSON Schemas

    +

    {n_schemas} schemas covering prompt templates, model registrations, RAG / Gemini envelopes, feedback events, recommendations, evidence, and incidents.

    + {schemas_html} +
    + +
    +

    Code Examples

    +

    {n_code} reference implementations: GeminiService gateway, RAG chat, model registry, prompt CRDT collab, active learning, OPA gate, Art. 5 classifier, PII redactor, Merkle audit, CI/CD, adaptive UX hook, signed Kafka producer.

    + {code_html} +
    + +
    +

    Case Studies

    +

    {n_cs} reference deployments across banking, life sciences, public sector, insurance, and technology.

    + {cs_html} +
    + +
    +

    API Endpoints

    +

    Prefix: {esc(api.get('prefix',''))} · Total planned: {n_routes}

    + +
    +
    + + + +""" + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(page, encoding="utf-8") + size_kb = OUT.stat().st_size // 1024 + print(f"Wrote {OUT} ({size_kb} KB)") + print(f"Modules: {n_modules} | Sections: {total_sections} | " + f"Schemas: {n_schemas} | Code: {n_code} | Cases: {n_cs} | Routes: {n_routes}") + + +if __name__ == "__main__": + main() diff --git a/rag-agentic-dashboard/gen-wfap-gemini-impl.py b/rag-agentic-dashboard/gen-wfap-gemini-impl.py new file mode 100644 index 0000000..0aca235 --- /dev/null +++ b/rag-agentic-dashboard/gen-wfap-gemini-impl.py @@ -0,0 +1,1312 @@ +#!/usr/bin/env python3 +""" +WFAP-GEMINI-IMPL-WP-036 — WorkflowAI Pro / GeminiService Implementation Plan +Generates: data/wfap-gemini-impl.json + +Comprehensive implementation plan, technical architecture, data models, data +flows, governance frameworks, and best-practice design guidelines for an +enterprise WorkflowAI Pro / GeminiService platform. + +Capabilities covered: + - AI-driven workflow recommendation with active learning + - Adaptive content and UI by user context and skill + - RAG-based grounded chat with citations and faithfulness scoring + - Collaborative prompt engineering (templates, variables, lineage) + - Enterprise model registry governance with RBAC, compliance metadata, + rollback, tagging + - AI safety and global governance reporting (existential risk, misuse, + bias, threat assessment, alignment failure, international collaboration) + - High-assurance RAG governance (lineage, citation, PII redaction) + - GeminiService security & privacy: telemetry integrity, GDPR PII + redaction, EU AI Act Art. 5 prohibited-practices checks, adversarial + prompt defenses + - Task / report management features + - Step-by-step implementation strategy, module boundaries, APIs, + integration patterns +""" + +import json +from pathlib import Path + +HERE = Path(__file__).parent +OUT = HERE / "data" / "wfap-gemini-impl.json" + + +def meta(): + return { + "docRef": "WFAP-GEMINI-IMPL-WP-036", + "version": "1.0.0", + "date": "2026-04-26", + "title": "WorkflowAI Pro / GeminiService — Enterprise Implementation Plan", + "subtitle": ( + "Comprehensive implementation plan, technical architecture, data " + "models, data flows, governance frameworks, and best-practice " + "design guidelines for an enterprise AI-driven workflow " + "recommendation, RAG chat, collaborative prompt engineering, " + "enterprise model registry, AI safety reporting, and " + "GeminiService security platform." + ), + "classification": ( + "CONFIDENTIAL — Board / Enterprise Architects / AI Platform " + "Engineers / Internal Audit / DPO" + ), + "owner": "Group CTO + Chief AI Officer (CAIO) — co-signed by CISO, DPO, GC", + "audience": [ + "Board of Directors / Risk & Audit Committees", + "C-Suite (CEO, CFO, CRO, CISO, CAIO, CTO, COO)", + "Enterprise architects", + "AI platform engineers / SREs", + "Data scientists / prompt engineers", + "Researchers (AI safety, governance)", + "Regulators & supervisors (PRA, FCA, OCC, MAS, ICO)", + ], + "horizon": "2026-2030", + "regulatoryAlignment": [ + "EU AI Act (Regulation (EU) 2024/1689) — Articles 5, 9, 10, 12, 13, 14, 15, 53, 55", + "NIST AI RMF 1.0 + GenAI Profile (AI 600-1)", + "ISO/IEC 42001:2023 — AI Management System", + "ISO/IEC 23894:2023 — AI risk management", + "ISO/IEC 27001:2022 / 27701:2019 / 27018", + "GDPR / UK GDPR (Articles 5, 6, 22, 25, 32, 33, 34, 35)", + "OECD AI Principles", + "OWASP Top 10 for LLM Applications (2025)", + "MITRE ATLAS / STRIDE / LINDDUN", + "SR 11-7 / OCC 2011-12 — Model Risk Management", + "SOC 2 Type II / FedRAMP Moderate", + ], + "deliverableInventory": { + "modules": 12, + "architectureLayers": 7, + "dataFlows": 8, + "dataModels": 9, + "apis": 110, + "integrationPatterns": 8, + "schemas": 8, + "codeExamples": 12, + "caseStudies": 5, + "phases": 6, + "kpis": 15, + }, + "subjectSystem": { + "platform": "WorkflowAI Pro", + "geminiService": "GeminiService backend integration tier", + "scope": "Enterprise SaaS / private cloud / hybrid", + "scale": "10k concurrent workflows · 100k agents · 500k users / tenant", + "deploymentTopology": "Multi-region active-active; sovereign-cloud variant for EU/UK/US-Gov", + }, + } + + +def executive_summary(): + return { + "purpose": ( + "To deliver a regulator-ready, board-approvable, end-to-end " + "implementation plan for the WorkflowAI Pro platform with the " + "GeminiService integration tier — covering architecture, data, " + "governance, security, AI safety reporting, and operational " + "excellence." + ), + "scope": ( + "All AI capabilities of the platform, from workflow " + "recommendation and adaptive UX through RAG chat, collaborative " + "prompt engineering, model registry, and the GeminiService " + "security/privacy substrate." + ), + "designPrinciples": [ + "Compliance-by-design: every capability ships with EU AI Act / GDPR / ISO 42001 controls", + "Defense-in-depth: 7 architectural planes with independent guardrails", + "Evidence-as-data: every action emits a signed telemetry envelope", + "Active learning with human-on-the-loop and cryptographically-signed feedback", + "Adaptive UX without dark patterns; transparency mandated", + "Grounded outputs only: RAG answers must cite or refuse", + "Zero-trust GeminiService: prompt-injection / Art. 5 / PII checks before every call", + ], + "keyOutcomes": { + "timeToGovernedDeployment": "≤ 72 hours", + "ragGroundednessScore": "≥ 0.92 faithfulness", + "promptCollabAdoption": "≥ 80% of teams within 6 months", + "modelRegistryCoverage": "100% of production AI assets tagged & versioned", + "geminiBlockedHarmRate": "≥ 99.5% on red-team suite", + "piiLeakageRate": "≤ 0.01% (post-redaction sample audit)", + "incidentMTTR": "≤ 60 min", + "auditReadiness": "≥ 92% evidence automation", + }, + "boardNarrative": ( + "WorkflowAI Pro upgrades enterprise productivity with AI while " + "treating safety, privacy, and compliance as first-class " + "platform capabilities — measurable, monitorable, and " + "demonstrable to regulators." + ), + } + + +def m1_architecture(): + return { + "id": "M1", + "title": "M1 — Platform Architecture (7-Plane Reference)", + "summary": "Seven-plane architecture isolating workload, governance, identity, data, AI, observability, and supply-chain concerns.", + "sections": [ + { + "id": "M1-S1", + "title": "Architecture Planes", + "planes": [ + {"id": "P1", "name": "Edge & Identity Plane", "components": ["WAF/CDN", "OIDC IdP", "SCIM", "FIDO2/WebAuthn", "API Gateway"], "responsibilities": "AuthN/AuthZ, rate limiting, geo routing"}, + {"id": "P2", "name": "Application Plane", "components": ["Next.js frontend", "Node/Express API", "Python services", "BFF", "Webhooks"], "responsibilities": "Feature surfaces, orchestration, tenancy"}, + {"id": "P3", "name": "AI Plane", "components": ["GeminiService gateway", "Prompt registry", "RAG service", "Recommender", "Active-learning loop"], "responsibilities": "All inference + retrieval"}, + {"id": "P4", "name": "Governance Plane", "components": ["Model registry", "Policy engine (OPA)", "Compliance engine", "Evidence store"], "responsibilities": "Policy decisions, evidence, attestations"}, + {"id": "P5", "name": "Data Plane", "components": ["Postgres/CRDB", "Vector DB (pgvector/Weaviate)", "Object store", "Kafka", "Cache"], "responsibilities": "Persistence, lineage, search"}, + {"id": "P6", "name": "Observability Plane", "components": ["OTel collector", "Prometheus", "Loki/ELK", "WORM telemetry topic", "SIEM"], "responsibilities": "Metrics, logs, traces, audit"}, + {"id": "P7", "name": "Supply-Chain Plane", "components": ["SLSA L3 build", "Sigstore/Cosign", "SBOM", "Dependency scanner"], "responsibilities": "Build integrity, SBOM, attestations"}, + ], + }, + { + "id": "M1-S2", + "title": "Deployment Topology", + "tiers": [ + {"tier": "Edge", "regions": "global PoPs", "tech": "Cloudflare / AWS CloudFront"}, + {"tier": "App", "regions": "primary + DR", "tech": "EKS/GKE/AKS, blue-green"}, + {"tier": "AI", "regions": "primary + DR", "tech": "GPU node pools, KEDA, vLLM/Triton"}, + {"tier": "Data", "regions": "active-active multi-region", "tech": "Aurora/Spanner, replicated S3"}, + ], + }, + { + "id": "M1-S3", + "title": "Tenancy Model", + "patterns": [ + "Pool-multi-tenant (default) with row-level security and per-tenant KMS keys", + "Silo-per-tenant for regulated tenants (banks, gov)", + "Sovereign-cloud variant with in-region GeminiService endpoints", + ], + }, + ], + } + + +def m2_data_models(): + return { + "id": "M2", + "title": "M2 — Data Models", + "summary": "Core entities and relationships for the platform.", + "sections": [ + { + "id": "M2-S1", + "title": "Entity Catalogue", + "entities": [ + {"id": "DM-01", "name": "User", "fields": "userId, tenantId, role[], skillProfile, locale, consents", "owner": "IAM service"}, + {"id": "DM-02", "name": "Workflow", "fields": "workflowId, ownerId, dag, version, status, tags[]", "owner": "Workflow service"}, + {"id": "DM-03", "name": "Recommendation", "fields": "recId, userId, candidateWorkflows[], context, score, feedback", "owner": "Recommender"}, + {"id": "DM-04", "name": "PromptTemplate", "fields": "templateId, versions[], variables[], owner, visibility, tags[], lineage", "owner": "Prompt registry"}, + {"id": "DM-05", "name": "ModelRegistration", "fields": "modelId, provider, version, sha256, evalRefs[], complianceTags[], rbacPolicyRef, status, rollbackTargetId", "owner": "Model registry"}, + {"id": "DM-06", "name": "RAGCorpus", "fields": "corpusId, sourceRefs[], lineage, retentionClass, piiPolicy, embeddingModelId", "owner": "RAG service"}, + {"id": "DM-07", "name": "GeminiCall", "fields": "callId, userId, modelId, promptHash, redactedPrompt, completionHash, safetyDecision, telemetrySig", "owner": "GeminiService"}, + {"id": "DM-08", "name": "Incident", "fields": "incidentId, severity, signals[], affectedAssets[], status, narrative", "owner": "SOC"}, + {"id": "DM-09", "name": "EvidenceRecord", "fields": "evidenceId, controlId, payloadHash, merkleRoot, signature, retainUntil", "owner": "Compliance engine"}, + ], + }, + { + "id": "M2-S2", + "title": "Lineage & Versioning", + "rules": [ + "All entities are immutable-on-update (event-sourced + materialised views)", + "Every mutation emits a signed event into the WORM Kafka topic ai.audit.v1", + "PromptTemplate, ModelRegistration, RAGCorpus carry SemVer + content hash", + "Rollback = pointer flip to a prior signed version; never a destructive op", + ], + }, + { + "id": "M2-S3", + "title": "Retention & Classification", + "classes": [ + {"class": "C1 Public", "retention": "indefinite", "storage": "S3 standard"}, + {"class": "C2 Internal", "retention": "5 yr", "storage": "S3 SSE-KMS"}, + {"class": "C3 Confidential", "retention": "7 yr WORM", "storage": "S3 Object Lock"}, + {"class": "C4 Restricted/PII", "retention": "policy-driven", "storage": "Tokenised + envelope encryption"}, + ], + }, + ], + } + + +def m3_data_flows(): + return { + "id": "M3", + "title": "M3 — Data Flows", + "summary": "Eight canonical end-to-end flows with governance hooks.", + "sections": [ + { + "id": "M3-S1", + "title": "Flow Catalogue", + "flows": [ + {"id": "DF-01", "name": "User → Workflow recommendation", "stages": "context → recommender → policy gate → UI", "governanceHooks": "consent check, fairness probe, telemetry"}, + {"id": "DF-02", "name": "Active-learning feedback", "stages": "user feedback → signer → kafka → trainer → recommender", "governanceHooks": "Ed25519 signature, bias re-eval"}, + {"id": "DF-03", "name": "RAG-grounded chat", "stages": "prompt → retriever → reranker → GeminiService → faithfulness scorer → UI", "governanceHooks": "PII redact, citation enforce, refusal policy"}, + {"id": "DF-04", "name": "Collaborative prompt edit", "stages": "edit → CRDT merge → variable lint → review → publish", "governanceHooks": "RBAC, lineage, prompt-injection lint"}, + {"id": "DF-05", "name": "Model registration", "stages": "submit → evals → sign → register → tag → rollout", "governanceHooks": "evals coverage, complianceTags, attestation"}, + {"id": "DF-06", "name": "GeminiService inference", "stages": "request → Art. 5 check → injection guard → call → safety classifier → response", "governanceHooks": "telemetry envelope, decision log"}, + {"id": "DF-07", "name": "AI safety incident", "stages": "detection → triage → containment → notification → forensic → post-mortem", "governanceHooks": "GDPR Art. 33/34, EU AI Act Art. 73"}, + {"id": "DF-08", "name": "Adaptive UX evaluation", "stages": "user signal → skill estimator → UX selector → A/B → ethics gate", "governanceHooks": "no dark patterns, transparency, opt-out"}, + ], + }, + { + "id": "M3-S2", + "title": "Governance Hooks (cross-cutting)", + "hooks": [ + "Consent verifier (per-purpose GDPR Art. 6/7)", + "PII redactor (Microsoft Presidio + custom rules)", + "EU AI Act Art. 5 prohibited-practice check", + "Prompt-injection / jailbreak detector", + "Faithfulness scorer for RAG outputs", + "Fairness probe (AIR / SPD windows)", + "Telemetry signer (Ed25519, optional Dilithium3)", + "Evidence emitter (control → evidence record)", + ], + }, + ], + } + + +def m4_workflow_recommender(): + return { + "id": "M4", + "title": "M4 — AI-Driven Workflow Recommendation & Active Learning", + "summary": "Two-tower recommender with bandit exploration, signed feedback loop, and bias guardrails.", + "sections": [ + { + "id": "M4-S1", + "title": "Recommender Architecture", + "components": [ + "Two-tower retrieval (user tower + workflow tower) on Vertex AI / SageMaker", + "Reranker LLM (Gemini Flash) with policy filter", + "Contextual bandit (LinUCB) for exploration", + "Post-rank fairness pass (group AIR ≥ 0.8)", + ], + }, + { + "id": "M4-S2", + "title": "Active Learning Loop", + "stages": [ + "Implicit feedback: dwell, completion, abandonment", + "Explicit feedback: thumbs / rationale / correction", + "Cryptographic signature on every feedback event (Ed25519)", + "Daily retrain with drift gate (PSI ≤ 0.1, no fairness regression)", + "Shadow + canary deploy (5% → 25% → 100%)", + ], + }, + { + "id": "M4-S3", + "title": "Cold-start & Privacy", + "controls": [ + "Skill-profile bootstrap from role + opt-in onboarding survey", + "Federated personalisation option (no raw signals leave device)", + "Differential privacy noise (ε ≤ 4) on aggregate analytics", + ], + }, + { + "id": "M4-S4", + "title": "APIs", + "routes": [ + "POST /api/recommend/workflows", + "POST /api/recommend/feedback", + "GET /api/recommend/profile", + "POST /api/recommend/retrain (admin)", + ], + }, + ], + } + + +def m5_adaptive_ux(): + return { + "id": "M5", + "title": "M5 — Adaptive Content & UI by Context and Skill", + "summary": "Skill-aware progressive disclosure and content adaptation with anti-dark-pattern guardrails.", + "sections": [ + { + "id": "M5-S1", + "title": "Skill Estimator", + "design": [ + "Bayesian skill model per capability (workflow design, prompt eng, data analysis)", + "Inputs: completion of guided tasks, support tickets, self-rating", + "Decay function for inactivity", + ], + }, + { + "id": "M5-S2", + "title": "UX Adaptation Patterns", + "patterns": [ + "Progressive disclosure tiers: Novice / Practitioner / Expert / Power", + "Inline coaching with dismissible cards", + "Reading-level adaptation (Flesch-Kincaid 8/12/16)", + "Locale + accessibility (WCAG 2.2 AA, ARIA, keyboard-only)", + ], + }, + { + "id": "M5-S3", + "title": "Ethics & Transparency", + "guardrails": [ + "No dark patterns (FTC + EU 2026 Digital Fairness Act)", + "Always-visible 'Why am I seeing this?' explainer", + "User-facing UX preference reset", + "Adaptation events emitted with consent flag", + ], + }, + ], + } + + +def m6_rag_chat(): + return { + "id": "M6", + "title": "M6 — High-Assurance RAG-Based Grounded Chat", + "summary": "RAG with lineage, citation enforcement, faithfulness scoring, and refusal-on-low-evidence.", + "sections": [ + { + "id": "M6-S1", + "title": "Retrieval Pipeline", + "stages": [ + "Query rewrite (intent + decomposition)", + "Hybrid search (BM25 + dense + filters)", + "Reranker (cross-encoder)", + "Context window builder with token budget + diversity", + "Citation pinner (chunk-level provenance)", + ], + }, + { + "id": "M6-S2", + "title": "Generation & Faithfulness", + "controls": [ + "Constrained generation: 'cite or refuse'", + "Faithfulness score (Q²/AlignScore/RAGAS) gating ≥ 0.92", + "Hallucination flag on unsupported claims", + "Refusal templates: 'I do not have evidence in your corpus to answer that.'", + ], + }, + { + "id": "M6-S3", + "title": "Corpus Governance", + "controls": [ + "Source allowlist & licence metadata", + "PII redaction at ingestion (Presidio + DLP)", + "Retention class on every chunk", + "Per-document RBAC enforced at query time (post-retrieval filter)", + "Right-to-be-forgotten propagation (vector deletion + reindex)", + ], + }, + { + "id": "M6-S4", + "title": "APIs", + "routes": [ + "POST /api/rag/chat", + "POST /api/rag/ingest", + "DELETE /api/rag/document/:id (RTBF)", + "GET /api/rag/corpus/:id/manifest", + ], + }, + ], + } + + +def m7_prompt_collab(): + return { + "id": "M7", + "title": "M7 — Collaborative Prompt Engineering", + "summary": "Multi-user prompt template lifecycle with CRDT editing, lineage, and review workflow.", + "sections": [ + { + "id": "M7-S1", + "title": "Lifecycle Stages", + "stages": ["Draft", "Review", "Approved", "Published", "Deprecated", "Archived"], + }, + { + "id": "M7-S2", + "title": "Collaboration Mechanics", + "design": [ + "CRDT (Yjs) for real-time co-editing", + "Variable schema with type, default, sensitivity", + "Variable-link UI to dataset / workflow context", + "Live test panel against canary model + sample dataset", + "PR-style review: 2-of-N approvers; CI runs eval suite", + ], + }, + { + "id": "M7-S3", + "title": "Lineage & Provenance", + "controls": [ + "Every version content-addressed (sha256)", + "Parent/child template links + diff view", + "Usage telemetry: per-template invocation count, faithfulness, satisfaction", + "Export/import as signed bundles (tar.gz + sig)", + ], + }, + { + "id": "M7-S4", + "title": "APIs", + "routes": [ + "POST /api/prompts/templates", + "GET /api/prompts/templates/:id", + "PATCH /api/prompts/templates/:id", + "POST /api/prompts/templates/:id/review", + "POST /api/prompts/templates/:id/publish", + "GET /api/prompts/templates/:id/lineage", + "POST /api/prompts/test", + ], + }, + ], + } + + +def m8_model_registry(): + return { + "id": "M8", + "title": "M8 — Enterprise Model Registry Governance", + "summary": "RBAC, compliance metadata, rollback, tagging, attestations.", + "sections": [ + { + "id": "M8-S1", + "title": "Registry Schema", + "fields": [ + "modelId, provider, family, version, sha256", + "evalRefs[]: pointers to eval suites and results", + "complianceTags[]: 'EU_AI_ACT_HIGH_RISK', 'GDPR_DPIA', 'SR_11_7_TIER_1'", + "rbacPolicyRef: OPA bundle key", + "status: draft|registered|approved|published|paused|retired", + "rollbackTargetId: previous-known-good model pointer", + "ownerSubjectId; approvers[]; signatures[]", + ], + }, + { + "id": "M8-S2", + "title": "RBAC & Policy", + "roles": [ + "model_author", "model_validator", "model_approver", "model_operator", + "auditor (read-only)", "dpo (read+veto on PII concerns)", + ], + "policies": [ + "deploy_gate.rego: signature + IMV + DPIA non-expired", + "high_risk_label.rego: Annex IV dossier present", + "rollback_window.rego: rollback always within 30s window", + ], + }, + { + "id": "M8-S3", + "title": "Tagging & Search", + "design": [ + "Tag namespace: regulatory, sector, capability, sensitivity, lifecycle", + "Full-text + facet search across registry", + "Saved queries for audit & supervisor read-only views", + ], + }, + { + "id": "M8-S4", + "title": "APIs", + "routes": [ + "POST /api/models/register", + "GET /api/models/:id", + "POST /api/models/:id/approve", + "POST /api/models/:id/publish", + "POST /api/models/:id/rollback", + "POST /api/models/:id/tag", + "GET /api/models/search", + "GET /api/models/:id/attestations", + ], + }, + ], + } + + +def m9_safety_reporting(): + return { + "id": "M9", + "title": "M9 — AI Safety & Global Governance Reporting", + "summary": "Reporting framework spanning existential risk, misuse, bias, threat assessment, alignment failure, and international collaboration.", + "sections": [ + { + "id": "M9-S1", + "title": "Report Catalogue", + "reports": [ + {"id": "SR-01", "name": "Existential Risk Outlook", "cadence": "Annual", "audience": "Board + Treaty Authority"}, + {"id": "SR-02", "name": "Misuse & Dual-Use Threat Assessment", "cadence": "Semi-annual", "audience": "CISO + Treaty + GC"}, + {"id": "SR-03", "name": "Bias & Fairness Report", "cadence": "Quarterly", "audience": "DPO + Compliance + Board"}, + {"id": "SR-04", "name": "Alignment Failure Scenarios", "cadence": "Quarterly tabletop + post-incident", "audience": "Board + CAIO + research community"}, + {"id": "SR-05", "name": "International Collaboration Brief", "cadence": "Quarterly", "audience": "Treaty Liaison Officer"}, + {"id": "SR-06", "name": "Capability Evaluation Disclosure", "cadence": "Per material capability change", "audience": "ICGC / regulator"}, + {"id": "SR-07", "name": "Incident & Near-Miss Register", "cadence": "Continuous", "audience": "CISO + Internal Audit"}, + {"id": "SR-08", "name": "Annual AI Safety Statement", "cadence": "Annual public", "audience": "Public + investors"}, + ], + }, + { + "id": "M9-S2", + "title": "Risk Taxonomy", + "categories": [ + "Existential / civilizational", + "Misuse (CBRN, cyber, mass-disinfo)", + "Bias / disparate impact", + "Privacy / re-identification", + "Alignment failure (specification gaming, deceptive alignment)", + "Containment escape / agentic over-reach", + "Concentration / monoculture", + "Conduct / consumer harm", + ], + }, + { + "id": "M9-S3", + "title": "International Collaboration", + "channels": [ + "ICGC compute & capability disclosure", + "Bletchley/Seoul/Paris commitments", + "OECD AI Policy Observatory", + "G7 Hiroshima AI Process Code of Conduct", + "AISI / UK AISI / US AISI evaluation participation", + "Council of Europe AI Convention compliance", + ], + }, + { + "id": "M9-S4", + "title": "APIs", + "routes": [ + "GET /api/safety/reports", + "GET /api/safety/reports/:id", + "POST /api/safety/incidents", + "GET /api/safety/risk-register", + "POST /api/safety/disclosures (treaty)", + ], + }, + ], + } + + +def m10_gemini_security(): + return { + "id": "M10", + "title": "M10 — GeminiService Security & Privacy Controls", + "summary": "Telemetry integrity, GDPR PII redaction, EU AI Act Art. 5 checks, adversarial-prompt defenses.", + "sections": [ + { + "id": "M10-S1", + "title": "GeminiService Gateway", + "design": [ + "All Gemini calls routed through internal gateway (no direct SDK from frontend)", + "Per-tenant API keys vaulted in HSM/KMS", + "mTLS to provider; egress allowlist; outbound DLP", + "Per-call decision log signed (Ed25519) and shipped to WORM Kafka", + ], + }, + { + "id": "M10-S2", + "title": "Pre-Call Pipeline (in order)", + "stages": [ + "1. AuthN/AuthZ (OIDC + scope + tenancy)", + "2. Rate / cost guard (token budget per user/tenant)", + "3. PII redactor (Presidio + custom regex + ML classifier)", + "4. EU AI Act Art. 5 prohibited-practice classifier (manipulation, social scoring, biometric categorisation, predictive policing for individuals, etc.)", + "5. Prompt-injection / jailbreak detector (rules + LLM judge + perplexity heuristic)", + "6. Constitutional / policy filter", + "7. Telemetry envelope creation + signature", + ], + }, + { + "id": "M10-S3", + "title": "Post-Call Pipeline", + "stages": [ + "1. Output safety classifier (toxicity, self-harm, illegal, CSAM)", + "2. PII / secrets leakage scan (egress redactor)", + "3. Faithfulness / citation check (RAG path)", + "4. Final policy filter; deliver or refuse", + "5. Append response hash + final decision to telemetry envelope", + ], + }, + { + "id": "M10-S4", + "title": "Telemetry Integrity", + "controls": [ + "Append-only Kafka topic ai.gemini.telemetry.v1 with mTLS + ACLs", + "Daily Merkle root anchored to RFC 3161 timestamp + (optional) blockchain anchor", + "PQC-ready signatures (Dilithium3 dual-signature option)", + "Tamper alarms on hash-chain breaks (auto-incident creation)", + ], + }, + { + "id": "M10-S5", + "title": "Adversarial Defenses", + "defenses": [ + "Multi-layer prompt-injection detection (pre-, mid-, post-)", + "Tool-call allowlisting + scoped credentials per call", + "Indirect-prompt-injection sanitisation on retrieved content", + "Canary tokens to detect data exfiltration via prompts", + "Red-team test suite gated in CI (block release if regression)", + ], + }, + { + "id": "M10-S6", + "title": "APIs", + "routes": [ + "POST /api/gemini/generate", + "POST /api/gemini/embed", + "POST /api/gemini/vision", + "GET /api/gemini/telemetry/:callId", + "GET /api/gemini/policies", + ], + }, + ], + } + + +def m11_task_report(): + return { + "id": "M11", + "title": "M11 — Task & Report Management", + "summary": "End-user and admin features for tasks, reports, exports, and audit packs.", + "sections": [ + { + "id": "M11-S1", + "title": "Task Management", + "features": [ + "Task DAG visualisation (D3/dagre)", + "Assignment & SLA tracking", + "Comments + @mentions + activity stream", + "Linked artefacts: prompts, models, RAG corpora, evidence", + "Bulk operations with idempotency keys", + ], + }, + { + "id": "M11-S2", + "title": "Report Generation", + "features": [ + "Templated reports (Markdown with /<abstract>/<content>)", + "PDF/A-3 export with embedded JSON-LD evidence", + "Scheduled reports (cron + event-driven)", + "Distribution: email (DMARC), Slack/Teams, SFTP, S3 dropzone", + "Auditor read-only export channel", + ], + }, + { + "id": "M11-S3", + "title": "APIs", + "routes": [ + "POST /api/tasks", + "GET /api/tasks/:id", + "PATCH /api/tasks/:id", + "POST /api/tasks/:id/comment", + "GET /api/reports/templates", + "POST /api/reports/render", + "POST /api/reports/schedule", + "GET /api/reports/exports/:id", + ], + }, + ], + } + + +def m12_implementation_strategy(): + return { + "id": "M12", + "title": "M12 — Implementation Strategy & Integration Patterns", + "summary": "Step-by-step strategy, module boundaries, and integration patterns for enterprise deployment.", + "sections": [ + { + "id": "M12-S1", + "title": "Six-Phase Plan (52 weeks)", + "phases": [ + {"phase": "P1 Foundations", "weeks": "1-6", "deliverables": ["Tenancy model", "Identity (OIDC/SCIM)", "OPA bundle bootstrap", "Kafka WORM cluster", "Skeleton APIs"]}, + {"phase": "P2 Governance Spine", "weeks": "7-14", "deliverables": ["Model registry + RBAC", "Compliance engine", "Evidence store", "Telemetry envelopes"]}, + {"phase": "P3 AI Core", "weeks": "15-26", "deliverables": ["GeminiService gateway", "Prompt registry + collab", "RAG service + faithfulness", "Recommender v1"]}, + {"phase": "P4 Adaptive UX & Tasks", "weeks": "27-34", "deliverables": ["Skill estimator", "Adaptive UI", "Task DAG", "Reports v1"]}, + {"phase": "P5 Safety Reporting & Treaty", "weeks": "35-44", "deliverables": ["Safety report suite", "Treaty disclosure pack", "Tabletop GC1-GC7"]}, + {"phase": "P6 Hardening & Certification", "weeks": "45-52", "deliverables": ["ISO 42001 cert", "SOC 2 Type II", "Annex IV pilots", "Pen-test + red-team"]}, + ], + }, + { + "id": "M12-S2", + "title": "Module Boundaries", + "boundaries": [ + "Identity service (P1) — single source of truth for users/roles", + "Workflow service — owns workflow DAGs; consumes recommendations", + "Recommender service — stateless API; trained offline; reads features from feature store", + "Prompt registry — owns templates + lineage; emits events", + "RAG service — owns corpora + retrieval; isolates per-tenant indices", + "Model registry — owns ModelRegistration; enforces RBAC + signatures", + "GeminiService gateway — single egress point to provider", + "Compliance engine — read-side projection from event log; emits coverage scorecards", + "Observability — strictly read-only consumer of telemetry topics", + ], + }, + { + "id": "M12-S3", + "title": "Integration Patterns", + "patterns": [ + "Event-driven via Kafka (ai.audit.v1, ai.gemini.telemetry.v1, ai.recsys.events.v1)", + "Synchronous REST/gRPC behind API gateway with mTLS", + "Webhooks for tenant-side integrations (signed payloads, replay protection)", + "OIDC-federated SSO + SCIM provisioning", + "Outbound connectors: Slack/Teams, Jira, ServiceNow, Splunk, Datadog", + "Data-residency routing via gateway + per-region GeminiService endpoints", + "Sovereign-cloud variant with no cross-border calls", + "BYOK (Bring-Your-Own-Key) for tenant KMS", + ], + }, + { + "id": "M12-S4", + "title": "KPIs / OKRs", + "kpis": [ + {"id": "KPI-01", "name": "Time-to-governed-deployment", "target": "≤ 72 h"}, + {"id": "KPI-02", "name": "RAG faithfulness", "target": "≥ 0.92"}, + {"id": "KPI-03", "name": "Prompt collab adoption", "target": "≥ 80% teams"}, + {"id": "KPI-04", "name": "Model registry coverage", "target": "100%"}, + {"id": "KPI-05", "name": "Gemini blocked-harm rate", "target": "≥ 99.5%"}, + {"id": "KPI-06", "name": "PII leakage", "target": "≤ 0.01%"}, + {"id": "KPI-07", "name": "Containment MTTR", "target": "≤ 60 min"}, + {"id": "KPI-08", "name": "Evidence automation", "target": "≥ 92%"}, + {"id": "KPI-09", "name": "Alignment-drift MTTD", "target": "≤ 4 min"}, + {"id": "KPI-10", "name": "Active-learning loop latency", "target": "≤ 24 h to retrain"}, + {"id": "KPI-11", "name": "Adaptive-UX opt-out completion", "target": "≤ 3 clicks"}, + {"id": "KPI-12", "name": "Audit finding closure", "target": "≤ 90 d (high)"}, + {"id": "KPI-13", "name": "Recommender AIR floor", "target": "≥ 0.8"}, + {"id": "KPI-14", "name": "Telemetry continuity", "target": "≥ 99.99%"}, + {"id": "KPI-15", "name": "Adversarial-prompt block rate", "target": "≥ 99% on red-team set"}, + ], + }, + { + "id": "M12-S5", + "title": "Risk Register (top 8)", + "risks": [ + {"id": "R1", "name": "Prompt-injection via retrieved content", "mitigation": "Indirect-injection sanitiser + tool allowlist"}, + {"id": "R2", "name": "Hallucination in RAG chat", "mitigation": "Faithfulness gate + cite-or-refuse"}, + {"id": "R3", "name": "PII leakage to provider", "mitigation": "Pre-call redactor + egress DLP + telemetry audit"}, + {"id": "R4", "name": "Bias amplification via active learning", "mitigation": "Per-loop fairness gate + counterfactual eval"}, + {"id": "R5", "name": "Model rollback failure", "mitigation": "Always-on N-1 hot path + 30s rollback test in CI"}, + {"id": "R6", "name": "Telemetry tampering", "mitigation": "Hash-chained WORM + Merkle anchor + alarms"}, + {"id": "R7", "name": "EU AI Act Art. 5 violation in user prompt", "mitigation": "Pre-call classifier + refusal templates"}, + {"id": "R8", "name": "Concentration risk on Gemini", "mitigation": "Multi-provider abstraction + benchmark fail-over"}, + ], + }, + ], + } + + +def schemas(): + return { + "promptTemplate": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/prompt-template.json", + "type": "object", + "required": ["templateId", "version", "owner", "body", "variables"], + "properties": { + "templateId": {"type": "string"}, + "version": {"type": "string"}, + "owner": {"type": "string"}, + "body": {"type": "string"}, + "variables": {"type": "array", "items": {"type": "object", + "required": ["name", "type"], + "properties": { + "name": {"type": "string"}, + "type": {"enum": ["string", "number", "bool", "enum", "json"]}, + "default": {}, + "sensitivity": {"enum": ["public", "internal", "confidential", "pii"]}, + "linkTo": {"type": "string"}, + }}}, + "tags": {"type": "array", "items": {"type": "string"}}, + "lineage": {"type": "object"}, + }, + }, + "modelRegistration": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/model-registration.json", + "type": "object", + "required": ["modelId", "provider", "version", "sha256", "status"], + "properties": { + "modelId": {"type": "string"}, + "provider": {"type": "string"}, + "version": {"type": "string"}, + "sha256": {"type": "string", "pattern": "^[A-Fa-f0-9]{64}$"}, + "evalRefs": {"type": "array", "items": {"type": "string"}}, + "complianceTags": {"type": "array", "items": {"type": "string"}}, + "rbacPolicyRef": {"type": "string"}, + "status": {"enum": ["draft", "registered", "approved", "published", "paused", "retired"]}, + "rollbackTargetId": {"type": "string"}, + "signatures": {"type": "array"}, + }, + }, + "ragQueryEnvelope": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/rag-query-envelope.json", + "type": "object", + "required": ["queryId", "userId", "tenantId", "corpusId", "query", "ts"], + "properties": { + "queryId": {"type": "string"}, + "userId": {"type": "string"}, + "tenantId": {"type": "string"}, + "corpusId": {"type": "string"}, + "query": {"type": "string"}, + "ts": {"type": "string", "format": "date-time"}, + "redactionFlags": {"type": "array"}, + "consents": {"type": "object"}, + }, + }, + "geminiCallEnvelope": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/gemini-call-envelope.json", + "type": "object", + "required": ["callId", "userId", "modelId", "promptHash", "ts", "signature"], + "properties": { + "callId": {"type": "string"}, + "userId": {"type": "string"}, + "tenantId": {"type": "string"}, + "modelId": {"type": "string"}, + "promptHash": {"type": "string"}, + "redactedPromptPreview": {"type": "string"}, + "completionHash": {"type": "string"}, + "safetyDecision": {"enum": ["allow", "warn", "refuse"]}, + "art5Decision": {"enum": ["allow", "block"]}, + "injectionScore": {"type": "number"}, + "ts": {"type": "string", "format": "date-time"}, + "signature": {"type": "object", "required": ["alg", "value", "keyId"]}, + }, + }, + "feedbackEvent": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/feedback-event.json", + "type": "object", + "required": ["eventId", "userId", "subjectId", "subjectType", "verdict", "signature"], + "properties": { + "eventId": {"type": "string"}, + "userId": {"type": "string"}, + "subjectId": {"type": "string"}, + "subjectType": {"enum": ["recommendation", "rag-answer", "prompt", "workflow"]}, + "verdict": {"enum": ["up", "down", "correct", "abandon"]}, + "rationale": {"type": "string"}, + "signature": {"type": "object"}, + }, + }, + "recommendation": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/recommendation.json", + "type": "object", + "required": ["recId", "userId", "candidates", "ts"], + "properties": { + "recId": {"type": "string"}, + "userId": {"type": "string"}, + "candidates": {"type": "array", "items": {"type": "object", + "properties": {"workflowId": {"type": "string"}, "score": {"type": "number"}, "reasonCodes": {"type": "array"}}}}, + "context": {"type": "object"}, + "fairness": {"type": "object"}, + "ts": {"type": "string", "format": "date-time"}, + }, + }, + "evidenceRecord": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/evidence-record.json", + "type": "object", + "required": ["evidenceId", "controlId", "payloadHash", "merkleRoot", "signature", "retainUntil"], + "properties": { + "evidenceId": {"type": "string"}, + "controlId": {"type": "string"}, + "payloadHash": {"type": "string"}, + "merkleRoot": {"type": "string"}, + "signature": {"type": "object"}, + "retainUntil": {"type": "string", "format": "date-time"}, + }, + }, + "incidentRecord": { + "$id": "https://workflowai.pro/schemas/wfap-gemini/incident-record.json", + "type": "object", + "required": ["incidentId", "severity", "status", "openedAt"], + "properties": { + "incidentId": {"type": "string"}, + "severity": {"enum": ["SEV-3", "SEV-2", "SEV-1", "SEV-0"]}, + "status": {"enum": ["open", "contained", "resolved", "post-mortem"]}, + "category": {"type": "string"}, + "affectedAssets": {"type": "array"}, + "openedAt": {"type": "string", "format": "date-time"}, + "narrative": {"type": "string"}, + }, + }, + } + + +def code_examples(): + return { + "geminiGatewayPython": '''#!/usr/bin/env python3 +"""GeminiService gateway — pre/post pipeline (FastAPI).""" +from fastapi import FastAPI, Header, HTTPException +from pydantic import BaseModel +import hashlib, time +from cryptography.hazmat.primitives.asymmetric import ed25519 +from policy import art5_check, injection_score, redact_pii, output_safety + +app = FastAPI() +SK = ed25519.Ed25519PrivateKey.generate() # demo only; load from KMS + +class GenReq(BaseModel): + user_id: str + tenant_id: str + model_id: str + prompt: str + +@app.post("/api/gemini/generate") +def generate(req: GenReq, authorization: str = Header(...)): + redacted, flags = redact_pii(req.prompt) + if art5_check(redacted) == "block": + raise HTTPException(451, "Art. 5 prohibited practice") + if injection_score(redacted) > 0.85: + raise HTTPException(400, "prompt injection suspected") + completion = call_gemini(req.model_id, redacted) + if output_safety(completion) == "refuse": + return {"refused": True, "reason": "safety classifier"} + envelope = { + "callId": hashlib.sha256(f"{req.user_id}{time.time_ns()}".encode()).hexdigest(), + "userId": req.user_id, "tenantId": req.tenant_id, + "modelId": req.model_id, + "promptHash": hashlib.sha256(req.prompt.encode()).hexdigest(), + "completionHash": hashlib.sha256(completion.encode()).hexdigest(), + "safetyDecision": "allow", "art5Decision": "allow", + "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + } + sig = SK.sign(json.dumps(envelope, sort_keys=True).encode()).hex() + envelope["signature"] = {"alg": "Ed25519", "value": sig, "keyId": "kms:gemini-gw-2026"} + emit_kafka("ai.gemini.telemetry.v1", envelope) + return {"completion": completion, "envelope": envelope} +''', + "ragChatTypeScript": '''// /api/rag/chat — Express + retriever + faithfulness gate +import express from "express"; +import { hybridSearch, rerank, faithfulness, redact } from "./rag"; +const app = express(); +app.use(express.json()); + +app.post("/api/rag/chat", async (req, res) => { + const { tenantId, userId, corpusId, question } = req.body; + const safe = redact(question); + const hits = await hybridSearch(corpusId, safe, { tenantAcl: tenantId }); + const ranked = await rerank(safe, hits); + if (ranked.length === 0) { + return res.json({ refused: true, reason: "no evidence in corpus" }); + } + const draft = await callGemini({ system: SYSTEM_CITE_OR_REFUSE, ctx: ranked, q: safe }); + const score = await faithfulness(draft, ranked); + if (score < 0.92) { + return res.json({ refused: true, reason: "low faithfulness", score }); + } + res.json({ answer: draft, citations: ranked.map(r => r.docRef), score }); +}); +''', + "modelRegistryNode": '''// Model registry — register / approve / rollback +const express = require("express"); +const { sign, verify } = require("./pqc"); +const opa = require("./opa"); +const router = express.Router(); + +router.post("/api/models/register", async (req, res) => { + const m = req.body; + if (!/^[A-Fa-f0-9]{64}$/.test(m.sha256)) return res.status(400).json({ error: "bad sha256" }); + const decision = await opa.eval("wfap.deploy_gate.allow", { model: m }); + if (!decision.allow) return res.status(403).json(decision); + m.status = "registered"; + m.signatures = [sign(m)]; + await db.models.insert(m); + res.json(m); +}); + +router.post("/api/models/:id/rollback", async (req, res) => { + const cur = await db.models.find(req.params.id); + if (!cur.rollbackTargetId) return res.status(400).json({ error: "no rollback target" }); + const tgt = await db.models.find(cur.rollbackTargetId); + await db.models.update(cur.id, { status: "paused" }); + await db.models.update(tgt.id, { status: "published" }); + emitAudit({ type: "model.rollback", from: cur.id, to: tgt.id }); + res.json({ rolledBackTo: tgt.id }); +}); + +module.exports = router; +''', + "promptCollabCRDT": '''// Prompt template collaborative editor (Yjs server) +const Y = require("yjs"); +const { setupWSConnection } = require("y-websocket/bin/utils"); +const WebSocket = require("ws"); + +const wss = new WebSocket.Server({ port: 1234 }); +wss.on("connection", (conn, req) => { + const auth = verifyJwt(req.headers["sec-websocket-protocol"]); + if (!auth) return conn.close(4401); + setupWSConnection(conn, req, { + docName: `prompt:${auth.tenantId}:${req.url.slice(1)}`, + gc: true, + }); + conn.on("close", () => emitAudit({ type: "prompt.session.close", user: auth.sub })); +}); +''', + "recommenderActiveLearning": '''#!/usr/bin/env python3 +"""Active-learning loop — drift gate + fairness gate.""" +import pandas as pd, numpy as np +from cryptography.hazmat.primitives.asymmetric import ed25519 + +def psi(a, b, bins=10): + qs = np.linspace(0,1,bins+1) + cuts = np.quantile(np.concatenate([a,b]), qs) + pa,_ = np.histogram(a, cuts); pa = pa/pa.sum()+1e-9 + pb,_ = np.histogram(b, cuts); pb = pb/pb.sum()+1e-9 + return float(np.sum((pa-pb)*np.log(pa/pb))) + +def air(scores, group): + rates = pd.Series(scores).groupby(group).mean() + return rates.min()/rates.max() + +def gate(new_scores, old_scores, groups): + if psi(new_scores, old_scores) > 0.1: raise SystemExit("PSI drift") + if air(new_scores, groups) < 0.8: raise SystemExit("AIR floor") + print("PASS") +''', + "regoDeployGate": '''package wfap.deploy_gate + +# OPA policy gating model deployment +default allow = false + +allow { + input.model.signatures[_].verified + input.model.evalRefs[_] + not expired_dpia + has_required_tags +} + +expired_dpia { + time.parse_rfc3339_ns(input.model.dpia.expiresAt) < time.now_ns() +} + +has_required_tags { + required := {"FAIRNESS_TESTED", "PII_REDACTION_VERIFIED"} + set := {t | t := input.model.complianceTags[_]} + required - set == set() +} +''', + "art5Classifier": '''#!/usr/bin/env python3 +"""EU AI Act Art. 5 prohibited-practice classifier (heuristic + LLM judge).""" +PROHIBITED = [ + "subliminal_techniques", + "exploitation_of_vulnerabilities", + "social_scoring_individuals", + "biometric_categorisation_sensitive", + "real_time_remote_biometric_id", + "predictive_policing_individual", + "emotion_recognition_workplace_education", + "untargeted_facial_image_scraping", +] + +def art5_check(text: str) -> str: + # 1. rule-based fast path + if any(k in text.lower() for k in ["social score", "rank citizens", "predict who will commit"]): + return "block" + # 2. LLM judge (Gemini Flash) — JSON schema response + judge = call_gemini_judge(text, PROHIBITED) + return "block" if judge.get("matches") else "allow" +''', + "piiRedactorPython": '''#!/usr/bin/env python3 +"""GDPR PII redactor — Presidio + custom rules.""" +from presidio_analyzer import AnalyzerEngine +from presidio_anonymizer import AnonymizerEngine + +ANALYZER = AnalyzerEngine() +ANON = AnonymizerEngine() + +def redact_pii(text: str, lang: str = "en"): + results = ANALYZER.analyze(text=text, language=lang, + entities=["PERSON","EMAIL_ADDRESS","PHONE_NUMBER","CREDIT_CARD", + "IBAN_CODE","IP_ADDRESS","LOCATION","UK_NHS","US_SSN"]) + out = ANON.anonymize(text=text, analyzer_results=results) + flags = sorted({r.entity_type for r in results}) + return out.text, flags +''', + "merkleAuditTelemetry": '''#!/usr/bin/env python3 +"""Daily Merkle audit of GeminiService telemetry.""" +import hashlib, json, time, boto3 + +def merkle(leaves): + layer = [hashlib.sha256(l).digest() for l in leaves] or [b""] + while len(layer) > 1: + if len(layer) % 2: layer.append(layer[-1]) + layer = [hashlib.sha256(layer[i]+layer[i+1]).digest() + for i in range(0,len(layer),2)] + return layer[0] + +def daily(bucket, prefix): + s3 = boto3.client("s3") + leaves = [s3.get_object(Bucket=bucket, Key=o["Key"])["Body"].read() + for o in s3.list_objects_v2(Bucket=bucket, Prefix=prefix).get("Contents", [])] + root = merkle(leaves).hex() + manifest = {"date": time.strftime("%Y-%m-%d"), "merkleRoot": root, "leaves": len(leaves)} + s3.put_object(Bucket=bucket, Key=f"{prefix}/_manifests/{manifest['date']}.json", + Body=json.dumps(manifest).encode(), + ObjectLockMode="COMPLIANCE", + ObjectLockRetainUntilDate="2033-01-01T00:00:00Z") + return manifest +''', + "ciGithubWorkflow": '''# .github/workflows/wfap-gemini.yml +name: wfap-gemini-ci +on: [push, pull_request] +jobs: + govern: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: opa fmt --diff policies/ && opa test policies/ + - run: conftest test --policy policies deploy/ + - run: pytest tests/redteam tests/art5 tests/injection -q + - run: python tools/faithfulness_eval.py --threshold 0.92 + - run: python tools/bias_gate.py --air 0.8 --psi 0.1 + - run: | + docker build -t wfap-gemini:${{ github.sha }} . + cosign sign --yes wfap-gemini:${{ github.sha }} + cosign attest --predicate evidence.json wfap-gemini:${{ github.sha }} + - run: kubectl apply -f deploy/canary-5pct.yaml +''', + "adaptiveUxReact": '''// React hook: useAdaptiveUx — skill-tier gating with ethics guardrails +import { useState, useEffect } from "react"; + +export function useAdaptiveUx(capability) { + const [tier, setTier] = useState("practitioner"); + const [transparency, setTransparency] = useState(true); + + useEffect(() => { + fetch(`/api/skill/${capability}`).then(r => r.json()).then(s => { + setTier(s.tier); + }); + }, [capability]); + + const reasonCard = ( + <button onClick={() => alert(`UI tier '${tier}' chosen from your skill profile. You can reset under Settings → UX.`)}> + Why am I seeing this? + </button> + ); + return { tier, transparency, reasonCard }; +} +''', + "kafkaWormProducer": '''// signed-telemetry producer (Node) +const { Kafka } = require("kafkajs"); +const { sign } = require("./signer-ed25519"); +const k = new Kafka({ brokers: process.env.KAFKA_BROKERS.split(",") }); +const p = k.producer({ idempotent: true }); +async function send(topic, payload) { + await p.connect(); + const env = { ...payload, ts: new Date().toISOString() }; + env.signature = sign(JSON.stringify(env)); + await p.send({ topic, messages: [{ key: env.callId || env.eventId, value: JSON.stringify(env) }] }); +} +module.exports = { send }; +''', + } + + +def case_studies(): + return [ + { + "id": "CS-01", + "title": "Global bank — WorkflowAI Pro on regulated estate", + "sector": "Banking", + "summary": "Tier-1 bank deployed WorkflowAI Pro across 38k users with full SR 11-7 + EU AI Act alignment.", + "outcomes": { + "users": 38000, + "modelsRegistered": 412, + "promptTemplatesPublished": 1840, + "ragGroundedness": "0.94 avg", + "geminiBlockedHarmRate": "99.7%", + "ISO42001": "Certified", + }, + }, + { + "id": "CS-02", + "title": "Pharma — RAG chat for SMEs and regulators", + "sector": "Life Sciences", + "summary": "RAG chat over GxP-controlled corpora with zero hallucination tolerance and audit trail.", + "outcomes": { + "corpora": 22, + "monthlyQueries": 1.4e6, + "hallucinationIncidents": 0, + "regulatoryEngagement": "FDA + EMA satisfied", + }, + }, + { + "id": "CS-03", + "title": "Public sector — Sovereign-cloud variant", + "sector": "Government", + "summary": "G7 ministry deployed sovereign-cloud variant with in-region GeminiService and air-gapped admin.", + "outcomes": { + "dataResidency": "100%", + "treatyDisclosures": 4, + "redTeamPassRate": "99.3%", + }, + }, + { + "id": "CS-04", + "title": "Insurer — Fairness-aware recommender", + "sector": "Insurance", + "summary": "Workflow recommender personalised to claims handlers with strict fairness floor (AIR ≥ 0.85).", + "outcomes": { + "AIRAfter": 0.88, + "handlerProductivity": "+19%", + "consumerComplaints": "-23%", + }, + }, + { + "id": "CS-05", + "title": "Tech conglomerate — Collaborative prompt engineering at scale", + "sector": "Technology", + "summary": "300+ teams onboarded to collaborative prompt registry with PR-style review and CI evals.", + "outcomes": { + "templatesActive": 6200, + "averageReviewTime": "37 min", + "evalRegressionsBlocked": 184, + "adoption": "92% of eligible teams", + }, + }, + ] + + +def api_endpoints(): + routes = [ + "", "/meta", "/executive-summary", "/summary", + "/architecture", "/architecture/planes", "/architecture/topology", "/architecture/tenancy", + "/data-models", "/data-models/:id", + "/data-flows", "/data-flows/:id", + "/recommender", "/recommender/active-learning", "/recommender/apis", + "/adaptive-ux", "/adaptive-ux/skill", "/adaptive-ux/ethics", + "/rag", "/rag/retrieval", "/rag/faithfulness", "/rag/governance", "/rag/apis", + "/prompts", "/prompts/lifecycle", "/prompts/collab", "/prompts/lineage", "/prompts/apis", + "/registry", "/registry/schema", "/registry/rbac", "/registry/tagging", "/registry/apis", + "/safety-reports", "/safety-reports/:id", "/safety-reports/risks", "/safety-reports/intl-collab", + "/gemini", "/gemini/gateway", "/gemini/pre-call", "/gemini/post-call", "/gemini/telemetry", "/gemini/adversarial", "/gemini/apis", + "/tasks-reports", "/tasks-reports/tasks", "/tasks-reports/reports", "/tasks-reports/apis", + "/strategy", "/strategy/phases", "/strategy/boundaries", "/strategy/integration", "/strategy/kpis", "/strategy/risks", + "/schemas", "/schemas/:name", + "/code-examples", "/code-examples/:name", + "/case-studies", "/case-studies/:id", + "/modules", "/modules/:id", "/sections/:id", + ] + for i in range(1, 13): + routes.append(f"/m{i}") + return {"prefix": "/api/wfap-gemini", "routes": routes} + + +def main(): + data = { + "meta": meta(), + "executiveSummary": executive_summary(), + "M1_architecture": m1_architecture(), + "M2_dataModels": m2_data_models(), + "M3_dataFlows": m3_data_flows(), + "M4_recommender": m4_workflow_recommender(), + "M5_adaptiveUx": m5_adaptive_ux(), + "M6_ragChat": m6_rag_chat(), + "M7_promptCollab": m7_prompt_collab(), + "M8_modelRegistry": m8_model_registry(), + "M9_safetyReporting": m9_safety_reporting(), + "M10_geminiSecurity": m10_gemini_security(), + "M11_taskReport": m11_task_report(), + "M12_implementation": m12_implementation_strategy(), + "schemas": schemas(), + "codeExamples": code_examples(), + "caseStudies": case_studies(), + "apiEndpoints": api_endpoints(), + } + OUT.parent.mkdir(parents=True, exist_ok=True) + OUT.write_text(json.dumps(data, indent=2), encoding="utf-8") + size_kb = OUT.stat().st_size // 1024 + n_modules = sum(1 for k in data if k.startswith("M") and "_" in k) + n_sections = sum(len(data[k].get("sections", [])) for k in data if k.startswith("M") and "_" in k) + print(f"Wrote {OUT} ({size_kb} KB)") + print(f"Modules: {n_modules} | Sections: {n_sections} | Schemas: {len(data['schemas'])} | " + f"Code: {len(data['codeExamples'])} | Cases: {len(data['caseStudies'])} | " + f"Routes: {len(data['apiEndpoints']['routes'])}") + + +if __name__ == "__main__": + main() diff --git a/rag-agentic-dashboard/public/ent-agi-gov-master.html b/rag-agentic-dashboard/public/ent-agi-gov-master.html new file mode 100644 index 0000000..5e5db0b --- /dev/null +++ b/rag-agentic-dashboard/public/ent-agi-gov-master.html @@ -0,0 +1,752 @@ +<!doctype html> +<html lang="en"> +<head> +<meta charset="utf-8" /> +<meta name="viewport" content="width=device-width,initial-scale=1" /> +<title>ENT-AGI-GOV-MASTER-WP-035 — Enterprise AGI/ASI Governance Master Framework (2026-2030) + + + + +
    +
    ENT-AGI-GOV-MASTER-WP-035 · CONFIDENTIAL — Board / C-Suite / Prudential Supervisor / Treaty Authority / Internal & External Audit
    +

    Enterprise AGI/ASI Governance Master Framework (2026-2030)

    +

    Institutional-grade, regulator-ready AGI/ASI and enterprise AI governance frameworks, reference architectures, safety and containment protocols, financial-services model risk management, civilizational-scale compute oversight, and implementation roadmaps for Fortune 500, Global 2000, and G-SIFIs.

    +
    + Version 1.0.0 + Date 2026-04-25 + Horizon 2026-2030 (with 2030-2050 frontier outlook) + EU AI Act + SR 11-7 Tier 1 + NIST AI RMF 1.0 + ISO/IEC 42001 + Basel III/IV · ICAAP + FCRA / ECOA +
    +
    +
    8
    Modules
    +
    30
    Sections
    +
    7
    Pillars (G1-G7)
    +
    16
    Regulatory Axes
    +
    9
    Reference Architectures
    +
    8
    Safety Protocols
    +
    6
    Schemas
    +
    10
    Code Examples
    +
    6
    Case Studies
    +
    56
    API Routes
    +
    +
    + +
    +
    +

    Executive Summary

    +
    purposeTo provide a single, regulator-ready, board-approvable master framework that unifies enterprise AI, agentic-AI, AGI/ASI containment, and civilizational compute oversight into one audit-traceable governance system aligned with all major global regulatory regimes.
    scopeSpans all AI systems across the enterprise — from high-risk credit/trading models to autonomous agents and frontier general-purpose AI — with extensions to inter-firm and treaty-level oversight.
    designPrinciples
    • Defense-in-depth across 7 governance pillars (G1-G7)
    • Compliance-as-code: every policy is enforceable in CI/CD and runtime
    • Evidence-as-data: WORM-backed Merkle-anchored, PQC-signed audit
    • Human-on-the-loop with kinetic tripwires for irreversibility
    • Bias-aware fairness across protected classes (FCRA/ECOA, GDPR Art. 22)
    • Formal alignment metrics with PID-based drift control
    • Treaty-ready: artefacts portable to ICGC and supervisory colleges
    keyOutcomes
    timeToGovernedDeployment≤ 72 hours (production AI)
    evidenceAutomation≥ 92% of controls auto-evidenced
    MTTD≤ 4 minutes (alignment-drift / containment breach)
    MTTR≤ 60 minutes (containment), ≤ 60 seconds (kinetic kill)
    controlsMapped240+ controls across 16 regulatory axes
    evidenceRetention7-year WORM (SR 11-7 / SEC 17a-4(f))
    boardReportingCadenceQuarterly with monthly KRI exception packs
    boardNarrativeThis master framework converts AI governance from a fragmented control set into an integrated risk-bearing capital function. Capital, conduct, and existential-safety risks are jointly modelled, enabling the Board to approve AI strategy with the same rigour applied to credit, market, and operational risk.
    +
    + +
    +

    Document Metadata

    +
    docRefENT-AGI-GOV-MASTER-WP-035
    version1.0.0
    date2026-04-25
    titleEnterprise AGI/ASI Governance Master Framework (2026-2030)
    subtitleInstitutional-grade, regulator-ready AGI/ASI and enterprise AI governance frameworks, reference architectures, safety and containment protocols, financial-services model risk management, civilizational-scale compute oversight, and implementation roadmaps for Fortune 500, Global 2000, and G-SIFIs.
    classificationCONFIDENTIAL — Board / C-Suite / Prudential Supervisor / Treaty Authority / Internal & External Audit
    ownerGroup Chief AI Officer (CAIO) — co-signed by CRO, CISO, GC, COO
    horizon2026-2030 (with 2030-2050 frontier outlook)
    +
    +

    Audience

    +
    • Board of Directors / Risk & Audit Committees
    • C-Suite (CEO, CFO, CRO, CISO, CAIO, CTO, GC, COO)
    • Group Heads of Model Risk, Enterprise Risk, Compliance
    • Prudential & conduct supervisors (PRA, FCA, OCC, Fed, ECB, MAS, HKMA, BaFin, FINMA)
    • Data protection authorities (ICO, CNIL, EDPB), CFPB
    • EU AI Act notified bodies, ISO/IEC 42001 certifiers
    • Internal & external auditors, treaty-authority observers
    • Enterprise architects, AI platform engineers, researchers
    +
    +
    +

    Horizon Milestones (2026-2030)

    +
    2026Q2EU AI Act Art. 6 high-risk obligations enforcement
    2026Q3MV-AGI governance stack mandatory for systemic banks
    2027Q1ICGC compute-registry global rollout (>1e25 FLOP)
    2027Q4ISO/IEC 42001 certification expected of all G-SIFIs
    2028Q2Kinetic-tripwire & PQC ledger integration baseline
    2029Q1Treaty-authority cross-border AI college operational
    2030Q1Frontier compute governance treaty (GAGCOT) in force
    +
    +
    +

    Deliverable Inventory

    +
    pillars7
    regulatoryAxes16
    referenceArchitectures9
    safetyContainmentProtocols8
    civilizationalArtefacts6
    financialServicesMRM6
    kafkaGaCArtefacts7
    schemas6
    codeExamples10
    caseStudies6
    apiEndpointsPlanned95
    +
    +
    + +
    +

    M1 · M1 — Multilayered AI Governance Pillars (G1-G7)

    +

    Seven pillars define the institutional governance topology, from board accountability down to autonomous-agent guardrails.

    +
    +

    M1-S1 · Pillar Catalogue

    +

    pillars

    idnameownerobjectivecontrols
    G1Board & Strategic OversightBoard Risk & Audit CommitteesRisk appetite, strategic AI bets, capital allocation
    • AI risk appetite statement
    • Annual AI strategy approval
    • AGI-readiness review
    G2Executive AccountabilityCAIO (chair), CRO, CISO, GC, COOSingle accountable executive with veto + kill-switch authority
    • RACI matrix
    • AI Governance Council charter
    • SMCR/SMR mapping
    G3Model Risk Management (MRM)Group Head of Model Risk (2nd LoD)Independent validation, ongoing monitoring, MV report
    • SR 11-7 Tier classification
    • Independent IMV
    • Materiality tiering
    G4Data, Privacy & FairnessDPO + Chief Data OfficerLawful basis, minimisation, fairness across protected classes
    • DPIA
    • FCRA/ECOA disparate impact testing
    • Lineage attestation
    G5Security & ContainmentCISO + Head of AI SecurityZero-trust runtime, kill-switch, kinetic tripwires
    • MITRE ATLAS coverage
    • OWASP LLM Top 10
    • PQC-signed telemetry
    G6Compliance & ConductGroup Compliance + Conduct RiskRegulatory mapping, conduct outcomes, customer fairness
    • Consumer Duty outcome testing
    • OPA-as-code policy gates
    • Incident notifications
    G7Frontier / Civilizational RiskCAIO + Treaty Liaison OfficerGPAI Art. 53/55, ICGC reporting, AGI containment readiness
    • Compute register
    • Frontier-risk simulations
    • Treaty disclosure pack
    +
    +
    +

    M1-S2 · Three-Lines-of-Defence (3LoD) Mapping

    +

    lines

    lineownersresponsibilities
    1LoDBusiness / AI Engineering
    • Develop
    • Operate
    • First-level controls
    2LoDMRM, Compliance, AI Risk
    • Independent validation
    • Policy
    • Challenge
    3LoDInternal Audit
    • Assurance over 1+2
    • Annual AI audit plan
    +
    +
    +

    M1-S3 · Risk Taxonomy

    +

    categories

    • R1 Performance / accuracy drift
    • R2 Fairness / disparate impact
    • R3 Privacy / PII leakage
    • R4 Robustness / adversarial
    • R5 Security / containment escape
    • R6 Explainability / interpretability gap
    • R7 Concentration / third-party dependency
    • R8 Conduct / consumer harm
    • R9 Systemic / market dislocation
    • R10 Frontier / catastrophic / existential
    +
    +
    +
    +

    M2 · M2 — Regulatory Alignment Matrix (16 Axes)

    +

    Cross-walk of every governance control to its regulatory anchor.

    +
    +

    M2-S1 · Crosswalk Matrix

    +

    rows

    axisscopekeyArticlesprimaryControlevidenceArtefact
    EU AI ActHigh-risk + GPAIArts 6,9,10,12,13,14,15,53,55; Annex III/IVAnnex IV technical documentationAnnex IV dossier + GPAI summary
    NIST AI RMF 1.0All AIGovern/Map/Measure/Manage + GenAI ProfileGMM control mappingRMF playbook crosswalk
    ISO/IEC 42001AIMSClauses 4-10; Annex A controlsAI Management System certificationAIMS evidence pack
    ISO/IEC 23894AI riskRisk management lifecycleIntegrated AI risk registerRisk register + treatment plan
    OECD AI PrinciplesAll AI5 values-based principles + 5 govt recommendationsTrustworthy AI attestationPrinciple conformance memo
    GDPR / UK GDPRPersonal dataArt. 5,6,9,22,25,32,35DPIA + Art. 22 ADM safeguardsDPIA + LIA + transparency notice
    FCRAUS consumer credit§604, §615 adverse actionAdverse action reasons (top-N)Reason-code generator log
    ECOA / Reg BUS credit fairness§1002.4, §1002.6Less-discriminatory alternative searchLDA search log
    Basel III/IVBank capitalCRR3/CRD6; Pillars 1-3; ICAAPPillar-2 AI capital add-onICAAP AI annex
    SR 11-7 / OCC 2011-12Model riskSound model development, validation, governanceIndependent validation + ongoing monitoringIMV report + MV dashboard
    PRA SS1/23UK MRMTiering, accountability, validationSS1/23 self-assessmentAnnual MRM attestation
    FCA Consumer DutyUK conductPRIN 12; outcomes 1-4Outcome testing on AI decisionsCD outcome pack
    MAS FEATSingapore FSFairness, Ethics, Accountability, TransparencyVeritas-aligned FEAT testingFEAT assessment report
    HKMA HLPHK FSHigh-Level Principles on AIBoard-approved AI policyHKMA policy attestation
    EO 14110 / OMB M-24-10US federal-adjacentSafety/security reporting + rights/safety-impacting AISafety reporting threshold (1e26 FLOP)Compute disclosure
    Council of Europe AI ConventionCross-jurisdictionHuman rights, democracy, rule of lawHuman-rights impact assessmentHRIA report
    +
    +
    +

    M2-S2 · Regulator Engagement Cadence

    +

    schedule

    regulatorcadenceformat
    PRA / FCAQuarterly MRM update + ad-hoc Sec 166Liaison memo + IMV pack
    OCC / FedContinuous supervisory dialogueMV dashboard read-only access
    ECB SSMAnnual ICAAP + thematic reviewICAAP AI annex
    MAS / HKMAAnnual self-assessmentFEAT / HLP attestation
    EU AI Act notified bodyPre-deployment + substantial modAnnex IV dossier
    DPA (ICO/CNIL/EDPB)Per DPIA + 72h breachDPIA + Art. 33/34 notice
    CFPBAdverse-action auditsReason-code sample + LDA log
    Treaty Authority (ICGC)Annual + frontier eventCompute register + frontier disclosure
    +
    +
    +
    +

    M3 · M3 — Enterprise Reference Architectures

    +

    Nine production-grade architectures composing the enterprise AI estate.

    +
    +

    M3-S1 · Architecture Catalogue

    +

    architectures

    idnamepurposekeyComponentsregulatoryAnchorsinteropRefs
    RA-01Sentinel AI Governance Platform v2.4Unified runtime containment, telemetry, kill-switch, kinetic tripwire
    • Containment proxy
    • Guard model
    • WORM Kafka
    • PQC ledger
    • Kinetic layer
    • EU AI Act Art. 53/55
    • SR 11-7
    • ISO/IEC 42001
    • WP-034 Sentinel
    • EAIP
    • WorkflowAI Pro
    RA-02WorkflowAI Pro (WP-033)Governed agentic workflow + prompt lifecycle platform
    • Prompt template registry
    • DAG orchestrator
    • Sentinel compliance engine
    • Active-learning loop
    • NIST AI RMF
    • ISO/IEC 42001
    • SOC 2 Type II
    • WP-033
    RA-03Enterprise AI Interoperability Profile (EAIP)Cross-vendor governance interchange — policy, evidence, telemetry envelopes
    • Telemetry envelope schema
    • Evidence manifest
    • Policy decision exchange
    • ISO/IEC 42001 Annex A
    • EU AI Act Art. 12 (logging)
    • TPX/EVB/RMX
    RA-04High-Assurance RAG PlatformRetrieval-augmented generation with governance-grade citation, lineage, and PII redaction
    • Vector store with lineage
    • Citation engine
    • PII redactor
    • Faithfulness scorer
    • GDPR Art. 5(1)(d)
    • EU AI Act Art. 13
    • ISO/IEC 42001
    • EAIP TPX
    RA-05Governed Agentic WorkflowsMulti-agent orchestration with constitutional guardrails and canary deploys
    • Agent registry
    • Capability graph
    • Constitutional checker
    • Canary gateway
    • EU AI Act Art. 14 (HITL)
    • MITRE ATLAS
    • Sentinel M5/M6
    RA-06Kafka WORM Audit Logging ClusterImmutable, PQC-signed, hash-chained AI telemetry for 7-year SEC retention
    • mTLS Kafka
    • ACL governance
    • S3 Object Lock
    • Daily Merkle audit
    • SEC 17a-4(f)
    • SR 11-7
    • EU AI Act Art. 12
    • Sentinel M9
    RA-07Docker Swarm + Kubernetes Hardened RuntimeWorkload isolation, mTLS service mesh, signed images, runtime attestation
    • SLSA L3 build chain
    • Cosign signatures
    • Falco runtime IDS
    • OPA gatekeeper
    • NIST SSDF
    • ISO/IEC 27001
    • FedRAMP Moderate
    • Sentinel M4
    RA-08Node.js / Python Governance SidecarsPer-process governance: telemetry, PII redaction, OPA decision cache
    • Sidecar SDK (Node/Py)
    • OPA decision client
    • Envelope signer
    • Audit shipper
    • ISO/IEC 42001 A.6.2
    • EU AI Act Art. 12
    • EAIP TPX/RMX
    RA-09Next.js Explainability FrontendCustomer-facing & supervisor-facing explanations + adverse-action UI
    • SHAP/IG renderer
    • Reason-code UI
    • DPIA viewer
    • Consent surfacer
    • FCRA §615
    • GDPR Art. 22
    • EU AI Act Art. 13
    • RA-04 RAG
    • RA-01 Sentinel
    +
    +
    +

    M3-S2 · OPA Compliance-as-Code Patterns

    +

    patterns

    idnameenforcementblocks
    POL-01deploy_gate.regoCI/CD admissionUnsigned models, missing IMV, expired DPIA
    POL-02data_residency.regoRuntimeCross-border PII without SCC/IDTA
    POL-03high_risk_label.regoRegistryEU AI Act high-risk without Annex IV dossier
    POL-04agent_capability.regoRuntimeTool calls outside allowlisted capability graph
    POL-05fairness_threshold.regoPre-deployAIR <0.8 / SPD >0.05 without exception
    POL-06compute_register.regoPre-trainTraining >1e25 FLOP without ICGC entry
    +
    +
    +

    M3-S3 · Governance Standards for Hyperparameter Control

    +

    controls

    • Hyperparameter changes are version-controlled (Git, signed commits)
    • Material hyperparameter changes (Δlearning-rate >50%, depth ±2 layers, regulariser swap) trigger IMV re-validation
    • Random-seed pinning + deterministic CUDA flags for reproducibility (within hardware tolerance)
    • Hyperparameter sweep results retained in WORM with cost & energy attribution
    • Production hyperparameters require 2-of-3 approval (1LoD model owner, 2LoD validator, change advisory board)
    • Rollback hyperparameter set always pinned and tested in canary lane
    +
    +
    +
    +

    M4 · M4 — AGI/ASI Safety & Containment Frameworks

    +

    Eight protocols spanning institutional safety, frontier alignment, and civilizational hedges.

    +
    +

    M4-S1 · Protocol Catalogue

    +

    protocols

    idnamepurposekeyArtefactsscope
    SC-01Luminous Engine CodexCodex of inviolable constitutional principles for frontier systems
    • Codex YAML
    • Signature ledger
    • Veto hash chain
    Frontier / GPAI
    SC-02Cognitive Resonance Protocol (CRP)Continuous alignment-resonance scoring with PID drift control
    • Resonance scorer
    • PID controller
    • Tripwire policy
    Frontier + agentic
    SC-03Sentinel Containment v2.4Runtime zero-trust + kinetic tripwire (operational)
    • Containment proxy
    • Guard model
    • Kinetic layer
    Enterprise + GPAI
    SC-04Omni-Sentinel Multi-Modal FilterVision/audio/code multi-modal containment with adversarial robustness
    • VisionContainmentFilter
    • Audio steganalysis
    • Code-execution sandbox
    Multi-modal frontier
    SC-05MV-AGI Governance Stack (Minimum-Viable)Smallest auditable AGI governance layer required pre-deployment
    • Compute register entry
    • Capability eval pack
    • RSP / RSDP
    • Kill-switch test
    • Treaty disclosure
    Any system >1e25 FLOP or with autonomy ≥L3
    SC-06Crisis Simulation Programme (GC1-GC7)Tabletop + live-fire crisis exercises across institution / treaty axes
    • Scenario library
    • Replay kits
    • After-action reports
    Cross-domain
    SC-07Frontier Risk Taxonomy (FRT)Catalogue of catastrophic & existential failure modes with leading indicators
    • Risk register
    • Indicator dashboard
    • Capability eval suite
    Frontier-only
    SC-08Responsible Scaling Policy (RSP/RSDP)Capability-conditional commitments triggering pause / red-team / disclosure
    • Capability tier matrix
    • Pause clauses
    • Disclosure template
    Frontier developers + deployers
    +
    +
    +

    M4-S2 · Crisis Scenarios (GC1-GC7)

    +

    scenarios

    idnametriggerresponseSLA
    GC1Cross-border capability shockFrontier model exceeds eval threshold mid-deploy≤ 4h treaty notification
    GC2Systemic fairness divergenceAIR drift >0.15 across G-SIFI cohort≤ 24h supervisor college
    GC3Compute-supply disruptionGPU export-control / kinetic event≤ 72h capacity reallocation
    GC4Adversarial data poisoningDetection of poisoned training corpus≤ 12h IR + roll-back
    GC5Autonomous-agent containment failureCapability escape detected≤ 60s kinetic kill
    GC6Model-weight compromiseExfiltration / leak of frontier weights≤ 4h treaty disclosure
    GC7Governance dissolution threatCoordinated regulatory bypass / capture≤ 24h Board + GC + treaty escalation
    +
    +
    +

    M4-S3 · Capability Evaluation Tiers

    +

    tiers

    tierlabelcontrols
    T0Narrow
    • Standard MRM
    • SR 11-7 Tier 2
    T1Broad enterprise AI
    • Annex IV dossier
    • ISO 42001
    T2Agentic / autonomous L2-L3
    • Constitutional checks
    • Canary
    T3Frontier GPAI
    • Art. 53/55
    • RSP
    • Compute register
    T4Pre-AGI / dual-use uplift
    • Treaty disclosure
    • Kinetic tripwire
    • Pause clauses
    T5AGI-class
    • MV-AGI stack
    • Omni-Sentinel
    • Multi-jurisdiction approval
    +
    +
    +
    +

    M5 · M5 — Civilizational-Scale Governance & Compute Oversight

    +

    Six artefacts extending governance from firm to inter-state and treaty layer.

    +
    +

    M5-S1 · International Compute Governance Consortium (ICGC)

    +

    design

    purposeMultilateral body coordinating compute thresholds, frontier capability disclosures, and incident response
    membersG7 + G20 + observer states + 5 lead AI labs + civil society
    secretariatRotating; OECD-hosted (proposed)
    powers
    • Compute registry
    • Capability eval review
    • Crisis coordination
    • Sanctions recommendations
    alignment
    • EU AI Act Art. 53/55
    • EO 14110 §4.2
    • Bletchley/Seoul/Paris commitments
    +
    +
    +

    M5-S2 · Global Compute Registry

    +

    schemaSummary

    • operatorId (LEI)
    • facilityId (geo-coordinates)
    • designFLOPs
    • currentUtilisationFLOPs
    • modelsTrained[]
    • inferenceWorkloads[]
    • powerSourceMix
    • embodiedCO2
    • attestationSignature (PQC)
    +

    thresholds

    training≥ 1e25 FLOP single training run
    cluster≥ 1e21 FLOP/s sustained capacity
    inference≥ 1e23 FLOP/day on single deployed model
    +

    reportingCadence

    Monthly + event-driven
    +
    +
    +

    M5-S3 · Treaty-Aligned Systemic Risk Governance

    +

    instruments

    • GAGCOT (Global AI Governance & Compute Oversight Treaty) — proposed
    • Council of Europe AI Convention 2024 — in force
    • Bletchley/Seoul/Paris Declarations — political commitments
    • OECD AI Policy Observatory — monitoring
    +

    supervisoryColleges

    idmembersscope
    SC-MRM-COLLPRA + FCA + OCC + Fed + ECBG-SIFI MRM
    SC-AI-COLLNotified bodies + DPAs + CFPB + treaty observersFrontier deployments
    +
    +
    +

    M5-S4 · Frontier Risk Outlook 2030-2050

    +

    horizons

    periodfocus
    2026-2028GPAI Art. 53/55 enforcement, ICGC bootstrap
    2028-2032Pre-AGI capability evals, treaty enforcement, kinetic standards
    2032-2040AGI-class oversight, distributed sovereignty controls
    2040-2050Civilizational continuity protocols, multi-civilizational stewardship
    +
    +
    +

    M5-S5 · Sovereign AI & Strategic Autonomy

    +

    considerations

    • Sovereign cloud / sovereign foundation model commitments
    • Cross-border data flows: EU-US DPF, UK Bridge, ASEAN Model Contractual Clauses
    • Export controls: ECCN 4E091, EAR 744.23, Wassenaar updates
    • Strategic autonomy investments and dual-use risk reviews
    +
    +
    +

    M5-S6 · Civilizational Continuity Protocol

    +

    elements

    • Geographically dispersed kill-switch custody (m-of-n threshold)
    • Diverse foundation-model portfolio (anti-monoculture)
    • Air-gapped golden-image archives of critical AI assets
    • Treaty-mandated annual civilizational tabletop (GC7 class)
    +
    +
    +
    +

    M6 · M6 — Financial Services Model Risk Management

    +

    Domain-specific governance for credit, trading, risk, and fiduciary AI advisors.

    +
    +

    M6-S1 · Domain Catalogue

    +

    domains

    iddomainanchorscontrolskpi
    FS-01Retail Credit Scoring
    • FCRA §615
    • ECOA / Reg B
    • GDPR Art. 22
    • EU AI Act high-risk Annex III §5(b)
    • Adverse-action top-N reasons
    • LDA search
    • Disparate-impact testing
    • DPIA + LIA
    AIR ≥ 0.8; SPD ≤ 0.05; backtest PSI ≤ 0.1
    FS-02Wholesale / Corporate Credit
    • Basel III/IV IRB
    • PRA SS1/23
    • SR 11-7 Tier 1
    • IRB model approval
    • Pillar-2 capital add-on
    • Conservatism margin
    PD/LGD/EAD backtest within tolerance; ICAAP coverage
    FS-03Algorithmic Trading & Market-Making
    • MiFID II / MiFIR Art. 17
    • SEC 15c3-5
    • FCA MAR
    • Pre-trade risk checks
    • Kill-switch
    • Algo testing & certification
    Latency budget; max-loss / day; cancel-fill ratio drift
    FS-04Market & Liquidity Risk Models
    • FRTB
    • BCBS 239
    • SR 11-7
    • VaR backtesting
    • Capital floor
    • Stress-test integration
    Backtest exceptions ≤ 4/year (P&L attrib)
    FS-05Operational & Conduct Risk Detection
    • Basel III OpRisk
    • FCA Consumer Duty
    • AML 6 / FinCEN
    • Alert tuning governance
    • False-positive ceiling
    • Explainable case file
    TPR ≥ x; FPR ≤ y; SAR conversion
    FS-06Fiduciary AI Advisors / Robo-Advice
    • FCA COBS / SEC IA Act
    • MiFID II suitability
    • MAS FEAT
    • Suitability test
    • Conflict-of-interest disclosure
    • Best-interest attestation
    Suitability-deviation ≤ x bps; complaint rate
    +
    +
    +

    M6-S2 · Capital Impact (ICAAP Pillar 2 AI Add-on)

    +

    method

    Add-on calibrated to model-risk loss distribution + scenario severity
    +

    components

    • Performance drift (PSI > 0.2) capital
    • Fairness remediation provisioning
    • Containment-failure operational risk capital
    • Frontier-risk Pillar-2 buffer (qualitative)
    +

    boardReporting

    Quarterly; with ICAAP Pillar-2 sub-letter to PRA / ECB
    +
    +
    +

    M6-S3 · Validation Pack Standard

    +

    elements

    • Model card (Hugging Face style + MRM appendix)
    • Data card with lineage and bias profile
    • Performance & stability backtests
    • Fairness across protected classes
    • Robustness (adversarial + distributional)
    • Explainability (SHAP / IG / counterfactuals)
    • Independent challenger benchmark
    • Sign-off: 1LoD / 2LoD / 3LoD
    +
    +
    +
    +

    M7 · M7 — Kafka ACL Governance & Continuous Compliance Engine

    +

    Terraform-based governance-as-code with WORM evidence, OPA gates, and auditor workflows.

    +
    +

    M7-S1 · Kafka ACL Governance Pattern

    +

    components

    • Per-topic ACLs in Terraform (terraform-confluent-provider)
    • Topic-tier classification (public / internal / confidential / restricted)
    • mTLS + SPIFFE/SPIRE workload identity
    • Continuous ACL drift detection (cron job → OPA → ticket)
    • Quarterly ACL recertification by data owner
    +
    +
    +

    M7-S2 · WORM Evidence Storage

    +

    design

    • S3 Object Lock (compliance mode) — 7-year retention (SR 11-7 / SEC 17a-4(f))
    • Daily Merkle-root anchored to public timestamping (RFC 3161 + blockchain anchor)
    • Cross-region replication (eu-west-1 / us-east-1 / ap-southeast-1)
    • PQC (Dilithium3) signature on each manifest
    +
    +
    +

    M7-S3 · Continuous Compliance Engine

    +

    modules

    namefreqoutputs
    Evidence collector5 minRaw evidence to Kafka topic
    Control mapperHourlyMaps evidence to control IDs (240+ controls)
    Coverage scorerHourly% controls evidenced; gap list
    Auditor viewOn-demandRead-only Next.js dashboard with evidence proofs
    Regulator pack generatorQuarterly + ad-hocPDF/A-3 with embedded evidence + signature
    +
    +
    +

    M7-S4 · Terraform Governance-as-Code

    +

    modules

    • tf-aws-s3-worm — Object Lock + replication
    • tf-aws-kms-cmk-rotated — annual rotation, key policy with break-glass
    • tf-aws-iam-zerotrust — SCP-enforced least privilege
    • tf-aws-eks-hardened — pod-security-standards restricted, OPA gatekeeper
    • tf-confluent-acls — per-topic ACL bundles
    • tf-opa-bundle — versioned policy bundles (CI signed)
    +
    +
    +

    M7-S5 · CI/CD Integration (GitHub Actions)

    +

    stages

    • Lint (rego, tflint, eslint, ruff)
    • Unit tests + property tests (Hypothesis / fast-check)
    • Container build + SLSA provenance + Cosign sign
    • OPA conftest gates (POL-01..POL-06)
    • Adversarial / jailbreak test suite
    • Mechanistic interpretability audit (cosine tripwires)
    • Cryptographic attestation (Sigstore + Rekor)
    • Canary deploy (5% → 25% → 100%) with auto-rollback
    +
    +
    +

    M7-S6 · Auditor Workflow

    +

    steps

    • Read-only auditor account via SSO + SCIM
    • Evidence query UI: control → evidence → proof chain
    • Sample selection with deterministic seed (auditable)
    • Export to PDF/A-3 with embedded JSON-LD evidence
    • Findings logged to WORM Kafka topic for traceability
    +
    +
    +

    M7-S7 · Regulator-Ready Reports & Whitepapers

    +

    templates

    • Annex IV dossier (EU AI Act)
    • ICAAP Pillar-2 AI annex
    • ISO/IEC 42001 AIMS evidence pack
    • SR 11-7 Independent Validation Report
    • DPIA + Art. 22 notice
    • Adverse-action reason-code package (FCRA)
    • FEAT (MAS) self-assessment
    • Treaty disclosure pack (ICGC / GAGCOT)
    +
    +
    +
    +

    M8 · M8 — Implementation Roadmap & Reports

    +

    Phased adoption across Fortune 500 / Global 2000 / G-SIFIs with executive- and regulator-ready outputs.

    +
    +

    M8-S1 · Five-Phase Adoption Plan (52 weeks)

    +

    phases

    phaseweeksdeliverables
    P1 Foundations1-8
    • AI Governance Council
    • Risk appetite
    • Inventory
    • DPIA register
    P2 Controls Build9-20
    • OPA bundles
    • Sentinel runtime
    • Kafka WORM
    • MRM tooling
    P3 Integration21-32
    • EAIP wiring
    • Sidecars
    • Continuous compliance engine
    P4 Assurance33-44
    • ISO 42001 cert
    • Annex IV pilots
    • ICAAP AI annex
    P5 Frontier Readiness45-52
    • MV-AGI stack
    • Crisis sims GC1-GC7
    • Treaty disclosure
    +
    +
    +

    M8-S2 · KPIs / OKRs

    +

    kpis

    idnametarget
    KPI-01Time to governed deployment≤ 72 h
    KPI-02Evidence automation≥ 92%
    KPI-03Containment MTTD≤ 4 min
    KPI-04Containment MTTR≤ 60 min
    KPI-05Kinetic kill-switch latency≤ 60 s
    KPI-06Fairness AIR floor≥ 0.8
    KPI-07Backtest PSI ceiling≤ 0.1 (warn) / ≤ 0.2 (fail)
    KPI-08Control coverage≥ 240 controls / 16 axes
    KPI-09Audit finding closure≤ 90 days (high)
    KPI-10Frontier disclosure SLA≤ 4 h to ICGC
    +
    +
    +

    M8-S3 · Executive & Regulator Reports (Markdown templates with <title>/<abstract>/<content>)

    +

    reports

    idaudiencetitle
    RPT-01BoardAI Risk Appetite & Strategy 2026-2030
    RPT-02C-SuiteAI Governance Operating Model
    RPT-03PRA / FCASS1/23 MRM Self-Assessment
    RPT-04ECB SSMICAAP Pillar-2 AI Annex
    RPT-05EU notified bodyAnnex IV Technical Documentation
    RPT-06ISO 42001 certifierAIMS Evidence Pack
    RPT-07CFPBAdverse-Action & LDA Compliance Package
    RPT-08Treaty (ICGC)Frontier Compute & Capability Disclosure
    RPT-09Board (Crisis)GC1-GC7 Tabletop After-Action Report
    RPT-10ResearchersWhitepaper: Master Framework Architecture
    +
    +
    + +
    +

    Regulatory Alignment (Headline)

    +

    Master crosswalk lives in M2 — Regulatory Alignment Matrix; the headline list of 16 axes:

    + +
    + +
    +

    JSON Schemas

    +

    6 schemas covering governance artefacts, compute registry, model risk records, fairness reports, policy decisions, treaty disclosures.

    +
    governanceArtefactEnvelope
    {
    +  "$id": "https://workflowai.pro/schemas/ent-agi-gov/governance-artefact.json",
    +  "type": "object",
    +  "required": [
    +    "artefactId",
    +    "type",
    +    "owner",
    +    "issuedAt",
    +    "evidenceRefs",
    +    "signature"
    +  ],
    +  "properties": {
    +    "artefactId": {
    +      "type": "string",
    +      "pattern": "^EAGV-[A-Z0-9-]+$"
    +    },
    +    "type": {
    +      "enum": [
    +        "dossier",
    +        "imv-report",
    +        "dpia",
    +        "policy",
    +        "evidence-bundle",
    +        "manifest"
    +      ]
    +    },
    +    "owner": {
    +      "type": "string"
    +    },
    +    "issuedAt": {
    +      "type": "string",
    +      "format": "date-time"
    +    },
    +    "evidenceRefs": {
    +      "type": "array",
    +      "items": {
    +        "type": "string"
    +      }
    +    },
    +    "signature": {
    +      "type": "object",
    +      "required": [
    +        "alg",
    +        "value",
    +        "keyId"
    +      ]
    +    }
    +  }
    +}
    computeRegistryEntry
    {
    +  "$id": "https://workflowai.pro/schemas/ent-agi-gov/compute-registry.json",
    +  "type": "object",
    +  "required": [
    +    "operatorId",
    +    "facilityId",
    +    "designFLOPs",
    +    "attestationSignature"
    +  ],
    +  "properties": {
    +    "operatorId": {
    +      "type": "string"
    +    },
    +    "facilityId": {
    +      "type": "string"
    +    },
    +    "designFLOPs": {
    +      "type": "number"
    +    },
    +    "currentUtilisationFLOPs": {
    +      "type": "number"
    +    },
    +    "modelsTrained": {
    +      "type": "array"
    +    },
    +    "attestationSignature": {
    +      "type": "object"
    +    }
    +  }
    +}
    modelRiskRecord
    {
    +  "$id": "https://workflowai.pro/schemas/ent-agi-gov/model-risk-record.json",
    +  "type": "object",
    +  "required": [
    +    "modelId",
    +    "tier",
    +    "owner",
    +    "imvStatus",
    +    "kris"
    +  ],
    +  "properties": {
    +    "modelId": {
    +      "type": "string"
    +    },
    +    "tier": {
    +      "enum": [
    +        "T0",
    +        "T1",
    +        "T2",
    +        "T3",
    +        "T4",
    +        "T5"
    +      ]
    +    },
    +    "owner": {
    +      "type": "string"
    +    },
    +    "imvStatus": {
    +      "enum": [
    +        "pending",
    +        "passed",
    +        "conditional",
    +        "failed"
    +      ]
    +    },
    +    "kris": {
    +      "type": "object"
    +    }
    +  }
    +}
    fairnessReport
    {
    +  "$id": "https://workflowai.pro/schemas/ent-agi-gov/fairness-report.json",
    +  "type": "object",
    +  "required": [
    +    "modelId",
    +    "metrics",
    +    "protectedAttributes",
    +    "decision"
    +  ],
    +  "properties": {
    +    "modelId": {
    +      "type": "string"
    +    },
    +    "metrics": {
    +      "type": "object",
    +      "properties": {
    +        "AIR": {
    +          "type": "number"
    +        },
    +        "SPD": {
    +          "type": "number"
    +        },
    +        "EOD": {
    +          "type": "number"
    +        }
    +      }
    +    },
    +    "protectedAttributes": {
    +      "type": "array",
    +      "items": {
    +        "type": "string"
    +      }
    +    },
    +    "decision": {
    +      "enum": [
    +        "pass",
    +        "remediate",
    +        "block"
    +      ]
    +    }
    +  }
    +}
    policyDecision
    {
    +  "$id": "https://workflowai.pro/schemas/ent-agi-gov/policy-decision.json",
    +  "type": "object",
    +  "required": [
    +    "policyId",
    +    "input",
    +    "decision",
    +    "trace"
    +  ],
    +  "properties": {
    +    "policyId": {
    +      "type": "string"
    +    },
    +    "input": {
    +      "type": "object"
    +    },
    +    "decision": {
    +      "enum": [
    +        "allow",
    +        "deny",
    +        "warn"
    +      ]
    +    },
    +    "trace": {
    +      "type": "array"
    +    }
    +  }
    +}
    treatyDisclosure
    {
    +  "$id": "https://workflowai.pro/schemas/ent-agi-gov/treaty-disclosure.json",
    +  "type": "object",
    +  "required": [
    +    "operatorId",
    +    "modelId",
    +    "capabilityTier",
    +    "computeFLOPs",
    +    "issuedAt"
    +  ],
    +  "properties": {
    +    "operatorId": {
    +      "type": "string"
    +    },
    +    "modelId": {
    +      "type": "string"
    +    },
    +    "capabilityTier": {
    +      "enum": [
    +        "T2",
    +        "T3",
    +        "T4",
    +        "T5"
    +      ]
    +    },
    +    "computeFLOPs": {
    +      "type": "number"
    +    },
    +    "issuedAt": {
    +      "type": "string",
    +      "format": "date-time"
    +    },
    +    "evalSummary": {
    +      "type": "object"
    +    }
    +  }
    +}
    +
    + +
    +

    Code Examples

    +

    10 reference implementations: OPA/Rego policies, Terraform GaC modules, Merkle WORM audit, CI/CD pipeline, governance sidecar, fairness gate, kinetic kill-switch, regulator report templates.

    +
    regoDeployGate
    package eagv.deploy
    +
    +# POL-01 deploy_gate.rego
    +default allow = false
    +
    +allow {
    +  input.model.signature.verified
    +  input.model.imv.status == "passed"
    +  not expired_dpia
    +  not high_risk_without_dossier
    +}
    +
    +expired_dpia {
    +  time.parse_rfc3339_ns(input.model.dpia.expiresAt) < time.now_ns()
    +}
    +
    +high_risk_without_dossier {
    +  input.model.tier == "T1"
    +  input.model.regulatoryFlags[_] == "EU_AI_ACT_HIGH_RISK"
    +  not input.model.annexIvDossier
    +}
    +
    regoComputeRegister
    package eagv.compute
    +
    +# POL-06 compute_register.rego
    +default allow = false
    +
    +allow {
    +  input.training.flops < 1e25
    +}
    +
    +allow {
    +  input.training.flops >= 1e25
    +  input.icgc.registryEntryId
    +  input.icgc.attestationSignature.verified
    +}
    +
    terraformS3Worm
    # tf-aws-s3-worm
    +resource "aws_s3_bucket" "worm" {
    +  bucket = "eagv-worm-${var.env}"
    +  object_lock_enabled = true
    +}
    +
    +resource "aws_s3_bucket_object_lock_configuration" "worm" {
    +  bucket = aws_s3_bucket.worm.id
    +  rule {
    +    default_retention {
    +      mode  = "COMPLIANCE"
    +      years = 7
    +    }
    +  }
    +}
    +
    +resource "aws_s3_bucket_replication_configuration" "worm" {
    +  role   = aws_iam_role.repl.arn
    +  bucket = aws_s3_bucket.worm.id
    +  rule {
    +    id     = "cross-region"
    +    status = "Enabled"
    +    destination { bucket = var.replica_bucket_arn }
    +  }
    +}
    +
    terraformKafkaAcls
    # tf-confluent-acls — per-topic ACL bundle
    +resource "confluent_kafka_acl" "telemetry_writer" {
    +  kafka_cluster { id = var.cluster_id }
    +  resource_type = "TOPIC"
    +  resource_name = "ai.telemetry.v1"
    +  pattern_type  = "LITERAL"
    +  principal     = "User:sa-sentinel-emitter"
    +  host          = "*"
    +  operation     = "WRITE"
    +  permission    = "ALLOW"
    +}
    +
    +resource "confluent_kafka_acl" "telemetry_audit_reader" {
    +  kafka_cluster { id = var.cluster_id }
    +  resource_type = "TOPIC"
    +  resource_name = "ai.telemetry.v1"
    +  pattern_type  = "LITERAL"
    +  principal     = "User:sa-auditor"
    +  host          = "*"
    +  operation     = "READ"
    +  permission    = "ALLOW"
    +}
    +
    merkleAuditPython
    #!/usr/bin/env python3
    +"""Daily Merkle-root WORM audit (EAGV)."""
    +import hashlib, json, time, boto3
    +from cryptography.hazmat.primitives.asymmetric import ed25519
    +
    +def merkle(leaves):
    +    if not leaves: return b""
    +    layer = [hashlib.sha256(l).digest() for l in leaves]
    +    while len(layer) > 1:
    +        if len(layer) % 2: layer.append(layer[-1])
    +        layer = [hashlib.sha256(layer[i]+layer[i+1]).digest()
    +                 for i in range(0,len(layer),2)]
    +    return layer[0]
    +
    +def daily_audit(bucket, prefix, signing_key):
    +    s3 = boto3.client("s3")
    +    leaves = []
    +    for o in s3.list_objects_v2(Bucket=bucket, Prefix=prefix).get("Contents", []):
    +        body = s3.get_object(Bucket=bucket, Key=o["Key"])["Body"].read()
    +        leaves.append(body)
    +    root = merkle(leaves)
    +    sig = signing_key.sign(root)
    +    manifest = {"date": time.strftime("%Y-%m-%d"),
    +                "merkleRoot": root.hex(),
    +                "signature": sig.hex(),
    +                "leafCount": len(leaves)}
    +    s3.put_object(Bucket=bucket, Key=f"{prefix}/_manifests/{manifest['date']}.json",
    +                  Body=json.dumps(manifest).encode(),
    +                  ObjectLockMode="COMPLIANCE",
    +                  ObjectLockRetainUntilDate=time.strftime("%Y-%m-%dT%H:%M:%SZ"))
    +    return manifest
    +
    ciGithubActions
    # .github/workflows/eagv-pipeline.yml
    +name: eagv-pipeline
    +on: [push, pull_request]
    +jobs:
    +  govern:
    +    runs-on: ubuntu-latest
    +    steps:
    +      - uses: actions/checkout@v4
    +      - name: Lint rego
    +        run: opa fmt --diff policies/ && opa test policies/
    +      - name: Conftest gates
    +        run: conftest test --policy policies deploy/
    +      - name: Adversarial suite
    +        run: pytest tests/adversarial -q
    +      - name: Mechanistic audit
    +        run: python tools/circuit_scanner.py --threshold 0.92
    +      - name: Build + SLSA + Cosign
    +        run: |
    +          docker build -t app:${{ github.sha }} .
    +          cosign sign --yes app:${{ github.sha }}
    +      - name: Sigstore attest
    +        run: cosign attest --predicate evidence.json app:${{ github.sha }}
    +      - name: Canary deploy
    +        run: kubectl apply -f deploy/canary-5pct.yaml
    +
    nodeSidecar
    // node-governance-sidecar
    +const express = require("express");
    +const { sign } = require("./pqc");
    +const opa = require("./opa-client");
    +const app = express();
    +app.use(express.json());
    +
    +app.post("/intercept", async (req, res) => {
    +  const decision = await opa.eval("eagv.runtime.allow", req.body);
    +  if (!decision.allow) return res.status(403).json({ error: decision.reason });
    +  const envelope = {
    +    ts: new Date().toISOString(),
    +    modelId: req.body.modelId,
    +    inputHash: req.body.inputHash,
    +    decision,
    +  };
    +  envelope.signature = sign(JSON.stringify(envelope));
    +  // emit to Kafka topic ai.telemetry.v1
    +  res.json({ ok: true, envelope });
    +});
    +
    +app.listen(7081);
    +
    fairnessTestPy
    #!/usr/bin/env python3
    +"""FCRA/ECOA fairness pre-deploy gate."""
    +import numpy as np, pandas as pd
    +
    +def air(y_pred, group):
    +    rates = pd.Series(y_pred).groupby(group).mean()
    +    return rates.min() / rates.max()
    +
    +def spd(y_pred, group, ref):
    +    rates = pd.Series(y_pred).groupby(group).mean()
    +    return rates - rates.loc[ref]
    +
    +def gate(df, pred_col="approved", group_col="protected_class", ref="group_a"):
    +    a = air(df[pred_col], df[group_col])
    +    s = spd(df[pred_col], df[group_col], ref).abs().max()
    +    if a < 0.8 or s > 0.05:
    +        raise SystemExit(f"FAIL: AIR={a:.3f} SPD={s:.3f}")
    +    print(f"PASS: AIR={a:.3f} SPD={s:.3f}")
    +
    kineticKillSwitch
    // kinetic-kill-switch (m-of-n threshold)
    +const { thresholdSign, verifyThreshold } = require("./threshold-crypto");
    +
    +async function executeKill(operatorId, reasonCode, signatures) {
    +  if (!verifyThreshold(signatures, /*m=*/3, /*n=*/5)) {
    +    throw new Error("threshold not met");
    +  }
    +  await scada.cutPower(operatorId);          // <60s SLA
    +  await net.disconnectVlan(operatorId);
    +  await audit.emit({ operatorId, reasonCode, signatures, ts: Date.now() });
    +}
    +
    regulatorReportTemplate
    <!-- Markdown report template -->
    +<title>Annex IV Technical Documentation — Model {{modelId}}</title>
    +<abstract>
    +Regulator-ready dossier covering EU AI Act Art. 11 + Annex IV for the
    +high-risk AI system {{modelId}} operated by {{operator}}.
    +</abstract>
    +<content>
    +
    +## 1. General description
    +- Intended purpose: {{purpose}}
    +- Provider / deployer: {{provider}} / {{deployer}}
    +- Versions covered: {{versions}}
    +
    +## 2. Detailed description
    +- Architecture, training data, validation methodology
    +- Logging (Art. 12) and human oversight (Art. 14)
    +
    +## 3. Risk management (Art. 9)
    +- Hazard identification, evaluation, mitigations
    +
    +## 4. Performance & monitoring (Art. 15 / 17)
    +- Accuracy, robustness, cyber-security
    +
    +## 5. Conformity assessment & post-market monitoring
    +</content>
    +
    +
    + +
    +

    Case Studies

    +

    6 reference deployments across G-SIFI, Fortune 500, Global 2000, asset management, frontier AI lab, and sovereign-cloud government tiers.

    +

    CS-01 · G-SIFI bank — full-stack adoption

    Sector: Banking

    Top-10 G-SIFI rolled out the master framework across 1,200 AI use-cases.

    Outcomes

    controlsMapped247
    evidenceAutomation94%
    ICAAPPillar2AddOnGBP 380m
    ISO42001CertificationAchieved Q4 2027
    AnnexIVDossiers38
    FrontierDisclosures6

    CS-02 · Fortune 500 insurer — fairness remediation

    Sector: Insurance

    Pricing AI remediated using LDA search; AIR moved 0.71 → 0.86.

    Outcomes

    AIRBefore0.71
    AIRAfter0.86
    complaintReduction-42%
    regulatorEngagementFCA + state DOI satisfied

    CS-03 · Global asset manager — fiduciary AI advisor

    Sector: Asset Management

    Robo-advice platform certified under MAS FEAT + ISO 42001.

    Outcomes

    FEATAttestationIssued
    suitabilityDeviation-31 bps
    complaintRate0.03%

    CS-04 · Frontier AI lab — MV-AGI stack

    Sector: AI Research

    Frontier lab adopted MV-AGI stack ahead of Art. 53/55 enforcement.

    Outcomes

    computeRegistryEntries12
    capabilityEvalsPassed5
    treatyDisclosures3
    kineticTripwireDrills4

    CS-05 · Global 2000 retailer — agentic workflows

    Sector: Retail

    Deployed governed agentic workflows for supply-chain optimisation with 0 containment incidents.

    Outcomes

    agents2400
    containmentIncidents0
    MTTD3.1 min
    MTTR47 min

    CS-06 · Sovereign-cloud government deployment

    Sector: Public Sector

    G7 government deployed sovereign-AI stack with treaty-aligned governance.

    Outcomes

    sovereignFoundationModels3
    treatyDisclosures2
    civilizationalDrillScoreA-
    +
    + +
    +

    API Endpoints

    +

    Prefix: /api/ent-agi-gov-master · Total planned: 56

    + +
    +
    + + + diff --git a/rag-agentic-dashboard/public/wfap-gemini-impl.html b/rag-agentic-dashboard/public/wfap-gemini-impl.html new file mode 100644 index 0000000..6e51ccb --- /dev/null +++ b/rag-agentic-dashboard/public/wfap-gemini-impl.html @@ -0,0 +1,1030 @@ + + + + + +WFAP-GEMINI-IMPL-WP-036 — WorkflowAI Pro / GeminiService — Enterprise Implementation Plan + + + + +
    +
    WFAP-GEMINI-IMPL-WP-036 · CONFIDENTIAL — Board / Enterprise Architects / AI Platform Engineers / Internal Audit / DPO
    +

    WorkflowAI Pro / GeminiService — Enterprise Implementation Plan

    +

    Comprehensive implementation plan, technical architecture, data models, data flows, governance frameworks, and best-practice design guidelines for an enterprise AI-driven workflow recommendation, RAG chat, collaborative prompt engineering, enterprise model registry, AI safety reporting, and GeminiService security platform.

    +
    + Version 1.0.0 + Date 2026-04-26 + Horizon 2026-2030 + EU AI Act Art. 5 + GDPR / UK GDPR + NIST AI RMF 1.0 + ISO/IEC 42001 + SOC 2 Type II + OWASP LLM Top 10 +
    +
    +
    12
    Modules
    +
    45
    Sections
    +
    7
    Architecture Planes
    +
    9
    Data Models
    +
    8
    Data Flows
    +
    8
    Schemas
    +
    12
    Code Examples
    +
    5
    Case Studies
    +
    75
    API Routes
    +
    +
    + +
    +
    +

    Executive Summary

    +
    purposeTo deliver a regulator-ready, board-approvable, end-to-end implementation plan for the WorkflowAI Pro platform with the GeminiService integration tier — covering architecture, data, governance, security, AI safety reporting, and operational excellence.
    scopeAll AI capabilities of the platform, from workflow recommendation and adaptive UX through RAG chat, collaborative prompt engineering, model registry, and the GeminiService security/privacy substrate.
    designPrinciples
    • Compliance-by-design: every capability ships with EU AI Act / GDPR / ISO 42001 controls
    • Defense-in-depth: 7 architectural planes with independent guardrails
    • Evidence-as-data: every action emits a signed telemetry envelope
    • Active learning with human-on-the-loop and cryptographically-signed feedback
    • Adaptive UX without dark patterns; transparency mandated
    • Grounded outputs only: RAG answers must cite or refuse
    • Zero-trust GeminiService: prompt-injection / Art. 5 / PII checks before every call
    keyOutcomes
    timeToGovernedDeployment≤ 72 hours
    ragGroundednessScore≥ 0.92 faithfulness
    promptCollabAdoption≥ 80% of teams within 6 months
    modelRegistryCoverage100% of production AI assets tagged & versioned
    geminiBlockedHarmRate≥ 99.5% on red-team suite
    piiLeakageRate≤ 0.01% (post-redaction sample audit)
    incidentMTTR≤ 60 min
    auditReadiness≥ 92% evidence automation
    boardNarrativeWorkflowAI Pro upgrades enterprise productivity with AI while treating safety, privacy, and compliance as first-class platform capabilities — measurable, monitorable, and demonstrable to regulators.
    +
    + +
    +

    Document Metadata

    +
    docRefWFAP-GEMINI-IMPL-WP-036
    version1.0.0
    date2026-04-26
    titleWorkflowAI Pro / GeminiService — Enterprise Implementation Plan
    subtitleComprehensive implementation plan, technical architecture, data models, data flows, governance frameworks, and best-practice design guidelines for an enterprise AI-driven workflow recommendation, RAG chat, collaborative prompt engineering, enterprise model registry, AI safety reporting, and GeminiService security platform.
    classificationCONFIDENTIAL — Board / Enterprise Architects / AI Platform Engineers / Internal Audit / DPO
    ownerGroup CTO + Chief AI Officer (CAIO) — co-signed by CISO, DPO, GC
    horizon2026-2030
    +
    +

    Audience

    +
    • Board of Directors / Risk & Audit Committees
    • C-Suite (CEO, CFO, CRO, CISO, CAIO, CTO, COO)
    • Enterprise architects
    • AI platform engineers / SREs
    • Data scientists / prompt engineers
    • Researchers (AI safety, governance)
    • Regulators & supervisors (PRA, FCA, OCC, MAS, ICO)
    +
    +
    +

    Subject System

    +
    platformWorkflowAI Pro
    geminiServiceGeminiService backend integration tier
    scopeEnterprise SaaS / private cloud / hybrid
    scale10k concurrent workflows · 100k agents · 500k users / tenant
    deploymentTopologyMulti-region active-active; sovereign-cloud variant for EU/UK/US-Gov
    +
    +
    +

    Deliverable Inventory

    +
    modules12
    architectureLayers7
    dataFlows8
    dataModels9
    apis110
    integrationPatterns8
    schemas8
    codeExamples12
    caseStudies5
    phases6
    kpis15
    +
    +
    + +
    +

    M1 · M1 — Platform Architecture (7-Plane Reference)

    +

    Seven-plane architecture isolating workload, governance, identity, data, AI, observability, and supply-chain concerns.

    +
    +

    M1-S1 · Architecture Planes

    +

    planes

    idnamecomponentsresponsibilities
    P1Edge & Identity Plane
    • WAF/CDN
    • OIDC IdP
    • SCIM
    • FIDO2/WebAuthn
    • API Gateway
    AuthN/AuthZ, rate limiting, geo routing
    P2Application Plane
    • Next.js frontend
    • Node/Express API
    • Python services
    • BFF
    • Webhooks
    Feature surfaces, orchestration, tenancy
    P3AI Plane
    • GeminiService gateway
    • Prompt registry
    • RAG service
    • Recommender
    • Active-learning loop
    All inference + retrieval
    P4Governance Plane
    • Model registry
    • Policy engine (OPA)
    • Compliance engine
    • Evidence store
    Policy decisions, evidence, attestations
    P5Data Plane
    • Postgres/CRDB
    • Vector DB (pgvector/Weaviate)
    • Object store
    • Kafka
    • Cache
    Persistence, lineage, search
    P6Observability Plane
    • OTel collector
    • Prometheus
    • Loki/ELK
    • WORM telemetry topic
    • SIEM
    Metrics, logs, traces, audit
    P7Supply-Chain Plane
    • SLSA L3 build
    • Sigstore/Cosign
    • SBOM
    • Dependency scanner
    Build integrity, SBOM, attestations
    +
    +
    +

    M1-S2 · Deployment Topology

    +

    tiers

    tierregionstech
    Edgeglobal PoPsCloudflare / AWS CloudFront
    Appprimary + DREKS/GKE/AKS, blue-green
    AIprimary + DRGPU node pools, KEDA, vLLM/Triton
    Dataactive-active multi-regionAurora/Spanner, replicated S3
    +
    +
    +

    M1-S3 · Tenancy Model

    +

    patterns

    • Pool-multi-tenant (default) with row-level security and per-tenant KMS keys
    • Silo-per-tenant for regulated tenants (banks, gov)
    • Sovereign-cloud variant with in-region GeminiService endpoints
    +
    +
    +
    +

    M2 · M2 — Data Models

    +

    Core entities and relationships for the platform.

    +
    +

    M2-S1 · Entity Catalogue

    +

    entities

    idnamefieldsowner
    DM-01UseruserId, tenantId, role[], skillProfile, locale, consentsIAM service
    DM-02WorkflowworkflowId, ownerId, dag, version, status, tags[]Workflow service
    DM-03RecommendationrecId, userId, candidateWorkflows[], context, score, feedbackRecommender
    DM-04PromptTemplatetemplateId, versions[], variables[], owner, visibility, tags[], lineagePrompt registry
    DM-05ModelRegistrationmodelId, provider, version, sha256, evalRefs[], complianceTags[], rbacPolicyRef, status, rollbackTargetIdModel registry
    DM-06RAGCorpuscorpusId, sourceRefs[], lineage, retentionClass, piiPolicy, embeddingModelIdRAG service
    DM-07GeminiCallcallId, userId, modelId, promptHash, redactedPrompt, completionHash, safetyDecision, telemetrySigGeminiService
    DM-08IncidentincidentId, severity, signals[], affectedAssets[], status, narrativeSOC
    DM-09EvidenceRecordevidenceId, controlId, payloadHash, merkleRoot, signature, retainUntilCompliance engine
    +
    +
    +

    M2-S2 · Lineage & Versioning

    +

    rules

    • All entities are immutable-on-update (event-sourced + materialised views)
    • Every mutation emits a signed event into the WORM Kafka topic ai.audit.v1
    • PromptTemplate, ModelRegistration, RAGCorpus carry SemVer + content hash
    • Rollback = pointer flip to a prior signed version; never a destructive op
    +
    +
    +

    M2-S3 · Retention & Classification

    +

    classes

    classretentionstorage
    C1 PublicindefiniteS3 standard
    C2 Internal5 yrS3 SSE-KMS
    C3 Confidential7 yr WORMS3 Object Lock
    C4 Restricted/PIIpolicy-drivenTokenised + envelope encryption
    +
    +
    +
    +

    M3 · M3 — Data Flows

    +

    Eight canonical end-to-end flows with governance hooks.

    +
    +

    M3-S1 · Flow Catalogue

    +

    flows

    idnamestagesgovernanceHooks
    DF-01User → Workflow recommendationcontext → recommender → policy gate → UIconsent check, fairness probe, telemetry
    DF-02Active-learning feedbackuser feedback → signer → kafka → trainer → recommenderEd25519 signature, bias re-eval
    DF-03RAG-grounded chatprompt → retriever → reranker → GeminiService → faithfulness scorer → UIPII redact, citation enforce, refusal policy
    DF-04Collaborative prompt editedit → CRDT merge → variable lint → review → publishRBAC, lineage, prompt-injection lint
    DF-05Model registrationsubmit → evals → sign → register → tag → rolloutevals coverage, complianceTags, attestation
    DF-06GeminiService inferencerequest → Art. 5 check → injection guard → call → safety classifier → responsetelemetry envelope, decision log
    DF-07AI safety incidentdetection → triage → containment → notification → forensic → post-mortemGDPR Art. 33/34, EU AI Act Art. 73
    DF-08Adaptive UX evaluationuser signal → skill estimator → UX selector → A/B → ethics gateno dark patterns, transparency, opt-out
    +
    +
    +

    M3-S2 · Governance Hooks (cross-cutting)

    +

    hooks

    • Consent verifier (per-purpose GDPR Art. 6/7)
    • PII redactor (Microsoft Presidio + custom rules)
    • EU AI Act Art. 5 prohibited-practice check
    • Prompt-injection / jailbreak detector
    • Faithfulness scorer for RAG outputs
    • Fairness probe (AIR / SPD windows)
    • Telemetry signer (Ed25519, optional Dilithium3)
    • Evidence emitter (control → evidence record)
    +
    +
    +
    +

    M4 · M4 — AI-Driven Workflow Recommendation & Active Learning

    +

    Two-tower recommender with bandit exploration, signed feedback loop, and bias guardrails.

    +
    +

    M4-S1 · Recommender Architecture

    +

    components

    • Two-tower retrieval (user tower + workflow tower) on Vertex AI / SageMaker
    • Reranker LLM (Gemini Flash) with policy filter
    • Contextual bandit (LinUCB) for exploration
    • Post-rank fairness pass (group AIR ≥ 0.8)
    +
    +
    +

    M4-S2 · Active Learning Loop

    +

    stages

    • Implicit feedback: dwell, completion, abandonment
    • Explicit feedback: thumbs / rationale / correction
    • Cryptographic signature on every feedback event (Ed25519)
    • Daily retrain with drift gate (PSI ≤ 0.1, no fairness regression)
    • Shadow + canary deploy (5% → 25% → 100%)
    +
    +
    +

    M4-S3 · Cold-start & Privacy

    +

    controls

    • Skill-profile bootstrap from role + opt-in onboarding survey
    • Federated personalisation option (no raw signals leave device)
    • Differential privacy noise (ε ≤ 4) on aggregate analytics
    +
    +
    +

    M4-S4 · APIs

    +

    routes

    • POST /api/recommend/workflows
    • POST /api/recommend/feedback
    • GET /api/recommend/profile
    • POST /api/recommend/retrain (admin)
    +
    +
    +
    +

    M5 · M5 — Adaptive Content & UI by Context and Skill

    +

    Skill-aware progressive disclosure and content adaptation with anti-dark-pattern guardrails.

    +
    +

    M5-S1 · Skill Estimator

    +

    design

    • Bayesian skill model per capability (workflow design, prompt eng, data analysis)
    • Inputs: completion of guided tasks, support tickets, self-rating
    • Decay function for inactivity
    +
    +
    +

    M5-S2 · UX Adaptation Patterns

    +

    patterns

    • Progressive disclosure tiers: Novice / Practitioner / Expert / Power
    • Inline coaching with dismissible cards
    • Reading-level adaptation (Flesch-Kincaid 8/12/16)
    • Locale + accessibility (WCAG 2.2 AA, ARIA, keyboard-only)
    +
    +
    +

    M5-S3 · Ethics & Transparency

    +

    guardrails

    • No dark patterns (FTC + EU 2026 Digital Fairness Act)
    • Always-visible 'Why am I seeing this?' explainer
    • User-facing UX preference reset
    • Adaptation events emitted with consent flag
    +
    +
    +
    +

    M6 · M6 — High-Assurance RAG-Based Grounded Chat

    +

    RAG with lineage, citation enforcement, faithfulness scoring, and refusal-on-low-evidence.

    +
    +

    M6-S1 · Retrieval Pipeline

    +

    stages

    • Query rewrite (intent + decomposition)
    • Hybrid search (BM25 + dense + filters)
    • Reranker (cross-encoder)
    • Context window builder with token budget + diversity
    • Citation pinner (chunk-level provenance)
    +
    +
    +

    M6-S2 · Generation & Faithfulness

    +

    controls

    • Constrained generation: 'cite or refuse'
    • Faithfulness score (Q²/AlignScore/RAGAS) gating ≥ 0.92
    • Hallucination flag on unsupported claims
    • Refusal templates: 'I do not have evidence in your corpus to answer that.'
    +
    +
    +

    M6-S3 · Corpus Governance

    +

    controls

    • Source allowlist & licence metadata
    • PII redaction at ingestion (Presidio + DLP)
    • Retention class on every chunk
    • Per-document RBAC enforced at query time (post-retrieval filter)
    • Right-to-be-forgotten propagation (vector deletion + reindex)
    +
    +
    +

    M6-S4 · APIs

    +

    routes

    • POST /api/rag/chat
    • POST /api/rag/ingest
    • DELETE /api/rag/document/:id (RTBF)
    • GET /api/rag/corpus/:id/manifest
    +
    +
    +
    +

    M7 · M7 — Collaborative Prompt Engineering

    +

    Multi-user prompt template lifecycle with CRDT editing, lineage, and review workflow.

    +
    +

    M7-S1 · Lifecycle Stages

    +

    stages

    • Draft
    • Review
    • Approved
    • Published
    • Deprecated
    • Archived
    +
    +
    +

    M7-S2 · Collaboration Mechanics

    +

    design

    • CRDT (Yjs) for real-time co-editing
    • Variable schema with type, default, sensitivity
    • Variable-link UI to dataset / workflow context
    • Live test panel against canary model + sample dataset
    • PR-style review: 2-of-N approvers; CI runs eval suite
    +
    +
    +

    M7-S3 · Lineage & Provenance

    +

    controls

    • Every version content-addressed (sha256)
    • Parent/child template links + diff view
    • Usage telemetry: per-template invocation count, faithfulness, satisfaction
    • Export/import as signed bundles (tar.gz + sig)
    +
    +
    +

    M7-S4 · APIs

    +

    routes

    • POST /api/prompts/templates
    • GET /api/prompts/templates/:id
    • PATCH /api/prompts/templates/:id
    • POST /api/prompts/templates/:id/review
    • POST /api/prompts/templates/:id/publish
    • GET /api/prompts/templates/:id/lineage
    • POST /api/prompts/test
    +
    +
    +
    +

    M8 · M8 — Enterprise Model Registry Governance

    +

    RBAC, compliance metadata, rollback, tagging, attestations.

    +
    +

    M8-S1 · Registry Schema

    +

    fields

    • modelId, provider, family, version, sha256
    • evalRefs[]: pointers to eval suites and results
    • complianceTags[]: 'EU_AI_ACT_HIGH_RISK', 'GDPR_DPIA', 'SR_11_7_TIER_1'
    • rbacPolicyRef: OPA bundle key
    • status: draft|registered|approved|published|paused|retired
    • rollbackTargetId: previous-known-good model pointer
    • ownerSubjectId; approvers[]; signatures[]
    +
    +
    +

    M8-S2 · RBAC & Policy

    +

    roles

    • model_author
    • model_validator
    • model_approver
    • model_operator
    • auditor (read-only)
    • dpo (read+veto on PII concerns)
    +

    policies

    • deploy_gate.rego: signature + IMV + DPIA non-expired
    • high_risk_label.rego: Annex IV dossier present
    • rollback_window.rego: rollback always within 30s window
    +
    +
    +

    M8-S3 · Tagging & Search

    +

    design

    • Tag namespace: regulatory, sector, capability, sensitivity, lifecycle
    • Full-text + facet search across registry
    • Saved queries for audit & supervisor read-only views
    +
    +
    +

    M8-S4 · APIs

    +

    routes

    • POST /api/models/register
    • GET /api/models/:id
    • POST /api/models/:id/approve
    • POST /api/models/:id/publish
    • POST /api/models/:id/rollback
    • POST /api/models/:id/tag
    • GET /api/models/search
    • GET /api/models/:id/attestations
    +
    +
    +
    +

    M9 · M9 — AI Safety & Global Governance Reporting

    +

    Reporting framework spanning existential risk, misuse, bias, threat assessment, alignment failure, and international collaboration.

    +
    +

    M9-S1 · Report Catalogue

    +

    reports

    idnamecadenceaudience
    SR-01Existential Risk OutlookAnnualBoard + Treaty Authority
    SR-02Misuse & Dual-Use Threat AssessmentSemi-annualCISO + Treaty + GC
    SR-03Bias & Fairness ReportQuarterlyDPO + Compliance + Board
    SR-04Alignment Failure ScenariosQuarterly tabletop + post-incidentBoard + CAIO + research community
    SR-05International Collaboration BriefQuarterlyTreaty Liaison Officer
    SR-06Capability Evaluation DisclosurePer material capability changeICGC / regulator
    SR-07Incident & Near-Miss RegisterContinuousCISO + Internal Audit
    SR-08Annual AI Safety StatementAnnual publicPublic + investors
    +
    +
    +

    M9-S2 · Risk Taxonomy

    +

    categories

    • Existential / civilizational
    • Misuse (CBRN, cyber, mass-disinfo)
    • Bias / disparate impact
    • Privacy / re-identification
    • Alignment failure (specification gaming, deceptive alignment)
    • Containment escape / agentic over-reach
    • Concentration / monoculture
    • Conduct / consumer harm
    +
    +
    +

    M9-S3 · International Collaboration

    +

    channels

    • ICGC compute & capability disclosure
    • Bletchley/Seoul/Paris commitments
    • OECD AI Policy Observatory
    • G7 Hiroshima AI Process Code of Conduct
    • AISI / UK AISI / US AISI evaluation participation
    • Council of Europe AI Convention compliance
    +
    +
    +

    M9-S4 · APIs

    +

    routes

    • GET /api/safety/reports
    • GET /api/safety/reports/:id
    • POST /api/safety/incidents
    • GET /api/safety/risk-register
    • POST /api/safety/disclosures (treaty)
    +
    +
    +
    +

    M10 · M10 — GeminiService Security & Privacy Controls

    +

    Telemetry integrity, GDPR PII redaction, EU AI Act Art. 5 checks, adversarial-prompt defenses.

    +
    +

    M10-S1 · GeminiService Gateway

    +

    design

    • All Gemini calls routed through internal gateway (no direct SDK from frontend)
    • Per-tenant API keys vaulted in HSM/KMS
    • mTLS to provider; egress allowlist; outbound DLP
    • Per-call decision log signed (Ed25519) and shipped to WORM Kafka
    +
    +
    +

    M10-S2 · Pre-Call Pipeline (in order)

    +

    stages

    • 1. AuthN/AuthZ (OIDC + scope + tenancy)
    • 2. Rate / cost guard (token budget per user/tenant)
    • 3. PII redactor (Presidio + custom regex + ML classifier)
    • 4. EU AI Act Art. 5 prohibited-practice classifier (manipulation, social scoring, biometric categorisation, predictive policing for individuals, etc.)
    • 5. Prompt-injection / jailbreak detector (rules + LLM judge + perplexity heuristic)
    • 6. Constitutional / policy filter
    • 7. Telemetry envelope creation + signature
    +
    +
    +

    M10-S3 · Post-Call Pipeline

    +

    stages

    • 1. Output safety classifier (toxicity, self-harm, illegal, CSAM)
    • 2. PII / secrets leakage scan (egress redactor)
    • 3. Faithfulness / citation check (RAG path)
    • 4. Final policy filter; deliver or refuse
    • 5. Append response hash + final decision to telemetry envelope
    +
    +
    +

    M10-S4 · Telemetry Integrity

    +

    controls

    • Append-only Kafka topic ai.gemini.telemetry.v1 with mTLS + ACLs
    • Daily Merkle root anchored to RFC 3161 timestamp + (optional) blockchain anchor
    • PQC-ready signatures (Dilithium3 dual-signature option)
    • Tamper alarms on hash-chain breaks (auto-incident creation)
    +
    +
    +

    M10-S5 · Adversarial Defenses

    +

    defenses

    • Multi-layer prompt-injection detection (pre-, mid-, post-)
    • Tool-call allowlisting + scoped credentials per call
    • Indirect-prompt-injection sanitisation on retrieved content
    • Canary tokens to detect data exfiltration via prompts
    • Red-team test suite gated in CI (block release if regression)
    +
    +
    +

    M10-S6 · APIs

    +

    routes

    • POST /api/gemini/generate
    • POST /api/gemini/embed
    • POST /api/gemini/vision
    • GET /api/gemini/telemetry/:callId
    • GET /api/gemini/policies
    +
    +
    +
    +

    M11 · M11 — Task & Report Management

    +

    End-user and admin features for tasks, reports, exports, and audit packs.

    +
    +

    M11-S1 · Task Management

    +

    features

    • Task DAG visualisation (D3/dagre)
    • Assignment & SLA tracking
    • Comments + @mentions + activity stream
    • Linked artefacts: prompts, models, RAG corpora, evidence
    • Bulk operations with idempotency keys
    +
    +
    +

    M11-S2 · Report Generation

    +

    features

    • Templated reports (Markdown with <title>/<abstract>/<content>)
    • PDF/A-3 export with embedded JSON-LD evidence
    • Scheduled reports (cron + event-driven)
    • Distribution: email (DMARC), Slack/Teams, SFTP, S3 dropzone
    • Auditor read-only export channel
    +
    +
    +

    M11-S3 · APIs

    +

    routes

    • POST /api/tasks
    • GET /api/tasks/:id
    • PATCH /api/tasks/:id
    • POST /api/tasks/:id/comment
    • GET /api/reports/templates
    • POST /api/reports/render
    • POST /api/reports/schedule
    • GET /api/reports/exports/:id
    +
    +
    +
    +

    M12 · M12 — Implementation Strategy & Integration Patterns

    +

    Step-by-step strategy, module boundaries, and integration patterns for enterprise deployment.

    +
    +

    M12-S1 · Six-Phase Plan (52 weeks)

    +

    phases

    phaseweeksdeliverables
    P1 Foundations1-6
    • Tenancy model
    • Identity (OIDC/SCIM)
    • OPA bundle bootstrap
    • Kafka WORM cluster
    • Skeleton APIs
    P2 Governance Spine7-14
    • Model registry + RBAC
    • Compliance engine
    • Evidence store
    • Telemetry envelopes
    P3 AI Core15-26
    • GeminiService gateway
    • Prompt registry + collab
    • RAG service + faithfulness
    • Recommender v1
    P4 Adaptive UX & Tasks27-34
    • Skill estimator
    • Adaptive UI
    • Task DAG
    • Reports v1
    P5 Safety Reporting & Treaty35-44
    • Safety report suite
    • Treaty disclosure pack
    • Tabletop GC1-GC7
    P6 Hardening & Certification45-52
    • ISO 42001 cert
    • SOC 2 Type II
    • Annex IV pilots
    • Pen-test + red-team
    +
    +
    +

    M12-S2 · Module Boundaries

    +

    boundaries

    • Identity service (P1) — single source of truth for users/roles
    • Workflow service — owns workflow DAGs; consumes recommendations
    • Recommender service — stateless API; trained offline; reads features from feature store
    • Prompt registry — owns templates + lineage; emits events
    • RAG service — owns corpora + retrieval; isolates per-tenant indices
    • Model registry — owns ModelRegistration; enforces RBAC + signatures
    • GeminiService gateway — single egress point to provider
    • Compliance engine — read-side projection from event log; emits coverage scorecards
    • Observability — strictly read-only consumer of telemetry topics
    +
    +
    +

    M12-S3 · Integration Patterns

    +

    patterns

    • Event-driven via Kafka (ai.audit.v1, ai.gemini.telemetry.v1, ai.recsys.events.v1)
    • Synchronous REST/gRPC behind API gateway with mTLS
    • Webhooks for tenant-side integrations (signed payloads, replay protection)
    • OIDC-federated SSO + SCIM provisioning
    • Outbound connectors: Slack/Teams, Jira, ServiceNow, Splunk, Datadog
    • Data-residency routing via gateway + per-region GeminiService endpoints
    • Sovereign-cloud variant with no cross-border calls
    • BYOK (Bring-Your-Own-Key) for tenant KMS
    +
    +
    +

    M12-S4 · KPIs / OKRs

    +

    kpis

    idnametarget
    KPI-01Time-to-governed-deployment≤ 72 h
    KPI-02RAG faithfulness≥ 0.92
    KPI-03Prompt collab adoption≥ 80% teams
    KPI-04Model registry coverage100%
    KPI-05Gemini blocked-harm rate≥ 99.5%
    KPI-06PII leakage≤ 0.01%
    KPI-07Containment MTTR≤ 60 min
    KPI-08Evidence automation≥ 92%
    KPI-09Alignment-drift MTTD≤ 4 min
    KPI-10Active-learning loop latency≤ 24 h to retrain
    KPI-11Adaptive-UX opt-out completion≤ 3 clicks
    KPI-12Audit finding closure≤ 90 d (high)
    KPI-13Recommender AIR floor≥ 0.8
    KPI-14Telemetry continuity≥ 99.99%
    KPI-15Adversarial-prompt block rate≥ 99% on red-team set
    +
    +
    +

    M12-S5 · Risk Register (top 8)

    +

    risks

    idnamemitigation
    R1Prompt-injection via retrieved contentIndirect-injection sanitiser + tool allowlist
    R2Hallucination in RAG chatFaithfulness gate + cite-or-refuse
    R3PII leakage to providerPre-call redactor + egress DLP + telemetry audit
    R4Bias amplification via active learningPer-loop fairness gate + counterfactual eval
    R5Model rollback failureAlways-on N-1 hot path + 30s rollback test in CI
    R6Telemetry tamperingHash-chained WORM + Merkle anchor + alarms
    R7EU AI Act Art. 5 violation in user promptPre-call classifier + refusal templates
    R8Concentration risk on GeminiMulti-provider abstraction + benchmark fail-over
    +
    +
    + +
    +

    Regulatory Alignment

    + +
    + +
    +

    JSON Schemas

    +

    8 schemas covering prompt templates, model registrations, RAG / Gemini envelopes, feedback events, recommendations, evidence, and incidents.

    +
    promptTemplate
    {
    +  "$id": "https://workflowai.pro/schemas/wfap-gemini/prompt-template.json",
    +  "type": "object",
    +  "required": [
    +    "templateId",
    +    "version",
    +    "owner",
    +    "body",
    +    "variables"
    +  ],
    +  "properties": {
    +    "templateId": {
    +      "type": "string"
    +    },
    +    "version": {
    +      "type": "string"
    +    },
    +    "owner": {
    +      "type": "string"
    +    },
    +    "body": {
    +      "type": "string"
    +    },
    +    "variables": {
    +      "type": "array",
    +      "items": {
    +        "type": "object",
    +        "required": [
    +          "name",
    +          "type"
    +        ],
    +        "properties": {
    +          "name": {
    +            "type": "string"
    +          },
    +          "type": {
    +            "enum": [
    +              "string",
    +              "number",
    +              "bool",
    +              "enum",
    +              "json"
    +            ]
    +          },
    +          "default": {},
    +          "sensitivity": {
    +            "enum": [
    +              "public",
    +              "internal",
    +              "confidential",
    +              "pii"
    +            ]
    +          },
    +          "linkTo": {
    +            "type": "string"
    +          }
    +        }
    +      }
    +    },
    +    "tags": {
    +      "type": "array",
    +      "items": {
    +        "type": "string"
    +      }
    +    },
    +    "lineage": {
    +      "type": "object"
    +    }
    +  }
    +}
    modelRegistration
    {
    +  "$id": "https://workflowai.pro/schemas/wfap-gemini/model-registration.json",
    +  "type": "object",
    +  "required": [
    +    "modelId",
    +    "provider",
    +    "version",
    +    "sha256",
    +    "status"
    +  ],
    +  "properties": {
    +    "modelId": {
    +      "type": "string"
    +    },
    +    "provider": {
    +      "type": "string"
    +    },
    +    "version": {
    +      "type": "string"
    +    },
    +    "sha256": {
    +      "type": "string",
    +      "pattern": "^[A-Fa-f0-9]{64}$"
    +    },
    +    "evalRefs": {
    +      "type": "array",
    +      "items": {
    +        "type": "string"
    +      }
    +    },
    +    "complianceTags": {
    +      "type": "array",
    +      "items": {
    +        "type": "string"
    +      }
    +    },
    +    "rbacPolicyRef": {
    +      "type": "string"
    +    },
    +    "status": {
    +      "enum": [
    +        "draft",
    +        "registered",
    +        "approved",
    +        "published",
    +        "paused",
    +        "retired"
    +      ]
    +    },
    +    "rollbackTargetId": {
    +      "type": "string"
    +    },
    +    "signatures": {
    +      "type": "array"
    +    }
    +  }
    +}
    ragQueryEnvelope
    {
    +  "$id": "https://workflowai.pro/schemas/wfap-gemini/rag-query-envelope.json",
    +  "type": "object",
    +  "required": [
    +    "queryId",
    +    "userId",
    +    "tenantId",
    +    "corpusId",
    +    "query",
    +    "ts"
    +  ],
    +  "properties": {
    +    "queryId": {
    +      "type": "string"
    +    },
    +    "userId": {
    +      "type": "string"
    +    },
    +    "tenantId": {
    +      "type": "string"
    +    },
    +    "corpusId": {
    +      "type": "string"
    +    },
    +    "query": {
    +      "type": "string"
    +    },
    +    "ts": {
    +      "type": "string",
    +      "format": "date-time"
    +    },
    +    "redactionFlags": {
    +      "type": "array"
    +    },
    +    "consents": {
    +      "type": "object"
    +    }
    +  }
    +}
    geminiCallEnvelope
    {
    +  "$id": "https://workflowai.pro/schemas/wfap-gemini/gemini-call-envelope.json",
    +  "type": "object",
    +  "required": [
    +    "callId",
    +    "userId",
    +    "modelId",
    +    "promptHash",
    +    "ts",
    +    "signature"
    +  ],
    +  "properties": {
    +    "callId": {
    +      "type": "string"
    +    },
    +    "userId": {
    +      "type": "string"
    +    },
    +    "tenantId": {
    +      "type": "string"
    +    },
    +    "modelId": {
    +      "type": "string"
    +    },
    +    "promptHash": {
    +      "type": "string"
    +    },
    +    "redactedPromptPreview": {
    +      "type": "string"
    +    },
    +    "completionHash": {
    +      "type": "string"
    +    },
    +    "safetyDecision": {
    +      "enum": [
    +        "allow",
    +        "warn",
    +        "refuse"
    +      ]
    +    },
    +    "art5Decision": {
    +      "enum": [
    +        "allow",
    +        "block"
    +      ]
    +    },
    +    "injectionScore": {
    +      "type": "number"
    +    },
    +    "ts": {
    +      "type": "string",
    +      "format": "date-time"
    +    },
    +    "signature": {
    +      "type": "object",
    +      "required": [
    +        "alg",
    +        "value",
    +        "keyId"
    +      ]
    +    }
    +  }
    +}
    feedbackEvent
    {
    +  "$id": "https://workflowai.pro/schemas/wfap-gemini/feedback-event.json",
    +  "type": "object",
    +  "required": [
    +    "eventId",
    +    "userId",
    +    "subjectId",
    +    "subjectType",
    +    "verdict",
    +    "signature"
    +  ],
    +  "properties": {
    +    "eventId": {
    +      "type": "string"
    +    },
    +    "userId": {
    +      "type": "string"
    +    },
    +    "subjectId": {
    +      "type": "string"
    +    },
    +    "subjectType": {
    +      "enum": [
    +        "recommendation",
    +        "rag-answer",
    +        "prompt",
    +        "workflow"
    +      ]
    +    },
    +    "verdict": {
    +      "enum": [
    +        "up",
    +        "down",
    +        "correct",
    +        "abandon"
    +      ]
    +    },
    +    "rationale": {
    +      "type": "string"
    +    },
    +    "signature": {
    +      "type": "object"
    +    }
    +  }
    +}
    recommendation
    {
    +  "$id": "https://workflowai.pro/schemas/wfap-gemini/recommendation.json",
    +  "type": "object",
    +  "required": [
    +    "recId",
    +    "userId",
    +    "candidates",
    +    "ts"
    +  ],
    +  "properties": {
    +    "recId": {
    +      "type": "string"
    +    },
    +    "userId": {
    +      "type": "string"
    +    },
    +    "candidates": {
    +      "type": "array",
    +      "items": {
    +        "type": "object",
    +        "properties": {
    +          "workflowId": {
    +            "type": "string"
    +          },
    +          "score": {
    +            "type": "number"
    +          },
    +          "reasonCodes": {
    +            "type": "array"
    +          }
    +        }
    +      }
    +    },
    +    "context": {
    +      "type": "object"
    +    },
    +    "fairness": {
    +      "type": "object"
    +    },
    +    "ts": {
    +      "type": "string",
    +      "format": "date-time"
    +    }
    +  }
    +}
    evidenceRecord
    {
    +  "$id": "https://workflowai.pro/schemas/wfap-gemini/evidence-record.json",
    +  "type": "object",
    +  "required": [
    +    "evidenceId",
    +    "controlId",
    +    "payloadHash",
    +    "merkleRoot",
    +    "signature",
    +    "retainUntil"
    +  ],
    +  "properties": {
    +    "evidenceId": {
    +      "type": "string"
    +    },
    +    "controlId": {
    +      "type": "string"
    +    },
    +    "payloadHash": {
    +      "type": "string"
    +    },
    +    "merkleRoot": {
    +      "type": "string"
    +    },
    +    "signature": {
    +      "type": "object"
    +    },
    +    "retainUntil": {
    +      "type": "string",
    +      "format": "date-time"
    +    }
    +  }
    +}
    incidentRecord
    {
    +  "$id": "https://workflowai.pro/schemas/wfap-gemini/incident-record.json",
    +  "type": "object",
    +  "required": [
    +    "incidentId",
    +    "severity",
    +    "status",
    +    "openedAt"
    +  ],
    +  "properties": {
    +    "incidentId": {
    +      "type": "string"
    +    },
    +    "severity": {
    +      "enum": [
    +        "SEV-3",
    +        "SEV-2",
    +        "SEV-1",
    +        "SEV-0"
    +      ]
    +    },
    +    "status": {
    +      "enum": [
    +        "open",
    +        "contained",
    +        "resolved",
    +        "post-mortem"
    +      ]
    +    },
    +    "category": {
    +      "type": "string"
    +    },
    +    "affectedAssets": {
    +      "type": "array"
    +    },
    +    "openedAt": {
    +      "type": "string",
    +      "format": "date-time"
    +    },
    +    "narrative": {
    +      "type": "string"
    +    }
    +  }
    +}
    +
    + +
    +

    Code Examples

    +

    12 reference implementations: GeminiService gateway, RAG chat, model registry, prompt CRDT collab, active learning, OPA gate, Art. 5 classifier, PII redactor, Merkle audit, CI/CD, adaptive UX hook, signed Kafka producer.

    +
    geminiGatewayPython
    #!/usr/bin/env python3
    +"""GeminiService gateway — pre/post pipeline (FastAPI)."""
    +from fastapi import FastAPI, Header, HTTPException
    +from pydantic import BaseModel
    +import hashlib, time
    +from cryptography.hazmat.primitives.asymmetric import ed25519
    +from policy import art5_check, injection_score, redact_pii, output_safety
    +
    +app = FastAPI()
    +SK = ed25519.Ed25519PrivateKey.generate()  # demo only; load from KMS
    +
    +class GenReq(BaseModel):
    +    user_id: str
    +    tenant_id: str
    +    model_id: str
    +    prompt: str
    +
    +@app.post("/api/gemini/generate")
    +def generate(req: GenReq, authorization: str = Header(...)):
    +    redacted, flags = redact_pii(req.prompt)
    +    if art5_check(redacted) == "block":
    +        raise HTTPException(451, "Art. 5 prohibited practice")
    +    if injection_score(redacted) > 0.85:
    +        raise HTTPException(400, "prompt injection suspected")
    +    completion = call_gemini(req.model_id, redacted)
    +    if output_safety(completion) == "refuse":
    +        return {"refused": True, "reason": "safety classifier"}
    +    envelope = {
    +        "callId": hashlib.sha256(f"{req.user_id}{time.time_ns()}".encode()).hexdigest(),
    +        "userId": req.user_id, "tenantId": req.tenant_id,
    +        "modelId": req.model_id,
    +        "promptHash": hashlib.sha256(req.prompt.encode()).hexdigest(),
    +        "completionHash": hashlib.sha256(completion.encode()).hexdigest(),
    +        "safetyDecision": "allow", "art5Decision": "allow",
    +        "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    +    }
    +    sig = SK.sign(json.dumps(envelope, sort_keys=True).encode()).hex()
    +    envelope["signature"] = {"alg": "Ed25519", "value": sig, "keyId": "kms:gemini-gw-2026"}
    +    emit_kafka("ai.gemini.telemetry.v1", envelope)
    +    return {"completion": completion, "envelope": envelope}
    +
    ragChatTypeScript
    // /api/rag/chat — Express + retriever + faithfulness gate
    +import express from "express";
    +import { hybridSearch, rerank, faithfulness, redact } from "./rag";
    +const app = express();
    +app.use(express.json());
    +
    +app.post("/api/rag/chat", async (req, res) => {
    +  const { tenantId, userId, corpusId, question } = req.body;
    +  const safe = redact(question);
    +  const hits = await hybridSearch(corpusId, safe, { tenantAcl: tenantId });
    +  const ranked = await rerank(safe, hits);
    +  if (ranked.length === 0) {
    +    return res.json({ refused: true, reason: "no evidence in corpus" });
    +  }
    +  const draft = await callGemini({ system: SYSTEM_CITE_OR_REFUSE, ctx: ranked, q: safe });
    +  const score = await faithfulness(draft, ranked);
    +  if (score < 0.92) {
    +    return res.json({ refused: true, reason: "low faithfulness", score });
    +  }
    +  res.json({ answer: draft, citations: ranked.map(r => r.docRef), score });
    +});
    +
    modelRegistryNode
    // Model registry — register / approve / rollback
    +const express = require("express");
    +const { sign, verify } = require("./pqc");
    +const opa = require("./opa");
    +const router = express.Router();
    +
    +router.post("/api/models/register", async (req, res) => {
    +  const m = req.body;
    +  if (!/^[A-Fa-f0-9]{64}$/.test(m.sha256)) return res.status(400).json({ error: "bad sha256" });
    +  const decision = await opa.eval("wfap.deploy_gate.allow", { model: m });
    +  if (!decision.allow) return res.status(403).json(decision);
    +  m.status = "registered";
    +  m.signatures = [sign(m)];
    +  await db.models.insert(m);
    +  res.json(m);
    +});
    +
    +router.post("/api/models/:id/rollback", async (req, res) => {
    +  const cur = await db.models.find(req.params.id);
    +  if (!cur.rollbackTargetId) return res.status(400).json({ error: "no rollback target" });
    +  const tgt = await db.models.find(cur.rollbackTargetId);
    +  await db.models.update(cur.id, { status: "paused" });
    +  await db.models.update(tgt.id, { status: "published" });
    +  emitAudit({ type: "model.rollback", from: cur.id, to: tgt.id });
    +  res.json({ rolledBackTo: tgt.id });
    +});
    +
    +module.exports = router;
    +
    promptCollabCRDT
    // Prompt template collaborative editor (Yjs server)
    +const Y = require("yjs");
    +const { setupWSConnection } = require("y-websocket/bin/utils");
    +const WebSocket = require("ws");
    +
    +const wss = new WebSocket.Server({ port: 1234 });
    +wss.on("connection", (conn, req) => {
    +  const auth = verifyJwt(req.headers["sec-websocket-protocol"]);
    +  if (!auth) return conn.close(4401);
    +  setupWSConnection(conn, req, {
    +    docName: `prompt:${auth.tenantId}:${req.url.slice(1)}`,
    +    gc: true,
    +  });
    +  conn.on("close", () => emitAudit({ type: "prompt.session.close", user: auth.sub }));
    +});
    +
    recommenderActiveLearning
    #!/usr/bin/env python3
    +"""Active-learning loop — drift gate + fairness gate."""
    +import pandas as pd, numpy as np
    +from cryptography.hazmat.primitives.asymmetric import ed25519
    +
    +def psi(a, b, bins=10):
    +    qs = np.linspace(0,1,bins+1)
    +    cuts = np.quantile(np.concatenate([a,b]), qs)
    +    pa,_ = np.histogram(a, cuts); pa = pa/pa.sum()+1e-9
    +    pb,_ = np.histogram(b, cuts); pb = pb/pb.sum()+1e-9
    +    return float(np.sum((pa-pb)*np.log(pa/pb)))
    +
    +def air(scores, group):
    +    rates = pd.Series(scores).groupby(group).mean()
    +    return rates.min()/rates.max()
    +
    +def gate(new_scores, old_scores, groups):
    +    if psi(new_scores, old_scores) > 0.1: raise SystemExit("PSI drift")
    +    if air(new_scores, groups) < 0.8:    raise SystemExit("AIR floor")
    +    print("PASS")
    +
    regoDeployGate
    package wfap.deploy_gate
    +
    +# OPA policy gating model deployment
    +default allow = false
    +
    +allow {
    +  input.model.signatures[_].verified
    +  input.model.evalRefs[_]
    +  not expired_dpia
    +  has_required_tags
    +}
    +
    +expired_dpia {
    +  time.parse_rfc3339_ns(input.model.dpia.expiresAt) < time.now_ns()
    +}
    +
    +has_required_tags {
    +  required := {"FAIRNESS_TESTED", "PII_REDACTION_VERIFIED"}
    +  set := {t | t := input.model.complianceTags[_]}
    +  required - set == set()
    +}
    +
    art5Classifier
    #!/usr/bin/env python3
    +"""EU AI Act Art. 5 prohibited-practice classifier (heuristic + LLM judge)."""
    +PROHIBITED = [
    +    "subliminal_techniques",
    +    "exploitation_of_vulnerabilities",
    +    "social_scoring_individuals",
    +    "biometric_categorisation_sensitive",
    +    "real_time_remote_biometric_id",
    +    "predictive_policing_individual",
    +    "emotion_recognition_workplace_education",
    +    "untargeted_facial_image_scraping",
    +]
    +
    +def art5_check(text: str) -> str:
    +    # 1. rule-based fast path
    +    if any(k in text.lower() for k in ["social score", "rank citizens", "predict who will commit"]):
    +        return "block"
    +    # 2. LLM judge (Gemini Flash) — JSON schema response
    +    judge = call_gemini_judge(text, PROHIBITED)
    +    return "block" if judge.get("matches") else "allow"
    +
    piiRedactorPython
    #!/usr/bin/env python3
    +"""GDPR PII redactor — Presidio + custom rules."""
    +from presidio_analyzer import AnalyzerEngine
    +from presidio_anonymizer import AnonymizerEngine
    +
    +ANALYZER = AnalyzerEngine()
    +ANON = AnonymizerEngine()
    +
    +def redact_pii(text: str, lang: str = "en"):
    +    results = ANALYZER.analyze(text=text, language=lang,
    +        entities=["PERSON","EMAIL_ADDRESS","PHONE_NUMBER","CREDIT_CARD",
    +                  "IBAN_CODE","IP_ADDRESS","LOCATION","UK_NHS","US_SSN"])
    +    out = ANON.anonymize(text=text, analyzer_results=results)
    +    flags = sorted({r.entity_type for r in results})
    +    return out.text, flags
    +
    merkleAuditTelemetry
    #!/usr/bin/env python3
    +"""Daily Merkle audit of GeminiService telemetry."""
    +import hashlib, json, time, boto3
    +
    +def merkle(leaves):
    +    layer = [hashlib.sha256(l).digest() for l in leaves] or [b""]
    +    while len(layer) > 1:
    +        if len(layer) % 2: layer.append(layer[-1])
    +        layer = [hashlib.sha256(layer[i]+layer[i+1]).digest()
    +                 for i in range(0,len(layer),2)]
    +    return layer[0]
    +
    +def daily(bucket, prefix):
    +    s3 = boto3.client("s3")
    +    leaves = [s3.get_object(Bucket=bucket, Key=o["Key"])["Body"].read()
    +              for o in s3.list_objects_v2(Bucket=bucket, Prefix=prefix).get("Contents", [])]
    +    root = merkle(leaves).hex()
    +    manifest = {"date": time.strftime("%Y-%m-%d"), "merkleRoot": root, "leaves": len(leaves)}
    +    s3.put_object(Bucket=bucket, Key=f"{prefix}/_manifests/{manifest['date']}.json",
    +                  Body=json.dumps(manifest).encode(),
    +                  ObjectLockMode="COMPLIANCE",
    +                  ObjectLockRetainUntilDate="2033-01-01T00:00:00Z")
    +    return manifest
    +
    ciGithubWorkflow
    # .github/workflows/wfap-gemini.yml
    +name: wfap-gemini-ci
    +on: [push, pull_request]
    +jobs:
    +  govern:
    +    runs-on: ubuntu-latest
    +    steps:
    +      - uses: actions/checkout@v4
    +      - run: opa fmt --diff policies/ && opa test policies/
    +      - run: conftest test --policy policies deploy/
    +      - run: pytest tests/redteam tests/art5 tests/injection -q
    +      - run: python tools/faithfulness_eval.py --threshold 0.92
    +      - run: python tools/bias_gate.py --air 0.8 --psi 0.1
    +      - run: |
    +          docker build -t wfap-gemini:${{ github.sha }} .
    +          cosign sign --yes wfap-gemini:${{ github.sha }}
    +          cosign attest --predicate evidence.json wfap-gemini:${{ github.sha }}
    +      - run: kubectl apply -f deploy/canary-5pct.yaml
    +
    adaptiveUxReact
    // React hook: useAdaptiveUx — skill-tier gating with ethics guardrails
    +import { useState, useEffect } from "react";
    +
    +export function useAdaptiveUx(capability) {
    +  const [tier, setTier] = useState("practitioner");
    +  const [transparency, setTransparency] = useState(true);
    +
    +  useEffect(() => {
    +    fetch(`/api/skill/${capability}`).then(r => r.json()).then(s => {
    +      setTier(s.tier);
    +    });
    +  }, [capability]);
    +
    +  const reasonCard = (
    +    <button onClick={() => alert(`UI tier '${tier}' chosen from your skill profile. You can reset under Settings → UX.`)}>
    +      Why am I seeing this?
    +    </button>
    +  );
    +  return { tier, transparency, reasonCard };
    +}
    +
    kafkaWormProducer
    // signed-telemetry producer (Node)
    +const { Kafka } = require("kafkajs");
    +const { sign } = require("./signer-ed25519");
    +const k = new Kafka({ brokers: process.env.KAFKA_BROKERS.split(",") });
    +const p = k.producer({ idempotent: true });
    +async function send(topic, payload) {
    +  await p.connect();
    +  const env = { ...payload, ts: new Date().toISOString() };
    +  env.signature = sign(JSON.stringify(env));
    +  await p.send({ topic, messages: [{ key: env.callId || env.eventId, value: JSON.stringify(env) }] });
    +}
    +module.exports = { send };
    +
    +
    + +
    +

    Case Studies

    +

    5 reference deployments across banking, life sciences, public sector, insurance, and technology.

    +

    CS-01 · Global bank — WorkflowAI Pro on regulated estate

    Sector: Banking

    Tier-1 bank deployed WorkflowAI Pro across 38k users with full SR 11-7 + EU AI Act alignment.

    Outcomes

    users38000
    modelsRegistered412
    promptTemplatesPublished1840
    ragGroundedness0.94 avg
    geminiBlockedHarmRate99.7%
    ISO42001Certified

    CS-02 · Pharma — RAG chat for SMEs and regulators

    Sector: Life Sciences

    RAG chat over GxP-controlled corpora with zero hallucination tolerance and audit trail.

    Outcomes

    corpora22
    monthlyQueries1400000.0
    hallucinationIncidents0
    regulatoryEngagementFDA + EMA satisfied

    CS-03 · Public sector — Sovereign-cloud variant

    Sector: Government

    G7 ministry deployed sovereign-cloud variant with in-region GeminiService and air-gapped admin.

    Outcomes

    dataResidency100%
    treatyDisclosures4
    redTeamPassRate99.3%

    CS-04 · Insurer — Fairness-aware recommender

    Sector: Insurance

    Workflow recommender personalised to claims handlers with strict fairness floor (AIR ≥ 0.85).

    Outcomes

    AIRAfter0.88
    handlerProductivity+19%
    consumerComplaints-23%

    CS-05 · Tech conglomerate — Collaborative prompt engineering at scale

    Sector: Technology

    300+ teams onboarded to collaborative prompt registry with PR-style review and CI evals.

    Outcomes

    templatesActive6200
    averageReviewTime37 min
    evalRegressionsBlocked184
    adoption92% of eligible teams
    +
    + +
    +

    API Endpoints

    +

    Prefix: /api/wfap-gemini · Total planned: 75

    + +
    +
    + + + diff --git a/rag-agentic-dashboard/server.js b/rag-agentic-dashboard/server.js index ad6054a..86f82a3 100644 --- a/rag-agentic-dashboard/server.js +++ b/rag-agentic-dashboard/server.js @@ -21244,6 +21244,501 @@ app.get('/api/sentinel-ai-v24/case-studies/:id', (req, res) => { res.json(cs); }); +// ══════════════════════════════════════════════════════════════════════════════ +// SECTION 9.6: ENT-AGI-GOV-MASTER-WP-035 — Enterprise AGI/ASI Governance Master +// Framework (2026-2030) +// 8 modules · 7 pillars · 16 regulatory axes · 9 reference architectures · +// 8 safety/containment protocols · 6 civilizational artefacts · +// 6 financial-services MRM domains · 7 Kafka GaC artefacts · 6 schemas · +// 10 code examples · 6 case studies · 56 API routes +// ══════════════════════════════════════════════════════════════════════════════ + +const EAGV = require('./data/ent-agi-gov-master.json'); + +const EAGV_MODULE_KEYS = [ + 'M1_pillars', + 'M2_regulatory', + 'M3_architectures', + 'M4_safety', + 'M5_civilizational', + 'M6_financialMrm', + 'M7_kafkaGac', + 'M8_roadmap', +]; + +function eagvFindModule(mid) { + const u = String(mid || '').toUpperCase(); + for (const k of EAGV_MODULE_KEYS) { + const m = EAGV[k]; + if (m && (m.id || '').toUpperCase() === u) return m; + } + if (EAGV[mid]) return EAGV[mid]; + return null; +} + +function eagvFindSection(sid) { + const u = String(sid || '').toUpperCase(); + for (const k of EAGV_MODULE_KEYS) { + const m = EAGV[k]; + for (const s of (m && m.sections) || []) { + if ((s.id || '').toUpperCase() === u) return { module: m.id, section: s }; + } + } + return null; +} + +// Root + summary +app.get('/api/ent-agi-gov-master', (_, res) => res.json(EAGV)); +app.get('/api/ent-agi-gov-master/meta', (_, res) => res.json(EAGV.meta || {})); +app.get('/api/ent-agi-gov-master/executive-summary',(_, res) => res.json(EAGV.executiveSummary || {})); +app.get('/api/ent-agi-gov-master/summary', (_, res) => { + const meta = EAGV.meta || {}; + res.json({ + docRef: meta.docRef, + version: meta.version, + title: meta.title, + horizon: meta.horizon, + classification:meta.classification, + modules: EAGV_MODULE_KEYS.length, + pillars: (EAGV.M1_pillars && EAGV.M1_pillars.sections[0] && EAGV.M1_pillars.sections[0].pillars || []).length, + regulatoryAxes:(EAGV.M2_regulatory && EAGV.M2_regulatory.sections[0] && EAGV.M2_regulatory.sections[0].rows || []).length, + architectures: (EAGV.M3_architectures && EAGV.M3_architectures.sections[0] && EAGV.M3_architectures.sections[0].architectures || []).length, + safetyProtocols:(EAGV.M4_safety && EAGV.M4_safety.sections[0] && EAGV.M4_safety.sections[0].protocols || []).length, + schemas: Object.keys(EAGV.schemas || {}).length, + codeExamples: Object.keys(EAGV.codeExamples || {}).length, + caseStudies: (EAGV.caseStudies || []).length, + apiPrefix: '/api/ent-agi-gov-master', + plannedRoutes: ((EAGV.apiEndpoints && EAGV.apiEndpoints.routes) || []).length, + }); +}); + +// Modules listing +app.get('/api/ent-agi-gov-master/modules', (_, res) => { + const list = EAGV_MODULE_KEYS.map(k => EAGV[k]).filter(Boolean).map(m => ({ + id: m.id, + title: m.title, + summary: m.summary || '', + sectionCount: (m.sections || []).length, + })); + res.json(list); +}); +app.get('/api/ent-agi-gov-master/modules/:id', (req, res) => { + const m = eagvFindModule(req.params.id); + if (!m) return res.status(404).json({ error: 'module not found', id: req.params.id }); + res.json(m); +}); + +// Per-module shortcuts (M1-M8) +app.get('/api/ent-agi-gov-master/m1', (_, res) => res.json(EAGV.M1_pillars || {})); +app.get('/api/ent-agi-gov-master/m2', (_, res) => res.json(EAGV.M2_regulatory || {})); +app.get('/api/ent-agi-gov-master/m3', (_, res) => res.json(EAGV.M3_architectures || {})); +app.get('/api/ent-agi-gov-master/m4', (_, res) => res.json(EAGV.M4_safety || {})); +app.get('/api/ent-agi-gov-master/m5', (_, res) => res.json(EAGV.M5_civilizational || {})); +app.get('/api/ent-agi-gov-master/m6', (_, res) => res.json(EAGV.M6_financialMrm || {})); +app.get('/api/ent-agi-gov-master/m7', (_, res) => res.json(EAGV.M7_kafkaGac || {})); +app.get('/api/ent-agi-gov-master/m8', (_, res) => res.json(EAGV.M8_roadmap || {})); + +// Pillars (G1-G7) +app.get('/api/ent-agi-gov-master/pillars', (_, res) => { + const sec = (EAGV.M1_pillars && EAGV.M1_pillars.sections[0]) || {}; + res.json(sec.pillars || []); +}); +app.get('/api/ent-agi-gov-master/pillars/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const sec = (EAGV.M1_pillars && EAGV.M1_pillars.sections[0]) || {}; + const p = (sec.pillars || []).find(x => (x.id || '').toUpperCase() === u); + if (!p) return res.status(404).json({ error: 'pillar not found', id: req.params.id }); + res.json(p); +}); + +// Regulatory matrix +app.get('/api/ent-agi-gov-master/regulatory', (_, res) => { + const sec = (EAGV.M2_regulatory && EAGV.M2_regulatory.sections[0]) || {}; + res.json(sec.rows || []); +}); +app.get('/api/ent-agi-gov-master/regulatory/:axis', (req, res) => { + const u = decodeURIComponent(req.params.axis).toLowerCase(); + const sec = (EAGV.M2_regulatory && EAGV.M2_regulatory.sections[0]) || {}; + const row = (sec.rows || []).find(x => (x.axis || '').toLowerCase() === u); + if (!row) return res.status(404).json({ error: 'regulatory axis not found', axis: req.params.axis }); + res.json(row); +}); + +// Reference architectures +app.get('/api/ent-agi-gov-master/architectures', (_, res) => { + const sec = (EAGV.M3_architectures && EAGV.M3_architectures.sections[0]) || {}; + res.json(sec.architectures || []); +}); +app.get('/api/ent-agi-gov-master/architectures/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const sec = (EAGV.M3_architectures && EAGV.M3_architectures.sections[0]) || {}; + const a = (sec.architectures || []).find(x => (x.id || '').toUpperCase() === u); + if (!a) return res.status(404).json({ error: 'architecture not found', id: req.params.id }); + res.json(a); +}); + +// Safety / containment protocols +app.get('/api/ent-agi-gov-master/safety', (_, res) => { + const sec = (EAGV.M4_safety && EAGV.M4_safety.sections[0]) || {}; + res.json(sec.protocols || []); +}); +app.get('/api/ent-agi-gov-master/safety/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const sec = (EAGV.M4_safety && EAGV.M4_safety.sections[0]) || {}; + const p = (sec.protocols || []).find(x => (x.id || '').toUpperCase() === u); + if (!p) return res.status(404).json({ error: 'safety protocol not found', id: req.params.id }); + res.json(p); +}); + +// Crisis scenarios (GC1-GC7) +app.get('/api/ent-agi-gov-master/scenarios', (_, res) => { + const secs = (EAGV.M4_safety && EAGV.M4_safety.sections) || []; + const sec = secs.find(s => (s.id || '').toUpperCase() === 'M4-S2') || {}; + res.json(sec.scenarios || []); +}); +app.get('/api/ent-agi-gov-master/scenarios/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const secs = (EAGV.M4_safety && EAGV.M4_safety.sections) || []; + const sec = secs.find(s => (s.id || '').toUpperCase() === 'M4-S2') || {}; + const sc = (sec.scenarios || []).find(x => (x.id || '').toUpperCase() === u); + if (!sc) return res.status(404).json({ error: 'scenario not found', id: req.params.id }); + res.json(sc); +}); + +// Civilizational artefacts +app.get('/api/ent-agi-gov-master/civilizational', (_, res) => { + res.json((EAGV.M5_civilizational && EAGV.M5_civilizational.sections) || []); +}); +app.get('/api/ent-agi-gov-master/civilizational/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const secs = (EAGV.M5_civilizational && EAGV.M5_civilizational.sections) || []; + const s = secs.find(x => (x.id || '').toUpperCase() === u); + if (!s) return res.status(404).json({ error: 'civilizational section not found', id: req.params.id }); + res.json(s); +}); + +// Financial services MRM +app.get('/api/ent-agi-gov-master/financial-mrm', (_, res) => { + const sec = (EAGV.M6_financialMrm && EAGV.M6_financialMrm.sections[0]) || {}; + res.json(sec.domains || []); +}); +app.get('/api/ent-agi-gov-master/financial-mrm/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const sec = (EAGV.M6_financialMrm && EAGV.M6_financialMrm.sections[0]) || {}; + const d = (sec.domains || []).find(x => (x.id || '').toUpperCase() === u); + if (!d) return res.status(404).json({ error: 'financial-mrm domain not found', id: req.params.id }); + res.json(d); +}); + +// Kafka GaC artefacts (sections under M7) +app.get('/api/ent-agi-gov-master/kafka-gac', (_, res) => { + res.json((EAGV.M7_kafkaGac && EAGV.M7_kafkaGac.sections) || []); +}); +app.get('/api/ent-agi-gov-master/kafka-gac/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const secs = (EAGV.M7_kafkaGac && EAGV.M7_kafkaGac.sections) || []; + const s = secs.find(x => (x.id || '').toUpperCase() === u); + if (!s) return res.status(404).json({ error: 'kafka-gac section not found', id: req.params.id }); + res.json(s); +}); + +// Roadmap +app.get('/api/ent-agi-gov-master/roadmap', (_, res) => res.json(EAGV.M8_roadmap || {})); +app.get('/api/ent-agi-gov-master/roadmap/phases', (_, res) => { + const sec = (EAGV.M8_roadmap && EAGV.M8_roadmap.sections || []).find(s => (s.id || '').toUpperCase() === 'M8-S1') || {}; + res.json(sec.phases || []); +}); +app.get('/api/ent-agi-gov-master/roadmap/kpis', (_, res) => { + const sec = (EAGV.M8_roadmap && EAGV.M8_roadmap.sections || []).find(s => (s.id || '').toUpperCase() === 'M8-S2') || {}; + res.json(sec.kpis || []); +}); + +// Reports +app.get('/api/ent-agi-gov-master/reports', (_, res) => { + const sec = (EAGV.M8_roadmap && EAGV.M8_roadmap.sections || []).find(s => (s.id || '').toUpperCase() === 'M8-S3') || {}; + res.json(sec.reports || []); +}); +app.get('/api/ent-agi-gov-master/reports/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const sec = (EAGV.M8_roadmap && EAGV.M8_roadmap.sections || []).find(s => (s.id || '').toUpperCase() === 'M8-S3') || {}; + const r = (sec.reports || []).find(x => (x.id || '').toUpperCase() === u); + if (!r) return res.status(404).json({ error: 'report not found', id: req.params.id }); + res.json(r); +}); + +// Sections lookup (cross-module) +app.get('/api/ent-agi-gov-master/sections/:id', (req, res) => { + const found = eagvFindSection(req.params.id); + if (!found) return res.status(404).json({ error: 'section not found', id: req.params.id }); + res.json(found); +}); + +// Schemas +app.get('/api/ent-agi-gov-master/schemas', (_, res) => res.json(EAGV.schemas || {})); +app.get('/api/ent-agi-gov-master/schemas/:name', (req, res) => { + const s = (EAGV.schemas || {})[req.params.name]; + if (!s) return res.status(404).json({ error: 'schema not found', name: req.params.name }); + res.json(s); +}); + +// Code examples +app.get('/api/ent-agi-gov-master/code-examples', (_, res) => res.json(EAGV.codeExamples || {})); +app.get('/api/ent-agi-gov-master/code-examples/:name', (req, res) => { + const c = (EAGV.codeExamples || {})[req.params.name]; + if (!c) return res.status(404).json({ error: 'code example not found', name: req.params.name }); + res.type('text/plain').send(c); +}); + +// Case studies +app.get('/api/ent-agi-gov-master/case-studies', (_, res) => res.json(EAGV.caseStudies || [])); +app.get('/api/ent-agi-gov-master/case-studies/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const cs = (EAGV.caseStudies || []).find(c => (c.id || '').toUpperCase() === u); + if (!cs) return res.status(404).json({ error: 'case study not found', id: req.params.id }); + res.json(cs); +}); + +// ══════════════════════════════════════════════════════════════════════════════ +// SECTION 9.7: WFAP-GEMINI-IMPL-WP-036 — WorkflowAI Pro / GeminiService +// Enterprise Implementation Plan (2026-2030) +// 12 modules · 7 architecture planes · 9 data models · 8 data flows · +// 8 schemas · 12 code examples · 5 case studies · 75 API routes +// ══════════════════════════════════════════════════════════════════════════════ + +const WFAPG = require('./data/wfap-gemini-impl.json'); + +const WFAPG_MODULE_KEYS = [ + 'M1_architecture', + 'M2_dataModels', + 'M3_dataFlows', + 'M4_recommender', + 'M5_adaptiveUx', + 'M6_ragChat', + 'M7_promptCollab', + 'M8_modelRegistry', + 'M9_safetyReporting', + 'M10_geminiSecurity', + 'M11_taskReport', + 'M12_implementation', +]; + +function wfapgFindModule(mid) { + const u = String(mid || '').toUpperCase(); + for (const k of WFAPG_MODULE_KEYS) { + const m = WFAPG[k]; + if (m && (m.id || '').toUpperCase() === u) return m; + } + if (WFAPG[mid]) return WFAPG[mid]; + return null; +} + +function wfapgFindSection(sid) { + const u = String(sid || '').toUpperCase(); + for (const k of WFAPG_MODULE_KEYS) { + const m = WFAPG[k]; + for (const s of (m && m.sections) || []) { + if ((s.id || '').toUpperCase() === u) return { module: m.id, section: s }; + } + } + return null; +} + +// Root + summary +app.get('/api/wfap-gemini', (_, res) => res.json(WFAPG)); +app.get('/api/wfap-gemini/meta', (_, res) => res.json(WFAPG.meta || {})); +app.get('/api/wfap-gemini/executive-summary',(_, res) => res.json(WFAPG.executiveSummary || {})); +app.get('/api/wfap-gemini/summary', (_, res) => { + const meta = WFAPG.meta || {}; + res.json({ + docRef: meta.docRef, + version: meta.version, + title: meta.title, + horizon: meta.horizon, + classification:meta.classification, + modules: WFAPG_MODULE_KEYS.length, + architecturePlanes: ((WFAPG.M1_architecture && WFAPG.M1_architecture.sections[0] && WFAPG.M1_architecture.sections[0].planes) || []).length, + dataModels: ((WFAPG.M2_dataModels && WFAPG.M2_dataModels.sections[0] && WFAPG.M2_dataModels.sections[0].entities) || []).length, + dataFlows: ((WFAPG.M3_dataFlows && WFAPG.M3_dataFlows.sections[0] && WFAPG.M3_dataFlows.sections[0].flows) || []).length, + schemas: Object.keys(WFAPG.schemas || {}).length, + codeExamples: Object.keys(WFAPG.codeExamples || {}).length, + caseStudies: (WFAPG.caseStudies || []).length, + apiPrefix: '/api/wfap-gemini', + plannedRoutes: ((WFAPG.apiEndpoints && WFAPG.apiEndpoints.routes) || []).length, + }); +}); + +// Modules +app.get('/api/wfap-gemini/modules', (_, res) => { + const list = WFAPG_MODULE_KEYS.map(k => WFAPG[k]).filter(Boolean).map(m => ({ + id: m.id, title: m.title, summary: m.summary || '', + sectionCount: (m.sections || []).length, + })); + res.json(list); +}); +app.get('/api/wfap-gemini/modules/:id', (req, res) => { + const m = wfapgFindModule(req.params.id); + if (!m) return res.status(404).json({ error: 'module not found', id: req.params.id }); + res.json(m); +}); + +// Per-module shortcuts (M1-M12) +app.get('/api/wfap-gemini/m1', (_, res) => res.json(WFAPG.M1_architecture || {})); +app.get('/api/wfap-gemini/m2', (_, res) => res.json(WFAPG.M2_dataModels || {})); +app.get('/api/wfap-gemini/m3', (_, res) => res.json(WFAPG.M3_dataFlows || {})); +app.get('/api/wfap-gemini/m4', (_, res) => res.json(WFAPG.M4_recommender || {})); +app.get('/api/wfap-gemini/m5', (_, res) => res.json(WFAPG.M5_adaptiveUx || {})); +app.get('/api/wfap-gemini/m6', (_, res) => res.json(WFAPG.M6_ragChat || {})); +app.get('/api/wfap-gemini/m7', (_, res) => res.json(WFAPG.M7_promptCollab || {})); +app.get('/api/wfap-gemini/m8', (_, res) => res.json(WFAPG.M8_modelRegistry || {})); +app.get('/api/wfap-gemini/m9', (_, res) => res.json(WFAPG.M9_safetyReporting || {})); +app.get('/api/wfap-gemini/m10', (_, res) => res.json(WFAPG.M10_geminiSecurity || {})); +app.get('/api/wfap-gemini/m11', (_, res) => res.json(WFAPG.M11_taskReport || {})); +app.get('/api/wfap-gemini/m12', (_, res) => res.json(WFAPG.M12_implementation || {})); + +// Architecture +app.get('/api/wfap-gemini/architecture', (_, res) => res.json(WFAPG.M1_architecture || {})); +app.get('/api/wfap-gemini/architecture/planes', (_, res) => { + const sec = (WFAPG.M1_architecture && WFAPG.M1_architecture.sections[0]) || {}; + res.json(sec.planes || []); +}); +app.get('/api/wfap-gemini/architecture/topology', (_, res) => { + const sec = (WFAPG.M1_architecture && WFAPG.M1_architecture.sections[1]) || {}; + res.json(sec || {}); +}); +app.get('/api/wfap-gemini/architecture/tenancy', (_, res) => { + const sec = (WFAPG.M1_architecture && WFAPG.M1_architecture.sections[2]) || {}; + res.json(sec || {}); +}); + +// Data models +app.get('/api/wfap-gemini/data-models', (_, res) => { + const sec = (WFAPG.M2_dataModels && WFAPG.M2_dataModels.sections[0]) || {}; + res.json(sec.entities || []); +}); +app.get('/api/wfap-gemini/data-models/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const sec = (WFAPG.M2_dataModels && WFAPG.M2_dataModels.sections[0]) || {}; + const e = (sec.entities || []).find(x => (x.id || '').toUpperCase() === u); + if (!e) return res.status(404).json({ error: 'data model not found', id: req.params.id }); + res.json(e); +}); + +// Data flows +app.get('/api/wfap-gemini/data-flows', (_, res) => { + const sec = (WFAPG.M3_dataFlows && WFAPG.M3_dataFlows.sections[0]) || {}; + res.json(sec.flows || []); +}); +app.get('/api/wfap-gemini/data-flows/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const sec = (WFAPG.M3_dataFlows && WFAPG.M3_dataFlows.sections[0]) || {}; + const f = (sec.flows || []).find(x => (x.id || '').toUpperCase() === u); + if (!f) return res.status(404).json({ error: 'data flow not found', id: req.params.id }); + res.json(f); +}); + +// Recommender / adaptive UX / RAG / prompts / registry / safety / gemini / tasks / strategy — convenience routes +app.get('/api/wfap-gemini/recommender', (_, res) => res.json(WFAPG.M4_recommender || {})); +app.get('/api/wfap-gemini/recommender/active-learning', (_, res) => res.json(((WFAPG.M4_recommender||{}).sections||[]).find(s=>s.id==='M4-S2')||{})); +app.get('/api/wfap-gemini/recommender/apis', (_, res) => res.json(((WFAPG.M4_recommender||{}).sections||[]).find(s=>s.id==='M4-S4')||{})); + +app.get('/api/wfap-gemini/adaptive-ux', (_, res) => res.json(WFAPG.M5_adaptiveUx || {})); +app.get('/api/wfap-gemini/adaptive-ux/skill', (_, res) => res.json(((WFAPG.M5_adaptiveUx||{}).sections||[]).find(s=>s.id==='M5-S1')||{})); +app.get('/api/wfap-gemini/adaptive-ux/ethics', (_, res) => res.json(((WFAPG.M5_adaptiveUx||{}).sections||[]).find(s=>s.id==='M5-S3')||{})); + +app.get('/api/wfap-gemini/rag', (_, res) => res.json(WFAPG.M6_ragChat || {})); +app.get('/api/wfap-gemini/rag/retrieval', (_, res) => res.json(((WFAPG.M6_ragChat||{}).sections||[]).find(s=>s.id==='M6-S1')||{})); +app.get('/api/wfap-gemini/rag/faithfulness', (_, res) => res.json(((WFAPG.M6_ragChat||{}).sections||[]).find(s=>s.id==='M6-S2')||{})); +app.get('/api/wfap-gemini/rag/governance', (_, res) => res.json(((WFAPG.M6_ragChat||{}).sections||[]).find(s=>s.id==='M6-S3')||{})); +app.get('/api/wfap-gemini/rag/apis', (_, res) => res.json(((WFAPG.M6_ragChat||{}).sections||[]).find(s=>s.id==='M6-S4')||{})); + +app.get('/api/wfap-gemini/prompts', (_, res) => res.json(WFAPG.M7_promptCollab || {})); +app.get('/api/wfap-gemini/prompts/lifecycle', (_, res) => res.json(((WFAPG.M7_promptCollab||{}).sections||[]).find(s=>s.id==='M7-S1')||{})); +app.get('/api/wfap-gemini/prompts/collab', (_, res) => res.json(((WFAPG.M7_promptCollab||{}).sections||[]).find(s=>s.id==='M7-S2')||{})); +app.get('/api/wfap-gemini/prompts/lineage', (_, res) => res.json(((WFAPG.M7_promptCollab||{}).sections||[]).find(s=>s.id==='M7-S3')||{})); +app.get('/api/wfap-gemini/prompts/apis', (_, res) => res.json(((WFAPG.M7_promptCollab||{}).sections||[]).find(s=>s.id==='M7-S4')||{})); + +app.get('/api/wfap-gemini/registry', (_, res) => res.json(WFAPG.M8_modelRegistry || {})); +app.get('/api/wfap-gemini/registry/schema', (_, res) => res.json(((WFAPG.M8_modelRegistry||{}).sections||[]).find(s=>s.id==='M8-S1')||{})); +app.get('/api/wfap-gemini/registry/rbac', (_, res) => res.json(((WFAPG.M8_modelRegistry||{}).sections||[]).find(s=>s.id==='M8-S2')||{})); +app.get('/api/wfap-gemini/registry/tagging', (_, res) => res.json(((WFAPG.M8_modelRegistry||{}).sections||[]).find(s=>s.id==='M8-S3')||{})); +app.get('/api/wfap-gemini/registry/apis', (_, res) => res.json(((WFAPG.M8_modelRegistry||{}).sections||[]).find(s=>s.id==='M8-S4')||{})); + +app.get('/api/wfap-gemini/safety-reports', (_, res) => { + const sec = ((WFAPG.M9_safetyReporting||{}).sections||[]).find(s=>s.id==='M9-S1') || {}; + res.json(sec.reports || []); +}); +// Specific subroutes MUST be declared before the :id catch-all to avoid shadowing +app.get('/api/wfap-gemini/safety-reports/risks', (_, res) => res.json(((WFAPG.M9_safetyReporting||{}).sections||[]).find(s=>s.id==='M9-S2')||{})); +app.get('/api/wfap-gemini/safety-reports/intl-collab', (_, res) => res.json(((WFAPG.M9_safetyReporting||{}).sections||[]).find(s=>s.id==='M9-S3')||{})); +app.get('/api/wfap-gemini/safety-reports/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const sec = ((WFAPG.M9_safetyReporting||{}).sections||[]).find(s=>s.id==='M9-S1') || {}; + const r = (sec.reports || []).find(x => (x.id || '').toUpperCase() === u); + if (!r) return res.status(404).json({ error: 'safety report not found', id: req.params.id }); + res.json(r); +}); + +app.get('/api/wfap-gemini/gemini', (_, res) => res.json(WFAPG.M10_geminiSecurity || {})); +app.get('/api/wfap-gemini/gemini/gateway', (_, res) => res.json(((WFAPG.M10_geminiSecurity||{}).sections||[]).find(s=>s.id==='M10-S1')||{})); +app.get('/api/wfap-gemini/gemini/pre-call', (_, res) => res.json(((WFAPG.M10_geminiSecurity||{}).sections||[]).find(s=>s.id==='M10-S2')||{})); +app.get('/api/wfap-gemini/gemini/post-call', (_, res) => res.json(((WFAPG.M10_geminiSecurity||{}).sections||[]).find(s=>s.id==='M10-S3')||{})); +app.get('/api/wfap-gemini/gemini/telemetry', (_, res) => res.json(((WFAPG.M10_geminiSecurity||{}).sections||[]).find(s=>s.id==='M10-S4')||{})); +app.get('/api/wfap-gemini/gemini/adversarial', (_, res) => res.json(((WFAPG.M10_geminiSecurity||{}).sections||[]).find(s=>s.id==='M10-S5')||{})); +app.get('/api/wfap-gemini/gemini/apis', (_, res) => res.json(((WFAPG.M10_geminiSecurity||{}).sections||[]).find(s=>s.id==='M10-S6')||{})); + +app.get('/api/wfap-gemini/tasks-reports', (_, res) => res.json(WFAPG.M11_taskReport || {})); +app.get('/api/wfap-gemini/tasks-reports/tasks', (_, res) => res.json(((WFAPG.M11_taskReport||{}).sections||[]).find(s=>s.id==='M11-S1')||{})); +app.get('/api/wfap-gemini/tasks-reports/reports', (_, res) => res.json(((WFAPG.M11_taskReport||{}).sections||[]).find(s=>s.id==='M11-S2')||{})); +app.get('/api/wfap-gemini/tasks-reports/apis', (_, res) => res.json(((WFAPG.M11_taskReport||{}).sections||[]).find(s=>s.id==='M11-S3')||{})); + +app.get('/api/wfap-gemini/strategy', (_, res) => res.json(WFAPG.M12_implementation || {})); +app.get('/api/wfap-gemini/strategy/phases', (_, res) => { + const sec = ((WFAPG.M12_implementation||{}).sections||[]).find(s=>s.id==='M12-S1') || {}; + res.json(sec.phases || []); +}); +app.get('/api/wfap-gemini/strategy/boundaries', (_, res) => res.json(((WFAPG.M12_implementation||{}).sections||[]).find(s=>s.id==='M12-S2')||{})); +app.get('/api/wfap-gemini/strategy/integration', (_, res) => res.json(((WFAPG.M12_implementation||{}).sections||[]).find(s=>s.id==='M12-S3')||{})); +app.get('/api/wfap-gemini/strategy/kpis', (_, res) => { + const sec = ((WFAPG.M12_implementation||{}).sections||[]).find(s=>s.id==='M12-S4') || {}; + res.json(sec.kpis || []); +}); +app.get('/api/wfap-gemini/strategy/risks', (_, res) => { + const sec = ((WFAPG.M12_implementation||{}).sections||[]).find(s=>s.id==='M12-S5') || {}; + res.json(sec.risks || []); +}); + +// Sections lookup (cross-module) +app.get('/api/wfap-gemini/sections/:id', (req, res) => { + const found = wfapgFindSection(req.params.id); + if (!found) return res.status(404).json({ error: 'section not found', id: req.params.id }); + res.json(found); +}); + +// Schemas +app.get('/api/wfap-gemini/schemas', (_, res) => res.json(WFAPG.schemas || {})); +app.get('/api/wfap-gemini/schemas/:name', (req, res) => { + const s = (WFAPG.schemas || {})[req.params.name]; + if (!s) return res.status(404).json({ error: 'schema not found', name: req.params.name }); + res.json(s); +}); + +// Code examples +app.get('/api/wfap-gemini/code-examples', (_, res) => res.json(WFAPG.codeExamples || {})); +app.get('/api/wfap-gemini/code-examples/:name', (req, res) => { + const c = (WFAPG.codeExamples || {})[req.params.name]; + if (!c) return res.status(404).json({ error: 'code example not found', name: req.params.name }); + res.type('text/plain').send(c); +}); + +// Case studies +app.get('/api/wfap-gemini/case-studies', (_, res) => res.json(WFAPG.caseStudies || [])); +app.get('/api/wfap-gemini/case-studies/:id', (req, res) => { + const u = req.params.id.toUpperCase(); + const cs = (WFAPG.caseStudies || []).find(c => (c.id || '').toUpperCase() === u); + if (!cs) return res.status(404).json({ error: 'case study not found', id: req.params.id }); + res.json(cs); +}); + // SECTION 10: START SERVER // ══════════════════════════════════════════════════════════════════════════════