@weavelogic/knowledge-graph-agent 0.11.4 → 0.11.5

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.
@@ -11,6 +11,7 @@
11
11
  *
12
12
  * @module cultivation/deep-analyzer
13
13
  */
14
+ import { ComplianceCheckResult, GapAnalysisResult } from '../sops/index.js';
14
15
  /**
15
16
  * Deep analyzer options
16
17
  */
@@ -59,6 +60,10 @@ export interface DeepAnalysisResult {
59
60
  duration: number;
60
61
  errors: string[];
61
62
  mode: 'cli' | 'anthropic' | 'gemini' | 'static';
63
+ /** SOP compliance check result */
64
+ sopCompliance?: ComplianceCheckResult;
65
+ /** SOP gap analysis result */
66
+ sopGaps?: GapAnalysisResult;
62
67
  }
63
68
  /**
64
69
  * DeepAnalyzer - Documentation cultivation with AI-powered analysis
@@ -161,6 +166,22 @@ export declare class DeepAnalyzer {
161
166
  * Build context-aware prompt for documentation cultivation
162
167
  */
163
168
  private buildPrompt;
169
+ /**
170
+ * Run SOP compliance check against the documentation
171
+ */
172
+ private runSOPComplianceCheck;
173
+ /**
174
+ * Run SOP gap analysis on compliance results
175
+ */
176
+ private runSOPGapAnalysis;
177
+ /**
178
+ * Write SOP gaps summary to analysis output
179
+ */
180
+ private writeSOPGapsSummary;
181
+ /**
182
+ * Build SOP agent-specific instructions with gap context
183
+ */
184
+ private buildSOPAgentInstructions;
164
185
  /**
165
186
  * Run analysis using Claude CLI
166
187
  */
