@code-sentinel-cli/code-sentinel-cli 4.0.3 → 4.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/bin.js +199 -185
  2. package/dist/index.js +199 -185
  3. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -4830,8 +4830,8 @@ function getCrawler(globInput, inputOptions = {}) {
4830
4830
  return patterns.length > 0 ? buildCrawler(options, patterns) : [];
4831
4831
  }
4832
4832
  async function glob(globInput, options) {
4833
- const [crawler, relative9] = getCrawler(globInput, options);
4834
- return crawler ? formatPaths(await crawler.withPromise(), relative9) : [];
4833
+ const [crawler, relative10] = getCrawler(globInput, options);
4834
+ return crawler ? formatPaths(await crawler.withPromise(), relative10) : [];
4835
4835
  }
4836
4836
  var import_picomatch, isReadonlyArray, BACKSLASHES, isWin, ONLY_PARENT_DIRECTORIES, WIN32_ROOT_DIR, isRoot, splitPatternOptions, POSIX_UNESCAPED_GLOB_SYMBOLS, WIN32_UNESCAPED_GLOB_SYMBOLS, escapePosixPath, escapeWin32Path, escapePath, PARENT_DIRECTORY, ESCAPING_BACKSLASHES, defaultOptions;
4837
4837
  var init_dist4 = __esm({
@@ -29863,7 +29863,7 @@ Language guard retry: the previous response contained an empty or English explan
29863
29863
  return { vulnerable: false, reason: `L\u1ED7i th\u1EF1c thi LLM: ${message}` };
29864
29864
  }
29865
29865
  }
