@weavelogic/knowledge-graph-agent 0.11.0 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -133,6 +133,18 @@ export declare class DeepAnalyzer {
133
133
  * Read full content of key documents
134
134
  */
135
135
  private readKeyDocuments;
136
+ /**
137
+ * Scan directory structure for MOC files and coverage
138
+ */
139
+ private scanDirectoryStructure;
140
+ /**
141
+ * Load previous analysis results for iteration tracking
142
+ */
143
+ private loadPreviousAnalysis;
144
+ /**
145
+ * Save analysis metadata for iteration tracking
146
+ */
147
+ private saveAnalysisMetadata;
136
148
  /**
137
149
  * Run deep analysis
138
150
  */
@@ -141,6 +153,10 @@ export declare class DeepAnalyzer {
141
153
  * Execute a single agent
142
154
  */
143
155
  private executeAgent;
156
+ /**
157
+ * Build directory coverage summary for prompts
158
+ */
159
+ private buildCoverageSummary;
144
160
  /**
145
161
  * Build context-aware prompt for documentation cultivation
146
162
  */
@@ -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,6BAA6B;IAC7B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,mCAAmC;IACnC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,qCAAqC;IACrC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oDAAoD;IACpD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,qDAAqD;IACrD,iBAAiB,CAAC,EAAE,WAAW,GAAG,QAAQ,CAAC;CAC5C;AAED;;GAEG;AACH,MAAM,WAAW,WAAW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,CAAC,eAAe;IASvB;;OAEG;IACH,OAAO,CAAC,cAAc;IAatB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAiD3B;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;IAKrC;;OAEG;IACG,qBAAqB,IAAI,OAAO,CAAC;QAAE,SAAS,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAQ9E;;OAEG;IACH,OAAO,CAAC,iBAAiB;IA6DzB;;OAEG;IACH,OAAO,CAAC,gBAAgB;IA+BxB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IA0F9B;;OAEG;IACH,OAAO,CAAC,oBAAoB;IAe5B;;OAEG;IACH,OAAO,CAAC,oBAAoB;IA+B5B;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,kBAAkB,CAAC;IAgI5C;;OAEG;YACW,YAAY;IAuD1B;;OAEG;IACH,OAAO,CAAC,oBAAoB;IA4C5B;;OAEG;IACH,OAAO,CAAC,WAAW;IA0JnB;;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"}
@@ -1,5 +1,5 @@
1
1
  import { execFileSync, execSync } from "child_process";
2
- import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, statSync } from "fs";
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
5
  const logger = createLogger("deep-analyzer");
@@ -200,6 +200,122 @@ class DeepAnalyzer {
200
200
  }
201
201
  return keyDocs;
202
202
  }
