@weavelogic/knowledge-graph-agent 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +290 -3
  2. package/dist/_virtual/index10.js +2 -2
  3. package/dist/_virtual/index6.js +2 -2
  4. package/dist/_virtual/index7.js +2 -2
  5. package/dist/_virtual/index8.js +2 -2
  6. package/dist/_virtual/index9.js +2 -2
  7. package/dist/audit/config.d.ts +150 -0
  8. package/dist/audit/config.d.ts.map +1 -0
  9. package/dist/audit/config.js +111 -0
  10. package/dist/audit/config.js.map +1 -0
  11. package/dist/audit/index.d.ts +38 -0
  12. package/dist/audit/index.d.ts.map +1 -0
  13. package/dist/audit/services/audit-chain.d.ts +276 -0
  14. package/dist/audit/services/audit-chain.d.ts.map +1 -0
  15. package/dist/audit/services/audit-chain.js +502 -0
  16. package/dist/audit/services/audit-chain.js.map +1 -0
  17. package/dist/audit/services/index.d.ts +11 -0
  18. package/dist/audit/services/index.d.ts.map +1 -0
  19. package/dist/audit/services/syndication.d.ts +334 -0
  20. package/dist/audit/services/syndication.d.ts.map +1 -0
  21. package/dist/audit/services/syndication.js +589 -0
  22. package/dist/audit/services/syndication.js.map +1 -0
  23. package/dist/audit/types.d.ts +453 -0
  24. package/dist/audit/types.d.ts.map +1 -0
  25. package/dist/cli/commands/audit.d.ts +21 -0
  26. package/dist/cli/commands/audit.d.ts.map +1 -0
  27. package/dist/cli/commands/audit.js +621 -0
  28. package/dist/cli/commands/audit.js.map +1 -0
  29. package/dist/cli/commands/vector.d.ts +14 -0
  30. package/dist/cli/commands/vector.d.ts.map +1 -0
  31. package/dist/cli/commands/vector.js +429 -0
  32. package/dist/cli/commands/vector.js.map +1 -0
  33. package/dist/cli/commands/workflow.d.ts +12 -0
  34. package/dist/cli/commands/workflow.d.ts.map +1 -0
  35. package/dist/cli/commands/workflow.js +471 -0
  36. package/dist/cli/commands/workflow.js.map +1 -0
  37. package/dist/cli/index.d.ts.map +1 -1
  38. package/dist/cli/index.js +26 -0
  39. package/dist/cli/index.js.map +1 -1
  40. package/dist/database/schemas/index.d.ts +85 -0
  41. package/dist/database/schemas/index.d.ts.map +1 -0
  42. package/dist/index.d.ts +2 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +9 -0
  45. package/dist/index.js.map +1 -1
  46. package/dist/mcp-server/tools/audit/checkpoint.d.ts +58 -0
  47. package/dist/mcp-server/tools/audit/checkpoint.d.ts.map +1 -0
  48. package/dist/mcp-server/tools/audit/checkpoint.js +73 -0
  49. package/dist/mcp-server/tools/audit/checkpoint.js.map +1 -0
  50. package/dist/mcp-server/tools/audit/index.d.ts +53 -0
  51. package/dist/mcp-server/tools/audit/index.d.ts.map +1 -0
  52. package/dist/mcp-server/tools/audit/index.js +12 -0
  53. package/dist/mcp-server/tools/audit/index.js.map +1 -0
  54. package/dist/mcp-server/tools/audit/query.d.ts +58 -0
  55. package/dist/mcp-server/tools/audit/query.d.ts.map +1 -0
  56. package/dist/mcp-server/tools/audit/query.js +125 -0
  57. package/dist/mcp-server/tools/audit/query.js.map +1 -0
  58. package/dist/mcp-server/tools/audit/sync.d.ts +58 -0
  59. package/dist/mcp-server/tools/audit/sync.d.ts.map +1 -0
  60. package/dist/mcp-server/tools/audit/sync.js +126 -0
  61. package/dist/mcp-server/tools/audit/sync.js.map +1 -0
  62. package/dist/mcp-server/tools/index.d.ts +3 -0
  63. package/dist/mcp-server/tools/index.d.ts.map +1 -1
  64. package/dist/mcp-server/tools/registry.js +90 -0
  65. package/dist/mcp-server/tools/registry.js.map +1 -1
  66. package/dist/mcp-server/tools/vector/index.d.ts +12 -0
  67. package/dist/mcp-server/tools/vector/index.d.ts.map +1 -0
  68. package/dist/mcp-server/tools/vector/index.js +12 -0
  69. package/dist/mcp-server/tools/vector/index.js.map +1 -0
  70. package/dist/mcp-server/tools/vector/search.d.ts +41 -0
  71. package/dist/mcp-server/tools/vector/search.d.ts.map +1 -0
  72. package/dist/mcp-server/tools/vector/search.js +224 -0
  73. package/dist/mcp-server/tools/vector/search.js.map +1 -0
  74. package/dist/mcp-server/tools/vector/trajectory.d.ts +39 -0
  75. package/dist/mcp-server/tools/vector/trajectory.d.ts.map +1 -0
  76. package/dist/mcp-server/tools/vector/trajectory.js +170 -0
  77. package/dist/mcp-server/tools/vector/trajectory.js.map +1 -0
  78. package/dist/mcp-server/tools/vector/upsert.d.ts +44 -0
  79. package/dist/mcp-server/tools/vector/upsert.d.ts.map +1 -0
  80. package/dist/mcp-server/tools/vector/upsert.js +175 -0
  81. package/dist/mcp-server/tools/vector/upsert.js.map +1 -0
  82. package/dist/mcp-server/tools/workflow/index.d.ts +29 -0
  83. package/dist/mcp-server/tools/workflow/index.d.ts.map +1 -0
  84. package/dist/mcp-server/tools/workflow/index.js +12 -0
  85. package/dist/mcp-server/tools/workflow/index.js.map +1 -0
  86. package/dist/mcp-server/tools/workflow/list.d.ts +41 -0
  87. package/dist/mcp-server/tools/workflow/list.d.ts.map +1 -0
  88. package/dist/mcp-server/tools/workflow/list.js +195 -0
  89. package/dist/mcp-server/tools/workflow/list.js.map +1 -0
  90. package/dist/mcp-server/tools/workflow/start.d.ts +40 -0
  91. package/dist/mcp-server/tools/workflow/start.d.ts.map +1 -0
  92. package/dist/mcp-server/tools/workflow/start.js +165 -0
  93. package/dist/mcp-server/tools/workflow/start.js.map +1 -0
  94. package/dist/mcp-server/tools/workflow/status.d.ts +38 -0
  95. package/dist/mcp-server/tools/workflow/status.d.ts.map +1 -0
  96. package/dist/mcp-server/tools/workflow/status.js +97 -0
  97. package/dist/mcp-server/tools/workflow/status.js.map +1 -0
  98. package/dist/node_modules/ajv/dist/compile/index.js +1 -1
  99. package/dist/node_modules/ajv/dist/vocabularies/applicator/index.js +1 -1
  100. package/dist/node_modules/ajv/dist/vocabularies/core/index.js +1 -1
  101. package/dist/node_modules/ajv/dist/vocabularies/format/index.js +1 -1
  102. package/dist/node_modules/ajv/dist/vocabularies/validation/index.js +1 -1
  103. package/dist/vector/config.d.ts +300 -0
  104. package/dist/vector/config.d.ts.map +1 -0
  105. package/dist/vector/config.js +124 -0
  106. package/dist/vector/config.js.map +1 -0
  107. package/dist/vector/index.d.ts +50 -0
  108. package/dist/vector/index.d.ts.map +1 -0
  109. package/dist/vector/services/index.d.ts +13 -0
  110. package/dist/vector/services/index.d.ts.map +1 -0
  111. package/dist/vector/services/trajectory-tracker.d.ts +405 -0
  112. package/dist/vector/services/trajectory-tracker.d.ts.map +1 -0
  113. package/dist/vector/services/trajectory-tracker.js +445 -0
  114. package/dist/vector/services/trajectory-tracker.js.map +1 -0
  115. package/dist/vector/services/vector-store.d.ts +339 -0
  116. package/dist/vector/services/vector-store.d.ts.map +1 -0
  117. package/dist/vector/services/vector-store.js +748 -0
  118. package/dist/vector/services/vector-store.js.map +1 -0
  119. package/dist/vector/types.d.ts +677 -0
  120. package/dist/vector/types.d.ts.map +1 -0
  121. package/dist/workflow/adapters/goap-adapter.d.ts +196 -0
  122. package/dist/workflow/adapters/goap-adapter.d.ts.map +1 -0
  123. package/dist/workflow/adapters/goap-adapter.js +706 -0
  124. package/dist/workflow/adapters/goap-adapter.js.map +1 -0
  125. package/dist/workflow/adapters/index.d.ts +10 -0
  126. package/dist/workflow/adapters/index.d.ts.map +1 -0
  127. package/dist/workflow/config.d.ts +135 -0
  128. package/dist/workflow/config.d.ts.map +1 -0
  129. package/dist/workflow/config.js +92 -0
  130. package/dist/workflow/config.js.map +1 -0
  131. package/dist/workflow/handlers/index.d.ts +9 -0
  132. package/dist/workflow/handlers/index.d.ts.map +1 -0
  133. package/dist/workflow/handlers/webhook-handlers.d.ts +397 -0
  134. package/dist/workflow/handlers/webhook-handlers.d.ts.map +1 -0
  135. package/dist/workflow/handlers/webhook-handlers.js +454 -0
  136. package/dist/workflow/handlers/webhook-handlers.js.map +1 -0
  137. package/dist/workflow/index.d.ts +42 -0
  138. package/dist/workflow/index.d.ts.map +1 -0
  139. package/dist/workflow/services/index.d.ts +9 -0
  140. package/dist/workflow/services/index.d.ts.map +1 -0
  141. package/dist/workflow/services/workflow-service.d.ts +318 -0
  142. package/dist/workflow/services/workflow-service.d.ts.map +1 -0
  143. package/dist/workflow/services/workflow-service.js +577 -0
  144. package/dist/workflow/services/workflow-service.js.map +1 -0
  145. package/dist/workflow/types.d.ts +470 -0
  146. package/dist/workflow/types.d.ts.map +1 -0
  147. package/dist/workflow/workflows/realtime-collab.d.ts +245 -0
  148. package/dist/workflow/workflows/realtime-collab.d.ts.map +1 -0
  149. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.js","sources":["../../../src/cli/commands/audit.ts"],"sourcesContent":["/**\n * Audit Command\n *\n * CLI commands for querying and managing the exochain audit log.\n * Provides access to:\n * - Query audit events with filtering\n * - Create checkpoints for chain finality\n * - Verify audit chain integrity\n * - Check and manage sync status with peers\n * - Export audit log data\n *\n * @module cli/commands/audit\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { writeFile } from 'fs/promises';\nimport {\n createAuditChain,\n createAuditChainConfig,\n type LedgerEvent,\n type EventQueryOptions,\n type ChainStats,\n type Checkpoint,\n type HybridLogicalClock,\n} from '../../audit/index.js';\nimport {\n createSyndicationService,\n type PeerInfo,\n type SyncResult,\n} from '../../audit/services/syndication.js';\nimport { validateProjectRoot } from '../../core/security.js';\n\n/**\n * Format a date for display\n *\n * @param date - Date to format\n * @returns Formatted date string\n */\nfunction formatDate(date: Date | undefined): string {\n if (!date) return 'N/A';\n return date.toISOString().replace('T', ' ').replace(/\\.\\d{3}Z$/, '');\n}\n\n/**\n * Format HLC timestamp for display\n *\n * @param hlc - Hybrid logical clock to format\n * @returns Formatted timestamp string\n */\nfunction formatHLC(hlc: HybridLogicalClock): string {\n const date = new Date(hlc.physicalMs);\n return `${formatDate(date)} (L:${hlc.logical})`;\n}\n\n/**\n * Format duration in milliseconds for display\n *\n * @param ms - Duration in milliseconds\n * @returns Formatted duration string\n */\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${ms}ms`;\n if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;\n return `${(ms / 60000).toFixed(1)}m`;\n}\n\n/**\n * Print events in a table format\n *\n * @param events - Events to display\n */\nfunction printEventsTable(events: LedgerEvent[]): void {\n if (events.length === 0) {\n console.log(chalk.gray(' No events found'));\n return;\n }\n\n // Header\n console.log(\n chalk.gray(\n ' ' +\n 'ID'.padEnd(16) +\n 'Type'.padEnd(24) +\n 'Author'.padEnd(20) +\n 'Timestamp'\n )\n );\n console.log(chalk.gray(' ' + '-'.repeat(80)));\n\n // Rows\n for (const event of events) {\n const id = event.id.substring(0, 14) + '..';\n const type = event.envelope.payload.type;\n const author = event.envelope.author.substring(0, 18);\n const timestamp = formatHLC(event.envelope.hlc);\n\n const typeColor =\n type.includes('Created') ? chalk.green :\n type.includes('Deleted') ? chalk.red :\n type.includes('Updated') ? chalk.yellow :\n type.includes('Completed') ? chalk.cyan :\n type.includes('Started') ? chalk.blue :\n chalk.white;\n\n console.log(\n ' ' +\n chalk.gray(id.padEnd(16)) +\n typeColor(type.padEnd(24)) +\n chalk.gray(author.padEnd(20)) +\n chalk.gray(timestamp)\n );\n }\n}\n\n/**\n * Print chain statistics\n *\n * @param stats - Chain statistics to display\n */\nfunction printChainStats(stats: ChainStats): void {\n const statusColor =\n stats.status === 'healthy' ? chalk.green :\n stats.status === 'syncing' ? chalk.yellow :\n chalk.red;\n\n console.log(chalk.white(' Overview'));\n console.log(chalk.gray(` Status: `) + statusColor(stats.status));\n console.log(chalk.gray(` Total events: ${stats.totalEvents}`));\n console.log(chalk.gray(` Checkpoint height: ${stats.checkpointHeight}`));\n console.log(chalk.gray(` Unique authors: ${stats.uniqueAuthors}`));\n if (stats.lastEventTime) {\n console.log(chalk.gray(` Last event: ${formatDate(stats.lastEventTime)}`));\n }\n\n if (Object.keys(stats.eventsByType).length > 0) {\n console.log();\n console.log(chalk.white(' Events by Type'));\n const sortedTypes = Object.entries(stats.eventsByType)\n .sort((a, b) => b[1] - a[1]);\n\n for (const [type, count] of sortedTypes) {\n const bar = '|'.repeat(Math.min(Math.ceil(count / 5), 30));\n console.log(\n chalk.gray(` ${type.padEnd(24)} ${String(count).padStart(5)} `) +\n chalk.blue(bar)\n );\n }\n }\n}\n\n/**\n * Print checkpoint information\n *\n * @param checkpoint - Checkpoint to display\n */\nfunction printCheckpoint(checkpoint: Checkpoint | null): void {\n if (!checkpoint) {\n console.log(chalk.gray(' No checkpoints created yet'));\n return;\n }\n\n console.log(chalk.white(' Latest Checkpoint'));\n console.log(chalk.gray(` Height: ${checkpoint.height}`));\n console.log(chalk.gray(` Event root: ${checkpoint.eventRoot.substring(0, 32)}...`));\n console.log(chalk.gray(` State root: ${checkpoint.stateRoot.substring(0, 32)}...`));\n console.log(chalk.gray(` Timestamp: ${formatDate(checkpoint.timestamp)}`));\n console.log(chalk.gray(` Signatures: ${checkpoint.validatorSignatures.length}`));\n}\n\n/**\n * Print peer information in table format\n *\n * @param peers - Peers to display\n */\nfunction printPeersTable(peers: PeerInfo[]): void {\n if (peers.length === 0) {\n console.log(chalk.gray(' No peers configured'));\n return;\n }\n\n console.log(\n chalk.gray(\n ' ' +\n 'ID'.padEnd(16) +\n 'Status'.padEnd(14) +\n 'Last Sync'.padEnd(22) +\n 'Events (Rx/Tx)'\n )\n );\n console.log(chalk.gray(' ' + '-'.repeat(70)));\n\n for (const peer of peers) {\n const statusColor =\n peer.status === 'connected' ? chalk.green :\n peer.status === 'syncing' ? chalk.yellow :\n peer.status === 'error' ? chalk.red :\n chalk.gray;\n\n const lastSync = peer.lastSyncTime ? formatDate(peer.lastSyncTime) : 'Never';\n const events = `${peer.eventsReceived}/${peer.eventsSent}`;\n\n console.log(\n ' ' +\n chalk.gray(peer.id.padEnd(16)) +\n statusColor(peer.status.padEnd(14)) +\n chalk.gray(lastSync.padEnd(22)) +\n chalk.gray(events)\n );\n\n if (peer.lastError) {\n console.log(chalk.red(` Error: ${peer.lastError}`));\n }\n }\n}\n\n/**\n * Print sync results\n *\n * @param results - Sync results to display\n */\nfunction printSyncResults(results: SyncResult[]): void {\n if (results.length === 0) {\n console.log(chalk.gray(' No sync operations performed'));\n return;\n }\n\n console.log(\n chalk.gray(\n ' ' +\n 'Peer'.padEnd(16) +\n 'Status'.padEnd(10) +\n 'Received'.padEnd(10) +\n 'Sent'.padEnd(10) +\n 'Duration'\n )\n );\n console.log(chalk.gray(' ' + '-'.repeat(60)));\n\n for (const result of results) {\n const statusColor = result.success ? chalk.green : chalk.red;\n const status = result.success ? 'OK' : 'FAIL';\n\n console.log(\n ' ' +\n chalk.gray(result.peerId.substring(0, 14).padEnd(16)) +\n statusColor(status.padEnd(10)) +\n chalk.gray(String(result.eventsReceived).padEnd(10)) +\n chalk.gray(String(result.eventsSent).padEnd(10)) +\n chalk.gray(formatDuration(result.duration))\n );\n\n if (result.error) {\n console.log(chalk.red(` Error: ${result.error}`));\n }\n }\n}\n\n/**\n * Parse date string to HLC for filtering\n *\n * @param dateStr - Date string to parse\n * @returns HLC timestamp or undefined\n */\nfunction parseDateToHLC(dateStr: string | undefined): HybridLogicalClock | undefined {\n if (!dateStr) return undefined;\n\n const date = new Date(dateStr);\n if (isNaN(date.getTime())) {\n throw new Error(`Invalid date format: ${dateStr}`);\n }\n\n return {\n physicalMs: date.getTime(),\n logical: 0,\n };\n}\n\n/**\n * Create audit command with subcommands\n *\n * @returns Configured audit command\n */\nexport function createAuditCommand(): Command {\n const audit = new Command('audit')\n .description('Query and manage the exochain audit log');\n\n // ============================================================================\n // Query subcommand\n // ============================================================================\n audit\n .command('query')\n .description('Query the audit log')\n .option('-t, --type <type>', 'Filter by event type (e.g., NodeCreated, WorkflowCompleted)')\n .option('-s, --start <date>', 'Start date (ISO format, e.g., 2024-01-01)')\n .option('-e, --end <date>', 'End date (ISO format)')\n .option('-l, --limit <n>', 'Maximum results to return', '50')\n .option('-a, --author <did>', 'Filter by author DID')\n .option('--json', 'Output as JSON')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (options) => {\n const spinner = ora('Querying audit log...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const auditChain = createAuditChain(createAuditChainConfig());\n\n // Build query options\n const queryOptions: EventQueryOptions = {\n limit: parseInt(options.limit, 10) || 50,\n includeProof: false,\n };\n\n if (options.type) {\n queryOptions.type = options.type;\n }\n\n if (options.author) {\n queryOptions.author = options.author;\n }\n\n if (options.start) {\n queryOptions.since = parseDateToHLC(options.start);\n }\n\n if (options.end) {\n queryOptions.until = parseDateToHLC(options.end);\n }\n\n const result = await auditChain.queryEvents(queryOptions);\n\n spinner.stop();\n\n if (options.json) {\n console.log(JSON.stringify({\n events: result.events.map(e => ({\n id: e.id,\n type: e.envelope.payload.type,\n author: e.envelope.author,\n timestamp: e.envelope.hlc.physicalMs,\n parents: e.envelope.parents,\n payload: e.envelope.payload,\n })),\n totalCount: result.totalCount,\n hasMore: result.hasMore,\n }, null, 2));\n return;\n }\n\n console.log(chalk.cyan('\\n Audit Log Query Results\\n'));\n console.log(chalk.gray(` Found ${result.totalCount} events (showing ${result.events.length})`));\n if (result.hasMore) {\n console.log(chalk.gray(' (more results available, increase --limit to see more)'));\n }\n console.log();\n\n printEventsTable(result.events);\n\n // Show chain stats summary\n console.log();\n const stats = auditChain.getStats();\n console.log(chalk.gray(` Chain status: `) + chalk.green(stats.status));\n console.log();\n\n } catch (error) {\n spinner.fail('Query failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // ============================================================================\n // Checkpoint subcommand\n // ============================================================================\n audit\n .command('checkpoint')\n .description('Create a checkpoint in the audit chain')\n .option('-n, --name <name>', 'Checkpoint name/label')\n .option('-t, --tags <tags>', 'Comma-separated tags')\n .option('--json', 'Output as JSON')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (options) => {\n const spinner = ora('Creating checkpoint...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const auditChain = createAuditChain(createAuditChainConfig());\n\n // Create the checkpoint\n const checkpoint = await auditChain.createCheckpoint();\n\n spinner.succeed('Checkpoint created!');\n\n if (options.json) {\n console.log(JSON.stringify({\n height: checkpoint.height,\n eventRoot: checkpoint.eventRoot,\n stateRoot: checkpoint.stateRoot,\n timestamp: checkpoint.timestamp.toISOString(),\n signatures: checkpoint.validatorSignatures.length,\n name: options.name,\n tags: options.tags?.split(',').map((t: string) => t.trim()),\n }, null, 2));\n return;\n }\n\n console.log(chalk.cyan('\\n Checkpoint Details\\n'));\n\n if (options.name) {\n console.log(chalk.white(` Name: ${options.name}`));\n }\n if (options.tags) {\n const tags = options.tags.split(',').map((t: string) => t.trim());\n console.log(chalk.white(` Tags: ${tags.join(', ')}`));\n }\n\n console.log();\n printCheckpoint(checkpoint);\n console.log();\n\n } catch (error) {\n spinner.fail('Checkpoint creation failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // ============================================================================\n // Verify subcommand\n // ============================================================================\n audit\n .command('verify')\n .description('Verify audit chain integrity')\n .option('--full', 'Perform full chain verification (slower)')\n .option('--json', 'Output as JSON')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (options) => {\n const spinner = ora('Verifying audit chain integrity...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const auditChain = createAuditChain(createAuditChainConfig());\n\n const startTime = Date.now();\n const stats = auditChain.getStats();\n const checkpoint = auditChain.getLatestCheckpoint();\n\n // Verify chain structure\n const issues: string[] = [];\n const warnings: string[] = [];\n\n // Check for basic chain health\n if (stats.status === 'degraded') {\n issues.push('Chain status is degraded');\n }\n\n // Check checkpoint consistency\n if (stats.checkpointHeight > 0 && !checkpoint) {\n issues.push('Checkpoint height > 0 but no checkpoint found');\n }\n\n // Check for orphan events (no parents and not genesis)\n const chainData = auditChain.export();\n let genesisCount = 0;\n for (const event of chainData.events) {\n if (event.envelope.parents.length === 0) {\n genesisCount++;\n }\n }\n if (genesisCount > 1) {\n warnings.push(`Multiple genesis events found: ${genesisCount}`);\n }\n\n // Verify tips are valid\n const tips = auditChain.getTips();\n if (tips.length === 0 && chainData.events.length > 0) {\n issues.push('No chain tips but events exist');\n }\n\n // Check event ordering if full verification\n if (options.full) {\n spinner.text = 'Performing full chain verification...';\n\n // Verify event IDs and signatures\n for (const event of chainData.events) {\n // Check parent existence\n for (const parentId of event.envelope.parents) {\n const parent = chainData.events.find(e => e.id === parentId);\n if (!parent) {\n issues.push(`Event ${event.id.substring(0, 12)}.. references missing parent ${parentId.substring(0, 12)}..`);\n }\n }\n }\n }\n\n const duration = Date.now() - startTime;\n const valid = issues.length === 0;\n\n spinner.stop();\n\n if (options.json) {\n console.log(JSON.stringify({\n valid,\n issues,\n warnings,\n stats: {\n totalEvents: stats.totalEvents,\n checkpointHeight: stats.checkpointHeight,\n status: stats.status,\n tips: tips.length,\n },\n duration,\n }, null, 2));\n return;\n }\n\n console.log(chalk.cyan('\\n Audit Chain Verification\\n'));\n\n if (valid) {\n console.log(chalk.green(' Status: VALID'));\n } else {\n console.log(chalk.red(' Status: INVALID'));\n }\n\n console.log();\n console.log(chalk.white(' Statistics'));\n console.log(chalk.gray(` Events verified: ${stats.totalEvents}`));\n console.log(chalk.gray(` Checkpoint height: ${stats.checkpointHeight}`));\n console.log(chalk.gray(` Chain tips: ${tips.length}`));\n console.log(chalk.gray(` Verification time: ${formatDuration(duration)}`));\n\n if (issues.length > 0) {\n console.log();\n console.log(chalk.red(' Issues Found'));\n for (const issue of issues) {\n console.log(chalk.red(` - ${issue}`));\n }\n }\n\n if (warnings.length > 0) {\n console.log();\n console.log(chalk.yellow(' Warnings'));\n for (const warning of warnings) {\n console.log(chalk.yellow(` - ${warning}`));\n }\n }\n\n console.log();\n\n if (!valid) {\n process.exit(1);\n }\n\n } catch (error) {\n spinner.fail('Verification failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // ============================================================================\n // Sync subcommand group\n // ============================================================================\n const sync = audit\n .command('sync')\n .description('Manage audit chain synchronization');\n\n // sync status\n sync\n .command('status')\n .description('Check synchronization status')\n .option('--json', 'Output as JSON')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (options) => {\n const spinner = ora('Checking sync status...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const auditChain = createAuditChain(createAuditChainConfig());\n const syndication = createSyndicationService({ auditChain });\n\n const stats = syndication.getStats();\n const chainStats = auditChain.getStats();\n\n spinner.stop();\n\n if (options.json) {\n console.log(JSON.stringify({\n service: {\n running: stats.isRunning,\n autoSyncEnabled: stats.autoSyncEnabled,\n syncInterval: stats.syncInterval,\n },\n peers: {\n total: stats.totalPeers,\n connected: stats.connectedPeers,\n syncing: stats.syncingPeers,\n error: stats.errorPeers,\n },\n transfer: {\n received: stats.totalEventsReceived,\n sent: stats.totalEventsSent,\n errors: stats.totalErrors,\n },\n chain: {\n status: chainStats.status,\n events: chainStats.totalEvents,\n checkpointHeight: chainStats.checkpointHeight,\n },\n }, null, 2));\n return;\n }\n\n console.log(chalk.cyan('\\n Sync Status\\n'));\n\n // Service status\n console.log(chalk.white(' Service'));\n console.log(chalk.gray(` Running: `) + (stats.isRunning ? chalk.green('Yes') : chalk.gray('No')));\n console.log(chalk.gray(` Auto-sync: `) + (stats.autoSyncEnabled ? chalk.green('Enabled') : chalk.gray('Disabled')));\n if (stats.autoSyncEnabled) {\n console.log(chalk.gray(` Interval: ${formatDuration(stats.syncInterval)}`));\n }\n\n // Peer status\n console.log();\n console.log(chalk.white(' Peers'));\n console.log(chalk.gray(` Total: ${stats.totalPeers}`));\n console.log(chalk.gray(` Connected: `) + chalk.green(String(stats.connectedPeers)));\n if (stats.syncingPeers > 0) {\n console.log(chalk.gray(` Syncing: `) + chalk.yellow(String(stats.syncingPeers)));\n }\n if (stats.errorPeers > 0) {\n console.log(chalk.gray(` Errors: `) + chalk.red(String(stats.errorPeers)));\n }\n\n // Transfer stats\n console.log();\n console.log(chalk.white(' Transfer Statistics'));\n console.log(chalk.gray(` Events received: ${stats.totalEventsReceived}`));\n console.log(chalk.gray(` Events sent: ${stats.totalEventsSent}`));\n if (stats.totalErrors > 0) {\n console.log(chalk.gray(` Errors: `) + chalk.red(String(stats.totalErrors)));\n }\n\n // Chain status\n console.log();\n console.log(chalk.white(' Chain'));\n const chainStatusColor =\n chainStats.status === 'healthy' ? chalk.green :\n chainStats.status === 'syncing' ? chalk.yellow :\n chalk.red;\n console.log(chalk.gray(` Status: `) + chainStatusColor(chainStats.status));\n console.log(chalk.gray(` Events: ${chainStats.totalEvents}`));\n console.log(chalk.gray(` Checkpoint: ${chainStats.checkpointHeight}`));\n\n console.log();\n\n } catch (error) {\n spinner.fail('Status check failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // sync peers\n sync\n .command('peers')\n .description('List sync peers')\n .option('--json', 'Output as JSON')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (options) => {\n const spinner = ora('Fetching peer list...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const auditChain = createAuditChain(createAuditChainConfig());\n const syndication = createSyndicationService({ auditChain });\n\n const peers = syndication.getAllPeers();\n\n spinner.stop();\n\n if (options.json) {\n console.log(JSON.stringify({\n peers: peers.map(p => ({\n id: p.id,\n endpoint: p.endpoint,\n did: p.did,\n status: p.status,\n lastSync: p.lastSyncTime?.toISOString(),\n lastCheckpointHeight: p.lastCheckpointHeight,\n eventsReceived: p.eventsReceived,\n eventsSent: p.eventsSent,\n errors: p.errors,\n lastError: p.lastError,\n latency: p.latency,\n })),\n summary: {\n total: peers.length,\n connected: peers.filter(p => p.status === 'connected').length,\n error: peers.filter(p => p.status === 'error').length,\n },\n }, null, 2));\n return;\n }\n\n console.log(chalk.cyan('\\n Sync Peers\\n'));\n\n printPeersTable(peers);\n\n // Summary\n const connected = peers.filter(p => p.status === 'connected').length;\n const errors = peers.filter(p => p.status === 'error').length;\n\n console.log();\n console.log(chalk.gray(` Total: ${peers.length}, Connected: ${connected}, Errors: ${errors}`));\n console.log();\n\n } catch (error) {\n spinner.fail('Failed to fetch peers');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // sync now (force immediate sync)\n sync\n .command('now')\n .description('Force immediate synchronization with all peers')\n .option('--json', 'Output as JSON')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (options) => {\n const spinner = ora('Syncing with peers...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const auditChain = createAuditChain(createAuditChainConfig());\n const syndication = createSyndicationService({ auditChain });\n\n await syndication.start();\n const results = await syndication.forceSyncNow();\n await syndication.stop();\n\n spinner.stop();\n\n if (options.json) {\n console.log(JSON.stringify({\n results: results.map(r => ({\n peerId: r.peerId,\n success: r.success,\n eventsReceived: r.eventsReceived,\n eventsSent: r.eventsSent,\n newCheckpointHeight: r.newCheckpointHeight,\n duration: r.duration,\n error: r.error,\n })),\n summary: {\n total: results.length,\n successful: results.filter(r => r.success).length,\n failed: results.filter(r => !r.success).length,\n },\n }, null, 2));\n return;\n }\n\n console.log(chalk.cyan('\\n Sync Results\\n'));\n\n printSyncResults(results);\n\n // Summary\n const successful = results.filter(r => r.success).length;\n const failed = results.filter(r => !r.success).length;\n const totalReceived = results.reduce((sum, r) => sum + r.eventsReceived, 0);\n const totalSent = results.reduce((sum, r) => sum + r.eventsSent, 0);\n\n console.log();\n console.log(chalk.gray(` Peers: ${results.length} (${successful} successful, ${failed} failed)`));\n console.log(chalk.gray(` Events: ${totalReceived} received, ${totalSent} sent`));\n console.log();\n\n if (failed > 0) {\n process.exit(1);\n }\n\n } catch (error) {\n spinner.fail('Sync failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // ============================================================================\n // Export subcommand\n // ============================================================================\n audit\n .command('export')\n .description('Export audit log data')\n .option('-o, --output <file>', 'Output file path')\n .option('-f, --format <format>', 'Export format (json|jsonl)', 'json')\n .option('-t, --type <type>', 'Filter by event type')\n .option('-s, --start <date>', 'Start date filter')\n .option('-e, --end <date>', 'End date filter')\n .option('-l, --limit <n>', 'Maximum events to export')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (options) => {\n const spinner = ora('Exporting audit log...').start();\n\n try {\n const projectRoot = validateProjectRoot(options.path);\n const auditChain = createAuditChain(createAuditChainConfig());\n\n // Build query options\n const queryOptions: EventQueryOptions = {\n includeProof: true,\n };\n\n if (options.type) {\n queryOptions.type = options.type;\n }\n\n if (options.start) {\n queryOptions.since = parseDateToHLC(options.start);\n }\n\n if (options.end) {\n queryOptions.until = parseDateToHLC(options.end);\n }\n\n if (options.limit) {\n queryOptions.limit = parseInt(options.limit, 10);\n }\n\n const result = await auditChain.queryEvents(queryOptions);\n const chainData = auditChain.export();\n const checkpoint = auditChain.getLatestCheckpoint();\n\n // Format export data\n const exportData = {\n metadata: {\n exportedAt: new Date().toISOString(),\n chainStatus: auditChain.getStats().status,\n totalEvents: result.totalCount,\n exportedEvents: result.events.length,\n checkpointHeight: checkpoint?.height ?? 0,\n filters: {\n type: options.type,\n startDate: options.start,\n endDate: options.end,\n limit: options.limit,\n },\n },\n checkpoint: checkpoint ? {\n height: checkpoint.height,\n eventRoot: checkpoint.eventRoot,\n stateRoot: checkpoint.stateRoot,\n timestamp: checkpoint.timestamp.toISOString(),\n signatures: checkpoint.validatorSignatures.length,\n } : null,\n events: result.events.map(e => ({\n id: e.id,\n type: e.envelope.payload.type,\n author: e.envelope.author,\n timestamp: new Date(e.envelope.hlc.physicalMs).toISOString(),\n hlc: e.envelope.hlc,\n parents: e.envelope.parents,\n payload: e.envelope.payload,\n signature: e.signature,\n })),\n tips: chainData.tips,\n };\n\n let output: string;\n if (options.format === 'jsonl') {\n // JSON Lines format - one event per line\n const lines = [\n JSON.stringify({ type: 'metadata', data: exportData.metadata }),\n ...(exportData.checkpoint ? [JSON.stringify({ type: 'checkpoint', data: exportData.checkpoint })] : []),\n ...exportData.events.map(e => JSON.stringify({ type: 'event', data: e })),\n ];\n output = lines.join('\\n');\n } else {\n output = JSON.stringify(exportData, null, 2);\n }\n\n spinner.stop();\n\n if (options.output) {\n const outputPath = join(projectRoot, options.output);\n await writeFile(outputPath, output, 'utf-8');\n console.log(chalk.green(`\\n Exported ${result.events.length} events to ${outputPath}\\n`));\n } else {\n console.log(output);\n }\n\n } catch (error) {\n spinner.fail('Export failed');\n console.error(chalk.red(String(error)));\n process.exit(1);\n }\n });\n\n // ============================================================================\n // Stats subcommand\n // ============================================================================\n audit\n .command('stats')\n .description('Show audit chain statistics')\n .option('--json', 'Output as JSON')\n .option('-p, --path <path>', 'Project root path', '.')\n .action(async (options) => {\n try {\n const projectRoot = validateProjectRoot(options.path);\n const auditChain = createAuditChain(createAuditChainConfig());\n\n const stats = auditChain.getStats();\n const checkpoint = auditChain.getLatestCheckpoint();\n const tips = auditChain.getTips();\n\n if (options.json) {\n console.log(JSON.stringify({\n stats,\n checkpoint: checkpoint ? {\n height: checkpoint.height,\n eventRoot: checkpoint.eventRoot,\n stateRoot: checkpoint.stateRoot,\n timestamp: checkpoint.timestamp.toISOString(),\n signatures: checkpoint.validatorSignatures.length,\n } : null,\n tips: {\n count: tips.length,\n ids: tips,\n },\n }, null, 2));\n return;\n }\n\n console.log(chalk.cyan('\\n Audit Chain Statistics\\n'));\n\n printChainStats(stats);\n\n console.log();\n printCheckpoint(checkpoint);\n\n if (tips.length > 0) {\n console.log();\n console.log(chalk.white(' Chain Tips'));\n console.log(chalk.gray(` Count: ${tips.length}`));\n for (const tip of tips.slice(0, 5)) {\n console.log(chalk.gray(` - ${tip.substring(0, 32)}...`));\n }\n if (tips.length > 5) {\n console.log(chalk.gray(` ... and ${tips.length - 5} more`));\n }\n }\n\n console.log();\n\n } catch (error) {\n console.error(chalk.red('Failed to get statistics:'), String(error));\n process.exit(1);\n }\n });\n\n return audit;\n}\n"],"names":[],"mappings":";;;;;;;;;AA0CA,SAAS,WAAW,MAAgC;AAClD,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KAAK,cAAc,QAAQ,KA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A,EACF,CAAC;AAEH,SAAO;AACT;"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Vector Command
3
+ *
4
+ * CLI commands for vector operations including semantic search,
5
+ * vector store statistics, index management, and trajectory tracking.
6
+ *
7
+ * @module cli/commands/vector
8
+ */
9
+ import { Command } from 'commander';
10
+ /**
11
+ * Create vector command group
12
+ */
13
+ export declare function createVectorCommand(): Command;
14
+ //# sourceMappingURL=vector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vector.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/vector.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAqEpC;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,OAAO,CAmiB7C"}
@@ -0,0 +1,429 @@
1
+ import { Command } from "commander";
2
+ import chalk from "chalk";
3
+ import ora from "ora";
4
+ import { join } from "path";
5
+ import { existsSync } from "fs";
6
+ import "../../vector/config.js";
7
+ import { createVectorStore } from "../../vector/services/vector-store.js";
8
+ import { createTrajectoryTracker } from "../../vector/services/trajectory-tracker.js";
9
+ import { validateProjectRoot } from "../../core/security.js";
10
+ function formatBytes(bytes) {
11
+ if (bytes < 1024) return `${bytes} B`;
12
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
13
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
14
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
15
+ }
16
+ function formatDuration(ms) {
17
+ if (ms < 1e3) return `${ms}ms`;
18
+ if (ms < 6e4) return `${(ms / 1e3).toFixed(2)}s`;
19
+ if (ms < 36e5) return `${(ms / 6e4).toFixed(2)}m`;
20
+ return `${(ms / 36e5).toFixed(2)}h`;
21
+ }
22
+ function formatRow(cells, widths) {
23
+ return cells.map((cell, i) => cell.padEnd(widths[i])).join(" ");
24
+ }
25
+ function printTable(headers, rows, options = {}) {
26
+ const indent = " ".repeat(options.indent ?? 1);
27
+ const headerColor = options.headerColor ?? chalk.white;
28
+ const widths = headers.map((h, i) => {
29
+ const maxRowWidth = Math.max(...rows.map((r) => (r[i] || "").length));
30
+ return Math.max(h.length, maxRowWidth);
31
+ });
32
+ console.log(indent + headerColor(formatRow(headers, widths)));
33
+ console.log(indent + chalk.gray("-".repeat(widths.reduce((a, b) => a + b + 2, 0))));
34
+ for (const row of rows) {
35
+ console.log(indent + chalk.gray(formatRow(row, widths)));
36
+ }
37
+ }
38
+ function createVectorCommand() {
39
+ const vector = new Command("vector").alias("vec").description("Vector operations for semantic search and trajectory tracking");
40
+ vector.command("search <query>").description("Perform semantic search on vector store").option("-p, --path <path>", "Project root path", ".").option("-k, --top-k <n>", "Number of results to return", "10").option("-t, --type <type>", "Filter by node type").option("--hybrid", "Enable hybrid search (combines vector + graph)").option("--min-score <score>", "Minimum similarity score (0-1)", "0").option("--json", "Output as JSON").action(async (query, options) => {
41
+ const spinner = ora("Searching vectors...").start();
42
+ try {
43
+ const projectRoot = validateProjectRoot(options.path);
44
+ const topK = parseInt(options.topK, 10) || 10;
45
+ const minScore = parseFloat(options.minScore) || 0;
46
+ const store = createVectorStore();
47
+ await store.initialize();
48
+ const stats = store.getStats();
49
+ if (stats.totalVectors === 0) {
50
+ spinner.warn("Vector store is empty");
51
+ console.log(chalk.gray(" No vectors have been indexed yet."));
52
+ console.log(chalk.gray(" Run ") + chalk.cyan("kg vector rebuild") + chalk.gray(" to index vectors."));
53
+ return;
54
+ }
55
+ spinner.text = "Generating query embedding...";
56
+ const queryEmbedding = createMockEmbedding(query, stats.dimensions);
57
+ spinner.text = `Searching ${stats.totalVectors} vectors...`;
58
+ let results;
59
+ if (options.hybrid) {
60
+ const hybridResults = await store.hybridSearch({
61
+ embedding: queryEmbedding,
62
+ limit: topK,
63
+ minScore,
64
+ filters: options.type ? { type: options.type } : void 0
65
+ });
66
+ results = hybridResults;
67
+ } else {
68
+ results = await store.search({
69
+ vector: queryEmbedding,
70
+ k: topK,
71
+ minScore,
72
+ filter: options.type ? { type: options.type } : void 0
73
+ });
74
+ }
75
+ spinner.stop();
76
+ if (options.json) {
77
+ console.log(JSON.stringify(results, null, 2));
78
+ return;
79
+ }
80
+ console.log(chalk.cyan(`
81
+ Search Results for "${query}"
82
+ `));
83
+ if (results.length === 0) {
84
+ console.log(chalk.gray(" No results found"));
85
+ return;
86
+ }
87
+ console.log(chalk.gray(` Found ${results.length} result${results.length === 1 ? "" : "s"}
88
+ `));
89
+ const headers = ["#", "ID", "Score", "Type", "Metadata"];
90
+ const rows = results.map((r, i) => [
91
+ String(i + 1),
92
+ r.id.substring(0, 24) + (r.id.length > 24 ? "..." : ""),
93
+ r.score.toFixed(4),
94
+ r.metadata?.type || "-",
95
+ Object.keys(r.metadata || {}).length > 0 ? Object.keys(r.metadata).slice(0, 3).join(", ") : "-"
96
+ ]);
97
+ printTable(headers, rows);
98
+ console.log(chalk.white("\n Top Result Details:\n"));
99
+ const top = results[0];
100
+ console.log(chalk.gray(` ID: ${top.id}`));
101
+ console.log(chalk.gray(` Score: ${top.score.toFixed(6)}`));
102
+ if (top.distance !== void 0) {
103
+ console.log(chalk.gray(` Distance: ${top.distance.toFixed(6)}`));
104
+ }
105
+ if (Object.keys(top.metadata || {}).length > 0) {
106
+ console.log(chalk.gray(" Metadata:"));
107
+ for (const [key, value] of Object.entries(top.metadata)) {
108
+ const displayValue = typeof value === "object" ? JSON.stringify(value) : String(value);
109
+ console.log(chalk.gray(` ${key}: ${displayValue.substring(0, 50)}`));
110
+ }
111
+ }
112
+ console.log();
113
+ } catch (error) {
114
+ spinner.fail("Search failed");
115
+ console.error(chalk.red(String(error)));
116
+ process.exit(1);
117
+ }
118
+ });
119
+ vector.command("stats").description("Display vector store statistics").option("-p, --path <path>", "Project root path", ".").option("--json", "Output as JSON").action(async (options) => {
120
+ try {
121
+ const projectRoot = validateProjectRoot(options.path);
122
+ const store = createVectorStore();
123
+ await store.initialize();
124
+ const stats = store.getStats();
125
+ if (options.json) {
126
+ console.log(JSON.stringify(stats, null, 2));
127
+ return;
128
+ }
129
+ console.log(chalk.cyan.bold("\n Vector Store Statistics\n"));
130
+ console.log(chalk.white(" Overview"));
131
+ console.log(chalk.gray(` Total Vectors: ${stats.totalVectors.toLocaleString()}`));
132
+ console.log(chalk.gray(` Dimensions: ${stats.dimensions}`));
133
+ console.log(chalk.gray(` Index Type: ${stats.indexType.toUpperCase()}`));
134
+ console.log(chalk.gray(` Memory Usage: ${formatBytes(stats.memoryUsage)}`));
135
+ console.log(chalk.gray(` Last Updated: ${stats.lastUpdated.toISOString()}`));
136
+ if (stats.indexStats) {
137
+ console.log();
138
+ console.log(chalk.white(" Index Configuration"));
139
+ if (stats.indexStats.levels !== void 0) {
140
+ console.log(chalk.gray(` HNSW Levels: ${stats.indexStats.levels}`));
141
+ }
142
+ if (stats.indexStats.entryPoint) {
143
+ console.log(chalk.gray(` Entry Point: ${stats.indexStats.entryPoint.substring(0, 24)}...`));
144
+ }
145
+ if (stats.indexStats.avgConnections !== void 0) {
146
+ console.log(chalk.gray(` Avg Connections: ${stats.indexStats.avgConnections.toFixed(2)}`));
147
+ }
148
+ }
149
+ if (stats.namespaces && Object.keys(stats.namespaces).length > 0) {
150
+ console.log();
151
+ console.log(chalk.white(" Namespaces"));
152
+ for (const [ns, count] of Object.entries(stats.namespaces)) {
153
+ const bar = "|".repeat(Math.min(count, 30));
154
+ console.log(chalk.gray(` ${ns.padEnd(15)} ${String(count).padStart(6)} ${chalk.blue(bar)}`));
155
+ }
156
+ }
157
+ console.log();
158
+ console.log(chalk.white(" Performance"));
159
+ if (stats.totalVectors === 0) {
160
+ console.log(chalk.yellow(" [!] Vector store is empty"));
161
+ console.log(chalk.gray(' Run "kg vector rebuild" to populate the index'));
162
+ } else if (stats.totalVectors < 100) {
163
+ console.log(chalk.green(" [OK] Small index - linear search may be faster"));
164
+ } else if (stats.totalVectors < 1e4) {
165
+ console.log(chalk.green(" [OK] Medium index - HNSW optimal"));
166
+ } else {
167
+ console.log(chalk.yellow(" [!] Large index - consider quantization"));
168
+ }
169
+ console.log();
170
+ } catch (error) {
171
+ console.error(chalk.red("Failed to get stats:"), String(error));
172
+ process.exit(1);
173
+ }
174
+ });
175
+ vector.command("rebuild").description("Rebuild vector index from knowledge graph").option("-p, --path <path>", "Project root path", ".").option("--force", "Force rebuild even if index exists").option("--batch-size <size>", "Batch size for indexing", "100").option("-v, --verbose", "Verbose output").action(async (options) => {
176
+ const spinner = ora("Rebuilding vector index...").start();
177
+ try {
178
+ const projectRoot = validateProjectRoot(options.path);
179
+ const batchSize = parseInt(options.batchSize, 10) || 100;
180
+ const store = createVectorStore();
181
+ await store.initialize();
182
+ const existingStats = store.getStats();
183
+ if (existingStats.totalVectors > 0 && !options.force) {
184
+ spinner.warn(`Index already contains ${existingStats.totalVectors} vectors`);
185
+ console.log(chalk.gray(" Use --force to rebuild anyway"));
186
+ return;
187
+ }
188
+ if (options.force && existingStats.totalVectors > 0) {
189
+ spinner.text = "Clearing existing index...";
190
+ await store.clear();
191
+ }
192
+ spinner.text = "Scanning knowledge graph...";
193
+ const kgPath = join(projectRoot, ".kg", "knowledge.db");
194
+ if (!existsSync(kgPath)) {
195
+ spinner.fail("Knowledge graph not found");
196
+ console.log(chalk.gray(" Run ") + chalk.cyan("kg graph") + chalk.gray(" first"));
197
+ return;
198
+ }
199
+ spinner.text = "Generating embeddings...";
200
+ spinner.succeed("Vector index rebuild complete");
201
+ console.log();
202
+ console.log(chalk.white(" Rebuild Summary"));
203
+ console.log(chalk.gray(` Vectors indexed: 0 (mock - no embedding model configured)`));
204
+ console.log(chalk.gray(` Batch size: ${batchSize}`));
205
+ console.log(chalk.gray(` Project root: ${projectRoot}`));
206
+ console.log();
207
+ console.log(chalk.yellow(" Note: Full vector indexing requires an embedding model."));
208
+ console.log(chalk.gray(" Configure OPENAI_API_KEY or use local embeddings."));
209
+ console.log();
210
+ } catch (error) {
211
+ spinner.fail("Rebuild failed");
212
+ console.error(chalk.red(String(error)));
213
+ process.exit(1);
214
+ }
215
+ });
216
+ const trajectory = vector.command("trajectory").alias("traj").description("Agent trajectory tracking operations");
217
+ trajectory.command("list").description("List recorded agent trajectories").option("-p, --path <path>", "Project root path", ".").option("-a, --agent <id>", "Filter by agent ID").option("-w, --workflow <id>", "Filter by workflow ID").option("-l, --limit <n>", "Maximum number of trajectories", "20").option("--success", "Show only successful trajectories").option("--failed", "Show only failed trajectories").option("--json", "Output as JSON").action(async (options) => {
218
+ try {
219
+ const limit = parseInt(options.limit, 10) || 20;
220
+ const tracker = createTrajectoryTracker({
221
+ maxTrajectories: 1e3,
222
+ enableAutoLearning: true
223
+ });
224
+ const stats = tracker.getStats();
225
+ if (options.json) {
226
+ const exported2 = tracker.export();
227
+ let trajectories2 = exported2.trajectories;
228
+ if (options.agent) {
229
+ trajectories2 = trajectories2.filter((t) => t.agentId === options.agent);
230
+ }
231
+ if (options.workflow) {
232
+ trajectories2 = trajectories2.filter((t) => t.workflowId === options.workflow);
233
+ }
234
+ if (options.success) {
235
+ trajectories2 = trajectories2.filter((t) => t.success);
236
+ }
237
+ if (options.failed) {
238
+ trajectories2 = trajectories2.filter((t) => !t.success);
239
+ }
240
+ console.log(JSON.stringify(trajectories2.slice(0, limit), null, 2));
241
+ return;
242
+ }
243
+ console.log(chalk.cyan.bold("\n Agent Trajectories\n"));
244
+ console.log(chalk.white(" Overview"));
245
+ console.log(chalk.gray(` Active: ${stats.activeTrajectories}`));
246
+ console.log(chalk.gray(` Completed: ${stats.completedTrajectories}`));
247
+ console.log(chalk.gray(` Success: ${(stats.successRate * 100).toFixed(1)}%`));
248
+ console.log(chalk.gray(` Avg Duration: ${formatDuration(stats.avgDuration)}`));
249
+ console.log(chalk.gray(` Patterns: ${stats.detectedPatterns}`));
250
+ const exported = tracker.export();
251
+ let trajectories = exported.trajectories;
252
+ if (options.agent) {
253
+ trajectories = trajectories.filter((t) => t.agentId === options.agent);
254
+ }
255
+ if (options.workflow) {
256
+ trajectories = trajectories.filter((t) => t.workflowId === options.workflow);
257
+ }
258
+ if (options.success) {
259
+ trajectories = trajectories.filter((t) => t.success);
260
+ }
261
+ if (options.failed) {
262
+ trajectories = trajectories.filter((t) => !t.success);
263
+ }
264
+ trajectories = trajectories.slice(-limit).reverse();
265
+ if (trajectories.length === 0) {
266
+ console.log();
267
+ console.log(chalk.gray(" No trajectories found"));
268
+ console.log(chalk.gray(" Trajectories are recorded during agent operations."));
269
+ console.log();
270
+ return;
271
+ }
272
+ console.log();
273
+ console.log(chalk.white(` Recent Trajectories (${trajectories.length})`));
274
+ const headers = ["ID", "Agent", "Steps", "Duration", "Status"];
275
+ const rows = trajectories.map((t) => [
276
+ t.id.substring(0, 16) + "...",
277
+ t.agentId.substring(0, 12) + (t.agentId.length > 12 ? "..." : ""),
278
+ String(t.steps.length),
279
+ formatDuration(t.totalDuration),
280
+ t.success ? chalk.green("OK") : chalk.red("FAIL")
281
+ ]);
282
+ printTable(headers, rows);
283
+ console.log();
284
+ } catch (error) {
285
+ console.error(chalk.red("Failed to list trajectories:"), String(error));
286
+ process.exit(1);
287
+ }
288
+ });
289
+ trajectory.command("show <id>").description("Show detailed trajectory information").option("--json", "Output as JSON").action(async (id, options) => {
290
+ try {
291
+ const tracker = createTrajectoryTracker({
292
+ maxTrajectories: 1e3,
293
+ enableAutoLearning: true
294
+ });
295
+ const trajectory2 = tracker.getTrajectory(id);
296
+ if (!trajectory2) {
297
+ console.log(chalk.yellow(`
298
+ Trajectory not found: ${id}
299
+ `));
300
+ console.log(chalk.gray(' Use "kg vector trajectory list" to see available trajectories.'));
301
+ console.log();
302
+ return;
303
+ }
304
+ if (options.json) {
305
+ console.log(JSON.stringify(trajectory2, null, 2));
306
+ return;
307
+ }
308
+ console.log(chalk.cyan.bold("\n Trajectory Details\n"));
309
+ console.log(chalk.white(" Information"));
310
+ console.log(chalk.gray(` ID: ${trajectory2.id}`));
311
+ console.log(chalk.gray(` Agent: ${trajectory2.agentId}`));
312
+ if (trajectory2.workflowId) {
313
+ console.log(chalk.gray(` Workflow: ${trajectory2.workflowId}`));
314
+ }
315
+ console.log(chalk.gray(` Started: ${trajectory2.startedAt.toISOString()}`));
316
+ if (trajectory2.completedAt) {
317
+ console.log(chalk.gray(` Completed: ${trajectory2.completedAt.toISOString()}`));
318
+ }
319
+ console.log(chalk.gray(` Duration: ${formatDuration(trajectory2.totalDuration)}`));
320
+ console.log(
321
+ chalk.gray(" Status: ") + (trajectory2.success ? chalk.green("SUCCESS") : chalk.red("FAILED"))
322
+ );
323
+ if (trajectory2.steps.length > 0) {
324
+ console.log();
325
+ console.log(chalk.white(` Steps (${trajectory2.steps.length})`));
326
+ const stepHeaders = ["#", "Action", "Outcome", "Duration"];
327
+ const stepRows = trajectory2.steps.map((s, i) => [
328
+ String(i + 1),
329
+ s.action.substring(0, 30) + (s.action.length > 30 ? "..." : ""),
330
+ s.outcome === "success" ? chalk.green(s.outcome) : s.outcome === "failure" ? chalk.red(s.outcome) : chalk.yellow(s.outcome),
331
+ formatDuration(s.duration)
332
+ ]);
333
+ printTable(stepHeaders, stepRows);
334
+ }
335
+ if (trajectory2.metadata && Object.keys(trajectory2.metadata).length > 0) {
336
+ console.log();
337
+ console.log(chalk.white(" Metadata"));
338
+ for (const [key, value] of Object.entries(trajectory2.metadata)) {
339
+ const displayValue = typeof value === "object" ? JSON.stringify(value) : String(value);
340
+ console.log(chalk.gray(` ${key}: ${displayValue.substring(0, 60)}`));
341
+ }
342
+ }
343
+ console.log();
344
+ } catch (error) {
345
+ console.error(chalk.red("Failed to show trajectory:"), String(error));
346
+ process.exit(1);
347
+ }
348
+ });
349
+ trajectory.command("patterns").description("Show detected action patterns").option("--min-confidence <n>", "Minimum confidence threshold (0-1)", "0.5").option("--type <type>", "Filter by pattern type (success, failure, optimization)").option("--json", "Output as JSON").action(async (options) => {
350
+ try {
351
+ const minConfidence = parseFloat(options.minConfidence) || 0.5;
352
+ const tracker = createTrajectoryTracker({
353
+ maxTrajectories: 1e3,
354
+ enableAutoLearning: true
355
+ });
356
+ const patterns = tracker.getPatterns({
357
+ minConfidence,
358
+ type: options.type
359
+ });
360
+ if (options.json) {
361
+ console.log(JSON.stringify(patterns, null, 2));
362
+ return;
363
+ }
364
+ console.log(chalk.cyan.bold("\n Detected Patterns\n"));
365
+ if (patterns.length === 0) {
366
+ console.log(chalk.gray(" No patterns detected yet."));
367
+ console.log(chalk.gray(" Patterns are learned from successful agent trajectories."));
368
+ console.log();
369
+ return;
370
+ }
371
+ const headers = ["ID", "Type", "Frequency", "Success", "Confidence"];
372
+ const rows = patterns.map((p) => [
373
+ p.id.substring(0, 30) + (p.id.length > 30 ? "..." : ""),
374
+ p.type,
375
+ String(p.frequency),
376
+ `${(p.successRate * 100).toFixed(0)}%`,
377
+ `${(p.confidence * 100).toFixed(0)}%`
378
+ ]);
379
+ printTable(headers, rows);
380
+ if (patterns.length > 0) {
381
+ const top = patterns[0];
382
+ console.log();
383
+ console.log(chalk.white(" Top Pattern Details"));
384
+ console.log(chalk.gray(` ID: ${top.id}`));
385
+ console.log(chalk.gray(` Actions: ${top.actions.join(" -> ")}`));
386
+ console.log(chalk.gray(` Avg Duration: ${formatDuration(top.avgDuration)}`));
387
+ }
388
+ console.log();
389
+ } catch (error) {
390
+ console.error(chalk.red("Failed to show patterns:"), String(error));
391
+ process.exit(1);
392
+ }
393
+ });
394
+ trajectory.command("clear").description("Clear all trajectory data").option("--confirm", "Confirm clearing without prompt").action(async (options) => {
395
+ try {
396
+ if (!options.confirm) {
397
+ console.log(chalk.yellow("\n Warning: This will delete all trajectory data.\n"));
398
+ console.log(chalk.gray(" Use --confirm to proceed."));
399
+ console.log();
400
+ return;
401
+ }
402
+ const tracker = createTrajectoryTracker();
403
+ tracker.clear();
404
+ console.log(chalk.green("\n Trajectory data cleared.\n"));
405
+ } catch (error) {
406
+ console.error(chalk.red("Failed to clear trajectories:"), String(error));
407
+ process.exit(1);
408
+ }
409
+ });
410
+ return vector;
411
+ }
412
+ function createMockEmbedding(text, dimensions) {
413
+ const embedding = [];
414
+ const normalized = text.toLowerCase().trim();
415
+ for (let i = 0; i < dimensions; i++) {
416
+ let value = 0;
417
+ for (let j = 0; j < normalized.length; j++) {
418
+ const charCode = normalized.charCodeAt(j);
419
+ value += Math.sin(charCode * (i + 1) * 0.1) * Math.cos(j * 0.3);
420
+ }
421
+ embedding.push(Math.tanh(value / Math.max(1, normalized.length)));
422
+ }
423
+ const norm = Math.sqrt(embedding.reduce((sum, v) => sum + v * v, 0));
424
+ return embedding.map((v) => v / (norm || 1));
425
+ }
426
+ export {
427
+ createVectorCommand
428
+ };
429
+ //# sourceMappingURL=vector.js.map