@dataparade/cli 0.0.13 → 0.0.14

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 (74) hide show
  1. package/dist/package.json +2 -2
  2. package/dist/src/ai-enrichment/candidate-selector.d.ts +4 -4
  3. package/dist/src/ai-enrichment/candidate-selector.js +37 -32
  4. package/dist/src/ai-enrichment/fallbacks.js +130 -3
  5. package/dist/src/ai-enrichment/merge-rules.d.ts +3 -3
  6. package/dist/src/ai-enrichment/merge-rules.js +118 -40
  7. package/dist/src/ai-enrichment/prompts/provider-enrichment-prompts.d.ts +2 -2
  8. package/dist/src/ai-enrichment/prompts/provider-enrichment-prompts.js +3 -3
  9. package/dist/src/ai-enrichment/property-priority.d.ts +5 -0
  10. package/dist/src/ai-enrichment/property-priority.js +23 -0
  11. package/dist/src/ai-enrichment/provider-prompt.d.ts +5 -5
  12. package/dist/src/ai-enrichment/provider-prompt.js +24 -19
  13. package/dist/src/ai-enrichment/red-flags.d.ts +46 -0
  14. package/dist/src/ai-enrichment/red-flags.js +365 -0
  15. package/dist/src/ai-enrichment/third-party-evidence.d.ts +3 -3
  16. package/dist/src/ai-enrichment/third-party-evidence.js +96 -93
  17. package/dist/src/cli.d.ts +1 -1
  18. package/dist/src/cli.js +158 -141
  19. package/dist/src/core/pipeline/orchestrator-result.d.ts +9 -1
  20. package/dist/src/core/pipeline/orchestrator.d.ts +2 -2
  21. package/dist/src/core/pipeline/scan-pipeline.d.ts +2 -2
  22. package/dist/src/core/pipeline/scan-pipeline.js +46 -34
  23. package/dist/src/output/json.d.ts +11 -3
  24. package/dist/src/output/json.js +10 -5
  25. package/dist/tests/unit/ai-enrichment/candidate-selector.spec.js +80 -49
  26. package/dist/tests/unit/ai-enrichment/fallbacks.spec.js +78 -0
  27. package/dist/tests/unit/ai-enrichment/merge-rules.spec.js +510 -264
  28. package/dist/tests/unit/ai-enrichment/provider-prompt.spec.js +80 -77
  29. package/dist/tests/unit/ai-enrichment/red-flags.spec.js +227 -0
  30. package/dist/tests/unit/ai-enrichment/third-party-evidence.spec.js +38 -34
  31. package/dist/tests/unit/cli/scan-command-e2e-backend-lambda-orphan.spec.d.ts +1 -0
  32. package/dist/tests/unit/cli/scan-command-e2e-backend-lambda-orphan.spec.js +60 -0
  33. package/dist/tests/unit/cli/scan-command-e2e-occupied-section-hubs.spec.d.ts +1 -0
  34. package/dist/tests/unit/cli/scan-command-e2e-occupied-section-hubs.spec.js +58 -0
  35. package/dist/tests/unit/cli/scan-command-e2e-ruby-basic.spec.d.ts +1 -0
  36. package/dist/tests/unit/cli/scan-command-e2e-ruby-basic.spec.js +46 -0
  37. package/dist/tests/unit/cli/scan-quota-flow.spec.js +8 -0
  38. package/package.json +2 -2
  39. package/dist/tests/fixtures/e2e-ts-sample/db-client-import.d.ts +0 -2
  40. package/dist/tests/fixtures/e2e-ts-sample/db-client-import.js +0 -8
  41. package/dist/tests/fixtures/e2e-ts-sample/db.d.ts +0 -3
  42. package/dist/tests/fixtures/e2e-ts-sample/db.js +0 -7
  43. package/dist/tests/fixtures/e2e-ts-sample/external-api.d.ts +0 -1
  44. package/dist/tests/fixtures/e2e-ts-sample/external-api.js +0 -18
  45. package/dist/tests/fixtures/e2e-ts-sample/pg-client.d.ts +0 -3
  46. package/dist/tests/fixtures/e2e-ts-sample/pg-client.js +0 -7
  47. package/dist/tests/fixtures/e2e-ts-sample/server.d.ts +0 -14
  48. package/dist/tests/fixtures/e2e-ts-sample/server.js +0 -4
  49. package/dist/tests/fixtures/e2e-ts-sentry-route-env/server.js +0 -24
  50. package/dist/tests/fixtures/ingest-basic/src/index.d.ts +0 -1
  51. package/dist/tests/fixtures/ingest-basic/src/index.js +0 -6
  52. package/dist/tests/fixtures/mixed-language-basic/api.d.ts +0 -2
  53. package/dist/tests/fixtures/mixed-language-basic/api.js +0 -12
  54. package/dist/tests/fixtures/monorepo-app-plus-terraform/packages/app/app/route.d.ts +0 -1
  55. package/dist/tests/fixtures/monorepo-app-plus-terraform/packages/app/app/route.js +0 -6
  56. package/dist/tests/fixtures/monorepo-front-back-sections/backend/app/route.d.ts +0 -1
  57. package/dist/tests/fixtures/monorepo-front-back-sections/backend/app/route.js +0 -6
  58. package/dist/tests/fixtures/monorepo-front-back-sections/frontend/app/route.d.ts +0 -1
  59. package/dist/tests/fixtures/monorepo-front-back-sections/frontend/app/route.js +0 -7
  60. package/dist/tests/fixtures/typescript-basic/app/route.d.ts +0 -1
  61. package/dist/tests/fixtures/typescript-basic/app/route.js +0 -7
  62. package/dist/tests/fixtures/typescript-basic/db-client-import.d.ts +0 -2
  63. package/dist/tests/fixtures/typescript-basic/db-client-import.js +0 -8
  64. package/dist/tests/fixtures/typescript-basic/db.d.ts +0 -3
  65. package/dist/tests/fixtures/typescript-basic/db.js +0 -7
  66. package/dist/tests/fixtures/typescript-basic/external-api.d.ts +0 -1
  67. package/dist/tests/fixtures/typescript-basic/external-api.js +0 -18
  68. package/dist/tests/fixtures/typescript-basic/pg-client.d.ts +0 -3
  69. package/dist/tests/fixtures/typescript-basic/pg-client.js +0 -7
  70. package/dist/tests/fixtures/typescript-basic/server.d.ts +0 -14
  71. package/dist/tests/fixtures/typescript-basic/server.js +0 -4
  72. package/dist/tests/fixtures/typescript-dependency-manifests-basic/src/index.d.ts +0 -0
  73. package/dist/tests/fixtures/typescript-dependency-manifests-basic/src/index.js +0 -2
  74. /package/dist/tests/{fixtures/e2e-ts-sentry-route-env/server.d.ts → unit/ai-enrichment/red-flags.spec.d.ts} +0 -0