29866
- var OLLAMA_DEFAULT_BASE, NETMIND_DEFAULT_BASE, OPENCODE_GO_DEFAULT_BASE, stripTrailingSlash2, buildLanguageModel, resolveModelOverride, pingTarget, shouldUseRawJsonChat, openAICompatibleChatUrl, REASONING_HEADROOM_TOKENS, NETMIND_MINIMAX_M3_MODEL, NETMIND_SMALL_PROMPT_MAX_CHARS, NETMIND_MEDIUM_PROMPT_MAX_CHARS, NETMIND_SMALL_OUTPUT_TOKENS, NETMIND_MEDIUM_OUTPUT_TOKENS, NETMIND_LARGE_OUTPUT_TOKENS, NETMIND_MAX_OUTPUT_TOKENS, supportsNetmindJsonResponseFormat, emptyResponseDiagnostics, effectiveMaxTokensFor, completeRawOpenAICompatibleJsonChat, createAiSdkProvider, createFallbackClient, numberLines, renderPrompt, cache, loadPromptTemplate, nullableOptional, AI_VIOLATION_MESSAGE_MAX_LENGTH, aiViolationSchema, aiResponseSchema, stripCodeFence, parseAiResponse, VIETNAMESE_OUTPUT_POLICY_VERSION, VIETNAMESE_OUTPUT_INSTRUCTION, TOKEN_BUDGET_WARN_DEFAULT, CHARS_PER_TOKEN, SAFETY_MARGIN, estimateTokens, formatTokenWarning, braceDelta, chunkSourceForAi, CACHE_NAMESPACE, DEFAULT_PROVIDER_RETRY_MAX_RETRIES, DEFAULT_PROVIDER_RETRY_MAX_DELAY_MS, DEFAULT_ADAPTIVE_RETRY_MAX_RETRIES, DEFAULT_ADAPTIVE_CONTEXT_REDUCTION_FACTOR, DEFAULT_ADAPTIVE_TIMEOUT_MULTIPLIER, DEFAULT_ADAPTIVE_MAX_DELAY_MS, DEFAULT_PROVIDER_TIMEOUT_MS, sleep, parseRetryDelayMs, providerRetryDelayMs, adaptiveFailureKind, compactClusterContext, findingDedupeKey, dedupeFindings, capFindings, createAiExecutor, PATH_FAST_PATHS, SPRING_BOOT_PATTERNS, ANGULAR_PATTERNS, FLUTTER_PATTERNS, ENTRY_HINTS, ALL_PATTERNS, matchesRule, classifyLayer, classifyLayers, PRIMARY_LAYER_CANDIDATES, TEST_AND_GENERATED, LAYER_SUFFIXES, FILE_SUFFIX_RE, ANY_EXT_RE, dropExt, stripPascalSuffix, normalize3, extractDomainTokens, extractDomainTokensBatch, TRIVIAL_TOKENS, sharesDomainToken, TS_IMPORT_RE, JAVA_IMPORT_RE, extractImports, POSIX_SEP_RE, sharedDirDepth, resolveImportTarget, KIND_STRENGTH, upsertEdge, buildEdges, ADVICE_ANNOTATION, isGlobalAdviceFile, findGlobalAdvicePaths, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_SUPPORT_FILES, DEFAULT_TOKEN_BUDGET, SCORE_DIRECT_NEIGHBOR, SCORE_SECOND_DEGREE, SCORE_SIBLING_STEM, SCORE_ANGULAR_TEMPLATE_SIBLING, SCORE_DOMAIN_TOKEN, PENALTY_TEST_VS_NON_TEST, PENALTY_GENERATED, SCORE_GLOBAL_ADVICE, prefilterCandidates, layerFlowBonus, isTest, isGenerated, scoreFor, tokensOf, trimToBudget, toMember, clusterIdFor, createClusterAssembler, CLUSTER_TREE_BUILDER_VERSION, DEFAULT_MODULE_DEPTH, posixDirname, moduleGroupKey, uniqueSortedPaths, memberFingerprint, featureNodeFor, moduleNodeFor, appNodeFor, countCrossModuleEdges, createClusterTreeBuilder, TRANSACTIONAL, TYPE_DECL3, METHOD_NAME2, MUTATION_CALL, LEADING_ANNOTATION2, SPRING_TX_SUPPORT_IMPORT, PROGRAMMATIC_TYPE, PROGRAMMATIC_CALL, INLINE_TEMPLATE_CALL, CONTROL_FLOW_NAMES, maskNonCode, methodNameFromHeader, methodAt, delegatedTargetAt, collectProgrammaticReceivers, readAttr, skipToDeclaration2, countMutations, lineOf19, configuredReadOnly, extractProgrammaticFromFile, extractFromFile2, extractTransactionBoundaries, renderPrDiffPrompt, nullableOptional2, prDiffResponseSchema, createPrDiffReviewer, renderGroupedRulePrompt, confidenceLabelSchema, severitySchema, groupedResponseSchema, labelToConfidence, createGroupedRuleReviewer, renderPerRulePrompt, createPerRuleReviewer, DEFAULT_MAX_TOKENS, SYSTEM_PROMPT, SCHEMA_PROMPT, clip, buildUserPrompt, extractJsonObject, describeUnusableAnswer, createRuntimeAuthHypothesisResolver, DEFAULT_MAX_TOKENS2, SYSTEM_PROMPT2, SCHEMA_PROMPT2, clip2, buildUserPrompt2, describeUnusableAnswer2, createRuntimeDataSeedResolver, endpointSchema, extractJsonObject2, HTTP_METHODS, PARAMETER_KINDS, ENGLISH_REASON_WORDS, ENGLISH_TECHNICAL_WORDS, VIETNAMESE_DIACRITICS, isLikelyEnglishReason, normalizeTriageReason, parseEndpointHint, TAINT_SINK_CATEGORIES, renderEndpointContext, buildTriageCandidates, runTwoWayAiTriage;
29866
+ var OLLAMA_DEFAULT_BASE, NETMIND_DEFAULT_BASE, OPENCODE_GO_DEFAULT_BASE, stripTrailingSlash2, buildLanguageModel, resolveModelOverride, pingTarget, shouldUseRawJsonChat, openAICompatibleChatUrl, REASONING_HEADROOM_TOKENS, NETMIND_MINIMAX_M3_MODEL, NETMIND_SMALL_PROMPT_MAX_CHARS, NETMIND_MEDIUM_PROMPT_MAX_CHARS, NETMIND_SMALL_OUTPUT_TOKENS, NETMIND_MEDIUM_OUTPUT_TOKENS, NETMIND_LARGE_OUTPUT_TOKENS, NETMIND_MAX_OUTPUT_TOKENS, supportsNetmindJsonResponseFormat, emptyResponseDiagnostics, effectiveMaxTokensFor, completeRawOpenAICompatibleJsonChat, createAiSdkProvider, createFallbackClient, numberLines, renderPrompt, cache, loadPromptTemplate, nullableOptional, AI_VIOLATION_MESSAGE_MAX_LENGTH, aiViolationSchema, aiResponseSchema, stripCodeFence, parseAiResponse, VIETNAMESE_OUTPUT_POLICY_VERSION, VIETNAMESE_OUTPUT_INSTRUCTION, TOKEN_BUDGET_WARN_DEFAULT, CHARS_PER_TOKEN, SAFETY_MARGIN, estimateTokens, formatTokenWarning, braceDelta, chunkSourceForAi, CACHE_NAMESPACE, DEFAULT_PROVIDER_RETRY_MAX_RETRIES, DEFAULT_PROVIDER_RETRY_MAX_DELAY_MS, DEFAULT_ADAPTIVE_RETRY_MAX_RETRIES, DEFAULT_ADAPTIVE_CONTEXT_REDUCTION_FACTOR, DEFAULT_ADAPTIVE_TIMEOUT_MULTIPLIER, DEFAULT_ADAPTIVE_MAX_DELAY_MS, DEFAULT_PROVIDER_TIMEOUT_MS, sleep, parseRetryDelayMs, providerRetryDelayMs, adaptiveFailureKind, compactClusterContext, findingDedupeKey, dedupeFindings, capFindings, createAiExecutor, PATH_FAST_PATHS, SPRING_BOOT_PATTERNS, ANGULAR_PATTERNS, FLUTTER_PATTERNS, ENTRY_HINTS, ALL_PATTERNS, matchesRule, classifyLayer, classifyLayers, PRIMARY_LAYER_CANDIDATES, TEST_AND_GENERATED, LAYER_SUFFIXES, FILE_SUFFIX_RE, ANY_EXT_RE, dropExt, stripPascalSuffix, normalize3, extractDomainTokens, extractDomainTokensBatch, TRIVIAL_TOKENS, sharesDomainToken, TS_IMPORT_RE, JAVA_IMPORT_RE, extractImports, POSIX_SEP_RE, sharedDirDepth, resolveImportTarget, KIND_STRENGTH, upsertEdge, buildEdges, ADVICE_ANNOTATION, isGlobalAdviceFile, findGlobalAdvicePaths, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_SUPPORT_FILES, DEFAULT_TOKEN_BUDGET, SCORE_DIRECT_NEIGHBOR, SCORE_SECOND_DEGREE, SCORE_SIBLING_STEM, SCORE_ANGULAR_TEMPLATE_SIBLING, SCORE_DOMAIN_TOKEN, PENALTY_TEST_VS_NON_TEST, PENALTY_GENERATED, SCORE_GLOBAL_ADVICE, prefilterCandidates, layerFlowBonus, isTest, isGenerated, scoreFor, tokensOf, trimToBudget, toMember, clusterIdFor, createClusterAssembler, CLUSTER_TREE_BUILDER_VERSION, DEFAULT_MODULE_DEPTH, posixDirname, moduleGroupKey, uniqueSortedPaths, memberFingerprint, featureNodeFor, moduleNodeFor, appNodeFor, countCrossModuleEdges, createClusterTreeBuilder, TRANSACTIONAL, TYPE_DECL3, METHOD_NAME2, MUTATION_CALL, LEADING_ANNOTATION2, SPRING_TX_SUPPORT_IMPORT, PROGRAMMATIC_TYPE, PROGRAMMATIC_CALL, INLINE_TEMPLATE_CALL, CONTROL_FLOW_NAMES, maskNonCode, methodNameFromHeader, methodAt, delegatedTargetAt, collectProgrammaticReceivers, readAttr, skipToDeclaration2, countMutations, lineOf19, configuredReadOnly, extractProgrammaticFromFile, extractFromFile2, extractTransactionBoundaries, renderPrDiffPrompt, nullableOptional2, prDiffResponseSchema, createPrDiffReviewer, renderGroupedRulePrompt, confidenceLabelSchema, severitySchema, groupedResponseSchema, labelToConfidence, createGroupedRuleReviewer, renderPerRulePrompt, createPerRuleReviewer, DEFAULT_MAX_TOKENS, SYSTEM_PROMPT, SCHEMA_PROMPT, clip, buildUserPrompt, extractJsonObject, describeUnusableAnswer, createRuntimeAuthHypothesisResolver, DEFAULT_MAX_TOKENS2, SYSTEM_PROMPT2, SCHEMA_PROMPT2, clip2, buildUserPrompt2, describeUnusableAnswer2, createRuntimeDataSeedResolver, endpointSchema, extractJsonObject2, HTTP_METHODS, PARAMETER_KINDS, ENGLISH_REASON_WORDS, ENGLISH_TECHNICAL_WORDS, VIETNAMESE_DIACRITICS, isLikelyEnglishReason, normalizeTriageReason, parseEndpointHint;
29867
29867
  var init_dist6 = __esm({
29868
29868
  "../ai-engine/dist/index.js"() {
29869
29869
  init_dist();
@@ -32947,130 +32947,6 @@ ${buildUserPrompt2(request, options.maxEvidenceChars, logger)}`,
32947
32947
  sinkLine
32948
32948
  };
32949
32949
  };
32950
- TAINT_SINK_CATEGORIES = {
32951
- "spring/jpa-create-query": "sqli",
32952
- "spring/jdbc-template": "sqli",
32953
- "spring/jdbc-raw": "sqli",
32954
- "spring/jdbc-statement-execute": "sqli",
32955
- "spring/runtime-exec": "cmdi",
32956
- "spring/process-builder-command": "cmdi",
32957
- "spring/process-builder-ctor": "cmdi",
32958
- "spring/path-file": "pathtraver",
32959
- "spring/path-resource": "pathtraver",
32960
- "spring/minio-object": "pathtraver",
32961
- "spring/rest-template-ssrf": "ssrf",
32962
- "spring/web-client-ssrf": "ssrf",
32963
- "spring/url-ssrf": "ssrf",
32964
- "spring/okhttp-url": "ssrf",
32965
- "spring/servlet-writer": "xss",
32966
- "spring/servlet-writer-typed": "xss",
32967
- "spring/ldap-search": "ldapi",
32968
- "spring/xpath-eval": "xpathi",
32969
- "spring/trust-boundary": "trustbound",
32970
- "spring/trust-boundary-typed": "trustbound"
32971
- };
32972
- renderEndpointContext = (endpoints) => endpoints.map((endpoint) => {
32973
- const params = endpoint.params.map((param) => `${param.name} (${param.kind})`).join(", ");
32974
- return `- ${endpoint.httpMethod} ${endpoint.path} @line ${endpoint.line}; params: ${params || "none"}`;
32975
- }).join("\n");
32976
- buildTriageCandidates = async (files, twoWay = true) => {
32977
- const analyzer = await createDefaultTaintAnalyzer();
32978
- const taintFindings = files.flatMap((f) => analyzer.analyze(f, { files }));
32979
- const endpoints = extractHttpEndpoints(files);
32980
- const candidatesMap = /* @__PURE__ */ new Map();
32981
- for (const finding of taintFindings) {
32982
- const category = TAINT_SINK_CATEGORIES[finding.sinkId];
32983
- if (category) {
32984
- const fileObj = files.find((f) => f.path === finding.file);
32985
- if (fileObj) {
32986
- const key = `${finding.file}::${category}`;
32987
- if (!candidatesMap.has(key)) {
32988
- candidatesMap.set(key, {
32989
- file: finding.file,
32990
- content: fileObj.content,
32991
- category,
32992
- isFalseNegativeCandidate: false,
32993
- endpointContext: renderEndpointContext(
32994
- endpoints.filter((endpoint) => endpoint.file === finding.file)
32995
- )
32996
- });
32997
- }
32998
- }
32999
- }
33000
- }
33001
- if (twoWay) {
33002
- const endpointFiles = new Set(endpoints.map((e) => e.file));
33003
- const fnCategories = ["sqli", "cmdi", "pathtraver", "ssrf", "xss"];
33004
- for (const epFile of endpointFiles) {
33005
- const fileObj = files.find((f) => f.path === epFile);
33006
- if (fileObj) {
33007
- for (const cat of fnCategories) {
33008
- const key = `${epFile}::${cat}`;
33009
- if (!candidatesMap.has(key)) {
33010
- candidatesMap.set(key, {
33011
- file: epFile,
33012
- content: fileObj.content,
33013
- category: cat,
33014
- isFalseNegativeCandidate: true,
33015
- endpointContext: renderEndpointContext(
33016
- endpoints.filter((endpoint) => endpoint.file === epFile)
33017
- )
33018
- });
33019
- }
33020
- }
33021
- }
33022
- }
33023
- }
33024
- return Array.from(candidatesMap.values());
33025
- };
33026
- runTwoWayAiTriage = async (options) => {
33027
- const candidates = await buildTriageCandidates(options.files, options.twoWay ?? true);
33028
- const results = [];
33029
- let completed = 0;
33030
- let succeeded = 0;
33031
- let failed = 0;
33032
- for (const candidate of candidates) {
33033
- try {
33034
- const triageRes = await evaluateSliceWithAi({
33035
- client: options.client,
33036
- category: candidate.category,
33037
- content: candidate.content,
33038
- endpointContext: candidate.endpointContext,
33039
- ...options.logger ? { logger: options.logger } : {}
33040
- });
33041
- results.push({
33042
- file: candidate.file,
33043
- category: candidate.category,
33044
- vulnerable: triageRes.vulnerable,
33045
- reason: triageRes.reason,
33046
- isFalseNegativeCandidate: candidate.isFalseNegativeCandidate,
33047
- ...triageRes.endpoint !== void 0 ? { endpoint: triageRes.endpoint } : {}
33048
- });
33049
- succeeded++;
33050
- } catch (e) {
33051
- failed++;
33052
- options.logger?.warn(
33053
- `[ai-triage] Failed to evaluate ${candidate.file} for ${candidate.category}: ${e.message}`
33054
- );
33055
- }
33056
- completed++;
33057
- options.onProgress?.(completed, candidates.length);
33058
- }
33059
- const vulnerable = results.filter((r) => r.vulnerable).length;
33060
- return {
33061
- report: {
33062
- version: 1,
33063
- items: results
33064
- },
33065
- stats: {
33066
- totalCandidates: candidates.length,
33067
- evaluated: completed,
33068
- succeeded,
33069
- failed,
33070
- vulnerable
33071
- }
33072
- };
33073
- };
33074
32950
  }
33075
32951
  });
33076
32952
  var escapeInline, escapeInlinePreservingCodeSpans, escapeCodeSpan, escapeTableCell, fenceFor, SEVERITY_DESC, severityLabel, groupBySeverity, groupByField, categoryOf, groupFindings, countBySeverity2, topFiles, topRootCauses, SEVERITY_SYMBOL, formatDuration, renderHeader, ruleRecallRiskSkips, ruleSkipReasons, renderAiStats, renderSummary, renderSnippet, languageHintFromPath, renderFinding, renderGroup, renderFindingsSection, renderFooter, renderReport, createMarkdownReporter, SEVERITY_DESC2, SEVERITY_RANK, SEVERITY_LABEL, pickModal, groupByRule, formatDuration2, renderCompactHeader, renderSeverityTable, renderRulesTable, renderCompactSummary, MAX_INLINE_LOCATIONS, renderRuleSection, renderCompactFindings, renderCompactFooter, renderCompactReport, createMarkdownCompactReporter, JSON_SCHEMA_VERSION, buildRunBlock, buildRangeBlock, buildFindingBlock, projectSkipReasons, buildAiStatsBlock, buildJsonDocument, renderJsonReport, createJsonReporter, SARIF_SCHEMA, SARIF_VERSION, SEVERITY_TO_LEVEL, toFileUri, toArtifactUri, buildRegion, buildResult, buildRules, sarifSkipReasons, buildInvocation, buildSarifReport, renderSarifReport, createSarifReporter, VERDICT_LABEL, noteFor, renderHeader2, renderPolicy, countVerdict, renderOverview, renderChecklistTable, renderEvidence, renderScenario, renderConfirmedDetails, renderControlGaps, renderInconclusiveLeads, renderChecklistCoverage, REASON_HEADING, REASON_NOTE, renderUnassessedGroup, renderUnassessed, renderCoverage, renderFooter2, renderAssessmentReport, renderAssessmentJson, renderVerificationManifest, renderClientVerificationReadme, E1_PROVENANCE_BADGE, VERDICT_BADGE, renderVerificationRunReport, VERDICT_BADGE2, renderClientVerificationRunReport, RUNTIME_BADGE, meaningFor, countSuffix, renderChecklistCorrelation, DB_INVARIANT_CHECKLIST_IDS, schemaInvariantCaveat, CODE_BADGE, DAST_PROVENANCE_BADGE, RUNTIME_BADGE2, runtimeCell, dastFullyUnscanned, dastRuntimeCell, clientRuntimeCell, sastCell, meaningFor2, renderHeader3, renderRuntimeDeviations, renderOverview2, renderCorrelationReport, PLAN_FILE, MANIFEST_FILE, REPORT_FILE, DAST_PROBE_SCRIPT_FILE2, DAST_PROBE_FILE, DAST_API_SEED_SCRIPT_FILE2, renderDastReadme, VERDICT_BADGE3, verdictCell, PROVENANCE_BADGE, COVERAGE_BADGE, hoursOf2, coverageCause, COVERAGE_COUNT, renderDastRunReport, locationOf, renderSastRunReport, UNASSESSED_LABEL, renderUnassessedSection, metaLine, fileNameOf, renderHandoffPacket, renderHandoffManifest;
@@ -47247,10 +47123,11 @@ __export(ai_triage_command_exports, {
47247
47123
  TAINT_SINK_CATEGORIES: () => TAINT_SINK_CATEGORIES,
47248
47124
  runAiTriageCommand: () => runAiTriageCommand
47249
47125
  });
47250
- var JAVA_GLOBS, EXCLUDES, runAiTriageCommand;
47126
+ var JAVA_GLOBS, EXCLUDES, TAINT_SINK_CATEGORIES, renderEndpointContext, runAiTriageCommand;
47251
47127
  var init_ai_triage_command = __esm({
47252
47128
  "src/commands/ai-triage.command.ts"() {
47253
47129
  init_dist6();
47130
+ init_dist5();
47254
47131
  init_dist();
47255
47132
  init_composition();
47256
47133
  init_load();
@@ -47258,8 +47135,35 @@ var init_ai_triage_command = __esm({
47258
47135
  init_find_files();
47259
47136
  JAVA_GLOBS = ["**/*.java"];
47260
47137
  EXCLUDES = ["**/node_modules/**", "**/dist/**", "**/target/**"];
47138
+ TAINT_SINK_CATEGORIES = {
47139
+ "spring/jpa-create-query": "sqli",
47140
+ "spring/jdbc-template": "sqli",
47141
+ "spring/jdbc-raw": "sqli",
47142
+ "spring/jdbc-statement-execute": "sqli",
47143
+ "spring/runtime-exec": "cmdi",
47144
+ "spring/process-builder-command": "cmdi",
47145
+ "spring/process-builder-ctor": "cmdi",
47146
+ "spring/path-file": "pathtraver",
47147
+ "spring/path-resource": "pathtraver",
47148
+ "spring/minio-object": "pathtraver",
47149
+ "spring/rest-template-ssrf": "ssrf",
47150
+ "spring/web-client-ssrf": "ssrf",
47151
+ "spring/url-ssrf": "ssrf",
47152
+ "spring/okhttp-url": "ssrf",
47153
+ "spring/servlet-writer": "xss",
47154
+ "spring/servlet-writer-typed": "xss",
47155
+ "spring/ldap-search": "ldapi",
47156
+ "spring/xpath-eval": "xpathi",
47157
+ "spring/trust-boundary": "trustbound",
47158
+ "spring/trust-boundary-typed": "trustbound"
47159
+ };
47160
+ renderEndpointContext = (endpoints) => endpoints.map((endpoint) => {
47161
+ const params = endpoint.params.map((param) => `${param.name} (${param.kind})`).join(", ");
47162
+ return `- ${endpoint.httpMethod} ${endpoint.path} @line ${endpoint.line}; params: ${params || "none"}`;
47163
+ }).join("\n");
47261
47164
  runAiTriageCommand = async (options) => {
47262
47165
  const source = resolve(process.cwd(), options.source);
47166
+ const reportRoot = resolve(process.cwd(), options.reportRoot ?? source);
47263
47167
  const logger = createLogger({ level: "info", destination: "stderr" });
47264
47168
  const configRes = await loadConfig(
47265
47169
  options.config === void 0 ? { cwd: source } : { cwd: source, configPath: resolve(process.cwd(), options.config) }
@@ -47288,27 +47192,101 @@ var init_ai_triage_command = __esm({
47288
47192
  return EXIT.SUCCESS;
47289
47193
  }
47290
47194
  const files = filesResult.value;
47291
- logger.info("[ai-triage] Running two-way AI triage analysis on Java source files...");
47292
- const result = await runTwoWayAiTriage({
47293
- files,
47294
- client,
47295
- twoWay: options.twoWay ?? true,
47296
- logger,
47297
- onProgress: (completed, total) => {
47298
- if (completed % 5 === 0 || completed === total) {
47299
- logger.info(`[ai-triage] Progress: ${completed}/${total} evaluated.`);
47195
+ const analyzer = await createDefaultTaintAnalyzer();
47196
+ const taintFindings = files.flatMap((f) => analyzer.analyze(f, { files }));
47197
+ const endpoints = extractHttpEndpoints(files);
47198
+ const candidatesMap = /* @__PURE__ */ new Map();
47199
+ for (const finding of taintFindings) {
47200
+ const category = TAINT_SINK_CATEGORIES[finding.sinkId];
47201
+ if (category) {
47202
+ const fileObj = files.find((f) => f.path === finding.file);
47203
+ if (fileObj) {
47204
+ const key = `${finding.file}::${category}`;
47205
+ if (!candidatesMap.has(key)) {
47206
+ candidatesMap.set(key, {
47207
+ file: finding.file,
47208
+ content: fileObj.content,
47209
+ category,
47210
+ isFalseNegativeCandidate: false,
47211
+ endpointContext: renderEndpointContext(
47212
+ endpoints.filter((endpoint) => endpoint.file === finding.file)
47213
+ )
47214
+ });
47215
+ }
47300
47216
  }
47301
47217
  }
47302
- });
47303
- const { report: report2, stats } = result;
47218
+ }
47219
+ if (options.twoWay) {
47220
+ const endpointFiles = new Set(endpoints.map((e) => e.file));
47221
+ const fnCategories = ["sqli", "cmdi", "pathtraver", "ssrf", "xss"];
47222
+ for (const epFile of endpointFiles) {
47223
+ const fileObj = files.find((f) => f.path === epFile);
47224
+ if (fileObj) {
47225
+ for (const cat of fnCategories) {
47226
+ const key = `${epFile}::${cat}`;
47227
+ if (!candidatesMap.has(key)) {
47228
+ candidatesMap.set(key, {
47229
+ file: epFile,
47230
+ content: fileObj.content,
47231
+ category: cat,
47232
+ isFalseNegativeCandidate: true,
47233
+ endpointContext: renderEndpointContext(
47234
+ endpoints.filter((endpoint) => endpoint.file === epFile)
47235
+ )
47236
+ });
47237
+ }
47238
+ }
47239
+ }
47240
+ }
47241
+ }
47242
+ const candidates = Array.from(candidatesMap.values());
47243
+ if (candidates.length === 0) {
47244
+ logger.info("[ai-triage] No candidates found for AI triage.");
47245
+ return EXIT.SUCCESS;
47246
+ }
47247
+ logger.info(`[ai-triage] Starting AI triage on ${candidates.length} candidates...`);
47248
+ const results = [];
47249
+ let completed = 0;
47250
+ for (const candidate of candidates) {
47251
+ try {
47252
+ const triageRes = await evaluateSliceWithAi({
47253
+ client,
47254
+ category: candidate.category,
47255
+ content: candidate.content,
47256
+ endpointContext: candidate.endpointContext,
47257
+ logger
47258
+ });
47259
+ results.push({
47260
+ file: toPosix(relative(reportRoot, resolve(source, candidate.file))),
47261
+ category: candidate.category,
47262
+ vulnerable: triageRes.vulnerable,
47263
+ reason: triageRes.reason,
47264
+ isFalseNegativeCandidate: candidate.isFalseNegativeCandidate,
47265
+ ...triageRes.endpoint !== void 0 ? { endpoint: triageRes.endpoint } : {}
47266
+ });
47267
+ } catch (e) {
47268
+ logger.warn(
47269
+ `[ai-triage] Failed to evaluate ${candidate.file} for ${candidate.category}: ${e.message}`
47270
+ );
47271
+ }
47272
+ completed++;
47273
+ if (completed % 5 === 0 || completed === candidates.length) {
47274
+ logger.info(`[ai-triage] Progress: ${completed}/${candidates.length} evaluated.`);
47275
+ }
47276
+ }
47277
+ const flagged = results.filter((r) => r.vulnerable).length;
47304
47278
  logger.info(
47305
- `[ai-triage] Completed. Found ${stats.vulnerable} vulnerable issues out of ${report2.items.length}.`
47279
+ `[ai-triage] Completed. Found ${flagged} vulnerable issues out of ${results.length}.`
47306
47280
  );
47307
47281
  if (options.emitReport) {
47308
47282
  const outPath = resolve(process.cwd(), options.emitReport);
47309
47283
  mkdirSync(dirname(outPath), { recursive: true });
47310
- await writeFile(outPath, `${JSON.stringify(report2, null, 2)}
47311
- `, "utf8");
47284
+ await writeFile(
47285
+ outPath,
47286
+ `${JSON.stringify({ version: 1, items: results }, null, 2)}
47287
+ `,
47288
+ "utf8"
47289
+ );
47312
47290
  logger.info(`[ai-triage] Wrote AI Triage report to ${outPath}`);
47313
47291
  }
47314
47292
  return EXIT.SUCCESS;
@@ -47324,11 +47302,11 @@ var definedBuildValue = (value, fallback) => typeof value === "string" && value.
47324
47302
  var getCliBuildMetadata = (version2) => ({
47325
47303
  version: version2,
47326
47304
  gitSha: definedBuildValue(
47327
- "964280406a33" ,
47305
+ "e8df2c6d599c" ,
47328
47306
  "unknown"
47329
47307
  ),
47330
47308
  buildTimestamp: definedBuildValue(
47331
- "2026-09-16T02:12:16.866Z" ,
47309
+ "2026-09-16T03:16:43.210Z" ,
47332
47310
  "unknown"
47333
47311
  ),
47334
47312
  configSchemaRange: definedBuildValue(
@@ -48529,7 +48507,7 @@ var projectListSchema = external_exports.object({
48529
48507
  total: external_exports.number().int().nonnegative(),
48530
48508
  limit: external_exports.number().int().positive(),
48531
48509
  offset: external_exports.number().int().nonnegative()
48532
- }).strict();
48510
+ }).passthrough();
48533
48511
  var createProjectRequestSchema = external_exports.object({
48534
48512
  id: projectIdSchema,
48535
48513
  name: external_exports.string().trim().min(1).max(255),
@@ -48575,7 +48553,7 @@ var dashboardRunListSchema = external_exports.object({
48575
48553
  total: external_exports.number().int().nonnegative(),
48576
48554
  limit: external_exports.number().int().positive(),
48577
48555
  offset: external_exports.number().int().nonnegative()
48578
- }).strict();
48556
+ }).passthrough();
48579
48557
  var dashboardRunDetailSchema = external_exports.object({ run: external_exports.unknown() }).strict();
48580
48558
  var repositoryRuleExportSchema = external_exports.object({
48581
48559
  schemaVersion: external_exports.literal(1),
@@ -48684,6 +48662,7 @@ var createCliApiClient = (options) => {
48684
48662
  const controller = new AbortController();
48685
48663
  const timer = setTimeout(() => controller.abort(), timeoutMs);
48686
48664
  const requestId = (options.requestId ?? defaultRequestId)();
48665
+ let payload;
48687
48666
  try {
48688
48667
  const response = await requestWithAuthorization(
48689
48668
  path,
@@ -48693,7 +48672,7 @@ var createCliApiClient = (options) => {
48693
48672
  requestId
48694
48673
  );
48695
48674
  if (!response.ok) throw await asError(response, requestId);
48696
- return parse2(await response.json());
48675
+ payload = await response.json();
48697
48676
  } catch (error) {
48698
48677
  if (error instanceof CliApiClientRequestError) throw error;
48699
48678
  const message = error instanceof Error && error.name === "AbortError" ? "Request timed out." : "Network request failed.";
@@ -48706,6 +48685,18 @@ var createCliApiClient = (options) => {
48706
48685
  } finally {
48707
48686
  clearTimeout(timer);
48708
48687
  }
48688
+ try {
48689
+ return parse2(payload);
48690
+ } catch (error) {
48691
+ if (error instanceof CliApiClientRequestError) throw error;
48692
+ const message = error instanceof Error ? `Invalid response format: ${error.message}` : "Invalid response format.";
48693
+ throw new CliApiClientRequestError({
48694
+ status: 0,
48695
+ requestId,
48696
+ message,
48697
+ retryable: false
48698
+ });
48699
+ }
48709
48700
  };
48710
48701
  const requestText = async (path, init) => {
48711
48702
  const controller = new AbortController();
@@ -55736,11 +55727,11 @@ function createPattern(matcher) {
55736
55727
  if (matcher.path === string)
55737
55728
  return true;
55738
55729
  if (matcher.recursive) {
55739
- const relative9 = sp2.relative(matcher.path, string);
55740
- if (!relative9) {
55730
+ const relative10 = sp2.relative(matcher.path, string);
55731
+ if (!relative10) {
55741
55732
  return false;
55742
55733
  }
55743
- return !relative9.startsWith("..") && !sp2.isAbsolute(relative9);
55734
+ return !relative10.startsWith("..") && !sp2.isAbsolute(relative10);
55744
55735
  }
55745
55736
  return false;
55746
55737
  };
@@ -61816,40 +61807,54 @@ H\xE3y ch\u1EA1y \`cs auth login\`.`
61816
61807
  });
61817
61808
  if (configRes.ok) {
61818
61809
  const payload = await configRes.json();
61819
- const ai = payload.config?.ai ?? payload.ai;
61820
- const provider = ai?.provider;
61821
- const isLocalOnly = provider === "none" || provider === "ollama";
61822
- const aiStr = JSON.stringify(ai ?? {});
61823
- const hasServerSecret = aiStr.includes("<configured server secret>");
61824
- const hasExplicitKey = typeof ai?.apiKey === "string" && ai.apiKey.trim().length > 0 && ai.apiKey.trim() !== "<configured server secret>" && !/^\$\{[^}]+\}$/.test(ai.apiKey.trim());
61825
- if (!provider || isLocalOnly || !hasServerSecret && !hasExplicitKey) {
61826
- const settingsUrl = `${serverUrl.replace(/\/+$/, "")}/runs?project=${encodeURIComponent(link.projectId)}&tab=review-config`;
61827
- console.error(
61828
- red("\n\u274C [Server] D\u1EF1 \xE1n ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5u h\xECnh Project AI Key tr\xEAn Web Dashboard.")
61829
- );
61830
- console.error(
61831
- red(
61832
- `\u{1F449} Vui l\xF2ng m\u1EDF \u0111\u01B0\u1EDDng d\u1EABn sau \u0111\u1EC3 c\u1EA5u h\xECnh nh\xE0 cung c\u1EA5p v\xE0 nh\u1EADp API Key:
61833
- ${settingsUrl}
61810
+ const config2 = payload.config ?? payload;
61811
+ const ai = config2?.ai;
61812
+ const provider = ai?.provider ?? config2?.aiProvider ?? "viettel-netmind";
61813
+ if (provider && provider !== "none" && provider !== "ollama") {
61814
+ const STORED_SECRET_PLACEHOLDER = "${CODE_SENTINEL_STORED_SECRET}";
61815
+ const pKey = provider === "viettel-netmind" ? "viettelNetmind" : provider === "openai-compatible" ? "openaiCompatible" : provider === "opencode-go" ? "opencodeGo" : provider;
61816
+ const providerConf = typeof ai?.[pKey] === "object" && ai?.[pKey] !== null ? ai[pKey] : {};
61817
+ const rawProviderApiKey = typeof providerConf.apiKey === "string" ? providerConf.apiKey.trim() : typeof ai?.apiKey === "string" ? ai.apiKey.trim() : "";
61818
+ const aiStr = JSON.stringify(ai ?? {});
61819
+ const hasServerSecret = aiStr.includes(STORED_SECRET_PLACEHOLDER) || aiStr.includes("<configured server secret>") || rawProviderApiKey === STORED_SECRET_PLACEHOLDER || rawProviderApiKey === "<configured server secret>" || rawProviderApiKey.startsWith("csenc:v1:");
61820
+ const hasExplicitKey = rawProviderApiKey.length > 0 && !hasServerSecret && !/^\$\{[A-Z0-9_]+\}$/.test(rawProviderApiKey);
61821
+ if (!hasServerSecret && !hasExplicitKey) {
61822
+ const drawerUrl = `${serverUrl.replace(/\/+$/, "")}/runs?project=${encodeURIComponent(link.projectId)}&drawer=pentest`;
61823
+ console.error(
61824
+ red("\n\u274C [Server] D\u1EF1 \xE1n ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5u h\xECnh Project AI Key tr\xEAn Web Dashboard.")
61825
+ );
61826
+ console.error(
61827
+ red(
61828
+ `\u{1F449} Vui l\xF2ng m\u1EDF drawer Pentest tr\xEAn Web Dashboard \u0111\u1EC3 nh\u1EADp API Key:
61829
+ ${drawerUrl}
61834
61830
  `
61835
- )
61836
- );
61837
- console.error(
61838
- red(
61839
- "Ghi ch\xFA: L\u1EC7nh `cs pentest` s\u1EED d\u1EE5ng Project AI Key tr\xEAn m\xE1y ch\u1EE7 \u0111\u1EC3 t\u1EF1 \u0111\u1ED9ng th\u1EF1c hi\u1EC7n:\n 1. Ph\xE2n t\xEDch & gi\u1EA3i quy\u1EBFt c\u01A1 ch\u1EBF x\xE1c th\u1EF1c (Auth Hypothesis)\n 2. Two-Way AI Triage (lo\u1EA1i b\u1ECF False Positive, t\xECm False Negative)\n 3. T\u1EA1o d\u1EEF li\u1EC7u m\u1ED3i (Data Seed Hypothesis)\nSau khi l\u01B0u key tr\xEAn Web, h\xE3y ch\u1EA1y l\u1EA1i l\u1EC7nh `cs pentest`.\n"
61840
- )
61841
- );
61842
- return 2;
61831
+ )
61832
+ );
61833
+ console.error(
61834
+ red(
61835
+ `H\u01B0\u1EDBng d\u1EABn thao t\xE1c:
61836
+ 1. M\u1EDF link tr\xEAn (ho\u1EB7c v\xE0o D\u1EF1 \xE1n -> b\u1EA5m n\xFAt "Pentest" \u0111\u1EC3 m\u1EDF drawer "Ki\u1EC3m th\u1EED trong m\xF4i tr\u01B0\u1EDDng c\xF4 l\u1EADp").
61837
+ 2. T\u1EA1i m\u1EE5c "Project AI Key (${provider})", nh\u1EADp API Key v\xE0 nh\u1EA5n "L\u01B0u key cho d\u1EF1 \xE1n".
61838
+ 3. Sau khi l\u01B0u key, ch\u1EA1y l\u1EA1i l\u1EC7nh \`cs pentest\`.
61839
+
61840
+ Ghi ch\xFA: L\u1EC7nh \`cs pentest\` s\u1EED d\u1EE5ng Project AI Key tr\xEAn m\xE1y ch\u1EE7 \u0111\u1EC3 t\u1EF1 \u0111\u1ED9ng th\u1EF1c hi\u1EC7n:
61841
+ - Ph\xE2n t\xEDch & gi\u1EA3i quy\u1EBFt c\u01A1 ch\u1EBF x\xE1c th\u1EF1c (Auth Hypothesis)
61842
+ - Two-Way AI Triage (lo\u1EA1i b\u1ECF False Positive, t\xECm False Negative)
61843
+ - T\u1EA1o d\u1EEF li\u1EC7u m\u1ED3i (Data Seed Hypothesis)
61844
+ `
61845
+ )
61846
+ );
61847
+ return 2;
61848
+ }
61843
61849
  }
