@raintree-technology/hig-doctor-core 0.1.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.
@@ -0,0 +1,354 @@
1
+ // benchmark.ts — precision/recall corpus for the rule engine.
2
+ //
3
+ // Each case is a small source file plus the exact set of concern rule IDs it
4
+ // should produce. "bad" fixtures assert true positives (a missing one is a
5
+ // false negative); "good" fixtures assert the absence of concerns (any concern
6
+ // is a false positive). The harness scores per-rule and overall so regressions
7
+ // in either direction are visible. docs/benchmark.md is generated from this.
8
+ import { analyzeFile } from "./analyze";
9
+
10
+ export interface BenchmarkCase {
11
+ id: string;
12
+ framework: string;
13
+ file: string;
14
+ kind: "good" | "bad";
15
+ code: string;
16
+ /** Concern rule IDs this fixture must produce (empty for good fixtures). */
17
+ expect: string[];
18
+ }
19
+
20
+ export const BENCHMARK_CASES: BenchmarkCase[] = [
21
+ // ── Swift / SwiftUI ────────────────────────────────────────────
22
+ {
23
+ id: "swift-color-bad",
24
+ framework: "swift",
25
+ file: "BadColors.swift",
26
+ kind: "bad",
27
+ code: `struct V: View {
28
+ var body: some View {
29
+ Text("Hi").foregroundColor(.red)
30
+ Rectangle().foregroundColor(.blue)
31
+ }
32
+ }`,
33
+ expect: ["swift/hardcoded-color", "swift/hardcoded-color"],
34
+ },
35
+ {
36
+ id: "swift-color-good",
37
+ framework: "swift",
38
+ file: "GoodColors.swift",
39
+ kind: "good",
40
+ code: `struct V: View {
41
+ var body: some View {
42
+ Text("Hi").foregroundStyle(.primary)
43
+ Rectangle().foregroundColor(Color("BrandAccent"))
44
+ }
45
+ }`,
46
+ expect: [],
47
+ },
48
+ {
49
+ id: "swift-nav-bad",
50
+ framework: "swift",
51
+ file: "BadNav.swift",
52
+ kind: "bad",
53
+ code: `struct Root: View {
54
+ var body: some View {
55
+ NavigationView {
56
+ Text("Legacy")
57
+ }
58
+ }
59
+ }`,
60
+ expect: ["swift/navigation-view-deprecated"],
61
+ },
62
+ {
63
+ id: "swift-nav-good",
64
+ framework: "swift",
65
+ file: "GoodNav.swift",
66
+ kind: "good",
67
+ code: `struct Root: View {
68
+ var body: some View {
69
+ NavigationStack {
70
+ Text("Modern")
71
+ }
72
+ }
73
+ }`,
74
+ expect: [],
75
+ },
76
+ {
77
+ id: "swift-typography-bad",
78
+ framework: "swift",
79
+ file: "BadType.swift",
80
+ kind: "bad",
81
+ code: `Text("Title").font(.system(size: 24))`,
82
+ expect: ["swift/hardcoded-font-size"],
83
+ },
84
+ {
85
+ id: "swift-typography-good",
86
+ framework: "swift",
87
+ file: "GoodType.swift",
88
+ kind: "good",
89
+ code: `Text("Title").font(.title)`,
90
+ expect: [],
91
+ },
92
+
93
+ // ── Web / React ────────────────────────────────────────────────
94
+ {
95
+ id: "web-img-bad",
96
+ framework: "web",
97
+ file: "BadImg.tsx",
98
+ kind: "bad",
99
+ code: `export const Hero = () => <img src="/hero.png" />;`,
100
+ expect: ["web/missing-alt"],
101
+ },
102
+ {
103
+ id: "web-img-good",
104
+ framework: "web",
105
+ file: "GoodImg.tsx",
106
+ kind: "good",
107
+ code: `export const Hero = () => <img src="/hero.png" alt="Product hero shot" />;`,
108
+ expect: [],
109
+ },
110
+ {
111
+ id: "web-clickable-bad",
112
+ framework: "web",
113
+ file: "BadClick.tsx",
114
+ kind: "bad",
115
+ code: `export const Row = () => <div onClick={() => open()}>Open</div>;`,
116
+ expect: ["web/div-with-on-click-no-role"],
117
+ },
118
+ {
119
+ id: "web-clickable-good",
120
+ framework: "web",
121
+ file: "GoodClick.tsx",
122
+ kind: "good",
123
+ code: `export const Row = () => <button onClick={() => open()}>Open</button>;`,
124
+ expect: [],
125
+ },
126
+ {
127
+ id: "web-tabindex-bad",
128
+ framework: "web",
129
+ file: "BadTab.tsx",
130
+ kind: "bad",
131
+ code: `export const F = () => <input tabIndex={3} />;`,
132
+ expect: ["web/positive-tabindex"],
133
+ },
134
+ {
135
+ id: "web-link-good",
136
+ framework: "web",
137
+ file: "GoodLink.tsx",
138
+ kind: "good",
139
+ code: `export const L = () => <a href="/pricing">See pricing plans</a>;`,
140
+ expect: [],
141
+ },
142
+
143
+ // ── CSS ────────────────────────────────────────────────────────
144
+ {
145
+ id: "css-outline-bad",
146
+ framework: "css",
147
+ file: "bad.css",
148
+ kind: "bad",
149
+ code: `button:focus { outline: none; }`,
150
+ expect: ["css/outline-none"],
151
+ },
152
+ {
153
+ id: "css-outline-good",
154
+ framework: "css",
155
+ file: "good.css",
156
+ kind: "good",
157
+ code: `button:focus-visible { outline: 2px solid Highlight; }`,
158
+ expect: [],
159
+ },
160
+ {
161
+ id: "css-important-bad",
162
+ framework: "css",
163
+ file: "important.css",
164
+ kind: "bad",
165
+ code: `.a { color: var(--fg) !important; }`,
166
+ expect: ["css/important-usage"],
167
+ },
168
+ {
169
+ id: "css-logical-good",
170
+ framework: "css",
171
+ file: "logical.css",
172
+ kind: "good",
173
+ code: `.a { text-align: start; margin-inline-start: 8px; }`,
174
+ expect: [],
175
+ },
176
+
177
+ // ── HTML ───────────────────────────────────────────────────────
178
+ {
179
+ id: "html-viewport-bad",
180
+ framework: "web",
181
+ file: "bad.html",
182
+ kind: "bad",
183
+ code: `<!doctype html><html lang="en"><head><meta name="viewport" content="width=device-width, user-scalable=no"></head><body><h1>Hi</h1></body></html>`,
184
+ expect: ["web/user-scalable-no"],
185
+ },
186
+ {
187
+ id: "html-good",
188
+ framework: "web",
189
+ file: "good.html",
190
+ kind: "good",
191
+ code: `<!doctype html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><h1>Hi</h1></body></html>`,
192
+ expect: [],
193
+ },
194
+
195
+ // ── AST-tier precision cases (regex would misjudge these) ──────
196
+ {
197
+ id: "web-img-spread-good",
198
+ framework: "web",
199
+ file: "SpreadImg.tsx",
200
+ kind: "good",
201
+ code: `export const Avatar = (props) => <img {...props} />;`,
202
+ expect: [], // spread props may carry alt — the AST tier abstains
203
+ },
204
+ {
205
+ id: "web-img-multiline-bad",
206
+ framework: "web",
207
+ file: "MultilineImg.tsx",
208
+ kind: "bad",
209
+ code: `export const Hero = () => (
210
+ <img
211
+ src="/hero.png"
212
+ width={640}
213
+ />
214
+ );`,
215
+ expect: ["web/missing-alt"],
216
+ },
217
+ {
218
+ id: "web-div-nested-gt-bad",
219
+ framework: "web",
220
+ file: "NestedGt.tsx",
221
+ kind: "bad",
222
+ code: `export const Row = () => (
223
+ <div onClick={() => select(a > b ? a : b)}>
224
+ Pick
225
+ </div>
226
+ );`,
227
+ expect: ["web/div-with-on-click-no-role"],
228
+ },
229
+ {
230
+ id: "web-span-keyboard-good",
231
+ framework: "web",
232
+ file: "AccessibleSpan.tsx",
233
+ kind: "good",
234
+ code: `export const Row = () => (
235
+ <span role="button" tabIndex={0} onKeyDown={onKey} onClick={onClick}>
236
+ Pick
237
+ </span>
238
+ );`,
239
+ expect: [], // AST tier abstains: role + tabIndex + keydown make it operable
240
+ },
241
+ {
242
+ id: "swift-image-labeled-good",
243
+ framework: "swift",
244
+ file: "LabeledImage.swift",
245
+ kind: "good",
246
+ code: `Image(systemName: "star")
247
+ .resizable()
248
+ .accessibilityLabel("Favorite")`,
249
+ expect: [], // structural analysis sees the chained label
250
+ },
251
+ {
252
+ id: "swift-image-bare-bad",
253
+ framework: "swift",
254
+ file: "BareImage.swift",
255
+ kind: "bad",
256
+ code: `Image(systemName: "star").frame(width: 20, height: 20)`,
257
+ expect: ["swift/image-without-a11y"],
258
+ },
259
+
260
+ // ── Cross-platform ─────────────────────────────────────────────
261
+ {
262
+ id: "compose-clickable-bad",
263
+ framework: "compose",
264
+ file: "Bad.kt",
265
+ kind: "bad",
266
+ code: `Box(Modifier.clickable { open() }) { Text("Open") }`,
267
+ expect: ["compose/clickable-without-role"],
268
+ },
269
+ {
270
+ id: "android-image-bad",
271
+ framework: "android-xml",
272
+ file: "bad.xml",
273
+ kind: "bad",
274
+ code: `<ImageView android:src="@drawable/logo" android:layout_width="48dp" android:layout_height="48dp" />`,
275
+ expect: ["android-xml/image-view-without-content-description"],
276
+ },
277
+ {
278
+ id: "flutter-color-bad",
279
+ framework: "flutter",
280
+ file: "bad.dart",
281
+ kind: "bad",
282
+ code: `Container(color: Color(0xFFFF0000));`,
283
+ expect: ["flutter/hardcoded-color"],
284
+ },
285
+ ];
286
+
287
+ export interface RuleScore {
288
+ ruleId: string;
289
+ tp: number;
290
+ fp: number;
291
+ fn: number;
292
+ precision: number;
293
+ recall: number;
294
+ }
295
+
296
+ export interface BenchmarkReport {
297
+ perRule: RuleScore[];
298
+ overall: { tp: number; fp: number; fn: number; precision: number; recall: number };
299
+ falsePositives: Array<{ case: string; ruleId: string; line: number }>;
300
+ falseNegatives: Array<{ case: string; ruleId: string }>;
301
+ }
302
+
303
+ function ratio(n: number, d: number): number {
304
+ return d === 0 ? 1 : Math.round((n / d) * 1000) / 1000;
305
+ }
306
+
307
+ export function runBenchmark(cases: BenchmarkCase[] = BENCHMARK_CASES): BenchmarkReport {
308
+ const tp = new Map<string, number>();
309
+ const fp = new Map<string, number>();
310
+ const fn = new Map<string, number>();
311
+ const bump = (m: Map<string, number>, k: string) => m.set(k, (m.get(k) ?? 0) + 1);
312
+ const falsePositives: BenchmarkReport["falsePositives"] = [];
313
+ const falseNegatives: BenchmarkReport["falseNegatives"] = [];
314
+
315
+ for (const c of cases) {
316
+ const concerns = analyzeFile(c.code, c.file).filter(m => m.type === "concern");
317
+ // Multiset comparison so a fixture that expects two of a rule and only
318
+ // produces one is scored as one TP + one FN.
319
+ const expected = [...c.expect];
320
+ for (const match of concerns) {
321
+ const idx = expected.indexOf(match.ruleId);
322
+ if (idx !== -1) {
323
+ expected.splice(idx, 1);
324
+ bump(tp, match.ruleId);
325
+ } else {
326
+ bump(fp, match.ruleId);
327
+ falsePositives.push({ case: c.id, ruleId: match.ruleId, line: match.line });
328
+ }
329
+ }
330
+ for (const missed of expected) {
331
+ bump(fn, missed);
332
+ falseNegatives.push({ case: c.id, ruleId: missed });
333
+ }
334
+ }
335
+
336
+ const ruleIds = new Set([...tp.keys(), ...fp.keys(), ...fn.keys()]);
337
+ const perRule: RuleScore[] = [...ruleIds].sort().map(ruleId => {
338
+ const t = tp.get(ruleId) ?? 0;
339
+ const f = fp.get(ruleId) ?? 0;
340
+ const n = fn.get(ruleId) ?? 0;
341
+ return { ruleId, tp: t, fp: f, fn: n, precision: ratio(t, t + f), recall: ratio(t, t + n) };
342
+ });
343
+
344
+ const sum = (m: Map<string, number>) => [...m.values()].reduce((a, b) => a + b, 0);
345
+ const T = sum(tp);
346
+ const F = sum(fp);
347
+ const N = sum(fn);
348
+ return {
349
+ perRule,
350
+ overall: { tp: T, fp: F, fn: N, precision: ratio(T, T + F), recall: ratio(T, T + N) },
351
+ falsePositives,
352
+ falseNegatives,
353
+ };
354
+ }
@@ -0,0 +1,64 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { ScanCache, CACHE_FILENAME } from "./cache";
6
+ import { audit } from "./audit";
7
+ import { detectPatterns } from "./patterns";
8
+
9
+ describe("ScanCache", () => {
10
+ test("hits on identical (path, content), misses when content changes", async () => {
11
+ const cache = await ScanCache.load(join(tmpdir(), "nonexistent-cache.json"));
12
+ const matches = detectPatterns(".a { text-align: left; }", "a.css");
13
+ expect(cache.get("a.css", ".a { text-align: left; }")).toBeNull();
14
+ cache.set("a.css", ".a { text-align: left; }", matches);
15
+ expect(cache.get("a.css", ".a { text-align: left; }")).toEqual(matches);
16
+ // Changed content → miss.
17
+ expect(cache.get("a.css", ".a { text-align: right; }")).toBeNull();
18
+ // Same content, different path → miss (findings carry the path).
19
+ expect(cache.get("b.css", ".a { text-align: left; }")).toBeNull();
20
+ expect(cache.stats.hits).toBe(1);
21
+ expect(cache.stats.misses).toBe(3);
22
+ });
23
+
24
+ test("persists and reloads only touched entries; namespace invalidates", async () => {
25
+ const dir = await mkdtemp(join(tmpdir(), "hig-cache-"));
26
+ const path = join(dir, CACHE_FILENAME);
27
+ try {
28
+ const cache = await ScanCache.load(path);
29
+ cache.set("a.css", "x", detectPatterns("x", "a.css"));
30
+ cache.set("stale.css", "y", []);
31
+ await cache.save(path, new Set([cache.keyOf("a.css", "x")]));
32
+
33
+ const reloaded = await ScanCache.load(path);
34
+ expect(reloaded.get("a.css", "x")).not.toBeNull();
35
+ // stale.css was not in the touched set, so it wasn't persisted.
36
+ expect(reloaded.get("stale.css", "y")).toBeNull();
37
+
38
+ // A namespace change (simulated) drops all entries.
39
+ const raw = JSON.parse(await readFile(path, "utf-8"));
40
+ raw.namespace = "v0.rules1";
41
+ await writeFile(path, JSON.stringify(raw));
42
+ const invalid = await ScanCache.load(path);
43
+ expect(invalid.get("a.css", "x")).toBeNull();
44
+ } finally {
45
+ await rm(dir, { recursive: true });
46
+ }
47
+ });
48
+
49
+ test("audit --cache produces identical findings and reports hits on re-run", async () => {
50
+ const dir = await mkdtemp(join(tmpdir(), "hig-cache-audit-"));
51
+ try {
52
+ await writeFile(join(dir, "V.swift"), ".foregroundColor(.red)\n");
53
+ const first = await audit(dir, undefined, { cache: true });
54
+ expect(first.cacheStats).toEqual({ hits: 0, misses: 1 });
55
+ const second = await audit(dir, undefined, { cache: true });
56
+ expect(second.cacheStats).toEqual({ hits: 1, misses: 0 });
57
+ // Cached results match a fresh (uncached) analysis.
58
+ const fresh = await audit(dir, undefined, { cache: false });
59
+ expect(second.allMatches.map(m => m.ruleId).sort()).toEqual(fresh.allMatches.map(m => m.ruleId).sort());
60
+ } finally {
61
+ await rm(dir, { recursive: true });
62
+ }
63
+ });
64
+ });
package/src/cache.ts ADDED
@@ -0,0 +1,83 @@
1
+ // cache.ts — content-hash cache for local scans.
2
+ //
3
+ // Analysis is a pure function of (path, content, ruleset), so re-scanning a
4
+ // project only needs to re-analyze files whose content changed. The cache keys
5
+ // each file's findings by a hash of its path + content and is namespaced by the
6
+ // engine's rule count and a cache-format version, so a rule change or a cache
7
+ // schema change transparently invalidates every stale entry.
8
+ import { createHash } from "node:crypto";
9
+ import { readFile, writeFile } from "node:fs/promises";
10
+ import { RULE_COUNT, type PatternMatch } from "./patterns";
11
+
12
+ const CACHE_VERSION = 2; // bump when analysis semantics change independent of rule count
13
+ export const CACHE_FILENAME = ".hig-cache.json";
14
+
15
+ interface CacheFile {
16
+ namespace: string;
17
+ entries: Record<string, PatternMatch[]>;
18
+ }
19
+
20
+ function namespace(): string {
21
+ return `v${CACHE_VERSION}.rules${RULE_COUNT}`;
22
+ }
23
+
24
+ function keyFor(path: string, content: string): string {
25
+ return createHash("sha256").update(path).update("\0").update(content).digest("hex").slice(0, 24);
26
+ }
27
+
28
+ export class ScanCache {
29
+ private entries: Map<string, PatternMatch[]>;
30
+ private hits = 0;
31
+ private misses = 0;
32
+
33
+ private constructor(entries: Map<string, PatternMatch[]>) {
34
+ this.entries = entries;
35
+ }
36
+
37
+ static async load(path: string): Promise<ScanCache> {
38
+ try {
39
+ const raw = await readFile(path, "utf-8");
40
+ const parsed = JSON.parse(raw) as CacheFile;
41
+ // A namespace mismatch means the ruleset or cache format changed — drop it.
42
+ if (parsed.namespace === namespace() && parsed.entries) {
43
+ return new ScanCache(new Map(Object.entries(parsed.entries)));
44
+ }
45
+ } catch {
46
+ // Missing or unreadable cache → start empty.
47
+ }
48
+ return new ScanCache(new Map());
49
+ }
50
+
51
+ /** Return cached findings for this file, or null on a miss. */
52
+ get(path: string, content: string): PatternMatch[] | null {
53
+ const hit = this.entries.get(keyFor(path, content));
54
+ if (hit) {
55
+ this.hits++;
56
+ return hit;
57
+ }
58
+ this.misses++;
59
+ return null;
60
+ }
61
+
62
+ set(path: string, content: string, matches: PatternMatch[]): void {
63
+ this.entries.set(keyFor(path, content), matches);
64
+ }
65
+
66
+ get stats(): { hits: number; misses: number } {
67
+ return { hits: this.hits, misses: this.misses };
68
+ }
69
+
70
+ /** Persist only the keys touched this run, so deleted files don't accumulate. */
71
+ async save(path: string, touched: Set<string>): Promise<void> {
72
+ const entries: Record<string, PatternMatch[]> = {};
73
+ for (const [k, v] of this.entries) {
74
+ if (touched.has(k)) entries[k] = v;
75
+ }
76
+ const file: CacheFile = { namespace: namespace(), entries };
77
+ await writeFile(path, JSON.stringify(file));
78
+ }
79
+
80
+ keyOf(path: string, content: string): string {
81
+ return keyFor(path, content);
82
+ }
83
+ }
@@ -0,0 +1,51 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { categorizeMatches } from "./categorizer";
3
+ import type { PatternMatch } from "./patterns";
4
+
5
+ describe("categorizeMatches", () => {
6
+ test("groups matches by HIG skill name", () => {
7
+ const matches: PatternMatch[] = [
8
+ { ruleId: "test/rule", engine: "regex", category: "foundations", subcategory: "color", type: "concern", pattern: "hardcodedColor", line: 1, lineContent: ".foregroundColor(.red)", file: "A.swift" },
9
+ { ruleId: "test/rule", engine: "regex", category: "foundations", subcategory: "typography", type: "positive", pattern: "dynamicTypeStyle", line: 2, lineContent: ".font(.body)", file: "A.swift" },
10
+ { ruleId: "test/rule", engine: "regex", category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "TabView", line: 3, lineContent: "TabView {", file: "B.swift" },
11
+ ];
12
+ const categories = categorizeMatches(matches);
13
+ expect(categories.length).toBe(2);
14
+ const foundations = categories.find(c => c.skillName === "hig-foundations");
15
+ expect(foundations).toBeDefined();
16
+ expect(foundations!.concerns).toBe(1);
17
+ expect(foundations!.positives).toBe(1);
18
+ expect(foundations!.label).toBe("Foundations");
19
+ expect(foundations!.files).toContain("A.swift");
20
+ const layout = categories.find(c => c.skillName === "hig-components-layout");
21
+ expect(layout).toBeDefined();
22
+ expect(layout!.patterns).toBe(1);
23
+ expect(layout!.label).toBe("Layout & Navigation");
24
+ });
25
+
26
+ test("sorts categories by match count descending", () => {
27
+ const matches: PatternMatch[] = [
28
+ { ruleId: "test/rule", engine: "regex", category: "foundations", subcategory: "color", type: "concern", pattern: "hardcodedColor", line: 1, lineContent: ".foregroundColor(.red)", file: "A.swift" },
29
+ { ruleId: "test/rule", engine: "regex", category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "TabView", line: 3, lineContent: "TabView {", file: "B.swift" },
30
+ { ruleId: "test/rule", engine: "regex", category: "components-layout", subcategory: "navigation", type: "pattern", pattern: "NavigationStack", line: 4, lineContent: "NavigationStack {", file: "B.swift" },
31
+ { ruleId: "test/rule", engine: "regex", category: "components-layout", subcategory: "layout", type: "pattern", pattern: "List", line: 5, lineContent: "List {", file: "C.swift" },
32
+ ];
33
+ const categories = categorizeMatches(matches);
34
+ expect(categories[0].skillName).toBe("hig-components-layout");
35
+ expect(categories[1].skillName).toBe("hig-foundations");
36
+ });
37
+
38
+ test("counts files per category", () => {
39
+ const matches: PatternMatch[] = [
40
+ { ruleId: "test/rule", engine: "regex", category: "foundations", subcategory: "color", type: "concern", pattern: "hardcodedColor", line: 1, lineContent: ".foregroundColor(.red)", file: "A.swift" },
41
+ { ruleId: "test/rule", engine: "regex", category: "foundations", subcategory: "color", type: "concern", pattern: "hardcodedColor", line: 2, lineContent: ".foregroundColor(.blue)", file: "B.swift" },
42
+ ];
43
+ const categories = categorizeMatches(matches);
44
+ expect(categories[0].fileCount).toBe(2);
45
+ });
46
+
47
+ test("returns empty array for no matches", () => {
48
+ const categories = categorizeMatches([]);
49
+ expect(categories.length).toBe(0);
50
+ });
51
+ });
@@ -0,0 +1,98 @@
1
+ // categorizer.ts
2
+ import type { PatternMatch } from "./patterns";
3
+
4
+ export interface CategorySummary {
5
+ skillName: string;
6
+ category: string;
7
+ label: string;
8
+ matches: PatternMatch[];
9
+ concerns: number;
10
+ positives: number;
11
+ patterns: number;
12
+ critical: number;
13
+ serious: number;
14
+ moderate: number;
15
+ fileCount: number;
16
+ files: string[];
17
+ }
18
+
19
+ const CATEGORY_TO_SKILL: Record<string, string> = {
20
+ "foundations": "hig-foundations",
21
+ "components-layout": "hig-components-layout",
22
+ "components-selection": "hig-components-selection",
23
+ "components-actions": "hig-components-actions",
24
+ "components-presentation": "hig-components-presentation",
25
+ "components-textinput": "hig-components-textinput",
26
+ "components-media": "hig-components-media",
27
+ "components-controls": "hig-components-controls",
28
+ "components-menus": "hig-components-menus",
29
+ "components-dialogs": "hig-components-dialogs",
30
+ "components-search": "hig-components-search",
31
+ "components-status": "hig-components-status",
32
+ "components-content": "hig-components-content",
33
+ "components-system": "hig-components-system",
34
+ "patterns": "hig-patterns",
35
+ "platforms": "hig-platforms",
36
+ "technologies": "hig-technologies",
37
+ "inputs": "hig-inputs",
38
+ };
39
+
40
+ const CATEGORY_LABELS: Record<string, string> = {
41
+ "hig-foundations": "Foundations",
42
+ "hig-components-layout": "Layout & Navigation",
43
+ "hig-components-selection": "Selection Controls",
44
+ "hig-components-actions": "Actions",
45
+ "hig-components-presentation": "Presentation",
46
+ "hig-components-textinput": "Text Input",
47
+ "hig-components-media": "Media",
48
+ "hig-components-controls": "Controls",
49
+ "hig-components-menus": "Menus & Actions",
50
+ "hig-components-dialogs": "Dialogs & Presentations",
51
+ "hig-components-search": "Search & Navigation",
52
+ "hig-components-status": "Status & Progress",
53
+ "hig-components-content": "Content Display",
54
+ "hig-components-system": "System Integration",
55
+ "hig-patterns": "Interaction Patterns",
56
+ "hig-inputs": "Input Methods",
57
+ "hig-technologies": "Apple Technologies",
58
+ "hig-platforms": "Platform Adaptation",
59
+ };
60
+
61
+ export function categorizeMatches(matches: PatternMatch[]): CategorySummary[] {
62
+ if (matches.length === 0) return [];
63
+
64
+ const grouped = new Map<string, PatternMatch[]>();
65
+
66
+ for (const match of matches) {
67
+ const skillName = CATEGORY_TO_SKILL[match.category] || `hig-${match.category}`;
68
+ if (!grouped.has(skillName)) {
69
+ grouped.set(skillName, []);
70
+ }
71
+ grouped.get(skillName)!.push(match);
72
+ }
73
+
74
+ const categories: CategorySummary[] = [];
75
+
76
+ for (const [skillName, skillMatches] of grouped) {
77
+ const files = [...new Set(skillMatches.map(m => m.file))];
78
+ const concerns = skillMatches.filter(m => m.type === "concern");
79
+ categories.push({
80
+ skillName,
81
+ category: skillMatches[0].category,
82
+ label: CATEGORY_LABELS[skillName] ?? skillName,
83
+ matches: skillMatches,
84
+ concerns: concerns.length,
85
+ positives: skillMatches.filter(m => m.type === "positive").length,
86
+ patterns: skillMatches.filter(m => m.type === "pattern").length,
87
+ critical: concerns.filter(m => m.severity === "critical").length,
88
+ serious: concerns.filter(m => m.severity === "serious").length,
89
+ moderate: concerns.filter(m => m.severity === "moderate").length,
90
+ fileCount: files.length,
91
+ files,
92
+ });
93
+ }
94
+
95
+ categories.sort((a, b) => b.matches.length - a.matches.length);
96
+
97
+ return categories;
98
+ }