203
+ /**
204
+ * Scan directory structure for MOC files and coverage
205
+ */
206
+ scanDirectoryStructure() {
207
+ const docsDir = join(this.projectRoot, this.docsPath);
208
+ if (!existsSync(docsDir)) {
209
+ return [];
210
+ }
211
+ const directories = [];
212
+ const ignoredDirs = /* @__PURE__ */ new Set([".", "..", "analysis", "node_modules", ".git", ".obsidian"]);
213
+ const scanDir = (dir, depth = 0) => {
214
+ if (depth > 5) return;
215
+ const relPath = relative(docsDir, dir) || ".";
216
+ const entries = readdirSync(dir, { withFileTypes: true });
217
+ const subdirs = [];
218
+ const docs = [];
219
+ let mocFile = null;
220
+ let mocContent = "";
221
+ for (const entry of entries) {
222
+ if (ignoredDirs.has(entry.name) || entry.name.startsWith(".")) continue;
223
+ if (entry.isDirectory()) {
224
+ subdirs.push(entry.name);
225
+ scanDir(join(dir, entry.name), depth + 1);
226
+ } else if (entry.isFile() && entry.name.endsWith(".md")) {
227
+ docs.push(entry.name);
228
+ if (entry.name === "_MOC.md" || entry.name === "MOC.md" || entry.name === "index.md") {
229
+ mocFile = entry.name;
230
+ try {
231
+ mocContent = readFileSync(join(dir, entry.name), "utf-8");
232
+ } catch {
233
+ mocContent = "";
234
+ }
235
+ }
236
+ }
237
+ }
238
+ let mocStatus = "missing";
239
+ if (mocFile) {
240
+ if (mocContent.length < 100) {
241
+ mocStatus = "empty";
242
+ } else if (mocContent.toLowerCase().includes("stub") || mocContent.includes("TODO") || mocContent.includes("TBD") || !mocContent.includes("[[")) {
243
+ mocStatus = "stub";
244
+ } else {
245
+ mocStatus = "complete";
246
+ }
247
+ }
248
+ let needsDocumentation = false;
249
+ let reason = "";
250
+ if (subdirs.length > 0 || docs.length > 1) {
251
+ if (mocStatus === "missing") {
252
+ needsDocumentation = true;
253
+ reason = "Directory has content but no MOC file";
254
+ } else if (mocStatus === "empty" || mocStatus === "stub") {
255
+ needsDocumentation = true;
256
+ reason = `MOC file is ${mocStatus} - needs content`;
257
+ }
258
+ }
259
+ if (subdirs.length > 0 || docs.length > 0 || relPath === ".") {
260
+ directories.push({
261
+ path: relPath,
262
+ name: basename(dir),
263
+ hasMOC: mocFile !== null,
264
+ mocStatus,
265
+ documentCount: docs.length,
266
+ subdirectories: subdirs,
267
+ documents: docs,
268
+ needsDocumentation,
269
+ reason
270
+ });
271
+ }
272
+ };
273
+ scanDir(docsDir);
274
+ return directories;
275
+ }
276
+ /**
277
+ * Load previous analysis results for iteration tracking
278
+ */
279
+ loadPreviousAnalysis() {
280
+ const metadataFile = join(this.outputDir, ".analysis-metadata.json");
281
+ if (!existsSync(metadataFile)) {
282
+ return null;
283
+ }
284
+ try {
285
+ const content = readFileSync(metadataFile, "utf-8");
286
+ return JSON.parse(content);
287
+ } catch {
288
+ return null;
289
+ }
290
+ }
291
+ /**
292
+ * Save analysis metadata for iteration tracking
293
+ */
294
+ saveAnalysisMetadata(result, dirCoverage) {
295
+ const metadataFile = join(this.outputDir, ".analysis-metadata.json");
296
+ const previous = this.loadPreviousAnalysis();
297
+ const totalDirs = dirCoverage.length;
298
+ const coveredDirs = dirCoverage.filter((d) => d.mocStatus === "complete").length;
299
+ const coverageScore = totalDirs > 0 ? coveredDirs / totalDirs * 100 : 0;
300
+ const gapsResult = result.results.find((r) => r.type === "gaps");
301
+ const questionsResult = result.results.find((r) => r.type === "research");
302
+ const coverageResult = result.results.find((r) => r.type === "coverage");
303
+ const metadata = {
304
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
305
+ iteration: (previous?.iteration || 0) + 1,
306
+ gapsIdentified: (gapsResult?.insights.length || 0) + (coverageResult?.insights.length || 0),
307
+ gapsFilled: 0,
308
+ // Updated by migrate command
309
+ questionsRaised: questionsResult?.insights.length || 0,
310
+ questionsAnswered: 0,
311
+ // Updated by migrate command
312
+ coverageScore
313
+ };
314
+ try {
315
+ writeFileSync(metadataFile, JSON.stringify(metadata, null, 2));
316
+ } catch {
317
+ }
318
+ }
203
319
  /**
204
320
  * Run deep analysis
205
321
  */
@@ -228,12 +344,21 @@ class DeepAnalyzer {
228
344
  }
229
345
  const documents = this.scanDocumentation();
230
346
  const keyDocs = this.readKeyDocuments();
