import { AlertCircle, CheckCircle, ChevronDown, ChevronUp, Clock, Download, History, Play, RefreshCw, Zap, } from 'lucide-react'; import { useEffect, useState } from 'react'; interface SignalChainStep { id: string; domain: string; action: string; status: 'pending' | 'executed' | 'skipped' | 'failed'; executedAt?: number; explainability: string; resultSummary?: string; } interface SignalChainExecution { executionId: string; chainId: string; triggeredAt: number; triggerReason: string; triggerValue: number; threshold: number; steps: SignalChainStep[]; status: 'running' | 'completed' | 'failed'; } interface SignalChain { id: string; name: string; description: string; triggerDomain: string; triggerSignal: string; triggerThreshold: number; targetDomains: string[]; severity: 'critical' | 'high' | 'medium' | 'low'; enabled: boolean; executionCount: number; lastExecuted?: number; stepCount: number; lastExecution?: SignalChainExecution; } interface AuditRow { id: number; chainId: string; triggerDomain: string; payloadSnapshot: { executionId: string; triggerReason: string; triggerValue: number; threshold: number; auditRef?: string; } | null; outcomes: SignalChainStep[] | null; triggeredAt: string; status: 'running' | 'completed' | 'failed'; } const DOMAIN_COLORS: Record = { vessels: 'var(--gi-accent-blue)', aegis: '#ef4444', terra: '#22c55e', prism: '#8b5cf6', lyte: '#f59e0b', 'szl-holdings': '#8b7ac8', }; const SEVERITY_COLORS: Record = { critical: '#ef4444', high: '#f59e0b', medium: '#3b82f6', low: '#6b7280', }; const STATUS_COLORS: Record = { completed: '#22c55e', failed: '#ef4444', running: '#f59e0b', }; const DEMO_CHAINS: SignalChain[] = [ { id: 'sc-fleet-reroute', name: 'Fleet Reroute on Weather Alert', description: 'When weather severity exceeds threshold in an active shipping corridor, notify fleet ops and queue route optimization across affected vessels.', triggerDomain: 'vessels', triggerSignal: 'weather_severity_score', triggerThreshold: 0.7, targetDomains: ['terra', 'szl-holdings'], severity: 'high', enabled: true, executionCount: 14, lastExecuted: Date.now() - 3600000, stepCount: 4, lastExecution: { executionId: 'exec-fleet-0042', chainId: 'sc-fleet-reroute', triggeredAt: Date.now() - 3600000, triggerReason: 'Bay of Bengal weather severity score reached 0.78 (threshold: 0.70)', triggerValue: 0.78, threshold: 0.7, status: 'completed', steps: [ { id: 'step-1', domain: 'vessels', action: 'Identify affected vessels', status: 'executed', executedAt: Date.now() - 3540000, explainability: 'Queried fleet positions — 3 vessels within affected corridor identified', resultSummary: 'MV Meridian, MV Catalyst, MV Horizon flagged', }, { id: 'step-2', domain: 'vessels', action: 'Queue route optimization', status: 'executed', executedAt: Date.now() - 3480000, explainability: 'Route optimization tasks queued for 3 vessels based on alternate corridor data', resultSummary: 'Estimated $180K fuel savings if approved', }, { id: 'step-3', domain: 'terra', action: 'Flag logistics-dependent properties', status: 'executed', executedAt: Date.now() - 3420000, explainability: 'Identified 12 DOMAINE properties with active port logistics dependencies', resultSummary: '12 assets flagged for delivery timeline review', }, { id: 'step-4', domain: 'szl-holdings', action: 'Update executive briefing', status: 'executed', executedAt: Date.now() - 3360000, explainability: 'Morning digest updated with fleet reroute context and estimated impact', resultSummary: 'Digest updated — financial exposure: ~$320K', }, ], }, }, { id: 'sc-cyber-escalate', name: 'Perimeter Breach → Legal Hold', description: 'When PARAGON detects a confirmed intrusion exceeding critical threshold, automatically trigger legal hold across affected subsidiaries and notify CISO.', triggerDomain: 'aegis', triggerSignal: 'intrusion_confidence_score', triggerThreshold: 0.85, targetDomains: ['szl-holdings', 'prism'], severity: 'critical', enabled: true, executionCount: 3, lastExecuted: Date.now() - 1800000, stepCount: 3, lastExecution: { executionId: 'exec-cyber-0011', chainId: 'sc-cyber-escalate', triggeredAt: Date.now() - 1800000, triggerReason: 'APT-41 lateral movement confidence score reached 0.97 (threshold: 0.85)', triggerValue: 0.97, threshold: 0.85, status: 'completed', steps: [ { id: 'step-1', domain: 'aegis', action: 'Isolate affected network segments', status: 'executed', executedAt: Date.now() - 1740000, explainability: 'Network isolation applied to 3 subsidiary segments exhibiting lateral movement indicators', }, { id: 'step-2', domain: 'szl-holdings', action: 'Trigger legal hold', status: 'executed', executedAt: Date.now() - 1680000, explainability: 'Legal hold initiated across 3 subsidiaries per incident response protocol', }, { id: 'step-3', domain: 'prism', action: 'Generate threat intelligence brief', status: 'executed', executedAt: Date.now() - 1620000, explainability: 'PRISM cross-domain pattern analysis completed — brief delivered to CISO and Legal', }, ], }, }, { id: 'sc-market-vol', name: 'Market Volatility → Portfolio Rebalance', description: 'When Holdings volatility index exceeds 0.70, trigger asset review across DOMAINE and SEXTANT, and queue rebalancing recommendation for the investment committee.', triggerDomain: 'szl-holdings', triggerSignal: 'market_volatility_index', triggerThreshold: 0.7, targetDomains: ['terra', 'vessels'], severity: 'medium', enabled: true, executionCount: 7, lastExecuted: Date.now() - 7200000, stepCount: 3, }, { id: 'sc-slo-breach', name: 'SLO Breach → On-Call Escalation', description: 'When KORA platform error budget drops below 10%, automatically page the on-call team and pause non-critical deployments.', triggerDomain: 'lyte', triggerSignal: 'error_budget_remaining', triggerThreshold: 0.1, targetDomains: ['lyte'], severity: 'high', enabled: false, executionCount: 2, lastExecuted: Date.now() - 86400000 * 3, stepCount: 2, }, ]; function timeAgo(ts?: number | string) { if (!ts) return 'Never'; const diff = Date.now() - (typeof ts === 'string' ? new Date(ts).getTime() : ts); if (diff < 60000) return 'Just now'; if (diff < 3600000) return `${Math.round(diff / 60000)}m ago`; if (diff < 86400000) return `${Math.round(diff / 3600000)}h ago`; return `${Math.round(diff / 86400000)}d ago`; } interface SignalChainsPanelProps { apiBase?: string; } export function SignalChainsPanel({ apiBase = '' }: SignalChainsPanelProps) { const [chains, setChains] = useState([]); const [loading, setLoading] = useState(true); const [isDemo, setIsDemo] = useState(null); const [triggering, setTriggering] = useState(null); const [expanded, setExpanded] = useState(null); const [auditView, setAuditView] = useState(null); const [auditRows, setAuditRows] = useState>({}); const [auditLoading, setAuditLoading] = useState(null); const [auditHasMore, setAuditHasMore] = useState>({}); const [auditTotal, setAuditTotal] = useState>({}); async function fetchChains() { setLoading(true); try { const res = await fetch(`${apiBase}/api/signal-chains`); if (res.status === 401 || res.status === 403) { if (chains.length === 0) { setChains(DEMO_CHAINS); setIsDemo(true); } return; } const data = await res.json(); if (data.success && Array.isArray(data.chains) && data.chains.length > 0) { setChains(data.chains); setIsDemo(false); } else if (chains.length === 0) { setChains(DEMO_CHAINS); setIsDemo(true); } } catch { if (chains.length === 0) { setChains(DEMO_CHAINS); setIsDemo(true); } } finally { setLoading(false); } } async function fetchAudit(chainId: string, append = false) { setAuditLoading(chainId); try { const currentRows = append ? (auditRows[chainId] ?? []) : []; const offset = append ? currentRows.length : 0; const res = await fetch( `${apiBase}/api/signal-chains/${chainId}/audit?limit=25&offset=${offset}`, ); const data = await res.json(); if (data.success) { const newRows = append ? [...currentRows, ...data.entries] : data.entries; setAuditRows((prev) => ({ ...prev, [chainId]: newRows })); setAuditHasMore((prev) => ({ ...prev, [chainId]: !!data.hasMore })); setAuditTotal((prev) => ({ ...prev, [chainId]: data.total ?? 0 })); } } catch { /* ignore */ } finally { setAuditLoading(null); } } const isDemoChain = (chainId: string) => DEMO_CHAINS.some((c) => c.id === chainId) && chains.every((c) => DEMO_CHAINS.some((d) => d.id === c.id)); async function triggerChain(chainId: string) { setTriggering(chainId); if (isDemoChain(chainId)) { await new Promise((resolve) => setTimeout(resolve, 1800)); setChains((prev) => prev.map((c) => { if (c.id !== chainId) return c; const demoChain = DEMO_CHAINS.find((d) => d.id === chainId); const existingExecution = demoChain?.lastExecution ?? c.lastExecution; const now = Date.now(); const simulatedExecution: SignalChainExecution = existingExecution ? { ...existingExecution, executionId: `exec-sim-${Math.floor(Math.random() * 9000) + 1000}`, triggeredAt: now, triggerReason: existingExecution.triggerReason.replace( /\d+m ago|\d+h ago|\d+d ago|Just now/, 'Just now', ), status: 'completed', steps: existingExecution.steps.map((s) => ({ ...s, executedAt: now, })), } : { executionId: `exec-sim-${Math.floor(Math.random() * 9000) + 1000}`, chainId: c.id, triggeredAt: now, triggerReason: `${c.triggerSignal} threshold of ${c.triggerThreshold} exceeded — manual trigger initiated`, triggerValue: c.triggerThreshold * 1.1, threshold: c.triggerThreshold, status: 'completed', steps: Array.from({ length: c.stepCount }, (_, i) => ({ id: `step-${i + 1}`, domain: i === 0 ? c.triggerDomain : (c.targetDomains[i - 1] ?? c.triggerDomain), action: i === 0 ? `Evaluate ${c.triggerSignal} signal` : `Execute action on ${c.targetDomains[i - 1] ?? c.triggerDomain}`, status: 'executed' as const, executedAt: now + i * 30000, explainability: `Step ${i + 1} completed successfully as part of automated chain execution`, })), }; return { ...c, executionCount: c.executionCount + 1, lastExecuted: now, lastExecution: simulatedExecution, }; }), ); setExpanded(chainId); setTriggering(null); return; } try { const res = await fetch(`${apiBase}/api/signal-chains/${chainId}/trigger`, { method: 'POST', }); const data = await res.json(); if (data.success) { setChains((prev) => prev.map((c) => c.id === chainId ? { ...c, executionCount: c.executionCount + 1, lastExecuted: Date.now(), lastExecution: data.execution, } : c, ), ); setExpanded(chainId); if (auditView === chainId) { await fetchAudit(chainId); } } } catch { /* ignore */ } finally { setTriggering(null); } } function toggleAudit(chainId: string) { if (auditView === chainId) { setAuditView(null); } else { setAuditView(chainId); if (!auditRows[chainId]) { fetchAudit(chainId); } } } function exportCsv(chainId?: string) { const params = new URLSearchParams({ format: 'csv' }); if (chainId) params.set('chainId', chainId); const url = `${apiBase}/api/signal-chains/audit-log/export?${params.toString()}`; const a = document.createElement('a'); a.href = url; a.download = ''; document.body.appendChild(a); a.click(); document.body.removeChild(a); } useEffect(() => { fetchChains(); }, []); return (

Autonomous Signal Chains

{!loading && isDemo === true && ( Demo )} {!loading && isDemo === false && ( Live )} {chains.length > 0 && ( {chains.filter((c) => c.enabled).length} active )}
{loading && (
Loading signal chains…
)}
{chains.map((chain) => { const severityColor = SEVERITY_COLORS[chain.severity] ?? '#6b7280'; const domainColor = DOMAIN_COLORS[chain.triggerDomain] ?? '#6b7280'; const isExpanded = expanded === chain.id; const isAuditOpen = auditView === chain.id; const chainAuditRows = auditRows[chain.id] ?? []; return (
{chain.triggerDomain} {chain.targetDomains.map((td) => ( {td} ))}

{chain.name}

{chain.description}

{chain.severity}
{chain.enabled ? 'Active' : 'Paused'}
{chain.stepCount} steps · {chain.executionCount} executions
Last: {timeAgo(chain.lastExecuted)}
{chain.lastExecution && ( )}
{isExpanded && chain.lastExecution && (
Execution Audit Trail · {chain.lastExecution.executionId}
Trigger: {chain.lastExecution.triggerReason} (value: {chain.lastExecution.triggerValue} vs threshold:{' '} {chain.lastExecution.threshold})
{chain.lastExecution.steps.map((step, i) => (
0 ? '1px solid var(--color-surface-border)' : undefined, }} >
{step.status === 'executed' ? ( ) : step.status === 'failed' ? ( ) : ( )}
{step.domain} {step.action}

{step.explainability}

))}
)} {isAuditOpen && (
Persistent Audit Trail · DB
{(auditTotal[chain.id] ?? 0) > 0 && ( {auditTotal[chain.id]} total )}
{auditLoading === chain.id && chainAuditRows.length === 0 && (
Loading audit history…
)} {auditLoading !== chain.id && chainAuditRows.length === 0 && (
No persistent executions yet. Trigger the chain to begin building an audit trail.
)} {chainAuditRows.map((row) => (
{row.status} #{row.id}
{timeAgo(row.triggeredAt)}
{row.payloadSnapshot && (
Trigger: {row.payloadSnapshot.triggerReason} ({row.payloadSnapshot.triggerValue} vs {row.payloadSnapshot.threshold} )
)} {row.outcomes && Array.isArray(row.outcomes) && row.outcomes.length > 0 && (
{(row.outcomes as SignalChainStep[]).map((step, i) => (
{step.explainability}
))}
)}
))} {chainAuditRows.length > 0 && auditHasMore[chain.id] && ( )} {chainAuditRows.length > 0 && !auditHasMore[chain.id] && (
All {auditTotal[chain.id]} execution {(auditTotal[chain.id] ?? 0) !== 1 ? 's' : ''} shown
)}
)}
); })}
); }