Code peculiar smell self-evolution detection and restoration system and method based on double agents

The code smell detection and repair system, which uses a dual-agent architecture and a human feedback loop, achieves accurate identification and automated repair of code smells. It solves the problems of high false alarm rate, low recall rate and lack of repair capability in existing technologies, and realizes the self-evolution and continuous optimization of the system.

CN121597565APending Publication Date: 2026-03-03HUAZHONG UNIV OF SCI & TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202511695798.0
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-11-19
Publication Date
2026-03-03

AI Technical Summary

Technical Problem

Existing technologies suffer from high false alarm rates and low recall rates in code smell detection, and lack the ability to provide automated repair suggestions. They also cannot achieve continuous evolution of system capabilities through feedback mechanisms, resulting in limited practicality and adaptability.

Method used

It adopts a dual-agent architecture, which works in collaboration between a rule analysis and strategy generation agent (Agent1) and a code detection and repair agent (Agent2), combined with a Model Context Protocol (MCP) server for accurate code slicing, and introduces a human-in-the-Loop for continuous self-optimization, dynamically generating prompts and repair suggestions.

Benefits of technology

It significantly reduces false positive and false negative rates, achieving a balance between detection accuracy and recall. It provides an integrated solution from problem discovery to remediation suggestions, and continuously iterates and optimizes detection capabilities through an active learning mechanism and feedback loop, solving the problem of rigidity in traditional tools.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121597565A_ABST
    Figure CN121597565A_ABST
Patent Text Reader

Abstract

The invention relates to the field of code detection and repair, in particular to a code peculiar smell self-evolution detection and repair system and method based on double agents. According to the system, through cooperative work of a rule analysis and strategy generation agent (Agent1) and a code detection and repair agent (Agent2) and in combination with precise code context slices provided by a model context protocol (MCP) server, precise recognition of code peculiar smell, root cause analysis, repair suggestions and automatic generation of repair codes are achieved. Besides, the Agent1 is based on a retrieval enhancement generation (RAG) mechanism, a historical success strategy is intelligently retrieved from a rule knowledge base, a targeted detection configuration and cue word template is automatically generated, and a high-cost mode of manually compiling, testing and iterating cue words in a traditional method is changed. The system also introduces an artificial feedback loop, so that each artificial correction can be attributed and analyzed and used for updating a corresponding knowledge base, thereby driving the whole system to have a continuous self-optimization capability.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of code detection and repair, specifically to a code smell self-evolution detection and repair system and method based on dual agents. Background Technology

[0002] With the continuous increase in the complexity of software systems, code quality maintenance has become a core challenge in the software development process. Code smells, as key signals characterizing potential design flaws, are crucial for reducing maintenance costs and preventing defects through early identification and remediation. Traditional code smell detection relies heavily on developer experience and manual code review, which is inefficient and difficult to scale. Therefore, automated detection technologies have emerged to systematically assist developers in identifying and improving code quality, thereby ensuring the long-term maintainability and robustness of software.

[0003] Currently, existing technologies in this field mainly revolve around rule-based static analysis, software metrics, machine learning, and large language model applications. Rule-based tools rely on predefined code patterns for matching. While widely applicable, their fixed rules fail to understand the specific semantics and context of the code, resulting in high false positives and high false negatives. Software metrics-based methods identify anomalous smells through quantitative indicators (such as cyclomatic complexity and coupling), but threshold settings are often subjective and struggle to capture complex anomalous smell patterns involving multiple code elements. Although machine learning methods attempt to improve detection capabilities through data-driven approaches, they are still limited by the complexity of feature engineering, the large amount of training data required, and poor model interpretability, leading to insufficient generalization ability and results that are difficult for developers to accept.

[0004] In recent years, although methods for code smell detection and repair using large language models have shown some potential in semantic understanding, they face significant challenges in practical applications, including limitations in context length, insufficient analysis depth, and the inability to continuously learn. Each analysis is independent, making it impossible to accumulate historical experience, and the output results are unstructured, making it difficult to integrate into automated development processes. Particularly noteworthy is that conventional LLM detection methods heavily rely on human experience when constructing effective prompts, resulting in huge manpower costs and long iteration cycles, severely restricting the large-scale application of this technology. Overall, existing technologies have failed to effectively solve the balance between detection accuracy and recall, lack the ability to provide automated repair suggestions, or consume excessive manpower and time, and cannot achieve continuous evolution of system capabilities through feedback mechanisms, thus limiting their practicality and adaptability in practice. Summary of the Invention

