Deterministic code security audit pre-scanning and multi-agent collaborative reasoning method

CN122595336APending Publication Date: 2026-08-18GUIZHOU BLUESKY INNOVATIVE SCI & TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611081544.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-21
Publication Date
2026-08-18

AI Technical Summary

Technical Problem

[0002]随着软件系统规模与复杂性持续增长,传统人工代码审计效率低、覆盖面有限,基于自动化技术的代码安全审计方法已成为软件安全领域的研究热点

Benefits of technology

[0019] By employing a deterministic pre-scan driven by a security specification attribute library carrying specification anchor IDs, and tracing each hit record back to the corresponding structured attribute entry via the specification anchor ID, the problem of traditional pre-scan results being unable to be traced back to specific security specification entries is solved. This ensures that each finding in the audit report has a complete traceable link from the pre-scan hit to the security specification, significantly improving the interpretability and verifiability of audit conclusions.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122595336A_ABST
    Figure CN122595336A_ABST
Patent Text Reader

Abstract

The application discloses a deterministic code security audit pre-scanning and multi-agent collaborative reasoning method. The method is based on reports to discover code assets and attack surface mapping, and the attack surface mapping results are associated with hit records through standard anchors. The attack surface mapping results are decomposed into four granularity levels of file architecture layer, function logic layer, statement data flow layer and expression calculation layer. The agents of each granularity level reason within the corresponding level and save the assertion record table. The collaborative analysis result set is obtained through the cross-granularity information transmission channel. The SMT-convertible conditions are filtered from the assertion record table and converted into satisfiability constraints. The SMT solver is called to filter the unsatisfiable attack paths. The attack chain is generated based on the verified reachable attack paths, and the attack chain is backtracked through the standard anchors to generate a traceable audit report. The application solves the problems that the traditional pre-scanning results cannot be traced to the security specifications and the multi-agent flat collaboration granularity is not fully covered.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer software security auditing technology, specifically to a code security auditing method that integrates deterministic rule scanning and large language model-driven reasoning, particularly to traceable deterministic pre-scanning driven by a security specification attribute library, multi-granularity hierarchical multi-agent collaborative reasoning, and path condition satisfiability verification based on SMT constraint solving. Background Technology

[0002] As software systems continue to grow in scale and complexity, traditional manual code auditing is inefficient and has limited coverage. Automated code security auditing methods have become a research hotspot in the field of software security. Currently, there are two main technical approaches in code security auditing: one is rule-based static application security testing (SAST), which uses a predefined rule base to perform pattern matching on source code and output a list of potential defects. This approach is fast and has broad coverage, but it is highly dependent on the quality of the rule base and cannot understand the semantic context of the code, resulting in a generally high false positive rate. The other is intelligent auditing methods based on large language models, which utilize the code understanding and reasoning capabilities of large language models to perform security analysis on the code. This method has semantic awareness and can discover logical vulnerabilities that rule-based methods cannot cover, but the reasoning results are uncertain and unreproducible, making it difficult to independently meet engineering-level reliability requirements in scenarios like security auditing where completeness and determinism are extremely important.

[0003] However, the aforementioned existing technical solutions have the following two prominent problems. First, the search patterns in the skill knowledge base are merely a set of pure regular expressions. Each matching record lacks a semantic anchor point related to security specifications, making it impossible to trace the pre-scan results back to specific specification entries or audit standards. This results in insufficient interpretability and traceability of the audit process—when an audit report points out a vulnerability, the reviewer cannot quickly pinpoint which specific requirement of which security specification the judgment is based on. Second, the collaboration between multiple agents lacks a structured granular hierarchical division. All agents reason on the same or overlapping code scopes at a flat level, failing to utilize the inherent granular hierarchical characteristics of code (file architecture → function logic → statement data flow → expression evaluation). This leads to redundant reasoning and potential conflicts between different agents on the same code region, wasting computational resources and lacking a systematic coverage from macro-architecture to micro-expressions. Summary of the Invention

[0004] This invention provides a deterministic code security audit pre-scanning and multi-agent collaborative reasoning method, comprising: performing a deterministic pre-scanning of a target codebase based on a security specification attribute library, generating a pre-scan traceable report, wherein each structured attribute entry in the security specification attribute library carries a specification anchor ID, and each hit record in the pre-scan traceable report is traced back to the corresponding structured attribute entry via the specification anchor ID; performing code asset discovery and attack surface mapping based on the pre-scan traceable report, and associating the obtained attack surface mapping results with the hit records via the specification anchor ID; and decomposing the attack surface mapping results into a file architecture layer. The system comprises four granular layers: function logic layer, statement data flow layer, and expression computation layer. Agents at each granularity layer reason and store assertion records within their respective layers. These records are then transmitted through cross-granularity information transmission channels to obtain a collaborative analysis result set. SMT-compliant conditions are selected from the assertion records in the collaborative analysis result set and transformed into satisfiability constraints. An SMT solver is then used to filter out attack paths deemed unsatisfiable, resulting in a satisfiability verification result set. Attack chains are chained together based on the verified reachable attack paths in the satisfiability verification result set, and a full-chain backtracking is performed using the specified anchor ID to generate a traceable audit report.

[0005] Furthermore, each structured attribute entry in the security specification attribute library also carries an associated CWE number, a matching confidence weight, and the security specification category to which it belongs. The correspondence between the associated CWE number and the search regular expression pattern in the structured attribute entry is established by statistically analyzing the co-occurrence of the CWE tags of historical vulnerability cases and the hit frequency of the search regular expression pattern. The deterministic pre-scanning of the target code library based on the security specification attribute library includes: using the search regular expression patterns of each structured attribute entry in the security specification attribute library, performing regular expression matching scans on the target code library in sequence, and capturing the matching position, the specification anchor ID of the structured attribute entry that triggered the matching, the associated CWE number, and the comprehensive confidence score for each matching record.

[0006] Furthermore, the comprehensive confidence score is calculated based on the preset matching confidence weight and matching accuracy of the structured attribute entries; the generation of the pre-scan traceable report includes: performing deduplication processing on the captured matching records, retaining the structured attribute entry with the highest comprehensive confidence score when the same line of code is matched by multiple structured attribute entries; performing merging processing on matching records in the same file after deduplication where the line number difference does not exceed a preset threshold to obtain merged code blocks; organizing the merged code blocks into a tree structure according to a three-level hierarchy of file path, line number, and standard anchor ID to generate the pre-scan traceable report.

[0007] Furthermore, the agent in the file architecture layer focuses on module dependencies, cross-file interface compliance, configuration security, and deployment boundaries; the agent in the function logic layer focuses on the integrity of control flow within functions, the completeness of exception handling, the distribution of authentication and authorization checkpoints, and business logic bypass conditions; the agent in the statement data flow layer focuses on the propagation path of variable taints from external input to sensitive convergence points, type security boundaries, and the validity of data verification points; and the agent in the expression computation layer focuses on operator precedence, integer overflow and underflow boundaries, the possibility of division by zero, and bitwise operation safety.

[0008] Furthermore, the reasoning by agents at each granularity level within their respective granularity levels includes: the main audit agent assigning the analysis tasks of the file architecture layer, function logic layer, statement data flow layer, and expression calculation layer to file-level agents, function-level agents, statement-level agents, and expression-level agents, respectively. Each agent executes a reasoning loop within its respective granularity level, including observing code context, inferring security vulnerabilities, calling static analysis tools, and performing the next round of reasoning based on the tool's returned results. The transmission via the cross-granularity information transmission channel includes: agents at higher granularity levels transmitting structural fact assertions down the cross-granularity information transmission channel to agents at lower granularity levels as targeted inspection prompts; agents at lower granularity levels transmitting atomic facts to agents at higher granularity levels as constraints; and an attack chain construction agent connecting isolated vulnerability clues from each granularity level into the attack chain.

[0009] Furthermore, the assertion record table records the conditional branch expressions and data flow assertions encountered by the agents at each granularity level during inference. The conditional branch expressions include the conditional parts of if, switch, while, and ternary operators. The step of filtering SMT-enhanced conditions from the assertion record table of the collaborative analysis result set includes: filtering key conditional branches that affect the reachability of attack paths from the assertion record table; for each attack path, concatenating the conditional branch expressions on the attack path into a path condition constraint set; dividing the conditions in the path condition constraint set into SMT-enhanced conditions and semantically rich conditions. The SMT-enhanced conditions include mathematical comparison conditions, string matching conditions, and Boolean logic combination conditions. The semantically rich conditions include method calls, database query result dependencies, and external service status judgments.

[0010] Furthermore, the step of converting the conditions into satisfiability constraints and calling the SMT solver includes: converting the integer comparison conditions in the SMT-saturable conditions into integer arithmetic theory constraints, the string matching conditions into string theory constraints, and the Boolean logic combination conditions into propositional logic constraints; calling the SMT solver to verify the satisfiability of the comprehensive conditions for each attack path one by one; marking the corresponding attack path as a verified attack path when the SMT solver returns satisfiable and assigns a satisfiability value; marking the corresponding attack path as a false alarm and attaching a proof of unsatisfiability when the SMT solver returns unsatisfiable; and marking the semantically rich conditions as requiring manual review.

[0011] Furthermore, the code asset discovery and attack surface mapping based on the pre-scan traceable report includes: extracting high-risk marked code blocks from the pre-scan traceable report; identifying code assets by combining the project file structure tree of the target code repository; the code assets include HTTP API route definitions, RPC service endpoints, message queue consumers, file upload and download processing functions, database query entry points, and third-party service call points; tracing the input data source, data flow path, and permission check context for each code asset; and calculating an attack surface feature vector that includes external accessibility scores, data sensitivity scores, and permission boundary offset risk scores; associating the attack surface feature vector with the pre-scan traceable report using the file path as the primary key, and marking the covered parts and the uncovered security specification gaps.

[0012] Furthermore, the method also includes: retrieving remediation solutions for similar historical vulnerability cases from the historical vulnerability knowledge base based on the code feature similarity of the attack chain and attaching them to the traceable audit report; and incrementally writing new vulnerability patterns confirmed in this audit that are not covered by the historical vulnerability knowledge base into the historical vulnerability knowledge base.

[0013] Furthermore, before sequentially performing regular expression matching scans on the target codebase using the search regular expression patterns of each structured attribute entry in the security specification attribute library, the process further includes: parsing the metadata of each structured attribute entry, the metadata including the target programming language, target framework, vulnerability category represented by the associated CWE number, and estimated single scan time; and dividing multiple structured attribute entries detecting the same vulnerability category into the same rule family according to the same associated CWE number; and extracting a list of programming languages, a list of frameworks, and a list of dependency libraries based on the file extension distribution, build configuration file, and dependency declaration file of the target codebase. The project's technology stack characteristics are analyzed. Based on the metadata of each structured attribute entry and the project's technology stack characteristics, the correlation between each structured attribute entry and the target code library is calculated. A basic correlation score is awarded when the target programming language belongs to the programming language list; a first correlation score is added when the target framework belongs to the framework list; and a second correlation score is added when the vulnerability category matches a known vulnerability type in the dependency library list. Based on the coverage coefficient of each vulnerability type, the severity weight of each vulnerability type, and the correlation in each structured attribute entry, a coverage function is constructed. The coverage function outputs a correlation coefficient for any subset of structured attribute entries. The expected vulnerability discovery coverage is weighted by vulnerability type severity. When the correlation is lower than the correlation threshold, a decay factor is applied to the corresponding coverage coefficient as the correlation decreases. The curvature parameter of the coverage function is calculated, and under the constraints of scan time budget and matroid, an adaptive curvature greedy selection is performed based on maximizing the ratio of marginal coverage gain to scan time. Structured attribute entries are iteratively selected until constraint saturation, obtaining an optimal subset of structured attribute entries. The matroid constraint limits each rule family to selecting at most one structured attribute entry. In each iteration of the greedy selection, for entries with a correlation not lower than the correlation confidence threshold... The marginal coverage gain of the structured attribute entries is directly calculated using the coverage coefficient. For the remaining structured attribute entries, the utility of the structured attribute entries relative to the target code library is evaluated using a large language model. The evaluated value is modeled as an estimate of superimposed sub-Gaussian noise. The average of multiple evaluations of the same structured attribute entry within a noise buffer window is taken as the estimate of the marginal coverage gain. The size of the noise buffer window is determined by the variance of the sub-Gaussian noise and a preset error bound. The regular matching scan of the target code library is performed only using the search regularization pattern of each structured attribute entry in the optimal subset of structured attribute entries.

[0014] Furthermore, when the audit scenario of the target code library is an incremental audit scenario that only scans changed code blocks, and the cardinality of the optimal subset of structured attribute entries does not exceed the preset cardinality limit, the curvature adaptive greedy selection is a two-stage approximate selection, including: a first stage, performing a standard greedy algorithm on the security specification attribute library to select a number of structured attribute entries equal to half of the preset cardinality limit, thus obtaining a basic entry set; a second stage, performing non-uniform random sampling on the structured attribute entries in the security specification attribute library other than the basic entry set, wherein the probability of each structured attribute entry being sampled increases monotonically with the marginal coverage gain relative to the basic entry set after adjustment by a temperature parameter, and a number of structured attribute entries equal to half of the preset cardinality limit are selected from the sampling distribution without replacement, and merged with the basic entry set to form a candidate entry subset, wherein the temperature parameter decreases when the variance of the sampling results exceeds the variance limit for multiple consecutive rounds and increases when the variance of the sampling results is in the range of multiple consecutive rounds; the second stage is repeated for a preset number of rounds, and the candidate entry subset with the largest value of the coverage function is taken as the optimal subset of structured attribute entries.