347
+ const dirCoverage = this.scanDirectoryStructure();
348
+ const previousAnalysis = this.loadPreviousAnalysis();
231
349
  if (documents.length === 0) {
232
350
  result.errors.push("No markdown documents found in docs directory");
233
351
  result.duration = Date.now() - startTime;
234
352
  return result;
235
353
  }
236
- logger.info("Found documentation", { documents: documents.length, keyDocs: keyDocs.size });
354
+ const iteration = (previousAnalysis?.iteration || 0) + 1;
355
+ logger.info("Found documentation", {
356
+ documents: documents.length,
357
+ keyDocs: keyDocs.size,
358
+ directories: dirCoverage.length,
359
+ needsWork: dirCoverage.filter((d) => d.needsDocumentation).length,
360
+ iteration
361
+ });
237
362
  const agents = [
238
363
  {
239
364
  name: "Vision Synthesizer",
@@ -241,6 +366,12 @@ class DeepAnalyzer {
241
366
  task: "Synthesize the project vision, goals, and core value proposition from the documentation",
242
367
  outputFile: "vision-synthesis.md"
243
368
  },
369
+ {
370
+ name: "Directory Coverage Analyst",
371
+ type: "coverage",
372
+ task: "Analyze directory structure, MOC files, and identify areas needing documentation",
373
+ outputFile: "directory-coverage.md"
374
+ },
244
375
  {
245
376
  name: "Gap Analyst",
246
377
  type: "gaps",
@@ -260,16 +391,19 @@ class DeepAnalyzer {
260
391
  outputFile: "knowledge-connections.md"
261
392
  }
262
393
  ];
263
- logger.info("Executing cultivation agents", { agents: agents.length, mode: "sequential" });
394
+ logger.info("Executing cultivation agents", { agents: agents.length, mode: "sequential", iteration });
264
395
  for (const agent of agents) {
265
396
  const agentResult = await this.executeAgent(
266
397
  agent,
267
398
  executionMode.mode,
268
399
  documents,
269
- keyDocs
400
+ keyDocs,
401
+ dirCoverage,
402
+ previousAnalysis
270
403
  );
271
404
  result.results.push(agentResult);
272
405
  }
406
+ this.saveAnalysisMetadata(result, dirCoverage);
273
407
  result.agentsSpawned = result.results.length;
274
408
  result.insightsCount = result.results.reduce((sum, r) => sum + r.insights.length, 0);
275
409
  result.documentsCreated = result.results.reduce((sum, r) => sum + r.documents.length, 0);
@@ -291,7 +425,7 @@ class DeepAnalyzer {
291
425
  /**
292
426
  * Execute a single agent
293
427
  */
294
- async executeAgent(agent, mode, documents, keyDocs) {
428
+ async executeAgent(agent, mode, documents, keyDocs, dirCoverage, previousAnalysis) {
295
429
  const startTime = Date.now();
296
430
  const outputPath = join(this.outputDir, agent.outputFile);
297
431
  const result = {
@@ -304,7 +438,7 @@ class DeepAnalyzer {
304
438
  };
305
439
  try {
306
440
  logger.info(`Executing agent: ${agent.name}`, { type: agent.type, mode });
307
- const prompt = this.buildPrompt(agent, documents, keyDocs);
441
+ const prompt = this.buildPrompt(agent, documents, keyDocs, dirCoverage, previousAnalysis);
308
442
  let output;
309
443
  if (mode === "cli") {
310
444
  output = await this.runWithCli(prompt);
@@ -327,16 +461,91 @@ class DeepAnalyzer {
327
461
  result.duration = Date.now() - startTime;
328
462
  return result;
329
463
  }
464
+ /**
465
+ * Build directory coverage summary for prompts
466
+ */
467
+ buildCoverageSummary(dirCoverage) {
468
+ const lines = [];
469
+ const total = dirCoverage.length;
470
+ const complete = dirCoverage.filter((d) => d.mocStatus === "complete").length;
471
+ const stub = dirCoverage.filter((d) => d.mocStatus === "stub").length;
472
+ const empty = dirCoverage.filter((d) => d.mocStatus === "empty").length;
473
+ const missing = dirCoverage.filter((d) => d.mocStatus === "missing").length;
474
+ lines.push(`### Summary`);
475
+ lines.push(`- Total Directories: ${total}`);
476
+ lines.push(`- Complete MOCs: ${complete} (${(complete / total * 100).toFixed(1)}%)`);
477
+ lines.push(`- Stub MOCs: ${stub}`);
478
+ lines.push(`- Empty MOCs: ${empty}`);
479
+ lines.push(`- Missing MOCs: ${missing}`);
480
+ lines.push(`- Coverage Score: ${(complete / total * 100).toFixed(1)}%`);
481
+ lines.push("");
482
+ const needsWork = dirCoverage.filter((d) => d.needsDocumentation);
483
+ if (needsWork.length > 0) {
484
+ lines.push("### Directories Needing Documentation");
485
+ for (const dir of needsWork) {
486
+ lines.push(`- **${dir.path}/** (${dir.mocStatus})`);
487
+ lines.push(` - Documents: ${dir.documents.join(", ") || "none"}`);
488
+ lines.push(` - Subdirectories: ${dir.subdirectories.join(", ") || "none"}`);
489
+ lines.push(` - Reason: ${dir.reason}`);
490
+ }
491
+ lines.push("");
492
+ }
493
+ const completeDirs = dirCoverage.filter((d) => d.mocStatus === "complete");
494
+ if (completeDirs.length > 0) {
495
+ lines.push("### Directories with Complete MOCs");
496
+ for (const dir of completeDirs) {
497
+ lines.push(`- ${dir.path}/ (${dir.documentCount} docs)`);
498
+ }
499
+ }
500
+ return lines.join("\n");
501
+ }
330
502
  /**
331
503
  * Build context-aware prompt for documentation cultivation
332
504
  */
333
- buildPrompt(agent, documents, keyDocs) {
505
+ buildPrompt(agent, documents, keyDocs, dirCoverage, previousAnalysis) {
334
506
  const inventory = documents.map((d) => `- ${d.path} (${d.type}): ${d.title}`).join("\n");
335
507
  const keyContent = Array.from(keyDocs.entries()).map(([name, content]) => `### ${name}
336
508
 
337
509
  ${content}`).join("\n\n---\n\n");
510
+ const coverageSummary = this.buildCoverageSummary(dirCoverage);
511
+ const iterationContext = previousAnalysis ? `
512
+ ## Previous Analysis (Iteration ${previousAnalysis.iteration})
513
+ - Timestamp: ${previousAnalysis.timestamp}
514
+ - Gaps Identified: ${previousAnalysis.gapsIdentified}
515
+ - Gaps Filled: ${previousAnalysis.gapsFilled}
516
+ - Questions Raised: ${previousAnalysis.questionsRaised}
517
+ - Questions Answered: ${previousAnalysis.questionsAnswered}
518
+ - Coverage Score: ${previousAnalysis.coverageScore.toFixed(1)}%
519
+
520
+ Focus on NEW gaps and questions not addressed in previous iterations.
521
+ ` : "";
338
522
  let specificInstructions = "";
339
523
  switch (agent.type) {
524
+ case "coverage":
525
+ specificInstructions = `
526
+ Focus on directory structure and MOC (Map of Content) files:
527
+
528
+ 1. **Directory Analysis**: Review each directory and its MOC file status
529
+ 2. **Empty/Stub MOCs**: Identify MOC files that are empty or just stubs
530
+ 3. **Missing MOCs**: Identify directories that need MOC files
531
+ 4. **Documentation Needs**: For each directory, determine what documentation is needed
532
+ 5. **Not Needed**: If a directory genuinely doesn't need documentation, explain why
533
+
534
+ For each directory needing work:
535
+ - State the directory path
536
+ - Current MOC status (missing/empty/stub/complete)
537
+ - What documentation should be added
538
+ - Priority (high/medium/low)
539
+ - Suggested content or links to include
540
+
541
+ The goal is 100% documentation coverage - every directory should either:
542
+ 1. Have a complete MOC with links to contents
543
+ 2. Have documentation explaining why it doesn't need more docs
544
+ 3. Be marked for future documentation
545
+
546
+ ## Directory Coverage Status
547
+ ${coverageSummary}`;
548
+ break;
340
549
  case "vision":
341
550
  specificInstructions = `
342
551
  Focus on:
@@ -356,11 +565,16 @@ Identify:
356
565
  3. Outdated information (anything that seems inconsistent?)
357
566
  4. Missing examples or use cases
358
567
  5. Unclear terminology or concepts that need definitions
568
+ 6. Empty or stub MOC files that need content (see Directory Coverage below)
359
569
 
360
570
  For each gap, specify:
361
571
  - What is missing
362
- - Where it should be documented
363
- - Why it's important`;
572
+ - Where it should be documented (specific file path)
573
+ - Why it's important
574
+ - Priority (high/medium/low)
575
+
576
+ ## Directory Coverage Status
577
+ ${coverageSummary}`;
364
578
  break;
365
579
  case "research":
366
580
  specificInstructions = `
@@ -392,7 +606,7 @@ Also identify concepts that should be linked but aren't currently.`;
392
606
  break;
393
607
  }
394
608
  return `You are a documentation analyst helping to cultivate a knowledge graph.
395
-
609
+ ${iterationContext}
396
610
  ## Your Task
397
611
  ${agent.task}
398
612
 
@@ -414,9 +628,11 @@ Provide your analysis in markdown format with:
414
628
  3. Specific recommendations (prefix with "Recommendation:")
415
629
  4. Key findings (prefix with "Finding:")
416
630
  5. Research questions where applicable (prefix with "Question:")
631
+ 6. Priority levels (high/medium/low) for actionable items
417
632
 
418
633
  Reference specific documents using [[document-name]] wiki-link format where relevant.
419
- Be specific and actionable in your analysis.`;
634
+ Be specific and actionable in your analysis.
635
+ ${previousAnalysis ? "\nFocus on NEW items not identified in previous iterations." : ""}`;
420
636
  }
421
637
  /**
422
638
  * Run analysis using Claude CLI
@@ -484,7 +700,7 @@ Be specific and actionable in your analysis.`;
484
700
  try {
485
701
  const { GoogleGenerativeAI } = await import("../node_modules/@google/generative-ai/dist/index.js");
486
702
  const genAI = new GoogleGenerativeAI(apiKey);
487
- const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
703
+ const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
488
704
  const result = await model.generateContent(prompt);
489
705
  const response = result.response;
490
706
  const text = response.text();
@@ -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 * 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 * 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\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 logger.info('Found documentation', { documents: documents.length, keyDocs: keyDocs.size });\n\n // Define documentation cultivation agents\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: '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' });\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 );\n result.results.push(agentResult);\n }\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 ): 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);\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 context-aware prompt for documentation cultivation\n */\n private buildPrompt(agent: AgentConfig, documents: DocMetadata[], keyDocs: Map<string, string>): 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 // Agent-specific instructions\n let specificInstructions = '';\n switch (agent.type) {\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\n\nFor each gap, specify:\n- What is missing\n- Where it should be documented\n- Why it's important`;\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\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:\")\n\nReference specific documents using [[document-name]] wiki-link format where relevant.\nBe specific and actionable in your analysis.`;\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.0-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":";;;;AAmBA,MAAM,SAAS,aAAa,eAAe;AAoGpC,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;AAClC,SAAK,eAAe,QAAQ,gBAAgB;AAE5C,SAAK,eAAe,QAAQ,gBAAgB;AAC5C,SAAK,cAAc,QAAQ,e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;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;"}
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"],"names":[],"mappings":";;;;AAmBA,MAAM,SAAS,aAAa,eAAe;AAgIpC,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,UAA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AAO;AAC1B,cAAM,IAAI,MAAM,2BAA2B,MAAM,OAAO,EAAE;AAAA,MAC5D;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,gBAAgB,QAA0B;AAChD,UAAM,WAAqB,CAAA;AAE3B,UAAM,WAAW;AAAA,MACf;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAGF,eAAW,WAAW,UAAU;AAC9B,YAAM,UAAU,OAAO,SAAS,OAAO;AACvC,iBAAW,SAAS,SAAS;AAC3B,YAAI,MAAM,CAAC,GAAG;AACZ,mBAAS,KAAK,MAAM,CAAC,EAAE,MAAM;AAAA,QAC/B;AAAA,MACF;AAAA,IACF;AAEA,WAAO,CAAC,GAAG,IAAI,IAAI,QAAQ,CAAC;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA,EAKQ,aAAa,OAAoB,QAAgB,MAAsB;AAC7E,UAAM,aAAY,oBAAI,KAAA,GAAO,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;"}
@@ -114,6 +114,10 @@ export declare class MigrationOrchestrator {
114
114
  * Parse documentation gaps file
115
115
  */
116
116
  private parseGapsFile;
117
+ /**
118
+ * Escape special regex characters in a string
119
+ */
120
+ private escapeRegex;
117
121
  /**
118
122
  * Parse research questions file
119
123
  */
@@ -158,6 +162,12 @@ export declare class MigrationOrchestrator {
158
162
  * Build prompt for agent
159
163
  */
160
164
  private buildAgentPrompt;
165
+ /**
166
+ * Select the best model based on task complexity
167
+ * - Research and gap-filling tasks use the most capable model
168
+ * - Simpler tasks use faster models
169
+ */
170
+ private selectGeminiModel;
161
171
  /**
162
172
  * Call AI (Gemini or fallback)
163
173
  */
@@ -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,oBAAo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AO,CAAC,aAAa;IAmDrB;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAkC1B;;OAEG;IACH,OAAO,CAAC,oBAAoB;IA6B5B;;OAEG;YACW,eAAe;IA6B7B;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAuF7B;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAmC7B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAwC9B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAgD9B;;OAEG;IACH,OAAO,CAAC,qBAAqB;IA2B7B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAgC9B;;OAEG;YACW,YAAY;IA4B1B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAwCxB;;OAEG;YACW,MAAM;IAiCpB;;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;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,CAA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AO,CAAC,aAAa;IAerB;;OAEG;IACH,OAAO,CAAC,GAAG;CAQZ;AAED,YAAY,EAAE,eAAe,EAAE,mBAAmB,EAAE,cAAc,EAAE,CAAC"}
@@ -213,6 +213,12 @@ class MigrationOrchestrator {
213
213
  }
214
214
  return gaps;
215
215
  }
216
+ /**
217
+ * Escape special regex characters in a string
218
+ */
219
+ escapeRegex(str) {
220
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
221
+ }
216
222
  /**
217
223
  * Parse research questions file
218
224
  */
@@ -222,11 +228,13 @@ class MigrationOrchestrator {
222
228
  for (const match of questionMatches) {
223
229
  const questionText = match[1].replace(/^Question:\s*/, "").trim();
224
230
  const context = match[2].trim();
225
- const importanceMatch = content.match(new RegExp(`${questionText.slice(0, 50)}[\\s\\S]*?\\*\\*Importance:\\*\\*\\s*([^\\n]+)`));
231
+ const safeQuestionShort = this.escapeRegex(questionText.slice(0, 50));
232
+ const safeQuestionVeryShort = this.escapeRegex(questionText.slice(0, 30));
233
+ const importanceMatch = content.match(new RegExp(`${safeQuestionShort}[\\s\\S]*?\\*\\*Importance:\\*\\*\\s*([^\\n]+)`));
226
234
  const importance = importanceMatch ? importanceMatch[1].trim() : "";
227
- const resourcesMatch = content.match(new RegExp(`${questionText.slice(0, 50)}[\\s\\S]*?\\*\\*Suggested Resources:\\*\\*\\s*([^\\n]+)`));
235
+ const resourcesMatch = content.match(new RegExp(`${safeQuestionShort}[\\s\\S]*?\\*\\*Suggested Resources:\\*\\*\\s*([^\\n]+)`));
228
236
  const resources = resourcesMatch ? resourcesMatch[1].split(",").map((r) => r.trim()) : [];
229
- const categoryMatch = content.match(new RegExp(`### \\d+\\. ([^\\n]+)[\\s\\S]*?${questionText.slice(0, 30)}`));
237
+ const categoryMatch = content.match(new RegExp(`### \\d+\\. ([^\\n]+)[\\s\\S]*?${safeQuestionVeryShort}`));
230
238
  const category = categoryMatch ? categoryMatch[1].trim() : "General";
231
239
  questions.push({
232
240
  question: questionText,
@@ -554,7 +562,7 @@ ${q.question}
554
562
  async executeAgent(agent, analysis, docsContext) {
555
563
  this.log("info", `Executing agent: ${agent.name}`, { type: agent.type });
556
564
  const prompt = this.buildAgentPrompt(agent);
557
- const response = await this.callAI(prompt);
565
+ const response = await this.callAI(prompt, agent.type);
558
566
  if (!response) {
559
567
  throw new Error("No response from AI");
560
568
  }
@@ -604,17 +612,42 @@ Your researched answer with [[citations]]
604
612
  \`\`\`
605
613
  `;
606
614
  }
615
+ /**
616
+ * Select the best model based on task complexity
617
+ * - Research and gap-filling tasks use the most capable model
618
+ * - Simpler tasks use faster models
619
+ */
620
+ selectGeminiModel(agentType) {
621
+ const complexTasks = ["gap-filler", "researcher"];
622
+ if (complexTasks.includes(agentType)) {
623
+ return "gemini-2.5-pro";
624
+ }
625
+ return "gemini-2.5-flash";
626
+ }
607
627
  /**
608
628
  * Call AI (Gemini or fallback)
609
629
  */
610
- async callAI(prompt) {
630
+ async callAI(prompt, agentType) {
611
631
  if (this.geminiClient) {
632
+ const modelName = this.selectGeminiModel(agentType);
612
633
  try {
613
- const model = this.geminiClient.getGenerativeModel({ model: "gemini-2.0-flash" });
634
+ this.log("info", `Using model: ${modelName}`, { agentType });
635
+ const model = this.geminiClient.getGenerativeModel({ model: modelName });
614
636
  const result = await model.generateContent(prompt);
615
637
  return result.response.text();
616
638
  } catch (error) {
617
- this.log("error", "Gemini API call failed", { error: String(error) });
639
+ if (modelName !== "gemini-2.5-flash") {
640
+ this.log("warn", `${modelName} failed, falling back to gemini-2.5-flash`, { error: String(error) });
641
+ try {
642
+ const fallbackModel = this.geminiClient.getGenerativeModel({ model: "gemini-2.5-flash" });
643
+ const result = await fallbackModel.generateContent(prompt);
644
+ return result.response.text();
645
+ } catch (fallbackError) {
646
+ this.log("error", "Gemini fallback also failed", { error: String(fallbackError) });
647
+ }
648
+ } else {
649
+ this.log("error", "Gemini API call failed", { error: String(error) });
650
+ }
618
651
  return null;
619
652
  }
620
653
  }
@@ -622,8 +655,10 @@ Your researched answer with [[citations]]
622
655
  try {
623
656
  const { default: Anthropic } = await import("@anthropic-ai/sdk");
624
657
  const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
658
+ const complexTasks = ["gap-filler", "researcher"];
659
+ const model = complexTasks.includes(agentType) ? "claude-sonnet-4-20250514" : "claude-sonnet-4-20250514";
625
660
  const message = await client.messages.create({
626
- model: "claude-sonnet-4-20250514",
661
+ model,
627
662
  max_tokens: 8e3,
628
663
  messages: [{ role: "user", content: prompt }]
629
664
  });
@@ -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 * 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 // Extract importance\n const importanceMatch = content.match(new RegExp(`${questionText.slice(0, 50)}[\\\\s\\\\S]*?\\\\*\\\\*Importance:\\\\*\\\\*\\\\s*([^\\\\n]+)`));\n const importance = importanceMatch ? importanceMatch[1].trim() : '';\n\n // Extract suggested resources\n const resourcesMatch = content.match(new RegExp(`${questionText.slice(0, 50)}[\\\\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]*?${questionText.slice(0, 30)}`));\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 content',\n context: this.buildGapFillerContext(highPriorityGaps, docsContext),\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',\n context: this.buildGapFillerContext(mediumPriorityGaps, docsContext)\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 proper structure and links',\n context: this.buildMOCBuilderContext(mocGaps, docsContext)\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 // 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 * Build context for gap filler agent\n */\n private buildGapFillerContext(gaps: DocumentationGap[], docsContext: Map<string, string>): string {\n let 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 += 'For each gap, create comprehensive documentation that:\\n';\n context += '1. Addresses the specific issue identified\\n';\n context += '2. Follows the existing documentation style\\n';\n context += '3. Includes proper wiki-links [[like-this]]\\n';\n context += '4. Has appropriate frontmatter (title, type, tags)\\n';\n context += '5. Integrates with existing documentation structure\\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(gaps: DocumentationGap[], docsContext: Map<string, string>): string {\n let 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\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 }\n\n context += '\\n## Instructions\\n';\n context += 'For each empty/stub MOC file:\\n';\n context += '1. Create a proper introduction for the section\\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 descriptions for each linked document\\n';\n context += '5. Include navigation links to parent/sibling MOCs\\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);\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 * Call AI (Gemini or fallback)\n */\n private async callAI(prompt: string): Promise<string | null> {\n if (this.geminiClient) {\n try {\n const model = this.geminiClient.getGenerativeModel({ model: 'gemini-2.0-flash' });\n const result = await model.generateContent(prompt);\n return result.response.text();\n } catch (error) {\n this.log('error', 'Gemini API call failed', { error: String(error) });\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 const message = await client.messages.create({\n model: 'claude-sonnet-4-20250514',\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,mBAAA;AAAA,IACpC;AAGA,QAAI,QAAQ,IAAI,mBAAmB;AACjC,aAAO,EAAE,WAAW,MAAM,QAAQ,sBAAA;AAAA,IACpC;AAEA,WAAO;AAAA,MACL,WAAW;AAAA,MACX,QAAQ;AAAA,IAAA;AAAA,EAEZ;AAAA;AAAA;A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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// 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 content',\n context: this.buildGapFillerContext(highPriorityGaps, docsContext),\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',\n context: this.buildGapFillerContext(mediumPriorityGaps, docsContext)\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 proper structure and links',\n context: this.buildMOCBuilderContext(mocGaps, docsContext)\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 // 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 * Build context for gap filler agent\n */\n private buildGapFillerContext(gaps: DocumentationGap[], docsContext: Map<string, string>): string {\n let 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 += 'For each gap, create comprehensive documentation that:\\n';\n context += '1. Addresses the specific issue identified\\n';\n context += '2. Follows the existing documentation style\\n';\n context += '3. Includes proper wiki-links [[like-this]]\\n';\n context += '4. Has appropriate frontmatter (title, type, tags)\\n';\n context += '5. Integrates with existing documentation structure\\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(gaps: DocumentationGap[], docsContext: Map<string, string>): string {\n let 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\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 }\n\n context += '\\n## Instructions\\n';\n context += 'For each empty/stub MOC file:\\n';\n context += '1. Create a proper introduction for the section\\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 descriptions for each linked document\\n';\n context += '5. Include navigation links to parent/sibling MOCs\\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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,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;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weavelogic/knowledge-graph-agent",
3
- "version": "0.11.0",
3
+ "version": "0.11.2",
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",