@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
|
@@ -1,14 +1,29 @@
|
|
|
1
1
|
// quality/clones.mjs: copied code in what a change adds. Tokens come from the parse tree with names and literals normalised, so a copy
|
|
2
|
-
// with its variables renamed still matches (Type-1 and Type-2 clones).
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// with its variables renamed still matches (Type-1 and Type-2 clones). Whole windows of the full size find exact copies. Short seed
|
|
3
|
+
// windows are also chained, with small gaps allowed, into one copied region, so a copy with a line changed or inserted is still one copy
|
|
4
|
+
// (a near-miss, Type-3 clone).
|
|
5
|
+
// A seed that also appears elsewhere, in the rest of the repository or in another part of the change, and more often than before the
|
|
6
|
+
// change, is copied. The copies of an access check that drifted apart on one task are exactly this.
|
|
5
7
|
|
|
6
8
|
import crypto from 'node:crypto';
|
|
7
9
|
|
|
8
10
|
const NAMES = new Set(['identifier', 'property_identifier', 'shorthand_property_identifier', 'shorthand_property_identifier_pattern', 'type_identifier', 'private_property_identifier', 'statement_identifier', 'field_identifier']);
|
|
9
|
-
const LITERALS = new Set(['string', 'template_string', 'number', 'regex', 'string_fragment'
|
|
11
|
+
const LITERALS = new Set(['string', 'template_string', 'number', 'regex', 'string_fragment',
|
|
12
|
+
'string_literal', 'verbatim_string_literal', 'raw_string_literal', 'interpolated_string_expression', 'integer_literal', 'real_literal', 'character_literal', 'integer', 'float']);
|
|
10
13
|
|
|
11
|
-
const FUNCTIONS = new Set(['function_declaration', 'function_expression', 'function', 'arrow_function', 'method_definition', 'generator_function_declaration', 'generator_function'
|
|
14
|
+
const FUNCTIONS = new Set(['function_declaration', 'function_expression', 'function', 'arrow_function', 'method_definition', 'generator_function_declaration', 'generator_function',
|
|
15
|
+
'method_declaration', 'constructor_declaration', 'operator_declaration', 'conversion_operator_declaration', 'local_function_statement', 'lambda_expression', 'anonymous_method_expression', 'accessor_declaration', 'function_definition']);
|
|
16
|
+
|
|
17
|
+
// A seed is this many tokens. Two seeds of one copy may be this far apart, and the copy may shift by this much against the original,
|
|
18
|
+
// which is a changed or inserted line or two. A copied region must still match this share of its tokens.
|
|
19
|
+
const SEED = 20;
|
|
20
|
+
const GAP = 20;
|
|
21
|
+
const SHIFT = 12;
|
|
22
|
+
const COVERAGE = 0.8;
|
|
23
|
+
// A seed found in more places than this before the change is an idiom of the language or the codebase, not a copy of one piece of
|
|
24
|
+
// logic. It is judged before the change, so making many copies at once cannot turn the copies into an idiom. Only this many of a seed's
|
|
25
|
+
// places are chained, which bounds the work and is enough to find one original.
|
|
26
|
+
const COMMON = 24;
|
|
12
27
|
|
|
13
28
|
/**
|
|
14
29
|
* [{ t, row }] for the code inside functions: names become ID, literals LIT, everything else its own text. Comments are dropped, and so
|
|
@@ -28,49 +43,121 @@ export function tokensOf(tree) {
|
|
|
28
43
|
return out;
|
|
29
44
|
}
|
|
30
45
|
|
|
31
|
-
const hash = (tokens) => crypto.createHash('sha1').update(tokens.map((x) => x.t).join('\u0001')).digest('
|
|
46
|
+
const hash = (tokens) => crypto.createHash('sha1').update(tokens.map((x) => x.t).join('\u0001')).digest('base64');
|
|
32
47
|
|
|
33
|
-
/** Every window of `size` tokens: [{ hash, first, last }] with first and last rows. */
|
|
48
|
+
/** Every window of `size` tokens: [{ hash, first, last, at }] with first and last rows. */
|
|
34
49
|
export function windows(tokens, size) {
|
|
35
50
|
const out = [];
|
|
36
51
|
for (let i = 0; i + size <= tokens.length; i++) out.push({ hash: hash(tokens.slice(i, i + size)), first: tokens[i].row, last: tokens[i + size - 1].row, at: i });
|
|
37
52
|
return out;
|
|
38
53
|
}
|
|
39
54
|
|
|
40
|
-
|
|
55
|
+
const seedOf = (f) => Math.min(SEED, f.size);
|
|
56
|
+
|
|
57
|
+
function index(files, sizeOf) {
|
|
41
58
|
const m = new Map();
|
|
42
|
-
for (const f of files)
|
|
59
|
+
for (const f of files) {
|
|
60
|
+
for (const w of windows(f.tokens, sizeOf(f))) {
|
|
61
|
+
const list = m.get(w.hash);
|
|
62
|
+
if (list) list.push({ file: f.file, at: w.at }); else m.set(w.hash, [{ file: f.file, at: w.at }]);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
43
65
|
return m;
|
|
44
66
|
}
|
|
45
67
|
|
|
46
|
-
//
|
|
47
|
-
function
|
|
68
|
+
// Whether a window is a new copy: it occurs at least twice after the change, and more often than before it.
|
|
69
|
+
function counter(files) {
|
|
70
|
+
const { after, before, rest, sizeOf } = files;
|
|
71
|
+
const old = index([...before, ...rest], sizeOf);
|
|
72
|
+
const now = index([...after, ...rest], sizeOf);
|
|
73
|
+
const count = (m, h) => m.get(h)?.length ?? 0;
|
|
74
|
+
return { isNew: (h) => count(now, h) >= 2 && count(now, h) > count(old, h), isIdiom: (h) => count(old, h) > COMMON, places: (h) => now.get(h) ?? [] };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Whole copies: runs of consecutive new windows of the full size, each with one other place it occurs. A window this long is not an
|
|
78
|
+
// idiom, so every copy is found however many there are.
|
|
79
|
+
function exactRuns(f, { isNew, places }) {
|
|
48
80
|
const runs = [];
|
|
49
81
|
let run = null;
|
|
50
82
|
for (const w of windows(f.tokens, f.size)) {
|
|
51
|
-
if (
|
|
52
|
-
if (run && w.at === run.end + 1) { run.end = w.at; run.last = w.last; continue; }
|
|
83
|
+
if (run && isNew(w.hash) && w.at === run.end + 1) { run.end = w.at; continue; }
|
|
53
84
|
if (run) runs.push(run);
|
|
54
|
-
const other = places(w.hash).find((c) => c.file !== f.file || Math.abs(c.
|
|
55
|
-
run = other ? {
|
|
85
|
+
const other = isNew(w.hash) ? places(w.hash).find((c) => c.file !== f.file || Math.abs(c.at - w.at) >= f.size) : null;
|
|
86
|
+
run = other ? { first: w.at, end: w.at, other: other.file, to: other.at } : null;
|
|
56
87
|
}
|
|
57
88
|
if (run) runs.push(run);
|
|
58
|
-
return runs;
|
|
89
|
+
return runs.map((r) => ({ first: r.first, last: r.end + f.size - 1, other: r.other, to: r.to, similarity: 1 }));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Seeds of one file chained into regions. Each point is a seed at `at` matching `other` at `to`. A point joins a chain in the same other
|
|
93
|
+
// file when it follows closely and keeps about the same offset; otherwise it starts a new chain. A chain left too far behind is closed,
|
|
94
|
+
// so each point is compared only with the chains still open near it.
|
|
95
|
+
function chains(points, seed) {
|
|
96
|
+
const open = new Map();
|
|
97
|
+
const done = [];
|
|
98
|
+
for (const p of points.sort((a, b) => a.at - b.at)) {
|
|
99
|
+
const delta = p.to - p.at;
|
|
100
|
+
const live = (open.get(p.other) ?? []).filter((c) => p.at - c.last <= seed + GAP || !done.push(c));
|
|
101
|
+
const chain = live.find((c) => Math.abs(delta - c.delta) <= SHIFT);
|
|
102
|
+
if (chain) { chain.last = p.at; chain.delta = delta; chain.seeds.push(p.at); }
|
|
103
|
+
else live.push({ other: p.other, first: p.at, firstTo: p.to, last: p.at, delta, seeds: [p.at] });
|
|
104
|
+
open.set(p.other, live);
|
|
105
|
+
}
|
|
106
|
+
return [...done, ...[...open.values()].flat()];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function covered(seeds, seed) {
|
|
110
|
+
let n = 0;
|
|
111
|
+
let end = -1;
|
|
112
|
+
for (const s of seeds) { n += Math.min(seed, s + seed - 1 - end); end = s + seed - 1; }
|
|
113
|
+
return n;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Near copies: seeds chained into regions at least `size` tokens long that mostly match.
|
|
117
|
+
function nearRegions(f, { isNew, isIdiom, places }) {
|
|
118
|
+
const seed = seedOf(f);
|
|
119
|
+
const points = [];
|
|
120
|
+
for (const w of windows(f.tokens, seed)) {
|
|
121
|
+
if (!isNew(w.hash) || isIdiom(w.hash)) continue;
|
|
122
|
+
const where = places(w.hash).filter((p) => p.file !== f.file || Math.abs(p.at - w.at) >= f.size).slice(0, COMMON);
|
|
123
|
+
for (const p of where) points.push({ at: w.at, other: p.file, to: p.at });
|
|
124
|
+
}
|
|
125
|
+
return chains(points, seed)
|
|
126
|
+
.map((c) => ({ first: c.first, last: c.last + seed - 1, other: c.other, to: c.firstTo, span: c.last + seed - c.first, cover: covered(c.seeds, seed) }))
|
|
127
|
+
.filter((c) => c.span >= f.size && c.cover / c.span >= COVERAGE)
|
|
128
|
+
.map((c) => ({ ...c, similarity: Number((c.cover / c.span).toFixed(2)) }));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// An exact copy is one the change made only if most of its short seeds are new as well. The same line added to code that was already
|
|
132
|
+
// copied makes every full window around it new, while the seeds away from it were copies before: the change kept the copies and made
|
|
133
|
+
// none. On a template codebase that charged one added field with 72 copies.
|
|
134
|
+
function madeHere(f, run, near) {
|
|
135
|
+
const seed = seedOf(f);
|
|
136
|
+
const seeds = windows(f.tokens.slice(run.first, run.last + 1), seed);
|
|
137
|
+
return seeds.filter((w) => near.isNew(w.hash)).length >= COVERAGE * seeds.length;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// One finding per stretch of a file, the longest region first, so a near copy that holds an exact stretch is reported whole.
|
|
141
|
+
function copiedRegions(f, { exact, near, others }) {
|
|
142
|
+
const kept = [];
|
|
143
|
+
const made = exactRuns(f, exact).filter((r) => madeHere(f, r, near));
|
|
144
|
+
const candidates = [...made, ...nearRegions(f, near)].sort((a, b) => (b.last - b.first) - (a.last - a.first));
|
|
145
|
+
for (const r of candidates) if (!kept.some((k) => r.first <= k.last && k.first <= r.last)) kept.push(r);
|
|
146
|
+
return kept.map((r) => ({ file: f.file, line: f.tokens[r.first].row, last: f.tokens[r.last].row, other: { file: r.other, line: others.get(r.other)?.tokens[r.to]?.row ?? 1 }, similarity: r.similarity }));
|
|
59
147
|
}
|
|
60
148
|
|
|
61
149
|
/**
|
|
62
|
-
* Copies a change made. A
|
|
63
|
-
*
|
|
64
|
-
*
|
|
150
|
+
* Copies a change made. A window is a new copy when it occurs more often after the change than before it, which does not depend on how
|
|
151
|
+
* git pairs the changed lines. after and before are the touched files in each version, rest the files the change did not touch; each is
|
|
152
|
+
* [{ file, tokens, size }]. Returns one finding per copied region: { file, line, lines, other: { file, line }, similarity }.
|
|
65
153
|
*/
|
|
66
154
|
export function findClones({ after, before = [], rest = [] }) {
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
const
|
|
71
|
-
const findings = after.flatMap((f) => copiedRuns(f, isNew, (h) => now.get(h)));
|
|
155
|
+
const exact = counter({ after, before, rest, sizeOf: (f) => f.size });
|
|
156
|
+
const near = counter({ after, before, rest, sizeOf: seedOf });
|
|
157
|
+
const others = new Map([...rest, ...after].map((f) => [f.file, f]));
|
|
158
|
+
const findings = after.flatMap((f) => copiedRegions(f, { exact, near, others }));
|
|
72
159
|
// Two copies that are both in the change would each be reported against the other: keep the later one.
|
|
73
|
-
const mirrors = (x, y) => y.file === x.other.file && y.line
|
|
160
|
+
const mirrors = (x, y) => y.file === x.other.file && Math.abs(y.line - x.other.line) <= 1 && y.other.file === x.file && Math.abs(y.other.line - x.line) <= 1;
|
|
74
161
|
const later = (x, y) => x.file > y.file || (x.file === y.file && x.line > y.line);
|
|
75
|
-
return findings.filter((x) => !findings.some((y) => y !== x && mirrors(x, y) && later(y, x))).map(({ file, line, last, other }) => ({ file, line, lines: last - line + 1, other }));
|
|
162
|
+
return findings.filter((x) => !findings.some((y) => y !== x && mirrors(x, y) && later(y, x))).map(({ file, line, last, other, similarity }) => ({ file, line, lines: last - line + 1, other, similarity }));
|
|
76
163
|
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// quality/coupling.mjs: how a change ties the modules of a repository together. Each rule compares the import graph after the change
|
|
2
|
+
// with the one before it, so a codebase that is already tangled is not failed for it:
|
|
3
|
+
// - cycle: a change may not add an import that closes a loop between modules that did not reach each other before. One that only adds
|
|
4
|
+
// another edge inside a loop that was already there is advice.
|
|
5
|
+
// - forbidden-import: a project or the user may name folders that must not import others, and a new import across that line fails.
|
|
6
|
+
// - import-fan-out: a module that something imports should not come to depend on too many others. It is advice.
|
|
7
|
+
// Only runtime imports count toward a cycle or the fan-out: a type-only import is gone when the code runs.
|
|
8
|
+
|
|
9
|
+
import { importGraph } from './imports.mjs';
|
|
10
|
+
import { report } from './findings.mjs';
|
|
11
|
+
import { scoreExports } from './exports.mjs';
|
|
12
|
+
|
|
13
|
+
const runtime = (edges = []) => edges.filter((e) => !e.typeOnly);
|
|
14
|
+
|
|
15
|
+
/** The path from one module to another along runtime imports, or null when there is none. */
|
|
16
|
+
function pathBetween(graph, from, to) {
|
|
17
|
+
const back = new Map([[from, null]]);
|
|
18
|
+
const queue = [from];
|
|
19
|
+
while (queue.length > 0) {
|
|
20
|
+
const at = queue.shift();
|
|
21
|
+
if (at === to) {
|
|
22
|
+
const out = [];
|
|
23
|
+
for (let n = to; n !== null; n = back.get(n)) out.unshift(n);
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
for (const e of runtime(graph.get(at))) if (!back.has(e.to)) { back.set(e.to, at); queue.push(e.to); }
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The graph before the change: every untouched file as it is now, each touched file as it was, gone if the change added it, and each
|
|
32
|
+
// deleted file as it was. A file the change moved keeps its new name, so a loop that was only renamed is one that was already there.
|
|
33
|
+
function graphBefore(ctx, after, files) {
|
|
34
|
+
const before = new Map(after);
|
|
35
|
+
const known = new Set(files);
|
|
36
|
+
const { touched, deleted, renames } = ctx.coupling;
|
|
37
|
+
for (const file of touched) {
|
|
38
|
+
before.delete(file);
|
|
39
|
+
known.delete(file);
|
|
40
|
+
}
|
|
41
|
+
const old = new Map([...touched, ...deleted].filter((f) => ctx.before.has(f)).map((f) => [f, ctx.before.get(f)]));
|
|
42
|
+
for (const file of old.keys()) known.add(file);
|
|
43
|
+
const named = (f) => renames.get(f) ?? f;
|
|
44
|
+
for (const [file, edges] of importGraph(old, known, ctx.coupling.aliases)) before.set(named(file), edges.map((e) => ({ ...e, to: named(e.to) })));
|
|
45
|
+
return before;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function scoreForbidden(ctx, file, edge) {
|
|
49
|
+
const rule = ctx.forbid.find((r) => file.startsWith(r.from) && edge.to.startsWith(r.to));
|
|
50
|
+
if (rule) ctx.violations.push({ rule: 'forbidden-import', file, line: 1, value: 1, limit: 0, other: { file: edge.to, line: 1 }, reason: `${rule.from} may not import ${rule.to}` });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function scoreEdge(ctx, { file, edge, after, before }) {
|
|
54
|
+
scoreForbidden(ctx, file, edge);
|
|
55
|
+
if (edge.typeOnly || ctx.isTest(edge.to)) return;
|
|
56
|
+
const loop = pathBetween(after, edge.to, file);
|
|
57
|
+
if (!loop) return;
|
|
58
|
+
const cycle = [file, ...loop].join(' -> ');
|
|
59
|
+
// The loop was already there when the two modules reached each other before the change.
|
|
60
|
+
const tangled = pathBetween(before, edge.to, file) && pathBetween(before, file, edge.to);
|
|
61
|
+
report(ctx, { rule: tangled ? 'cycle-grown' : 'cycle', file, line: 1, value: loop.length, limit: 0, reason: cycle });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function fanOut(graph, file, isTest) {
|
|
65
|
+
return new Set(runtime(graph.get(file)).map((e) => e.to).filter((f) => !isTest(f))).size;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function scoreFanOut(ctx, { file, after, before, importers }) {
|
|
69
|
+
const now = fanOut(after, file, ctx.isTest);
|
|
70
|
+
const was = fanOut(before, file, ctx.isTest);
|
|
71
|
+
const limit = ctx.limits.imports.fan_out;
|
|
72
|
+
if (now > limit && was <= limit && (importers.get(file)?.length ?? 0) > 0) report(ctx, { rule: 'import-fan-out', file, line: 1, value: now, limit, before: was });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// The modules that import each module, with the names each one takes.
|
|
76
|
+
function importersOf(graph) {
|
|
77
|
+
const importers = new Map();
|
|
78
|
+
for (const [from, edges] of graph) {
|
|
79
|
+
for (const e of edges) { if (!importers.has(e.to)) importers.set(e.to, []); importers.get(e.to).push({ from, names: e.names }); }
|
|
80
|
+
}
|
|
81
|
+
return importers;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// The imports a touched module did not have before, each target once for runtime and once for type-only imports.
|
|
85
|
+
function newEdges(file, after, before) {
|
|
86
|
+
const had = new Set((before.get(file) ?? []).map((e) => `${e.typeOnly}:${e.to}`));
|
|
87
|
+
const runtimeHad = new Set(runtime(before.get(file)).map((e) => e.to));
|
|
88
|
+
const seen = new Set();
|
|
89
|
+
return after.get(file).filter((e) => {
|
|
90
|
+
const key = `${e.typeOnly}:${e.to}`;
|
|
91
|
+
const fresh = !seen.has(key) && !had.has(key) && !(e.typeOnly && runtimeHad.has(e.to));
|
|
92
|
+
seen.add(key);
|
|
93
|
+
return fresh;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Every coupling rule on the touched modules. texts is every JavaScript and TypeScript file of the repository after the change, and
|
|
99
|
+
* aliases the root tsconfig's paths. A test is held to the folders a project forbids too; its loops and fan-out are not the product's.
|
|
100
|
+
*/
|
|
101
|
+
export function scoreCoupling(ctx, texts, renames = new Map(), aliases = []) {
|
|
102
|
+
ctx.coupling.renames = renames;
|
|
103
|
+
ctx.coupling.aliases = aliases;
|
|
104
|
+
const files = new Set(texts.keys());
|
|
105
|
+
const after = importGraph(texts, files, aliases);
|
|
106
|
+
const before = graphBefore(ctx, after, files);
|
|
107
|
+
const importers = importersOf(after);
|
|
108
|
+
for (const file of ctx.coupling.touched.filter((f) => after.has(f))) {
|
|
109
|
+
const fresh = newEdges(file, after, before);
|
|
110
|
+
if (ctx.isTest(file)) { for (const edge of fresh) scoreForbidden(ctx, file, edge); continue; }
|
|
111
|
+
for (const edge of fresh) scoreEdge(ctx, { file, edge, after, before });
|
|
112
|
+
scoreFanOut(ctx, { file, after, before, importers });
|
|
113
|
+
}
|
|
114
|
+
for (const { file, names } of ctx.coupling.exports) scoreExports(ctx, { file, names, importers });
|
|
115
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// quality/exports.mjs: a name a change exports from a module that the repository imports, when nothing imports that name. A module
|
|
2
|
+
// nothing imports may be an entry point or a package's public face, and one imported whole may use any name, so neither is held to it.
|
|
3
|
+
// It is advice.
|
|
4
|
+
|
|
5
|
+
import { report, overlaps } from './findings.mjs';
|
|
6
|
+
|
|
7
|
+
const field = (node, name) => node.childForFieldName(name);
|
|
8
|
+
const isDefault = (node) => node.children.some((c) => c.type === 'default');
|
|
9
|
+
|
|
10
|
+
// The names one export statement declares: export default, export function f, export const a = 1, b = 2, and export { a, b as c }.
|
|
11
|
+
function declared(node) {
|
|
12
|
+
if (isDefault(node)) return [[node, 'default']];
|
|
13
|
+
const declaration = field(node, 'declaration');
|
|
14
|
+
const own = field(declaration ?? node, 'name');
|
|
15
|
+
if (declaration && own) return [[declaration, own.text]];
|
|
16
|
+
const variables = (declaration?.namedChildren ?? []).filter((c) => c.type === 'variable_declarator' && field(c, 'name')?.type === 'identifier');
|
|
17
|
+
const clause = node.namedChildren.find((c) => c.type === 'export_clause')?.namedChildren ?? [];
|
|
18
|
+
return [...variables.map((d) => [d, field(d, 'name').text]), ...clause.map((spec) => [spec, (field(spec, 'alias') ?? field(spec, 'name'))?.text])];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The names a change exported from a module at its top level, with their lines: [{ name, line }]. A re-export is not one. */
|
|
22
|
+
export function exportsAdded(tree, added) {
|
|
23
|
+
const statements = tree.rootNode.namedChildren.filter((n) => n.type === 'export_statement' && !field(n, 'source') && overlaps(added, n.startPosition.row + 1, n.endPosition.row + 1));
|
|
24
|
+
return statements.flatMap(declared).filter(([, name]) => name).map(([node, name]) => ({ name, line: node.startPosition.row + 1 }));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Advice for each name a change exported that no importer of the module takes. */
|
|
28
|
+
export function scoreExports(ctx, { file, names, importers }) {
|
|
29
|
+
const users = importers.get(file) ?? [];
|
|
30
|
+
if (users.length === 0 || users.some((e) => e.names === null)) return;
|
|
31
|
+
const used = new Set(users.flatMap((e) => e.names));
|
|
32
|
+
for (const { name, line } of names) if (!used.has(name)) report(ctx, { rule: 'unused-export', file, line, name, value: users.length, limit: 0 });
|
|
33
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// quality/findings.mjs: where a finding goes. A rule that has been calibrated on known-good code fails a change. A rule that has not
|
|
2
|
+
// yet, or whose false alarms on that code were too many to fail on, is advice: it is reported with the warnings and fails nothing.
|
|
3
|
+
// Which is which is fixed here and is not configuration, so a project cannot turn a failing rule into advice.
|
|
4
|
+
|
|
5
|
+
const ADVISORY = Object.freeze(new Set([
|
|
6
|
+
'options', 'unanalyzed',
|
|
7
|
+
'empty-catch', 'log-only-catch', 'rethrow-catch', 'skipped-test', 'test-without-assertion', 'console', 'unused-binding', 'pass-through',
|
|
8
|
+
'unused-export', 'unused-import', 'import-fan-out', 'cycle-grown', 'file-lines', 'file-functions', 'file-added-lines',
|
|
9
|
+
]));
|
|
10
|
+
|
|
11
|
+
/** A finding as a violation or a warning, by its rule. In a benchmark, code the parser cannot follow fails. */
|
|
12
|
+
export function report(ctx, finding) {
|
|
13
|
+
const advice = ADVISORY.has(finding.rule) && !(finding.rule === 'unanalyzed' && ctx.mode === 'benchmark');
|
|
14
|
+
(advice ? ctx.warnings : ctx.violations).push(finding);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const inAdded = (added, line) => added.some(([a, b]) => line >= a && line <= b);
|
|
18
|
+
export const overlaps = (added, first, last) => added.some(([a, b]) => a <= last && b >= first);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// quality/functions.mjs: one touched function against the limits and against its own old version. A change may not take a function over
|
|
2
|
+
// a limit. One that was already over may get a little worse, as SonarQube treats an existing issue, but not by more than the growth
|
|
3
|
+
// limit, so an old function cannot keep taking a branch at a time for ever.
|
|
4
|
+
|
|
5
|
+
import { report } from './findings.mjs';
|
|
6
|
+
|
|
7
|
+
export const METRICS = ['cognitive', 'depth', 'lines', 'params', 'options'];
|
|
8
|
+
const ALLOW = /somi-gate-allow\s+([a-z_-]+)\s+reason="([^"]{20,})"\s+expires=(\d{4}-\d{2}-\d{2})/;
|
|
9
|
+
export const MAX_EXEMPTION_DAYS = 90;
|
|
10
|
+
const ANONYMOUS = /^<anonymous:(\d+)>$/;
|
|
11
|
+
|
|
12
|
+
// An exemption sits on the line just above the function. It needs a reason of 20 characters or more and an expiry no more than 90 days
|
|
13
|
+
// out. In benchmark mode none counts: an agent writing its own exemption is a violation.
|
|
14
|
+
export function exemption(ctx, lines, unit, rule) {
|
|
15
|
+
const m = ALLOW.exec(lines[unit.start - 2] ?? '');
|
|
16
|
+
if (!m || (m[1] !== rule && m[1] !== 'all') || ctx.mode === 'benchmark') return null;
|
|
17
|
+
const expires = Date.parse(`${m[3]}T00:00:00Z`);
|
|
18
|
+
const today = Date.parse(ctx.now);
|
|
19
|
+
if (!(expires >= today) || expires - today > MAX_EXEMPTION_DAYS * 86400000) return null;
|
|
20
|
+
return { reason: m[2], expires: m[3] };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// 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
|
|
24
|
+
// old one got different. What is left is paired by name alone, so a function whose parameters changed is still the same function. An
|
|
25
|
+
// anonymous function is named by its line, so its line is traced back through the change first: lines added above it do not make an
|
|
26
|
+
// old callback look new.
|
|
27
|
+
export function pairUnits(before, after, toOld = (line) => line) {
|
|
28
|
+
const taken = new Set();
|
|
29
|
+
const nameOf = (u) => (ANONYMOUS.test(u.name) ? anonymousName(before, u, toOld) : u.name);
|
|
30
|
+
const match = (u, key) => {
|
|
31
|
+
const old = before.find((b) => !taken.has(b) && key(b, b.name) === key(u, nameOf(u)));
|
|
32
|
+
if (old) taken.add(old);
|
|
33
|
+
return old ?? null;
|
|
34
|
+
};
|
|
35
|
+
const exact = after.map((u) => match(u, (x, name) => `${x.kind}:${name}:${x.signature}`));
|
|
36
|
+
return after.map((u, i) => ({ after: u, before: exact[i] ?? match(u, (x, name) => `${x.kind}:${name}`) }));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// An anonymous function's old name. When the change edited its first line, as when a test's title changes, the first of its lines the
|
|
40
|
+
// change left alone is traced back instead, and the innermost old anonymous function holding that line is the one it was.
|
|
41
|
+
function anonymousName(before, u, toOld) {
|
|
42
|
+
const start = toOld(u.start);
|
|
43
|
+
if (start !== null) return `<anonymous:${start}>`;
|
|
44
|
+
let line = null;
|
|
45
|
+
for (let row = u.start + 1; row <= u.end && line === null; row++) line = toOld(row);
|
|
46
|
+
const holders = line === null ? [] : before.filter((b) => ANONYMOUS.test(b.name) && b.start <= line && b.end >= line);
|
|
47
|
+
const inner = holders.sort((x, y) => (x.end - x.start) - (y.end - y.start))[0];
|
|
48
|
+
return inner?.name ?? `<added:${u.start}>`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function overLimit(ctx, { file, lines, after, before, metric, limit, grown }) {
|
|
52
|
+
const allowed = exemption(ctx, lines, after, metric);
|
|
53
|
+
if (allowed) return ctx.exemptions.push({ rule: metric, file, line: after.start, name: after.name, ...allowed });
|
|
54
|
+
return report(ctx, { rule: metric, file, line: after.start, name: after.name, kind: after.kind, value: after[metric], limit, ...(before ? { before: before[metric] } : {}), ...(grown ? { grown } : {}) });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** One touched function, paired with its old version or null. */
|
|
58
|
+
export function scoreUnit(ctx, { file, lines, after, before }) {
|
|
59
|
+
ctx.scored.functions += 1;
|
|
60
|
+
for (const metric of METRICS) {
|
|
61
|
+
const limit = ctx.limits[after.kind][metric];
|
|
62
|
+
if (after[metric] <= limit || (before && after[metric] <= before[metric])) continue;
|
|
63
|
+
const growth = ctx.limits.growth[metric];
|
|
64
|
+
const already = before && before[metric] > limit;
|
|
65
|
+
if (already && (growth === undefined || after[metric] - before[metric] <= growth)) {
|
|
66
|
+
ctx.warnings.push({ rule: metric, file, line: after.start, name: after.name, value: after[metric], limit, before: before[metric] });
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
overLimit(ctx, { file, lines, after, before, metric, limit: already ? before[metric] + growth : limit, grown: already });
|
|
70
|
+
}
|
|
71
|
+
}
|