[0015] Furthermore, the method further includes: for each structured attribute entry in the optimal subset of structured attribute entries that has been scanned, performing multiple post-application applicability assessments using a large language model under multiple different contextual temperatures. The post-application applicability assessment includes whether the hit code line constitutes a real vulnerability, false positive rate estimation, and the matching degree between the structured attribute entry and the target codebase technology stack; grouping the structured attribute entries in the optimal subset of structured attribute entries according to the rule families; taking the median of the post-application applicability assessments for structured attribute entries within the same rule family as the noise reduction utility estimate; and considering the historical phase of the assessment bias within the rule family... The number of relationships is adjusted to the required number of assessments for the post-application suitability evaluation; the correlation degree of each structured attribute item is updated based on the noise reduction utility estimate, increasing the correlation degree of structured attribute items whose noise reduction utility estimate is higher than the high utility threshold and decreasing the correlation degree of structured attribute items whose noise reduction utility estimate is lower than the low utility threshold; the coverage coefficient is updated using an exponentially weighted moving average method based on the actual hit data of this scan; the updated correlation degree and coverage coefficient are fed back to the correlation degree calculation and coverage function construction of the next audit cycle, forming a closed loop of scanning, evaluation, updating and re-scanning.

[0016] Furthermore, the method also includes: for multiple agents that output security judgment results for the same code location in the collaborative analysis result set, collecting the binary judgment result and judgment confidence score of each agent for the vulnerability or non-vulnerability of that code location; based on the historical audit annotations of each agent confirmed by manual verification or automated exploitability testing, constructing a confusion matrix for each agent containing the counts of true positives, false positives, true negatives, and false negatives, and estimating the true positive rate, false positive rate, and historical effective sample size of each agent using the confusion matrix; based on the true positive rate, the false positive rate, and the empirical vulnerability prior probability, using Bayes' theorem to calibrate the confidence of each agent's judgment, obtaining the conditional posterior probability of the true result when each agent judges it as a vulnerability or non-vulnerability, constituting the confidence parameter of each agent.

[0017] This invention also provides a deterministic code security audit pre-scanning and multi-agent collaborative reasoning device for executing the above method, comprising: a pre-scanning module for performing a deterministic pre-scan on a target codebase based on a security specification attribute library, generating a pre-scanning traceable report, wherein each structured attribute entry in the security specification attribute library carries a specification anchor ID, and each hit record in the pre-scanning traceable report is traced back to the corresponding structured attribute entry via the specification anchor ID; an attack surface mapping module for performing code asset discovery and attack surface mapping based on the pre-scanning traceable report, and associating the obtained attack surface mapping results with the hit records via the specification anchor ID; and a multi-granularity collaborative analysis module for analyzing the attack surface mapping results. The results are decomposed into four granular layers: file architecture layer, function logic layer, statement data flow layer, and expression calculation layer. Agents at each granularity layer reason within their respective layers and store assertion record tables. These records are then transmitted through cross-granularity information transmission channels to obtain a collaborative analysis result set. A satisfiability verification module is used to filter SMT-based conditions from the assertion record tables in the collaborative analysis result set and convert them into satisfiability constraints. It then calls the SMT solver to filter out attack paths deemed unsatisfiable, resulting in a satisfiability verification result set. An audit report generation module is used to connect attack chains based on verified reachable attack paths in the satisfiability verification result set and perform full-chain backtracking via the specified anchor ID to generate a traceable audit report.

[0018] The technical effects of this invention are as follows:

[0019] By employing a deterministic pre-scan driven by a security specification attribute library carrying specification anchor IDs, and tracing each hit record back to the corresponding structured attribute entry via the specification anchor ID, the problem of traditional pre-scan results being unable to be traced back to specific security specification entries is solved. This ensures that each finding in the audit report has a complete traceable link from the pre-scan hit to the security specification, significantly improving the interpretability and verifiability of audit conclusions.

[0020] By employing a mechanism that decomposes the attack surface mapping results into four granular levels—file architecture layer, function logic layer, statement data flow layer, and expression computation layer—and configuring dedicated agents at each level, and achieving bidirectional information flow through cross-granularity information transmission channels, the problems of overlapping responsibilities, inference conflicts, and incomplete granularity coverage in multi-agent flat collaboration are solved. This achieves systematic coverage from macro-architectural security to micro-expression computation security, while eliminating redundant inference in the same code region and improving the efficiency of computing resource utilization. Attached Figure Description

[0021] Figure 1 This is a schematic diagram of the overall process of the deterministic code security audit pre-scanning and multi-agent collaborative reasoning method provided in the embodiments of the present invention;

[0022] Figure 2 A schematic diagram illustrating the structured expansion mechanism and pre-scanning execution process of the security specification attribute library provided in this embodiment of the invention;

[0023] Figure 3 This is a schematic diagram of the process for constructing an optimal subset of structured attribute entries based on curvature adaptive greedy selection, provided in an embodiment of the present invention.

[0024] Figure 4 A schematic diagram of the module structure of the deterministic code security audit pre-scanning and multi-agent collaborative reasoning device provided in an embodiment of the present invention. Detailed Implementation

[0025] like Figure 1 As shown, this embodiment covers the overall execution flow of the deterministic code security audit pre-scan and multi-agent collaborative reasoning method.

[0026] S1. Perform a deterministic pre-scan on the target code library based on the security specification attribute library and generate a pre-scan traceable report. Each structured attribute entry in the security specification attribute library carries a specification anchor ID. Each hit record in the pre-scan traceable report is traced back to the corresponding structured attribute entry through the specification anchor ID.

[0027] The security specification attribute library is the core data structure for the deterministic audit coverage of this invention. Its key difference from traditional pure regular expression sets lies in the specification anchor ID (SpecAnchorID) mechanism. Each structured attribute entry uses a globally unique specification anchor ID as its primary key, and also carries the search regular expression pattern, associated CWE number, matching confidence weight, and the security specification category to which it belongs. This elevates the traditional semantically meaningless regular expression matching results to traceable specification hit records.

[0028] Deterministic pre-scanning sequentially applies the search regular expression patterns of each entry in the security specification attribute library to the target codebase, employing a multi-file parallel stream processing strategy to synchronously capture the file path, line number, the specification anchor ID that triggered the match, and the overall confidence score for each matching location. Since each scan record carries a specification anchor ID, a deterministic one-to-one correspondence is established between the scan results and the security specification attribute library, creating a complete traceability chain: "pre-scan hit → structured attribute entry → CWE number → security specification category." This fundamentally eliminates the limitation of traditional pre-scanning in that audit results cannot be traced back to their source, ensuring that each vulnerability indication record can be independently verified.

[0029] Specifically, the SpecAnchorID mechanism introduces a globally integrated chain of semantic identifiers into the code security audit pipeline. This chain connects three previously separate information domains—source code location, security specification attribute library entries, and final audit conclusions—into a directed reference graph that can be independently verified, using unique identifiers. Before the introduction of SpecAnchorID, traditional pre-scanning matching records only carried the information "Rule C was triggered on line B of file A," where "Rule C" was a semantically meaningless regular expression string. Faced with such a matching record, the reviewer could not directly determine from this string: which specific requirement of which security standard was detected, what the corresponding CWE vulnerability category was, the historical false positive rate of the rule, or which standard requirement should be followed for remediation and closure after discovering the vulnerability. This information gap meant that traditional pre-scanning reports could only be used as a "potential problem list" in form, and could not serve as formal audit evidence with security specification support.

[0030] The specification anchor ID severs the root cause of the aforementioned broken chain in terms of information structure. The uniqueness of each specification anchor ID in the security specification attribute library is guaranteed by the globally unique ID generation mechanism during library initialization. Once assigned, the binding relationship between the ID and the corresponding attribute entry cannot be changed. When a pre-scan triggers an attribute entry in the code, the specification anchor ID carried in the matching record becomes a verifiable "compliance pointer"—anyone holding the report can use this ID to retrieve the complete attribute entry content in the security specification attribute library, including the name of the security specification standard to which the entry belongs (such as OWASP Top 10A03, CWE Top 25, etc.), the specific clause description, the associated CWE number, the applicable programming language and framework scope, and historical verification statistics. This design transforms "rule credibility" from tacit knowledge implicit in the rule writer's mind into an explicit data structure that can be independently verified externally.

[0031] In the subsequent attack chain chaining and report generation phases, the traceability of canonical anchor IDs is further extended into a three-in-one structure of "discovery—canonical specification—proof": each step of each attack chain carries a sequence of canonical anchor IDs that triggered the discovery at that step. This allows each vulnerability discovery in the final traceable audit report to be traced back to a specific security specification entry along the canonical anchor ID sequence, accompanied by a reachability proof (satisfaction of assignment) or exclusion proof (unsatisfaction proof) output by the SMT solver. This gives the traceable audit report the formal integrity to serve as a basis for security compliance review, allowing reviewers to independently verify the canonical basis of each discovery without accessing the source code or re-executing the scanning tool.