@@ -1 +1,9 @@
1
- export type { OrchestratorScanResult } from "@dataparade/scanner";
1
+ import type { OrchestratorScanResult as ScannerOrchestratorScanResult } from '@dataparade/scanner';
2
+ import type { ScanRedFlag } from '../../ai-enrichment/red-flags';
3
+ /**
4
+ * CLI scan result: scanner orchestrator payload plus optional connectivity RED flags
5
+ * collected after deterministic fallbacks / repair (soft gate; JSON still written).
6
+ */
7
+ export type OrchestratorScanResult = ScannerOrchestratorScanResult & {
8
+ redFlags?: ScanRedFlag[];
9
+ };
@@ -1,2 +1,2 @@
1
- export { createDefaultScanConfiguration, scan, } from "@dataparade/scanner";
2
- export type { OrchestratorScanResult } from "@dataparade/scanner";
1
+ export { createDefaultScanConfiguration, scan } from '@dataparade/scanner';
2
+ export type { OrchestratorScanResult } from './orchestrator-result';
@@ -1,5 +1,5 @@
1
- import type { ScanConfiguration, ScanProgress } from "../types";
2
- import type { OrchestratorScanResult } from "./orchestrator-result";
1
+ import type { ScanConfiguration, ScanProgress } from '../types';
2
+ import type { OrchestratorScanResult } from './orchestrator-result';
3
3
  /**
4
4
  * Full CLI scan pipeline: deterministic structural scan, optional structural enrichment,
5
5
  * optional LLM inference, and LangSmith tracing when enabled.
@@ -5,6 +5,7 @@ const ai_orchestrator_options_1 = require("./ai-orchestrator-options");
5
5
  const scanner_1 = require("@dataparade/scanner");
6
6
  const pipeline_1 = require("../../ai-enrichment/pipeline");
7
7
  const fallbacks_1 = require("../../ai-enrichment/fallbacks");
8
+ const red_flags_1 = require("../../ai-enrichment/red-flags");
8
9
  const agent_orchestrator_1 = require("../../ai-enrichment/agent-orchestrator");
9
10
  const third_party_data_flow_1 = require("../../ai-enrichment/third-party-data-flow");
10
11
  const third_party_subtype_1 = require("../../ai-enrichment/third-party-subtype");
@@ -15,8 +16,8 @@ function buildAiProposalDetails(input) {
15
16
  const beforeById = new Map(input.componentsBeforeAi.map((component) => [component.id, component]));
16
17
  return input.proposals.map(({ id, proposal }) => {
17
18
  const rejectionReason = rejectedById.get(id);
18
- const status = appliedSet.has(id) ? "applied" : "rejected";
19
- const propertyChanges = proposal.kind === "component_patch" && status === "applied"
19
+ const status = appliedSet.has(id) ? 'applied' : 'rejected';
20
+ const propertyChanges = proposal.kind === 'component_patch' && status === 'applied'
20
21
  ? Object.entries(proposal.setProperties).map(([key, to]) => ({
21
22
  key,
22
23
  from: beforeById.get(proposal.targetComponentId)?.properties?.[key],
@@ -25,9 +26,9 @@ function buildAiProposalDetails(input) {
25
26
  : undefined;
26
27
  return {
27
28
  id,
28
- source: id.startsWith("heuristic_") ? "heuristic" : "provider",
29
+ source: id.startsWith('heuristic_') ? 'heuristic' : 'provider',
29
30
  status,
30
- rejectionReason: status === "rejected" ? rejectionReason : undefined,
31
+ rejectionReason: status === 'rejected' ? rejectionReason : undefined,
31
32
  kind: proposal.kind,
32
33
  candidateType: proposal.candidateType,
33
34
  agent: proposal.agent,
@@ -35,10 +36,12 @@ function buildAiProposalDetails(input) {
35
36
  model: proposal.model,
36
37
  confidence: proposal.confidence.score,
37
38
  confidenceBand: proposal.confidence.band,
38
- targetComponentId: proposal.kind === "component_patch" ? proposal.targetComponentId : undefined,
39
- targetFlowId: proposal.kind === "flow_patch" ? proposal.targetFlowId : undefined,
40
- sourceComponentId: proposal.kind === "flow_patch" ? proposal.sourceComponentId : undefined,
41
- targetFlowComponentId: proposal.kind === "flow_patch" ? proposal.targetComponentId : undefined,
39
+ targetComponentId: proposal.kind === 'component_patch'
40
+ ? proposal.targetComponentId
41
+ : undefined,
42
+ targetFlowId: proposal.kind === 'flow_patch' ? proposal.targetFlowId : undefined,
43
+ sourceComponentId: proposal.kind === 'flow_patch' ? proposal.sourceComponentId : undefined,
44
+ targetFlowComponentId: proposal.kind === 'flow_patch' ? proposal.targetComponentId : undefined,
42
45
  evidence: proposal.evidence,
43
46
  propertyChanges,
44
47
  };
@@ -47,9 +50,9 @@ function buildAiProposalDetails(input) {
47
50
  function countRejectionsByReason(rejected, proposalById) {
48
51
  const counts = new Map();
49
52
  for (const item of rejected) {
50
- const source = proposalById.get(item.proposalId)?.id.startsWith("provider_")
51
- ? "provider"
52
- : "heuristic";
53
+ const source = proposalById.get(item.proposalId)?.id.startsWith('provider_')
54
+ ? 'provider'
55
+ : 'heuristic';
53
56
  const key = `${source}:${item.reason}`;
54
57
  counts.set(key, (counts.get(key) ?? 0) + 1);
55
58
  }
@@ -58,7 +61,7 @@ function countRejectionsByReason(rejected, proposalById) {
58
61
  function isSparse(value) {
59
62
  if (value === null || value === undefined)
60
63
  return true;
61
- if (typeof value === "string")
64
+ if (typeof value === 'string')
62
65
  return value.trim().length === 0;
63
66
  if (Array.isArray(value))
64
67
  return value.length === 0;
@@ -75,9 +78,9 @@ function buildThirdPartyCoverage(input) {
75
78
  const rejectedReasonById = new Map(input.rejectedProposalIds.map((entry) => [entry.proposalId, entry.reason]));
76
79
  for (const proposalEntry of input.proposals) {
77
80
  const proposal = proposalEntry.proposal;
78
- if (proposal.kind !== "component_patch")
81
+ if (proposal.kind !== 'component_patch')
79
82
  continue;
80
- if (proposal.candidateType !== "third_party")
83
+ if (proposal.candidateType !== 'third_party')
81
84
  continue;
82
85
  const keys = Object.keys(proposal.setProperties ?? {});
83
86
  if (keys.length === 0)
@@ -87,14 +90,14 @@ function buildThirdPartyCoverage(input) {
87
90
  incrementCounter(autofilled, key);
88
91
  continue;
89
92
  }
90
- const reason = rejectedReasonById.get(proposalEntry.id) ?? "";
91
- if (reason.startsWith("confidence_below_threshold")) {
93
+ const reason = rejectedReasonById.get(proposalEntry.id) ?? '';
94
+ if (reason.startsWith('confidence_below_threshold')) {
92
95
  for (const key of keys)
93
96
  incrementCounter(suggested, key);
94
97
  }
95
98
  }
96
99
  for (const component of input.componentsAfterAi) {
97
- if (component.type !== "third_party")
100
+ if (component.type !== 'third_party')
98
101
  continue;
99
102
  for (const [key, value] of Object.entries(component.properties ?? {})) {
100
103
  if (isSparse(value))
@@ -132,16 +135,16 @@ async function runScanPipelineInner(rootPath, config, onProgress) {
132
135
  sections,
133
136
  files,
134
137
  findings,
135
- inferenceScope: config.aiInferenceScope ?? "default",
138
+ inferenceScope: config.aiInferenceScope ?? 'default',
136
139
  plannerOptions: {
137
140
  maxModelCalls: config.aiMaxModelCalls,
138
141
  totalBudgetTokens: config.aiBudgetTokens,
139
- maxCandidatesPerAgent: (config.aiInferenceScope ?? "default") === "third_party_only"
142
+ maxCandidatesPerAgent: (config.aiInferenceScope ?? 'default') === 'third_party_only'
140
143
  ? (config.aiMaxCandidatesPerAgent ?? 0)
141
144
  : config.aiMaxCandidatesPerAgent,
142
145
  },
143
146
  };
144
- (0, scanner_1.emitScanProgress)(onProgress, "data_flow", 0.82, filesScanned, "Running structural enrichment...");
147
+ (0, scanner_1.emitScanProgress)(onProgress, 'data_flow', 0.82, filesScanned, 'Running structural enrichment...');
145
148
  const structuralInference = await (0, pipeline_1.runInferencePipeline)(plannerInputBase, {
146
149
  generateProposals: async (ctx) => (0, agent_orchestrator_1.generateAgenticProposals)({
147
150
  components: ctx.components,
@@ -163,12 +166,12 @@ async function runScanPipelineInner(rootPath, config, onProgress) {
163
166
  proposalsRejected: structuralInference.mergeResult.rejectedProposalIds.length,
164
167
  };
165
168
  if (config.enableAiInference) {
166
- warnings.push("ai-inference: .env files are excluded from scans and provider prompts for security.");
169
+ warnings.push('ai-inference: .env files are excluded from scans and provider prompts for security.');
167
170
  const componentsBeforeAi = components.map((component) => ({
168
171
  ...component,
169
172
  properties: { ...component.properties },
170
173
  }));
171
- (0, scanner_1.emitScanProgress)(onProgress, "data_flow", 0.85, filesScanned, "Running LLM inference...");
174
+ (0, scanner_1.emitScanProgress)(onProgress, 'data_flow', 0.85, filesScanned, 'Running LLM inference...');
172
175
  const orchOptions = (0, ai_orchestrator_options_1.buildAgentOrchestratorOptions)(config, {
173
176
  llmEnabled: true,
174
177
  skipStructuralHeuristics: true,
@@ -193,34 +196,34 @@ async function runScanPipelineInner(rootPath, config, onProgress) {
193
196
  properties: { ...component.properties },
194
197
  }));
195
198
  const appliedIds = inference.mergeResult.appliedProposalIds;
196
- const genP = inference.proposals.filter((p) => p.id.startsWith("provider_"));
197
- const appliedP = appliedIds.filter((id) => id.startsWith("provider_")).length;
199
+ const genP = inference.proposals.filter((p) => p.id.startsWith('provider_'));
200
+ const appliedP = appliedIds.filter((id) => id.startsWith('provider_')).length;
198
201
  warnings.push(`ai-inference: applied=${appliedIds.length} (provider=${appliedP}), rejected=${inference.mergeResult.rejectedProposalIds.length}`);
199
202
  const proposalById = new Map(inference.proposals.map((p) => [p.id, p]));
200
203
  const rejectionCounts = countRejectionsByReason(inference.mergeResult.rejectedProposalIds, proposalById);
201
- const providerTargetNotFound = rejectionCounts.get("provider:target_not_found") ?? 0;
204
+ const providerTargetNotFound = rejectionCounts.get('provider:target_not_found') ?? 0;
202
205
  if (providerTargetNotFound > 0) {
203
206
  warnings.push(`ai-provider: ${providerTargetNotFound} provider proposal(s) rejected as target_not_found (likely non-canonical targetComponentId; expected component IDs like cmp_*).`);
204
207
  }
205
- const providerEvidencePathMissing = rejectionCounts.get("provider:evidence_path_not_in_scan") ?? 0;
208
+ const providerEvidencePathMissing = rejectionCounts.get('provider:evidence_path_not_in_scan') ?? 0;
206
209
  if (providerEvidencePathMissing > 0) {
207
210
  warnings.push(`ai-provider: ${providerEvidencePathMissing} provider proposal(s) rejected due to evidence_path_not_in_scan.`);
208
211
  }
209
212
  const providerConfidenceRejected = [...rejectionCounts.entries()]
210
- .filter(([k]) => k.startsWith("provider:confidence_below_threshold:"))
213
+ .filter(([k]) => k.startsWith('provider:confidence_below_threshold:'))
211
214
  .reduce((acc, [, n]) => acc + n, 0);
212
215
  if (providerConfidenceRejected > 0) {
213
216
  warnings.push(`ai-provider: ${providerConfidenceRejected} provider proposal(s) rejected by confidence thresholds.`);
214
217
  }
215
218
  if (genP.length === 0) {
216
219
  warnings.push([
217
- "ai-provider: zero LLM proposals were accepted after inference.",
218
- "Check workspace API key, BYOK credentials, network, and SCAN_AI_MAX_TOKENS for large prompts.",
219
- "Set SCAN_AI_DEBUG=true to log provider HTTP status and parse/normalization details.",
220
- ].join(" "));
220
+ 'ai-provider: zero LLM proposals were accepted after inference.',
221
+ 'Check workspace API key, BYOK credentials, network, and SCAN_AI_MAX_TOKENS for large prompts.',
222
+ 'Set SCAN_AI_DEBUG=true to log provider HTTP status and parse/normalization details.',
223
+ ].join(' '));
221
224
  }
222
225
  else if (genP.length > 0 && appliedP === 0) {
223
- warnings.push("ai-provider: proposals were returned but none passed validation/merge (evidence paths, confidence, or thresholds).");
226
+ warnings.push('ai-provider: proposals were returned but none passed validation/merge (evidence paths, confidence, or thresholds).');
224
227
  }
225
228
  aiInferenceSummary = {
226
229
  ran: true,
@@ -232,7 +235,9 @@ async function runScanPipelineInner(rootPath, config, onProgress) {
232
235
  proposalsAppliedHeuristic: 0,
233
236
  proposalsGeneratedProvider: genP.length,
234
237
  proposalsAppliedProvider: appliedP,
235
- aiProvider: orchOptions.platformProxy ? "dataparade" : orchOptions.provider,
238
+ aiProvider: orchOptions.platformProxy
239
+ ? 'dataparade'
240
+ : orchOptions.provider,
236
241
  aiModel: orchOptions.model,
237
242
  providerCalls: inference.usageSummary?.providerCalls ?? 0,
238
243
  inputTokens: inference.usageSummary?.inputTokens ?? 0,
@@ -259,6 +264,13 @@ async function runScanPipelineInner(rootPath, config, onProgress) {
259
264
  const fallbackResult = (0, fallbacks_1.applyDeterministicInferenceFallbacks)(components, dataFlows);
260
265
  components.splice(0, components.length, ...fallbackResult.components);
261
266
  let finalizedFlows = fallbackResult.dataFlows;
267
+ const redFlagPass = (0, red_flags_1.applyConnectivityRedFlagPass)(components, finalizedFlows);
268
+ components.splice(0, components.length, ...redFlagPass.components);
269
+ finalizedFlows = redFlagPass.dataFlows;
270
+ const redFlags = redFlagPass.redFlags;
271
+ for (const flag of redFlags) {
272
+ warnings.push((0, red_flags_1.formatRedFlagWarning)(flag));
273
+ }
262
274
  const subTypesFilledLate = (0, third_party_subtype_1.ensureThirdPartySubTypes)(components);
263
275
  if (subTypesFilledLate > 0) {
264
276
  warnings.push(`third-party-subtype: filled subType for ${subTypesFilledLate} third-party component(s) after inference.`);
@@ -290,7 +302,7 @@ async function runScanPipelineInner(rootPath, config, onProgress) {
290
302
  }),
291
303
  };
292
304
  }
293
- return result;
305
+ return { ...result, redFlags };
294
306
  }
295
307
  /**
296
308
  * Full CLI scan pipeline: deterministic structural scan, optional structural enrichment,
@@ -1,6 +1,7 @@
1
- import type { DiagramGraphJsonSchema } from "../core/schema";
2
- import { type DataflowWrapperSchema } from "../core/schema/dataflow-wrapper.schema";
3
- import type { ScanResult } from "../core/types";
1
+ import type { DiagramGraphJsonSchema } from '../core/schema';
2
+ import { type DataflowWrapperSchema } from '../core/schema/dataflow-wrapper.schema';
3
+ import type { ScanResult } from '../core/types';
4
+ import type { ScanRedFlag } from '../ai-enrichment/red-flags';
4
5
  export interface BuildDataflowWrapperOptions {
5
6
  /**
6
7
  * Optional schema version to embed in the wrapper.
@@ -12,6 +13,11 @@ export interface BuildDataflowWrapperOptions {
12
13
  schemaVersion?: string;
13
14
  /** Assessment / project name shown in the dashboard import preview. */
