@sixbell-telco/sdk-tools 0.1.5 → 0.1.6

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/CHANGELOG.md CHANGED
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.1.6] - 2026-12-02
11
+
12
+ ### Fixed
13
+
14
+ - **doctor**: a committed `.claude/settings.json` (shared skill listing budget) no longer raises `MFE_AGENT_TRACKED_001`; installed skills and other agent files still do
15
+
16
+ ### Added
17
+
18
+ - **check**: `--baseline <file>` (a previous `check --json` output) and `--since <git-ref>` fail only on findings that are new: a (rule, file) pair that occurs more often than in the baseline. `--since` checks the ref in a temporary git worktree that reuses the app's `node_modules` and removes it afterwards; a missing ref is a usage error. `--json` keeps the new findings in `findings` and `counts` and lists the old ones under `baseline`; the exit code and `--max-warnings` follow the new ones (NSU-159)
19
+
10
20
  ## [0.1.5] - 2026-12-02
11
21
 
12
22
  ### Added
package/README.md CHANGED
@@ -7,6 +7,7 @@ npx @sixbell-telco/sdk-tools check # lint and type-check src/
7
7
  npx @sixbell-telco/sdk-tools check src/app/orders # only some paths
8
8
  npx @sixbell-telco/sdk-tools check --json # one JSON envelope, for agents and scripts
9
9
  npx @sixbell-telco/sdk-tools check --fix # apply the safe fixes (deprecated tokens)