[0032] Let's illustrate the complete tracing path of a specification anchor ID with a concrete example. Suppose there is an attribute entry in the security specification attribute library with a specification anchor ID of SPEC-PY-089-003. Its search regular expression pattern is: "execute\s*\(\s*[f"'].*%.*[f"']" (matching the pattern of constructing SQL statements using f-strings or percent signs in Python). It is associated with the CWE number CWE-89, belongs to the injection category of security specification, and has a match confidence weight of 0.85. When a pre-scan is executed on a target codebase, this entry is hit in line 143 of api / user_service.py, generating a matching record with the specification anchor ID field value of SPEC-PY-089-003 and a comprehensive confidence score of 0.85 × 0.9 = 0.765. After attack surface mapping, multi-granularity agent analysis, and SMT verification, if this matching record is chained into a verified attack chain, the vulnerability discovery entry in the final audit report will be recorded. The report will clearly list: source code location (api / user_service.py:143), specification anchor ID (SPEC-PY-089-003), associated security specification (CWE-89 / OWASPA03 injection), and SMT (Security Management Technique) assignment evidence (e.g., the path condition set is satisfied when the username parameter contains a string concatenated with single quotes). Security auditors holding this report can directly access the complete entry information in the security specification attribute library using SPEC-PY-089-003, forming a complete and independently verifiable traceability chain from "code line—attribute entry—CWE number—security specification standard," ensuring full interpretability of the audit conclusions.

[0033] In the post-processing stage, duplicates and merges are performed on the matching records in sequence: when the same line of code is matched by multiple attribute entries, the one with the highest overall confidence score is retained, and the remaining entries are recorded as related references; matching records within the same file whose line number difference does not exceed a preset threshold are merged into a unified code block; finally, all merged code blocks are organized into a tree structure according to the three-level hierarchy of file path, line number, and standard anchor ID, generating a structured pre-scan traceable report.

[0034] S2. Based on the pre-scan traceable report, code asset discovery and attack surface mapping are performed, and the obtained attack surface mapping results are associated with the hit records via the standard anchor ID;

[0035] In S2, the pre-scan traceability report output in step S1 is used as the object to extract code blocks marked with high risk. The code assets are identified by combining the project file structure tree of the target code library. The identified asset types include HTTP API route definitions, RPC service endpoints, message queue consumers, file upload and download processing functions, database query entry points, and third-party service call points.

[0036] For each code asset, its input data source, data flow path, and permission check context are traced along the code semantic graph. Based on this, an attack surface feature vector containing three components—external accessibility score, data sensitivity score, and permission boundary offset risk score—is calculated. Finally, using the file path as the primary key, the attack surface feature vector is associated with the hit records in the pre-scan traceability report through specification anchor IDs. This identifies the parts covered by security specifications and the uncovered specification gaps, outputting the attack surface mapping result with pre-scan associations.

[0037] S3. The attack surface mapping result is decomposed into four granularity layers: file architecture layer, function logic layer, statement data flow layer, and expression calculation layer. The agents at each granularity layer reason and save the assertion record table within their respective granularity layer, and then transmit it through the cross-granularity information transmission channel to obtain the collaborative analysis result set.

[0038] This method maps the inherent hierarchical structure of the code into four independent analysis granularities: the file architecture layer focuses on module dependencies and cross-file interface compliance; the function logic layer focuses on control flow integrity and business logic bypass conditions; the statement data flow layer focuses on the complete propagation path of variable taints; and the expression computation layer focuses on integer overflow and bitwise operation safety boundaries. Each granularity's dedicated agent strictly executes its inference loop within its assigned layer, limiting the analysis scope to the allocated code granularity and eliminating redundant cross-layer inference in a flat collaborative model.

[0039] A cross-granularity information transmission channel establishes a two-way information flow: upper-level agents transmit structured fact assertions to lower-level agents as directional inspection prompts, while lower-level agents transmit atomic facts to upper-level agents as constraints. The attack chain construction agent, within this cross-granularity information network, links isolated vulnerability clues at each level into a complete attack chain. Starting from the external input point identified at the file architecture layer, the chain propagates through the function logic layer's bypass path, along the statement data flow layer, and reaches the sensitive operation point at the expression computation layer. Each granularity-level agent must maintain a separate assertion record table during the reasoning process, recording all encountered conditional branch expressions and data flow assertions.

[0040] S4. Select SMT-compatible conditions from the assertion record table of the collaborative analysis result set and convert them into satisfiability constraints. Call the SMT solver to filter out attack paths that are determined to be unsatisfiable, and obtain a satisfiability verification result set.

[0041] From the assertion record table of the collaborative analysis result set, key condition branches affecting the reachability of attack paths are selected. The condition branch expressions on each potential attack path are concatenated into a set of path condition constraints, and these conditions are divided into SMT-reducible conditions and semantically rich conditions. SMT-reducible conditions (mathematical comparison, string matching, Boolean logic combination) are transformed into SMT constraints of the corresponding theoretical domain. The SMT solver is called to verify the comprehensive condition satisfiability of each attack path one by one: when the solver returns satisfiable, the corresponding path is marked as a verified attack path and a satisfiability assignment is given; when it returns unsatisfiable, it is marked as a false alarm and a proof of unsatisfiability is given. Semantically rich conditions (method calls, database query result dependencies, external service status judgments) are marked as requiring manual review and are not included in the SMT solution of this stage, in order to cover the semantic blind spots of the SMT solver.

[0042] Because SMT constraint solving is used to formally verify path reachability, attack paths that are actually unreachable (where the conditional branches on the path are mathematically contradictory and cannot be satisfied simultaneously) are filtered out before entering the audit report, which significantly reduces the false alarm rate and improves the reliability of audit conclusions.

[0043] S5. Based on the verified reachable attack paths in the satisfiability verification result set, connect the attack chains and perform full chain backtracking through the standardized anchor point ID to generate a traceable audit report.

[0044] Only entries marked as verified attack paths in the satisfiability verification result set are retained. The attack chain building agent then performs the final complete attack chain concatenation, starting from the external entry point, passing through verified reachable intermediate paths to reach the final harm point, forming a set of verified attack chains. Each attack chain includes the file location and line number corresponding to each step, the sequence of canonical anchor IDs triggered at each step, and the satisfaction assignment evidence from the SMT solver.

[0045] The verified attack chain set is then used for final anchor point backtracking with the pre-scanning traceable report from step S1. This records the complete security specification attribute entry anchor ID sequence triggered by each attack chain, and includes remediation solutions for similar historical cases retrieved from the historical vulnerability knowledge base, generating a final traceable audit report. Each vulnerability discovery in the report can be traced back to a specific security specification entry along the specification anchor ID, and is accompanied by SMT verification evidence, achieving a three-in-one traceability of "discovery—specification—proof".

[0046] Example 2

[0047] Each structured attribute entry in the security specification attribute library also carries an associated CWE number, a matching confidence weight, and the security specification category to which it belongs. The correspondence between the associated CWE number and the search regular expression pattern in the structured attribute entry is established by statistically analyzing the co-occurrence of CWE tags from historical vulnerability cases and the hit frequency of the search regular expression pattern. The deterministic pre-scanning of the target codebase based on the security specification attribute library includes: using the search regular expression patterns of each structured attribute entry in the security specification attribute library, sequentially performing a regular expression matching scan on the target codebase, and capturing the matching position, the specification anchor ID of the structured attribute entry that triggered the matching, the associated CWE number, and the comprehensive confidence score for each matching record. Figure 2 As shown in the figure, this embodiment demonstrates the structured expansion mechanism of the security specification attribute library and the pre-scan execution process.

[0048] Based on Example 1, this example further clarifies the mechanism for establishing the relationship between the content composition of structured attribute entries and CWE mapping.

[0049] Each structured attribute entry, in addition to the canonical anchor ID and search regular expression pattern, also carries the associated CWE number, matching confidence weight, and the security specification category it belongs to (injection, authentication, encryption, configuration, permission, or data leakage). The associated CWE number is automatically established using a statistical co-occurrence method: the association strength is calculated by using the hit frequency of search regular expression patterns in the CWE tags and corresponding code features of historical vulnerability cases. The strength of the correspondence between the CWE number and the regular expression pattern... It can be represented as:

[0050]

[0051] in Indicates CWE number With search regular expression patterns The statistical co-occurrence association strength, This indicates that historical vulnerability cases simultaneously hit the CWE number. And trigger the search regular expression mode The number of cases Indicates triggering the search regular expression pattern The total number of historical cases. Pairs with association strength exceeding a preset threshold (CWE number, search regular expression pattern) are recorded as formal mapping relationships. After manual calibration by security experts, they are written into attribute entries, giving the search regular expression pattern structured vulnerability semantics.

[0052] During the deterministic pre-scan, for each record that successfully matches a regular expression, four pieces of information are captured simultaneously: the matching location (file path and line number), the canonical anchor ID of the structured attribute entry that triggered the match, the associated CWE number read from the attribute entry, and the overall confidence score. The calculation of the overall confidence score is further clarified in Example 3. The four pieces of information captured here together constitute the complete information set of a single original matching record.

[0053] Example 3

[0054] Based on Example 2, this example further clarifies the calculation mechanism of the comprehensive confidence score and the generation process of the pre-scan traceability report.

[0055] Overall confidence score Matching confidence weights based on attribute entries Match accuracy with the actual match calculate:

[0056]

[0057] in The CWE co-occurrence frequency statistics of historical vulnerability cases are pre-determined and stored in attribute entries. This reflects the precision with which the regular expression match covers the target line of code (e.g., an exact match of the entire line is more valuable than a match of only a part of the substring). The overall confidence score provides a comparable quantitative indicator for multiple hit records of the same line of code.

[0058] The matching precision Prec is quantified and assigned in four levels based on the coverage of the regular expression matching result in the target code line. When the regular expression pattern forms a full-line match with the target code line, that is, when the length of the matched string accounts for more than 90% of the total number of valid characters in the target line after removing leading and trailing whitespace, Prec is assigned a value of 1.0, indicating that the match has strong coverage of the entire line of code and the lowest possibility of false positives; when the matched string covers 50% to 90% of the valid characters in the target line, Prec is assigned a value of 0.8, indicating that the match covers the main logical segment within the line; when the coverage ratio is 20% to 50%, Prec is assigned a value of 0.5, indicating that only a local pattern segment within the line is hit, and further confirmation is required based on the context; when the matched string covers less than 20% of the valid characters (usually seen in coarse-grained matching of a single keyword or operator), Prec is assigned a value of 0.2, and this hit record is downgraded and marked as a low-confidence candidate in the report.

[0059] It should be noted that the four assignment rules are based on the effective character coverage rate, rather than the original byte length, to eliminate the interference of code indentation and whitespace on accuracy judgment. In multi-line macro expansion or string continuation scenarios, if the same logical expression spans multiple physical lines, the coverage rate is calculated using the complete text length of the logical expression involved in the matching as the denominator, avoiding a systematic underestimation of accuracy due to physical line splitting.

[0060] Deduplication is performed based on a comprehensive confidence score: when the same line of code is matched by multiple structured attribute entries, it is retained. The highest-ranking attribute entry is used as the primary hit record for that row, while the remaining attribute entries are used as related references. Their canonical anchor IDs are retained for subsequent tracing, but they are not included in the statistics as independent hits.

[0061] The merging process is based on line number proximity: multiple matching records that belong to the same file after deduplication and whose line number difference does not exceed a preset threshold are merged into a merged code block. This block carries a set of canonical anchor IDs for all matching records within it to support multi-canonical association tracing at the block granularity.

[0062] Finally, all merged code blocks are organized into a three-level tree structure, with file path as the first level, line number range as the second level, and canonical anchor ID as the third level, generating a pre-scan traceable report. In one example, in the `views.py` file of a Python project, there are two matching records in the interval between lines 47 and 52 that trigger CWE-89 (SQL injection) and CWE-22 (path traversal) attribute entries respectively (the line number difference is 5, which does not exceed the preset threshold of 8). These two records are merged into one code block, which is mounted under the `views.py` node in the tree structure, carrying two canonical anchor IDs, providing file-level dual canonical coverage indications for subsequent attack surface mapping.

[0063] Example 4

[0064] Based on Example 1, this example further clarifies the analysis focus of each of the four granularity levels of the intelligent agents, reflecting the core idea of ​​the "function × granularity" two-dimensional division of labor matrix.

[0065] Example 4 specifically includes: the agent in the file architecture layer focuses on module dependencies, cross-file interface compliance, configuration security, and deployment boundaries; the agent in the function logic layer focuses on the integrity of control flow within functions, the completeness of exception handling, the distribution of authentication and authorization checkpoints, and business logic bypass conditions; the agent in the statement data flow layer focuses on the propagation path of variable taints from external input to sensitive convergence points, type security boundaries, and the validity of data verification points; and the agent in the expression computation layer focuses on operator precedence, integer overflow and underflow boundaries, the possibility of division by zero, and bitwise operation safety.

[0066] The agent at the file architecture layer analyzes the codebase from the most macroscopic architectural perspective: its checks include abnormal coupling in the dependency graph between modules, whether cross-file interface exposure complies with the principle of least privilege, the presence of plaintext keys or high-risk configuration items in configuration files, and the integrity of security isolation at deployment boundaries. The analysis conclusions at this layer provide lower-level agents with structural facts on "which modules have interface compliance defects," guiding the function logic layer to focus on verifying authentication checkpoints within the functions of relevant modules.

[0067] The agent in the function logic layer focuses on the integrity of the control flow graph within the function: whether all branch paths are correctly covered, whether try-catch blocks are fully covered, whether there are bypassable conditional paths for authentication and authorization checkpoints, and whether there are unauthorized paths in the business logic due to flawed condition combinations. Atomic discoveries at this layer (e.g., whether an authentication check of a function can be bypassed by a specific parameter combination) are propagated upwards to the file architecture layer as constraints for interface compliance and downwards to the statement data flow layer as the starting point for taint analysis.

[0068] The agent in the statement dataflow layer traces the complete propagation path of taints from external input sources (HTTP request parameters, message queue message bodies, etc.) to sensitive convergence points (SQL execution points, file system operation points, deserialization points, etc.) along the variable assignment chain and function call chain. Simultaneously, it checks for type casting risks at type safety boundaries and the validity of data validation points. Atomic discoveries at this layer (e.g., a variable reaching the SQL execution convergence point without valid validation in the propagation path) are passed up to the function logic layer, providing specific data flow constraints for control flow bypass analysis of that function.

[0069] The agent in the expression computation layer examines the safety boundaries of individual operational expressions at the finest granularity: operator precedence confusion (e.g., the equals sign in `a&b==c` has higher precedence than the bitwise AND operator, leading to semantic misreading), overflow and underflow boundaries in integer arithmetic operations (especially wraparound behavior of unsigned integers), the possibility of division by zero in division expressions, and the risk of negative or out-of-bounds shifts in bitwise operations. Atom discovery at this layer propagates upwards to the statement dataflow layer, providing precise range constraints for dataflow assertions involving the results of the operation.

[0070] Example 5

[0071] Based on Example 4, this example further clarifies the task assignment mechanism and the cross-granularity bidirectional information transmission mechanism.

[0072] The four-granularity hierarchical collaborative reasoning architecture is rooted in the inherent information abstraction hierarchy of the code structure itself, as well as the natural distribution patterns of different types of security vulnerabilities within the code hierarchy. Security risks in the codebase exhibit clear functional differentiation across the four information abstraction levels: security issues at the file architecture level (such as excessive trust dependencies between modules or exposed credentials in configuration files) cannot be detected from a single-file perspective and require cross-file dependency graph analysis; security issues at the function logic level (such as logical bypass paths for authentication checks) require a complete traversal of the control flow graph within the function, but this analysis is too granular from a file architecture perspective and lacks control flow context from a statement data flow perspective; issues at the statement data flow level (such as unvalidated user input propagating to the SQL execution point) require cross-statement variable lifecycle tracing, which at the function logic level can only provide a coarse-grained conclusion that "unvalidated input propagation exists in this function," unable to precisely locate the specific variable assignment chain; and issues at the expression computation level (such as integer overflow) rely on the value range analysis of individual computational expressions, and these fine-grained features are not visible at a more macroscopic level.

[0073] The aforementioned functional differentiation determines the inherent limitations of flat collaboration: if all agents share the same undifferentiated task space, each agent's context window will simultaneously contain file architecture information, function control flow information, variable data flow information, and expression computation information. Agents need to frequently switch their focus between four abstraction levels, which can easily lead to overlooking key security features at a certain level and result in redundant analysis of the same code region among different agents, leading to redundant reasoning. The four-granularity hierarchical architecture orthogonally decomposes the task space according to the information abstraction level, allowing agents at each granular level to focus only on and master the security feature categories of their respective levels. Irrelevant information noise in the context window is structurally eliminated, resulting in a dual improvement in inference accuracy and efficiency.

[0074] The bidirectional cross-granularity information transmission channel follows a directional convention of "downloading structured assertions and uploading atomic facts." Downloaded structured assertions are expressed using a triple format of "scope + security feature category + conclusion marker." For example, an assertion downloaded from a file-level agent to a function-level agent can be expressed as (scope: the verify_token call point in auth / middleware.py; security feature: authentication middleware missing; conclusion: this routing endpoint has no authentication protection at the architectural level). This structured assertion serves as a directional check hint, guiding the function-level agent to focus on checking for authentication condition paths that can be bypassed by specific parameter combinations along the verify_token call path. The uploaded atomic facts are expressed in the triple format of "variable or expression + precise range constraint + location". For example, the atomic facts uploaded by the expression-level agent to the statement-level agent can be expressed as (variable: length; range constraint: when data is external user input and its length exceeds 65535 bytes, length will undergo unsigned integer wrap-around, and the range after overflow is [0, 65535]; location: parser.c:87). This atomic fact refines the range assertion of the statement-level agent when tracking the data stream of the length variable, preventing the statement-level agent from making a misjudgment of data stream safety based on the wrong assumption that "length is a positive integer".

[0075] The execution timing of bidirectional information transmission adopts an asynchronous push strategy of "triggering transmission after the completion of the current round of inference within the hierarchy": After the inference loop of the current iteration is completed, the agent at each granularity level packages the newly generated structural assertions or atomic facts into cross-granularity messages, which are then distributed to the corresponding receivers through the cross-granularity information transmission channel; upon receiving the new message, the receiving agent incorporates it into the context starting point of the next round of inference, without waiting for the full completion of the same round of inference at all granularities before initiating cross-granularity transmission, thus supporting pipelined parallel execution from coarse-grained to fine-grained. After the file-level agent completes the analysis of the first batch of modules, it can send structural assertions to the function-level agent. The function-level agent can start the analysis task of the corresponding function without waiting for the file-level agent to complete its full execution, making full use of multi-core parallel execution capabilities to reduce overall audit latency.

[0076] This embodiment specifically includes:

[0077] S3.1. The main auditing agent assigns the analysis tasks of the file architecture layer, function logic layer, statement data flow layer and expression calculation layer to the file-level agent, function-level agent, statement-level agent and expression-level agent respectively. Each agent executes a reasoning loop within its respective granularity level, including observing code context, inferring security risks, calling static analysis tools and performing the next round of reasoning based on the results returned by the tools.

[0078] The master audit agent receives the attack surface mapping results with pre-scan associations. Based on the code scope involved in each code asset, it breaks down the analysis task into granular levels and assigns it to four dedicated agent instances. Each dedicated agent independently executes an inference loop within its assigned granular level: observes the code context of the current granular level → infers potential security vulnerabilities → calls a static analysis tool suitable for the current granularity (such as dependency analysis tools, control flow graph extraction tools, taint analysis tools, and computational security check tools) → receives the results returned by the tool → performs the next round of inference based on the new information, until the analysis task at that granular level is completed. The inference scope of each agent is strictly limited to its assigned granular level and cross-level analysis is prohibited.

[0079] Agents at each granularity level interact with external static analysis tools through a unified tool invocation adaptation layer. This adaptation layer provides standardized invocation interfaces, converting tool invocation requests from agents into the corresponding tool's input format and returning the tool's output as a structured JSON result object to the invoking agent. Typical tool types and their result object formats configured at each granularity level are as follows:

[0080] The file-level agent calls the dependency graph analysis tool, with the input being the path to the project's build configuration file. The result object contains a list of module nodes and a list of directed dependency edges.

[0081] The function-level agent calls the control flow graph extraction tool, with the source code location of the specified function as input. The result object contains a sequence of basic blocks and a set of directed control flow edges, with each control flow edge carrying edge condition constraint text.

[0082] The statement-level agent invokes the taint analysis tool, with the input being the specified taint source variable name and source code location. The result object contains a list of reachable convergence points of the taint on the function call graph and a sequence of verification checkpoints passed through each convergence point.

[0083] An expression-level agent invokes an operation safety check tool. The input is a specified arithmetic expression and its context, and the result object contains a range of input values ​​that can trigger overflow or underflow.

[0084] The structured result objects returned by the tool are incorporated into the context window of the current granularity level as new observations in the agent's next inference iteration. The inference loop follows the sequence of "observation—inference—invocation—update": after incorporating the tool results, the agent re-infers security vulnerabilities based on the updated context. If the inference generates new tool invocation requirements, the agent continues to invoke the corresponding tool and starts a new iteration; if the inference does not generate new tool invocation requirements and the analysis task at the current granularity level has covered all allocated code assets, the inference loop terminates, and the agent outputs the assertion record table for the current granularity level. The upper limit of tool invocations for each agent is configured by the master audit agent when assigning tasks to prevent the inference loop at a single granularity level from exceeding the overall audit time budget due to repeated tool invocations.

[0085] S3.2. The upper-level agent transmits structural fact assertions along the cross-granularity information transmission channel to the lower-level agent as a directional inspection prompt. The lower-level agent transmits atomic facts to the upper-level agent as constraints. The attack chain construction agent then links isolated vulnerability clues from each granularity level into the attack chain.

[0086] Cross-granularity information transmission channels enable bidirectional information flow.

[0087] Downlink direction: The file-level agent transmits the module interface compliance defect assertions (structural facts) it identifies to the function-level agent as a directional hint for the authentication check integrity analysis of the function; the function-level agent transmits the authentication bypass condition path assertions it identifies to the statement-level agent as a directional starting point for taint analysis.

[0088] Upstream direction: The expression-level agent uploads the identified operation range constraints (atomic facts) to the statement-level agent to refine the data flow assertions in which the operation results participate; the statement-level agent uploads the path assertions from taints to the sink to the function-level agent as constraints for the reachability analysis of the function path.

[0089] Attack chain building agents execute attack chain chaining on cross-granularity information networks: based on the assertion record tables output by agents at each granularity level and cross-granularity transmission information, isolated vulnerability clues are linked into a complete attack chain according to causal relationships.

[0090] The attack chain process is illustrated with an example: A file-level agent discovers that a REST API endpoint is missing an authentication middleware configuration (file architecture layer assertion); after this assertion is passed down, a function-level agent confirms the existence of an bypassable authentication check path in the corresponding processing function of the endpoint (function logic layer assertion); a statement-level agent traces along this bypass path to find that user input parameters are propagated unverified to the database query execution point (statement data flow layer assertion); an expression-level agent discovers a string operation boundary defect in the parameter concatenation at the query execution point (expression computation layer assertion). The attack chain building agent connects the above four layers of assertions into a complete attack chain of "unauthenticated API access → authentication bypass → taint propagation → SQL injection," and attaches the canonical anchor ID sequence of each layer of assertions.

[0091] Example 6

[0092] Based on Example 1, this example further clarifies the recording content of the assertion record table and the screening and classification mechanism of SMT-compatible conditions.

[0093] During the execution of the inference loop, agents at each granularity level record each conditional branch expression and data flow assertion they encounter in real time, forming an assertion record table. The recording scope of conditional branch expressions covers the conditional part of if statements, the case matching condition of switch statements, the persistence condition of while loops, and the judgment part of ternary operators; the recording scope of data flow assertions covers the complete propagation path description of variables from external input sources to the target convergence point.

[0094] Each record in the assertion log table consists of the following fields: assertion unique identifier (a globally unique string used to precisely reference a single assertion in cross-granularity information transmission and SMT constraint construction), agent identifier that generated the assertion (one of file-level, function-level, statement-level, or expression-level), code location (file path and line number range, identifying the source code section corresponding to the assertion), assertion type (either "conditional branch" or "data flow assertion"), expression raw text (the original expression text extracted from the source code, maintaining literal consistency with the source code), and path context (the path of the attack path to which the assertion belongs). The system includes identifiers (all assertions on the same attack path share the same path identifier, supporting fast aggregation of path condition constraint sets), SMT-compatible flags (Boolean type, filled in during the key condition branch filtering stage, indicating whether the condition is an SMT-compatible condition), converted constraint text (string type, for SMT-compatible conditions, it records the constraint text converted to SMT-LIB2 format, and for semantically rich conditions, it fills in the "manual review" flag), and a list of canonical anchor ID associations (records the sequence of canonical anchor IDs of attribute entries that trigger the assertion, supporting backtracking of assertion records to security specifications).

[0095] Specifically, the assertion record table is logically organized using attack path identifiers as group keys. When the satisfiability verification module traverses each attack path group, it takes the conjunction of the transformed constraint text in all records within the group where the assertion type is "conditional branch" and is marked as true by SMT, and directly submits it to the SMT solver for path satisfiability verification without re-parsing the original expression text, thus decoupling the assertion record table from the SMT solver call.

[0096] When filtering key condition branches affecting the reachability of attack paths from the assertion record table, the filtering criterion is "whether the condition branch directly controls whether external input can reach a certain sensitive operation," filtering out business logic branches unrelated to security. For each potential attack path, all the filtered condition branch expressions on that path are sequentially concatenated to form a set of path condition constraints.

[0097] The path condition constraints are categorized into two types based on their formalizability. SMT-formable conditions include: mathematical comparison conditions (e.g., `x>0`, `len(buf)<=MAX_SIZE`), string matching conditions (e.g., `role=="admin"`, `path.startswith(" / api / public")`), and Boolean logic combination conditions (e.g., `isAuthenticated&&hasPermission`). These conditions have clear mathematical semantics and can be directly mapped to the theoretical domain supported by the SMT solver. Semantically rich conditions include: method calls (e.g., `user.hasPermission(resource)`), database query result dependencies (e.g., `db.query(sql).rowCount>0`), and external service status judgments (e.g., `cache.exists(key)`). The satisfiability of these conditions depends on the runtime system state, exceeding the static analysis capabilities of the SMT solver, and are marked as requiring manual review to avoid omissions.

[0098] Example 7

[0099] Based on Example 6, this example further clarifies the transformation rules of satisfiability constraints and the SMT solver calling and result processing mechanism.

[0100] S4.1. Convert the integer comparison condition in the SMT-compatible condition into integer arithmetic theory constraints, the string matching condition into string theory constraints, and the Boolean logic combination condition into propositional logic constraints;

[0101] Integer comparison conditions are mapped to the integer arithmetic theory (QF_LIA or QF_NIA): Linear integer comparisons (such as `index < MAX_SIZE`, `offset + len <= buf_len`) are transformed into QF_LIA constraints, and non-linear integer comparisons with products or powers are transformed into QF_NIA constraints. String matching conditions are mapped to string theory (QF_S) constraints: String equality comparisons (such as `role == "admin"`) are directly transformed into equality constraints, and string prefix / suffix / containment comparisons are transformed into corresponding string theory predicates. Boolean logic combination conditions are mapped to propositional logic constraints, conjunction (`&&`) is mapped to the And operation in SMT, disjunction (`||`) is mapped to the Or operation, and negation (`!`) is mapped to the Not operation.

[0102] For an attack path containing multiple types of SMT-izable conditions, the set of path condition constraints is transformed into the conjunction of the above-mentioned theory domain constraints (the path is reachable if all conditions hold simultaneously), and submitted to an SMT solver that supports hybrid theory solving (such as the Z3 solver).

[0103] S4.2. Call the SMT solver to verify the satisfiability of the comprehensive conditions of each attack path one by one. When the SMT solver returns satisfiable and gives a satisfying assignment, mark the corresponding attack path as a verified attack path. When the SMT solver returns unsatisfiable, mark the corresponding attack path as a false alarm and attach the unsatisfiability proof, and mark the semantically rich conditions as requiring manual review.

[0104] The SMT solver solves the comprehensive constraint formula for each attack path. If the solver returns SAT (satisfiable) and gives a set of variable assignments that make all constraints hold, then this assignment is an example of the actual reachable condition values of the attack path, and the corresponding path is marked as a verified attack path, and the assignment is attached as reachability evidence to the audit report. If the solver returns UNSAT (unsatisfiable), it indicates that there is a logical contradiction in the set of conditional constraints on the path (for example, both `x > 100` and `x < 0` are required on the same path). In actual operation, it is impossible for this path to satisfy all conditions simultaneously, and the corresponding path is marked as a false alarm, and the unsatisfiability proof output by the solver is attached to the report as a filtering basis so that reviewers can independently verify the filtering reason. Semantically rich conditions do not participate in SMT solving and are uniformly marked as requiring manual review to maintain the logical integrity of the SMT verification level (only give clear conclusions for paths that can be confirmed with certainty, and avoid misjudgments due to semantic coverage blind spots).

[0105] The verification of the satisfiability of the SMT path condition is essentially a formal mathematical verification of the conclusions of multi-agent collaborative reasoning, and its mechanism of action can be understood from two dimensions.

[0106] The first dimension is the source of uncertainty in agent reasoning: the agent reasoning process driven by large language models is based on the code text in the context window. When the attack path crosses multiple function call levels, the agent needs to maintain the logical relationships of all path conditions simultaneously within a limited context window. When the number of path conditions exceeds a certain amount or there are interdependent composite constraints (especially the combination of integer operation boundaries and string format constraints), the reliability of the agent's judgment on "whether these conditions can be satisfied simultaneously" decreases significantly. Human experts also find it difficult to accurately determine whether there exists an input assignment that makes all conditions true simultaneously, even when only reading the code text. The SMT solver, through a formal complete search of combined constraints (an exact decision-making process in a finite theoretical domain), fills the systematic weakness of agent reasoning in such judgments, forming a complementary relationship.

[0107] The second dimension is the mechanism of false alarm generation: Multi-granularity agent reasoning uses the probability of vulnerability as a conservative principle, tending to output potential vulnerability assertions for any path with any suspicious conditions. However, the codebase actually contains many paths that appear to have vulnerabilities but are mathematically unreachable. For example, a certain SQL injection path may have two conditions that must be satisfied simultaneously: if(len(input)>0&&len(input)<=5) (requiring an input length between 1 and 5) and if(len(input)>10) (requiring an input length exceeding 10). These two conditions constitute a contradictory set, and no input can satisfy both simultaneously. This path is never reachable during runtime. The SMT solver can give a deterministic conclusion that such mathematically contradictory paths are unsatisfiable and output a proof of unsatisfiability (usually the contradiction kernel, i.e., the smallest subset that causes the constraint set to be unsatisfiable). This proof can be independently verified, providing a logically irrefutable basis for eliminating false alarms.

[0108] The complete working process of SMT filtering is illustrated with a specific numerical example. Suppose that a statement-level agent outputs the following assertion records on an attack path in some Java code: condition branch 1 is age>=18 (adulthood check), condition branch 2 is age<0 (negative value protection logic in a security verification code; the attack path must pass through the "age invalid" branch to reach the privilege bypass point), and condition branch 3 is role.equals("admin") (role matching). The agent marks this path as a potential privilege bypass vulnerability and writes it to the assertion record table. In the SMT satisfiability verification phase, conditional branches 1 and 2 are transformed into integer arithmetic theory constraints age>=18∧age<0. This conjunction is obviously unsatisfiable in the integer theory domain (there is no integer that is simultaneously greater than or equal to 18 and less than 0). The Z3 solver returns UNSAT within milliseconds and outputs the contradiction kernel {age>=18,age<0}. The corresponding attack path is marked as a false alarm and accompanied by proof of unsatisfiability. It is not included in the final audit report, thus avoiding security engineers wasting manual verification resources on a mathematically impossible path.

[0109] It should be noted that SMT constraint solving may encounter situations where it is undecidable or computationally expensive when dealing with paths containing nonlinear integer constraints (QF_NIA). To address this, this invention uniformly marks nonlinear constraints that exceed the solver's capabilities (failure to return a conclusion within the timeout threshold) as requiring manual review rather than mandatory solving. This preserves the complete accuracy of formal verification for tractable constraints while avoiding delays in the overall audit process due to solution timeouts, maintaining an engineering-feasible balance between formal coverage and execution time.

[0110] Example 8

[0111] The code asset discovery and attack surface mapping based on the pre-scan traceable report includes: extracting high-risk marked code blocks from the pre-scan traceable report; identifying code assets by combining the project file structure tree of the target code repository; the code assets include HTTP API route definitions, RPC service endpoints, message queue consumers, file upload and download processing functions, database query entry points, and third-party service call points; tracing the input data source, data flow path, and permission check context for each code asset; and calculating an attack surface feature vector that includes external accessibility scores, data sensitivity scores, and permission boundary offset risk scores; associating the attack surface feature vector with the pre-scan traceable report using file paths as the primary key, and marking the covered parts and the uncovered security specification gaps.

[0112] Based on Example 1, this example further clarifies the specific mechanism for code asset discovery and attack surface feature vector calculation.

[0113] Before the code asset discovery and attack surface mapping steps are executed, a unified code semantic graph is constructed for the target code repository as the basic data structure for subsequent graph tracing analysis. This code semantic graph is constructed by overlaying data flow graphs and call graph edge types on top of an abstract syntax tree, and consists of a set of nodes and a set of directed edges. Node types include four categories: variable nodes (corresponding to the definition point of each named variable in the code, carrying the variable name, type information, and the file and line number), function nodes (corresponding to the definition of each function or method, carrying the function name, parameter list, return type, and the file and line number), data source nodes (corresponding to external input sources such as API request body parsing results, database query return values, and file read results, labeled with their data source category), and convergence point nodes (corresponding to sensitive operations such as SQL statement execution points, command execution points, deserialization points, and file system write points, labeled with their convergence point category).

[0114] The directed edges in the code semantic graph fall into three categories: data flow edges (pointing from the data source node to the variable node using the data, or from the expression node on the right side of an assignment statement to the variable node on the left side, indicating the direction of data flow), control flow edges (representing the execution order between basic blocks within a function, carrying edge condition constraint text), and call edges (pointing from the calling function node to the called function node, indicating the call dependency relationship between functions). After construction, external input source nodes are marked as taint start markers, and sensitive convergence point nodes are marked as taint convergence markers, so that the agent in the statement data flow layer can perform reachability traversal along the data flow edges, accurately tracking the complete path of the taint from the external input through the variable propagation chain to the convergence point, as well as the distribution of permission check function call nodes along the path.

[0115] Merged code blocks with a comprehensive confidence score exceeding the high-risk threshold are extracted from the pre-scan traceability report. Combined with the project file structure tree of the target code repository (generated through AST parsing), six types of code assets are identified based on code characteristics: HTTP API route definitions (REST endpoint decorators or route registration expressions), RPC service endpoints (gRPC / Thrift service interface registration code), message queue consumers (Kafka / RabbitMQConsumer decorators or subscription registration code), file upload and download processing functions (multipart parsing or streaming file read / write entry points), database query entry points (SQL string construction or ORM query call points), and third-party service call points (external HTTP client or SDK call entry points).

[0116] For each identified code asset, its three-dimensional contextual features are traced along the code semantic graph, and an attack surface feature vector is calculated based on this. :

[0117]

[0118] in This represents the external accessibility score, which is assigned based on whether the asset is exposed to unauthenticated interfaces or public endpoints (1.0 for completely public unauthenticated interfaces, 0.6 for authentication but registration, and 0.2 for internal services). The data sensitivity score is assigned based on whether the data processed for the asset contains personal information, credentials, keys, or payment data. This indicates a risk score for permission boundary deviation, assigned based on whether there are potential paths for authentication bypass or vertical / horizontal overreach in the asset processing path.

[0119] Data sensitivity score sens Values ​​are assigned according to the hierarchical rules based on the data categories involved in the code asset data flow path. If the data processed in the data flow path includes credential data such as password hash values, session tokens, private keys, certificates, or API keys, s sens The initial value is 1.0; if it contains user personal identification information (name, ID number, contact information, etc.) or payment-related data (card number, transaction history, etc.), the initial value is 0.8; if it contains internal non-public business data but does not belong to the above-mentioned high-sensitivity categories, the initial value is 0.4; if the data flow path only involves public or non-sensitive data, the initial value is 0.1. When multiple types of sensitive data are processed simultaneously in the data flow path of the same code asset, the highest-level value is taken to reflect the highest-risk data type based on a conservative estimation principle.

[0120] Permission boundary offset risk score s priv The value is assigned based on the analysis results of the completeness of permission checks in the code asset data flow path. If permission checks are completely missing in the data flow path, meaning any external request can directly reach the target operation without any authentication or authorization checks, then... priv Assign a value of 1.0; if there is a permission check but the function logic layer agent finds an authentication condition path that can be bypassed by a specific parameter combination, assign a value of 0.7; if there is a function-level permission check but the object-level permission (horizontal unauthorized protection for specific data resources, such as the scenario where user A accesses user B's private data) is not effectively constrained, assign a value of 0.5; if both function-level and object-level permission checks are fully covered and no bypass path is found in the analysis, assign a value of 0.1.

[0121] It should be noted that s access s sens s privThe three components are assigned values ​​independently and do not interfere with each other. When prioritizing multiple code assets, the three components can be linearly weighted according to their configuration weights (such as 0.4saccess + 0.3ssens + 0.3spriv) to synthesize a comprehensive risk score. The code assets with higher comprehensive risk scores are given priority in allocating multi-granularity intelligent agent deep analysis resources, thereby achieving risk-oriented allocation of audit computing resources.

[0122] Using file path as the primary key, the attack surface feature vectors of each code asset are associated with the hit records of the pre-scan traceable report through the specification anchor ID. Each code asset is labeled with the security specification categories that have been hit by the pre-scan in its file (the covered parts) and the specification categories that should be focused on according to the asset type but were not hit by the pre-scan (the uncovered security specification gaps), which provides targeted priority inspection directions for subsequent multi-granularity intelligent agent analysis.

[0123] Example 9

[0124] Based on Example 1, this example further clarifies the two-way utilization mechanism of the historical vulnerability knowledge base: on the one hand, it is used to retrieve enhanced audit reports, and on the other hand, it is continuously updated through the current audit results.

[0125] Specifically, in this embodiment, based on the code feature similarity of the attack chain, remediation solutions for similar historical vulnerability cases are retrieved from the historical vulnerability knowledge base and attached to the traceable audit report; new vulnerability patterns confirmed in this audit but not covered by the historical vulnerability knowledge base are incrementally written into the historical vulnerability knowledge base.

[0126] Based on the code characteristics of each verified attack chain (the sequence of canonical anchor IDs triggered at each step of the chain, the combination of CWE numbers, and code structure characteristics), a similarity search is performed with historical vulnerability cases stored in the historical vulnerability knowledge base. The similarity calculation comprehensively considers the overlap of the CWE number set and the vector distance of the code structure characteristics. The search results are sorted in descending order of similarity. The remediation solutions for historical cases with similarity exceeding the search threshold are attached to the remediation suggestion section of the corresponding vulnerability discovery in the traceable audit report, providing audit report users with remediation references supported by historical evidence.

[0127] For novel vulnerabilities identified in this audit as verified attack paths through SMT and whose vulnerability pattern characteristics are not covered by existing entries in the historical vulnerability knowledge base (determined by similarity search results being below the entry threshold), their code features, CWE tags, attack chain structures, and SMT-compliant assignment evidence are extracted and incrementally written into the historical vulnerability knowledge base. This continuously expands the vulnerability pattern coverage of the knowledge base, enabling subsequent audit cycles to benefit from the findings of this audit.

[0128] Example 10

[0129] like Figure 3 As shown in the figure, this embodiment describes the complete execution process of constructing an optimal subset of structured attribute entries based on curvature adaptive greedy selection.

[0130] The core invention of this embodiment lies in modeling the selection problem of safety specification attribute items as a problem of maximizing a monotonic submodular function, using the mathematical property of diminishing marginal gain of the submodular function to support the approximate optimality of the greedy algorithm, and using curvature parameters to adaptively tighten the approximation ratio on an instance basis.

[0131] The technical intuition of modeling the selection problem of security specification attribute items as a problem of maximizing a monotonically submodular function can be understood from the following perspective: Items in the security specification attribute library exhibit two key characteristics in terms of vulnerability coverage—coverage benefit (the more items selected, the wider the range of detectable vulnerabilities, and the coverage rate remains monotonically constant) and diminishing marginal coverage (after a certain number of items have been selected, the increase in coverage brought by each additional item is no higher than the increase when adding the same item when only a few items have been selected, because there is an overlap in vulnerability coverage between the newly added item and the already selected items). These two characteristics precisely correspond to the mathematical definition of a monotonically submodular function, and this structural feature of diminishing marginal coverage gain provides a quantifiable theoretical guarantee of near-optimality for greedy algorithms based on "selecting the item with the largest current marginal gain each time," rather than merely a heuristic strategy.

[0132] The curvature parameter α provides additional value for the adaptive tightening of the greedy approximation ratio. The standard greedy algorithm has a general approximation ratio of (1−1 / e)≈0.632 on the monotonic submodular function, indicating that the coverage of the greedy selection result can reach at least 63.2% of the optimal solution. The curvature α characterizes the "severity" of marginal diminishing returns in specific instances—when the vulnerability types covered by different entries are highly complementary and substitutable, the growth curve of the coverage function is closer to linear (smaller α), and the instance-related approximation ratio is improved to 1α(1−e−α), which is far better than the general bound. In the attribute entry set for mainstream full-stack projects (such as web applications that simultaneously include Python backend, JavaScript frontend, and SQL database), SQL injection entries, XSS entries, path traversal entries, etc., cover completely different vulnerability categories and are highly complementary. The curvature is about 0.35 to 0.45, corresponding to an instance-related approximation ratio between 0.80 and 0.85, allowing the greedy method to approach the theoretical optimal solution with extremely high efficiency in such scenarios.

[0133] The following simplified numerical example illustrates the complete execution process of curvature adaptive greedy selection. Assume the security specification attribute library contains six attribute entries, covering three vulnerability types (CWE-89 / SQL injection, CWE-79 / XSS, CWE-22 / path traversal), with severity weights of 0.5, 0.3, and 0.2 respectively. The maximum scan time budget is 10 seconds. The rule families are divided into CWE-89 (entries A, B, F), CWE-79 (entries C, E), and CWE-22 (entry D), with matroid constraints limiting selection to at most one rule from each family. Key parameters for each entry:

[0134] Item A (Python SQL injection detection, correlation score 0.9, coverage coefficient cover[CWE-89]=0.70, time taken 3 seconds).

[0135] Item B (JavaSQL injection detection, correlation 0.2, coverage coefficient cover[CWE-89]=0.65, time taken 3 seconds).

[0136] Item C (JavaScriptXSS detection, relevance 0.85, coverage coefficient cover[CWE-79]=0.80, time taken 2 seconds).

[0137] Item D (Python path traversal detection, relevance 0.9, coverage coefficient cover[CWE-22]=0.75, time taken 2 seconds).

[0138] Item E (PythonXSS template injection detection, relevance 0.75, coverage coefficient cover[CWE-79]=0.60, time taken 3 seconds).

[0139] Item F (PHPSQL injection detection, correlation 0.1, coverage coefficient cover[CWE-89]=0.60, time taken 2 seconds), correlation threshold θ=0.5.

[0140] First iteration: For high-confidence entries (relevance ≥ 0.8), the marginal coverage gain to time ratio is directly calculated using the coverage coefficient. The ratio for entry A is (0.5 × 0.70) / 3 = 0.117, for entry C it is (0.3 × 0.80) / 2 = 0.120, and for entry D it is (0.2 × 0.75) / 2 = 0.075. For low-relevance entries B, E, and F, the utility is estimated using the large language model. Because the relevance is below the confidence threshold of 0.8, the final estimated values, after decay, are all lower than the ratio for entry C. In the first round, entry C with the largest ratio is selected, S1 = {C}, and 2 seconds have elapsed.

[0141] Second iteration (S1={C}, 8 seconds remaining): Item E is excluded due to matroid constraints (CWE-79 family already selected C); the ratio of item A is (0.5×0.70) / 3=0.117, the ratio of item D is (0.2×0.75) / 2=0.075, and the ratio of A is the largest. Item A is selected, S2={C,A}, 5 seconds have been used.

[0142] Third iteration (S2={C,A}, 5 seconds remaining): Item B is excluded due to matroid constraints (CWE-89 family already selected A); Item F, being from the same family, is also excluded; Item D's ratio (0.2×0.75) / 2=0.075, satisfying the remaining budget (2 seconds ≤ 5 seconds). Item D is selected, S3={C,A,D}, 7 seconds have been used.

[0143] Fourth iteration: With 3 seconds remaining, item E has been excluded by matroid constraints, and the remaining candidate items cannot contribute positive increments in the three vulnerability type dimensions (one item has been selected for each of the three rule families). The marginal gain is zero, constraints are saturated, and the iteration terminates. The optimal subset of structured attribute items is {A,C,D}, with a total time of 7 seconds (meeting the 10-second budget). The expected vulnerability discovery coverage f({A,C,D}) = 0.5 × 0.70 + 0.3 × 0.80 + 0.2 × 0.75 = 0.350 + 0.240 + 0.150 = 0.740, compressing the scan time from 15 seconds for all six items to 7 seconds. Furthermore, by excluding low-relevance items B and F (with relevance to the Python target project of only 0.2 and 0.1, respectively, the effective coverage coefficient is decayed to near zero), the waste of ineffective scan time is avoided, fully demonstrating the time-coverage efficiency advantage of curvature adaptive greedy selection in rule item selection.

[0144] S10.1. Parse the metadata of each structured attribute entry, the metadata including the target programming language, target framework, vulnerability category represented by the associated CWE number and the estimated time for a single scan, and divide multiple structured attribute entries that detect the same vulnerability category into the same rule family according to the same associated CWE number.

[0145] Rule family segmentation is achieved by grouping all attribute entries according to their associated CWE numbers: multiple attribute entries that detect the same vulnerability category (same CWE number) but target different programming language variants are grouped into the same rule family. For example, the CWE-89 (SQL injection) rule family contains three attribute entries targeting Python parameterized query missing, Java string concatenation query, and Go formatted string injection respectively. In the same audit task, only the one most suitable for the target codebase's technology stack needs to be selected, thereby eliminating redundant scanning of entries within the same family through matroid constraints.

[0146] S10.2. Based on the file extension distribution, build configuration file and dependency declaration file of the target code library, extract the project technology stack features containing the programming language list, framework list and dependency library list;

[0147] Project technology stack feature extraction integrates three types of information sources:

[0148] File extension distribution (a high percentage of `.py` files indicates that Python is the primary language).

[0149] Build configuration files (`requirements.txt` / `pom.xml` / `go.mod` / `package.json`)

[0150] Dependency declaration file.

[0151] For example, the technology stack feature extraction result of a Django REST Framework project is as follows:

[0152] Programming languages ​​list = [Python],

[0153] Framework list = [Django, djangorestframework],

[0154] Dependency list = [django-rest-framework, PyJWT, sqlalchemy, ...].

[0155] S10.3. Based on the metadata of each structured attribute entry and the project technology stack characteristics, calculate the correlation between each structured attribute entry and the target code library, wherein when the target programming language belongs to the programming language list, a basic correlation score is included; when the target framework belongs to the framework list, a first correlation score is added; and when the vulnerability category matches the known vulnerability type in the dependency library list, a second correlation score is added.

[0156] correlation The calculation formula is:

[0157]

[0158] in For indicator functions, For attribute entries The target programming language For attribute entries The target framework For attribute entries Associate the vulnerability categories represented by CWE. This represents the set of known vulnerability types in the project's dependency library list. The physical meaning of the three scores reflects the levels of matching accuracy: language matching is the basic availability for performing regular expression scanning (contribution 0.6), frame matching determines the targeting of the rules (contribution 0.3), and vulnerability categories that match known dependency risks further increase priority (contribution 0.1).

[0159] S10.4. Based on the coverage coefficient of each vulnerability type, the severity weight of each vulnerability type, and the correlation degree in each structured attribute entry, a coverage function is constructed. The coverage function outputs the expected vulnerability discovery coverage weighted by vulnerability type severity for any subset of structured attribute entries. When the correlation degree is lower than the correlation degree threshold, an attenuation is applied to the corresponding coverage coefficient as the correlation degree decreases.

[0160] Coverage function Defined as:

[0161]

[0162] in This is a set of known vulnerability types (categorized by CWE). Vulnerability type Severity weights (taken from CVSSv3.1 scores normalized to) (interval) The effective coverage coefficient after applying correlation decay:

[0163]

[0164] in For attribute entries Vulnerability types Historical experience coverage coefficient For attribute entries The degree of correlation, This is the relevance threshold. The physical meaning of the relevance decay mechanism is: when the target programming language and framework of an attribute entry do not match the current codebase ( Even if an item has a high coverage coefficient in historical data, its actual coverage effectiveness for the current project is reduced proportionally to the relevance, thus avoiding the inflated coverage rate of low-relevance items.

[0165] The initial value of the coverage coefficient cover(p,v) is determined as follows when the system is first deployed or a new entry is added. For attribute entries that have accumulated enough hit records in historical audit data, the initial value of cover(p,v) is directly estimated by statistically analyzing the actual hit rate of historical hit data, i.e., the true positive hit frequency of the entry for vulnerability type v in historical audits. For new attribute entries with insufficient historical hit data (it is recommended to set it to items that cover the vulnerability type in at least 10 audits), an expert prior assignment strategy is adopted. Security engineers manually assign initial values ​​in the range of [0.1, 0.6] based on the semantic specificity of the regular expression pattern (the more precise the pattern, the higher the initial coverage coefficient; the lower the initial value for coarse-grained keyword matching). This conservative approach avoids consuming valuable time budget quotas for new entries due to excessively high initial values.

[0166] Furthermore, the coverage coefficient cover(p,v) of each attribute entry is maintained independently according to the vulnerability type v. The same attribute entry can have a non-zero coverage coefficient for multiple vulnerability types. The coefficients under each vulnerability type are updated independently, reflecting the differentiated detection capability of the attribute entry under different vulnerability categories. After the exponentially weighted moving average update mechanism described in Example 12 takes effect, the weight of the initial assignment will decrease exponentially with the accumulation of audit cycles. After 10 to 15 audit cycles, the coverage coefficient will be mainly dominated by the actual hit data and will no longer be affected by the initial assignment, completing a smooth transition from the cold start prior value to the actual measured posterior value.

[0167] It is a monotonically non-decreasing modulo function. Monotonicity is obviously true: adding entries does not decrease coverage. The modulo property is guaranteed by the diminishing marginal gain property: for any and ,have:

[0168] because ,gather Contains more Factors (each item) ), the product does not increase; and , Therefore The submodularity is satisfied. Here, Ω represents the complete set of candidate structured attribute entries, A and B represent arbitrary subsets of structured attribute entries in Ω, and x represents any structured attribute entry in Ω that has not yet been selected into B.

[0169] S10.5. Calculate the curvature parameter of the coverage function, and under the constraints of scan time budget and matroid, perform curvature adaptive greedy selection with the criterion of maximizing the ratio of marginal coverage gain to scan time, iteratively select structured attribute entries until constraint saturation, and obtain the optimal subset of structured attribute entries. The matroid constraint limits each rule family to select at most one structured attribute entry.

[0170] curvature parameters Defined as:

[0171]

[0172] It describes the decay rate of the marginal gain: Approaching 0 For functions that approximate linearity, the greedy method approximates the function by approximately 1. As the value approaches 1, the marginal diminishing becomes drastic, and the greedy algorithm's performance degrades to the general limit. In a full-stack scenario (Python + JavaScript + SQL) where the project's technology stack and multiple attribute entries are highly matched, different entries cover different vulnerability areas, have strong substitutability, and exhibit relatively gentle marginal decreases, with a curvature of approximately 0.4. At this point, the instance-related approximation ratio is... Far superior to general-purpose interfaces Where j represents any structured attribute entry in the complete set Ω of candidate structured attribute entries, and f({j}) represents the coverage function value when only entry j is selected. This represents the marginal coverage gain resulting from adding j to the already selected Ω.

[0173] Matroid constraints are formalized as follows: for each family of rules ,Require This means that at most one attribute entry can be selected within the same rule family. This constraint satisfies the three axioms of matroids (independence of the empty set, heritability, and commutativity), ensuring the effectiveness of the greedy algorithm under matroid constraints.

[0174] Curvature adaptive greedy selection in the first In the round of iteration, select the one that makes The largest number of attribute entries that, when added, do not violate the time budget constraint and matroid constraint. ,Will Iterate until constraint saturation. Here, time_cost(p) represents the estimated time for a single scan of structured attribute entry p, p* represents the selected structured attribute entry in this iteration, and S... t This represents the set of structured attribute entries that have been selected after the t-th iteration.

[0175] S10.6. In each iteration of the greedy selection, the marginal coverage gain is directly calculated using the coverage coefficient for structured attribute entries whose relevance is not lower than the relevance confidence threshold. For the remaining structured attribute entries, the utility of the structured attribute entries relative to the target code library is evaluated using a large language model. The evaluation value is modeled as an estimate of superimposed sub-Gaussian noise. The mean of multiple evaluations of the same structured attribute entry within the noise buffer window is taken as the estimate of the marginal coverage gain. The size of the noise buffer window is determined by the variance of the sub-Gaussian noise and the preset error bound.

[0176] After the curvature adaptive greedy selection is completed and the optimal subset of structured attribute entries is determined, subsequent regular expression matching scans are performed only with the search regular expression patterns of each entry in the optimal subset of structured attribute entries as input. Entries in the security specification attribute library that are not selected into the optimal subset of structured attribute entries are skipped in this round of auditing. The optimal subset of structured attribute entries is persistently cached after being determined in the greedy selection stage. In the scan execution stage, the search regular expression patterns are read one by one from this cached subset, and regular expression matching is performed on the target code library sequentially. The capture fields of the matching records (matching position, specification anchor ID, associated CWE number, comprehensive confidence score), the deduplication and merging logic in the post-processing stage, and the tree structure generation mechanism of the pre-scan traceable report are exactly the same as step S1 in Example 1. The only difference is that the set of regular expression patterns actually participating in the scan is narrowed from the entire set of the security specification attribute library to the cardinality range of the optimal subset of structured attribute entries.

[0177] Furthermore, since the optimal structured attribute entry subset is constructed using matroid constraints to ensure that each rule family retains at most one attribute entry that best matches the target codebase's technology stack, the optimal subset scanning, while eliminating redundant scans within the same family, maintains an effective approximation of the expected vulnerability discovery coverage for the entire library scan through curvature adaptive greedy approximation ratio guarantees (the instance-related approximation ratio can reach 0.82). In actual deployment, when the security specification attribute library contains thousands of attribute entries while the cardinality of the optimal structured attribute entry subset is only a few dozen, the total execution time of the regular expression matching scan can be controlled within the preset time budget, making it particularly suitable for incremental auditing scenarios in CI / CD pipelines with strict latency requirements.

[0178] In each round of greedy iteration, the correlation degree is... For high-confidence attribute entries (relatedness confidence threshold), the marginal coverage gain is calculated accurately directly based on the coverage coefficient. For the remaining attribute entries, the large language model is invoked to evaluate their utility relative to the target codebase. The evaluation output of the large language model is... Modeled as real utility superimposed with sub-Gaussian noise:

[0179]

[0180] Where ỹ(p) represents the utility evaluation output of the large language model for the structured attribute item p, y(p) represents the true utility of the structured attribute item p relative to the target codebase, η represents the evaluation noise, and σ² represents the variance of the sub-Gaussian noise.

[0181] Noise buffer window size The determination is based on Hoeffding's inequality:

[0182]

[0183] in The variance is the sub-Gaussian noise (estimated through calibration experiments). To predetermine the error bound, This represents the total number of candidate attribute entries. (In the window...) Perform on the same attribute entry The second largest language model is evaluated and the mean is taken. (Noise standard deviation) (Achievable with high-quality prompt word configuration) When curvature tightening gain (approximately) The percentage point difference is much greater than the noise loss (approximately 3 to 5 percentage points), and the large language model-assisted evaluation has a net positive benefit.

[0184] The variance of the sub-Gaussian noise σ 2 The core idea behind the offline calibration experiment is to collect the deviation distribution between the output of multiple evaluations of the large language model and the actual utility value on a labeled sample set with known true utility values, and then fit sub-Gaussian parameters from this distribution. Specifically, several structured attribute items are extracted from historical audit data as calibration samples. The true utility values ​​of these items (i.e., the actual vulnerability discovery capability score in the corresponding technology stack project) have been labeled by human security experts. Subsequently, under the same large language model configuration (model version, system prompt word template) as the actual deployment, 30 independent large language model evaluations are performed on each labeled item, and the evaluation output sequence is recorded.

[0185] For each calibration sample item p, calculate the sample variance of the difference between its 30 evaluation outputs and the true utility value; take the maximum value of all calibration sample items as a conservative estimate of the global sub-Gaussian noise variance. The reason for using the maximum value estimate is the conservative assumption of the sub-Gaussian parameters: a conservative estimate of the upper bound of noise for the attribute item types most difficult to be stably evaluated by the large language model (usually boundary items where the matching degree between the target technology stack and the current project is ambiguous) ensures that the calculated noise buffer window size is sufficiently large for all items, avoiding the possibility that the mean estimation error of some items exceeds the preset error bound δ due to an excessively small window. It is recommended that the calibration experiment be re-executed after each large language model version upgrade to reflect the changes in evaluation consistency of the new version model on code security evaluation tasks.

[0186] Example 11

[0187] When the audit scenario of the target code library is an incremental audit scenario that only scans changed code blocks, and the cardinality of the optimal subset of structured attribute entries does not exceed the preset cardinality limit, the curvature adaptive greedy selection is a two-stage approximate selection, including: a first stage, performing a standard greedy algorithm on the security specification attribute library to select a number of structured attribute entries equal to half of the preset cardinality limit, thus obtaining a basic entry set; a second stage, performing non-uniform random sampling on the structured attribute entries in the security specification attribute library other than the basic entry set, wherein the probability of each structured attribute entry being sampled increases monotonically with the marginal coverage gain relative to the basic entry set after adjustment by a temperature parameter, and selecting a number of structured attribute entries equal to half of the preset cardinality limit from the sampling distribution without replacement, merging them with the basic entry set to form a candidate entry subset, wherein the temperature parameter decreases when the variance of multiple consecutive rounds of sampling results exceeds the variance limit and increases when the variance of multiple consecutive rounds of sampling results is in the set; the second stage is repeated for a preset number of rounds, and the candidate entry subset with the largest value of the coverage function is taken as the optimal subset of structured attribute entries.

[0188] Based on Example 10, this example further clarifies the two-stage approximate selection algorithm in the incremental audit scenario (CI / CD scenario), which provides an approximate guarantee of 0.385 times the optimal value under cardinality constraints.

[0189] The first phase (construction of the basic item set) applies a greedy algorithm to the security specification attribute library, iteratively selecting attribute items that maximize marginal coverage gain, and selecting a total of... strip( (Based on the preset upper limit of the base number), the basic set of entries is obtained. This stage guarantees a deterministic lower bound on the basic coverage rate, utilizing the inherent advantages of the greedy algorithm on the monotonic modulo function. Basic guarantee.

[0190] The second stage (non-uniform random sampling enhancement) involves processing the remaining candidate entries. Perform non-uniform sampling, attribute entries The probability of being sampled is proportional to ,in This refers to the temperature parameter. The adaptive adjustment rule is as follows: if the variance of three consecutive rounds of sampling results exceeds the upper limit of variance (the difference in the sampling set is too large), it indicates that the current... If the sampling is too low (resulting in overly random sampling), then... Reduce; if the sampling results of three consecutive rounds are highly concentrated (a large number of samples repeatedly selected the same item, indicating...), it means... If the sampling rate is too high (causing it to degenerate into determinism), then... Increase. Draw without replacement from the adjusted sampling distribution. strip, and Merging to form a subset of candidate entries .

[0191] The second phase will be repeated for a preset number of rounds (100 rounds), and the coverage function value will be calculated for the subset of candidate entries obtained in each round. The largest subset of structured attribute entries is selected as the optimal subset. This two-stage algorithm provides... The approximate guarantee (based on multilinear extended rounding analysis) is in In scenarios with small cardinality, compared to the standard greedy algorithm under cardinality constraints... The improvement is approximately 4.9 percentage points, with each point of improvement in approximation ratio having a substantial impact on coverage. The 100 rounds of second-stage sampling support fully parallel execution (each round is independent and has no data dependency), making it suitable for CI / CD multi-core parallel acceleration scenarios.

[0192] Example 12

[0193] Based on Example 10, this example further clarifies the post-scan evaluation and parameter adaptive closed-loop update mechanism, which enables the selection strategy of the security specification attribute library to continuously converge with the cumulative audit cycle.

[0194] For each scanned attribute entry in the optimal structured attribute entry subset, perform multiple post-hoc applicability assessments on the large language model under various context temperatures (e.g., alternating between 0.3, 0.5, and 0.7). The assessment dimensions include: whether the hit code line constitutes a real vulnerability (distinguishing between true positives and false positives), the false positive rate estimate, and the actual matching degree between the attribute entry and the target codebase technology stack.

[0195] To address the non-independence of noise in large language model evaluations (where attribute entries within the same rule family share the same language / framework feature space, leading to systematic correlation in evaluation bias), a grouped median strategy is adopted instead of the simple mean: attribute entries are grouped by rule family, and multiple rounds of large language model evaluation are performed on each attribute entry within a family, with the median being taken. As a noise reduction utility estimate, the median estimate has a much better robustness to bias (breakdown point of 50%) than the mean, and can effectively resist the systematic overestimation or underestimation of family items by large language models.

[0196] Historical correlation coefficient of intra-family assessment bias Affecting the effective independent sample size: ,in The number of times each attribute entry is evaluated. , In the case of The effective sample size can be restored to more than 3 by increasing the number of assessments to 9 to 11, thus ensuring the statistical stability of the median estimate.

[0197] Based on noise reduction effectiveness estimation Update correlation: Use efficient entries to increase relevance. ;right Inefficient items, reduce relevance Based on the actual hit rate data from this scan, the coverage coefficient is updated using an exponentially weighted moving average:

[0198]

[0199] in For learning rate, For the attribute entries in this scan Actual vulnerability types hit The experience hit rate. The updated correlation and coverage coefficients are fed back to the correlation calculation and coverage function construction of the next audit cycle, forming a closed loop of "scanning-evaluation-update-re-scanning". As the number of audit cycles increases, the correlation vector tends to a stable fixed point of the true distribution of the project's technology stack.

[0200] Example 13

[0201] Based on Example 1, this example further clarifies the Bayesian credibility rating mechanism when multiple agents disagree on the same code location, providing a mathematical basis for arbitration of conflict determination.

[0202] For cases where multiple agents output security decisions for the same code location in the collaborative analysis results set, a confusion matrix is ​​constructed for each agent: based on the labeled records confirmed by manual verification or automated availability testing in the agent's historical audits, the counts of true positives (TP), false positives (FP), true negatives (TN), and false negatives (FN) are counted, thereby estimating the true positive rate. With false positive rate .

[0203] The historical effective sample size Neff is directly derived from the sum of the four counts in the confusion matrix, i.e., Neff = TP + FP + TN + FN, representing the total number of code locations in the historical audit records that the agent has been manually verified or automatically tested for usability. The historical effective sample size is a statistical measure of the reliability of the estimated true positive rate and false positive rate: the larger Neff is, the closer the TPR and FPR estimated by frequency counts are to the actual performance indicators of the agent, and the higher the confidence level of the derived Bayesian posterior probability; conversely, when Neff is lower than the preset minimum sample size threshold (e.g., 50 labeled samples), the estimated TPR and FPR have a large risk of random fluctuation, and the estimated values ​​must be smoothed and corrected.

[0204] Specifically, when the historical effective sample size is less than a preset threshold, the point estimates of TPR and FPR are corrected using Laplace smoothing: the corrected true positive rate is estimated as TP + FN + 2TP + 1, and the corrected false positive rate is estimated as FP + TN + 2FP + 1, to avoid degenerate extreme values ​​of 0 or 1 in the case of extremely small samples, ensuring the numerical stability of subsequent Bayesian posterior probability calculations. The historical effective sample size is stored as supplementary metadata for the confidence parameter of each agent, along with TPR and FPR; during multi-agent decision fusion, agents with a historical effective sample size less than the threshold are subject to a strong prior conservative bias, avoiding assigning excessively high decision confidence to the agent in the fusion weight allocation due to scarce historical labeled data, thus ensuring the statistical robustness of the fusion conclusion.

[0205] Bayesian credibility rating is rooted in the individual differences in judgment capabilities among agents at different granularity levels. Because agents at different granularity levels focus on different categories of security features, they accumulate drastically different obfuscation matrix characteristics in historical audits: document-level agents focus on architectural defects, typically having a high true positive rate for "module interface compliance" vulnerabilities, but a high false positive rate for vulnerabilities requiring specific numerical boundaries for confirmation (such as integer overflows) (because the architectural perspective lacks precise numerical constraint information); expression-level agents have a high true positive rate for integer overflows, but a high false positive rate for logical privilege circumvention vulnerabilities (a single expression's perspective cannot perceive the complete authentication bypass path). Simple majority voting cannot distinguish these structural differences, potentially including non-existent vulnerabilities in the report due to "joint voting" by multiple agents with high false positive rates, or missing genuine vulnerabilities due to dilution by a few high-precision agents.

[0206] The posterior probability of an agent identifying a vulnerability is calibrated based on Bayes' theorem.

[0207]

[0208] in Let be the prior probability of an empirical vulnerability (i.e., the historical base probability that a code location in the codebase is actually a vulnerability, which can be estimated from historical audit data). Similarly, the posterior probability when the agent determines that a vulnerability is not a vulnerability is:

[0209]

[0210] The two conditional posterior probabilities constitute the credibility parameters of the agent, quantifying the agent's actual confidence in the current judgment under the constraint of historical performance. This provides a theoretically consistent mathematical basis for the weighted fusion of multi-agent judgment results and avoids the undue trust in agents with high false alarm rates by the simple majority voting method.

[0211] The empirical vulnerability prior probability Pprior represents the basic probability that a code location to be inspected is a real vulnerability when no agent's judgment result is obtained. Its value is estimated by stratifying historical audit data by project category. Specifically, from the historical audit knowledge base, for similar projects with a technology stack (main programming language, framework category) similar to the current target codebase, the proportion of real vulnerability code locations confirmed by manual verification or automated exploitability testing is calculated out of the total number of code locations whose judgment results are output by multiple agents. This proportion is used as the estimated value of Pprior.

[0212] It should be noted that the Pprior estimate should use "code locations marked as suspicious by at least one agent" as the denominator, rather than the total number of lines of code. This is because the semantics of Bayesian updates are based on assessing the true vulnerability probability of a code location given that an agent has already made at least one decision regarding that code location, rather than assessing the base probability of any single line of code being a vulnerability across the entire codebase. If the total number of lines of code in the entire codebase is used as the denominator, the resulting base probability will be extremely low (usually below 0.001), causing the Bayesian posterior probability to be insensitive to the decisions of all agents, and the credibility labeling to lose its discriminative power. The prior probability Pprior calculated with "code locations marked as suspicious by at least one agent" as the denominator is typically in the range of 0.05 to 0.30 (depending on the codebase quality and agent sensitivity configuration). Within this range, agents with different TPRs and FPRs will make substantial differences in their contributions to the posterior probability, allowing the credibility labeling mechanism to effectively leverage the discriminative power of multi-agent decision fusion.

[0213] Example 14

[0214] A deterministic code security audit pre-scanning and multi-agent collaborative reasoning device includes: a pre-scanning module, used to perform a deterministic pre-scan on a target codebase based on a security specification attribute library, and generate a pre-scan traceable report, wherein each structured attribute entry in the security specification attribute library carries a specification anchor ID, and each hit record in the pre-scan traceable report is traced back to the corresponding structured attribute entry via the specification anchor ID; an attack surface mapping module, used to perform code asset discovery and attack surface mapping based on the pre-scan traceable report, and associate the obtained attack surface mapping results with the hit records via the specification anchor ID; and a multi-granularity collaborative analysis module, used to decompose the attack surface mapping results into file racks. The system comprises four granular layers: the structure layer, the function logic layer, the statement data flow layer, and the expression computation layer. Agents at each granularity layer reason within their respective layers and store assertion record tables. These records are then transmitted through cross-granularity information transmission channels to obtain a collaborative analysis result set. A satisfiability verification module filters SMT-based conditions from the assertion record tables in the collaborative analysis result set, converts them into satisfiability constraints, and calls the SMT solver to filter out attack paths deemed unsatisfiable, thus obtaining a satisfiability verification result set. An audit report generation module connects attack chains based on verified reachable attack paths in the satisfiability verification result set and performs full-chain backtracking via the specified anchor ID to generate a traceable audit report. Figure 4 As shown, this embodiment corresponds to the device implementation of the above method.

[0215] The pre-scanning module contains a security specification attribute library management unit and a multi-file parallel scanning execution unit. The former is responsible for storing and retrieving structured attribute entries (including specification anchor ID, search regular expression pattern, associated CWE number, and matching confidence weight), while the latter is responsible for parallel execution of regular expression matching scans and summarizing the original matching record set with specification anchors. The post-processing unit performs deduplication, merging, and tree structure organization, and outputs a pre-scanning traceable report.

[0216] The attack surface mapping module works in collaboration with the code asset identification unit and the attack surface feature vector calculation unit: the code asset identification unit parses the project file structure tree based on AST to identify six types of code asset entry points; the attack surface feature vector calculation unit tracks three-dimensional context features along the code semantic graph and calculates the attack surface feature vector; the anchor point association unit associates the attack surface mapping results with the pre-scan hit records using the file path as the primary key and standardizes the anchor point IDs.

[0217] The multi-granularity collaborative analysis module includes a main audit agent scheduling unit and four granularity-level agent instances (file-level agent, function-level agent, statement-level agent, and expression-level agent) as well as a cross-granularity information transmission channel. Each agent instance independently executes the inference loop and maintains the assertion record table within its respective granularity level. The cross-granularity information transmission channel enables the bidirectional flow of structured fact assertions and atomic facts between upper and lower layers. The attack chain construction agent connects isolated vulnerability clues into a complete attack chain based on cross-granularity information.

[0218] The satisfiability verification module includes a condition classification unit and an SMT constraint transformation unit: the condition classification unit selects key condition branches from the assertion record table and divides them into SMT-encapsulated conditions and semantically rich conditions; the SMT constraint transformation unit transforms the SMT-encapsulated conditions into SMT constraints of the corresponding theoretical domain and calls the SMT solver (such as Z3) to perform path satisfiability verification, marking verified attack paths and false alarms.

[0219] The audit report generation module will use the verified attack chain verified by SMT and the pre-scan traceable report to make a final anchor point backtracking, retrieve the historical vulnerability knowledge base and attach remediation solutions to generate the final traceable audit report, while incrementally writing new vulnerability patterns into the historical vulnerability knowledge base.

Claims

1. A deterministic code security audit pre-scanning and multi-agent collaborative reasoning method, characterized in that, include: A deterministic pre-scan is performed on the target code library based on the security specification attribute library, and a pre-scan traceable report is generated. Each structured attribute entry in the security specification attribute library carries a specification anchor ID. Each hit record in the pre-scan traceable report is traced back to the corresponding structured attribute entry through the specification anchor ID. Based on the pre-scan traceable report, code asset discovery and attack surface mapping are performed, and the obtained attack surface mapping results are associated with the hit records via the standard anchor ID; The attack surface mapping result is decomposed into four granularity layers: file architecture layer, function logic layer, statement data flow layer, and expression calculation layer. Agents at each granularity layer infer and save assertion record tables within their respective granularity layers, and then transmit the results through cross-granularity information transmission channels to obtain a collaborative analysis result set. The SMT-encapsulated conditions are selected from the assertion record table of the collaborative analysis result set and transformed into satisfiability constraints. The SMT solver is then called to filter out attack paths that are determined to be unsatisfiable, and a satisfiability verification result set is obtained. Based on the verified reachable attack paths in the satisfiability verification result set, the attack chain is linked together, and the entire chain is traced back through the standardized anchor point ID to generate a traceable audit report.

2. The method according to claim 1, characterized in that, Each structured attribute entry in the security specification attribute library also carries an associated CWE number, a matching confidence weight, and the security specification category to which it belongs. The correspondence between the associated CWE number and the search regular expression pattern in the structured attribute entry is established by the co-occurrence statistics of the CWE tags of historical vulnerability cases and the hit frequency of the search regular expression pattern. The deterministic pre-scanning of the target code library based on the security specification attribute library includes: Using the search regular expression patterns of each structured attribute entry in the security specification attribute library, the target code library is sequentially scanned using regular expression matching. For each matching record, the matching position, the specification anchor ID of the structured attribute entry that triggered the matching, the associated CWE number, and the comprehensive confidence score are captured.

3. The method according to claim 2, characterized in that, The comprehensive confidence score is calculated based on the pre-defined matching confidence weights and matching accuracy of the structured attribute entries; the generation of the pre-scanned traceable report includes: The captured matching records are deduplicated. When the same line of code is matched by multiple structured attribute entries, the structured attribute entry with the highest comprehensive confidence score is retained. Merge matching records in the same file after deduplication where the line number difference does not exceed a preset threshold to obtain merged code blocks; The merged code blocks are organized into a tree structure according to a three-level hierarchy of file path, line number, and standard anchor ID to generate the pre-scan traceable report.

4. The method according to claim 1, characterized in that, The agents in the file architecture layer focus on module dependencies, cross-file interface compliance, configuration security, and deployment boundaries; the agents in the function logic layer focus on the integrity of control flow within functions, the completeness of exception handling, the distribution of authentication and authorization checkpoints, and business logic bypass conditions; the agents in the statement data flow layer focus on the propagation path of variable taints from external input to sensitive convergence points, type security boundaries, and the validity of data verification points; and the agents in the expression computation layer focus on operator precedence, integer overflow and underflow boundaries, the possibility of division by zero, and bitwise operation safety.

5. The method according to claim 4, characterized in that, The reasoning by agents at each granularity level within their respective granularity levels includes: The main auditing agent assigns the analysis tasks of the file architecture layer, function logic layer, statement data flow layer, and expression calculation layer to the file-level agent, function-level agent, statement-level agent, and expression-level agent, respectively. Each agent executes an inference loop within its respective granularity level, including observing code context, inferring security vulnerabilities, calling static analysis tools, and performing the next round of inference based on the results returned by the tools. The transmission via the cross-granularity information transmission channel includes: The upper-level agent transmits structural fact assertions along the cross-granularity information transmission channel to the lower-level agent as a directional inspection prompt. The lower-level agent transmits atomic facts to the upper-level agent as constraints. The attack chain construction agent then links isolated vulnerability clues from each granularity level into the attack chain.

6. The method according to claim 1, characterized in that, The assertion record table records the conditional branch expressions and data flow assertions encountered by the agents at each granularity level during reasoning. The conditional branch expressions include the conditional parts of if, switch, while, and ternary operators. The step of filtering SMT-compatible conditions from the assertion record table of the collaborative analysis result set includes: The key condition branches affecting the reachability of the attack path are selected from the assertion record table. For each attack path, the condition branch expressions on the attack path are concatenated into a path condition constraint set. The conditions in the path condition constraint set are divided into SMT-enabled conditions and semantically rich conditions. The SMT-enabled conditions include mathematical comparison conditions, string matching conditions, and Boolean logic combination conditions. The semantically rich conditions include method calls, database query result dependencies, and external service status judgments.

7. The method according to claim 6, characterized in that, The process of converting it into a satisfiability constraint and calling the SMT solver includes: The integer comparison condition in the SMT-compatible condition is transformed into integer arithmetic theory constraint, the string matching condition is transformed into string theory constraint, and the Boolean logic combination condition is transformed into propositional logic constraint. The SMT solver is invoked to verify the comprehensive condition satisfiability of each attack path one by one. When the SMT solver returns that the condition is satisfiable and assigns a satisfiability value, the corresponding attack path is marked as a verified attack path. When the SMT solver returns that the condition is not satisfiable, the corresponding attack path is marked as a false alarm and accompanied by proof of non-satisfiability. The semantically rich condition is marked as requiring manual review.

8. The method according to claim 1, characterized in that, The code asset discovery and attack surface mapping based on the pre-scanned traceable report includes: High-risk marked code blocks are extracted from the pre-scan traceable report, and code assets are identified by combining the project file structure tree of the target code library. The code assets include HTTP API route definitions, RPC service endpoints, message queue consumers, file upload and download processing functions, database query entry points, and third-party service call points. For each of the code assets, the source of input data, the data flow path and the permission check context are traced, and an attack surface feature vector including external accessibility score, data sensitivity score and permission boundary offset risk score is calculated; The attack surface feature vector is associated with the pre-scan traceable report using the file path as the primary key, marking the covered parts and the uncovered security specification gaps.

9. The method according to claim 1, characterized in that, The method further includes: Based on the code feature similarity of the attack chain, remediation solutions for similar historical vulnerability cases are retrieved from the historical vulnerability knowledge base and attached to the traceable audit report; New vulnerability patterns identified in this audit that are not covered by the historical vulnerability knowledge base will be incrementally written into the historical vulnerability knowledge base.

10. The method according to claim 2, characterized in that, Before performing regular expression matching scans on the target code library sequentially using the search regular expression patterns of each structured attribute entry in the security specification attribute library, the process further includes: Parse the metadata of each structured attribute entry, the metadata including the target programming language, target framework, vulnerability category represented by the associated CWE number, and estimated single scan time, and divide multiple structured attribute entries that detect the same vulnerability category into the same rule family according to the same associated CWE number; Based on the file extension distribution, build configuration files and dependency declaration files of the target code library, extract the project technology stack features containing a list of programming languages, a list of frameworks and a list of dependency libraries. Based on the metadata of each structured attribute entry and the project technology stack characteristics, the correlation between each structured attribute entry and the target code library is calculated. When the target programming language belongs to the programming language list, a basic correlation score is included; when the target framework belongs to the framework list, a first correlation score is added; and when the vulnerability category matches the known vulnerability type in the dependency library list, a second correlation score is added. Based on the coverage coefficient of each vulnerability type, the severity weight of each vulnerability type, and the correlation degree in each structured attribute entry, a coverage function is constructed. The coverage function outputs the expected vulnerability discovery coverage weighted by vulnerability type severity for any subset of structured attribute entries. When the correlation degree is lower than the correlation degree threshold, the corresponding coverage coefficient is subject to a decay that decreases with the correlation degree. The curvature parameter of the coverage function is calculated, and under the constraints of scan time budget and matroid, the curvature adaptive greedy selection is performed with the criterion of maximizing the ratio of marginal coverage gain to scan time. The structured attribute entries are iteratively selected until the constraints are saturated, and the optimal subset of structured attribute entries is obtained. The matroid constraint limits each rule family to selecting at most one structured attribute entry. In each iteration of the greedy selection, the marginal coverage gain is directly calculated using the coverage coefficient for structured attribute entries whose relevance is not lower than the relevance confidence threshold. For the remaining structured attribute entries, the utility of the structured attribute entries relative to the target code library is evaluated using a large language model. The evaluation value is modeled as an estimate of superimposed sub-Gaussian noise. The mean of multiple evaluations of the same structured attribute entry within the noise buffer window is taken as the estimate of the marginal coverage gain. The size of the noise buffer window is determined by the variance of the sub-Gaussian noise and the preset error bound. The regular expression matching scan is performed on the target code library only using the search regular expression pattern of each structured attribute entry in the optimal subset of structured attribute entries.

11. The method according to claim 10, characterized in that, When the audit scenario for the target codebase is an incremental audit scenario that only scans changed code blocks, and the cardinality of the optimal subset of structured attribute entries does not exceed a preset cardinality upper limit, the curvature adaptive greedy selection is a two-stage approximate selection, including: In the first stage, a standard greedy algorithm is applied to the security specification attribute library to select structured attribute entries with a quantity equal to half of the preset base upper limit, thereby obtaining a basic entry set. In the second stage, non-uniform random sampling is performed on the structured attribute entries outside the basic entry set in the safety specification attribute library. The probability of each structured attribute entry being sampled increases monotonically with the marginal coverage gain relative to the basic entry set after adjustment by the temperature parameter. A number of structured attribute entries equal to half of the preset upper limit are selected from the sampling distribution without replacement and merged with the basic entry set to form a subset of candidate entries. The temperature parameter decreases when the variance of the sampling results exceeds the upper limit of variance in multiple consecutive rounds and increases when the sampling results are in a set in multiple consecutive rounds. The second stage is repeated for a preset number of rounds, and the subset of candidate entries with the largest value of the coverage function is taken as the optimal subset of structured attribute entries.

12. The method according to claim 10, characterized in that, The method further includes: For each structured attribute entry that has been scanned in the optimal subset of structured attribute entries, a large language model is used to perform multiple post-application applicability assessments under multiple different contextual temperatures. The post-application applicability assessment includes whether the hit code line constitutes a real vulnerability, the false positive rate estimation, and the matching degree between the structured attribute entry and the target code library technology stack. The structured attribute entries in the optimal subset of structured attribute entries are grouped according to the rule family. The median of the ex-post applicability assessment is taken as the noise reduction utility estimate for the structured attribute entries within the same rule family. The required number of assessments for the ex-post applicability assessment is adjusted according to the historical correlation coefficient of the assessment bias within the rule family. The correlation degree of each structured attribute entry is updated based on the noise reduction utility estimate. The correlation degree of structured attribute entries whose noise reduction utility estimate is higher than the high utility threshold is increased, and the correlation degree of structured attribute entries whose noise reduction utility estimate is lower than the low utility threshold is decreased. The coverage coefficient is updated using an exponentially weighted moving average based on the actual hit data of this scan. The updated correlation and coverage coefficient are fed back to the correlation calculation and coverage function construction in the next audit cycle, forming a closed loop of scanning, evaluation, updating and re-scanning.

13. The method according to claim 1, characterized in that, The method further includes: For multiple agents that output security judgment results for the same code location in the collaborative analysis result set, collect the binary judgment result and judgment confidence score of each agent for the code location as to whether it is a vulnerability or not. Based on the historical audit annotations of each agent confirmed by manual verification or automated availability testing, a confusion matrix containing the counts of true positives, false positives, true negatives and false negatives is constructed for each agent, and the true positive rate, false positive rate and historical effective sample size of each agent are estimated from the confusion matrix. Based on the true positive rate, the false positive rate, and the prior probability of empirical vulnerabilities, the credibility of each agent's judgment is calibrated using Bayes' theorem, and the conditional posterior probability of the true result when each agent judges a vulnerability or a non-vulnerability is obtained, which constitutes the credibility parameter of each agent.