14
15
  projectName?: string;
16
+ /**
17
+ * Connectivity RED flags from the CLI soft gate (after repair).
18
+ * Written under `metadata.redFlags` (passthrough metadata schema).
19
+ */
20
+ redFlags?: ScanRedFlag[];
15
21
  }
16
22
  /**
17
23
  * Assemble the top-level `dataflow.json` wrapper object from a scan result and graph.
@@ -39,6 +45,8 @@ export interface WriteDataflowJsonOptions {
39
45
  schemaVersion?: string;
40
46
  /** Assessment / project name stored in wrapper metadata for upload and preview. */
41
47
  projectName?: string;
48
+ /** Optional connectivity RED flags for `metadata.redFlags`. */
49
+ redFlags?: ScanRedFlag[];
42
50
  }
43
51
  /**
44
52
  * Validate and write a `dataflow.json` wrapper to disk.
@@ -14,7 +14,7 @@ const dataflow_wrapper_schema_1 = require("../core/schema/dataflow-wrapper.schem
14
14
  * just constructs a value that can then be validated and written by callers.
15
15
  */
16
16
  function buildDataflowWrapper(scanResult, graph, options = {}) {
17
- const schemaVersion = options.schemaVersion ?? "1.0";
17
+ const schemaVersion = options.schemaVersion ?? '1.0';
18
18
  const projectName = options.projectName?.trim();
19
19
  const metadata = {
20
20
  componentsCount: scanResult.components.length,
@@ -28,7 +28,11 @@ function buildDataflowWrapper(scanResult, graph, options = {}) {
28
28
  scanResult.aiInferenceSummary;
29
29
  }
30
30
  if (scanResult.terraformScanSummary) {
31
- metadata.terraform = scanResult.terraformScanSummary;
31
+ metadata.terraform =
32
+ scanResult.terraformScanSummary;
33
+ }
34
+ if (options.redFlags && options.redFlags.length > 0) {
35
+ metadata.redFlags = options.redFlags;
32
36
  }
33
37
  return {
34
38
  schemaVersion,
@@ -49,16 +53,17 @@ function buildDataflowWrapper(scanResult, graph, options = {}) {
49
53
  * can emit a non-zero exit code.
50
54
  */
51
55
  function writeDataflowJson(options) {
52
- const { scanResult, graph, outputPath, schemaVersion, projectName } = options;
56
+ const { scanResult, graph, outputPath, schemaVersion, projectName, redFlags, } = options;
53
57
  const wrapper = buildDataflowWrapper(scanResult, graph, {
54
58
  schemaVersion,
55
59
  projectName,
60
+ redFlags,
56
61
  });
57
62
  const validation = (0, dataflow_wrapper_schema_1.validateDataflowJson)(wrapper);
58
63
  if (!validation.ok) {
59
- const messages = validation.errors.join("; ");
64
+ const messages = validation.errors.join('; ');
60
65
  throw new Error(`Invalid dataflow.json wrapper: ${messages}`);
61
66
  }
62
67
  const json = JSON.stringify(validation.value, null, 2);
63
- fs_1.default.writeFileSync(outputPath, json, "utf8");
68
+ fs_1.default.writeFileSync(outputPath, json, 'utf8');
64
69
  }
@@ -1,106 +1,137 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const candidate_selector_1 = require("../../../src/ai-enrichment/candidate-selector");
4
- describe("ai-enrichment candidate selector", () => {
5
- it("selects third-party, sparse property, flow direction, and missing interaction candidates", () => {
4
+ describe('ai-enrichment candidate selector', () => {
5
+ it('selects third-party, sparse property, flow direction, and missing interaction candidates', () => {
6
6
  const sections = [
7
7
  {
8
- id: "frontend",
9
- label: "frontend",
10
- role: "service",
11
- sectionDir: "frontend",
12
- manifestPaths: ["frontend/package.json"],
8
+ id: 'frontend',
9
+ label: 'frontend',
10
+ role: 'service',
11
+ sectionDir: 'frontend',
12
+ manifestPaths: ['frontend/package.json'],
13
13
  },
14
14
  {
15
- id: "backend",
16
- label: "backend",
17
- role: "service",
18
- sectionDir: "backend",
19
- manifestPaths: ["backend/package.json"],
15
+ id: 'backend',
16
+ label: 'backend',
17
+ role: 'service',
18
+ sectionDir: 'backend',
19
+ manifestPaths: ['backend/package.json'],
20
20
  },
21
21
  ];
22
22
  const components = [
23
23
  {
24
- id: "tp_1",
25
- name: "Stripe",
26
- type: "third_party",
24
+ id: 'tp_1',
25
+ name: 'Stripe',
26
+ type: 'third_party',
27
27
  confidence: 0.9,
28
28
  detectedFrom: [],
29
29
  sourceLocations: [],
30
- properties: { section_id: "backend", dpa_signed: null },
30
+ properties: { section_id: 'backend', dpa_signed: null },
31
31
  },
32
32
  {
33
- id: "app_1",
34
- name: "Backend",
35
- type: "asset",
33
+ id: 'app_1',
34
+ name: 'Backend',
35
+ type: 'asset',
36
36
  confidence: 0.95,
37
37
  detectedFrom: [],
38
38
  sourceLocations: [],
39
- properties: { section_id: "backend", encryption_at_rest: null },
39
+ properties: { section_id: 'backend', encryption_at_rest: null },
40
40
  },
41
41
  {
42
- id: "actor_1",
43
- name: "Customer",
44
- type: "actor",
42
+ id: 'actor_1',
43
+ name: 'Customer',
44
+ type: 'actor',
45
45
  confidence: 0.7,
46
46
  detectedFrom: [],
47
47
  sourceLocations: [],
48
- properties: { section_id: "frontend" },
48
+ properties: { section_id: 'frontend' },
49
49
  },
50
50
  ];
51
51
  const flows = [
52
52
  {
53
- id: "flow_1",
54
- sourceComponentId: "app_1",
55
- targetComponentId: "actor_1",
56
- type: "api_call",
53
+ id: 'flow_1',
54
+ sourceComponentId: 'app_1',
55
+ targetComponentId: 'actor_1',
56
+ type: 'api_call',
57
57
  confidence: 0.6,
58
58
  },
59
59
  ];
60
- const candidates = (0, candidate_selector_1.selectInferenceCandidates)({ components, dataFlows: flows, sections });
60
+ const candidates = (0, candidate_selector_1.selectInferenceCandidates)({
61
+ components,
62
+ dataFlows: flows,
63
+ sections,
64
+ });
61
65
  const candidateTypes = candidates.map((candidate) => candidate.candidateType);
62
- expect(candidateTypes).toContain("third_party");
63
- expect(candidateTypes).toContain("node_property");
64
- expect(candidateTypes).toContain("flow_direction");
65
- expect(candidateTypes).toContain("missing_interaction");
66
+ expect(candidateTypes).toContain('third_party');
67
+ expect(candidateTypes).toContain('node_property');
68
+ expect(candidateTypes).toContain('flow_direction');
69
+ expect(candidateTypes).toContain('missing_interaction');
66
70
  });
67
- it("third_party_only returns one third_party candidate per third-party and skips assets", () => {
71
+ it('third_party_only returns one third_party candidate per third-party and skips assets', () => {
68
72
  const components = [
69
73
  {
70
- id: "tp_a",
71
- name: "Stripe",
72
- type: "third_party",
74
+ id: 'tp_a',
75
+ name: 'Stripe',
76
+ type: 'third_party',
73
77
  confidence: 0.9,
74
78
  detectedFrom: [],
75
79
  sourceLocations: [],
76
- properties: { section_id: "backend", subType: "payments" },
80
+ properties: { section_id: 'backend', subType: 'payments' },
77
81
  },
78
82
  {
79
- id: "tp_b",
80
- name: "Sentry",
81
- type: "third_party",
83
+ id: 'tp_b',
84
+ name: 'Sentry',
85
+ type: 'third_party',
82
86
  confidence: 0.85,
83
87
  detectedFrom: [],
84
88
  sourceLocations: [],
85
- properties: { section_id: "backend" },
89
+ properties: { section_id: 'backend' },
86
90
  },
87
91
  {
88
- id: "app_1",
89
- name: "API",
90
- type: "asset",
92
+ id: 'app_1',
93
+ name: 'API',
94
+ type: 'asset',
91
95
  confidence: 0.95,
92
96
  detectedFrom: [],
93
97
  sourceLocations: [],
94
- properties: { section_id: "backend", encryption_at_rest: null },
98
+ properties: { section_id: 'backend', encryption_at_rest: null },
95
99
  },
96
100
  ];
97
101
  const candidates = (0, candidate_selector_1.selectInferenceCandidates)({
98
102
  components,
99
103
  dataFlows: [],
100
- inferenceScope: "third_party_only",
104
+ inferenceScope: 'third_party_only',
101
105
  });
102
106
  expect(candidates).toHaveLength(2);
103
- expect(candidates.every((c) => c.candidateType === "third_party")).toBe(true);
104
- expect(new Set(candidates.map((c) => c.componentId))).toEqual(new Set(["tp_a", "tp_b"]));
107
+ expect(candidates.every((c) => c.candidateType === 'third_party')).toBe(true);
108
+ expect(new Set(candidates.map((c) => c.componentId))).toEqual(new Set(['tp_a', 'tp_b']));
109
+ });
110
+ it('puts Tier 1 property keys first in bounded missingFields', () => {
111
+ const properties = Object.fromEntries(Array.from({ length: 40 }, (_, index) => [
112
+ `z_field_${String(index).padStart(2, '0')}`,
113
+ null,
114
+ ]));
115
+ properties.encrypt_at_rest = null;
116
+ properties.authentication_method = null;
117
+ const candidates = (0, candidate_selector_1.selectInferenceCandidates)({
118
+ components: [
119
+ {
120
+ id: 'asset_1',
121
+ name: 'API',
122
+ type: 'asset',
123
+ confidence: 0.9,
124
+ detectedFrom: [],
125
+ sourceLocations: [],
126
+ properties,
127
+ },
128
+ ],
129
+ dataFlows: [],
130
+ });
131
+ const propertyCandidate = candidates.find((candidate) => candidate.candidateType === 'node_property');
132
+ expect(propertyCandidate?.missingFields.slice(0, 2)).toEqual([
133
+ 'authentication_method',
134
+ 'encrypt_at_rest',
135
+ ]);
105
136
  });
106
137
  });
@@ -1301,4 +1301,82 @@ describe("ai-enrichment deterministic fallbacks", () => {
1301
1301
  (f.targetComponentId === "section_api" || f.targetComponentId === "db_pg"));
1302
1302
  expect(badFallbacks).toHaveLength(0);
1303
1303
  });
1304
+ it("injects a section hub and edges for third_party-only sections (cli-shaped)", () => {
1305
+ const components = [
1306
+ {
1307
+ id: "tp_openai",
1308
+ name: "Openai",
1309
+ type: "third_party",
1310
+ subType: "saas_service",
1311
+ confidence: 0.9,
1312
+ detectedFrom: [],
1313
+ sourceLocations: [],
1314
+ properties: {
1315
+ section_id: "cli",
1316
+ section_label: "cli",
1317
+ section_role: "service",
1318
+ },
1319
+ },
1320
+ {
1321
+ id: "tp_sentry",
1322
+ name: "Sentry",
1323
+ type: "third_party",
1324
+ subType: "saas_service",
1325
+ confidence: 0.9,
1326
+ detectedFrom: [],
1327
+ sourceLocations: [],
1328
+ properties: {
1329
+ section_id: "cli",
1330
+ section_label: "cli",
1331
+ section_role: "service",
1332
+ },
1333
+ },
1334
+ ];
1335
+ const result = (0, fallbacks_1.applyDeterministicInferenceFallbacks)(components, []);
1336
+ const hub = result.components.find((c) => c.type === "asset" &&
1337
+ c.properties?.section_id === "cli" &&
1338
+ (c.properties?.isMainApplication === true ||
1339
+ c.properties?.isMainApplication === "true"));
1340
+ expect(hub).toBeDefined();
1341
+ expect(hub?.name).toBe("cli");
1342
+ expect(result.dataFlows.filter((f) => f.sourceComponentId === hub?.id &&
1343
+ (f.targetComponentId === "tp_openai" ||
1344
+ f.targetComponentId === "tp_sentry"))).toHaveLength(2);
1345
+ });
1346
+ it("promotes an existing section asset to main hub instead of duplicating", () => {
1347
+ const components = [
1348
+ {
1349
+ id: "asset_scripts",
1350
+ name: "Scripts Service",
1351
+ type: "asset",
1352
+ subType: "service",
1353
+ confidence: 1,
1354
+ detectedFrom: [],
1355
+ sourceLocations: [],
1356
+ properties: {
1357
+ section_id: "scripts",
1358
+ section_label: "scripts",
1359
+ },
1360
+ },
1361
+ {
1362
+ id: "tp_stripe",
1363
+ name: "Stripe",
1364
+ type: "third_party",
1365
+ confidence: 1,
1366
+ detectedFrom: [],
1367
+ sourceLocations: [],
1368
+ properties: { section_id: "scripts", section_label: "scripts" },
1369
+ },
1370
+ ];
1371
+ const result = (0, fallbacks_1.applyDeterministicInferenceFallbacks)(components, []);
1372
+ const hubs = result.components.filter((c) => c.type === "asset" &&
1373
+ c.properties?.section_id === "scripts" &&
1374
+ (c.properties?.isMainApplication === true ||
1375
+ c.properties?.isMainApplication === "true"));
1376
+ expect(hubs).toHaveLength(1);
1377
+ expect(hubs[0]?.id).toBe("asset_scripts");
1378
+ expect(hubs[0]?.name).toBe("scripts");
1379
+ expect(result.dataFlows.some((f) => f.sourceComponentId === "asset_scripts" &&
1380
+ f.targetComponentId === "tp_stripe")).toBe(true);
1381
+ });
1304
1382
  });