@weavelogic/knowledge-graph-agent
v0.9.0
Published
Knowledge graph agent for Claude Code - generates knowledge graphs, initializes docs, and integrates with claude-flow
Maintainers
Readme
@weavelogic/knowledge-graph-agent
A powerful NPM library for creating and managing knowledge graphs for Claude Code. Integrates with Obsidian-style documentation, claude-flow for AI coordination, and provides enterprise-grade features for production deployments.
Features
| Category | Features | |----------|----------| | Core | Knowledge graph generation, Obsidian integration, CLAUDE.md management | | Cultivation | Codebase analysis, seed generation, deep analysis with claude-flow | | Agents | Multi-agent system, rules engine, workflows, MCP server with 30+ tools | | Services | Service management, config migrations, health monitoring | | Enterprise | Chunking, backup/recovery, advanced caching, diagnostics | | Integrations | Workflow DevKit, RuVector semantic search, Exochain audit trail | | API & UI | Plugin system, GraphQL API, Web dashboard, concurrent servers |
Installation
npm install @weavelogic/knowledge-graph-agentOr use directly with npx:
npx @weavelogic/knowledge-graph-agent initQuick Start
# Initialize knowledge graph in project
kg init
# Bootstrap primitives from codebase analysis
kg init-primitives
# Generate knowledge graph
kg graph
# Start all servers (MCP, GraphQL, Dashboard)
kg serve --allCultivation System
SeedGenerator
Analyzes codebases to bootstrap knowledge graphs with primitive nodes.
Supported Ecosystems:
- Node.js:
package.jsondependencies - Python:
requirements.txt,pyproject.toml - PHP:
composer.json - Rust:
Cargo.toml - Go:
go.mod - Java:
pom.xml,build.gradle
import { SeedGenerator, analyzeSeed, initPrimitives } from '@weavelogic/knowledge-graph-agent';
// Full analysis
const analysis = await analyzeSeed('/project', 'docs');
console.log(`Found ${analysis.frameworks.length} frameworks`);
console.log(`Found ${analysis.dependencies.length} dependencies`);
console.log(`Found ${analysis.services.length} services`);
// Generate primitive nodes
const result = await initPrimitives('/project', 'docs', { dryRun: false });
console.log(`Generated ${result.documentsGenerated.length} documents`);DeepAnalyzer with claude-flow Integration
Advanced codebase analysis using multi-agent orchestration.
# Deep analysis with claude-flow agents
kg analyze deep
# Generate analysis report
kg analyze report --jsonShadow Cache for File Tracking
Tracks file changes efficiently using SHA-256 hashing.
import { ShadowCache } from '@weavelogic/knowledge-graph-agent';
const cache = new ShadowCache('/project/.kg');
const changed = await cache.getChangedFiles('/project/docs');
console.log(`${changed.length} files changed since last sync`);Agent System
A comprehensive agent framework with specialized agents for different tasks.
Agent Types:
ResearcherAgent- Research and information gatheringCoderAgent- Code generation and modificationTesterAgent- Test creation and validationAnalystAgent- Analysis and recommendationsArchitectAgent- System design and architecture
import {
BaseAgent,
getRegistry,
AgentType,
createTask
} from '@weavelogic/knowledge-graph-agent';
// Get the agent registry
const registry = getRegistry();
// Spawn a researcher agent
const agent = await registry.spawn(AgentType.RESEARCHER, {
name: 'docs-researcher',
claudeFlow: { enabled: true, namespace: 'kg' },
});
// Execute a task
const task = createTask('Research authentication patterns', {
priority: TaskPriority.HIGH,
input: { topic: 'OAuth2' },
});
const result = await agent.execute(task);
console.log(result.data);RulesEngine for Automation
import { RulesEngine, RuleType, TriggerType } from '@weavelogic/knowledge-graph-agent';
const engine = new RulesEngine();
engine.registerRule({
id: 'auto-tag',
name: 'Auto-tag documentation',
type: RuleType.TRANSFORM,
trigger: { type: TriggerType.FILE_CHANGE, pattern: 'docs/**/*.md' },
condition: (context) => context.file.endsWith('.md'),
action: async (context) => { /* auto-tag logic */ },
});
engine.start();Workflow Registry
import { WorkflowRegistry } from '@weavelogic/knowledge-graph-agent';
const registry = new WorkflowRegistry();
registry.register({
id: 'documentation-sync',
name: 'Documentation Sync',
steps: [
{ id: 'analyze', action: 'analyze-docs' },
{ id: 'generate', action: 'generate-graph', dependsOn: ['analyze'] },
{ id: 'sync', action: 'sync-memory', dependsOn: ['generate'] },
],
});
await registry.execute('documentation-sync', { projectRoot: '/project' });Plugin System
Extensible plugin architecture for custom analyzers with 13 lifecycle hooks.
Built-in Plugins
| Plugin | Description |
|--------|-------------|
| code-complexity | Cyclomatic, cognitive, and Halstead complexity metrics |
| dependency-health | Vulnerability scanning, outdated detection, health scores |
Plugin CLI
# List installed plugins
kg plugin list
# Install a plugin
kg plugin install <source>
# Run an analyzer
kg plugin run code-complexity src/index.ts
# Show plugin details
kg plugin info dependency-health
# Create a plugin from template
kg plugin create my-analyzerCustom Plugin Development
import { AnalyzerPlugin, PluginContext } from '@weavelogic/knowledge-graph-agent';
export class MyAnalyzerPlugin implements AnalyzerPlugin {
name = 'my-analyzer';
version = '1.0.0';
supportedContentTypes = ['text/typescript', 'text/javascript'];
async analyze(input: AnalysisInput): Promise<AnalysisResult> {
// Analysis logic
return {
success: true,
analysisType: 'my-analyzer',
entities: [...],
relationships: [...],
tags: [...],
};
}
// Streaming support
async *analyzeStream(input: AnalysisInput): AsyncIterable<AnalysisStreamChunk> {
yield { type: 'progress', progress: 50 };
yield { type: 'entity', data: { id: '...', type: '...' } };
yield { type: 'complete', data: { message: 'Done' } };
}
}GraphQL API
Full-featured GraphQL API with real-time subscriptions.
Start GraphQL Server
# Start GraphQL server on port 4000
kg serve --graphql
# Custom port
kg serve --graphql --port-graphql 8080Query Examples
# Get all nodes
query {
nodes(filter: { type: CONCEPT }, pagination: { first: 10 }) {
edges {
node {
id
title
type
tags
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
# Search nodes
query {
searchNodes(query: "authentication", options: { limit: 5 }) {
id
title
score
snippet
}
}
# Get graph structure
query {
graph {
nodes { id title type }
edges { source target type }
stats { nodeCount edgeCount }
}
}Subscriptions
# Real-time node updates
subscription {
nodeCreated {
id
title
createdAt
}
}
subscription {
analysisProgress(analysisId: "abc123") {
progress
phase
message
}
}Custom Scalars
DateTime- ISO 8601 timestampsJSON- Arbitrary JSON dataUUID- RFC 4122 UUIDsFilePath- Validated file paths
Web Dashboard
Interactive visualization dashboard built with Next.js 14.
Start Dashboard
# Start dashboard on port 3000
kg serve --dashboard
# Development mode with hot reload
kg dashboard start
# Build for production
kg dashboard build
# Serve production build
kg dashboard serveFeatures
- Graph Visualization: Interactive cytoscape.js graph with zoom, pan, and node selection
- Data Tables: Sortable, filterable tables with TanStack Table
- Search: Full-text and semantic search with filters
- Real-time Updates: WebSocket subscriptions for live data
- Agent Monitoring: View agent status and execution history
- Workflow Tracking: Monitor workflow progress and results
Dashboard CLI
kg dashboard start # Start dev server
kg dashboard start --port 8080 # Custom port
kg dashboard start --open # Open in browser
kg dashboard build # Production build
kg dashboard serve # Serve production
kg dashboard status # Check status
kg dashboard open # Open in browserConcurrent Server Execution
Run multiple servers simultaneously with the serve command.
# Start all servers
kg serve --all
# Start specific servers
kg serve --mcp --graphql
kg serve --graphql --dashboard
# Custom ports
kg serve --all --port-graphql 4001 --port-dashboard 3001
# With custom database
kg serve --all --db ./data/knowledge.dbServer Options
| Flag | Description | Default |
|------|-------------|---------|
| --mcp | Enable MCP server (stdio) | Enabled by default |
| --graphql | Enable GraphQL server | Port 4000 |
| --dashboard | Enable web dashboard | Port 3000 |
| --all | Enable all servers | - |
| --port-graphql <port> | GraphQL port | 4000 |
| --port-dashboard <port> | Dashboard port | 3000 |
| --db <path> | Database path | .kg/knowledge.db |
MCP Server
Model Context Protocol server for Claude integration with 30+ tools.
# Start MCP server
kg serve --mcp
# Or via npx
npx @weavelogic/knowledge-graph-agent mcp startAvailable MCP Tools:
| Category | Tools |
|----------|-------|
| Graph | kg_query, kg_stats, kg_get_node, kg_list_tags |
| Cache | kg_cache_stats |
| Agents | kg_agent_spawn, kg_agent_list |
| System | kg_health, kg_health_check |
| Search | kg_search_nodes, kg_search_tags |
| Workflow | kg_workflow_start, kg_workflow_status, kg_workflow_list |
| Vector | kg_vector_search, kg_vector_upsert |
| Trajectory | kg_trajectory_list |
| Audit | kg_audit_query, kg_audit_checkpoint |
Enterprise Features
Chunker for Large Documents
import { createChunker, chunkDocument } from '@weavelogic/knowledge-graph-agent';
const result = chunkDocument(largeMarkdownContent, {
strategy: 'adaptive', // fixed, semantic, markdown, code, adaptive
maxSize: 2000,
overlap: 50,
});
console.log(`Split into ${result.chunks.length} chunks`);BackupManager
import { createBackupManager } from '@weavelogic/knowledge-graph-agent';
const backup = createBackupManager('/project/.kg/knowledge.db', {
enabled: true,
interval: 86400000, // 24 hours
maxBackups: 5,
compress: true,
});
await backup.createBackup();
backup.startAutoBackup();AdvancedCache
import { createAdvancedCache } from '@weavelogic/knowledge-graph-agent';
const cache = createAdvancedCache<User>({
maxSize: 50 * 1024 * 1024,
maxEntries: 1000,
defaultTTL: 300000,
evictionPolicy: 'lru', // lru, lfu, fifo, ttl
});
cache.set('user:123', userData, { tags: ['user'] });
const user = cache.get<User>('user:123');HealthMonitor
import { createHealthMonitor, createMemoryCheck } from '@weavelogic/knowledge-graph-agent';
const monitor = createHealthMonitor({ checkInterval: 30000 });
monitor.registerCheck(createMemoryCheck(85));
monitor.on('alert', (alert) => console.error(alert));
monitor.start();External Integrations
RuVector Semantic Search
import { VectorStore, TrajectoryTracker } from '@weavelogic/knowledge-graph-agent';
const vectors = new VectorStore({
dimensions: 1536,
metric: 'cosine',
});
await vectors.upsert([
{ id: 'doc-1', values: embedding, metadata: { type: 'concept' } },
]);
const results = await vectors.search(queryEmbedding, { topK: 10 });Exochain Audit Trail
import { AuditTrail } from '@weavelogic/knowledge-graph-agent';
const audit = new AuditTrail({
signingKey: process.env.AGENT_PRIVATE_KEY,
hlcEnabled: true,
});
const checkpoint = await audit.checkpoint({
operation: 'node_created',
nodeId: 'concept-123',
agent: 'coder-agent',
});Workflow DevKit
import { WorkflowManager } from '@weavelogic/knowledge-graph-agent';
const workflow = new WorkflowManager({
postgres: process.env.DATABASE_URL,
durableAgents: true,
});
const execution = await workflow.start('document-analysis', {
input: { path: '/docs' },
resumable: true,
});CLI Commands Reference
Initialization
| Command | Description |
|---------|-------------|
| kg init | Initialize knowledge graph in project |
| kg init-primitives | Bootstrap primitives from codebase |
| kg analyze-codebase | Analyze dependencies and services |
Knowledge Graph
| Command | Description |
|---------|-------------|
| kg graph | Generate/update knowledge graph |
| kg stats | Display graph statistics |
| kg search <query> | Search the knowledge graph |
Servers
| Command | Description |
|---------|-------------|
| kg serve | Start MCP server (default) |
| kg serve --all | Start all servers |
| kg serve --graphql | Start GraphQL server |
| kg serve --dashboard | Start web dashboard |
Plugin Management
| Command | Description |
|---------|-------------|
| kg plugin list | List installed plugins |
| kg plugin install <source> | Install a plugin |
| kg plugin run <name> [file] | Run an analyzer |
| kg plugin info <name> | Show plugin details |
| kg plugin create <name> | Create plugin from template |
Dashboard
| Command | Description |
|---------|-------------|
| kg dashboard start | Start dashboard dev server |
| kg dashboard build | Build for production |
| kg dashboard serve | Serve production build |
| kg dashboard status | Check dashboard status |
Documentation
| Command | Description |
|---------|-------------|
| kg docs init | Initialize docs directory |
| kg analyze | Analyze & migrate to knowledge graph |
| kg convert docs | Convert docs/ to docs-nn/ |
Configuration
| Command | Description |
|---------|-------------|
| kg config show | Show current configuration |
| kg config set <key> <value> | Set configuration value |
Diagnostics
| Command | Description |
|---------|-------------|
| kg diag run | Run full diagnostics |
| kg diag health | Check system health |
| kg diag repair | Repair database issues |
| kg diag backup | Create database backup |
Workflows & Vectors
| Command | Description |
|---------|-------------|
| kg workflow start <name> | Start a workflow |
| kg workflow status <id> | Get workflow status |
| kg vector search <query> | Semantic search |
| kg trajectory list | List trajectories |
| kg audit query | Query audit trail |
Configuration
Create .kg/config.json to customize behavior:
{
"version": "1.0.0",
"projectRoot": ".",
"docsPath": "docs",
"database": {
"path": ".kg/knowledge.db",
"autoBackup": true,
"backupInterval": 86400000,
"maxBackups": 5
},
"cache": {
"enabled": true,
"maxSize": 1000,
"ttl": 3600000,
"evictionPolicy": "lru"
},
"agents": {
"maxConcurrent": 5,
"defaultTimeout": 30000,
"retryAttempts": 3,
"claudeFlowEnabled": true
},
"graphql": {
"port": 4000,
"cors": true,
"playground": true
},
"dashboard": {
"port": 3000
},
"plugins": {
"autoLoad": true,
"searchPaths": ["./plugins", "./node_modules"]
}
}Programmatic Usage
import {
// Core
createKnowledgeGraph,
createDatabase,
quickInit,
// Analysis
analyzeSeed,
initPrimitives,
analyzeDocs,
// Agents
BaseAgent,
getRegistry,
AgentType,
// Services
createServiceManager,
createConfigManager,
createHealthMonitor,
// Enterprise
createChunker,
createBackupManager,
createAdvancedCache,
// Plugins
createPluginManager,
CodeComplexityPlugin,
DependencyHealthPlugin,
// GraphQL
createGraphQLServer,
// Server
createServerManager,
ServiceContainer,
// Integrations
VectorStore,
AuditTrail,
WorkflowManager,
} from '@weavelogic/knowledge-graph-agent';Changelog
v0.7.4
- Fixed repository URL in package.json to match actual GitHub repo name
v0.7.3
- Added SOP Governance documentation (
docs/guides/sop-governance.md) - Added SOP Reference documentation (
docs/reference/sops.md) - Complete documentation for all 40 AI-SDLC SOPs with requirements and checkpoints
- Updated docs README and main README with governance documentation links
v0.7.2
- Fixed repository URL in package.json to correct GitHub repo
- Resolved stale Dependabot security alerts (Next.js not a dependency)
v0.7.1
- Fixed documentation links to use new organized reference structure
- Updated Reference section with proper paths to
docs/reference/api/,docs/reference/cli/,docs/reference/mcp/ - Added Architecture section with integration documentation links
v0.7.0
Core Features:
- Agent Equilibrium Selector - Intelligent agent selection based on task requirements
- Memory & Graph Pruning - Automatic cleanup and optimization of graph data
- Agentic-Flow Integration - Full AgentDB, ReasoningBank, and Federation Hub support
- Trajectory Tracking - Agent behavior learning and pattern optimization
- Agent Booster Integration - Enhanced agent capabilities with performance boosting
- Multi-Model Router - Dynamic model selection based on task complexity
- QUIC Transport - High-performance, low-latency communication protocol
Documentation:
- Documentation overhaul with Diátaxis framework (tutorials, guides, reference, explanation)
- 5 Architecture Decision Records (ADRs) from SPEC files
- Comprehensive API/CLI/MCP reference documentation
- Enterprise guides (chunking, backup, caching, health monitoring)
- Integration architecture docs (claude-flow, ruvector, exochain, agentic-flow)
- Getting started tutorials (installation, quick-start, configuration)
- MIT License added to project root
- Dependencies documentation with licenses
- 68 markdown documentation files
v0.6.0
- Plugin system with custom analyzers (13 lifecycle hooks, async streaming)
- Code Complexity Analyzer plugin (cyclomatic, cognitive, Halstead metrics)
- Dependency Health Analyzer plugin (vulnerability scanning, health scores)
- GraphQL API with graphql-yoga server and WebSocket subscriptions
- Custom GraphQL scalars (DateTime, JSON, UUID, FilePath)
- Web dashboard with Next.js 14, cytoscape.js visualization
- Dashboard CLI commands (start, build, serve, status)
- Concurrent server execution (
kg serve --all) - ServiceContainer singleton for dependency injection
- TypedEventBus for cross-service communication
- Plugin CLI commands (list, install, run, info, create)
v0.5.0
- Workflow DevKit integration with MCP tools
- RuVector semantic search with trajectory tracking
- Exochain audit trail with DAG-BFT consensus
- 9 MCP tools for workflows, vectors, and audit
- 22 CLI subcommands for external integrations
v0.4.0
- Chunker with 5 chunking strategies
- BackupManager with gzip compression
- IntegrityChecker for database validation
- AdvancedCache with LRU/LFU/FIFO/TTL eviction
- Diagnostics CLI commands
v0.3.0
- ServiceManager for background processes
- ConfigManager with migrations
- HealthMonitor with alerts
- DecisionTracker for AI explainability
v0.2.0
- Agent system with specialized agents
- RulesEngine for automation
- WorkflowRegistry for multi-step workflows
- VaultMemorySync for memory synchronization
- Git integration with auto-commit
- MCP Server with 20+ tools
v0.1.0
- SeedGenerator for codebase analysis
- DeepAnalyzer with claude-flow
- Shadow Cache for file tracking
- Initial knowledge graph generation
Documentation
Comprehensive documentation is available in the docs/ directory, organized using the Diátaxis framework:
Getting Started
- Installation Guide - Set up your environment
- Quick Start - Build your first knowledge graph
- Configuration - Configure for your project
Guides
- Knowledge Graph Management - Create, query, and traverse graphs
- Cultivation System - Analyze codebases and generate primitives
- Agent System - Work with AI agents and rules engine
- SOP Governance - AI-SDLC compliance and governance enforcement
Enterprise Features
- Document Chunking - Split large documents efficiently
- Backup & Recovery - Protect your data
- Cache Configuration - Optimize performance
- Health Monitoring - Monitor production systems
Reference
- API Reference - Complete API surface
- Core API - Database, cache, knowledge graph
- Agents API - Agent system interfaces
- Graph API - Graph operations
- CLI Commands - All CLI commands
- MCP Tools - MCP server tools
- SOP Reference - AI-SDLC SOPs technical reference
Architecture
- Architecture Overview - System architecture
- Integration Index - All integrations
- Claude-Flow - MCP orchestration
- RuVector - Vector search
- Exochain - Audit trail
- Agentic-Flow - Agent framework
- ADR Index - Architecture decisions
- Dependencies - Package dependencies and licenses
Contributing
Contributions are welcome! Please read our Contributing Guide.
License
MIT - See LICENSE for details.
