Code knowledge graph incremental generation and interaction method
Patent Information
- Application Number
- CN202611157713.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-31
- Publication Date
- 2026-10-23
AI Technical Summary
该方式能够补充语义信息,但模型可能对文件路径、函数、类或依赖关系作出缺乏源码依据的推断;项目规模超过上下文容量后,如仅按目录或固定数量分批,紧密依赖的文件可能位于不同批次,跨批关系难以识别
[0046]本发明实现代码知识图谱的高效生成与可靠应用。将可由解析器确定的语法事实与模型生成的语义信息进行分层处理,使路径、函数、类和导入等基础事实具有可验证来源,从而限制模型对确定性结构的自由推断,确保基础事实的准确性和可靠性。基于依赖社区形成全图批次并提供受控载荷外一跳邻居上下文,在限制单次输入规模的同时保留当前分析载荷边界处的依赖线索,既保证处理效率,又确保依赖关系的完整性。通过确定性标识改写、去重、端点校验和内部导入边恢复等机制,提高完整构建和版本差异路径的图谱结构完整性以及不同运行结果之间的可比较性,确保图谱数据的一致性和可追溯性。通过版本差异增量路径或结构指纹分级路径减少不必要的重分析;在优选整合实施例中,结构指纹进一步限定依赖社区增量分批的待分析范围,并在局部更新中保留未变化图谱部分,从而显著提升更新效率。通过架构分层、模糊检索、节点下钻、广度优先路径查询和差异覆盖等功能,使图谱能够有效用于代码理解和变更影响查看,为用户提供丰富的代码分析能力。将展示交互与分析更新进行解耦,普通界面操作不会改变图谱或模型状态,有利于保持分析结果的可复现性,确保分析结果的稳定性和可靠性。
Smart Images

