/**
 * SINT Protocol — OWASP Agentic Top 10 coverage map.
 *
 * Formal declaration of which OWASP ASI categories SINT addresses,
 * at what coverage level, and via which components.
 *
 * @module @sint/core/constants/compliance
 */

import { ApprovalTier } from "../types/policy.js";
import {
  OwaspAsi,
  type OwaspCoverageEntry,
  type SintTierComplianceCrosswalkEntry,
} from "../types/compliance.js";

/**
 * SINT Protocol OWASP Agentic Top 10 coverage.
 *
 * Coverage summary:
 *   Full    (8/10): ASI01, ASI02, ASI03, ASI04, ASI07, ASI08, ASI09, ASI10
 *   Partial (2/10): ASI05, ASI06
 *   None    (0/10)
 */
export const SINT_OWASP_COVERAGE: readonly OwaspCoverageEntry[] = [
  {
    category: OwaspAsi.ASI01_GOAL_HIJACK,
    level: "full",
    implementedBy: [
      "@pshkv/gate-policy-gateway (forbidden-combos)",
      "@pshkv/avatar (CSML drift detection)",
      "@pshkv/gate-policy-gateway (GoalHijackPlugin)",
    ],
    description:
      "Forbidden action-sequence detection catches known goal-hijack patterns " +
      "(e.g., read + exfiltrate combo). CSML drift score detects anomalous " +
      "action-frequency shifts that may indicate injected objectives. " +
      "GoalHijackPlugin provides 5-layer heuristic detection of prompt injection, " +
      "role override, semantic escalation, exfiltration probes, and cross-agent injection.",
  },
  {
    category: OwaspAsi.ASI02_TOOL_MISUSE,
    level: "full",
    implementedBy: [
      "@pshkv/bridge-mcp (TAM enforcement)",
      "@pshkv/gate-policy-gateway (tier assignment)",
      "@pshkv/gate-capability-tokens (resource scope)",
    ],
    description:
      "Tool Authorization Manifests (TAM) define per-tool security requirements. " +
      "Every MCP tool call is validated against the manifest before execution. " +
      "Capability token resource scope ensures tools can only be called within " +
      "the authorized resource pattern.",
  },
  {
    category: OwaspAsi.ASI03_IDENTITY_ABUSE,
    level: "full",
    implementedBy: [
      "@pshkv/gate-capability-tokens (Ed25519 signing)",
      "@pshkv/gate-capability-tokens (did:key identity)",
      "@pshkv/gate-capability-tokens (delegation chain)",
    ],
    description:
      "Every capability token is Ed25519-signed with the issuer's private key. " +
      "Agent identity = did:key (Ed25519 public key). Delegation chain is verified " +
      "at every level — a forged token or broken chain is rejected at step 2 of intercept(). " +
      "Revocation store provides instant invalidation.",
  },
  {
    category: OwaspAsi.ASI04_SUPPLY_CHAIN,
    level: "full",
    implementedBy: [
      "@pshkv/bridge-mcp (TAM manifest validation)",
      "@pshkv/gate-capability-tokens (Ed25519 plugin signing)",
      "@pshkv/gate-policy-gateway (DefaultSupplyChainVerifier)",
    ],
    description:
      "TAM manifests are defined by the operator (not the tool provider) — " +
      "a malicious tool cannot self-declare elevated permissions. " +
      "All tool schemas are validated against the operator-controlled manifest " +
      "before any call is forwarded. DefaultSupplyChainVerifier checks model " +
      "fingerprint hash, model ID allowlist, and bridge protocol consistency " +
      "at runtime to detect tampered tools or swapped model versions.",
  },
  {
    category: OwaspAsi.ASI05_CODE_EXECUTION,
    level: "partial",
    implementedBy: [
      "@pshkv/gate-policy-gateway (forbidden-combos)",
      "@pshkv/engine-capsule-sandbox (isolation)",
    ],
    description:
      "Capsule sandbox provides process-level isolation for agent execution. " +
      "Forbidden combo rules block known shell-execution sequences.",
    gaps:
      "No semantic analysis of tool arguments for code injection. " +
      "Shell tool calls are not specifically classified at T3_COMMIT tier by default.",
  },
  {
    category: OwaspAsi.ASI06_MEMORY_POISONING,
    level: "partial",
    implementedBy: [
      "@pshkv/gate-policy-gateway (DefaultMemoryIntegrityChecker)",
    ],
    description:
      "DefaultMemoryIntegrityChecker detects history anomalies: suspicious " +
      "repetition (replay attack), unauthorized privilege claims in recentActions, " +
      "history length overflow, and UUIDv7 timestamp monotonicity violations. " +
      "High-severity anomalies (privilege claims, timestamp rollback) → deny. " +
      "Medium/low → warn-and-allow with audit event.",
    gaps:
      "Memory store not yet persisted — checker state is per-gateway-instance only. " +
      "No semantic analysis of memory embedding space for vector poisoning. " +
      "Cross-session memory continuity not yet verified.",
  },
  {
    category: OwaspAsi.ASI07_INTER_AGENT,
    level: "full",
    implementedBy: [
      "@pshkv/bridge-a2a (A2A protocol enforcement)",
      "@pshkv/gate-capability-tokens (did:key per agent)",
    ],
    description:
      "A2A bridge validates the sender's capability token before processing " +
      "any inter-agent message. Each agent's identity is a did:key — " +
      "spoofed messages from unknown or unauthorized senders are rejected. " +
      "APS↔SINT interop mapping covers cross-org agent communication.",
  },
  {
    category: OwaspAsi.ASI08_CASCADE,
    level: "full",
    implementedBy: [
      "@pshkv/gate-policy-gateway (CircuitBreakerPlugin)",
      "@pshkv/gate-policy-gateway (rate limiting)",
      "@pshkv/bridge-swarm (SwarmCoordinator collective constraints)",
    ],
    description:
      "CircuitBreakerPlugin opens the circuit (OPEN state) when an agent trips " +
      "N consecutive denials — all subsequent requests auto-deny without processing. " +
      "Rate limiting prevents runaway tool-call storms. SwarmCoordinator caps " +
      "collective kinetic energy Σ(½mv²) and escalated-fraction across fleets.",
  },
  {
    category: OwaspAsi.ASI09_TRUST_EXPLOIT,
    level: "full",
    implementedBy: [
      "@pshkv/gate-policy-gateway (T2/T3 human approval)",
      "@pshkv/gate-policy-gateway (M-of-N quorum)",
      "@pshkv/avatar (CSML drift detection)",
    ],
    description:
      "T2_act requires operator review before physical execution. " +
      "T3_commit requires explicit human sign-off with configurable M-of-N quorum. " +
      "CSML drift detection auto-escalates agents showing deceptive behavioral patterns " +
      "(anomalous persona) regardless of their token tier.",
  },
  {
    category: OwaspAsi.ASI10_ROGUE_AGENT,
    level: "full",
    implementedBy: [
      "@pshkv/gate-policy-gateway (CircuitBreakerPlugin)",
      "@pshkv/avatar (CSML anomalous persona)",
      "@pshkv/gate-policy-gateway (DynamicEnvelopePlugin)",
    ],
    description:
      "CircuitBreakerPlugin provides the EU AI Act Article 14(4)(e) 'stop button': " +
      "operators can manually trip() the circuit, instantly blocking all actions " +
      "from an agent. CSML anomalous persona auto-trips the circuit when safety events " +
      "are detected. DynamicEnvelopePlugin enforces environment-adaptive physical limits " +
      "even when the agent presents a valid token.",
  },
] as const;

