UNPKG

mcp-context-engineering

Version:

The intelligent context optimization system for AI coding assistants. Built with Cole's PRP methodology, Context Portal knowledge graphs, and production-ready MongoDB architecture.

219 lines (218 loc) 7.74 kB
import { ObjectId } from 'mongodb'; import { z } from 'zod'; /** * Context History Schema - Following Context Portal's versioning patterns * * Provides comprehensive context evolution tracking with: * - Automatic versioning for all context changes * - Change source tracking (user, system, AI agent) * - Temporal queries for context at any point in time * - Incremental version management */ // Individual context history entry export const ContextHistoryEntrySchema = z.object({ _id: z.instanceof(ObjectId).optional(), // Context identification workspace_id: z.string(), project_id: z.string(), context_type: z.enum(['product_context', 'active_context', 'decision', 'progress_entry', 'system_pattern', 'context_pattern']), context_item_id: z.string(), // Version management version: z.number(), previous_version: z.number().optional(), // Change tracking change_source: z.enum(['user', 'system', 'ai_agent', 'api', 'automation']), change_type: z.enum(['create', 'update', 'delete', 'archive', 'restore']), change_summary: z.string(), change_details: z.record(z.any()).optional(), // Content snapshots content_before: z.record(z.any()).optional(), content_after: z.record(z.any()), content_diff: z.record(z.any()).optional(), // Metadata timestamp: z.date(), user_id: z.string().optional(), agent_type: z.enum(['cursor', 'windsurf', 'claude_code', 'generic']).optional(), session_id: z.string().optional(), // Impact tracking impact_score: z.number().min(0).max(1).optional(), related_changes: z.array(z.string()).optional() }); // Workspace evolution summary export const WorkspaceEvolutionSchema = z.object({ _id: z.instanceof(ObjectId).optional(), workspace_id: z.string(), project_id: z.string(), // Version statistics current_version: z.number(), total_changes: z.number(), change_velocity: z.number(), // Changes per day // Change patterns change_frequency: z.object({ hourly: z.array(z.number()), daily: z.array(z.number()), weekly: z.array(z.number()) }), // Source analytics change_sources: z.record(z.number()), agent_activity: z.record(z.number()), // Content evolution context_growth: z.object({ decisions_added: z.number(), patterns_created: z.number(), progress_entries: z.number(), total_content_size: z.number() }), // Quality metrics stability_score: z.number().min(0).max(1), consistency_score: z.number().min(0).max(1), completeness_score: z.number().min(0).max(1), // Time tracking created_at: z.date(), last_updated: z.date(), analysis_date: z.date() }); // Context snapshot for temporal queries export const ContextSnapshotSchema = z.object({ _id: z.instanceof(ObjectId).optional(), // Snapshot identification workspace_id: z.string(), project_id: z.string(), snapshot_version: z.number(), snapshot_timestamp: z.date(), // Complete context state at this version context_state: z.object({ product_context: z.record(z.any()), active_context: z.record(z.any()), decisions: z.array(z.record(z.any())), progress_entries: z.array(z.record(z.any())), system_patterns: z.array(z.record(z.any())), context_links: z.array(z.record(z.any())) }), // Snapshot metadata created_by: z.enum(['system', 'user', 'ai_agent', 'scheduled']), snapshot_reason: z.string(), retention_policy: z.enum(['permanent', 'long_term', 'short_term']), // Compression and optimization compressed: z.boolean().default(false), compression_ratio: z.number().optional(), original_size: z.number().optional() }); // Change analytics for learning and optimization export const ChangeAnalyticsSchema = z.object({ _id: z.instanceof(ObjectId).optional(), workspace_id: z.string(), analysis_period: z.object({ start_date: z.date(), end_date: z.date() }), // Change patterns patterns: z.object({ most_active_hours: z.array(z.number()), peak_activity_days: z.array(z.string()), common_change_types: z.array(z.object({ type: z.string(), frequency: z.number(), impact: z.number() })) }), // Agent behavior analytics agent_behavior: z.record(z.object({ total_changes: z.number(), avg_change_impact: z.number(), preferred_change_types: z.array(z.string()), effectiveness_score: z.number(), learning_velocity: z.number() })), // Context health metrics health_metrics: z.object({ consistency_trend: z.array(z.number()), completeness_trend: z.array(z.number()), stability_trend: z.array(z.number()), growth_rate: z.number(), quality_score: z.number() }), // Recommendations recommendations: z.array(z.object({ category: z.enum(['optimization', 'maintenance', 'expansion', 'cleanup']), priority: z.enum(['high', 'medium', 'low']), description: z.string(), expected_impact: z.number(), effort_estimate: z.string() })), // Metadata analysis_date: z.date(), next_analysis_due: z.date(), analysis_version: z.number() }); // Main Context History Collection Schema export const ContextHistorySchema = z.object({ _id: z.instanceof(ObjectId).optional(), workspace_id: z.string(), project_id: z.string(), // History entries history_entries: z.array(ContextHistoryEntrySchema), // Evolution tracking workspace_evolution: WorkspaceEvolutionSchema, // Periodic snapshots snapshots: z.array(ContextSnapshotSchema), // Analytics and insights change_analytics: ChangeAnalyticsSchema, // Metadata metadata: z.object({ created_at: z.date(), last_updated: z.date(), retention_policy: z.enum(['standard', 'extended', 'permanent']), archive_after_days: z.number().default(365), compress_after_days: z.number().default(90) }) }); // Helper functions for version management export class ContextVersionManager { /** * Generate next version number for a context item */ static generateNextVersion(currentVersion = 0) { return currentVersion + 1; } /** * Create change diff between two context states */ static createChangeDiff(before, after) { const diff = {}; // Simple diff implementation - would be enhanced with proper diff library for (const key in after) { if (JSON.stringify(before?.[key]) !== JSON.stringify(after[key])) { diff[key] = { before: before?.[key], after: after[key] }; } } return diff; } /** * Calculate impact score based on change magnitude */ static calculateImpactScore(changeDiff) { const changeCount = Object.keys(changeDiff).length; const maxChanges = 20; // Configurable threshold return Math.min(changeCount / maxChanges, 1.0); } /** * Create context snapshot for temporal queries */ static createSnapshot(workspaceId, projectId, version, contextState, reason = 'periodic') { return { workspace_id: workspaceId, project_id: projectId, snapshot_version: version, snapshot_timestamp: new Date(), context_state: contextState, created_by: 'system', snapshot_reason: reason, retention_policy: 'long_term', compressed: false }; } }