@boringparts/verule 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,703 @@
1
+ import { isAbsolute, relative } from "node:path";
2
+ import { performance } from "node:perf_hooks";
3
+ import { locationMatchesTarget, locationsOverlap, normalizeObserveConfig as normalizeEngineObserveConfig, } from "tssae";
4
+ import { toVeruleError, VeruleExecutionError, } from "./types.js";
5
+ export {};
6
+ function normalizeSlashes(value) {
7
+ return value.replaceAll("\\", "/");
8
+ }
9
+ function normalizeRelativeFile(file, cwd) {
10
+ const normalized = normalizeSlashes(file).trim();
11
+ const normCwd = normalizeSlashes(cwd);
12
+ let rel = normalized;
13
+ if (isAbsolute(normalized) || /^[A-Za-z]:\//u.test(normalized)) {
14
+ rel = normalizeSlashes(relative(normCwd, normalized));
15
+ }
16
+ while (rel.startsWith("./")) {
17
+ rel = rel.slice(2);
18
+ }
19
+ return rel;
20
+ }
21
+ function parsePositiveInt(raw, label, input) {
22
+ if (!/^\d+$/u.test(raw)) {
23
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid ${label} in target "${input}": expected positive integer.`);
24
+ }
25
+ const value = Number(raw);
26
+ if (!Number.isSafeInteger(value) || value < 1) {
27
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid ${label} in target "${input}": must be >= 1.`);
28
+ }
29
+ return value;
30
+ }
31
+ /** Parses `<file[:line[:column]]>` into a normalized `SourceTarget` relative to `cwd`. */
32
+ export function parseTargetSpec(input, cwd) {
33
+ const trimmed = input.trim();
34
+ if (trimmed === "") {
35
+ throw new VeruleExecutionError("INVALID_CONFIG", "Target location (--at) cannot be empty.");
36
+ }
37
+ let filePart = trimmed;
38
+ let line;
39
+ let column;
40
+ const lastColon = trimmed.lastIndexOf(":");
41
+ if (lastColon > 1) {
42
+ const tail = trimmed.slice(lastColon + 1);
43
+ const prefix = trimmed.slice(0, lastColon);
44
+ if (/^\d+$/u.test(tail)) {
45
+ const secondLastColon = prefix.lastIndexOf(":");
46
+ if (secondLastColon > 1) {
47
+ const mid = prefix.slice(secondLastColon + 1);
48
+ if (/^\d+$/u.test(mid)) {
49
+ filePart = prefix.slice(0, secondLastColon);
50
+ line = parsePositiveInt(mid, "line", input);
51
+ column = parsePositiveInt(tail, "column", input);
52
+ }
53
+ else {
54
+ filePart = prefix;
55
+ line = parsePositiveInt(tail, "line", input);
56
+ }
57
+ }
58
+ else {
59
+ filePart = prefix;
60
+ line = parsePositiveInt(tail, "line", input);
61
+ }
62
+ }
63
+ else if (tail === "" || !tail.includes("/")) {
64
+ // Allow Windows drive letters like C:\foo only when colon is at index 1; otherwise reject non-numeric suffix.
65
+ if (lastColon > 1) {
66
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid target location "${input}": expected <file[:line[:column]]>.`);
67
+ }
68
+ }
69
+ }
70
+ else if (lastColon === 0) {
71
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid target location "${input}": missing file path.`);
72
+ }
73
+ const normalizedFile = normalizeRelativeFile(filePart, cwd);
74
+ if (normalizedFile === "" || normalizedFile === ".") {
75
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid target location "${input}": missing file path.`);
76
+ }
77
+ return {
78
+ file: normalizedFile,
79
+ ...(line !== undefined ? { line } : {}),
80
+ ...(column !== undefined ? { column } : {}),
81
+ };
82
+ }
83
+ /** Normalizes a string or `SourceTarget` relative to `cwd`. */
84
+ export function normalizeTargetSpec(target, cwd) {
85
+ if (typeof target === "string") {
86
+ return parseTargetSpec(target, cwd);
87
+ }
88
+ const file = normalizeRelativeFile(target.file, cwd);
89
+ if (file === "" || file === ".") {
90
+ throw new VeruleExecutionError("INVALID_CONFIG", "Target location file cannot be empty.");
91
+ }
92
+ if (target.line !== undefined &&
93
+ (!Number.isInteger(target.line) || target.line < 1)) {
94
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid target line ${String(target.line)}: must be >= 1.`);
95
+ }
96
+ if (target.column !== undefined &&
97
+ (!Number.isInteger(target.column) || target.column < 1)) {
98
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid target column ${String(target.column)}: must be >= 1.`);
99
+ }
100
+ return {
101
+ file,
102
+ ...(target.line !== undefined ? { line: target.line } : {}),
103
+ ...(target.column !== undefined ? { column: target.column } : {}),
104
+ };
105
+ }
106
+ function parseNonNegativeInt(raw, source) {
107
+ if (!/^\d+$/u.test(raw)) {
108
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid observe limit "${source}": expected a non-negative integer.`);
109
+ }
110
+ const value = Number(raw);
111
+ if (!Number.isSafeInteger(value)) {
112
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid observe limit "${source}" ${String(value)}: must be a non-negative integer.`);
113
+ }
114
+ return value;
115
+ }
116
+ /** Parses `--observe-limit` strings (e.g. `20`, `4096b`, `4kb`, `10items`) or SDK limit objects. */
117
+ export function parseObserveLimit(input) {
118
+ if (typeof input !== "string") {
119
+ try {
120
+ return (normalizeEngineObserveConfig({ mode: "off", limit: input }).limit ?? {});
121
+ }
122
+ catch (err) {
123
+ throw toVeruleError(err, "INVALID_CONFIG");
124
+ }
125
+ }
126
+ const normalized = input.trim().toLowerCase();
127
+ if (normalized === "") {
128
+ throw new VeruleExecutionError("INVALID_CONFIG", "Observe limit cannot be empty.");
129
+ }
130
+ if (normalized.startsWith("bytes:")) {
131
+ return {
132
+ maxBytes: parseNonNegativeInt(normalized.slice("bytes:".length), input),
133
+ };
134
+ }
135
+ if (normalized.startsWith("items:")) {
136
+ return {
137
+ maxItems: parseNonNegativeInt(normalized.slice("items:".length), input),
138
+ };
139
+ }
140
+ if (normalized.endsWith("kb")) {
141
+ const kb = parseNonNegativeInt(normalized.slice(0, -2), input);
142
+ return { maxBytes: kb * 1024 };
143
+ }
144
+ if (normalized.endsWith("b")) {
145
+ return { maxBytes: parseNonNegativeInt(normalized.slice(0, -1), input) };
146
+ }
147
+ if (normalized.endsWith("items")) {
148
+ return { maxItems: parseNonNegativeInt(normalized.slice(0, -5), input) };
149
+ }
150
+ return { maxItems: parseNonNegativeInt(normalized, input) };
151
+ }
152
+ /** Normalizes Verule `observe` and `observeLimit` inputs into validated `tssae` observe options. */
153
+ export function normalizeObserveConfig(observe, observeLimit) {
154
+ const mode = observe === undefined
155
+ ? "off"
156
+ : typeof observe === "string"
157
+ ? observe
158
+ : observe.mode;
159
+ const rawLimit = typeof observe === "object" && observe.limit !== undefined
160
+ ? observe.limit
161
+ : observeLimit;
162
+ const limit = typeof rawLimit === "string" ? parseObserveLimit(rawLimit) : rawLimit;
163
+ try {
164
+ return normalizeEngineObserveConfig({
165
+ mode,
166
+ ...(limit !== undefined ? { limit } : {}),
167
+ });
168
+ }
169
+ catch (err) {
170
+ throw toVeruleError(err, "INVALID_CONFIG");
171
+ }
172
+ }
173
+ /** Collects observation metrics, bounded detail entries, and explain traces for a check run. */
174
+ export class ObservationCollector {
175
+ mode;
176
+ limit;
177
+ explainTarget;
178
+ #startedAt;
179
+ #configAndOpenMs;
180
+ #engineQueryMs = 0;
181
+ #ruleExecutionMs = 0;
182
+ #rpcBatches = 0;
183
+ #queryBatches = 0;
184
+ #bytesSent = 0;
185
+ #bytesReceived = 0;
186
+ #checkpointMs = 0;
187
+ #encodeMs = 0;
188
+ #writeMs = 0;
189
+ #queryCount = 0;
190
+ #computedQueryCount = 0;
191
+ #reusedQueryCount = 0;
192
+ #candidateCount = 0;
193
+ #checkpointCount = 0;
194
+ #truncated = false;
195
+ #droppedCount = 0;
196
+ #usedDetailBytes = 0;
197
+ #lowering = { functionsLowered: 0, verticesCreated: 0, durationMs: 0 };
198
+ #irCache = {
199
+ functionHits: 0,
200
+ functionMisses: 0,
201
+ filesReused: 0,
202
+ filesInvalidated: 0,
203
+ };
204
+ #summaryLookup = {
205
+ lookups: 0,
206
+ hits: 0,
207
+ misses: 0,
208
+ hitsBySource: { local: 0, package: 0, community: 0, builtin: 0 },
209
+ };
210
+ #providers = new Set();
211
+ #details = [];
212
+ #queriesByRule = new Map();
213
+ #checkpointsByRule = new Map();
214
+ #matchingCandidatesByRule = new Map();
215
+ #cleanupPathsByRule = new Map();
216
+ #gapsByRule = new Map();
217
+ constructor(options) {
218
+ this.mode = options.mode;
219
+ this.limit = options.limit;
220
+ this.explainTarget = options.explainTarget;
221
+ this.#configAndOpenMs = options.configAndOpenMs ?? 0;
222
+ this.#startedAt = this.isObserveEnabled() ? performance.now() : 0;
223
+ }
224
+ isObserveEnabled() {
225
+ return this.mode !== "off";
226
+ }
227
+ isExplainEnabled() {
228
+ return this.explainTarget !== undefined;
229
+ }
230
+ isActive() {
231
+ return this.isObserveEnabled() || this.isExplainEnabled();
232
+ }
233
+ addConfigAndOpenMs(ms) {
234
+ if (this.isObserveEnabled()) {
235
+ this.#configAndOpenMs += ms;
236
+ }
237
+ }
238
+ addEngineQueryMs(ms) {
239
+ if (this.isObserveEnabled()) {
240
+ this.#engineQueryMs += ms;
241
+ }
242
+ }
243
+ addRuleExecutionMs(ms) {
244
+ if (this.isObserveEnabled()) {
245
+ this.#ruleExecutionMs += ms;
246
+ }
247
+ }
248
+ recordRpcCall(io) {
249
+ if (!this.isObserveEnabled()) {
250
+ return;
251
+ }
252
+ this.#rpcBatches += 1;
253
+ if (io.isQueryBatch) {
254
+ this.#queryBatches += 1;
255
+ }
256
+ this.#bytesSent += io.bytesSent;
257
+ this.#bytesReceived += io.bytesReceived;
258
+ this.#encodeMs += io.encodeMs;
259
+ this.#writeMs += io.writeMs;
260
+ const engineMetrics = io.engineMetrics;
261
+ if (!engineMetrics) {
262
+ return;
263
+ }
264
+ this.#encodeMs += engineMetrics.encodeMs;
265
+ if (engineMetrics.steps) {
266
+ for (const step of engineMetrics.steps) {
267
+ this.#providers.add(step.provider);
268
+ if (this.mode === "detail" && step.details) {
269
+ for (const item of step.details) {
270
+ this.#appendDetail({
271
+ kind: "engineStep",
272
+ provider: step.provider,
273
+ durationMs: step.durationMs,
274
+ summary: item.summary,
275
+ ...(item.file !== undefined &&
276
+ item.line !== undefined &&
277
+ item.column !== undefined
278
+ ? {
279
+ detail: {
280
+ file: item.file,
281
+ line: item.line,
282
+ column: item.column,
283
+ kind: item.kind,
284
+ },
285
+ }
286
+ : {}),
287
+ });
288
+ }
289
+ }
290
+ }
291
+ }
292
+ if (engineMetrics.lowering) {
293
+ this.#lowering.functionsLowered +=
294
+ engineMetrics.lowering.functionsLowered;
295
+ this.#lowering.verticesCreated += engineMetrics.lowering.verticesCreated;
296
+ this.#lowering.durationMs += engineMetrics.lowering.durationMs;
297
+ }
298
+ if (engineMetrics.irCache) {
299
+ this.#irCache.functionHits += engineMetrics.irCache.functionHits;
300
+ this.#irCache.functionMisses += engineMetrics.irCache.functionMisses;
301
+ this.#irCache.filesReused += engineMetrics.irCache.filesReused;
302
+ this.#irCache.filesInvalidated += engineMetrics.irCache.filesInvalidated;
303
+ }
304
+ if (engineMetrics.summaryLookup) {
305
+ this.#summaryLookup.lookups += engineMetrics.summaryLookup.lookups;
306
+ this.#summaryLookup.hits += engineMetrics.summaryLookup.hits;
307
+ this.#summaryLookup.misses += engineMetrics.summaryLookup.misses;
308
+ this.#summaryLookup.hitsBySource.local +=
309
+ engineMetrics.summaryLookup.hitsBySource.local;
310
+ this.#summaryLookup.hitsBySource.package +=
311
+ engineMetrics.summaryLookup.hitsBySource.package;
312
+ this.#summaryLookup.hitsBySource.community +=
313
+ engineMetrics.summaryLookup.hitsBySource.community;
314
+ this.#summaryLookup.hitsBySource.builtin +=
315
+ engineMetrics.summaryLookup.hitsBySource.builtin;
316
+ }
317
+ if (engineMetrics.truncated) {
318
+ this.#truncated = true;
319
+ }
320
+ if (engineMetrics.droppedCount > 0) {
321
+ this.#droppedCount += engineMetrics.droppedCount;
322
+ }
323
+ }
324
+ recordQuery(params) {
325
+ if (!this.isActive()) {
326
+ return;
327
+ }
328
+ if (this.isObserveEnabled()) {
329
+ this.#queryCount += 1;
330
+ if (params.cacheStatus === "computed") {
331
+ this.#computedQueryCount += 1;
332
+ }
333
+ else {
334
+ this.#reusedQueryCount += 1;
335
+ }
336
+ this.#candidateCount += params.candidateCount;
337
+ const providersToAdd = params.providers ?? [params.provider];
338
+ for (const providerId of providersToAdd) {
339
+ this.#providers.add(providerId);
340
+ }
341
+ if (this.mode === "detail") {
342
+ this.#appendDetail({
343
+ kind: "query",
344
+ ruleId: params.ruleId,
345
+ projectId: params.projectId,
346
+ provider: params.provider,
347
+ name: params.op,
348
+ cacheStatus: params.cacheStatus,
349
+ candidateCount: params.candidateCount,
350
+ durationMs: params.durationMs,
351
+ summary: params.summary,
352
+ ...(params.detail !== undefined ? { detail: params.detail } : {}),
353
+ });
354
+ }
355
+ }
356
+ if (this.isExplainEnabled()) {
357
+ const ruleQueries = this.#queriesByRule.get(params.ruleId) ?? [];
358
+ const matchedTarget = (params.matchedLocations?.length ?? 0) > 0;
359
+ ruleQueries.push({
360
+ ruleId: params.ruleId,
361
+ queryIndex: ruleQueries.length + 1,
362
+ op: params.op,
363
+ projectId: params.projectId,
364
+ provider: params.provider,
365
+ ...(params.providers !== undefined
366
+ ? { providers: params.providers }
367
+ : {}),
368
+ cacheStatus: params.cacheStatus,
369
+ candidateCount: params.candidateCount,
370
+ matchedTarget,
371
+ durationMs: params.durationMs,
372
+ summary: params.summary,
373
+ ...(params.detail !== undefined ? { detail: params.detail } : {}),
374
+ });
375
+ this.#queriesByRule.set(params.ruleId, ruleQueries);
376
+ if (params.matchedLocations && params.matchedLocations.length > 0) {
377
+ const list = this.#matchingCandidatesByRule.get(params.ruleId) ?? [];
378
+ for (const loc of params.matchedLocations) {
379
+ list.push(loc);
380
+ }
381
+ this.#matchingCandidatesByRule.set(params.ruleId, list);
382
+ }
383
+ }
384
+ }
385
+ recordCheckpoint(params) {
386
+ if (!this.isActive()) {
387
+ return;
388
+ }
389
+ const start = performance.now();
390
+ if (this.isObserveEnabled()) {
391
+ this.#checkpointCount += 1;
392
+ }
393
+ const at = params.resolveLocation();
394
+ const matchesExplain = this.explainTarget !== undefined &&
395
+ at !== undefined &&
396
+ (locationMatchesTarget(at, this.explainTarget) ||
397
+ this.hasMatchingCandidateOverlapping(params.ruleId, at));
398
+ const shouldEvalForDetail = this.mode === "detail" && !this.#isItemLimitReached();
399
+ const shouldEvalForExplain = this.isExplainEnabled() && matchesExplain;
400
+ let evaluatedDetail;
401
+ let hasEvaluatedDetail = false;
402
+ if (params.detailFn && (shouldEvalForDetail || shouldEvalForExplain)) {
403
+ evaluatedDetail = params.detailFn();
404
+ hasEvaluatedDetail = true;
405
+ }
406
+ if (this.mode === "detail") {
407
+ this.#appendDetail({
408
+ kind: "checkpoint",
409
+ ruleId: params.ruleId,
410
+ projectId: params.projectId,
411
+ name: params.name,
412
+ outcome: params.outcome,
413
+ ...(at !== undefined ? { at } : {}),
414
+ summary: `${params.name}: ${params.outcome}`,
415
+ ...(hasEvaluatedDetail ? { detail: evaluatedDetail } : {}),
416
+ });
417
+ }
418
+ if (this.isExplainEnabled()) {
419
+ const list = this.#checkpointsByRule.get(params.ruleId) ?? [];
420
+ list.push({
421
+ ruleId: params.ruleId,
422
+ projectId: params.projectId,
423
+ name: params.name,
424
+ outcome: params.outcome,
425
+ ...(at !== undefined ? { at } : {}),
426
+ ...(hasEvaluatedDetail ? { detail: evaluatedDetail } : {}),
427
+ });
428
+ this.#checkpointsByRule.set(params.ruleId, list);
429
+ }
430
+ if (this.isObserveEnabled()) {
431
+ this.#checkpointMs += performance.now() - start;
432
+ }
433
+ }
434
+ hasMatchingCandidateOverlapping(ruleId, loc) {
435
+ const candidates = this.#matchingCandidatesByRule.get(ruleId);
436
+ if (!candidates)
437
+ return false;
438
+ return candidates.some((candidate) => locationsOverlap(candidate, loc));
439
+ }
440
+ recordCleanupPaths(params) {
441
+ if (!this.isExplainEnabled()) {
442
+ return;
443
+ }
444
+ const list = this.#cleanupPathsByRule.get(params.ruleId) ?? [];
445
+ for (const path of params.paths) {
446
+ list.push({
447
+ targetLocations: params.targetLocations,
448
+ path,
449
+ });
450
+ }
451
+ this.#cleanupPathsByRule.set(params.ruleId, list);
452
+ }
453
+ recordRuleGaps(ruleId, gaps, relatedLocation) {
454
+ if (!this.isExplainEnabled() || gaps.length === 0) {
455
+ return;
456
+ }
457
+ const list = this.#gapsByRule.get(ruleId) ?? [];
458
+ for (const gap of gaps) {
459
+ list.push({
460
+ gap,
461
+ ...(relatedLocation !== undefined ? { relatedLocation } : {}),
462
+ });
463
+ }
464
+ this.#gapsByRule.set(ruleId, list);
465
+ }
466
+ #isItemLimitReached() {
467
+ return (this.#truncated ||
468
+ (this.limit?.maxItems !== undefined &&
469
+ this.#details.length >= this.limit.maxItems));
470
+ }
471
+ #appendDetail(entry) {
472
+ if (this.#isItemLimitReached()) {
473
+ this.#truncated = true;
474
+ this.#droppedCount += 1;
475
+ return;
476
+ }
477
+ const encodeStart = performance.now();
478
+ const encoded = JSON.stringify(entry);
479
+ const entryBytes = Buffer.byteLength(encoded, "utf8");
480
+ this.#encodeMs += performance.now() - encodeStart;
481
+ if (this.limit?.maxBytes !== undefined &&
482
+ this.#usedDetailBytes + entryBytes > this.limit.maxBytes) {
483
+ this.#truncated = true;
484
+ this.#droppedCount += 1;
485
+ return;
486
+ }
487
+ this.#usedDetailBytes += entryBytes;
488
+ this.#details.push(entry);
489
+ }
490
+ buildObservationReport() {
491
+ if (!this.isObserveEnabled()) {
492
+ return undefined;
493
+ }
494
+ const mode = this.mode === "detail" ? "detail" : "summary";
495
+ const totalMs = Math.max(0, performance.now() - this.#startedAt);
496
+ const lowering = {
497
+ functionsLowered: this.#lowering.functionsLowered,
498
+ verticesCreated: this.#lowering.verticesCreated,
499
+ durationMs: roundMs(this.#lowering.durationMs),
500
+ };
501
+ const irCache = { ...this.#irCache };
502
+ const summaryLookup = {
503
+ lookups: this.#summaryLookup.lookups,
504
+ hits: this.#summaryLookup.hits,
505
+ misses: this.#summaryLookup.misses,
506
+ hitsBySource: { ...this.#summaryLookup.hitsBySource },
507
+ };
508
+ return {
509
+ mode,
510
+ phases: {
511
+ configAndOpenMs: roundMs(this.#configAndOpenMs),
512
+ engineQueryMs: roundMs(this.#engineQueryMs),
513
+ ruleExecutionMs: roundMs(this.#ruleExecutionMs),
514
+ totalMs: roundMs(totalMs),
515
+ },
516
+ rpc: {
517
+ batches: this.#rpcBatches,
518
+ queryBatches: this.#queryBatches,
519
+ bytesSent: this.#bytesSent,
520
+ bytesReceived: this.#bytesReceived,
521
+ },
522
+ overhead: {
523
+ checkpointMs: roundMs(this.#checkpointMs),
524
+ encodeMs: roundMs(this.#encodeMs),
525
+ writeMs: roundMs(this.#writeMs),
526
+ },
527
+ queryCount: this.#queryCount,
528
+ computedQueryCount: this.#computedQueryCount,
529
+ reusedQueryCount: this.#reusedQueryCount,
530
+ candidateCount: this.#candidateCount,
531
+ checkpointCount: this.#checkpointCount,
532
+ providers: [...this.#providers].toSorted(),
533
+ lowering,
534
+ irCache,
535
+ summaryLookup,
536
+ ...(this.limit !== undefined ? { limit: this.limit } : {}),
537
+ truncated: this.#truncated,
538
+ droppedCount: this.#droppedCount,
539
+ ...(mode === "detail" ? { details: [...this.#details] } : {}),
540
+ };
541
+ }
542
+ buildExplainResult(params) {
543
+ const target = this.explainTarget;
544
+ if (!target) {
545
+ throw new VeruleExecutionError("ENGINE_ERROR", "Cannot build explanation without a target location.");
546
+ }
547
+ const queries = this.#queriesByRule.get(params.ruleId) ?? [];
548
+ const checkpoints = this.#checkpointsByRule.get(params.ruleId) ?? [];
549
+ const matchingCandidates = this.#matchingCandidatesByRule.get(params.ruleId) ?? [];
550
+ const hasTargetCheckpoint = checkpoints.some((cp) => cp.at !== undefined && locationMatchesTarget(cp.at, target));
551
+ const inCandidates = matchingCandidates.length > 0 || hasTargetCheckpoint;
552
+ const relevantCheckpoints = checkpoints
553
+ .filter((cp) => cp.at !== undefined &&
554
+ (locationMatchesTarget(cp.at, target) ||
555
+ matchingCandidates.some((cand) => locationsOverlap(cand, cp.at))))
556
+ .map((cp) => ({
557
+ name: cp.name,
558
+ ruleId: cp.ruleId,
559
+ projectId: cp.projectId,
560
+ outcome: cp.outcome,
561
+ ...(cp.at !== undefined ? { at: cp.at } : {}),
562
+ ...(cp.detail !== undefined ? { detail: cp.detail } : {}),
563
+ }));
564
+ const querySteps = queries.map((q) => ({
565
+ queryIndex: q.queryIndex,
566
+ op: q.op,
567
+ projectId: q.projectId,
568
+ provider: q.provider,
569
+ cacheStatus: q.cacheStatus,
570
+ candidateCount: q.candidateCount,
571
+ matchedTarget: q.matchedTarget,
572
+ durationMs: roundMs(q.durationMs),
573
+ summary: q.summary,
574
+ ...(q.detail !== undefined ? { detail: q.detail } : {}),
575
+ }));
576
+ const providers = [
577
+ ...new Set(queries.flatMap((q) => q.providers ?? [q.provider])),
578
+ ].toSorted();
579
+ const projectsChecked = params.projects.map((p) => p.projectId);
580
+ const matchingDiagnostic = params.diagnostics.find((diag) => diag.ruleId === params.ruleId && locationMatchesTarget(diag.at, target));
581
+ const matchingSuppression = params.suppressions?.find((sup) => sup.ruleId === params.ruleId && locationMatchesTarget(sup.at, target));
582
+ const targetInAnyProject = params.projects.some((project) => project.sourceFiles.includes(target.file));
583
+ const excludedCheckpoint = relevantCheckpoints.find((cp) => cp.outcome === "exclude" &&
584
+ cp.at !== undefined &&
585
+ locationMatchesTarget(cp.at, target)) ?? relevantCheckpoints.find((cp) => cp.outcome === "exclude");
586
+ const firstNonMatchingFindSyntax = querySteps.find((step) => step.op === "findSyntax" && !step.matchedTarget);
587
+ const lastMatchingQuery = [...querySteps]
588
+ .reverse()
589
+ .find((step) => step.matchedTarget);
590
+ let status;
591
+ let summary;
592
+ let excludedByQuery;
593
+ let excludedByCheckpoint;
594
+ let inlineIgnore;
595
+ const matchingCleanupEntries = (this.#cleanupPathsByRule.get(params.ruleId) ?? []).filter((entry) => entry.targetLocations.some((loc) => locationMatchesTarget(loc, target) ||
596
+ matchingCandidates.some((cand) => locationsOverlap(cand, loc))));
597
+ const cleanupPaths = [];
598
+ const seenCleanupKeys = new Set();
599
+ for (const entry of matchingCleanupEntries) {
600
+ const key = `${entry.path.instanceKey}:${entry.path.scopeLocation.file}:${entry.path.scopeLocation.start}`;
601
+ if (!seenCleanupKeys.has(key)) {
602
+ seenCleanupKeys.add(key);
603
+ cleanupPaths.push(entry.path);
604
+ }
605
+ }
606
+ const matchesLoc = (loc) => loc !== undefined &&
607
+ (locationMatchesTarget(loc, target) ||
608
+ matchingCandidates.some((cand) => locationsOverlap(cand, loc)));
609
+ const relevantGaps = [];
610
+ const seenGapKeys = new Set();
611
+ const pushGap = (gap) => {
612
+ const key = JSON.stringify([
613
+ gap.kind,
614
+ gap.message,
615
+ gap.at?.file ?? null,
616
+ gap.at?.start ?? null,
617
+ gap.at?.end ?? null,
618
+ ]);
619
+ if (!seenGapKeys.has(key)) {
620
+ seenGapKeys.add(key);
621
+ relevantGaps.push(gap);
622
+ }
623
+ };
624
+ for (const entry of this.#gapsByRule.get(params.ruleId) ?? []) {
625
+ if (matchesLoc(entry.gap.at) ||
626
+ matchesLoc(entry.relatedLocation) ||
627
+ (entry.gap.at === undefined && inCandidates)) {
628
+ pushGap(entry.gap);
629
+ }
630
+ }
631
+ if (matchingDiagnostic) {
632
+ status = "reported";
633
+ summary = `Rule "${params.ruleId}" reported a diagnostic at ${formatTarget(target)}.`;
634
+ }
635
+ else if (matchingSuppression) {
636
+ status = "suppressed_by_ignore";
637
+ inlineIgnore = {
638
+ matched: true,
639
+ ruleId: matchingSuppression.ruleId,
640
+ reason: matchingSuppression.reason,
641
+ commentAt: matchingSuppression.directiveAt,
642
+ };
643
+ summary = `Diagnostic for rule "${params.ruleId}" at ${formatTarget(target)} was suppressed by verule-ignore-next-code-line at ${matchingSuppression.directiveAt.file}:${matchingSuppression.directiveAt.line}:${matchingSuppression.directiveAt.column} (reason: ${matchingSuppression.reason}).`;
644
+ }
645
+ else if (!targetInAnyProject) {
646
+ status = "target_not_in_project";
647
+ summary = `Target "${target.file}" is not part of any opened compiler project.`;
648
+ }
649
+ else if (cleanupPaths.length > 0) {
650
+ status = "covered_by_cleanup";
651
+ summary = `Target is covered by valid cleanup path(s) (${cleanupPaths.map((cp) => cp.instanceKey).join(", ")}).`;
652
+ }
653
+ else if (excludedCheckpoint) {
654
+ status = "excluded_by_checkpoint";
655
+ excludedByCheckpoint = excludedCheckpoint;
656
+ summary = `Target entered candidates and was excluded at checkpoint "${excludedCheckpoint.name}".`;
657
+ }
658
+ else if (relevantGaps.length > 0) {
659
+ status = "blocked_by_gap";
660
+ excludedByQuery = lastMatchingQuery ?? querySteps[0];
661
+ summary = `Target conclusion was blocked by ${relevantGaps.length} active gap(s) (${relevantGaps.map((g) => g.kind).join(", ")}).`;
662
+ }
663
+ else if (!inCandidates) {
664
+ status = "not_in_candidates";
665
+ excludedByQuery = firstNonMatchingFindSyntax ?? querySteps[0];
666
+ summary = excludedByQuery
667
+ ? `Target did not enter candidates in ${excludedByQuery.op} (${excludedByQuery.candidateCount} candidates, ${excludedByQuery.cacheStatus}).`
668
+ : `Target did not enter any candidate set for rule "${params.ruleId}".`;
669
+ }
670
+ else {
671
+ status = "rule_filtered";
672
+ excludedByQuery = lastMatchingQuery;
673
+ summary = `Target entered ${matchingCandidates.length} candidate(s) and rule "${params.ruleId}" did not report a diagnostic.`;
674
+ }
675
+ return {
676
+ ruleId: params.ruleId,
677
+ target,
678
+ status,
679
+ inCandidates,
680
+ summary,
681
+ projectsChecked,
682
+ matchingCandidates,
683
+ ...(excludedByQuery !== undefined ? { excludedByQuery } : {}),
684
+ ...(excludedByCheckpoint !== undefined ? { excludedByCheckpoint } : {}),
685
+ ...(inlineIgnore !== undefined ? { inlineIgnore } : {}),
686
+ queries: querySteps,
687
+ checkpoints: relevantCheckpoints,
688
+ gaps: relevantGaps,
689
+ providers,
690
+ cleanupPaths,
691
+ };
692
+ }
693
+ }
694
+ function formatTarget(target) {
695
+ if (target.line === undefined)
696
+ return target.file;
697
+ if (target.column === undefined)
698
+ return `${target.file}:${target.line}`;
699
+ return `${target.file}:${target.line}:${target.column}`;
700
+ }
701
+ function roundMs(value) {
702
+ return Math.round(value * 1000) / 1000;
703
+ }