61844
61850
  }
61845
- } catch (_e) {
61851
+ } catch {
61846
61852
  }
61847
61853
  }
61848
61854
  let hypothesisTmp;
61849
61855
  let triageTmp;
61850
61856
  if (resolveAuthLocally) {
61851
61857
  hypothesisTmp = join(tmpdir(), `cs-auth-hypothesis-${process.pid}-${Date.now()}.json`);
61852
- triageTmp = join(tmpdir(), `cs-ai-triage-${process.pid}-${Date.now()}.json`);
61853
61858
  await runRuntimeAuthSeed({
61854
61859
  source: join(repoRoot, modulePath),
61855
61860
  useAi: true,
@@ -61857,13 +61862,6 @@ H\xE3y ch\u1EA1y \`cs auth login\`.`
61857
61862
  ...options.refreshHypothesis === true ? { refreshHypothesis: true } : {},
61858
61863
  ...options.config === void 0 ? {} : { config: options.config }
61859
61864
  });
61860
- await runAiTriageCommand({
61861
- source: join(repoRoot, modulePath),
61862
- emitReport: triageTmp,
61863
- twoWay: true,
61864
- // Enable FN hunting on endpoints
61865
- ...options.config === void 0 ? {} : { config: options.config }
61866
- });
61867
61865
  const newEntries = [...plan.entries];
61868
61866
  if (existsSync(hypothesisTmp)) {
61869
61867
  newEntries.push({ name: HYPOTHESIS_ENTRY, absolutePath: hypothesisTmp });
@@ -61872,10 +61870,27 @@ H\xE3y ch\u1EA1y \`cs auth login\`.`
61872
61870
  `cs package: kh\xF4ng gi\u1EA3i \u0111\u01B0\u1EE3c gi\u1EA3 thuy\u1EBFt x\xE1c th\u1EF1c \u2014 ZIP kh\xF4ng mang gi\u1EA3 thuy\u1EBFt, lane runtime s\u1EBD ch\u1EA1y \u0111\u01B0\u1EDDng t\u1EA5t \u0111\u1ECBnh${String.fromCharCode(10)}`
61873
61871
  );
61874
61872
  }