/**
 * SINT approval-tier mapping to NIST AI RMF / ISO 42001 / EU AI Act obligations.
 *
 * This is an implementation-focused crosswalk for agentic/physical AI deployments.
 * It is not legal advice; organizations should still validate obligations against
 * their sector and deployment context.
 */
export const SINT_TIER_COMPLIANCE_CROSSWALK: readonly SintTierComplianceCrosswalkEntry[] = [
  {
    tier: ApprovalTier.T0_OBSERVE,
    consequenceClass: "monitoring",
    mappings: [
      {
        framework: "nist-ai-rmf-1.0",
        reference: "MAP + MEASURE + MANAGE (low-consequence monitoring path)",
        requirement: "Continuously monitor model behavior and retain traceable records.",
        sintEnforcement: "Auto-approved T0 requests are still ledgered with immutable evidence events.",
      },
      {
        framework: "iso-iec-42001-2023",
        reference: "Clause 9 (performance evaluation) + Clause 8 (operational controls)",
        requirement: "Monitor AI system performance and keep auditable operational controls.",
        sintEnforcement: "Per-request policy decisions and evidence telemetry provide operational monitoring baselines.",
      },
      {
        framework: "eu-ai-act-2024-1689",
        reference: "Article 12 (record-keeping) + Article 13 (transparency)",
        requirement: "Maintain logs and transparent technical documentation for AI behavior.",
        sintEnforcement: "Read-path decisions are hash-chained and queryable via ledger/discovery endpoints.",
      },
    ],
  },
  {
    tier: ApprovalTier.T1_PREPARE,
    consequenceClass: "bounded-write",
    mappings: [
      {
        framework: "nist-ai-rmf-1.0",
        reference: "GOVERN + MANAGE (controlled low-impact action path)",
        requirement: "Apply governance controls before low-impact state mutation.",
        sintEnforcement: "Capability tokens, scoped actions, and rate limits gate bounded write operations.",
      },
      {
        framework: "iso-iec-42001-2023",
        reference: "Clause 8.1/8.2 (operational planning and AI risk treatment)",
        requirement: "Treat operational AI risk before deployment-stage actions.",
        sintEnforcement: "Tier assignment and constraints are evaluated before every write-style request.",
      },
      {
        framework: "eu-ai-act-2024-1689",
        reference: "Article 9 (risk management) + Article 12 (logging)",
        requirement: "Keep risk controls active and auditable during operation.",
        sintEnforcement: "Gateway policy checks and ledger evidence enforce and document bounded action controls.",
      },
    ],
  },
  {
    tier: ApprovalTier.T2_ACT,
    consequenceClass: "physical-state-change",
    mappings: [
      {
        framework: "nist-ai-rmf-1.0",
        reference: "MANAGE (risk response) + GOVERN (accountability for high-impact operation)",
        requirement: "Escalate and govern physical-impact actions with human accountability.",
        sintEnforcement: "T2 actions require escalation to approval flow; optional quorum and attestation are enforced.",
      },
      {
        framework: "iso-iec-42001-2023",
        reference: "Clause 8 (operational control) + Clause 6 (risk planning)",
        requirement: "Apply explicit controls for AI operations that alter physical state.",
        sintEnforcement: "Physical constraints (force/velocity/geofence) are enforced at token and gateway levels.",
      },
      {
        framework: "eu-ai-act-2024-1689",
        reference: "Article 14 (human oversight) + Article 15 (accuracy/robustness/cybersecurity)",
        requirement: "Maintain effective human oversight and robust behavior for high-impact AI actions.",
        sintEnforcement: "T2 escalation, dynamic envelopes, and deterministic deny paths enforce fail-safe oversight.",
      },
    ],
  },
  {
    tier: ApprovalTier.T3_COMMIT,
    consequenceClass: "irreversible-commit",
    mappings: [
      {
        framework: "nist-ai-rmf-1.0",
        reference: "GOVERN + MANAGE (highest-consequence decision authority)",
        requirement: "Apply strongest accountability and control to irreversible actions.",
        sintEnforcement: "T3 requires explicit human sign-off (with optional M-of-N quorum) before commit.",
      },
      {
        framework: "iso-iec-42001-2023",
        reference: "Clause 8.3 (risk treatment implementation) + Clause 10 (continual improvement)",
        requirement: "Execute highest-severity controls and corrective feedback loops.",
        sintEnforcement: "Commit-tier actions require evidence-backed approvals and post-incident traceability.",
      },
      {
        framework: "eu-ai-act-2024-1689",
        reference: "Article 14(4)(e) (human override/stop) + Articles 9/12/15",
        requirement: "Support immediate human intervention with rigorous logging and safety robustness.",
        sintEnforcement: "Circuit-breaker stop control, T3 approval gates, and tamper-evident ledger receipts are mandatory controls.",
      },
    ],
  },
] as const;
