@skathio/somi 5.1.1 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.copilot-extension/extension.json +1 -1
- package/.copilot-extension/marketplace.json +1 -1
- package/README.md +13 -5
- package/VERSION +1 -1
- package/agents/somi-reviewer.md +1 -1
- package/agents/somi-security-reviewer.md +1 -1
- package/commands/somi-deliver.md +1 -1
- package/commands/somi.md +2 -2
- package/hooks/pre-tool/apply-tier.mjs +12 -6
- package/package.json +1 -2
- package/rules/digest.md +6 -0
- package/scripts/lib/advisor.mjs +34 -10
- package/scripts/lib/chat-commands.mjs +65 -0
- package/scripts/lib/git-tree.mjs +32 -8
- package/scripts/lib/pr.mjs +2 -2
- package/scripts/lib/quality/clones.mjs +113 -26
- package/scripts/lib/quality/coupling.mjs +115 -0
- package/scripts/lib/quality/exports.mjs +33 -0
- package/scripts/lib/quality/findings.mjs +18 -0
- package/scripts/lib/quality/functions.mjs +71 -0
- package/scripts/lib/quality/gate.mjs +134 -144
- package/scripts/lib/quality/imports.mjs +88 -0
- package/scripts/lib/quality/js-source.mjs +55 -0
- package/scripts/lib/quality/limits.mjs +102 -23
- package/scripts/lib/quality/metrics.mjs +65 -16
- package/scripts/lib/quality/parse.mjs +16 -11
- package/scripts/lib/quality/path-aliases.mjs +36 -0
- package/scripts/lib/quality/python-exports.mjs +31 -0
- package/scripts/lib/quality/python-findings.mjs +82 -0
- package/scripts/lib/quality/python-imports.mjs +64 -0
- package/scripts/lib/quality/python.mjs +50 -0
- package/scripts/lib/quality/repo.mjs +31 -12
- package/scripts/lib/quality/run.mjs +2 -2
- package/scripts/lib/quality/slop.mjs +168 -0
- package/scripts/lib/quality/suppressions.mjs +38 -0
- package/scripts/lib/quality/totals.mjs +39 -0
- package/scripts/lib/reviews.mjs +10 -6
- package/scripts/lib/views.mjs +3 -1
- package/scripts/lib/workflows.mjs +22 -1
- package/scripts/somi-mcp.mjs +7 -2
- package/scripts/somi.mjs +7 -5
- package/scripts/vendor/tree-sitter/LICENSE.tree-sitter-python +21 -0
- package/scripts/vendor/tree-sitter/manifest.json +11 -1
- package/scripts/vendor/tree-sitter/tree-sitter-python.wasm +0 -0
- package/workflows/deliver-stages.js +357 -46
|
@@ -2,133 +2,76 @@
|
|
|
2
2
|
// so an old codebase is not failed on day one: a change may not take a function or a file over a limit, and a file may not gain more
|
|
3
3
|
// complexity in one change than its per-change limit, which is what stops a function being split apart just to pass. A function that
|
|
4
4
|
// was already over and got worse is reported as a warning. Copied code, stylesheet rules and newly added suppressions are checked in
|
|
5
|
-
// what the change added. A change the parser cannot follow fails, because a change that cannot be measured must not pass as clean.
|
|
5
|
+
// what the change added, and so are Python's leftover debugging, swallowed errors and exports nothing imports. A change the parser cannot follow fails, because a change that cannot be measured must not pass as clean.
|
|
6
6
|
|
|
7
7
|
import crypto from 'node:crypto';
|
|
8
8
|
import { TEST_FILE } from '../signals.mjs';
|
|
9
|
-
import { addedRanges, filesAt } from '../git-tree.mjs';
|
|
9
|
+
import { addedRanges, filesAt, oldLine, renamedFiles } from '../git-tree.mjs';
|
|
10
10
|
import { findClones, tokensOf } from './clones.mjs';
|
|
11
|
+
import { scoreCoupling } from './coupling.mjs';
|
|
12
|
+
import { aliasesFrom } from './path-aliases.mjs';
|
|
13
|
+
import { exportsAdded } from './exports.mjs';
|
|
11
14
|
import { cssRules } from './css.mjs';
|
|
12
|
-
import {
|
|
15
|
+
import { report, overlaps } from './findings.mjs';
|
|
16
|
+
import { pairUnits, scoreUnit } from './functions.mjs';
|
|
17
|
+
import { codeLines, unitsOf, topLevelCognitive } from './metrics.mjs';
|
|
13
18
|
import { languageOf, parseSource } from './parse.mjs';
|
|
19
|
+
import { scorePython, scoreUnusedExports } from './python.mjs';
|
|
20
|
+
import { scoreSlop } from './slop.mjs';
|
|
21
|
+
import { scoreComments, scoreLines } from './suppressions.mjs';
|
|
22
|
+
import { keyOf, scoreTotals } from './totals.mjs';
|
|
23
|
+
|
|
24
|
+
export { exemption, METRICS, MAX_EXEMPTION_DAYS } from './functions.mjs';
|
|
25
|
+
export { scoreComments } from './suppressions.mjs';
|
|
14
26
|
|
|
15
27
|
// Code that is not the product: dependencies, build output, test data, and docs, examples and playgrounds, which are written to be
|
|
16
28
|
// read once.
|
|
17
29
|
const SKIPPED = /(^|\/)(node_modules|vendor|dist|build|coverage|\.next|\.somi|fixtures?|__fixtures__|testdata|test-data|docs?|examples?|demos?|playgrounds?)\//;
|
|
18
30
|
const MINIFIED = /\.min\.(js|css)$/;
|
|
19
31
|
const GENERATED = /@generated\b|Code generated .* DO NOT EDIT/;
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
// shortcut. Outside a benchmark it passes.
|
|
23
|
-
const REASONED = /eslint-disable[^\n]*\s--\s+\S.{8,}|@ts-(expect-error|ignore)\s*:?\s+\S.{8,}|stylelint-disable[^\n]*\s--\s+\S.{8,}/;
|
|
24
|
-
const ALLOW = /somi-gate-allow\s+([a-z_-]+)\s+reason="([^"]{20,})"\s+expires=(\d{4}-\d{2}-\d{2})/;
|
|
25
|
-
export const MAX_EXEMPTION_DAYS = 90;
|
|
26
|
-
export const METRICS = ['cognitive', 'depth', 'lines', 'params'];
|
|
32
|
+
// Source files in a language the gate has no grammar for. A change made only of these passes with nothing scored, so it says so.
|
|
33
|
+
const UNCOVERED = /\.(go|rs|java|kt|kts|rb|php|swift|scala|c|cc|cpp|cxx|h|hpp|m|mm|dart|lua|ex|exs|clj|fs|vb|sh|ps1|sql|vue|svelte)$/i;
|
|
27
34
|
export const JS_FAMILY = new Set(['javascript', 'typescript', 'tsx']);
|
|
35
|
+
// Copies are compared within one family of languages: JavaScript with TypeScript, C# with C#, and Python with Python.
|
|
36
|
+
const FAMILIES = { 'c-sharp': 'cs', python: 'py' };
|
|
37
|
+
export const familyOf = (language) => (JS_FAMILY.has(language) ? 'js' : FAMILIES[language] ?? null);
|
|
28
38
|
const MAX_REPO_FILES = 3000;
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
39
|
+
const MAX_GRAPH_FILES = 10000;
|
|
40
|
+
export const TOO_DEEP = 'nested too deeply to measure';
|
|
41
|
+
|
|
42
|
+
const touches = (unit, ranges) => overlaps(ranges, unit.start, unit.end);
|
|
43
|
+
// The review signals' test pattern, and two more the calibration found: .NET test projects (src/UnitTests/, Foo.Tests/) and a file named
|
|
44
|
+
// test.ts beside the code it tests.
|
|
45
|
+
const MORE_TESTS = /(^|\/)[^/]*Tests?\/|Tests?\.cs$|(^|\/)(test|spec)\.[^/]+$/;
|
|
46
|
+
export const isTest = (file) => TEST_FILE.test(file) || MORE_TESTS.test(file);
|
|
47
|
+
/** Why a file is not scored: its folder, a minified name, or a generated marker in its first lines. Null when it is scored. */
|
|
48
|
+
function skipReason(file, text) {
|
|
49
|
+
if (SKIPPED.test(file)) return 'folder';
|
|
50
|
+
if (MINIFIED.test(file)) return 'minified';
|
|
51
|
+
return GENERATED.test(text.split('\n').slice(0, 5).join('\n')) ? 'generated' : null;
|
|
52
|
+
}
|
|
53
|
+
export const skipped = (file, text) => skipReason(file, text) !== null;
|
|
33
54
|
export const total = (units, top) => units.reduce((s, u) => s + u.cognitive, 0) + top;
|
|
55
|
+
const totalsOf = (tree, units) => ({ cognitive: total(units, topLevelCognitive(tree)), lines: codeLines(tree), functions: units.length });
|
|
34
56
|
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
return { reason: m[2], expires: m[3] };
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// A function is paired with its old version by name and signature first, so a new overload added above an old one is new, not the
|
|
47
|
-
// old one got different. What is left is paired by name alone, so a function whose parameters changed is still the same function.
|
|
48
|
-
function pairUnits(before, after) {
|
|
49
|
-
const taken = new Set();
|
|
50
|
-
const match = (u, key) => {
|
|
51
|
-
const old = before.find((b) => !taken.has(b) && key(b) === key(u));
|
|
52
|
-
if (old) taken.add(old);
|
|
53
|
-
return old ?? null;
|
|
54
|
-
};
|
|
55
|
-
const exact = after.map((u) => match(u, (x) => `${x.kind}:${x.name}:${x.signature}`));
|
|
56
|
-
return after.map((u, i) => ({ after: u, before: exact[i] ?? match(u, (x) => `${x.kind}:${x.name}`) }));
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
const inAdded = (added, line) => added.some(([a, b]) => line >= a && line <= b);
|
|
60
|
-
const flag = (ctx, v) => ctx.violations.push(v);
|
|
61
|
-
|
|
62
|
-
// Comments the change added: a new suppression is a violation, and in a benchmark so is an exemption the agent wrote. Only comments
|
|
63
|
-
// count, so a string that mentions eslint-disable is not one.
|
|
64
|
-
function scoreComment(ctx, file, line, text) {
|
|
65
|
-
if (SUPPRESSION.test(text) && (ctx.mode === 'benchmark' || !REASONED.test(text))) flag(ctx, { rule: 'suppression', file, line, value: 1, limit: ctx.limits.suppressions.added });
|
|
66
|
-
if (ctx.mode === 'benchmark' && /somi-gate-allow/.test(text)) flag(ctx, { rule: 'exemption', file, line, value: 1, limit: 0 });
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// A directive opens its comment: // eslint-disable-next-line, /* @ts-nocheck */. A comment that only mentions one is prose.
|
|
70
|
-
const DIRECTIVE = /^(\/\/|\/\*+|#)\s*(eslint-disable|@ts-ignore|@ts-expect-error|@ts-nocheck|NOSONAR|nolint|stylelint-disable|istanbul ignore|c8 ignore|somi-gate-allow)/;
|
|
71
|
-
|
|
72
|
-
export function scoreComments(ctx, file, tree, added) {
|
|
73
|
-
const visit = (n) => {
|
|
74
|
-
if (n.type === 'comment') { if (inAdded(added, n.startPosition.row + 1) && DIRECTIVE.test(n.text)) scoreComment(ctx, file, n.startPosition.row + 1, n.text); return; }
|
|
75
|
-
for (const c of n.children) visit(c);
|
|
76
|
-
};
|
|
77
|
-
visit(tree.rootNode);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// With no tree to read comments from, every added line is checked instead.
|
|
81
|
-
function scoreLines(ctx, file, lines, added) {
|
|
82
|
-
for (const [i, line] of lines.entries()) if (inAdded(added, i + 1)) scoreComment(ctx, file, i + 1, line);
|
|
57
|
+
// No skip holds in a benchmark: an agent must not pass by writing a generated marker, by putting its code under examples/, or by adding
|
|
58
|
+
// it to a file that was skipped already. Only what the change added is new there, so the old code of such a file fails nothing. In a
|
|
59
|
+
// project the skip holds, and is reported, so a person sees what was not scored.
|
|
60
|
+
function skipFile(ctx, file, text) {
|
|
61
|
+
const reason = skipReason(file, text);
|
|
62
|
+
if (!reason || ctx.mode === 'benchmark') return false;
|
|
63
|
+
ctx.skipped.push({ file, reason });
|
|
64
|
+
return true;
|
|
83
65
|
}
|
|
84
66
|
|
|
85
67
|
export function scoreCss(ctx, file, tree, added) {
|
|
86
|
-
for (const r of cssRules(tree).filter((x) => added
|
|
68
|
+
for (const r of cssRules(tree).filter((x) => overlaps(added, x.line, x.end))) {
|
|
87
69
|
for (const rule of ['nesting', 'compound', 'ids', 'important']) {
|
|
88
|
-
if (r[rule] > ctx.limits.css[rule])
|
|
70
|
+
if (r[rule] > ctx.limits.css[rule]) ctx.violations.push({ rule: `css-${rule}`, file, line: r.line, value: r[rule], limit: ctx.limits.css[rule] });
|
|
89
71
|
}
|
|
90
72
|
}
|
|
91
73
|
}
|
|
92
74
|
|
|
93
|
-
// One touched function. A change that takes it over a limit is a violation, whether it is new or was within the limit before. One that
|
|
94
|
-
// was already over and got worse is a warning: well-kept projects add a branch to a complex function every week, and SonarQube does
|
|
95
|
-
// not count that as a new issue either. The file's per-change limit still caps how much any change may add.
|
|
96
|
-
function scoreUnit(ctx, { file, lines, after, before }) {
|
|
97
|
-
ctx.scored.functions += 1;
|
|
98
|
-
for (const metric of METRICS) {
|
|
99
|
-
const limit = ctx.limits[after.kind][metric];
|
|
100
|
-
if (after[metric] <= limit || (before && after[metric] <= before[metric])) continue;
|
|
101
|
-
if (before && before[metric] > limit) { ctx.warnings.push({ rule: metric, file, line: after.start, name: after.name, value: after[metric], limit, before: before[metric] }); continue; }
|
|
102
|
-
const allowed = exemption(ctx, lines, after, metric);
|
|
103
|
-
if (allowed) ctx.exemptions.push({ rule: metric, file, line: after.start, name: after.name, ...allowed });
|
|
104
|
-
else flag(ctx, { rule: metric, file, line: after.start, name: after.name, kind: after.kind, value: after[metric], limit, ...(before ? { before: before[metric] } : {}) });
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// A change may not take a file over its limit, nor add more than the per-change limit at once, however its functions are cut up. What
|
|
109
|
-
// it moved in from another file it touched is not added, so splitting a file into modules is not refused for its size.
|
|
110
|
-
function scoreTotals(ctx, { file, now, was, moved }) {
|
|
111
|
-
if (now > ctx.limits.file.cognitive && was <= ctx.limits.file.cognitive) flag(ctx, { rule: 'file-cognitive', file, line: 1, value: now, limit: ctx.limits.file.cognitive, before: was });
|
|
112
|
-
const added = now - was - moved;
|
|
113
|
-
if (added > ctx.limits.file.added_cognitive) flag(ctx, { rule: 'file-added-cognitive', file, line: 1, value: added, limit: ctx.limits.file.added_cognitive, ...(moved > 0 ? { moved } : {}) });
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// A function's text, trimmed line by line, so the same function moved elsewhere, or indented differently, has the same key.
|
|
117
|
-
const keyOf = (lines, u) => lines.slice(u.start - 1, u.end).map((l) => l.trim()).join('\n');
|
|
118
|
-
const countOf = (keys) => keys.reduce((m, k) => m.set(k, (m.get(k) ?? 0) + 1), new Map());
|
|
119
|
-
|
|
120
|
-
// A function is moved, not added, when its file did not have it, the files the change touched did, and it occurs no more often after
|
|
121
|
-
// the change than before. A copy occurs more often, and a function changed on the way has a new key, so both still count in full.
|
|
122
|
-
function scoreMoves(ctx) {
|
|
123
|
-
const before = countOf(ctx.moves.before);
|
|
124
|
-
const after = countOf(ctx.moves.after);
|
|
125
|
-
const moved = (key) => (before.get(key) ?? 0) >= after.get(key);
|
|
126
|
-
for (const { units, own, ...totals } of ctx.totals) {
|
|
127
|
-
const credit = units.filter((u) => !own.has(u.key) && moved(u.key)).reduce((s, u) => s + u.cognitive, 0);
|
|
128
|
-
scoreTotals(ctx, { ...totals, moved: credit });
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
75
|
// A tree lives in the parser's WebAssembly memory, which the garbage collector does not free, so each one is deleted as soon as what
|
|
133
76
|
// the gate needs has been taken from it. Without that a large repository fills the memory and the runtime aborts.
|
|
134
77
|
export async function withTree(file, text, read) {
|
|
@@ -136,106 +79,153 @@ export async function withTree(file, text, read) {
|
|
|
136
79
|
try { return read(parsed); } finally { parsed?.tree?.delete(); }
|
|
137
80
|
}
|
|
138
81
|
|
|
139
|
-
const NO_VERSION = Object.freeze({ units: [], keys: [],
|
|
82
|
+
const NO_VERSION = Object.freeze({ units: [], keys: [], totals: { cognitive: 0, lines: 0, functions: 0 }, tokens: null });
|
|
140
83
|
async function previousVersion(ctx, file, status, test) {
|
|
141
84
|
const text = status.startsWith('A') ? null : ctx.before.get(file) ?? null;
|
|
142
|
-
|
|
85
|
+
// A benchmark scores a skipped file too, so its old version is read as well: only what the change added is new.
|
|
86
|
+
if (text === null || (ctx.mode !== 'benchmark' && skipped(file, text))) return NO_VERSION;
|
|
143
87
|
const lines = text.split('\n');
|
|
144
88
|
return withTree(file, text, (parsed) => {
|
|
145
89
|
if (!parsed?.tree) return NO_VERSION;
|
|
146
90
|
const units = unitsOf(parsed.tree, { file, isTest: test });
|
|
147
|
-
return { units, keys: units.map((u) => keyOf(lines, u)),
|
|
91
|
+
return { units, keys: units.map((u) => keyOf(lines, u)), totals: totalsOf(parsed.tree, units), tokens: familyOf(parsed.language) && !test ? tokensOf(parsed.tree) : null };
|
|
148
92
|
});
|
|
149
93
|
}
|
|
150
94
|
|
|
151
95
|
// A deleted file scores nothing, but what it held may have moved to another file the change touched.
|
|
152
96
|
async function recordDeleted(ctx, file, status) {
|
|
97
|
+
if (familyOf(languageOf(file)) === 'js') ctx.coupling.deleted.push(file);
|
|
153
98
|
ctx.moves.before.push(...(await previousVersion(ctx, file, status, isTest(file))).keys);
|
|
154
99
|
}
|
|
155
100
|
|
|
156
|
-
async function scoreCode(ctx, { file, status, added, lines, tree, language, errors }) {
|
|
101
|
+
async function scoreCode(ctx, { file, status, added, hunks, lines, tree, language, errors }) {
|
|
157
102
|
const test = isTest(file);
|
|
158
103
|
const units = unitsOf(tree, { file, isTest: test });
|
|
159
104
|
const old = await previousVersion(ctx, file, status, test);
|
|
160
105
|
// A function the parser could not follow is not scored, and with any such function the file's total is not trusted either.
|
|
161
106
|
const readable = (u) => !errors.some(([a, b]) => a <= u.end && b >= u.start);
|
|
162
|
-
for (const pair of pairUnits(old.units, units)) if (touches(pair.after, added) && readable(pair.after)) scoreUnit(ctx, { file, lines, ...pair });
|
|
163
|
-
const keyed = units.map((u) => ({ key: keyOf(lines, u), cognitive: u.cognitive }));
|
|
107
|
+
for (const pair of pairUnits(old.units, units, (line) => oldLine(hunks, line))) if (touches(pair.after, added) && readable(pair.after)) scoreUnit(ctx, { file, lines, ...pair });
|
|
108
|
+
const keyed = units.map((u) => ({ key: keyOf(lines, u), cognitive: u.cognitive, lines: u.lines }));
|
|
164
109
|
ctx.moves.before.push(...old.keys);
|
|
165
110
|
ctx.moves.after.push(...keyed.map((u) => u.key));
|
|
166
|
-
if (errors.length === 0) ctx.totals.push({ file, now:
|
|
111
|
+
if (errors.length === 0) ctx.totals.push({ file, now: totalsOf(tree, units), was: old.totals, units: keyed, own: new Set(old.keys) });
|
|
167
112
|
// Copies are looked for in product code. Copied setup between tests is mostly benign (Kapser and Godfrey), and it was most of the
|
|
168
113
|
// false alarms on known-good projects.
|
|
169
|
-
if (
|
|
114
|
+
if (language === 'python') scorePython(ctx, { file, tree, added, test }); else scoreSlop(ctx, { file, tree, added, language, test });
|
|
115
|
+
const family = familyOf(language);
|
|
116
|
+
if (family === 'js') ctx.coupling.touched.push(file);
|
|
117
|
+
if (family === 'js' && !test) ctx.coupling.exports.push({ file, names: exportsAdded(tree, added) });
|
|
118
|
+
if (!family || test) return;
|
|
170
119
|
const size = ctx.limits.clones.tokens;
|
|
171
|
-
ctx.cloneAfter.push({ file, tokens: tokensOf(tree), size });
|
|
172
|
-
if (old.tokens) ctx.cloneBefore.push({ file, tokens: old.tokens, size });
|
|
120
|
+
ctx.cloneAfter.push({ file, family, tokens: tokensOf(tree), size });
|
|
121
|
+
if (old.tokens) ctx.cloneBefore.push({ file, family, tokens: old.tokens, size });
|
|
173
122
|
}
|
|
174
123
|
|
|
175
|
-
async function scoreFile(ctx, file, { status, added }) {
|
|
176
|
-
if (!languageOf(file)) return;
|
|
124
|
+
async function scoreFile(ctx, file, { status, added, hunks }) {
|
|
125
|
+
if (!languageOf(file)) { if (!status.startsWith('D') && UNCOVERED.test(file)) ctx.uncovered.push(file); return; }
|
|
177
126
|
if (status.startsWith('D')) return recordDeleted(ctx, file, status);
|
|
178
127
|
const text = ctx.after.get(file) ?? null;
|
|
179
|
-
if (text === null ||
|
|
128
|
+
if (text === null || skipFile(ctx, file, text)) return;
|
|
180
129
|
const lines = text.split('\n');
|
|
181
130
|
const parsed = await parseSource(file, text);
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
131
|
+
let commented = false;
|
|
132
|
+
const mark = ctx.violations.length;
|
|
133
|
+
try {
|
|
134
|
+
if (parsed?.tree) scoreComments(ctx, file, parsed.tree, added); else scoreLines(ctx, file, lines, added);
|
|
135
|
+
commented = true;
|
|
136
|
+
await scoreParsed(ctx, { file, status, added, hunks, lines, parsed });
|
|
137
|
+
} catch (e) {
|
|
138
|
+
// Code nested deeper than the measuring walks can follow is unanalyzed, as a parse that never finished is, rather than the gate
|
|
139
|
+
// failing to run at all. Its added lines are still checked for suppressions, line by line, as when there is no tree.
|
|
140
|
+
if (!(e instanceof RangeError)) throw e;
|
|
141
|
+
if (!commented) { ctx.violations.length = mark; scoreLines(ctx, file, lines, added); }
|
|
142
|
+
ctx.unanalyzed.push({ file, reason: TOO_DEEP });
|
|
143
|
+
report(ctx, { rule: 'unanalyzed', file, line: 1, value: 1, limit: 0, reason: TOO_DEEP });
|
|
144
|
+
} finally { parsed?.tree?.delete(); }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function scoreParsed(ctx, { file, status, added, hunks, lines, parsed }) {
|
|
187
148
|
// A change the parser cannot follow cannot be measured, so it must not pass as clean. An error elsewhere in the file only stops the
|
|
188
|
-
// functions it sits in from being scored.
|
|
189
|
-
|
|
190
|
-
//
|
|
191
|
-
|
|
149
|
+
// functions it sits in from being scored. In a project this is a warning: a grammar can lag valid new syntax, and failing correct
|
|
150
|
+
// code on that would teach people to ignore the gate. In a benchmark it fails, so an agent cannot pass by writing what the gate
|
|
151
|
+
// cannot read.
|
|
152
|
+
const unreadable = parsed?.unanalyzed ?? (parsed.errors.some(([a, b]) => overlaps(added, a, b)) ? 'the parser could not follow the changed lines' : null);
|
|
192
153
|
if (unreadable) {
|
|
193
154
|
ctx.unanalyzed.push({ file, reason: unreadable });
|
|
194
|
-
|
|
195
|
-
if (ctx.mode === 'benchmark') flag(ctx, finding); else ctx.warnings.push(finding);
|
|
155
|
+
report(ctx, { rule: 'unanalyzed', file, line: 1, value: 1, limit: 0, reason: unreadable });
|
|
196
156
|
return;
|
|
197
157
|
}
|
|
198
158
|
ctx.scored.files += 1;
|
|
199
159
|
if (parsed.language === 'css') scoreCss(ctx, file, parsed.tree, added);
|
|
200
|
-
else await scoreCode(ctx, { file, status, added, lines, ...parsed });
|
|
160
|
+
else await scoreCode(ctx, { file, status, added, hunks, lines, ...parsed });
|
|
201
161
|
}
|
|
202
162
|
|
|
203
163
|
async function cachedTokens(cache, file, text) {
|
|
204
164
|
const key = cache ? `${file}\0${crypto.createHash('sha1').update(text).digest('hex')}` : null;
|
|
205
165
|
if (key && cache.has(key)) return cache.get(key);
|
|
206
|
-
|
|
166
|
+
// A file nested too deeply to walk is left out of the comparison, as one the parser could not read is.
|
|
167
|
+
const tokens = await withTree(file, text, (parsed) => { try { return parsed?.tree ? tokensOf(parsed.tree) : null; } catch (e) { if (e instanceof RangeError) return null; throw e; } });
|
|
207
168
|
if (key) cache.set(key, tokens);
|
|
208
169
|
return tokens;
|
|
209
170
|
}
|
|
210
171
|
|
|
172
|
+
// Every scored file of the families the change touched, as it is after the change: the import graph reads them, and the copy
|
|
173
|
+
// comparison the product files among them. The files the change touched come first and are always read. Past the cap the rest is not
|
|
174
|
+
// read, and the report says so, since an import from a file beyond it is not seen.
|
|
175
|
+
function repoTexts(ctx, touched) {
|
|
176
|
+
const families = new Set([...ctx.cloneAfter.map((f) => f.family), ...(ctx.coupling.touched.length ? ['js'] : [])]);
|
|
177
|
+
const wanted = ctx.repoFiles.filter((f) => families.has(familyOf(languageOf(f))) && !SKIPPED.test(f) && !MINIFIED.test(f));
|
|
178
|
+
const ordered = [...wanted.filter((f) => touched.has(f)), ...wanted.filter((f) => !touched.has(f))];
|
|
179
|
+
if (ordered.length > ctx.maxGraphFiles) ctx.warnings.push({ rule: 'coupling-scope', file: '.', line: 1, value: ordered.length, limit: ctx.maxGraphFiles });
|
|
180
|
+
return new Map([...filesAt(ctx.root, ctx.to, ordered.slice(0, ctx.maxGraphFiles))].filter(([file, text]) => !skipped(file, text)));
|
|
181
|
+
}
|
|
182
|
+
|
|
211
183
|
// The rest of the repository is what a copy is compared against. Test files are left out of it: copied setup in tests is often benign.
|
|
212
|
-
// A caller scoring many changes in one repository can pass a cache, so files it has read once are not parsed again.
|
|
213
|
-
|
|
184
|
+
// A caller scoring many changes in one repository can pass a cache, so files it has read once are not parsed again. Past the cap the
|
|
185
|
+
// rest is not read, and the report says so, since a copy of a file beyond it would be missed.
|
|
186
|
+
async function restOfRepo(ctx, touched, texts) {
|
|
214
187
|
const rest = [];
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
188
|
+
const families = new Set(ctx.cloneAfter.map((f) => f.family));
|
|
189
|
+
const candidates = [...texts.keys()].filter((f) => families.has(familyOf(languageOf(f))) && !touched.has(f) && !isTest(f));
|
|
190
|
+
if (candidates.length > ctx.maxRepoFiles) ctx.warnings.push({ rule: 'clone-scope', file: '.', line: 1, value: candidates.length, limit: ctx.maxRepoFiles });
|
|
191
|
+
for (const file of candidates.slice(0, ctx.maxRepoFiles)) {
|
|
192
|
+
const text = texts.get(file);
|
|
218
193
|
const tokens = await cachedTokens(ctx.cache, file, text);
|
|
219
|
-
if (tokens) rest.push({ file, tokens, size: ctx.limits.clones.tokens });
|
|
194
|
+
if (tokens) rest.push({ file, family: familyOf(languageOf(file)), tokens, size: ctx.limits.clones.tokens });
|
|
220
195
|
}
|
|
221
196
|
return rest;
|
|
222
197
|
}
|
|
223
198
|
|
|
199
|
+
// The import aliases of the repository's root tsconfig.json, or jsconfig.json when it has none, as they are after the change.
|
|
200
|
+
const CONFIGS = ['tsconfig.json', 'jsconfig.json'];
|
|
201
|
+
function aliasesAt(ctx) {
|
|
202
|
+
const config = CONFIGS.find((f) => ctx.repoFiles.includes(f));
|
|
203
|
+
return config ? aliasesFrom(filesAt(ctx.root, ctx.to, [config]).get(config) ?? '') : [];
|
|
204
|
+
}
|
|
205
|
+
|
|
224
206
|
/**
|
|
225
|
-
* The gate's verdict on the change from `from` to `to`: { ok, violations, warnings, exemptions, scored, unanalyzed }.
|
|
226
|
-
* { rule, file, line, name?, value, limit, before? }.
|
|
207
|
+
* The gate's verdict on the change from `from` to `to`: { ok, violations, warnings, exemptions, scored, unanalyzed, skipped, uncovered }.
|
|
208
|
+
* Each violation is { rule, file, line, name?, value, limit, before? }.
|
|
227
209
|
*/
|
|
228
|
-
export async function qualityGate(root, { from, to, limits, now = new Date().toISOString(), mode = 'project', repoFiles = [], cache = null }) {
|
|
229
|
-
const ctx = { root, from, to, limits, now, mode, repoFiles, cache, violations: [], warnings: [], exemptions: [], unanalyzed: [], scored: { files: 0, functions: 0 }, cloneAfter: [], cloneBefore: [], totals: [], moves: { before: [], after: [] } };
|
|
210
|
+
export async function qualityGate(root, { from, to, limits, now = new Date().toISOString(), mode = 'project', repoFiles = [], cache = null, maxRepoFiles = MAX_REPO_FILES, maxGraphFiles = MAX_GRAPH_FILES, forbid = [] }) {
|
|
211
|
+
const ctx = { root, from, to, limits, now, mode, repoFiles, cache, maxRepoFiles, maxGraphFiles, forbid, isTest, coupling: { touched: [], deleted: [], exports: [], renames: new Map() }, violations: [], warnings: [], exemptions: [], unanalyzed: [], skipped: [], uncovered: [], scored: { files: 0, functions: 0 }, cloneAfter: [], cloneBefore: [], totals: [], moves: { before: [], after: [] }, pyExports: [] };
|
|
230
212
|
const changed = addedRanges(root, from, to);
|
|
231
213
|
// The changed code is read up front, a batch at a time. One git process per file was most of the gate's time on a large branch.
|
|
232
214
|
const code = [...changed].filter(([file]) => languageOf(file));
|
|
233
215
|
ctx.before = filesAt(root, from, code.filter(([, c]) => !c.status.startsWith('A')).map(([file]) => file));
|
|
234
216
|
ctx.after = filesAt(root, to, code.filter(([, c]) => !c.status.startsWith('D')).map(([file]) => file));
|
|
235
217
|
for (const [file, change] of changed) await scoreFile(ctx, file, change);
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
218
|
+
scoreTotals(ctx);
|
|
219
|
+
await scoreUnusedExports(ctx, { skipped: SKIPPED, maxFiles: ctx.maxRepoFiles });
|
|
220
|
+
// The rest of the repository is only read when the change holds code it is compared with.
|
|
221
|
+
const touched = new Set(changed.keys());
|
|
222
|
+
const texts = ctx.cloneAfter.length > 0 || ctx.coupling.touched.length > 0 ? repoTexts(ctx, touched) : new Map();
|
|
223
|
+
if (ctx.coupling.touched.length > 0) scoreCoupling(ctx, texts, renamedFiles(root, from, to), aliasesAt(ctx));
|
|
224
|
+
const rest = ctx.cloneAfter.length > 0 ? await restOfRepo(ctx, touched, texts) : [];
|
|
225
|
+
for (const family of new Set(ctx.cloneAfter.map((f) => f.family))) {
|
|
226
|
+
const of = (files) => files.filter((f) => f.family === family);
|
|
227
|
+
for (const c of findClones({ after: of(ctx.cloneAfter), before: of(ctx.cloneBefore), rest: of(rest) })) ctx.violations.push({ rule: 'clone', file: c.file, line: c.line, value: c.lines, limit: 0, other: c.other, similarity: c.similarity });
|
|
228
|
+
}
|
|
229
|
+
const { violations, warnings, exemptions, scored, unanalyzed, skipped: notScored, uncovered } = ctx;
|
|
230
|
+
return { ok: violations.length === 0, violations, warnings, exemptions, scored, unanalyzed, skipped: notScored, uncovered };
|
|
241
231
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// quality/imports.mjs: which files of the repository a JavaScript or TypeScript file imports, and which of their names. It reads the
|
|
2
|
+
// text, not a parse tree, so the whole repository can be read in the time a gate has: static import and export-from statements,
|
|
3
|
+
// require() and import() of a literal path. Relative paths are followed, and so are the aliases a root tsconfig.json or jsconfig.json
|
|
4
|
+
// declares under compilerOptions.paths and baseUrl. A package is not a file of this repository, so it is not followed. Type-only imports are kept apart, because they do not exist when the code runs and so cannot make a cycle.
|
|
5
|
+
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { codeOnly } from './js-source.mjs';
|
|
8
|
+
import { aliased } from './path-aliases.mjs';
|
|
9
|
+
|
|
10
|
+
export { codeOnly } from './js-source.mjs';
|
|
11
|
+
export { aliasesFrom } from './path-aliases.mjs';
|
|
12
|
+
|
|
13
|
+
// A statement is found by its keyword, and its clause is the text up to the next quote, at most MAX_CLAUSE characters on. The clause
|
|
14
|
+
// must have the shape of an import clause, so an `export type A = {` cannot swallow the import on the line after it. Every pattern
|
|
15
|
+
// here is anchored and bounded, so a hostile file costs the same as an ordinary one.
|
|
16
|
+
const STATEMENT = /^[ \t]*(import|export)\b/gm;
|
|
17
|
+
const MAX_CLAUSE = 1000;
|
|
18
|
+
const CLAUSES = {
|
|
19
|
+
import: /^\s*(type\s+)?((?:[\w$]+\s*,\s*)?(?:\{[^{}]*\}|\*\s*as\s+[\w$]+)|[\w$]+)\s*from\s*$/,
|
|
20
|
+
export: /^\s*(type\s+)?(\{[^{}]*\}|\*(?:\s*as\s+[\w$]+)?)\s*from\s*$/,
|
|
21
|
+
};
|
|
22
|
+
const SPEC = /^(['"])([^'"\n]+)\1/;
|
|
23
|
+
const BARE = /^[ \t]*import\s*['"]([^'"\n]+)['"]/gm;
|
|
24
|
+
const CALL = /\b(?:require|import)\(\s*['"]([^'"\n]+)['"]\s*\)/g;
|
|
25
|
+
const EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
|
|
26
|
+
// TypeScript written for ESM imports './x.js' for the file x.ts.
|
|
27
|
+
const SOURCE_FOR = { '.js': ['.ts', '.tsx'], '.jsx': ['.tsx'], '.mjs': ['.mts'], '.cjs': ['.cts'] };
|
|
28
|
+
|
|
29
|
+
// The names an import clause takes: null for all of them (a namespace, export *, or anything not spelled out).
|
|
30
|
+
function namesOf(kind, clause) {
|
|
31
|
+
if (/(^|,)\s*\*/.test(clause)) return null;
|
|
32
|
+
const names = [];
|
|
33
|
+
const braces = /\{([^}]*)\}/.exec(clause);
|
|
34
|
+
const outside = clause.replace(/\{[^}]*\}/, '').replace(/,/g, ' ').trim();
|
|
35
|
+
if (kind === 'import' && outside && outside !== 'type') names.push('default');
|
|
36
|
+
for (const part of braces ? braces[1].split(',') : []) {
|
|
37
|
+
const name = part.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0].trim();
|
|
38
|
+
if (name) names.push(name);
|
|
39
|
+
}
|
|
40
|
+
return names;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const typeOnly = (kind, type, clause) => Boolean(type) || (/^\{[^}]*\}$/.test(clause.trim()) && clause.replace(/[{}]/g, '').split(',').every((p) => /^\s*type\s/.test(p) || !p.trim()));
|
|
44
|
+
|
|
45
|
+
function fromStatement(text, m) {
|
|
46
|
+
const start = m.index + m[0].length;
|
|
47
|
+
const window = text.slice(start, start + MAX_CLAUSE);
|
|
48
|
+
const quote = window.search(/['"`]/);
|
|
49
|
+
const clause = quote < 0 ? null : CLAUSES[m[1]].exec(window.slice(0, quote));
|
|
50
|
+
const spec = clause ? SPEC.exec(window.slice(quote)) : null;
|
|
51
|
+
return spec ? { spec: spec[2], names: namesOf(m[1], clause[2]), typeOnly: typeOnly(m[1], clause[1], clause[2]) } : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** [{ spec, names, typeOnly }] for every import of a file's text. names is null when the import may use any name. */
|
|
55
|
+
export function importsOf(source) {
|
|
56
|
+
const text = codeOnly(source);
|
|
57
|
+
const out = [];
|
|
58
|
+
for (const m of text.matchAll(STATEMENT)) { const found = fromStatement(text, m); if (found) out.push(found); }
|
|
59
|
+
for (const m of text.matchAll(BARE)) out.push({ spec: m[1], names: [], typeOnly: false });
|
|
60
|
+
for (const m of text.matchAll(CALL)) out.push({ spec: m[1], names: null, typeOnly: false });
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The repository file an import names: a relative path, or an alias of the root tsconfig. Null for a package or a file not there. */
|
|
65
|
+
export function resolveImport(spec, from, files, aliases = []) {
|
|
66
|
+
if (!spec.startsWith('.')) return aliased(spec, aliases).map((base) => candidatesFor(base).find((c) => files.has(c))).find(Boolean) ?? null;
|
|
67
|
+
return candidatesFor(path.posix.join(path.posix.dirname(from), spec)).find((c) => files.has(c)) ?? null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function candidatesFor(base) {
|
|
71
|
+
const ext = path.posix.extname(base);
|
|
72
|
+
const swapped = (SOURCE_FOR[ext] ?? []).map((e) => base.slice(0, -ext.length) + e);
|
|
73
|
+
return [base, ...swapped, ...EXTENSIONS.map((e) => base + e), ...EXTENSIONS.map((e) => `${base}/index${e}`)];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A Map from each file to its edges [{ to, names, typeOnly }], for the files whose texts are given. */
|
|
77
|
+
export function importGraph(texts, files, aliases = []) {
|
|
78
|
+
const graph = new Map();
|
|
79
|
+
for (const [file, text] of texts) {
|
|
80
|
+
const edges = [];
|
|
81
|
+
for (const imp of importsOf(text)) {
|
|
82
|
+
const to = resolveImport(imp.spec, file, files, aliases);
|
|
83
|
+
if (to && to !== file) edges.push({ to, names: imp.names, typeOnly: imp.typeOnly });
|
|
84
|
+
}
|
|
85
|
+
graph.set(file, edges);
|
|
86
|
+
}
|
|
87
|
+
return graph;
|
|
88
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// quality/js-source.mjs: JavaScript and TypeScript source with its comments and template strings blanked, so text that only mentions code
|
|
2
|
+
// is not read as code. Quoted strings stay, because import paths are quoted. A slash opens a regular expression after an operator or a
|
|
3
|
+
// keyword that ends an expression, so a quote inside one does not open a string. Blanked text keeps its newlines, so every line stays
|
|
4
|
+
// where it was. tsconfig.json is read the same way, since JSON with comments is this with no templates.
|
|
5
|
+
|
|
6
|
+
const REGEX_AFTER = /(^|[(,=:[!&|?{};+\-*%<>~^]|\b(return|typeof|case|do|else|in|of|void|yield|await|delete|throw|new))\s*$/;
|
|
7
|
+
|
|
8
|
+
function quotedEnd(text, i) {
|
|
9
|
+
const quote = text[i];
|
|
10
|
+
let j = i + 1;
|
|
11
|
+
while (j < text.length && text[j] !== quote && (quote === '`' || text[j] !== '\n')) j += text[j] === '\\' ? 2 : 1;
|
|
12
|
+
return j + 1;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function regexEnd(text, i) {
|
|
16
|
+
let j = i + 1;
|
|
17
|
+
let inClass = false;
|
|
18
|
+
while (j < text.length && text[j] !== '\n') {
|
|
19
|
+
if (text[j] === '\\') j += 1;
|
|
20
|
+
else if (text[j] === '[' || text[j] === ']') inClass = text[j] === '[';
|
|
21
|
+
else if (text[j] === '/' && !inClass) return j + 1;
|
|
22
|
+
j += 1;
|
|
23
|
+
}
|
|
24
|
+
return j;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const until = (text, from, mark, past) => { const at = text.indexOf(mark, from); return at === -1 ? text.length : at + past; };
|
|
28
|
+
// What opens at a position, where it ends, and whether it is blanked.
|
|
29
|
+
const OPENERS = [
|
|
30
|
+
['//', (text, i) => until(text, i, '\n', 0), true],
|
|
31
|
+
['/*', (text, i) => until(text, i + 2, '*/', 2), true],
|
|
32
|
+
['`', quotedEnd, true],
|
|
33
|
+
['"', quotedEnd, false],
|
|
34
|
+
["'", quotedEnd, false],
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
function sourcePiece(text, i, before) {
|
|
38
|
+
const opener = OPENERS.find(([mark]) => text.startsWith(mark, i));
|
|
39
|
+
if (opener) return { end: opener[1](text, i), blank: opener[2] };
|
|
40
|
+
return { end: text[i] === '/' && REGEX_AFTER.test(before) ? regexEnd(text, i) : i + 1, blank: false };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The text with its comments and template strings blanked to spaces, newlines kept. */
|
|
44
|
+
export function codeOnly(text) {
|
|
45
|
+
const parts = [];
|
|
46
|
+
let tail = '';
|
|
47
|
+
for (let i = 0; i < text.length;) {
|
|
48
|
+
const { end, blank } = sourcePiece(text, i, tail);
|
|
49
|
+
const piece = text.slice(i, end);
|
|
50
|
+
parts.push(blank ? piece.replace(/[^\n]/g, ' ') : piece);
|
|
51
|
+
if (!blank && piece.trim() !== '') tail = (tail + piece).slice(-12);
|
|
52
|
+
i = end;
|
|
53
|
+
}
|
|
54
|
+
return parts.join('');
|
|
55
|
+
}
|