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.
- package/LICENSE +21 -0
- package/Procfile +2 -0
- package/README.md +300 -2
- package/app/__init__.py +1 -0
- package/app/api/__init__.py +1 -0
- package/app/api/cli.py +35 -0
- package/app/api/github.py +168 -0
- package/app/api/history.py +123 -0
- package/app/api/main.py +95 -0
- package/app/api/queue.py +45 -0
- package/app/api/responses.py +28 -0
- package/app/api/signature.py +19 -0
- package/app/api/sync.py +189 -0
- package/app/api/sync_rules_pure.py +71 -0
- package/app/api/webhook.py +166 -0
- package/app/setup/__init__.py +4 -0
- package/app/setup/cli.py +90 -0
- package/app/setup/configure.py +720 -0
- package/app/setup/files.py +93 -0
- package/app/setup/github_setup.py +149 -0
- package/app/setup/install_hints.json +32 -0
- package/app/setup/setup_pure.py +312 -0
- package/app/setup/start.py +113 -0
- package/app/shared/__init__.py +1 -0
- package/app/shared/comment_pure.py +29 -0
- package/app/shared/config.py +106 -0
- package/app/shared/db_pure.py +339 -0
- package/app/shared/embed_models_pure.py +55 -0
- package/app/shared/feedback_pure.py +84 -0
- package/app/shared/github_auth.py +74 -0
- package/app/shared/job_pure.py +43 -0
- package/app/shared/notify.py +97 -0
- package/app/shared/ops_alert_pure.py +38 -0
- package/app/shared/state_keys_pure.py +24 -0
- package/app/shared/version.py +27 -0
- package/app/worker/__init__.py +1 -0
- package/app/worker/access_pure.py +180 -0
- package/app/worker/ai/__init__.py +1 -0
- package/app/worker/ai/claude_cli.py +684 -0
- package/app/worker/ai/mcp_relay.py +42 -0
- package/app/worker/ai/path_hook.py +103 -0
- package/app/worker/ai/tool_server.py +139 -0
- package/app/worker/ai/workdir.py +333 -0
- package/app/worker/base_config.py +173 -0
- package/app/worker/budget.py +100 -0
- package/app/worker/cache_key_pure.py +34 -0
- package/app/worker/call_budget_pure.py +132 -0
- package/app/worker/checker_authoring_pure.py +599 -0
- package/app/worker/checker_pure.py +196 -0
- package/app/worker/cli.py +97 -0
- package/app/worker/command.py +191 -0
- package/app/worker/command_pure.py +38 -0
- package/app/worker/coverage.py +123 -0
- package/app/worker/coverage_pure.py +202 -0
- package/app/worker/deps.py +22 -0
- package/app/worker/diff_pure.py +419 -0
- package/app/worker/doc_rules_pure.py +201 -0
- package/app/worker/doc_rules_report.py +979 -0
- package/app/worker/eval_run_pure.py +241 -0
- package/app/worker/evaluation.py +151 -0
- package/app/worker/feedback.py +448 -0
- package/app/worker/feedback_pure.py +131 -0
- package/app/worker/feedback_report_pure.py +90 -0
- package/app/worker/feedback_triage.py +85 -0
- package/app/worker/feedback_triage_pure.py +363 -0
- package/app/worker/fix/__init__.py +1 -0
- package/app/worker/fix/decide.py +197 -0
- package/app/worker/fix/feedback_fix_pure.py +125 -0
- package/app/worker/fix/fix_decision_pure.py +386 -0
- package/app/worker/fix/fix_pure.py +70 -0
- package/app/worker/fix/mechanical_fix.py +214 -0
- package/app/worker/fix/model_fix.py +575 -0
- package/app/worker/fix/model_fix_pure.py +593 -0
- package/app/worker/fix/proposal.py +584 -0
- package/app/worker/fix/proposal_pure.py +103 -0
- package/app/worker/fix/scope.py +40 -0
- package/app/worker/fix/scope_pure.py +222 -0
- package/app/worker/generated_tests_pure.py +442 -0
- package/app/worker/github.py +471 -0
- package/app/worker/graph.py +963 -0
- package/app/worker/guard.py +91 -0
- package/app/worker/lang/__init__.py +0 -0
- package/app/worker/lang/install_pure.py +25 -0
- package/app/worker/lang/python.py +862 -0
- package/app/worker/loop.py +200 -0
- package/app/worker/main.py +76 -0
- package/app/worker/markdown_pure.py +29 -0
- package/app/worker/mcp_pure.py +150 -0
- package/app/worker/memory.py +503 -0
- package/app/worker/merged_fix_pure.py +236 -0
- package/app/worker/pr_check_report_pure.py +201 -0
- package/app/worker/pr_description_report_pure.py +112 -0
- package/app/worker/preflight.py +125 -0
- package/app/worker/rag_pure.py +285 -0
- package/app/worker/rag_switch_pure.py +203 -0
- package/app/worker/records.py +207 -0
- package/app/worker/records_pure.py +239 -0
- package/app/worker/repo.py +588 -0
- package/app/worker/repo_config_pure.py +269 -0
- package/app/worker/report.py +300 -0
- package/app/worker/retry.py +65 -0
- package/app/worker/rule_pure.py +223 -0
- package/app/worker/rule_reading_pure.py +503 -0
- package/app/worker/rules/__init__.py +1 -0
- package/app/worker/rules/checkers.py +615 -0
- package/app/worker/rules/detect.py +154 -0
- package/app/worker/rules/doc_rules.py +301 -0
- package/app/worker/rules/doc_sections_pure.py +168 -0
- package/app/worker/rules/judge.py +410 -0
- package/app/worker/rules/judge_pure.py +627 -0
- package/app/worker/rules/pr_check.py +404 -0
- package/app/worker/rules/pr_check_pure.py +922 -0
- package/app/worker/rules/pr_description.py +218 -0
- package/app/worker/rules/pr_description_pure.py +743 -0
- package/app/worker/rules/rules.py +314 -0
- package/app/worker/rules/run_check.py +95 -0
- package/app/worker/rules/run_check_pure.py +219 -0
- package/app/worker/rules/tool_choice_pure.py +135 -0
- package/app/worker/sandbox/__init__.py +1 -0
- package/app/worker/sandbox/checker_runner.py +412 -0
- package/app/worker/sandbox/container.py +130 -0
- package/app/worker/sandbox/docker_cli.py +170 -0
- package/app/worker/sandbox/safe_read.py +32 -0
- package/app/worker/sandbox/toolcache.py +425 -0
- package/app/worker/state.py +602 -0
- package/app/worker/test_lines.py +77 -0
- package/app/worker/test_run_pure.py +133 -0
- package/app/worker/text_edit_pure.py +66 -0
- package/app/worker/tools_pure.py +152 -0
- package/app/worker/update.py +305 -0
- package/app/worker/violation_pure.py +33 -0
- package/bin/pr-proof.js +173 -0
- package/docker/sandbox/Dockerfile +12 -0
- package/docker/sandbox/coveragerc +19 -0
- package/docker-compose.yml +5 -0
- package/package.json +31 -4
- package/pyproject.toml +60 -0
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
"""문서 규칙 위반의 모델 수정: 공용 틀(app/worker/loop.py)의 작성과 출구 검사 (docs/DESIGN.md 4.7,
|
|
2
|
+
4.8, 5.3 (b)).
|
|
3
|
+
|
|
4
|
+
write는 모델 전용 폴더(`workdir.run_in_model_folder`)에서 파일 도구와 파이프라인 도구 둘(규칙 검사,
|
|
5
|
+
테스트)을 준 모델을 부른다. 모델이 한 호출 안에서 테스트를 쓰고, 돌려 보고, 고치고, 다시 돌려 본다.
|
|
6
|
+
도구의 구현은 아래 verify가 쓰는 것과 같은 함수다(`check_now`, `judge_before`, `tools.run_suite`).
|
|
7
|
+
지시는 시스템 프롬프트로, 규칙 원문과 위반 목록은 사용자 메시지의 자료로 넘긴다. 회차가 적용한
|
|
8
|
+
diff와 마지막 답(설명 JSON)은 `model_cache`에 저장하고, 같은 입력이면 모델을 다시 부르지 않고
|
|
9
|
+
저장한 diff를 적용한다. 호출은 PR 상한(9.2)에서 센다.
|
|
10
|
+
|
|
11
|
+
verify는 올리기 직전의 출구 검사다. 모델이 도구 결과를 잘못 전하거나 PR 코드에 심어진 글에 속을 수
|
|
12
|
+
있어 같은 검사를 프로그램이 한 번 더 돌린다. 4.8의 순서대로 하고 앞에서 떨어지면 뒤는 하지 않는다:
|
|
13
|
+
허용 범위, 비밀값(여기까지 떨어지면 재시도 없이 버림), 설명 JSON, 규칙 재검사, 만든 테스트,
|
|
14
|
+
테스트, 크기 상한(여기는 이유를 다음 회차에 넘긴다). 조건에 맞지 않는 만든 테스트는 그 파일만 빼고
|
|
15
|
+
이어 간다. 샌드박스에서 무엇이든 돌리기 전에 앞의 둘을 끝낸다. 재검사가 읽는 base 설정은 worktree
|
|
16
|
+
밖에 있어 모델이 바꿀 수 없다 (4.8의 2번).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import ast
|
|
20
|
+
import json
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import stat
|
|
24
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
25
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Final
|
|
28
|
+
|
|
29
|
+
from app.shared.db_pure import FixAttempt
|
|
30
|
+
from app.shared.job_pure import PRJob
|
|
31
|
+
from app.worker import mcp_pure, records_pure, repo
|
|
32
|
+
from app.worker.ai.claude_cli import (
|
|
33
|
+
FIX_TOOLS_TIMEOUT_S,
|
|
34
|
+
AIEnvironmentError,
|
|
35
|
+
ClaudeResult,
|
|
36
|
+
environment_problem,
|
|
37
|
+
)
|
|
38
|
+
from app.worker.budget import CallBudget
|
|
39
|
+
from app.worker.cache_key_pure import text_hash
|
|
40
|
+
from app.worker.call_budget_pure import Denied, PrScope
|
|
41
|
+
from app.worker.diff_pure import ChangedLines, added_lines, change_blocks, new_files
|
|
42
|
+
from app.worker.doc_rules_pure import Found, outcomes_by_rule
|
|
43
|
+
from app.worker.fix import model_fix_pure, scope
|
|
44
|
+
from app.worker.fix.model_fix_pure import (
|
|
45
|
+
Explanation,
|
|
46
|
+
ModelFix,
|
|
47
|
+
Picked,
|
|
48
|
+
Target,
|
|
49
|
+
Verification,
|
|
50
|
+
Written,
|
|
51
|
+
)
|
|
52
|
+
from app.worker.fix.proposal import MODEL_BUNDLE
|
|
53
|
+
from app.worker.fix.proposal_pure import (
|
|
54
|
+
SECRET_BLOCKED,
|
|
55
|
+
changed_line_count,
|
|
56
|
+
find_secret,
|
|
57
|
+
find_secret_in_text,
|
|
58
|
+
)
|
|
59
|
+
from app.worker.fix.scope_pure import (
|
|
60
|
+
AI_POLICY,
|
|
61
|
+
generated_test_dir,
|
|
62
|
+
is_generated_test,
|
|
63
|
+
is_pipeline_output,
|
|
64
|
+
parse_porcelain,
|
|
65
|
+
)
|
|
66
|
+
from app.worker.generated_tests_pure import (
|
|
67
|
+
Candidate,
|
|
68
|
+
GeneratedTest,
|
|
69
|
+
Suite,
|
|
70
|
+
after_check,
|
|
71
|
+
judge_tests,
|
|
72
|
+
line_runs,
|
|
73
|
+
render_before,
|
|
74
|
+
render_check,
|
|
75
|
+
render_now,
|
|
76
|
+
)
|
|
77
|
+
from app.worker.lang.python import read_sources
|
|
78
|
+
from app.worker.loop import LoopPolicy, LoopState, Verdict, WriteFailed, WriteResult, build_loop
|
|
79
|
+
from app.worker.mcp_pure import ToolUsage
|
|
80
|
+
from app.worker.memory import FindsRecords
|
|
81
|
+
from app.worker.rag_pure import (
|
|
82
|
+
EMPTY,
|
|
83
|
+
Selection,
|
|
84
|
+
merge_retrievals,
|
|
85
|
+
query_text,
|
|
86
|
+
render_records,
|
|
87
|
+
retrieval,
|
|
88
|
+
)
|
|
89
|
+
from app.worker.repo_config_pure import ModelSettings
|
|
90
|
+
from app.worker.report import format_test_line
|
|
91
|
+
from app.worker.rules.detect import Detection, source_lines
|
|
92
|
+
from app.worker.sandbox.safe_read import read_regular_file
|
|
93
|
+
from app.worker.state import Store
|
|
94
|
+
from app.worker.test_run_pure import PytestRun
|
|
95
|
+
from app.worker.violation_pure import Violation
|
|
96
|
+
|
|
97
|
+
log = logging.getLogger(__name__)
|
|
98
|
+
|
|
99
|
+
MAX_FILE_BYTES: Final = 5 * 1024 * 1024
|
|
100
|
+
NOTHING_CHANGED: Final = "아무 파일도 바꾸지 않았다. 목록의 위반을 고친다."
|
|
101
|
+
# 수정 작성 호출 하나의 claude `--max-budget-usd` (9.2). 도구를 부르며 차례가 늘어 다른 단계(0.30,
|
|
102
|
+
# 0.50)보다 크게 둔다. 끝없이 도는 호출을 막을 뿐 상한 계산은 호출 수로 한다
|
|
103
|
+
FIX_CALL_BUDGET_USD: Final = {"light": 1.00, "heavy": 2.00}
|
|
104
|
+
_NEW_FILE_CODES: Final = frozenset({"??", " A"})
|
|
105
|
+
# 도구·검사기로 다시 확인하지 못하는 위반: 모델이 찾은 것, 받아들인 코멘트 (4.8의 5번, 4.11)
|
|
106
|
+
_UNCHECKED: Final = frozenset({"model", "feedback"})
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def module_constants(worktree: Path, files: Sequence[str]) -> dict[str, list[str]]:
|
|
110
|
+
"""파일마다 이미 있는 모듈 수준 상수(대문자 이름). 호스트에서 파싱만 하고 실행하지 않는다."""
|
|
111
|
+
result: dict[str, list[str]] = {}
|
|
112
|
+
for file, source in read_sources(worktree, files).items():
|
|
113
|
+
try:
|
|
114
|
+
tree = ast.parse(source)
|
|
115
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
|
116
|
+
continue
|
|
117
|
+
names: list[str] = []
|
|
118
|
+
for node in tree.body:
|
|
119
|
+
targets = (
|
|
120
|
+
node.targets if isinstance(node, ast.Assign) else [getattr(node, "target", None)]
|
|
121
|
+
)
|
|
122
|
+
for t in targets:
|
|
123
|
+
if isinstance(t, ast.Name) and t.id.isupper() and t.id not in names:
|
|
124
|
+
names.append(t.id)
|
|
125
|
+
result[file] = names
|
|
126
|
+
return result
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass
|
|
130
|
+
class FixTools:
|
|
131
|
+
"""수정 루프가 쓰는 외부 동작. 테스트에서는 가짜로 바꾼다."""
|
|
132
|
+
|
|
133
|
+
# (worktree, 사용자 메시지, *, system_prompt, model, max_budget_usd) → 결과.
|
|
134
|
+
# 그래프는 workdir.run_in_model_folder를 넘긴다
|
|
135
|
+
run_model: Callable[..., ClaudeResult]
|
|
136
|
+
# 도구·검사기로 확인하는 모든 규칙을 다시 돌린다: (바뀐 줄, 새 파일) → 위반
|
|
137
|
+
recheck: Callable[[ChangedLines, frozenset[str]], Detection]
|
|
138
|
+
rules_rechecked: int # recheck가 돌리는 도구·검사기 수 (수정안 PR의 검증 절에 쓴다)
|
|
139
|
+
# 샌드박스 테스트 (줄마다 실행한 테스트까지): (만든 테스트의 내용, 줄을 볼 소스 파일) → 결과.
|
|
140
|
+
# 내용이 None이면 worktree의 지금 상태, 있으면 PR head에 그 파일만 얹은 따로 된 worktree
|
|
141
|
+
run_suite: Callable[[Mapping[str, bytes] | None, Sequence[str]], Suite]
|
|
142
|
+
is_stale: Callable[[], bool] = lambda: False
|
|
143
|
+
secrets: Sequence[str] = () # 파이프라인의 비밀값
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class _Cancelled(Exception):
|
|
147
|
+
pass
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class _CapHit(Exception):
|
|
151
|
+
pass
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclass(frozen=True)
|
|
155
|
+
class _Passed:
|
|
156
|
+
"""출구 검사를 통과한 회차의 결과."""
|
|
157
|
+
|
|
158
|
+
explanation: Explanation
|
|
159
|
+
files: tuple[str, ...]
|
|
160
|
+
verification: Verification
|
|
161
|
+
tests: tuple[GeneratedTest, ...]
|
|
162
|
+
untested: Mapping[tuple[str, str], str]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@dataclass
|
|
166
|
+
class _Tally:
|
|
167
|
+
calls: int = 0
|
|
168
|
+
cache_hits: int = 0
|
|
169
|
+
input_tokens: int = 0
|
|
170
|
+
output_tokens: int = 0
|
|
171
|
+
models: list[str] = field(default_factory=list)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def file_hashes(worktree: Path, files: Sequence[str]) -> dict[str, str]:
|
|
175
|
+
out = {}
|
|
176
|
+
for rel in files:
|
|
177
|
+
path = repo.worktree_file(worktree, rel)
|
|
178
|
+
data = read_regular_file(path, max_bytes=MAX_FILE_BYTES) if path is not None else None
|
|
179
|
+
out[rel] = text_hash(data.decode("utf-8", errors="replace")) if data is not None else ""
|
|
180
|
+
return out
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def notes_for(found: Found, picked: Picked, worktree: Path) -> tuple[records_pure.Target, ...]:
|
|
184
|
+
"""고치기 전에 대상 위반마다 규칙 원문과 위반 줄 앞뒤를 남긴다. 그 수정안이 머지·닫히거나
|
|
185
|
+
검증에 실패하면 이것으로 기록을 만든다 (4.10)."""
|
|
186
|
+
texts = {rule_id: o.rule.text for rule_id, o in outcomes_by_rule(found).items()}
|
|
187
|
+
lines: dict[str, list[str]] = {}
|
|
188
|
+
for v in picked.targets:
|
|
189
|
+
if v.file not in lines:
|
|
190
|
+
path = repo.worktree_file(worktree, v.file)
|
|
191
|
+
data = read_regular_file(path, max_bytes=MAX_FILE_BYTES) if path is not None else None
|
|
192
|
+
lines[v.file] = data.decode("utf-8", errors="replace").split("\n") if data else []
|
|
193
|
+
return tuple(
|
|
194
|
+
records_pure.Target(
|
|
195
|
+
v.id, v.rule_id, texts.get(v.rule_id, ""), v.file, v.line, v.line_text or "",
|
|
196
|
+
records_pure.context_around(lines[v.file], v.line),
|
|
197
|
+
)
|
|
198
|
+
for v in picked.targets
|
|
199
|
+
) # fmt: skip
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def save_attempt(
|
|
203
|
+
store: Store,
|
|
204
|
+
job: PRJob,
|
|
205
|
+
merge_base: str,
|
|
206
|
+
fix: ModelFix,
|
|
207
|
+
notes: Sequence[records_pure.Target],
|
|
208
|
+
worktree: Path,
|
|
209
|
+
bundle: str = MODEL_BUNDLE,
|
|
210
|
+
) -> ModelFix:
|
|
211
|
+
"""시도 결과를 `fix_attempts`에 저장하고 그 id를 붙인다. 검증을 통과했으면 지금 worktree의
|
|
212
|
+
패치와 바뀐 파일의 해시도 남긴다. 전달은 이 패치만 올린다 (4.8 끝). bundle은 코멘트 수정이면
|
|
213
|
+
`feedback`이다 (4.11)."""
|
|
214
|
+
ready = fix.ready
|
|
215
|
+
explanation = asdict(fix.explanation) if fix.explanation is not None else None
|
|
216
|
+
attempt_id = store.save_fix_attempt(
|
|
217
|
+
FixAttempt(
|
|
218
|
+
repo=job.repo, pr_number=job.pr_number, head_sha=job.head_sha, merge_base=merge_base,
|
|
219
|
+
bundle=bundle, status=fix.status, attempts=fix.attempts,
|
|
220
|
+
models_json=json.dumps(list(fix.models)), detail=fix.detail,
|
|
221
|
+
targets_json=records_pure.targets_to_json(notes),
|
|
222
|
+
patch=repo.head_diff(worktree) if ready else None,
|
|
223
|
+
explanation_json=json.dumps(explanation, ensure_ascii=False) if ready else None,
|
|
224
|
+
file_hashes_json=(
|
|
225
|
+
json.dumps(file_hashes(worktree, fix.changed_files)) if ready else None
|
|
226
|
+
),
|
|
227
|
+
references_json=json.dumps(sorted(
|
|
228
|
+
{ref.record_id for r in fix.retrievals for ref in r.references}
|
|
229
|
+
)) if fix.retrievals else None,
|
|
230
|
+
)
|
|
231
|
+
) # fmt: skip
|
|
232
|
+
return replace(fix, attempt_id=attempt_id)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def reapply(store: Store, attempt_id: int | None, worktree: Path) -> FixAttempt | str:
|
|
236
|
+
"""검증을 통과한 시도의 패치를 새 worktree에 적용하고 바뀐 파일의 해시가 저장한 값과 같은지
|
|
237
|
+
본다. 모델을 부르지 않는다. 같으면 그 시도, 다르거나 적용하지 못하면 올리지 않는 이유."""
|
|
238
|
+
attempt = store.fix_attempt(attempt_id) if attempt_id is not None else None
|
|
239
|
+
if attempt is None or attempt.patch is None or attempt.file_hashes_json is None:
|
|
240
|
+
return "검증을 통과한 수정안을 저장한 기록이 없음"
|
|
241
|
+
try:
|
|
242
|
+
repo.apply_patch(worktree, attempt.patch.encode())
|
|
243
|
+
except repo.GitError as e:
|
|
244
|
+
log.warning("저장한 수정안을 다시 적용하지 못함 (시도 %s): %s", attempt_id, e)
|
|
245
|
+
return "저장한 수정안을 새 worktree에 다시 적용하지 못함"
|
|
246
|
+
expected = json.loads(attempt.file_hashes_json)
|
|
247
|
+
if file_hashes(worktree, sorted(expected)) != expected:
|
|
248
|
+
log.warning("다시 적용한 수정안의 파일 해시가 다름 (시도 %s)", attempt_id)
|
|
249
|
+
return "다시 적용한 수정안이 검증한 파일과 다름"
|
|
250
|
+
return attempt
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _top_dirs(worktree: Path) -> list[str]:
|
|
254
|
+
"""worktree 맨 위의 진짜 폴더 이름 (링크는 뺀다)."""
|
|
255
|
+
try:
|
|
256
|
+
entries = list(os.scandir(worktree))
|
|
257
|
+
except OSError:
|
|
258
|
+
return []
|
|
259
|
+
return [e.name for e in entries if stat.S_ISDIR(e.stat(follow_symlinks=False).st_mode)]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _read_generated(worktree: Path, paths: Sequence[str]) -> dict[str, bytes]:
|
|
263
|
+
out = {}
|
|
264
|
+
for rel in paths:
|
|
265
|
+
path = repo.worktree_file(worktree, rel)
|
|
266
|
+
data = read_regular_file(path, max_bytes=MAX_FILE_BYTES) if path is not None else None
|
|
267
|
+
if data is not None:
|
|
268
|
+
out[rel] = data
|
|
269
|
+
return out
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def fix_violations(
|
|
273
|
+
found: Found,
|
|
274
|
+
picked: Picked,
|
|
275
|
+
*,
|
|
276
|
+
worktree: Path,
|
|
277
|
+
merge_base: str,
|
|
278
|
+
test_before: PytestRun,
|
|
279
|
+
store: Store,
|
|
280
|
+
budget: CallBudget,
|
|
281
|
+
models: ModelSettings,
|
|
282
|
+
max_attempts: int,
|
|
283
|
+
tools: FixTools,
|
|
284
|
+
generation: int = model_fix_pure.GENERATION,
|
|
285
|
+
retriever: FindsRecords | None = None,
|
|
286
|
+
context_of: Callable[[Violation], str] = lambda v: "",
|
|
287
|
+
note: str = "",
|
|
288
|
+
) -> ModelFix | None:
|
|
289
|
+
"""picked.targets를 모델로 고치고 출구 검사를 한다. 새 커밋이 와서 중단되면 None.
|
|
290
|
+
|
|
291
|
+
found는 수정 전 위반 전체, picked는 `model_fix.pick_targets`의 결과다(대상이 하나 이상).
|
|
292
|
+
generation은 시도 세대다. `/fix`가 다시 돌릴 때마다 올라 저장된 수정 작성을 쓰지 않는다 (4.9).
|
|
293
|
+
retriever가 있으면(검색을 켬) 첫 회차에는 비슷한 채택 기록을, 재시도에는 비슷한 실패 기록을
|
|
294
|
+
참고 자료로 넣는다 (6.2). context_of(위반)는 위반 줄과 앞뒤 5줄이다. note는 시스템 프롬프트
|
|
295
|
+
뒤에 붙이는 글이다(코멘트 수정의 안내, 4.11). 저장 키에도 들어간다.
|
|
296
|
+
"""
|
|
297
|
+
by_rule = {rule_id: o.rule for rule_id, o in outcomes_by_rule(found).items()}
|
|
298
|
+
targets = picked.targets
|
|
299
|
+
allowed = sorted({v.file for v in targets})
|
|
300
|
+
tally = _Tally()
|
|
301
|
+
passed: list[_Passed] = [] # 통과한 회차의 결과
|
|
302
|
+
found_for: dict[str, Selection] = {} # 쓰는 곳(fix, fix_retry) → 고른 기록. 한 번만 찾는다
|
|
303
|
+
usage: list[ToolUsage] = []
|
|
304
|
+
kept: list[str] = [] # 앞 회차의 출구 검사가 받아들인 만든 테스트 (회차를 넘어 겹치지 않음)
|
|
305
|
+
|
|
306
|
+
def records_for(site: str) -> Selection:
|
|
307
|
+
if retriever is None:
|
|
308
|
+
return EMPTY
|
|
309
|
+
if site not in found_for:
|
|
310
|
+
queries = [query_text(by_rule[v.rule_id].text, context_of(v)) for v in targets]
|
|
311
|
+
found_for[site] = retriever.find(site, list(dict.fromkeys(queries)))
|
|
312
|
+
return found_for[site]
|
|
313
|
+
|
|
314
|
+
def outcome(status: model_fix_pure.ModelFixStatus, attempts: int, detail: str = "") -> ModelFix:
|
|
315
|
+
last = passed[-1] if passed else None
|
|
316
|
+
found = merge_retrievals(retrieval(s, site) for site, s in found_for.items())
|
|
317
|
+
error = retriever.error if retriever is not None else ""
|
|
318
|
+
return ModelFix(
|
|
319
|
+
status=status, targets=tuple(v.id for v in targets),
|
|
320
|
+
size_capped=tuple(v.id for v in picked.size_capped), detail=detail,
|
|
321
|
+
explanation=last.explanation if last else None,
|
|
322
|
+
verification=last.verification if last else None,
|
|
323
|
+
changed_files=last.files if last else (),
|
|
324
|
+
calls=tally.calls, cache_hits=tally.cache_hits, input_tokens=tally.input_tokens,
|
|
325
|
+
output_tokens=tally.output_tokens, models=tuple(tally.models), attempts=attempts,
|
|
326
|
+
retrievals=tuple(replace(r, error=error) for r in found),
|
|
327
|
+
generated=last.tests if last else (),
|
|
328
|
+
line_runs=line_runs(targets, last.tests, last.untested) if last else (),
|
|
329
|
+
tool_usage=sum(usage, ToolUsage()),
|
|
330
|
+
) # fmt: skip
|
|
331
|
+
|
|
332
|
+
outside = repo.outside_symlinks(worktree)
|
|
333
|
+
if outside: # 링크 폴더를 거친 쓰기는 worktree 밖으로 가고 범위 검사에도 안 보인다
|
|
334
|
+
shown = ", ".join(outside[:5])
|
|
335
|
+
return outcome("refused", 0, f"worktree 밖을 가리키는 심볼릭 링크: {shown}")
|
|
336
|
+
# 모델을 처음 실행하기 직전에 한 번만 찍는다. 재시도 사이에 다시 찍지 않는다 (4.8의 1번)
|
|
337
|
+
ignored_before = scope.snapshot_ignored(worktree)
|
|
338
|
+
test_dir = generated_test_dir(_top_dirs(worktree))
|
|
339
|
+
policy = replace(AI_POLICY, generated_test_dir=test_dir)
|
|
340
|
+
constants = module_constants(worktree, allowed)
|
|
341
|
+
start = file_hashes(worktree, allowed)
|
|
342
|
+
sources_before = read_sources(worktree, allowed) # 만든 테스트를 고치기 전 코드로 판정한다
|
|
343
|
+
# 모델이 찾은 위반은 도구로 다시 확인하지 못해 그 줄이 바뀌었는지만 본다 (4.8의 5번).
|
|
344
|
+
# 받아들인 코멘트(feedback)는 검사기가 없어 그 파일이 바뀌었는지만 본다 (4.11)
|
|
345
|
+
by_model = [v for v in targets if v.found_by == "model"]
|
|
346
|
+
by_feedback = [v for v in targets if v.found_by == "feedback"]
|
|
347
|
+
by_tools = [v for v in targets if v.found_by not in _UNCHECKED]
|
|
348
|
+
lines_before = {f: source_lines(worktree, f) for f in {v.file for v in by_model}}
|
|
349
|
+
asked = [Target(v, by_rule[v.rule_id]) for v in targets]
|
|
350
|
+
|
|
351
|
+
def generated_now() -> list[str]:
|
|
352
|
+
"""정한 자리에 새로 만든 테스트 파일. diff에 보이게 `git add -N`한다."""
|
|
353
|
+
paths = sorted(
|
|
354
|
+
e.path for e in parse_porcelain(repo.status(worktree))
|
|
355
|
+
if e.orig_path is None and e.code in _NEW_FILE_CODES
|
|
356
|
+
and is_generated_test(e.path, test_dir)
|
|
357
|
+
) # fmt: skip
|
|
358
|
+
repo.track_new(worktree, paths)
|
|
359
|
+
return paths
|
|
360
|
+
|
|
361
|
+
def check_now() -> tuple[list[Violation], list[Violation], list[str]]:
|
|
362
|
+
"""규칙 재검사 (4.8의 5번): (남은 대상 위반, 새 위반, 검사하지 못한 규칙)."""
|
|
363
|
+
generated_now()
|
|
364
|
+
diff = repo.working_diff(worktree, merge_base)
|
|
365
|
+
detection = tools.recheck(added_lines(diff), new_files(diff))
|
|
366
|
+
unchecked = [f"{u.rule.id}: {u.detail}" for u in detection.unchecked]
|
|
367
|
+
before = [v for v in found.violations if v.found_by not in _UNCHECKED]
|
|
368
|
+
left, new = model_fix_pure.recheck(before, by_tools, detection.violations)
|
|
369
|
+
lines_after = {f: source_lines(worktree, f) for f in lines_before}
|
|
370
|
+
left += model_fix_pure.unchanged_lines(by_model, lines_before, lines_after)
|
|
371
|
+
now = file_hashes(worktree, sorted({v.file for v in by_feedback}))
|
|
372
|
+
left += [v for v in by_feedback if now[v.file] == start[v.file]]
|
|
373
|
+
return left, new, unchecked
|
|
374
|
+
|
|
375
|
+
def judge_before() -> tuple[tuple[GeneratedTest, ...], Suite]:
|
|
376
|
+
"""만든 테스트를 고치기 전 코드에 얹어 돌리고 받아들일지 정한다 (4.8의 6번)."""
|
|
377
|
+
contents = _read_generated(worktree, generated_now())
|
|
378
|
+
suite = tools.run_suite(contents, allowed)
|
|
379
|
+
candidates = [Candidate(f, d.decode("utf-8", errors="replace"))
|
|
380
|
+
for f, d in contents.items()] # fmt: skip
|
|
381
|
+
return judge_tests(candidates, targets, suite, sources_before, kept=kept), suite
|
|
382
|
+
|
|
383
|
+
def check_tool(args: Mapping[str, str]) -> str:
|
|
384
|
+
left, new, unchecked = check_now()
|
|
385
|
+
return render_check(left, new, unchecked, len(by_model))
|
|
386
|
+
|
|
387
|
+
def test_tool(args: Mapping[str, str]) -> str:
|
|
388
|
+
if args.get("code") == "before":
|
|
389
|
+
judged, suite = judge_before()
|
|
390
|
+
return render_before(judged, suite, targets)
|
|
391
|
+
return render_now(tools.run_suite(None, allowed), generated_now())
|
|
392
|
+
|
|
393
|
+
pipeline_tools = {mcp_pure.CHECK_RULES: check_tool, mcp_pure.RUN_TESTS: test_tool}
|
|
394
|
+
|
|
395
|
+
def write(state: LoopState) -> WriteResult:
|
|
396
|
+
attempt, tier = state["attempt"], state["tier"]
|
|
397
|
+
model = models.heavy if tier == "heavy" else models.light
|
|
398
|
+
feedback = state.get("feedback", [])
|
|
399
|
+
chosen = records_for("fix" if attempt == 1 else "fix_retry")
|
|
400
|
+
records = render_records(chosen.chosen)
|
|
401
|
+
key = model_fix_pure.write_key(
|
|
402
|
+
targets, start, file_hashes(worktree, allowed), feedback, model, generation,
|
|
403
|
+
records=chosen.ids, note=note,
|
|
404
|
+
) # fmt: skip
|
|
405
|
+
entry = store.cached_result(key)
|
|
406
|
+
if entry is not None:
|
|
407
|
+
written = model_fix_pure.written_from_json(entry.result_json)
|
|
408
|
+
if written.patch:
|
|
409
|
+
try:
|
|
410
|
+
repo.apply_patch(worktree, written.patch)
|
|
411
|
+
except repo.GitError as e:
|
|
412
|
+
raise WriteFailed(f"저장한 수정을 적용하지 못함: {e}") from e
|
|
413
|
+
budget.record_hit(PrScope(), stage="fix", tier=tier, model=model)
|
|
414
|
+
tally.cache_hits += 1
|
|
415
|
+
return WriteResult(artifact=key)
|
|
416
|
+
call = budget.begin(PrScope(), stage="fix", tier=tier, model=model, attempt=attempt)
|
|
417
|
+
if isinstance(call, Denied):
|
|
418
|
+
raise _CapHit(call.reason)
|
|
419
|
+
prompt = model_fix_pure.build_prompt(
|
|
420
|
+
asked, constants=constants, feedback=feedback,
|
|
421
|
+
current_diff=repo.head_diff(worktree) if attempt > 1 else "", records=records,
|
|
422
|
+
test_dir=test_dir,
|
|
423
|
+
) # fmt: skip
|
|
424
|
+
system_prompt = (
|
|
425
|
+
model_fix_pure.SYSTEM_PROMPT + (model_fix_pure.RECORDS_NOTE if records else "") + note
|
|
426
|
+
)
|
|
427
|
+
result = tools.run_model(
|
|
428
|
+
worktree, prompt, system_prompt=system_prompt, model=model,
|
|
429
|
+
max_budget_usd=FIX_CALL_BUDGET_USD[tier], tools=pipeline_tools,
|
|
430
|
+
timeout=FIX_TOOLS_TIMEOUT_S,
|
|
431
|
+
) # fmt: skip
|
|
432
|
+
failure = None if result.ok else f"모델 호출 실패: {result.error}: {result.detail}"
|
|
433
|
+
budget.finish(
|
|
434
|
+
call, ok=result.ok, error=failure, model_id=result.model_id,
|
|
435
|
+
input_tokens=result.input_tokens, output_tokens=result.output_tokens,
|
|
436
|
+
permission_denials=len(result.permission_denials),
|
|
437
|
+
) # fmt: skip
|
|
438
|
+
tally.calls += 3 if tier == "heavy" else 1
|
|
439
|
+
tally.input_tokens += result.input_tokens or 0
|
|
440
|
+
tally.output_tokens += result.output_tokens or 0
|
|
441
|
+
tally.models.append(result.model_id or model)
|
|
442
|
+
usage.append(result.tool_usage)
|
|
443
|
+
if result.tool_usage.calls:
|
|
444
|
+
log.info("수정 모델의 도구 호출: 규칙 검사 %d회, 테스트 %d회, %.0f초%s",
|
|
445
|
+
result.tool_usage.check_rules, result.tool_usage.run_tests,
|
|
446
|
+
result.tool_usage.seconds,
|
|
447
|
+
" (상한에 닿음)" if result.tool_usage.limited else "") # fmt: skip
|
|
448
|
+
if result.permission_denials:
|
|
449
|
+
log.warning("수정 모델이 허용 범위 밖 도구 호출을 시도함 (%d건): %s",
|
|
450
|
+
len(result.permission_denials),
|
|
451
|
+
", ".join(d.tool_name for d in result.permission_denials)) # fmt: skip
|
|
452
|
+
if result.unexpected_tools:
|
|
453
|
+
log.warning("수정 모델이 목록에 없는 도구를 부르려 함: %s",
|
|
454
|
+
", ".join(f"{n} {c}회" for n, c in result.unexpected_tools)) # fmt: skip
|
|
455
|
+
problem = environment_problem(result)
|
|
456
|
+
if problem is not None:
|
|
457
|
+
raise AIEnvironmentError(problem)
|
|
458
|
+
if tools.is_stale():
|
|
459
|
+
raise _Cancelled
|
|
460
|
+
if failure is not None:
|
|
461
|
+
raise WriteFailed(failure)
|
|
462
|
+
store.save_result(
|
|
463
|
+
key, stage="fix", model=result.model_id or model,
|
|
464
|
+
prompt_version=model_fix_pure.PROMPT_VERSION,
|
|
465
|
+
result_json=model_fix_pure.written_to_json(Written(result.applied, result.text)),
|
|
466
|
+
) # fmt: skip
|
|
467
|
+
return WriteResult(artifact=key)
|
|
468
|
+
|
|
469
|
+
def verify(state: LoopState) -> Verdict:
|
|
470
|
+
entry = store.cached_result(state["artifact"])
|
|
471
|
+
if entry is None:
|
|
472
|
+
raise LookupError(f"저장한 수정이 없다: {state['artifact']}")
|
|
473
|
+
written = model_fix_pure.written_from_json(entry.result_json)
|
|
474
|
+
checked = scope.check_scope(worktree, set(allowed), ignored_before, policy=policy)
|
|
475
|
+
if not checked.ok:
|
|
476
|
+
return Verdict("drop", f"허용 범위 밖의 변경: {checked.detail}")
|
|
477
|
+
entries = [
|
|
478
|
+
e for e in parse_porcelain(repo.status(worktree)) if not is_pipeline_output(e.path)
|
|
479
|
+
]
|
|
480
|
+
if not entries:
|
|
481
|
+
return Verdict("retry", "아무 파일도 바꾸지 않음", (NOTHING_CHANGED,))
|
|
482
|
+
generated = generated_now()
|
|
483
|
+
patch = repo.head_diff(worktree)
|
|
484
|
+
kind = find_secret(patch, tools.secrets) or find_secret_in_text(written.text, tools.secrets)
|
|
485
|
+
if kind is not None:
|
|
486
|
+
return Verdict("drop", f"{SECRET_BLOCKED} ({kind})")
|
|
487
|
+
|
|
488
|
+
try:
|
|
489
|
+
answer = model_fix_pure.parse_answer(written.text)
|
|
490
|
+
except ValueError as e:
|
|
491
|
+
return Verdict("retry", f"설명 JSON을 읽지 못함: {e}")
|
|
492
|
+
code_blocks = [b for b in change_blocks(patch) if b.file not in generated]
|
|
493
|
+
explanation = model_fix_pure.explain(answer, code_blocks, targets)
|
|
494
|
+
if isinstance(explanation, model_fix_pure.Mismatch):
|
|
495
|
+
detail = f"설명이 수정과 맞지 않음: {explanation.detail}"
|
|
496
|
+
return Verdict("retry", detail, (detail, *explanation.feedback))
|
|
497
|
+
|
|
498
|
+
left, new, unchecked = check_now()
|
|
499
|
+
if unchecked:
|
|
500
|
+
return Verdict("retry", f"고친 뒤 규칙 재검사를 하지 못함: {'; '.join(unchecked)}")
|
|
501
|
+
if left or new:
|
|
502
|
+
feedback = model_fix_pure.violation_feedback(
|
|
503
|
+
"아직 남은 위반", left
|
|
504
|
+
) + model_fix_pure.violation_feedback("새로 생긴 위반", new)
|
|
505
|
+
detail = f"남은 위반 {len(left)}건, 새 위반 {len(new)}건"
|
|
506
|
+
return Verdict("retry", detail, tuple(feedback))
|
|
507
|
+
|
|
508
|
+
judged: tuple[GeneratedTest, ...] = ()
|
|
509
|
+
if generated:
|
|
510
|
+
judged, before_run = judge_before()
|
|
511
|
+
if before_run.run.cancelled:
|
|
512
|
+
raise _Cancelled
|
|
513
|
+
for t in judged:
|
|
514
|
+
if not t.accepted: # 조건에 맞지 않는 테스트는 그 파일만 뺀다
|
|
515
|
+
(worktree / t.file).unlink(missing_ok=True)
|
|
516
|
+
repo.untrack(worktree, t.file)
|
|
517
|
+
after = tools.run_suite(None, allowed)
|
|
518
|
+
if after.run.cancelled:
|
|
519
|
+
raise _Cancelled
|
|
520
|
+
check = after_check(judged, test_before, after)
|
|
521
|
+
if check.broken:
|
|
522
|
+
failed = [n for n in (after.run.summary.failed_tests if after.run.summary else ())]
|
|
523
|
+
detail = f"만든 테스트 {len(check.broken)}개가 고치기 전에는 통과했는데 고친 뒤 실패함"
|
|
524
|
+
feedback = [f"만든 테스트가 고친 뒤 실패함 (수정이 동작을 바꿈): {f}"
|
|
525
|
+
for f in check.broken] # fmt: skip
|
|
526
|
+
return Verdict("retry", detail, (*feedback, *(f"실패한 테스트: {n}" for n in failed)))
|
|
527
|
+
if not check.existing_ok:
|
|
528
|
+
line = format_test_line(after.run)
|
|
529
|
+
failed = list(after.run.summary.failed_tests) if after.run.summary else []
|
|
530
|
+
return Verdict(
|
|
531
|
+
"retry",
|
|
532
|
+
f"고친 뒤 테스트: {line}",
|
|
533
|
+
(f"고친 뒤 테스트: {line}", *(f"실패한 테스트: {t}" for t in failed)),
|
|
534
|
+
)
|
|
535
|
+
kept[:] = [t.file for t in check.tests if t.accepted]
|
|
536
|
+
|
|
537
|
+
entries = [
|
|
538
|
+
e for e in parse_porcelain(repo.status(worktree)) if not is_pipeline_output(e.path)
|
|
539
|
+
]
|
|
540
|
+
files = sorted({e.path for e in entries})
|
|
541
|
+
test_files = set(kept)
|
|
542
|
+
code_files = [f for f in files if f not in test_files]
|
|
543
|
+
test_lines = sum(t.lines for t in check.tests if t.accepted)
|
|
544
|
+
lines = changed_line_count(repo.head_diff(worktree)) - test_lines
|
|
545
|
+
too_big = model_fix_pure.size_problem(len(code_files), lines)
|
|
546
|
+
if too_big is not None:
|
|
547
|
+
return Verdict("retry", too_big)
|
|
548
|
+
verification = Verification(
|
|
549
|
+
tests=test_before.passed_count, resolved=len(targets),
|
|
550
|
+
rules_rechecked=tools.rules_rechecked, files=len(code_files), lines=lines,
|
|
551
|
+
unverified=len(by_model) + len(by_feedback),
|
|
552
|
+
) # fmt: skip
|
|
553
|
+
untested = {(n.file, n.rule): n.why for n in explanation.untested}
|
|
554
|
+
passed.append(_Passed(explanation, tuple(files), verification, check.tests, untested))
|
|
555
|
+
return Verdict("pass")
|
|
556
|
+
|
|
557
|
+
policy_ = LoopPolicy(max_attempts=max_attempts, may_call=budget.may_call(PrScope()))
|
|
558
|
+
try:
|
|
559
|
+
final = build_loop("fix_model", write, verify, policy_).invoke({"task": {}})
|
|
560
|
+
except _Cancelled:
|
|
561
|
+
return None
|
|
562
|
+
except _CapHit as e:
|
|
563
|
+
return outcome("budget", len(tally.models), str(e))
|
|
564
|
+
attempts = final.get("attempt", 0)
|
|
565
|
+
match final["outcome"]:
|
|
566
|
+
case "accepted":
|
|
567
|
+
return outcome("ready", attempts)
|
|
568
|
+
case "dropped":
|
|
569
|
+
return outcome("dropped", attempts, final.get("detail", ""))
|
|
570
|
+
case "budget":
|
|
571
|
+
denied = budget.decide(PrScope(), "light")
|
|
572
|
+
reason = denied.reason if isinstance(denied, Denied) else "호출 상한"
|
|
573
|
+
return outcome("budget", attempts, reason)
|
|
574
|
+
case _:
|
|
575
|
+
return outcome("failed", attempts, final.get("detail", ""))
|