@gobing-ai/ts-rule-engine 0.2.6 → 0.2.7
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.
- package/dist/config/extensions.d.ts +46 -0
- package/dist/config/extensions.d.ts.map +1 -0
- package/dist/config/extensions.js +63 -0
- package/dist/config/loader.js +13 -3
- package/dist/engine.d.ts +26 -1
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +79 -0
- package/dist/evaluators/exit-code-evaluator.d.ts +1 -1
- package/dist/evaluators/exit-code-evaluator.d.ts.map +1 -1
- package/dist/evaluators/exit-code-evaluator.js +22 -9
- package/dist/evaluators/forbidden-import-evaluator.d.ts +16 -3
- package/dist/evaluators/forbidden-import-evaluator.d.ts.map +1 -1
- package/dist/evaluators/forbidden-import-evaluator.js +71 -6
- package/dist/evaluators/import-boundary-evaluator.d.ts +19 -0
- package/dist/evaluators/import-boundary-evaluator.d.ts.map +1 -0
- package/dist/evaluators/import-boundary-evaluator.js +85 -0
- package/dist/evaluators/path-evaluator.d.ts +15 -2
- package/dist/evaluators/path-evaluator.d.ts.map +1 -1
- package/dist/evaluators/path-evaluator.js +49 -3
- package/dist/evaluators/regex-evaluator.d.ts.map +1 -1
- package/dist/evaluators/regex-evaluator.js +43 -8
- package/dist/evaluators/schema-artifact-evaluator.d.ts +21 -0
- package/dist/evaluators/schema-artifact-evaluator.d.ts.map +1 -0
- package/dist/evaluators/schema-artifact-evaluator.js +102 -0
- package/dist/evaluators/secrets-scanner-evaluator.d.ts +13 -2
- package/dist/evaluators/secrets-scanner-evaluator.d.ts.map +1 -1
- package/dist/evaluators/secrets-scanner-evaluator.js +72 -9
- package/dist/evaluators/sg-evaluator.d.ts +19 -0
- package/dist/evaluators/sg-evaluator.d.ts.map +1 -0
- package/dist/evaluators/sg-evaluator.js +112 -0
- package/dist/evaluators/test-location-evaluator.d.ts +14 -1
- package/dist/evaluators/test-location-evaluator.d.ts.map +1 -1
- package/dist/evaluators/test-location-evaluator.js +42 -22
- package/dist/evaluators/tsdoc-export-evaluator.js +19 -5
- package/dist/fixers/fixers.d.ts +86 -0
- package/dist/fixers/fixers.d.ts.map +1 -0
- package/dist/fixers/fixers.js +230 -0
- package/dist/fixers/test-stub-fixer.d.ts +49 -0
- package/dist/fixers/test-stub-fixer.d.ts.map +1 -0
- package/dist/fixers/test-stub-fixer.js +91 -0
- package/dist/host/builtins.d.ts.map +1 -1
- package/dist/host/builtins.js +12 -1
- package/dist/host/rule-engine-host.d.ts +3 -0
- package/dist/host/rule-engine-host.d.ts.map +1 -1
- package/dist/host/rule-engine-host.js +3 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/resolvers/test-path-resolver.d.ts +72 -0
- package/dist/resolvers/test-path-resolver.d.ts.map +1 -0
- package/dist/resolvers/test-path-resolver.js +112 -0
- package/dist/types.d.ts +30 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +8 -0
- package/package.json +3 -3
- package/src/config/extensions.ts +108 -0
- package/src/config/loader.ts +13 -3
- package/src/engine.ts +99 -2
- package/src/evaluators/exit-code-evaluator.ts +27 -9
- package/src/evaluators/forbidden-import-evaluator.ts +101 -7
- package/src/evaluators/import-boundary-evaluator.ts +135 -0
- package/src/evaluators/path-evaluator.ts +66 -3
- package/src/evaluators/regex-evaluator.ts +53 -12
- package/src/evaluators/schema-artifact-evaluator.ts +134 -0
- package/src/evaluators/secrets-scanner-evaluator.ts +89 -11
- package/src/evaluators/sg-evaluator.ts +133 -0
- package/src/evaluators/test-location-evaluator.ts +47 -35
- package/src/evaluators/tsdoc-export-evaluator.ts +19 -5
- package/src/fixers/fixers.ts +294 -0
- package/src/fixers/test-stub-fixer.ts +118 -0
- package/src/host/builtins.ts +17 -1
- package/src/host/rule-engine-host.ts +4 -0
- package/src/index.ts +4 -0
- package/src/resolvers/test-path-resolver.ts +133 -0
- package/src/types.ts +34 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core fixer pipeline: provider contracts, built-in fixer implementations,
|
|
3
|
+
* and the byte-range fix application function.
|
|
4
|
+
*
|
|
5
|
+
* @module rule-engine/fixers
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
9
|
+
import { NodeFileSystem, type ProcessExecutor } from '@gobing-ai/ts-runtime';
|
|
10
|
+
import type { CapabilityRegistry } from '../host/capability-registry';
|
|
11
|
+
import type { TestPathResolver } from '../resolvers/test-path-resolver';
|
|
12
|
+
import type { ConstraintFinding, ConstraintRule, Fix, FixMode, RuleContext } from '../types';
|
|
13
|
+
import { TestStubFixer } from './test-stub-fixer';
|
|
14
|
+
|
|
15
|
+
/** Numeric ordering for fix authority; higher means more write authority. */
|
|
16
|
+
export const FIX_MODE_RANK: Record<FixMode, number> = {
|
|
17
|
+
none: 0,
|
|
18
|
+
suggest: 1,
|
|
19
|
+
auto: 2,
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** Result of resolving effective fix authority for a rule. */
|
|
23
|
+
export interface EffectiveFix {
|
|
24
|
+
/** Effective mode after all downgrades. */
|
|
25
|
+
readonly mode: FixMode;
|
|
26
|
+
/** Optional replacement text configured by the rule author. */
|
|
27
|
+
readonly replacement?: string;
|
|
28
|
+
/** Optional provider-specific parameters. */
|
|
29
|
+
readonly params?: Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Input passed to a rule fixer provider. */
|
|
33
|
+
export interface RuleFixerInput {
|
|
34
|
+
/** Rule that produced the findings. */
|
|
35
|
+
readonly rule: ConstraintRule;
|
|
36
|
+
/** Rule execution context. */
|
|
37
|
+
readonly context: RuleContext;
|
|
38
|
+
/** Findings emitted for this rule. */
|
|
39
|
+
readonly findings: ConstraintFinding[];
|
|
40
|
+
/** Effective fix metadata after authority enforcement. */
|
|
41
|
+
readonly fix: EffectiveFix;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Provider that turns findings into byte-range fixes. */
|
|
45
|
+
export interface RuleFixerProvider {
|
|
46
|
+
/** Produce fixes for mechanically fixable findings. */
|
|
47
|
+
createFixes(input: RuleFixerInput): Fix[] | Promise<Fix[]>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Result of applying or previewing a batch of fixes. */
|
|
51
|
+
export interface FixApplicationResult {
|
|
52
|
+
/** Files changed in memory or on disk. */
|
|
53
|
+
readonly changedFiles: string[];
|
|
54
|
+
/** Fixes successfully applied. */
|
|
55
|
+
readonly applied: Fix[];
|
|
56
|
+
/** Fixes skipped because they overlapped an already-applied edit. */
|
|
57
|
+
readonly deferred: Fix[];
|
|
58
|
+
/** Unified diff when dry-run mode is requested. */
|
|
59
|
+
readonly diff: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Dependencies required for the built-in fixer registry. */
|
|
63
|
+
export interface BuiltInFixersDeps {
|
|
64
|
+
/** Resolver registry, required for TestStubFixer. */
|
|
65
|
+
resolvers: CapabilityRegistry<TestPathResolver>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Registry of built-in rule fixer providers keyed by evaluator type. */
|
|
69
|
+
export function builtInFixers(host?: BuiltInFixersDeps, exec?: ProcessExecutor): Map<string, RuleFixerProvider> {
|
|
70
|
+
const regexFixer = new RegexFixerProvider();
|
|
71
|
+
const pathFixer = new PathFixerProvider();
|
|
72
|
+
const entries: Array<[string, RuleFixerProvider]> = [
|
|
73
|
+
['regex', regexFixer],
|
|
74
|
+
['rg', regexFixer],
|
|
75
|
+
['path', pathFixer],
|
|
76
|
+
['file-exist', pathFixer],
|
|
77
|
+
];
|
|
78
|
+
if (host && exec) {
|
|
79
|
+
entries.push(['test-location', new TestStubFixer({ resolvers: host.resolvers, processExecutor: exec })]);
|
|
80
|
+
}
|
|
81
|
+
return new Map(entries);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Resolve a workdir-relative or absolute path to an absolute path. */
|
|
85
|
+
export function resolveWorkdirPath(workdir: string, filePath: string): string {
|
|
86
|
+
return isAbsolute(filePath) ? filePath : join(workdir, filePath);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Apply byte-range fixes to files, optionally returning a dry-run diff only. */
|
|
90
|
+
export async function applyFixes(
|
|
91
|
+
workdir: string,
|
|
92
|
+
fixes: readonly Fix[],
|
|
93
|
+
dryRun = false,
|
|
94
|
+
fs: NodeFileSystem = new NodeFileSystem(),
|
|
95
|
+
): Promise<FixApplicationResult> {
|
|
96
|
+
const byFile = new Map<string, Fix[]>();
|
|
97
|
+
for (const fix of fixes) {
|
|
98
|
+
const list = byFile.get(fix.filePath) ?? [];
|
|
99
|
+
list.push(fix);
|
|
100
|
+
byFile.set(fix.filePath, list);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const applied: Fix[] = [];
|
|
104
|
+
const deferred: Fix[] = [];
|
|
105
|
+
const changedFiles: string[] = [];
|
|
106
|
+
const diffs: string[] = [];
|
|
107
|
+
|
|
108
|
+
for (const [filePath, fileFixes] of byFile) {
|
|
109
|
+
const absPath = resolveWorkdirPath(workdir, filePath);
|
|
110
|
+
if (!isInsideWorkdir(workdir, absPath)) {
|
|
111
|
+
deferred.push(...fileFixes);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const fileExists = await fs.exists(absPath);
|
|
116
|
+
const original = fileExists ? await fs.readFile(absPath) : '';
|
|
117
|
+
const selected = selectNonOverlappingFixes(fileFixes);
|
|
118
|
+
deferred.push(...selected.deferred);
|
|
119
|
+
|
|
120
|
+
let next = original;
|
|
121
|
+
for (const fix of [...selected.applied].sort((a, b) => b.start - a.start)) {
|
|
122
|
+
if (!fileExists && (fix.start !== 0 || fix.end !== 0)) {
|
|
123
|
+
deferred.push(fix);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (!isValidRange(fix.start, fix.end, original.length)) {
|
|
127
|
+
deferred.push(fix);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
next = `${next.slice(0, fix.start)}${fix.replacement}${next.slice(fix.end)}`;
|
|
131
|
+
applied.push(fix);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (next === original) {
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
changedFiles.push(filePath);
|
|
139
|
+
diffs.push(createUnifiedDiff(filePath, original, next));
|
|
140
|
+
|
|
141
|
+
if (!dryRun) {
|
|
142
|
+
const isFullDeletion =
|
|
143
|
+
next.length === 0 && selected.applied.some((fix) => fix.start === 0 && fix.end === original.length);
|
|
144
|
+
if (isFullDeletion) {
|
|
145
|
+
await fs.unlink(absPath);
|
|
146
|
+
} else {
|
|
147
|
+
await fs.writeFile(absPath, next);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return { changedFiles, applied, deferred, diff: diffs.join('\n') };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Create a coarse unified diff string for dry-run CLI output. */
|
|
156
|
+
export function createUnifiedDiff(filePath: string, before: string, after: string): string {
|
|
157
|
+
const beforeLines = before.split('\n');
|
|
158
|
+
const afterLines = after.split('\n');
|
|
159
|
+
const lines = [`--- ${filePath}`, `+++ ${filePath}`, `@@ -1,${beforeLines.length} +1,${afterLines.length} @@`];
|
|
160
|
+
lines.push(...beforeLines.map((line) => `-${line}`));
|
|
161
|
+
lines.push(...afterLines.map((line) => `+${line}`));
|
|
162
|
+
return lines.join('\n');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Select the maximal non-overlapping set of fixes, ordered by ascending start offset. */
|
|
166
|
+
function selectNonOverlappingFixes(fixes: readonly Fix[]): { applied: Fix[]; deferred: Fix[] } {
|
|
167
|
+
const applied: Fix[] = [];
|
|
168
|
+
const deferred: Fix[] = [];
|
|
169
|
+
const ordered = [...fixes].sort((a, b) => a.start - b.start || a.end - b.end);
|
|
170
|
+
let lastEnd = -1;
|
|
171
|
+
for (const fix of ordered) {
|
|
172
|
+
if (fix.start < lastEnd) {
|
|
173
|
+
deferred.push(fix);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
applied.push(fix);
|
|
177
|
+
lastEnd = fix.end;
|
|
178
|
+
}
|
|
179
|
+
return { applied, deferred };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Return true when absPath is at or below workdir. */
|
|
183
|
+
function isInsideWorkdir(workdir: string, absPath: string): boolean {
|
|
184
|
+
const rel = relative(resolve(workdir), resolve(absPath));
|
|
185
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Return true when [start, end] is a valid byte range for a string of contentLength bytes. */
|
|
189
|
+
function isValidRange(start: number, end: number, contentLength: number): boolean {
|
|
190
|
+
return start >= 0 && end >= start && end <= contentLength;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Fixer provider for `regex` / `rg` evaluators.
|
|
195
|
+
*
|
|
196
|
+
* For each finding with a known line number, reads the file and emits a Fix that
|
|
197
|
+
* replaces every regex match on that line using `rule.fix.replacement` as the
|
|
198
|
+
* replacement string (supports `$1` / `$&` back-references).
|
|
199
|
+
*/
|
|
200
|
+
export class RegexFixerProvider implements RuleFixerProvider {
|
|
201
|
+
private readonly fs = new NodeFileSystem();
|
|
202
|
+
|
|
203
|
+
/** Produce fixes for regex-evaluator findings. */
|
|
204
|
+
async createFixes({ rule, context, findings, fix }: RuleFixerInput): Promise<Fix[]> {
|
|
205
|
+
if (fix.mode === 'none' || fix.replacement === undefined) return [];
|
|
206
|
+
// After the guard above, mode is guaranteed to not be 'none'.
|
|
207
|
+
const fixMode = fix.mode as Exclude<FixMode, 'none'>;
|
|
208
|
+
const replacement = fix.replacement;
|
|
209
|
+
const pattern = rule.evaluator.config?.pattern;
|
|
210
|
+
if (typeof pattern !== 'string' || pattern.length === 0) return [];
|
|
211
|
+
const flags = flagsFromRule(rule);
|
|
212
|
+
const regex = new RegExp(pattern, flags.includes('g') ? flags : `${flags}g`);
|
|
213
|
+
|
|
214
|
+
const fixes: Fix[] = [];
|
|
215
|
+
for (const finding of findings) {
|
|
216
|
+
if (!finding.filePath) continue;
|
|
217
|
+
const absPath = resolveWorkdirPath(context.workdir, finding.filePath);
|
|
218
|
+
if (!isInsideWorkdir(context.workdir, absPath) || finding.line == null) continue;
|
|
219
|
+
if (!(await this.fs.exists(absPath))) continue;
|
|
220
|
+
const source = await this.fs.readFile(absPath);
|
|
221
|
+
const line = getLineRange(source, finding.line);
|
|
222
|
+
if (!line) continue;
|
|
223
|
+
for (const match of source.slice(line.start, line.end).matchAll(regex)) {
|
|
224
|
+
if (match.index === undefined) continue;
|
|
225
|
+
const matched = match[0];
|
|
226
|
+
fixes.push({
|
|
227
|
+
ruleId: rule.id,
|
|
228
|
+
filePath: finding.filePath,
|
|
229
|
+
start: line.start + match.index,
|
|
230
|
+
end: line.start + match.index + matched.length,
|
|
231
|
+
replacement: matched.replace(new RegExp(pattern, flags), replacement),
|
|
232
|
+
mode: fixMode,
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return fixes;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Fixer provider for `path` / `file-exist` evaluators.
|
|
242
|
+
*
|
|
243
|
+
* In `auto` mode, when a rule requires a file to be absent (`must: absent`),
|
|
244
|
+
* emits a Fix that replaces the entire file content with an empty string.
|
|
245
|
+
* `applyFixes` interprets a zero-length result spanning the full file as a deletion.
|
|
246
|
+
*/
|
|
247
|
+
export class PathFixerProvider implements RuleFixerProvider {
|
|
248
|
+
private readonly fs = new NodeFileSystem();
|
|
249
|
+
|
|
250
|
+
/** Produce deletion fixes for path-evaluator findings. */
|
|
251
|
+
async createFixes({ rule, context, findings, fix }: RuleFixerInput): Promise<Fix[]> {
|
|
252
|
+
if (fix.mode !== 'auto' || rule.evaluator.config?.must !== 'absent') return [];
|
|
253
|
+
const fixes: Fix[] = [];
|
|
254
|
+
for (const finding of findings) {
|
|
255
|
+
if (!finding.filePath) continue;
|
|
256
|
+
const absPath = resolveWorkdirPath(context.workdir, finding.filePath);
|
|
257
|
+
if (!isInsideWorkdir(context.workdir, absPath)) continue;
|
|
258
|
+
if (!(await this.fs.exists(absPath))) continue;
|
|
259
|
+
const content = await this.fs.readFile(absPath);
|
|
260
|
+
fixes.push({
|
|
261
|
+
ruleId: rule.id,
|
|
262
|
+
filePath: finding.filePath,
|
|
263
|
+
start: 0,
|
|
264
|
+
end: content.length,
|
|
265
|
+
replacement: '',
|
|
266
|
+
mode: 'auto' as const,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
return fixes;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Extract regex flags from a rule's evaluator config. */
|
|
274
|
+
function flagsFromRule(rule: ConstraintRule): string {
|
|
275
|
+
const raw = rule.evaluator.config?.flags;
|
|
276
|
+
if (typeof raw !== 'string') return '';
|
|
277
|
+
if (raw.startsWith('(?') && raw.endsWith(')')) {
|
|
278
|
+
return raw.slice(2, -1).replace(/[^imsuy]/g, '');
|
|
279
|
+
}
|
|
280
|
+
return raw.replace(/[^imsuy]/g, '');
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Return the byte range [start, end) of a one-based line number within source. */
|
|
284
|
+
function getLineRange(source: string, oneBasedLine: number): { start: number; end: number } | null {
|
|
285
|
+
if (oneBasedLine < 1) return null;
|
|
286
|
+
let start = 0;
|
|
287
|
+
for (let line = 1; line < oneBasedLine; line += 1) {
|
|
288
|
+
const next = source.indexOf('\n', start);
|
|
289
|
+
if (next === -1) return null;
|
|
290
|
+
start = next + 1;
|
|
291
|
+
}
|
|
292
|
+
const newline = source.indexOf('\n', start);
|
|
293
|
+
return { start, end: newline === -1 ? source.length : newline };
|
|
294
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fixer that generates test file skeletons for source files missing tests.
|
|
3
|
+
*
|
|
4
|
+
* Resolver-aware: selects the correct {@link TestPathResolver} from
|
|
5
|
+
* `rule.evaluator.config.resolver`. Passes empty exports to the resolver's
|
|
6
|
+
* `generateSkeleton` — AST / sg discovery is intentionally omitted here to
|
|
7
|
+
* keep the shared package dependency-free; callers that need export-aware
|
|
8
|
+
* skeletons should register a custom resolver that performs its own discovery.
|
|
9
|
+
* Never overwrites an existing test file.
|
|
10
|
+
*
|
|
11
|
+
* @module rule-engine/fixers/test-stub-fixer
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { isAbsolute, join } from 'node:path';
|
|
15
|
+
import { NodeFileSystem, type ProcessExecutor } from '@gobing-ai/ts-runtime';
|
|
16
|
+
import type { CapabilityRegistry } from '../host/capability-registry';
|
|
17
|
+
import type { TestPathResolver } from '../resolvers/test-path-resolver';
|
|
18
|
+
import type { Fix } from '../types';
|
|
19
|
+
import type { RuleFixerInput, RuleFixerProvider } from './fixers';
|
|
20
|
+
|
|
21
|
+
/** File-system seam for dependency injection in tests. */
|
|
22
|
+
export interface TestStubFileSystem {
|
|
23
|
+
/** Resolve to true if the path exists on disk. */
|
|
24
|
+
exists(path: string): Promise<boolean>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Real file-system implementation backed by the runtime FileSystem seam. */
|
|
28
|
+
export const realFileSystem: TestStubFileSystem = new NodeFileSystem();
|
|
29
|
+
|
|
30
|
+
/** Dependencies injected into {@link TestStubFixer}. */
|
|
31
|
+
export interface TestStubFixerDeps {
|
|
32
|
+
/** Resolver registry from the engine host. */
|
|
33
|
+
readonly resolvers: CapabilityRegistry<TestPathResolver>;
|
|
34
|
+
/** Process executor (reserved for future export discovery). */
|
|
35
|
+
readonly processExecutor: ProcessExecutor;
|
|
36
|
+
/** Optional file-system override for testing. */
|
|
37
|
+
readonly fileSystem?: TestStubFileSystem;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Normalize a finding path to a repository-relative POSIX path, or return null when invalid. */
|
|
41
|
+
function normalizeFindingPath(filePath: string): string | null {
|
|
42
|
+
if (!filePath || isAbsolute(filePath)) return null;
|
|
43
|
+
const normalized = filePath.replaceAll('\\', '/').replace(/^\.\//, '');
|
|
44
|
+
if (normalized === '..' || normalized.startsWith('../') || normalized.includes('/../')) return null;
|
|
45
|
+
return normalized;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Fixer provider for the `test-location` evaluator.
|
|
50
|
+
*
|
|
51
|
+
* Emits a create-file Fix (start=0, end=0) for each finding whose source file
|
|
52
|
+
* has no corresponding test file yet. The test path and skeleton content are
|
|
53
|
+
* produced by the resolver named in `rule.evaluator.config.resolver`
|
|
54
|
+
* (default: `typescript`).
|
|
55
|
+
*/
|
|
56
|
+
export class TestStubFixer implements RuleFixerProvider {
|
|
57
|
+
private readonly resolvers: CapabilityRegistry<TestPathResolver>;
|
|
58
|
+
private readonly fs: TestStubFileSystem;
|
|
59
|
+
|
|
60
|
+
constructor(deps: TestStubFixerDeps) {
|
|
61
|
+
this.resolvers = deps.resolvers;
|
|
62
|
+
// processExecutor is accepted for interface parity but export discovery
|
|
63
|
+
// is not performed in this shared-package implementation — see module doc.
|
|
64
|
+
this.fs = deps.fileSystem ?? realFileSystem;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Produce create-file fixes for missing test stubs. */
|
|
68
|
+
async createFixes(input: RuleFixerInput): Promise<Fix[]> {
|
|
69
|
+
const { rule, context, findings, fix } = input;
|
|
70
|
+
|
|
71
|
+
if (fix.mode === 'none') return [];
|
|
72
|
+
|
|
73
|
+
const resolverName = (rule.evaluator.config?.resolver as string | undefined) ?? 'typescript';
|
|
74
|
+
let resolver: TestPathResolver;
|
|
75
|
+
try {
|
|
76
|
+
resolver = this.resolvers.get(resolverName);
|
|
77
|
+
} catch {
|
|
78
|
+
// Resolver not registered — return no fixes rather than silently falling back.
|
|
79
|
+
return [];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const result: Fix[] = [];
|
|
83
|
+
|
|
84
|
+
for (const finding of findings) {
|
|
85
|
+
if (!finding.filePath) continue;
|
|
86
|
+
|
|
87
|
+
const srcRelPath = normalizeFindingPath(finding.filePath);
|
|
88
|
+
if (!srcRelPath) continue;
|
|
89
|
+
|
|
90
|
+
let testRelPath: string;
|
|
91
|
+
try {
|
|
92
|
+
testRelPath = resolver.resolveTestPath(srcRelPath);
|
|
93
|
+
} catch {
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const absTestPath = join(context.workdir, testRelPath);
|
|
98
|
+
if (await this.fs.exists(absTestPath)) continue;
|
|
99
|
+
|
|
100
|
+
// Export discovery is intentionally omitted — pass empty exports array.
|
|
101
|
+
// Resolvers that need per-export stubs should perform their own discovery.
|
|
102
|
+
const skeleton = resolver.generateSkeleton?.(srcRelPath, []) ?? '';
|
|
103
|
+
if (!skeleton) continue;
|
|
104
|
+
|
|
105
|
+
result.push({
|
|
106
|
+
ruleId: rule.id,
|
|
107
|
+
filePath: testRelPath,
|
|
108
|
+
start: 0,
|
|
109
|
+
end: 0,
|
|
110
|
+
replacement: skeleton,
|
|
111
|
+
// fix.mode !== 'none' is guaranteed by the guard at the top of this method.
|
|
112
|
+
mode: fix.mode as Exclude<typeof fix.mode, 'none'>,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
}
|
package/src/host/builtins.ts
CHANGED
|
@@ -3,13 +3,22 @@ import { AgentDetectionEvaluator } from '../evaluators/agent-detection-evaluator
|
|
|
3
3
|
import { CoverageGateEvaluator } from '../evaluators/coverage-gate-evaluator';
|
|
4
4
|
import { ExitCodeEvaluator } from '../evaluators/exit-code-evaluator';
|
|
5
5
|
import { ForbiddenImportEvaluator } from '../evaluators/forbidden-import-evaluator';
|
|
6
|
+
import { ImportBoundaryEvaluator } from '../evaluators/import-boundary-evaluator';
|
|
6
7
|
import { PathEvaluator } from '../evaluators/path-evaluator';
|
|
7
8
|
import { RegexEvaluator } from '../evaluators/regex-evaluator';
|
|
9
|
+
import { SchemaArtifactEvaluator } from '../evaluators/schema-artifact-evaluator';
|
|
8
10
|
import { SecretsScannerEvaluator } from '../evaluators/secrets-scanner-evaluator';
|
|
11
|
+
import { SgEvaluator } from '../evaluators/sg-evaluator';
|
|
9
12
|
import { TestLocationEvaluator } from '../evaluators/test-location-evaluator';
|
|
10
13
|
import { TsdocExportEvaluator } from '../evaluators/tsdoc-export-evaluator';
|
|
11
14
|
import { JsonFormatter } from '../formatters/json';
|
|
12
15
|
import { TextFormatter } from '../formatters/text';
|
|
16
|
+
import {
|
|
17
|
+
GoTestPathResolver,
|
|
18
|
+
PythonTestPathResolver,
|
|
19
|
+
RustTestPathResolver,
|
|
20
|
+
TypeScriptTestPathResolver,
|
|
21
|
+
} from '../resolvers/test-path-resolver';
|
|
13
22
|
import type { RuleEngineHost } from './rule-engine-host';
|
|
14
23
|
|
|
15
24
|
/** Register bundled evaluators and formatters on a host. */
|
|
@@ -26,7 +35,14 @@ export function registerBuiltins(host: RuleEngineHost, executor?: ProcessExecuto
|
|
|
26
35
|
host.evaluators.register('agent-detection', new AgentDetectionEvaluator(), 'builtin');
|
|
27
36
|
host.evaluators.register('coverage-gate', new CoverageGateEvaluator(), 'builtin');
|
|
28
37
|
host.evaluators.register('tsdoc-export', new TsdocExportEvaluator(), 'builtin');
|
|
29
|
-
host.
|
|
38
|
+
host.resolvers.register('typescript', new TypeScriptTestPathResolver(), 'builtin');
|
|
39
|
+
host.resolvers.register('python', new PythonTestPathResolver(), 'builtin');
|
|
40
|
+
host.resolvers.register('go', new GoTestPathResolver(), 'builtin');
|
|
41
|
+
host.resolvers.register('rust', new RustTestPathResolver(), 'builtin');
|
|
42
|
+
host.evaluators.register('test-location', new TestLocationEvaluator(host.resolvers), 'builtin');
|
|
43
|
+
host.evaluators.register('sg', new SgEvaluator(executor), 'builtin');
|
|
44
|
+
host.evaluators.register('schema-artifact', new SchemaArtifactEvaluator(), 'builtin');
|
|
45
|
+
host.evaluators.register('import-boundary', new ImportBoundaryEvaluator(), 'builtin');
|
|
30
46
|
host.formatters.register('text', new TextFormatter(), 'builtin');
|
|
31
47
|
host.formatters.register('json', new JsonFormatter(), 'builtin');
|
|
32
48
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { TestPathResolver } from '../resolvers/test-path-resolver';
|
|
1
2
|
import type { ResultFormatter, RuleEvaluator } from '../types';
|
|
2
3
|
import { CapabilityRegistry } from './capability-registry';
|
|
3
4
|
|
|
@@ -7,9 +8,12 @@ export class RuleEngineHost {
|
|
|
7
8
|
readonly evaluators: CapabilityRegistry<RuleEvaluator>;
|
|
8
9
|
/** Formatter registry keyed by formatter name. */
|
|
9
10
|
readonly formatters: CapabilityRegistry<ResultFormatter>;
|
|
11
|
+
/** Test-path resolver registry keyed by language name. */
|
|
12
|
+
readonly resolvers: CapabilityRegistry<TestPathResolver>;
|
|
10
13
|
|
|
11
14
|
constructor() {
|
|
12
15
|
this.evaluators = new CapabilityRegistry<RuleEvaluator>('evaluator');
|
|
13
16
|
this.formatters = new CapabilityRegistry<ResultFormatter>('formatter');
|
|
17
|
+
this.resolvers = new CapabilityRegistry<TestPathResolver>('resolver');
|
|
14
18
|
}
|
|
15
19
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
export * from './config/extensions';
|
|
1
2
|
export * from './config/loader';
|
|
2
3
|
export * from './engine';
|
|
4
|
+
export * from './fixers/fixers';
|
|
5
|
+
export * from './fixers/test-stub-fixer';
|
|
3
6
|
export * from './formatters/json';
|
|
4
7
|
export * from './formatters/text';
|
|
5
8
|
export * from './host/capability-registry';
|
|
6
9
|
export * from './host/rule-engine-host';
|
|
10
|
+
export * from './resolvers/test-path-resolver';
|
|
7
11
|
export * from './types';
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pluggable test-path resolution for the test-location evaluator.
|
|
3
|
+
*
|
|
4
|
+
* Each implementation maps a source file path to its conventional test file path
|
|
5
|
+
* for one language, so the same evaluator works across TypeScript, Python, Go, and
|
|
6
|
+
* Rust projects. Resolvers are registered on the host and selected per rule via
|
|
7
|
+
* `evaluator.config.resolver`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Metadata about an exported symbol, used when generating a test skeleton. */
|
|
11
|
+
export interface ExportInfo {
|
|
12
|
+
/** Symbol name. */
|
|
13
|
+
readonly name: string;
|
|
14
|
+
/** Declaration kind. */
|
|
15
|
+
readonly kind: 'function' | 'class' | 'const' | 'type' | 'interface' | 'unknown';
|
|
16
|
+
/** One-based source line, when known. */
|
|
17
|
+
readonly line?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Maps source files to expected test files for a project type. */
|
|
21
|
+
export interface TestPathResolver {
|
|
22
|
+
/** Language name this resolver handles (registry key). */
|
|
23
|
+
readonly name: string;
|
|
24
|
+
/** Compute the expected test file path for a source file. */
|
|
25
|
+
resolveTestPath(srcRelPath: string): string;
|
|
26
|
+
/** Optionally generate a test skeleton for a source file. */
|
|
27
|
+
generateSkeleton?(srcRelPath: string, exports: ExportInfo[]): string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* TypeScript conventions:
|
|
32
|
+
* src/foo/bar.ts → tests/foo/bar.test.ts
|
|
33
|
+
* packages/core/src/foo/bar.ts → packages/core/tests/foo/bar.test.ts
|
|
34
|
+
*/
|
|
35
|
+
export class TypeScriptTestPathResolver implements TestPathResolver {
|
|
36
|
+
/** Registry key. */
|
|
37
|
+
readonly name = 'typescript';
|
|
38
|
+
|
|
39
|
+
constructor() {}
|
|
40
|
+
|
|
41
|
+
/** Map a TS/JS source path to its `tests/…test.ts` counterpart. */
|
|
42
|
+
resolveTestPath(srcRelPath: string): string {
|
|
43
|
+
if (srcRelPath.includes('.test.') || srcRelPath.includes('.spec.')) return srcRelPath;
|
|
44
|
+
const srcIdx = srcRelPath.indexOf('/src/');
|
|
45
|
+
if (srcIdx !== -1) {
|
|
46
|
+
const pkg = srcRelPath.slice(0, srcIdx);
|
|
47
|
+
const rel = srcRelPath.slice(srcIdx + '/src/'.length).replace(/\.(ts|tsx|js|jsx)$/, '.test.ts');
|
|
48
|
+
return `${pkg}/tests/${rel}`;
|
|
49
|
+
}
|
|
50
|
+
const withoutExt = srcRelPath.replace(/\.(ts|tsx|js|jsx)$/, '');
|
|
51
|
+
return `tests/${withoutExt.replace(/^src\//, '')}.test.ts`;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Python conventions (pytest):
|
|
57
|
+
* src/foo/bar.py → tests/foo/test_bar.py
|
|
58
|
+
*/
|
|
59
|
+
export class PythonTestPathResolver implements TestPathResolver {
|
|
60
|
+
/** Registry key. */
|
|
61
|
+
readonly name = 'python';
|
|
62
|
+
|
|
63
|
+
constructor() {}
|
|
64
|
+
|
|
65
|
+
/** Map a Python source path to its `tests/…/test_*.py` counterpart. */
|
|
66
|
+
resolveTestPath(srcRelPath: string): string {
|
|
67
|
+
if (!srcRelPath) throw new Error('empty source path');
|
|
68
|
+
if (srcRelPath.endsWith('_test.py') || srcRelPath.includes('/test_') || srcRelPath.startsWith('test_')) {
|
|
69
|
+
return srcRelPath;
|
|
70
|
+
}
|
|
71
|
+
if (srcRelPath.startsWith('tests/')) return srcRelPath;
|
|
72
|
+
if (!srcRelPath.endsWith('.py')) throw new Error(`unsupported extension for python resolver: ${srcRelPath}`);
|
|
73
|
+
const srcIdx = srcRelPath.indexOf('/src/');
|
|
74
|
+
if (srcIdx !== -1) {
|
|
75
|
+
const pkg = srcRelPath.slice(0, srcIdx);
|
|
76
|
+
return `${pkg}/tests/${testify(srcRelPath.slice(srcIdx + '/src/'.length))}`;
|
|
77
|
+
}
|
|
78
|
+
if (srcRelPath.startsWith('src/')) return `tests/${testify(srcRelPath.slice(4))}`;
|
|
79
|
+
return `tests/${testify(srcRelPath)}`;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Go conventions:
|
|
85
|
+
* foo/bar.go → foo/bar_test.go (sibling)
|
|
86
|
+
*/
|
|
87
|
+
export class GoTestPathResolver implements TestPathResolver {
|
|
88
|
+
/** Registry key. */
|
|
89
|
+
readonly name = 'go';
|
|
90
|
+
|
|
91
|
+
constructor() {}
|
|
92
|
+
|
|
93
|
+
/** Map a Go source path to its sibling `_test.go` file. */
|
|
94
|
+
resolveTestPath(srcRelPath: string): string {
|
|
95
|
+
if (!srcRelPath) throw new Error('empty source path');
|
|
96
|
+
if (srcRelPath.endsWith('_test.go')) return srcRelPath;
|
|
97
|
+
if (!srcRelPath.endsWith('.go')) throw new Error(`unsupported extension for go resolver: ${srcRelPath}`);
|
|
98
|
+
return srcRelPath.replace(/\.go$/, '_test.go');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Rust conventions (Cargo integration tests):
|
|
104
|
+
* crate/src/foo.rs → crate/tests/foo.rs
|
|
105
|
+
*/
|
|
106
|
+
export class RustTestPathResolver implements TestPathResolver {
|
|
107
|
+
/** Registry key. */
|
|
108
|
+
readonly name = 'rust';
|
|
109
|
+
|
|
110
|
+
constructor() {}
|
|
111
|
+
|
|
112
|
+
/** Map a Rust source path to its `tests/` integration-test counterpart. */
|
|
113
|
+
resolveTestPath(srcRelPath: string): string {
|
|
114
|
+
if (!srcRelPath) throw new Error('empty source path');
|
|
115
|
+
if (srcRelPath.startsWith('tests/') || srcRelPath.includes('/tests/')) return srcRelPath;
|
|
116
|
+
if (!srcRelPath.endsWith('.rs')) throw new Error(`unsupported extension for rust resolver: ${srcRelPath}`);
|
|
117
|
+
const srcIdx = srcRelPath.indexOf('/src/');
|
|
118
|
+
if (srcIdx !== -1) {
|
|
119
|
+
const crate = srcRelPath.slice(0, srcIdx);
|
|
120
|
+
return `${crate}/tests/${srcRelPath.slice(srcIdx + '/src/'.length)}`;
|
|
121
|
+
}
|
|
122
|
+
if (srcRelPath.startsWith('src/')) return `tests/${srcRelPath.slice(4)}`;
|
|
123
|
+
return `tests/${srcRelPath}`;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Prefix the basename of a Python source path with `test_`. */
|
|
128
|
+
function testify(rel: string): string {
|
|
129
|
+
const lastSlash = rel.lastIndexOf('/');
|
|
130
|
+
const dir = lastSlash >= 0 ? rel.slice(0, lastSlash + 1) : '';
|
|
131
|
+
const base = lastSlash >= 0 ? rel.slice(lastSlash + 1) : rel;
|
|
132
|
+
return `${dir}test_${base}`;
|
|
133
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -56,6 +56,18 @@ export interface ConstraintRuleFile {
|
|
|
56
56
|
rules: ConstraintRule[];
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
/** Relative module paths a preset contributes per capability kind. */
|
|
60
|
+
export interface PresetExtensions {
|
|
61
|
+
/** Test-path resolver module paths. */
|
|
62
|
+
resolvers?: string[];
|
|
63
|
+
/** Evaluator module paths. */
|
|
64
|
+
evaluators?: string[];
|
|
65
|
+
/** Fixer module paths. */
|
|
66
|
+
fixers?: string[];
|
|
67
|
+
/** Formatter module paths. */
|
|
68
|
+
formatters?: string[];
|
|
69
|
+
}
|
|
70
|
+
|
|
59
71
|
/** Preset definition that composes category folders or other presets. */
|
|
60
72
|
export interface PresetDefinition {
|
|
61
73
|
/** Preset name. */
|
|
@@ -66,6 +78,8 @@ export interface PresetDefinition {
|
|
|
66
78
|
disable?: string[];
|
|
67
79
|
/** Per-rule overrides. */
|
|
68
80
|
overrides?: Record<string, { fix?: { mode: FixMode } }>;
|
|
81
|
+
/** Custom capability modules contributed by this preset (opt-in to load). */
|
|
82
|
+
extensions?: PresetExtensions;
|
|
69
83
|
}
|
|
70
84
|
|
|
71
85
|
/** Candidate fix emitted by an evaluator or fixer. */
|
|
@@ -84,6 +98,16 @@ export interface Fix {
|
|
|
84
98
|
mode: Exclude<FixMode, 'none'>;
|
|
85
99
|
}
|
|
86
100
|
|
|
101
|
+
/**
|
|
102
|
+
* What a finding represents.
|
|
103
|
+
*
|
|
104
|
+
* - `violation`: the rule ran and the project breached its policy (the default).
|
|
105
|
+
* - `error`: the rule could not run — a misconfiguration or runtime fault in the
|
|
106
|
+
* evaluator itself. These are not policy breaches and callers may surface them
|
|
107
|
+
* separately (e.g. "rule misconfigured") rather than as project violations.
|
|
108
|
+
*/
|
|
109
|
+
export type FindingKind = 'violation' | 'error';
|
|
110
|
+
|
|
87
111
|
/** Finding emitted by a constraint rule. */
|
|
88
112
|
export interface ConstraintFinding {
|
|
89
113
|
/** Rule identifier. */
|
|
@@ -100,6 +124,8 @@ export interface ConstraintFinding {
|
|
|
100
124
|
column?: number;
|
|
101
125
|
/** Machine-readable evaluator/source code. */
|
|
102
126
|
code?: string;
|
|
127
|
+
/** Whether this is a policy violation or an evaluator error. Absent means `violation`. */
|
|
128
|
+
kind?: FindingKind;
|
|
103
129
|
}
|
|
104
130
|
|
|
105
131
|
/** Aggregate result returned by a rule evaluator. */
|
|
@@ -194,4 +220,12 @@ export const PresetDefinitionSchema = z.object({
|
|
|
194
220
|
overrides: z
|
|
195
221
|
.record(z.string(), z.object({ fix: z.object({ mode: z.enum(['none', 'suggest', 'auto']) }).optional() }))
|
|
196
222
|
.optional(),
|
|
223
|
+
extensions: z
|
|
224
|
+
.object({
|
|
225
|
+
resolvers: z.array(z.string()).optional(),
|
|
226
|
+
evaluators: z.array(z.string()).optional(),
|
|
227
|
+
fixers: z.array(z.string()).optional(),
|
|
228
|
+
formatters: z.array(z.string()).optional(),
|
|
229
|
+
})
|
|
230
|
+
.optional(),
|
|
197
231
|
});
|