@weavelogic/knowledge-graph-agent 0.11.9 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/commands/sparc.d.ts +14 -0
- package/dist/cli/commands/sparc.d.ts.map +1 -0
- package/dist/cli/commands/sparc.js +262 -0
- package/dist/cli/commands/sparc.js.map +1 -0
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +7 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -1
- package/dist/node_modules/@typescript-eslint/project-service/dist/index.js +1 -1
- package/dist/node_modules/tinyglobby/dist/index.js +1 -1
- package/dist/sparc/consensus.d.ts +149 -0
- package/dist/sparc/consensus.d.ts.map +1 -0
- package/dist/sparc/consensus.js +356 -0
- package/dist/sparc/consensus.js.map +1 -0
- package/dist/sparc/decision-log.d.ts +131 -0
- package/dist/sparc/decision-log.d.ts.map +1 -0
- package/dist/sparc/decision-log.js +325 -0
- package/dist/sparc/decision-log.js.map +1 -0
- package/dist/sparc/index.d.ts +14 -0
- package/dist/sparc/index.d.ts.map +1 -0
- package/dist/sparc/index.js +15 -0
- package/dist/sparc/index.js.map +1 -0
- package/dist/sparc/review-process.d.ts +72 -0
- package/dist/sparc/review-process.d.ts.map +1 -0
- package/dist/sparc/review-process.js +609 -0
- package/dist/sparc/review-process.js.map +1 -0
- package/dist/sparc/sparc-planner.d.ts +144 -0
- package/dist/sparc/sparc-planner.d.ts.map +1 -0
- package/dist/sparc/sparc-planner.js +757 -0
- package/dist/sparc/sparc-planner.js.map +1 -0
- package/dist/sparc/types.d.ts +664 -0
- package/dist/sparc/types.d.ts.map +1 -0
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * Knowledge Graph Agent\n *\n * NPM library for creating and managing knowledge graphs for Claude Code.\n *\n * @packageDocumentation\n */\n\n// Internal imports for quickInit\nimport { createDatabase as _createDatabase } from './core/database.js';\nimport { initDocs as _initDocs, docsExist as _docsExist } from './generators/docs-init.js';\nimport { generateAndSave as _generateAndSave } from './generators/graph-generator.js';\nimport { updateClaudeMd as _updateClaudeMd } from './generators/claude-md.js';\n\n// ============================================================================\n// Core\n// ============================================================================\n\nexport {\n KnowledgeGraphManager,\n createKnowledgeGraph,\n} from './core/graph.js';\n\nexport {\n KnowledgeGraphDatabase,\n createDatabase,\n} from './core/database.js';\n\n// Cache exports\nexport {\n ShadowCache,\n createShadowCache,\n loadShadowCache,\n} from './core/cache.js';\n\nexport type {\n FileMetadata,\n FileType,\n ChangeType,\n FileChange,\n CacheStats,\n ShadowCacheOptions,\n} from './core/cache.js';\n\nexport type {\n // Node types\n NodeType,\n NodeStatus,\n NodeLink,\n NodeFrontmatter,\n KnowledgeNode,\n\n // Graph types\n GraphEdge,\n GraphMetadata,\n GraphStats,\n KnowledgeGraph,\n\n // Configuration\n KGConfig,\n ConfigSchema,\n\n // Generator types\n GeneratorOptions,\n GeneratedDocument,\n DocsInitOptions,\n DocsInitResult,\n\n // Integration types\n MemoryEntry,\n SyncResult,\n\n // CLAUDE.md types\n ClaudeMdSection,\n ClaudeMdTemplate,\n ClaudeMdGeneratorOptions,\n} from './core/types.js';\n\n// ============================================================================\n// Generators\n// ============================================================================\n\nexport {\n generateGraph,\n generateAndSave,\n updateGraph,\n} from './generators/graph-generator.js';\n\nexport {\n initDocs,\n docsExist,\n getDocsPath,\n} from './generators/docs-init.js';\n\nexport {\n generateClaudeMd,\n updateClaudeMd,\n addSection,\n getSectionTemplate,\n listSectionTemplates,\n} from './generators/claude-md.js';\n\n// Conversion exports\nexport {\n convertDocs,\n addFrontmatter,\n validateFrontmatter,\n} from './generators/docs-convert.js';\n\nexport type {\n ConvertOptions,\n ConvertResult,\n FrontmatterOptions,\n FrontmatterResult,\n} from './generators/docs-convert.js';\n\n// Analyzer exports\nexport {\n analyzeDocs,\n} from './generators/docs-analyzer.js';\n\nexport type {\n AnalyzerOptions,\n AnalyzedDoc,\n AnalyzerResult,\n} from './generators/docs-analyzer.js';\n\n// ============================================================================\n// Integrations\n// ============================================================================\n\nexport {\n ClaudeFlowIntegration,\n createClaudeFlowIntegration,\n generateMcpConfig,\n} from './integrations/claude-flow.js';\n\n// ============================================================================\n// CLI\n// ============================================================================\n\nexport { createCLI } from './cli/index.js';\n\n// ============================================================================\n// Agents\n// ============================================================================\n\nexport {\n // Agent system core\n AgentType,\n AgentStatus,\n TaskPriority,\n MessageType,\n createMessageId,\n createTaskId,\n createAgentId,\n\n // Registry\n AgentRegistry,\n getRegistry,\n createRegistry,\n setDefaultRegistry,\n registerDefaultAgents,\n\n // Base Agent\n BaseAgent,\n createTask,\n isAgentResult,\n isAgentError,\n\n // Specialized Agents\n ResearcherAgent,\n CoderAgent,\n TesterAgent,\n AnalystAgent,\n ArchitectAgent,\n\n // Rules Engine\n RulesEngine,\n createRulesEngine,\n createRule,\n createConditionalRule,\n createFileChangeLogRule,\n createGraphUpdateNotificationRule,\n createAgentCompletionRule,\n} from './agents/index.js';\n\nexport type {\n // Agent types\n AgentConfig,\n ResearcherAgentConfig,\n CoderAgentConfig,\n TesterAgentConfig,\n AnalystAgentConfig,\n ArchitectAgentConfig,\n SpecializedAgentConfig,\n TaskInput,\n AgentTask,\n AgentResult as AgentSystemResult,\n AgentError,\n ExecutionMetrics,\n ResultArtifact,\n AgentMessage,\n TaskRequestMessage,\n TaskResponseMessage,\n StatusMessage,\n ErrorMessage,\n CoordinationMessage,\n AgentMessageUnion,\n AgentState,\n AgentFactory,\n AgentInstance,\n AgentCapability,\n AgentHealthCheck,\n RegistryOptions,\n SpawnOptions,\n\n // Rules Engine types\n RuleTrigger,\n RulePriority,\n RuleExecutionStatus,\n RuleContext,\n RuleCondition,\n RuleAction,\n AgentRule,\n RuleExecutionLog,\n RuleStatistics,\n EngineStatistics,\n RulesEngineConfig,\n} from './agents/index.js';\n\n// ============================================================================\n// Cultivation\n// ============================================================================\n\nexport {\n SeedGenerator,\n analyzeSeed,\n initPrimitives,\n DeepAnalyzer,\n createDeepAnalyzer,\n analyzeDeep,\n} from './cultivation/index.js';\n\nexport type {\n VaultContext,\n Ecosystem,\n DependencyType,\n ServiceType,\n DependencyInfo,\n ServiceInfo,\n SeedAnalysis,\n DocumentMetadata as CultivationDocumentMetadata,\n GeneratedDocument as CultivationGeneratedDocument,\n CultivationReport,\n CultivationOptions,\n GapAnalysis as CultivationGapAnalysis,\n InitPrimitivesResult,\n DeepAnalyzerOptions,\n AgentResult,\n DeepAnalysisResult,\n} from './cultivation/index.js';\n\n// ============================================================================\n// SOPs\n// ============================================================================\n\nexport {\n // Enums\n SOPCategory,\n ComplianceStatus,\n SOPPriority,\n IRBStatus,\n GraphLayer,\n // Registry\n getSOPById,\n getSOPsByCategory,\n getSOPsRequiringIRB,\n searchSOPs,\n getAllSOPs,\n getSopCount,\n getCategories,\n // Compliance\n checkCompliance,\n checkSOPCompliance,\n meetsMinimumCompliance,\n // Gap Analysis\n analyzeGaps,\n getGapsForSOP,\n getQuickWins,\n calculateProgress,\n // Overlay Management\n createMultiLayerGraph,\n addProjectLayer,\n addComplianceOverlay,\n filterByLayer,\n filterByComplianceStatus,\n getComplianceSummary,\n getGapNodes,\n toggleLayerVisibility,\n exportToVisualizationFormat,\n createSOPFocusedSubgraph,\n} from './sops/index.js';\n\nexport type {\n // SOP types\n SOPRequirement,\n SOPCheckpoint,\n SOPDefinition,\n SOPAssessment,\n ComplianceGap,\n LayerDefinition,\n LayerNode,\n LayerEdge,\n MultiLayerGraph,\n ComplianceReport,\n SOPFrontmatter,\n SOPConfig,\n // Compliance types\n ComplianceCheckOptions,\n ComplianceCheckResult,\n EvidenceItem,\n // Gap types\n GapAnalysisOptions,\n GapAnalysisResult,\n GapSummary,\n RemediationRoadmap,\n RemediationPhase,\n GapDependency,\n // Overlay types\n OverlayManagerOptions,\n NodeStyleConfig,\n} from './sops/index.js';\n\n// ============================================================================\n// Workflows\n// ============================================================================\n\nexport {\n WorkflowStatus,\n WorkflowRegistry,\n createWorkflowRegistry,\n} from './workflows/index.js';\n\nexport type {\n StepContext,\n StepHandler,\n RollbackHandler,\n WorkflowStep,\n WorkflowDefinition,\n StepExecution,\n WorkflowExecution,\n WorkflowResult,\n WorkflowExecutionStats,\n WorkflowRegistryOptions,\n WorkflowListOptions,\n ExecutionHistoryOptions,\n WorkflowEventType,\n WorkflowEvent,\n WorkflowEventListener,\n} from './workflows/index.js';\n\n// ============================================================================\n// Memory\n// ============================================================================\n\nexport {\n VaultMemorySync,\n createVaultMemorySync,\n} from './memory/index.js';\n\nexport type {\n SyncDirection,\n ConflictStrategy,\n SyncStatus,\n MemoryNode,\n SyncConflict,\n VaultSyncOptions,\n SyncOperationResult,\n FullSyncResult,\n} from './memory/index.js';\n\n// ============================================================================\n// Utils\n// ============================================================================\n\nexport {\n // Error Taxonomy\n ErrorCategory,\n ErrorSeverity,\n classifyError,\n isRetryableError,\n isTransientError,\n isRateLimitError,\n isPermanentError,\n KnowledgeGraphError,\n createValidationError,\n createConfigurationError,\n createResourceError,\n // Error Recovery\n withRetry,\n retry,\n withFallback,\n withCircuitBreaker,\n retryable,\n calculateBackoff,\n sleep,\n CircuitBreaker,\n CircuitState,\n RetriesExhaustedError,\n CircuitOpenError,\n // Logger\n Logger,\n LogLevel,\n getLogger,\n createLogger,\n setDefaultLogger,\n parseLogLevel,\n createProgressLogger,\n} from './utils/index.js';\n\nexport type {\n ClassifiedError,\n RetryOptions,\n RetryResult,\n FallbackOptions,\n CircuitBreakerOptions,\n LoggerOptions,\n LogEntry,\n ProgressLogger,\n} from './utils/index.js';\n\n// ============================================================================\n// MCP Server\n// ============================================================================\n\nexport {\n KnowledgeGraphMCPServer,\n createMCPServer,\n runServer,\n initializeTools,\n registerTool,\n getToolHandler,\n getToolDefinition,\n getToolDefinitions,\n getToolCategories,\n handleToolCall,\n handleError,\n createErrorResult,\n createSuccessResult,\n} from './mcp-server/index.js';\n\nexport type {\n MCPServerConfig,\n ServerHealth,\n ToolCategory,\n ToolHandler,\n ToolHandlerEntry,\n ToolResult,\n ToolContext,\n ToolInputSchema,\n ToolDefinition,\n GraphQueryParams,\n GraphNodeResult,\n AgentInvokeParams,\n AgentResult as MCPAgentResult,\n WorkflowParams,\n WorkflowResult as MCPWorkflowResult,\n MemoryParams,\n MemoryResult,\n} from './mcp-server/index.js';\n\n// ============================================================================\n// Server Infrastructure\n// ============================================================================\n\nexport {\n // Server Manager\n ServerManager,\n createServerManager,\n\n // Shared Services\n SharedServices,\n createSharedServices,\n getSharedServices,\n createDefaultConfig,\n\n // Service Container\n ServiceContainer,\n createServiceContainer,\n getServiceContainer,\n hasServiceContainer,\n shutdownServiceContainer,\n\n // TypedEventBus\n TypedEventBus,\n createTypedEventBus,\n createSubscriptionIterator,\n createNodeTypeFilter,\n createSourceFilter,\n\n // Constants\n DEFAULT_GRAPHQL_PORT,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_DATABASE_PATH,\n SHUTDOWN_TIMEOUT,\n HEALTH_CHECK_INTERVAL,\n} from './server/index.js';\n\nexport type {\n // Configuration types\n ServerConfig,\n MCPServerConfig as ServerMCPConfig,\n GraphQLServerConfig,\n DashboardServerConfig,\n DatabaseServerConfig,\n CacheServerConfig,\n\n // State types\n ServerStatus,\n ServerState,\n ServerManagerState,\n\n // Health types\n ComponentHealth as ServerComponentHealth,\n HealthStatus as ServerHealthStatus,\n\n // Event types\n ServerEventType,\n ServerEvent,\n ServerEventListener,\n\n // Instance types\n HTTPServerInstance,\n MCPServerInstance,\n\n // CLI types\n ServeCommandOptions,\n ParsedServeOptions,\n\n // Interface types\n ISharedServices,\n IServerManager,\n\n // Service Container types\n ServiceInitState,\n ServiceDependency,\n ContainerConfig,\n ContainerEventType,\n\n // TypedEventBus types\n EventType as ServerEventTypeEnum,\n EventDataMap,\n EventEntry,\n EventFilter,\n EventHandler as ServerEventHandler,\n Unsubscribe,\n NodeEventData,\n RelationEventData,\n AgentEventData,\n WorkflowEventData,\n PluginEventData,\n HealthEventData,\n CacheEvictionData,\n EventTypeMetrics,\n EventBusMetrics,\n ITypedEventBus,\n TypedEventBusOptions,\n} from './server/index.js';\n\n// ============================================================================\n// GraphQL\n// ============================================================================\n\nexport {\n // Server\n createGraphQLServer,\n\n // Context\n createContextFactory,\n hasScope,\n requireAuth,\n requireScope,\n isGraphQLContext,\n\n // Scalars\n DateTimeScalar,\n JSONScalar,\n UUIDScalar,\n FilePathScalar,\n customScalars,\n scalarTypeDefs,\n} from './graphql/index.js';\n\nexport type {\n // Server types\n GraphQLServerConfig as GraphQLServerOptions,\n GraphQLServerInstance,\n CorsConfig,\n HealthCheckResponse as GraphQLHealthCheckResponse,\n\n // Context types\n GraphQLContext,\n AuthResult,\n RequestMeta,\n RequestUtils,\n Services as GraphQLServices,\n ContextFactoryConfig,\n} from './graphql/index.js';\n\n// ============================================================================\n// Services\n// ============================================================================\n\nexport {\n ServiceManager,\n createServiceManager,\n FileWatcherService,\n} from './services/index.js';\n\nexport type {\n ServiceStatus,\n ServiceType as ManagerServiceType,\n ServiceConfig,\n ServiceState,\n ServiceMetrics,\n ServiceHandler,\n} from './services/index.js';\n\n// ============================================================================\n// Config\n// ============================================================================\n\nexport {\n ConfigManager,\n createConfigManager,\n getDefaultConfig,\n} from './config/index.js';\n\nexport type {\n KGConfiguration,\n DatabaseConfig,\n CacheConfig,\n AgentConfig as ConfigAgentConfig,\n ServicesConfig,\n LoggingConfig,\n ConfigMigration,\n} from './config/index.js';\n\n// ============================================================================\n// Health\n// ============================================================================\n\nexport {\n HealthMonitor,\n createHealthMonitor,\n createDatabaseCheck,\n createCacheCheck,\n createMemoryCheck,\n createDiskCheck,\n} from './health/index.js';\n\nexport type {\n HealthStatus,\n ComponentHealth,\n SystemHealth,\n MemoryMetrics,\n PerformanceMetrics,\n HealthCheck,\n HealthMonitorConfig,\n} from './health/index.js';\n\n// ============================================================================\n// Chunking\n// ============================================================================\n\nexport {\n Chunker,\n createChunker,\n chunkDocument,\n} from './chunking/index.js';\n\nexport type {\n ChunkStrategy,\n ChunkOptions,\n Chunk,\n ChunkMetadata,\n ChunkResult,\n} from './chunking/index.js';\n\n// ============================================================================\n// Recovery\n// ============================================================================\n\nexport {\n BackupManager,\n createBackupManager,\n IntegrityChecker,\n createIntegrityChecker,\n checkDatabaseIntegrity,\n} from './recovery/index.js';\n\nexport type {\n BackupConfig,\n BackupInfo,\n RestoreResult,\n RecoveryOptions,\n IntegrityCheckResult,\n TableIntegrity,\n} from './recovery/index.js';\n\n// ============================================================================\n// Advanced Caching\n// ============================================================================\n\nexport {\n AdvancedCache,\n createAdvancedCache,\n} from './caching/index.js';\n\nexport type {\n EvictionPolicy,\n CacheEntry,\n CacheConfig as AdvancedCacheConfig,\n CacheStats as AdvancedCacheStats,\n} from './caching/index.js';\n\n// ============================================================================\n// Reasoning\n// ============================================================================\n\nexport {\n DecisionTracker,\n createDecisionTracker,\n getDecisionTracker,\n} from './reasoning/index.js';\n\nexport type {\n DecisionType,\n ConfidenceLevel,\n Decision,\n DecisionContext,\n Alternative,\n DecisionOutcome,\n ReasoningChain,\n} from './reasoning/index.js';\n\n// ============================================================================\n// Workflow DevKit\n// ============================================================================\n\nexport {\n createWorkflowConfig,\n validateWorkflowConfig,\n createPostgresConfig,\n createVercelConfig,\n createLocalConfig,\n defaultConfig as defaultWorkflowConfig,\n} from './workflow/index.js';\n\nexport type {\n // Configuration types\n WorkflowConfig as WorkflowDevKitConfig,\n PostgresPoolConfig,\n PostgresWorldConfig,\n VercelWorldConfig,\n LocalWorldConfig,\n // World state types\n WorldState,\n // Event types\n NodeUpdateEvent,\n GapDetectedEvent,\n WorkflowCompleteEvent,\n WorkflowRunMetadata as DevKitRunMetadata,\n // Task types\n TaskSpec,\n DocumentGap,\n GapAnalysis as DevKitGapAnalysis,\n // GOAP types\n GOAPAction,\n GOAPGoal,\n GOAPPlanStep,\n GOAPPlan,\n GOAPPlanExtended,\n PlanExecutionResult,\n ReadinessEvaluation,\n // Execution types\n WorkflowExecutionOptions as DevKitExecutionOptions,\n WorkflowExecutionResult as DevKitExecutionResult,\n // Hook types\n HookHandler,\n HookRegistration,\n} from './workflow/index.js';\n\n// ============================================================================\n// Plugins\n// ============================================================================\n\n// Plugin System - Core exports (includes types, manager, analyzers)\n// This re-exports everything from plugins/index.js including:\n// - Types: PluginType, PluginHook, PluginStatus, PluginCapability, PluginDependency,\n// PluginConfigSchema, KGPluginManifest, PluginMetadata, KGPlugin, AnalyzerPlugin,\n// PluginContext, PluginAPI, PluginCommand, PluginEventEmitter, PluginLoader,\n// PluginRegistry, PluginManager, PluginManagerConfig, DiscoveredPlugin,\n// PluginLoadOptions, PluginLoadResult, PluginRegistryEvents, AnalysisInput,\n// AnalysisResult, AnalysisStreamChunk, PluginFactory, PluginConstructor,\n// PluginModuleExport, PluginConfigType\n// - Manager: PluginManagerImpl, PluginRegistryImpl, PluginLoaderImpl,\n// createPluginManager, createPluginRegistry, createPluginLoader,\n// createDefaultPluginManager\n// - Analyzers: CodeComplexityPlugin, DependencyHealthPlugin, and related exports\nexport * from './plugins/index.js';\n\n// ============================================================================\n// Equilibrium (SPEC-006a)\n// ============================================================================\n\nexport {\n AgentEquilibriumSelector,\n createAgentEquilibriumSelector,\n createEquilibriumTask,\n} from './equilibrium/index.js';\n\nexport type {\n AgentParticipation,\n EquilibriumConfig,\n EquilibriumResult,\n Task as EquilibriumTask,\n} from './equilibrium/index.js';\n\n// ============================================================================\n// Quick Start\n// ============================================================================\n\n/**\n * Quick start function for programmatic usage\n *\n * @example\n * ```typescript\n * import { quickInit } from '@weave-nn/knowledge-graph-agent';\n *\n * await quickInit({\n * projectRoot: '/path/to/project',\n * docsPath: 'docs',\n * });\n * ```\n */\nexport async function quickInit(options: {\n projectRoot: string;\n docsPath?: string;\n generateGraph?: boolean;\n updateClaudeMd?: boolean;\n}): Promise<{\n success: boolean;\n docsCreated: boolean;\n graphGenerated: boolean;\n claudeMdUpdated: boolean;\n errors: string[];\n}> {\n const {\n projectRoot,\n docsPath = 'docs',\n generateGraph: genGraph = true,\n updateClaudeMd: updateClaude = true,\n } = options;\n\n const result = {\n success: true,\n docsCreated: false,\n graphGenerated: false,\n claudeMdUpdated: false,\n errors: [] as string[],\n };\n\n try {\n // Initialize docs if needed\n const { existsSync, mkdirSync, writeFileSync } = await import('fs');\n const { join } = await import('path');\n\n // Create .kg directory\n const kgDir = join(projectRoot, '.kg');\n if (!existsSync(kgDir)) {\n mkdirSync(kgDir, { recursive: true });\n }\n\n // Initialize database\n const dbPath = join(kgDir, 'knowledge.db');\n const db = _createDatabase(dbPath);\n db.setMetadata('initialized', new Date().toISOString());\n\n // Initialize docs\n if (!_docsExist(projectRoot, docsPath)) {\n const docsResult = await _initDocs({\n projectRoot,\n docsPath,\n includeExamples: true,\n detectFramework: true,\n });\n result.docsCreated = docsResult.success;\n if (!docsResult.success) {\n result.errors.push(...docsResult.errors);\n }\n }\n\n // Generate graph\n if (genGraph && _docsExist(projectRoot, docsPath)) {\n const graphResult = await _generateAndSave(\n {\n projectRoot,\n outputPath: join(projectRoot, docsPath),\n },\n dbPath\n );\n result.graphGenerated = graphResult.success;\n if (!graphResult.success) {\n result.errors.push(...graphResult.stats.errors);\n }\n }\n\n // Update CLAUDE.md\n if (updateClaude) {\n const claudeResult = await _updateClaudeMd({\n projectRoot,\n includeKnowledgeGraph: true,\n includeClaudeFlow: true,\n });\n result.claudeMdUpdated = claudeResult.created || claudeResult.updated;\n }\n\n db.close();\n result.success = result.errors.length === 0;\n\n } catch (error) {\n result.success = false;\n result.errors.push(String(error));\n }\n\n return result;\n}\n"],"names":["_createDatabase","_docsExist","_initDocs","_generateAndSave","_updateClaudeMd"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+0BA,eAAsB,UAAU,SAW7B;AACD,QAAM;AAAA,IACJ;AAAA,IACA,WAAW;AAAA,IACX,eAAe,WAAW;AAAA,IAC1B,gBAAgB,eAAe;AAAA,EAAA,IAC7B;AAEJ,QAAM,SAAS;AAAA,IACb,SAAS;AAAA,IACT,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,IACjB,QAAQ,CAAA;AAAA,EAAC;AAGX,MAAI;AAEF,UAAM,EAAE,YAAY,WAAW,kBAAkB,MAAM,OAAO,IAAI;AAClE,UAAM,EAAE,KAAA,IAAS,MAAM,OAAO,MAAM;AAGpC,UAAM,QAAQ,KAAK,aAAa,KAAK;AACrC,QAAI,CAAC,WAAW,KAAK,GAAG;AACtB,gBAAU,OAAO,EAAE,WAAW,KAAA,CAAM;AAAA,IACtC;AAGA,UAAM,SAAS,KAAK,OAAO,cAAc;AACzC,UAAM,KAAKA,eAAgB,MAAM;AACjC,OAAG,YAAY,gBAAe,oBAAI,KAAA,GAAO,aAAa;AAGtD,QAAI,CAACC,UAAW,aAAa,QAAQ,GAAG;AACtC,YAAM,aAAa,MAAMC,SAAU;AAAA,QACjC;AAAA,QACA;AAAA,QACA,iBAAiB;AAAA,QACjB,iBAAiB;AAAA,MAAA,CAClB;AACD,aAAO,cAAc,WAAW;AAChC,UAAI,CAAC,WAAW,SAAS;AACvB,eAAO,OAAO,KAAK,GAAG,WAAW,MAAM;AAAA,MACzC;AAAA,IACF;AAGA,QAAI,YAAYD,UAAW,aAAa,QAAQ,GAAG;AACjD,YAAM,cAAc,MAAME;AAAAA,QACxB;AAAA,UACE;AAAA,UACA,YAAY,KAAK,aAAa,QAAQ;AAAA,QAAA;AAAA,QAExC;AAAA,MAAA;AAEF,aAAO,iBAAiB,YAAY;AACpC,UAAI,CAAC,YAAY,SAAS;AACxB,eAAO,OAAO,KAAK,GAAG,YAAY,MAAM,MAAM;AAAA,MAChD;AAAA,IACF;AAGA,QAAI,cAAc;AAChB,YAAM,eAAe,MAAMC,eAAgB;AAAA,QACzC;AAAA,QACA,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,MAAA,CACpB;AACD,aAAO,kBAAkB,aAAa,WAAW,aAAa;AAAA,IAChE;AAEA,OAAG,MAAA;AACH,WAAO,UAAU,OAAO,OAAO,WAAW;AAAA,EAE5C,SAAS,OAAO;AACd,WAAO,UAAU;AACjB,WAAO,OAAO,KAAK,OAAO,KAAK,CAAC;AAAA,EAClC;AAEA,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["/**\n * Knowledge Graph Agent\n *\n * NPM library for creating and managing knowledge graphs for Claude Code.\n *\n * @packageDocumentation\n */\n\n// Internal imports for quickInit\nimport { createDatabase as _createDatabase } from './core/database.js';\nimport { initDocs as _initDocs, docsExist as _docsExist } from './generators/docs-init.js';\nimport { generateAndSave as _generateAndSave } from './generators/graph-generator.js';\nimport { updateClaudeMd as _updateClaudeMd } from './generators/claude-md.js';\n\n// ============================================================================\n// Core\n// ============================================================================\n\nexport {\n KnowledgeGraphManager,\n createKnowledgeGraph,\n} from './core/graph.js';\n\nexport {\n KnowledgeGraphDatabase,\n createDatabase,\n} from './core/database.js';\n\n// Cache exports\nexport {\n ShadowCache,\n createShadowCache,\n loadShadowCache,\n} from './core/cache.js';\n\nexport type {\n FileMetadata,\n FileType,\n ChangeType,\n FileChange,\n CacheStats,\n ShadowCacheOptions,\n} from './core/cache.js';\n\nexport type {\n // Node types\n NodeType,\n NodeStatus,\n NodeLink,\n NodeFrontmatter,\n KnowledgeNode,\n\n // Graph types\n GraphEdge,\n GraphMetadata,\n GraphStats,\n KnowledgeGraph,\n\n // Configuration\n KGConfig,\n ConfigSchema,\n\n // Generator types\n GeneratorOptions,\n GeneratedDocument,\n DocsInitOptions,\n DocsInitResult,\n\n // Integration types\n MemoryEntry,\n SyncResult,\n\n // CLAUDE.md types\n ClaudeMdSection,\n ClaudeMdTemplate,\n ClaudeMdGeneratorOptions,\n} from './core/types.js';\n\n// ============================================================================\n// Generators\n// ============================================================================\n\nexport {\n generateGraph,\n generateAndSave,\n updateGraph,\n} from './generators/graph-generator.js';\n\nexport {\n initDocs,\n docsExist,\n getDocsPath,\n} from './generators/docs-init.js';\n\nexport {\n generateClaudeMd,\n updateClaudeMd,\n addSection,\n getSectionTemplate,\n listSectionTemplates,\n} from './generators/claude-md.js';\n\n// Conversion exports\nexport {\n convertDocs,\n addFrontmatter,\n validateFrontmatter,\n} from './generators/docs-convert.js';\n\nexport type {\n ConvertOptions,\n ConvertResult,\n FrontmatterOptions,\n FrontmatterResult,\n} from './generators/docs-convert.js';\n\n// Analyzer exports\nexport {\n analyzeDocs,\n} from './generators/docs-analyzer.js';\n\nexport type {\n AnalyzerOptions,\n AnalyzedDoc,\n AnalyzerResult,\n} from './generators/docs-analyzer.js';\n\n// ============================================================================\n// Integrations\n// ============================================================================\n\nexport {\n ClaudeFlowIntegration,\n createClaudeFlowIntegration,\n generateMcpConfig,\n} from './integrations/claude-flow.js';\n\n// ============================================================================\n// CLI\n// ============================================================================\n\nexport { createCLI } from './cli/index.js';\n\n// ============================================================================\n// Agents\n// ============================================================================\n\nexport {\n // Agent system core\n AgentType,\n AgentStatus,\n TaskPriority,\n MessageType,\n createMessageId,\n createTaskId,\n createAgentId,\n\n // Registry\n AgentRegistry,\n getRegistry,\n createRegistry,\n setDefaultRegistry,\n registerDefaultAgents,\n\n // Base Agent\n BaseAgent,\n createTask,\n isAgentResult,\n isAgentError,\n\n // Specialized Agents\n ResearcherAgent,\n CoderAgent,\n TesterAgent,\n AnalystAgent,\n ArchitectAgent,\n\n // Rules Engine\n RulesEngine,\n createRulesEngine,\n createRule,\n createConditionalRule,\n createFileChangeLogRule,\n createGraphUpdateNotificationRule,\n createAgentCompletionRule,\n} from './agents/index.js';\n\nexport type {\n // Agent types\n AgentConfig,\n ResearcherAgentConfig,\n CoderAgentConfig,\n TesterAgentConfig,\n AnalystAgentConfig,\n ArchitectAgentConfig,\n SpecializedAgentConfig,\n TaskInput,\n AgentTask,\n AgentResult as AgentSystemResult,\n AgentError,\n ExecutionMetrics,\n ResultArtifact,\n AgentMessage,\n TaskRequestMessage,\n TaskResponseMessage,\n StatusMessage,\n ErrorMessage,\n CoordinationMessage,\n AgentMessageUnion,\n AgentState,\n AgentFactory,\n AgentInstance,\n AgentCapability,\n AgentHealthCheck,\n RegistryOptions,\n SpawnOptions,\n\n // Rules Engine types\n RuleTrigger,\n RulePriority,\n RuleExecutionStatus,\n RuleContext,\n RuleCondition,\n RuleAction,\n AgentRule,\n RuleExecutionLog,\n RuleStatistics,\n EngineStatistics,\n RulesEngineConfig,\n} from './agents/index.js';\n\n// ============================================================================\n// Cultivation\n// ============================================================================\n\nexport {\n SeedGenerator,\n analyzeSeed,\n initPrimitives,\n DeepAnalyzer,\n createDeepAnalyzer,\n analyzeDeep,\n} from './cultivation/index.js';\n\nexport type {\n VaultContext,\n Ecosystem,\n DependencyType,\n ServiceType,\n DependencyInfo,\n ServiceInfo,\n SeedAnalysis,\n DocumentMetadata as CultivationDocumentMetadata,\n GeneratedDocument as CultivationGeneratedDocument,\n CultivationReport,\n CultivationOptions,\n GapAnalysis as CultivationGapAnalysis,\n InitPrimitivesResult,\n DeepAnalyzerOptions,\n AgentResult,\n DeepAnalysisResult,\n} from './cultivation/index.js';\n\n// ============================================================================\n// SOPs\n// ============================================================================\n\nexport {\n // Enums\n SOPCategory,\n ComplianceStatus,\n SOPPriority,\n IRBStatus,\n GraphLayer,\n // Registry\n getSOPById,\n getSOPsByCategory,\n getSOPsRequiringIRB,\n searchSOPs,\n getAllSOPs,\n getSopCount,\n getCategories,\n // Compliance\n checkCompliance,\n checkSOPCompliance,\n meetsMinimumCompliance,\n // Gap Analysis\n analyzeGaps,\n getGapsForSOP,\n getQuickWins,\n calculateProgress,\n // Overlay Management\n createMultiLayerGraph,\n addProjectLayer,\n addComplianceOverlay,\n filterByLayer,\n filterByComplianceStatus,\n getComplianceSummary,\n getGapNodes,\n toggleLayerVisibility,\n exportToVisualizationFormat,\n createSOPFocusedSubgraph,\n} from './sops/index.js';\n\nexport type {\n // SOP types\n SOPRequirement,\n SOPCheckpoint,\n SOPDefinition,\n SOPAssessment,\n ComplianceGap,\n LayerDefinition,\n LayerNode,\n LayerEdge,\n MultiLayerGraph,\n ComplianceReport,\n SOPFrontmatter,\n SOPConfig,\n // Compliance types\n ComplianceCheckOptions,\n ComplianceCheckResult,\n EvidenceItem,\n // Gap types\n GapAnalysisOptions,\n GapAnalysisResult,\n GapSummary,\n RemediationRoadmap,\n RemediationPhase,\n GapDependency,\n // Overlay types\n OverlayManagerOptions,\n NodeStyleConfig,\n} from './sops/index.js';\n\n// ============================================================================\n// Workflows\n// ============================================================================\n\nexport {\n WorkflowStatus,\n WorkflowRegistry,\n createWorkflowRegistry,\n} from './workflows/index.js';\n\nexport type {\n StepContext,\n StepHandler,\n RollbackHandler,\n WorkflowStep,\n WorkflowDefinition,\n StepExecution,\n WorkflowExecution,\n WorkflowResult,\n WorkflowExecutionStats,\n WorkflowRegistryOptions,\n WorkflowListOptions,\n ExecutionHistoryOptions,\n WorkflowEventType,\n WorkflowEvent,\n WorkflowEventListener,\n} from './workflows/index.js';\n\n// ============================================================================\n// Memory\n// ============================================================================\n\nexport {\n VaultMemorySync,\n createVaultMemorySync,\n} from './memory/index.js';\n\nexport type {\n SyncDirection,\n ConflictStrategy,\n SyncStatus,\n MemoryNode,\n SyncConflict,\n VaultSyncOptions,\n SyncOperationResult,\n FullSyncResult,\n} from './memory/index.js';\n\n// ============================================================================\n// Utils\n// ============================================================================\n\nexport {\n // Error Taxonomy\n ErrorCategory,\n ErrorSeverity,\n classifyError,\n isRetryableError,\n isTransientError,\n isRateLimitError,\n isPermanentError,\n KnowledgeGraphError,\n createValidationError,\n createConfigurationError,\n createResourceError,\n // Error Recovery\n withRetry,\n retry,\n withFallback,\n withCircuitBreaker,\n retryable,\n calculateBackoff,\n sleep,\n CircuitBreaker,\n CircuitState,\n RetriesExhaustedError,\n CircuitOpenError,\n // Logger\n Logger,\n LogLevel,\n getLogger,\n createLogger,\n setDefaultLogger,\n parseLogLevel,\n createProgressLogger,\n} from './utils/index.js';\n\nexport type {\n ClassifiedError,\n RetryOptions,\n RetryResult,\n FallbackOptions,\n CircuitBreakerOptions,\n LoggerOptions,\n LogEntry,\n ProgressLogger,\n} from './utils/index.js';\n\n// ============================================================================\n// MCP Server\n// ============================================================================\n\nexport {\n KnowledgeGraphMCPServer,\n createMCPServer,\n runServer,\n initializeTools,\n registerTool,\n getToolHandler,\n getToolDefinition,\n getToolDefinitions,\n getToolCategories,\n handleToolCall,\n handleError,\n createErrorResult,\n createSuccessResult,\n} from './mcp-server/index.js';\n\nexport type {\n MCPServerConfig,\n ServerHealth,\n ToolCategory,\n ToolHandler,\n ToolHandlerEntry,\n ToolResult,\n ToolContext,\n ToolInputSchema,\n ToolDefinition,\n GraphQueryParams,\n GraphNodeResult,\n AgentInvokeParams,\n AgentResult as MCPAgentResult,\n WorkflowParams,\n WorkflowResult as MCPWorkflowResult,\n MemoryParams,\n MemoryResult,\n} from './mcp-server/index.js';\n\n// ============================================================================\n// Server Infrastructure\n// ============================================================================\n\nexport {\n // Server Manager\n ServerManager,\n createServerManager,\n\n // Shared Services\n SharedServices,\n createSharedServices,\n getSharedServices,\n createDefaultConfig,\n\n // Service Container\n ServiceContainer,\n createServiceContainer,\n getServiceContainer,\n hasServiceContainer,\n shutdownServiceContainer,\n\n // TypedEventBus\n TypedEventBus,\n createTypedEventBus,\n createSubscriptionIterator,\n createNodeTypeFilter,\n createSourceFilter,\n\n // Constants\n DEFAULT_GRAPHQL_PORT,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_DATABASE_PATH,\n SHUTDOWN_TIMEOUT,\n HEALTH_CHECK_INTERVAL,\n} from './server/index.js';\n\nexport type {\n // Configuration types\n ServerConfig,\n MCPServerConfig as ServerMCPConfig,\n GraphQLServerConfig,\n DashboardServerConfig,\n DatabaseServerConfig,\n CacheServerConfig,\n\n // State types\n ServerStatus,\n ServerState,\n ServerManagerState,\n\n // Health types\n ComponentHealth as ServerComponentHealth,\n HealthStatus as ServerHealthStatus,\n\n // Event types\n ServerEventType,\n ServerEvent,\n ServerEventListener,\n\n // Instance types\n HTTPServerInstance,\n MCPServerInstance,\n\n // CLI types\n ServeCommandOptions,\n ParsedServeOptions,\n\n // Interface types\n ISharedServices,\n IServerManager,\n\n // Service Container types\n ServiceInitState,\n ServiceDependency,\n ContainerConfig,\n ContainerEventType,\n\n // TypedEventBus types\n EventType as ServerEventTypeEnum,\n EventDataMap,\n EventEntry,\n EventFilter,\n EventHandler as ServerEventHandler,\n Unsubscribe,\n NodeEventData,\n RelationEventData,\n AgentEventData,\n WorkflowEventData,\n PluginEventData,\n HealthEventData,\n CacheEvictionData,\n EventTypeMetrics,\n EventBusMetrics,\n ITypedEventBus,\n TypedEventBusOptions,\n} from './server/index.js';\n\n// ============================================================================\n// GraphQL\n// ============================================================================\n\nexport {\n // Server\n createGraphQLServer,\n\n // Context\n createContextFactory,\n hasScope,\n requireAuth,\n requireScope,\n isGraphQLContext,\n\n // Scalars\n DateTimeScalar,\n JSONScalar,\n UUIDScalar,\n FilePathScalar,\n customScalars,\n scalarTypeDefs,\n} from './graphql/index.js';\n\nexport type {\n // Server types\n GraphQLServerConfig as GraphQLServerOptions,\n GraphQLServerInstance,\n CorsConfig,\n HealthCheckResponse as GraphQLHealthCheckResponse,\n\n // Context types\n GraphQLContext,\n AuthResult,\n RequestMeta,\n RequestUtils,\n Services as GraphQLServices,\n ContextFactoryConfig,\n} from './graphql/index.js';\n\n// ============================================================================\n// Services\n// ============================================================================\n\nexport {\n ServiceManager,\n createServiceManager,\n FileWatcherService,\n} from './services/index.js';\n\nexport type {\n ServiceStatus,\n ServiceType as ManagerServiceType,\n ServiceConfig,\n ServiceState,\n ServiceMetrics,\n ServiceHandler,\n} from './services/index.js';\n\n// ============================================================================\n// Config\n// ============================================================================\n\nexport {\n ConfigManager,\n createConfigManager,\n getDefaultConfig,\n} from './config/index.js';\n\nexport type {\n KGConfiguration,\n DatabaseConfig,\n CacheConfig,\n AgentConfig as ConfigAgentConfig,\n ServicesConfig,\n LoggingConfig,\n ConfigMigration,\n} from './config/index.js';\n\n// ============================================================================\n// Health\n// ============================================================================\n\nexport {\n HealthMonitor,\n createHealthMonitor,\n createDatabaseCheck,\n createCacheCheck,\n createMemoryCheck,\n createDiskCheck,\n} from './health/index.js';\n\nexport type {\n HealthStatus,\n ComponentHealth,\n SystemHealth,\n MemoryMetrics,\n PerformanceMetrics,\n HealthCheck,\n HealthMonitorConfig,\n} from './health/index.js';\n\n// ============================================================================\n// Chunking\n// ============================================================================\n\nexport {\n Chunker,\n createChunker,\n chunkDocument,\n} from './chunking/index.js';\n\nexport type {\n ChunkStrategy,\n ChunkOptions,\n Chunk,\n ChunkMetadata,\n ChunkResult,\n} from './chunking/index.js';\n\n// ============================================================================\n// Recovery\n// ============================================================================\n\nexport {\n BackupManager,\n createBackupManager,\n IntegrityChecker,\n createIntegrityChecker,\n checkDatabaseIntegrity,\n} from './recovery/index.js';\n\nexport type {\n BackupConfig,\n BackupInfo,\n RestoreResult,\n RecoveryOptions,\n IntegrityCheckResult,\n TableIntegrity,\n} from './recovery/index.js';\n\n// ============================================================================\n// Advanced Caching\n// ============================================================================\n\nexport {\n AdvancedCache,\n createAdvancedCache,\n} from './caching/index.js';\n\nexport type {\n EvictionPolicy,\n CacheEntry,\n CacheConfig as AdvancedCacheConfig,\n CacheStats as AdvancedCacheStats,\n} from './caching/index.js';\n\n// ============================================================================\n// Reasoning\n// ============================================================================\n\nexport {\n DecisionTracker,\n createDecisionTracker,\n getDecisionTracker,\n} from './reasoning/index.js';\n\nexport type {\n DecisionType,\n ConfidenceLevel,\n Decision,\n DecisionContext,\n Alternative,\n DecisionOutcome,\n ReasoningChain,\n} from './reasoning/index.js';\n\n// ============================================================================\n// Workflow DevKit\n// ============================================================================\n\nexport {\n createWorkflowConfig,\n validateWorkflowConfig,\n createPostgresConfig,\n createVercelConfig,\n createLocalConfig,\n defaultConfig as defaultWorkflowConfig,\n} from './workflow/index.js';\n\nexport type {\n // Configuration types\n WorkflowConfig as WorkflowDevKitConfig,\n PostgresPoolConfig,\n PostgresWorldConfig,\n VercelWorldConfig,\n LocalWorldConfig,\n // World state types\n WorldState,\n // Event types\n NodeUpdateEvent,\n GapDetectedEvent,\n WorkflowCompleteEvent,\n WorkflowRunMetadata as DevKitRunMetadata,\n // Task types\n TaskSpec,\n DocumentGap,\n GapAnalysis as DevKitGapAnalysis,\n // GOAP types\n GOAPAction,\n GOAPGoal,\n GOAPPlanStep,\n GOAPPlan,\n GOAPPlanExtended,\n PlanExecutionResult,\n ReadinessEvaluation,\n // Execution types\n WorkflowExecutionOptions as DevKitExecutionOptions,\n WorkflowExecutionResult as DevKitExecutionResult,\n // Hook types\n HookHandler,\n HookRegistration,\n} from './workflow/index.js';\n\n// ============================================================================\n// Plugins\n// ============================================================================\n\n// Plugin System - Core exports (includes types, manager, analyzers)\n// This re-exports everything from plugins/index.js including:\n// - Types: PluginType, PluginHook, PluginStatus, PluginCapability, PluginDependency,\n// PluginConfigSchema, KGPluginManifest, PluginMetadata, KGPlugin, AnalyzerPlugin,\n// PluginContext, PluginAPI, PluginCommand, PluginEventEmitter, PluginLoader,\n// PluginRegistry, PluginManager, PluginManagerConfig, DiscoveredPlugin,\n// PluginLoadOptions, PluginLoadResult, PluginRegistryEvents, AnalysisInput,\n// AnalysisResult, AnalysisStreamChunk, PluginFactory, PluginConstructor,\n// PluginModuleExport, PluginConfigType\n// - Manager: PluginManagerImpl, PluginRegistryImpl, PluginLoaderImpl,\n// createPluginManager, createPluginRegistry, createPluginLoader,\n// createDefaultPluginManager\n// - Analyzers: CodeComplexityPlugin, DependencyHealthPlugin, and related exports\nexport * from './plugins/index.js';\n\n// ============================================================================\n// Equilibrium (SPEC-006a)\n// ============================================================================\n\nexport {\n AgentEquilibriumSelector,\n createAgentEquilibriumSelector,\n createEquilibriumTask,\n} from './equilibrium/index.js';\n\nexport type {\n AgentParticipation,\n EquilibriumConfig,\n EquilibriumResult,\n Task as EquilibriumTask,\n} from './equilibrium/index.js';\n\n// ============================================================================\n// SPARC Planning\n// ============================================================================\n\nexport {\n // Decision Log\n DecisionLogManager,\n createDecisionLogManager,\n // Consensus Builder\n ConsensusBuilder,\n createConsensusBuilder,\n // Review Process\n ReviewProcessManager,\n createReviewProcess,\n // SPARC Planner\n SPARCPlanner,\n createSPARCPlanner,\n} from './sparc/index.js';\n\nexport type {\n // Core SPARC types\n SPARCPhase,\n ConfidenceLevel as SPARCConfidenceLevel,\n DecisionStatus,\n ReviewPassType,\n FindingSeverity,\n TaskExecutionMode,\n // Specification types\n Requirement,\n Feature,\n SpecificationDocument,\n // Pseudocode types\n AlgorithmStep,\n AlgorithmDesign,\n // Architecture types\n ArchitectureComponent,\n ComponentInterface,\n ArchitectureDecision,\n ArchitectureDocument,\n // Task types\n SPARCTask,\n TaskOutput,\n ContextLink,\n KGReference,\n // Decision types\n DecisionEntry,\n ConsensusInfo,\n DecisionLog,\n // Review types\n ReviewFinding,\n ReviewPassResult,\n ReviewResult,\n // Plan types\n SPARCPlanStatus,\n ExistingCodeAnalysis,\n ResearchFinding,\n SPARCPlan,\n // Agent coordination types\n AgentSpawnRequest,\n AgentExecutionResult,\n ConsensusRequest,\n ConsensusResult,\n // Options types\n DecisionLogManagerOptions,\n AddDecisionOptions,\n ConsensusBuilderOptions,\n AgentVote,\n ConsensusOption,\n ReviewProcessOptions,\n SPARCPlannerOptions,\n} from './sparc/index.js';\n\n// ============================================================================\n// Quick Start\n// ============================================================================\n\n/**\n * Quick start function for programmatic usage\n *\n * @example\n * ```typescript\n * import { quickInit } from '@weave-nn/knowledge-graph-agent';\n *\n * await quickInit({\n * projectRoot: '/path/to/project',\n * docsPath: 'docs',\n * });\n * ```\n */\nexport async function quickInit(options: {\n projectRoot: string;\n docsPath?: string;\n generateGraph?: boolean;\n updateClaudeMd?: boolean;\n}): Promise<{\n success: boolean;\n docsCreated: boolean;\n graphGenerated: boolean;\n claudeMdUpdated: boolean;\n errors: string[];\n}> {\n const {\n projectRoot,\n docsPath = 'docs',\n generateGraph: genGraph = true,\n updateClaudeMd: updateClaude = true,\n } = options;\n\n const result = {\n success: true,\n docsCreated: false,\n graphGenerated: false,\n claudeMdUpdated: false,\n errors: [] as string[],\n };\n\n try {\n // Initialize docs if needed\n const { existsSync, mkdirSync, writeFileSync } = await import('fs');\n const { join } = await import('path');\n\n // Create .kg directory\n const kgDir = join(projectRoot, '.kg');\n if (!existsSync(kgDir)) {\n mkdirSync(kgDir, { recursive: true });\n }\n\n // Initialize database\n const dbPath = join(kgDir, 'knowledge.db');\n const db = _createDatabase(dbPath);\n db.setMetadata('initialized', new Date().toISOString());\n\n // Initialize docs\n if (!_docsExist(projectRoot, docsPath)) {\n const docsResult = await _initDocs({\n projectRoot,\n docsPath,\n includeExamples: true,\n detectFramework: true,\n });\n result.docsCreated = docsResult.success;\n if (!docsResult.success) {\n result.errors.push(...docsResult.errors);\n }\n }\n\n // Generate graph\n if (genGraph && _docsExist(projectRoot, docsPath)) {\n const graphResult = await _generateAndSave(\n {\n projectRoot,\n outputPath: join(projectRoot, docsPath),\n },\n dbPath\n );\n result.graphGenerated = graphResult.success;\n if (!graphResult.success) {\n result.errors.push(...graphResult.stats.errors);\n }\n }\n\n // Update CLAUDE.md\n if (updateClaude) {\n const claudeResult = await _updateClaudeMd({\n projectRoot,\n includeKnowledgeGraph: true,\n includeClaudeFlow: true,\n });\n result.claudeMdUpdated = claudeResult.created || claudeResult.updated;\n }\n\n db.close();\n result.success = result.errors.length === 0;\n\n } catch (error) {\n result.success = false;\n result.errors.push(String(error));\n }\n\n return result;\n}\n"],"names":["_createDatabase","_docsExist","_initDocs","_generateAndSave","_updateClaudeMd"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAu5BA,eAAsB,UAAU,SAW7B;AACD,QAAM;AAAA,IACJ;AAAA,IACA,WAAW;AAAA,IACX,eAAe,WAAW;AAAA,IAC1B,gBAAgB,eAAe;AAAA,EAAA,IAC7B;AAEJ,QAAM,SAAS;AAAA,IACb,SAAS;AAAA,IACT,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,IACjB,QAAQ,CAAA;AAAA,EAAC;AAGX,MAAI;AAEF,UAAM,EAAE,YAAY,WAAW,kBAAkB,MAAM,OAAO,IAAI;AAClE,UAAM,EAAE,KAAA,IAAS,MAAM,OAAO,MAAM;AAGpC,UAAM,QAAQ,KAAK,aAAa,KAAK;AACrC,QAAI,CAAC,WAAW,KAAK,GAAG;AACtB,gBAAU,OAAO,EAAE,WAAW,KAAA,CAAM;AAAA,IACtC;AAGA,UAAM,SAAS,KAAK,OAAO,cAAc;AACzC,UAAM,KAAKA,eAAgB,MAAM;AACjC,OAAG,YAAY,gBAAe,oBAAI,KAAA,GAAO,aAAa;AAGtD,QAAI,CAACC,UAAW,aAAa,QAAQ,GAAG;AACtC,YAAM,aAAa,MAAMC,SAAU;AAAA,QACjC;AAAA,QACA;AAAA,QACA,iBAAiB;AAAA,QACjB,iBAAiB;AAAA,MAAA,CAClB;AACD,aAAO,cAAc,WAAW;AAChC,UAAI,CAAC,WAAW,SAAS;AACvB,eAAO,OAAO,KAAK,GAAG,WAAW,MAAM;AAAA,MACzC;AAAA,IACF;AAGA,QAAI,YAAYD,UAAW,aAAa,QAAQ,GAAG;AACjD,YAAM,cAAc,MAAME;AAAAA,QACxB;AAAA,UACE;AAAA,UACA,YAAY,KAAK,aAAa,QAAQ;AAAA,QAAA;AAAA,QAExC;AAAA,MAAA;AAEF,aAAO,iBAAiB,YAAY;AACpC,UAAI,CAAC,YAAY,SAAS;AACxB,eAAO,OAAO,KAAK,GAAG,YAAY,MAAM,MAAM;AAAA,MAChD;AAAA,IACF;AAGA,QAAI,cAAc;AAChB,YAAM,eAAe,MAAMC,eAAgB;AAAA,QACzC;AAAA,QACA,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,MAAA,CACpB;AACD,aAAO,kBAAkB,aAAa,WAAW,aAAa;AAAA,IAChE;AAEA,OAAG,MAAA;AACH,WAAO,UAAU,OAAO,OAAO,WAAW;AAAA,EAE5C,SAAS,OAAO;AACd,WAAO,UAAU;AACjB,WAAO,OAAO,KAAK,OAAO,KAAK,CAAC;AAAA,EAClC;AAEA,SAAO;AACT;"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { __exports as dist } from "../../../../_virtual/
|
|
1
|
+
import { __exports as dist } from "../../../../_virtual/index8.js";
|
|
2
2
|
import { __require as requireCreateProjectService } from "./createProjectService.js";
|
|
3
3
|
var hasRequiredDist;
|
|
4
4
|
function requireDist() {
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Consensus Builder
|
|
3
|
+
*
|
|
4
|
+
* Builds consensus among multiple agents when confidence is low.
|
|
5
|
+
* Coordinates voting, discussion, and final decision making.
|
|
6
|
+
*
|
|
7
|
+
* @module sparc/consensus
|
|
8
|
+
*/
|
|
9
|
+
import type { ConsensusInfo, ConsensusRequest, ConsensusResult, ConfidenceLevel } from './types.js';
|
|
10
|
+
/**
|
|
11
|
+
* Consensus builder options
|
|
12
|
+
*/
|
|
13
|
+
export interface ConsensusBuilderOptions {
|
|
14
|
+
/** Default threshold for consensus (0-1) */
|
|
15
|
+
defaultThreshold?: number;
|
|
16
|
+
/** Default timeout in ms */
|
|
17
|
+
defaultTimeout?: number;
|
|
18
|
+
/** Consensus method */
|
|
19
|
+
method?: 'majority' | 'unanimous' | 'weighted' | 'expert';
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Agent vote
|
|
23
|
+
*/
|
|
24
|
+
export interface AgentVote {
|
|
25
|
+
/** Agent identifier */
|
|
26
|
+
agent: string;
|
|
27
|
+
/** Selected option ID */
|
|
28
|
+
option: string;
|
|
29
|
+
/** Confidence in vote (0-1) */
|
|
30
|
+
confidence: number;
|
|
31
|
+
/** Reasoning for vote */
|
|
32
|
+
reasoning: string;
|
|
33
|
+
/** Weight (for weighted consensus) */
|
|
34
|
+
weight?: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Consensus option
|
|
38
|
+
*/
|
|
39
|
+
export interface ConsensusOption {
|
|
40
|
+
/** Option ID */
|
|
41
|
+
id: string;
|
|
42
|
+
/** Option description */
|
|
43
|
+
description: string;
|
|
44
|
+
/** Pros */
|
|
45
|
+
pros: string[];
|
|
46
|
+
/** Cons */
|
|
47
|
+
cons: string[];
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Consensus session state
|
|
51
|
+
*/
|
|
52
|
+
interface ConsensusSession {
|
|
53
|
+
/** Session ID */
|
|
54
|
+
id: string;
|
|
55
|
+
/** Topic */
|
|
56
|
+
topic: string;
|
|
57
|
+
/** Options */
|
|
58
|
+
options: ConsensusOption[];
|
|
59
|
+
/** Votes collected */
|
|
60
|
+
votes: AgentVote[];
|
|
61
|
+
/** Participants expected */
|
|
62
|
+
participants: string[];
|
|
63
|
+
/** Threshold required */
|
|
64
|
+
threshold: number;
|
|
65
|
+
/** Method */
|
|
66
|
+
method: 'majority' | 'unanimous' | 'weighted' | 'expert';
|
|
67
|
+
/** Status */
|
|
68
|
+
status: 'pending' | 'voting' | 'completed' | 'failed';
|
|
69
|
+
/** Start time */
|
|
70
|
+
startedAt: Date;
|
|
71
|
+
/** Timeout */
|
|
72
|
+
timeout: number;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Consensus Builder
|
|
76
|
+
*
|
|
77
|
+
* Coordinates multi-agent consensus building for important decisions.
|
|
78
|
+
*/
|
|
79
|
+
export declare class ConsensusBuilder {
|
|
80
|
+
private readonly options;
|
|
81
|
+
private sessions;
|
|
82
|
+
constructor(options?: ConsensusBuilderOptions);
|
|
83
|
+
/**
|
|
84
|
+
* Create a new consensus session
|
|
85
|
+
*/
|
|
86
|
+
createSession(request: ConsensusRequest): string;
|
|
87
|
+
/**
|
|
88
|
+
* Submit a vote for a consensus session
|
|
89
|
+
*/
|
|
90
|
+
submitVote(sessionId: string, vote: AgentVote): boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Calculate consensus result
|
|
93
|
+
*/
|
|
94
|
+
calculateResult(sessionId: string): ConsensusResult;
|
|
95
|
+
/**
|
|
96
|
+
* Evaluate consensus based on method
|
|
97
|
+
*/
|
|
98
|
+
private evaluateConsensus;
|
|
99
|
+
/**
|
|
100
|
+
* Evaluate unanimous consensus
|
|
101
|
+
*/
|
|
102
|
+
private evaluateUnanimous;
|
|
103
|
+
/**
|
|
104
|
+
* Evaluate majority consensus
|
|
105
|
+
*/
|
|
106
|
+
private evaluateMajority;
|
|
107
|
+
/**
|
|
108
|
+
* Evaluate weighted consensus
|
|
109
|
+
*/
|
|
110
|
+
private evaluateWeighted;
|
|
111
|
+
/**
|
|
112
|
+
* Evaluate expert consensus (highest confidence vote wins)
|
|
113
|
+
*/
|
|
114
|
+
private evaluateExpert;
|
|
115
|
+
/**
|
|
116
|
+
* Get leading option from vote counts
|
|
117
|
+
*/
|
|
118
|
+
private getLeadingOption;
|
|
119
|
+
/**
|
|
120
|
+
* Check if session has timed out
|
|
121
|
+
*/
|
|
122
|
+
isSessionTimedOut(sessionId: string): boolean;
|
|
123
|
+
/**
|
|
124
|
+
* Get session status
|
|
125
|
+
*/
|
|
126
|
+
getSessionStatus(sessionId: string): ConsensusSession | undefined;
|
|
127
|
+
/**
|
|
128
|
+
* Check if all participants have voted
|
|
129
|
+
*/
|
|
130
|
+
allParticipantsVoted(sessionId: string): boolean;
|
|
131
|
+
/**
|
|
132
|
+
* Convert result to ConsensusInfo for decision log
|
|
133
|
+
*/
|
|
134
|
+
toConsensusInfo(sessionId: string, result: ConsensusResult, required?: boolean): ConsensusInfo;
|
|
135
|
+
/**
|
|
136
|
+
* Determine if consensus is needed based on confidence
|
|
137
|
+
*/
|
|
138
|
+
static needsConsensus(confidence: ConfidenceLevel): boolean;
|
|
139
|
+
/**
|
|
140
|
+
* Get recommended threshold based on confidence
|
|
141
|
+
*/
|
|
142
|
+
static getRecommendedThreshold(confidence: ConfidenceLevel): number;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Create a consensus builder
|
|
146
|
+
*/
|
|
147
|
+
export declare function createConsensusBuilder(options?: ConsensusBuilderOptions): ConsensusBuilder;
|
|
148
|
+
export {};
|
|
149
|
+
//# sourceMappingURL=consensus.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consensus.d.ts","sourceRoot":"","sources":["../../src/sparc/consensus.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,KAAK,EACV,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,eAAe,EAChB,MAAM,YAAY,CAAC;AAIpB;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,4CAA4C;IAC5C,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,4BAA4B;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,uBAAuB;IACvB,MAAM,CAAC,EAAE,UAAU,GAAG,WAAW,GAAG,UAAU,GAAG,QAAQ,CAAC;CAC3D;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,uBAAuB;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,yBAAyB;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,+BAA+B;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,yBAAyB;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,sCAAsC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,gBAAgB;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,yBAAyB;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW;IACX,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,WAAW;IACX,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB;AAED;;GAEG;AACH,UAAU,gBAAgB;IACxB,iBAAiB;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,YAAY;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,cAAc;IACd,OAAO,EAAE,eAAe,EAAE,CAAC;IAC3B,sBAAsB;IACtB,KAAK,EAAE,SAAS,EAAE,CAAC;IACnB,4BAA4B;IAC5B,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,yBAAyB;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa;IACb,MAAM,EAAE,UAAU,GAAG,WAAW,GAAG,UAAU,GAAG,QAAQ,CAAC;IACzD,aAAa;IACb,MAAM,EAAE,SAAS,GAAG,QAAQ,GAAG,WAAW,GAAG,QAAQ,CAAC;IACtD,iBAAiB;IACjB,SAAS,EAAE,IAAI,CAAC;IAChB,cAAc;IACd,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoC;IAC5D,OAAO,CAAC,QAAQ,CAA4C;gBAEhD,OAAO,GAAE,uBAA4B;IASjD;;OAEG;IACH,aAAa,CAAC,OAAO,EAAE,gBAAgB,GAAG,MAAM;IA4BhD;;OAEG;IACH,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,GAAG,OAAO;IA4CvD;;OAEG;IACH,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,eAAe;IAoBnD;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAgDzB;;OAEG;IACH,OAAO,CAAC,iBAAiB;IA4CzB;;OAEG;IACH,OAAO,CAAC,gBAAgB;IA4CxB;;OAEG;IACH,OAAO,CAAC,gBAAgB;IA4CxB;;OAEG;IACH,OAAO,CAAC,cAAc;IAgCtB;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAcxB;;OAEG;IACH,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO;IAQ7C;;OAEG;IACH,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS;IAIjE;;OAEG;IACH,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO;IAOhD;;OAEG;IACH,eAAe,CACb,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,eAAe,EACvB,QAAQ,GAAE,OAAc,GACvB,aAAa;IAoBhB;;OAEG;IACH,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO;IAI3D;;OAEG;IACH,MAAM,CAAC,uBAAuB,CAAC,UAAU,EAAE,eAAe,GAAG,MAAM;CAcpE;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,CAAC,EAAE,uBAAuB,GAAG,gBAAgB,CAE1F"}
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import { createLogger } from "../utils/logger.js";
|
|
2
|
+
const logger = createLogger("consensus");
|
|
3
|
+
class ConsensusBuilder {
|
|
4
|
+
options;
|
|
5
|
+
sessions = /* @__PURE__ */ new Map();
|
|
6
|
+
constructor(options = {}) {
|
|
7
|
+
this.options = {
|
|
8
|
+
defaultThreshold: 0.67,
|
|
9
|
+
defaultTimeout: 6e4,
|
|
10
|
+
method: "majority",
|
|
11
|
+
...options
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Create a new consensus session
|
|
16
|
+
*/
|
|
17
|
+
createSession(request) {
|
|
18
|
+
const sessionId = `consensus_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
19
|
+
const session = {
|
|
20
|
+
id: sessionId,
|
|
21
|
+
topic: request.topic,
|
|
22
|
+
options: request.options,
|
|
23
|
+
votes: [],
|
|
24
|
+
participants: request.participants,
|
|
25
|
+
threshold: request.threshold || this.options.defaultThreshold,
|
|
26
|
+
method: this.options.method,
|
|
27
|
+
status: "pending",
|
|
28
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
29
|
+
timeout: request.timeout || this.options.defaultTimeout
|
|
30
|
+
};
|
|
31
|
+
this.sessions.set(sessionId, session);
|
|
32
|
+
logger.info("Created consensus session", {
|
|
33
|
+
sessionId,
|
|
34
|
+
topic: request.topic,
|
|
35
|
+
participants: request.participants.length,
|
|
36
|
+
threshold: session.threshold
|
|
37
|
+
});
|
|
38
|
+
return sessionId;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Submit a vote for a consensus session
|
|
42
|
+
*/
|
|
43
|
+
submitVote(sessionId, vote) {
|
|
44
|
+
const session = this.sessions.get(sessionId);
|
|
45
|
+
if (!session) {
|
|
46
|
+
logger.warn("Consensus session not found", { sessionId });
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
if (session.status === "completed" || session.status === "failed") {
|
|
50
|
+
logger.warn("Cannot vote on completed session", { sessionId, status: session.status });
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
if (!session.participants.includes(vote.agent)) {
|
|
54
|
+
logger.warn("Agent not a participant", { sessionId, agent: vote.agent });
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
const existingVote = session.votes.find((v) => v.agent === vote.agent);
|
|
58
|
+
if (existingVote) {
|
|
59
|
+
logger.warn("Agent already voted", { sessionId, agent: vote.agent });
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
if (!session.options.find((o) => o.id === vote.option)) {
|
|
63
|
+
logger.warn("Invalid option", { sessionId, option: vote.option });
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
session.votes.push(vote);
|
|
67
|
+
session.status = "voting";
|
|
68
|
+
logger.info("Vote submitted", {
|
|
69
|
+
sessionId,
|
|
70
|
+
agent: vote.agent,
|
|
71
|
+
option: vote.option,
|
|
72
|
+
confidence: vote.confidence
|
|
73
|
+
});
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Calculate consensus result
|
|
78
|
+
*/
|
|
79
|
+
calculateResult(sessionId) {
|
|
80
|
+
const session = this.sessions.get(sessionId);
|
|
81
|
+
if (!session) {
|
|
82
|
+
throw new Error(`Consensus session not found: ${sessionId}`);
|
|
83
|
+
}
|
|
84
|
+
const result = this.evaluateConsensus(session);
|
|
85
|
+
session.status = result.achieved ? "completed" : "failed";
|
|
86
|
+
logger.info("Consensus calculated", {
|
|
87
|
+
sessionId,
|
|
88
|
+
achieved: result.achieved,
|
|
89
|
+
selectedOption: result.selectedOption
|
|
90
|
+
});
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Evaluate consensus based on method
|
|
95
|
+
*/
|
|
96
|
+
evaluateConsensus(session) {
|
|
97
|
+
const { votes, options, threshold, method } = session;
|
|
98
|
+
if (votes.length === 0) {
|
|
99
|
+
return {
|
|
100
|
+
achieved: false,
|
|
101
|
+
votes: [],
|
|
102
|
+
rationale: "No votes received"
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const voteCounts = /* @__PURE__ */ new Map();
|
|
106
|
+
const weightedCounts = /* @__PURE__ */ new Map();
|
|
107
|
+
for (const option of options) {
|
|
108
|
+
voteCounts.set(option.id, 0);
|
|
109
|
+
weightedCounts.set(option.id, 0);
|
|
110
|
+
}
|
|
111
|
+
for (const vote of votes) {
|
|
112
|
+
voteCounts.set(vote.option, (voteCounts.get(vote.option) || 0) + 1);
|
|
113
|
+
const weight = vote.weight || vote.confidence;
|
|
114
|
+
weightedCounts.set(vote.option, (weightedCounts.get(vote.option) || 0) + weight);
|
|
115
|
+
}
|
|
116
|
+
let result;
|
|
117
|
+
switch (method) {
|
|
118
|
+
case "unanimous":
|
|
119
|
+
result = this.evaluateUnanimous(votes, options, voteCounts);
|
|
120
|
+
break;
|
|
121
|
+
case "weighted":
|
|
122
|
+
result = this.evaluateWeighted(votes, options, weightedCounts, threshold);
|
|
123
|
+
break;
|
|
124
|
+
case "expert":
|
|
125
|
+
result = this.evaluateExpert(votes, options);
|
|
126
|
+
break;
|
|
127
|
+
case "majority":
|
|
128
|
+
default:
|
|
129
|
+
result = this.evaluateMajority(votes, options, voteCounts, threshold);
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
return result;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Evaluate unanimous consensus
|
|
136
|
+
*/
|
|
137
|
+
evaluateUnanimous(votes, options, voteCounts) {
|
|
138
|
+
const totalVotes = votes.length;
|
|
139
|
+
for (const [optionId, count] of voteCounts.entries()) {
|
|
140
|
+
if (count === totalVotes) {
|
|
141
|
+
const option = options.find((o) => o.id === optionId);
|
|
142
|
+
return {
|
|
143
|
+
achieved: true,
|
|
144
|
+
selectedOption: optionId,
|
|
145
|
+
votes: votes.map((v) => ({
|
|
146
|
+
agent: v.agent,
|
|
147
|
+
option: v.option,
|
|
148
|
+
confidence: v.confidence,
|
|
149
|
+
reasoning: v.reasoning
|
|
150
|
+
})),
|
|
151
|
+
rationale: `Unanimous consensus achieved for "${option?.description}"`
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const mainOption = this.getLeadingOption(voteCounts);
|
|
156
|
+
const dissent = votes.filter((v) => v.option !== mainOption).map((v) => `${v.agent}: ${v.reasoning}`);
|
|
157
|
+
return {
|
|
158
|
+
achieved: false,
|
|
159
|
+
votes: votes.map((v) => ({
|
|
160
|
+
agent: v.agent,
|
|
161
|
+
option: v.option,
|
|
162
|
+
confidence: v.confidence,
|
|
163
|
+
reasoning: v.reasoning
|
|
164
|
+
})),
|
|
165
|
+
rationale: "Unanimous consensus not achieved",
|
|
166
|
+
dissent
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Evaluate majority consensus
|
|
171
|
+
*/
|
|
172
|
+
evaluateMajority(votes, options, voteCounts, threshold) {
|
|
173
|
+
const totalVotes = votes.length;
|
|
174
|
+
for (const [optionId, count] of voteCounts.entries()) {
|
|
175
|
+
const percentage = count / totalVotes;
|
|
176
|
+
if (percentage >= threshold) {
|
|
177
|
+
const option = options.find((o) => o.id === optionId);
|
|
178
|
+
const dissent = votes.filter((v) => v.option !== optionId).map((v) => `${v.agent}: ${v.reasoning}`);
|
|
179
|
+
return {
|
|
180
|
+
achieved: true,
|
|
181
|
+
selectedOption: optionId,
|
|
182
|
+
votes: votes.map((v) => ({
|
|
183
|
+
agent: v.agent,
|
|
184
|
+
option: v.option,
|
|
185
|
+
confidence: v.confidence,
|
|
186
|
+
reasoning: v.reasoning
|
|
187
|
+
})),
|
|
188
|
+
rationale: `Majority consensus (${(percentage * 100).toFixed(1)}%) achieved for "${option?.description}"`,
|
|
189
|
+
dissent: dissent.length > 0 ? dissent : void 0
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
achieved: false,
|
|
195
|
+
votes: votes.map((v) => ({
|
|
196
|
+
agent: v.agent,
|
|
197
|
+
option: v.option,
|
|
198
|
+
confidence: v.confidence,
|
|
199
|
+
reasoning: v.reasoning
|
|
200
|
+
})),
|
|
201
|
+
rationale: `No option reached threshold of ${(threshold * 100).toFixed(1)}%`
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Evaluate weighted consensus
|
|
206
|
+
*/
|
|
207
|
+
evaluateWeighted(votes, options, weightedCounts, threshold) {
|
|
208
|
+
const totalWeight = Array.from(weightedCounts.values()).reduce((a, b) => a + b, 0);
|
|
209
|
+
for (const [optionId, weight] of weightedCounts.entries()) {
|
|
210
|
+
const percentage = weight / totalWeight;
|
|
211
|
+
if (percentage >= threshold) {
|
|
212
|
+
const option = options.find((o) => o.id === optionId);
|
|
213
|
+
const dissent = votes.filter((v) => v.option !== optionId).map((v) => `${v.agent}: ${v.reasoning}`);
|
|
214
|
+
return {
|
|
215
|
+
achieved: true,
|
|
216
|
+
selectedOption: optionId,
|
|
217
|
+
votes: votes.map((v) => ({
|
|
218
|
+
agent: v.agent,
|
|
219
|
+
option: v.option,
|
|
220
|
+
confidence: v.confidence,
|
|
221
|
+
reasoning: v.reasoning
|
|
222
|
+
})),
|
|
223
|
+
rationale: `Weighted consensus (${(percentage * 100).toFixed(1)}%) achieved for "${option?.description}"`,
|
|
224
|
+
dissent: dissent.length > 0 ? dissent : void 0
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
achieved: false,
|
|
230
|
+
votes: votes.map((v) => ({
|
|
231
|
+
agent: v.agent,
|
|
232
|
+
option: v.option,
|
|
233
|
+
confidence: v.confidence,
|
|
234
|
+
reasoning: v.reasoning
|
|
235
|
+
})),
|
|
236
|
+
rationale: `No option reached weighted threshold of ${(threshold * 100).toFixed(1)}%`
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Evaluate expert consensus (highest confidence vote wins)
|
|
241
|
+
*/
|
|
242
|
+
evaluateExpert(votes, options) {
|
|
243
|
+
const sortedVotes = [...votes].sort((a, b) => {
|
|
244
|
+
const aScore = a.confidence * (a.weight || 1);
|
|
245
|
+
const bScore = b.confidence * (b.weight || 1);
|
|
246
|
+
return bScore - aScore;
|
|
247
|
+
});
|
|
248
|
+
const topVote = sortedVotes[0];
|
|
249
|
+
const option = options.find((o) => o.id === topVote.option);
|
|
250
|
+
const dissent = votes.filter((v) => v.option !== topVote.option).map((v) => `${v.agent}: ${v.reasoning}`);
|
|
251
|
+
return {
|
|
252
|
+
achieved: true,
|
|
253
|
+
selectedOption: topVote.option,
|
|
254
|
+
votes: votes.map((v) => ({
|
|
255
|
+
agent: v.agent,
|
|
256
|
+
option: v.option,
|
|
257
|
+
confidence: v.confidence,
|
|
258
|
+
reasoning: v.reasoning
|
|
259
|
+
})),
|
|
260
|
+
rationale: `Expert consensus: ${topVote.agent} (confidence: ${topVote.confidence}) selected "${option?.description}"`,
|
|
261
|
+
dissent: dissent.length > 0 ? dissent : void 0
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Get leading option from vote counts
|
|
266
|
+
*/
|
|
267
|
+
getLeadingOption(voteCounts) {
|
|
268
|
+
let maxCount = 0;
|
|
269
|
+
let leadingOption = "";
|
|
270
|
+
for (const [optionId, count] of voteCounts.entries()) {
|
|
271
|
+
if (count > maxCount) {
|
|
272
|
+
maxCount = count;
|
|
273
|
+
leadingOption = optionId;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return leadingOption;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Check if session has timed out
|
|
280
|
+
*/
|
|
281
|
+
isSessionTimedOut(sessionId) {
|
|
282
|
+
const session = this.sessions.get(sessionId);
|
|
283
|
+
if (!session) return true;
|
|
284
|
+
const elapsed = Date.now() - session.startedAt.getTime();
|
|
285
|
+
return elapsed > session.timeout;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Get session status
|
|
289
|
+
*/
|
|
290
|
+
getSessionStatus(sessionId) {
|
|
291
|
+
return this.sessions.get(sessionId);
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Check if all participants have voted
|
|
295
|
+
*/
|
|
296
|
+
allParticipantsVoted(sessionId) {
|
|
297
|
+
const session = this.sessions.get(sessionId);
|
|
298
|
+
if (!session) return false;
|
|
299
|
+
return session.votes.length >= session.participants.length;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Convert result to ConsensusInfo for decision log
|
|
303
|
+
*/
|
|
304
|
+
toConsensusInfo(sessionId, result, required = true) {
|
|
305
|
+
const session = this.sessions.get(sessionId);
|
|
306
|
+
if (!session) {
|
|
307
|
+
throw new Error(`Session not found: ${sessionId}`);
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
required,
|
|
311
|
+
achieved: result.achieved,
|
|
312
|
+
participants: session.participants,
|
|
313
|
+
votes: result.votes.map((v) => ({
|
|
314
|
+
agent: v.agent,
|
|
315
|
+
vote: v.option === result.selectedOption ? "agree" : "disagree",
|
|
316
|
+
reason: v.reasoning
|
|
317
|
+
})),
|
|
318
|
+
method: session.method,
|
|
319
|
+
outcome: result.rationale
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Determine if consensus is needed based on confidence
|
|
324
|
+
*/
|
|
325
|
+
static needsConsensus(confidence) {
|
|
326
|
+
return confidence === "low" || confidence === "uncertain";
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Get recommended threshold based on confidence
|
|
330
|
+
*/
|
|
331
|
+
static getRecommendedThreshold(confidence) {
|
|
332
|
+
switch (confidence) {
|
|
333
|
+
case "uncertain":
|
|
334
|
+
return 0.8;
|
|
335
|
+
// Need strong agreement for uncertain decisions
|
|
336
|
+
case "low":
|
|
337
|
+
return 0.67;
|
|
338
|
+
// Standard majority
|
|
339
|
+
case "medium":
|
|
340
|
+
return 0.6;
|
|
341
|
+
case "high":
|
|
342
|
+
return 0.5;
|
|
343
|
+
// Simple majority OK for high confidence
|
|
344
|
+
default:
|
|
345
|
+
return 0.67;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function createConsensusBuilder(options) {
|
|
350
|
+
return new ConsensusBuilder(options);
|
|
351
|
+
}
|
|
352
|
+
export {
|
|
353
|
+
ConsensusBuilder,
|
|
354
|
+
createConsensusBuilder
|
|
355
|
+
};
|
|
356
|
+
//# sourceMappingURL=consensus.js.map
|