-- Agent Governance Ledger Schema

CREATE TABLE IF NOT EXISTS agent_actions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp TEXT NOT NULL,
    agent_id TEXT NOT NULL,
    agent_version TEXT NOT NULL,
    tier INTEGER NOT NULL,
    action TEXT NOT NULL,
    decision TEXT NOT NULL,
    confidence REAL NOT NULL,
    target TEXT,
    side_effects TEXT,  -- JSON array
    success INTEGER NOT NULL,  -- 0 or 1
    error_type TEXT,
    error_message TEXT,
    vault_token_accessor TEXT,
    session_id TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS agent_metrics (
    agent_id TEXT PRIMARY KEY,
    current_tier INTEGER DEFAULT 0,
    compliant_runs INTEGER DEFAULT 0,
    consecutive_compliant INTEGER DEFAULT 0,
    total_runs INTEGER DEFAULT 0,
    last_violation_at TEXT,
    last_active_at TEXT,
    promotion_eligible INTEGER DEFAULT 0,
    updated_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS violations (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp TEXT NOT NULL,
    agent_id TEXT NOT NULL,
    violation_type TEXT NOT NULL,
    severity TEXT NOT NULL,  -- low, medium, high, critical
    description TEXT NOT NULL,
    triggering_action TEXT,
    evidence TEXT,  -- JSON
    remediation TEXT,
    acknowledged INTEGER DEFAULT 0,
    acknowledged_by TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS promotions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp TEXT NOT NULL,
    agent_id TEXT NOT NULL,
    from_tier INTEGER NOT NULL,
    to_tier INTEGER NOT NULL,
    approved_by TEXT NOT NULL,
    rationale TEXT,
    evidence TEXT,  -- JSON: compliant runs, etc.
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_actions_agent ON agent_actions(agent_id);
CREATE INDEX IF NOT EXISTS idx_actions_timestamp ON agent_actions(timestamp);
CREATE INDEX IF NOT EXISTS idx_violations_agent ON violations(agent_id);
CREATE INDEX IF NOT EXISTS idx_violations_severity ON violations(severity);
