This is page 27 of 29. Use http://codebase.md/tosin2013/documcp?lines=true&page={x} to view the full context.
# Directory Structure
```
├── .dockerignore
├── .eslintignore
├── .eslintrc.json
├── .github
│ ├── agents
│ │ ├── documcp-ast.md
│ │ ├── documcp-deploy.md
│ │ ├── documcp-memory.md
│ │ ├── documcp-test.md
│ │ └── documcp-tool.md
│ ├── copilot-instructions.md
│ ├── dependabot.yml
│ ├── ISSUE_TEMPLATE
│ │ ├── automated-changelog.md
│ │ ├── bug_report.md
│ │ ├── bug_report.yml
│ │ ├── documentation_issue.md
│ │ ├── feature_request.md
│ │ ├── feature_request.yml
│ │ ├── npm-publishing-fix.md
│ │ └── release_improvements.md
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── release-drafter.yml
│ └── workflows
│ ├── auto-merge.yml
│ ├── ci.yml
│ ├── codeql.yml
│ ├── dependency-review.yml
│ ├── deploy-docs.yml
│ ├── README.md
│ ├── release-drafter.yml
│ └── release.yml
├── .gitignore
├── .husky
│ ├── commit-msg
│ └── pre-commit
├── .linkcheck.config.json
├── .markdown-link-check.json
├── .nvmrc
├── .pre-commit-config.yaml
├── .versionrc.json
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── commitlint.config.js
├── CONTRIBUTING.md
├── docker-compose.docs.yml
├── Dockerfile.docs
├── docs
│ ├── .docusaurus
│ │ ├── docusaurus-plugin-content-docs
│ │ │ └── default
│ │ │ └── __mdx-loader-dependency.json
│ │ └── docusaurus-plugin-content-pages
│ │ └── default
│ │ └── __plugin.json
│ ├── adrs
│ │ ├── 001-mcp-server-architecture.md
│ │ ├── 002-repository-analysis-engine.md
│ │ ├── 003-static-site-generator-recommendation-engine.md
│ │ ├── 004-diataxis-framework-integration.md
│ │ ├── 005-github-pages-deployment-automation.md
│ │ ├── 006-mcp-tools-api-design.md
│ │ ├── 007-mcp-prompts-and-resources-integration.md
│ │ ├── 008-intelligent-content-population-engine.md
│ │ ├── 009-content-accuracy-validation-framework.md
│ │ ├── 010-mcp-resource-pattern-redesign.md
│ │ └── README.md
│ ├── api
│ │ ├── .nojekyll
│ │ ├── assets
│ │ │ ├── hierarchy.js
│ │ │ ├── highlight.css
│ │ │ ├── icons.js
│ │ │ ├── icons.svg
│ │ │ ├── main.js
│ │ │ ├── navigation.js
│ │ │ ├── search.js
│ │ │ └── style.css
│ │ ├── hierarchy.html
│ │ ├── index.html
│ │ ├── modules.html
│ │ └── variables
│ │ └── TOOLS.html
│ ├── assets
│ │ └── logo.svg
│ ├── development
│ │ └── MCP_INSPECTOR_TESTING.md
│ ├── docusaurus.config.js
│ ├── explanation
│ │ ├── architecture.md
│ │ └── index.md
│ ├── guides
│ │ ├── link-validation.md
│ │ ├── playwright-integration.md
│ │ └── playwright-testing-workflow.md
│ ├── how-to
│ │ ├── analytics-setup.md
│ │ ├── custom-domains.md
│ │ ├── documentation-freshness-tracking.md
│ │ ├── github-pages-deployment.md
│ │ ├── index.md
│ │ ├── local-testing.md
│ │ ├── performance-optimization.md
│ │ ├── prompting-guide.md
│ │ ├── repository-analysis.md
│ │ ├── seo-optimization.md
│ │ ├── site-monitoring.md
│ │ ├── troubleshooting.md
│ │ └── usage-examples.md
│ ├── index.md
│ ├── knowledge-graph.md
│ ├── package-lock.json
│ ├── package.json
│ ├── phase-2-intelligence.md
│ ├── reference
│ │ ├── api-overview.md
│ │ ├── cli.md
│ │ ├── configuration.md
│ │ ├── deploy-pages.md
│ │ ├── index.md
│ │ ├── mcp-tools.md
│ │ └── prompt-templates.md
│ ├── research
│ │ ├── cross-domain-integration
│ │ │ └── README.md
│ │ ├── domain-1-mcp-architecture
│ │ │ ├── index.md
│ │ │ └── mcp-performance-research.md
│ │ ├── domain-2-repository-analysis
│ │ │ └── README.md
│ │ ├── domain-3-ssg-recommendation
│ │ │ ├── index.md
│ │ │ └── ssg-performance-analysis.md
│ │ ├── domain-4-diataxis-integration
│ │ │ └── README.md
│ │ ├── domain-5-github-deployment
│ │ │ ├── github-pages-security-analysis.md
│ │ │ └── index.md
│ │ ├── domain-6-api-design
│ │ │ └── README.md
│ │ ├── README.md
│ │ ├── research-integration-summary-2025-01-14.md
│ │ ├── research-progress-template.md
│ │ └── research-questions-2025-01-14.md
│ ├── robots.txt
│ ├── sidebars.js
│ ├── sitemap.xml
│ ├── src
│ │ └── css
│ │ └── custom.css
│ └── tutorials
│ ├── development-setup.md
│ ├── environment-setup.md
│ ├── first-deployment.md
│ ├── getting-started.md
│ ├── index.md
│ ├── memory-workflows.md
│ └── user-onboarding.md
├── jest.config.js
├── LICENSE
├── Makefile
├── MCP_PHASE2_IMPLEMENTATION.md
├── mcp-config-example.json
├── mcp.json
├── package-lock.json
├── package.json
├── README.md
├── release.sh
├── scripts
│ └── check-package-structure.cjs
├── SECURITY.md
├── setup-precommit.sh
├── src
│ ├── benchmarks
│ │ └── performance.ts
│ ├── index.ts
│ ├── memory
│ │ ├── contextual-retrieval.ts
│ │ ├── deployment-analytics.ts
│ │ ├── enhanced-manager.ts
│ │ ├── export-import.ts
│ │ ├── freshness-kg-integration.ts
│ │ ├── index.ts
│ │ ├── integration.ts
│ │ ├── kg-code-integration.ts
│ │ ├── kg-health.ts
│ │ ├── kg-integration.ts
│ │ ├── kg-link-validator.ts
│ │ ├── kg-storage.ts
│ │ ├── knowledge-graph.ts
│ │ ├── learning.ts
│ │ ├── manager.ts
│ │ ├── multi-agent-sharing.ts
│ │ ├── pruning.ts
│ │ ├── schemas.ts
│ │ ├── storage.ts
│ │ ├── temporal-analysis.ts
│ │ ├── user-preferences.ts
│ │ └── visualization.ts
│ ├── prompts
│ │ └── technical-writer-prompts.ts
│ ├── scripts
│ │ └── benchmark.ts
│ ├── templates
│ │ └── playwright
│ │ ├── accessibility.spec.template.ts
│ │ ├── Dockerfile.template
│ │ ├── docs-e2e.workflow.template.yml
│ │ ├── link-validation.spec.template.ts
│ │ └── playwright.config.template.ts
│ ├── tools
│ │ ├── analyze-deployments.ts
│ │ ├── analyze-readme.ts
│ │ ├── analyze-repository.ts
│ │ ├── check-documentation-links.ts
│ │ ├── deploy-pages.ts
│ │ ├── detect-gaps.ts
│ │ ├── evaluate-readme-health.ts
│ │ ├── generate-config.ts
│ │ ├── generate-contextual-content.ts
│ │ ├── generate-llm-context.ts
│ │ ├── generate-readme-template.ts
│ │ ├── generate-technical-writer-prompts.ts
│ │ ├── kg-health-check.ts
│ │ ├── manage-preferences.ts
│ │ ├── manage-sitemap.ts
│ │ ├── optimize-readme.ts
│ │ ├── populate-content.ts
│ │ ├── readme-best-practices.ts
│ │ ├── recommend-ssg.ts
│ │ ├── setup-playwright-tests.ts
│ │ ├── setup-structure.ts
│ │ ├── sync-code-to-docs.ts
│ │ ├── test-local-deployment.ts
│ │ ├── track-documentation-freshness.ts
│ │ ├── update-existing-documentation.ts
│ │ ├── validate-content.ts
│ │ ├── validate-documentation-freshness.ts
│ │ ├── validate-readme-checklist.ts
│ │ └── verify-deployment.ts
│ ├── types
│ │ └── api.ts
│ ├── utils
│ │ ├── ast-analyzer.ts
│ │ ├── code-scanner.ts
│ │ ├── content-extractor.ts
│ │ ├── drift-detector.ts
│ │ ├── freshness-tracker.ts
│ │ ├── language-parsers-simple.ts
│ │ ├── permission-checker.ts
│ │ └── sitemap-generator.ts
│ └── workflows
│ └── documentation-workflow.ts
├── test-docs-local.sh
├── tests
│ ├── api
│ │ └── mcp-responses.test.ts
│ ├── benchmarks
│ │ └── performance.test.ts
│ ├── edge-cases
│ │ └── error-handling.test.ts
│ ├── functional
│ │ └── tools.test.ts
│ ├── integration
│ │ ├── kg-documentation-workflow.test.ts
│ │ ├── knowledge-graph-workflow.test.ts
│ │ ├── mcp-readme-tools.test.ts
│ │ ├── memory-mcp-tools.test.ts
│ │ ├── readme-technical-writer.test.ts
│ │ └── workflow.test.ts
│ ├── memory
│ │ ├── contextual-retrieval.test.ts
│ │ ├── enhanced-manager.test.ts
│ │ ├── export-import.test.ts
│ │ ├── freshness-kg-integration.test.ts
│ │ ├── kg-code-integration.test.ts
│ │ ├── kg-health.test.ts
│ │ ├── kg-link-validator.test.ts
│ │ ├── kg-storage-validation.test.ts
│ │ ├── kg-storage.test.ts
│ │ ├── knowledge-graph-enhanced.test.ts
│ │ ├── knowledge-graph.test.ts
│ │ ├── learning.test.ts
│ │ ├── manager-advanced.test.ts
│ │ ├── manager.test.ts
│ │ ├── mcp-resource-integration.test.ts
│ │ ├── mcp-tool-persistence.test.ts
│ │ ├── schemas.test.ts
│ │ ├── storage.test.ts
│ │ ├── temporal-analysis.test.ts
│ │ └── user-preferences.test.ts
│ ├── performance
│ │ ├── memory-load-testing.test.ts
│ │ └── memory-stress-testing.test.ts
│ ├── prompts
│ │ ├── guided-workflow-prompts.test.ts
│ │ └── technical-writer-prompts.test.ts
│ ├── server.test.ts
│ ├── setup.ts
│ ├── tools
│ │ ├── all-tools.test.ts
│ │ ├── analyze-coverage.test.ts
│ │ ├── analyze-deployments.test.ts
│ │ ├── analyze-readme.test.ts
│ │ ├── analyze-repository.test.ts
│ │ ├── check-documentation-links.test.ts
│ │ ├── deploy-pages-kg-retrieval.test.ts
│ │ ├── deploy-pages-tracking.test.ts
│ │ ├── deploy-pages.test.ts
│ │ ├── detect-gaps.test.ts
│ │ ├── evaluate-readme-health.test.ts
│ │ ├── generate-contextual-content.test.ts
│ │ ├── generate-llm-context.test.ts
│ │ ├── generate-readme-template.test.ts
│ │ ├── generate-technical-writer-prompts.test.ts
│ │ ├── kg-health-check.test.ts
│ │ ├── manage-sitemap.test.ts
│ │ ├── optimize-readme.test.ts
│ │ ├── readme-best-practices.test.ts
│ │ ├── recommend-ssg-historical.test.ts
│ │ ├── recommend-ssg-preferences.test.ts
│ │ ├── recommend-ssg.test.ts
│ │ ├── simple-coverage.test.ts
│ │ ├── sync-code-to-docs.test.ts
│ │ ├── test-local-deployment.test.ts
│ │ ├── tool-error-handling.test.ts
│ │ ├── track-documentation-freshness.test.ts
│ │ ├── validate-content.test.ts
│ │ ├── validate-documentation-freshness.test.ts
│ │ └── validate-readme-checklist.test.ts
│ ├── types
│ │ └── type-safety.test.ts
│ └── utils
│ ├── ast-analyzer.test.ts
│ ├── content-extractor.test.ts
│ ├── drift-detector.test.ts
│ ├── freshness-tracker.test.ts
│ └── sitemap-generator.test.ts
├── tsconfig.json
└── typedoc.json
```
# Files
--------------------------------------------------------------------------------
/src/tools/populate-content.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { Tool } from "@modelcontextprotocol/sdk/types.js";
2 | import * as fs from "fs/promises";
3 | import * as path from "path";
4 | import {
5 | handleMemoryRecall,
6 | handleMemoryEnhancedRecommendation,
7 | handleMemoryIntelligentAnalysis,
8 | } from "../memory/index.js";
9 |
10 | interface PopulationOptions {
11 | analysisId: string;
12 | docsPath: string;
13 | populationLevel: "basic" | "comprehensive" | "intelligent";
14 | includeProjectSpecific: boolean;
15 | preserveExisting: boolean;
16 | technologyFocus?: string[];
17 | }
18 |
19 | interface TutorialContent {
20 | title: string;
21 | description: string;
22 | content: string;
23 | codeExamples?: string[];
24 | }
25 |
26 | interface ContentPlan {
27 | tutorials: TutorialContent[];
28 | howToGuides: any[];
29 | reference: any[];
30 | explanation: any[];
31 | }
32 |
33 | // ProjectContext interface - currently unused but kept for future enhancements
34 | // interface ProjectContext {
35 | // primaryLanguage: string;
36 | // frameworks: any[];
37 | // testingFrameworks: any[];
38 | // dependencies: any;
39 | // devopsTools?: DevOpsToolProfile;
40 | // }
41 |
42 | interface DevOpsToolProfile {
43 | containerization: ContainerTechnology[];
44 | orchestration: OrchestrationTechnology[];
45 | cicd: CICDTechnology[];
46 | configuration: ConfigManagementTechnology[];
47 | monitoring: MonitoringTechnology[];
48 | security: SecurityTechnology[];
49 | }
50 |
51 | interface ContainerTechnology {
52 | name: string;
53 | version?: string;
54 | configFiles: string[];
55 | usage: string;
56 | }
57 |
58 | interface OrchestrationTechnology {
59 | name: string;
60 | manifests?: string[];
61 | resources?: string[];
62 | namespaces?: string[];
63 | }
64 |
65 | interface CICDTechnology {
66 | name: string;
67 | pipelines?: string[];
68 | tasks?: string[];
69 | triggers?: string[];
70 | }
71 |
72 | interface ConfigManagementTechnology {
73 | name: string;
74 | playbooks?: string[];
75 | roles?: string[];
76 | inventory?: string[];
77 | vaultFiles?: string[];
78 | }
79 |
80 | interface MonitoringTechnology {
81 | name: string;
82 | }
83 |
84 | interface SecurityTechnology {
85 | name: string;
86 | }
87 |
88 | // Interfaces for future extensibility
89 | // interface LanguageContentGenerator {
90 | // detectFrameworks(analysis: any): any[];
91 | // generateContent(frameworks: any[], context: ProjectContext): any;
92 | // }
93 |
94 | // interface DevOpsContentGenerator {
95 | // detectDevOpsTools(analysis: any): DevOpsToolProfile;
96 | // generateDevOpsContent(tools: DevOpsToolProfile, context: ProjectContext): any;
97 | // }
98 |
99 | interface PopulationResult {
100 | success: boolean;
101 | filesCreated: number;
102 | contentPlan: ContentPlan;
103 | populationMetrics: {
104 | coverage: number;
105 | completeness: number;
106 | projectSpecificity: number;
107 | };
108 | nextSteps: string[];
109 | }
110 |
111 | class ContentPopulationEngine {
112 | private analysisCache: Map<string, any> = new Map();
113 | private memoryInsights: any = null;
114 | private similarProjects: any[] = [];
115 |
116 | async populateContent(
117 | options: PopulationOptions,
118 | context?: any,
119 | ): Promise<PopulationResult> {
120 | // Report initial progress
121 | if (context?.meta?.progressToken) {
122 | await context.meta.reportProgress?.({ progress: 0, total: 100 });
123 | }
124 |
125 | await context?.info?.("📝 Starting Diataxis content population...");
126 |
127 | // 1. Retrieve and validate repository analysis
128 | await context?.info?.("📊 Retrieving repository analysis...");
129 | const analysis = await this.getRepositoryAnalysis(options.analysisId);
130 |
131 | if (context?.meta?.progressToken) {
132 | await context.meta.reportProgress?.({ progress: 20, total: 100 });
133 | }
134 |
135 | // 2. Get memory-enhanced insights for intelligent content generation
136 | await context?.info?.(
137 | "🧠 Loading memory insights for intelligent generation...",
138 | );
139 | await this.loadMemoryInsights(analysis, options);
140 |
141 | if (context?.meta?.progressToken) {
142 | await context.meta.reportProgress?.({ progress: 40, total: 100 });
143 | }
144 |
145 | // 3. Generate content plan based on project characteristics AND memory insights
146 | await context?.info?.("🗺️ Generating intelligent content plan...");
147 | const contentPlan = await this.generateIntelligentContentPlan(
148 | analysis,
149 | options.populationLevel,
150 | this.memoryInsights,
151 | );
152 |
153 | // 4. Generate memory-informed content for each Diataxis category
154 | const tutorials = await this.generateMemoryInformedTutorialContent(
155 | contentPlan.tutorials,
156 | analysis,
157 | this.memoryInsights,
158 | );
159 | const howTos = await this.generateMemoryInformedHowToContent(
160 | contentPlan.howToGuides,
161 | analysis,
162 | this.memoryInsights,
163 | );
164 | const reference = await this.generateMemoryInformedReferenceContent(
165 | contentPlan.reference,
166 | analysis,
167 | this.memoryInsights,
168 | );
169 | const explanation = await this.generateMemoryInformedExplanationContent(
170 | contentPlan.explanation,
171 | analysis,
172 | this.memoryInsights,
173 | );
174 |
175 | // 5. Write content to documentation structure
176 | const filesCreated = await this.writeContentToStructure(
177 | options.docsPath,
178 | { tutorials, howTos, reference, explanation },
179 | options.preserveExisting,
180 | );
181 |
182 | // 6. Generate cross-references and navigation updates
183 | await context?.info?.("🔗 Generating cross-references and navigation...");
184 | await this.updateNavigationAndCrossReferences(
185 | options.docsPath,
186 | contentPlan,
187 | );
188 |
189 | if (context?.meta?.progressToken) {
190 | await context.meta.reportProgress?.({ progress: 100, total: 100 });
191 | }
192 |
193 | await context?.info?.(
194 | `✅ Content population complete! Generated ${filesCreated} file(s)`,
195 | );
196 |
197 | return {
198 | success: true,
199 | filesCreated,
200 | contentPlan,
201 | populationMetrics: this.calculatePopulationMetrics(
202 | filesCreated,
203 | contentPlan,
204 | ),
205 | nextSteps: this.generateMemoryInformedNextSteps(
206 | analysis,
207 | contentPlan,
208 | this.memoryInsights,
209 | ),
210 | };
211 | }
212 |
213 | private async getRepositoryAnalysis(analysisId: string): Promise<any> {
214 | // First try to get analysis from memory system
215 | try {
216 | const memoryRecall = await this.getFromMemorySystem(analysisId);
217 | if (memoryRecall) {
218 | return memoryRecall;
219 | }
220 | } catch (error) {
221 | console.warn("Failed to retrieve from memory system:", error);
222 | }
223 |
224 | // Fallback to reading from cached analysis file
225 | const analysisPath = path.join(
226 | ".documcp",
227 | "analyses",
228 | `${analysisId}.json`,
229 | );
230 | try {
231 | const content = await fs.readFile(analysisPath, "utf-8");
232 | return JSON.parse(content);
233 | } catch {
234 | throw new Error(
235 | `Repository analysis with ID '${analysisId}' not found. Please run analyze_repository first.`,
236 | );
237 | }
238 | }
239 |
240 | private async getFromMemorySystem(analysisId: string): Promise<any> {
241 | try {
242 | const result = await handleMemoryRecall({
243 | query: analysisId,
244 | type: "analysis",
245 | limit: 1,
246 | });
247 |
248 | // Handle the memory recall result structure
249 | if (result && result.memories && result.memories.length > 0) {
250 | const memory = result.memories[0];
251 |
252 | // Handle wrapped content structure
253 | if (
254 | memory.data &&
255 | memory.data.content &&
256 | Array.isArray(memory.data.content)
257 | ) {
258 | // Extract the JSON from the first text content
259 | const firstContent = memory.data.content[0];
260 | if (
261 | firstContent &&
262 | firstContent.type === "text" &&
263 | firstContent.text
264 | ) {
265 | try {
266 | return JSON.parse(firstContent.text);
267 | } catch (parseError) {
268 | console.warn(
269 | "Failed to parse analysis content from memory:",
270 | parseError,
271 | );
272 | return memory.data;
273 | }
274 | }
275 | }
276 |
277 | // Try direct content access (legacy format)
278 | if (memory.content) {
279 | return memory.content;
280 | }
281 |
282 | // Try data field
283 | if (memory.data) {
284 | return memory.data;
285 | }
286 | }
287 |
288 | return null;
289 | } catch (error) {
290 | console.warn("Memory system recall failed:", error);
291 | return null;
292 | }
293 | }
294 |
295 | private async loadMemoryInsights(
296 | analysis: any,
297 | options: PopulationOptions,
298 | ): Promise<void> {
299 | try {
300 | // Get similar projects from memory system
301 | const similarProjectsQuery = `${
302 | analysis.metadata?.primaryLanguage || ""
303 | } ${analysis.metadata?.ecosystem || ""} documentation`;
304 | const similarProjects = await handleMemoryRecall({
305 | query: similarProjectsQuery,
306 | type: "recommendation",
307 | limit: 5,
308 | });
309 |
310 | // Get memory-enhanced analysis
311 | const enhancedAnalysis = await handleMemoryIntelligentAnalysis({
312 | projectPath: analysis.projectPath || "",
313 | baseAnalysis: analysis,
314 | });
315 |
316 | // Get memory-enhanced recommendations for content strategy
317 | const enhancedRecommendations = await handleMemoryEnhancedRecommendation({
318 | projectPath: analysis.projectPath || "",
319 | baseRecommendation: {
320 | contentStrategy: "diataxis",
321 | populationLevel: options.populationLevel,
322 | },
323 | projectFeatures: {
324 | ecosystem: analysis.metadata?.ecosystem || "unknown",
325 | primaryLanguage: analysis.metadata?.primaryLanguage || "unknown",
326 | complexity: analysis.complexity || "medium",
327 | hasTests: analysis.structure?.hasTests || false,
328 | hasCI: analysis.structure?.hasCI || false,
329 | },
330 | });
331 |
332 | this.memoryInsights = {
333 | similarProjects: similarProjects.memories || [],
334 | enhancedAnalysis: enhancedAnalysis,
335 | enhancedRecommendations: enhancedRecommendations,
336 | patterns: this.extractPatternsFromSimilarProjects(
337 | similarProjects.memories || [],
338 | ),
339 | };
340 |
341 | this.similarProjects = similarProjects.memories || [];
342 | } catch (error) {
343 | console.warn("Failed to load memory insights:", error);
344 | // Fallback to minimal insights
345 | this.memoryInsights = {
346 | similarProjects: [],
347 | enhancedAnalysis: null,
348 | enhancedRecommendations: null,
349 | patterns: {},
350 | };
351 | }
352 | }
353 |
354 | private extractPatternsFromSimilarProjects(projects: any[]): any {
355 | const patterns = {
356 | commonFrameworks: {} as Record<string, number>,
357 | successfulSSGs: {} as Record<string, number>,
358 | documentationStructures: {} as Record<string, number>,
359 | deploymentStrategies: {} as Record<string, number>,
360 | };
361 |
362 | projects.forEach((project) => {
363 | const content = project.content || {};
364 |
365 | // Extract framework patterns
366 | if (content.frameworks) {
367 | content.frameworks.forEach((framework: string) => {
368 | patterns.commonFrameworks[framework] =
369 | (patterns.commonFrameworks[framework] || 0) + 1;
370 | });
371 | }
372 |
373 | // Extract SSG success patterns
374 | if (content.recommendedSSG) {
375 | patterns.successfulSSGs[content.recommendedSSG] =
376 | (patterns.successfulSSGs[content.recommendedSSG] || 0) + 1;
377 | }
378 |
379 | // Extract documentation structure patterns
380 | if (content.documentationApproach) {
381 | patterns.documentationStructures[content.documentationApproach] =
382 | (patterns.documentationStructures[content.documentationApproach] ||
383 | 0) + 1;
384 | }
385 |
386 | // Extract deployment patterns
387 | if (content.deploymentStrategy) {
388 | patterns.deploymentStrategies[content.deploymentStrategy] =
389 | (patterns.deploymentStrategies[content.deploymentStrategy] || 0) + 1;
390 | }
391 | });
392 |
393 | return patterns;
394 | }
395 |
396 | private async generateIntelligentContentPlan(
397 | analysis: any,
398 | level: string,
399 | _memoryInsights: any,
400 | ): Promise<ContentPlan> {
401 | const plan: ContentPlan = {
402 | tutorials: [],
403 | howToGuides: [],
404 | reference: [],
405 | explanation: [],
406 | };
407 |
408 | // Generate tutorials based on project type AND memory patterns
409 | plan.tutorials = this.generateMemoryInformedTutorialPlan(
410 | analysis,
411 | level,
412 | _memoryInsights,
413 | );
414 |
415 | // Generate how-to guides for common tasks (enhanced with successful patterns)
416 | plan.howToGuides = this.generateMemoryInformedHowToPlan(
417 | analysis,
418 | level,
419 | _memoryInsights,
420 | );
421 |
422 | // Generate reference documentation (based on similar project structures)
423 | plan.reference = this.generateMemoryInformedReferencePlan(
424 | analysis,
425 | level,
426 | _memoryInsights,
427 | );
428 |
429 | // Generate explanation content (leveraging successful explanation patterns)
430 | plan.explanation = this.generateMemoryInformedExplanationPlan(
431 | analysis,
432 | level,
433 | _memoryInsights,
434 | );
435 |
436 | return plan;
437 | }
438 |
439 | private generateMemoryInformedTutorialPlan(
440 | analysis: any,
441 | _level: string,
442 | _memoryInsights: any,
443 | ): TutorialContent[] {
444 | const tutorials: TutorialContent[] = [];
445 | const similarProjects = _memoryInsights?.similarProjects || [];
446 | tutorials.push({
447 | title: `Getting Started with ${
448 | analysis.metadata?.projectName || "the Project"
449 | }`,
450 | description: this.generateMemoryInformedDescription(
451 | analysis,
452 | similarProjects,
453 | "getting-started",
454 | ),
455 | content: this.generateMemoryInformedGettingStartedContent(
456 | analysis,
457 | _memoryInsights,
458 | ),
459 | codeExamples: this.generateMemoryInformedGettingStartedExamples(
460 | analysis,
461 | _memoryInsights,
462 | ),
463 | });
464 |
465 | // Add technology-specific tutorials based on what worked for similar projects
466 | const ecosystem =
467 | analysis.metadata?.ecosystem || analysis.technologies?.runtime;
468 | if (
469 | ecosystem === "Node.js" ||
470 | ecosystem === "javascript" ||
471 | ecosystem === "typescript"
472 | ) {
473 | const nodeSuccessPatterns =
474 | this.extractNodeSuccessPatterns(similarProjects);
475 | tutorials.push({
476 | title: this.generateMemoryInformedTutorialTitle(
477 | "environment-setup",
478 | nodeSuccessPatterns,
479 | analysis,
480 | ),
481 | description:
482 | "Configure your development environment based on proven successful patterns",
483 | content: this.generateMemoryInformedNodeSetupContent(
484 | analysis,
485 | nodeSuccessPatterns,
486 | ),
487 | codeExamples: this.generateMemoryInformedNodeSetupExamples(
488 | analysis,
489 | nodeSuccessPatterns,
490 | ),
491 | });
492 | }
493 |
494 | // Add testing tutorial if tests detected
495 | if (analysis.structure.hasTests) {
496 | tutorials.push({
497 | title: "Writing and Running Tests",
498 | description: "Learn how to test your code effectively",
499 | content: this.generateTestingTutorialContent(analysis),
500 | codeExamples: this.generateTestingExamples(analysis),
501 | });
502 | }
503 |
504 | // Add DevOps tutorials based on detected tools
505 | const devopsTools = this.detectDevOpsTools(analysis);
506 | if (devopsTools.containerization.length > 0) {
507 | const containerTech = devopsTools.containerization[0];
508 | tutorials.push({
509 | title: `Containerizing ${analysis.metadata.projectName} with ${containerTech.name}`,
510 | description: `Learn how to containerize your application using ${containerTech.name}`,
511 | content: this.generateContainerTutorialContent(analysis, containerTech),
512 | codeExamples: this.generateContainerExamples(analysis, containerTech),
513 | });
514 | }
515 |
516 | if (devopsTools.orchestration.length > 0) {
517 | const orchestrationTech = devopsTools.orchestration[0];
518 | tutorials.push({
519 | title: `Deploying to ${orchestrationTech.name}`,
520 | description: `Deploy your application to ${orchestrationTech.name}`,
521 | content: this.generateOrchestrationTutorialContent(
522 | analysis,
523 | orchestrationTech,
524 | ),
525 | codeExamples: this.generateOrchestrationExamples(
526 | analysis,
527 | orchestrationTech,
528 | ),
529 | });
530 | }
531 |
532 | // Python-specific tutorials
533 | if (analysis.metadata.primaryLanguage === "Python") {
534 | tutorials.push({
535 | title: "Python Virtual Environment Setup",
536 | description: "Set up isolated Python development environment",
537 | content: this.generatePythonEnvironmentContent(analysis),
538 | codeExamples: this.generatePythonEnvironmentExamples(),
539 | });
540 |
541 | // Python framework-specific tutorials
542 | const pythonFrameworks = this.detectPythonFrameworks(analysis);
543 | pythonFrameworks.forEach((framework) => {
544 | tutorials.push({
545 | title: `Building Applications with ${framework.name}`,
546 | description: `Complete guide to ${framework.name} development`,
547 | content: this.generatePythonFrameworkTutorialContent(
548 | analysis,
549 | framework,
550 | ),
551 | codeExamples: this.generatePythonFrameworkExamples(framework),
552 | });
553 | });
554 | }
555 |
556 | return tutorials;
557 | }
558 |
559 | private generateHowToPlan(analysis: any, _level: string): any[] {
560 | const howTos: any[] = [];
561 |
562 | // Common development tasks
563 | howTos.push({
564 | title: "How to Add a New Feature",
565 | content: this.generateFeatureGuideContent(analysis),
566 | });
567 |
568 | howTos.push({
569 | title: "How to Debug Common Issues",
570 | content: this.generateDebuggingGuideContent(analysis),
571 | });
572 |
573 | // Deployment guides if CI detected
574 | if (analysis.structure.hasCI) {
575 | howTos.push({
576 | title: "How to Deploy Your Application",
577 | content: this.generateDeploymentGuideContent(analysis),
578 | });
579 | }
580 |
581 | return howTos;
582 | }
583 |
584 | private generateReferencePlan(analysis: any, _level: string): any[] {
585 | const reference: any[] = [];
586 |
587 | // API reference
588 | reference.push({
589 | title: "API Reference",
590 | content: this.generateAPIReference(analysis),
591 | });
592 |
593 | // Configuration reference
594 | reference.push({
595 | title: "Configuration Options",
596 | content: this.generateConfigReference(analysis),
597 | });
598 |
599 | // CLI reference if applicable
600 | reference.push({
601 | title: "Command Line Interface",
602 | content: this.generateCLIReference(analysis),
603 | });
604 |
605 | return reference;
606 | }
607 |
608 | private generateExplanationPlan(analysis: any, _level: string): any[] {
609 | const explanations: any[] = [];
610 |
611 | // Architecture overview
612 | explanations.push({
613 | title: "Architecture Overview",
614 | content: this.generateArchitectureContent(analysis),
615 | });
616 |
617 | // Design decisions
618 | explanations.push({
619 | title: "Design Decisions",
620 | content: this.generateDesignDecisionsContent(analysis),
621 | });
622 |
623 | // Technology choices
624 | explanations.push({
625 | title: "Technology Stack",
626 | content: this.generateTechnologyStackContent(analysis),
627 | });
628 |
629 | return explanations;
630 | }
631 |
632 | // Memory-informed helper methods
633 | private getSuccessfulGettingStartedApproach(
634 | similarProjects: any[],
635 | analysis: any,
636 | ): any {
637 | // Analyze successful getting-started approaches from similar projects
638 | const approaches = similarProjects
639 | .filter((p) => p.content?.gettingStartedApproach)
640 | .map((p) => p.content.gettingStartedApproach);
641 |
642 | // Return most common successful approach, or default based on project type
643 | return approaches.length > 0
644 | ? approaches[0]
645 | : this.getDefaultApproachForProjectType(analysis);
646 | }
647 |
648 | private generateMemoryInformedDescription(
649 | analysis: any,
650 | similarProjects: any[],
651 | tutorialType: string,
652 | ): string {
653 | const successfulDescriptions = similarProjects
654 | .filter((p) => p.content?.tutorials?.[tutorialType])
655 | .map((p) => p.content.tutorials[tutorialType].description);
656 |
657 | if (successfulDescriptions.length > 0) {
658 | // Adapt successful pattern for this project
659 | return `Learn ${
660 | analysis.metadata?.primaryLanguage || "development"
661 | } with ${
662 | analysis.metadata?.projectName || "this project"
663 | } using proven patterns from ${
664 | successfulDescriptions.length
665 | } similar successful projects`;
666 | }
667 |
668 | return `Learn ${
669 | analysis.metadata?.primaryLanguage || "development"
670 | } development with ${analysis.metadata?.projectName || "this project"}`;
671 | }
672 |
673 | private extractNodeSuccessPatterns(similarProjects: any[]): any {
674 | const nodeProjects = similarProjects.filter(
675 | (p) =>
676 | p.content?.ecosystem === "Node.js" ||
677 | p.content?.primaryLanguage === "TypeScript" ||
678 | p.content?.primaryLanguage === "JavaScript",
679 | );
680 |
681 | return {
682 | commonTools: this.extractCommonTools(nodeProjects),
683 | successfulCommands: this.extractSuccessfulCommands(nodeProjects),
684 | recommendedVersions: this.extractRecommendedVersions(nodeProjects),
685 | bestPractices: this.extractBestPractices(nodeProjects),
686 | };
687 | }
688 |
689 | private extractCommonTools(projects: any[]): string[] {
690 | const toolCounts: Record<string, number> = {};
691 | projects.forEach((p) => {
692 | (p.content?.tools || []).forEach((tool: string) => {
693 | toolCounts[tool] = (toolCounts[tool] || 0) + 1;
694 | });
695 | });
696 |
697 | // Return tools used by >50% of similar projects
698 | const threshold = Math.ceil(projects.length * 0.5);
699 | return Object.entries(toolCounts)
700 | .filter(([_, count]) => count >= threshold)
701 | .map(([tool, _]) => tool);
702 | }
703 |
704 | private extractSuccessfulCommands(projects: any[]): Record<string, string[]> {
705 | const commands: Record<string, string[]> = {};
706 | projects.forEach((p) => {
707 | if (p.content?.commands) {
708 | Object.entries(p.content.commands).forEach(([key, cmds]) => {
709 | if (!commands[key]) commands[key] = [];
710 | commands[key].push(...(cmds as string[]));
711 | });
712 | }
713 | });
714 |
715 | // Deduplicate and return most common commands
716 | Object.keys(commands).forEach((key) => {
717 | commands[key] = [...new Set(commands[key])];
718 | });
719 |
720 | return commands;
721 | }
722 |
723 | private extractRecommendedVersions(projects: any[]): Record<string, string> {
724 | const versions: Record<string, Record<string, number>> = {};
725 | projects.forEach((p) => {
726 | if (p.content?.versions) {
727 | Object.entries(p.content.versions).forEach(([tool, version]) => {
728 | if (!versions[tool]) versions[tool] = {};
729 | versions[tool][version as string] =
730 | (versions[tool][version as string] || 0) + 1;
731 | });
732 | }
733 | });
734 |
735 | // Return most commonly used versions
736 | const recommendedVersions: Record<string, string> = {};
737 | Object.entries(versions).forEach(([tool, versionCounts]) => {
738 | const mostCommon = Object.entries(versionCounts).sort(
739 | ([, a], [, b]) => (b as number) - (a as number),
740 | )[0];
741 | if (mostCommon) {
742 | recommendedVersions[tool] = mostCommon[0];
743 | }
744 | });
745 |
746 | return recommendedVersions;
747 | }
748 |
749 | private extractBestPractices(projects: any[]): string[] {
750 | const practices: Record<string, number> = {};
751 | projects.forEach((p) => {
752 | (p.content?.bestPractices || []).forEach((practice: string) => {
753 | practices[practice] = (practices[practice] || 0) + 1;
754 | });
755 | });
756 |
757 | // Return practices mentioned by >30% of projects
758 | const threshold = Math.ceil(projects.length * 0.3);
759 | return Object.entries(practices)
760 | .filter(([_, count]) => count >= threshold)
761 | .map(([practice, _]) => practice);
762 | }
763 |
764 | private getDefaultApproachForProjectType(analysis: any): any {
765 | const projectType = analysis.metadata?.projectType || "library";
766 | const primaryLanguage = analysis.metadata?.primaryLanguage || "JavaScript";
767 |
768 | return {
769 | type: projectType,
770 | language: primaryLanguage,
771 | approach: "hands-on",
772 | complexity: "progressive",
773 | };
774 | }
775 |
776 | private generateMemoryInformedTutorialTitle(
777 | tutorialType: string,
778 | patterns: any,
779 | analysis: any,
780 | ): string {
781 | const projectName = analysis.metadata?.projectName || "Project";
782 | const language = analysis.metadata?.primaryLanguage || "Development";
783 |
784 | switch (tutorialType) {
785 | case "environment-setup":
786 | return patterns.commonTools?.length > 0
787 | ? `Setting Up Your ${language} Development Environment`
788 | : `Development Environment Setup for ${projectName}`;
789 | default:
790 | return `${tutorialType} Tutorial for ${projectName}`;
791 | }
792 | }
793 |
794 | // Enhanced content generation methods with memory insights
795 | private generateMemoryInformedGettingStartedContent(
796 | analysis: any,
797 | _memoryInsights: any,
798 | ): string {
799 | const projectName = analysis.metadata?.projectName || "the project";
800 | const language = analysis.metadata?.primaryLanguage || "development";
801 | const patterns = _memoryInsights?.patterns || {};
802 | const similarProjects = _memoryInsights?.similarProjects || [];
803 |
804 | // Extract real project structure and dependencies
805 | const realDependencies = analysis.dependencies?.packages || [];
806 | const hasTests = analysis.structure?.hasTests;
807 | const hasCI = analysis.structure?.hasCI;
808 | const ecosystem = analysis.metadata?.ecosystem || "Node.js";
809 |
810 | // Build getting started content based on actual project characteristics
811 | let content = `# Getting Started with ${projectName}\n\n`;
812 |
813 | if (similarProjects.length > 0) {
814 | content += `Welcome to ${projectName}! This tutorial leverages successful patterns from ${similarProjects.length} similar ${language} projects to get you up and running quickly.\n\n`;
815 | } else {
816 | content += `Welcome to ${projectName}! This tutorial will guide you through setting up and running the project.\n\n`;
817 | }
818 |
819 | // Prerequisites based on actual analysis
820 | content += `## Prerequisites\n\n`;
821 | content += `Based on the project analysis, you'll need:\n\n`;
822 |
823 | if (
824 | ecosystem === "Node.js" ||
825 | language === "TypeScript" ||
826 | language === "JavaScript"
827 | ) {
828 | const recommendedVersion =
829 | this.getRecommendedNodeVersion(similarProjects);
830 | content += `- Node.js (version ${recommendedVersion} or higher)\n`;
831 | content += `- npm or yarn package manager\n`;
832 | }
833 |
834 | if (language === "TypeScript") {
835 | content += `- TypeScript (globally installed or via npx)\n`;
836 | }
837 |
838 | content += `- Git for version control\n\n`;
839 |
840 | // Installation based on real dependencies
841 | content += `## Installation\n\n`;
842 | content += `1. Clone the repository:\n`;
843 | content += ` \`\`\`bash\n`;
844 | content += ` git clone <repository-url>\n`;
845 | content += ` cd ${projectName}\n`;
846 | content += ` \`\`\`\n\n`;
847 |
848 | content += `2. Install dependencies:\n`;
849 | content += ` \`\`\`bash\n`;
850 | if (realDependencies.includes("yarn")) {
851 | content += ` yarn install\n`;
852 | } else {
853 | content += ` npm install\n`;
854 | }
855 | content += ` \`\`\`\n\n`;
856 |
857 | // Real environment setup
858 | if (this.projectHasEnvFile(analysis)) {
859 | content += `3. Set up environment variables:\n`;
860 | content += ` \`\`\`bash\n`;
861 | content += ` cp .env.example .env\n`;
862 | content += ` \`\`\`\n\n`;
863 | }
864 |
865 | // Running based on actual project setup
866 | content += `## Running the Project\n\n`;
867 | const runCommands = this.extractActualRunCommands(analysis);
868 | if (runCommands.length > 0) {
869 | runCommands.forEach((cmd) => {
870 | content += `\`\`\`bash\n${cmd}\n\`\`\`\n\n`;
871 | });
872 | } else {
873 | content += `\`\`\`bash\nnpm start\n\`\`\`\n\n`;
874 | }
875 |
876 | // Testing section based on actual test setup
877 | if (hasTests) {
878 | content += `## Verifying Your Setup\n\n`;
879 | content += `Run the test suite to ensure everything is working:\n`;
880 | content += `\`\`\`bash\n`;
881 | const testFramework = this.detectTestFramework(analysis);
882 | if (testFramework) {
883 | content += `npm test # Uses ${testFramework}\n`;
884 | } else {
885 | content += `npm test\n`;
886 | }
887 | content += `\`\`\`\n\n`;
888 | }
889 |
890 | // Next steps based on memory insights
891 | content += `## Next Steps\n\n`;
892 | if (patterns.documentationStructures) {
893 | content += `- Explore the [Architecture Overview](../explanation/architecture.md)\n`;
894 | content += `- Learn about [Adding New Features](../how-to/add-feature.md)\n`;
895 | }
896 | if (hasCI) {
897 | content += `- Check the [Deployment Guide](../how-to/deploy.md)\n`;
898 | }
899 | content += `- Review the [API Reference](../reference/api.md)\n`;
900 |
901 | return content;
902 | }
903 |
904 | private generateMemoryInformedGettingStartedExamples(
905 | analysis: any,
906 | _memoryInsights: any,
907 | ): string[] {
908 | const examples: string[] = [];
909 |
910 | // Generate real usage example based on actual entry points
911 | const entryPoint = this.findProjectEntryPoint(analysis);
912 | if (entryPoint) {
913 | examples.push(
914 | `// Example: Basic usage\nimport { initialize } from './${entryPoint}';\n\nconst app = initialize({\n // Configuration options\n});\n\napp.start();`,
915 | );
916 | }
917 |
918 | // TypeScript config example if project uses TypeScript
919 | if (analysis.metadata?.primaryLanguage === "TypeScript") {
920 | const actualTsConfig = this.extractTsConfigPatterns(analysis);
921 | examples.push(
922 | `// TypeScript configuration\n${JSON.stringify(
923 | actualTsConfig,
924 | null,
925 | 2,
926 | )}`,
927 | );
928 | }
929 |
930 | // Real package.json scripts
931 | const scripts = this.extractPackageScripts(analysis);
932 | if (scripts && Object.keys(scripts).length > 0) {
933 | examples.push(
934 | `// Available scripts\n${JSON.stringify({ scripts }, null, 2)}`,
935 | );
936 | }
937 |
938 | return examples;
939 | }
940 |
941 | private getRecommendedNodeVersion(similarProjects: any[]): string {
942 | const versions = similarProjects
943 | .map((p) => p.content?.versions?.node)
944 | .filter(Boolean);
945 |
946 | if (versions.length > 0) {
947 | // Return most common version
948 | const versionCounts = versions.reduce(
949 | (acc, v) => {
950 | acc[v] = (acc[v] || 0) + 1;
951 | return acc;
952 | },
953 | {} as Record<string, number>,
954 | );
955 |
956 | const mostCommon = Object.entries(versionCounts).sort(
957 | ([, a], [, b]) => (b as number) - (a as number),
958 | )[0];
959 | return mostCommon ? mostCommon[0] : "18";
960 | }
961 |
962 | return "18"; // Default modern version
963 | }
964 |
965 | private projectHasEnvFile(analysis: any): boolean {
966 | const files = analysis.files || [];
967 | return files.some(
968 | (f: any) =>
969 | f.name === ".env.example" ||
970 | f.name === ".env.template" ||
971 | f.name === "env.example",
972 | );
973 | }
974 |
975 | private extractActualRunCommands(analysis: any): string[] {
976 | const packageJson = this.findPackageJson(analysis);
977 | if (packageJson?.scripts) {
978 | const scripts = packageJson.scripts;
979 | const runCommands = [];
980 |
981 | if (scripts.dev) runCommands.push("npm run dev");
982 | else if (scripts.start) runCommands.push("npm start");
983 | else if (scripts.serve) runCommands.push("npm run serve");
984 |
985 | return runCommands;
986 | }
987 |
988 | return [];
989 | }
990 |
991 | private detectTestFramework(analysis: any): string | null {
992 | const dependencies = analysis.dependencies?.packages || [];
993 |
994 | if (dependencies.includes("jest")) return "Jest";
995 | if (dependencies.includes("mocha")) return "Mocha";
996 | if (dependencies.includes("vitest")) return "Vitest";
997 | if (dependencies.includes("jasmine")) return "Jasmine";
998 |
999 | return null;
1000 | }
1001 |
1002 | private findProjectEntryPoint(analysis: any): string | null {
1003 | const packageJson = this.findPackageJson(analysis);
1004 | if (packageJson?.main) {
1005 | return packageJson.main.replace(/\.(js|ts)$/, "");
1006 | }
1007 |
1008 | // Look for common entry points
1009 | const files = analysis.files || [];
1010 | const entryPoints = ["index", "main", "app", "server"];
1011 |
1012 | for (const entry of entryPoints) {
1013 | if (
1014 | files.some(
1015 | (f: any) => f.name === `${entry}.ts` || f.name === `${entry}.js`,
1016 | )
1017 | ) {
1018 | return entry;
1019 | }
1020 | }
1021 |
1022 | return null;
1023 | }
1024 |
1025 | private findPackageJson(analysis: any): any {
1026 | const files = analysis.files || [];
1027 | const packageFile = files.find((f: any) => f.name === "package.json");
1028 |
1029 | if (packageFile?.content) {
1030 | try {
1031 | return JSON.parse(packageFile.content);
1032 | } catch {
1033 | return null;
1034 | }
1035 | }
1036 |
1037 | return null;
1038 | }
1039 |
1040 | private extractTsConfigPatterns(analysis: any): any {
1041 | const files = analysis.files || [];
1042 | const tsConfigFile = files.find((f: any) => f.name === "tsconfig.json");
1043 |
1044 | if (tsConfigFile?.content) {
1045 | try {
1046 | return JSON.parse(tsConfigFile.content);
1047 | } catch {
1048 | // Return sensible defaults based on project analysis
1049 | return {
1050 | compilerOptions: {
1051 | target: "ES2020",
1052 | module: "commonjs",
1053 | strict: true,
1054 | esModuleInterop: true,
1055 | skipLibCheck: true,
1056 | forceConsistentCasingInFileNames: true,
1057 | },
1058 | };
1059 | }
1060 | }
1061 |
1062 | return null;
1063 | }
1064 |
1065 | private extractPackageScripts(analysis: any): any {
1066 | const packageJson = this.findPackageJson(analysis);
1067 | return packageJson?.scripts || null;
1068 | }
1069 |
1070 | // Content generation methods (keeping original structure but with memory enhancement)
1071 | private generateGettingStartedContent(_analysis: any): string {
1072 | return `# Getting Started with ${_analysis.metadata.projectName}
1073 |
1074 | Welcome to ${_analysis.metadata.projectName}! This tutorial will guide you through setting up and running the project for the first time.
1075 |
1076 | ## Prerequisites
1077 |
1078 | Before you begin, ensure you have the following installed:
1079 |
1080 | - Node.js (version 18 or higher)
1081 | - npm or yarn package manager
1082 | - Git for version control
1083 |
1084 | ## Installation
1085 |
1086 | 1. Clone the repository:
1087 | \`\`\`bash
1088 | git clone <repository-url>
1089 | cd ${_analysis.metadata.projectName}
1090 | \`\`\`
1091 |
1092 | 2. Install dependencies:
1093 | \`\`\`bash
1094 | npm install
1095 | \`\`\`
1096 |
1097 | 3. Set up environment variables:
1098 | \`\`\`bash
1099 | cp .env.example .env
1100 | \`\`\`
1101 |
1102 | ## Running the Project
1103 |
1104 | Start the development server:
1105 | \`\`\`bash
1106 | npm run dev
1107 | \`\`\`
1108 |
1109 | ## Verifying Your Setup
1110 |
1111 | Run the test suite to ensure everything is working:
1112 | \`\`\`bash
1113 | npm test
1114 | \`\`\`
1115 |
1116 | ## Next Steps
1117 |
1118 | - Explore the [Architecture Overview](../explanation/architecture.md)
1119 | - Learn about [Adding New Features](../how-to/add-feature.md)
1120 | - Check the [API Reference](../reference/api.md)
1121 | `;
1122 | }
1123 |
1124 | private generateGettingStartedExamples(_analysis: any): string[] {
1125 | return [
1126 | `// Example: Basic usage
1127 | import { initialize } from './${_analysis.metadata.projectName}';
1128 |
1129 | const app = initialize({
1130 | // Configuration options
1131 | });
1132 |
1133 | app.start();`,
1134 |
1135 | `// Example: TypeScript configuration
1136 | {
1137 | "compilerOptions": {
1138 | "target": "ES2020",
1139 | "module": "commonjs",
1140 | "strict": true,
1141 | "esModuleInterop": true,
1142 | "skipLibCheck": true,
1143 | "forceConsistentCasingInFileNames": true
1144 | }
1145 | }`,
1146 | ];
1147 | }
1148 |
1149 | private generateNodeSetupContent(_analysis: any): string {
1150 | return `# Setting Up Your Development Environment
1151 |
1152 | This guide will help you configure a complete Node.js and TypeScript development environment.
1153 |
1154 | ## Installing Node.js
1155 |
1156 | ### Using Node Version Manager (nvm)
1157 |
1158 | 1. Install nvm:
1159 | \`\`\`bash
1160 | curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
1161 | \`\`\`
1162 |
1163 | 2. Install and use the correct Node.js version:
1164 | \`\`\`bash
1165 | nvm install 18
1166 | nvm use 18
1167 | \`\`\`
1168 |
1169 | ## TypeScript Setup
1170 |
1171 | 1. Install TypeScript globally:
1172 | \`\`\`bash
1173 | npm install -g typescript
1174 | \`\`\`
1175 |
1176 | 2. Initialize TypeScript configuration:
1177 | \`\`\`bash
1178 | npx tsc --init
1179 | \`\`\`
1180 |
1181 | ## Development Tools
1182 |
1183 | ### Recommended VS Code Extensions
1184 |
1185 | - ESLint
1186 | - Prettier
1187 | - TypeScript and JavaScript Language Features
1188 | - GitLens
1189 |
1190 | ### Debugging Configuration
1191 |
1192 | Create a \`.vscode/launch.json\` file:
1193 | \`\`\`json
1194 | {
1195 | "version": "0.2.0",
1196 | "configurations": [
1197 | {
1198 | "type": "node",
1199 | "request": "launch",
1200 | "name": "Debug TypeScript",
1201 | "skipFiles": ["<node_internals>/**"],
1202 | "program": "\${workspaceFolder}/src/index.ts",
1203 | "preLaunchTask": "tsc: build - tsconfig.json",
1204 | "outFiles": ["\${workspaceFolder}/dist/**/*.js"]
1205 | }
1206 | ]
1207 | }
1208 | \`\`\`
1209 | `;
1210 | }
1211 |
1212 | private generateNodeSetupExamples(): string[] {
1213 | return [
1214 | `// package.json scripts
1215 | {
1216 | "scripts": {
1217 | "dev": "ts-node-dev --respawn src/index.ts",
1218 | "build": "tsc",
1219 | "start": "node dist/index.js",
1220 | "test": "jest",
1221 | "lint": "eslint src --ext .ts"
1222 | }
1223 | }`,
1224 | ];
1225 | }
1226 |
1227 | private generateTestingTutorialContent(_analysis: any): string {
1228 | const testFramework = _analysis.technologies.testing?.[0] || "Jest";
1229 |
1230 | return `# Writing and Running Tests
1231 |
1232 | Learn how to write effective tests for your ${_analysis.metadata.projectName} code using ${testFramework}.
1233 |
1234 | ## Test Structure
1235 |
1236 | Tests should follow the AAA pattern:
1237 | - **Arrange**: Set up test data and conditions
1238 | - **Act**: Execute the code being tested
1239 | - **Assert**: Verify the results
1240 |
1241 | ## Writing Your First Test
1242 |
1243 | Create a test file with the \`.test.ts\` extension:
1244 |
1245 | \`\`\`typescript
1246 | // example.test.ts
1247 | describe('Example Module', () => {
1248 | it('should perform expected behavior', () => {
1249 | // Arrange
1250 | const input = 'test';
1251 |
1252 | // Act
1253 | const result = exampleFunction(input);
1254 |
1255 | // Assert
1256 | expect(result).toBe('expected output');
1257 | });
1258 | });
1259 | \`\`\`
1260 |
1261 | ## Running Tests
1262 |
1263 | Execute all tests:
1264 | \`\`\`bash
1265 | npm test
1266 | \`\`\`
1267 |
1268 | Run tests in watch mode:
1269 | \`\`\`bash
1270 | npm test -- --watch
1271 | \`\`\`
1272 |
1273 | ## Test Coverage
1274 |
1275 | Generate a coverage report:
1276 | \`\`\`bash
1277 | npm test -- --coverage
1278 | \`\`\`
1279 |
1280 | ## Best Practices
1281 |
1282 | 1. **Test behavior, not implementation**: Focus on what the code does, not how
1283 | 2. **Keep tests simple**: Each test should verify one thing
1284 | 3. **Use descriptive names**: Test names should explain what is being tested
1285 | 4. **Maintain test independence**: Tests should not depend on each other
1286 | `;
1287 | }
1288 |
1289 | private generateTestingExamples(_analysis: any): string[] {
1290 | return [
1291 | `// Unit test example
1292 | import { calculateTotal } from './calculator';
1293 |
1294 | describe('Calculator', () => {
1295 | describe('calculateTotal', () => {
1296 | it('should sum all numbers correctly', () => {
1297 | const numbers = [1, 2, 3, 4, 5];
1298 | const result = calculateTotal(numbers);
1299 | expect(result).toBe(15);
1300 | });
1301 |
1302 | it('should handle empty arrays', () => {
1303 | const result = calculateTotal([]);
1304 | expect(result).toBe(0);
1305 | });
1306 |
1307 | it('should handle negative numbers', () => {
1308 | const numbers = [-1, -2, 3];
1309 | const result = calculateTotal(numbers);
1310 | expect(result).toBe(0);
1311 | });
1312 | });
1313 | });`,
1314 |
1315 | `// Integration test example
1316 | import request from 'supertest';
1317 | import { app } from './app';
1318 |
1319 | describe('API Endpoints', () => {
1320 | describe('GET /api/health', () => {
1321 | it('should return health status', async () => {
1322 | const response = await request(app)
1323 | .get('/api/health')
1324 | .expect(200);
1325 |
1326 | expect(response.body).toEqual({
1327 | status: 'healthy',
1328 | timestamp: expect.any(String)
1329 | });
1330 | });
1331 | });
1332 | });`,
1333 | ];
1334 | }
1335 |
1336 | private generateFeatureGuideContent(_analysis: any): string {
1337 | return `# How to Add a New Feature
1338 |
1339 | This guide walks you through the process of adding a new feature to ${_analysis.metadata.projectName}.
1340 |
1341 | ## Step 1: Plan Your Feature
1342 |
1343 | Before writing code:
1344 | 1. Define the feature requirements
1345 | 2. Consider the impact on existing functionality
1346 | 3. Plan the implementation approach
1347 |
1348 | ## Step 2: Create a Feature Branch
1349 |
1350 | \`\`\`bash
1351 | git checkout -b feature/your-feature-name
1352 | \`\`\`
1353 |
1354 | ## Step 3: Implement the Feature
1355 |
1356 | 1. Write the core functionality
1357 | 2. Add appropriate error handling
1358 | 3. Include logging for debugging
1359 |
1360 | ## Step 4: Write Tests
1361 |
1362 | Create tests for your new feature:
1363 | - Unit tests for individual functions
1364 | - Integration tests for feature workflows
1365 | - Edge case testing
1366 |
1367 | ## Step 5: Update Documentation
1368 |
1369 | - Add API documentation if applicable
1370 | - Update user guides
1371 | - Include code examples
1372 |
1373 | ## Step 6: Submit for Review
1374 |
1375 | 1. Push your branch:
1376 | \`\`\`bash
1377 | git push origin feature/your-feature-name
1378 | \`\`\`
1379 |
1380 | 2. Create a pull request
1381 | 3. Address review feedback
1382 |
1383 | ## Best Practices
1384 |
1385 | - Keep changes focused and atomic
1386 | - Follow existing code patterns
1387 | - Maintain backward compatibility
1388 | - Consider performance implications
1389 | `;
1390 | }
1391 |
1392 | private generateDebuggingGuideContent(_analysis: any): string {
1393 | return `# How to Debug Common Issues
1394 |
1395 | This guide helps you troubleshoot and debug common issues in ${_analysis.metadata.projectName}.
1396 |
1397 | ## Debugging Tools
1398 |
1399 | ### Using the Built-in Debugger
1400 |
1401 | 1. Set breakpoints in your code
1402 | 2. Run with debugging enabled:
1403 | \`\`\`bash
1404 | node --inspect src/index.js
1405 | \`\`\`
1406 | 3. Connect your debugger (VS Code, Chrome DevTools, etc.)
1407 |
1408 | ### Logging
1409 |
1410 | Enable verbose logging:
1411 | \`\`\`bash
1412 | DEBUG=* npm start
1413 | \`\`\`
1414 |
1415 | ## Common Issues and Solutions
1416 |
1417 | ### Issue: Module Not Found
1418 |
1419 | **Symptoms**: Error message "Cannot find module"
1420 |
1421 | **Solutions**:
1422 | 1. Check if dependencies are installed: \`npm install\`
1423 | 2. Verify import paths are correct
1424 | 3. Check TypeScript path mappings in tsconfig.json
1425 |
1426 | ### Issue: Type Errors
1427 |
1428 | **Symptoms**: TypeScript compilation errors
1429 |
1430 | **Solutions**:
1431 | 1. Run type checking: \`npm run typecheck\`
1432 | 2. Update type definitions: \`npm install @types/package-name\`
1433 | 3. Check for version mismatches
1434 |
1435 | ### Issue: Test Failures
1436 |
1437 | **Symptoms**: Tests failing unexpectedly
1438 |
1439 | **Solutions**:
1440 | 1. Run tests in isolation
1441 | 2. Check for race conditions
1442 | 3. Verify test data setup
1443 |
1444 | ## Performance Debugging
1445 |
1446 | ### Memory Leaks
1447 |
1448 | Use heap snapshots:
1449 | \`\`\`bash
1450 | node --expose-gc --inspect src/index.js
1451 | \`\`\`
1452 |
1453 | ### Slow Performance
1454 |
1455 | Profile your application:
1456 | \`\`\`bash
1457 | node --prof src/index.js
1458 | \`\`\`
1459 |
1460 | ## Getting Help
1461 |
1462 | If you're still stuck:
1463 | 1. Check the [FAQ](../reference/faq.md)
1464 | 2. Search existing issues on GitHub
1465 | 3. Ask in the community forum
1466 | `;
1467 | }
1468 |
1469 | private generateDeploymentGuideContent(_analysis: any): string {
1470 | return `# How to Deploy Your Application
1471 |
1472 | This guide covers deployment options and best practices for ${_analysis.metadata.projectName}.
1473 |
1474 | ## Pre-Deployment Checklist
1475 |
1476 | - [ ] All tests passing
1477 | - [ ] Environment variables configured
1478 | - [ ] Production dependencies installed
1479 | - [ ] Build process successful
1480 | - [ ] Security vulnerabilities addressed
1481 |
1482 | ## Deployment Options
1483 |
1484 | ### Option 1: GitHub Pages (Static Sites)
1485 |
1486 | 1. Build your application:
1487 | \`\`\`bash
1488 | npm run build
1489 | \`\`\`
1490 |
1491 | 2. Deploy to GitHub Pages:
1492 | \`\`\`bash
1493 | npm run deploy
1494 | \`\`\`
1495 |
1496 | ### Option 2: Cloud Platforms
1497 |
1498 | #### Vercel
1499 | \`\`\`bash
1500 | vercel --prod
1501 | \`\`\`
1502 |
1503 | #### Netlify
1504 | \`\`\`bash
1505 | netlify deploy --prod
1506 | \`\`\`
1507 |
1508 | #### Heroku
1509 | \`\`\`bash
1510 | git push heroku main
1511 | \`\`\`
1512 |
1513 | ### Option 3: Docker Container
1514 |
1515 | 1. Build the Docker image:
1516 | \`\`\`bash
1517 | docker build -t ${_analysis.metadata.projectName} .
1518 | \`\`\`
1519 |
1520 | 2. Run the container:
1521 | \`\`\`bash
1522 | docker run -p 3000:3000 ${_analysis.metadata.projectName}
1523 | \`\`\`
1524 |
1525 | ## Continuous Deployment
1526 |
1527 | ### GitHub Actions
1528 |
1529 | Create \`.github/workflows/deploy.yml\`:
1530 | \`\`\`yaml
1531 | name: Deploy
1532 | on:
1533 | push:
1534 | branches: [main]
1535 |
1536 | jobs:
1537 | deploy:
1538 | runs-on: ubuntu-latest
1539 | steps:
1540 | - uses: actions/checkout@v2
1541 | - uses: actions/setup-node@v2
1542 | - run: npm ci
1543 | - run: npm run build
1544 | - run: npm run deploy
1545 | \`\`\`
1546 |
1547 | ## Post-Deployment
1548 |
1549 | 1. Verify deployment success
1550 | 2. Run smoke tests
1551 | 3. Monitor application logs
1552 | 4. Check performance metrics
1553 | `;
1554 | }
1555 |
1556 | private generateAPIReference(analysis: any): string {
1557 | return `# API Reference
1558 |
1559 | Complete reference for ${analysis.metadata.projectName} APIs.
1560 |
1561 | ## Core APIs
1562 |
1563 | ### initialize(options)
1564 |
1565 | Initialize the application with the given options.
1566 |
1567 | **Parameters:**
1568 | - \`options\` (Object): Configuration options
1569 | - \`port\` (number): Server port (default: 3000)
1570 | - \`host\` (string): Server host (default: 'localhost')
1571 | - \`debug\` (boolean): Enable debug mode (default: false)
1572 |
1573 | **Returns:**
1574 | - \`Application\`: Application instance
1575 |
1576 | **Example:**
1577 | \`\`\`typescript
1578 | const app = initialize({
1579 | port: 8080,
1580 | debug: true
1581 | });
1582 | \`\`\`
1583 |
1584 | ### start()
1585 |
1586 | Start the application server.
1587 |
1588 | **Returns:**
1589 | - \`Promise<void>\`: Resolves when server is running
1590 |
1591 | **Example:**
1592 | \`\`\`typescript
1593 | await app.start();
1594 | console.log('Server running');
1595 | \`\`\`
1596 |
1597 | ### stop()
1598 |
1599 | Stop the application server.
1600 |
1601 | **Returns:**
1602 | - \`Promise<void>\`: Resolves when server is stopped
1603 |
1604 | **Example:**
1605 | \`\`\`typescript
1606 | await app.stop();
1607 | console.log('Server stopped');
1608 | \`\`\`
1609 |
1610 | ## Events
1611 |
1612 | ### 'ready'
1613 |
1614 | Emitted when the application is ready to accept connections.
1615 |
1616 | \`\`\`typescript
1617 | app.on('ready', () => {
1618 | console.log('Application ready');
1619 | });
1620 | \`\`\`
1621 |
1622 | ### 'error'
1623 |
1624 | Emitted when an error occurs.
1625 |
1626 | \`\`\`typescript
1627 | app.on('error', (error) => {
1628 | console.error('Application error:', error);
1629 | });
1630 | \`\`\`
1631 |
1632 | ## Error Codes
1633 |
1634 | | Code | Description |
1635 | |------|-------------|
1636 | | ERR_INVALID_CONFIG | Invalid configuration provided |
1637 | | ERR_PORT_IN_USE | Specified port is already in use |
1638 | | ERR_STARTUP_FAILED | Application failed to start |
1639 | `;
1640 | }
1641 |
1642 | private generateConfigReference(analysis: any): string {
1643 | return `# Configuration Reference
1644 |
1645 | Complete guide to configuring ${analysis.metadata.projectName}.
1646 |
1647 | ## Configuration File
1648 |
1649 | Configuration can be provided via:
1650 | 1. Environment variables
1651 | 2. Configuration file (config.json)
1652 | 3. Command-line arguments
1653 |
1654 | ## Configuration Options
1655 |
1656 | ### Server Configuration
1657 |
1658 | | Option | Type | Default | Description |
1659 | |--------|------|---------|-------------|
1660 | | \`server.port\` | number | 3000 | Server port |
1661 | | \`server.host\` | string | 'localhost' | Server host |
1662 | | \`server.timeout\` | number | 30000 | Request timeout (ms) |
1663 |
1664 | ### Database Configuration
1665 |
1666 | | Option | Type | Default | Description |
1667 | |--------|------|---------|-------------|
1668 | | \`database.host\` | string | 'localhost' | Database host |
1669 | | \`database.port\` | number | 5432 | Database port |
1670 | | \`database.name\` | string | 'myapp' | Database name |
1671 | | \`database.pool.min\` | number | 2 | Minimum pool connections |
1672 | | \`database.pool.max\` | number | 10 | Maximum pool connections |
1673 |
1674 | ### Logging Configuration
1675 |
1676 | | Option | Type | Default | Description |
1677 | |--------|------|---------|-------------|
1678 | | \`logging.level\` | string | 'info' | Log level (debug, info, warn, error) |
1679 | | \`logging.format\` | string | 'json' | Log format (json, text) |
1680 | | \`logging.destination\` | string | 'stdout' | Log destination |
1681 |
1682 | ## Environment Variables
1683 |
1684 | All configuration options can be set via environment variables:
1685 |
1686 | \`\`\`bash
1687 | # Server
1688 | PORT=8080
1689 | HOST=0.0.0.0
1690 |
1691 | # Database
1692 | DATABASE_URL=postgresql://user:pass@localhost:5432/myapp
1693 |
1694 | # Logging
1695 | LOG_LEVEL=debug
1696 | \`\`\`
1697 |
1698 | ## Configuration File Example
1699 |
1700 | \`\`\`json
1701 | {
1702 | "server": {
1703 | "port": 3000,
1704 | "host": "localhost"
1705 | },
1706 | "database": {
1707 | "host": "localhost",
1708 | "port": 5432,
1709 | "name": "myapp"
1710 | },
1711 | "logging": {
1712 | "level": "info",
1713 | "format": "json"
1714 | }
1715 | }
1716 | \`\`\`
1717 | `;
1718 | }
1719 |
1720 | private generateCLIReference(analysis: any): string {
1721 | return `# Command Line Interface
1722 |
1723 | Reference for ${analysis.metadata.projectName} CLI commands.
1724 |
1725 | ## Global Options
1726 |
1727 | | Option | Description |
1728 | |--------|-------------|
1729 | | \`--help, -h\` | Show help information |
1730 | | \`--version, -v\` | Show version number |
1731 | | \`--verbose\` | Enable verbose output |
1732 | | \`--quiet\` | Suppress non-error output |
1733 |
1734 | ## Commands
1735 |
1736 | ### start
1737 |
1738 | Start the application.
1739 |
1740 | \`\`\`bash
1741 | ${analysis.metadata.projectName} start [options]
1742 | \`\`\`
1743 |
1744 | **Options:**
1745 | - \`--port, -p <port>\`: Server port (default: 3000)
1746 | - \`--host, -h <host>\`: Server host (default: localhost)
1747 | - \`--config, -c <file>\`: Configuration file path
1748 |
1749 | ### build
1750 |
1751 | Build the application for production.
1752 |
1753 | \`\`\`bash
1754 | ${analysis.metadata.projectName} build [options]
1755 | \`\`\`
1756 |
1757 | **Options:**
1758 | - \`--output, -o <dir>\`: Output directory (default: dist)
1759 | - \`--minify\`: Minify output
1760 | - \`--sourcemap\`: Generate source maps
1761 |
1762 | ### test
1763 |
1764 | Run tests.
1765 |
1766 | \`\`\`bash
1767 | ${analysis.metadata.projectName} test [options]
1768 | \`\`\`
1769 |
1770 | **Options:**
1771 | - \`--watch, -w\`: Run in watch mode
1772 | - \`--coverage\`: Generate coverage report
1773 | - \`--bail\`: Stop on first test failure
1774 |
1775 | ### lint
1776 |
1777 | Run linting checks.
1778 |
1779 | \`\`\`bash
1780 | ${analysis.metadata.projectName} lint [options]
1781 | \`\`\`
1782 |
1783 | **Options:**
1784 | - \`--fix\`: Automatically fix issues
1785 | - \`--format <format>\`: Output format (stylish, json, compact)
1786 |
1787 | ## Examples
1788 |
1789 | ### Starting with custom configuration
1790 | \`\`\`bash
1791 | ${analysis.metadata.projectName} start --config production.json --port 8080
1792 | \`\`\`
1793 |
1794 | ### Running tests with coverage
1795 | \`\`\`bash
1796 | ${analysis.metadata.projectName} test --coverage --watch
1797 | \`\`\`
1798 |
1799 | ### Building for production
1800 | \`\`\`bash
1801 | ${analysis.metadata.projectName} build --minify --output ./production
1802 | \`\`\`
1803 | `;
1804 | }
1805 |
1806 | private generateArchitectureContent(_analysis: any): string {
1807 | return `# Architecture Overview
1808 |
1809 | Understanding the architecture of ${_analysis.metadata.projectName}.
1810 |
1811 | ## System Architecture
1812 |
1813 | ${_analysis.metadata.projectName} follows a modular architecture designed for scalability and maintainability.
1814 |
1815 | ### Core Components
1816 |
1817 | 1. **Core Engine**: The main processing engine that handles all operations
1818 | 2. **Plugin System**: Extensible plugin architecture for custom functionality
1819 | 3. **API Layer**: RESTful API for external integrations
1820 | 4. **Data Layer**: Abstracted data access layer
1821 |
1822 | ## Design Principles
1823 |
1824 | ### Separation of Concerns
1825 |
1826 | Each module has a single, well-defined responsibility:
1827 | - Business logic is separated from presentation
1828 | - Data access is abstracted from business logic
1829 | - External dependencies are isolated
1830 |
1831 | ### Dependency Injection
1832 |
1833 | Dependencies are injected rather than hard-coded:
1834 | - Improves testability
1835 | - Enables easier mocking
1836 | - Supports multiple implementations
1837 |
1838 | ### Event-Driven Architecture
1839 |
1840 | Components communicate through events:
1841 | - Loose coupling between modules
1842 | - Asynchronous processing capabilities
1843 | - Scalable message handling
1844 |
1845 | ## Directory Structure
1846 |
1847 | \`\`\`
1848 | ${_analysis.metadata.projectName}/
1849 | ├── src/
1850 | │ ├── core/ # Core functionality
1851 | │ ├── plugins/ # Plugin implementations
1852 | │ ├── api/ # API endpoints
1853 | │ ├── services/ # Business services
1854 | │ ├── models/ # Data models
1855 | │ └── utils/ # Utility functions
1856 | ├── tests/ # Test files
1857 | ├── docs/ # Documentation
1858 | └── config/ # Configuration files
1859 | \`\`\`
1860 |
1861 | ## Data Flow
1862 |
1863 | 1. **Request Reception**: API receives incoming requests
1864 | 2. **Validation**: Input validation and sanitization
1865 | 3. **Processing**: Business logic execution
1866 | 4. **Data Access**: Database operations if needed
1867 | 5. **Response Generation**: Format and return response
1868 |
1869 | ## Scalability Considerations
1870 |
1871 | ### Horizontal Scaling
1872 |
1873 | The application supports horizontal scaling through:
1874 | - Stateless design
1875 | - Load balancer compatibility
1876 | - Distributed caching support
1877 |
1878 | ### Performance Optimization
1879 |
1880 | - Lazy loading of modules
1881 | - Caching strategies
1882 | - Database connection pooling
1883 | - Asynchronous operations
1884 |
1885 | ## Security Architecture
1886 |
1887 | ### Authentication & Authorization
1888 |
1889 | - JWT-based authentication
1890 | - Role-based access control (RBAC)
1891 | - API key management
1892 |
1893 | ### Data Protection
1894 |
1895 | - Encryption at rest and in transit
1896 | - Input validation and sanitization
1897 | - SQL injection prevention
1898 | - XSS protection
1899 | `;
1900 | }
1901 |
1902 | private generateDesignDecisionsContent(_analysis: any): string {
1903 | return `# Design Decisions
1904 |
1905 | Key architectural and design decisions made in ${_analysis.metadata.projectName}.
1906 |
1907 | ## Technology Stack
1908 |
1909 | ### Why ${_analysis.metadata.primaryLanguage}?
1910 |
1911 | We chose ${_analysis.metadata.primaryLanguage} for:
1912 | - Strong type safety
1913 | - Excellent tooling support
1914 | - Large ecosystem of libraries
1915 | - Good performance characteristics
1916 | - Team familiarity
1917 |
1918 | ### Framework Selection
1919 |
1920 | After evaluating multiple options, we selected our current stack based on:
1921 | - Community support and documentation
1922 | - Performance benchmarks
1923 | - Learning curve for new developers
1924 | - Long-term maintenance considerations
1925 |
1926 | ## Architectural Patterns
1927 |
1928 | ### Repository Pattern
1929 |
1930 | We implement the repository pattern for data access:
1931 | - **Benefit**: Abstracts data source details
1932 | - **Trade-off**: Additional abstraction layer
1933 | - **Rationale**: Enables easy switching between data sources
1934 |
1935 | ### Service Layer
1936 |
1937 | Business logic is encapsulated in services:
1938 | - **Benefit**: Reusable business logic
1939 | - **Trade-off**: More files and complexity
1940 | - **Rationale**: Clear separation of concerns
1941 |
1942 | ### Dependency Injection
1943 |
1944 | We use dependency injection throughout:
1945 | - **Benefit**: Improved testability and flexibility
1946 | - **Trade-off**: Initial setup complexity
1947 | - **Rationale**: Essential for large-scale applications
1948 |
1949 | ## API Design
1950 |
1951 | ### RESTful vs GraphQL
1952 |
1953 | We chose REST because:
1954 | - Simpler to implement and understand
1955 | - Better caching strategies
1956 | - Fits our use case well
1957 | - Lower operational complexity
1958 |
1959 | ### Versioning Strategy
1960 |
1961 | API versioning through URL paths:
1962 | - **Format**: /api/v1/resource
1963 | - **Benefit**: Clear version boundaries
1964 | - **Trade-off**: URL complexity
1965 | - **Rationale**: Industry standard approach
1966 |
1967 | ## Database Decisions
1968 |
1969 | ### SQL vs NoSQL
1970 |
1971 | We use SQL for:
1972 | - ACID compliance requirements
1973 | - Complex relational data
1974 | - Mature tooling and expertise
1975 | - Predictable performance
1976 |
1977 | ### Migration Strategy
1978 |
1979 | Database migrations are managed through:
1980 | - Version-controlled migration files
1981 | - Automated migration on deployment
1982 | - Rollback capabilities
1983 | - Data validation steps
1984 |
1985 | ## Testing Strategy
1986 |
1987 | ### Test Pyramid
1988 |
1989 | Our testing approach follows the test pyramid:
1990 | - Many unit tests (fast, isolated)
1991 | - Some integration tests (component interaction)
1992 | - Few E2E tests (full system validation)
1993 |
1994 | ### Coverage Goals
1995 |
1996 | - Unit test coverage: 80% minimum
1997 | - Critical path coverage: 100%
1998 | - Integration test coverage: Key workflows
1999 |
2000 | ## Performance Decisions
2001 |
2002 | ### Caching Strategy
2003 |
2004 | Multi-level caching approach:
2005 | - Application-level caching
2006 | - Database query caching
2007 | - CDN for static assets
2008 | - Redis for session data
2009 |
2010 | ### Async Processing
2011 |
2012 | Background jobs for:
2013 | - Email sending
2014 | - Report generation
2015 | - Data processing
2016 | - Third-party integrations
2017 |
2018 | ## Security Decisions
2019 |
2020 | ### Authentication Method
2021 |
2022 | JWT tokens because:
2023 | - Stateless authentication
2024 | - Scalable across services
2025 | - Standard implementation
2026 | - Good library support
2027 |
2028 | ### Data Encryption
2029 |
2030 | - Passwords: bcrypt with salt rounds
2031 | - Sensitive data: AES-256 encryption
2032 | - Communications: TLS 1.3
2033 | - Secrets: Environment variables
2034 |
2035 | ## Future Considerations
2036 |
2037 | ### Microservices
2038 |
2039 | Currently monolithic, but designed for potential splitting:
2040 | - Clear module boundaries
2041 | - Service-oriented architecture
2042 | - Database per service capability
2043 | - API gateway ready
2044 |
2045 | ### Cloud Native
2046 |
2047 | Prepared for cloud deployment:
2048 | - 12-factor app principles
2049 | - Container-ready architecture
2050 | - Environment-based configuration
2051 | - Stateless design
2052 | `;
2053 | }
2054 |
2055 | private generateTechnologyStackContent(_analysis: any): string {
2056 | return `# Technology Stack
2057 |
2058 | Complete overview of technologies used in ${_analysis.metadata.projectName}.
2059 |
2060 | ## Core Technologies
2061 |
2062 | ### Runtime & Language
2063 | - **${_analysis.metadata.primaryLanguage}**: Primary development language
2064 | - **${_analysis.metadata.ecosystem}**: Runtime environment
2065 | - **TypeScript**: Type-safe JavaScript development
2066 |
2067 | ### Package Management
2068 | - **npm/yarn**: Dependency management
2069 | - **npx**: Package execution
2070 | - **nvm**: Node version management
2071 |
2072 | ## Development Tools
2073 |
2074 | ### Build Tools
2075 | - **TypeScript Compiler**: Transpilation to JavaScript
2076 | - **Webpack/Rollup**: Module bundling
2077 | - **Babel**: JavaScript transformation
2078 |
2079 | ### Code Quality
2080 | - **ESLint**: Code linting
2081 | - **Prettier**: Code formatting
2082 | - **Husky**: Git hooks
2083 | - **lint-staged**: Pre-commit checks
2084 |
2085 | ### Testing
2086 | ${
2087 | _analysis.technologies.testing
2088 | ?.map((t: string) => `- **${t}**: Testing framework`)
2089 | .join("\\n") || "- **Jest**: Testing framework"
2090 | }
2091 | - **Supertest**: API testing
2092 | - **Coverage tools**: Code coverage reporting
2093 |
2094 | ## Infrastructure
2095 |
2096 | ### Version Control
2097 | - **Git**: Source control
2098 | - **GitHub**: Repository hosting
2099 | - **GitHub Actions**: CI/CD pipelines
2100 |
2101 | ### Deployment
2102 | ${
2103 | _analysis.technologies.deployment
2104 | ?.map((t: string) => `- **${t}**: Deployment platform`)
2105 | .join("\\n") || "- **Docker**: Containerization"
2106 | }
2107 | - **GitHub Pages**: Documentation hosting
2108 |
2109 | ### Monitoring
2110 | - **Application logs**: Custom logging
2111 | - **Error tracking**: Error monitoring
2112 | - **Performance monitoring**: APM tools
2113 |
2114 | ## Dependencies
2115 |
2116 | ### Core Dependencies
2117 | \`\`\`json
2118 | ${JSON.stringify(_analysis.dependencies.packages?.slice(0, 5) || [], null, 2)}
2119 | \`\`\`
2120 |
2121 | ### Development Dependencies
2122 | - Testing frameworks
2123 | - Build tools
2124 | - Linting tools
2125 | - Type definitions
2126 |
2127 | ## Database & Storage
2128 |
2129 | ${
2130 | _analysis.technologies.database
2131 | ? `### Database
2132 | - **${_analysis.technologies.database}**: Primary database
2133 | - **Migration tools**: Database versioning
2134 | - **ORMs/Query builders**: Data access layer`
2135 | : `### Storage
2136 | - File system for local development
2137 | - Cloud storage for production
2138 | - Caching layers for performance`
2139 | }
2140 |
2141 | ## External Services
2142 |
2143 | ### Third-party APIs
2144 | - Authentication services
2145 | - Payment processing
2146 | - Email services
2147 | - Analytics
2148 |
2149 | ### Cloud Services
2150 | - Hosting platforms
2151 | - CDN services
2152 | - Backup solutions
2153 | - Monitoring services
2154 |
2155 | ## Security Tools
2156 |
2157 | ### Development Security
2158 | - **Dependency scanning**: npm audit
2159 | - **Secret management**: Environment variables
2160 | - **Security headers**: Helmet.js
2161 | - **Input validation**: Sanitization libraries
2162 |
2163 | ### Production Security
2164 | - **TLS/SSL**: Encrypted communications
2165 | - **WAF**: Web application firewall
2166 | - **DDoS protection**: Rate limiting
2167 | - **Access control**: Authentication/authorization
2168 |
2169 | ## Documentation Tools
2170 |
2171 | ### Documentation Generation
2172 | - **Markdown**: Documentation format
2173 | - **Static site generators**: Documentation hosting
2174 | - **API documentation**: OpenAPI/Swagger
2175 | - **Code documentation**: JSDoc/TypeDoc
2176 |
2177 | ## Development Environment
2178 |
2179 | ### Recommended IDE
2180 | - **VS Code**: Primary development environment
2181 | - **Extensions**: Language support, debugging
2182 | - **Configuration**: Shared team settings
2183 |
2184 | ### Local Development
2185 | - **Hot reloading**: Development server
2186 | - **Debugging tools**: Chrome DevTools, VS Code debugger
2187 | - **Database tools**: Local database management
2188 | - **API testing**: Postman/Insomnia
2189 |
2190 | ## Upgrade Path
2191 |
2192 | ### Version Management
2193 | - Regular dependency updates
2194 | - Security patch monitoring
2195 | - Breaking change management
2196 | - Deprecation handling
2197 |
2198 | ### Future Technologies
2199 | - Considering adoption of:
2200 | - New framework versions
2201 | - Performance improvements
2202 | - Developer experience enhancements
2203 | - Security improvements
2204 | `;
2205 | }
2206 |
2207 | private async generateTutorialContent(
2208 | tutorials: any[],
2209 | _analysis: any,
2210 | ): Promise<any[]> {
2211 | // Transform tutorial plans into actual content
2212 | return tutorials;
2213 | }
2214 |
2215 | private async generateHowToContent(
2216 | howTos: any[],
2217 | _analysis: any,
2218 | ): Promise<any[]> {
2219 | return howTos;
2220 | }
2221 |
2222 | private async generateReferenceContent(
2223 | reference: any[],
2224 | _analysis: any,
2225 | ): Promise<any[]> {
2226 | return reference;
2227 | }
2228 |
2229 | private async generateExplanationContent(
2230 | explanation: any[],
2231 | _analysis: any,
2232 | ): Promise<any[]> {
2233 | return explanation;
2234 | }
2235 |
2236 | private async writeContentToStructure(
2237 | docsPath: string,
2238 | content: any,
2239 | preserveExisting: boolean,
2240 | ): Promise<number> {
2241 | let filesCreated = 0;
2242 |
2243 | // Create directory structure if it doesn't exist
2244 | const dirs = ["tutorials", "how-to", "reference", "explanation"];
2245 | for (const dir of dirs) {
2246 | const dirPath = path.join(docsPath, dir);
2247 | await fs.mkdir(dirPath, { recursive: true });
2248 | }
2249 |
2250 | // Write tutorial content
2251 | for (const tutorial of content.tutorials) {
2252 | const fileName = this.slugify(tutorial.title) + ".md";
2253 | const filePath = path.join(docsPath, "tutorials", fileName);
2254 |
2255 | if (preserveExisting) {
2256 | try {
2257 | await fs.access(filePath);
2258 | continue; // Skip if file exists
2259 | } catch {
2260 | // File doesn't exist, proceed to write
2261 | }
2262 | }
2263 |
2264 | await fs.writeFile(filePath, tutorial.content, "utf-8");
2265 | filesCreated++;
2266 | }
2267 |
2268 | // Write how-to guides
2269 | for (const howTo of content.howTos) {
2270 | const fileName = this.slugify(howTo.title) + ".md";
2271 | const filePath = path.join(docsPath, "how-to", fileName);
2272 |
2273 | if (preserveExisting) {
2274 | try {
2275 | await fs.access(filePath);
2276 | continue;
2277 | } catch {
2278 | // File doesn't exist, proceed with creation
2279 | }
2280 | }
2281 |
2282 | await fs.writeFile(filePath, howTo.content, "utf-8");
2283 | filesCreated++;
2284 | }
2285 |
2286 | // Write reference documentation
2287 | for (const ref of content.reference) {
2288 | const fileName = this.slugify(ref.title) + ".md";
2289 | const filePath = path.join(docsPath, "reference", fileName);
2290 |
2291 | if (preserveExisting) {
2292 | try {
2293 | await fs.access(filePath);
2294 | continue;
2295 | } catch {
2296 | // File doesn't exist, proceed with creation
2297 | }
2298 | }
2299 |
2300 | await fs.writeFile(filePath, ref.content, "utf-8");
2301 | filesCreated++;
2302 | }
2303 |
2304 | // Write explanation content
2305 | for (const exp of content.explanation) {
2306 | const fileName = this.slugify(exp.title) + ".md";
2307 | const filePath = path.join(docsPath, "explanation", fileName);
2308 |
2309 | if (preserveExisting) {
2310 | try {
2311 | await fs.access(filePath);
2312 | continue;
2313 | } catch {
2314 | // File doesn't exist, proceed with creation
2315 | }
2316 | }
2317 |
2318 | await fs.writeFile(filePath, exp.content, "utf-8");
2319 | filesCreated++;
2320 | }
2321 |
2322 | return filesCreated;
2323 | }
2324 |
2325 | private async updateNavigationAndCrossReferences(
2326 | docsPath: string,
2327 | contentPlan: ContentPlan,
2328 | ): Promise<void> {
2329 | // Create main index file with navigation
2330 | const indexContent = `# Documentation
2331 |
2332 | Welcome to the documentation! This comprehensive guide is organized following the Diataxis framework.
2333 |
2334 | ## 📚 Learning-Oriented: Tutorials
2335 |
2336 | Start here if you're new to the project:
2337 | ${contentPlan.tutorials
2338 | .map((t) => `- [${t.title}](tutorials/${this.slugify(t.title)}.md)`)
2339 | .join("\\n")}
2340 |
2341 | ## 🔧 Task-Oriented: How-To Guides
2342 |
2343 | Practical guides for specific tasks:
2344 | ${contentPlan.howToGuides
2345 | .map((h) => `- [${h.title}](how-to/${this.slugify(h.title)}.md)`)
2346 | .join("\\n")}
2347 |
2348 | ## 📖 Information-Oriented: Reference
2349 |
2350 | Detailed technical reference:
2351 | ${contentPlan.reference
2352 | .map((r) => `- [${r.title}](reference/${this.slugify(r.title)}.md)`)
2353 | .join("\\n")}
2354 |
2355 | ## 💡 Understanding-Oriented: Explanation
2356 |
2357 | Conceptual documentation and background:
2358 | ${contentPlan.explanation
2359 | .map((e) => `- [${e.title}](explanation/${this.slugify(e.title)}.md)`)
2360 | .join("\\n")}
2361 | `;
2362 |
2363 | await fs.writeFile(path.join(docsPath, "index.md"), indexContent, "utf-8");
2364 | }
2365 |
2366 | private calculatePopulationMetrics(
2367 | filesCreated: number,
2368 | contentPlan: ContentPlan,
2369 | ): any {
2370 | const totalPlanned =
2371 | contentPlan.tutorials.length +
2372 | contentPlan.howToGuides.length +
2373 | contentPlan.reference.length +
2374 | contentPlan.explanation.length;
2375 |
2376 | return {
2377 | coverage: (filesCreated / totalPlanned) * 100,
2378 | completeness: 85, // Example metric
2379 | projectSpecificity: 75, // Example metric
2380 | };
2381 | }
2382 |
2383 | private generateMemoryInformedNextSteps(
2384 | analysis: any,
2385 | _contentPlan: ContentPlan,
2386 | _memoryInsights: any,
2387 | ): string[] {
2388 | const nextSteps = [];
2389 | const patterns = _memoryInsights?.patterns || {};
2390 | const _similarProjects = _memoryInsights?.similarProjects || [];
2391 |
2392 | // Memory-informed next steps based on successful patterns
2393 | if (_similarProjects.length > 0) {
2394 | nextSteps.push(
2395 | `Review and customize the generated content (based on ${_similarProjects.length} similar project patterns)`,
2396 | );
2397 | } else {
2398 | nextSteps.push("Review and customize the generated content");
2399 | }
2400 |
2401 | // Project-specific recommendations
2402 | if (analysis.structure?.hasTests) {
2403 | nextSteps.push("Run and validate all code examples and commands");
2404 | }
2405 |
2406 | if (analysis.structure?.hasCI) {
2407 | nextSteps.push(
2408 | "Set up automated documentation deployment using successful CI patterns",
2409 | );
2410 | }
2411 |
2412 | // Memory-informed improvements
2413 | if (patterns.documentationStructures) {
2414 | nextSteps.push(
2415 | "Enhance documentation structure based on successful similar projects",
2416 | );
2417 | }
2418 |
2419 | if (patterns.deploymentStrategies) {
2420 | nextSteps.push(
2421 | "Implement proven deployment strategies from similar projects",
2422 | );
2423 | }
2424 |
2425 | // Update sitemap after content population
2426 | nextSteps.push(
2427 | "Update sitemap.xml using manage_sitemap tool (action: update) to include new pages",
2428 | );
2429 |
2430 | // Always include validation
2431 | nextSteps.push(
2432 | "Validate technical accuracy using project-specific analysis",
2433 | );
2434 |
2435 | return nextSteps;
2436 | }
2437 |
2438 | // Add the missing memory-informed content generation methods
2439 | private async generateMemoryInformedTutorialContent(
2440 | tutorials: any[],
2441 | analysis: any,
2442 | _memoryInsights: any,
2443 | ): Promise<any[]> {
2444 | return tutorials.map((tutorial) => ({
2445 | ...tutorial,
2446 | content: this.enhanceContentWithMemoryInsights(
2447 | tutorial.content,
2448 | analysis,
2449 | _memoryInsights,
2450 | ),
2451 | codeExamples: this.enhanceExamplesWithRealCode(
2452 | tutorial.codeExamples || [],
2453 | analysis,
2454 | _memoryInsights,
2455 | ),
2456 | }));
2457 | }
2458 |
2459 | private async generateMemoryInformedHowToContent(
2460 | howTos: any[],
2461 | analysis: any,
2462 | _memoryInsights: any,
2463 | ): Promise<any[]> {
2464 | return howTos.map((howTo) => ({
2465 | ...howTo,
2466 | content: this.enhanceContentWithMemoryInsights(
2467 | howTo.content,
2468 | analysis,
2469 | _memoryInsights,
2470 | ),
2471 | }));
2472 | }
2473 |
2474 | private async generateMemoryInformedReferenceContent(
2475 | reference: any[],
2476 | analysis: any,
2477 | _memoryInsights: any,
2478 | ): Promise<any[]> {
2479 | return reference.map((ref) => ({
2480 | ...ref,
2481 | content: this.generateMemoryInformedAPIReference(
2482 | analysis,
2483 | _memoryInsights,
2484 | ),
2485 | }));
2486 | }
2487 |
2488 | private async generateMemoryInformedExplanationContent(
2489 | explanation: any[],
2490 | analysis: any,
2491 | _memoryInsights: any,
2492 | ): Promise<any[]> {
2493 | return explanation.map((exp) => ({
2494 | ...exp,
2495 | content: this.enhanceContentWithMemoryInsights(
2496 | exp.content,
2497 | analysis,
2498 | _memoryInsights,
2499 | ),
2500 | }));
2501 | }
2502 |
2503 | private enhanceContentWithMemoryInsights(
2504 | content: string,
2505 | analysis: any,
2506 | _memoryInsights: any,
2507 | ): string {
2508 | // Replace generic placeholders with real project information
2509 | const language = analysis.metadata?.primaryLanguage || "development";
2510 | const similarCount = _memoryInsights?.similarProjects?.length || 0;
2511 |
2512 | let enhancedContent = content;
2513 |
2514 | // Add memory-informed context
2515 | if (similarCount > 0) {
2516 | enhancedContent = enhancedContent.replace(
2517 | /This guide/g,
2518 | `This guide (based on patterns from ${similarCount} similar ${language} projects)`,
2519 | );
2520 | }
2521 |
2522 | // Replace generic examples with real ones
2523 | enhancedContent = this.replaceGenericExamplesWithReal(
2524 | enhancedContent,
2525 | analysis,
2526 | );
2527 |
2528 | return enhancedContent;
2529 | }
2530 |
2531 | private enhanceExamplesWithRealCode(
2532 | examples: string[],
2533 | analysis: any,
2534 | _memoryInsights: any,
2535 | ): string[] {
2536 | return examples.map((example) => {
2537 | // Replace generic project names with actual project name
2538 | const projectName = analysis.metadata?.projectName || "project";
2539 | return example.replace(
2540 | /your-project|myproject|example-project/g,
2541 | projectName,
2542 | );
2543 | });
2544 | }
2545 |
2546 | private generateMemoryInformedAPIReference(
2547 | analysis: any,
2548 | _memoryInsights: any,
2549 | ): string {
2550 | // Extract actual API structure from project analysis
2551 | const entryPoint = this.findProjectEntryPoint(analysis);
2552 | const packageJson = this.findPackageJson(analysis);
2553 | const projectName = analysis.metadata?.projectName || "the project";
2554 |
2555 | let content = `# API Reference\n\n`;
2556 | content += `Complete reference for ${projectName} APIs.\n\n`;
2557 |
2558 | if (entryPoint) {
2559 | content += `## Core APIs\n\n`;
2560 | content += `### Entry Point: ${entryPoint}\n\n`;
2561 | content += `The main entry point for ${projectName}.\n\n`;
2562 | }
2563 |
2564 | // Add real configuration if available
2565 | if (packageJson?.main) {
2566 | content += `**Main Module:** \`${packageJson.main}\`\n\n`;
2567 | }
2568 |
2569 | // Add real scripts if available
2570 | const scripts = packageJson?.scripts;
2571 | if (scripts && Object.keys(scripts).length > 0) {
2572 | content += `## Available Scripts\n\n`;
2573 | Object.entries(scripts).forEach(([script, command]) => {
2574 | content += `### ${script}\n\n`;
2575 | content += `\`\`\`bash\nnpm run ${script}\n\`\`\`\n\n`;
2576 | content += `Runs: \`${command}\`\n\n`;
2577 | });
2578 | }
2579 |
2580 | return content;
2581 | }
2582 |
2583 | private replaceGenericExamplesWithReal(
2584 | content: string,
2585 | analysis: any,
2586 | ): string {
2587 | const projectName = analysis.metadata?.projectName || "project";
2588 | const language = analysis.metadata?.primaryLanguage || "JavaScript";
2589 |
2590 | // Replace generic project references
2591 | content = content.replace(/your-project-name/g, projectName);
2592 | content = content.replace(/YourProject/g, projectName);
2593 | content = content.replace(/your-language/g, language);
2594 |
2595 | // Replace generic ports with common defaults for the project type
2596 | const defaultPort = this.getDefaultPortForProject(analysis);
2597 | content = content.replace(/3000/g, defaultPort.toString());
2598 |
2599 | return content;
2600 | }
2601 |
2602 | private getDefaultPortForProject(analysis: any): number {
2603 | const packageJson = this.findPackageJson(analysis);
2604 | if (
2605 | packageJson?.scripts?.start &&
2606 | packageJson.scripts.start.includes("port")
2607 | ) {
2608 | // Try to extract port from start script
2609 | const portMatch = packageJson.scripts.start.match(/port[:\s=](\d+)/i);
2610 | if (portMatch) {
2611 | return parseInt(portMatch[1], 10);
2612 | }
2613 | }
2614 |
2615 | // Default ports based on project type
2616 | const dependencies = analysis.dependencies?.packages || [];
2617 | if (dependencies.includes("express")) return 3000;
2618 | if (dependencies.includes("fastify")) return 3000;
2619 | if (dependencies.includes("next")) return 3000;
2620 | if (dependencies.includes("gatsby")) return 8000;
2621 | if (dependencies.includes("nuxt")) return 3000;
2622 |
2623 | return 3000; // Generic default
2624 | }
2625 |
2626 | // Stub methods for the missing plan generation (to be implemented if needed)
2627 | private generateMemoryInformedHowToPlan(
2628 | analysis: any,
2629 | level: string,
2630 | _memoryInsights: any,
2631 | ): any[] {
2632 | return this.generateHowToPlan(analysis, level);
2633 | }
2634 |
2635 | private generateMemoryInformedReferencePlan(
2636 | analysis: any,
2637 | level: string,
2638 | _memoryInsights: any,
2639 | ): any[] {
2640 | return this.generateReferencePlan(analysis, level);
2641 | }
2642 |
2643 | private generateMemoryInformedExplanationPlan(
2644 | analysis: any,
2645 | level: string,
2646 | _memoryInsights: any,
2647 | ): any[] {
2648 | return this.generateExplanationPlan(analysis, level);
2649 | }
2650 |
2651 | private generateMemoryInformedNodeSetupContent(
2652 | _analysis: any,
2653 | _patterns: any,
2654 | ): string {
2655 | return this.generateNodeSetupContent(_analysis);
2656 | }
2657 |
2658 | private generateMemoryInformedNodeSetupExamples(
2659 | _analysis: any,
2660 | _patterns: any,
2661 | ): string[] {
2662 | return this.generateNodeSetupExamples();
2663 | }
2664 |
2665 | private generateNextSteps(
2666 | _analysis: any,
2667 | _contentPlan: ContentPlan,
2668 | ): string[] {
2669 | return [
2670 | "Review and customize the generated content",
2671 | "Add project-specific examples and use cases",
2672 | "Validate technical accuracy of code examples",
2673 | "Add screenshots and diagrams where helpful",
2674 | "Test all commands and code snippets",
2675 | "Set up automated documentation deployment",
2676 | ];
2677 | }
2678 |
2679 | private slugify(text: string): string {
2680 | return text
2681 | .toLowerCase()
2682 | .replace(/[^\w\s-]/g, "")
2683 | .replace(/\s+/g, "-")
2684 | .replace(/--+/g, "-")
2685 | .trim();
2686 | }
2687 |
2688 | // DevOps Detection Methods
2689 | private detectDevOpsTools(analysis: any): DevOpsToolProfile {
2690 | return {
2691 | containerization: this.detectContainerization(analysis),
2692 | orchestration: this.detectOrchestration(analysis),
2693 | cicd: this.detectCICD(analysis),
2694 | configuration: this.detectConfigManagement(analysis),
2695 | monitoring: this.detectMonitoring(analysis),
2696 | security: this.detectSecurity(analysis),
2697 | };
2698 | }
2699 |
2700 | private detectContainerization(analysis: any): ContainerTechnology[] {
2701 | const detected: ContainerTechnology[] = [];
2702 | const files = analysis.files || [];
2703 |
2704 | // Docker detection
2705 | if (
2706 | files.some((f: any) => f.name === "Dockerfile") ||
2707 | files.some((f: any) => f.name === "docker-compose.yml") ||
2708 | files.some((f: any) => f.name === "docker-compose.yaml")
2709 | ) {
2710 | detected.push({
2711 | name: "docker",
2712 | version: this.extractDockerVersion(analysis),
2713 | configFiles: this.getDockerFiles(analysis),
2714 | usage: "containerization",
2715 | });
2716 | }
2717 |
2718 | // Podman detection
2719 | if (
2720 | files.some((f: any) => f.name === "Containerfile") ||
2721 | files.some((f: any) => f.name === "podman-compose.yml")
2722 | ) {
2723 | detected.push({
2724 | name: "podman",
2725 | configFiles: this.getPodmanFiles(analysis),
2726 | usage: "containerization",
2727 | });
2728 | }
2729 |
2730 | return detected;
2731 | }
2732 |
2733 | private detectOrchestration(analysis: any): OrchestrationTechnology[] {
2734 | const detected: OrchestrationTechnology[] = [];
2735 | const files = analysis.files || [];
2736 |
2737 | // Kubernetes detection
2738 | if (
2739 | files.some(
2740 | (f: any) => f.path?.includes("k8s/") || f.path?.includes("kubernetes/"),
2741 | )
2742 | ) {
2743 | detected.push({
2744 | name: "kubernetes",
2745 | manifests: this.getKubernetesManifests(analysis),
2746 | resources: this.analyzeKubernetesResources(analysis),
2747 | namespaces: this.extractNamespaces(analysis),
2748 | });
2749 | }
2750 |
2751 | // OpenShift detection
2752 | if (
2753 | files.some((f: any) => f.path?.includes(".s2i/")) ||
2754 | this.hasFileContent(analysis, "kind: DeploymentConfig")
2755 | ) {
2756 | detected.push({
2757 | name: "openshift",
2758 | });
2759 | }
2760 |
2761 | return detected;
2762 | }
2763 |
2764 | private detectCICD(analysis: any): CICDTechnology[] {
2765 | const detected: CICDTechnology[] = [];
2766 | const files = analysis.files || [];
2767 |
2768 | // GitHub Actions detection
2769 | if (files.some((f: any) => f.path?.includes(".github/workflows/"))) {
2770 | detected.push({
2771 | name: "github-actions",
2772 | });
2773 | }
2774 |
2775 | // Tekton detection
2776 | if (
2777 | files.some((f: any) => f.path?.includes(".tekton/")) ||
2778 | this.hasFileContent(analysis, "apiVersion: tekton.dev")
2779 | ) {
2780 | detected.push({
2781 | name: "tekton",
2782 | });
2783 | }
2784 |
2785 | return detected;
2786 | }
2787 |
2788 | private detectConfigManagement(analysis: any): ConfigManagementTechnology[] {
2789 | const detected: ConfigManagementTechnology[] = [];
2790 | const files = analysis.files || [];
2791 |
2792 | // Ansible detection
2793 | if (
2794 | files.some((f: any) => f.name === "ansible.cfg") ||
2795 | files.some((f: any) => f.path?.includes("playbooks/")) ||
2796 | files.some((f: any) => f.path?.includes("roles/"))
2797 | ) {
2798 | detected.push({
2799 | name: "ansible",
2800 | playbooks: this.getAnsiblePlaybooks(analysis),
2801 | roles: this.getAnsibleRoles(analysis),
2802 | });
2803 | }
2804 |
2805 | // Terraform detection
2806 | if (files.some((f: any) => f.name?.endsWith(".tf"))) {
2807 | detected.push({
2808 | name: "terraform",
2809 | });
2810 | }
2811 |
2812 | return detected;
2813 | }
2814 |
2815 | private detectMonitoring(analysis: any): MonitoringTechnology[] {
2816 | const detected: MonitoringTechnology[] = [];
2817 |
2818 | if (this.hasFileContent(analysis, "prometheus")) {
2819 | detected.push({ name: "prometheus" });
2820 | }
2821 |
2822 | if (this.hasFileContent(analysis, "grafana")) {
2823 | detected.push({ name: "grafana" });
2824 | }
2825 |
2826 | return detected;
2827 | }
2828 |
2829 | private detectSecurity(analysis: any): SecurityTechnology[] {
2830 | const detected: SecurityTechnology[] = [];
2831 |
2832 | if (this.hasFileContent(analysis, "falco")) {
2833 | detected.push({ name: "falco" });
2834 | }
2835 |
2836 | return detected;
2837 | }
2838 |
2839 | // Python Framework Detection
2840 | private detectPythonFrameworks(analysis: any): any[] {
2841 | const frameworks: any[] = [];
2842 | const dependencies = analysis.dependencies?.packages || [];
2843 |
2844 | if (dependencies.includes("django")) {
2845 | frameworks.push({ name: "django", type: "web-framework" });
2846 | }
2847 |
2848 | if (dependencies.includes("fastapi")) {
2849 | frameworks.push({ name: "fastapi", type: "web-framework" });
2850 | }
2851 |
2852 | if (dependencies.includes("flask")) {
2853 | frameworks.push({ name: "flask", type: "web-framework" });
2854 | }
2855 |
2856 | return frameworks;
2857 | }
2858 |
2859 | // Helper methods for file detection
2860 | private hasFileContent(analysis: any, content: string): boolean {
2861 | const files = analysis.files || [];
2862 | return files.some((f: any) => f.content?.includes(content));
2863 | }
2864 |
2865 | private extractDockerVersion(_analysis: any): string | undefined {
2866 | return undefined; // Could be implemented to parse Dockerfile
2867 | }
2868 |
2869 | private getDockerFiles(analysis: any): string[] {
2870 | const files = analysis.files || [];
2871 | return files
2872 | .filter(
2873 | (f: any) =>
2874 | f.name === "Dockerfile" || f.name.includes("docker-compose"),
2875 | )
2876 | .map((f: any) => f.name);
2877 | }
2878 |
2879 | private getPodmanFiles(analysis: any): string[] {
2880 | const files = analysis.files || [];
2881 | return files
2882 | .filter(
2883 | (f: any) =>
2884 | f.name === "Containerfile" || f.name.includes("podman-compose"),
2885 | )
2886 | .map((f: any) => f.name);
2887 | }
2888 |
2889 | private getKubernetesManifests(analysis: any): string[] {
2890 | const files = analysis.files || [];
2891 | return files
2892 | .filter(
2893 | (f: any) => f.path?.includes("k8s/") || f.path?.includes("kubernetes/"),
2894 | )
2895 | .map((f: any) => f.name);
2896 | }
2897 |
2898 | private analyzeKubernetesResources(_analysis: any): string[] {
2899 | return ["Deployment", "Service", "ConfigMap"]; // Simplified
2900 | }
2901 |
2902 | private extractNamespaces(_analysis: any): string[] {
2903 | return ["default"]; // Simplified
2904 | }
2905 |
2906 | private getAnsiblePlaybooks(analysis: any): string[] {
2907 | const files = analysis.files || [];
2908 | return files
2909 | .filter(
2910 | (f: any) => f.path?.includes("playbooks/") && f.name?.endsWith(".yml"),
2911 | )
2912 | .map((f: any) => f.name);
2913 | }
2914 |
2915 | private getAnsibleRoles(analysis: any): string[] {
2916 | const files = analysis.files || [];
2917 | return files
2918 | .filter((f: any) => f.path?.includes("roles/"))
2919 | .map((f: any) => f.name);
2920 | }
2921 |
2922 | // Content generation methods for new features
2923 | private generateContainerTutorialContent(
2924 | _analysis: any,
2925 | _containerTech: ContainerTechnology,
2926 | ): string {
2927 | return `# Containerizing ${_analysis.metadata.projectName} with ${
2928 | _containerTech.name
2929 | }
2930 |
2931 | Learn how to package your ${
2932 | _analysis.metadata.primaryLanguage
2933 | } application into a container for consistent deployment across environments.
2934 |
2935 | ## Prerequisites
2936 |
2937 | - ${_containerTech.name} installed on your system
2938 | - Basic understanding of containerization concepts
2939 | - Your application running locally
2940 |
2941 | ## Understanding Containerization
2942 |
2943 | Containers provide a lightweight, portable way to package applications with all their dependencies. This ensures your application runs consistently across different environments.
2944 |
2945 | ## Creating a ${
2946 | _containerTech.name === "docker" ? "Dockerfile" : "Containerfile"
2947 | }
2948 |
2949 | 1. Create a ${
2950 | _containerTech.name === "docker" ? "Dockerfile" : "Containerfile"
2951 | } in your project root:
2952 |
2953 | \`\`\`dockerfile
2954 | ${this.generateContainerFileContent(_analysis, _containerTech)}
2955 | \`\`\`
2956 |
2957 | ## Building Your Container Image
2958 |
2959 | \`\`\`bash
2960 | ${_containerTech.name} build -t ${_analysis.metadata.projectName}:latest .
2961 | \`\`\`
2962 |
2963 | ## Running Your Container
2964 |
2965 | \`\`\`bash
2966 | ${_containerTech.name} run -p 3000:3000 ${_analysis.metadata.projectName}:latest
2967 | \`\`\`
2968 |
2969 | ## Best Practices
2970 |
2971 | - Use multi-stage builds to reduce image size
2972 | - Don't run containers as root user
2973 | - Use .dockerignore to exclude unnecessary files
2974 | - Pin base image versions for reproducibility
2975 |
2976 | ## Next Steps
2977 |
2978 | - Learn about container orchestration with Kubernetes
2979 | - Set up automated builds in CI/CD pipeline
2980 | - Implement health checks for production deployments
2981 | `;
2982 | }
2983 |
2984 | private generateOrchestrationTutorialContent(
2985 | _analysis: any,
2986 | _orchestrationTech: OrchestrationTechnology,
2987 | ): string {
2988 | return `# Deploying ${_analysis.metadata.projectName} to ${
2989 | _orchestrationTech.name
2990 | }
2991 |
2992 | Deploy your containerized application to ${
2993 | _orchestrationTech.name
2994 | } for scalable, production-ready hosting.
2995 |
2996 | ## Prerequisites
2997 |
2998 | - ${_orchestrationTech.name} cluster access
2999 | - kubectl CLI tool installed
3000 | - Container image built and pushed to registry
3001 |
3002 | ## Understanding ${_orchestrationTech.name}
3003 |
3004 | ${
3005 | _orchestrationTech.name
3006 | } is a container orchestration platform that automates deployment, scaling, and management of containerized applications.
3007 |
3008 | ## Creating Deployment Manifests
3009 |
3010 | 1. Create a deployment configuration:
3011 |
3012 | \`\`\`yaml
3013 | ${this.generateKubernetesManifest(_analysis, "deployment")}
3014 | \`\`\`
3015 |
3016 | 2. Create a service configuration:
3017 |
3018 | \`\`\`yaml
3019 | ${this.generateKubernetesManifest(_analysis, "service")}
3020 | \`\`\`
3021 |
3022 | ## Deploying to ${_orchestrationTech.name}
3023 |
3024 | \`\`\`bash
3025 | kubectl apply -f deployment.yaml
3026 | kubectl apply -f service.yaml
3027 | \`\`\`
3028 |
3029 | ## Monitoring Your Deployment
3030 |
3031 | \`\`\`bash
3032 | kubectl get pods
3033 | kubectl get services
3034 | kubectl logs -f deployment/${_analysis.metadata.projectName}
3035 | \`\`\`
3036 |
3037 | ## Scaling Your Application
3038 |
3039 | \`\`\`bash
3040 | kubectl scale deployment ${_analysis.metadata.projectName} --replicas=3
3041 | \`\`\`
3042 |
3043 | ## Next Steps
3044 |
3045 | - Set up ingress for external access
3046 | - Configure persistent storage
3047 | - Implement monitoring and logging
3048 | `;
3049 | }
3050 |
3051 | private generatePythonEnvironmentContent(_analysis: any): string {
3052 | return `# Python Virtual Environment Setup
3053 |
3054 | Set up an isolated Python development environment for ${_analysis.metadata.projectName}.
3055 |
3056 | ## Why Virtual Environments?
3057 |
3058 | Virtual environments isolate project dependencies, preventing conflicts between different projects and ensuring reproducible builds.
3059 |
3060 | ## Creating a Virtual Environment
3061 |
3062 | ### Using venv (Python 3.3+)
3063 |
3064 | \`\`\`bash
3065 | python -m venv venv
3066 | \`\`\`
3067 |
3068 | ### Using virtualenv
3069 |
3070 | \`\`\`bash
3071 | pip install virtualenv
3072 | virtualenv venv
3073 | \`\`\`
3074 |
3075 | ### Using conda
3076 |
3077 | \`\`\`bash
3078 | conda create --name ${_analysis.metadata.projectName} python=3.11
3079 | \`\`\`
3080 |
3081 | ## Activating the Environment
3082 |
3083 | ### Linux/macOS
3084 |
3085 | \`\`\`bash
3086 | source venv/bin/activate
3087 | \`\`\`
3088 |
3089 | ### Windows
3090 |
3091 | \`\`\`bash
3092 | venv\\Scripts\\activate
3093 | \`\`\`
3094 |
3095 | ### Conda
3096 |
3097 | \`\`\`bash
3098 | conda activate ${_analysis.metadata.projectName}
3099 | \`\`\`
3100 |
3101 | ## Installing Dependencies
3102 |
3103 | \`\`\`bash
3104 | pip install -r requirements.txt
3105 | \`\`\`
3106 |
3107 | ## Development Tools
3108 |
3109 | Install useful development tools:
3110 |
3111 | \`\`\`bash
3112 | pip install black flake8 pytest mypy
3113 | \`\`\`
3114 |
3115 | ## Deactivating the Environment
3116 |
3117 | \`\`\`bash
3118 | deactivate
3119 | \`\`\`
3120 |
3121 | ## Best Practices
3122 |
3123 | - Always use virtual environments for Python projects
3124 | - Keep requirements.txt updated
3125 | - Use requirements-dev.txt for development dependencies
3126 | - Consider using poetry or pipenv for advanced dependency management
3127 | `;
3128 | }
3129 |
3130 | private generatePythonFrameworkTutorialContent(
3131 | _analysis: any,
3132 | framework: any,
3133 | ): string {
3134 | if (framework.name === "django") {
3135 | return this.generateDjangoTutorialContent(_analysis);
3136 | } else if (framework.name === "fastapi") {
3137 | return this.generateFastAPITutorialContent(_analysis);
3138 | } else if (framework.name === "flask") {
3139 | return this.generateFlaskTutorialContent(_analysis);
3140 | }
3141 |
3142 | return `# Building Applications with ${framework.name}
3143 |
3144 | Learn how to build applications using ${framework.name}.
3145 |
3146 | ## Getting Started
3147 |
3148 | Install ${framework.name}:
3149 |
3150 | \`\`\`bash
3151 | pip install ${framework.name}
3152 | \`\`\`
3153 |
3154 | ## Basic Application Structure
3155 |
3156 | Create your first ${framework.name} application and explore the framework's core concepts.
3157 | `;
3158 | }
3159 |
3160 | private generateDjangoTutorialContent(_analysis: any): string {
3161 | return `# Building Applications with Django
3162 |
3163 | Create robust web applications using Django's Model-View-Template architecture.
3164 |
3165 | ## Project Setup
3166 |
3167 | 1. Install Django:
3168 |
3169 | \`\`\`bash
3170 | pip install django
3171 | \`\`\`
3172 |
3173 | 2. Create a new Django project:
3174 |
3175 | \`\`\`bash
3176 | django-admin startproject ${_analysis.metadata.projectName}
3177 | cd ${_analysis.metadata.projectName}
3178 | \`\`\`
3179 |
3180 | 3. Create your first app:
3181 |
3182 | \`\`\`bash
3183 | python manage.py startapp core
3184 | \`\`\`
3185 |
3186 | ## Understanding Django Architecture
3187 |
3188 | Django follows the MTV (Model-View-Template) pattern:
3189 | - **Models**: Define your data structure
3190 | - **Views**: Handle business logic and user interactions
3191 | - **Templates**: Control presentation layer
3192 |
3193 | ## Creating Your First Model
3194 |
3195 | \`\`\`python
3196 | # core/models.py
3197 | from django.db import models
3198 |
3199 | class Item(models.Model):
3200 | name = models.CharField(max_length=100)
3201 | description = models.TextField()
3202 | created_at = models.DateTimeField(auto_now_add=True)
3203 |
3204 | def __str__(self):
3205 | return self.name
3206 | \`\`\`
3207 |
3208 | ## Running Migrations
3209 |
3210 | \`\`\`bash
3211 | python manage.py makemigrations
3212 | python manage.py migrate
3213 | \`\`\`
3214 |
3215 | ## Creating Views
3216 |
3217 | \`\`\`python
3218 | # core/views.py
3219 | from django.shortcuts import render
3220 | from .models import Item
3221 |
3222 | def item_list(request):
3223 | items = Item.objects.all()
3224 | return render(request, 'core/item_list.html', {'items': items})
3225 | \`\`\`
3226 |
3227 | ## URL Configuration
3228 |
3229 | \`\`\`python
3230 | # core/urls.py
3231 | from django.urls import path
3232 | from . import views
3233 |
3234 | urlpatterns = [
3235 | path('', views.item_list, name='item_list'),
3236 | ]
3237 | \`\`\`
3238 |
3239 | ## Running the Development Server
3240 |
3241 | \`\`\`bash
3242 | python manage.py runserver
3243 | \`\`\`
3244 |
3245 | ## Next Steps
3246 |
3247 | - Learn about Django REST Framework for API development
3248 | - Explore Django's admin interface
3249 | - Implement user authentication
3250 | - Deploy with Gunicorn and PostgreSQL
3251 | `;
3252 | }
3253 |
3254 | private generateFastAPITutorialContent(_analysis: any): string {
3255 | return `# Building APIs with FastAPI
3256 |
3257 | Create modern, fast APIs with automatic documentation using FastAPI.
3258 |
3259 | ## Installation
3260 |
3261 | \`\`\`bash
3262 | pip install fastapi uvicorn
3263 | \`\`\`
3264 |
3265 | ## Basic Application
3266 |
3267 | \`\`\`python
3268 | # main.py
3269 | from fastapi import FastAPI
3270 | from pydantic import BaseModel
3271 |
3272 | app = FastAPI()
3273 |
3274 | class Item(BaseModel):
3275 | name: str
3276 | description: str = None
3277 | price: float
3278 | tax: float = None
3279 |
3280 | @app.get("/")
3281 | async def read_root():
3282 | return {"Hello": "World"}
3283 |
3284 | @app.post("/items/")
3285 | async def create_item(item: Item):
3286 | return item
3287 |
3288 | @app.get("/items/{item_id}")
3289 | async def read_item(item_id: int, q: str = None):
3290 | return {"item_id": item_id, "q": q}
3291 | \`\`\`
3292 |
3293 | ## Running the Server
3294 |
3295 | \`\`\`bash
3296 | uvicorn main:app --reload
3297 | \`\`\`
3298 |
3299 | ## Interactive Documentation
3300 |
3301 | FastAPI automatically generates interactive API documentation:
3302 | - Swagger UI: http://127.0.0.1:8000/docs
3303 | - ReDoc: http://127.0.0.1:8000/redoc
3304 |
3305 | ## Key Features
3306 |
3307 | - **Type Hints**: Python type hints for automatic validation
3308 | - **Async Support**: Native async/await support
3309 | - **Dependency Injection**: Powerful dependency injection system
3310 | - **Security**: Built-in security utilities
3311 |
3312 | ## Next Steps
3313 |
3314 | - Add database integration with SQLAlchemy
3315 | - Implement authentication with JWT
3316 | - Add background tasks
3317 | - Deploy with Docker
3318 | `;
3319 | }
3320 |
3321 | private generateFlaskTutorialContent(_analysis: any): string {
3322 | return `# Building Applications with Flask
3323 |
3324 | Create lightweight web applications and APIs using Flask's minimalist approach.
3325 |
3326 | ## Installation
3327 |
3328 | \`\`\`bash
3329 | pip install flask
3330 | \`\`\`
3331 |
3332 | ## Basic Application
3333 |
3334 | \`\`\`python
3335 | # app.py
3336 | from flask import Flask, request, jsonify
3337 |
3338 | app = Flask(__name__)
3339 |
3340 | @app.route('/')
3341 | def hello_world():
3342 | return 'Hello, World!'
3343 |
3344 | @app.route('/api/items', methods=['GET', 'POST'])
3345 | def handle_items():
3346 | if request.method == 'POST':
3347 | data = request.get_json()
3348 | return jsonify(data), 201
3349 | else:
3350 | return jsonify([{"name": "item1"}, {"name": "item2"}])
3351 |
3352 | if __name__ == '__main__':
3353 | app.run(debug=True)
3354 | \`\`\`
3355 |
3356 | ## Running the Application
3357 |
3358 | \`\`\`bash
3359 | python app.py
3360 | \`\`\`
3361 |
3362 | ## Application Factory Pattern
3363 |
3364 | For larger applications, use the application factory pattern:
3365 |
3366 | \`\`\`python
3367 | # app/__init__.py
3368 | from flask import Flask
3369 |
3370 | def create_app():
3371 | app = Flask(__name__)
3372 | app.config.from_object('config.Config')
3373 |
3374 | from app.main import bp as main_bp
3375 | app.register_blueprint(main_bp)
3376 |
3377 | return app
3378 | \`\`\`
3379 |
3380 | ## Flask Extensions
3381 |
3382 | Popular Flask extensions:
3383 | - **Flask-SQLAlchemy**: Database ORM
3384 | - **Flask-Login**: User session management
3385 | - **Flask-WTF**: Form handling and validation
3386 | - **Flask-Migrate**: Database migrations
3387 |
3388 | ## Next Steps
3389 |
3390 | - Structure larger applications with Blueprints
3391 | - Add database integration
3392 | - Implement user authentication
3393 | - Deploy with Gunicorn
3394 | `;
3395 | }
3396 |
3397 | // Helper methods for container content generation
3398 | private generateContainerFileContent(
3399 | _analysis: any,
3400 | _containerTech: ContainerTechnology,
3401 | ): string {
3402 | const language = _analysis.metadata.primaryLanguage?.toLowerCase();
3403 |
3404 | if (language === "python") {
3405 | return `FROM python:3.11-slim
3406 |
3407 | WORKDIR /app
3408 |
3409 | COPY requirements.txt .
3410 | RUN pip install --no-cache-dir -r requirements.txt
3411 |
3412 | COPY . .
3413 |
3414 | EXPOSE 8000
3415 |
3416 | CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]`;
3417 | } else if (language === "javascript" || language === "typescript") {
3418 | return `FROM node:18-alpine
3419 |
3420 | WORKDIR /app
3421 |
3422 | COPY package*.json ./
3423 | RUN npm ci --only=production
3424 |
3425 | COPY . .
3426 |
3427 | EXPOSE 3000
3428 |
3429 | USER node
3430 |
3431 | CMD ["npm", "start"]`;
3432 | } else {
3433 | return `FROM ubuntu:22.04
3434 |
3435 | WORKDIR /app
3436 |
3437 | COPY . .
3438 |
3439 | EXPOSE 8080
3440 |
3441 | CMD ["./start.sh"]`;
3442 | }
3443 | }
3444 |
3445 | private generateKubernetesManifest(analysis: any, type: string): string {
3446 | if (type === "deployment") {
3447 | return `apiVersion: apps/v1
3448 | kind: Deployment
3449 | metadata:
3450 | name: ${analysis.metadata.projectName}
3451 | labels:
3452 | app: ${analysis.metadata.projectName}
3453 | spec:
3454 | replicas: 3
3455 | selector:
3456 | matchLabels:
3457 | app: ${analysis.metadata.projectName}
3458 | template:
3459 | metadata:
3460 | labels:
3461 | app: ${analysis.metadata.projectName}
3462 | spec:
3463 | containers:
3464 | - name: ${analysis.metadata.projectName}
3465 | image: ${analysis.metadata.projectName}:latest
3466 | ports:
3467 | - containerPort: 3000
3468 | env:
3469 | - name: NODE_ENV
3470 | value: "production"`;
3471 | } else if (type === "service") {
3472 | return `apiVersion: v1
3473 | kind: Service
3474 | metadata:
3475 | name: ${analysis.metadata.projectName}-service
3476 | spec:
3477 | selector:
3478 | app: ${analysis.metadata.projectName}
3479 | ports:
3480 | - protocol: TCP
3481 | port: 80
3482 | targetPort: 3000
3483 | type: LoadBalancer`;
3484 | }
3485 |
3486 | return "";
3487 | }
3488 |
3489 | private generateContainerExamples(
3490 | _analysis: any,
3491 | _containerTech: ContainerTechnology,
3492 | ): string[] {
3493 | return [
3494 | `# Build the container image
3495 | ${_containerTech.name} build -t ${_analysis.metadata.projectName}:latest .`,
3496 |
3497 | `# Run the container locally
3498 | ${_containerTech.name} run -p 3000:3000 -d ${_analysis.metadata.projectName}:latest`,
3499 |
3500 | `# View running containers
3501 | ${_containerTech.name} ps`,
3502 | ];
3503 | }
3504 |
3505 | private generateOrchestrationExamples(
3506 | _analysis: any,
3507 | _orchestrationTech: OrchestrationTechnology,
3508 | ): string[] {
3509 | return [
3510 | `# Deploy the application
3511 | kubectl apply -f k8s/`,
3512 |
3513 | `# Check deployment status
3514 | kubectl get deployments`,
3515 |
3516 | `# View application logs
3517 | kubectl logs -f deployment/${_analysis.metadata.projectName}`,
3518 | ];
3519 | }
3520 |
3521 | private generatePythonEnvironmentExamples(): string[] {
3522 | return [
3523 | `# Create virtual environment
3524 | python -m venv venv`,
3525 |
3526 | `# Activate environment (Linux/macOS)
3527 | source venv/bin/activate`,
3528 |
3529 | `# Install dependencies
3530 | pip install -r requirements.txt`,
3531 | ];
3532 | }
3533 |
3534 | private generatePythonFrameworkExamples(framework: any): string[] {
3535 | if (framework.name === "django") {
3536 | return [
3537 | `# Create Django project
3538 | django-admin startproject myproject`,
3539 |
3540 | `# Run development server
3541 | python manage.py runserver`,
3542 |
3543 | `# Create superuser
3544 | python manage.py createsuperuser`,
3545 | ];
3546 | }
3547 |
3548 | return [];
3549 | }
3550 | }
3551 |
3552 | // Export the tool implementation
3553 | export const populateDiataxisContent: Tool = {
3554 | name: "populate_diataxis_content",
3555 | description:
3556 | "Intelligently populate Diataxis documentation with project-specific content",
3557 | inputSchema: {
3558 | type: "object",
3559 | properties: {
3560 | analysisId: {
3561 | type: "string",
3562 | description: "Repository analysis ID from analyze_repository tool",
3563 | },
3564 | docsPath: {
3565 | type: "string",
3566 | description: "Path to documentation directory",
3567 | },
3568 | populationLevel: {
3569 | type: "string",
3570 | enum: ["basic", "comprehensive", "intelligent"],
3571 | default: "comprehensive",
3572 | description: "Level of content generation detail",
3573 | },
3574 | includeProjectSpecific: {
3575 | type: "boolean",
3576 | default: true,
3577 | description: "Generate project-specific examples and code",
3578 | },
3579 | preserveExisting: {
3580 | type: "boolean",
3581 | default: true,
3582 | description: "Preserve any existing content",
3583 | },
3584 | technologyFocus: {
3585 | type: "array",
3586 | items: { type: "string" },
3587 | description: "Specific technologies to emphasize in content",
3588 | },
3589 | },
3590 | required: ["analysisId", "docsPath"],
3591 | },
3592 | };
3593 |
3594 | export async function handlePopulateDiataxisContent(
3595 | args: any,
3596 | context?: any,
3597 | ): Promise<PopulationResult> {
3598 | const engine = new ContentPopulationEngine();
3599 | return await engine.populateContent(args, context);
3600 | }
3601 |
```