@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,677 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { performance } from "node:perf_hooks";
5
+ import { extractBasisEvidence, openProject, syntaxLocationOf, } from "tssae";
6
+ import { createAdditionalInputRegistry, createScopedAdditionalInputRegistrar, validateAdditionalInputPaths, } from "./additional-inputs.js";
7
+ import { INLINE_IGNORE_RULE_ID, parseInlineIgnoreDirectives, resolveInlineIgnores, } from "./inline-ignore.js";
8
+ import { ObservationCollector, normalizeObserveConfig, normalizeTargetSpec, } from "./observation.js";
9
+ import { buildDiagnostics, buildGaps, resolveProjectEntries, } from "./projects.js";
10
+ import { REPORT_SCHEMA_VERSION, VeruleExecutionError, toVeruleError, } from "./types.js";
11
+ // Watch needs these paths for hashing without adding them to the public project summary.
12
+ const sessionWorkspaceFileStates = new WeakMap();
13
+ /** Returns all workspace source file paths tracked by the active session for file watching. */
14
+ export function getSessionWorkspaceFiles(session) {
15
+ return sessionWorkspaceFileStates.get(session)?.files ?? [];
16
+ }
17
+ function canonicalizeDir(dirPath) {
18
+ if (!existsSync(dirPath))
19
+ return dirPath;
20
+ try {
21
+ return realpathSync.native(dirPath);
22
+ }
23
+ catch {
24
+ return dirPath;
25
+ }
26
+ }
27
+ async function invokeProjectQuery(fn) {
28
+ try {
29
+ return await fn();
30
+ }
31
+ catch (err) {
32
+ throw toVeruleError(err);
33
+ }
34
+ }
35
+ function invokeProjectSync(fn) {
36
+ try {
37
+ return fn();
38
+ }
39
+ catch (err) {
40
+ throw toVeruleError(err);
41
+ }
42
+ }
43
+ function validateRules(rules) {
44
+ const seen = new Set();
45
+ for (const rule of rules) {
46
+ if (typeof rule.id !== "string" || rule.id.trim() === "") {
47
+ throw new VeruleExecutionError("INVALID_CONFIG", "Each rule must have a non-empty string id.");
48
+ }
49
+ if (seen.has(rule.id)) {
50
+ throw new VeruleExecutionError("INVALID_CONFIG", `Duplicate rule id: "${rule.id}".`);
51
+ }
52
+ if (rule.id === INLINE_IGNORE_RULE_ID) {
53
+ throw new VeruleExecutionError("INVALID_CONFIG", `Rule id "${INLINE_IGNORE_RULE_ID}" is reserved.`);
54
+ }
55
+ if (typeof rule.run !== "function") {
56
+ throw new VeruleExecutionError("INVALID_CONFIG", `Rule "${rule.id}" must provide a run function.`);
57
+ }
58
+ seen.add(rule.id);
59
+ }
60
+ return [...rules];
61
+ }
62
+ function selectRules(baseRules, ruleIds) {
63
+ if (!ruleIds || ruleIds.length === 0) {
64
+ return baseRules;
65
+ }
66
+ const byId = new Map(baseRules.map((rule) => [rule.id, rule]));
67
+ const selected = [];
68
+ const seen = new Set();
69
+ for (const id of ruleIds) {
70
+ const found = byId.get(id);
71
+ if (!found) {
72
+ throw new VeruleExecutionError("INVALID_CONFIG", `Unknown rule id "${id}".`);
73
+ }
74
+ if (!seen.has(id)) {
75
+ seen.add(id);
76
+ selected.push(found);
77
+ }
78
+ }
79
+ return selected;
80
+ }
81
+ /** Validates and normalizes a rule definition. */
82
+ export function defineRule(rule) {
83
+ if (typeof rule.id !== "string" || rule.id.trim() === "") {
84
+ throw new VeruleExecutionError("INVALID_CONFIG", "Rule id must be a non-empty string.");
85
+ }
86
+ if (typeof rule.run !== "function") {
87
+ throw new VeruleExecutionError("INVALID_CONFIG", `Rule "${rule.id}" must provide a run function.`);
88
+ }
89
+ return rule;
90
+ }
91
+ /** Validates and normalizes a Verule project configuration, defaulting to zero rules. */
92
+ export function defineConfig(config) {
93
+ if (config.tsconfig !== undefined && config.projects !== undefined) {
94
+ throw new VeruleExecutionError("INVALID_CONFIG", 'Specify either "tsconfig" or "projects", not both.');
95
+ }
96
+ if (config.projects !== undefined && config.projects.length === 0) {
97
+ throw new VeruleExecutionError("INVALID_CONFIG", '"projects" must contain at least one tsconfig path when specified.');
98
+ }
99
+ const rules = validateRules(config.rules ?? []);
100
+ const additionalInputs = validateAdditionalInputPaths(config.additionalInputs);
101
+ return {
102
+ ...(config.tsconfig !== undefined ? { tsconfig: config.tsconfig } : {}),
103
+ ...(config.projects !== undefined
104
+ ? { projects: [...config.projects] }
105
+ : {}),
106
+ rules,
107
+ additionalInputs,
108
+ };
109
+ }
110
+ function stableSerialize(value) {
111
+ if (value === null || typeof value !== "object") {
112
+ return JSON.stringify(value) ?? "undefined";
113
+ }
114
+ if (Array.isArray(value)) {
115
+ return `[${value.map((item) => stableSerialize(item)).join(",")}]`;
116
+ }
117
+ const record = value;
118
+ const keys = Object.keys(record).toSorted();
119
+ return `{${keys
120
+ .filter((key) => record[key] !== undefined)
121
+ .map((key) => `${JSON.stringify(key)}:${stableSerialize(record[key])}`)
122
+ .join(",")}}`;
123
+ }
124
+ function sha256Prefix(input) {
125
+ return createHash("sha256").update(input).digest("hex").slice(0, 16);
126
+ }
127
+ function summarizeRule(rule) {
128
+ return {
129
+ id: rule.id,
130
+ digest: sha256Prefix(stableSerialize({
131
+ id: rule.id,
132
+ description: rule.description ?? null,
133
+ run: rule.run.toString(),
134
+ })),
135
+ };
136
+ }
137
+ function computeReportIdentity(snapshotDigest, entries, rules, additionalInputs = []) {
138
+ const ruleSummaries = rules.map(summarizeRule);
139
+ const configDigest = sha256Prefix(stableSerialize({
140
+ entries,
141
+ rules: ruleSummaries,
142
+ ...(additionalInputs.length > 0 ? { additionalInputs } : {}),
143
+ }));
144
+ return {
145
+ snapshotDigest,
146
+ configDigest,
147
+ rules: ruleSummaries,
148
+ };
149
+ }
150
+ function resolveCheckpointLocation(target) {
151
+ if ("location" in target) {
152
+ return target.location;
153
+ }
154
+ if ("file" in target && "line" in target && "start" in target) {
155
+ return target;
156
+ }
157
+ return syntaxLocationOf(target);
158
+ }
159
+ function resolveNextConfig(current, options) {
160
+ if (options?.config !== undefined) {
161
+ return defineConfig(options.config);
162
+ }
163
+ const rules = options?.rules ? validateRules(options.rules) : current.rules;
164
+ const additionalInputs = options?.additionalInputs !== undefined
165
+ ? validateAdditionalInputPaths(options.additionalInputs)
166
+ : current.additionalInputs;
167
+ if (options?.entries !== undefined) {
168
+ if (options.entries.length === 0) {
169
+ throw new VeruleExecutionError("INVALID_CONFIG", '"entries" must contain at least one tsconfig path when specified.');
170
+ }
171
+ return {
172
+ projects: [...options.entries],
173
+ rules,
174
+ additionalInputs,
175
+ };
176
+ }
177
+ return {
178
+ ...(current.tsconfig !== undefined ? { tsconfig: current.tsconfig } : {}),
179
+ ...(current.projects !== undefined ? { projects: current.projects } : {}),
180
+ rules,
181
+ additionalInputs,
182
+ };
183
+ }
184
+ function isSessionCheckOptions(value) {
185
+ return value !== undefined && !Array.isArray(value);
186
+ }
187
+ /**
188
+ * Opens an analysis session backed by a single TSSAE `ProjectSession`.
189
+ *
190
+ * Call `session.close()` when finished to release the snapshot and terminate the engine process.
191
+ */
192
+ export async function openSession(options) {
193
+ let normalizedConfig = options.config
194
+ ? defineConfig(options.config)
195
+ : defineConfig({});
196
+ const absCwd = resolve(options.cwd);
197
+ const canonicalCwd = canonicalizeDir(absCwd);
198
+ const sessionObserve = normalizeObserveConfig(options.observe, options.observeLimit);
199
+ let openIoMetrics;
200
+ const openStart = performance.now();
201
+ const tssaeSession = await invokeProjectQuery(() => openProject({
202
+ cwd: absCwd,
203
+ ...(normalizedConfig.tsconfig !== undefined
204
+ ? { tsconfig: normalizedConfig.tsconfig }
205
+ : {}),
206
+ ...(normalizedConfig.projects !== undefined
207
+ ? { projects: normalizedConfig.projects }
208
+ : {}),
209
+ additionalInputs: normalizedConfig.additionalInputs,
210
+ ...(sessionObserve.mode !== "off"
211
+ ? {
212
+ observe: sessionObserve,
213
+ onRpcMetrics: (io) => {
214
+ openIoMetrics = io;
215
+ },
216
+ }
217
+ : {}),
218
+ }));
219
+ const openDurationMs = performance.now() - openStart;
220
+ const workspaceFileState = {
221
+ files: tssaeSession.workspaceSourceFiles,
222
+ };
223
+ let closed = false;
224
+ let pendingOpenIoMetrics = openIoMetrics;
225
+ const pendingUpdateIoMetrics = [];
226
+ let pendingOpenDurationMs = openDurationMs;
227
+ let pendingConfigLoadMs = options.configLoadMs ?? 0;
228
+ const explicitRegistrations = [];
229
+ let lastRuleRegistrations = [];
230
+ function syncNonConfigEntries(registry, entries) {
231
+ for (const entry of entries) {
232
+ const targetPath = resolve(canonicalCwd, entry.file);
233
+ for (const source of entry.sources) {
234
+ if (source.kind !== "config") {
235
+ registry.registerAdditionalInput(targetPath, source);
236
+ }
237
+ }
238
+ }
239
+ }
240
+ function buildSessionRegistry(configInputs, explicit, dynamic, tssaeEntries) {
241
+ const registry = createAdditionalInputRegistry({ cwd: absCwd });
242
+ for (const filePath of configInputs) {
243
+ registry.registerAdditionalInput(filePath, { kind: "config" });
244
+ }
245
+ for (const item of explicit) {
246
+ registry.registerAdditionalInput(item.filePath, item.source);
247
+ }
248
+ for (const item of dynamic) {
249
+ registry.registerAdditionalInput(item.filePath, item.source);
250
+ }
251
+ syncNonConfigEntries(registry, tssaeEntries);
252
+ return registry;
253
+ }
254
+ let sessionRegistry = buildSessionRegistry(normalizedConfig.additionalInputs, explicitRegistrations, lastRuleRegistrations, tssaeSession.additionalInputs);
255
+ function assertOpen() {
256
+ if (closed) {
257
+ throw new VeruleExecutionError("SESSION_CLOSED", "Analysis session is already closed.");
258
+ }
259
+ }
260
+ function createRuleContext(ruleId, projectCtx, activeSnapshotId, collected, collector, additionalInputRegistrar) {
261
+ const scopedAdditionalInputs = createScopedAdditionalInputRegistrar(additionalInputRegistrar, { kind: "rule", id: ruleId });
262
+ const assertActiveSnapshot = () => {
263
+ assertOpen();
264
+ if (activeSnapshotId !== tssaeSession.snapshotId) {
265
+ throw new VeruleExecutionError("STALE_SNAPSHOT", `Snapshot ${String(activeSnapshotId)} has been superseded by snapshot ${String(tssaeSession.snapshotId)}.`);
266
+ }
267
+ };
268
+ return {
269
+ project: projectCtx.project,
270
+ findSyntax: (query) => invokeProjectQuery(() => projectCtx.findSyntax(query)),
271
+ typeAt: (targets) => invokeProjectQuery(() => projectCtx.typeAt(targets)),
272
+ listBranches: (functions) => invokeProjectQuery(() => projectCtx.listBranches(functions)),
273
+ branchCoverage: (query) => invokeProjectQuery(() => projectCtx.branchCoverage(query)),
274
+ resolveDeclarations: (targets, opts) => invokeProjectQuery(() => projectCtx.resolveDeclarations(targets, opts)),
275
+ resolveCalls: (targets, opts) => invokeProjectQuery(() => projectCtx.resolveCalls(targets, opts)),
276
+ projectCalls: (calls, opts) => invokeProjectQuery(() => projectCtx.projectCalls(calls, opts)),
277
+ projectSignatures: (signatures, opts) => invokeProjectQuery(() => projectCtx.projectSignatures(signatures, opts)),
278
+ projectTypes: (types, opts) => invokeProjectQuery(() => projectCtx.projectTypes(types, opts)),
279
+ isAssignableTo: (pairs) => invokeProjectQuery(() => projectCtx.isAssignableTo(pairs)),
280
+ syntaxOf: (targets, opts) => invokeProjectQuery(() => projectCtx.syntaxOf(targets, opts)),
281
+ callersOf: (declarations, opts) => invokeProjectQuery(() => projectCtx.callersOf(declarations, opts)),
282
+ calleesOf: (calls) => invokeProjectQuery(() => projectCtx.calleesOf(calls)),
283
+ resolveImplementations: (targets) => invokeProjectQuery(() => projectCtx.resolveImplementations(targets)),
284
+ valuePropagation: (opts) => invokeProjectQuery(() => projectCtx.valuePropagation(opts)),
285
+ resolveInstances: (targets, opts) => invokeProjectQuery(() => projectCtx.resolveInstances(targets, opts)),
286
+ projectInstances: (instances, opts) => invokeProjectQuery(() => projectCtx.projectInstances(instances, opts)),
287
+ callEffects: (opts) => invokeProjectQuery(() => projectCtx.callEffects(opts)),
288
+ instanceCleanup: (opts) => invokeProjectQuery(() => projectCtx.instanceCleanup(opts)),
289
+ registerAdditionalInput: (filePath) => {
290
+ assertActiveSnapshot();
291
+ return scopedAdditionalInputs.registerAdditionalInput(filePath);
292
+ },
293
+ readAdditionalInput: (filePath) => {
294
+ assertActiveSnapshot();
295
+ return scopedAdditionalInputs.readAdditionalInput(filePath);
296
+ },
297
+ recordGaps: (gaps, gapOptions) => {
298
+ assertActiveSnapshot();
299
+ projectCtx.recordGaps(gaps);
300
+ if (gapOptions?.relatedLocation !== undefined && gaps.length > 0) {
301
+ collector.recordRuleGaps(ruleId, gaps, gapOptions.relatedLocation);
302
+ }
303
+ },
304
+ report: (input) => {
305
+ assertActiveSnapshot();
306
+ collected.push({
307
+ ruleId,
308
+ projectId: projectCtx.project.projectId,
309
+ at: input.at,
310
+ message: input.message,
311
+ ...(input.findingKey !== undefined
312
+ ? { findingKey: input.findingKey }
313
+ : {}),
314
+ evidence: extractBasisEvidence(input.basis),
315
+ });
316
+ },
317
+ checkpoint: (name, target, outcome, detail) => {
318
+ if (!collector.isActive()) {
319
+ return;
320
+ }
321
+ collector.recordCheckpoint({
322
+ ruleId,
323
+ projectId: projectCtx.project.projectId,
324
+ name,
325
+ outcome,
326
+ resolveLocation: () => resolveCheckpointLocation(target),
327
+ ...(detail !== undefined ? { detailFn: detail } : {}),
328
+ });
329
+ },
330
+ };
331
+ }
332
+ async function executeCheckRun(runOptions) {
333
+ assertOpen();
334
+ const baseRules = runOptions?.rulesOverride
335
+ ? validateRules(runOptions.rulesOverride)
336
+ : normalizedConfig.rules;
337
+ const rules = selectRules(baseRules, runOptions?.ruleIds);
338
+ const explainTarget = runOptions?.at !== undefined
339
+ ? normalizeTargetSpec(runOptions.at, absCwd)
340
+ : undefined;
341
+ if (explainTarget !== undefined && rules.length === 0) {
342
+ throw new VeruleExecutionError("INVALID_CONFIG", "At least one rule must be configured or selected via ruleIds to explain a target location.");
343
+ }
344
+ const effectiveObserve = runOptions?.observe !== undefined ||
345
+ runOptions?.observeLimit !== undefined
346
+ ? normalizeObserveConfig(runOptions.observe ?? sessionObserve.mode, runOptions.observeLimit ?? sessionObserve.limit)
347
+ : sessionObserve;
348
+ const configLoadMs = runOptions?.configLoadMs ?? pendingConfigLoadMs;
349
+ pendingConfigLoadMs = 0;
350
+ const openMs = pendingOpenDurationMs;
351
+ pendingOpenDurationMs = 0;
352
+ const collector = new ObservationCollector({
353
+ mode: effectiveObserve.mode,
354
+ ...(effectiveObserve.limit !== undefined
355
+ ? { limit: effectiveObserve.limit }
356
+ : {}),
357
+ ...(explainTarget !== undefined ? { explainTarget } : {}),
358
+ configAndOpenMs: configLoadMs + openMs,
359
+ });
360
+ if (pendingOpenIoMetrics) {
361
+ collector.recordRpcCall(pendingOpenIoMetrics);
362
+ pendingOpenIoMetrics = undefined;
363
+ }
364
+ if (pendingUpdateIoMetrics.length > 0) {
365
+ for (const io of pendingUpdateIoMetrics) {
366
+ collector.recordRpcCall(io);
367
+ }
368
+ pendingUpdateIoMetrics.length = 0;
369
+ }
370
+ const collected = [];
371
+ const collectedGaps = [];
372
+ const runRegistry = buildSessionRegistry(normalizedConfig.additionalInputs, explicitRegistrations, [], []);
373
+ const runRuleRegistrations = [];
374
+ const runRegistrar = {
375
+ cwd: runRegistry.cwd,
376
+ registerAdditionalInput: (filePath, source) => {
377
+ sessionRegistry.registerAdditionalInput(filePath, source);
378
+ runRuleRegistrations.push({ filePath, source });
379
+ return runRegistry.registerAdditionalInput(filePath, source);
380
+ },
381
+ readAdditionalInput: (filePath, source) => {
382
+ sessionRegistry.registerAdditionalInput(filePath, source);
383
+ runRuleRegistrations.push({ filePath, source });
384
+ return runRegistry.readAdditionalInput(filePath, source);
385
+ },
386
+ listAdditionalInputs: () => runRegistry.listAdditionalInputs(),
387
+ getTrackedAbsolutePaths: () => runRegistry.getTrackedAbsolutePaths(),
388
+ };
389
+ const currentSnapshotId = tssaeSession.snapshotId;
390
+ for (const project of tssaeSession.projects) {
391
+ for (const rule of rules) {
392
+ let ruleEngineMs = 0;
393
+ const ruleStart = collector.isObserveEnabled() ? performance.now() : 0;
394
+ const observer = {
395
+ onGaps: (gaps) => {
396
+ collectedGaps.push(...gaps);
397
+ collector.recordRuleGaps(rule.id, gaps);
398
+ },
399
+ ...(collector.isObserveEnabled()
400
+ ? {
401
+ observe: effectiveObserve,
402
+ onRpcMetrics: (io) => collector.recordRpcCall(io),
403
+ }
404
+ : {}),
405
+ ...(explainTarget !== undefined ? { explainTarget } : {}),
406
+ ...(collector.isActive()
407
+ ? {
408
+ onQueryCompleted: (event) => {
409
+ if (event.cacheStatus === "computed") {
410
+ collector.addEngineQueryMs(event.durationMs);
411
+ ruleEngineMs += event.durationMs;
412
+ }
413
+ collector.recordQuery({
414
+ ruleId: rule.id,
415
+ op: event.op,
416
+ projectId: event.projectId,
417
+ provider: event.provider,
418
+ ...(event.providers !== undefined
419
+ ? { providers: event.providers }
420
+ : {}),
421
+ cacheStatus: event.cacheStatus,
422
+ candidateCount: event.candidateCount,
423
+ durationMs: event.durationMs,
424
+ summary: event.summary,
425
+ ...(event.matchedLocations !== undefined
426
+ ? { matchedLocations: event.matchedLocations }
427
+ : {}),
428
+ ...(event.detail !== undefined
429
+ ? { detail: event.detail }
430
+ : {}),
431
+ });
432
+ },
433
+ }
434
+ : {}),
435
+ ...(collector.isExplainEnabled()
436
+ ? {
437
+ onCleanupCovered: (event) => {
438
+ collector.recordCleanupPaths({
439
+ ruleId: rule.id,
440
+ targetLocations: event.targetLocations,
441
+ paths: event.paths,
442
+ });
443
+ },
444
+ }
445
+ : {}),
446
+ };
447
+ const projectCtx = invokeProjectSync(() => tssaeSession.project(project, { observer }));
448
+ const ctx = createRuleContext(rule.id, projectCtx, currentSnapshotId, collected, collector, runRegistrar);
449
+ try {
450
+ await rule.run(ctx);
451
+ }
452
+ catch (err) {
453
+ if (err instanceof VeruleExecutionError) {
454
+ throw err;
455
+ }
456
+ const mapped = toVeruleError(err, "RULE_EXECUTION_ERROR");
457
+ if (mapped.code !== "RULE_EXECUTION_ERROR" || err !== mapped.cause) {
458
+ // Preserve TssaeError codes/details while wrapping generic JS rule throws with rule context.
459
+ if (err instanceof Error &&
460
+ (err.name === "TssaeError" || "code" in err)) {
461
+ throw mapped;
462
+ }
463
+ }
464
+ const detail = err instanceof Error ? err.message : String(err);
465
+ throw new VeruleExecutionError("RULE_EXECUTION_ERROR", `Rule "${rule.id}" failed: ${detail}`, { cause: err });
466
+ }
467
+ finally {
468
+ if (collector.isObserveEnabled()) {
469
+ const ruleElapsed = performance.now() - ruleStart;
470
+ collector.addRuleExecutionMs(Math.max(0, ruleElapsed - ruleEngineMs));
471
+ }
472
+ }
473
+ }
474
+ }
475
+ const scannedComments = await invokeProjectQuery(() => tssaeSession.scanComments(collector.isObserveEnabled()
476
+ ? {
477
+ observe: effectiveObserve,
478
+ onRpcMetrics: (io) => collector.recordRpcCall(io),
479
+ }
480
+ : undefined));
481
+ const scannedDirectives = parseInlineIgnoreDirectives(scannedComments);
482
+ const settlement = resolveInlineIgnores({
483
+ directives: scannedDirectives,
484
+ collected,
485
+ projects: tssaeSession.projects,
486
+ configuredRuleIds: new Set(baseRules.map((rule) => rule.id)),
487
+ executedRuleIds: new Set(rules.map((rule) => rule.id)),
488
+ isPartialRuleSelection: runOptions?.ruleIds !== undefined && runOptions.ruleIds.length > 0,
489
+ });
490
+ const diagnostics = buildDiagnostics(settlement.diagnostics);
491
+ const gaps = buildGaps(collectedGaps);
492
+ syncNonConfigEntries(runRegistry, tssaeSession.additionalInputs);
493
+ const additionalInputs = runRegistry.listAdditionalInputs();
494
+ if (!runOptions?.ruleIds && !runOptions?.rulesOverride) {
495
+ lastRuleRegistrations = runRuleRegistrations;
496
+ sessionRegistry = buildSessionRegistry(normalizedConfig.additionalInputs, explicitRegistrations, lastRuleRegistrations, tssaeSession.additionalInputs);
497
+ }
498
+ else {
499
+ syncNonConfigEntries(sessionRegistry, tssaeSession.additionalInputs);
500
+ }
501
+ const observation = collector.buildObservationReport();
502
+ const explanations = explainTarget
503
+ ? rules.map((rule) => collector.buildExplainResult({
504
+ ruleId: rule.id,
505
+ projects: tssaeSession.projects,
506
+ diagnostics,
507
+ suppressions: settlement.suppressions,
508
+ }))
509
+ : undefined;
510
+ return {
511
+ reportVersion: REPORT_SCHEMA_VERSION,
512
+ status: diagnostics.length > 0 ? "findings" : "clean",
513
+ projects: tssaeSession.projects,
514
+ fileOrigins: tssaeSession.fileOrigins,
515
+ additionalInputs,
516
+ diagnostics,
517
+ gaps,
518
+ identity: computeReportIdentity(tssaeSession.snapshotDigest, resolveProjectEntries(normalizedConfig), rules, normalizedConfig.additionalInputs),
519
+ ...(settlement.entries.length > 0
520
+ ? { inlineIgnores: settlement.entries }
521
+ : {}),
522
+ ...(observation !== undefined ? { observation } : {}),
523
+ ...(explanations !== undefined && explanations.length === 1
524
+ ? { explanation: explanations[0] }
525
+ : {}),
526
+ ...(explanations !== undefined && explanations.length > 1
527
+ ? { explanations }
528
+ : {}),
529
+ };
530
+ }
531
+ const analysisSession = {
532
+ get snapshotId() {
533
+ return tssaeSession.snapshotId;
534
+ },
535
+ get projects() {
536
+ return tssaeSession.projects;
537
+ },
538
+ get fileOrigins() {
539
+ return tssaeSession.fileOrigins;
540
+ },
541
+ get additionalInputs() {
542
+ return sessionRegistry.listAdditionalInputs();
543
+ },
544
+ get memory() {
545
+ return tssaeSession.memory;
546
+ },
547
+ registerAdditionalInput: (filePath, source) => {
548
+ assertOpen();
549
+ const entry = invokeProjectSync(() => tssaeSession.registerAdditionalInput(filePath, source));
550
+ explicitRegistrations.push({ filePath, source });
551
+ return sessionRegistry.registerAdditionalInput(filePath, source) ?? entry;
552
+ },
553
+ check: (optionsOrRules) => {
554
+ if (isSessionCheckOptions(optionsOrRules)) {
555
+ return executeCheckRun(optionsOrRules);
556
+ }
557
+ return executeCheckRun(optionsOrRules !== undefined
558
+ ? { rulesOverride: optionsOrRules }
559
+ : undefined);
560
+ },
561
+ update: async (updateOptions) => {
562
+ assertOpen();
563
+ const changedAdditionalFiles = sessionRegistry.refresh();
564
+ const nextConfig = resolveNextConfig(normalizedConfig, updateOptions);
565
+ const nextEntries = resolveProjectEntries(nextConfig);
566
+ const prevIdentity = computeReportIdentity("", resolveProjectEntries(normalizedConfig), normalizedConfig.rules, normalizedConfig.additionalInputs);
567
+ const nextIdentity = computeReportIdentity("", nextEntries, nextConfig.rules, nextConfig.additionalInputs);
568
+ const tssaeUpdate = await invokeProjectQuery(() => tssaeSession.update({
569
+ ...(updateOptions?.changed !== undefined
570
+ ? { changed: updateOptions.changed }
571
+ : {}),
572
+ ...(updateOptions?.created !== undefined
573
+ ? { created: updateOptions.created }
574
+ : {}),
575
+ ...(updateOptions?.deleted !== undefined
576
+ ? { deleted: updateOptions.deleted }
577
+ : {}),
578
+ entries: nextEntries,
579
+ additionalInputs: nextConfig.additionalInputs,
580
+ ...(sessionObserve.mode !== "off"
581
+ ? {
582
+ observe: sessionObserve,
583
+ onRpcMetrics: (io) => {
584
+ pendingUpdateIoMetrics.push(io);
585
+ },
586
+ }
587
+ : {}),
588
+ }));
589
+ const invalidatedReasons = [...tssaeUpdate.recomputation.invalidatedBy];
590
+ const existingReasons = new Set(invalidatedReasons);
591
+ const changedSet = new Set(updateOptions?.changed ?? []);
592
+ for (const file of changedAdditionalFiles) {
593
+ const marker = `additional-input:${file}`;
594
+ if (!changedSet.has(file) && !existingReasons.has(marker)) {
595
+ invalidatedReasons.push(marker);
596
+ existingReasons.add(marker);
597
+ }
598
+ }
599
+ if (stableSerialize(prevIdentity.rules) !==
600
+ stableSerialize(nextIdentity.rules) &&
601
+ !existingReasons.has("rules")) {
602
+ invalidatedReasons.push("rules");
603
+ existingReasons.add("rules");
604
+ }
605
+ if (updateOptions?.config !== undefined &&
606
+ invalidatedReasons.length === 0) {
607
+ invalidatedReasons.push("config");
608
+ }
609
+ normalizedConfig = nextConfig;
610
+ workspaceFileState.files = tssaeUpdate.workspaceSourceFiles;
611
+ sessionRegistry = buildSessionRegistry(nextConfig.additionalInputs, explicitRegistrations, lastRuleRegistrations, tssaeSession.additionalInputs);
612
+ const recomputation = {
613
+ ...tssaeUpdate.recomputation,
614
+ invalidatedBy: invalidatedReasons,
615
+ };
616
+ return {
617
+ previousSnapshotId: tssaeUpdate.previousSnapshotId,
618
+ snapshotId: tssaeUpdate.snapshotId,
619
+ projects: tssaeUpdate.projects,
620
+ fileOrigins: tssaeUpdate.fileOrigins,
621
+ additionalInputs: sessionRegistry.listAdditionalInputs(),
622
+ recomputation,
623
+ memory: tssaeUpdate.memory,
624
+ };
625
+ },
626
+ explain: async (explainOptions) => {
627
+ const report = await executeCheckRun({
628
+ ...(explainOptions.rulesOverride !== undefined
629
+ ? { rulesOverride: explainOptions.rulesOverride }
630
+ : {}),
631
+ ...(explainOptions.ruleId !== undefined
632
+ ? { ruleIds: [explainOptions.ruleId] }
633
+ : {}),
634
+ at: explainOptions.at,
635
+ ...(explainOptions.observe !== undefined
636
+ ? { observe: explainOptions.observe }
637
+ : {}),
638
+ ...(explainOptions.observeLimit !== undefined
639
+ ? { observeLimit: explainOptions.observeLimit }
640
+ : {}),
641
+ });
642
+ const primaryExplanation = report.explanation ?? report.explanations?.[0];
643
+ if (!primaryExplanation) {
644
+ throw new VeruleExecutionError("ENGINE_ERROR", "Failed to generate explanation for the requested target.");
645
+ }
646
+ return {
647
+ ...report,
648
+ explanation: primaryExplanation,
649
+ };
650
+ },
651
+ close: async () => {
652
+ if (closed)
653
+ return;
654
+ closed = true;
655
+ await tssaeSession.close();
656
+ },
657
+ };
658
+ sessionWorkspaceFileStates.set(analysisSession, workspaceFileState);
659
+ return analysisSession;
660
+ }
661
+ /** Runs a one-shot check in a dedicated analysis session and releases resources before returning. */
662
+ export async function runCheck(options) {
663
+ const session = await openSession(options);
664
+ try {
665
+ return await session.check({
666
+ ...(options.ruleIds !== undefined ? { ruleIds: options.ruleIds } : {}),
667
+ ...(options.at !== undefined ? { at: options.at } : {}),
668
+ ...(options.observe !== undefined ? { observe: options.observe } : {}),
669
+ ...(options.observeLimit !== undefined
670
+ ? { observeLimit: options.observeLimit }
671
+ : {}),
672
+ });
673
+ }
674
+ finally {
675
+ await session.close();
676
+ }
677
+ }
@@ -0,0 +1,13 @@
1
+ import { type CheckReport, type RequestSharedReportOptions, type SharedSession, type SharedSessionOptions } from "./types.ts";
2
+ /**
3
+ * Starts an explicit long-lived shared analysis session bound to a single configuration and
4
+ * local socket/pipe endpoint. Reuses the same incremental update and rule execution pipeline
5
+ * as `watchProject`, and verifies disk state synchronously on every client query to avoid
6
+ * watcher debounce races.
7
+ */
8
+ export declare function startSharedSession(options: SharedSessionOptions): Promise<SharedSession>;
9
+ /**
10
+ * Queries a running shared analysis session over its local socket/pipe endpoint
11
+ * and returns the latest complete `CheckReport`.
12
+ */
13
+ export declare function requestSharedReport(options: RequestSharedReportOptions): Promise<CheckReport>;