[0005] To overcome the shortcomings of existing technologies, this invention provides a self-evolving code smell detection and repair system and method based on dual agents. This system utilizes the collaborative work of a rule analysis and strategy generation agent (Agent1) and a code detection and repair agent (Agent2), combined with a Model Context Protocol (MCP) server for accurate code slicing, and introduces a human-in-the-Loop for continuous self-optimization. This solution significantly reduces false positives and false negatives, provides repair suggestions and code for confirmed smells, and continuously improves detection capabilities through iterative updates to the knowledge base, achieving a leap from "static analysis" to "intelligent diagnosis and repair."

[0006] According to one aspect of the present invention, a code odor self-evolution detection and repair system based on dual agents is provided, comprising: The rule analysis and strategy generation agent, Agent1, first parses the rules and extracts key features; then it accesses the rule knowledge base to retrieve successful strategies for handling the corresponding rules in the past, and obtains the corresponding code slice type, prompt word template, and positive and negative code examples; finally, it combines the current rule features, historical strategies, and code examples to generate a complete detection configuration. The code detection and repair agent Agent2 first performs a preliminary scan of the codebase using static analysis tools, generating alerts and formatting the output. The results are then saved according to rules. Next, based on the detection configuration, the agent calls a model context protocol server to slice the code involved in each alert, obtaining code context fragments containing complete semantic relationships and related data dependencies. Then, positive and negative code examples are quantitatively evaluated, selecting up to six typical examples most relevant to the current alert code. The precisely sliced ​​code, rule descriptions, selected positive and negative examples, and constructed prompt words are then integrated and submitted to a large language model for in-depth analysis and reasoning, completing the process from false alarm screening to root cause analysis of actual alerts and generation of repair suggestions. Finally, the output of the large language model is structured and parsed, including false alarm determination, detailed reasons, repair suggestions, and executable code patches, and rule attributes are marked for each result.

[0007] Preferably, the model context protocol server is used to provide a code slicing strategy, specifically including: For variable-related slices, the complete definition and usage chain of key variables involved in the alert code line are obtained by parsing the abstract syntax tree; For statement-level slicing, extract the current alarm code line for expression comparison operations; For context slicing, when the relational information involved in the alarm is limited to the vicinity of the code line, the range of lines to be sliced ​​forward and backward is dynamically determined based on the alarm behavior center; For structural integrity slices, for alerts related to switch structures, the complete structural code is extracted by parsing the abstract syntax tree; For macro definition slices, when the alert line involves a macro call, the abstract syntax tree is used to locate and obtain the complete macro definition content. For annotation slices, the complete syntactic module in which the annotation is located is obtained based on pattern matching technology; For function slicing, when an alert is located inside a function and may be related to function parameters, the complete function body structure containing the alert code is extracted by parsing the abstract syntax tree. Overly long functions are intelligently pruned to remove remote, low-relevance code, ensuring the conciseness of the slice.

[0008] Preferably, the system further includes: The rule knowledge base stores the mapping relationship between rule descriptions, positive and negative example code, slicing strategies, and prompt word templates, as well as cross-language rule similarity. The case knowledge base stores typical error / boundary cases that have been manually verified, as well as categorized data of simple / complex and advisory / severity rules.

[0009] Preferably, the system further includes an intelligent feedback strategy: First, the detection results are automatically graded, and the sampling priority is determined by the complexity and severity of the rules. For detection results based on simple or suggested rules, they are automatically adopted but subject to periodic sampling and review; for detection results based on complex rules, they are submitted for manual review first; and for detection results based on severe rules, they are forced into the manual review process.

[0010] Preferably, the intelligent feedback strategy further includes: The system status is comprehensively evaluated using a multidimensional loss function (Loss). Loss=α×ClassificationLoss+β×DiversityLoss; Among them, ClassificationLoss is the classification loss, which quantifies the performance degradation of the model task by calculating the 1 - F1-Score of the recent human feedback dataset. 1 - F1-Score is the harmonic mean of precision and recall. DiversityLoss is the diversity loss, which penalizes sampling bias by evaluating the uniformity of the distribution of labeled samples in the code vector space, ensuring the diversity of selected samples. Loss provides a basis for active learning sampling, prioritizing the selection of samples with high classification loss and the ability to improve diversity for submission to human review.

[0011] Preferably, the system further includes an error attribution analysis module: If the error stems from an improper slicing strategy, a problem with the prompt word template, or an incomplete and unrepresentative positive and negative code example library, it will be determined to be the responsibility of Agent1, and the corresponding correction strategy will be recorded in the rule knowledge base. If the error stems from an error in the LLM's judgment within sufficient context, it is determined to be the responsibility of Agent2, and the case is stored in the case knowledge base.

