pr-proof 0.0.0-stage → 0.1.0-beta.0

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/Procfile +2 -0
  3. package/README.md +300 -2
  4. package/app/__init__.py +1 -0
  5. package/app/api/__init__.py +1 -0
  6. package/app/api/cli.py +35 -0
  7. package/app/api/github.py +168 -0
  8. package/app/api/history.py +123 -0
  9. package/app/api/main.py +95 -0
  10. package/app/api/queue.py +45 -0
  11. package/app/api/responses.py +28 -0
  12. package/app/api/signature.py +19 -0
  13. package/app/api/sync.py +189 -0
  14. package/app/api/sync_rules_pure.py +71 -0
  15. package/app/api/webhook.py +166 -0
  16. package/app/setup/__init__.py +4 -0
  17. package/app/setup/cli.py +90 -0
  18. package/app/setup/configure.py +720 -0
  19. package/app/setup/files.py +93 -0
  20. package/app/setup/github_setup.py +149 -0
  21. package/app/setup/install_hints.json +32 -0
  22. package/app/setup/setup_pure.py +312 -0
  23. package/app/setup/start.py +113 -0
  24. package/app/shared/__init__.py +1 -0
  25. package/app/shared/comment_pure.py +29 -0
  26. package/app/shared/config.py +106 -0
  27. package/app/shared/db_pure.py +339 -0
  28. package/app/shared/embed_models_pure.py +55 -0
  29. package/app/shared/feedback_pure.py +84 -0
  30. package/app/shared/github_auth.py +74 -0
  31. package/app/shared/job_pure.py +43 -0
  32. package/app/shared/notify.py +97 -0
  33. package/app/shared/ops_alert_pure.py +38 -0
  34. package/app/shared/state_keys_pure.py +24 -0
  35. package/app/shared/version.py +27 -0
  36. package/app/worker/__init__.py +1 -0
  37. package/app/worker/access_pure.py +180 -0
  38. package/app/worker/ai/__init__.py +1 -0
  39. package/app/worker/ai/claude_cli.py +684 -0
  40. package/app/worker/ai/mcp_relay.py +42 -0
  41. package/app/worker/ai/path_hook.py +103 -0
  42. package/app/worker/ai/tool_server.py +139 -0
  43. package/app/worker/ai/workdir.py +333 -0
  44. package/app/worker/base_config.py +173 -0
  45. package/app/worker/budget.py +100 -0
  46. package/app/worker/cache_key_pure.py +34 -0
  47. package/app/worker/call_budget_pure.py +132 -0
  48. package/app/worker/checker_authoring_pure.py +599 -0
  49. package/app/worker/checker_pure.py +196 -0
  50. package/app/worker/cli.py +97 -0
  51. package/app/worker/command.py +191 -0
  52. package/app/worker/command_pure.py +38 -0
  53. package/app/worker/coverage.py +123 -0
  54. package/app/worker/coverage_pure.py +202 -0
  55. package/app/worker/deps.py +22 -0
  56. package/app/worker/diff_pure.py +419 -0
  57. package/app/worker/doc_rules_pure.py +201 -0
  58. package/app/worker/doc_rules_report.py +979 -0
  59. package/app/worker/eval_run_pure.py +241 -0
  60. package/app/worker/evaluation.py +151 -0
  61. package/app/worker/feedback.py +448 -0
  62. package/app/worker/feedback_pure.py +131 -0
  63. package/app/worker/feedback_report_pure.py +90 -0
  64. package/app/worker/feedback_triage.py +85 -0
  65. package/app/worker/feedback_triage_pure.py +363 -0
  66. package/app/worker/fix/__init__.py +1 -0
  67. package/app/worker/fix/decide.py +197 -0
  68. package/app/worker/fix/feedback_fix_pure.py +125 -0
  69. package/app/worker/fix/fix_decision_pure.py +386 -0
  70. package/app/worker/fix/fix_pure.py +70 -0
  71. package/app/worker/fix/mechanical_fix.py +214 -0
  72. package/app/worker/fix/model_fix.py +575 -0
  73. package/app/worker/fix/model_fix_pure.py +593 -0
  74. package/app/worker/fix/proposal.py +584 -0
  75. package/app/worker/fix/proposal_pure.py +103 -0
  76. package/app/worker/fix/scope.py +40 -0
  77. package/app/worker/fix/scope_pure.py +222 -0
  78. package/app/worker/generated_tests_pure.py +442 -0
  79. package/app/worker/github.py +471 -0
  80. package/app/worker/graph.py +963 -0
  81. package/app/worker/guard.py +91 -0
  82. package/app/worker/lang/__init__.py +0 -0
  83. package/app/worker/lang/install_pure.py +25 -0
  84. package/app/worker/lang/python.py +862 -0
  85. package/app/worker/loop.py +200 -0
  86. package/app/worker/main.py +76 -0
  87. package/app/worker/markdown_pure.py +29 -0
  88. package/app/worker/mcp_pure.py +150 -0
  89. package/app/worker/memory.py +503 -0
  90. package/app/worker/merged_fix_pure.py +236 -0
  91. package/app/worker/pr_check_report_pure.py +201 -0
  92. package/app/worker/pr_description_report_pure.py +112 -0
  93. package/app/worker/preflight.py +125 -0
  94. package/app/worker/rag_pure.py +285 -0
  95. package/app/worker/rag_switch_pure.py +203 -0
  96. package/app/worker/records.py +207 -0
  97. package/app/worker/records_pure.py +239 -0
  98. package/app/worker/repo.py +588 -0
  99. package/app/worker/repo_config_pure.py +269 -0
  100. package/app/worker/report.py +300 -0
  101. package/app/worker/retry.py +65 -0
  102. package/app/worker/rule_pure.py +223 -0
  103. package/app/worker/rule_reading_pure.py +503 -0
  104. package/app/worker/rules/__init__.py +1 -0
  105. package/app/worker/rules/checkers.py +615 -0
  106. package/app/worker/rules/detect.py +154 -0
  107. package/app/worker/rules/doc_rules.py +301 -0
  108. package/app/worker/rules/doc_sections_pure.py +168 -0
  109. package/app/worker/rules/judge.py +410 -0
  110. package/app/worker/rules/judge_pure.py +627 -0
  111. package/app/worker/rules/pr_check.py +404 -0
  112. package/app/worker/rules/pr_check_pure.py +922 -0
  113. package/app/worker/rules/pr_description.py +218 -0
  114. package/app/worker/rules/pr_description_pure.py +743 -0
  115. package/app/worker/rules/rules.py +314 -0
  116. package/app/worker/rules/run_check.py +95 -0
  117. package/app/worker/rules/run_check_pure.py +219 -0
  118. package/app/worker/rules/tool_choice_pure.py +135 -0
  119. package/app/worker/sandbox/__init__.py +1 -0
  120. package/app/worker/sandbox/checker_runner.py +412 -0
  121. package/app/worker/sandbox/container.py +130 -0
  122. package/app/worker/sandbox/docker_cli.py +170 -0
  123. package/app/worker/sandbox/safe_read.py +32 -0
  124. package/app/worker/sandbox/toolcache.py +425 -0
  125. package/app/worker/state.py +602 -0
  126. package/app/worker/test_lines.py +77 -0
  127. package/app/worker/test_run_pure.py +133 -0
  128. package/app/worker/text_edit_pure.py +66 -0
  129. package/app/worker/tools_pure.py +152 -0
  130. package/app/worker/update.py +305 -0
  131. package/app/worker/violation_pure.py +33 -0
  132. package/bin/pr-proof.js +173 -0
  133. package/docker/sandbox/Dockerfile +12 -0
  134. package/docker/sandbox/coveragerc +19 -0
  135. package/docker-compose.yml +5 -0
  136. package/package.json +31 -4
  137. package/pyproject.toml +60 -0
