@boringparts/verule 0.0.0-stage → 0.1.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,767 @@
1
+ import { isAbsolute, relative } from "node:path";
2
+ import { performance } from "node:perf_hooks";
3
+ import { locationMatchesTarget, locationsOverlap, } from "tssae";
4
+ import { 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) || value < 0) {
112
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid observe limit "${source}": 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 === "number") {
119
+ if (!Number.isSafeInteger(input) || input < 0) {
120
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid observe limit ${String(input)}: must be a non-negative integer.`);
121
+ }
122
+ return { maxItems: input };
123
+ }
124
+ if (typeof input === "object") {
125
+ if (input.maxItems !== undefined &&
126
+ (!Number.isSafeInteger(input.maxItems) || input.maxItems < 0)) {
127
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid maxItems ${String(input.maxItems)}: must be a non-negative integer.`);
128
+ }
129
+ if (input.maxBytes !== undefined &&
130
+ (!Number.isSafeInteger(input.maxBytes) || input.maxBytes < 0)) {
131
+ throw new VeruleExecutionError("INVALID_CONFIG", `Invalid maxBytes ${String(input.maxBytes)}: must be a non-negative integer.`);
132
+ }
133
+ return {
134
+ ...(input.maxItems !== undefined ? { maxItems: input.maxItems } : {}),
135
+ ...(input.maxBytes !== undefined ? { maxBytes: input.maxBytes } : {}),
136
+ };
137
+ }
138
+ const normalized = input.trim().toLowerCase();
139
+ if (normalized === "") {
140
+ throw new VeruleExecutionError("INVALID_CONFIG", "Observe limit cannot be empty.");
141
+ }
142
+ if (normalized.startsWith("bytes:")) {
143
+ return {
144
+ maxBytes: parseNonNegativeInt(normalized.slice("bytes:".length), input),
145
+ };
146
+ }
147
+ if (normalized.startsWith("items:")) {
148
+ return {
149
+ maxItems: parseNonNegativeInt(normalized.slice("items:".length), input),
150
+ };
151
+ }
152
+ if (normalized.endsWith("kb")) {
153
+ const kb = parseNonNegativeInt(normalized.slice(0, -2), input);
154
+ return { maxBytes: kb * 1024 };
155
+ }
156
+ if (normalized.endsWith("b")) {
157
+ return { maxBytes: parseNonNegativeInt(normalized.slice(0, -1), input) };
158
+ }
159
+ if (normalized.endsWith("items")) {
160
+ return { maxItems: parseNonNegativeInt(normalized.slice(0, -5), input) };
161
+ }
162
+ return { maxItems: parseNonNegativeInt(normalized, input) };
163
+ }
164
+ export function normalizeObserveConfig(observe, observeLimit) {
165
+ const mode = observe === undefined
166
+ ? "off"
167
+ : typeof observe === "string"
168
+ ? observe
169
+ : observe.mode;
170
+ const rawLimit = typeof observe === "object" && observe.limit !== undefined
171
+ ? observe.limit
172
+ : observeLimit;
173
+ const limit = rawLimit !== undefined ? parseObserveLimit(rawLimit) : undefined;
174
+ return {
175
+ mode,
176
+ ...(limit !== undefined ? { limit } : {}),
177
+ };
178
+ }
179
+ /** Collects observation metrics, bounded detail entries, and explain traces for a check run. */
180
+ export class ObservationCollector {
181
+ mode;
182
+ limit;
183
+ explainTarget;
184
+ #nativeAdapters;
185
+ #configuredAdapters;
186
+ #startedAt;
187
+ #configAndOpenMs;
188
+ #engineQueryMs = 0;
189
+ #ruleExecutionMs = 0;
190
+ #rpcBatches = 0;
191
+ #queryBatches = 0;
192
+ #bytesSent = 0;
193
+ #bytesReceived = 0;
194
+ #checkpointMs = 0;
195
+ #encodeMs = 0;
196
+ #writeMs = 0;
197
+ #queryCount = 0;
198
+ #computedQueryCount = 0;
199
+ #reusedQueryCount = 0;
200
+ #candidateCount = 0;
201
+ #checkpointCount = 0;
202
+ #truncated = false;
203
+ #droppedCount = 0;
204
+ #usedDetailBytes = 0;
205
+ #providers = new Set();
206
+ #engineExtractions = new Map();
207
+ #details = [];
208
+ #queriesByRule = new Map();
209
+ #checkpointsByRule = new Map();
210
+ #matchingCandidatesByRule = new Map();
211
+ #cleanupPathsByRule = new Map();
212
+ #gapsByRule = new Map();
213
+ #factGapsByRule = new Map();
214
+ #localGapsByRule = new Map();
215
+ #providerEvaluationsByRule = new Map();
216
+ constructor(options) {
217
+ this.mode = options.mode;
218
+ this.limit = options.limit;
219
+ this.explainTarget = options.explainTarget;
220
+ this.#configAndOpenMs = options.configAndOpenMs ?? 0;
221
+ this.#nativeAdapters = options.nativeAdapters ?? [];
222
+ this.#configuredAdapters = options.configuredAdapters ?? [];
223
+ this.#startedAt = this.isObserveEnabled() ? performance.now() : 0;
224
+ }
225
+ isObserveEnabled() {
226
+ return this.mode !== "off";
227
+ }
228
+ isExplainEnabled() {
229
+ return this.explainTarget !== undefined;
230
+ }
231
+ isActive() {
232
+ return this.isObserveEnabled() || this.isExplainEnabled();
233
+ }
234
+ addConfigAndOpenMs(ms) {
235
+ if (this.isObserveEnabled()) {
236
+ this.#configAndOpenMs += ms;
237
+ }
238
+ }
239
+ addEngineQueryMs(ms) {
240
+ if (this.isObserveEnabled()) {
241
+ this.#engineQueryMs += ms;
242
+ }
243
+ }
244
+ addRuleExecutionMs(ms) {
245
+ if (this.isObserveEnabled()) {
246
+ this.#ruleExecutionMs += ms;
247
+ }
248
+ }
249
+ recordRpcCall(io) {
250
+ if (!this.isObserveEnabled()) {
251
+ return;
252
+ }
253
+ this.#rpcBatches += 1;
254
+ if (io.isQueryBatch) {
255
+ this.#queryBatches += 1;
256
+ }
257
+ this.#bytesSent += io.bytesSent;
258
+ this.#bytesReceived += io.bytesReceived;
259
+ this.#encodeMs += io.encodeMs;
260
+ this.#writeMs += io.writeMs;
261
+ const engineMetrics = io.engineMetrics;
262
+ if (!engineMetrics) {
263
+ return;
264
+ }
265
+ this.#encodeMs += engineMetrics.encodeMs;
266
+ if (engineMetrics.steps) {
267
+ for (const step of engineMetrics.steps) {
268
+ this.#providers.add(step.provider);
269
+ if (this.mode === "detail" && step.details) {
270
+ for (const item of step.details) {
271
+ this.#appendDetail({
272
+ kind: "engineStep",
273
+ provider: step.provider,
274
+ durationMs: step.durationMs,
275
+ summary: item.summary,
276
+ ...(item.file !== undefined &&
277
+ item.line !== undefined &&
278
+ item.column !== undefined
279
+ ? {
280
+ detail: {
281
+ file: item.file,
282
+ line: item.line,
283
+ column: item.column,
284
+ kind: item.kind,
285
+ },
286
+ }
287
+ : {}),
288
+ });
289
+ }
290
+ }
291
+ }
292
+ }
293
+ if (engineMetrics.truncated) {
294
+ this.#truncated = true;
295
+ }
296
+ if (engineMetrics.droppedCount > 0) {
297
+ this.#droppedCount += engineMetrics.droppedCount;
298
+ }
299
+ if (engineMetrics.providerExtractions) {
300
+ for (const [providerId, stats] of Object.entries(engineMetrics.providerExtractions)) {
301
+ const current = this.#engineExtractions.get(providerId) ?? {
302
+ extractions: 0,
303
+ candidates: 0,
304
+ };
305
+ current.extractions += stats.extractions;
306
+ current.candidates += stats.candidates;
307
+ this.#engineExtractions.set(providerId, current);
308
+ }
309
+ }
310
+ }
311
+ recordQuery(params) {
312
+ if (!this.isActive()) {
313
+ return;
314
+ }
315
+ if (this.isObserveEnabled()) {
316
+ this.#queryCount += 1;
317
+ if (params.cacheStatus === "computed") {
318
+ this.#computedQueryCount += 1;
319
+ }
320
+ else {
321
+ this.#reusedQueryCount += 1;
322
+ }
323
+ this.#candidateCount += params.candidateCount;
324
+ const providersToAdd = params.providers ?? [params.provider];
325
+ for (const providerId of providersToAdd) {
326
+ this.#providers.add(providerId);
327
+ }
328
+ if (this.mode === "detail") {
329
+ this.#appendDetail({
330
+ kind: "query",
331
+ ruleId: params.ruleId,
332
+ projectId: params.projectId,
333
+ provider: params.provider,
334
+ name: params.op,
335
+ cacheStatus: params.cacheStatus,
336
+ candidateCount: params.candidateCount,
337
+ durationMs: params.durationMs,
338
+ summary: params.summary,
339
+ ...(params.detail !== undefined ? { detail: params.detail } : {}),
340
+ });
341
+ }
342
+ }
343
+ if (this.isExplainEnabled()) {
344
+ const ruleQueries = this.#queriesByRule.get(params.ruleId) ?? [];
345
+ const matchedTarget = (params.matchedLocations?.length ?? 0) > 0;
346
+ ruleQueries.push({
347
+ ruleId: params.ruleId,
348
+ queryIndex: ruleQueries.length + 1,
349
+ op: params.op,
350
+ projectId: params.projectId,
351
+ provider: params.provider,
352
+ ...(params.providers !== undefined
353
+ ? { providers: params.providers }
354
+ : {}),
355
+ cacheStatus: params.cacheStatus,
356
+ candidateCount: params.candidateCount,
357
+ matchedTarget,
358
+ durationMs: params.durationMs,
359
+ summary: params.summary,
360
+ ...(params.detail !== undefined ? { detail: params.detail } : {}),
361
+ });
362
+ this.#queriesByRule.set(params.ruleId, ruleQueries);
363
+ if (params.matchedLocations && params.matchedLocations.length > 0) {
364
+ const list = this.#matchingCandidatesByRule.get(params.ruleId) ?? [];
365
+ for (const loc of params.matchedLocations) {
366
+ list.push(loc);
367
+ }
368
+ this.#matchingCandidatesByRule.set(params.ruleId, list);
369
+ }
370
+ }
371
+ }
372
+ recordCheckpoint(params) {
373
+ if (!this.isActive()) {
374
+ return;
375
+ }
376
+ const start = performance.now();
377
+ if (this.isObserveEnabled()) {
378
+ this.#checkpointCount += 1;
379
+ }
380
+ const at = params.resolveLocation();
381
+ const matchesExplain = this.explainTarget !== undefined &&
382
+ at !== undefined &&
383
+ (locationMatchesTarget(at, this.explainTarget) ||
384
+ this.hasMatchingCandidateOverlapping(params.ruleId, at));
385
+ const shouldEvalForDetail = this.mode === "detail" && !this.#isItemLimitReached();
386
+ const shouldEvalForExplain = this.isExplainEnabled() && matchesExplain;
387
+ let evaluatedDetail;
388
+ let hasEvaluatedDetail = false;
389
+ if (params.detailFn && (shouldEvalForDetail || shouldEvalForExplain)) {
390
+ evaluatedDetail = params.detailFn();
391
+ hasEvaluatedDetail = true;
392
+ }
393
+ if (this.mode === "detail") {
394
+ this.#appendDetail({
395
+ kind: "checkpoint",
396
+ ruleId: params.ruleId,
397
+ projectId: params.projectId,
398
+ name: params.name,
399
+ outcome: params.outcome,
400
+ ...(at !== undefined ? { at } : {}),
401
+ summary: `${params.name}: ${params.outcome}`,
402
+ ...(hasEvaluatedDetail ? { detail: evaluatedDetail } : {}),
403
+ });
404
+ }
405
+ if (this.isExplainEnabled()) {
406
+ const list = this.#checkpointsByRule.get(params.ruleId) ?? [];
407
+ list.push({
408
+ ruleId: params.ruleId,
409
+ projectId: params.projectId,
410
+ name: params.name,
411
+ outcome: params.outcome,
412
+ ...(at !== undefined ? { at } : {}),
413
+ ...(hasEvaluatedDetail ? { detail: evaluatedDetail } : {}),
414
+ });
415
+ this.#checkpointsByRule.set(params.ruleId, list);
416
+ }
417
+ if (this.isObserveEnabled()) {
418
+ this.#checkpointMs += performance.now() - start;
419
+ }
420
+ }
421
+ hasMatchingCandidateOverlapping(ruleId, loc) {
422
+ const candidates = this.#matchingCandidatesByRule.get(ruleId);
423
+ if (!candidates)
424
+ return false;
425
+ return candidates.some((candidate) => locationsOverlap(candidate, loc));
426
+ }
427
+ recordCleanupPaths(params) {
428
+ if (!this.isExplainEnabled()) {
429
+ return;
430
+ }
431
+ const list = this.#cleanupPathsByRule.get(params.ruleId) ?? [];
432
+ for (const path of params.paths) {
433
+ list.push({
434
+ targetLocations: params.targetLocations,
435
+ path,
436
+ });
437
+ }
438
+ this.#cleanupPathsByRule.set(params.ruleId, list);
439
+ }
440
+ recordRuleGaps(ruleId, gaps) {
441
+ if (!this.isExplainEnabled() || gaps.length === 0) {
442
+ return;
443
+ }
444
+ const list = this.#gapsByRule.get(ruleId) ?? [];
445
+ list.push(...gaps);
446
+ this.#gapsByRule.set(ruleId, list);
447
+ }
448
+ recordFactExplain(params) {
449
+ if (!this.isExplainEnabled()) {
450
+ return;
451
+ }
452
+ if (params.gaps.length > 0) {
453
+ const list = this.#factGapsByRule.get(params.ruleId) ?? [];
454
+ for (const gap of params.gaps) {
455
+ list.push({
456
+ gap,
457
+ ...(params.subjectLocation !== undefined
458
+ ? { subjectLocation: params.subjectLocation }
459
+ : {}),
460
+ });
461
+ }
462
+ this.#factGapsByRule.set(params.ruleId, list);
463
+ }
464
+ if (params.localGaps.length > 0) {
465
+ const list = this.#localGapsByRule.get(params.ruleId) ?? [];
466
+ for (const localGap of params.localGaps) {
467
+ list.push({
468
+ localGap,
469
+ ...(params.subjectLocation !== undefined
470
+ ? { consumerLocation: params.subjectLocation }
471
+ : {}),
472
+ });
473
+ }
474
+ this.#localGapsByRule.set(params.ruleId, list);
475
+ }
476
+ }
477
+ recordProviderEvaluation(params) {
478
+ if (!this.isExplainEnabled()) {
479
+ return;
480
+ }
481
+ const list = this.#providerEvaluationsByRule.get(params.ruleId) ?? [];
482
+ list.push(params.evaluation);
483
+ this.#providerEvaluationsByRule.set(params.ruleId, list);
484
+ }
485
+ #isItemLimitReached() {
486
+ return (this.#truncated ||
487
+ (this.limit?.maxItems !== undefined &&
488
+ this.#details.length >= this.limit.maxItems));
489
+ }
490
+ #appendDetail(entry) {
491
+ if (this.#isItemLimitReached()) {
492
+ this.#truncated = true;
493
+ this.#droppedCount += 1;
494
+ return;
495
+ }
496
+ const encodeStart = performance.now();
497
+ const encoded = JSON.stringify(entry);
498
+ const entryBytes = Buffer.byteLength(encoded, "utf8");
499
+ this.#encodeMs += performance.now() - encodeStart;
500
+ if (this.limit?.maxBytes !== undefined &&
501
+ this.#usedDetailBytes + entryBytes > this.limit.maxBytes) {
502
+ this.#truncated = true;
503
+ this.#droppedCount += 1;
504
+ return;
505
+ }
506
+ this.#usedDetailBytes += entryBytes;
507
+ this.#details.push(entry);
508
+ }
509
+ buildObservationReport() {
510
+ if (!this.isObserveEnabled()) {
511
+ return undefined;
512
+ }
513
+ const mode = this.mode === "detail" ? "detail" : "summary";
514
+ const totalMs = Math.max(0, performance.now() - this.#startedAt);
515
+ return {
516
+ mode,
517
+ phases: {
518
+ configAndOpenMs: roundMs(this.#configAndOpenMs),
519
+ engineQueryMs: roundMs(this.#engineQueryMs),
520
+ ruleExecutionMs: roundMs(this.#ruleExecutionMs),
521
+ totalMs: roundMs(totalMs),
522
+ },
523
+ rpc: {
524
+ batches: this.#rpcBatches,
525
+ queryBatches: this.#queryBatches,
526
+ bytesSent: this.#bytesSent,
527
+ bytesReceived: this.#bytesReceived,
528
+ },
529
+ overhead: {
530
+ checkpointMs: roundMs(this.#checkpointMs),
531
+ encodeMs: roundMs(this.#encodeMs),
532
+ writeMs: roundMs(this.#writeMs),
533
+ },
534
+ queryCount: this.#queryCount,
535
+ computedQueryCount: this.#computedQueryCount,
536
+ reusedQueryCount: this.#reusedQueryCount,
537
+ candidateCount: this.#candidateCount,
538
+ checkpointCount: this.#checkpointCount,
539
+ providers: [...this.#providers].toSorted(),
540
+ nativeAdapters: [...this.#nativeAdapters],
541
+ engineExtractions: Object.fromEntries([...this.#engineExtractions.entries()]
542
+ .toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
543
+ .map(([k, v]) => [
544
+ k,
545
+ { extractions: v.extractions, candidates: v.candidates },
546
+ ])),
547
+ ...(this.limit !== undefined ? { limit: this.limit } : {}),
548
+ truncated: this.#truncated,
549
+ droppedCount: this.#droppedCount,
550
+ ...(mode === "detail" ? { details: [...this.#details] } : {}),
551
+ };
552
+ }
553
+ buildExplainResult(params) {
554
+ const target = this.explainTarget;
555
+ if (!target) {
556
+ throw new VeruleExecutionError("ENGINE_ERROR", "Cannot build explanation without a target location.");
557
+ }
558
+ const queries = this.#queriesByRule.get(params.ruleId) ?? [];
559
+ const checkpoints = this.#checkpointsByRule.get(params.ruleId) ?? [];
560
+ const matchingCandidates = this.#matchingCandidatesByRule.get(params.ruleId) ?? [];
561
+ const inCandidates = matchingCandidates.length > 0;
562
+ const relevantCheckpoints = checkpoints
563
+ .filter((cp) => cp.at !== undefined &&
564
+ (locationMatchesTarget(cp.at, target) ||
565
+ matchingCandidates.some((cand) => locationsOverlap(cand, cp.at))))
566
+ .map((cp) => ({
567
+ name: cp.name,
568
+ ruleId: cp.ruleId,
569
+ projectId: cp.projectId,
570
+ outcome: cp.outcome,
571
+ ...(cp.at !== undefined ? { at: cp.at } : {}),
572
+ ...(cp.detail !== undefined ? { detail: cp.detail } : {}),
573
+ }));
574
+ const querySteps = queries.map((q) => ({
575
+ queryIndex: q.queryIndex,
576
+ op: q.op,
577
+ projectId: q.projectId,
578
+ provider: q.provider,
579
+ cacheStatus: q.cacheStatus,
580
+ candidateCount: q.candidateCount,
581
+ matchedTarget: q.matchedTarget,
582
+ durationMs: roundMs(q.durationMs),
583
+ summary: q.summary,
584
+ ...(q.detail !== undefined ? { detail: q.detail } : {}),
585
+ }));
586
+ const providers = [
587
+ ...new Set(queries.flatMap((q) => q.providers ?? [q.provider])),
588
+ ].toSorted();
589
+ const projectsChecked = params.projects.map((p) => p.projectId);
590
+ const matchingDiagnostic = params.diagnostics.find((diag) => diag.ruleId === params.ruleId && locationMatchesTarget(diag.at, target));
591
+ const matchingSuppression = params.suppressions?.find((sup) => sup.ruleId === params.ruleId && locationMatchesTarget(sup.at, target));
592
+ const targetInAnyProject = params.projects.some((project) => project.sourceFiles.includes(target.file));
593
+ const excludedCheckpoint = relevantCheckpoints.find((cp) => cp.outcome === "exclude" &&
594
+ cp.at !== undefined &&
595
+ locationMatchesTarget(cp.at, target)) ?? relevantCheckpoints.find((cp) => cp.outcome === "exclude");
596
+ const firstNonMatchingFindSyntax = querySteps.find((step) => step.op === "findSyntax" && !step.matchedTarget);
597
+ const lastMatchingQuery = [...querySteps]
598
+ .reverse()
599
+ .find((step) => step.matchedTarget);
600
+ let status;
601
+ let summary;
602
+ let excludedByQuery;
603
+ let excludedByCheckpoint;
604
+ let inlineIgnore;
605
+ const matchingCleanupEntries = (this.#cleanupPathsByRule.get(params.ruleId) ?? []).filter((entry) => entry.targetLocations.some((loc) => locationMatchesTarget(loc, target) ||
606
+ matchingCandidates.some((cand) => locationsOverlap(cand, loc))));
607
+ const cleanupPaths = [];
608
+ const seenCleanupKeys = new Set();
609
+ for (const entry of matchingCleanupEntries) {
610
+ const key = `${entry.path.instanceKey}:${entry.path.scopeLocation.file}:${entry.path.scopeLocation.start}`;
611
+ if (!seenCleanupKeys.has(key)) {
612
+ seenCleanupKeys.add(key);
613
+ cleanupPaths.push(entry.path);
614
+ }
615
+ }
616
+ const matchesLoc = (loc) => loc !== undefined &&
617
+ (locationMatchesTarget(loc, target) ||
618
+ matchingCandidates.some((cand) => locationsOverlap(cand, loc)));
619
+ const relevantGaps = [];
620
+ const seenGapKeys = new Set();
621
+ const pushGap = (gap) => {
622
+ const key = JSON.stringify([
623
+ gap.kind,
624
+ gap.message,
625
+ gap.at?.file ?? null,
626
+ gap.at?.start ?? null,
627
+ gap.at?.end ?? null,
628
+ ]);
629
+ if (!seenGapKeys.has(key)) {
630
+ seenGapKeys.add(key);
631
+ relevantGaps.push(gap);
632
+ }
633
+ };
634
+ for (const gap of this.#gapsByRule.get(params.ruleId) ?? []) {
635
+ if (matchesLoc(gap.at) || (gap.at === undefined && inCandidates)) {
636
+ pushGap(gap);
637
+ }
638
+ }
639
+ for (const entry of this.#factGapsByRule.get(params.ruleId) ?? []) {
640
+ if (matchesLoc(entry.gap.at) || matchesLoc(entry.subjectLocation)) {
641
+ pushGap(entry.gap);
642
+ }
643
+ }
644
+ const relevantLocalGaps = [];
645
+ const seenLocalGapKeys = new Set();
646
+ for (const entry of this.#localGapsByRule.get(params.ruleId) ?? []) {
647
+ const lg = entry.localGap;
648
+ if (matchesLoc(lg.gap.at) ||
649
+ matchesLoc(lg.subjectLocation) ||
650
+ matchesLoc(entry.consumerLocation) ||
651
+ matchesLoc(lg.resolvedBy?.at)) {
652
+ const key = JSON.stringify(lg);
653
+ if (!seenLocalGapKeys.has(key)) {
654
+ seenLocalGapKeys.add(key);
655
+ relevantLocalGaps.push(lg);
656
+ }
657
+ }
658
+ }
659
+ const providerEvaluations = [];
660
+ const seenEvalKeys = new Set();
661
+ const activeProviderIds = new Set();
662
+ const skippedProviderIds = new Set();
663
+ for (const evalEntry of this.#providerEvaluationsByRule.get(params.ruleId) ?? []) {
664
+ if (evalEntry.status === "skipped") {
665
+ skippedProviderIds.add(evalEntry.providerId);
666
+ }
667
+ else {
668
+ activeProviderIds.add(evalEntry.providerId);
669
+ }
670
+ const key = JSON.stringify([
671
+ evalEntry.providerId,
672
+ evalEntry.factTypeId ?? null,
673
+ evalEntry.status,
674
+ evalEntry.reason ?? null,
675
+ evalEntry.subjectLocation?.file ?? null,
676
+ evalEntry.subjectLocation?.start ?? null,
677
+ ]);
678
+ if (!seenEvalKeys.has(key)) {
679
+ seenEvalKeys.add(key);
680
+ providerEvaluations.push(evalEntry);
681
+ }
682
+ }
683
+ for (const adapter of this.#configuredAdapters) {
684
+ if (!activeProviderIds.has(adapter.id) &&
685
+ !skippedProviderIds.has(adapter.id)) {
686
+ providerEvaluations.push({
687
+ providerId: adapter.id,
688
+ status: "skipped",
689
+ reason: "Not queried during rule execution.",
690
+ });
691
+ }
692
+ }
693
+ if (matchingDiagnostic) {
694
+ status = "reported";
695
+ summary = `Rule "${params.ruleId}" reported a diagnostic at ${formatTarget(target)}.`;
696
+ }
697
+ else if (matchingSuppression) {
698
+ status = "suppressed_by_ignore";
699
+ inlineIgnore = {
700
+ matched: true,
701
+ ruleId: matchingSuppression.ruleId,
702
+ reason: matchingSuppression.reason,
703
+ commentAt: matchingSuppression.directiveAt,
704
+ };
705
+ 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}).`;
706
+ }
707
+ else if (!targetInAnyProject) {
708
+ status = "target_not_in_project";
709
+ summary = `Target "${target.file}" is not part of any opened compiler project.`;
710
+ }
711
+ else if (cleanupPaths.length > 0) {
712
+ status = "covered_by_cleanup";
713
+ summary = `Target is covered by valid cleanup path(s) (${cleanupPaths.map((cp) => cp.instanceKey).join(", ")}).`;
714
+ }
715
+ else if (excludedCheckpoint) {
716
+ status = "excluded_by_checkpoint";
717
+ excludedByCheckpoint = excludedCheckpoint;
718
+ summary = `Target entered candidates and was excluded at checkpoint "${excludedCheckpoint.name}".`;
719
+ }
720
+ else if (relevantGaps.length > 0) {
721
+ status = "blocked_by_gap";
722
+ excludedByQuery = lastMatchingQuery ?? querySteps[0];
723
+ summary = `Target conclusion was blocked by ${relevantGaps.length} active gap(s) (${relevantGaps.map((g) => g.kind).join(", ")}).`;
724
+ }
725
+ else if (!inCandidates) {
726
+ status = "not_in_candidates";
727
+ excludedByQuery = firstNonMatchingFindSyntax ?? querySteps[0];
728
+ summary = excludedByQuery
729
+ ? `Target did not enter candidates in ${excludedByQuery.op} (${excludedByQuery.candidateCount} candidates, ${excludedByQuery.cacheStatus}).`
730
+ : `Target did not enter any candidate set for rule "${params.ruleId}".`;
731
+ }
732
+ else {
733
+ status = "rule_filtered";
734
+ excludedByQuery = lastMatchingQuery;
735
+ summary = `Target entered ${matchingCandidates.length} candidate(s) and rule "${params.ruleId}" did not report a diagnostic.`;
736
+ }
737
+ return {
738
+ ruleId: params.ruleId,
739
+ target,
740
+ status,
741
+ inCandidates,
742
+ summary,
743
+ projectsChecked,
744
+ matchingCandidates,
745
+ ...(excludedByQuery !== undefined ? { excludedByQuery } : {}),
746
+ ...(excludedByCheckpoint !== undefined ? { excludedByCheckpoint } : {}),
747
+ ...(inlineIgnore !== undefined ? { inlineIgnore } : {}),
748
+ queries: querySteps,
749
+ checkpoints: relevantCheckpoints,
750
+ gaps: relevantGaps,
751
+ localGaps: relevantLocalGaps,
752
+ providerEvaluations,
753
+ providers,
754
+ cleanupPaths,
755
+ };
756
+ }
757
+ }
758
+ function formatTarget(target) {
759
+ if (target.line === undefined)
760
+ return target.file;
761
+ if (target.column === undefined)
762
+ return `${target.file}:${target.line}`;
763
+ return `${target.file}:${target.line}:${target.column}`;
764
+ }
765
+ function roundMs(value) {
766
+ return Math.round(value * 1000) / 1000;
767
+ }