deepwiki-rs 1.5.0

deepwiki-rs(also known as Litho) is a high-performance automatic generation engine for C4 architecture documentation, developed using Rust. It can intelligently analyze project structures, identify core components, parse dependency relationships, and leverage large language models (LLMs) to automatically generate professional architecture documentation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use crate::generator::preprocess::memory::{MemoryScope, ScopedKeys};
use crate::generator::research::types::{AgentType, DatabaseOverviewReport};
use crate::generator::{
    context::GeneratorContext,
    step_forward_agent::{
        AgentDataConfig, DataSource, FormatterConfig, LLMCallMode, PromptTemplate, StepForwardAgent,
    },
};
use crate::types::code::{CodeInsight, CodePurpose};
use anyhow::{Result, anyhow};
use async_trait::async_trait;

/// Database Overview Analyzer - Analyzes SQL database projects, tables, views, stored procedures, and data relationships
#[derive(Default, Clone)]
pub struct DatabaseOverviewAnalyzer;

#[async_trait]
impl StepForwardAgent for DatabaseOverviewAnalyzer {
    type Output = DatabaseOverviewReport;

    fn agent_type(&self) -> String {
        AgentType::DatabaseOverviewAnalyzer.to_string()
    }

    fn agent_type_enum(&self) -> Option<AgentType> {
        Some(AgentType::DatabaseOverviewAnalyzer)
    }

    fn memory_scope_key(&self) -> String {
        crate::generator::research::memory::MemoryScope::STUDIES_RESEARCH.to_string()
    }

    fn data_config(&self) -> AgentDataConfig {
        AgentDataConfig {
            required_sources: vec![
                DataSource::PROJECT_STRUCTURE,
                DataSource::CODE_INSIGHTS,
            ],
            // Use database documentation for additional context
            optional_sources: vec![DataSource::knowledge_categories(vec!["database", "architecture"])],
        }
    }