Figure CN122964256A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of knowledge graph technology, and more specifically, to a method for incremental generation and interaction of code knowledge graphs. Background Technology
[0002] Existing technologies employ deterministic static analysis methods such as abstract syntax trees, lexical rules, or regular expressions. While these methods can obtain syntactic structures like functions, classes, imports, and exports, they struggle to capture semantic information such as component purpose, business meaning, data flow, and architectural layering. Conversely, directly analyzing the entire code repository using large language models is limited by context length, output uncertainty, and repetitive input. Mechanically batching by directory or fixed number of files can lead to the fragmentation of files within the same dependency community. In incremental analysis, files not included in the current batch may still depend on changed files; without providing one-hop neighbor information beyond the current analysis load, necessary boundary context can be lost. Generating nodes and edges separately for different analysis batches can result in inconsistent node identifiers, duplicate generation of the same entity, non-standard relationship directions or types, missing edge endpoints, and a lack of deterministic import relationships, making it difficult to directly form a persistent and queryable global graph. When minor modifications are made to a code repository, existing methods typically involve reanalyzing all files. This fails to differentiate between cases where content remains unchanged, cases where the predetermined structural signature dimension remains unchanged, and cases where structural changes occur, such as changes to function signatures, class structures, import / export relationships, etc., leading to unnecessary model calls and redundant calculations. Furthermore, when the graph is large, a single planar graph is insufficient for users to locate nodes, trace dependency paths, view architectural layers, and identify the scope of changes. A local read-only interactive query method adapted to the generated results is needed.
[0003] Existing technologies are mainly divided into five categories. The first category is static structure extraction, which uses syntax trees, lexical analysis, or regular expression matching to extract functions, classes, modules, import and call relationships. The output is relatively deterministic, but it usually only obtains explicit syntactic facts and is difficult to generate semantic information such as component function summaries, domain concepts, behavioral relationships, data relationships, architectural layers, and learning paths. The handling of non-program files such as configuration files, interface definitions, deployment files, and documentation is also inconsistent. The second category is direct model analysis, which inputs project files into an artificial intelligence model all at once or in batches, and the model generates a graph. This method can supplement semantic information, but the model may make inferences about file paths, functions, classes, or dependencies without source code basis. When the project size exceeds the context capacity, if it is only divided into batches by directory or fixed number, closely dependent files may be located in different batches, making it difficult to identify cross-batch relationships. The third type is the batch result direct concatenation method, where different batches independently generate node identifiers, node types, relationship directions, and descriptions. This is prone to node duplication, identifier conflicts, dangling edges, duplicate relationships, and omissions of deterministic dependency edges. If not standardized and validated before persistence, it will affect graph retrieval, path querying, and change analysis. The fourth type is the full reconstruction method, which rebuilds the entire graph after code version changes. It does not utilize the structural characteristics of code changes, cannot skip files whose content has not changed or only have non-structural changes, and has a large amount of data repeatedly read and submitted to the model. The fifth type is the simple visualization method, which only displays nodes and connections. It does not unify the architecture layering, node details, adjacency relationships, dependency paths, navigation steps, and version differences into the same graph data model. If ordinary interface behaviors such as clicking and filtering are used as analysis feedback, it will also increase the uncertainty of the system status. Summary of the Invention
[0004] To address the shortcomings of existing technologies, the present invention aims to provide a method for incremental generation and interaction of code knowledge graphs.
[0005] To achieve the above objectives, the present invention provides the following technical solution:
[0006] A method for incremental generation and interaction of code knowledge graphs, comprising the following steps:
[0007] Obtain the target project, and scan, filter, and categorize it to obtain a unified file list and project metadata.
[0008] Based on the unified file list pre-parsing of the project's internal import mapping, a file dependency graph is constructed with program code files as vertices and internal import relationships as edges. Based on the file dependency graph, dependency community partitioning is performed to obtain the full graph batch. Based on the full graph batch and the file dependency graph, the current analysis load and its one-hop neighbor context outside the load are generated.
[0009] Deterministic structure extraction is performed based on the current analysis load and project metadata to obtain structural facts; semantic graph fragments are generated based on the structural facts, the project internal imported data corresponding to the current analysis load, and the one-hop neighbor context outside the load.
[0010] The semantic graph fragments are merged and normalized, and a knowledge graph is generated based on the deterministic import edges of the import mapping within the project.
[0011] A structural fingerprint is generated based on a unified file list and structural facts. File changes are classified according to the structural fingerprint to obtain classification results. Hierarchical incremental updates are then performed based on the classification results.
[0012] Load the knowledge graph, respond to interactive query requests, and return query results based on the knowledge graph.
[0013] Preferably, a full graph batch is obtained by performing dependency community partitioning based on the file dependency graph, and the current analysis load and its one-hop neighbor context outside the load are generated based on the full graph batch and the file dependency graph, specifically including:
[0014] A community detection algorithm is used to group mutually dependent or co-dependent files in the file dependency graph into the same community, and a full graph batch is assigned to each community.
[0015] Communities exceeding the preset batch limit are split according to the stable path order of the file dependency graph, isolated or small communities below the preset minimum batch are merged, and non-code groups with clear semantic boundaries are retained.
[0016] Based on the full graph batch and file dependency graph, the import target and reverse import source of the file in the current analysis load are extracted. After excluding the file in the current analysis load, the file is stably truncated in descending order of the total degree of the neighbors in the file dependency graph and ascending order of the normalized path to obtain a set of neighbor items. Each neighbor item in the set of neighbor items contains a file path, a full graph batch identifier and an export symbol.
[0017] Preferably, a structural fact is obtained by deterministic structural extraction based on the current analysis load and project metadata. A semantic graph fragment is then generated based on the structural fact, the project's internal imported data corresponding to the current analysis load, and the load's external one-hop neighbor context. Specifically, this includes:
[0018] Select the corresponding parsing plugin based on the programming language or file extension of the files in the current analysis payload. Extract functions, classes, methods, attributes, parameters, return types, imports, exports, and call candidates from program code files. Extract chapters, definitions, fields, services, endpoints, or resources from non-code files to obtain structural facts.
[0019] Generate a graph fragment containing nodes and edges based on project metadata, full graph batches, file information of the current analysis load, structural facts, imported data from within the project, one-hop neighbor context outside the load, and preset output constraints.
[0020] Preferably, the semantic graph fragments are merged and normalized, and a knowledge graph is generated based on the deterministic import edges of the import mapping within the project, specifically including:
[0021] A mapping from original node identifiers to canonical identifiers is established based on semantic graph fragments, and the endpoint identifiers of edges are rewritten based on the mapping.
[0022] Based on preset rules, the complexity of nodes in semantic graph fragments is normalized to a preset level, and the edge directions are normalized to a preset set of directions.
[0023] Deduplicat nodes of semantic graph fragments according to the standard identifier, and deduplicat edges of semantic graph fragments according to the key composed of source node, target node, relation type and standard direction;
[0024] Remove any dangling edges in the semantic graph fragment whose endpoints do not exist in the merged node set;
[0025] The pre-parsed project internal import mapping is compared with the merged edge set. When both file nodes exist and there are no import edges in the same direction, deterministic import edges based on the project internal import mapping are added to generate a knowledge graph.
[0026] Preferably, a structural fingerprint is generated based on a unified file list and structural facts, and file changes are classified according to the structural fingerprint to obtain a classification result, specifically including:
[0027] The structural fingerprint is constructed by extracting the file content hash value, function feature set, class feature set, import set, and export set from the structural facts.
[0028] Compare the structural fingerprints of the changed files before and after the changes;
[0029] If the content hash values are the same, it is determined that there is no change; if the content hash values are different but the function characteristics, class characteristics, import set, and export set are all unchanged, it is determined that there is a surface change; if the function characteristics, class characteristics, import set, or export set changes, it is determined that there is a structural change.
[0030] Preferably, hierarchical incremental updates are performed based on the classification results, specifically including:
[0031] When the decision is to skip the update, only update the project metadata and terminate the process;
[0032] When the decision is a partial update or an architecture update, the nodes and associated edges corresponding to the changed files in the existing knowledge graph are pruned based on the decision. The files to be reanalyzed are re-batched according to their dependency communities based on the file dependency graph. After generating new semantic graph fragments, they are merged with the pruned graph. When the decision is an architecture update, the architecture layer and navigation steps are regenerated.
[0033] When the decision is a full update, prompt the user to execute a full build process based on a unified file manifest and terminate automatic updates.
[0034] Preferably, it further includes:
[0035] Based on the knowledge graph, the required fields, duplicate identifiers, and edge endpoint validity of nodes, edges, architectural layers, and navigation steps are verified.
[0036] If the verification passes, persist the knowledge graph, project metadata, and structural fingerprint; if the verification fails, save a portion of the graph and record a warning.
[0037] Preferably, loading a knowledge graph specifically includes:
[0038] Load the persistent knowledge graph and perform full schema validation based on the knowledge graph, including type alias normalization, default value correction, invalid node / edge deletion, and reference integrity check;
[0039] Based on the knowledge graph, it supports fuzzy search based on node name, tag, summary and language description. It supports querying the adjacency relationship of selected nodes and the dependency path based on breadth-first search. It supports displaying related nodes in the order of the navigation steps. It supports mapping version change files and displaying the affected nodes and related edges.
[0040] Preferably, it further includes:
[0041] When the community detection algorithm malfunctions, the standardized path sorting results based on the unified file list are deterministically downgraded and grouped by a fixed number of preset parameters.
[0042] When a single file resolution fails, the file-level neighbor context of the file is preserved based on the file dependency graph, a warning is logged, and the file is added to the skip list.
[0043] If a batch semantic analysis task fails, it will be retried once. If the retry still fails, the batch will be included in the failure report and empty outputs will not be considered valid graph fragments.
[0044] Dangling edges are removed during the merge normalization process, and imported edges are only restored if both file nodes exist based on the import mapping within the project.
[0045] Compared with the prior art, the present invention has the following beneficial effects:
[0046] This invention achieves efficient generation and reliable application of code knowledge graphs. It hierarchically processes syntactic facts determined by the parser and semantic information generated by the model, ensuring that fundamental facts such as paths, functions, classes, and imports have verifiable sources. This restricts the model's free inference of deterministic structures, ensuring the accuracy and reliability of fundamental facts. Based on dependency communities, it forms full-graph batches and provides one-hop neighbor contexts outside the controlled payload. While limiting the size of a single input, it retains dependency clues at the boundaries of the current analysis payload, ensuring both processing efficiency and the integrity of dependencies. Through mechanisms such as deterministic identifier rewriting, deduplication, endpoint verification, and internal import edge recovery, it improves the structural integrity of the graph of complete construction and version difference paths, as well as the comparability between different running results, ensuring the consistency and traceability of graph data. It reduces unnecessary re-analysis through version difference incremental paths or structural fingerprint hierarchical paths. In the preferred integration embodiment, structural fingerprints further limit the analysis scope of incremental batches of dependency communities and retain unchanged graph parts in local updates, thereby significantly improving update efficiency. Through features such as architecture layering, fuzzy search, node drill-down, breadth-first path query, and difference coverage, the graph can be effectively used for code understanding and viewing the impact of changes, providing users with rich code analysis capabilities. The display interaction is decoupled from analysis updates; ordinary interface operations do not change the graph or model state, which helps maintain the reproducibility of analysis results and ensures the stability and reliability of the analysis results. Attached Figure Description
[0047] Figure 1 This is a schematic diagram of the overall architecture of the incremental generation and interaction system for code knowledge graphs according to an embodiment of the present invention;
[0048] Figure 2 This is a flowchart illustrating the subsequent update and return process of the mapping and structural fingerprint path in an embodiment of the present invention.
[0049] Figure 3 This is a schematic diagram illustrating the collaborative processing of deterministic structure parsing and semantic analysis in an embodiment of the present invention;
[0050] Figure 4 This is a schematic diagram illustrating the construction of a community-based batching and payload-outside-one-hop neighbor context in an embodiment of the present invention.
[0051] Figure 5 This is a schematic diagram illustrating the multi-source map merging, normalization, and deterministic relationship recovery used in the complete construction and version difference path A of this invention embodiment;
[0052] Figure 6 This is a schematic diagram of the structural fingerprint decision-making and optimization integration sub-process of an embodiment of the present invention. Detailed Implementation
[0053] To make the above-mentioned objects, features and advantages of the present invention more apparent and understandable, the specific embodiments of the present invention will be described in detail below with reference to the accompanying drawings.
[0054] Many specific details are set forth in the following description in order to provide a full understanding of the invention. However, the invention may also be practiced in other ways different from those described herein, and those skilled in the art can make similar extensions without departing from the spirit of the invention. Therefore, the invention is not limited to the specific embodiments disclosed below.
[0055] Secondly, the term "an embodiment" or "embodiment" as used herein refers to a specific feature, structure, or characteristic that may be included in at least one implementation of the present invention. The phrase "in one embodiment" appearing in different places throughout this specification does not necessarily refer to the same embodiment, nor is it a single embodiment or an embodiment selectively excluded from other embodiments.
[0056] Reference Figures 1-6 As shown.
[0057] The embodiments further illustrate the incremental generation and interaction method of code knowledge graph proposed in this invention.
[0058] A method for incremental generation and interaction of code knowledge graphs, comprising the following steps:
[0059] Obtain the target project, and scan, filter, and categorize it to obtain a unified file list and project metadata.
[0060] Based on the unified file list pre-parsing of the project's internal import mapping, a file dependency graph is constructed with program code files as vertices and internal import relationships as edges. Based on the file dependency graph, dependency community partitioning is performed to obtain the full graph batch. Based on the full graph batch and the file dependency graph, the current analysis load and its one-hop neighbor context outside the load are generated.
[0061] Deterministic structure extraction is performed based on the current analysis load and project metadata to obtain structural facts; semantic graph fragments are generated based on the structural facts, the project internal imported data corresponding to the current analysis load, and the one-hop neighbor context outside the load.
[0062] The semantic graph fragments are merged and normalized, and a knowledge graph is generated based on the deterministic import edges of the import mapping within the project.
[0063] A structural fingerprint is generated based on a unified file list and structural facts. File changes are classified according to the structural fingerprint to obtain classification results. Hierarchical incremental updates are then performed based on the classification results.
[0064] Load the knowledge graph, respond to interactive query requests, and return query results based on the knowledge graph.
[0065] Suppose the project includes src / api / user.ts, src / service / user-service.ts, src / db / user-repository.ts, and tests / user-service.test.ts. The project access module 110 obtains the local directory and commit identifier, and the deterministic structure parsing module 120 normalizes the four paths and parses them to obtain the internal import mappings of user.ts importing user-service.ts, user-service.ts importing user-repository.ts, and test files importing user-service.ts.
[0066] The batching module 130 builds a file dependency graph based on this. Assuming that after community partitioning and batch upper limit adjustment, batch 0 contains user.ts and user-service.ts, and batch 1 contains user-repository.ts and user-service.test.ts. When analyzing batch 0, the files in Pb are the first two files, and batchImportData records the deterministic internal imports from user.ts to user-service.ts and from user-service.ts to user-repository.ts. The neighborMap calculated for user-service.ts includes user-repository.ts and user-service.test.ts other than load A, and carries their respective full graph batchIndex and available exported symbols.
[0067] The structural extraction results indicate that the user-service.ts file contains an exported UserService class and its methods, providing the name, line range, imports, and exports. Based on this, the file analysis unit outputs a GraphFragment: at least forming a file node file:src / service / user-service.ts and a class node class:src / service / user-service.ts:UserService that conforms to the saliency rules, connected by a contain edge. It can also generate a summary and labels to describe business responsibilities. Internal import edges must be based on batchImportData or subsequent deterministic recovery results.
[0068] The two batches of GraphFragments enter the merge and normalization module 150. The merge and normalization module 150 standardizes node identifiers and edge directions, deduplicates edges by node identifier, source, destination, type, and direction, and removes edges with missing endpoints. If a model fragment omits the imports edge from user-service.ts to user-repository.ts, but the nodes in both files exist, the edge is added back based on the internal import mapping. Subsequently, the architecture generation and validation module 160 generates the interface layer, service layer, data access layer, and test layer, and provides a guided walkthrough from user.ts to UserService and then to user-repository.ts.
[0069] After completing the lightweight validation, knowledge-graph.json, meta.json, and fingerprints.json are saved; the interactive display module 190 performs a full mode validation again and then displays the data in read-only mode. Users can search for nodes by UserService name, tag, summary, or languageNotes, view their one-hop neighbors, and also use breadth-first search to find the shortest graph path between user.ts and user-repository.ts; none of these operations modify the graph.
[0070] If subsequent submissions only add a method to the UserService class in user-service.ts, then when the core library's full comparator is called or the comparator is accessed by the preferred integration embodiment C, the content hash changes and the set of class methods recorded in classes[].methods changes, so it is judged as STRUCTURAL; when Q=1 and there is no change in the top-level directory, the action category outputs PARTIAL_UPDATE. The prompt-driven regular expression script for frozen path B only requires matching coarse-grained structures such as class names; adding a method within the class does not guarantee recognition, and it cannot be claimed that the hook will necessarily output PARTIAL_UPDATE in this case.
[0071] Path A can generate the user-service.ts changed file payload and external neighbors in the existing full map batch background according to version differences; the preferred integration embodiment C rescans the current import map, takes user-service.ts as payload A, connects it to the core library full comparator, and allows user.ts in the same batch but unchanged, as well as other adjacent files, to enter the neighborMap.
[0072] In the preferred integration embodiment C, the nodes and associated edges corresponding to user-service.ts in the old graph's filePath are trimmed, a new fragment is added, and it is merged with the unchanged baseline graph. The architecture layer and navigation steps are then rebuilt based on the update action. Subsequently, FingerprintStore.files['src / service / user-service.ts'] is replaced, and the historical fingerprints of the other three files are retained. If the change scale reaches the FULL_UPDATE condition, the automatic path freezing only prompts for explicit execution / understand--full, without automatically completing the aforementioned full reconstruction.
[0073] Dependency community partitioning is performed based on the file dependency graph to obtain a full graph batch. Based on the full graph batch and the file dependency graph, the current analysis load and its one-hop neighbor context outside the load are generated, specifically including:
[0074] A community detection algorithm is used to group mutually dependent or co-dependent files in the file dependency graph into the same community, and a full graph batch is assigned to each community.
[0075] Communities exceeding the preset batch limit are split according to the stable path order of the file dependency graph, isolated or small communities below the preset minimum batch are merged, and non-code groups with clear semantic boundaries are retained.
[0076] Based on the full map batch and file dependency graph, the import target and reverse import source of the file in the current analysis load are extracted. After excluding the file in the current analysis load, the file is stably truncated in descending order of the total degree of the neighbors in the file dependency graph and ascending order of the normalized path, resulting in a set of neighbor items. Each neighbor item in the set of neighbor items contains a file path, a full map batch identifier, and an export symbol.
[0077] A community detection algorithm is used to divide the file dependency graph into communities, grouping mutually dependent or jointly dependent files into the same community, and assigning a corresponding full-graph batch identifier to each community. By clustering files based on dependency relationships, functionally closely related files can be grouped into the same processing batch.
[0078] After initial community partitioning, communities are adjusted based on a preset batch size threshold. For communities with more files than the preset batch limit, they are split according to the stable path order of the file dependency graph, ensuring reasonable dependency relationships between sub-batches. Isolated or small communities with fewer files than the preset minimum batch size are merged to improve overall analysis efficiency. During community adjustment, non-code groups with clear semantic boundaries are retained to ensure the semantic independence of non-code files is unaffected by batch merging or splitting.
[0079] Based on the full-map batch determination, the one-hop neighbor context outside the current analysis payload is generated. For each file contained in the current analysis payload, its import target and reverse import source are extracted, i.e., other files imported by the file and other files that import the file. After extraction, files contained in the current analysis payload itself are excluded, and the remaining neighbor files are sorted in descending order according to their total degree in the file dependency graph. Files with the same total degree are sorted in ascending order according to the canonical path. Then, a stable truncation process is performed to obtain the final set of neighbor items. Each neighbor item contains the file path, full-map batch identifier, and exported symbol information. This contextual information provides the necessary external dependency references for semantic analysis, ensuring that sufficient cross-batch association information can still be obtained in batch processing mode, thereby ensuring that the generated map fragments have complete semantic boundaries and accurate dependencies.
[0080] In the full build and version difference-driven implementation path A, fragments of the graph for each batch are obtained; during incremental updates, the existing baseline subgraphs retained after pruning are also obtained, and the same deterministic merge script is invoked. The freeze implementation of the automatic fingerprint path B after commit only executes a subset of this step.
[0081] The merge script first checks the node identifiers and establishes a mapping from the original identifiers to the standardized identifiers. Node records lacking the `id` field are skipped. For existing but non-standard `id` values, prefix removal, supplementation, or rewriting is performed. Then, all edge endpoints are rewritten according to the mapping, normalizing the complexity to simple, moderate, or complex, and the edge direction to forward, backward, or bidirectional. Unknown node / edge types and out-of-bounds weights are handled in the subsequent complete pattern verification stage; it is not claimed that these are all handled by the current merge script.
[0082] Nodes are deduplicated according to the canonical identifier, retaining results from later in the stable reading order; edges are deduplicated according to the key composed of the canonical source node, canonical target node, relation type, and canonical direction, retaining the result with the larger numerical weight for edges with the same key. Dangling edges whose endpoints are not in the merged node set are deleted.
[0083] The deterministic specification for the tested_by relationship is as follows: the reverse relationship from test to production is rewritten as production to test, invalid relationships such as test-test, production-production or missing endpoints are deleted, and uncovered test relationships can be added according to the test file path convention.
[0084] Compare the deterministic internal import mappings in the scan results with the merged edge set; only when the file nodes corresponding to the source and target both exist and there are no imports edges in the same direction, supplement the deterministic import edges with predetermined directions and weights. Figure 5 This shows the complete build and the merge process used by path A.
[0085] Deterministic structure extraction is performed based on the current analysis load and project metadata to obtain structural facts. Semantic graph fragments are then generated based on these structural facts, the project's internal imported data corresponding to the current analysis load, and the one-hop neighbor context outside the load. Specifically, these fragments include:
[0086] Select the corresponding parsing plugin based on the programming language or file extension of the files in the current analysis payload. Extract functions, classes, methods, attributes, parameters, return types, imports, exports, and call candidates from program code files. Extract chapters, definitions, fields, services, endpoints, or resources from non-code files to obtain structural facts.
[0087] Generate a graph fragment containing nodes and edges based on project metadata, full graph batches, file information of the current analysis load, structural facts, imported data from within the project, one-hop neighbor context outside the load, and preset output constraints.
[0088] First, deterministic structure extraction is performed to obtain structural facts. Based on the programming language type or file extension of each file in the current analysis load, the corresponding parsing plugin is selected to perform structure analysis. Structural elements such as functions, classes, methods, attributes, parameters, return types, imports, exports, and call candidates are extracted from program code files; structural elements such as chapters, definitions, fields, services, endpoints, or resources are extracted from non-code files. By employing differentiated extraction strategies for different file types, complete and accurate structural fact data is ultimately obtained.
[0089] Semantic graph fragments are generated based on the obtained structural facts. The generation process integrates multi-dimensional input information, including project metadata, full-graph batch information, file information of the current analysis payload, the aforementioned extracted structural facts, imported data within the project, one-hop neighbor context outside the payload, and preset output constraints. Based on this multi-source input information, graph fragments containing nodes and edges are generated. Nodes correspond to various structural entities in code or non-code files, while edges correspond to the relationships between these structural entities. By fusing the structural information within the current analysis payload with the neighbor context information outside the payload, the generated graph fragments ensure that they possess both complete structural details within the payload and accurate associations with external dependencies, thus providing high-quality basic data support for graph merging and normalization processing.
[0090] The semantic graph fragments are merged and normalized, and a knowledge graph is generated based on the deterministic import edges of the project's internal import mapping. Specifically, this includes:
[0091] A mapping from original node identifiers to canonical identifiers is established based on semantic graph fragments, and the endpoint identifiers of edges are rewritten based on the mapping.
[0092] Based on preset rules, the complexity of nodes in semantic graph fragments is normalized to a preset level, and the edge directions are normalized to a preset set of directions.
[0093] Deduplicat nodes of semantic graph fragments according to the standard identifier, and deduplicat edges of semantic graph fragments according to the key composed of source node, target node, relation type and standard direction;
[0094] Remove any dangling edges in the semantic graph fragment whose endpoints do not exist in the merged node set;
[0095] The pre-parsed project internal import mapping is compared with the merged edge set. When both file nodes exist and there are no import edges in the same direction, deterministic import edges based on the project internal import mapping are added to generate a knowledge graph.
[0096] Based on semantic graph fragments, establish a mapping relationship between the original node identifiers and the standardized identifiers. Rewrite the endpoint identifiers of all edges according to this mapping relationship to unify the node identifiers into a standardized form.
[0097] Based on preset rules, the complexity of each node in the semantic graph fragment is normalized to a preset level, and the direction of the edges is normalized to a preset set of directions. Through attribute normalization, it is ensured that graph fragments from different sources maintain consistency in node complexity description and edge direction representation, eliminating merging obstacles caused by representation differences.
[0098] For nodes, deduplication is performed on nodes in the semantic graph fragment according to the canonical identifier, ensuring that each canonical identifier corresponds to only one node entity. For edges, deduplication is performed according to the key composed of the source node, target node, relation type, and canonical direction, ensuring that only one edge with the same source node, target node, relation type, and direction is retained. Through dual deduplication of nodes and edges, redundant information in the graph fragment is effectively eliminated.
[0099] Remove any dangling edges in the semantic graph fragment whose endpoints do not exist in the merged node set, ensuring that both endpoints of all edges exist in the node set, thus guaranteeing the reference integrity and structural validity of the graph.
[0100] The pre-parsed import mappings within the project are compared with the merged edge set. When both file nodes exist in the node set and there are no import edges in the same direction, deterministic import edges based on the import mappings within the project are added. By adding deterministic import edges, the import relationships between files in the knowledge graph are ensured to be complete and accurate, ultimately generating a complete knowledge graph.
[0101] A structural fingerprint is generated based on a unified document list and structural facts. Document changes are then classified according to the structural fingerprint to obtain classification results, specifically including:
[0102] The structural fingerprint is constructed by extracting the file content hash value, function feature set, class feature set, import set, and export set from the structural facts.
[0103] Compare the structural fingerprints of the changed files before and after the changes;
[0104] If the content hash values are the same, it is determined that there is no change; if the content hash values are different but the function characteristics, class characteristics, import set, and export set are all unchanged, it is determined that there is a surface change; if the function characteristics, class characteristics, import set, or export set changes, it is determined that there is a structural change.
[0105] The structural fingerprint of a file is constructed by extracting its content hash, function feature set, class feature set, import set, and export set from structural facts. These extracted multi-dimensional elements collectively constitute the file's structural fingerprint. The structural fingerprint characterizes the file's structural features from multiple levels, including content hashing, function structure, class structure, import dependencies, and export interfaces, providing a comprehensive basis for comparison in change detection and classification.
[0106] After generating the structural fingerprint, the structural fingerprints of the changed files are compared before and after the changes. By comparing the structural fingerprints of the files before and after the changes, the system can identify the changes in the files from multiple dimensions, thereby achieving accurate classification and determination of the types of file changes.
[0107] Based on the comparison results of structural fingerprints, file changes are categorized into three types. If the content hash values are the same, it is determined that there is no change, indicating that the file content has not changed. If the content hash values are different, but the function characteristics, class characteristics, import sets, and export sets remain unchanged, it is determined to be a superficial change, indicating that the file has only undergone superficial modifications that do not affect the code structure. If the function characteristics, class characteristics, import sets, or export sets change, it is determined to be a structural change, indicating that the file's code structure has undergone substantial changes. This three-level classification mechanism can identify the degree and type of file changes, providing a decision-making basis for hierarchical incremental updates.
[0108] Perform hierarchical incremental updates based on the classification results, specifically including:
[0109] When the decision is to skip the update, only update the project metadata and terminate the process;
[0110] When the decision is a partial update or an architecture update, the nodes and associated edges corresponding to the changed files in the existing knowledge graph are pruned based on the decision. The files to be reanalyzed are re-batched according to their dependency communities based on the file dependency graph. After generating new semantic graph fragments, they are merged with the pruned graph. When the decision is an architecture update, the architecture layer and navigation steps are regenerated.
[0111] The architecture analysis unit takes merged file-level nodes, deterministic imports edges, other file-level relationships, project directory structure, and framework information as input to generate architecture layers; each layer includes an identifier, name, description, and a set of node identifiers. The navigation construction unit takes nodes, edges, architecture layers, and the in-degree, out-degree, entry candidate, and breadth-first traversal results from deterministic computation as input to generate navigation steps with sequence numbers, titles, descriptions, and a set of node identifiers. The model can only reference node identifiers already present in the input graph.
[0112] The semantic content of the architecture layer and navigation steps can be generated by an artificial intelligence model, and its reference cleanup, field normalization and sorting are done by a deterministic procedure, so it is not claimed that the semantic text is exactly the same in every run.
[0113] Check the required fields, duplicate identifiers, edge endpoints, and layer / guide references for nodes, edges, architecture layers, and navigation steps. Perform the check once to confirm the fixes before re-verifying. If the re-verification passes, the graph is saved and automatic interactive display is allowed. According to the fault tolerance strategy of the frozen version, if critical issues still exist after re-verification, a portion of the graph will be written to knowledge-graph.json and a warning will be listed in the final report, but the automatic startup of interactive display will be skipped.
[0114] The persisted content includes knowledge-graph.json, meta.json, and fingerprints.json. The complete process only writes to the new meta.json after the structural fingerprint baseline is successfully generated, avoiding inconsistencies between the new commit identifier and the old fingerprint. In a preferred strict embodiment, candidate graphs and official graphs use different storage locations, and the official baseline is atomically replaced only after the candidate graph has completely passed pattern validation; this transactional persistence is not the default behavior for frozen versions.
[0115] When the decision is a full update, prompt the user to execute a full build process based on a unified file manifest and terminate automatic updates.
[0116] When the decision is to skip the update, only the project metadata is updated, terminating the entire update process. This approach is suitable when the files have not undergone substantial changes, minimizing unnecessary computational overhead.
[0117] When the decision is a partial update or an architecture update, the corresponding incremental update process is executed. Based on the decision result, nodes and associated edges corresponding to the changed files in the existing knowledge graph are pruned, removing the parts that need to be re-analyzed. Then, based on the file dependency graph, the files to be re-analyzed are re-batched according to their dependency communities to ensure that the batches of re-analysis maintain reasonable dependency relationships. Next, new semantic graph fragments are generated. Finally, the newly generated semantic graph fragments are merged with the pruned graph to complete the knowledge graph update. In addition, when the decision is an architecture update, based on the above update operations, the architecture layer and navigation steps need to be regenerated to ensure that the architecture level of the knowledge graph is consistent with the actual code structure.
[0118] The core library `fingerprint.ts` of the frozen repository and `build-fingerprints.mjs` in the full analysis phase can create a structural fingerprint F(f) = {Hf, Funcf, Classf, Importf, Exportf, Linesf, Af} for a predetermined source code file `f`. Here, `Hf` is the content hash value; `Funcf` contains the function name, parameters, return type, export status, and line number; `Classf` contains the class name, methods, properties, export status, and line number; `Importf` and `Exportf` are the import and export sets, respectively; `Linesf` is the file line number; and `Af` indicates whether a valid structural resolution was obtained. The full baseline container includes `version`, `gitCommitHash`, `generatedAt`, and a path-indexed `files` mapping. Non-source code configuration, documentation, and infrastructure files are not currently within the scope of automatic fingerprinting but may be included in extended implementations. Fine-grained comparison functions in the core library have been implemented, but as of the frozen commit, they have not been directly imported and called by the post-commit automatic hook.
[0119] In the implementation of the full comparator `compareFingerprints` in the core library, if the content hash values are the same, it is judged as `NONE`; if the content is different but the predefined structure comparison items remain unchanged, it is judged as `COSMETIC`. If a function is added / deleted, its parameters, return type, or export status changes, or if the line count ratio of shared functions `newLines / oldLines` is strictly greater than 1.5 or strictly less than 0.5, it is judged as `STRUCTURAL`; a ratio of exactly 1.5 or 0.5 does not trigger the line count condition alone. Changes in class methods, properties, or export status, as well as changes in import sources / import specifier sets or export sets, are also judged as `STRUCTURAL`. If any version lacks a valid structure resolution, it is conservatively judged as `STRUCTURAL`. `COSMETIC` only indicates that no change was detected in the predefined structure dimensions of the corresponding comparator; it does not necessarily mean that the business logic or call relationships have not changed.
[0120] The core library `classifyUpdate` applies the following action rules to the obtained set of file changes: Let Q be the sum of the number of structurally changed files, newly added files, and deleted files, and N be the total number of files in the existing graph; when Q=0, output `SKIP`; when Q is not greater than 10 and no top-level directory change is detected, output `PARTIAL_UPDATE`; when Q is greater than 10 or a top-level directory change is detected but the conditions for a complete update are not met, output `ARCHITECTURE_UPDATE`; when Q is greater than 30, or N is greater than 0 and Q / N is strictly greater than 0.5, prioritize outputting `FULL_UPDATE`. The auto-completion feature also requires the temporary script to use this decision matrix, but its Q depends on the results of a coarser-grained regularization comparison.
[0121] Implementation path A is a version difference-driven dependency community incremental path: A list of changed files is obtained from version control information; the dependency batching module 130 outputs only the changed file payloads within the context of the full graph batch number and existing neighbor relationships; the corresponding nodes and associated edges of the changed files are removed from the existing graph; and the cropped graph is merged with the new batch fragments according to S106. This path uses dependency community batching and the one-hop neighbor context outside the payload, but does not require structural fingerprint classification as a necessary prerequisite.
[0122] Implementation path B is the automatic fingerprinting path after a commit. This path first restricts version differences to predetermined source code extensions and applies ignore rules. Then, the prompt word requests the runtime to temporarily generate a regular expression script to perform lightweight function name, class name, import, and export comparisons on the changed files. The authoritative baseline is generated by the structure parser in the full analysis phase. The frozen repository does not commit a hook that directly calls compareFingerprints and classifyUpdate, and the regular expression patterns listed in the prompt do not extract class methods, function parameters, return types, or function line count ratios. Therefore, these subtle changes are not guaranteed to be recognized in path B. SKIP only updates the commit metadata and then stops; for filesToReanalyze of PARTIAL_UPDATE or ARCHITECTURE_UPDATE, if the number is no more than 10, they are grouped into a normal batch, and if the number is more than 10, they are grouped into batches of 5 to 10 files each, where PARTIAL_UPDATE will not exceed 10 files according to the above classification threshold; ARCHITECTURE_UPDATE regenerates the architecture layer and can rebuild the navigation steps after a partial map update; FULL_UPDATE only reports the need for a full rebuild and stops the automatic process in a frozen implementation, and a full rebuild must be triggered by a separate and explicit / understand--full command.
[0123] Path B currently does not invoke the dependent community batch script, load-external neighbor mapping, or the full S106 merge script. Its merge subset consists of: deleting old nodes and associated edges of changed or deleted files, adding new fragments, retaining new results by node identifier, deduplicating by source node, target node, and relation type, and deleting dangling edges. Therefore, the identifier normalization, direction normalization, tested_by correction, and internal imported edge recovery of S106 are not described as existing functions of Path B.
[0124] In the preferred integration embodiment C, S102 and S103 are first re-executed to replace the old intermediate data with the current file list and the current internal import mapping; then the files to be re-analyzed output by fingerprint classification are sent to the dependent batching module 130 to relocate their full graph community and generate the load external neighbor context; subsequently, the nodes and associated edges corresponding to the changed or deleted files are pruned, only the newly added and structurally changed files are re-analyzed, and merged with the retained baseline according to S106. Figure 1 The preferred incremental return module is indicated. Figure 2 Indicates the overall return path. Figure 6 This represents the fingerprint decision-making process and the optimal integration sub-process.
[0125] The preferred integration implementation performs a LOAD-PATCH-SAVE on the standard FingerprintStore container: first, load the entire container; replace `files[path]` for newly added or structurally changed files; delete `files[path]` for deleted files; update `gitCommitHash` and `generatedAt`; and then save the complete container containing the fingerprints of all unchanged files. The complete build of the frozen version has generated a baseline based on this container; however, the example code for automatic paths after commits has not yet correctly completed container-level patching of the `files` member, and `filesToReanalyze` does not include deleted files. Therefore, this section, as a preferred corrective implementation, does not claim that the frozen version has been fully implemented.
[0126] When the decision is a full update, the system prompts the user to execute a full build process based on a unified document checklist and terminates the automatic update process. This approach is suitable for situations where a project undergoes large-scale structural changes and incremental updates cannot guarantee the accuracy of the knowledge graph. By rebuilding the entire graph, the system ensures the integrity and accuracy of the knowledge graph.
[0127] Let the file dependency graph be Gf=(Vf, Ef), where Vf is the set of code files and Ef is the resolved internal import relationships. The community function C:Vf→B maps files to the full graph batch set B. Let A⊆Vf be the current analysis load actually sent to the analysis unit. For file x within A, construct a set of one-hop neighbors outside the load:
[0128] NA(x) = TopK({y∈Vf|[(x,y)∈Ef or (y,x)∈Ef],y∉A,and C(y) is defined},degree(y,path(y)).
[0129] In this process, TopK first sorts neighbors in descending order of their total degree in the full graph dependency graph, then performs stable truncation in ascending order of the canonical path; each preserved neighbor can carry its exported symbol and full graph batch identifier. During full construction, A is usually equal to a full graph batch, so neighbors are usually located in other batches; during incremental construction, A may only contain changed files within that batch, while unchanged files in the same batch can still enter NA(x).
[0130] For nodes with an `id` field, define a normalized identifier κv(v) = normalizeId(v.id, v.type, v.filePath, v.name). If the `id` field is missing, record the problem and skip the node; do not reconstruct the complete identifier from other fields. The edge normalization key κe(e) = (normalizeId(e.source), normalizeId(e.target), e.type, normalizeDirection(e.direction)). Following a stable reading order, nodes with the same normalized identifier are retained in the later results; edges with the same normalization key are retained in the results with the higher numerical weight; any edge whose endpoint does not belong to the merged node set is deleted.
[0131] The core library's full comparator first compares content hash values to quickly identify identical files, then compares structural sets such as functions, classes, imports, and exports; it does not use ordinary interface interactions or model-generated summaries as criteria for structural changes. The function line count ratio and action quantity / ratio threshold are calculated according to the strict inequality of S108. Freeze path B only temporarily generates a coarser-grained regular expression comparison script based on prompts and cannot encompass the full detection capabilities of the full comparator.
[0132] Construct an adjacency list from the edge set, enqueuing the starting point and recording its predecessor; visit unvisited neighbors in breadth-first order, and reconstruct the path along the predecessor chain when visiting the destination for the first time. This query is read-only and does not change the edge weights or graph content.
[0133] Also includes:
[0134] Based on the knowledge graph, the required fields, duplicate identifiers, and edge endpoint validity of nodes, edges, architectural layers, and navigation steps are verified.
[0135] If the verification passes, persist the knowledge graph, project metadata, and structural fingerprint; if the verification fails, save a portion of the graph and record a warning.
[0136] A comprehensive validation of the knowledge graph is performed. The validation scope covers nodes, edges, the architecture layer, and navigation steps, and includes checking the completeness of required fields, the existence of duplicate identifiers, and the validity of edge endpoints, among other aspects. This multi-dimensional validation ensures the data integrity and structural validity of the knowledge graph.
[0137] Different persistence strategies are executed based on the verification results. When verification passes, the knowledge graph, project metadata, and structural fingerprint are persistently stored to ensure that the data can be loaded and used subsequently. When verification fails, a portion of the graph data is saved, and corresponding warning messages are recorded to facilitate subsequent troubleshooting and remediation. Through differentiated persistence strategies, the complete persistence of data under normal circumstances is guaranteed, while the recoverability of partial data and the traceability of problems are ensured in abnormal situations.
[0138] Loading knowledge graphs, specifically including:
[0139] Load the persistent knowledge graph and perform full schema validation based on the knowledge graph, including type alias normalization, default value correction, invalid node / edge deletion, and reference integrity check;
[0140] Based on the knowledge graph, it supports fuzzy search based on node name, tag, summary and language description. It supports querying the adjacency relationship of selected nodes and the dependency path based on breadth-first search. It supports displaying related nodes in the order of the navigation steps. It supports mapping version change files and displaying the affected nodes and related edges.
[0141] First, the persistent knowledge graph is loaded, and then a full schema validation is performed based on the loaded knowledge graph. The validation includes several aspects, such as type alias normalization, default value correction, deletion of invalid nodes and edges, and referential integrity checks. This full schema validation ensures that the loaded knowledge graph data is standardized and structurally complete, providing a reliable data foundation for interactive queries.
[0142] Based on the validated knowledge graph, it offers a variety of interactive query functions. It supports fuzzy string searches based on node name, tags, summaries, and language descriptions, allowing users to quickly locate target nodes; it supports querying the adjacency relationships of selected nodes, as well as dependency path queries based on breadth-first search, helping users understand the connections between nodes; it supports displaying related nodes in the order of the guided tour steps, providing a structured browsing experience; it supports mapping version change files and displaying the affected nodes and related edges for one hop, facilitating users to analyze the scope of the impact of version changes. Through these multi-dimensional interactive query functions, it provides users with comprehensive and flexible knowledge graph access capabilities.
[0143] Also includes:
[0144] When the community detection algorithm malfunctions, the standardized path sorting results based on the unified file list are deterministically downgraded and grouped by a fixed number of preset parameters.
[0145] When a single file resolution fails, the file-level neighbor context of the file is preserved based on the file dependency graph, a warning is logged, and the file is added to the skip list.
[0146] If a batch semantic analysis task fails, it will be retried once. If the retry still fails, the batch will be included in the failure report and empty outputs will not be considered valid graph fragments.
[0147] Dangling edges are removed during the merge normalization process, and imported edges are only restored if both file nodes exist based on the import mapping within the project.
[0148] When the community detection algorithm malfunctions, a degradation grouping strategy is employed. Based on the standardized path sorting results of the unified file list, deterministic degradation grouping is performed according to a preset fixed number of groups to ensure stable batch partitioning results even when the community detection algorithm fails, thus guaranteeing the continuity of subsequent processing.
[0149] When a single file fails to resolve, the file-level neighbor context of that file is preserved based on the file dependency graph, a warning message is logged, and the file is added to the skip list. By preserving the neighbor context, it is ensured that even if a single file fails to resolve, its related dependency information can still be partially retained, reducing the impact on the overall graph quality.
[0150] When a batch semantic analysis task fails, a retry mechanism is implemented. First, the semantic analysis task for that batch is retried once. If the retry also fails, the batch is included in the failure report, and empty outputs are not considered valid graph fragments. The retry mechanism improves the success rate of batch analysis, while the failure reporting mechanism ensures that problems are traceable and prevents invalid data from affecting graph quality.
[0151] The merge and normalization process includes corresponding fault-tolerance mechanisms. First, dangling edges generated during the merge process are removed to ensure the validity of the graph structure. Then, imported edges are only restored after confirming the existence of both file nodes based on the project's internal import mapping. This cautious edge restoration strategy ensures the accuracy and completeness of imported edges, avoiding the introduction of invalid or erroneous edge relationships.
[0152] The present invention includes a project access module 110, a deterministic structure parsing module 120, a dependency batching module 130, a semantic analysis module 140, a merging and normalization module 150, an architecture generation and verification module 160, an incremental update module 170, a graph and fingerprint storage module 180, and an interactive display module 190.
[0153] The project access module 110 is used to acquire target projects, perform scanning, filtering, and classification processing on them, and finally generate a unified file list and project metadata, providing a basic data source for subsequent full-process analysis and calculation. The deterministic structure parsing module 120 combines the current analysis load and project metadata to complete deterministic structure extraction, obtain structural facts, and provide verifiable underlying structural basis for semantic analysis. The dependency batching module 130 relies on the unified file list to pre-parse the internal import mapping of the project, uses program code files as vertices and internal import relationships as edges to build a file dependency graph, completes dependency community partitioning based on the file dependency graph to obtain full graph batches, and then combines the full graph batches and the file dependency graph to generate the current analysis load and the one-hop neighbor context outside the load, retaining complete boundary dependency clues while controlling the data volume of a single analysis.
[0154] The semantic analysis module 140 integrates structural facts, imported data from within the project corresponding to the current analysis payload, and one-hop neighbor context outside the payload to generate semantic graph fragments containing nodes and edges, supplementing complete semantic information based on a fixed underlying grammatical structure. The merging and normalization module 150 performs identifier mapping rewriting, node and edge normalization and deduplication, and dangling edge deletion on all semantic graph fragments. Simultaneously, it compares the imported mappings within the project to supplement deterministic imported edges, integrating them to generate a standardized knowledge graph. The architecture generation and verification module 160 is responsible for building the architecture layer and navigation steps, verifying required fields, duplicate identifiers, and edge endpoint validity for nodes, edges, architecture layer, and navigation steps in the knowledge graph, ensuring the compliance and validity of the graph data.
[0155] The incremental update module 170 generates structural fingerprints based on a unified file list and structural fingerprints. It compares the structural fingerprints before and after file modifications to classify change types and performs hierarchical incremental updates according to different types, avoiding redundant and repetitive analysis calculations. The knowledge graph and fingerprint storage module 180 persists the data according to the verification results. If all verifications pass, the knowledge graph, project metadata, and structural fingerprints are fully stored. If verification issues are found, a portion of the knowledge graph is saved, and warning records are retained. The interactive display module 190 loads the persisted knowledge graph and performs pattern verification. It provides multiple interactive functions such as fuzzy node search, adjacency relationship query, breadth-first dependency path query, guided order display, and viewing nodes affected by version changes. It receives user query requests and returns matching knowledge graph results. The entire system relies on the sequential flow of data from each module to complete the entire process of batch construction, incremental update, storage verification, and interactive query of the code knowledge graph.
[0156] The interactive display module 190 read-only loads the persistent knowledge graph and calls the full schema validation program to perform type alias normalization, default value and weight correction, invalid node / edge deletion, and reference integrity checks. If validation is successful, the normalized graph is displayed according to the architecture layer; if fatal errors such as missing project metadata or no valid nodes occur, a loading failure message is displayed instead of rendering the invalid graph.
[0157] The basic search uses Fuse string approximation matching, and the actual search fields are node name, tags, summary, and language notes. In one embodiment, the field weights are 0.4, 0.3, 0.2, and 0.1 respectively, with a matching threshold of 0.4, and a default maximum of 50 results are returned. The frozen version does not use filePath as the search key for this search engine; the "semantic" mode shown in the interface currently reuses the same approximation matching engine.
[0158] Displays the type, summary, file location, tag, and neighboring nodes of the selected node; constructs an adjacency list based on graph edges, and uses breadth-first search to find the shortest connection path between two specified nodes. During exploration, directed edges can be treated as bidirectional traversable connections, but the original edge direction is still preserved in the details.
[0159] The guide displays related nodes sequentially; it maps version change files to graph nodes and displays the affected nodes, related edges, and architecture layers of each node; and it provides separate prompts for unmapped files.
[0160] Interface events only update the client's selection state, filtering conditions, view position, and temporary query results; they do not write structural fingerprints, modify the formal graph, or serve as training samples for artificial intelligence models.
[0161] Through the above description of the embodiments, those skilled in the art can clearly understand that each embodiment can be implemented by means of software plus necessary general-purpose hardware platforms, and of course, it can also be implemented by hardware. Based on this understanding, the above technical solutions, in essence or the part that contributes to the prior art, can be embodied in the form of a software product. This computer software product can be stored in a computer-readable storage medium, such as ROM / RAM, magnetic disk, optical disk, etc., and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute the methods described in the various embodiments or some parts of the embodiments.
[0162] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention.
Claims
1. A method for incremental generation and interaction of code knowledge graphs, characterized in that, Includes the following steps: Obtain the target project, and scan, filter, and categorize it to obtain a unified file list and project metadata. Based on the unified file list pre-parsing of the project's internal import mapping, a file dependency graph is constructed with program code files as vertices and internal import relationships as edges. Based on the file dependency graph, dependency community partitioning is performed to obtain the full graph batch. Based on the full graph batch and the file dependency graph, the current analysis load and its one-hop neighbor context outside the load are generated. Structural facts are obtained by deterministic structure extraction based on the current analysis load and project metadata; Semantic graph fragments are generated based on structural facts, the project-internal imported data corresponding to the current analysis load, and the one-hop neighbor context outside the load. The semantic graph fragments are merged and normalized, and a knowledge graph is generated based on the deterministic import edges of the import mapping within the project. A structural fingerprint is generated based on a unified file list and structural facts. File changes are classified according to the structural fingerprint to obtain classification results. Hierarchical incremental updates are then performed based on the classification results. Load the knowledge graph, respond to interactive query requests, and return query results based on the knowledge graph.
2. The incremental generation and interaction method for code knowledge graphs according to claim 1, characterized in that, Dependency community partitioning is performed based on the file dependency graph to obtain a full graph batch. Based on the full graph batch and the file dependency graph, the current analysis load and its one-hop neighbor context outside the load are generated, specifically including: A community detection algorithm is used to group mutually dependent or co-dependent files in the file dependency graph into the same community, and a full graph batch is assigned to each community. Communities exceeding the preset batch limit are split according to the stable path order of the file dependency graph, isolated or small communities below the preset minimum batch are merged, and non-code groups with clear semantic boundaries are retained. Based on the full graph batch and file dependency graph, the import target and reverse import source of the file in the current analysis load are extracted. After excluding the file in the current analysis load, the file is stably truncated in descending order of the total degree of the neighbors in the file dependency graph and ascending order of the normalized path to obtain a set of neighbor items. Each neighbor item in the set of neighbor items contains a file path, a full graph batch identifier and an export symbol.
3. The incremental generation and interaction method for code knowledge graphs according to claim 1, characterized in that, Deterministic structure extraction is performed based on the current analysis load and project metadata to obtain structural facts. Semantic graph fragments are then generated based on these structural facts, the project's internal imported data corresponding to the current analysis load, and the one-hop neighbor context outside the load. Specifically, these fragments include: Select the corresponding parsing plugin based on the programming language or file extension of the files in the current analysis payload. Extract functions, classes, methods, attributes, parameters, return types, imports, exports, and call candidates from program code files. Extract chapters, definitions, fields, services, endpoints, or resources from non-code files to obtain structural facts. Generate a graph fragment containing nodes and edges based on project metadata, full graph batches, file information of the current analysis load, structural facts, imported data from within the project, one-hop neighbor context outside the load, and preset output constraints.
4. The incremental generation and interaction method for code knowledge graphs according to claim 1, characterized in that, The semantic graph fragments are merged and normalized, and a knowledge graph is generated based on the deterministic import edges of the project's internal import mapping. Specifically, this includes: A mapping from original node identifiers to canonical identifiers is established based on semantic graph fragments, and the endpoint identifiers of edges are rewritten based on the mapping. Based on preset rules, the complexity of nodes in semantic graph fragments is normalized to a preset level, and the edge directions are normalized to a preset set of directions. Deduplicat nodes of semantic graph fragments according to the standard identifier, and deduplicat edges of semantic graph fragments according to the key composed of source node, target node, relation type and standard direction; Remove any dangling edges in the semantic graph fragment whose endpoints do not exist in the merged node set; The pre-parsed project internal import mapping is compared with the merged edge set. When both file nodes exist and there are no import edges in the same direction, deterministic import edges based on the project internal import mapping are added to generate a knowledge graph.
5. The incremental generation and interaction method for code knowledge graphs according to claim 1, characterized in that, A structural fingerprint is generated based on a unified document list and structural facts. Document changes are then classified according to the structural fingerprint to obtain classification results, specifically including: The structural fingerprint is constructed by extracting the file content hash value, function feature set, class feature set, import set, and export set from the structural facts. Compare the structural fingerprints of the changed files before and after the changes; If the content hash values are the same, it is determined that there is no change; if the content hash values are different but the function characteristics, class characteristics, import set, and export set are all unchanged, it is determined that there is a surface change; if the function characteristics, class characteristics, import set, or export set changes, it is determined that there is a structural change.
6. The incremental generation and interaction method for code knowledge graphs according to claim 5, characterized in that, Perform hierarchical incremental updates based on the classification results, specifically including: When the decision is to skip the update, only update the project metadata and terminate the process; When the decision is a partial update or an architecture update, the nodes and associated edges corresponding to the changed files in the existing knowledge graph are pruned based on the decision. The files to be reanalyzed are re-batched according to their dependency communities based on the file dependency graph. After generating new semantic graph fragments, they are merged with the pruned graph. When the decision is an architecture update, the architecture layer and navigation steps are regenerated. When the decision is a full update, prompt the user to execute a full build process based on a unified file manifest and terminate automatic updates.
7. The incremental generation and interaction method for code knowledge graphs according to claim 6, characterized in that, Also includes: Based on the knowledge graph, the required fields, duplicate identifiers, and edge endpoint validity of nodes, edges, architectural layers, and navigation steps are verified. If the verification passes, persist the knowledge graph, project metadata, and structural fingerprint; if the verification fails, save a portion of the graph and record a warning.
8. The incremental generation and interaction method for code knowledge graphs according to claim 1, characterized in that, Loading knowledge graphs, specifically including: Load the persistent knowledge graph and perform full schema validation based on the knowledge graph, including type alias normalization, default value correction, invalid node / edge deletion, and reference integrity check.
9. The incremental generation and interaction method for code knowledge graphs according to claim 1, characterized in that, Also includes: When the community detection algorithm malfunctions, the standardized path sorting results based on the unified file list are deterministically downgraded and grouped by a fixed number of preset parameters. When a single file resolution fails, the file-level neighbor context of the file is preserved based on the file dependency graph, a warning is logged, and the file is added to the skip list. If a batch semantic analysis task fails, it will be retried once. If the retry still fails, the batch will be included in the failure report and empty outputs will not be considered valid graph fragments. Dangling edges are removed during the merge normalization process, and imported edges are only restored if the file nodes at both ends are confirmed to exist based on the import mapping within the project.
10. The incremental generation and interaction method for code knowledge graphs according to claim 9, characterized in that, Based on the knowledge graph, it supports fuzzy search based on node name, tag, summary and language description. It supports querying the adjacency relationship of selected nodes and the dependency path based on breadth-first search. It supports displaying related nodes in the order of the navigation steps. It supports mapping version change files and displaying the affected nodes and related edges.