@@ -0,0 +1,442 @@
1
+ """수정 작성의 모델이 만든 테스트 (docs/DESIGN.md 4.7, 4.8의 6번, 7.9). 데이터, 받아들이는 조건,
2
+ 위반 줄의 실행 상태, 도구 결과의 글. 판단만 하고 테스트를 돌리거나 파일을 바꾸지 않는다.
3
+
4
+ 테스트를 돌리고 결과 파일을 읽는 것은 `app/worker/lang/python.py`, 도구와 출구 검사의 실행은
5
+ `app/worker/fix/model_fix.py`가 한다. 받아들이는 조건은 저장소 주인이 정했다(2026-11-21, 11.1):
6
+ 고치기 전 코드에서 통과한다, 위반이 있는 줄을 실행한다, 있던 테스트(와 앞서 받아들인 테스트)가
7
+ 실행하지 않던 줄을 새로 실행한다, 고친 뒤에도 통과한다. 여기에 빈 테스트가 아니다(테스트 함수마다
8
+ assert나 `pytest.raises`)를 더했다.
9
+ """
10
+
11
+ import ast
12
+ import json
13
+ from collections.abc import Iterable, Mapping, Sequence
14
+ from dataclasses import dataclass
15
+ from typing import Final, Literal
16
+
17
+ from app.worker.coverage_pure import FileCoverage, line_covered, statements
18
+ from app.worker.test_run_pure import PytestRun
19
+ from app.worker.violation_pure import Violation
20
+
21
+ # 만든 테스트의 상한 (9.2). 수정의 크기 상한(파일 20개, 바뀐 줄 500줄)과 따로 센다. 테스트 줄이
22
+ # 수정의 상한을 먹어 수정이 못 올라가는 일이 없게 한다
23
+ MAX_TEST_FILES: Final = 10
24
+ MAX_TEST_LINES: Final = 200 # 파일 하나
25
+ MAX_TOTAL_TEST_LINES: Final = 1000
26
+ # 도구 결과에 싣는 글의 상한 (글자 수). PR 코드가 만든 글이라 자료로만 넣는다
27
+ MAX_OUTPUT_CHARS: Final = 3000
28
+ MAX_LISTED: Final = 20
29
+
30
+ Rejection = Literal[
31
+ "empty", "too_many", "too_big", "not_run", "fails_before", "misses_violation", "overlaps"
32
+ ]
33
+ REJECTION_LABEL: Final[Mapping[str, str]] = {
34
+ "empty": "assert나 pytest.raises가 없는 테스트 함수가 있음",
35
+ "too_many": f"만든 테스트 파일 상한({MAX_TEST_FILES}개)을 넘음",
36
+ "too_big": f"테스트 줄 상한(파일마다 {MAX_TEST_LINES}줄, 합 {MAX_TOTAL_TEST_LINES}줄)을 넘음",
37
+ "not_run": "pytest가 이 파일의 테스트를 하나도 돌리지 않음",
38
+ "fails_before": "고치기 전 코드에서 실패함",
39
+ "misses_violation": "대상 위반의 줄을 하나도 실행하지 않음",
40
+ "overlaps": "있던 테스트나 앞서 받아들인 테스트가 이미 실행하는 줄만 실행함",
41
+ }
42
+
43
+ Outcome = Literal["passed", "failed", "not_run"]
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class FileLines:
48
+ """소스 파일 하나에서 테스트 파일마다 실행한 줄. by의 값은 그 줄을 실행한 테스트 파일들이고 ""는
49
+ 테스트가 아니라 모듈을 불러올 때(수집) 실행된 것이다."""
50
+
51
+ measured: frozenset[int]
52
+ by: Mapping[int, frozenset[str]]
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Suite:
57
+ """샌드박스에서 pytest를 한 번 돈 결과 중 판단에 쓰는 것. outcomes와 counts는 테스트 파일마다,
58
+ lines는 대상 위반이 있는 소스 파일마다다."""
59
+
60
+ run: PytestRun
61
+ outcomes: Mapping[str, Outcome]
62
+ counts: Mapping[str, int]
63
+ lines: Mapping[str, FileLines]
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class GeneratedTest:
68
+ """만든 테스트 파일 하나의 기록 (7.9). covers는 고치기 전 코드에서 이 파일이 실행한 대상
69
+ 위반 id다. 파이프라인이 실행으로 정하고, 모델이 무엇을 위해 썼다고 말한 것은 쓰지 않는다."""
70
+
71
+ file: str
72
+ lines: int
73
+ before: Outcome
74
+ covers: tuple[str, ...] = ()
75
+ new_lines: int = 0 # 있던 테스트와 앞서 받아들인 테스트가 실행하지 않던 줄 수
76
+ after: Outcome | None = None # 고친 뒤. 고치기 전에 떨어졌으면 None
77
+ rejected: Rejection | None = None
78
+
79
+ @property
80
+ def accepted(self) -> bool:
81
+ return self.rejected is None
82
+
83
+
84
+ LineStatus = Literal["existing", "generated", "none", "unknown"]
85
+ # 고친 위반마다의 표시 (4.9). "이 줄을 실행하는 테스트가 없음"은 "테스트 자체가 없다"로 읽혀 지웠다
86
+ LINE_LABEL: Final[Mapping[str, str]] = {
87
+ "existing": "있던 테스트가 실행함",
88
+ "generated": "만든 테스트가 실행함",
89
+ "none": "있던 테스트도 만든 테스트도 이 줄을 실행하지 않음",
90
+ "unknown": "테스트가 이 줄을 실행하는지 알 수 없음",
91
+ }
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class LineRun:
96
+ """대상 위반 하나의 실행 상태. why는 어느 테스트도 실행하지 않는 줄에 모델이 적은 까닭이다."""
97
+
98
+ violation_id: str
99
+ status: LineStatus
100
+ why: str = ""
101
+
102
+
103
+ STATE_TYPES: Final = (
104
+ ("app.worker.generated_tests_pure", "GeneratedTest"),
105
+ ("app.worker.generated_tests_pure", "LineRun"),
106
+ )
107
+
108
+
109
+ # --- 결과 파일 읽기 (파일은 python.py가 읽어 넘긴다) ---
110
+
111
+
112
+ def file_of_test(context: str) -> str:
113
+ """pytest-cov의 테스트 문맥(`tests/test_a.py::TestX::test_y|run`)에서 테스트 파일."""
114
+ return context.split("::", 1)[0].split("|", 1)[0]
115
+
116
+
117
+ def parse_report(data: object) -> tuple[dict[str, Outcome], dict[str, int]]:
118
+ """pytest-json-report의 report.json에서 테스트 파일마다 (결과, 테스트 수). 하나라도 실패·오류면
119
+ 실패다. 수집에 실패한 파일은 테스트가 0개이고 실패다. 모양이 틀린 항목은 건너뛴다."""
120
+ outcomes: dict[str, Outcome] = {}
121
+ counts: dict[str, int] = {}
122
+ if not isinstance(data, dict):
123
+ return outcomes, counts
124
+ for test in data.get("tests") or []:
125
+ if not isinstance(test, dict) or not isinstance(test.get("nodeid"), str):
126
+ continue
127
+ file = file_of_test(test["nodeid"])
128
+ counts[file] = counts.get(file, 0) + 1
129
+ failed = test.get("outcome") in ("failed", "error")
130
+ if failed or outcomes.get(file) == "failed":
131
+ outcomes[file] = "failed"
132
+ elif test.get("outcome") == "passed":
133
+ outcomes[file] = "passed"
134
+ else:
135
+ outcomes.setdefault(file, "not_run") # skipped 등
136
+ for collector in data.get("collectors") or []:
137
+ if isinstance(collector, dict) and collector.get("outcome") == "failed":
138
+ nodeid = collector.get("nodeid")
139
+ if isinstance(nodeid, str) and nodeid:
140
+ outcomes[file_of_test(nodeid)] = "failed"
141
+ return outcomes, counts
142
+
143
+
144
+ def parse_contexts(data: bytes, files: Iterable[str]) -> dict[str, FileLines] | None:
145
+ """coverage.py JSON 보고서(`show_contexts`)에서 files의 줄마다 실행한 테스트 파일.
146
+ 깨졌으면 None."""
147
+ try:
148
+ report = json.loads(data)
149
+ except (ValueError, UnicodeDecodeError, RecursionError):
150
+ return None
151
+ entries = report.get("files") if isinstance(report, dict) else None
152
+ if not isinstance(entries, dict):
153
+ return None
154
+ out: dict[str, FileLines] = {}
155
+ for file in files:
156
+ entry = entries.get(file)
157
+ if not isinstance(entry, dict):
158
+ continue
159
+ try:
160
+ measured = frozenset(
161
+ int(n) for n in [*entry.get("executed_lines", []), *entry.get("missing_lines", [])]
162
+ )
163
+ by = {
164
+ int(line): frozenset(file_of_test(c) if c else "" for c in contexts)
165
+ for line, contexts in (entry.get("contexts") or {}).items()
166
+ }
167
+ except (TypeError, ValueError, AttributeError):
168
+ return None
169
+ out[file] = FileLines(measured, by)
170
+ return out
171
+
172
+
173
+ # --- 받아들이는 조건 (4.8의 6번) ---
174
+
175
+
176
+ def _is_test_function(node: ast.AST) -> bool:
177
+ return isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) and node.name.startswith("test")
178
+
179
+
180
+ def _checks_something(func: ast.AST) -> bool:
181
+ for node in ast.walk(func):
182
+ if isinstance(node, ast.Assert):
183
+ return True
184
+ if isinstance(node, ast.Call):
185
+ name = getattr(node.func, "attr", getattr(node.func, "id", ""))
186
+ if name in ("raises", "warns") or name.startswith("assert"):
187
+ return True
188
+ return False
189
+
190
+
191
+ def has_checks(source: str) -> bool:
192
+ """테스트 함수가 하나 이상이고 모두 assert, `pytest.raises`·`warns`, `assert*` 호출 중 하나를
193
+ 가진다. 프로그램이 볼 수 있는 최소 조건이고 테스트의 질을 보지는 않는다 (BACKLOG)."""
194
+ try:
195
+ tree = ast.parse(source)
196
+ except (SyntaxError, ValueError, RecursionError, MemoryError):
197
+ return False
198
+ funcs = [n for n in tree.body if _is_test_function(n)]
199
+ funcs += [
200
+ m for n in tree.body if isinstance(n, ast.ClassDef) and n.name.startswith("Test")
201
+ for m in n.body if _is_test_function(m)
202
+ ] # fmt: skip
203
+ return bool(funcs) and all(_checks_something(f) for f in funcs)
204
+
205
+
206
+ def _own_lines(lines: FileLines | None, test: str) -> frozenset[int]:
207
+ if lines is None:
208
+ return frozenset()
209
+ return frozenset(n for n, by in lines.by.items() if test in by)
210
+
211
+
212
+ def _executes(v: Violation, test: str, suite: Suite, sources: Mapping[str, str]) -> bool:
213
+ """고치기 전 코드에서 test가 위반 v의 줄을 실행했는지. 모듈을 불러올 때 실행된 줄("")은 test가
214
+ 그 파일의 다른 줄을 실행했고 있던 테스트가 그 줄을 실행하지 않았을 때만 test의 것으로 본다."""
215
+ lines = suite.lines.get(v.file)
216
+ own = _own_lines(lines, test)
217
+ if lines is None or not own:
218
+ return False
219
+ on_import = frozenset(n for n, by in lines.by.items() if "" in by)
220
+ executed = own | (on_import if v.covered is not True else frozenset())
221
+ source = sources.get(v.file)
222
+ stmts = statements(source) if source is not None else None
223
+ return line_covered(FileCoverage(lines.measured, executed), v.line, stmts)
224
+
225
+
226
+ @dataclass(frozen=True)
227
+ class Candidate:
228
+ file: str
229
+ source: str
230
+
231
+
232
+ def judge_tests(
233
+ candidates: Sequence[Candidate],
234
+ targets: Sequence[Violation],
235
+ before: Suite,
236
+ sources: Mapping[str, str],
237
+ *,
238
+ kept: Sequence[str] = (),
239
+ ) -> tuple[GeneratedTest, ...]:
240
+ """고치기 전 코드에 만든 테스트를 얹어 돈 결과로 파일마다 받아들일지 정한다.
241
+
242
+ sources는 대상 위반이 있는 파일의 고치기 전 소스다. kept는 앞 회차에 받아들인 테스트 파일이다.
243
+ 그 파일을 먼저, 나머지는 이름순으로 본다. 앞에서 받아들인 테스트가 실행한 줄만 다시 실행하는
244
+ 테스트는 받지 않는다(회차를 넘어 겹치지 않는다). 고친 뒤의 결과(after)는 `after_problem`이 본다.
245
+ """
246
+ order = sorted(candidates, key=lambda c: (c.file not in kept, c.file))
247
+ generated = {c.file for c in candidates}
248
+ tested = set(before.counts) | set(before.outcomes)
249
+ existing: set[tuple[str, int]] = set()
250
+ for file, lines in before.lines.items():
251
+ for test in {t for by in lines.by.values() for t in by if t and t not in generated}:
252
+ existing |= {(file, n) for n in _own_lines(lines, test)}
253
+ taken: set[tuple[str, int]] = set()
254
+ total_lines = accepted = 0
255
+ out: list[GeneratedTest] = []
256
+ for c in order:
257
+ size = len(c.source.splitlines())
258
+ outcome: Outcome = before.outcomes.get(c.file, "not_run") if c.file in tested else "not_run"
259
+ covers = tuple(v.id for v in targets if _executes(v, c.file, before, sources))
260
+ own = {(f, n) for f, lines in before.lines.items() for n in _own_lines(lines, c.file)}
261
+ newly = own | {
262
+ (v.file, v.line) for v in targets if v.id in covers and v.covered is not True
263
+ }
264
+ fresh = newly - existing - taken
265
+ rejected: Rejection | None = None
266
+ if not has_checks(c.source):
267
+ rejected = "empty"
268
+ elif accepted >= MAX_TEST_FILES:
269
+ rejected = "too_many"
270
+ elif size > MAX_TEST_LINES or total_lines + size > MAX_TOTAL_TEST_LINES:
271
+ rejected = "too_big"
272
+ elif outcome == "not_run" or not before.counts.get(c.file):
273
+ rejected = "not_run"
274
+ elif outcome == "failed":
275
+ rejected = "fails_before"
276
+ elif not covers:
277
+ rejected = "misses_violation"
278
+ elif not fresh:
279
+ rejected = "overlaps"
280
+ if rejected is None:
281
+ accepted += 1
282
+ total_lines += size
283
+ taken |= newly
284
+ out.append(GeneratedTest(c.file, size, outcome, covers, len(fresh), rejected=rejected))
285
+ return tuple(out)
286
+
287
+
288
+ @dataclass(frozen=True)
289
+ class AfterCheck:
290
+ """고친 뒤의 결과 (4.8의 6번). broken은 고치기 전에 통과했는데 고친 뒤 실패한 만든 테스트다."""
291
+
292
+ tests: tuple[GeneratedTest, ...]
293
+ existing_ok: bool
294
+ broken: tuple[str, ...]
295
+
296
+ @property
297
+ def ok(self) -> bool:
298
+ return self.existing_ok and not self.broken
299
+
300
+
301
+ def after_check(tests: Sequence[GeneratedTest], before: PytestRun, after: Suite) -> AfterCheck:
302
+ """있던 테스트는 모두 통과하고 수정 전과 같은 수가 돌아야 한다. 받아들인 만든 테스트는 고친
303
+ 뒤에도 통과해야 한다. 고치기 전에 통과한 테스트가 고친 뒤 실패하면 수정이 동작을 바꾼 것이라,
304
+ 테스트를 빼지 않고 수정을 다시 쓰게 한다(호출하는 쪽이 회차를 넘긴다). broken이 있으면
305
+ existing_ok는 보지 않는다(만든 테스트의 실패로 전체 상태가 실패다)."""
306
+ filled = tuple(
307
+ _with_after(t, after.outcomes.get(t.file, "not_run")) if t.accepted else t for t in tests
308
+ )
309
+ broken = tuple(t.file for t in filled if t.accepted and t.after != "passed")
310
+ run, summary = after.run, after.run.summary
311
+ generated = sum(after.counts.get(t.file, 0) for t in filled if t.accepted)
312
+ existing_ok = (
313
+ run.allows_code_fix
314
+ and before.summary is not None
315
+ and summary is not None
316
+ and (run.passed_count - generated, summary.total - generated)
317
+ == (before.passed_count, before.summary.total)
318
+ )
319
+ return AfterCheck(filled, existing_ok, broken)
320
+
321
+
322
+ def _with_after(t: GeneratedTest, outcome: Outcome) -> GeneratedTest:
323
+ return GeneratedTest(t.file, t.lines, t.before, t.covers, t.new_lines, outcome, t.rejected)
324
+
325
+
326
+ def line_runs(
327
+ targets: Sequence[Violation],
328
+ tests: Sequence[GeneratedTest],
329
+ untested: Mapping[tuple[str, str], str] | None = None,
330
+ ) -> tuple[LineRun, ...]:
331
+ """대상 위반마다의 실행 상태. 있던 테스트가 실행했으면(`Violation.covered`, 수정 전 테스트 단계)
332
+ existing, 받아들인 만든 테스트가 실행했으면 generated, 그 밖은 none(커버리지를 읽지 못했으면
333
+ unknown)이다. untested는 (파일, 규칙) → 모델이 적은 까닭이다."""
334
+ covered_by_new = {vid for t in tests if t.accepted for vid in t.covers}
335
+ out = []
336
+ for v in targets:
337
+ if v.covered is True:
338
+ out.append(LineRun(v.id, "existing"))
339
+ elif v.id in covered_by_new:
340
+ out.append(LineRun(v.id, "generated"))
341
+ else:
342
+ why = (untested or {}).get((v.file, v.rule_id), "")
343
+ out.append(LineRun(v.id, "unknown" if v.covered is None else "none", why))
344
+ return tuple(out)
345
+
346
+
347
+ def group_lines(
348
+ runs: Sequence[LineRun], violations: Sequence[Violation]
349
+ ) -> list[tuple[LineStatus, str, tuple[int, ...], str]]:
350
+ """표시를 (상태, 파일, 줄 번호들, 까닭)으로 묶는다. 같은 글이 위반마다 되풀이되지 않게 한다.
351
+ 상태 순서는 LINE_LABEL의 순서, 그 안은 처음 나온 파일 순서다."""
352
+ by_id = {v.id: v for v in violations}
353
+ groups: dict[tuple[str, str, str], list[int]] = {}
354
+ for r in runs:
355
+ v = by_id.get(r.violation_id)
356
+ if v is not None:
357
+ groups.setdefault((r.status, v.file, r.why), []).append(v.line)
358
+ order = list(LINE_LABEL)
359
+ keys = sorted(groups, key=lambda k: order.index(k[0]))
360
+ return [(s, f, tuple(sorted(set(groups[(s, f, w)]))), w) for s, f, w in keys] # type: ignore[misc]
361
+
362
+
363
+ # --- 도구 결과의 글 (모델에 자료로 넘긴다) ---
364
+
365
+
366
+ def clip(text: str, limit: int = MAX_OUTPUT_CHARS) -> str:
367
+ text = text.strip()
368
+ return text if len(text) <= limit else f"… (앞 {len(text) - limit}자 생략)\n" + text[-limit:]
369
+
370
+
371
+ def _violation_lines(prefix: str, violations: Sequence[Violation]) -> list[str]:
372
+ shown = [f"- {v.file}:{v.line} 규칙 {v.rule_id}: {v.message}" for v in violations[:MAX_LISTED]]
373
+ more = len(violations) - MAX_LISTED
374
+ return [f"{prefix} {len(violations)}건", *shown, *([f"- 외 {more}건"] if more > 0 else [])]
375
+
376
+
377
+ def render_check(
378
+ left: Sequence[Violation], new: Sequence[Violation], unchecked: Sequence[str], by_model: int
379
+ ) -> str:
380
+ """규칙 검사 도구의 결과 글."""
381
+ lines = []
382
+ if unchecked:
383
+ lines += ["규칙 검사를 하지 못한 규칙:", *(f"- {u}" for u in unchecked)]
384
+ lines += _violation_lines("남은 대상 위반", left) + _violation_lines("새로 생긴 위반", new)
385
+ if by_model:
386
+ lines.append(
387
+ f"모델 판단으로 찾은 대상 위반 {by_model}건은 도구로 다시 확인할 수 없다. 이 결과는 "
388
+ "그 줄이 바뀌었는지만 본다."
389
+ )
390
+ if not (left or new or unchecked):
391
+ lines.append("남은 대상 위반과 새 위반이 없다.")
392
+ return "\n".join(lines)
393
+
394
+
395
+ def _run_line(run: PytestRun) -> str:
396
+ s = run.summary
397
+ if s is None:
398
+ return f"테스트 결과를 읽지 못함 (상태 {run.status})"
399
+ counts = f"통과 {run.passed_count}, 실패 {s.failed}, 오류 {s.errors}, 전체 {s.total}"
400
+ return f"상태 {run.status}: {counts}"
401
+
402
+
403
+ def render_before(
404
+ tests: Sequence[GeneratedTest], suite: Suite, targets: Sequence[Violation]
405
+ ) -> str:
406
+ """run_tests(code="before")의 결과 글: 고치기 전 코드에 만든 테스트를 얹어 돈 결과와, 출구
407
+ 검사가 그 테스트를 받아들일지."""
408
+ lines = [f"고치기 전 코드 + 만든 테스트: {_run_line(suite.run)}"]
409
+ if not tests:
410
+ lines.append("만든 테스트 파일이 없다. 새 테스트 파일은 정한 자리에만 만든다.")
411
+ by_id = {v.id: v for v in targets}
412
+ for t in tests:
413
+ state = "받아들임" if t.rejected is None else f"받지 않음 ({REJECTION_LABEL[t.rejected]})"
414
+ where = ", ".join(f"{by_id[i].file}:{by_id[i].line}" for i in t.covers if i in by_id)
415
+ lines.append(
416
+ f"- {t.file}: {state}. 고치기 전 {t.before}, 실행한 대상 위반 {len(t.covers)}건"
417
+ + (f" ({where})" if where else "")
418
+ + f", 새로 실행한 줄 {t.new_lines}줄"
419
+ )
420
+ left = [v for v in targets if v.covered is not True
421
+ and not any(v.id in t.covers for t in tests if t.accepted)] # fmt: skip
422
+ if left:
423
+ lines += _violation_lines("있던 테스트도 받아들인 테스트도 실행하지 않는 대상 위반", left)
424
+ failed = suite.run.summary.failed_tests if suite.run.summary else ()
425
+ if failed:
426
+ lines += ["실패한 테스트:", *(f"- {n}" for n in failed[:MAX_LISTED])]
427
+ if suite.run.status != "passed" and suite.run.output:
428
+ lines += ["pytest 출력 (끝 부분):", clip(suite.run.output)]
429
+ return "\n".join(lines)
430
+
431
+
432
+ def render_now(suite: Suite, generated: Sequence[str]) -> str:
433
+ """run_tests(code="now")의 결과 글: 지금 파일 상태로 모든 테스트를 돈 결과."""
434
+ lines = [f"지금 코드 + 모든 테스트: {_run_line(suite.run)}"]
435
+ for file in generated:
436
+ lines.append(f"- 만든 테스트 {file}: {suite.outcomes.get(file, 'not_run')}")
437
+ failed = suite.run.summary.failed_tests if suite.run.summary else ()
438
+ if failed:
439
+ lines += ["실패한 테스트:", *(f"- {n}" for n in failed[:MAX_LISTED])]
440
+ if suite.run.status != "passed" and suite.run.output:
441
+ lines += ["pytest 출력 (끝 부분):", clip(suite.run.output)]
442
+ return "\n".join(lines)