#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
#![deny(unused_imports)]
#![deny(unused_variables)]
#![allow(clippy::needless_range_loop)]
#![allow(clippy::single_match)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::only_used_in_recursion)]
#![allow(clippy::if_same_then_else)]
#![allow(clippy::arc_with_non_send_sync)]
#![allow(clippy::manual_clamp)]
#[cfg(feature = "agent-daemon")]
pub mod agent; #[cfg(feature = "mcp-integration")]
pub mod agents; #[cfg(feature = "agents-md")]
pub mod agents_md; pub mod ast; #[cfg(feature = "claude-integration")]
pub mod claude_integration; pub mod cli;
pub mod contracts; #[cfg(feature = "demo")]
pub mod demo;
pub mod docs_enforcement; pub mod entropy; pub mod explain; pub mod graph; pub mod handlers;
pub mod maintenance; pub mod mcp; #[cfg(feature = "mcp-integration")]
pub mod mcp_integration; pub mod mcp_pmcp; pub mod mcp_server;
pub mod models;
#[cfg(feature = "mcp-integration")]
pub mod modules; pub mod prompts; pub mod protocol; pub mod qdd; pub mod quality; pub mod red_team; #[cfg(feature = "mcp-integration")]
pub mod resources; pub mod roadmap; pub mod scaffold;
pub mod services;
pub mod state; pub mod stateless_server;
pub mod tdg; pub mod test_performance;
#[cfg(feature = "mcp-integration")]
pub mod workflow; #[cfg(feature = "unified-protocol")]
pub mod unified_protocol;
pub mod unified_quality; pub mod utils;
pub mod viz; #[cfg(feature = "wasm-ast")]
pub mod wasm;
use anyhow::Result;
use lru::LruCache;
use std::num::NonZeroUsize;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::info;
use crate::models::template::TemplateResource;
use crate::services::renderer::TemplateRenderer;
pub type MetadataCache = Arc<RwLock<LruCache<String, Arc<TemplateResource>>>>;
pub type ContentCache = Arc<RwLock<LruCache<String, Arc<str>>>>;
pub use crate::models::template::TemplateResource as PublicTemplateResource;
pub use crate::services::renderer::TemplateRenderer as PublicTemplateRenderer;
pub struct S3Client;
#[async_trait::async_trait]
pub trait TemplateServerTrait: Send + Sync {
async fn get_template_metadata(&self, uri: &str) -> Result<Arc<TemplateResource>>;
async fn get_template_content(&self, s3_key: &str) -> Result<Arc<str>>;
async fn list_templates(&self, prefix: &str) -> Result<Vec<Arc<TemplateResource>>>;
fn get_renderer(&self) -> &TemplateRenderer;
fn get_metadata_cache(&self) -> Option<&MetadataCache>;
fn get_content_cache(&self) -> Option<&ContentCache>;
fn get_s3_client(&self) -> Option<&S3Client>;
fn get_bucket_name(&self) -> Option<&str>;
}
pub struct TemplateServer {
pub s3_client: S3Client,
pub bucket_name: String,
pub metadata_cache: MetadataCache,
pub content_cache: ContentCache,
pub renderer: TemplateRenderer,
}
#[cfg_attr(coverage_nightly, coverage(off))]
impl TemplateServer {
pub async fn new() -> Result<Self> {
let cache_size = 1024;
Ok(Self {
s3_client: S3Client,
bucket_name: "dummy".to_string(),
metadata_cache: Arc::new(RwLock::new(LruCache::new(
NonZeroUsize::new(cache_size / 2).expect("internal error"),
))),
content_cache: Arc::new(RwLock::new(LruCache::new(
NonZeroUsize::new(cache_size).expect("internal error"),
))),
renderer: TemplateRenderer::new()?,
})
}
pub async fn warm_cache(&self) -> Result<()> {
let common_templates = vec![
"template://makefile/rust/cli",
"template://makefile/deno/cli",
"template://makefile/python-uv/cli",
"template://readme/rust/cli",
"template://gitignore/rust/cli",
];
info!(
"Warming cache with {} common templates",
common_templates.len()
);
for template_uri in common_templates {
match self.get_template_metadata(template_uri).await {
Ok(resource) => {
let _ = self.get_template_content(&resource.s3_object_key).await;
}
Err(e) => {
info!("Failed to warm cache for {}: {}", template_uri, e);
}
}
}
Ok(())
}
pub async fn get_template_metadata(&self, _uri: &str) -> Result<Arc<TemplateResource>> {
Err(anyhow::anyhow!(
"TemplateServer with S3 is deprecated. Use StatelessTemplateServer instead."
))
}
pub async fn get_template_content(&self, _s3_key: &str) -> Result<Arc<str>> {
Err(anyhow::anyhow!(
"TemplateServer with S3 is deprecated. Use StatelessTemplateServer instead."
))
}
}
#[async_trait::async_trait]
#[cfg_attr(coverage_nightly, coverage(off))]
impl TemplateServerTrait for TemplateServer {
async fn get_template_metadata(&self, uri: &str) -> Result<Arc<TemplateResource>> {
self.get_template_metadata(uri).await
}
async fn get_template_content(&self, s3_key: &str) -> Result<Arc<str>> {
self.get_template_content(s3_key).await
}
async fn list_templates(&self, _prefix: &str) -> Result<Vec<Arc<TemplateResource>>> {
Err(anyhow::anyhow!(
"TemplateServer with S3 is deprecated. Use StatelessTemplateServer instead."
))
}
fn get_renderer(&self) -> &TemplateRenderer {
&self.renderer
}
fn get_metadata_cache(&self) -> Option<&MetadataCache> {
Some(&self.metadata_cache)
}
fn get_content_cache(&self) -> Option<&ContentCache> {
Some(&self.content_cache)
}
fn get_s3_client(&self) -> Option<&S3Client> {
Some(&self.s3_client)
}
fn get_bucket_name(&self) -> Option<&str> {
Some(&self.bucket_name)
}
}
pub use models::error::TemplateError;
pub use models::template::{ParameterSpec, ParameterType};
pub use services::template_service::{
generate_template, list_templates, scaffold_project, search_templates, validate_template,
};
#[cfg_attr(coverage_nightly, coverage(off))]
pub async fn run_mcp_server<T: TemplateServerTrait + 'static>(server: Arc<T>) -> Result<()> {
use std::io::{self, BufRead};
use tracing::info;
info!("MCP server ready, waiting for requests on stdin...");
let stdin = io::stdin();
let mut stdout = io::stdout();
for line in stdin.lock().lines() {
let line = line?;
if should_skip_line(&line) {
continue;
}
process_mcp_line(&line, Arc::clone(&server), &mut stdout).await?;
}
Ok(())
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn should_skip_line(line: &str) -> bool {
line.trim().is_empty()
}
async fn process_mcp_line<T: TemplateServerTrait + 'static, W: std::io::Write>(
line: &str,
server: Arc<T>,
stdout: &mut W,
) -> Result<()> {
match parse_mcp_request(line) {
Ok(request) => handle_valid_request(request, server, stdout).await,
Err(e) => handle_parse_error(&e, stdout),
}
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn parse_mcp_request(line: &str) -> Result<crate::models::mcp::McpRequest> {
serde_json::from_str(line).map_err(anyhow::Error::from)
}
async fn handle_valid_request<T: TemplateServerTrait + 'static, W: std::io::Write>(
request: crate::models::mcp::McpRequest,
server: Arc<T>,
stdout: &mut W,
) -> Result<()> {
use tracing::info;
info!(
"Received request: method={}, id={:?}",
request.method, request.id
);
let response = handlers::handle_request(server, request).await;
write_response_to_stdout(&response, stdout)
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn handle_parse_error<W: std::io::Write>(error: &anyhow::Error, stdout: &mut W) -> Result<()> {
use crate::models::mcp::McpResponse;
use tracing::error;
error!("Failed to parse JSON-RPC request: {}", error);
let error_response = McpResponse::error(
serde_json::Value::Null,
-32700,
format!("Parse error: {error}"),
);
write_response_to_stdout(&error_response, stdout)
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn write_response_to_stdout<W: std::io::Write>(
response: &crate::models::mcp::McpResponse,
stdout: &mut W,
) -> Result<()> {
let response_json = serde_json::to_string(response)?;
writeln!(stdout, "{response_json}")?;
stdout.flush()?;
Ok(())
}
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
#[path = "../tests/template_rendering.rs"]
mod template_rendering;
#[path = "../tests/claude_code_e2e.rs"]
mod claude_code_e2e;
#[path = "../tests/mcp_protocol.rs"]
mod mcp_protocol;
#[path = "../tests/template_resources.rs"]
mod template_resources;
#[path = "../tests/helpers.rs"]
mod helpers;
#[path = "../tests/cli_integration_tests.rs"]
mod cli_integration_tests;
#[path = "../tests/quality_checks_property_tests.rs"]
mod quality_checks_property_tests;
#[path = "../tests/prompts.rs"]
mod prompts;
#[path = "../tests/binary_size.rs"]
mod binary_size;
#[path = "../tests/error.rs"]
mod error;
#[path = "../tests/cache.rs"]
mod cache;
#[path = "../tests/tools.rs"]
mod tools;
#[path = "../tests/analyze_cli_tests.rs"]
mod analyze_cli_tests;
#[path = "../tests/cli_integration_full.rs"]
mod cli_integration_full;
#[path = "../tests/resources.rs"]
mod resources;
#[path = "../tests/lib.rs"]
mod lib_tests;
#[path = "../tests/build_naming_validation.rs"]
mod build_naming_validation;
#[path = "../tests/ast_e2e.rs"]
mod ast_e2e;
#[path = "../tests/cli_tests.rs"]
mod cli_tests;
#[path = "../tests/churn.rs"]
mod churn;
#[path = "../tests/cli_simple_tests.rs"]
mod cli_simple_tests;
#[path = "../tests/deep_context_simplified_tests.rs"]
mod deep_context_simplified_tests;
#[cfg(feature = "demo")]
#[path = "../tests/demo_comprehensive_tests.rs"]
mod demo_comprehensive_tests;
#[cfg(feature = "unified-protocol")]
#[path = "../tests/http_adapter_tests.rs"]
mod http_adapter_tests;
#[path = "../tests/cache_comprehensive_tests.rs"]
mod cache_comprehensive_tests;
#[cfg(feature = "unified-protocol")]
#[path = "../tests/unified_protocol_tests.rs"]
mod unified_protocol_tests;
#[path = "../tests/models.rs"]
mod models_tests;
#[path = "../tests/e2e_full_coverage.rs"]
mod e2e_full_coverage;
#[path = "../tests/additional_coverage.rs"]
mod additional_coverage;
#[path = "../tests/error_handling.rs"]
mod error_handling;
#[path = "../tests/cli_comprehensive_tests.rs"]
mod cli_comprehensive_tests;
#[path = "../tests/cli_property_tests.rs"]
mod cli_property_tests;
mod extreme_tdd_deep_context_quality_fixes;
#[path = "../tests/ast_regression_test.rs"]
mod ast_regression_test;
#[path = "../tests/dead_code_verification.rs"]
mod dead_code_verification;
#[path = "../tests/complexity_distribution_verification.rs"]
mod complexity_distribution_verification;
#[path = "../tests/extreme_tdd_concurrency_fix.rs"]
mod extreme_tdd_concurrency_fix;
#[path = "../tests/extreme_tdd_language_support.rs"]
mod extreme_tdd_language_support;
#[path = "../tests/extreme_tdd_smart_bounds.rs"]
mod extreme_tdd_smart_bounds;
#[path = "../tests/multi_language_deep_context_tests.rs"]
mod multi_language_deep_context_tests;
#[path = "../tests/language_regression_tests.rs"]
mod language_regression_tests;
#[path = "../tests/hallucination_detection_tests.rs"]
mod hallucination_detection_tests;
#[path = "../tests/unified_rust_analyzer_tests.rs"]
mod unified_rust_analyzer_tests;
#[path = "../tests/unified_typescript_analyzer_tests.rs"]
mod unified_typescript_analyzer_tests;
#[cfg(feature = "python-ast")]
#[path = "../tests/unified_python_analyzer_tests.rs"]
mod unified_python_analyzer_tests;
#[cfg(feature = "go-ast")]
#[path = "../tests/unified_go_analyzer_tests.rs"]
mod unified_go_analyzer_tests;
#[cfg(feature = "wasm-ast")]
#[path = "../tests/unified_wasm_analyzer_tests.rs"]
mod unified_wasm_analyzer_tests;
#[cfg(feature = "shell-ast")]
#[path = "../tests/unified_bash_analyzer_tests.rs"]
mod unified_bash_analyzer_tests;
#[path = "../tests/audit_provability_retest.rs"]
mod audit_provability_retest;
#[path = "../tests/cli_coverage_boost.rs"]
mod cli_coverage_boost;
#[path = "../tests/clap_argument_parsing_tests.rs"]
mod clap_argument_parsing_tests;
#[path = "../tests/clap_command_structure_tests.rs"]
mod clap_command_structure_tests;
#[path = "../tests/clap_env_var_tests.rs"]
mod clap_env_var_tests;
#[path = "../tests/cli_basic_tests.rs"]
mod cli_basic_tests;
#[path = "../tests/code_smell_comprehensive_tests.rs"]
mod code_smell_comprehensive_tests;
#[path = "../tests/coverage_boost_analyze_defects_handler.rs"]
mod coverage_boost_analyze_defects_handler;
#[path = "../tests/coverage_boost_analyzer_formatting.rs"]
mod coverage_boost_analyzer_formatting;
#[path = "../tests/coverage_boost_ast_strategies.rs"]
mod coverage_boost_ast_strategies;
#[path = "../tests/coverage_boost_big_o.rs"]
mod coverage_boost_big_o;
#[path = "../tests/coverage_boost_brick_score.rs"]
mod coverage_boost_brick_score;
#[path = "../tests/coverage_boost_check_handlers.rs"]
mod coverage_boost_check_handlers;
#[path = "../tests/coverage_boost_chunker.rs"]
mod coverage_boost_chunker;
#[path = "../tests/coverage_boost_churn.rs"]
mod coverage_boost_churn;
#[path = "../tests/coverage_boost_cli_enums.rs"]
mod coverage_boost_cli_enums;
#[path = "../tests/coverage_boost_complexity.rs"]
mod coverage_boost_complexity;
#[path = "../tests/coverage_boost_comply_cb_detect.rs"]
mod coverage_boost_comply_cb_detect;
#[path = "../tests/coverage_boost_comprehensive.rs"]
mod coverage_boost_comprehensive;
#[path = "../tests/coverage_boost_configuration_service.rs"]
mod coverage_boost_configuration_service;
#[path = "../tests/coverage_boost_coverage_improvement2.rs"]
mod coverage_boost_coverage_improvement2;
#[path = "../tests/coverage_boost_coverage_improvement.rs"]
mod coverage_boost_coverage_improvement;
#[path = "../tests/coverage_boost_dag_builder.rs"]
mod coverage_boost_dag_builder;
#[path = "../tests/coverage_boost_dead_code_pure.rs"]
mod coverage_boost_dead_code_pure;
#[path = "../tests/coverage_boost_dead_code.rs"]
mod coverage_boost_dead_code;
#[path = "../tests/coverage_boost_debug_analysis.rs"]
mod coverage_boost_debug_analysis;
#[path = "../tests/coverage_boost_defect_analyzers.rs"]
mod coverage_boost_defect_analyzers;
#[path = "../tests/coverage_boost_defect_report.rs"]
mod coverage_boost_defect_report;
#[path = "../tests/coverage_boost_defect_report_svc2.rs"]
mod coverage_boost_defect_report_svc2;
#[path = "../tests/coverage_boost_defect_report_svc.rs"]
mod coverage_boost_defect_report_svc;
#[path = "../tests/coverage_boost_doc_validator.rs"]
mod coverage_boost_doc_validator;
#[path = "../tests/coverage_boost_enforce.rs"]
mod coverage_boost_enforce;
#[path = "../tests/coverage_boost_enhanced_reporting2.rs"]
mod coverage_boost_enhanced_reporting2;
#[path = "../tests/coverage_boost_enhanced_reporting3.rs"]
mod coverage_boost_enhanced_reporting3;
#[path = "../tests/coverage_boost_enhanced_reporting.rs"]
mod coverage_boost_enhanced_reporting;
#[path = "../tests/coverage_boost_error2.rs"]
mod coverage_boost_error2;
#[path = "../tests/coverage_boost_error.rs"]
mod coverage_boost_error;
#[path = "../tests/coverage_boost_facades.rs"]
mod coverage_boost_facades;
#[path = "../tests/coverage_boost_falsification.rs"]
mod coverage_boost_falsification;
#[path = "../tests/coverage_boost_file_health.rs"]
mod coverage_boost_file_health;
#[path = "../tests/coverage_boost_language_analyzer2.rs"]
mod coverage_boost_language_analyzer2;
#[path = "../tests/coverage_boost_language_analyzer.rs"]
mod coverage_boost_language_analyzer;
#[path = "../tests/coverage_boost_lint_hotspot_handlers.rs"]
mod coverage_boost_lint_hotspot_handlers;
#[path = "../tests/coverage_boost_lint_hotspot.rs"]
mod coverage_boost_lint_hotspot;
#[path = "../tests/coverage_boost_maintenance.rs"]
mod coverage_boost_maintenance;
#[path = "../tests/coverage_boost_mermaid.rs"]
mod coverage_boost_mermaid;
#[path = "../tests/coverage_boost_metric_trends.rs"]
mod coverage_boost_metric_trends;
#[path = "../tests/coverage_boost_ml_quality.rs"]
mod coverage_boost_ml_quality;
#[path = "../tests/coverage_boost_mutation.rs"]
mod coverage_boost_mutation;
#[path = "../tests/coverage_boost_normalized_score.rs"]
mod coverage_boost_normalized_score;
#[path = "../tests/coverage_boost_onboarding.rs"]
mod coverage_boost_onboarding;
#[path = "../tests/coverage_boost_perfection_score.rs"]
mod coverage_boost_perfection_score;
#[path = "../tests/coverage_boost_performance.rs"]
mod coverage_boost_performance;
#[path = "../tests/coverage_boost_polyglot.rs"]
mod coverage_boost_polyglot;
#[path = "../tests/coverage_boost_proof_annotations_handler.rs"]
mod coverage_boost_proof_annotations_handler;
#[path = "../tests/coverage_boost_provability_handler.rs"]
mod coverage_boost_provability_handler;
#[path = "../tests/coverage_boost_qdd.rs"]
mod coverage_boost_qdd;
#[path = "../tests/coverage_boost_quality_gate.rs"]
mod coverage_boost_quality_gate;
#[path = "../tests/coverage_boost_ranking.rs"]
mod coverage_boost_ranking;
#[path = "../tests/coverage_boost_refactor.rs"]
mod coverage_boost_refactor;
#[path = "../tests/coverage_boost_services1.rs"]
mod coverage_boost_services1;
#[path = "../tests/coverage_boost_services2.rs"]
mod coverage_boost_services2;
#[path = "../tests/coverage_boost_services3.rs"]
mod coverage_boost_services3;
#[path = "../tests/coverage_boost_services4.rs"]
mod coverage_boost_services4;
#[path = "../tests/coverage_boost_signal_collector.rs"]
mod coverage_boost_signal_collector;
#[path = "../tests/coverage_boost_similarity.rs"]
mod coverage_boost_similarity;
#[path = "../tests/coverage_boost_tdg_calculator.rs"]
mod coverage_boost_tdg_calculator;
#[path = "../tests/coverage_boost_tdg.rs"]
mod coverage_boost_tdg;
#[path = "../tests/coverage_boost_ticket_handlers.rs"]
mod coverage_boost_ticket_handlers;
#[path = "../tests/coverage_boost_unified_ast2.rs"]
mod coverage_boost_unified_ast2;
#[path = "../tests/coverage_boost_unified_ast3.rs"]
mod coverage_boost_unified_ast3;
#[path = "../tests/coverage_boost_unified_ast.rs"]
mod coverage_boost_unified_ast;
#[path = "../tests/diagnose_tests.rs"]
mod diagnose_tests;
#[path = "../tests/gitignore_respect_tests.rs"]
mod gitignore_respect_tests;
#[path = "../tests/kaizen_reliability_patterns.rs"]
mod kaizen_reliability_patterns;
#[path = "../tests/kaizen_test_optimizations.rs"]
mod kaizen_test_optimizations;
#[path = "../tests/metric_accuracy_suite.rs"]
mod metric_accuracy_suite;
#[path = "../tests/project_meta_integration_test.rs"]
mod project_meta_integration_test;
#[path = "../tests/test_include_patterns.rs"]
mod test_include_patterns;
}
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod property_tests {
use proptest::prelude::*;
proptest! {
#[test]
fn basic_property_stability(_input in ".*") {
prop_assert!(true);
}
#[test]
fn module_consistency_check(_x in 0u32..1000) {
prop_assert!(_x < 1001);
}
}
}
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod lib_unit_tests {
use super::*;
#[test]
fn test_should_skip_line() {
assert!(should_skip_line(""));
assert!(should_skip_line(" "));
assert!(should_skip_line("\t\n"));
assert!(!should_skip_line("{\"method\":\"test\"}"));
}
#[test]
fn test_parse_mcp_request_valid() {
let line = r#"{"jsonrpc":"2.0","method":"test","id":1}"#;
let result = parse_mcp_request(line);
assert!(result.is_ok());
}
#[test]
fn test_parse_mcp_request_invalid() {
let line = "not valid json";
let result = parse_mcp_request(line);
assert!(result.is_err());
}
#[test]
fn test_write_response_to_stdout() {
use crate::models::mcp::McpResponse;
let response =
McpResponse::error(serde_json::Value::Null, -32600, "Test error".to_string());
let mut output = Vec::new();
let result = write_response_to_stdout(&response, &mut output);
assert!(result.is_ok());
assert!(!output.is_empty());
}
#[test]
fn test_handle_parse_error() {
let error = anyhow::anyhow!("Test error");
let mut output = Vec::new();
let result = handle_parse_error(&error, &mut output);
assert!(result.is_ok());
let output_str = String::from_utf8(output).unwrap();
assert!(output_str.contains("Parse error"));
}
#[tokio::test]
async fn test_template_server_new() {
let server = TemplateServer::new().await;
assert!(server.is_ok());
}
#[tokio::test]
async fn test_template_server_deprecated_methods() {
let server = TemplateServer::new().await.unwrap();
let metadata_result = server.get_template_metadata("test://uri").await;
assert!(metadata_result.is_err());
assert!(metadata_result
.unwrap_err()
.to_string()
.contains("deprecated"));
let content_result = server.get_template_content("test_key").await;
assert!(content_result.is_err());
assert!(content_result
.unwrap_err()
.to_string()
.contains("deprecated"));
}
#[tokio::test]
async fn test_template_server_trait_methods() {
let server = TemplateServer::new().await.unwrap();
let _ = server.get_renderer();
assert!(server.get_metadata_cache().is_some());
assert!(server.get_content_cache().is_some());
assert!(server.get_s3_client().is_some());
assert!(server.get_bucket_name().is_some());
let list_result = TemplateServerTrait::list_templates(&server, "").await;
assert!(list_result.is_err());
}
#[test]
fn test_s3_client_struct() {
let _client = S3Client; }
#[tokio::test]
async fn test_process_mcp_line_valid() {
let server = Arc::new(TemplateServer::new().await.unwrap());
let mut output = Vec::new();
let line = r#"{"jsonrpc":"2.0","method":"tools/list","id":1}"#;
let result = process_mcp_line(line, server, &mut output).await;
assert!(result.is_ok() || result.is_err()); }
#[tokio::test]
async fn test_process_mcp_line_invalid_json() {
let server = Arc::new(TemplateServer::new().await.unwrap());
let mut output = Vec::new();
let line = "not json at all";
let result = process_mcp_line(line, server, &mut output).await;
assert!(result.is_ok());
let output_str = String::from_utf8(output).unwrap();
assert!(output_str.contains("Parse error"));
}
#[tokio::test]
async fn test_template_server_warm_cache() {
let server = TemplateServer::new().await.unwrap();
let result = server.warm_cache().await;
assert!(result.is_ok());
}
}