@repometry/core 0.0.0-dev.0 → 0.0.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.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +37 -2
  3. package/target/main/ts/engine/execute.d.ts +15 -0
  4. package/target/main/ts/engine/execute.js +63 -0
  5. package/target/main/ts/engine/manifest.d.ts +3 -0
  6. package/target/main/ts/engine/manifest.js +129 -0
  7. package/target/main/ts/engine/operation-cache.d.ts +14 -0
  8. package/target/main/ts/engine/operation-cache.js +66 -0
  9. package/target/main/ts/engine/plan.d.ts +21 -0
  10. package/target/main/ts/engine/plan.js +123 -0
  11. package/target/main/ts/engine/plugin.d.ts +71 -0
  12. package/target/main/ts/engine/plugin.js +3 -0
  13. package/target/main/ts/engine/report-products.d.ts +16 -0
  14. package/target/main/ts/engine/report-products.js +76 -0
  15. package/target/main/ts/index.d.ts +20 -0
  16. package/target/main/ts/index.js +8 -0
  17. package/target/main/ts/model/changes.d.ts +39 -0
  18. package/target/main/ts/model/changes.js +6 -0
  19. package/target/main/ts/model/churn.d.ts +11 -0
  20. package/target/main/ts/model/churn.js +6 -0
  21. package/target/main/ts/model/clone-source.d.ts +19 -0
  22. package/target/main/ts/model/clone-source.js +20 -0
  23. package/target/main/ts/model/code-structure.d.ts +45 -0
  24. package/target/main/ts/model/code-structure.js +63 -0
  25. package/target/main/ts/model/comparison.d.ts +24 -0
  26. package/target/main/ts/model/comparison.js +2 -0
  27. package/target/main/ts/model/coverage-input.d.ts +12 -0
  28. package/target/main/ts/model/coverage-input.js +11 -0
  29. package/target/main/ts/model/diff-coverage.d.ts +25 -0
  30. package/target/main/ts/model/diff-coverage.js +10 -0
  31. package/target/main/ts/model/file-types.d.ts +20 -0
  32. package/target/main/ts/model/file-types.js +50 -0
  33. package/target/main/ts/model/finding-ignore.d.ts +8 -0
  34. package/target/main/ts/model/finding-ignore.js +36 -0
  35. package/target/main/ts/model/finding.d.ts +34 -0
  36. package/target/main/ts/model/finding.js +45 -0
  37. package/target/main/ts/model/ignore-rule.d.ts +11 -0
  38. package/target/main/ts/model/ignore-rule.js +2 -0
  39. package/target/main/ts/model/language.d.ts +44 -0
  40. package/target/main/ts/model/language.js +31 -0
  41. package/target/main/ts/model/line-coverage.d.ts +15 -0
  42. package/target/main/ts/model/line-coverage.js +43 -0
  43. package/target/main/ts/model/measurement.d.ts +34 -0
  44. package/target/main/ts/model/measurement.js +42 -0
  45. package/target/main/ts/model/metric-descriptor.d.ts +17 -0
  46. package/target/main/ts/model/metric-descriptor.js +2 -0
  47. package/target/main/ts/model/plugin-data.d.ts +32 -0
  48. package/target/main/ts/model/plugin-data.js +16 -0
  49. package/target/main/ts/model/pull-review.d.ts +70 -0
  50. package/target/main/ts/model/pull-review.js +4 -0
  51. package/target/main/ts/model/quality-summary.d.ts +46 -0
  52. package/target/main/ts/model/quality-summary.js +92 -0
  53. package/target/main/ts/model/report.d.ts +45 -0
  54. package/target/main/ts/model/report.js +5 -0
  55. package/target/main/ts/model/scanner-import.d.ts +39 -0
  56. package/target/main/ts/model/scanner-import.js +29 -0
  57. package/target/main/ts/model/snapshot.d.ts +14 -0
  58. package/target/main/ts/model/snapshot.js +49 -0
  59. package/target/main/ts/model/source-locator.d.ts +7 -0
  60. package/target/main/ts/model/source-locator.js +2 -0
  61. package/target/main/ts/model/source.d.ts +31 -0
  62. package/target/main/ts/model/source.js +20 -0
  63. package/target/main/ts/ports/report.d.ts +9 -0
  64. package/target/main/ts/ports/report.js +2 -0
  65. package/target/main/ts/ports/source-provider.d.ts +14 -0
  66. package/target/main/ts/ports/source-provider.js +5 -0
  67. package/target/main/ts/ports/tool-runner.d.ts +18 -0
  68. package/target/main/ts/ports/tool-runner.js +2 -0
  69. package/target/main/ts/profile/exclusions.d.ts +11 -0
  70. package/target/main/ts/profile/exclusions.js +58 -0
  71. package/target/main/ts/profile/maintainability.d.ts +31 -0
  72. package/target/main/ts/profile/maintainability.js +10 -0
  73. package/target/main/ts/profile/profile.d.ts +4 -0
  74. package/target/main/ts/profile/profile.js +11 -0
  75. package/target/main/ts/usecases/diff-coverage-policy.d.ts +6 -0
  76. package/target/main/ts/usecases/diff-coverage-policy.js +11 -0
  77. package/target/main/ts/usecases/diff-coverage.d.ts +40 -0
  78. package/target/main/ts/usecases/diff-coverage.js +16 -0
  79. package/target/main/ts/usecases/inspect.d.ts +37 -0
  80. package/target/main/ts/usecases/inspect.js +42 -0
  81. package/target/main/ts/usecases/review-effect.d.ts +18 -0
  82. package/target/main/ts/usecases/review-effect.js +37 -0
  83. package/target/main/ts/usecases/review-match.d.ts +14 -0
  84. package/target/main/ts/usecases/review-match.js +72 -0
  85. package/target/main/ts/usecases/review-position.d.ts +14 -0
  86. package/target/main/ts/usecases/review-position.js +53 -0
  87. package/target/main/ts/usecases/review-scope.d.ts +21 -0
  88. package/target/main/ts/usecases/review-scope.js +41 -0
  89. package/target/main/ts/usecases/review.d.ts +42 -0
  90. package/target/main/ts/usecases/review.js +112 -0
  91. package/README.md +0 -4
