@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,121 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { audit } from "./audit";
3
+ import { mkdtemp, writeFile, mkdir, rm } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+
7
+ describe("audit", () => {
8
+ test("audits a Swift project", async () => {
9
+ const dir = await mkdtemp(join(tmpdir(), "hig-audit-"));
10
+ try {
11
+ await writeFile(join(dir, "ContentView.swift"), `
12
+ import SwiftUI
13
+
14
+ struct ContentView: View {
15
+ var body: some View {
16
+ TabView {
17
+ Text("Hello")
18
+ .foregroundColor(.red)
19
+ .font(.system(size: 14))
20
+ }
21
+ }
22
+ }
23
+ `);
24
+ const result = await audit(dir);
25
+ expect(result.markdown).toContain("# HIG Audit");
26
+ expect(result.categories.length).toBeGreaterThan(0);
27
+ expect(result.scanResult.swiftFiles.length).toBe(1);
28
+ expect(result.scanResult.frameworks).toContain("swiftui");
29
+
30
+ const foundations = result.categories.find(c => c.skillName === "hig-foundations");
31
+ expect(foundations).toBeDefined();
32
+ expect(foundations!.concerns).toBeGreaterThan(0);
33
+ } finally {
34
+ await rm(dir, { recursive: true });
35
+ }
36
+ });
37
+
38
+ test("audits a web/React project", async () => {
39
+ const dir = await mkdtemp(join(tmpdir(), "hig-web-"));
40
+ try {
41
+ await writeFile(join(dir, "next.config.ts"), "export default {}");
42
+ await writeFile(join(dir, "package.json"), '{"dependencies":{"react":"^19","next":"^16"}}');
43
+ await writeFile(join(dir, "Header.tsx"), `
44
+ "use client"
45
+ export function Header() {
46
+ return (
47
+ <header>
48
+ <nav aria-label="Main">
49
+ <a href="/" aria-current="page">Home</a>
50
+ </nav>
51
+ <button aria-label="Menu" aria-expanded={open}>
52
+ <span className="sr-only">Open menu</span>
53
+ </button>
54
+ </header>
55
+ )
56
+ }
57
+ `);
58
+ await writeFile(join(dir, "globals.css"), `
59
+ :root {
60
+ --background: 225 10% 6%;
61
+ --foreground: 0 0% 95%;
62
+ }
63
+ body {
64
+ font-family: -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
65
+ font-size: 1.0625rem;
66
+ }
67
+ @media (prefers-reduced-motion: reduce) {
68
+ * { animation: none !important; }
69
+ }
70
+ @media (prefers-color-scheme: dark) {
71
+ :root { --background: 0 0% 5%; }
72
+ }
73
+ button:focus-visible {
74
+ outline: 3px solid var(--ring);
75
+ }
76
+ `);
77
+ const result = await audit(dir);
78
+ expect(result.scanResult.frameworks).toContain("nextjs");
79
+ expect(result.scanResult.codeFiles.length).toBeGreaterThanOrEqual(1);
80
+ expect(result.scanResult.styleFiles.length).toBe(1); // globals.css
81
+ expect(result.categories.length).toBeGreaterThan(0);
82
+
83
+ // Should find accessibility positives
84
+ const foundations = result.categories.find(c => c.skillName === "hig-foundations");
85
+ expect(foundations).toBeDefined();
86
+ expect(foundations!.positives).toBeGreaterThan(0);
87
+
88
+ // Should find layout patterns
89
+ const layout = result.categories.find(c => c.skillName === "hig-components-layout");
90
+ expect(layout).toBeDefined();
91
+ } finally {
92
+ await rm(dir, { recursive: true });
93
+ }
94
+ });
95
+
96
+ test("handles empty project gracefully", async () => {
97
+ const dir = await mkdtemp(join(tmpdir(), "hig-empty-"));
98
+ try {
99
+ const result = await audit(dir);
100
+ expect(result.scanResult.codeFiles.length).toBe(0);
101
+ expect(result.categories.length).toBe(0);
102
+ expect(result.markdown).toContain("# HIG Audit");
103
+ } finally {
104
+ await rm(dir, { recursive: true });
105
+ }
106
+ });
107
+
108
+ test("loads skill content when skills directory available", async () => {
109
+ const dir = await mkdtemp(join(tmpdir(), "hig-skills-"));
110
+ try {
111
+ await writeFile(join(dir, "View.swift"), `.foregroundColor(.red)`);
112
+ const skillsDir = join(import.meta.dir, "..", "..", "..", "skills");
113
+ const result = await audit(dir, skillsDir);
114
+ const foundations = result.categories.find(c => c.skillName === "hig-foundations");
115
+ expect(foundations).toBeDefined();
116
+ expect(result.markdown).not.toContain("*Load reference from skill: hig-foundations*");
117
+ } finally {
118
+ await rm(dir, { recursive: true });
119
+ }
120
+ });
121
+ });
package/src/audit.ts ADDED
@@ -0,0 +1,150 @@
1
+ // audit.ts — Full pipeline: scan → detect → categorize → generate markdown
2
+ import { scanProject, type ScanResult } from "./scanner";
3
+ import { type PatternMatch } from "./patterns";
4
+ import { analyzeFile } from "./analyze";
5
+ import { categorizeMatches, type CategorySummary } from "./categorizer";
6
+ import { generateAuditMarkdown, loadSkillContent } from "./audit-generator";
7
+ import { applyConfig, loadConfig } from "./config";
8
+ import { applyBaseline, loadBaseline } from "./baseline";
9
+ import { ScanCache, CACHE_FILENAME } from "./cache";
10
+ import { resolve, join } from "node:path";
11
+ import { access } from "node:fs/promises";
12
+ import { fileURLToPath } from "node:url";
13
+
14
+ // Directory of this module, resolved cross-runtime (Bun has import.meta.dir,
15
+ // Node does not). Used only to locate the bundled skills/ folder in dev.
16
+ const moduleDir = fileURLToPath(new URL(".", import.meta.url));
17
+
18
+ export interface AuditOptions {
19
+ /** Path globs (relative to the audited directory) to exclude from scanning. */
20
+ exclude?: string[];
21
+ /** Explicit path to a hig-doctor.config.json (default: discovered in the audited directory). */
22
+ configPath?: string;
23
+ /** Skip config discovery entirely. */
24
+ noConfig?: boolean;
25
+ /** Explicit path to a .hig-baseline.json (default: discovered in the audited directory). */
26
+ baselinePath?: string;
27
+ /** Skip baseline discovery entirely. */
28
+ noBaseline?: boolean;
29
+ /** Enable the content-hash cache under the audited directory (local scans). */
30
+ cache?: boolean;
31
+ }
32
+
33
+ export interface AuditResult {
34
+ scanResult: ScanResult;
35
+ allMatches: PatternMatch[];
36
+ categories: CategorySummary[];
37
+ markdown: string;
38
+ /** Absolute path of the applied config file, or null. */
39
+ configPath: string | null;
40
+ /** Non-fatal config problems (unknown rule IDs etc.). */
41
+ configWarnings: string[];
42
+ /** Absolute path of the applied baseline file, or null. */
43
+ baselinePath: string | null;
44
+ /** Concerns absorbed by the baseline (hidden from results and gating). */
45
+ baselined: number;
46
+ /** Baseline occurrences that no longer match anything — time to re-snapshot. */
47
+ baselineStale: number;
48
+ /** Cache hit/miss counts when the cache is enabled, else null. */
49
+ cacheStats: { hits: number; misses: number } | null;
50
+ }
51
+
52
+ export async function audit(directory: string, skillsDir?: string, options: AuditOptions = {}): Promise<AuditResult> {
53
+ const resolvedDir = resolve(directory);
54
+
55
+ // 1. Load config (unless disabled), merging its ignore globs with caller excludes
56
+ const loaded = options.noConfig
57
+ ? { path: null, config: {}, warnings: [] as string[] }
58
+ : await loadConfig(resolvedDir, options.configPath);
59
+ const exclude = [...(loaded.config.ignore ?? []), ...(options.exclude ?? [])];
60
+
61
+ // 2. Scan project
62
+ const scanResult = await scanProject(resolvedDir, { exclude });
63
+
64
+ // 3. Detect patterns in all source files (code + style + markup), then apply
65
+ // rule settings from the config (off / severity remap / per-path overrides).
66
+ // The optional content-hash cache skips re-analysis of unchanged files.
67
+ const detected: PatternMatch[] = [];
68
+ const allFiles = [...scanResult.codeFiles, ...scanResult.styleFiles, ...scanResult.markupFiles];
69
+ const cachePath = join(resolvedDir, CACHE_FILENAME);
70
+ const cache = options.cache ? await ScanCache.load(cachePath) : null;
71
+ const touched = new Set<string>();
72
+ for (const file of allFiles) {
73
+ let matches = cache?.get(file.relativePath, file.content) ?? null;
74
+ if (matches === null) {
75
+ matches = analyzeFile(file.content, file.relativePath);
76
+ cache?.set(file.relativePath, file.content, matches);
77
+ }
78
+ if (cache) touched.add(cache.keyOf(file.relativePath, file.content));
79
+ detected.push(...matches);
80
+ }
81
+ if (cache) await cache.save(cachePath, touched);
82
+ const configured = applyConfig(detected, loaded.config);
83
+
84
+ // 4. Apply baseline: previously-snapshotted concerns are absorbed so only
85
+ // new violations surface in results and gating
86
+ let allMatches = configured;
87
+ let baselinePath: string | null = null;
88
+ let baselined = 0;
89
+ let baselineStale = 0;
90
+ if (!options.noBaseline) {
91
+ const found = await loadBaseline(resolvedDir, options.baselinePath);
92
+ if (found) {
93
+ const applied = applyBaseline(configured, found.baseline);
94
+ allMatches = applied.kept;
95
+ baselinePath = found.path;
96
+ baselined = applied.baselined;
97
+ baselineStale = applied.stale;
98
+ }
99
+ }
100
+
101
+ // 5. Categorize
102
+ const categories = categorizeMatches(allMatches);
103
+
104
+ // 6. Try to load skill content
105
+ let resolvedSkillsDir: string | null = null;
106
+ const skillContents = new Map<string, string>();
107
+
108
+ if (skillsDir) {
109
+ resolvedSkillsDir = resolve(skillsDir);
110
+ } else {
111
+ // Try to find skills directory relative to common locations
112
+ const candidates = [
113
+ join(resolvedDir, "skills"),
114
+ join(resolvedDir, "..", "skills"),
115
+ join(resolvedDir, "..", "..", "skills"),
116
+ // Relative to this package (for development: packages/core/src → repo root)
117
+ join(moduleDir, "..", "..", "..", "skills"),
118
+ ];
119
+ for (const candidate of candidates) {
120
+ try {
121
+ await access(candidate);
122
+ resolvedSkillsDir = candidate;
123
+ break;
124
+ } catch {}
125
+ }
126
+ }
127
+
128
+ if (resolvedSkillsDir) {
129
+ for (const category of categories) {
130
+ const content = await loadSkillContent(resolvedSkillsDir, category.skillName);
131
+ if (content) skillContents.set(category.skillName, content);
132
+ }
133
+ }
134
+
135
+ // 7. Generate markdown
136
+ const markdown = generateAuditMarkdown(scanResult, categories, resolvedSkillsDir, skillContents);
137
+
138
+ return {
139
+ scanResult,
140
+ allMatches,
141
+ categories,
142
+ markdown,
143
+ configPath: loaded.path,
144
+ configWarnings: loaded.warnings,
145
+ baselinePath,
146
+ baselined,
147
+ baselineStale,
148
+ cacheStats: cache ? cache.stats : null,
149
+ };
150
+ }
@@ -0,0 +1,83 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createBaseline, applyBaseline, parseBaseline, BASELINE_FILENAME } from "./baseline";
6
+ import { audit } from "./audit";
7
+ import type { PatternMatch } from "./patterns";
8
+
9
+ const concern = (over: Partial<PatternMatch>): PatternMatch => ({
10
+ ruleId: "swift/hardcoded-color",
11
+ engine: "regex",
12
+ category: "foundations",
13
+ subcategory: "color",
14
+ type: "concern",
15
+ pattern: "hardcodedColor",
16
+ line: 1,
17
+ lineContent: ".foregroundColor(.red)",
18
+ file: "A.swift",
19
+ severity: "moderate",
20
+ ...over,
21
+ });
22
+
23
+ describe("baseline", () => {
24
+ test("createBaseline counts concern fingerprints, ignores positives", () => {
25
+ const b = createBaseline(
26
+ [concern({}), concern({ line: 9 }), concern({ type: "positive", severity: undefined })],
27
+ "2026-07-21",
28
+ );
29
+ expect(Object.values(b.findings)).toEqual([2]);
30
+ });
31
+
32
+ test("applyBaseline absorbs up to the counted occurrences, content-keyed not line-keyed", () => {
33
+ const baseline = createBaseline([concern({ line: 1 })], "2026-07-21");
34
+ // Same content moved to another line: still absorbed.
35
+ const moved = applyBaseline([concern({ line: 40 })], baseline);
36
+ expect(moved.baselined).toBe(1);
37
+ expect(moved.kept).toEqual([]);
38
+ // A second occurrence beyond the count is NEW.
39
+ const grown = applyBaseline([concern({ line: 1 }), concern({ line: 2 })], baseline);
40
+ expect(grown.baselined).toBe(1);
41
+ expect(grown.kept.length).toBe(1);
42
+ });
43
+
44
+ test("stale counts unmatched baseline entries", () => {
45
+ const baseline = createBaseline([concern({}), concern({ ruleId: "swift/other", pattern: "other" })], "2026-07-21");
46
+ const applied = applyBaseline([concern({})], baseline);
47
+ expect(applied.stale).toBe(1);
48
+ });
49
+
50
+ test("whitespace changes don't break fingerprints", () => {
51
+ const baseline = createBaseline([concern({ lineContent: ".foregroundColor(.red)" })], "2026-07-21");
52
+ const applied = applyBaseline([concern({ lineContent: " .foregroundColor(.red) " })], baseline);
53
+ expect(applied.baselined).toBe(1);
54
+ });
55
+
56
+ test("parseBaseline rejects malformed files", () => {
57
+ expect(() => parseBaseline("{}", "b")).toThrow("not a hig-doctor baseline");
58
+ expect(() => parseBaseline(JSON.stringify({ version: 1, findings: { k: "x" } }), "b")).toThrow("invalid count");
59
+ });
60
+
61
+ test("audit discovers and applies the baseline file", async () => {
62
+ const dir = await mkdtemp(join(tmpdir(), "hig-baseline-"));
63
+ try {
64
+ await writeFile(join(dir, "View.swift"), ".foregroundColor(.red)\n");
65
+ const before = await audit(dir);
66
+ const concerns = before.allMatches.filter(m => m.type === "concern");
67
+ expect(concerns.length).toBeGreaterThan(0);
68
+ await writeFile(
69
+ join(dir, BASELINE_FILENAME),
70
+ JSON.stringify(createBaseline(before.allMatches, "2026-07-21")),
71
+ );
72
+ const after = await audit(dir);
73
+ expect(after.baselinePath).toContain(BASELINE_FILENAME);
74
+ expect(after.baselined).toBe(concerns.length);
75
+ expect(after.allMatches.filter(m => m.type === "concern")).toEqual([]);
76
+ const skipped = await audit(dir, undefined, { noBaseline: true });
77
+ expect(skipped.baselined).toBe(0);
78
+ expect(skipped.allMatches.filter(m => m.type === "concern").length).toBe(concerns.length);
79
+ } finally {
80
+ await rm(dir, { recursive: true });
81
+ }
82
+ });
83
+ });
Binary file
@@ -0,0 +1,29 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { runBenchmark, BENCHMARK_CASES } from "./benchmark";
3
+
4
+ describe("rule engine benchmark", () => {
5
+ const report = runBenchmark();
6
+
7
+ test("good fixtures produce zero false positives", () => {
8
+ // Every FP is a concern that fired on code that should be clean — list them
9
+ // so a regression names the exact fixture and rule.
10
+ expect(report.falsePositives).toEqual([]);
11
+ });
12
+
13
+ test("bad fixtures produce zero false negatives", () => {
14
+ expect(report.falseNegatives).toEqual([]);
15
+ });
16
+
17
+ test("overall precision and recall stay at the published thresholds", () => {
18
+ // Thresholds are the floor the README/benchmark doc quote. Tighten only.
19
+ expect(report.overall.precision).toBeGreaterThanOrEqual(1);
20
+ expect(report.overall.recall).toBeGreaterThanOrEqual(1);
21
+ });
22
+
23
+ test("corpus covers good and bad cases across multiple frameworks", () => {
24
+ const frameworks = new Set(BENCHMARK_CASES.map(c => c.framework));
25
+ expect(frameworks.size).toBeGreaterThanOrEqual(5);
26
+ expect(BENCHMARK_CASES.some(c => c.kind === "good")).toBe(true);
27
+ expect(BENCHMARK_CASES.some(c => c.kind === "bad")).toBe(true);
28
+ });
29
+ });