61873
+ planWithAuth = { ...plan, entries: newEntries };
61874
+ }
61875
+ if (options.resolveAuth === true) {
61876
+ triageTmp = join(tmpdir(), `cs-ai-triage-${process.pid}-${Date.now()}.json`);
61877
+ await runAiTriageCommand({
61878
+ source: join(repoRoot, modulePath),
61879
+ reportRoot: repoRoot,
61880
+ emitReport: triageTmp,
61881
+ twoWay: true,
61882
+ ...options.config === void 0 ? {} : { config: options.config }
61883
+ });
61875
61884
  if (existsSync(triageTmp)) {
61876
- newEntries.push({ name: AI_TRIAGE_ENTRY, absolutePath: triageTmp });
61885
+ planWithAuth = {
61886
+ ...planWithAuth,
61887
+ entries: [...planWithAuth.entries, { name: AI_TRIAGE_ENTRY, absolutePath: triageTmp }]
61888
+ };
61889
+ } else {
61890
+ process.stderr.write(
61891
+ "[ai-triage] Kh\xF4ng t\u1EA1o \u0111\u01B0\u1EE3c b\xE1o c\xE1o AI triage; ZIP kh\xF4ng mang k\u1EBFt qu\u1EA3 triage.\n"
61892
+ );
61877
61893
  }
61878
- planWithAuth = { ...plan, entries: newEntries };
61879
61894
  }
61880
61895
  let dataSeedTmp;
61881
61896
  const resolveDataSeedLocally = options.resolveDataSeed === true && !options.push;
@@ -61907,7 +61922,6 @@ H\xE3y ch\u1EA1y \`cs auth login\`.`
61907
61922
  );
61908
61923
  const bytes = writePackageZip(planWithAuth, outPath);
61909
61924
  if (hypothesisTmp !== void 0) rmSync(hypothesisTmp, { force: true });
61910
- if (hypothesisTmp !== void 0) rmSync(hypothesisTmp, { force: true });
61911
61925
  if (triageTmp !== void 0) rmSync(triageTmp, { force: true });
61912
61926
  if (dataSeedTmp !== void 0) rmSync(dataSeedTmp, { force: true });