[0012] Preferably, the system further includes an intelligent collection mechanism: First, a lightweight large language model is used to calculate the semantic similarity between the current feedback case and the existing positive and negative examples in the knowledge base; Then, the training-free Bayesian method is applied to quantify the uncertainty of the lightweight model in similarity judgment. By setting an uncertainty threshold, it is determined whether the current case should be included as a new example in the knowledge base.

[0013] This invention also provides a method for self-evolutionary detection and repair of code smells based on dual proxies, including: Receive new rule set definitions, language specifications, and the project codebase to be tested; The rule analysis and strategy generation agent Agent1 is based on the retrieval enhancement generation RAG mechanism. It intelligently retrieves the slicing methods of historical similar rules, related positive and negative code examples and prompt word templates from the rule knowledge base, and dynamically generates the optimal detection configuration. The code detection and repair agent Agent2 uses basic static analysis tools to generate an initial list of alerts and saves the results in a formatted and categorized manner. Agent2 invokes the Model Context Protocol Server based on the strategy provided by Agent1, performs precise code slicing, and extracts the code context containing complete semantic relationships and related data dependencies; Agent2 integrates alarm slice code and data dependencies, and uses the training free Bayesian method to select the 6 most relevant code examples to construct complete prompt words; Agent2 submits the refined prompts to the large language model for in-depth analysis and reasoning, and parses and post-processes the output to generate structured results. Present the final judgment result, detailed repair suggestions, and executable code patch to the user; Entering the stage of human feedback and knowledge update, expert correction opinions are collected through intelligent feedback strategies, and system performance defects are quantified based on multi-dimensional loss assessment functions. This drives the error attribution of feedback data and intelligent updates of the knowledge base, forming a closed loop of continuous optimization.

[0014] The present invention also provides a computer device, including a memory and a processor, wherein the memory stores a computer program, and the processor executes the computer program to implement the steps of a code odor self-evolution detection and repair method based on dual agents.

[0015] The present invention also provides a non-transitory computer read storage medium that stores computer instructions that cause the computer to execute steps of a code smell self-evolution detection and repair method based on dual agents.

[0016] Compared with the prior art, the beneficial effects of the present invention are as follows: (1) In this invention, through deep semantic understanding and precise context slicing, the false positive rate and false negative rate are significantly reduced, and an effective balance between detection accuracy and recall rate is achieved.

[0017] (2) It provides an integrated solution from problem discovery to repair suggestions, which surpasses the limitations of traditional tools that can only "detect" but not "repair". More importantly, Agent1's intelligent strategy generation enables the dynamic and automated construction of prompt words, which fundamentally solves the pain point of conventional LLM methods that consume a lot of manpower and time in prompt word construction.

[0018] (3) Through active learning mechanism and feedback loop, it can continuously iterate and optimize its knowledge base and strategy by utilizing the artificial feedback data generated during operation, so that the detection capability will continue to be enhanced as the frequency of use increases, thus solving the problem of the solidification of the capabilities of traditional tools.

[0019] (4) It has good versatility and scalability, and can support multiple programming languages ​​and custom rules by adapting to different MCP slicing strategies. Attached Figure Description

[0020] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the accompanying drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the accompanying drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0021] Figure 1 This is a schematic diagram illustrating the working principle of a code odor self-evolution detection and repair system based on dual agents, provided in an embodiment of the present invention. Detailed Implementation

[0022] The terms “comprising” and “having”, and any variations thereof, in the specification, claims, and accompanying drawings of this invention are intended to cover a non-exclusive inclusion, such as a process, method, system, product, or apparatus that includes a series of steps or units, not necessarily limited to those explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.

[0023] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention. In addition, the technical features of the various embodiments or individual embodiments provided by the present invention can be arbitrarily combined to form new technical solutions. Such combinations are not bound by the order of steps and / or structural composition patterns, but must be based on the ability of those skilled in the art to implement them. When the combination of technical solutions is contradictory or cannot be implemented, it should be considered that such a combination of technical solutions does not exist and is not within the scope of protection claimed by the present invention.

[0024] To better explain this plan, some terms are explained below: Large Language Models (LLMs) are deep learning-based artificial intelligence models, typically built upon deep neural networks containing hundreds of billions or even trillions of parameters. These models are pre-trained on massive amounts of text data to understand and generate human natural language. LLMs exhibit emergent capabilities such as context learning, instruction following, and stepwise reasoning, enabling them to perform a variety of complex tasks, including text generation, translation, question answering, and code analysis and generation, without requiring dedicated model training for each task.

