/** * Reads the static facts `score` grades from a repository on disk. Everything here is a file read or * a `git` query: nothing is built, installed, or run, so a scan takes seconds and costs no tokens. Two * exceptions: `runKnip` opts in to running the repo's knip command (see `knip.ts`), and an installed * buddy-agent-harness has its read-only `doctor` run (see `harness-doctor.ts`). */ import { spawnSync } from 'node:child_process' import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs' import { basename, join, posix } from 'node:path' import { readBaselineAt } from './aced-bench.js' import { findUndocumentedEnv, isSetupDoc, type UndocumentedEnv } from './env.js' import { findSearchedFixtureDirs, type SearchedFixtureDir } from './fixtures.js' import { findHarnessDoctor, type HarnessDoctorRun, runHarnessDoctor } from './harness-doctor.js' import { type InjectionSurface, readInjectionSurface } from './injection-surface.js' import { type DeadCodeRun, runKnip } from './knip.js' import { type CommentFacts, findNameCollisions, measureComments, type NameCollision } from './source.js' import { type ReleaseAgeGate, readReleaseAgeGate, readWorkflows, type WorkflowFacts } from './supply-chain.js' import { readWorkspacePackages } from './workspaces.js' interface InstructionFile { path: string tokens: number } /** Where the instruction files state what the project is for and what it deliberately is not. */ interface ScopeFacts { /** Files an instructions file names that carry the detail: a well-known name, or one with a scope or non-goals heading. */ linked: string[] /** Well-known scope files (`GOALS.md`, `SCOPE.md`, …) at the root or under `docs/` that no instructions file names. */ unlinked: string[] /** `:: ` for each scope, purpose, or non-goals heading or line in an instruction file. */ sections: string[] /** * In a monorepo, the same facts for each workspace package that is not `private`; the root's own * then hold only files outside those packages. `undefined` in a single-package repo. */ packages?: PackageScope[] | undefined /** In a monorepo, the `private` workspace packages the check skips: apps, fixtures, the docs site. */ privatePackages?: string[] | undefined } interface PackageScope { dir: string name: string /** Files the package's own `AGENTS.md`/`CLAUDE.md`, or a root instructions file, names inside the package. */ linked: string[] /** Well-known scope files at the package root or its `docs/` that nothing names. */ unlinked: string[] /** Scope lines in the package's own `AGENTS.md`/`CLAUDE.md`. */ sections: string[] } interface SkillDescription { path: string name: string tokens: number } interface LargeFile { path: string lines: number } export interface Facts { isGitRepo: boolean hasReadme: boolean hasManifest: boolean /** Root `package.json` scripts, or `Makefile` targets, by name. */ scripts: string[] ciConfigs: string[] instructionFiles: InstructionFile[] skillDescriptions: SkillDescription[] scope: ScopeFacts /** Package-manager commands named in the instruction files whose script does not exist. */ missingInstructionCommands: string[] toolchainPins: string[] hasLockfile: boolean preCommitHooks: string[] hasContributing: boolean hasIssueTemplates: boolean isMonorepo: boolean /** `undefined` when the repo has no `tsconfig.json`. */ tsStrict: boolean | undefined largeFiles: LargeFile[] trackedBuildOutput: string[] /** * Tracked fixture and vendored folders whose files no ignore file excludes from search; `undefined` * outside a git repo, where ignore rules cannot be asked. */ searchedFixtureDirs: SearchedFixtureDir[] | undefined /** `undefined` outside a git repo, where ignore rules cannot be asked. */ envIgnored: boolean | undefined committedSecretFiles: string[] /** `: ` for each MCP env entry holding a literal value under a credential-like name. */ mcpLiteralCredentials: string[] /** `undefined` when the repo has no `.github/workflows`. */ workflows: WorkflowFacts | undefined /** `undefined` when the repo has no JavaScript package manager. */ releaseAgeGate: ReleaseAgeGate | undefined /** Session-start and per-prompt hooks, and MCP servers: reported, never scored. */ injectionSurface: InjectionSurface /** `undefined` when the repo has no non-test source in a language with `//` comments. */ comments: CommentFacts | undefined /** `undefined` when the repo has no non-test JS or TS source. */ nameCollisions: NameCollision[] | undefined /** * Variables the source reads that no instructions file, README, CONTRIBUTING, or `.env.example` * names; `undefined` when the repo has no non-test JS or TS source. */ undocumentedEnv: UndocumentedEnv[] | undefined /** The command that runs knip, when the repo has it configured; `undefined` otherwise. */ deadCodeCommand: string | undefined /** knip's result, when `score --run-knip` ran it; `undefined` otherwise. */ deadCodeRun?: DeadCodeRun | undefined /** buddy-agent-harness `doctor`'s result; `undefined` when the repo does not have it installed. */ harnessDoctor?: HarnessDoctorRun | undefined /** When the stored `bench` baseline was recorded; `undefined` when there is none. */ benchBaselineAt: string | undefined } /** A rough, model-agnostic estimate. Real tokenizers land within about 20% of it for English and code. */ export function estimateTokens(text: string): number { return Math.ceil(text.length / 4) } const MANIFESTS = ['package.json', 'pyproject.toml', 'Cargo.toml', 'go.mod', 'pom.xml', 'build.gradle', 'Makefile'] const INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md', '.github/copilot-instructions.md', '.cursorrules'] const SKILL_DIRS = ['.agents/skills', '.claude/skills', '.cursor/skills', '.codex/skills', '.github/skills'] const CI_CONFIGS = [ '.github/workflows', '.gitlab-ci.yml', 'bitbucket-pipelines.yml', 'azure-pipelines.yml', '.forgejo/workflows', '.gitea/workflows', '.circleci/config.yml', 'Jenkinsfile', ] const TOOLCHAIN_FILES = [ '.nvmrc', '.node-version', '.tool-versions', 'mise.toml', '.mise.toml', '.python-version', 'rust-toolchain', 'rust-toolchain.toml', '.go-version', ] const LOCKFILES = [ 'pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb', 'uv.lock', 'poetry.lock', 'Cargo.lock', 'go.sum', ] const HOOK_CONFIGS = ['.husky', 'lefthook.yml', '.lefthook.yml', '.pre-commit-config.yaml', '.simple-git-hooks.json'] const MCP_FILES = ['.mcp.json', '.cursor/mcp.json', '.vscode/mcp.json'] /** A script that runs knip itself, not one that names a task called `knip` (`turbo run knip`). */ const KNIP_SCRIPT = /^\s*((npx|bunx|pnpm exec|pnpm dlx|yarn)\s+)?knip(\s|$)/ const KNIP_CONFIGS = [ 'knip.json', 'knip.jsonc', '.knip.json', '.knip.jsonc', 'knip.ts', 'knip.js', 'knip.mts', 'knip.config.ts', 'knip.config.js', 'knip.config.mjs', ] const BUILD_OUTPUT = /(^|\/)(dist|build|out|coverage|\.next|\.turbo)\/|\.min\.(js|css)$/ const SECRET_FILE = /(^|\/)(\.env(\.[^/]*)?|id_rsa|id_ed25519|credentials\.json|[^/]*\.(pem|p12|pfx|key))$/ const SECRET_FILE_ALLOWED = /\.(example|sample|template|dist)$/ const CREDENTIAL_KEY = /(token|secret|password|passwd|api[_-]?key|auth)/i const TEXT_EXTENSIONS = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs|py|rs|go|java|kt|rb|php|cs|swift|c|h|cc|cpp|hpp|vue|svelte|astro|md|mdx|css|scss|sh)$/ const LOCK_OR_GENERATED = /(^|\/)(pnpm-lock\.yaml|package-lock\.json|yarn\.lock|CHANGELOG\.md)$/ const LARGE_FILE_LINES = 1000 /** Package-manager built-ins, which an instruction file can name without a matching script. */ const PM_BUILTINS = new Set([ 'install', 'i', 'add', 'remove', 'rm', 'update', 'up', 'dlx', 'exec', 'create', 'init', 'publish', 'pack', 'link', 'unlink', 'outdated', 'audit', 'why', 'list', 'ls', 'run', 'store', 'patch', 'patch-commit', 'approve-builds', 'config', 'licenses', 'rebuild', 'prune', 'dedupe', 'import', 'fetch', 'deploy', 'env', 'setup', 'self-update', 'cache', 'version', 'help', 'test', 'start', 'stop', 'restart', 'ci', 'x', ]) function read(dir: string, file: string): string | undefined { try { return readFileSync(join(dir, file), 'utf8') } catch { return undefined } } function exists(dir: string, file: string) { return existsSync(join(dir, file)) } function git(dir: string, args: string[]) { return spawnSync('git', args, { cwd: dir, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }) } /** Tracked files in a git repo; outside one, a walk that skips dependency and VCS folders. */ function listFiles(dir: string, isGitRepo: boolean): string[] { if (isGitRepo) { const r = git(dir, ['ls-files', '-z']) if (r.status === 0) return r.stdout.split('\0').filter(Boolean) } const files: string[] = [] const walk = (rel: string) => { for (const entry of readdirSync(join(dir, rel), { withFileTypes: true })) { if (entry.name === 'node_modules' || entry.name === '.git') continue const path = rel ? `${rel}/${entry.name}` : entry.name if (entry.isDirectory()) walk(path) else if (entry.isFile()) files.push(path) } } walk('') return files } function readScripts(dir: string): string[] { const scripts = new Set() const pkg = read(dir, 'package.json') if (pkg) { try { for (const name of Object.keys(JSON.parse(pkg).scripts ?? {})) scripts.add(name) } catch { // An unparsable package.json has no scripts an agent could run either. } } const makefile = read(dir, 'Makefile') if (makefile) { for (const m of makefile.matchAll(/^([A-Za-z][\w-]*):/gm)) scripts.add(m[1] as string) } return [...scripts] } interface PackageJson { scripts?: Record devDependencies?: Record knip?: unknown packageManager?: unknown engines?: { node?: unknown } workspaces?: unknown 'simple-git-hooks'?: unknown 'lint-staged'?: unknown } function readPackageJson(dir: string): PackageJson { try { return JSON.parse(read(dir, 'package.json') ?? '{}') } catch { return {} } } function frontmatterField(text: string, field: string): string | undefined { const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] if (!fm) return undefined const m = new RegExp(`^${field}:\\s*(.*)$`, 'm').exec(fm) return m?.[1]?.trim().replace(/^["']|["']$/g, '') } function readSkillDescriptions(dir: string): SkillDescription[] { const seen = new Set() const skills: SkillDescription[] = [] for (const skillDir of SKILL_DIRS) { if (!exists(dir, skillDir)) continue for (const entry of readdirSync(join(dir, skillDir))) { const path = `${skillDir}/${entry}/SKILL.md` if (!exists(dir, path)) continue // Harness folders often symlink one shared skill; the harness loads each copy, but it is one skill. const real = realpathSync(join(dir, path)) if (seen.has(real)) continue seen.add(real) const text = read(dir, path) ?? '' const name = frontmatterField(text, 'name') ?? entry const description = frontmatterField(text, 'description') ?? '' skills.push({ path, name, tokens: estimateTokens(`${name}: ${description}`) }) } } return skills } /** `pnpm