A tiny, local-first CLI that finds the files your AI coding agent actually needs — and packs them into a focused context.
| 1 | """Repository file discovery and classification.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import os |
| 6 | import stat |
| 7 | from dataclasses import dataclass, field |
| 8 | from enum import Enum |
| 9 | from pathlib import Path |
| 10 | |
| 11 | from agent_context.config import Config |
| 12 | from agent_context.ignore import IgnoreMatcher |
| 13 | from agent_context.security import detect_sensitive_paths, is_sensitive_path |
| 14 | from agent_context.tokens import estimate_tokens_from_file, format_int |
| 15 | |
| 16 | # Extensions treated as source code. |
| 17 | SOURCE_EXTENSIONS: frozenset[str] = frozenset( |
| 18 | { |
| 19 | ".py", ".pyi", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", |
| 20 | ".go", ".rs", ".java", ".kt", ".kts", ".scala", |
| 21 | ".c", ".h", ".cpp", ".cc", ".cxx", ".hpp", ".hh", |
| 22 | ".cs", ".fs", ".swift", ".m", ".mm", |
| 23 | ".rb", ".php", ".pl", ".pm", ".lua", ".r", ".jl", |
| 24 | ".sh", ".bash", ".zsh", ".ps1", ".bat", ".cmd", |
| 25 | ".sql", ".graphql", ".gql", ".proto", |
| 26 | ".vue", ".svelte", ".astro", |
| 27 | ".ex", ".exs", ".erl", ".hrl", ".clj", ".cljs", |
| 28 | ".dart", ".zig", ".nim", ".v", ".vue", |
| 29 | } |
| 30 | ) |
| 31 | |
| 32 | TEST_NAME_HINTS: tuple[str, ...] = ( |
| 33 | "test", "tests", "spec", "specs", "__tests__", "testing", |
| 34 | ) |
| 35 | |
| 36 | DOC_EXTENSIONS: frozenset[str] = frozenset( |
| 37 | {".md", ".mdx", ".rst", ".txt", ".adoc", ".org"} |
| 38 | ) |
| 39 | |
| 40 | DOC_BASENAMES: frozenset[str] = frozenset( |
| 41 | { |
| 42 | "readme", "changelog", "changes", "license", "licence", |
| 43 | "contributing", "authors", "code_of_conduct", "security", |
| 44 | } |
| 45 | ) |
| 46 | |
| 47 | CONFIG_BASENAMES: frozenset[str] = frozenset( |
| 48 | { |
| 49 | "package.json", "tsconfig.json", "jsconfig.json", "pyproject.toml", |
| 50 | "setup.py", "setup.cfg", "cargo.toml", "go.mod", "go.sum", |
| 51 | "composer.json", "gemfile", "podfile", "makefile", "cmakelists.txt", |
| 52 | "dockerfile", "docker-compose.yml", "docker-compose.yaml", |
| 53 | "next.config.js", "next.config.mjs", "next.config.ts", |
| 54 | "vite.config.js", "vite.config.ts", "webpack.config.js", |
| 55 | "requirements.txt", "pipfile", "poetry.lock", |
| 56 | ".editorconfig", ".prettierrc", ".eslintrc", ".eslintrc.js", |
| 57 | "babel.config.js", "jest.config.js", "vitest.config.ts", |
| 58 | } |
| 59 | ) |
| 60 | |
| 61 | BINARY_EXTENSIONS: frozenset[str] = frozenset( |
| 62 | { |
| 63 | ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".bmp", ".svg", |
| 64 | ".pdf", ".zip", ".gz", ".tar", ".tgz", ".7z", ".rar", ".bz2", ".xz", |
| 65 | ".mp4", ".mov", ".avi", ".mkv", ".webm", |
| 66 | ".mp3", ".wav", ".ogg", ".flac", ".aac", |
| 67 | ".woff", ".woff2", ".ttf", ".otf", ".eot", |
| 68 | ".exe", ".dll", ".so", ".dylib", ".bin", ".dat", |
| 69 | ".class", ".jar", ".war", ".ear", |
| 70 | ".pyc", ".pyo", ".o", ".a", ".lib", ".obj", |
| 71 | ".wasm", ".parquet", ".pkl", ".pickle", ".npy", ".npz", |
| 72 | ".db", ".sqlite", ".sqlite3", |
| 73 | } |
| 74 | ) |
| 75 | |
| 76 | GENERATED_HINTS: tuple[str, ...] = ( |
| 77 | "generated", "gen/", ".gen.", "autogen", "_pb2.py", ".pb.go", |
| 78 | ".min.js", ".min.css", ".bundle.js", "lock", |
| 79 | ) |
| 80 | |
| 81 | # How many bytes to sample for binary content detection. |
| 82 | _BINARY_SAMPLE = 8192 |
| 83 | _NULL_BYTE = b"\x00" |
| 84 | # Soft limit for "large" file classification (token estimate). |
| 85 | LARGE_FILE_TOKEN_THRESHOLD = 8_000 |
| 86 | |
| 87 | |
| 88 | class FileKind(str, Enum): |
| 89 | SOURCE = "source" |
| 90 | TEST = "test" |
| 91 | DOCUMENTATION = "documentation" |
| 92 | CONFIG = "config" |
| 93 | BINARY = "binary" |
| 94 | OTHER = "other" |
| 95 | |
| 96 | |
| 97 | @dataclass |
| 98 | class FileInfo: |
| 99 | """Metadata for a single discovered file.""" |
| 100 | |
| 101 | path: Path |
| 102 | rel_path: str |
| 103 | kind: FileKind |
| 104 | size_bytes: int |
| 105 | estimated_tokens: int |
| 106 | is_binary: bool = False |
| 107 | is_sensitive: bool = False |
| 108 | is_generated: bool = False |
| 109 | is_large: bool = False |
| 110 | extension: str = "" |
| 111 | |
| 112 | def to_dict(self) -> dict: |
| 113 | return { |
| 114 | "path": self.rel_path, |
| 115 | "kind": self.kind.value, |
| 116 | "size_bytes": self.size_bytes, |
| 117 | "estimated_tokens": self.estimated_tokens, |
| 118 | "is_binary": self.is_binary, |
| 119 | "is_sensitive": self.is_sensitive, |
| 120 | "is_generated": self.is_generated, |
| 121 | "is_large": self.is_large, |
| 122 | "extension": self.extension, |
| 123 | } |
| 124 | |
| 125 | |
| 126 | @dataclass |
| 127 | class ScanResult: |
| 128 | """Full repository scan summary.""" |
| 129 | |
| 130 | root: Path |
| 131 | files: list[FileInfo] = field(default_factory=list) |
| 132 | ignored_count: int = 0 |
| 133 | warnings: list[str] = field(default_factory=list) |
| 134 | sensitive: list[str] = field(default_factory=list) |
| 135 | |
| 136 | @property |
| 137 | def total_files(self) -> int: |
| 138 | return len(self.files) |
| 139 | |
| 140 | @property |
| 141 | def source_files(self) -> list[FileInfo]: |
| 142 | return [f for f in self.files if f.kind == FileKind.SOURCE] |
| 143 | |
| 144 | @property |
| 145 | def test_files(self) -> list[FileInfo]: |
| 146 | return [f for f in self.files if f.kind == FileKind.TEST] |
| 147 | |
| 148 | @property |
| 149 | def doc_files(self) -> list[FileInfo]: |
| 150 | return [f for f in self.files if f.kind == FileKind.DOCUMENTATION] |
| 151 | |
| 152 | @property |
| 153 | def binary_files(self) -> list[FileInfo]: |
| 154 | return [f for f in self.files if f.is_binary or f.kind == FileKind.BINARY] |
| 155 | |
| 156 | @property |
| 157 | def large_files(self) -> list[FileInfo]: |
| 158 | return [f for f in self.files if f.is_large] |
| 159 | |
| 160 | @property |
| 161 | def total_tokens(self) -> int: |
| 162 | return sum(f.estimated_tokens for f in self.files if not f.is_binary) |
| 163 | |
| 164 | @property |
| 165 | def context_candidates(self) -> list[FileInfo]: |
| 166 | """Non-binary, non-sensitive text files suitable for packing.""" |
| 167 | return [ |
| 168 | f |
| 169 | for f in self.files |
| 170 | if not f.is_binary and not f.is_sensitive and f.kind != FileKind.BINARY |
| 171 | ] |
| 172 | |
| 173 | def top_by_tokens(self, n: int = 10) -> list[FileInfo]: |
| 174 | eligible = [f for f in self.files if not f.is_binary] |
| 175 | return sorted(eligible, key=lambda f: (-f.estimated_tokens, f.rel_path))[:n] |
| 176 | |
| 177 | def to_dict(self) -> dict: |
| 178 | return { |
| 179 | "root": str(self.root), |
| 180 | "files": { |
| 181 | "total": self.total_files, |
| 182 | "source": len(self.source_files), |
| 183 | "tests": len(self.test_files), |
| 184 | "documentation": len(self.doc_files), |
| 185 | "binary": len(self.binary_files), |
| 186 | "ignored": self.ignored_count, |
| 187 | "large": len(self.large_files), |
| 188 | "sensitive": len(self.sensitive), |
| 189 | }, |
| 190 | "estimated_tokens": self.total_tokens, |
| 191 | "suggested_context_tokens": min(12_000, max(2_000, self.total_tokens // 6 or 0)), |
| 192 | "sensitive": list(self.sensitive), |
| 193 | "largest_files": [ |
| 194 | {"path": f.rel_path, "estimated_tokens": f.estimated_tokens} |
| 195 | for f in self.top_by_tokens(10) |
| 196 | ], |
| 197 | "warnings": list(self.warnings), |
| 198 | } |
| 199 | |
| 200 | |
| 201 | def find_repo_root(path: Path) -> Path: |
| 202 | """Resolve the directory to analyze. |
| 203 | |
| 204 | Walks up looking for ``.git``; falls back to the given path if none found. |
| 205 | """ |
| 206 | path = path.resolve() |
| 207 | if path.is_file(): |
| 208 | path = path.parent |
| 209 | current = path |
| 210 | for candidate in [current, *current.parents]: |
| 211 | if (candidate / ".git").exists(): |
| 212 | return candidate |
| 213 | return path |
| 214 | |
| 215 | |
| 216 | def is_binary_path(path: Path) -> bool: |
| 217 | """Extension-based binary check.""" |
| 218 | return path.suffix.lower() in BINARY_EXTENSIONS |
| 219 | |
| 220 | |
| 221 | def is_binary_content(path: Path) -> bool: |
| 222 | """Content-based binary detection for unknown extensions.""" |
| 223 | try: |
| 224 | with path.open("rb") as fh: |
| 225 | sample = fh.read(_BINARY_SAMPLE) |
| 226 | except OSError: |
| 227 | return False |
| 228 | if not sample: |
| 229 | return False |
| 230 | if _NULL_BYTE in sample: |
| 231 | return True |
| 232 | # High ratio of non-text bytes → likely binary. |
| 233 | text_chars = sum(1 for b in sample if b in b"\t\n\r\f\b" or 32 <= b < 127) |
| 234 | return (text_chars / len(sample)) < 0.70 |
| 235 | |
| 236 | |
| 237 | def classify_file(rel_path: str, path: Path, *, is_binary: bool) -> FileKind: |
| 238 | if is_binary: |
| 239 | return FileKind.BINARY |
| 240 | |
| 241 | name = path.name.lower() |
| 242 | suffix = path.suffix.lower() |
| 243 | parts_lower = [p.lower() for p in Path(rel_path).parts] |
| 244 | |
| 245 | # Tests first (a file in tests/ with .py is a test). |
| 246 | if _looks_like_test(name, parts_lower, suffix): |
| 247 | return FileKind.TEST |
| 248 | |
| 249 | # Documentation: extension-based, or well-known doc basenames with doc-like suffixes. |
| 250 | stem = Path(name).stem.lower() |
| 251 | if suffix in DOC_EXTENSIONS: |
| 252 | return FileKind.DOCUMENTATION |
| 253 | if stem in DOC_BASENAMES and suffix in {".md", ".rst", ".txt", ".adoc", ""}: |
| 254 | return FileKind.DOCUMENTATION |
| 255 | |
| 256 | if name in CONFIG_BASENAMES or name.startswith(".") and suffix in { |
| 257 | ".json", ".yml", ".yaml", ".toml", ".ini", ".cfg", |
| 258 | }: |
| 259 | return FileKind.CONFIG |
| 260 | |
| 261 | if suffix in SOURCE_EXTENSIONS: |
| 262 | return FileKind.SOURCE |
| 263 | |
| 264 | # Common config extensions without being "source". |
| 265 | if suffix in {".json", ".yml", ".yaml", ".toml", ".ini", ".cfg", ".xml"}: |
| 266 | return FileKind.CONFIG |
| 267 | |
| 268 | return FileKind.OTHER |
| 269 | |
| 270 | |
| 271 | def _looks_like_test(name: str, parts_lower: list[str], suffix: str) -> bool: |
| 272 | if any(hint in parts_lower for hint in TEST_NAME_HINTS): |
| 273 | return True |
| 274 | stem = Path(name).stem.lower() |
| 275 | if stem.startswith("test_") or stem.endswith("_test"): |
| 276 | return True |
| 277 | if stem.startswith("test") and suffix in SOURCE_EXTENSIONS: |
| 278 | return True |
| 279 | if ".test." in name or ".spec." in name: |
| 280 | return True |
| 281 | if stem.endswith(".test") or stem.endswith(".spec"): |
| 282 | return True |
| 283 | return False |
| 284 | |
| 285 | |
| 286 | def looks_generated(rel_path: str) -> bool: |
| 287 | lower = rel_path.replace("\\", "/").lower() |
| 288 | return any(hint in lower for hint in GENERATED_HINTS) |
| 289 | |
| 290 | |
| 291 | def scan_repository( |
| 292 | root: Path, |
| 293 | *, |
| 294 | config: Config | None = None, |
| 295 | follow_symlinks: bool = False, |
| 296 | ) -> ScanResult: |
| 297 | """Walk ``root`` and collect file metadata. |
| 298 | |
| 299 | Never executes project code. Never follows symlinks by default. |
| 300 | Unreadable files produce warnings and are skipped. |
| 301 | """ |
| 302 | root = find_repo_root(root) |
| 303 | config = config or Config.defaults() |
| 304 | matcher = IgnoreMatcher.create( |
| 305 | root, |
| 306 | include=config.include or None, |
| 307 | exclude=config.exclude or None, |
| 308 | ) |
| 309 | |
| 310 | result = ScanResult(root=root) |
| 311 | seen_real: set[Path] = set() |
| 312 | |
| 313 | for dirpath, dirnames, filenames in os.walk(root, followlinks=follow_symlinks): |
| 314 | current = Path(dirpath) |
| 315 | try: |
| 316 | rel_dir = current.resolve().relative_to(root.resolve()).as_posix() |
| 317 | except ValueError: |
| 318 | dirnames.clear() |
| 319 | continue |
| 320 | if rel_dir == ".": |
| 321 | rel_dir = "" |
| 322 | |
| 323 | # Prune ignored directories in-place (early skip). |
| 324 | keep_dirs: list[str] = [] |
| 325 | for d in sorted(dirnames): |
| 326 | if d in {".git", ".hg", ".svn"}: |
| 327 | result.ignored_count += 1 |
| 328 | continue |
| 329 | child_rel = f"{rel_dir}/{d}" if rel_dir else d |
| 330 | if matcher.should_skip_dir(child_rel): |
| 331 | result.ignored_count += 1 |
| 332 | continue |
| 333 | keep_dirs.append(d) |
| 334 | dirnames[:] = keep_dirs |
| 335 | |
| 336 | for name in sorted(filenames): |
| 337 | path = current / name |
| 338 | rel = f"{rel_dir}/{name}" if rel_dir else name |
| 339 | |
| 340 | if matcher.is_ignored(rel, is_dir=False): |
| 341 | result.ignored_count += 1 |
| 342 | continue |
| 343 | |
| 344 | try: |
| 345 | st = path.lstat() |
| 346 | except OSError as exc: |
| 347 | result.warnings.append(f"Warning: skipped unreadable file: {rel} ({exc})") |
| 348 | continue |
| 349 | |
| 350 | # Skip symlinks unless explicitly following. |
| 351 | if stat.S_ISLNK(st.st_mode) and not follow_symlinks: |
| 352 | result.warnings.append(f"Warning: skipped symlink: {rel}") |
| 353 | continue |
| 354 | |
| 355 | if not stat.S_ISREG(st.st_mode): |
| 356 | continue |
| 357 | |
| 358 | try: |
| 359 | real = path.resolve() |
| 360 | except OSError: |
| 361 | result.warnings.append(f"Warning: skipped unreadable file: {rel}") |
| 362 | continue |
| 363 | |
| 364 | if real in seen_real: |
| 365 | continue |
| 366 | seen_real.add(real) |
| 367 | |
| 368 | is_bin = is_binary_path(path) |
| 369 | if not is_bin: |
| 370 | # Content check only for non-obvious extensions. |
| 371 | try: |
| 372 | if is_binary_content(path): |
| 373 | is_bin = True |
| 374 | except OSError as exc: |
| 375 | result.warnings.append(f"Warning: skipped unreadable file: {rel} ({exc})") |
| 376 | continue |
| 377 | |
| 378 | sensitive = is_sensitive_path(path) |
| 379 | tokens = 0 if is_bin else estimate_tokens_from_file(path) |
| 380 | kind = classify_file(rel, path, is_binary=is_bin) |
| 381 | info = FileInfo( |
| 382 | path=path, |
| 383 | rel_path=rel.replace("\\", "/"), |
| 384 | kind=kind, |
| 385 | size_bytes=st.st_size, |
| 386 | estimated_tokens=tokens, |
| 387 | is_binary=is_bin, |
| 388 | is_sensitive=sensitive, |
| 389 | is_generated=looks_generated(rel), |
| 390 | is_large=tokens >= LARGE_FILE_TOKEN_THRESHOLD, |
| 391 | extension=path.suffix.lower(), |
| 392 | ) |
| 393 | result.files.append(info) |
| 394 | |
| 395 | # Deterministic order. |
| 396 | result.files.sort(key=lambda f: f.rel_path) |
| 397 | findings = detect_sensitive_paths( |
| 398 | [f.path for f in result.files if f.is_sensitive], |
| 399 | root=root, |
| 400 | ) |
| 401 | result.sensitive = [f.path for f in findings] |
| 402 | return result |
| 403 | |
| 404 | |
| 405 | def format_analysis(result: ScanResult) -> str: |
| 406 | """Human-readable analyze output.""" |
| 407 | lines = [ |
| 408 | "Repository Analysis", |
| 409 | "", |
| 410 | "Root:", |
| 411 | f" {result.root}", |
| 412 | "", |
| 413 | "Files", |
| 414 | f" Total: {result.total_files}", |
| 415 | f" Source: {len(result.source_files)}", |
| 416 | f" Tests: {len(result.test_files)}", |
| 417 | f" Documentation: {len(result.doc_files)}", |
| 418 | f" Binary: {len(result.binary_files)}", |
| 419 | f" Ignored: {result.ignored_count}", |
| 420 | "", |
| 421 | "Estimated tokens:", |
| 422 | f" {format_int(result.total_tokens)}", |
| 423 | "", |
| 424 | ] |
| 425 | |
| 426 | if result.sensitive: |
| 427 | lines.append("Potentially sensitive:") |
| 428 | for s in result.sensitive: |
| 429 | lines.append(f" {s}") |
| 430 | lines.append("") |
| 431 | |
| 432 | largest = result.top_by_tokens(8) |
| 433 | if largest: |
| 434 | lines.append("Largest files:") |
| 435 | for f in largest: |
| 436 | lines.append(f" {f.rel_path:<40} {format_int(f.estimated_tokens)} tokens") |
| 437 | lines.append("") |
| 438 | |
| 439 | suggested = result.to_dict()["suggested_context_tokens"] |
| 440 | lines.append("Suggested context:") |
| 441 | lines.append(f" ~{format_int(suggested)} tokens") |
| 442 | |
| 443 | if result.warnings: |
| 444 | lines.append("") |
| 445 | lines.append("Warnings:") |
| 446 | for w in result.warnings[:20]: |
| 447 | lines.append(f" {w}") |
| 448 | |
| 449 | return "\n".join(lines) + "\n" |