[0025] In the fields of artificial intelligence and computer science, an agent is a computational entity or program capable of perceiving its environment, making autonomous decisions, and executing corresponding actions to achieve specific goals or maximize its utility. Its core characteristics include autonomy, responsiveness, initiative, and sociality.

[0026] The Model Context Protocol (MCP) is an open protocol standard designed to standardize a secure and structured communication mechanism between large language models and external tools, data sources, and services, thereby enabling scalable and standardized integration of model capabilities.

[0027] Abstract Syntax Tree (AST) is a tree-like representation of the abstract syntax structure of source code. Each node represents a syntax structure (such as an expression, declaration, or statement) in the source code, and it serves as the basic intermediate representation for compilers to perform syntax analysis, code transformation, and static program analysis.

[0028] Tree-sitter is an open-source, high-performance incremental parser generation tool and its runtime library. It can quickly generate accurate abstract syntax trees (ASTs) for various programming languages, efficiently update the AST after code editing, and has good fault-tolerant parsing capabilities.

[0029] Code smells are structural features or patterns in software source code that may indicate potential design flaws, lead to maintenance difficulties, or increase the risk of errors. They are usually not functional errors themselves, but they reduce maintainability.

[0030] Static analysis tools are a class of software tools that examine program properties, discover potential errors, security vulnerabilities, violations of programming standards, or measure code quality by analyzing source code, bytecode, or binary code (rather than by running the program).

[0031] A false positive (FP) refers to a situation during testing or analysis where a system incorrectly identifies a negative (no problem) instance as a positive (problem). In software testing and static analysis, it specifically refers to a tool issuing an incorrect alert for code that is not defective.

[0032] A false negative (FN) refers to a situation during testing or analysis where the system fails to identify an instance that is actually positive (has a problem) and incorrectly classifies it as negative (has no problem). In software testing and static analysis, it specifically refers to the failure of tools to detect actual defects in the code.

[0033] Active learning is a machine learning paradigm in which learning algorithms proactively and selectively query users (usually annotation experts) to obtain labels for specific unlabeled data instances, with the goal of achieving the highest possible model performance with the fewest possible annotation queries.

[0034] Human-in-the-Loop is a human-computer interaction computing paradigm that embeds human cognition and judgment as key components into the closed loop of an artificial intelligence system. Humans review, correct, or provide guidance feedback on the system's predictions, decisions, or outputs, and the system uses this feedback to learn and optimize.

[0035] Retrieval-Augmented Generation (RAG) is a framework that combines information retrieval technology with the generation capabilities of large language models. Its core idea is to retrieve information fragments related to a given query from an external knowledge base before the large language model generates an answer, and use this information as a hint for the context-enhanced generation process, in order to generate more factually accurate, relevant and timely content.

[0036] Confidence level typically refers to the degree of certainty that a machine learning model or statistical model is about the correctness of its output predictions, and is often quantified in the form of probability values ​​or percentages.

[0037] Precision is a metric for evaluating the performance of a classification model. It is calculated as the proportion of true positives out of all predictions that are true positives (the sum of true positives and false positives). High precision means a low false positive rate.

[0038] Recall is a metric for evaluating the performance of a classification model. It is calculated as the proportion of true positives to all true positives (the sum of true positives and false negatives). A high recall rate means a low false negative rate.

[0039] The F1 score is the harmonic mean of precision and recall. It is a metric used to comprehensively evaluate the performance of classification models, and is especially suitable for datasets with imbalanced class distributions. Its value ranges from 0 to 1, with higher values ​​indicating better model performance.

[0040] Training-FreeBayesianization (TFB) is an optimization technique for low-rank adapters in large language models. Its core feature is that it achieves Bayesianization of the model without requiring additional training. This method endows the model with intrinsic uncertainty estimation capabilities by introducing probability distribution assumptions and quantifying the uncertainty of model parameters or outputs. This allows the model to provide the confidence level or probability distribution of the predicted result along with the output, significantly improving the model's interpretability and reliability. In resource-constrained scenarios or those requiring rapid deployment, TFB offers significant advantages due to its training-free nature, providing a lightweight uncertainty calibration scheme for the model.

[0041] CodeArtsCheck, a static code analysis tool provided by Huawei Cloud DevCloud, supports multiple programming languages ​​and can automatically scan source code using predefined coding rules, security standards, and best practices to identify potential code defects, security vulnerabilities, code smells, and style inconsistencies. Its core value lies in shifting code quality checks to the left and integrating them into continuous integration / continuous delivery (CI / CD) pipelines, helping development teams discover and fix issues early, thereby improving software quality and development efficiency.

