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,404 @@
|
|
|
1
|
+
"""PR 단위 확인 (docs/DESIGN.md 4.5 끝, 완료 기준 4-11–4-14, 위협 T27).
|
|
2
|
+
|
|
3
|
+
확인 대상이 `pr`인 규칙을 PR 자체(커밋 메시지, PR 제목·본문, 브랜치 이름, 바뀐 파일)에 대해 본다.
|
|
4
|
+
그래프의 `pr_check` node가 모델 판단(`judge`) 다음, 테스트 전에 부른다. 가드레일(8.6)이 작업을 들인
|
|
5
|
+
뒤에만 돌고, `pr` 규칙이 없으면 PR의 글을 읽지 않는다.
|
|
6
|
+
|
|
7
|
+
1. 사실 읽기 (`gather`): 커밋은 이 작업이 받은 git 객체(merge-base..head)에서, 제목·본문·브랜치
|
|
8
|
+
이름은 GitHub의 PR 조회에서, 바뀐 파일은 worktree의 diff에서 읽는다. 크기 상한은
|
|
9
|
+
app/worker/rules/pr_check_pure.py에 있다.
|
|
10
|
+
2. 계획 (`plan`): 규칙마다 PR 패턴(결정적) 또는 모델 판단을 정한다. 모델은 규칙 원문과 문서의
|
|
11
|
+
예시만 보고 PR의 글은 보지 않는다. 예시 확인은 샌드박스의 고정 스크립트가 한다. 계획은 규칙
|
|
12
|
+
묶음 상한에서 세고 `model_cache`에 저장한다.
|
|
13
|
+
3. 확인 (`check`): 패턴과 바뀐 파일 조건은 샌드박스에서 맞추고, 모델 판단은 도구 없이 부른다
|
|
14
|
+
(PR 상한). 판단의 답은 결정적으로 확인하고 (규칙, 사실의 해시)로 저장한다.
|
|
15
|
+
|
|
16
|
+
결과(`PrChecks`)는 알리기만 한다. 수정 판단과 수정 작성은 이 값을 받지 않는다 (4-13).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
21
|
+
from dataclasses import dataclass, field, replace
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Literal, Protocol
|
|
24
|
+
|
|
25
|
+
from app.worker import repo
|
|
26
|
+
from app.worker.budget import CallBudget
|
|
27
|
+
from app.worker.call_budget_pure import CALL_BUDGET_USD, Denied, PrScope, RulesetScope
|
|
28
|
+
from app.worker.doc_rules_pure import Found, RuleUnchecked
|
|
29
|
+
from app.worker.github import GitHub, GitHubError
|
|
30
|
+
from app.worker.repo import GitError
|
|
31
|
+
from app.worker.rule_pure import Rule
|
|
32
|
+
from app.worker.rules.pr_check_pure import (
|
|
33
|
+
JUDGE_PROMPT_VERSION,
|
|
34
|
+
JUDGE_SCHEMA,
|
|
35
|
+
JUDGE_SYSTEM_PROMPT,
|
|
36
|
+
MAX_COMMITS,
|
|
37
|
+
MAX_MESSAGE_BYTES,
|
|
38
|
+
PATTERN_ATTEMPTS,
|
|
39
|
+
PLAN_PROMPT_VERSION,
|
|
40
|
+
PLAN_SCHEMA,
|
|
41
|
+
PLAN_SYSTEM_PROMPT,
|
|
42
|
+
TEXT_FACTS,
|
|
43
|
+
CaseResult,
|
|
44
|
+
PlanDraft,
|
|
45
|
+
PrChecks,
|
|
46
|
+
PrFacts,
|
|
47
|
+
PrPattern,
|
|
48
|
+
PrPlan,
|
|
49
|
+
PrRuleResult,
|
|
50
|
+
PrUsage,
|
|
51
|
+
PrViolation,
|
|
52
|
+
Shown,
|
|
53
|
+
build_judge_prompt,
|
|
54
|
+
build_plan_prompt,
|
|
55
|
+
candidates_shown,
|
|
56
|
+
confirmed,
|
|
57
|
+
example_cases,
|
|
58
|
+
example_problems,
|
|
59
|
+
facts_from,
|
|
60
|
+
gate_ok,
|
|
61
|
+
judge_key,
|
|
62
|
+
parse_judge,
|
|
63
|
+
parse_plan,
|
|
64
|
+
partial_note,
|
|
65
|
+
pattern_violations,
|
|
66
|
+
pipeline_commits,
|
|
67
|
+
plan_from_json,
|
|
68
|
+
plan_key,
|
|
69
|
+
plan_to_json,
|
|
70
|
+
read_plan,
|
|
71
|
+
read_results,
|
|
72
|
+
real_case,
|
|
73
|
+
shown_for,
|
|
74
|
+
verify_judge,
|
|
75
|
+
violations_from_json,
|
|
76
|
+
violations_to_json,
|
|
77
|
+
)
|
|
78
|
+
from app.worker.rules.rules import AskModel
|
|
79
|
+
from app.worker.sandbox.checker_runner import Failed, PrRan
|
|
80
|
+
from app.worker.sandbox.toolcache import ToolUnavailable
|
|
81
|
+
from app.worker.state import Store
|
|
82
|
+
|
|
83
|
+
log = logging.getLogger(__name__)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class MatchesPrFacts(Protocol):
|
|
87
|
+
def pr_pattern(
|
|
88
|
+
self, decl: Mapping[str, object], cases: Sequence[Mapping[str, object]]
|
|
89
|
+
) -> PrRan | Failed: ...
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class Tools:
|
|
94
|
+
store: Store
|
|
95
|
+
budget: CallBudget
|
|
96
|
+
ask: AskModel
|
|
97
|
+
sandbox: MatchesPrFacts
|
|
98
|
+
plan_model: str # `model.checker` (검사기 작성과 같은 몫)
|
|
99
|
+
judge_model: str # `model.judge`
|
|
100
|
+
ruleset: RulesetScope # 계획 작성을 세는 규칙 묶음 상한
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def pr_rules(found: object) -> tuple[Rule, ...]:
|
|
104
|
+
"""확인 대상이 `pr`인 규칙 (검사 방법 정하기가 검사기 없이 넘긴 것)."""
|
|
105
|
+
if not isinstance(found, Found):
|
|
106
|
+
return ()
|
|
107
|
+
return tuple(o.rule for o in found.outcomes if isinstance(o, RuleUnchecked) and o.kind == "pr")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def gather(
|
|
111
|
+
worktree: Path, merge_base: str, head_sha: str, *, github: GitHub, store: Store, repo_name: str,
|
|
112
|
+
pr_number: int,
|
|
113
|
+
) -> PrFacts | str: # fmt: skip
|
|
114
|
+
"""이 PR의 사실. 읽지 못하면 그 이유(그때 모든 PR 규칙은 "확인하지 못함"이다)."""
|
|
115
|
+
try:
|
|
116
|
+
text = github.pr_text(repo_name, pr_number)
|
|
117
|
+
raw, more = repo.pr_commits(
|
|
118
|
+
worktree, merge_base, head_sha, limit=MAX_COMMITS, message_bytes=MAX_MESSAGE_BYTES
|
|
119
|
+
)
|
|
120
|
+
paths = repo.changed_paths(worktree, merge_base, head_sha)
|
|
121
|
+
except (GitHubError, GitError, UnicodeDecodeError) as e:
|
|
122
|
+
log.warning("PR 사실을 읽지 못함: %s", e)
|
|
123
|
+
return f"PR 사실을 읽지 못함: {str(e).strip().splitlines()[0] if str(e).strip() else e}"
|
|
124
|
+
merged = [
|
|
125
|
+
p.merge_commit for p in store.proposals(repo_name, pr_number)
|
|
126
|
+
if p.state == "merged" and p.merge_commit
|
|
127
|
+
] # fmt: skip
|
|
128
|
+
return facts_from(
|
|
129
|
+
title=text.title, body=text.body, branch=text.branch, commits=raw, more_commits=more,
|
|
130
|
+
paths=paths, pipeline_shas=pipeline_commits(merged, raw),
|
|
131
|
+
) # fmt: skip
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass
|
|
135
|
+
class _Run:
|
|
136
|
+
plan_calls: int = 0
|
|
137
|
+
judge_calls: int = 0
|
|
138
|
+
cached: int = 0
|
|
139
|
+
dropped: int = 0
|
|
140
|
+
input_tokens: int = 0
|
|
141
|
+
output_tokens: int = 0
|
|
142
|
+
models: list[str] = field(default_factory=list)
|
|
143
|
+
judge_stop: str = "" # PR 상한에 걸리면 남은 판단은 묻지 않는다
|
|
144
|
+
|
|
145
|
+
def usage(self) -> PrUsage:
|
|
146
|
+
return PrUsage(
|
|
147
|
+
plan_calls=self.plan_calls, judge_calls=self.judge_calls, cached=self.cached,
|
|
148
|
+
dropped=self.dropped, input_tokens=self.input_tokens,
|
|
149
|
+
output_tokens=self.output_tokens, models=tuple(sorted(set(self.models))),
|
|
150
|
+
) # fmt: skip
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(frozen=True)
|
|
154
|
+
class _NoPlan:
|
|
155
|
+
"""계획을 정하지 못했고 저장하지 않는다 (다음 검사가 다시 한다)."""
|
|
156
|
+
|
|
157
|
+
kind: Literal["cap", "model_failed", "tool_unavailable"]
|
|
158
|
+
detail: str
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def check(
|
|
162
|
+
rules: Sequence[Rule],
|
|
163
|
+
facts: PrFacts | str,
|
|
164
|
+
tools: Tools,
|
|
165
|
+
*,
|
|
166
|
+
known: int = 0,
|
|
167
|
+
is_stale: Callable[[], bool] = lambda: False,
|
|
168
|
+
) -> PrChecks:
|
|
169
|
+
"""PR 규칙마다 계획을 정하고 이 PR의 사실에 맞춘다. known은 이 검사의 코드 위반 수다(PR 상한의
|
|
170
|
+
대상 위반 수에 쓴다. PR 단위 위반은 세지 않는다)."""
|
|
171
|
+
run = _Run()
|
|
172
|
+
if isinstance(facts, str):
|
|
173
|
+
results = tuple(PrRuleResult(r, "unchecked", kind="no_facts", detail=facts) for r in rules)
|
|
174
|
+
return PrChecks(results, (), note=facts)
|
|
175
|
+
results: list[PrRuleResult] = []
|
|
176
|
+
violations: list[PrViolation] = []
|
|
177
|
+
for rule in rules:
|
|
178
|
+
plan = _plan(rule, tools, run)
|
|
179
|
+
if isinstance(plan, _NoPlan):
|
|
180
|
+
results.append(PrRuleResult(rule, "unchecked", kind=plan.kind, detail=plan.detail))
|
|
181
|
+
continue
|
|
182
|
+
result, found = _check_rule(rule, plan, facts, tools, run, known=known, is_stale=is_stale)
|
|
183
|
+
results.append(result)
|
|
184
|
+
violations += found
|
|
185
|
+
commits = facts.commits
|
|
186
|
+
return PrChecks(
|
|
187
|
+
tuple(results), tuple(violations), commits=sum(1 for c in commits if c.checked),
|
|
188
|
+
skipped_merge=sum(1 for c in commits if c.merge),
|
|
189
|
+
skipped_pipeline=sum(1 for c in commits if c.pipeline and not c.merge),
|
|
190
|
+
usage=run.usage(),
|
|
191
|
+
) # fmt: skip
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _plan(rule: Rule, tools: Tools, run: _Run) -> PrPlan | _NoPlan:
|
|
195
|
+
"""저장한 계획을 쓰거나 새로 쓴다. 예시 확인을 두 번 통과하지 못한 패턴은 글 사실이고 바뀐
|
|
196
|
+
파일 조건이 예시에 맞으면 모델 판단으로, 아니면 "확인 방법 없음"으로 저장한다."""
|
|
197
|
+
key = plan_key(rule, tools.plan_model)
|
|
198
|
+
entry = tools.store.cached_result(key)
|
|
199
|
+
if entry is not None:
|
|
200
|
+
try:
|
|
201
|
+
plan = plan_from_json(entry.result_json)
|
|
202
|
+
except (ValueError, KeyError, TypeError):
|
|
203
|
+
log.warning("저장한 PR 계획을 읽지 못해 다시 씀: %s", rule.id)
|
|
204
|
+
else:
|
|
205
|
+
run.cached += 1
|
|
206
|
+
tools.budget.record_hit(tools.ruleset, stage="pr_plan", tier="light",
|
|
207
|
+
model=tools.plan_model) # fmt: skip
|
|
208
|
+
return plan
|
|
209
|
+
feedback: list[str] = []
|
|
210
|
+
last: tuple[PlanDraft, bool] | None = None
|
|
211
|
+
for attempt in range(1, PATTERN_ATTEMPTS + 1):
|
|
212
|
+
call = tools.budget.begin(tools.ruleset, stage="pr_plan", tier="light",
|
|
213
|
+
model=tools.plan_model, attempt=attempt) # fmt: skip
|
|
214
|
+
if isinstance(call, Denied):
|
|
215
|
+
return _NoPlan("cap", call.reason)
|
|
216
|
+
answer = tools.ask(
|
|
217
|
+
build_plan_prompt(rule, feedback), system_prompt=PLAN_SYSTEM_PROMPT,
|
|
218
|
+
schema=PLAN_SCHEMA, model=tools.plan_model, max_budget_usd=CALL_BUDGET_USD["light"],
|
|
219
|
+
) # fmt: skip
|
|
220
|
+
failure = None if answer.ok else f"{answer.error}: {answer.detail}"
|
|
221
|
+
draft = None
|
|
222
|
+
if failure is None:
|
|
223
|
+
try:
|
|
224
|
+
draft = read_plan(parse_plan(answer.data or {}), rule)
|
|
225
|
+
except ValueError as e:
|
|
226
|
+
feedback = [f"답의 형식이 틀림: {str(e).splitlines()[0]}"]
|
|
227
|
+
tools.budget.finish(
|
|
228
|
+
call, ok=failure is None, error=failure, model_id=answer.model_id,
|
|
229
|
+
input_tokens=answer.input_tokens, output_tokens=answer.output_tokens,
|
|
230
|
+
permission_denials=answer.permission_denials,
|
|
231
|
+
) # fmt: skip
|
|
232
|
+
run.plan_calls += 1
|
|
233
|
+
run.input_tokens += answer.input_tokens or 0
|
|
234
|
+
run.output_tokens += answer.output_tokens or 0
|
|
235
|
+
model_id = answer.model_id or tools.plan_model
|
|
236
|
+
run.models.append(model_id)
|
|
237
|
+
if failure is not None:
|
|
238
|
+
return _NoPlan("model_failed", failure)
|
|
239
|
+
if draft is None:
|
|
240
|
+
continue
|
|
241
|
+
if draft.method == "none":
|
|
242
|
+
return _save(key, PrPlan("none", reason=draft.reason or "PR 사실로 확인할 수 없음",
|
|
243
|
+
model=model_id), tools) # fmt: skip
|
|
244
|
+
if draft.problems:
|
|
245
|
+
feedback = list(draft.problems)
|
|
246
|
+
continue
|
|
247
|
+
judged = draft.method == "model"
|
|
248
|
+
tried = _try_examples(draft, tools, judged=judged)
|
|
249
|
+
if isinstance(tried, _NoPlan):
|
|
250
|
+
return tried
|
|
251
|
+
problems, gate_passed = tried
|
|
252
|
+
if not problems:
|
|
253
|
+
return _save(key, PrPlan(draft.method, draft.decl, draft.examples, draft.reason,
|
|
254
|
+
"model_said" if judged else "", model_id), tools) # fmt: skip
|
|
255
|
+
feedback, last = problems, (draft, gate_passed and not judged)
|
|
256
|
+
if last is not None:
|
|
257
|
+
draft, gate_passed = last
|
|
258
|
+
if draft.decl.fact in TEXT_FACTS and gate_passed:
|
|
259
|
+
decl = PrPattern(draft.decl.fact, draft.decl.condition, "", draft.decl.when_changed)
|
|
260
|
+
reason = f"PR 패턴이 예시 확인을 {PATTERN_ATTEMPTS}번 통과하지 못함: {feedback[0]}"
|
|
261
|
+
return _save(key, PrPlan("model", decl, draft.examples, reason, "examples",
|
|
262
|
+
run.models[-1]), tools) # fmt: skip
|
|
263
|
+
why = feedback[0] if feedback else "답이 없음"
|
|
264
|
+
return _save(key, PrPlan("none", reason=f"예시를 통과하는 PR 패턴을 만들지 못함: {why}",
|
|
265
|
+
model=run.models[-1] if run.models else ""), tools) # fmt: skip
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _try_examples(
|
|
269
|
+
draft: PlanDraft, tools: Tools, *, judged: bool
|
|
270
|
+
) -> tuple[list[str], bool] | _NoPlan:
|
|
271
|
+
"""선언을 예시에 맞춘다. (문제 목록, 바뀐 파일 조건이 예시에 맞는지)."""
|
|
272
|
+
cases = example_cases(draft.decl, draft.examples)
|
|
273
|
+
ran = _run_pattern(draft.decl, cases, tools)
|
|
274
|
+
if isinstance(ran, _NoPlan):
|
|
275
|
+
return ran
|
|
276
|
+
if isinstance(ran, str):
|
|
277
|
+
return [ran], False
|
|
278
|
+
return (example_problems(draft.decl, draft.examples, ran, judged=judged),
|
|
279
|
+
gate_ok(draft.examples, ran, draft.decl)) # fmt: skip
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _run_pattern(
|
|
283
|
+
decl: PrPattern, cases: Sequence[Mapping[str, object]], tools: Tools
|
|
284
|
+
) -> tuple[CaseResult, ...] | str | _NoPlan:
|
|
285
|
+
"""샌드박스에서 맞춘 결과, 실패 이유(str), 또는 도구를 준비하지 못함(_NoPlan)."""
|
|
286
|
+
try:
|
|
287
|
+
ran = tools.sandbox.pr_pattern(decl.script_input(), cases)
|
|
288
|
+
except ToolUnavailable as e:
|
|
289
|
+
return _NoPlan("tool_unavailable", str(e))
|
|
290
|
+
if isinstance(ran, Failed):
|
|
291
|
+
return ran.reason
|
|
292
|
+
try:
|
|
293
|
+
return read_results(ran.items, cases)
|
|
294
|
+
except ValueError as e:
|
|
295
|
+
return f"샌드박스 출력을 읽지 못함: {e}"
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _save(key: str, plan: PrPlan, tools: Tools) -> PrPlan:
|
|
299
|
+
tools.store.save_result(
|
|
300
|
+
key, stage="pr_plan", model=plan.model or tools.plan_model,
|
|
301
|
+
prompt_version=PLAN_PROMPT_VERSION, result_json=plan_to_json(plan),
|
|
302
|
+
) # fmt: skip
|
|
303
|
+
return plan
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _check_rule(
|
|
307
|
+
rule: Rule, plan: PrPlan, facts: PrFacts, tools: Tools, run: _Run, *, known: int,
|
|
308
|
+
is_stale: Callable[[], bool],
|
|
309
|
+
) -> tuple[PrRuleResult, tuple[PrViolation, ...]]: # fmt: skip
|
|
310
|
+
base = PrRuleResult(rule, "checked", plan.method, plan.decl, plan.route, plan.reason)
|
|
311
|
+
if plan.method == "none" or plan.decl is None:
|
|
312
|
+
return PrRuleResult(rule, "unchecked", "none", reason=plan.reason, kind="plan_none",
|
|
313
|
+
detail=plan.reason), () # fmt: skip
|
|
314
|
+
decl = plan.decl
|
|
315
|
+
partial = partial_note(decl.fact, bool(decl.when_changed), facts)
|
|
316
|
+
if plan.method == "pattern" or decl.when_changed:
|
|
317
|
+
case = real_case(decl, facts)
|
|
318
|
+
ran = _run_pattern(decl, [case], tools)
|
|
319
|
+
if isinstance(ran, _NoPlan):
|
|
320
|
+
return PrRuleResult(rule, "unchecked", plan.method, decl, kind="tool_unavailable",
|
|
321
|
+
detail=ran.detail), () # fmt: skip
|
|
322
|
+
if isinstance(ran, str):
|
|
323
|
+
return PrRuleResult(rule, "unchecked", plan.method, decl, kind="run_failed",
|
|
324
|
+
detail=ran), () # fmt: skip
|
|
325
|
+
(result,) = ran
|
|
326
|
+
if not result.gated:
|
|
327
|
+
return _with(base, status="not_applicable"), ()
|
|
328
|
+
if plan.method == "pattern":
|
|
329
|
+
candidates = pattern_violations(rule, decl, facts, result)
|
|
330
|
+
if not candidates or decl.fact not in TEXT_FACTS:
|
|
331
|
+
return _with(base, partial=partial), candidates
|
|
332
|
+
# 패턴이 잡은 것은 후보다. 규칙 원문과 그 글을 모델에게 보여 위반인지 정한다 (4.5 끝)
|
|
333
|
+
shown = candidates_shown(facts, candidates)
|
|
334
|
+
judged, answered = _judge(rule, plan, decl, facts, tools, run, base, partial, known,
|
|
335
|
+
is_stale, shown=shown) # fmt: skip
|
|
336
|
+
if judged.status != "checked":
|
|
337
|
+
return judged, ()
|
|
338
|
+
kept, dropped = confirmed(candidates, answered)
|
|
339
|
+
return _with(judged, dismissed=dropped), kept
|
|
340
|
+
return _judge(rule, plan, decl, facts, tools, run, base, partial, known, is_stale)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _with(result: PrRuleResult, **changes: object) -> PrRuleResult:
|
|
344
|
+
return replace(result, **changes) # type: ignore[arg-type]
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _judge(
|
|
348
|
+
rule: Rule, plan: PrPlan, decl: PrPattern, facts: PrFacts, tools: Tools, run: _Run,
|
|
349
|
+
base: PrRuleResult, partial: str, known: int, is_stale: Callable[[], bool],
|
|
350
|
+
shown: Shown | None = None,
|
|
351
|
+
) -> tuple[PrRuleResult, tuple[PrViolation, ...]]: # fmt: skip
|
|
352
|
+
"""글 규칙 하나를 모델에 묻는다. 저장한 답이 있으면 묻지 않는다. shown이 있으면 그것만
|
|
353
|
+
보인다(PR 패턴의 후보)."""
|
|
354
|
+
shown = shown or shown_for(decl.fact, facts)
|
|
355
|
+
if not shown.commits and shown.title is None:
|
|
356
|
+
return _with(base, partial=partial), () # 볼 커밋이 없다
|
|
357
|
+
key = judge_key(rule, shown, tools.judge_model)
|
|
358
|
+
entry = tools.store.cached_result(key)
|
|
359
|
+
if entry is not None:
|
|
360
|
+
verified = violations_from_json(rule, shown, entry.result_json)
|
|
361
|
+
run.cached += 1
|
|
362
|
+
tools.budget.record_hit(PrScope(), stage="pr_judge", tier="light", model=tools.judge_model)
|
|
363
|
+
return _with(base, partial=partial), verified.kept
|
|
364
|
+
if not run.judge_stop and is_stale():
|
|
365
|
+
run.judge_stop = "새 커밋이 와서 멈춤"
|
|
366
|
+
if run.judge_stop:
|
|
367
|
+
return _with(base, status="left", kind="cap", detail=run.judge_stop), ()
|
|
368
|
+
call = tools.budget.with_targets(known).begin(
|
|
369
|
+
PrScope(), stage="pr_judge", tier="light", model=tools.judge_model
|
|
370
|
+
)
|
|
371
|
+
if isinstance(call, Denied):
|
|
372
|
+
run.judge_stop = call.reason
|
|
373
|
+
return _with(base, status="left", kind="cap", detail=call.reason), ()
|
|
374
|
+
answer = tools.ask(
|
|
375
|
+
build_judge_prompt(rule, shown), system_prompt=JUDGE_SYSTEM_PROMPT, schema=JUDGE_SCHEMA,
|
|
376
|
+
model=tools.judge_model, max_budget_usd=CALL_BUDGET_USD["light"],
|
|
377
|
+
) # fmt: skip
|
|
378
|
+
failure = None if answer.ok else f"{answer.error}: {answer.detail}"
|
|
379
|
+
items = ()
|
|
380
|
+
if failure is None:
|
|
381
|
+
try:
|
|
382
|
+
items = parse_judge(answer.data or {})
|
|
383
|
+
except ValueError as e:
|
|
384
|
+
failure = f"답의 형식이 틀림: {str(e).splitlines()[0]}"
|
|
385
|
+
tools.budget.finish(
|
|
386
|
+
call, ok=failure is None, error=failure, model_id=answer.model_id,
|
|
387
|
+
input_tokens=answer.input_tokens, output_tokens=answer.output_tokens,
|
|
388
|
+
permission_denials=answer.permission_denials,
|
|
389
|
+
) # fmt: skip
|
|
390
|
+
run.judge_calls += 1
|
|
391
|
+
run.input_tokens += answer.input_tokens or 0
|
|
392
|
+
run.output_tokens += answer.output_tokens or 0
|
|
393
|
+
run.models.append(answer.model_id or tools.judge_model)
|
|
394
|
+
if failure is not None:
|
|
395
|
+
log.warning("PR 단위 모델 판단 실패: %s", failure)
|
|
396
|
+
return _with(base, status="left", kind="model_failed", detail=failure), ()
|
|
397
|
+
verified = verify_judge(rule, shown, items)
|
|
398
|
+
for reason in verified.dropped:
|
|
399
|
+
log.info("PR 단위 판단의 답을 버림: %s", reason)
|
|
400
|
+
run.dropped += len(verified.dropped)
|
|
401
|
+
tools.store.save_result(key, stage="pr_judge", model=answer.model_id or tools.judge_model,
|
|
402
|
+
prompt_version=JUDGE_PROMPT_VERSION,
|
|
403
|
+
result_json=violations_to_json(verified.kept)) # fmt: skip
|
|
404
|
+
return _with(base, partial=partial), verified.kept
|