diff --git a/CHANGELOG.md b/CHANGELOG.md index 59448f6..9d3835e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,18 @@ releases; any change that moves scores is called out here. clones and for docs that reference no code. Score: 1 − 0.5 × the share of drifting docs. Effect on real repos: excalidraw 88 → 87 (a 537-day-old CLAUDE.md); repos with recently edited docs gain a passing check (openai-agents-python 85 → 86, vitest context 87 → 88). +- Deeper Go and Rust checks: + - `types.go-any` (weight 1): `interface{}`/`any` used as a type per 1000 lines of Go product + code. Generic constraints, comments, strings, tests and generated files don't count. 1.0 up to + 2/kloc, falling linearly to 0.7 at 30/kloc. + - `types.rust-unsafe` (weight 1): `unsafe` blocks/fns/impls per 1000 lines of Rust. `-sys` crates + are skipped, and `#![forbid(unsafe_code)]` or `unsafe_code = "forbid"` scores 1. 1.0 up to + 1/kloc, falling to 0.7 at 20/kloc. + - `feedback.cargo-workspace` (weight 1): one cargo workspace reaches every crate. Nested + workspaces and crates in no workspace are flagged; members globs, `exclude`, path dependencies + (implicit members) and cargo-fuzz `fuzz/` crates are understood. + - Score effect: tokio 66 → 65 (9.4 unsafe/kloc), hugo 80 → 78 (15 any/kloc), zap types 100 → 95, + ripgrep 62 → 63 (workspace check passes); ollama, cobra, hyper and codex are unchanged overall. ### Changed diff --git a/README.md b/README.md index a9e699b..0f66afb 100644 --- a/README.md +++ b/README.md @@ -143,10 +143,10 @@ It also: | Category | Weight | Checks | | ------------------ | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Context docs** | 30% | `AGENTS.md` / `CLAUDE.md` / `.cursor/rules` / Copilot / Gemini instructions exist · they list exact build, test and lint commands · they describe architecture and key directories · **not stale**: every referenced path and `npm run` script actually exists · **not drifting** (git history): a doc untouched for 90+ days while 25+ later commits changed the files it names or added/removed files in the dirs it describes · not too long (or too thin) · both `AGENTS.md` and `CLAUDE.md` so every agent is covered · `.cursor/rules/*.mdc` actually apply (frontmatter, globs that match files) · monorepos: large workspace packages have a nested `AGENTS.md` or are mentioned in the root docs | -| **Feedback loops** | 25% | A discoverable test command (package.json `test`, pytest config, `make test`, `cargo test`, `go test`) · linter configured (eslint, biome, oxlint, ruff, flake8, clippy, golangci-lint) · typecheck command (`tsc`, mypy, pyright) · CI config · `--run`: test suite passes and is fast, lint and typecheck pass, `--flaky` flags tests that change result between two runs | +| **Feedback loops** | 25% | A discoverable test command (package.json `test`, pytest config, `make test`, `cargo test`, `go test`) · linter configured (eslint, biome, oxlint, ruff, flake8, clippy, golangci-lint) · typecheck command (`tsc`, mypy, pyright) · CI config · MCP server configs (`.mcp.json`, `.cursor/mcp.json`, `.vscode/mcp.json`) and Claude Code hooks are valid · Rust: one cargo workspace reaches every crate (nested workspaces and orphan crates flagged; path deps and `fuzz/` understood) · `--run`: test suite passes and is fast, lint and typecheck pass, `--flaky` flags tests that change result between two runs | | **Navigability** | 20% | `node_modules`, `.venv`, `dist`, caches ignored (and not committed) · no source files over 1000 lines · no minified/vendored/generated blobs in agent view · shallow directory tree · README | -| **Type safety** | 15% | TypeScript `strict` across root and package tsconfigs (follows `extends`, incl. workspace packages), `any` / `@ts-ignore` / `@ts-nocheck` density · plain JS penalized · Python type-hint coverage of product code + mypy/pyright config · Go/Rust count as compiler-checked | -| **Safety** | 10% | Committed `.env` / keys / credentials files · AWS, GitHub, Slack, Stripe, OpenAI, Anthropic, Google, npm token patterns · dangerous scripts: `rm -rf ~`, `curl \| sh`, force-push, `npm publish` hidden in `build`/`test`, network calls in install hooks | +| **Type safety** | 15% | TypeScript `strict` across root and package tsconfigs (follows `extends`, incl. workspace packages), `any` / `@ts-ignore` / `@ts-nocheck` density · plain JS penalized · Python type-hint coverage of product code + mypy/pyright config · Go/Rust count as compiler-checked · Go `interface{}`/`any` density and Rust `unsafe` density | +| **Safety** | 10% | Committed `.env` / keys / credentials files · AWS, GitHub, Slack, Stripe, OpenAI, Anthropic, Google, npm token patterns · dangerous scripts: `rm -rf ~`, `curl \| sh`, force-push, `npm publish` hidden in `build`/`test`, network calls in install hooks · committed agent permissions (`Bash(*)` allow rules, `bypassPermissions`, Codex `danger-full-access`) | **`--run` executes project code**, so it is opt-in. It runs the test command (timed), the lint command and the typecheck command the report detected (package.json scripts, `make` targets, @@ -280,7 +280,7 @@ whatever `npm run build` does. ## Roadmap -- [ ] Deeper Go and Rust checks (unsafe/`interface{}` density, nested `Cargo.toml` workspaces) and Java/Kotlin support +- [ ] Deeper Go and Rust checks (unsafe/`interface{}` density, nested `Cargo.toml` workspaces) and Java/Kotlin support (Go/Rust done) - [x] `--run` for lint/typecheck too, and flaky-test detection (run twice, compare) - [x] Monorepo awareness: score each workspace package, check nested `AGENTS.md` - [x] Doc staleness via git history (doc untouched while referenced code churned) diff --git a/src/checks/go-rust.ts b/src/checks/go-rust.ts new file mode 100644 index 0000000..949d491 --- /dev/null +++ b/src/checks/go-rust.ts @@ -0,0 +1,335 @@ +import { posix } from 'node:path'; +import type { RepoContext } from '../context.js'; +import type { Check, CheckResult, Finding } from '../types.js'; +import { isAuxiliaryPath, isFixturePath } from '../util/paths.js'; + +/** + * Deeper Go and Rust checks: how much of the code opts out of the type system (`interface{}`/`any` + * in Go, `unsafe` in Rust), and whether one `cargo` invocation reaches every crate. + */ + +/** Go/Rust product code: no tests, fixtures, examples, vendored or generated files. */ +function productFiles(ctx: RepoContext, ext: string): string[] { + return ctx.files.filter( + (f) => + f.endsWith(ext) && + !isAuxiliaryPath(f) && + !isFixturePath(f) && + !/(^|\/)(vendor|third[-_]party|target|benches|fuzz)\//.test(f) && + !/_test\.go$|\.pb\.go$|_gen\.go$|\.gen\.go$|zz_generated/.test(f), + ); +} + +/** Remove comments and string literals so `"any"` or `// interface{}` don't count. */ +function stripGo(src: string): string { + return src + .replace(/\/\*[\s\S]*?\*\//g, ' ') + .replace(/\/\/[^\n]*/g, '') + .replace(/`[^`]*`/g, '""') + .replace(/"(?:[^"\\\n]|\\.)*"/g, '""') + .replace(/'(?:[^'\\\n]|\\.)*'/g, "''"); +} + +/** + * `interface{}` and `any` used as a type. Type-parameter constraints (`[T any]`, `[K comparable, V + * any]`) are idiomatic generics and are not counted. + */ +export function goAnyCount(src: string): number { + const code = stripGo(src); + const empty = (code.match(/\binterface\s*\{\s*\}/g) ?? []).length; + let anys = 0; + for (const m of code.matchAll(/\bany\b/g)) { + const before = code.slice(Math.max(0, (m.index ?? 0) - 40), m.index); + const after = code.slice((m.index ?? 0) + 3, (m.index ?? 0) + 4); + // `[T any]`, `[T any, U comparable]`, `[K comparable, V any]`, `[K, V any]` + if (/[[,]\s*[A-Z]\w*\s+$/.test(before) && /[\],]/.test(after)) continue; + anys++; + } + return empty + anys; +} + +/** `unsafe { }` blocks, `unsafe fn`, `unsafe impl` and `unsafe trait` in Rust source. */ +export function rustUnsafeCount(src: string): number { + const code = src + .replace(/\/\*[\s\S]*?\*\//g, ' ') + .replace(/\/\/[^\n]*/g, '') + .replace(/"(?:[^"\\\n]|\\.)*"/g, '""'); + return (code.match(/\bunsafe\s*(?:\{|fn\b|impl\b|trait\b|extern\b)/g) ?? []).length; +} + +function nonBlankLines(src: string): number { + let n = 0; + for (const line of src.split('\n')) if (line.trim()) n++; + return n; +} + +/** Linear score: 1 at or below `ok` per KLOC, down to `floor` at `bad` per KLOC and beyond. */ +function densityScore(perKloc: number, ok: number, bad: number, floor = 0.6): number { + if (perKloc <= ok) return 1; + if (perKloc >= bad) return floor; + return 1 - ((perKloc - ok) / (bad - ok)) * (1 - floor); +} + +interface Density { + total: number; + lines: number; + perKloc: number; + top: Array<{ file: string; count: number }>; +} + +async function density( + ctx: RepoContext, + files: string[], + count: (src: string) => number, +): Promise { + const per = await ctx.mapFiles(files.slice(0, 5000), (file, text) => ({ + file, + count: count(text), + lines: nonBlankLines(text), + })); + let total = 0; + let lines = 0; + const top: Array<{ file: string; count: number }> = []; + for (const p of per) { + if (!p) continue; + total += p.count; + lines += p.lines; + if (p.count) top.push({ file: p.file, count: p.count }); + } + top.sort((a, b) => b.count - a.count || a.file.localeCompare(b.file)); + return { total, lines, perKloc: lines ? (total / lines) * 1000 : 0, top: top.slice(0, 5) }; +} + +const goAnyCheck: Check = { + id: 'types.go-any', + category: 'types', + title: 'Go code avoids interface{} / any', + weight: 1, + async run(ctx): Promise { + if (!ctx.languages.includes('go')) return { score: null, summary: 'No Go' }; + const files = productFiles(ctx, '.go'); + if (files.length === 0) return { score: null, summary: 'No Go product code' }; + const d = await density(ctx, files, goAnyCount); + const score = densityScore(d.perKloc, 2, 30, 0.7); + return { + score, + weightScale: ctx.share('go'), + summary: `${d.total} interface{}/any in ${Math.round(d.lines / 100) / 10}k lines of Go (${d.perKloc.toFixed(1)}/kloc)`, + findings: + score < 1 + ? d.top.map((t) => ({ + severity: 'info', + file: t.file, + message: `${t.count} interface{}/any`, + })) + : [], + suggestion: + score < 1 + ? 'Every interface{}/any is a type assertion an agent has to guess. Prefer concrete types or generics (`[T any]` constraints are fine).' + : undefined, + }; + }, +}; + +/** FFI binding crates (`openssl-sys/`) are unsafe by definition. */ +const SYS_CRATE = /(^|\/)[\w-]+-sys\//; + +/** `#![forbid(unsafe_code)]` in a crate root, or `unsafe_code = "forbid"` lints in Cargo.toml. */ +function forbidsUnsafe(ctx: RepoContext): boolean { + const cargo = ctx.read('Cargo.toml') ?? ''; + if (/^\s*unsafe_code\s*=\s*["'](?:forbid|deny)["']/m.test(cargo)) return true; + const roots = ctx.files.filter( + (f) => /(^|\/)src\/(?:lib|main)\.rs$/.test(f) && !isAuxiliaryPath(f) && !SYS_CRATE.test(f), + ); + return ( + roots.length > 0 && + roots.every((f) => /#!\[(?:forbid|deny)\([^)]*\bunsafe_code\b/.test(ctx.read(f) ?? '')) + ); +} + +const rustUnsafeCheck: Check = { + id: 'types.rust-unsafe', + category: 'types', + title: 'Rust code keeps unsafe rare', + weight: 1, + async run(ctx): Promise { + if (!ctx.languages.includes('rust')) return { score: null, summary: 'No Rust' }; + // FFI binding crates (`*-sys`) are unsafe by definition. + const files = productFiles(ctx, '.rs').filter((f) => !SYS_CRATE.test(f)); + if (files.length === 0) return { score: null, summary: 'No Rust product code' }; + if (forbidsUnsafe(ctx)) { + return { score: 1, weightScale: ctx.share('rust'), summary: 'unsafe_code is forbidden' }; + } + const d = await density(ctx, files, rustUnsafeCount); + const score = densityScore(d.perKloc, 1, 20, 0.7); + return { + score, + weightScale: ctx.share('rust'), + summary: `${d.total} unsafe block(s)/fn(s) in ${Math.round(d.lines / 100) / 10}k lines of Rust (${d.perKloc.toFixed(1)}/kloc)`, + findings: + score < 1 + ? d.top.map((t) => ({ severity: 'info', file: t.file, message: `${t.count} unsafe` })) + : [], + suggestion: + score < 1 + ? 'The compiler can’t check unsafe code for an agent. Wrap it in small, documented safe abstractions (with `// SAFETY:` comments) and add `#![deny(unsafe_code)]` where it isn’t needed.' + : undefined, + }; + }, +}; + +/** A TOML array (`members = [...]`, possibly multi-line) inside `[section]`. */ +export function tomlArray(text: string, section: string, key: string): string[] | null { + const lines = text.split(/\r?\n/); + let inSection = false; + for (let i = 0; i < lines.length; i++) { + const line = (lines[i] ?? '').trim(); + if (line.startsWith('[')) { + inSection = line === `[${section}]`; + continue; + } + if (!inSection) continue; + const m = new RegExp(`^${key}\\s*=\\s*\\[(.*)$`).exec(line); + if (!m) continue; + let buf = m[1] ?? ''; + while (!buf.includes(']') && i + 1 < lines.length) buf += `\n${lines[++i] ?? ''}`; + const inner = buf.slice(0, buf.indexOf(']')).replace(/#[^\n]*/g, ''); + return [...inner.matchAll(/["']([^"']+)["']/g)].map((x) => x[1] as string); + } + return null; +} + +function globRe(glob: string): RegExp { + let g = glob.trim().replace(/^\.\//, ''); + while (g.endsWith('/')) g = g.slice(0, -1); + const body = g + .split('') + .map((ch) => + ch === '*' ? '[^/]*' : ch === '?' ? '[^/]' : /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch, + ) + .join(''); + return new RegExp(`^${body}$`); +} + +interface Workspace { + dir: string; + members: RegExp[]; + exclude: RegExp[]; +} + +const cargoWorkspaceCheck: Check = { + id: 'feedback.cargo-workspace', + category: 'feedback', + title: 'One cargo workspace reaches every crate', + weight: 1, + run(ctx): CheckResult { + if (!ctx.languages.includes('rust')) return { score: null, summary: 'No Rust' }; + // cargo-fuzz's `fuzz/` crate is its own workspace by design; examples and fixtures aren't product. + const manifests = ctx.files.filter( + (f) => + /(^|\/)Cargo\.toml$/.test(f) && + !isFixturePath(f) && + !isAuxiliaryPath(f) && + !/(^|\/)fuzz\//.test(f), + ); + const crates: string[] = []; + const workspaces: Workspace[] = []; + /** Manifest dir -> crate dirs it depends on by `path = "..."`. */ + const pathDeps = new Map(); + for (const m of manifests) { + const text = ctx.read(m) ?? ''; + const dir = posix.dirname(m); + pathDeps.set( + dir, + [...text.matchAll(/\bpath\s*=\s*["']([^"']+)["']/g)].map((x) => + posix.normalize(posix.join(dir, x[1] as string)), + ), + ); + if (/^\[package\]/m.test(text)) crates.push(dir); + if (/^\[workspace\]/m.test(text)) { + const rel = (g: string) => (dir === '.' ? g : posix.join(dir, g)); + workspaces.push({ + dir, + members: (tomlArray(text, 'workspace', 'members') ?? []).map((g) => globRe(rel(g))), + exclude: (tomlArray(text, 'workspace', 'exclude') ?? []).map((g) => globRe(rel(g))), + }); + } + } + if (crates.length <= 1 && workspaces.length <= 1) { + return { score: null, summary: crates.length ? 'Single crate' : 'No Cargo crates' }; + } + const covers = (w: Workspace, crate: string) => + crate === w.dir || + (w.members.some((re) => re.test(crate)) && !w.exclude.some((re) => re.test(crate))); + const excluded = (w: Workspace, crate: string) => w.exclude.some((re) => re.test(crate)); + // The entry point: the root workspace, else the workspace (or crate) that reaches the most crates. + const rootWs = workspaces.find((w) => w.dir === '.'); + const primary = + rootWs ?? + [...workspaces].sort( + (a, b) => + crates.filter((c) => covers(b, c)).length - crates.filter((c) => covers(a, c)).length, + )[0]; + // Cargo makes path dependencies of members (inside the workspace dir) members too. + const reachedSet = new Set(crates.filter((c) => (primary ? covers(primary, c) : c === '.'))); + if (primary) reachedSet.add(primary.dir); + const inside = (c: string) => + !primary || primary.dir === '.' || c.startsWith(`${primary.dir}/`); + for (let changed = true; changed; ) { + changed = false; + for (const from of [...reachedSet]) { + for (const dep of pathDeps.get(from) ?? []) { + if (crates.includes(dep) && inside(dep) && !reachedSet.has(dep)) { + reachedSet.add(dep); + changed = true; + } + } + } + } + const reached = (c: string) => reachedSet.has(c); + // Crates the primary workspace deliberately excludes are a choice, not an oversight. + const relevant = crates.filter((c) => !(primary && excluded(primary, c))); + const missed = relevant.filter((c) => !reached(c)); + if (relevant.length === 0) return { score: null, summary: 'No Cargo crates' }; + const findings: Finding[] = []; + const nested = workspaces.filter((w) => w !== primary); + for (const w of nested) { + const own = missed.filter((c) => covers(w, c)); + if (own.length) { + findings.push({ + severity: 'warn', + file: w.dir === '.' ? 'Cargo.toml' : `${w.dir}/Cargo.toml`, + message: `separate workspace with ${own.length} crate(s): \`cargo test\` in ${primary?.dir ?? 'the root'} never builds them`, + }); + } + } + for (const c of missed.filter((c) => !nested.some((w) => covers(w, c))).slice(0, 10)) { + findings.push({ + severity: 'warn', + file: c === '.' ? 'Cargo.toml' : `${c}/Cargo.toml`, + message: + 'crate is in no workspace: add it to `[workspace] members` (or `exclude` it explicitly)', + }); + } + const where = primary + ? primary.dir === '.' + ? 'the root workspace' + : `\`${primary.dir}/\`` + : 'the root crate'; + const score = (relevant.length - missed.length) / relevant.length; + return { + score, + weightScale: ctx.share('rust'), + summary: + missed.length === 0 + ? `All ${relevant.length} crates are in ${where}` + : `${missed.length} of ${relevant.length} crates are outside ${where}`, + findings, + suggestion: missed.length + ? 'Agents run one `cargo test --workspace`; crates outside that workspace go unbuilt and untested. Add them to `members`, or document the extra workspace and its commands in AGENTS.md.' + : undefined, + }; + }, +}; + +export const goRustChecks: Check[] = [goAnyCheck, rustUnsafeCheck, cargoWorkspaceCheck]; diff --git a/src/checks/index.ts b/src/checks/index.ts index a74feae..ef4969a 100644 --- a/src/checks/index.ts +++ b/src/checks/index.ts @@ -3,6 +3,7 @@ import { agentToolingChecks } from './agent-tooling.js'; import { contextChecks } from './context-docs.js'; import { docHistoryCheck } from './doc-history.js'; import { feedbackChecks } from './feedback.js'; +import { goRustChecks } from './go-rust.js'; import { navigabilityChecks } from './navigability.js'; import { runChecks } from './run-checks.js'; import { safetyChecks } from './safety.js'; @@ -17,6 +18,7 @@ export const builtinChecks: Check[] = [ ...navigabilityChecks, ...typeSafetyChecks, ...safetyChecks, + ...goRustChecks, docHistoryCheck, ...agentToolingChecks, ...runChecks, diff --git a/src/scan.ts b/src/scan.ts index 020dc12..63acf71 100644 --- a/src/scan.ts +++ b/src/scan.ts @@ -38,13 +38,17 @@ export interface ScanOptions extends Partial { /** Categories that make sense for one package on its own; docs and safety are repo-wide. */ const PACKAGE_CATEGORIES = new Set(['feedback', 'navigability', 'types']); -/** Repo-level checks inside those categories (one CI and README per repo is normal; --run checks run once). */ +/** + * Repo-level checks inside those categories: one CI, README and cargo workspace per repo is + * normal, and the --run checks run once for the whole repo. + */ const REPO_ONLY_CHECKS = new Set([ 'feedback.ci', 'feedback.speed', 'feedback.lint-passes', 'feedback.typecheck-passes', 'feedback.flaky', + 'feedback.cargo-workspace', 'nav.readme', ]); /** Packages scored one by one (the largest by code size); the rest are only counted. */ diff --git a/test/go-rust.test.ts b/test/go-rust.test.ts new file mode 100644 index 0000000..da78932 --- /dev/null +++ b/test/go-rust.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, it } from 'vitest'; +import { goAnyCount, rustUnsafeCount, tomlArray } from '../src/checks/go-rust.js'; +import { scan } from '../src/scan.js'; +import type { Report } from '../src/types.js'; +import { fixture } from './helpers.js'; + +function check(report: Report, id: string) { + const c = report.checks.find((x) => x.id === id); + if (!c) throw new Error(`no check ${id}`); + return c; +} + +/** `n` lines of plain Go. */ +function goLines(n: number): string { + return Array.from({ length: n }, (_, i) => `var v${i} = ${i}`).join('\n'); +} + +describe('Go interface{}/any counting', () => { + it('counts empty interfaces and any as a type, not generic constraints, comments or strings', () => { + const src = [ + 'package x', + 'func F(v interface{}) {}', + 'func G(m map[string]any, xs ...any) []any { return nil }', + 'type Box[T any] struct{ v T }', + 'func Map[K comparable, V any](m map[K]V) {}', + 'func Pair[K, V any]() {}', + '// interface{} in a comment', + 'var s = "any interface{}"', + 'type I interface{ M() }', + ].join('\n'); + expect(goAnyCount(src)).toBe(4); + }); + + it('scores dense any usage lower and ignores tests and generated code', async () => { + const heavy = Array.from( + { length: 40 }, + (_, i) => `func F${i}(v any) interface{} { return v }`, + ); + const r = await scan( + fixture(null, { + git: true, + files: { + 'go.mod': 'module example.com/x\n', + 'x.go': `package x\n${heavy.join('\n')}\n`, + 'x_test.go': `package x\n${heavy.join('\n')}\n`, + 'api.pb.go': `package x\n${heavy.join('\n')}\n`, + }, + }), + ); + const c = check(r, 'types.go-any'); + expect(c.score).toBeCloseTo(0.7); + expect(c.summary).toMatch(/^80 interface\{\}\/any/); + expect(c.findings?.map((f) => f.file)).toEqual(['x.go']); + const clean = await scan( + fixture(null, { + git: true, + files: { 'go.mod': 'module x\n', 'x.go': `package x\n${goLines(500)}\nfunc F(v any) {}\n` }, + }), + ); + expect(check(clean, 'types.go-any').score).toBe(1); + }); +}); + +describe('Rust unsafe counting', () => { + it('counts unsafe blocks, fns and impls but not comments, strings or identifiers', () => { + const src = [ + 'unsafe fn a() {}', + 'fn b() { unsafe { a() } }', + 'unsafe impl Send for X {}', + '// unsafe { }', + 'let s = "unsafe {";', + 'fn not_unsafe_at_all() {}', + ].join('\n'); + expect(rustUnsafeCount(src)).toBe(3); + }); + + it('scores dense unsafe lower, skips -sys crates, and trusts forbid(unsafe_code)', async () => { + const unsafeHeavy = Array.from({ length: 30 }, (_, i) => `fn f${i}() { unsafe { g() } }`).join( + '\n', + ); + const base = { + 'Cargo.toml': '[package]\nname = "x"\n', + 'src/lib.rs': `${unsafeHeavy}\n`, + 'ffi-sys/src/lib.rs': `${unsafeHeavy}\n`, + }; + const r = await scan(fixture(null, { git: true, files: base })); + const c = check(r, 'types.rust-unsafe'); + expect(c.score).toBeCloseTo(0.7); + expect(c.summary).toMatch(/^30 unsafe/); + const forbidden = await scan( + fixture(null, { + git: true, + files: { ...base, 'src/lib.rs': `#![forbid(unsafe_code)]\n${unsafeHeavy}\n` }, + }), + ); + expect(check(forbidden, 'types.rust-unsafe')).toMatchObject({ + score: 1, + summary: 'unsafe_code is forbidden', + }); + }); +}); + +describe('feedback.cargo-workspace', () => { + const crate = (name: string, deps = '') => + `[package]\nname = "${name}"\n\n[dependencies]\n${deps}`; + + it('passes when the root workspace reaches every crate (globs, path deps, fuzz)', async () => { + const r = await scan( + fixture(null, { + git: true, + files: { + 'Cargo.toml': '[workspace]\nmembers = [\n "crates/*",\n]\nexclude = ["crates/old"]\n', + 'crates/a/Cargo.toml': crate('a', 'helper = { path = "../../helper" }\n'), + 'crates/a/src/lib.rs': 'pub fn a() {}\n', + 'crates/old/Cargo.toml': crate('old'), + 'helper/Cargo.toml': crate('helper'), + 'helper/src/lib.rs': 'pub fn h() {}\n', + 'fuzz/Cargo.toml': '[package]\nname = "fuzz"\n\n[workspace]\nmembers = ["."]\n', + }, + }), + ); + const c = check(r, 'feedback.cargo-workspace'); + expect(c.score).toBe(1); + expect(c.summary).toBe('All 2 crates are in the root workspace'); + }); + + it('flags nested workspaces and orphan crates', async () => { + const r = await scan( + fixture(null, { + git: true, + files: { + 'Cargo.toml': '[workspace]\nmembers = ["core"]\n', + 'core/Cargo.toml': crate('core'), + 'core/src/lib.rs': 'pub fn c() {}\n', + 'tools/lint/Cargo.toml': `${crate('lint')}\n[workspace]\n`, + 'tools/lint/src/main.rs': 'fn main() {}\n', + 'stray/Cargo.toml': crate('stray'), + 'stray/src/lib.rs': 'pub fn s() {}\n', + }, + }), + ); + const c = check(r, 'feedback.cargo-workspace'); + expect(c.score).toBeCloseTo(1 / 3); + expect(c.findings?.map((f) => [f.file, f.message.split(':')[0]])).toEqual([ + ['tools/lint/Cargo.toml', 'separate workspace with 1 crate(s)'], + ['stray/Cargo.toml', 'crate is in no workspace'], + ]); + }); + + it('is n/a for a single crate', async () => { + const r = await scan( + fixture(null, { files: { 'Cargo.toml': crate('x'), 'src/main.rs': 'fn main() {}\n' } }), + ); + expect(check(r, 'feedback.cargo-workspace').score).toBeNull(); + }); + + it('parses multi-line TOML arrays in the right section', () => { + const toml = '[package]\nmembers = ["no"]\n[workspace]\nmembers = [\n "a", # c\n "b/*"\n]\n'; + expect(tomlArray(toml, 'workspace', 'members')).toEqual(['a', 'b/*']); + }); +});