codescope-ai 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. codescope/__init__.py +3 -0
  2. codescope/__main__.py +3 -0
  3. codescope/ai/__init__.py +0 -0
  4. codescope/ai/agent.py +191 -0
  5. codescope/ai/answer.py +89 -0
  6. codescope/ai/redact.py +54 -0
  7. codescope/ai/reviewer.py +187 -0
  8. codescope/ai/schemas.py +69 -0
  9. codescope/ai/summarizer.py +388 -0
  10. codescope/cli.py +605 -0
  11. codescope/config.py +192 -0
  12. codescope/docs/__init__.py +0 -0
  13. codescope/docs/writer.py +432 -0
  14. codescope/evaluation/__init__.py +0 -0
  15. codescope/evaluation/report.py +252 -0
  16. codescope/evaluation/runner.py +296 -0
  17. codescope/gitutils.py +92 -0
  18. codescope/graph/__init__.py +0 -0
  19. codescope/graph/components.py +25 -0
  20. codescope/graph/model.py +81 -0
  21. codescope/graph/modules.py +61 -0
  22. codescope/graph/resolver.py +349 -0
  23. codescope/index/__init__.py +0 -0
  24. codescope/index/builder.py +81 -0
  25. codescope/index/chunker.py +164 -0
  26. codescope/index/search.py +144 -0
  27. codescope/llm/__init__.py +0 -0
  28. codescope/llm/base.py +108 -0
  29. codescope/llm/client.py +164 -0
  30. codescope/llm/gemini.py +216 -0
  31. codescope/llm/ratelimit.py +43 -0
  32. codescope/mcp_server.py +147 -0
  33. codescope/models.py +137 -0
  34. codescope/parsing/__init__.py +0 -0
  35. codescope/parsing/python.py +246 -0
  36. codescope/pipeline.py +145 -0
  37. codescope/review/__init__.py +0 -0
  38. codescope/review/analysis.py +292 -0
  39. codescope/review/diff.py +100 -0
  40. codescope/review/run.py +118 -0
  41. codescope/scanner/__init__.py +0 -0
  42. codescope/scanner/files.py +156 -0
  43. codescope/storage/__init__.py +0 -0
  44. codescope/storage/db.py +519 -0
  45. codescope/templates/architecture.md.j2 +38 -0
  46. codescope/templates/module.md.j2 +94 -0
  47. codescope/templates/overview.md.j2 +100 -0
  48. codescope/templates/prompts/agent.j2 +13 -0
  49. codescope/templates/prompts/ask.j2 +15 -0
  50. codescope/templates/prompts/component_summary.j2 +8 -0
  51. codescope/templates/prompts/file_summary.j2 +19 -0
  52. codescope/templates/prompts/project_summary.j2 +15 -0
  53. codescope/templates/prompts/review.j2 +40 -0
  54. codescope/templates/prompts/system.j2 +8 -0
  55. codescope/templates/review.md.j2 +113 -0
  56. codescope/tools.py +114 -0
  57. codescope_ai-0.1.0.dist-info/METADATA +214 -0
  58. codescope_ai-0.1.0.dist-info/RECORD +61 -0
  59. codescope_ai-0.1.0.dist-info/WHEEL +4 -0
  60. codescope_ai-0.1.0.dist-info/entry_points.txt +2 -0
  61. codescope_ai-0.1.0.dist-info/licenses/LICENSE +21 -0
