@dataparade/cli 0.0.13 → 0.0.15

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 (81) 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 +236 -143
  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/core/schema/dataflow-wrapper.schema.d.ts +33 -1
  24. package/dist/src/core/schema/dataflow-wrapper.schema.js +19 -3
  25. package/dist/src/output/json.d.ts +18 -3
  26. package/dist/src/output/json.js +14 -5
  27. package/dist/src/platform-api/cli-scan-failure-report.d.ts +9 -0
  28. package/dist/src/platform-api/cli-scan-failure-report.js +23 -0
  29. package/dist/tests/schema/dataflow-wrapper.schema.spec.js +142 -21
  30. package/dist/tests/unit/ai-enrichment/candidate-selector.spec.js +80 -49
  31. package/dist/tests/unit/ai-enrichment/fallbacks.spec.js +78 -0
  32. package/dist/tests/unit/ai-enrichment/merge-rules.spec.js +510 -264
  33. package/dist/tests/unit/ai-enrichment/provider-prompt.spec.js +80 -77
  34. package/dist/tests/unit/ai-enrichment/red-flags.spec.js +227 -0
  35. package/dist/tests/unit/ai-enrichment/third-party-evidence.spec.js +38 -34
  36. package/dist/tests/unit/cli/scan-command-e2e-backend-lambda-orphan.spec.d.ts +1 -0
  37. package/dist/tests/unit/cli/scan-command-e2e-backend-lambda-orphan.spec.js +60 -0
  38. package/dist/tests/unit/cli/scan-command-e2e-occupied-section-hubs.spec.d.ts +1 -0
  39. package/dist/tests/unit/cli/scan-command-e2e-occupied-section-hubs.spec.js +58 -0
  40. package/dist/tests/unit/cli/scan-command-e2e-ruby-basic.spec.d.ts +1 -0
  41. package/dist/tests/unit/cli/scan-command-e2e-ruby-basic.spec.js +46 -0
  42. package/dist/tests/unit/cli/scan-quota-flow.spec.js +57 -45
  43. package/dist/tests/unit/platform-api/cli-scan-failure-report.spec.d.ts +1 -0
  44. package/dist/tests/unit/platform-api/cli-scan-failure-report.spec.js +25 -0
  45. package/package.json +2 -2
  46. package/dist/tests/fixtures/e2e-ts-sample/db-client-import.d.ts +0 -2
  47. package/dist/tests/fixtures/e2e-ts-sample/db-client-import.js +0 -8
  48. package/dist/tests/fixtures/e2e-ts-sample/db.d.ts +0 -3
  49. package/dist/tests/fixtures/e2e-ts-sample/db.js +0 -7
  50. package/dist/tests/fixtures/e2e-ts-sample/external-api.d.ts +0 -1
  51. package/dist/tests/fixtures/e2e-ts-sample/external-api.js +0 -18
  52. package/dist/tests/fixtures/e2e-ts-sample/pg-client.d.ts +0 -3
  53. package/dist/tests/fixtures/e2e-ts-sample/pg-client.js +0 -7
  54. package/dist/tests/fixtures/e2e-ts-sample/server.d.ts +0 -14
  55. package/dist/tests/fixtures/e2e-ts-sample/server.js +0 -4
  56. package/dist/tests/fixtures/e2e-ts-sentry-route-env/server.js +0 -24
  57. package/dist/tests/fixtures/ingest-basic/src/index.d.ts +0 -1
  58. package/dist/tests/fixtures/ingest-basic/src/index.js +0 -6
  59. package/dist/tests/fixtures/mixed-language-basic/api.d.ts +0 -2
  60. package/dist/tests/fixtures/mixed-language-basic/api.js +0 -12
  61. package/dist/tests/fixtures/monorepo-app-plus-terraform/packages/app/app/route.d.ts +0 -1
  62. package/dist/tests/fixtures/monorepo-app-plus-terraform/packages/app/app/route.js +0 -6
  63. package/dist/tests/fixtures/monorepo-front-back-sections/backend/app/route.d.ts +0 -1
  64. package/dist/tests/fixtures/monorepo-front-back-sections/backend/app/route.js +0 -6
  65. package/dist/tests/fixtures/monorepo-front-back-sections/frontend/app/route.d.ts +0 -1
  66. package/dist/tests/fixtures/monorepo-front-back-sections/frontend/app/route.js +0 -7
  67. package/dist/tests/fixtures/typescript-basic/app/route.d.ts +0 -1
  68. package/dist/tests/fixtures/typescript-basic/app/route.js +0 -7
  69. package/dist/tests/fixtures/typescript-basic/db-client-import.d.ts +0 -2
  70. package/dist/tests/fixtures/typescript-basic/db-client-import.js +0 -8
  71. package/dist/tests/fixtures/typescript-basic/db.d.ts +0 -3
  72. package/dist/tests/fixtures/typescript-basic/db.js +0 -7
  73. package/dist/tests/fixtures/typescript-basic/external-api.d.ts +0 -1
  74. package/dist/tests/fixtures/typescript-basic/external-api.js +0 -18
  75. package/dist/tests/fixtures/typescript-basic/pg-client.d.ts +0 -3
  76. package/dist/tests/fixtures/typescript-basic/pg-client.js +0 -7
  77. package/dist/tests/fixtures/typescript-basic/server.d.ts +0 -14
  78. package/dist/tests/fixtures/typescript-basic/server.js +0 -4
  79. package/dist/tests/fixtures/typescript-dependency-manifests-basic/src/index.d.ts +0 -0
  80. package/dist/tests/fixtures/typescript-dependency-manifests-basic/src/index.js +0 -2
  81. /package/dist/tests/{fixtures/e2e-ts-sentry-route-env/server.d.ts → unit/ai-enrichment/red-flags.spec.d.ts} +0 -0
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataparade/cli",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
4
4
  "description": "dataPARADE CLI — scan codebases for privacy and security data flows",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -54,7 +54,7 @@