    fn prompt_template(&self) -> PromptTemplate {
        PromptTemplate {
            system_prompt:
                r#"You are a professional database architect and SQL analyst, focused on analyzing SQL Server database projects and their structures.

Your task is to analyze the provided SQL code insights and produce a comprehensive database overview including:

1. **Database Projects** - Identify .sqlproj files and their structure
2. **Tables** - Extract table definitions, columns, data types, constraints
3. **Views** - Identify views and their source tables
4. **Stored Procedures** - Analyze stored procedures, their parameters, and the tables they interact with
5. **Functions** - Identify scalar and table-valued functions
6. **Relationships** - Detect foreign key relationships and implicit references between tables
7. **Data Flows** - Identify data movement patterns through procedures and ETL-like operations

You may have access to existing database documentation from external sources.
If available:
- Cross-reference discovered objects with documented schemas
- Validate naming conventions and data types
- Use documented business context for descriptions
- Identify any undocumented database objects

Focus on:
- Extract schema and object names accurately
- Identify column data types and constraints
- Detect relationships between tables (explicit FKs and implicit references via JOINs)
- Understand the purpose of stored procedures and functions
- Map data flow patterns through the database

You MUST output strict JSON only (no markdown, no code fences, no prose outside JSON).
Return exactly this shape with all keys present:
{
  "database_projects": [
    {
      "name": "string",
      "project_path": "string",
      "target_platform": "string or null",
      "table_count": 0,
      "view_count": 0,
      "procedure_count": 0,
      "function_count": 0,
      "references": ["string"]
    }
  ],
  "tables": [
    {
      "schema": "string",
      "name": "string",
      "columns": [
        {
          "name": "string",
          "data_type": "string",
          "nullable": false,
          "is_identity": false,
          "default_value": "string or null"
        }
      ],
      "primary_key": ["string"],
      "description": "string",
      "source_path": "string"
    }
  ],
  "views": [
    {
      "schema": "string",
      "name": "string",
      "description": "string",
      "referenced_tables": ["string"],
      "source_path": "string"
    }
  ],
  "stored_procedures": [
    {
      "schema": "string",
      "name": "string",
      "parameters": [
        {
          "name": "string",
          "data_type": "string",
          "is_optional": false,
          "direction": "string"
        }
      ],
      "description": "string",
      "referenced_tables": ["string"],
      "source_path": "string"
    }
  ],
  "database_functions": [
    {
      "schema": "string",
      "name": "string",
      "function_type": "string",
      "parameters": [
        {
          "name": "string",
          "data_type": "string",
          "is_optional": false,
          "direction": "string"
        }
      ],
      "return_type": "string",
      "description": "string",
      "source_path": "string"
    }
  ],
  "table_relationships": [
    {
      "from_table": "string",
      "from_columns": ["string"],
      "to_table": "string",
      "to_columns": ["string"],
      "relationship_type": "string",
      "constraint_name": "string or null"
    }
  ],
  "data_flows": [
    {
      "name": "string",
      "source": "string",
      "destination": "string",
      "operations": ["string"],
      "procedures_involved": ["string"]
    }
  ],
  "confidence_score": 0.0
}

Rules:
- Always include all top-level keys.
- Items in arrays must be objects, never plain strings.
- Use empty arrays if no database objects exist.
- Use empty strings or null for unknown fields.
- confidence_score must be numeric (0.0-10.0)."#
                    .to_string(),

            opening_instruction: "Analyze the database structure based on the following SQL code insights and project information:".to_string(),

            closing_instruction: r#"
## Analysis Requirements:
- Focus on Database-purpose code (.sql, .sqlproj files)
- Extract table schemas, columns, and data types from CREATE TABLE statements
- Identify stored procedure parameters and referenced tables
- Detect foreign key relationships from constraint definitions
- Identify implicit relationships from JOIN conditions in views and procedures
- Map data flows through INSERT/UPDATE/DELETE operations in procedures
- If certain database objects don't exist, the corresponding arrays can be empty
- Provide meaningful descriptions based on naming conventions and context"#
                .to_string(),

            llm_call_mode: LLMCallMode::Extract,
            formatter_config: FormatterConfig {
                include_source_code: true, // Database analysis requires viewing SQL source code
                code_insights_limit: 50,   // Reduced limit to prevent token overflow
                only_directories_when_files_more_than: Some(300),
                ..FormatterConfig::default()
            },
        }
    }

    /// Provide custom database code analysis content
    async fn provide_custom_prompt_content(
        &self,
        context: &GeneratorContext,
    ) -> Result<Option<String>> {
        // Filter database-related code insights
        let database_insights = self.filter_database_code_insights(context).await?;

        if database_insights.is_empty() {
            return Ok(Some(
                "### Database-Related Code Insights\nNo SQL database-related code found in this project.\n\n".to_string(),
            ));
        }

        // Format database code insights
        let formatted_content = self.format_database_insights(&database_insights);

        Ok(Some(formatted_content))
    }

    /// Post-processing - output analysis summary
    fn post_process(
        &self,
        result: &DatabaseOverviewReport,
        _context: &GeneratorContext,
    ) -> Result<()> {
        println!("✅ Database overview analysis completed:");
        println!("   - Database projects: {} items", result.database_projects.len());
        println!("   - Tables: {} items", result.tables.len());
        println!("   - Views: {} items", result.views.len());
        println!("   - Stored procedures: {} items", result.stored_procedures.len());
        println!("   - Functions: {} items", result.database_functions.len());
        println!("   - Table relationships: {} items", result.table_relationships.len());
        println!("   - Data flows: {} items", result.data_flows.len());
        println!("   - Confidence: {:.1}/10", result.confidence_score);

        Ok(())
    }
}

