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,223 @@
1
+ """규칙과 규칙 묶음 (docs/DESIGN.md 7.1). 데이터와 id 계산만 한다.
2
+
3
+ 규칙 읽기(4.3) 직후의 `check`와 `fix`는 모델이 준 힌트다. 검사 방법 정하기(4.4)가 확정한다.
4
+ """
5
+
6
+ import hashlib
7
+ import re
8
+ import unicodedata
9
+ from collections.abc import Mapping, Sequence
10
+ from dataclasses import dataclass, field, replace
11
+ from pathlib import PurePosixPath
12
+ from typing import Final, Literal
13
+
14
+ from pydantic import TypeAdapter
15
+
16
+ # 인용 확인과 규칙 id에서 무시하는 마크다운 강조 기호. 모델이 `print`를 print로 옮겨도 같은 문장이다
17
+ _EMPHASIS: Final = re.compile(r"[`*]")
18
+ _SPACE: Final = re.compile(r"\s+")
19
+ _NOT_ALNUM: Final = re.compile(r"[^a-z0-9]+")
20
+ # 내용을 보는 검사기(ast-grep, Python AST)의 검사 대상 (7.7 Python 프로필)
21
+ PYTHON_SUFFIXES: Final = (".py", ".pyi")
22
+
23
+ # 규칙을 무엇을 보고 확인하는지 (4.3). code: 바뀐 코드 줄(실행 결과·생성물에 대한 규칙이면 그것을
24
+ # 만드는 코드). pr: PR 자체(커밋 메시지, 제목·본문, 브랜치 이름, 바뀐 파일의 종류). run:
25
+ # 파이프라인이 이미 돌리는 테스트·정적 검사의 결과
26
+ Target = Literal["code", "pr", "run"]
27
+ # run 규칙이 말하는 실행 결과: tests는 샌드박스 테스트, lint는 도구 설정의 규칙 묶음(ruff)이다
28
+ RunPart = Literal["tests", "lint"]
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class RuleSource:
33
+ file: str # "CONTRIBUTING.md", "pyproject.toml"
34
+ section: str # 문서의 제목 경로. 예: "코드 스타일 > 상수". 문서 맨 위 제목은 넣지 않는다
35
+ blob_sha: str # 읽은 파일의 git blob 해시
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class CheckMethod:
40
+ # path는 규칙 읽기의 힌트다: 파일의 이름·경로만 보고 가리는 규칙이라 경로 패턴 검사기를 쓴다
41
+ kind: Literal["tool", "checker", "path", "model", "none"]
42
+ tool: str = "" # "ruff", "ruff-format"
43
+ params: Mapping[str, object] = field(default_factory=dict) # 예: {"codes": ["N802"]}
44
+ checker_id: str = ""
45
+ reason: str = "" # none·model로 정한 이유
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Example:
50
+ code: str
51
+ expect_lines: tuple[int, ...] # 위반 예시면 잡혀야 할 줄(1부터), 정상 예시면 빈 튜플
52
+ written_by: Literal["document", "model"]
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Rule:
57
+ id: str # 문서 규칙: R-<파일 약칭>-<원문 해시 8자>. 도구 규칙: 도구의 코드
58
+ text: str # 원문 인용 (출처 문서의 그 절에 있음을 확인한 것)
59
+ source: RuleSource
60
+ origin: Literal["document", "tool_config"]
61
+ scope: tuple[str, ...] # 적용 범위 glob. 비면 저장소 전체
62
+ check: CheckMethod
63
+ fix: Literal["mechanical", "model", "none"]
64
+ examples: tuple[Example, ...] = ()
65
+ # 문서가 범위를 밝히지 않은 규칙에서 모델이 뺀 경로 glob과 그 이유 (4.3). 좁히기만 한다:
66
+ # 빼는 목록이라 범위를 넓힐 수 없다. 문서가 범위를 밝힌 규칙에는 비어 있다
67
+ exclude: tuple[str, ...] = ()
68
+ exclude_reason: str = ""
69
+ # 효과 확인(`checked_exclude`)이 이 PR의 base 파일 목록에 맞춰 보고 버린 추정. 코멘트에 보인다
70
+ exclude_dropped: str = ""
71
+ # 확인 대상. 모델이 고른다. code는 도구·검사기·모델 판단, pr은 PR 단위 확인, run은 테스트와
72
+ # 정적 검사의 결과로 답한다
73
+ target: Target = "code"
74
+ runs: tuple[RunPart, ...] = () # target이 run일 때 규칙이 말하는 실행 결과
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class UnreadDoc:
79
+ path: str
80
+ reason: str
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class DroppedRule:
85
+ """모델이 답했지만 원문 확인에서 버린 규칙. 코멘트와 로그에 보인다."""
86
+
87
+ file: str
88
+ section: str
89
+ quote: str
90
+ reason: str
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class RuleSet:
95
+ rules: tuple[Rule, ...]
96
+ sources: tuple[tuple[str, str], ...] # 읽은 문서의 (경로, blob 해시)
97
+ pipeline_version: str # 문서 고르기와 원문 확인의 버전 (app/worker/rule_reading_pure.py)
98
+ prompt_version: str
99
+ model: str # 답한 모델의 전체 id
100
+ unread: tuple[UnreadDoc, ...] = ()
101
+ dropped: tuple[DroppedRule, ...] = ()
102
+
103
+ def to_json(self) -> str:
104
+ return _RULESET.dump_json(self).decode()
105
+
106
+ @classmethod
107
+ def from_json(cls, text: str) -> "RuleSet":
108
+ return _RULESET.validate_json(text)
109
+
110
+
111
+ _RULESET: Final = TypeAdapter(RuleSet)
112
+
113
+
114
+ def normalize(text: str) -> str:
115
+ """인용 확인과 규칙 id에 쓰는 형태. 공백을 하나로 모으고 강조 기호(`, *)를 뺀다."""
116
+ text = unicodedata.normalize("NFC", text)
117
+ return _SPACE.sub(" ", _EMPHASIS.sub("", text)).strip()
118
+
119
+
120
+ def rule_id(doc_path: str, quote: str) -> str:
121
+ """`R-<파일 약칭>-<정리한 원문의 해시 앞 8자>`. 문서의 다른 부분이 바뀌어도 그대로다."""
122
+ stem = _NOT_ALNUM.sub("-", PurePosixPath(doc_path).stem.lower()).strip("-") or "doc"
123
+ digest = hashlib.sha256(normalize(quote).encode()).hexdigest()[:8]
124
+ return f"R-{stem}-{digest}"
125
+
126
+
127
+ def applies_to(rule: Rule, path: str) -> bool:
128
+ """규칙이 path(저장소 기준)에 적용되는지: 적용 범위 안이고 추정으로 뺀 경로가 아니다."""
129
+ return in_scope(rule.scope, path) and not (rule.exclude and in_scope(rule.exclude, path))
130
+
131
+
132
+ def looks_at_paths(rule: Rule) -> bool:
133
+ """파일의 내용이 아니라 이름·경로를 보는 규칙인지 (경로 패턴 검사기)."""
134
+ return rule.check.kind == "path"
135
+
136
+
137
+ def checked_file(rule: Rule, path: str) -> bool:
138
+ """규칙의 검사 대상 파일인지. 경로 규칙은 모든 파일, 그 밖은 Python 파일이다 (7.7)."""
139
+ return applies_to(rule, path) and (looks_at_paths(rule) or path.endswith(PYTHON_SUFFIXES))
140
+
141
+
142
+ def starts_with_a_folder(pattern: str) -> bool:
143
+ """첫 마디가 글자 그대로의 폴더 이름인지. `**`나 `*.py`처럼 저장소 전체를 뺄 수 있는 glob이
144
+ 아니다."""
145
+ first, _, rest = pattern.partition("/")
146
+ return bool(rest) and not (set("*?[") & set(first))
147
+
148
+
149
+ def checked_exclude(rule: Rule, base_files: Sequence[str]) -> Rule:
150
+ """추정으로 뺀 경로의 효과 확인 (4.3). base 커밋의 파일 목록에 맞춰 보고 너무 많이 빼는 glob을
151
+ 버린다.
152
+
153
+ 규칙이 적용되는 파일(적용 범위 안의 검사 대상 파일)의 절반 이상을 빼는 glob은 버린다. 남은
154
+ glob을 합쳐 절반 이상을 빼면 모두 버린다. 적용되는 파일이 base에 없어 잴 수 없으면 첫 마디가
155
+ 폴더 이름인 glob만 받는다. 버리면 범위가 넓은 쪽으로 남고, 버린 사실은 `exclude_dropped`에
156
+ 남는다.
157
+ """
158
+ if not rule.exclude:
159
+ return rule
160
+ bare = replace(rule, exclude=(), exclude_reason="")
161
+ applicable = [f for f in base_files if checked_file(bare, f)]
162
+ total = len(applicable)
163
+ kept, dropped = [], []
164
+ for glob in rule.exclude:
165
+ removed = sum(1 for f in applicable if in_scope((glob,), f))
166
+ if total == 0:
167
+ if starts_with_a_folder(glob):
168
+ kept.append(glob)
169
+ else:
170
+ dropped.append(f"{glob}: 적용되는 파일이 base에 없어 효과를 잴 수 없음")
171
+ elif removed * 2 >= total:
172
+ dropped.append(f"{glob}: 적용되는 파일 {total}개 중 {removed}개를 뺌")
173
+ else:
174
+ kept.append(glob)
175
+ if kept and total:
176
+ removed = sum(1 for f in applicable if in_scope(tuple(kept), f))
177
+ if removed * 2 >= total:
178
+ dropped.append(f"{', '.join(kept)}: 합쳐서 적용되는 파일 {total}개 중 {removed}개를 뺌")
179
+ kept = []
180
+ if not dropped:
181
+ return rule
182
+ return replace(
183
+ rule,
184
+ exclude=tuple(kept),
185
+ exclude_reason=rule.exclude_reason if kept else "",
186
+ exclude_dropped="; ".join(dropped),
187
+ )
188
+
189
+
190
+ def in_scope(scope: tuple[str, ...], path: str) -> bool:
191
+ """path(저장소 기준)가 규칙의 적용 범위 glob 중 하나에 드는지. 범위가 비면 저장소 전체다.
192
+
193
+ `**`는 폴더 여러 단계, `*`·`?`는 한 단계 안에서만 맞춘다 (`orders/*.py`는 `orders/a/b.py`를
194
+ 담지 않는다). `orders/**`는 `orders` 아래 모든 파일이다.
195
+ """
196
+ return not scope or any(_glob_regex(pattern).fullmatch(path) for pattern in scope)
197
+
198
+
199
+ def _glob_regex(pattern: str) -> re.Pattern[str]:
200
+ out, i = [], 0
201
+ while i < len(pattern):
202
+ if pattern.startswith("**/", i):
203
+ out.append("(?:.*/)?")
204
+ i += 3
205
+ elif pattern.startswith("**", i):
206
+ out.append(".*")
207
+ i += 2
208
+ elif pattern[i] == "*":
209
+ out.append("[^/]*")
210
+ i += 1
211
+ elif pattern[i] == "?":
212
+ out.append("[^/]")
213
+ i += 1
214
+ elif pattern[i] == "[" and (end := pattern.find("]", i + 1)) > i + 1:
215
+ body = pattern[i + 1 : end]
216
+ negate = body.startswith("!")
217
+ body = (body[1:] if negate else body).replace("^", r"\^")
218
+ out.append(f"[{'^' if negate else ''}{body}]")
219
+ i = end + 1
220
+ else:
221
+ out.append(re.escape(pattern[i]))
222
+ i += 1
223
+ return re.compile("".join(out))