[0042] This invention provides a code smell self-evolution detection and repair system based on dual agents, such as... Figure 1 As shown, it includes: The core function of the rule analysis and strategy generation agent, Agent1, is to deeply analyze the input rule set and generate the optimal slicing strategy for each rule. It first parses the rules, extracting key features such as rule type and boundary conditions. Then, it accesses the rule knowledge base to retrieve successful strategies for handling similar rules in the past, including code slice types, targeted prompt word templates, and a large number of positive and negative code examples corresponding to the rule. Finally, Agent1 integrates the current rule features, historical strategies, and code examples to generate a complete detection configuration, the core of which is the LLM prompt word construction scheme, and passes it to Agent2 to guide subsequent analysis.

[0043] The code detection and remediation agent, Agent2, is responsible for executing specific code detection, analysis, and remediation tasks. This agent first performs pre-detection of alerts, using static analysis tools to initially scan the codebase and generate alerts, then formats and saves the results according to rules. Next, in the data preprocessing stage, Agent2, based on the strategy provided by Agent1, calls the MCP server to precisely slice the code involved in each alert to obtain code context fragments containing complete semantic relationships and related data dependencies. Subsequently, Agent2 uses the TFB method to quantitatively evaluate the positive and negative code examples provided by Agent1, selecting up to six typical examples most relevant to the current alert code as reference context for LLM analysis. Afterward, Agent2 integrates the precisely sliced ​​code, rule descriptions, selected positive and negative examples, and constructed prompt words, submitting them to the Large Language Model (LLM) for deep analysis and inference, completing the process from false alarm screening to root cause analysis of actual alerts and generation of remediation suggestions. Finally, Agent2 performs structured parsing of the LLM output, including false positives, detailed reasons, remediation suggestions, and executable code patches, and marks each result with rule attributes (such as simple / complex, suggestive / severe) to guide the subsequent human feedback process.

[0044] The Model Context Protocol (MCP) server is the core infrastructure for this system to obtain accurate code context, encapsulating complex code analysis capabilities into standardized service interfaces. By integrating the Tree-sitter high-performance parsing engine, this server can perform deep syntactic analysis on source code, generating an Abstract Syntax Tree (AST) containing a complete syntactic structure. Based on rule analysis and policy generation, the agent (Agent1) performs targeted code context extraction using slicing strategy instructions learned from historical experience. Specifically: For variable-related slices, the system obtains the complete definition and usage chain of key variables involved in the alarm code line by parsing the AST; for statement-level slices, for relatively simple rules (such as expression comparison operations), only the current alarm code line needs to be extracted; for context-related slices, when the relational information involved in the alarm is limited to the vicinity of the code line, the system dynamically determines the range of lines to be sliced ​​forward and backward, centered on the alarm line; for structural integrity slices, for alarms related to special structures (such as switch structures), the complete structural code is extracted by parsing the AST; for macro definition slices, when the alarm code line involves macro calls, the system uses the AST to locate and obtain the complete macro definition content; for comment slices, the system obtains the complete syntax module where the comment is located based on pattern matching technology; for function slices, when the alarm is located inside a function and may be related to function parameters, the complete function body structure where the alarm code is located is extracted by parsing the AST, and excessively long functions are intelligently pruned to remove remote low-relevance code, ensuring the conciseness of the slice. Ultimately, the MCP server provides these structured dependency analysis results to the code detection and repair agent (Agent2), providing a reliable contextual basis for subsequent intelligent suggestion word construction and in-depth analysis.

[0045] The system's knowledge base consists of a rule knowledge base and a case knowledge base. The rule knowledge base stores the mapping relationships between rule descriptions, positive and negative example code, slicing strategies, and prompt word templates, as well as cross-language rule similarity. The case knowledge base stores manually verified typical error / boundary cases, as well as classification data for simple / complex and advisory / severity rules. These dual knowledge bases not only provide knowledge support for the decision-making of Agent1 and Agent2, but also serve as carriers of the system's learning outcomes, continuously enriching and optimizing through subsequent feedback loops.

[0046] The manual feedback loop mechanism is the core of driving the system to achieve continuous self-optimization. It consists of four key parts: intelligent feedback strategy, multidimensional loss function, error classification attribution, and collection of new positive and negative examples, forming a complete optimization closed loop. 1) Intelligent feedback strategy: The system first automatically categorizes the detection results, with sampling priority determined by the complexity and severity of the rules. For results based on simple or suggestive rules, the system automatically adopts the results but periodically samples them for review. For results based on complex rules, they are prioritized for manual review. For results based on severe rules, manual review is mandatory. This ensures that manual review resources are used for the most critical and error-prone judgments.