10
+ npx @sixbell-telco/sdk-tools check --since origin/develop # fail only on findings new since develop
10
11
  ```
11
12
 
12
13
  ## check
@@ -59,6 +60,10 @@ Every finding in `--json` has an `id`: the mfe-tools id (a project step's `rule`
59
60
 
60
61
  `rule` matches a finding's `rule` (an mfe-tools id, or a lint rule name such as `sdk/button-role`) or its `id` (eslint-plugin-sdk findings carry the mfe-tools id, their messageId, as `id`). `path` is a glob over the finding's file (`**`, `*`, `?`). A matched finding moves to `excepted` in `--json`, shows as a count in the human output and does not change the exit code. After `until` the entry excepts nothing and is itself a finding (`exceptions/expired`); a malformed entry is `exceptions/invalid`.
61
62
 
63
+ **Baseline.** On an app with old findings, `--baseline <file>` or `--since <git-ref>` fails only on new ones. `--baseline` takes a previous `check --json` output (the envelope, its `data`, or a findings array; a run that had a baseline adds its baseline findings). `--since` builds the baseline itself: it checks the app as it is at that ref, with the same paths and options, in a temporary git worktree that links the app's `node_modules` (from the app folder up to the checkout root), and removes the worktree afterwards. A ref that does not resolve is a usage error (exit 2); fetch it first in a shallow CI checkout.
64
+
65
+ A finding is new when its (rule, file) pair occurs more often than in the baseline. Within a pair the old findings are matched closest first (same line, column and message, then same message), so the leftover ones are the new ones. In `--json`, `findings` and `counts` hold the new findings and `baseline` holds `{ file }` or `{ ref, commit }` with the old `findings` and their `counts`. The exit code and `--max-warnings` look at new findings only; the human output lists the old ones dimmed (`--quiet` hides them).
66
+
62
67
  Options:
63
68
 
64
69
  | Option | Meaning |
@@ -73,8 +78,10 @@ Options:
73
78
  | `--manifest <file>` | Check against this manifest instead of the installed one |
74
79
  | `--integration` | Check the cross-repo wiring under `--root` instead (below) |
75
80
  | `--root <dir>` | With `--integration`: the folder holding the repos (default `.`) |
81
+ | `--baseline <file>` | Fail only on findings new against this previous `--json` output |
82
+ | `--since <git-ref>` | Fail only on findings new against the same check on that git ref |
76
83
 
77
- Exit codes: 0 no errors (warnings allowed, unless `--max-warnings`), 1 errors or a failure, 2 usage error.
84
+ Exit codes: 0 no errors (warnings allowed, unless `--max-warnings`; with a baseline, no new errors), 1 errors or a failure, 2 usage error.
78
85
 
79
86
  ### check --integration
80
87
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sixbell-telco/sdk-tools",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "CLI and MCP server for apps built with @sixbell-telco/sdk: check templates, imports and types against the installed SDK, and create or upgrade MFEs from their template repos",
5
5
  "type": "module",
6
6
  "bin": {
@@ -27,7 +27,7 @@
27
27
  "node": "^22.12.0 || ^24.0.0"
28
28
  },
29
29
  "dependencies": {
30
- "@sixbell-telco/eslint-plugin-sdk": "0.1.1",
30
+ "@sixbell-telco/eslint-plugin-sdk": "0.1.2",
31
31
  "angular-eslint": "^19.0.0",
32
32
  "eslint": "^9.0.0",
33
33
  "shadcn-lint-angular": "0.1.2",
@@ -0,0 +1,191 @@
1
+ /**
2
+ * `check --baseline` and `check --since`: compare a run's findings with an earlier run's, so a check
3
+ * fails only on what is new. A finding is new when its (rule, file) pair occurs more often now than
4
+ * in the baseline; the others are listed as baseline findings and do not count.
5
+ */
6
+ import { spawnSync } from 'node:child_process';
7
+ import { existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, unlinkSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import { dirname, join, relative } from 'node:path';
10
+
11
+ /**
12
+ * @typedef {import('../types.js').Finding} Finding
13
+ * @typedef {import('../types.js').CheckResult} CheckResult
14
+ * @typedef {import('../types.js').CheckBaseline} CheckBaseline
15
+ * @typedef {Pick<Finding, 'rule' | 'file' | 'line' | 'column' | 'message'>} BaselineFinding
16
+ */
17
+
18
+ /** Bad input for a baseline: a file that is not a check output, a missing ref. The CLI exits 2. */
19
+ export class BaselineError extends Error {}
20
+
21
+ /** @param {BaselineFinding} finding */
22
+ const pair = (finding) => `${finding.rule}\u0000${finding.file}`;
23
+
24
+ /**
25
+ * The findings of a previous `sdk-tools check --json` output: the envelope, its `data`, or a bare
26
+ * findings array. When that run had a baseline itself, its baseline findings count too, so a
27
+ * baseline can be refreshed from a run that used one.
28
+ * @param {string} file
29
+ * @returns {BaselineFinding[]}
30
+ */
31
+ export function readBaseline(file) {
32
+ /** @type {string} */
33
+ let text;
34
+ try {
35
+ text = readFileSync(file, 'utf8');
36
+ } catch {
37
+ throw new BaselineError(`baseline file ${file} not found`);
38
+ }
39
+ /** @type {unknown} */
40
+ let parsed;
41
+ try {
42
+ parsed = JSON.parse(text);
43
+ } catch {
44
+ throw new BaselineError(`baseline file ${file} is not JSON; pass the output of sdk-tools check --json`);
45
+ }
46
+ const envelope = /** @type {{ data?: unknown, error?: unknown }} */ (parsed && typeof parsed === 'object' ? parsed : {});
47
+ const data = /** @type {{ findings?: unknown, baseline?: { findings?: unknown } } | null} */ (
48
+ Array.isArray(parsed) ? { findings: parsed } : 'data' in envelope ? envelope.data : parsed
49
+ );
50
+ if (!data || !Array.isArray(data.findings)) {
51
+ const failed = typeof envelope.error === 'string' ? ` (that run failed: ${envelope.error})` : '';
52
+ throw new BaselineError(`baseline file ${file} holds no findings${failed}; pass the output of sdk-tools check --json`);
53
+ }
54
+ const findings = [...data.findings, ...(Array.isArray(data.baseline?.findings) ? data.baseline.findings : [])];
55
+ for (const finding of findings) {
56
+ if (!finding || typeof finding.rule !== 'string' || typeof finding.file !== 'string') {
57
+ throw new BaselineError(`baseline file ${file} has a finding without a rule and a file: ${JSON.stringify(finding)}`);
58
+ }
59
+ }
60
+ return findings;
61
+ }
62
+
63
+ /**
64
+ * Splits `findings` into new ones and ones the baseline already had. Per (rule, file) pair, as many
65
+ * findings as the baseline holds are old and the rest are new. The old ones are matched closest
66
+ * first (same line, column and message; then same message; then any), so a finding whose line
67
+ * moved keeps its match and the new one is the one that appeared.
68
+ * @template {BaselineFinding} T
69
+ * @param {T[]} findings
70
+ * @param {BaselineFinding[]} baseline
71
+ * @returns {{ fresh: T[], old: T[] }}
72
+ */
73
+ export function compareWithBaseline(findings, baseline) {
74
+ /** @type {Map<string, BaselineFinding[]>} */
75
+ const pool = new Map();
76
+ for (const finding of baseline) {
77
+ const list = pool.get(pair(finding)) ?? [];
78
+ list.push(finding);
79
+ pool.set(pair(finding), list);
80
+ }
81
+ /** @type {((a: BaselineFinding, b: BaselineFinding) => boolean)[]} */
82
+ const closestFirst = [
83
+ (a, b) => a.line === b.line && a.column === b.column && a.message === b.message,
84
+ (a, b) => a.message === b.message,
85
+ () => true,
86
+ ];
87
+ /** @type {Set<T>} */
88
+ const old = new Set();
89
+ for (const same of closestFirst) {
90
+ for (const finding of findings) {
91
+ const left = old.has(finding) ? undefined : pool.get(pair(finding));
92
+ const index = left ? left.findIndex((candidate) => same(finding, candidate)) : -1;
93
+ if (!left || index < 0) continue;
94
+ left.splice(index, 1);
95
+ old.add(finding);
96
+ }
97
+ }
98
+ return { fresh: findings.filter((f) => !old.has(f)), old: findings.filter((f) => old.has(f)) };
99
+ }
100
+
101
+ /** @param {Finding[]} findings */
102
+ const countOf = (findings) => ({
103
+ errors: findings.filter((f) => f.severity === 'error').length,
104
+ warnings: findings.filter((f) => f.severity === 'warn').length,
105
+ });
106
+
107
+ /**
108
+ * The result with only new findings in `findings` and `counts` (so the exit code follows them), and
109
+ * the old ones under `baseline`, with where the baseline came from.
110
+ * @param {CheckResult} result
111
+ * @param {BaselineFinding[]} baseline
112
+ * @param {{ file: string } | { ref: string, commit: string }} source
113
+ * @returns {CheckResult & { baseline: CheckBaseline }}
114
+ */
115
+ export function applyBaseline(result, baseline, source) {
116
+ const { fresh, old } = compareWithBaseline(result.findings, baseline);
117
+ return { ...result, findings: fresh, counts: countOf(fresh), baseline: { ...source, findings: old, counts: countOf(old) } };
118
+ }
119
+
120
+ /**
121
+ * @param {string[]} args
122
+ * @param {string} cwd
123
+ */
124
+ const git = (args, cwd) => spawnSync('git', args, { cwd, encoding: 'utf8' });
125
+
126
+ /**
127
+ * The git checkout `cwd` is in and the commit `ref` names there.
128
+ * @param {string} cwd
129
+ * @param {string} ref
130
+ * @returns {{ root: string, commit: string }}
131
+ */
132
+ export function resolveRef(cwd, ref) {
133
+ const top = git(['rev-parse', '--show-toplevel'], cwd);
134
+ if (top.status !== 0) throw new BaselineError(`--since needs a git checkout, and ${cwd} is not in one`);
135
+ const commit = ref.startsWith('-') ? null : git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], cwd);
136
+ if (!commit || commit.status !== 0) {
137
+ const remote = /^origin\/(.+)$/.exec(ref)?.[1];
138
+ throw new BaselineError(`git ref "${ref}" not found${remote ? `; fetch it first (git fetch origin ${remote})` : ''}`);
139
+ }
140
+ return { root: realpathSync(top.stdout.trim()), commit: commit.stdout.trim() };
141
+ }
142
+
143
+ /**
144
+ * Runs `run` on the app as it is at `commit`: in a temporary git worktree, with the app's
145
+ * node_modules linked in (from the app folder up to the checkout root), so both runs use the same
146
+ * packages and rules. The worktree is removed afterwards, also when the run is interrupted.
147
+ * @template T
148
+ * @param {{ cwd: string, root: string, commit: string, ref: string, run: (app: string) => Promise<T> }} options
149
+ * @returns {Promise<T>}
150
+ */
151
+ export async function runAtCommit({ cwd, root, commit, ref, run }) {
152
+ const prefix = relative(root, realpathSync(cwd));
153
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'sdk-tools-since-')));
154
+ const added = git(['worktree', 'add', '--detach', '--quiet', dir, commit], root);
155
+ if (added.status !== 0) {
156
+ rmSync(dir, { recursive: true, force: true });
157
+ throw new Error(`could not check out ${ref} in a temporary worktree: ${added.stderr.trim()}`);
158
+ }
159
+ /** @type {string[]} */
160
+ const links = [];
161
+ const cleanup = () => {
162
+ for (const link of links) if (lstatSync(link, { throwIfNoEntry: false })?.isSymbolicLink()) unlinkSync(link);
163
+ git(['worktree', 'remove', '--force', dir], root);
164
+ rmSync(dir, { recursive: true, force: true });
165
+ git(['worktree', 'prune'], root);
166
+ };
167
+ /** @param {NodeJS.Signals} signal */
168
+ const interrupted = (signal) => {
169
+ cleanup();
170
+ process.kill(process.pid, signal);
171
+ };
172
+ process.once('SIGINT', interrupted);
173
+ process.once('SIGTERM', interrupted);
174
+ try {
175
+ const app = join(dir, prefix);
176
+ if (!existsSync(app)) throw new BaselineError(`${prefix || '.'} does not exist at ${ref}`);
177
+ for (let from = realpathSync(cwd), to = app; ; from = dirname(from), to = dirname(to)) {
178
+ const modules = join(from, 'node_modules');
179
+ if (existsSync(modules) && !existsSync(join(to, 'node_modules'))) {
180
+ symlinkSync(modules, join(to, 'node_modules'), 'dir');
181
+ links.push(join(to, 'node_modules'));
182
+ }
183
+ if (from === root || dirname(from) === from) break;
184
+ }
185
+ return await run(app);
186
+ } finally {
187
+ process.off('SIGINT', interrupted);
188
+ process.off('SIGTERM', interrupted);
189
+ cleanup();
190
+ }
191
+ }
package/src/cli.mjs CHANGED
@@ -43,6 +43,12 @@ const VERBS = {
43
43
  'mounts, proxy entries, served manifest and translations, permission translations, seed',
44
44
  'files, themes.json), with ids MFE_INT_001..010 and MFE_INT_ASSET_001..004. Files only.',
45
45
  '',
46
+ 'Baseline: --baseline <file> takes a previous --json output; --since <ref> builds one by',
47
+ "running the same check on that git ref, in a temporary worktree that reuses the app's",
48
+ 'node_modules (removed afterwards). A finding is new when its (rule, file) pair occurs more',
49
+ 'often than in the baseline. Only new findings count toward the exit code and',
50
+ '--max-warnings; the others are listed as baseline findings ("baseline" in --json).',
51
+ '',
46
52
  'Options:',
47
53
  ' --json one JSON envelope on stdout, for agents and scripts',
48
54
  ' --fix apply safe fixes (deprecated tokens, outline-none)',
@@ -53,11 +59,15 @@ const VERBS = {
53
59
  ' --manifest <file> check against this manifest instead of the installed SDK',
54
60
  ' --integration check the cross-repo wiring under --root (no lint or typecheck)',
55
61
  ' --root <dir> with --integration: the folder holding the repos (default .)',
62
+ ' --baseline <file> fail only on findings that are new against this --json output',
63
+ ' --since <git-ref> fail only on findings that are new against the check on that ref',
56
64
  '',
57
65
  'Examples:',
58
66
  ' sdk-tools check',
59
67
  ' sdk-tools check src/app/orders --no-typecheck',
60
68
  ' sdk-tools check --json > findings.json',
69
+ ' sdk-tools check --baseline findings.json',
70
+ ' sdk-tools check --since origin/develop',
61
71
  ' sdk-tools check --integration --root ~/work/irp --json',
62
72
  ].join('\n'),
63
73
  options: {
@@ -70,12 +80,23 @@ const VERBS = {
70
80
  manifest: { type: 'string' },
71
81
  integration: { type: 'boolean', default: false },
72
82
  root: { type: 'string' },
83
+ baseline: { type: 'string' },
84
+ since: { type: 'string' },
73
85
  help: { type: 'boolean', short: 'h', default: false },
74
86
  },
75
87
  async run(values, positionals) {
76
88
  /** @param {string} name */
77
89
  const flag = (name) => values[name] === true;
90
+ /** @param {string} name */
91
+ const text = (name) => (typeof values[name] === 'string' ? /** @type {string} */ (values[name]) : undefined);
78
92
  if (typeof values.root === 'string' && !flag('integration')) throw new UsageError('--root needs --integration');
93
+ const baselineFile = text('baseline');
94
+ const since = text('since');
95
+ if (baselineFile !== undefined && since !== undefined) throw new UsageError('--baseline and --since are exclusive; pass one');
96
+ if (flag('integration') && (baselineFile !== undefined || since !== undefined)) {
97
+ throw new UsageError('--baseline and --since apply to the app check, not --integration');
98
+ }
99
+ if (since === '') throw new UsageError('--since takes a git ref');
79
100
  if (flag('integration')) {
80
101
  if (positionals.length) throw new UsageError('--integration takes no paths; pass the folder with --root');
81
102
  const { resolve } = await import('node:path');
@@ -91,21 +112,66 @@ const VERBS = {
91
112
  }
92
113
  const { check } = await import('./check.mjs');
93
114
  const { formatCheck, progress } = await import('./format.mjs');
115
+ const baseline = await import('./check/baseline.mjs');
94
116
  const maxWarnings = typeof values['max-warnings'] === 'string' ? Number(values['max-warnings']) : undefined;
95
117
  if (maxWarnings !== undefined && !Number.isInteger(maxWarnings)) throw new UsageError('--max-warnings takes a whole number');
118
+ /** @template T @param {() => T} read @returns {T} */
119
+ const usage = (read) => {
120
+ try {
121
+ return read();
122
+ } catch (thrown) {
123
+ throw thrown instanceof baseline.BaselineError ? new UsageError(thrown.message) : thrown;
124
+ }
125
+ };
126
+ const cwd = process.cwd();
127
+ // Bad baseline input fails before the (slow) check runs.
128
+ const fromFile = baselineFile === undefined ? undefined : usage(() => baseline.readBaseline(baselineFile));
129
+ const at = since === undefined ? undefined : usage(() => baseline.resolveRef(cwd, since));
96
130
  const report = flag('json') ? () => {} : progress();
97
131
  const started = Date.now();
132
+ /** @type {import('./types.js').CheckResult} */
98
133
  let data;
99
134
  try {
100
135
  data = await check({
101
- cwd: process.cwd(),
136
+ cwd,
102
137
  paths: positionals.length ? positionals : undefined,
103
138
  fix: flag('fix'),
104
139
  typecheck: !flag('no-typecheck'),
105
- project: typeof values.project === 'string' ? values.project : undefined,
106
- manifestPath: typeof values.manifest === 'string' ? values.manifest : undefined,
140
+ project: text('project'),
141
+ manifestPath: text('manifest'),
107
142
  onProgress: report,
108
143
  });
144
+ if (fromFile) data = baseline.applyBaseline(data, fromFile, { file: /** @type {string} */ (baselineFile) });
145
+ if (at && since !== undefined) {
146
+ const { isAbsolute, relative, resolve } = await import('node:path');
147
+ const manifest = text('manifest');
148
+ const project = text('project');
149
+ const atBase = await baseline
150
+ .runAtCommit({
151
+ cwd,
152
+ ...at,
153
+ ref: since,
154
+ // The same check on the app as it was: paths inside the app follow it there, the manifest stays the given one.
155
+ run: async (app) => {
156
+ /** @param {string} path */
157
+ const moved = (path) => (isAbsolute(path) && !relative(cwd, path).startsWith('..') ? resolve(app, relative(cwd, path)) : path);
158
+ return (
159
+ await check({
160
+ cwd: app,
161
+ paths: positionals.length ? positionals.map(moved) : undefined,
162
+ typecheck: !flag('no-typecheck'),
163
+ project: project === undefined ? undefined : moved(project),
164
+ manifestPath: manifest === undefined ? undefined : resolve(cwd, manifest),
165
+ onProgress: (message) => report(message && `${since}: ${message}`),
166
+ })
167
+ ).findings;
168
+ },
169
+ })
170
+ .catch((/** @type {unknown} */ thrown) => {
171
+ throw thrown instanceof baseline.BaselineError ? new UsageError(thrown.message) : thrown;
172
+ });
173
+ data = baseline.applyBaseline(data, atBase, { ref: since, commit: at.commit });
174
+ }
109
175
  } finally {
110
176
  report('');
111
177
  }
@@ -28,6 +28,8 @@ const CHILD_INTERCEPTOR = 'src/app/core/interceptors/error/child-error.intercept
28
28
  const CHILD_ERROR_POLICY = 'src/app/core/interceptors/error/http-error-policy.util.ts';
29
29
  /** Agent tooling is installed per checkout and never committed (the skills lock included). */
30
30
  const AGENT_LOCAL_PATHS = ['.agents', '.claude', '.opencode', '.cursor', 'skills.lock.yaml', 'skills-lock.json'];
31
+ /** Shared agent config a repo commits on purpose (the skill listing budget); everything else under AGENT_LOCAL_PATHS stays per checkout. */
32
+ const AGENT_SHARED_FILES = new Set(['.claude/settings.json']);
31
33
  /** Starter features the templates ship to be replaced by the first real feature. */
32
34
  const PLACEHOLDER_FEATURES = new Set(['host', 'microfrontend', 'example']);
33
35
  /** Template features that stay: the status pages. */
@@ -193,7 +195,7 @@ function trackedAgentRoots(root) {
193
195
  ...new Set(
194
196
  tracked
195
197
  .split('\n')
196
- .filter(Boolean)
198
+ .filter((file) => file && !AGENT_SHARED_FILES.has(file))
197
199
  .map((file) => file.split('/')[0]),
198
200
  ),
199
201
  ].sort();
package/src/format.mjs CHANGED
@@ -30,39 +30,68 @@ function painter(stream = process.stdout) {
30
30
  const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
31
31
 
32
32
  /**
33
- * Findings grouped by file, then a summary: totals, the most frequent rules, fixable count, time.
34
- * @param {CheckResult} result
35
- * @param {{ paint?: Paint, quiet?: boolean, durationMs?: number, maxWarnings?: number }} [options]
36
- * @returns {string}
33
+ * Findings grouped by file, as indented lines after an empty line and the file name.
34
+ * @param {Finding[]} findings
35
+ * @param {Paint} paint
36
+ * @param {boolean} [dim] the whole line dimmed (baseline findings)
37
+ * @returns {string[]}
37
38
  */
38
- export function formatCheck({ findings, counts, excepted = [] }, { paint = painter(), quiet = false, durationMs, maxWarnings } = {}) {
39
- const shown = quiet ? findings.filter((f) => f.severity === 'error') : findings;
39
+ function byFileLines(findings, paint, dim = false) {
40
40
  /** @type {string[]} */
41
41
  const lines = [];
42
42
  /** @type {Map<string, Finding[]>} */
43
43
  const byFile = new Map();
44
- for (const finding of shown) {
44
+ for (const finding of findings) {
45
45
  const key = [finding.repo, finding.file].filter(Boolean).join('/') || '(project)';
46
46
  const list = byFile.get(key) ?? [];
47
47
  list.push(finding);
48
48
  byFile.set(key, list);
49
49
  }
50
50
  for (const [file, list] of byFile) {
51
- lines.push('', paint('underline', file));
51
+ lines.push('', paint(dim ? 'dim' : 'underline', file));
52
52
  const width = Math.max(...list.map((f) => `${f.line}:${f.column}`.length));
53
53
  for (const f of list) {
54
- const where = paint('dim', `${f.line}:${f.column}`.padEnd(width));
54
+ const where = `${f.line}:${f.column}`.padEnd(width);
55
+ if (dim) {
56
+ lines.push(paint('dim', ` ${where} ${f.severity === 'error' ? 'error' : 'warn '} ${f.message} ${f.rule}`));
57
+ continue;
58
+ }
55
59
  const severity = f.severity === 'error' ? paint('red', 'error') : paint('yellow', 'warn ');
56
60
  const fix = f.fixable ? paint('green', ' (fixable)') : '';
57
- lines.push(` ${where} ${severity} ${f.message}${fix} ${paint('dim', f.rule)}`);
61
+ lines.push(` ${paint('dim', where)} ${severity} ${f.message}${fix} ${paint('dim', f.rule)}`);
58
62
  }
59
63
  }
64
+ return lines;
65
+ }
66
+
67
+ /**
68
+ * Findings grouped by file, then a summary: totals, the most frequent rules, fixable count, time.
69
+ * With a baseline, the findings it already had come first, dimmed, and the summary counts new ones.
70
+ * @param {CheckResult} result
71
+ * @param {{ paint?: Paint, quiet?: boolean, durationMs?: number, maxWarnings?: number }} [options]
72
+ * @returns {string}
73
+ */
74
+ export function formatCheck({ findings, counts, excepted = [], baseline }, { paint = painter(), quiet = false, durationMs, maxWarnings } = {}) {
75
+ const shown = quiet ? findings.filter((f) => f.severity === 'error') : findings;
76
+ /** @type {string[]} */
77
+ const lines = [];
78
+ const source = baseline ? (baseline.ref ? `${baseline.ref}${baseline.commit ? ` (${baseline.commit.slice(0, 12)})` : ''}` : baseline.file) : '';
79
+ if (baseline?.findings.length && !quiet) {
80
+ lines.push('', paint('dim', `Already in the baseline, ${source}:`), ...byFileLines(baseline.findings, paint, true));
81
+ if (shown.length) lines.push('', paint('bold', 'New:'));
82
+ }
83
+ lines.push(...byFileLines(shown, paint));
60
84
 
61
85
  lines.push('');
62
86
  if (excepted.length) lines.push(paint('dim', `${plural(excepted.length, 'finding')} excepted by sdk-tools.exceptions.json (see --json)`));
87
+ if (baseline) {
88
+ const old = baseline.counts.errors + baseline.counts.warnings;
89
+ lines.push(paint('dim', `${plural(old, 'finding')} already in the baseline ${source}, not counted`));
90
+ }
63
91
  const total = counts.errors + counts.warnings;
92
+ const fresh = baseline ? 'new ' : '';
64
93
  if (!total) {
65
- lines.push(`${paint('green', '✔')} No problems${durationMs !== undefined ? paint('dim', ` (${(durationMs / 1000).toFixed(1)}s)`) : ''}`);
94
+ lines.push(`${paint('green', '✔')} No ${fresh}problems${durationMs !== undefined ? paint('dim', ` (${(durationMs / 1000).toFixed(1)}s)`) : ''}`);
66
95
  return lines.join('\n').replace(/^\n/, '');
67
96
  }
68
97
  const failed = counts.errors > 0 || (maxWarnings !== undefined && counts.warnings > maxWarnings);
@@ -72,7 +101,7 @@ export function formatCheck({ findings, counts, excepted = [] }, { paint = paint
72
101
  counts.warnings ? paint('yellow', plural(counts.warnings, 'warning')) : plural(0, 'warning'),
73
102
  ];
74
103
  lines.push(
75
- `${mark} ${plural(total, 'problem')} (${parts.join(', ')})${durationMs !== undefined ? paint('dim', ` in ${(durationMs / 1000).toFixed(1)}s`) : ''}`,
104
+ `${mark} ${plural(total, `${fresh}problem`)} (${parts.join(', ')})${durationMs !== undefined ? paint('dim', ` in ${(durationMs / 1000).toFixed(1)}s`) : ''}`,
76
105
  );
77
106
 
78
107
  /** @type {Map<string, number>} */
package/src/types.d.ts CHANGED
@@ -31,6 +31,22 @@ export interface CheckResult {
31
31
  counts: Counts;
32
32
  /** Findings an `sdk-tools.exceptions.json` entry covers: listed, never counted. */
33
33
  excepted?: ExceptedFinding[];
34
+ /**
35
+ * `check --baseline` or `--since`: the findings the baseline already had (per rule and file, as
36
+ * many as it held). They are listed, never counted: `findings` and `counts` hold the new ones.
37
+ */
38
+ baseline?: CheckBaseline;
39
+ }
40
+
41
+ /** Where a `check` baseline came from and the findings it already had. */
42
+ export interface CheckBaseline {
43
+ /** `--baseline`: the file, as given. */
44
+ file?: string;
45
+ /** `--since`: the git ref, as given, and the commit it named. */
46
+ ref?: string;
47
+ commit?: string;
48
+ findings: Finding[];
49
+ counts: Counts;
34
50
  }
35
51
 
36
52
  /** One entry of the app-root `sdk-tools.exceptions.json` (approved through PR review). */