Intelligent understanding methods, devices, equipment, and storage media for code repositories
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-10
- Publication Date
- 2026-08-14
AI Technical Summary
[0004]本申请的主要目的在于提供一种代码仓库的智能理解方法、装置、设备及存储介质,旨在解决对代码仓库的整体结构理解碎片化的技术问题
Smart Images

Figure CN122569948A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of code repository technology, and in particular to intelligent understanding methods, apparatus, devices and storage media for code repositories. Background Technology
[0002] With the popularization of cloud-native and microservice architectures and the deepening of open-source collaboration models, modern software code repositories are characterized by continuous expansion in scale, multi-language hybrid development, increasingly complex dependencies, and a surge in iteration frequency. Existing technologies primarily achieve code repository understanding through text retrieval, static program analysis, vector semantic retrieval, and direct understanding of large models. However, text retrieval relies solely on keyword matching of literal symbols, static program analysis is limited to single-file or single-function granularity, vector semantic retrieval is prone to semantic drift during dimensionality reduction, and direct understanding of large models is constrained by context windows and lacks external knowledge verification. These technologies have significant shortcomings in practical applications. In particular, traditional static program analysis methods lack the ability to model global relationships, making it difficult to automatically identify logical aggregates across modules. This results in a fragmented understanding of the overall structure of the code repository, hindering efficient analysis of large-scale, complex repositories.
[0003] The above content is only used to help understand the technical solution of this application and does not represent an admission that the above content is prior art. Summary of the Invention
[0004] The main purpose of this application is to provide a method, apparatus, device and storage medium for intelligent understanding of code repositories, aiming to solve the technical problem of fragmented understanding of the overall structure of code repositories.
[0005] To achieve the above objectives, this application proposes an intelligent understanding method for code repositories, the method comprising: Traverse the abstract syntax tree corresponding to the source code file, extract the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and construct a code knowledge graph; The code knowledge graph is logically divided into several initial logical community subgraphs based on the code semantic nodes using a community discovery algorithm. The code semantic nodes in the initial logical community subgraph are vectorized to generate node semantic vectors, which are then stored in the corresponding code semantic nodes to obtain the target logical community subgraph. The code semantic nodes of the target logical community subgraph are retrieved based on a hybrid retrieval strategy to determine candidate code node subgraphs; Enhanced reasoning is performed on the candidate code node subgraph based on the target rules corresponding to the application query scenario to generate code understanding results.
[0006] In one embodiment, the step of dividing the code knowledge graph into logical communities based on the code semantic nodes using a community detection algorithm to obtain several initial logical community subgraphs includes: The code semantic node is initialized as an initial community, and the initial community of the code semantic node is iteratively merged into the neighboring communities through a community discovery algorithm to obtain an intermediate community; Determine the size of the community nodes in the intermediate community, and determine whether the size of the community nodes exceeds a preset size threshold; If the size of the community node is smaller than the size threshold, then the subgraph corresponding to the intermediate community is used as the initial logical community subgraph. If the size of the community nodes is greater than the size threshold, the intermediate community is divided into local communities, and the subgraph corresponding to the local community is used as the initial logical community subgraph.
[0007] In one embodiment, the step of performing a secondary division of the intermediate community to obtain local communities includes: Extract the semantic nodes and semantic relationship edges from the intermediate community to construct a local subgraph; Determine whether there are connected edges inside the local subgraph; If there are connecting edges within the local subgraph, the local subgraph is further divided according to the principle of optimal internal modularity to obtain the local community; If there are no connecting edges within the local subgraph, then the code semantic nodes in the local subgraph are taken as the local community.
[0008] In one embodiment, the step of vectorizing the code semantic nodes in the initial logical community subgraph to generate node semantic vectors and storing them in the corresponding code semantic nodes to obtain the target logical community subgraph includes: In the initial logical community subgraph, the name, docstring, and function signature of the code semantic node are extracted and concatenated into node text; The pre-trained text embedding model is invoked to vectorize the node text, generating node semantic vectors; The semantic vectors of the nodes are normalized, and the normalized vectors are written into the corresponding code semantic nodes to obtain the target logical community subgraph.
[0009] In one embodiment, the step of retrieving code semantic nodes of the target logical community subgraph based on a hybrid retrieval strategy to determine candidate code node subgraphs includes: The user query request is converted into a query vector, and the similarity between the query vector and the node semantic vector of each code semantic node in the target logical community subgraph is calculated. The semantic retrieval results are obtained by sorting them by similarity. The user query request is segmented into words, and the keyword retrieval results are obtained by matching the text attributes of the code semantic nodes in the target logical community subgraph based on the word frequency. Based on the ranking position of each code semantic node in the semantic retrieval results and the keyword retrieval results, a fusion score is calculated using a reciprocal ranking fusion algorithm, and candidate code node subgraphs are determined based on the fusion score.
[0010] In one embodiment, the step of performing enhanced reasoning on the candidate code node subgraph based on the target rules corresponding to the application query scenario to generate code understanding results includes: Identify the target scenario type corresponding to the application query scenario; The target rules that match the target scenario type are determined from a pre-configured scenario-based rule base. The target rules include at least one of architecture understanding rules, impact analysis rules, defect tracking rules, and refactoring assistance rules. Based on the target rules, the relationships between the candidate code node subgraphs in the code knowledge graph are traversed and analyzed to generate code understanding results.
[0011] In one embodiment, the step of traversing the abstract syntax tree corresponding to the source code file, extracting the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and constructing a code knowledge graph includes: An abstract syntax tree is generated by parsing the source code file using a syntax parser. Traverse the abstract syntax tree, identify the syntax unit nodes of the abstract syntax tree, and obtain the code semantic nodes; In the abstract syntax tree, the calling relationships, definition relationships, and dependency relationships between the syntax unit nodes are identified, and corresponding semantic relationship edges are generated.
[0012] Furthermore, to achieve the above objectives, this application also proposes an intelligent understanding device for code repositories, the intelligent understanding device for code repositories comprising: The graph construction module is used to traverse the abstract syntax tree corresponding to the source code file, extract the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and construct a code knowledge graph. The initial community module is used to divide the code knowledge graph into logical communities based on the code semantic nodes using a community discovery algorithm, resulting in several initial logical community subgraphs. The target community module is used to vectorize the code semantic nodes in the initial logical community subgraph, generate node semantic vectors and store them in the corresponding code semantic nodes to obtain the target logical community subgraph. The hybrid retrieval module is used to retrieve code semantic nodes of the target logical community subgraph based on a hybrid retrieval strategy, and determine candidate code node subgraphs; The enhanced reasoning module is used to perform enhanced reasoning on the candidate code node subgraph based on the target rules corresponding to the application query scenario, and generate code understanding results.
[0013] In addition, to achieve the above objectives, this application also proposes an intelligent understanding device for code repositories, the device comprising: a memory, a processor, and a computer program stored in the memory and executable on the processor, the computer program being configured to implement the steps of the intelligent understanding method for code repositories as described above.
[0014] In addition, to achieve the above objectives, this application also proposes a storage medium, which is a computer-readable storage medium, on which a computer program is stored, and when the computer program is executed by a processor, it implements the steps of the intelligent understanding method of the code repository as described above.
[0015] In addition, to achieve the above objectives, this application also provides a computer program product, which includes a computer program that, when executed by a processor, implements the steps of the intelligent understanding method for the code repository as described above.
[0016] One or more technical solutions proposed in this application have at least the following technical effects: This application proposes an intelligent understanding method, apparatus, device, and storage medium for code repositories. It traverses the abstract syntax tree (AST) corresponding to the source code files, extracts the code semantic nodes and semantic relationship edges between them, and constructs a code knowledge graph. A community detection algorithm is used to logically divide the code knowledge graph into several initial logical community subgraphs based on the code semantic nodes. The code semantic nodes in the initial logical community subgraphs are vectorized to generate node semantic vectors, which are then stored in the corresponding code semantic nodes to obtain target logical community subgraphs. A hybrid retrieval strategy is used to search the code semantic nodes in the target logical community subgraphs to determine candidate code node subgraphs. Enhanced reasoning is performed on the candidate code node subgraphs according to the target rules corresponding to the application query scenario to generate code understanding results. By constructing a complete chain of code knowledge graph, logical community division, vectorization processing, hybrid retrieval, and scenario-based rule-enhanced reasoning, a global structured understanding and intelligent analysis of large-scale complex code repositories is achieved. Attached Figure Description
[0017] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application.
[0018] To more clearly illustrate the technical solutions in the embodiments of this application or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, for those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0019] Figure 1 A flowchart illustrating the intelligent understanding method embodiment 1 of the code repository of this application; Figure 2 A flowchart illustrating the second embodiment of the intelligent understanding method for the code repository of this application; Figure 3 A simplified flowchart illustrating the intelligent understanding method for the code repository provided in Embodiment 2 of this application; Figure 4 This is a schematic diagram of the module structure of the intelligent understanding device in the code repository of this application embodiment; Figure 5 This is a schematic diagram of the device structure of the hardware operating environment involved in the intelligent understanding method of the code repository in the embodiments of this application.
[0020] The purpose, features, and advantages of this application will be further explained in conjunction with the embodiments and with reference to the accompanying drawings. Detailed Implementation
[0021] It should be understood that the specific embodiments described herein are merely illustrative of the technical solutions of this application and are not intended to limit this application.
[0022] To better understand the technical solution of this application, a detailed description will be provided below in conjunction with the accompanying drawings and specific implementation methods.
[0023] The main solution of this application embodiment is as follows: traverse the abstract syntax tree corresponding to the source code file, extract the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and construct a code knowledge graph; use a community detection algorithm to logically divide the code knowledge graph based on the code semantic nodes to obtain several initial logical community subgraphs; vectorize the code semantic nodes in the initial logical community subgraphs to generate node semantic vectors and store them in the corresponding code semantic nodes to obtain target logical community subgraphs; search the code semantic nodes of the target logical community subgraphs based on a hybrid retrieval strategy to determine candidate code node subgraphs; perform enhanced reasoning on the candidate code node subgraphs according to the target rules corresponding to the application query scenario to generate code understanding results.
[0024] In this embodiment, for ease of description, the following description uses the intelligent understanding device of the code repository as the execution subject.
[0025] With the popularization of cloud-native and microservice architectures and the deepening of open-source collaboration models, modern software code repositories are characterized by continuous expansion in scale, multi-language hybrid development, increasingly complex dependencies, and a surge in iteration frequency. Existing technologies primarily achieve code repository understanding through text retrieval, static program analysis, vector semantic retrieval, and direct understanding of large models. However, text retrieval relies solely on keyword matching of literal symbols, static program analysis is limited to single-file or single-function granularity, vector semantic retrieval is prone to semantic drift during dimensionality reduction, and direct understanding of large models is constrained by context windows and lacks external knowledge verification. These technologies have significant shortcomings in practical applications. In particular, traditional static program analysis methods lack the ability to model global relationships, making it difficult to automatically identify logical aggregates across modules. This results in a fragmented understanding of the overall structure of the code repository, hindering efficient analysis of large-scale, complex repositories.
[0026] This application provides a solution that achieves a global structured understanding and intelligent analysis of large-scale complex code repositories by constructing a complete chain of code knowledge graphs, logical community division, vectorization processing, hybrid retrieval, and scenario-based rule-enhanced reasoning.
[0027] It should be noted that the executing entity in this embodiment can be a computing service device with data processing, network communication, and program execution functions, such as a tablet computer, personal computer, or mobile phone, or an electronic device capable of performing the above functions, such as an intelligent understanding device for code repositories. The following description uses an intelligent understanding device for code repositories as an example to illustrate this embodiment and the subsequent embodiments.
[0028] Based on this, embodiments of this application provide an intelligent understanding method for code repositories, referring to... Figure 1 , Figure 1 This is a flowchart illustrating the first embodiment of the intelligent understanding method in the code repository of this application.
[0029] In this embodiment, the intelligent understanding method for the code repository includes steps S11 to S15: Step S11: Traverse the abstract syntax tree corresponding to the source code file, extract the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and construct a code knowledge graph.
[0030] It should be noted that an Abstract Syntax Tree (AST) is a tree-like structure generated by a parser after performing lexical and syntactic analysis on the source code. Each node corresponds to a syntactic unit in the source code (such as variable declaration, function definition, class definition, etc.), used to completely preserve the structured information of the code. Semantic nodes are entity nodes with clear semantics extracted from the AST, including but not limited to file nodes, class nodes, function nodes, and variable nodes. Each node carries meta-information of the corresponding code unit (such as file path, class name, function parameter list, etc.). Semantic relationship edges are edges that describe the logical connections between semantic nodes, including call edges (CALLS, representing function A calling function B), definition edges (DEFINES, representing file containing class, class containing method), dependency edges (IMPORT, representing file A depending on file B), etc. A code knowledge graph is a graph structure with semantic nodes as vertices and semantic relationship edges as directed edges, used to globally model the logical topology of the code repository.
[0031] Understandably, the purpose of this step is to transform unstructured source code into structured graph data, addressing the limitations of traditional text retrieval, which only matches literal text and static analysis, which is confined to single files. By traversing the AST to extract all semantic nodes and cross-file relationship edges, we can comprehensively cover the code's hierarchical structure, cross-module calls, implicit dependencies, and other information, providing foundational data support for subsequent global logic analysis and semantic retrieval, and avoiding the omission of key code connections.
[0032] Specifically, this step can be implemented in three feasible ways: The first is a basic and general implementation method. Based on the programming language of the code repository, a corresponding Tree-sitter parser is selected. After reading the source code file content, a parsing function is called to generate an Abstract Syntax Tree (AST). A depth-first traversal of the AST identifies syntactic units such as ClassDef (class definition node), FunctionDef (function definition node), and VariableDeclaration (variable declaration node) to generate corresponding code semantic nodes. Simultaneously, import statements are scanned to generate dependency edges, function call expressions are identified to generate call edges, and definition edges are generated based on the nesting relationships of syntactic units. Finally, the nodes and edges are combined to construct a code knowledge graph. This method is adaptable to Java. The first approach uses three main implementation methods: 1) Global relationship modeling across files; 2) Enhanced implementation for dynamic languages, adding implicit relationship deduction logic to the basic process. For example, for Julia code, this involves tracing nested structures through the scope stack, concatenating fragmented identifiers, and generating corresponding semantic edges by identifying multiple dispatch relationships. This approach addresses the challenges of adapting to the flexible syntax of dynamic languages and the difficulty of static analysis, covering complex features such as macros, generics, and multiple dispatch. 3) Multi-language hybrid repository implementation, matching corresponding Tree-sitter parsers to files with different suffixes in the repository, performing parsing and node relationship extraction in parallel, and finally merging them into a unified code knowledge graph. This approach supports multi-language hybrid development scenarios. These three implementation methods can be combined as needed. For example, when processing Julia code in a hybrid language repository, the second and third methods can be used simultaneously, adapting to the characteristics of dynamic languages and achieving unified modeling of multi-language repositories, ultimately achieving a structured transformation of the entire codebase and providing complete foundational data for subsequent processes.
[0033] Step S12: The code knowledge graph is logically divided into several initial logical community subgraphs based on the code semantic nodes using a community discovery algorithm.
[0034] It should be noted that the community detection algorithm is used to identify sets of tightly connected nodes in a graph. The Louvain algorithm is preferred here, and the quality of community partitioning is measured by calculating the modularity. A logical community is a subgraph composed of semantic nodes of code. The connection density between internal nodes is much higher than the connection density between nodes in other communities, reflecting the real logical coupling relationship of the code, rather than the physical folder structure. The initial logical community subgraph is the subgraph corresponding to the community obtained by the first round of partitioning of the community detection algorithm, which contains all nodes in the community and the semantic relationship edges between nodes.
[0035] Understandably, the purpose of this step is to overcome the limitations of the physical directory structure of the code and identify logical aggregation units across files. The folder structure of traditional code repositories often fails to reflect the true coupling of business logic (such as order-related code scattered across different directories). By mining the topological features of the code knowledge graph through community discovery algorithms, functionally related code can be aggregated into the same logical community, providing a foundation for subsequent adaptation to the context window of large models and improving retrieval accuracy.
[0036] Specifically, this step can be implemented in two feasible ways: The first is the standard Louvain partitioning implementation, which initializes each code semantic node as an independent community, traverses each node and attempts to move it to a neighboring community, calculates the change in global modularity before and after the move, and performs the move if the modularity increases. This process is repeated until the modularity no longer increases to obtain an intermediate community. Then, the nodes and edges of each intermediate community are extracted to generate an initial logical community subgraph. This method is suitable for medium-sized code repositories and can quickly obtain logically aggregated communities. The second is the incremental update implementation, which only re-executes the iterative merging on the nodes involved in the change and their neighboring communities, without the need for a full repartition. This method can reduce the update cost of large-scale repositories and improve processing efficiency.
[0037] Step S13: Vectorize the code semantic nodes in the initial logical community subgraph to generate node semantic vectors and store them in the corresponding code semantic nodes to obtain the target logical community subgraph.
[0038] It should be noted that vectorization is the process of converting textual information into fixed-dimensional numerical vectors. In one embodiment of this application, a pre-trained text-embedding-v4 model is used to achieve this. Node semantic vectors are vector representations of the text corresponding to code semantic nodes, which can capture the logical semantic features of the code. The target logical community subgraph is the logical community subgraph after the node vectors are stored. It retains the original graph structure and adds semantic vector attributes to the nodes, supporting semantic similarity calculation.
[0039] Understandably, the purpose of this step is to fuse the structured and semantic information of the code, resolving issues such as semantic drift in vector retrieval and the inability of keyword retrieval to match synonyms. By converting information such as the name, document, and signature of code nodes into vectors, the logical similarity of the code can be represented in vector space, providing a semantic matching basis for subsequent hybrid retrieval. Simultaneously, the vectors, stored as node attributes, can be used in conjunction with graph structure information.
[0040] Specifically, a standard vectorization implementation is adopted. For each code semantic node, the name, docstring, and function signature are extracted and concatenated into node text. After generating vectors using the text-embedding-v4 model, L2 normalization is performed, and the unit vectors are written into the node attributes. This method is suitable for most code nodes and can balance semantic coverage and processing efficiency. For nodes with excessively long docstrings (such as those exceeding the model input length limit), the text is split into semantic blocks and vectorized separately. The average of multiple vectors is then taken to obtain the node semantic vector. This method can avoid information loss caused by truncation of long texts. At the same time, vectorization processing is performed on newly added or changed nodes, and the existing vectors of unchanged nodes are reused. This method can reduce the update overhead of large-scale repositories.
[0041] Step S14: Based on the hybrid retrieval strategy, the code semantic nodes of the target logical community subgraph are retrieved to determine the candidate code node subgraph.
[0042] It should be noted that the hybrid retrieval strategy is a retrieval scheme that combines keyword matching and semantic similarity matching. In one embodiment of this application, a combination of BM25 retrieval and vector semantic retrieval is adopted. The target logical community subgraph is a logical community subgraph with node vectors. The candidate code node subgraph is a subgraph composed of the retrieved code nodes related to the user query and the relationship edges between the nodes, which is used for subsequent reasoning and analysis.
[0043] Understandably, the purpose of this step is to address the shortcomings of single search methods: BM25 search can accurately match keywords such as core function names and class names in code, but it cannot handle synonyms; semantic search can capture potential logical connections, but it is prone to semantic drift. By combining the advantages of both through hybrid search, the accuracy of literal matching and the integrity of semantic connections can be guaranteed simultaneously, outputting a highly relevant set of candidate code.
[0044] Specifically, a dual-path parallel retrieval implementation method is first adopted, where user queries are simultaneously input into semantic retrieval and BM25 retrieval channels. Cosine similarity and BM25 scores are calculated separately and then ranked. The final result is obtained by fusing the rankings using the RRF algorithm. This method is suitable for general query scenarios and can take into account both semantic and keyword matching. At the same time, a scenario-adaptive weight implementation method is adopted, which dynamically adjusts the weights of the two types of retrieval according to the user query scenario. For example, in the architecture understanding scenario, semantic association is emphasized, so the weight of semantic retrieval is increased. In the impact analysis scenario, precise matching is emphasized, so the weight of BM25 retrieval is increased. This method can improve the retrieval accuracy in specific scenarios. Furthermore, a community pruning implementation method is adopted, which first locates possible relevant logical communities based on the initial keyword matching of the user query. The retrieval is only performed within the corresponding community, reducing the computational overhead of irrelevant nodes. This method can improve the retrieval efficiency of large-scale repositories.
[0045] Step S15: Perform enhanced reasoning on the candidate code node subgraph according to the target rules corresponding to the application query scenario to generate code understanding results.
[0046] It should be noted that the application query scenario refers to the type of code understanding task initiated by the user, including architecture understanding, impact analysis, defect tracking, refactoring assistance, etc.; the target rule is a pre-configured inference rule that matches the scenario, defining the graph traversal logic and output paradigm under different scenarios; the enhanced inference is a logical deduction based on the structural relationships and rule constraints of the code knowledge graph, avoiding the illusion of large models being generated freely; the code understanding result is the output content that meets the requirements of the scenario obtained by inference, such as architectural dependencies, scope of impact, defect paths, etc.
[0047] Understandably, the purpose of this step is to address the illusion problem when large models directly understand code. By constraining the inference process through scenario-based rules, the large model can analyze based on factual relationships within a graph. Rules for different scenarios can dynamically adapt to retrieval strategies and output structures. For example, in impact analysis scenarios, forced traversal of call edges ensures that no affected code is missed, significantly improving the accuracy and reliability of the results.
[0048] Specifically, in the single-scenario rule-based reasoning implementation of this application, after identifying the target scenario type of the user query, the corresponding rule is loaded (e.g., the explosion radius rule is loaded for impact analysis). A specified order is traversed along the specified relational edges (call edges, dependency edges) of the candidate nodes. After collecting associated nodes, the results are output according to the rule paradigm. This method is suitable for single, clear query scenarios, with a clear reasoning path and accurate results. In the multi-scenario fusion reasoning implementation of this application, when the query involves multiple scenarios (e.g., "reconstructing the order module and evaluating the impact"), multiple corresponding rules are loaded sequentially, and the reasoning is performed in stages before merging the results. This method can support code understanding for complex and composite requirements. Simultaneously, a manual feedback iterative implementation is adopted, allowing users to adjust the output results and feed the adjusted rules back to the rule base to optimize the reasoning logic for subsequent similar queries. This method can continuously improve the system's adaptability to specific business scenarios.
[0049] This embodiment, through the above-described scheme, breaks through the limitations of traditional code understanding methods by implementing a full-link process of code knowledge graph construction, logical community division, node vectorization, hybrid retrieval, and scenario-based reasoning. It achieves cross-file, full-granular code relationship modeling, integrates the advantages of keyword matching and semantic understanding, and suppresses the illusion of large models through rule constraints. It can efficiently support various understanding tasks such as architecture analysis, defect localization, and impact analysis of large-scale complex code repositories.
[0050] Based on the above implementation scheme, in one feasible implementation, the step of dividing the code knowledge graph into logical communities based on the code semantic nodes using a community detection algorithm to obtain several initial logical community subgraphs includes S21~S24: Step S21: Initialize the code semantic node as an initial community, and iteratively merge the initial community of the code semantic node into the neighboring communities through a community discovery algorithm to obtain an intermediate community.
[0051] It should be noted that the initial community is the initial state of community partitioning, with each code semantic node corresponding to an independent community; the neighbor community is the community to which the node with a semantic relationship edge with the current node belongs; the community discovery algorithm here preferably uses the Louvain algorithm, the core logic of which is to maximize the global modularity by adjusting the community to which the node belongs; the intermediate community is the community partitioning result obtained after iterative merging without scale filtering.
[0052] Understandably, the purpose of this step is to obtain a preliminary logical community division through iterative optimization. Initializing each node as an independent community avoids interference from prior assumptions on the division results. By continuously attempting to merge nodes into neighboring communities, closely connected nodes are gradually aggregated, making the logical relationships between nodes within the same community stronger, thus providing a foundation for subsequent scaled filtering.
[0053] Specifically, in one embodiment of this application, a standard Louvain iteration method is adopted. Each code semantic node is initialized as an independent community. All nodes are traversed, and the modularity gain of moving a node to each neighboring community is calculated. The direction with the largest gain is selected to perform the move. The iteration is repeated until the modularity has no continuous increase, resulting in an intermediate community. This method is applicable to most code repositories and can reliably obtain a high-quality initial partition. At the same time, a weighted edge iteration method is adopted. Different weights are set according to the type of semantic relationship edge (e.g., the weight of the call edge is higher than that of the dependency edge). A weight factor is introduced into the modularity calculation, so that the strong relationship has a greater impact on the community partitioning. This method can improve the logical rationality of the community partitioning and better reflect the actual coupling strength of the code.
[0054] Step S22: Determine the size of the community nodes in the intermediate community and determine whether the size of the community nodes exceeds a preset size threshold.
[0055] It should be noted that the community node size refers to the number of code semantic nodes contained in the intermediate community; the size threshold is a preset value limited by the context window of Graph RAG (Graph Retrieval Enhanced Generation), and the formula for calculating the size threshold is as follows: ,in To minimize the number of community nodes, This represents the total number of nodes in the entire graph. This is a limiting factor (e.g., 0.1), determined based on the specific scenario, used to balance community integrity and contextual adaptability.
[0056] Understandably, the purpose of this step is to filter out communities that are too large, preventing them from exceeding the context window of the large model during subsequent processing. If the community node size is too large, inputting it into the large model all at once will lead to information truncation or semantic loss. Therefore, it is necessary to divide it a second time to ensure that the size of all communities is suitable for the processing requirements.
[0057] Specifically, the first implementation method of this application is a fixed threshold implementation method, which calculates the scale threshold based on the preset minimum number of community nodes and the restriction coefficient, traverses the intermediate communities to count the node scale and compares it with the threshold. This method is suitable for scenarios with a fixed context window, is simple to configure and has stable results. The second implementation method is a dynamic adjustment implementation method, which dynamically adjusts the restriction coefficient according to the current model context window size. For example, when using a model with a larger window, the restriction coefficient is increased to allow for a larger community scale. This method can flexibly adapt to the processing capabilities of different models and improve resource utilization.
[0058] Step S23: If the size of the community node is smaller than the size threshold, then the subgraph corresponding to the intermediate community is used as the initial logical community subgraph.
[0059] It should be noted that the initial logical community subgraph is the subgraph corresponding to a community that meets the size requirements. It contains all nodes within the community and the semantic relationship edges between nodes, and can be directly used for subsequent vectorization, retrieval and other processing.
[0060] Understandably, the purpose of this step is to preserve the integrity of small-scale communities. These communities have a high degree of logical cohesion and can be fully input into subsequent processing flows without splitting, thus avoiding unnecessary splitting that could disrupt the coherence of the code logic.
[0061] Specifically, extract all nodes and semantic relationship edges between nodes within intermediate communities with a size less than a threshold, and construct the corresponding subgraph, which is the initial logical community subgraph.
[0062] Step S24: If the size of the community node is greater than the size threshold, the intermediate community is divided into local communities, and the subgraph corresponding to the local community is used as the initial logical community subgraph.
[0063] It should be noted that the secondary partitioning is a fine-grained split of the ultra-large-scale community, which is performed based on the local topological features within the community; the local community is a smaller sub-community obtained after the secondary partitioning, whose node size does not exceed the size threshold; the initial logical community subgraph is the subgraph corresponding to the local community.
[0064] Understandably, the purpose of this step is to reduce the dimensionality of the ultra-large-scale community by breaking it down into sub-units that adapt to the context window without destroying the internal logical connections. This preserves the logical integrity of the community while meeting the scale requirements of subsequent processing.
[0065] Specifically, one implementation of this application is to adopt a standard quadratic partitioning approach, extracting internal nodes and edges from the super-large intermediate community to construct a local subgraph. If the subgraph has connecting edges, the Louvain algorithm is used to split it according to the principle of optimal local modularity. If there are no connecting edges, each node is treated as an independent local community. This approach is suitable for splitting most super-large communities. Another implementation of this application is to adopt a hierarchical quadratic partitioning approach, first performing coarse-grained splitting on the super-large community, and then repeatedly splitting the still super-large sub-communities until all sub-communities meet the size requirements. This approach avoids the computational pressure of a single split and is suitable for communities with extremely large node sizes.
[0066] This embodiment solves the problems of uneven community partitioning results and easy exceeding of the large model context window by adding a scale threshold judgment and a secondary partitioning mechanism for super-large communities after the initial partitioning of the Louvain algorithm. This ensures that all logical community subgraphs can be efficiently processed by subsequent processes, while preserving the logical aggregation characteristics of the code to the greatest extent.
[0067] Based on the above implementation scheme, in one feasible implementation, the step of performing secondary division of the intermediate community to obtain the local community includes S31~S34: Step S31: Extract the code semantic nodes and semantic relationship edges in the intermediate community and construct a local subgraph.
[0068] It should be noted that a local subgraph is a subgraph that only contains the internal nodes and internal edges of the intermediate community, and does not contain the edges connecting it to other communities. It is used for independent secondary partitioning.
[0069] Understandably, the purpose of this step is to isolate the topological information of oversized communities and prevent nodes from other communities from interfering with the results of the secondary partitioning. By extracting the nodes and edges within a community, we can focus on the logical structure of that community and achieve more accurate, fine-grained partitioning.
[0070] Specifically, all semantic nodes of the intermediate community to be split are traversed, and all semantic relationship edges between these nodes are collected (excluding edges connected to nodes outside the community). The nodes and edges are combined to construct a local subgraph. This method is applicable to most scenarios and can completely preserve the internal topology of the community. At the same time, a weighted filtering method is adopted. When extracting edges, weakly related edges are filtered according to the type or strength of the edges. Only edges with weights higher than the threshold are retained to construct the local subgraph. This method can reduce the interference of noisy edges on the secondary partitioning and improve the purity of community partitioning.
[0071] For example, the intermediate community to be split contains nodes A, B, C, and D, where A has an edge with B, C has an edge with D, and B has an edge with node E outside the community. Then, extract the four nodes A, B, C, and D, as well as the two edges AB and CD, to construct a local subgraph.
[0072] Step S32: Determine whether there are any connected edges inside the local subgraph.
[0073] It should be noted that the connecting edge is the semantic relationship edge between nodes within the local subgraph. If there is at least one pair of nodes with an edge between them, it is determined that there is a connecting edge; if all nodes are isolated points, it is determined that there is no connecting edge.
[0074] Understandably, the purpose of this step is to distinguish the topological features of local subgraphs and adopt different partitioning strategies for subgraphs with different features: subgraphs with connected edges have a topological basis for further splitting, while subgraphs without connected edges have no logical aggregation and do not need to be split.
[0075] Specifically, iterate through all node pairs in the local subgraph and check if there are semantic relationship edges.
[0076] For example, if the aforementioned local subgraph contains two edges AB and CD, it is determined that there are connected edges; if the local subgraph only contains nodes F and G and has no edges, it is determined that there are no connected edges.
[0077] Step S33: If there are connecting edges inside the local subgraph, the local subgraph is further divided according to the principle of optimal internal modularity to obtain the local community.
[0078] It should be noted that the principle of optimal internal modularity refers to maximizing local modularity during the partitioning of local subgraphs. The modularity calculation formula is consistent with the global Louvain algorithm. Local communities are the sub-communities obtained after further partitioning, and their modularity calculation formula is as follows:
[0079] in, This is the modularity value, which is typically in the range of [ The range is between [1,1] (for large images, this range may be exceeded, but it is generally considered that the range between [0,1] is meaningful). The larger the value, the more prominent the community structure, meaning that the nodes within a community are closely connected, while the nodes between communities are sparsely connected. This represents the total number of sides. For the elements of the adjacency matrix, if the node and nodes If there is an edge, then =1; otherwise =0. It represents the actual connection state between the two nodes. For nodes and nodes The degree. This is the Kronecker function, which is an indicator function. If the node... and nodes Classified into the same community If the value is 1, then the value is 1; otherwise, the value is 0.
[0080] Understandably, the purpose of this step is to perform fine-grained clustering on connected local subgraphs to further uncover their more tightly packed logical sub-units. By optimizing local modularity, more functionally focused sub-modules can be identified within large-scale communities, avoiding the disruption of core logical connections caused by splitting.
[0081] Specifically, the Louvain algorithm is applied to the local subgraph, and iterative partitioning is performed with the goal of maximizing the local modularity until the node size of all sub-communities does not exceed the size threshold. During the local Louvain iteration, if the size of a sub-community exceeds the threshold, it is forcibly split until all sub-communities meet the requirements. This method can avoid the situation where the size exceeds the threshold again during the iteration process and improve the splitting efficiency.
[0082] For example, in the local subgraph containing edges AB and CD, if the size threshold is still 50 and the current node size is 4, no further splitting is needed; {A,B} and {C,D} are directly divided into two local communities. If the local subgraph contains 60 nodes and has multiple connection clusters, it is split into multiple local communities with a node size ≤ 50.
[0083] Step S34: If there are no connecting edges inside the local subgraph, then the code semantic nodes in the local subgraph are taken as the local community.
[0084] It should be noted that local communities treat each isolated node as a separate community, because nodes without connections have no logical relationship, and forced aggregation is meaningless.
[0085] Understandably, the purpose of this step is to process local subgraphs without internal connections and avoid invalid partitions. Nodes in such subgraphs are aggregated only due to the initial Louvain partition and are not actually logically coupled. Therefore, treating each node as a separate local community ensures the accuracy of subsequent processing.
[0086] Specifically, by traversing all isolated nodes in the local subgraph, each node corresponds to a local community. This eliminates the need to construct complex subgraphs and avoids invalid processing of unrelated nodes, ensuring the accuracy of subsequent reasoning.
[0087] For example, if a local subgraph contains isolated nodes F and G, then F and G are respectively regarded as two independent local communities.
[0088] This embodiment employs the above-described scheme and a differentiated secondary partitioning strategy based on the internal topological characteristics of ultra-large communities. This approach not only performs fine-grained splitting of logically related communities but also avoids invalid processing of unrelated nodes. While ensuring the logical integrity of the communities, it also ensures that all subgraphs are adapted to the scale requirements of subsequent processing flows.
[0089] Based on the above implementation scheme, in one feasible implementation, the step of vectorizing the code semantic nodes in the initial logical community subgraph to generate node semantic vectors and storing them in the corresponding code semantic nodes to obtain the target logical community subgraph includes S41~S43: Step S41: In the initial logical community subgraph, extract the name, document string and function signature of the code semantic node, and concatenate them into node text.
[0090] It should be noted that the semantic node name is the identifier of the node (such as file name, class name, function name), used to reflect the core semantics of the node; the docstring is the comment text in the code that follows the node definition, used to explain the function of the node, the meaning of the parameters, etc.; the function signature is the parameter list and return value type label of the function, used to reflect the input and output characteristics of the function; the node text is a string concatenated from the above three types of information, serving as the vectorized input source.
[0091] Understandably, the purpose of this step is to transform the structured meta-information of the code into a text format suitable for vector model processing. Node names carry the core semantics, docstrings supplement the functional description, and function signatures reflect logical characteristics. Concatenating these three elements comprehensively covers the semantic information of code nodes, avoiding semantic gaps caused by single pieces of information.
[0092] Specifically, information is extracted based on node type (file nodes extract filenames, class nodes extract class names and comments, function nodes extract names, docstrings, and signatures), and concatenated in the format of "name + document + signature". This method is suitable for most nodes and can balance information coverage and conciseness. Adding a node type prefix (such as "function:" or "class:") during concatenation helps the model better distinguish node semantics, which can improve the semantic clarity of vector representations. Excessively long docstrings are truncated according to semantic integrity, retaining the core descriptive part and avoiding exceeding the model input length. This method can adapt to the processing of long document nodes.
[0093] Step S42: Call the pre-trained text embedding model to vectorize the node text and generate node semantic vectors.
[0094] It should be noted that the pre-trained text embedding model is a pre-trained model based on the Transformer architecture, which supports long text input and multilingual alignment. It can map natural language and code text to the same vector space. In one embodiment of this application, the text-embedding-v4 model is selected as the pre-trained text embedding model. The node semantic vector is a fixed-dimensional floating-point array output by the model. Each dimension corresponds to a semantic feature, and the distance between the vectors can reflect the similarity of the text semantics.
[0095] Understandably, the purpose of this step is to transform discrete text information into continuous vector representations, capturing the deep logical semantics of the code. The pre-trained model has learned syntactic and semantic features on a large corpus of code, accurately identifying logical connections in the code, and the generated vectors can support subsequent semantic similarity calculations.
[0096] Specifically, the text-embedding-v4 model is called through an external interface, with the node text as input and the vector returned by the model as the node semantic vector. Multiple node texts can be input into the model in batches, and multiple vectors can be obtained at once. This method can reduce the number of interface calls and improve the processing efficiency of large-scale nodes.
[0097] Step S43: Normalize the node semantic vector and write the normalized vector into the corresponding code semantic node to obtain the target logical community subgraph.
[0098] It should be noted that the normalization process here uses L2 normalization, which calculates the L2 norm of the vector. The formula is as follows:
[0099] in, For node semantic vectors; These are the numerical values of the node's semantic vector in each dimension; Let L2 be the L2 norm of the node semantic vector.
[0100] Furthermore, the original node semantic vector is normalized to obtain a unit vector, calculated using the following formula:
[0101] in, This is the normalized standard vector.
[0102] The target logical community subgraph is the logical community subgraph after vector storage is completed. It retains the original graph structure and node attributes, and adds the Embedding (vector embedding) attribute.
[0103] Understandably, the purpose of this step is to eliminate the interference of vector magnitude length on similarity calculation and improve retrieval stability. Cosine similarity is determined solely by the angle between vectors; calculating cosine similarity for unit vectors avoids bias caused by node text length, ensuring that semantically similar nodes score higher.
[0104] Specifically, the L2 norm is calculated for the semantic vector of each node, and each dimension value is divided by the norm to obtain a unit vector, which is then written into the vector embedding attribute of the corresponding node. At the same time, for incremental updates, the newly generated or changed vectors are normalized and written, and the existing vectors of the unchanged nodes are reused. This method can reduce the update overhead of large-scale repositories.
[0105] This embodiment achieves precise vectorization of code semantics through the above-described scheme, which involves structurally splicing node information, calling a high-precision embedding model, and normalizing vector storage. This provides a reliable semantic matching foundation for subsequent hybrid retrieval. At the same time, the combination of vectors and graph structures can simultaneously support semantic retrieval and relation traversal.
[0106] Based on the above implementation scheme, in one feasible implementation, the step of retrieving code semantic nodes of the target logical community subgraph based on a hybrid retrieval strategy to determine candidate code node subgraphs includes S51~S53: Step S51: Convert the user query request into a query vector, calculate the similarity between the query vector and the node semantic vectors of each code semantic node in the target logical community subgraph, and sort the results by similarity to obtain the semantic retrieval results.
[0107] It should be noted that the user query request is a natural language question input by the user (e.g., "How is the order amount calculated"); the query vector is a vector obtained from the user query input text-embedding-v4 model, with the same dimension as the semantic vectors of the nodes in the target logical community subgraph; the similarity here uses cosine similarity, calculated using the following formula:
[0108] in, For query vector; For node semantic vectors; This queries the similarity between the query vector and the semantic vector of a node. The semantic retrieval result is a list of code semantic nodes sorted from highest to lowest similarity.
[0109] Understandably, the purpose of this step is to uncover the potential logical connections between user queries and code nodes, resolving issues such as keyword retrieval failing to match synonyms or implicit calls. For example, a user query for "calculate money" can match the function `calculate_amount`, even if the two have no literal overlap, the semantic vector can still capture their logical similarity.
[0110] Specifically, in one embodiment of this application, standard semantic retrieval is employed. The user query is input into the text-embedding-v4 model to obtain a query vector. The semantic vectors of all nodes in the target logical community subgraph are traversed, cosine similarity is calculated, and the top K nodes are selected based on their scores. This method is applicable to most query scenarios and can capture potential semantic associations. In another embodiment of this application, community pruning semantic retrieval is employed. Possible related logical communities are first located based on the initial keywords of the user query. Similarity is calculated only within the corresponding communities, reducing the computational load on irrelevant nodes. This method can improve the retrieval efficiency of large-scale repositories. Optionally, the top N nodes of the semantic retrieval results are further sorted based on the structural features of the code nodes (such as node type and number of calls) to improve the ranking of core nodes. This method can enhance the practicality of the results.
[0111] Step S52: Segment the user query request into words, and match the word frequency in the text attributes of the code semantic nodes in the target logical community subgraph to obtain keyword retrieval results.
[0112] It should be noted that word segmentation breaks down a user query into independent terms (e.g., "how to calculate order amount" is broken down into "order," "amount," and "calculate"); term frequency is the number of times a term appears in the node's text attributes; the BM25 algorithm is a classic information retrieval algorithm, and its calculation formula is:
[0113] in, This refers to the keyword search results, i.e., the relevance score; It refers to a term in the query vector, that is, a word or symbol after word segmentation; Inverse document frequency (IVF) is a measure of term frequency. A measure of prevalence across the entire codebase; the rarer and more distinctive a word is, the higher its prevalence. The higher the value (e.g., for core function names); For terms Text in the code semantic node Frequency of occurrence in; The current text length of the code semantic node; This represents the average text length of the entire codebase. The first adjustment factor, typically between 1.2 and 2.0, controls word frequency. The influence of saturation degree; This is the second adjustment factor, typically between 0 and 1, often 0.75, which controls document length. The moderating effect on the score is shown; b=0 indicates that document length is not considered; a value closer to 1 indicates that the influence of length is fully considered. Keyword search results are a list of semantic code nodes sorted from highest to lowest by BM25 score.
[0114] Understandably, the purpose of this step is to accurately match keywords in the code and resolve the semantic drift problem that may occur in semantic retrieval. Identifiers such as function names and class names in the code have clear semantics, and the BM25 algorithm can assign high weights to these keywords to ensure that literal matching results are recalled first.
[0115] Specifically, in one embodiment of this application, standard BM25 retrieval is used to segment the user query, traverse the node text attributes of the target logical community subgraph, calculate the BM25 score of each node, and sort and select the top K. This method is applicable to most scenarios and can accurately match keywords. In another embodiment of this application, field weighting is used to set different weights for different types of text attributes (e.g., function names have higher weights than comments). A weight factor is introduced when calculating the BM25 score to improve the matching priority of core fields. This method can improve the accuracy of keyword matching. In yet another embodiment of this application, phrase matching is used to identify phrase structures in the query (e.g., "order amount") and prioritize matching nodes containing complete phrases. This method can improve the matching accuracy of multi-word combinations.
[0116] Step S53: Based on the ranking position of each code semantic node in the semantic retrieval results and the keyword retrieval results, calculate the fusion score using the inverse ranking fusion algorithm, and determine the candidate code node subgraph based on the fusion score.
[0117] It should be noted that the inverse ranking fusion algorithm is a result fusion method. It does not directly use the original score, but calculates the weight based on the node's ranking in different result lists. The calculation formula is as follows:
[0118] in, Refers to code semantic nodes The final recommendation score obtained after fusion is the one that determines the number of recommendations received; For code semantic nodes The ranking set in different search result lists; For code semantic nodes The specific ranking position in a particular search list; This is a smoothing constant, usually set to a small positive number, used to prevent issues arising when rankings are affected. When the fraction is placed very early in the alphabet, the denominator becomes too small, resulting in an excessively large fraction, while simultaneously ensuring the mathematical stability of the formula.
[0119] The fusion score is the final score of a node, which combines the weights of semantic retrieval and keyword retrieval; the candidate code node subgraph is a subgraph composed of the top-K nodes of the fusion score and their relation edges.
[0120] Understandably, the purpose of this step is to eliminate the quantitative bias of different search strategies and combine their advantages. If a node appears at the top of both types of results, its fusion score will be significantly improved, ensuring that nodes that match both keywords and are semantically relevant are selected first, thereby improving the accuracy of search results.
[0121] Specifically, the ranking of each node in semantic retrieval and keyword retrieval is collected, and the fusion score is calculated by substituting the ranking into the inverse ranking fusion algorithm formula. The top-K nodes are then sorted by score, and their relation edges are extracted to obtain candidate subgraphs. Optionally, the ranking weights of the two types of retrieval are adjusted according to the query type. For example, for queries with explicit keywords, the ranking weight of keyword retrieval is increased, and for queries with ambiguous semantics, the ranking weight of semantic retrieval is increased. This approach can further improve the adaptability of the fusion results.
[0122] This embodiment, through the above-described scheme, employs a hybrid strategy of "semantic retrieval + keyword retrieval + inverse ranking fusion," which balances the accuracy of literal matching with the completeness of semantic association, overcoming the shortcomings of a single retrieval method. It can output a set of highly relevant candidate codes, providing a reliable data foundation for subsequent reasoning.
[0123] Based on the above implementation scheme, in one feasible implementation, the step of performing enhanced reasoning on the candidate code node subgraph according to the target rule corresponding to the application query scenario to generate code understanding results includes S61~S63: Step S61: Identify the target scenario type corresponding to the application query scenario.
[0124] It should be noted that the application query scenario is a code understanding task initiated by the user, such as sorting out the system architecture, modifying the scope of influence of func_a, locating the cause of null pointer exception, and refactoring the user module; the target scenario type is the scenario's category tag, corresponding to four pre-configured rules: architecture understanding, impact analysis, defect tracking, and refactoring assistance.
[0125] Understandably, the purpose of this step is to clarify the user's task requirements and provide a basis for loading and matching rules subsequently. The reasoning logic and output requirements vary greatly across different scenarios; accurate scenario identification ensures that subsequent processing meets user expectations.
[0126] Specifically, in one embodiment of this application, keyword matching is used to classify scenarios by identifying characteristic keywords in the query (such as "impact" and "modify" corresponding to impact analysis, and "architecture" and "dependency" corresponding to architecture understanding). This method is simple and fast. In another embodiment of this application, model classification is used. The user query is input into a pre-trained intent classification model, which outputs the scenario type. This method can handle more flexible query expressions and improve classification accuracy. Simultaneously, manual assistance can be used. When the system confidence level is below a threshold, the user is prompted to confirm the scenario type to avoid misclassification. This method can improve the accuracy of identifying complex scenarios.
[0127] Step S62: Determine the target rule that matches the target scenario type from the pre-configured scenario-based rule base. The target rule includes at least one of architecture understanding rules, impact analysis rules, defect tracking rules, and refactoring assistance rules.
[0128] It should be noted that the scenario-based rule base is a pre-configured set of rules. Each rule contains the execution logic and output paradigm of the scenario: architecture understanding rules are used to parse module dependencies and call chains, and output the hierarchical structure and community division results; impact analysis rules are used to evaluate the impact of modifications and output the called and dependent units; defect tracking rules are used to locate the root cause of anomalies and output the functions and risk points associated with the error stack; refactoring assistance rules are used to support refactoring and output renaming and splitting suggestions; target rules are rules that match the target scenario type and guide the subsequent reasoning process.
[0129] Understandably, the purpose of this step is to provide customized inference constraints for different scenarios, preventing large models from creating illusions through unrestrained speculation. The rules clearly define the direction of graph traversal, the types of edges to focus on, and the output format, ensuring that the inference process is based on graph facts and that the results meet the scenario requirements.
[0130] Specifically, a single-rule matching implementation can be used, where a single rule is loaded based on the target scenario type, suitable for queries in a single scenario; or a multi-rule matching implementation can be used, where multiple corresponding rules are loaded when the query involves multiple scenarios (such as "reconstructing the order module and assessing the impact"), and inference is performed in stages. This approach can support the processing of complex requirements.
[0131] Step S63: Based on the target rule, perform traversal reasoning analysis on the association relationship of the candidate code node subgraph in the code knowledge graph to generate code understanding results.
[0132] It should be noted that traversal reasoning analysis follows the graph traversal logic specified by the target rules, expanding nodes along semantic relationship edges in the code knowledge graph to mine related information; the code understanding result is structured content that conforms to the rule output paradigm, such as a list of impact scopes, architecture dependency graphs, defect paths, etc.
[0133] Understandably, the purpose of this step is to combine the structured relationships of the graph with the constraints of rules to generate accurate and interpretable understanding results. Compared to generating results directly from a large model, reasoning based on graph traversal ensures that each step is based on facts, significantly reducing the probability of illusions, while the structured output is more user-friendly.
[0134] Specifically, starting with the candidate code node subgraph, nodes are expanded in the code knowledge graph according to the edge type and traversal order specified by the target rules. After collecting the results, they are output according to the rule paradigm. This method is suitable for most scenarios, with clear inference paths and reliable results. Optionally, extended traversals of related nodes can be added based on the rules (such as additional traversal of downstream dependencies of affected nodes in impact analysis) to enrich the output information, which can improve the completeness of the results. The nodes and edges obtained from the traversal can also be converted into visual charts (such as dependency graphs and call chain graphs) to improve the readability of the results. This method is suitable for scenarios that require intuitive display, such as architectural understanding.
[0135] This embodiment, through the above-described scheme and the process of scene recognition, rule matching, and graph traversal, realizes customized reasoning for different code understanding tasks. It uses rules to constrain the generation process of the large model, ensuring that the results are based on graph facts, thus significantly improving the accuracy and reliability of code understanding.
[0136] Based on the above implementation scheme, in one feasible implementation, the step of traversing the abstract syntax tree corresponding to the source code file, extracting the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and constructing the code knowledge graph includes S71~S73: Step S71: The source code file is parsed by a syntax parser to generate an abstract syntax tree.
[0137] It should be noted that the preferred parser is Tree-sitter, an incremental parsing tool that supports multiple languages and can generate accurate abstract syntax trees. An abstract syntax tree (AST) is a tree-like representation of source code, where each node corresponds to a grammatical unit (such as import statements, class definitions, function definitions, variable declarations, etc.), preserving the grammatical structure and hierarchical relationship of the code while removing information unrelated to syntax, such as spaces and comments.
[0138] Understandably, the purpose of this step is to transform unstructured source code into a structured syntax tree, providing a foundation for subsequent node and relation extraction. Tree-sitter supports multiple programming languages, accurately parses code with different syntaxes, generates a unified AST structure, and is compatible with code repositories developed using multiple languages.
[0139] Specifically, the corresponding Tree-sitter language parser is selected based on the file extension of the source code file. After reading the file content, the parsing function is called to generate the AST. When the file is modified, only the modified code is parsed, and the original AST is updated. This method can reduce the parsing overhead of frequently modified files and improve processing efficiency. For other language code embedded in the file (such as SQL statements in Python files), the corresponding parser is switched for nested parsing.
[0140] Step S72: Traverse the abstract syntax tree, identify the syntax unit nodes of the abstract syntax tree, and obtain the code semantic nodes.
[0141] It should be noted that syntactic unit nodes are node types in AST that have explicit semantics, such as ClassDef, FunctionDef, VariableDeclaration, and File; code semantic nodes are entity nodes extracted from AST and used to construct knowledge graphs. Each node carries meta-information of the corresponding syntactic unit (such as class name, function parameters, file path, etc.).
[0142] Understandably, the purpose of this step is to filter valuable semantic entities from the AST and avoid interference from redundant information. By identifying specific types of syntactic unit nodes, the core structural elements of the code can be extracted, providing data for constructing the node layer of the knowledge graph.
[0143] Specifically, in one embodiment of this application, a depth-first traversal implementation is used. This involves using a depth-first algorithm to traverse all nodes of the AST, identifying predefined semantic node types, and extracting attribute information to generate code semantic nodes. This method is applicable to most AST structures and can completely cover all semantic nodes. Simultaneously, specific types of nodes are filtered according to requirements (e.g., extracting only function and class nodes) to reduce the storage and processing overhead of irrelevant nodes. This method is suitable for scenarios focusing on specific structures. Furthermore, additional attributes such as decorators and access modifiers are collected during node extraction to enrich the node's meta-information, thereby enhancing the dimensionality of subsequent analysis.
[0144] Step S73: Identify the calling relationships, definition relationships, and dependency relationships between the syntax unit nodes in the abstract syntax tree, and generate corresponding semantic relationship edges.
[0145] It should be noted that the call relationship is the association between functions, corresponding to the CALLS edge; the definition relationship is the hierarchical association where a parent node contains a child node, corresponding to the DEFINES edge (such as a file containing a class, or a class containing a method); the dependency relationship is the import association between files, corresponding to the IMPORT edge; and the semantic relationship edge is a directed edge that connects semantic nodes in the code, used to describe the logical association between nodes.
[0146] Understandably, the purpose of this step is to uncover the logical connections between semantic nodes in the code and construct the edge layers of the knowledge graph. Simply extracting nodes cannot reveal the logical flow of the code. By identifying three core relationships, the call chain, hierarchical structure, and dependencies of the code can be fully modeled, providing support for subsequent global analysis.
[0147] Specifically, the method generates IMPORT edges by scanning import statements in the AST, DEFINES edges based on nested structures, and CALLS edges by identifying function call expressions. This approach is applicable to most programming languages and can cover core relationships. For dynamic languages, implicit relationships are derived (such as multiple dispatch relationships in Julia and decorator call relationships in Python), adapting to the complex syntax of dynamic languages. Weights are assigned based on the call frequency and density of relationships, providing a weighted basis for subsequent community segmentation and retrieval, thus improving the accuracy of the analysis.
[0148] For example, a specific method for extracting nodes and relation edges from the Julia language AST achieves complete modeling of Julia code into a knowledge graph through processing mechanisms such as traversal, concatenation, pattern matching, semantic inference, hierarchical reconstruction, and scope tracking.
[0149] First, a depth-first search is used to traverse the Julia AST. When the head attribute of the Expr node is detected to be :module, :struct, :function, or :macro, its name is extracted, a globally unique UUID is generated, and the path string of the current node is constructed. Then, it is pushed onto the scope stack.
[0150] Using the current scope stack state, calculate the fully qualified name (FQN) of the current node using a recursive formula:
[0151] in, For the current AST node, For the current scope stack, The base name of the node. Returns the fully qualified name of the top element of the stack. This represents a string concatenation operation. Used as a path separator, such as . or ::.
[0152] When the iterator completes its visit to all child nodes of a node in a given scope, a pop operation is performed. For Julia's unique include statement, the system pauses current file traversal upon encountering the node, loads the target file's AST, and enters the new file for parsing while preserving the current scope stack, thus achieving cross-file hierarchical reconstruction.
[0153] For expression nodes of type :. (dot), the system starts from the right leaf node, identifies the last identifier, and then recursively visits its left child nodes. During the concatenation process, the system actively checks whether the current identifier contains a relative path. If it is a relative path or an isolated identifier, the system automatically extracts the top element of the scope stack as the base prefix for string concatenation. If the node is identified as belonging to the macrocall category, the `@` symbol is automatically added to the prefix of the restored identifier. For compound nodes with curly braces, such as Array{Int64,1}, the system parses it into a structure of base name plus parameter list, ensuring that Array as the core identifier is correctly restored, while generic parameters are stored as associated properties.
[0154] Three-dimensional features are extracted from the abstract syntax tree nodes: syntax header type, assignment lvalue structure, and whether they possess anonymous function identifiers. Standard function definitions, assignment-based short function definitions, and anonymous function definitions are uniformly identified as abstract function entities. Simultaneously, the field information and parent class association information corresponding to the structure definition and abstract type definition are extracted and filled into a standardized type metadata template. After matching, the entities are stripped of their original syntactic differences and uniformly stored as structured objects containing specification names, entity categories, and feature signatures.
[0155] For the Julia-specific implementation, implicit relationships and multiple dispatch modeling are derived through semantic rules: First, basic hierarchical relationships are derived. If entity A (e.g., Field) is physically located in a subtree of entity B (e.g., Struct) in the AST, and the scope stack records show that B is the direct parent of A, then the edge (B)-[CONTAINS]->(A) is established. Second, for Julia's unique multiple dispatch mechanism, the system defines a triple describing the dispatch logic: ,in Represents the fully qualified name of a generic function. The method signature (a list of parameter types that the method is bound to). This indicates a node that implements a specific method.
[0156] During the AST traversal, when the system identifies a MethodDefinition node, it parses the parameter list of the method definition, extracts the type annotation for each parameter, and marks it as Any if the parameter has no explicit type annotation. The extracted type annotation is then matched with the fully qualified name of existing Struct or DataType nodes in the graph. If a match is successful, the system creates a directed edge in the graph from the generic function node F to the concrete method node M, and marks the "applicable type" of this edge as... For any generic function node in the graph and method nodes If multiple dispatch relationships exist, then the following logic is satisfied:
[0157] This means that in subsequent Graph RAG (Graph-based Retrieval-Augmented Generation) retrieval, it is possible to directly locate the method implementation that satisfies specific type constraints through graph traversal.
[0158] For better understanding, please refer to Figure 2 , Figure 2 This diagram illustrates the module framework for parsing the Julia Abstract Syntax Tree (AST). First, the source code is parsed by an AST parser, transforming it into a machine-traversable AST structure. Then, the parsing process enters the core Julia semantic parsing system module. This module integrates four closely cooperating core processing units, ensuring context accuracy through a bidirectional interaction mechanism: First is the scope stack, which maintains the hierarchical structure of the current parsing process. Its state is updated and fed back to the external stack memory to ensure scope consistency across files or deep nesting. Next is the identifier concatenation unit, which reads the current prefix information from the stack memory as a baseline when restoring fragmented identifiers. Following this is the pattern matching stage, which compares the current node features with the syntax pattern library to identify Julia-specific grammatical structures. Finally, the relation derivation unit applies a set of semantic rules to mine implicit semantic relationships. These four units execute sequentially from top to bottom within the system, collectively realizing the transformation from source code to structured knowledge, ultimately outputting a completed code knowledge graph.
[0159] This embodiment, through the above-described scheme and the process of AST parsing, semantic node extraction, and semantic relationship recognition, realizes the transformation from unstructured source code to a structured code knowledge graph, fully preserving the code's structure, hierarchy, and logical connections, and providing comprehensive basic data for subsequent community division, retrieval, and reasoning.
[0160] For example, to help understand the implementation process of the intelligent understanding method for the code repository obtained by combining this embodiment with the above embodiment one, please refer to... Figure 3 , Figure 3 A simplified flowchart illustrating an intelligent understanding method for code repositories is provided, specifically: The process begins with Step 1: Source Code Parsing and AST Generation. Based on the file type in the code repository, a corresponding parser is selected (e.g., a specific AST parser is used for Julia code). Lexical and syntactic analysis is performed on the source code to generate a file-level Abstract Syntax Tree (AST), completing the initial transformation from unstructured text to a structured syntax tree. The process then moves to Step 2: Static Program Analysis and Initial Graph Construction. Static analysis is conducted based on the AST, performing file-level modeling, extracting atomic entities such as classes, functions, and variables, and establishing basic semantic relationships such as definition-reference and import dependencies. This outputs an initial code knowledge graph containing basic nodes and edges.
[0161] Next, we proceed to step 3: Community Building and Subgraph Optimization. To overcome the limitations of the physical directory, community discovery algorithms such as Louvain are used to logically divide the initial graph into communities. During this process, large communities are recursively decomposed and denoised by calculating metrics such as modularity, and the modularity is evaluated to optimize the structure, ultimately outputting an initial logical community subgraph with moderate granularity and high logical aggregation. The process then moves to step 4: Node Vectorization. Textual features (such as name, document, signature, etc.) of each code semantic node are extracted, and a pre-trained model (such as text-embedding-v4) is called to generate semantic vectors. After L2 regularization, the vector attributes are stored back into the corresponding nodes, resulting in a target logical community subgraph that contains both topological structure and rich semantic features.
[0162] The process then proceeds to step 5: BM25+ Semantic Hybrid Retrieval. Upon receiving the user's query request, a dual-path parallel retrieval mechanism is employed: one path uses the BM25 algorithm for precise keyword matching, while the other uses cosine similarity calculation for semantic association matching. Subsequently, the RRF algorithm is used to fuse and reorder the results from both paths, and combined with community pruning strategies, highly relevant code nodes are efficiently selected within the relevant logical community to determine the candidate code node subgraph. Finally, step 6: Contextualized Reasoning and Output. Based on the user's query intent (such as architecture analysis, impact analysis, defect localization, or refactoring suggestions), corresponding target reasoning rules are loaded. Enhanced reasoning is performed on the candidate subgraph based on the structural relationships of the knowledge graph, ultimately outputting high-quality code understanding results that meet business requirements.
[0163] It should be noted that the above examples are only for understanding this application and do not constitute a limitation on the intelligent understanding method of the code repository of this application. Any simple transformations based on this technical concept are within the protection scope of this application.
[0164] This application also provides an intelligent understanding device for code repositories; please refer to [reference needed]. Figure 4 The intelligent understanding device for the code repository includes: The graph construction module 401 is used to traverse the abstract syntax tree corresponding to the source code file, extract the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and construct a code knowledge graph. The initial community module 402 is used to perform logical community division on the code knowledge graph based on the code semantic nodes through a community discovery algorithm to obtain several initial logical community subgraphs; The target community module 403 is used to perform vectorization processing on the code semantic nodes in the initial logical community subgraph, generate node semantic vectors and store them in the corresponding code semantic nodes to obtain the target logical community subgraph. The hybrid retrieval module 404 is used to retrieve the code semantic nodes of the target logical community subgraph based on a hybrid retrieval strategy, and determine the candidate code node subgraph. The enhanced reasoning module 405 is used to perform enhanced reasoning on the candidate code node subgraph according to the target rules corresponding to the application query scenario, and generate code understanding results.
[0165] The intelligent code repository understanding device provided in this application, employing the intelligent code repository understanding method in the above embodiments, can solve the technical problem of fragmented understanding of the overall structure of the code repository. Compared with the prior art, the beneficial effects of the intelligent code repository understanding device provided in this application are the same as those of the intelligent code repository understanding method provided in the above embodiments, and other technical features in the intelligent code repository understanding device are the same as those disclosed in the methods of the above embodiments, and will not be repeated here.
[0166] This application provides an intelligent understanding device for a code repository, comprising: at least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores instructions executable by the at least one processor, the instructions being executed by the at least one processor to enable the at least one processor to execute the intelligent understanding method for the code repository in Embodiment 1 above.
[0167] The following is for reference. Figure 5This document illustrates a structural schematic diagram of an intelligent understanding device suitable for implementing the embodiments of this application regarding a code repository. The intelligent understanding device for the code repository in the embodiments of this application may include, but is not limited to, mobile terminals such as mobile phones, laptops, digital broadcast receivers, PDAs (Personal Digital Assistants), PADs (Portable Application Description), PMPs (Portable Media Players), in-vehicle terminals (e.g., in-vehicle navigation terminals), and fixed terminals such as digital TVs and desktop computers. Figure 5 The intelligent understanding device of the code repository shown is merely an example and should not impose any limitations on the functionality and scope of use of the embodiments of this application.
[0168] like Figure 5 As shown, the intelligent understanding device for the code repository may include a processing unit 1001 (e.g., a central processing unit, a graphics processing unit, etc.), which can perform various appropriate actions and processes according to a program stored in the read-only memory 1002 or a program loaded from the storage device 1003 into the random access memory 1004. The random access memory 1004 also stores various programs and data required for the operation of the intelligent understanding device for the code repository. The processing unit 1001, the read-only memory 1002, and the random access memory 1004 are interconnected via a bus 1005. An input / output interface 1006 is also connected to the bus. Typically, the following systems can be connected to the input / output interface 1006: input devices 1007 including, for example, a touchscreen, touchpad, keyboard, mouse, image sensor, microphone, accelerometer, gyroscope, etc.; output devices 1008 including, for example, a liquid crystal display (LCD), speaker, vibrator, etc.; storage devices 1003 including, for example, magnetic tape, hard disk, etc.; and communication devices 1009. Communication device 1009 allows the intelligent understanding device of the code repository to communicate wirelessly or wiredly with other devices to exchange data. While the figure shows intelligent understanding devices for code repositories with various systems, it should be understood that implementing or having all of the systems shown is not required. More or fewer systems may be implemented alternatively.
[0169] Specifically, according to the embodiments disclosed in this application, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments disclosed in this application include a computer program product comprising a computer program carried on a computer-readable medium, the computer program containing program code for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via a communication device, or installed from storage device 1003, or installed from read-only memory 1002. When the computer program is executed by processing device 1001, it performs the functions defined in the methods of the embodiments disclosed in this application.
[0170] The intelligent code repository understanding device provided in this application, employing the intelligent code repository understanding method in the above embodiments, can solve the technical problem of fragmented understanding of the overall structure of the code repository. Compared with the prior art, the beneficial effects of the intelligent code repository understanding device provided in this application are the same as those of the intelligent code repository understanding method provided in the above embodiments, and other technical features in this intelligent code repository understanding device are the same as those disclosed in the previous embodiment method, and will not be repeated here.
[0171] It should be understood that the various parts disclosed in this application can be implemented using hardware, software, firmware, or a combination thereof. In the description of the above embodiments, specific features, structures, materials, or characteristics can be combined in any suitable manner in one or more embodiments or examples.
[0172] The above description is merely a specific embodiment of this application, but the scope of protection of this application is not limited thereto. Any variations or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in this application should be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.
[0173] This application provides a computer-readable storage medium having computer-readable program instructions (i.e., a computer program) stored thereon, which are used to execute the intelligent understanding method of the code repository in the above embodiments.
[0174] The computer-readable storage medium provided in this application may be, for example, a USB flash drive, but is not limited to, electrical, magnetic, optical, electromagnetic, infrared, or semiconductor systems or devices, or any combination thereof. More specific examples of computer-readable storage media may include, but are not limited to: electrical connections having one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fiber, portable compact disk read-only memory (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination thereof. In this embodiment, the computer-readable storage medium may be any tangible medium containing or storing a program that can be used by or in conjunction with an instruction execution system or device. The program code contained on the computer-readable storage medium may be transmitted using any suitable medium, including but not limited to: wires, optical cables, RF (Radio Frequency), etc., or any suitable combination thereof.
[0175] The aforementioned computer-readable storage medium may be included in the intelligent understanding device of the code repository; or it may exist independently and not be assembled into the intelligent understanding device of the code repository.
[0176] The aforementioned computer-readable storage medium carries one or more programs. When these programs are executed by an intelligent understanding device of the code repository, the intelligent understanding device of the code repository performs the following actions: traverses the abstract syntax tree corresponding to the source code file, extracts the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and constructs a code knowledge graph; uses a community detection algorithm to logically divide the code knowledge graph based on the code semantic nodes to obtain several initial logical community subgraphs; vectorizes the code semantic nodes in the initial logical community subgraphs to generate node semantic vectors and stores them in the corresponding code semantic nodes to obtain target logical community subgraphs; retrieves the code semantic nodes in the target logical community subgraphs based on a hybrid retrieval strategy to determine candidate code node subgraphs; and performs enhanced reasoning on the candidate code node subgraphs according to the target rules corresponding to the application query scenario to generate code understanding results.
[0177] Computer program code for performing the operations of this application can be written in one or more programming languages or a combination thereof, including object-oriented programming languages such as Java, Smalltalk, and C++, and conventional procedural programming languages such as the "C" language or similar programming languages. The program code can be executed entirely on the user's computer, partially on the user's computer, as a standalone software package, partially on the user's computer and partially on a remote computer, or entirely on a remote computer or server. In cases involving remote computers, the remote computer can be connected to the user's computer via any type of network—including a Local Area Network (LAN) or a Wide Area Network (WAN)—or can be connected to an external computer (e.g., via the Internet using an Internet service provider).
[0178] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of this application. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of code containing one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions indicated in the blocks may occur in a different order than those indicated in the drawings. For example, two consecutively indicated blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in the block diagrams and / or flowcharts, and combinations of blocks in the block diagrams and / or flowcharts, can be implemented using a dedicated hardware-based system that performs the specified function or operation, or using a combination of dedicated hardware and computer instructions.
[0179] The modules described in the embodiments of this application can be implemented in software or hardware. The names of the modules do not necessarily limit the functionality of the unit itself.
[0180] The readable storage medium provided in this application is a computer-readable storage medium that stores computer-readable program instructions (i.e., a computer program) for executing the intelligent understanding method of the code repository described above, which can solve the technical problem of fragmented understanding of the overall structure of the code repository. Compared with the prior art, the beneficial effects of the computer-readable storage medium provided in this application are the same as the beneficial effects of the intelligent understanding method of the code repository provided in the above embodiments, and will not be repeated here.
[0181] This application also provides a computer program product, including a computer program that, when executed by a processor, implements the steps of the intelligent understanding method for the code repository as described above.
[0182] The computer program product provided in this application can solve the technical problem of fragmented understanding of the overall structure of code repositories. Compared with the prior art, the beneficial effects of the computer program product provided in this application are the same as those of the intelligent understanding method for code repositories provided in the above embodiments, and will not be repeated here.
[0183] The above description is only a part of the embodiments of this application and does not limit the patent scope of this application. All equivalent structural transformations made under the technical concept of this application and using the contents of the specification and drawings of this application, or direct / indirect applications in other related technical fields, are included in the patent protection scope of this application.
Claims
1. A method for intelligently understanding code repositories, characterized in that, The intelligent understanding method for the code repository includes: Traverse the abstract syntax tree corresponding to the source code file, extract the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and construct a code knowledge graph; The code knowledge graph is logically divided into several initial logical community subgraphs based on the code semantic nodes using a community discovery algorithm. The code semantic nodes in the initial logical community subgraph are vectorized to generate node semantic vectors, which are then stored in the corresponding code semantic nodes to obtain the target logical community subgraph. The code semantic nodes of the target logical community subgraph are retrieved based on a hybrid retrieval strategy to determine candidate code node subgraphs; Enhanced reasoning is performed on the candidate code node subgraph based on the target rules corresponding to the application query scenario to generate code understanding results.
2. The intelligent understanding method for code repositories as described in claim 1, characterized in that, The step of dividing the code knowledge graph into logical communities based on the code semantic nodes using a community detection algorithm to obtain several initial logical community subgraphs includes: The code semantic node is initialized as an initial community, and the initial community of the code semantic node is iteratively merged into the neighboring communities through a community discovery algorithm to obtain an intermediate community; Determine the size of the community nodes in the intermediate community, and determine whether the size of the community nodes exceeds a preset size threshold; If the size of the community node is smaller than the size threshold, then the subgraph corresponding to the intermediate community is used as the initial logical community subgraph. If the size of the community nodes is greater than the size threshold, the intermediate community is divided into local communities, and the subgraph corresponding to the local community is used as the initial logical community subgraph.
3. The intelligent understanding method for code repositories as described in claim 2, characterized in that, The step of further dividing the intermediate community into local communities includes: Extract the semantic nodes and semantic relationship edges from the intermediate community to construct a local subgraph; Determine whether there are connected edges inside the local subgraph; If there are connecting edges within the local subgraph, the local subgraph is further divided according to the principle of optimal internal modularity to obtain the local community; If there are no connecting edges within the local subgraph, then the code semantic nodes in the local subgraph are taken as the local community.
4. The intelligent understanding method for code repositories as described in claim 1, characterized in that, The step of vectorizing the code semantic nodes in the initial logical community subgraph to generate node semantic vectors and storing them in the corresponding code semantic nodes to obtain the target logical community subgraph includes: In the initial logical community subgraph, the name, docstring, and function signature of the code semantic node are extracted and concatenated into node text; The pre-trained text embedding model is invoked to vectorize the node text, generating node semantic vectors; The semantic vectors of the nodes are normalized, and the normalized vectors are written into the corresponding code semantic nodes to obtain the target logical community subgraph.
5. The intelligent understanding method for code repositories as described in claim 1, characterized in that, The step of retrieving code semantic nodes of the target logical community subgraph based on a hybrid retrieval strategy to determine candidate code node subgraphs includes: The user query request is converted into a query vector, and the similarity between the query vector and the node semantic vector of each code semantic node in the target logical community subgraph is calculated. The semantic retrieval results are obtained by sorting them by similarity. The user query request is segmented into words, and the keyword retrieval results are obtained by matching the text attributes of the code semantic nodes in the target logical community subgraph based on the word frequency. Based on the ranking position of each code semantic node in the semantic retrieval results and the keyword retrieval results, a fusion score is calculated using a reciprocal ranking fusion algorithm, and candidate code node subgraphs are determined based on the fusion score.
6. The intelligent understanding method for code repositories as described in claim 1, characterized in that, The step of performing enhanced reasoning on the candidate code node subgraph based on the target rules corresponding to the application query scenario to generate code understanding results includes: Identify the target scenario type corresponding to the application query scenario; The target rules that match the target scenario type are determined from a pre-configured scenario-based rule base. The target rules include at least one of architecture understanding rules, impact analysis rules, defect tracking rules, and refactoring assistance rules. Based on the target rules, the relationships between the candidate code node subgraphs in the code knowledge graph are traversed and analyzed to generate code understanding results.
7. The intelligent understanding method for code repositories as described in claim 1, characterized in that, The steps of traversing the abstract syntax tree corresponding to the source code file, extracting the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and constructing the code knowledge graph include: An abstract syntax tree is generated by parsing the source code file using a syntax parser. Traverse the abstract syntax tree, identify the syntax unit nodes of the abstract syntax tree, and obtain the code semantic nodes; In the abstract syntax tree, the calling relationships, definition relationships, and dependency relationships between the syntax unit nodes are identified, and corresponding semantic relationship edges are generated.
8. An intelligent understanding device for a code repository, characterized in that, The intelligent understanding device for the code repository includes: The graph construction module is used to traverse the abstract syntax tree corresponding to the source code file, extract the code semantic nodes of the abstract syntax tree and the semantic relationship edges between the code semantic nodes, and construct a code knowledge graph. The initial community module is used to divide the code knowledge graph into logical communities based on the code semantic nodes using a community discovery algorithm, resulting in several initial logical community subgraphs. The target community module is used to vectorize the code semantic nodes in the initial logical community subgraph, generate node semantic vectors and store them in the corresponding code semantic nodes to obtain the target logical community subgraph. The hybrid retrieval module is used to retrieve code semantic nodes of the target logical community subgraph based on a hybrid retrieval strategy, and determine candidate code node subgraphs; The enhanced reasoning module is used to perform enhanced reasoning on the candidate code node subgraph based on the target rules corresponding to the application query scenario, and generate code understanding results.
9. An intelligent understanding device for code repositories, characterized in that, The device includes: a memory, a processor, and a computer program stored in the memory and executable on the processor, the computer program being configured to implement the steps of the intelligent understanding method for the code repository as described in any one of claims 1 to 7.
10. A storage medium, characterized in that, The storage medium is a computer-readable storage medium, and a computer program is stored on the storage medium. When the computer program is executed by a processor, it implements the steps of the intelligent understanding method of the code repository as described in any one of claims 1 to 7.