@@ -0,0 +1,49 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isRecord } from './plugin-data.js';
3
+ export const sourceFile = {
4
+ id: 'repometry.source-file/v1',
5
+ accepts: (value) => isRecord(value) && typeof value.path === 'string' && value.bytes instanceof Uint8Array,
6
+ };
7
+ export const sourceFiles = {
8
+ id: 'repometry.source-files/v1',
9
+ accepts: (value) => Array.isArray(value) && value.every(sourceFile.accepts),
10
+ };
11
+ export const sourceDirectoriesExcluded = ['.git', '.repometry', 'node_modules', 'target'];
12
+ const excluded = new Set(sourceDirectoriesExcluded);
13
+ export function isExcludedDirectory(name) {
14
+ return excluded.has(name);
15
+ }
16
+ export function digest(bytes) {
17
+ return createHash('sha256').update(bytes).digest('hex');
18
+ }
19
+ export function utf8(bytes) {
20
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
21
+ }
22
+ export function physicalLines(text) {
23
+ if (text === '')
24
+ return 0;
25
+ return text.split(/\r\n|[\n\r\u2028\u2029]/).length - Number(/[\n\r\u2028\u2029]$/.test(text));
26
+ }
27
+ export function sourceLineCounts(files) {
28
+ const decoder = new TextDecoder('utf-8', { ignoreBOM: true });
29
+ return new Map(files.map(file => [file.path, physicalLines(decoder.decode(file.bytes))]));
30
+ }
31
+ export function textLineCount(bytes) {
32
+ if (bytes.includes(0))
33
+ return null;
34
+ try {
35
+ return physicalLines(utf8(bytes));
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ export function comparePaths(left, right) {
42
+ return left < right ? -1 : left > right ? 1 : 0;
43
+ }
44
+ export function workingSnapshot(files) {
45
+ files.sort((left, right) => comparePaths(left.path, right.path));
46
+ const id = digest(JSON.stringify(files.map(file => [file.path, digest(file.bytes)])));
47
+ return { subject: { kind: 'working-tree', id }, files };
48
+ }
49
+ //# sourceMappingURL=snapshot.js.map
@@ -0,0 +1,7 @@
1
+ export interface SourceLocator {
2
+ readonly provider: string;
3
+ /** A fetch URL with {revision} and either {path} or {path:component}. */
4
+ readonly url: string;
5
+ /** An optional forge page URL, which can also use {line}. */
6
+ readonly web?: string;
7
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=source-locator.js.map
@@ -0,0 +1,31 @@
1
+ export type Subject = {
2
+ readonly kind: 'commit';
3
+ readonly id: string;
4
+ } | {
5
+ readonly kind: 'working-tree';
6
+ readonly id: string;
7
+ };
8
+ export interface SourceFile {
9
+ readonly path: string;
10
+ readonly bytes: Uint8Array;
11
+ }
12
+ /** A 1-based inclusive range in source text. */
13
+ export type SourceLineRange = readonly [first: number, last: number];
14
+ export declare function isMergedLineRanges(value: unknown): value is readonly SourceLineRange[];
15
+ export declare const maxClaimedFileBytes: number;
16
+ export declare function isClaimedText(bytes: Uint8Array): boolean;
17
+ export interface InventoryFile {
18
+ readonly path: string;
19
+ readonly lines: number | null;
20
+ /** Size in bytes, from Git or the file system; independent of formatting, unlike lines. */
21
+ readonly bytes?: number;
22
+ }
23
+ export interface SourceSnapshot {
24
+ readonly subject: Subject;
25
+ readonly files: readonly SourceFile[];
26
+ /** Object IDs from the immutable Git tree, keyed by repository-relative path. */
27
+ readonly blobIds?: ReadonlyMap<string, string>;
28
+ readonly inventory?: readonly InventoryFile[];
29
+ readonly generatedExcluded?: readonly string[];
30
+ readonly oversizedClaims?: readonly string[];
31
+ }
@@ -0,0 +1,20 @@
1
+ export function isMergedLineRanges(value) {
2
+ if (!Array.isArray(value))
3
+ return false;
4
+ let previous = -1;
5
+ for (const range of value) {
6
+ if (!Array.isArray(range) || range.length !== 2)
7
+ return false;
8
+ const [first, last] = range;
9
+ if (typeof first !== 'number' || typeof last !== 'number' || !Number.isSafeInteger(first)
10
+ || !Number.isSafeInteger(last) || first <= previous + 1 || last < first)
11
+ return false;
12
+ previous = last;
13
+ }
14
+ return true;
15
+ }
16
+ export const maxClaimedFileBytes = 1024 * 1024;
17
+ export function isClaimedText(bytes) {
18
+ return bytes.byteLength <= maxClaimedFileBytes && !bytes.subarray(0, 8192).includes(0);
19
+ }
20
+ //# sourceMappingURL=source.js.map
@@ -0,0 +1,9 @@
1
+ import type { Report } from '../model/report.js';
2
+ import type { Subject } from '../model/source.js';
3
+ export interface ReportReader {
4
+ read(subject: Subject): Promise<Report>;
5
+ list(): Promise<readonly Report[]>;
6
+ }
7
+ export interface ReportWriter {
8
+ save(report: Report): Promise<void>;
9
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=report.js.map
@@ -0,0 +1,14 @@
1
+ import type { Plugin } from '../engine/plugin.js';
2
+ import type { SourceLocator } from '../model/source-locator.js';
3
+ export interface SourceContext {
4
+ readonly option?: string;
5
+ readonly remotes: readonly string[];
6
+ readonly env: Readonly<Record<string, string | undefined>>;
7
+ }
8
+ export interface SourceProvider {
9
+ readonly id: string;
10
+ locate(context: SourceContext): SourceLocator | undefined;
11
+ read?(revision: string, path: string, signal?: AbortSignal): Promise<Uint8Array | undefined>;
12
+ }
13
+ export type SourcePlugin = Plugin & SourceProvider;
14
+ export declare function isSourcePathname(path: string): boolean;
@@ -0,0 +1,5 @@
1
+ export function isSourcePathname(path) {
2
+ return !/^[A-Za-z]:/.test(path) && !/[\\\0\r\n]/.test(path)
3
+ && path.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..');
4
+ }
5
+ //# sourceMappingURL=source-provider.js.map
@@ -0,0 +1,18 @@
1
+ import type { SourceFile } from '../model/source.js';
2
+ export interface ToolInvocation {
3
+ readonly argv: readonly string[];
4
+ readonly files: readonly SourceFile[];
5
+ readonly stdin?: Uint8Array;
6
+ readonly timeoutMs: number;
7
+ readonly maxOutputBytes: number;
8
+ }
9
+ export interface ToolResult {
10
+ readonly exitCode: number;
11
+ readonly stdout: Uint8Array;
12
+ readonly stderr: Uint8Array;
13
+ }
14
+ export interface ToolRunner {
15
+ readonly network: 'none';
16
+ readonly implementation?: string;
17
+ run(invocation: ToolInvocation): Promise<ToolResult>;
18
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=tool-runner.js.map
@@ -0,0 +1,11 @@
1
+ export declare const defaultSourceExclusions: readonly ['**/.yarn', '**/.pnp.{js,cjs,loader.mjs}', '**/vendor', '**/third_party', '**/*.min.{js,cjs,mjs}', '**/*{.,-}bundle.{js,cjs,mjs}'];
2
+ export declare function sourceExclusionMatcher(patterns: readonly string[], generated?: readonly string[]): (path: string) => boolean;
3
+ export declare const generatedSourcePolicy: {
4
+ readonly version: 1;
5
+ readonly minBytes: 1024;
6
+ readonly minMeanLineLength: 300;
7
+ };
8
+ /** Detect generated text by its source-map trailer or the density of its nonblank lines. */
9
+ export declare function isGeneratedSource(bytes: Uint8Array): boolean;
10
+ export declare function normalizeExclusions(value: unknown): readonly string[];
11
+ export declare function exclusionMatcher(patterns: readonly string[]): (path: string) => boolean;
@@ -0,0 +1,58 @@
1
+ import { posix } from 'node:path';
2
+ export const defaultSourceExclusions = [
3
+ '**/.yarn', '**/.pnp.{js,cjs,loader.mjs}', '**/vendor', '**/third_party',
4
+ '**/*.min.{js,cjs,mjs}', '**/*{.,-}bundle.{js,cjs,mjs}',
5
+ ];
6
+ export function sourceExclusionMatcher(patterns, generated = []) {
7
+ const matches = exclusionMatcher([...defaultSourceExclusions, ...patterns]);
8
+ const generatedPaths = new Set(generated);
9
+ return path => generatedPaths.has(path) || matches(path);
10
+ }
11
+ export const generatedSourcePolicy = { version: 1, minBytes: 1024, minMeanLineLength: 300 };
12
+ /** Detect generated text by its source-map trailer or the density of its nonblank lines. */
13
+ export function isGeneratedSource(bytes) {
14
+ const source = new TextDecoder().decode(bytes);
15
+ if (/(?:^|\n)[ \t]*(?:\/\/[#@][ \t]*sourceMappingURL=\S+|\/\*[#@][ \t]*sourceMappingURL=[^\r\n]+\*\/)[ \t\r\n]*$/.test(source))
16
+ return true;
17
+ if (bytes.length < generatedSourcePolicy.minBytes)
18
+ return false;
19
+ const lines = source.split(/\r\n|[\n\r\u2028\u2029]/).map(line => line.trim()).filter(Boolean);
20
+ return lines.reduce((sum, line) => sum + line.length, 0) > lines.length * generatedSourcePolicy.minMeanLineLength;
21
+ }
22
+ export function normalizeExclusions(value) {
23
+ if (!Array.isArray(value))
24
+ throw new Error('Profile exclude must be an array of repository-relative paths or globs');
25
+ const patterns = new Set();
26
+ for (const item of value) {
27
+ if (typeof item !== 'string')
28
+ throw new Error('Each exclusion must be a string');
29
+ const pattern = item.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '');
30
+ if (!isRelativePath(pattern) || /[\\\0]/.test(pattern) || /^[#!]/.test(pattern)) {
31
+ throw new Error(`Invalid source exclusion: ${JSON.stringify(item)}. Use a repository-relative path or glob.`);
32
+ }
33
+ patterns.add(pattern);
34
+ }
35
+ return [...patterns];
36
+ }
37
+ export function exclusionMatcher(patterns) {
38
+ if (patterns.length === 0)
39
+ return () => false;
40
+ return path => {
41
+ if (!isRelativePath(path))
42
+ return false;
43
+ // A rule that matches a directory excludes its entire subtree.
44
+ let candidate = path;
45
+ for (;;) {
46
+ if (patterns.some(pattern => candidate === pattern || posix.matchesGlob(candidate, pattern)))
47
+ return true;
48
+ const slash = candidate.lastIndexOf('/');
49
+ if (slash === -1)
50
+ return false;
51
+ candidate = candidate.slice(0, slash);
52
+ }
53
+ };
54
+ }
55
+ function isRelativePath(path) {
56
+ return !/^[A-Za-z]:/.test(path) && path.split('/').every(part => part !== '' && part !== '.' && part !== '..');
57
+ }
58
+ //# sourceMappingURL=exclusions.js.map
@@ -0,0 +1,31 @@
1
+ export declare const structuralRules: {
2
+ readonly 'function-parameters': {
3
+ readonly limit: 5;
4
+ readonly minutesPerExcess: 10;
5
+ };
6
+ readonly 'return-statements': {
7
+ readonly limit: 6;
8
+ readonly minutesPerExcess: 10;
9
+ };
10
+ readonly 'boolean-logic': {
11
+ readonly limit: 4;
12
+ readonly minutesPerExcess: 10;
13
+ };
14
+ readonly 'nested-control-flow': {
15
+ readonly limit: 4;
16
+ readonly minutesPerExcess: 20;
17
+ };
18
+ readonly 'function-complexity': {
19
+ readonly limit: 15;
20
+ readonly minutesPerExcess: 10;
21
+ };
22
+ readonly 'file-complexity': {
23
+ readonly limit: 50;
24
+ readonly minutesPerExcess: 5;
25
+ };
26
+ };
27
+ export declare const duplicationSettings: {
28
+ readonly minCodeLines: 12;
29
+ readonly minNodes: 50;
30
+ readonly minutesPerRepeatedLine: 2;
31
+ };
@@ -0,0 +1,10 @@
1
+ export const structuralRules = {
2
+ 'function-parameters': { limit: 5, minutesPerExcess: 10 },
3
+ 'return-statements': { limit: 6, minutesPerExcess: 10 },
4
+ 'boolean-logic': { limit: 4, minutesPerExcess: 10 },
5
+ 'nested-control-flow': { limit: 4, minutesPerExcess: 20 },
6
+ 'function-complexity': { limit: 15, minutesPerExcess: 10 },
7
+ 'file-complexity': { limit: 50, minutesPerExcess: 5 },
8
+ };
9
+ export const duplicationSettings = { minCodeLines: 12, minNodes: 50, minutesPerRepeatedLine: 2 };
10
+ //# sourceMappingURL=maintainability.js.map
@@ -0,0 +1,4 @@
1
+ export declare function normalizeProfile(profile: unknown): {
2
+ exclude: readonly string[];
3
+ ignore: readonly import("../model/ignore-rule.js").FindingIgnoreRule[];
4
+ };
@@ -0,0 +1,11 @@
1
+ import { isRecord } from '../engine/plugin.js';
2
+ import { normalizeFindingIgnore } from '../model/finding-ignore.js';
3
+ import { normalizeExclusions } from './exclusions.js';
4
+ export function normalizeProfile(profile) {
5
+ if (!isRecord(profile) || Object.keys(profile).some(key => key !== 'exclude' && key !== 'ignore')) {
6
+ throw new Error('Expected a JSON profile with optional exclude and ignore arrays');
7
+ }
8
+ return { exclude: normalizeExclusions(profile.exclude === undefined ? [] : profile.exclude),
9
+ ignore: normalizeFindingIgnore(profile.ignore === undefined ? [] : profile.ignore) };
10
+ }
11
+ //# sourceMappingURL=profile.js.map
@@ -0,0 +1,6 @@
1
+ import type { DiffCoverage } from '../model/diff-coverage.js';
2
+ export interface CoverageDecision {
3
+ readonly status: 'passed' | 'failed' | 'not-applicable' | 'indeterminate';
4
+ readonly minimumPercent: number;
5
+ }
6
+ export declare function assessDiffCoverage(result: DiffCoverage, minimumPercent: number): CoverageDecision;
@@ -0,0 +1,11 @@
1
+ export function assessDiffCoverage(result, minimumPercent) {
2
+ if (!Number.isFinite(minimumPercent) || minimumPercent < 0 || minimumPercent > 100) {
3
+ throw new Error('Minimum diff coverage must be a percentage from 0 to 100');
4
+ }
5
+ if (result.status === 'partial')
6
+ return { status: 'indeterminate', minimumPercent };
7
+ if (result.percent === null)
8
+ return { status: 'not-applicable', minimumPercent };
9
+ return { status: result.percent >= minimumPercent ? 'passed' : 'failed', minimumPercent };
10
+ }
11
+ //# sourceMappingURL=diff-coverage-policy.js.map
@@ -0,0 +1,40 @@
1
+ import type { GitChanges } from '../model/changes.js';
2
+ import type { DiffCoverage, DiffCoverageResult } from '../model/diff-coverage.js';
3
+ import type { SourceSnapshot } from '../model/source.js';
4
+ import type { CoverageDecision } from './diff-coverage-policy.js';
5
+ export declare const diffCoverageSchema = "urn:repometry:schema:diff-coverage:1";
6
+ export interface DiffCoverageReport extends DiffCoverage {
7
+ readonly schema: typeof diffCoverageSchema;
8
+ readonly requestedBase: string;
9
+ readonly base: string;
10
+ readonly head: string;
11
+ readonly generatedAt: string;
12
+ readonly appliedConfig: Readonly<Record<string, unknown>>;
13
+ readonly decision: CoverageDecision | null;
14
+ }
15
+ export interface DiffCoverageSource {
16
+ readonly requestedBase: string;
17
+ readonly base: string;
18
+ readonly head: string;
19
+ readonly snapshot: SourceSnapshot;
20
+ readonly changes: GitChanges;
21
+ readonly root: string;
22
+ readonly lcovText: string;
23
+ readonly appliedConfig: Readonly<Record<string, unknown>>;
24
+ }
25
+ export interface DiffCoveragePorts {
26
+ readInputs(excludedPaths: readonly string[], excludes: (path: string) => boolean): Promise<DiffCoverageSource>;
27
+ measure(source: DiffCoverageSource, excludes: (path: string) => boolean): Promise<DiffCoverageResult>;
28
+ }
29
+ interface DiffCoverageOptions {
30
+ readonly exclude?: readonly string[];
31
+ readonly minimumPercent?: number;
32
+ }
33
+ export declare function executeDiffCoverage(options: DiffCoverageOptions, ports: DiffCoveragePorts): Promise<{
34
+ report: DiffCoverageReport;
35
+ uncovered: readonly {
36
+ readonly path: string;
37
+ readonly lines: readonly number[];
38
+ }[];
39
+ }>;
40
+ export {};
@@ -0,0 +1,16 @@
1
+ import { normalizeExclusions, sourceExclusionMatcher } from '../profile/exclusions.js';
2
+ import { assessDiffCoverage } from './diff-coverage-policy.js';
3
+ export const diffCoverageSchema = 'urn:repometry:schema:diff-coverage:1';
4
+ export async function executeDiffCoverage(options, ports) {
5
+ const excludedPaths = normalizeExclusions(options.exclude ?? []);
6
+ const source = await ports.readInputs(excludedPaths, sourceExclusionMatcher(excludedPaths));
7
+ const value = await ports.measure(source, sourceExclusionMatcher(excludedPaths, source.snapshot.generatedExcluded));
8
+ const { uncovered, ...observation } = value;
9
+ const { requestedBase, base, head, appliedConfig } = source;
10
+ const report = {
11
+ schema: diffCoverageSchema, requestedBase, base, head, generatedAt: new Date().toISOString(), appliedConfig,
12
+ ...observation, decision: options.minimumPercent === undefined ? null : assessDiffCoverage(value, options.minimumPercent),
13
+ };
14
+ return { report, uncovered };
15
+ }
16
+ //# sourceMappingURL=diff-coverage.js.map
@@ -0,0 +1,37 @@
1
+ import type { FindingIgnoreRule } from '../model/finding-ignore.js';
2
+ import type { Report } from '../model/report.js';
3
+ import type { SourceSnapshot } from '../model/source.js';
4
+ export interface AnalysisInput {
5
+ /** The source adapter has already applied the exclusions to this snapshot. */
6
+ readonly snapshot: SourceSnapshot;
7
+ readonly excludedOutput: string | null;
8
+ readonly excludedPaths?: readonly string[];
9
+ readonly coverage?: {
10
+ readonly text: string;
11
+ readonly sourceRoot: string;
12
+ };
13
+ }
14
+ type Excludes = (path: string) => boolean;
15
+ interface InspectionSource {
16
+ readonly snapshot: SourceSnapshot;
17
+ readonly root: string;
18
+ readonly excludedOutput: string | null;
19
+ save(report: Report): Promise<void>;
20
+ }
21
+ interface InspectionCoverage {
22
+ readonly text: string;
23
+ readonly inputDigests: readonly string[];
24
+ }
25
+ export interface InspectionPorts {
26
+ readSource(excludes: Excludes): Promise<InspectionSource>;
27
+ analyze(input: AnalysisInput): Promise<Report>;
28
+ readCoverage?(source: Pick<InspectionSource, 'root' | 'snapshot'>): Promise<InspectionCoverage>;
29
+ importFindings?(report: Report, root: string, excludes: Excludes): Promise<Report>;
30
+ recordChurn?(report: Report, root: string, paths: readonly string[]): Promise<Report>;
31
+ }
32
+ export interface InspectionOptions {
33
+ readonly exclude?: readonly string[];
34
+ readonly ignore?: readonly FindingIgnoreRule[];
35
+ }
36
+ export declare function executeInspection(options: InspectionOptions, ports: InspectionPorts): Promise<Report>;
37
+ export {};
@@ -0,0 +1,42 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { isRecord } from '../engine/plugin.js';
3
+ import { normalizeFindingIgnore, partitionFindings } from '../model/finding-ignore.js';
4
+ import { reportSchema } from '../model/report.js';
5
+ import { digest } from '../model/snapshot.js';
6
+ import { normalizeExclusions, sourceExclusionMatcher } from '../profile/exclusions.js';
7
+ export async function executeInspection(options, ports) {
8
+ const excludedPaths = normalizeExclusions(options.exclude ?? []);
9
+ const ignore = normalizeFindingIgnore(options.ignore ?? []);
10
+ const source = await ports.readSource(sourceExclusionMatcher(excludedPaths));
11
+ const { snapshot, root, excludedOutput } = source;
12
+ const lcov = await ports.readCoverage?.(source);
13
+ const report = await ports.analyze({
14
+ snapshot, excludedOutput, excludedPaths,
15
+ coverage: lcov === undefined ? undefined : { text: lcov.text, sourceRoot: root },
16
+ });
17
+ if (report.subject.kind !== snapshot.subject.kind || report.subject.id !== snapshot.subject.id) {
18
+ throw new Error('Analysis result belongs to a different source snapshot');
19
+ }
20
+ const appliedSource = report.appliedConfig.source;
21
+ if (excludedPaths.length > 0 && (!isRecord(appliedSource) || !isDeepStrictEqual(appliedSource.excludedPaths, excludedPaths))) {
22
+ throw new Error('Analysis result does not record the requested source exclusions');
23
+ }
24
+ const covered = lcov && lcov.inputDigests.length > 1 ? withLcovDigests(report, lcov) : report;
25
+ const findings = ports.importFindings
26
+ ? await ports.importFindings(covered, root, sourceExclusionMatcher(excludedPaths, snapshot.generatedExcluded)) : covered;
27
+ const filtered = ignore.length === 0 ? findings : { ...findings, schema: reportSchema,
28
+ appliedConfig: { ...findings.appliedConfig, findingIgnore: ignore },
29
+ ...(findings.findings === undefined ? {} : partitionFindings(findings.findings, ignore)) };
30
+ const result = snapshot.subject.kind === 'commit' && ports.recordChurn
31
+ ? await ports.recordChurn(filtered, root, snapshot.files.map(file => file.path)) : filtered;
32
+ await source.save(result);
33
+ return result;
34
+ }
35
+ function withLcovDigests(report, { text, inputDigests }) {
36
+ const coverage = report.appliedConfig.coverage;
37
+ if (!isRecord(coverage) || coverage.inputDigest !== digest(text)) {
38
+ throw new Error('Analysis result does not record the requested LCOV inputs');
39
+ }
40
+ return { ...report, appliedConfig: { ...report.appliedConfig, coverage: { ...coverage, inputDigests } } };
41
+ }
42
+ //# sourceMappingURL=inspect.js.map
@@ -0,0 +1,18 @@
1
+ import type { LineChanges } from '../model/changes.js';
2
+ import type { Finding } from '../model/finding.js';
3
+ import type { ReviewedIssue } from '../model/pull-review.js';
4
+ export type { IssueEffect, ReviewedIssue } from '../model/pull-review.js';
5
+ export type { SourceLines } from './review-scope.js';
6
+ import type { SourceLines } from './review-scope.js';
7
+ /**
8
+ * Pairs base and head findings that are the same issue, and keeps the pairs on the changed lines of either side.
9
+ * A head finding without a pair is new; a base finding without one was fixed.
10
+ */
11
+ export declare function classifyIssues(base: readonly Finding[], head: readonly Finding[], changes: LineChanges, sources: {
12
+ readonly base: SourceLines;
13
+ readonly head: SourceLines;
14
+ }): readonly ReviewedIssue[];
15
+ export declare function debtEffect(issues: readonly ReviewedIssue[]): {
16
+ readonly added: number;
17
+ readonly removed: number;
18
+ };
@@ -0,0 +1,37 @@
1
+ import { isSensitiveFinding } from '../model/finding.js';
2
+ import { pairFindings } from './review-match.js';
3
+ import { compare, inScope, placed, reviewSide } from './review-scope.js';
4
+ const order = { new: 0, worsened: 1, improved: 2, touched: 3 };
5
+ /**
6
+ * Pairs base and head findings that are the same issue, and keeps the pairs on the changed lines of either side.
7
+ * A head finding without a pair is new; a base finding without one was fixed.
8
+ */
9
+ export function classifyIssues(base, head, changes, sources) {
10
+ const before = reviewSide(changes, 'base', sources.base);
11
+ const after = reviewSide(changes, 'head', sources.head);
12
+ const issues = pairFindings(base, head, changes, { base: before, head: after })
13
+ .filter(([from, to]) => (from !== undefined && inScope(from, before)) || (to !== undefined && inScope(to, after)))
14
+ .map(([from, to]) => review(from, to, before, after));
15
+ return issues.sort((left, right) => Number(isSensitiveFinding(right.finding.category)) - Number(isSensitiveFinding(left.finding.category))
16
+ || order[left.effect] - order[right.effect] || compare(left.finding.path ?? '', right.finding.path ?? '')
17
+ || (left.finding.line ?? 0) - (right.finding.line ?? 0));
18
+ }
19
+ export function debtEffect(issues) {
20
+ return issues.reduce((total, { debtMinutes }) => debtMinutes > 0 ? { ...total, added: total.added + debtMinutes }
21
+ : { ...total, removed: total.removed - debtMinutes }, { added: 0, removed: 0 });
22
+ }
23
+ function review(base, head, before, after) {
24
+ const effort = (finding) => finding?.effortMinutes ?? 0;
25
+ if (!head)
26
+ return { effect: 'improved', ...placed(base, before), before: base.value ?? null, fixed: true, debtMinutes: -effort(base) };
27
+ return { effect: effectOf(base, head), ...placed(head, after), before: base?.value ?? null, fixed: false,
28
+ debtMinutes: effort(head) - effort(base) };
29
+ }
30
+ function effectOf(base, head) {
31
+ if (!base)
32
+ return 'new';
33
+ if (head.value === undefined || base.value === undefined || head.value === base.value)
34
+ return 'touched';
35
+ return head.value > base.value ? 'worsened' : 'improved';
36
+ }
37
+ //# sourceMappingURL=review-effect.js.map
@@ -0,0 +1,14 @@
1
+ import type { LineChanges } from '../model/changes.js';
2
+ import type { Finding } from '../model/finding.js';
3
+ import type { ReviewSide } from './review-scope.js';
4
+ /** A base finding and a head finding that are the same issue; one side is absent for a new or a fixed issue. */
5
+ export type FindingPair = readonly [base: Finding | undefined, head: Finding | undefined];
6
+ /**
7
+ * Pairs the findings of both sides that are the same issue. First by position through the diff, which follows code that
8
+ * moved or was renamed and tells unnamed functions apart. Then by rule, file, anchor and the text of the first line, in
9
+ * line order. Last, an anchor that only one finding on each side still carries, such as a rewritten named function.
10
+ */
11
+ export declare function pairFindings(base: readonly Finding[], head: readonly Finding[], changes: LineChanges, sides: {
12
+ readonly base: ReviewSide;
13
+ readonly head: ReviewSide;
14
+ }): FindingPair[];
@@ -0,0 +1,72 @@
1
+ import { digest } from '../model/snapshot.js';
2
+ import { positionMatches } from './review-position.js';
3
+ /**
4
+ * Pairs the findings of both sides that are the same issue. First by position through the diff, which follows code that
5
+ * moved or was renamed and tells unnamed functions apart. Then by rule, file, anchor and the text of the first line, in
6
+ * line order. Last, an anchor that only one finding on each side still carries, such as a rewritten named function.
7
+ */
8
+ export function pairFindings(base, head, changes, sides) {
9
+ const byBase = new Map(changes.files.flatMap(file => file.previous === null ? [] : [[file.previous, file]]));
10
+ const headPath = (path) => byBase.has(path) ? byBase.get(path).path : path;
11
+ const baseLeft = new Set(base);
12
+ const headLeft = new Set(head);
13
+ const pairs = [];
14
+ const take = (from, to) => {
15
+ if (!baseLeft.has(from) || !headLeft.has(to))
16
+ return;
17
+ baseLeft.delete(from);
18
+ headLeft.delete(to);
19
+ pairs.push([from, to]);
20
+ };
21
+ for (const { base: from, head: to } of positionMatches(base, head, byBase, headPath))
22
+ take(from, to);
23
+ pairByKey(baseLeft, headLeft, headPath, (finding, path, side) => identity(finding, path, side === 'base' ? sides.base : sides.head), take);
24
+ pairByKey(baseLeft, headLeft, headPath, uniqueAnchor(baseLeft, headLeft, headPath), take);
25
+ return [...pairs, ...[...headLeft].map(finding => [undefined, finding]), ...[...baseLeft].map(finding => [finding, undefined])];
26
+ }
27
+ /** Pairs leftover findings with equal keys, in line order. */
28
+ function pairByKey(baseLeft, headLeft, headPath, keyOf, take) {
29
+ const waiting = new Map();
30
+ for (const finding of inLineOrder(baseLeft)) {
31
+ const path = finding.path === undefined ? undefined : headPath(finding.path);
32
+ const key = path === null ? undefined : keyOf(finding, path, 'base');
33
+ if (key !== undefined)
34
+ waiting.set(key, [...waiting.get(key) ?? [], finding]);
35
+ }
36
+ for (const finding of inLineOrder(headLeft)) {
37
+ const key = keyOf(finding, finding.path, 'head');
38
+ const match = key === undefined ? undefined : waiting.get(key)?.shift();
39
+ if (match)
40
+ take(match, finding);
41
+ }
42
+ }
43
+ /** Keys an anchor that exactly one leftover finding carries on each side; repeated anchors such as `(anonymous)` get none. */
44
+ function uniqueAnchor(baseLeft, headLeft, headPath) {
45
+ const anchorKey = (finding, path) => finding.anchor === undefined || finding.category === 'duplication' ? undefined : JSON.stringify([finding.rule, path ?? null, finding.anchor]);
46
+ const counts = new Map();
47
+ const count = (key, side) => {
48
+ if (key !== undefined)
49
+ counts.set(`${side}${key}`, (counts.get(`${side}${key}`) ?? 0) + 1);
50
+ };
51
+ for (const finding of baseLeft)
52
+ count(anchorKey(finding, finding.path === undefined ? undefined : headPath(finding.path) ?? undefined), 0);
53
+ for (const finding of headLeft)
54
+ count(anchorKey(finding, finding.path), 1);
55
+ return (finding, path) => {
56
+ const key = anchorKey(finding, path);
57
+ return key !== undefined && counts.get(`0${key}`) === 1 && counts.get(`1${key}`) === 1 ? key : undefined;
58
+ };
59
+ }
60
+ function identity(finding, path, side) {
61
+ if (finding.category === 'duplication' && finding.anchor !== undefined)
62
+ return JSON.stringify(['duplication', finding.anchor]);
63
+ return JSON.stringify([finding.rule, path ?? null, finding.anchor ?? null, lineHash(finding, side)]);
64
+ }
65
+ function lineHash(finding, side) {
66
+ const text = finding.path === undefined || finding.line === undefined ? undefined : side.lines.line(finding.path, finding.line);
67
+ return text === undefined ? '(file)' : digest(text.replace(/\s+/g, '')).slice(0, 16);
68
+ }
69
+ function inLineOrder(findings) {
70
+ return [...findings].sort((left, right) => (left.line ?? 0) - (right.line ?? 0) || (left.endLine ?? 0) - (right.endLine ?? 0));
71
+ }
72
+ //# sourceMappingURL=review-match.js.map
@@ -0,0 +1,14 @@
1
+ import type { FileLineChange } from '../model/changes.js';
2
+ import type { Finding } from '../model/finding.js';
3
+ /** A base finding and a head finding the diff places at the same lines. */
4
+ export interface PositionMatch {
5
+ readonly base: Finding;
6
+ readonly head: Finding;
7
+ }
8
+ /**
9
+ * Pairs by position, best first: most of a base finding's lines, carried through the diff, land inside a head finding of
10
+ * the same rule. More carried lines win, then the same anchor, then the closer size.
11
+ */
12
+ export declare function positionMatches(base: readonly Finding[], head: readonly Finding[], byBase: ReadonlyMap<string, FileLineChange>, headPath: (path: string) => string | null): PositionMatch[];
13
+ /** Where an unchanged base line sits on the head side; undefined for a changed line or a file without a counterpart. */
14
+ export declare function headLine(file: FileLineChange | undefined, line: number): number | undefined;