61913
61927
  process.stdout.write(`Packaged ${plan.modulePath} \u2192 ${outPath} (${formatBytes(bytes)})
package/dist/index.js CHANGED
@@ -4830,8 +4830,8 @@ function getCrawler(globInput, inputOptions = {}) {
4830
4830
  return patterns.length > 0 ? buildCrawler(options, patterns) : [];
4831
4831
  }
4832
4832
  async function glob(globInput, options) {
4833
- const [crawler, relative9] = getCrawler(globInput, options);
4834
- return crawler ? formatPaths(await crawler.withPromise(), relative9) : [];
4833
+ const [crawler, relative10] = getCrawler(globInput, options);
4834
+ return crawler ? formatPaths(await crawler.withPromise(), relative10) : [];
4835
4835
  }
4836
4836
  var import_picomatch, isReadonlyArray, BACKSLASHES, isWin, ONLY_PARENT_DIRECTORIES, WIN32_ROOT_DIR, isRoot, splitPatternOptions, POSIX_UNESCAPED_GLOB_SYMBOLS, WIN32_UNESCAPED_GLOB_SYMBOLS, escapePosixPath, escapeWin32Path, escapePath, PARENT_DIRECTORY, ESCAPING_BACKSLASHES, defaultOptions;
4837
4837
  var init_dist4 = __esm({
@@ -29863,7 +29863,7 @@ Language guard retry: the previous response contained an empty or English explan
29863
29863
  return { vulnerable: false, reason: `L\u1ED7i th\u1EF1c thi LLM: ${message}` };
29864
29864
  }
29865
29865
  }
29866
- var OLLAMA_DEFAULT_BASE, NETMIND_DEFAULT_BASE, OPENCODE_GO_DEFAULT_BASE, stripTrailingSlash2, buildLanguageModel, resolveModelOverride, pingTarget, shouldUseRawJsonChat, openAICompatibleChatUrl, REASONING_HEADROOM_TOKENS, NETMIND_MINIMAX_M3_MODEL, NETMIND_SMALL_PROMPT_MAX_CHARS, NETMIND_MEDIUM_PROMPT_MAX_CHARS, NETMIND_SMALL_OUTPUT_TOKENS, NETMIND_MEDIUM_OUTPUT_TOKENS, NETMIND_LARGE_OUTPUT_TOKENS, NETMIND_MAX_OUTPUT_TOKENS, supportsNetmindJsonResponseFormat, emptyResponseDiagnostics, effectiveMaxTokensFor, completeRawOpenAICompatibleJsonChat, createAiSdkProvider, createFallbackClient, numberLines, renderPrompt, cache, loadPromptTemplate, nullableOptional, AI_VIOLATION_MESSAGE_MAX_LENGTH, aiViolationSchema, aiResponseSchema, stripCodeFence, parseAiResponse, VIETNAMESE_OUTPUT_POLICY_VERSION, VIETNAMESE_OUTPUT_INSTRUCTION, TOKEN_BUDGET_WARN_DEFAULT, CHARS_PER_TOKEN, SAFETY_MARGIN, estimateTokens, formatTokenWarning, braceDelta, chunkSourceForAi, CACHE_NAMESPACE, DEFAULT_PROVIDER_RETRY_MAX_RETRIES, DEFAULT_PROVIDER_RETRY_MAX_DELAY_MS, DEFAULT_ADAPTIVE_RETRY_MAX_RETRIES, DEFAULT_ADAPTIVE_CONTEXT_REDUCTION_FACTOR, DEFAULT_ADAPTIVE_TIMEOUT_MULTIPLIER, DEFAULT_ADAPTIVE_MAX_DELAY_MS, DEFAULT_PROVIDER_TIMEOUT_MS, sleep, parseRetryDelayMs, providerRetryDelayMs, adaptiveFailureKind, compactClusterContext, findingDedupeKey, dedupeFindings, capFindings, createAiExecutor, PATH_FAST_PATHS, SPRING_BOOT_PATTERNS, ANGULAR_PATTERNS, FLUTTER_PATTERNS, ENTRY_HINTS, ALL_PATTERNS, matchesRule, classifyLayer, classifyLayers, PRIMARY_LAYER_CANDIDATES, TEST_AND_GENERATED, LAYER_SUFFIXES, FILE_SUFFIX_RE, ANY_EXT_RE, dropExt, stripPascalSuffix, normalize3, extractDomainTokens, extractDomainTokensBatch, TRIVIAL_TOKENS, sharesDomainToken, TS_IMPORT_RE, JAVA_IMPORT_RE, extractImports, POSIX_SEP_RE, sharedDirDepth, resolveImportTarget, KIND_STRENGTH, upsertEdge, buildEdges, ADVICE_ANNOTATION, isGlobalAdviceFile, findGlobalAdvicePaths, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_SUPPORT_FILES, DEFAULT_TOKEN_BUDGET, SCORE_DIRECT_NEIGHBOR, SCORE_SECOND_DEGREE, SCORE_SIBLING_STEM, SCORE_ANGULAR_TEMPLATE_SIBLING, SCORE_DOMAIN_TOKEN, PENALTY_TEST_VS_NON_TEST, PENALTY_GENERATED, SCORE_GLOBAL_ADVICE, prefilterCandidates, layerFlowBonus, isTest, isGenerated, scoreFor, tokensOf, trimToBudget, toMember, clusterIdFor, createClusterAssembler, CLUSTER_TREE_BUILDER_VERSION, DEFAULT_MODULE_DEPTH, posixDirname, moduleGroupKey, uniqueSortedPaths, memberFingerprint, featureNodeFor, moduleNodeFor, appNodeFor, countCrossModuleEdges, createClusterTreeBuilder, TRANSACTIONAL, TYPE_DECL3, METHOD_NAME2, MUTATION_CALL, LEADING_ANNOTATION2, SPRING_TX_SUPPORT_IMPORT, PROGRAMMATIC_TYPE, PROGRAMMATIC_CALL, INLINE_TEMPLATE_CALL, CONTROL_FLOW_NAMES, maskNonCode, methodNameFromHeader, methodAt, delegatedTargetAt, collectProgrammaticReceivers, readAttr, skipToDeclaration2, countMutations, lineOf19, configuredReadOnly, extractProgrammaticFromFile, extractFromFile2, extractTransactionBoundaries, renderPrDiffPrompt, nullableOptional2, prDiffResponseSchema, createPrDiffReviewer, renderGroupedRulePrompt, confidenceLabelSchema, severitySchema, groupedResponseSchema, labelToConfidence, createGroupedRuleReviewer, renderPerRulePrompt, createPerRuleReviewer, DEFAULT_MAX_TOKENS, SYSTEM_PROMPT, SCHEMA_PROMPT, clip, buildUserPrompt, extractJsonObject, describeUnusableAnswer, createRuntimeAuthHypothesisResolver, DEFAULT_MAX_TOKENS2, SYSTEM_PROMPT2, SCHEMA_PROMPT2, clip2, buildUserPrompt2, describeUnusableAnswer2, createRuntimeDataSeedResolver, endpointSchema, extractJsonObject2, HTTP_METHODS, PARAMETER_KINDS, ENGLISH_REASON_WORDS, ENGLISH_TECHNICAL_WORDS, VIETNAMESE_DIACRITICS, isLikelyEnglishReason, normalizeTriageReason, parseEndpointHint, TAINT_SINK_CATEGORIES, renderEndpointContext, buildTriageCandidates, runTwoWayAiTriage;
29866
+ var OLLAMA_DEFAULT_BASE, NETMIND_DEFAULT_BASE, OPENCODE_GO_DEFAULT_BASE, stripTrailingSlash2, buildLanguageModel, resolveModelOverride, pingTarget, shouldUseRawJsonChat, openAICompatibleChatUrl, REASONING_HEADROOM_TOKENS, NETMIND_MINIMAX_M3_MODEL, NETMIND_SMALL_PROMPT_MAX_CHARS, NETMIND_MEDIUM_PROMPT_MAX_CHARS, NETMIND_SMALL_OUTPUT_TOKENS, NETMIND_MEDIUM_OUTPUT_TOKENS, NETMIND_LARGE_OUTPUT_TOKENS, NETMIND_MAX_OUTPUT_TOKENS, supportsNetmindJsonResponseFormat, emptyResponseDiagnostics, effectiveMaxTokensFor, completeRawOpenAICompatibleJsonChat, createAiSdkProvider, createFallbackClient, numberLines, renderPrompt, cache, loadPromptTemplate, nullableOptional, AI_VIOLATION_MESSAGE_MAX_LENGTH, aiViolationSchema, aiResponseSchema, stripCodeFence, parseAiResponse, VIETNAMESE_OUTPUT_POLICY_VERSION, VIETNAMESE_OUTPUT_INSTRUCTION, TOKEN_BUDGET_WARN_DEFAULT, CHARS_PER_TOKEN, SAFETY_MARGIN, estimateTokens, formatTokenWarning, braceDelta, chunkSourceForAi, CACHE_NAMESPACE, DEFAULT_PROVIDER_RETRY_MAX_RETRIES, DEFAULT_PROVIDER_RETRY_MAX_DELAY_MS, DEFAULT_ADAPTIVE_RETRY_MAX_RETRIES, DEFAULT_ADAPTIVE_CONTEXT_REDUCTION_FACTOR, DEFAULT_ADAPTIVE_TIMEOUT_MULTIPLIER, DEFAULT_ADAPTIVE_MAX_DELAY_MS, DEFAULT_PROVIDER_TIMEOUT_MS, sleep, parseRetryDelayMs, providerRetryDelayMs, adaptiveFailureKind, compactClusterContext, findingDedupeKey, dedupeFindings, capFindings, createAiExecutor, PATH_FAST_PATHS, SPRING_BOOT_PATTERNS, ANGULAR_PATTERNS, FLUTTER_PATTERNS, ENTRY_HINTS, ALL_PATTERNS, matchesRule, classifyLayer, classifyLayers, PRIMARY_LAYER_CANDIDATES, TEST_AND_GENERATED, LAYER_SUFFIXES, FILE_SUFFIX_RE, ANY_EXT_RE, dropExt, stripPascalSuffix, normalize3, extractDomainTokens, extractDomainTokensBatch, TRIVIAL_TOKENS, sharesDomainToken, TS_IMPORT_RE, JAVA_IMPORT_RE, extractImports, POSIX_SEP_RE, sharedDirDepth, resolveImportTarget, KIND_STRENGTH, upsertEdge, buildEdges, ADVICE_ANNOTATION, isGlobalAdviceFile, findGlobalAdvicePaths, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_SUPPORT_FILES, DEFAULT_TOKEN_BUDGET, SCORE_DIRECT_NEIGHBOR, SCORE_SECOND_DEGREE, SCORE_SIBLING_STEM, SCORE_ANGULAR_TEMPLATE_SIBLING, SCORE_DOMAIN_TOKEN, PENALTY_TEST_VS_NON_TEST, PENALTY_GENERATED, SCORE_GLOBAL_ADVICE, prefilterCandidates, layerFlowBonus, isTest, isGenerated, scoreFor, tokensOf, trimToBudget, toMember, clusterIdFor, createClusterAssembler, CLUSTER_TREE_BUILDER_VERSION, DEFAULT_MODULE_DEPTH, posixDirname, moduleGroupKey, uniqueSortedPaths, memberFingerprint, featureNodeFor, moduleNodeFor, appNodeFor, countCrossModuleEdges, createClusterTreeBuilder, TRANSACTIONAL, TYPE_DECL3, METHOD_NAME2, MUTATION_CALL, LEADING_ANNOTATION2, SPRING_TX_SUPPORT_IMPORT, PROGRAMMATIC_TYPE, PROGRAMMATIC_CALL, INLINE_TEMPLATE_CALL, CONTROL_FLOW_NAMES, maskNonCode, methodNameFromHeader, methodAt, delegatedTargetAt, collectProgrammaticReceivers, readAttr, skipToDeclaration2, countMutations, lineOf19, configuredReadOnly, extractProgrammaticFromFile, extractFromFile2, extractTransactionBoundaries, renderPrDiffPrompt, nullableOptional2, prDiffResponseSchema, createPrDiffReviewer, renderGroupedRulePrompt, confidenceLabelSchema, severitySchema, groupedResponseSchema, labelToConfidence, createGroupedRuleReviewer, renderPerRulePrompt, createPerRuleReviewer, DEFAULT_MAX_TOKENS, SYSTEM_PROMPT, SCHEMA_PROMPT, clip, buildUserPrompt, extractJsonObject, describeUnusableAnswer, createRuntimeAuthHypothesisResolver, DEFAULT_MAX_TOKENS2, SYSTEM_PROMPT2, SCHEMA_PROMPT2, clip2, buildUserPrompt2, describeUnusableAnswer2, createRuntimeDataSeedResolver, endpointSchema, extractJsonObject2, HTTP_METHODS, PARAMETER_KINDS, ENGLISH_REASON_WORDS, ENGLISH_TECHNICAL_WORDS, VIETNAMESE_DIACRITICS, isLikelyEnglishReason, normalizeTriageReason, parseEndpointHint;
29867
29867
  var init_dist6 = __esm({
29868
29868
  "../ai-engine/dist/index.js"() {
29869
29869
  init_dist();
@@ -32947,130 +32947,6 @@ ${buildUserPrompt2(request, options.maxEvidenceChars, logger)}`,
32947
32947
  sinkLine
32948
32948
  };
