patchwise 0.2.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.
@@ -0,0 +1,965 @@
1
+ # Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import time
9
+ from typing import Any, Dict, List, Set, Optional, Tuple
10
+ from dataclasses import dataclass
11
+ import threading
12
+
13
+ from ... import KERNEL_PATH, SANDBOX_PATH
14
+ from ...patch_review.decorators import register_llm_review, register_long_review
15
+ from ..patch_review import Dependency
16
+ from .ai_review import AiReview
17
+
18
+
19
+
20
+ @dataclass
21
+ class LSPLocation:
22
+ """Represents an LSP location with file URI and position."""
23
+ uri: str
24
+ line: int
25
+ character: int
26
+
27
+
28
+ @dataclass
29
+ class DefinitionRange:
30
+ """Represents a definition with its file location and line range."""
31
+ file_path: str
32
+ start_line: int
33
+ end_line: int
34
+ identifier: str
35
+
36
+
37
+ @register_llm_review
38
+ @register_long_review
39
+ class AiCodeReview(AiReview):
40
+ """AI-powered code review for Linux kernel patches using LSP and clangd."""
41
+
42
+ DEPENDENCIES = getattr(AiReview, "DEPENDENCIES", []) + [
43
+ Dependency(
44
+ name="clangd",
45
+ min_version="14.0.0",
46
+ max_version="20.0.0",
47
+ ),
48
+ Dependency(
49
+ name="clang",
50
+ min_version="14.0.0",
51
+ max_version="20.0.0",
52
+ ),
53
+ ]
54
+
55
+ # LSP Configuration
56
+ MAX_GAP = 5
57
+
58
+ # File processing
59
+ IDENTIFIER_PATTERN = r'\b[_a-zA-Z][_a-zA-Z0-9]*\b'
60
+
61
+ # LSP message IDs
62
+ INIT_MSG_ID = 1
63
+ DEFINITION_MSG_ID = 2
64
+ SYMBOL_MSG_ID = 3
65
+ DOC_SYMBOL_MSG_ID = 100
66
+
67
+ PROMPT_TEMPLATE = """
68
+ # User Prompt
69
+
70
+ Review the following patch diff and provide inline feedback on the code changes. Additional context will be provided to help you understand the code and its purpose.
71
+
72
+ ## Relevant context
73
+
74
+ {context}
75
+
76
+ ## Commit text
77
+
78
+ {commit_text}
79
+
80
+ ## Patch Diff to review
81
+
82
+ ```diff
83
+ {diff}
84
+ ```
85
+
86
+ """
87
+
88
+ @staticmethod
89
+ def get_kernel_coding_style() -> str:
90
+ """Load kernel coding style guidelines from documentation."""
91
+ coding_style_path = os.path.join(KERNEL_PATH, "Documentation/process/coding-style.rst")
92
+ try:
93
+ with open(coding_style_path, "r") as f:
94
+ return f.read()
95
+ except Exception as e:
96
+ return f"[Could not load kernel coding style guidelines: {e}]"
97
+
98
+ @classmethod
99
+ def get_system_prompt(cls) -> str:
100
+ """Generate the system prompt including kernel coding style guidelines."""
101
+ return ("""
102
+ # System Prompt
103
+
104
+ ## Instructions
105
+
106
+ You are a Linux kernel maintainer reviewing patches sent to the Linux kernel mailing list. You will receive a patch diff and your task is to provide inline feedback on the code changes. Your task is to find issues in the code, if any. Is it imperative that your diagnosis is accurate, that you correctly identify real bugs that must be addressed and do not provide false positives. You should NOT provide suggestions that place any burden of investigation onto the developer such as "verify" or "you should consider", if it is not worth being concrete and direct about, it's not worth mentioning. Most changes will have few to no bugs, so be very careful with pointing out issues as false positives are strictly not acceptable.
107
+
108
+ - Do NOT compliment the code.
109
+ - Do not comment on what the code is doing, your comments should exclusively be problems.
110
+ - Do not summarize the change.
111
+ - Do not comment on how the change makes a difference, you are providing feedback to the developer, not the maintainer.
112
+ - Your output must strictly be comments on bugs and what is incorrect.
113
+ - Only point out specific issues in the code.
114
+ - Keep your feedback minimal and to the point.
115
+ - Do NOT comment on what the code does correctly.
116
+ - Stay focused on the issues that need to be fixed.
117
+ - You should not provide a summary or a list of issues outside the inline comments.
118
+ - Do NOT summarize the code or your feedback at the end of the review.
119
+ - Your comments should not be C comments, they should be unquoted, interleaved between the lines of the quoted text (the lines that start with '>').
120
+ - MAKE SURE THAT YOUR SUGGESTIONS FOLLOW KERNEL CODING STYLE GUIDELINES.
121
+ - Use correct grammar and only ASCII characters.
122
+ - Do not tell developers to add comments.
123
+
124
+ ### Positive Feedback
125
+
126
+ You have been doing a good job of only providing feedback when you are absolutely confident and not commenting on things you are not sure about. You have been doing a great job at keeping each of your comments short and to the point, without unnecessary explanations or compliments. You have been following the Linux kernel coding style guidelines and providing feedback that is relevant to the code changes. You have been doing a great job at providing feedback that is actionable and can be easily understood by the developer.
127
+
128
+ ### Constructive Feedback
129
+
130
+ You need to work on providing feedback that is more specific and actionable. **You can also do a better job at not summarizing or stating what's correct.** It is not appropriate to tell developers that their code is correct or that they have done a good job. Instead, focus on the specific issues that need to be fixed and provide actionable feedback.
131
+
132
+ ## Example Feedback from Maintainers
133
+
134
+ ```
135
+ > diff --git a/arch/arm64/Kconfig.platforms b/arch/arm64/Kconfig.platforms
136
+ > index a541bb029..0ffd65e36 100644
137
+ > --- a/arch/arm64/Kconfig.platforms
138
+ > +++ b/arch/arm64/Kconfig.platforms
139
+ > @@ -270,6 +270,7 @@ config ARCH_QCOM
140
+ > select GPIOLIB
141
+ > select PINCTRL
142
+ > select HAVE_PWRCTRL if PCI
143
+ > + select PCI_PWRCTRL_SLOT if PCI
144
+
145
+ PWRCTL isn't a fundamental feature of ARCH_QCOM, so why do we select it
146
+ here?
147
+
148
+ > diff --git a/arch/arm64/boot/dts/qcom/sm8550-hdk.dts b/arch/arm64/boot/dts/qcom/sm8550-hdk.dts
149
+ > index 29bc1ddfc7b25f203c9f3b530610e45c44ae4fb2..fe46699804b3a8fb792edc06b58b961778cd8d70 100644
150
+ > --- a/arch/arm64/boot/dts/qcom/sm8550-hdk.dts
151
+ > +++ b/arch/arm64/boot/dts/qcom/sm8550-hdk.dts
152
+ > @@ -857,10 +857,10 @@ vreg_l5n_1p8: ldo5 {{
153
+ > regulator-initial-mode = <RPMH_REGULATOR_MODE_HPM>;
154
+ > }};
155
+ >
156
+ > - vreg_l6n_3p3: ldo6 {{
157
+ > - regulator-name = "vreg_l6n_3p3";
158
+ > + vreg_l6n_3p2: ldo6 {{
159
+
160
+ Please follow the naming from the board's schematics for the label and
161
+ regulator-name.
162
+
163
+ > + regulator-name = "vreg_l6n_3p2";
164
+ > regulator-min-microvolt = <2800000>;
165
+ ```
166
+
167
+ ## Kernel Coding Style Guidelines
168
+
169
+ """ + cls.get_kernel_coding_style())
170
+
171
+
172
+ def _read_file_safely(self, file_path: str) -> Optional[str]:
173
+ """Safely read a file and return its contents, or None on error."""
174
+ try:
175
+ with open(file_path, "r") as f:
176
+ return f.read()
177
+ except Exception as e:
178
+ self.logger.error(f"Failed to read {file_path}: {e}")
179
+ return None
180
+
181
+ def _get_file_lines(self, file_path: str) -> List[str]:
182
+ """Get file lines as a list, or empty list on error."""
183
+ content = self._read_file_safely(file_path)
184
+ return content.splitlines(keepends=True) if content else []
185
+
186
+ def _run_make_command(
187
+ self, args: List[str], capture_output: bool = True, stdout_file: Optional[str] = None
188
+ ) -> None:
189
+ """Run a make command with consistent arguments."""
190
+ base_args = [
191
+ "make",
192
+ f"O={self.build_dir}",
193
+ f"-j{os.cpu_count()}",
194
+ "ARCH=arm64",
195
+ "LLVM=1",
196
+ ]
197
+ full_args = base_args + args
198
+
199
+ desc = " ".join(args)
200
+
201
+ if capture_output:
202
+ self.run_cmd_with_timer(full_args, desc, cwd=str(KERNEL_PATH))
203
+ elif stdout_file:
204
+ output = self.run_cmd_with_timer(
205
+ full_args,
206
+ desc,
207
+ cwd=str(KERNEL_PATH),
208
+ )
209
+ with open(stdout_file, "w") as f:
210
+ f.write(output)
211
+ else:
212
+ self.run_cmd_with_timer(full_args, desc, cwd=str(KERNEL_PATH))
213
+
214
+ def generate_compile_commands(self) -> None:
215
+ """Generate compile_commands.json for clangd."""
216
+ self.logger.debug("Running make defconfig")
217
+ self._run_make_command(["defconfig"])
218
+
219
+ self.logger.debug("Running make")
220
+ build_log_path = self.build_dir / "build.log"
221
+ self._run_make_command(["V=1"], capture_output=False, stdout_file=str(build_log_path))
222
+
223
+ self.logger.debug("Generating compile commands")
224
+ subprocess.run(
225
+ [
226
+ "python3",
227
+ os.path.join(KERNEL_PATH, "scripts", "clang-tools", "gen_compile_commands.py"),
228
+ "-d", str(self.build_dir),
229
+ "-o", str(self.build_dir / "compile_commands.json"),
230
+ ],
231
+ cwd=str(self.build_dir),
232
+ )
233
+ self.logger.debug("compile_commands.json generated")
234
+
235
+ def _create_lsp_message(self, method: str, params: Dict[str, Any],
236
+ msg_id: Optional[int] = None) -> Dict[str, Any]:
237
+ """Create a standardized LSP message."""
238
+ message = {
239
+ "jsonrpc": "2.0",
240
+ "method": method,
241
+ "params": params
242
+ }
243
+ if msg_id is not None:
244
+ message["id"] = msg_id
245
+ return message
246
+
247
+ def _make_message_bytes(self, msg: Dict[str, Any]) -> bytes:
248
+ """Convert LSP message to bytes with proper headers."""
249
+ msg_bytes = json.dumps(msg).encode("utf-8")
250
+ return f"Content-Length: {len(msg_bytes)}\r\n\r\n".encode("utf-8") + msg_bytes
251
+
252
+ def send_workDoneProgress_response(self, proc):
253
+ message = {
254
+ "id": 0,
255
+ "jsonrpc": "2.0",
256
+ "result": None
257
+ }
258
+ self._send_lsp_message(proc, message)
259
+
260
+
261
+ def _read_lsp_response(self, proc: subprocess.Popen[Any],
262
+ expected_id: Optional[int] = None) -> Dict[str, Any]:
263
+ """Read and parse LSP response from process."""
264
+
265
+ if proc.stdout is None:
266
+ raise RuntimeError("Process stdout is None")
267
+
268
+ while True:
269
+ # Read headers
270
+ headers = b""
271
+ while b"\r\n\r\n" not in headers:
272
+ chunk = proc.stdout.read(1)
273
+ if chunk is None:
274
+ raise RuntimeError("Failed to read from process stdout (header)")
275
+ headers += chunk
276
+
277
+ # Parse content length
278
+ content_length = 0
279
+ for line in headers.split(b"\r\n"):
280
+ if line.lower().startswith(b"content-length:"):
281
+ content_length = int(line.split(b":")[1].strip())
282
+
283
+ # Read content
284
+ content = proc.stdout.read(content_length)
285
+ if content is None:
286
+ raise RuntimeError("Failed to read content from process stdout")
287
+
288
+ msg = json.loads(content.decode("utf-8"))
289
+
290
+ if expected_id is None or msg.get("id") == expected_id:
291
+ return msg
292
+
293
+ # Log and handle progress notifications and workDoneProgress
294
+ if msg.get("method") == "window/workDoneProgress/create":
295
+ token = msg.get("params", {}).get("token")
296
+ self.logger.debug(f"LSP workDoneProgress created for token: {token}")
297
+ self.send_workDoneProgress_response(proc)
298
+ continue # Don't return, keep waiting for expected response
299
+
300
+ if msg.get("method") == "textDocument/publishDiagnostics":
301
+ self.logger.debug(f"Received diagnostics: {json.dumps(msg, indent=2)}")
302
+ continue
303
+
304
+ if msg.get("method") == "textDocument/clangd.fileStatus":
305
+ self.logger.debug(f"Received clangd fileStatus notification: {json.dumps(msg)}")
306
+ continue
307
+
308
+ if msg.get("method") == "$/progress" and "params" in msg:
309
+ params = msg["params"]
310
+ token = params.get("token")
311
+ # value = params.get("value", {})
312
+ if token == "backgroundIndexProgress":
313
+ continue
314
+ self.logger.debug(f"Background index progress: {json.dumps(msg)}")
315
+
316
+ self.logger.debug(f"Received LSP message with id {msg.get('id')}, expected {expected_id}: {json.dumps(msg, indent=2)}")
317
+
318
+ def _send_lsp_message(self, proc: subprocess.Popen[Any], message: Dict[str, Any]) -> None:
319
+ """Send an LSP message to the process."""
320
+ if proc.stdin is None:
321
+ raise RuntimeError("Process stdin is None")
322
+ proc.stdin.write(self._make_message_bytes(message))
323
+ proc.stdin.flush()
324
+
325
+ def _initialize_lsp(self, proc: subprocess.Popen[Any], project_root: os.PathLike[str]) -> None:
326
+ """Initialize LSP connection."""
327
+ self.logger.debug("Initializing LSP connection")
328
+
329
+ init_msg = self._create_lsp_message(
330
+ "initialize",
331
+ {
332
+ "rootUri": f"file://{project_root}",
333
+ "capabilities": {
334
+ "window": {
335
+ "showDocument": {
336
+ "support": True
337
+ },
338
+ "showMessage": {
339
+ "messageActionItem": {
340
+ "additionalPropertiesSupport": True
341
+ }
342
+ },
343
+ "workDoneProgress": True
344
+ }
345
+ },
346
+ "initializationOptions": {
347
+ "clangdFileStatus": True,
348
+ "fallbackFlags": [],
349
+ }
350
+ }, self.INIT_MSG_ID)
351
+
352
+ self._send_lsp_message(proc, init_msg)
353
+ init_response = self._read_lsp_response(proc, expected_id=self.INIT_MSG_ID)
354
+
355
+ initialized_msg = self._create_lsp_message("initialized", {})
356
+ self._send_lsp_message(proc, initialized_msg)
357
+ self.logger.debug("LSP initialized")
358
+
359
+ def _open_file_in_lsp(self, proc: subprocess.Popen[Any], uri: str,
360
+ text: Optional[str] = None, language: str = "c") -> None:
361
+ """Open a file in the LSP server. If text is not provided, omit it from the message."""
362
+ self.logger.debug(f"Opening file in LSP: {uri}")
363
+ text_document = {
364
+ "uri": uri,
365
+ "languageId": language,
366
+ "version": 1
367
+ }
368
+ if text is not None:
369
+ text_document["text"] = text
370
+ didopen_msg = self._create_lsp_message("textDocument/didOpen", {
371
+ "textDocument": text_document
372
+ })
373
+ self._send_lsp_message(proc, didopen_msg)
374
+ time.sleep(0.1) # Allow LSP to process
375
+
376
+ def _find_definition(self, proc: subprocess.Popen[Any], uri: str,
377
+ line: int, character: int) -> Dict[str, Any]:
378
+ """Find definition using LSP."""
379
+ def_msg = self._create_lsp_message("textDocument/definition", {
380
+ "textDocument": {"uri": uri},
381
+ "position": {"line": line, "character": character}
382
+ }, self.DEFINITION_MSG_ID)
383
+
384
+ self._send_lsp_message(proc, def_msg)
385
+ return self._read_lsp_response(proc, expected_id=self.DEFINITION_MSG_ID)
386
+
387
+ def _find_actual_definition(self, proc: subprocess.Popen[Any], uri: str,
388
+ line: int, character: int, identifier: str) -> Dict[str, Any]:
389
+ # Log the original identifier location
390
+ self.logger.debug(f"Looking up definition for identifier '{identifier}' at location: {uri}:{line}:{character}")
391
+ current_location = LSPLocation(uri, line, character)
392
+
393
+ # # Always perform two definition lookups and only use the second result (first is assumed cache miss)
394
+ # resp_first = self._find_definition(proc, current_location.uri, current_location.line, current_location.character)
395
+ # self.logger.debug(f"Clangd response for definition request (assumed cache miss): {json.dumps(resp_first, indent=2)}")
396
+
397
+ # # If the first response has a result, open the file containing the supposed definition in the LSP
398
+ # def_file_uri = None
399
+ # def_file_text = None
400
+ # if resp_first.get("result") and len(resp_first["result"]) > 0:
401
+ # loc = resp_first["result"][0]
402
+ # def_file_uri = loc["uri"]
403
+ # def_file_path = def_file_uri.replace("file://", "")
404
+ # if os.path.exists(def_file_path):
405
+ # def_file_text = self._read_file_safely(def_file_path)
406
+ # self._open_file_in_lsp(proc, def_file_uri, def_file_text)
407
+ # self.wait_for_diagnostics(proc, def_file_uri, timeout=15)
408
+ # else:
409
+ # self.logger.warning(f"No definition found for {identifier} at {current_location.uri}:{current_location.line}:{current_location.character}.")
410
+
411
+
412
+
413
+ # Wait for clangd indexing for 1 second before retrying
414
+ # # self.wait_for_clangd_indexing(proc, max_total_wait=15) # TEMP reset to max_total_wait=1
415
+ resp_second = self._find_definition(proc, current_location.uri, current_location.line, current_location.character)
416
+ self.logger.debug(f"Clangd response for definition request (used result): {json.dumps(resp_second, indent=2)}")
417
+
418
+ if resp_second.get("result") and len(resp_second["result"]) > 0:
419
+ loc = resp_second["result"][0]
420
+ new_location = LSPLocation(
421
+ loc["uri"],
422
+ loc["range"]["start"]["line"],
423
+ loc["range"]["start"]["character"]
424
+ )
425
+ self.logger.debug(
426
+ f"Found at {new_location.uri}:{new_location.line}:{new_location.character} (after forced retry)"
427
+ )
428
+ else:
429
+ self.logger.debug(f"No definition found for {identifier} after forced retry.")
430
+ return resp_second
431
+
432
+ def _get_document_symbols(self, proc: subprocess.Popen[Any], uri: str,
433
+ text: str, identifier: str) -> Optional[Dict[str, Any]]:
434
+ """Get document symbols and find specific identifier."""
435
+ self._open_file_in_lsp(proc, uri, text, language="c")
436
+
437
+ doc_symbol_msg = self._create_lsp_message("textDocument/documentSymbol", {
438
+ "textDocument": {"uri": uri}
439
+ }, self.SYMBOL_MSG_ID)
440
+
441
+ self._send_lsp_message(proc, doc_symbol_msg)
442
+ symbol_resp = self._read_lsp_response(proc, expected_id=self.SYMBOL_MSG_ID)
443
+
444
+ if symbol_resp.get("result"):
445
+ for sym in symbol_resp["result"]:
446
+ if sym.get("name") == identifier:
447
+ return sym
448
+ return None
449
+
450
+ def parse_diff(self, diff_lines: List[str]) -> Dict[str, Set[int]]:
451
+ """Parse diff lines to extract file additions and their line numbers."""
452
+ file_adds: Dict[str, Set[int]] = {}
453
+ current_file: Optional[str] = None
454
+ new_line: Optional[int] = None
455
+
456
+ for line in diff_lines:
457
+ if line.startswith('+++ b/'):
458
+ current_file = line[6:].strip()
459
+ file_adds[current_file] = set()
460
+ elif line.startswith('@@'):
461
+ match = re.match(r'@@ -\d+(,\d+)? \+(\d+)(,\d+)? @@', line)
462
+ if match:
463
+ new_line = int(match.group(2)) - 1
464
+ elif (line.startswith('+') and not line.startswith('+++') and
465
+ current_file is not None and new_line is not None):
466
+ file_adds[current_file].add(new_line)
467
+ new_line += 1
468
+ elif (not line.startswith('-') and not line.startswith('---') and
469
+ not line.startswith('+++') and new_line is not None):
470
+ new_line += 1
471
+
472
+ return file_adds
473
+
474
+ def extract_identifiers_with_positions(self, line: str, line_number: int) -> List[Tuple[str, int, int]]:
475
+ """Extract all identifiers from a line with their positions."""
476
+ results: List[Tuple[str, int, int]] = []
477
+ for match in re.finditer(self.IDENTIFIER_PATTERN, line):
478
+ identifier = match.group(0)
479
+ char_offset = match.start()
480
+ results.append((identifier, line_number, char_offset))
481
+ return results
482
+
483
+ def _find_symbol_and_parent(self, symbols: List[Dict[str, Any]],
484
+ identifier: str, line: int) -> Optional[Tuple[Dict[str, Any], Optional[Dict[str, Any]]]]:
485
+ """Recursively search the symbol tree for the symbol matching identifier at the given line."""
486
+ def helper(nodes: List[Dict[str, Any]], parent: Optional[Dict[str, Any]] = None) -> Optional[Tuple[Dict[str, Any], Optional[Dict[str, Any]]]]:
487
+ for node in nodes:
488
+ rng = node.get("range")
489
+ if (node.get("name") == identifier and rng and
490
+ rng["start"]["line"] <= line <= rng["end"]["line"]):
491
+ return (node, parent)
492
+ if "children" in node:
493
+ found = helper(node["children"], node)
494
+ if found:
495
+ return found
496
+ return None
497
+ return helper(symbols)
498
+
499
+ def _collect_definition(self, def_file: str, start: int, end: int,
500
+ identifier: str, collected_defs: Dict[str, List[Tuple[int, int, str]]],
501
+ parent_range: Optional[Tuple[int, int]] = None) -> None:
502
+ """Collect definition information for later context building."""
503
+ if def_file not in collected_defs:
504
+ collected_defs[def_file] = []
505
+
506
+ if parent_range:
507
+ collected_defs[def_file].append((parent_range[0], parent_range[1], f"parent_of_{identifier}"))
508
+ else:
509
+ collected_defs[def_file].append((start, end, identifier))
510
+
511
+ def _build_essential_lines(self, collected_defs: Dict[str, List[Tuple[int, int, str]]],
512
+ diff_line_numbers: Dict[str, Set[int]], def_file: str) -> Set[int]:
513
+ """Build set of essential lines to print: diff lines + all definition regions."""
514
+ essential_lines: Set[int] = set()
515
+
516
+ # Add diff lines
517
+ diff_lines = diff_line_numbers.get(os.path.relpath(def_file, KERNEL_PATH), set())
518
+ essential_lines.update(diff_lines)
519
+
520
+ # Add definition ranges
521
+ for start, end, _ in collected_defs.get(def_file, []):
522
+ essential_lines.update(range(start, end + 1))
523
+
524
+ return essential_lines
525
+
526
+ def _fill_context_gaps(self, essential_lines: Set[int]) -> Set[int]:
527
+ """Fill gaps of MAX_GAP or less between essential lines."""
528
+ if not essential_lines:
529
+ return essential_lines
530
+
531
+ sorted_lines = sorted(essential_lines)
532
+ print_lines = set(essential_lines)
533
+
534
+ for i in range(len(sorted_lines) - 1):
535
+ current_line = sorted_lines[i]
536
+ next_line = sorted_lines[i + 1]
537
+ gap_size = next_line - current_line - 1
538
+
539
+ # Fill gaps of MAX_GAP or less
540
+ if 0 < gap_size <= self.MAX_GAP:
541
+ print_lines.update(range(current_line + 1, next_line))
542
+
543
+ return print_lines
544
+
545
+ def _format_file_context(self, def_file: str, print_lines: Set[int]) -> List[str]:
546
+ """Format file context with proper gap indicators."""
547
+ lines = self._get_file_lines(def_file)
548
+ if not lines:
549
+ return []
550
+
551
+ file_context: List[str] = []
552
+ n_lines = len(lines)
553
+ i = 0
554
+
555
+ while i < n_lines:
556
+ if i in print_lines:
557
+ # Start of a region to print
558
+ region_start = i
559
+ while i < n_lines and i in print_lines:
560
+ i += 1
561
+ region_end = i
562
+ file_context.extend(lines[region_start:region_end])
563
+ else:
564
+ # Start of a gap
565
+ gap_start = i
566
+ while i < n_lines and i not in print_lines:
567
+ i += 1
568
+ gap_len = i - gap_start
569
+
570
+ if gap_len > self.MAX_GAP:
571
+ # Convert 0-based to 1-based line numbers for display
572
+ start_line = gap_start + 1
573
+ end_line = gap_start + gap_len
574
+ file_context.append(f"// skipping lines {start_line}-{end_line}\n")
575
+
576
+ return file_context
577
+
578
+ def _get_definition_context(self, collected_defs: Dict[str, List[Tuple[int, int, str]]],
579
+ diff_line_numbers: Dict[str, Set[int]]) -> List[str]:
580
+ """Build context strings for all found definitions."""
581
+ context_parts: List[str] = []
582
+
583
+ for def_file in collected_defs:
584
+ essential_lines = self._build_essential_lines(collected_defs, diff_line_numbers, def_file)
585
+ if not essential_lines:
586
+ continue
587
+
588
+ print_lines = self._fill_context_gaps(essential_lines)
589
+ file_context = self._format_file_context(def_file, print_lines)
590
+
591
+ if file_context:
592
+ rel_path = os.path.relpath(def_file, KERNEL_PATH).lstrip("/\\")
593
+ context_parts.append(f"{rel_path} (definition/diff context):\n\n```c\n" + "".join(file_context) + "```\n")
594
+
595
+ return context_parts
596
+
597
+ def _merge_and_build_context(self, collected_defs: Dict[str, List[Tuple[int, int, str]]],
598
+ file_adds: Dict[str, Set[int]]) -> str:
599
+ """Build the final context string from collected definitions."""
600
+ diff_line_numbers = {file: set(lines) for file, lines in file_adds.items()}
601
+ context_parts = self._get_definition_context(collected_defs, diff_line_numbers)
602
+ return "\n\n".join(context_parts)
603
+
604
+ def _setup_lsp_client(self) -> subprocess.Popen[Any]:
605
+ """Set up and initialize the LSP client, and start background notification logger."""
606
+ proc = subprocess.Popen(
607
+ [
608
+ "clangd",
609
+ "--header-insertion=never",
610
+ "--pretty",
611
+ f"--compile-commands-dir={self.build_dir}",
612
+ "--background-index",
613
+ "--print-all-options",
614
+ # "--log=verbose",
615
+ "--log=error",
616
+ # "--completion-parse=always"
617
+ ],
618
+ stdin=subprocess.PIPE,
619
+ stdout=subprocess.PIPE,
620
+ stderr=subprocess.PIPE,
621
+ cwd=str(KERNEL_PATH),
622
+ )
623
+
624
+ def _stderr_reader(stderr, logger):
625
+ log_path = os.path.join(SANDBOX_PATH, "clangd_stderr.log")
626
+ try:
627
+ with open(log_path, "w") as log_file:
628
+ while True:
629
+ line = stderr.readline(4096)
630
+ if not line:
631
+ break
632
+ decoded_line = line.decode(errors='replace').rstrip()
633
+ # Print to console for explicit visibility
634
+ logger.debug(f"clangd stderr: {decoded_line}")
635
+ log_file.write(decoded_line + "\n")
636
+ except Exception as e:
637
+ logger.error(f"Error reading clangd stderr: {e}")
638
+
639
+
640
+ stderr_thread = threading.Thread(target=_stderr_reader, args=(proc.stderr, self.logger), daemon=True)
641
+ stderr_thread.start()
642
+
643
+ # stdout_logger_thread = threading.Thread(target=_stdout_notification_logger, args=(proc.stdout, self.logger), daemon=True)
644
+ # stdout_logger_thread.start()
645
+
646
+ self._initialize_lsp(proc, KERNEL_PATH)
647
+ return proc
648
+
649
+
650
+
651
+ def _process_file_identifiers(self, proc: subprocess.Popen[Any], filename: str,
652
+ lines: Set[int], collected_defs: Dict[str, List[Tuple[int, int, str]]],
653
+ printed_defs: Set[str], printed_locations: Set[Tuple[str, int, int]]) -> None:
654
+ """Process identifiers in a specific file."""
655
+ abs_path = os.path.join(KERNEL_PATH, filename)
656
+ uri = f"file://{abs_path}"
657
+
658
+ if not os.path.exists(abs_path):
659
+ return
660
+
661
+ file_lines = self._get_file_lines(abs_path)
662
+ if not file_lines:
663
+ return
664
+
665
+ self._open_file_in_lsp(proc, uri, ''.join(file_lines))
666
+
667
+ # Extract identifiers from added lines
668
+ idents_with_pos: List[Tuple[str, int, int]] = []
669
+ for lnum in lines:
670
+ if lnum < len(file_lines):
671
+ idents_with_pos.extend(self.extract_identifiers_with_positions(file_lines[lnum], lnum))
672
+
673
+ # Get document symbols for the file
674
+ doc_symbol_msg = self._create_lsp_message("textDocument/documentSymbol", {
675
+ "textDocument": {"uri": uri}
676
+ }, self.DOC_SYMBOL_MSG_ID)
677
+
678
+ self._send_lsp_message(proc, doc_symbol_msg)
679
+ symbol_resp = self._read_lsp_response(proc, expected_id=self.DOC_SYMBOL_MSG_ID)
680
+ symbols = symbol_resp.get("result", [])
681
+
682
+
683
+ for ident, lnum, col in idents_with_pos:
684
+ self.logger.debug(f"Processing identifier '{ident}' at {uri}:{lnum + 1}:{col + 1}")
685
+
686
+ resp = self._find_actual_definition(proc, uri, lnum, col, ident)
687
+ if not resp.get("result") or len(resp["result"]) == 0:
688
+ continue
689
+ loc = resp["result"][0]
690
+ def_file = loc["uri"].replace("file://", "")
691
+ if not os.path.exists(def_file):
692
+ continue
693
+ header_contents = self._read_file_safely(def_file)
694
+ if not header_contents:
695
+ continue
696
+ def_symbol = self._get_document_symbols(proc, loc["uri"], header_contents, ident)
697
+
698
+ self.logger.debug("Sleeping and trying again")
699
+ time.sleep(15)
700
+
701
+ # Process each identifier
702
+ for ident, lnum, col in idents_with_pos:
703
+ self.logger.debug(f"Processing identifier '{ident}' at {uri}:{lnum + 1}:{col + 1}")
704
+
705
+ if ident in printed_defs: # TODO we shouldn't be skipping all matching identifiers, we should be only skipping duplicate definitions. It's possible that 2 matching identifiers (at different positions) actually have different definitions.
706
+ continue
707
+
708
+ resp = self._find_actual_definition(proc, uri, lnum, col, ident)
709
+ if not resp.get("result") or len(resp["result"]) == 0:
710
+ self.logger.debug(f"No definition found for {ident} in {uri} at line {lnum + 1}, column {col + 1}.")
711
+ continue
712
+
713
+ loc = resp["result"][0]
714
+ def_file = loc["uri"].replace("file://", "")
715
+
716
+ if not os.path.exists(def_file):
717
+ continue
718
+
719
+ header_contents = self._read_file_safely(def_file)
720
+ if not header_contents:
721
+ continue
722
+
723
+ def_symbol = self._get_document_symbols(proc, loc["uri"], header_contents, ident)
724
+
725
+ if def_symbol:
726
+ start = def_symbol["location"]["range"]["start"]["line"]
727
+ end = def_symbol["location"]["range"]["end"]["line"]
728
+ else:
729
+ self.logger.debug(f"Definition for {ident}, {lnum}, {col} not found in {def_file}.")
730
+ start = loc["range"]["start"]["line"]
731
+ end = loc["range"]["end"]["line"]
732
+
733
+ def_loc = (def_file, start, end)
734
+ if def_loc in printed_locations:
735
+ continue
736
+
737
+ # Find parent symbol range
738
+ parent_range = None
739
+ if symbols:
740
+ found = self._find_symbol_and_parent(symbols, ident, start)
741
+ if found and found[1]:
742
+ parent = found[1]
743
+ prng = parent.get("range")
744
+ if prng:
745
+ parent_range = (prng["start"]["line"], prng["end"]["line"])
746
+
747
+ self._collect_definition(def_file, start, end, ident, collected_defs, parent_range)
748
+ printed_defs.add(ident)
749
+ printed_locations.add(def_loc)
750
+
751
+ def wait_for_diagnostics(self, proc: subprocess.Popen[Any], file_uri: str, timeout: int = 10) -> Optional[dict]:
752
+ """
753
+ Wait for textDocument/publishDiagnostics for the given file URI.
754
+ Returns the diagnostics params dict, or None if timeout.
755
+ """
756
+ self.logger.debug(f"Waiting for diagnostics for {file_uri} with timeout {timeout} seconds")
757
+ start_time = time.time()
758
+ while time.time() - start_time < timeout:
759
+ try:
760
+ msg = self._read_lsp_response(proc)
761
+ except Exception as e:
762
+ self.logger.debug(f"Exception while waiting for diagnostics: {e}")
763
+ break
764
+ if msg.get("method") == "textDocument/publishDiagnostics":
765
+ params = msg.get("params", {})
766
+ if params.get("uri") == file_uri:
767
+ self.logger.debug(f"Received diagnostics for {file_uri}: {json.dumps(msg, indent=2)}")
768
+ return params
769
+ self.logger.debug(f"Received message that wasn't a diagnostic message for {file_uri}: {json.dumps(msg)}")
770
+ self.logger.warning(f"Timeout waiting for diagnostics for {file_uri}")
771
+ return None
772
+
773
+ def wait_for_clangd_indexing(self, proc: subprocess.Popen[Any], max_total_wait: int = 600, max_stale_time: int = 60, interval: int = 1, max_interval: int = 10) -> None:
774
+ """
775
+ Wait for clangd background indexing progress notifications, using exponential backoff.
776
+ Reads all available messages from proc.stdout without pausing, only sleeps when no messages are available.
777
+ Breaks if:
778
+ - percentage reaches 100
779
+ - no $/progress notification is received for max_wait seconds
780
+ - the value does not change from the last message for max_wait seconds
781
+ """
782
+ import select
783
+ last_percentage = None
784
+ last_value = None
785
+ waited = 0
786
+ current_interval = interval
787
+ start_time = time.time()
788
+ while time.time() - start_time < max_total_wait:
789
+ message_read = False
790
+ while True:
791
+ # Check if there's data to read from proc.stdout
792
+ ready = select.select([proc.stdout], [], [], 0)[0]
793
+ if not ready:
794
+ break
795
+ try:
796
+ msg = self._read_lsp_response(proc)
797
+ message_read = True
798
+ except Exception as e:
799
+ self.logger.debug(f"Exception while waiting for clangd indexing: {e}")
800
+ break
801
+ # Only interested in $/progress notifications
802
+ if msg.get("method") == "$/progress":
803
+ params = msg.get("params", {})
804
+ token = params.get("token")
805
+ value = params.get("value", {})
806
+ if token == "backgroundIndexProgress" and isinstance(value, dict):
807
+ percentage = value.get("percentage")
808
+ if percentage is not None:
809
+ # self.logger.debug(f"clangd indexing progress: {percentage}%")
810
+ if percentage == 100:
811
+ return
812
+ if last_percentage == percentage and last_value == value:
813
+ # No progress since last check
814
+ waited += current_interval
815
+ if current_interval >= max_stale_time:
816
+ self.logger.error(f"No progress in {max_stale_time} seconds, giving up.")
817
+ return
818
+ else:
819
+ waited = 0
820
+ current_interval = interval
821
+ last_percentage = percentage
822
+ last_value = value
823
+ else:
824
+ # No percentage, just continue
825
+ self.logger.debug(f"Received backgroundIndexProgress without percentage: {json.dumps(value, indent=2)}")
826
+ pass
827
+ else:
828
+ # Not a backgroundIndexProgress, just continue
829
+ self.logger.debug(f"Received $/progress with token {token} but not backgroundIndexProgress: {json.dumps(msg, indent=2)}")
830
+ pass
831
+ else:
832
+ # Not a $/progress message, just continue
833
+ self.logger.debug(f"Received non-progress message: {json.dumps(msg, indent=2)}")
834
+ pass
835
+ # If no message was read, sleep with exponential backoff
836
+ if not message_read:
837
+ time.sleep(current_interval)
838
+ current_interval = min(current_interval * 2, max_interval)
839
+ waited += current_interval
840
+ if time.time() - start_time >= max_total_wait:
841
+ self.logger.warning(f"Clangd indexing did not complete within {max_total_wait} seconds, giving up.")
842
+
843
+ def trick_clangd(self, proc: subprocess.Popen[Any], file_adds: Dict[str, Set[int]]) -> None:
844
+ """Trick clangd into indexing definitions by making a dummy pass and reading messages for 15 seconds."""
845
+ # Dummy query: open the first file if any
846
+ first_file = next(iter(file_adds), None)
847
+ if first_file:
848
+ abs_path = os.path.join(KERNEL_PATH, first_file)
849
+ if os.path.exists(abs_path):
850
+ file_lines = self._get_file_lines(abs_path)
851
+ if file_lines:
852
+ self._open_file_in_lsp(proc, f"file://{abs_path}", ''.join(file_lines))
853
+
854
+ self.wait_for_clangd_indexing(proc)
855
+ # Read LSP messages for 15 seconds
856
+ # start_time = time.time()
857
+ # while time.time() - start_time < 15:
858
+ # try:
859
+ # self._read_lsp_response(proc)
860
+ # except Exception as e:
861
+ # self.logger.debug(f"Exception while reading LSP response: {e}")
862
+ # # break
863
+
864
+ def _collect_definitions(self, file_adds: Dict[str, Set[int]]) -> Dict[str, List[Tuple[int, int, str]]]:
865
+ """Collect all definitions from the diff using LSP, but wait after a dummy pass before real querying."""
866
+ # Start the LSP client and make a dummy query to trigger indexing
867
+ proc = self._setup_lsp_client()
868
+
869
+ # self.trick_clangd(proc, file_adds)
870
+
871
+ # import psutil
872
+ # max_wait = 10
873
+ # interval = 5
874
+ # waited = 0
875
+ # while waited < max_wait:
876
+ # try:
877
+ # self.logger.debug(f"pid: {proc.pid}, waiting for clangd-19 to index files...")
878
+ # p = psutil.Process(proc.pid)
879
+ # parent_pid = p.ppid()
880
+ # sibling_procs = [s for s in psutil.process_iter(['pid', 'ppid', 'name', 'cmdline'])
881
+ # if s.info['ppid'] == parent_pid]
882
+ # sibling_pids = [s.info['pid'] for s in sibling_procs]
883
+ # self.logger.debug(f"Sibling PIDs (same parent as clangd-19 proc {proc.pid}, parent {parent_pid}): {sibling_pids}")
884
+ # except Exception as e:
885
+ # self.logger.debug(f"Error listing sibling processes: {e}")
886
+ # time.sleep(interval)
887
+ # waited += interval
888
+
889
+
890
+
891
+ # Now process all identifiers as normal
892
+ printed_defs: Set[str] = set()
893
+ printed_locations: Set[Tuple[str, int, int]] = set()
894
+ collected_defs: Dict[str, List[Tuple[int, int, str]]] = {}
895
+ for filename, lines in file_adds.items():
896
+ self._process_file_identifiers(proc, filename, lines, collected_defs, printed_defs, printed_locations)
897
+ proc.terminate()
898
+ return collected_defs
899
+
900
+ def process_diff_and_print_definitions(self, diff_lines: List[str]) -> None:
901
+ """Process diff and collect definitions for context building."""
902
+ file_adds = self.parse_diff(diff_lines)
903
+ if not file_adds:
904
+ self.logger.error("No additions found in diff.")
905
+ return
906
+
907
+ collected_defs = self._collect_definitions(file_adds)
908
+ self.context = self._merge_and_build_context(collected_defs, file_adds)
909
+
910
+
911
+ def delete_cache(self) -> None:
912
+ """ Remove the .cache directory under KERNEL_PATH """
913
+ import os
914
+ cache_dir = os.path.join(KERNEL_PATH, ".cache")
915
+ try:
916
+ import shutil
917
+ shutil.rmtree(cache_dir, ignore_errors=True)
918
+ self.logger.debug(f"Removed cache directory: {cache_dir}")
919
+ except Exception as e:
920
+ self.logger.error(f"Failed to remove cache directory {cache_dir}: {e}")
921
+
922
+ def get_context(self) -> None:
923
+ """Generate context for the AI review."""
924
+ self.delete_cache() # TEMP DELETE
925
+
926
+ self.generate_compile_commands() # TEMP uncomment
927
+ if not hasattr(self, 'context'):
928
+ self.context = ""
929
+ # Split self.diff into lines and strip trailing newlines
930
+ diff_lines = [line.rstrip('\n') for line in self.diff.splitlines()]
931
+ self.process_diff_and_print_definitions(diff_lines)
932
+ self.logger.debug(f"Context after processing diff: {self.context}")
933
+
934
+ def setup(self) -> None:
935
+ super().setup()
936
+
937
+ def run(self) -> str:
938
+ """Execute the AI code review."""
939
+ self.get_context()
940
+
941
+ formatted_prompt = self.PROMPT_TEMPLATE.format(
942
+ diff=self.diff,
943
+ commit_text=self.commit_message,
944
+ context=self.context
945
+ )
946
+
947
+ # self.logger.debug(f"System prompt:\n{self.get_system_prompt()}") # TEMP
948
+ self.logger.debug(f"Formatted prompt for AI review:\n{formatted_prompt}")
949
+
950
+ # Write prompts to sandbox for debugging
951
+ prompt_path = os.path.join(SANDBOX_PATH, "prompt.md")
952
+ with open(prompt_path, "w") as f:
953
+ f.write(formatted_prompt)
954
+
955
+ system_prompt_path = os.path.join(SANDBOX_PATH, "system_prompt.md")
956
+ with open(system_prompt_path, "w") as f:
957
+ f.write(self.get_system_prompt())
958
+
959
+
960
+ result = self.provider_api_call(
961
+ user_prompt=formatted_prompt,
962
+ system_prompt=self.get_system_prompt(),
963
+ )
964
+
965
+ return self.format_chat_response(result)