A tiny, local-first CLI that finds the files your AI coding agent actually needs — and packs them into a focused context.
| 1 | """Deterministic heuristic relevance scoring for context packing.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import re |
| 6 | from dataclasses import dataclass, field |
| 7 | from pathlib import Path |
| 8 | |
| 9 | from agent_context.scanner import FileInfo, FileKind |
| 10 | from agent_context.tokens import estimate_tokens_from_text |
| 11 | |
| 12 | # Explainable score contributions. |
| 13 | SCORE_FILENAME = 30 |
| 14 | SCORE_PATH = 25 |
| 15 | SCORE_CONTENT = 20 |
| 16 | SCORE_SYMBOL = 15 |
| 17 | SCORE_TEST = 10 |
| 18 | SCORE_SOURCE_EXT = 5 |
| 19 | SCORE_DOCUMENTATION = 3 |
| 20 | SCORE_CONFIG = 2 |
| 21 | SCORE_DIRECTORY_BOOST = 8 |
| 22 | PENALTY_LARGE = -10 |
| 23 | PENALTY_GENERATED = -30 |
| 24 | PENALTY_OTHER = -5 |
| 25 | |
| 26 | # Max characters to scan for content/symbol relevance. |
| 27 | _CONTENT_SCAN_CHARS = 100_000 |
| 28 | |
| 29 | # Lightweight symbol patterns (language-independent heuristics). |
| 30 | _SYMBOL_PATTERNS: tuple[re.Pattern[str], ...] = ( |
| 31 | re.compile(r"\b(?:class|interface|type|enum|struct|trait|impl)\s+([A-Za-z_][\w]*)"), |
| 32 | re.compile(r"\b(?:def|function|fn|func|fun|method|proc)\s+([A-Za-z_][\w]*)"), |
| 33 | re.compile(r"\b(?:export\s+(?:default\s+)?(?:async\s+)?(?:function|class|const|let|var|type|interface)\s+)([A-Za-z_][\w]*)"), |
| 34 | re.compile(r"^\s*(?:public|private|protected|static|async)?\s*(?:function\s+)?([A-Za-z_][\w]*)\s*\([^;]*\)\s*\{", re.MULTILINE), |
| 35 | re.compile(r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_][\w]*)\s*=", re.MULTILINE), |
| 36 | ) |
| 37 | |
| 38 | _TOKEN_SPLIT = re.compile(r"[^a-z0-9]+", re.IGNORECASE) |
| 39 | _CAMEL_SPLIT = re.compile(r"(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])") |
| 40 | |
| 41 | # Common stopwords that add noise to task matching. |
| 42 | _STOPWORDS = frozenset( |
| 43 | { |
| 44 | "a", "an", "the", "and", "or", "to", "of", "in", "on", "for", "with", |
| 45 | "from", "into", "by", "is", "are", "be", "as", "at", "it", "this", |
| 46 | "that", "fix", "add", "implement", "create", "update", "refactor", |
| 47 | "change", "make", "please", "help", "bug", "issue", "feature", |
| 48 | "code", "file", "files", "need", "want", "should", "would", "could", |
| 49 | } |
| 50 | ) |
| 51 | |
| 52 | |
| 53 | @dataclass(frozen=True) |
| 54 | class ScoreSignal: |
| 55 | """One explainable contribution to a file's score.""" |
| 56 | |
| 57 | name: str |
| 58 | points: int |
| 59 | detail: str = "" |
| 60 | |
| 61 | |
| 62 | @dataclass |
| 63 | class ScoredFile: |
| 64 | """A candidate file with relevance score and signal breakdown.""" |
| 65 | |
| 66 | file: FileInfo |
| 67 | score: int |
| 68 | signals: list[ScoreSignal] = field(default_factory=list) |
| 69 | matched_keywords: list[str] = field(default_factory=list) |
| 70 | |
| 71 | @property |
| 72 | def rel_path(self) -> str: |
| 73 | return self.file.rel_path |
| 74 | |
| 75 | def to_dict(self) -> dict: |
| 76 | return { |
| 77 | "path": self.rel_path, |
| 78 | "score": self.score, |
| 79 | "kind": self.file.kind.value, |
| 80 | "estimated_tokens": self.file.estimated_tokens, |
| 81 | "signals": [ |
| 82 | {"name": s.name, "points": s.points, "detail": s.detail} |
| 83 | for s in self.signals |
| 84 | ], |
| 85 | "matched_keywords": list(self.matched_keywords), |
| 86 | } |
| 87 | |
| 88 | |
| 89 | def tokenize_task(task: str) -> list[str]: |
| 90 | """Extract meaningful lowercase keywords from a task description.""" |
| 91 | raw = _TOKEN_SPLIT.split(task.lower()) |
| 92 | tokens: list[str] = [] |
| 93 | seen: set[str] = set() |
| 94 | for t in raw: |
| 95 | t = t.strip() |
| 96 | if len(t) < 2 or t in _STOPWORDS: |
| 97 | continue |
| 98 | if t not in seen: |
| 99 | seen.add(t) |
| 100 | tokens.append(t) |
| 101 | # Also split camelCase fragments embedded in the task. |
| 102 | for part in _CAMEL_SPLIT.split(t): |
| 103 | p = part.lower() |
| 104 | if len(p) >= 2 and p not in _STOPWORDS and p not in seen: |
| 105 | seen.add(p) |
| 106 | tokens.append(p) |
| 107 | return tokens |
| 108 | |
| 109 | |
| 110 | def _keyword_hits(keywords: list[str], haystack_tokens: set[str], haystack_text: str = "") -> list[str]: |
| 111 | """Return keywords that match tokens or text, including simple stem/prefix matches. |
| 112 | |
| 113 | Examples: ``authentication`` matches token ``auth``; ``auth`` matches |
| 114 | ``authenticate`` in content when the shorter form is a prefix (len >= 3). |
| 115 | """ |
| 116 | hits: list[str] = [] |
| 117 | text = haystack_text.lower() |
| 118 | for kw in keywords: |
| 119 | if kw in haystack_tokens or (text and kw in text): |
| 120 | hits.append(kw) |
| 121 | continue |
| 122 | # Prefix / stem style: auth ↔ authentication |
| 123 | for tok in haystack_tokens: |
| 124 | if len(kw) >= 3 and len(tok) >= 3 and (kw.startswith(tok) or tok.startswith(kw)): |
| 125 | hits.append(kw) |
| 126 | break |
| 127 | else: |
| 128 | if text: |
| 129 | for tok in _TOKEN_SPLIT.split(text): |
| 130 | if len(tok) >= 3 and len(kw) >= 3 and (kw.startswith(tok) or tok.startswith(kw)): |
| 131 | hits.append(kw) |
| 132 | break |
| 133 | # Preserve order, unique |
| 134 | seen: set[str] = set() |
| 135 | ordered: list[str] = [] |
| 136 | for h in hits: |
| 137 | if h not in seen: |
| 138 | seen.add(h) |
| 139 | ordered.append(h) |
| 140 | return ordered |
| 141 | |
| 142 | |
| 143 | def _path_tokens(rel_path: str) -> set[str]: |
| 144 | parts: set[str] = set() |
| 145 | path = Path(rel_path) |
| 146 | for part in path.parts: |
| 147 | stem = Path(part).stem |
| 148 | for piece in _TOKEN_SPLIT.split(stem.lower()): |
| 149 | if len(piece) >= 2: |
| 150 | parts.add(piece) |
| 151 | for piece in _CAMEL_SPLIT.split(stem): |
| 152 | p = piece.lower() |
| 153 | if len(p) >= 2: |
| 154 | parts.add(p) |
| 155 | return parts |
| 156 | |
| 157 | |
| 158 | def _read_text_sample(path: Path, max_chars: int = _CONTENT_SCAN_CHARS) -> str: |
| 159 | try: |
| 160 | with path.open("r", encoding="utf-8", errors="replace") as fh: |
| 161 | return fh.read(max_chars) |
| 162 | except OSError: |
| 163 | return "" |
| 164 | |
| 165 | |
| 166 | def _extract_symbols(text: str) -> set[str]: |
| 167 | symbols: set[str] = set() |
| 168 | for pattern in _SYMBOL_PATTERNS: |
| 169 | for match in pattern.finditer(text): |
| 170 | name = match.group(1) |
| 171 | if name and len(name) >= 2: |
| 172 | symbols.add(name.lower()) |
| 173 | for piece in _CAMEL_SPLIT.split(name): |
| 174 | p = piece.lower() |
| 175 | if len(p) >= 2: |
| 176 | symbols.add(p) |
| 177 | return symbols |
| 178 | |
| 179 | |
| 180 | def score_file(info: FileInfo, keywords: list[str], *, content: str | None = None) -> ScoredFile: |
| 181 | """Score a single file against task keywords. Deterministic.""" |
| 182 | signals: list[ScoreSignal] = [] |
| 183 | matched: set[str] = set() |
| 184 | score = 0 |
| 185 | |
| 186 | if not keywords: |
| 187 | # No task keywords → prefer source/config lightly by kind only. |
| 188 | if info.kind == FileKind.SOURCE: |
| 189 | signals.append(ScoreSignal("source file", SCORE_SOURCE_EXT)) |
| 190 | score += SCORE_SOURCE_EXT |
| 191 | return ScoredFile(file=info, score=score, signals=signals) |
| 192 | |
| 193 | rel = info.rel_path.replace("\\", "/") |
| 194 | path_toks = _path_tokens(rel) |
| 195 | filename = Path(rel).stem.lower() |
| 196 | filename_toks = set(_TOKEN_SPLIT.split(filename)) | { |
| 197 | p.lower() for p in _CAMEL_SPLIT.split(Path(rel).stem) if len(p) >= 2 |
| 198 | } |
| 199 | |
| 200 | # Filename relevance |
| 201 | filename_hits = _keyword_hits(keywords, filename_toks, filename) |
| 202 | if filename_hits: |
| 203 | signals.append( |
| 204 | ScoreSignal("filename match", SCORE_FILENAME, ", ".join(filename_hits)) |
| 205 | ) |
| 206 | score += SCORE_FILENAME |
| 207 | matched.update(filename_hits) |
| 208 | |
| 209 | # Path relevance |
| 210 | dir_part = "/".join(Path(rel).parts[:-1]).lower() |
| 211 | dir_toks = _path_tokens(dir_part) if dir_part else set() |
| 212 | dir_hits = _keyword_hits(keywords, dir_toks, dir_part) |
| 213 | path_hits = _keyword_hits(keywords, path_toks, rel.lower()) |
| 214 | |
| 215 | if dir_hits: |
| 216 | signals.append(ScoreSignal("path match", SCORE_PATH, ", ".join(sorted(set(dir_hits))))) |
| 217 | score += SCORE_PATH |
| 218 | matched.update(dir_hits) |
| 219 | signals.append( |
| 220 | ScoreSignal( |
| 221 | "directory boost", |
| 222 | SCORE_DIRECTORY_BOOST, |
| 223 | ", ".join(sorted(set(dir_hits))), |
| 224 | ) |
| 225 | ) |
| 226 | score += SCORE_DIRECTORY_BOOST |
| 227 | elif path_hits and not filename_hits: |
| 228 | signals.append( |
| 229 | ScoreSignal("path match", SCORE_PATH, ", ".join(sorted(set(path_hits)))) |
| 230 | ) |
| 231 | score += SCORE_PATH |
| 232 | matched.update(path_hits) |
| 233 | |
| 234 | # Content + symbol relevance (lazy read) |
| 235 | text = content if content is not None else _read_text_sample(info.path) |
| 236 | lower = text.lower() if text else "" |
| 237 | |
| 238 | if text: |
| 239 | content_token_set = { |
| 240 | t for t in _TOKEN_SPLIT.split(lower) if len(t) >= 2 |
| 241 | } |
| 242 | content_hits = _keyword_hits(keywords, content_token_set, lower) |
| 243 | if content_hits: |
| 244 | # Scale lightly by hit density but cap at SCORE_CONTENT. |
| 245 | unique = sorted(set(content_hits)) |
| 246 | points = min(SCORE_CONTENT, 8 + 4 * len(unique)) |
| 247 | signals.append(ScoreSignal("content match", points, ", ".join(unique[:8]))) |
| 248 | score += points |
| 249 | matched.update(unique) |
| 250 | |
| 251 | symbols = _extract_symbols(text) |
| 252 | symbol_hits = _keyword_hits(keywords, symbols) |
| 253 | if symbol_hits: |
| 254 | signals.append( |
| 255 | ScoreSignal( |
| 256 | "symbol match", SCORE_SYMBOL, ", ".join(sorted(set(symbol_hits))) |
| 257 | ) |
| 258 | ) |
| 259 | score += SCORE_SYMBOL |
| 260 | matched.update(symbol_hits) |
| 261 | |
| 262 | # Kind / extension signals |
| 263 | if info.kind == FileKind.SOURCE: |
| 264 | signals.append(ScoreSignal("source file", SCORE_SOURCE_EXT)) |
| 265 | score += SCORE_SOURCE_EXT |
| 266 | elif info.kind == FileKind.TEST: |
| 267 | # Tests get a bonus when they already match keywords. |
| 268 | if matched or filename_hits or path_hits: |
| 269 | signals.append(ScoreSignal("test match", SCORE_TEST)) |
| 270 | score += SCORE_TEST |
| 271 | else: |
| 272 | signals.append(ScoreSignal("test", 0)) |
| 273 | elif info.kind == FileKind.DOCUMENTATION: |
| 274 | if matched or any(k in lower for k in keywords): |
| 275 | signals.append(ScoreSignal("documentation", SCORE_DOCUMENTATION)) |
| 276 | score += SCORE_DOCUMENTATION |
| 277 | else: |
| 278 | signals.append(ScoreSignal("documentation", 0)) |
| 279 | elif info.kind == FileKind.CONFIG: |
| 280 | signals.append(ScoreSignal("config", SCORE_CONFIG)) |
| 281 | score += SCORE_CONFIG |
| 282 | else: |
| 283 | signals.append(ScoreSignal("other file", PENALTY_OTHER)) |
| 284 | score += PENALTY_OTHER |
| 285 | |
| 286 | if info.is_large: |
| 287 | signals.append(ScoreSignal("large file penalty", PENALTY_LARGE)) |
| 288 | score += PENALTY_LARGE |
| 289 | |
| 290 | if info.is_generated: |
| 291 | signals.append(ScoreSignal("generated penalty", PENALTY_GENERATED)) |
| 292 | score += PENALTY_GENERATED |
| 293 | |
| 294 | return ScoredFile( |
| 295 | file=info, |
| 296 | score=score, |
| 297 | signals=signals, |
| 298 | matched_keywords=sorted(matched), |
| 299 | ) |
| 300 | |
| 301 | |
| 302 | def rank_files( |
| 303 | files: list[FileInfo], |
| 304 | task: str, |
| 305 | *, |
| 306 | min_score: int = 1, |
| 307 | ) -> list[ScoredFile]: |
| 308 | """Score and rank files. Ties broken by path for determinism.""" |
| 309 | keywords = tokenize_task(task) |
| 310 | scored = [score_file(f, keywords) for f in files] |
| 311 | scored.sort(key=lambda s: (-s.score, s.rel_path)) |
| 312 | if min_score > 0: |
| 313 | filtered = [s for s in scored if s.score >= min_score] |
| 314 | # Always keep at least something if everything scored 0: top source files. |
| 315 | if not filtered and scored: |
| 316 | fallback = [s for s in scored if s.file.kind in {FileKind.SOURCE, FileKind.CONFIG}] |
| 317 | return fallback[:20] if fallback else scored[:10] |
| 318 | return filtered |
| 319 | return scored |
| 320 | |
| 321 | |
| 322 | def format_verbose_score(scored: ScoredFile) -> str: |
| 323 | lines = [ |
| 324 | scored.rel_path, |
| 325 | "", |
| 326 | f"score: {scored.score}", |
| 327 | "", |
| 328 | "signals:", |
| 329 | ] |
| 330 | for sig in scored.signals: |
| 331 | detail = f" ({sig.detail})" if sig.detail else "" |
| 332 | lines.append(f" {sig.name:<22} {sig.points:+d}{detail}") |
| 333 | return "\n".join(lines) + "\n" |
| 334 | |
| 335 | |
| 336 | def content_token_estimate(text: str) -> int: |
| 337 | return estimate_tokens_from_text(text) |