Self-adaptive code processing method based on artificial intelligence
By constructing a heterogeneous dependency graph and combining static and dynamic edge fingerprint matching, the problems of non-executable code generation and configuration file linkage in complex software engineering are solved, achieving high-precision dependency identification and reliable code generation, and reducing the risk of anomalies.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-30
- Publication Date
- 2026-03-31
AI Technical Summary
Existing code generation technologies cannot accurately parse dynamic features when dealing with enterprise-level software engineering with complex dependencies, resulting in non-executable generated code logic and the inability to link source code and configuration files for changes, leading to runtime exceptions.
By constructing a heterogeneous dependency graph and combining static and dynamic edge fingerprint matching, dependencies are identified, and logical reachability checks and atomic operations are performed when generating code to ensure that the source code and configuration files are changed synchronously.
It improves the accuracy of identifying dependencies in complex software engineering, reduces the cost of compilation errors and runtime exceptions, and ensures the consistency and integrity of software state.
Smart Images

Figure CN121764477A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of software engineering technology, specifically to an adaptive code processing method based on artificial intelligence. Background Technology
[0002] With the widespread application of large language models in software development, intelligent code assistants can automatically generate code snippets based on contextual prompts, helping developers complete logic writing. However, when facing enterprise-level software engineering with complex dependencies, existing code generation technologies still have significant technical bottlenecks.
[0003] Because modern software engineering widely employs reflection mechanisms, dependency injection containers, and multi-language hybrid configuration architectures, traditional static code analysis methods struggle to accurately parse such dynamic characteristics and cannot construct an engineering dependency graph consistent with the runtime state. This lack or bias in contextual information directly leads to factual errors in the generative model's code predictions, such as calling interfaces that do not exist in the project or using incorrect parameter types, thus generating logic code that cannot be compiled.
[0004] Furthermore, existing generation solutions typically focus only on text completion of source code files, neglecting changes to system configuration files that are tightly coupled with them. This results in the inability to synchronously update corresponding Bean definitions, database structures, or routing configurations when generating business logic code. This non-atomic change approach is highly prone to causing runtime exceptions due to missing configurations in actual deployments, forcing developers to spend a significant amount of time manually troubleshooting and completing the necessary changes.
[0005] Therefore, this invention proposes an adaptive code processing method based on artificial intelligence to address the shortcomings of existing technologies. Summary of the Invention
[0006] To address the shortcomings of existing technologies, this invention provides an adaptive code processing method based on artificial intelligence. This method solves the problems of existing technologies failing to accurately parse dynamic dependencies in complex engineering environments, resulting in unexecutable generated code logic, and the inability of source code and configuration files to be linked for changes, leading to inconsistent software states.
[0007] To achieve the above objectives, the present invention provides the following technical solution: an adaptive code processing method based on artificial intelligence, comprising the following steps:
[0008] The source code files and configuration files of the software project are parsed to build a heterogeneous dependency graph. The graph nodes are divided into white, gray and black areas according to the completeness of the parsed source, and static edge fingerprints containing caller information and line number offsets are calculated.
[0009] Collect call stack data during application execution and generate dynamic edge fingerprints. Match the dynamic edge fingerprints with the static edge fingerprints. Update the confidence of the graph nodes or create dynamic dependency edges based on the matching results.
[0010] In response to an input event, nodes in the heterogeneous dependency graph are retrieved as context to drive the model to generate candidate code. Logical reachability checks are performed on the candidate code, and an interception instruction is triggered when an invalid call involving the white zone node is made.
[0011] In response to the interception command, a virtual node is created in the heterogeneous dependency graph, and an atomic operation set including source code changes and configuration file changes is generated according to the priority preset strategy of local search, global clustering and framework default.
[0012] Preferably, parsing the source code files and configuration files of the software project to establish a heterogeneous dependency graph includes:
[0013] Traverse the target project's file directory, call the language parser to generate an abstract syntax tree for the source code files, and extract class declarations, method declarations, and field declarations from the abstract syntax tree as atomic nodes;
[0014] The parser extracts the configuration item definitions, application interface routing configurations, and database connection pool configurations from the configuration file, maps the configuration item definitions to graph nodes, and uses the path of the configuration file as the source attribute of the graph nodes.
[0015] Parse the table creation statements in the Data Definition Language file, map the database table structure to data entity nodes, and map column definitions to field nodes.
[0016] Preferably, the graph nodes are divided into white, gray, and black regions based on the completeness of the parsed source, including:
[0017] The static information integrity index of the graph node is calculated based on whether the source code file of the graph node exists, whether the abstract syntax tree is parsed without errors, whether only compiled bytecode or interface definition exists, and whether it has been obfuscated.
[0018] If the static information integrity index is greater than or equal to the preset white area determination threshold, the map node is classified into the white area;
[0019] If the static information integrity index is less than or equal to the preset black area determination threshold, the map node is classified into the black area;
[0020] If the static information integrity index is between the black area determination threshold and the white area determination threshold, the map node is classified into the gray area.
[0021] Preferably, calculating the static edge fingerprint, which includes caller information and row number offset, includes:
[0022] Traverse the call expressions inside the method definition bodies of the abstract syntax tree of the source code file;
[0023] For each of the calling expressions, extract the unique signature of the calling method, the name of the called party, and the line number offset of the calling expression within the body of the calling method.
[0024] The static edge fingerprint is generated by calculating the unique signature of the calling method, the name of the called party, and the offset of the calling line number using a hash mapping function.
[0025] Preferably, collecting call stack data during application execution and generating dynamic edge fingerprints includes:
[0026] Implant probes during application startup to intercept the call stack information of the current thread in real time, and extract the runtime class information, runtime method signature, line number of the call, and the actual receiving object type of the callee.
[0027] Based on the caller's runtime method signature, the actual receiving object type of the callee, and the runtime line number offset calculated based on the line number of the initiating call, a dynamic edge fingerprint is generated using the same hash mapping function as that used to calculate the static edge fingerprint.
[0028] Preferably, updating the confidence of the graph nodes or creating dynamic dependency edges based on the matching results includes:
[0029] The dynamic edge fingerprint is indexed and matched with the existing static edge fingerprint in the heterogeneous dependency graph.
[0030] When a match is successful, it is determined that the corresponding static dependency in the heterogeneous dependency graph is valid at runtime, and the edge confidence corresponding to the static dependency is increased.
[0031] When a match fails, the node corresponding to the caller and the node corresponding to the callee are connected in the heterogeneous dependency graph to create a dynamic dependency edge, and the dynamic dependency edge is marked as dynamic type.
[0032] Preferably, performing a logical reachability check on the candidate code includes:
[0033] The candidate code is parsed and dependency reference information is extracted, including the class name, method name, and parameter type of the call.
[0034] Determine the region to which the target node corresponding to the dependency reference information belongs in the heterogeneous dependency graph;
[0035] If the target node belongs to the white area, perform exact matching verification. If the target node does not define a method name or the parameter type cannot be exactly matched, it is determined to be an invalid call.
[0036] If the target node belongs to the gray area, calculate the fingerprint similarity between the dependency reference information and the known interface features in the gray area, and output a warning message when the fingerprint similarity is lower than a preset threshold.
[0037] Preferably, the set of atomic operations that includes source code changes and configuration file changes, generated according to a preset strategy, includes:
[0038] The following strategies will be executed in descending order of priority:
[0039] Prioritize searching for sibling nodes in the heterogeneous dependency graph that are located in the same package path as the virtual node or have the same parent class inheritance relationship. If the sibling node exists, extract the configuration pattern of the sibling node to generate the configuration code of the virtual node.
[0040] If the sibling node does not exist, perform abstract syntax tree subtree hash clustering on the nodes in the heterogeneous dependency graph to identify global code patterns and generate configuration code for the virtual node;
[0041] If the global code pattern cannot be identified, generate skeleton code consisting of class definitions and empty method bodies according to the programming language and framework specifications.
[0042] Preferably, the configuration mode for extracting the sibling node includes:
[0043] Calculate the proximity of the sibling node and the virtual node in the physical directory path and the overlap of the metadata sets;
[0044] The sibling node with the highest similarity is selected as the template prototype;
[0045] Extract the object-relational mapping annotations, log framework definitions, and transaction control methods used in the template prototype, and combine them with the constraint information of the virtual nodes to generate the corresponding source code and configuration file content.
[0046] Preferably, the atomic operation set satisfies the transaction integrity verification requirements, ensuring that there are no dangling references when the source code changes and configuration file changes take effect simultaneously.
[0047] This invention provides an adaptive code processing method based on artificial intelligence. It has the following beneficial effects:
[0048] 1. This invention effectively solves the parsing blind spots of static analysis when facing reflection, generic type erasure, and complex configurations by constructing a heterogeneous dependency graph that includes source code, configuration files, and database structures, and combining it with runtime call stack data for dynamic calibration. Utilizing a matching mechanism between static and dynamic edge fingerprints, the system can correct the confidence level of graph nodes in real time, thereby eliminating the deviation between static code features and actual runtime logic. Compared to traditional methods that rely solely on text analysis, this significantly improves the accuracy of identifying dependencies in complex software engineering.
[0049] 2. This invention proposes a logical reachability check mechanism based on confidence partitioning, which can proactively intercept invalid references during the code generation stage. By dividing dependent nodes into white, gray, and black zones, and performing precise signature matching verification on calls within the white zone, the system can effectively identify and block fictitious code generated by large language models. This mechanism ensures that the generated candidate code is logically valid and compileable, reducing the cost of subsequent manual troubleshooting of compilation errors or runtime exceptions.
[0050] 3. This invention utilizes a layered rollback dependency compensation strategy to achieve atomic, linked changes to source code and configuration files. When generating new feature code, the system can automatically complete the corresponding Bean definitions, database structures, or routing configurations based on local source nodes or global code patterns, and perform transactional integrity checks. This avoids the dangling reference problem caused by traditional code completion tools that only focus on code snippets and overlook environment configurations, ensuring the integrity and consistency of software changes. Attached Figure Description
[0051] Figure 1 This is a system architecture diagram of the present invention;
[0052] Figure 2 This is a flowchart of the adaptive code processing method of the present invention;
[0053] Figure 3 This is a flowchart of the heterogeneous spectrum construction process of the present invention;
[0054] Figure 4 This is a flowchart of the dynamic calibration process of the present invention;
[0055] Figure 5 This is a flowchart of the adaptive verification process of the present invention;
[0056] Figure 6 This is a flowchart of the reverse compensation process of the present invention.
[0057] Among them, 110 is the heterogeneous spectrum construction module; 120 is the dynamic calibration module; 130 is the adaptive verification module; and 140 is the reverse compensation module. Detailed Implementation
[0058] The technical solutions in 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, and 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.
[0059] See attached document Figure 1 , Figure 1 This is a system architecture diagram of an adaptive code processing method according to an embodiment of the present invention. The system provided by the present invention includes:
[0060] The heterogeneous graph construction module 110 is used to parse and structure static assets in software engineering. The module reads source code files, configuration files, and database definition files, extracting classes, methods, interfaces, configuration items, and data columns as graph nodes. It executes confidence partitioning logic, dividing nodes into white, gray, or black regions based on the completeness of the parsed source, and calculates temporal stability weights for each node. Furthermore, the module calculates static edge fingerprints for static call relationships, including the caller's signature, the callee's signature, and line number offsets, to establish the initial static topology.
[0061] The dynamic calibration module 120 collects actual call data during application runtime and corrects deviations in the static graph. The dynamic calibration module 120 captures method call events using a probe component mounted in the runtime environment. Based on the caller and callee information captured at runtime, the dynamic calibration module 120 generates a dynamic edge fingerprint and performs a hash match between this dynamic edge fingerprint and the static edge fingerprint generated by the heterogeneous graph construction module 110. When a match is successful, the dynamic calibration module 120 updates the confidence attribute of the relevant node to a high-confidence state; when the corresponding edge does not exist in the static graph, the dynamic calibration module 120 performs an incremental edge completion operation.
[0062] The adaptive verification module 130 performs context retrieval and multi-level logical verification on the code generation request. Responding to user input events, the adaptive verification module 130 retrieves nodes with high stability and high confidence from the heterogeneous dependency graph as context, driving the large language model to generate candidate code. The adaptive verification module 130 sequentially performs syntax analysis, logical reachability checks, and architectural constraint checks on the candidate code. During the logical reachability check, the adaptive verification module 130 reads the confidence attribute of the target node. If invalid calls to white zone nodes are involved, an interception instruction is triggered; if ambiguous calls to gray zone nodes are involved, a warning message is output based on the fingerprint similarity threshold.
[0063] The reverse compensation module 140 is used to automatically generate missing dependency configurations when code verification fails. When the adaptive verification module 130 issues an interception command, the reverse compensation module 140 creates virtual nodes in the graph. The reverse compensation module 140 performs a search according to a preset priority strategy: it prioritizes searching for sibling nodes with topological homology within a local scope as reference anchors; if the search fails, it expands the search scope to perform global configuration pattern clustering; if clustering fails, it uses the framework's default rules to generate configurations. The reverse compensation module 140 ultimately generates a set of atomic operations that include source code changes and configuration file changes, and feeds them back to the user interface.
[0064] See attached document Figure 2 , Figure 2 This is a flowchart of an adaptive code processing method according to an embodiment of the present invention. The method includes the following steps:
[0065] S200 performs multi-source heterogeneous parsing and graph initialization; loads the target project, identifies source code files and configuration files. It performs abstract syntax tree parsing on the source code and structured parsing on the configuration files, establishing a heterogeneous dependency graph containing entity nodes. Based on the completeness of the parsed source, corresponding nodes are marked as white, gray, or black areas, and initial confidence scores are assigned. Static edge fingerprints containing caller information are calculated.
[0066] S201, Perform runtime graph calibration based on edge verification. Call stack data is collected during application runtime. The hash fingerprints of runtime call edges are calculated and matched against static edge fingerprints. The combined features of the caller and callee are used to eliminate ambiguities caused by generic erasure and verify the validity of static dependencies. When a match is successful, the confidence of the relevant nodes is increased; when a match fails, dynamic dependency edges are created in the graph.
[0067] S202, perform confidence-based code generation and logic verification. Retrieve high-confidence nodes from the heterogeneous dependency graph based on the user's edit location as context to generate candidate code. Parse the dependency references in the candidate code and perform path reachability checks in the graph. If the code references a node that does not exist or is unreachable in the white zone, the reference is deemed invalid and an interception is triggered; if the code references a node in the gray zone, a warning is output based on the fingerprint similarity threshold.
[0068] S203 performs dependency compensation generation for hierarchical fallback. When candidate code is intercepted, virtual nodes are created in the graph. Sibling nodes with the same parent class or package path are retrieved from the graph; if they exist, their configuration patterns are copied; if they do not exist, the global configuration patterns are calculated and generated; if the global patterns are not significant, the framework's default configuration is generated. The generated compensation configurations are merged with the candidate code to output an atomic changeset.
[0069] To further clarify the implementation of each technical aspect of the present invention, the following will provide a detailed description of the implementation of each functional module involved above and its internal processing flow.
[0070] See attached document Figure 2 as well as Figure 3 In step S200, the heterogeneous graph construction module 110 performs entity parsing and integrity-based confidence partitioning of multi-source heterogeneous data. This process aims to convert discrete, heterogeneous code assets in physical storage media into logically unified graph nodes and to hierarchically label the nodes based on the observability of the information. Step S200 specifically includes the following steps:
[0071] S2001 performs normalization parsing of heterogeneous source data. The system traverses the target project's file directory, and for source code files with extensions .java, .go, and .py, calls the corresponding language parser to generate an Abstract Syntax Tree (AST). The system traverses the class declarations, method declarations, and field declarations in the AST, extracting them as atomic nodes in the graph. For XML, YAML, or Properties configuration files, the system uses a DOM parser or key-value pair reader to extract Bean definitions, API routing configurations, and database connection pool configurations, mapping configuration items to graph nodes and using the configuration file path as the node's source attribute. For SQL-DDL (Data Definition Language) files, the system parses CREATE-TABLE statements, mapping the database table structure to data entity nodes and column definitions to field nodes.
[0072] S2002 defines the key metadata attributes of the node. The system defines the key metadata attributes for each node generated in step S2001. Assign a unified set of attributes. This set of attributes includes a unique identifier. Node type Source path and signature features For method nodes in the source code, the signature characteristics... It consists of a method name, a list of parameter types, and a return type. To address the generic type erasure issue, the system retains generic metadata at the source code level during the parsing phase, storing it in an extended attribute field. Instead of discarding it directly, the system records the start and end line numbers of the overloaded method in the source file as an auxiliary feature to distinguish methods with the same name.
[0073] S2003 executes node confidence partitioning based on node integrity. The system divides all nodes in the graph into three mutually exclusive confidence regions: white region, gray region, and black region, based on the resolution completeness and observability of the node's source. This partitioning strategy is based on the node's static information completeness index. Perform the calculation.
[0074] System-defined nodes Completeness of static information The calculation logic is as follows:
[0075] ;
[0076] in, It is an indicator function, when the node The value is 1 if the corresponding source code file exists and the AST parsing is error-free; otherwise, it is 0. It is an indicator function, when the node The value is 1 only if the compiled bytecode or interface definition (such as JAR package dependency or RPC interface definition) exists; otherwise, it is 0. It is an indicator function, when the node The value is 1 if the code is detected to have been obfuscated or encrypted, and 0 otherwise. , , These are the source code integrity weight, interface visibility weight, and obfuscation penalty coefficient, respectively, all of which are positive numbers, and in one embodiment, they satisfy... For example, take .
[0077] S2004, based on the calculated completeness index The system determines the region to which the node belongs and writes it. Attributes; System preset white area detection threshold Black area determination threshold .
[0078] For satisfying The system classifies the node as a white area. A threshold is set for the white zone. A white zone node represents a node over which the system has complete control, including complete source code, accurate type definitions, and a defined control flow structure. Within this region, the system has the highest confidence in the accuracy of code generation, and subsequent verification logic will employ a strict matching strategy.
[0079] For satisfying Nodes that violate this rule are classified as gray zones by the system. Gray zone nodes typically correspond to third-party binary libraries, dynamically generated classes, or components invoked via reflection. While these nodes expose public interface signatures, their internal implementation logic is either invisible to the system or exhibits dynamic uncertainty. Gray zone nodes are marked in the graph by the system. The attributes are then used to perform fuzzy matching or downgraded validation strategies in subsequent validations.
[0080] For satisfying The system classifies the node as a black zone. The threshold for black zone determination is set. Black zone nodes correspond to completely unparseable code blocks, remote opaque services, or encrypted logic. For black zone nodes, the system only retains their existence marker and forces manual intervention for confirmation when generating code involving that node, or directly blocks the automated generation process to prevent logical risks.
[0081] S2005 establishes static dependency edges between nodes. The system creates directed edges between nodes based on the reference relationships in the AST, the `ref` attribute in the configuration file, and foreign key constraints in the SQL. For calls between white zone nodes, the system establishes deterministic connections based on precise method signatures; for calls involving gray zone nodes, if there is ambiguity due to polymorphism or generics, the system establishes multiple candidate edges and assigns them initial low-confidence weights, waiting for subsequent dynamic calibration steps to correct them.
[0082] S2006 extracts call context features and constructs static edge fingerprints. When parsing the Abstract Syntax Tree (AST) of the source code, the system traverses the call expression within each method definition body. For each call point, the system not only records the name of the called method but also simultaneously extracts the complete signature of the currently initiating method (i.e., the caller) and the relative position of the call instruction within the caller's method body. Using the extracted context features, the system generates static edge fingerprints through a specific hash algorithm. .
[0083] Static edge fingerprint The computational logic is defined by the following formula:
[0084] ;
[0085] in, Represents a collision-resistant hash mapping function (e.g., SHA-256); A unique signature representing the calling method, which includes the package name, class name, method name, and a list of parameter types, used to identify the context in which the call was initiated; Indicates the name of the callee or the signature of the reference that is visible on the surface of the code; This refers to the concatenation operation of strings or binary data. This indicates the line number offset from the call.
[0086] S2007 calculates the call line number offset to enhance the timing stability of the fingerprint. Instead of directly using the absolute line number in the source code file as the hash factor, the system calculates the difference between the call statement and the relative line number of the initial definition of the calling method.
[0087] Call line number offset The calculation logic is as follows:
[0088] ;
[0089] in, The absolute line number of the calling expression in the source code file. The starting line number for the calling method definition in the source code file. This is achieved by using a relative offset. When comments, blank lines, or package imports are modified in the area of the source code file before the method definition, as long as the internal logical structure of the method body remains unchanged, the generated static edge fingerprint will still be valid. This approach significantly reduces the impact of minor code changes on the graph structure, ensuring the robustness of dependency tracking.
[0090] S2008 utilizes static edge fingerprinting to eliminate ambiguity related to polymorphism and overloading. During the static analysis phase, when encountering method overloading or generic calls, relying solely on the caller's name often fails to determine the specific target node. For example, for methods with the same name `execute(String)` and `execute(Integer)`, if the parameter type at the caller is ambiguous, traditional analysis will generate multiple uncertain candidate edges. This invention introduces a method that includes... and The fingerprint mechanism transforms dependency identification from "who is called" to "who initiates the call from what location".
[0091] Specifically, even if there are multiple candidate targets for the callee (i.e., static ambiguity), the location where the call occurs (i.e., the combination of the caller's signature and the line number offset) is physically unique. The system will use this unique fingerprint. Serving as the index key for the graph edges. In the subsequent dynamic calibration phase, the call stack information captured by the runtime probe also includes caller and offset information. This is achieved by recalculating the runtime fingerprint and comparing it with the graph. By performing a precise comparison, the system can uniquely pinpoint the exact line of code where the call occurred. Once the fingerprint match is successful, the system can infer the specific overloaded method or generic implementation that could not be determined during the static analysis phase based on the actual parameter types passed at runtime. This corrects the originally ambiguous dependency edges to solid edges pointing to specific nodes, achieving precise association and correction between the static topology and dynamic runtime data.
[0092] See attached document Figure 2 as well as Figure 4In step S201, the dynamic calibration module 120 performs runtime spectrum calibration based on edge verification. This step utilizes the data stream generated by the actual operation of the application to verify, prune, and complete the static heterogeneous spectrum constructed in step S200, thereby eliminating the inherent uncertainties in static analysis. Step S201 specifically includes the following steps:
[0093] S2011 executes runtime probe deployment and context data capture. During the application startup phase, the system implants non-intrusive probes at method entry and exit points using bytecode manipulation techniques based on frameworks such as ASM and Byte-Buddy, or an instrumentation mechanism based on Java-Agent. When the application responds to external requests or executes scheduled tasks, the probes intercept the call stack information of the current thread in real time. For each method call event, the probes extract the runtime class information, method signature, and line number of the caller; simultaneously, they extract the actual receiving object type and method signature of the callee. The system assembles the above information into a runtime call tuple. This tuple does not contain specific business data content, but only structured metadata for topology verification, to achieve logical verification while ensuring data privacy.
[0094] S2012, Generate runtime dynamic hash fingerprints. To associate the discrete call events captured at runtime with the abstract dependency edges in the static graph, the system uses the same hashing strategy as in step S2006 to calculate dynamic fingerprints. The system reads the caller's signature from the runtime call tuple. and the signature of the callee At the same time, the system obtains the absolute line number at the time the runtime call occurred. And, combined with the starting line number of the class definition file loaded at runtime, calculate the relative line number offset at runtime. .
[0095] Dynamic hash fingerprint The calculation logic is as follows:
[0096] ;
[0097] By reproducing the calculation process including line number offsets at runtime, the system establishes a unique mapping key between "static code location" and "program execution time".
[0098] S2013, perform anti-ambiguous matching based on topological feature locking. The system will calculate the... Compared with existing static edge fingerprints in the graph Perform a full index matching. This step aims to resolve dependency ambiguity issues caused by generic type erasure and interface polymorphism in static analysis. In the compilation process of strongly typed languages such as Java, generic parameters (such as List...)... <t>The type T will be erased to an upper bound type (such as Object), making it impossible for static analysis to determine the specific type of T; at the same time, calls to the interface may point to all implementation classes in the static view.
[0099] This invention solves the above problem using the principle of "combinatorial uniqueness": although the specific type of the callee is hidden or obscured in the static code, the topological characteristic of "who initiated the call and where" is physically determined. When With a certain static edge fingerprint When a match is successful, the fingerprint contains a high-precision row number offset. The system can then determine that the runtime call corresponds to the code logic described by the static edge in the graph. At this point, the system uses the actual type of the callee captured at runtime (e.g., runtime confirmation that T is UserDTO) to reverse-engineer the generic placeholder or interface definition in the static graph.
[0100] Specifically, the system identifies the concrete implementation class node determined at runtime as the true target of the call, thereby updating the corresponding candidate edges in the graph to confirmed edges and removing other candidate edges that have not been verified at runtime. This edge-verification-based mechanism effectively maps runtime data flow features back to the static graph, achieving accurate identification and correction of polymorphic call relationships. This ensures that the graph reflects not only how the code is written but also the actual runtime execution logic of the code.
[0101] In S2014, confidence propagation and incremental graph update are performed. Based on the fingerprint matching results, the system performs differential updates on the node and edge attributes in the graph; if a match is successful, it indicates that the dependency actually exists in operation, and the system increases the confidence of the corresponding static edge. .
[0102] The confidence score update follows an asymptotic saturation rule, and its calculation logic is as follows:
[0103] ;
[0104] in, The confidence level before the update. This is the learning rate coefficient (ranging from 0.1 to 0.3). This is an indicator factor for a successful fingerprint match (value 1 if the fingerprint matches successfully, otherwise value 0). As runtime progresses, the confidence level of the frequently called core paths will approach 1.0, becoming a highly reliable context for subsequent code generation.
[0105] If the match fails, that is The absence of a corresponding entry in the static graph usually indicates an implicit dependency call generated through reflection, dynamic script execution, or AOP aspect-driven dynamic injection. In this case, the system creates a new dynamic dependency edge in the graph, connecting the caller node and the callee node, and marks the edge as "Dynamic" with its initial confidence set to the baseline value. In this way, the system can automatically discover hidden logical paths that static resolution cannot cover, achieving adaptive graph completion.
[0106] See attached document Figure 2 as well as Figure 5 In step S202, the adaptive verification module 130 performs code completion generation and security review based on the real-time state of the heterogeneous dependency graph. This step utilizes the structured information of the graph to constrain the generation space of the large language model and implements hierarchical post-verification. Step S202 specifically includes the following steps:
[0107] S2021, Execute context retrieval based on graph stability. When the system detects user editing behavior or receives code completion instructions, it first locates the current node where the cursor is located. Using this anchor point as the center, the system performs a breadth-first search (BFS) traversal in the heterogeneous dependency graph, retrieving adjacent nodes associated with the current logical path. During the retrieval process, the system filters the context based on the node confidence and edge frequency weights calculated in step S201. The system prioritizes nodes with high confidence. The white area nodes and dependencies that have been verified at runtime and marked as "real edges" serve as contextual material for the project. The system injects the retrieved class definitions, method signatures, and configuration items into the input window of the generated model in a structured manner, thereby guiding the model to generate candidate code snippets based on the real-world project structure.
[0108] S2022, parsing the generated code and extracting dependency references. The system performs lightweight abstract syntax tree parsing on the candidate code output by the model, identifying all symbolic references contained therein. Extracted reference information... This includes the class name, method name, field name, and parameter types passed. This process does not focus on the specific business algorithm logic, but only on the code's reference relationships to external entities.
[0109] S2023 implements a confidence-based partitioned gating verification strategy. The system adopts differentiated verification strictness based on the region (white, gray, or black) in the graph to which the referenced entity belongs. The core of this strategy is: for white regions where the system has complete control over the source code, deterministic judgment is implemented; for gray regions where only interface or binary information is known, probabilistic judgment is implemented.
[0110] For white zone nodes, the system executes an "exact match verification" mechanism. Due to the white zone nodes'... The system has a very high degree of completeness; any path that does not exist in the graph is considered to be logically non-existent. If candidate code references a class in the white area, but the class does not define the method to be called, or the parameter signature cannot be found to be exactly matched in the graph, the system determines that the reference is invalid. At this time, the system triggers a "hard interception" action.
[0111] For gray zone nodes, the system implements a "fuzzy compatibility" mechanism. Since gray zone nodes may originate from third-party libraries or dynamic proxies that have not been fully parsed, the lack of graph information does not necessarily indicate a logical error. The system calculates the similarity between candidate references and known interface features of the gray zone. If no direct match is found in the graph for a candidate reference, but its naming conventions conform to the target library's pattern, or its parameter types have a covariance relationship with known overloaded methods, the system calculates its risk coefficient. When the risk coefficient exceeds the warning threshold, the system triggers a "soft alert" action.
[0112] S2024, Construct and compute the gating verification decision function. System-defined decision function. , to generate code reference snippets As input, combined with the map state Based on the confidence-based partitioning rules, the function outputs a ternary decision result of {BLOCK, WARN, PASS}. This function not only considers the existence of nodes but also integrates accessibility and fuzzy similarity judgments, forming a multi-dimensional defense logic.
[0113] Verification decision function The logical definition is as follows:
[0114] ;
[0115] in, The negation operator is used to negate the subsequent Boolean condition; for example, Indicates "in the map" Unable to find a reference in The state of "a perfectly matched node"; and These represent the logical AND and logical OR operators, respectively. and These represent the namespace sets for the white area (source code control area) and the gray area (third-party dependency area), respectively. If the referenced package name or classpath prefix belongs to the project's own scope, then... ; For an exact match of the indicator function; if and only if a node exists in the graph. Its signature With reference signature The function returns true if the identifier name, parameter type list, and return type are completely identical through byte-level comparison; otherwise, it returns false. This is a fuzzy similarity calculation function; the system uses a weighted combination of the edit distance algorithm and the type covariance detection algorithm to calculate the reference. With known candidate nodes in the gray area Similarity scores; The confidence threshold for fuzzy matching; For reachability access checks, the system uses Java language access control rules (such as private / protected / public modifiers) to determine the current class node. Do I have permission to access the target node? Specifically, this includes: inspection Whether class modifiers allow cross-package access, and whether member method access modifiers allow cross-package access. It is evident that there may be an inheritance relationship leading to elevated access permissions; if for If the member class is an inner class or subclass of the protected member, it automatically gains access to the protected member; otherwise, it returns unreachable.
[0116] S2025, execute the hierarchical control strategy based on the output of the decision function.
[0117] When the decision result satisfies At this time, a hard block is triggered. This entry corresponds to two specific technical scenarios:
[0118] Hallucination reference: condition This means that the large language model has generated methods or classes that belong to the current project's namespace but do not actually exist in the source code. Because white-area data has completeness, their absence in the graph represents their physical absence; therefore, the system determines this to be a generative illusion and must intercept it.
[0119] Unauthorized access: conditions This means that although the target node physically exists, according to the language specification, the current context does not have the authority to call that node. This often occurs when the model ignores the encapsulation characteristics of the code, and the system needs to prevent such logical errors.
[0120] When the decision result satisfies When this occurs, a soft warning is triggered. This scenario corresponds to the following: the code references a third-party gray-zone component, and a known interface cannot be precisely matched, but highly similar candidate targets exist in the graph. This usually suggests potential version differences (such as minor differences in method name spelling or parameter order changes) or incomplete parsing. The system does not prevent code generation at this time, but marks the warning in the IDE and utilizes... The function finds the best candidate node This suggestion is presented to the user as a correction.
[0121] When the decision result is When the reference passes all consistency checks or belongs to an unverifiable black zone (such as a pure reflection call string), the system allows the direct application of the code snippet.
[0122] See attached document Figure 2 as well as Figure 6 In step S203, the hierarchical rollback reverse compensation module 140 performs automatic completion for the missing dependencies intercepted in step S202. This step is activated when the gating verification mechanism determines that the code references a non-existent entity and that the missing dependency is not a logical error but a function to be implemented. Step S203 specifically includes the following steps:
[0123] S2031, Construct a virtual node and identify interface constraints. The system first analyzes the context of the reference point that triggered the interception and creates a "virtual node". Temporarily stored in the heterogeneous graph. This node is in a "pending objectification" state. The system scans the abstract syntax tree (AST) of the reference point to extract the set of functional constraints for this virtual node. This set includes the inferred method name, sequence of input parameter types, expected return type, and exception throwing declaration. The system will... Mark it as the target completion object and use its package path or module location as the context anchor.
[0124] S2032, Execute the layered rollback generation strategy. To ensure that the automatically generated completed code conforms to the project-specific coding style while guaranteeing the correctness of the basic syntax, the system executes three generation strategies in descending order of priority. The system calculates the feature score of the current scene and dynamically selects the optimal strategy to generate the code structure.
[0125] Strategy 1: Local homogeneous anchoring.
[0126] System priority search and Sibling nodes are located in the same package path or have the same parent class inheritance relationship. Based on the assumption that "the code style of the same module is highly similar", the system calculates the configuration feature similarity of sibling nodes.
[0127] Homology similarity The calculation logic is as follows:
[0128] ;
[0129] in, These are candidate nodes that already exist in the graph; For the virtual nodes to be generated; Represents a node The physical directory path where it is located; For the target path; For indicator functions; Represents a node The collection of metadata it possesses (including annotations, modifiers, and dependency injection field references); is the Jaccard similarity coefficient, used to calculate the degree of overlap between two sets; and These are the weighting coefficients; satisfying... In one embodiment, setting This emphasizes the proximity of physical paths.
[0130] System selection The node with the highest score is used as the "template prototype". Instead of directly copying the node's code, the system extracts its structural features (such as the ORM annotations used, logging framework definitions, and transaction control methods) and applies these high-level structures to... During the generation process, only the specific business method signature is replaced with the constraint identified in S2031.
[0131] Strategy 2: Global statistical clustering.
[0132] If Strategy 1 fails to find a sibling node that meets the threshold (e.g., this is a completely new empty module), the system falls back to global mode. The system performs AST subtree hash clustering on all nodes in the entire project or graph to identify the most frequent "code pattern". The system statistically analyzes the standard structural features of different types of nodes (such as Controller, Service, Repository) and selects the global mode as the generation template. For example, if 80% of the Service classes in the system inherit from BaseService and inject UserContext, the system automatically applies this pattern when generating a new Service.
[0133] Strategy 3: Framework default conventions.
[0134] If the dispersion of global statistical features is too high to extract effective patterns, the system reverts to the lowest priority framework convention strategy. The system generates a minimal, runnable skeleton code based on the official specifications of the current programming language and framework (such as Spring Boot or Django). This skeleton contains only necessary class definitions and empty method bodies, with the minimum goal of ensuring successful compilation.
[0135] S2033 generates and outputs atomic change sets. After completing code generation in S2032, the system not only generates source code files but also simultaneously checks for associated configuration changes triggered by the new node. If This is a new Bean definition; the system automatically generates registration code in the XML configuration or Configuration class. If database table mapping is involved, the system generates corresponding DDL statements. The system will modify the source code. Configuration changes and Schema changes It is encapsulated as an indivisible "atomic change set".
[0136] Change set The structure is defined as follows:
[0137] ;
[0138] ;
[0139] in, The file path, To change the content, The change type is (Add / Modify). The system performs transactional integrity checks on the change set. This ensures that there are no dangling references when all changed files take effect simultaneously. Finally, the system presents this changeset to the user as a Diff view or writes it directly to the file system, thus completing missing dependencies while maintaining the consistency of the overall project configuration.
[0140] The present invention also provides a computer device, including: a processor and a memory, the memory storing a computer program executable by the processor, the computer program performing the method described above when executed by the processor.
[0141] The present invention also provides a storage medium storing a computer program, which is executed by a processor to perform the method described above.
[0142] The storage medium can be implemented by any type of volatile or non-volatile storage device or a combination thereof, such as Static Random Access Memory (SRAM), Electrically Erasable Programmable Read-Only Memory (EEPROM), Erasable Programmable Read-Only Memory (EPROM), Programmable Read-Only Memory (PROM), Read-Only Memory (ROM), magnetic storage, flash memory, magnetic disk, or optical disk.
[0143] Although embodiments of the invention have been shown and described, it will be understood by those skilled in the art that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the appended claims and their equivalents.< / t>
Claims
1. An adaptive code processing method based on artificial intelligence, characterized in that, Includes the following steps: The source code files and configuration files of the software project are parsed to build a heterogeneous dependency graph. The graph nodes are divided into white, gray and black areas according to the completeness of the parsed source, and static edge fingerprints containing caller information and line number offsets are calculated. Collect call stack data during application execution and generate dynamic edge fingerprints. Match the dynamic edge fingerprints with the static edge fingerprints. Update the confidence of the graph nodes or create dynamic dependency edges based on the matching results. In response to an input event, nodes in the heterogeneous dependency graph are retrieved as context to drive the model to generate candidate code. Logical reachability checks are performed on the candidate code, and an interception instruction is triggered when an invalid call involving the white zone node is made. In response to the interception command, a virtual node is created in the heterogeneous dependency graph, and an atomic operation set including source code changes and configuration file changes is generated according to the priority preset strategy of local search, global clustering and framework default.
2. The adaptive code processing method based on artificial intelligence according to claim 1, characterized in that, Parsing source code files and configuration files of software engineering to build a heterogeneous dependency graph includes: Traverse the target project's file directory, call the language parser to generate an abstract syntax tree for the source code files, and extract class declarations, method declarations, and field declarations from the abstract syntax tree as atomic nodes; The parser extracts the configuration item definitions, application interface routing configurations, and database connection pool configurations from the configuration file, maps the configuration item definitions to graph nodes, and uses the path of the configuration file as the source attribute of the graph nodes. Parse the table creation statements in the Data Definition Language file, map the database table structure to data entity nodes, and map column definitions to field nodes.
3. The adaptive code processing method based on artificial intelligence according to claim 1, characterized in that, Based on the completeness of the parsed source, the graph nodes are divided into white, gray, and black regions, including: The static information integrity index of the graph node is calculated based on whether the source code file of the graph node exists, whether the abstract syntax tree is parsed without errors, whether only compiled bytecode or interface definition exists, and whether it has been obfuscated. If the static information integrity index is greater than or equal to the preset white area determination threshold, the map node is classified into the white area; If the static information integrity index is less than or equal to the preset black area determination threshold, the map node is classified into the black area; If the static information integrity index is between the black area determination threshold and the white area determination threshold, the map node is classified into the gray area.
4. The adaptive code processing method based on artificial intelligence according to claim 1, characterized in that, Calculating the static edge fingerprint, which includes caller information and row number offset, includes: Traverse the call expressions inside the method definition bodies of the abstract syntax tree of the source code file; For each of the calling expressions, extract the unique signature of the calling method, the name of the called party, and the line number offset of the calling expression within the body of the calling method. The static edge fingerprint is generated by calculating the unique signature of the calling method, the name of the called party, and the offset of the calling line number using a hash mapping function.
5. The adaptive code processing method based on artificial intelligence according to claim 4, characterized in that, Collecting call stack data during application execution and generating dynamic edge fingerprints includes: Implant probes during application startup to intercept the call stack information of the current thread in real time, and extract the runtime class information, runtime method signature, line number of the call, and the actual receiving object type of the callee. Based on the caller's runtime method signature, the actual receiving object type of the callee, and the runtime line number offset calculated based on the line number of the initiating call, a dynamic edge fingerprint is generated using the same hash mapping function as that used to calculate the static edge fingerprint.
6. The adaptive code processing method based on artificial intelligence according to claim 5, characterized in that, Updating the confidence of the graph nodes or creating dynamic dependency edges based on the matching results includes: The dynamic edge fingerprint is indexed and matched with the existing static edge fingerprint in the heterogeneous dependency graph. When a match is successful, it is determined that the corresponding static dependency in the heterogeneous dependency graph is valid at runtime, and the edge confidence corresponding to the static dependency is increased. When a match fails, the node corresponding to the caller and the node corresponding to the callee are connected in the heterogeneous dependency graph to create a dynamic dependency edge, and the dynamic dependency edge is marked as dynamic type.
7. The adaptive code processing method based on artificial intelligence according to claim 1, characterized in that, Performing a logical reachability check on the candidate code includes: The candidate code is parsed and dependency reference information is extracted, including the class name, method name, and parameter type of the call. Determine the region to which the target node corresponding to the dependency reference information belongs in the heterogeneous dependency graph; If the target node belongs to the white area, perform exact matching verification. If the target node does not define a method name or the parameter type cannot be exactly matched, it is determined to be an invalid call. If the target node belongs to the gray area, calculate the fingerprint similarity between the dependency reference information and the known interface features in the gray area, and output a warning message when the fingerprint similarity is lower than a preset threshold.
8. The adaptive code processing method based on artificial intelligence according to claim 1, characterized in that, The set of atomic operations generated according to the preset strategy, which includes source code changes and configuration file changes, includes: The following strategies will be executed in descending order of priority: Prioritize searching for sibling nodes in the heterogeneous dependency graph that are located in the same package path as the virtual node or have the same parent class inheritance relationship. If the sibling node exists, extract the configuration pattern of the sibling node to generate the configuration code of the virtual node. If the sibling node does not exist, perform abstract syntax tree subtree hash clustering on the nodes in the heterogeneous dependency graph to identify global code patterns and generate configuration code for the virtual node; If the global code pattern cannot be identified, generate skeleton code consisting of class definitions and empty method bodies according to the programming language and framework specifications.
9. The adaptive code processing method based on artificial intelligence according to claim 8, characterized in that, Extracting the configuration mode of the sibling node includes: Calculate the proximity of the sibling node and the virtual node in the physical directory path and the overlap of the metadata sets; The sibling node with the highest similarity is selected as the template prototype; Extract the object-relational mapping annotations, log framework definitions, and transaction control methods used in the template prototype, and combine them with the constraint information of the virtual nodes to generate the corresponding source code and configuration file content.
10. The adaptive code processing method based on artificial intelligence according to claim 1, characterized in that, The atomic operation set satisfies the transaction integrity verification requirements, ensuring that there are no dangling references when the source code changes and configuration file changes take effect simultaneously.