@weavelogic/knowledge-graph-agent 0.10.0 → 0.10.2
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/README.md +166 -2
- package/dist/agents/base-agent.js +3 -3
- package/dist/agents/base-agent.js.map +1 -1
- package/dist/cli/commands/analyze.js +3 -3
- package/dist/cli/commands/analyze.js.map +1 -1
- package/dist/cli/commands/convert.js +1 -1
- package/dist/cli/commands/convert.js.map +1 -1
- package/dist/cli/commands/cultivate.js +8 -3
- package/dist/cli/commands/cultivate.js.map +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/cultivation/deep-analyzer.d.ts +8 -1
- package/dist/cultivation/deep-analyzer.d.ts.map +1 -1
- package/dist/cultivation/deep-analyzer.js +36 -8
- package/dist/cultivation/deep-analyzer.js.map +1 -1
- package/dist/generators/claude-md.js +1 -1
- package/dist/generators/claude-md.js.map +1 -1
- package/dist/generators/doc-cultivator.js +2 -3
- package/dist/generators/doc-cultivator.js.map +1 -1
- package/dist/generators/doc-generator-agents.js +18 -9
- package/dist/generators/doc-generator-agents.js.map +1 -1
- package/dist/generators/docs-analyzer.d.ts +2 -2
- package/dist/generators/docs-analyzer.d.ts.map +1 -1
- package/dist/generators/docs-analyzer.js +1 -1
- package/dist/generators/docs-analyzer.js.map +1 -1
- package/dist/generators/docs-convert.d.ts +1 -1
- package/dist/generators/docs-convert.d.ts.map +1 -1
- package/dist/generators/docs-convert.js +1 -1
- package/dist/generators/docs-convert.js.map +1 -1
- package/dist/integrations/claude-flow.js +4 -4
- package/dist/integrations/claude-flow.js.map +1 -1
- package/dist/mcp/clients/mcp-client-adapter.d.ts +1 -1
- package/dist/mcp/clients/mcp-client-adapter.d.ts.map +1 -1
- package/dist/mcp/clients/mcp-client-adapter.js +1 -1
- package/dist/mcp/clients/mcp-client-adapter.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,8 +10,9 @@ A powerful NPM library for creating and managing knowledge graphs for Claude Cod
|
|
|
10
10
|
| Category | Features |
|
|
11
11
|
|----------|----------|
|
|
12
12
|
| **Core** | Knowledge graph generation, Obsidian integration, CLAUDE.md management |
|
|
13
|
-
| **Cultivation** | Codebase analysis, seed generation, deep analysis with claude-flow |
|
|
13
|
+
| **Cultivation** | Codebase analysis, seed generation, deep analysis with claude-flow, doc cultivation |
|
|
14
14
|
| **Agents** | Multi-agent system, rules engine, workflows, MCP server with 30+ tools |
|
|
15
|
+
| **Claude Hooks** | Capture all interactions, hierarchical storage, sub-agent tracking, swarm tracking |
|
|
15
16
|
| **Services** | Service management, config migrations, health monitoring |
|
|
16
17
|
| **Enterprise** | Chunking, backup/recovery, advanced caching, diagnostics |
|
|
17
18
|
| **Integrations** | Workflow DevKit, RuVector semantic search, Exochain audit trail |
|
|
@@ -431,6 +432,110 @@ npx @weavelogic/knowledge-graph-agent mcp start
|
|
|
431
432
|
|
|
432
433
|
---
|
|
433
434
|
|
|
435
|
+
## Claude Code Hooks
|
|
436
|
+
|
|
437
|
+
Capture all Claude Code interactions and store them in a hierarchical knowledge graph structure.
|
|
438
|
+
|
|
439
|
+
### Installation
|
|
440
|
+
|
|
441
|
+
```bash
|
|
442
|
+
# Install hooks to capture all interactions
|
|
443
|
+
kg hooks install
|
|
444
|
+
|
|
445
|
+
# Check hooks status
|
|
446
|
+
kg hooks status
|
|
447
|
+
|
|
448
|
+
# View captured sessions
|
|
449
|
+
kg hooks sessions
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
### Features
|
|
453
|
+
|
|
454
|
+
- **Hierarchical Storage**: Sessions → Conversations → Messages → Tool Calls
|
|
455
|
+
- **Sub-Agent Tracking**: Automatically tracks Task tool spawns
|
|
456
|
+
- **Swarm Tracking**: Captures claude-flow swarm operations
|
|
457
|
+
- **Markdown Generation**: Creates documentation for all interactions
|
|
458
|
+
- **Tool Output Separation**: Stores tool outputs in dedicated files
|
|
459
|
+
|
|
460
|
+
### Hook Events Captured
|
|
461
|
+
|
|
462
|
+
| Event | Description |
|
|
463
|
+
|-------|-------------|
|
|
464
|
+
| `UserPromptSubmit` | All user prompts |
|
|
465
|
+
| `PreToolUse` | Tool invocations with inputs |
|
|
466
|
+
| `PostToolUse` | Tool results and outputs |
|
|
467
|
+
| `Stop` | Session completion |
|
|
468
|
+
| `PreCompact` | Before context compaction |
|
|
469
|
+
|
|
470
|
+
### Storage Structure
|
|
471
|
+
|
|
472
|
+
```
|
|
473
|
+
.kg/claude/
|
|
474
|
+
├── sessions/ # JSON session data
|
|
475
|
+
├── agents/ # Sub-agent tracking
|
|
476
|
+
├── tool-outputs/ # Separated tool outputs
|
|
477
|
+
├── docs/
|
|
478
|
+
│ ├── sessions/ # Session markdown docs
|
|
479
|
+
│ ├── conversations/ # Conversation logs
|
|
480
|
+
│ └── agents/ # Sub-agent markdown docs
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
### Programmatic Usage
|
|
484
|
+
|
|
485
|
+
```typescript
|
|
486
|
+
import { HookCaptureSystem, generateHookConfig } from '@weavelogic/knowledge-graph-agent';
|
|
487
|
+
|
|
488
|
+
// Create capture system
|
|
489
|
+
const capture = new HookCaptureSystem('/project', {
|
|
490
|
+
createMarkdown: true,
|
|
491
|
+
separateToolOutputs: true,
|
|
492
|
+
captureSubAgents: true,
|
|
493
|
+
captureSwarms: true,
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
// Start a session
|
|
497
|
+
const session = capture.startSession('Development Session', 'Feature implementation');
|
|
498
|
+
|
|
499
|
+
// Handle hook events
|
|
500
|
+
capture.handleHookEvent({
|
|
501
|
+
event: 'UserPromptSubmit',
|
|
502
|
+
timestamp: new Date().toISOString(),
|
|
503
|
+
userPrompt: 'Help me implement...',
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
// End session
|
|
507
|
+
const completedSession = capture.endSession();
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
---
|
|
511
|
+
|
|
512
|
+
## Document Cultivation
|
|
513
|
+
|
|
514
|
+
Automatically build out comprehensive documentation using claude-flow swarm orchestration.
|
|
515
|
+
|
|
516
|
+
### Usage
|
|
517
|
+
|
|
518
|
+
```bash
|
|
519
|
+
# Cultivate documentation with swarm agents
|
|
520
|
+
kg cultivate --path /project
|
|
521
|
+
|
|
522
|
+
# Include SOP compliance analysis
|
|
523
|
+
kg cultivate --include-sops
|
|
524
|
+
|
|
525
|
+
# Dry run to preview
|
|
526
|
+
kg cultivate --dry-run
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
### Features
|
|
530
|
+
|
|
531
|
+
- **7-Phase Cultivation Process**: Structure analysis through completion
|
|
532
|
+
- **Development Planning**: Generates phased development plans
|
|
533
|
+
- **Infrastructure Planning**: Creates dev/staging/production infrastructure plans
|
|
534
|
+
- **SOP Compliance**: Integrates AI-SDLC SOP analysis
|
|
535
|
+
- **Swarm Orchestration**: Uses claude-flow for parallel documentation generation
|
|
536
|
+
|
|
537
|
+
---
|
|
538
|
+
|
|
434
539
|
## Enterprise Features
|
|
435
540
|
|
|
436
541
|
### Chunker for Large Documents
|
|
@@ -592,13 +697,25 @@ const execution = await workflow.start('document-analysis', {
|
|
|
592
697
|
| `kg dashboard serve` | Serve production build |
|
|
593
698
|
| `kg dashboard status` | Check dashboard status |
|
|
594
699
|
|
|
595
|
-
### Documentation
|
|
700
|
+
### Documentation & Cultivation
|
|
596
701
|
|
|
597
702
|
| Command | Description |
|
|
598
703
|
|---------|-------------|
|
|
599
704
|
| `kg docs init` | Initialize docs directory |
|
|
600
705
|
| `kg analyze` | Analyze & migrate to knowledge graph |
|
|
601
706
|
| `kg convert docs` | Convert docs/ to docs-nn/ |
|
|
707
|
+
| `kg cultivate` | Cultivate docs using swarm orchestration |
|
|
708
|
+
| `kg cultivate --include-sops` | Include SOP compliance analysis |
|
|
709
|
+
|
|
710
|
+
### Claude Code Hooks
|
|
711
|
+
|
|
712
|
+
| Command | Description |
|
|
713
|
+
|---------|-------------|
|
|
714
|
+
| `kg hooks install` | Install hooks to capture interactions |
|
|
715
|
+
| `kg hooks uninstall` | Remove hooks configuration |
|
|
716
|
+
| `kg hooks status` | Show hooks status |
|
|
717
|
+
| `kg hooks sessions` | List captured sessions |
|
|
718
|
+
| `kg hooks export` | Export captured sessions |
|
|
602
719
|
|
|
603
720
|
### Configuration
|
|
604
721
|
|
|
@@ -724,6 +841,53 @@ import {
|
|
|
724
841
|
|
|
725
842
|
## Changelog
|
|
726
843
|
|
|
844
|
+
### v0.10.1
|
|
845
|
+
|
|
846
|
+
**Default Directory Fix:**
|
|
847
|
+
- Changed default target directory from `docs-nn` to `docs`
|
|
848
|
+
- `kg analyze`, `kg convert docs`, and related commands now output to `docs/` by default
|
|
849
|
+
- Use `--target docs-nn` if you specifically need the old behavior
|
|
850
|
+
- Updated help text and documentation to reflect the change
|
|
851
|
+
|
|
852
|
+
### v0.10.0
|
|
853
|
+
|
|
854
|
+
**Claude Code Hooks System:**
|
|
855
|
+
- **Hook Capture System** - Capture all Claude interactions (prompts, responses, tool calls)
|
|
856
|
+
- **Hierarchical Storage** - Sessions → Conversations → Messages → Tool Calls
|
|
857
|
+
- **Sub-Agent Tracking** - Automatically tracks Task tool spawns with full context
|
|
858
|
+
- **Swarm Tracking** - Captures claude-flow swarm operations
|
|
859
|
+
- **Markdown Generation** - Creates documentation for sessions, conversations, agents
|
|
860
|
+
- **Tool Output Separation** - Stores tool outputs in dedicated JSON files
|
|
861
|
+
- **CLI Commands** - `kg hooks install/uninstall/status/sessions/export`
|
|
862
|
+
- Comprehensive type definitions with Zod validation
|
|
863
|
+
- 22 new tests for hook system
|
|
864
|
+
|
|
865
|
+
### v0.9.0
|
|
866
|
+
|
|
867
|
+
**Document Cultivation System:**
|
|
868
|
+
- **Doc Cultivation Command** - `kg cultivate` for automated documentation buildout
|
|
869
|
+
- **7-Phase Cultivation Process** - Structure → Content → Architecture → Development → Infrastructure → Review → Completion
|
|
870
|
+
- **Development Planning** - Generates phased development plans with tasks
|
|
871
|
+
- **Infrastructure Planning** - Creates dev/staging/production infrastructure plans
|
|
872
|
+
- **SOP Compliance Analysis** - Integrates AI-SDLC SOP requirements
|
|
873
|
+
- **Swarm Orchestration** - Uses claude-flow for parallel documentation generation
|
|
874
|
+
- Support for multi-service projects (api, backend, frontend, admin)
|
|
875
|
+
|
|
876
|
+
### v0.8.8
|
|
877
|
+
|
|
878
|
+
- Added `src/{service}/docs` directory scanning and copying for doc generation
|
|
879
|
+
- Enhanced service documentation detection
|
|
880
|
+
|
|
881
|
+
### v0.8.7
|
|
882
|
+
|
|
883
|
+
- Improved Python project detection for doc generation
|
|
884
|
+
- Better handling of `requirements.txt` and `pyproject.toml`
|
|
885
|
+
|
|
886
|
+
### v0.8.6
|
|
887
|
+
|
|
888
|
+
- Fixed vault-sync.test.ts timeout issues
|
|
889
|
+
- Improved test stability
|
|
890
|
+
|
|
727
891
|
### v0.7.4
|
|
728
892
|
|
|
729
893
|
- Fixed repository URL in package.json to match actual GitHub repo name
|
|
@@ -525,11 +525,11 @@ class BaseAgent {
|
|
|
525
525
|
const namespace = this.config.claudeFlow?.namespace ?? "knowledge-graph";
|
|
526
526
|
switch (hookType) {
|
|
527
527
|
case "pre-task":
|
|
528
|
-
return `
|
|
528
|
+
return `claude-flow hooks pre-task --description "${task.description}"`;
|
|
529
529
|
case "post-task":
|
|
530
|
-
return `
|
|
530
|
+
return `claude-flow hooks post-task --task-id "${task.id}"`;
|
|
531
531
|
case "post-edit":
|
|
532
|
-
return `
|
|
532
|
+
return `claude-flow hooks post-edit --memory-key "${namespace}/agent/${this.config.id}/task/${task.id}"`;
|
|
533
533
|
default:
|
|
534
534
|
return "";
|
|
535
535
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-agent.js","sources":["../../src/agents/base-agent.ts"],"sourcesContent":["/**\n * Base Agent Implementation\n *\n * Abstract base class for all agents providing common functionality\n * including task execution, input validation, output formatting,\n * error handling, and optional claude-flow integration.\n *\n * @module agents/base-agent\n */\n\nimport { getLogger, retry, type Logger, type RetryOptions } from '../utils/index.js';\nimport {\n AgentType,\n AgentStatus,\n TaskPriority,\n MessageType,\n type AgentConfig,\n type AgentInstance,\n type AgentState,\n type AgentTask,\n type AgentResult,\n type AgentError,\n type AgentMessage,\n type ExecutionMetrics,\n type ResultArtifact,\n createAgentId,\n createTaskId,\n} from './types.js';\nimport {\n TrajectoryTracker,\n type TrajectoryTrackerConfig,\n} from '../learning/services/trajectory-tracker.js';\nimport type { TrajectoryStep } from '../integrations/agentic-flow/adapters/reasoning-bank-adapter.js';\n\n// ============================================================================\n// Base Agent Abstract Class\n// ============================================================================\n\n/**\n * Abstract base class for all agents\n *\n * Provides common functionality that all agents share, including:\n * - Task execution with timeout and retry handling\n * - Input validation\n * - Output formatting\n * - Error handling and logging\n * - Optional claude-flow hooks integration\n *\n * @example\n * ```typescript\n * class ResearchAgent extends BaseAgent {\n * protected async executeTask(task: AgentTask): Promise<AgentResult> {\n * // Implementation specific to researcher agent\n * const results = await this.searchSources(task.input);\n * return this.formatOutput(results);\n * }\n * }\n * ```\n */\nexport abstract class BaseAgent implements AgentInstance {\n /** Agent configuration */\n public readonly config: AgentConfig;\n\n /** Agent runtime state */\n private _state: AgentState;\n\n /** Logger instance */\n protected readonly logger: Logger;\n\n /** Message handlers for different message types */\n private messageHandlers: Map<MessageType, (message: AgentMessage) => Promise<void>> =\n new Map();\n\n /** Trajectory tracker for learning */\n protected trajectoryTracker: TrajectoryTracker | null = null;\n\n /** Current active trajectory ID */\n protected currentTrajectoryId: string | null = null;\n\n /** Whether to auto-track trajectories */\n protected autoTrackTrajectories: boolean = true;\n\n constructor(config: AgentConfig) {\n // Ensure ID is set\n this.config = {\n ...config,\n id: config.id ?? createAgentId(config.type),\n };\n\n // Initialize state\n this._state = {\n id: this.config.id!,\n status: AgentStatus.IDLE,\n taskQueue: [],\n completedTasks: [],\n lastActivity: new Date(),\n errorCount: 0,\n };\n\n // Create logger\n this.logger = getLogger().child(`agent:${this.config.name}`);\n\n // Register default message handlers\n this.registerDefaultMessageHandlers();\n }\n\n // ============================================================================\n // State Management\n // ============================================================================\n\n /**\n * Get current agent state\n */\n get state(): AgentState {\n return { ...this._state };\n }\n\n /**\n * Get current agent status\n */\n getStatus(): AgentStatus {\n return this._state.status;\n }\n\n /**\n * Update agent status\n */\n protected setStatus(status: AgentStatus): void {\n const previousStatus = this._state.status;\n this._state.status = status;\n this._state.lastActivity = new Date();\n\n if (previousStatus !== status) {\n this.logger.debug(`Status changed: ${previousStatus} -> ${status}`);\n }\n }\n\n // ============================================================================\n // Task Execution\n // ============================================================================\n\n /**\n * Execute a task\n *\n * This is the main entry point for task execution. It handles:\n * - Pre-task hooks (if enabled)\n * - Input validation\n * - Retry logic\n * - Timeout handling\n * - Post-task hooks (if enabled)\n * - Error handling and logging\n */\n async execute(task: AgentTask): Promise<AgentResult> {\n const startTime = new Date();\n\n this.logger.info(`Executing task: ${task.id}`, {\n description: task.description,\n priority: task.priority,\n });\n\n // Run pre-task hook if enabled\n if (this.config.claudeFlow?.hooks?.preTask) {\n await this.runClaudeFlowHook('pre-task', task);\n }\n\n // Start trajectory tracking if enabled\n if (this.autoTrackTrajectories && this.trajectoryTracker?.isEnabled()) {\n this.startTrajectory(task.id, {\n description: task.description,\n priority: task.priority,\n input: task.input,\n });\n this.recordStep('task_started', `Starting task: ${task.description}`, 1.0);\n }\n\n try {\n // Validate input\n const validationResult = await this.validateInput(task);\n if (!validationResult.valid) {\n this.recordStep('validation_failed', validationResult.error ?? 'Input validation failed', 0.0);\n await this.completeTrajectory('failure', { validationError: validationResult.error });\n return this.createErrorResult(\n 'VALIDATION_ERROR',\n validationResult.error ?? 'Input validation failed',\n startTime\n );\n }\n\n this.recordStep('validation_passed', 'Input validation successful', 1.0);\n\n // Set status to running\n this.setStatus(AgentStatus.RUNNING);\n this._state.currentTask = task;\n\n // Execute with retry if configured\n let result: AgentResult;\n const retryConfig = this.config.retry;\n\n if (retryConfig && retryConfig.maxRetries > 0) {\n const retryOptions: RetryOptions = {\n maxRetries: retryConfig.maxRetries,\n initialDelay: retryConfig.backoffMs,\n backoffFactor: retryConfig.backoffMultiplier ?? 2,\n isRetryable: (error: unknown) => this.isRetryableError(error),\n };\n\n result = await retry(\n async () => this.executeWithTimeout(task),\n retryOptions\n );\n } else {\n result = await this.executeWithTimeout(task);\n }\n\n // Update state on success\n if (result.success) {\n this._state.completedTasks.push(task.id);\n this.setStatus(AgentStatus.COMPLETED);\n this.recordStep('task_completed', 'Task completed successfully', 1.0, { success: true });\n await this.completeTrajectory('success', {\n durationMs: result.metrics?.durationMs,\n artifactCount: result.artifacts?.length ?? 0,\n });\n } else {\n this._state.errorCount++;\n this.setStatus(AgentStatus.FAILED);\n this.recordStep('task_failed', result.error?.message ?? 'Task failed', 0.0, { error: result.error });\n await this.completeTrajectory('failure', {\n errorCode: result.error?.code,\n errorMessage: result.error?.message,\n });\n }\n\n // Add metrics\n result.metrics = this.calculateMetrics(startTime, new Date());\n\n // Run post-task hook if enabled\n if (this.config.claudeFlow?.hooks?.postTask) {\n await this.runClaudeFlowHook('post-task', task, result);\n }\n\n return result;\n } catch (error) {\n this._state.errorCount++;\n this.setStatus(AgentStatus.FAILED);\n\n const agentError = this.normalizeError(error);\n this.logger.error(`Task execution failed: ${task.id}`, error as Error);\n\n // Record trajectory failure\n this.recordStep('task_exception', agentError.message, 0.0, {\n errorCode: agentError.code,\n stack: agentError.stack,\n });\n await this.completeTrajectory('failure', {\n exception: true,\n errorCode: agentError.code,\n errorMessage: agentError.message,\n });\n\n return this.createErrorResult(agentError.code, agentError.message, startTime, {\n stack: agentError.stack,\n retryable: agentError.retryable,\n });\n } finally {\n this._state.currentTask = undefined;\n this._state.lastActivity = new Date();\n }\n }\n\n /**\n * Execute task with timeout\n */\n private async executeWithTimeout(task: AgentTask): Promise<AgentResult> {\n const timeout = task.timeout ?? this.config.taskTimeout ?? 30000;\n\n return new Promise<AgentResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`Task execution timed out after ${timeout}ms`));\n }, timeout);\n\n this.executeTask(task)\n .then((result) => {\n clearTimeout(timer);\n resolve(result);\n })\n .catch((error) => {\n clearTimeout(timer);\n reject(error);\n });\n });\n }\n\n /**\n * Abstract method for actual task execution\n *\n * Subclasses must implement this method with their specific logic.\n */\n protected abstract executeTask(task: AgentTask): Promise<AgentResult>;\n\n // ============================================================================\n // Input Validation\n // ============================================================================\n\n /**\n * Validate task input\n *\n * Override this method to implement custom validation logic.\n */\n async validateInput(task: AgentTask): Promise<{ valid: boolean; error?: string }> {\n // Basic validation\n if (!task.id) {\n return { valid: false, error: 'Task ID is required' };\n }\n\n if (!task.description) {\n return { valid: false, error: 'Task description is required' };\n }\n\n // Check dependencies are resolved\n if (task.dependencies && task.dependencies.length > 0) {\n const unresolvedDeps = task.dependencies.filter(\n (dep) => !this._state.completedTasks.includes(dep)\n );\n\n if (unresolvedDeps.length > 0) {\n return {\n valid: false,\n error: `Unresolved dependencies: ${unresolvedDeps.join(', ')}`,\n };\n }\n }\n\n return { valid: true };\n }\n\n // ============================================================================\n // Output Formatting\n // ============================================================================\n\n /**\n * Format successful output\n */\n formatOutput<T>(data: T, artifacts?: ResultArtifact[]): AgentResult<T> {\n return {\n success: true,\n data,\n artifacts,\n metadata: {\n agentId: this.config.id,\n agentType: this.config.type,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n /**\n * Create a success result\n */\n protected createSuccessResult<T>(\n data: T,\n startTime: Date,\n artifacts?: ResultArtifact[]\n ): AgentResult<T> {\n return {\n success: true,\n data,\n artifacts,\n metrics: this.calculateMetrics(startTime, new Date()),\n metadata: {\n agentId: this.config.id,\n agentType: this.config.type,\n },\n };\n }\n\n /**\n * Create an error result\n */\n protected createErrorResult(\n code: string,\n message: string,\n startTime: Date,\n details?: Partial<AgentError>\n ): AgentResult {\n return {\n success: false,\n error: {\n code,\n message,\n ...details,\n },\n metrics: this.calculateMetrics(startTime, new Date()),\n metadata: {\n agentId: this.config.id,\n agentType: this.config.type,\n },\n };\n }\n\n /**\n * Calculate execution metrics\n */\n private calculateMetrics(startTime: Date, endTime: Date): ExecutionMetrics {\n return {\n startTime,\n endTime,\n durationMs: endTime.getTime() - startTime.getTime(),\n memoryUsage: process.memoryUsage?.().heapUsed,\n retries: 0, // Updated by retry logic if needed\n };\n }\n\n // ============================================================================\n // Error Handling\n // ============================================================================\n\n /**\n * Normalize error to AgentError format\n */\n private normalizeError(error: unknown): AgentError {\n if (error instanceof Error) {\n return {\n code: error.name || 'UNKNOWN_ERROR',\n message: error.message,\n stack: error.stack,\n retryable: this.isRetryableError(error),\n };\n }\n\n return {\n code: 'UNKNOWN_ERROR',\n message: String(error),\n retryable: false,\n };\n }\n\n /**\n * Check if an error is retryable\n */\n protected isRetryableError(error: unknown): boolean {\n if (error instanceof Error) {\n const message = error.message.toLowerCase();\n\n // Network/transient errors\n if (\n message.includes('timeout') ||\n message.includes('network') ||\n message.includes('connection') ||\n message.includes('econnreset') ||\n message.includes('rate limit')\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n // ============================================================================\n // Lifecycle Methods\n // ============================================================================\n\n /**\n * Pause the agent\n */\n async pause(): Promise<void> {\n if (this._state.status === AgentStatus.RUNNING) {\n this.logger.info('Pausing agent');\n this.setStatus(AgentStatus.PAUSED);\n }\n }\n\n /**\n * Resume the agent\n */\n async resume(): Promise<void> {\n if (this._state.status === AgentStatus.PAUSED) {\n this.logger.info('Resuming agent');\n this.setStatus(AgentStatus.IDLE);\n }\n }\n\n /**\n * Terminate the agent\n */\n async terminate(): Promise<void> {\n this.logger.info('Terminating agent');\n\n // Clean up any resources\n await this.cleanup();\n\n this.setStatus(AgentStatus.TERMINATED);\n }\n\n /**\n * Cleanup resources\n *\n * Override to implement custom cleanup logic.\n */\n protected async cleanup(): Promise<void> {\n // Default: no cleanup needed\n }\n\n // ============================================================================\n // Messaging\n // ============================================================================\n\n /**\n * Send a message to another agent\n */\n async sendMessage(message: AgentMessage): Promise<void> {\n this.logger.debug(`Sending message to ${message.to}`, {\n type: message.type,\n correlationId: message.correlationId,\n });\n\n // In a real implementation, this would use a message bus\n // For now, just log the message\n this.logger.trace('Message payload', { payload: message.payload });\n }\n\n /**\n * Receive and process a message\n */\n async receiveMessage(message: AgentMessage): Promise<void> {\n this.logger.debug(`Received message from ${message.from}`, {\n type: message.type,\n correlationId: message.correlationId,\n });\n\n const handler = this.messageHandlers.get(message.type);\n if (handler) {\n await handler(message);\n } else {\n this.logger.warn(`No handler for message type: ${message.type}`);\n }\n }\n\n /**\n * Register a message handler\n */\n protected registerMessageHandler(\n type: MessageType,\n handler: (message: AgentMessage) => Promise<void>\n ): void {\n this.messageHandlers.set(type, handler);\n }\n\n /**\n * Register default message handlers\n */\n private registerDefaultMessageHandlers(): void {\n // Handle status requests\n this.registerMessageHandler(MessageType.STATUS, async (message) => {\n await this.sendMessage({\n id: `${Date.now()}`,\n type: MessageType.STATUS,\n from: this.config.id!,\n to: message.from,\n timestamp: new Date(),\n correlationId: message.id,\n payload: {\n agentId: this.config.id,\n status: this._state.status,\n currentTask: this._state.currentTask?.id,\n },\n });\n });\n }\n\n // ============================================================================\n // Trajectory Tracking\n // ============================================================================\n\n /**\n * Set the trajectory tracker for this agent\n *\n * @param tracker - The trajectory tracker instance\n */\n setTrajectoryTracker(tracker: TrajectoryTracker): void {\n this.trajectoryTracker = tracker;\n }\n\n /**\n * Enable or disable auto-tracking of trajectories\n *\n * @param enabled - Whether to auto-track\n */\n setAutoTrackTrajectories(enabled: boolean): void {\n this.autoTrackTrajectories = enabled;\n }\n\n /**\n * Start tracking a task trajectory\n *\n * @param taskId - The task ID to track\n * @param metadata - Optional metadata\n * @returns The trajectory ID\n */\n protected startTrajectory(\n taskId: string,\n metadata: Record<string, unknown> = {}\n ): string | null {\n if (!this.trajectoryTracker?.isEnabled()) {\n return null;\n }\n\n this.currentTrajectoryId = this.trajectoryTracker.startTrajectory(taskId, {\n ...metadata,\n agentId: this.config.id,\n agentType: this.config.type,\n agentName: this.config.name,\n });\n\n return this.currentTrajectoryId;\n }\n\n /**\n * Record a step in the current trajectory\n *\n * @param action - The action taken\n * @param observation - The observation/result\n * @param confidence - Optional confidence score (0-1)\n * @param metadata - Optional step metadata\n */\n protected recordStep(\n action: string,\n observation: string,\n confidence?: number,\n metadata?: Record<string, unknown>\n ): void {\n if (!this.trajectoryTracker || !this.currentTrajectoryId) {\n return;\n }\n\n this.trajectoryTracker.recordStep(this.currentTrajectoryId, {\n action,\n observation,\n confidence,\n metadata,\n });\n }\n\n /**\n * Complete the current trajectory\n *\n * @param outcome - The task outcome\n * @param metadata - Optional final metadata\n * @returns The stored trajectory ID, or null\n */\n protected async completeTrajectory(\n outcome: 'success' | 'failure' | 'partial',\n metadata: Record<string, unknown> = {}\n ): Promise<string | null> {\n if (!this.trajectoryTracker || !this.currentTrajectoryId) {\n return null;\n }\n\n const storedId = await this.trajectoryTracker.completeTrajectory(\n this.currentTrajectoryId,\n outcome,\n metadata\n );\n\n this.currentTrajectoryId = null;\n return storedId;\n }\n\n /**\n * Abort the current trajectory\n *\n * @param reason - The reason for aborting\n */\n protected abortTrajectory(reason: string): void {\n if (!this.trajectoryTracker || !this.currentTrajectoryId) {\n return;\n }\n\n this.trajectoryTracker.abortTrajectory(this.currentTrajectoryId, reason);\n this.currentTrajectoryId = null;\n }\n\n /**\n * Check if trajectory tracking is active\n */\n isTrackingTrajectory(): boolean {\n return this.currentTrajectoryId !== null;\n }\n\n /**\n * Get current trajectory progress\n */\n getTrajectoryProgress(): {\n stepCount: number;\n duration: number;\n lastStep?: TrajectoryStep;\n } | null {\n if (!this.trajectoryTracker || !this.currentTrajectoryId) {\n return null;\n }\n\n return this.trajectoryTracker.getProgress(this.currentTrajectoryId);\n }\n\n // ============================================================================\n // Claude-Flow Integration\n // ============================================================================\n\n /**\n * Run a claude-flow hook\n */\n protected async runClaudeFlowHook(\n hookType: 'pre-task' | 'post-task' | 'post-edit',\n task: AgentTask,\n result?: AgentResult\n ): Promise<void> {\n if (!this.config.claudeFlow?.enabled) {\n return;\n }\n\n const namespace = this.config.claudeFlow.namespace ?? 'knowledge-graph';\n\n this.logger.debug(`Running claude-flow hook: ${hookType}`, {\n namespace,\n taskId: task.id,\n });\n\n // Generate the hook command that would be run\n const hookCommand = this.generateHookCommand(hookType, task, result);\n\n this.logger.trace('Claude-flow hook command', { command: hookCommand });\n\n // In production, this would execute via child_process or MCP\n // For now, we just log the intent\n }\n\n /**\n * Generate claude-flow hook command\n */\n private generateHookCommand(\n hookType: 'pre-task' | 'post-task' | 'post-edit',\n task: AgentTask,\n result?: AgentResult\n ): string {\n const namespace = this.config.claudeFlow?.namespace ?? 'knowledge-graph';\n\n switch (hookType) {\n case 'pre-task':\n return `npx claude-flow@alpha hooks pre-task --description \"${task.description}\"`;\n\n case 'post-task':\n return `npx claude-flow@alpha hooks post-task --task-id \"${task.id}\"`;\n\n case 'post-edit':\n return `npx claude-flow@alpha hooks post-edit --memory-key \"${namespace}/agent/${this.config.id}/task/${task.id}\"`;\n\n default:\n return '';\n }\n }\n\n /**\n * Store result in claude-flow memory\n */\n protected async storeInMemory(key: string, value: unknown): Promise<void> {\n if (!this.config.claudeFlow?.enabled) {\n return;\n }\n\n const namespace = this.config.claudeFlow.namespace ?? 'knowledge-graph';\n\n this.logger.debug('Storing in claude-flow memory', { namespace, key });\n\n // This would call the MCP memory_usage tool\n // For now, just log the intent\n this.logger.trace('Memory store', {\n action: 'store',\n namespace,\n key,\n value: JSON.stringify(value).slice(0, 100),\n });\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create a task with defaults\n */\nexport function createTask(\n description: string,\n options?: Partial<Omit<AgentTask, 'id' | 'description' | 'createdAt'>>\n): AgentTask {\n return {\n id: createTaskId(),\n description,\n priority: options?.priority ?? TaskPriority.MEDIUM,\n input: options?.input ?? {},\n expectedOutput: options?.expectedOutput,\n dependencies: options?.dependencies,\n timeout: options?.timeout,\n metadata: options?.metadata,\n createdAt: new Date(),\n deadline: options?.deadline,\n };\n}\n\n/**\n * Type guard for checking if an object is an AgentResult\n */\nexport function isAgentResult(obj: unknown): obj is AgentResult {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n 'success' in obj &&\n typeof (obj as AgentResult).success === 'boolean'\n );\n}\n\n/**\n * Type guard for checking if an object is an AgentError\n */\nexport function isAgentError(obj: unknown): obj is AgentError {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n 'code' in obj &&\n 'message' in obj &&\n typeof (obj as AgentError).code === 'string' &&\n typeof (obj as AgentError).message === 'string'\n );\n}\n"],"names":[],"mappings":";;;AA2DO,MAAe,UAAmC;AAAA;AAAA,EAEvC;AAAA;AAAA,EAGR;AAAA;AAAA,EAGW;AAAA;AAAA,EAGX,sCACF,IAAA;AAAA;AAAA,EAGI,oBAA8C;AAAA;AAAA,EAG9C,sBAAqC;AAAA;AAAA,EAGrC,wBAAiC;AAAA,EAE3C,YAAY,QAAqB;AAE/B,SAAK,SAAS;AAAA,MACZ,GAAG;AAAA,MACH,IAAI,OAAO,MAAM,cAAc,OAAO,IAAI;AAAA,IAAA;AAI5C,SAAK,SAAS;AAAA,MACZ,IAAI,KAAK,OAAO;AAAA,MAChB,QAAQ,YAAY;AAAA,MACpB,WAAW,CAAA;AAAA,MACX,gBAAgB,CAAA;AAAA,MAChB,kCAAkB,KAAA;AAAA,MAClB,YAAY;AAAA,IAAA;AAId,SAAK,SAAS,YAAY,MAAM,SAAS,KAAK,OAAO,IAAI,EAAE;AAG3D,SAAK,+BAAA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,IAAI,QAAoB;AACtB,WAAO,EAAE,GAAG,KAAK,OAAA;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA,EAKA,YAAyB;AACvB,WAAO,KAAK,OAAO;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA,EAKU,UAAU,QAA2B;AAC7C,UAAM,iBAAiB,KAAK,OAAO;AACnC,SAAK,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;AAEtD,SAAK,OAAO,MAAM,iCAAiC,EAAE,WAAW,KAAK;AAIrE,SAAK,OAAO,MAAM,gBAAgB;AAAA,MAChC,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA,OAAO,KAAK,UAAU,KAAK,EAAE,MAAM,GAAG,GAAG;AAAA,IAAA,CAC1C;AAAA,EACH;AACF;AASO,SAAS,WACd,aACA,SACW;AACX,SAAO;AAAA,IACL,IAAI,aAAA;AAAA,IACJ;AAAA,IACA,UAAU,SAAS,YAAY,aAAa;AAAA,IAC5C,OAAO,SAAS,SAAS,CAAA;AAAA,IACzB,gBAAgB,SAAS;AAAA,IACzB,cAAc,SAAS;AAAA,IACvB,SAAS,SAAS;AAAA,IAClB,UAAU,SAAS;AAAA,IACnB,+BAAe,KAAA;AAAA,IACf,UAAU,SAAS;AAAA,EAAA;AAEvB;AAKO,SAAS,cAAc,KAAkC;AAC9D,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,aAAa,OACb,OAAQ,IAAoB,YAAY;AAE5C;AAKO,SAAS,aAAa,KAAiC;AAC5D,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,aAAa,OACb,OAAQ,IAAmB,SAAS,YACpC,OAAQ,IAAmB,YAAY;AAE3C;"}
|
|
1
|
+
{"version":3,"file":"base-agent.js","sources":["../../src/agents/base-agent.ts"],"sourcesContent":["/**\n * Base Agent Implementation\n *\n * Abstract base class for all agents providing common functionality\n * including task execution, input validation, output formatting,\n * error handling, and optional claude-flow integration.\n *\n * @module agents/base-agent\n */\n\nimport { getLogger, retry, type Logger, type RetryOptions } from '../utils/index.js';\nimport {\n AgentType,\n AgentStatus,\n TaskPriority,\n MessageType,\n type AgentConfig,\n type AgentInstance,\n type AgentState,\n type AgentTask,\n type AgentResult,\n type AgentError,\n type AgentMessage,\n type ExecutionMetrics,\n type ResultArtifact,\n createAgentId,\n createTaskId,\n} from './types.js';\nimport {\n TrajectoryTracker,\n type TrajectoryTrackerConfig,\n} from '../learning/services/trajectory-tracker.js';\nimport type { TrajectoryStep } from '../integrations/agentic-flow/adapters/reasoning-bank-adapter.js';\n\n// ============================================================================\n// Base Agent Abstract Class\n// ============================================================================\n\n/**\n * Abstract base class for all agents\n *\n * Provides common functionality that all agents share, including:\n * - Task execution with timeout and retry handling\n * - Input validation\n * - Output formatting\n * - Error handling and logging\n * - Optional claude-flow hooks integration\n *\n * @example\n * ```typescript\n * class ResearchAgent extends BaseAgent {\n * protected async executeTask(task: AgentTask): Promise<AgentResult> {\n * // Implementation specific to researcher agent\n * const results = await this.searchSources(task.input);\n * return this.formatOutput(results);\n * }\n * }\n * ```\n */\nexport abstract class BaseAgent implements AgentInstance {\n /** Agent configuration */\n public readonly config: AgentConfig;\n\n /** Agent runtime state */\n private _state: AgentState;\n\n /** Logger instance */\n protected readonly logger: Logger;\n\n /** Message handlers for different message types */\n private messageHandlers: Map<MessageType, (message: AgentMessage) => Promise<void>> =\n new Map();\n\n /** Trajectory tracker for learning */\n protected trajectoryTracker: TrajectoryTracker | null = null;\n\n /** Current active trajectory ID */\n protected currentTrajectoryId: string | null = null;\n\n /** Whether to auto-track trajectories */\n protected autoTrackTrajectories: boolean = true;\n\n constructor(config: AgentConfig) {\n // Ensure ID is set\n this.config = {\n ...config,\n id: config.id ?? createAgentId(config.type),\n };\n\n // Initialize state\n this._state = {\n id: this.config.id!,\n status: AgentStatus.IDLE,\n taskQueue: [],\n completedTasks: [],\n lastActivity: new Date(),\n errorCount: 0,\n };\n\n // Create logger\n this.logger = getLogger().child(`agent:${this.config.name}`);\n\n // Register default message handlers\n this.registerDefaultMessageHandlers();\n }\n\n // ============================================================================\n // State Management\n // ============================================================================\n\n /**\n * Get current agent state\n */\n get state(): AgentState {\n return { ...this._state };\n }\n\n /**\n * Get current agent status\n */\n getStatus(): AgentStatus {\n return this._state.status;\n }\n\n /**\n * Update agent status\n */\n protected setStatus(status: AgentStatus): void {\n const previousStatus = this._state.status;\n this._state.status = status;\n this._state.lastActivity = new Date();\n\n if (previousStatus !== status) {\n this.logger.debug(`Status changed: ${previousStatus} -> ${status}`);\n }\n }\n\n // ============================================================================\n // Task Execution\n // ============================================================================\n\n /**\n * Execute a task\n *\n * This is the main entry point for task execution. It handles:\n * - Pre-task hooks (if enabled)\n * - Input validation\n * - Retry logic\n * - Timeout handling\n * - Post-task hooks (if enabled)\n * - Error handling and logging\n */\n async execute(task: AgentTask): Promise<AgentResult> {\n const startTime = new Date();\n\n this.logger.info(`Executing task: ${task.id}`, {\n description: task.description,\n priority: task.priority,\n });\n\n // Run pre-task hook if enabled\n if (this.config.claudeFlow?.hooks?.preTask) {\n await this.runClaudeFlowHook('pre-task', task);\n }\n\n // Start trajectory tracking if enabled\n if (this.autoTrackTrajectories && this.trajectoryTracker?.isEnabled()) {\n this.startTrajectory(task.id, {\n description: task.description,\n priority: task.priority,\n input: task.input,\n });\n this.recordStep('task_started', `Starting task: ${task.description}`, 1.0);\n }\n\n try {\n // Validate input\n const validationResult = await this.validateInput(task);\n if (!validationResult.valid) {\n this.recordStep('validation_failed', validationResult.error ?? 'Input validation failed', 0.0);\n await this.completeTrajectory('failure', { validationError: validationResult.error });\n return this.createErrorResult(\n 'VALIDATION_ERROR',\n validationResult.error ?? 'Input validation failed',\n startTime\n );\n }\n\n this.recordStep('validation_passed', 'Input validation successful', 1.0);\n\n // Set status to running\n this.setStatus(AgentStatus.RUNNING);\n this._state.currentTask = task;\n\n // Execute with retry if configured\n let result: AgentResult;\n const retryConfig = this.config.retry;\n\n if (retryConfig && retryConfig.maxRetries > 0) {\n const retryOptions: RetryOptions = {\n maxRetries: retryConfig.maxRetries,\n initialDelay: retryConfig.backoffMs,\n backoffFactor: retryConfig.backoffMultiplier ?? 2,\n isRetryable: (error: unknown) => this.isRetryableError(error),\n };\n\n result = await retry(\n async () => this.executeWithTimeout(task),\n retryOptions\n );\n } else {\n result = await this.executeWithTimeout(task);\n }\n\n // Update state on success\n if (result.success) {\n this._state.completedTasks.push(task.id);\n this.setStatus(AgentStatus.COMPLETED);\n this.recordStep('task_completed', 'Task completed successfully', 1.0, { success: true });\n await this.completeTrajectory('success', {\n durationMs: result.metrics?.durationMs,\n artifactCount: result.artifacts?.length ?? 0,\n });\n } else {\n this._state.errorCount++;\n this.setStatus(AgentStatus.FAILED);\n this.recordStep('task_failed', result.error?.message ?? 'Task failed', 0.0, { error: result.error });\n await this.completeTrajectory('failure', {\n errorCode: result.error?.code,\n errorMessage: result.error?.message,\n });\n }\n\n // Add metrics\n result.metrics = this.calculateMetrics(startTime, new Date());\n\n // Run post-task hook if enabled\n if (this.config.claudeFlow?.hooks?.postTask) {\n await this.runClaudeFlowHook('post-task', task, result);\n }\n\n return result;\n } catch (error) {\n this._state.errorCount++;\n this.setStatus(AgentStatus.FAILED);\n\n const agentError = this.normalizeError(error);\n this.logger.error(`Task execution failed: ${task.id}`, error as Error);\n\n // Record trajectory failure\n this.recordStep('task_exception', agentError.message, 0.0, {\n errorCode: agentError.code,\n stack: agentError.stack,\n });\n await this.completeTrajectory('failure', {\n exception: true,\n errorCode: agentError.code,\n errorMessage: agentError.message,\n });\n\n return this.createErrorResult(agentError.code, agentError.message, startTime, {\n stack: agentError.stack,\n retryable: agentError.retryable,\n });\n } finally {\n this._state.currentTask = undefined;\n this._state.lastActivity = new Date();\n }\n }\n\n /**\n * Execute task with timeout\n */\n private async executeWithTimeout(task: AgentTask): Promise<AgentResult> {\n const timeout = task.timeout ?? this.config.taskTimeout ?? 30000;\n\n return new Promise<AgentResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`Task execution timed out after ${timeout}ms`));\n }, timeout);\n\n this.executeTask(task)\n .then((result) => {\n clearTimeout(timer);\n resolve(result);\n })\n .catch((error) => {\n clearTimeout(timer);\n reject(error);\n });\n });\n }\n\n /**\n * Abstract method for actual task execution\n *\n * Subclasses must implement this method with their specific logic.\n */\n protected abstract executeTask(task: AgentTask): Promise<AgentResult>;\n\n // ============================================================================\n // Input Validation\n // ============================================================================\n\n /**\n * Validate task input\n *\n * Override this method to implement custom validation logic.\n */\n async validateInput(task: AgentTask): Promise<{ valid: boolean; error?: string }> {\n // Basic validation\n if (!task.id) {\n return { valid: false, error: 'Task ID is required' };\n }\n\n if (!task.description) {\n return { valid: false, error: 'Task description is required' };\n }\n\n // Check dependencies are resolved\n if (task.dependencies && task.dependencies.length > 0) {\n const unresolvedDeps = task.dependencies.filter(\n (dep) => !this._state.completedTasks.includes(dep)\n );\n\n if (unresolvedDeps.length > 0) {\n return {\n valid: false,\n error: `Unresolved dependencies: ${unresolvedDeps.join(', ')}`,\n };\n }\n }\n\n return { valid: true };\n }\n\n // ============================================================================\n // Output Formatting\n // ============================================================================\n\n /**\n * Format successful output\n */\n formatOutput<T>(data: T, artifacts?: ResultArtifact[]): AgentResult<T> {\n return {\n success: true,\n data,\n artifacts,\n metadata: {\n agentId: this.config.id,\n agentType: this.config.type,\n timestamp: new Date().toISOString(),\n },\n };\n }\n\n /**\n * Create a success result\n */\n protected createSuccessResult<T>(\n data: T,\n startTime: Date,\n artifacts?: ResultArtifact[]\n ): AgentResult<T> {\n return {\n success: true,\n data,\n artifacts,\n metrics: this.calculateMetrics(startTime, new Date()),\n metadata: {\n agentId: this.config.id,\n agentType: this.config.type,\n },\n };\n }\n\n /**\n * Create an error result\n */\n protected createErrorResult(\n code: string,\n message: string,\n startTime: Date,\n details?: Partial<AgentError>\n ): AgentResult {\n return {\n success: false,\n error: {\n code,\n message,\n ...details,\n },\n metrics: this.calculateMetrics(startTime, new Date()),\n metadata: {\n agentId: this.config.id,\n agentType: this.config.type,\n },\n };\n }\n\n /**\n * Calculate execution metrics\n */\n private calculateMetrics(startTime: Date, endTime: Date): ExecutionMetrics {\n return {\n startTime,\n endTime,\n durationMs: endTime.getTime() - startTime.getTime(),\n memoryUsage: process.memoryUsage?.().heapUsed,\n retries: 0, // Updated by retry logic if needed\n };\n }\n\n // ============================================================================\n // Error Handling\n // ============================================================================\n\n /**\n * Normalize error to AgentError format\n */\n private normalizeError(error: unknown): AgentError {\n if (error instanceof Error) {\n return {\n code: error.name || 'UNKNOWN_ERROR',\n message: error.message,\n stack: error.stack,\n retryable: this.isRetryableError(error),\n };\n }\n\n return {\n code: 'UNKNOWN_ERROR',\n message: String(error),\n retryable: false,\n };\n }\n\n /**\n * Check if an error is retryable\n */\n protected isRetryableError(error: unknown): boolean {\n if (error instanceof Error) {\n const message = error.message.toLowerCase();\n\n // Network/transient errors\n if (\n message.includes('timeout') ||\n message.includes('network') ||\n message.includes('connection') ||\n message.includes('econnreset') ||\n message.includes('rate limit')\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n // ============================================================================\n // Lifecycle Methods\n // ============================================================================\n\n /**\n * Pause the agent\n */\n async pause(): Promise<void> {\n if (this._state.status === AgentStatus.RUNNING) {\n this.logger.info('Pausing agent');\n this.setStatus(AgentStatus.PAUSED);\n }\n }\n\n /**\n * Resume the agent\n */\n async resume(): Promise<void> {\n if (this._state.status === AgentStatus.PAUSED) {\n this.logger.info('Resuming agent');\n this.setStatus(AgentStatus.IDLE);\n }\n }\n\n /**\n * Terminate the agent\n */\n async terminate(): Promise<void> {\n this.logger.info('Terminating agent');\n\n // Clean up any resources\n await this.cleanup();\n\n this.setStatus(AgentStatus.TERMINATED);\n }\n\n /**\n * Cleanup resources\n *\n * Override to implement custom cleanup logic.\n */\n protected async cleanup(): Promise<void> {\n // Default: no cleanup needed\n }\n\n // ============================================================================\n // Messaging\n // ============================================================================\n\n /**\n * Send a message to another agent\n */\n async sendMessage(message: AgentMessage): Promise<void> {\n this.logger.debug(`Sending message to ${message.to}`, {\n type: message.type,\n correlationId: message.correlationId,\n });\n\n // In a real implementation, this would use a message bus\n // For now, just log the message\n this.logger.trace('Message payload', { payload: message.payload });\n }\n\n /**\n * Receive and process a message\n */\n async receiveMessage(message: AgentMessage): Promise<void> {\n this.logger.debug(`Received message from ${message.from}`, {\n type: message.type,\n correlationId: message.correlationId,\n });\n\n const handler = this.messageHandlers.get(message.type);\n if (handler) {\n await handler(message);\n } else {\n this.logger.warn(`No handler for message type: ${message.type}`);\n }\n }\n\n /**\n * Register a message handler\n */\n protected registerMessageHandler(\n type: MessageType,\n handler: (message: AgentMessage) => Promise<void>\n ): void {\n this.messageHandlers.set(type, handler);\n }\n\n /**\n * Register default message handlers\n */\n private registerDefaultMessageHandlers(): void {\n // Handle status requests\n this.registerMessageHandler(MessageType.STATUS, async (message) => {\n await this.sendMessage({\n id: `${Date.now()}`,\n type: MessageType.STATUS,\n from: this.config.id!,\n to: message.from,\n timestamp: new Date(),\n correlationId: message.id,\n payload: {\n agentId: this.config.id,\n status: this._state.status,\n currentTask: this._state.currentTask?.id,\n },\n });\n });\n }\n\n // ============================================================================\n // Trajectory Tracking\n // ============================================================================\n\n /**\n * Set the trajectory tracker for this agent\n *\n * @param tracker - The trajectory tracker instance\n */\n setTrajectoryTracker(tracker: TrajectoryTracker): void {\n this.trajectoryTracker = tracker;\n }\n\n /**\n * Enable or disable auto-tracking of trajectories\n *\n * @param enabled - Whether to auto-track\n */\n setAutoTrackTrajectories(enabled: boolean): void {\n this.autoTrackTrajectories = enabled;\n }\n\n /**\n * Start tracking a task trajectory\n *\n * @param taskId - The task ID to track\n * @param metadata - Optional metadata\n * @returns The trajectory ID\n */\n protected startTrajectory(\n taskId: string,\n metadata: Record<string, unknown> = {}\n ): string | null {\n if (!this.trajectoryTracker?.isEnabled()) {\n return null;\n }\n\n this.currentTrajectoryId = this.trajectoryTracker.startTrajectory(taskId, {\n ...metadata,\n agentId: this.config.id,\n agentType: this.config.type,\n agentName: this.config.name,\n });\n\n return this.currentTrajectoryId;\n }\n\n /**\n * Record a step in the current trajectory\n *\n * @param action - The action taken\n * @param observation - The observation/result\n * @param confidence - Optional confidence score (0-1)\n * @param metadata - Optional step metadata\n */\n protected recordStep(\n action: string,\n observation: string,\n confidence?: number,\n metadata?: Record<string, unknown>\n ): void {\n if (!this.trajectoryTracker || !this.currentTrajectoryId) {\n return;\n }\n\n this.trajectoryTracker.recordStep(this.currentTrajectoryId, {\n action,\n observation,\n confidence,\n metadata,\n });\n }\n\n /**\n * Complete the current trajectory\n *\n * @param outcome - The task outcome\n * @param metadata - Optional final metadata\n * @returns The stored trajectory ID, or null\n */\n protected async completeTrajectory(\n outcome: 'success' | 'failure' | 'partial',\n metadata: Record<string, unknown> = {}\n ): Promise<string | null> {\n if (!this.trajectoryTracker || !this.currentTrajectoryId) {\n return null;\n }\n\n const storedId = await this.trajectoryTracker.completeTrajectory(\n this.currentTrajectoryId,\n outcome,\n metadata\n );\n\n this.currentTrajectoryId = null;\n return storedId;\n }\n\n /**\n * Abort the current trajectory\n *\n * @param reason - The reason for aborting\n */\n protected abortTrajectory(reason: string): void {\n if (!this.trajectoryTracker || !this.currentTrajectoryId) {\n return;\n }\n\n this.trajectoryTracker.abortTrajectory(this.currentTrajectoryId, reason);\n this.currentTrajectoryId = null;\n }\n\n /**\n * Check if trajectory tracking is active\n */\n isTrackingTrajectory(): boolean {\n return this.currentTrajectoryId !== null;\n }\n\n /**\n * Get current trajectory progress\n */\n getTrajectoryProgress(): {\n stepCount: number;\n duration: number;\n lastStep?: TrajectoryStep;\n } | null {\n if (!this.trajectoryTracker || !this.currentTrajectoryId) {\n return null;\n }\n\n return this.trajectoryTracker.getProgress(this.currentTrajectoryId);\n }\n\n // ============================================================================\n // Claude-Flow Integration\n // ============================================================================\n\n /**\n * Run a claude-flow hook\n */\n protected async runClaudeFlowHook(\n hookType: 'pre-task' | 'post-task' | 'post-edit',\n task: AgentTask,\n result?: AgentResult\n ): Promise<void> {\n if (!this.config.claudeFlow?.enabled) {\n return;\n }\n\n const namespace = this.config.claudeFlow.namespace ?? 'knowledge-graph';\n\n this.logger.debug(`Running claude-flow hook: ${hookType}`, {\n namespace,\n taskId: task.id,\n });\n\n // Generate the hook command that would be run\n const hookCommand = this.generateHookCommand(hookType, task, result);\n\n this.logger.trace('Claude-flow hook command', { command: hookCommand });\n\n // In production, this would execute via child_process or MCP\n // For now, we just log the intent\n }\n\n /**\n * Generate claude-flow hook command\n */\n private generateHookCommand(\n hookType: 'pre-task' | 'post-task' | 'post-edit',\n task: AgentTask,\n result?: AgentResult\n ): string {\n const namespace = this.config.claudeFlow?.namespace ?? 'knowledge-graph';\n\n switch (hookType) {\n case 'pre-task':\n return `claude-flow hooks pre-task --description \"${task.description}\"`;\n\n case 'post-task':\n return `claude-flow hooks post-task --task-id \"${task.id}\"`;\n\n case 'post-edit':\n return `claude-flow hooks post-edit --memory-key \"${namespace}/agent/${this.config.id}/task/${task.id}\"`;\n\n default:\n return '';\n }\n }\n\n /**\n * Store result in claude-flow memory\n */\n protected async storeInMemory(key: string, value: unknown): Promise<void> {\n if (!this.config.claudeFlow?.enabled) {\n return;\n }\n\n const namespace = this.config.claudeFlow.namespace ?? 'knowledge-graph';\n\n this.logger.debug('Storing in claude-flow memory', { namespace, key });\n\n // This would call the MCP memory_usage tool\n // For now, just log the intent\n this.logger.trace('Memory store', {\n action: 'store',\n namespace,\n key,\n value: JSON.stringify(value).slice(0, 100),\n });\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create a task with defaults\n */\nexport function createTask(\n description: string,\n options?: Partial<Omit<AgentTask, 'id' | 'description' | 'createdAt'>>\n): AgentTask {\n return {\n id: createTaskId(),\n description,\n priority: options?.priority ?? TaskPriority.MEDIUM,\n input: options?.input ?? {},\n expectedOutput: options?.expectedOutput,\n dependencies: options?.dependencies,\n timeout: options?.timeout,\n metadata: options?.metadata,\n createdAt: new Date(),\n deadline: options?.deadline,\n };\n}\n\n/**\n * Type guard for checking if an object is an AgentResult\n */\nexport function isAgentResult(obj: unknown): obj is AgentResult {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n 'success' in obj &&\n typeof (obj as AgentResult).success === 'boolean'\n );\n}\n\n/**\n * Type guard for checking if an object is an AgentError\n */\nexport function isAgentError(obj: unknown): obj is AgentError {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n 'code' in obj &&\n 'message' in obj &&\n typ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AU,SAAS,YAAY,aAAa;AAAA,IAC5C,OAAO,SAAS,SAAS,CAAA;AAAA,IACzB,gBAAgB,SAAS;AAAA,IACzB,cAAc,SAAS;AAAA,IACvB,SAAS,SAAS;AAAA,IAClB,UAAU,SAAS;AAAA,IACnB,+BAAe,KAAA;AAAA,IACf,UAAU,SAAS;AAAA,EAAA;AAEvB;AAKO,SAAS,cAAc,KAAkC;AAC9D,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,aAAa,OACb,OAAQ,IAAoB,YAAY;AAE5C;AAKO,SAAS,aAAa,KAAiC;AAC5D,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,aAAa,OACb,OAAQ,IAAmB,SAAS,YACpC,OAAQ,IAAmB,YAAY;AAE3C;"}
|
|
@@ -7,7 +7,7 @@ import { analyzeDocs } from "../../generators/docs-analyzer.js";
|
|
|
7
7
|
import { validateProjectRoot } from "../../core/security.js";
|
|
8
8
|
function createAnalyzeCommand() {
|
|
9
9
|
const command = new Command("analyze");
|
|
10
|
-
command.description("Analyze and migrate docs to knowledge graph structure").option("-p, --path <path>", "Project root path", ".").option("-s, --source <dir>", "Source docs directory", "docs").option("-t, --target <dir>", "Target directory", "docs
|
|
10
|
+
command.description("Analyze and migrate docs to knowledge graph structure").option("-p, --path <path>", "Project root path", ".").option("-s, --source <dir>", "Source docs directory", "docs").option("-t, --target <dir>", "Target directory", "docs").option("--use-claude-flow", "Use claude-flow for deep analysis").option("--no-moc", "Skip MOC (Map of Content) generation").option("--no-link-original", "Do not link back to original docs").option("--max-depth <n>", "Maximum analysis depth", "3").option("--dry-run", "Show what would be done without making changes").option("-v, --verbose", "Verbose output").action(async (options) => {
|
|
11
11
|
const spinner = ora("Analyzing documentation...").start();
|
|
12
12
|
try {
|
|
13
13
|
const projectRoot = validateProjectRoot(options.path);
|
|
@@ -119,7 +119,7 @@ function createAnalyzeCommand() {
|
|
|
119
119
|
process.exit(1);
|
|
120
120
|
}
|
|
121
121
|
});
|
|
122
|
-
command.command("deep").description("Deep analysis using claude-flow agents for comprehensive knowledge extraction").option("-p, --path <path>", "Project root path", ".").option("-s, --source <dir>", "Source docs directory", "docs").option("-t, --target <dir>", "Target directory", "docs
|
|
122
|
+
command.command("deep").description("Deep analysis using claude-flow agents for comprehensive knowledge extraction").option("-p, --path <path>", "Project root path", ".").option("-s, --source <dir>", "Source docs directory", "docs").option("-t, --target <dir>", "Target directory", "docs").option("--agents <n>", "Number of parallel agents", "3").action(async (options) => {
|
|
123
123
|
const spinner = ora("Initializing deep analysis with claude-flow...").start();
|
|
124
124
|
try {
|
|
125
125
|
const projectRoot = validateProjectRoot(options.path);
|
|
@@ -184,7 +184,7 @@ function createAnalyzeCommand() {
|
|
|
184
184
|
}
|
|
185
185
|
const result = await analyzeDocs({
|
|
186
186
|
sourceDir,
|
|
187
|
-
targetDir: "docs
|
|
187
|
+
targetDir: "docs",
|
|
188
188
|
projectRoot,
|
|
189
189
|
useClaudeFlow: false,
|
|
190
190
|
createMOC: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analyze.js","sources":["../../../src/cli/commands/analyze.ts"],"sourcesContent":["/**\n * Analyze Command\n *\n * Advanced documentation analyzer using claude-flow for deep analysis\n * and creating proper knowledge graph documentation structure.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { analyzeDocs } from '../../generators/docs-analyzer.js';\nimport { validateProjectRoot } from '../../core/security.js';\n\n/**\n * Create analyze command\n */\nexport function createAnalyzeCommand(): Command {\n const command = new Command('analyze');\n\n command\n .description('Analyze and migrate docs to knowledge graph structure')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-s, --source <dir>', 'Source docs directory', 'docs')\n .option('-t, --target <dir>', 'Target directory', 'docs-nn')\n .option('--use-claude-flow', 'Use claude-flow for deep analysis')\n .option('--no-moc', 'Skip MOC (Map of Content) generation')\n .option('--no-link-original', 'Do not link back to original docs')\n .option('--max-depth <n>', 'Maximum analysis depth', '3')\n .option('--dry-run', 'Show what would be done without making changes')\n .option('-v, --verbose', 'Verbose output')\n .action(async (options) => {\n const spinner = ora('Analyzing documentation...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const sourceDir = options.source;\n const targetDir = options.target;\n\n // Check source exists\n if (!existsSync(join(projectRoot, sourceDir))) {\n spinner.fail(`Source directory not found: ${sourceDir}`);\n console.log(chalk.gray(' Specify source with --source <dir>'));\n process.exit(1);\n }\n\n // Check if target already exists\n if (existsSync(join(projectRoot, targetDir)) && !options.dryRun) {\n spinner.warn(`Target directory exists: ${targetDir}`);\n console.log(chalk.yellow(' Files may be overwritten. Use --dry-run to preview.'));\n }\n\n if (options.dryRun) {\n spinner.text = 'Analyzing documentation (dry run)...';\n }\n\n if (options.useClaudeFlow) {\n spinner.text = 'Analyzing with claude-flow (deep analysis)...';\n }\n\n const result = await analyzeDocs({\n sourceDir,\n targetDir,\n projectRoot,\n useClaudeFlow: options.useClaudeFlow,\n createMOC: options.moc !== false,\n linkOriginal: options.linkOriginal !== false,\n maxDepth: parseInt(options.maxDepth, 10),\n dryRun: options.dryRun,\n verbose: options.verbose,\n });\n\n if (result.success) {\n if (options.dryRun) {\n spinner.succeed('Dry run complete!');\n } else {\n spinner.succeed('Documentation analyzed and migrated!');\n }\n } else {\n spinner.warn('Analysis completed with errors');\n }\n\n // Display results\n console.log();\n console.log(chalk.cyan.bold(' Analysis Results'));\n console.log(chalk.gray(' ─────────────────────────────────────'));\n console.log();\n console.log(chalk.white(' Summary:'));\n console.log(chalk.gray(` Source: ${sourceDir}/`));\n console.log(chalk.gray(` Target: ${targetDir}/`));\n console.log(chalk.green(` Files analyzed: ${result.filesAnalyzed}`));\n console.log(chalk.green(` Files created: ${result.filesCreated}`));\n console.log(chalk.blue(` MOC files: ${result.mocFilesCreated}`));\n\n // Category breakdown\n if (result.structure.size > 0) {\n console.log();\n console.log(chalk.white(' Categories:'));\n for (const [category, docs] of result.structure) {\n console.log(chalk.cyan(` ${category.padEnd(15)}`), chalk.gray(`${docs.length} docs`));\n }\n }\n\n // Show sample analyzed documents\n if (result.analyzed.length > 0 && options.verbose) {\n console.log();\n console.log(chalk.white(' Sample documents:'));\n result.analyzed.slice(0, 5).forEach(doc => {\n console.log(chalk.gray(` ${doc.originalPath}`));\n console.log(chalk.cyan(` → ${doc.newPath}`) + chalk.gray(` [${doc.type}]`));\n if (doc.tags.length > 0) {\n console.log(chalk.gray(` tags: ${doc.tags.slice(0, 5).map(t => `#${t}`).join(' ')}`));\n }\n });\n if (result.analyzed.length > 5) {\n console.log(chalk.gray(` ... and ${result.analyzed.length - 5} more`));\n }\n }\n\n // Show errors\n if (result.errors.length > 0) {\n console.log();\n console.log(chalk.red(' Errors:'));\n result.errors.slice(0, 5).forEach(err => {\n console.log(chalk.gray(` - ${err}`));\n });\n if (result.errors.length > 5) {\n console.log(chalk.gray(` ... and ${result.errors.length - 5} more`));\n }\n }\n\n // Research needed summary\n const researchDocs = result.analyzed.filter(d => d.researchNeeded.length > 0);\n const todoDocs = result.analyzed.filter(d => d.todos.length > 0);\n\n if (researchDocs.length > 0 || todoDocs.length > 0) {\n console.log();\n console.log(chalk.yellow(' Attention Needed:'));\n if (researchDocs.length > 0) {\n console.log(chalk.yellow(` 📚 ${researchDocs.length} docs need research`));\n }\n if (todoDocs.length > 0) {\n console.log(chalk.yellow(` ✏️ ${todoDocs.length} docs have TODOs`));\n }\n }\n\n // Next steps\n if (!options.dryRun && result.filesCreated > 0) {\n console.log();\n console.log(chalk.cyan(' Next steps:'));\n console.log(chalk.white(` 1. Review ${targetDir}/MOC.md (Master Index)`));\n console.log(chalk.white(` 2. Check ${targetDir}/PRIMITIVES.md`));\n console.log(chalk.white(` 3. Run: kg graph --docs ${targetDir}`));\n console.log(chalk.white(` 4. Run: kg stats --docs ${targetDir}`));\n if (researchDocs.length > 0) {\n console.log(chalk.white(` 5. Address research items in flagged docs`));\n }\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Analysis failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // Deep analyze subcommand (uses claude-flow agents)\n command\n .command('deep')\n .description('Deep analysis using claude-flow agents for comprehensive knowledge extraction')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-s, --source <dir>', 'Source docs directory', 'docs')\n .option('-t, --target <dir>', 'Target directory', 'docs-nn')\n .option('--agents <n>', 'Number of parallel agents', '3')\n .action(async (options) => {\n const spinner = ora('Initializing deep analysis with claude-flow...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const sourceDir = options.source;\n const targetDir = options.target;\n\n // Check source exists\n if (!existsSync(join(projectRoot, sourceDir))) {\n spinner.fail(`Source directory not found: ${sourceDir}`);\n process.exit(1);\n }\n\n spinner.text = 'Running claude-flow deep analysis...';\n\n // Run deep analysis with claude-flow\n const result = await analyzeDocs({\n sourceDir,\n targetDir,\n projectRoot,\n useClaudeFlow: true,\n createMOC: true,\n linkOriginal: true,\n maxDepth: 5,\n dryRun: false,\n verbose: true,\n });\n\n if (result.success) {\n spinner.succeed('Deep analysis complete!');\n } else {\n spinner.warn('Deep analysis completed with some errors');\n }\n\n console.log();\n console.log(chalk.cyan.bold(' Deep Analysis Results'));\n console.log(chalk.gray(' ─────────────────────────────────────'));\n console.log(chalk.green(` Documents analyzed: ${result.filesAnalyzed}`));\n console.log(chalk.green(` Knowledge docs: ${result.filesCreated}`));\n console.log(chalk.blue(` Index files (MOC): ${result.mocFilesCreated}`));\n console.log(chalk.gray(` Categories: ${result.structure.size}`));\n\n // Research summary\n const totalResearch = result.analyzed.reduce((sum, d) => sum + d.researchNeeded.length, 0);\n const totalTodos = result.analyzed.reduce((sum, d) => sum + d.todos.length, 0);\n\n console.log();\n console.log(chalk.white(' Knowledge extraction:'));\n console.log(chalk.cyan(` Research areas: ${totalResearch}`));\n console.log(chalk.cyan(` TODOs found: ${totalTodos}`));\n console.log(chalk.cyan(` Concepts: ${result.analyzed.reduce((sum, d) => sum + d.concepts.length, 0)}`));\n console.log(chalk.cyan(` Cross-refs: ${result.analyzed.reduce((sum, d) => sum + d.related.length, 0)}`));\n\n console.log();\n console.log(chalk.white(` Output: ${targetDir}/`));\n console.log(chalk.gray(` MOC.md Master index`));\n console.log(chalk.gray(` PRIMITIVES.md Core building blocks`));\n console.log(chalk.gray(` */\\_MOC.md Category indexes`));\n console.log();\n\n } catch (error) {\n spinner.fail('Deep analysis failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // Report subcommand\n command\n .command('report')\n .description('Generate analysis report without creating files')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-s, --source <dir>', 'Source docs directory', 'docs')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n const spinner = ora('Generating analysis report...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const sourceDir = options.source;\n\n if (!existsSync(join(projectRoot, sourceDir))) {\n spinner.fail(`Source directory not found: ${sourceDir}`);\n process.exit(1);\n }\n\n const result = await analyzeDocs({\n sourceDir,\n targetDir: 'docs-nn',\n projectRoot,\n useClaudeFlow: false,\n createMOC: false,\n linkOriginal: false,\n dryRun: true,\n verbose: false,\n });\n\n spinner.succeed('Report generated!');\n\n if (options.json) {\n // JSON output\n const report = {\n summary: {\n totalDocs: result.filesAnalyzed,\n categories: Object.fromEntries(result.structure),\n },\n documents: result.analyzed.map(d => ({\n original: d.originalPath,\n target: d.newPath,\n type: d.type,\n category: d.category,\n tags: d.tags,\n concepts: d.concepts,\n researchNeeded: d.researchNeeded,\n todos: d.todos,\n })),\n researchAreas: result.analyzed\n .flatMap(d => d.researchNeeded.map(r => ({ doc: d.title, area: r }))),\n todos: result.analyzed\n .flatMap(d => d.todos.map(t => ({ doc: d.title, todo: t }))),\n };\n console.log(JSON.stringify(report, null, 2));\n } else {\n // Human-readable output\n console.log();\n console.log(chalk.cyan.bold(' Documentation Analysis Report'));\n console.log(chalk.gray(' ─────────────────────────────────────'));\n console.log();\n console.log(chalk.white(` Total documents: ${result.filesAnalyzed}`));\n console.log();\n\n // Type breakdown\n const byType = new Map<string, number>();\n result.analyzed.forEach(d => {\n byType.set(d.type, (byType.get(d.type) || 0) + 1);\n });\n\n console.log(chalk.white(' By Type:'));\n for (const [type, count] of byType) {\n const bar = '█'.repeat(Math.ceil(count / result.filesAnalyzed * 20));\n console.log(chalk.cyan(` ${type.padEnd(12)} ${bar} ${count}`));\n }\n console.log();\n\n // Category breakdown\n console.log(chalk.white(' By Category:'));\n for (const [category, docs] of result.structure) {\n const bar = '█'.repeat(Math.ceil(docs.length / result.filesAnalyzed * 20));\n console.log(chalk.cyan(` ${category.padEnd(12)} ${bar} ${docs.length}`));\n }\n console.log();\n\n // Issues\n const withResearch = result.analyzed.filter(d => d.researchNeeded.length > 0);\n const withTodos = result.analyzed.filter(d => d.todos.length > 0);\n\n console.log(chalk.white(' Areas Needing Attention:'));\n console.log(chalk.yellow(` 📚 Research needed: ${withResearch.length} docs`));\n console.log(chalk.yellow(` ✏️ With TODOs: ${withTodos.length} docs`));\n console.log();\n\n // Top research areas\n if (withResearch.length > 0) {\n console.log(chalk.white(' Top Research Areas:'));\n withResearch.slice(0, 5).forEach(d => {\n console.log(chalk.gray(` ${d.title}:`));\n d.researchNeeded.slice(0, 2).forEach(r => {\n console.log(chalk.yellow(` - ${r.slice(0, 60)}...`));\n });\n });\n console.log();\n }\n\n console.log(chalk.cyan(' Run `kg analyze` to migrate documentation'));\n console.log();\n }\n\n } catch (error) {\n spinner.fail('Report generation failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n return command;\n}\n"],"names":[],"mappings":";;;;;;;AAkBO,SAAS,uBAAgC;AAC9C,QAAM,UAAU,IAAI,QAAQ,SAAS;AAErC,UACG,YAAY,uDAAuD,EACnE,OAAO,qBAAqB,qBAAqB,GAAG,EACpD,OAAO,sBAAsB,yBAAyB,MAAM,EAC5D,OAAO,sBAAsB,oBAAoB,SAAS,EAC1D,OAAO,qBA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command\n *\n * Advanced documentation analyzer using claude-flow for deep analysis\n * and creating proper knowledge graph documentation structure.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { analyzeDocs } from '../../generators/docs-analyzer.js';\nimport { validateProjectRoot } from '../../core/security.js';\n\n/**\n * Create analyze command\n */\nexport function createAnalyzeCommand(): Command {\n const command = new Command('analyze');\n\n command\n .description('Analyze and migrate docs to knowledge graph structure')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-s, --source <dir>', 'Source docs directory', 'docs')\n .option('-t, --target <dir>', 'Target directory', 'docs')\n .option('--use-claude-flow', 'Use claude-flow for deep analysis')\n .option('--no-moc', 'Skip MOC (Map of Content) generation')\n .option('--no-link-original', 'Do not link back to original docs')\n .option('--max-depth <n>', 'Maximum analysis depth', '3')\n .option('--dry-run', 'Show what would be done without making changes')\n .option('-v, --verbose', 'Verbose output')\n .action(async (options) => {\n const spinner = ora('Analyzing documentation...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const sourceDir = options.source;\n const targetDir = options.target;\n\n // Check source exists\n if (!existsSync(join(projectRoot, sourceDir))) {\n spinner.fail(`Source directory not found: ${sourceDir}`);\n console.log(chalk.gray(' Specify source with --source <dir>'));\n process.exit(1);\n }\n\n // Check if target already exists\n if (existsSync(join(projectRoot, targetDir)) && !options.dryRun) {\n spinner.warn(`Target directory exists: ${targetDir}`);\n console.log(chalk.yellow(' Files may be overwritten. Use --dry-run to preview.'));\n }\n\n if (options.dryRun) {\n spinner.text = 'Analyzing documentation (dry run)...';\n }\n\n if (options.useClaudeFlow) {\n spinner.text = 'Analyzing with claude-flow (deep analysis)...';\n }\n\n const result = await analyzeDocs({\n sourceDir,\n targetDir,\n projectRoot,\n useClaudeFlow: options.useClaudeFlow,\n createMOC: options.moc !== false,\n linkOriginal: options.linkOriginal !== false,\n maxDepth: parseInt(options.maxDepth, 10),\n dryRun: options.dryRun,\n verbose: options.verbose,\n });\n\n if (result.success) {\n if (options.dryRun) {\n spinner.succeed('Dry run complete!');\n } else {\n spinner.succeed('Documentation analyzed and migrated!');\n }\n } else {\n spinner.warn('Analysis completed with errors');\n }\n\n // Display results\n console.log();\n console.log(chalk.cyan.bold(' Analysis Results'));\n console.log(chalk.gray(' ─────────────────────────────────────'));\n console.log();\n console.log(chalk.white(' Summary:'));\n console.log(chalk.gray(` Source: ${sourceDir}/`));\n console.log(chalk.gray(` Target: ${targetDir}/`));\n console.log(chalk.green(` Files analyzed: ${result.filesAnalyzed}`));\n console.log(chalk.green(` Files created: ${result.filesCreated}`));\n console.log(chalk.blue(` MOC files: ${result.mocFilesCreated}`));\n\n // Category breakdown\n if (result.structure.size > 0) {\n console.log();\n console.log(chalk.white(' Categories:'));\n for (const [category, docs] of result.structure) {\n console.log(chalk.cyan(` ${category.padEnd(15)}`), chalk.gray(`${docs.length} docs`));\n }\n }\n\n // Show sample analyzed documents\n if (result.analyzed.length > 0 && options.verbose) {\n console.log();\n console.log(chalk.white(' Sample documents:'));\n result.analyzed.slice(0, 5).forEach(doc => {\n console.log(chalk.gray(` ${doc.originalPath}`));\n console.log(chalk.cyan(` → ${doc.newPath}`) + chalk.gray(` [${doc.type}]`));\n if (doc.tags.length > 0) {\n console.log(chalk.gray(` tags: ${doc.tags.slice(0, 5).map(t => `#${t}`).join(' ')}`));\n }\n });\n if (result.analyzed.length > 5) {\n console.log(chalk.gray(` ... and ${result.analyzed.length - 5} more`));\n }\n }\n\n // Show errors\n if (result.errors.length > 0) {\n console.log();\n console.log(chalk.red(' Errors:'));\n result.errors.slice(0, 5).forEach(err => {\n console.log(chalk.gray(` - ${err}`));\n });\n if (result.errors.length > 5) {\n console.log(chalk.gray(` ... and ${result.errors.length - 5} more`));\n }\n }\n\n // Research needed summary\n const researchDocs = result.analyzed.filter(d => d.researchNeeded.length > 0);\n const todoDocs = result.analyzed.filter(d => d.todos.length > 0);\n\n if (researchDocs.length > 0 || todoDocs.length > 0) {\n console.log();\n console.log(chalk.yellow(' Attention Needed:'));\n if (researchDocs.length > 0) {\n console.log(chalk.yellow(` 📚 ${researchDocs.length} docs need research`));\n }\n if (todoDocs.length > 0) {\n console.log(chalk.yellow(` ✏️ ${todoDocs.length} docs have TODOs`));\n }\n }\n\n // Next steps\n if (!options.dryRun && result.filesCreated > 0) {\n console.log();\n console.log(chalk.cyan(' Next steps:'));\n console.log(chalk.white(` 1. Review ${targetDir}/MOC.md (Master Index)`));\n console.log(chalk.white(` 2. Check ${targetDir}/PRIMITIVES.md`));\n console.log(chalk.white(` 3. Run: kg graph --docs ${targetDir}`));\n console.log(chalk.white(` 4. Run: kg stats --docs ${targetDir}`));\n if (researchDocs.length > 0) {\n console.log(chalk.white(` 5. Address research items in flagged docs`));\n }\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Analysis failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // Deep analyze subcommand (uses claude-flow agents)\n command\n .command('deep')\n .description('Deep analysis using claude-flow agents for comprehensive knowledge extraction')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-s, --source <dir>', 'Source docs directory', 'docs')\n .option('-t, --target <dir>', 'Target directory', 'docs')\n .option('--agents <n>', 'Number of parallel agents', '3')\n .action(async (options) => {\n const spinner = ora('Initializing deep analysis with claude-flow...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const sourceDir = options.source;\n const targetDir = options.target;\n\n // Check source exists\n if (!existsSync(join(projectRoot, sourceDir))) {\n spinner.fail(`Source directory not found: ${sourceDir}`);\n process.exit(1);\n }\n\n spinner.text = 'Running claude-flow deep analysis...';\n\n // Run deep analysis with claude-flow\n const result = await analyzeDocs({\n sourceDir,\n targetDir,\n projectRoot,\n useClaudeFlow: true,\n createMOC: true,\n linkOriginal: true,\n maxDepth: 5,\n dryRun: false,\n verbose: true,\n });\n\n if (result.success) {\n spinner.succeed('Deep analysis complete!');\n } else {\n spinner.warn('Deep analysis completed with some errors');\n }\n\n console.log();\n console.log(chalk.cyan.bold(' Deep Analysis Results'));\n console.log(chalk.gray(' ─────────────────────────────────────'));\n console.log(chalk.green(` Documents analyzed: ${result.filesAnalyzed}`));\n console.log(chalk.green(` Knowledge docs: ${result.filesCreated}`));\n console.log(chalk.blue(` Index files (MOC): ${result.mocFilesCreated}`));\n console.log(chalk.gray(` Categories: ${result.structure.size}`));\n\n // Research summary\n const totalResearch = result.analyzed.reduce((sum, d) => sum + d.researchNeeded.length, 0);\n const totalTodos = result.analyzed.reduce((sum, d) => sum + d.todos.length, 0);\n\n console.log();\n console.log(chalk.white(' Knowledge extraction:'));\n console.log(chalk.cyan(` Research areas: ${totalResearch}`));\n console.log(chalk.cyan(` TODOs found: ${totalTodos}`));\n console.log(chalk.cyan(` Concepts: ${result.analyzed.reduce((sum, d) => sum + d.concepts.length, 0)}`));\n console.log(chalk.cyan(` Cross-refs: ${result.analyzed.reduce((sum, d) => sum + d.related.length, 0)}`));\n\n console.log();\n console.log(chalk.white(` Output: ${targetDir}/`));\n console.log(chalk.gray(` MOC.md Master index`));\n console.log(chalk.gray(` PRIMITIVES.md Core building blocks`));\n console.log(chalk.gray(` */\\_MOC.md Category indexes`));\n console.log();\n\n } catch (error) {\n spinner.fail('Deep analysis failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // Report subcommand\n command\n .command('report')\n .description('Generate analysis report without creating files')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-s, --source <dir>', 'Source docs directory', 'docs')\n .option('--json', 'Output as JSON')\n .action(async (options) => {\n const spinner = ora('Generating analysis report...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const sourceDir = options.source;\n\n if (!existsSync(join(projectRoot, sourceDir))) {\n spinner.fail(`Source directory not found: ${sourceDir}`);\n process.exit(1);\n }\n\n const result = await analyzeDocs({\n sourceDir,\n targetDir: 'docs',\n projectRoot,\n useClaudeFlow: false,\n createMOC: false,\n linkOriginal: false,\n dryRun: true,\n verbose: false,\n });\n\n spinner.succeed('Report generated!');\n\n if (options.json) {\n // JSON output\n const report = {\n summary: {\n totalDocs: result.filesAnalyzed,\n categories: Object.fromEntries(result.structure),\n },\n documents: result.analyzed.map(d => ({\n original: d.originalPath,\n target: d.newPath,\n type: d.type,\n category: d.category,\n tags: d.tags,\n concepts: d.concepts,\n researchNeeded: d.researchNeeded,\n todos: d.todos,\n })),\n researchAreas: result.analyzed\n .flatMap(d => d.researchNeeded.map(r => ({ doc: d.title, area: r }))),\n todos: result.analyzed\n .flatMap(d => d.todos.map(t => ({ doc: d.title, todo: t }))),\n };\n console.log(JSON.stringify(report, null, 2));\n } else {\n // Human-readable output\n console.log();\n console.log(chalk.cyan.bold(' Documentation Analysis Report'));\n console.log(chalk.gray(' ─────────────────────────────────────'));\n console.log();\n console.log(chalk.white(` Total documents: ${result.filesAnalyzed}`));\n console.log();\n\n // Type breakdown\n const byType = new Map<string, number>();\n result.analyzed.forEach(d => {\n byType.set(d.type, (byType.get(d.type) || 0) + 1);\n });\n\n console.log(chalk.white(' By Type:'));\n for (const [type, count] of byType) {\n const bar = '█'.repeat(Math.ceil(count / result.filesAnalyzed * 20));\n console.log(chalk.cyan(` ${type.padEnd(12)} ${bar} ${count}`));\n }\n console.log();\n\n // Category breakdown\n console.log(chalk.white(' By Category:'));\n for (const [category, docs] of result.structure) {\n const bar = '█'.repeat(Math.ceil(docs.length / result.filesAnalyzed * 20));\n console.log(chalk.cyan(` ${category.padEnd(12)} ${bar} ${docs.length}`));\n }\n console.log();\n\n // Issues\n const withResearch = result.analyzed.filter(d => d.researchNeeded.length > 0);\n const withTodos = result.analyzed.filter(d => d.todos.length > 0);\n\n console.log(chalk.white(' Areas Needing Attention:'));\n console.log(chalk.yellow(` 📚 Research needed: ${withResearch.length} docs`));\n console.log(chalk.yellow(` ✏️ With TODOs: ${withTodos.length} docs`));\n console.log();\n\n // Top research areas\n if (withResearch.length > 0) {\n console.log(chalk.white(' Top Research Areas:'));\n withResearch.slice(0, 5).forEach(d => {\n console.log(chalk.gray(` ${d.title}:`));\n d.researchNeeded.slice(0, 2).forEach(r => {\n console.log(chalk.yellow(` - ${r.slice(0, 60)}...`));\n });\n });\n console.log();\n }\n\n console.log(chalk.cyan(' Run `kg analyze` to migrate documentation'));\n console.log();\n }\n\n } catch (error) {\n spinner.fail('Report generation failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n return command;\n}\n"],"names":[],"mappings":";;;;;;;AAkBO,SAAS,uBAAgC;AAC9C,QAAM,UAAU,IAAI,QAAQ,SAAS;AAErC,UACG,YAAY,uDAAuD,EACnE,OAAO,qBAAqB,qBAAqB,GAAG,EACpD,OAAO,sBAAsB,yBAAyB,MAAM,EAC5D,OAAO,sBAAsB,oBAAoB,MAAM,EACvD,OAAO,qBAAqB,mCAAmC,EAC/D,OAAO,YAAY,sCAAsC,EACzD,OAAO,sBAAsB,mCAAmC,EAChE,OAAO,mBAAmB,0BAA0B,GAAG,EACvD,OAAO,aAAa,gDAAgD,EACpE,OAAO,iBAAiB,gBAAgB,EACxC,OAAO,OAAO,YAAY;AACzB,UAAM,UAAU,IAAI,4BAA4B,EAAE,MAAA;AAElD,QAAI;AACF,YAAM,cAAc,oBAAoB,QAAQ,IAAI;AACpD,YAAM,YAAY,QAAQ;AAC1B,YAAM,YAAY,QAAQ;AAG1B,UAAI,CAAC,WAAW,KAAK,aAAa,SAAS,CAAC,GAAG;AAC7C,gBAAQ,KAAK,+BAA+B,SAAS,EAAE;AACvD,gBAAQ,IAAI,MAAM,KAAK,sCAAsC,CAAC;AAC9D,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAGA,UAAI,WAAW,KAAK,aAAa,SAAS,CAAC,KAAK,CAAC,QAAQ,QAAQ;AAC/D,gBAAQ,KAAK,4BAA4B,SAAS,EAAE;AACpD,gBAAQ,IAAI,MAAM,OAAO,uDAAuD,CAAC;AAAA,MACnF;AAEA,UAAI,QAAQ,QAAQ;AAClB,gBAAQ,OAAO;AAAA,MAC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AK;AACxC,sBAAQ,IAAI,MAAM,OAAO,WAAW,EAAE,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC;AAAA,YAC1D,CAAC;AAAA,UACH,CAAC;AACD,kBAAQ,IAAA;AAAA,QACV;AAEA,gBAAQ,IAAI,MAAM,KAAK,6CAA6C,CAAC;AACrE,gBAAQ,IAAA;AAAA,MACV;AAAA,IAEF,SAAS,OAAO;AACd,cAAQ,KAAK,0BAA0B;AACvC,cAAQ,MAAM,MAAM,IAAI,OAAO,KAAK,CAAC,CAAC;AACtC,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;"}
|
|
@@ -8,7 +8,7 @@ import { validateProjectRoot } from "../../core/security.js";
|
|
|
8
8
|
function createConvertCommand() {
|
|
9
9
|
const command = new Command("convert");
|
|
10
10
|
command.description("Convert existing docs to weave-nn structure");
|
|
11
|
-
command.command("docs").description("Convert existing documentation
|
|
11
|
+
command.command("docs").description("Convert existing documentation with proper structure").option("-p, --path <path>", "Project root path", ".").option("-s, --source <dir>", "Source docs directory", "docs").option("-t, --target <dir>", "Target directory", "docs").option("--no-auto-category", "Disable auto-categorization").option("-f, --force", "Overwrite existing files").option("--dry-run", "Show what would be done without making changes").action(async (options) => {
|
|
12
12
|
const spinner = ora("Converting documentation...").start();
|
|
13
13
|
try {
|
|
14
14
|
const projectRoot = validateProjectRoot(options.path);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"convert.js","sources":["../../../src/cli/commands/convert.ts"],"sourcesContent":["/**\n * Convert Command\n *\n * Convert existing documentation to weave-nn structure.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport {\n convertDocs,\n addFrontmatter,\n validateFrontmatter,\n} from '../../generators/docs-convert.js';\nimport { validateProjectRoot, validateDocsPath } from '../../core/security.js';\n\n/**\n * Create convert command\n */\nexport function createConvertCommand(): Command {\n const command = new Command('convert');\n\n command\n .description('Convert existing docs to weave-nn structure');\n\n // Main convert subcommand\n command\n .command('docs')\n .description('Convert existing documentation to docs-nn/ with proper structure')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-s, --source <dir>', 'Source docs directory', 'docs')\n .option('-t, --target <dir>', 'Target directory', 'docs-nn')\n .option('--no-auto-category', 'Disable auto-categorization')\n .option('-f, --force', 'Overwrite existing files')\n .option('--dry-run', 'Show what would be done without making changes')\n .action(async (options) => {\n const spinner = ora('Converting documentation...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const sourceDir = options.source;\n const targetDir = options.target;\n\n // Check source exists\n if (!existsSync(join(projectRoot, sourceDir))) {\n spinner.fail(`Source directory not found: ${sourceDir}`);\n console.log(chalk.gray(' Specify source with --source <dir>'));\n process.exit(1);\n }\n\n if (options.dryRun) {\n spinner.text = 'Analyzing documentation (dry run)...';\n }\n\n const result = await convertDocs({\n sourceDir,\n targetDir,\n projectRoot,\n preserveOriginal: true,\n force: options.force,\n autoCategory: options.autoCategory !== false,\n dryRun: options.dryRun,\n });\n\n if (result.success) {\n if (options.dryRun) {\n spinner.succeed('Dry run complete!');\n } else {\n spinner.succeed('Documentation converted!');\n }\n } else {\n spinner.warn('Conversion completed with errors');\n }\n\n console.log();\n console.log(chalk.white(' Summary:'));\n console.log(chalk.gray(` Source: ${sourceDir}/`));\n console.log(chalk.gray(` Target: ${targetDir}/`));\n console.log(chalk.green(` Converted: ${result.filesConverted}`));\n console.log(chalk.yellow(` Skipped: ${result.filesSkipped}`));\n console.log(chalk.gray(` Total: ${result.filesProcessed}`));\n\n if (result.converted.length > 0 && result.converted.length <= 10) {\n console.log();\n console.log(chalk.white(' Converted files:'));\n result.converted.forEach(({ source, target, type }) => {\n console.log(chalk.gray(` ${source}`));\n console.log(chalk.cyan(` → ${target}`) + chalk.gray(` [${type}]`));\n });\n } else if (result.converted.length > 10) {\n console.log();\n console.log(chalk.white(' Sample conversions:'));\n result.converted.slice(0, 5).forEach(({ source, target, type }) => {\n console.log(chalk.gray(` ${source}`));\n console.log(chalk.cyan(` → ${target}`) + chalk.gray(` [${type}]`));\n });\n console.log(chalk.gray(` ... and ${result.converted.length - 5} more`));\n }\n\n if (result.errors.length > 0) {\n console.log();\n console.log(chalk.red(' Errors:'));\n result.errors.slice(0, 5).forEach(err => {\n console.log(chalk.gray(` - ${err}`));\n });\n if (result.errors.length > 5) {\n console.log(chalk.gray(` ... and ${result.errors.length - 5} more`));\n }\n }\n\n if (!options.dryRun && result.filesConverted > 0) {\n console.log();\n console.log(chalk.cyan('Next steps:'));\n console.log(chalk.white(` 1. Review ${targetDir}/ structure`));\n console.log(chalk.white(' 2. Run: kg graph --docs ' + targetDir));\n console.log(chalk.white(' 3. Run: kg stats'));\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Conversion failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n return command;\n}\n\n/**\n * Create frontmatter command\n */\nexport function createFrontmatterCommand(): Command {\n const command = new Command('frontmatter');\n\n command\n .description('Manage frontmatter in markdown files');\n\n // Add frontmatter\n command\n .command('add [target]')\n .description('Add frontmatter to files missing it')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-t, --type <type>', 'Node type (concept, technical, feature, service, guide, standard, integration)')\n .option('-s, --status <status>', 'Status (draft, active, deprecated, archived)', 'active')\n .option('--tags <tags>', 'Comma-separated tags')\n .option('-f, --force', 'Overwrite existing frontmatter')\n .option('--dry-run', 'Show what would be done')\n .action(async (target, options) => {\n const spinner = ora('Adding frontmatter...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const targetPath = target || 'docs';\n\n const tags = options.tags ? options.tags.split(',').map((t: string) => t.trim()) : [];\n\n const result = await addFrontmatter({\n target: targetPath,\n projectRoot,\n type: options.type,\n status: options.status,\n tags,\n force: options.force,\n dryRun: options.dryRun,\n });\n\n if (result.success) {\n spinner.succeed(options.dryRun ? 'Dry run complete!' : 'Frontmatter added!');\n } else {\n spinner.warn('Completed with errors');\n }\n\n console.log();\n console.log(chalk.white(' Summary:'));\n console.log(chalk.green(` Updated: ${result.filesUpdated}`));\n console.log(chalk.yellow(` Skipped: ${result.filesSkipped}`));\n console.log(chalk.gray(` Total: ${result.filesProcessed}`));\n\n if (result.errors.length > 0) {\n console.log();\n console.log(chalk.red(' Errors:'));\n result.errors.forEach(err => {\n console.log(chalk.gray(` - ${err}`));\n });\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Failed to add frontmatter');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // Validate frontmatter\n command\n .command('validate [target]')\n .description('Validate frontmatter in markdown files')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (target, options) => {\n const spinner = ora('Validating frontmatter...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const targetPath = target || 'docs';\n\n const result = await validateFrontmatter(targetPath, projectRoot);\n\n spinner.succeed('Validation complete!');\n\n console.log();\n console.log(chalk.white(' Frontmatter Validation:'));\n console.log(chalk.green(` Valid: ${result.valid}`));\n console.log(chalk.red(` Invalid: ${result.invalid}`));\n console.log(chalk.yellow(` Missing: ${result.missing}`));\n\n if (result.issues.length > 0) {\n console.log();\n console.log(chalk.yellow(' Issues found:'));\n result.issues.slice(0, 10).forEach(({ file, issues }) => {\n console.log(chalk.white(` ${file}`));\n issues.forEach(issue => {\n console.log(chalk.gray(` - ${issue}`));\n });\n });\n if (result.issues.length > 10) {\n console.log(chalk.gray(` ... and ${result.issues.length - 10} more files`));\n }\n\n console.log();\n console.log(chalk.cyan('Fix with: ') + chalk.white('kg frontmatter add <target>'));\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Validation failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // Update frontmatter (force mode)\n command\n .command('update [target]')\n .description('Update/regenerate frontmatter (overwrites existing)')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-t, --type <type>', 'Force specific node type')\n .option('--dry-run', 'Show what would be done')\n .action(async (target, options) => {\n const spinner = ora('Updating frontmatter...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const targetPath = target || 'docs';\n\n const result = await addFrontmatter({\n target: targetPath,\n projectRoot,\n type: options.type,\n force: true,\n dryRun: options.dryRun,\n });\n\n if (result.success) {\n spinner.succeed(options.dryRun ? 'Dry run complete!' : 'Frontmatter updated!');\n } else {\n spinner.warn('Completed with errors');\n }\n\n console.log();\n console.log(chalk.green(` Updated: ${result.filesUpdated} files`));\n\n if (result.errors.length > 0) {\n console.log(chalk.red(` Errors: ${result.errors.length}`));\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Failed to update frontmatter');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n return command;\n}\n"],"names":[],"mappings":";;;;;;;AAqBO,SAAS,uBAAgC;AAC9C,QAAM,UAAU,IAAI,QAAQ,SAAS;AAErC,UACG,YAAY,6CAA6C;AAG5D,UACG,QAAQ,MAAM,EACd,YAAY,kEAAkE,EAC9E,OAAO,qBAAqB,qBAAqB,GAAG,EACpD,OAAO,sBAAsB,yBAAyB,MAAM,EAC5D,OAAO,sBAAsB,oBAAoB,SAAS,EAC1D,OAAO,sBAAsB,6BAA6B,EAC1D,OAAO,eAAe,0BAA0B,EAChD,OAAO,aAAa,gDAAgD,EACpE,OAAO,OAAO,YAAY;AACzB,UAAM,UAAU,IAAI,6BAA6B,EAAE,MAAA;AAEnD,QAAI;AACF,YAAM,cAAc,oBAAoB,QAAQ,IAAI;AACpD,YAAM,YAAY,QAAQ;AAC1B,YAAM,YAAY,QAAQ;AAG1B,UAAI,CAAC,WAAW,KAAK,aAAa,SAAS,CAAC,GAAG;AAC7C,gBAAQ,KAAK,+BAA+B,SAAS,EAAE;AACvD,gBAAQ,IAAI,MAAM,KAAK,sCAAsC,CAAC;AAC9D,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAEA,UAAI,QAAQ,QAAQ;AAClB,gBAAQ,OAAO;AAAA,MACj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M,MAAM,IAAI,OAAO,KAAK,CAAC,CAAC;AACtC,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"convert.js","sources":["../../../src/cli/commands/convert.ts"],"sourcesContent":["/**\n * Convert Command\n *\n * Convert existing documentation to weave-nn structure.\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport {\n convertDocs,\n addFrontmatter,\n validateFrontmatter,\n} from '../../generators/docs-convert.js';\nimport { validateProjectRoot, validateDocsPath } from '../../core/security.js';\n\n/**\n * Create convert command\n */\nexport function createConvertCommand(): Command {\n const command = new Command('convert');\n\n command\n .description('Convert existing docs to weave-nn structure');\n\n // Main convert subcommand\n command\n .command('docs')\n .description('Convert existing documentation with proper structure')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-s, --source <dir>', 'Source docs directory', 'docs')\n .option('-t, --target <dir>', 'Target directory', 'docs')\n .option('--no-auto-category', 'Disable auto-categorization')\n .option('-f, --force', 'Overwrite existing files')\n .option('--dry-run', 'Show what would be done without making changes')\n .action(async (options) => {\n const spinner = ora('Converting documentation...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const sourceDir = options.source;\n const targetDir = options.target;\n\n // Check source exists\n if (!existsSync(join(projectRoot, sourceDir))) {\n spinner.fail(`Source directory not found: ${sourceDir}`);\n console.log(chalk.gray(' Specify source with --source <dir>'));\n process.exit(1);\n }\n\n if (options.dryRun) {\n spinner.text = 'Analyzing documentation (dry run)...';\n }\n\n const result = await convertDocs({\n sourceDir,\n targetDir,\n projectRoot,\n preserveOriginal: true,\n force: options.force,\n autoCategory: options.autoCategory !== false,\n dryRun: options.dryRun,\n });\n\n if (result.success) {\n if (options.dryRun) {\n spinner.succeed('Dry run complete!');\n } else {\n spinner.succeed('Documentation converted!');\n }\n } else {\n spinner.warn('Conversion completed with errors');\n }\n\n console.log();\n console.log(chalk.white(' Summary:'));\n console.log(chalk.gray(` Source: ${sourceDir}/`));\n console.log(chalk.gray(` Target: ${targetDir}/`));\n console.log(chalk.green(` Converted: ${result.filesConverted}`));\n console.log(chalk.yellow(` Skipped: ${result.filesSkipped}`));\n console.log(chalk.gray(` Total: ${result.filesProcessed}`));\n\n if (result.converted.length > 0 && result.converted.length <= 10) {\n console.log();\n console.log(chalk.white(' Converted files:'));\n result.converted.forEach(({ source, target, type }) => {\n console.log(chalk.gray(` ${source}`));\n console.log(chalk.cyan(` → ${target}`) + chalk.gray(` [${type}]`));\n });\n } else if (result.converted.length > 10) {\n console.log();\n console.log(chalk.white(' Sample conversions:'));\n result.converted.slice(0, 5).forEach(({ source, target, type }) => {\n console.log(chalk.gray(` ${source}`));\n console.log(chalk.cyan(` → ${target}`) + chalk.gray(` [${type}]`));\n });\n console.log(chalk.gray(` ... and ${result.converted.length - 5} more`));\n }\n\n if (result.errors.length > 0) {\n console.log();\n console.log(chalk.red(' Errors:'));\n result.errors.slice(0, 5).forEach(err => {\n console.log(chalk.gray(` - ${err}`));\n });\n if (result.errors.length > 5) {\n console.log(chalk.gray(` ... and ${result.errors.length - 5} more`));\n }\n }\n\n if (!options.dryRun && result.filesConverted > 0) {\n console.log();\n console.log(chalk.cyan('Next steps:'));\n console.log(chalk.white(` 1. Review ${targetDir}/ structure`));\n console.log(chalk.white(' 2. Run: kg graph --docs ' + targetDir));\n console.log(chalk.white(' 3. Run: kg stats'));\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Conversion failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n return command;\n}\n\n/**\n * Create frontmatter command\n */\nexport function createFrontmatterCommand(): Command {\n const command = new Command('frontmatter');\n\n command\n .description('Manage frontmatter in markdown files');\n\n // Add frontmatter\n command\n .command('add [target]')\n .description('Add frontmatter to files missing it')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-t, --type <type>', 'Node type (concept, technical, feature, service, guide, standard, integration)')\n .option('-s, --status <status>', 'Status (draft, active, deprecated, archived)', 'active')\n .option('--tags <tags>', 'Comma-separated tags')\n .option('-f, --force', 'Overwrite existing frontmatter')\n .option('--dry-run', 'Show what would be done')\n .action(async (target, options) => {\n const spinner = ora('Adding frontmatter...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const targetPath = target || 'docs';\n\n const tags = options.tags ? options.tags.split(',').map((t: string) => t.trim()) : [];\n\n const result = await addFrontmatter({\n target: targetPath,\n projectRoot,\n type: options.type,\n status: options.status,\n tags,\n force: options.force,\n dryRun: options.dryRun,\n });\n\n if (result.success) {\n spinner.succeed(options.dryRun ? 'Dry run complete!' : 'Frontmatter added!');\n } else {\n spinner.warn('Completed with errors');\n }\n\n console.log();\n console.log(chalk.white(' Summary:'));\n console.log(chalk.green(` Updated: ${result.filesUpdated}`));\n console.log(chalk.yellow(` Skipped: ${result.filesSkipped}`));\n console.log(chalk.gray(` Total: ${result.filesProcessed}`));\n\n if (result.errors.length > 0) {\n console.log();\n console.log(chalk.red(' Errors:'));\n result.errors.forEach(err => {\n console.log(chalk.gray(` - ${err}`));\n });\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Failed to add frontmatter');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // Validate frontmatter\n command\n .command('validate [target]')\n .description('Validate frontmatter in markdown files')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (target, options) => {\n const spinner = ora('Validating frontmatter...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const targetPath = target || 'docs';\n\n const result = await validateFrontmatter(targetPath, projectRoot);\n\n spinner.succeed('Validation complete!');\n\n console.log();\n console.log(chalk.white(' Frontmatter Validation:'));\n console.log(chalk.green(` Valid: ${result.valid}`));\n console.log(chalk.red(` Invalid: ${result.invalid}`));\n console.log(chalk.yellow(` Missing: ${result.missing}`));\n\n if (result.issues.length > 0) {\n console.log();\n console.log(chalk.yellow(' Issues found:'));\n result.issues.slice(0, 10).forEach(({ file, issues }) => {\n console.log(chalk.white(` ${file}`));\n issues.forEach(issue => {\n console.log(chalk.gray(` - ${issue}`));\n });\n });\n if (result.issues.length > 10) {\n console.log(chalk.gray(` ... and ${result.issues.length - 10} more files`));\n }\n\n console.log();\n console.log(chalk.cyan('Fix with: ') + chalk.white('kg frontmatter add <target>'));\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Validation failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // Update frontmatter (force mode)\n command\n .command('update [target]')\n .description('Update/regenerate frontmatter (overwrites existing)')\n .option('-p, --path <path>', 'Project root path', '.')\n .option('-t, --type <type>', 'Force specific node type')\n .option('--dry-run', 'Show what would be done')\n .action(async (target, options) => {\n const spinner = ora('Updating frontmatter...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const targetPath = target || 'docs';\n\n const result = await addFrontmatter({\n target: targetPath,\n projectRoot,\n type: options.type,\n force: true,\n dryRun: options.dryRun,\n });\n\n if (result.success) {\n spinner.succeed(options.dryRun ? 'Dry run complete!' : 'Frontmatter updated!');\n } else {\n spinner.warn('Completed with errors');\n }\n\n console.log();\n console.log(chalk.green(` Updated: ${result.filesUpdated} files`));\n\n if (result.errors.length > 0) {\n console.log(chalk.red(` Errors: ${result.errors.length}`));\n }\n\n console.log();\n\n } catch (error) {\n spinner.fail('Failed to update frontmatter');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n return command;\n}\n"],"names":[],"mappings":";;;;;;;AAqBO,SAAS,uBAAgC;AAC9C,QAAM,UAAU,IAAI,QAAQ,SAAS;AAErC,UACG,YAAY,6CAA6C;AAG5D,UACG,QAAQ,MAAM,EACd,YAAY,sDAAsD,EAClE,OAAO,qBAAqB,qBAAqB,GAAG,EACpD,OAAO,sBAAsB,yBAAyB,MAAM,EAC5D,OAAO,sBAAsB,oBAAoB,MAAM,EACvD,OAAO,sBAAsB,6BAA6B,EAC1D,OAAO,eAAe,0BAA0B,EACh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