@dataparade/cli 0.0.28 → 0.0.30

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 (31) hide show
  1. package/README.md +4 -1
  2. package/dist/package.json +2 -2
  3. package/dist/src/ai-enrichment/providers/platform-proxy-provider.js +6 -1
  4. package/dist/src/cli/scan-interrupt-handlers.d.ts +34 -0
  5. package/dist/src/cli/scan-interrupt-handlers.js +105 -0
  6. package/dist/src/cli.d.ts +3 -0
  7. package/dist/src/cli.js +163 -58
  8. package/dist/src/config/scan-env.d.ts +5 -2
  9. package/dist/src/config/scan-env.js +8 -2
  10. package/dist/src/platform-api/fetch-failure.d.ts +5 -0
  11. package/dist/src/platform-api/fetch-failure.js +13 -0
  12. package/dist/src/platform-api/scan-quota-client.d.ts +3 -1
  13. package/dist/src/platform-api/scan-quota-client.js +41 -28
  14. package/dist/src/platform-api/upload-client.d.ts +5 -0
  15. package/dist/src/platform-api/upload-client.js +11 -1
  16. package/dist/src/ui/scan-progress-renderer.d.ts +38 -0
  17. package/dist/src/ui/scan-progress-renderer.js +110 -3
  18. package/dist/src/ui/types.d.ts +5 -0
  19. package/dist/tests/unit/ai-enrichment/platform-proxy-provider.spec.js +26 -0
  20. package/dist/tests/unit/cli/scan-ai-session-fallback.spec.d.ts +1 -0
  21. package/dist/tests/unit/cli/scan-ai-session-fallback.spec.js +156 -0
  22. package/dist/tests/unit/cli/scan-interrupt-handlers.spec.d.ts +1 -0
  23. package/dist/tests/unit/cli/scan-interrupt-handlers.spec.js +154 -0
  24. package/dist/tests/unit/cli/scan-quota-flow.spec.js +2 -2
  25. package/dist/tests/unit/platform-api/read-cli-api-error-message.spec.js +2 -2
  26. package/dist/tests/unit/ui/scan-progress-renderer.spec.js +155 -0
  27. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.d.ts +24 -0
  28. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.js +19 -6
  29. package/dist/vendor/scanner/dist/src/pii-signals/occurrence-group.js +5 -2
  30. package/dist/vendor/scanner/dist/src/pii-signals/pii-signal-aliases.js +5 -2
  31. package/package.json +2 -2