codescope/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """CodeScope: scan a codebase, document it, and review changes."""
2
+
3
+ __version__ = "0.1.0"
codescope/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from codescope.cli import app
2
+
3
+ app(prog_name="codescope")
File without changes
codescope/ai/agent.py ADDED
@@ -0,0 +1,191 @@
1
+ """Answer questions with an agent: the model searches and reads the code itself, step by step.
2
+
3
+ `ask` (ai/answer.py) searches once and answers from those sources. Here the model gets two
4
+ tools and decides what to look at next, so it can follow a trail through several files:
5
+ read `return_book`, see it calls `should_block`, read that too.
6
+
7
+ 1. Loop: the model asks for tools, we run them and send the results back, until it answers
8
+ or MAX_STEPS is reached. At the limit it gets one more turn with the tools switched off.
9
+ 2. Sources: every piece of code a tool returns gets a number, [S1], [S2], ... (secrets removed).
10
+ 3. Verify: the answer must cite those numbers, checked exactly like `ask`.
11
+
12
+ Every model turn is one request through LLMClient, so the budget, rate limit and retries apply.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass, field
19
+
20
+ from jinja2 import Environment, PackageLoader, StrictUndefined
21
+
22
+ from codescope.ai.answer import verify_citations
23
+ from codescope.config import Config
24
+ from codescope.index.search import Hit
25
+ from codescope.llm.base import LLMError, Tool, ToolCall
26
+ from codescope.llm.client import LLMClient
27
+ from codescope.models import Chunk
28
+ from codescope.storage.db import Database
29
+ from codescope.tools import CodeTools, ToolError
30
+
31
+ MAX_STEPS = 8 # model turns with tools; one more turn without tools if it has not answered
32
+ SEARCH_RESULTS = 5 # matches per search
33
+ SHOW_CODE = 3 # of those, how many come back with their code (the rest by name only)
34
+
35
+ TOOLS = [
36
+ Tool(
37
+ "search_code",
38
+ "Search the project by keywords or meaning. Returns the code of the best matches, "
39
+ "numbered as sources, and the names of a few more.",
40
+ {"query": "What to look for, e.g. 'late fine' or 'MAX_RENEWALS'"},
41
+ ),
42
+ Tool(
43
+ "read_code",
44
+ "Read the full source code of one class, function or method by its name.",
45
+ {"name": "e.g. 'calculate_fine', 'LoanService' or 'LoanService.renew'"},
46
+ ),
47
+ ]
48
+
49
+
50
+ @dataclass(slots=True)
51
+ class AgentStep:
52
+ """One tool the model asked for, for the trace shown to the user."""
53
+
54
+ tool: str
55
+ args: dict[str, str]
56
+ sources: list[int] = field(default_factory=list) # source numbers the result added
57
+ note: str = "" # e.g. "no matches"
58
+
59
+
60
+ @dataclass(slots=True)
61
+ class AgentResult:
62
+ question: str
63
+ sources: list[Hit] = field(default_factory=list) # [S1] is sources[0]
64
+ steps: list[AgentStep] = field(default_factory=list)
65
+ answer: str = ""
66
+ found: bool = False
67
+ cited: list[int] = field(default_factory=list) # 1-based source numbers used in the answer
68
+ invalid_citations: int = 0
69
+ turns: int = 0 # model turns, i.e. requests for the agent itself
70
+ forced: bool = False # the step limit was reached and the answer was asked for
71
+ error: str | None = None
72
+
73
+
74
+ def ask_agent(
75
+ db: Database, config: Config, question: str, llm: LLMClient, max_steps: int = MAX_STEPS
76
+ ) -> AgentResult:
77
+ return _Agent(db, config, llm, max_steps).run(question)
78
+
79
+
80
+ class _Agent:
81
+ def __init__(self, db: Database, config: Config, llm: LLMClient, max_steps: int) -> None:
82
+ self.code = CodeTools(db, config, llm) # the tools, shared with the MCP server
83
+ self.llm = llm
84
+ self.max_steps = max_steps
85
+ self.result = AgentResult(question="")
86
+ self.numbers: dict[tuple[str, int, int], int] = {} # (path, start, end) -> [S..]
87
+ self.tools: dict[str, Callable[[ToolCall, AgentStep], str]] = {
88
+ "search_code": self._search_code,
89
+ "read_code": self._read_code,
90
+ }
91
+ env = Environment(
92
+ loader=PackageLoader("codescope", "templates"),
93
+ autoescape=False,
94
+ trim_blocks=True,
95
+ lstrip_blocks=True,
96
+ undefined=StrictUndefined,
97
+ )
98
+ self.system = (
99
+ env.get_template("prompts/system.j2").render()
100
+ + "\n\n"
101
+ + env.get_template("prompts/agent.j2").render(
102
+ project=config.project_name, max_steps=max_steps
103
+ )
104
+ )
105
+
106
+ def run(self, question: str) -> AgentResult:
107
+ result = self.result
108
+ result.question = question
109
+ turns = [self.llm.user_turn(question)]
110
+ text = ""
111
+ try:
112
+ for _ in range(self.max_steps):
113
+ reply = self.llm.next_turn(system=self.system, turns=turns, tools=TOOLS)
114
+ result.turns += 1
115
+ turns.append(reply.turn)
116
+ if not reply.calls:
117
+ text = reply.text
118
+ break
119
+ turns.append(self.llm.tool_results_turn([self._run(c) for c in reply.calls]))
120
+ else: # the step limit: one last turn, tools off, so the work so far is not lost
121
+ result.forced = True
122
+ turns.append(
123
+ self.llm.user_turn(
124
+ "You have reached the step limit. Answer now from the code you have "
125
+ "been given, and say clearly if anything is still unknown."
126
+ )
127
+ )
128
+ reply = self.llm.next_turn(
129
+ system=self.system, turns=turns, tools=TOOLS, use_tools=False
130
+ )
131
+ result.turns += 1
132
+ text = reply.text
133
+ except LLMError as exc:
134
+ result.error = str(exc)
135
+ return result
136
+
137
+ text, cited, invalid = verify_citations(text, len(result.sources))
138
+ result.answer = text.strip()
139
+ result.cited = cited
140
+ result.invalid_citations = invalid
141
+ result.found = bool(cited) and not result.answer.lower().startswith("not found")
142
+ return result
143
+
144
+ # ------------------------------------------------------------------ tools
145
+ def _run(self, call: ToolCall) -> tuple[ToolCall, str]:
146
+ step = AgentStep(call.name, dict(call.args))
147
+ self.result.steps.append(step)
148
+ tool = self.tools.get(call.name)
149
+ if tool is None: # the model can only use the tools we offer
150
+ step.note = "unknown tool"
151
+ return call, f"There is no tool named {call.name!r}."
152
+ try:
153
+ return call, tool(call, step)
154
+ except ToolError as exc: # e.g. an unknown name: tell the model, let it try again
155
+ step.note = exc.note
156
+ return call, str(exc)
157
+
158
+ def _search_code(self, call: ToolCall, step: AgentStep) -> str:
159
+ hits = self.code.search(call.args.get("query", ""), limit=SEARCH_RESULTS)
160
+ parts = []
161
+ for rank, hit in enumerate(hits, start=1):
162
+ if rank <= SHOW_CODE:
163
+ number = self._source(hit.chunk, "search")
164
+ step.sources.append(number)
165
+ parts.append(_show(number, hit.chunk))
166
+ else:
167
+ parts.append(f"- also related: {_label(hit.chunk)}")
168
+ return "\n\n".join(parts)
169
+
170
+ def _read_code(self, call: ToolCall, step: AgentStep) -> str:
171
+ chunk = self.code.read(call.args.get("name", ""))
172
+ number = self._source(chunk, "read")
173
+ step.sources.append(number)
174
+ return _show(number, chunk)
175
+
176
+ def _source(self, chunk: Chunk, found_by: str) -> int:
177
+ """The source number for this code, the same each time it comes back."""
178
+ key = (chunk.path, chunk.line_start, chunk.line_end)
179
+ if key not in self.numbers:
180
+ self.result.sources.append(Hit(chunk, found_by, len(self.result.sources) + 1))
181
+ self.numbers[key] = len(self.result.sources)
182
+ return self.numbers[key]
183
+
184
+
185
+ def _label(chunk: Chunk) -> str:
186
+ name = chunk.title.split(": ", 1)[-1]
187
+ return f"{name} ({chunk.path}, lines {chunk.line_start}-{chunk.line_end})"
188
+
189
+
190
+ def _show(number: int, chunk: Chunk) -> str:
191
+ return f"[S{number}] {_label(chunk)}\n<code>\n{chunk.text}\n</code>"
codescope/ai/answer.py ADDED
@@ -0,0 +1,89 @@
1
+ """Answer questions about the code with retrieval-augmented generation (RAG).
2
+
3
+ 1. Search: hybrid keyword + meaning search, plus related code from the dependency graph.
4
+ 2. Generate: the model answers using only those numbered sources and cites them as [S1].
5
+ 3. Verify: citations must point at a source that was actually given. Invalid ones are
6
+ removed, and an answer with no valid citation is treated as "not found".
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass, field
13
+
14
+ from jinja2 import Environment, PackageLoader, StrictUndefined
15
+
16
+ from codescope.ai.schemas import Answer
17
+ from codescope.config import Config
18
+ from codescope.index.search import Hit, SearchResult, search
19
+ from codescope.llm.base import LLMError
20
+ from codescope.llm.client import LLMClient
21
+ from codescope.storage.db import Database
22
+
23
+ _CITATION = re.compile(r"\[S(\d+)\]")
24
+
25
+
26
+ @dataclass(slots=True)
27
+ class AskResult:
28
+ question: str
29
+ search: SearchResult
30
+ answer: str = ""
31
+ found: bool = False
32
+ cited: list[int] = field(default_factory=list) # 1-based source numbers used in the answer
33
+ invalid_citations: int = 0
34
+ error: str | None = None
35
+
36
+ @property
37
+ def sources(self) -> list[Hit]:
38
+ return self.search.hits
39
+
40
+
41
+ def ask(db: Database, config: Config, question: str, llm: LLMClient | None) -> AskResult:
42
+ found = search(db, config, question, llm)
43
+ result = AskResult(question=question, search=found)
44
+ if llm is None or not found.hits:
45
+ return result
46
+
47
+ env = Environment(
48
+ loader=PackageLoader("codescope", "templates"),
49
+ autoescape=False,
50
+ trim_blocks=True,
51
+ lstrip_blocks=True,
52
+ undefined=StrictUndefined,
53
+ )
54
+ system = env.get_template("prompts/system.j2").render()
55
+ prompt = env.get_template("prompts/ask.j2").render(
56
+ project=config.project_name,
57
+ question=question,
58
+ sources=[hit.chunk for hit in found.hits],
59
+ )
60
+ try:
61
+ reply = llm.generate(Answer, system=system, prompt=prompt, strong=True)
62
+ except LLMError as exc:
63
+ result.error = str(exc)
64
+ return result
65
+
66
+ text, cited, invalid = verify_citations(reply.answer, len(found.hits))
67
+ result.answer = text.strip()
68
+ result.cited = cited
69
+ result.invalid_citations = invalid
70
+ result.found = reply.found and bool(cited)
71
+ return result
72
+
73
+
74
+ def verify_citations(text: str, source_count: int) -> tuple[str, list[int], int]:
75
+ """Remove citations to sources that were not given. Returns (text, cited, removed)."""
76
+ cited: list[int] = []
77
+ removed = 0
78
+
79
+ def check(match: re.Match[str]) -> str:
80
+ nonlocal removed
81
+ number = int(match.group(1))
82
+ if 1 <= number <= source_count:
83
+ if number not in cited:
84
+ cited.append(number)
85
+ return match.group(0)
86
+ removed += 1
87
+ return ""
88
+
89
+ return _CITATION.sub(check, text), sorted(cited), removed
codescope/ai/redact.py ADDED
@@ -0,0 +1,54 @@
1
+ """Remove secrets from source code before any of it is sent to an AI provider.
2
+
3
+ Secret files (.env, *.pem, ...) are never read at all. This catches secrets written
4
+ inside normal source files, such as Django's `SECRET_KEY = "..."` in settings.py.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ REDACTED = "<redacted>"
12
+
13
+ # `SECRET_KEY = "abc"`, `'PASSWORD': 'abc'`, `api_key="abc"` -> keep the name, hide the value.
14
+ _SECRET_NAME = (
15
+ r"[\w.]*(?:secret|passw(?:or)?d|pwd|token|api_?key|private_?key|access_?key|credential)[\w.]*"
16
+ )
17
+ _ASSIGNED_SECRET = re.compile(
18
+ rf"""(?P<lead>(?P<q>['"]?){_SECRET_NAME}(?P=q)\s*[:=]\s*[rRbBuU]?)(?P<quote>['"])(?P<value>[^'"\n]+)(?P=quote)""",
19
+ re.IGNORECASE,
20
+ )
21
+
22
+ # Well-known token formats, wherever they appear.
23
+ _TOKEN_PATTERNS = [
24
+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----"),
25
+ re.compile(r"\bAKIA[0-9A-Z]{16}\b"), # AWS access key id
26
+ re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b"), # Google API key
27
+ re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"), # GitHub token
28
+ re.compile(r"\bsk-[A-Za-z0-9_\-]{20,}\b"), # OpenAI / Anthropic style keys
29
+ re.compile(r"\bxox[abprs]-[A-Za-z0-9\-]{10,}\b"), # Slack token
30
+ ]
31
+
32
+ # `postgres://user:password@host` -> keep the user and host, hide the password.
33
+ _URL_PASSWORD = re.compile(r"(?P<lead>[a-z][a-z0-9+.\-]*://[^:/@\s'\"]+:)[^@/\s'\"]+(?=@)")
34
+
35
+
36
+ def redact_secrets(text: str) -> tuple[str, int]:
37
+ """Return the text with secrets replaced by `<redacted>`, and how many were replaced."""
38
+ count = 0
39
+
40
+ def assigned(match: re.Match[str]) -> str:
41
+ nonlocal count
42
+ if match.group("value").strip() in ("", REDACTED):
43
+ return match.group(0)
44
+ count += 1
45
+ return f"{match.group('lead')}{match.group('quote')}{REDACTED}{match.group('quote')}"
46
+
47
+ text = _ASSIGNED_SECRET.sub(assigned, text)
48
+ for pattern in _TOKEN_PATTERNS:
49
+ # Keep the line breaks of a multi-line secret, so line numbers stay correct.
50
+ text, found = pattern.subn(lambda m: REDACTED + "\n" * m.group(0).count("\n"), text)
51
+ count += found
52
+ text, found = _URL_PASSWORD.subn(lambda m: f"{m.group('lead')}{REDACTED}", text)
53
+ count += found
54
+ return text, count
@@ -0,0 +1,187 @@
1
+ """AI review of a change, with every finding checked against the real code.
2
+
3
+ The model sees the diff (secrets removed), changed signatures, removed symbols, and the
4
+ exact lines of code that use the changed code (from the dependency graph). It must point
5
+ each finding at a file and line. Findings whose location is not part of what it was shown,
6
+ or does not exist, are dropped: the model cannot report on code it never saw.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ from jinja2 import Environment, PackageLoader, StrictUndefined
15
+
16
+ from codescope.ai.redact import redact_secrets
17
+ from codescope.ai.schemas import CATEGORIES, SEVERITIES, Finding, ReviewAnswer
18
+ from codescope.config import Config
19
+ from codescope.llm.base import LLMError
20
+ from codescope.llm.client import LLMClient
21
+ from codescope.review.analysis import ReviewAnalysis
22
+
23
+ MAX_DIFF_CHARS = 40_000
24
+ MAX_CALL_SITES = 40
25
+ NEAR = 3 # a finding may point this many lines away from a changed line
26
+
27
+
28
+ @dataclass(slots=True, frozen=True)
29
+ class CallSite:
30
+ """A line that uses changed code, shown to the model with its source text."""
31
+
32
+ path: str
33
+ line: int
34
+ fqn: str
35
+ via: str
36
+ code: str
37
+
38
+
39
+ @dataclass(slots=True)
40
+ class AIReview:
41
+ summary: str = ""
42
+ findings: list[Finding] = field(default_factory=list)
43
+ tests_to_add: list[str] = field(default_factory=list)
44
+ dropped: int = 0 # findings rejected because their location was not in the review
45
+ truncated: bool = False # the diff was too long and was cut
46
+ error: str | None = None
47
+
48
+
49
+ def ai_review(config: Config, analysis: ReviewAnalysis, diff_text: str, llm: LLMClient) -> AIReview:
50
+ review = AIReview()
51
+ diffs, review.truncated = _python_diffs(config, analysis, diff_text)
52
+ if not diffs:
53
+ return review
54
+ call_sites = [
55
+ CallSite(
56
+ path=item.path,
57
+ line=item.line,
58
+ fqn=item.fqn,
59
+ via=item.via,
60
+ code=_line_text(config.root / item.path, item.line) or "",
61
+ )
62
+ for item in analysis.impact
63
+ if item.direct
64
+ ][:MAX_CALL_SITES]
65
+
66
+ env = Environment(
67
+ loader=PackageLoader("codescope", "templates"),
68
+ autoescape=False,
69
+ trim_blocks=True,
70
+ lstrip_blocks=True,
71
+ undefined=StrictUndefined,
72
+ )
73
+ prompt = env.get_template("prompts/review.j2").render(
74
+ project=config.project_name,
75
+ base=analysis.base_ref,
76
+ diffs=diffs,
77
+ signature_changes=[s for s in analysis.symbols if s.signature_changed],
78
+ removed=[s for s in analysis.symbols if s.change == "removed"],
79
+ call_sites=call_sites,
80
+ )
81
+ system = env.get_template("prompts/system.j2").render()
82
+ try:
83
+ answer = llm.generate(ReviewAnswer, system=system, prompt=prompt, strong=True)
84
+ except LLMError as exc:
85
+ review.error = str(exc)
86
+ return review
87
+
88
+ allowed = _allowed_locations(analysis, call_sites)
89
+ for finding in answer.findings:
90
+ checked = _checked(config, finding, allowed)
91
+ if checked is None:
92
+ review.dropped += 1
93
+ else:
94
+ review.findings.append(checked)
95
+ order = {severity: index for index, severity in enumerate(SEVERITIES)}
96
+ review.findings.sort(key=lambda f: (order[f.severity], f.path, f.line))
97
+ review.summary = " ".join(answer.summary.split())
98
+ review.tests_to_add = [" ".join(t.split()) for t in answer.tests_to_add if t.strip()][:3]
99
+ return review
100
+
101
+
102
+ def _python_diffs(
103
+ config: Config, analysis: ReviewAnalysis, diff_text: str
104
+ ) -> tuple[list[dict[str, str]], bool]:
105
+ """The diff of each changed Python file (new untracked files in full), secrets removed."""
106
+ sections: dict[str, str] = {}
107
+ current: str | None = None
108
+ for line in diff_text.splitlines():
109
+ if line.startswith("diff --git "):
110
+ current = None
111
+ elif line.startswith("+++ ") or line.startswith("--- "):
112
+ path = line[4:].rstrip("\t").removeprefix("b/").removeprefix("a/")
113
+ if path != "/dev/null" and path.endswith(".py"):
114
+ current = path
115
+ sections.setdefault(current, "")
116
+ continue
117
+ if current is not None:
118
+ sections[current] += line + "\n"
119
+
120
+ diffs: list[dict[str, str]] = []
121
+ size = 0
122
+ truncated = False
123
+ for change in analysis.python_files:
124
+ text = sections.get(change.path) or sections.get(change.old_path or "")
125
+ if text is None and change.status == "added": # untracked file: show it whole
126
+ content = (config.root / change.path).read_text("utf-8", errors="replace")
127
+ text = "".join(f"+{line}\n" for line in content.splitlines())
128
+ if not text:
129
+ continue
130
+ text, _ = redact_secrets(text)
131
+ if size + len(text) > MAX_DIFF_CHARS:
132
+ truncated = True
133
+ text = text[: max(0, MAX_DIFF_CHARS - size)]
134
+ size += len(text)
135
+ diffs.append({"path": change.path, "status": change.status, "text": text.rstrip()})
136
+ if size >= MAX_DIFF_CHARS:
137
+ break
138
+ return diffs, truncated
139
+
140
+
141
+ def _allowed_locations(
142
+ analysis: ReviewAnalysis, call_sites: list[CallSite]
143
+ ) -> dict[str, list[tuple[int, int]]]:
144
+ """Per file, the line ranges the model was shown: changed lines and call sites."""
145
+ allowed: dict[str, list[tuple[int, int]]] = {}
146
+ for change in analysis.python_files:
147
+ ranges = allowed.setdefault(change.path, [])
148
+ ranges.extend((max(1, a - NEAR), b + NEAR) for a, b in change.changed_lines())
149
+ for symbol in analysis.symbols:
150
+ if symbol.change != "removed" and symbol.kind != "module":
151
+ allowed.setdefault(symbol.path, []).append((symbol.line_start, symbol.line_end))
152
+ for site in call_sites:
153
+ allowed.setdefault(site.path, []).append((max(1, site.line - NEAR), site.line + NEAR))
154
+ return allowed
155
+
156
+
157
+ def _checked(
158
+ config: Config, finding: Finding, allowed: dict[str, list[tuple[int, int]]]
159
+ ) -> Finding | None:
160
+ path = finding.path.strip().strip("`").removeprefix("./")
161
+ ranges = allowed.get(path)
162
+ if not ranges or not any(start <= finding.line <= end for start, end in ranges):
163
+ return None
164
+ if _line_text(config.root / path, finding.line) is None: # past the end of the file
165
+ return None
166
+ severity = finding.severity.strip().lower()
167
+ category = finding.category.strip().lower()
168
+ return finding.model_copy(
169
+ update={
170
+ "path": path,
171
+ "severity": severity if severity in SEVERITIES else "medium",
172
+ "category": category if category in CATEGORIES else "bug",
173
+ "title": " ".join(finding.title.split()),
174
+ "explanation": " ".join(finding.explanation.split()),
175
+ "suggestion": " ".join(finding.suggestion.split()),
176
+ }
177
+ )
178
+
179
+
180
+ def _line_text(path: Path, line: int) -> str | None:
181
+ try:
182
+ lines = path.read_text("utf-8", errors="replace").splitlines()
183
+ except OSError:
184
+ return None
185
+ if 1 <= line <= len(lines):
186
+ return redact_secrets(lines[line - 1].strip())[0]
187
+ return None
@@ -0,0 +1,69 @@
1
+ """The JSON shapes the AI must answer with. Gemini is given these as a response schema,
2
+ and every answer is validated against them before it is used."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+
9
+ class SymbolNote(BaseModel):
10
+ name: str = Field(description="Exactly as listed under 'Symbols to describe'.")
11
+ summary: str = Field(description="One sentence: what it does.")
12
+
13
+
14
+ class FileSummary(BaseModel):
15
+ path: str = Field(description="The file path, exactly as given.")
16
+ purpose: str = Field(description="One or two sentences: what this file is responsible for.")
17
+ details: list[str] = Field(description="Up to 4 short points on how it works.")
18
+ symbols: list[SymbolNote] = Field(description="One entry per listed symbol you can describe.")
19
+
20
+
21
+ class FileSummaryBatch(BaseModel):
22
+ files: list[FileSummary]
23
+
24
+
25
+ class ComponentSummary(BaseModel):
26
+ purpose: str = Field(description="One or two sentences: what this component is for.")
27
+ details: list[str] = Field(description="Up to 4 short points on how its files work together.")
28
+
29
+
30
+ class ProjectSummary(BaseModel):
31
+ overview: str = Field(description="2 to 4 sentences: what the project does, how it is built.")
32
+ how_it_works: list[str] = Field(
33
+ description="3 to 6 points: the main parts and how a typical request or task flows."
34
+ )
35
+
36
+
37
+ class Answer(BaseModel):
38
+ found: bool = Field(description="false if the sources do not contain the answer.")
39
+ answer: str = Field(
40
+ description="Short Markdown answer. Cite the sources after each statement, like [S2]."
41
+ )
42
+
43
+
44
+ SEVERITIES = ("high", "medium", "low")
45
+ CATEGORIES = (
46
+ "bug",
47
+ "breaking-change",
48
+ "security",
49
+ "error-handling",
50
+ "missing-test",
51
+ "performance",
52
+ "maintainability",
53
+ )
54
+
55
+
56
+ class Finding(BaseModel):
57
+ severity: str = Field(description="One of: high, medium, low.")
58
+ category: str = Field(description="One of: " + ", ".join(CATEGORIES) + ".")
59
+ title: str = Field(description="One short line naming the problem.")
60
+ path: str = Field(description="File path exactly as shown in the change.")
61
+ line: int = Field(description="Line number in the new version of the file.")
62
+ explanation: str = Field(description="Why this is a problem, in 1 to 3 sentences.")
63
+ suggestion: str = Field(description="How to fix it, in one or two sentences.")
64
+
65
+
66
+ class ReviewAnswer(BaseModel):
67
+ summary: str = Field(description="2 or 3 sentences: what the change does.")
68
+ findings: list[Finding] = Field(description="Real problems only. Empty if there are none.")
69
+ tests_to_add: list[str] = Field(description="Up to 3 test cases worth adding, one line each.")