impl DatabaseOverviewAnalyzer {
    /// Filter database-related code insights
    async fn filter_database_code_insights(
        &self,
        context: &GeneratorContext,
    ) -> Result<Vec<CodeInsight>> {
        let all_insights = context
            .get_from_memory::<Vec<CodeInsight>>(MemoryScope::PREPROCESS, ScopedKeys::CODE_INSIGHTS)
            .await
            .ok_or_else(|| anyhow!("CODE_INSIGHTS not found in PREPROCESS memory"))?;

        // Filter database-related code
        let mut database_insights: Vec<CodeInsight> = all_insights
            .into_iter()
            .filter(|insight| {
                // First check file size to exclude extremely large files
                let source_len = insight.code_dossier.source_summary.len();
                if source_len > 50000 {
                    return false; // Skip files with source summaries larger than 50KB
                }

                // Include files with Database purpose
                matches!(insight.code_dossier.code_purpose, CodePurpose::Database)
                    // Also include DAO files as they often reflect database structure
                    || matches!(insight.code_dossier.code_purpose, CodePurpose::Dao)
                    // Include files with SQL-related component types
                    || insight.code_dossier.file_path.to_string_lossy().ends_with(".sql")
                    || insight.code_dossier.file_path.to_string_lossy().ends_with(".sqlproj")
            })
            .collect();

        // Truncate source summaries for remaining files to prevent token overflow
        for insight in &mut database_insights {
            let source_len = insight.code_dossier.source_summary.len();
            if source_len > 10000 {
                // If source summary is very large, truncate it to first 10KB
                let truncated: String = insight.code_dossier.source_summary.chars().take(10000).collect();
                insight.code_dossier.source_summary = truncated;

                // Add a note that the content was truncated
                if !insight.code_dossier.source_summary.is_empty() {
                    insight.code_dossier.source_summary.push_str("\n\n[Content truncated for analysis]");
                }
            }
        }

        // Sort by importance
        let mut sorted_insights = database_insights;
        sorted_insights.sort_by(|a, b| {
            b.code_dossier
                .importance_score
                .partial_cmp(&a.code_dossier.importance_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Take up to 50 most important to prevent token overflow
        sorted_insights.truncate(50);

        // Group by type and count
        let mut sqlproj_count = 0;
        let mut sql_count = 0;
        let mut dao_count = 0;

        for insight in &sorted_insights {
            let path = insight.code_dossier.file_path.to_string_lossy();
            if path.ends_with(".sqlproj") {
                sqlproj_count += 1;
            } else if path.ends_with(".sql") {
                sql_count += 1;
            } else if matches!(insight.code_dossier.code_purpose, CodePurpose::Dao) {
                dao_count += 1;
            }
        }

        println!(
            "📊 Database code distribution: Projects({}) SQL Files({}) DAO({})",
            sqlproj_count, sql_count, dao_count
        );

        Ok(sorted_insights)
    }

    /// Format database code insights
    fn format_database_insights(&self, insights: &[CodeInsight]) -> String {
        let mut content = String::from("### Database-Related Code Insights\n\n");

        // Group by type
        let mut projects = Vec::new();
        let mut tables = Vec::new();
        let mut views = Vec::new();
        let mut procedures = Vec::new();
        let mut functions = Vec::new();
        let mut other_sql = Vec::new();
        let mut dao_files = Vec::new();

        for insight in insights {
            let path = insight.code_dossier.file_path.to_string_lossy().to_lowercase();

            if path.ends_with(".sqlproj") {
                projects.push(insight);
            } else if path.ends_with(".sql") {
                // Categorize SQL files by content/path
                if path.contains("table") || insight.code_dossier.name.to_lowercase().contains("table") {
                    tables.push(insight);
                } else if path.contains("view") || insight.code_dossier.name.to_lowercase().contains("view") {
                    views.push(insight);
                } else if path.contains("procedure") || path.contains("storedproc") || path.contains("sproc") {
                    procedures.push(insight);
                } else if path.contains("function") {
                    functions.push(insight);
                } else {
                    other_sql.push(insight);
                }
            } else if matches!(insight.code_dossier.code_purpose, CodePurpose::Dao) {
                dao_files.push(insight);
            }
        }

        // Format each category
        if !projects.is_empty() {
            content.push_str("#### Database Projects (.sqlproj)\n");
            content.push_str("These are SQL Server Database Projects:\n\n");
            for insight in projects {
                self.add_insight_item(&mut content, insight);
            }
        }

        if !tables.is_empty() {
            content.push_str("#### Table Definitions\n");
            content.push_str("SQL files containing table definitions:\n\n");
            for insight in tables {
                self.add_insight_item(&mut content, insight);
            }
        }

        if !views.is_empty() {
            content.push_str("#### View Definitions\n");
            content.push_str("SQL files containing view definitions:\n\n");
            for insight in views {
                self.add_insight_item(&mut content, insight);
            }
        }

        if !procedures.is_empty() {
            content.push_str("#### Stored Procedures\n");
            content.push_str("SQL files containing stored procedure definitions:\n\n");
            for insight in procedures {
                self.add_insight_item(&mut content, insight);
            }
        }

        if !functions.is_empty() {
            content.push_str("#### Functions\n");
            content.push_str("SQL files containing function definitions:\n\n");
            for insight in functions {
                self.add_insight_item(&mut content, insight);
            }
        }

        if !other_sql.is_empty() {
            content.push_str("#### Other SQL Files\n");
            content.push_str("Other SQL scripts and files:\n\n");
            for insight in other_sql {
                self.add_insight_item(&mut content, insight);
            }
        }

        if !dao_files.is_empty() {
            content.push_str("#### Data Access Objects (DAO)\n");
            content.push_str("Code files that interact with the database:\n\n");
            for insight in dao_files {
                self.add_insight_item(&mut content, insight);
            }
        }

        content.push_str("\n");
        content
    }

    /// Determine appropriate language identifier based on file type
    fn determine_code_language(&self, file_path: &std::path::Path) -> &str {
        let path = file_path.to_string_lossy();

        if path.ends_with(".sql") || path.ends_with(".sqlproj") {
            "sql"
        } else if path.ends_with(".java") {
            "java"
        } else if path.ends_with(".py") || path.ends_with(".pyw") {
            "python"
        } else if path.ends_with(".cs") {
            "csharp"
        } else if path.ends_with(".js") {
            "javascript"
        } else if path.ends_with(".ts") {
            "typescript"
        } else if path.ends_with(".go") {
            "go"
        } else if path.ends_with(".rs") {
            "rust"
        } else if path.ends_with(".xml") || path.ends_with(".config") {
            "xml"
        } else if path.ends_with(".json") {
            "json"
        } else if path.ends_with(".yaml") || path.ends_with(".yml") {
            "yaml"
        } else {
            "source file"
        }
    }

    /// Add single insight item to content
    fn add_insight_item(&self, content: &mut String, insight: &CodeInsight) {
        content.push_str(&format!(
            "- **{}** (`{}`)\n",
            insight.code_dossier.name,
            insight.code_dossier.file_path.display()
        ));

        if let Some(desc) = &insight.code_dossier.description {
            content.push_str(&format!("  - Description: {}\n", desc));
        }

        // Add interface information for SQL objects
        if !insight.code_dossier.interfaces.is_empty() {
            content.push_str("  - SQL Objects: ");
            content.push_str(&insight.code_dossier.interfaces.join(", "));
            content.push_str("\n");
        }

        // Add source summary if available (only for high-importance files)
        if !insight.code_dossier.source_summary.is_empty() && insight.code_dossier.importance_score > 0.5 {
            content.push_str("  - Source Preview:\n");
            content.push_str(&format!("    ```{}\n", self.determine_code_language(&insight.code_dossier.file_path)));
            // Limit to first 150 chars to reduce token usage
            let preview: String = insight.code_dossier.source_summary.chars().take(150).collect();
            for line in preview.lines().take(8) {
                content.push_str(&format!("    {}\n", line));
            }
            if insight.code_dossier.source_summary.len() > 150 {
                content.push_str("    ...\n");
            }
            content.push_str("    ```\n");
        }

        content.push_str("\n");
    }
}