@dataparade/cli 0.0.21 → 0.0.22

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.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataparade/cli",
3
- "version": "0.0.21",
3
+ "version": "0.0.22",
4
4
  "description": "dataPARADE CLI — scan codebases for privacy and security data flows",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -1,5 +1,5 @@
1
- import type { AiProposal, InferencePlannerResult, RunInferencePipelineInput, AiInferenceCandidate, AiProviderId, AiInferenceUsageSummary } from "./types";
2
- import type { PlatformProxyProviderConfig } from "./providers/platform-proxy-provider";
1
+ import type { AiProposal, InferencePlannerResult, RunInferencePipelineInput, AiInferenceCandidate, AiProviderId, AiInferenceUsageSummary } from './types';
2
+ import type { PlatformProxyProviderConfig } from './providers/platform-proxy-provider';
3
3
  export interface AgentOrchestratorOptions {
4
4
  provider: AiProviderId;
5
5
  model: string;
@@ -21,6 +21,12 @@ export interface AgentOrchestratorOptions {
21
21
  /** Hosted scan in VPC worker: loopback proxy → scan-cli-ai-helper Lambda. */
22
22
  hostedWorkerInferProxyUrl?: string;
23
23
  }
24
+ /**
25
+ * Hosted infer proxy rejects prompts over 512 KB, and the request body re-escapes
26
+ * the prompt JSON, so keep a margin below that.
27
+ */
28
+ export declare const MAX_PROVIDER_PROMPT_BYTES = 400000;
29
+ export declare function isPromptTooLargeError(err: unknown): boolean;
24
30
  export declare function generateAgenticProposals(input: RunInferencePipelineInput, plan: InferencePlannerResult, candidates: AiInferenceCandidate[], options: AgentOrchestratorOptions): Promise<{
25
31
  proposals: Array<{
26
32
  id: string;
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_PROVIDER_PROMPT_BYTES = void 0;
4
+ exports.isPromptTooLargeError = isPromptTooLargeError;
3
5
  exports.generateAgenticProposals = generateAgenticProposals;
4
6
  const agents_1 = require("./agents");
5
7
  const provider_prompt_1 = require("./provider-prompt");
@@ -15,6 +17,24 @@ const PROPERTY_AGENT_SLICE_SIZE = 12;
15
17
  const TP_AGENT_MAX_ROUNDS = 3;
16
18
  const TP_AGENT_MAX_FILES = 8;
17
19
  const TP_AGENT_SEARCH_LIMIT = 6;
20
+ /**
21
+ * Hosted infer proxy rejects prompts over 512 KB, and the request body re-escapes
22
+ * the prompt JSON, so keep a margin below that.
23
+ */
24
+ exports.MAX_PROVIDER_PROMPT_BYTES = 400_000;
25
+ const PROMPT_TOO_LARGE_RE = /request_body_too_large|prompt too large|prompt is too long|context_length_exceeded|maximum context length|\(413\)/i;
26
+ function promptBytes(prompt) {
27
+ return Buffer.byteLength(prompt, 'utf8');
28
+ }
29
+ function isPromptTooLargeError(err) {
30
+ const message = err instanceof Error ? err.message : String(err);
31
+ return PROMPT_TOO_LARGE_RE.test(message);
32
+ }
33
+ function warnSkippedProviderCall(agent, detail) {
34
+ if (!(0, provider_contract_1.aiDebugEnabled)())
35
+ return;
36
+ console.warn(`[dataparade-ai] ${agent} provider call skipped: ${detail}`);
37
+ }
18
38
  const IMPORT_RE = /\bimport\s+(?:[^"']+from\s+)?["']([^"']+)["']|\brequire\(["']([^"']+)["']\)/g;
19
39
  function chunkCandidates(queue, size) {
20
40
  const n = Math.max(1, Math.floor(size));
@@ -27,10 +47,10 @@ function chunkCandidates(queue, size) {
27
47
  function shouldCallProviderForAgent(agent) {
28
48
  // Flow patches are now merge-gated to intra-section changes only, so provider
29
49
  // calls can safely support both property and flow-oriented queues.
30
- return (agent === "tpAgent" ||
31
- agent === "propertyAgent" ||
32
- agent === "directionAgent" ||
33
- agent === "interactionAgent");
50
+ return (agent === 'tpAgent' ||
51
+ agent === 'propertyAgent' ||
52
+ agent === 'directionAgent' ||
53
+ agent === 'interactionAgent');
34
54
  }
35
55
  function estimateTokens(text) {
36
56
  // Rough but stable approximation used only for budget gating.
@@ -61,7 +81,7 @@ function gatherSeedPathsForCandidate(candidate, components) {
61
81
  return [];
62
82
  const out = new Set();
63
83
  const sectionId = component.properties.section_id;
64
- if (typeof sectionId === "string" && sectionId.trim())
84
+ if (typeof sectionId === 'string' && sectionId.trim())
65
85
  out.add(sectionId.trim());
66
86
  for (const loc of component.sourceLocations ?? []) {
67
87
  if (loc.filePath?.trim())
@@ -76,11 +96,18 @@ function gatherSeedPathsForCandidate(candidate, components) {
76
96
  }
77
97
  function gatherSearchTerms(componentName) {
78
98
  const base = componentName.trim().toLowerCase();
79
- const terms = new Set([base, "auth", "token", "api", "storage", "database"]);
80
- if (base.includes("supabase")) {
81
- terms.add("supabase");
82
- terms.add("storage.from");
83
- terms.add("create_client");
99
+ const terms = new Set([
100
+ base,
101
+ 'auth',
102
+ 'token',
103
+ 'api',
104
+ 'storage',
105
+ 'database',
106
+ ]);
107
+ if (base.includes('supabase')) {
108
+ terms.add('supabase');
109
+ terms.add('storage.from');
110
+ terms.add('create_client');
84
111
  }
85
112
  return [...terms].filter((t) => t.length >= 3);
86
113
  }
@@ -102,27 +129,34 @@ function pickUniqueSearchMatches(matches, alreadyReviewed, limit) {
102
129
  return [...preferred, ...fallback].slice(0, max);
103
130
  }
104
131
  function resolveRelativeImportPath(fromFile, rawImport) {
105
- if (!rawImport.startsWith("."))
132
+ if (!rawImport.startsWith('.'))
106
133
  return undefined;
107
- const normalizedFrom = fromFile.replace(/\\/g, "/");
108
- const parts = normalizedFrom.split("/");
134
+ const normalizedFrom = fromFile.replace(/\\/g, '/');
135
+ const parts = normalizedFrom.split('/');
109
136
  parts.pop();
110
- for (const piece of rawImport.split("/")) {
111
- if (piece === "." || piece === "")
137
+ for (const piece of rawImport.split('/')) {
138
+ if (piece === '.' || piece === '')
112
139
  continue;
113
- if (piece === "..")
140
+ if (piece === '..')
114
141
  parts.pop();
115
142
  else
116
143
  parts.push(piece);
117
144
  }
118
- const base = parts.join("/");
119
- const candidates = [base, `${base}.ts`, `${base}.js`, `${base}.py`, `${base}/index.ts`, `${base}/index.js`];
145
+ const base = parts.join('/');
146
+ const candidates = [
147
+ base,
148
+ `${base}.ts`,
149
+ `${base}.js`,
150
+ `${base}.py`,
151
+ `${base}/index.ts`,
152
+ `${base}/index.js`,
153
+ ];
120
154
  return candidates[0];
121
155
  }
122
156
  function expandImportPaths(filePath, content) {
123
157
  const out = [];
124
158
  for (const match of content.matchAll(IMPORT_RE)) {
125
- const rawImport = (match[1] ?? match[2] ?? "").trim();
159
+ const rawImport = (match[1] ?? match[2] ?? '').trim();
126
160
  if (!rawImport)
127
161
  continue;
128
162
  const rel = resolveRelativeImportPath(filePath, rawImport);
@@ -140,7 +174,7 @@ function logToolStep(candidateId, step) {
140
174
  const touched = step.filesTouched?.length ?? 0;
141
175
  const stats = step.stats && Object.keys(step.stats).length > 0
142
176
  ? ` stats=${JSON.stringify(step.stats)}`
143
- : "";
177
+ : '';
144
178
  console.warn(`[dataparade-ai] tpAgent tool call candidate=${candidateId} round=${step.round} action=${step.action} files_touched=${touched} detail="${step.detail}"${stats}`);
145
179
  }
146
180
  async function generateAgenticProposals(input, plan, candidates, options) {
@@ -164,6 +198,28 @@ async function generateAgenticProposals(input, plan, candidates, options) {
164
198
  model: options.model,
165
199
  apiKey: options.apiKey,
166
200
  });
201
+ const inferUnlessTooLarge = async (agent, prompt) => {
202
+ try {
203
+ return await (0, langsmith_tracing_1.traceDataparadeProviderInfer)({
204
+ providerId: options.provider,
205
+ model: options.model,
206
+ run: () => provider.infer({
207
+ prompt,
208
+ model: options.model,
209
+ endpoint: options.endpoint,
210
+ apiKey: options.apiKey,
211
+ maxTokens: options.maxTokens,
212
+ temperature: options.temperature,
213
+ }),
214
+ });
215
+ }
216
+ catch (err) {
217
+ if (!isPromptTooLargeError(err))
218
+ throw err;
219
+ warnSkippedProviderCall(agent, err instanceof Error ? err.message : String(err));
220
+ return null;
221
+ }
222
+ };
167
223
  const generated = [];
168
224
  const agenticTrace = [];
169
225
  const aggregateUsage = {
@@ -175,12 +231,12 @@ async function generateAgenticProposals(input, plan, candidates, options) {
175
231
  };
176
232
  let sequence = 0;
177
233
  for (const queue of plan.queues) {
178
- if (!skipStructural && queue.agent === "tpAgent") {
234
+ if (!skipStructural && queue.agent === 'tpAgent') {
179
235
  for (const candidate of queue.queue) {
180
236
  if (!candidate.componentId)
181
237
  continue;
182
238
  const component = input.components.find((item) => item.id === candidate.componentId);
183
- if (!component || component.type !== "third_party")
239
+ if (!component || component.type !== 'third_party')
184
240
  continue;
185
241
  const patch = (0, third_party_evidence_1.buildThirdPartyHeuristicProposal)({
186
242
  candidate,
@@ -206,7 +262,7 @@ async function generateAgenticProposals(input, plan, candidates, options) {
206
262
  if (!llmEnabled || !shouldCallProviderForAgent(queue.agent)) {
207
263
  continue;
208
264
  }
209
- if (queue.agent === "tpAgent") {
265
+ if (queue.agent === 'tpAgent') {
210
266
  const maxCalls = Math.max(0, Math.floor(queue.maxModelCalls));
211
267
  const maxCandidates = maxCalls === 0 ? 0 : Math.min(queue.queue.length, maxCalls);
212
268
  const tpCandidates = queue.queue.slice(0, maxCandidates);
@@ -226,8 +282,8 @@ async function generateAgenticProposals(input, plan, candidates, options) {
226
282
  reviewed.add(p);
227
283
  appendTraceStep(traceSteps, {
228
284
  round: 0,
229
- action: "seed_files",
230
- detail: "Seed files from detectedFrom/sourceLocations/section_id",
285
+ action: 'seed_files',
286
+ detail: 'Seed files from detectedFrom/sourceLocations/section_id',
231
287
  filesTouched: [...reviewed],
232
288
  stats: { seedCount: reviewed.size },
233
289
  });
@@ -240,7 +296,7 @@ async function generateAgenticProposals(input, plan, candidates, options) {
240
296
  reviewed.add(match.filePath);
241
297
  appendTraceStep(traceSteps, {
242
298
  round: 0,
243
- action: "search_text",
299
+ action: 'search_text',
244
300
  detail: `Search term: ${term}`,
245
301
  filesTouched: matches.map((m) => m.filePath),
246
302
  stats: { hits: matches.length },
@@ -262,29 +318,32 @@ async function generateAgenticProposals(input, plan, candidates, options) {
262
318
  preferredPaths,
263
319
  }));
264
320
  const estimatedTokens = estimateTokens(prompt) + Math.max(1, options.maxTokens ?? 8192);
265
- if (queueBudget > 0 && queueBudgetSpent + estimatedTokens > queueBudget) {
321
+ if (queueBudget > 0 &&
322
+ queueBudgetSpent + estimatedTokens > queueBudget) {
266
323
  appendTraceStep(traceSteps, {
267
324
  round,
268
- action: "provider_infer",
269
- detail: "Skipped provider inference due to queue budget limit",
325
+ action: 'provider_infer',
326
+ detail: 'Skipped provider inference due to queue budget limit',
270
327
  filesTouched: preferredPaths,
271
328
  stats: { estimatedTokens, queueBudget, queueBudgetSpent },
272
329
  });
273
330
  logToolStep(candidate.id, traceSteps[traceSteps.length - 1]);
274
331
  break;
275
332
  }
276
- const providerResult = await (0, langsmith_tracing_1.traceDataparadeProviderInfer)({
277
- providerId: options.provider,
278
- model: options.model,
279
- run: () => provider.infer({
280
- prompt,
281
- model: options.model,
282
- endpoint: options.endpoint,
283
- apiKey: options.apiKey,
284
- maxTokens: options.maxTokens,
285
- temperature: options.temperature,
286
- }),
287
- });
333
+ const providerResult = promptBytes(prompt) > exports.MAX_PROVIDER_PROMPT_BYTES
334
+ ? null
335
+ : await inferUnlessTooLarge(queue.agent, prompt);
336
+ if (!providerResult) {
337
+ appendTraceStep(traceSteps, {
338
+ round,
339
+ action: 'provider_infer',
340
+ detail: 'Skipped provider inference because the prompt is too large',
341
+ filesTouched: preferredPaths,
342
+ stats: { promptBytes: promptBytes(prompt) },
343
+ });
344
+ logToolStep(candidate.id, traceSteps[traceSteps.length - 1]);
345
+ break;
346
+ }
288
347
  if (queueBudget > 0)
289
348
  queueBudgetSpent += estimatedTokens;
290
349
  if (providerResult.usage) {
@@ -292,9 +351,10 @@ async function generateAgenticProposals(input, plan, candidates, options) {
292
351
  aggregateUsage.inputTokens += providerResult.usage.inputTokens;
293
352
  aggregateUsage.outputTokens += providerResult.usage.outputTokens;
294
353
  aggregateUsage.totalTokens += providerResult.usage.totalTokens;
295
- if (typeof providerResult.usage.estimatedCostUsd === "number") {
354
+ if (typeof providerResult.usage.estimatedCostUsd === 'number') {
296
355
  aggregateUsage.estimatedCostUsd =
297
- (aggregateUsage.estimatedCostUsd ?? 0) + providerResult.usage.estimatedCostUsd;
356
+ (aggregateUsage.estimatedCostUsd ?? 0) +
357
+ providerResult.usage.estimatedCostUsd;
298
358
  }
299
359
  else {
300
360
  aggregateUsage.estimatedCostUsd = undefined;
@@ -302,10 +362,13 @@ async function generateAgenticProposals(input, plan, candidates, options) {
302
362
  }
303
363
  appendTraceStep(traceSteps, {
304
364
  round,
305
- action: "provider_infer",
306
- detail: "Provider inference call for current reviewed file set",
365
+ action: 'provider_infer',
366
+ detail: 'Provider inference call for current reviewed file set',
307
367
  filesTouched: preferredPaths,
308
- stats: { reviewedCount: preferredPaths.length, proposals: providerResult.proposals.length },
368
+ stats: {
369
+ reviewedCount: preferredPaths.length,
370
+ proposals: providerResult.proposals.length,
371
+ },
309
372
  });
310
373
  logToolStep(candidate.id, traceSteps[traceSteps.length - 1]);
311
374
  const acceptedThisRound = [];
@@ -331,7 +394,9 @@ async function generateAgenticProposals(input, plan, candidates, options) {
331
394
  const beforeExpand = reviewed.size;
332
395
  const filesForExpand = [...reviewed].slice(0, maxFiles);
333
396
  for (const fp of filesForExpand) {
334
- const fi = input.files ? (0, scan_paths_1.resolveScannedFileExact)(input.files, fp) : undefined;
397
+ const fi = input.files
398
+ ? (0, scan_paths_1.resolveScannedFileExact)(input.files, fp)
399
+ : undefined;
335
400
  if (!fi)
336
401
  continue;
337
402
  const imports = expandImportPaths(fi.path, fi.content);
@@ -350,8 +415,8 @@ async function generateAgenticProposals(input, plan, candidates, options) {
350
415
  const added = reviewed.size - beforeExpand;
351
416
  appendTraceStep(traceSteps, {
352
417
  round,
353
- action: "expand_imports",
354
- detail: "Expand import graph from reviewed files",
418
+ action: 'expand_imports',
419
+ detail: 'Expand import graph from reviewed files',
355
420
  filesTouched: [...reviewed],
356
421
  stats: { addedFiles: added, totalReviewed: reviewed.size },
357
422
  });
@@ -361,8 +426,8 @@ async function generateAgenticProposals(input, plan, candidates, options) {
361
426
  }
362
427
  appendTraceStep(traceSteps, {
363
428
  round: executedRounds,
364
- action: "finalize",
365
- detail: "Finalize accepted proposals for candidate",
429
+ action: 'finalize',
430
+ detail: 'Finalize accepted proposals for candidate',
366
431
  filesTouched: [...reviewed],
367
432
  stats: { finalProposalCount: finalProposals.length },
368
433
  });
@@ -386,8 +451,10 @@ async function generateAgenticProposals(input, plan, candidates, options) {
386
451
  continue;
387
452
  }
388
453
  // Non-tp agents stay in bounded prompt batches.
389
- const providerSlices = chunkCandidates(queue.queue, PROPERTY_AGENT_SLICE_SIZE);
390
- const preparedProviderCalls = providerSlices.map((slice) => {
454
+ const pendingSlices = chunkCandidates(queue.queue, PROPERTY_AGENT_SLICE_SIZE);
455
+ const preparedProviderCalls = [];
456
+ while (pendingSlices.length > 0) {
457
+ const slice = pendingSlices.shift();
391
458
  const prompt = JSON.stringify((0, provider_prompt_1.buildProviderPromptPayload)({
392
459
  agent: queue.agent,
393
460
  queue: slice,
@@ -396,9 +463,20 @@ async function generateAgenticProposals(input, plan, candidates, options) {
396
463
  sections: input.sections,
397
464
  files: input.files,
398
465
  }));
466
+ const bytes = promptBytes(prompt);
467
+ if (bytes > exports.MAX_PROVIDER_PROMPT_BYTES) {
468
+ if (slice.length > 1) {
469
+ const mid = Math.ceil(slice.length / 2);
470
+ pendingSlices.unshift(slice.slice(0, mid), slice.slice(mid));
471
+ }
472
+ else {
473
+ warnSkippedProviderCall(queue.agent, `prompt for ${slice[0].id} is ${bytes} bytes (limit ${exports.MAX_PROVIDER_PROMPT_BYTES})`);
474
+ }
475
+ continue;
476
+ }
399
477
  const estimatedTokens = estimateTokens(prompt) + Math.max(1, options.maxTokens ?? 8192);
400
- return { prompt, estimatedTokens };
401
- });
478
+ preparedProviderCalls.push({ prompt, estimatedTokens });
479
+ }
402
480
  const maxCalls = Math.max(0, Math.floor(queue.maxModelCalls));
403
481
  const callsWithinLimit = maxCalls === 0
404
482
  ? []
@@ -414,7 +492,7 @@ async function generateAgenticProposals(input, plan, candidates, options) {
414
492
  spent += call.estimatedTokens;
415
493
  }
416
494
  // Avoid starving property enrichment when estimated tokens are conservative.
417
- if (queue.agent === "propertyAgent" &&
495
+ if (queue.agent === 'propertyAgent' &&
418
496
  budgetedCalls.length === 0 &&
419
497
  callsWithinLimit.length > 0) {
420
498
  budgetedCalls.push(callsWithinLimit[0]);
@@ -425,27 +503,19 @@ async function generateAgenticProposals(input, plan, candidates, options) {
425
503
  budgetedCalls.push(...[]);
426
504
  }
427
505
  const providerConcurrency = Math.max(1, Math.floor(options.providerConcurrency ?? 1));
428
- const providerResults = await mapWithConcurrency(budgetedCalls, providerConcurrency, (call) => (0, langsmith_tracing_1.traceDataparadeProviderInfer)({
429
- providerId: options.provider,
430
- model: options.model,
431
- run: () => provider.infer({
432
- prompt: call.prompt,
433
- model: options.model,
434
- endpoint: options.endpoint,
435
- apiKey: options.apiKey,
436
- maxTokens: options.maxTokens,
437
- temperature: options.temperature,
438
- }),
439
- }));
506
+ const providerResults = await mapWithConcurrency(budgetedCalls, providerConcurrency, (call) => inferUnlessTooLarge(queue.agent, call.prompt));
440
507
  for (const providerResult of providerResults) {
508
+ if (!providerResult)
509
+ continue;
441
510
  if (providerResult.usage) {
442
511
  aggregateUsage.providerCalls += 1;
443
512
  aggregateUsage.inputTokens += providerResult.usage.inputTokens;
444
513
  aggregateUsage.outputTokens += providerResult.usage.outputTokens;
445
514
  aggregateUsage.totalTokens += providerResult.usage.totalTokens;
446
- if (typeof providerResult.usage.estimatedCostUsd === "number") {
515
+ if (typeof providerResult.usage.estimatedCostUsd === 'number') {
447
516
  aggregateUsage.estimatedCostUsd =
448
- (aggregateUsage.estimatedCostUsd ?? 0) + providerResult.usage.estimatedCostUsd;
517
+ (aggregateUsage.estimatedCostUsd ?? 0) +
518
+ providerResult.usage.estimatedCostUsd;
449
519
  }
450
520
  else {
451
521
  aggregateUsage.estimatedCostUsd = undefined;
@@ -14,12 +14,44 @@ const MAX_SOURCE_LOCS = 12;
14
14
  const MAX_FILES_IN_PROMPT = 28;
15
15
  const MAX_CHARS_PER_FILE = 14_000;
16
16
  const MAX_TOTAL_EXCERPT_CHARS = 100_000;
17
- const NON_ENRICHMENT_PROPERTY_KEYS = new Set(['inference_status']);
17
+ /** Cap per already-set property value; scanner evidence lists can reach hundreds of KB. */
18
+ const MAX_PROPERTY_VALUE_CHARS = 4_000;
19
+ const NON_ENRICHMENT_PROPERTY_KEYS = new Set([
20
+ 'inference_status',
21
+ 'propertyEvidence',
22
+ ]);
18
23
  function truncateChars(text, max) {
19
24
  if (text.length <= max)
20
25
  return text;
21
26
  return `${text.slice(0, max)}\n\n...[truncated]`;
22
27
  }
28
+ function compactDataActions(value) {
29
+ if (!Array.isArray(value))
30
+ return value;
31
+ const actions = value.map((entry) => entry && typeof entry === 'object' && 'action' in entry
32
+ ? entry.action
33
+ : entry);
34
+ return [...new Set(actions)];
35
+ }
36
+ function capPropertyValue(value) {
37
+ if (JSON.stringify(value).length <= MAX_PROPERTY_VALUE_CHARS)
38
+ return value;
39
+ if (typeof value === 'string') {
40
+ return truncateChars(value, MAX_PROPERTY_VALUE_CHARS);
41
+ }
42
+ if (Array.isArray(value)) {
43
+ const kept = [];
44
+ let size = 2;
45
+ for (const item of value) {
46
+ size += JSON.stringify(item).length + 1;
47
+ if (size > MAX_PROPERTY_VALUE_CHARS)
48
+ break;
49
+ kept.push(item);
50
+ }
51
+ return kept;
52
+ }
53
+ return undefined;
54
+ }
23
55
  function pathsFromComponent(comp) {
24
56
  if (!comp)
25
57
  return [];
@@ -127,7 +159,9 @@ function slimComponentForLlm(component) {
127
159
  sparseKeys.push(key);
128
160
  }
129
161
  else {
130
- propertiesSet[key] = value;
162
+ const compact = capPropertyValue(key === 'dataActions' ? compactDataActions(value) : value);
163
+ if (compact !== undefined)
164
+ propertiesSet[key] = compact;
131
165
  }
132
166
  }
133
167
  const prioritizedSparseKeys = (0, property_priority_1.sortPropertyKeysByPriority)(sparseKeys);
@@ -5,62 +5,62 @@ const chat_completions_family_1 = require("../../../src/ai-enrichment/providers/
5
5
  function tpCandidate(id, componentId) {
6
6
  return {
7
7
  id,
8
- candidateType: "third_party",
8
+ candidateType: 'third_party',
9
9
  priority: 90,
10
10
  componentId,
11
11
  missingFields: [],
12
- rationale: "r",
12
+ rationale: 'r',
13
13
  hints: [],
14
14
  };
15
15
  }
16
16
  function propertyCandidate(id, componentId) {
17
17
  return {
18
18
  id,
19
- candidateType: "node_property",
19
+ candidateType: 'node_property',
20
20
  priority: 50,
21
21
  componentId,
22
- missingFields: ["encryption_at_rest"],
23
- rationale: "r",
22
+ missingFields: ['encryption_at_rest'],
23
+ rationale: 'r',
24
24
  hints: [],
25
25
  };
26
26
  }
27
- describe("generateAgenticProposals", () => {
27
+ describe('generateAgenticProposals', () => {
28
28
  let inferSpy;
29
29
  beforeEach(() => {
30
30
  inferSpy = jest
31
- .spyOn(chat_completions_family_1.ChatCompletionsFamilyProvider.prototype, "infer")
31
+ .spyOn(chat_completions_family_1.ChatCompletionsFamilyProvider.prototype, 'infer')
32
32
  .mockResolvedValue({ proposals: [] });
33
33
  });
34
34
  afterEach(() => {
35
35
  inferSpy.mockRestore();
36
36
  });
37
- it("invokes the provider once per third-party queue item (tpAgent)", async () => {
37
+ it('invokes the provider once per third-party queue item (tpAgent)', async () => {
38
38
  const components = [
39
39
  {
40
- id: "tp_a",
41
- name: "A",
42
- type: "third_party",
40
+ id: 'tp_a',
41
+ name: 'A',
42
+ type: 'third_party',
43
43
  confidence: 0.9,
44
44
  detectedFrom: [],
45
45
  sourceLocations: [],
46
46
  properties: { vendor: null },
47
47
  },
48
48
  {
49
- id: "tp_b",
50
- name: "B",
51
- type: "third_party",
49
+ id: 'tp_b',
50
+ name: 'B',
51
+ type: 'third_party',
52
52
  confidence: 0.9,
53
53
  detectedFrom: [],
54
54
  sourceLocations: [],
55
55
  properties: { vendor: null },
56
56
  },
57
57
  ];
58
- const c1 = tpCandidate("c1", "tp_a");
59
- const c2 = tpCandidate("c2", "tp_b");
58
+ const c1 = tpCandidate('c1', 'tp_a');
59
+ const c2 = tpCandidate('c2', 'tp_b');
60
60
  await (0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, {
61
61
  queues: [
62
62
  {
63
- agent: "tpAgent",
63
+ agent: 'tpAgent',
64
64
  queue: [c1, c2],
65
65
  budgetTokens: 200_000,
66
66
  maxModelCalls: 10,
@@ -68,9 +68,9 @@ describe("generateAgenticProposals", () => {
68
68
  ],
69
69
  droppedCandidates: [],
70
70
  }, [c1, c2], {
71
- provider: "openai",
72
- model: "gpt-4o-mini",
73
- apiKey: "sk-test",
71
+ provider: 'openai',
72
+ model: 'gpt-4o-mini',
73
+ apiKey: 'sk-test',
74
74
  toolLoopMaxRounds: 1,
75
75
  });
76
76
  expect(inferSpy).toHaveBeenCalledTimes(2);
@@ -79,33 +79,33 @@ describe("generateAgenticProposals", () => {
79
79
  expect(payload.candidates).toHaveLength(1);
80
80
  }
81
81
  });
82
- it("batches propertyAgent into a single infer call", async () => {
82
+ it('batches propertyAgent into a single infer call', async () => {
83
83
  const components = [
84
84
  {
85
- id: "asset_1",
86
- name: "DB",
87
- type: "asset",
85
+ id: 'asset_1',
86
+ name: 'DB',
87
+ type: 'asset',
88
88
  confidence: 0.9,
89
89
  detectedFrom: [],
90
90
  sourceLocations: [],
91
91
  properties: {},
92
92
  },
93
93
  {
94
- id: "asset_2",
95
- name: "Cache",
96
- type: "asset",
94
+ id: 'asset_2',
95
+ name: 'Cache',
96
+ type: 'asset',
97
97
  confidence: 0.9,
98
98
  detectedFrom: [],
99
99
  sourceLocations: [],
100
100
  properties: {},
101
101
  },
102
102
  ];
103
- const c1 = propertyCandidate("p1", "asset_1");
104
- const c2 = propertyCandidate("p2", "asset_2");
103
+ const c1 = propertyCandidate('p1', 'asset_1');
104
+ const c2 = propertyCandidate('p2', 'asset_2');
105
105
  await (0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, {
106
106
  queues: [
107
107
  {
108
- agent: "propertyAgent",
108
+ agent: 'propertyAgent',
109
109
  queue: [c1, c2],
110
110
  budgetTokens: 200_000,
111
111
  maxModelCalls: 10,
@@ -113,52 +113,52 @@ describe("generateAgenticProposals", () => {
113
113
  ],
114
114
  droppedCandidates: [],
115
115
  }, [c1, c2], {
116
- provider: "openai",
117
- model: "gpt-4o-mini",
118
- apiKey: "sk-test",
116
+ provider: 'openai',
117
+ model: 'gpt-4o-mini',
118
+ apiKey: 'sk-test',
119
119
  toolLoopMaxRounds: 1,
120
120
  });
121
121
  expect(inferSpy).toHaveBeenCalledTimes(1);
122
122
  const payload = JSON.parse(inferSpy.mock.calls[0][0].prompt);
123
123
  expect(payload.candidates).toHaveLength(2);
124
124
  });
125
- it("respects maxModelCalls limit for tpAgent provider calls", async () => {
125
+ it('respects maxModelCalls limit for tpAgent provider calls', async () => {
126
126
  const components = [
127
127
  {
128
- id: "tp_a",
129
- name: "A",
130
- type: "third_party",
128
+ id: 'tp_a',
129
+ name: 'A',
130
+ type: 'third_party',
131
131
  confidence: 0.9,
132
132
  detectedFrom: [],
133
133
  sourceLocations: [],
134
134
  properties: { vendor: null },
135
135
  },
136
136
  {
137
- id: "tp_b",
138
- name: "B",
139
- type: "third_party",
137
+ id: 'tp_b',
138
+ name: 'B',
139
+ type: 'third_party',
140
140
  confidence: 0.9,
141
141
  detectedFrom: [],
142
142
  sourceLocations: [],
143
143
  properties: { vendor: null },
144
144
  },
145
145
  {
146
- id: "tp_c",
147
- name: "C",
148
- type: "third_party",
146
+ id: 'tp_c',
147
+ name: 'C',
148
+ type: 'third_party',
149
149
  confidence: 0.9,
150
150
  detectedFrom: [],
151
151
  sourceLocations: [],
152
152
  properties: { vendor: null },
153
153
  },
154
154
  ];
155
- const c1 = tpCandidate("c1", "tp_a");
156
- const c2 = tpCandidate("c2", "tp_b");
157
- const c3 = tpCandidate("c3", "tp_c");
155
+ const c1 = tpCandidate('c1', 'tp_a');
156
+ const c2 = tpCandidate('c2', 'tp_b');
157
+ const c3 = tpCandidate('c3', 'tp_c');
158
158
  await (0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, {
159
159
  queues: [
160
160
  {
161
- agent: "tpAgent",
161
+ agent: 'tpAgent',
162
162
  queue: [c1, c2, c3],
163
163
  budgetTokens: 100_000,
164
164
  maxModelCalls: 2,
@@ -166,30 +166,30 @@ describe("generateAgenticProposals", () => {
166
166
  ],
167
167
  droppedCandidates: [],
168
168
  }, [c1, c2, c3], {
169
- provider: "openai",
170
- model: "gpt-4o-mini",
171
- apiKey: "sk-test",
169
+ provider: 'openai',
170
+ model: 'gpt-4o-mini',
171
+ apiKey: 'sk-test',
172
172
  toolLoopMaxRounds: 1,
173
173
  });
174
174
  expect(inferSpy).toHaveBeenCalledTimes(2);
175
175
  });
176
- it("respects budgetTokens and skips provider calls when budget is exhausted", async () => {
176
+ it('respects budgetTokens and skips provider calls when budget is exhausted', async () => {
177
177
  const components = [
178
178
  {
179
- id: "tp_a",
180
- name: "A",
181
- type: "third_party",
179
+ id: 'tp_a',
180
+ name: 'A',
181
+ type: 'third_party',
182
182
  confidence: 0.9,
183
183
  detectedFrom: [],
184
184
  sourceLocations: [],
185
185
  properties: { vendor: null },
186
186
  },
187
187
  ];
188
- const c1 = tpCandidate("c1", "tp_a");
188
+ const c1 = tpCandidate('c1', 'tp_a');
189
189
  await (0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, {
190
190
  queues: [
191
191
  {
192
- agent: "tpAgent",
192
+ agent: 'tpAgent',
193
193
  queue: [c1],
194
194
  budgetTokens: 1,
195
195
  maxModelCalls: 1,
@@ -197,19 +197,19 @@ describe("generateAgenticProposals", () => {
197
197
  ],
198
198
  droppedCandidates: [],
199
199
  }, [c1], {
200
- provider: "openai",
201
- model: "gpt-4o-mini",
202
- apiKey: "sk-test",
200
+ provider: 'openai',
201
+ model: 'gpt-4o-mini',
202
+ apiKey: 'sk-test',
203
203
  toolLoopMaxRounds: 1,
204
204
  });
205
205
  expect(inferSpy).toHaveBeenCalledTimes(0);
206
206
  });
207
- it("invokes the provider for interactionAgent when the queue is eligible", async () => {
207
+ it('invokes the provider for interactionAgent when the queue is eligible', async () => {
208
208
  const components = [
209
209
  {
210
- id: "asset_1",
211
- name: "A",
212
- type: "asset",
210
+ id: 'asset_1',
211
+ name: 'A',
212
+ type: 'asset',
213
213
  confidence: 0.9,
214
214
  detectedFrom: [],
215
215
  sourceLocations: [],
@@ -217,17 +217,17 @@ describe("generateAgenticProposals", () => {
217
217
  },
218
218
  ];
219
219
  const interactionCandidate = {
220
- id: "m1",
221
- candidateType: "missing_interaction",
220
+ id: 'm1',
221
+ candidateType: 'missing_interaction',
222
222
  priority: 80,
223
223
  missingFields: [],
224
- rationale: "r",
225
- hints: ["frontend", "backend"],
224
+ rationale: 'r',
225
+ hints: ['frontend', 'backend'],
226
226
  };
227
227
  await (0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, {
228
228
  queues: [
229
229
  {
230
- agent: "interactionAgent",
230
+ agent: 'interactionAgent',
231
231
  queue: [interactionCandidate],
232
232
  budgetTokens: 200_000,
233
233
  maxModelCalls: 10,
@@ -235,14 +235,14 @@ describe("generateAgenticProposals", () => {
235
235
  ],
236
236
  droppedCandidates: [],
237
237
  }, [interactionCandidate], {
238
- provider: "openai",
239
- model: "gpt-4o-mini",
240
- apiKey: "sk-test",
238
+ provider: 'openai',
239
+ model: 'gpt-4o-mini',
240
+ apiKey: 'sk-test',
241
241
  toolLoopMaxRounds: 1,
242
242
  });
243
243
  expect(inferSpy).toHaveBeenCalledTimes(1);
244
244
  });
245
- it("aggregates provider token usage across calls", async () => {
245
+ it('aggregates provider token usage across calls', async () => {
246
246
  inferSpy.mockResolvedValue({
247
247
  proposals: [],
248
248
  usage: {
@@ -254,30 +254,30 @@ describe("generateAgenticProposals", () => {
254
254
  });
255
255
  const components = [
256
256
  {
257
- id: "tp_a",
258
- name: "A",
259
- type: "third_party",
257
+ id: 'tp_a',
258
+ name: 'A',
259
+ type: 'third_party',
260
260
  confidence: 0.9,
261
261
  detectedFrom: [],
262
262
  sourceLocations: [],
263
263
  properties: { vendor: null },
264
264
  },
265
265
  {
266
- id: "tp_b",
267
- name: "B",
268
- type: "third_party",
266
+ id: 'tp_b',
267
+ name: 'B',
268
+ type: 'third_party',
269
269
  confidence: 0.9,
270
270
  detectedFrom: [],
271
271
  sourceLocations: [],
272
272
  properties: { vendor: null },
273
273
  },
274
274
  ];
275
- const c1 = tpCandidate("c1", "tp_a");
276
- const c2 = tpCandidate("c2", "tp_b");
275
+ const c1 = tpCandidate('c1', 'tp_a');
276
+ const c2 = tpCandidate('c2', 'tp_b');
277
277
  const out = await (0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, {
278
278
  queues: [
279
279
  {
280
- agent: "tpAgent",
280
+ agent: 'tpAgent',
281
281
  queue: [c1, c2],
282
282
  budgetTokens: 200_000,
283
283
  maxModelCalls: 10,
@@ -285,9 +285,9 @@ describe("generateAgenticProposals", () => {
285
285
  ],
286
286
  droppedCandidates: [],
287
287
  }, [c1, c2], {
288
- provider: "openai",
289
- model: "gpt-4o-mini",
290
- apiKey: "sk-test",
288
+ provider: 'openai',
289
+ model: 'gpt-4o-mini',
290
+ apiKey: 'sk-test',
291
291
  toolLoopMaxRounds: 1,
292
292
  });
293
293
  expect(out.usageSummary).toMatchObject({
@@ -299,29 +299,29 @@ describe("generateAgenticProposals", () => {
299
299
  });
300
300
  expect(out.usageSummary?.agenticTrace?.length).toBe(2);
301
301
  });
302
- it("adds deterministic third-party heuristic proposals with evidence", async () => {
302
+ it('adds deterministic third-party heuristic proposals with evidence', async () => {
303
303
  inferSpy.mockResolvedValue({ proposals: [] });
304
304
  const components = [
305
305
  {
306
- id: "tp_stripe",
307
- name: "Stripe",
308
- type: "third_party",
306
+ id: 'tp_stripe',
307
+ name: 'Stripe',
308
+ type: 'third_party',
309
309
  confidence: 0.9,
310
310
  detectedFrom: [
311
311
  {
312
- pattern: "external_api_call",
312
+ pattern: 'external_api_call',
313
313
  sourceLocation: {
314
- filePath: "backend/payments/index.ts",
314
+ filePath: 'backend/payments/index.ts',
315
315
  startLine: 1,
316
316
  endLine: 1,
317
317
  },
318
318
  },
319
319
  ],
320
320
  sourceLocations: [
321
- { filePath: "backend/payments/index.ts", startLine: 1, endLine: 1 },
321
+ { filePath: 'backend/payments/index.ts', startLine: 1, endLine: 1 },
322
322
  ],
323
323
  properties: {
324
- section_id: "backend/payments",
324
+ section_id: 'backend/payments',
325
325
  vendor: null,
326
326
  api_type: null,
327
327
  authentication_method: null,
@@ -334,61 +334,63 @@ describe("generateAgenticProposals", () => {
334
334
  dataFlows: [],
335
335
  files: [
336
336
  {
337
- path: "backend/payments/index.ts",
338
- name: "index.ts",
339
- language: "typescript",
337
+ path: 'backend/payments/index.ts',
338
+ name: 'index.ts',
339
+ language: 'typescript',
340
340
  size: 180,
341
341
  content: [
342
342
  'import Stripe from "stripe";',
343
343
  'await fetch("https://api.stripe.com/v1/customers", {',
344
- " headers: { Authorization: `Bearer ${process.env.STRIPE_API_KEY}` },",
345
- "});",
346
- ].join("\n"),
344
+ ' headers: { Authorization: `Bearer ${process.env.STRIPE_API_KEY}` },',
345
+ '});',
346
+ ].join('\n'),
347
347
  },
348
348
  {
349
- path: "backend/payments/package.json",
350
- name: "package.json",
351
- language: "json",
349
+ path: 'backend/payments/package.json',
350
+ name: 'package.json',
351
+ language: 'json',
352
352
  size: 60,
353
- content: JSON.stringify({ dependencies: { stripe: "^17.0.0" } }),
353
+ content: JSON.stringify({ dependencies: { stripe: '^17.0.0' } }),
354
354
  },
355
355
  ],
356
356
  }, {
357
357
  queues: [
358
358
  {
359
- agent: "tpAgent",
360
- queue: [tpCandidate("c1", "tp_stripe")],
359
+ agent: 'tpAgent',
360
+ queue: [tpCandidate('c1', 'tp_stripe')],
361
361
  budgetTokens: 200_000,
362
362
  maxModelCalls: 1,
363
363
  },
364
364
  ],
365
365
  droppedCandidates: [],
366
- }, [tpCandidate("c1", "tp_stripe")], {
367
- provider: "openai",
368
- model: "gpt-4o-mini",
369
- apiKey: "sk-test",
366
+ }, [tpCandidate('c1', 'tp_stripe')], {
367
+ provider: 'openai',
368
+ model: 'gpt-4o-mini',
369
+ apiKey: 'sk-test',
370
370
  toolLoopMaxRounds: 1,
371
371
  });
372
- const heuristic = out.proposals.find((item) => item.id.startsWith("heuristic_"));
372
+ const heuristic = out.proposals.find((item) => item.id.startsWith('heuristic_'));
373
373
  expect(heuristic).toBeDefined();
374
- expect(heuristic?.proposal.kind).toBe("component_patch");
375
- if (heuristic?.proposal.kind === "component_patch") {
374
+ expect(heuristic?.proposal.kind).toBe('component_patch');
375
+ if (heuristic?.proposal.kind === 'component_patch') {
376
376
  expect(Object.keys(heuristic.proposal.setProperties).length).toBeGreaterThan(0);
377
377
  expect(heuristic.proposal.evidence.length).toBeGreaterThan(0);
378
- expect(heuristic.proposal.provider).toBe("mock");
379
- expect(heuristic.proposal.agent).toBe("tpAgent");
378
+ expect(heuristic.proposal.provider).toBe('mock');
379
+ expect(heuristic.proposal.agent).toBe('tpAgent');
380
380
  }
381
381
  });
382
- it("persists agentic trace for tp tool loop runs", async () => {
382
+ it('persists agentic trace for tp tool loop runs', async () => {
383
383
  inferSpy.mockResolvedValue({ proposals: [] });
384
384
  const components = [
385
385
  {
386
- id: "tp_trace",
387
- name: "Stripe",
388
- type: "third_party",
386
+ id: 'tp_trace',
387
+ name: 'Stripe',
388
+ type: 'third_party',
389
389
  confidence: 0.9,
390
390
  detectedFrom: [],
391
- sourceLocations: [{ filePath: "src/payments.ts", startLine: 1, endLine: 1 }],
391
+ sourceLocations: [
392
+ { filePath: 'src/payments.ts', startLine: 1, endLine: 1 },
393
+ ],
392
394
  properties: { vendor: null },
393
395
  },
394
396
  ];
@@ -397,9 +399,9 @@ describe("generateAgenticProposals", () => {
397
399
  dataFlows: [],
398
400
  files: [
399
401
  {
400
- path: "src/payments.ts",
401
- name: "payments.ts",
402
- language: "typescript",
402
+ path: 'src/payments.ts',
403
+ name: 'payments.ts',
404
+ language: 'typescript',
403
405
  size: 64,
404
406
  content: 'import x from "./client";\nexport const payments = true;',
405
407
  },
@@ -407,34 +409,34 @@ describe("generateAgenticProposals", () => {
407
409
  }, {
408
410
  queues: [
409
411
  {
410
- agent: "tpAgent",
411
- queue: [tpCandidate("c_trace", "tp_trace")],
412
+ agent: 'tpAgent',
413
+ queue: [tpCandidate('c_trace', 'tp_trace')],
412
414
  budgetTokens: 100_000,
413
415
  maxModelCalls: 1,
414
416
  },
415
417
  ],
416
418
  droppedCandidates: [],
417
- }, [tpCandidate("c_trace", "tp_trace")], {
418
- provider: "openai",
419
- model: "gpt-4o-mini",
420
- apiKey: "sk-test",
419
+ }, [tpCandidate('c_trace', 'tp_trace')], {
420
+ provider: 'openai',
421
+ model: 'gpt-4o-mini',
422
+ apiKey: 'sk-test',
421
423
  toolLoopMaxRounds: 1,
422
424
  });
423
425
  expect(out.usageSummary?.agenticTrace).toBeDefined();
424
426
  expect(out.usageSummary?.agenticTrace?.length).toBe(1);
425
427
  expect(out.usageSummary?.agenticTrace?.[0]?.toolCalls.length).toBeGreaterThan(0);
426
428
  });
427
- it("deduplicates repeated search hits and prefers unseen files", async () => {
429
+ it('deduplicates repeated search hits and prefers unseen files', async () => {
428
430
  inferSpy.mockResolvedValue({ proposals: [] });
429
431
  const components = [
430
432
  {
431
- id: "tp_search_dedupe",
432
- name: "Supabase",
433
- type: "third_party",
433
+ id: 'tp_search_dedupe',
434
+ name: 'Supabase',
435
+ type: 'third_party',
434
436
  confidence: 0.9,
435
437
  detectedFrom: [],
436
- sourceLocations: [{ filePath: "src/a.ts", startLine: 1, endLine: 1 }],
437
- properties: { vendor: null, section_id: "src" },
438
+ sourceLocations: [{ filePath: 'src/a.ts', startLine: 1, endLine: 1 }],
439
+ properties: { vendor: null, section_id: 'src' },
438
440
  },
439
441
  ];
440
442
  const out = await (0, agent_orchestrator_1.generateAgenticProposals)({
@@ -442,16 +444,16 @@ describe("generateAgenticProposals", () => {
442
444
  dataFlows: [],
443
445
  files: [
444
446
  {
445
- path: "src/a.ts",
446
- name: "a.ts",
447
- language: "typescript",
447
+ path: 'src/a.ts',
448
+ name: 'a.ts',
449
+ language: 'typescript',
448
450
  size: 200,
449
451
  content: "const one = 'supabase';\nconst two = 'supabase';\nconst three = 'supabase';\n",
450
452
  },
451
453
  {
452
- path: "src/b.ts",
453
- name: "b.ts",
454
- language: "typescript",
454
+ path: 'src/b.ts',
455
+ name: 'b.ts',
456
+ language: 'typescript',
455
457
  size: 120,
456
458
  content: "const other = 'supabase';\n",
457
459
  },
@@ -459,25 +461,103 @@ describe("generateAgenticProposals", () => {
459
461
  }, {
460
462
  queues: [
461
463
  {
462
- agent: "tpAgent",
463
- queue: [tpCandidate("c_search_dedupe", "tp_search_dedupe")],
464
+ agent: 'tpAgent',
465
+ queue: [tpCandidate('c_search_dedupe', 'tp_search_dedupe')],
464
466
  budgetTokens: 100_000,
465
467
  maxModelCalls: 1,
466
468
  },
467
469
  ],
468
470
  droppedCandidates: [],
469
- }, [tpCandidate("c_search_dedupe", "tp_search_dedupe")], {
470
- provider: "openai",
471
- model: "gpt-4o-mini",
472
- apiKey: "sk-test",
471
+ }, [tpCandidate('c_search_dedupe', 'tp_search_dedupe')], {
472
+ provider: 'openai',
473
+ model: 'gpt-4o-mini',
474
+ apiKey: 'sk-test',
473
475
  toolLoopMaxRounds: 1,
474
476
  });
475
477
  const trace = out.usageSummary?.agenticTrace?.[0];
476
478
  expect(trace).toBeDefined();
477
- const searchCall = trace?.toolCalls.find((step) => step.action === "search_text");
479
+ const searchCall = trace?.toolCalls.find((step) => step.action === 'search_text');
478
480
  expect(searchCall).toBeDefined();
479
481
  const touched = searchCall?.filesTouched ?? [];
480
482
  expect(new Set(touched).size).toBe(touched.length);
481
- expect(touched).toContain("src/b.ts");
483
+ expect(touched).toContain('src/b.ts');
484
+ });
485
+ describe('oversized prompts', () => {
486
+ function largeAsset(id) {
487
+ const properties = { vendor: null };
488
+ for (let i = 0; i < 30; i += 1)
489
+ properties[`note_${i}`] = 'x'.repeat(3_900);
490
+ return {
491
+ id,
492
+ name: id,
493
+ type: 'asset',
494
+ confidence: 0.9,
495
+ detectedFrom: [],
496
+ sourceLocations: [],
497
+ properties,
498
+ };
499
+ }
500
+ function propertyPlan(candidates) {
501
+ return {
502
+ queues: [
503
+ {
504
+ agent: 'propertyAgent',
505
+ queue: candidates,
506
+ budgetTokens: 10_000_000,
507
+ maxModelCalls: 20,
508
+ },
509
+ ],
510
+ droppedCandidates: [],
511
+ };
512
+ }
513
+ const orchestratorOptions = {
514
+ provider: 'openai',
515
+ model: 'gpt-4o-mini',
516
+ apiKey: 'sk-test',
517
+ toolLoopMaxRounds: 1,
518
+ };
519
+ it('splits a propertyAgent batch until each prompt fits the size limit', async () => {
520
+ const components = Array.from({ length: 12 }, (_, i) => largeAsset(`asset_${i}`));
521
+ const candidates = components.map((c) => propertyCandidate(`p_${c.id}`, c.id));
522
+ await (0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, propertyPlan(candidates), candidates, orchestratorOptions);
523
+ expect(inferSpy.mock.calls.length).toBeGreaterThan(1);
524
+ const sent = [];
525
+ for (const call of inferSpy.mock.calls) {
526
+ const prompt = call[0].prompt;
527
+ expect(Buffer.byteLength(prompt, 'utf8')).toBeLessThanOrEqual(agent_orchestrator_1.MAX_PROVIDER_PROMPT_BYTES);
528
+ const payload = JSON.parse(prompt);
529
+ sent.push(...payload.candidates.map((c) => c.id));
530
+ }
531
+ expect(sent).toEqual(candidates.map((c) => c.id));
532
+ });
533
+ it('skips a call the provider rejects as too large and keeps the scan going', async () => {
534
+ inferSpy
535
+ .mockRejectedValueOnce(new Error('request_body_too_large'))
536
+ .mockResolvedValueOnce({ proposals: [] });
537
+ const components = [largeAsset('asset_a')];
538
+ const candidates = [propertyCandidate('p_a', 'asset_a')];
539
+ await expect((0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, propertyPlan(candidates), candidates, orchestratorOptions)).resolves.toEqual(expect.objectContaining({ proposals: [] }));
540
+ });
541
+ it('still fails the scan for provider errors unrelated to prompt size', async () => {
542
+ inferSpy.mockRejectedValueOnce(new Error('Invalid workspace API key'));
543
+ const components = [largeAsset('asset_a')];
544
+ const candidates = [propertyCandidate('p_a', 'asset_a')];
545
+ await expect((0, agent_orchestrator_1.generateAgenticProposals)({ components, dataFlows: [] }, propertyPlan(candidates), candidates, orchestratorOptions)).rejects.toThrow('Invalid workspace API key');
546
+ });
547
+ });
548
+ });
549
+ describe('isPromptTooLargeError', () => {
550
+ it.each([
551
+ 'request_body_too_large',
552
+ 'prompt too large',
553
+ 'prompt is too long: 250000 tokens > 200000 maximum',
554
+ "This model's maximum context length is 128000 tokens",
555
+ 'Hosted scan AI infer failed (413)',
556
+ ])('matches %s', (message) => {
557
+ expect((0, agent_orchestrator_1.isPromptTooLargeError)(new Error(message))).toBe(true);
558
+ });
559
+ it('does not match auth or quota errors', () => {
560
+ expect((0, agent_orchestrator_1.isPromptTooLargeError)(new Error('platform_llm_not_configured'))).toBe(false);
561
+ expect((0, agent_orchestrator_1.isPromptTooLargeError)(new Error('Platform AI infer failed (402)'))).toBe(false);
482
562
  });
483
563
  });
@@ -37,6 +37,41 @@ describe('provider-prompt', () => {
37
37
  expect(slim.sparsePropertyKeys).not.toContain('inference_status');
38
38
  expect(slim.sparsePropertyKeys[0]).toBe('encrypt_at_rest');
39
39
  });
40
+ it('slimComponentForLlm drops scanner evidence and caps oversized set values', () => {
41
+ const evidence = Array.from({ length: 2_000 }, (_, i) => ({
42
+ filePath: `backend/src/entities/e${i}.ts`,
43
+ startLine: i,
44
+ endLine: i,
45
+ reason: 'property.patterns.yaml:database_connection',
46
+ }));
47
+ const c = {
48
+ id: 'cmp_orm',
49
+ name: 'Typeorm',
50
+ type: 'asset',
51
+ confidence: 0.9,
52
+ detectedFrom: [],
53
+ sourceLocations: [],
54
+ properties: {
55
+ propertyEvidence: { audit_logging_enabled: evidence },
56
+ dataActions: [
57
+ { action: 'store', source: 'deterministic', evidence },
58
+ { action: 'combine', source: 'deterministic', evidence },
59
+ { action: 'store', source: 'deterministic', evidence },
60
+ ],
61
+ data_categories: Array.from({ length: 2_000 }, (_, i) => `cat_${i}`),
62
+ vendor: null,
63
+ },
64
+ };
65
+ const slim = (0, provider_prompt_1.slimComponentForLlm)(c);
66
+ const propertiesSet = slim.propertiesSet;
67
+ expect(propertiesSet.propertyEvidence).toBeUndefined();
68
+ expect(slim.sparsePropertyKeys).not.toContain('propertyEvidence');
69
+ expect(propertiesSet.dataActions).toEqual(['store', 'combine']);
70
+ const categories = propertiesSet.data_categories;
71
+ expect(categories.length).toBeGreaterThan(0);
72
+ expect(categories.length).toBeLessThan(2_000);
73
+ expect(JSON.stringify(slim).length).toBeLessThan(10_000);
74
+ });
40
75
  it('buildProviderPromptPayload includes componentContext for queued componentIds', () => {
41
76
  const components = [
42
77
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataparade/cli",
3
- "version": "0.0.21",
3
+ "version": "0.0.22",
4
4
  "description": "dataPARADE CLI — scan codebases for privacy and security data flows",
5
5
  "publishConfig": {
6
6
  "access": "public",