@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
package/dist/src/cli.js CHANGED
@@ -57,16 +57,18 @@ const scanner_1 = require("@dataparade/scanner");
57
57
  function formatEvidence(detail) {
58
58
  const evidence = detail.evidence;
59
59
  if (!evidence || evidence.length === 0) {
60
- return "none";
60
+ return 'none';
61
61
  }
62
62
  const head = evidence[0];
63
63
  const first = head != null
64
64
  ? `${head.filePath}:${head.startLine}-${head.endLine} (${head.reason})`
65
- : "none";
66
- return evidence.length === 1 ? first : `${first}; +${evidence.length - 1} more`;
65
+ : 'none';
66
+ return evidence.length === 1
67
+ ? first
68
+ : `${first}; +${evidence.length - 1} more`;
67
69
  }
68
70
  function formatProposalTarget(detail) {
69
- if (detail.kind === "component_patch" && detail.targetComponentId) {
71
+ if (detail.kind === 'component_patch' && detail.targetComponentId) {
70
72
  return `component:${detail.targetComponentId}`;
71
73
  }
72
74
  if (detail.targetFlowId)
@@ -74,18 +76,20 @@ function formatProposalTarget(detail) {
74
76
  if (detail.sourceComponentId && detail.targetFlowComponentId) {
75
77
  return `flow:${detail.sourceComponentId}->${detail.targetFlowComponentId}`;
76
78
  }
77
- return "unknown";
79
+ return 'unknown';
78
80
  }
79
81
  function printAiInferenceVerbose(details) {
80
82
  if (details.length === 0) {
81
83
  // eslint-disable-next-line no-console
82
- console.log("[scan] ai-inference details: no proposals generated");
84
+ console.log('[scan] ai-inference details: no proposals generated');
83
85
  return;
84
86
  }
85
87
  // eslint-disable-next-line no-console
86
- console.log("[scan] ai-inference details:");
88
+ console.log('[scan] ai-inference details:');
87
89
  for (const detail of details) {
88
- const status = detail.status === "applied" ? "applied" : `rejected (${detail.rejectionReason})`;
90
+ const status = detail.status === 'applied'
91
+ ? 'applied'
92
+ : `rejected (${detail.rejectionReason})`;
89
93
  const confidence = detail.confidence.toFixed(2);
90
94
  // eslint-disable-next-line no-console
91
95
  console.log(`[scan] - ${detail.id}: ${status} | ${detail.source} | ${detail.kind} | target=${formatProposalTarget(detail)} | confidence=${confidence} (${detail.confidenceBand})`);
@@ -93,7 +97,9 @@ function printAiInferenceVerbose(details) {
93
97
  console.log(`[scan] candidate=${detail.candidateType} agent=${detail.agent} provider=${detail.provider}/${detail.model}`);
94
98
  // eslint-disable-next-line no-console
95
99
  console.log(`[scan] evidence=${formatEvidence(detail)}`);
96
- if (detail.status === "applied" && detail.propertyChanges && detail.propertyChanges.length) {
100
+ if (detail.status === 'applied' &&
101
+ detail.propertyChanges &&
102
+ detail.propertyChanges.length) {
97
103
  const formatted = detail.propertyChanges.map((change) => {
98
104
  const from = JSON.stringify(change.from);
99
105
  const to = JSON.stringify(change.to);
@@ -107,53 +113,53 @@ function printAiInferenceVerbose(details) {
107
113
  }
108
114
  }
109
115
  function formatUsd(value) {
110
- if (typeof value !== "number" || !Number.isFinite(value))
111
- return "n/a";
116
+ if (typeof value !== 'number' || !Number.isFinite(value))
117
+ return 'n/a';
112
118
  return `$${value.toFixed(6)}`;
113
119
  }
114
120
  function createProgram() {
115
121
  const program = new commander_1.Command();
116
122
  program
117
- .name("dataparade")
118
- .description("DataParade CLI - scan codebases for data flow components")
123
+ .name('dataparade')
124
+ .description('DataParade CLI - scan codebases for data flow components')
119
125
  .version(package_json_1.default.version);
120
126
  program
121
- .command("scan <path>")
122
- .description("Scan a directory (or a single supported source file) for data flow components")
123
- .option("-o, --output <file>", "Write dataflow.json wrapper to the given file (default: ./dataflow.json)")
124
- .option("--exclude <pattern...>", "One or more glob patterns to exclude from scanning")
125
- .option("--minimum-confidence <number>", "Minimum confidence (0-1) for including detections")
126
- .option("--language <language...>", "Limit scanning to specific languages (e.g. typescript, javascript, python, go, java, kotlin, cpp, csharp, terraform)")
127
- .option("--project-name <name>", "Override the inferred project name used for the application asset")
128
- .option("--deep-analysis", "Enable deeper, potentially slower structural analysis where supported")
129
- .option("--terraform-json <path>", "Merge resource addresses from a saved `terraform show -json` file (absolute or relative to scan root)")
130
- .option("--terraform-plan <path>", "Merge addresses by running `terraform show -json <path>` from the scan root (path relative to scan root; requires terraform on PATH)")
131
- .option("--terraform-stack-section-path-depth <n>", "Register Terraform stack directories as service sections when their path has exactly N segments (e.g. 4 for packages/foo/k8s/terraform)")
132
- .option("--no-terraform-stack-section-auto", "Do not infer terraformStackSectionPathDepth from .tf layout when depth is unset")
133
- .option("--monorepo-package-section-path-depth <n>", "Workspace package section depth (max 3): primary packages and rollup use N POSIX path segments (e.g. 3 for packages/twenty-apps/hello)")
134
- .option("--no-monorepo-package-section-auto", "Do not infer monorepoPackageSectionPathDepth from package.json layout when depth is unset")
135
- .option("--ai-inference", "Enable post-scan AI inference (default: on; SCAN_AI_INFERENCE=false also disables)")
136
- .option("--no-ai-inference", "Disable post-scan AI inference")
137
- .option("--ai-provider <provider>", `AI provider: ${types_1.AI_PROVIDER_IDS.join("|")}`)
138
- .option("--ai-model <model>", "Model name for AI inference")
139
- .option("--ai-endpoint <url>", "Override provider endpoint URL")
140
- .option("--ai-temperature <number>", "Sampling temperature for model calls")
141
- .option("--ai-max-tokens <number>", "Max tokens per inference call")
142
- .option("--ai-max-calls <number>", "Max model calls for a scan")
143
- .option("--ai-budget-tokens <number>", "Total token budget for inference")
144
- .option("--ai-max-candidates-per-agent <number>", "Max inference queue items per agent (0 = no cap; default from config: 25)")
145
- .option("--ai-inference-scope <scope>", "default | third_party_only — third_party_only runs AI enrichment only on every third-party node")
146
- .option("--ai-verbose", "Print per-proposal AI inference details (applied/rejected + evidence)")
147
- .option("--workspace-api-key <key>", "DataParade workspace API key (platform AI + quota; env: DATAPARADE_WORKSPACE_API_KEY)")
148
- .option("--api-key <key>", "(deprecated) alias for --workspace-api-key")
149
- .option("--byok-provider <provider>", `BYOK LLM provider when using your own API key: ${types_1.AI_PROVIDER_IDS.join("|")}`)
150
- .option("--byok-model <model>", "BYOK model name (env: SCAN_BYOK_MODEL)")
151
- .option("--skip-auto-upload", "Do not upload dataflow.json to the dashboard after scan (env: DATAPARADE_SKIP_AUTO_UPLOAD)")
127
+ .command('scan <path>')
128
+ .description('Scan a directory (or a single supported source file) for data flow components')
129
+ .option('-o, --output <file>', 'Write dataflow.json wrapper to the given file (default: ./dataflow.json)')
130
+ .option('--exclude <pattern...>', 'One or more glob patterns to exclude from scanning')
131
+ .option('--minimum-confidence <number>', 'Minimum confidence (0-1) for including detections')
132
+ .option('--language <language...>', 'Limit scanning to specific languages (e.g. typescript, javascript, python, go, java, kotlin, cpp, csharp, terraform)')
133
+ .option('--project-name <name>', 'Override the inferred project name used for the application asset')
134
+ .option('--deep-analysis', 'Enable deeper, potentially slower structural analysis where supported')
135
+ .option('--terraform-json <path>', 'Merge resource addresses from a saved `terraform show -json` file (absolute or relative to scan root)')
136
+ .option('--terraform-plan <path>', 'Merge addresses by running `terraform show -json <path>` from the scan root (path relative to scan root; requires terraform on PATH)')
137
+ .option('--terraform-stack-section-path-depth <n>', 'Register Terraform stack directories as service sections when their path has exactly N segments (e.g. 4 for packages/foo/k8s/terraform)')
138
+ .option('--no-terraform-stack-section-auto', 'Do not infer terraformStackSectionPathDepth from .tf layout when depth is unset')
139
+ .option('--monorepo-package-section-path-depth <n>', 'Workspace package section depth (max 3): primary packages and rollup use N POSIX path segments (e.g. 3 for packages/twenty-apps/hello)')
140
+ .option('--no-monorepo-package-section-auto', 'Do not infer monorepoPackageSectionPathDepth from package.json layout when depth is unset')
141
+ .option('--ai-inference', 'Enable post-scan AI inference (default: on; SCAN_AI_INFERENCE=false also disables)')
142
+ .option('--no-ai-inference', 'Disable post-scan AI inference')
143
+ .option('--ai-provider <provider>', `AI provider: ${types_1.AI_PROVIDER_IDS.join('|')}`)
144
+ .option('--ai-model <model>', 'Model name for AI inference')
145
+ .option('--ai-endpoint <url>', 'Override provider endpoint URL')
146
+ .option('--ai-temperature <number>', 'Sampling temperature for model calls')
147
+ .option('--ai-max-tokens <number>', 'Max tokens per inference call')
148
+ .option('--ai-max-calls <number>', 'Max model calls for a scan')
149
+ .option('--ai-budget-tokens <number>', 'Total token budget for inference')
150
+ .option('--ai-max-candidates-per-agent <number>', 'Max inference queue items per agent (0 = no cap; default from config: 25)')
151
+ .option('--ai-inference-scope <scope>', 'default | third_party_only — third_party_only runs AI enrichment only on every third-party node')
152
+ .option('--ai-verbose', 'Print per-proposal AI inference details (applied/rejected + evidence)')
153
+ .option('--workspace-api-key <key>', 'DataParade workspace API key (platform AI + quota; env: DATAPARADE_WORKSPACE_API_KEY)')
154
+ .option('--api-key <key>', '(deprecated) alias for --workspace-api-key')
155
+ .option('--byok-provider <provider>', `BYOK LLM provider when using your own API key: ${types_1.AI_PROVIDER_IDS.join('|')}`)
156
+ .option('--byok-model <model>', 'BYOK model name (env: SCAN_BYOK_MODEL)')
157
+ .option('--skip-auto-upload', 'Do not upload dataflow.json to the dashboard after scan (env: DATAPARADE_SKIP_AUTO_UPLOAD)')
152
158
  .action(async (path, options) => {
153
159
  let cliQuotaJobId;
154
160
  let platformQuotaApiKey;
155
161
  let quotaCompletionReported = false;
156
- let fallbackFailureMessage = "CLI scan did not complete successfully";
162
+ let fallbackFailureMessage = 'CLI scan did not complete successfully';
157
163
  let sentryScanRoot;
158
164
  let sentryAiMode;
159
165
  let sentryAiProvider;
@@ -164,14 +170,14 @@ function createProgram() {
164
170
  const usageSessionId = (0, crypto_1.randomUUID)();
165
171
  await (0, telemetry_client_1.reportCliUsageEvent)({
166
172
  sessionId: usageSessionId,
167
- event: "scan_started",
168
- command: "scan",
173
+ event: 'scan_started',
174
+ command: 'scan',
169
175
  hasApiKey: Boolean(workspaceApiKey),
170
176
  apiKey: workspaceApiKey,
171
177
  cliVersion: package_json_1.default.version,
172
178
  });
173
179
  try {
174
- const rootPathArg = path || ".";
180
+ const rootPathArg = path || '.';
175
181
  // Load dataparade.config.json from the directory being scanned, not
176
182
  // process.cwd(). Locally these often match; in Lambda the worker cwd
177
183
  // is the image root (/var/task) while the scan path is /tmp/.../project.
@@ -181,23 +187,23 @@ function createProgram() {
181
187
  scanEntry = await (0, scanner_1.resolveScanFilesystemEntry)(resolvedScanRoot);
182
188
  }
183
189
  catch (err) {
184
- const message = err instanceof Error ? err.message : "Path does not exist.";
190
+ const message = err instanceof Error ? err.message : 'Path does not exist.';
185
191
  sentryScanRoot = resolvedScanRoot;
186
192
  await (0, scan_sentry_1.reportScanCliError)({
187
193
  error: err,
188
194
  scanRoot: sentryScanRoot,
189
- failurePhase: "resolve_path",
190
- failureCode: "path_not_found",
195
+ failurePhase: 'resolve_path',
196
+ failureCode: 'path_not_found',
191
197
  });
192
198
  // eslint-disable-next-line no-console
193
199
  console.error(`[scan] error: ${message}`);
194
200
  process.exitCode = 2;
195
201
  return;
196
202
  }
197
- const [{ createDefaultScanConfiguration }, { runScanPipeline }, { buildDiagramGraphFromScanResult }] = await Promise.all([
198
- Promise.resolve().then(() => __importStar(require("./core/pipeline/orchestrator"))),
199
- Promise.resolve().then(() => __importStar(require("./core/pipeline/scan-pipeline"))),
200
- Promise.resolve().then(() => __importStar(require("./core/pipeline/graph-mapping"))),
203
+ const [{ createDefaultScanConfiguration }, { runScanPipeline }, { buildDiagramGraphFromScanResult },] = await Promise.all([
204
+ Promise.resolve().then(() => __importStar(require('./core/pipeline/orchestrator'))),
205
+ Promise.resolve().then(() => __importStar(require('./core/pipeline/scan-pipeline'))),
206
+ Promise.resolve().then(() => __importStar(require('./core/pipeline/graph-mapping'))),
201
207
  ]);
202
208
  if (isInteractive) {
203
209
  // eslint-disable-next-line no-console
@@ -205,7 +211,7 @@ function createProgram() {
205
211
  }
206
212
  const flags = {
207
213
  exclude: options.exclude,
208
- minimumConfidence: typeof options.minimumConfidence === "string"
214
+ minimumConfidence: typeof options.minimumConfidence === 'string'
209
215
  ? Number(options.minimumConfidence)
210
216
  : undefined,
211
217
  language: options.language,
@@ -213,11 +219,11 @@ function createProgram() {
213
219
  projectName: options.projectName,
214
220
  terraformJson: options.terraformJson,
215
221
  terraformPlan: options.terraformPlan,
216
- terraformStackSectionPathDepth: typeof options.terraformStackSectionPathDepth === "string"
222
+ terraformStackSectionPathDepth: typeof options.terraformStackSectionPathDepth === 'string'
217
223
  ? Number(options.terraformStackSectionPathDepth)
218
224
  : undefined,
219
225
  noTerraformStackSectionAuto: options.noTerraformStackSectionAuto,
220
- monorepoPackageSectionPathDepth: typeof options.monorepoPackageSectionPathDepth === "string"
226
+ monorepoPackageSectionPathDepth: typeof options.monorepoPackageSectionPathDepth === 'string'
221
227
  ? Number(options.monorepoPackageSectionPathDepth)
222
228
  : undefined,
223
229
  noMonorepoPackageSectionAuto: options.noMonorepoPackageSectionAuto,
@@ -225,19 +231,19 @@ function createProgram() {
225
231
  aiProvider: options.aiProvider,
226
232
  aiModel: options.aiModel,
227
233
  aiEndpoint: options.aiEndpoint,
228
- aiTemperature: typeof options.aiTemperature === "string"
234
+ aiTemperature: typeof options.aiTemperature === 'string'
229
235
  ? Number(options.aiTemperature)
230
236
  : undefined,
231
- aiMaxTokens: typeof options.aiMaxTokens === "string"
237
+ aiMaxTokens: typeof options.aiMaxTokens === 'string'
232
238
  ? Number(options.aiMaxTokens)
233
239
  : undefined,
234
- aiMaxModelCalls: typeof options.aiMaxCalls === "string"
240
+ aiMaxModelCalls: typeof options.aiMaxCalls === 'string'
235
241
  ? Number(options.aiMaxCalls)
236
242
  : undefined,
237
- aiBudgetTokens: typeof options.aiBudgetTokens === "string"
243
+ aiBudgetTokens: typeof options.aiBudgetTokens === 'string'
238
244
  ? Number(options.aiBudgetTokens)
239
245
  : undefined,
240
- aiMaxCandidatesPerAgent: typeof options.aiMaxCandidatesPerAgent === "string"
246
+ aiMaxCandidatesPerAgent: typeof options.aiMaxCandidatesPerAgent === 'string'
241
247
  ? Number(options.aiMaxCandidatesPerAgent)
242
248
  : undefined,
243
249
  aiInferenceScope: (0, inference_scope_1.parseAiInferenceScope)(options.aiInferenceScope),
@@ -255,15 +261,15 @@ function createProgram() {
255
261
  config.workspaceApiKey = workspaceApiKey;
256
262
  }
257
263
  const aiMode = (0, validate_scan_ai_1.resolveAiMode)(config);
258
- const usesByok = aiMode === "byok";
264
+ const usesByok = aiMode === 'byok';
259
265
  sentryScanRoot = scanEntry.scanRootDir;
260
266
  sentryAiMode = aiMode;
261
267
  sentryAiProvider = config.aiProvider;
262
268
  // Quota preflight for platform billing. Structural-only scans (AI off) do not use quota API.
263
269
  if (workspaceApiKey && !usesByok && config.enableAiInference) {
264
270
  const [{ cliScanPreflight }, { estimateScanFootprint }] = await Promise.all([
265
- Promise.resolve().then(() => __importStar(require("./platform-api/scan-quota-client"))),
266
- Promise.resolve().then(() => __importStar(require("./platform-api/estimate-scan-footprint"))),
271
+ Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client'))),
272
+ Promise.resolve().then(() => __importStar(require('./platform-api/estimate-scan-footprint'))),
267
273
  ]);
268
274
  const footprint = await estimateScanFootprint(scanEntry.scanRootDir, config.excludePaths ?? []);
269
275
  const preflight = await cliScanPreflight({
@@ -283,8 +289,8 @@ function createProgram() {
283
289
  // budget above the configured default (or user override).
284
290
  config.aiBudgetTokens = Math.min(config.aiBudgetTokens ?? 12_000, preflight.suggestedAiBudgetTokens);
285
291
  }
286
- if (preflight.aiDelivery === "platform_proxy") {
287
- config.aiMode = "platform";
292
+ if (preflight.aiDelivery === 'platform_proxy') {
293
+ config.aiMode = 'platform';
288
294
  }
289
295
  if (isInteractive) {
290
296
  // eslint-disable-next-line no-console
@@ -293,9 +299,10 @@ function createProgram() {
293
299
  }
294
300
  else if (!workspaceApiKey &&
295
301
  !usesByok &&
302
+ aiMode !== "hosted_worker" &&
296
303
  config.enableAiInference) {
297
304
  try {
298
- const { cliAnonymousAiSession } = await Promise.resolve().then(() => __importStar(require("./platform-api/anonymous-ai-session-client")));
305
+ const { cliAnonymousAiSession } = await Promise.resolve().then(() => __importStar(require('./platform-api/anonymous-ai-session-client')));
299
306
  const session = await cliAnonymousAiSession({
300
307
  projectName: config.projectName,
301
308
  });
@@ -307,8 +314,8 @@ function createProgram() {
307
314
  // Applying it as the working budget caused scans to burn ~100k tokens.
308
315
  config.aiBudgetTokens = Math.min(config.aiBudgetTokens ?? 12_000, session.suggestedAiBudgetTokens);
309
316
  }
310
- if (session.aiDelivery === "platform_proxy") {
311
- config.aiMode = "platform";
317
+ if (session.aiDelivery === 'platform_proxy') {
318
+ config.aiMode = 'platform';
312
319
  }
313
320
  if (isInteractive) {
314
321
  // eslint-disable-next-line no-console
@@ -316,10 +323,10 @@ function createProgram() {
316
323
  }
317
324
  }
318
325
  catch (anonSessionError) {
319
- const { CliAnonymousIpLimitError } = await Promise.resolve().then(() => __importStar(require("./platform-api/anonymous-ai-session-client")));
326
+ const { CliAnonymousIpLimitError } = await Promise.resolve().then(() => __importStar(require('./platform-api/anonymous-ai-session-client')));
320
327
  const message = anonSessionError instanceof Error
321
328
  ? anonSessionError.message
322
- : "Anonymous AI session failed.";
329
+ : 'Anonymous AI session failed.';
323
330
  // eslint-disable-next-line no-console
324
331
  console.error(`[scan] ${message}`);
325
332
  process.exitCode =
@@ -330,28 +337,28 @@ function createProgram() {
330
337
  const configValidation = (0, scan_config_schema_1.validateScanConfiguration)(config);
331
338
  if (!configValidation.ok) {
332
339
  await (0, scan_sentry_1.reportScanCliError)({
333
- error: configValidation.errors.join("\n"),
340
+ error: configValidation.errors.join('\n'),
334
341
  scanRoot: sentryScanRoot,
335
342
  jobId: cliQuotaJobId,
336
343
  aiMode: sentryAiMode,
337
344
  aiProvider: sentryAiProvider,
338
- failurePhase: "config_validation",
339
- failureCode: "invalid_configuration",
345
+ failurePhase: 'config_validation',
346
+ failureCode: 'invalid_configuration',
340
347
  });
341
348
  // eslint-disable-next-line no-console
342
- console.error(`[scan] invalid configuration:\n${configValidation.errors.map((e) => ` - ${e}`).join("\n")}`);
349
+ console.error(`[scan] invalid configuration:\n${configValidation.errors.map((e) => ` - ${e}`).join('\n')}`);
343
350
  process.exitCode = 2;
344
351
  return;
345
352
  }
346
353
  if (isInteractive && warnings.length > 0) {
347
354
  // eslint-disable-next-line no-console
348
- console.warn(`[scan] warnings:\n${warnings.map((w) => ` - ${w}`).join("\n")}`);
355
+ console.warn(`[scan] warnings:\n${warnings.map((w) => ` - ${w}`).join('\n')}`);
349
356
  }
350
- const { scanResult } = await runScanPipeline(resolvedScanRoot, config, (progress) => {
357
+ const { scanResult, redFlags } = await runScanPipeline(resolvedScanRoot, config, (progress) => {
351
358
  if (!isInteractive)
352
359
  return;
353
360
  // eslint-disable-next-line no-console
354
- console.log(`[scan] ${progress.phase}: ${progress.message ?? ""}`.trim());
361
+ console.log(`[scan] ${progress.phase}: ${progress.message ?? ''}`.trim());
355
362
  });
356
363
  if (scanResult.structuralEnrichmentSummary) {
357
364
  const st = scanResult.structuralEnrichmentSummary;
@@ -365,37 +372,41 @@ function createProgram() {
365
372
  // Always show real provider token usage (budget_cap is only a ceiling, not cost).
366
373
  // eslint-disable-next-line no-console
367
374
  console.log(`[scan] ai-usage: provider_calls=${s.providerCalls} tokens_in=${s.inputTokens} tokens_out=${s.outputTokens} tokens_total=${s.totalTokens}` +
368
- (typeof s.estimatedCostUsd === "number"
375
+ (typeof s.estimatedCostUsd === 'number'
369
376
  ? ` estimated_cost_usd=${formatUsd(s.estimatedCostUsd)}`
370
- : ""));
377
+ : ''));
371
378
  if (options.aiVerbose && scanResult.aiInferenceProposalDetails) {
372
379
  printAiInferenceVerbose(scanResult.aiInferenceProposalDetails);
373
380
  }
374
381
  }
375
382
  for (const w of scanResult.warnings ?? []) {
376
- if (w.startsWith("ai-provider:")) {
383
+ if (w.startsWith('ai-provider:')) {
377
384
  await (0, scan_sentry_1.reportScanCliError)({
378
385
  error: w,
379
386
  scanRoot: sentryScanRoot,
380
387
  jobId: cliQuotaJobId,
381
388
  aiMode: sentryAiMode,
382
389
  aiProvider: sentryAiProvider,
383
- failurePhase: "ai_provider",
384
- failureCode: "ai_provider_warning",
390
+ failurePhase: 'ai_provider',
391
+ failureCode: 'ai_provider_warning',
385
392
  });
386
393
  // eslint-disable-next-line no-console
387
394
  console.warn(`[scan] ${w}`);
388
395
  }
396
+ else if (w.startsWith('red-flag:')) {
397
+ // eslint-disable-next-line no-console
398
+ console.warn(`[scan] ${w}`);
399
+ }
389
400
  }
390
401
  if (scanResult.errors?.length) {
391
402
  await (0, scan_sentry_1.reportScanCliError)({
392
- error: scanResult.errors.join("\n"),
403
+ error: scanResult.errors.join('\n'),
393
404
  scanRoot: sentryScanRoot,
394
405
  jobId: cliQuotaJobId,
395
406
  aiMode: sentryAiMode,
396
407
  aiProvider: sentryAiProvider,
397
- failurePhase: "scan_pipeline",
398
- failureCode: "scan_errors",
408
+ failurePhase: 'scan_pipeline',
409
+ failureCode: 'scan_errors',
399
410
  extra: { errorCount: scanResult.errors.length },
400
411
  });
401
412
  process.exitCode = 1;
@@ -411,20 +422,20 @@ function createProgram() {
411
422
  jobId: cliQuotaJobId,
412
423
  aiMode: sentryAiMode,
413
424
  aiProvider: sentryAiProvider,
414
- failurePhase: "diagram_graph",
415
- failureCode: "graph_build_failed",
425
+ failurePhase: 'diagram_graph',
426
+ failureCode: 'graph_build_failed',
416
427
  });
417
428
  if (isInteractive) {
418
429
  const message = graphError instanceof Error
419
430
  ? graphError.message
420
- : "Unknown error while building diagram graph.";
431
+ : 'Unknown error while building diagram graph.';
421
432
  // eslint-disable-next-line no-console
422
433
  console.error(`[scan] warning: unable to build diagram graph: ${message}`);
423
434
  }
424
435
  process.exitCode = 1;
425
436
  }
426
437
  if (diagramGraph) {
427
- const dataflowOutputPath = path_1.default.resolve(process.cwd(), options.output ?? "dataflow.json");
438
+ const dataflowOutputPath = path_1.default.resolve(process.cwd(), options.output ?? 'dataflow.json');
428
439
  const resolvedProjectName = config.projectName?.trim() ||
429
440
  path_1.default.basename(scanEntry.scanRootDir);
430
441
  try {
@@ -433,6 +444,7 @@ function createProgram() {
433
444
  graph: diagramGraph,
434
445
  outputPath: dataflowOutputPath,
435
446
  projectName: resolvedProjectName,
447
+ redFlags,
436
448
  });
437
449
  // Always print a short message so non-interactive callers and
438
450
  // tests can rely on it.
@@ -442,22 +454,22 @@ function createProgram() {
442
454
  (0, upload_env_1.resolveSkipAutoUpload)(process.env);
443
455
  if (!skipAutoUpload) {
444
456
  try {
445
- const { runDataflowUpload } = await Promise.resolve().then(() => __importStar(require("./upload/run-upload")));
446
- const dataflowWrapper = (0, json_1.buildDataflowWrapper)(scanResult, diagramGraph, { projectName: resolvedProjectName });
457
+ const { runDataflowUpload } = await Promise.resolve().then(() => __importStar(require('./upload/run-upload')));
458
+ const dataflowWrapper = (0, json_1.buildDataflowWrapper)(scanResult, diagramGraph, { projectName: resolvedProjectName, redFlags });
447
459
  await runDataflowUpload({
448
460
  apiKey: workspaceApiKey,
449
461
  dataflow: dataflowWrapper,
450
462
  projectName: resolvedProjectName,
451
463
  scanJobId: cliQuotaJobId,
452
- logPrefix: "[scan]",
464
+ logPrefix: '[scan]',
453
465
  cliUsageSessionId: usageSessionId,
454
- command: "scan",
466
+ command: 'scan',
455
467
  });
456
468
  }
457
469
  catch (uploadError) {
458
470
  const uploadMessage = uploadError instanceof Error
459
471
  ? uploadError.message
460
- : "Unknown upload error.";
472
+ : 'Unknown upload error.';
461
473
  // eslint-disable-next-line no-console
462
474
  console.error(`[scan] Auto-upload failed: ${uploadMessage}`);
463
475
  }
@@ -470,42 +482,44 @@ function createProgram() {
470
482
  jobId: cliQuotaJobId,
471
483
  aiMode: sentryAiMode,
472
484
  aiProvider: sentryAiProvider,
473
- failurePhase: "dataflow_output",
474
- failureCode: "dataflow_write_failed",
485
+ failurePhase: 'dataflow_output',
486
+ failureCode: 'dataflow_write_failed',
475
487
  });
476
488
  const message = dataflowError instanceof Error
477
489
  ? dataflowError.message
478
- : "Unknown error while writing dataflow.json.";
490
+ : 'Unknown error while writing dataflow.json.';
479
491
  // eslint-disable-next-line no-console
480
492
  console.error(`[scan] error: failed to write dataflow.json: ${message}`);
481
493
  process.exitCode = 1;
482
494
  }
483
495
  }
484
496
  if (platformQuotaApiKey && cliQuotaJobId) {
485
- const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require("./platform-api/scan-quota-client")));
497
+ const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
486
498
  const exitFailed = (process.exitCode ?? 0) !== 0;
487
- const platformAiMode = (0, validate_scan_ai_1.resolveAiMode)(config) === "platform";
499
+ const platformAiMode = (0, validate_scan_ai_1.resolveAiMode)(config) === 'platform';
488
500
  await cliScanComplete({
489
501
  apiKey: platformQuotaApiKey,
490
502
  jobId: cliQuotaJobId,
491
- status: exitFailed ? "failed" : "completed",
503
+ status: exitFailed ? 'failed' : 'completed',
492
504
  aiTokensUsed: platformAiMode
493
505
  ? 0
494
506
  : (scanResult.aiInferenceSummary?.totalTokens ?? 0),
495
- failureCode: exitFailed ? "scan_failed" : undefined,
496
- failureMessage: exitFailed ? "CLI scan did not complete successfully" : undefined,
507
+ failureCode: exitFailed ? 'scan_failed' : undefined,
508
+ failureMessage: exitFailed
509
+ ? 'CLI scan did not complete successfully'
510
+ : undefined,
497
511
  });
498
512
  quotaCompletionReported = true;
499
513
  if (isInteractive) {
500
514
  // eslint-disable-next-line no-console
501
- console.log("[scan] Scan finished — you can start a new scan now.");
515
+ console.log('[scan] Scan finished — you can start a new scan now.');
502
516
  }
503
517
  }
504
518
  }
505
519
  catch (err) {
506
- const message = err instanceof Error ? err.message : "Unknown error during scan.";
520
+ const message = err instanceof Error ? err.message : 'Unknown error during scan.';
507
521
  fallbackFailureMessage = message;
508
- const { CliScanQuotaExceededError, CliScanAlreadyRunningError } = await Promise.resolve().then(() => __importStar(require("./platform-api/scan-quota-client")));
522
+ const { CliScanQuotaExceededError, CliScanAlreadyRunningError } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
509
523
  const quotaBlocked = err instanceof CliScanQuotaExceededError;
510
524
  const scanInProgress = err instanceof CliScanAlreadyRunningError;
511
525
  await (0, scan_sentry_1.reportScanCliError)({
@@ -514,12 +528,12 @@ function createProgram() {
514
528
  jobId: cliQuotaJobId,
515
529
  aiMode: sentryAiMode,
516
530
  aiProvider: sentryAiProvider,
517
- failurePhase: quotaBlocked || scanInProgress ? "preflight" : "scan_command",
531
+ failurePhase: quotaBlocked || scanInProgress ? 'preflight' : 'scan_command',
518
532
  failureCode: quotaBlocked
519
- ? "scan_quota_exceeded"
533
+ ? 'scan_quota_exceeded'
520
534
  : scanInProgress
521
- ? "scan_already_running"
522
- : "scan_exception",
535
+ ? 'scan_already_running'
536
+ : 'scan_exception',
523
537
  });
524
538
  // eslint-disable-next-line no-console
525
539
  console.error(quotaBlocked
@@ -533,28 +547,30 @@ function createProgram() {
533
547
  const scanFailed = (process.exitCode ?? 0) !== 0;
534
548
  await (0, telemetry_client_1.reportCliUsageEvent)({
535
549
  sessionId: usageSessionId,
536
- event: scanFailed ? "scan_failed" : "scan_succeeded",
537
- command: "scan",
550
+ event: scanFailed ? 'scan_failed' : 'scan_succeeded',
551
+ command: 'scan',
538
552
  hasApiKey: Boolean(workspaceApiKey),
539
553
  apiKey: workspaceApiKey,
540
554
  cliVersion: package_json_1.default.version,
541
- errorCode: scanFailed ? "scan_failed" : undefined,
555
+ errorCode: scanFailed ? 'scan_failed' : undefined,
542
556
  errorMessage: scanFailed ? fallbackFailureMessage : undefined,
543
557
  });
544
- if (platformQuotaApiKey && cliQuotaJobId && !quotaCompletionReported) {
558
+ if (platformQuotaApiKey &&
559
+ cliQuotaJobId &&
560
+ !quotaCompletionReported) {
545
561
  try {
546
- const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require("./platform-api/scan-quota-client")));
562
+ const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
547
563
  await cliScanComplete({
548
564
  apiKey: platformQuotaApiKey,
549
565
  jobId: cliQuotaJobId,
550
- status: "failed",
551
- failureCode: "scan_failed",
566
+ status: 'failed',
567
+ failureCode: 'scan_failed',
552
568
  failureMessage: fallbackFailureMessage,
553
569
  });
554
570
  quotaCompletionReported = true;
555
571
  if (isInteractive) {
556
572
  // eslint-disable-next-line no-console
557
- console.log("[scan] Scan finished — you can start a new scan now.");
573
+ console.log('[scan] Scan finished — you can start a new scan now.');
558
574
  }
559
575
  }
560
576
  catch {
@@ -564,64 +580,65 @@ function createProgram() {
564
580
  }
565
581
  });
566
582
  program
567
- .command("upload <file>")
568
- .description("Upload a dataflow.json file to the dashboard as an import preview")
569
- .option("--project-name <name>", "Assessment name shown in the preview (default: from file metadata if present)")
570
- .option("--workspace-api-key <key>", "DataParade workspace API key (env: DATAPARADE_WORKSPACE_API_KEY)")
571
- .option("--api-key <key>", "(deprecated) alias for --workspace-api-key")
583
+ .command('upload <file>')
584
+ .description('Upload a dataflow.json file to the dashboard as an import preview')
585
+ .option('--project-name <name>', 'Assessment name shown in the preview (default: from file metadata if present)')
586
+ .option('--workspace-api-key <key>', 'DataParade workspace API key (env: DATAPARADE_WORKSPACE_API_KEY)')
587
+ .option('--api-key <key>', '(deprecated) alias for --workspace-api-key')
572
588
  .action(async (file, options) => {
573
589
  const apiKey = options.workspaceApiKey?.trim() ||
574
590
  options.apiKey?.trim() ||
575
591
  (0, scan_env_1.resolveWorkspaceApiKey)(process.env);
576
592
  const usageSessionId = (0, crypto_1.randomUUID)();
577
- const filePath = path_1.default.resolve(process.cwd(), file || "dataflow.json");
593
+ const filePath = path_1.default.resolve(process.cwd(), file || 'dataflow.json');
578
594
  let dataflow;
579
595
  try {
580
- const { readFileSync } = await Promise.resolve().then(() => __importStar(require("fs")));
581
- dataflow = JSON.parse(readFileSync(filePath, "utf8"));
596
+ const { readFileSync } = await Promise.resolve().then(() => __importStar(require('fs')));
597
+ dataflow = JSON.parse(readFileSync(filePath, 'utf8'));
582
598
  }
583
599
  catch (err) {
584
- const message = err instanceof Error ? err.message : "Failed to read dataflow.json";
600
+ const message = err instanceof Error ? err.message : 'Failed to read dataflow.json';
585
601
  // eslint-disable-next-line no-console
586
602
  console.error(`[upload] error: ${message}`);
587
603
  process.exitCode = 1;
588
604
  return;
589
605
  }
590
606
  let projectName = options.projectName?.trim();
591
- if (!projectName && dataflow && typeof dataflow === "object") {
607
+ if (!projectName && dataflow && typeof dataflow === 'object') {
592
608
  const meta = dataflow
593
609
  .metadata;
594
- if (typeof meta?.projectName === "string" && meta.projectName.trim()) {
610
+ if (typeof meta?.projectName === 'string' &&
611
+ meta.projectName.trim()) {
595
612
  projectName = meta.projectName.trim();
596
613
  }
597
614
  }
598
615
  try {
599
- const { runDataflowUpload } = await Promise.resolve().then(() => __importStar(require("./upload/run-upload")));
616
+ const { runDataflowUpload } = await Promise.resolve().then(() => __importStar(require('./upload/run-upload')));
600
617
  await runDataflowUpload({
601
618
  apiKey,
602
619
  dataflow,
603
620
  projectName,
604
621
  cliUsageSessionId: usageSessionId,
605
- command: "upload",
622
+ command: 'upload',
606
623
  });
607
624
  }
608
625
  catch (err) {
609
- const message = err instanceof Error ? err.message : "Upload failed.";
626
+ const message = err instanceof Error ? err.message : 'Upload failed.';
610
627
  // eslint-disable-next-line no-console
611
628
  console.error(`[upload] error: ${message}`);
612
629
  process.exitCode = 1;
613
630
  }
614
631
  });
615
632
  program
616
- .command("config")
617
- .description("View the effective configuration for the current project")
618
- .argument("[path]", "Project directory (default: current working directory)")
633
+ .command('config')
634
+ .description('View the effective configuration for the current project')
635
+ .argument('[path]', 'Project directory (default: current working directory)')
619
636
  .action(async (pathArg) => {
620
637
  try {
621
638
  const [{ createDefaultScanConfiguration }] = await Promise.all([
622
- Promise.resolve().then(() => __importStar(require("./core/pipeline/orchestrator"))),
639
+ Promise.resolve().then(() => __importStar(require('./core/pipeline/orchestrator'))),
623
640
  ]);
624
- const rootPathArg = pathArg?.trim() || ".";
641
+ const rootPathArg = pathArg?.trim() || '.';
625
642
  const resolvedRoot = path_1.default.resolve(process.cwd(), rootPathArg);
626
643
  let configCwd = resolvedRoot;
627
644
  try {
@@ -643,9 +660,9 @@ function createProgram() {
643
660
  catch (err) {
644
661
  const message = err instanceof Error
645
662
  ? err.message
646
- : "Unknown error while loading configuration.";
663
+ : 'Unknown error while loading configuration.';
647
664
  // eslint-disable-next-line no-console
648
- console.error("Failed to read configuration:", message);
665
+ console.error('Failed to read configuration:', message);
649
666
  process.exitCode = 1;
650
667
  }
651
668
  });