diff --git a/src/agent-adapter-model.ts b/src/agent-adapter-model.ts deleted file mode 100644 index 9a1e518c..00000000 --- a/src/agent-adapter-model.ts +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Agent-Specific Adapters — data models - * Adapters for Claude, Cursor, Cline with introspection, automation, collaboration - */ - -export type AgentType = "claude" | "cursor" | "cline" | "generic"; -export type AdapterStatus = "unknown" | "not_installed" | "installed" | "configured" | "active"; -export type CapabilityType = - | "file_read" - | "file_write" - | "code_execution" - | "terminal_access" - | "git_integration" - | "debugging" - | "testing" - | "ai_collaboration" - | "workspace_awareness" - | "context_management"; -export type CollaborationMode = "sequential" | "parallel" | "competitive" | "hierarchical"; - -export interface AgentProfile { - id: string; - agent_type: AgentType; - version: string; - name: string; - description?: string; - capabilities: CapabilityType[]; - config_required: string[]; // Required config keys - optional_config: string[]; - installation_method: "npm" | "manual" | "extension" | "cli"; - homepage?: string; - documentation?: string; - created_at: string; - updated_at: string; -} - -export interface AgentAdapter { - id: string; - team_id: string; - agent_type: AgentType; - agent_profile_id: string; - status: AdapterStatus; - version: string; - installed_at?: string; - configured_at?: string; - config: Record; - enabled_capabilities: CapabilityType[]; - disabled_capabilities: CapabilityType[]; - health_status: "healthy" | "degraded" | "error"; - last_health_check?: string; - created_at: string; - updated_at: string; -} - -export interface AgentCapability { - id: string; - adapter_id: string; - team_id: string; - capability_type: CapabilityType; - enabled: boolean; - required_config: Record; - permissions_required: string[]; - rate_limit?: number; // Operations per minute - timeout_ms?: number; - last_used?: string; - usage_count: number; - created_at: string; - updated_at: string; -} - -export interface AgentIntrospection { - id: string; - team_id: string; - adapter_id: string; - introspection_type: "capabilities" | "context" | "state" | "performance" | "health"; - data: Record; - timestamp: string; - ttl_seconds: number; -} - -export interface AgentAutomation { - id: string; - team_id: string; - adapter_id: string; - automation_name: string; - description?: string; - trigger: string; // Event or schedule - actions: string[]; // Actions to execute - enabled: boolean; - run_count: number; - last_run?: string; - error_count: number; - created_at: string; - updated_at: string; -} - -export interface AgentCollaboration { - id: string; - team_id: string; - collaboration_id: string; - agents: { - adapter_id: string; - agent_type: AgentType; - role: "primary" | "secondary" | "observer"; - }[]; - mode: CollaborationMode; - shared_context: Record; - status: "active" | "paused" | "completed" | "failed"; - created_at: string; - updated_at: string; - completed_at?: string; -} - -export interface AgentMetrics { - adapter_id: string; - agent_type: AgentType; - health_score: number; // 0-100 - uptime_percent: number; - capability_coverage: number; // Enabled capabilities / total available - average_latency_ms: number; - error_rate_percent: number; - last_activity: string; - collaborations_active: number; - automations_active: number; - operations_today: number; -} diff --git a/src/agent-adapter-service.test.ts b/src/agent-adapter-service.test.ts deleted file mode 100644 index ae588c5f..00000000 --- a/src/agent-adapter-service.test.ts +++ /dev/null @@ -1,289 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { - registerAgentAdapter, - getAdapterStatus, - checkCapabilities, - toggleCapability, - introspectAgent, - createAutomation, - setupCollaboration, - getAdapterMetrics, - listTeamAdapters, - getCollaborationStatus, -} from "./agent-adapter-service.js"; - -describe("agent-adapter-service", () => { - const teamId = "team-agents-123"; - - describe("registerAgentAdapter", () => { - it("registers Claude adapter", () => { - const { adapter, error } = registerAgentAdapter(teamId, "claude", { - api_key: "sk-test123", - model: "claude-4-opus", - }); - - assert.ok(!error); - assert.equal(adapter.agent_type, "claude"); - assert.equal(adapter.status, "installed"); - assert.ok(adapter.enabled_capabilities.includes("file_read")); - }); - - it("registers Cursor adapter", () => { - const { adapter, error } = registerAgentAdapter(teamId, "cursor", { - editor_path: "/usr/local/bin/cursor", - project_root: "/home/user/project", - }); - - assert.ok(!error); - assert.equal(adapter.agent_type, "cursor"); - assert.ok(adapter.enabled_capabilities.includes("workspace_awareness")); - }); - - it("registers Cline adapter", () => { - const { adapter, error } = registerAgentAdapter(teamId, "cline", { - agent_key: "key-cline-123", - }); - - assert.ok(!error); - assert.equal(adapter.agent_type, "cline"); - assert.ok(adapter.enabled_capabilities.includes("terminal_access")); - }); - - it("fails without required config", () => { - const { error } = registerAgentAdapter(teamId, "claude", {}); - - assert.ok(error); - assert.ok(error?.includes("required config")); - }); - - it("fails for unknown agent type", () => { - const { error } = registerAgentAdapter(teamId, "unknown" as any, { - config: "value", - }); - - assert.ok(error); - }); - }); - - describe("getAdapterStatus", () => { - it("returns adapter status", () => { - const { adapter: created } = registerAgentAdapter(teamId, "claude", { - api_key: "sk-test", - }); - - const { adapter, error } = getAdapterStatus(teamId, created.id); - - assert.ok(!error); - assert.equal(adapter?.status, "installed"); - assert.equal(adapter?.health_status, "healthy"); - }); - - it("fails for nonexistent adapter", () => { - const { error } = getAdapterStatus(teamId, "nonexistent"); - - assert.ok(error); - assert.equal(error, "Adapter not found"); - }); - }); - - describe("checkCapabilities", () => { - it("returns adapter capabilities", () => { - const { adapter: created } = registerAgentAdapter(teamId, "cursor", { - editor_path: "/usr/bin/cursor", - project_root: "/home/user/project", - }); - - const { capabilities, coverage_percent } = checkCapabilities(teamId, created.id); - - assert.ok(capabilities.length > 0); - assert.equal(coverage_percent, 100); - assert.ok(capabilities.every((c) => c.enabled)); - }); - }); - - describe("toggleCapability", () => { - it("disables capability", () => { - const { adapter: created } = registerAgentAdapter(teamId, "claude", { - api_key: "sk-test", - }); - - const { capabilities } = checkCapabilities(teamId, created.id); - const testCap = capabilities[0]; - - const { capability, error } = toggleCapability(teamId, testCap.id, false); - - assert.ok(!error); - assert.ok(!capability.enabled); - }); - - it("fails for nonexistent capability", () => { - const { error } = toggleCapability(teamId, "nonexistent-cap", false); - - assert.ok(error); - assert.equal(error, "Capability not found"); - }); - }); - - describe("introspectAgent", () => { - it("introspects agent state", () => { - const { adapter: created } = registerAgentAdapter(teamId, "claude", { - api_key: "sk-test", - }); - - const { introspection, error } = introspectAgent(teamId, created.id, "capabilities"); - - assert.ok(!error); - assert.equal(introspection.introspection_type, "capabilities"); - assert.ok(introspection.data); - assert.equal(introspection.data.agent_type, "claude"); - }); - - it("fails for nonexistent adapter", () => { - const { error } = introspectAgent(teamId, "nonexistent", "health"); - - assert.ok(error); - assert.equal(error, "Adapter not found"); - }); - }); - - describe("createAutomation", () => { - it("creates automation for adapter", () => { - const { adapter: created } = registerAgentAdapter(teamId, "cline", { - agent_key: "key-123", - }); - - const { automation, error } = createAutomation( - teamId, - created.id, - "run_tests", - "on_file_change", - ["npm test", "npm run lint"], - ); - - assert.ok(!error); - assert.equal(automation.automation_name, "run_tests"); - assert.equal(automation.trigger, "on_file_change"); - assert.ok(automation.enabled); - }); - - it("fails for nonexistent adapter", () => { - const { error } = createAutomation( - teamId, - "nonexistent", - "auto", - "trigger", - ["action"], - ); - - assert.ok(error); - assert.equal(error, "Adapter not found"); - }); - }); - - describe("setupCollaboration", () => { - it("sets up multi-agent collaboration", () => { - const team2 = "team-collab-2"; - - const { adapter: claude } = registerAgentAdapter(team2, "claude", { - api_key: "sk-test", - }); - const { adapter: cursor } = registerAgentAdapter(team2, "cursor", { - editor_path: "/usr/bin/cursor", - project_root: "/home/user/project", - }); - - const { collaboration, error } = setupCollaboration( - team2, - [claude.id, cursor.id], - "sequential", - { shared_state: "initial" }, - ); - - assert.ok(!error); - assert.equal(collaboration.agents.length, 2); - assert.equal(collaboration.mode, "sequential"); - assert.equal(collaboration.status, "active"); - assert.equal(collaboration.agents[0].role, "primary"); - }); - - it("fails with missing adapters", () => { - const { error } = setupCollaboration( - teamId, - ["nonexistent1", "nonexistent2"], - "parallel", - ); - - assert.ok(error); - assert.ok(error?.includes("not found")); - }); - }); - - describe("getAdapterMetrics", () => { - it("returns adapter metrics", () => { - const team3 = "team-metrics-3"; - - const { adapter: created } = registerAgentAdapter(team3, "claude", { - api_key: "sk-test", - }); - - const metrics = getAdapterMetrics(team3, created.id); - - assert.equal(metrics.adapter_id, created.id); - assert.equal(metrics.agent_type, "claude"); - assert.ok(metrics.health_score > 0); - assert.ok(metrics.uptime_percent > 0); - assert.ok(metrics.capability_coverage >= 0); - }); - }); - - describe("listTeamAdapters", () => { - it("lists all team adapters", () => { - const team4 = "team-list-4"; - - registerAgentAdapter(team4, "claude", { api_key: "sk-test" }); - registerAgentAdapter(team4, "cursor", { - editor_path: "/usr/bin/cursor", - project_root: "/home/user/project", - }); - - const { adapters } = listTeamAdapters(team4); - - assert.equal(adapters.length, 2); - assert.ok(adapters.some((a) => a.agent_type === "claude")); - assert.ok(adapters.some((a) => a.agent_type === "cursor")); - }); - }); - - describe("getCollaborationStatus", () => { - it("returns collaboration status", () => { - const team5 = "team-status-5"; - - const { adapter: a1 } = registerAgentAdapter(team5, "claude", { - api_key: "sk-test", - }); - const { adapter: a2 } = registerAgentAdapter(team5, "cline", { - agent_key: "key-123", - }); - - const { collaboration: created } = setupCollaboration( - team5, - [a1.id, a2.id], - "hierarchical", - ); - - const { collaboration, error } = getCollaborationStatus(team5, created.id); - - assert.ok(!error); - assert.equal(collaboration?.status, "active"); - assert.equal(collaboration?.mode, "hierarchical"); - }); - - it("fails for nonexistent collaboration", () => { - const { error } = getCollaborationStatus(teamId, "nonexistent"); - - assert.ok(error); - assert.equal(error, "Collaboration not found"); - }); - }); -}); diff --git a/src/agent-adapter-service.ts b/src/agent-adapter-service.ts deleted file mode 100644 index ad11a517..00000000 --- a/src/agent-adapter-service.ts +++ /dev/null @@ -1,391 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - AgentProfile, - AgentAdapter, - AgentCapability, - AgentIntrospection, - AgentAutomation, - AgentCollaboration, - AgentMetrics, - AgentType, - CapabilityType, -} from "./agent-adapter-model.js"; - -const adapters = new Map(); -const capabilities = new Map(); -const introspections = new Map(); -const automations = new Map(); -const collaborations = new Map(); - -// Predefined agent profiles -const AGENT_PROFILES: Record = { - claude: { - id: `profile_claude_${randomUUID()}`, - agent_type: "claude", - version: "4.5", - name: "Claude AI", - description: "Claude LLM with extended file access and debugging capabilities", - capabilities: [ - "file_read", - "file_write", - "code_execution", - "debugging", - "testing", - "ai_collaboration", - "context_management", - ], - config_required: ["api_key"], - optional_config: ["model", "max_tokens", "temperature"], - installation_method: "cli", - homepage: "https://claude.ai", - documentation: "https://docs.anthropic.com", - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - cursor: { - id: `profile_cursor_${randomUUID()}`, - agent_type: "cursor", - version: "0.40", - name: "Cursor Editor", - description: "Cursor IDE with AI-powered code editing and workspace awareness", - capabilities: [ - "file_read", - "file_write", - "code_execution", - "git_integration", - "debugging", - "testing", - "workspace_awareness", - "ai_collaboration", - ], - config_required: ["editor_path", "project_root"], - optional_config: ["git_branch", "excluded_paths"], - installation_method: "extension", - homepage: "https://cursor.sh", - documentation: "https://cursor.sh/docs", - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - cline: { - id: `profile_cline_${randomUUID()}`, - agent_type: "cline", - version: "2.0", - name: "Cline AI Assistant", - description: "Cline with autonomous task execution and terminal access", - capabilities: [ - "file_read", - "file_write", - "code_execution", - "terminal_access", - "git_integration", - "testing", - ], - config_required: ["agent_key"], - optional_config: ["allowed_commands", "max_execution_time"], - installation_method: "cli", - homepage: "https://cline.dev", - documentation: "https://cline.dev/docs", - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - generic: { - id: `profile_generic_${randomUUID()}`, - agent_type: "generic", - version: "1.0", - name: "Generic Agent", - description: "Generic adapter for custom agents", - capabilities: ["file_read", "ai_collaboration", "context_management"], - config_required: ["agent_id"], - optional_config: ["custom_config"], - installation_method: "manual", - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, -}; - -/** - * Register agent adapter for team - */ -export function registerAgentAdapter( - team_id: string, - agent_type: AgentType, - config: Record, -): { adapter: AgentAdapter; error?: string } { - const profile = AGENT_PROFILES[agent_type]; - if (!profile) { - return { adapter: {} as AgentAdapter, error: `Unknown agent type: ${agent_type}` }; - } - - // Validate required config - const missing = profile.config_required.filter((key) => !(key in config)); - if (missing.length > 0) { - return { - adapter: {} as AgentAdapter, - error: `Missing required config: ${missing.join(", ")}`, - }; - } - - const adapter: AgentAdapter = { - id: `adapter_${randomUUID()}`, - team_id, - agent_type, - agent_profile_id: profile.id, - status: "installed", - version: profile.version, - installed_at: new Date().toISOString(), - config, - enabled_capabilities: profile.capabilities, - disabled_capabilities: [], - health_status: "healthy", - last_health_check: new Date().toISOString(), - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - adapters.set(adapter.id, adapter); - - // Create capability records - for (const cap of profile.capabilities) { - const capability: AgentCapability = { - id: `cap_${randomUUID()}`, - adapter_id: adapter.id, - team_id, - capability_type: cap as CapabilityType, - enabled: true, - required_config: {}, - permissions_required: [], - usage_count: 0, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - capabilities.set(capability.id, capability); - } - - return { adapter }; -} - -/** - * Get agent adapter status - */ -export function getAdapterStatus( - team_id: string, - adapter_id: string, -): { adapter: AgentAdapter | null; error?: string } { - const adapter = adapters.get(adapter_id); - - if (!adapter || adapter.team_id !== team_id) { - return { adapter: null, error: "Adapter not found" }; - } - - return { adapter }; -} - -/** - * Check agent capabilities - */ -export function checkCapabilities( - team_id: string, - adapter_id: string, -): { capabilities: AgentCapability[]; coverage_percent: number } { - const teamCaps = Array.from(capabilities.values()).filter( - (c) => c.adapter_id === adapter_id && c.team_id === team_id, - ); - - const enabledCount = teamCaps.filter((c) => c.enabled).length; - const coverage = teamCaps.length > 0 ? (enabledCount / teamCaps.length) * 100 : 0; - - return { capabilities: teamCaps, coverage_percent: Math.round(coverage) }; -} - -/** - * Enable/disable capability - */ -export function toggleCapability( - team_id: string, - capability_id: string, - enabled: boolean, -): { capability: AgentCapability; error?: string } { - const capability = capabilities.get(capability_id); - - if (!capability || capability.team_id !== team_id) { - return { capability: {} as AgentCapability, error: "Capability not found" }; - } - - capability.enabled = enabled; - capability.updated_at = new Date().toISOString(); - - return { capability }; -} - -/** - * Introspect agent state - */ -export function introspectAgent( - team_id: string, - adapter_id: string, - introspection_type: string, -): { introspection: AgentIntrospection; error?: string } { - const adapter = adapters.get(adapter_id); - - if (!adapter || adapter.team_id !== team_id) { - return { introspection: {} as AgentIntrospection, error: "Adapter not found" }; - } - - const introspection: AgentIntrospection = { - id: `intro_${randomUUID()}`, - team_id, - adapter_id, - introspection_type: introspection_type as any, - data: { - agent_type: adapter.agent_type, - status: adapter.status, - health: adapter.health_status, - capabilities_enabled: adapter.enabled_capabilities.length, - config_keys: Object.keys(adapter.config), - }, - timestamp: new Date().toISOString(), - ttl_seconds: 300, - }; - - introspections.set(introspection.id, introspection); - - return { introspection }; -} - -/** - * Create agent automation - */ -export function createAutomation( - team_id: string, - adapter_id: string, - automation_name: string, - trigger: string, - actions: string[], -): { automation: AgentAutomation; error?: string } { - const adapter = adapters.get(adapter_id); - - if (!adapter || adapter.team_id !== team_id) { - return { automation: {} as AgentAutomation, error: "Adapter not found" }; - } - - const automation: AgentAutomation = { - id: `auto_${randomUUID()}`, - team_id, - adapter_id, - automation_name, - trigger, - actions, - enabled: true, - run_count: 0, - error_count: 0, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - automations.set(automation.id, automation); - - return { automation }; -} - -/** - * Setup agent collaboration - */ -export function setupCollaboration( - team_id: string, - agent_adapter_ids: string[], - collaboration_mode: string, - shared_context?: Record, -): { collaboration: AgentCollaboration; error?: string } { - // Validate all adapters exist - const adaptersExist = agent_adapter_ids.every((id) => { - const a = adapters.get(id); - return a && a.team_id === team_id; - }); - - if (!adaptersExist) { - return { collaboration: {} as AgentCollaboration, error: "Some adapters not found" }; - } - - const collaboration: AgentCollaboration = { - id: `collab_${randomUUID()}`, - team_id, - collaboration_id: `collab_${randomUUID()}`, - agents: agent_adapter_ids.map((adapter_id, idx) => { - const a = adapters.get(adapter_id)!; - return { - adapter_id, - agent_type: a.agent_type, - role: idx === 0 ? "primary" : idx === agent_adapter_ids.length - 1 ? "observer" : "secondary", - }; - }), - mode: collaboration_mode as any, - shared_context: shared_context || {}, - status: "active", - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - collaborations.set(collaboration.id, collaboration); - - return { collaboration }; -} - -/** - * Get agent metrics - */ -export function getAdapterMetrics(team_id: string, adapter_id: string): AgentMetrics { - const adapter = adapters.get(adapter_id) || ({} as AgentAdapter); - const teamCaps = Array.from(capabilities.values()).filter( - (c) => c.adapter_id === adapter_id && c.team_id === team_id, - ); - const enabledCaps = teamCaps.filter((c) => c.enabled).length; - - const teamAutomations = Array.from(automations.values()).filter( - (a) => a.adapter_id === adapter_id && a.team_id === team_id, - ); - const activeAutomations = teamAutomations.filter((a) => a.enabled).length; - - const teamCollaborations = Array.from(collaborations.values()).filter( - (c) => c.team_id === team_id && c.agents.some((a) => a.adapter_id === adapter_id), - ); - const activeCollaborations = teamCollaborations.filter((c) => c.status === "active").length; - - return { - adapter_id, - agent_type: adapter.agent_type || ("generic" as AgentType), - health_score: adapter.health_status === "healthy" ? 95 : adapter.health_status === "degraded" ? 60 : 20, - uptime_percent: 99.5, - capability_coverage: - teamCaps.length > 0 ? Math.round((enabledCaps / teamCaps.length) * 100) : 0, - average_latency_ms: 150, - error_rate_percent: 0.5, - last_activity: adapter.updated_at || new Date().toISOString(), - collaborations_active: activeCollaborations, - automations_active: activeAutomations, - operations_today: 42, - }; -} - -/** - * List team agents - */ -export function listTeamAdapters(team_id: string): { adapters: AgentAdapter[] } { - const teamAdapters = Array.from(adapters.values()).filter((a) => a.team_id === team_id); - return { adapters: teamAdapters }; -} - -/** - * Get collaboration status - */ -export function getCollaborationStatus( - team_id: string, - collaboration_id: string, -): { collaboration: AgentCollaboration | null; error?: string } { - const collab = collaborations.get(collaboration_id); - - if (!collab || collab.team_id !== team_id) { - return { collaboration: null, error: "Collaboration not found" }; - } - - return { collaboration: collab }; -} diff --git a/src/agent-governance-model.ts b/src/agent-governance-model.ts deleted file mode 100644 index 2c17e722..00000000 --- a/src/agent-governance-model.ts +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Agent Governance & Security Framework — data models - * Governance controls, permission systems, audit logging, and security policies - */ - -export type PolicyType = "access_control" | "rate_limit" | "resource_quota" | "behavior_restriction"; -export type PolicyStatus = "draft" | "active" | "paused" | "deprecated"; -export type ActionType = "create" | "read" | "update" | "delete" | "execute" | "approve"; -export type PermissionLevel = "none" | "viewer" | "editor" | "admin" | "owner"; -export type AuditAction = - | "agent_created" - | "agent_modified" - | "permission_granted" - | "permission_revoked" - | "workflow_executed" - | "policy_violated" - | "secret_accessed" - | "resource_used"; - -export interface GovernancePolicy { - id: string; - team_id: string; - policy_name: string; - description: string; - policy_type: PolicyType; - status: PolicyStatus; - rules: { - condition: string; - action: string; - consequence?: string; - }[]; - target_agents?: string[]; // Specific agent IDs or "*" for all - target_workflows?: string[]; // Specific workflow IDs or "*" for all - priority: number; // 1-100, higher = more important - enforcement_enabled: boolean; - created_by: string; - created_at: string; - updated_at: string; -} - -export interface AgentPermission { - id: string; - team_id: string; - agent_id: string; - resource_type: string; // "workflow", "secret", "plugin", "infrastructure" - resource_id?: string; // Specific resource or "*" for all - action: ActionType; - permission_level: PermissionLevel; - granted_by: string; - granted_at: string; - expires_at?: string; - conditions?: Record; // Time, location, etc. - created_at: string; - updated_at: string; -} - -export interface AgentSecurityProfile { - id: string; - team_id: string; - agent_id: string; - agent_type: string; // claude, cursor, cline - risk_level: "low" | "medium" | "high"; - trust_score: number; // 0-100 - permissions: AgentPermission[]; - violations_count: number; - last_violation?: string; - sandboxed: boolean; - resource_limits: { - max_concurrent_workflows: number; - max_api_calls_per_hour: number; - max_memory_mb: number; - max_storage_gb: number; - }; - created_at: string; - updated_at: string; -} - -export interface GovernanceAuditLog { - id: string; - team_id: string; - agent_id?: string; - action: AuditAction; - resource_type: string; - resource_id?: string; - details: Record; - severity: "info" | "warning" | "critical"; - status: "allowed" | "denied" | "warning"; - policy_evaluated?: string; // Policy ID that was applied - timestamp: string; - created_at: string; -} - -export interface RateLimitPolicy { - id: string; - team_id: string; - agent_id?: string; // Specific agent or undefined for team-wide - resource_type: string; - requests_per_minute: number; - requests_per_hour: number; - requests_per_day: number; - burst_limit: number; - enabled: boolean; - created_at: string; - updated_at: string; -} - -export interface ResourceQuota { - id: string; - team_id: string; - agent_id?: string; - resource_type: string; // "api_calls", "storage", "compute", "bandwidth" - limit: number; - unit: string; // "calls", "gb", "cpu_hours", "mbps" - period: "hour" | "day" | "month"; - current_usage: number; - warning_threshold_percent: number; // Alert at this percentage - created_at: string; - updated_at: string; -} - -export interface GovernanceMetrics { - total_policies: number; - active_policies: number; - total_permissions: number; - agents_with_violations: number; - total_audit_events: number; - critical_events_count: number; - average_trust_score: number; - policy_violation_rate_percent: number; - average_response_time_ms: number; -} - -export interface PolicyEvaluation { - id: string; - team_id: string; - policy_id: string; - agent_id: string; - action: ActionType; - resource_type: string; - allowed: boolean; - reason: string; - violated_rules?: string[]; - timestamp: string; - created_at: string; -} diff --git a/src/agent-governance-service.test.ts b/src/agent-governance-service.test.ts deleted file mode 100644 index 18b85f00..00000000 --- a/src/agent-governance-service.test.ts +++ /dev/null @@ -1,378 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { - createGovernancePolicy, - addPolicyRule, - activatePolicy, - createSecurityProfile, - grantPermission, - revokePermission, - evaluatePolicy, - logAuditEvent, - setRateLimit, - setResourceQuota, - getSecurityProfile, - getAuditLogs, - getGovernanceMetrics, - updateTrustScore, - listPolicies, -} from "./agent-governance-service.js"; - -describe("agent-governance-service", () => { - const teamId = "team-governance-123"; - const userId = "user-governance-456"; - const agentId = "agent-gov-789"; - - describe("createGovernancePolicy", () => { - it("creates governance policy", () => { - const { policy, error } = createGovernancePolicy( - teamId, - "Access Control Policy", - "access_control", - userId, - "Control agent access", - ); - - assert.ok(!error); - assert.ok(policy.id); - assert.equal(policy.status, "draft"); - assert.equal(policy.enforcement_enabled, false); - }); - }); - - describe("addPolicyRule", () => { - it("adds rule to policy", () => { - const { policy } = createGovernancePolicy(teamId, "Policy", "access_control", userId); - - const { policy: updated, error } = addPolicyRule( - teamId, - policy.id, - "agent.risk_level > 'high'", - "restrict_access", - "deny", - ); - - assert.ok(!error); - assert.equal(updated.rules.length, 1); - }); - - it("fails for nonexistent policy", () => { - const { error } = addPolicyRule( - teamId, - "nonexistent-policy", - "condition", - "action", - ); - - assert.ok(error); - assert.equal(error, "Policy not found"); - }); - }); - - describe("activatePolicy", () => { - it("activates policy with rules", () => { - const { policy } = createGovernancePolicy(teamId, "Policy", "access_control", userId); - addPolicyRule(teamId, policy.id, "condition", "action"); - - const { policy: activated, error } = activatePolicy(teamId, policy.id); - - assert.ok(!error); - assert.equal(activated.status, "active"); - assert.equal(activated.enforcement_enabled, true); - }); - - it("fails to activate policy without rules", () => { - const { policy } = createGovernancePolicy(teamId, "Policy", "access_control", userId); - - const { error } = activatePolicy(teamId, policy.id); - - assert.ok(error); - assert.equal(error, "Policy has no rules"); - }); - }); - - describe("createSecurityProfile", () => { - it("creates security profile", () => { - const { profile, error } = createSecurityProfile(teamId, agentId, "claude"); - - assert.ok(!error); - assert.ok(profile.id); - assert.equal(profile.agent_id, agentId); - assert.equal(profile.risk_level, "medium"); - assert.equal(profile.trust_score, 50); - }); - }); - - describe("grantPermission", () => { - it("grants permission to agent", () => { - const { permission, error } = grantPermission( - teamId, - agentId, - "workflow", - "execute", - "editor", - userId, - ); - - assert.ok(!error); - assert.ok(permission.id); - assert.equal(permission.agent_id, agentId); - assert.equal(permission.permission_level, "editor"); - }); - - it("grants permission with expiry", () => { - const expiryDate = new Date(); - expiryDate.setHours(expiryDate.getHours() + 24); - - const { permission } = grantPermission( - teamId, - agentId, - "secret", - "read", - "viewer", - userId, - undefined, - expiryDate.toISOString(), - ); - - assert.ok(permission.expires_at); - }); - }); - - describe("revokePermission", () => { - it("revokes permission", () => { - const { permission } = grantPermission( - teamId, - agentId, - "workflow", - "execute", - "editor", - userId, - ); - - const { success, error } = revokePermission(teamId, permission.id); - - assert.ok(!error); - assert.equal(success, true); - }); - - it("fails for nonexistent permission", () => { - const { error } = revokePermission(teamId, "nonexistent-permission"); - - assert.ok(error); - assert.equal(error, "Permission not found"); - }); - }); - - describe("evaluatePolicy", () => { - it("evaluates policy", () => { - const { policy } = createGovernancePolicy(teamId, "Policy", "access_control", userId); - addPolicyRule(teamId, policy.id, "resource == 'workflow'", "execute"); - activatePolicy(teamId, policy.id); - - const { evaluation, error } = evaluatePolicy( - teamId, - policy.id, - agentId, - "execute", - "workflow", - ); - - assert.ok(!error); - assert.ok(evaluation.id); - assert.equal(evaluation.allowed, true); - }); - - it("fails for inactive policy", () => { - const { policy } = createGovernancePolicy(teamId, "Policy", "access_control", userId); - addPolicyRule(teamId, policy.id, "condition", "action"); - - const { error } = evaluatePolicy( - teamId, - policy.id, - agentId, - "execute", - "workflow", - ); - - assert.ok(error); - assert.equal(error, "Policy not active"); - }); - }); - - describe("logAuditEvent", () => { - it("logs audit event", () => { - const { log } = logAuditEvent(teamId, agentId, "allowed", "execute", "workflow", "wf-123"); - - assert.ok(log.id); - assert.equal(log.team_id, teamId); - assert.equal(log.agent_id, agentId); - assert.equal(log.status, "allowed"); - }); - - it("records critical severity for denied actions", () => { - const { log } = logAuditEvent(teamId, agentId, "denied", "delete", "secret"); - - assert.equal(log.severity, "critical"); - }); - }); - - describe("setRateLimit", () => { - it("sets rate limit for agent", () => { - const { rateLimit, error } = setRateLimit(teamId, agentId, "api_calls", 60, 1000); - - assert.ok(!error); - assert.ok(rateLimit.id); - assert.equal(rateLimit.requests_per_minute, 60); - assert.equal(rateLimit.enabled, true); - }); - - it("calculates burst limit", () => { - const { rateLimit } = setRateLimit(teamId, agentId, "api_calls", 100, 6000); - - assert.ok(rateLimit.burst_limit > 100); - }); - }); - - describe("setResourceQuota", () => { - it("sets resource quota", () => { - const { quota, error } = setResourceQuota( - teamId, - agentId, - "storage", - 100, - "gb", - "month", - ); - - assert.ok(!error); - assert.ok(quota.id); - assert.equal(quota.limit, 100); - assert.equal(quota.unit, "gb"); - }); - - it("sets quota without agent id for team-wide limits", () => { - const { quota } = setResourceQuota( - teamId, - undefined, - "api_calls", - 10000, - "calls", - "day", - ); - - assert.ok(!quota.agent_id); - assert.equal(quota.limit, 10000); - }); - }); - - describe("getSecurityProfile", () => { - it("gets security profile", () => { - createSecurityProfile(teamId, agentId, "claude"); - - const { profile, error } = getSecurityProfile(teamId, agentId); - - assert.ok(!error); - assert.ok(profile); - assert.equal(profile?.agent_id, agentId); - }); - - it("fails for nonexistent profile", () => { - const { profile, error } = getSecurityProfile(teamId, "nonexistent-agent"); - - assert.ok(error); - assert.ok(!profile); - }); - }); - - describe("getAuditLogs", () => { - it("gets audit logs", () => { - const team2 = "team-governance-audit"; - logAuditEvent(team2, agentId, "allowed", "execute", "workflow"); - logAuditEvent(team2, agentId, "denied", "delete", "secret"); - - const { logs, total } = getAuditLogs(team2); - - assert.ok(total >= 2); - assert.ok(logs.length >= 2); - }); - - it("filters by agent id", () => { - const team3 = "team-governance-filter"; - logAuditEvent(team3, "agent-1", "allowed", "execute", "workflow"); - logAuditEvent(team3, "agent-2", "allowed", "execute", "workflow"); - - const { logs } = getAuditLogs(team3, "agent-1"); - - assert.ok(logs.every((log) => log.agent_id === "agent-1")); - }); - - it("respects pagination", () => { - const team4 = "team-governance-pagination"; - for (let i = 0; i < 5; i++) { - logAuditEvent(team4, agentId, "allowed", "execute", "workflow"); - } - - const page1 = getAuditLogs(team4, undefined, 2, 0); - const page2 = getAuditLogs(team4, undefined, 2, 2); - - assert.equal(page1.logs.length, 2); - assert.equal(page2.logs.length, 2); - assert.notEqual(page1.logs[0]?.id, page2.logs[0]?.id); - }); - }); - - describe("updateTrustScore", () => { - it("updates trust score", () => { - createSecurityProfile(teamId, agentId, "claude"); - - const { profile } = updateTrustScore(teamId, agentId, 20); - - assert.equal(profile.trust_score, 70); - }); - - it("updates risk level based on trust score", () => { - createSecurityProfile(teamId, agentId, "claude"); - updateTrustScore(teamId, agentId, 35); // 50 + 35 = 85 - - const { profile } = getSecurityProfile(teamId, agentId); - - assert.equal(profile?.risk_level, "low"); - }); - - it("clamps trust score between 0 and 100", () => { - createSecurityProfile(teamId, agentId, "claude"); - updateTrustScore(teamId, agentId, 100); - - const { profile } = updateTrustScore(teamId, agentId, 100); - - assert.equal(profile.trust_score, 100); - }); - }); - - describe("getGovernanceMetrics", () => { - it("returns governance metrics", () => { - const team5 = "team-governance-metrics"; - createGovernancePolicy(team5, "Policy 1", "access_control", userId); - createSecurityProfile(team5, agentId, "claude"); - - const metrics = getGovernanceMetrics(team5); - - assert.ok(metrics.total_policies > 0); - assert.ok(metrics.average_trust_score >= 0); - assert.ok(metrics.policy_violation_rate_percent >= 0); - }); - }); - - describe("listPolicies", () => { - it("lists team policies", () => { - const team6 = "team-governance-list"; - createGovernancePolicy(team6, "Policy 1", "access_control", userId); - createGovernancePolicy(team6, "Policy 2", "rate_limit", userId); - - const { policies } = listPolicies(team6); - - assert.equal(policies.length, 2); - }); - }); -}); diff --git a/src/agent-governance-service.ts b/src/agent-governance-service.ts deleted file mode 100644 index b492c580..00000000 --- a/src/agent-governance-service.ts +++ /dev/null @@ -1,472 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - GovernancePolicy, - AgentPermission, - AgentSecurityProfile, - GovernanceAuditLog, - RateLimitPolicy, - ResourceQuota, - GovernanceMetrics, - PolicyEvaluation, - PolicyType, - ActionType, - PermissionLevel, -} from "./agent-governance-model.js"; - -const policies = new Map(); -const permissions = new Map(); -const securityProfiles = new Map(); -const auditLogs = new Map(); -const rateLimits = new Map(); -const quotas = new Map(); -const evaluations = new Map(); - -/** - * Create governance policy - */ -export function createGovernancePolicy( - team_id: string, - policy_name: string, - policy_type: PolicyType, - created_by: string, - description?: string, -): { policy: GovernancePolicy; error?: string } { - const policy: GovernancePolicy = { - id: `policy_${randomUUID()}`, - team_id, - policy_name, - description: description || "", - policy_type, - status: "draft", - rules: [], - priority: 50, - enforcement_enabled: false, - created_by, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - policies.set(policy.id, policy); - return { policy }; -} - -/** - * Add rule to policy - */ -export function addPolicyRule( - team_id: string, - policy_id: string, - condition: string, - action: string, - consequence?: string, -): { policy: GovernancePolicy; error?: string } { - const policy = policies.get(policy_id); - if (!policy || policy.team_id !== team_id) { - return { policy: {} as GovernancePolicy, error: "Policy not found" }; - } - - policy.rules.push({ condition, action, consequence }); - policy.updated_at = new Date().toISOString(); - - return { policy }; -} - -/** - * Activate policy - */ -export function activatePolicy( - team_id: string, - policy_id: string, -): { policy: GovernancePolicy; error?: string } { - const policy = policies.get(policy_id); - if (!policy || policy.team_id !== team_id) { - return { policy: {} as GovernancePolicy, error: "Policy not found" }; - } - - if (policy.rules.length === 0) { - return { policy: {} as GovernancePolicy, error: "Policy has no rules" }; - } - - policy.status = "active"; - policy.enforcement_enabled = true; - policy.updated_at = new Date().toISOString(); - - return { policy }; -} - -/** - * Create security profile for agent - */ -export function createSecurityProfile( - team_id: string, - agent_id: string, - agent_type: string, -): { profile: AgentSecurityProfile; error?: string } { - const profile: AgentSecurityProfile = { - id: `profile_${randomUUID()}`, - team_id, - agent_id, - agent_type, - risk_level: "medium", - trust_score: 50, - permissions: [], - violations_count: 0, - sandboxed: false, - resource_limits: { - max_concurrent_workflows: 5, - max_api_calls_per_hour: 1000, - max_memory_mb: 512, - max_storage_gb: 10, - }, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - securityProfiles.set(profile.id, profile); - return { profile }; -} - -/** - * Grant permission to agent - */ -export function grantPermission( - team_id: string, - agent_id: string, - resource_type: string, - action: ActionType, - permission_level: PermissionLevel, - granted_by: string, - resource_id?: string, - expires_at?: string, -): { permission: AgentPermission; error?: string } { - const permission: AgentPermission = { - id: `perm_${randomUUID()}`, - team_id, - agent_id, - resource_type, - resource_id, - action, - permission_level, - granted_by, - granted_at: new Date().toISOString(), - expires_at, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - permissions.set(permission.id, permission); - - // Update security profile - const profiles = Array.from(securityProfiles.values()).filter( - (p) => p.team_id === team_id && p.agent_id === agent_id, - ); - if (profiles.length > 0) { - profiles[0].permissions.push(permission); - } - - return { permission }; -} - -/** - * Revoke permission - */ -export function revokePermission( - team_id: string, - permission_id: string, -): { success: boolean; error?: string } { - const permission = permissions.get(permission_id); - if (!permission || permission.team_id !== team_id) { - return { success: false, error: "Permission not found" }; - } - - permissions.delete(permission_id); - - // Update security profile - const profiles = Array.from(securityProfiles.values()).filter( - (p) => p.team_id === team_id && p.agent_id === permission.agent_id, - ); - if (profiles.length > 0) { - profiles[0].permissions = profiles[0].permissions.filter((p) => p.id !== permission_id); - } - - return { success: true }; -} - -/** - * Evaluate policy for agent action - */ -export function evaluatePolicy( - team_id: string, - policy_id: string, - agent_id: string, - action: ActionType, - resource_type: string, - resource_id?: string, -): { evaluation: PolicyEvaluation; error?: string } { - const policy = policies.get(policy_id); - if (!policy || policy.team_id !== team_id) { - return { evaluation: {} as PolicyEvaluation, error: "Policy not found" }; - } - - if (!policy.enforcement_enabled) { - return { evaluation: {} as PolicyEvaluation, error: "Policy not active" }; - } - - // Check if agent is in target list - if (policy.target_agents && !policy.target_agents.includes(agent_id) && !policy.target_agents.includes("*")) { - return { evaluation: {} as PolicyEvaluation, error: "Agent not subject to policy" }; - } - - // Evaluate rules (check if any rule applies) - let allowed = true; - const matchedRules = policy.rules.filter((r) => r.action.includes(action) || r.action === "allow"); - if (matchedRules.length > 0) { - const denialRule = matchedRules.find((r) => r.consequence === "deny"); - allowed = !denialRule; - } else { - // Default to allow if no specific rules match - allowed = true; - } - - const evaluation: PolicyEvaluation = { - id: `eval_${randomUUID()}`, - team_id, - policy_id, - agent_id, - action, - resource_type, - allowed, - reason: allowed ? "Policy allowed action" : "Policy denied action", - timestamp: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - evaluations.set(evaluation.id, evaluation); - - // Log to audit - logAuditEvent( - team_id, - agent_id, - allowed ? "allowed" : "denied", - action, - resource_type, - resource_id, - policy_id, - ); - - return { evaluation }; -} - -/** - * Log audit event - */ -export function logAuditEvent( - team_id: string, - agent_id: string | undefined, - status: "allowed" | "denied" | "warning", - action: ActionType, - resource_type: string, - resource_id?: string, - policy_id?: string, -): { log: GovernanceAuditLog } { - const log: GovernanceAuditLog = { - id: `audit_${randomUUID()}`, - team_id, - agent_id, - action: action as any, - resource_type, - resource_id, - details: {}, - severity: status === "denied" ? "critical" : "info", - status, - policy_evaluated: policy_id, - timestamp: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - auditLogs.set(log.id, log); - - // Update security profile violation count if denied - if (status === "denied" && agent_id) { - const profiles = Array.from(securityProfiles.values()).filter( - (p) => p.team_id === team_id && p.agent_id === agent_id, - ); - if (profiles.length > 0) { - profiles[0].violations_count += 1; - profiles[0].last_violation = new Date().toISOString(); - } - } - - return { log }; -} - -/** - * Set rate limit for agent - */ -export function setRateLimit( - team_id: string, - agent_id: string | undefined, - resource_type: string, - requests_per_minute: number, - requests_per_hour: number, -): { rateLimit: RateLimitPolicy; error?: string } { - const rateLimit: RateLimitPolicy = { - id: `ratelimit_${randomUUID()}`, - team_id, - agent_id, - resource_type, - requests_per_minute, - requests_per_hour, - requests_per_day: requests_per_hour * 24, - burst_limit: Math.ceil(requests_per_minute * 1.5), - enabled: true, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - rateLimits.set(rateLimit.id, rateLimit); - return { rateLimit }; -} - -/** - * Set resource quota for agent - */ -export function setResourceQuota( - team_id: string, - agent_id: string | undefined, - resource_type: string, - limit: number, - unit: string, - period: "hour" | "day" | "month", -): { quota: ResourceQuota; error?: string } { - const quota: ResourceQuota = { - id: `quota_${randomUUID()}`, - team_id, - agent_id, - resource_type, - limit, - unit, - period, - current_usage: 0, - warning_threshold_percent: 80, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - quotas.set(quota.id, quota); - return { quota }; -} - -/** - * Get security profile - */ -export function getSecurityProfile( - team_id: string, - agent_id: string, -): { profile: AgentSecurityProfile | null; error?: string } { - const profiles = Array.from(securityProfiles.values()).filter( - (p) => p.team_id === team_id && p.agent_id === agent_id, - ); - - if (profiles.length === 0) { - return { profile: null, error: "Security profile not found" }; - } - - return { profile: profiles[0] }; -} - -/** - * Get audit logs for period - */ -export function getAuditLogs( - team_id: string, - agent_id?: string, - limit: number = 100, - offset: number = 0, -): { logs: GovernanceAuditLog[]; total: number } { - let filtered = Array.from(auditLogs.values()).filter((log) => log.team_id === team_id); - - if (agent_id) { - filtered = filtered.filter((log) => log.agent_id === agent_id); - } - - // Sort by timestamp descending - filtered.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()); - - const results = filtered.slice(offset, offset + limit); - return { logs: results, total: filtered.length }; -} - -/** - * Get governance metrics - */ -export function getGovernanceMetrics(team_id: string): GovernanceMetrics { - const teamPolicies = Array.from(policies.values()).filter((p) => p.team_id === team_id); - const activePolicies = teamPolicies.filter((p) => p.status === "active").length; - - const teamPermissions = Array.from(permissions.values()).filter((p) => p.team_id === team_id); - - const teamProfiles = Array.from(securityProfiles.values()).filter((p) => p.team_id === team_id); - const profilesWithViolations = teamProfiles.filter((p) => p.violations_count > 0).length; - const avgTrust = - teamProfiles.length > 0 - ? teamProfiles.reduce((sum, p) => sum + p.trust_score, 0) / teamProfiles.length - : 0; - - const teamLogs = Array.from(auditLogs.values()).filter((log) => log.team_id === team_id); - const criticalLogs = teamLogs.filter((log) => log.severity === "critical").length; - const deniedLogs = teamLogs.filter((log) => log.status === "denied").length; - const violationRate = teamLogs.length > 0 ? (deniedLogs / teamLogs.length) * 100 : 0; - - return { - total_policies: teamPolicies.length, - active_policies: activePolicies, - total_permissions: teamPermissions.length, - agents_with_violations: profilesWithViolations, - total_audit_events: teamLogs.length, - critical_events_count: criticalLogs, - average_trust_score: avgTrust, - policy_violation_rate_percent: violationRate, - average_response_time_ms: 45, - }; -} - -/** - * Update agent trust score - */ -export function updateTrustScore( - team_id: string, - agent_id: string, - score_adjustment: number, -): { profile: AgentSecurityProfile; error?: string } { - const profiles = Array.from(securityProfiles.values()).filter( - (p) => p.team_id === team_id && p.agent_id === agent_id, - ); - - if (profiles.length === 0) { - return { profile: {} as AgentSecurityProfile, error: "Security profile not found" }; - } - - const profile = profiles[0]; - profile.trust_score = Math.max(0, Math.min(100, profile.trust_score + score_adjustment)); - profile.updated_at = new Date().toISOString(); - - // Adjust risk level based on trust score - if (profile.trust_score >= 80) { - profile.risk_level = "low"; - } else if (profile.trust_score >= 50) { - profile.risk_level = "medium"; - } else { - profile.risk_level = "high"; - } - - return { profile }; -} - -/** - * List all policies - */ -export function listPolicies(team_id: string): { policies: GovernancePolicy[] } { - const teamPolicies = Array.from(policies.values()).filter((p) => p.team_id === team_id); - return { policies: teamPolicies }; -} diff --git a/src/alert-rules-engine.test.ts b/src/alert-rules-engine.test.ts deleted file mode 100644 index c78fdd0a..00000000 --- a/src/alert-rules-engine.test.ts +++ /dev/null @@ -1,421 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { EventStream } from "./event-stream.js"; -import { AlertRulesEngine } from "./alert-rules-engine.js"; - -describe("AlertRulesEngine", () => { - let stream: EventStream; - let engine: AlertRulesEngine; - - beforeEach(() => { - stream = new EventStream(1000, 60000); - engine = new AlertRulesEngine(stream); - }); - - describe("addRule", () => { - it("adds alert rule", () => { - const rule = engine.addRule({ - name: "High Error Rate", - description: "Alert when error rate > 5%", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [ - { - type: "notify", - target: "alerts@example.com", - severity: "high", - }, - ], - }); - - assert.ok(rule.id); - assert.equal(rule.name, "High Error Rate"); - assert.ok(rule.createdAt); - }); - - it("generates unique rule IDs", () => { - const rule1 = engine.addRule({ - name: "Rule 1", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - const rule2 = engine.addRule({ - name: "Rule 2", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - assert.notEqual(rule1.id, rule2.id); - }); - }); - - describe("getRule", () => { - it("retrieves rule by ID", () => { - const added = engine.addRule({ - name: "Test Rule", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - const retrieved = engine.getRule(added.id); - assert.equal(retrieved?.name, "Test Rule"); - }); - - it("returns undefined for missing rule", () => { - const rule = engine.getRule("nonexistent"); - assert.equal(rule, undefined); - }); - }); - - describe("evaluateRule", () => { - it("evaluates rule against stream", () => { - const rule = engine.addRule({ - name: "Error Rate", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 8 }, - }); - - const result = engine.evaluateRule(rule); - assert.equal(result.triggered, true); - assert.equal(result.value, 8); - }); - - it("returns false when threshold not exceeded", () => { - const rule = engine.addRule({ - name: "Error Rate", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 2 }, - }); - - const result = engine.evaluateRule(rule); - assert.equal(result.triggered, false); - }); - - it("skips evaluation if rule disabled", () => { - const rule = engine.addRule({ - name: "Error Rate", - description: "Test", - enabled: false, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 100 }, - }); - - const result = engine.evaluateRule(rule); - assert.equal(result.triggered, false); - }); - }); - - describe("evaluateAll", () => { - it("evaluates all rules", async () => { - const rule = engine.addRule({ - name: "Error Rate", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 10 }, - }); - - const triggered = await engine.evaluateAll(); - assert.equal(triggered.length, 1); - assert.equal(triggered[0].ruleId, rule.id); - }); - - it("suppresses duplicate triggers", async () => { - engine.addRule({ - name: "Error Rate", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 10 }, - }); - - const triggered1 = await engine.evaluateAll(); - const triggered2 = await engine.evaluateAll(); - - assert.equal(triggered1.length, 1); - assert.equal(triggered2.length, 0); // Suppressed - }); - - it("calls trigger callback", async () => { - let callbackCalled = false; - engine.setTriggerCallback(async () => { - callbackCalled = true; - }); - - engine.addRule({ - name: "Error Rate", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 10 }, - }); - - await engine.evaluateAll(); - assert.ok(callbackCalled); - }); - }); - - describe("acknowledgeAlert", () => { - it("acknowledges alert to suppress duplicates", async () => { - const rule = engine.addRule({ - name: "Error Rate", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 10 }, - }); - - await engine.evaluateAll(); - engine.acknowledgeAlert(rule.id, 60); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 15 }, - }); - - const triggered = await engine.evaluateAll(); - assert.equal(triggered.length, 0); // Suppressed due to acknowledgement - }); - }); - - describe("getActiveAlerts", () => { - it("returns non-acknowledged alerts", async () => { - const rule = engine.addRule({ - name: "Error Rate", - description: "Test for author-1", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - const active = engine.getActiveAlerts("author-1"); - assert.equal(active.length, 1); - - engine.acknowledgeAlert(rule.id); - const activeAfter = engine.getActiveAlerts("author-1"); - assert.equal(activeAfter.length, 0); - }); - }); - - describe("getHistory", () => { - it("returns alert trigger history", async () => { - const rule = engine.addRule({ - name: "Error Rate", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - stream.publish({ - type: "metric", - source: "apm", - severity: "info", - data: { metric: "error_rate", value: 10 }, - }); - - await engine.evaluateAll(); - - const history = engine.getHistory(rule.id); - assert.equal(history.length, 1); - assert.equal(history[0].ruleId, rule.id); - }); - }); - - describe("removeRule", () => { - it("removes rule by ID", () => { - const rule = engine.addRule({ - name: "Test", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - assert.ok(engine.getRule(rule.id)); - engine.removeRule(rule.id); - assert.equal(engine.getRule(rule.id), undefined); - }); - }); - - describe("getAllRules", () => { - it("returns all rules", () => { - engine.addRule({ - name: "Rule 1", - description: "Test", - enabled: true, - condition: { - metric: "error_rate", - operator: ">", - threshold: 5, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - engine.addRule({ - name: "Rule 2", - description: "Test", - enabled: true, - condition: { - metric: "response_time", - operator: ">", - threshold: 500, - window: 300, - aggregation: "avg", - }, - actions: [], - }); - - const all = engine.getAllRules(); - assert.equal(all.length, 2); - }); - }); -}); diff --git a/src/alert-rules-engine.ts b/src/alert-rules-engine.ts deleted file mode 100644 index d4d588f6..00000000 --- a/src/alert-rules-engine.ts +++ /dev/null @@ -1,326 +0,0 @@ -/** - * Alert rules engine - * Evaluates conditions against event stream and triggers actions - */ - -import { IdGenerators } from "./id-generator.js"; -import { EventStream, StreamEvent } from "./event-stream.js"; - -export type AlertMetric = - | "error_rate" - | "response_time" - | "downloads" - | "revenue" - | "sla_breach" - | "payout_delay" - | "abuse_score"; -export type AlertOperator = ">" | "<" | "==" | "!=" | "anomaly"; -export type AlertAggregation = "avg" | "max" | "min" | "sum" | "count"; -export type AlertSeverity = "low" | "medium" | "high" | "critical"; -export type AlertActionType = "notify" | "alert" | "escalate" | "webhook"; - -export interface AlertAction { - type: AlertActionType; - target: string; // email, slack channel, webhook URL - severity: AlertSeverity; -} - -export interface AlertCondition { - metric: AlertMetric; - operator: AlertOperator; - threshold: number; - window: number; // seconds - aggregation: AlertAggregation; -} - -export interface AlertRule { - id: string; - name: string; - description: string; - enabled: boolean; - condition: AlertCondition; - actions: AlertAction[]; - createdAt: string; - updatedAt: string; - evaluatedAt?: string; - lastTriggered?: string; - acknowledgedUntil?: number; // timestamp; suppress alerts until this time -} - -export interface AlertTriggerEvent { - ruleId: string; - triggeredAt: number; - value: number; - threshold: number; - window: number; - breachEvents: StreamEvent[]; -} - -export class AlertRulesEngine { - private rules: Map = new Map(); - private history: AlertTriggerEvent[] = []; - private stream: EventStream; - private onTrigger?: (event: AlertTriggerEvent) => Promise; - private maxHistorySize: number = 10000; - - constructor(stream: EventStream) { - this.stream = stream; - } - - /** - * Add or update alert rule - */ - addRule(rule: Omit): AlertRule { - const fullRule: AlertRule = { - ...rule, - id: IdGenerators.alert(), - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }; - - this.rules.set(fullRule.id, fullRule); - return fullRule; - } - - /** - * Remove rule by ID - */ - removeRule(ruleId: string): boolean { - return this.rules.delete(ruleId); - } - - /** - * Get rule by ID - */ - getRule(ruleId: string): AlertRule | undefined { - return this.rules.get(ruleId); - } - - /** - * Get all rules - */ - getAllRules(): AlertRule[] { - return Array.from(this.rules.values()); - } - - /** - * Get active (non-acknowledged) rules - */ - getActiveAlerts(authorId?: string): AlertRule[] { - const now = Date.now(); - return Array.from(this.rules.values()).filter((rule) => { - // Skip if acknowledged - if (rule.acknowledgedUntil && rule.acknowledgedUntil > now) { - return false; - } - // Filter by author if provided - return !authorId || rule.description.includes(authorId); - }); - } - - /** - * Evaluate rule against stream events - */ - evaluateRule(rule: AlertRule): { triggered: boolean; value: number } { - if (!rule.enabled) { - return { triggered: false, value: 0 }; - } - - const windowMs = rule.condition.window * 1000; - const events = this.stream.query(windowMs, (event) => - this.matchesMetric(event, rule.condition.metric), - ); - - const value = this.aggregateValue(events, rule.condition); - const triggered = this.evaluateCondition( - value, - rule.condition.operator, - rule.condition.threshold, - ); - - return { triggered, value }; - } - - /** - * Evaluate all rules and trigger actions - */ - async evaluateAll(): Promise { - const triggered: AlertTriggerEvent[] = []; - - for (const rule of this.rules.values()) { - const { triggered: shouldTrigger, value } = this.evaluateRule(rule); - - if (shouldTrigger) { - const windowMs = rule.condition.window * 1000; - const breachEvents = this.stream.query(windowMs, (event) => - this.matchesMetric(event, rule.condition.metric), - ); - - const triggerEvent: AlertTriggerEvent = { - ruleId: rule.id, - triggeredAt: Date.now(), - value, - threshold: rule.condition.threshold, - window: rule.condition.window, - breachEvents, - }; - - // Check if already triggered recently (within 5 minutes) - const recentTrigger = this.history.find( - (h) => - h.ruleId === rule.id && - Date.now() - h.triggeredAt < 5 * 60 * 1000, - ); - - if (!recentTrigger) { - triggered.push(triggerEvent); - this.recordTrigger(triggerEvent); - - // Update rule - rule.lastTriggered = new Date().toISOString(); - rule.evaluatedAt = new Date().toISOString(); - - // Dispatch actions - if (this.onTrigger) { - await this.onTrigger(triggerEvent); - } - } - } - } - - return triggered; - } - - /** - * Acknowledge alert to suppress duplicates - */ - acknowledgeAlert(ruleId: string, suppressMinutes: number = 60): void { - const rule = this.rules.get(ruleId); - if (rule) { - rule.acknowledgedUntil = Date.now() + suppressMinutes * 60 * 1000; - } - } - - /** - * Get alert trigger history - */ - getHistory( - ruleId?: string, - limit: number = 100, - offset: number = 0, - ): AlertTriggerEvent[] { - let results = this.history; - if (ruleId) { - results = results.filter((h) => h.ruleId === ruleId); - } - return results.slice(offset, offset + limit); - } - - /** - * Clear history - */ - clearHistory(): void { - this.history = []; - } - - /** - * Set trigger callback - */ - setTriggerCallback(callback: (event: AlertTriggerEvent) => Promise): void { - this.onTrigger = callback; - } - - // ─── Private Helpers ──────────────────────────────────────────────────── - - private recordTrigger(event: AlertTriggerEvent): void { - this.history.push(event); - if (this.history.length > this.maxHistorySize) { - this.history = this.history.slice(-this.maxHistorySize); - } - } - - private matchesMetric(event: StreamEvent, metric: AlertMetric): boolean { - switch (metric) { - case "error_rate": - return ( - event.type === "metric" && - event.data.metric === "error_rate" - ); - case "response_time": - return ( - event.type === "metric" && - event.data.metric === "response_time" - ); - case "downloads": - return ( - event.type === "metric" && - event.data.metric === "downloads" - ); - case "revenue": - return ( - event.type === "metric" && - event.data.metric === "revenue" - ); - case "sla_breach": - return event.severity === "critical" && event.data.sla_breach === true; - case "payout_delay": - return ( - event.type === "alert" && - event.data.alertType === "payout_delay" - ); - case "abuse_score": - return ( - event.type === "metric" && - event.data.metric === "abuse_score" - ); - default: - return false; - } - } - - private aggregateValue( - events: StreamEvent[], - condition: AlertCondition, - ): number { - if (events.length === 0) return 0; - - const values = events.map((e) => e.data.value || 0); - - switch (condition.aggregation) { - case "avg": - return values.reduce((a, b) => a + b, 0) / values.length; - case "max": - return Math.max(...values); - case "min": - return Math.min(...values); - case "sum": - return values.reduce((a, b) => a + b, 0); - case "count": - return values.length; - default: - return 0; - } - } - - private evaluateCondition( - value: number, - operator: AlertOperator, - threshold: number, - ): boolean { - switch (operator) { - case ">": - return value > threshold; - case "<": - return value < threshold; - case "==": - return value === threshold; - case "!=": - return value !== threshold; - case "anomaly": - // Simplified: value is 2+ std devs above mean - return Math.abs(value - threshold) > threshold * 0.2; - default: - return false; - } - } -} diff --git a/src/analytics-service.test.ts b/src/analytics-service.test.ts deleted file mode 100644 index aab38b13..00000000 --- a/src/analytics-service.test.ts +++ /dev/null @@ -1,306 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { AnalyticsService } from "./analytics-service.js"; - -describe("AnalyticsService", () => { - let service: AnalyticsService; - let mockDb: any; - - beforeEach(() => { - mockDb = { - query: async (sql: string, params: any[]) => { - // Return default result to avoid undefined errors - const defaultResult = { - rows: [{ - id: params[0], - count: 100, - total: "10000", - downloads: 5000, - rating: 4.5, - revenue: "5000.00", - }], - }; - - if (sql.includes("SELECT") && sql.includes("p.id") && sql.includes("plugins p") && sql.includes("LEFT JOIN plugin_installations")) { - // getPluginAnalytics main query - return { - rows: [{ - id: params[0], - downloads: 5000, - rating: 4.8, - reviews_count: 120, - trending_score: 850, - unique_installs: 2400, - last_updated: new Date().toISOString(), - }], - }; - } - if (sql.includes("DATE_TRUNC") && sql.includes("plugin_downloads")) { - // getMonthlyDownloads - return { - rows: [ - { month: "2026-04-01T00:00:00", downloads: 1500 }, - { month: "2026-03-01T00:00:00", downloads: 1200 }, - { month: "2026-02-01T00:00:00", downloads: 1000 }, - ], - }; - } - if (sql.includes("DATE_TRUNC") && sql.includes("plugin_installations")) { - // getMonthlyInstallations - return { - rows: [ - { month: "2026-04-01T00:00:00", installations: 800 }, - { month: "2026-03-01T00:00:00", installations: 700 }, - { month: "2026-02-01T00:00:00", installations: 600 }, - ], - }; - } - if (sql.includes("COUNT(DISTINCT p.id) as total_plugins") && sql.includes("SUM(p.downloads)")) { - // getAuthorAnalytics main query - return { - rows: [{ - id: params[0], - name: "Test Author", - total_plugins: 3, - total_downloads: 15000, - total_installations: 7200, - avg_rating: 4.7, - total_earnings: "45000.00", - created_at: new Date().toISOString(), - }], - }; - } - if (sql.includes("SELECT id FROM plugins") && sql.includes("ORDER BY downloads")) { - // getAuthorTopPlugins - return { - rows: [ - { id: "plugin-1" }, - { id: "plugin-2" }, - { id: "plugin-3" }, - ], - }; - } - if (sql.includes("DATE_TRUNC") && sql.includes("period") && sql.includes("plugin_revenue")) { - // getMonthlyEarnings - return { - rows: [ - { month: "2026-04-01T00:00:00", earnings: "15000.00" }, - { month: "2026-03-01T00:00:00", earnings: "12000.00" }, - { month: "2026-02-01T00:00:00", earnings: "18000.00" }, - ], - }; - } - if (sql.includes("plugin_id") && sql.includes("period") && sql.includes("plugin_revenue")) { - // getPluginRevenueMetrics - return { - rows: [ - { - plugin_id: params[0], - period: "2026-04", - downloads: 1500, - conversions: 150, - total_revenue: 750, - author_share: 600, - kit_share: 150, - conversion_rate: 0.1, - }, - { - plugin_id: params[0], - period: "2026-03", - downloads: 1200, - conversions: 120, - total_revenue: 600, - author_share: 480, - kit_share: 120, - conversion_rate: 0.1, - }, - ], - }; - } - if (sql.includes("COUNT(*) as count FROM plugins") && !sql.includes("DISTINCT")) { - // getDashboardMetrics - total plugins - return { rows: [{ count: 1250 }] }; - } - if (sql.includes("SUM(downloads) as total FROM plugins")) { - // getDashboardMetrics - total downloads - return { rows: [{ total: "500000" }] }; - } - if (sql.includes("SUM(author_earnings) as total FROM plugin_revenue") && !sql.includes("DISTINCT")) { - // getDashboardMetrics - total earnings - return { rows: [{ total: "1200000.00" }] }; - } - if (sql.includes("COUNT(DISTINCT author_id) as count FROM plugins")) { - // getDashboardMetrics - active authors - return { rows: [{ count: 340 }] }; - } - if (sql.includes("SELECT id, downloads, rating FROM plugins ORDER BY downloads")) { - // getDashboardMetrics - top plugins - return { - rows: [ - { id: "plugin-1", downloads: 25000, rating: 4.9 }, - { id: "plugin-2", downloads: 20000, rating: 4.8 }, - { id: "plugin-3", downloads: 18000, rating: 4.7 }, - ], - }; - } - if (sql.includes("SUM(author_earnings + kit_commission) as revenue")) { - // getDashboardMetrics - revenue by month - return { - rows: [ - { month: "2026-04", revenue: "185000.00" }, - { month: "2026-03", revenue: "165000.00" }, - { month: "2026-02", revenue: "195000.00" }, - ], - }; - } - if (sql.includes("SUM(downloads) as downloads") && sql.includes("plugin_tags")) { - // getDashboardMetrics - downloads by category - return { - rows: [ - { tag: "database", downloads: 125000 }, - { tag: "auth", downloads: 95000 }, - { tag: "hosting", downloads: 85000 }, - ], - }; - } - if (sql.includes("ORDER BY trending_score DESC")) { - // getTrendingPlugins - return { - rows: Array.from({ length: params[0] || 10 }, (_, i) => ({ - id: `trending-plugin-${i + 1}`, - })), - }; - } - if (sql.includes("plugin_downloads d") && sql.includes("plugin_installations i")) { - // getAnalyticsByDateRange - return { - rows: [{ - unique_downloads: 2500, - unique_installations: 1800, - total_revenue: "125000.00", - unique_authors: 180, - }], - }; - } - - return defaultResult; - }, - }; - - service = new AnalyticsService(mockDb); - }); - - describe("getPluginAnalytics", () => { - it("retrieves plugin analytics", async () => { - const analytics = await service.getPluginAnalytics("plugin-1"); - assert.ok(analytics); - assert.equal(analytics.pluginId, "plugin-1"); - assert.equal(analytics.totalDownloads, 5000); - assert.equal(analytics.rating, 4.8); - assert.equal(analytics.reviewsCount, 120); - }); - - it("returns null for nonexistent plugin", async () => { - mockDb.query = async (sql: string) => { - if (sql.includes("p.id") && sql.includes("plugins p")) { - return { rows: [] }; - } - return { rows: [] }; - }; - service = new AnalyticsService(mockDb); - const analytics = await service.getPluginAnalytics("nonexistent"); - assert.equal(analytics, null); - }); - - it("calculates retention rate", async () => { - const analytics = await service.getPluginAnalytics("plugin-1"); - assert.ok(analytics); - // retentionRate = (2400 / 5000) * 100 = 48% - assert.ok(analytics.retentionRate > 40 && analytics.retentionRate < 50); - }); - - it("includes monthly download history", async () => { - const analytics = await service.getPluginAnalytics("plugin-1"); - assert.ok(analytics); - assert.ok(Array.isArray(analytics.monthlyDownloads)); - assert.ok(analytics.monthlyDownloads.length > 0); - }); - }); - - describe("getAuthorAnalytics", () => { - it("retrieves author basic data", async () => { - const analytics = await service.getAuthorAnalytics("author-1"); - if (analytics) { - assert.equal(analytics.authorId, analytics.authorId); - assert.ok(true); // Just verify it returns something - } else { - assert.ok(true); // OK if null - } - }); - }); - - describe("getPluginRevenueMetrics", () => { - it("retrieves revenue metrics for plugin", async () => { - const metrics = await service.getPluginRevenueMetrics("plugin-1"); - assert.ok(Array.isArray(metrics)); - assert.ok(metrics.length > 0); - - const first = metrics[0]; - assert.equal(first.pluginId, "plugin-1"); - assert.equal(first.period, "2026-04"); - assert.equal(first.downloads, 1500); - assert.ok(first.totalRevenue > 0); - }); - - it("calculates author and kit shares correctly", async () => { - const metrics = await service.getPluginRevenueMetrics("plugin-1"); - assert.ok(metrics.length > 0); - - const first = metrics[0]; - // Author share should be ~80% of total revenue - const expectedAuthorShare = first.totalRevenue * 0.8; - assert.ok(Math.abs(first.authorShare - expectedAuthorShare) < 10); - }); - - it("calculates conversion rates", async () => { - const metrics = await service.getPluginRevenueMetrics("plugin-1"); - assert.ok(metrics.length > 0); - - const first = metrics[0]; - assert.ok(first.conversionRate >= 0 && first.conversionRate <= 1); - }); - }); - - describe("getDashboardMetrics", () => { - it("has getDashboardMetrics method", () => { - assert.ok(typeof service.getDashboardMetrics === 'function'); - }); - }); - - describe("getTrendingPlugins", () => { - it("returns trending plugins", async () => { - const plugins = await service.getTrendingPlugins(10); - assert.ok(Array.isArray(plugins)); - }); - - it("respects limit parameter", async () => { - const plugins = await service.getTrendingPlugins(5); - assert.ok(Array.isArray(plugins)); - assert.ok(plugins.length <= 5); - }); - }); - - describe("getAnalyticsByDateRange", () => { - it("returns analytics object for date range", async () => { - const startDate = new Date("2026-04-01"); - const endDate = new Date("2026-04-30"); - const analytics = await service.getAnalyticsByDateRange(startDate, endDate); - - assert.ok(analytics); - assert.ok(typeof analytics.downloads === 'number'); - assert.ok(typeof analytics.installations === 'number'); - assert.ok(typeof analytics.revenue === 'number'); - assert.ok(typeof analytics.authors === 'number'); - }); - }); -}); diff --git a/src/analytics-service.ts b/src/analytics-service.ts deleted file mode 100644 index 712d49ea..00000000 --- a/src/analytics-service.ts +++ /dev/null @@ -1,463 +0,0 @@ -/** - * kit Analytics Service - * - * Aggregates plugin downloads, installations, ratings, and revenue data - * for developer dashboards and marketplace insights. - */ - -export interface PluginAnalytics { - pluginId: string; - totalDownloads: number; - monthlyDownloads: { month: string; downloads: number }[]; - totalInstallations: number; - monthlyInstallations: { month: string; installations: number }[]; - rating: number; - reviewsCount: number; - trendingScore: number; - uniqueInstalls: number; - retentionRate: number; - lastUpdated: string; -} - -export interface AuthorAnalytics { - authorId: string; - totalEarnings: number; - monthlyEarnings: { month: string; earnings: number }[]; - topPlugins: string[]; - totalDownloads: number; - totalInstallations: number; - averageRating: number; - totalGrants: number; - grantsFunded: number; - createdAt: string; - lastUpdated: string; -} - -export interface RevenueMetrics { - pluginId: string; - period: string; // "2026-04" - downloads: number; - conversions: number; - totalRevenue: number; - authorShare: number; // 80% - kitShare: number; // 20% - conversionRate: number; -} - -export interface DashboardMetrics { - totalPlugins: number; - totalDownloads: number; - totalEarnings: number; - activeAuthors: number; - topPlugins: { pluginId: string; downloads: number; rating: number }[]; - revenueByMonth: { month: string; revenue: number }[]; - downloadsByCategory: { category: string; downloads: number }[]; -} - -/** - * Analytics service for marketplace insights and revenue tracking - */ -export class AnalyticsService { - private db: any; - - constructor(db?: any) { - this.db = db; - } - - /** - * Get plugin analytics - */ - async getPluginAnalytics(pluginId: string): Promise { - const result = await this.db.query( - ` - SELECT - p.id, - p.downloads, - p.rating, - p.reviews_count, - p.trending_score, - COUNT(DISTINCT pi.id) as unique_installs, - p.last_updated - FROM plugins p - LEFT JOIN plugin_installations pi ON p.id = pi.plugin_id - WHERE p.id = $1 - GROUP BY p.id, p.downloads, p.rating, p.reviews_count, p.trending_score, p.last_updated - `, - [pluginId], - ); - - if (result.rows.length === 0) { - return null; - } - - const plugin = result.rows[0]; - - // Get monthly downloads - const monthlyDownloads = await this.getMonthlyDownloads(pluginId); - - // Get monthly installations - const monthlyInstallations = await this.getMonthlyInstallations(pluginId); - - return { - pluginId: plugin.id, - totalDownloads: plugin.downloads || 0, - monthlyDownloads, - totalInstallations: plugin.unique_installs || 0, - monthlyInstallations, - rating: plugin.rating || 0, - reviewsCount: plugin.reviews_count || 0, - trendingScore: plugin.trending_score || 0, - uniqueInstalls: plugin.unique_installs || 0, - retentionRate: this.calculateRetentionRate( - plugin.unique_installs, - plugin.downloads, - ), - lastUpdated: plugin.last_updated || new Date().toISOString(), - }; - } - - /** - * Get monthly downloads for plugin - */ - private async getMonthlyDownloads( - pluginId: string, - ): Promise<{ month: string; downloads: number }[]> { - const result = await this.db.query( - ` - SELECT - DATE_TRUNC('month', downloaded_at)::text as month, - COUNT(*) as downloads - FROM plugin_downloads - WHERE plugin_id = $1 - GROUP BY DATE_TRUNC('month', downloaded_at) - ORDER BY month DESC - LIMIT 12 - `, - [pluginId], - ); - - return result.rows.map((row: any) => ({ - month: row.month.split('T')[0], - downloads: row.downloads, - })); - } - - /** - * Get monthly installations for plugin - */ - private async getMonthlyInstallations( - pluginId: string, - ): Promise<{ month: string; installations: number }[]> { - const result = await this.db.query( - ` - SELECT - DATE_TRUNC('month', installed_at)::text as month, - COUNT(*) as installations - FROM plugin_installations - WHERE plugin_id = $1 - GROUP BY DATE_TRUNC('month', installed_at) - ORDER BY month DESC - LIMIT 12 - `, - [pluginId], - ); - - return result.rows.map((row: any) => ({ - month: row.month.split('T')[0], - installations: row.installations, - })); - } - - /** - * Calculate retention rate (installations/downloads ratio) - */ - private calculateRetentionRate(installations: number, downloads: number): number { - if (downloads === 0) return 0; - return (installations / downloads) * 100; - } - - /** - * Get author analytics - */ - async getAuthorAnalytics(authorId: string): Promise { - const result = await this.db.query( - ` - SELECT - a.id, - a.name, - COUNT(DISTINCT p.id) as total_plugins, - SUM(p.downloads) as total_downloads, - COUNT(DISTINCT pi.id) as total_installations, - AVG(p.rating) as avg_rating, - COALESCE(pr.total_earnings, 0) as total_earnings, - a.created_at - FROM authors a - LEFT JOIN plugins p ON a.id = p.author_id - LEFT JOIN plugin_installations pi ON p.id = pi.plugin_id - LEFT JOIN ( - SELECT - author_id, - SUM(author_earnings) as total_earnings - FROM plugin_revenue - GROUP BY author_id - ) pr ON a.id = pr.author_id - WHERE a.id = $1 - GROUP BY a.id, a.name, a.created_at, pr.total_earnings - `, - [authorId], - ); - - if (result.rows.length === 0) { - return null; - } - - const author = result.rows[0]; - - // Get top plugins by downloads - const topPlugins = await this.getAuthorTopPlugins(authorId, 5); - - // Get monthly earnings - const monthlyEarnings = await this.getMonthlyEarnings(authorId); - - return { - authorId: author.id, - totalEarnings: parseFloat(author.total_earnings) || 0, - monthlyEarnings, - topPlugins, - totalDownloads: author.total_downloads || 0, - totalInstallations: author.total_installations || 0, - averageRating: parseFloat(author.avg_rating) || 0, - totalGrants: 0, // From grant_applications table - grantsFunded: 0, // From grant_applications where status='approved' - createdAt: author.created_at, - lastUpdated: new Date().toISOString(), - }; - } - - /** - * Get author's top plugins by downloads - */ - private async getAuthorTopPlugins( - authorId: string, - limit: number = 5, - ): Promise { - const result = await this.db.query( - ` - SELECT id FROM plugins - WHERE author_id = $1 - ORDER BY downloads DESC - LIMIT $2 - `, - [authorId, limit], - ); - - return result.rows.map((row: any) => row.id); - } - - /** - * Get monthly earnings for author - */ - private async getMonthlyEarnings( - authorId: string, - ): Promise<{ month: string; earnings: number }[]> { - const result = await this.db.query( - ` - SELECT - DATE_TRUNC('month', period)::text as month, - SUM(author_earnings) as earnings - FROM plugin_revenue - WHERE ( - SELECT author_id FROM plugins WHERE id = plugin_id - ) = $1 - GROUP BY DATE_TRUNC('month', period) - ORDER BY month DESC - LIMIT 12 - `, - [authorId], - ); - - return result.rows.map((row: any) => ({ - month: row.month.split('T')[0], - earnings: parseFloat(row.earnings) || 0, - })); - } - - /** - * Get revenue metrics for plugin - */ - async getPluginRevenueMetrics(pluginId: string): Promise { - const result = await this.db.query( - ` - SELECT - plugin_id, - period, - downloads, - conversions, - (downloads * 0.5) as total_revenue, - (downloads * 0.5 * 0.8) as author_share, - (downloads * 0.5 * 0.2) as kit_share, - CASE WHEN downloads > 0 THEN (conversions::float / downloads) ELSE 0 END as conversion_rate - FROM plugin_revenue - WHERE plugin_id = $1 - ORDER BY period DESC - LIMIT 12 - `, - [pluginId], - ); - - return result.rows.map((row: any) => ({ - pluginId: row.plugin_id, - period: row.period, - downloads: row.downloads, - conversions: row.conversions, - totalRevenue: parseFloat(row.total_revenue) || 0, - authorShare: parseFloat(row.author_share) || 0, - kitShare: parseFloat(row.kit_share) || 0, - conversionRate: parseFloat(row.conversion_rate) || 0, - })); - } - - /** - * Get dashboard metrics (admin view) - */ - async getDashboardMetrics(): Promise { - // Total plugins - const pluginsResult = await this.db.query( - `SELECT COUNT(*) as count FROM plugins`, - ); - const totalPlugins = pluginsResult.rows[0]?.count || 0; - - // Total downloads - const downloadsResult = await this.db.query( - `SELECT SUM(downloads) as total FROM plugins`, - ); - const totalDownloads = parseInt(downloadsResult.rows[0]?.total) || 0; - - // Total earnings - const earningsResult = await this.db.query( - `SELECT SUM(author_earnings) as total FROM plugin_revenue`, - ); - const totalEarnings = parseFloat(earningsResult.rows[0]?.total) || 0; - - // Active authors - const authorsResult = await this.db.query( - `SELECT COUNT(DISTINCT author_id) as count FROM plugins`, - ); - const activeAuthors = authorsResult.rows[0]?.count || 0; - - // Top plugins - const topPluginsResult = await this.db.query( - `SELECT id, downloads, rating FROM plugins ORDER BY downloads DESC LIMIT 5`, - ); - const topPlugins = topPluginsResult.rows || []; - - // Revenue by month - const revenueResult = await this.db.query( - ` - SELECT - period as month, - SUM(author_earnings + kit_commission) as revenue - FROM plugin_revenue - GROUP BY period - ORDER BY month DESC - LIMIT 12 - `, - ); - const revenueByMonth = (revenueResult.rows || []).map((row: any) => ({ - month: row.month, - revenue: parseFloat(row.revenue) || 0, - })); - - // Downloads by category (from tags) - const categoryResult = await this.db.query( - ` - SELECT - tag, - SUM(downloads) as downloads - FROM plugin_tags pt - JOIN plugins p ON pt.plugin_id = p.id - GROUP BY tag - ORDER BY downloads DESC - LIMIT 10 - `, - ); - const downloadsByCategory = (categoryResult.rows || []).map((row: any) => ({ - category: row.tag, - downloads: row.downloads, - })); - - return { - totalPlugins, - totalDownloads, - totalEarnings, - activeAuthors, - topPlugins: topPlugins.map((p: any) => ({ - pluginId: p.id, - downloads: p.downloads, - rating: p.rating, - })), - revenueByMonth, - downloadsByCategory, - }; - } - - /** - * Get trending plugins (by recent downloads) - */ - async getTrendingPlugins(limit: number = 10): Promise { - const result = await this.db.query( - ` - SELECT id FROM plugins - ORDER BY trending_score DESC, downloads DESC - LIMIT $1 - `, - [limit], - ); - - const plugins: PluginAnalytics[] = []; - for (const row of result.rows) { - const analytics = await this.getPluginAnalytics(row.id); - if (analytics) { - plugins.push(analytics); - } - } - return plugins; - } - - /** - * Search analytics by date range - */ - async getAnalyticsByDateRange( - startDate: Date, - endDate: Date, - ): Promise<{ - downloads: number; - installations: number; - revenue: number; - authors: number; - }> { - const result = await this.db.query( - ` - SELECT - COUNT(DISTINCT d.plugin_id) as unique_downloads, - COUNT(DISTINCT i.id) as unique_installations, - COALESCE(SUM(pr.total_earnings), 0) as total_revenue, - COUNT(DISTINCT p.author_id) as unique_authors - FROM plugin_downloads d - FULL OUTER JOIN plugin_installations i ON d.plugin_id = i.plugin_id - LEFT JOIN plugins p ON d.plugin_id = p.id OR i.plugin_id = p.id - LEFT JOIN plugin_revenue pr ON p.id = pr.plugin_id - WHERE (d.downloaded_at BETWEEN $1 AND $2 OR i.installed_at BETWEEN $1 AND $2) - `, - [startDate.toISOString(), endDate.toISOString()], - ); - - const row = result.rows[0]; - return { - downloads: row.unique_downloads || 0, - installations: row.unique_installations || 0, - revenue: parseFloat(row.total_revenue) || 0, - authors: row.unique_authors || 0, - }; - } -} diff --git a/src/apm-instrumentor.test.ts b/src/apm-instrumentor.test.ts deleted file mode 100644 index 548288c1..00000000 --- a/src/apm-instrumentor.test.ts +++ /dev/null @@ -1,322 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { APMInstrumentor } from "./apm-instrumentor.js"; - -describe("APMInstrumentor", () => { - describe("tracing", () => { - let apm: APMInstrumentor; - - beforeEach(() => { - apm = new APMInstrumentor("test-service"); - }); - - it("starts a trace", () => { - const trace = apm.startTrace("user_request"); - assert(trace.id); - assert.equal(trace.name, "user_request"); - assert.equal(trace.status, "pending"); - }); - - it("ends a trace", () => { - const trace = apm.startTrace("request"); - const ended = apm.endTrace(trace.id, "success"); - assert(ended); - assert.equal(ended.status, "success"); - assert(ended.endTime); - assert(ended.duration >= 0); - }); - - it("calculates trace duration", () => { - const trace = apm.startTrace("request"); - apm.endTrace(trace.id); - const retrieved = apm.getTrace(trace.id); - assert(retrieved); - assert(retrieved.duration >= 0); - }); - - it("marks trace as error", () => { - const trace = apm.startTrace("request"); - apm.endTrace(trace.id, "error"); - const retrieved = apm.getTrace(trace.id); - assert.equal(retrieved?.status, "error"); - }); - - it("gets trace by ID", () => { - const trace = apm.startTrace("request"); - const retrieved = apm.getTrace(trace.id); - assert(retrieved); - assert.equal(retrieved.name, "request"); - }); - - it("returns null for unknown trace", () => { - const trace = apm.getTrace("unknown"); - assert.equal(trace, null); - }); - - it("gets recent traces", () => { - apm.startTrace("trace1"); - apm.startTrace("trace2"); - apm.startTrace("trace3"); - - const recent = apm.getRecentTraces(10); - // Recent traces would be empty until they're ended - assert(Array.isArray(recent)); - }); - - it("gets slow traces", () => { - const trace = apm.startTrace("slow_request"); - apm.endTrace(trace.id); - - const slow = apm.getSlowTraces(0); // All traces are >= 0ms - assert(slow.length > 0); - }); - }); - - describe("spans", () => { - let apm: APMInstrumentor; - let traceId: string; - - beforeEach(() => { - apm = new APMInstrumentor("test-service"); - const trace = apm.startTrace("request"); - traceId = trace.id; - }); - - it("starts a span", () => { - const span = apm.startSpan(traceId, "database_query", "SELECT"); - assert(span.id); - assert.equal(span.name, "database_query"); - assert.equal(span.operation, "SELECT"); - assert.equal(span.status, "pending"); - }); - - it("ends a span", () => { - const span = apm.startSpan(traceId, "db_query", "SELECT"); - const ended = apm.endSpan(span.id, "success"); - assert(ended); - assert.equal(ended.status, "success"); - assert(ended.duration >= 0); - }); - - it("supports nested spans with parent ID", () => { - const parentSpan = apm.startSpan(traceId, "http_request", "GET"); - const childSpan = apm.startSpan( - traceId, - "database_query", - "SELECT", - parentSpan.id, - ); - assert.equal(childSpan.parentId, parentSpan.id); - }); - - it("adds tags to span", () => { - const span = apm.startSpan(traceId, "http_request", "GET"); - apm.addTag(span.id, "http.status_code", 200); - apm.addTag(span.id, "http.method", "GET"); - assert.equal(Object.keys(span.tags).length, 2); - }); - - it("adds logs to span", () => { - const span = apm.startSpan(traceId, "operation", "EXECUTE"); - apm.addLog(span.id, "Starting operation"); - apm.addLog(span.id, "Operation completed"); - assert.equal(span.logs.length, 2); - }); - - it("returns null for unknown span", () => { - const span = apm.endSpan("unknown"); - assert.equal(span, null); - }); - }); - - describe("metrics", () => { - let apm: APMInstrumentor; - - beforeEach(() => { - apm = new APMInstrumentor("test-service"); - }); - - it("records performance metric", () => { - apm.recordMetric("response_time", 125, "ms"); - const metrics = apm.getAllMetrics(); - assert.equal(metrics.length, 1); - assert.equal(metrics[0].name, "response_time"); - assert.equal(metrics[0].value, 125); - }); - - it("gets metrics by name", () => { - apm.recordMetric("response_time", 100); - apm.recordMetric("response_time", 200); - apm.recordMetric("cpu_usage", 45); - - const responseTimes = apm.getMetricsByName("response_time"); - assert.equal(responseTimes.length, 2); - }); - - it("calculates metric statistics", () => { - apm.recordMetric("latency", 100); - apm.recordMetric("latency", 200); - apm.recordMetric("latency", 300); - - const stats = apm.getMetricStats("latency"); - assert(stats); - assert.equal(stats.min, 100); - assert.equal(stats.max, 300); - assert.equal(stats.average, 200); - assert.equal(stats.count, 3); - }); - - it("returns null for unknown metric", () => { - const stats = apm.getMetricStats("unknown"); - assert.equal(stats, null); - }); - - it("gets all metrics", () => { - apm.recordMetric("metric1", 100); - apm.recordMetric("metric2", 200); - - const metrics = apm.getAllMetrics(); - assert.equal(metrics.length, 2); - }); - }); - - describe("service metrics", () => { - let apm: APMInstrumentor; - - beforeEach(() => { - apm = new APMInstrumentor("api-service"); - }); - - it("returns service metrics", () => { - const trace = apm.startTrace("request"); - apm.endTrace(trace.id); - - const metrics = apm.getServiceMetrics(); - assert.equal(metrics.serviceName, "api-service"); - assert.equal(metrics.requestCount, 1); - assert(metrics.averageResponseTime >= 0); - }); - - it("calculates error count", () => { - const trace1 = apm.startTrace("request1"); - const trace2 = apm.startTrace("request2"); - apm.endTrace(trace1.id, "success"); - apm.endTrace(trace2.id, "error"); - - const metrics = apm.getServiceMetrics(); - assert.equal(metrics.errorCount, 1); - }); - - it("calculates average response time", () => { - apm.startTrace("req1"); - apm.startTrace("req2"); - - const metrics = apm.getServiceMetrics(); - assert(metrics.averageResponseTime >= 0); - }); - - it("calculates p95 and p99 percentiles", () => { - for (let i = 0; i < 100; i++) { - const trace = apm.startTrace(`request_${i}`); - apm.endTrace(trace.id); - } - - const metrics = apm.getServiceMetrics(); - assert(metrics.p95ResponseTime >= 0); - assert(metrics.p99ResponseTime >= 0); - }); - - it("calculates throughput", () => { - const trace = apm.startTrace("request"); - apm.endTrace(trace.id); - - const metrics = apm.getServiceMetrics(); - assert(metrics.throughput >= 0); - }); - }); - - describe("health checks", () => { - let apm: APMInstrumentor; - - beforeEach(() => { - apm = new APMInstrumentor("service"); - }); - - it("checks service health", () => { - const trace = apm.startTrace("request"); - apm.endTrace(trace.id); - - const health = apm.checkHealth(); - assert(typeof health.healthy === "boolean"); - assert(typeof health.status === "string"); - assert(health.metrics); - }); - - it("marks service as healthy when response times are good", () => { - const trace = apm.startTrace("fast_request"); - apm.endTrace(trace.id); - - const health = apm.checkHealth(); - assert(health.healthy); - }); - - it("marks service as degraded when error rate is high", () => { - // Create multiple traces with errors to trigger > 5% error rate - for (let i = 0; i < 20; i++) { - const trace = apm.startTrace(`request_${i}`); - apm.endTrace(trace.id, i < 2 ? "error" : "success"); - } - - const health = apm.checkHealth(); - // With 20 requests and 2 errors, error rate is 10% which should trigger degraded - assert(!health.healthy); - }); - }); - - describe("service name", () => { - it("uses provided service name", () => { - const apm = new APMInstrumentor("custom-service"); - const metrics = apm.getServiceMetrics(); - assert.equal(metrics.serviceName, "custom-service"); - }); - - it("uses default service name", () => { - const apm = new APMInstrumentor(); - const metrics = apm.getServiceMetrics(); - assert.equal(metrics.serviceName, "default-service"); - }); - }); - - describe("cache helpers", () => { - let apm: APMInstrumentor; - - beforeEach(() => { - apm = new APMInstrumentor(); - }); - - it("returns trace cache", () => { - apm.startTrace("trace1"); - apm.startTrace("trace2"); - - const cache = apm.getTraceCache(); - assert.equal(cache.size, 2); - }); - - it("returns span cache", () => { - const trace = apm.startTrace("request"); - apm.startSpan(trace.id, "span1", "OP"); - apm.startSpan(trace.id, "span2", "OP"); - - const cache = apm.getSpanCache(); - assert.equal(cache.size, 2); - }); - - it("returns metrics cache", () => { - apm.recordMetric("m1", 100); - apm.recordMetric("m2", 200); - - const cache = apm.getMetricsCache(); - assert.equal(cache.length, 2); - }); - }); -}); diff --git a/src/apm-instrumentor.ts b/src/apm-instrumentor.ts deleted file mode 100644 index fab0a647..00000000 --- a/src/apm-instrumentor.ts +++ /dev/null @@ -1,315 +0,0 @@ -import { IdGenerators } from "./id-generator.js"; -// ─── Types ──────────────────────────────────────────────────────────────────── - -export interface TraceSpan { - id: string; - traceId: string; - parentId?: string; - name: string; - operation: string; - duration: number; // milliseconds - startTime: string; - endTime: string; - status: "success" | "error" | "pending"; - tags: Record; - logs: Array<{ timestamp: string; message: string }>; -} - -export interface Trace { - id: string; - name: string; - startTime: string; - endTime: string; - duration: number; - spans: TraceSpan[]; - status: "success" | "error" | "pending"; -} - -export interface PerformanceMetric { - name: string; - value: number; - unit: string; - timestamp: string; -} - -export interface ServiceMetrics { - serviceName: string; - requestCount: number; - errorCount: number; - averageResponseTime: number; - p95ResponseTime: number; - p99ResponseTime: number; - throughput: number; // requests per second -} - -// ─── APMInstrumentor ────────────────────────────────────────────────────────── - -export class APMInstrumentor { - private traces: Map = new Map(); - private spans: Map = new Map(); - private metrics: PerformanceMetric[] = []; - private serviceName: string; - - constructor(serviceName: string = "default-service") { - this.serviceName = serviceName; - } - - // ─── Tracing ────────────────────────────────────────────────────────────── - - /** - * Start a new trace. - */ - startTrace(name: string): Trace { - const id = IdGenerators.trace(); - const trace: Trace = { - id, - name, - startTime: new Date().toISOString(), - endTime: "", - duration: 0, - spans: [], - status: "pending", - }; - - this.traces.set(id, trace); - return trace; - } - - /** - * End a trace. - */ - endTrace(traceId: string, status: "success" | "error" = "success"): Trace | null { - const trace = this.traces.get(traceId); - if (!trace) return null; - - trace.endTime = new Date().toISOString(); - trace.duration = - new Date(trace.endTime).getTime() - new Date(trace.startTime).getTime(); - trace.status = status; - - return trace; - } - - /** - * Start a span within a trace. - */ - startSpan( - traceId: string, - name: string, - operation: string, - parentId?: string, - ): TraceSpan { - const span: TraceSpan = { - id: IdGenerators.span(), - traceId, - parentId, - name, - operation, - duration: 0, - startTime: new Date().toISOString(), - endTime: "", - status: "pending", - tags: {}, - logs: [], - }; - - this.spans.set(span.id, span); - - // Add span to trace - const trace = this.traces.get(traceId); - if (trace) { - trace.spans.push(span); - } - - return span; - } - - /** - * End a span. - */ - endSpan(spanId: string, status: "success" | "error" = "success"): TraceSpan | null { - const span = this.spans.get(spanId); - if (!span) return null; - - span.endTime = new Date().toISOString(); - span.duration = - new Date(span.endTime).getTime() - new Date(span.startTime).getTime(); - span.status = status; - - return span; - } - - /** - * Add tag to span. - */ - addTag(spanId: string, key: string, value: unknown): void { - const span = this.spans.get(spanId); - if (span) { - span.tags[key] = value; - } - } - - /** - * Add log entry to span. - */ - addLog(spanId: string, message: string): void { - const span = this.spans.get(spanId); - if (span) { - span.logs.push({ - timestamp: new Date().toISOString(), - message, - }); - } - } - - /** - * Get trace by ID. - */ - getTrace(traceId: string): Trace | null { - return this.traces.get(traceId) || null; - } - - /** - * Get recent traces. - */ - getRecentTraces(limit = 10): Trace[] { - return [...this.traces.values()] - .filter((t) => t.endTime) // completed traces - .sort((a, b) => new Date(b.endTime).getTime() - new Date(a.endTime).getTime()) - .slice(0, limit); - } - - /** - * Get slow traces (above or equal to threshold). - */ - getSlowTraces(thresholdMs: number = 1000): Trace[] { - return [...this.traces.values()].filter((t) => t.endTime && t.duration >= thresholdMs); - } - - // ─── Metrics ────────────────────────────────────────────────────────────── - - /** - * Record performance metric. - */ - recordMetric(name: string, value: number, unit: string = "ms"): void { - this.metrics.push({ - name, - value, - unit, - timestamp: new Date().toISOString(), - }); - } - - /** - * Get service metrics. - */ - getServiceMetrics(): ServiceMetrics { - const traces = [...this.traces.values()].filter((t) => t.endTime); - const responseTimes = traces.map((t) => t.duration).sort((a, b) => a - b); - - const getPercentile = (p: number): number => { - if (responseTimes.length === 0) return 0; - const index = Math.ceil((responseTimes.length * p) / 100) - 1; - return Math.max(0, responseTimes[index] || 0); - }; - - const errors = traces.filter((t) => t.status === "error").length; - const totalDuration = traces.reduce((sum, t) => sum + t.duration, 0); - const avgResponseTime = - traces.length > 0 ? totalDuration / traces.length : 0; - - // Calculate throughput (requests per second) - const timespan = - traces.length > 0 - ? (new Date(traces[traces.length - 1].startTime).getTime() - - new Date(traces[0].startTime).getTime()) / - 1000 - : 0; - const throughput = timespan > 0 ? traces.length / timespan : 0; - - return { - serviceName: this.serviceName, - requestCount: traces.length, - errorCount: errors, - averageResponseTime: Math.round(avgResponseTime), - p95ResponseTime: getPercentile(95), - p99ResponseTime: getPercentile(99), - throughput: Math.round(throughput * 100) / 100, - }; - } - - /** - * Get metrics by name. - */ - getMetricsByName(name: string): PerformanceMetric[] { - return this.metrics.filter((m) => m.name === name); - } - - /** - * Get all metrics. - */ - getAllMetrics(): PerformanceMetric[] { - return [...this.metrics]; - } - - /** - * Get metric statistics. - */ - getMetricStats(name: string): { - min: number; - max: number; - average: number; - count: number; - } | null { - const metrics = this.getMetricsByName(name); - if (metrics.length === 0) return null; - - const values = metrics.map((m) => m.value); - const sum = values.reduce((a, b) => a + b, 0); - - return { - min: Math.min(...values), - max: Math.max(...values), - average: sum / values.length, - count: values.length, - }; - } - - // ─── Health Check ──────────────────────────────────────────────────────── - - /** - * Check service health based on metrics. - */ - checkHealth(): { healthy: boolean; status: string; metrics: ServiceMetrics } { - const metrics = this.getServiceMetrics(); - const errorRate = metrics.requestCount > 0 ? metrics.errorCount / metrics.requestCount : 0; - - let healthy = true; - let status = "healthy"; - - if (metrics.averageResponseTime > 2000) { - healthy = false; - status = "degraded - slow response times"; - } else if (errorRate > 0.05) { - // > 5% error rate - healthy = false; - status = "unhealthy - high error rate"; - } - - return { healthy, status, metrics }; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getTraceCache(): Map { - return this.traces; - } - - getSpanCache(): Map { - return this.spans; - } - - getMetricsCache(): PerformanceMetric[] { - return this.metrics; - } -} diff --git a/src/approval-model.ts b/src/approval-model.ts deleted file mode 100644 index 0fb9f16e..00000000 --- a/src/approval-model.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Governance & Approvals System — data models - * Approval workflows, policies, change tracking - */ - -export type ChangeType = - | "config_change" - | "secret_access" - | "service_integration" - | "policy_update" - | "member_role_change"; - -export type ApprovalStatus = "pending" | "approved" | "rejected" | "expired"; -export type ApprovalDecision = "approve" | "reject"; - -export interface ChangeRequest { - id: string; - team_id: string; - type: ChangeType; - requester_id: string; - requester_email: string; - resource_type: string; - resource_id: string; - resource_name: string; - description: string; - proposed_changes: Record; - status: "pending" | "approved" | "rejected" | "executed" | "rolled_back"; - policy_id?: string; - required_approvals: number; - collected_approvals: number; - created_at: string; - expires_at: string; - executed_at?: string; - auto_execute?: boolean; // Execute if all approvals collected -} - -export interface ApprovalPolicy { - id: string; - team_id: string; - resource_type: string; - change_types: ChangeType[]; - required_approvers: number; - allowed_approver_roles: string[]; // ["admin", "owner"] - auto_approve_for_roles?: string[]; // Auto-approve for owner changes - timeout_hours: number; // Approval request expires in N hours - notification_channels: string[]; // ["email", "slack"] - created_at: string; - updated_at: string; -} - -export interface Approval { - id: string; - request_id: string; - team_id: string; - approver_id: string; - approver_email: string; - decision: ApprovalDecision; - status: ApprovalStatus; - comment?: string; - approved_at?: string; - created_at: string; -} - -export interface GovernanceLog { - id: string; - team_id: string; - event_type: - | "change_requested" - | "approval_requested" - | "approval_given" - | "change_executed" - | "change_rejected" - | "policy_violated" - | "policy_created"; - actor_id: string; - actor_email: string; - resource_type: string; - resource_id: string; - details: Record; - timestamp: string; -} - -/** - * Policy evaluation result - */ -export interface PolicyEvaluation { - requiresApproval: boolean; - policy?: ApprovalPolicy; - requiredApprovals: number; - reason: string; -} - -/** - * Approval statistics for dashboard - */ -export interface ApprovalMetrics { - total_pending: number; - total_approved: number; - total_rejected: number; - avg_approval_time_hours: number; - approval_rate_percent: number; -} diff --git a/src/approval-service.test.ts b/src/approval-service.test.ts deleted file mode 100644 index 6e748dd2..00000000 --- a/src/approval-service.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { - createApprovalPolicy, - requestChangeApproval, - respondToApprovalRequest, - getApprovalMetrics, - getGovernanceLogs, -} from "./approval-service.js"; - -describe("approval-service", () => { - const teamId = "team-test-123"; - const ownerId = "owner-456"; - const adminId = "admin-789"; - - describe("createApprovalPolicy", () => { - it("creates approval policy", () => { - const { policy, error } = createApprovalPolicy( - teamId, - "config_change", - 2, - ["owner", "admin"], - ); - - assert.ok(!error); - assert.ok(policy.id); - assert.equal(policy.required_approvers, 2); - assert.deepEqual(policy.allowed_approver_roles, ["owner", "admin"]); - }); - - it("rejects invalid approver count", () => { - const { error } = createApprovalPolicy(teamId, "secret_access", 0); - - assert.ok(error); - assert.equal(error, "At least 1 approver required"); - }); - }); - - describe("requestChangeApproval", () => { - it("creates change request requiring approval", () => { - const { request, error } = requestChangeApproval( - teamId, - "config_change", - ownerId, - "owner@kit.local", - "database", - "db-123", - "PostgreSQL DB", - "Upgrade version", - { version: "15.0" }, - ); - - assert.ok(!error); - assert.ok(request.id); - assert.equal(request.status, "pending"); - assert.ok(request.required_approvals >= 1); - }); - }); - - describe("respondToApprovalRequest", () => { - it("approves change request", () => { - const { request } = requestChangeApproval( - teamId, - "config_change", - ownerId, - "owner@kit.local", - "service", - "svc-123", - "Stripe", - "Add integration", - { service: "stripe" }, - ); - - const { approval, error } = respondToApprovalRequest( - request.id, - adminId, - "admin@kit.local", - "approve", - "Looks good", - ); - - assert.ok(!error); - assert.ok(approval.id); - assert.equal(approval.decision, "approve"); - assert.equal(approval.comment, "Looks good"); - }); - - it("rejects change request", () => { - const { request } = requestChangeApproval( - teamId, - "secret_access", - ownerId, - "owner@kit.local", - "secret", - "secret-123", - "API_KEY", - "Access production secret", - {}, - ); - - const { approval, error } = respondToApprovalRequest( - request.id, - adminId, - "admin@kit.local", - "reject", - "Not authorized for prod access", - ); - - assert.ok(!error); - assert.equal(approval.decision, "reject"); - assert.equal(approval.status, "rejected"); - }); - - it("returns error for missing request", () => { - const { error } = respondToApprovalRequest( - "nonexistent-123", - adminId, - "admin@kit.local", - "approve", - ); - - assert.ok(error); - assert.equal(error, "Change request not found"); - }); - }); - - describe("getApprovalMetrics", () => { - it("calculates approval metrics", () => { - const metricsTeamId = "team-metrics-456"; - - // Create and approve a change - const { request } = requestChangeApproval( - metricsTeamId, - "config_change", - ownerId, - "owner@kit.local", - "tool", - "tool-123", - "Node", - "Update to v22", - { version: "22.0.0" }, - ); - - respondToApprovalRequest( - request.id, - adminId, - "admin@kit.local", - "approve", - ); - - const metrics = getApprovalMetrics(metricsTeamId); - - assert.equal(metrics.total_approved, 1); - assert.ok(metrics.approval_rate_percent >= 0); - }); - }); - - describe("getGovernanceLogs", () => { - it("returns governance events", () => { - requestChangeApproval( - teamId, - "service_integration", - ownerId, - "owner@kit.local", - "service", - "github-123", - "GitHub", - "Add org integration", - { organization: "kit-org" }, - ); - - const { logs, total } = getGovernanceLogs(teamId); - - // Position-independent: the governance log is a process-global singleton shared - // across concurrently-run test files, so assert the event exists rather than [0]. - assert.ok(total >= 1); - assert.ok(logs.some((l) => l.event_type === "change_requested")); - }); - }); -}); diff --git a/src/approval-service.ts b/src/approval-service.ts deleted file mode 100644 index 4c58a478..00000000 --- a/src/approval-service.ts +++ /dev/null @@ -1,331 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - ChangeRequest, - ApprovalPolicy, - Approval, - GovernanceLog, - ChangeType, - ApprovalDecision, - PolicyEvaluation, - ApprovalMetrics, -} from "./approval-model.js"; - -/** - * In-memory storage (production would use database) - */ -const changeRequests = new Map(); -const approvalPolicies = new Map(); -const approvals = new Map(); -const governanceLogs: GovernanceLog[] = []; - -/** - * Default policies per resource type - */ -const DEFAULT_POLICIES: Record> = { - config_change: { - required_approvers: 1, - allowed_approver_roles: ["owner", "admin"], - timeout_hours: 24, - }, - secret_access: { - required_approvers: 2, - allowed_approver_roles: ["owner"], - timeout_hours: 1, - }, - service_integration: { - required_approvers: 1, - allowed_approver_roles: ["owner", "admin"], - timeout_hours: 24, - }, -}; - -/** - * Create approval policy - */ -export function createApprovalPolicy( - team_id: string, - resource_type: string, - required_approvers: number, - allowed_roles: string[] = ["owner", "admin"], -): { policy: ApprovalPolicy; error?: string } { - if (required_approvers < 1) { - return { policy: {} as ApprovalPolicy, error: "At least 1 approver required" }; - } - - const policy: ApprovalPolicy = { - id: `policy_${randomUUID()}`, - team_id, - resource_type, - change_types: ["config_change", "secret_access", "service_integration"], - required_approvers, - allowed_approver_roles: allowed_roles, - timeout_hours: 24, - notification_channels: ["email"], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - approvalPolicies.set(policy.id, policy); - logGovernance(team_id, "system", "policy_created", resource_type, policy.id, { - required_approvers, - allowed_roles, - }); - - return { policy }; -} - -/** - * Request change approval - */ -export function requestChangeApproval( - team_id: string, - change_type: ChangeType, - requester_id: string, - requester_email: string, - resource_type: string, - resource_id: string, - resource_name: string, - description: string, - proposed_changes: Record, -): { request: ChangeRequest; error?: string } { - // Evaluate policy - const evaluation = evaluatePolicy(team_id, change_type, resource_type); - - const timeoutHours = evaluation.policy?.timeout_hours ?? 24; - - const changeRequest: ChangeRequest = { - id: `change_${randomUUID()}`, - team_id, - type: change_type, - requester_id, - requester_email, - resource_type, - resource_id, - resource_name, - description, - proposed_changes, - status: evaluation.requiresApproval ? "pending" : "approved", - policy_id: evaluation.policy?.id, - required_approvals: evaluation.requiredApprovals, - collected_approvals: 0, - created_at: new Date().toISOString(), - expires_at: new Date(Date.now() + timeoutHours * 60 * 60 * 1000).toISOString(), - auto_execute: true, - }; - - changeRequests.set(changeRequest.id, changeRequest); - logGovernance( - team_id, - requester_id, - "change_requested", - resource_type, - resource_id, - { - change_type, - requires_approval: evaluation.requiresApproval, - required_approvals: evaluation.requiredApprovals, - }, - ); - - return { request: changeRequest }; -} - -/** - * Approve or reject change - */ -export function respondToApprovalRequest( - request_id: string, - approver_id: string, - approver_email: string, - decision: ApprovalDecision, - comment?: string, -): { approval: Approval; error?: string } { - const request = changeRequests.get(request_id); - if (!request) { - return { approval: {} as Approval, error: "Change request not found" }; - } - - // Check expiry - if (new Date(request.expires_at) < new Date()) { - return { approval: {} as Approval, error: "Approval request expired" }; - } - - // Check if already approved/rejected - if (request.status !== "pending") { - return { approval: {} as Approval, error: "Request already processed" }; - } - - const approval: Approval = { - id: `approval_${randomUUID()}`, - request_id, - team_id: request.team_id, - approver_id, - approver_email, - decision, - status: decision === "approve" ? "approved" : "rejected", - comment, - approved_at: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - approvals.set(approval.id, approval); - - // Update request status - if (decision === "approve") { - request.collected_approvals += 1; - - if (request.collected_approvals >= request.required_approvals) { - request.status = "approved"; - logGovernance(request.team_id, approver_id, "change_executed", request.resource_type, request.resource_id, { - change_id: request.id, - total_approvals: request.collected_approvals, - }); - } - } else { - request.status = "rejected"; - logGovernance(request.team_id, approver_id, "change_rejected", request.resource_type, request.resource_id, { - change_id: request.id, - reason: comment, - }); - } - - logGovernance(request.team_id, approver_id, "approval_given", request.resource_type, request.resource_id, { - change_id: request.id, - decision, - comment, - }); - - return { approval }; -} - -/** - * Evaluate if change requires approval based on policy - */ -function evaluatePolicy( - team_id: string, - change_type: ChangeType, - resource_type: string, -): PolicyEvaluation { - // Check for existing custom policy - const customPolicy = Array.from(approvalPolicies.values()).find( - (p) => p.team_id === team_id && p.resource_type === resource_type, - ); - - if (customPolicy) { - return { - requiresApproval: true, - policy: customPolicy, - requiredApprovals: customPolicy.required_approvers, - reason: `Requires ${customPolicy.required_approvers} approvals per team policy`, - }; - } - - // Check default policy based on change_type - const defaultPolicy = DEFAULT_POLICIES[change_type]; - if (defaultPolicy) { - return { - requiresApproval: true, - requiredApprovals: defaultPolicy.required_approvers || 1, - reason: `Requires ${defaultPolicy.required_approvers || 1} approvals per default policy`, - }; - } - - return { - requiresApproval: false, - requiredApprovals: 0, - reason: "No approval policy configured", - }; -} - -/** - * Get pending approvals for user - */ -export function getPendingApprovalsForUser( - user_id: string, -): { requests: ChangeRequest[] } { - const userApprovals = Array.from(approvals.values()).filter( - (a) => a.approver_id === user_id && a.status === "approved", - ); - - const requestIds = new Set(userApprovals.map((a) => a.request_id)); - const pending = Array.from(changeRequests.values()).filter( - (r) => r.status === "pending" && !requestIds.has(r.id), - ); - - return { requests: pending }; -} - -/** - * Get approval metrics - */ -export function getApprovalMetrics(team_id: string): ApprovalMetrics { - const teamRequests = Array.from(changeRequests.values()).filter((r) => r.team_id === team_id); - - const approved = teamRequests.filter((r) => r.status === "approved"); - const rejected = teamRequests.filter((r) => r.status === "rejected"); - const pending = teamRequests.filter((r) => r.status === "pending"); - - let avgApprovalTime = 0; - if (approved.length > 0) { - const totalTime = approved.reduce((sum, r) => { - const created = new Date(r.created_at).getTime(); - const executed = new Date(r.executed_at || r.created_at).getTime(); - return sum + (executed - created); - }, 0); - avgApprovalTime = totalTime / approved.length / (60 * 60 * 1000); // Convert to hours - } - - const approvalRate = - approved.length + rejected.length > 0 - ? (approved.length / (approved.length + rejected.length)) * 100 - : 0; - - return { - total_pending: pending.length, - total_approved: approved.length, - total_rejected: rejected.length, - avg_approval_time_hours: Math.round(avgApprovalTime * 10) / 10, - approval_rate_percent: Math.round(approvalRate), - }; -} - -/** - * Log governance event - */ -function logGovernance( - team_id: string, - actor_id: string, - event_type: string, - resource_type: string, - resource_id: string, - details: Record, -): void { - const log: GovernanceLog = { - id: `log_${randomUUID()}`, - team_id, - event_type: event_type as any, - actor_id, - actor_email: `user_${actor_id}@kit.local`, - resource_type, - resource_id, - details, - timestamp: new Date().toISOString(), - }; - - governanceLogs.push(log); -} - -/** - * Get governance logs - */ -export function getGovernanceLogs( - team_id: string, - limit = 100, -): { logs: GovernanceLog[]; total: number } { - const filtered = governanceLogs - .filter((log) => log.team_id === team_id) - .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()) - .slice(0, limit); - - return { logs: filtered, total: governanceLogs.filter((l) => l.team_id === team_id).length }; -} diff --git a/src/audit-logging-model.ts b/src/audit-logging-model.ts deleted file mode 100644 index 3aea6c8e..00000000 --- a/src/audit-logging-model.ts +++ /dev/null @@ -1,191 +0,0 @@ -/** - * Audit Logging & Compliance — data models - * Comprehensive audit trail, activity tracking, change history, compliance reporting - */ - -export type AuditAction = - | "create" - | "read" - | "update" - | "delete" - | "execute" - | "approve" - | "reject" - | "export" - | "import" - | "login" - | "logout"; - -export type AuditResource = - | "team" - | "member" - | "role" - | "permission" - | "plugin" - | "workflow" - | "integration" - | "settings" - | "api_key" - | "session"; - -export type ComplianceStandard = "SOC2" | "GDPR" | "HIPAA" | "ISO27001" | "PCI-DSS"; -export type AuditSeverity = "low" | "medium" | "high" | "critical"; - -export interface AuditEntry { - id: string; - action: AuditAction; - resource: AuditResource; - resource_id: string; - actor_id: string; - actor_name: string; - actor_ip?: string; - team_id?: string; - status: "success" | "failure"; - status_code?: number; - changes?: { - field: string; - old_value: unknown; - new_value: unknown; - }[]; - details: Record; - severity: AuditSeverity; - timestamp: string; - created_at: string; -} - -export interface UserActivity { - id: string; - user_id: string; - user_name: string; - team_id?: string; - action_count: number; - last_action_at: string; - first_action_at: string; - login_count: number; - last_login_at?: string; - unique_resources_accessed: number; - is_active: boolean; - created_at: string; - updated_at: string; -} - -export interface ChangeHistory { - id: string; - resource_id: string; - resource_type: AuditResource; - team_id?: string; - change_type: "created" | "updated" | "deleted"; - previous_state?: Record; - current_state: Record; - changed_by: string; - changed_by_name: string; - reason?: string; - timestamp: string; - created_at: string; -} - -export interface ComplianceReport { - id: string; - standard: ComplianceStandard; - period_start: string; - period_end: string; - team_id?: string; - total_audit_entries: number; - security_events: number; - failed_operations: number; - data_access_events: number; - deletion_events: number; - role_changes: number; - permission_changes: number; - compliance_score: number; // 0-100 - issues: ComplianceIssue[]; - generated_at: string; - generated_by: string; - created_at: string; -} - -export interface ComplianceIssue { - id: string; - severity: AuditSeverity; - type: string; // "unauthorized_access", "data_deletion", "role_elevation", etc. - description: string; - resource_id?: string; - resource_type?: AuditResource; - actor_id?: string; - timestamp: string; - remediation?: string; -} - -export interface AuditLog { - id: string; - team_id?: string; - action: AuditAction; - resource: AuditResource; - resource_id: string; - actor_id: string; - actor_name: string; - status: "success" | "failure"; - severity: AuditSeverity; - details: Record; - timestamp: string; - created_at: string; -} - -export interface AuditQuery { - team_id?: string; - actor_id?: string; - resource?: AuditResource; - action?: AuditAction; - status?: "success" | "failure"; - severity?: AuditSeverity; - start_date?: string; - end_date?: string; - limit?: number; - offset?: number; -} - -export interface AuditMetrics { - total_entries: number; - entries_last_24h: number; - entries_last_7d: number; - entries_last_30d: number; - unique_users: number; - unique_resources: number; - failed_operations_count: number; - critical_events_count: number; - average_actions_per_user: number; - most_common_action: string; - most_accessed_resource: string; -} - -export interface DataExportRequest { - id: string; - user_id: string; - team_id?: string; - export_type: "full" | "filtered"; - data_types: AuditResource[]; - start_date?: string; - end_date?: string; - format: "json" | "csv" | "parquet"; - status: "pending" | "processing" | "completed" | "failed"; - download_url?: string; - expires_at?: string; - requested_at: string; - completed_at?: string; - created_at: string; -} - -export interface SessionAudit { - id: string; - user_id: string; - session_id: string; - ip_address: string; - user_agent: string; - login_time: string; - logout_time?: string; - duration_minutes?: number; - actions_count: number; - last_activity_at: string; - is_active: boolean; - created_at: string; -} diff --git a/src/audit-logging-service.test.ts b/src/audit-logging-service.test.ts deleted file mode 100644 index b7361b4f..00000000 --- a/src/audit-logging-service.test.ts +++ /dev/null @@ -1,686 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import * as AuditLogging from "./audit-logging-service.js"; - -describe("audit-logging-service", () => { - describe("recordAuditEntry", () => { - it("records audit entry with success status", () => { - const { entry, error } = AuditLogging.recordAuditEntry( - "create", - "team", - "team-123", - "user-456", - "John Doe", - "success", - { team_name: "Dev Team" }, - "low", - ); - - assert.ok(!error); - assert.ok(entry.id); - assert.equal(entry.action, "create"); - assert.equal(entry.resource, "team"); - assert.equal(entry.status, "success"); - }); - - it("records audit entry with failure status", () => { - const { entry } = AuditLogging.recordAuditEntry( - "update", - "permission", - "perm-789", - "user-789", - "Admin User", - "failure", - { reason: "Unauthorized" }, - "high", - ); - - assert.equal(entry.status, "failure"); - assert.equal(entry.severity, "high"); - }); - - it("includes optional fields when provided", () => { - const { entry } = AuditLogging.recordAuditEntry( - "delete", - "member", - "member-123", - "user-admin", - "Admin", - "success", - {}, - "critical", - "team-456", - "192.168.1.1", - ); - - assert.equal(entry.team_id, "team-456"); - assert.equal(entry.actor_ip, "192.168.1.1"); - }); - }); - - describe("recordChangeHistory", () => { - it("records change history", () => { - const previousState = { name: "Old Name", status: "active" }; - const currentState = { name: "New Name", status: "active" }; - - const { history } = AuditLogging.recordChangeHistory( - "team-123", - "team", - "updated", - currentState, - "user-admin", - "Admin User", - previousState, - "Renamed for clarity", - ); - - assert.ok(history.id); - assert.equal(history.resource_id, "team-123"); - assert.equal(history.change_type, "updated"); - assert.equal(history.reason, "Renamed for clarity"); - assert.deepEqual(history.previous_state, previousState); - assert.deepEqual(history.current_state, currentState); - }); - - it("records deletion with current state", () => { - const state = { id: "member-789", user_id: "user-x", role: "guest" }; - - const { history } = AuditLogging.recordChangeHistory( - "member-789", - "member", - "deleted", - state, - "user-admin", - "Admin", - ); - - assert.equal(history.change_type, "deleted"); - assert.deepEqual(history.current_state, state); - }); - }); - - describe("queryAuditEntries", () => { - it("queries all audit entries", () => { - AuditLogging.recordAuditEntry( - "create", - "team", - "q-team-1", - "q-user-1", - "User 1", - ); - AuditLogging.recordAuditEntry( - "read", - "member", - "q-member-1", - "q-user-2", - "User 2", - ); - - const { entries, total } = AuditLogging.queryAuditEntries({}); - - assert.ok(entries.length >= 2); - assert.ok(total >= 2); - }); - - it("filters by action", () => { - AuditLogging.recordAuditEntry( - "create", - "team", - "q-team-2", - "q-user-3", - "User 3", - ); - AuditLogging.recordAuditEntry( - "delete", - "team", - "q-team-3", - "q-user-4", - "User 4", - ); - - const { entries } = AuditLogging.queryAuditEntries({ action: "create" }); - - assert.ok(entries.every((e) => e.action === "create")); - }); - - it("filters by resource", () => { - AuditLogging.recordAuditEntry( - "read", - "plugin", - "q-plugin-1", - "q-user-5", - "User 5", - ); - AuditLogging.recordAuditEntry( - "update", - "workflow", - "q-workflow-1", - "q-user-6", - "User 6", - ); - - const { entries } = AuditLogging.queryAuditEntries({ resource: "plugin" }); - - assert.ok(entries.every((e) => e.resource === "plugin")); - }); - - it("filters by status", () => { - AuditLogging.recordAuditEntry( - "execute", - "workflow", - "q-workflow-2", - "q-user-7", - "User 7", - "success", - ); - AuditLogging.recordAuditEntry( - "execute", - "workflow", - "q-workflow-3", - "q-user-8", - "User 8", - "failure", - ); - - const { entries } = AuditLogging.queryAuditEntries({ status: "failure" }); - - assert.ok(entries.every((e) => e.status === "failure")); - }); - - it("filters by actor", () => { - AuditLogging.recordAuditEntry( - "create", - "role", - "q-role-1", - "specific-user", - "Specific User", - ); - - const { entries } = AuditLogging.queryAuditEntries({ actor_id: "specific-user" }); - - assert.ok(entries.every((e) => e.actor_id === "specific-user")); - }); - - it("respects pagination", () => { - const { entries: page1 } = AuditLogging.queryAuditEntries({ limit: 5, offset: 0 }); - const { entries: page2 } = AuditLogging.queryAuditEntries({ limit: 5, offset: 5 }); - - assert.ok(page1.length > 0); - if (page2.length > 0) { - assert.notEqual(page1[0]?.id, page2[0]?.id); - } - }); - }); - - describe("getUserActivity", () => { - it("gets user activity after recording entries", () => { - const userId = "activity-user"; - AuditLogging.recordAuditEntry( - "create", - "team", - "a-team-1", - userId, - "Activity User", - ); - AuditLogging.recordAuditEntry( - "update", - "member", - "a-member-1", - userId, - "Activity User", - ); - - const { activity, error } = AuditLogging.getUserActivity(userId); - - assert.ok(!error); - assert.ok(activity); - assert.equal(activity?.action_count, 2); - assert.equal(activity?.user_id, userId); - }); - - it("returns error for nonexistent user", () => { - const { activity, error } = AuditLogging.getUserActivity("nonexistent"); - - assert.ok(error); - assert.ok(!activity); - }); - }); - - describe("listUserActivities", () => { - it("lists all user activities", () => { - AuditLogging.recordAuditEntry( - "read", - "plugin", - "l-plugin-1", - "user-list-1", - "User 1", - ); - AuditLogging.recordAuditEntry( - "read", - "plugin", - "l-plugin-2", - "user-list-2", - "User 2", - ); - - const { activities, total } = AuditLogging.listUserActivities(); - - assert.ok(activities.length >= 2); - assert.ok(total >= 2); - }); - - it("filters by team", () => { - AuditLogging.recordAuditEntry( - "read", - "plugin", - "l-plugin-3", - "user-team-1", - "User", - "success", - {}, - "low", - "team-a", - ); - - const { activities } = AuditLogging.listUserActivities("team-a"); - - assert.ok(activities.length > 0); - }); - }); - - describe("getChangeHistory", () => { - it("gets change history for resource", () => { - const resourceId = "res-123"; - AuditLogging.recordChangeHistory( - resourceId, - "team", - "created", - { name: "New Team" }, - "user-1", - "User One", - ); - AuditLogging.recordChangeHistory( - resourceId, - "team", - "updated", - { name: "Updated Team" }, - "user-2", - "User Two", - { name: "New Team" }, - ); - - const { history, total } = AuditLogging.getChangeHistory(resourceId); - - assert.equal(total, 2); - assert.equal(history.length, 2); - assert.ok(history.every((h) => h.resource_id === resourceId)); - }); - - it("respects pagination", () => { - const resourceId = "res-456"; - for (let i = 0; i < 3; i++) { - AuditLogging.recordChangeHistory( - resourceId, - "member", - "updated", - { role: `role-${i}` }, - `user-${i}`, - `User ${i}`, - ); - } - - const { history: page1 } = AuditLogging.getChangeHistory(resourceId, 2, 0); - const { history: page2 } = AuditLogging.getChangeHistory(resourceId, 2, 2); - - assert.equal(page1.length, 2); - assert.ok(page2.length > 0); - }); - }); - - describe("generateComplianceReport", () => { - it("generates compliance report", () => { - const start = new Date(); - start.setDate(start.getDate() - 1); - - AuditLogging.recordAuditEntry( - "create", - "team", - "c-team-1", - "admin", - "Admin", - "success", - ); - AuditLogging.recordAuditEntry( - "delete", - "member", - "c-member-1", - "admin", - "Admin", - "success", - ); - - // Capture `end` AFTER recording so the report window includes the entries. - // Capturing before record races on fast CI machines (entries land 1ms past end). - const end = new Date(Date.now() + 1000); - const { report } = AuditLogging.generateComplianceReport( - "SOC2", - start.toISOString(), - end.toISOString(), - "auditor", - ); - - assert.ok(report.id); - assert.equal(report.standard, "SOC2"); - assert.ok(report.total_audit_entries >= 2); - assert.ok(report.deletion_events >= 1); - assert.ok(report.compliance_score >= 0 && report.compliance_score <= 100); - }); - - it("filters by team in report", () => { - const start = new Date(); - start.setDate(start.getDate() - 1); - - AuditLogging.recordAuditEntry( - "create", - "workflow", - "c-wf-1", - "user-c", - "User C", - "success", - {}, - "low", - "team-compliance", - ); - - const end = new Date(Date.now() + 1000); - const { report } = AuditLogging.generateComplianceReport( - "GDPR", - start.toISOString(), - end.toISOString(), - "auditor", - "team-compliance", - ); - - assert.equal(report.team_id, "team-compliance"); - assert.ok(report.total_audit_entries >= 1); - }); - - it("includes critical events as issues", () => { - const start = new Date(); - start.setDate(start.getDate() - 1); - - AuditLogging.recordAuditEntry( - "delete", - "team", - "c-team-2", - "admin", - "Admin", - "success", - {}, - "critical", - ); - - const end = new Date(Date.now() + 1000); - const { report } = AuditLogging.generateComplianceReport( - "ISO27001", - start.toISOString(), - end.toISOString(), - "auditor", - ); - - assert.ok(report.issues.length > 0); - assert.ok(report.issues.some((i) => i.severity === "critical")); - }); - }); - - describe("listComplianceReports", () => { - it("lists compliance reports", () => { - const start = new Date(); - start.setDate(start.getDate() - 7); - const end = new Date(); - - AuditLogging.generateComplianceReport( - "SOC2", - start.toISOString(), - end.toISOString(), - "auditor", - ); - - const { reports, total } = AuditLogging.listComplianceReports(); - - assert.ok(reports.length >= 1); - assert.ok(total >= 1); - }); - }); - - describe("requestDataExport", () => { - it("creates data export request", () => { - const { request } = AuditLogging.requestDataExport( - "user-export", - "json", - ["team", "member"], - ); - - assert.ok(request.id); - assert.equal(request.user_id, "user-export"); - assert.equal(request.format, "json"); - assert.equal(request.status, "pending"); - }); - - it("handles csv export", () => { - const { request } = AuditLogging.requestDataExport( - "user-csv", - "csv", - ["plugin", "workflow"], - ); - - assert.equal(request.format, "csv"); - assert.equal(request.data_types.length, 2); - }); - - it("includes date range", () => { - const start = new Date(); - start.setDate(start.getDate() - 30); - - const { request } = AuditLogging.requestDataExport( - "user-range", - "json", - ["member"], - undefined, - start.toISOString(), - new Date().toISOString(), - ); - - assert.ok(request.start_date); - assert.ok(request.end_date); - }); - }); - - describe("getDataExportStatus", () => { - it("gets export status", (t, done) => { - const { request: initial } = AuditLogging.requestDataExport( - "user-status", - "json", - ["team"], - ); - - // Check immediately (should be pending) - const { request: check1 } = AuditLogging.getDataExportStatus(initial.id); - assert.equal(check1?.status, "pending"); - - // Wait for simulated processing - setTimeout(() => { - const { request: check2 } = AuditLogging.getDataExportStatus(initial.id); - assert.equal(check2?.status, "completed"); - assert.ok(check2?.download_url); - assert.ok(check2?.expires_at); - done(); - }, 1500); - }); - }); - - describe("recordSessionAudit", () => { - it("records session audit", () => { - const { session } = AuditLogging.recordSessionAudit( - "session-user", - "session-abc123", - "10.0.0.1", - "Mozilla/5.0", - ); - - assert.ok(session.id); - assert.equal(session.user_id, "session-user"); - assert.equal(session.ip_address, "10.0.0.1"); - assert.equal(session.is_active, true); - }); - }); - - describe("endSessionAudit", () => { - it("ends session audit", () => { - const { session } = AuditLogging.recordSessionAudit( - "session-user-2", - "session-xyz789", - "10.0.0.2", - "Chrome/120.0", - ); - - const { success } = AuditLogging.endSessionAudit(session.session_id); - - assert.equal(success, true); - }); - - it("returns error for nonexistent session", () => { - const { success, error } = AuditLogging.endSessionAudit("nonexistent-session"); - - assert.equal(success, false); - assert.ok(error); - }); - }); - - describe("getAuditMetrics", () => { - it("returns audit metrics", () => { - AuditLogging.recordAuditEntry( - "create", - "team", - "m-team-1", - "metrics-user-1", - "User 1", - ); - AuditLogging.recordAuditEntry( - "update", - "team", - "m-team-1", - "metrics-user-2", - "User 2", - ); - AuditLogging.recordAuditEntry( - "delete", - "member", - "m-member-1", - "metrics-user-1", - "User 1", - "failure", - ); - - const metrics = AuditLogging.getAuditMetrics(); - - assert.ok(metrics.total_entries >= 3); - assert.ok(metrics.unique_users >= 2); - assert.ok(metrics.failed_operations_count >= 1); - assert.ok(metrics.entries_last_24h >= 3); - assert.ok(metrics.entries_last_7d >= 3); - assert.ok(metrics.entries_last_30d >= 3); - }); - - it("identifies most common action", () => { - for (let i = 0; i < 5; i++) { - AuditLogging.recordAuditEntry( - "read", - "plugin", - `m-plugin-${i}`, - `m-user-${i}`, - `User ${i}`, - ); - } - - const metrics = AuditLogging.getAuditMetrics(); - - assert.ok(metrics.most_common_action); - }); - - it("filters metrics by team", () => { - AuditLogging.recordAuditEntry( - "create", - "team", - "m-team-2", - "team-metrics", - "Team User", - "success", - {}, - "low", - "special-team", - ); - - const metrics = AuditLogging.getAuditMetrics("special-team"); - - assert.ok(metrics.total_entries >= 1); - }); - }); - - describe("end-to-end compliance workflow", () => { - it("tracks operations and generates report", () => { - const now = new Date(); - const start = new Date(now.getTime() - 2 * 60 * 60 * 1000); - - // Simulate team operations - AuditLogging.recordAuditEntry( - "create", - "team", - "e2e-team", - "e2e-owner", - "Owner", - "success", - {}, - "low", - "e2e-team", - ); - - AuditLogging.recordChangeHistory( - "e2e-team", - "team", - "created", - { name: "E2E Team", status: "active" }, - "e2e-owner", - "Owner", - ); - - AuditLogging.recordAuditEntry( - "update", - "team", - "e2e-team", - "e2e-admin", - "Admin", - "success", - { change: "name" }, - "medium", - "e2e-team", - ); - - const end = new Date(Date.now() + 1000); - const { report } = AuditLogging.generateComplianceReport( - "HIPAA", - start.toISOString(), - end.toISOString(), - "compliance-officer", - "e2e-team", - ); - - assert.equal(report.team_id, "e2e-team"); - assert.ok(report.total_audit_entries >= 2); - assert.ok(report.compliance_score > 0); - - const metrics = AuditLogging.getAuditMetrics("e2e-team"); - assert.ok(metrics.total_entries >= 2); - }); - }); -}); diff --git a/src/audit-logging-service.ts b/src/audit-logging-service.ts deleted file mode 100644 index 5ad93bba..00000000 --- a/src/audit-logging-service.ts +++ /dev/null @@ -1,513 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - AuditEntry, - UserActivity, - ChangeHistory, - ComplianceReport, - ComplianceIssue, - AuditLog, - AuditQuery, - AuditMetrics, - DataExportRequest, - SessionAudit, - AuditAction, - AuditResource, - AuditSeverity, - ComplianceStandard, -} from "./audit-logging-model.js"; - -const auditEntries = new Map(); -const userActivity = new Map(); -const changeHistory = new Map(); -const complianceReports = new Map(); -const auditLogs = new Map(); -const dataExports = new Map(); -const sessionAudits = new Map(); - -/** - * Record audit entry - */ -export function recordAuditEntry( - action: AuditAction, - resource: AuditResource, - resource_id: string, - actor_id: string, - actor_name: string, - status: "success" | "failure" = "success", - details: Record = {}, - severity: AuditSeverity = "low", - team_id?: string, - actor_ip?: string, -): { entry: AuditEntry; error?: string } { - const entry: AuditEntry = { - id: `audit_${randomUUID()}`, - action, - resource, - resource_id, - actor_id, - actor_name, - actor_ip, - team_id, - status, - details, - severity, - timestamp: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - auditEntries.set(entry.id, entry); - - // Update user activity - updateUserActivity(actor_id, actor_name, team_id); - - // Create audit log entry - const log: AuditLog = { - id: `log_${randomUUID()}`, - team_id, - action, - resource, - resource_id, - actor_id, - actor_name, - status, - severity, - details, - timestamp: entry.timestamp, - created_at: entry.created_at, - }; - - auditLogs.set(log.id, log); - - return { entry }; -} - -/** - * Record change history - */ -export function recordChangeHistory( - resource_id: string, - resource_type: AuditResource, - change_type: "created" | "updated" | "deleted", - current_state: Record, - changed_by: string, - changed_by_name: string, - previous_state?: Record, - reason?: string, - team_id?: string, -): { history: ChangeHistory; error?: string } { - const history: ChangeHistory = { - id: `hist_${randomUUID()}`, - resource_id, - resource_type, - team_id, - change_type, - current_state, - previous_state, - changed_by, - changed_by_name, - reason, - timestamp: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - changeHistory.set(history.id, history); - - return { history }; -} - -/** - * Query audit entries - */ -export function queryAuditEntries( - query: AuditQuery, -): { entries: AuditEntry[]; total: number } { - let results = Array.from(auditEntries.values()); - - if (query.team_id) { - results = results.filter((e) => e.team_id === query.team_id); - } - - if (query.actor_id) { - results = results.filter((e) => e.actor_id === query.actor_id); - } - - if (query.resource) { - results = results.filter((e) => e.resource === query.resource); - } - - if (query.action) { - results = results.filter((e) => e.action === query.action); - } - - if (query.status) { - results = results.filter((e) => e.status === query.status); - } - - if (query.severity) { - results = results.filter((e) => e.severity === query.severity); - } - - if (query.start_date) { - const startDate = new Date(query.start_date); - results = results.filter((e) => new Date(e.timestamp) >= startDate); - } - - if (query.end_date) { - const endDate = new Date(query.end_date); - results = results.filter((e) => new Date(e.timestamp) <= endDate); - } - - // Sort by timestamp descending - results.sort( - (a, b) => - new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(), - ); - - const limit = query.limit || 100; - const offset = query.offset || 0; - const total = results.length; - - return { entries: results.slice(offset, offset + limit), total }; -} - -/** - * Get user activity - */ -export function getUserActivity(user_id: string): { activity: UserActivity | null; error?: string } { - const activity = userActivity.get(user_id); - return { - activity: activity || null, - error: activity ? undefined : "User activity not found", - }; -} - -/** - * List user activities - */ -export function listUserActivities( - team_id?: string, - limit: number = 50, - offset: number = 0, -): { activities: UserActivity[]; total: number } { - let all = Array.from(userActivity.values()); - - if (team_id) { - all = all.filter((a) => a.team_id === team_id); - } - - all.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()); - - const total = all.length; - return { activities: all.slice(offset, offset + limit), total }; -} - -/** - * Get change history for resource - */ -export function getChangeHistory( - resource_id: string, - limit: number = 50, - offset: number = 0, -): { history: ChangeHistory[]; total: number } { - const all = Array.from(changeHistory.values()).filter((h) => h.resource_id === resource_id); - - all.sort( - (a, b) => - new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(), - ); - - const total = all.length; - return { history: all.slice(offset, offset + limit), total }; -} - -/** - * Generate compliance report - */ -export function generateComplianceReport( - standard: ComplianceStandard, - period_start: string, - period_end: string, - generated_by: string, - team_id?: string, -): { report: ComplianceReport; error?: string } { - const startDate = new Date(period_start); - const endDate = new Date(period_end); - - const entries = Array.from(auditEntries.values()).filter((e) => { - const timestamp = new Date(e.timestamp); - const teamMatch = !team_id || e.team_id === team_id; - const dateMatch = timestamp >= startDate && timestamp <= endDate; - return teamMatch && dateMatch; - }); - - const issues: ComplianceIssue[] = []; - - // Identify compliance issues - const failedOps = entries.filter((e) => e.status === "failure"); - failedOps.forEach((e) => { - if (failedOps.length > 10) { - // Threshold for concern - issues.push({ - id: `issue_${randomUUID()}`, - severity: "medium", - type: "high_failure_rate", - description: `High rate of failed operations detected (${failedOps.length} in period)`, - timestamp: new Date().toISOString(), - }); - } - }); - - const criticalEvents = entries.filter((e) => e.severity === "critical"); - if (criticalEvents.length > 0) { - criticalEvents.forEach((e) => { - issues.push({ - id: `issue_${randomUUID()}`, - severity: "critical", - type: "critical_event", - description: `Critical event: ${e.action} on ${e.resource}`, - resource_id: e.resource_id, - resource_type: e.resource, - actor_id: e.actor_id, - timestamp: e.timestamp, - }); - }); - } - - // Calculate compliance score - let score = 100; - score -= failedOps.length * 2; - score -= criticalEvents.length * 10; - score = Math.max(0, Math.min(100, score)); - - const report: ComplianceReport = { - id: `report_${randomUUID()}`, - standard, - period_start, - period_end, - team_id, - total_audit_entries: entries.length, - security_events: entries.filter((e) => e.severity === "critical" || e.severity === "high") - .length, - failed_operations: failedOps.length, - data_access_events: entries.filter( - (e) => - e.action === "read" || - e.action === "export" || - e.action === "import", - ).length, - deletion_events: entries.filter((e) => e.action === "delete").length, - role_changes: entries.filter( - (e) => e.resource === "role" && e.action === "update", - ).length, - permission_changes: entries.filter( - (e) => e.resource === "permission", - ).length, - compliance_score: score, - issues, - generated_at: new Date().toISOString(), - generated_by, - created_at: new Date().toISOString(), - }; - - complianceReports.set(report.id, report); - - return { report }; -} - -/** - * List compliance reports - */ -export function listComplianceReports( - team_id?: string, - limit: number = 50, - offset: number = 0, -): { reports: ComplianceReport[]; total: number } { - let all = Array.from(complianceReports.values()); - - if (team_id) { - all = all.filter((r) => r.team_id === team_id); - } - - all.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); - - const total = all.length; - return { reports: all.slice(offset, offset + limit), total }; -} - -/** - * Request data export for compliance - */ -export function requestDataExport( - user_id: string, - format: "json" | "csv" | "parquet", - data_types: AuditResource[], - team_id?: string, - start_date?: string, - end_date?: string, -): { request: DataExportRequest; error?: string } { - const request: DataExportRequest = { - id: `export_${randomUUID()}`, - user_id, - team_id, - export_type: "filtered", - data_types, - start_date, - end_date, - format, - status: "pending", - requested_at: new Date().toISOString(), - created_at: new Date().toISOString(), - }; - - dataExports.set(request.id, request); - - // Simulate processing (in real system would be async) - setTimeout(() => { - const exp = dataExports.get(request.id); - if (exp) { - exp.status = "completed"; - exp.download_url = `https://api.example.com/exports/${request.id}`; - const expiresAt = new Date(); - expiresAt.setDate(expiresAt.getDate() + 7); - exp.expires_at = expiresAt.toISOString(); - exp.completed_at = new Date().toISOString(); - } - }, 1000); - - return { request }; -} - -/** - * Get data export status - */ -export function getDataExportStatus(export_id: string): { request: DataExportRequest | null; error?: string } { - const request = dataExports.get(export_id); - return { - request: request || null, - error: request ? undefined : "Export request not found", - }; -} - -/** - * Record session audit - */ -export function recordSessionAudit( - user_id: string, - session_id: string, - ip_address: string, - user_agent: string, -): { session: SessionAudit; error?: string } { - const session: SessionAudit = { - id: `session_${randomUUID()}`, - user_id, - session_id, - ip_address, - user_agent, - login_time: new Date().toISOString(), - actions_count: 0, - last_activity_at: new Date().toISOString(), - is_active: true, - created_at: new Date().toISOString(), - }; - - sessionAudits.set(session.id, session); - - return { session }; -} - -/** - * End session audit - */ -export function endSessionAudit(session_id: string): { success: boolean; error?: string } { - const session = Array.from(sessionAudits.values()).find((s) => s.session_id === session_id); - if (!session) { - return { success: false, error: "Session not found" }; - } - - session.is_active = false; - session.logout_time = new Date().toISOString(); - session.duration_minutes = Math.round( - (new Date(session.logout_time).getTime() - new Date(session.login_time).getTime()) / - 60000, - ); - - return { success: true }; -} - -/** - * Get audit metrics - */ -export function getAuditMetrics(team_id?: string): AuditMetrics { - const now = new Date(); - const last24h = new Date(now.getTime() - 24 * 60 * 60 * 1000); - const last7d = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); - const last30d = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000); - - let entries = Array.from(auditEntries.values()); - if (team_id) { - entries = entries.filter((e) => e.team_id === team_id); - } - - const entries24h = entries.filter((e) => new Date(e.timestamp) >= last24h).length; - const entries7d = entries.filter((e) => new Date(e.timestamp) >= last7d).length; - const entries30d = entries.filter((e) => new Date(e.timestamp) >= last30d).length; - - const uniqueUsers = new Set(entries.map((e) => e.actor_id)).size; - const uniqueResources = new Set(entries.map((e) => e.resource_id)).size; - const failedOps = entries.filter((e) => e.status === "failure").length; - const criticalEvents = entries.filter((e) => e.severity === "critical").length; - - const actionCounts: Record = {}; - const resourceCounts: Record = {}; - - entries.forEach((e) => { - actionCounts[e.action] = (actionCounts[e.action] || 0) + 1; - resourceCounts[e.resource] = (resourceCounts[e.resource] || 0) + 1; - }); - - const mostCommonAction = Object.entries(actionCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || "none"; - const mostAccessedResource = Object.entries(resourceCounts).sort((a, b) => b[1] - a[1])[0]?.[0] || "none"; - - return { - total_entries: entries.length, - entries_last_24h: entries24h, - entries_last_7d: entries7d, - entries_last_30d: entries30d, - unique_users: uniqueUsers, - unique_resources: uniqueResources, - failed_operations_count: failedOps, - critical_events_count: criticalEvents, - average_actions_per_user: uniqueUsers > 0 ? Math.round(entries.length / uniqueUsers) : 0, - most_common_action: mostCommonAction, - most_accessed_resource: mostAccessedResource, - }; -} - -/** - * Update user activity (internal) - */ -function updateUserActivity(user_id: string, user_name: string, team_id?: string): void { - const existing = userActivity.get(user_id); - - if (existing) { - existing.action_count += 1; - existing.last_action_at = new Date().toISOString(); - existing.updated_at = new Date().toISOString(); - } else { - const activity: UserActivity = { - id: `activity_${randomUUID()}`, - user_id, - user_name, - team_id, - action_count: 1, - first_action_at: new Date().toISOString(), - last_action_at: new Date().toISOString(), - login_count: 0, - unique_resources_accessed: 1, - is_active: true, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - userActivity.set(user_id, activity); - } -} diff --git a/src/autonomous-setup-model.ts b/src/autonomous-setup-model.ts deleted file mode 100644 index 23524399..00000000 --- a/src/autonomous-setup-model.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Autonomous Project Setup — data models - * Agents initialize projects with minimal guidance via workflow orchestration - */ - -export type SetupPhase = "detection" | "planning" | "initialization" | "verification" | "complete"; -export type ProjectType = "nodejs" | "python" | "go" | "rust" | "java" | "custom"; -export type SetupStatus = "pending" | "in_progress" | "completed" | "failed" | "paused"; -export type DecisionMode = "autonomous" | "guided" | "manual"; - -export interface ProjectDetection { - id: string; - project_path: string; - detected_type: ProjectType; - confidence: number; // 0-100 - detected_tools: string[]; - detected_frameworks: string[]; - detected_services: string[]; - language_primary?: string; - package_manager?: string; - git_initialized: boolean; - detected_at: string; -} - -export interface SetupWorkflow { - id: string; - team_id: string; - project_id: string; - project_path: string; - project_type: ProjectType; - workflow_name: string; - current_phase: SetupPhase; - phases_completed: SetupPhase[]; - decision_mode: DecisionMode; - steps: SetupStep[]; - status: SetupStatus; - initiated_by: string; - initiated_at: string; - estimated_completion?: string; - actual_completion?: string; - created_at: string; - updated_at: string; -} - -export interface SetupStep { - id: string; - workflow_id: string; - step_number: number; - step_name: string; - description: string; - category: "detect" | "install" | "configure" | "initialize" | "test" | "verify"; - status: "pending" | "in_progress" | "completed" | "failed" | "skipped"; - command?: string; - expected_output?: string; - error_message?: string; - executed_at?: string; - duration_ms?: number; - requires_approval: boolean; - approved_by?: string; - approved_at?: string; - rollback_command?: string; - created_at: string; - updated_at: string; -} - -export interface SetupDecision { - id: string; - workflow_id: string; - step_id: string; - team_id: string; - decision_type: "tool_selection" | "configuration" | "service" | "dependency" | "other"; - question: string; - options: string[]; - recommendation?: string; - selected_option?: string; - selected_by?: string; - selected_at?: string; - reasoning?: string; - created_at: string; -} - -export interface SetupPreset { - id: string; - preset_name: string; - project_type: ProjectType; - description?: string; - tools: string[]; - services: string[]; - framework?: string; - database?: string; - auth_method?: string; - hosting?: string; - ci_cd?: string; - monitoring?: string; - created_at: string; - public: boolean; -} - -export interface SetupVerification { - id: string; - workflow_id: string; - team_id: string; - verification_type: "tools" | "services" | "secrets" | "config" | "health"; - status: "passed" | "failed" | "warning"; - checks: { - name: string; - status: "pass" | "fail" | "warn"; - message?: string; - }[]; - verified_at: string; -} - -export interface SetupMetrics { - total_workflows: number; - completed_workflows: number; - failed_workflows: number; - in_progress: number; - average_duration_minutes: number; - success_rate_percent: number; - most_common_project_type: ProjectType; - most_common_preset: string; - autonomous_success_rate: number; - guided_success_rate: number; - manual_success_rate: number; -} diff --git a/src/autonomous-setup-service.test.ts b/src/autonomous-setup-service.test.ts deleted file mode 100644 index 8824d868..00000000 --- a/src/autonomous-setup-service.test.ts +++ /dev/null @@ -1,336 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { - detectProjectStack, - initiateSetupWorkflow, - executeSetupStep, - approveSetupStep, - requestSetupDecision, - recordSetupDecision, - applySetupPreset, - verifySetupCompletion, - getWorkflowStatus, - getSetupMetrics, - listAvailablePresets, -} from "./autonomous-setup-service.js"; - -describe("autonomous-setup-service", () => { - const teamId = "team-setup-123"; - const userId = "user-setup-456"; - const projectPath = "/home/user/my-project"; - - describe("detectProjectStack", () => { - it("detects project stack", () => { - const { detection, error } = detectProjectStack(projectPath); - - assert.ok(!error); - assert.ok(detection.id); - assert.equal(detection.project_path, projectPath); - assert.ok(detection.detected_type); - assert.ok(detection.confidence >= 0 && detection.confidence <= 100); - assert.ok(detection.detected_tools.length > 0); - }); - }); - - describe("initiateSetupWorkflow", () => { - it("initiates setup workflow", () => { - const { workflow, error } = initiateSetupWorkflow( - teamId, - "proj-123", - projectPath, - "nodejs", - "autonomous", - userId, - ); - - assert.ok(!error); - assert.ok(workflow.id); - assert.equal(workflow.team_id, teamId); - assert.equal(workflow.project_type, "nodejs"); - assert.equal(workflow.current_phase, "detection"); - assert.equal(workflow.status, "pending"); - assert.ok(workflow.steps.length > 0); - }); - }); - - describe("executeSetupStep", () => { - it("executes setup step", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-123", - projectPath, - "nodejs", - "autonomous", - userId, - ); - - const detectStep = workflow.steps.find((s) => s.category === "detect")!; - - const { step, error } = executeSetupStep(teamId, workflow.id, detectStep.id); - - assert.ok(!error); - assert.equal(step.status, "completed"); - assert.ok(step.executed_at); - assert.ok(step.duration_ms !== undefined); - }); - - it("fails for step requiring approval", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-456", - projectPath, - "nodejs", - "autonomous", - userId, - ); - - const configStep = workflow.steps.find((s) => s.category === "configure")!; - - const { error } = executeSetupStep(teamId, workflow.id, configStep.id); - - assert.ok(error); - assert.ok(error?.includes("approval")); - }); - - it("fails for nonexistent workflow", () => { - const { error } = executeSetupStep(teamId, "nonexistent-workflow", "step-123"); - - assert.ok(error); - assert.equal(error, "Workflow not found"); - }); - }); - - describe("approveSetupStep", () => { - it("approves setup step", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-789", - projectPath, - "nodejs", - "guided", - userId, - ); - - const configStep = workflow.steps.find((s) => s.category === "configure")!; - - const { step, error } = approveSetupStep(teamId, workflow.id, configStep.id, userId); - - assert.ok(!error); - assert.equal(step.approved_by, userId); - assert.ok(step.approved_at); - }); - - it("fails for nonexistent step", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-111", - projectPath, - "python", - "autonomous", - userId, - ); - - const { error } = approveSetupStep(teamId, workflow.id, "nonexistent-step", userId); - - assert.ok(error); - assert.equal(error, "Step not found"); - }); - }); - - describe("requestSetupDecision", () => { - it("creates setup decision", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-222", - projectPath, - "nodejs", - "guided", - userId, - ); - - const detectStep = workflow.steps[0]; - - const { decision, error } = requestSetupDecision( - teamId, - workflow.id, - detectStep.id, - "tool_selection", - "Which package manager?", - ["npm", "yarn", "pnpm"], - "npm recommended", - ); - - assert.ok(!error); - assert.ok(decision.id); - assert.equal(decision.decision_type, "tool_selection"); - assert.equal(decision.options.length, 3); - }); - }); - - describe("recordSetupDecision", () => { - it("records user decision", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-333", - projectPath, - "nodejs", - "guided", - userId, - ); - - const detectStep = workflow.steps[0]; - - const { decision: created } = requestSetupDecision( - teamId, - workflow.id, - detectStep.id, - "framework", - "Which framework?", - ["next.js", "remix", "nuxt"], - ); - - const { decision, error } = recordSetupDecision( - teamId, - created.id, - "next.js", - userId, - "Best for startup projects", - ); - - assert.ok(!error); - assert.equal(decision.selected_option, "next.js"); - assert.equal(decision.selected_by, userId); - assert.ok(decision.selected_at); - }); - - it("fails for nonexistent decision", () => { - const { error } = recordSetupDecision( - teamId, - "nonexistent-decision", - "option", - userId, - ); - - assert.ok(error); - assert.equal(error, "Decision not found"); - }); - }); - - describe("applySetupPreset", () => { - it("applies preset to workflow", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-444", - projectPath, - "nodejs", - "autonomous", - userId, - ); - - const { workflow: updated, error } = applySetupPreset( - teamId, - workflow.id, - "Next.js + PostgreSQL", - ); - - assert.ok(!error); - assert.ok(updated.steps.some((s) => s.status === "completed")); - }); - - it("fails for nonexistent preset", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-555", - projectPath, - "nodejs", - "autonomous", - userId, - ); - - const { error } = applySetupPreset( - teamId, - workflow.id, - "Nonexistent Preset", - ); - - assert.ok(error); - assert.equal(error, "Preset not found"); - }); - }); - - describe("verifySetupCompletion", () => { - it("verifies setup completion", () => { - const { workflow } = initiateSetupWorkflow( - teamId, - "proj-666", - projectPath, - "nodejs", - "autonomous", - userId, - ); - - const { verification, error } = verifySetupCompletion( - teamId, - workflow.id, - "tools", - ); - - assert.ok(!error); - assert.ok(verification.checks.length > 0); - assert.ok(["passed", "warning", "failed"].includes(verification.status)); - }); - }); - - describe("getWorkflowStatus", () => { - it("returns workflow status", () => { - const { workflow: created } = initiateSetupWorkflow( - teamId, - "proj-777", - projectPath, - "nodejs", - "autonomous", - userId, - ); - - const { workflow, error } = getWorkflowStatus(teamId, created.id); - - assert.ok(!error); - assert.equal(workflow?.id, created.id); - assert.equal(workflow?.status, "pending"); - }); - - it("fails for nonexistent workflow", () => { - const { workflow, error } = getWorkflowStatus(teamId, "nonexistent"); - - assert.ok(error); - assert.equal(error, "Workflow not found"); - assert.ok(!workflow); - }); - }); - - describe("getSetupMetrics", () => { - it("returns setup metrics", () => { - const team2 = "team-metrics-2"; - - initiateSetupWorkflow(team2, "proj-a", projectPath, "nodejs", "autonomous", userId); - initiateSetupWorkflow(team2, "proj-b", projectPath, "python", "guided", userId); - - const metrics = getSetupMetrics(team2); - - assert.equal(metrics.total_workflows, 2); - assert.ok(metrics.success_rate_percent >= 0); - assert.ok(metrics.autonomous_success_rate >= 0); - assert.ok(metrics.guided_success_rate >= 0); - }); - }); - - describe("listAvailablePresets", () => { - it("lists available presets", () => { - const { presets } = listAvailablePresets(); - - assert.ok(presets.length > 0); - assert.ok(presets.some((p) => p.preset_name.includes("Next.js"))); - assert.ok(presets.some((p) => p.preset_name.includes("FastAPI"))); - }); - }); -}); diff --git a/src/autonomous-setup-service.ts b/src/autonomous-setup-service.ts deleted file mode 100644 index fe7a0451..00000000 --- a/src/autonomous-setup-service.ts +++ /dev/null @@ -1,416 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - ProjectDetection, - SetupWorkflow, - SetupStep, - SetupDecision, - SetupPreset, - SetupVerification, - SetupMetrics, - ProjectType, -} from "./autonomous-setup-model.js"; - -const workflows = new Map(); -const detections = new Map(); -const decisions = new Map(); -const verifications = new Map(); - -// Default presets for quick setup -const DEFAULT_PRESETS: SetupPreset[] = [ - { - id: `preset_${randomUUID()}`, - preset_name: "Next.js + PostgreSQL", - project_type: "nodejs", - description: "Full-stack Next.js with PostgreSQL database", - tools: ["node", "npm", "git"], - services: ["postgresql"], - framework: "next.js", - database: "postgresql", - auth_method: "jwt", - hosting: "vercel", - ci_cd: "github-actions", - monitoring: "sentry", - created_at: new Date().toISOString(), - public: true, - }, - { - id: `preset_${randomUUID()}`, - preset_name: "Python FastAPI", - project_type: "python", - description: "Python FastAPI with SQLAlchemy", - tools: ["python", "pip", "git"], - services: ["postgresql"], - framework: "fastapi", - database: "postgresql", - auth_method: "oauth2", - hosting: "heroku", - ci_cd: "github-actions", - monitoring: "sentry", - created_at: new Date().toISOString(), - public: true, - }, -]; - -/** - * Detect project stack - */ -export function detectProjectStack( - project_path: string, -): { detection: ProjectDetection; error?: string } { - const detection: ProjectDetection = { - id: `detect_${randomUUID()}`, - project_path, - detected_type: "nodejs", - confidence: 85, - detected_tools: ["node", "npm", "git"], - detected_frameworks: ["react", "next.js"], - detected_services: ["postgresql"], - language_primary: "typescript", - package_manager: "npm", - git_initialized: true, - detected_at: new Date().toISOString(), - }; - - detections.set(detection.id, detection); - - return { detection }; -} - -/** - * Initiate setup workflow - */ -export function initiateSetupWorkflow( - team_id: string, - project_id: string, - project_path: string, - project_type: ProjectType, - decision_mode: string, - initiated_by: string, -): { workflow: SetupWorkflow; error?: string } { - const workflow: SetupWorkflow = { - id: `workflow_${randomUUID()}`, - team_id, - project_id, - project_path, - project_type, - workflow_name: `Setup: ${project_path.split("/").pop()}`, - current_phase: "detection", - phases_completed: [], - decision_mode: decision_mode as any, - steps: [ - { - id: `step_${randomUUID()}`, - workflow_id: `workflow_${randomUUID()}`, - step_number: 1, - step_name: "Detect Stack", - description: "Analyze project structure and dependencies", - category: "detect", - status: "pending", - requires_approval: false, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - { - id: `step_${randomUUID()}`, - workflow_id: `workflow_${randomUUID()}`, - step_number: 2, - step_name: "Install Tools", - description: "Install required tools and dependencies", - category: "install", - status: "pending", - requires_approval: false, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - { - id: `step_${randomUUID()}`, - workflow_id: `workflow_${randomUUID()}`, - step_number: 3, - step_name: "Configure Project", - description: "Generate configuration files", - category: "configure", - status: "pending", - requires_approval: true, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - { - id: `step_${randomUUID()}`, - workflow_id: `workflow_${randomUUID()}`, - step_number: 4, - step_name: "Initialize Services", - description: "Set up services and external integrations", - category: "initialize", - status: "pending", - requires_approval: true, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - { - id: `step_${randomUUID()}`, - workflow_id: `workflow_${randomUUID()}`, - step_number: 5, - step_name: "Verify Setup", - description: "Verify all components working correctly", - category: "verify", - status: "pending", - requires_approval: false, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - ], - status: "pending", - initiated_by, - initiated_at: new Date().toISOString(), - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - workflows.set(workflow.id, workflow); - - return { workflow }; -} - -/** - * Execute setup step - */ -export function executeSetupStep( - team_id: string, - workflow_id: string, - step_id: string, -): { step: SetupStep; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { step: {} as SetupStep, error: "Workflow not found" }; - } - - const step = workflow.steps.find((s) => s.id === step_id); - if (!step) { - return { step: {} as SetupStep, error: "Step not found" }; - } - - if (step.requires_approval && !step.approved_by) { - return { step: {} as SetupStep, error: "Step requires approval" }; - } - - const startTime = Date.now(); - step.status = "in_progress"; - step.updated_at = new Date().toISOString(); - - // Simulate execution - step.status = "completed"; - step.executed_at = new Date().toISOString(); - step.duration_ms = Date.now() - startTime; - - // Update workflow phase - if (step.category === "detect") { - workflow.current_phase = "planning"; - } else if (step.category === "install") { - workflow.current_phase = "initialization"; - } else if (step.category === "configure") { - workflow.current_phase = "initialization"; - } else if (step.category === "verify") { - workflow.current_phase = "complete"; - workflow.status = "completed"; - workflow.actual_completion = new Date().toISOString(); - } - - workflow.updated_at = new Date().toISOString(); - - return { step }; -} - -/** - * Approve setup step - */ -export function approveSetupStep( - team_id: string, - workflow_id: string, - step_id: string, - approved_by: string, -): { step: SetupStep; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { step: {} as SetupStep, error: "Workflow not found" }; - } - - const step = workflow.steps.find((s) => s.id === step_id); - if (!step) { - return { step: {} as SetupStep, error: "Step not found" }; - } - - step.approved_by = approved_by; - step.approved_at = new Date().toISOString(); - step.updated_at = new Date().toISOString(); - - return { step }; -} - -/** - * Request setup decision - */ -export function requestSetupDecision( - team_id: string, - workflow_id: string, - step_id: string, - decision_type: string, - question: string, - options: string[], - recommendation?: string, -): { decision: SetupDecision; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { decision: {} as SetupDecision, error: "Workflow not found" }; - } - - const decision: SetupDecision = { - id: `decision_${randomUUID()}`, - workflow_id, - step_id, - team_id, - decision_type: decision_type as any, - question, - options, - recommendation, - created_at: new Date().toISOString(), - }; - - decisions.set(decision.id, decision); - - return { decision }; -} - -/** - * Record setup decision - */ -export function recordSetupDecision( - team_id: string, - decision_id: string, - selected_option: string, - selected_by: string, - reasoning?: string, -): { decision: SetupDecision; error?: string } { - const decision = decisions.get(decision_id); - if (!decision || decision.team_id !== team_id) { - return { decision: {} as SetupDecision, error: "Decision not found" }; - } - - decision.selected_option = selected_option; - decision.selected_by = selected_by; - decision.selected_at = new Date().toISOString(); - decision.reasoning = reasoning; - - return { decision }; -} - -/** - * Apply setup preset - */ -export function applySetupPreset( - team_id: string, - workflow_id: string, - preset_name: string, -): { workflow: SetupWorkflow; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { workflow: {} as SetupWorkflow, error: "Workflow not found" }; - } - - const preset = DEFAULT_PRESETS.find((p) => p.preset_name === preset_name); - if (!preset) { - return { workflow: {} as SetupWorkflow, error: "Preset not found" }; - } - - // Apply preset configurations - workflow.steps.forEach((step) => { - if (step.category === "configure") { - step.status = "completed"; - step.executed_at = new Date().toISOString(); - } - }); - - workflow.updated_at = new Date().toISOString(); - - return { workflow }; -} - -/** - * Verify setup completion - */ -export function verifySetupCompletion( - team_id: string, - workflow_id: string, - verification_type: string, -): { verification: SetupVerification; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { verification: {} as SetupVerification, error: "Workflow not found" }; - } - - const checks = [ - { name: "Tools installed", status: "pass" as const, message: "All tools available" }, - { name: "Configuration valid", status: "pass" as const, message: "Config files created" }, - { name: "Services accessible", status: "pass" as const, message: "All services responding" }, - { name: "Dependencies resolved", status: "pass" as const, message: "No conflicts found" }, - ]; - - const verification: SetupVerification = { - id: `verify_${randomUUID()}`, - workflow_id, - team_id, - verification_type: verification_type as any, - status: checks.every((c) => c.status === "pass") ? "passed" : "warning", - checks, - verified_at: new Date().toISOString(), - }; - - verifications.set(verification.id, verification); - - return { verification }; -} - -/** - * Get setup workflow status - */ -export function getWorkflowStatus( - team_id: string, - workflow_id: string, -): { workflow: SetupWorkflow | null; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { workflow: null, error: "Workflow not found" }; - } - - return { workflow }; -} - -/** - * Get setup metrics - */ -export function getSetupMetrics(team_id: string): SetupMetrics { - const teamWorkflows = Array.from(workflows.values()).filter((w) => w.team_id === team_id); - const completed = teamWorkflows.filter((w) => w.status === "completed").length; - const failed = teamWorkflows.filter((w) => w.status === "failed").length; - const inProgress = teamWorkflows.filter((w) => w.status === "in_progress").length; - - return { - total_workflows: teamWorkflows.length, - completed_workflows: completed, - failed_workflows: failed, - in_progress: inProgress, - average_duration_minutes: 15, - success_rate_percent: teamWorkflows.length > 0 ? (completed / teamWorkflows.length) * 100 : 0, - most_common_project_type: "nodejs", - most_common_preset: "Next.js + PostgreSQL", - autonomous_success_rate: 87, - guided_success_rate: 95, - manual_success_rate: 100, - }; -} - -/** - * List available presets - */ -export function listAvailablePresets(): { presets: SetupPreset[] } { - return { presets: DEFAULT_PRESETS }; -} diff --git a/src/cache-manager.test.ts b/src/cache-manager.test.ts deleted file mode 100644 index 2a09100a..00000000 --- a/src/cache-manager.test.ts +++ /dev/null @@ -1,264 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { CacheManager, type CacheConfig } from "./cache-manager.js"; - -describe("CacheManager", () => { - describe("basic operations", () => { - let manager: CacheManager; - - beforeEach(() => { - manager = new CacheManager(); - }); - - it("sets and gets a cache entry", () => { - manager.set("key1", { value: "test" }); - const result = manager.get("key1"); - assert.deepEqual(result, { value: "test" }); - }); - - it("returns null for unknown key", () => { - const result = manager.get("unknown"); - assert.equal(result, null); - }); - - it("checks if key exists", () => { - manager.set("key1", "value1"); - assert(manager.has("key1")); - assert(!manager.has("unknown")); - }); - - it("deletes a cache entry", () => { - manager.set("key1", "value1"); - const deleted = manager.delete("key1"); - assert(deleted); - assert.equal(manager.get("key1"), null); - }); - - it("clears all entries", () => { - manager.set("key1", "value1"); - manager.set("key2", "value2"); - manager.clear(); - assert.equal(manager.get("key1"), null); - assert.equal(manager.get("key2"), null); - }); - - it("tracks hits and misses", () => { - manager.set("key1", "value1"); - manager.get("key1"); - manager.get("unknown"); - assert.equal(manager.getHits(), 1); - assert.equal(manager.getMisses(), 1); - }); - }); - - describe("expiration", () => { - let manager: CacheManager; - - beforeEach(() => { - manager = new CacheManager({ maxSize: 100, defaultTtl: 3600, strategy: "lru" }); - }); - - it("expires entries with TTL", (t, done) => { - const ttl = 1; // 1 second - manager.set("key1", "value1", ttl); - assert(manager.has("key1")); - - setTimeout(() => { - assert(!manager.has("key1")); - done?.(); - }, 1100); - }); - - it("does not expire entries without TTL", () => { - manager.set("key1", "value1"); - assert(manager.has("key1")); - }); - - it("cleans expired entries", (t, done) => { - manager.set("key1", "value1", 1); - manager.set("key2", "value2"); - - setTimeout(() => { - const cleaned = manager.cleanExpired(); - assert(cleaned > 0); - assert(!manager.has("key1")); - assert(manager.has("key2")); - done?.(); - }, 1100); - }); - }); - - describe("invalidation", () => { - let manager: CacheManager; - - beforeEach(() => { - manager = new CacheManager(); - manager.set("user:1:profile", { id: 1 }); - manager.set("user:1:settings", { theme: "dark" }); - manager.set("user:2:profile", { id: 2 }); - manager.set("plugin:stripe", { name: "stripe" }); - }); - - it("invalidates by pattern", () => { - const invalidated = manager.invalidatePattern("user:1:.*"); - assert(invalidated > 0); - assert(!manager.has("user:1:profile")); - assert(!manager.has("user:1:settings")); - assert(manager.has("user:2:profile")); - }); - - it("invalidates by prefix", () => { - const invalidated = manager.invalidatePrefix("user:1:"); - assert.equal(invalidated, 2); - assert(!manager.has("user:1:profile")); - assert(!manager.has("user:1:settings")); - assert(manager.has("user:2:profile")); - }); - }); - - describe("eviction strategies", () => { - it("uses LRU eviction when at capacity", () => { - const manager = new CacheManager({ - maxSize: 3, - defaultTtl: 3600, - strategy: "lru", - }); - - manager.set("key1", "value1"); - manager.set("key2", "value2"); - manager.set("key3", "value3"); - - // Access key1 to increase its hit count - manager.get("key1"); - manager.get("key1"); - - // Add new entry - should evict key2 or key3 (not key1) - manager.set("key4", "value4"); - - // key1 should still be there due to higher hit count - assert(manager.has("key1")); - assert.equal(manager.getCacheMap().size, 3); - }); - - it("uses FIFO eviction when at capacity", () => { - const manager = new CacheManager({ - maxSize: 2, - defaultTtl: 3600, - strategy: "fifo", - }); - - manager.set("key1", "value1"); - manager.set("key2", "value2"); - manager.set("key3", "value3"); // Should evict key1 - - assert(!manager.has("key1")); - assert(manager.has("key2")); - assert(manager.has("key3")); - }); - - it("tracks evictions", () => { - const manager = new CacheManager({ - maxSize: 2, - defaultTtl: 3600, - strategy: "lru", - }); - - manager.set("key1", "value1"); - manager.set("key2", "value2"); - manager.set("key3", "value3"); - - const stats = manager.getStats(); - assert(stats.evictions > 0); - }); - }); - - describe("statistics", () => { - let manager: CacheManager; - - beforeEach(() => { - manager = new CacheManager(); - }); - - it("returns cache statistics", () => { - manager.set("key1", "value1"); - manager.get("key1"); - manager.get("unknown"); - - const stats = manager.getStats(); - assert.equal(stats.totalEntries, 1); - assert(stats.hitRate > 0); - assert(stats.hitRate <= 1); - }); - - it("calculates hit rate", () => { - manager.set("key1", "value1"); - manager.get("key1"); - manager.get("key1"); - manager.get("unknown"); - - const hitRate = manager.getHitRate(); - assert(hitRate > 0); - assert(hitRate <= 100); - }); - - it("returns empty hit rate for no requests", () => { - const hitRate = manager.getHitRate(); - assert.equal(hitRate, 0); - }); - }); - - describe("inspection", () => { - let manager: CacheManager; - - beforeEach(() => { - manager = new CacheManager(); - manager.set("key1", "value1"); - manager.set("key2", { count: 2 }); - }); - - it("gets all cache keys", () => { - const keys = manager.getKeys(); - assert(keys.includes("key1")); - assert(keys.includes("key2")); - }); - - it("gets cache entry details", () => { - manager.get("key1"); // increment hits - const entry = manager.getEntry("key1"); - assert(entry); - assert.equal(entry.key, "key1"); - assert.equal(entry.hits, 1); - }); - - it("gets all entries", () => { - const entries = manager.getAllEntries(); - assert.equal(entries.length, 2); - }); - - it("estimates cache size", () => { - manager.set("large_key", { data: "x".repeat(1000) }); - const size = manager.getApproximateSize(); - assert(size > 0); - }); - }); - - describe("configuration", () => { - it("uses custom config", () => { - const config: CacheConfig = { - maxSize: 500, - defaultTtl: 7200, - strategy: "lfu", - }; - const manager = new CacheManager(config); - const returnedConfig = manager.getConfig(); - assert.deepEqual(returnedConfig, config); - }); - - it("uses default config when not provided", () => { - const manager = new CacheManager(); - const config = manager.getConfig(); - assert.equal(config.maxSize, 1000); - assert.equal(config.defaultTtl, 3600); - }); - }); -}); diff --git a/src/cache-manager.ts b/src/cache-manager.ts deleted file mode 100644 index a4237cc0..00000000 --- a/src/cache-manager.ts +++ /dev/null @@ -1,317 +0,0 @@ -// ─── Types ──────────────────────────────────────────────────────────────────── - -export interface CacheEntry { - key: string; - value: T; - ttl?: number; // seconds - createdAt: string; - expiresAt?: string; - hits: number; -} - -export interface CacheStats { - totalSize: number; - totalEntries: number; - hitRate: number; - evictions: number; -} - -export interface CacheConfig { - maxSize: number; // max entries - defaultTtl: number; // seconds - strategy: "lru" | "lfu" | "fifo"; -} - -// ─── CacheManager ──────────────────────────────────────────────────────────── - -export class CacheManager { - private cache: Map = new Map(); - private hits: number = 0; - private misses: number = 0; - private evictions: number = 0; - private config: CacheConfig; - - constructor(config: CacheConfig = { maxSize: 1000, defaultTtl: 3600, strategy: "lru" }) { - this.config = config; - } - - // ─── Basic Operations ────────────────────────────────────────────────────── - - /** - * Set cache entry. - */ - set(key: string, value: T, ttl?: number): void { - // Check capacity - if ( - this.cache.size >= this.config.maxSize && - !this.cache.has(key) - ) { - this.evictEntry(); - } - - const expiresAt = ttl - ? new Date(Date.now() + ttl * 1000).toISOString() - : undefined; - - this.cache.set(key, { - key, - value, - ttl, - createdAt: new Date().toISOString(), - expiresAt, - hits: 0, - }); - } - - /** - * Get cache entry. - */ - get(key: string): T | null { - const entry = this.cache.get(key); - - if (!entry) { - this.misses++; - return null; - } - - // Check expiration - if (entry.expiresAt && new Date(entry.expiresAt) < new Date()) { - this.cache.delete(key); - this.misses++; - return null; - } - - // Record hit - entry.hits++; - this.hits++; - - return entry.value as T; - } - - /** - * Check if key exists. - */ - has(key: string): boolean { - const entry = this.cache.get(key); - if (!entry) return false; - - // Check expiration - if (entry.expiresAt && new Date(entry.expiresAt) < new Date()) { - this.cache.delete(key); - return false; - } - - return true; - } - - /** - * Delete cache entry. - */ - delete(key: string): boolean { - return this.cache.delete(key); - } - - /** - * Clear all cache entries. - */ - clear(): void { - this.cache.clear(); - this.hits = 0; - this.misses = 0; - } - - // ─── Cache Invalidation ──────────────────────────────────────────────────── - - /** - * Invalidate entries by pattern. - */ - invalidatePattern(pattern: string): number { - let count = 0; - const regex = new RegExp(pattern); - - for (const key of this.cache.keys()) { - if (regex.test(key)) { - this.cache.delete(key); - count++; - } - } - - return count; - } - - /** - * Invalidate entries by prefix. - */ - invalidatePrefix(prefix: string): number { - let count = 0; - - for (const key of this.cache.keys()) { - if (key.startsWith(prefix)) { - this.cache.delete(key); - count++; - } - } - - return count; - } - - /** - * Clear expired entries. - */ - cleanExpired(): number { - let count = 0; - const now = new Date(); - - for (const entry of this.cache.values()) { - if (entry.expiresAt && new Date(entry.expiresAt) < now) { - this.cache.delete(entry.key); - count++; - } - } - - return count; - } - - // ─── Eviction Strategy ───────────────────────────────────────────────────── - - private evictEntry(): void { - let keyToEvict: string | null = null; - - if (this.config.strategy === "lru") { - // Least Recently Used: lowest hit count - keyToEvict = this.findLRUKey(); - } else if (this.config.strategy === "lfu") { - // Least Frequently Used: oldest entry - keyToEvict = this.findLFUKey(); - } else if (this.config.strategy === "fifo") { - // First In First Out: oldest by creation time - keyToEvict = this.findFIFOKey(); - } - - if (keyToEvict) { - this.cache.delete(keyToEvict); - this.evictions++; - } - } - - private findLRUKey(): string | null { - let minHits = Infinity; - let oldestKey: string | null = null; - - for (const [key, entry] of this.cache.entries()) { - if (entry.hits < minHits) { - minHits = entry.hits; - oldestKey = key; - } - } - - return oldestKey; - } - - private findLFUKey(): string | null { - let minTime = Infinity; - let oldestKey: string | null = null; - - for (const [key, entry] of this.cache.entries()) { - const createdTime = new Date(entry.createdAt).getTime(); - if (createdTime < minTime) { - minTime = createdTime; - oldestKey = key; - } - } - - return oldestKey; - } - - private findFIFOKey(): string | null { - return this.cache.keys().next().value || null; - } - - // ─── Statistics ──────────────────────────────────────────────────────────── - - /** - * Get cache statistics. - */ - getStats(): CacheStats { - const totalRequests = this.hits + this.misses; - const hitRate = totalRequests > 0 ? this.hits / totalRequests : 0; - - return { - totalSize: this.cache.size, - totalEntries: this.cache.size, - hitRate: Math.round(hitRate * 100) / 100, - evictions: this.evictions, - }; - } - - /** - * Get hit count. - */ - getHits(): number { - return this.hits; - } - - /** - * Get miss count. - */ - getMisses(): number { - return this.misses; - } - - /** - * Get hit rate percentage. - */ - getHitRate(): number { - const total = this.hits + this.misses; - if (total === 0) return 0; - return Math.round((this.hits / total) * 100); - } - - // ─── Cache Inspection ────────────────────────────────────────────────────── - - /** - * Get all cache keys. - */ - getKeys(): string[] { - return [...this.cache.keys()]; - } - - /** - * Get cache entry details. - */ - getEntry(key: string): CacheEntry | null { - const entry = this.cache.get(key); - return entry ? (entry as CacheEntry) : null; - } - - /** - * Get all entries. - */ - getAllEntries(): CacheEntry[] { - return [...this.cache.values()]; - } - - /** - * Get size in bytes (rough estimate). - */ - getApproximateSize(): number { - let size = 0; - - for (const entry of this.cache.values()) { - // Rough estimate: key length + value serialization - size += entry.key.length + JSON.stringify(entry.value).length; - } - - return size; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getCacheMap(): Map { - return this.cache; - } - - getConfig(): CacheConfig { - return this.config; - } -} diff --git a/src/cdn-adapter.test.ts b/src/cdn-adapter.test.ts deleted file mode 100644 index b2232382..00000000 --- a/src/cdn-adapter.test.ts +++ /dev/null @@ -1,486 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { CDNAdapter, createCDNAdapter } from "./cdn-adapter.js"; - -describe("CDNAdapter", () => { - describe("initialization", () => { - it("creates adapter with config", () => { - const adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - - assert.equal(adapter.name, "cdn"); - assert.equal(adapter.version, "1.0.0"); - }); - - it("initializes with disabled config", () => { - const adapter = new CDNAdapter({ enabled: false }); - assert(!adapter.isConnected()); - }); - - it("creates adapter with default config", () => { - const adapter = new CDNAdapter(); - assert(!adapter.isConnected()); - }); - }); - - describe("connection management", () => { - let adapter: CDNAdapter; - - beforeEach(() => { - adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - }); - - it("connects with valid credentials", async () => { - await adapter.connect(); - assert(adapter.isConnected()); - }); - - it("throws error when enabled without API key", async () => { - const invalidAdapter = new CDNAdapter({ - enabled: true, - endpoint: "E123ABC.cloudfront.net", - }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("API Key is required")); - } - }); - - it("throws error when enabled without endpoint", async () => { - const invalidAdapter = new CDNAdapter({ - enabled: true, - apiKey: "test-key", - }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("endpoint")); - } - }); - - it("disconnects cleanly", async () => { - await adapter.connect(); - assert(adapter.isConnected()); - - await adapter.disconnect(); - assert(!adapter.isConnected()); - }); - - it("skips connection when disabled", async () => { - const disabledAdapter = new CDNAdapter({ - enabled: false, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - - await disabledAdapter.connect(); - assert(!disabledAdapter.isConnected()); - }); - }); - - describe("health monitoring", () => { - let adapter: CDNAdapter; - - beforeEach(async () => { - adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - await adapter.connect(); - }); - - it("reports healthy status when connected", async () => { - const health = await adapter.getHealth(); - - assert.equal(health.status, "healthy"); - assert(health.lastCheck); - assert(health.responseTime >= 0); - assert.equal(health.errorCount, 0); - }); - - it("records response time", async () => { - const health = await adapter.getHealth(); - assert(typeof health.responseTime === "number"); - }); - - it("updates lastCheck timestamp", async () => { - const before = new Date(); - const health = await adapter.getHealth(); - const after = new Date(); - - const lastCheck = new Date(health.lastCheck); - - assert(lastCheck >= before); - assert(lastCheck <= after); - }); - }); - - describe("cache purging", () => { - let adapter: CDNAdapter; - - beforeEach(async () => { - adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - await adapter.connect(); - }); - - it("purges specific paths", async () => { - const result = await adapter.purge(["/index.html", "/api/*"]); - - assert.equal(result, true); - }); - - it("purges single path", async () => { - const result = await adapter.purge(["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/assets/style.css"]); - - assert.equal(result, true); - }); - - it("purges all cache", async () => { - const result = await adapter.purgeAll(); - - assert.equal(result, true); - }); - - it("tracks invalidation count", async () => { - await adapter.purge(["/path1", "/path2", "/path3"]); - - const stats = adapter.getCacheStats(); - assert.equal(stats.invalidations, 3); - }); - - it("fails when disconnected", async () => { - await adapter.disconnect(); - - const result = await adapter.purge(["/test"]); - - assert.equal(result, false); - }); - }); - - describe("cache metrics", () => { - let adapter: CDNAdapter; - - beforeEach(async () => { - adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - await adapter.connect(); - }); - - it("records cache hits", async () => { - const result = await adapter.recordCacheHit("/index.html", 45000); - - assert.equal(result, true); - }); - - it("records cache misses", async () => { - const result = await adapter.recordCacheMiss("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/api/data", 12000); - - assert.equal(result, true); - }); - - it("records cache misses without size", async () => { - const result = await adapter.recordCacheMiss("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/new/path"); - - assert.equal(result, true); - }); - - it("tracks hit count", async () => { - await adapter.recordCacheHit("/path1"); - await adapter.recordCacheHit("/path2"); - - const stats = adapter.getCacheStats(); - assert.equal(stats.hits, 2); - }); - - it("tracks miss count", async () => { - await adapter.recordCacheMiss("/miss1"); - await adapter.recordCacheMiss("/miss2"); - await adapter.recordCacheMiss("/miss3"); - - const stats = adapter.getCacheStats(); - assert.equal(stats.misses, 3); - }); - - it("calculates hit rate", async () => { - await adapter.recordCacheHit("/hit1"); - await adapter.recordCacheHit("/hit2"); - await adapter.recordCacheMiss("/miss1"); - await adapter.recordCacheMiss("/miss2"); - - const stats = adapter.getCacheStats(); - assert.equal(stats.hitRate, 50); - }); - - it("records cache evictions", async () => { - await adapter.recordEviction(); - await adapter.recordEviction(); - - const stats = adapter.getCacheStats(); - assert.equal(stats.evictions, 2); - }); - - it("handles zero hits/misses gracefully", () => { - const stats = adapter.getCacheStats(); - assert.equal(stats.hitRate, 0); - }); - }); - - describe("cache policy", () => { - let adapter: CDNAdapter; - - beforeEach(async () => { - adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - await adapter.connect(); - }); - - it("sets cache policy for path pattern", async () => { - const result = await adapter.setCachePolicy("/assets/*", 3600); - - assert.equal(result, true); - }); - - it("sets cache policy with cache key", async () => { - const result = await adapter.setCachePolicy("/api/*", 300, { - headers: "accept-encoding", - queryStrings: "v", - }); - - assert.equal(result, true); - }); - - it("fails when disconnected", async () => { - await adapter.disconnect(); - - const result = await adapter.setCachePolicy("/path/*", 60); - - assert.equal(result, false); - }); - }); - - describe("cdn info", () => { - it("detects CloudFront provider", () => { - const adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-key", - endpoint: "E123ABC.cloudfront.net", - }); - - const info = adapter.getInfo(); - assert.equal(info.provider, "cloudfront"); - }); - - it("detects Cloudflare provider", () => { - const adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-key", - endpoint: "cf.example.com/cloudflare", - }); - - const info = adapter.getInfo(); - assert.equal(info.provider, "cloudflare"); - }); - - it("returns masked API key", () => { - const adapter = new CDNAdapter({ - enabled: true, - apiKey: "secret-key-12345", - endpoint: "E123ABC.cloudfront.net", - }); - - const info = adapter.getInfo(); - assert.equal(info.apiKey, "***"); - }); - - it("returns empty API key when not set", () => { - const adapter = new CDNAdapter({ - enabled: false, - }); - - const info = adapter.getInfo(); - assert.equal(info.apiKey, ""); - }); - - it("returns endpoint", () => { - const adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-key", - endpoint: "E123ABC.cloudfront.net", - }); - - const info = adapter.getInfo(); - assert.equal(info.endpoint, "E123ABC.cloudfront.net"); - }); - }); - - describe("event validation", () => { - let adapter: CDNAdapter; - - beforeEach(async () => { - adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - await adapter.connect(); - }); - - it("requires event type", async () => { - try { - await (adapter as any).sendEvent({ - data: { operation: "purge" }, - timestamp: new Date().toISOString(), - }); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid event")); - } - }); - - it("requires event data", async () => { - try { - await (adapter as any).sendEvent({ - type: "event", - timestamp: new Date().toISOString(), - }); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid event")); - } - }); - }); - - describe("queue flushing", () => { - let adapter: CDNAdapter; - - beforeEach(() => { - adapter = new CDNAdapter({ - enabled: true, - apiKey: "test-api-key", - endpoint: "E123ABC.cloudfront.net", - }); - }); - - it("flushes queued events on connection", async () => { - await adapter.purge(["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/queued/path1"]); - await adapter.purge(["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/queued/path2"]); - - await adapter.connect(); - - assert(adapter.isConnected()); - }); - - it("handles empty queue gracefully", async () => { - await adapter.connect(); - - assert(true); - }); - }); - - describe("factory function", () => { - it("creates enabled adapter with all env vars", () => { - const originalKey = process.env.CDN_API_KEY; - const originalEndpoint = process.env.CDN_ENDPOINT; - - try { - process.env.CDN_API_KEY = "test-key"; - process.env.CDN_ENDPOINT = "E123ABC.cloudfront.net"; - - const adapter = createCDNAdapter(true); - - assert(adapter.config.enabled); - assert(adapter.config.apiKey); - assert(adapter.config.endpoint); - } finally { - process.env.CDN_API_KEY = originalKey; - process.env.CDN_ENDPOINT = originalEndpoint; - } - }); - - it("creates enabled adapter with CLOUDFRONT_DISTRIBUTION_ID", () => { - const originalKey = process.env.CDN_API_KEY; - const originalDist = process.env.CLOUDFRONT_DISTRIBUTION_ID; - const originalEndpoint = process.env.CDN_ENDPOINT; - - try { - process.env.CDN_API_KEY = "test-key"; - delete process.env.CDN_ENDPOINT; - process.env.CLOUDFRONT_DISTRIBUTION_ID = "E123ABC"; - - const adapter = createCDNAdapter(true); - - assert(adapter.config.enabled); - } finally { - process.env.CDN_API_KEY = originalKey; - process.env.CLOUDFRONT_DISTRIBUTION_ID = originalDist; - process.env.CDN_ENDPOINT = originalEndpoint; - } - }); - - it("creates disabled adapter without credentials", () => { - const originalKey = process.env.CDN_API_KEY; - const originalEndpoint = process.env.CDN_ENDPOINT; - const originalDist = process.env.CLOUDFRONT_DISTRIBUTION_ID; - - try { - delete process.env.CDN_API_KEY; - delete process.env.CDN_ENDPOINT; - delete process.env.CLOUDFRONT_DISTRIBUTION_ID; - - const adapter = createCDNAdapter(true); - - assert(!adapter.config.enabled); - } finally { - process.env.CDN_API_KEY = originalKey; - process.env.CDN_ENDPOINT = originalEndpoint; - process.env.CLOUDFRONT_DISTRIBUTION_ID = originalDist; - } - }); - - it("respects enabled parameter", () => { - const adapter = createCDNAdapter(false); - - assert(!adapter.config.enabled); - }); - - it("defaults to enabled", () => { - const originalKey = process.env.CDN_API_KEY; - const originalEndpoint = process.env.CDN_ENDPOINT; - - try { - process.env.CDN_API_KEY = "test-key"; - process.env.CDN_ENDPOINT = "E123ABC.cloudfront.net"; - - const adapter = createCDNAdapter(); - - assert(adapter.config.enabled); - } finally { - process.env.CDN_API_KEY = originalKey; - process.env.CDN_ENDPOINT = originalEndpoint; - } - }); - }); -}); diff --git a/src/cdn-adapter.ts b/src/cdn-adapter.ts deleted file mode 100644 index e1753d59..00000000 --- a/src/cdn-adapter.ts +++ /dev/null @@ -1,335 +0,0 @@ -// ─── CDN Integration Adapter (CloudFront/Cloudflare) ──────────────────── - -import { - AbstractServiceAdapter, - simulatedFailuresEnabled, - type ServiceConfig, - type ServiceEvent, - type ServiceHealth, -} from "./service-adapter.js"; - -/** - * CDN adapter for CloudFront and Cloudflare integration. - */ -export class CDNAdapter extends AbstractServiceAdapter { - private lastHealthCheck: string = new Date().toISOString(); - private healthCheckErrors: number = 0; - private cacheStats = { - hits: 0, - misses: 0, - evictions: 0, - invalidations: 0, - }; - - constructor(config: ServiceConfig = { enabled: false }) { - super("cdn", "1.0.0", config); - } - - async connect(): Promise { - if (!this.config.enabled) { - this.connected = false; - return; - } - - // Validate required config - if (!this.config.apiKey) { - throw new Error("CDN API Key is required"); - } - - if (!this.config.endpoint) { - throw new Error("CDN endpoint/distribution ID is required"); - } - - // Simulate connection test - await new Promise((resolve) => setTimeout(resolve, 75)); - - this.connected = true; - - // Flush queued events - await this.flushQueue(); - } - - async disconnect(): Promise { - if (this.healthCheckInterval) { - clearInterval(this.healthCheckInterval); - this.healthCheckInterval = null; - } - this.connected = false; - } - - async getHealth(): Promise { - const responseTime = Math.random() * 100; - - try { - if (!this.connected) { - this.healthCheckErrors++; - } - - this.lastHealthCheck = new Date().toISOString(); - - const status = - this.healthCheckErrors < 3 - ? this.connected - ? "healthy" - : "degraded" - : "unhealthy"; - - return { - status, - lastCheck: this.lastHealthCheck, - responseTime: Math.round(responseTime), - errorCount: this.healthCheckErrors, - }; - } catch { - this.healthCheckErrors++; - return { - status: "unhealthy", - lastCheck: new Date().toISOString(), - responseTime: -1, - errorCount: this.healthCheckErrors, - }; - } - } - - protected async sendEvent(event: ServiceEvent): Promise { - if (!this.connected) { - throw new Error("Not connected to CDN"); - } - - // Validate event - if (!event.type || !event.data) { - throw new Error("Invalid event format"); - } - - // Simulate CDN API call - await new Promise((resolve) => setTimeout(resolve, Math.random() * 75)); - - // Simulate occasional failures (0.2% rate for CDN) - if (simulatedFailuresEnabled() && Math.random() < 0.002) { - throw new Error("Simulated CDN API error"); - } - } - - /** - * Purge cache for specific paths. - */ - async purge(paths: string[]): Promise { - const event: ServiceEvent = { - type: "event", - data: { - operation: "purge", - paths, - count: paths.length, - }, - timestamp: new Date().toISOString(), - tags: { - operation: "purge", - }, - }; - - const success = await this.send(event); - - if (success) { - this.cacheStats.invalidations += paths.length; - } - - return success; - } - - /** - * Purge all cache. - */ - async purgeAll(): Promise { - const event: ServiceEvent = { - type: "event", - data: { - operation: "purge_all", - }, - timestamp: new Date().toISOString(), - tags: { - operation: "purge_all", - }, - }; - - const success = await this.send(event); - - if (success) { - this.cacheStats.invalidations++; - } - - return success; - } - - /** - * Record cache hit. - */ - async recordCacheHit(path: string, sizeBytes?: number): Promise { - const event: ServiceEvent = { - type: "metric", - data: { - operation: "cache_hit", - path, - sizeBytes, - }, - timestamp: new Date().toISOString(), - tags: { - operation: "cache_hit", - }, - }; - - const success = await this.send(event); - - if (success) { - this.cacheStats.hits++; - } - - return success; - } - - /** - * Record cache miss. - */ - async recordCacheMiss(path: string, sizeBytes?: number): Promise { - const event: ServiceEvent = { - type: "metric", - data: { - operation: "cache_miss", - path, - sizeBytes, - }, - timestamp: new Date().toISOString(), - tags: { - operation: "cache_miss", - }, - }; - - const success = await this.send(event); - - if (success) { - this.cacheStats.misses++; - } - - return success; - } - - /** - * Set cache headers. - */ - async setCachePolicy( - pathPattern: string, - ttl: number, - cacheKeyPolicy?: Record, - ): Promise { - const event: ServiceEvent = { - type: "event", - data: { - operation: "set_cache_policy", - pathPattern, - ttl, - cacheKeyPolicy, - }, - timestamp: new Date().toISOString(), - tags: { - operation: "set_cache_policy", - }, - }; - - return this.send(event); - } - - /** - * Get current cache statistics. - */ - getCacheStats(): { - hits: number; - misses: number; - evictions: number; - invalidations: number; - hitRate: number; - } { - const total = this.cacheStats.hits + this.cacheStats.misses; - const hitRate = total > 0 ? (this.cacheStats.hits / total) * 100 : 0; - - return { - ...this.cacheStats, - hitRate: Math.round(hitRate * 100) / 100, - }; - } - - /** - * Record cache eviction. - */ - async recordEviction(): Promise { - const event: ServiceEvent = { - type: "metric", - data: { - operation: "eviction", - }, - timestamp: new Date().toISOString(), - tags: { - operation: "eviction", - }, - }; - - const success = await this.send(event); - - if (success) { - this.cacheStats.evictions++; - } - - return success; - } - - /** - * Flush all queued events. - */ - private async flushQueue(): Promise { - const queued = this.getQueuedEvents(); - if (queued.length === 0) return; - - const { sent, failed } = await this.batch(queued); - - if (sent > 0) { - this.clearQueue(); - } - - console.log(`Flushed CDN queue: ${sent} sent, ${failed} failed`); - } - - /** - * Get CDN configuration info. - */ - getInfo(): { - provider: string; - endpoint: string; - apiKey: string; - } { - const provider = this.config.endpoint?.includes("cloudflare") ? "cloudflare" : "cloudfront"; - - return { - provider, - endpoint: this.config.endpoint || "", - apiKey: this.config.apiKey ? "***" : "", - }; - } -} - -/** - * Create a CDN adapter from environment variables. - */ -export function createCDNAdapter(enabled: boolean = true): CDNAdapter { - const apiKey = process.env.CDN_API_KEY; - const endpoint = process.env.CDN_ENDPOINT || process.env.CLOUDFRONT_DISTRIBUTION_ID; - - if (enabled && (!apiKey || !endpoint)) { - console.warn( - "CDN is enabled but CDN_API_KEY and CDN_ENDPOINT environment variables are required", - ); - } - - return new CDNAdapter({ - enabled: enabled && !!apiKey && !!endpoint, - apiKey, - endpoint, - }); -} diff --git a/src/ci-cd-publisher.test.ts b/src/ci-cd-publisher.test.ts deleted file mode 100644 index fce55f8e..00000000 --- a/src/ci-cd-publisher.test.ts +++ /dev/null @@ -1,500 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { - CICDPublishEngine, - type PublishConfig, - type GitHubEvent, -} from "./ci-cd-publisher.js"; - -// ─── Helpers ────────────────────────────────────────────────────────────────── - -function makeConfig(overrides: Partial = {}): PublishConfig { - return { - enabled: true, - trigger: "tag", - validateBuild: true, - validateTests: true, - requireApproval: false, - autoGenerateChangelog: true, - githubReleaseTracking: true, - ...overrides, - }; -} - -function makeGitHubEvent( - event: string, - overrides: Partial = {}, -): GitHubEvent { - return { - event, - timestamp: new Date().toISOString(), - ...overrides, - }; -} - -// ─── Tests ──────────────────────────────────────────────────────────────────── - -describe("CICDPublishEngine", () => { - describe("initialization", () => { - it("creates engine instance", () => { - const engine = new CICDPublishEngine(); - assert(engine); - }); - - it("starts with empty caches", () => { - const engine = new CICDPublishEngine(); - assert.equal(engine.getPublishPlansCache().size, 0); - assert.equal(engine.getExecutionsCache().size, 0); - assert.equal(engine.getGitHubReleasesCache().size, 0); - }); - }); - - describe("setPublishConfig & getPublishConfig", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - }); - - it("stores publish config", () => { - const config = makeConfig(); - engine.setPublishConfig("stripe/payments", config); - const stored = engine.getPublishConfig("stripe/payments"); - assert.deepEqual(stored, config); - }); - - it("returns null for unknown plugin", () => { - const config = engine.getPublishConfig("unknown"); - assert.equal(config, null); - }); - - it("supports multiple plugins", () => { - engine.setPublishConfig("stripe/payments", makeConfig()); - engine.setPublishConfig("supabase/db", makeConfig({ trigger: "release" })); - - const stripe = engine.getPublishConfig("stripe/payments"); - const supabase = engine.getPublishConfig("supabase/db"); - assert(stripe); - assert(supabase); - assert.notEqual(stripe.trigger, supabase.trigger); - }); - }); - - describe("handleGitHubEvent", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - engine.setPublishConfig("stripe/payments", makeConfig({ trigger: "tag" })); - engine.setPublishConfig("supabase/db", makeConfig({ trigger: "release" })); - }); - - it("creates publish plan on tag push", () => { - const plan = engine.handleGitHubEvent( - "stripe/payments", - makeGitHubEvent("push", { ref: "refs/tags/v1.2.3", tag: "v1.2.3" }), - ); - assert(plan); - assert.equal(plan.nextVersion, "v1.2.3"); - }); - - it("creates publish plan on release event", () => { - const plan = engine.handleGitHubEvent( - "supabase/db", - makeGitHubEvent("release", { tag: "v2.0.0" }), - ); - assert(plan); - }); - - it("returns null if config disabled", () => { - engine.setPublishConfig("disabled", makeConfig({ enabled: false })); - const plan = engine.handleGitHubEvent( - "disabled", - makeGitHubEvent("push", { tag: "v1.0.0" }), - ); - assert.equal(plan, null); - }); - - it("returns null if trigger doesn't match", () => { - const plan = engine.handleGitHubEvent( - "stripe/payments", - makeGitHubEvent("release", { tag: "v1.0.0" }), - ); - assert.equal(plan, null); - }); - - it("returns null if no version in event", () => { - const plan = engine.handleGitHubEvent( - "stripe/payments", - makeGitHubEvent("push", { ref: "refs/heads/main" }), - ); - assert.equal(plan, null); - }); - }); - - describe("detectVersion", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - }); - - it("detects version from package.json method", () => { - const detection = engine.detectVersion("stripe/payments", "package.json"); - assert.equal(detection.method, "package.json"); - assert(detection.detected); - }); - - it("detects version from git tag method", () => { - const detection = engine.detectVersion("stripe/payments", "git_tag"); - assert.equal(detection.method, "git_tag"); - assert(detection.detected); - }); - - it("accepts manual version", () => { - const detection = engine.detectVersion("stripe/payments", "manual", "1.5.0"); - assert.equal(detection.detected, "1.5.0"); - }); - - it("determines bump type", () => { - const detection = engine.detectVersion("stripe/payments", "manual", "2.0.0"); - assert(detection.bump); // Should detect some bump type - }); - }); - - describe("validateBeforePublish", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - engine.setPublishConfig("test-plugin", makeConfig()); - }); - - it("returns validation result", () => { - const result = engine.validateBeforePublish("test-plugin"); - assert(result.checks.length > 0); - assert(result.status); - assert(result.timestamp); - }); - - it("includes build check when configured", () => { - engine.setPublishConfig("test-plugin", makeConfig({ validateBuild: true })); - const result = engine.validateBeforePublish("test-plugin"); - assert(result.checks.some((c) => c.name === "Build")); - }); - - it("includes test check when configured", () => { - engine.setPublishConfig("test-plugin", makeConfig({ validateTests: true })); - const result = engine.validateBeforePublish("test-plugin"); - assert(result.checks.some((c) => c.name === "Tests")); - }); - - it("marks validation as pass when all checks pass", () => { - const result = engine.validateBeforePublish("test-plugin"); - assert.equal(result.status, "pass"); - }); - }); - - describe("createPublishPlan", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - engine.setPublishConfig("stripe/payments", makeConfig()); - }); - - it("creates publish plan", () => { - const plan = engine.createPublishPlan("stripe/payments", "1.2.3", "1.2.0"); - assert(plan); - assert.equal(plan.nextVersion, "1.2.3"); - assert.equal(plan.currentVersion, "1.2.0"); - }); - - it("includes validation results", () => { - const plan = engine.createPublishPlan("stripe/payments", "1.2.3"); - assert(plan.validations); - assert(plan.validations.checks.length > 0); - }); - - it("includes changelog", () => { - const plan = engine.createPublishPlan("stripe/payments", "1.2.3"); - assert(plan.changelog); - assert(plan.changelog.includes("1.2.3")); - }); - - it("marks as ready when no approval required", () => { - engine.setPublishConfig("stripe/payments", makeConfig({ requireApproval: false })); - const plan = engine.createPublishPlan("stripe/payments", "1.2.3"); - assert(plan.readyToPublish); - }); - - it("marks as not ready when approval required", () => { - engine.setPublishConfig("stripe/payments", makeConfig({ requireApproval: true })); - const plan = engine.createPublishPlan("stripe/payments", "1.2.3"); - assert(!plan.readyToPublish); - }); - - it("retrieves plan by pluginId and version", () => { - const created = engine.createPublishPlan("stripe/payments", "1.2.3"); - const retrieved = engine.getPublishPlan("stripe/payments", "1.2.3"); - assert.equal(retrieved?.nextVersion, created.nextVersion); - }); - }); - - describe("approvePlan & isPlanApproved", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - engine.setPublishConfig("stripe/payments", makeConfig({ requireApproval: true })); - engine.createPublishPlan("stripe/payments", "1.2.3"); - }); - - it("approves a plan", () => { - const approved = engine.approvePlan("stripe/payments", "1.2.3", "user-1"); - assert(approved); - }); - - it("returns false when no plan exists", () => { - const approved = engine.approvePlan("unknown", "1.0.0", "user-1"); - assert(!approved); - }); - - it("checks if plan is approved", () => { - engine.approvePlan("stripe/payments", "1.2.3", "user-1"); - assert(engine.isPlanApproved("stripe/payments", "1.2.3")); - }); - - it("marks plan as ready after approval", () => { - engine.approvePlan("stripe/payments", "1.2.3", "user-1"); - const plan = engine.getPublishPlan("stripe/payments", "1.2.3"); - assert(plan?.readyToPublish); - assert.equal(plan?.approvedBy, "user-1"); - }); - }); - - describe("startPublish & updateExecution", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - }); - - it("starts a publish execution", () => { - const exec = engine.startPublish("stripe/payments", "1.2.3", "tag"); - assert(exec.id); - assert.equal(exec.status, "pending"); - assert.equal(exec.version, "1.2.3"); - }); - - it("retrieves execution by ID", () => { - const started = engine.startPublish("stripe/payments", "1.2.3", "tag"); - const retrieved = engine.getExecution(started.id); - assert.equal(retrieved?.id, started.id); - }); - - it("returns null for unknown execution", () => { - const exec = engine.getExecution("unknown"); - assert.equal(exec, null); - }); - - it("updates execution status", () => { - const started = engine.startPublish("stripe/payments", "1.2.3", "tag"); - const updated = engine.updateExecution(started.id, "validating", ["Running tests"]); - assert.equal(updated?.status, "validating"); - assert(updated?.logs.includes("Running tests")); - }); - - it("appends logs on update", () => { - const started = engine.startPublish("stripe/payments", "1.2.3", "tag"); - engine.updateExecution(started.id, "validating", ["Log 1"]); - engine.updateExecution(started.id, "publishing", ["Log 2"]); - const final = engine.getExecution(started.id); - assert.equal(final?.logs.length, 2); - }); - - it("marks completion time when done", () => { - const started = engine.startPublish("stripe/payments", "1.2.3", "tag"); - engine.updateExecution(started.id, "completed"); - const final = engine.getExecution(started.id); - assert(final?.completedAt); - }); - - it("failExecution sets error and failed status", () => { - const started = engine.startPublish("stripe/payments", "1.2.3", "tag"); - engine.failExecution(started.id, "Build failed"); - const final = engine.getExecution(started.id); - assert.equal(final?.status, "failed"); - assert.equal(final?.error, "Build failed"); - assert(final?.completedAt); - }); - }); - - describe("createGitHubRelease", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - }); - - it("creates GitHub release", () => { - const release = engine.createGitHubRelease( - "stripe/payments", - "1.2.3", - "## Changes\n- Feature X", - ); - assert(release.id); - assert.equal(release.tagName, "v1.2.3"); - assert(release.releaseUrl.includes("v1.2.3")); - }); - - it("includes asset URL for npm", () => { - const release = engine.createGitHubRelease("stripe/payments", "1.2.3", ""); - assert(release.assetUrl); - assert(release.assetUrl.includes("stripe/payments")); - assert(release.assetUrl.includes("1.2.3")); - }); - - it("retrieves release by plugin and version", () => { - const created = engine.createGitHubRelease("stripe/payments", "1.2.3", ""); - const retrieved = engine.getGitHubRelease("stripe/payments", "1.2.3"); - assert.equal(retrieved?.id, created.id); - }); - - it("returns null for unknown release", () => { - const release = engine.getGitHubRelease("unknown", "1.0.0"); - assert.equal(release, null); - }); - }); - - describe("generateChangelog", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - }); - - it("generates changelog", () => { - const changelog = engine.generateChangelog("stripe/payments", "1.2.3"); - assert(changelog.includes("1.2.3")); - assert(changelog.includes("Added")); - assert(changelog.includes("Fixed")); - }); - - it("includes version and date", () => { - const changelog = engine.generateChangelog("stripe/payments", "2.0.0"); - assert(changelog.includes("[2.0.0]")); - }); - }); - - describe("generateWorkflow", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - }); - - it("generates GitHub Actions workflow for tag trigger", () => { - const config = makeConfig({ trigger: "tag" }); - const workflow = engine.generateWorkflow("stripe/payments", config); - assert(workflow.includes("on:")); - assert(workflow.includes("push:")); - assert(workflow.includes("tags:")); - }); - - it("includes build step when configured", () => { - const config = makeConfig({ trigger: "tag", validateBuild: true }); - const workflow = engine.generateWorkflow("stripe/payments", config); - assert(workflow.includes("npm run build")); - }); - - it("includes test step when configured", () => { - const config = makeConfig({ trigger: "tag", validateTests: true }); - const workflow = engine.generateWorkflow("stripe/payments", config); - assert(workflow.includes("npm test")); - }); - - it("generates workflow for release trigger", () => { - const config = makeConfig({ trigger: "release" }); - const workflow = engine.generateWorkflow("stripe/payments", config); - assert(workflow.includes("release:")); - }); - }); - - describe("pre/post publish scripts", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - }); - - it("executes pre-publish script when configured", () => { - const config = makeConfig({ prePublishScript: "npm run validate" }); - engine.setPublishConfig("stripe/payments", config); - const logs = engine.executePrePublishScript("stripe/payments", "1.2.3"); - assert(logs.length > 0); - assert(logs.some((l) => l.includes("validation"))); - }); - - it("executes post-publish script when configured", () => { - const config = makeConfig({ postPublishScript: "npm run cleanup" }); - engine.setPublishConfig("stripe/payments", config); - const logs = engine.executePostPublishScript("stripe/payments", "1.2.3"); - assert(logs.length > 0); - assert(logs.some((l) => l.includes("cleanup"))); - }); - - it("returns empty logs when no script configured", () => { - const logs = engine.executePrePublishScript("stripe/payments", "1.2.3"); - assert.equal(logs.length, 0); - }); - }); - - describe("changelog history", () => { - let engine: CICDPublishEngine; - - beforeEach(() => { - engine = new CICDPublishEngine(); - }); - - it("records changelog entry", () => { - engine.recordChangelogEntry("stripe/payments", { - version: "1.0.0", - date: "2025-04-15", - summary: "Initial release", - commits: [], - breaking: false, - features: ["Feature A"], - fixes: [], - docs: [], - }); - const history = engine.getChangelogHistory("stripe/payments"); - assert.equal(history.length, 1); - }); - - it("tracks multiple changelog entries", () => { - engine.recordChangelogEntry("stripe/payments", { - version: "1.0.0", - date: "2025-04-15", - summary: "Initial release", - commits: [], - breaking: false, - features: [], - fixes: [], - docs: [], - }); - engine.recordChangelogEntry("stripe/payments", { - version: "1.1.0", - date: "2025-04-16", - summary: "Bug fixes", - commits: [], - breaking: false, - features: [], - fixes: ["Bug X"], - docs: [], - }); - const history = engine.getChangelogHistory("stripe/payments"); - assert.equal(history.length, 2); - }); - }); -}); diff --git a/src/ci-cd-publisher.ts b/src/ci-cd-publisher.ts deleted file mode 100644 index 81eda9e7..00000000 --- a/src/ci-cd-publisher.ts +++ /dev/null @@ -1,485 +0,0 @@ -import { IdGenerators } from "./id-generator.js"; -// ─── Types ──────────────────────────────────────────────────────────────────── - -export type PublishTrigger = "manual" | "tag" | "release" | "workflow_dispatch"; -export type ValidationStatus = "pass" | "fail" | "warning"; - -export interface GitHubEvent { - event: string; - ref?: string; - tag?: string; - sha?: string; - actor?: string; - timestamp: string; -} - -export interface PublishConfig { - enabled: boolean; - trigger: PublishTrigger; - validateBuild: boolean; - validateTests: boolean; - requireApproval: boolean; - autoGenerateChangelog: boolean; - githubReleaseTracking: boolean; - prePublishScript?: string; - postPublishScript?: string; -} - -export interface VersionDetection { - method: "package.json" | "git_tag" | "manual"; - detected: string | null; - previous: string | null; - bump: "major" | "minor" | "patch" | "prerelease" | null; -} - -export interface ValidationResult { - status: ValidationStatus; - checks: Array<{ name: string; status: ValidationStatus; message: string }>; - timestamp: string; -} - -export interface PublishPlan { - pluginId: string; - currentVersion: string; - nextVersion: string; - changelog: string; - validations: ValidationResult; - approvalRequired: boolean; - approvedBy?: string; - approvedAt?: string; - readyToPublish: boolean; -} - -export interface PublishExecution { - id: string; - pluginId: string; - version: string; - trigger: PublishTrigger; - status: "pending" | "validating" | "approved" | "publishing" | "completed" | "failed"; - startedAt: string; - completedAt?: string; - githubRelease?: { url: string; id: string }; - logs: string[]; - error?: string; -} - -export interface GitHubRelease { - id: string; - tagName: string; - releaseUrl: string; - assetUrl?: string; - publishedAt: string; - body: string; -} - -export interface ChangelogEntry { - version: string; - date: string; - summary: string; - commits: Array<{ hash: string; message: string; author: string }>; - breaking: boolean; - features: string[]; - fixes: string[]; - docs: string[]; -} - -// ─── CICDPublishEngine ─────────────────────────────────────────────────────── - -export class CICDPublishEngine { - private publishPlans: Map = new Map(); - private executions: Map = new Map(); - private githubReleases: Map = new Map(); - private changelogHistory: Map = new Map(); - private publishConfig: Map = new Map(); - private approvals: Map = new Map(); - - // ─── Configuration ──────────────────────────────────────────────────────── - - /** - * Configure CI/CD publishing for a plugin. - */ - setPublishConfig(pluginId: string, config: PublishConfig): void { - this.publishConfig.set(pluginId, config); - } - - getPublishConfig(pluginId: string): PublishConfig | null { - return this.publishConfig.get(pluginId) || null; - } - - // ─── GitHub Event Handling ──────────────────────────────────────────────── - - /** - * Handle GitHub event (push, release, workflow dispatch, etc.). - */ - handleGitHubEvent(pluginId: string, event: GitHubEvent): PublishPlan | null { - const config = this.publishConfig.get(pluginId); - if (!config || !config.enabled) return null; - - // Check if event matches trigger - const shouldTrigger = - (config.trigger === "tag" && event.event === "push" && event.ref?.includes("refs/tags/")) || - (config.trigger === "release" && event.event === "release") || - (config.trigger === "workflow_dispatch" && event.event === "workflow_dispatch"); - - if (!shouldTrigger && config.trigger !== "manual") return null; - - // Extract version from tag or event - const version = event.tag || event.ref?.split("/").pop() || null; - if (!version) return null; - - // Create publish plan - const plan = this.createPublishPlan( - pluginId, - version, - "previous-1.0.0", - config.requireApproval, - ); - - return plan; - } - - // ─── Version Detection & Validation ─────────────────────────────────────── - - /** - * Detect current and next version from various sources. - */ - detectVersion( - pluginId: string, - method: "package.json" | "git_tag" | "manual", - manualVersion?: string, - ): VersionDetection { - const detection: VersionDetection = { - method, - detected: null, - previous: null, - bump: null, - }; - - if (method === "manual" && manualVersion) { - detection.detected = manualVersion; - } else if (method === "package.json") { - // Simulate reading package.json - detection.detected = "1.2.3"; - } else if (method === "git_tag") { - // Simulate reading git tags - detection.detected = "v1.2.3"; - } - - detection.previous = "1.2.0"; - detection.bump = this.determineBump(detection.previous || "1.0.0", detection.detected || "1.0.0"); - - return detection; - } - - private determineBump( - prev: string, - next: string, - ): "major" | "minor" | "patch" | "prerelease" | null { - const [prevMajor, prevMinor, prevPatch] = prev.split(".").map(Number); - const [nextMajor, nextMinor, nextPatch] = next.split(".").map(Number); - - if (nextMajor > prevMajor) return "major"; - if (nextMinor > prevMinor) return "minor"; - if (nextPatch > prevPatch) return "patch"; - if (next.includes("-")) return "prerelease"; - return null; - } - - /** - * Validate plugin before publishing. - */ - validateBeforePublish(pluginId: string): ValidationResult { - const config = this.publishConfig.get(pluginId); - const checks: Array<{ name: string; status: ValidationStatus; message: string }> = []; - - // Always run basic checks - checks.push({ - name: "Plugin ID valid", - status: "pass", - message: `Plugin ${pluginId} exists`, - }); - - checks.push({ - name: "Package metadata", - status: "pass", - message: "name, version, description present", - }); - - // Conditional checks - if (config?.validateBuild) { - checks.push({ - name: "Build", - status: "pass", - message: "TypeScript compilation successful", - }); - } - - if (config?.validateTests) { - checks.push({ - name: "Tests", - status: "pass", - message: "All tests passing (100% suite)", - }); - } - - checks.push({ - name: "License", - status: "pass", - message: "License file present", - }); - - checks.push({ - name: "README", - status: "pass", - message: "README with usage instructions", - }); - - const status: ValidationStatus = checks.every((c) => c.status !== "fail") ? "pass" : "fail"; - - return { - status, - checks, - timestamp: new Date().toISOString(), - }; - } - - // ─── Publish Planning ────────────────────────────────────────────────────── - - /** - * Create a publish plan with validations and approvals. - */ - createPublishPlan( - pluginId: string, - nextVersion: string, - currentVersion: string = "1.0.0", - requireApproval?: boolean, - ): PublishPlan { - const config = this.publishConfig.get(pluginId); - const needsApproval = requireApproval !== undefined ? requireApproval : config?.requireApproval ?? false; - - const validations = this.validateBeforePublish(pluginId); - const changelog = this.generateChangelog(pluginId, nextVersion); - - const plan: PublishPlan = { - pluginId, - currentVersion, - nextVersion, - changelog, - validations, - approvalRequired: needsApproval, - readyToPublish: validations.status === "pass" && (!needsApproval || !!this.approvals.get(`${pluginId}:${nextVersion}`)), - }; - - this.publishPlans.set(`${pluginId}:${nextVersion}`, plan); - return plan; - } - - getPublishPlan(pluginId: string, version: string): PublishPlan | null { - return this.publishPlans.get(`${pluginId}:${version}`) || null; - } - - // ─── Approvals ──────────────────────────────────────────────────────────── - - /** - * Approve a publish plan. - */ - approvePlan(pluginId: string, version: string, approvedBy: string): boolean { - const plan = this.publishPlans.get(`${pluginId}:${version}`); - if (!plan || !plan.approvalRequired) return false; - - const approval = { approvedBy, approvedAt: new Date().toISOString() }; - this.approvals.set(`${pluginId}:${version}`, approval); - plan.approvedBy = approvedBy; - plan.approvedAt = approval.approvedAt; - plan.readyToPublish = true; - - return true; - } - - /** - * Check if plan is approved. - */ - isPlanApproved(pluginId: string, version: string): boolean { - return this.approvals.has(`${pluginId}:${version}`); - } - - // ─── Publish Execution ──────────────────────────────────────────────────── - - /** - * Start a publish execution. - */ - startPublish(pluginId: string, version: string, trigger: PublishTrigger): PublishExecution { - const execId = IdGenerators.publish(); - - const execution: PublishExecution = { - id: execId, - pluginId, - version, - trigger, - status: "pending", - startedAt: new Date().toISOString(), - logs: [], - }; - - this.executions.set(execId, execution); - return execution; - } - - getExecution(execId: string): PublishExecution | null { - return this.executions.get(execId) || null; - } - - /** - * Update execution status and logs. - */ - updateExecution( - execId: string, - status: PublishExecution["status"], - logs: string[] = [], - ): PublishExecution | null { - const exec = this.executions.get(execId); - if (!exec) return null; - - exec.status = status; - exec.logs.push(...logs); - - if (status === "completed" || status === "failed") { - exec.completedAt = new Date().toISOString(); - } - - return exec; - } - - failExecution(execId: string, error: string): PublishExecution | null { - const exec = this.executions.get(execId); - if (!exec) return null; - - exec.status = "failed"; - exec.error = error; - exec.completedAt = new Date().toISOString(); - exec.logs.push(`ERROR: ${error}`); - - return exec; - } - - // ─── GitHub Release Creation ────────────────────────────────────────────── - - /** - * Create GitHub release after successful publish. - */ - createGitHubRelease( - pluginId: string, - version: string, - changelog: string, - ): GitHubRelease { - const releaseId = `gh-${Date.now()}`; - const release: GitHubRelease = { - id: releaseId, - tagName: `v${version}`, - releaseUrl: `https://github.com/sandstream/kit/releases/tag/v${version}`, - assetUrl: `https://registry.npmjs.org/${pluginId}/-/${pluginId}-${version}.tgz`, - publishedAt: new Date().toISOString(), - body: changelog, - }; - - this.githubReleases.set(`${pluginId}:${version}`, release); - return release; - } - - getGitHubRelease(pluginId: string, version: string): GitHubRelease | null { - return this.githubReleases.get(`${pluginId}:${version}`) || null; - } - - // ─── Changelog Generation ──────────────────────────────────────────────── - - /** - * Generate changelog from commits between versions. - */ - generateChangelog(pluginId: string, version: string): string { - const now = new Date(); - return `## [${version}] - ${now.toISOString().split("T")[0]}\n\n### Added\n- New features\n\n### Fixed\n- Bug fixes\n\n### Changed\n- Breaking changes\n`; - } - - /** - * Record changelog entry for historical tracking. - */ - recordChangelogEntry(pluginId: string, entry: ChangelogEntry): void { - const entries = this.changelogHistory.get(pluginId) || []; - entries.push(entry); - this.changelogHistory.set(pluginId, entries); - } - - getChangelogHistory(pluginId: string): ChangelogEntry[] { - return this.changelogHistory.get(pluginId) || []; - } - - // ─── GitHub Actions Workflow Generation ──────────────────────────────────── - - /** - * Generate GitHub Actions workflow file for automated publishing. - */ - generateWorkflow(pluginId: string, config: PublishConfig): string { - const trigger = config.trigger === "tag" ? "on:\n push:\n tags:\n - 'v*'" : - config.trigger === "release" ? "on:\n release:\n types: [published]" : - "on:\n workflow_dispatch:"; - - const validateBuild = config.validateBuild ? "- run: npm run build\n" : ""; - const validateTests = config.validateTests ? "- run: npm test\n" : ""; - - return `name: Publish Plugin - -${trigger} - -jobs: - publish: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - ${validateBuild}${validateTests}- run: npm publish -`; - } - - // ─── Pre/Post Publish Hooks ─────────────────────────────────────────────── - - /** - * Execute pre-publish script if configured. - */ - executePrePublishScript(pluginId: string, version: string): string[] { - const config = this.publishConfig.get(pluginId); - if (!config?.prePublishScript) return []; - - // Simulate script execution - return [ - `Running pre-publish script for ${pluginId}@${version}`, - "✓ Pre-publish validation passed", - ]; - } - - /** - * Execute post-publish script if configured. - */ - executePostPublishScript(pluginId: string, version: string): string[] { - const config = this.publishConfig.get(pluginId); - if (!config?.postPublishScript) return []; - - // Simulate script execution - return [ - `Running post-publish script for ${pluginId}@${version}`, - "✓ Post-publish cleanup completed", - ]; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getPublishPlansCache(): Map { - return this.publishPlans; - } - - getExecutionsCache(): Map { - return this.executions; - } - - getGitHubReleasesCache(): Map { - return this.githubReleases; - } -} diff --git a/src/compression-manager.test.ts b/src/compression-manager.test.ts deleted file mode 100644 index 5d3680ad..00000000 --- a/src/compression-manager.test.ts +++ /dev/null @@ -1,300 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { CompressionManager, type CompressionConfig } from "./compression-manager.js"; - -describe("CompressionManager", () => { - describe("compression", () => { - let manager: CompressionManager; - - beforeEach(() => { - manager = new CompressionManager(); - }); - - it("compresses data", () => { - const data = "x".repeat(10000); - const { metrics } = manager.compress(data); - assert(metrics.compressedSize < metrics.originalSize); - }); - - it("returns metrics for compression", () => { - const data = "x".repeat(10000); - const { metrics } = manager.compress(data); - assert(metrics.algorithm); - assert(metrics.originalSize > 0); - assert(metrics.ratio >= 0); - }); - - it("skips compression for small data", () => { - const data = "small"; - const { metrics } = manager.compress(data); - assert.equal(metrics.algorithm, "none"); - assert.equal(metrics.originalSize, metrics.compressedSize); - }); - - it("decompresses data", () => { - const original = "test data"; - const { compressed } = manager.compress(original); - const decompressed = manager.decompress(compressed); - assert(decompressed.includes("test")); - }); - - it("determines if compression should occur", () => { - const largeJson = JSON.stringify({ data: "x".repeat(5000) }); - const shouldCompress = manager.shouldCompress("application/json", largeJson.length); - assert(shouldCompress); - }); - - it("skips compression for unsupported mime types", () => { - const shouldCompress = manager.shouldCompress( - "image/jpeg", - 100000, - ); - assert(!shouldCompress); - }); - - it("skips compression for small responses", () => { - const shouldCompress = manager.shouldCompress("application/json", 100); - assert(!shouldCompress); - }); - }); - - describe("configuration", () => { - let manager: CompressionManager; - - beforeEach(() => { - manager = new CompressionManager(); - }); - - it("sets compression algorithm", () => { - manager.setAlgorithm("brotli"); - const config = manager.getConfig(); - assert.equal(config.algorithm, "brotli"); - }); - - it("sets compression level", () => { - manager.setCompressionLevel(9); - const config = manager.getConfig(); - assert.equal(config.level, 9); - }); - - it("clamps compression level to valid range", () => { - manager.setCompressionLevel(20); - const config = manager.getConfig(); - assert.equal(config.level, 11); - - manager.setCompressionLevel(0); - const config2 = manager.getConfig(); - assert.equal(config2.level, 1); - }); - - it("sets minimum size threshold", () => { - manager.setMinimumSize(2048); - const config = manager.getConfig(); - assert.equal(config.minSize, 2048); - }); - - it("adds mime type", () => { - manager.addMimeType("application/custom"); - const config = manager.getConfig(); - assert(config.mimeTypes.includes("application/custom")); - }); - - it("removes mime type", () => { - const config = manager.getConfig(); - const initialCount = config.mimeTypes.length; - manager.removeMimeType("text/css"); - const newConfig = manager.getConfig(); - assert.equal(newConfig.mimeTypes.length, initialCount - 1); - }); - - it("uses custom configuration", () => { - const customConfig: Partial = { - algorithm: "brotli", - level: 8, - minSize: 2048, - }; - const customManager = new CompressionManager(customConfig); - const config = customManager.getConfig(); - assert.equal(config.algorithm, "brotli"); - assert.equal(config.level, 8); - assert.equal(config.minSize, 2048); - }); - }); - - describe("caching", () => { - let manager: CompressionManager; - - beforeEach(() => { - manager = new CompressionManager(); - }); - - it("caches compressed response", () => { - const data = "test data"; - manager.cacheCompressed("key1", data); - const cached = manager.getCached("key1"); - assert(cached); - }); - - it("retrieves cached data", () => { - const data = "cached content"; - manager.cacheCompressed("key1", data); - const retrieved = manager.getCached("key1"); - assert.equal(retrieved, data); - }); - - it("returns null for uncached key", () => { - const cached = manager.getCached("unknown"); - assert.equal(cached, null); - }); - - it("validates cache with hash", () => { - const data = "test data"; - manager.cacheCompressed("key1", data); - const isValid = manager.isCacheValid("key1", data); - assert(isValid); - }); - - it("invalidates cache when data changes", () => { - manager.cacheCompressed("key1", "original data"); - const isValid = manager.isCacheValid("key1", "modified data"); - assert(!isValid); - }); - - it("clears compression cache", () => { - manager.cacheCompressed("key1", "data1"); - manager.cacheCompressed("key2", "data2"); - manager.clearCache(); - assert.equal(manager.getCached("key1"), null); - assert.equal(manager.getCached("key2"), null); - }); - }); - - describe("statistics", () => { - let manager: CompressionManager; - - beforeEach(() => { - manager = new CompressionManager(); - }); - - it("returns compression metrics", () => { - const data = "x".repeat(10000); - manager.compress(data); - const metrics = manager.getMetrics(); - assert(metrics.totalCompressions > 0); - assert(metrics.averageRatio >= 0); - }); - - it("calculates total sizes", () => { - const data1 = "x".repeat(5000); - const data2 = "y".repeat(8000); - manager.compress(data1); - manager.compress(data2); - const metrics = manager.getMetrics(); - assert(metrics.totalOriginalSize > 0); - assert(metrics.totalCompressedSize > 0); - }); - - it("calculates average compression ratio", () => { - const data = "x".repeat(10000); - manager.compress(data); - const metrics = manager.getMetrics(); - assert(metrics.averageRatio > 0); - assert(metrics.averageRatio <= 100); - }); - - it("calculates average compression time", () => { - const data = "x".repeat(10000); - manager.compress(data); - const metrics = manager.getMetrics(); - assert(metrics.averageTime >= 0); - }); - - it("tracks metrics by algorithm", () => { - const data = "x".repeat(10000); - manager.setAlgorithm("gzip"); - manager.compress(data); - const metrics = manager.getMetrics(); - assert(metrics.byAlgorithm.gzip.count > 0); - }); - - it("gets all metrics", () => { - manager.compress("x".repeat(10000)); - manager.compress("y".repeat(5000)); - const metrics = manager.getAllMetrics(); - assert(metrics.length >= 2); - }); - - it("clears metrics", () => { - manager.compress("x".repeat(10000)); - manager.clearMetrics(); - const metrics = manager.getMetrics(); - assert.equal(metrics.totalCompressions, 0); - }); - }); - - describe("algorithm selection", () => { - it("uses gzip by default", () => { - const manager = new CompressionManager(); - const config = manager.getConfig(); - assert.equal(config.algorithm, "gzip"); - }); - - it("supports brotli compression", () => { - const manager = new CompressionManager({ algorithm: "brotli" }); - const config = manager.getConfig(); - assert.equal(config.algorithm, "brotli"); - }); - - it("supports deflate compression", () => { - const manager = new CompressionManager({ algorithm: "deflate" }); - const config = manager.getConfig(); - assert.equal(config.algorithm, "deflate"); - }); - - it("supports no compression", () => { - const manager = new CompressionManager({ algorithm: "none" }); - const data = "x".repeat(10000); - const { metrics } = manager.compress(data); - assert.equal(metrics.algorithm, "none"); - }); - }); - - describe("mime type handling", () => { - let manager: CompressionManager; - - beforeEach(() => { - manager = new CompressionManager(); - }); - - it("compresses JSON responses", () => { - const data = JSON.stringify({ data: "x".repeat(5000) }); - const shouldCompress = manager.shouldCompress("application/json", data.length); - assert(shouldCompress); - }); - - it("compresses HTML responses", () => { - const html = "" + "x".repeat(5000) + ""; - const shouldCompress = manager.shouldCompress("text/html", html.length); - assert(shouldCompress); - }); - - it("compresses JavaScript responses", () => { - const js = "const x = " + '"value"'.repeat(5000); - const shouldCompress = manager.shouldCompress( - "application/javascript", - js.length, - ); - assert(shouldCompress); - }); - - it("does not compress image responses", () => { - const shouldCompress = manager.shouldCompress("image/png", 100000); - assert(!shouldCompress); - }); - - it("does not compress video responses", () => { - const shouldCompress = manager.shouldCompress("video/mp4", 100000000); - assert(!shouldCompress); - }); - }); -}); diff --git a/src/compression-manager.ts b/src/compression-manager.ts deleted file mode 100644 index 8ad94d80..00000000 --- a/src/compression-manager.ts +++ /dev/null @@ -1,314 +0,0 @@ -// ─── Types ──────────────────────────────────────────────────────────────────── - -export type CompressionAlgorithm = "gzip" | "brotli" | "deflate" | "none"; - -export interface CompressionConfig { - algorithm: CompressionAlgorithm; - level: number; // 1-11 for gzip, 0-11 for brotli - minSize: number; // minimum bytes before compression - mimeTypes: string[]; // mime types to compress -} - -export interface CompressionMetrics { - algorithm: CompressionAlgorithm; - originalSize: number; - compressedSize: number; - ratio: number; - compressionTime: number; -} - -// ─── CompressionManager ──────────────────────────────────────────────────── - -export class CompressionManager { - private config: CompressionConfig; - private metrics: CompressionMetrics[] = []; - private compressionCache: Map = new Map(); - - constructor(config: Partial = {}) { - this.config = { - algorithm: config.algorithm || "gzip", - level: config.level || 6, - minSize: config.minSize || 1024, - mimeTypes: config.mimeTypes || [ - "application/json", - "text/html", - "text/css", - "application/javascript", - "text/plain", - "application/xml", - ], - }; - } - - // ─── Compression ────────────────────────────────────────────────────────── - - /** - * Compress data. - */ - compress(data: string): { compressed: string; metrics: CompressionMetrics } { - const startTime = Date.now(); - const originalSize = Buffer.byteLength(data, "utf-8"); - - // Don't compress if too small - if (originalSize < this.config.minSize) { - return { - compressed: data, - metrics: { - algorithm: "none", - originalSize, - compressedSize: originalSize, - ratio: 0, - compressionTime: 0, - }, - }; - } - - // Simulate compression based on algorithm - const compressedSize = this.estimateCompressedSize(data, this.config.algorithm); - const compressionTime = Date.now() - startTime; - const ratio = ((originalSize - compressedSize) / originalSize) * 100; - - const metrics: CompressionMetrics = { - algorithm: this.config.algorithm, - originalSize, - compressedSize, - ratio: Math.round(ratio * 100) / 100, - compressionTime, - }; - - this.metrics.push(metrics); - - // Return base64-encoded data with metadata for decompression - const encoded = Buffer.from(data).toString("base64"); - const header = `[${this.config.algorithm}]`; - const compressed = header + encoded; - - return { compressed, metrics }; - } - - /** - * Decompress data. - */ - decompress(data: string): string { - // Simulate decompression - extract base64 part and decode - try { - // Check if data has algorithm header - const match = data.match(/^\[([^\]]+)\](.+)$/); - if (match) { - const base64Part = match[2]; - return Buffer.from(base64Part, "base64").toString("utf-8"); - } - // If it looks like base64, try to decode it - if (/^[A-Za-z0-9+/=]+$/.test(data)) { - return Buffer.from(data, "base64").toString("utf-8"); - } - // Otherwise, return as-is (uncompressed data) - return data; - } catch { - return data; - } - } - - /** - * Estimate compressed size based on algorithm. - */ - private estimateCompressedSize(data: string, algorithm: CompressionAlgorithm): number { - const size = Buffer.byteLength(data, "utf-8"); - - switch (algorithm) { - case "gzip": - // Gzip typically compresses text by 60-70% - return Math.round(size * (0.3 + (11 - this.config.level) * 0.005)); - case "brotli": - // Brotli is typically 5-15% better than gzip - return Math.round(size * (0.25 + (11 - this.config.level) * 0.004)); - case "deflate": - // Deflate is similar to gzip but slightly less efficient - return Math.round(size * (0.35 + (11 - this.config.level) * 0.005)); - case "none": - default: - return size; - } - } - - /** - * Should compress response based on mime type and size. - */ - shouldCompress(mimeType: string, size: number): boolean { - return ( - size >= this.config.minSize && - this.config.mimeTypes.some((mt) => mimeType.includes(mt)) - ); - } - - // ─── Configuration ──────────────────────────────────────────────────────── - - /** - * Set compression algorithm. - */ - setAlgorithm(algorithm: CompressionAlgorithm): void { - this.config.algorithm = algorithm; - } - - /** - * Set compression level. - */ - setCompressionLevel(level: number): void { - this.config.level = Math.max(1, Math.min(11, level)); - } - - /** - * Set minimum size threshold. - */ - setMinimumSize(bytes: number): void { - this.config.minSize = bytes; - } - - /** - * Add mime type to compression list. - */ - addMimeType(mimeType: string): void { - if (!this.config.mimeTypes.includes(mimeType)) { - this.config.mimeTypes.push(mimeType); - } - } - - /** - * Remove mime type from compression list. - */ - removeMimeType(mimeType: string): void { - this.config.mimeTypes = this.config.mimeTypes.filter((mt) => mt !== mimeType); - } - - /** - * Get current configuration. - */ - getConfig(): CompressionConfig { - return { ...this.config }; - } - - // ─── Caching ────────────────────────────────────────────────────────────── - - /** - * Cache compressed response. - */ - cacheCompressed(key: string, data: string): void { - const hash = this.calculateHash(data); - this.compressionCache.set(key, { data, hash }); - } - - /** - * Get cached compressed data. - */ - getCached(key: string): string | null { - return this.compressionCache.get(key)?.data || null; - } - - /** - * Check if cache is valid for data. - */ - isCacheValid(key: string, data: string): boolean { - const cached = this.compressionCache.get(key); - if (!cached) return false; - - const currentHash = this.calculateHash(data); - return cached.hash === currentHash; - } - - /** - * Clear compression cache. - */ - clearCache(): void { - this.compressionCache.clear(); - } - - private calculateHash(data: string): string { - // Simple hash function (in production, use crypto.createHash) - let hash = 0; - for (let i = 0; i < data.length; i++) { - const char = data.charCodeAt(i); - hash = (hash << 5) - hash + char; - hash = hash & hash; // Convert to 32bit integer - } - return hash.toString(); - } - - // ─── Statistics ──────────────────────────────────────────────────────────── - - /** - * Get compression statistics. - */ - getMetrics(): { - totalCompressions: number; - totalOriginalSize: number; - totalCompressedSize: number; - averageRatio: number; - averageTime: number; - byAlgorithm: Record; - } { - let totalOriginal = 0; - let totalCompressed = 0; - let totalTime = 0; - const byAlgorithm: Record = { - gzip: { count: 0, ratio: 0 }, - brotli: { count: 0, ratio: 0 }, - deflate: { count: 0, ratio: 0 }, - none: { count: 0, ratio: 0 }, - }; - - for (const metric of this.metrics) { - totalOriginal += metric.originalSize; - totalCompressed += metric.compressedSize; - totalTime += metric.compressionTime; - - byAlgorithm[metric.algorithm].count++; - byAlgorithm[metric.algorithm].ratio += metric.ratio; - } - - // Calculate averages - const count = this.metrics.length; - const avgRatio = count > 0 ? totalOriginal > 0 ? ((totalOriginal - totalCompressed) / totalOriginal) * 100 : 0 : 0; - const avgTime = count > 0 ? totalTime / count : 0; - - // Calculate per-algorithm averages - for (const algo in byAlgorithm) { - const algoData = byAlgorithm[algo as CompressionAlgorithm]; - if (algoData.count > 0) { - algoData.ratio = Math.round((algoData.ratio / algoData.count) * 100) / 100; - } - } - - return { - totalCompressions: count, - totalOriginalSize: totalOriginal, - totalCompressedSize: totalCompressed, - averageRatio: Math.round(avgRatio * 100) / 100, - averageTime: Math.round(avgTime * 100) / 100, - byAlgorithm, - }; - } - - /** - * Get compression metrics. - */ - getAllMetrics(): CompressionMetrics[] { - return [...this.metrics]; - } - - /** - * Clear metrics. - */ - clearMetrics(): void { - this.metrics = []; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getCompressionCache(): Map { - return this.compressionCache; - } - - getMetricsCache(): CompressionMetrics[] { - return this.metrics; - } -} diff --git a/src/datadog-adapter.test.ts b/src/datadog-adapter.test.ts deleted file mode 100644 index 294cbbae..00000000 --- a/src/datadog-adapter.test.ts +++ /dev/null @@ -1,592 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { DatadogAdapter, createDatadogAdapter } from "./datadog-adapter.js"; - -describe("DatadogAdapter", () => { - describe("initialization", () => { - it("creates adapter with config", () => { - const adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - - assert.equal(adapter.name, "datadog"); - assert.equal(adapter.version, "1.0.0"); - }); - - it("initializes with disabled config", () => { - const adapter = new DatadogAdapter({ enabled: false }); - assert(!adapter.isConnected()); - }); - - it("creates adapter with default config", () => { - const adapter = new DatadogAdapter(); - assert(!adapter.isConnected()); - }); - }); - - describe("connection management", () => { - let adapter: DatadogAdapter; - - beforeEach(() => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - }); - - it("connects with valid API key", async () => { - await adapter.connect(); - assert(adapter.isConnected()); - }); - - it("throws error when enabled without API key", async () => { - const invalidAdapter = new DatadogAdapter({ enabled: true }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("API Key is required")); - } - }); - - it("throws error with invalid API key format", async () => { - const invalidAdapter = new DatadogAdapter({ - enabled: true, - apiKey: "invalid-key", - }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid Datadog API Key")); - } - }); - - it("disconnects cleanly", async () => { - await adapter.connect(); - assert(adapter.isConnected()); - - await adapter.disconnect(); - assert(!adapter.isConnected()); - }); - - it("skips connection when disabled", async () => { - const disabledAdapter = new DatadogAdapter({ - enabled: false, - apiKey: "abcdef0123456789abcdef0123456789", - }); - - await disabledAdapter.connect(); - assert(!disabledAdapter.isConnected()); - }); - }); - - describe("health monitoring", () => { - let adapter: DatadogAdapter; - - beforeEach(async () => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - await adapter.connect(); - }); - - it("reports healthy status when connected", async () => { - const health = await adapter.getHealth(); - - assert.equal(health.status, "healthy"); - assert(health.lastCheck); - assert(health.responseTime >= 0); - assert.equal(health.errorCount, 0); - }); - - it("records response time", async () => { - const health = await adapter.getHealth(); - assert(typeof health.responseTime === "number"); - }); - - it("updates lastCheck timestamp", async () => { - const before = new Date(); - const health = await adapter.getHealth(); - const after = new Date(); - - const lastCheck = new Date(health.lastCheck); - - assert(lastCheck >= before); - assert(lastCheck <= after); - }); - }); - - describe("metric recording", () => { - let adapter: DatadogAdapter; - - beforeEach(async () => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - await adapter.connect(); - }); - - it("records metric value", async () => { - const result = await adapter.recordMetric("request.latency", 150); - - assert.equal(result, true); - }); - - it("records metric with tags", async () => { - const result = await adapter.recordMetric("cache.hits", 42, { - cache_type: "redis", - region: "us-east-1", - }); - - assert.equal(result, true); - }); - - it("increments metric counter", async () => { - const result = await adapter.incrementMetric("api.requests", 1); - - assert.equal(result, true); - }); - - it("increments by custom amount", async () => { - const result = await adapter.incrementMetric("batch.processed", 50); - - assert.equal(result, true); - }); - - it("defaults to increment of 1", async () => { - const result = await adapter.incrementMetric("counter"); - - assert.equal(result, true); - }); - - it("gets metric value", async () => { - await adapter.incrementMetric("test.metric", 5); - - const value = adapter.getMetric("test.metric"); - assert.equal(value, 5); - }); - - it("returns undefined for non-existent metric", () => { - const value = adapter.getMetric("nonexistent"); - - assert.equal(value, undefined); - }); - - it("fails to record when disconnected", async () => { - await adapter.disconnect(); - - const result = await adapter.recordMetric("offline.metric", 100); - - assert.equal(result, false); - }); - }); - - describe("trace spans", () => { - let adapter: DatadogAdapter; - - beforeEach(async () => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - await adapter.connect(); - }); - - it("starts a trace span", async () => { - const spanId = await adapter.startSpan("trace-123", "database-query"); - - assert(spanId); - assert(spanId.includes("trace-123")); - }); - - it("starts span with parent", async () => { - const spanId = await adapter.startSpan("trace-456", "nested-operation", "parent-span-789"); - - assert(spanId); - }); - - it("ends span with success", async () => { - const spanId = await adapter.startSpan("trace-789", "operation"); - await adapter.endSpan(spanId, "ok"); - - assert(true); - }); - - it("ends span with error", async () => { - const spanId = await adapter.startSpan("trace-error", "failed-op"); - await adapter.endSpan(spanId, "error"); - - assert(true); - }); - - it("defaults to ok status", async () => { - const spanId = await adapter.startSpan("trace-default", "op"); - await adapter.endSpan(spanId); - - assert(true); - }); - - it("tracks span duration", async () => { - const spanId = await adapter.startSpan("trace-timing", "slow-op"); - await new Promise((resolve) => setTimeout(resolve, 10)); - await adapter.endSpan(spanId); - - assert(true); - }); - }); - - describe("logging", () => { - let adapter: DatadogAdapter; - - beforeEach(async () => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - await adapter.connect(); - }); - - it("logs info message", async () => { - const result = await adapter.logEvent("Application started"); - - assert.equal(result, true); - }); - - it("logs with debug level", async () => { - const result = await adapter.logEvent("Debug info", "debug"); - - assert.equal(result, true); - }); - - it("logs with info level", async () => { - const result = await adapter.logEvent("Information", "info"); - - assert.equal(result, true); - }); - - it("logs with warning level", async () => { - const result = await adapter.logEvent("Warning message", "warning"); - - assert.equal(result, true); - }); - - it("logs with error level", async () => { - const result = await adapter.logEvent("Error occurred", "error"); - - assert.equal(result, true); - }); - - it("logs with metadata", async () => { - const result = await adapter.logEvent("Database operation", "info", { - duration: 250, - query: "SELECT * FROM users", - rows: 1000, - }); - - assert.equal(result, true); - }); - - it("defaults to info level", async () => { - const result = await adapter.logEvent("Default level message"); - - assert.equal(result, true); - }); - - it("fails when disconnected", async () => { - await adapter.disconnect(); - - const result = await adapter.logEvent("Offline log"); - - assert.equal(result, false); - }); - }); - - describe("events", () => { - let adapter: DatadogAdapter; - - beforeEach(async () => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - await adapter.connect(); - }); - - it("records event", async () => { - const result = await adapter.recordEvent( - "Deployment Started", - "Version 1.2.3 deployed to production", - ); - - assert.equal(result, true); - }); - - it("records event with tags", async () => { - const result = await adapter.recordEvent( - "Database Migration", - "Schema updated", - { - service: "api", - environment: "production", - }, - ); - - assert.equal(result, true); - }); - - it("records event with low severity", async () => { - const result = await adapter.recordEvent("Minor Issue", "Non-critical alert", {}, "low"); - - assert.equal(result, true); - }); - - it("records event with medium severity", async () => { - const result = await adapter.recordEvent( - "Medium Alert", - "Moderate issue detected", - {}, - "medium", - ); - - assert.equal(result, true); - }); - - it("records event with high severity", async () => { - const result = await adapter.recordEvent("High Priority", "Critical issue", {}, "high"); - - assert.equal(result, true); - }); - - it("records event with critical severity", async () => { - const result = await adapter.recordEvent( - "Critical Issue", - "System failure", - {}, - "critical", - ); - - assert.equal(result, true); - }); - - it("defaults to medium severity", async () => { - const result = await adapter.recordEvent("Default Severity", "No severity specified"); - - assert.equal(result, true); - }); - - it("fails when disconnected", async () => { - await adapter.disconnect(); - - const result = await adapter.recordEvent("Offline Event", "Cannot send"); - - assert.equal(result, false); - }); - }); - - describe("site info", () => { - let adapter: DatadogAdapter; - - beforeEach(() => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - endpoint: "datadoghq.eu", - }); - }); - - it("returns API key", () => { - const info = adapter.getSiteInfo(); - - assert(info.apiKey.includes("abcdef")); - }); - - it("returns site", () => { - const info = adapter.getSiteInfo(); - - assert.equal(info.site, "datadoghq.eu"); - }); - - it("defaults to datadoghq.com site", () => { - const noSiteAdapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - - const info = noSiteAdapter.getSiteInfo(); - assert.equal(info.site, "datadoghq.com"); - }); - - it("counts metrics", async () => { - await adapter.connect(); - await adapter.recordMetric("test.metric", 100); - - const info = adapter.getSiteInfo(); - assert.equal(info.metricsCount, 1); - }); - - it("counts traces", async () => { - await adapter.connect(); - await adapter.startSpan("trace-1", "op"); - - const info = adapter.getSiteInfo(); - assert(info.tracesCount > 0); - }); - - it("clears metrics on disconnect", async () => { - await adapter.connect(); - await adapter.recordMetric("metric1", 100); - assert.equal(adapter.getSiteInfo().metricsCount, 1); - - await adapter.disconnect(); - assert.equal(adapter.getSiteInfo().metricsCount, 0); - }); - }); - - describe("event validation", () => { - let adapter: DatadogAdapter; - - beforeEach(async () => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - await adapter.connect(); - }); - - it("requires event type", async () => { - try { - await (adapter as any).sendEvent({ - data: { message: "test" }, - timestamp: new Date().toISOString(), - }); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid event")); - } - }); - - it("requires event data", async () => { - try { - await (adapter as any).sendEvent({ - type: "metric", - timestamp: new Date().toISOString(), - }); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid event")); - } - }); - }); - - describe("queue flushing", () => { - let adapter: DatadogAdapter; - - beforeEach(() => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - }); - - it("flushes queued events on connection", async () => { - await adapter.recordMetric("queued.metric", 100); - await adapter.recordMetric("queued.metric2", 200); - - await adapter.connect(); - - assert(adapter.isConnected()); - }); - - it("handles empty queue gracefully", async () => { - await adapter.connect(); - - assert(true); - }); - }); - - describe("error simulation", () => { - let adapter: DatadogAdapter; - - beforeEach(async () => { - adapter = new DatadogAdapter({ - enabled: true, - apiKey: "abcdef0123456789abcdef0123456789", - }); - await adapter.connect(); - }); - - it("sometimes fails to send", async () => { - let failures = 0; - const attempts = 100; - - for (let i = 0; i < attempts; i++) { - const result = await adapter.recordMetric("stress-test", i); - if (!result) { - failures++; - } - } - - assert(failures >= 0); - }); - }); - - describe("factory function", () => { - it("creates enabled adapter with DATADOG_API_KEY", () => { - const originalKey = process.env.DATADOG_API_KEY; - const originalSite = process.env.DATADOG_SITE; - - try { - process.env.DATADOG_API_KEY = "abcdef0123456789abcdef0123456789"; - process.env.DATADOG_SITE = "datadoghq.eu"; - - const adapter = createDatadogAdapter(true); - - assert(adapter.config.enabled); - assert(adapter.config.apiKey); - } finally { - process.env.DATADOG_API_KEY = originalKey; - process.env.DATADOG_SITE = originalSite; - } - }); - - it("creates disabled adapter without API key", () => { - const originalKey = process.env.DATADOG_API_KEY; - - try { - delete process.env.DATADOG_API_KEY; - - const adapter = createDatadogAdapter(true); - - assert(!adapter.config.enabled); - } finally { - process.env.DATADOG_API_KEY = originalKey; - } - }); - - it("respects enabled parameter", () => { - const adapter = createDatadogAdapter(false); - - assert(!adapter.config.enabled); - }); - - it("defaults to enabled", () => { - const originalKey = process.env.DATADOG_API_KEY; - - try { - process.env.DATADOG_API_KEY = "abcdef0123456789abcdef0123456789"; - - const adapter = createDatadogAdapter(); - - assert(adapter.config.enabled); - } finally { - process.env.DATADOG_API_KEY = originalKey; - } - }); - }); -}); diff --git a/src/datadog-adapter.ts b/src/datadog-adapter.ts deleted file mode 100644 index 7394e735..00000000 --- a/src/datadog-adapter.ts +++ /dev/null @@ -1,314 +0,0 @@ -import { IdGenerators } from "./id-generator.js"; -// ─── Datadog APM & Analytics Adapter ────────────────────────────────────── - -import { - AbstractServiceAdapter, - type ServiceConfig, - type ServiceEvent, - type ServiceHealth, -} from "./service-adapter.js"; - -/** - * Datadog adapter for APM, metrics, and analytics. - */ -export class DatadogAdapter extends AbstractServiceAdapter { - private lastHealthCheck: string = new Date().toISOString(); - private healthCheckErrors: number = 0; - private metrics: Map = new Map(); - private traces: Map = new Map(); - - constructor(config: ServiceConfig = { enabled: false }) { - super("datadog", "1.0.0", config); - } - - async connect(): Promise { - if (!this.config.enabled) { - this.connected = false; - return; - } - - if (!this.config.apiKey) { - throw new Error("Datadog API Key is required"); - } - - // Validate API key format (should be alphanumeric) - if (!this.config.apiKey.match(/^[a-f0-9]{32}$/i)) { - throw new Error("Invalid Datadog API Key format"); - } - - // Simulate connection test - await new Promise((resolve) => setTimeout(resolve, 50)); - - this.connected = true; - - // Flush queued events - await this.flushQueue(); - } - - async disconnect(): Promise { - if (this.healthCheckInterval) { - clearInterval(this.healthCheckInterval); - this.healthCheckInterval = null; - } - this.metrics.clear(); - this.traces.clear(); - this.connected = false; - } - - async getHealth(): Promise { - const responseTime = Math.random() * 50; - - try { - if (!this.connected) { - this.healthCheckErrors++; - } - - this.lastHealthCheck = new Date().toISOString(); - - const status = - this.healthCheckErrors < 3 - ? this.connected - ? "healthy" - : "degraded" - : "unhealthy"; - - return { - status, - lastCheck: this.lastHealthCheck, - responseTime: Math.round(responseTime), - errorCount: this.healthCheckErrors, - }; - } catch { - this.healthCheckErrors++; - return { - status: "unhealthy", - lastCheck: new Date().toISOString(), - responseTime: -1, - errorCount: this.healthCheckErrors, - }; - } - } - - protected async sendEvent(event: ServiceEvent): Promise { - if (!this.connected) { - throw new Error("Not connected to Datadog"); - } - - // Validate event - if (!event.type || !event.data) { - throw new Error("Invalid event format"); - } - - // Simulate sending to Datadog (fixed delay to avoid flaky tests) - await new Promise((resolve) => setTimeout(resolve, 5)); - - // Simulate occasional failures (disabled in test — use explicit error injection instead) - // if (Math.random() < 0.01) { - // throw new Error("Simulated Datadog API error"); - // } - } - - /** - * Record a metric value. - */ - async recordMetric( - name: string, - value: number, - tags?: Record, - ): Promise { - this.metrics.set(name, value); - - const event: ServiceEvent = { - type: "metric", - data: { - name, - value, - tags, - timestamp: Date.now(), - }, - timestamp: new Date().toISOString(), - }; - - return this.send(event); - } - - /** - * Increment a metric counter. - */ - async incrementMetric(name: string, increment: number = 1): Promise { - const current = this.metrics.get(name) || 0; - this.metrics.set(name, current + increment); - - return this.recordMetric(name, current + increment); - } - - /** - * Get current metric value. - */ - getMetric(name: string): number | undefined { - return this.metrics.get(name); - } - - /** - * Start a trace span. - */ - async startSpan( - traceId: string, - spanName: string, - parentSpanId?: string, - ): Promise { - const spanId = `${traceId}-${IdGenerators.span().slice(-12)}`; - - this.traces.set(spanId, { - startTime: Date.now(), - status: "active", - }); - - const event: ServiceEvent = { - type: "trace", - data: { - traceId, - spanId, - spanName, - parentSpanId, - startTime: Date.now(), - }, - timestamp: new Date().toISOString(), - tags: { - spanType: "span", - }, - }; - - await this.send(event); - return spanId; - } - - /** - * End a trace span. - */ - async endSpan(spanId: string, status: "ok" | "error" = "ok"): Promise { - const span = this.traces.get(spanId); - if (span) { - span.endTime = Date.now(); - span.status = status; - } - - const event: ServiceEvent = { - type: "trace", - data: { - spanId, - status, - endTime: Date.now(), - duration: span ? span.endTime! - span.startTime : 0, - }, - timestamp: new Date().toISOString(), - tags: { - spanType: "span-end", - }, - }; - - await this.send(event); - } - - /** - * Record a log event. - */ - async logEvent( - message: string, - level: "debug" | "info" | "warning" | "error" = "info", - metadata?: Record, - ): Promise { - const event: ServiceEvent = { - type: "log", - data: { - message, - level, - metadata, - }, - timestamp: new Date().toISOString(), - tags: { - level, - }, - }; - - return this.send(event); - } - - /** - * Record a custom event/incident. - */ - async recordEvent( - title: string, - text: string, - tags?: Record, - severity?: "low" | "medium" | "high" | "critical", - ): Promise { - const event: ServiceEvent = { - type: "event", - data: { - title, - text, - severity, - timestamp: Date.now(), - }, - timestamp: new Date().toISOString(), - tags: { - ...tags, - severity: severity || "medium", - }, - }; - - return this.send(event); - } - - /** - * Flush all queued events. - */ - private async flushQueue(): Promise { - const queued = this.getQueuedEvents(); - if (queued.length === 0) return; - - const { sent, failed } = await this.batch(queued); - - if (sent > 0) { - this.clearQueue(); - } - - console.log(`Flushed Datadog queue: ${sent} sent, ${failed} failed`); - } - - /** - * Get Datadog site configuration. - */ - getSiteInfo(): { - apiKey: string; - site?: string; - metricsCount: number; - tracesCount: number; - } { - return { - apiKey: this.config.apiKey || "", - site: this.config.endpoint || "datadoghq.com", - metricsCount: this.metrics.size, - tracesCount: this.traces.size, - }; - } -} - -/** - * Create a Datadog adapter from environment variables. - */ -export function createDatadogAdapter(enabled: boolean = true): DatadogAdapter { - const apiKey = process.env.DATADOG_API_KEY; - const site = process.env.DATADOG_SITE || "datadoghq.com"; - - if (enabled && !apiKey) { - console.warn("Datadog is enabled but DATADOG_API_KEY environment variable is not set"); - } - - return new DatadogAdapter({ - enabled: enabled && !!apiKey, - apiKey, - endpoint: site, - }); -} diff --git a/src/documentation-generator.test.ts b/src/documentation-generator.test.ts deleted file mode 100644 index c17d8584..00000000 --- a/src/documentation-generator.test.ts +++ /dev/null @@ -1,373 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { - DocumentationGenerator, - type APIDoc, - type Example, - type Tutorial, -} from "./documentation-generator.js"; - -// ─── Helpers ────────────────────────────────────────────────────────────────── - -function makeAPIDoc(endpoint: string, overrides: Partial = {}): APIDoc { - return { - endpoint, - method: "GET", - description: "API endpoint", - parameters: [], - response: { type: "object", example: {} }, - errors: [], - ...overrides, - }; -} - -function makeExample(id: string, overrides: Partial = {}): Example { - return { - id, - title: "Example Title", - description: "Example description", - language: "typescript", - code: "const x = 1;", - explanation: "This is an explanation", - tags: ["basic"], - difficulty: "beginner", - runnable: true, - ...overrides, - }; -} - -function makeTutorial(id: string, overrides: Partial = {}): Tutorial { - return { - id, - title: "Tutorial Title", - description: "Tutorial description", - steps: [ - { - title: "Step 1", - content: "Do this", - expectedOutcome: "You should see X", - }, - ], - estimatedTime: 30, - difficulty: "beginner", - prerequisites: [], - relatedDocs: [], - ...overrides, - }; -} - -// ─── Tests ──────────────────────────────────────────────────────────────────── - -describe("DocumentationGenerator", () => { - describe("initialization", () => { - it("creates generator instance", () => { - const gen = new DocumentationGenerator(); - assert(gen); - }); - - it("starts with empty caches", () => { - const gen = new DocumentationGenerator(); - assert.equal(gen.getPagesCache().size, 0); - assert.equal(gen.getExamplesCache().size, 0); - assert.equal(gen.getTutorialsCache().size, 0); - assert.equal(gen.getAPIDocsCache().size, 0); - }); - }); - - describe("page creation", () => { - let gen: DocumentationGenerator; - - beforeEach(() => { - gen = new DocumentationGenerator(); - }); - - it("creates a documentation page", () => { - const page = gen.createPage("Getting Started", "# Content", "guide", "author-1"); - assert(page.id); - assert.equal(page.title, "Getting Started"); - assert.equal(page.type, "guide"); - }); - - it("generates slug from title", () => { - const page = gen.createPage("Getting Started", "Content", "guide", "author-1"); - assert.equal(page.slug, "getting-started"); - }); - - it("generates table of contents", () => { - const content = "# Heading 1\n## Heading 2\n### Heading 3"; - const page = gen.createPage("Test", content, "guide", "author-1"); - assert(page.toc); - assert(page.toc.length === 3); - }); - - it("tracks page views", () => { - const created = gen.createPage("Test", "Content", "guide", "author-1"); - const page = gen.getPage(created.id); - assert.equal(page?.views, 1); - gen.getPage(created.id); - assert.equal(page?.views, 2); - }); - - it("updates a page", () => { - const created = gen.createPage("Test", "Content", "guide", "author-1"); - const updated = gen.updatePage(created.id, { content: "New content" }); - assert.equal(updated?.content, "New content"); - }); - - it("deletes a page", () => { - const created = gen.createPage("Test", "Content", "guide", "author-1"); - const deleted = gen.deletePage(created.id); - assert(deleted); - assert.equal(gen.getPage(created.id), null); - }); - - it("returns null for unknown page", () => { - const page = gen.getPage("unknown"); - assert.equal(page, null); - }); - }); - - describe("search & indexing", () => { - let gen: DocumentationGenerator; - - beforeEach(() => { - gen = new DocumentationGenerator(); - gen.createPage("Stripe Integration", "How to integrate Stripe payments", "guide", "author-1"); - gen.createPage("Payment Methods", "Supported payment methods", "api", "author-1"); - gen.createPage("Getting Started", "Start building", "guide", "author-1"); - }); - - it("searches by keyword", () => { - const results = gen.search("stripe"); - assert(results.length > 0); - assert(results.some((r) => r.page.title.includes("Stripe"))); - }); - - it("returns search results with snippets", () => { - const results = gen.search("payment"); - assert(results.every((r) => r.snippet.length > 0)); - }); - - it("ranks by relevance", () => { - const results = gen.search("payment"); - if (results.length > 1) { - assert(results[0].relevance >= results[1].relevance); - } - }); - - it("respects search limit", () => { - const results = gen.search("guide", 5); - assert(results.length <= 5); - }); - - it("returns empty for unknown search", () => { - const results = gen.search("nonexistent"); - assert.equal(results.length, 0); - }); - }); - - describe("API documentation", () => { - let gen: DocumentationGenerator; - - beforeEach(() => { - gen = new DocumentationGenerator(); - }); - - it("registers API doc", () => { - const doc = makeAPIDoc("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/api/plugins"); - gen.registerAPIDoc(doc); - assert.equal(gen.getAPIDoc("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/api/plugins"), doc); - }); - - it("returns null for unknown endpoint", () => { - const doc = gen.getAPIDoc("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/api/unknown"); - assert.equal(doc, null); - }); - - it("gets all API docs", () => { - gen.registerAPIDoc(makeAPIDoc("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/api/plugins")); - gen.registerAPIDoc(makeAPIDoc("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/api/authors")); - const all = gen.getAllAPIDocsIndex(); - assert.equal(all.length, 2); - }); - - it("generates OpenAPI spec", () => { - gen.registerAPIDoc(makeAPIDoc("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/api/plugins", { method: "GET" })); - const spec = gen.generateOpenAPISpec("3.0.0"); - assert.equal(spec.openapi, "3.0.0"); - assert(spec.paths); - }); - }); - - describe("examples", () => { - let gen: DocumentationGenerator; - - beforeEach(() => { - gen = new DocumentationGenerator(); - }); - - it("registers an example", () => { - const example = makeExample("ex-1"); - gen.registerExample(example); - assert.equal(gen.getExample("ex-1"), example); - }); - - it("gets examples by tag", () => { - gen.registerExample(makeExample("ex-1", { tags: ["api"] })); - gen.registerExample(makeExample("ex-2", { tags: ["api", "auth"] })); - gen.registerExample(makeExample("ex-3", { tags: ["database"] })); - - const apiExamples = gen.getExamplesByTag("api"); - assert.equal(apiExamples.length, 2); - }); - - it("gets examples by difficulty", () => { - gen.registerExample(makeExample("ex-1", { difficulty: "beginner" })); - gen.registerExample(makeExample("ex-2", { difficulty: "advanced" })); - - const beginner = gen.getExamplesByDifficulty("beginner"); - assert.equal(beginner.length, 1); - }); - }); - - describe("tutorials", () => { - let gen: DocumentationGenerator; - - beforeEach(() => { - gen = new DocumentationGenerator(); - }); - - it("registers a tutorial", () => { - const tutorial = makeTutorial("tut-1"); - gen.registerTutorial(tutorial); - assert.equal(gen.getTutorial("tut-1"), tutorial); - }); - - it("gets tutorials by difficulty", () => { - gen.registerTutorial(makeTutorial("tut-1", { difficulty: "beginner" })); - gen.registerTutorial(makeTutorial("tut-2", { difficulty: "advanced" })); - - const beginner = gen.getTutorialsByDifficulty("beginner"); - assert.equal(beginner.length, 1); - }); - - it("gets beginner tutorials", () => { - gen.registerTutorial(makeTutorial("tut-1", { difficulty: "beginner" })); - gen.registerTutorial(makeTutorial("tut-2", { difficulty: "advanced" })); - - const beginner = gen.getBeginnerTutorials(); - assert.equal(beginner.length, 1); - }); - }); - - describe("collections", () => { - let gen: DocumentationGenerator; - - beforeEach(() => { - gen = new DocumentationGenerator(); - }); - - it("creates a collection", () => { - const page = gen.createPage("Test", "Content", "guide", "author-1"); - const col = gen.createCollection("Getting Started", "Getting started docs", [page], 1); - assert.equal(col.category, "Getting Started"); - }); - - it("gets collection by category", () => { - const page = gen.createPage("Test", "Content", "guide", "author-1"); - gen.createCollection("API", "API docs", [page], 1); - const col = gen.getCollection("API"); - assert(col); - assert.equal(col.category, "API"); - }); - - it("gets all collections sorted by order", () => { - const p1 = gen.createPage("Page 1", "Content", "guide", "author-1"); - const p2 = gen.createPage("Page 2", "Content", "guide", "author-1"); - gen.createCollection("Z Category", "Docs", [p1], 3); - gen.createCollection("A Category", "Docs", [p2], 1); - - const cols = gen.getAllCollections(); - assert.equal(cols[0].category, "A Category"); - assert.equal(cols[1].category, "Z Category"); - }); - }); - - describe("export & generation", () => { - let gen: DocumentationGenerator; - - beforeEach(() => { - gen = new DocumentationGenerator(); - const p1 = gen.createPage("Guide 1", "# Content", "guide", "author-1"); - const p2 = gen.createPage("API Reference", "# API", "api", "author-1"); - gen.createCollection("Guides", "Guide docs", [p1], 1); - gen.createCollection("API", "API docs", [p2], 2); - }); - - it("generates site structure", () => { - const structure = gen.generateSiteStructure(); - assert(structure.collections); - assert(structure.collections.length > 0); - }); - - it("generates markdown dump", () => { - const dump = gen.generateMarkdownDump(); - assert(Object.keys(dump).length > 0); - assert(Object.keys(dump).some((k) => k.includes(".md"))); - }); - - it("generates navigation", () => { - const nav = gen.generateNavigation(); - assert(nav.length > 0); - assert(nav[0].items.length > 0); - }); - }); - - describe("statistics", () => { - let gen: DocumentationGenerator; - - beforeEach(() => { - gen = new DocumentationGenerator(); - }); - - it("returns documentation statistics", () => { - gen.createPage("Page 1", "Content", "guide", "author-1"); - gen.createPage("Page 2", "Content", "api", "author-1"); - gen.registerExample(makeExample("ex-1")); - gen.registerTutorial(makeTutorial("tut-1")); - - const stats = gen.getStats(); - assert.equal(stats.totalPages, 2); - assert.equal(stats.totalExamples, 1); - assert.equal(stats.totalTutorials, 1); - }); - - it("counts pages by type", () => { - gen.createPage("Guide", "Content", "guide", "author-1"); - gen.createPage("API", "Content", "api", "author-1"); - gen.createPage("Tutorial", "Content", "tutorial", "author-1"); - - const stats = gen.getStats(); - assert.equal(stats.byType.guide, 1); - assert.equal(stats.byType.api, 1); - assert.equal(stats.byType.tutorial, 1); - }); - - it("calculates average page length", () => { - gen.createPage("Short", "Hi", "guide", "author-1"); - gen.createPage("Long", "This is a longer content string", "guide", "author-1"); - - const stats = gen.getStats(); - assert(stats.avgPageLength > 0); - }); - - it("tracks total views", () => { - const p1 = gen.createPage("Page", "Content", "guide", "author-1"); - gen.getPage(p1.id); - gen.getPage(p1.id); - - const stats = gen.getStats(); - assert.equal(stats.totalViews, 2); - }); - }); -}); diff --git a/src/documentation-generator.ts b/src/documentation-generator.ts deleted file mode 100644 index 9ccacbdb..00000000 --- a/src/documentation-generator.ts +++ /dev/null @@ -1,519 +0,0 @@ -import { IdGenerators } from "./id-generator.js"; -// ─── Types ──────────────────────────────────────────────────────────────────── - -export type DocType = "guide" | "api" | "example" | "tutorial" | "troubleshooting" | "architecture"; -export type DocFormat = "markdown" | "html" | "pdf"; - -export interface DocPage { - id: string; - title: string; - slug: string; - type: DocType; - content: string; - format: DocFormat; - author: string; - createdAt: string; - updatedAt: string; - views: number; - tags: string[]; - relatedPages: string[]; - toc?: TableOfContents[]; -} - -export interface TableOfContents { - level: number; - title: string; - id: string; -} - -export interface APIDoc { - endpoint: string; - method: "GET" | "POST" | "PATCH" | "DELETE" | "PUT"; - description: string; - parameters: Array<{ - name: string; - type: string; - required: boolean; - description: string; - }>; - response: { - type: string; - example: Record; - }; - errors: Array<{ - code: number; - message: string; - }>; -} - -export interface Example { - id: string; - title: string; - description: string; - language: "typescript" | "javascript" | "python" | "bash"; - code: string; - explanation: string; - tags: string[]; - difficulty: "beginner" | "intermediate" | "advanced"; - runnable: boolean; -} - -export interface Tutorial { - id: string; - title: string; - description: string; - steps: Array<{ - title: string; - content: string; - code?: string; - expectedOutcome: string; - }>; - estimatedTime: number; // minutes - difficulty: "beginner" | "intermediate" | "advanced"; - prerequisites: string[]; - relatedDocs: string[]; -} - -export interface DocSearchResult { - page: DocPage; - relevance: number; - snippet: string; -} - -export interface DocCollection { - category: string; - pages: DocPage[]; - description: string; - order: number; -} - -// ─── DocumentationGenerator ─────────────────────────────────────────────────── - -export class DocumentationGenerator { - private pages: Map = new Map(); - private apiDocs: Map = new Map(); - private examples: Map = new Map(); - private tutorials: Map = new Map(); - private collections: Map = new Map(); - private searchIndex: Map> = new Map(); // term → pageIds - - // ─── Page Management ────────────────────────────────────────────────────── - - /** - * Create a documentation page. - */ - createPage( - title: string, - content: string, - type: DocType, - author: string, - tags: string[] = [], - ): DocPage { - const id = IdGenerators.documentation(); - const slug = title.toLowerCase().replace(/\s+/g, "-").replace(/[^\w-]/g, ""); - - const page: DocPage = { - id, - title, - slug, - type, - content, - format: "markdown", - author, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - views: 0, - tags, - relatedPages: [], - toc: this.generateTableOfContents(content), - }; - - this.pages.set(id, page); - this.indexPage(id, content); - return page; - } - - /** - * Get a page by ID. - */ - getPage(pageId: string): DocPage | null { - const page = this.pages.get(pageId); - if (page) { - page.views++; - } - return page || null; - } - - /** - * Update a page. - */ - updatePage(pageId: string, updates: Partial): DocPage | null { - const page = this.pages.get(pageId); - if (!page) return null; - - Object.assign(page, updates, { updatedAt: new Date().toISOString() }); - return page; - } - - /** - * Delete a page. - */ - deletePage(pageId: string): boolean { - const page = this.pages.get(pageId); - if (!page) return false; - - // Remove from index - const terms = this.extractTerms(page.content); - for (const term of terms) { - this.searchIndex.get(term)?.delete(pageId); - } - - this.pages.delete(pageId); - return true; - } - - // ─── Table of Contents ──────────────────────────────────────────────────── - - /** - * Generate table of contents from markdown headings. - */ - private generateTableOfContents(content: string): TableOfContents[] { - const headings: TableOfContents[] = []; - const lines = content.split("\n"); - - lines.forEach((line) => { - const match = line.match(/^(#+)\s+(.+)$/); - if (match) { - const level = match[1].length; - const title = match[2]; - const id = title.toLowerCase().replace(/\s+/g, "-"); - - headings.push({ level, title, id }); - } - }); - - return headings; - } - - // ─── Search & Indexing ─────────────────────────────────────────────────── - - /** - * Index page content for full-text search. - */ - private indexPage(pageId: string, content: string): void { - const terms = this.extractTerms(content); - for (const term of terms) { - const pages = this.searchIndex.get(term) || new Set(); - pages.add(pageId); - this.searchIndex.set(term, pages); - } - } - - /** - * Extract searchable terms from content. - */ - private extractTerms(content: string): string[] { - return content - .toLowerCase() - .split(/\W+/) - .filter((term) => term.length > 2 && !this.isStopWord(term)); - } - - private isStopWord(word: string): boolean { - const stops = ["the", "and", "or", "is", "are", "was", "be", "to", "of", "in", "on", "at"]; - return stops.includes(word); - } - - /** - * Search documentation by keyword. - */ - search(query: string, limit = 20): DocSearchResult[] { - const terms = this.extractTerms(query); - const pageScores = new Map(); - - for (const term of terms) { - const pageIds = this.searchIndex.get(term) || new Set(); - for (const pageId of pageIds) { - pageScores.set(pageId, (pageScores.get(pageId) || 0) + 1); - } - } - - return [...pageScores.entries()] - .map(([pageId, score]) => { - const page = this.pages.get(pageId)!; - const snippet = this.extractSnippet(page.content, query, 150); - return { page, relevance: score, snippet }; - }) - .sort((a, b) => b.relevance - a.relevance) - .slice(0, limit); - } - - /** - * Extract snippet around query term. - */ - private extractSnippet(content: string, query: string, length: number): string { - const index = content.toLowerCase().indexOf(query.toLowerCase()); - if (index === -1) return content.substring(0, length) + "..."; - - const start = Math.max(0, index - length / 2); - const end = Math.min(content.length, start + length); - return (start > 0 ? "..." : "") + content.substring(start, end) + (end < content.length ? "..." : ""); - } - - // ─── API Documentation ─────────────────────────────────────────────────── - - /** - * Register API endpoint documentation. - */ - registerAPIDoc(doc: APIDoc): void { - this.apiDocs.set(doc.endpoint, doc); - } - - /** - * Get API documentation for an endpoint. - */ - getAPIDoc(endpoint: string): APIDoc | null { - return this.apiDocs.get(endpoint) || null; - } - - /** - * Get all API documentation. - */ - getAllAPIDocsIndex(): APIDoc[] { - return [...this.apiDocs.values()]; - } - - /** - * Generate OpenAPI spec from registered endpoints. - */ - generateOpenAPISpec(version: string = "3.0.0", baseUrl: string = "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/sandstream/kit"): Record { - const paths: Record = {}; - - for (const doc of this.apiDocs.values()) { - paths[doc.endpoint] = { - [doc.method.toLowerCase()]: { - summary: doc.description, - parameters: doc.parameters, - responses: { - 200: { - description: "Success", - content: { - "application/json": { - schema: doc.response, - }, - }, - }, - ...Object.fromEntries(doc.errors.map((e) => [e.code, { description: e.message }])), - }, - }, - }; - } - - return { - openapi: version, - info: { title: "kit Marketplace API", version }, - servers: [{ url: baseUrl }], - paths, - }; - } - - // ─── Examples ──────────────────────────────────────────────────────────── - - /** - * Register a code example. - */ - registerExample(example: Example): void { - this.examples.set(example.id, example); - } - - /** - * Get example by ID. - */ - getExample(exampleId: string): Example | null { - return this.examples.get(exampleId) || null; - } - - /** - * Get examples by tag. - */ - getExamplesByTag(tag: string): Example[] { - return [...this.examples.values()].filter((e) => e.tags.includes(tag)); - } - - /** - * Get examples by difficulty. - */ - getExamplesByDifficulty(difficulty: string): Example[] { - return [...this.examples.values()].filter((e) => e.difficulty === difficulty); - } - - // ─── Tutorials ─────────────────────────────────────────────────────────── - - /** - * Register a tutorial. - */ - registerTutorial(tutorial: Tutorial): void { - this.tutorials.set(tutorial.id, tutorial); - } - - /** - * Get tutorial by ID. - */ - getTutorial(tutorialId: string): Tutorial | null { - return this.tutorials.get(tutorialId) || null; - } - - /** - * Get tutorials by difficulty. - */ - getTutorialsByDifficulty(difficulty: string): Tutorial[] { - return [...this.tutorials.values()].filter((t) => t.difficulty === difficulty); - } - - /** - * Get tutorials for beginners. - */ - getBeginnerTutorials(): Tutorial[] { - return this.getTutorialsByDifficulty("beginner"); - } - - // ─── Collections ───────────────────────────────────────────────────────── - - /** - * Create a documentation collection (category). - */ - createCollection( - category: string, - description: string, - pages: DocPage[], - order: number = 0, - ): DocCollection { - const collection: DocCollection = { - category, - pages, - description, - order, - }; - this.collections.set(category, collection); - return collection; - } - - /** - * Get collection by category. - */ - getCollection(category: string): DocCollection | null { - return this.collections.get(category) || null; - } - - /** - * Get all collections sorted by order. - */ - getAllCollections(): DocCollection[] { - return [...this.collections.values()].sort((a, b) => a.order - b.order); - } - - // ─── Export & Generation ───────────────────────────────────────────────── - - /** - * Generate documentation HTML site structure. - */ - generateSiteStructure(): { - collections: Array<{ - name: string; - pages: Array<{ title: string; slug: string; type: DocType }>; - }>; - } { - return { - collections: this.getAllCollections().map((col) => ({ - name: col.category, - pages: col.pages.map((p) => ({ - title: p.title, - slug: p.slug, - type: p.type, - })), - })), - }; - } - - /** - * Generate a static site dump (markdown files). - */ - generateMarkdownDump(): Record { - const dump: Record = {}; - - for (const page of this.pages.values()) { - const filename = `${page.slug}.md`; - dump[filename] = `# ${page.title}\n\n${page.content}`; - } - - return dump; - } - - /** - * Generate navigation sidebar structure. - */ - generateNavigation(): Array<{ - label: string; - items: Array<{ label: string; href: string; type: DocType }>; - }> { - return this.getAllCollections().map((col) => ({ - label: col.category, - items: col.pages.map((p) => ({ - label: p.title, - href: `/docs/${p.slug}`, - type: p.type, - })), - })); - } - - // ─── Statistics ─────────────────────────────────────────────────────────── - - /** - * Get documentation statistics. - */ - getStats(): { - totalPages: number; - byType: Record; - totalViews: number; - totalExamples: number; - totalTutorials: number; - avgPageLength: number; - } { - const byType: Record = {} as Record; - let totalLength = 0; - let totalViews = 0; - - for (const page of this.pages.values()) { - byType[page.type] = (byType[page.type] || 0) + 1; - totalLength += page.content.length; - totalViews += page.views; - } - - return { - totalPages: this.pages.size, - byType, - totalViews, - totalExamples: this.examples.size, - totalTutorials: this.tutorials.size, - avgPageLength: this.pages.size > 0 ? Math.round(totalLength / this.pages.size) : 0, - }; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getPagesCache(): Map { - return this.pages; - } - - getExamplesCache(): Map { - return this.examples; - } - - getTutorialsCache(): Map { - return this.tutorials; - } - - getAPIDocsCache(): Map { - return this.apiDocs; - } -} diff --git a/src/error-tracker.test.ts b/src/error-tracker.test.ts deleted file mode 100644 index d942fa05..00000000 --- a/src/error-tracker.test.ts +++ /dev/null @@ -1,298 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { ErrorTracker } from "./error-tracker.js"; - -describe("ErrorTracker", () => { - describe("error logging", () => { - let tracker: ErrorTracker; - - beforeEach(() => { - tracker = new ErrorTracker(); - }); - - it("logs an error", () => { - const error = tracker.logError( - "Database connection failed", - "Error: Connection timeout", - "critical", - ); - assert(error.id); - assert.equal(error.message, "Database connection failed"); - assert.equal(error.resolved, false); - }); - - it("logs error with context", () => { - const context = { database: "main", retries: 3 }; - const error = tracker.logError("DB error", "stack", "high", context); - assert.deepEqual(error.context, context); - }); - - it("logs error with user and session ID", () => { - const error = tracker.logError( - "Error", - "stack", - "high", - {}, - "user-123", - "session-456", - ); - assert.equal(error.userId, "user-123"); - assert.equal(error.sessionId, "session-456"); - }); - - it("gets error by ID", () => { - const logged = tracker.logError("Test error", "stack"); - const retrieved = tracker.getError(logged.id); - assert(retrieved); - assert.equal(retrieved.message, "Test error"); - }); - - it("returns null for unknown error ID", () => { - const error = tracker.getError("unknown"); - assert.equal(error, null); - }); - - it("resolves an error", () => { - const logged = tracker.logError("Test", "stack"); - const resolved = tracker.resolveError(logged.id); - assert(resolved); - assert(resolved.resolved); - assert(resolved.resolvedAt); - }); - - it("gets all unresolved errors", () => { - tracker.logError("Error 1", "stack"); - const error2 = tracker.logError("Error 2", "stack"); - tracker.logError("Error 3", "stack"); - tracker.resolveError(error2.id); - - const unresolved = tracker.getUnresolvedErrors(); - assert.equal(unresolved.length, 2); - }); - - it("gets errors by severity", () => { - tracker.logError("Error 1", "stack", "critical"); - tracker.logError("Error 2", "stack", "high"); - tracker.logError("Error 3", "stack", "critical"); - - const critical = tracker.getErrorsBySeverity("critical"); - assert.equal(critical.length, 2); - }); - - it("uses high severity as default", () => { - const error = tracker.logError("Test", "stack"); - assert.equal(error.severity, "high"); - }); - }); - - describe("error grouping", () => { - let tracker: ErrorTracker; - - beforeEach(() => { - tracker = new ErrorTracker(); - }); - - it("groups same errors together", () => { - const msg = "Database connection failed"; - tracker.logError(msg, "stack1"); - tracker.logError(msg, "stack2"); - tracker.logError(msg, "stack3"); - - const groups = tracker.getAllErrorGroups(); - assert.equal(groups.length, 1); - assert.equal(groups[0].occurrences, 3); - }); - - it("creates separate groups for different errors", () => { - tracker.logError("Error A", "stack"); - tracker.logError("Error B", "stack"); - tracker.logError("Error C", "stack"); - - const groups = tracker.getAllErrorGroups(); - assert.equal(groups.length, 3); - }); - - it("tracks first and last occurrence", () => { - const msg = "Recurring error"; - tracker.logError(msg, "stack1"); - tracker.logError(msg, "stack2"); - - const groups = tracker.getAllErrorGroups(); - const group = groups[0]; - assert(group.firstSeen); - assert(group.lastSeen); - assert(group.firstSeen <= group.lastSeen); - }); - - it("escalates severity to critical", () => { - const msg = "API error"; - tracker.logError(msg, "stack", "low"); - tracker.logError(msg, "stack", "critical"); - - const groups = tracker.getAllErrorGroups(); - const group = groups[0]; - assert.equal(group.severity, "critical"); - }); - - it("gets errors by group", () => { - const msg = "Database error"; - tracker.logError(msg, "stack1"); - tracker.logError(msg, "stack2"); - tracker.logError("Other error", "stack"); - - const groups = tracker.getAllErrorGroups(); - const dbGroup = groups.find((g) => g.message === msg); - const errors = tracker.getErrorsByGroup(dbGroup!.id); - assert.equal(errors.length, 2); - }); - - it("marks group as resolved when all errors resolved", () => { - const msg = "Test error"; - const e1 = tracker.logError(msg, "stack1"); - const e2 = tracker.logError(msg, "stack2"); - - tracker.resolveError(e1.id); - tracker.resolveError(e2.id); - - const groups = tracker.getAllErrorGroups(); - const group = groups[0]; - assert(group.resolved); - }); - }); - - describe("metrics", () => { - let tracker: ErrorTracker; - - beforeEach(() => { - tracker = new ErrorTracker(); - }); - - it("returns error metrics", () => { - tracker.logError("Error 1", "stack", "critical"); - tracker.logError("Error 2", "stack", "high"); - tracker.logError("Error 3", "stack", "low"); - - const metrics = tracker.getMetrics(); - assert.equal(metrics.totalErrors, 3); - assert.equal(metrics.errorsBySeverity.critical, 1); - assert.equal(metrics.errorsBySeverity.high, 1); - assert.equal(metrics.errorsBySeverity.low, 1); - }); - - it("counts errors by type", () => { - tracker.logError("Database error", "stack"); - tracker.logError("Database error", "stack"); - tracker.logError("Network error", "stack"); - - const metrics = tracker.getMetrics(); - assert.equal(metrics.errorsByType["Database error"], 2); - assert.equal(metrics.errorsByType["Network error"], 1); - }); - - it("returns top errors", () => { - tracker.logError("Common error", "stack"); - tracker.logError("Common error", "stack"); - tracker.logError("Common error", "stack"); - tracker.logError("Rare error", "stack"); - - const metrics = tracker.getMetrics(); - const topErrors = metrics.topErrors; - assert(topErrors.length > 0); - assert.equal(topErrors[0].message, "Common error"); - }); - - it("tracks error trend over time", () => { - tracker.logError("Error 1", "stack"); - tracker.logError("Error 2", "stack"); - tracker.logError("Error 3", "stack"); - - const metrics = tracker.getMetrics(); - assert(metrics.errorTrend.length > 0); - assert(metrics.errorTrend[0].date); - assert(metrics.errorTrend[0].count > 0); - }); - - it("calculates error rate", () => { - tracker.logError("Error 1", "stack"); - tracker.logError("Error 2", "stack"); - - const rate = tracker.getErrorRate(); - assert(rate >= 0); - }); - - it("returns recent errors sorted by timestamp", () => { - tracker.logError("Error 1", "stack"); - tracker.logError("Error 2", "stack"); - tracker.logError("Error 3", "stack"); - - const recent = tracker.getRecentErrors(2); - assert.equal(recent.length, 2); - assert( - new Date(recent[0].timestamp).getTime() >= - new Date(recent[1].timestamp).getTime(), - ); - }); - - it("respects limit on recent errors", () => { - for (let i = 0; i < 20; i++) { - tracker.logError(`Error ${i}`, "stack"); - } - - const recent = tracker.getRecentErrors(5); - assert.equal(recent.length, 5); - }); - }); - - describe("cleanup", () => { - let tracker: ErrorTracker; - - beforeEach(() => { - tracker = new ErrorTracker(); - }); - - it("clears resolved errors", () => { - const e1 = tracker.logError("Error 1", "stack"); - const e2 = tracker.logError("Error 2", "stack"); - tracker.logError("Error 3", "stack"); - - tracker.resolveError(e1.id); - tracker.resolveError(e2.id); - - const cleared = tracker.clearResolvedErrors(); - assert(cleared > 0); - assert.equal(tracker.getUnresolvedErrors().length, 1); - }); - - it("clears old errors", () => { - tracker.logError("Recent error", "stack"); - // This test would need to set timestamps manually in a real scenario - const cache = tracker.getErrorCache(); - assert(cache.size > 0); - }); - }); - - describe("cache helpers", () => { - let tracker: ErrorTracker; - - beforeEach(() => { - tracker = new ErrorTracker(); - }); - - it("returns error cache", () => { - tracker.logError("Error 1", "stack"); - tracker.logError("Error 2", "stack"); - - const cache = tracker.getErrorCache(); - assert.equal(cache.size, 2); - }); - - it("returns error group cache", () => { - tracker.logError("Error 1", "stack"); - tracker.logError("Error 2", "stack"); - tracker.logError("Error 3", "stack"); - - const groupCache = tracker.getErrorGroupCache(); - assert.equal(groupCache.size, 3); - }); - }); -}); diff --git a/src/error-tracker.ts b/src/error-tracker.ts deleted file mode 100644 index 8b58264c..00000000 --- a/src/error-tracker.ts +++ /dev/null @@ -1,288 +0,0 @@ -// ─── Types ──────────────────────────────────────────────────────────────────── - -import { IdGenerators } from "./id-generator.js"; - -export interface ErrorLog { - id: string; - message: string; - stack: string; - severity: "critical" | "high" | "medium" | "low"; - context: Record; - timestamp: string; - userId?: string; - sessionId?: string; - resolved: boolean; - resolvedAt?: string; -} - -export interface ErrorMetrics { - totalErrors: number; - errorsBySeverity: Record; - errorsByType: Record; - errorTrend: Array<{ date: string; count: number }>; - topErrors: Array<{ message: string; count: number }>; -} - -export interface ErrorGroup { - id: string; - message: string; - firstSeen: string; - lastSeen: string; - occurrences: number; - severity: "critical" | "high" | "medium" | "low"; - resolved: boolean; -} - -// ─── ErrorTracker ──────────────────────────────────────────────────────────── - -export class ErrorTracker { - private errors: Map = new Map(); - private errorGroups: Map = new Map(); - private errorIndex: Map> = new Map(); // message → errorIds - - // ─── Error Logging ──────────────────────────────────────────────────────── - - /** - * Log an error. - */ - logError( - message: string, - stack: string, - severity: "critical" | "high" | "medium" | "low" = "high", - context: Record = {}, - userId?: string, - sessionId?: string, - ): ErrorLog { - const id = IdGenerators.error(); - const error: ErrorLog = { - id, - message, - stack, - severity, - context, - timestamp: new Date().toISOString(), - userId, - sessionId, - resolved: false, - }; - - this.errors.set(id, error); - this.indexError(id, message); - this.groupError(error); - - return error; - } - - /** - * Get error by ID. - */ - getError(errorId: string): ErrorLog | null { - return this.errors.get(errorId) || null; - } - - /** - * Resolve an error. - */ - resolveError(errorId: string): ErrorLog | null { - const error = this.errors.get(errorId); - if (!error) return null; - - error.resolved = true; - error.resolvedAt = new Date().toISOString(); - - // Update error group - const group = this.findGroupForError(error); - if (group) { - const unresolved = this.getErrorsByGroup(group.id).filter((e) => !e.resolved); - if (unresolved.length === 0) { - group.resolved = true; - } - } - - return error; - } - - /** - * Get all unresolved errors. - */ - getUnresolvedErrors(): ErrorLog[] { - return [...this.errors.values()].filter((e) => !e.resolved); - } - - /** - * Get errors by severity. - */ - getErrorsBySeverity(severity: string): ErrorLog[] { - return [...this.errors.values()].filter((e) => e.severity === severity && !e.resolved); - } - - // ─── Error Grouping ─────────────────────────────────────────────────────── - - private indexError(errorId: string, message: string): void { - const ids = this.errorIndex.get(message) || new Set(); - ids.add(errorId); - this.errorIndex.set(message, ids); - } - - private groupError(error: ErrorLog): void { - // Check if error message already has a group - const existingGroup = [...this.errorGroups.values()].find( - (g) => g.message === error.message, - ); - - if (existingGroup) { - existingGroup.occurrences++; - existingGroup.lastSeen = error.timestamp; - if (error.severity === "critical" && existingGroup.severity !== "critical") { - existingGroup.severity = "critical"; - } - } else { - // Create new group - const groupId = IdGenerators.errorGroup(); - const group: ErrorGroup = { - id: groupId, - message: error.message, - firstSeen: error.timestamp, - lastSeen: error.timestamp, - occurrences: 1, - severity: error.severity, - resolved: false, - }; - this.errorGroups.set(groupId, group); - } - } - - private findGroupForError(error: ErrorLog): ErrorGroup | null { - return ( - [...this.errorGroups.values()].find((g) => g.message === error.message) || null - ); - } - - /** - * Get all error groups. - */ - getAllErrorGroups(): ErrorGroup[] { - return [...this.errorGroups.values()].sort( - (a, b) => b.occurrences - a.occurrences, - ); - } - - /** - * Get errors in a group. - */ - getErrorsByGroup(groupId: string): ErrorLog[] { - const group = this.errorGroups.get(groupId); - if (!group) return []; - - return [...this.errors.values()].filter((e) => e.message === group.message); - } - - // ─── Metrics & Analytics ────────────────────────────────────────────────── - - /** - * Get error metrics. - */ - getMetrics(): ErrorMetrics { - const errorsBySeverity: Record = { - critical: 0, - high: 0, - medium: 0, - low: 0, - }; - const errorsByType: Record = {}; - const errorTrend: Map = new Map(); - - for (const error of this.errors.values()) { - errorsBySeverity[error.severity]++; - - // Count by message type - errorsByType[error.message] = (errorsByType[error.message] || 0) + 1; - - // Count by date - const date = error.timestamp.split("T")[0]; - errorTrend.set(date, (errorTrend.get(date) || 0) + 1); - } - - // Get top errors - const topErrors = Object.entries(errorsByType) - .map(([message, count]) => ({ message, count })) - .sort((a, b) => b.count - a.count) - .slice(0, 10); - - return { - totalErrors: this.errors.size, - errorsBySeverity, - errorsByType, - errorTrend: [...errorTrend.entries()] - .map(([date, count]) => ({ date, count })) - .sort((a, b) => a.date.localeCompare(b.date)), - topErrors, - }; - } - - /** - * Get error rate (errors per minute). - */ - getErrorRate(): number { - if (this.errors.size === 0) return 0; - - const now = Date.now(); - const oneMinuteAgo = now - 60 * 1000; - const recentErrors = [...this.errors.values()].filter( - (e) => new Date(e.timestamp).getTime() > oneMinuteAgo, - ); - - return recentErrors.length; - } - - /** - * Get most recent errors. - */ - getRecentErrors(limit = 10): ErrorLog[] { - return [...this.errors.values()] - .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()) - .slice(0, limit); - } - - // ─── Cleanup ────────────────────────────────────────────────────────────── - - /** - * Clear old errors (older than days). - */ - clearOldErrors(days: number): number { - const cutoff = Date.now() - days * 24 * 60 * 60 * 1000; - let count = 0; - - for (const [id, error] of this.errors.entries()) { - if (new Date(error.timestamp).getTime() < cutoff) { - this.errors.delete(id); - count++; - } - } - - return count; - } - - /** - * Clear resolved errors. - */ - clearResolvedErrors(): number { - const before = this.errors.size; - for (const [id, error] of this.errors.entries()) { - if (error.resolved) { - this.errors.delete(id); - } - } - return before - this.errors.size; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getErrorCache(): Map { - return this.errors; - } - - getErrorGroupCache(): Map { - return this.errorGroups; - } -} diff --git a/src/image-optimizer.test.ts b/src/image-optimizer.test.ts deleted file mode 100644 index c1eeff63..00000000 --- a/src/image-optimizer.test.ts +++ /dev/null @@ -1,338 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { ImageOptimizer, type OptimizationProfile } from "./image-optimizer.js"; - -describe("ImageOptimizer", () => { - describe("optimization profiles", () => { - let optimizer: ImageOptimizer; - - beforeEach(() => { - optimizer = new ImageOptimizer(); - }); - - it("creates optimization profile", () => { - const profile: OptimizationProfile = { - name: "thumbnail", - maxWidth: 200, - maxHeight: 200, - quality: 70, - format: "webp", - }; - optimizer.createProfile(profile); - const retrieved = optimizer.getProfile("thumbnail"); - assert.deepEqual(retrieved, profile); - }); - - it("gets profile by name", () => { - const profile: OptimizationProfile = { - name: "mobile", - maxWidth: 480, - maxHeight: 640, - quality: 80, - format: "webp", - }; - optimizer.createProfile(profile); - const retrieved = optimizer.getProfile("mobile"); - assert(retrieved); - assert.equal(retrieved.name, "mobile"); - }); - - it("returns null for unknown profile", () => { - const profile = optimizer.getProfile("unknown"); - assert.equal(profile, null); - }); - - it("gets all profiles", () => { - optimizer.createProfile({ - name: "p1", - maxWidth: 100, - maxHeight: 100, - quality: 70, - format: "webp", - }); - optimizer.createProfile({ - name: "p2", - maxWidth: 500, - maxHeight: 500, - quality: 85, - format: "webp", - }); - const all = optimizer.getAllProfiles(); - assert.equal(all.length, 2); - }); - - it("deletes profile", () => { - optimizer.createProfile({ - name: "temp", - maxWidth: 100, - maxHeight: 100, - quality: 70, - format: "webp", - }); - const deleted = optimizer.deleteProfile("temp"); - assert(deleted); - assert.equal(optimizer.getProfile("temp"), null); - }); - }); - - describe("image optimization", () => { - let optimizer: ImageOptimizer; - let profile: OptimizationProfile; - - beforeEach(() => { - optimizer = new ImageOptimizer(); - profile = { - name: "web", - maxWidth: 1200, - maxHeight: 800, - quality: 85, - format: "webp", - }; - optimizer.createProfile(profile); - }); - - it("optimizes image", () => { - const metadata = optimizer.optimizeImage( - "test.jpg", - 500000, // 500KB - 2000, - 1500, - profile, - ); - assert(metadata); - assert.equal(metadata.filename, "test.jpg"); - assert(metadata.optimizedSize < metadata.originalSize); - }); - - it("respects max width constraint", () => { - const metadata = optimizer.optimizeImage("test.jpg", 500000, 2000, 1500, profile); - assert(metadata.width <= profile.maxWidth); - }); - - it("respects max height constraint", () => { - const metadata = optimizer.optimizeImage( - "test.jpg", - 500000, - 800, - 2000, // tall image - profile, - ); - assert(metadata.height <= profile.maxHeight); - }); - - it("maintains aspect ratio", () => { - const metadata = optimizer.optimizeImage("test.jpg", 500000, 1000, 500, profile); - // If width was reduced by 50%, height should also be reduced by ~50% - assert(metadata.height <= 250 || metadata.height > 240); - }); - - it("calculates compression ratio", () => { - const metadata = optimizer.optimizeImage( - "test.jpg", - 500000, - 2000, - 1500, - profile, - ); - assert(metadata.compressionRatio > 0); - assert(metadata.compressionRatio <= 100); - }); - - it("gets image metadata", () => { - optimizer.optimizeImage("test.jpg", 500000, 2000, 1500, profile); - const metadata = optimizer.getImageMetadata("test.jpg"); - assert(metadata); - assert.equal(metadata.filename, "test.jpg"); - }); - - it("gets all optimized images", () => { - optimizer.optimizeImage("test1.jpg", 500000, 2000, 1500, profile); - optimizer.optimizeImage("test2.jpg", 300000, 1500, 1000, profile); - const all = optimizer.getAllOptimizedImages(); - assert.equal(all.length, 2); - }); - }); - - describe("responsive variants", () => { - let optimizer: ImageOptimizer; - - beforeEach(() => { - optimizer = new ImageOptimizer(); - }); - - it("generates responsive variants", () => { - const variants = optimizer.generateResponsiveVariants( - "test.jpg", - "https://cdn.example.com", - [320, 640, 1024], - ); - assert.equal(variants.length, 3); - assert.equal(variants[0].width, 320); - assert.equal(variants[1].width, 640); - assert.equal(variants[2].width, 1024); - }); - - it("uses custom widths for variants", () => { - const variants = optimizer.generateResponsiveVariants( - "test.jpg", - "https://cdn.example.com", - [200, 400, 600, 800], - ); - assert.equal(variants.length, 4); - }); - - it("generates correct URLs for variants", () => { - const variants = optimizer.generateResponsiveVariants( - "test.jpg", - "https://cdn.example.com", - [320], - ); - assert(variants[0].url.includes("w=320")); - }); - - it("caches responsive variants", () => { - optimizer.generateResponsiveVariants( - "test.jpg", - "https://cdn.example.com", - ); - const cached = optimizer.getResponsiveVariants("test.jpg"); - assert(cached.length > 0); - }); - - it("returns empty array for uncached image", () => { - const variants = optimizer.getResponsiveVariants("unknown.jpg"); - assert.equal(variants.length, 0); - }); - }); - - describe("lazy loading markup", () => { - let optimizer: ImageOptimizer; - let profile: OptimizationProfile; - - beforeEach(() => { - optimizer = new ImageOptimizer(); - profile = { - name: "web", - maxWidth: 1200, - maxHeight: 800, - quality: 85, - format: "webp", - }; - optimizer.createProfile(profile); - optimizer.optimizeImage("test.jpg", 500000, 2000, 1500, profile); - }); - - it("generates lazy loading markup", () => { - const markup = optimizer.generateLazyLoadMarkup( - "test.jpg", - "https://cdn.example.com", - "Test Image", - ); - assert(markup.includes("loading=\"lazy\"")); - assert(markup.includes("data-src")); - assert(markup.includes("Test Image")); - }); - - it("includes width and height in markup", () => { - const markup = optimizer.generateLazyLoadMarkup( - "test.jpg", - "https://cdn.example.com", - "Test", - ); - assert(markup.includes("width=")); - assert(markup.includes("height=")); - }); - - it("generates picture element with srcset", () => { - optimizer.generateResponsiveVariants("test.jpg", "https://cdn.example.com"); - const markup = optimizer.generatePictureElement( - "test.jpg", - "https://cdn.example.com", - "Test", - ); - assert(markup.includes("")); - assert(markup.includes("srcset=")); - assert(markup.includes("")); - }); - - it("returns empty string for unknown image", () => { - const markup = optimizer.generateLazyLoadMarkup( - "unknown.jpg", - "https://cdn.example.com", - "Unknown", - ); - assert.equal(markup, ""); - }); - }); - - describe("format conversion", () => { - let optimizer: ImageOptimizer; - - beforeEach(() => { - optimizer = new ImageOptimizer(); - }); - - it("recommends WebP for high quality", () => { - const format = optimizer.recommendFormat("jpeg", 85); - assert.equal(format, "webp"); - }); - - it("recommends AVIF for very high quality", () => { - const format = optimizer.recommendFormat("jpeg", 90); - assert.equal(format, "avif"); - }); - - it("preserves original format when appropriate", () => { - const format = optimizer.recommendFormat("jpeg", 70); - assert.equal(format, "jpeg"); - }); - - it("checks transparency support", () => { - assert(optimizer.supportsTransparency("png")); - assert(optimizer.supportsTransparency("webp")); - assert(optimizer.supportsTransparency("avif")); - assert(!optimizer.supportsTransparency("jpeg")); - }); - }); - - describe("statistics", () => { - let optimizer: ImageOptimizer; - let profile: OptimizationProfile; - - beforeEach(() => { - optimizer = new ImageOptimizer(); - profile = { - name: "web", - maxWidth: 1200, - maxHeight: 800, - quality: 85, - format: "webp", - }; - optimizer.createProfile(profile); - }); - - it("returns optimization statistics", () => { - optimizer.optimizeImage("test1.jpg", 500000, 2000, 1500, profile); - optimizer.optimizeImage("test2.jpg", 300000, 1500, 1000, profile); - - const stats = optimizer.getOptimizationStats(); - assert.equal(stats.totalImages, 2); - assert(stats.totalOriginalSize > 0); - assert(stats.totalOptimizedSize > 0); - assert(stats.averageCompressionRatio > 0); - }); - - it("calculates compression ratio correctly", () => { - optimizer.optimizeImage("test.jpg", 1000000, 2000, 1500, profile); - const stats = optimizer.getOptimizationStats(); - assert(stats.averageCompressionRatio > 0); - assert(stats.averageCompressionRatio <= 100); - }); - - it("returns zero compression for no images", () => { - const stats = optimizer.getOptimizationStats(); - assert.equal(stats.totalImages, 0); - assert.equal(stats.averageCompressionRatio, 0); - }); - }); -}); diff --git a/src/image-optimizer.ts b/src/image-optimizer.ts deleted file mode 100644 index 57bba3c5..00000000 --- a/src/image-optimizer.ts +++ /dev/null @@ -1,290 +0,0 @@ -// ─── Types ──────────────────────────────────────────────────────────────────── - -export interface ImageMetadata { - filename: string; - originalSize: number; - optimizedSize: number; - width: number; - height: number; - format: "jpeg" | "png" | "webp" | "avif"; - quality: number; - compressionRatio: number; -} - -export interface OptimizationProfile { - name: string; - maxWidth: number; - maxHeight: number; - quality: number; - format: string; -} - -export interface ResponsiveVariant { - width: number; - height: number; - url: string; - size: number; -} - -// ─── ImageOptimizer ─────────────────────────────────────────────────────────── - -export class ImageOptimizer { - private optimizationStats: Map = new Map(); - private profiles: Map = new Map(); - private thumbnailCache: Map = new Map(); - - // ─── Optimization Profiles ──────────────────────────────────────────────── - - /** - * Create optimization profile. - */ - createProfile(profile: OptimizationProfile): void { - this.profiles.set(profile.name, profile); - } - - /** - * Get optimization profile. - */ - getProfile(profileName: string): OptimizationProfile | null { - return this.profiles.get(profileName) || null; - } - - /** - * Get all profiles. - */ - getAllProfiles(): OptimizationProfile[] { - return [...this.profiles.values()]; - } - - /** - * Delete profile. - */ - deleteProfile(profileName: string): boolean { - return this.profiles.delete(profileName); - } - - // ─── Image Optimization ─────────────────────────────────────────────────── - - /** - * Optimize image. - */ - optimizeImage( - filename: string, - originalSize: number, - width: number, - height: number, - profile: OptimizationProfile, - ): ImageMetadata { - // Calculate new dimensions based on profile - let newWidth = width; - let newHeight = height; - - if (width > profile.maxWidth) { - const ratio = profile.maxWidth / width; - newWidth = profile.maxWidth; - newHeight = Math.round(height * ratio); - } - - if (newHeight > profile.maxHeight) { - const ratio = profile.maxHeight / newHeight; - newHeight = profile.maxHeight; - newWidth = Math.round(newWidth * ratio); - } - - // Estimate optimized size based on compression - const optimizedSize = Math.round(originalSize * (0.5 + (profile.quality / 100) * 0.5)); - - const metadata: ImageMetadata = { - filename, - originalSize, - optimizedSize, - width: newWidth, - height: newHeight, - format: (profile.format || "webp") as "jpeg" | "png" | "webp" | "avif", - quality: profile.quality, - compressionRatio: Math.round((1 - optimizedSize / originalSize) * 100), - }; - - this.optimizationStats.set(filename, metadata); - return metadata; - } - - /** - * Generate responsive image variants. - */ - generateResponsiveVariants( - filename: string, - baseUrl: string, - widths: number[] = [320, 640, 1024], - ): ResponsiveVariant[] { - const variants: ResponsiveVariant[] = []; - const cached = this.thumbnailCache.get(filename); - - if (cached) { - return cached; - } - - for (const width of widths) { - const variant: ResponsiveVariant = { - width, - height: Math.round((width / 16) * 9), // 16:9 aspect ratio - url: `${baseUrl}/${filename}?w=${width}`, - size: Math.round(50 * (width / 320)), // Rough size estimate - }; - variants.push(variant); - } - - this.thumbnailCache.set(filename, variants); - return variants; - } - - /** - * Get responsive variants for image. - */ - getResponsiveVariants(filename: string): ResponsiveVariant[] { - return this.thumbnailCache.get(filename) || []; - } - - // ─── Lazy Loading ──────────────────────────────────────────────────────── - - /** - * Generate lazy loading markup. - */ - generateLazyLoadMarkup( - filename: string, - baseUrl: string, - alt: string, - ): string { - const metadata = this.optimizationStats.get(filename); - if (!metadata) return ""; - - const placeholderUrl = `${baseUrl}/${filename}?w=20&blur=5`; - const mainUrl = `${baseUrl}/${filename}`; - - return ` -${alt}`.trim(); - } - - /** - * Generate picture element with srcset. - */ - generatePictureElement( - filename: string, - baseUrl: string, - alt: string, - ): string { - const variants = this.getResponsiveVariants(filename); - const metadata = this.optimizationStats.get(filename); - - if (!metadata || variants.length === 0) return ""; - - const srcset = variants - .map((v) => `${v.url} ${v.width}w`) - .join(", "); - - return ` - - - ${alt} -`.trim(); - } - - // ─── Format Conversion ───────────────────────────────────────────────────── - - /** - * Recommend best format for image. - */ - recommendFormat( - originalFormat: string, - targetQuality: number, - ): "webp" | "avif" | "jpeg" | "png" { - // AVIF: better compression, newer format (highest quality first) - if (targetQuality >= 90) return "avif"; - // WebP: good compression, broad support - if (targetQuality >= 75) return "webp"; - // JPEG: legacy support, good quality - if (originalFormat === "jpeg") return "jpeg"; - return "webp"; - } - - /** - * Check if format supports transparency. - */ - supportsTransparency(format: string): boolean { - return ["png", "webp", "avif"].includes(format.toLowerCase()); - } - - // ─── Statistics ──────────────────────────────────────────────────────────── - - /** - * Get optimization statistics. - */ - getOptimizationStats(): { - totalImages: number; - totalOriginalSize: number; - totalOptimizedSize: number; - averageCompressionRatio: number; - } { - let totalOriginal = 0; - let totalOptimized = 0; - - for (const meta of this.optimizationStats.values()) { - totalOriginal += meta.originalSize; - totalOptimized += meta.optimizedSize; - } - - const avgCompressionRatio = - this.optimizationStats.size > 0 - ? Math.round(((totalOriginal - totalOptimized) / totalOriginal) * 100) - : 0; - - return { - totalImages: this.optimizationStats.size, - totalOriginalSize: totalOriginal, - totalOptimizedSize: totalOptimized, - averageCompressionRatio: avgCompressionRatio, - }; - } - - /** - * Get metadata for image. - */ - getImageMetadata(filename: string): ImageMetadata | null { - return this.optimizationStats.get(filename) || null; - } - - /** - * Get all optimized images. - */ - getAllOptimizedImages(): ImageMetadata[] { - return [...this.optimizationStats.values()]; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getOptimizationCache(): Map { - return this.optimizationStats; - } - - getProfilesCache(): Map { - return this.profiles; - } - - getThumbnailCache(): Map { - return this.thumbnailCache; - } -} diff --git a/src/mcp-kit-tools-model.ts b/src/mcp-kit-tools-model.ts deleted file mode 100644 index f4c43619..00000000 --- a/src/mcp-kit-tools-model.ts +++ /dev/null @@ -1,217 +0,0 @@ -/** - * kit MCP Tools — data models - * Configuration, health checks, installation, and provisioning via MCP - */ - -export type ConfigScope = "global" | "project" | "user"; -export type ConfigCategory = "adapter" | "tool" | "service" | "path" | "feature"; -export type ValidationResult = "valid" | "invalid" | "warning"; - -export interface ConfigValue { - key: string; - value: unknown; - type: "string" | "number" | "boolean" | "array" | "object"; - scope: ConfigScope; - category: ConfigCategory; - description?: string; - required?: boolean; - default?: unknown; - validation_rule?: string; - last_modified?: string; - modified_by?: string; -} - -export interface ConfigValidation { - key: string; - result: ValidationResult; - message: string; - suggestions?: string[]; - timestamp: string; -} - -export interface ConfigDiff { - key: string; - old_value: unknown; - new_value: unknown; - scope: ConfigScope; - changed_at: string; - changed_by?: string; -} - -export interface AdapterConfig { - name: string; - enabled: boolean; - version?: string; - settings: Record; - credentials_configured: boolean; - health_status?: "healthy" | "warning" | "error"; - last_check?: string; -} - -export interface ToolConfig { - name: string; - installed: boolean; - version?: string; - path?: string; - required: boolean; - auto_update: boolean; - health_status?: "healthy" | "missing" | "incompatible"; -} - -export interface ServiceConfig { - name: string; - enabled: boolean; - endpoint?: string; - port?: number; - protocol?: "http" | "https" | "websocket" | "grpc"; - health_check_url?: string; - status?: "running" | "stopped" | "error"; - last_status_check?: string; -} - -export interface PathConfig { - key: string; - value: string; - type: "project_root" | "cache_dir" | "config_dir" | "data_dir" | "temp_dir" | "lock_dir"; - expandable: boolean; - must_exist: boolean; - writable: boolean; -} - -export interface FeatureFlag { - name: string; - enabled: boolean; - scope: ConfigScope; - rollout_percentage?: number; - description?: string; - dependencies?: string[]; -} - -export interface MCPTool { - id: string; - name: string; - description: string; - category: "configuration" | "health" | "installation" | "provisioning" | "utility"; - version: string; - actions: ToolAction[]; - requires_auth?: boolean; - rate_limit?: number; -} - -export interface ToolAction { - name: string; - description: string; - parameters: ToolParameter[]; - returns: ToolReturn; - requires_confirmation?: boolean; - dry_run_supported?: boolean; -} - -export interface ToolParameter { - name: string; - description: string; - type: "string" | "number" | "boolean" | "array" | "object"; - required: boolean; - default?: unknown; - enum?: unknown[]; - min?: number; - max?: number; - pattern?: string; -} - -export interface ToolReturn { - type: "string" | "number" | "boolean" | "object" | "array"; - description: string; - schema?: Record; -} - -export interface MCPToolResult { - success: boolean; - data?: T; - error?: string; - warnings?: string[]; - execution_time_ms?: number; -} - -export interface ConfigSnapshot { - id: string; - timestamp: string; - created_by?: string; - config_state: Record; - description?: string; -} - -export interface ConfigRollback { - from_snapshot: string; - to_snapshot: string; - changes_reverted: number; - timestamp: string; - performed_by?: string; -} - -export interface AdapterCheckResult { - adapter_name: string; - overall_status: "healthy" | "degraded" | "unhealthy"; - installed: boolean; - configured: boolean; - authenticated: boolean; - available: boolean; - checks: { - name: string; - status: "pass" | "fail" | "warning"; - message: string; - details?: Record; - }[]; - recommendations?: string[]; - last_checked: string; -} - -export interface AdapterDependency { - name: string; - required: boolean; - installed: boolean; - version?: string; - compatible: boolean; - min_version?: string; -} - -export interface AdapterHealth { - adapter_name: string; - healthy: boolean; - uptime_seconds?: number; - last_error?: string; - error_count: number; - success_count: number; - average_response_time_ms?: number; - last_checked: string; -} - -export interface AdapterInstallResult { - adapter_name: string; - success: boolean; - installed: boolean; - version?: string; - configured: boolean; - env_vars_set: string[]; - setup_required: boolean; - next_steps?: string[]; - message: string; - timestamp: string; -} - -export interface AdapterSetupConfig { - adapter_name: string; - auto_configure: boolean; - interactive: boolean; - env_vars?: Record; - settings?: Record; -} - -export interface EnvironmentVariable { - key: string; - value: string; - adapter_name: string; - required: boolean; - description?: string; - set_at: string; -} diff --git a/src/mcp-kit-tools-service.test.ts b/src/mcp-kit-tools-service.test.ts deleted file mode 100644 index 298c7138..00000000 --- a/src/mcp-kit-tools-service.test.ts +++ /dev/null @@ -1,676 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import * as MCPTools from "./mcp-kit-tools-service.js"; - -describe("mcp-kit-tools-service", () => { - describe("kit_configure — config operations", () => { - it("sets configuration value", () => { - const result = MCPTools.setConfig("test.timeout", 5000, "project", "tool", "user-123"); - - assert.equal(result.success, true); - assert.equal(result.data?.key, "test.timeout"); - assert.equal(result.data?.value, 5000); - assert.equal(result.data?.scope, "project"); - }); - - it("gets configuration value", () => { - MCPTools.setConfig("app.name", "kit", "global", "tool"); - - const result = MCPTools.getConfig("app.name"); - - assert.equal(result.success, true); - assert.equal(result.data?.value, "kit"); - }); - - it("returns error for nonexistent key", () => { - const result = MCPTools.getConfig("nonexistent.key"); - - assert.equal(result.success, false); - assert.ok(result.error); - }); - - it("lists configurations with filters", () => { - MCPTools.setConfig("global.setting", "value1", "global", "adapter"); - MCPTools.setConfig("project.setting", "value2", "project", "tool"); - - const result = MCPTools.listConfigs("project", "tool"); - - assert.equal(result.success, true); - assert.ok(result.data!.configs.length > 0); - assert.ok(result.data!.configs.every((c) => c.scope === "project" && c.category === "tool")); - }); - - it("respects pagination in list", () => { - for (let i = 0; i < 10; i++) { - MCPTools.setConfig(`item.${i}`, i, "project", "tool"); - } - - const result1 = MCPTools.listConfigs(undefined, undefined, 5, 0); - const result2 = MCPTools.listConfigs(undefined, undefined, 5, 5); - - assert.equal(result1.data!.configs.length, 5); - assert.ok(result2.data!.configs.length > 0); - }); - }); - - describe("configuration validation", () => { - it("validates configuration value successfully", () => { - const result = MCPTools.validateConfigValue("test.port", 8080); - - assert.equal(result.result, "valid"); - }); - - it("detects type mismatch", () => { - MCPTools.setConfig("strict.number", 42, "project", "tool"); - - const validation = MCPTools.validateConfigValue("strict.number", "not a number"); - - assert.ok(validation.result !== "valid"); - assert.ok(validation.message); - }); - - it("provides conversion suggestion for string-to-number", () => { - MCPTools.setConfig("numeric.value", 100, "project", "tool"); - - const validation = MCPTools.validateConfigValue("numeric.value", "123"); - - // Should allow conversion - assert.ok(validation.message); - }); - }); - - describe("adapter configuration", () => { - it("configures adapter", () => { - const result = MCPTools.configureAdapter("stripe", true, { - api_key: "sk_test_...", - version: "2023-10-16", - }); - - assert.equal(result.success, true); - assert.equal(result.data?.name, "stripe"); - assert.equal(result.data?.enabled, true); - assert.equal(result.data?.credentials_configured, true); - }); - - it("gets adapter configuration", () => { - MCPTools.configureAdapter("github", true, { token: "ghp_..." }); - - const result = MCPTools.getAdapterConfig("github"); - - assert.equal(result.success, true); - assert.equal(result.data?.name, "github"); - }); - - it("returns error for nonexistent adapter", () => { - const result = MCPTools.getAdapterConfig("nonexistent"); - - assert.equal(result.success, false); - }); - - it("lists all adapters", () => { - MCPTools.configureAdapter("slack", true, {}); - MCPTools.configureAdapter("discord", false, {}); - - const result = MCPTools.listAdapters(); - - assert.equal(result.success, true); - assert.ok(result.data!.length > 0); - }); - }); - - describe("tool configuration", () => { - it("gets tool configuration", () => { - const result = MCPTools.getToolConfig("node"); - - // Tool might not exist, that's okay - if (!result.success) { - assert.ok(result.error); - } - }); - - it("lists all tools", () => { - const result = MCPTools.listTools(); - - assert.equal(result.success, true); - assert.ok(Array.isArray(result.data)); - }); - }); - - describe("service configuration", () => { - it("configures service", () => { - const result = MCPTools.configureService("api-server", true, "http://localhost", 3000); - - assert.equal(result.success, true); - assert.equal(result.data?.name, "api-server"); - assert.equal(result.data?.enabled, true); - assert.equal(result.data?.port, 3000); - }); - - it("gets service configuration", () => { - MCPTools.configureService("database", true, "localhost", 5432); - - const result = MCPTools.getServiceConfig("database"); - - assert.equal(result.success, true); - assert.equal(result.data?.port, 5432); - }); - - it("lists services", () => { - MCPTools.configureService("cache", true, "redis://localhost", 6379); - - const result = MCPTools.listServices(); - - assert.equal(result.success, true); - assert.ok(result.data!.length > 0); - }); - }); - - describe("path configuration", () => { - it("sets path configuration", () => { - const result = MCPTools.setPathConfig( - "project_root", - "/home/user/projects/kit", - "project_root", - ); - - assert.equal(result.success, true); - assert.equal(result.data?.key, "project_root"); - assert.equal(result.data?.type, "project_root"); - }); - - it("gets path configuration", () => { - MCPTools.setPathConfig("cache_dir", "/tmp/.kit/cache", "cache_dir"); - - const result = MCPTools.getPathConfig("cache_dir"); - - assert.equal(result.success, true); - assert.ok(result.data?.value.includes("cache")); - }); - - it("marks expandable paths", () => { - const result = MCPTools.setPathConfig( - "temp_dir", - "$TEMP/.kit", - "temp_dir", - ); - - assert.equal(result.data?.expandable, true); - }); - - it("lists paths", () => { - MCPTools.setPathConfig("data_dir", "/var/lib/kit", "data_dir"); - - const result = MCPTools.listPaths(); - - assert.equal(result.success, true); - assert.ok(result.data!.length > 0); - }); - }); - - describe("feature flags", () => { - it("toggles feature flag on", () => { - const result = MCPTools.toggleFeatureFlag("experimental_mode", true, "project"); - - assert.equal(result.success, true); - assert.equal(result.data?.name, "experimental_mode"); - assert.equal(result.data?.enabled, true); - }); - - it("toggles feature flag off", () => { - MCPTools.toggleFeatureFlag("beta_feature", true); - - const result = MCPTools.toggleFeatureFlag("beta_feature", false); - - assert.equal(result.success, true); - assert.equal(result.data?.enabled, false); - }); - - it("gets feature flag", () => { - MCPTools.toggleFeatureFlag("dark_mode", true); - - const result = MCPTools.getFeatureFlag("dark_mode"); - - assert.equal(result.success, true); - assert.equal(result.data?.enabled, true); - }); - - it("lists feature flags", () => { - MCPTools.toggleFeatureFlag("flag1", true); - MCPTools.toggleFeatureFlag("flag2", false); - - const result = MCPTools.listFeatureFlags(); - - assert.equal(result.success, true); - assert.ok(result.data!.length > 0); - }); - }); - - describe("configuration snapshots", () => { - it("creates configuration snapshot", () => { - MCPTools.setConfig("snap.key1", "value1", "project", "tool"); - MCPTools.setConfig("snap.key2", "value2", "project", "tool"); - - const result = MCPTools.createConfigSnapshot("user-123", "Before migration"); - - assert.equal(result.success, true); - assert.ok(result.data?.id); - assert.equal(result.data?.description, "Before migration"); - assert.ok(Object.keys(result.data!.config_state).length > 0); - }); - - it("lists snapshots", () => { - MCPTools.createConfigSnapshot("user-456", "Snapshot 1"); - MCPTools.createConfigSnapshot("user-456", "Snapshot 2"); - - const result = MCPTools.listSnapshots(); - - assert.equal(result.success, true); - assert.ok(result.data!.snapshots.length > 0); - }); - - it("respects pagination in snapshots", () => { - const result1 = MCPTools.listSnapshots(5, 0); - MCPTools.listSnapshots(5, 5); - - assert.equal(result1.success, true); - assert.ok(result1.data!.snapshots.length > 0); - }); - - it("rolls back to snapshot", () => { - // Create snapshot - const snap = MCPTools.createConfigSnapshot(undefined, "Rollback test"); - const snapshot_id = snap.data!.id; - - // Change config - MCPTools.setConfig("rollback.test", "changed"); - - // Rollback - const result = MCPTools.rollbackToSnapshot(snapshot_id, "admin"); - - assert.equal(result.success, true); - assert.ok((result.data?.changes_reverted || 0) >= 0); - }); - - it("fails rollback for nonexistent snapshot", () => { - const result = MCPTools.rollbackToSnapshot("nonexistent_snap"); - - assert.equal(result.success, false); - assert.ok(result.error); - }); - }); - - describe("MCP tool definitions", () => { - it("returns MCP tool definitions", () => { - const tools = MCPTools.getMCPTools(); - - assert.ok(Array.isArray(tools)); - assert.ok(tools.length >= 2); - }); - - it("defines kit_configure tool", () => { - const tools = MCPTools.getMCPTools(); - const configureTool = tools.find((t) => t.id === "kit_configure"); - - assert.ok(configureTool); - assert.equal(configureTool!.category, "configuration"); - assert.ok(configureTool!.actions.length > 0); - }); - - it("defines kit_adapter_check tool", () => { - const tools = MCPTools.getMCPTools(); - const checkTool = tools.find((t) => t.id === "kit_adapter_check"); - - assert.ok(checkTool); - assert.equal(checkTool!.category, "health"); - assert.ok(checkTool!.actions.length > 0); - }); - - it("kit_configure has required actions", () => { - const tools = MCPTools.getMCPTools(); - const configureTool = tools.find((t) => t.id === "kit_configure"); - const actionNames = configureTool!.actions.map((a) => a.name); - - assert.ok(actionNames.includes("get")); - assert.ok(actionNames.includes("set")); - assert.ok(actionNames.includes("list")); - assert.ok(actionNames.includes("validate")); - }); - - it("action parameters are properly defined", () => { - const tools = MCPTools.getMCPTools(); - const configureTool = tools.find((t) => t.id === "kit_configure"); - const getAction = configureTool!.actions.find((a) => a.name === "get"); - - assert.ok(getAction!.parameters.length > 0); - assert.ok(getAction!.parameters[0].name === "key"); - assert.equal(getAction!.parameters[0].required, true); - }); - }); - - describe("kit_adapter_check — adapter status checks", () => { - it("checks adapter status", () => { - MCPTools.configureAdapter("check-test", true, { api_key: "secret" }); - - const result = MCPTools.checkAdapterStatus("check-test"); - - assert.equal(result.success, true); - assert.ok(result.data?.overall_status); - assert.ok(result.data?.checks.length > 0); - assert.equal(result.data?.installed, true); - assert.equal(result.data?.authenticated, true); - }); - - it("returns error for nonexistent adapter", () => { - const result = MCPTools.checkAdapterStatus("nonexistent-adapter"); - - assert.equal(result.success, false); - assert.ok(result.error); - }); - - it("provides recommendations for unhealthy adapters", () => { - MCPTools.configureAdapter("unhealthy", false, {}); - - const result = MCPTools.checkAdapterStatus("unhealthy"); - - assert.ok(result.data?.recommendations); - assert.ok(result.data!.recommendations!.length > 0); - }); - - it("checks adapter dependencies", () => { - const result = MCPTools.checkAdapterDependencies("stripe"); - - assert.equal(result.success, true); - assert.ok(Array.isArray(result.data)); - assert.ok(result.data!.length > 0); - assert.ok(result.data!.some((d) => d.name === "node")); - }); - - it("returns empty dependencies for unknown adapter", () => { - const result = MCPTools.checkAdapterDependencies("unknown"); - - assert.equal(result.success, true); - assert.equal(result.data?.length, 0); - }); - - it("gets adapter health status", () => { - MCPTools.configureAdapter("health-check", true, {}); - - const result = MCPTools.getAdapterHealth("health-check"); - - assert.equal(result.success, true); - assert.ok(typeof result.data?.healthy === "boolean"); - assert.ok(result.data?.uptime_seconds !== undefined); - assert.ok(result.data?.error_count !== undefined); - assert.ok(result.data?.success_count !== undefined); - }); - - it("returns error for nonexistent adapter in health check", () => { - const result = MCPTools.getAdapterHealth("nonexistent"); - - assert.equal(result.success, false); - assert.ok(result.error); - }); - }); - - describe("adapter installation and setup", () => { - it("installs adapter successfully", () => { - const result = MCPTools.installAdapter("stripe", false, "2.0.0"); - - assert.equal(result.success, true); - assert.equal(result.data?.adapter_name, "stripe"); - assert.equal(result.data?.installed, true); - assert.equal(result.data?.version, "2.0.0"); - assert.equal(result.data?.setup_required, true); - }); - - it("installs adapter with auto-configuration", () => { - const result = MCPTools.installAdapter("github", true, "1.5.0"); - - assert.equal(result.success, true); - assert.equal(result.data?.configured, false); - assert.equal(result.data?.setup_required, false); - assert.ok(result.data?.message.includes("auto-configured")); - }); - - it("sets up adapter automatically with environment variables", () => { - MCPTools.installAdapter("slack", false); - - const result = MCPTools.setupAdapterAuto("slack", { - api_token: "xoxb-test", - bot_id: "bot-123", - }); - - assert.equal(result.success, true); - assert.equal(result.data?.configured, true); - assert.equal(result.data?.env_vars_set.length, 2); - assert.ok(result.data?.env_vars_set.includes("SLACK_API_TOKEN")); - assert.ok(result.data?.env_vars_set.includes("SLACK_BOT_ID")); - }); - - it("returns error when setting up non-existent adapter", () => { - const result = MCPTools.setupAdapterAuto("nonexistent", { - key: "value", - }); - - assert.equal(result.success, false); - assert.ok(result.error); - }); - - it("sets up adapter interactively", () => { - MCPTools.installAdapter("datadog", false); - - const result = MCPTools.setupAdapterInteractive("datadog", { - api_key: "dd_api_key", - app_key: "dd_app_key", - }); - - assert.equal(result.success, true); - assert.equal(result.data?.configured, true); - assert.equal(result.data?.env_vars_set.length, 2); - }); - - it("sets environment variable", () => { - const result = MCPTools.setEnvironmentVariable( - "AWS_ACCESS_KEY_ID", - "AKIA...", - "aws", - true, - "AWS access key", - ); - - assert.equal(result.success, true); - assert.equal(result.data?.key, "AWS_ACCESS_KEY_ID"); - assert.equal(result.data?.value, "AKIA..."); - assert.equal(result.data?.required, true); - }); - - it("retrieves environment variables", () => { - MCPTools.setEnvironmentVariable("STRIPE_KEY", "sk_test", "stripe", true); - MCPTools.setEnvironmentVariable("STRIPE_SECRET", "sk_secret", "stripe", true); - MCPTools.setEnvironmentVariable("GITHUB_TOKEN", "ghp_test", "github", true); - - const result = MCPTools.getEnvironmentVariables("stripe"); - - assert.equal(result.success, true); - assert.equal(result.data!.length, 2); - assert.ok(result.data!.every((v) => v.adapter_name === "stripe")); - }); - - it("retrieves only required environment variables", () => { - MCPTools.setEnvironmentVariable("REQUIRED_VAR", "value", "test", true); - MCPTools.setEnvironmentVariable("OPTIONAL_VAR", "value", "test", false); - - const result = MCPTools.getEnvironmentVariables("test", true); - - assert.equal(result.data!.length, 1); - assert.equal(result.data![0].required, true); - }); - }); - - describe("kit_adapter_install tool definition", () => { - it("defines kit_adapter_install tool", () => { - const tools = MCPTools.getMCPTools(); - const installTool = tools.find((t) => t.id === "kit_adapter_install"); - - assert.ok(installTool); - assert.equal(installTool!.category, "installation"); - assert.ok(installTool!.actions.length >= 3); - }); - - it("has install action", () => { - const tools = MCPTools.getMCPTools(); - const installTool = tools.find((t) => t.id === "kit_adapter_install"); - const installAction = installTool!.actions.find((a) => a.name === "install"); - - assert.ok(installAction); - assert.ok(installAction!.parameters.some((p) => p.name === "adapter")); - assert.ok(installAction!.parameters.some((p) => p.name === "version")); - }); - - it("has setup action", () => { - const tools = MCPTools.getMCPTools(); - const installTool = tools.find((t) => t.id === "kit_adapter_install"); - const setupAction = installTool!.actions.find((a) => a.name === "setup"); - - assert.ok(setupAction); - assert.ok(setupAction!.parameters.some((p) => p.name === "adapter")); - assert.ok(setupAction!.parameters.some((p) => p.name === "mode")); - }); - - it("has configure action", () => { - const tools = MCPTools.getMCPTools(); - const installTool = tools.find((t) => t.id === "kit_adapter_install"); - const configAction = installTool!.actions.find((a) => a.name === "configure"); - - assert.ok(configAction); - assert.ok(configAction!.parameters.some((p) => p.name === "key")); - assert.ok(configAction!.parameters.some((p) => p.name === "value")); - assert.ok(configAction!.parameters.some((p) => p.name === "adapter")); - }); - }); - - describe("end-to-end configuration workflow", () => { - it("manages complete configuration lifecycle", () => { - // Set configurations - MCPTools.setConfig("app.debug", true, "project", "feature"); - MCPTools.setConfig("db.host", "localhost", "project", "service"); - MCPTools.setConfig("api.timeout", 30000, "project", "tool"); - - // Validate - const validation = MCPTools.validateConfigValue("db.host", "localhost"); - assert.equal(validation.result, "valid"); - - // Create snapshot - const snap = MCPTools.createConfigSnapshot("dev", "Initial setup"); - assert.equal(snap.success, true); - - // List configurations - const list = MCPTools.listConfigs("project"); - assert.ok(list.data!.total >= 3); - - // Get specific config - const get = MCPTools.getConfig("app.debug"); - assert.equal(get.success, true); - assert.equal(get.data?.value, true); - - // Configure adapter - const adapter = MCPTools.configureAdapter("dev-tools", true, {}); - assert.equal(adapter.success, true); - - // Configure service - const service = MCPTools.configureService("debug-server", true, "localhost", 9229); - assert.equal(service.success, true); - - // Toggle feature - const feature = MCPTools.toggleFeatureFlag("debug_mode", true, "project"); - assert.equal(feature.success, true); - }); - }); - - describe("MCP tool definitions validation", () => { - it("kit_configure actions have required parameters", () => { - const tools = MCPTools.getMCPTools(); - const configureTool = tools.find((t) => t.id === "kit_configure"); - const getAction = configureTool!.actions.find((a) => a.name === "get"); - - // Verify get action requires 'key' parameter - assert.ok(getAction!.parameters.find((p) => p.name === "key" && p.required)); - }); - - it("kit_adapter_install has all required action parameters", () => { - const tools = MCPTools.getMCPTools(); - const installTool = tools.find((t) => t.id === "kit_adapter_install"); - - // Check install action - const installAction = installTool!.actions.find((a) => a.name === "install"); - assert.ok(installAction!.parameters.find((p) => p.name === "adapter" && p.required)); - - // Check setup action - const setupAction = installTool!.actions.find((a) => a.name === "setup"); - assert.ok(setupAction!.parameters.find((p) => p.name === "adapter" && p.required)); - assert.ok(setupAction!.parameters.find((p) => p.name === "mode" && p.required)); - - // Check configure action - const configAction = installTool!.actions.find((a) => a.name === "configure"); - assert.ok(configAction!.parameters.find((p) => p.name === "key" && p.required)); - assert.ok(configAction!.parameters.find((p) => p.name === "value" && p.required)); - assert.ok(configAction!.parameters.find((p) => p.name === "adapter" && p.required)); - }); - - it("tool definitions include proper return types", () => { - const tools = MCPTools.getMCPTools(); - const configureTool = tools.find((t) => t.id === "kit_configure"); - const getAction = configureTool!.actions.find((a) => a.name === "get"); - - // Verify return type is object - assert.ok(getAction!.returns); - assert.equal(getAction!.returns.type, "object"); - assert.ok(getAction!.returns.description); - }); - - it("all kit_adapter_check actions specify return types", () => { - const tools = MCPTools.getMCPTools(); - const checkTool = tools.find((t) => t.id === "kit_adapter_check"); - - checkTool!.actions.forEach((action) => { - assert.ok(action.returns); - assert.ok(["object", "array"].includes(action.returns.type)); - assert.ok(action.returns.description); - }); - }); - - it("MCP tools include rate limit configuration", () => { - const tools = MCPTools.getMCPTools(); - const configureTool = tools.find((t) => t.id === "kit_configure"); - - // Tools should have rate_limit or not require auth - assert.ok(configureTool!.rate_limit !== undefined || !configureTool!.requires_auth); - }); - }); - - describe("end-to-end adapter installation workflow", () => { - it("manages complete adapter installation and setup lifecycle", () => { - // Install adapter - const install = MCPTools.installAdapter("sendgrid", false, "5.0.0"); - assert.equal(install.success, true); - assert.equal(install.data?.installed, true); - - // Setup adapter - const setup = MCPTools.setupAdapterAuto("sendgrid", { - api_key: "SG.test...", - }); - assert.equal(setup.success, true); - assert.equal(setup.data?.configured, true); - - // Verify environment variables - const envVars = MCPTools.getEnvironmentVariables("sendgrid"); - assert.equal(envVars.success, true); - assert.ok(envVars.data!.length > 0); - - // Check adapter status - const status = MCPTools.checkAdapterStatus("sendgrid"); - assert.equal(status.success, true); - assert.equal(status.data?.installed, true); - }); - }); -}); diff --git a/src/mcp-kit-tools-service.ts b/src/mcp-kit-tools-service.ts deleted file mode 100644 index 0dc30b64..00000000 --- a/src/mcp-kit-tools-service.ts +++ /dev/null @@ -1,1136 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - ConfigValue, - ConfigValidation, - AdapterConfig, - ToolConfig, - ServiceConfig, - PathConfig, - FeatureFlag, - MCPTool, - MCPToolResult, - ConfigSnapshot, - ConfigRollback, - ValidationResult, - AdapterCheckResult, - AdapterDependency, - AdapterHealth, - AdapterInstallResult, - EnvironmentVariable, -} from "./mcp-kit-tools-model.js"; - -const configs = new Map(); -const adapters = new Map(); -const tools = new Map(); -const services = new Map(); -const paths = new Map(); -const featureFlags = new Map(); -const snapshots = new Map(); -const validationHistory = new Map(); -const environmentVariables = new Map(); - -/** - * Get configuration value - */ -export function getConfig(key: string): MCPToolResult { - const config = configs.get(key); - - if (!config) { - return { - success: false, - error: `Configuration key '${key}' not found`, - }; - } - - return { - success: true, - data: config, - }; -} - -/** - * Set configuration value - */ -export function setConfig( - key: string, - value: unknown, - scope: "global" | "project" | "user" = "project", - category: "adapter" | "tool" | "service" | "path" | "feature" = "tool", - modified_by?: string, -): MCPToolResult { - const validation = validateConfigValue(key, value); - if (validation.result === "invalid") { - return { - success: false, - error: validation.message, - warnings: validation.suggestions, - }; - } - - const config: ConfigValue = { - key, - value, - type: typeof value === "object" ? (Array.isArray(value) ? "array" : "object") : (typeof value as any), - scope, - category, - last_modified: new Date().toISOString(), - modified_by, - }; - - configs.set(key, config); - - return { - success: true, - data: config, - }; -} - -/** - * List configurations - */ -export function listConfigs( - scope?: "global" | "project" | "user", - category?: "adapter" | "tool" | "service" | "path" | "feature", - limit: number = 100, - offset: number = 0, -): MCPToolResult<{ configs: ConfigValue[]; total: number }> { - let results = Array.from(configs.values()); - - if (scope) { - results = results.filter((c) => c.scope === scope); - } - - if (category) { - results = results.filter((c) => c.category === category); - } - - const total = results.length; - const paged = results.slice(offset, offset + limit); - - return { - success: true, - data: { configs: paged, total }, - }; -} - -/** - * Validate configuration value - */ -export function validateConfigValue( - key: string, - value: unknown, -): ConfigValidation { - const existingConfig = configs.get(key); - let result: ValidationResult = "valid"; - let message = `Configuration '${key}' is valid`; - const suggestions: string[] = []; - - // Type validation - if (existingConfig && existingConfig.type !== typeof value) { - if (typeof value === "string" && existingConfig.type === "number") { - // Allow string to number conversion - result = "warning"; - message = `Type mismatch: expected ${existingConfig.type}, got ${typeof value}. Will attempt conversion.`; - } else { - result = "invalid"; - message = `Type mismatch: expected ${existingConfig.type}, got ${typeof value}`; - } - } - - // Pattern validation - if (existingConfig?.validation_rule && typeof value === "string") { - const regex = new RegExp(existingConfig.validation_rule); - if (!regex.test(value)) { - result = "invalid"; - message = `Value does not match required pattern: ${existingConfig.validation_rule}`; - } - } - - // Range validation - const configAny = existingConfig as any; - if (configAny?.min && typeof value === "number" && value < configAny.min) { - result = "warning"; - message = `Value ${value} is below minimum ${configAny.min}`; - } - - if (configAny?.max && typeof value === "number" && value > configAny.max) { - result = "warning"; - message = `Value ${value} is above maximum ${configAny.max}`; - } - - const validation: ConfigValidation = { - key, - result, - message, - suggestions, - timestamp: new Date().toISOString(), - }; - - validationHistory.set(`${key}_${Date.now()}`, validation); - - return validation; -} - -/** - * Get adapter configuration - */ -export function getAdapterConfig(name: string): MCPToolResult { - const adapter = adapters.get(name); - - if (!adapter) { - return { - success: false, - error: `Adapter '${name}' not found`, - }; - } - - return { - success: true, - data: adapter, - }; -} - -/** - * List adapters - */ -export function listAdapters(): MCPToolResult { - const adapterList = Array.from(adapters.values()); - return { - success: true, - data: adapterList, - }; -} - -/** - * Configure adapter - */ -export function configureAdapter( - name: string, - enabled: boolean, - settings: Record, -): MCPToolResult { - const existing = adapters.get(name); - - const adapter: AdapterConfig = { - name, - enabled, - version: existing?.version, - settings, - credentials_configured: Object.keys(settings).length > 0, - health_status: "healthy", - last_check: new Date().toISOString(), - }; - - adapters.set(name, adapter); - - return { - success: true, - data: adapter, - }; -} - -/** - * Get tool configuration - */ -export function getToolConfig(name: string): MCPToolResult { - const tool = tools.get(name); - - if (!tool) { - return { - success: false, - error: `Tool '${name}' not found`, - }; - } - - return { - success: true, - data: tool, - }; -} - -/** - * List tools - */ -export function listTools(): MCPToolResult { - return { - success: true, - data: Array.from(tools.values()), - }; -} - -/** - * Get service configuration - */ -export function getServiceConfig(name: string): MCPToolResult { - const service = services.get(name); - - if (!service) { - return { - success: false, - error: `Service '${name}' not found`, - }; - } - - return { - success: true, - data: service, - }; -} - -/** - * List services - */ -export function listServices(): MCPToolResult { - return { - success: true, - data: Array.from(services.values()), - }; -} - -/** - * Configure service - */ -export function configureService( - name: string, - enabled: boolean, - endpoint?: string, - port?: number, -): MCPToolResult { - const service: ServiceConfig = { - name, - enabled, - endpoint, - port, - status: enabled ? "running" : "stopped", - last_status_check: new Date().toISOString(), - }; - - services.set(name, service); - - return { - success: true, - data: service, - }; -} - -/** - * Get path configuration - */ -export function getPathConfig(key: string): MCPToolResult { - const path = paths.get(key); - - if (!path) { - return { - success: false, - error: `Path '${key}' not found`, - }; - } - - return { - success: true, - data: path, - }; -} - -/** - * List paths - */ -export function listPaths(): MCPToolResult { - return { - success: true, - data: Array.from(paths.values()), - }; -} - -/** - * Set path configuration - */ -export function setPathConfig( - key: string, - value: string, - type: "project_root" | "cache_dir" | "config_dir" | "data_dir" | "temp_dir" | "lock_dir", -): MCPToolResult { - const path: PathConfig = { - key, - value, - type, - expandable: value.includes("$") || value.includes("~"), - must_exist: type !== "temp_dir", - writable: !["project_root"].includes(type), - }; - - paths.set(key, path); - - return { - success: true, - data: path, - }; -} - -/** - * Get feature flag - */ -export function getFeatureFlag(name: string): MCPToolResult { - const flag = featureFlags.get(name); - - if (!flag) { - return { - success: false, - error: `Feature flag '${name}' not found`, - }; - } - - return { - success: true, - data: flag, - }; -} - -/** - * List feature flags - */ -export function listFeatureFlags(): MCPToolResult { - return { - success: true, - data: Array.from(featureFlags.values()), - }; -} - -/** - * Toggle feature flag - */ -export function toggleFeatureFlag( - name: string, - enabled: boolean, - scope: "global" | "project" | "user" = "project", -): MCPToolResult { - const existing = featureFlags.get(name) || { - name, - enabled: false, - scope, - }; - - const flag: FeatureFlag = { - ...existing, - enabled, - scope, - }; - - featureFlags.set(name, flag); - - return { - success: true, - data: flag, - }; -} - -/** - * Create configuration snapshot - */ -export function createConfigSnapshot( - created_by?: string, - description?: string, -): MCPToolResult { - const snapshot: ConfigSnapshot = { - id: `snap_${randomUUID()}`, - timestamp: new Date().toISOString(), - created_by, - config_state: Object.fromEntries(configs), - description, - }; - - snapshots.set(snapshot.id, snapshot); - - return { - success: true, - data: snapshot, - }; -} - -/** - * List configuration snapshots - */ -export function listSnapshots(limit: number = 20, offset: number = 0): MCPToolResult<{ snapshots: ConfigSnapshot[]; total: number }> { - const all = Array.from(snapshots.values()).sort( - (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(), - ); - - const total = all.length; - const paged = all.slice(offset, offset + limit); - - return { - success: true, - data: { snapshots: paged, total }, - }; -} - -/** - * Rollback to snapshot - */ -export function rollbackToSnapshot( - snapshot_id: string, - performed_by?: string, -): MCPToolResult { - const snapshot = snapshots.get(snapshot_id); - - if (!snapshot) { - return { - success: false, - error: `Snapshot '${snapshot_id}' not found`, - }; - } - - const changeCount = configs.size; - - // Restore config state - configs.clear(); - Object.entries(snapshot.config_state).forEach(([key, value]) => { - configs.set(key, value as ConfigValue); - }); - - const rollback: ConfigRollback = { - from_snapshot: snapshots.get(Array.from(snapshots.keys())[0])?.id || "current", - to_snapshot: snapshot_id, - changes_reverted: changeCount, - timestamp: new Date().toISOString(), - performed_by, - }; - - return { - success: true, - data: rollback, - }; -} - -/** - * Check adapter status - */ -export function checkAdapterStatus(adapter_name: string): MCPToolResult { - const adapter = adapters.get(adapter_name); - - if (!adapter) { - return { - success: false, - error: `Adapter '${adapter_name}' not found`, - }; - } - - const checks: AdapterCheckResult["checks"] = []; - - // Check if installed - checks.push({ - name: "installation", - status: adapter.enabled ? "pass" : "fail", - message: adapter.enabled - ? `${adapter_name} is installed and enabled` - : `${adapter_name} is not enabled`, - }); - - // Check configuration - checks.push({ - name: "configuration", - status: Object.keys(adapter.settings).length > 0 ? "pass" : "warning", - message: - Object.keys(adapter.settings).length > 0 - ? `Configuration present (${Object.keys(adapter.settings).length} settings)` - : "No configuration found", - }); - - // Check credentials - checks.push({ - name: "credentials", - status: adapter.credentials_configured ? "pass" : "warning", - message: adapter.credentials_configured - ? "Credentials are configured" - : "Credentials not configured", - }); - - // Check health - checks.push({ - name: "health", - status: adapter.health_status === "healthy" ? "pass" : adapter.health_status === "warning" ? "warning" : "fail", - message: `Health status: ${adapter.health_status || "unknown"}`, - }); - - const overallStatus = - checks.every((c) => c.status === "pass") - ? "healthy" - : checks.some((c) => c.status === "fail") - ? "unhealthy" - : "degraded"; - - const result: AdapterCheckResult = { - adapter_name, - overall_status: overallStatus, - installed: adapter.enabled, - configured: Object.keys(adapter.settings).length > 0, - authenticated: adapter.credentials_configured, - available: adapter.health_status === "healthy", - checks, - last_checked: new Date().toISOString(), - }; - - // Add recommendations - if (overallStatus !== "healthy") { - result.recommendations = []; - if (!adapter.enabled) { - result.recommendations.push(`Enable ${adapter_name} in configuration`); - } - if (!adapter.credentials_configured) { - result.recommendations.push(`Configure credentials for ${adapter_name}`); - } - if (adapter.health_status === "warning" || adapter.health_status === "error") { - result.recommendations.push(`Check ${adapter_name} health status`); - } - } - - return { - success: true, - data: result, - }; -} - -/** - * Check adapter dependencies - */ -export function checkAdapterDependencies(adapter_name: string): MCPToolResult { - // Simulated dependencies for adapters - const dependencyMap: Record = { - stripe: [ - { name: "node", required: true, installed: true, compatible: true, version: "20.0.0" }, - { name: "npm", required: true, installed: true, compatible: true, version: "10.0.0" }, - ], - github: [ - { name: "git", required: true, installed: true, compatible: true, version: "2.40.0" }, - { name: "curl", required: false, installed: true, compatible: true }, - ], - slack: [ - { name: "node", required: true, installed: true, compatible: true, version: "20.0.0" }, - ], - }; - - const deps = dependencyMap[adapter_name] || []; - - return { - success: true, - data: deps, - }; -} - -/** - * Get adapter health status - */ -export function getAdapterHealth(adapter_name: string): MCPToolResult { - const adapter = adapters.get(adapter_name); - - if (!adapter) { - return { - success: false, - error: `Adapter '${adapter_name}' not found`, - }; - } - - const health: AdapterHealth = { - adapter_name, - healthy: adapter.health_status === "healthy", - uptime_seconds: Math.floor(Math.random() * 86400), - error_count: Math.floor(Math.random() * 5), - success_count: Math.floor(Math.random() * 100), - average_response_time_ms: Math.floor(Math.random() * 500) + 50, - last_checked: adapter.last_check || new Date().toISOString(), - }; - - return { - success: true, - data: health, - }; -} - -/** - * Install adapter - */ -export function installAdapter( - adapter_name: string, - auto_configure: boolean = false, - version?: string, - installed_by?: string, -): MCPToolResult { - const existing = adapters.get(adapter_name); - - const result: AdapterInstallResult = { - adapter_name, - success: true, - installed: true, - version: version || existing?.version || "1.0.0", - configured: false, - env_vars_set: [], - setup_required: !auto_configure, - next_steps: auto_configure - ? [] - : [ - `Run: kit adapter setup ${adapter_name}`, - `Or set environment variables manually`, - ], - message: `${adapter_name} adapter installed successfully`, - timestamp: new Date().toISOString(), - }; - - // Mark adapter as installed - const adapter: AdapterConfig = { - name: adapter_name, - enabled: true, - version: result.version, - settings: {}, - credentials_configured: false, - health_status: "healthy", - last_check: new Date().toISOString(), - }; - - adapters.set(adapter_name, adapter); - - if (auto_configure) { - result.setup_required = false; - result.message += " and auto-configured"; - } - - return { - success: true, - data: result, - }; -} - -/** - * Setup adapter automatically - */ -export function setupAdapterAuto( - adapter_name: string, - env_vars: Record, - setup_by?: string, -): MCPToolResult { - const adapter = adapters.get(adapter_name); - - if (!adapter) { - return { - success: false, - error: `Adapter '${adapter_name}' not found. Install it first.`, - }; - } - - const vars_set: string[] = []; - - // Set environment variables - Object.entries(env_vars).forEach(([key, value]) => { - const var_key = `${adapter_name}_${key}`.toUpperCase(); - const envVar: EnvironmentVariable = { - key: var_key, - value, - adapter_name, - required: true, - set_at: new Date().toISOString(), - }; - environmentVariables.set(var_key, envVar); - vars_set.push(var_key); - }); - - // Update adapter config - adapter.settings = env_vars; - adapter.credentials_configured = true; - adapter.last_check = new Date().toISOString(); - - const result: AdapterInstallResult = { - adapter_name, - success: true, - installed: true, - version: adapter.version, - configured: true, - env_vars_set: vars_set, - setup_required: false, - next_steps: [], - message: `${adapter_name} adapter configured with ${vars_set.length} environment variables`, - timestamp: new Date().toISOString(), - }; - - return { - success: true, - data: result, - }; -} - -/** - * Setup adapter interactively - */ -export function setupAdapterInteractive( - adapter_name: string, - responses: Record, - setup_by?: string, -): MCPToolResult { - const adapter = adapters.get(adapter_name); - - if (!adapter) { - return { - success: false, - error: `Adapter '${adapter_name}' not found. Install it first.`, - }; - } - - const vars_set: string[] = []; - - // Process interactive responses - Object.entries(responses).forEach(([key, value]) => { - const var_key = `${adapter_name}_${key}`.toUpperCase(); - const envVar: EnvironmentVariable = { - key: var_key, - value, - adapter_name, - required: true, - set_at: new Date().toISOString(), - }; - environmentVariables.set(var_key, envVar); - vars_set.push(var_key); - }); - - // Update adapter settings - adapter.settings = responses; - adapter.credentials_configured = true; - adapter.last_check = new Date().toISOString(); - - const result: AdapterInstallResult = { - adapter_name, - success: true, - installed: true, - version: adapter.version, - configured: true, - env_vars_set: vars_set, - setup_required: false, - next_steps: [], - message: `${adapter_name} adapter configured interactively with ${vars_set.length} variables`, - timestamp: new Date().toISOString(), - }; - - return { - success: true, - data: result, - }; -} - -/** - * Set environment variable - */ -export function setEnvironmentVariable( - key: string, - value: string, - adapter_name: string, - required: boolean = false, - description?: string, -): MCPToolResult { - const envVar: EnvironmentVariable = { - key, - value, - adapter_name, - required, - description, - set_at: new Date().toISOString(), - }; - - environmentVariables.set(key, envVar); - - return { - success: true, - data: envVar, - }; -} - -/** - * Get environment variables for adapter - */ -export function getEnvironmentVariables( - adapter_name?: string, - required_only: boolean = false, -): MCPToolResult { - let vars = Array.from(environmentVariables.values()); - - if (adapter_name) { - vars = vars.filter((v) => v.adapter_name === adapter_name); - } - - if (required_only) { - vars = vars.filter((v) => v.required); - } - - return { - success: true, - data: vars, - }; -} - -/** - * Get MCP tool definitions - */ -export function getMCPTools(): MCPTool[] { - return [ - { - id: "kit_configure", - name: "kit_configure", - description: "Get/set/list/validate kit configuration", - category: "configuration", - version: "1.0.0", - requires_auth: false, - actions: [ - { - name: "get", - description: "Get configuration value by key", - parameters: [ - { - name: "key", - description: "Configuration key", - type: "string", - required: true, - }, - ], - returns: { - type: "object", - description: "Configuration value object", - }, - }, - { - name: "set", - description: "Set configuration value", - parameters: [ - { - name: "key", - description: "Configuration key", - type: "string", - required: true, - }, - { - name: "value", - description: "Value to set", - type: "string", - required: true, - }, - { - name: "scope", - description: "Configuration scope", - type: "string", - required: false, - enum: ["global", "project", "user"], - }, - ], - returns: { - type: "object", - description: "Updated configuration", - }, - }, - { - name: "list", - description: "List configurations", - parameters: [ - { - name: "scope", - description: "Filter by scope", - type: "string", - required: false, - }, - { - name: "category", - description: "Filter by category", - type: "string", - required: false, - }, - ], - returns: { - type: "object", - description: "Configuration list", - }, - }, - { - name: "validate", - description: "Validate configuration value", - parameters: [ - { - name: "key", - description: "Configuration key", - type: "string", - required: true, - }, - { - name: "value", - description: "Value to validate", - type: "string", - required: true, - }, - ], - returns: { - type: "object", - description: "Validation result", - }, - }, - ], - }, - { - id: "kit_adapter_check", - name: "kit_adapter_check", - description: "Check adapter installation, configuration, and authentication status", - category: "health", - version: "1.0.0", - requires_auth: false, - actions: [ - { - name: "status", - description: "Get complete adapter status with all checks", - parameters: [ - { - name: "adapter", - description: "Adapter name", - type: "string", - required: true, - }, - ], - returns: { - type: "object", - description: "Adapter status with check results", - }, - }, - { - name: "dependencies", - description: "Check adapter dependencies", - parameters: [ - { - name: "adapter", - description: "Adapter name", - type: "string", - required: true, - }, - ], - returns: { - type: "array", - description: "Dependency list", - }, - }, - { - name: "health", - description: "Get adapter health metrics", - parameters: [ - { - name: "adapter", - description: "Adapter name", - type: "string", - required: true, - }, - ], - returns: { - type: "object", - description: "Health metrics", - }, - }, - ], - }, - { - id: "kit_adapter_install", - name: "kit_adapter_install", - description: "Install, configure, and setup kit adapters with auto or interactive configuration", - category: "installation", - version: "1.0.0", - requires_auth: false, - actions: [ - { - name: "install", - description: "Install an adapter", - parameters: [ - { - name: "adapter", - description: "Adapter name", - type: "string", - required: true, - }, - { - name: "version", - description: "Adapter version", - type: "string", - required: false, - }, - { - name: "auto_configure", - description: "Auto-configure after installation", - type: "boolean", - required: false, - }, - ], - returns: { - type: "object", - description: "Installation result", - }, - }, - { - name: "setup", - description: "Setup adapter with environment variables", - parameters: [ - { - name: "adapter", - description: "Adapter name", - type: "string", - required: true, - }, - { - name: "mode", - description: "Setup mode", - type: "string", - required: true, - enum: ["auto", "interactive"], - }, - { - name: "env_vars", - description: "Environment variables for auto mode", - type: "object", - required: false, - }, - { - name: "responses", - description: "Interactive responses", - type: "object", - required: false, - }, - ], - returns: { - type: "object", - description: "Setup result", - }, - }, - { - name: "configure", - description: "Configure environment variables", - parameters: [ - { - name: "key", - description: "Environment variable key", - type: "string", - required: true, - }, - { - name: "value", - description: "Environment variable value", - type: "string", - required: true, - }, - { - name: "adapter", - description: "Adapter name", - type: "string", - required: true, - }, - { - name: "required", - description: "Whether variable is required", - type: "boolean", - required: false, - }, - ], - returns: { - type: "object", - description: "Configuration result", - }, - }, - ], - }, - ]; -} diff --git a/src/middleware/rate-limiter.ts b/src/middleware/rate-limiter.ts deleted file mode 100644 index 92a47abd..00000000 --- a/src/middleware/rate-limiter.ts +++ /dev/null @@ -1,423 +0,0 @@ -/** - * Rate Limiting Middleware - * - * Redis-based distributed rate limiting with tier-based quotas. - * Implements token bucket algorithm for fair rate limiting. - * - * Limits by tier: - * - Free: 100 req/min, 10k req/day, 100 concurrent - * - Team: 1k req/min, 100k req/day, 1k concurrent - * - Enterprise: Custom (negotiated) - */ - -import { Redis } from '@upstash/redis'; -import { appendAuditEventDirect } from '../audit.js'; - -/** - * On Redis failure the limiter defaults to fail-closed (reject). The - * previous "fail-open" behavior turned a Redis outage into an unlimited - * burst window with no audit trail. Operators who knowingly accept that - * trade-off (e.g. a development environment where Redis is not yet wired - * up) opt in via `KIT_RATE_LIMIT_FAIL_OPEN=1`. The opt-in emits a - * one-time stderr warning and an audit event so the choice is visible. - */ -let warnedAboutFailOpen = false; -function failOpenAllowed(identifier: string): boolean { - if (process.env.KIT_RATE_LIMIT_FAIL_OPEN !== '1') return false; - if (!warnedAboutFailOpen) { - warnedAboutFailOpen = true; - console.error( - '[kit] WARNING: KIT_RATE_LIMIT_FAIL_OPEN=1 active — rate-limiter is fail-open on Redis errors.', - ); - void appendAuditEventDirect({ - operation: 'rate-limit-fail-open-enabled', - environment: process.env.NODE_ENV ?? 'unknown', - success: true, - metadata: { identifier }, - }); - } - return true; -} - -/** - * Test-only: reset the module-scoped fail-open warning flag. - */ -export function _resetFailOpenWarningForTests(): void { - warnedAboutFailOpen = false; -} - -// Rate limit tiers -export type UserTier = 'free' | 'team' | 'enterprise'; - -export const RATE_LIMITS: Record = { - free: { - requestsPerMinute: 100, - requestsPerDay: 10_000, - concurrentConnections: 100, - burstMultiplier: 1.5, - }, - team: { - requestsPerMinute: 1_000, - requestsPerDay: 100_000, - concurrentConnections: 1_000, - burstMultiplier: 1.2, - }, - enterprise: { - requestsPerMinute: 10_000, - requestsPerDay: 10_000_000, - concurrentConnections: 10_000, - burstMultiplier: 1.1, - }, -}; - -// Rate limit keys -type RateLimitKey = 'minute' | 'day' | 'concurrent'; - -interface RateLimitStatus { - allowed: boolean; - limit: number; - remaining: number; - resetAt: Date; - retryAfter?: number; -} - -export class RateLimiter { - private redis: Redis; - - constructor(redisUrl?: string) { - this.redis = new Redis({ - url: redisUrl || process.env.REDIS_URL, - token: process.env.REDIS_TOKEN, - }); - } - - /** - * Check rate limit for user/API key - */ - async checkLimit( - identifier: string, - tier: UserTier = 'free', - keyType: RateLimitKey = 'minute' - ): Promise { - const limits = RATE_LIMITS[tier]; - const limit = this.getLimitForKey(limits, keyType); - const ttl = this.getTTLForKey(keyType); - const key = this.buildKey(identifier, keyType); - - try { - // Get current count - const count = await this.redis.incr(key); - - // Set expiry on first request - if (count === 1) { - await this.redis.expire(key, ttl); - } - - // Check if limit exceeded - if (count > limit) { - const ttlRemaining = await this.redis.ttl(key); - return { - allowed: false, - limit, - remaining: 0, - resetAt: new Date(Date.now() + (ttlRemaining * 1000)), - retryAfter: ttlRemaining, - }; - } - - // Calculate reset time - const ttlRemaining = await this.redis.ttl(key); - const resetAt = new Date(Date.now() + (ttlRemaining * 1000)); - - return { - allowed: true, - limit, - remaining: Math.max(0, limit - count), - resetAt, - }; - } catch (error) { - console.error('Rate limiter error:', error); - void appendAuditEventDirect({ - operation: 'rate-limit-redis-error', - environment: process.env.NODE_ENV ?? 'unknown', - success: false, - error: String(error instanceof Error ? error.message : error), - metadata: { identifier, tier, keyType }, - }); - if (failOpenAllowed(identifier)) { - return { - allowed: true, - limit, - remaining: limit - 1, - resetAt: new Date(Date.now() + 60000), - }; - } - return { - allowed: false, - limit, - remaining: 0, - resetAt: new Date(Date.now() + 60000), - retryAfter: 60, - }; - } - } - - /** - * Check concurrent connections - */ - async checkConcurrent( - identifier: string, - tier: UserTier = 'free' - ): Promise { - const limits = RATE_LIMITS[tier]; - const limit = limits.concurrentConnections; - const key = this.buildKey(identifier, 'concurrent'); - - try { - const count = await this.redis.incr(key); - - // Set TTL (clear after 1 hour of inactivity) - if (count === 1) { - await this.redis.expire(key, 3600); - } - - if (count > limit) { - // Decrement on failure - await this.redis.decr(key); - return { - allowed: false, - limit, - remaining: 0, - resetAt: new Date(Date.now() + 60000), - }; - } - - return { - allowed: true, - limit, - remaining: Math.max(0, limit - count), - resetAt: new Date(Date.now() + 3600000), - }; - } catch (error) { - console.error('Concurrent limit error:', error); - void appendAuditEventDirect({ - operation: 'rate-limit-redis-error', - environment: process.env.NODE_ENV ?? 'unknown', - success: false, - error: String(error instanceof Error ? error.message : error), - metadata: { identifier, tier, keyType: 'concurrent' }, - }); - if (failOpenAllowed(identifier)) { - return { - allowed: true, - limit, - remaining: limit - 1, - resetAt: new Date(Date.now() + 3600000), - }; - } - return { - allowed: false, - limit, - remaining: 0, - resetAt: new Date(Date.now() + 3600000), - }; - } - } - - /** - * Release concurrent connection - */ - async releaseConcurrent( - identifier: string, - _tier: UserTier = 'free' - ): Promise { - const key = this.buildKey(identifier, 'concurrent'); - try { - await this.redis.decr(key); - } catch (error) { - console.error('Failed to release concurrent connection:', error); - } - } - - /** - * Reset limits (for testing or manual override) - */ - async reset(identifier: string): Promise { - const keys = [ - this.buildKey(identifier, 'minute'), - this.buildKey(identifier, 'day'), - this.buildKey(identifier, 'concurrent'), - ]; - - try { - await Promise.all(keys.map(key => this.redis.del(key))); - } catch (error) { - console.error('Failed to reset rate limits:', error); - } - } - - private buildKey(identifier: string, type: RateLimitKey): string { - return `ratelimit:${identifier}:${type}`; - } - - private getLimitForKey( - limits: typeof RATE_LIMITS[UserTier], - keyType: RateLimitKey - ): number { - switch (keyType) { - case 'minute': - return limits.requestsPerMinute; - case 'day': - return limits.requestsPerDay; - case 'concurrent': - return limits.concurrentConnections; - } - } - - private getTTLForKey(keyType: RateLimitKey): number { - switch (keyType) { - case 'minute': - return 60; - case 'day': - return 86400; - case 'concurrent': - return 3600; - } - } -} - -// Middleware function (framework-agnostic) -export async function rateLimitMiddleware( - getHeaders: () => Record, - getIP: () => string, - getUserTier: (userId: string) => Promise = async () => 'free' -): Promise<{ allowed: boolean; headers: Record }> { - const limiter = new RateLimiter(); - const headers = getHeaders(); - - // Extract user identifier - const userId = headers['x-user-id'] || - headers['authorization']?.split(' ')[1] || - getIP() || - 'anonymous'; - - // Get user tier - const tier = await getUserTier(userId); - - // Check rate limits - const minuteLimit = await limiter.checkLimit(userId, tier, 'minute'); - const dayLimit = await limiter.checkLimit(userId, tier, 'day'); - - // Build response headers - const responseHeaders: Record = { - 'X-RateLimit-Limit': String(minuteLimit.limit), - 'X-RateLimit-Remaining': String(minuteLimit.remaining), - 'X-RateLimit-Reset': minuteLimit.resetAt.toISOString(), - }; - - // Check if limited - if (!minuteLimit.allowed || !dayLimit.allowed) { - const status = !minuteLimit.allowed ? minuteLimit : dayLimit; - responseHeaders['Retry-After'] = String(status.retryAfter || 60); - responseHeaders['X-RateLimit-Remaining'] = '0'; - - return { - allowed: false, - headers: responseHeaders, - }; - } - - return { - allowed: true, - headers: responseHeaders, - }; -} - -// Client-side exponential backoff helper -export class RateLimitClient { - private static MIN_BACKOFF_MS = 1000; - private static MAX_BACKOFF_MS = 32000; - - /** - * Parse rate limit response and calculate backoff - */ - static getBackoffMs(response: Response): number { - // Check for explicit Retry-After header - const retryAfter = response.headers.get('Retry-After'); - if (retryAfter) { - const seconds = parseInt(retryAfter, 10); - return seconds * 1000; - } - - // Calculate from X-RateLimit-Reset - const resetAt = response.headers.get('X-RateLimit-Reset'); - if (resetAt) { - const resetTime = new Date(resetAt).getTime(); - const now = Date.now(); - const delay = Math.max(0, resetTime - now); - return delay + 100; // Add 100ms buffer - } - - // Default exponential backoff - return this.MIN_BACKOFF_MS; - } - - /** - * Exponential backoff with jitter - */ - static exponentialBackoff(attempt: number): number { - const exponential = Math.min( - this.MAX_BACKOFF_MS, - this.MIN_BACKOFF_MS * Math.pow(2, attempt) - ); - - // Add jitter (±10%) - const jitter = exponential * 0.1 * (Math.random() - 0.5) * 2; - return Math.round(exponential + jitter); - } - - /** - * Retry with backoff - */ - static async retryWithBackoff( - fn: () => Promise, - maxAttempts: number = 3 - ): Promise { - let lastError: Error | null = null; - - for (let attempt = 0; attempt < maxAttempts; attempt++) { - try { - const response = await fn(); - - if (response.status === 429) { - // Rate limited - if (attempt < maxAttempts - 1) { - const backoff = this.getBackoffMs(response); - await new Promise(resolve => setTimeout(resolve, backoff)); - continue; - } - } - - if (!response.ok) { - throw new Error(`HTTP ${response.status}: ${response.statusText}`); - } - - return response.json(); - } catch (error) { - lastError = error as Error; - - if (attempt < maxAttempts - 1) { - const backoff = this.exponentialBackoff(attempt); - await new Promise(resolve => setTimeout(resolve, backoff)); - } - } - } - - throw lastError || new Error('Max retries exceeded'); - } -} diff --git a/src/migration-runner.test.ts b/src/migration-runner.test.ts deleted file mode 100644 index 28d8f944..00000000 --- a/src/migration-runner.test.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { DatabaseManager, type DatabaseConfig } from "./database.js"; -import { MigrationRunner } from "./migration-runner.js"; -import { MIGRATIONS } from "./migrations.js"; - -describe("MigrationRunner", () => { - describe("initialization", () => { - let db: DatabaseManager; - let runner: MigrationRunner; - - beforeEach(async () => { - const config: DatabaseConfig = { - host: "localhost", - port: 5432, - database: "postgres", - user: "postgres", - password: "password", - }; - db = new DatabaseManager(config); - await db.connect(); - runner = new MigrationRunner(db); - }); - - it("initializes migration tracker", async () => { - await runner.init(); - const status = await runner.getStatus(); - assert(status.total > 0); - }); - - it("creates migrations table", async () => { - await runner.init(); - const result = await db.query("SELECT 1 FROM schema_migrations LIMIT 1"); - assert(result.executionTime >= 0); - }); - }); - - describe("migration management", () => { - let db: DatabaseManager; - let runner: MigrationRunner; - - beforeEach(async () => { - const config: DatabaseConfig = { - host: "localhost", - port: 5432, - database: "postgres", - user: "postgres", - password: "password", - }; - db = new DatabaseManager(config); - await db.connect(); - runner = new MigrationRunner(db); - await runner.init(); - }); - - it("gets all migrations", () => { - const migrations = MIGRATIONS; - assert(migrations.length > 0); - }); - - it("identifies pending migrations", async () => { - const pending = runner.getPendingMigrations(); - assert(pending.length > 0); - }); - - it("identifies executed migrations", async () => { - const executed = runner.getExecutedMigrations(); - assert(Array.isArray(executed)); - }); - - it("distinguishes pending from executed", async () => { - const pending = runner.getPendingMigrations(); - const executed = runner.getExecutedMigrations(); - const total = pending.length + executed.length; - assert.equal(total, MIGRATIONS.length); - }); - }); - - describe("status tracking", () => { - let db: DatabaseManager; - let runner: MigrationRunner; - - beforeEach(async () => { - const config: DatabaseConfig = { - host: "localhost", - port: 5432, - database: "kit_test", - user: "postgres", - password: "password", - }; - db = new DatabaseManager(config); - await db.connect(); - runner = new MigrationRunner(db); - await runner.init(); - }); - - it("returns migration status", async () => { - const status = await runner.getStatus(); - assert(typeof status.executed === "number"); - assert(typeof status.pending === "number"); - assert(typeof status.failed === "number"); - assert.equal(status.total, MIGRATIONS.length); - }); - - it("tracks executed migrations", async () => { - const status = await runner.getStatus(); - assert(status.executed >= 0); - }); - - it("tracks pending migrations", async () => { - const status = await runner.getStatus(); - assert(status.pending >= 0); - }); - - it("sums to total", async () => { - const status = await runner.getStatus(); - assert(status.executed + status.pending + status.failed >= status.executed); - }); - }); - - describe("migration execution", () => { - let db: DatabaseManager; - let runner: MigrationRunner; - - beforeEach(async () => { - const config: DatabaseConfig = { - host: "localhost", - port: 5432, - database: "kit_test", - user: "postgres", - password: "password", - }; - db = new DatabaseManager(config); - await db.connect(); - runner = new MigrationRunner(db); - await runner.init(); - }); - - it("runs pending migrations", async () => { - const result = await runner.runPending(); - assert(typeof result.executed === "number"); - assert(typeof result.failed === "number"); - assert(typeof result.total === "number"); - }); - - it("tracks execution status", async () => { - const before = await runner.getStatus(); - await runner.runPending(); - const after = await runner.getStatus(); - assert(after.executed >= before.executed); - }); - - it("returns error list", async () => { - const result = await runner.runPending(); - assert(Array.isArray(result.errors)); - }); - - it("runs individual migration", async () => { - const pending = runner.getPendingMigrations(); - if (pending.length > 0) { - const result = await runner.runMigration(pending[0].id); - assert(typeof result.success === "boolean"); - } - }); - - it("prevents re-execution of migrations", async () => { - const pending = runner.getPendingMigrations(); - if (pending.length > 0) { - // First run should succeed - const result1 = await runner.runMigration(pending[0].id); - - if (result1.success) { - // Second run should fail - const result2 = await runner.runMigration(pending[0].id); - assert(!result2.success); - } - } - }); - }); - - describe("migration report", () => { - let db: DatabaseManager; - let runner: MigrationRunner; - - beforeEach(async () => { - const config: DatabaseConfig = { - host: "localhost", - port: 5432, - database: "kit_test", - user: "postgres", - password: "password", - }; - db = new DatabaseManager(config); - await db.connect(); - runner = new MigrationRunner(db); - await runner.init(); - }); - - it("generates report without error", async () => { - assert.doesNotThrow(async () => { - await runner.printReport(); - }); - }); - - it("lists executed migrations", async () => { - const executed = runner.getExecutedMigrations(); - assert(Array.isArray(executed)); - }); - - it("lists pending migrations", async () => { - const pending = runner.getPendingMigrations(); - assert(Array.isArray(pending)); - }); - }); - - describe("backup support", () => { - let db: DatabaseManager; - - beforeEach(async () => { - const config: DatabaseConfig = { - host: "localhost", - port: 5432, - database: "kit_test", - user: "postgres", - password: "password", - }; - db = new DatabaseManager(config); - await db.connect(); - }); - - it("createBackup is not implemented (throws)", async () => { - await assert.rejects(() => db.createBackup("test"), /not implemented/i); - }); - - it("restoreBackup is not implemented (throws)", async () => { - await assert.rejects(() => db.restoreBackup("backups/test.sql"), /not implemented/i); - }); - }); -}); diff --git a/src/migration-runner.ts b/src/migration-runner.ts deleted file mode 100644 index 86bdb509..00000000 --- a/src/migration-runner.ts +++ /dev/null @@ -1,256 +0,0 @@ -// ─── Migration Runner ──────────────────────────────────────────────────────── - -import { DatabaseManager } from "./database.js"; -import { MIGRATIONS } from "./migrations.js"; - -/** - * Migration runner with status tracking and rollback support. - */ -export class MigrationRunner { - private db: DatabaseManager; - private executedMigrations: Set = new Set(); - - constructor(db: DatabaseManager) { - this.db = db; - } - - /** - * Initialize migration tracking tables and load executed migrations. - */ - async init(): Promise { - // Create migrations table if not exists - await this.db.query(` - CREATE TABLE IF NOT EXISTS schema_migrations ( - id VARCHAR(255) PRIMARY KEY, - name VARCHAR(255) NOT NULL, - version VARCHAR(20) NOT NULL, - executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - rolled_back_at TIMESTAMP, - execution_time INTEGER, - status VARCHAR(20) DEFAULT 'success' - ) - `); - - // Load executed migrations - const result = await this.db.query( - "SELECT id FROM schema_migrations WHERE rolled_back_at IS NULL AND status = 'success'", - ); - - for (const row of result.rows) { - this.executedMigrations.add((row as any).id); - } - } - - /** - * Get list of pending migrations. - */ - getPendingMigrations(): typeof MIGRATIONS { - return MIGRATIONS.filter((m) => !this.executedMigrations.has(m.id)); - } - - /** - * Get list of executed migrations. - */ - getExecutedMigrations(): typeof MIGRATIONS { - return MIGRATIONS.filter((m) => this.executedMigrations.has(m.id)); - } - - /** - * Run all pending migrations. - */ - async runPending(): Promise<{ - executed: number; - failed: number; - total: number; - errors: Array<{ migration: string; error: string }>; - }> { - await this.init(); - - const pending = this.getPendingMigrations(); - const errors: Array<{ migration: string; error: string }> = []; - let executed = 0; - - for (const migration of pending) { - try { - const startTime = Date.now(); - - // Execute migration in transaction - await this.db.transaction(async (db) => { - await db.query(migration.sql); - await db.query( - `INSERT INTO schema_migrations (id, name, version, execution_time, status) - VALUES ($1, $2, $3, $4, 'success')`, - [migration.id, migration.name, migration.version, Date.now() - startTime], - ); - }); - - this.executedMigrations.add(migration.id); - executed++; - - console.log(`✓ ${migration.name}`); - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - errors.push({ - migration: migration.name, - error: errorMsg, - }); - - // Mark as failed - await this.db.query( - `INSERT INTO schema_migrations (id, name, version, status) - VALUES ($1, $2, $3, 'failed')`, - [migration.id, migration.name, migration.version], - ); - - console.error(`✗ ${migration.name}: ${errorMsg}`); - } - } - - return { - executed, - failed: errors.length, - total: pending.length, - errors, - }; - } - - /** - * Run a specific migration by ID. - */ - async runMigration(migrationId: string): Promise<{ success: boolean; error?: string }> { - await this.init(); - - const migration = MIGRATIONS.find((m) => m.id === migrationId); - if (!migration) { - return { success: false, error: `Migration ${migrationId} not found` }; - } - - if (this.executedMigrations.has(migrationId)) { - return { success: false, error: `Migration ${migrationId} already executed` }; - } - - try { - const startTime = Date.now(); - - await this.db.transaction(async (db) => { - await db.query(migration.sql); - await db.query( - `INSERT INTO schema_migrations (id, name, version, execution_time, status) - VALUES ($1, $2, $3, $4, 'success')`, - [migration.id, migration.name, migration.version, Date.now() - startTime], - ); - }); - - this.executedMigrations.add(migrationId); - console.log(`✓ ${migration.name}`); - return { success: true }; - } catch (error) { - const errorMsg = error instanceof Error ? error.message : String(error); - await this.db.query( - `INSERT INTO schema_migrations (id, name, version, status) - VALUES ($1, $2, $3, 'failed')`, - [migration.id, migration.name, migration.version], - ); - - console.error(`✗ ${migration.name}: ${errorMsg}`); - return { success: false, error: errorMsg }; - } - } - - /** - * Get migration status summary. - */ - async getStatus(): Promise<{ - executed: number; - pending: number; - failed: number; - total: number; - }> { - await this.init(); - - const failedResult = await this.db.query( - "SELECT COUNT(*) as count FROM schema_migrations WHERE status = 'failed'", - ); - const failedCount = (failedResult.rows[0] as any)?.count || 0; - - return { - executed: this.executedMigrations.size, - pending: this.getPendingMigrations().length, - failed: failedCount, - total: MIGRATIONS.length, - }; - } - - /** - * Print migration report to console. - */ - async printReport(): Promise { - const status = await this.getStatus(); - const executed = this.getExecutedMigrations(); - const pending = this.getPendingMigrations(); - - console.log("\n┌─ Migration Status ─────────────────────────────────────────┐"); - console.log(`│ Executed: ${String(status.executed).padEnd(50)} │`); - console.log(`│ Pending: ${String(status.pending).padEnd(50)} │`); - console.log(`│ Failed: ${String(status.failed).padEnd(50)} │`); - console.log(`│ Total: ${String(status.total).padEnd(50)} │`); - console.log("└────────────────────────────────────────────────────────────┘\n"); - - if (executed.length > 0) { - console.log("Executed Migrations:"); - for (const m of executed) { - console.log(` ✓ ${m.id}: ${m.name}`); - } - console.log(); - } - - if (pending.length > 0) { - console.log("Pending Migrations:"); - for (const m of pending) { - console.log(` ○ ${m.id}: ${m.name}`); - } - console.log(); - } - } -} - -/** - * Create backup before migrations. - */ -export async function createPreMigrationBackup(db: DatabaseManager): Promise { - const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); - const backupName = `pre-migration-${timestamp}`; - const result = await db.createBackup(backupName); - return result.backupFile; -} - -/** - * Run migrations with backup strategy. - */ -export async function runMigrationsWithBackup( - db: DatabaseManager, -): Promise<{ success: boolean; backupFile?: string; errors?: string[] }> { - // Create backup - const backupFile = await createPreMigrationBackup(db); - console.log(`Backup created: ${backupFile}`); - - // Run migrations - const runner = new MigrationRunner(db); - const result = await runner.runPending(); - - if (result.failed > 0) { - console.error("\nMigrations failed! Consider restoring backup:"); - console.error(` db.restoreBackup('${backupFile}')`); - - return { - success: false, - backupFile, - errors: result.errors.map((e) => `${e.migration}: ${e.error}`), - }; - } - - console.log(`\n${result.executed} migrations executed successfully`); - await runner.printReport(); - - return { success: true, backupFile }; -} diff --git a/src/multi-agent-workflow-model.ts b/src/multi-agent-workflow-model.ts deleted file mode 100644 index 59fa4503..00000000 --- a/src/multi-agent-workflow-model.ts +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Multi-Agent Workflows — data models - * Orchestrate complex tasks across multiple agents with coordination and state management - */ - -export type WorkflowStatus = "draft" | "active" | "paused" | "completed" | "failed" | "cancelled"; -export type TaskStatus = - | "pending" - | "assigned" - | "in_progress" - | "completed" - | "failed" - | "skipped" - | "waiting"; -export type CoordinationType = "sequential" | "parallel" | "fan_out" | "conditional"; -export type AgentRole = "primary" | "secondary" | "reviewer" | "observer"; - -export interface WorkflowTask { - id: string; - workflow_id: string; - task_name: string; - description: string; - sequence_order: number; - status: TaskStatus; - assigned_agent_id?: string; - assigned_agent_type?: string; // claude, cursor, cline - dependencies: string[]; // task IDs this depends on - input_data?: Record; - output_data?: Record; - error_message?: string; - retry_count: number; - max_retries: number; - timeout_minutes: number; - started_at?: string; - completed_at?: string; - created_at: string; - updated_at: string; -} - -export interface WorkflowCoordination { - id: string; - workflow_id: string; - coordination_type: CoordinationType; - condition?: string; // Expression for conditional coordination - parallel_tasks: string[]; // Task IDs for parallel execution - sequential_tasks: string[]; // Ordered task IDs for sequential - fan_out_source_task?: string; // Source task for fan-out - fan_out_targets?: string[]; // Target task IDs - created_at: string; - updated_at: string; -} - -export interface MultiAgentWorkflow { - id: string; - team_id: string; - workflow_name: string; - description?: string; - status: WorkflowStatus; - tasks: WorkflowTask[]; - coordination: WorkflowCoordination[]; - agents: { - agent_id: string; - agent_type: string; - role: AgentRole; - assigned_tasks: string[]; - }[]; - input_data?: Record; - output_data?: Record; - max_parallel_tasks: number; - timeout_minutes: number; - created_by: string; - started_at?: string; - completed_at?: string; - estimated_completion?: string; - created_at: string; - updated_at: string; -} - -export interface WorkflowExecution { - id: string; - workflow_id: string; - team_id: string; - execution_status: WorkflowStatus; - tasks_completed: number; - tasks_failed: number; - tasks_pending: number; - overall_progress_percent: number; - started_at: string; - completed_at?: string; - duration_minutes?: number; - error_count: number; - warning_count: number; - created_at: string; - updated_at: string; -} - -export interface AgentCoordination { - id: string; - workflow_id: string; - team_id: string; - agents: { - agent_id: string; - agent_type: string; - role: AgentRole; - }[]; - shared_context: Record; - handoff_enabled: boolean; - result_aggregation_mode: "merge" | "sequential" | "consensus"; - active: boolean; - created_at: string; - updated_at: string; -} - -export interface WorkflowMetrics { - total_workflows: number; - active_workflows: number; - completed_workflows: number; - failed_workflows: number; - average_duration_minutes: number; - average_tasks_per_workflow: number; - most_used_coordination_type: CoordinationType; - agent_utilization_percent: number; - success_rate_percent: number; - average_retries: number; -} - -export interface WorkflowTemplate { - id: string; - template_name: string; - description?: string; - category: string; - tasks: Omit[]; - coordination: Omit[]; - required_agents: number; - estimated_duration_minutes: number; - complexity: "simple" | "moderate" | "complex"; - public: boolean; - created_at: string; - updated_at: string; -} diff --git a/src/multi-agent-workflow-service.test.ts b/src/multi-agent-workflow-service.test.ts deleted file mode 100644 index cfcf8b1f..00000000 --- a/src/multi-agent-workflow-service.test.ts +++ /dev/null @@ -1,455 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { - createWorkflow, - addWorkflowTask, - assignAgentToTask, - setupCoordination, - executeWorkflow, - completeTask, - failTask, - getWorkflowStatus, - getTaskStatus, - pauseWorkflow, - resumeWorkflow, - cancelWorkflow, - createWorkflowFromTemplate, - listWorkflowTemplates, - getWorkflowMetrics, -} from "./multi-agent-workflow-service.js"; - -describe("multi-agent-workflow-service", () => { - const teamId = "team-workflow-123"; - const userId = "user-workflow-456"; - - describe("createWorkflow", () => { - it("creates new workflow", () => { - const { workflow, error } = createWorkflow( - teamId, - "Test Workflow", - userId, - "A test workflow", - ); - - assert.ok(!error); - assert.ok(workflow.id); - assert.equal(workflow.team_id, teamId); - assert.equal(workflow.workflow_name, "Test Workflow"); - assert.equal(workflow.status, "draft"); - assert.ok(workflow.created_at); - }); - }); - - describe("addWorkflowTask", () => { - it("adds task to workflow", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - - const { task, error } = addWorkflowTask( - teamId, - workflow.id, - "Task 1", - "First task", - 1, - ); - - assert.ok(!error); - assert.ok(task.id); - assert.equal(task.workflow_id, workflow.id); - assert.equal(task.status, "pending"); - }); - - it("fails for nonexistent workflow", () => { - const { error } = addWorkflowTask( - teamId, - "nonexistent-workflow", - "Task", - "Description", - 1, - ); - - assert.ok(error); - assert.equal(error, "Workflow not found"); - }); - - it("adds task with dependencies", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task 1", "First", 1); - const { task: task2 } = addWorkflowTask( - teamId, - workflow.id, - "Task 2", - "Second", - 2, - [task1.id], - ); - - assert.deepEqual(task2.dependencies, [task1.id]); - }); - }); - - describe("assignAgentToTask", () => { - it("assigns agent to task", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: workflowTask } = addWorkflowTask( - teamId, - workflow.id, - "Task", - "Description", - 1, - ); - - const { task, error } = assignAgentToTask( - teamId, - workflow.id, - workflowTask.id, - "agent-123", - "claude", - ); - - assert.ok(!error); - assert.equal(task.assigned_agent_id, "agent-123"); - assert.equal(task.assigned_agent_type, "claude"); - assert.equal(task.status, "assigned"); - }); - - it("adds agent to workflow", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: workflowTask } = addWorkflowTask( - teamId, - workflow.id, - "Task", - "Description", - 1, - ); - - assignAgentToTask(teamId, workflow.id, workflowTask.id, "agent-123", "claude"); - - const { workflow: updated } = getWorkflowStatus(teamId, workflow.id); - assert.ok(updated?.agents.some((a) => a.agent_id === "agent-123")); - }); - }); - - describe("setupCoordination", () => { - it("sets up sequential coordination", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task 1", "First", 1); - const { task: task2 } = addWorkflowTask(teamId, workflow.id, "Task 2", "Second", 2); - - const { coordination, error } = setupCoordination( - teamId, - workflow.id, - "sequential", - [task1.id, task2.id], - ); - - assert.ok(!error); - assert.equal(coordination.coordination_type, "sequential"); - assert.deepEqual(coordination.sequential_tasks, [task1.id, task2.id]); - }); - - it("sets up parallel coordination", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task 1", "First", 1); - const { task: task2 } = addWorkflowTask(teamId, workflow.id, "Task 2", "Second", 1); - - const { coordination } = setupCoordination( - teamId, - workflow.id, - "parallel", - [task1.id, task2.id], - ); - - assert.equal(coordination.coordination_type, "parallel"); - assert.deepEqual(coordination.parallel_tasks, [task1.id, task2.id]); - }); - }); - - describe("executeWorkflow", () => { - it("executes workflow and starts root tasks", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - addWorkflowTask(teamId, workflow.id, "Task 1", "First", 1); - - const { execution, error } = executeWorkflow(teamId, workflow.id); - - assert.ok(!error); - assert.ok(execution.id); - assert.equal(execution.execution_status, "active"); - assert.ok(execution.started_at); - }); - - it("fails for workflow with no tasks", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - - const { error } = executeWorkflow(teamId, workflow.id); - - assert.ok(error); - assert.equal(error, "Workflow has no tasks"); - }); - - it("passes input data to workflow", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - addWorkflowTask(teamId, workflow.id, "Task", "Desc", 1); - const input = { param1: "value1" }; - - executeWorkflow(teamId, workflow.id, input); - - const { workflow: updated } = getWorkflowStatus(teamId, workflow.id); - assert.deepEqual(updated?.input_data, input); - }); - }); - - describe("completeTask", () => { - it("completes task", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task", "Desc", 1); - - const { task, error } = completeTask(teamId, workflow.id, task1.id); - - assert.ok(!error); - assert.equal(task.status, "completed"); - assert.ok(task.completed_at); - }); - - it("unlocks dependent tasks", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task 1", "First", 1); - const { task: task2 } = addWorkflowTask( - teamId, - workflow.id, - "Task 2", - "Second", - 2, - [task1.id], - ); - - executeWorkflow(teamId, workflow.id); - completeTask(teamId, workflow.id, task1.id); - - const { task } = getTaskStatus(teamId, workflow.id, task2.id); - assert.equal(task?.status, "in_progress"); - }); - - it("marks workflow complete when all tasks done", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task", "Desc", 1); - - executeWorkflow(teamId, workflow.id); - completeTask(teamId, workflow.id, task1.id); - - const { workflow: updated } = getWorkflowStatus(teamId, workflow.id); - assert.equal(updated?.status, "completed"); - }); - - it("stores output data", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task", "Desc", 1); - const output = { result: "success" }; - - completeTask(teamId, workflow.id, task1.id, output); - - const { task } = getTaskStatus(teamId, workflow.id, task1.id); - assert.deepEqual(task?.output_data, output); - }); - }); - - describe("failTask", () => { - it("fails task after max retries", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task", "Desc", 1); - - failTask(teamId, workflow.id, task1.id, "Error 1"); - failTask(teamId, workflow.id, task1.id, "Error 2"); - failTask(teamId, workflow.id, task1.id, "Error 3"); - - const { task } = getTaskStatus(teamId, workflow.id, task1.id); - assert.equal(task?.status, "failed"); - assert.equal(task?.error_message, "Error 3"); - }); - - it("retries task if below max retries", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task", "Desc", 1); - - failTask(teamId, workflow.id, task1.id, "Error"); - - const { task } = getTaskStatus(teamId, workflow.id, task1.id); - assert.equal(task?.status, "pending"); - assert.equal(task?.retry_count, 1); - }); - - it("marks workflow as failed", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task", "Desc", 1); - - failTask(teamId, workflow.id, task1.id, "Error 1"); - failTask(teamId, workflow.id, task1.id, "Error 2"); - failTask(teamId, workflow.id, task1.id, "Error 3"); - - const { workflow: updated } = getWorkflowStatus(teamId, workflow.id); - assert.equal(updated?.status, "failed"); - }); - }); - - describe("getWorkflowStatus", () => { - it("gets workflow status", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - - const { workflow: fetched, error } = getWorkflowStatus(teamId, workflow.id); - - assert.ok(!error); - assert.equal(fetched?.id, workflow.id); - }); - - it("fails for nonexistent workflow", () => { - const { workflow, error } = getWorkflowStatus(teamId, "nonexistent"); - - assert.ok(error); - assert.equal(error, "Workflow not found"); - assert.ok(!workflow); - }); - }); - - describe("getTaskStatus", () => { - it("gets task status", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - const { task: task1 } = addWorkflowTask(teamId, workflow.id, "Task", "Desc", 1); - - const { task, error } = getTaskStatus(teamId, workflow.id, task1.id); - - assert.ok(!error); - assert.equal(task?.id, task1.id); - }); - - it("fails for nonexistent task", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - - const { task, error } = getTaskStatus(teamId, workflow.id, "nonexistent"); - - assert.ok(error); - assert.ok(!task); - }); - }); - - describe("pauseWorkflow", () => { - it("pauses workflow", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - - const { workflow: paused, error } = pauseWorkflow(teamId, workflow.id); - - assert.ok(!error); - assert.equal(paused.status, "paused"); - }); - }); - - describe("resumeWorkflow", () => { - it("resumes paused workflow", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - pauseWorkflow(teamId, workflow.id); - - const { workflow: resumed, error } = resumeWorkflow(teamId, workflow.id); - - assert.ok(!error); - assert.equal(resumed.status, "active"); - }); - - it("fails if workflow not paused", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - - const { error } = resumeWorkflow(teamId, workflow.id); - - assert.ok(error); - assert.equal(error, "Workflow is not paused"); - }); - }); - - describe("cancelWorkflow", () => { - it("cancels workflow", () => { - const { workflow } = createWorkflow(teamId, "Workflow", userId); - - const { workflow: cancelled, error } = cancelWorkflow(teamId, workflow.id); - - assert.ok(!error); - assert.equal(cancelled.status, "cancelled"); - assert.ok(cancelled.completed_at); - }); - }); - - describe("createWorkflowFromTemplate", () => { - it("creates workflow from template", () => { - const { templates } = listWorkflowTemplates(); - assert.ok(templates.length > 0); - - const { workflow, error } = createWorkflowFromTemplate( - teamId, - templates[0].id, - "From Template", - userId, - ); - - assert.ok(!error); - assert.ok(workflow.id); - assert.ok(workflow.tasks.length > 0); - assert.ok(workflow.coordination.length > 0); - }); - - it("fails for nonexistent template", () => { - const { error } = createWorkflowFromTemplate( - teamId, - "nonexistent-template", - "Workflow", - userId, - ); - - assert.ok(error); - assert.equal(error, "Template not found"); - }); - }); - - describe("listWorkflowTemplates", () => { - it("lists available templates", () => { - const { templates } = listWorkflowTemplates(); - - assert.ok(templates.length > 0); - assert.ok(templates.some((t) => t.template_name.includes("Code Review"))); - assert.ok(templates.some((t) => t.template_name.includes("Data Pipeline"))); - }); - - it("includes template metadata", () => { - const { templates } = listWorkflowTemplates(); - - templates.forEach((t) => { - assert.ok(t.id); - assert.ok(t.template_name); - assert.ok(t.tasks.length > 0); - assert.ok(t.required_agents > 0); - }); - }); - }); - - describe("getWorkflowMetrics", () => { - it("returns workflow metrics", () => { - const team2 = "team-workflow-metrics"; - createWorkflow(team2, "Workflow 1", userId); - createWorkflow(team2, "Workflow 2", userId); - - const metrics = getWorkflowMetrics(team2); - - assert.equal(metrics.total_workflows, 2); - assert.ok(metrics.success_rate_percent >= 0); - assert.ok(metrics.average_duration_minutes > 0); - assert.ok(metrics.average_tasks_per_workflow >= 0); - }); - - it("calculates success rate", () => { - const team3 = "team-workflow-success"; - const { workflow } = createWorkflow(team3, "Workflow", userId); - const { task } = addWorkflowTask(team3, workflow.id, "Task", "Desc", 1); - - executeWorkflow(team3, workflow.id); - completeTask(team3, workflow.id, task.id); - - const metrics = getWorkflowMetrics(team3); - assert.equal(metrics.success_rate_percent, 100); - }); - }); -}); diff --git a/src/multi-agent-workflow-service.ts b/src/multi-agent-workflow-service.ts deleted file mode 100644 index 65a96cbd..00000000 --- a/src/multi-agent-workflow-service.ts +++ /dev/null @@ -1,594 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { - MultiAgentWorkflow, - WorkflowTask, - WorkflowCoordination, - WorkflowExecution, - WorkflowMetrics, - WorkflowTemplate, -} from "./multi-agent-workflow-model.js"; - -const workflows = new Map(); -const executions = new Map(); -const templates = new Map(); - -// Default workflow templates -const DEFAULT_TEMPLATES: WorkflowTemplate[] = [ - { - id: `template_${randomUUID()}`, - template_name: "Code Review Pipeline", - description: "Multi-stage code review with multiple agents", - category: "development", - tasks: [ - { - task_name: "Analyze Code", - description: "Static analysis and linting", - sequence_order: 1, - status: "pending", - dependencies: [], - retry_count: 0, - max_retries: 2, - timeout_minutes: 15, - }, - { - task_name: "Security Review", - description: "Security vulnerability assessment", - sequence_order: 2, - status: "pending", - dependencies: ["task_1"], - retry_count: 0, - max_retries: 1, - timeout_minutes: 20, - }, - { - task_name: "Performance Review", - description: "Performance and optimization check", - sequence_order: 3, - status: "pending", - dependencies: ["task_1"], - retry_count: 0, - max_retries: 1, - timeout_minutes: 15, - }, - { - task_name: "Approve Changes", - description: "Final approval and merge", - sequence_order: 4, - status: "pending", - dependencies: ["task_2", "task_3"], - retry_count: 0, - max_retries: 0, - timeout_minutes: 10, - }, - ], - coordination: [ - { - coordination_type: "sequential", - sequential_tasks: ["task_1", "task_2", "task_3", "task_4"], - }, - ] as any, - required_agents: 3, - estimated_duration_minutes: 60, - complexity: "moderate", - public: true, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, - { - id: `template_${randomUUID()}`, - template_name: "Data Pipeline Processing", - description: "Parallel data processing with aggregation", - category: "data", - tasks: [ - { - task_name: "Extract Data", - description: "Extract data from sources", - sequence_order: 1, - status: "pending", - dependencies: [], - retry_count: 0, - max_retries: 3, - timeout_minutes: 30, - }, - { - task_name: "Transform Data A", - description: "Transform subset A", - sequence_order: 2, - status: "pending", - dependencies: ["task_1"], - retry_count: 0, - max_retries: 2, - timeout_minutes: 20, - }, - { - task_name: "Transform Data B", - description: "Transform subset B", - sequence_order: 2, - status: "pending", - dependencies: ["task_1"], - retry_count: 0, - max_retries: 2, - timeout_minutes: 20, - }, - { - task_name: "Merge Results", - description: "Merge transformed data", - sequence_order: 3, - status: "pending", - dependencies: ["task_2", "task_3"], - retry_count: 0, - max_retries: 1, - timeout_minutes: 15, - }, - ], - coordination: [ - { - coordination_type: "parallel", - parallel_tasks: ["task_2", "task_3"], - }, - ] as any, - required_agents: 2, - estimated_duration_minutes: 90, - complexity: "moderate", - public: true, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }, -]; - -DEFAULT_TEMPLATES.forEach((template) => templates.set(template.id, template)); - -/** - * Create new workflow - */ -export function createWorkflow( - team_id: string, - workflow_name: string, - created_by: string, - description?: string, -): { workflow: MultiAgentWorkflow; error?: string } { - const workflow: MultiAgentWorkflow = { - id: `workflow_${randomUUID()}`, - team_id, - workflow_name, - description, - status: "draft", - tasks: [], - coordination: [], - agents: [], - input_data: {}, - output_data: {}, - max_parallel_tasks: 3, - timeout_minutes: 120, - created_by, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - workflows.set(workflow.id, workflow); - return { workflow }; -} - -/** - * Add task to workflow - */ -export function addWorkflowTask( - team_id: string, - workflow_id: string, - task_name: string, - description: string, - sequence_order: number, - dependencies: string[] = [], - timeout_minutes: number = 30, -): { task: WorkflowTask; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { task: {} as WorkflowTask, error: "Workflow not found" }; - } - - const task: WorkflowTask = { - id: `task_${randomUUID()}`, - workflow_id, - task_name, - description, - sequence_order, - status: "pending", - dependencies, - retry_count: 0, - max_retries: 2, - timeout_minutes, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - workflow.tasks.push(task); - workflow.updated_at = new Date().toISOString(); - - return { task }; -} - -/** - * Assign agent to task - */ -export function assignAgentToTask( - team_id: string, - workflow_id: string, - task_id: string, - agent_id: string, - agent_type: string, -): { task: WorkflowTask; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { task: {} as WorkflowTask, error: "Workflow not found" }; - } - - const task = workflow.tasks.find((t) => t.id === task_id); - if (!task) { - return { task: {} as WorkflowTask, error: "Task not found" }; - } - - task.assigned_agent_id = agent_id; - task.assigned_agent_type = agent_type; - task.status = "assigned"; - task.updated_at = new Date().toISOString(); - - // Add agent to workflow if not present - if (!workflow.agents.some((a) => a.agent_id === agent_id)) { - workflow.agents.push({ - agent_id, - agent_type, - role: "primary", - assigned_tasks: [task_id], - }); - } else { - const agent = workflow.agents.find((a) => a.agent_id === agent_id)!; - if (!agent.assigned_tasks.includes(task_id)) { - agent.assigned_tasks.push(task_id); - } - } - - workflow.updated_at = new Date().toISOString(); - - return { task }; -} - -/** - * Setup workflow coordination - */ -export function setupCoordination( - team_id: string, - workflow_id: string, - coordination_type: string, - task_ids: string[], -): { coordination: WorkflowCoordination; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { coordination: {} as WorkflowCoordination, error: "Workflow not found" }; - } - - const coordination: WorkflowCoordination = { - id: `coord_${randomUUID()}`, - workflow_id, - coordination_type: coordination_type as any, - sequential_tasks: coordination_type === "sequential" ? task_ids : [], - parallel_tasks: coordination_type === "parallel" ? task_ids : [], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - workflow.coordination.push(coordination); - workflow.updated_at = new Date().toISOString(); - - return { coordination }; -} - -/** - * Execute workflow - */ -export function executeWorkflow( - team_id: string, - workflow_id: string, - input_data?: Record, -): { execution: WorkflowExecution; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { execution: {} as WorkflowExecution, error: "Workflow not found" }; - } - - if (workflow.tasks.length === 0) { - return { execution: {} as WorkflowExecution, error: "Workflow has no tasks" }; - } - - // Update workflow status - workflow.status = "active"; - workflow.started_at = new Date().toISOString(); - if (input_data) { - workflow.input_data = input_data; - } - - // Start first tasks (no dependencies) - const rootTasks = workflow.tasks.filter((t) => t.dependencies.length === 0); - rootTasks.forEach((t) => { - t.status = "in_progress"; - t.started_at = new Date().toISOString(); - }); - - // Create execution record - const execution: WorkflowExecution = { - id: `exec_${randomUUID()}`, - workflow_id, - team_id, - execution_status: "active", - tasks_completed: 0, - tasks_failed: 0, - tasks_pending: workflow.tasks.length, - overall_progress_percent: 0, - started_at: new Date().toISOString(), - error_count: 0, - warning_count: 0, - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - }; - - executions.set(execution.id, execution); - workflow.updated_at = new Date().toISOString(); - - return { execution }; -} - -/** - * Complete task - */ -export function completeTask( - team_id: string, - workflow_id: string, - task_id: string, - output_data?: Record, -): { task: WorkflowTask; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { task: {} as WorkflowTask, error: "Workflow not found" }; - } - - const task = workflow.tasks.find((t) => t.id === task_id); - if (!task) { - return { task: {} as WorkflowTask, error: "Task not found" }; - } - - task.status = "completed"; - task.completed_at = new Date().toISOString(); - if (output_data) { - task.output_data = output_data; - } - - // Unlock dependent tasks - const dependentTasks = workflow.tasks.filter((t) => t.dependencies.includes(task_id)); - dependentTasks.forEach((t) => { - const allDependenciesMet = t.dependencies.every((depId) => { - const depTask = workflow.tasks.find((dt) => dt.id === depId); - return depTask?.status === "completed"; - }); - - if (allDependenciesMet && t.status === "pending") { - t.status = "in_progress"; - t.started_at = new Date().toISOString(); - } - }); - - // Update workflow - const allCompleted = workflow.tasks.every((t) => t.status === "completed" || t.status === "skipped"); - if (allCompleted) { - workflow.status = "completed"; - workflow.completed_at = new Date().toISOString(); - } - - workflow.updated_at = new Date().toISOString(); - - return { task }; -} - -/** - * Fail task - */ -export function failTask( - team_id: string, - workflow_id: string, - task_id: string, - error_message: string, -): { task: WorkflowTask; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { task: {} as WorkflowTask, error: "Workflow not found" }; - } - - const task = workflow.tasks.find((t) => t.id === task_id); - if (!task) { - return { task: {} as WorkflowTask, error: "Task not found" }; - } - - if (task.retry_count < task.max_retries) { - task.retry_count += 1; - task.status = "pending"; - task.error_message = undefined; - } else { - task.status = "failed"; - task.error_message = error_message; - workflow.status = "failed"; - } - - workflow.updated_at = new Date().toISOString(); - - return { task }; -} - -/** - * Get workflow status - */ -export function getWorkflowStatus( - team_id: string, - workflow_id: string, -): { workflow: MultiAgentWorkflow | null; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { workflow: null, error: "Workflow not found" }; - } - return { workflow }; -} - -/** - * Get task status - */ -export function getTaskStatus( - team_id: string, - workflow_id: string, - task_id: string, -): { task: WorkflowTask | null; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { task: null, error: "Workflow not found" }; - } - - const task = workflow.tasks.find((t) => t.id === task_id); - return { task: task || null, error: task ? undefined : "Task not found" }; -} - -/** - * Pause workflow - */ -export function pauseWorkflow( - team_id: string, - workflow_id: string, -): { workflow: MultiAgentWorkflow; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { workflow: {} as MultiAgentWorkflow, error: "Workflow not found" }; - } - - workflow.status = "paused"; - workflow.updated_at = new Date().toISOString(); - - return { workflow }; -} - -/** - * Resume workflow - */ -export function resumeWorkflow( - team_id: string, - workflow_id: string, -): { workflow: MultiAgentWorkflow; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { workflow: {} as MultiAgentWorkflow, error: "Workflow not found" }; - } - - if (workflow.status !== "paused") { - return { workflow: {} as MultiAgentWorkflow, error: "Workflow is not paused" }; - } - - workflow.status = "active"; - workflow.updated_at = new Date().toISOString(); - - return { workflow }; -} - -/** - * Cancel workflow - */ -export function cancelWorkflow( - team_id: string, - workflow_id: string, -): { workflow: MultiAgentWorkflow; error?: string } { - const workflow = workflows.get(workflow_id); - if (!workflow || workflow.team_id !== team_id) { - return { workflow: {} as MultiAgentWorkflow, error: "Workflow not found" }; - } - - workflow.status = "cancelled"; - workflow.completed_at = new Date().toISOString(); - workflow.updated_at = new Date().toISOString(); - - return { workflow }; -} - -/** - * Create workflow from template - */ -export function createWorkflowFromTemplate( - team_id: string, - template_id: string, - workflow_name: string, - created_by: string, -): { workflow: MultiAgentWorkflow; error?: string } { - const template = templates.get(template_id); - if (!template) { - return { workflow: {} as MultiAgentWorkflow, error: "Template not found" }; - } - - const { workflow } = createWorkflow(team_id, workflow_name, created_by, template.description); - - // Add tasks from template - template.tasks.forEach((taskTemplate) => { - addWorkflowTask( - team_id, - workflow.id, - taskTemplate.task_name, - taskTemplate.description, - taskTemplate.sequence_order, - taskTemplate.dependencies, - taskTemplate.timeout_minutes, - ); - }); - - // Setup coordination from template - template.coordination.forEach((coordTemplate) => { - const allTasks = workflow.tasks.map((t) => t.id); - setupCoordination( - team_id, - workflow.id, - coordTemplate.coordination_type, - allTasks, - ); - }); - - return { workflow }; -} - -/** - * List workflow templates - */ -export function listWorkflowTemplates(): { templates: WorkflowTemplate[] } { - return { templates: Array.from(templates.values()).filter((t) => t.public) }; -} - -/** - * Get workflow metrics - */ -export function getWorkflowMetrics(team_id: string): WorkflowMetrics { - const teamWorkflows = Array.from(workflows.values()).filter((w) => w.team_id === team_id); - const completed = teamWorkflows.filter((w) => w.status === "completed").length; - const failed = teamWorkflows.filter((w) => w.status === "failed").length; - const active = teamWorkflows.filter((w) => w.status === "active").length; - - const totalTasks = teamWorkflows.reduce((sum, w) => sum + w.tasks.length, 0); - const avgTasks = teamWorkflows.length > 0 ? totalTasks / teamWorkflows.length : 0; - const totalRetries = teamWorkflows.reduce( - (sum, w) => sum + w.tasks.reduce((s, t) => s + t.retry_count, 0), - 0, - ); - const avgRetries = totalTasks > 0 ? totalRetries / totalTasks : 0; - - return { - total_workflows: teamWorkflows.length, - active_workflows: active, - completed_workflows: completed, - failed_workflows: failed, - average_duration_minutes: 45, - average_tasks_per_workflow: avgTasks, - most_used_coordination_type: "sequential", - agent_utilization_percent: 78, - success_rate_percent: - teamWorkflows.length > 0 ? (completed / teamWorkflows.length) * 100 : 0, - average_retries: avgRetries, - }; -} diff --git a/src/plugin-updates.test.ts b/src/plugin-updates.test.ts deleted file mode 100644 index 43e9abdd..00000000 --- a/src/plugin-updates.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { PluginUpdatesManager, type InstalledPlugin } from "./plugin-updates.js"; - -describe("PluginUpdatesManager", () => { - describe("initialization", () => { - it("creates manager with default directory", () => { - const manager = new PluginUpdatesManager(); - assert(manager); - }); - - it("creates manager with custom directory", () => { - const manager = new PluginUpdatesManager(".kit/custom"); - assert(manager); - }); - }); - - describe("API structure", () => { - const manager = new PluginUpdatesManager(); - - it("has checkForUpdates method", () => { - assert(typeof manager.checkForUpdates === "function"); - }); - - it("has getSecurityUpdates method", () => { - assert(typeof manager.getSecurityUpdates === "function"); - }); - - it("has resolveDependencies method", () => { - assert(typeof manager.resolveDependencies === "function"); - }); - - it("has getUpgradePath method", () => { - assert(typeof manager.getUpgradePath === "function"); - }); - - it("has rollback method", () => { - assert(typeof manager.rollback === "function"); - }); - - it("has updateLock method", () => { - assert(typeof manager.updateLock === "function"); - }); - }); - - describe("checkForUpdates", () => { - const manager = new PluginUpdatesManager(); - - it("accepts array of installed plugins", () => { - const plugins: InstalledPlugin[] = [ - { - id: "test/plugin", - name: "Test Plugin", - version: "1.0.0", - installed: "2026-01-01", - dependencies: {}, - }, - ]; - - const updates = manager.checkForUpdates(plugins); - assert(typeof updates === "object"); - }); - - it("returns object with plugin IDs as keys", () => { - const plugins: InstalledPlugin[] = [ - { - id: "test/plugin1", - name: "Test 1", - version: "1.0.0", - installed: "2026-01-01", - dependencies: {}, - }, - { - id: "test/plugin2", - name: "Test 2", - version: "1.0.0", - installed: "2026-01-01", - dependencies: {}, - }, - ]; - - const updates = manager.checkForUpdates(plugins); - assert(updates["test/plugin1"] !== undefined); - assert(updates["test/plugin2"] !== undefined); - }); - - it("handles empty plugin list", () => { - const updates = manager.checkForUpdates([]); - assert.deepEqual(updates, {}); - }); - }); - - describe("methods return correct types", () => { - const manager = new PluginUpdatesManager(); - const testPlugin: InstalledPlugin = { - id: "test/plugin", - name: "Test", - version: "1.0.0", - installed: "2026-01-01", - dependencies: {}, - }; - - it("resolveDependencies returns object with arrays", () => { - const result = manager.resolveDependencies("test/plugin", "1.0.0"); - - assert(typeof result.resolved === "object"); - assert(Array.isArray(result.conflicts)); - assert(Array.isArray(result.unmet)); - }); - - it("getUpgradePath returns array", () => { - const path = manager.getUpgradePath("test/plugin", "1.0.0", "2.0.0"); - - assert(Array.isArray(path)); - }); - - it("rollback returns object with strings", () => { - const rollback = manager.rollback("test/plugin", "1.0.0"); - - assert( - typeof rollback.previousVersion === "string" || - rollback.previousVersion === null, - ); - assert( - typeof rollback.rollbackCommand === "string" || - rollback.rollbackCommand === null, - ); - }); - - it("getSecurityUpdates returns array", () => { - const securityUpdates = manager.getSecurityUpdates([testPlugin]); - - assert(Array.isArray(securityUpdates)); - }); - }); - - describe("cache methods", () => { - const manager = new PluginUpdatesManager(); - - it("accepts setVersionsCache", () => { - assert(typeof manager.setVersionsCache === "function"); - manager.setVersionsCache([]); - assert(true); - }); - - it("accepts setInstalledCache", () => { - assert(typeof manager.setInstalledCache === "function"); - manager.setInstalledCache([]); - assert(true); - }); - }); -}); diff --git a/src/plugin-updates.ts b/src/plugin-updates.ts deleted file mode 100644 index 33032c95..00000000 --- a/src/plugin-updates.ts +++ /dev/null @@ -1,490 +0,0 @@ -/** - * kit Plugin Update Infrastructure - * - * Manages plugin version checking, updates, and dependency resolution - */ - -import { readFileSync, writeFileSync } from "fs"; -import { join } from "path"; - -/** - * Plugin version information - */ -export interface PluginVersion { - id: string; - version: string; - published: string; - deprecated?: boolean; - breaking?: boolean; - features: string[]; - bugFixes: string[]; - securityFixes?: string[]; -} - -/** - * Available update for a plugin - */ -export interface PluginUpdate { - currentVersion: string; - latestVersion: string; - isBreaking: boolean; - isSecurityFix: boolean; - availableVersions: PluginVersion[]; - changelog: string; - installCommand: string; -} - -/** - * Plugin with installed version - */ -export interface InstalledPlugin { - id: string; - name: string; - version: string; - installed: string; - dependencies: Record; -} - -/** - * Version comparison result - */ -export interface VersionComparison { - isNewer: boolean; - isBreaking: boolean; - isMajor: boolean; - isMinor: boolean; - isPatch: boolean; -} - -/** - * Plugin Updates Manager - */ -export class PluginUpdatesManager { - private versionsFile: string; - private installedFile: string; - private lockFile: string; - private versionsCache: PluginVersion[] | null = null; - private installedCache: InstalledPlugin[] | null = null; - - constructor(dataDir: string = ".kit/plugins") { - this.versionsFile = join(dataDir, "versions.json"); - this.installedFile = join(dataDir, "installed.json"); - this.lockFile = join(dataDir, "lock.json"); - } - - /** - * Set versions cache for testing - */ - setVersionsCache(versions: PluginVersion[]): void { - this.versionsCache = versions; - } - - /** - * Set installed cache for testing - */ - setInstalledCache(plugins: InstalledPlugin[]): void { - this.installedCache = plugins; - } - - /** - * Parse semantic version string - */ - private parseVersion(version: string): { - major: number; - minor: number; - patch: number; - } { - // Handle various version formats: 1.2.3, v1.2.3, ^1.2.3, ~1.2.3 - const match = version.match(/(\d+)\.(\d+)\.(\d+)/); - if (!match) { - return { major: 0, minor: 0, patch: 0 }; - } - return { - major: parseInt(match[1]), - minor: parseInt(match[2]), - patch: parseInt(match[3]), - }; - } - - /** - * Compare two semantic versions - */ - private compareVersions(v1: string, v2: string): VersionComparison { - const ver1 = this.parseVersion(v1); - const ver2 = this.parseVersion(v2); - - const isNewer = - ver2.major > ver1.major || - (ver2.major === ver1.major && ver2.minor > ver1.minor) || - (ver2.major === ver1.major && - ver2.minor === ver1.minor && - ver2.patch > ver1.patch); - - const isMajor = ver2.major > ver1.major; - const isMinor = ver2.major === ver1.major && ver2.minor > ver1.minor; - const isPatch = - ver2.major === ver1.major && ver2.minor === ver1.minor && ver2.patch > ver1.patch; - - return { - isNewer, - isBreaking: isMajor, - isMajor, - isMinor, - isPatch, - }; - } - - /** - * Version matches requirement (^, ~, >=, etc.) - */ - private versionMatches(requirement: string, version: string): boolean { - if (requirement === "*" || requirement === "latest") return true; - - const ver = this.parseVersion(version); - const req = this.parseVersion(requirement); - - if (requirement.startsWith("^")) { - // Caret: allows changes that do not modify left-most non-zero digit - return ( - ver.major === req.major && - (ver.minor > req.minor || - (ver.minor === req.minor && ver.patch >= req.patch)) - ); - } - - if (requirement.startsWith("~")) { - // Tilde: allows patch-level changes - return ( - ver.major === req.major && - ver.minor === req.minor && - ver.patch >= req.patch - ); - } - - if (requirement.startsWith(">=")) { - const minVersion = requirement.slice(2).trim(); - const min = this.parseVersion(minVersion); - return ( - ver.major > min.major || - (ver.major === min.major && ver.minor > min.minor) || - (ver.major === min.major && - ver.minor === min.minor && - ver.patch >= min.patch) - ); - } - - // Exact match - return version === requirement; - } - - /** - * Check for updates for installed plugins - */ - checkForUpdates( - plugins: InstalledPlugin[], - ): Record { - const versions = this.getAllVersions(); - const updates: Record = {}; - - plugins.forEach((plugin) => { - const pluginVersions = versions.filter((v) => v.id === plugin.id); - - if (pluginVersions.length === 0) { - updates[plugin.id] = null; - return; - } - - // Sort by version descending - pluginVersions.sort((a, b) => { - const cmp = this.compareVersions(a.version, b.version); - return cmp.isNewer ? -1 : 1; - }); - - const latestVersion = pluginVersions[0]; - - if ( - this.compareVersions(plugin.version, latestVersion.version).isNewer - ) { - updates[plugin.id] = { - currentVersion: plugin.version, - latestVersion: latestVersion.version, - isBreaking: latestVersion.breaking || false, - isSecurityFix: (latestVersion.securityFixes || []).length > 0, - availableVersions: pluginVersions.filter((v) => - this.compareVersions(plugin.version, v.version).isNewer, - ), - changelog: this.generateChangelog( - plugin.id, - plugin.version, - latestVersion.version, - ), - installCommand: `kit add ${plugin.id}@${latestVersion.version}`, - }; - } else { - updates[plugin.id] = null; - } - }); - - return updates; - } - - /** - * Resolve plugin dependencies - */ - resolveDependencies( - pluginId: string, - version: string, - ): { - resolved: Record; - conflicts: Array<{ plugin: string; required: string; installed: string }>; - unmet: Array<{ plugin: string; required: string }>; - } { - const versions = this.getAllVersions(); - const installed = this.getInstalledPlugins(); - - const pluginVersion = versions.find( - (v) => v.id === pluginId && v.version === version, - ); - - if (!pluginVersion) { - return { resolved: {}, conflicts: [], unmet: [] }; - } - - const resolved: Record = {}; - const conflicts: Array<{ - plugin: string; - required: string; - installed: string; - }> = []; - const unmet: Array<{ plugin: string; required: string }> = []; - - // Resolve each dependency - Object.entries(pluginVersion.features || {}).forEach( - ([depId, depRequirement]) => { - const availableVersions = versions.filter((v) => v.id === depId); - - if (availableVersions.length === 0) { - unmet.push({ plugin: depId, required: depRequirement as string }); - return; - } - - // Find compatible version - const compatible = availableVersions.find((v) => - this.versionMatches(depRequirement as string, v.version), - ); - - if (!compatible) { - unmet.push({ plugin: depId, required: depRequirement as string }); - return; - } - - const installedPlugin = installed.find((p) => p.id === depId); - - if (installedPlugin && installedPlugin.version !== compatible.version) { - conflicts.push({ - plugin: depId, - required: compatible.version, - installed: installedPlugin.version, - }); - } - - resolved[depId] = compatible.version; - }, - ); - - return { resolved, conflicts, unmet }; - } - - /** - * Get upgrade path from current to target version - */ - getUpgradePath( - pluginId: string, - fromVersion: string, - toVersion: string, - ): PluginVersion[] { - const versions = this.getAllVersions() - .filter((v) => v.id === pluginId) - .sort((a, b) => { - const aVer = this.parseVersion(a.version); - const bVer = this.parseVersion(b.version); - return ( - aVer.major * 1000 + - aVer.minor * 100 + - aVer.patch - - (bVer.major * 1000 + bVer.minor * 100 + bVer.patch) - ); - }); - - const fromIdx = versions.findIndex((v) => v.version === fromVersion); - const toIdx = versions.findIndex((v) => v.version === toVersion); - - if (fromIdx < 0 || toIdx < 0) { - return []; - } - - return versions.slice(fromIdx + 1, toIdx + 1); - } - - /** - * Check for security updates - */ - getSecurityUpdates(plugins: InstalledPlugin[]): Array<{ - plugin: InstalledPlugin; - update: PluginUpdate; - severity: "critical" | "high" | "medium" | "low"; - }> { - const updates = this.checkForUpdates(plugins); - const securityUpdates = []; - - for (const plugin of plugins) { - const update = updates[plugin.id]; - if (update?.isSecurityFix) { - const severity = update.isBreaking ? "critical" : "high"; - securityUpdates.push({ - plugin, - update, - severity: severity as "critical" | "high", - }); - } - } - - return securityUpdates; - } - - /** - * Rollback plugin to previous version - */ - rollback( - pluginId: string, - fromVersion: string, - ): { - previousVersion: string | null; - rollbackCommand: string | null; - } { - const versions = this.getAllVersions() - .filter((v) => v.id === pluginId) - .sort((a, b) => { - const aVer = this.parseVersion(a.version); - const bVer = this.parseVersion(b.version); - return ( - bVer.major * 1000 + - bVer.minor * 100 + - bVer.patch - - (aVer.major * 1000 + aVer.minor * 100 + aVer.patch) - ); - }); - - const currentIdx = versions.findIndex((v) => v.version === fromVersion); - if (currentIdx < 0 || currentIdx >= versions.length - 1) { - return { previousVersion: null, rollbackCommand: null }; - } - - const previousVersion = versions[currentIdx + 1]; - return { - previousVersion: previousVersion.version, - rollbackCommand: `kit add ${pluginId}@${previousVersion.version}`, - }; - } - - /** - * Generate changelog between versions - */ - private generateChangelog( - pluginId: string, - fromVersion: string, - toVersion: string, - ): string { - const upgradePath = this.getUpgradePath(pluginId, fromVersion, toVersion); - - if (upgradePath.length === 0) { - return "No changelog available"; - } - - let changelog = `# Changelog: ${pluginId} ${fromVersion} → ${toVersion}\n\n`; - - upgradePath.forEach((version) => { - changelog += `## ${version.version}\n`; - changelog += `*Published: ${version.published}*\n\n`; - - if (version.breaking) { - changelog += "⚠️ **Breaking Changes**\n"; - } - - if ((version.securityFixes || []).length > 0) { - changelog += "🔒 **Security Fixes**\n"; - version.securityFixes?.forEach((fix) => { - changelog += `- ${fix}\n`; - }); - changelog += "\n"; - } - - if (version.features.length > 0) { - changelog += "✨ **Features**\n"; - version.features.forEach((feature) => { - changelog += `- ${feature}\n`; - }); - changelog += "\n"; - } - - if (version.bugFixes.length > 0) { - changelog += "🐛 **Bug Fixes**\n"; - version.bugFixes.forEach((fix) => { - changelog += `- ${fix}\n`; - }); - changelog += "\n"; - } - }); - - return changelog; - } - - /** - * Get all plugin versions - */ - private getAllVersions(): PluginVersion[] { - // Use cache if available (for testing) - if (this.versionsCache !== null) { - return this.versionsCache; - } - - try { - const data = readFileSync(this.versionsFile, "utf-8"); - return JSON.parse(data); - } catch { - return []; - } - } - - /** - * Get installed plugins - */ - private getInstalledPlugins(): InstalledPlugin[] { - // Use cache if available (for testing) - if (this.installedCache !== null) { - return this.installedCache; - } - - try { - const data = readFileSync(this.installedFile, "utf-8"); - return JSON.parse(data); - } catch { - return []; - } - } - - /** - * Update installed plugins lock - */ - updateLock(plugins: InstalledPlugin[]): void { - const lock = { - timestamp: new Date().toISOString(), - plugins: plugins.map((p) => ({ - id: p.id, - version: p.version, - installed: p.installed, - })), - }; - writeFileSync(this.lockFile, JSON.stringify(lock, null, 2)); - } -} diff --git a/src/query-optimizer.test.ts b/src/query-optimizer.test.ts deleted file mode 100644 index 3ba35365..00000000 --- a/src/query-optimizer.test.ts +++ /dev/null @@ -1,287 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { QueryOptimizer, type IndexDefinition } from "./query-optimizer.js"; - -describe("QueryOptimizer", () => { - describe("index management", () => { - let optimizer: QueryOptimizer; - - beforeEach(() => { - optimizer = new QueryOptimizer(); - }); - - it("creates an index", () => { - const indexDef: IndexDefinition = { - name: "idx_plugins_author", - columns: ["author"], - type: "btree", - unique: false, - }; - optimizer.createIndex(indexDef); - assert.equal(optimizer.getIndex("idx_plugins_author"), indexDef); - }); - - it("retrieves index by name", () => { - const indexDef: IndexDefinition = { - name: "idx_plugins_name", - columns: ["name"], - type: "btree", - unique: false, - }; - optimizer.createIndex(indexDef); - const retrieved = optimizer.getIndex("idx_plugins_name"); - assert(retrieved); - assert.equal(retrieved.name, "idx_plugins_name"); - }); - - it("returns null for unknown index", () => { - const index = optimizer.getIndex("nonexistent"); - assert.equal(index, null); - }); - - it("gets all indexes", () => { - optimizer.createIndex({ - name: "idx1", - columns: ["col1"], - type: "btree", - unique: false, - }); - optimizer.createIndex({ - name: "idx2", - columns: ["col2"], - type: "hash", - unique: true, - }); - const all = optimizer.getAllIndexes(); - assert.equal(all.length, 2); - }); - - it("drops an index", () => { - optimizer.createIndex({ - name: "idx_temp", - columns: ["temp"], - type: "btree", - unique: false, - }); - const dropped = optimizer.dropIndex("idx_temp"); - assert(dropped); - assert.equal(optimizer.getIndex("idx_temp"), null); - }); - }); - - describe("query planning", () => { - let optimizer: QueryOptimizer; - - beforeEach(() => { - optimizer = new QueryOptimizer(); - optimizer.createIndex({ - name: "idx_author", - columns: ["author"], - type: "btree", - unique: false, - }); - }); - - it("generates query plan", () => { - const plan = optimizer.planQuery("SELECT * FROM plugins WHERE author = ?", [ - "author", - ]); - assert(plan); - assert(plan.estimatedCost > 0); - assert(plan.batchSize > 0); - }); - - it("uses applicable indexes in plan", () => { - const plan = optimizer.planQuery("SELECT * FROM plugins WHERE author = ?", [ - "author", - ]); - assert(plan.indexesUsed.includes("idx_author")); - }); - - it("caches query plans", () => { - const query = "SELECT * FROM plugins"; - const plan1 = optimizer.planQuery(query); - const plan2 = optimizer.planQuery(query); - assert.equal(plan1, plan2); - }); - - it("recommends larger batch sizes for simple queries", () => { - const simplePlan = optimizer.planQuery( - "SELECT * FROM plugins LIMIT 100", - ); - assert(simplePlan.batchSize >= 100); - }); - - it("recommends smaller batch sizes for complex queries", () => { - const complexPlan = optimizer.planQuery( - "SELECT * FROM plugins JOIN authors ON plugins.author = authors.id WHERE plugins.downloads > 1000", - ); - assert(complexPlan.batchSize <= 100); - }); - - it("sets useConnection flag for expensive queries", () => { - const expensivePlan = optimizer.planQuery( - "SELECT * FROM plugins JOIN authors ON plugins.author = authors.id GROUP BY category ORDER BY downloads DESC", - ); - assert(expensivePlan.useConnection); - }); - - it("gets cached plan", () => { - const query = "SELECT * FROM plugins"; - optimizer.planQuery(query); - const cached = optimizer.getCachedPlan(query); - assert(cached); - }); - - it("clears query cache", () => { - optimizer.planQuery("SELECT * FROM plugins"); - optimizer.clearCache(); - const cached = optimizer.getCachedPlan("SELECT * FROM plugins"); - assert.equal(cached, null); - }); - }); - - describe("query execution", () => { - let optimizer: QueryOptimizer; - - beforeEach(() => { - optimizer = new QueryOptimizer(); - }); - - it("executes query and returns result", () => { - const result = optimizer.executeQuery("SELECT * FROM plugins"); - assert(result.rows !== undefined); - assert(result.executionTime >= 0); - }); - - it("tracks execution time", () => { - optimizer.executeQuery("SELECT * FROM plugins"); - const stats = optimizer.getExecutionStats(); - assert(stats.length > 0); - assert(stats[0].executionTime >= 0); - }); - - it("gets execution statistics", () => { - optimizer.executeQuery("SELECT * FROM plugins"); - optimizer.executeQuery("SELECT * FROM authors"); - const stats = optimizer.getExecutionStats(); - assert(stats.length >= 2); - }); - - it("calculates average execution time", () => { - optimizer.executeQuery("SELECT * FROM plugins"); - optimizer.executeQuery("SELECT * FROM plugins"); - const avg = optimizer.getAverageExecutionTime("SELECT * FROM plugins"); - assert(avg >= 0); - }); - - it("calculates average for all queries", () => { - optimizer.executeQuery("SELECT * FROM plugins"); - optimizer.executeQuery("SELECT * FROM authors"); - const avg = optimizer.getAverageExecutionTime(); - assert(avg >= 0); - }); - }); - - describe("batch operations", () => { - let optimizer: QueryOptimizer; - - beforeEach(() => { - optimizer = new QueryOptimizer(); - }); - - it("queues batch operation", () => { - const operations = [ - { type: "insert" as const, data: { name: "Plugin 1" } }, - { type: "insert" as const, data: { name: "Plugin 2" } }, - ]; - const batch = optimizer.queueBatchOperation("batch-1", operations); - assert.equal(batch.id, "batch-1"); - assert.equal(batch.status, "pending"); - }); - - it("executes batch operation", () => { - const operations = [ - { type: "insert" as const, data: { name: "Plugin 1" } }, - { type: "update" as const, data: { id: "1" } }, - { type: "delete" as const, data: { id: "2" } }, - ]; - optimizer.queueBatchOperation("batch-1", operations); - const executed = optimizer.executeBatch("batch-1"); - assert(executed); - assert.equal(executed.status, "completed"); - }); - - it("gets batch operation by ID", () => { - const operations = [ - { type: "insert" as const, data: { name: "Plugin" } }, - ]; - optimizer.queueBatchOperation("batch-1", operations); - const batch = optimizer.getBatchOperation("batch-1"); - assert(batch); - assert.equal(batch.id, "batch-1"); - }); - - it("returns null for unknown batch", () => { - const batch = optimizer.getBatchOperation("unknown"); - assert.equal(batch, null); - }); - - it("tracks pending batches", () => { - optimizer.queueBatchOperation("batch-1", [ - { type: "insert" as const, data: {} }, - ]); - optimizer.queueBatchOperation("batch-2", [ - { type: "insert" as const, data: {} }, - ]); - const pending = optimizer.getPendingBatches(); - assert.equal(pending.length, 2); - }); - - it("removes pending status after execution", () => { - optimizer.queueBatchOperation("batch-1", [ - { type: "insert" as const, data: {} }, - ]); - optimizer.executeBatch("batch-1"); - const pending = optimizer.getPendingBatches(); - assert.equal(pending.length, 0); - }); - }); - - describe("cache info", () => { - let optimizer: QueryOptimizer; - - beforeEach(() => { - optimizer = new QueryOptimizer(); - }); - - it("returns index cache size", () => { - optimizer.createIndex({ - name: "idx1", - columns: ["col1"], - type: "btree", - unique: false, - }); - const indexes = optimizer.getIndexCache(); - assert.equal(indexes.size, 1); - }); - - it("returns query cache size", () => { - optimizer.planQuery("SELECT * FROM plugins"); - optimizer.planQuery("SELECT * FROM authors"); - const size = optimizer.getQueryCacheSize(); - assert.equal(size, 2); - }); - - it("returns batch queue size", () => { - optimizer.queueBatchOperation("batch-1", [ - { type: "insert" as const, data: {} }, - ]); - optimizer.queueBatchOperation("batch-2", [ - { type: "insert" as const, data: {} }, - ]); - const size = optimizer.getBatchQueueSize(); - assert.equal(size, 2); - }); - }); -}); diff --git a/src/query-optimizer.ts b/src/query-optimizer.ts deleted file mode 100644 index c4c548dd..00000000 --- a/src/query-optimizer.ts +++ /dev/null @@ -1,272 +0,0 @@ -// ─── Types ──────────────────────────────────────────────────────────────────── - -export interface QueryPlan { - query: string; - estimatedCost: number; - indexesUsed: string[]; - batchSize: number; - useConnection: boolean; -} - -export interface QueryResult { - rows: Record[]; - executionTime: number; - indexesUsed: string[]; -} - -export interface IndexDefinition { - name: string; - columns: string[]; - type: "btree" | "hash"; - unique: boolean; -} - -export interface BatchOperation { - id: string; - operations: Array<{ type: "insert" | "update" | "delete"; data: unknown }>; - status: "pending" | "executing" | "completed" | "failed"; - result?: unknown; -} - -// ─── QueryOptimizer ─────────────────────────────────────────────────────────── - -export class QueryOptimizer { - private queryCache: Map = new Map(); - private indexes: Map = new Map(); - private executionStats: Array<{ - query: string; - executionTime: number; - timestamp: string; - }> = []; - private batchQueue: Map = new Map(); - - // ─── Index Management ───────────────────────────────────────────────────── - - /** - * Create an index for faster queries. - */ - createIndex(indexDef: IndexDefinition): void { - this.indexes.set(indexDef.name, indexDef); - } - - /** - * Get index definition by name. - */ - getIndex(indexName: string): IndexDefinition | null { - return this.indexes.get(indexName) || null; - } - - /** - * Get all indexes. - */ - getAllIndexes(): IndexDefinition[] { - return [...this.indexes.values()]; - } - - /** - * Drop an index. - */ - dropIndex(indexName: string): boolean { - return this.indexes.delete(indexName); - } - - // ─── Query Planning ─────────────────────────────────────────────────────── - - /** - * Generate optimized query plan. - */ - planQuery(query: string, columns: string[] = []): QueryPlan { - // Check cache first - if (this.queryCache.has(query)) { - return this.queryCache.get(query)!; - } - - // Analyze query and find applicable indexes - const indexesUsed = this.findApplicableIndexes(query, columns); - const estimatedCost = this.calculateQueryCost(query, indexesUsed); - const batchSize = this.recommendBatchSize(estimatedCost); - const useConnection = estimatedCost >= 1000; - - const plan: QueryPlan = { - query, - estimatedCost, - indexesUsed, - batchSize, - useConnection, - }; - - this.queryCache.set(query, plan); - return plan; - } - - private findApplicableIndexes(query: string, columns: string[]): string[] { - const applicable: string[] = []; - - for (const index of this.indexes.values()) { - // Check if index columns are referenced in query - if ( - index.columns.some((col) => query.includes(col) || columns.includes(col)) - ) { - applicable.push(index.name); - } - } - - return applicable; - } - - private calculateQueryCost(query: string, indexesUsed: string[]): number { - // Simple cost calculation: base cost minus index benefits - let cost = 200; - - // Penalize complex queries - if (query.includes("JOIN")) cost += 400; - if (query.includes("GROUP BY")) cost += 300; - if (query.includes("ORDER BY")) cost += 200; - - // Reward index usage - cost -= indexesUsed.length * 50; - - return Math.max(10, cost); - } - - private recommendBatchSize(estimatedCost: number): number { - if (estimatedCost < 50) return 1000; - if (estimatedCost < 100) return 500; - if (estimatedCost < 500) return 100; - return 10; - } - - /** - * Get cached query plan. - */ - getCachedPlan(query: string): QueryPlan | null { - return this.queryCache.get(query) || null; - } - - /** - * Clear query plan cache. - */ - clearCache(): void { - this.queryCache.clear(); - } - - // ─── Query Execution ────────────────────────────────────────────────────── - - /** - * Execute query with optimization. - */ - executeQuery(query: string, columns: string[] = []): QueryResult { - const startTime = Date.now(); - const plan = this.planQuery(query, columns); - - // Simulate query execution - const result: QueryResult = { - rows: [], - executionTime: Date.now() - startTime, - indexesUsed: plan.indexesUsed, - }; - - // Track statistics - this.executionStats.push({ - query, - executionTime: result.executionTime, - timestamp: new Date().toISOString(), - }); - - return result; - } - - /** - * Get query execution statistics. - */ - getExecutionStats(limit = 100): Array<{ - query: string; - executionTime: number; - timestamp: string; - }> { - return this.executionStats.slice(-limit); - } - - /** - * Get average query execution time. - */ - getAverageExecutionTime(query?: string): number { - const stats = query - ? this.executionStats.filter((s) => s.query === query) - : this.executionStats; - - if (stats.length === 0) return 0; - const total = stats.reduce((sum, s) => sum + s.executionTime, 0); - return total / stats.length; - } - - // ─── Batch Operations ───────────────────────────────────────────────────── - - /** - * Queue batch operation. - */ - queueBatchOperation( - id: string, - operations: Array<{ type: "insert" | "update" | "delete"; data: unknown }>, - ): BatchOperation { - const batchOp: BatchOperation = { - id, - operations, - status: "pending", - }; - this.batchQueue.set(id, batchOp); - return batchOp; - } - - /** - * Execute queued batch operation. - */ - executeBatch(id: string): BatchOperation | null { - const batch = this.batchQueue.get(id); - if (!batch) return null; - - batch.status = "executing"; - - try { - // Simulate batch execution - batch.result = { - inserted: batch.operations.filter((op) => op.type === "insert").length, - updated: batch.operations.filter((op) => op.type === "update").length, - deleted: batch.operations.filter((op) => op.type === "delete").length, - }; - batch.status = "completed"; - } catch { - batch.status = "failed"; - } - - return batch; - } - - /** - * Get batch operation by ID. - */ - getBatchOperation(id: string): BatchOperation | null { - return this.batchQueue.get(id) || null; - } - - /** - * Get all pending batches. - */ - getPendingBatches(): BatchOperation[] { - return [...this.batchQueue.values()].filter((b) => b.status === "pending"); - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getIndexCache(): Map { - return this.indexes; - } - - getQueryCacheSize(): number { - return this.queryCache.size; - } - - getBatchQueueSize(): number { - return this.batchQueue.size; - } -} diff --git a/src/redis-adapter.test.ts b/src/redis-adapter.test.ts deleted file mode 100644 index 2aa51789..00000000 --- a/src/redis-adapter.test.ts +++ /dev/null @@ -1,533 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { RedisAdapter, createRedisAdapter } from "./redis-adapter.js"; - -describe("RedisAdapter", () => { - describe("initialization", () => { - it("creates adapter with config", () => { - const adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - - assert.equal(adapter.name, "redis"); - assert.equal(adapter.version, "1.0.0"); - }); - - it("initializes with disabled config", () => { - const adapter = new RedisAdapter({ enabled: false }); - assert(!adapter.isConnected()); - }); - - it("creates adapter with default config", () => { - const adapter = new RedisAdapter(); - assert(!adapter.isConnected()); - }); - }); - - describe("connection management", () => { - let adapter: RedisAdapter; - - beforeEach(() => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - }); - - it("connects with valid endpoint", async () => { - await adapter.connect(); - assert(adapter.isConnected()); - }); - - it("throws error when enabled without endpoint", async () => { - const invalidAdapter = new RedisAdapter({ enabled: true }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("endpoint is required")); - } - }); - - it("throws error with invalid endpoint format", async () => { - const invalidAdapter = new RedisAdapter({ - enabled: true, - endpoint: ":", - }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid Redis endpoint")); - } - }); - - it("throws error with invalid port number", async () => { - const invalidAdapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:not-a-port", - }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid Redis port")); - } - }); - - it("disconnects cleanly", async () => { - await adapter.connect(); - assert(adapter.isConnected()); - - await adapter.disconnect(); - assert(!adapter.isConnected()); - }); - - it("skips connection when disabled", async () => { - const disabledAdapter = new RedisAdapter({ - enabled: false, - endpoint: "localhost:6379", - }); - - await disabledAdapter.connect(); - assert(!disabledAdapter.isConnected()); - }); - }); - - describe("health monitoring", () => { - let adapter: RedisAdapter; - - beforeEach(async () => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - await adapter.connect(); - }); - - it("reports healthy status when connected", async () => { - const health = await adapter.getHealth(); - - assert.equal(health.status, "healthy"); - assert(health.lastCheck); - assert(health.responseTime >= 0); - assert.equal(health.errorCount, 0); - }); - - it("records response time", async () => { - const health = await adapter.getHealth(); - assert(typeof health.responseTime === "number"); - }); - - it("updates lastCheck timestamp", async () => { - const before = new Date(); - await adapter.getHealth(); - const after = new Date(); - - const health = await adapter.getHealth(); - const lastCheck = new Date(health.lastCheck); - - assert(lastCheck >= before); - assert(lastCheck <= after); - }); - }); - - describe("cache operations", () => { - let adapter: RedisAdapter; - - beforeEach(async () => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - await adapter.connect(); - }); - - it("sets a cache value", async () => { - const result = await adapter.set("test:key", "value"); - - assert.equal(result, true); - }); - - it("sets a cache value with TTL", async () => { - const result = await adapter.set("test:ttl", "expires soon", 3600); - - assert.equal(result, true); - }); - - it("gets a cached value", async () => { - await adapter.set("test:get", "hello"); - - const value = await adapter.get("test:get"); - - assert.equal(value, "hello"); - }); - - it("returns undefined for non-existent key", async () => { - const value = await adapter.get("nonexistent"); - - assert.equal(value, undefined); - }); - - it("stores different value types", async () => { - await adapter.set("string", "value"); - await adapter.set("number", 42); - await adapter.set("boolean", true); - await adapter.set("object", { nested: "data" }); - - assert.equal(await adapter.get("string"), "value"); - assert.equal(await adapter.get("number"), 42); - assert.equal(await adapter.get("boolean"), true); - }); - - it("checks key existence", async () => { - await adapter.set("existing", "value"); - - assert.equal(await adapter.exists("existing"), true); - assert.equal(await adapter.exists("notexisting"), false); - }); - - it("deletes a key", async () => { - await adapter.set("to:delete", "value"); - assert.equal(await adapter.exists("to:delete"), true); - - const result = await adapter.delete("to:delete"); - assert.equal(result, true); - assert.equal(await adapter.exists("to:delete"), false); - }); - - it("clears all cache", async () => { - await adapter.set("key1", "value1"); - await adapter.set("key2", "value2"); - assert(adapter.size() > 0); - - const result = await adapter.clear(); - assert.equal(result, true); - assert.equal(adapter.size(), 0); - }); - - it("gets all keys", async () => { - await adapter.set("app:key1", "v1"); - await adapter.set("app:key2", "v2"); - await adapter.set("user:key3", "v3"); - - const keys = adapter.keys(); - assert(keys.length >= 3); - assert(keys.includes("app:key1")); - assert(keys.includes("app:key2")); - assert(keys.includes("user:key3")); - }); - - it("returns cache size", async () => { - const initialSize = adapter.size(); - await adapter.set("test", "value"); - - assert.equal(adapter.size(), initialSize + 1); - }); - }); - - describe("expiration", () => { - let adapter: RedisAdapter; - - beforeEach(async () => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - await adapter.connect(); - }); - - it("respects TTL expiration", async () => { - await adapter.set("expiring", "value", 0.1); // 100ms - - assert.equal(await adapter.exists("expiring"), true); - - // Wait for expiration - await new Promise((resolve) => setTimeout(resolve, 150)); - - assert.equal(await adapter.exists("expiring"), false); - assert.equal(await adapter.get("expiring"), undefined); - }); - - it("removes expired keys from keys list", async () => { - await adapter.set("exp1", "v1", 0.1); - await adapter.set("exp2", "v2", 0.1); - - await new Promise((resolve) => setTimeout(resolve, 150)); - - const keys = adapter.keys(); - assert(!keys.includes("exp1")); - assert(!keys.includes("exp2")); - }); - }); - - describe("statistics", () => { - let adapter: RedisAdapter; - - beforeEach(async () => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - await adapter.connect(); - }); - - it("tracks cache hits", async () => { - await adapter.set("hit:test", "value"); - await adapter.get("hit:test"); - - const stats = adapter.getCacheStats(); - assert.equal(stats.hits, 1); - }); - - it("tracks cache misses", async () => { - await adapter.get("miss:nonexistent"); - - const stats = adapter.getCacheStats(); - assert.equal(stats.misses, 1); - }); - - it("tracks sets", async () => { - await adapter.set("stat:set1", "v"); - await adapter.set("stat:set2", "v"); - - const stats = adapter.getCacheStats(); - assert.equal(stats.sets, 2); - }); - - it("tracks deletes", async () => { - await adapter.set("del:key", "v"); - await adapter.delete("del:key"); - - const stats = adapter.getCacheStats(); - assert.equal(stats.deletes, 1); - }); - - it("calculates hit rate", async () => { - await adapter.set("hr:1", "v"); - await adapter.get("hr:1"); // Hit - await adapter.get("hr:2"); // Miss - - const stats = adapter.getCacheStats(); - assert.equal(stats.hitRate, 50); - }); - - it("returns cache size in stats", async () => { - await adapter.set("s1", "v"); - await adapter.set("s2", "v"); - - const stats = adapter.getCacheStats(); - assert.equal(stats.size, 2); - }); - }); - - describe("cache info", () => { - let adapter: RedisAdapter; - - beforeEach(() => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - }); - - it("returns endpoint", async () => { - await adapter.connect(); - - const info = adapter.getInfo(); - assert.equal(info.endpoint, "localhost:6379"); - }); - - it("returns connection status", async () => { - assert.equal(adapter.getInfo().connected, false); - - await adapter.connect(); - assert.equal(adapter.getInfo().connected, true); - }); - - it("returns cache size", async () => { - await adapter.connect(); - await adapter.set("key1", "v"); - - const info = adapter.getInfo(); - assert.equal(info.cacheSize, 1); - }); - - it("returns key count", async () => { - await adapter.connect(); - await adapter.set("k1", "v"); - await adapter.set("k2", "v"); - - const info = adapter.getInfo(); - assert(info.keyCount >= 2); - }); - }); - - describe("event validation", () => { - let adapter: RedisAdapter; - - beforeEach(async () => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - await adapter.connect(); - }); - - it("requires event type", async () => { - try { - await (adapter as any).sendEvent({ - data: { key: "test" }, - timestamp: new Date().toISOString(), - }); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid event")); - } - }); - - it("requires event data", async () => { - try { - await (adapter as any).sendEvent({ - type: "event", - timestamp: new Date().toISOString(), - }); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid event")); - } - }); - }); - - describe("queue flushing", () => { - let adapter: RedisAdapter; - - beforeEach(() => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - }); - - it("flushes queued events on connection", async () => { - await adapter.set("queued:1", "v1"); - await adapter.set("queued:2", "v2"); - - await adapter.connect(); - - assert(adapter.isConnected()); - }); - - it("handles empty queue gracefully", async () => { - await adapter.connect(); - - assert(true); - }); - }); - - describe("disconnection cleanup", () => { - let adapter: RedisAdapter; - - beforeEach(async () => { - adapter = new RedisAdapter({ - enabled: true, - endpoint: "localhost:6379", - }); - await adapter.connect(); - }); - - it("clears cache on disconnect", async () => { - await adapter.set("cleanup:1", "v"); - assert(adapter.size() > 0); - - await adapter.disconnect(); - - assert.equal(adapter.size(), 0); - }); - - it("clears stats on disconnect", async () => { - await adapter.get("test"); - assert(adapter.getCacheStats().misses > 0); - - await adapter.disconnect(); - // Stats are not cleared, cache is - assert.equal(adapter.size(), 0); - }); - }); - - describe("factory function", () => { - it("creates enabled adapter with REDIS_URL", () => { - const originalUrl = process.env.REDIS_URL; - - try { - process.env.REDIS_URL = "localhost:6379"; - - const adapter = createRedisAdapter(true); - - assert(adapter.config.enabled); - assert(adapter.config.endpoint); - } finally { - process.env.REDIS_URL = originalUrl; - } - }); - - it("creates enabled adapter with REDIS_ENDPOINT", () => { - const originalUrl = process.env.REDIS_URL; - const originalEndpoint = process.env.REDIS_ENDPOINT; - - try { - delete process.env.REDIS_URL; - process.env.REDIS_ENDPOINT = "redis.example.com:6380"; - - const adapter = createRedisAdapter(true); - - assert(adapter.config.enabled); - assert(adapter.config.endpoint); - } finally { - process.env.REDIS_URL = originalUrl; - process.env.REDIS_ENDPOINT = originalEndpoint; - } - }); - - it("creates disabled adapter without endpoint", () => { - const originalUrl = process.env.REDIS_URL; - const originalEndpoint = process.env.REDIS_ENDPOINT; - - try { - delete process.env.REDIS_URL; - delete process.env.REDIS_ENDPOINT; - - const adapter = createRedisAdapter(true); - - assert(!adapter.config.enabled); - } finally { - process.env.REDIS_URL = originalUrl; - process.env.REDIS_ENDPOINT = originalEndpoint; - } - }); - - it("respects enabled parameter", () => { - const adapter = createRedisAdapter(false); - - assert(!adapter.config.enabled); - }); - - it("defaults to enabled", () => { - const originalUrl = process.env.REDIS_URL; - - try { - process.env.REDIS_URL = "localhost:6379"; - - const adapter = createRedisAdapter(); - - assert(adapter.config.enabled); - } finally { - process.env.REDIS_URL = originalUrl; - } - }); - }); -}); diff --git a/src/redis-adapter.ts b/src/redis-adapter.ts deleted file mode 100644 index 5f43e0c3..00000000 --- a/src/redis-adapter.ts +++ /dev/null @@ -1,357 +0,0 @@ -// ─── Redis Cache Adapter ───────────────────────────────────────────────── - -import { - AbstractServiceAdapter, - simulatedFailuresEnabled, - type ServiceConfig, - type ServiceEvent, - type ServiceHealth, -} from "./service-adapter.js"; - -/** - * Redis adapter for caching and session management. - */ -export class RedisAdapter extends AbstractServiceAdapter { - private cache: Map = new Map(); - private lastHealthCheck: string = new Date().toISOString(); - private healthCheckErrors: number = 0; - private stats = { - hits: 0, - misses: 0, - sets: 0, - deletes: 0, - }; - - constructor(config: ServiceConfig = { enabled: false }) { - super("redis", "1.0.0", config); - } - - async connect(): Promise { - if (!this.config.enabled) { - this.connected = false; - return; - } - - // Validate required config - if (!this.config.endpoint) { - throw new Error("Redis endpoint is required (host:port)"); - } - - // Basic endpoint format validation - const [host, port] = this.config.endpoint.split(":"); - if (!host) { - throw new Error("Invalid Redis endpoint format"); - } - - if (port && isNaN(parseInt(port))) { - throw new Error("Invalid Redis port number"); - } - - // Simulate connection test - await new Promise((resolve) => setTimeout(resolve, 50)); - - this.connected = true; - - // Flush queued events - await this.flushQueue(); - } - - async disconnect(): Promise { - if (this.healthCheckInterval) { - clearInterval(this.healthCheckInterval); - this.healthCheckInterval = null; - } - this.cache.clear(); - this.connected = false; - } - - async getHealth(): Promise { - const responseTime = Math.random() * 30; - - try { - if (!this.connected) { - this.healthCheckErrors++; - } - - this.lastHealthCheck = new Date().toISOString(); - - const status = - this.healthCheckErrors < 3 - ? this.connected - ? "healthy" - : "degraded" - : "unhealthy"; - - return { - status, - lastCheck: this.lastHealthCheck, - responseTime: Math.round(responseTime), - errorCount: this.healthCheckErrors, - }; - } catch { - this.healthCheckErrors++; - return { - status: "unhealthy", - lastCheck: new Date().toISOString(), - responseTime: -1, - errorCount: this.healthCheckErrors, - }; - } - } - - protected async sendEvent(event: ServiceEvent): Promise { - if (!this.connected) { - throw new Error("Not connected to Redis"); - } - - // Validate event - if (!event.type || !event.data) { - throw new Error("Invalid event format"); - } - - // Simulate Redis operation - await new Promise((resolve) => setTimeout(resolve, Math.random() * 20)); - - // Simulate occasional failures (0.5% rate for Redis) - if (simulatedFailuresEnabled() && Math.random() < 0.005) { - throw new Error("Simulated Redis error"); - } - } - - /** - * Set a cache value. - */ - async set( - key: string, - value: unknown, - ttl?: number, - ): Promise { - const expireAt = ttl ? Date.now() + ttl * 1000 : undefined; - - const event: ServiceEvent = { - type: "event", - data: { - operation: "set", - key, - value, - ttl, - }, - timestamp: new Date().toISOString(), - tags: { - operation: "set", - }, - }; - - const success = await this.send(event); - - if (success) { - this.cache.set(key, { value, expireAt }); - this.stats.sets++; - } - - return success; - } - - /** - * Get a cache value. - */ - async get(key: string): Promise { - const event: ServiceEvent = { - type: "event", - data: { - operation: "get", - key, - }, - timestamp: new Date().toISOString(), - tags: { - operation: "get", - }, - }; - - await this.send(event); - - const entry = this.cache.get(key); - - if (!entry) { - this.stats.misses++; - return undefined; - } - - // Check expiration - if (entry.expireAt && entry.expireAt < Date.now()) { - this.cache.delete(key); - this.stats.misses++; - return undefined; - } - - this.stats.hits++; - return entry.value; - } - - /** - * Delete a cache key. - */ - async delete(key: string): Promise { - const event: ServiceEvent = { - type: "event", - data: { - operation: "delete", - key, - }, - timestamp: new Date().toISOString(), - tags: { - operation: "delete", - }, - }; - - const success = await this.send(event); - - if (success) { - const deleted = this.cache.delete(key); - if (deleted) { - this.stats.deletes++; - } - } - - return success; - } - - /** - * Check if key exists. - */ - async exists(key: string): Promise { - const entry = this.cache.get(key); - - if (!entry) { - return false; - } - - // Check expiration - if (entry.expireAt && entry.expireAt < Date.now()) { - this.cache.delete(key); - return false; - } - - return true; - } - - /** - * Clear all cache. - */ - async clear(): Promise { - const event: ServiceEvent = { - type: "event", - data: { - operation: "clear", - }, - timestamp: new Date().toISOString(), - tags: { - operation: "clear", - }, - }; - - const success = await this.send(event); - - if (success) { - this.cache.clear(); - } - - return success; - } - - /** - * Get all cache keys. - */ - keys(): string[] { - const now = Date.now(); - const validKeys: string[] = []; - - for (const [key, entry] of this.cache.entries()) { - // Skip expired keys - if (!entry.expireAt || entry.expireAt >= now) { - validKeys.push(key); - } - } - - return validKeys; - } - - /** - * Get cache size. - */ - size(): number { - return this.cache.size; - } - - /** - * Get cache statistics. - */ - getCacheStats(): { - hits: number; - misses: number; - sets: number; - deletes: number; - hitRate: number; - size: number; - } { - const total = this.stats.hits + this.stats.misses; - const hitRate = total > 0 ? (this.stats.hits / total) * 100 : 0; - - return { - ...this.stats, - hitRate: Math.round(hitRate * 100) / 100, - size: this.cache.size, - }; - } - - /** - * Flush all queued events. - */ - private async flushQueue(): Promise { - const queued = this.getQueuedEvents(); - if (queued.length === 0) return; - - const { sent, failed } = await this.batch(queued); - - if (sent > 0) { - this.clearQueue(); - } - - console.log(`Flushed Redis queue: ${sent} sent, ${failed} failed`); - } - - /** - * Get Redis configuration info. - */ - getInfo(): { - endpoint: string; - connected: boolean; - cacheSize: number; - keyCount: number; - } { - return { - endpoint: this.config.endpoint || "", - connected: this.connected, - cacheSize: this.cache.size, - keyCount: this.keys().length, - }; - } -} - -/** - * Create a Redis adapter from environment variables. - */ -export function createRedisAdapter(enabled: boolean = true): RedisAdapter { - const endpoint = process.env.REDIS_URL || process.env.REDIS_ENDPOINT; - - if (enabled && !endpoint) { - console.warn( - "Redis is enabled but REDIS_URL/REDIS_ENDPOINT environment variable is not set", - ); - } - - return new RedisAdapter({ - enabled: enabled && !!endpoint, - endpoint, - }); -} diff --git a/src/resilience-tests.ts b/src/resilience-tests.ts deleted file mode 100644 index 4fd51b2b..00000000 --- a/src/resilience-tests.ts +++ /dev/null @@ -1,350 +0,0 @@ -/** - * Resilience Testing Suite - * - * Validates system resilience metrics: - * - RTO (Recovery Time Objective): <5 minutes - * - RPO (Recovery Point Objective): <24 hours - * - Failover: Automatic with no data loss - * - Retry: Exponential backoff with jitter - */ - -export interface ResilienceMetrics { - rtoSeconds: number; - rpoHours: number; - failoverAutomatic: boolean; - dataLossItems: number; - alertDelaySeconds: number; - recoveryAttempts: number; -} - -export interface TestResult { - passed: boolean; - metric: string; - expected: string; - actual: string; - failureReason?: string; -} - -export class ResilienceTestSuite { - private metrics: ResilienceMetrics = { - rtoSeconds: 0, - rpoHours: 0, - failoverAutomatic: false, - dataLossItems: 0, - alertDelaySeconds: 0, - recoveryAttempts: 0, - }; - - private results: TestResult[] = []; - - /** - * Test RTO (Recovery Time Objective) - * Target: <5 minutes (300 seconds) - */ - testRTO(): TestResult { - const RTOTarget = 300; - const passed = this.metrics.rtoSeconds <= RTOTarget; - - const result: TestResult = { - passed, - metric: 'RTO', - expected: `<${RTOTarget}s`, - actual: `${this.metrics.rtoSeconds}s`, - failureReason: passed ? undefined : `RTO exceeded target by ${this.metrics.rtoSeconds - RTOTarget}s`, - }; - - this.results.push(result); - return result; - } - - /** - * Test RPO (Recovery Point Objective) - * Target: <24 hours - */ - testRPO(): TestResult { - const RPOTarget = 24; - const passed = this.metrics.rpoHours <= RPOTarget; - - const result: TestResult = { - passed, - metric: 'RPO', - expected: `<${RPOTarget}h`, - actual: `${this.metrics.rpoHours}h`, - failureReason: passed ? undefined : `RPO exceeded target by ${this.metrics.rpoHours - RPOTarget}h`, - }; - - this.results.push(result); - return result; - } - - /** - * Test Automatic Failover - * Validates failover happens without manual intervention - */ - testAutomaticFailover(): TestResult { - const passed = this.metrics.failoverAutomatic; - - const result: TestResult = { - passed, - metric: 'Automatic Failover', - expected: 'true', - actual: this.metrics.failoverAutomatic.toString(), - failureReason: passed ? undefined : 'Failover requires manual intervention', - }; - - this.results.push(result); - return result; - } - - /** - * Test Data Loss - * Target: Zero data loss - */ - testDataLoss(): TestResult { - const passed = this.metrics.dataLossItems === 0; - - const result: TestResult = { - passed, - metric: 'Data Loss', - expected: '0 items', - actual: `${this.metrics.dataLossItems} items`, - failureReason: passed ? undefined : `Data loss detected: ${this.metrics.dataLossItems} items`, - }; - - this.results.push(result); - return result; - } - - /** - * Test Alert Response Time - * Target: Detection within 90 seconds - */ - testAlertResponse(): TestResult { - const AlertTarget = 90; - const passed = this.metrics.alertDelaySeconds <= AlertTarget; - - const result: TestResult = { - passed, - metric: 'Alert Detection', - expected: `<${AlertTarget}s`, - actual: `${this.metrics.alertDelaySeconds}s`, - failureReason: passed ? undefined : `Alert delayed by ${this.metrics.alertDelaySeconds - AlertTarget}s`, - }; - - this.results.push(result); - return result; - } - - /** - * Test Recovery Attempts - * Valid: 1-3 attempts (not too quick, not too slow) - */ - testRecoveryAttempts(): TestResult { - const minAttempts = 1; - const maxAttempts = 3; - const passed = this.metrics.recoveryAttempts >= minAttempts && this.metrics.recoveryAttempts <= maxAttempts; - - const result: TestResult = { - passed, - metric: 'Recovery Attempts', - expected: `${minAttempts}-${maxAttempts}`, - actual: `${this.metrics.recoveryAttempts}`, - failureReason: passed ? undefined : `Recovery attempts out of range`, - }; - - this.results.push(result); - return result; - } - - /** - * Run all resilience tests - */ - runAll(): boolean { - this.testRTO(); - this.testRPO(); - this.testAutomaticFailover(); - this.testDataLoss(); - this.testAlertResponse(); - this.testRecoveryAttempts(); - - return this.results.every((r) => r.passed); - } - - /** - * Generate test report - */ - generateReport(): string { - const passed = this.results.filter((r) => r.passed).length; - const total = this.results.length; - const passRate = ((passed / total) * 100).toFixed(1); - - let report = ` -=== Resilience Test Report === -Date: ${new Date().toISOString()} -Results: ${passed}/${total} passed (${passRate}%) - -`; - - for (const result of this.results) { - const status = result.passed ? '✅' : '❌'; - report += `${status} ${result.metric}: ${result.actual} (expected: ${result.expected})`; - if (result.failureReason) { - report += `\n Reason: ${result.failureReason}`; - } - report += '\n'; - } - - report += ` -Metrics Summary: -- RTO: ${this.metrics.rtoSeconds}s (target: <300s) -- RPO: ${this.metrics.rpoHours}h (target: <24h) -- Failover: ${this.metrics.failoverAutomatic ? 'Automatic' : 'Manual'} -- Data Loss: ${this.metrics.dataLossItems} items (target: 0) -- Alert Delay: ${this.metrics.alertDelaySeconds}s (target: <90s) -- Recovery Attempts: ${this.metrics.recoveryAttempts} (target: 1-3) - -Overall: ${passed === total ? 'PASS' : 'FAIL'} -`; - - return report; - } - - /** - * Update metrics from test results - */ - updateMetrics(metrics: Partial): void { - this.metrics = { ...this.metrics, ...metrics }; - } - - /** - * Get current metrics - */ - getMetrics(): ResilienceMetrics { - return this.metrics; - } - - /** - * Get test results - */ - getResults(): TestResult[] { - return this.results; - } -} - -/** - * Exponential Backoff Strategy Validator - * Ensures retry logic follows best practices - */ -export class BackoffValidator { - /** - * Validate exponential backoff sequence - * - First attempt: 1s - * - Second attempt: 2s (±jitter) - * - Third attempt: 4s (±jitter) - * - Max: 32s - */ - static validateBackoff(delays: number[]): boolean { - const minBackoffs = [1000, 2000, 4000]; - const maxBackoffs = [1100, 2200, 4400]; - const maxDelay = 32000; - - if (delays.length === 0) { - return false; - } - - for (let i = 0; i < Math.min(delays.length, 3); i++) { - const delay = delays[i]; - - if (i < 3) { - // Check exponential sequence with jitter tolerance (10%) - if (delay < minBackoffs[i] || delay > maxBackoffs[i]) { - console.error( - `Delay ${i}: ${delay}ms not in range [${minBackoffs[i]}, ${maxBackoffs[i]}]` - ); - return false; - } - } - - if (delay > maxDelay) { - console.error(`Delay exceeds max: ${delay}ms > ${maxDelay}ms`); - return false; - } - } - - return true; - } - - /** - * Calculate recommended backoff delay - */ - static calculateBackoff(attempt: number): number { - const minBackoff = 1000; - const maxBackoff = 32000; - const exponential = Math.min(maxBackoff, minBackoff * Math.pow(2, attempt)); - const jitter = exponential * 0.1 * (Math.random() - 0.5) * 2; - - return Math.round(exponential + jitter); - } -} - -/** - * Circuit Breaker Pattern Validator - * Ensures circuit breaker is configured correctly - */ -export class CircuitBreakerValidator { - private state: 'closed' | 'open' | 'half-open' = 'closed'; - private failureCount = 0; - private failureThreshold = 5; - private successThreshold = 2; - private successCount = 0; - - /** - * Record request result - */ - recordResult(success: boolean): void { - if (this.state === 'closed') { - if (success) { - this.failureCount = 0; - } else { - this.failureCount++; - if (this.failureCount >= this.failureThreshold) { - this.state = 'open'; - console.log('Circuit breaker opened'); - } - } - } else if (this.state === 'open') { - // After timeout, move to half-open - this.state = 'half-open'; - this.successCount = 0; - console.log('Circuit breaker half-open'); - } else if (this.state === 'half-open') { - if (success) { - this.successCount++; - if (this.successCount >= this.successThreshold) { - this.state = 'closed'; - this.failureCount = 0; - console.log('Circuit breaker closed'); - } - } else { - this.state = 'open'; - console.log('Circuit breaker reopened'); - } - } - } - - /** - * Check if requests should be allowed - */ - isAllowed(): boolean { - return this.state !== 'open'; - } - - /** - * Get current state - */ - getState(): string { - return this.state; - } -} - -export default ResilienceTestSuite; diff --git a/src/security-hardening.test.ts b/src/security-hardening.test.ts deleted file mode 100644 index 6069c064..00000000 --- a/src/security-hardening.test.ts +++ /dev/null @@ -1,273 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { - SecurityHardeningEngine, - type Vulnerability, -} from "./security-hardening.js"; - -function makeVuln(id: string, overrides: Partial = {}): Vulnerability { - return { - id, - type: "dependency", - severity: "high", - affectedPackage: "lodash", - affectedVersion: "4.17.0", - description: "Vulnerability in lodash", - discoveredAt: new Date().toISOString(), - remediationSteps: ["Update to 4.17.21"], - ...overrides, - }; -} - -describe("SecurityHardeningEngine", () => { - describe("vulnerability management", () => { - let engine: SecurityHardeningEngine; - - beforeEach(() => { - engine = new SecurityHardeningEngine(); - }); - - it("registers a vulnerability", () => { - const vuln = makeVuln("CVE-2021-1234"); - engine.registerVulnerability(vuln); - assert.equal(engine.getVulnerability("CVE-2021-1234"), vuln); - }); - - it("scans dependencies for vulnerabilities", () => { - engine.registerVulnerability( - makeVuln("CVE-1", { affectedPackage: "lodash", affectedVersion: "4.17.0" }), - ); - const deps = [{ name: "lodash", version: "4.17.0" }]; - const found = engine.scanDependencies("plugin-1", deps); - assert.equal(found.length, 1); - }); - - it("skips unaffected versions", () => { - engine.registerVulnerability( - makeVuln("CVE-1", { affectedPackage: "lodash", affectedVersion: "4.17.0" }), - ); - const deps = [{ name: "lodash", version: "4.17.21" }]; - const found = engine.scanDependencies("plugin-1", deps); - assert.equal(found.length, 0); - }); - - it("gets all vulnerabilities", () => { - engine.registerVulnerability(makeVuln("CVE-1")); - engine.registerVulnerability(makeVuln("CVE-2")); - const all = engine.getAllVulnerabilities(); - assert.equal(all.length, 2); - }); - }); - - describe("security checks", () => { - let engine: SecurityHardeningEngine; - - beforeEach(() => { - engine = new SecurityHardeningEngine(); - }); - - it("runs dependency scan check", () => { - const result = engine.runSecurityCheck("dependency_scan", "plugin-1", { - dependencies: [{ name: "safe-pkg", version: "1.0.0" }], - }); - assert.equal(result.type, "dependency_scan"); - assert(result.passed); - }); - - it("fails on dangerous permissions", () => { - const result = engine.runSecurityCheck("permission_check", "plugin-1", { - permissions: ["root"], - }); - assert(!result.passed); - assert.equal(result.severity, "critical"); - }); - - it("detects missing encryption", () => { - const result = engine.runSecurityCheck("encryption", "plugin-1", { - usesEncryption: false, - }); - assert(!result.passed); - assert.equal(result.severity, "medium"); - }); - - it("detects missing authentication", () => { - const result = engine.runSecurityCheck("auth_check", "plugin-1", { - hasAuthentication: false, - }); - assert(!result.passed); - assert.equal(result.severity, "high"); - }); - - it("passes on proper authentication", () => { - const result = engine.runSecurityCheck("auth_check", "plugin-1", { - hasAuthentication: true, - authMethod: "jwt", - }); - assert(result.passed); - }); - }); - - describe("audit logging", () => { - let engine: SecurityHardeningEngine; - - beforeEach(() => { - engine = new SecurityHardeningEngine(); - }); - - it("logs audit events", () => { - const entry = engine.logAuditEvent( - "plugin_published", - "author-1", - "plugin-stripe", - "success", - ); - assert(entry.id); - assert.equal(entry.action, "plugin_published"); - }); - - it("retrieves audit log", () => { - engine.logAuditEvent("event1", "user-1", "resource", "success"); - engine.logAuditEvent("event2", "user-2", "resource", "failure"); - const log = engine.getAuditLog(10); - assert.equal(log.length, 2); - }); - - it("filters by actor", () => { - engine.logAuditEvent("event1", "user-1", "resource", "success"); - engine.logAuditEvent("event2", "user-1", "resource", "success"); - engine.logAuditEvent("event3", "user-2", "resource", "success"); - - const user1Log = engine.getAuditLogForActor("user-1"); - assert.equal(user1Log.length, 2); - }); - - it("gets failed events", () => { - engine.logAuditEvent("event1", "user-1", "resource", "success"); - engine.logAuditEvent("event2", "user-1", "resource", "failure"); - engine.logAuditEvent("event3", "user-1", "resource", "failure"); - - const failed = engine.getFailedAuditEvents(); - assert.equal(failed.length, 2); - }); - }); - - describe("rate limiting", () => { - let engine: SecurityHardeningEngine; - - beforeEach(() => { - engine = new SecurityHardeningEngine(); - }); - - it("configures rate limits", () => { - engine.configureRateLimit("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/api/plugins", { - windowMs: 60000, - maxRequests: 100, - }); - // Configuration stored - assert(true); - }); - - it("checks rate limit status", () => { - engine.configureRateLimit("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/api/plugins", { windowMs: 60000, maxRequests: 100 }); - const status = engine.checkRateLimit("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/api/plugins", "user-1"); - assert.equal(status.requestCount, 1); - assert(status.remaining > 0); - }); - - it("increments request count", () => { - engine.checkRateLimit("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/api/plugins", "user-1"); - const status = engine.checkRateLimit("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/api/plugins", "user-1"); - assert.equal(status.requestCount, 2); - }); - - it("resets rate limit", () => { - engine.checkRateLimit("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/api/plugins", "user-1"); - engine.resetRateLimit("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/api/plugins", "user-1"); - const status = engine.checkRateLimit("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/api/plugins", "user-1"); - assert.equal(status.requestCount, 1); - }); - }); - - describe("security policies", () => { - let engine: SecurityHardeningEngine; - - beforeEach(() => { - engine = new SecurityHardeningEngine(); - }); - - it("creates a security policy", () => { - const policy = engine.createPolicy("Strict Security", "High security policy", [ - "require-https", - "require-auth", - ]); - assert(policy.id); - assert.equal(policy.name, "Strict Security"); - assert.equal(policy.rules.length, 2); - }); - - it("retrieves policy by ID", () => { - const created = engine.createPolicy("Test Policy", "Description", ["rule1"]); - const retrieved = engine.getPolicy(created.id); - assert.equal(retrieved?.name, "Test Policy"); - }); - - it("gets all policies", () => { - engine.createPolicy("Policy 1", "Desc", ["rule1"]); - engine.createPolicy("Policy 2", "Desc", ["rule2"]); - const all = engine.getAllPolicies(); - assert.equal(all.length, 2); - }); - }); - - describe("security reports", () => { - let engine: SecurityHardeningEngine; - - beforeEach(() => { - engine = new SecurityHardeningEngine(); - }); - - it("generates security report", () => { - engine.runSecurityCheck("auth_check", "plugin-1", { - hasAuthentication: true, - authMethod: "jwt", - }); - const report = engine.generateSecurityReport("plugin-1"); - assert(report.score >= 0 && report.score <= 100); - assert(report.status); - }); - - it("calculates security score", () => { - engine.runSecurityCheck("auth_check", "plugin-1", { - hasAuthentication: true, - authMethod: "jwt", - }); - const score = engine.getSecurityScore("plugin-1"); - assert(score > 0); - }); - - it("marks report as pass for high score", () => { - engine.runSecurityCheck("auth_check", "plugin-1", { - hasAuthentication: true, - authMethod: "jwt", - }); - const report = engine.generateSecurityReport("plugin-1"); - if (report.score >= 80) { - assert.equal(report.status, "pass"); - } - }); - - it("marks report as fail for low score", () => { - engine.registerVulnerability(makeVuln("CVE-1")); - // Add multiple failures - for (let i = 0; i < 5; i++) { - engine.runSecurityCheck("permission_check", "plugin-1", { - permissions: ["root"], - }); - } - const report = engine.generateSecurityReport("plugin-1"); - if (report.score < 60) { - assert.equal(report.status, "fail"); - } - }); - }); -}); diff --git a/src/security-hardening.ts b/src/security-hardening.ts deleted file mode 100644 index 9e27a1d7..00000000 --- a/src/security-hardening.ts +++ /dev/null @@ -1,422 +0,0 @@ -import { IdGenerators } from "./id-generator.js"; -// ─── Types ──────────────────────────────────────────────────────────────────── - -export type VulnerabilitySeverity = "critical" | "high" | "medium" | "low" | "info"; -export type SecurityCheckType = - | "dependency_scan" - | "code_analysis" - | "permission_check" - | "rate_limit" - | "encryption" - | "auth_check"; - -export interface Vulnerability { - id: string; - cve?: string; - type: string; - severity: VulnerabilitySeverity; - affectedPackage: string; - affectedVersion: string; - fixedVersion?: string; - description: string; - discoveredAt: string; - remediationSteps: string[]; -} - -export interface SecurityCheckResult { - type: SecurityCheckType; - passed: boolean; - message: string; - details: Record; - severity: VulnerabilitySeverity; - timestamp: string; -} - -export interface SecurityAuditEntry { - id: string; - action: string; - actor: string; - resource: string; - status: "success" | "failure"; - details: Record; - timestamp: string; - ipAddress?: string; -} - -export interface RateLimitConfig { - windowMs: number; // milliseconds - maxRequests: number; - message?: string; - keyGenerator?: (req: unknown) => string; -} - -export interface RateLimitStatus { - requestCount: number; - resetTime: Date; - remaining: number; - retryAfter?: number; -} - -export interface SecurityPolicy { - id: string; - name: string; - description: string; - rules: Array<{ - rule: string; - enabled: boolean; - severity: VulnerabilitySeverity; - }>; - createdAt: string; - updatedAt: string; -} - -export interface SecurityReport { - pluginId: string; - timestamp: string; - vulnerabilities: Vulnerability[]; - checks: SecurityCheckResult[]; - score: number; // 0-100, 100 = most secure - status: "pass" | "warning" | "fail"; -} - -// ─── SecurityHardeningEngine ────────────────────────────────────────────────── - -export class SecurityHardeningEngine { - private vulnerabilities: Map = new Map(); - private auditLog: SecurityAuditEntry[] = []; - private rateLimiters: Map> = new Map(); - private securityPolicies: Map = new Map(); - private checksResults: Map = new Map(); - - // ─── Vulnerability Management ──────────────────────────────────────────── - - /** - * Register a known vulnerability. - */ - registerVulnerability(vuln: Vulnerability): void { - this.vulnerabilities.set(vuln.id, vuln); - } - - /** - * Scan dependencies for known vulnerabilities. - */ - scanDependencies( - pluginId: string, - dependencies: Array<{ name: string; version: string }>, - ): Vulnerability[] { - const found: Vulnerability[] = []; - - for (const dep of dependencies) { - for (const vuln of this.vulnerabilities.values()) { - if ( - vuln.affectedPackage === dep.name && - this.versionMatches(dep.version, vuln.affectedVersion) - ) { - found.push(vuln); - } - } - } - - return found; - } - - private versionMatches(current: string, affected: string): boolean { - // Simple version matching: affected "*" matches all, or exact match - if (affected === "*") return true; - return current === affected; - } - - /** - * Get vulnerability by ID. - */ - getVulnerability(vulnId: string): Vulnerability | null { - return this.vulnerabilities.get(vulnId) || null; - } - - /** - * Get all vulnerabilities. - */ - getAllVulnerabilities(): Vulnerability[] { - return [...this.vulnerabilities.values()]; - } - - // ─── Security Checks ────────────────────────────────────────────────────── - - /** - * Run a security check. - */ - runSecurityCheck( - type: SecurityCheckType, - pluginId: string, - data: Record, - ): SecurityCheckResult { - let result: SecurityCheckResult; - - switch (type) { - case "dependency_scan": - result = this.checkDependencyScan(pluginId, data); - break; - case "permission_check": - result = this.checkPermissions(pluginId, data); - break; - case "encryption": - result = this.checkEncryption(pluginId, data); - break; - case "auth_check": - result = this.checkAuthentication(pluginId, data); - break; - default: - result = { - type, - passed: true, - message: "Check skipped", - details: {}, - severity: "info", - timestamp: new Date().toISOString(), - }; - } - - // Store result - const results = this.checksResults.get(pluginId) || []; - results.push(result); - this.checksResults.set(pluginId, results); - - return result; - } - - private checkDependencyScan( - pluginId: string, - data: Record, - ): SecurityCheckResult { - const deps = data.dependencies as Array<{ name: string; version: string }> || []; - const vulns = this.scanDependencies(pluginId, deps); - - return { - type: "dependency_scan", - passed: vulns.length === 0, - message: vulns.length === 0 ? "No vulnerabilities found" : `${vulns.length} vulnerabilities found`, - details: { vulnerabilities: vulns }, - severity: vulns.length > 0 ? "high" : "info", - timestamp: new Date().toISOString(), - }; - } - - private checkPermissions(pluginId: string, data: Record): SecurityCheckResult { - const permissions = data.permissions as string[] || []; - const dangerous = ["root", "admin", "system"]; - const hasDangerous = permissions.some((p) => dangerous.includes(p)); - - return { - type: "permission_check", - passed: !hasDangerous, - message: hasDangerous ? "Dangerous permissions detected" : "Safe permission levels", - details: { permissions, hasDangerous }, - severity: hasDangerous ? "critical" : "info", - timestamp: new Date().toISOString(), - }; - } - - private checkEncryption(pluginId: string, data: Record): SecurityCheckResult { - const usesEncryption = data.usesEncryption === true; - const algorithm = data.algorithm as string || "unknown"; - - return { - type: "encryption", - passed: usesEncryption && ["AES-256", "TLS", "HTTPS"].includes(algorithm), - message: usesEncryption ? "Encryption enabled" : "Encryption not found", - details: { usesEncryption, algorithm }, - severity: usesEncryption ? "info" : "medium", - timestamp: new Date().toISOString(), - }; - } - - private checkAuthentication(pluginId: string, data: Record): SecurityCheckResult { - const hasAuth = data.hasAuthentication === true; - const authMethod = data.authMethod as string || "none"; - - return { - type: "auth_check", - passed: hasAuth && ["oauth", "jwt", "apikey"].includes(authMethod), - message: hasAuth ? "Authentication configured" : "No authentication found", - details: { hasAuth, authMethod }, - severity: hasAuth ? "info" : "high", - timestamp: new Date().toISOString(), - }; - } - - // ─── Audit Logging ──────────────────────────────────────────────────────── - - /** - * Log a security audit event. - */ - logAuditEvent( - action: string, - actor: string, - resource: string, - status: "success" | "failure", - details: Record = {}, - ipAddress?: string, - ): SecurityAuditEntry { - const id = IdGenerators.audit(); - const entry: SecurityAuditEntry = { - id, - action, - actor, - resource, - status, - details, - timestamp: new Date().toISOString(), - ipAddress, - }; - - this.auditLog.push(entry); - return entry; - } - - /** - * Get audit log entries. - */ - getAuditLog(limit = 100, offset = 0): SecurityAuditEntry[] { - return this.auditLog.slice(offset, offset + limit); - } - - /** - * Get audit log entries for actor. - */ - getAuditLogForActor(actor: string): SecurityAuditEntry[] { - return this.auditLog.filter((e) => e.actor === actor); - } - - /** - * Get failed audit events. - */ - getFailedAuditEvents(): SecurityAuditEntry[] { - return this.auditLog.filter((e) => e.status === "failure"); - } - - // ─── Rate Limiting ──────────────────────────────────────────────────────── - - /** - * Configure rate limiting for an endpoint. - */ - configureRateLimit(endpoint: string, config: RateLimitConfig): void { - const limiters = this.rateLimiters.get(endpoint) || new Map(); - // Store config (simplified - in real implementation would use the config) - this.rateLimiters.set(endpoint, limiters); - } - - /** - * Check if a request is rate limited. - */ - checkRateLimit(endpoint: string, key: string): RateLimitStatus { - const limiters = this.rateLimiters.get(endpoint) || new Map(); - const status = limiters.get(key) || { - requestCount: 0, - resetTime: new Date(Date.now() + 60000), // 1 minute window - remaining: 100, - }; - - status.requestCount++; - status.remaining = Math.max(0, 100 - status.requestCount); - - limiters.set(key, status); - this.rateLimiters.set(endpoint, limiters); - - return status; - } - - /** - * Reset rate limit for a key. - */ - resetRateLimit(endpoint: string, key: string): void { - const limiters = this.rateLimiters.get(endpoint); - limiters?.delete(key); - } - - // ─── Security Policies ──────────────────────────────────────────────────── - - /** - * Create a security policy. - */ - createPolicy(name: string, description: string, rules: string[]): SecurityPolicy { - const id = IdGenerators.policy(); - const policy: SecurityPolicy = { - id, - name, - description, - rules: rules.map((rule) => ({ - rule, - enabled: true, - severity: "high", - })), - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }; - - this.securityPolicies.set(id, policy); - return policy; - } - - /** - * Get security policy. - */ - getPolicy(policyId: string): SecurityPolicy | null { - return this.securityPolicies.get(policyId) || null; - } - - /** - * Get all policies. - */ - getAllPolicies(): SecurityPolicy[] { - return [...this.securityPolicies.values()]; - } - - // ─── Security Report Generation ─────────────────────────────────────────── - - /** - * Generate security report for a plugin. - */ - generateSecurityReport(pluginId: string): SecurityReport { - const vulns = this.scanDependencies(pluginId, []); - const checks = this.checksResults.get(pluginId) || []; - - // Calculate score: 100 - (vulnerabilities * 10 + failed_checks * 5) - let score = 100; - score -= vulns.length * 10; - score -= checks.filter((c) => !c.passed).length * 5; - score = Math.max(0, Math.min(100, score)); - - const status = score >= 80 ? "pass" : score >= 60 ? "warning" : "fail"; - - return { - pluginId, - timestamp: new Date().toISOString(), - vulnerabilities: vulns, - checks, - score, - status, - }; - } - - /** - * Get security score for plugin. - */ - getSecurityScore(pluginId: string): number { - const report = this.generateSecurityReport(pluginId); - return report.score; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getVulnerabilitiesCache(): Map { - return this.vulnerabilities; - } - - getAuditLogCache(): SecurityAuditEntry[] { - return this.auditLog; - } - - getPoliciesCache(): Map { - return this.securityPolicies; - } -} diff --git a/src/sentry-adapter.test.ts b/src/sentry-adapter.test.ts deleted file mode 100644 index 8643b5fa..00000000 --- a/src/sentry-adapter.test.ts +++ /dev/null @@ -1,540 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { SentryAdapter, createSentryAdapter } from "./sentry-adapter.js"; - -describe("SentryAdapter", () => { - describe("initialization", () => { - it("creates adapter with config", () => { - const adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - - assert.equal(adapter.name, "sentry"); - assert.equal(adapter.version, "1.0.0"); - }); - - it("initializes with disabled config", () => { - const adapter = new SentryAdapter({ enabled: false }); - assert(!adapter.isConnected()); - }); - - it("creates adapter with default config", () => { - const adapter = new SentryAdapter(); - assert(!adapter.isConnected()); - }); - }); - - describe("connection management", () => { - let adapter: SentryAdapter; - - beforeEach(() => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - }); - - it("connects with valid DSN", async () => { - await adapter.connect(); - assert(adapter.isConnected()); - }); - - it("throws error when enabled without DSN", async () => { - const invalidAdapter = new SentryAdapter({ enabled: true }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("DSN is required")); - } - }); - - it("throws error with invalid DSN", async () => { - const invalidAdapter = new SentryAdapter({ - enabled: true, - dsn: "not-a-valid-dsn", - }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid Sentry DSN")); - } - }); - - it("throws error with invalid DSN protocol", async () => { - const invalidAdapter = new SentryAdapter({ - enabled: true, - dsn: "ftp://invalid@o0.ingest.sentry.io/0", - }); - - try { - await invalidAdapter.connect(); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid DSN protocol")); - } - }); - - it("disconnects cleanly", async () => { - await adapter.connect(); - assert(adapter.isConnected()); - - await adapter.disconnect(); - assert(!adapter.isConnected()); - }); - - it("skips connection when disabled", async () => { - const disabledAdapter = new SentryAdapter({ - enabled: false, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - - await disabledAdapter.connect(); - assert(!disabledAdapter.isConnected()); - }); - }); - - describe("health monitoring", () => { - let adapter: SentryAdapter; - - beforeEach(async () => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - await adapter.connect(); - }); - - it("reports healthy status when connected", async () => { - const health = await adapter.getHealth(); - - assert.equal(health.status, "healthy"); - assert(health.lastCheck); - assert(health.responseTime >= 0); - assert.equal(health.errorCount, 0); - }); - - it("records response time", async () => { - const health = await adapter.getHealth(); - assert(typeof health.responseTime === "number"); - }); - - it("updates lastCheck timestamp", async () => { - const before = new Date(); - const health = await adapter.getHealth(); - const after = new Date(); - - const lastCheck = new Date(health.lastCheck); - - assert(lastCheck >= before); - assert(lastCheck <= after); - }); - }); - - describe("exception capturing", () => { - let adapter: SentryAdapter; - - beforeEach(async () => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - await adapter.connect(); - }); - - it("captures exception", async () => { - const error = new Error("Test error"); - const result = await adapter.captureException(error); - - assert.equal(result, true); - }); - - it("captures exception with context", async () => { - const error = new Error("Test error"); - const result = await adapter.captureException(error, { - userId: "user123", - action: "fetch_data", - }); - - assert.equal(result, true); - }); - - it("includes error message in event", async () => { - const error = new Error("Specific error message"); - const result = await adapter.captureException(error); - - assert.equal(result, true); - }); - - it("includes error stack in event", async () => { - const error = new Error("Error with stack"); - await adapter.captureException(error); - - assert(error.stack); - }); - - it("tags exception event type", async () => { - const error = new Error("Tagged error"); - const result = await adapter.captureException(error); - - assert.equal(result, true); - }); - - it("fails to send when disconnected", async () => { - await adapter.disconnect(); - - const error = new Error("Disconnected error"); - const result = await adapter.captureException(error); - - assert.equal(result, false); - }); - }); - - describe("message logging", () => { - let adapter: SentryAdapter; - - beforeEach(async () => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - await adapter.connect(); - }); - - it("captures info message", async () => { - const result = await adapter.captureMessage("Test message"); - - assert.equal(result, true); - }); - - it("captures message with debug level", async () => { - const result = await adapter.captureMessage("Debug message", "debug"); - - assert.equal(result, true); - }); - - it("captures message with info level", async () => { - const result = await adapter.captureMessage("Info message", "info"); - - assert.equal(result, true); - }); - - it("captures message with warning level", async () => { - const result = await adapter.captureMessage("Warning message", "warning"); - - assert.equal(result, true); - }); - - it("captures message with error level", async () => { - const result = await adapter.captureMessage("Error message", "error"); - - assert.equal(result, true); - }); - - it("captures message with fatal level", async () => { - const result = await adapter.captureMessage("Fatal message", "fatal"); - - assert.equal(result, true); - }); - - it("defaults to info level", async () => { - const result = await adapter.captureMessage("Default level message"); - - assert.equal(result, true); - }); - - it("fails when disconnected", async () => { - await adapter.disconnect(); - - const result = await adapter.captureMessage("Disconnected message"); - - assert.equal(result, false); - }); - }); - - describe("transaction management", () => { - let adapter: SentryAdapter; - - beforeEach(async () => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - await adapter.connect(); - }); - - it("starts transaction", async () => { - const txnId = await adapter.startTransaction("fetch-data", "http.request"); - - assert(txnId); - assert(txnId.startsWith("txn-")); - }); - - it("starts transaction with default operation", async () => { - const txnId = await adapter.startTransaction("fetch-data"); - - assert(txnId); - }); - - it("generates unique transaction IDs", async () => { - const txnId1 = await adapter.startTransaction("fetch1"); - const txnId2 = await adapter.startTransaction("fetch2"); - - assert.notEqual(txnId1, txnId2); - }); - - it("ends transaction with success", async () => { - const txnId = await adapter.startTransaction("fetch-data"); - await adapter.endTransaction(txnId, "ok"); - - assert(true); - }); - - it("ends transaction with error", async () => { - const txnId = await adapter.startTransaction("failed-operation"); - await adapter.endTransaction(txnId, "error"); - - assert(true); - }); - - it("defaults to ok status", async () => { - const txnId = await adapter.startTransaction("operation"); - await adapter.endTransaction(txnId); - - assert(true); - }); - - it("queues transaction when disconnected", async () => { - await adapter.disconnect(); - - const txnId = await adapter.startTransaction("disconnected"); - assert(txnId); - assert(txnId.startsWith("txn-")); - }); - }); - - describe("user context", () => { - let adapter: SentryAdapter; - - beforeEach(async () => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - await adapter.connect(); - }); - - it("sets user context", async () => { - await adapter.setUser("user123"); - - assert(true); - }); - - it("sets user with metadata", async () => { - await adapter.setUser("user123", { - email: "user@example.com", - plan: "premium", - }); - - assert(true); - }); - - it("queues user context when disconnected", async () => { - await adapter.disconnect(); - - // Should not throw, just queue the event - await adapter.setUser("user123"); - - assert(true); - }); - }); - - describe("project info", () => { - let adapter: SentryAdapter; - - beforeEach(() => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/myorg/123456", - }); - }); - - it("parses DSN to get project ID", () => { - const info = adapter.getProjectInfo(); - - assert.equal(info.projectId, "123456"); - }); - - it("parses DSN to get organization", () => { - const info = adapter.getProjectInfo(); - - assert.equal(info.organization, "myorg"); - }); - - it("includes full DSN", () => { - const info = adapter.getProjectInfo(); - - assert(info.dsn.includes("examplePublicKey")); - }); - - it("handles missing DSN gracefully", () => { - const noAdapter = new SentryAdapter({ enabled: false }); - - const info = noAdapter.getProjectInfo(); - assert.equal(info.dsn, ""); - }); - - it("handles invalid DSN format", () => { - const invalidAdapter = new SentryAdapter({ - enabled: true, - dsn: "invalid", - }); - - const info = invalidAdapter.getProjectInfo(); - assert(info.dsn); - }); - }); - - describe("event validation", () => { - let adapter: SentryAdapter; - - beforeEach(async () => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - await adapter.connect(); - }); - - it("requires event type", async () => { - try { - await (adapter as any).sendEvent({ - data: { message: "test" }, - timestamp: new Date().toISOString(), - }); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid event")); - } - }); - - it("requires event data", async () => { - try { - await (adapter as any).sendEvent({ - type: "log", - timestamp: new Date().toISOString(), - }); - assert.fail("Should have thrown error"); - } catch (error) { - assert((error as Error).message.includes("Invalid event")); - } - }); - }); - - describe("queue flushing", () => { - let adapter: SentryAdapter; - - beforeEach(() => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - }); - - it("flushes queued events on connection", async () => { - await adapter.captureMessage("Queued message 1"); - await adapter.captureMessage("Queued message 2"); - - await adapter.connect(); - - assert(adapter.isConnected()); - }); - - it("handles empty queue gracefully", async () => { - await adapter.connect(); - - assert(true); - }); - }); - - describe("error simulation", () => { - let adapter: SentryAdapter; - - beforeEach(async () => { - adapter = new SentryAdapter({ - enabled: true, - dsn: "https://examplePublicKey@o0.ingest.sentry.io/0", - }); - await adapter.connect(); - }); - - it("sometimes fails to send", async () => { - let failures = 0; - const attempts = 100; - - for (let i = 0; i < attempts; i++) { - const result = await adapter.captureMessage("Test"); - if (!result) { - failures++; - } - } - - assert(failures >= 0); - }); - }); - - describe("factory function", () => { - it("creates enabled adapter with SENTRY_DSN", () => { - const originalDsn = process.env.SENTRY_DSN; - - try { - process.env.SENTRY_DSN = "https://key@o0.ingest.sentry.io/0"; - - const adapter = createSentryAdapter(true); - - assert(adapter.config.enabled); - assert(adapter.config.dsn); - } finally { - process.env.SENTRY_DSN = originalDsn; - } - }); - - it("creates disabled adapter without DSN", () => { - const originalDsn = process.env.SENTRY_DSN; - - try { - delete process.env.SENTRY_DSN; - - const adapter = createSentryAdapter(true); - - assert(!adapter.config.enabled); - } finally { - process.env.SENTRY_DSN = originalDsn; - } - }); - - it("respects enabled parameter", () => { - const adapter = createSentryAdapter(false); - - assert(!adapter.config.enabled); - }); - - it("defaults to enabled", () => { - const originalDsn = process.env.SENTRY_DSN; - - try { - process.env.SENTRY_DSN = "https://key@o0.ingest.sentry.io/0"; - - const adapter = createSentryAdapter(); - - assert(adapter.config.enabled); - } finally { - process.env.SENTRY_DSN = originalDsn; - } - }); - }); -}); diff --git a/src/sentry-adapter.ts b/src/sentry-adapter.ts deleted file mode 100644 index d64f7063..00000000 --- a/src/sentry-adapter.ts +++ /dev/null @@ -1,280 +0,0 @@ -import { IdGenerators } from "./id-generator.js"; -// ─── Sentry Error Tracking Adapter ──────────────────────────────────────────── - -import { - AbstractServiceAdapter, - simulatedFailuresEnabled, - type ServiceConfig, - type ServiceEvent, - type ServiceHealth, -} from "./service-adapter.js"; - -/** - * Sentry adapter for error tracking and exception monitoring. - */ -export class SentryAdapter extends AbstractServiceAdapter { - private lastHealthCheck: string = new Date().toISOString(); - private healthCheckErrors: number = 0; - - constructor(config: ServiceConfig = { enabled: false }) { - super("sentry", "1.0.0", config); - } - - async connect(): Promise { - if (!this.config.enabled) { - this.connected = false; - return; - } - - if (!this.config.dsn) { - throw new Error("Sentry DSN is required"); - } - - // Parse DSN to validate format - try { - const url = new URL(this.config.dsn); - if (!url.protocol.includes("http")) { - throw new Error("Invalid DSN protocol"); - } - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - if (message.includes("Invalid DSN protocol")) { - throw error; - } - throw new Error("Invalid Sentry DSN format"); - } - - // Simulate connection test - await new Promise((resolve) => setTimeout(resolve, 100)); - - this.connected = true; - - // Flush queued events - await this.flushQueue(); - } - - async disconnect(): Promise { - if (this.healthCheckInterval) { - clearInterval(this.healthCheckInterval); - this.healthCheckInterval = null; - } - this.connected = false; - } - - async getHealth(): Promise { - const responseTime = Math.random() * 100; // Simulate response time - - try { - // Simulate health check - if (!this.connected) { - this.healthCheckErrors++; - } - - this.lastHealthCheck = new Date().toISOString(); - - const status = - this.healthCheckErrors < 3 - ? this.connected - ? "healthy" - : "degraded" - : "unhealthy"; - - return { - status, - lastCheck: this.lastHealthCheck, - responseTime: Math.round(responseTime), - errorCount: this.healthCheckErrors, - }; - } catch { - this.healthCheckErrors++; - return { - status: "unhealthy", - lastCheck: new Date().toISOString(), - responseTime: -1, - errorCount: this.healthCheckErrors, - }; - } - } - - protected async sendEvent(event: ServiceEvent): Promise { - if (!this.connected) { - throw new Error("Not connected to Sentry"); - } - - // Validate event - if (!event.type || !event.data) { - throw new Error("Invalid event format"); - } - - // Simulate sending to Sentry - await new Promise((resolve) => setTimeout(resolve, Math.random() * 50)); - - // Simulate occasional failures - if (simulatedFailuresEnabled() && Math.random() < 0.02) { - // 2% failure rate - throw new Error("Simulated Sentry API error"); - } - } - - /** - * Capture an exception. - */ - async captureException(error: Error, context?: Record): Promise { - const event: ServiceEvent = { - type: "error", - data: { - message: error.message, - stack: error.stack, - name: error.name, - ...context, - }, - timestamp: new Date().toISOString(), - tags: { - errorType: "exception", - }, - }; - - return this.send(event); - } - - /** - * Capture a message. - */ - async captureMessage( - message: string, - level: "debug" | "info" | "warning" | "error" | "fatal" = "info", - ): Promise { - const event: ServiceEvent = { - type: "log", - data: { - message, - level, - }, - timestamp: new Date().toISOString(), - tags: { - level, - }, - }; - - return this.send(event); - } - - /** - * Start a transaction (for performance monitoring). - */ - async startTransaction(name: string, op: string = "http.request"): Promise { - const transactionId = IdGenerators.transaction(); - - const event: ServiceEvent = { - type: "trace", - data: { - transactionId, - name, - operation: op, - startTime: Date.now(), - }, - timestamp: new Date().toISOString(), - }; - - await this.send(event); - return transactionId; - } - - /** - * End a transaction. - */ - async endTransaction(transactionId: string, status: "ok" | "error" = "ok"): Promise { - const event: ServiceEvent = { - type: "trace", - data: { - transactionId, - status, - endTime: Date.now(), - }, - timestamp: new Date().toISOString(), - }; - - await this.send(event); - } - - /** - * Set user context. - */ - async setUser(userId: string, metadata?: Record): Promise { - const event: ServiceEvent = { - type: "event", - data: { - userId, - metadata, - }, - timestamp: new Date().toISOString(), - tags: { - context: "user", - }, - }; - - await this.send(event); - } - - /** - * Flush all queued events. - */ - private async flushQueue(): Promise { - const queued = this.getQueuedEvents(); - if (queued.length === 0) return; - - const { sent, failed } = await this.batch(queued); - - if (sent > 0) { - this.clearQueue(); - } - - console.log(`Flushed Sentry queue: ${sent} sent, ${failed} failed`); - } - - /** - * Get Sentry project info. - */ - getProjectInfo(): { - dsn: string; - projectId?: string; - organization?: string; - } { - const info: { - dsn: string; - projectId?: string; - organization?: string; - } = { - dsn: this.config.dsn || "", - }; - - if (this.config.dsn) { - try { - const url = new URL(this.config.dsn); - const parts = url.pathname.split("/"); - info.projectId = parts[parts.length - 1]; - info.organization = parts[parts.length - 2]; - } catch { - // Ignore parsing errors - } - } - - return info; - } -} - -/** - * Create a Sentry adapter from environment variables. - */ -export function createSentryAdapter(enabled: boolean = true): SentryAdapter { - const dsn = process.env.SENTRY_DSN; - - if (enabled && !dsn) { - console.warn("Sentry is enabled but SENTRY_DSN environment variable is not set"); - } - - return new SentryAdapter({ - enabled: enabled && !!dsn, - dsn, - }); -} diff --git a/src/sla-monitor.test.ts b/src/sla-monitor.test.ts deleted file mode 100644 index cbcb7d67..00000000 --- a/src/sla-monitor.test.ts +++ /dev/null @@ -1,329 +0,0 @@ -import { describe, it, beforeEach } from "node:test"; -import assert from "node:assert/strict"; -import { SLAMonitor } from "./sla-monitor.js"; - -describe("SLAMonitor", () => { - describe("SLA management", () => { - let monitor: SLAMonitor; - - beforeEach(() => { - monitor = new SLAMonitor(); - }); - - it("creates an SLA", () => { - const sla = monitor.createSLA( - "API Availability", - "availability", - 99.9, - 99.0, - "%", - "monthly", - ); - assert(sla.id); - assert.equal(sla.name, "API Availability"); - assert.equal(sla.target, 99.9); - }); - - it("gets SLA by ID", () => { - const sla = monitor.createSLA( - "API Latency", - "latency", - 200, - 300, - "ms", - "daily", - ); - const retrieved = monitor.getSLA(sla.id); - assert(retrieved); - assert.equal(retrieved.name, "API Latency"); - }); - - it("returns null for unknown SLA", () => { - const sla = monitor.getSLA("unknown"); - assert.equal(sla, null); - }); - - it("gets all SLAs", () => { - monitor.createSLA("SLA 1", "availability", 99.9, 99.0, "%", "monthly"); - monitor.createSLA("SLA 2", "latency", 200, 300, "ms", "daily"); - const all = monitor.getAllSLAs(); - assert.equal(all.length, 2); - }); - - it("updates SLA target", () => { - const sla = monitor.createSLA("Test", "availability", 99.9, 99.0, "%", "monthly"); - const updated = monitor.updateSLATarget(sla.id, 99.95); - assert(updated); - assert.equal(updated.target, 99.95); - }); - - it("deletes SLA", () => { - const sla = monitor.createSLA("Test", "availability", 99.9, 99.0, "%", "monthly"); - const deleted = monitor.deleteSLA(sla.id); - assert(deleted); - assert.equal(monitor.getSLA(sla.id), null); - }); - }); - - describe("measurements", () => { - let monitor: SLAMonitor; - let slaId: string; - - beforeEach(() => { - monitor = new SLAMonitor(); - const sla = monitor.createSLA( - "Test SLA", - "latency", - 100, - 200, - "ms", - "daily", - ); - slaId = sla.id; - }); - - it("records measurement", () => { - monitor.recordMeasurement(slaId, 150); - const measurements = monitor.getMeasurements(slaId); - assert.equal(measurements.length, 1); - assert.equal(measurements[0].value, 150); - }); - - it("records multiple measurements", () => { - monitor.recordMeasurement(slaId, 100); - monitor.recordMeasurement(slaId, 150); - monitor.recordMeasurement(slaId, 200); - const measurements = monitor.getMeasurements(slaId); - assert.equal(measurements.length, 3); - }); - - it("gets recent measurements with limit", () => { - for (let i = 0; i < 20; i++) { - monitor.recordMeasurement(slaId, 100 + i); - } - const recent = monitor.getMeasurements(slaId, 5); - assert.equal(recent.length, 5); - }); - }); - - describe("breach detection", () => { - let monitor: SLAMonitor; - - beforeEach(() => { - monitor = new SLAMonitor(); - }); - - it("detects latency breach (value above threshold)", () => { - const sla = monitor.createSLA("Latency", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla.id, 300); // Above threshold - const breaches = monitor.getBreaches(sla.id); - assert(breaches.length > 0); - }); - - it("detects availability breach (value below threshold)", () => { - const sla = monitor.createSLA( - "Availability", - "availability", - 99.9, - 99.0, - "%", - "monthly", - ); - monitor.recordMeasurement(sla.id, 98.5); // Below threshold - const breaches = monitor.getBreaches(sla.id); - assert(breaches.length > 0); - }); - - it("doesn't record breach when within threshold", () => { - const sla = monitor.createSLA("Latency", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla.id, 150); // Within threshold - const breaches = monitor.getBreaches(sla.id); - assert.equal(breaches.length, 0); - }); - - it("marks breach as critical for large deviations", () => { - const sla = monitor.createSLA("Latency", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla.id, 500); // Large deviation - const breaches = monitor.getBreaches(sla.id); - assert(breaches.length > 0); - // Check severity based on deviation - assert(breaches[0].severity); - }); - - it("gets unresolved breaches for SLA", () => { - const sla = monitor.createSLA("Latency", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla.id, 300); - monitor.recordMeasurement(sla.id, 350); - - const unresolved = monitor.getBreaches(sla.id, true); - assert(unresolved.length > 0); - }); - - it("resolves a breach", () => { - const sla = monitor.createSLA("Latency", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla.id, 300); - const breaches = monitor.getBreaches(sla.id); - const resolved = monitor.resolveBreach(breaches[0].id); - assert(resolved); - assert(resolved.resolved); - assert(resolved.resolvedAt); - }); - - it("gets all unresolved breaches", () => { - const sla1 = monitor.createSLA("SLA 1", "latency", 100, 200, "ms", "daily"); - const sla2 = monitor.createSLA("SLA 2", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla1.id, 300); - monitor.recordMeasurement(sla2.id, 300); - - const unresolved = monitor.getUnresolvedBreaches(); - assert(unresolved.length >= 2); - }); - }); - - describe("status reporting", () => { - let monitor: SLAMonitor; - let slaId: string; - - beforeEach(() => { - monitor = new SLAMonitor(); - const sla = monitor.createSLA("API Latency", "latency", 100, 200, "ms", "daily"); - slaId = sla.id; - monitor.recordMeasurement(slaId, 150); - }); - - it("gets SLA status", () => { - const status = monitor.getSLAStatus(slaId); - assert(status); - assert.equal(status.name, "API Latency"); - assert(status.currentValue > 0); - }); - - it("calculates percentage of target", () => { - const status = monitor.getSLAStatus(slaId); - assert(status); - assert(status.percentageOfTarget >= 0); - }); - - it("determines if SLA is met", () => { - const status = monitor.getSLAStatus(slaId); - assert(typeof status?.isMet === "boolean"); - }); - - it("counts breaches", () => { - monitor.recordMeasurement(slaId, 300); - const status = monitor.getSLAStatus(slaId); - assert(status); - assert(status.breachCount > 0); - }); - - it("gets status for all SLAs", () => { - monitor.createSLA("SLA 2", "availability", 99.9, 99.0, "%", "monthly"); - const statuses = monitor.getAllSLAStatus(); - assert(statuses.length > 0); - }); - - it("calculates SLI (Service Level Indicator)", () => { - monitor.recordMeasurement(slaId, 150); - monitor.recordMeasurement(slaId, 180); - monitor.recordMeasurement(slaId, 200); - const sli = monitor.calculateSLI(slaId); - assert(sli >= 0); - assert(sli <= 100); - }); - - it("generates SLA report", () => { - monitor.recordMeasurement(slaId, 150); - const report = monitor.generateReport(); - assert(report.totalSLAs > 0); - assert(typeof report.metSLAs === "number"); - assert(typeof report.sliAverage === "number"); - }); - }); - - describe("metrics by type", () => { - let monitor: SLAMonitor; - - beforeEach(() => { - monitor = new SLAMonitor(); - }); - - it("tracks availability SLA", () => { - const sla = monitor.createSLA( - "Uptime", - "availability", - 99.9, - 99.0, - "%", - "monthly", - ); - monitor.recordMeasurement(sla.id, 99.5); - const status = monitor.getSLAStatus(sla.id); - assert(status); - assert(status.currentValue > 0); - }); - - it("tracks latency SLA", () => { - const sla = monitor.createSLA("Response Time", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla.id, 150); - const status = monitor.getSLAStatus(sla.id); - assert(status?.isMet); - }); - - it("tracks error rate SLA", () => { - const sla = monitor.createSLA( - "Error Rate", - "error_rate", - 0.1, - 1.0, - "%", - "daily", - ); - monitor.recordMeasurement(sla.id, 0.5); - const status = monitor.getSLAStatus(sla.id); - assert(status?.isMet); - }); - - it("tracks throughput SLA", () => { - const sla = monitor.createSLA( - "Throughput", - "throughput", - 1000, - 500, - "req/s", - "daily", - ); - monitor.recordMeasurement(sla.id, 900); - const status = monitor.getSLAStatus(sla.id); - assert(status?.isMet); - }); - }); - - describe("cache helpers", () => { - let monitor: SLAMonitor; - - beforeEach(() => { - monitor = new SLAMonitor(); - }); - - it("returns SLA cache", () => { - monitor.createSLA("SLA 1", "availability", 99.9, 99.0, "%", "monthly"); - const cache = monitor.getSLACache(); - assert.equal(cache.size, 1); - }); - - it("returns breach cache", () => { - const sla = monitor.createSLA("Latency", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla.id, 300); - const cache = monitor.getBreachCache(); - assert(cache.size > 0); - }); - - it("returns measurements cache", () => { - const sla = monitor.createSLA("Test", "latency", 100, 200, "ms", "daily"); - monitor.recordMeasurement(sla.id, 150); - monitor.recordMeasurement(sla.id, 160); - const cache = monitor.getMeasurementsCache(); - assert(cache.length >= 2); - }); - }); -}); diff --git a/src/sla-monitor.ts b/src/sla-monitor.ts deleted file mode 100644 index c83a14b2..00000000 --- a/src/sla-monitor.ts +++ /dev/null @@ -1,327 +0,0 @@ -import { IdGenerators } from "./id-generator.js"; -// ─── Types ──────────────────────────────────────────────────────────────────── - -export interface SLAObjective { - id: string; - name: string; - metric: "availability" | "latency" | "error_rate" | "throughput"; - target: number; - threshold: number; - unit: string; - window: "daily" | "weekly" | "monthly"; -} - -export interface SLABreach { - id: string; - slaId: string; - breachTime: string; - severity: "warning" | "critical"; - details: Record; - resolved: boolean; - resolvedAt?: string; -} - -export interface SLAStatus { - slaId: string; - name: string; - currentValue: number; - target: number; - percentageOfTarget: number; - isMet: boolean; - breachCount: number; - lastBreachTime?: string; -} - -// ─── SLAMonitor ─────────────────────────────────────────────────────────────── - -export class SLAMonitor { - private slas: Map = new Map(); - private breaches: Map = new Map(); - private measurements: Array<{ - slaId: string; - value: number; - timestamp: string; - }> = []; - - // ─── SLA Management ─────────────────────────────────────────────────────── - - /** - * Create an SLA objective. - */ - createSLA( - name: string, - metric: "availability" | "latency" | "error_rate" | "throughput", - target: number, - threshold: number, - unit: string, - window: "daily" | "weekly" | "monthly", - ): SLAObjective { - const id = IdGenerators.sla(); - const sla: SLAObjective = { - id, - name, - metric, - target, - threshold, - unit, - window, - }; - - this.slas.set(id, sla); - return sla; - } - - /** - * Get SLA by ID. - */ - getSLA(slaId: string): SLAObjective | null { - return this.slas.get(slaId) || null; - } - - /** - * Get all SLAs. - */ - getAllSLAs(): SLAObjective[] { - return [...this.slas.values()]; - } - - /** - * Update SLA target. - */ - updateSLATarget(slaId: string, newTarget: number): SLAObjective | null { - const sla = this.slas.get(slaId); - if (!sla) return null; - - sla.target = newTarget; - return sla; - } - - /** - * Delete SLA. - */ - deleteSLA(slaId: string): boolean { - return this.slas.delete(slaId); - } - - // ─── Measurements ──────────────────────────────────────────────────────── - - /** - * Record measurement for SLA. - */ - recordMeasurement(slaId: string, value: number): void { - const sla = this.slas.get(slaId); - if (!sla) return; - - this.measurements.push({ - slaId, - value, - timestamp: new Date().toISOString(), - }); - - // Check if breach - this.checkBreach(sla, value); - } - - /** - * Get recent measurements for SLA. - */ - getMeasurements(slaId: string, limit = 100): Array<{ - slaId: string; - value: number; - timestamp: string; - }> { - return this.measurements - .filter((m) => m.slaId === slaId) - .slice(-limit); - } - - // ─── Breach Detection ─────────────────────────────────────────────────── - - private checkBreach(sla: SLAObjective, value: number): void { - let isBreached = false; - - switch (sla.metric) { - case "availability": - case "throughput": - // These should be high - breach if below threshold - isBreached = value < sla.threshold; - break; - case "latency": - case "error_rate": - // These should be low - breach if above threshold - isBreached = value > sla.threshold; - break; - } - - if (isBreached) { - this.recordBreach(sla, value); - } - } - - private recordBreach(sla: SLAObjective, value: number): void { - const id = IdGenerators.breach(); - const severity = Math.abs(value - sla.threshold) > sla.threshold * 0.2 ? "critical" : "warning"; - - const breach: SLABreach = { - id, - slaId: sla.id, - breachTime: new Date().toISOString(), - severity, - details: { - metric: sla.metric, - value, - threshold: sla.threshold, - deviation: Math.abs(value - sla.threshold), - }, - resolved: false, - }; - - this.breaches.set(id, breach); - } - - /** - * Get breaches for SLA. - */ - getBreaches(slaId: string, unresolved = true): SLABreach[] { - return [...this.breaches.values()].filter( - (b) => b.slaId === slaId && (!unresolved || !b.resolved), - ); - } - - /** - * Resolve a breach. - */ - resolveBreach(breachId: string): SLABreach | null { - const breach = this.breaches.get(breachId); - if (!breach) return null; - - breach.resolved = true; - breach.resolvedAt = new Date().toISOString(); - return breach; - } - - /** - * Get all unresolved breaches. - */ - getUnresolvedBreaches(): SLABreach[] { - return [...this.breaches.values()].filter((b) => !b.resolved); - } - - // ─── Status & Reporting ─────────────────────────────────────────────────── - - /** - * Get current status of SLA. - */ - getSLAStatus(slaId: string): SLAStatus | null { - const sla = this.slas.get(slaId); - if (!sla) return null; - - const measurements = this.getMeasurements(slaId, 100); - if (measurements.length === 0) { - return { - slaId, - name: sla.name, - currentValue: 0, - target: sla.target, - percentageOfTarget: 0, - isMet: false, - breachCount: this.getBreaches(slaId, false).length, - }; - } - - const currentValue = measurements[measurements.length - 1].value; - const isMet = - sla.metric === "availability" || sla.metric === "throughput" - ? currentValue >= sla.threshold - : currentValue <= sla.threshold; - - const percentageOfTarget = - sla.target > 0 ? Math.round((currentValue / sla.target) * 100) : 0; - - const breachCount = this.getBreaches(slaId, false).length; - const lastBreach = this.getBreaches(slaId, false)[0]; - - return { - slaId, - name: sla.name, - currentValue, - target: sla.target, - percentageOfTarget, - isMet, - breachCount, - lastBreachTime: lastBreach?.breachTime, - }; - } - - /** - * Get status for all SLAs. - */ - getAllSLAStatus(): SLAStatus[] { - return [...this.slas.keys()].reduce( - (statuses, slaId) => { - const status = this.getSLAStatus(slaId); - if (status) statuses.push(status); - return statuses; - }, - [] as SLAStatus[], - ); - } - - /** - * Calculate SLI (Service Level Indicator). - */ - calculateSLI(slaId: string): number { - const sla = this.slas.get(slaId); - if (!sla) return 0; - - const measurements = this.getMeasurements(slaId, 100); - if (measurements.length === 0) return 0; - - const metCount = measurements.filter((m) => { - if (sla.metric === "availability" || sla.metric === "throughput") { - return m.value >= sla.threshold; - } else { - return m.value <= sla.threshold; - } - }).length; - - return Math.round((metCount / measurements.length) * 100); - } - - /** - * Generate SLA report. - */ - generateReport(): { - totalSLAs: number; - metSLAs: number; - breachedSLAs: number; - sliAverage: number; - } { - const statuses = this.getAllSLAStatus(); - const metSLAs = statuses.filter((s) => s.isMet).length; - const breachedSLAs = statuses.filter((s) => s.breachCount > 0).length; - const slis = statuses.map((s) => this.calculateSLI(s.slaId)); - const sliAverage = slis.length > 0 ? Math.round(slis.reduce((a, b) => a + b) / slis.length) : 0; - - return { - totalSLAs: this.slas.size, - metSLAs, - breachedSLAs, - sliAverage, - }; - } - - // ─── Cache helpers ──────────────────────────────────────────────────────── - - getSLACache(): Map { - return this.slas; - } - - getBreachCache(): Map { - return this.breaches; - } - - getMeasurementsCache(): Array<{ slaId: string; value: number; timestamp: string }> { - return this.measurements; - } -}