gitutil.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. """
  2. Leaf git/subprocess helpers and diff parsing for the security-guidance plugin.
  3. Everything here is a thin wrapper over ``git``/``subprocess`` plus pure
  4. diff-text parsing and source-file classification. None of these functions
  5. reference any name that the test suite monkeypatches on
  6. ``security_reminder_hook`` and then calls *through* another function in this
  7. module — that property is what makes them safe to live in their own module
  8. while still being re-exported (so tests that patch ``hook._git_toplevel`` and
  9. then call a handler in ``security_reminder_hook`` continue to see the patched
  10. binding).
  11. Functions that DO compose patched leaves (``compute_v2_review_set``,
  12. ``_list_untracked``, ``_append_reviewed_shas``) deliberately remain in
  13. ``security_reminder_hook.py`` for that reason.
  14. """
  15. import contextlib
  16. import os
  17. import re
  18. import subprocess
  19. from _base import debug_log
  20. GIT_CMD = [
  21. "git",
  22. "-c", "core.fsmonitor=false",
  23. "-c", "core.hooksPath=/dev/null",
  24. ]
  25. def _git_rev_parse_head(cwd):
  26. """Return the current HEAD SHA, or None if not a git repo / no commits."""
  27. try:
  28. result = subprocess.run(
  29. [*GIT_CMD, "rev-parse", "HEAD"],
  30. cwd=cwd, capture_output=True, text=True, timeout=5
  31. )
  32. if result.returncode == 0 and result.stdout.strip():
  33. return result.stdout.strip()
  34. return None
  35. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  36. return None
  37. def _find_git_index(cwd):
  38. """
  39. Find the real index file for a git repo. Handles worktrees where .git
  40. is a file pointing to the main repo's gitdir.
  41. Returns the absolute path to the index file, or None.
  42. """
  43. try:
  44. result = subprocess.run(
  45. [*GIT_CMD, "rev-parse", "--git-dir"],
  46. cwd=cwd, capture_output=True, text=True, timeout=5
  47. )
  48. if result.returncode != 0:
  49. return None
  50. git_dir = result.stdout.strip()
  51. if not os.path.isabs(git_dir):
  52. git_dir = os.path.join(cwd, git_dir)
  53. index_path = os.path.join(git_dir, "index")
  54. return index_path if os.path.isfile(index_path) else None
  55. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  56. return None
  57. def _diff_pathspec(cwd, paths):
  58. """Convert absolute touched-paths to repo-relative pathspec args for
  59. git diff. Paths outside cwd (e.g. ~/.claude/…) are dropped. Returns the
  60. list to splice after `--`, or [] for an unrestricted diff. realpath both
  61. sides so the macOS /var ↔ /private/var symlink doesn't make in-repo
  62. paths look external."""
  63. if not paths:
  64. return []
  65. cwd_abs = os.path.realpath(cwd)
  66. rel = []
  67. for p in paths:
  68. try:
  69. r = os.path.relpath(os.path.realpath(p), cwd_abs)
  70. except ValueError:
  71. continue
  72. if r.startswith(".."):
  73. continue
  74. rel.append(r)
  75. return ["--"] + rel if rel else []
  76. @contextlib.contextmanager
  77. def _temp_index(cwd, untracked_paths=None):
  78. """Yield an env dict pointing GIT_INDEX_FILE at a throwaway copy of the
  79. repo's index with `git add --intent-to-add` applied, so untracked files
  80. show up in subsequent `git diff` calls without touching the user's real
  81. index. Yields None if no index can be found (bare repo / not a repo); the
  82. caller should fall back to a plain diff. Always cleans up the temp file.
  83. Perf: when `untracked_paths` is given, only those paths are added (O(n)
  84. in untracked count). The default `add -N .` stats every file in the
  85. worktree — slow in large repos vs fast targeted scan. v2 callers
  86. already know the untracked set from `git status --porcelain`, so they
  87. pass it; v1 keeps the whole-tree scan since it has no prior list."""
  88. import shutil
  89. import tempfile
  90. real_index = _find_git_index(cwd)
  91. if not real_index:
  92. yield None
  93. return
  94. tmp_fd, tmp_index = tempfile.mkstemp(prefix="security_hook_idx_")
  95. os.close(tmp_fd)
  96. try:
  97. shutil.copy2(real_index, tmp_index)
  98. env = {**os.environ, "GIT_INDEX_FILE": tmp_index}
  99. if untracked_paths is None:
  100. add_args = ["."]
  101. elif untracked_paths:
  102. # `git add -N -- a b nonexistent` is atomic — one missing path
  103. # makes it exit 128 and add NOTHING, so a file removed between
  104. # `git status` and here would silently drop ALL untracked files
  105. # from the diff. --ignore-missing only works with --dry-run, so
  106. # filter to surviving paths (lexists so dangling symlinks count).
  107. surviving = [p for p in untracked_paths
  108. if os.path.lexists(os.path.join(cwd, p))]
  109. add_args = ["--"] + surviving if surviving else None
  110. else:
  111. add_args = None
  112. if add_args:
  113. subprocess.run(
  114. [*GIT_CMD, "add", "--intent-to-add"] + add_args,
  115. cwd=cwd, capture_output=True, text=True, timeout=10,
  116. env=env,
  117. )
  118. yield env
  119. finally:
  120. try:
  121. os.unlink(tmp_index)
  122. except OSError:
  123. pass
  124. def _git_toplevel(cwd):
  125. """Absolute repo root for `cwd`, or None if not in a work tree."""
  126. try:
  127. r = subprocess.run(
  128. [*GIT_CMD, "rev-parse", "--show-toplevel"],
  129. cwd=cwd, capture_output=True, text=True, timeout=5,
  130. )
  131. return r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None
  132. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  133. return None
  134. def _git_dir(repo_root):
  135. """Absolute shared `.git` directory for repo_root.
  136. Uses `rev-parse --git-common-dir` so linked worktrees resolve to the
  137. SHARED gitdir, not the per-worktree `.git/worktrees/<name>/`. That way
  138. push-sweep's reviewed-shas record (and the bash-hook-once sentinel)
  139. is per-clone — a commit reviewed in one worktree counts as reviewed
  140. if a different worktree later pushes it. Returns None on failure so
  141. callers can degrade (push-sweep state is best-effort).
  142. """
  143. try:
  144. r = subprocess.run(
  145. [*GIT_CMD, "rev-parse", "--git-common-dir"],
  146. cwd=repo_root, capture_output=True, text=True, timeout=5,
  147. )
  148. if r.returncode != 0:
  149. return None
  150. d = r.stdout.strip()
  151. return d if os.path.isabs(d) else os.path.join(repo_root, d)
  152. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  153. return None
  154. def _git_rev_list_range(repo_root, base, head="HEAD"):
  155. """Shas in `base..head`, oldest→newest. Empty list on error."""
  156. try:
  157. r = subprocess.run(
  158. [*GIT_CMD, "rev-list", "--reverse", f"{base}..{head}"],
  159. cwd=repo_root, capture_output=True, text=True, timeout=10,
  160. )
  161. if r.returncode != 0:
  162. return []
  163. return [s for s in r.stdout.strip().split("\n") if s]
  164. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  165. return []
  166. def _git_diff_range(repo_root, base, head="HEAD"):
  167. """`git diff -p base head` as text on success, None on error.
  168. Distinguishing failure from success-with-empty-diff matters: the push-sweep
  169. caller marks the tail reviewed when the diff is empty (nothing to review),
  170. but on failure (timeout, non-zero exit, missing git) it must NOT mark
  171. them reviewed — otherwise unreviewed commits get permanently silenced.
  172. """
  173. try:
  174. r = subprocess.run(
  175. [*GIT_CMD, "diff", "-p", "--no-color", "--no-ext-diff", base, head],
  176. cwd=repo_root, capture_output=True, timeout=30,
  177. )
  178. if r.returncode != 0:
  179. return None
  180. return r.stdout.decode("utf-8", errors="replace")
  181. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  182. return None
  183. def _detect_main_branch(repo_root):
  184. for ref in ("origin/HEAD", "origin/main", "origin/master", "main", "master"):
  185. try:
  186. r = subprocess.run(
  187. [*GIT_CMD, "rev-parse", "--verify", "-q", ref],
  188. cwd=repo_root, capture_output=True, text=True, timeout=5,
  189. )
  190. if r.returncode == 0 and r.stdout.strip():
  191. return ref
  192. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  193. pass
  194. return None
  195. def _git_reflog_recent_commits(repo_root, max_age_s=120, max_n=5):
  196. """Return (fresh_commit_shas, stale_count) from the HEAD reflog.
  197. Scans the last `max_n` reflog entries and returns the SHAs whose action is
  198. `commit*` AND whose commit timestamp is within `max_age_s` of now,
  199. newest-first. `stale_count` is the number of commit-action entries that
  200. were too old (so the caller can distinguish "no commit happened" from
  201. "commit happened earlier than the window").
  202. Used by commit-review when stdout-based `[branch sha]` detection fails
  203. (output piped/redirected/-q, or a chained command after `git commit`
  204. pushed the success line off — `git commit && git push` makes HEAD@{0}
  205. `update by push`, not `commit:`). The HEAD@{0}-only check
  206. keeps the not-yet-visible-HEAD skip rare; analysis showed the
  207. residual is dominated by these chained-command and noop-guard cases.
  208. Safety vs. blindly reading HEAD:
  209. - cross-repo (`cd ../other && git commit`): repo_root's own reflog has
  210. no fresh commit, so this returns ([], 0).
  211. - commit actually failed (pre-commit reject, nothing-staged): reflog's
  212. recent entries are the prior checkout/commit/reset → ([], 0) or only
  213. stale entries.
  214. - HEAD raced ahead (a second commit landed before this async hook ran):
  215. both commits appear in the scan and both get reviewed — correct.
  216. - prior Bash call's commit within the window: would be returned here,
  217. but the call site deduplicates against `.git/sg-reviewed-shas` so a
  218. SHA is reviewed at most once. This is also the non-overlap invariant
  219. with push-sweep.
  220. """
  221. if not repo_root:
  222. return [], 0
  223. try:
  224. # %gs (the reflog subject) is `commit: <commit-msg first line>` and can
  225. # contain `|`; put it LAST so split("|", 2) leaves it intact. %H is
  226. # hex and %ct is integer, so the first two fields are delimiter-safe.
  227. r = subprocess.run(
  228. [*GIT_CMD, "log", "-g", "-n", str(max_n),
  229. "--format=%H|%ct|%gs", "HEAD"],
  230. cwd=repo_root, capture_output=True, text=True, timeout=5,
  231. )
  232. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  233. return [], 0
  234. if r.returncode != 0:
  235. return [], 0
  236. import time as _time
  237. now = int(_time.time())
  238. fresh, stale = [], 0
  239. for idx, line in enumerate(r.stdout.splitlines()):
  240. parts = line.split("|", 2)
  241. if len(parts) != 3:
  242. continue
  243. sha, ct, subject = parts
  244. # `commit: msg`, `commit (amend): msg`, `commit (initial): msg`,
  245. # `commit (merge): msg` — all create a reviewable commit object.
  246. if not subject.startswith("commit"):
  247. continue
  248. try:
  249. age = now - int(ct)
  250. except ValueError:
  251. continue
  252. # HEAD@{0} (idx==0) is exempt from the age gate. The gate exists to
  253. # bound the WIDENED HEAD@{1..max_n-1} scan from picking up commits
  254. # made by *prior* Bash calls; HEAD@{0} is by definition the most
  255. # recent reflog entry and was previously accepted unconditionally
  256. # (_git_reflog_head_if_just_committed previously had no age check).
  257. # Applying max_age_s to idx==0 made the not-yet-visible-HEAD skip
  258. # noticeably more frequent on chained
  259. # `git commit && <slow command>` where %ct is >120s old by the
  260. # time the async PostToolUse hook fires.
  261. if idx == 0 or age <= max_age_s:
  262. fresh.append(sha)
  263. else:
  264. stale += 1
  265. return fresh, stale
  266. def _git_name_only(cwd, base, include_untracked=False):
  267. """Return the set of repo-root-relative paths that differ from `base`,
  268. or None if git failed (unresolvable ref, not a repo, timeout). Callers
  269. must distinguish None (error → don't trust as a filter) from set()
  270. (genuinely nothing changed). `-c core.quotePath=false -z` keeps non-ASCII
  271. and space-containing paths intact."""
  272. def _run(env):
  273. result = subprocess.run(
  274. [*GIT_CMD, "-c", "core.quotePath=false", "diff", "--name-only", "-z", base],
  275. cwd=cwd, capture_output=True, text=True, timeout=30,
  276. env=env,
  277. )
  278. if result.returncode != 0:
  279. debug_log(f"_git_name_only({base!r}) rc={result.returncode}: {result.stderr[:200]}")
  280. return None
  281. return {p for p in result.stdout.split("\0") if p}
  282. try:
  283. if not include_untracked:
  284. return _run(None)
  285. with _temp_index(cwd) as env:
  286. return _run(env)
  287. except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
  288. debug_log(f"_git_name_only({base!r}) error: {e}")
  289. return None
  290. def _git_status_porcelain(cwd):
  291. """One `git status --porcelain=v1 -z` → (tracked_dirty, untracked) sets of
  292. repo-root-relative paths, or (None, None) on error. Replaces the
  293. `_temp_index + git diff HEAD --name-only` pair for the v2 dirty_now
  294. computation: faster in large repos, and yields the
  295. untracked set separately so the later get_git_diff can do a targeted
  296. `add -N -- <files>` instead of a whole-tree `add -N .`.
  297. -uall: list individual files inside untracked directories (default
  298. collapses to `dir/`). Required so the untracked set subtracts cleanly
  299. against the UPS-time `_list_untracked` snapshot, which uses ls-files and
  300. therefore always lists individual files."""
  301. try:
  302. r = subprocess.run(
  303. [*GIT_CMD, "-c", "core.quotePath=false", "status",
  304. "--porcelain=v1", "-uall", "-z"],
  305. cwd=cwd, capture_output=True, text=True, timeout=30,
  306. )
  307. if r.returncode != 0:
  308. debug_log(f"_git_status_porcelain rc={r.returncode}: {r.stderr[:200]}")
  309. return None, None
  310. tracked, untracked = set(), set()
  311. entries = r.stdout.split("\0")
  312. i = 0
  313. while i < len(entries):
  314. e = entries[i]
  315. if not e:
  316. i += 1
  317. continue
  318. xy, path = e[:2], e[3:]
  319. if xy == "??":
  320. untracked.add(path)
  321. else:
  322. tracked.add(path)
  323. # Rename/copy entries are XY old\0new\0 — second NUL field is
  324. # the origin path; consume it so it isn't misparsed as a new
  325. # 2-char-status entry.
  326. if "R" in xy or "C" in xy:
  327. i += 1
  328. i += 1
  329. return tracked, untracked
  330. except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
  331. debug_log(f"_git_status_porcelain error: {e}")
  332. return None, None
  333. def _is_ancestor(cwd, maybe_ancestor, descendant):
  334. """True if `maybe_ancestor` is reachable from `descendant` (i.e. HEAD
  335. moved forward via commit/merge, not sideways via checkout)."""
  336. try:
  337. result = subprocess.run(
  338. [*GIT_CMD, "merge-base", "--is-ancestor", maybe_ancestor, descendant],
  339. cwd=cwd, capture_output=True, text=True, timeout=5,
  340. )
  341. return result.returncode == 0
  342. except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
  343. return False
  344. def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_paths=None):
  345. """
  346. Get the git diff between the baseline SHA and the current working tree,
  347. including untracked (new) files.
  348. Uses a temporary copy of the git index (GIT_INDEX_FILE) so the user's
  349. real index is never modified. The temp index gets intent-to-add entries
  350. for untracked files, making them visible in the diff output. Cleanup
  351. is just deleting the temp file in a finally block.
  352. If `paths` is given, the diff is restricted to those paths (relative to
  353. cwd; absolute paths are converted, paths outside cwd are dropped).
  354. `untracked_paths` (repo-root-relative) is forwarded to _temp_index so it
  355. can add only those files instead of scanning the whole worktree.
  356. """
  357. pathspec = _diff_pathspec(cwd, paths)
  358. if paths and not pathspec:
  359. # Caller restricted to specific paths but none are inside this repo
  360. # (e.g. only ~/.claude/... edits). Returning "" flows to skip(6); an
  361. # empty pathspec would mean an UNRESTRICTED diff — the bug this whole
  362. # change exists to fix.
  363. return ""
  364. cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
  365. try:
  366. with _temp_index(cwd, untracked_paths) as env:
  367. # env is None when no index could be found (bare repo / not a
  368. # repo) — diff still runs, just without untracked-file support.
  369. result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30, env=env)
  370. if result.returncode != 0:
  371. debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}")
  372. return None
  373. # Decode with errors='replace' so binary diffs don't crash
  374. return result.stdout.decode("utf-8", errors="replace")
  375. except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
  376. debug_log(f"git diff error: {e}")
  377. return None
  378. # Source file extensions worth reviewing for security
  379. SOURCE_CODE_EXTENSIONS = {
  380. '.py', '.js', '.ts', '.jsx', '.tsx', '.go', '.java', '.rb', '.php',
  381. '.rs', '.c', '.cpp', '.h', '.hpp', '.cs', '.swift', '.kt', '.scala',
  382. '.html', '.htm', '.ejs', '.yaml', '.yml', '.properties',
  383. '.mjs', '.cjs', '.mts', '.cts', '.vue', '.svelte',
  384. '.sh', '.bash', '.zsh', '.fish', '.ksh', '.ps1', '.sql',
  385. '.gradle', '.groovy',
  386. '.tf', '.hcl', '.tfvars',
  387. '.json', '.toml', '.ipynb',
  388. }
  389. # Reviewable files identified by basename rather than extension (lowercased).
  390. # These are by-convention extensionless but contain executable recipes/DSL
  391. # with shell/exec surface (Make recipes, Jenkinsfile Groovy, Rakefile Ruby).
  392. SOURCE_CODE_BASENAMES = {
  393. 'dockerfile', 'makefile', 'gnumakefile', 'jenkinsfile', 'vagrantfile',
  394. 'rakefile', 'gemfile', 'procfile', 'brewfile', 'justfile',
  395. }
  396. # Extensionless basenames that are NOT source — plain-text metadata. Anything
  397. # extensionless not in this set is treated as source (likely a shebang script
  398. # under bin/ or scripts/). Analysis of skipped reviews found
  399. # extensionless executables (bin/deploy, scripts/run-canary) were the largest
  400. # remaining false-negative class — they carry shell-injection surface but
  401. # `splitext` gives '' so they were filtered out. _cap_files_for_prompt bounds
  402. # the byte cost downstream, and the reviewer ignores prose, so opting
  403. # extensionless IN with this small deny-list is the better default than
  404. # opting OUT.
  405. NON_SOURCE_EXTENSIONLESS_BASENAMES = {
  406. 'license', 'licence', 'copying', 'notice', 'patents', 'authors',
  407. 'contributors', 'maintainers', 'changelog', 'changes', 'news',
  408. 'readme', 'todo', 'install', 'version', 'codeowners',
  409. 'owners', 'copyright',
  410. }
  411. # Directory components and file suffixes that are never worth reviewing even
  412. # when the extension is in SOURCE_CODE_EXTENSIONS — vendored deps, build
  413. # output, generated code, minified bundles, lockfiles, protobuf stubs.
  414. # Matched as path *components* (so `node_modules/` matches anywhere in the
  415. # path, not just as a prefix) and as case-sensitive suffixes (the ecosystems
  416. # that emit `.min.js` / `_pb2.py` / `.pb.go` are case-consistent).
  417. SKIP_PATH_PATTERNS = (
  418. 'node_modules/', 'dist/', 'build/', '.next/', 'vendor/',
  419. '__generated__/', '__pycache__/', '.venv/', 'target/',
  420. )
  421. SKIP_FILE_SUFFIXES = (
  422. '.min.js', '.min.css', '.d.ts', '.d.mts', '.d.cts',
  423. '.lock', '_pb2.py', '.pb.go',
  424. )
  425. # Path tokens that bump a file's review priority when a commit exceeds
  426. # MAX_DIFF_FILES and we have to pick a subset. These are exactly the surfaces
  427. # single-shot and agentic reviews disagree on most (auth, routing, IPC,
  428. # subprocess, deserialization). Matched as lowercase substrings against the
  429. # path; not regex — keep it cheap.
  430. _SECURITY_RISK_PATH_TOKENS = (
  431. "auth", "login", "session", "token", "secret", "credential", "perm",
  432. "acl", "rbac", "iam", "policy",
  433. "route", "handler", "controller", "endpoint", "api/", "/api", "gateway",
  434. "middleware", "view",
  435. "exec", "subprocess", "shell", "spawn", "command",
  436. "client", "request", "fetch", "http", "url",
  437. "serialize", "pickle", "yaml", "parse", "deser",
  438. # Short tokens that would substring-match unrelated names (`format`,
  439. # `transform`, `sandbox`, `platform`) are intentionally omitted —
  440. # `sql`/`query` already cover the DB surface.
  441. "sql", "query",
  442. )
  443. # Suffixes that pass _is_reviewable_source but are almost always low-signal
  444. # in large scaffolds — generated clients, migrations, test fixtures, config
  445. # shims. These go to the BACK of the priority sort, not dropped outright.
  446. _LOW_PRIORITY_SUFFIXES = (
  447. ".gen.ts", ".gen.tsx", ".generated.ts", "_gen.py",
  448. ".test.ts", ".test.tsx", ".test.py", ".spec.ts", ".spec.js",
  449. ".config.js", ".config.ts", ".config.mjs", ".config.cjs",
  450. )
  451. _LOW_PRIORITY_PATH_TOKENS = (
  452. "/migrations/", "/alembic/versions/", "/__tests__/", "/fixtures/",
  453. )
  454. def _prioritize_diff_files(diff_files, cap):
  455. """When `diff_files` exceeds `cap`, return the top-`cap` by security
  456. relevance plus the count dropped. Otherwise return (diff_files, 0).
  457. Score = (risk_tokens_in_path, not_low_priority, added_lines). The
  458. added-lines proxy is `content.count('\\n+')` which counts diff additions
  459. cheaply without re-parsing hunks. This is a heuristic, not a guarantee —
  460. the goal is to review the likely-dangerous subset of an over-cap diff
  461. instead of reviewing nothing. Diffs that exceed the cap are typically
  462. large multi-file scaffolds, and the cross-file source→sink vulnerabilities
  463. in them concentrate in a handful of api/client/route files.
  464. """
  465. if len(diff_files) <= cap:
  466. return diff_files, 0
  467. def _score(item):
  468. fp, content = item
  469. low = fp.lower()
  470. # Prepend "/" so leading-slash patterns in _LOW_PRIORITY_PATH_TOKENS
  471. # match top-level dirs (git diff paths are repo-root-relative, e.g.
  472. # `migrations/001.py` not `/migrations/001.py`). Same trick as
  473. # _is_reviewable_source.
  474. low_slashed = "/" + low
  475. risk = sum(1 for t in _SECURITY_RISK_PATH_TOKENS if t in low)
  476. low_prio = (
  477. fp.endswith(_LOW_PRIORITY_SUFFIXES)
  478. or any(t in low_slashed for t in _LOW_PRIORITY_PATH_TOKENS)
  479. )
  480. # added_lines: count('\n+') over-counts by including '+++' header and
  481. # any literal '+' at line start in context, but it's a consistent
  482. # ordinal across files in the same diff which is all we need.
  483. added = content.count("\n+")
  484. return (risk, not low_prio, added)
  485. ranked = sorted(diff_files, key=_score, reverse=True)
  486. return ranked[:cap], len(diff_files) - cap
  487. def _is_reviewable_source(file_path):
  488. # Normalize for component matching: a path like `.next/x.js` or
  489. # `pkg/node_modules/y.ts` should both be excluded; matching against
  490. # `'/' + path` lets each pattern be checked as `'/' + p in '/' + path`
  491. # without false-positiving on `rebuild/` matching `build/`.
  492. norm = "/" + file_path.replace("\\", "/")
  493. if any(("/" + p) in norm for p in SKIP_PATH_PATTERNS):
  494. return False
  495. if file_path.endswith(SKIP_FILE_SUFFIXES):
  496. return False
  497. ext = os.path.splitext(file_path)[1].lower()
  498. if ext in SOURCE_CODE_EXTENSIONS:
  499. return True
  500. base = os.path.basename(file_path).lower()
  501. # Accept dot-suffixed variants too: `Dockerfile.dev`, `Makefile.am`,
  502. # `Jenkinsfile.release`. splitext gives ext='.dev'/'.am' for these so they
  503. # miss both the extension check and the exact-basename check otherwise.
  504. if base in SOURCE_CODE_BASENAMES \
  505. or base.split(".", 1)[0] in SOURCE_CODE_BASENAMES:
  506. return True
  507. # Extensionless files default to reviewable unless they're known
  508. # plain-text metadata or dotfiles. Covers shebang scripts under bin/ or
  509. # scripts/ (`deploy`, `run-canary`, `entrypoint`) which carry
  510. # shell-injection surface but were previously filtered out — the largest
  511. # remaining false-negative class for extensionless files. Dotfiles (`.gitignore`,
  512. # `.nvmrc`, `.env`) are config, not code; `.bashrc`-style runnables are
  513. # rare in repos and not worth the noise. The deny-list is prefix-aware on
  514. # `-`/`_` so dual-license / i18n variants (`LICENSE-MIT`, `README-CN`)
  515. # don't fall through as source.
  516. if ext == "" and not base.startswith("."):
  517. if any(base == x or base.startswith(x + "-") or base.startswith(x + "_")
  518. for x in NON_SOURCE_EXTENSIONLESS_BASENAMES):
  519. return False
  520. return True
  521. return False
  522. def extract_file_paths_from_diff(diff_output):
  523. """
  524. Extract file paths from unified diff output (without content).
  525. Only includes files with source code extensions.
  526. Returns a list of file paths.
  527. """
  528. if not diff_output or not diff_output.strip():
  529. return []
  530. paths = []
  531. file_diffs = diff_output.split("diff --git ")
  532. for file_diff in file_diffs:
  533. if not file_diff.strip():
  534. continue
  535. lines = file_diff.split('\n')
  536. header_match = re.match(r'^a/(.+?) b/(.+)$', lines[0])
  537. if not header_match:
  538. continue
  539. file_path = header_match.group(2) or header_match.group(1) or ''
  540. if not _is_reviewable_source(file_path):
  541. continue
  542. paths.append(file_path)
  543. return paths
  544. def parse_diff_into_files(diff_output):
  545. """
  546. Parse unified diff output into a list of (file_path, diff_content) tuples.
  547. Only includes files with source code extensions.
  548. """
  549. if not diff_output or not diff_output.strip():
  550. return []
  551. files = []
  552. file_diffs = diff_output.split("diff --git ")
  553. for file_diff in file_diffs:
  554. if not file_diff.strip():
  555. continue
  556. # Extract filename from first line: "a/path/to/file b/path/to/file"
  557. lines = file_diff.split('\n')
  558. header_match = re.match(r'^a/(.+?) b/(.+)$', lines[0])
  559. if not header_match:
  560. continue
  561. file_path = header_match.group(2) or header_match.group(1) or ''
  562. # Filter to source code files only
  563. if not _is_reviewable_source(file_path):
  564. continue
  565. # Extract the diff content (from first @@ onwards)
  566. diff_lines = []
  567. in_hunks = False
  568. for line in lines[1:]:
  569. if line.startswith('@@'):
  570. in_hunks = True
  571. if in_hunks:
  572. diff_lines.append(line)
  573. if diff_lines:
  574. files.append((file_path, '\n'.join(diff_lines)))
  575. return files
  576. def filter_preexisting_from_diff(diff_files, cwd, baseline_sha):
  577. """
  578. Filter out pre-existing content from diff files.
  579. When a file is fully rewritten (Write tool replaces entire content),
  580. git shows all lines as removed (-) then re-added (+). This function
  581. detects such rewrites and strips lines from the + section that also
  582. appeared in the - section, so the LLM reviewer only sees truly new code.
  583. """
  584. if not baseline_sha:
  585. return diff_files
  586. filtered = []
  587. for file_path, diff_content in diff_files:
  588. lines = diff_content.split('\n')
  589. # Collect removed and added lines (stripping the +/- prefix)
  590. removed_lines = set()
  591. added_lines = []
  592. for line in lines:
  593. if line.startswith('-') and not line.startswith('---'):
  594. removed_lines.add(line[1:].strip())
  595. elif line.startswith('+') and not line.startswith('+++'):
  596. added_lines.append(line[1:].strip())
  597. if not removed_lines:
  598. # New file, no pre-existing content to filter
  599. filtered.append((file_path, diff_content))
  600. continue
  601. # Check what fraction of added lines were pre-existing
  602. preexisting_count = sum(1 for l in added_lines if l in removed_lines)
  603. if preexisting_count == 0:
  604. filtered.append((file_path, diff_content))
  605. continue
  606. added_lines_set = set(added_lines)
  607. # Rebuild diff with pre-existing lines converted to context (space prefix).
  608. # Known imprecision: .strip() matches across indentation (so reindented
  609. # code is treated as unchanged) and the set lets one removal mask N
  610. # additions of the same stripped text. Accepted trade-off — this filter
  611. # exists for the full-file Write rewrite case where exact-match would
  612. # miss everything; the diff-review prompt's previous-findings recheck
  613. # is the backstop.
  614. new_lines = []
  615. for line in lines:
  616. if line.startswith('+') and not line.startswith('+++'):
  617. content = line[1:].strip()
  618. if content in removed_lines:
  619. # Convert to context line (pre-existing, not new)
  620. new_lines.append(' ' + line[1:])
  621. else:
  622. new_lines.append(line)
  623. elif line.startswith('-') and not line.startswith('---'):
  624. content = line[1:].strip()
  625. if content in added_lines_set:
  626. # Skip removed lines that were re-added (they become context)
  627. continue
  628. else:
  629. new_lines.append(line)
  630. else:
  631. new_lines.append(line)
  632. filtered.append((file_path, '\n'.join(new_lines)))
  633. return filtered