@gobing-ai/ts-rule-engine 0.2.6 → 0.2.8

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 (80) hide show
  1. package/README.md +563 -1
  2. package/dist/config/extensions.d.ts +48 -0
  3. package/dist/config/extensions.d.ts.map +1 -0
  4. package/dist/config/extensions.js +67 -0
  5. package/dist/config/loader.d.ts +20 -1
  6. package/dist/config/loader.d.ts.map +1 -1
  7. package/dist/config/loader.js +52 -26
  8. package/dist/engine.d.ts +26 -1
  9. package/dist/engine.d.ts.map +1 -1
  10. package/dist/engine.js +79 -0
  11. package/dist/evaluators/exit-code-evaluator.d.ts +1 -1
  12. package/dist/evaluators/exit-code-evaluator.d.ts.map +1 -1
  13. package/dist/evaluators/exit-code-evaluator.js +22 -9
  14. package/dist/evaluators/forbidden-import-evaluator.d.ts +16 -3
  15. package/dist/evaluators/forbidden-import-evaluator.d.ts.map +1 -1
  16. package/dist/evaluators/forbidden-import-evaluator.js +71 -6
  17. package/dist/evaluators/import-boundary-evaluator.d.ts +19 -0
  18. package/dist/evaluators/import-boundary-evaluator.d.ts.map +1 -0
  19. package/dist/evaluators/import-boundary-evaluator.js +85 -0
  20. package/dist/evaluators/path-evaluator.d.ts +15 -2
  21. package/dist/evaluators/path-evaluator.d.ts.map +1 -1
  22. package/dist/evaluators/path-evaluator.js +49 -3
  23. package/dist/evaluators/regex-evaluator.d.ts.map +1 -1
  24. package/dist/evaluators/regex-evaluator.js +43 -8
  25. package/dist/evaluators/schema-artifact-evaluator.d.ts +21 -0
  26. package/dist/evaluators/schema-artifact-evaluator.d.ts.map +1 -0
  27. package/dist/evaluators/schema-artifact-evaluator.js +102 -0
  28. package/dist/evaluators/secrets-scanner-evaluator.d.ts +13 -2
  29. package/dist/evaluators/secrets-scanner-evaluator.d.ts.map +1 -1
  30. package/dist/evaluators/secrets-scanner-evaluator.js +72 -9
  31. package/dist/evaluators/sg-evaluator.d.ts +19 -0
  32. package/dist/evaluators/sg-evaluator.d.ts.map +1 -0
  33. package/dist/evaluators/sg-evaluator.js +112 -0
  34. package/dist/evaluators/test-location-evaluator.d.ts +14 -1
  35. package/dist/evaluators/test-location-evaluator.d.ts.map +1 -1
  36. package/dist/evaluators/test-location-evaluator.js +42 -22
  37. package/dist/evaluators/tsdoc-export-evaluator.js +19 -5
  38. package/dist/fixers/fixers.d.ts +86 -0
  39. package/dist/fixers/fixers.d.ts.map +1 -0
  40. package/dist/fixers/fixers.js +230 -0
  41. package/dist/fixers/test-stub-fixer.d.ts +49 -0
  42. package/dist/fixers/test-stub-fixer.d.ts.map +1 -0
  43. package/dist/fixers/test-stub-fixer.js +91 -0
  44. package/dist/host/builtins.d.ts.map +1 -1
  45. package/dist/host/builtins.js +12 -1
  46. package/dist/host/rule-engine-host.d.ts +3 -0
  47. package/dist/host/rule-engine-host.d.ts.map +1 -1
  48. package/dist/host/rule-engine-host.js +3 -0
  49. package/dist/index.d.ts +4 -0
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +4 -0
  52. package/dist/resolvers/test-path-resolver.d.ts +72 -0
  53. package/dist/resolvers/test-path-resolver.d.ts.map +1 -0
  54. package/dist/resolvers/test-path-resolver.js +112 -0
  55. package/dist/types.d.ts +36 -0
  56. package/dist/types.d.ts.map +1 -1
  57. package/dist/types.js +10 -0
  58. package/package.json +4 -3
  59. package/schemas/preset.schema.json +40 -0
  60. package/schemas/rule-file.schema.json +49 -0
  61. package/src/config/extensions.ts +115 -0
  62. package/src/config/loader.ts +81 -25
  63. package/src/engine.ts +99 -2
  64. package/src/evaluators/exit-code-evaluator.ts +27 -9
  65. package/src/evaluators/forbidden-import-evaluator.ts +101 -7
  66. package/src/evaluators/import-boundary-evaluator.ts +135 -0
  67. package/src/evaluators/path-evaluator.ts +66 -3
  68. package/src/evaluators/regex-evaluator.ts +53 -12
  69. package/src/evaluators/schema-artifact-evaluator.ts +134 -0
  70. package/src/evaluators/secrets-scanner-evaluator.ts +89 -11
  71. package/src/evaluators/sg-evaluator.ts +133 -0
  72. package/src/evaluators/test-location-evaluator.ts +47 -35
  73. package/src/evaluators/tsdoc-export-evaluator.ts +19 -5
  74. package/src/fixers/fixers.ts +294 -0
  75. package/src/fixers/test-stub-fixer.ts +118 -0
  76. package/src/host/builtins.ts +17 -1
  77. package/src/host/rule-engine-host.ts +4 -0
  78. package/src/index.ts +4 -0
  79. package/src/resolvers/test-path-resolver.ts +133 -0
  80. package/src/types.ts +40 -0