[0047] 2) The system uses the following multidimensional loss function to comprehensively evaluate the system state: Loss=α×ClassificationLoss+β×DiversityLoss; Specifically, Classification Loss quantifies the performance degradation of the model task by calculating the 1-F1-Score on recent human feedback datasets. Diversity Loss penalizes sampling bias by evaluating the uniformity of the distribution of labeled samples in the code vector space, ensuring the diversity of selected samples. Loss provides a basis for active learning sampling; the system prioritizes samples with high classification loss (indicating model errors) and the ability to improve diversity (covering new code patterns) for submission to human review, thereby achieving the maximum model performance improvement with minimal human annotation cost.

[0048] Based on the loss assessment results, the system will perform error attribution analysis. If the error stems from an inappropriate slicing strategy, a problem with the prompt word template, or an incomplete or unrepresentative positive and negative code example library, it will be determined to be the responsibility of Agent 1, and the corresponding corrective strategy will be recorded in the rule knowledge base. If the error stems from the LLM's judgment bias under sufficient context, it will be determined to be the responsibility of Agent 2, and the case (including code snippets, correct labels, and error analysis) will be stored in the case knowledge base.

[0049] For errors attributed to Agent1, the system employs an intelligent collection mechanism based on the TFB algorithm when updating the rule knowledge base. This mechanism first uses a lightweight large language model to calculate the semantic similarity between the current feedback case and existing positive and negative examples in the knowledge base. Then, it applies the TFB method to quantify the uncertainty of this lightweight model's similarity judgment. By setting an uncertainty threshold, the system can accurately determine whether the current case needs to be included as a new example in the knowledge base. This mechanism effectively avoids example redundancy while continuously enriching knowledge, ensuring the comprehensiveness and conciseness of the positive and negative example codebase.

[0050] The system's workflow begins with the input reception phase, where the system receives new rule set definitions, language specifications, and the codebase of the project to be inspected. This is followed by the rule analysis and strategy generation phase. The rule analysis and strategy generation agent (Agent1), based on the Retrieval Enhanced Generation (RAG) mechanism, intelligently retrieves slicing methods for historically similar rules, relevant positive and negative code examples, and prompt word templates from the rule knowledge base, dynamically generating the optimal detection configuration. Next, the process moves to the alarm pre-detection phase. The code detection and repair agent (Agent2) uses basic static analysis tools (such as CodeArtsCheck) to generate an initial alarm list and saves the results in a formatted and categorized manner. In the code slicing and context acquisition phase, Agent2 invokes the Model Context Protocol (MCP) server according to the strategy provided by Agent1 to perform precise code slicing, extracting code context containing complete semantic relationships and related data dependencies. In the data preprocessing phase, Agent2 integrates the alarm slice code and data dependencies, and uses the TFB algorithm to select the six most relevant code examples to construct a complete prompt word. In the odor detection and remediation phase, Agent2 submits the refined prompts to a Large Language Model (LLM) for deep analysis and reasoning, and parses and post-processes the output to generate structured results. In the result generation and output phase, the system presents the user with the final judgment, detailed remediation suggestions, and executable code patches. Finally, the system enters the human feedback and knowledge update phase, collecting expert corrections through intelligent feedback strategies and quantifying system performance defects based on a multi-dimensional loss assessment function. This drives error attribution in the feedback data and intelligent updates to the knowledge base, forming a closed loop of continuous optimization.

[0051] This invention presents an innovative architecture based on dual-agent collaboration and a human feedback loop, enabling a self-evolving code smell detection and repair system. The core of this system consists of a rule analysis and policy generation agent (Agent1), a code detection and repair agent (Agent2), a Model Context Protocol (MCP) server, and two knowledge bases (a rule knowledge base and a case knowledge base), and is continuously optimized through a human feedback loop.

