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,214 @@
1
+ """기계적 수정 묶음 (docs/DESIGN.md 4.7 기계적 수정, 4.8, 3.1의 C7): 도구 자신의 수정을 적용하고
2
+ 다른 수정과 같이 결정적으로 검증한다. 모델을 부르지 않는다.
3
+
4
+ - 수정 판단(4.6)이 `fix`·`mechanical`로 정한 위반만 고친다. ruff의 안전한 수정 중 그 위반의 편집만
5
+ 적용한다. `ruff check --fix`는 PR이 건드리지 않은 줄까지 고치므로 쓰지 않는다. 편집이 겹치면 한
6
+ 회차에 하나만 적용하고 ruff를 다시 돌려 최대 5회 반복한다.
7
+ - `ruff format`은 base가 `ruff format --check`를 통과하는 저장소에서만, 고친 파일에 적용한다.
8
+ - 검증은 4.8의 순서다: 허용 범위(고친 파일의 수정만), 비밀값, 규칙 재검사(도구·검사기로 확인하는
9
+ 모든 규칙, 새 위반 없음), 테스트 결과 동일, 크기 상한. 통과한 패치는 `fix_attempts`에 저장하고
10
+ 전달은 그 패치만 올린다.
11
+ """
12
+
13
+ import json
14
+ import logging
15
+ from collections.abc import Callable, Collection, Sequence
16
+ from dataclasses import replace
17
+ from pathlib import Path
18
+ from typing import Final
19
+
20
+ from app.shared.db_pure import FixAttempt
21
+ from app.shared.job_pure import PRJob
22
+ from app.worker import records_pure, repo
23
+ from app.worker.checker_authoring_pure import Checked, RuleCheck
24
+ from app.worker.diff_pure import added_lines_except_moved, added_texts, new_files
25
+ from app.worker.doc_rules_pure import Found
26
+ from app.worker.fix import model_fix_pure, scope
27
+ from app.worker.fix.fix_decision_pure import FixDecision
28
+ from app.worker.fix.fix_pure import (
29
+ MECHANICAL_BUNDLE,
30
+ MechanicalFix,
31
+ MechanicalStatus,
32
+ same_test_result,
33
+ )
34
+ from app.worker.fix.model_fix import file_hashes
35
+ from app.worker.fix.model_fix_pure import Picked
36
+ from app.worker.fix.proposal_pure import SECRET_BLOCKED, changed_line_count, find_secret
37
+ from app.worker.fix.scope_pure import MECHANICAL_POLICY, is_pipeline_output, parse_porcelain
38
+ from app.worker.lang import python
39
+ from app.worker.report import format_test_line
40
+ from app.worker.rules import detect
41
+ from app.worker.rules.checkers import FormatsFiles
42
+ from app.worker.state import Store
43
+ from app.worker.test_run_pure import PytestRun
44
+ from app.worker.text_edit_pure import TextEdit, apply_edits
45
+ from app.worker.violation_pure import Violation
46
+
47
+ log = logging.getLogger(__name__)
48
+
49
+ # 겹치는 수정은 한 회차에 하나만 적용하고 다음 회차에 다시 돌린다 (ruff --fix와 같은 방식)
50
+ MAX_ROUNDS: Final = 5
51
+ BASE_NOT_FORMATTED: Final = "base 브랜치가 ruff format을 따르지 않음"
52
+
53
+
54
+ def pick_targets(violations: Sequence[Violation], decisions: Sequence[FixDecision]) -> Picked:
55
+ """기계적 수정 대상: 수정 판단이 `fix`·`mechanical`로 정한 줄 단위 위반. 크기 상한은 검증의
56
+ 7번이 본다."""
57
+ fix = {d.violation_id for d in decisions if d.action == "fix" and d.method == "mechanical"}
58
+ return Picked(tuple(v for v in violations if v.id in fix and v.unit == "line"), ())
59
+
60
+
61
+ def fix_violations(
62
+ found: Found,
63
+ picked: Picked,
64
+ *,
65
+ worktree: Path,
66
+ merge_base: str,
67
+ base_sha: str,
68
+ test_before: PytestRun,
69
+ checks: Sequence[RuleCheck],
70
+ sandbox: FormatsFiles,
71
+ run_tests: Callable[[], PytestRun],
72
+ is_stale: Callable[[], bool],
73
+ secrets: Sequence[str],
74
+ disabled: Collection[str] = (),
75
+ max_rounds: int = MAX_ROUNDS,
76
+ ) -> MechanicalFix | None:
77
+ """picked.targets를 도구의 수정으로 고치고 검증한다. 새 커밋이 와서 중단되면 None.
78
+
79
+ checks는 수정 전 위반을 찾은 규칙의 확인 방법 전부다(`doc_rules.saved_checks`). 재검사가 모두
80
+ 다시 돌린다.
81
+ """
82
+ targets = picked.targets
83
+ wanted = {v.id for v in targets}
84
+ allowed = sorted({v.file for v in targets})
85
+ ruff_checks = [c for c in checks if isinstance(c, Checked) and c.checker.kind == "ruff"]
86
+ ignored_before = scope.snapshot_ignored(worktree)
87
+
88
+ def outcome(status: MechanicalStatus, detail: str = "", **more) -> MechanicalFix:
89
+ return MechanicalFix(status=status, targets=tuple(sorted(wanted)), detail=detail, **more)
90
+
91
+ # 수정 전 PR이 추가한 줄. 정렬 같은 수정이 자리만 옮긴 base의 줄은 PR의 줄로 다시 세지 않는다
92
+ pr_added = added_texts(repo.working_diff(worktree, merge_base))
93
+
94
+ def recheck(chosen: Sequence[RuleCheck]) -> detect.Detection:
95
+ diff = repo.working_diff(worktree, merge_base)
96
+ return detect.detect(
97
+ chosen, worktree, added_lines_except_moved(diff, pr_added),
98
+ new_files=new_files(diff), sandbox=sandbox, disabled=disabled,
99
+ ) # fmt: skip
100
+
101
+ touched: set[str] = set()
102
+ for _ in range(max_rounds):
103
+ found_now = recheck(ruff_checks)
104
+ groups = {}
105
+ for v in found_now.violations:
106
+ if v.id in wanted and v.id in found_now.edits:
107
+ groups.setdefault(v.file, []).append(found_now.edits[v.id])
108
+ if not groups or not _apply(worktree, groups, touched):
109
+ break
110
+ formatted: list[str] = []
111
+ format_skipped = ""
112
+ format_files = sorted(touched | {v.file for v in targets if v.code == python.FORMAT_CODE})
113
+ if format_files:
114
+ with repo.side_worktree(worktree, base_sha) as base_tree:
115
+ base_ok = sandbox.format_check(base_tree)
116
+ if base_ok is True:
117
+ before = {f: _read(worktree, f) for f in format_files}
118
+ done = sandbox.format_apply(worktree, format_files)
119
+ if done is True:
120
+ formatted = [f for f in format_files if _read(worktree, f) != before[f]]
121
+ else:
122
+ format_skipped = str(done)
123
+ else:
124
+ format_skipped = BASE_NOT_FORMATTED if base_ok is False else base_ok
125
+ if not touched and not formatted:
126
+ return outcome("nothing_fixed", format_skipped=format_skipped)
127
+ changed_files = tuple(sorted(touched | set(formatted)))
128
+ common = {"changed_files": changed_files, "formatted_files": tuple(formatted),
129
+ "format_skipped": format_skipped} # fmt: skip
130
+
131
+ checked = scope.check_scope(worktree, set(allowed), ignored_before, policy=MECHANICAL_POLICY)
132
+ if not checked.ok:
133
+ return outcome("out_of_scope", checked.detail, **common)
134
+ patch = repo.head_diff(worktree)
135
+ kind = find_secret(patch, secrets)
136
+ if kind is not None:
137
+ return outcome("secret", f"{SECRET_BLOCKED} ({kind})", **common)
138
+ after = recheck(checks)
139
+ if after.unchecked:
140
+ what = "; ".join(f"{u.rule.id}: {u.detail}" for u in after.unchecked)
141
+ return outcome("unchecked", what, **common)
142
+ left, new = model_fix_pure.recheck(found.violations, targets, after.violations)
143
+ if new:
144
+ detail = ", ".join(f"{v.file}:{v.line} {v.rule_id}" for v in new[:10])
145
+ return outcome("new_violations", detail, **common)
146
+ if is_stale():
147
+ return None
148
+ run = run_tests()
149
+ if run.cancelled:
150
+ return None
151
+ if not same_test_result(test_before, run):
152
+ return outcome("tests_changed", format_test_line(run), **common)
153
+ entries = [e for e in parse_porcelain(repo.status(worktree)) if not is_pipeline_output(e.path)]
154
+ too_big = model_fix_pure.size_problem(len(entries), changed_line_count(patch))
155
+ if too_big is not None:
156
+ return outcome("too_big", too_big, **common)
157
+ left_ids = {v.id for v in left}
158
+ return outcome(
159
+ "ready",
160
+ fixed=tuple(sorted(wanted - left_ids)),
161
+ remaining=tuple(sorted(left_ids)),
162
+ tests=run.passed_count,
163
+ test_line=format_test_line(run),
164
+ **common,
165
+ )
166
+
167
+
168
+ def _apply(worktree: Path, groups: dict[str, list[tuple[TextEdit, ...]]], touched: set[str]) -> int:
169
+ """파일마다 편집을 적용한다. 적용한 편집 묶음 수."""
170
+ applied = 0
171
+ for file, edits in groups.items():
172
+ path = repo.worktree_file(worktree, file)
173
+ if path is None: # 쓰기 직전에 링크·밖을 가리키는 경로가 아닌지 다시 본다
174
+ continue
175
+ # newline=""로 읽고 써서 CRLF 같은 줄바꿈을 그대로 둔다
176
+ with path.open(encoding="utf-8", newline="") as f:
177
+ text = f.read()
178
+ new_text, count = apply_edits(text, edits)
179
+ if count and new_text != text:
180
+ with path.open("w", encoding="utf-8", newline="") as f:
181
+ f.write(new_text)
182
+ applied += count
183
+ touched.add(file)
184
+ return applied
185
+
186
+
187
+ def _read(worktree: Path, rel: str) -> bytes:
188
+ path = repo.worktree_file(worktree, rel)
189
+ return path.read_bytes() if path is not None else b""
190
+
191
+
192
+ def save_attempt(
193
+ store: Store,
194
+ job: PRJob,
195
+ merge_base: str,
196
+ fix: MechanicalFix,
197
+ notes: Sequence[records_pure.Target],
198
+ worktree: Path,
199
+ ) -> MechanicalFix:
200
+ """시도 결과를 `fix_attempts`에 저장하고 그 id를 붙인다. 통과했으면 패치와 바뀐 파일의 해시도
201
+ 남긴다. 전달은 이 패치만 올린다 (4.8 끝)."""
202
+ ready = fix.ready
203
+ attempt_id = store.save_fix_attempt(
204
+ FixAttempt(
205
+ repo=job.repo, pr_number=job.pr_number, head_sha=job.head_sha, merge_base=merge_base,
206
+ bundle=MECHANICAL_BUNDLE, status=fix.status, attempts=1, models_json="[]",
207
+ detail=fix.detail, targets_json=records_pure.targets_to_json(notes),
208
+ patch=repo.head_diff(worktree) if ready else None,
209
+ file_hashes_json=(
210
+ json.dumps(file_hashes(worktree, fix.changed_files)) if ready else None
211
+ ),
212
+ )
213
+ ) # fmt: skip
214
+ return replace(fix, attempt_id=attempt_id)