patchpilot-mcp 0.4.1__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.
patchpilot/changed.py ADDED
@@ -0,0 +1,464 @@
1
+ """Review supplied full source against explicitly supplied unified diff and baseline."""
2
+
3
+ from typing import Any
4
+ from .analysis import MAX_FILES, MAX_FINDINGS, InputError, bounded, parse_diff
5
+ from .config import PARSE_RULES, apply_policy, parse_policy, python_comments
6
+ from .js_review import GRAMMARS, review_static
7
+ from .json_review import review_json
8
+ from .analysis import review_python
9
+ from .common import no_input
10
+ from .snapshot import attach_ids
11
+
12
+ MAX_TOTAL = 1024 * 1024
13
+ LANGUAGES = {"python", "json", *GRAMMARS, "unknown"}
14
+
15
+
16
+ def infer(path):
17
+ return {
18
+ "py": "python",
19
+ "pyi": "python",
20
+ "json": "json",
21
+ "js": "javascript",
22
+ "mjs": "javascript",
23
+ "cjs": "javascript",
24
+ "jsx": "jsx",
25
+ "ts": "typescript",
26
+ "tsx": "tsx",
27
+ "go": "go",
28
+ "java": "java",
29
+ "cs": "csharp",
30
+ "dart": "dart",
31
+ }.get(path.lower().rsplit(".", 1)[-1], "unknown")
32
+
33
+
34
+ def _source_args(source, path, language, start_line, complete):
35
+ if not isinstance(path, str):
36
+ raise InputError("Invalid path label")
37
+ language = infer(path) if language is None else language
38
+ if not isinstance(language, str) or language not in LANGUAGES:
39
+ raise InputError("Unsupported source language label")
40
+ if (
41
+ not isinstance(source, str)
42
+ or not isinstance(path, str)
43
+ or not 1 <= len(path) <= 1024
44
+ ):
45
+ raise InputError("Invalid source, label, offset or completeness")
46
+ _source_offset(start_line, complete)
47
+ return language
48
+
49
+
50
+ def _source_offset(start_line, complete):
51
+ if (
52
+ type(start_line) is not int
53
+ or not 1 <= start_line <= 10**8
54
+ or type(complete) is not bool
55
+ ):
56
+ raise InputError("Invalid offset or completeness")
57
+ if complete and start_line != 1:
58
+ raise InputError("Complete source starts at line 1")
59
+
60
+
61
+ def _analyze_source(source, path, language, start_line, threshold, complete):
62
+ comments = {}
63
+ if source == "" and not complete:
64
+ report = no_input(path)
65
+ elif language == "python":
66
+ report = review_python(source, path, start_line, threshold, complete)
67
+ comments = python_comments(source, start_line) if report["syntax_ok"] else {}
68
+ elif language == "json":
69
+ report = review_json(source, path, start_line, complete=complete)
70
+ elif language in GRAMMARS:
71
+ report = review_static(
72
+ source, path, start_line, language, include_comments=True, complete=complete
73
+ )
74
+ comments = report.pop("comments", {}) if report["syntax_ok"] else {}
75
+ else:
76
+ report = dict(
77
+ path=path,
78
+ syntax_ok=None,
79
+ coverage="unknown_unsupported_language",
80
+ lines=len(bounded(source, name="source")),
81
+ findings=[],
82
+ omitted_findings=0,
83
+ limitations=["No parser for supplied language."],
84
+ )
85
+ return report, comments
86
+
87
+
88
+ def _source_coverage(report, complete, omitted):
89
+ if report["syntax_ok"] is None:
90
+ return report.get("coverage", "unknown")
91
+ if omitted:
92
+ return "checked_incomplete_findings"
93
+ return "checked_complete" if complete else "checked_fragment"
94
+
95
+
96
+ def review_source(
97
+ source,
98
+ path="snippet.py",
99
+ language=None,
100
+ config_toml=None,
101
+ start_line=1,
102
+ complete=None,
103
+ complexity_threshold=10,
104
+ ):
105
+ if complete is None:
106
+ complete = source != ""
107
+ language = _source_args(source, path, language, start_line, complete)
108
+ policy = parse_policy(config_toml, complexity_threshold)
109
+ threshold, settings = policy.for_path(path)
110
+ report, comments = _analyze_source(
111
+ source, path, language, start_line, threshold, complete
112
+ )
113
+ active, suppressed, diagnostics = apply_policy(
114
+ report["findings"], comments, settings
115
+ )
116
+ omitted = report.get("omitted_findings", 0)
117
+ report.update(
118
+ language=language,
119
+ coverage=_source_coverage(report, complete, omitted),
120
+ omitted_findings=omitted,
121
+ findings=attach_ids(active),
122
+ suppressed_findings=attach_ids(suppressed),
123
+ policy_diagnostics=diagnostics,
124
+ original_finding_count=len(active) + len(suppressed) + omitted,
125
+ )
126
+ return report
127
+
128
+
129
+ def _verify_eof(source, lines, context, eof):
130
+ if eof is not None and (eof != len(lines) or source.endswith("\n")):
131
+ return False, "end_of_file", eof
132
+ if (
133
+ eof is None
134
+ and lines
135
+ and context
136
+ and context[-1][0] == len(lines)
137
+ and not source.endswith("\n")
138
+ ):
139
+ return False, "missing_eof_marker", len(lines)
140
+ return True, None, None
141
+
142
+
143
+ def _invalid_range(start, count, line_count):
144
+ return start + count - 1 > line_count if count else start > line_count
145
+
146
+
147
+ def _verify_context(source, context, ranges, eof):
148
+ lines = bounded(source, name="full source")
149
+ for start, count in ranges:
150
+ if _invalid_range(start, count, len(lines)):
151
+ return False, "range", start
152
+ for position, expected in context:
153
+ if position < 1 or position > len(lines) or lines[position - 1] != expected:
154
+ return False, "line_content", position
155
+ return _verify_eof(source, lines, context, eof)
156
+
157
+
158
+ def _map_range(mapping, oi, ni, old_end, new_end):
159
+ for old, new in zip(range(oi, old_end), range(ni, new_end)):
160
+ mapping[new] = old
161
+
162
+
163
+ def _map_unchanged(mapping, os, oc, ns, nc, old_removed, new_added):
164
+ old_unchanged = [n for n in range(os, os + oc) if n not in old_removed]
165
+ new_unchanged = [n for n in range(ns, ns + nc) if n not in new_added]
166
+ for old, new in zip(old_unchanged, new_unchanged):
167
+ mapping[new] = old
168
+
169
+
170
+ def _line_mapping(old_count, new_count, file):
171
+ """Map unchanged lines across hunks (new coordinate -> old coordinate)."""
172
+ mapping = {}
173
+ old_removed = set(file.removed_lines)
174
+ new_added = set(file.added_lines)
175
+ oi = 1
176
+ ni = 1
177
+ for (os, oc), (ns, nc) in zip(file.old_ranges, file.new_ranges):
178
+ old_start = os + 1 if not oc else os
179
+ new_start = ns + 1 if not nc else ns
180
+ _map_range(mapping, oi, ni, old_start, new_start)
181
+ _map_unchanged(mapping, os, oc, ns, nc, old_removed, new_added)
182
+ oi = os + oc if oc else os + 1
183
+ ni = ns + nc if nc else ns + 1
184
+ _map_range(mapping, oi, ni, old_count + 1, new_count + 1)
185
+ return mapping
186
+
187
+
188
+ def _identity(f):
189
+ return (
190
+ f.get("code"),
191
+ f.get("line"),
192
+ f.get("column"),
193
+ f.get("message"),
194
+ f.get("evidence"),
195
+ )
196
+
197
+
198
+ def _entry_source(entry, expected, supplied):
199
+ if not isinstance(entry, dict) or set(entry) - {
200
+ "path",
201
+ "source",
202
+ "previous_source",
203
+ "language",
204
+ }:
205
+ raise InputError("Unexpected changed review entry fields")
206
+ path = entry.get("path")
207
+ if not isinstance(path, str) or path not in expected or path in supplied:
208
+ raise InputError("Entry path must uniquely match a nondeleted new diff path")
209
+ language = entry.get("language", infer(path))
210
+ if not isinstance(language, str) or language not in LANGUAGES:
211
+ raise InputError("Unsupported language")
212
+ return path
213
+
214
+
215
+ def _source_bytes(entry):
216
+ source, before = entry.get("source"), entry.get("previous_source")
217
+ if not isinstance(source, str) or (
218
+ before is not None and not isinstance(before, str)
219
+ ):
220
+ raise InputError(
221
+ "Each entry requires full source text; previous_source is optional text"
222
+ )
223
+ total = 0
224
+ for value in (source, before):
225
+ if value is not None:
226
+ bounded(value, name="source")
227
+ total += len(value.encode("utf-8"))
228
+ return total
229
+
230
+
231
+ def _validate_entries(files, entries):
232
+ expected = {f.path: f for f in files if f.new != "/dev/null"}
233
+ if not isinstance(entries, list) or len(entries) > MAX_FILES:
234
+ raise InputError("entries must be a bounded list")
235
+ supplied = {}
236
+ total = 0
237
+ for entry in entries:
238
+ path = _entry_source(entry, expected, supplied)
239
+ total += _source_bytes(entry)
240
+ if total > MAX_TOTAL:
241
+ raise InputError("Combined source exceeds 1 MiB")
242
+ supplied[path] = entry
243
+ return supplied
244
+
245
+
246
+ def _baseline(file, entry, source, row, config_toml):
247
+ if entry.get("previous_source") is None or file.old == "/dev/null":
248
+ return set(), {}
249
+ before = entry["previous_source"]
250
+ old_valid, _, bad_line = _verify_context(
251
+ before, file.old_context, file.old_ranges, file.old_eof
252
+ )
253
+ if not old_valid:
254
+ row.update(baseline_coverage="context_mismatch", baseline_context_line=bad_line)
255
+ return set(), {}
256
+ try:
257
+ prior = review_source(
258
+ before, file.old, entry.get("language"), config_toml, complete=True
259
+ )
260
+ except InputError:
261
+ row["baseline_coverage"] = "unknown_input_limit"
262
+ return set(), {}
263
+ if (
264
+ prior["syntax_ok"] is not True
265
+ or prior["original_finding_count"] >= MAX_FINDINGS
266
+ ):
267
+ row["baseline_coverage"] = "unknown_or_incomplete"
268
+ return set(), {}
269
+ old_lines = bounded(before, name="baseline")
270
+ new_lines = bounded(source, name="source")
271
+ mapping = _line_mapping(len(old_lines), len(new_lines), file)
272
+ if not _matching_baseline(old_lines, new_lines, mapping, file):
273
+ row["baseline_coverage"] = "context_mismatch"
274
+ return set(), {}
275
+ row["baseline_coverage"] = "checked_complete"
276
+ return {
277
+ _identity(f) for f in prior["findings"] + prior["suppressed_findings"]
278
+ }, mapping
279
+
280
+
281
+ def _matching_baseline(old_lines, new_lines, mapping, file):
282
+ return (
283
+ len(mapping) == len(old_lines) - len(file.removed_lines)
284
+ and len(mapping) == len(new_lines) - len(file.added_lines)
285
+ and all(old_lines[o - 1] == new_lines[n - 1] for n, o in mapping.items())
286
+ )
287
+
288
+
289
+ def _post_context(file, source):
290
+ valid, kind, line = _verify_context(
291
+ source, file.new_context, file.new_ranges, file.new_eof
292
+ )
293
+ if valid and file.old == "/dev/null":
294
+ count = len(bounded(source, name="new source"))
295
+ if (
296
+ file.old_context
297
+ or any(n for _, n in file.old_ranges)
298
+ or file.added_lines != list(range(1, count + 1))
299
+ ):
300
+ return False, "new_file_incomplete", None
301
+ return valid, kind, line
302
+
303
+
304
+ def _file_row(file):
305
+ return dict(
306
+ path=file.path,
307
+ change_kind=file.change_kind,
308
+ added_lines=file.added_lines,
309
+ coverage="unknown_missing_source",
310
+ syntax_ok=None,
311
+ context_validated=None,
312
+ baseline_coverage="not_supplied",
313
+ changed_findings=0,
314
+ outside_changed_findings=0,
315
+ )
316
+
317
+
318
+ def _post_review(file, entry, row, config_toml):
319
+ if file.new == "/dev/null":
320
+ row["coverage"] = "removed_no_post_source"
321
+ return None
322
+ if entry is None:
323
+ return None
324
+ source = entry["source"]
325
+ valid, kind, line = _post_context(file, source)
326
+ if not valid:
327
+ row.update(
328
+ coverage="context_mismatch",
329
+ context_validated=False,
330
+ context_issue=dict(kind=kind, line=line),
331
+ )
332
+ return None
333
+ row["context_validated"] = True if file.hunks or file.old == "/dev/null" else None
334
+ try:
335
+ result = review_source(
336
+ source, file.path, entry.get("language"), config_toml, complete=True
337
+ )
338
+ except InputError:
339
+ row["coverage"] = "unknown_input_limit"
340
+ return None
341
+ row.update(
342
+ coverage=result["coverage"],
343
+ syntax_ok=result["syntax_ok"],
344
+ original_finding_count=result["original_finding_count"],
345
+ omitted_source_findings=result.get("omitted_findings", 0),
346
+ )
347
+ return result
348
+
349
+
350
+ def _outside_scope(f, mapping, prior_identities, row):
351
+ old_line = mapping.get(f.get("line"))
352
+ if old_line is not None and _identity(dict(f, line=old_line)) in prior_identities:
353
+ return "preexisting_verified"
354
+ if old_line is not None and row["baseline_coverage"] == "checked_complete":
355
+ return "outside_changed_lines_newly_observed"
356
+ return "outside_changed_lines_unverified"
357
+
358
+
359
+ def _collect(result, file, row, prior_identities, mapping, groups):
360
+ added = set(file.added_lines)
361
+ for f in result["findings"]:
362
+ if f["code"] in PARSE_RULES:
363
+ groups["changed"].append(dict(f, change_scope="file_syntax_error"))
364
+ row["changed_findings"] += 1
365
+ elif f.get("line") in added:
366
+ groups["changed"].append(dict(f, change_scope="changed_line"))
367
+ row["changed_findings"] += 1
368
+ else:
369
+ scope = _outside_scope(f, mapping, prior_identities, row)
370
+ groups["outside"].append(dict(f, change_scope=scope))
371
+ row["outside_changed_findings"] += 1
372
+ for f in result["suppressed_findings"]:
373
+ scope = "changed_line" if f.get("line") in added else "outside_changed_lines"
374
+ groups["suppressed"].append(dict(f, change_scope=scope))
375
+ groups["diagnostics"].extend(
376
+ dict(x, path=file.path) for x in result["policy_diagnostics"]
377
+ )
378
+
379
+
380
+ def _prioritize(items):
381
+ rank = {"error": 0, "warning": 1, "info": 2}
382
+ return sorted(
383
+ items,
384
+ key=lambda f: (
385
+ rank.get(f["severity"], 3),
386
+ f["path"],
387
+ f.get("line") or 0,
388
+ f["id"],
389
+ ),
390
+ )
391
+
392
+
393
+ def _diff_facts(diff_findings, policy):
394
+ for fact in diff_findings:
395
+ _, settings = policy.for_path(fact["path"])
396
+ active, _, _ = apply_policy([fact], {}, settings)
397
+ for f in attach_ids(active):
398
+ yield dict(f, change_scope="changed_line", evidence_source="diff")
399
+
400
+
401
+ def _coverage_complete(rows, groups):
402
+ return (
403
+ bool(rows)
404
+ and all(
405
+ r["coverage"] in {"checked_complete", "removed_no_post_source"}
406
+ and r["context_validated"] is not False
407
+ and r["baseline_coverage"] in {"not_supplied", "checked_complete"}
408
+ and r.get("original_finding_count", 0) < MAX_FINDINGS
409
+ for r in rows
410
+ )
411
+ and all(len(items) <= MAX_FINDINGS for items in groups.values())
412
+ )
413
+
414
+
415
+ def _result(rows, groups):
416
+ changed, outside, suppressed, diagnostics = (
417
+ groups[k] for k in ("changed", "outside", "suppressed", "diagnostics")
418
+ )
419
+ coverage_complete = _coverage_complete(rows, groups)
420
+ source_omissions = sum(r.get("omitted_source_findings", 0) for r in rows)
421
+ statuses = {row["coverage"] for row in rows}
422
+ return dict(
423
+ files=rows,
424
+ coverage_complete=coverage_complete,
425
+ coverage_statuses=sorted(statuses),
426
+ findings=_prioritize(changed)[:MAX_FINDINGS],
427
+ omitted_findings=max(0, len(changed) - MAX_FINDINGS) + source_omissions,
428
+ omitted_source_findings=source_omissions,
429
+ outside_changed_findings=_prioritize(outside)[:MAX_FINDINGS],
430
+ omitted_outside_findings=max(0, len(outside) - MAX_FINDINGS),
431
+ suppressed_findings=_prioritize(suppressed)[:MAX_FINDINGS],
432
+ omitted_suppressed_findings=max(0, len(suppressed) - MAX_FINDINGS),
433
+ policy_diagnostics=diagnostics[:MAX_FINDINGS],
434
+ omitted_policy_diagnostics=max(0, len(diagnostics) - MAX_FINDINGS),
435
+ limitations=[
436
+ "Only supplied source and diff hunks are checked; no repository or runtime verification.",
437
+ "File-level parse errors are always reported, even outside added lines.",
438
+ "Without a matching baseline, outside-line findings are not proven preexisting.",
439
+ "Incomplete/mismatched source or a reached finding cap makes coverage incomplete, never a clean pass.",
440
+ ],
441
+ )
442
+
443
+
444
+ def review_changed(
445
+ diff: str, entries: list[dict[str, Any]], config_toml: str | None = None
446
+ ) -> dict:
447
+ policy = parse_policy(config_toml)
448
+ groups = dict(changed=[], outside=[], suppressed=[], diagnostics=[])
449
+ if diff == "" and entries == []:
450
+ groups["changed"] = attach_ids(no_input("")["findings"])
451
+ return _result([], groups)
452
+ files, diff_findings = parse_diff(diff)
453
+ supplied = _validate_entries(files, entries)
454
+ rows = []
455
+ for file in files:
456
+ row = _file_row(file)
457
+ rows.append(row)
458
+ entry = supplied.get(file.path)
459
+ result = _post_review(file, entry, row, config_toml)
460
+ if result is not None:
461
+ prior, mapping = _baseline(file, entry, entry["source"], row, config_toml)
462
+ _collect(result, file, row, prior, mapping, groups)
463
+ groups["changed"].extend(_diff_facts(diff_findings, policy))
464
+ return _result(rows, groups)
patchpilot/common.py ADDED
@@ -0,0 +1,75 @@
1
+ """Shared bounded input and finding primitives."""
2
+
3
+ from typing import Any
4
+
5
+ MAX_BYTES = 256 * 1024
6
+ MAX_LINES = 6000
7
+ MAX_FILES = 100
8
+ MAX_FINDINGS = 100
9
+ MAX_AST_NODES = 20000
10
+
11
+
12
+ class InputError(ValueError):
13
+ """Supplied text is unsupported or exceeds the review budget."""
14
+
15
+
16
+ def bounded(text: str, *, name: str) -> list[str]:
17
+ if len(text) > MAX_BYTES:
18
+ raise InputError(f"{name} exceeds {MAX_BYTES} UTF-8 bytes")
19
+ try:
20
+ byte_count = len(text.encode("utf-8"))
21
+ except UnicodeError as exc:
22
+ raise InputError(f"{name} is not valid UTF-8 text") from exc
23
+ if byte_count > MAX_BYTES:
24
+ raise InputError(f"{name} exceeds {MAX_BYTES} UTF-8 bytes")
25
+ lines = text.split("\n")
26
+ if lines[-1] == "":
27
+ lines.pop()
28
+ lines = [line.removesuffix("\r") for line in lines]
29
+ if len(lines) > MAX_LINES:
30
+ raise InputError(f"{name} exceeds {MAX_LINES} lines")
31
+ return lines
32
+
33
+
34
+ def finding(
35
+ code: str,
36
+ severity: str,
37
+ evidence: str,
38
+ path: str,
39
+ line: int | None,
40
+ message: str,
41
+ recommendation: str,
42
+ ) -> dict[str, Any]:
43
+ return dict(
44
+ code=code,
45
+ severity=severity,
46
+ evidence=evidence,
47
+ path=path,
48
+ line=line,
49
+ message=message,
50
+ recommendation=recommendation,
51
+ )
52
+
53
+
54
+ def no_input(path: str, **fields) -> dict:
55
+ """No supplied content is unknown, not a syntax success."""
56
+ return dict(
57
+ path=path,
58
+ syntax_ok=None,
59
+ coverage="unknown_empty_input",
60
+ lines=0,
61
+ findings=[
62
+ finding(
63
+ "NO_INPUT",
64
+ "warning",
65
+ "fact",
66
+ path,
67
+ None,
68
+ "No source text was supplied.",
69
+ "Supply source or explicitly identify an intentional empty file.",
70
+ )
71
+ ],
72
+ limitations=["Empty input has no source syntax coverage."],
73
+ omitted_findings=0,
74
+ **fields,
75
+ )