[0052] Based on the same concept as any of the above-mentioned dual-proxy-based code smell self-evolution detection and repair systems, this invention also provides a dual-proxy-based code smell self-evolution detection and repair method, including: Receive new rule set definitions, language specifications, and the project codebase to be tested; The rule analysis and strategy generation agent Agent1 is based on the retrieval enhancement generation RAG mechanism. It intelligently retrieves the slicing methods of historical similar rules, related positive and negative code examples and prompt word templates from the rule knowledge base, and dynamically generates the optimal detection configuration. The code detection and repair agent Agent2 uses basic static analysis tools to generate an initial list of alerts and saves the results in a formatted and categorized manner. Agent2 invokes the Model Context Protocol Server based on the strategy provided by Agent1, performs precise code slicing, and extracts the code context containing complete semantic relationships and related data dependencies; Agent2 integrates alarm slice code and data dependencies, and uses the training free Bayesian method to select the 6 most relevant code examples to construct complete prompt words; Agent2 submits the refined prompts to the large language model for in-depth analysis and reasoning, and parses and post-processes the output to generate structured results. Present the final judgment result, detailed repair suggestions, and executable code patch to the user; Entering the stage of human feedback and knowledge update, expert correction opinions are collected through intelligent feedback strategies, and system performance defects are quantified based on multi-dimensional loss assessment functions. This drives the error attribution of feedback data and intelligent updates of the knowledge base, forming a closed loop of continuous optimization.

[0053] Based on the same concept as the previous method for self-evolutionary detection and repair of code odors based on dual agents, this embodiment of the invention also provides a computer device, including a memory and a processor. The memory stores a computer program, and the processor executes the computer program to implement the steps of a method for self-evolutionary detection and repair of code odors based on dual agents.

[0054] Based on the same concept as the previous method for self-evolutionary detection and repair of code odors based on dual agents, this embodiment of the invention also provides a non-transitory computer read storage medium that stores computer instructions, which cause the computer to execute the steps of a method for self-evolutionary detection and repair of code odors based on dual agents.

[0055] Compared with existing code smell detection technologies, the core innovation of this invention lies in proposing an intelligent detection system based on a dual-agent collaborative architecture. By dividing the work and cooperating between the rule analysis agent and the code detection agent, and combining the precise code slicing capability of the MCP server and the knowledge retrieval mechanism enhanced by RAG, it achieves accurate identification of code smells, generation of repair suggestions, and system self-evolution capability, effectively solving the limitations of traditional methods in terms of high false positive rate, low recall rate, and lack of repair capability.

[0056] Technical solutions to be protected: 1) Architecture and method of code smell detection system based on the collaborative work of rule analysis agent and code detection agent.

[0057] 2) A method that uses an MCP server to slice code and provide code slices with complete semantics for large language models.

[0058] 3) A method for dynamically obtaining detection strategies from a knowledge base using Retrieval Enhanced Generation (RAG) technology.

[0059] 4) A method for active learning sample selection and system optimization based on multi-dimensional loss functions.

[0060] 5) A complete system for detecting and repairing code smells by integrating dual agents, MCP, and manual feedback loops.

[0061] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some or all of the technical features therein; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the technical solutions of the embodiments of the present invention.

Claims

1. A code smell self-evolution detection and repair system based on dual agents, characterized in that, include: The rule analysis and strategy generation agent, Agent1, first parses the rules and extracts key features; Then, the rule knowledge base is accessed to retrieve successful strategies for handling the corresponding rules in the past, obtain the corresponding code slice type, prompt word template, and positive and negative code examples; finally, a complete detection configuration is generated by combining the current rule features, historical strategies and code examples. The code detection and repair agent Agent2 first uses static analysis tools to perform a preliminary scan of the codebase to generate alerts and outputs the results in a formatted manner. The results are then saved according to the rules. Then, based on the detection configuration, the agent calls the model context protocol server to slice the code involved in each alert to obtain code context fragments containing complete semantic relationships and related data dependencies. Then, the positive and negative code examples are quantitatively evaluated, and at most six typical examples most relevant to the current alarm code are selected. The precisely sliced ​​code, rule description, selected positive and negative examples, and constructed prompt words are then integrated and submitted to the large language model for in-depth analysis and reasoning, completing the process from false alarm screening to root cause analysis of real alarms and generation of remediation suggestions. Finally, the output of the large language model is structured and parsed, including false alarm judgment, detailed reasons, remediation suggestions, and executable code patches, and rule attributes are marked for each result.

2. The code smell self-evolution detection and repair system based on dual agents according to claim 1, characterized in that, The model context protocol server is used to provide code slicing strategies, specifically including: For variable-related slices, the complete definition and usage chain of key variables involved in the alert code line are obtained by parsing the abstract syntax tree; For statement-level slicing, extract the current alarm code line for expression comparison operations; For context slicing, when the relational information involved in the alarm is limited to the vicinity of the code line, the range of lines to be sliced ​​forward and backward is dynamically determined based on the alarm behavior center; For structural integrity slices, for alerts related to switch structures, the complete structural code is extracted by parsing the abstract syntax tree; For macro definition slices, when the alert line involves a macro call, the abstract syntax tree is used to locate and obtain the complete macro definition content. For annotation slices, the complete syntactic module in which the annotation is located is obtained based on pattern matching technology; For function slicing, when an alert is located inside a function and may be related to function parameters, the complete function body structure containing the alert code is extracted by parsing the abstract syntax tree. Overly long functions are intelligently pruned to remove remote, low-relevance code, ensuring the conciseness of the slice.