54
54
  "eval:models": "pnpm exec node dist/src/evals/run-model-matrix.js"
55
55
  },
56
56
  "dependencies": {
57
- "@dataparade/scanner": "github:DataParade-io/scanner#998fb12b2db667dd7ff305e34c716634b867e806",
57
+ "@dataparade/scanner": "github:DataParade-io/scanner#4363d8ce2925e3457923432e3de1703e0f9ab46f",
58
58
  "@sentry/node": "^10.38.0",
59
59
  "commander": "^12.1.0",
60
60
  "dotenv": "^16.4.7",
@@ -1,7 +1,7 @@
1
- import type { ServiceSection } from "@dataparade/scanner";
2
- import type { DetectedComponent } from "../core/types/component";
3
- import type { DetectedDataFlow } from "../core/types/data-flow";
4
- import type { AiInferenceCandidate, AiInferenceScope } from "./types";
1
+ import type { ServiceSection } from '@dataparade/scanner';
2
+ import type { DetectedComponent } from '../core/types/component';
3
+ import type { DetectedDataFlow } from '../core/types/data-flow';
4
+ import type { AiInferenceCandidate, AiInferenceScope } from './types';
5
5
  export declare function selectInferenceCandidates(input: {
6
6
  components: DetectedComponent[];
7
7
  dataFlows: DetectedDataFlow[];
@@ -1,18 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.selectInferenceCandidates = selectInferenceCandidates;
4
+ const property_priority_1 = require("./property-priority");
4
5
  /** Keep LangSmith / LLM prompts small; tools still see full `properties`. */
5
6
  const MAX_MISSING_FIELD_KEYS_IN_CANDIDATE = 36;
6
7
  function getSectionId(component) {
7
8
  const section = component.properties.section_id;
8
- return typeof section === "string" && section.length > 0 ? section : undefined;
9
+ return typeof section === 'string' && section.length > 0
10
+ ? section
11
+ : undefined;
9
12
  }
10
13
  function isSparseValue(value) {
11
14
  if (value === null || value === undefined)
12
15
  return true;
13
16
  if (Array.isArray(value))
14
17
  return value.length === 0;
15
- if (typeof value === "string")
18
+ if (typeof value === 'string')
16
19
  return value.trim().length === 0;
17
20
  return false;
18
21
  }
@@ -28,7 +31,7 @@ function countCrossSectionFlows(flows, componentsById) {
28
31
  const target = componentsById.get(flow.targetComponentId);
29
32
  if (!source || !target)
30
33
  return false;
31
- if (source.type === "actor" || target.type === "actor")
34
+ if (source.type === 'actor' || target.type === 'actor')
32
35
  return false;
33
36
  const sourceSection = getSectionId(source);
34
37
  const targetSection = getSectionId(target);
@@ -50,37 +53,36 @@ function buildCandidate(candidateType, id, priority, rationale, fields = {}) {
50
53
  };
51
54
  }
52
55
  function selectInferenceCandidates(input) {
53
- const scope = input.inferenceScope ?? "default";
54
- if (scope === "third_party_only") {
56
+ const scope = input.inferenceScope ?? 'default';
57
+ if (scope === 'third_party_only') {
55
58
  return selectThirdPartyOnlyCandidates(input.components);
56
59
  }
57
60
  const candidates = [];
58
61
  const byId = new Map(input.components.map((component) => [component.id, component]));
59
62
  for (const component of input.components) {
60
- if (component.type === "third_party" &&
63
+ if (component.type === 'third_party' &&
61
64
  (!component.subType || component.subType.trim().length === 0)) {
62
- candidates.push(buildCandidate("third_party", `cand_third_party_${component.id}`, 95, "Third-party component is missing subtype metadata.", {
65
+ candidates.push(buildCandidate('third_party', `cand_third_party_${component.id}`, 95, 'Third-party component is missing subtype metadata.', {
63
66
  componentId: component.id,
64
- missingFields: ["subType"],
65
- hints: ["infer vendor/product from import and endpoint evidence"],
67
+ missingFields: ['subType'],
68
+ hints: ['infer vendor/product from import and endpoint evidence'],
66
69
  }));
67
70
  }
68
- if (component.type !== "actor" && hasSparseProperties(component)) {
69
- const sparseFields = Object.entries(component.properties)
71
+ if (component.type !== 'actor' && hasSparseProperties(component)) {
72
+ const sparseFields = (0, property_priority_1.sortPropertyKeysByPriority)(Object.entries(component.properties)
70
73
  .filter(([, value]) => isSparseValue(value))
71
- .map(([key]) => key)
72
- .sort((a, b) => a.localeCompare(b));
74
+ .map(([key]) => key));
73
75
  const listed = sparseFields.length <= MAX_MISSING_FIELD_KEYS_IN_CANDIDATE
74
76
  ? sparseFields
75
77
  : sparseFields.slice(0, MAX_MISSING_FIELD_KEYS_IN_CANDIDATE);
76
78
  const omitted = sparseFields.length - listed.length;
77
79
  const hints = omitted > 0
78
80
  ? [
79
- "prioritize Tier 1 fields first",
81
+ 'prioritize Tier 1 fields first',
80
82
  `${omitted} more sparse property keys omitted here; use tooling / full component context for the complete list`,
81
83
  ]
82
- : ["prioritize Tier 1 fields first"];
83
- candidates.push(buildCandidate("node_property", `cand_node_property_${component.id}`, 85, "Component has sparse properties requiring evidence-backed completion.", {
84
+ : ['prioritize Tier 1 fields first'];
85
+ candidates.push(buildCandidate('node_property', `cand_node_property_${component.id}`, 85, 'Component has sparse properties requiring evidence-backed completion.', {
84
86
  componentId: component.id,
85
87
  missingFields: listed,
86
88
  hints,
@@ -92,20 +94,24 @@ function selectInferenceCandidates(input) {
92
94
  const target = byId.get(flow.targetComponentId);
93
95
  if (!source || !target)
94
96
  continue;
95
- const actorInvolved = source.type === "actor" || target.type === "actor";
97
+ const actorInvolved = source.type === 'actor' || target.type === 'actor';
96
98
  const uncertain = flow.confidence < 0.8;
97
- const suspiciousDirection = source.type !== "actor" && target.type === "actor";
99
+ const suspiciousDirection = source.type !== 'actor' && target.type === 'actor';
98
100
  if (actorInvolved && (uncertain || suspiciousDirection)) {
99
- candidates.push(buildCandidate("flow_direction", `cand_flow_direction_${flow.id}`, suspiciousDirection ? 90 : 80, "Flow involving actor has low confidence or suspicious direction.", {
101
+ candidates.push(buildCandidate('flow_direction', `cand_flow_direction_${flow.id}`, suspiciousDirection ? 90 : 80, 'Flow involving actor has low confidence or suspicious direction.', {
100
102
  flowId: flow.id,
101
- hints: ["verify caller->callee direction from route and handler evidence"],
103
+ hints: [
104
+ 'verify caller->callee direction from route and handler evidence',
105
+ ],
102
106
  }));
103
107
  }
104
108
  }
105
109
  const crossSectionFlows = countCrossSectionFlows(input.dataFlows, byId);
106
110
  if ((input.sections?.length ?? 0) >= 2 && crossSectionFlows === 0) {
107
- candidates.push(buildCandidate("missing_interaction", "cand_missing_interaction_cross_section", 88, "Multiple sections were detected without any inferred cross-section interactions.", {
108
- hints: ["search for API clients, fetch/axios, and backend route wiring"],
111
+ candidates.push(buildCandidate('missing_interaction', 'cand_missing_interaction_cross_section', 88, 'Multiple sections were detected without any inferred cross-section interactions.', {
112
+ hints: [
113
+ 'search for API clients, fetch/axios, and backend route wiring',
114
+ ],
109
115
  }));
110
116
  }
111
117
  return candidates.sort((a, b) => {
@@ -120,32 +126,31 @@ function selectInferenceCandidates(input) {
120
126
  function selectThirdPartyOnlyCandidates(components) {
121
127
  const out = [];
122
128
  for (const component of components) {
123
- if (component.type !== "third_party")
129
+ if (component.type !== 'third_party')
124
130
  continue;
125
131
  const needsSubType = !component.subType || component.subType.trim().length === 0;
126
- const sparseFields = Object.entries(component.properties ?? {})
132
+ const sparseFields = (0, property_priority_1.sortPropertyKeysByPriority)(Object.entries(component.properties ?? {})
127
133
  .filter(([, value]) => isSparseValue(value))
128
- .map(([key]) => key)
129
- .sort((a, b) => a.localeCompare(b));
134
+ .map(([key]) => key));
130
135
  const missingFields = needsSubType
131
- ? ["subType", ...sparseFields.filter((k) => k !== "subType")]
136
+ ? ['subType', ...sparseFields.filter((k) => k !== 'subType')]
132
137
  : sparseFields;
133
138
  const listed = missingFields.length <= MAX_MISSING_FIELD_KEYS_IN_CANDIDATE
134
139
  ? missingFields
135
140
  : missingFields.slice(0, MAX_MISSING_FIELD_KEYS_IN_CANDIDATE);
136
141
  const omitted = missingFields.length - listed.length;
137
- out.push(buildCandidate("third_party", `cand_third_party_${component.id}`, needsSubType ? 95 : 90, needsSubType
138
- ? "Third-party AI pass: infer setSubType (required) plus sparse properties with evidence."
139
- : "Third-party AI pass: fill every sparse property key you can support with evidence from the repo (vendor, auth, methods, data handling, compliance, etc.).", {
142
+ out.push(buildCandidate('third_party', `cand_third_party_${component.id}`, needsSubType ? 95 : 90, needsSubType
143
+ ? 'Third-party AI pass: infer setSubType (required) plus sparse properties with evidence.'
144
+ : 'Third-party AI pass: fill every sparse property key you can support with evidence from the repo (vendor, auth, methods, data handling, compliance, etc.).', {
140
145
  componentId: component.id,
141
146
  missingFields: listed,
142
147
  hints: [
143
148
  ...(needsSubType
144
149
  ? [
145
- "setSubType is required when componentContext.subType is empty — pick one taxonomy value (e.g. ai_provider, saas_service, payment_processor, cloud_provider)",
150
+ 'setSubType is required when componentContext.subType is empty — pick one taxonomy value (e.g. ai_provider, saas_service, payment_processor, cloud_provider)',
146
151
  ]
147
152
  : []),
148
- "Focus on vendor, integration_method, endpoints, SDKs, and auth patterns from imports and config",
153
+ 'Focus on vendor, integration_method, endpoints, SDKs, and auth patterns from imports and config',
149
154
  ...(omitted > 0
150
155
  ? [
151
156
  `${omitted} more sparse property keys omitted in this payload; use agent tools for full context`,
@@ -72,6 +72,132 @@ function sectionHasMainApplicationAsset(components, sectionId) {
72
72
  (c.properties?.isMainApplication === true ||
73
73
  c.properties?.isMainApplication === 'true'));
74
74
  }
75
+ function nextSyntheticComponentId(components) {
76
+ let maxNumericId = 0;
77
+ for (const component of components) {
78
+ const match = /^cmp_(\d+)$/.exec(component.id);
79
+ if (match) {
80
+ const num = Number.parseInt(match[1], 10);
81
+ if (!Number.isNaN(num) && num > maxNumericId)
82
+ maxNumericId = num;
83
+ }
84
+ }
85
+ return `cmp_${maxNumericId + 1}`;
86
+ }
87
+ const INJECTED_SECTION_HUB_SOURCE_CONTEXT = 'injected_project_placeholder';
88
+ /**
89
+ * Ensures every concrete service section with components has a main-app hub,
90
+ * and connects that hub to orphan third parties in the same section.
91
+ */
92
+ function ensureSectionHubsAndOrphanThirdPartyFlows(components, flows, policy) {
93
+ const nextComponents = components.map((c) => ({
94
+ ...c,
95
+ properties: { ...c.properties },
96
+ }));
97
+ const occupied = new Set();
98
+ for (const c of nextComponents) {
99
+ const sid = String(c.properties?.section_id ?? '').trim();
100
+ if (isConcreteServiceSectionId(sid, policy))
101
+ occupied.add(sid);
102
+ }
103
+ const sortedSections = [...occupied].sort((a, b) => a.localeCompare(b));
104
+ for (const sectionId of sortedSections) {
105
+ if (sectionHasMainApplicationAsset(nextComponents, sectionId))
106
+ continue;
107
+ const sectionAssets = nextComponents.filter((c) => c.type === 'asset' &&
108
+ String(c.properties?.section_id ?? '') === sectionId &&
109
+ !c.properties?.managed_by_provider &&
110
+ !c.properties?.managed_service_key &&
111
+ c.subType !== 'database');
112
+ const promoteable = sectionAssets.find((c) => c.subType === 'application' ||
113
+ c.subType === 'service' ||
114
+ c.subType === 'api' ||
115
+ c.subType === undefined);
116
+ const sample = nextComponents.find((c) => String(c.properties?.section_id ?? '') === sectionId);
117
+ const label = String(sample?.properties?.section_label ?? '').trim() || sectionId;
118
+ const role = String(sample?.properties?.section_role ?? '').trim() || 'service';
119
+ if (promoteable) {
120
+ promoteable.properties = {
121
+ ...promoteable.properties,
122
+ isMainApplication: true,
123
+ section_id: sectionId,
124
+ section_label: String(promoteable.properties?.section_label ?? '').trim() || label,
125
+ section_role: String(promoteable.properties?.section_role ?? '').trim() || role,
126
+ };
127
+ if (promoteable.properties?.isSectionApiNode !== true &&
128
+ promoteable.properties?.isSectionApiNode !== 'true') {
129
+ promoteable.name = label;
130
+ }
131
+ continue;
132
+ }
133
+ nextComponents.push({
134
+ id: nextSyntheticComponentId(nextComponents),
135
+ name: label,
136
+ type: 'asset',
137
+ subType: 'application',
138
+ confidence: 1,
139
+ detectedFrom: [],
140
+ sourceLocations: [],
141
+ properties: {
142
+ section_id: sectionId,
143
+ section_label: label,
144
+ section_role: role,
145
+ isMainApplication: true,
146
+ sourceContext: INJECTED_SECTION_HUB_SOURCE_CONTEXT,
147
+ },
148
+ });
149
+ }
150
+ const byId = componentById(nextComponents);
151
+ const nextFlows = [...flows];
152
+ const pairKeys = new Set(nextFlows.map((f) => flowPairKey(f)));
153
+ const hasInSectionInbound = new Set();
154
+ for (const flow of nextFlows) {
155
+ const source = byId.get(flow.sourceComponentId);
156
+ const target = byId.get(flow.targetComponentId);
157
+ if (!source || !target || target.type !== 'third_party')
158
+ continue;
159
+ const sourceSection = String(source.properties?.section_id ?? '').trim();
160
+ const targetSection = String(target.properties?.section_id ?? '').trim();
161
+ if (!sourceSection || sourceSection !== targetSection)
162
+ continue;
163
+ hasInSectionInbound.add(target.id);
164
+ }
165
+ const orphanThirdParties = nextComponents
166
+ .filter((c) => {
167
+ if (c.type !== 'third_party')
168
+ return false;
169
+ if (hasInSectionInbound.has(c.id))
170
+ return false;
171
+ const sid = String(c.properties?.section_id ?? '').trim();
172
+ return isConcreteServiceSectionId(sid, policy);
173
+ })
174
+ .sort((a, b) => a.id.localeCompare(b.id));
175
+ for (const tp of orphanThirdParties) {
176
+ const sectionId = String(tp.properties?.section_id ?? '').trim();
177
+ const hub = nextComponents.find((c) => c.type === 'asset' &&
178
+ String(c.properties?.section_id ?? '') === sectionId &&
179
+ (c.properties?.isMainApplication === true ||
180
+ c.properties?.isMainApplication === 'true'));
181
+ if (!hub || hub.id === tp.id)
182
+ continue;
183
+ const key = flowPairKey({
184
+ sourceComponentId: hub.id,
185
+ targetComponentId: tp.id,
186
+ });
187
+ if (pairKeys.has(key))
188
+ continue;
189
+ pairKeys.add(key);
190
+ nextFlows.push({
191
+ id: `flow_fallback_${nextFlows.length + 1}`,
192
+ sourceComponentId: hub.id,
193
+ targetComponentId: tp.id,
194
+ type: 'api_call',
195
+ confidence: 0.6,
196
+ description: 'Section hub to orphan third party',
197
+ });
198
+ }
199
+ return { components: nextComponents, flows: nextFlows };
200
+ }
75
201
  function getStringValues(value) {
76
202
  if (typeof value === 'string')
77
203
  return [value.toLowerCase()];
@@ -470,14 +596,15 @@ function selectPreferredApiSource(source, target, components) {
470
596
  return candidates[0];
471
597
  }
472
598
  function applyDeterministicInferenceFallbacks(components, flows) {
473
- const nextComponents = components.map((c) => ({
599
+ const fallbackPolicy = (0, provider_topology_rules_1.loadProviderTopologyFallbackPolicy)();
600
+ const ensured = ensureSectionHubsAndOrphanThirdPartyFlows(components, flows, fallbackPolicy);
601
+ const nextComponents = ensured.components.map((c) => ({
474
602
  ...c,
475
603
  properties: { ...c.properties },
476
604
  }));
477
605
  const byId = componentById(nextComponents);
478
- const next = flows.map((flow) => ({ ...flow }));
606
+ const next = ensured.flows.map((flow) => ({ ...flow }));
479
607
  const keys = new Set(next.map((flow) => flowPairKey(flow)));
480
- const fallbackPolicy = (0, provider_topology_rules_1.loadProviderTopologyFallbackPolicy)();
481
608
  for (const flow of next) {
482
609
  const source = byId.get(flow.sourceComponentId);
483
610
  const target = byId.get(flow.targetComponentId);
@@ -1,6 +1,6 @@
1
- import type { DetectedComponent } from "../core/types/component";
2
- import type { DetectedDataFlow } from "../core/types/data-flow";
3
- import type { AiMergeResult, AiMergeThresholds, AiProposal } from "./types";
1
+ import type { DetectedComponent } from '../core/types/component';
2
+ import type { DetectedDataFlow } from '../core/types/data-flow';
3
+ import type { AiMergeResult, AiMergeThresholds, AiProposal } from './types';
4
4
  /** PRD §4.4 / task 2.2 — AI data-action assignments gated at ≥ 0.72. */
5
5
  export declare const DATA_ACTION_MIN_CONFIDENCE = 0.72;
6
6
  /** When true, flow_patch proposals are not applied — data-flow graph stays exactly as detected before AI. */
@@ -20,19 +20,19 @@ const DEFAULT_THRESHOLDS = {
20
20
  function normalizeAlias(raw) {
21
21
  return raw
22
22
  .trim()
23
- .replace(/\\/g, "/")
24
- .replace(/^\.\//, "")
25
- .replace(/\/+$/, "")
23
+ .replace(/\\/g, '/')
24
+ .replace(/^\.\//, '')
25
+ .replace(/\/+$/, '')
26
26
  .toLowerCase();
27
27
  }
28
28
  function stripIndexSuffix(p) {
29
29
  const normalized = normalizeAlias(p);
30
30
  const base = path_1.default.posix.basename(normalized);
31
- const stem = base.replace(/\.[^.]+$/, "");
32
- if (stem !== "index")
31
+ const stem = base.replace(/\.[^.]+$/, '');
32
+ if (stem !== 'index')
33
33
  return normalized;
34
34
  const dir = path_1.default.posix.dirname(normalized);
35
- return dir === "." ? normalized : normalizeAlias(dir);
35
+ return dir === '.' ? normalized : normalizeAlias(dir);
36
36
  }
37
37
  function addAlias(aliasMap, alias, componentId) {
38
38
  const key = normalizeAlias(alias);
@@ -83,10 +83,12 @@ function remapComponentPatchTarget(patch, componentIds, aliasMap) {
83
83
  };
84
84
  }
85
85
  function proposalTargetKey(proposal) {
86
- if (proposal.kind === "component_patch") {
87
- const propKeys = Object.keys(proposal.setProperties ?? {}).sort().join("|");
88
- const sub = proposal.setSubType ? `sub:${proposal.setSubType}` : "";
89
- const desc = proposal.setDescription ? "desc" : "";
86
+ if (proposal.kind === 'component_patch') {
87
+ const propKeys = Object.keys(proposal.setProperties ?? {})
88
+ .sort()
89
+ .join('|');
90
+ const sub = proposal.setSubType ? `sub:${proposal.setSubType}` : '';
91
+ const desc = proposal.setDescription ? 'desc' : '';
90
92
  return `component:${proposal.targetComponentId}:${propKeys}:${sub}:${desc}`;
91
93
  }
92
94
  if (proposal.targetFlowId) {
@@ -97,8 +99,8 @@ function proposalTargetKey(proposal) {
97
99
  function proposalRank(proposal) {
98
100
  const confidenceScore = proposal.confidence.score;
99
101
  const evidenceWeight = proposal.evidence.length / 100;
100
- const insertPenalty = proposal.kind === "flow_patch" && proposal.insertIfMissing ? -0.02 : 0;
101
- const llmBonus = proposal.provider !== "mock" ? 0.25 : 0;
102
+ const insertPenalty = proposal.kind === 'flow_patch' && proposal.insertIfMissing ? -0.02 : 0;
103
+ const llmBonus = proposal.provider !== 'mock' ? 0.25 : 0;
102
104
  return confidenceScore + evidenceWeight + insertPenalty + llmBonus;
103
105
  }
104
106
  function sortedProposals(proposals) {
@@ -115,7 +117,7 @@ function sortedProposals(proposals) {
115
117
  }
116
118
  function toProvenance(proposal, confidence) {
117
119
  return {
118
- source: "ai_agent",
120
+ source: 'ai_agent',
119
121
  provider: proposal.provider,
120
122
  model: proposal.model,
121
123
  agent: proposal.agent,
@@ -131,6 +133,60 @@ function evidenceRefsForDataAction(patch) {
131
133
  return fromProperty;
132
134
  return patch.evidence;
133
135
  }
136
+ function isEvidenceRef(value) {
137
+ if (!value || typeof value !== 'object' || Array.isArray(value))
138
+ return false;
139
+ const ref = value;
140
+ return (typeof ref.filePath === 'string' &&
141
+ typeof ref.startLine === 'number' &&
142
+ typeof ref.endLine === 'number' &&
143
+ typeof ref.reason === 'string');
144
+ }
145
+ function readExistingPropertyEvidence(raw) {
146
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
147
+ return {};
148
+ const out = {};
149
+ for (const [key, value] of Object.entries(raw)) {
150
+ if (!Array.isArray(value))
151
+ continue;
152
+ const refs = value.filter(isEvidenceRef);
153
+ if (refs.length > 0)
154
+ out[key] = refs;
155
+ }
156
+ return out;
157
+ }
158
+ /**
159
+ * Persist AI per-property evidence onto the component so graph-mapping can
160
+ * flatten it to node.data.propertyEvidence (not dropped after merge).
161
+ */
162
+ function mergePropertyEvidenceMap(existingRaw, incoming) {
163
+ if (!incoming || Object.keys(incoming).length === 0) {
164
+ const existing = readExistingPropertyEvidence(existingRaw);
165
+ return {
166
+ next: Object.keys(existing).length > 0 ? existing : undefined,
167
+ changed: false,
168
+ };
169
+ }
170
+ const next = readExistingPropertyEvidence(existingRaw);
171
+ let changed = false;
172
+ for (const [key, refs] of Object.entries(incoming)) {
173
+ if (!Array.isArray(refs) || refs.length === 0)
174
+ continue;
175
+ const validRefs = refs.filter(isEvidenceRef);
176
+ if (validRefs.length === 0)
177
+ continue;
178
+ const current = next[key] ?? [];
179
+ if ((0, util_1.isDeepStrictEqual)(current, validRefs))
180
+ continue;
181
+ // Prefer incoming refs for this key; keep unrelated keys intact.
182
+ next[key] = validRefs;
183
+ changed = true;
184
+ }
185
+ return {
186
+ next: Object.keys(next).length > 0 ? next : undefined,
187
+ changed,
188
+ };
189
+ }
134
190
  function toSourceLocations(refs) {
135
191
  return refs.map((ref) => ({
136
192
  filePath: ref.filePath,
@@ -147,15 +203,15 @@ function buildAiDataActionAssignment(action, patch) {
147
203
  const reason = refs
148
204
  .map((r) => r.reason.trim())
149
205
  .filter(Boolean)
150
- .join("; ") || "ai enrichment evidence";
151
- if (action === "relay") {
206
+ .join('; ') || 'ai enrichment evidence';
207
+ if (action === 'relay') {
152
208
  return {
153
- action: "relay",
154
- source: "ai",
209
+ action: 'relay',
210
+ source: 'ai',
155
211
  confidence: patch.confidence.score,
156
- status: "asserted",
212
+ status: 'asserted',
157
213
  evidence: {
158
- kind: "pattern_rule",
214
+ kind: 'pattern_rule',
159
215
  description: reason,
160
216
  corroboration: reason,
161
217
  },
@@ -163,9 +219,9 @@ function buildAiDataActionAssignment(action, patch) {
163
219
  }
164
220
  return {
165
221
  action,
166
- source: "ai",
222
+ source: 'ai',
167
223
  confidence: patch.confidence.score,
168
- status: "asserted",
224
+ status: 'asserted',
169
225
  evidence: toSourceLocations(refs),
170
226
  };
171
227
  }
@@ -228,6 +284,7 @@ function mergeComponentPatch(components, patch) {
228
284
  if (!component)
229
285
  return false;
230
286
  let changed = false;
287
+ const acceptedEvidenceKeys = new Set();
231
288
  const normalizedSubType = (0, third_party_subtype_1.normalizeThirdPartySubType)(patch.setSubType);
232
289
  if (normalizedSubType && normalizedSubType !== component.subType) {
233
290
  component.subType = normalizedSubType;
@@ -242,24 +299,45 @@ function mergeComponentPatch(components, patch) {
242
299
  if (dataActionRaw !== undefined) {
243
300
  if (mergeDataActionProperties(component, patch, dataActionRaw)) {
244
301
  changed = true;
302
+ acceptedEvidenceKeys.add(provider_contract_1.UI_DATA_ACTION_PROPERTY_KEY);
245
303
  }
246
304
  }
247
305
  const currentProperties = component.properties ?? {};
248
306
  const nextProperties = { ...currentProperties };
249
307
  for (const [key, value] of Object.entries(setProperties)) {
250
- if (key === provider_contract_1.UI_DATA_ACTION_PROPERTY_KEY || key === "dataActions") {
308
+ if (key === provider_contract_1.UI_DATA_ACTION_PROPERTY_KEY || key === 'dataActions') {
251
309
  continue;
252
310
  }
253
311
  const currentValue = currentProperties[key];
254
- if (key === "inference_status" && value === "needs_review") {
312
+ if (key === 'inference_status' && value === 'needs_review') {
255
313
  continue;
256
314
  }
257
315
  const normalizedCurrent = normalizeEmptyLikeValue(currentValue);
258
316
  const normalizedNext = normalizeEmptyLikeValue(value);
317
+ if (normalizedCurrent !== '__empty__') {
318
+ continue;
319
+ }
320
+ if (normalizedNext === '__empty__') {
321
+ continue;
322
+ }
259
323
  if ((0, util_1.isDeepStrictEqual)(normalizedCurrent, normalizedNext)) {
260
324
  continue;
261
325
  }
262
326
  nextProperties[key] = value;
327
+ acceptedEvidenceKeys.add(key);
328
+ changed = true;
329
+ }
330
+ const acceptedEvidence = patch.propertyEvidence
331
+ ? Object.fromEntries(Object.entries(patch.propertyEvidence).filter(([key]) => acceptedEvidenceKeys.has(key)))
332
+ : undefined;
333
+ const evidenceMerge = mergePropertyEvidenceMap(currentProperties.propertyEvidence, acceptedEvidence);
334
+ if (evidenceMerge.next) {
335
+ nextProperties.propertyEvidence = evidenceMerge.next;
336
+ }
337
+ else {
338
+ delete nextProperties.propertyEvidence;
339
+ }
340
+ if (evidenceMerge.changed) {
263
341
  changed = true;
264
342
  }
265
343
  component.properties = nextProperties;
@@ -267,12 +345,12 @@ function mergeComponentPatch(components, patch) {
267
345
  }
268
346
  function normalizeEmptyLikeValue(value) {
269
347
  if (value == null)
270
- return "__empty__";
271
- if (typeof value === "string" && value.trim().toLowerCase() === "none") {
272
- return "__empty__";
348
+ return '__empty__';
349
+ if (typeof value === 'string' && value.trim().toLowerCase() === 'none') {
350
+ return '__empty__';
273
351
  }
274
352
  if (Array.isArray(value) && value.length === 0)
275
- return "__empty__";
353
+ return '__empty__';
276
354
  return value;
277
355
  }
278
356
  function normalizeSectionId(raw) {
@@ -325,7 +403,7 @@ function mergeFlowPatch(flows, patch) {
325
403
  id: `flow_ai_${patch.sourceComponentId}_${patch.targetComponentId}_${flows.length + 1}`,
326
404
  sourceComponentId: patch.sourceComponentId,
327
405
  targetComponentId: patch.targetComponentId,
328
- type: patch.setType ?? "api_call",
406
+ type: patch.setType ?? 'api_call',
329
407
  description: patch.setDescription,
330
408
  confidence: patch.confidence.score,
331
409
  method: patch.setMethod,
@@ -364,26 +442,26 @@ function mergeAiProposals(components, dataFlows, proposals, thresholds = {}, opt
364
442
  const aliasMap = buildComponentAliasMap(nextComponents);
365
443
  const componentsById = new Map(nextComponents.map((c) => [c.id, c]));
366
444
  for (const { id, proposal } of sortedProposals(proposals)) {
367
- const resolvedProposal = proposal.kind === "component_patch"
445
+ const resolvedProposal = proposal.kind === 'component_patch'
368
446
  ? remapComponentPatchTarget(proposal, componentIds, aliasMap)
369
447
  : proposal;
370
- if (options.preserveDataFlowTopology && proposal.kind === "flow_patch") {
448
+ if (options.preserveDataFlowTopology && proposal.kind === 'flow_patch') {
371
449
  rejectedProposalIds.push({
372
450
  proposalId: id,
373
- reason: "data_flow_topology_preserved",
451
+ reason: 'data_flow_topology_preserved',
374
452
  });
375
453
  continue;
376
454
  }
377
455
  if (options.enforceIntraSectionFlowChangesOnly &&
378
- resolvedProposal.kind === "flow_patch" &&
456
+ resolvedProposal.kind === 'flow_patch' &&
379
457
  !isIntraSectionFlowPatch(resolvedProposal, componentsById, nextFlows)) {
380
458
  rejectedProposalIds.push({
381
459
  proposalId: id,
382
- reason: "cross_section_flow_change_blocked",
460
+ reason: 'cross_section_flow_change_blocked',
383
461
  });
384
462
  continue;
385
463
  }
386
- const minConfidence = resolvedProposal.kind === "component_patch"
464
+ const minConfidence = resolvedProposal.kind === 'component_patch'
387
465
  ? mergedThresholds.minComponentPatchConfidence
388
466
  : resolvedProposal.insertIfMissing
389
467
  ? mergedThresholds.minInsertFlowConfidence
@@ -396,26 +474,26 @@ function mergeAiProposals(components, dataFlows, proposals, thresholds = {}, opt
396
474
  continue;
397
475
  }
398
476
  if (resolvedProposal.evidence.length === 0) {
399
- rejectedProposalIds.push({ proposalId: id, reason: "missing_evidence" });
477
+ rejectedProposalIds.push({ proposalId: id, reason: 'missing_evidence' });
400
478
  continue;
401
479
  }
402
480
  const targetKey = proposalTargetKey(resolvedProposal);
403
481
  if (provenanceByTarget[targetKey]) {
404
482
  rejectedProposalIds.push({
405
483
  proposalId: id,
406
- reason: "target_already_modified_by_higher_ranked_proposal",
484
+ reason: 'target_already_modified_by_higher_ranked_proposal',
407
485
  });
408
486
  continue;
409
487
  }
410
- const merged = resolvedProposal.kind === "component_patch"
488
+ const merged = resolvedProposal.kind === 'component_patch'
411
489
  ? mergeComponentPatch(nextComponents, resolvedProposal)
412
490
  : mergeFlowPatch(nextFlows, resolvedProposal);
413
491
  if (!merged) {
414
492
  rejectedProposalIds.push({
415
493
  proposalId: id,
416
- reason: resolvedProposal.kind === "component_patch"
417
- ? "no_meaningful_changes"
418
- : "target_not_found",
494
+ reason: resolvedProposal.kind === 'component_patch'
495
+ ? 'no_meaningful_changes'
496
+ : 'target_not_found',
419
497
  });
420
498
  continue;
421
499
  }