export type AgentTool = 'claude-code' | 'kilo-code' | 'cline' | 'opencode' | 'codex' | 'roo-code' | 'aider' | 'cursor' | 'windsurf' | 'copilot'; export interface AgentAdapter { name: AgentTool; displayName: string; /** Detect if this agent tool is running */ detect(): Promise; /** Get the project directory the agent is working on */ getProjectDir(): Promise; /** Read the agent's memory/context files */ readMemory(): Promise; /** Inject context/instructions into the agent's memory */ injectContext(ctx: BrainInsight): Promise; /** Read recent conversation/activity logs */ readActivity(): Promise; /** Get agent-specific config paths */ getConfigPaths(): AgentPaths; } export interface AgentPaths { memoryDir: string; rulesDir: string; conversationDir?: string; configFile?: string; } export interface AgentMemory { rules: string[]; context: string[]; recentFiles: string[]; projectKnowledge: Record; } export interface AgentActivity { timestamp: Date; type: 'file_edit' | 'file_read' | 'command' | 'conversation' | 'error' | 'search'; detail: string; file?: string; diff?: string; } export interface BrainInsight { type: 'review' | 'suggestion' | 'warning' | 'context' | 'pattern' | 'instruction' | 'prediction' | 'mutation' | 'a11y' | 'i18n' | 'dead-code' | 'api-contract' | 'env' | 'license' | 'config-drift' | 'complexity' | 'security' | 'architecture'; priority: 'critical' | 'high' | 'medium' | 'low'; title: string; content: string; files?: string[]; timestamp: Date; sourceAgent?: AgentTool; targetAgent?: AgentTool; confidence?: number; metadata?: Record; } export interface BrainConfig { provider: LLMProvider; apiKey?: string; model?: string; agents: AgentTool[]; projectDir: string; watchMode: boolean; autoInject: boolean; reviewDepth: 'quick' | 'standard' | 'deep'; brainPersonality: BrainPersonality; } export type LLMProvider = 'anthropic' | 'openai' | 'ollama' | 'openrouter' | 'gemini' | 'mistral' | 'deepseek'; export type BrainPersonality = 'mentor' | 'critic' | 'architect' | 'security' | 'performance' | 'balanced'; export interface FileChange { path: string; type: 'add' | 'modify' | 'delete' | 'rename'; diff?: string; content?: string; oldPath?: string; } export interface ProjectContext { name: string; rootDir: string; language: string[]; framework?: string; packageManager?: string; structure: string[]; recentChanges: FileChange[]; gitBranch?: string; gitStatus?: string; } export interface BrainSession { id: string; startedAt: Date; agent: AgentTool; projectDir: string; insights: BrainInsight[]; filesReviewed: number; suggestionsInjected: number; } export interface CustomRule { id: string; name: string; description: string; pattern: string; flags?: string; severity: 'critical' | 'high' | 'medium' | 'low'; category: 'security' | 'performance' | 'quality' | 'architecture' | 'style'; suggestion?: string; enabled: boolean; } export interface ProjectConfig { version: string; rules?: { customRules?: CustomRule[]; ignorePatterns?: string[]; ignorePaths?: string[]; }; notifications?: { webhook?: string; slack?: string; discord?: string; email?: string; onHealthDrop?: boolean; onCriticalInsight?: boolean; minInterval?: number; }; health?: { weights?: Record; thresholds?: Record; }; metrics?: { excludePaths?: string[]; complexityThreshold?: number; }; } export interface CodeMetrics { totalFiles: number; totalLines: number; codeLines: number; commentLines: number; blankLines: number; languages: Record; largestFiles: Array<{ path: string; lines: number; }>; complexityHotspots: Array<{ path: string; complexity: number; functions: number; }>; fileTypes: Record; avgFileSize: number; timestamp: Date; } export interface PRDescription { title: string; body: string; type: 'feat' | 'fix' | 'refactor' | 'docs' | 'test' | 'chore' | 'perf'; scope?: string; breaking: boolean; } export interface CommitMessage { conventional: string; short: string; detailed: string; } export interface VulnResult { package: string; severity: 'critical' | 'high' | 'medium' | 'low'; title: string; url?: string; patchedIn?: string; } export interface NotificationPayload { type: 'health-drop' | 'critical-insight' | 'analysis-complete' | 'error'; title: string; message: string; data?: Record; timestamp: Date; } export interface ProjectFileChange { path: string; type: 'add' | 'modify' | 'delete'; insertions: number; deletions: number; } export interface SymbolInfo { name: string; type: 'function' | 'class' | 'variable' | 'import' | 'export' | 'method' | 'interface' | 'type'; line: number; file: string; exported: boolean; usedInFiles: string[]; } export interface GraphNode { id: string; file: string; imports: number; importedBy: number; type: 'source' | 'config' | 'test' | 'style' | 'other'; } export interface GraphEdge { from: string; to: string; type: 'import' | 'require' | 'dynamic'; } export interface DependencyGraphResult { nodes: GraphNode[]; edges: GraphEdge[]; orphans: string[]; cycles: string[][]; } export interface HubInfo { file: string; dependents: number; risk: 'high' | 'medium' | 'low'; } export interface CodeBlock { file: string; startLine: number; endLine: number; content: string; type: 'function' | 'method' | 'class' | 'block'; } export interface DuplicateGroup { blocks: CodeBlock[]; similarity: number; suggestedRefactor: string; } export interface ADRDecision { id: string; title: string; status: 'proposed' | 'accepted' | 'deprecated' | 'superseded'; date: Date; context: string; decision: string; consequences: string; alternatives?: string[]; files?: string[]; } export interface LearnedLesson { id: string; category: string; pattern: string; lesson: string; confidence: number; occurrences: number; lastSeen: Date; source: 'rule' | 'llm' | 'user-feedback'; } export interface CodePattern { id: string; language: string; pattern: string; description: string; frequency: number; lastSeen: Date; associatedInsights: string[]; } export interface ProjectKnowledge { name: string; conventions: string[]; architecture: string; commonPatterns: string[]; avoidPatterns: string[]; dependencies: string[]; lastUpdated: Date; } export interface SharedPattern { id: string; pattern: string; description: string; language: string; category: string; addedBy: string; addedAt: Date; occurrences: number; } export interface TeamInsight { id: string; insight: BrainInsight; sharedBy: string; sharedAt: Date; upvotes: number; downvotes: number; tags: string[]; } export interface TeamStats { members: number; totalInsights: number; totalPatterns: number; topContributors: Array<{ name: string; insights: number; }>; recentActivity: Array<{ user: string; action: string; timestamp: Date; }>; } export interface ProjectInfo { id: string; dir: string; name: string; status: 'running' | 'stopped' | 'error'; lastHealth: number | null; lastAnalyzed: Date | null; insightCount: number; } export interface AggregatedHealth { projects: number; averageHealth: number; bestProject: string; worstProject: string; criticalIssues: number; } export interface MCPRequest { jsonrpc: '2.0'; id?: string | number; method: string; params?: Record; } export interface MCPResponse { jsonrpc: '2.0'; id?: string | number; result?: unknown; error?: { code: number; message: string; data?: unknown; }; } export interface MCPTool { name: string; description: string; inputSchema: Record; } export interface MCPServerOptions { port?: number; host?: string; authToken?: string; corsOrigin?: string; } export interface PerfInsight { category: string; severity: 'low' | 'medium' | 'high' | 'critical'; pattern: string; description: string; suggestion: string; estimatedImpact: string; } export interface MeshNode { id: string; sessionId: string; projectDir: string; projectName: string; pid: number; startedAt: Date; lastHeartbeat: Date; status: 'active' | 'idle' | 'disconnected'; personality: BrainPersonality; insightsGenerated: number; healthScore: number | null; currentTask: string | null; } export interface MeshMessage { id: string; fromNode: string; type: 'insight' | 'health-update' | 'task-update' | 'pattern-learned' | 'warning' | 'knowledge-sync' | 'heartbeat' | 'session-start' | 'session-end'; payload: unknown; timestamp: Date; priority: 'critical' | 'high' | 'medium' | 'low'; tags: string[]; entropy: number; } export interface MeshKnowledge { id: string; sourceNode: string; sourceProject: string; category: 'architecture' | 'pattern' | 'anti-pattern' | 'security' | 'performance' | 'convention' | 'dependency' | 'config'; content: string; confidence: number; frequency: number; firstSeen: Date; lastSeen: Date; relatedFiles: string[]; vector: number[]; } export interface MeshState { nodes: MeshNode[]; messages: MeshMessage[]; knowledge: MeshKnowledge[]; totalInsightsExchanged: number; meshUptime: number; averageEntropy: number; quantumState: 'coherent' | 'decoherent' | 'collapsed'; } export interface CrossSessionInsight { sourceSession: string; sourceProject: string; insight: BrainInsight; relevanceScore: number; transferredAt: Date; } export interface NeuralMeshConfig { enabled: boolean; meshPort: number; meshHost: string; discoveryInterval: number; heartbeatInterval: number; maxNodes: number; knowledgeRetentionMs: number; entropyThreshold: number; conflictResolution: 'latest-wins' | 'highest-confidence' | 'consensus'; } export interface ASTFunctionInfo { name: string; file: string; startLine: number; endLine: number; params: number; nestingDepth: number; returnPaths: number; cyclomaticComplexity: number; cognitiveComplexity: number; linesOfCode: number; isExported: boolean; isAsync: boolean; isPure: boolean; } export interface ComplexityReport { totalFunctions: number; avgComplexity: number; maxComplexity: number; highComplexityFunctions: ASTFunctionInfo[]; maintainabilityIndex: number; halsteadVolume: number; technicalDebtMinutes: number; } export interface A11yIssue { rule: string; severity: 'critical' | 'serious' | 'moderate' | 'minor'; element: string; file: string; line: number; message: string; suggestion: string; wcagLevel: 'A' | 'AA' | 'AAA'; wcagCriterion: string; } export interface I18nIssue { type: 'hardcoded-string' | 'concatenation' | 'date-format' | 'number-format' | 'rtl-missing' | 'pluralization'; file: string; line: number; content: string; suggestion: string; severity: 'high' | 'medium' | 'low'; } export interface DeadCodeResult { type: 'unreachable' | 'unused-export' | 'unused-variable' | 'unused-import' | 'dead-branch' | 'unused-parameter'; name: string; file: string; line: number; confidence: number; safeToRemove: boolean; impact: string; } export interface MutationSuggestion { id: string; file: string; line: number; originalCode: string; mutatedCode: string; mutationType: 'arithmetic' | 'conditional' | 'logical' | 'negation' | 'string' | 'boundary' | 'return-value' | 'statement-deletion'; killability: 'easy' | 'medium' | 'hard'; rationale: string; } export interface CodeAgeResult { file: string; lastModified: Date; daysSinceModification: number; linesChangedRecently: number; stalenessScore: number; risk: 'fresh' | 'stable' | 'aging' | 'stale' | 'ancient'; authors: string[]; churnRate: number; } export interface APIEndpoint { path: string; method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; file: string; line: number; hasValidation: boolean; hasAuth: boolean; hasRateLimit: boolean; hasDocs: boolean; hasTests: boolean; requestType?: string; responseType?: string; statusCode: number[]; issues: string[]; } export interface EnvIssue { variable: string; file: string; line: number; type: 'missing-default' | 'hardcoded-secret' | 'missing-validation' | 'wrong-type' | 'unused' | 'missing-docs' | 'inconsistent-naming'; severity: 'critical' | 'high' | 'medium' | 'low'; suggestion: string; } export interface LicenseIssue { package: string; version: string; license: string; type: 'restricted' | 'unknown' | 'conflict' | 'outdated' | 'copyleft'; severity: 'critical' | 'high' | 'medium' | 'low'; description: string; recommendation: string; } export interface HealthDimensionV3 { name: string; score: number; weight: number; grade: string; issues: string[]; trend: 'improving' | 'stable' | 'declining'; predictedScore: number; } export interface PredictiveInsight { type: 'degradation-warning' | 'improvement-opportunity' | 'risk-forecast' | 'trend-anomaly'; confidence: number; description: string; projectedImpact: string; recommendation: string; timeframe: string; } export interface LLMStreamChunk { text: string; done: boolean; tokensUsed?: number; } export interface WSMeshMessage { type: 'insight' | 'health' | 'knowledge' | 'node-join' | 'node-leave' | 'sync-request' | 'sync-response'; fromNode: string; payload: unknown; timestamp: number; } export interface CrossLanguagePattern { pattern: string; languages: string[]; files: string[]; description: string; severity: 'info' | 'warning' | 'critical'; } export interface ConfigDrift { file: string; expected: string; actual: string; severity: 'low' | 'medium' | 'high'; description: string; autoFixable: boolean; } export interface TurboVector { /** PolarQuant main body: 2 bits per angle, packed into Uint8Array */ polar: Uint8Array; /** QJL residual: 1 bit per dimension, packed into Uint8Array */ qjl: Uint8Array; /** Original dimension count */ dim: number; /** Radius from PolarQuant (stored as float, single value) */ radius: number; } export interface TurboEntry { id: string; key: string; vector: TurboVector; metadata: Record; timestamp: Date; accessCount: number; lastAccessed: Date; } export interface TurboMemoryStore { version: 4; entries: TurboEntry[]; totalCompressed: number; totalOriginal: number; compressionRatio: number; createdAt: Date; lastUpdated: Date; } export interface InfiniteMemoryStats { totalEntries: number; compressionRatio: number; memoryUsedMB: number; queryTimeMs: number; hitRate: number; retentionDays: number; } export interface SSSPEdge { to: string; weight: number; } export interface SSSPGraph { adjacency: Map; nodeCount: number; edgeCount: number; } export interface SSSPResult { distances: Map; predecessors: Map; pivots: string[]; computedAt: Date; } export interface PivotSet { pivots: string[]; covered: string[]; uncovered: string[]; k: number; computedAt: Date; } export interface CAIPMessage { id: string; from: AgentTool; to: AgentTool | 'broadcast'; type: 'insight' | 'boost' | 'health' | 'knowledge' | 'handshake' | 'heartbeat' | 'disconnect'; payload: unknown; timestamp: Date; priority: 'critical' | 'high' | 'medium' | 'low'; signature?: string; } export interface CAIPHandshake { agentId: string; agentTool: AgentTool; version: string; capabilities: string[]; publicKey?: string; projectDir: string; personality: string; } export interface CAIPChannel { id: string; participants: AgentTool[]; created: Date; messageCount: number; lastActivity: Date; type: 'broadcast' | 'pair' | 'team'; } export interface AgentBoostPacket { fromAgent: AgentTool; insights: BrainInsight[]; patterns: string[]; rules: string[]; healthScore: number; contextSummary: string; timestamp: Date; } export interface CrossAgentBus { channels: CAIPChannel[]; pendingMessages: CAIPMessage[]; connectedAgents: Map; totalExchanged: number; uptime: number; } export interface GeneticRule { id: string; chromosome: number[]; fitness: number; generation: number; mutations: number; category: string; originalRuleId?: string; createdAt: Date; } export interface EvolutionSnapshot { generation: number; bestFitness: number; avgFitness: number; worstFitness: number; population: GeneticRule[]; eliteCount: number; timestamp: Date; } export interface MetaLearningLog { strategy: string; successRate: number; avgImprovement: number; sampleCount: number; lastUpdated: Date; category: string; } export interface SelfEvolutionConfig { populationSize: number; mutationRate: number; crossoverRate: number; elitePercent: number; fitnessTarget: number; maxGenerations: number; tournamentSize: number; } export interface BugRiskScore { file: string; riskLevel: 'critical' | 'high' | 'medium' | 'low'; factors: string[]; confidence: number; predicted30Days: number; churnRate: number; complexity: number; age: number; } export interface TechDebtForecast { currentDebt: number; projectedDebt30d: number; projectedDebt90d: number; breakEvenDate: Date | null; recommendation: string; trend: 'improving' | 'stable' | 'worsening'; velocity: number; } export interface AnomalyEvent { timestamp: Date; metric: string; observed: number; expected: number; zScore: number; severity: 'info' | 'warning' | 'critical'; description: string; } export interface MonteCarloResult { simulations: number; median: number; p95: number; p99: number; confidenceInterval: [number, number]; mean: number; stdDev: number; } export interface KGEntity { id: string; type: 'function' | 'class' | 'interface' | 'module' | 'variable' | 'method'; name: string; file: string; line: number; refs: string[]; pageRankScore: number; exported: boolean; async: boolean; } export interface KGRelation { from: string; to: string; type: 'calls' | 'imports' | 'extends' | 'implements' | 'uses' | 'tests'; weight: number; } export interface KGGraph { entities: Map; relations: KGRelation[]; lastBuilt: Date; fileCount: number; } export interface PageRankResult { scores: Map; iterations: number; converged: boolean; danglingNodes: number; } export interface PheromoneTrail { path: string[]; strength: number; evaporation: number; lastReinforced: Date; totalDetections: number; } export interface SwarmTask { id: string; type: 'analyze' | 'deep-scan' | 'pattern-hunt' | 'security-sweep'; file?: string; priority: 'critical' | 'high' | 'medium' | 'low'; assignedTo?: string; status: 'pending' | 'in-progress' | 'completed' | 'failed'; result?: unknown; createdAt: Date; } export interface AntColonyState { trails: PheromoneTrail[]; activeTasks: SwarmTask[]; convergenceScore: number; totalAnts: number; cycleCount: number; highPriorityFiles: string[]; } export interface SwarmConfig { antCount: number; evaporationRate: number; reinforcementFactor: number; maxIterations: number; convergenceThreshold: number; } export interface HallucinationFlag { claim: string; confidence: number; verified: boolean; contradictions: string[]; verdict: 'real' | 'hallucinated' | 'uncertain'; evidence: string[]; checkedAt: Date; } export interface EnsembleVote { question: string; votes: Array<{ model: string; answer: string; confidence: number; }>; consensus: 'unanimous' | 'majority' | 'split' | 'none'; agreedAnswer: string; confidence: number; } export interface AdversarialLog { timestamp: Date; flagged: number; blocked: number; accuracy: number; totalChecked: number; falsePositives: number; } export interface ThreatVector { type: 'prompt-injection' | 'hallucination' | 'data-poisoning' | 'contradiction'; severity: 'low' | 'medium' | 'high' | 'critical'; blocked: boolean; source: string; pattern: string; timestamp: Date; } export type MemoryTier = 'raw' | 'summary' | 'pattern' | 'principle'; export interface HierarchicalMemoryEntry { id: string; tier: MemoryTier; content: string; category: string; confidence: number; importance: number; accessCount: number; createdAt: Date; lastAccessed: Date; promotedAt: Date | null; parentIds: string[]; childIds: string[]; vector: number[]; metadata: Record; compressedSize: number; originalSize: number; } export interface HierarchicalMemoryStats { rawCount: number; summaryCount: number; patternCount: number; principleCount: number; totalEntries: number; totalSizeMB: number; compressionRatio: number; promotionRate: number; retentionDays: number; drillDownDepth: number; } export interface RecallTrigger { /** What activates this memory — file path patterns, keywords, categories, code patterns */ patterns: string[]; /** How strongly this trigger activates (0-1) */ strength: number; /** Recency boost — newer triggers get slight priority */ recency: number; } export interface RecallResult { entry: HierarchicalMemoryEntry; relevanceScore: number; activatedTriggers: string[]; activationPath: string[]; } export interface RecallContext { currentFile: string; currentCategory: string; recentEdits: string[]; projectType: string; keywords: string[]; timeOfDay: number; dayOfWeek: number; } export interface ConsensusProposal { id: string; proposer: string; content: string; category: string; confidence: number; evidence: string[]; timestamp: Date; } export interface ConsensusVote { voter: string; proposalId: string; vote: 'agree' | 'disagree' | 'abstain'; confidence: number; reasoning: string; timestamp: Date; } export interface ConsensusResult { proposal: ConsensusProposal; votes: ConsensusVote[]; verdict: 'accepted' | 'rejected' | 'pending' | 'conflicted'; agreementScore: number; confidenceInterval: [number, number]; resolvedAt: Date | null; conflictResolution?: string; } export interface TrustScore { agent: string; score: number; totalProposals: number; acceptedProposals: number; rejectedProposals: number; accuracyHistory: number[]; lastUpdated: Date; } export interface CollectiveRule { id: string; content: string; category: string; originProject: string; originAgent: string; verifiedBy: string[]; verifiedCount: number; contradictCount: number; trustScore: number; applicability: string[]; exceptions: string[]; createdAt: Date; lastVerifiedAt: Date; timesApplied: number; timesCorrect: number; accuracy: number; viralScore: number; } export interface CollectiveLearningStats { totalRules: number; verifiedRules: number; averageAccuracy: number; topCategories: Array<{ category: string; count: number; avgAccuracy: number; }>; recentAdoptions: number; consensusRate: number; networkSize: number; knowledgeBaseSizeMB: number; } export interface AutoConfigResult { projectDir: string; projectName: string; projectType: string; languages: string[]; frameworks: string[]; buildTools: string[]; packageManager: 'npm' | 'yarn' | 'pnpm' | 'bun' | 'unknown'; aiTools: Array<{ name: string; path: string; detected: boolean; }>; testFrameworks: string[]; linters: string[]; formatters: string[]; cicd: string[]; hasGit: boolean; hasDocker: boolean; config: Partial; timestamp: Date; } export interface PluginManifest { name: string; version: string; description: string; author: string; main: string; hooks: PluginHook[]; dependencies?: string[]; } export interface PluginHook { event: 'pre-analysis' | 'post-analysis' | 'pre-insight' | 'post-insight' | 'pre-fix' | 'post-fix' | 'on-start' | 'on-stop' | 'on-file-change'; handler: string; priority?: number; } export interface PluginInstance { manifest: PluginManifest; enabled: boolean; loadedAt: Date; errorCount: number; lastError?: string; } export interface BrainExportData { version: string; exportedAt: Date; projectName: string; projectDir: string; hierarchicalMemory: any; patternMemory: any; learningEngine: any; neuralMesh: any; consensusState: any; recallState: any; collectiveRules: any; turboMemory: any; knowledgeGraph: any; swarmState: any; evolutionState: any; customRules: any; plugins: PluginManifest[]; } export interface ConnectedTool { name: string; type: AgentTool; status: 'connected' | 'disconnected' | 'unknown'; lastSeen: Date; capabilities: string[]; } export interface BrainModuleStatus { name: string; version: string; status: 'active' | 'idle' | 'error'; entries?: number; memoryMB?: number; lastActivity?: Date; details?: Record; } export interface FineTuneModel { version: string; trainedAt: number; totalPatterns: number; totalTrainingPoints: number; styleRules: StyleRule[]; accuracy: number; } export interface StyleRule { name: string; pattern: string; confidence: number; occurrences: number; category: string; enforced: boolean; } export interface CodeSuggestion { type: string; suggestion: string; confidence: number; basedOn: string; example?: string; } export interface FineTuneStats { totalPatterns: number; totalTrainingPoints: number; styleRules: number; modelAccuracy: number; categoryCounts: Record; lastTrained: number | null; topPatterns: Array<{ pattern: string; category: string; frequency: number; }>; } export interface SmartCacheStats { hotEntries: number; warmEntries: number; coldEntries: number; totalEntries: number; hits: number; misses: number; hitRate: number; evictions: number; promotions: number; demotions: number; memoryUsageMB: number; prefetchHits: number; avgAccessTime: number; } export type IntentAction = 'adding-feature' | 'fixing-bug' | 'refactoring' | 'adding-tests' | 'updating-deps' | 'improving-perf' | 'adding-docs' | 'cleanup' | 'security-fix' | 'api-change' | 'ui-change' | 'config-change' | 'ci-cd' | 'database-migration' | 'unknown'; export interface DeveloperIntent { action: IntentAction; confidence: number; evidence: string[]; prediction: string; suggestions: string[]; relatedFiles: string[]; estimatedScope: 'small' | 'medium' | 'large'; timestamp: number; } export interface IntentStats { totalPredictions: number; confirmedCorrect: number; confirmedWrong: number; accuracy: number; topActions: Array<{ action: IntentAction; count: number; }>; sessionCount: number; avgConfidence: number; } export type GeneCategory = 'formatting' | 'naming' | 'structure' | 'complexity' | 'documentation' | 'error-handling' | 'testing' | 'imports' | 'typing' | 'async-patterns' | 'functional' | 'oop'; export interface CodeGene { name: string; category: GeneCategory; value: number; confidence: number; sampleSize: number; } export interface DNAProfile { id: string; name: string; genes: CodeGene[]; fileCount: number; createdAt: number; updatedAt: number; } export interface DNAComparison { similarity: number; profileA: string; profileB: string; matchingGenes: string[]; divergentGenes: Array<{ gene: string; valueA: number; valueB: number; delta: number; }>; } export interface StyleConsistencyReport { overallScore: number; fileScores: Array<{ file: string; score: number; deviations: string[]; }>; topDeviations: Array<{ gene: string; avgDeviation: number; worstFile: string; }>; recommendations: string[]; } export interface CodeDNAStats { profileCount: number; totalGenesTracked: number; avgGeneConfidence: number; categoryCoverage: Record; filesAnalyzed: number; lastProfileUpdate: number | null; } export interface TemporalEvent { id: string; timestamp: number; type: 'commit' | 'file-change' | 'bug-fix' | 'feature' | 'refactor' | 'incident' | 'deploy' | 'review'; file?: string; description: string; impact: number; metadata?: Record; } export interface VelocityMetrics { daily: number; weekly: number; monthly: number; trend: 'accelerating' | 'stable' | 'decelerating' | 'stalled'; trendConfidence: number; peakHours: number[]; peakDays: number[]; avgCycleTime: number; } export interface TemporalAnomaly { timestamp: number; type: 'burst' | 'drought' | 'pattern-break' | 'unusual-hour' | 'regression'; severity: 'info' | 'warning' | 'critical'; description: string; evidence: string[]; recommendation: string; } export interface FileHeatmap { file: string; changeFrequency: number; lastChanged: number; avgTimeBetweenChanges: number; hotness: number; churnRisk: number; stabilityScore: number; } export interface BugPrediction { file: string; probability: number; factors: string[]; lastBugFix: number | null; changesSinceLastFix: number; complexity: number; } export interface TemporalStats { totalEvents: number; timeSpan: { start: number; end: number; durationDays: number; }; velocity: VelocityMetrics; anomalyCount: number; hotFiles: number; bugPredictions: number; avgEventsPerDay: number; } export interface LSPDiagnosticRule { code: string; severity: 'error' | 'warning' | 'info' | 'hint'; pattern: RegExp; message: string; category: string; } export interface LSPStats { documentsOpen: number; diagnosticsEmitted: number; hoversServed: number; completionsServed: number; codeActionsServed: number; uptime: number; lastActivity: number; } export interface V6ModuleStatus { fineTuning: FineTuneStats | null; smartCache: SmartCacheStats | null; intentEngine: IntentStats | null; codeDNA: CodeDNAStats | null; temporal: TemporalStats | null; lsp: LSPStats | null; } export interface GlobalBrainConfig { /** Path to the singleton global brain store. Default: ~/.shadow-brain/global.json */ dbPath: string; /** Reserved for future SQLite backend compatibility. JSON backend ignores this. */ walMode: boolean; /** Max in-memory queue size for pending writes */ writeQueueSize: number; /** Auto-vacuum threshold in MB */ autoVacuumMB: number; /** Auto-prune threshold in MB (compress to lower tier when exceeded) */ autoPruneMB: number; /** Sync interval to flush pending writes (ms) */ syncIntervalMs: number; } export interface GlobalBrainStats { totalProjects: number; totalAgents: number; totalEntries: number; totalSizeMB: number; pendingWrites: number; hits: number; misses: number; hitRate: number; lastSync: Date; lastVacuum: Date | null; lastPrune: Date | null; uptime: number; } export interface GlobalEntry { id: string; projectId: string; projectName: string; agentTool: AgentTool; category: string; content: string; vector?: number[]; importance: number; accessCount: number; createdAt: Date; lastAccessed: Date; metadata: Record; } /** * Confidence breakdown for a recalled memory (v6.3.0). * * Not all memories are equally reliable. `global_recall` can attach a * confidence score so the consuming agent can weight memories by recency, * author-assigned importance, cross-agent corroboration, prior usage, and * keyword relevance instead of treating every hit as equally trustworthy. */ export interface RecallConfidence { /** Final blended confidence in [0,1]. */ score: number; /** Bucketed label: high >= 0.66, medium >= 0.33, else low. */ level: 'high' | 'medium' | 'low'; /** Normalized [0,1] component signals so consumers can re-weight if desired. */ signals: { /** Keyword match strength (0.5 baseline when no keywords supplied). */ relevance: number; /** Recency of last access — exponential decay with a ~30-day half-life. */ recency: number; /** Author-assigned importance. */ importance: number; /** Cross-agent agreement — distinct agents corroborating this category. */ corroboration: number; /** How often this memory has been recalled before. */ usage: number; }; } /** A recalled entry enriched with a confidence score (v6.3.0). */ export interface ScoredGlobalEntry extends GlobalEntry { confidence: RecallConfidence; } export interface SubconsciousConfig { /** Enable proactive context injection */ enabled: boolean; /** Maximum tokens to inject per session (default 2000) */ tokenBudget: number; /** Lookback window in hours for recent context */ lookbackHours: number; /** Minimum relevance score to include (0-1) */ relevanceThreshold: number; /** Categories to always include if available */ alwaysInclude: string[]; /** Inject for these agents (empty = all) */ enabledAgents: AgentTool[]; } export interface SubconsciousBriefing { agentTool: AgentTool; projectDir: string; sessionId: string; generatedAt: Date; tokenCount: number; sections: { recentDecisions: string[]; activeTasks: string[]; similarPastWork: string[]; projectState: string; crossAgentInsights: string[]; warnings: string[]; }; fullText: string; } export interface SubconsciousStats { totalBriefings: number; avgTokenCount: number; avgGenerationMs: number; acceptedRate: number; byAgent: Record; lastBriefing: Date | null; } export type HookEvent = 'session-start' | 'session-end' | 'pre-prompt' | 'post-response' | 'file-edit'; export interface SessionHook { agent: AgentTool; event: HookEvent; /** Hook implementation type for this agent */ hookType: 'settings-json' | 'config-file' | 'env-var' | 'wrapper-script' | 'workspace-rule' | 'extension-config'; /** File path where the hook is installed */ installPath: string; /** Command/script the hook executes */ command: string; /** Whether the hook is currently active */ active: boolean; installedAt: Date; } export interface AttachReport { detected: AgentTool[]; attached: AgentTool[]; failed: Array<{ agent: AgentTool; reason: string; }>; hooks: SessionHook[]; totalAgents: number; durationMs: number; } export interface L0CacheEntry { key: string; value: T; hits: number; insertedAt: number; lastAccessed: number; bytes: number; } export interface L0CacheStats { entries: number; bytesUsed: number; bytesLimit: number; hits: number; misses: number; hitRate: number; evictions: number; avgAccessNs: number; topKeys: Array<{ key: string; hits: number; }>; } export interface BrainTimelineEvent { id: string; projectId: string; projectName: string; agentTool: AgentTool; category: string; content: string; importance: number; createdAt: Date; lastAccessed: Date; metadata: Record; } export interface AgentHandoffPacket { fromAgent: AgentTool; toAgent: AgentTool; projectDir: string; projectName: string; task: string; createdAt: Date; recentMemories: BrainTimelineEvent[]; changedFiles: string[]; gitSummary: string; safetyWarnings: string[]; markdown: string; } export interface FirewallFinding { type: 'secret-access' | 'destructive-command' | 'network-risk' | 'package-risk' | 'prompt-injection' | 'path-risk'; severity: 'critical' | 'high' | 'medium' | 'low'; blocked: boolean; reason: string; evidence: string; recommendation: string; } export interface FirewallCheckInput { command?: string; filePath?: string; url?: string; content?: string; toolName?: string; } export interface FirewallDecision { allowed: boolean; riskScore: number; findings: FirewallFinding[]; summary: string; } export type SubAgentFramework = 'claude-code-task' | 'cursor-composer' | 'cline-substep' | 'crewai' | 'langgraph' | 'autogen' | 'generic'; export interface SubAgentSpawnRequest { parentAgent: AgentTool; subAgentId: string; framework: SubAgentFramework; taskDescription: string; projectDir: string; spawnTime: Date; expectedDurationMs?: number; tokenBudget?: number; } export interface ContextSliver { subAgentId: string; parentAgent: AgentTool; taskDescription: string; memories: Array<{ id: string; content: string; category: string; relevance: number; }>; warnings: string[]; tokenCount: number; markdown: string; generatedAt: Date; } export interface QuarantinedMemory { id: string; subAgentId: string; parentAgent: AgentTool; content: string; category: string; confidence: number; graduatedAt: Date | null; verdict: 'pending' | 'graduated' | 'rejected'; evidence: string[]; createdAt: Date; } export interface SABBStats { totalSpawns: number; totalSlivers: number; quarantined: number; graduated: number; rejected: number; avgSliverTokens: number; avgGraduationMs: number; byFramework: Record; byParent: Record; } export interface CausalLink { id: string; /** The memory/decision this is the cause of */ effectId: string; /** The memory/event that caused it */ causeId: string; /** Optional text explaining the causal relationship */ rationale?: string; strength: number; createdAt: Date; } export interface CausalChainNode { id: string; content: string; agentTool: AgentTool; category: string; createdAt: Date; parents: string[]; children: string[]; depth: number; } export interface CausalChain { rootId: string; nodes: CausalChainNode[]; links: CausalLink[]; maxDepth: number; generatedAt: Date; dot: string; } export interface AgentEditIntent { agentTool: AgentTool; sessionId: string; filePath: string; startLine: number; endLine: number; intent: string; declaredAt: Date; expiresAt: Date; } export interface CollisionAlert { id: string; filePath: string; conflictingIntents: AgentEditIntent[]; overlapStartLine: number; overlapEndLine: number; severity: 'info' | 'warning' | 'critical'; suggestedResolution: string; detectedAt: Date; } export interface CollisionStats { totalIntents: number; activeIntents: number; collisionsDetected: number; collisionsResolved: number; collisionsByAgent: Record; avgOverlapLines: number; } export type DreamType = 'revisit' | 'counterfactual' | 'consolidation' | 'contradiction' | 'pattern-discovery'; export interface DreamInsight { id: string; type: DreamType; content: string; sourceMemoryIds: string[]; confidence: number; generatedAt: Date; actOnNextSession: boolean; acknowledged: boolean; } export interface DreamEngineConfig { enabled: boolean; idleThresholdMs: number; maxDreamsPerCycle: number; useLocalLLM: boolean; dreamIntervalMs: number; } export interface DreamEngineStats { totalDreams: number; byType: Record; avgConfidence: number; actionableCount: number; acknowledgedCount: number; lastDreamAt: Date | null; totalDreamTimeMs: number; } export interface AgentDecisionReceipt { id: string; agentTool: AgentTool; agentVersion: string; projectId: string; decision: string; category: string; confidence: number; signedAt: Date; signature: string; publicKey: string; outcomeVerdict?: 'correct' | 'incorrect' | 'partial' | 'unverified'; outcomeVerifiedAt?: Date; } export interface ReputationScore { agentTool: AgentTool; agentVersion: string; totalDecisions: number; correct: number; incorrect: number; partial: number; accuracyRate: number; categoryScores: Record; streakDays: number; lastActive: Date; publicKey: string; ledgerHash: string; } export interface ReputationLedgerStats { totalAgents: number; totalReceipts: number; verifiedReceipts: number; averageAccuracy: number; topAgents: Array<{ agentTool: AgentTool; accuracy: number; decisions: number; }>; } export interface DebateTurn { turnId: number; agentLabel: string; position: 'pro' | 'con' | 'arbiter'; statement: string; confidence: number; timestamp: Date; } export interface DebateTranscript { id: string; question: string; context: string; turns: DebateTurn[]; verdict: string; arbiterConfidence: number; durationMs: number; createdAt: Date; } export interface PreMortemFailure { id: string; description: string; source: 'past-incident' | 'similar-project' | 'llm-predicted'; probability: number; severity: 'low' | 'medium' | 'high' | 'critical'; mitigation: string; relatedMemoryIds: string[]; } export interface PreMortemReport { taskDescription: string; generatedAt: Date; failures: PreMortemFailure[]; riskScore: number; summary: string; } export interface BranchBrainState { currentBranch: string; activeMemoryIds: string[]; branchMemoryCount: number; globalMemoryCount: number; lastSwitchAt: Date; branchSpecificCategories: string[]; } export interface BranchMemoryTag { memoryId: string; branch: string; scope: 'branch' | 'global'; taggedAt: Date; } export interface AttentionWeight { memoryId: string; memoryContent: string; weight: number; category: string; reasoning: string; } export interface AttentionReport { decisionId: string; decisionText: string; agentTool: AgentTool; weights: AttentionWeight[]; totalMemoriesConsidered: number; generatedAt: Date; } export interface TokenSpendRecord { id: string; agentTool: AgentTool; model: string; provider?: string; inputTokens: number; outputTokens: number; estimatedCostUsd: number; taskCategory: string; timestamp: Date; } export interface TokenEconomyBucket { spendUsd: number; calls: number; inputTokens?: number; outputTokens?: number; lastSeen?: Date; } export interface TokenEconomyStats { totalSpendUsd: number; totalInputTokens: number; totalOutputTokens: number; byAgent: Record; byModel: Record; byCategory: Record; recentWindowDays: number; recentSpendUsd: number; recentByAgent: Record; recentByModel: Record; recentByCategory: Record; lastRecord: TokenSpendRecord | null; monthlyProjectionUsd: number; savingsOpportunitiesUsd: number; suggestions: string[]; } export interface ForgettingState { memoryId: string; initialStrength: number; currentStrength: number; lastReinforced: Date; accessCount: number; halfLifeHours: number; consolidatedTier: MemoryTier; } export interface ConsolidationReport { cycle: number; processedMemories: number; promoted: number; demoted: number; forgotten: number; strengthened: number; ranAt: Date; durationMs: number; } export interface FormalRule { id: string; sourceMemoryId: string; naturalLanguage: string; eslintRule?: string; semgrepRule?: string; lspDiagnostic?: { code: string; pattern: string; message: string; }; languageScope: string[]; generatedAt: Date; verified: boolean; } export interface FormalBridgeStats { totalRules: number; byLanguage: Record; verifiedRules: number; lastGenerated: Date | null; } export interface CalibrationRecord { agentTool: AgentTool; category: string; claim: string; claimedConfidence: number; actualOutcome: 'correct' | 'incorrect' | 'partial'; outcomeAt: Date; recordedAt: Date; } export interface CalibrationScore { agentTool: AgentTool; category: string; sampleSize: number; brierScore: number; calibrationError: number; overconfidenceRatio: number; trustWeight: number; updatedAt: Date; } export interface SpawnCostEstimate { subAgentModel: string; estimatedInputTokens: number; estimatedOutputTokens: number; estimatedCostUsd: number; expectedValueScore: number; cheaperAlternative: { model: string; costUsd: number; } | null; recommendation: 'proceed' | 'use-alternative' | 'skip'; rationale: string; } export interface AirGapStatus { enabled: boolean; blockedOutboundCount: number; allowedLocalCount: number; lastAttempt: Date | null; policy: 'strict' | 'loose'; } export interface EncryptedBrainFile { schemaVersion: number; cipher: 'chacha20-poly1305'; salt: string; nonce: string; ciphertext: string; authTag: string; createdAt: string; } export interface QuarantineEntry { id: string; source: string; claim: string; evidence: string[]; reasonFlagged: string; quarantinedAt: Date; decision: 'pending' | 'promoted' | 'deleted'; } export interface VoiceCommandResult { transcript: string; confidence: number; intent: string; response: string; audioPath?: string; timestamp: Date; } export interface GardenNode { id: string; kind: 'memory' | 'pattern' | 'decision' | 'link'; label: string; age: number; strength: number; connections: string[]; bloom: number; } export interface PRReviewComment { prNumber: number; repo: string; body: string; sections: { matches: string[]; contradictions: string[]; suggestions: string[]; citations: Array<{ memoryId: string; snippet: string; }>; }; generatedAt: Date; } export interface TeamPeerInfo { peerId: string; displayName: string; agentTools: AgentTool[]; connectedAt: Date; lastSeenAt: Date; sharedMemoryCount: number; } export interface TeamSyncMessage { type: 'offer' | 'answer' | 'ice' | 'memory-sync' | 'heartbeat'; from: string; to?: string; payload: unknown; timestamp: Date; } export interface BrainSlicePackage { id: string; name: string; description: string; author: string; version: string; tags: string[]; categories: string[]; memoryCount: number; memories: Array<{ content: string; category: string; importance: number; }>; createdAt: Date; license: string; } export type LocalLLMProvider = 'ollama' | 'llamacpp' | 'lmstudio' | 'none'; export interface LocalLLMConfig { provider: LocalLLMProvider; model: string; endpoint: string; timeoutMs: number; maxTokens: number; temperature: number; } export interface LocalLLMResponse { text: string; provider: LocalLLMProvider; model: string; inputTokens: number; outputTokens: number; durationMs: number; local: true; } export interface HiveMindStatus { version: '6.0.0'; modules: { sabb: SABBStats; causal: { chains: number; links: number; }; collision: CollisionStats; dream: DreamEngineStats; reputation: ReputationLedgerStats; tokenEconomy: TokenEconomyStats; formalBridge: FormalBridgeStats; airGap: AirGapStatus; }; localFirst: boolean; totalAgentsConnected: number; totalMemoriesStored: number; generatedAt: Date; } //# sourceMappingURL=types.d.ts.map