3. The code odor self-evolution detection and repair system based on dual agents according to claim 1, characterized in that, The system also includes: The rule knowledge base stores the mapping relationship between rule descriptions, positive and negative example code, slicing strategies, and prompt word templates, as well as cross-language rule similarity. The case knowledge base stores typical error / boundary cases that have been manually verified, as well as categorized data of simple / complex and advisory / severity rules.

4. The code smell self-evolution detection and repair system based on dual agents according to claim 1, characterized in that, The system also includes an intelligent feedback strategy: First, the detection results are automatically graded, and the sampling priority is determined by the complexity and severity of the rules. For detection results based on simple or suggestive rules, they are automatically adopted but subject to periodic sampling and review; for detection results based on complex rules, they are submitted for manual review first; and for detection results based on severe rules, they are forced into the manual review process.

5. The code odor self-evolution detection and repair system based on dual agents according to claim 4, characterized in that, The intelligent feedback strategy also includes: The system status is comprehensively evaluated using a multidimensional loss function (Loss). Loss=α×ClassificationLoss+β×DiversityLoss; Among them, ClassificationLoss is the classification loss, which quantifies the performance degradation of the model task by calculating the 1 - F1-Score of the recent human feedback dataset. 1 - F1-Score is the harmonic mean of precision and recall. DiversityLoss is the diversity loss, which penalizes sampling bias by evaluating the uniformity of the distribution of labeled samples in the code vector space, ensuring the diversity of selected samples. Loss provides a basis for active learning sampling, prioritizing the selection of samples with high classification loss and the ability to improve diversity for submission to human review.

6. The code odor self-evolution detection and repair system based on dual agents according to claim 1, characterized in that, The system also includes an error attribution analysis module: If the error stems from an improper slicing strategy, a problem with the prompt word template, or an incomplete and unrepresentative positive and negative code example library, it will be determined to be the responsibility of Agent1, and the corresponding correction strategy will be recorded in the rule knowledge base. If the error stems from an error in the LLM's judgment within sufficient context, it is determined to be the responsibility of Agent2 and stored in the case knowledge base.

7. The code odor self-evolution detection and repair system based on dual agents according to claim 6, characterized in that, The system also includes an intelligent collection mechanism: First, a lightweight large language model is used to calculate the semantic similarity between the current feedback case and the existing positive and negative examples in the knowledge base; Then, the training-free Bayesian method is applied to quantify the uncertainty of the lightweight model in similarity judgment. By setting an uncertainty threshold, it is determined whether the current case should be included as a new example in the knowledge base.

8. A method for self-evolutionary detection and repair of code smells based on dual proxies, characterized in that, include: Receive new rule set definitions, language specifications, and the project codebase to be tested; The rule analysis and strategy generation agent Agent1 is based on the retrieval enhancement generation RAG mechanism. It intelligently retrieves the slicing methods of historical similar rules, related positive and negative code examples and prompt word templates from the rule knowledge base, and dynamically generates the optimal detection configuration. The code detection and repair agent Agent2 uses basic static analysis tools to generate an initial list of alerts and saves the results in a formatted and categorized manner. Agent2 invokes the Model Context Protocol Server based on the strategy provided by Agent1, performs precise code slicing, and extracts the code context containing complete semantic relationships and related data dependencies; Agent2 integrates alarm slice code and data dependencies, and uses the training free Bayesian method to select the 6 most relevant code examples to construct complete prompt words; Agent2 submits the refined prompts to the large language model for in-depth analysis and reasoning, and parses and post-processes the output to generate structured results. Present the final judgment result, detailed repair suggestions, and executable code patch to the user; Entering the stage of human feedback and knowledge update, expert correction opinions are collected through intelligent feedback strategies, and system performance defects are quantified based on multi-dimensional loss assessment functions. This drives the error attribution of feedback data and intelligent updates of the knowledge base, forming a closed loop of continuous optimization.

9. A computer device comprising a memory and a processor, wherein the memory stores a computer program, characterized in that, When the processor executes the computer program, it implements the steps of the code odor self-evolution detection and repair method based on dual agents as described in claim 8.

10. A non-transitory computer read storage medium, characterized in that, The non-transitory computer reads the storage medium to store computer instructions, which cause the computer to execute the steps of the code odor self-evolution detection and repair method based on dual agents as described in claim 8.