package/README.md CHANGED
@@ -32,6 +32,7 @@ A scan reads the source and config files under the folder (skipping dependencies
32
32
  - In a TTY: brand header, staged progress (spinner → checkmarks), a short **What we found** summary (routes, databases, outbound services), and a clear next-step note.
33
33
  - In CI / non-TTY (or with `NO_COLOR`): the same content as plain logs — no spinners or ANSI.
34
34
  - On success: `[scan] dataflow.json written to /absolute/path/to/dataflow.json` (always printed for scripts/tests).
35
+ - If AI enrichment cannot start (no network, anonymous per-IP limit, server error), the CLI prints `AI enrichment unavailable (<reason>); continuing with a structural scan.` and still writes the output. Use `--no-ai-inference` to skip AI.
35
36
  - When auto-upload runs: `[scan] Preview ready: <URL>` (plus a friendly next-step note with the same URL).
36
37
  - By default, the output goes to a **`.dataparade/`** folder in the current working directory (override the path of `dataflow.json` with `-o` / `--output`; the other files sit next to it).
37
38
 
@@ -50,7 +51,9 @@ After a scan, the CLI **auto-uploads** `dataflow.json` and the Facts next to it
50
51
  - **With a workspace API key** (`DATAPARADE_WORKSPACE_API_KEY` from **Workspace → Access keys**): prints a dashboard link (`?importDraft=`) for that workspace.
51
52
  - **Without a workspace key**: prints a sign-up link (`/preview/cli/<token>`). Create an account to open **Preview & Edit** on your dashboard.
52
53
  - Opt out: `--skip-auto-upload` or `DATAPARADE_SKIP_AUTO_UPLOAD=true`
53
- - Upload alone does **not** consume scan quota
54
+ - With a workspace API key, an upload does **not** use scan quota.
55
+ - Without a key, uploads count toward a small per-IP limit on anonymous scans. A default scan (AI on) counts once, when its AI session starts, and its auto-upload does not count again. A scan with `--no-ai-inference`, or a separate `dataparade upload`, counts once when it uploads. When the limit is reached, the scan still writes `.dataparade/`; set `DATAPARADE_WORKSPACE_API_KEY` and run `dataparade upload .dataparade/dataflow.json`.
56
+ - If the upload fails, the scan output stays on disk and the CLI prints the `dataparade upload` command to retry.
54
57
 
55
58
  ```bash
56
59
  npx @dataparade/cli upload .dataparade/dataflow.json --project-name "My service"
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataparade/cli",
3
- "version": "0.0.28",
3
+ "version": "0.0.30",
4
4
  "description": "dataPARADE CLI — scan codebases for privacy and security data flows",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -66,7 +66,7 @@
66
66
  "zod": "^4.3.5"
67
67
  },
68
68
  "devDependencies": {
69
- "@dataparade/scanner": "github:DataParade-io/scanner#a08a57b046b7b6be0afd84b7866432e6242d216a",
69
+ "@dataparade/scanner": "github:DataParade-io/scanner#6a5a95897fe9ccd60230b0636f3a91b2e21a1ab1",
70
70
  "@eslint/js": "^9.18.0",
71
71
  "@types/jest": "^30.0.0",
72
72
  "@types/node": "^22.0.0",
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PlatformProxyProvider = void 0;
4
4
  const lambda_init_error_1 = require("../lambda-init-error");
5
5
  const fetch_failure_1 = require("../../platform-api/fetch-failure");
6
+ const scan_env_1 = require("../../config/scan-env");
6
7
  const DEFAULT_NETWORK_RETRY_DELAYS_MS = [1000, 2000];
7
8
  function resolvePollTimeoutMs(configured) {
8
9
  if (typeof configured === 'number' &&
@@ -95,7 +96,11 @@ class PlatformProxyProvider {
95
96
  if (attempt >= delays.length || !(0, fetch_failure_1.isTransientFetchError)(err)) {
96
97
  throw (0, fetch_failure_1.toApiReachabilityError)(err, url, method, attempt + 1);
97
98
  }
98
- console.warn(`[dataparade-ai] ${(0, fetch_failure_1.describeRequestTarget)(url, method)} failed (${(0, fetch_failure_1.fetchFailureDetail)(err)}). Retrying (${attempt + 1}/${delays.length}).`);
99
+ // The Clack UI owns the terminal; a final failure still surfaces
100
+ // through the scan error ("Tried N times").
101
+ if (!(0, scan_env_1.isScanAiDebugSuppressed)()) {
102
+ console.warn(`[dataparade-ai] ${(0, fetch_failure_1.describeRequestTarget)(url, method)} failed (${(0, fetch_failure_1.fetchFailureDetail)(err)}). Retrying (${attempt + 1}/${delays.length}).`);
103
+ }
99
104
  await this.wait(delays[attempt] ?? 0);
100
105
  }
101
106
  }
@@ -0,0 +1,34 @@
1
+ export type CliScanQuotaCompletionStatus = 'none' | 'in_flight' | 'done';
2
+ export type CliScanInterruptSignal = 'SIGINT' | 'SIGTERM' | 'SIGHUP';
3
+ export declare const CLI_SCAN_INTERRUPT_EXIT_CODES: Record<CliScanInterruptSignal, number>;
4
+ /** Cap how long Ctrl+C waits on a hung complete API before exiting. */
5
+ export declare const CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS = 2500;
6
+ export type CliScanInterruptProcess = {
7
+ on(event: string, listener: (...args: unknown[]) => void): CliScanInterruptProcess | unknown;
8
+ off?(event: string, listener: (...args: unknown[]) => void): CliScanInterruptProcess | unknown;
9
+ removeListener?(event: string, listener: (...args: unknown[]) => void): CliScanInterruptProcess | unknown;
10
+ };
11
+ export type InstallCliScanInterruptHandlersInput = {
12
+ proc: CliScanInterruptProcess;
13
+ exit: (code: number) => void;
14
+ getState: () => {
15
+ apiKey?: string;
16
+ jobId?: string;
17
+ completionStatus: CliScanQuotaCompletionStatus;
18
+ /** Pending normal-path complete, awaited (bounded) instead of duplicated. */
19
+ inFlight?: Promise<unknown>;
20
+ };
21
+ /** Claim the completion so the scan's own paths don't report it again. */
22
+ setCompletionStatus: (status: CliScanQuotaCompletionStatus) => void;
23
+ onAbortUi: () => void;
24
+ reportFailed: (input: {
25
+ apiKey: string;
26
+ jobId: string;
27
+ timeoutMs: number;
28
+ }) => Promise<void>;
29
+ };
30
+ /**
31
+ * Release the CLI scan lock on Ctrl+C / kill / hangup, then exit.
32
+ * Returns uninstall(); safe to call more than once.
33
+ */
34
+ export declare function installCliScanInterruptHandlers(input: InstallCliScanInterruptHandlersInput): () => void;
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS = exports.CLI_SCAN_INTERRUPT_EXIT_CODES = void 0;
4
+ exports.installCliScanInterruptHandlers = installCliScanInterruptHandlers;
5
+ exports.CLI_SCAN_INTERRUPT_EXIT_CODES = {
6
+ SIGINT: 130,
7
+ SIGTERM: 143,
8
+ SIGHUP: 129,
9
+ };
10
+ /** Cap how long Ctrl+C waits on a hung complete API before exiting. */
11
+ exports.CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS = 2_500;
12
+ const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
13
+ /** Below this, a follow-up report can't realistically land before exit. */
14
+ const MIN_REPORT_WINDOW_MS = 250;
15
+ /** Resolve when `promise` settles or `ms` elapses, whichever comes first. */
16
+ async function settleWithin(promise, ms) {
17
+ let timer;
18
+ try {
19
+ await Promise.race([
20
+ promise.then(() => undefined, () => undefined),
21
+ new Promise((resolve) => {
22
+ timer = setTimeout(resolve, ms);
23
+ }),
24
+ ]);
25
+ }
26
+ finally {
27
+ if (timer)
28
+ clearTimeout(timer);
29
+ }
30
+ }
31
+ /**
32
+ * Release the CLI scan lock on Ctrl+C / kill / hangup, then exit.
33
+ * Returns uninstall(); safe to call more than once.
34
+ */
35
+ function installCliScanInterruptHandlers(input) {
36
+ let handling = false;
37
+ let uninstalled = false;
38
+ const remove = (event, listener) => {
39
+ if (typeof input.proc.off === 'function') {
40
+ input.proc.off(event, listener);
41
+ return;
42
+ }
43
+ if (typeof input.proc.removeListener === 'function') {
44
+ input.proc.removeListener(event, listener);
45
+ }
46
+ };
47
+ const onSignal = (signal) => {
48
+ const code = exports.CLI_SCAN_INTERRUPT_EXIT_CODES[signal];
49
+ if (handling) {
50
+ input.exit(code);
51
+ return;
52
+ }
53
+ handling = true;
54
+ void (async () => {
55
+ const deadline = Date.now() + exports.CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS;
56
+ try {
57
+ input.onAbortUi();
58
+ const pending = input.getState();
59
+ if (pending.completionStatus === 'in_flight' && pending.inFlight) {
60
+ // Let the scan's own complete land; exiting now could cut it off.
61
+ await settleWithin(pending.inFlight, deadline - Date.now());
62
+ }
63
+ // Re-read: a failed in-flight complete resets the status to 'none'.
64
+ const state = input.getState();
65
+ const remainingMs = deadline - Date.now();
66
+ if (state.apiKey &&
67
+ state.jobId &&
68
+ state.completionStatus === 'none' &&
69
+ remainingMs >= MIN_REPORT_WINDOW_MS) {
70
+ input.setCompletionStatus('in_flight');
71
+ try {
72
+ await input.reportFailed({
73
+ apiKey: state.apiKey,
74
+ jobId: state.jobId,
75
+ timeoutMs: remainingMs,
76
+ });
77
+ }
78
+ catch {
79
+ // Lock release must not block exit.
80
+ }
81
+ // Exiting either way; keep the scan's finally from reporting again.
82
+ input.setCompletionStatus('done');
83
+ }
84
+ }
85
+ finally {
86
+ input.exit(code);
87
+ }
88
+ })();
89
+ };
90
+ const listeners = SIGNALS.map((signal) => {
91
+ const listener = () => {
92
+ onSignal(signal);
93
+ };
94
+ input.proc.on(signal, listener);
95
+ return { signal, listener };
96
+ });
97
+ return () => {
98
+ if (uninstalled)
99
+ return;
100
+ uninstalled = true;
101
+ for (const { signal, listener } of listeners) {
102
+ remove(signal, listener);
103
+ }
104
+ };
105
+ }
package/dist/src/cli.d.ts CHANGED
@@ -1,2 +1,5 @@
1
1
  import './config/load-cli-env';
2
+ import { type ScanUploadFailure } from './ui/scan-progress-renderer';
3
+ /** Retry command and advice shown when the scan's auto-upload fails. */
4
+ export declare function describeAutoUploadFailure(uploadError: unknown, dataflowOutputPath: string, hasWorkspaceApiKey: boolean): ScanUploadFailure;
2
5
  export declare function run(argv?: string[]): Promise<void>;
package/dist/src/cli.js CHANGED
@@ -36,6 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.describeAutoUploadFailure = describeAutoUploadFailure;
39
40
  exports.run = run;
40
41
  require("./config/load-cli-env");
41
42
  const path_1 = __importDefault(require("path"));
@@ -63,6 +64,7 @@ const telemetry_client_1 = require("./platform-api/telemetry-client");
63
64
  const cli_scan_failure_report_1 = require("./platform-api/cli-scan-failure-report");
64
65
  const scan_config_schema_1 = require("./core/schema/scan-config.schema");
65
66
  const scanner_1 = require("../vendor/scanner/dist/src/index.js");
67
+ const scan_interrupt_handlers_1 = require("./cli/scan-interrupt-handlers");
66
68
  const scan_progress_renderer_1 = require("./ui/scan-progress-renderer");
67
69
  /** The scanner is vendored into the CLI; its version is the commit the CLI depends on. */
68
70
  function scannerVersionFromPackage() {
@@ -124,6 +126,24 @@ function formatAiInferenceVerbose(details) {
124
126
  }
125
127
  return lines;
126
128
  }
129
+ /** Retry command and advice shown when the scan's auto-upload fails. */
130
+ function describeAutoUploadFailure(uploadError, dataflowOutputPath, hasWorkspaceApiKey) {
131
+ const relative = path_1.default.relative(process.cwd(), dataflowOutputPath);
132
+ const target = relative && !relative.startsWith('..') ? relative : dataflowOutputPath;
133
+ const quoted = /\s/.test(target) ? `"${target}"` : target;
134
+ const status = uploadError && typeof uploadError === 'object' && 'status' in uploadError
135
+ ? uploadError.status
136
+ : undefined;
137
+ const message = uploadError instanceof Error ? uploadError.message : '';
138
+ const rateLimited = status === 429 || /too many anonymous cli scans/i.test(message);
139
+ return {
140
+ reason: (0, fetch_failure_1.describeUnavailableReason)(uploadError),
141
+ retryCommand: `dataparade upload ${quoted}`,
142
+ hint: rateLimited && !hasWorkspaceApiKey
143
+ ? 'Anonymous uploads are limited per IP address. To avoid the limit, set DATAPARADE_WORKSPACE_API_KEY (from Workspace → Access keys in DataParade) and run the upload again.'
144
+ : undefined,
145
+ };
146
+ }
127
147
  function formatUsd(value) {
128
148
  if (typeof value !== 'number' || !Number.isFinite(value))
129
149
  return 'n/a';
@@ -172,7 +192,9 @@ function createProgram() {
172
192
  .action(async (path, options) => {
173
193
  let cliQuotaJobId;
174
194
  let platformQuotaApiKey;
175
- let quotaCompletionReported = false;
195
+ let progressUi;
196
+ let quotaCompletionStatus = 'none';
197
+ let quotaCompletionInFlight;
176
198
  let fallbackFailureMessage = 'CLI scan did not complete successfully';
177
199
  let reportedFailure;
178
200
  let sentryScanRoot;
@@ -182,6 +204,15 @@ function createProgram() {
182
204
  // True once Clack owns the terminal: raw `[scan]` lines would break its
183
205
  // guide rail, so they go through the renderer or are skipped.
184
206
  let friendlyTty = false;
207
+ // Errors close the Clack UI as a plain sentence; logs (CI, non-TTY)
208
+ // keep the `[scan] …:` prefix so they stay greppable.
209
+ const reportScanError = (logLine, friendlyText) => {
210
+ if (friendlyTty && progressUi) {
211
+ progressUi.fail(friendlyText);
212
+ return;
213
+ }
214
+ console.error(logLine);
215
+ };
185
216
  // Parse and validate --git-context if provided
186
217
  let parsedGitContext;
187
218
  if (options.gitContext) {
@@ -217,6 +248,35 @@ function createProgram() {
217
248
  apiKey: workspaceApiKey,
218
249
  cliVersion: package_json_1.default.version,
219
250
  });
251
+ const uninstallInterruptHandlers = (0, scan_interrupt_handlers_1.installCliScanInterruptHandlers)({
252
+ proc: process,
253
+ exit: (code) => {
254
+ process.exit(code);
255
+ },
256
+ getState: () => ({
257
+ apiKey: platformQuotaApiKey,
258
+ jobId: cliQuotaJobId,
259
+ completionStatus: quotaCompletionStatus,
260
+ inFlight: quotaCompletionInFlight,
261
+ }),
262
+ setCompletionStatus: (status) => {
263
+ quotaCompletionStatus = status;
264
+ },
265
+ onAbortUi: () => {
266
+ progressUi?.abort('Scan cancelled');
267
+ },
268
+ reportFailed: async ({ apiKey, jobId, timeoutMs }) => {
269
+ const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
270
+ await cliScanComplete({
271
+ apiKey,
272
+ jobId,
273
+ status: 'failed',
274
+ failureCode: 'scan_interrupted',
275
+ failureMessage: 'You stopped this scan',
276
+ timeoutMs,
277
+ });
278
+ },
279
+ });
220
280
  try {
221
281
  const rootPathArg = path || '.';
222
282
  // Load dataparade.config.json from the directory being scanned, not
@@ -249,15 +309,16 @@ function createProgram() {
249
309
  Promise.resolve().then(() => __importStar(require('./core/pipeline/scan-pipeline'))),
250
310
  Promise.resolve().then(() => __importStar(require('./core/pipeline/graph-mapping'))),
251
311
  ]);
252
- const progressUi = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
312
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
253
313
  isTTY: Boolean(isInteractive),
254
314
  noColor: Boolean(typeof process.env.NO_COLOR === 'string' &&
255
315
  process.env.NO_COLOR.length > 0),
256
316
  projectLabel: resolvedScanRoot,
257
317
  version: package_json_1.default.version,
258
318
  });
259
- progressUi.start();
260
- friendlyTty = progressUi.usesClackChrome;
319
+ progressUi = ui;
320
+ ui.start();
321
+ friendlyTty = ui.usesClackChrome;
261
322
  (0, scan_env_1.setScanAiDebugSuppressed)(friendlyTty && !options.aiVerbose);
262
323
  // Technical meters, shown as one block after the scan (TTY) or
263
324
  // printed as before (non-TTY).
@@ -321,6 +382,16 @@ function createProgram() {
321
382
  sentryScanRoot = scanEntry.scanRootDir;
322
383
  sentryAiMode = aiMode;
323
384
  sentryAiProvider = config.aiProvider;
385
+ // AI enrichment is optional. When its platform setup fails (no
386
+ // network, anonymous per-IP cap, server error), say so once and
387
+ // run the structural scan so the local output is still written.
388
+ const continueWithoutAi = (setupError) => {
389
+ config.enableAiInference = false;
390
+ config.cliQuotaJobId = undefined;
391
+ config.anonSessionToken = undefined;
392
+ sentryAiMode = 'none';
393
+ ui.warn(`AI enrichment unavailable (${(0, fetch_failure_1.describeUnavailableReason)(setupError)}); continuing with a structural scan. Use --no-ai-inference to skip this step.`);
394
+ };
324
395
  // Quota preflight for platform billing. Structural-only scans (AI off) do not use quota API.
325
396
  if (workspaceApiKey && !usesByok && config.enableAiInference) {
326
397
  const [{ cliScanPreflight }, { estimateScanFootprint }] = await Promise.all([
@@ -334,27 +405,38 @@ function createProgram() {
334
405
  projectName: config.projectName,
335
406
  fileCount: footprint.fileCount,
336
407
  bytesIngested: footprint.bytesIngested,
408
+ }).catch(async (preflightError) => {
409
+ const { CliScanQuotaExceededError, CliScanAlreadyRunningError } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
410
+ // Workspace quota and concurrency answers stay blocking.
411
+ if (preflightError instanceof CliScanQuotaExceededError ||
412
+ preflightError instanceof CliScanAlreadyRunningError) {
413
+ throw preflightError;
414
+ }
415
+ continueWithoutAi(preflightError);
416
+ return undefined;
337
417
  });
338
- cliQuotaJobId = preflight.jobId;
339
- platformQuotaApiKey = workspaceApiKey;
340
- config.cliQuotaJobId = preflight.jobId;
341
- if (config.enableAiInference &&
342
- preflight.suggestedAiBudgetTokens > 0) {
343
- // suggestedAiBudgetTokens is a server ceiling (remaining quota /
344
- // per-job cap), not a spend target. Never raise the CLI working
345
- // budget above the configured default (or user override).
346
- config.aiBudgetTokens = Math.min(config.aiBudgetTokens ?? 12_000, preflight.suggestedAiBudgetTokens);
347
- }
348
- if (preflight.aiDelivery === 'platform_proxy') {
349
- config.aiMode = 'platform';
350
- }
351
- if (isInteractive) {
352
- const quotaLine = `[scan] quota: scans_remaining=${preflight.scansRemaining} ai_tokens_remaining=${preflight.aiTokensRemaining} job_id=${preflight.jobId} working_budget=${config.aiBudgetTokens ?? 0}`;
353
- if (friendlyTty) {
354
- technicalLines.push(quotaLine);
418
+ if (preflight) {
419
+ cliQuotaJobId = preflight.jobId;
420
+ platformQuotaApiKey = workspaceApiKey;
421
+ config.cliQuotaJobId = preflight.jobId;
422
+ if (config.enableAiInference &&
423
+ preflight.suggestedAiBudgetTokens > 0) {
424
+ // suggestedAiBudgetTokens is a server ceiling (remaining quota /
425
+ // per-job cap), not a spend target. Never raise the CLI working
426
+ // budget above the configured default (or user override).
427
+ config.aiBudgetTokens = Math.min(config.aiBudgetTokens ?? 12_000, preflight.suggestedAiBudgetTokens);
428
+ }
429
+ if (preflight.aiDelivery === 'platform_proxy') {
430
+ config.aiMode = 'platform';
355
431
  }
356
- else {
357
- console.log(quotaLine);
432
+ if (isInteractive) {
433
+ const quotaLine = `[scan] quota: scans_remaining=${preflight.scansRemaining} ai_tokens_remaining=${preflight.aiTokensRemaining} job_id=${preflight.jobId} working_budget=${config.aiBudgetTokens ?? 0}`;
434
+ if (friendlyTty) {
435
+ technicalLines.push(quotaLine);
436
+ }
437
+ else {
438
+ console.log(quotaLine);
439
+ }
358
440
  }
359
441
  }
360
442
  }
@@ -389,18 +471,9 @@ function createProgram() {
389
471
  }
390
472
  }
391
473
  catch (anonSessionError) {
392
- const { CliAnonymousIpLimitError } = await Promise.resolve().then(() => __importStar(require('./platform-api/anonymous-ai-session-client')));
393
- const message = anonSessionError instanceof Error
394
- ? anonSessionError.message
395
- : 'Anonymous AI session failed.';
396
- reportedFailure = {
397
- code: 'anonymous_ai_session_failed',
398
- message: (0, cli_scan_failure_report_1.truncateFailureMessage)(message),
399
- };
400
- console.error(`[scan] ${message}`);
401
- process.exitCode =
402
- anonSessionError instanceof CliAnonymousIpLimitError ? 2 : 1;
403
- return;
474
+ // AI is optional: keep scanning without it so the user still
475
+ // gets the local .dataparade/ output.
476
+ continueWithoutAi(anonSessionError);
404
477
  }
405
478
  }
406
479
  const configValidation = (0, scan_config_schema_1.validateScanConfiguration)(config);
@@ -418,14 +491,17 @@ function createProgram() {
418
491
  failurePhase: 'config_validation',
419
492
  failureCode: 'invalid_configuration',
420
493
  });
421
- console.error(`[scan] invalid configuration:\n${configValidation.errors.map((e) => ` - ${e}`).join('\n')}`);
494
+ const configErrors = configValidation.errors
495
+ .map((e) => ` - ${e}`)
496
+ .join('\n');
497
+ reportScanError(`[scan] invalid configuration:\n${configErrors}`, `Invalid configuration:\n${configErrors}`);
422
498
  process.exitCode = 2;
423
499
  return;
424
500
  }
425
501
  if (isInteractive && warnings.length > 0) {
426
502
  if (friendlyTty) {
427
503
  for (const w of warnings)
428
- progressUi.warn(w);
504
+ ui.warn(w);
429
505
  }
430
506
  else {
431
507
  console.warn(`[scan] warnings:\n${warnings.map((w) => ` - ${w}`).join('\n')}`);
@@ -439,13 +515,13 @@ function createProgram() {
439
515
  progressUi.warn(tree.warning);
440
516
  }
441
517
  const orchestratorResult = await runScanPipeline(resolvedScanRoot, config, (progress) => {
442
- progressUi.onProgress(progress);
518
+ ui.onProgress(progress);
443
519
  }, (recognition) => {
444
- progressUi.onRecognition(recognition);
520
+ ui.onRecognition(recognition);
445
521
  });
446
522
  const { scanResult, redFlags } = orchestratorResult;
447
523
  if (scanResult.aiInferenceSummary) {
448
- progressUi.onAiResult({
524
+ ui.onAiResult({
449
525
  proposalsApplied: scanResult.aiInferenceSummary.proposalsApplied,
450
526
  });
451
527
  }
@@ -473,7 +549,7 @@ function createProgram() {
473
549
  }
474
550
  // Friendly TTY only shows the block on request (--ai-verbose).
475
551
  if (!friendlyTty || options.aiVerbose) {
476
- progressUi.showTechnicalDetails('Scan details', technicalLines);
552
+ ui.showTechnicalDetails('Scan details', technicalLines);
477
553
  }
478
554
  for (const w of scanResult.warnings ?? []) {
479
555
  if (w.startsWith('ai-provider:')) {
@@ -486,10 +562,10 @@ function createProgram() {
486
562
  failurePhase: 'ai_provider',
487
563
  failureCode: 'ai_provider_warning',
488
564
  });
489
- progressUi.warn(w);
565
+ ui.warn(w);
490
566
  }
491
567
  else if (w.startsWith('red-flag:')) {
492
- progressUi.warn(w);
568
+ ui.warn(w);
493
569
  }
494
570
  }
495
571
  if (scanResult.errors?.length) {
@@ -533,7 +609,7 @@ function createProgram() {
533
609
  const message = graphError instanceof Error
534
610
  ? graphError.message
535
611
  : 'Unknown error while building diagram graph.';
536
- console.error(`[scan] warning: unable to build diagram graph: ${message}`);
612
+ reportScanError(`[scan] warning: unable to build diagram graph: ${message}`, `Could not build the diagram: ${message}`);
537
613
  }
538
614
  process.exitCode = 1;
539
615
  }
@@ -562,7 +638,7 @@ function createProgram() {
562
638
  scannerVersion: scannerVersionFromPackage(),
563
639
  });
564
640
  // Friendly TTY/plain progress line (additive).
565
- progressUi.onWroteDataflow(dataflowOutputPath);
641
+ ui.onWroteDataflow(dataflowOutputPath);
566
642
  // Machine line for scripts / CI (non-TTY). The friendly TTY UI
567
643
  // shows the path in its own success line instead.
568
644
  if (!friendlyTty) {
@@ -593,7 +669,7 @@ function createProgram() {
593
669
  quiet: friendlyTty,
594
670
  });
595
671
  if (uploadResult.previewUrl) {
596
- progressUi.onPreviewUrl(uploadResult.previewUrl, uploadResult.notice);
672
+ ui.onPreviewUrl(uploadResult.previewUrl, uploadResult.notice);
597
673
  }
598
674
  }
599
675
  catch (uploadError) {
@@ -601,14 +677,17 @@ function createProgram() {
601
677
  ? uploadError.message
602
678
  : 'Unknown upload error.';
603
679
  if (friendlyTty) {
604
- progressUi.warn(`Auto-upload failed: ${uploadMessage}`);
680
+ ui.warn(`Auto-upload failed: ${uploadMessage}`);
605
681
  }
606
682
  else {
607
683
  console.error(`[scan] Auto-upload failed: ${uploadMessage}`);
608
684
  }
685
+ // The scan itself succeeded (exit 0), but do not close with
686
+ // the success line: say the upload failed and how to retry.
687
+ progressUi.onUploadFailed(describeAutoUploadFailure(uploadError, dataflowOutputPath, Boolean(workspaceApiKey)));
609
688
  }
610
689
  }
611
- progressUi.finish();
690
+ ui.finish();
612
691
  }
613
692
  catch (dataflowError) {
614
693
  reportedFailure = {
@@ -629,15 +708,18 @@ function createProgram() {
629
708
  const message = dataflowError instanceof Error
630
709
  ? dataflowError.message
631
710
  : 'Unknown error while writing dataflow.json.';
632
- console.error(`[scan] error: failed to write dataflow.json: ${message}`);
711
+ reportScanError(`[scan] error: failed to write dataflow.json: ${message}`, `Could not save dataflow.json: ${message}`);
633
712
  process.exitCode = 1;
634
713
  }
635
714
  }
636
- if (platformQuotaApiKey && cliQuotaJobId) {
715
+ if (platformQuotaApiKey &&
716
+ cliQuotaJobId &&
717
+ quotaCompletionStatus === 'none') {
637
718
  const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
638
719
  const exitFailed = (process.exitCode ?? 0) !== 0;
639
720
  const platformAiMode = (0, validate_scan_ai_1.resolveAiMode)(config) === 'platform';
640
- await cliScanComplete({
721
+ quotaCompletionStatus = 'in_flight';
722
+ quotaCompletionInFlight = cliScanComplete({
641
723
  apiKey: platformQuotaApiKey,
642
724
  jobId: cliQuotaJobId,
643
725
  status: exitFailed ? 'failed' : 'completed',
@@ -651,7 +733,18 @@ function createProgram() {
651
733
  ? (reportedFailure?.message ?? fallbackFailureMessage)
652
734
  : undefined,
653
735
  });
654
- quotaCompletionReported = true;
736
+ try {
737
+ await quotaCompletionInFlight;
738
+ quotaCompletionStatus = 'done';
739
+ }
740
+ catch (completeError) {
741
+ // Not reported: let the finally (or an interrupt) retry as failed.
742
+ quotaCompletionStatus = 'none';
743
+ throw completeError;
744
+ }
745
+ finally {
746
+ quotaCompletionInFlight = undefined;
747
+ }
655
748
  // The Clack outro already closes the run in friendly TTY.
656
749
  if (isInteractive && !friendlyTty) {
657
750
  console.log('[scan] Scan finished — you can start a new scan now.');
@@ -685,11 +778,13 @@ function createProgram() {
685
778
  ? 'scan_already_running'
686
779
  : 'scan_exception',
687
780
  });
688
- console.error(quotaBlocked
781
+ // Clack: the error closes the live spinner. A raw line would land
782
+ // mid-spinner and Clack would add its own "Canceled" on exit.
783
+ reportScanError(quotaBlocked
689
784
  ? `[scan] workspace quota: ${message}`
690
785
  : scanInProgress
691
786
  ? `[scan] scan in progress: ${message}`
692
- : `Scan failed: ${message}`);
787
+ : `Scan failed: ${message}`, quotaBlocked || scanInProgress ? message : `Scan failed: ${message}`);
693
788
  process.exitCode = 1;
694
789
  }
695
790
  finally {
@@ -710,25 +805,35 @@ function createProgram() {
710
805
  });
711
806
  if (platformQuotaApiKey &&
712
807
  cliQuotaJobId &&
713
- !quotaCompletionReported) {
808
+ quotaCompletionStatus === 'none') {
714
809
  try {
715
810
  const { cliScanComplete } = await Promise.resolve().then(() => __importStar(require('./platform-api/scan-quota-client')));
716
- await cliScanComplete({
811
+ quotaCompletionStatus = 'in_flight';
812
+ quotaCompletionInFlight = cliScanComplete({
717
813
  apiKey: platformQuotaApiKey,
718
814
  jobId: cliQuotaJobId,
719
815
  status: 'failed',
720
816
  failureCode: reportedFailure?.code ?? 'scan_failed',
721
817
  failureMessage: reportedFailure?.message ?? fallbackFailureMessage,
722
818
  });
723
- quotaCompletionReported = true;
724
- if (isInteractive) {
819
+ await quotaCompletionInFlight;
820
+ quotaCompletionStatus = 'done';
821
+ // Clack already closed the run with the error line.
822
+ if (isInteractive && !friendlyTty) {
725
823
  console.log('[scan] Scan finished — you can start a new scan now.');
726
824
  }
727
825
  }
728
826
  catch {
729
827
  // Quota report failure must not mask the original scan error.
828
+ quotaCompletionStatus = 'none';
829
+ }
830
+ finally {
831
+ quotaCompletionInFlight = undefined;
730
832
  }
731
833
  }
834
+ // Last: Ctrl+C during the usage event or complete above must still
835
+ // release the lock.
836
+ uninstallInterruptHandlers();
732
837
  }
733
838
  });
734
839
  program
@@ -5,9 +5,12 @@ export declare function resolveByokModel(env: NodeJS.ProcessEnv): string | undef
5
5
  export declare function resolveScanAiInference(env: NodeJS.ProcessEnv): string | undefined;
6
6
  export declare function resolveHostedInferProxyUrl(env: NodeJS.ProcessEnv): string | undefined;
7
7
  /**
8
- * Mute SCAN_AI_DEBUG logs for this run. The interactive progress UI sets this:
9
- * raw `[dataparade-ai]` lines written mid-spinner break its layout.
8
+ * Mute SCAN_AI_DEBUG logs and transient AI notices (e.g. network retries) for
9
+ * this run. The interactive progress UI sets this: raw `[dataparade-ai]` lines
10
+ * written mid-spinner break its layout.
10
11
  */
11
12
  export declare function setScanAiDebugSuppressed(suppressed: boolean): void;
13
+ /** True while the interactive UI owns the terminal (see setScanAiDebugSuppressed). */
14
+ export declare function isScanAiDebugSuppressed(): boolean;
12
15
  /** Extra provider HTTP / normalization logging (all providers, not OpenAI-only). */
13
16
  export declare function isScanAiDebugEnabled(env?: NodeJS.ProcessEnv): boolean;