32949
32949
  };
32950
- TAINT_SINK_CATEGORIES = {
32951
- "spring/jpa-create-query": "sqli",
32952
- "spring/jdbc-template": "sqli",
32953
- "spring/jdbc-raw": "sqli",
32954
- "spring/jdbc-statement-execute": "sqli",
32955
- "spring/runtime-exec": "cmdi",
32956
- "spring/process-builder-command": "cmdi",
32957
- "spring/process-builder-ctor": "cmdi",
32958
- "spring/path-file": "pathtraver",
32959
- "spring/path-resource": "pathtraver",
32960
- "spring/minio-object": "pathtraver",
32961
- "spring/rest-template-ssrf": "ssrf",
32962
- "spring/web-client-ssrf": "ssrf",
32963
- "spring/url-ssrf": "ssrf",
32964
- "spring/okhttp-url": "ssrf",
32965
- "spring/servlet-writer": "xss",
32966
- "spring/servlet-writer-typed": "xss",
32967
- "spring/ldap-search": "ldapi",
32968
- "spring/xpath-eval": "xpathi",
32969
- "spring/trust-boundary": "trustbound",
32970
- "spring/trust-boundary-typed": "trustbound"
32971
- };
32972
- renderEndpointContext = (endpoints) => endpoints.map((endpoint) => {
32973
- const params = endpoint.params.map((param) => `${param.name} (${param.kind})`).join(", ");
32974
- return `- ${endpoint.httpMethod} ${endpoint.path} @line ${endpoint.line}; params: ${params || "none"}`;
32975
- }).join("\n");
32976
- buildTriageCandidates = async (files, twoWay = true) => {
32977
- const analyzer = await createDefaultTaintAnalyzer();
32978
- const taintFindings = files.flatMap((f) => analyzer.analyze(f, { files }));
32979
- const endpoints = extractHttpEndpoints(files);
32980
- const candidatesMap = /* @__PURE__ */ new Map();
32981
- for (const finding of taintFindings) {
32982
- const category = TAINT_SINK_CATEGORIES[finding.sinkId];
32983
- if (category) {
32984
- const fileObj = files.find((f) => f.path === finding.file);
32985
- if (fileObj) {
32986
- const key = `${finding.file}::${category}`;
32987
- if (!candidatesMap.has(key)) {
32988
- candidatesMap.set(key, {
32989
- file: finding.file,
32990
- content: fileObj.content,
32991
- category,
32992
- isFalseNegativeCandidate: false,
32993
- endpointContext: renderEndpointContext(
32994
- endpoints.filter((endpoint) => endpoint.file === finding.file)
32995
- )
32996
- });
32997
- }
32998
- }
32999
- }
33000
- }
33001
- if (twoWay) {
33002
- const endpointFiles = new Set(endpoints.map((e) => e.file));
33003
- const fnCategories = ["sqli", "cmdi", "pathtraver", "ssrf", "xss"];
33004
- for (const epFile of endpointFiles) {
33005
- const fileObj = files.find((f) => f.path === epFile);
33006
- if (fileObj) {
33007
- for (const cat of fnCategories) {
33008
- const key = `${epFile}::${cat}`;
33009
- if (!candidatesMap.has(key)) {
33010
- candidatesMap.set(key, {
33011
- file: epFile,
33012
- content: fileObj.content,
33013
- category: cat,
33014
- isFalseNegativeCandidate: true,
33015
- endpointContext: renderEndpointContext(
33016
- endpoints.filter((endpoint) => endpoint.file === epFile)
33017
- )
33018
- });
33019
- }
33020
- }
33021
- }
33022
- }
33023
- }
33024
- return Array.from(candidatesMap.values());
33025
- };
33026
- runTwoWayAiTriage = async (options) => {
33027
- const candidates = await buildTriageCandidates(options.files, options.twoWay ?? true);
33028
- const results = [];
33029
- let completed = 0;
33030
- let succeeded = 0;
33031
- let failed = 0;
33032
- for (const candidate of candidates) {
33033
- try {
33034
- const triageRes = await evaluateSliceWithAi({
33035
- client: options.client,
33036
- category: candidate.category,
33037
- content: candidate.content,
33038
- endpointContext: candidate.endpointContext,
33039
- ...options.logger ? { logger: options.logger } : {}
33040
- });
33041
- results.push({
33042
- file: candidate.file,
33043
- category: candidate.category,
33044
- vulnerable: triageRes.vulnerable,
33045
- reason: triageRes.reason,
33046
- isFalseNegativeCandidate: candidate.isFalseNegativeCandidate,
33047
- ...triageRes.endpoint !== void 0 ? { endpoint: triageRes.endpoint } : {}
33048
- });
33049
- succeeded++;
33050
- } catch (e) {
33051
- failed++;
33052
- options.logger?.warn(
33053
- `[ai-triage] Failed to evaluate ${candidate.file} for ${candidate.category}: ${e.message}`
33054
- );
33055
- }
33056
- completed++;
33057
- options.onProgress?.(completed, candidates.length);
33058
- }
33059
- const vulnerable = results.filter((r) => r.vulnerable).length;
33060
- return {
33061
- report: {
33062
- version: 1,
33063
- items: results
33064
- },
33065
- stats: {
33066
- totalCandidates: candidates.length,
33067
- evaluated: completed,
33068
- succeeded,
33069
- failed,
33070
- vulnerable
33071
- }
33072
- };
33073
- };
33074
32950
  }
33075
32951
  });
33076
32952
  var escapeInline, escapeInlinePreservingCodeSpans, escapeCodeSpan, escapeTableCell, fenceFor, SEVERITY_DESC, severityLabel, groupBySeverity, groupByField, categoryOf, groupFindings, countBySeverity2, topFiles, topRootCauses, SEVERITY_SYMBOL, formatDuration, renderHeader, ruleRecallRiskSkips, ruleSkipReasons, renderAiStats, renderSummary, renderSnippet, languageHintFromPath, renderFinding, renderGroup, renderFindingsSection, renderFooter, renderReport, createMarkdownReporter, SEVERITY_DESC2, SEVERITY_RANK, SEVERITY_LABEL, pickModal, groupByRule, formatDuration2, renderCompactHeader, renderSeverityTable, renderRulesTable, renderCompactSummary, MAX_INLINE_LOCATIONS, renderRuleSection, renderCompactFindings, renderCompactFooter, renderCompactReport, createMarkdownCompactReporter, JSON_SCHEMA_VERSION, buildRunBlock, buildRangeBlock, buildFindingBlock, projectSkipReasons, buildAiStatsBlock, buildJsonDocument, renderJsonReport, createJsonReporter, SARIF_SCHEMA, SARIF_VERSION, SEVERITY_TO_LEVEL, toFileUri, toArtifactUri, buildRegion, buildResult, buildRules, sarifSkipReasons, buildInvocation, buildSarifReport, renderSarifReport, createSarifReporter, VERDICT_LABEL, noteFor, renderHeader2, renderPolicy, countVerdict, renderOverview, renderChecklistTable, renderEvidence, renderScenario, renderConfirmedDetails, renderControlGaps, renderInconclusiveLeads, renderChecklistCoverage, REASON_HEADING, REASON_NOTE, renderUnassessedGroup, renderUnassessed, renderCoverage, renderFooter2, renderAssessmentReport, renderAssessmentJson, renderVerificationManifest, renderClientVerificationReadme, E1_PROVENANCE_BADGE, VERDICT_BADGE, renderVerificationRunReport, VERDICT_BADGE2, renderClientVerificationRunReport, RUNTIME_BADGE, meaningFor, countSuffix, renderChecklistCorrelation, DB_INVARIANT_CHECKLIST_IDS, schemaInvariantCaveat, CODE_BADGE, DAST_PROVENANCE_BADGE, RUNTIME_BADGE2, runtimeCell, dastFullyUnscanned, dastRuntimeCell, clientRuntimeCell, sastCell, meaningFor2, renderHeader3, renderRuntimeDeviations, renderOverview2, renderCorrelationReport, PLAN_FILE, MANIFEST_FILE, REPORT_FILE, DAST_PROBE_SCRIPT_FILE2, DAST_PROBE_FILE, DAST_API_SEED_SCRIPT_FILE2, renderDastReadme, VERDICT_BADGE3, verdictCell, PROVENANCE_BADGE, COVERAGE_BADGE, hoursOf2, coverageCause, COVERAGE_COUNT, renderDastRunReport, locationOf, renderSastRunReport, UNASSESSED_LABEL, renderUnassessedSection, metaLine, fileNameOf, renderHandoffPacket, renderHandoffManifest;
@@ -47247,10 +47123,11 @@ __export(ai_triage_command_exports, {
47247
47123
  TAINT_SINK_CATEGORIES: () => TAINT_SINK_CATEGORIES,
47248
47124
  runAiTriageCommand: () => runAiTriageCommand
47249
47125
  });