@@ -1 +1 @@
1
- {"version":3,"file":"deep-analyzer.d.ts","sourceRoot":"","sources":["../../src/cultivation/deep-analyzer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AASH;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,6BAA6B;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,oDAAoD;IACpD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4CAA4C;IAC5C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6BAA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B;IA4C5B;;OAEG;IACH,OAAO,CAAC,WAAW;IA+JnB;;OAEG;YACW,qBAAqB;IAyBnC;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAwBzB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IA+C3B;;OAEG;IACH,OAAO,CAAC,yBAAyB;IA6FjC;;OAEG;YACW,UAAU;IA4BxB;;OAEG;YACW,gBAAgB;IA8B9B;;OAEG;YACW,aAAa;IA4B3B;;OAEG;IACH,OAAO,CAAC,eAAe;IAqBvB;;OAEG;IACH,OAAO,CAAC,YAAY;CA6BrB;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,YAAY,CAE7E;AAED;;GAEG;AACH,wBAAsB,WAAW,CAC/B,WAAW,EAAE,MAAM,EACnB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,kBAAkB,CAAC,CAG7B"}
@@ -2,6 +2,11 @@ import { execFileSync, execSync } from "child_process";
2
2
  import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from "fs";
3
3
  import { resolve, join, extname, relative, basename } from "path";
4
4
  import { createLogger } from "../utils/logger.js";
5
+ import { SOPPriority } from "../sops/types.js";
6
+ import "../sops/registry.js";
7
+ import { checkCompliance } from "../sops/compliance-checker.js";
8
+ import { analyzeGaps } from "../sops/gap-analyzer.js";
9
+ import "../sops/overlay-manager.js";
5
10
  const logger = createLogger("deep-analyzer");
6
11
  class DeepAnalyzer {
7
12
  projectRoot;
@@ -359,6 +364,8 @@ class DeepAnalyzer {
359
364
  needsWork: dirCoverage.filter((d) => d.needsDocumentation).length,
360
365
  iteration
361
366
  });
367
+ const sopCompliance = await this.runSOPComplianceCheck();
368
+ const sopGaps = sopCompliance ? this.runSOPGapAnalysis(sopCompliance) : void 0;
362
369
  const agents = [
363
370
  {
364
371
  name: "Vision Synthesizer",
@@ -389,9 +396,20 @@ class DeepAnalyzer {
389
396
  type: "connections",
390
397
  task: "Identify relationships between concepts and suggest knowledge graph connections",
391
398
  outputFile: "knowledge-connections.md"
399
+ },
400
+ {
401
+ name: "SOP Compliance Analyst",
402
+ type: "sop",
403
+ task: "Analyze AI-SDLC SOP compliance gaps and recommend documentation to address them",
404
+ outputFile: "sop-compliance-gaps.md"
392
405
  }
393
406
  ];
394
- logger.info("Executing cultivation agents", { agents: agents.length, mode: "sequential", iteration });
407
+ logger.info("Executing cultivation agents", {
408
+ agents: agents.length,
409
+ mode: "sequential",
410
+ iteration,
411
+ sopGapsCount: sopGaps?.totalGaps || 0
412
+ });
395
413
  for (const agent of agents) {
396
414
  const agentResult = await this.executeAgent(
397
415
  agent,
@@ -399,10 +417,13 @@ class DeepAnalyzer {
399
417
  documents,
400
418
  keyDocs,
401
419
  dirCoverage,
402
- previousAnalysis
420
+ previousAnalysis,
421
+ sopGaps
403
422
  );
404
423
  result.results.push(agentResult);
405
424
  }
425
+ result.sopCompliance = sopCompliance;
426
+ result.sopGaps = sopGaps;
406
427
  this.saveAnalysisMetadata(result, dirCoverage);
407
428
  result.agentsSpawned = result.results.length;
408
429
  result.insightsCount = result.results.reduce((sum, r) => sum + r.insights.length, 0);
@@ -425,7 +446,7 @@ class DeepAnalyzer {
425
446
  /**
426
447
  * Execute a single agent
427
448
  */
428
- async executeAgent(agent, mode, documents, keyDocs, dirCoverage, previousAnalysis) {
449
+ async executeAgent(agent, mode, documents, keyDocs, dirCoverage, previousAnalysis, sopGaps) {
429
450
  const startTime = Date.now();
430
451
  const outputPath = join(this.outputDir, agent.outputFile);
431
452
  const result = {
@@ -438,7 +459,7 @@ class DeepAnalyzer {
438
459
  };
439
460
  try {
440
461
  logger.info(`Executing agent: ${agent.name}`, { type: agent.type, mode });
441
- const prompt = this.buildPrompt(agent, documents, keyDocs, dirCoverage, previousAnalysis);
462
+ const prompt = this.buildPrompt(agent, documents, keyDocs, dirCoverage, previousAnalysis, sopGaps);
442
463
  let output;
443
464
  if (mode === "cli") {
444
465
  output = await this.runWithCli(prompt);
@@ -502,7 +523,7 @@ class DeepAnalyzer {
502
523
  /**
503
524
  * Build context-aware prompt for documentation cultivation
504
525
  */
505
- buildPrompt(agent, documents, keyDocs, dirCoverage, previousAnalysis) {
526
+ buildPrompt(agent, documents, keyDocs, dirCoverage, previousAnalysis, sopGaps) {
506
527
  const inventory = documents.map((d) => `- ${d.path} (${d.type}): ${d.title}`).join("\n");
507
528
  const keyContent = Array.from(keyDocs.entries()).map(([name, content]) => `### ${name}
508
529
 
@@ -604,6 +625,9 @@ Suggest knowledge graph nodes and edges in this format:
604
625
 
605
626
  Also identify concepts that should be linked but aren't currently.`;
606
627
  break;
628
+ case "sop":
629
+ specificInstructions = this.buildSOPAgentInstructions(sopGaps);
630
+ break;
607
631
  }
608
632
  return `You are a documentation analyst helping to cultivate a knowledge graph.
609
633
  ${iterationContext}
@@ -634,6 +658,187 @@ Reference specific documents using [[document-name]] wiki-link format where rele
634
658
  Be specific and actionable in your analysis.
635
659
  ${previousAnalysis ? "\nFocus on NEW items not identified in previous iterations." : ""}`;
636
660
  }
661
+ /**
662
+ * Run SOP compliance check against the documentation
663
+ */
664
+ async runSOPComplianceCheck() {
665
+ try {
666
+ logger.info("Running SOP compliance check", { projectRoot: this.projectRoot });
667
+ const result = await checkCompliance({
668
+ projectRoot: this.projectRoot,
669
+ docsPath: this.docsPath,
670
+ deepAnalysis: false,
671
+ assessor: "deep-analyzer"
672
+ });
673
+ logger.info("SOP compliance check complete", {
674
+ score: result.overallScore,
675
+ compliant: result.assessments.filter((a) => a.score >= 70).length,
676
+ nonCompliant: result.assessments.filter((a) => a.score < 70).length
677
+ });
678
+ return result;
679
+ } catch (error) {
680
+ logger.warn("SOP compliance check failed", { error: error instanceof Error ? error.message : String(error) });
681
+ return void 0;
682
+ }
683
+ }
684
+ /**
685
+ * Run SOP gap analysis on compliance results
686
+ */
687
+ runSOPGapAnalysis(compliance) {
688
+ try {
689
+ const result = analyzeGaps(compliance, {
690
+ complianceThreshold: 70,
691
+ includePartial: true,
692
+ generateRemediation: true
693
+ });
694
+ logger.info("SOP gap analysis complete", {
695
+ totalGaps: result.totalGaps,
696
+ criticalGaps: result.criticalGaps.length,
697
+ compliancePercentage: result.summary.compliancePercentage
698
+ });
699
+ this.writeSOPGapsSummary(result);
700
+ return result;
701
+ } catch (error) {
702
+ logger.warn("SOP gap analysis failed", { error: error instanceof Error ? error.message : String(error) });
703
+ return void 0;
704
+ }
705
+ }
706
+ /**
707
+ * Write SOP gaps summary to analysis output
708
+ */
709
+ writeSOPGapsSummary(gaps) {
710
+ const summaryPath = join(this.outputDir, "sop-gaps-summary.json");
711
+ try {
712
+ const summary = {
713
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
714
+ totalGaps: gaps.totalGaps,
715
+ criticalGaps: gaps.criticalGaps.length,
716
+ summary: gaps.summary,
717
+ byPriority: {
718
+ critical: gaps.byPriority[SOPPriority.CRITICAL].length,
719
+ high: gaps.byPriority[SOPPriority.HIGH].length,
720
+ medium: gaps.byPriority[SOPPriority.MEDIUM].length,
721
+ low: gaps.byPriority[SOPPriority.LOW].length
722
+ },
723
+ byCategory: Object.entries(gaps.byCategory).reduce((acc, [key, value]) => {
724
+ acc[key] = value.length;
725
+ return acc;
726
+ }, {}),
727
+ gaps: gaps.gaps.map((g) => ({
728
+ id: g.id,
729
+ sopId: g.sopId,
730
+ requirementId: g.requirementId,
731
+ description: g.description,
732
+ priority: g.priority,
733
+ effort: g.effort,
734
+ remediation: g.remediation
735
+ })),
736
+ roadmap: gaps.roadmap ? {
737
+ phases: gaps.roadmap.phases.map((p) => ({
738
+ phase: p.phase,
739
+ name: p.name,
740
+ focus: p.focus,
741
+ effort: p.effort,
742
+ gapCount: p.gaps.length
743
+ })),
744
+ quickWinsCount: gaps.roadmap.quickWins.length
745
+ } : void 0
746
+ };
747
+ writeFileSync(summaryPath, JSON.stringify(summary, null, 2));
748
+ logger.debug("Wrote SOP gaps summary", { path: summaryPath });
749
+ } catch (error) {
750
+ logger.warn("Failed to write SOP gaps summary", { error: error instanceof Error ? error.message : String(error) });
751
+ }
752
+ }
753
+ /**
754
+ * Build SOP agent-specific instructions with gap context
755
+ */
756
+ buildSOPAgentInstructions(sopGaps) {
757
+ let instructions = `
758
+ Analyze AI-SDLC SOP (Standard Operating Procedures) compliance gaps and recommend documentation:
759
+
760
+ 1. **Gap Prioritization**: Review the compliance gaps and prioritize by impact
761
+ 2. **Documentation Recommendations**: For each gap, suggest what documentation should be created
762
+ 3. **Remediation Steps**: Provide actionable steps to address each gap
763
+ 4. **Quick Wins**: Identify low-effort, high-impact gaps that can be addressed quickly
764
+ 5. **Documentation Templates**: Suggest document templates for common gap types
765
+
766
+ For each gap, recommend:
767
+ - Document type (guide, standard, process, reference)
768
+ - Suggested file path (using project conventions)
769
+ - Key sections to include
770
+ - Related documents to link to ([[wiki-links]])
771
+ - Priority level (high/medium/low)
772
+ `;
773
+ if (sopGaps && sopGaps.totalGaps > 0) {
774
+ instructions += `
775
+ ## Current SOP Compliance Gaps
776
+
777
+ **Summary:**
778
+ - Total Gaps: ${sopGaps.totalGaps}
779
+ - Critical Gaps: ${sopGaps.criticalGaps.length}
780
+ - Compliance Score: ${sopGaps.summary.compliancePercentage}%
781
+
782
+ ### Gaps by Priority:
783
+ - Critical: ${sopGaps.byPriority[SOPPriority.CRITICAL].length}
784
+ - High: ${sopGaps.byPriority[SOPPriority.HIGH].length}
785
+ - Medium: ${sopGaps.byPriority[SOPPriority.MEDIUM].length}
786
+ - Low: ${sopGaps.byPriority[SOPPriority.LOW].length}
787
+
788
+ ### Detailed Gaps:
789
+ `;
790
+ const priorityGaps = [
791
+ ...sopGaps.byPriority[SOPPriority.CRITICAL],
792
+ ...sopGaps.byPriority[SOPPriority.HIGH]
793
+ ].slice(0, 15);
794
+ for (const gap of priorityGaps) {
795
+ instructions += `
796
+ #### ${gap.priority.toUpperCase()}: ${gap.description}
797
+ - SOP: ${gap.sopId}
798
+ - Requirement: ${gap.requirementId}
799
+ - Effort: ${gap.effort}
800
+ - Remediation: ${gap.remediation}
801
+ - Impact: ${gap.impact}
802
+ `;
803
+ }
804
+ if (sopGaps.roadmap) {
805
+ instructions += `
806
+ ### Remediation Roadmap:
807
+ `;
808
+ for (const phase of sopGaps.roadmap.phases) {
809
+ instructions += `
810
+ **Phase ${phase.phase}: ${phase.name}**
811
+ - Focus: ${phase.focus}
812
+ - Effort: ${phase.effort}
813
+ - Gaps to address: ${phase.gaps.length}
814
+ `;
815
+ }
816
+ if (sopGaps.roadmap.quickWins.length > 0) {
817
+ instructions += `
818
+ ### Quick Wins (High Impact, Low Effort):
819
+ `;
820
+ for (const win of sopGaps.roadmap.quickWins.slice(0, 5)) {
821
+ instructions += `- ${win.description} (${win.effort} effort)
822
+ `;
823
+ }
824
+ }
825
+ }
826
+ } else {
827
+ instructions += `
828
+ ## No SOP Gaps Data Available
829
+
830
+ Perform a general AI-SDLC compliance analysis based on the documentation structure.
831
+ Review for common compliance areas:
832
+ - Requirements documentation
833
+ - Architecture documentation
834
+ - Testing documentation
835
+ - Security documentation
836
+ - Deployment documentation
837
+ - Operational procedures
838
+ `;
839
+ }
840
+ return instructions;
841
+ }
637
842
  /**
638
843
  * Run analysis using Claude CLI
639
844
  */
@@ -1 +1 @@
1
- {"version":3,"file":"deep-analyzer.js","sources":["../../src/cultivation/deep-analyzer.ts"],"sourcesContent":["/**\n * DeepAnalyzer - Documentation Cultivation & Knowledge Graph Enhancement\n *\n * Analyzes existing documentation to:\n * - Understand the vision and requirements described\n * - Identify documentation gaps and unclear areas\n * - Guide the documentation process with research questions\n * - Build knowledge graph connections\n *\n * This is NOT for code analysis - use analyze-codebase for that.\n *\n * @module cultivation/deep-analyzer\n */\n\nimport { execFileSync, execSync } from 'child_process';\nimport { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, statSync } from 'fs';\nimport { join, resolve, relative, basename, extname } from 'path';\nimport { createLogger } from '../utils/index.js';\n\nconst logger = createLogger('deep-analyzer');\n\n/**\n * Deep analyzer options\n */\nexport interface DeepAnalyzerOptions {\n /** Project root directory */\n projectRoot: string;\n /** Documentation path (relative to project root) */\n docsPath?: string;\n /** Output directory for analysis results */\n outputDir?: string;\n /** Enable verbose logging */\n verbose?: boolean;\n /** Maximum documents to analyze */\n maxDocuments?: number;\n /** Timeout for each analysis (ms) */\n agentTimeout?: number;\n /** Force use of API key even if CLI is available */\n forceApiKey?: boolean;\n /** Preferred provider when multiple are available */\n preferredProvider?: 'anthropic' | 'gemini';\n}\n\n/**\n * Analysis result from an agent\n */\nexport interface AgentResult {\n name: string;\n type: string;\n success: boolean;\n insights: string[];\n documents: Array<{ path: string; title: string }>;\n duration: number;\n error?: string;\n}\n\n/**\n * Deep analysis result\n */\nexport interface DeepAnalysisResult {\n success: boolean;\n agentsSpawned: number;\n insightsCount: number;\n documentsCreated: number;\n results: AgentResult[];\n duration: number;\n errors: string[];\n mode: 'cli' | 'anthropic' | 'gemini' | 'static';\n}\n\n/**\n * Agent configuration\n */\ninterface AgentConfig {\n name: string;\n type: string;\n task: string;\n outputFile: string;\n}\n\n/**\n * Execution mode detection result\n */\ninterface ExecutionMode {\n mode: 'cli' | 'anthropic' | 'gemini' | 'unavailable';\n reason: string;\n}\n\n/**\n * Document metadata for analysis\n */\ninterface DocMetadata {\n path: string;\n title: string;\n type: string;\n size: number;\n preview: string;\n}\n\n/**\n * Directory coverage information\n */\ninterface DirectoryCoverage {\n path: string;\n name: string;\n hasMOC: boolean;\n mocStatus: 'complete' | 'stub' | 'empty' | 'missing';\n documentCount: number;\n subdirectories: string[];\n documents: string[];\n needsDocumentation: boolean;\n reason?: string;\n}\n\n/**\n * Previous analysis metadata for iteration tracking\n */\ninterface PreviousAnalysis {\n timestamp: string;\n iteration: number;\n gapsIdentified: number;\n gapsFilled: number;\n questionsRaised: number;\n questionsAnswered: number;\n coverageScore: number;\n}\n\n/**\n * DeepAnalyzer - Documentation cultivation with AI-powered analysis\n *\n * Reads existing markdown documentation and provides:\n * - Vision synthesis from requirements\n * - Gap analysis identifying missing documentation\n * - Research questions for unclear areas\n * - Knowledge graph connection suggestions\n *\n * @example\n * ```typescript\n * const analyzer = new DeepAnalyzer({\n * projectRoot: '/my/project',\n * docsPath: 'docs',\n * });\n *\n * const result = await analyzer.analyze();\n * console.log(`Generated ${result.insightsCount} insights`);\n * ```\n */\nexport class DeepAnalyzer {\n private projectRoot: string;\n private docsPath: string;\n private outputDir: string;\n private verbose: boolean;\n private maxDocuments: number;\n private agentTimeout: number;\n private forceApiKey: boolean;\n private preferredProvider: 'anthropic' | 'gemini';\n\n constructor(options: DeepAnalyzerOptions) {\n this.projectRoot = resolve(options.projectRoot);\n this.docsPath = options.docsPath || 'docs';\n this.outputDir = options.outputDir || join(this.projectRoot, this.docsPath, 'analysis');\n this.verbose = options.verbose || false;\n this.maxDocuments = options.maxDocuments || 50;\n // Default timeout of 2 minutes (120 seconds)\n this.agentTimeout = options.agentTimeout || 120000;\n this.forceApiKey = options.forceApiKey || false;\n this.preferredProvider = options.preferredProvider || 'anthropic';\n }\n\n /**\n * Check if running inside a Claude Code session\n */\n private isInsideClaudeCode(): boolean {\n return process.env.CLAUDECODE === '1' || process.env.CLAUDE_CODE === '1';\n }\n\n /**\n * Check if Anthropic API key is available\n */\n private hasAnthropicApiKey(): boolean {\n return !!process.env.ANTHROPIC_API_KEY;\n }\n\n /**\n * Check if Google AI / Gemini API key is available\n */\n private hasGeminiApiKey(): boolean {\n return !!(\n process.env.GOOGLE_AI_API_KEY ||\n process.env.GOOGLE_GEMINI_API_KEY ||\n process.env.GEMINI_API_KEY ||\n process.env.GOOGLE_API_KEY\n );\n }\n\n /**\n * Get the Gemini API key from available env vars\n */\n private getGeminiApiKey(): string | undefined {\n return (\n process.env.GOOGLE_AI_API_KEY ||\n process.env.GOOGLE_GEMINI_API_KEY ||\n process.env.GEMINI_API_KEY ||\n process.env.GOOGLE_API_KEY\n );\n }\n\n /**\n * Check if Claude CLI is available\n */\n private isCliAvailable(): boolean {\n try {\n execFileSync('claude', ['--version'], {\n stdio: 'pipe',\n timeout: 5000,\n windowsHide: true,\n });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Determine the best execution mode\n */\n private detectExecutionMode(): ExecutionMode {\n const insideClaudeCode = this.isInsideClaudeCode();\n const hasAnthropicKey = this.hasAnthropicApiKey();\n const hasGeminiKey = this.hasGeminiApiKey();\n const cliAvailable = this.isCliAvailable();\n\n // If forced to use API key\n if (this.forceApiKey) {\n if (this.preferredProvider === 'gemini' && hasGeminiKey) {\n return { mode: 'gemini', reason: 'Using Gemini API (forced, preferred)' };\n }\n if (hasAnthropicKey) {\n return { mode: 'anthropic', reason: 'Using Anthropic API (forced)' };\n }\n if (hasGeminiKey) {\n return { mode: 'gemini', reason: 'Using Gemini API (forced, fallback)' };\n }\n return { mode: 'unavailable', reason: 'No API key found. Set ANTHROPIC_API_KEY or GOOGLE_AI_API_KEY.' };\n }\n\n // Prefer API keys for reliability\n if (this.preferredProvider === 'gemini' && hasGeminiKey) {\n return { mode: 'gemini', reason: 'Using Gemini API (preferred)' };\n }\n if (hasAnthropicKey) {\n return { mode: 'anthropic', reason: 'Using Anthropic API' };\n }\n if (hasGeminiKey) {\n return { mode: 'gemini', reason: 'Using Gemini API' };\n }\n\n // No API keys - try CLI as last resort\n if (insideClaudeCode) {\n return {\n mode: 'unavailable',\n reason: 'Cannot run inside Claude Code without an API key. Set ANTHROPIC_API_KEY or GOOGLE_AI_API_KEY.',\n };\n }\n\n if (cliAvailable) {\n return { mode: 'cli', reason: 'Using Claude CLI (no API key found)' };\n }\n\n return {\n mode: 'unavailable',\n reason: 'No execution method available. Set ANTHROPIC_API_KEY or GOOGLE_AI_API_KEY.',\n };\n }\n\n /**\n * Check if analysis is available\n */\n async isAvailable(): Promise<boolean> {\n const mode = this.detectExecutionMode();\n return mode.mode !== 'unavailable';\n }\n\n /**\n * Get availability status with reason\n */\n async getAvailabilityStatus(): Promise<{ available: boolean; reason: string }> {\n const mode = this.detectExecutionMode();\n return {\n available: mode.mode !== 'unavailable',\n reason: mode.reason,\n };\n }\n\n /**\n * Scan documentation directory for markdown files\n */\n private scanDocumentation(): DocMetadata[] {\n const docsDir = join(this.projectRoot, this.docsPath);\n if (!existsSync(docsDir)) {\n return [];\n }\n\n const documents: DocMetadata[] = [];\n const scan = (dir: string) => {\n const entries = readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'analysis') {\n continue;\n }\n\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n scan(fullPath);\n } else if (entry.isFile() && extname(entry.name) === '.md') {\n try {\n const content = readFileSync(fullPath, 'utf-8');\n const stats = statSync(fullPath);\n const relPath = relative(docsDir, fullPath);\n\n // Extract title from first heading or filename\n const titleMatch = content.match(/^#\\s+(.+)$/m);\n const title = titleMatch ? titleMatch[1] : basename(entry.name, '.md');\n\n // Determine document type from path or frontmatter\n let type = 'general';\n if (relPath.includes('concepts/')) type = 'concept';\n else if (relPath.includes('components/')) type = 'component';\n else if (relPath.includes('services/')) type = 'service';\n else if (relPath.includes('features/')) type = 'feature';\n else if (relPath.includes('guides/')) type = 'guide';\n else if (relPath.includes('standards/')) type = 'standard';\n else if (relPath.includes('references/')) type = 'reference';\n else if (relPath.includes('integrations/')) type = 'integration';\n else if (entry.name.includes('requirement')) type = 'requirement';\n else if (entry.name.includes('spec')) type = 'specification';\n\n // Get preview (first 500 chars after title)\n const preview = content.slice(0, 2000).replace(/^#.+\\n/, '').trim().slice(0, 500);\n\n documents.push({\n path: relPath,\n title,\n type,\n size: stats.size,\n preview,\n });\n } catch {\n // Skip files that can't be read\n }\n }\n }\n };\n\n scan(docsDir);\n return documents.slice(0, this.maxDocuments);\n }\n\n /**\n * Read full content of key documents\n */\n private readKeyDocuments(): Map<string, string> {\n const docsDir = join(this.projectRoot, this.docsPath);\n const keyDocs = new Map<string, string>();\n\n // Priority documents to read in full\n const priorityFiles = [\n 'README.md',\n 'MOC.md',\n 'PRIMITIVES.md',\n 'original_specs.md',\n 'business_requirements_document.md',\n 'technical_requirements.md',\n 'test_strategy.md',\n ];\n\n for (const file of priorityFiles) {\n const filePath = join(docsDir, file);\n if (existsSync(filePath)) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n // Limit to 15KB per document to fit in context\n keyDocs.set(file, content.slice(0, 15000));\n } catch {\n // Skip\n }\n }\n }\n\n return keyDocs;\n }\n\n /**\n * Scan directory structure for MOC files and coverage\n */\n private scanDirectoryStructure(): DirectoryCoverage[] {\n const docsDir = join(this.projectRoot, this.docsPath);\n if (!existsSync(docsDir)) {\n return [];\n }\n\n const directories: DirectoryCoverage[] = [];\n const ignoredDirs = new Set(['.', '..', 'analysis', 'node_modules', '.git', '.obsidian']);\n\n const scanDir = (dir: string, depth: number = 0): void => {\n if (depth > 5) return; // Max depth to prevent infinite loops\n\n const relPath = relative(docsDir, dir) || '.';\n const entries = readdirSync(dir, { withFileTypes: true });\n\n const subdirs: string[] = [];\n const docs: string[] = [];\n let mocFile: string | null = null;\n let mocContent = '';\n\n for (const entry of entries) {\n if (ignoredDirs.has(entry.name) || entry.name.startsWith('.')) continue;\n\n if (entry.isDirectory()) {\n subdirs.push(entry.name);\n scanDir(join(dir, entry.name), depth + 1);\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n docs.push(entry.name);\n if (entry.name === '_MOC.md' || entry.name === 'MOC.md' || entry.name === 'index.md') {\n mocFile = entry.name;\n try {\n mocContent = readFileSync(join(dir, entry.name), 'utf-8');\n } catch {\n mocContent = '';\n }\n }\n }\n }\n\n // Determine MOC status\n let mocStatus: DirectoryCoverage['mocStatus'] = 'missing';\n if (mocFile) {\n if (mocContent.length < 100) {\n mocStatus = 'empty';\n } else if (\n mocContent.toLowerCase().includes('stub') ||\n mocContent.includes('TODO') ||\n mocContent.includes('TBD') ||\n !mocContent.includes('[[')\n ) {\n mocStatus = 'stub';\n } else {\n mocStatus = 'complete';\n }\n }\n\n // Determine if documentation is needed\n let needsDocumentation = false;\n let reason = '';\n\n if (subdirs.length > 0 || docs.length > 1) {\n if (mocStatus === 'missing') {\n needsDocumentation = true;\n reason = 'Directory has content but no MOC file';\n } else if (mocStatus === 'empty' || mocStatus === 'stub') {\n needsDocumentation = true;\n reason = `MOC file is ${mocStatus} - needs content`;\n }\n }\n\n // Only track directories that have content or subdirectories\n if (subdirs.length > 0 || docs.length > 0 || relPath === '.') {\n directories.push({\n path: relPath,\n name: basename(dir),\n hasMOC: mocFile !== null,\n mocStatus,\n documentCount: docs.length,\n subdirectories: subdirs,\n documents: docs,\n needsDocumentation,\n reason,\n });\n }\n };\n\n scanDir(docsDir);\n return directories;\n }\n\n /**\n * Load previous analysis results for iteration tracking\n */\n private loadPreviousAnalysis(): PreviousAnalysis | null {\n const metadataFile = join(this.outputDir, '.analysis-metadata.json');\n\n if (!existsSync(metadataFile)) {\n return null;\n }\n\n try {\n const content = readFileSync(metadataFile, 'utf-8');\n return JSON.parse(content) as PreviousAnalysis;\n } catch {\n return null;\n }\n }\n\n /**\n * Save analysis metadata for iteration tracking\n */\n private saveAnalysisMetadata(result: DeepAnalysisResult, dirCoverage: DirectoryCoverage[]): void {\n const metadataFile = join(this.outputDir, '.analysis-metadata.json');\n const previous = this.loadPreviousAnalysis();\n\n // Count coverage metrics\n const totalDirs = dirCoverage.length;\n const coveredDirs = dirCoverage.filter(d => d.mocStatus === 'complete').length;\n const coverageScore = totalDirs > 0 ? (coveredDirs / totalDirs) * 100 : 0;\n\n // Count gaps and questions from results\n const gapsResult = result.results.find(r => r.type === 'gaps');\n const questionsResult = result.results.find(r => r.type === 'research');\n const coverageResult = result.results.find(r => r.type === 'coverage');\n\n const metadata: PreviousAnalysis = {\n timestamp: new Date().toISOString(),\n iteration: (previous?.iteration || 0) + 1,\n gapsIdentified: (gapsResult?.insights.length || 0) + (coverageResult?.insights.length || 0),\n gapsFilled: 0, // Updated by migrate command\n questionsRaised: questionsResult?.insights.length || 0,\n questionsAnswered: 0, // Updated by migrate command\n coverageScore,\n };\n\n try {\n writeFileSync(metadataFile, JSON.stringify(metadata, null, 2));\n } catch {\n // Non-critical, continue\n }\n }\n\n /**\n * Run deep analysis\n */\n async analyze(): Promise<DeepAnalysisResult> {\n const startTime = Date.now();\n const executionMode = this.detectExecutionMode();\n\n const result: DeepAnalysisResult = {\n success: false,\n agentsSpawned: 0,\n insightsCount: 0,\n documentsCreated: 0,\n results: [],\n duration: 0,\n errors: [],\n mode: executionMode.mode === 'unavailable' ? 'static' : executionMode.mode,\n };\n\n // Check availability\n if (executionMode.mode === 'unavailable') {\n result.errors.push(executionMode.reason);\n result.duration = Date.now() - startTime;\n logger.error('Deep analysis unavailable', new Error(executionMode.reason));\n return result;\n }\n\n logger.info(`Starting documentation cultivation`, { mode: executionMode.mode, reason: executionMode.reason });\n\n // Ensure output directory exists\n if (!existsSync(this.outputDir)) {\n mkdirSync(this.outputDir, { recursive: true });\n }\n\n // Scan existing documentation\n const documents = this.scanDocumentation();\n const keyDocs = this.readKeyDocuments();\n const dirCoverage = this.scanDirectoryStructure();\n const previousAnalysis = this.loadPreviousAnalysis();\n\n if (documents.length === 0) {\n result.errors.push('No markdown documents found in docs directory');\n result.duration = Date.now() - startTime;\n return result;\n }\n\n // Log iteration info\n const iteration = (previousAnalysis?.iteration || 0) + 1;\n logger.info('Found documentation', {\n documents: documents.length,\n keyDocs: keyDocs.size,\n directories: dirCoverage.length,\n needsWork: dirCoverage.filter(d => d.needsDocumentation).length,\n iteration,\n });\n\n // Define documentation cultivation agents - including Directory Coverage\n const agents: AgentConfig[] = [\n {\n name: 'Vision Synthesizer',\n type: 'vision',\n task: 'Synthesize the project vision, goals, and core value proposition from the documentation',\n outputFile: 'vision-synthesis.md',\n },\n {\n name: 'Directory Coverage Analyst',\n type: 'coverage',\n task: 'Analyze directory structure, MOC files, and identify areas needing documentation',\n outputFile: 'directory-coverage.md',\n },\n {\n name: 'Gap Analyst',\n type: 'gaps',\n task: 'Identify documentation gaps, missing sections, and areas that need more detail',\n outputFile: 'documentation-gaps.md',\n },\n {\n name: 'Research Guide',\n type: 'research',\n task: 'Generate research questions and areas that need further investigation or clarification',\n outputFile: 'research-questions.md',\n },\n {\n name: 'Connection Mapper',\n type: 'connections',\n task: 'Identify relationships between concepts and suggest knowledge graph connections',\n outputFile: 'knowledge-connections.md',\n },\n ];\n\n logger.info('Executing cultivation agents', { agents: agents.length, mode: 'sequential', iteration });\n\n // Execute agents sequentially\n for (const agent of agents) {\n const agentResult = await this.executeAgent(\n agent,\n executionMode.mode as 'cli' | 'anthropic' | 'gemini',\n documents,\n keyDocs,\n dirCoverage,\n previousAnalysis\n );\n result.results.push(agentResult);\n }\n\n // Save metadata for iteration tracking\n this.saveAnalysisMetadata(result, dirCoverage);\n\n // Calculate totals\n result.agentsSpawned = result.results.length;\n result.insightsCount = result.results.reduce((sum, r) => sum + r.insights.length, 0);\n result.documentsCreated = result.results.reduce((sum, r) => sum + r.documents.length, 0);\n result.success = result.results.some(r => r.success);\n result.duration = Date.now() - startTime;\n\n // Collect errors\n for (const agentResult of result.results) {\n if (agentResult.error) {\n result.errors.push(`${agentResult.name}: ${agentResult.error}`);\n }\n }\n\n logger.info('Documentation cultivation complete', {\n success: result.success,\n insights: result.insightsCount,\n documents: result.documentsCreated,\n duration: result.duration,\n });\n\n return result;\n }\n\n /**\n * Execute a single agent\n */\n private async executeAgent(\n agent: AgentConfig,\n mode: 'cli' | 'anthropic' | 'gemini',\n documents: DocMetadata[],\n keyDocs: Map<string, string>,\n dirCoverage: DirectoryCoverage[],\n previousAnalysis: PreviousAnalysis | null\n ): Promise<AgentResult> {\n const startTime = Date.now();\n const outputPath = join(this.outputDir, agent.outputFile);\n\n const result: AgentResult = {\n name: agent.name,\n type: agent.type,\n success: false,\n insights: [],\n documents: [],\n duration: 0,\n };\n\n try {\n logger.info(`Executing agent: ${agent.name}`, { type: agent.type, mode });\n\n const prompt = this.buildPrompt(agent, documents, keyDocs, dirCoverage, previousAnalysis);\n let output: string;\n\n if (mode === 'cli') {\n output = await this.runWithCli(prompt);\n } else if (mode === 'anthropic') {\n output = await this.runWithAnthropic(prompt);\n } else {\n output = await this.runWithGemini(prompt);\n }\n\n // Parse output for insights\n result.insights = this.extractInsights(output);\n\n // Write output to file\n writeFileSync(outputPath, this.formatOutput(agent, output, mode));\n result.documents.push({ path: outputPath, title: agent.name });\n\n result.success = true;\n\n if (this.verbose) {\n logger.debug(`Agent completed: ${agent.name}`, { insights: result.insights.length });\n }\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error);\n logger.error(`Agent failed: ${agent.name}`, error instanceof Error ? error : new Error(String(error)));\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n\n /**\n * Build directory coverage summary for prompts\n */\n private buildCoverageSummary(dirCoverage: DirectoryCoverage[]): string {\n const lines: string[] = [];\n\n // Summary stats\n const total = dirCoverage.length;\n const complete = dirCoverage.filter(d => d.mocStatus === 'complete').length;\n const stub = dirCoverage.filter(d => d.mocStatus === 'stub').length;\n const empty = dirCoverage.filter(d => d.mocStatus === 'empty').length;\n const missing = dirCoverage.filter(d => d.mocStatus === 'missing').length;\n\n lines.push(`### Summary`);\n lines.push(`- Total Directories: ${total}`);\n lines.push(`- Complete MOCs: ${complete} (${((complete / total) * 100).toFixed(1)}%)`);\n lines.push(`- Stub MOCs: ${stub}`);\n lines.push(`- Empty MOCs: ${empty}`);\n lines.push(`- Missing MOCs: ${missing}`);\n lines.push(`- Coverage Score: ${((complete / total) * 100).toFixed(1)}%`);\n lines.push('');\n\n // Directories needing work\n const needsWork = dirCoverage.filter(d => d.needsDocumentation);\n if (needsWork.length > 0) {\n lines.push('### Directories Needing Documentation');\n for (const dir of needsWork) {\n lines.push(`- **${dir.path}/** (${dir.mocStatus})`);\n lines.push(` - Documents: ${dir.documents.join(', ') || 'none'}`);\n lines.push(` - Subdirectories: ${dir.subdirectories.join(', ') || 'none'}`);\n lines.push(` - Reason: ${dir.reason}`);\n }\n lines.push('');\n }\n\n // Complete directories\n const completeDirs = dirCoverage.filter(d => d.mocStatus === 'complete');\n if (completeDirs.length > 0) {\n lines.push('### Directories with Complete MOCs');\n for (const dir of completeDirs) {\n lines.push(`- ${dir.path}/ (${dir.documentCount} docs)`);\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Build context-aware prompt for documentation cultivation\n */\n private buildPrompt(\n agent: AgentConfig,\n documents: DocMetadata[],\n keyDocs: Map<string, string>,\n dirCoverage: DirectoryCoverage[],\n previousAnalysis: PreviousAnalysis | null\n ): string {\n // Build document inventory\n const inventory = documents.map(d => `- ${d.path} (${d.type}): ${d.title}`).join('\\n');\n\n // Build key document content\n const keyContent = Array.from(keyDocs.entries())\n .map(([name, content]) => `### ${name}\\n\\n${content}`)\n .join('\\n\\n---\\n\\n');\n\n // Build directory coverage summary\n const coverageSummary = this.buildCoverageSummary(dirCoverage);\n\n // Build iteration context\n const iterationContext = previousAnalysis\n ? `\\n## Previous Analysis (Iteration ${previousAnalysis.iteration})\n- Timestamp: ${previousAnalysis.timestamp}\n- Gaps Identified: ${previousAnalysis.gapsIdentified}\n- Gaps Filled: ${previousAnalysis.gapsFilled}\n- Questions Raised: ${previousAnalysis.questionsRaised}\n- Questions Answered: ${previousAnalysis.questionsAnswered}\n- Coverage Score: ${previousAnalysis.coverageScore.toFixed(1)}%\n\nFocus on NEW gaps and questions not addressed in previous iterations.\n`\n : '';\n\n // Agent-specific instructions\n let specificInstructions = '';\n switch (agent.type) {\n case 'coverage':\n specificInstructions = `\nFocus on directory structure and MOC (Map of Content) files:\n\n1. **Directory Analysis**: Review each directory and its MOC file status\n2. **Empty/Stub MOCs**: Identify MOC files that are empty or just stubs\n3. **Missing MOCs**: Identify directories that need MOC files\n4. **Documentation Needs**: For each directory, determine what documentation is needed\n5. **Not Needed**: If a directory genuinely doesn't need documentation, explain why\n\nFor each directory needing work:\n- State the directory path\n- Current MOC status (missing/empty/stub/complete)\n- What documentation should be added\n- Priority (high/medium/low)\n- Suggested content or links to include\n\nThe goal is 100% documentation coverage - every directory should either:\n1. Have a complete MOC with links to contents\n2. Have documentation explaining why it doesn't need more docs\n3. Be marked for future documentation\n\n## Directory Coverage Status\n${coverageSummary}`;\n break;\n\n case 'vision':\n specificInstructions = `\nFocus on:\n1. What is the core purpose/goal of this project?\n2. What problem does it solve?\n3. What is the target audience/user?\n4. What are the key success metrics?\n5. What is the overall architecture vision?\n\nProvide a clear, concise synthesis of the project vision with references to specific documentation.`;\n break;\n\n case 'gaps':\n specificInstructions = `\nIdentify:\n1. Missing documentation (what topics are mentioned but not explained?)\n2. Incomplete sections (what areas need more detail?)\n3. Outdated information (anything that seems inconsistent?)\n4. Missing examples or use cases\n5. Unclear terminology or concepts that need definitions\n6. Empty or stub MOC files that need content (see Directory Coverage below)\n\nFor each gap, specify:\n- What is missing\n- Where it should be documented (specific file path)\n- Why it's important\n- Priority (high/medium/low)\n\n## Directory Coverage Status\n${coverageSummary}`;\n break;\n\n case 'research':\n specificInstructions = `\nGenerate research questions in these categories:\n1. Technical questions (how should X be implemented?)\n2. Design decisions (why this approach vs alternatives?)\n3. Integration questions (how does X connect to Y?)\n4. Validation questions (how do we verify X works?)\n5. Scalability questions (will this work at scale?)\n\nFor each question:\n- State the question clearly\n- Explain why answering it is important\n- Suggest where to look for answers`;\n break;\n\n case 'connections':\n specificInstructions = `\nIdentify relationships between documented concepts:\n1. Dependencies (X requires Y)\n2. Extensions (X extends Y)\n3. Alternatives (X is an alternative to Y)\n4. Compositions (X is made up of Y and Z)\n5. References (X references Y for details)\n\nSuggest knowledge graph nodes and edges in this format:\n- [Node A] --relationship--> [Node B]: description\n\nAlso identify concepts that should be linked but aren't currently.`;\n break;\n }\n\n return `You are a documentation analyst helping to cultivate a knowledge graph.\n${iterationContext}\n## Your Task\n${agent.task}\n\n## Documentation Inventory\nThe following markdown documents exist in this project:\n${inventory}\n\n## Key Document Contents\n\n${keyContent}\n\n## Instructions\n${specificInstructions}\n\n## Output Format\nProvide your analysis in markdown format with:\n1. Clear section headings\n2. Specific observations (prefix with \"Observation:\")\n3. Specific recommendations (prefix with \"Recommendation:\")\n4. Key findings (prefix with \"Finding:\")\n5. Research questions where applicable (prefix with \"Question:\")\n6. Priority levels (high/medium/low) for actionable items\n\nReference specific documents using [[document-name]] wiki-link format where relevant.\nBe specific and actionable in your analysis.\n${previousAnalysis ? '\\nFocus on NEW items not identified in previous iterations.' : ''}`;\n }\n\n /**\n * Run analysis using Claude CLI\n */\n private async runWithCli(prompt: string): Promise<string> {\n const sanitizedPrompt = prompt\n .replace(/\"/g, '\\\\\"')\n .replace(/[`$]/g, '');\n\n try {\n const result = execSync(`claude -p \"${sanitizedPrompt}\"`, {\n cwd: this.projectRoot,\n encoding: 'utf8',\n timeout: this.agentTimeout,\n maxBuffer: 10 * 1024 * 1024,\n });\n return result;\n } catch (error) {\n if (error instanceof Error) {\n const execError = error as { stderr?: string; stdout?: string; killed?: boolean };\n if (execError.killed) {\n if (execError.stdout && execError.stdout.length > 100) {\n return execError.stdout;\n }\n throw new Error(`Claude CLI timed out after ${this.agentTimeout / 1000}s`);\n }\n throw new Error(execError.stderr || error.message);\n }\n throw error;\n }\n }\n\n /**\n * Run analysis using Anthropic API directly\n */\n private async runWithAnthropic(prompt: string): Promise<string> {\n const apiKey = process.env.ANTHROPIC_API_KEY;\n if (!apiKey) {\n throw new Error('ANTHROPIC_API_KEY not set');\n }\n\n try {\n const { default: Anthropic } = await import('@anthropic-ai/sdk');\n const client = new Anthropic({ apiKey });\n\n const response = await client.messages.create({\n model: 'claude-sonnet-4-20250514',\n max_tokens: 4096,\n messages: [{ role: 'user', content: prompt }],\n });\n\n const textBlock = response.content.find(block => block.type === 'text');\n if (textBlock && textBlock.type === 'text') {\n return textBlock.text;\n }\n\n throw new Error('No text content in API response');\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Anthropic API call failed: ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Run analysis using Google Gemini API\n */\n private async runWithGemini(prompt: string): Promise<string> {\n const apiKey = this.getGeminiApiKey();\n if (!apiKey) {\n throw new Error('GOOGLE_AI_API_KEY not set');\n }\n\n try {\n const { GoogleGenerativeAI } = await import('@google/generative-ai');\n const genAI = new GoogleGenerativeAI(apiKey);\n const model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' });\n\n const result = await model.generateContent(prompt);\n const response = result.response;\n const text = response.text();\n\n if (!text) {\n throw new Error('No text content in Gemini response');\n }\n\n return text;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Gemini API call failed: ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Extract insights from agent output\n */\n private extractInsights(output: string): string[] {\n const insights: string[] = [];\n\n const patterns = [\n /[-*]?\\s*(?:insight|finding|observation|recommendation|question):\\s*(.+)/gi,\n /##\\s*(?:insight|finding|observation|recommendation|question):\\s*(.+)/gi,\n /(?:key\\s+)?(?:insight|finding|observation|recommendation|question):\\s*(.+)/gi,\n ];\n\n for (const pattern of patterns) {\n const matches = output.matchAll(pattern);\n for (const match of matches) {\n if (match[1]) {\n insights.push(match[1].trim());\n }\n }\n }\n\n return [...new Set(insights)];\n }\n\n /**\n * Format output for documentation\n */\n private formatOutput(agent: AgentConfig, output: string, mode: string): string {\n const timestamp = new Date().toISOString();\n\n return `---\ntitle: \"${agent.name}\"\ntype: cultivation-analysis\ngenerator: deep-analyzer\nagent: ${agent.type}\nprovider: ${mode}\ncreated: ${timestamp}\n---\n\n# ${agent.name}\n\n> Generated by DeepAnalyzer for documentation cultivation\n\n## Purpose\n\n${agent.task}\n\n## Analysis\n\n${output}\n\n---\n\n*Generated on ${new Date().toLocaleString()}*\n`;\n }\n}\n\n/**\n * Create a deep analyzer instance\n */\nexport function createDeepAnalyzer(options: DeepAnalyzerOptions): DeepAnalyzer {\n return new DeepAnalyzer(options);\n}\n\n/**\n * Run deep analysis on a project\n */\nexport async function analyzeDeep(\n projectRoot: string,\n docsPath?: string\n): Promise<DeepAnalysisResult> {\n const analyzer = new DeepAnalyzer({ projectRoot, docsPath });\n return analyzer.analyze();\n}\n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SAAS,mBAAmB,SAA4C;AAC7E,SAAO,IAAI,aAAa,OAAO;AACjC;AAKA,eAAsB,YACpB,aACA,UAC6B;AAC7B,QAAM,WAAW,IAAI,aAAa,EAAE,aAAa,UAAU;AAC3D,SAAO,SAAS,QAAA;AAClB;"}
1
+ {"version":3,"file":"deep-analyzer.js","sources":["../../src/cultivation/deep-analyzer.ts"],"sourcesContent":["/**\n * DeepAnalyzer - Documentation Cultivation & Knowledge Graph Enhancement\n *\n * Analyzes existing documentation to:\n * - Understand the vision and requirements described\n * - Identify documentation gaps and unclear areas\n * - Guide the documentation process with research questions\n * - Build knowledge graph connections\n *\n * This is NOT for code analysis - use analyze-codebase for that.\n *\n * @module cultivation/deep-analyzer\n */\n\nimport { execFileSync, execSync } from 'child_process';\nimport { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, statSync } from 'fs';\nimport { join, resolve, relative, basename, extname } from 'path';\nimport { createLogger } from '../utils/index.js';\nimport {\n checkCompliance,\n analyzeGaps,\n ComplianceCheckResult,\n GapAnalysisResult,\n ComplianceGap,\n SOPPriority,\n SOPCategory,\n} from '../sops/index.js';\n\nconst logger = createLogger('deep-analyzer');\n\n/**\n * Deep analyzer options\n */\nexport interface DeepAnalyzerOptions {\n /** Project root directory */\n projectRoot: string;\n /** Documentation path (relative to project root) */\n docsPath?: string;\n /** Output directory for analysis results */\n outputDir?: string;\n /** Enable verbose logging */\n verbose?: boolean;\n /** Maximum documents to analyze */\n maxDocuments?: number;\n /** Timeout for each analysis (ms) */\n agentTimeout?: number;\n /** Force use of API key even if CLI is available */\n forceApiKey?: boolean;\n /** Preferred provider when multiple are available */\n preferredProvider?: 'anthropic' | 'gemini';\n}\n\n/**\n * Analysis result from an agent\n */\nexport interface AgentResult {\n name: string;\n type: string;\n success: boolean;\n insights: string[];\n documents: Array<{ path: string; title: string }>;\n duration: number;\n error?: string;\n}\n\n/**\n * Deep analysis result\n */\nexport interface DeepAnalysisResult {\n success: boolean;\n agentsSpawned: number;\n insightsCount: number;\n documentsCreated: number;\n results: AgentResult[];\n duration: number;\n errors: string[];\n mode: 'cli' | 'anthropic' | 'gemini' | 'static';\n /** SOP compliance check result */\n sopCompliance?: ComplianceCheckResult;\n /** SOP gap analysis result */\n sopGaps?: GapAnalysisResult;\n}\n\n/**\n * Agent configuration\n */\ninterface AgentConfig {\n name: string;\n type: string;\n task: string;\n outputFile: string;\n}\n\n/**\n * Execution mode detection result\n */\ninterface ExecutionMode {\n mode: 'cli' | 'anthropic' | 'gemini' | 'unavailable';\n reason: string;\n}\n\n/**\n * Document metadata for analysis\n */\ninterface DocMetadata {\n path: string;\n title: string;\n type: string;\n size: number;\n preview: string;\n}\n\n/**\n * Directory coverage information\n */\ninterface DirectoryCoverage {\n path: string;\n name: string;\n hasMOC: boolean;\n mocStatus: 'complete' | 'stub' | 'empty' | 'missing';\n documentCount: number;\n subdirectories: string[];\n documents: string[];\n needsDocumentation: boolean;\n reason?: string;\n}\n\n/**\n * Previous analysis metadata for iteration tracking\n */\ninterface PreviousAnalysis {\n timestamp: string;\n iteration: number;\n gapsIdentified: number;\n gapsFilled: number;\n questionsRaised: number;\n questionsAnswered: number;\n coverageScore: number;\n}\n\n/**\n * DeepAnalyzer - Documentation cultivation with AI-powered analysis\n *\n * Reads existing markdown documentation and provides:\n * - Vision synthesis from requirements\n * - Gap analysis identifying missing documentation\n * - Research questions for unclear areas\n * - Knowledge graph connection suggestions\n *\n * @example\n * ```typescript\n * const analyzer = new DeepAnalyzer({\n * projectRoot: '/my/project',\n * docsPath: 'docs',\n * });\n *\n * const result = await analyzer.analyze();\n * console.log(`Generated ${result.insightsCount} insights`);\n * ```\n */\nexport class DeepAnalyzer {\n private projectRoot: string;\n private docsPath: string;\n private outputDir: string;\n private verbose: boolean;\n private maxDocuments: number;\n private agentTimeout: number;\n private forceApiKey: boolean;\n private preferredProvider: 'anthropic' | 'gemini';\n\n constructor(options: DeepAnalyzerOptions) {\n this.projectRoot = resolve(options.projectRoot);\n this.docsPath = options.docsPath || 'docs';\n this.outputDir = options.outputDir || join(this.projectRoot, this.docsPath, 'analysis');\n this.verbose = options.verbose || false;\n this.maxDocuments = options.maxDocuments || 50;\n // Default timeout of 2 minutes (120 seconds)\n this.agentTimeout = options.agentTimeout || 120000;\n this.forceApiKey = options.forceApiKey || false;\n this.preferredProvider = options.preferredProvider || 'anthropic';\n }\n\n /**\n * Check if running inside a Claude Code session\n */\n private isInsideClaudeCode(): boolean {\n return process.env.CLAUDECODE === '1' || process.env.CLAUDE_CODE === '1';\n }\n\n /**\n * Check if Anthropic API key is available\n */\n private hasAnthropicApiKey(): boolean {\n return !!process.env.ANTHROPIC_API_KEY;\n }\n\n /**\n * Check if Google AI / Gemini API key is available\n */\n private hasGeminiApiKey(): boolean {\n return !!(\n process.env.GOOGLE_AI_API_KEY ||\n process.env.GOOGLE_GEMINI_API_KEY ||\n process.env.GEMINI_API_KEY ||\n process.env.GOOGLE_API_KEY\n );\n }\n\n /**\n * Get the Gemini API key from available env vars\n */\n private getGeminiApiKey(): string | undefined {\n return (\n process.env.GOOGLE_AI_API_KEY ||\n process.env.GOOGLE_GEMINI_API_KEY ||\n process.env.GEMINI_API_KEY ||\n process.env.GOOGLE_API_KEY\n );\n }\n\n /**\n * Check if Claude CLI is available\n */\n private isCliAvailable(): boolean {\n try {\n execFileSync('claude', ['--version'], {\n stdio: 'pipe',\n timeout: 5000,\n windowsHide: true,\n });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Determine the best execution mode\n */\n private detectExecutionMode(): ExecutionMode {\n const insideClaudeCode = this.isInsideClaudeCode();\n const hasAnthropicKey = this.hasAnthropicApiKey();\n const hasGeminiKey = this.hasGeminiApiKey();\n const cliAvailable = this.isCliAvailable();\n\n // If forced to use API key\n if (this.forceApiKey) {\n if (this.preferredProvider === 'gemini' && hasGeminiKey) {\n return { mode: 'gemini', reason: 'Using Gemini API (forced, preferred)' };\n }\n if (hasAnthropicKey) {\n return { mode: 'anthropic', reason: 'Using Anthropic API (forced)' };\n }\n if (hasGeminiKey) {\n return { mode: 'gemini', reason: 'Using Gemini API (forced, fallback)' };\n }\n return { mode: 'unavailable', reason: 'No API key found. Set ANTHROPIC_API_KEY or GOOGLE_AI_API_KEY.' };\n }\n\n // Prefer API keys for reliability\n if (this.preferredProvider === 'gemini' && hasGeminiKey) {\n return { mode: 'gemini', reason: 'Using Gemini API (preferred)' };\n }\n if (hasAnthropicKey) {\n return { mode: 'anthropic', reason: 'Using Anthropic API' };\n }\n if (hasGeminiKey) {\n return { mode: 'gemini', reason: 'Using Gemini API' };\n }\n\n // No API keys - try CLI as last resort\n if (insideClaudeCode) {\n return {\n mode: 'unavailable',\n reason: 'Cannot run inside Claude Code without an API key. Set ANTHROPIC_API_KEY or GOOGLE_AI_API_KEY.',\n };\n }\n\n if (cliAvailable) {\n return { mode: 'cli', reason: 'Using Claude CLI (no API key found)' };\n }\n\n return {\n mode: 'unavailable',\n reason: 'No execution method available. Set ANTHROPIC_API_KEY or GOOGLE_AI_API_KEY.',\n };\n }\n\n /**\n * Check if analysis is available\n */\n async isAvailable(): Promise<boolean> {\n const mode = this.detectExecutionMode();\n return mode.mode !== 'unavailable';\n }\n\n /**\n * Get availability status with reason\n */\n async getAvailabilityStatus(): Promise<{ available: boolean; reason: string }> {\n const mode = this.detectExecutionMode();\n return {\n available: mode.mode !== 'unavailable',\n reason: mode.reason,\n };\n }\n\n /**\n * Scan documentation directory for markdown files\n */\n private scanDocumentation(): DocMetadata[] {\n const docsDir = join(this.projectRoot, this.docsPath);\n if (!existsSync(docsDir)) {\n return [];\n }\n\n const documents: DocMetadata[] = [];\n const scan = (dir: string) => {\n const entries = readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'analysis') {\n continue;\n }\n\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n scan(fullPath);\n } else if (entry.isFile() && extname(entry.name) === '.md') {\n try {\n const content = readFileSync(fullPath, 'utf-8');\n const stats = statSync(fullPath);\n const relPath = relative(docsDir, fullPath);\n\n // Extract title from first heading or filename\n const titleMatch = content.match(/^#\\s+(.+)$/m);\n const title = titleMatch ? titleMatch[1] : basename(entry.name, '.md');\n\n // Determine document type from path or frontmatter\n let type = 'general';\n if (relPath.includes('concepts/')) type = 'concept';\n else if (relPath.includes('components/')) type = 'component';\n else if (relPath.includes('services/')) type = 'service';\n else if (relPath.includes('features/')) type = 'feature';\n else if (relPath.includes('guides/')) type = 'guide';\n else if (relPath.includes('standards/')) type = 'standard';\n else if (relPath.includes('references/')) type = 'reference';\n else if (relPath.includes('integrations/')) type = 'integration';\n else if (entry.name.includes('requirement')) type = 'requirement';\n else if (entry.name.includes('spec')) type = 'specification';\n\n // Get preview (first 500 chars after title)\n const preview = content.slice(0, 2000).replace(/^#.+\\n/, '').trim().slice(0, 500);\n\n documents.push({\n path: relPath,\n title,\n type,\n size: stats.size,\n preview,\n });\n } catch {\n // Skip files that can't be read\n }\n }\n }\n };\n\n scan(docsDir);\n return documents.slice(0, this.maxDocuments);\n }\n\n /**\n * Read full content of key documents\n */\n private readKeyDocuments(): Map<string, string> {\n const docsDir = join(this.projectRoot, this.docsPath);\n const keyDocs = new Map<string, string>();\n\n // Priority documents to read in full\n const priorityFiles = [\n 'README.md',\n 'MOC.md',\n 'PRIMITIVES.md',\n 'original_specs.md',\n 'business_requirements_document.md',\n 'technical_requirements.md',\n 'test_strategy.md',\n ];\n\n for (const file of priorityFiles) {\n const filePath = join(docsDir, file);\n if (existsSync(filePath)) {\n try {\n const content = readFileSync(filePath, 'utf-8');\n // Limit to 15KB per document to fit in context\n keyDocs.set(file, content.slice(0, 15000));\n } catch {\n // Skip\n }\n }\n }\n\n return keyDocs;\n }\n\n /**\n * Scan directory structure for MOC files and coverage\n */\n private scanDirectoryStructure(): DirectoryCoverage[] {\n const docsDir = join(this.projectRoot, this.docsPath);\n if (!existsSync(docsDir)) {\n return [];\n }\n\n const directories: DirectoryCoverage[] = [];\n const ignoredDirs = new Set(['.', '..', 'analysis', 'node_modules', '.git', '.obsidian']);\n\n const scanDir = (dir: string, depth: number = 0): void => {\n if (depth > 5) return; // Max depth to prevent infinite loops\n\n const relPath = relative(docsDir, dir) || '.';\n const entries = readdirSync(dir, { withFileTypes: true });\n\n const subdirs: string[] = [];\n const docs: string[] = [];\n let mocFile: string | null = null;\n let mocContent = '';\n\n for (const entry of entries) {\n if (ignoredDirs.has(entry.name) || entry.name.startsWith('.')) continue;\n\n if (entry.isDirectory()) {\n subdirs.push(entry.name);\n scanDir(join(dir, entry.name), depth + 1);\n } else if (entry.isFile() && entry.name.endsWith('.md')) {\n docs.push(entry.name);\n if (entry.name === '_MOC.md' || entry.name === 'MOC.md' || entry.name === 'index.md') {\n mocFile = entry.name;\n try {\n mocContent = readFileSync(join(dir, entry.name), 'utf-8');\n } catch {\n mocContent = '';\n }\n }\n }\n }\n\n // Determine MOC status\n let mocStatus: DirectoryCoverage['mocStatus'] = 'missing';\n if (mocFile) {\n if (mocContent.length < 100) {\n mocStatus = 'empty';\n } else if (\n mocContent.toLowerCase().includes('stub') ||\n mocContent.includes('TODO') ||\n mocContent.includes('TBD') ||\n !mocContent.includes('[[')\n ) {\n mocStatus = 'stub';\n } else {\n mocStatus = 'complete';\n }\n }\n\n // Determine if documentation is needed\n let needsDocumentation = false;\n let reason = '';\n\n if (subdirs.length > 0 || docs.length > 1) {\n if (mocStatus === 'missing') {\n needsDocumentation = true;\n reason = 'Directory has content but no MOC file';\n } else if (mocStatus === 'empty' || mocStatus === 'stub') {\n needsDocumentation = true;\n reason = `MOC file is ${mocStatus} - needs content`;\n }\n }\n\n // Only track directories that have content or subdirectories\n if (subdirs.length > 0 || docs.length > 0 || relPath === '.') {\n directories.push({\n path: relPath,\n name: basename(dir),\n hasMOC: mocFile !== null,\n mocStatus,\n documentCount: docs.length,\n subdirectories: subdirs,\n documents: docs,\n needsDocumentation,\n reason,\n });\n }\n };\n\n scanDir(docsDir);\n return directories;\n }\n\n /**\n * Load previous analysis results for iteration tracking\n */\n private loadPreviousAnalysis(): PreviousAnalysis | null {\n const metadataFile = join(this.outputDir, '.analysis-metadata.json');\n\n if (!existsSync(metadataFile)) {\n return null;\n }\n\n try {\n const content = readFileSync(metadataFile, 'utf-8');\n return JSON.parse(content) as PreviousAnalysis;\n } catch {\n return null;\n }\n }\n\n /**\n * Save analysis metadata for iteration tracking\n */\n private saveAnalysisMetadata(result: DeepAnalysisResult, dirCoverage: DirectoryCoverage[]): void {\n const metadataFile = join(this.outputDir, '.analysis-metadata.json');\n const previous = this.loadPreviousAnalysis();\n\n // Count coverage metrics\n const totalDirs = dirCoverage.length;\n const coveredDirs = dirCoverage.filter(d => d.mocStatus === 'complete').length;\n const coverageScore = totalDirs > 0 ? (coveredDirs / totalDirs) * 100 : 0;\n\n // Count gaps and questions from results\n const gapsResult = result.results.find(r => r.type === 'gaps');\n const questionsResult = result.results.find(r => r.type === 'research');\n const coverageResult = result.results.find(r => r.type === 'coverage');\n\n const metadata: PreviousAnalysis = {\n timestamp: new Date().toISOString(),\n iteration: (previous?.iteration || 0) + 1,\n gapsIdentified: (gapsResult?.insights.length || 0) + (coverageResult?.insights.length || 0),\n gapsFilled: 0, // Updated by migrate command\n questionsRaised: questionsResult?.insights.length || 0,\n questionsAnswered: 0, // Updated by migrate command\n coverageScore,\n };\n\n try {\n writeFileSync(metadataFile, JSON.stringify(metadata, null, 2));\n } catch {\n // Non-critical, continue\n }\n }\n\n /**\n * Run deep analysis\n */\n async analyze(): Promise<DeepAnalysisResult> {\n const startTime = Date.now();\n const executionMode = this.detectExecutionMode();\n\n const result: DeepAnalysisResult = {\n success: false,\n agentsSpawned: 0,\n insightsCount: 0,\n documentsCreated: 0,\n results: [],\n duration: 0,\n errors: [],\n mode: executionMode.mode === 'unavailable' ? 'static' : executionMode.mode,\n };\n\n // Check availability\n if (executionMode.mode === 'unavailable') {\n result.errors.push(executionMode.reason);\n result.duration = Date.now() - startTime;\n logger.error('Deep analysis unavailable', new Error(executionMode.reason));\n return result;\n }\n\n logger.info(`Starting documentation cultivation`, { mode: executionMode.mode, reason: executionMode.reason });\n\n // Ensure output directory exists\n if (!existsSync(this.outputDir)) {\n mkdirSync(this.outputDir, { recursive: true });\n }\n\n // Scan existing documentation\n const documents = this.scanDocumentation();\n const keyDocs = this.readKeyDocuments();\n const dirCoverage = this.scanDirectoryStructure();\n const previousAnalysis = this.loadPreviousAnalysis();\n\n if (documents.length === 0) {\n result.errors.push('No markdown documents found in docs directory');\n result.duration = Date.now() - startTime;\n return result;\n }\n\n // Log iteration info\n const iteration = (previousAnalysis?.iteration || 0) + 1;\n logger.info('Found documentation', {\n documents: documents.length,\n keyDocs: keyDocs.size,\n directories: dirCoverage.length,\n needsWork: dirCoverage.filter(d => d.needsDocumentation).length,\n iteration,\n });\n\n // Run SOP compliance check before agents\n const sopCompliance = await this.runSOPComplianceCheck();\n const sopGaps = sopCompliance ? this.runSOPGapAnalysis(sopCompliance) : undefined;\n\n // Define documentation cultivation agents - including Directory Coverage and SOP Compliance\n const agents: AgentConfig[] = [\n {\n name: 'Vision Synthesizer',\n type: 'vision',\n task: 'Synthesize the project vision, goals, and core value proposition from the documentation',\n outputFile: 'vision-synthesis.md',\n },\n {\n name: 'Directory Coverage Analyst',\n type: 'coverage',\n task: 'Analyze directory structure, MOC files, and identify areas needing documentation',\n outputFile: 'directory-coverage.md',\n },\n {\n name: 'Gap Analyst',\n type: 'gaps',\n task: 'Identify documentation gaps, missing sections, and areas that need more detail',\n outputFile: 'documentation-gaps.md',\n },\n {\n name: 'Research Guide',\n type: 'research',\n task: 'Generate research questions and areas that need further investigation or clarification',\n outputFile: 'research-questions.md',\n },\n {\n name: 'Connection Mapper',\n type: 'connections',\n task: 'Identify relationships between concepts and suggest knowledge graph connections',\n outputFile: 'knowledge-connections.md',\n },\n {\n name: 'SOP Compliance Analyst',\n type: 'sop',\n task: 'Analyze AI-SDLC SOP compliance gaps and recommend documentation to address them',\n outputFile: 'sop-compliance-gaps.md',\n },\n ];\n\n logger.info('Executing cultivation agents', {\n agents: agents.length,\n mode: 'sequential',\n iteration,\n sopGapsCount: sopGaps?.totalGaps || 0,\n });\n\n // Execute agents sequentially\n for (const agent of agents) {\n const agentResult = await this.executeAgent(\n agent,\n executionMode.mode as 'cli' | 'anthropic' | 'gemini',\n documents,\n keyDocs,\n dirCoverage,\n previousAnalysis,\n sopGaps\n );\n result.results.push(agentResult);\n }\n\n // Store SOP results\n result.sopCompliance = sopCompliance;\n result.sopGaps = sopGaps;\n\n // Save metadata for iteration tracking\n this.saveAnalysisMetadata(result, dirCoverage);\n\n // Calculate totals\n result.agentsSpawned = result.results.length;\n result.insightsCount = result.results.reduce((sum, r) => sum + r.insights.length, 0);\n result.documentsCreated = result.results.reduce((sum, r) => sum + r.documents.length, 0);\n result.success = result.results.some(r => r.success);\n result.duration = Date.now() - startTime;\n\n // Collect errors\n for (const agentResult of result.results) {\n if (agentResult.error) {\n result.errors.push(`${agentResult.name}: ${agentResult.error}`);\n }\n }\n\n logger.info('Documentation cultivation complete', {\n success: result.success,\n insights: result.insightsCount,\n documents: result.documentsCreated,\n duration: result.duration,\n });\n\n return result;\n }\n\n /**\n * Execute a single agent\n */\n private async executeAgent(\n agent: AgentConfig,\n mode: 'cli' | 'anthropic' | 'gemini',\n documents: DocMetadata[],\n keyDocs: Map<string, string>,\n dirCoverage: DirectoryCoverage[],\n previousAnalysis: PreviousAnalysis | null,\n sopGaps?: GapAnalysisResult\n ): Promise<AgentResult> {\n const startTime = Date.now();\n const outputPath = join(this.outputDir, agent.outputFile);\n\n const result: AgentResult = {\n name: agent.name,\n type: agent.type,\n success: false,\n insights: [],\n documents: [],\n duration: 0,\n };\n\n try {\n logger.info(`Executing agent: ${agent.name}`, { type: agent.type, mode });\n\n const prompt = this.buildPrompt(agent, documents, keyDocs, dirCoverage, previousAnalysis, sopGaps);\n let output: string;\n\n if (mode === 'cli') {\n output = await this.runWithCli(prompt);\n } else if (mode === 'anthropic') {\n output = await this.runWithAnthropic(prompt);\n } else {\n output = await this.runWithGemini(prompt);\n }\n\n // Parse output for insights\n result.insights = this.extractInsights(output);\n\n // Write output to file\n writeFileSync(outputPath, this.formatOutput(agent, output, mode));\n result.documents.push({ path: outputPath, title: agent.name });\n\n result.success = true;\n\n if (this.verbose) {\n logger.debug(`Agent completed: ${agent.name}`, { insights: result.insights.length });\n }\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error);\n logger.error(`Agent failed: ${agent.name}`, error instanceof Error ? error : new Error(String(error)));\n }\n\n result.duration = Date.now() - startTime;\n return result;\n }\n\n /**\n * Build directory coverage summary for prompts\n */\n private buildCoverageSummary(dirCoverage: DirectoryCoverage[]): string {\n const lines: string[] = [];\n\n // Summary stats\n const total = dirCoverage.length;\n const complete = dirCoverage.filter(d => d.mocStatus === 'complete').length;\n const stub = dirCoverage.filter(d => d.mocStatus === 'stub').length;\n const empty = dirCoverage.filter(d => d.mocStatus === 'empty').length;\n const missing = dirCoverage.filter(d => d.mocStatus === 'missing').length;\n\n lines.push(`### Summary`);\n lines.push(`- Total Directories: ${total}`);\n lines.push(`- Complete MOCs: ${complete} (${((complete / total) * 100).toFixed(1)}%)`);\n lines.push(`- Stub MOCs: ${stub}`);\n lines.push(`- Empty MOCs: ${empty}`);\n lines.push(`- Missing MOCs: ${missing}`);\n lines.push(`- Coverage Score: ${((complete / total) * 100).toFixed(1)}%`);\n lines.push('');\n\n // Directories needing work\n const needsWork = dirCoverage.filter(d => d.needsDocumentation);\n if (needsWork.length > 0) {\n lines.push('### Directories Needing Documentation');\n for (const dir of needsWork) {\n lines.push(`- **${dir.path}/** (${dir.mocStatus})`);\n lines.push(` - Documents: ${dir.documents.join(', ') || 'none'}`);\n lines.push(` - Subdirectories: ${dir.subdirectories.join(', ') || 'none'}`);\n lines.push(` - Reason: ${dir.reason}`);\n }\n lines.push('');\n }\n\n // Complete directories\n const completeDirs = dirCoverage.filter(d => d.mocStatus === 'complete');\n if (completeDirs.length > 0) {\n lines.push('### Directories with Complete MOCs');\n for (const dir of completeDirs) {\n lines.push(`- ${dir.path}/ (${dir.documentCount} docs)`);\n }\n }\n\n return lines.join('\\n');\n }\n\n /**\n * Build context-aware prompt for documentation cultivation\n */\n private buildPrompt(\n agent: AgentConfig,\n documents: DocMetadata[],\n keyDocs: Map<string, string>,\n dirCoverage: DirectoryCoverage[],\n previousAnalysis: PreviousAnalysis | null,\n sopGaps?: GapAnalysisResult\n ): string {\n // Build document inventory\n const inventory = documents.map(d => `- ${d.path} (${d.type}): ${d.title}`).join('\\n');\n\n // Build key document content\n const keyContent = Array.from(keyDocs.entries())\n .map(([name, content]) => `### ${name}\\n\\n${content}`)\n .join('\\n\\n---\\n\\n');\n\n // Build directory coverage summary\n const coverageSummary = this.buildCoverageSummary(dirCoverage);\n\n // Build iteration context\n const iterationContext = previousAnalysis\n ? `\\n## Previous Analysis (Iteration ${previousAnalysis.iteration})\n- Timestamp: ${previousAnalysis.timestamp}\n- Gaps Identified: ${previousAnalysis.gapsIdentified}\n- Gaps Filled: ${previousAnalysis.gapsFilled}\n- Questions Raised: ${previousAnalysis.questionsRaised}\n- Questions Answered: ${previousAnalysis.questionsAnswered}\n- Coverage Score: ${previousAnalysis.coverageScore.toFixed(1)}%\n\nFocus on NEW gaps and questions not addressed in previous iterations.\n`\n : '';\n\n // Agent-specific instructions\n let specificInstructions = '';\n switch (agent.type) {\n case 'coverage':\n specificInstructions = `\nFocus on directory structure and MOC (Map of Content) files:\n\n1. **Directory Analysis**: Review each directory and its MOC file status\n2. **Empty/Stub MOCs**: Identify MOC files that are empty or just stubs\n3. **Missing MOCs**: Identify directories that need MOC files\n4. **Documentation Needs**: For each directory, determine what documentation is needed\n5. **Not Needed**: If a directory genuinely doesn't need documentation, explain why\n\nFor each directory needing work:\n- State the directory path\n- Current MOC status (missing/empty/stub/complete)\n- What documentation should be added\n- Priority (high/medium/low)\n- Suggested content or links to include\n\nThe goal is 100% documentation coverage - every directory should either:\n1. Have a complete MOC with links to contents\n2. Have documentation explaining why it doesn't need more docs\n3. Be marked for future documentation\n\n## Directory Coverage Status\n${coverageSummary}`;\n break;\n\n case 'vision':\n specificInstructions = `\nFocus on:\n1. What is the core purpose/goal of this project?\n2. What problem does it solve?\n3. What is the target audience/user?\n4. What are the key success metrics?\n5. What is the overall architecture vision?\n\nProvide a clear, concise synthesis of the project vision with references to specific documentation.`;\n break;\n\n case 'gaps':\n specificInstructions = `\nIdentify:\n1. Missing documentation (what topics are mentioned but not explained?)\n2. Incomplete sections (what areas need more detail?)\n3. Outdated information (anything that seems inconsistent?)\n4. Missing examples or use cases\n5. Unclear terminology or concepts that need definitions\n6. Empty or stub MOC files that need content (see Directory Coverage below)\n\nFor each gap, specify:\n- What is missing\n- Where it should be documented (specific file path)\n- Why it's important\n- Priority (high/medium/low)\n\n## Directory Coverage Status\n${coverageSummary}`;\n break;\n\n case 'research':\n specificInstructions = `\nGenerate research questions in these categories:\n1. Technical questions (how should X be implemented?)\n2. Design decisions (why this approach vs alternatives?)\n3. Integration questions (how does X connect to Y?)\n4. Validation questions (how do we verify X works?)\n5. Scalability questions (will this work at scale?)\n\nFor each question:\n- State the question clearly\n- Explain why answering it is important\n- Suggest where to look for answers`;\n break;\n\n case 'connections':\n specificInstructions = `\nIdentify relationships between documented concepts:\n1. Dependencies (X requires Y)\n2. Extensions (X extends Y)\n3. Alternatives (X is an alternative to Y)\n4. Compositions (X is made up of Y and Z)\n5. References (X references Y for details)\n\nSuggest knowledge graph nodes and edges in this format:\n- [Node A] --relationship--> [Node B]: description\n\nAlso identify concepts that should be linked but aren't currently.`;\n break;\n\n case 'sop':\n specificInstructions = this.buildSOPAgentInstructions(sopGaps);\n break;\n }\n\n return `You are a documentation analyst helping to cultivate a knowledge graph.\n${iterationContext}\n## Your Task\n${agent.task}\n\n## Documentation Inventory\nThe following markdown documents exist in this project:\n${inventory}\n\n## Key Document Contents\n\n${keyContent}\n\n## Instructions\n${specificInstructions}\n\n## Output Format\nProvide your analysis in markdown format with:\n1. Clear section headings\n2. Specific observations (prefix with \"Observation:\")\n3. Specific recommendations (prefix with \"Recommendation:\")\n4. Key findings (prefix with \"Finding:\")\n5. Research questions where applicable (prefix with \"Question:\")\n6. Priority levels (high/medium/low) for actionable items\n\nReference specific documents using [[document-name]] wiki-link format where relevant.\nBe specific and actionable in your analysis.\n${previousAnalysis ? '\\nFocus on NEW items not identified in previous iterations.' : ''}`;\n }\n\n /**\n * Run SOP compliance check against the documentation\n */\n private async runSOPComplianceCheck(): Promise<ComplianceCheckResult | undefined> {\n try {\n logger.info('Running SOP compliance check', { projectRoot: this.projectRoot });\n\n // Run compliance check with project settings\n const result = await checkCompliance({\n projectRoot: this.projectRoot,\n docsPath: this.docsPath,\n deepAnalysis: false,\n assessor: 'deep-analyzer',\n });\n\n logger.info('SOP compliance check complete', {\n score: result.overallScore,\n compliant: result.assessments.filter(a => a.score >= 70).length,\n nonCompliant: result.assessments.filter(a => a.score < 70).length,\n });\n\n return result;\n } catch (error) {\n logger.warn('SOP compliance check failed', { error: error instanceof Error ? error.message : String(error) });\n return undefined;\n }\n }\n\n /**\n * Run SOP gap analysis on compliance results\n */\n private runSOPGapAnalysis(compliance: ComplianceCheckResult): GapAnalysisResult | undefined {\n try {\n const result = analyzeGaps(compliance, {\n complianceThreshold: 70,\n includePartial: true,\n generateRemediation: true,\n });\n\n logger.info('SOP gap analysis complete', {\n totalGaps: result.totalGaps,\n criticalGaps: result.criticalGaps.length,\n compliancePercentage: result.summary.compliancePercentage,\n });\n\n // Write gap analysis summary to output\n this.writeSOPGapsSummary(result);\n\n return result;\n } catch (error) {\n logger.warn('SOP gap analysis failed', { error: error instanceof Error ? error.message : String(error) });\n return undefined;\n }\n }\n\n /**\n * Write SOP gaps summary to analysis output\n */\n private writeSOPGapsSummary(gaps: GapAnalysisResult): void {\n const summaryPath = join(this.outputDir, 'sop-gaps-summary.json');\n\n try {\n const summary = {\n timestamp: new Date().toISOString(),\n totalGaps: gaps.totalGaps,\n criticalGaps: gaps.criticalGaps.length,\n summary: gaps.summary,\n byPriority: {\n critical: gaps.byPriority[SOPPriority.CRITICAL].length,\n high: gaps.byPriority[SOPPriority.HIGH].length,\n medium: gaps.byPriority[SOPPriority.MEDIUM].length,\n low: gaps.byPriority[SOPPriority.LOW].length,\n },\n byCategory: Object.entries(gaps.byCategory).reduce((acc, [key, value]) => {\n acc[key] = value.length;\n return acc;\n }, {} as Record<string, number>),\n gaps: gaps.gaps.map(g => ({\n id: g.id,\n sopId: g.sopId,\n requirementId: g.requirementId,\n description: g.description,\n priority: g.priority,\n effort: g.effort,\n remediation: g.remediation,\n })),\n roadmap: gaps.roadmap ? {\n phases: gaps.roadmap.phases.map(p => ({\n phase: p.phase,\n name: p.name,\n focus: p.focus,\n effort: p.effort,\n gapCount: p.gaps.length,\n })),\n quickWinsCount: gaps.roadmap.quickWins.length,\n } : undefined,\n };\n\n writeFileSync(summaryPath, JSON.stringify(summary, null, 2));\n logger.debug('Wrote SOP gaps summary', { path: summaryPath });\n } catch (error) {\n logger.warn('Failed to write SOP gaps summary', { error: error instanceof Error ? error.message : String(error) });\n }\n }\n\n /**\n * Build SOP agent-specific instructions with gap context\n */\n private buildSOPAgentInstructions(sopGaps?: GapAnalysisResult): string {\n let instructions = `\nAnalyze AI-SDLC SOP (Standard Operating Procedures) compliance gaps and recommend documentation:\n\n1. **Gap Prioritization**: Review the compliance gaps and prioritize by impact\n2. **Documentation Recommendations**: For each gap, suggest what documentation should be created\n3. **Remediation Steps**: Provide actionable steps to address each gap\n4. **Quick Wins**: Identify low-effort, high-impact gaps that can be addressed quickly\n5. **Documentation Templates**: Suggest document templates for common gap types\n\nFor each gap, recommend:\n- Document type (guide, standard, process, reference)\n- Suggested file path (using project conventions)\n- Key sections to include\n- Related documents to link to ([[wiki-links]])\n- Priority level (high/medium/low)\n`;\n\n if (sopGaps && sopGaps.totalGaps > 0) {\n instructions += `\n## Current SOP Compliance Gaps\n\n**Summary:**\n- Total Gaps: ${sopGaps.totalGaps}\n- Critical Gaps: ${sopGaps.criticalGaps.length}\n- Compliance Score: ${sopGaps.summary.compliancePercentage}%\n\n### Gaps by Priority:\n- Critical: ${sopGaps.byPriority[SOPPriority.CRITICAL].length}\n- High: ${sopGaps.byPriority[SOPPriority.HIGH].length}\n- Medium: ${sopGaps.byPriority[SOPPriority.MEDIUM].length}\n- Low: ${sopGaps.byPriority[SOPPriority.LOW].length}\n\n### Detailed Gaps:\n`;\n\n // Add critical and high priority gaps in detail\n const priorityGaps = [\n ...sopGaps.byPriority[SOPPriority.CRITICAL],\n ...sopGaps.byPriority[SOPPriority.HIGH],\n ].slice(0, 15); // Limit to top 15 to fit in context\n\n for (const gap of priorityGaps) {\n instructions += `\n#### ${gap.priority.toUpperCase()}: ${gap.description}\n- SOP: ${gap.sopId}\n- Requirement: ${gap.requirementId}\n- Effort: ${gap.effort}\n- Remediation: ${gap.remediation}\n- Impact: ${gap.impact}\n`;\n }\n\n if (sopGaps.roadmap) {\n instructions += `\n### Remediation Roadmap:\n`;\n for (const phase of sopGaps.roadmap.phases) {\n instructions += `\n**Phase ${phase.phase}: ${phase.name}**\n- Focus: ${phase.focus}\n- Effort: ${phase.effort}\n- Gaps to address: ${phase.gaps.length}\n`;\n }\n\n if (sopGaps.roadmap.quickWins.length > 0) {\n instructions += `\n### Quick Wins (High Impact, Low Effort):\n`;\n for (const win of sopGaps.roadmap.quickWins.slice(0, 5)) {\n instructions += `- ${win.description} (${win.effort} effort)\\n`;\n }\n }\n }\n } else {\n instructions += `\n## No SOP Gaps Data Available\n\nPerform a general AI-SDLC compliance analysis based on the documentation structure.\nReview for common compliance areas:\n- Requirements documentation\n- Architecture documentation\n- Testing documentation\n- Security documentation\n- Deployment documentation\n- Operational procedures\n`;\n }\n\n return instructions;\n }\n\n /**\n * Run analysis using Claude CLI\n */\n private async runWithCli(prompt: string): Promise<string> {\n const sanitizedPrompt = prompt\n .replace(/\"/g, '\\\\\"')\n .replace(/[`$]/g, '');\n\n try {\n const result = execSync(`claude -p \"${sanitizedPrompt}\"`, {\n cwd: this.projectRoot,\n encoding: 'utf8',\n timeout: this.agentTimeout,\n maxBuffer: 10 * 1024 * 1024,\n });\n return result;\n } catch (error) {\n if (error instanceof Error) {\n const execError = error as { stderr?: string; stdout?: string; killed?: boolean };\n if (execError.killed) {\n if (execError.stdout && execError.stdout.length > 100) {\n return execError.stdout;\n }\n throw new Error(`Claude CLI timed out after ${this.agentTimeout / 1000}s`);\n }\n throw new Error(execError.stderr || error.message);\n }\n throw error;\n }\n }\n\n /**\n * Run analysis using Anthropic API directly\n */\n private async runWithAnthropic(prompt: string): Promise<string> {\n const apiKey = process.env.ANTHROPIC_API_KEY;\n if (!apiKey) {\n throw new Error('ANTHROPIC_API_KEY not set');\n }\n\n try {\n const { default: Anthropic } = await import('@anthropic-ai/sdk');\n const client = new Anthropic({ apiKey });\n\n const response = await client.messages.create({\n model: 'claude-sonnet-4-20250514',\n max_tokens: 4096,\n messages: [{ role: 'user', content: prompt }],\n });\n\n const textBlock = response.content.find(block => block.type === 'text');\n if (textBlock && textBlock.type === 'text') {\n return textBlock.text;\n }\n\n throw new Error('No text content in API response');\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Anthropic API call failed: ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Run analysis using Google Gemini API\n */\n private async runWithGemini(prompt: string): Promise<string> {\n const apiKey = this.getGeminiApiKey();\n if (!apiKey) {\n throw new Error('GOOGLE_AI_API_KEY not set');\n }\n\n try {\n const { GoogleGenerativeAI } = await import('@google/generative-ai');\n const genAI = new GoogleGenerativeAI(apiKey);\n const model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' });\n\n const result = await model.generateContent(prompt);\n const response = result.response;\n const text = response.text();\n\n if (!text) {\n throw new Error('No text content in Gemini response');\n }\n\n return text;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Gemini API call failed: ${error.message}`);\n }\n throw error;\n }\n }\n\n /**\n * Extract insights from agent output\n */\n private extractInsights(output: string): string[] {\n const insights: string[] = [];\n\n const patterns = [\n /[-*]?\\s*(?:insight|finding|observation|recommendation|question):\\s*(.+)/gi,\n /##\\s*(?:insight|finding|observation|recommendation|question):\\s*(.+)/gi,\n /(?:key\\s+)?(?:insight|finding|observation|recommendation|question):\\s*(.+)/gi,\n ];\n\n for (const pattern of patterns) {\n const matches = output.matchAll(pattern);\n for (const match of matches) {\n if (match[1]) {\n insights.push(match[1].trim());\n }\n }\n }\n\n return [...new Set(insights)];\n }\n\n /**\n * Format output for documentation\n */\n private formatOutput(agent: AgentConfig, output: string, mode: string): string {\n const timestamp = new Date().toISOString();\n\n return `---\ntitle: \"${agent.name}\"\ntype: cultivation-analysis\ngenerator: deep-analyzer\nagent: ${agent.type}\nprovider: ${mode}\ncreated: ${timestamp}\n---\n\n# ${agent.name}\n\n> Generated by DeepAnalyzer for documentation cultivation\n\n## Purpose\n\n${agent.task}\n\n## Analysis\n\n${output}\n\n---\n\n*Generated on ${new Date().toLocaleString()}*\n`;\n }\n}\n\n/**\n * Create a deep analyzer instance\n */\nexport function createDeepAnalyzer(options: DeepAnalyzerOptions): DeepAnalyzer {\n return new DeepAnalyzer(options);\n}\n\n/**\n * Run deep analysis on a project\n */\nexport async function analyzeDeep(\n projectRoot: string,\n docsPath?: string\n): Promise<DeepAnalysisResult> {\n const analyzer = new DeepAnalyzer({ projectRoot, docsPath });\n return analyzer.analyze();\n}\n"],"names":[],"mappings":";;;;;;;;;AA4BA,MAAM,SAAS,aAAa,eAAe;AAoIpC,MAAM,aAAa;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,SAA8B;AACxC,SAAK,cAAc,QAAQ,QAAQ,WAAW;AAC9C,SAAK,WAAW,QAAQ,YAAY;AACpC,SAAK,YAAY,QAAQ,aAAa,KAAK,KAAK,aAAa,KAAK,UAAU,UAAU;AACtF,SAAK,UAAU,QAAQ,WAAW;AA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AAO,YAAA;AAE7B,WAAO;AAAA,UACD,MAAM,IAAI;AAAA;AAAA;AAAA,SAGX,MAAM,IAAI;AAAA,YACP,IAAI;AAAA,WACL,SAAS;AAAA;AAAA;AAAA,IAGhB,MAAM,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMZ,MAAM,IAAI;AAAA;AAAA;AAAA;AAAA,EAIV,MAAM;AAAA;AAAA;AAAA;AAAA,iBAIQ,oBAAI,QAAO,gBAAgB;AAAA;AAAA,EAEzC;AACF;AAKO,SAAS,mBAAmB,SAA4C;AAC7E,SAAO,IAAI,aAAa,OAAO;AACjC;AAKA,eAAsB,YACpB,aACA,UAC6B;AAC7B,QAAM,WAAW,IAAI,aAAa,EAAE,aAAa,UAAU;AAC3D,SAAO,SAAS,QAAA;AAClB;"}
@@ -9,6 +9,18 @@
9
9
  *
10
10
  * @module cultivation/migration-orchestrator
11
11
  */
12
+ /**
13
+ * SOP Gap from analysis (simplified version for migration)
14
+ */
15
+ interface SOPGapSummary {
16
+ id: string;
17
+ sopId: string;
18
+ requirementId: string;
19
+ description: string;
20
+ priority: string;
21
+ effort: string;
22
+ remediation: string;
23
+ }
12
24
  /**
13
25
  * Parsed gap from analysis
14
26
  */
@@ -50,6 +62,13 @@ interface ParsedAnalysis {
50
62
  gaps: DocumentationGap[];
51
63
  questions: ResearchQuestion[];
52
64
  connections: ConnectionSuggestion[];
65
+ sopGaps: SOPGapSummary[];
66
+ sopSummary?: {
67
+ totalGaps: number;
68
+ criticalGaps: number;
69
+ compliancePercentage: number;
70
+ byPriority: Record<string, number>;
71
+ };
53
72
  }
54
73
  /**
55
74
  * Migration result
@@ -162,6 +181,10 @@ export declare class MigrationOrchestrator {
162
181
  * Build context for integrator agent
163
182
  */
164
183
  private buildIntegratorContext;
184
+ /**
185
+ * Build context for SOP gap filler agent
186
+ */
187
+ private buildSOPGapFillerContext;
165
188
  /**
166
189
  * Execute a single migration agent
167
190
  */
@@ -1 +1 @@
1
- {"version":3,"file":"migration-orchestrator.d.ts","sourceRoot":"","sources":["../../src/cultivation/migration-orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAWH;;GAEG;AACH,UAAU,gBAAgB;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC;IACpC,WAAW,EAAE,MAAM,EAAE,CAAC;CACvB;AAED;;GAEG;AACH,UAAU,gBAAgB;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,kBAAkB,EAAE,MAAM,EAAE,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,UAAU,oBAAoB;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,UAAU,cAAc;IACtB,MAAM,EAAE;QACN,OAAO,EAAE,MAAM,CAAC;QAChB,KAAK,EAAE,MAAM,EAAE,CAAC;QAChB,eAAe,EAAE,MAAM,EAAE,CAAC;KAC3B,CAAC;IACF,IAAI,EAAE,gBAAgB,EAAE,CAAC;IACzB,SAAS,EAAE,gBAAgB,EAAE,CAAC;IAC9B,WAAW,EAAE,oBAAoB,EAAE,CAAC;CACrC;AAaD;;GAEG;AACH,UAAU,eAAe;IACvB,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MA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OAEG;IACH,OAAO,CAAC,qBAAqB;IAgF7B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAwC9B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAuF9B;;OAEG;IACH,OAAO,CAAC,qBAAqB;IA2B7B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAgC9B;;OAEG;YACW,YAAY;IA4B1B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAwCxB;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAWzB;;OAEG;YACW,MAAM;IAoDpB;;OAEG;YACW,oBAAoB;IA+FlC;;OAEG;IACH,OAAO,CAAC,cAAc;IAmBtB;;OAEG;IACH,OAAO,CAAC,YAAY;IAapB;;OAEG;YACW,cAAc;IAM5B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IA+BxB;;OAEG;IACH,OAAO,CAAC,aAAa;IAerB;;OAEG;IACH,OAAO,CAAC,GAAG;CAQZ;AAED,YAAY,EAAE,eAAe,EAAE,mBAAmB,EAAE,cAAc,EAAE,CAAC"}
1
+ {"version":3,"file":"migration-orchestrator.d.ts","sourceRoot":"","sources":["../../src/cultivation/migration-orchestrator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH;;GAEG;AACH,UAAU,aAAa;IACrB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;CACrB;AAMD;;GAEG;AACH,UAAU,gBAAgB;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC;IACpC,WAAW,EAAE,MAAM,EAAE,CAAC;CACvB;AAED;;GA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sBAAsB;IAuF9B;;OAEG;IACH,OAAO,CAAC,qBAAqB;IA2B7B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAgC9B;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAqFhC;;OAEG;YACW,YAAY;IA4B1B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAwCxB;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAWzB;;OAEG;YACW,MAAM;IAoDpB;;OAEG;YACW,oBAAoB;IA+FlC;;OAEG;IACH,OAAO,CAAC,cAAc;IAmBtB;;OAEG;IACH,OAAO,CAAC,YAAY;IAapB;;OAEG;YACW,cAAc;IAM5B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IA+BxB;;OAEG;IACH,OAAO,CAAC,aAAa;IAerB;;OAEG;IACH,OAAO,CAAC,GAAG;CAQZ;AAED,YAAY,EAAE,eAAe,EAAE,mBAAmB,EAAE,cAAc,EAAE,CAAC"}
@@ -126,7 +126,9 @@ class MigrationOrchestrator {
126
126
  vision: { purpose: "", goals: [], recommendations: [] },
127
127
  gaps: [],
128
128
  questions: [],
129
- connections: []
129
+ connections: [],
130
+ sopGaps: [],
131
+ sopSummary: void 0
130
132
  };
131
133
  if (!existsSync(analysisPath)) {
132
134
  throw new Error(`Analysis directory not found: ${analysisPath}`);
@@ -147,6 +149,25 @@ class MigrationOrchestrator {
147
149
  if (existsSync(connectionsFile)) {
148
150
  result.connections = this.parseConnectionsFile(readFileSync(connectionsFile, "utf-8"));
149
151
  }
152
+ const sopGapsFile = join(analysisPath, "sop-gaps-summary.json");
153
+ if (existsSync(sopGapsFile)) {
154
+ try {
155
+ const sopData = JSON.parse(readFileSync(sopGapsFile, "utf-8"));
156
+ result.sopGaps = sopData.gaps || [];
157
+ result.sopSummary = {
158
+ totalGaps: sopData.totalGaps || 0,
159
+ criticalGaps: sopData.criticalGaps || 0,
160
+ compliancePercentage: sopData.summary?.compliancePercentage || 0,
161
+ byPriority: sopData.byPriority || {}
162
+ };
163
+ this.log("info", "Loaded SOP gaps from analysis", {
164
+ totalGaps: result.sopSummary.totalGaps,
165
+ criticalGaps: result.sopSummary.criticalGaps
166
+ });
167
+ } catch (error) {
168
+ this.log("warn", "Failed to parse SOP gaps summary", { error: String(error) });
169
+ }
170
+ }
150
171
  return result;
151
172
  }
152
173
  /**
@@ -368,6 +389,31 @@ class MigrationOrchestrator {
368
389
  context: this.buildDirectoryPopulatorContext(emptyDirs, docsContext, analysis)
369
390
  });
370
391
  }
392
+ if (analysis.sopGaps.length > 0) {
393
+ const criticalAndHighGaps = analysis.sopGaps.filter(
394
+ (g) => g.priority === "critical" || g.priority === "high"
395
+ );
396
+ const mediumAndLowGaps = analysis.sopGaps.filter(
397
+ (g) => g.priority === "medium" || g.priority === "low"
398
+ );
399
+ if (criticalAndHighGaps.length > 0) {
400
+ agents.push({
401
+ name: "SOP Gap Filler - Critical/High",
402
+ type: "gap-filler",
403
+ task: "Create documentation to address critical and high-priority SOP compliance gaps",
404
+ context: this.buildSOPGapFillerContext(criticalAndHighGaps, docsContext, analysis),
405
+ outputFile: "sop-gap-implementations.md"
406
+ });
407
+ }
408
+ if (mediumAndLowGaps.length > 0) {
409
+ agents.push({
410
+ name: "SOP Gap Filler - Medium/Low",
411
+ type: "gap-filler",
412
+ task: "Create documentation to address medium and low-priority SOP compliance gaps",
413
+ context: this.buildSOPGapFillerContext(mediumAndLowGaps, docsContext, analysis)
414
+ });
415
+ }
416
+ }
371
417
  agents.push({
372
418
  name: "Documentation Integrator",
373
419
  type: "integrator",
@@ -731,6 +777,98 @@ ${analysis.vision.purpose}
731
777
  context += "4. Provides a quality assessment\n";
732
778
  return context;
733
779
  }
780
+ /**
781
+ * Build context for SOP gap filler agent
782
+ */
783
+ buildSOPGapFillerContext(sopGaps, docsContext, analysis) {
784
+ let context = "## AI-SDLC SOP Compliance Gaps\n\n";
785
+ if (analysis.sopSummary) {
786
+ context += "### Compliance Summary\n";
787
+ context += `- Total Gaps: ${analysis.sopSummary.totalGaps}
788
+ `;
789
+ context += `- Critical Gaps: ${analysis.sopSummary.criticalGaps}
790
+ `;
791
+ context += `- Compliance: ${analysis.sopSummary.compliancePercentage}%
792
+
793
+ `;
794
+ }
795
+ if (analysis.vision.purpose) {
796
+ context += `### Project Purpose
797
+ ${analysis.vision.purpose}
798
+
799
+ `;
800
+ }
801
+ context += "## Key Technical Documentation\n\n";
802
+ const keyDocPatterns = [
803
+ "test_strategy",
804
+ "technical",
805
+ "architecture",
806
+ "wasm",
807
+ "rust",
808
+ "original_spec",
809
+ "integration",
810
+ "requirements",
811
+ "security"
812
+ ];
813
+ for (const [docPath, docContent] of docsContext) {
814
+ const lowerPath = docPath.toLowerCase();
815
+ if (keyDocPatterns.some((pattern) => lowerPath.includes(pattern))) {
816
+ context += `### ${docPath}
817
+ `;
818
+ context += docContent.slice(0, 3e3) + "\n\n";
819
+ }
820
+ }
821
+ context += "## SOP Compliance Gaps to Address\n\n";
822
+ context += "The following gaps were identified from AI-SDLC SOP compliance analysis.\n";
823
+ context += "Create documentation to address each gap based on the project context.\n\n";
824
+ const gapsBySOP = /* @__PURE__ */ new Map();
825
+ for (const gap of sopGaps) {
826
+ const sopId = gap.sopId || "general";
827
+ if (!gapsBySOP.has(sopId)) {
828
+ gapsBySOP.set(sopId, []);
829
+ }
830
+ gapsBySOP.get(sopId).push(gap);
831
+ }
832
+ for (const [sopId, gaps] of gapsBySOP) {
833
+ context += `### SOP: ${sopId}
834
+
835
+ `;
836
+ for (const gap of gaps) {
837
+ context += `#### ${gap.priority.toUpperCase()}: ${gap.description}
838
+ `;
839
+ context += `- **Requirement:** ${gap.requirementId}
840
+ `;
841
+ context += `- **Effort:** ${gap.effort}
842
+ `;
843
+ context += `- **Remediation:** ${gap.remediation}
844
+
845
+ `;
846
+ }
847
+ }
848
+ context += "\n## Instructions\n";
849
+ context += "CRITICAL: Create documentation to address the SOP compliance gaps above.\n";
850
+ context += "Use the project context and technical documentation to ensure relevance.\n\n";
851
+ context += "OUTPUT FORMAT - Use this EXACT format for EACH document you create:\n\n";
852
+ context += "```document\n";
853
+ context += "---\n";
854
+ context += "path: relative/path/to/file.md\n";
855
+ context += "action: create\n";
856
+ context += "---\n";
857
+ context += "# Document Title\n\n";
858
+ context += "Document content with [[wiki-links]] to other documents.\n";
859
+ context += "```\n\n";
860
+ context += "For each SOP gap:\n";
861
+ context += "1. Create documentation that directly addresses the compliance requirement\n";
862
+ context += "2. Place documents in appropriate directories based on type:\n";
863
+ context += " - standards/ for coding standards, style guides, policies\n";
864
+ context += " - guides/ for tutorials, how-tos, processes\n";
865
+ context += " - references/ for API docs, specifications, schemas\n";
866
+ context += " - docs/ for general documentation\n";
867
+ context += "3. Include project-specific content (Rust, WASM, TypeScript, Knowledge Graph)\n";
868
+ context += "4. Reference existing documentation with [[wiki-links]]\n";
869
+ context += "5. Follow the remediation guidance provided for each gap\n";
870
+ return context;
871
+ }
734
872
  /**
735
873
  * Execute a single migration agent
736
874
  */
@@ -1 +1 @@
1
- {"version":3,"file":"migration-orchestrator.js","sources":["../../src/cultivation/migration-orchestrator.ts"],"sourcesContent":["/**\n * Migration Orchestrator - Implements Analysis Recommendations\n *\n * Uses claude-flow swarms to implement suggestions from cultivation analysis:\n * - Fill documentation gaps identified by Gap Analyst\n * - Answer research questions with specialized agents\n * - Build knowledge graph connections\n * - Create missing MOC files and documentation\n *\n * @module cultivation/migration-orchestrator\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs';\nimport { join, dirname, basename, relative } from 'path';\nimport { GoogleGenerativeAI } from '@google/generative-ai';\nimport matter from 'gray-matter';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parsed gap from analysis\n */\ninterface DocumentationGap {\n section: string;\n description: string;\n recommendation: string;\n priority: 'high' | 'medium' | 'low';\n relatedDocs: string[];\n}\n\n/**\n * Parsed research question from analysis\n */\ninterface ResearchQuestion {\n question: string;\n context: string;\n importance: string;\n suggestedResources: string[];\n category: string;\n}\n\n/**\n * Parsed connection suggestion from analysis\n */\ninterface ConnectionSuggestion {\n source: string;\n target: string;\n relationship: string;\n reason: string;\n}\n\n/**\n * Parsed analysis results\n */\ninterface ParsedAnalysis {\n vision: {\n purpose: string;\n goals: string[];\n recommendations: string[];\n };\n gaps: DocumentationGap[];\n questions: ResearchQuestion[];\n connections: ConnectionSuggestion[];\n}\n\n/**\n * Agent configuration for migration\n */\ninterface MigrationAgent {\n name: string;\n type: 'gap-filler' | 'researcher' | 'moc-builder' | 'connector' | 'integrator';\n task: string;\n context: string;\n outputFile?: string;\n}\n\n/**\n * Migration result\n */\ninterface MigrationResult {\n success: boolean;\n agentsUsed: number;\n documentsCreated: number;\n documentsUpdated: number;\n connectionsAdded: number;\n questionsAnswered: number;\n gapsFilled: number;\n errors: string[];\n warnings: string[];\n duration: number;\n}\n\n/**\n * Orchestrator options\n */\ninterface OrchestratorOptions {\n projectRoot: string;\n docsPath: string;\n analysisDir: string;\n verbose?: boolean;\n dryRun?: boolean;\n useVectorSearch?: boolean;\n maxAgents?: number;\n}\n\n// ============================================================================\n// Migration Orchestrator\n// ============================================================================\n\n/**\n * Orchestrates the migration from analysis to implemented documentation\n */\nexport class MigrationOrchestrator {\n private projectRoot: string;\n private docsPath: string;\n private analysisDir: string;\n private verbose: boolean;\n private dryRun: boolean;\n private useVectorSearch: boolean;\n private maxAgents: number;\n private geminiClient: GoogleGenerativeAI | null = null;\n\n constructor(options: OrchestratorOptions) {\n this.projectRoot = options.projectRoot;\n this.docsPath = options.docsPath;\n this.analysisDir = options.analysisDir;\n this.verbose = options.verbose ?? false;\n this.dryRun = options.dryRun ?? false;\n this.useVectorSearch = options.useVectorSearch ?? false;\n this.maxAgents = options.maxAgents ?? 8;\n\n // Initialize Gemini client if available\n const apiKey = process.env.GOOGLE_GEMINI_API_KEY ||\n process.env.GOOGLE_AI_API_KEY ||\n process.env.GEMINI_API_KEY ||\n process.env.GOOGLE_API_KEY;\n if (apiKey) {\n this.geminiClient = new GoogleGenerativeAI(apiKey);\n }\n }\n\n /**\n * Check availability status\n */\n async getAvailabilityStatus(): Promise<{ available: boolean; reason: string }> {\n if (this.geminiClient) {\n return { available: true, reason: 'Using Gemini API' };\n }\n\n // Check for Anthropic API\n if (process.env.ANTHROPIC_API_KEY) {\n return { available: true, reason: 'Using Anthropic API' };\n }\n\n return {\n available: false,\n reason: 'No API key found. Set GOOGLE_GEMINI_API_KEY or ANTHROPIC_API_KEY'\n };\n }\n\n /**\n * Run the migration process\n */\n async migrate(): Promise<MigrationResult> {\n const startTime = Date.now();\n const result: MigrationResult = {\n success: false,\n agentsUsed: 0,\n documentsCreated: 0,\n documentsUpdated: 0,\n connectionsAdded: 0,\n questionsAnswered: 0,\n gapsFilled: 0,\n errors: [],\n warnings: [],\n duration: 0\n };\n\n try {\n this.log('info', 'Starting migration orchestration', {\n analysisDir: this.analysisDir,\n docsPath: this.docsPath\n });\n\n // Step 1: Parse analysis files\n const analysis = await this.parseAnalysisFiles();\n this.log('info', 'Parsed analysis files', {\n gaps: analysis.gaps.length,\n questions: analysis.questions.length,\n connections: analysis.connections.length\n });\n\n // Step 2: Load existing documentation context\n const docsContext = await this.loadDocsContext();\n this.log('info', 'Loaded documentation context', {\n totalDocs: docsContext.size,\n keyDocs: Array.from(docsContext.keys()).slice(0, 5)\n });\n\n // Step 3: Create migration agents based on analysis\n const agents = this.createMigrationAgents(analysis, docsContext);\n this.log('info', 'Created migration agents', { agents: agents.length });\n\n // Step 4: Execute agents\n for (const agent of agents) {\n try {\n const agentResult = await this.executeAgent(agent, analysis, docsContext);\n result.agentsUsed++;\n\n if (agentResult.documentsCreated) {\n result.documentsCreated += agentResult.documentsCreated;\n }\n if (agentResult.documentsUpdated) {\n result.documentsUpdated += agentResult.documentsUpdated;\n }\n if (agentResult.gapsFilled) {\n result.gapsFilled += agentResult.gapsFilled;\n }\n if (agentResult.questionsAnswered) {\n result.questionsAnswered += agentResult.questionsAnswered;\n }\n if (agentResult.connectionsAdded) {\n result.connectionsAdded += agentResult.connectionsAdded;\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n result.errors.push(`Agent ${agent.name} failed: ${msg}`);\n this.log('error', `Agent ${agent.name} failed`, { error: msg });\n }\n }\n\n // Step 5: Update MOC files with new connections\n if (result.documentsCreated > 0 || result.connectionsAdded > 0) {\n await this.updateMOCFiles(analysis.connections);\n }\n\n result.success = result.errors.length === 0;\n result.duration = Date.now() - startTime;\n\n this.log('info', 'Migration complete', {\n success: result.success,\n documentsCreated: result.documentsCreated,\n gapsFilled: result.gapsFilled,\n duration: result.duration\n });\n\n return result;\n\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n result.errors.push(`Migration failed: ${msg}`);\n result.duration = Date.now() - startTime;\n return result;\n }\n }\n\n /**\n * Parse all analysis files from the analysis directory\n */\n private async parseAnalysisFiles(): Promise<ParsedAnalysis> {\n const analysisPath = join(this.projectRoot, this.docsPath, this.analysisDir);\n const result: ParsedAnalysis = {\n vision: { purpose: '', goals: [], recommendations: [] },\n gaps: [],\n questions: [],\n connections: []\n };\n\n if (!existsSync(analysisPath)) {\n throw new Error(`Analysis directory not found: ${analysisPath}`);\n }\n\n // Parse vision-synthesis.md\n const visionFile = join(analysisPath, 'vision-synthesis.md');\n if (existsSync(visionFile)) {\n result.vision = this.parseVisionFile(readFileSync(visionFile, 'utf-8'));\n }\n\n // Parse documentation-gaps.md\n const gapsFile = join(analysisPath, 'documentation-gaps.md');\n if (existsSync(gapsFile)) {\n result.gaps = this.parseGapsFile(readFileSync(gapsFile, 'utf-8'));\n }\n\n // Parse research-questions.md\n const questionsFile = join(analysisPath, 'research-questions.md');\n if (existsSync(questionsFile)) {\n result.questions = this.parseQuestionsFile(readFileSync(questionsFile, 'utf-8'));\n }\n\n // Parse knowledge-connections.md\n const connectionsFile = join(analysisPath, 'knowledge-connections.md');\n if (existsSync(connectionsFile)) {\n result.connections = this.parseConnectionsFile(readFileSync(connectionsFile, 'utf-8'));\n }\n\n return result;\n }\n\n /**\n * Parse vision synthesis file\n */\n private parseVisionFile(content: string): ParsedAnalysis['vision'] {\n const vision: ParsedAnalysis['vision'] = {\n purpose: '',\n goals: [],\n recommendations: []\n };\n\n // Extract purpose from \"Core Purpose\" or \"Problem Statement\" sections\n const purposeMatch = content.match(/## (?:Core Purpose|Problem Statement)[^#]*?\\n([\\s\\S]*?)(?=\\n##|\\n\\*\\*|$)/i);\n if (purposeMatch) {\n vision.purpose = purposeMatch[1].trim().slice(0, 500);\n }\n\n // Extract goals/metrics\n const goalsMatch = content.match(/## (?:Key Success Metrics|Goals)[^#]*?\\n([\\s\\S]*?)(?=\\n##|$)/i);\n if (goalsMatch) {\n const goalLines = goalsMatch[1].match(/\\*\\s+\\*\\*[^*]+\\*\\*/g) || [];\n vision.goals = goalLines.map(g => g.replace(/\\*+/g, '').trim()).slice(0, 10);\n }\n\n // Extract recommendations\n const recsMatch = content.match(/## (?:Actionable Recommendations|Recommendations)[^#]*?\\n([\\s\\S]*?)(?=\\n##|```|$)/i);\n if (recsMatch) {\n const recLines = recsMatch[1].match(/\\d+\\.\\s+\\*\\*[^*]+\\*\\*[^*\\n]*/g) || [];\n vision.recommendations = recLines.map(r => r.replace(/\\d+\\.\\s*\\*\\*|\\*\\*/g, '').trim()).slice(0, 10);\n }\n\n return vision;\n }\n\n /**\n * Parse documentation gaps file\n */\n private parseGapsFile(content: string): DocumentationGap[] {\n const gaps: DocumentationGap[] = [];\n\n // Find all sections with observations/recommendations\n const sections = content.split(/###\\s+\\d+\\.\\s+/);\n\n for (const section of sections.slice(1)) {\n const titleMatch = section.match(/^([^\\n]+)/);\n const title = titleMatch ? titleMatch[1].trim() : 'Unknown Section';\n\n // Extract observations\n const obsMatches = section.matchAll(/\\*\\*Observation:\\*\\*\\s*([^\\n]+)/g);\n for (const match of obsMatches) {\n const observation = match[1].trim();\n\n // Find related recommendation\n const recMatch = section.match(/\\*\\*Recommendation:\\*\\*\\s*([^\\n]+)/);\n const recommendation = recMatch ? recMatch[1].trim() : '';\n\n // Extract wiki-links as related docs\n const wikiLinks = observation.match(/\\[\\[[^\\]]+\\]\\]/g) || [];\n const relatedDocs = wikiLinks.map(l => l.replace(/\\[\\[|\\]\\]/g, ''));\n\n gaps.push({\n section: title,\n description: observation,\n recommendation,\n priority: this.inferPriority(observation, recommendation),\n relatedDocs\n });\n }\n\n // Extract findings as gaps\n const findingMatches = section.matchAll(/\\*\\*Finding:\\*\\*\\s*([^\\n]+)/g);\n for (const match of findingMatches) {\n const finding = match[1].trim();\n const wikiLinks = finding.match(/\\[\\[[^\\]]+\\]\\]/g) || [];\n\n gaps.push({\n section: title,\n description: finding,\n recommendation: '',\n priority: 'medium',\n relatedDocs: wikiLinks.map(l => l.replace(/\\[\\[|\\]\\]/g, ''))\n });\n }\n }\n\n return gaps;\n }\n\n /**\n * Escape special regex characters in a string\n */\n private escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n\n /**\n * Parse research questions file\n */\n private parseQuestionsFile(content: string): ResearchQuestion[] {\n const questions: ResearchQuestion[] = [];\n\n // Find all Question: entries\n const questionMatches = content.matchAll(/(?:Question:|####\\s+\\d+\\.\\d+\\s+)([^\\n]+)\\n([\\s\\S]*?)(?=\\n(?:Question:|####|\\*\\*Importance|\\*\\*Suggested|###|$))/g);\n\n for (const match of questionMatches) {\n const questionText = match[1].replace(/^Question:\\s*/, '').trim();\n const context = match[2].trim();\n\n // Escape special regex characters in question text before using in RegExp\n const safeQuestionShort = this.escapeRegex(questionText.slice(0, 50));\n const safeQuestionVeryShort = this.escapeRegex(questionText.slice(0, 30));\n\n // Extract importance\n const importanceMatch = content.match(new RegExp(`${safeQuestionShort}[\\\\s\\\\S]*?\\\\*\\\\*Importance:\\\\*\\\\*\\\\s*([^\\\\n]+)`));\n const importance = importanceMatch ? importanceMatch[1].trim() : '';\n\n // Extract suggested resources\n const resourcesMatch = content.match(new RegExp(`${safeQuestionShort}[\\\\s\\\\S]*?\\\\*\\\\*Suggested Resources:\\\\*\\\\*\\\\s*([^\\\\n]+)`));\n const resources = resourcesMatch ? resourcesMatch[1].split(',').map(r => r.trim()) : [];\n\n // Determine category from section header\n const categoryMatch = content.match(new RegExp(`### \\\\d+\\\\. ([^\\\\n]+)[\\\\s\\\\S]*?${safeQuestionVeryShort}`));\n const category = categoryMatch ? categoryMatch[1].trim() : 'General';\n\n questions.push({\n question: questionText,\n context,\n importance,\n suggestedResources: resources,\n category\n });\n }\n\n return questions;\n }\n\n /**\n * Parse knowledge connections file\n */\n private parseConnectionsFile(content: string): ConnectionSuggestion[] {\n const connections: ConnectionSuggestion[] = [];\n\n // Find relationship patterns like: [source] --RELATIONSHIP--> [target]\n const relationshipMatches = content.matchAll(/\\[([^\\]]+)\\]\\s*--([A-Z_-]+)-->\\s*\\[([^\\]]+)\\](?::\\s*([^\\n]+))?/g);\n\n for (const match of relationshipMatches) {\n connections.push({\n source: match[1].trim(),\n target: match[3].trim(),\n relationship: match[2].trim(),\n reason: match[4]?.trim() || ''\n });\n }\n\n // Also find wiki-link based suggestions\n const wikiMatches = content.matchAll(/\\[\\[([^\\]]+)\\]\\]\\s*(?:to|→|->|--)\\s*\\[\\[([^\\]]+)\\]\\]/g);\n for (const match of wikiMatches) {\n connections.push({\n source: match[1].trim(),\n target: match[2].trim(),\n relationship: 'RELATED-TO',\n reason: ''\n });\n }\n\n return connections;\n }\n\n /**\n * Load all documentation as context\n */\n private async loadDocsContext(): Promise<Map<string, string>> {\n const context = new Map<string, string>();\n const docsDir = join(this.projectRoot, this.docsPath);\n\n if (!existsSync(docsDir)) {\n return context;\n }\n\n const loadDir = (dir: string) => {\n const entries = readdirSync(dir);\n for (const entry of entries) {\n const fullPath = join(dir, entry);\n const stat = statSync(fullPath);\n\n if (stat.isDirectory() && !entry.startsWith('.') && entry !== 'analysis') {\n loadDir(fullPath);\n } else if (entry.endsWith('.md')) {\n const relativePath = relative(docsDir, fullPath);\n const content = readFileSync(fullPath, 'utf-8');\n // Limit content size for context\n context.set(relativePath, content.slice(0, 15000));\n }\n }\n };\n\n loadDir(docsDir);\n return context;\n }\n\n /**\n * Create migration agents based on analysis\n */\n private createMigrationAgents(\n analysis: ParsedAnalysis,\n docsContext: Map<string, string>\n ): MigrationAgent[] {\n const agents: MigrationAgent[] = [];\n\n // High priority gaps get dedicated gap-filler agents\n const highPriorityGaps = analysis.gaps.filter(g => g.priority === 'high');\n if (highPriorityGaps.length > 0) {\n agents.push({\n name: 'Gap Filler - High Priority',\n type: 'gap-filler',\n task: 'Fill high-priority documentation gaps with comprehensive, project-specific content',\n context: this.buildGapFillerContext(highPriorityGaps, docsContext, analysis),\n outputFile: 'gap-implementations.md'\n });\n }\n\n // Medium priority gaps\n const mediumPriorityGaps = analysis.gaps.filter(g => g.priority === 'medium');\n if (mediumPriorityGaps.length > 0) {\n agents.push({\n name: 'Gap Filler - Medium Priority',\n type: 'gap-filler',\n task: 'Fill medium-priority documentation gaps with project-specific content',\n context: this.buildGapFillerContext(mediumPriorityGaps, docsContext, analysis)\n });\n }\n\n // Research agents for questions by category\n const questionsByCategory = new Map<string, ResearchQuestion[]>();\n for (const q of analysis.questions) {\n const cat = q.category || 'General';\n if (!questionsByCategory.has(cat)) {\n questionsByCategory.set(cat, []);\n }\n questionsByCategory.get(cat)!.push(q);\n }\n\n for (const [category, questions] of questionsByCategory) {\n if (questions.length > 0) {\n agents.push({\n name: `Researcher - ${category}`,\n type: 'researcher',\n task: `Research and answer questions about ${category}`,\n context: this.buildResearcherContext(questions, docsContext),\n outputFile: `research-${category.toLowerCase().replace(/\\s+/g, '-')}.md`\n });\n }\n }\n\n // MOC builder for empty stub MOCs\n const mocGaps = analysis.gaps.filter(g =>\n g.description.toLowerCase().includes('moc') ||\n g.description.toLowerCase().includes('stub')\n );\n if (mocGaps.length > 0) {\n agents.push({\n name: 'MOC Builder',\n type: 'moc-builder',\n task: 'Populate empty MOC (Map of Content) files with project-specific structure and links',\n context: this.buildMOCBuilderContext(mocGaps, docsContext, analysis)\n });\n }\n\n // Connection builder\n if (analysis.connections.length > 0) {\n agents.push({\n name: 'Connection Builder',\n type: 'connector',\n task: 'Build knowledge graph connections by adding wiki-links to documents',\n context: this.buildConnectorContext(analysis.connections, docsContext)\n });\n }\n\n // Directory populator for empty directories\n const emptyDirs = this.findEmptyDirectories(docsContext);\n if (emptyDirs.length > 0) {\n agents.push({\n name: 'Directory Populator',\n type: 'gap-filler',\n task: 'Create documentation files for empty directories based on project context',\n context: this.buildDirectoryPopulatorContext(emptyDirs, docsContext, analysis)\n });\n }\n\n // Integrator agent to ensure consistency\n agents.push({\n name: 'Documentation Integrator',\n type: 'integrator',\n task: 'Ensure all new documentation is consistent and properly integrated',\n context: this.buildIntegratorContext(analysis, docsContext),\n outputFile: 'integration-summary.md'\n });\n\n return agents.slice(0, this.maxAgents);\n }\n\n /**\n * Find directories with no or minimal documentation\n */\n private findEmptyDirectories(docsContext: Map<string, string>): string[] {\n const directories = new Map<string, number>();\n const docsDir = join(this.projectRoot, this.docsPath);\n\n // Count docs per directory from docsContext\n for (const path of docsContext.keys()) {\n const dir = dirname(path);\n if (dir !== '.') {\n directories.set(dir, (directories.get(dir) || 0) + 1);\n }\n }\n\n // Also scan filesystem for truly empty directories\n const scanDir = (dir: string, relativePath: string = '') => {\n try {\n const entries = readdirSync(dir);\n for (const entry of entries) {\n const fullPath = join(dir, entry);\n const relPath = relativePath ? `${relativePath}/${entry}` : entry;\n\n if (statSync(fullPath).isDirectory() &&\n !entry.startsWith('.') &&\n entry !== 'analysis' &&\n entry !== '_templates' &&\n entry !== '_attachments' &&\n entry !== '_archive') {\n // Check if this directory has any .md files\n const mdFiles = readdirSync(fullPath).filter(f => f.endsWith('.md'));\n if (!directories.has(relPath)) {\n directories.set(relPath, mdFiles.length);\n }\n // Recurse into subdirectories\n scanDir(fullPath, relPath);\n }\n }\n } catch {\n // Ignore errors from inaccessible directories\n }\n };\n\n scanDir(docsDir);\n\n // Find directories with 0-1 docs\n const emptyDirs: string[] = [];\n for (const [dir, count] of directories) {\n if (count <= 1 &&\n !dir.includes('analysis') &&\n !dir.includes('_templates') &&\n !dir.includes('.obsidian') &&\n !dir.includes('_attachments') &&\n !dir.includes('_archive')) {\n emptyDirs.push(dir);\n }\n }\n\n return emptyDirs;\n }\n\n /**\n * Build context for directory populator agent\n */\n private buildDirectoryPopulatorContext(\n emptyDirs: string[],\n docsContext: Map<string, string>,\n analysis: ParsedAnalysis\n ): string {\n let context = '## Project Context\\n\\n';\n\n // Include the project vision\n if (analysis.vision.purpose) {\n context += `### Project Purpose\\n${analysis.vision.purpose}\\n\\n`;\n }\n\n // Include key technical documentation\n context += '## Key Technical Documentation\\n\\n';\n const keyDocPatterns = ['test_strategy', 'technical', 'wasm', 'rust', 'original_spec', 'integration'];\n for (const [docPath, docContent] of docsContext) {\n const lowerPath = docPath.toLowerCase();\n if (keyDocPatterns.some(pattern => lowerPath.includes(pattern))) {\n context += `### ${docPath}\\n`;\n context += docContent.slice(0, 3000) + '\\n\\n';\n }\n }\n\n context += '## Empty Directories Needing Documentation\\n\\n';\n for (const dir of emptyDirs) {\n context += `- ${dir}/\\n`;\n }\n\n context += '\\n## Instructions\\n';\n context += 'CRITICAL: Create actual document files for these empty directories.\\n';\n context += 'Use the project context above to create RELEVANT, PROJECT-SPECIFIC content.\\n\\n';\n context += 'For EACH empty directory, create at least one document using this EXACT format:\\n\\n';\n context += '```document\\n';\n context += '---\\n';\n context += 'path: directory-name/filename.md\\n';\n context += 'action: create\\n';\n context += '---\\n';\n context += '# Document Title\\n\\n';\n context += 'Content with [[wiki-links]] to other docs.\\n';\n context += '```\\n\\n';\n context += 'Guidelines:\\n';\n context += '1. Create documents relevant to the directory purpose (e.g., standards/testing needs testing standards)\\n';\n context += '2. Reference actual project technologies: Rust, WASM, Node.js, TypeScript, Knowledge Graph\\n';\n context += '3. Link to existing documents like [[test_strategy]], [[PRIMITIVES]], [[rust_wasm_knowledge_graph_integration_research]]\\n';\n context += '4. Include project-specific examples and best practices\\n';\n context += '5. Do NOT create generic placeholder content\\n';\n\n return context;\n }\n\n /**\n * Build context for gap filler agent\n */\n private buildGapFillerContext(\n gaps: DocumentationGap[],\n docsContext: Map<string, string>,\n analysis: ParsedAnalysis\n ): string {\n let context = '## Project Context\\n\\n';\n\n // Include the project vision/purpose so gaps are filled with relevant content\n if (analysis.vision.purpose) {\n context += `### Project Purpose\\n${analysis.vision.purpose}\\n\\n`;\n }\n if (analysis.vision.goals.length > 0) {\n context += `### Key Goals\\n`;\n for (const goal of analysis.vision.goals.slice(0, 5)) {\n context += `- ${goal}\\n`;\n }\n context += '\\n';\n }\n\n // Include key technical documentation for context\n context += '## Key Technical Documentation\\n\\n';\n const keyDocPatterns = [\n 'test_strategy', 'technical', 'architecture', 'wasm', 'rust',\n 'original_spec', 'integration', 'primitives', 'requirements'\n ];\n\n for (const [docPath, docContent] of docsContext) {\n const lowerPath = docPath.toLowerCase();\n if (keyDocPatterns.some(pattern => lowerPath.includes(pattern))) {\n context += `### ${docPath}\\n`;\n context += docContent.slice(0, 4000) + '\\n\\n';\n }\n }\n\n context += '## Documentation Gaps to Fill\\n\\n';\n\n for (const gap of gaps) {\n context += `### ${gap.section}\\n`;\n context += `**Issue:** ${gap.description}\\n`;\n if (gap.recommendation) {\n context += `**Recommendation:** ${gap.recommendation}\\n`;\n }\n context += `**Priority:** ${gap.priority}\\n`;\n\n // Add related doc content\n for (const relatedDoc of gap.relatedDocs.slice(0, 2)) {\n const docKey = Array.from(docsContext.keys()).find(k =>\n k.toLowerCase().includes(relatedDoc.toLowerCase().replace(/\\s+/g, '-'))\n );\n if (docKey) {\n context += `\\n**Related: ${relatedDoc}**\\n`;\n context += docsContext.get(docKey)?.slice(0, 2000) + '\\n';\n }\n }\n context += '\\n---\\n\\n';\n }\n\n context += '\\n## Instructions\\n';\n context += 'CRITICAL: Create actual document FILES using the exact format below.\\n';\n context += 'Use the project context and technical documentation above.\\n';\n context += 'Do NOT generate generic placeholder content. Use ACTUAL project details.\\n\\n';\n context += 'OUTPUT FORMAT - Use this EXACT format for EACH document you create:\\n\\n';\n context += '```document\\n';\n context += '---\\n';\n context += 'path: relative/path/to/file.md\\n';\n context += 'action: create\\n';\n context += '---\\n';\n context += '# Document Title\\n\\n';\n context += 'Document content with [[wiki-links]] to other documents.\\n';\n context += '```\\n\\n';\n context += 'For each gap, create documentation that:\\n';\n context += '1. Addresses the specific issue using REAL project details (Rust, WASM, Knowledge Graph, etc.)\\n';\n context += '2. References specific technologies mentioned in the technical docs\\n';\n context += '3. Links to existing docs: [[test_strategy]], [[PRIMITIVES]], [[rust_wasm_knowledge_graph_integration_research]]\\n';\n context += '4. Contains concrete, project-specific information - NOT generic placeholders\\n';\n context += '5. Uses proper frontmatter with title, type, and tags\\n';\n\n return context;\n }\n\n /**\n * Build context for researcher agent\n */\n private buildResearcherContext(questions: ResearchQuestion[], docsContext: Map<string, string>): string {\n let context = '## Research Questions to Answer\\n\\n';\n\n for (const q of questions) {\n context += `### Question\\n${q.question}\\n\\n`;\n if (q.importance) {\n context += `**Importance:** ${q.importance}\\n`;\n }\n if (q.context) {\n context += `**Context:** ${q.context}\\n`;\n }\n if (q.suggestedResources.length > 0) {\n context += `**Resources:** ${q.suggestedResources.join(', ')}\\n`;\n }\n context += '\\n---\\n\\n';\n }\n\n // Add relevant documentation context\n context += '\\n## Available Documentation Context\\n\\n';\n const relevantDocs = this.findRelevantDocs(\n questions.map(q => q.question).join(' '),\n docsContext,\n 5\n );\n for (const [path, content] of relevantDocs) {\n context += `### ${path}\\n`;\n context += content.slice(0, 3000) + '\\n\\n';\n }\n\n context += '\\n## Instructions\\n';\n context += 'For each research question:\\n';\n context += '1. Analyze the available documentation\\n';\n context += '2. Synthesize a well-researched answer\\n';\n context += '3. Cite sources using [[wiki-links]]\\n';\n context += '4. Identify any remaining unknowns\\n';\n context += '5. Suggest best practices based on the knowledge graph\\n';\n\n return context;\n }\n\n /**\n * Build context for MOC builder agent\n */\n private buildMOCBuilderContext(\n gaps: DocumentationGap[],\n docsContext: Map<string, string>,\n analysis: ParsedAnalysis\n ): string {\n let context = '## Project Context\\n\\n';\n\n // Include the project vision so MOCs reflect actual project content\n if (analysis.vision.purpose) {\n context += `### Project Purpose\\n${analysis.vision.purpose}\\n\\n`;\n }\n if (analysis.vision.goals.length > 0) {\n context += `### Key Goals\\n`;\n for (const goal of analysis.vision.goals.slice(0, 5)) {\n context += `- ${goal}\\n`;\n }\n context += '\\n';\n }\n\n context += '## MOC Files to Populate\\n\\n';\n\n // Find all MOC files\n const mocFiles = Array.from(docsContext.keys()).filter(k =>\n k.includes('_MOC.md') || k.includes('MOC.md')\n );\n\n context += '### Current MOC Files\\n';\n for (const mocFile of mocFiles) {\n const content = docsContext.get(mocFile) || '';\n const isEmpty = content.length < 200 || content.includes('stub');\n context += `- ${mocFile} ${isEmpty ? '(EMPTY/STUB)' : '(has content)'}\\n`;\n }\n\n context += '\\n### Gap Analysis Related to MOCs\\n';\n for (const gap of gaps) {\n context += `- ${gap.section}: ${gap.description}\\n`;\n if (gap.recommendation) {\n context += ` Recommendation: ${gap.recommendation}\\n`;\n }\n }\n\n // Add directory structure with document names\n context += '\\n### Documentation Structure\\n';\n const directories = new Set<string>();\n for (const path of docsContext.keys()) {\n const dir = dirname(path);\n if (dir !== '.') {\n directories.add(dir);\n }\n }\n for (const dir of directories) {\n const docsInDir = Array.from(docsContext.keys()).filter(k => dirname(k) === dir);\n context += `- ${dir}/ (${docsInDir.length} docs)\\n`;\n for (const doc of docsInDir.slice(0, 10)) {\n context += ` - ${basename(doc)}\\n`;\n }\n }\n\n // Include key technical docs for context\n context += '\\n### Key Technical Documentation (for reference)\\n';\n const keyDocs = Array.from(docsContext.entries())\n .filter(([path]) => {\n const lower = path.toLowerCase();\n return lower.includes('test_strategy') || lower.includes('wasm') ||\n lower.includes('architecture') || lower.includes('original_spec');\n })\n .slice(0, 3);\n\n for (const [path, content] of keyDocs) {\n context += `\\n#### ${path}\\n`;\n context += content.slice(0, 2000) + '\\n';\n }\n\n context += '\\n## Instructions\\n';\n context += 'CRITICAL: Create MOCs that reflect the ACTUAL project content, not generic placeholders.\\n';\n context += 'Use the project context and technical documentation above.\\n\\n';\n context += 'For each empty/stub MOC file:\\n';\n context += '1. Create a proper introduction describing what the section covers IN THIS PROJECT\\n';\n context += '2. List all documents in that directory with [[wiki-links]]\\n';\n context += '3. Organize by subcategory if applicable\\n';\n context += '4. Add brief, PROJECT-SPECIFIC descriptions for each linked document\\n';\n context += '5. Include navigation links to parent/sibling MOCs\\n';\n context += '6. Reference actual technologies and concepts from the project (e.g., Rust WASM, knowledge graph)\\n';\n\n return context;\n }\n\n /**\n * Build context for connector agent\n */\n private buildConnectorContext(connections: ConnectionSuggestion[], docsContext: Map<string, string>): string {\n let context = '## Suggested Knowledge Graph Connections\\n\\n';\n\n for (const conn of connections) {\n context += `- [${conn.source}] --${conn.relationship}--> [${conn.target}]`;\n if (conn.reason) {\n context += `: ${conn.reason}`;\n }\n context += '\\n';\n }\n\n context += '\\n## Existing Documents\\n';\n for (const [path] of Array.from(docsContext.entries()).slice(0, 30)) {\n context += `- [[${path.replace('.md', '')}]]\\n`;\n }\n\n context += '\\n## Instructions\\n';\n context += 'For each suggested connection:\\n';\n context += '1. Find the source document\\n';\n context += '2. Add appropriate wiki-link [[target]] to the source\\n';\n context += '3. Consider adding reciprocal links where appropriate\\n';\n context += '4. Use \"See also\" or \"Related\" sections for connections\\n';\n context += '5. Ensure the link context is meaningful\\n';\n\n return context;\n }\n\n /**\n * Build context for integrator agent\n */\n private buildIntegratorContext(analysis: ParsedAnalysis, docsContext: Map<string, string>): string {\n let context = '## Integration Context\\n\\n';\n\n context += '### Project Vision\\n';\n context += analysis.vision.purpose + '\\n\\n';\n\n context += '### Goals\\n';\n for (const goal of analysis.vision.goals) {\n context += `- ${goal}\\n`;\n }\n\n context += '\\n### Key Recommendations\\n';\n for (const rec of analysis.vision.recommendations) {\n context += `- ${rec}\\n`;\n }\n\n context += '\\n### Statistics\\n';\n context += `- Total documents: ${docsContext.size}\\n`;\n context += `- Gaps identified: ${analysis.gaps.length}\\n`;\n context += `- Questions to answer: ${analysis.questions.length}\\n`;\n context += `- Connections to build: ${analysis.connections.length}\\n`;\n\n context += '\\n## Instructions\\n';\n context += 'Create an integration summary that:\\n';\n context += '1. Lists all changes made during migration\\n';\n context += '2. Highlights any remaining gaps\\n';\n context += '3. Suggests next steps for documentation improvement\\n';\n context += '4. Provides a quality assessment\\n';\n\n return context;\n }\n\n /**\n * Execute a single migration agent\n */\n private async executeAgent(\n agent: MigrationAgent,\n analysis: ParsedAnalysis,\n docsContext: Map<string, string>\n ): Promise<{\n documentsCreated?: number;\n documentsUpdated?: number;\n gapsFilled?: number;\n questionsAnswered?: number;\n connectionsAdded?: number;\n }> {\n this.log('info', `Executing agent: ${agent.name}`, { type: agent.type });\n\n const prompt = this.buildAgentPrompt(agent);\n const response = await this.callAI(prompt, agent.type);\n\n if (!response) {\n throw new Error('No response from AI');\n }\n\n // Parse response and create/update documents\n const result = await this.processAgentResponse(agent, response, docsContext);\n\n this.log('info', `Agent ${agent.name} completed`, result);\n\n return result;\n }\n\n /**\n * Build prompt for agent\n */\n private buildAgentPrompt(agent: MigrationAgent): string {\n return `# ${agent.name}\n\n## Task\n${agent.task}\n\n${agent.context}\n\n## Output Format\nProvide your response in markdown format with clear sections.\nFor each document to create or update, use this format:\n\n\\`\\`\\`document\n---\npath: relative/path/to/file.md\naction: create|update\n---\n# Document Title\n\nDocument content here with [[wiki-links]] to other documents.\n\\`\\`\\`\n\nFor research answers, use:\n\\`\\`\\`answer\n## Question\nThe original question\n\n## Answer\nYour researched answer with [[citations]]\n\n## Best Practices\n- Recommendation 1\n- Recommendation 2\n\n## Remaining Unknowns\n- Any unresolved items\n\\`\\`\\`\n`;\n }\n\n /**\n * Select the best model based on task complexity\n * - Research and gap-filling tasks use the most capable model\n * - Simpler tasks use faster models\n */\n private selectGeminiModel(agentType: MigrationAgent['type']): string {\n // Use the most capable model for complex reasoning tasks\n const complexTasks = ['gap-filler', 'researcher'];\n if (complexTasks.includes(agentType)) {\n // gemini-2.5-pro for complex planning/research tasks\n return 'gemini-2.5-pro';\n }\n // Use fast model for simpler tasks (gemini-2.5-flash is better than 2.0-flash)\n return 'gemini-2.5-flash';\n }\n\n /**\n * Call AI (Gemini or fallback)\n */\n private async callAI(prompt: string, agentType: MigrationAgent['type']): Promise<string | null> {\n if (this.geminiClient) {\n const modelName = this.selectGeminiModel(agentType);\n try {\n this.log('info', `Using model: ${modelName}`, { agentType });\n const model = this.geminiClient.getGenerativeModel({ model: modelName });\n const result = await model.generateContent(prompt);\n return result.response.text();\n } catch (error) {\n // Fallback to gemini-2.5-flash if the pro model fails\n if (modelName !== 'gemini-2.5-flash') {\n this.log('warn', `${modelName} failed, falling back to gemini-2.5-flash`, { error: String(error) });\n try {\n const fallbackModel = this.geminiClient.getGenerativeModel({ model: 'gemini-2.5-flash' });\n const result = await fallbackModel.generateContent(prompt);\n return result.response.text();\n } catch (fallbackError) {\n this.log('error', 'Gemini fallback also failed', { error: String(fallbackError) });\n }\n } else {\n this.log('error', 'Gemini API call failed', { error: String(error) });\n }\n return null;\n }\n }\n\n // Fallback to Anthropic if available\n if (process.env.ANTHROPIC_API_KEY) {\n try {\n const { default: Anthropic } = await import('@anthropic-ai/sdk');\n const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n // Use opus for complex tasks, sonnet for simpler ones\n const complexTasks = ['gap-filler', 'researcher'];\n const model = complexTasks.includes(agentType)\n ? 'claude-sonnet-4-20250514' // Best available\n : 'claude-sonnet-4-20250514';\n const message = await client.messages.create({\n model,\n max_tokens: 8000,\n messages: [{ role: 'user', content: prompt }]\n });\n const textBlock = message.content.find(b => b.type === 'text');\n return textBlock ? textBlock.text : null;\n } catch (error) {\n this.log('error', 'Anthropic API call failed', { error: String(error) });\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Process agent response and create/update documents\n */\n private async processAgentResponse(\n agent: MigrationAgent,\n response: string,\n docsContext: Map<string, string>\n ): Promise<{\n documentsCreated?: number;\n documentsUpdated?: number;\n gapsFilled?: number;\n questionsAnswered?: number;\n connectionsAdded?: number;\n }> {\n const result = {\n documentsCreated: 0,\n documentsUpdated: 0,\n gapsFilled: 0,\n questionsAnswered: 0,\n connectionsAdded: 0\n };\n\n // Extract document blocks\n const documentMatches = response.matchAll(/```document\\n---\\npath:\\s*([^\\n]+)\\naction:\\s*(\\w+)\\n---\\n([\\s\\S]*?)```/g);\n\n for (const match of documentMatches) {\n const path = match[1].trim();\n const action = match[2].trim();\n const content = match[3].trim();\n\n if (this.dryRun) {\n this.log('info', `[DRY RUN] Would ${action}: ${path}`);\n continue;\n }\n\n const fullPath = join(this.projectRoot, this.docsPath, path);\n\n // Ensure directory exists\n const dir = dirname(fullPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n // Write document\n const finalContent = this.addFrontmatter(content, path, agent.type);\n writeFileSync(fullPath, finalContent, 'utf-8');\n\n if (action === 'create') {\n result.documentsCreated++;\n if (agent.type === 'gap-filler') {\n result.gapsFilled++;\n }\n } else {\n result.documentsUpdated++;\n }\n\n // Count connections added\n const wikiLinks = content.match(/\\[\\[[^\\]]+\\]\\]/g) || [];\n result.connectionsAdded += wikiLinks.length;\n }\n\n // Extract answer blocks\n const answerMatches = response.matchAll(/```answer\\n([\\s\\S]*?)```/g);\n for (const match of answerMatches) {\n result.questionsAnswered++;\n\n // Save answer to research output file\n if (agent.outputFile && !this.dryRun) {\n const outputPath = join(this.projectRoot, this.docsPath, 'analysis', agent.outputFile);\n const existing = existsSync(outputPath) ? readFileSync(outputPath, 'utf-8') : '';\n const newContent = existing + '\\n\\n---\\n\\n' + match[1].trim();\n writeFileSync(outputPath, newContent, 'utf-8');\n }\n }\n\n // If agent has output file and no document blocks, save raw response\n if (agent.outputFile && result.documentsCreated === 0 && !this.dryRun) {\n const outputPath = join(this.projectRoot, this.docsPath, 'analysis', agent.outputFile);\n const frontmatter = `---\ntitle: \"${agent.name}\"\ntype: migration-output\ngenerator: migration-orchestrator\nagent: ${agent.type}\ncreated: ${new Date().toISOString()}\n---\n\n# ${agent.name}\n\n> Generated by MigrationOrchestrator\n\n`;\n writeFileSync(outputPath, frontmatter + response, 'utf-8');\n result.documentsCreated++;\n }\n\n return result;\n }\n\n /**\n * Add frontmatter to document if not present\n */\n private addFrontmatter(content: string, path: string, agentType: string): string {\n if (content.startsWith('---')) {\n return content;\n }\n\n const title = basename(path, '.md').replace(/-/g, ' ').replace(/_/g, ' ');\n const type = this.inferDocType(path);\n\n return `---\ntitle: \"${title}\"\ntype: ${type}\ngenerator: migration-orchestrator\nagent: ${agentType}\ncreated: ${new Date().toISOString()}\n---\n\n${content}`;\n }\n\n /**\n * Infer document type from path\n */\n private inferDocType(path: string): string {\n if (path.includes('concepts')) return 'concept';\n if (path.includes('components')) return 'component';\n if (path.includes('services')) return 'service';\n if (path.includes('features')) return 'feature';\n if (path.includes('guides')) return 'guide';\n if (path.includes('references')) return 'reference';\n if (path.includes('standards')) return 'standard';\n if (path.includes('integrations')) return 'integration';\n if (path.includes('MOC')) return 'moc';\n return 'document';\n }\n\n /**\n * Update MOC files with new connections\n */\n private async updateMOCFiles(connections: ConnectionSuggestion[]): Promise<void> {\n // This would update MOC files with new links\n // For now, we'll let the MOC builder agent handle this\n this.log('info', 'MOC files updated with new connections', { count: connections.length });\n }\n\n /**\n * Find relevant docs based on query\n */\n private findRelevantDocs(\n query: string,\n docsContext: Map<string, string>,\n limit: number\n ): Map<string, string> {\n const relevant = new Map<string, string>();\n const queryWords = query.toLowerCase().split(/\\s+/).filter(w => w.length > 3);\n\n // Simple keyword matching (would use vector search if available)\n const scored = Array.from(docsContext.entries()).map(([path, content]) => {\n let score = 0;\n const lowerContent = content.toLowerCase();\n for (const word of queryWords) {\n if (lowerContent.includes(word)) {\n score++;\n }\n }\n return { path, content, score };\n });\n\n scored.sort((a, b) => b.score - a.score);\n\n for (const item of scored.slice(0, limit)) {\n if (item.score > 0) {\n relevant.set(item.path, item.content);\n }\n }\n\n return relevant;\n }\n\n /**\n * Infer priority from description\n */\n private inferPriority(description: string, recommendation: string): 'high' | 'medium' | 'low' {\n const text = (description + ' ' + recommendation).toLowerCase();\n\n if (text.includes('critical') || text.includes('missing') || text.includes('empty') ||\n text.includes('stub') || text.includes('required')) {\n return 'high';\n }\n\n if (text.includes('should') || text.includes('recommend') || text.includes('consider')) {\n return 'medium';\n }\n\n return 'low';\n }\n\n /**\n * Log message\n */\n private log(level: 'info' | 'warn' | 'error', message: string, data?: Record<string, unknown>): void {\n if (!this.verbose && level === 'info') return;\n\n const timestamp = new Date().toISOString().split('T')[1].split('.')[0];\n const prefix = level === 'error' ? '❌' : level === 'warn' ? '⚠️' : '📋';\n\n console.log(`[${timestamp}] ${prefix} [migration] ${message}`, data ? JSON.stringify(data) : '');\n }\n}\n\nexport type { MigrationResult, OrchestratorOptions, ParsedAnalysis };\n"],"names":[],"mappings":";;;AAkHO,MAAM,sBAAsB;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAA0C;AAAA,EAElD,YAAY,SAA8B;AACxC,SAAK,cAAc,QAAQ;AAC3B,SAAK,WAAW,QAAQ;AACxB,SAAK,cAAc,QAAQ;AAC3B,SAAK,UAAU,QAAQ,WAAW;AAClC,SAAK,SAAS,QAAQ,UAAU;AAChC,SAAK,kBAAkB,QAAQ,mBAAmB;AAClD,SAAK,YAAY,QAAQ,aAAa;AAGtC,UAAM,SAAS,QAAQ,IAAI,yBACZ,QAAQ,IAAI,qBACZ,QAAQ,IAAI,kBACZ,QAAQ,IAAI;AAC3B,QAAI,QAAQ;AACV,WAAK,eAAe,IAAI,mBAAmB,MAAM;AAAA,IACnD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,wBAAyE;AAC7E,QAAI,KAAK,cAAc;AACrB,aAAO,EAAE,WAAW,MAAM,QAAQ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,SAAS,OAAO;AAEnE,YAAQ,IAAI,IAAI,SAAS,KAAK,MAAM,gBAAgB,OAAO,IAAI,OAAO,KAAK,UAAU,IAAI,IAAI,EAAE;AAAA,EACjG;AACF;"}
1
+ {"version":3,"file":"migration-orchestrator.js","sources":["../../src/cultivation/migration-orchestrator.ts"],"sourcesContent":["/**\n * Migration Orchestrator - Implements Analysis Recommendations\n *\n * Uses claude-flow swarms to implement suggestions from cultivation analysis:\n * - Fill documentation gaps identified by Gap Analyst\n * - Answer research questions with specialized agents\n * - Build knowledge graph connections\n * - Create missing MOC files and documentation\n *\n * @module cultivation/migration-orchestrator\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs';\nimport { join, dirname, basename, relative } from 'path';\nimport { GoogleGenerativeAI } from '@google/generative-ai';\nimport matter from 'gray-matter';\n\n/**\n * SOP Gap from analysis (simplified version for migration)\n */\ninterface SOPGapSummary {\n id: string;\n sopId: string;\n requirementId: string;\n description: string;\n priority: string;\n effort: string;\n remediation: string;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parsed gap from analysis\n */\ninterface DocumentationGap {\n section: string;\n description: string;\n recommendation: string;\n priority: 'high' | 'medium' | 'low';\n relatedDocs: string[];\n}\n\n/**\n * Parsed research question from analysis\n */\ninterface ResearchQuestion {\n question: string;\n context: string;\n importance: string;\n suggestedResources: string[];\n category: string;\n}\n\n/**\n * Parsed connection suggestion from analysis\n */\ninterface ConnectionSuggestion {\n source: string;\n target: string;\n relationship: string;\n reason: string;\n}\n\n/**\n * Parsed analysis results\n */\ninterface ParsedAnalysis {\n vision: {\n purpose: string;\n goals: string[];\n recommendations: string[];\n };\n gaps: DocumentationGap[];\n questions: ResearchQuestion[];\n connections: ConnectionSuggestion[];\n sopGaps: SOPGapSummary[];\n sopSummary?: {\n totalGaps: number;\n criticalGaps: number;\n compliancePercentage: number;\n byPriority: Record<string, number>;\n };\n}\n\n/**\n * Agent configuration for migration\n */\ninterface MigrationAgent {\n name: string;\n type: 'gap-filler' | 'researcher' | 'moc-builder' | 'connector' | 'integrator';\n task: string;\n context: string;\n outputFile?: string;\n}\n\n/**\n * Migration result\n */\ninterface MigrationResult {\n success: boolean;\n agentsUsed: number;\n documentsCreated: number;\n documentsUpdated: number;\n connectionsAdded: number;\n questionsAnswered: number;\n gapsFilled: number;\n errors: string[];\n warnings: string[];\n duration: number;\n}\n\n/**\n * Orchestrator options\n */\ninterface OrchestratorOptions {\n projectRoot: string;\n docsPath: string;\n analysisDir: string;\n verbose?: boolean;\n dryRun?: boolean;\n useVectorSearch?: boolean;\n maxAgents?: number;\n}\n\n// ============================================================================\n// Migration Orchestrator\n// ============================================================================\n\n/**\n * Orchestrates the migration from analysis to implemented documentation\n */\nexport class MigrationOrchestrator {\n private projectRoot: string;\n private docsPath: string;\n private analysisDir: string;\n private verbose: boolean;\n private dryRun: boolean;\n private useVectorSearch: boolean;\n private maxAgents: number;\n private geminiClient: GoogleGenerativeAI | null = null;\n\n constructor(options: OrchestratorOptions) {\n this.projectRoot = options.projectRoot;\n this.docsPath = options.docsPath;\n this.analysisDir = options.analysisDir;\n this.verbose = options.verbose ?? false;\n this.dryRun = options.dryRun ?? false;\n this.useVectorSearch = options.useVectorSearch ?? false;\n this.maxAgents = options.maxAgents ?? 8;\n\n // Initialize Gemini client if available\n const apiKey = process.env.GOOGLE_GEMINI_API_KEY ||\n process.env.GOOGLE_AI_API_KEY ||\n process.env.GEMINI_API_KEY ||\n process.env.GOOGLE_API_KEY;\n if (apiKey) {\n this.geminiClient = new GoogleGenerativeAI(apiKey);\n }\n }\n\n /**\n * Check availability status\n */\n async getAvailabilityStatus(): Promise<{ available: boolean; reason: string }> {\n if (this.geminiClient) {\n return { available: true, reason: 'Using Gemini API' };\n }\n\n // Check for Anthropic API\n if (process.env.ANTHROPIC_API_KEY) {\n return { available: true, reason: 'Using Anthropic API' };\n }\n\n return {\n available: false,\n reason: 'No API key found. Set GOOGLE_GEMINI_API_KEY or ANTHROPIC_API_KEY'\n };\n }\n\n /**\n * Run the migration process\n */\n async migrate(): Promise<MigrationResult> {\n const startTime = Date.now();\n const result: MigrationResult = {\n success: false,\n agentsUsed: 0,\n documentsCreated: 0,\n documentsUpdated: 0,\n connectionsAdded: 0,\n questionsAnswered: 0,\n gapsFilled: 0,\n errors: [],\n warnings: [],\n duration: 0\n };\n\n try {\n this.log('info', 'Starting migration orchestration', {\n analysisDir: this.analysisDir,\n docsPath: this.docsPath\n });\n\n // Step 1: Parse analysis files\n const analysis = await this.parseAnalysisFiles();\n this.log('info', 'Parsed analysis files', {\n gaps: analysis.gaps.length,\n questions: analysis.questions.length,\n connections: analysis.connections.length\n });\n\n // Step 2: Load existing documentation context\n const docsContext = await this.loadDocsContext();\n this.log('info', 'Loaded documentation context', {\n totalDocs: docsContext.size,\n keyDocs: Array.from(docsContext.keys()).slice(0, 5)\n });\n\n // Step 3: Create migration agents based on analysis\n const agents = this.createMigrationAgents(analysis, docsContext);\n this.log('info', 'Created migration agents', { agents: agents.length });\n\n // Step 4: Execute agents\n for (const agent of agents) {\n try {\n const agentResult = await this.executeAgent(agent, analysis, docsContext);\n result.agentsUsed++;\n\n if (agentResult.documentsCreated) {\n result.documentsCreated += agentResult.documentsCreated;\n }\n if (agentResult.documentsUpdated) {\n result.documentsUpdated += agentResult.documentsUpdated;\n }\n if (agentResult.gapsFilled) {\n result.gapsFilled += agentResult.gapsFilled;\n }\n if (agentResult.questionsAnswered) {\n result.questionsAnswered += agentResult.questionsAnswered;\n }\n if (agentResult.connectionsAdded) {\n result.connectionsAdded += agentResult.connectionsAdded;\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n result.errors.push(`Agent ${agent.name} failed: ${msg}`);\n this.log('error', `Agent ${agent.name} failed`, { error: msg });\n }\n }\n\n // Step 5: Update MOC files with new connections\n if (result.documentsCreated > 0 || result.connectionsAdded > 0) {\n await this.updateMOCFiles(analysis.connections);\n }\n\n result.success = result.errors.length === 0;\n result.duration = Date.now() - startTime;\n\n this.log('info', 'Migration complete', {\n success: result.success,\n documentsCreated: result.documentsCreated,\n gapsFilled: result.gapsFilled,\n duration: result.duration\n });\n\n return result;\n\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n result.errors.push(`Migration failed: ${msg}`);\n result.duration = Date.now() - startTime;\n return result;\n }\n }\n\n /**\n * Parse all analysis files from the analysis directory\n */\n private async parseAnalysisFiles(): Promise<ParsedAnalysis> {\n const analysisPath = join(this.projectRoot, this.docsPath, this.analysisDir);\n const result: ParsedAnalysis = {\n vision: { purpose: '', goals: [], recommendations: [] },\n gaps: [],\n questions: [],\n connections: [],\n sopGaps: [],\n sopSummary: undefined\n };\n\n if (!existsSync(analysisPath)) {\n throw new Error(`Analysis directory not found: ${analysisPath}`);\n }\n\n // Parse vision-synthesis.md\n const visionFile = join(analysisPath, 'vision-synthesis.md');\n if (existsSync(visionFile)) {\n result.vision = this.parseVisionFile(readFileSync(visionFile, 'utf-8'));\n }\n\n // Parse documentation-gaps.md\n const gapsFile = join(analysisPath, 'documentation-gaps.md');\n if (existsSync(gapsFile)) {\n result.gaps = this.parseGapsFile(readFileSync(gapsFile, 'utf-8'));\n }\n\n // Parse research-questions.md\n const questionsFile = join(analysisPath, 'research-questions.md');\n if (existsSync(questionsFile)) {\n result.questions = this.parseQuestionsFile(readFileSync(questionsFile, 'utf-8'));\n }\n\n // Parse knowledge-connections.md\n const connectionsFile = join(analysisPath, 'knowledge-connections.md');\n if (existsSync(connectionsFile)) {\n result.connections = this.parseConnectionsFile(readFileSync(connectionsFile, 'utf-8'));\n }\n\n // Parse SOP gaps summary (generated by deep-analyzer)\n const sopGapsFile = join(analysisPath, 'sop-gaps-summary.json');\n if (existsSync(sopGapsFile)) {\n try {\n const sopData = JSON.parse(readFileSync(sopGapsFile, 'utf-8'));\n result.sopGaps = sopData.gaps || [];\n result.sopSummary = {\n totalGaps: sopData.totalGaps || 0,\n criticalGaps: sopData.criticalGaps || 0,\n compliancePercentage: sopData.summary?.compliancePercentage || 0,\n byPriority: sopData.byPriority || {}\n };\n this.log('info', 'Loaded SOP gaps from analysis', {\n totalGaps: result.sopSummary.totalGaps,\n criticalGaps: result.sopSummary.criticalGaps\n });\n } catch (error) {\n this.log('warn', 'Failed to parse SOP gaps summary', { error: String(error) });\n }\n }\n\n return result;\n }\n\n /**\n * Parse vision synthesis file\n */\n private parseVisionFile(content: string): ParsedAnalysis['vision'] {\n const vision: ParsedAnalysis['vision'] = {\n purpose: '',\n goals: [],\n recommendations: []\n };\n\n // Extract purpose from \"Core Purpose\" or \"Problem Statement\" sections\n const purposeMatch = content.match(/## (?:Core Purpose|Problem Statement)[^#]*?\\n([\\s\\S]*?)(?=\\n##|\\n\\*\\*|$)/i);\n if (purposeMatch) {\n vision.purpose = purposeMatch[1].trim().slice(0, 500);\n }\n\n // Extract goals/metrics\n const goalsMatch = content.match(/## (?:Key Success Metrics|Goals)[^#]*?\\n([\\s\\S]*?)(?=\\n##|$)/i);\n if (goalsMatch) {\n const goalLines = goalsMatch[1].match(/\\*\\s+\\*\\*[^*]+\\*\\*/g) || [];\n vision.goals = goalLines.map(g => g.replace(/\\*+/g, '').trim()).slice(0, 10);\n }\n\n // Extract recommendations\n const recsMatch = content.match(/## (?:Actionable Recommendations|Recommendations)[^#]*?\\n([\\s\\S]*?)(?=\\n##|```|$)/i);\n if (recsMatch) {\n const recLines = recsMatch[1].match(/\\d+\\.\\s+\\*\\*[^*]+\\*\\*[^*\\n]*/g) || [];\n vision.recommendations = recLines.map(r => r.replace(/\\d+\\.\\s*\\*\\*|\\*\\*/g, '').trim()).slice(0, 10);\n }\n\n return vision;\n }\n\n /**\n * Parse documentation gaps file\n */\n private parseGapsFile(content: string): DocumentationGap[] {\n const gaps: DocumentationGap[] = [];\n\n // Find all sections with observations/recommendations\n const sections = content.split(/###\\s+\\d+\\.\\s+/);\n\n for (const section of sections.slice(1)) {\n const titleMatch = section.match(/^([^\\n]+)/);\n const title = titleMatch ? titleMatch[1].trim() : 'Unknown Section';\n\n // Extract observations\n const obsMatches = section.matchAll(/\\*\\*Observation:\\*\\*\\s*([^\\n]+)/g);\n for (const match of obsMatches) {\n const observation = match[1].trim();\n\n // Find related recommendation\n const recMatch = section.match(/\\*\\*Recommendation:\\*\\*\\s*([^\\n]+)/);\n const recommendation = recMatch ? recMatch[1].trim() : '';\n\n // Extract wiki-links as related docs\n const wikiLinks = observation.match(/\\[\\[[^\\]]+\\]\\]/g) || [];\n const relatedDocs = wikiLinks.map(l => l.replace(/\\[\\[|\\]\\]/g, ''));\n\n gaps.push({\n section: title,\n description: observation,\n recommendation,\n priority: this.inferPriority(observation, recommendation),\n relatedDocs\n });\n }\n\n // Extract findings as gaps\n const findingMatches = section.matchAll(/\\*\\*Finding:\\*\\*\\s*([^\\n]+)/g);\n for (const match of findingMatches) {\n const finding = match[1].trim();\n const wikiLinks = finding.match(/\\[\\[[^\\]]+\\]\\]/g) || [];\n\n gaps.push({\n section: title,\n description: finding,\n recommendation: '',\n priority: 'medium',\n relatedDocs: wikiLinks.map(l => l.replace(/\\[\\[|\\]\\]/g, ''))\n });\n }\n }\n\n return gaps;\n }\n\n /**\n * Escape special regex characters in a string\n */\n private escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n\n /**\n * Parse research questions file\n */\n private parseQuestionsFile(content: string): ResearchQuestion[] {\n const questions: ResearchQuestion[] = [];\n\n // Find all Question: entries\n const questionMatches = content.matchAll(/(?:Question:|####\\s+\\d+\\.\\d+\\s+)([^\\n]+)\\n([\\s\\S]*?)(?=\\n(?:Question:|####|\\*\\*Importance|\\*\\*Suggested|###|$))/g);\n\n for (const match of questionMatches) {\n const questionText = match[1].replace(/^Question:\\s*/, '').trim();\n const context = match[2].trim();\n\n // Escape special regex characters in question text before using in RegExp\n const safeQuestionShort = this.escapeRegex(questionText.slice(0, 50));\n const safeQuestionVeryShort = this.escapeRegex(questionText.slice(0, 30));\n\n // Extract importance\n const importanceMatch = content.match(new RegExp(`${safeQuestionShort}[\\\\s\\\\S]*?\\\\*\\\\*Importance:\\\\*\\\\*\\\\s*([^\\\\n]+)`));\n const importance = importanceMatch ? importanceMatch[1].trim() : '';\n\n // Extract suggested resources\n const resourcesMatch = content.match(new RegExp(`${safeQuestionShort}[\\\\s\\\\S]*?\\\\*\\\\*Suggested Resources:\\\\*\\\\*\\\\s*([^\\\\n]+)`));\n const resources = resourcesMatch ? resourcesMatch[1].split(',').map(r => r.trim()) : [];\n\n // Determine category from section header\n const categoryMatch = content.match(new RegExp(`### \\\\d+\\\\. ([^\\\\n]+)[\\\\s\\\\S]*?${safeQuestionVeryShort}`));\n const category = categoryMatch ? categoryMatch[1].trim() : 'General';\n\n questions.push({\n question: questionText,\n context,\n importance,\n suggestedResources: resources,\n category\n });\n }\n\n return questions;\n }\n\n /**\n * Parse knowledge connections file\n */\n private parseConnectionsFile(content: string): ConnectionSuggestion[] {\n const connections: ConnectionSuggestion[] = [];\n\n // Find relationship patterns like: [source] --RELATIONSHIP--> [target]\n const relationshipMatches = content.matchAll(/\\[([^\\]]+)\\]\\s*--([A-Z_-]+)-->\\s*\\[([^\\]]+)\\](?::\\s*([^\\n]+))?/g);\n\n for (const match of relationshipMatches) {\n connections.push({\n source: match[1].trim(),\n target: match[3].trim(),\n relationship: match[2].trim(),\n reason: match[4]?.trim() || ''\n });\n }\n\n // Also find wiki-link based suggestions\n const wikiMatches = content.matchAll(/\\[\\[([^\\]]+)\\]\\]\\s*(?:to|→|->|--)\\s*\\[\\[([^\\]]+)\\]\\]/g);\n for (const match of wikiMatches) {\n connections.push({\n source: match[1].trim(),\n target: match[2].trim(),\n relationship: 'RELATED-TO',\n reason: ''\n });\n }\n\n return connections;\n }\n\n /**\n * Load all documentation as context\n */\n private async loadDocsContext(): Promise<Map<string, string>> {\n const context = new Map<string, string>();\n const docsDir = join(this.projectRoot, this.docsPath);\n\n if (!existsSync(docsDir)) {\n return context;\n }\n\n const loadDir = (dir: string) => {\n const entries = readdirSync(dir);\n for (const entry of entries) {\n const fullPath = join(dir, entry);\n const stat = statSync(fullPath);\n\n if (stat.isDirectory() && !entry.startsWith('.') && entry !== 'analysis') {\n loadDir(fullPath);\n } else if (entry.endsWith('.md')) {\n const relativePath = relative(docsDir, fullPath);\n const content = readFileSync(fullPath, 'utf-8');\n // Limit content size for context\n context.set(relativePath, content.slice(0, 15000));\n }\n }\n };\n\n loadDir(docsDir);\n return context;\n }\n\n /**\n * Create migration agents based on analysis\n */\n private createMigrationAgents(\n analysis: ParsedAnalysis,\n docsContext: Map<string, string>\n ): MigrationAgent[] {\n const agents: MigrationAgent[] = [];\n\n // High priority gaps get dedicated gap-filler agents\n const highPriorityGaps = analysis.gaps.filter(g => g.priority === 'high');\n if (highPriorityGaps.length > 0) {\n agents.push({\n name: 'Gap Filler - High Priority',\n type: 'gap-filler',\n task: 'Fill high-priority documentation gaps with comprehensive, project-specific content',\n context: this.buildGapFillerContext(highPriorityGaps, docsContext, analysis),\n outputFile: 'gap-implementations.md'\n });\n }\n\n // Medium priority gaps\n const mediumPriorityGaps = analysis.gaps.filter(g => g.priority === 'medium');\n if (mediumPriorityGaps.length > 0) {\n agents.push({\n name: 'Gap Filler - Medium Priority',\n type: 'gap-filler',\n task: 'Fill medium-priority documentation gaps with project-specific content',\n context: this.buildGapFillerContext(mediumPriorityGaps, docsContext, analysis)\n });\n }\n\n // Research agents for questions by category\n const questionsByCategory = new Map<string, ResearchQuestion[]>();\n for (const q of analysis.questions) {\n const cat = q.category || 'General';\n if (!questionsByCategory.has(cat)) {\n questionsByCategory.set(cat, []);\n }\n questionsByCategory.get(cat)!.push(q);\n }\n\n for (const [category, questions] of questionsByCategory) {\n if (questions.length > 0) {\n agents.push({\n name: `Researcher - ${category}`,\n type: 'researcher',\n task: `Research and answer questions about ${category}`,\n context: this.buildResearcherContext(questions, docsContext),\n outputFile: `research-${category.toLowerCase().replace(/\\s+/g, '-')}.md`\n });\n }\n }\n\n // MOC builder for empty stub MOCs\n const mocGaps = analysis.gaps.filter(g =>\n g.description.toLowerCase().includes('moc') ||\n g.description.toLowerCase().includes('stub')\n );\n if (mocGaps.length > 0) {\n agents.push({\n name: 'MOC Builder',\n type: 'moc-builder',\n task: 'Populate empty MOC (Map of Content) files with project-specific structure and links',\n context: this.buildMOCBuilderContext(mocGaps, docsContext, analysis)\n });\n }\n\n // Connection builder\n if (analysis.connections.length > 0) {\n agents.push({\n name: 'Connection Builder',\n type: 'connector',\n task: 'Build knowledge graph connections by adding wiki-links to documents',\n context: this.buildConnectorContext(analysis.connections, docsContext)\n });\n }\n\n // Directory populator for empty directories\n const emptyDirs = this.findEmptyDirectories(docsContext);\n if (emptyDirs.length > 0) {\n agents.push({\n name: 'Directory Populator',\n type: 'gap-filler',\n task: 'Create documentation files for empty directories based on project context',\n context: this.buildDirectoryPopulatorContext(emptyDirs, docsContext, analysis)\n });\n }\n\n // SOP Gap Filler - creates documentation to address SOP compliance gaps\n if (analysis.sopGaps.length > 0) {\n // Group by priority for better handling\n const criticalAndHighGaps = analysis.sopGaps.filter(\n g => g.priority === 'critical' || g.priority === 'high'\n );\n const mediumAndLowGaps = analysis.sopGaps.filter(\n g => g.priority === 'medium' || g.priority === 'low'\n );\n\n if (criticalAndHighGaps.length > 0) {\n agents.push({\n name: 'SOP Gap Filler - Critical/High',\n type: 'gap-filler',\n task: 'Create documentation to address critical and high-priority SOP compliance gaps',\n context: this.buildSOPGapFillerContext(criticalAndHighGaps, docsContext, analysis),\n outputFile: 'sop-gap-implementations.md'\n });\n }\n\n if (mediumAndLowGaps.length > 0) {\n agents.push({\n name: 'SOP Gap Filler - Medium/Low',\n type: 'gap-filler',\n task: 'Create documentation to address medium and low-priority SOP compliance gaps',\n context: this.buildSOPGapFillerContext(mediumAndLowGaps, docsContext, analysis)\n });\n }\n }\n\n // Integrator agent to ensure consistency\n agents.push({\n name: 'Documentation Integrator',\n type: 'integrator',\n task: 'Ensure all new documentation is consistent and properly integrated',\n context: this.buildIntegratorContext(analysis, docsContext),\n outputFile: 'integration-summary.md'\n });\n\n return agents.slice(0, this.maxAgents);\n }\n\n /**\n * Find directories with no or minimal documentation\n */\n private findEmptyDirectories(docsContext: Map<string, string>): string[] {\n const directories = new Map<string, number>();\n const docsDir = join(this.projectRoot, this.docsPath);\n\n // Count docs per directory from docsContext\n for (const path of docsContext.keys()) {\n const dir = dirname(path);\n if (dir !== '.') {\n directories.set(dir, (directories.get(dir) || 0) + 1);\n }\n }\n\n // Also scan filesystem for truly empty directories\n const scanDir = (dir: string, relativePath: string = '') => {\n try {\n const entries = readdirSync(dir);\n for (const entry of entries) {\n const fullPath = join(dir, entry);\n const relPath = relativePath ? `${relativePath}/${entry}` : entry;\n\n if (statSync(fullPath).isDirectory() &&\n !entry.startsWith('.') &&\n entry !== 'analysis' &&\n entry !== '_templates' &&\n entry !== '_attachments' &&\n entry !== '_archive') {\n // Check if this directory has any .md files\n const mdFiles = readdirSync(fullPath).filter(f => f.endsWith('.md'));\n if (!directories.has(relPath)) {\n directories.set(relPath, mdFiles.length);\n }\n // Recurse into subdirectories\n scanDir(fullPath, relPath);\n }\n }\n } catch {\n // Ignore errors from inaccessible directories\n }\n };\n\n scanDir(docsDir);\n\n // Find directories with 0-1 docs\n const emptyDirs: string[] = [];\n for (const [dir, count] of directories) {\n if (count <= 1 &&\n !dir.includes('analysis') &&\n !dir.includes('_templates') &&\n !dir.includes('.obsidian') &&\n !dir.includes('_attachments') &&\n !dir.includes('_archive')) {\n emptyDirs.push(dir);\n }\n }\n\n return emptyDirs;\n }\n\n /**\n * Build context for directory populator agent\n */\n private buildDirectoryPopulatorContext(\n emptyDirs: string[],\n docsContext: Map<string, string>,\n analysis: ParsedAnalysis\n ): string {\n let context = '## Project Context\\n\\n';\n\n // Include the project vision\n if (analysis.vision.purpose) {\n context += `### Project Purpose\\n${analysis.vision.purpose}\\n\\n`;\n }\n\n // Include key technical documentation\n context += '## Key Technical Documentation\\n\\n';\n const keyDocPatterns = ['test_strategy', 'technical', 'wasm', 'rust', 'original_spec', 'integration'];\n for (const [docPath, docContent] of docsContext) {\n const lowerPath = docPath.toLowerCase();\n if (keyDocPatterns.some(pattern => lowerPath.includes(pattern))) {\n context += `### ${docPath}\\n`;\n context += docContent.slice(0, 3000) + '\\n\\n';\n }\n }\n\n context += '## Empty Directories Needing Documentation\\n\\n';\n for (const dir of emptyDirs) {\n context += `- ${dir}/\\n`;\n }\n\n context += '\\n## Instructions\\n';\n context += 'CRITICAL: Create actual document files for these empty directories.\\n';\n context += 'Use the project context above to create RELEVANT, PROJECT-SPECIFIC content.\\n\\n';\n context += 'For EACH empty directory, create at least one document using this EXACT format:\\n\\n';\n context += '```document\\n';\n context += '---\\n';\n context += 'path: directory-name/filename.md\\n';\n context += 'action: create\\n';\n context += '---\\n';\n context += '# Document Title\\n\\n';\n context += 'Content with [[wiki-links]] to other docs.\\n';\n context += '```\\n\\n';\n context += 'Guidelines:\\n';\n context += '1. Create documents relevant to the directory purpose (e.g., standards/testing needs testing standards)\\n';\n context += '2. Reference actual project technologies: Rust, WASM, Node.js, TypeScript, Knowledge Graph\\n';\n context += '3. Link to existing documents like [[test_strategy]], [[PRIMITIVES]], [[rust_wasm_knowledge_graph_integration_research]]\\n';\n context += '4. Include project-specific examples and best practices\\n';\n context += '5. Do NOT create generic placeholder content\\n';\n\n return context;\n }\n\n /**\n * Build context for gap filler agent\n */\n private buildGapFillerContext(\n gaps: DocumentationGap[],\n docsContext: Map<string, string>,\n analysis: ParsedAnalysis\n ): string {\n let context = '## Project Context\\n\\n';\n\n // Include the project vision/purpose so gaps are filled with relevant content\n if (analysis.vision.purpose) {\n context += `### Project Purpose\\n${analysis.vision.purpose}\\n\\n`;\n }\n if (analysis.vision.goals.length > 0) {\n context += `### Key Goals\\n`;\n for (const goal of analysis.vision.goals.slice(0, 5)) {\n context += `- ${goal}\\n`;\n }\n context += '\\n';\n }\n\n // Include key technical documentation for context\n context += '## Key Technical Documentation\\n\\n';\n const keyDocPatterns = [\n 'test_strategy', 'technical', 'architecture', 'wasm', 'rust',\n 'original_spec', 'integration', 'primitives', 'requirements'\n ];\n\n for (const [docPath, docContent] of docsContext) {\n const lowerPath = docPath.toLowerCase();\n if (keyDocPatterns.some(pattern => lowerPath.includes(pattern))) {\n context += `### ${docPath}\\n`;\n context += docContent.slice(0, 4000) + '\\n\\n';\n }\n }\n\n context += '## Documentation Gaps to Fill\\n\\n';\n\n for (const gap of gaps) {\n context += `### ${gap.section}\\n`;\n context += `**Issue:** ${gap.description}\\n`;\n if (gap.recommendation) {\n context += `**Recommendation:** ${gap.recommendation}\\n`;\n }\n context += `**Priority:** ${gap.priority}\\n`;\n\n // Add related doc content\n for (const relatedDoc of gap.relatedDocs.slice(0, 2)) {\n const docKey = Array.from(docsContext.keys()).find(k =>\n k.toLowerCase().includes(relatedDoc.toLowerCase().replace(/\\s+/g, '-'))\n );\n if (docKey) {\n context += `\\n**Related: ${relatedDoc}**\\n`;\n context += docsContext.get(docKey)?.slice(0, 2000) + '\\n';\n }\n }\n context += '\\n---\\n\\n';\n }\n\n context += '\\n## Instructions\\n';\n context += 'CRITICAL: Create actual document FILES using the exact format below.\\n';\n context += 'Use the project context and technical documentation above.\\n';\n context += 'Do NOT generate generic placeholder content. Use ACTUAL project details.\\n\\n';\n context += 'OUTPUT FORMAT - Use this EXACT format for EACH document you create:\\n\\n';\n context += '```document\\n';\n context += '---\\n';\n context += 'path: relative/path/to/file.md\\n';\n context += 'action: create\\n';\n context += '---\\n';\n context += '# Document Title\\n\\n';\n context += 'Document content with [[wiki-links]] to other documents.\\n';\n context += '```\\n\\n';\n context += 'For each gap, create documentation that:\\n';\n context += '1. Addresses the specific issue using REAL project details (Rust, WASM, Knowledge Graph, etc.)\\n';\n context += '2. References specific technologies mentioned in the technical docs\\n';\n context += '3. Links to existing docs: [[test_strategy]], [[PRIMITIVES]], [[rust_wasm_knowledge_graph_integration_research]]\\n';\n context += '4. Contains concrete, project-specific information - NOT generic placeholders\\n';\n context += '5. Uses proper frontmatter with title, type, and tags\\n';\n\n return context;\n }\n\n /**\n * Build context for researcher agent\n */\n private buildResearcherContext(questions: ResearchQuestion[], docsContext: Map<string, string>): string {\n let context = '## Research Questions to Answer\\n\\n';\n\n for (const q of questions) {\n context += `### Question\\n${q.question}\\n\\n`;\n if (q.importance) {\n context += `**Importance:** ${q.importance}\\n`;\n }\n if (q.context) {\n context += `**Context:** ${q.context}\\n`;\n }\n if (q.suggestedResources.length > 0) {\n context += `**Resources:** ${q.suggestedResources.join(', ')}\\n`;\n }\n context += '\\n---\\n\\n';\n }\n\n // Add relevant documentation context\n context += '\\n## Available Documentation Context\\n\\n';\n const relevantDocs = this.findRelevantDocs(\n questions.map(q => q.question).join(' '),\n docsContext,\n 5\n );\n for (const [path, content] of relevantDocs) {\n context += `### ${path}\\n`;\n context += content.slice(0, 3000) + '\\n\\n';\n }\n\n context += '\\n## Instructions\\n';\n context += 'For each research question:\\n';\n context += '1. Analyze the available documentation\\n';\n context += '2. Synthesize a well-researched answer\\n';\n context += '3. Cite sources using [[wiki-links]]\\n';\n context += '4. Identify any remaining unknowns\\n';\n context += '5. Suggest best practices based on the knowledge graph\\n';\n\n return context;\n }\n\n /**\n * Build context for MOC builder agent\n */\n private buildMOCBuilderContext(\n gaps: DocumentationGap[],\n docsContext: Map<string, string>,\n analysis: ParsedAnalysis\n ): string {\n let context = '## Project Context\\n\\n';\n\n // Include the project vision so MOCs reflect actual project content\n if (analysis.vision.purpose) {\n context += `### Project Purpose\\n${analysis.vision.purpose}\\n\\n`;\n }\n if (analysis.vision.goals.length > 0) {\n context += `### Key Goals\\n`;\n for (const goal of analysis.vision.goals.slice(0, 5)) {\n context += `- ${goal}\\n`;\n }\n context += '\\n';\n }\n\n context += '## MOC Files to Populate\\n\\n';\n\n // Find all MOC files\n const mocFiles = Array.from(docsContext.keys()).filter(k =>\n k.includes('_MOC.md') || k.includes('MOC.md')\n );\n\n context += '### Current MOC Files\\n';\n for (const mocFile of mocFiles) {\n const content = docsContext.get(mocFile) || '';\n const isEmpty = content.length < 200 || content.includes('stub');\n context += `- ${mocFile} ${isEmpty ? '(EMPTY/STUB)' : '(has content)'}\\n`;\n }\n\n context += '\\n### Gap Analysis Related to MOCs\\n';\n for (const gap of gaps) {\n context += `- ${gap.section}: ${gap.description}\\n`;\n if (gap.recommendation) {\n context += ` Recommendation: ${gap.recommendation}\\n`;\n }\n }\n\n // Add directory structure with document names\n context += '\\n### Documentation Structure\\n';\n const directories = new Set<string>();\n for (const path of docsContext.keys()) {\n const dir = dirname(path);\n if (dir !== '.') {\n directories.add(dir);\n }\n }\n for (const dir of directories) {\n const docsInDir = Array.from(docsContext.keys()).filter(k => dirname(k) === dir);\n context += `- ${dir}/ (${docsInDir.length} docs)\\n`;\n for (const doc of docsInDir.slice(0, 10)) {\n context += ` - ${basename(doc)}\\n`;\n }\n }\n\n // Include key technical docs for context\n context += '\\n### Key Technical Documentation (for reference)\\n';\n const keyDocs = Array.from(docsContext.entries())\n .filter(([path]) => {\n const lower = path.toLowerCase();\n return lower.includes('test_strategy') || lower.includes('wasm') ||\n lower.includes('architecture') || lower.includes('original_spec');\n })\n .slice(0, 3);\n\n for (const [path, content] of keyDocs) {\n context += `\\n#### ${path}\\n`;\n context += content.slice(0, 2000) + '\\n';\n }\n\n context += '\\n## Instructions\\n';\n context += 'CRITICAL: Create MOCs that reflect the ACTUAL project content, not generic placeholders.\\n';\n context += 'Use the project context and technical documentation above.\\n\\n';\n context += 'For each empty/stub MOC file:\\n';\n context += '1. Create a proper introduction describing what the section covers IN THIS PROJECT\\n';\n context += '2. List all documents in that directory with [[wiki-links]]\\n';\n context += '3. Organize by subcategory if applicable\\n';\n context += '4. Add brief, PROJECT-SPECIFIC descriptions for each linked document\\n';\n context += '5. Include navigation links to parent/sibling MOCs\\n';\n context += '6. Reference actual technologies and concepts from the project (e.g., Rust WASM, knowledge graph)\\n';\n\n return context;\n }\n\n /**\n * Build context for connector agent\n */\n private buildConnectorContext(connections: ConnectionSuggestion[], docsContext: Map<string, string>): string {\n let context = '## Suggested Knowledge Graph Connections\\n\\n';\n\n for (const conn of connections) {\n context += `- [${conn.source}] --${conn.relationship}--> [${conn.target}]`;\n if (conn.reason) {\n context += `: ${conn.reason}`;\n }\n context += '\\n';\n }\n\n context += '\\n## Existing Documents\\n';\n for (const [path] of Array.from(docsContext.entries()).slice(0, 30)) {\n context += `- [[${path.replace('.md', '')}]]\\n`;\n }\n\n context += '\\n## Instructions\\n';\n context += 'For each suggested connection:\\n';\n context += '1. Find the source document\\n';\n context += '2. Add appropriate wiki-link [[target]] to the source\\n';\n context += '3. Consider adding reciprocal links where appropriate\\n';\n context += '4. Use \"See also\" or \"Related\" sections for connections\\n';\n context += '5. Ensure the link context is meaningful\\n';\n\n return context;\n }\n\n /**\n * Build context for integrator agent\n */\n private buildIntegratorContext(analysis: ParsedAnalysis, docsContext: Map<string, string>): string {\n let context = '## Integration Context\\n\\n';\n\n context += '### Project Vision\\n';\n context += analysis.vision.purpose + '\\n\\n';\n\n context += '### Goals\\n';\n for (const goal of analysis.vision.goals) {\n context += `- ${goal}\\n`;\n }\n\n context += '\\n### Key Recommendations\\n';\n for (const rec of analysis.vision.recommendations) {\n context += `- ${rec}\\n`;\n }\n\n context += '\\n### Statistics\\n';\n context += `- Total documents: ${docsContext.size}\\n`;\n context += `- Gaps identified: ${analysis.gaps.length}\\n`;\n context += `- Questions to answer: ${analysis.questions.length}\\n`;\n context += `- Connections to build: ${analysis.connections.length}\\n`;\n\n context += '\\n## Instructions\\n';\n context += 'Create an integration summary that:\\n';\n context += '1. Lists all changes made during migration\\n';\n context += '2. Highlights any remaining gaps\\n';\n context += '3. Suggests next steps for documentation improvement\\n';\n context += '4. Provides a quality assessment\\n';\n\n return context;\n }\n\n /**\n * Build context for SOP gap filler agent\n */\n private buildSOPGapFillerContext(\n sopGaps: SOPGapSummary[],\n docsContext: Map<string, string>,\n analysis: ParsedAnalysis\n ): string {\n let context = '## AI-SDLC SOP Compliance Gaps\\n\\n';\n\n // Include summary if available\n if (analysis.sopSummary) {\n context += '### Compliance Summary\\n';\n context += `- Total Gaps: ${analysis.sopSummary.totalGaps}\\n`;\n context += `- Critical Gaps: ${analysis.sopSummary.criticalGaps}\\n`;\n context += `- Compliance: ${analysis.sopSummary.compliancePercentage}%\\n\\n`;\n }\n\n // Include project context\n if (analysis.vision.purpose) {\n context += `### Project Purpose\\n${analysis.vision.purpose}\\n\\n`;\n }\n\n // Include key technical documentation\n context += '## Key Technical Documentation\\n\\n';\n const keyDocPatterns = [\n 'test_strategy', 'technical', 'architecture', 'wasm', 'rust',\n 'original_spec', 'integration', 'requirements', 'security'\n ];\n\n for (const [docPath, docContent] of docsContext) {\n const lowerPath = docPath.toLowerCase();\n if (keyDocPatterns.some(pattern => lowerPath.includes(pattern))) {\n context += `### ${docPath}\\n`;\n context += docContent.slice(0, 3000) + '\\n\\n';\n }\n }\n\n context += '## SOP Compliance Gaps to Address\\n\\n';\n context += 'The following gaps were identified from AI-SDLC SOP compliance analysis.\\n';\n context += 'Create documentation to address each gap based on the project context.\\n\\n';\n\n // Group gaps by SOP for better organization\n const gapsBySOP = new Map<string, SOPGapSummary[]>();\n for (const gap of sopGaps) {\n const sopId = gap.sopId || 'general';\n if (!gapsBySOP.has(sopId)) {\n gapsBySOP.set(sopId, []);\n }\n gapsBySOP.get(sopId)!.push(gap);\n }\n\n for (const [sopId, gaps] of gapsBySOP) {\n context += `### SOP: ${sopId}\\n\\n`;\n for (const gap of gaps) {\n context += `#### ${gap.priority.toUpperCase()}: ${gap.description}\\n`;\n context += `- **Requirement:** ${gap.requirementId}\\n`;\n context += `- **Effort:** ${gap.effort}\\n`;\n context += `- **Remediation:** ${gap.remediation}\\n\\n`;\n }\n }\n\n context += '\\n## Instructions\\n';\n context += 'CRITICAL: Create documentation to address the SOP compliance gaps above.\\n';\n context += 'Use the project context and technical documentation to ensure relevance.\\n\\n';\n context += 'OUTPUT FORMAT - Use this EXACT format for EACH document you create:\\n\\n';\n context += '```document\\n';\n context += '---\\n';\n context += 'path: relative/path/to/file.md\\n';\n context += 'action: create\\n';\n context += '---\\n';\n context += '# Document Title\\n\\n';\n context += 'Document content with [[wiki-links]] to other documents.\\n';\n context += '```\\n\\n';\n context += 'For each SOP gap:\\n';\n context += '1. Create documentation that directly addresses the compliance requirement\\n';\n context += '2. Place documents in appropriate directories based on type:\\n';\n context += ' - standards/ for coding standards, style guides, policies\\n';\n context += ' - guides/ for tutorials, how-tos, processes\\n';\n context += ' - references/ for API docs, specifications, schemas\\n';\n context += ' - docs/ for general documentation\\n';\n context += '3. Include project-specific content (Rust, WASM, TypeScript, Knowledge Graph)\\n';\n context += '4. Reference existing documentation with [[wiki-links]]\\n';\n context += '5. Follow the remediation guidance provided for each gap\\n';\n\n return context;\n }\n\n /**\n * Execute a single migration agent\n */\n private async executeAgent(\n agent: MigrationAgent,\n analysis: ParsedAnalysis,\n docsContext: Map<string, string>\n ): Promise<{\n documentsCreated?: number;\n documentsUpdated?: number;\n gapsFilled?: number;\n questionsAnswered?: number;\n connectionsAdded?: number;\n }> {\n this.log('info', `Executing agent: ${agent.name}`, { type: agent.type });\n\n const prompt = this.buildAgentPrompt(agent);\n const response = await this.callAI(prompt, agent.type);\n\n if (!response) {\n throw new Error('No response from AI');\n }\n\n // Parse response and create/update documents\n const result = await this.processAgentResponse(agent, response, docsContext);\n\n this.log('info', `Agent ${agent.name} completed`, result);\n\n return result;\n }\n\n /**\n * Build prompt for agent\n */\n private buildAgentPrompt(agent: MigrationAgent): string {\n return `# ${agent.name}\n\n## Task\n${agent.task}\n\n${agent.context}\n\n## Output Format\nProvide your response in markdown format with clear sections.\nFor each document to create or update, use this format:\n\n\\`\\`\\`document\n---\npath: relative/path/to/file.md\naction: create|update\n---\n# Document Title\n\nDocument content here with [[wiki-links]] to other documents.\n\\`\\`\\`\n\nFor research answers, use:\n\\`\\`\\`answer\n## Question\nThe original question\n\n## Answer\nYour researched answer with [[citations]]\n\n## Best Practices\n- Recommendation 1\n- Recommendation 2\n\n## Remaining Unknowns\n- Any unresolved items\n\\`\\`\\`\n`;\n }\n\n /**\n * Select the best model based on task complexity\n * - Research and gap-filling tasks use the most capable model\n * - Simpler tasks use faster models\n */\n private selectGeminiModel(agentType: MigrationAgent['type']): string {\n // Use the most capable model for complex reasoning tasks\n const complexTasks = ['gap-filler', 'researcher'];\n if (complexTasks.includes(agentType)) {\n // gemini-2.5-pro for complex planning/research tasks\n return 'gemini-2.5-pro';\n }\n // Use fast model for simpler tasks (gemini-2.5-flash is better than 2.0-flash)\n return 'gemini-2.5-flash';\n }\n\n /**\n * Call AI (Gemini or fallback)\n */\n private async callAI(prompt: string, agentType: MigrationAgent['type']): Promise<string | null> {\n if (this.geminiClient) {\n const modelName = this.selectGeminiModel(agentType);\n try {\n this.log('info', `Using model: ${modelName}`, { agentType });\n const model = this.geminiClient.getGenerativeModel({ model: modelName });\n const result = await model.generateContent(prompt);\n return result.response.text();\n } catch (error) {\n // Fallback to gemini-2.5-flash if the pro model fails\n if (modelName !== 'gemini-2.5-flash') {\n this.log('warn', `${modelName} failed, falling back to gemini-2.5-flash`, { error: String(error) });\n try {\n const fallbackModel = this.geminiClient.getGenerativeModel({ model: 'gemini-2.5-flash' });\n const result = await fallbackModel.generateContent(prompt);\n return result.response.text();\n } catch (fallbackError) {\n this.log('error', 'Gemini fallback also failed', { error: String(fallbackError) });\n }\n } else {\n this.log('error', 'Gemini API call failed', { error: String(error) });\n }\n return null;\n }\n }\n\n // Fallback to Anthropic if available\n if (process.env.ANTHROPIC_API_KEY) {\n try {\n const { default: Anthropic } = await import('@anthropic-ai/sdk');\n const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n // Use opus for complex tasks, sonnet for simpler ones\n const complexTasks = ['gap-filler', 'researcher'];\n const model = complexTasks.includes(agentType)\n ? 'claude-sonnet-4-20250514' // Best available\n : 'claude-sonnet-4-20250514';\n const message = await client.messages.create({\n model,\n max_tokens: 8000,\n messages: [{ role: 'user', content: prompt }]\n });\n const textBlock = message.content.find(b => b.type === 'text');\n return textBlock ? textBlock.text : null;\n } catch (error) {\n this.log('error', 'Anthropic API call failed', { error: String(error) });\n return null;\n }\n }\n\n return null;\n }\n\n /**\n * Process agent response and create/update documents\n */\n private async processAgentResponse(\n agent: MigrationAgent,\n response: string,\n docsContext: Map<string, string>\n ): Promise<{\n documentsCreated?: number;\n documentsUpdated?: number;\n gapsFilled?: number;\n questionsAnswered?: number;\n connectionsAdded?: number;\n }> {\n const result = {\n documentsCreated: 0,\n documentsUpdated: 0,\n gapsFilled: 0,\n questionsAnswered: 0,\n connectionsAdded: 0\n };\n\n // Extract document blocks\n const documentMatches = response.matchAll(/```document\\n---\\npath:\\s*([^\\n]+)\\naction:\\s*(\\w+)\\n---\\n([\\s\\S]*?)```/g);\n\n for (const match of documentMatches) {\n const path = match[1].trim();\n const action = match[2].trim();\n const content = match[3].trim();\n\n if (this.dryRun) {\n this.log('info', `[DRY RUN] Would ${action}: ${path}`);\n continue;\n }\n\n const fullPath = join(this.projectRoot, this.docsPath, path);\n\n // Ensure directory exists\n const dir = dirname(fullPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n // Write document\n const finalContent = this.addFrontmatter(content, path, agent.type);\n writeFileSync(fullPath, finalContent, 'utf-8');\n\n if (action === 'create') {\n result.documentsCreated++;\n if (agent.type === 'gap-filler') {\n result.gapsFilled++;\n }\n } else {\n result.documentsUpdated++;\n }\n\n // Count connections added\n const wikiLinks = content.match(/\\[\\[[^\\]]+\\]\\]/g) || [];\n result.connectionsAdded += wikiLinks.length;\n }\n\n // Extract answer blocks\n const answerMatches = response.matchAll(/```answer\\n([\\s\\S]*?)```/g);\n for (const match of answerMatches) {\n result.questionsAnswered++;\n\n // Save answer to research output file\n if (agent.outputFile && !this.dryRun) {\n const outputPath = join(this.projectRoot, this.docsPath, 'analysis', agent.outputFile);\n const existing = existsSync(outputPath) ? readFileSync(outputPath, 'utf-8') : '';\n const newContent = existing + '\\n\\n---\\n\\n' + match[1].trim();\n writeFileSync(outputPath, newContent, 'utf-8');\n }\n }\n\n // If agent has output file and no document blocks, save raw response\n if (agent.outputFile && result.documentsCreated === 0 && !this.dryRun) {\n const outputPath = join(this.projectRoot, this.docsPath, 'analysis', agent.outputFile);\n const frontmatter = `---\ntitle: \"${agent.name}\"\ntype: migration-output\ngenerator: migration-orchestrator\nagent: ${agent.type}\ncreated: ${new Date().toISOString()}\n---\n\n# ${agent.name}\n\n> Generated by MigrationOrchestrator\n\n`;\n writeFileSync(outputPath, frontmatter + response, 'utf-8');\n result.documentsCreated++;\n }\n\n return result;\n }\n\n /**\n * Add frontmatter to document if not present\n */\n private addFrontmatter(content: string, path: string, agentType: string): string {\n if (content.startsWith('---')) {\n return content;\n }\n\n const title = basename(path, '.md').replace(/-/g, ' ').replace(/_/g, ' ');\n const type = this.inferDocType(path);\n\n return `---\ntitle: \"${title}\"\ntype: ${type}\ngenerator: migration-orchestrator\nagent: ${agentType}\ncreated: ${new Date().toISOString()}\n---\n\n${content}`;\n }\n\n /**\n * Infer document type from path\n */\n private inferDocType(path: string): string {\n if (path.includes('concepts')) return 'concept';\n if (path.includes('components')) return 'component';\n if (path.includes('services')) return 'service';\n if (path.includes('features')) return 'feature';\n if (path.includes('guides')) return 'guide';\n if (path.includes('references')) return 'reference';\n if (path.includes('standards')) return 'standard';\n if (path.includes('integrations')) return 'integration';\n if (path.includes('MOC')) return 'moc';\n return 'document';\n }\n\n /**\n * Update MOC files with new connections\n */\n private async updateMOCFiles(connections: ConnectionSuggestion[]): Promise<void> {\n // This would update MOC files with new links\n // For now, we'll let the MOC builder agent handle this\n this.log('info', 'MOC files updated with new connections', { count: connections.length });\n }\n\n /**\n * Find relevant docs based on query\n */\n private findRelevantDocs(\n query: string,\n docsContext: Map<string, string>,\n limit: number\n ): Map<string, string> {\n const relevant = new Map<string, string>();\n const queryWords = query.toLowerCase().split(/\\s+/).filter(w => w.length > 3);\n\n // Simple keyword matching (would use vector search if available)\n const scored = Array.from(docsContext.entries()).map(([path, content]) => {\n let score = 0;\n const lowerContent = content.toLowerCase();\n for (const word of queryWords) {\n if (lowerContent.includes(word)) {\n score++;\n }\n }\n return { path, content, score };\n });\n\n scored.sort((a, b) => b.score - a.score);\n\n for (const item of scored.slice(0, limit)) {\n if (item.score > 0) {\n relevant.set(item.path, item.content);\n }\n }\n\n return relevant;\n }\n\n /**\n * Infer priority from description\n */\n private inferPriority(description: string, recommendation: string): 'high' | 'medium' | 'low' {\n const text = (description + ' ' + recommendation).toLowerCase();\n\n if (text.includes('critical') || text.includes('missing') || text.includes('empty') ||\n text.includes('stub') || text.includes('required')) {\n return 'high';\n }\n\n if (text.includes('should') || text.includes('recommend') || text.includes('consider')) {\n return 'medium';\n }\n\n return 'low';\n }\n\n /**\n * Log message\n */\n private log(level: 'info' | 'warn' | 'error', message: string, data?: Record<string, unknown>): void {\n if (!this.verbose && level === 'info') return;\n\n const timestamp = new Date().toISOString().split('T')[1].split('.')[0];\n const prefix = level === 'error' ? '❌' : level === 'warn' ? '⚠️' : '📋';\n\n console.log(`[${timestamp}] ${prefix} [migration] ${message}`, data ? JSON.stringify(data) : '');\n }\n}\n\nexport type { MigrationResult, OrchestratorOptions, ParsedAnalysis };\n"],"names":[],"mappings":";;;AAsIO,MAAM,sBAAsB;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAA0C;AAAA,EAElD,YAAY,SAA8B;AACxC,SAAK,cAAc,QAAQ;AAC3B,SAAK,WAAW,QAAQ;AACxB,SAAK,cAAc,QAAQ;AAC3B,SAAK,UAAU,QAAQ,WAAW;AAClC,SAAK,SAAS,QAAQ,UAAU;AAChC,SAAK,kBAAkB,QAAQ,mBAAmB;AAClD,SAAK,YAAY,QAAQ,aAAa;AAGtC,UAAM,SAAS,QAAQ,IAAI,yBACZ,QAAQ,IAAI,qBACZ,QAAQ,IAAI,kBACZ,QAAQ,IAAI;AA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UAAM,QAAQ,cAAc,MAAM,gBAAgB,YAAA;AAElD,QAAI,KAAK,SAAS,UAAU,KAAK,KAAK,SAAS,SAAS,KAAK,KAAK,SAAS,OAAO,KAC9E,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,UAAU,GAAG;AACtD,aAAO;AAAA,IACT;AAEA,QAAI,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,UAAU,GAAG;AACtF,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKQ,IAAI,OAAkC,SAAiB,MAAsC;AACnG,QAAI,CAAC,KAAK,WAAW,UAAU,OAAQ;AAEvC,UAAM,aAAY,oBAAI,KAAA,GAAO,cAAc,MAAM,GAAG,EAAE,CAAC,EAAE,MAAM,GAAG,EAAE,CAAC;AACrE,UAAM,SAAS,UAAU,UAAU,MAAM,UAAU,SAAS,OAAO;AAEnE,YAAQ,IAAI,IAAI,SAAS,KAAK,MAAM,gBAAgB,OAAO,IAAI,OAAO,KAAK,UAAU,IAAI,IAAI,EAAE;AAAA,EACjG;AACF;"}
@@ -1,4 +1,4 @@
1
- import { __exports as dist } from "../../../../_virtual/index5.js";
1
+ import { __exports as dist } from "../../../../_virtual/index6.js";
2
2
  import { __require as requireAstSpec } from "./generated/ast-spec.js";
3
3
  import { __require as requireLib } from "./lib.js";
4
4
  import { __require as requireParserOptions } from "./parser-options.js";
@@ -1,4 +1,4 @@
1
- import { __exports as dist } from "../../../../_virtual/index6.js";
1
+ import { __exports as dist } from "../../../../_virtual/index5.js";
2
2
  import { __require as requireGetKeys } from "./get-keys.js";
3
3
  import { __require as requireVisitorKeys } from "./visitor-keys.js";
4
4
  var hasRequiredDist;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weavelogic/knowledge-graph-agent",
3
- "version": "0.11.4",
3
+ "version": "0.11.5",
4
4
  "description": "Knowledge graph agent for Claude Code - generates knowledge graphs, initializes docs, and integrates with claude-flow",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",