@@ -1,3 +1,5 @@
1
+ import type { CapabilityRegistry } from '../host/capability-registry';
2
+ import type { TestPathResolver } from '../resolvers/test-path-resolver';
1
3
  import {
2
4
  type ConstraintRule,
3
5
  createFinding,
@@ -12,6 +14,7 @@ interface TestLocationConfig {
12
14
  expected?: string;
13
15
  forbid?: string[];
14
16
  requireCorrespondingTest?: boolean;
17
+ resolver?: string;
15
18
  }
16
19
 
17
20
  /**
@@ -22,12 +25,16 @@ interface TestLocationConfig {
22
25
  * - `expected`: glob the test files must match (required)
23
26
  * - `forbid`: globs where tests must not live (e.g. `**\/__tests__/**`)
24
27
  * - `requireCorrespondingTest`: when true, flags source files (from `rule.include`)
25
- * that lack a test at the TypeScript-conventional path
28
+ * that lack a test at the resolver's conventional path
29
+ * - `resolver`: language resolver name (`typescript` default, or `python`/`go`/`rust`)
26
30
  *
27
31
  * Discovery walks the workdir and applies `**` globs precisely, so it stays
28
32
  * self-contained (no `rg --files` shell-out).
29
33
  */
30
34
  export class TestLocationEvaluator implements RuleEvaluator {
35
+ /** Optional resolver registry; when absent, the TypeScript convention is used. */
36
+ constructor(private readonly resolvers?: CapabilityRegistry<TestPathResolver>) {}
37
+
31
38
  /** Evaluate test-file placement and optional coverage of source files. */
32
39
  async evaluate(rule: ConstraintRule, context: RuleContext): Promise<RuleEvaluationResult> {
33
40
  const config = (rule.evaluator.config ?? {}) as TestLocationConfig;
@@ -49,20 +56,15 @@ export class TestLocationEvaluator implements RuleEvaluator {
49
56
  const violated = forbid.find((pattern) => matchesGlob(file, pattern));
50
57
  if (violated !== undefined) {
51
58
  findings.push(
52
- createFinding(
53
- rule,
54
- `Test file "${file}" is in a forbidden location (matches "${violated}")`,
55
- file,
56
- {
57
- code: 'test-location:forbidden',
58
- },
59
- ),
59
+ createFinding(rule, `test file in forbidden location (matches "${violated}")`, file, {
60
+ code: 'test-location:forbidden',
61
+ }),
60
62
  );
61
63
  continue;
62
64
  }
63
65
  if (!matchesGlob(file, expected)) {
64
66
  findings.push(
65
- createFinding(rule, `Test file "${file}" does not match expected pattern "${expected}"`, file, {
67
+ createFinding(rule, `test file outside expected location (expected "${expected}")`, file, {
66
68
  code: 'test-location:unexpected',
67
69
  }),
68
70
  );
@@ -70,23 +72,19 @@ export class TestLocationEvaluator implements RuleEvaluator {
70
72
  }
71
73
 
72
74
  if (config.requireCorrespondingTest) {
75
+ const resolver = this.selectResolver(config.resolver);
73
76
  const srcPatterns = rule.include ?? ['**/*.ts', '**/*.tsx'];
74
77
  const testSet = new Set(testFiles);
75
78
  for (const srcFile of allFiles) {
76
79
  if (!srcPatterns.some((pattern) => matchesGlob(srcFile, pattern))) continue;
77
80
  if (exclude.some((pattern) => matchesGlob(srcFile, pattern))) continue;
78
- const testPath = resolveTestPath(srcFile);
81
+ const testPath = resolver.resolveTestPath(srcFile);
79
82
  if (testPath === srcFile) continue;
80
83
  if (!testSet.has(testPath)) {
81
84
  findings.push(
82
- createFinding(
83
- rule,
84
- `Source file "${srcFile}" has no corresponding test → ${testPath}`,
85
- srcFile,
86
- {
87
- code: 'test-location:missing',
88
- },
89
- ),
85
+ createFinding(rule, `no corresponding test → ${testPath}`, srcFile, {
86
+ code: 'test-location:missing',
87
+ }),
90
88
  );
91
89
  }
92
90
  }
@@ -94,22 +92,36 @@ export class TestLocationEvaluator implements RuleEvaluator {
94
92
 
95
93
  return { findings, fixes: [] };
96
94
  }
97
- }
98
95
 
99
- /**
100
- * Map a TypeScript source path to its conventional test path.
101
- *
102
- * packages/core/src/foo/bar.ts packages/core/tests/foo/bar.test.ts
103
- * src/foo/bar.ts → tests/foo/bar.test.ts
104
- */
105
- function resolveTestPath(srcRelPath: string): string {
106
- if (srcRelPath.includes('.test.') || srcRelPath.includes('.spec.')) return srcRelPath;
107
- const srcIdx = srcRelPath.indexOf('/src/');
108
- if (srcIdx !== -1) {
109
- const pkg = srcRelPath.slice(0, srcIdx);
110
- const rel = srcRelPath.slice(srcIdx + '/src/'.length).replace(/\.(ts|tsx|js|jsx)$/, '.test.ts');
111
- return `${pkg}/tests/${rel}`;
96
+ /**
97
+ * Pick the resolver named in config (default `typescript`).
98
+ *
99
+ * Falls back to the built-in TypeScript convention when no registry was
100
+ * injected; throws if a named resolver is requested but not registered.
101
+ */
102
+ private selectResolver(name = 'typescript'): TestPathResolver {
103
+ if (this.resolvers === undefined) {
104
+ if (name !== 'typescript') {
105
+ throw new Error(`test-location resolver "${name}" requested but no resolver registry is available`);
106
+ }
107
+ return TYPESCRIPT_FALLBACK;
108
+ }
109
+ return this.resolvers.get(name);
112
110
  }
113
- const withoutExt = srcRelPath.replace(/\.(ts|tsx|js|jsx)$/, '');
114
- return `tests/${withoutExt.replace(/^src\//, '')}.test.ts`;
115
111
  }
112
+
113
+ /** Built-in TypeScript convention used when no resolver registry is injected. */
114
+ const TYPESCRIPT_FALLBACK: TestPathResolver = {
115
+ name: 'typescript',
116
+ resolveTestPath(srcRelPath: string): string {
117
+ if (srcRelPath.includes('.test.') || srcRelPath.includes('.spec.')) return srcRelPath;
118
+ const srcIdx = srcRelPath.indexOf('/src/');
119
+ if (srcIdx !== -1) {
120
+ const pkg = srcRelPath.slice(0, srcIdx);
121
+ const rel = srcRelPath.slice(srcIdx + '/src/'.length).replace(/\.(ts|tsx|js|jsx)$/, '.test.ts');
122
+ return `${pkg}/tests/${rel}`;
123
+ }
124
+ const withoutExt = srcRelPath.replace(/\.(ts|tsx|js|jsx)$/, '');
125
+ return `tests/${withoutExt.replace(/^src\//, '')}.test.ts`;
126
+ },
127
+ };
@@ -20,8 +20,8 @@ interface ExportSite {
20
20
  }
21
21
 
22
22
  const KIND_PATTERN: Record<ExportKind, RegExp> = {
23
- function: /^export\s+(?:async\s+)?function\s+([A-Za-z0-9_$]+)/,
24
- class: /^export\s+(?:abstract\s+)?class\s+([A-Za-z0-9_$]+)/,
23
+ function: /^export\s+(?:default\s+)?(?:async\s+)?function\s*\*?\s+([A-Za-z0-9_$]+)/,
24
+ class: /^export\s+(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z0-9_$]+)/,
25
25
  interface: /^export\s+interface\s+([A-Za-z0-9_$]+)/,
26
26
  type: /^export\s+type\s+([A-Za-z0-9_$]+)/,
27
27
  const: /^export\s+const\s+([A-Za-z0-9_$]+)/,
@@ -90,8 +90,22 @@ function findExports(lines: string[], requested: ReadonlySet<ExportKind>): Expor
90
90
  return sites;
91
91
  }
92
92
 
93
- /** True when the line immediately above a declaration closes a JSDoc block. */
93
+ /**
94
+ * True when a JSDoc block precedes a declaration.
95
+ *
96
+ * Skips decorator lines (`@Component(...)`) so a documented but decorated class
97
+ * is not falsely flagged, then checks whether the nearest preceding non-decorator
98
+ * line closes (or is) a JSDoc comment.
99
+ */
94
100
  function precededByJsdoc(lines: string[], declarationLine: number): boolean {
95
- const prev = lines[declarationLine - 2]?.trim();
96
- return prev !== undefined && (prev.endsWith('*/') || prev.startsWith('/**'));
101
+ let cursor = declarationLine - 2; // zero-based line above the declaration
102
+ while (cursor >= 0) {
103
+ const prev = lines[cursor]?.trim() ?? '';
104
+ if (prev.startsWith('@')) {
105
+ cursor -= 1; // decorator — keep walking up
106
+ continue;
107
+ }
108
+ return prev.endsWith('*/') || prev.startsWith('/**');
109
+ }
110
+ return false;
97
111
  }
@@ -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
+ }
@@ -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.evaluators.register('test-location', new TestLocationEvaluator(), 'builtin');
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';