47250
- var JAVA_GLOBS, EXCLUDES, runAiTriageCommand;
47126
+ var JAVA_GLOBS, EXCLUDES, TAINT_SINK_CATEGORIES, renderEndpointContext, runAiTriageCommand;
47251
47127
  var init_ai_triage_command = __esm({
47252
47128
  "src/commands/ai-triage.command.ts"() {
47253
47129
  init_dist6();
47130
+ init_dist5();
47254
47131
  init_dist();
47255
47132
  init_composition();
47256
47133
  init_load();
@@ -47258,8 +47135,35 @@ var init_ai_triage_command = __esm({
47258
47135
  init_find_files();
47259
47136
  JAVA_GLOBS = ["**/*.java"];
47260
47137
  EXCLUDES = ["**/node_modules/**", "**/dist/**", "**/target/**"];
47138
+ TAINT_SINK_CATEGORIES = {
47139
+ "spring/jpa-create-query": "sqli",
47140
+ "spring/jdbc-template": "sqli",
47141
+ "spring/jdbc-raw": "sqli",
47142
+ "spring/jdbc-statement-execute": "sqli",
47143
+ "spring/runtime-exec": "cmdi",
47144
+ "spring/process-builder-command": "cmdi",
47145
+ "spring/process-builder-ctor": "cmdi",
47146
+ "spring/path-file": "pathtraver",
47147
+ "spring/path-resource": "pathtraver",
47148
+ "spring/minio-object": "pathtraver",
47149
+ "spring/rest-template-ssrf": "ssrf",
47150
+ "spring/web-client-ssrf": "ssrf",
47151
+ "spring/url-ssrf": "ssrf",
47152
+ "spring/okhttp-url": "ssrf",
47153
+ "spring/servlet-writer": "xss",
47154
+ "spring/servlet-writer-typed": "xss",
47155
+ "spring/ldap-search": "ldapi",
47156
+ "spring/xpath-eval": "xpathi",
47157
+ "spring/trust-boundary": "trustbound",
47158
+ "spring/trust-boundary-typed": "trustbound"
47159
+ };
47160
+ renderEndpointContext = (endpoints) => endpoints.map((endpoint) => {
47161
+ const params = endpoint.params.map((param) => `${param.name} (${param.kind})`).join(", ");
47162
+ return `- ${endpoint.httpMethod} ${endpoint.path} @line ${endpoint.line}; params: ${params || "none"}`;
47163
+ }).join("\n");
47261
47164
  runAiTriageCommand = async (options) => {
47262
47165
  const source = resolve(process.cwd(), options.source);
47166
+ const reportRoot = resolve(process.cwd(), options.reportRoot ?? source);
47263
47167
  const logger = createLogger({ level: "info", destination: "stderr" });
47264
47168
  const configRes = await loadConfig(
47265
47169
  options.config === void 0 ? { cwd: source } : { cwd: source, configPath: resolve(process.cwd(), options.config) }
@@ -47288,27 +47192,101 @@ var init_ai_triage_command = __esm({
47288
47192
  return EXIT.SUCCESS;
47289
47193
  }
47290
47194
  const files = filesResult.value;
47291
- logger.info("[ai-triage] Running two-way AI triage analysis on Java source files...");
47292
- const result = await runTwoWayAiTriage({
47293
- files,
47294
- client,
47295
- twoWay: options.twoWay ?? true,
47296
- logger,
47297
- onProgress: (completed, total) => {
47298
- if (completed % 5 === 0 || completed === total) {
47299
- logger.info(`[ai-triage] Progress: ${completed}/${total} evaluated.`);
47195
+ const analyzer = await createDefaultTaintAnalyzer();
47196
+ const taintFindings = files.flatMap((f) => analyzer.analyze(f, { files }));
47197
+ const endpoints = extractHttpEndpoints(files);
47198
+ const candidatesMap = /* @__PURE__ */ new Map();
47199
+ for (const finding of taintFindings) {
47200
+ const category = TAINT_SINK_CATEGORIES[finding.sinkId];
47201
+ if (category) {
47202
+ const fileObj = files.find((f) => f.path === finding.file);
47203
+ if (fileObj) {
47204
+ const key = `${finding.file}::${category}`;
47205
+ if (!candidatesMap.has(key)) {
47206
+ candidatesMap.set(key, {
47207
+ file: finding.file,
47208
+ content: fileObj.content,
47209
+ category,
47210
+ isFalseNegativeCandidate: false,
47211
+ endpointContext: renderEndpointContext(
47212
+ endpoints.filter((endpoint) => endpoint.file === finding.file)
47213
+ )
47214
+ });
47215
+ }
47300
47216
  }
47301
47217
  }
47302
- });
47303
- const { report: report2, stats } = result;
47218
+ }
47219
+ if (options.twoWay) {
47220
+ const endpointFiles = new Set(endpoints.map((e) => e.file));
47221
+ const fnCategories = ["sqli", "cmdi", "pathtraver", "ssrf", "xss"];
47222
+ for (const epFile of endpointFiles) {
47223
+ const fileObj = files.find((f) => f.path === epFile);
47224
+ if (fileObj) {
47225
+ for (const cat of fnCategories) {
47226
+ const key = `${epFile}::${cat}`;
47227
+ if (!candidatesMap.has(key)) {
47228
+ candidatesMap.set(key, {
47229
+ file: epFile,
47230
+ content: fileObj.content,
47231
+ category: cat,
47232
+ isFalseNegativeCandidate: true,
47233
+ endpointContext: renderEndpointContext(
47234
+ endpoints.filter((endpoint) => endpoint.file === epFile)
47235
+ )
47236
+ });
47237
+ }
47238
+ }
47239
+ }
47240
+ }
47241
+ }
47242
+ const candidates = Array.from(candidatesMap.values());
47243
+ if (candidates.length === 0) {
47244
+ logger.info("[ai-triage] No candidates found for AI triage.");
47245
+ return EXIT.SUCCESS;
47246
+ }
47247
+ logger.info(`[ai-triage] Starting AI triage on ${candidates.length} candidates...`);
47248
+ const results = [];
47249
+ let completed = 0;
47250
+ for (const candidate of candidates) {
47251
+ try {
47252
+ const triageRes = await evaluateSliceWithAi({
47253
+ client,
47254
+ category: candidate.category,
47255
+ content: candidate.content,
47256
+ endpointContext: candidate.endpointContext,
47257
+ logger
47258
+ });
47259
+ results.push({
47260
+ file: toPosix(relative(reportRoot, resolve(source, candidate.file))),
47261
+ category: candidate.category,
47262
+ vulnerable: triageRes.vulnerable,
47263
+ reason: triageRes.reason,
47264
+ isFalseNegativeCandidate: candidate.isFalseNegativeCandidate,
47265
+ ...triageRes.endpoint !== void 0 ? { endpoint: triageRes.endpoint } : {}
47266
+ });
47267
+ } catch (e) {
47268
+ logger.warn(
47269
+ `[ai-triage] Failed to evaluate ${candidate.file} for ${candidate.category}: ${e.message}`
47270
+ );
47271
+ }
47272
+ completed++;
47273
+ if (completed % 5 === 0 || completed === candidates.length) {
47274
+ logger.info(`[ai-triage] Progress: ${completed}/${candidates.length} evaluated.`);
47275
+ }
47276
+ }
47277
+ const flagged = results.filter((r) => r.vulnerable).length;
47304
47278
  logger.info(
47305
- `[ai-triage] Completed. Found ${stats.vulnerable} vulnerable issues out of ${report2.items.length}.`
47279
+ `[ai-triage] Completed. Found ${flagged} vulnerable issues out of ${results.length}.`
47306
47280
  );
47307
47281
  if (options.emitReport) {
47308
47282
  const outPath = resolve(process.cwd(), options.emitReport);
47309
47283
  mkdirSync(dirname(outPath), { recursive: true });
47310
- await writeFile(outPath, `${JSON.stringify(report2, null, 2)}
47311
- `, "utf8");
47284
+ await writeFile(
47285
+ outPath,
47286
+ `${JSON.stringify({ version: 1, items: results }, null, 2)}
47287
+ `,
47288
+ "utf8"
47289
+ );
47312
47290
  logger.info(`[ai-triage] Wrote AI Triage report to ${outPath}`);
47313
47291
  }
47314
47292
  return EXIT.SUCCESS;
@@ -47324,11 +47302,11 @@ var definedBuildValue = (value, fallback) => typeof value === "string" && value.
47324
47302
  var getCliBuildMetadata = (version2) => ({
47325
47303
  version: version2,
47326
47304
  gitSha: definedBuildValue(
47327
- "964280406a33" ,
47305
+ "e8df2c6d599c" ,
47328
47306
  "unknown"
47329
47307
  ),
47330
47308
  buildTimestamp: definedBuildValue(
47331
- "2026-09-16T02:12:16.866Z" ,
47309
+ "2026-09-16T03:16:43.210Z" ,
47332
47310
  "unknown"
47333
47311
  ),
47334
47312
  configSchemaRange: definedBuildValue(
@@ -48546,7 +48524,7 @@ var projectListSchema = external_exports.object({
48546
48524
  total: external_exports.number().int().nonnegative(),
48547
48525
  limit: external_exports.number().int().positive(),
48548
48526
  offset: external_exports.number().int().nonnegative()
48549
- }).strict();
48527
+ }).passthrough();
48550
48528
  var createProjectRequestSchema = external_exports.object({
48551
48529
  id: projectIdSchema,
48552
48530
  name: external_exports.string().trim().min(1).max(255),
@@ -48592,7 +48570,7 @@ var dashboardRunListSchema = external_exports.object({
48592
48570
  total: external_exports.number().int().nonnegative(),
48593
48571
  limit: external_exports.number().int().positive(),
48594
48572
  offset: external_exports.number().int().nonnegative()
48595
- }).strict();
48573
+ }).passthrough();
48596
48574
  var dashboardRunDetailSchema = external_exports.object({ run: external_exports.unknown() }).strict();
48597
48575
  var repositoryRuleExportSchema = external_exports.object({
48598
48576
  schemaVersion: external_exports.literal(1),
@@ -48701,6 +48679,7 @@ var createCliApiClient = (options) => {
48701
48679
  const controller = new AbortController();
48702
48680
  const timer = setTimeout(() => controller.abort(), timeoutMs);
48703
48681
  const requestId = (options.requestId ?? defaultRequestId)();
48682
+ let payload;
48704
48683
  try {
48705
48684
  const response = await requestWithAuthorization(
48706
48685
  path,
@@ -48710,7 +48689,7 @@ var createCliApiClient = (options) => {
48710
48689
  requestId
48711
48690
  );
48712
48691
  if (!response.ok) throw await asError(response, requestId);
48713
- return parse2(await response.json());
48692
+ payload = await response.json();
48714
48693
  } catch (error) {
48715
48694
  if (error instanceof CliApiClientRequestError) throw error;
48716
48695
  const message = error instanceof Error && error.name === "AbortError" ? "Request timed out." : "Network request failed.";
@@ -48723,6 +48702,18 @@ var createCliApiClient = (options) => {
48723
48702
  } finally {
48724
48703
  clearTimeout(timer);
48725
48704
  }
48705
+ try {
48706
+ return parse2(payload);
48707
+ } catch (error) {
48708
+ if (error instanceof CliApiClientRequestError) throw error;
48709
+ const message = error instanceof Error ? `Invalid response format: ${error.message}` : "Invalid response format.";
48710
+ throw new CliApiClientRequestError({
48711
+ status: 0,
48712
+ requestId,
48713
+ message,
48714
+ retryable: false
48715
+ });
48716
+ }
48726
48717
  };
48727
48718
  const requestText = async (path, init) => {
48728
48719
  const controller = new AbortController();
@@ -55766,11 +55757,11 @@ function createPattern(matcher) {
55766
55757
  if (matcher.path === string)
55767
55758
  return true;
55768
55759
  if (matcher.recursive) {
55769
- const relative9 = sp2.relative(matcher.path, string);
55770
- if (!relative9) {
55760
+ const relative10 = sp2.relative(matcher.path, string);
55761
+ if (!relative10) {
55771
55762
  return false;
55772
55763
  }
55773
- return !relative9.startsWith("..") && !sp2.isAbsolute(relative9);
55764
+ return !relative10.startsWith("..") && !sp2.isAbsolute(relative10);
55774
55765
  }
55775
55766
  return false;
55776
55767
  };
@@ -61846,40 +61837,54 @@ H\xE3y ch\u1EA1y \`cs auth login\`.`
61846
61837
  });
61847
61838
  if (configRes.ok) {
61848
61839
  const payload = await configRes.json();
61849
- const ai = payload.config?.ai ?? payload.ai;
61850
- const provider = ai?.provider;
61851
- const isLocalOnly = provider === "none" || provider === "ollama";
61852
- const aiStr = JSON.stringify(ai ?? {});
61853
- const hasServerSecret = aiStr.includes("<configured server secret>");
61854
- const hasExplicitKey = typeof ai?.apiKey === "string" && ai.apiKey.trim().length > 0 && ai.apiKey.trim() !== "<configured server secret>" && !/^\$\{[^}]+\}$/.test(ai.apiKey.trim());
61855
- if (!provider || isLocalOnly || !hasServerSecret && !hasExplicitKey) {
61856
- const settingsUrl = `${serverUrl.replace(/\/+$/, "")}/runs?project=${encodeURIComponent(link.projectId)}&tab=review-config`;
61857
- console.error(
61858
- red("\n\u274C [Server] D\u1EF1 \xE1n ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5u h\xECnh Project AI Key tr\xEAn Web Dashboard.")
61859
- );
61860
- console.error(
61861
- red(
61862
- `\u{1F449} Vui l\xF2ng m\u1EDF \u0111\u01B0\u1EDDng d\u1EABn sau \u0111\u1EC3 c\u1EA5u h\xECnh nh\xE0 cung c\u1EA5p v\xE0 nh\u1EADp API Key:
61863
- ${settingsUrl}
61840
+ const config2 = payload.config ?? payload;
61841
+ const ai = config2?.ai;
61842
+ const provider = ai?.provider ?? config2?.aiProvider ?? "viettel-netmind";
61843
+ if (provider && provider !== "none" && provider !== "ollama") {
61844
+ const STORED_SECRET_PLACEHOLDER = "${CODE_SENTINEL_STORED_SECRET}";
61845
+ const pKey = provider === "viettel-netmind" ? "viettelNetmind" : provider === "openai-compatible" ? "openaiCompatible" : provider === "opencode-go" ? "opencodeGo" : provider;
61846
+ const providerConf = typeof ai?.[pKey] === "object" && ai?.[pKey] !== null ? ai[pKey] : {};
61847
+ const rawProviderApiKey = typeof providerConf.apiKey === "string" ? providerConf.apiKey.trim() : typeof ai?.apiKey === "string" ? ai.apiKey.trim() : "";
61848
+ const aiStr = JSON.stringify(ai ?? {});
61849
+ const hasServerSecret = aiStr.includes(STORED_SECRET_PLACEHOLDER) || aiStr.includes("<configured server secret>") || rawProviderApiKey === STORED_SECRET_PLACEHOLDER || rawProviderApiKey === "<configured server secret>" || rawProviderApiKey.startsWith("csenc:v1:");
61850
+ const hasExplicitKey = rawProviderApiKey.length > 0 && !hasServerSecret && !/^\$\{[A-Z0-9_]+\}$/.test(rawProviderApiKey);
61851
+ if (!hasServerSecret && !hasExplicitKey) {
61852
+ const drawerUrl = `${serverUrl.replace(/\/+$/, "")}/runs?project=${encodeURIComponent(link.projectId)}&drawer=pentest`;
61853
+ console.error(
61854
+ red("\n\u274C [Server] D\u1EF1 \xE1n ch\u01B0a \u0111\u01B0\u1EE3c c\u1EA5u h\xECnh Project AI Key tr\xEAn Web Dashboard.")
61855
+ );
61856
+ console.error(
61857
+ red(
61858
+ `\u{1F449} Vui l\xF2ng m\u1EDF drawer Pentest tr\xEAn Web Dashboard \u0111\u1EC3 nh\u1EADp API Key:
61859
+ ${drawerUrl}
61864
61860
  `
61865
- )
61866
- );
61867
- console.error(
61868
- red(
61869
- "Ghi ch\xFA: L\u1EC7nh `cs pentest` s\u1EED d\u1EE5ng Project AI Key tr\xEAn m\xE1y ch\u1EE7 \u0111\u1EC3 t\u1EF1 \u0111\u1ED9ng th\u1EF1c hi\u1EC7n:\n 1. Ph\xE2n t\xEDch & gi\u1EA3i quy\u1EBFt c\u01A1 ch\u1EBF x\xE1c th\u1EF1c (Auth Hypothesis)\n 2. Two-Way AI Triage (lo\u1EA1i b\u1ECF False Positive, t\xECm False Negative)\n 3. T\u1EA1o d\u1EEF li\u1EC7u m\u1ED3i (Data Seed Hypothesis)\nSau khi l\u01B0u key tr\xEAn Web, h\xE3y ch\u1EA1y l\u1EA1i l\u1EC7nh `cs pentest`.\n"
61870
- )
61871
- );
61872
- return 2;
61861
+ )
61862
+ );
61863
+ console.error(
61864
+ red(
61865
+ `H\u01B0\u1EDBng d\u1EABn thao t\xE1c:
61866
+ 1. M\u1EDF link tr\xEAn (ho\u1EB7c v\xE0o D\u1EF1 \xE1n -> b\u1EA5m n\xFAt "Pentest" \u0111\u1EC3 m\u1EDF drawer "Ki\u1EC3m th\u1EED trong m\xF4i tr\u01B0\u1EDDng c\xF4 l\u1EADp").
61867
+ 2. T\u1EA1i m\u1EE5c "Project AI Key (${provider})", nh\u1EADp API Key v\xE0 nh\u1EA5n "L\u01B0u key cho d\u1EF1 \xE1n".
61868
+ 3. Sau khi l\u01B0u key, ch\u1EA1y l\u1EA1i l\u1EC7nh \`cs pentest\`.
61869
+
61870
+ Ghi ch\xFA: L\u1EC7nh \`cs pentest\` s\u1EED d\u1EE5ng Project AI Key tr\xEAn m\xE1y ch\u1EE7 \u0111\u1EC3 t\u1EF1 \u0111\u1ED9ng th\u1EF1c hi\u1EC7n:
61871
+ - Ph\xE2n t\xEDch & gi\u1EA3i quy\u1EBFt c\u01A1 ch\u1EBF x\xE1c th\u1EF1c (Auth Hypothesis)
61872
+ - Two-Way AI Triage (lo\u1EA1i b\u1ECF False Positive, t\xECm False Negative)
61873
+ - T\u1EA1o d\u1EEF li\u1EC7u m\u1ED3i (Data Seed Hypothesis)
61874
+ `
61875
+ )
61876
+ );
61877
+ return 2;
61878
+ }
61873
61879
  }
61874
61880
  }
61875
- } catch (_e) {
61881
+ } catch {
61876
61882
  }
61877
61883
  }
61878
61884
  let hypothesisTmp;
61879
61885
  let triageTmp;
61880
61886
  if (resolveAuthLocally) {
61881
61887
  hypothesisTmp = join(tmpdir(), `cs-auth-hypothesis-${process.pid}-${Date.now()}.json`);
61882
- triageTmp = join(tmpdir(), `cs-ai-triage-${process.pid}-${Date.now()}.json`);
61883
61888
  await runRuntimeAuthSeed({
61884
61889
  source: join(repoRoot, modulePath),
61885
61890
  useAi: true,
@@ -61887,13 +61892,6 @@ H\xE3y ch\u1EA1y \`cs auth login\`.`
61887
61892
  ...options.refreshHypothesis === true ? { refreshHypothesis: true } : {},
61888
61893
  ...options.config === void 0 ? {} : { config: options.config }
61889
61894
  });
61890
- await runAiTriageCommand({
61891
- source: join(repoRoot, modulePath),
61892
- emitReport: triageTmp,
61893
- twoWay: true,
61894
- // Enable FN hunting on endpoints
61895
- ...options.config === void 0 ? {} : { config: options.config }
61896
- });
61897
61895
  const newEntries = [...plan.entries];
61898
61896
  if (existsSync(hypothesisTmp)) {
61899
61897
  newEntries.push({ name: HYPOTHESIS_ENTRY, absolutePath: hypothesisTmp });
@@ -61902,10 +61900,27 @@ H\xE3y ch\u1EA1y \`cs auth login\`.`
61902
61900
  `cs package: kh\xF4ng gi\u1EA3i \u0111\u01B0\u1EE3c gi\u1EA3 thuy\u1EBFt x\xE1c th\u1EF1c \u2014 ZIP kh\xF4ng mang gi\u1EA3 thuy\u1EBFt, lane runtime s\u1EBD ch\u1EA1y \u0111\u01B0\u1EDDng t\u1EA5t \u0111\u1ECBnh${String.fromCharCode(10)}`
61903
61901
  );
61904
61902
  }
61903
+ planWithAuth = { ...plan, entries: newEntries };
61904
+ }
61905
+ if (options.resolveAuth === true) {
61906
+ triageTmp = join(tmpdir(), `cs-ai-triage-${process.pid}-${Date.now()}.json`);
61907
+ await runAiTriageCommand({
61908
+ source: join(repoRoot, modulePath),
61909
+ reportRoot: repoRoot,
61910
+ emitReport: triageTmp,
61911
+ twoWay: true,
61912
+ ...options.config === void 0 ? {} : { config: options.config }
61913
+ });
61905
61914
  if (existsSync(triageTmp)) {
61906
- newEntries.push({ name: AI_TRIAGE_ENTRY, absolutePath: triageTmp });
61915
+ planWithAuth = {
61916
+ ...planWithAuth,
61917
+ entries: [...planWithAuth.entries, { name: AI_TRIAGE_ENTRY, absolutePath: triageTmp }]
61918
+ };
61919
+ } else {
61920
+ process.stderr.write(
61921
+ "[ai-triage] Kh\xF4ng t\u1EA1o \u0111\u01B0\u1EE3c b\xE1o c\xE1o AI triage; ZIP kh\xF4ng mang k\u1EBFt qu\u1EA3 triage.\n"
61922
+ );
61907
61923
  }
61908
- planWithAuth = { ...plan, entries: newEntries };
61909
61924
  }
61910
61925
  let dataSeedTmp;
61911
61926
  const resolveDataSeedLocally = options.resolveDataSeed === true && !options.push;
@@ -61937,7 +61952,6 @@ H\xE3y ch\u1EA1y \`cs auth login\`.`
61937
61952
  );
61938
61953
  const bytes = writePackageZip(planWithAuth, outPath);
61939
61954
  if (hypothesisTmp !== void 0) rmSync(hypothesisTmp, { force: true });
61940
- if (hypothesisTmp !== void 0) rmSync(hypothesisTmp, { force: true });
61941
61955
  if (triageTmp !== void 0) rmSync(triageTmp, { force: true });
61942
61956
  if (dataSeedTmp !== void 0) rmSync(dataSeedTmp, { force: true });
61943
61957
  process.stdout.write(`Packaged ${plan.modulePath} \u2192 ${outPath} (${formatBytes(bytes)})
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-sentinel-cli/code-sentinel-cli",
3
- "version": "4.0.3",
3
+ "version": "4.0.5",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "AI-assisted code review CLI for Angular, Spring Boot, and Flutter projects.",