pr-proof 0.0.0-stage → 0.1.1-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 +172 -0
- package/app/setup/__init__.py +4 -0
- package/app/setup/cli.py +90 -0
- package/app/setup/configure.py +735 -0
- package/app/setup/files.py +104 -0
- package/app/setup/github_setup.py +153 -0
- package/app/setup/install_hints.json +32 -0
- package/app/setup/setup_pure.py +344 -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,236 @@
|
|
|
1
|
+
"""수정안을 머지한 커밋을 다시 검사하지 않고 검증한 결과를 옮겨 적을지 정한다 (docs/DESIGN.md
|
|
2
|
+
4.9 "수정안 PR 상태 관리", 5.6).
|
|
3
|
+
|
|
4
|
+
원래 PR의 head가 파이프라인 수정안의 머지 커밋이고 그 내용이 검증한 수정안과 같으면, 규칙 검사와
|
|
5
|
+
테스트와 모델 호출 없이 앞 커밋의 검사 결과와 수정안 검증의 결과를 옮겨 적는다. 여기서는 판정과
|
|
6
|
+
옮겨 적을 값의 계산만 한다. 조건이 하나라도 맞지 않으면 그 까닭(글)을 돌려주고, 부르는 쪽은 전체
|
|
7
|
+
검사를 한다. 의심스러우면 전체 검사 쪽이다: 틀린 결과를 "검증됨"으로 남기는 것이 가장 나쁜 실패다.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable, Collection, Sequence
|
|
11
|
+
from dataclasses import dataclass, replace
|
|
12
|
+
from typing import Final
|
|
13
|
+
|
|
14
|
+
from app.shared.db_pure import FixAttempt, Proposal, Run
|
|
15
|
+
from app.worker.diff_pure import line_after
|
|
16
|
+
from app.worker.doc_rules_pure import Found, RuleJudged
|
|
17
|
+
from app.worker.fix.fix_decision_pure import Decided
|
|
18
|
+
from app.worker.fix.fix_pure import MECHANICAL_BUNDLE, MechanicalFix
|
|
19
|
+
from app.worker.fix.model_fix_pure import MODEL_BUNDLE, ModelFix
|
|
20
|
+
from app.worker.rules import pr_check_pure, pr_description_pure
|
|
21
|
+
from app.worker.rules.pr_description_pure import PrDescription
|
|
22
|
+
from app.worker.test_run_pure import PytestRun
|
|
23
|
+
|
|
24
|
+
# 규칙 수정안의 묶음. 코멘트 수정안(feedback)은 규칙 검사의 결과를 고친 것이 아니라 넣지 않는다
|
|
25
|
+
RULE_BUNDLES: Final = frozenset({MECHANICAL_BUNDLE, MODEL_BUNDLE})
|
|
26
|
+
_SETTLED: Final = frozenset({"done", "error"})
|
|
27
|
+
NOT_MERGE_COMMIT: Final = (
|
|
28
|
+
"수정안의 머지 커밋이 아님" # 거의 모든 커밋의 까닭이라 로그에 남기지 않는다
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class CarriedFrom:
|
|
34
|
+
"""이 커밋의 결과를 옮겨 온 곳. 그래프 상태에 들어가고 결과 코멘트가 한 줄로 보인다."""
|
|
35
|
+
|
|
36
|
+
number: int # 머지한 수정안 PR
|
|
37
|
+
bundle: str # mechanical, model
|
|
38
|
+
verified_sha: str # 수정안을 검증한 원래 PR의 커밋
|
|
39
|
+
# 수정안이 고친 위반 중 모델 판단으로 찾아 도구로 재검사하지 못한 것 (4.8의 5번). 수정안 PR에
|
|
40
|
+
# 적었던 안내를 결과 코멘트에도 적는다
|
|
41
|
+
unverified: int = 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# 체크포인트에서 되살릴 수 있게 graph.py가 등록하는 타입
|
|
45
|
+
STATE_TYPES: Final = (("app.worker.merged_fix_pure", "CarriedFrom"),)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class VerifiedCheck:
|
|
50
|
+
"""수정안을 검증한 커밋의 검사가 체크포인트에 남긴 값."""
|
|
51
|
+
|
|
52
|
+
finished: bool # 그래프가 멈춘 node 없이 코멘트까지 갔다
|
|
53
|
+
base_sha: str | None # 그 검사가 규칙과 설정을 읽은 base 커밋
|
|
54
|
+
found: object # doc_rules
|
|
55
|
+
test_run: PytestRun | None
|
|
56
|
+
decisions: Decided | None
|
|
57
|
+
fix: MechanicalFix | ModelFix | None # 머지한 묶음의 수정 결과
|
|
58
|
+
pr_checks: object # PR 단위 확인의 결과. PR 규칙이 없으면 None
|
|
59
|
+
pr_description: object = None # PR 설명 확인의 결과. 끈 저장소면 None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def merged_proposal(proposals: Sequence[Proposal], head: str) -> Proposal | str:
|
|
63
|
+
"""head를 머지 커밋으로 가진 규칙 수정안. 없거나 옮겨 적을 수 없으면 까닭.
|
|
64
|
+
|
|
65
|
+
같은 커밋에서 만든 다른 묶음의 수정안이 있으면 옮겨 적지 않는다. 하나만 머지됐으면 다른 묶음의
|
|
66
|
+
수정안은 이번 작업이 닫고(superseded) 그 위반은 이 커밋에서 다시 고쳐야 하며, 둘 다 머지됐으면
|
|
67
|
+
두 번째 머지 커밋의 부모가 검증한 커밋이 아니다.
|
|
68
|
+
"""
|
|
69
|
+
merged = [p for p in proposals if p.state == "merged" and p.merge_commit == head]
|
|
70
|
+
if not merged:
|
|
71
|
+
return NOT_MERGE_COMMIT
|
|
72
|
+
if len(merged) > 1:
|
|
73
|
+
return "머지 커밋이 같은 수정안이 둘 이상"
|
|
74
|
+
(p,) = merged
|
|
75
|
+
if p.skill not in RULE_BUNDLES:
|
|
76
|
+
return f"규칙 수정안이 아님 ({p.skill})"
|
|
77
|
+
if p.attempt_id is None:
|
|
78
|
+
return "수정안에 저장한 수정 시도가 없음"
|
|
79
|
+
if any(q.id != p.id and q.head_sha == p.head_sha and q.skill in RULE_BUNDLES
|
|
80
|
+
for q in proposals): # fmt: skip
|
|
81
|
+
return "검증한 커밋에 다른 묶음의 수정안이 있음"
|
|
82
|
+
return p
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def attempt_problem(attempt: FixAttempt | None, p: Proposal) -> str | None:
|
|
86
|
+
"""수정안이 올린 시도가 검증을 통과한 패치를 저장했고 그 수정안의 것인지."""
|
|
87
|
+
if attempt is None or attempt.patch is None or attempt.file_hashes_json is None:
|
|
88
|
+
return "검증을 통과한 패치를 저장한 기록이 없음"
|
|
89
|
+
if (attempt.repo, attempt.pr_number, attempt.head_sha, attempt.bundle) != (
|
|
90
|
+
p.repo, p.pr_number, p.head_sha, p.skill,
|
|
91
|
+
): # fmt: skip
|
|
92
|
+
return "저장한 수정 시도가 수정안과 맞지 않음"
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def runs_problem(verified: Sequence[Run], head: Sequence[Run], pipeline_commit: str) -> str | None:
|
|
97
|
+
"""검사 기록으로 본 조건. verified는 검증한 커밋의 기록, head는 이 커밋의 기록이다.
|
|
98
|
+
|
|
99
|
+
- 이 커밋에 끝난 검사가 이미 있으면 옮겨 적지 않는다. 그 작업은 동기화가 배포 뒤 옛 코드의
|
|
100
|
+
결과를 다시 검사하려고 넣은 것(`new_pipeline`)이다. 옮겨 적기만 하면 옛 결과가 새 코드의
|
|
101
|
+
기록으로 남는다.
|
|
102
|
+
- 검증한 커밋의 끝난 검사가 모두 지금 코드의 것이어야 한다. 배포를 사이에 두면 옛 코드의
|
|
103
|
+
결과를 지금 코드의 기록(`pipeline_commit`)으로 남기게 된다.
|
|
104
|
+
"""
|
|
105
|
+
if any(r.state in _SETTLED for r in head):
|
|
106
|
+
return "이 커밋의 끝난 검사가 이미 있음"
|
|
107
|
+
done = [r for r in verified if r.state == "done"]
|
|
108
|
+
if not done:
|
|
109
|
+
return "검증한 커밋의 끝난 검사가 없음"
|
|
110
|
+
if any((r.pipeline_commit or "") != pipeline_commit for r in done):
|
|
111
|
+
return "검증한 커밋의 검사가 지금 파이프라인 코드의 것이 아님"
|
|
112
|
+
return None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def state_problem(
|
|
116
|
+
check: VerifiedCheck, *, bundle: str, attempt_id: int, base_sha: str | None
|
|
117
|
+
) -> str | None:
|
|
118
|
+
"""검증한 커밋의 체크포인트로 본 조건. 남은 일(승인 대기, 호출 상한으로 남은 판단, 다른 묶음의
|
|
119
|
+
수정)이 있으면 옮겨 적지 않는다.
|
|
120
|
+
|
|
121
|
+
PR 단위 확인의 결과는 옮겨 적는다. PR 단위 확인은 파이프라인의 수정안이 데려온 커밋을 PR의
|
|
122
|
+
커밋으로 세지 않으므로(`pr_check_pure.pipeline_commits`) 머지 커밋에서 다시 봐도 볼 것이 같다.
|
|
123
|
+
모델 판단으로 찾은 위반을 고친 수정안도 옮겨 적는다. 그 위반은 도구로 재검사하지 못한 것이고
|
|
124
|
+
(4.8의 5번) 수정안 PR에 그렇게 적혔으며 사람이 보고 머지했다. 같은 안내를 결과 코멘트에 적는다
|
|
125
|
+
(`unverified_count`).
|
|
126
|
+
|
|
127
|
+
PR 설명 확인의 결과도 옮겨 적는다(`carried_description`). PR 글도 사람의 커밋도 그대로이고
|
|
128
|
+
수정안의 변경은 PR의 변경으로 세지 않는다. 호출 상한으로 견주지 못했으면 처음부터 검사한다."""
|
|
129
|
+
if not check.finished:
|
|
130
|
+
return "검증한 커밋의 검사가 끝까지 가지 않음"
|
|
131
|
+
found, decisions, fix = check.found, check.decisions, check.fix
|
|
132
|
+
if not isinstance(found, Found) or check.test_run is None or decisions is None:
|
|
133
|
+
return "검증한 커밋의 규칙 결과, 테스트 결과, 수정 판단이 없음"
|
|
134
|
+
if check.base_sha != base_sha:
|
|
135
|
+
return "base가 그 뒤 바뀜"
|
|
136
|
+
if fix is None or not fix.ready or fix.attempt_id != attempt_id:
|
|
137
|
+
return "검증한 커밋의 수정 결과가 수정안의 시도와 다름"
|
|
138
|
+
if isinstance(fix, ModelFix) and fix.verification is None:
|
|
139
|
+
return "수정안의 검증 결과가 없음"
|
|
140
|
+
if pr_check_pure.judge_left(check.pr_checks):
|
|
141
|
+
return "호출 상한으로 남은 PR 단위 판단이 있음"
|
|
142
|
+
if pr_description_pure.description_left(check.pr_description):
|
|
143
|
+
return "호출 상한으로 견주지 못한 PR 설명 확인이 있음"
|
|
144
|
+
if any(isinstance(o, RuleJudged) and o.left for o in found.outcomes):
|
|
145
|
+
return "판단하지 못한 hunk가 남음"
|
|
146
|
+
if any(d.reason == "call_limit" for d in decisions.decisions):
|
|
147
|
+
return "호출 상한으로 정하지 못한 수정 판단이 남음"
|
|
148
|
+
if any(d.action == "fix" and d.method != bundle for d in decisions.decisions):
|
|
149
|
+
return "다른 묶음으로 고칠 위반이 있음"
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def merge_problem(
|
|
154
|
+
verified_sha: str, parents: Sequence[str], tree: str, expected: str
|
|
155
|
+
) -> str | None:
|
|
156
|
+
"""머지 커밋의 내용이 "검증한 커밋 + 저장한 패치"와 같은지. 부모에 검증한 커밋이 있어야 하고
|
|
157
|
+
(머지 커밋, 스쿼시, 리베이스 모두), 트리가 같아야 한다. 검증한 커밋 뒤에 원래 브랜치에 커밋이
|
|
158
|
+
더 올라온 뒤 머지했거나 머지에 다른 변경이 섞였으면 트리가 다르다."""
|
|
159
|
+
if verified_sha not in parents:
|
|
160
|
+
return "머지 커밋의 부모에 검증한 커밋이 없음"
|
|
161
|
+
if tree != expected:
|
|
162
|
+
return "머지 커밋의 내용이 검증한 수정안과 다름"
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def unverified_count(fix: MechanicalFix | ModelFix) -> int:
|
|
167
|
+
"""수정안이 고친 위반 중 도구로 재검사하지 못한 것의 수. 기계적 수정은 도구가 다시 본다."""
|
|
168
|
+
if isinstance(fix, ModelFix) and fix.verification is not None:
|
|
169
|
+
return fix.verification.unverified
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def fixed_ids(fix: MechanicalFix | ModelFix) -> frozenset[str]:
|
|
174
|
+
"""수정안이 고친 위반. 기계적 수정은 고친 뒤 없어진 것, 모델 수정은 출구 검사가 해소를 확인한
|
|
175
|
+
대상이다(크기 상한으로 넣지 못한 위반은 대상이 아니다)."""
|
|
176
|
+
return frozenset(fix.fixed if isinstance(fix, MechanicalFix) else fix.targets)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def carried(
|
|
180
|
+
found: Found,
|
|
181
|
+
decisions: Decided,
|
|
182
|
+
fixed: Collection[str],
|
|
183
|
+
patch: str,
|
|
184
|
+
lines_of: Callable[[str], Sequence[str] | None],
|
|
185
|
+
) -> tuple[Found, Decided] | str:
|
|
186
|
+
"""수정안이 고친 위반을 빼고, 남은 위반(고치지 않기로 한 것 등)을 머지 커밋의 줄 번호로 옮긴다.
|
|
187
|
+
|
|
188
|
+
lines_of(파일)은 머지 커밋의 그 파일 줄들이다(읽지 못하면 None). 패치가 남은 위반의 줄을
|
|
189
|
+
바꿨거나, 옮긴 줄의 내용이 위반의 줄 내용과 다르거나, 파일 단위 위반의 파일이 없으면 까닭을
|
|
190
|
+
돌려준다.
|
|
191
|
+
"""
|
|
192
|
+
kept = []
|
|
193
|
+
for v in found.violations:
|
|
194
|
+
if v.id in fixed:
|
|
195
|
+
continue
|
|
196
|
+
lines = lines_of(v.file)
|
|
197
|
+
if v.unit == "file" or v.line == 0:
|
|
198
|
+
if lines is None:
|
|
199
|
+
return f"남은 파일 위반의 파일을 머지 커밋에서 읽지 못함 ({v.file})"
|
|
200
|
+
kept.append(v)
|
|
201
|
+
continue
|
|
202
|
+
line = line_after(patch, v.file, v.line)
|
|
203
|
+
if line is None:
|
|
204
|
+
return f"수정안이 남은 위반의 줄을 바꿈 ({v.file}:{v.line})"
|
|
205
|
+
text = (v.line_text or "").strip()
|
|
206
|
+
if (
|
|
207
|
+
not text
|
|
208
|
+
or lines is None
|
|
209
|
+
or not 0 < line <= len(lines)
|
|
210
|
+
or lines[line - 1].strip() != text
|
|
211
|
+
):
|
|
212
|
+
return f"남은 위반의 줄을 머지 커밋에서 찾지 못함 ({v.file}:{v.line})"
|
|
213
|
+
kept.append(replace(v, line=line))
|
|
214
|
+
ids = {v.id for v in kept}
|
|
215
|
+
return (
|
|
216
|
+
replace(found, violations=tuple(kept)),
|
|
217
|
+
replace(
|
|
218
|
+
decisions, decisions=tuple(d for d in decisions.decisions if d.violation_id in ids)
|
|
219
|
+
),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def carried_description(description: PrDescription, patch: str) -> PrDescription | str:
|
|
224
|
+
"""검증한 커밋의 PR 설명 확인을 머지 커밋에 옮긴다. 더한 줄(head 쪽)을 가리킨 어긋남은 패치로 줄
|
|
225
|
+
번호를 옮기고, 지운 줄은 base의 번호라 그대로 둔다. 패치가 그 줄을 바꿨으면 까닭을 돌려준다
|
|
226
|
+
(처음부터 검사한다)."""
|
|
227
|
+
moved = []
|
|
228
|
+
for m in description.items:
|
|
229
|
+
if m.side != "new" or not m.file:
|
|
230
|
+
moved.append(m)
|
|
231
|
+
continue
|
|
232
|
+
line = line_after(patch, m.file, m.line)
|
|
233
|
+
if line is None:
|
|
234
|
+
return f"수정안이 PR 설명 확인이 가리킨 줄을 바꿈 ({m.file}:{m.line})"
|
|
235
|
+
moved.append(replace(m, line=line))
|
|
236
|
+
return replace(description, items=tuple(moved))
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""결과 코멘트의 PR 단위 확인 부분 (docs/DESIGN.md 4.5 끝, 4.9). 판정을 새로 내지 않는다.
|
|
2
|
+
|
|
3
|
+
`PrChecks` 하나만 받는다. 규칙의 인용, 커밋 제목, PR 글의 인용, 모델의 이유, 패턴, 실패 이유는 모두
|
|
4
|
+
믿지 않는 글이라 코드 스팬 안에만 넣는다 (app/worker/markdown_pure.py). 커밋은 짧은 해시로 보인다.
|
|
5
|
+
코드 위반과 따로 된 목록이고, 수정안을 만들지 않는다는 것을 머리줄에 적는다 (4-13).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import replace
|
|
11
|
+
from typing import Final
|
|
12
|
+
|
|
13
|
+
from app.worker.markdown_pure import inline_code
|
|
14
|
+
from app.worker.rule_pure import Rule
|
|
15
|
+
from app.worker.rules.pr_check_pure import (
|
|
16
|
+
FACT_LABEL,
|
|
17
|
+
WHERE_LABEL,
|
|
18
|
+
PrChecks,
|
|
19
|
+
PrRuleResult,
|
|
20
|
+
PrViolation,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
VIOLATION: Final = "⚠️"
|
|
24
|
+
TITLE: Final = "**PR 단위:**"
|
|
25
|
+
NOTIFY_ONLY: Final = "알리기만 함 (커밋 메시지, PR 글, 브랜치 이름은 수정안으로 고칠 수 없음)"
|
|
26
|
+
HEAD: Final = "PR 단위 위반 (알리기만 하고 수정안은 만들지 않음)"
|
|
27
|
+
MAX_SHOWN_PER_RULE: Final = 10
|
|
28
|
+
MAX_QUOTE_CHARS: Final = 200
|
|
29
|
+
MAX_RULE_CHARS: Final = 500
|
|
30
|
+
MAX_DETAIL_CHARS: Final = 300
|
|
31
|
+
RERUN_HINT: Final = "`/fix`로 다시 돌릴 수 있습니다."
|
|
32
|
+
# 제목·본문만 고친 것(pull_request.edited)은 아직 다시 확인하지 않는다 (DESIGN 4.5 끝, 12.2)
|
|
33
|
+
RECHECK_HINT: Final = (
|
|
34
|
+
"PR 제목·본문을 고쳤으면 `/recheck`를 달아 다시 확인하세요. 커밋 없이 고친 것은 저절로 다시 "
|
|
35
|
+
"보지 않습니다."
|
|
36
|
+
)
|
|
37
|
+
_UNCHECKED_TEXT: Final[Mapping[str, str]] = {
|
|
38
|
+
"plan_none": "모델이 PR의 커밋, 글, 바뀐 파일로는 판단하지 못함",
|
|
39
|
+
"cap": "호출 상한에 걸려 확인 방법을 정하지 못함 (다음 검사가 이어서 합니다)",
|
|
40
|
+
"model_failed": "확인 방법을 정하는 모델 호출이 실패함",
|
|
41
|
+
"tool_unavailable": "샌드박스 도구를 준비하지 못함",
|
|
42
|
+
"run_failed": "패턴을 이 PR에 맞추지 못함",
|
|
43
|
+
"no_facts": "PR 사실을 읽지 못함",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def title(checks: PrChecks | None) -> str | None:
|
|
48
|
+
"""PR 단위 위반이 있을 때만 결론 아래에 붙는 따로 된 줄. 코드 위반의 결론과 섞지 않는다."""
|
|
49
|
+
if checks is None or not checks.violations:
|
|
50
|
+
return None
|
|
51
|
+
rules = len({v.rule_id for v in checks.violations})
|
|
52
|
+
return f"{TITLE} {VIOLATION} 위반 {len(checks.violations)}건 (규칙 {rules}개) · {NOTIFY_ONLY}"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def violations(checks: PrChecks) -> list[str]:
|
|
56
|
+
"""PR 단위 위반의 목록 (펼친 부분). 없으면 빈 목록."""
|
|
57
|
+
if not checks.violations:
|
|
58
|
+
return []
|
|
59
|
+
lines = ["", f"**{HEAD}:**", *_violations(checks)]
|
|
60
|
+
if any(v.where in ("pr_body", "pr_title") for v in checks.violations):
|
|
61
|
+
lines.append(RECHECK_HINT)
|
|
62
|
+
return lines
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def unresolved(checks: PrChecks) -> list[str]:
|
|
66
|
+
"""확인하지 못했거나 일부만 확인한 PR 단위 규칙과 까닭 (펼친 부분). 없으면 빈 목록."""
|
|
67
|
+
lines: list[str] = []
|
|
68
|
+
if checks.note:
|
|
69
|
+
lines += ["", "PR 사실을 읽지 못해 PR 단위 규칙을 확인하지 못함: "
|
|
70
|
+
+ inline_code(checks.note, MAX_DETAIL_CHARS)] # fmt: skip
|
|
71
|
+
partial = [r for r in checks.results if r.partial]
|
|
72
|
+
if partial:
|
|
73
|
+
lines += ["", "상한을 넘어 일부만 확인한 PR 단위 규칙:"]
|
|
74
|
+
lines += [f"- `{r.rule.id}` · {inline_code(r.partial, MAX_DETAIL_CHARS)}" for r in partial]
|
|
75
|
+
capped = [r for r in checks.results if r.status == "left" and r.kind == "cap"]
|
|
76
|
+
if capped:
|
|
77
|
+
why = inline_code(capped[0].detail, MAX_DETAIL_CHARS)
|
|
78
|
+
lines += ["", f"모델 호출 상한에 걸려 처리하지 못함: PR 단위 판단 {len(capped)}개 규칙 "
|
|
79
|
+
f"({why}). {RERUN_HINT}"] # fmt: skip
|
|
80
|
+
failed = [r for r in checks.results if r.status == "left" and r.kind != "cap"]
|
|
81
|
+
unchecked = [r for r in checks.results if r.status == "unchecked"]
|
|
82
|
+
if failed or unchecked:
|
|
83
|
+
lines += ["", f"확인하지 못한 PR 단위 규칙 {len(failed) + len(unchecked)}개:"]
|
|
84
|
+
for r in failed:
|
|
85
|
+
why = inline_code(r.detail, MAX_DETAIL_CHARS)
|
|
86
|
+
lines.append(f"- `{r.rule.id}` {_quote(r.rule)} · 모델 판단 실패 (다음 검사가 다시 "
|
|
87
|
+
f"묻습니다): {why}") # fmt: skip
|
|
88
|
+
for r in unchecked:
|
|
89
|
+
text = _UNCHECKED_TEXT.get(r.kind or "", "확인하지 못함")
|
|
90
|
+
detail = f": {inline_code(r.detail, MAX_DETAIL_CHARS)}" if r.detail else ""
|
|
91
|
+
lines.append(f"- `{r.rule.id}` {_quote(r.rule)} · {text}{detail}")
|
|
92
|
+
return lines
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def details(checks: PrChecks) -> list[str]:
|
|
96
|
+
"""PR 단위 확인의 사용량과 위반이 없는 규칙의 확인 방법 (접는 블록 안)."""
|
|
97
|
+
lines = ["", f"PR 단위 확인: {_summary(checks)}"]
|
|
98
|
+
clean = [r for r in checks.results if r.status in ("checked", "not_applicable")
|
|
99
|
+
and not any(v.rule_id == r.rule.id for v in checks.violations)] # fmt: skip
|
|
100
|
+
if clean:
|
|
101
|
+
lines += ["", "PR 단위 규칙 중 위반 없음:"]
|
|
102
|
+
lines += [f"- `{r.rule.id}` {_quote(r.rule)} · {_how(r)}" for r in clean]
|
|
103
|
+
dismissed = [(r, v) for r in checks.results for v in r.dismissed]
|
|
104
|
+
if dismissed:
|
|
105
|
+
lines += ["", f"PR 패턴이 잡았지만 모델이 위반이 아니라고 판단함 {len(dismissed)}건:"]
|
|
106
|
+
lines += [f"- `{r.rule.id}` {_where(replace(v, why=''))} · 패턴 {_regex(r.decl.pattern)}"
|
|
107
|
+
if r.decl else f"- `{r.rule.id}` {_where(replace(v, why=''))}"
|
|
108
|
+
for r, v in dismissed] # fmt: skip
|
|
109
|
+
return lines
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _summary(checks: PrChecks) -> str:
|
|
113
|
+
usage = checks.usage
|
|
114
|
+
parts = [f"규칙 {len(checks.results)}개"]
|
|
115
|
+
if not checks.note:
|
|
116
|
+
skipped = []
|
|
117
|
+
if checks.skipped_merge:
|
|
118
|
+
skipped.append(f"merge 커밋 {checks.skipped_merge}개")
|
|
119
|
+
if checks.skipped_pipeline:
|
|
120
|
+
skipped.append(f"파이프라인 수정안 커밋 {checks.skipped_pipeline}개")
|
|
121
|
+
commits = f"커밋 {checks.commits}개"
|
|
122
|
+
if skipped:
|
|
123
|
+
commits += f" (보지 않음: {', '.join(skipped)})"
|
|
124
|
+
parts.append(commits)
|
|
125
|
+
calls = f"모델 호출 {usage.plan_calls + usage.judge_calls}회"
|
|
126
|
+
if usage.plan_calls or usage.judge_calls:
|
|
127
|
+
calls += f" (확인 방법 정하기 {usage.plan_calls}, 판단 {usage.judge_calls})"
|
|
128
|
+
parts.append(calls)
|
|
129
|
+
parts.append(f"저장된 결과 {usage.cached}건 사용")
|
|
130
|
+
if usage.models:
|
|
131
|
+
parts.append(", ".join(inline_code(m, 80) for m in usage.models))
|
|
132
|
+
if usage.dropped:
|
|
133
|
+
parts.append(f"버린 답 {usage.dropped}건 (이 PR의 커밋이나 글을 그대로 가리키지 않음)")
|
|
134
|
+
if usage.plan_calls or usage.judge_calls:
|
|
135
|
+
parts.append(f"토큰 입력 {usage.input_tokens}, 출력 {usage.output_tokens}")
|
|
136
|
+
return " · ".join(parts)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _violations(checks: PrChecks) -> list[str]:
|
|
140
|
+
if not checks.violations:
|
|
141
|
+
return []
|
|
142
|
+
by_rule = {r.rule.id: r for r in checks.results}
|
|
143
|
+
grouped: dict[str, list[PrViolation]] = {}
|
|
144
|
+
for v in checks.violations:
|
|
145
|
+
grouped.setdefault(v.rule_id, []).append(v)
|
|
146
|
+
lines = []
|
|
147
|
+
for rule_id, found in grouped.items():
|
|
148
|
+
result = by_rule[rule_id]
|
|
149
|
+
lines += [
|
|
150
|
+
f"- `{rule_id}` {_quote(result.rule)} · {len(found)}건",
|
|
151
|
+
f" 출처: {_source(result.rule)} · 확인: {_how(result)}",
|
|
152
|
+
]
|
|
153
|
+
lines += [f" - {_where(v)}" for v in found[:MAX_SHOWN_PER_RULE]]
|
|
154
|
+
if len(found) > MAX_SHOWN_PER_RULE:
|
|
155
|
+
lines.append(f" - 외 {len(found) - MAX_SHOWN_PER_RULE}건")
|
|
156
|
+
return lines
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _where(v: PrViolation) -> str:
|
|
160
|
+
place = f"커밋 `{v.sha[:7]}`" if v.where == "commit" else WHERE_LABEL[v.where]
|
|
161
|
+
if v.quote:
|
|
162
|
+
place += f" {inline_code(v.quote, MAX_QUOTE_CHARS)}"
|
|
163
|
+
elif v.where in ("pr_body", "pr_title"):
|
|
164
|
+
place += " (빠진 내용)"
|
|
165
|
+
if v.why:
|
|
166
|
+
place += f" · {inline_code(v.why, MAX_DETAIL_CHARS)}"
|
|
167
|
+
return place
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _how(r: PrRuleResult) -> str:
|
|
171
|
+
decl = r.decl
|
|
172
|
+
if decl is None:
|
|
173
|
+
return "확인 방법 없음"
|
|
174
|
+
gate = f", 바뀐 파일이 {_regex(decl.when_changed)}에 맞을 때만" if decl.when_changed else ""
|
|
175
|
+
if r.method == "pattern":
|
|
176
|
+
verb = "맞아야 함" if decl.condition == "must_match" else "맞으면 안 됨"
|
|
177
|
+
how = f"PR 패턴 ({FACT_LABEL[decl.fact]}이 {_regex(decl.pattern)}에 {verb}{gate})"
|
|
178
|
+
else:
|
|
179
|
+
why = (
|
|
180
|
+
"PR 패턴이 예시 확인을 두 번 통과하지 못함" if r.route == "examples"
|
|
181
|
+
else "글의 뜻을 읽어야 한다고 모델이 답함"
|
|
182
|
+
) # fmt: skip
|
|
183
|
+
how = f"모델 판단 ({FACT_LABEL[decl.fact]}, {why}{gate})"
|
|
184
|
+
if r.status == "not_applicable":
|
|
185
|
+
how += " · 이 PR은 바뀐 파일이 조건에 맞지 않아 해당 없음"
|
|
186
|
+
return how
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _regex(pattern: str) -> str:
|
|
190
|
+
"""정규식은 JSON 문자열로 보인다. 앞뒤 공백과 줄바꿈이 뜻을 가진다 ("^feat: ")."""
|
|
191
|
+
return inline_code(json.dumps(pattern, ensure_ascii=False), 160)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _quote(rule: Rule) -> str:
|
|
195
|
+
return inline_code(rule.text, MAX_RULE_CHARS)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _source(rule: Rule) -> str:
|
|
199
|
+
source = rule.source
|
|
200
|
+
where = f"{source.file} > {source.section}" if source.section else source.file
|
|
201
|
+
return inline_code(where, 200)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""결과 코멘트의 PR 설명 절 (docs/DESIGN.md 4.5 끝 "PR 설명과 diff 견주기", 4.9). 판정을 새로
|
|
2
|
+
내지 않는다.
|
|
3
|
+
|
|
4
|
+
`PrDescription` 하나만 받는다. 맨 위 결론 줄 하나("**PR 설명:**")와, 펼친 부분에는 사람이 할 일이
|
|
5
|
+
있는 것(어긋난 곳, 견주지 못한 까닭, 잘라서 일부만 견준 것)만, 접는 블록에는 사용량을 둔다. 기계적인
|
|
6
|
+
분류 이름을 쓰지 않고 리뷰어가 말하듯 적는다. 모델이 쓴 글과 파일 경로는 믿지 않는 글이라 코드 스팬
|
|
7
|
+
안에만 넣는다 (app/worker/markdown_pure.py).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from typing import Final
|
|
12
|
+
|
|
13
|
+
from app.worker.markdown_pure import inline_code
|
|
14
|
+
from app.worker.rules.pr_description_pure import Mismatch, PrDescription
|
|
15
|
+
|
|
16
|
+
TITLE: Final = "**PR 설명:**"
|
|
17
|
+
MATCHED: Final = f"{TITLE} 설명한 내용과 변경이 맞습니다."
|
|
18
|
+
EMPTY: Final = f"{TITLE} 설명이 비어 있어 견주지 못했습니다."
|
|
19
|
+
HEAD: Final = "**PR 설명과 다른 곳:**"
|
|
20
|
+
LABEL: Final[Mapping[str, str]] = {
|
|
21
|
+
"unrelated": "PR과 관련 없는 수정",
|
|
22
|
+
"missing": "설명에는 있는데 코드에 없음",
|
|
23
|
+
"different": "설명과 다름",
|
|
24
|
+
}
|
|
25
|
+
_GAP_TEXT: Final[Mapping[str, str]] = {
|
|
26
|
+
"cap": "모델 호출 상한에 걸림",
|
|
27
|
+
"model_failed": "모델 호출이 실패함",
|
|
28
|
+
"no_facts": "PR 글을 읽지 못함",
|
|
29
|
+
"no_diff": "바뀐 내용이 없음",
|
|
30
|
+
}
|
|
31
|
+
MAX_SUMMARY_CHARS: Final = 300
|
|
32
|
+
MAX_DETAIL_CHARS: Final = 300
|
|
33
|
+
# PR 제목·본문만 고친 것(pull_request.edited)은 다시 보지 않는다 (4.5 끝)
|
|
34
|
+
RECHECK_HINT: Final = (
|
|
35
|
+
"PR 제목·본문을 고쳤으면 `/recheck`를 달아 다시 견주세요. 커밋 없이 고친 것은 저절로 다시 "
|
|
36
|
+
"보지 않습니다."
|
|
37
|
+
)
|
|
38
|
+
EMPTY_HINT: Final = "PR 본문이나 커밋 메시지에 무엇을 바꿨는지 적고 `/recheck`를 달면 견줍니다."
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def title(d: PrDescription | None) -> str | None:
|
|
42
|
+
"""맨 위 결론 줄. 이 확인을 끈 저장소나 돌기 전에 끝난 검사는 None."""
|
|
43
|
+
if d is None:
|
|
44
|
+
return None
|
|
45
|
+
match d.status:
|
|
46
|
+
case "empty":
|
|
47
|
+
return EMPTY
|
|
48
|
+
case "unchecked":
|
|
49
|
+
return f"{TITLE} 견주지 못했습니다 ({_GAP_TEXT.get(d.gap, '까닭을 모름')})."
|
|
50
|
+
case _:
|
|
51
|
+
if not d.items:
|
|
52
|
+
return MATCHED
|
|
53
|
+
return f"{TITLE} 설명과 다른 곳이 {len(d.items)}건 있습니다."
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def expanded(d: PrDescription | None) -> list[str]:
|
|
57
|
+
"""펼친 부분. 사람이 할 일이 없으면 빈 목록이다. 맞게 된 항목은 나열하지 않는다."""
|
|
58
|
+
if d is None:
|
|
59
|
+
return []
|
|
60
|
+
lines: list[str] = []
|
|
61
|
+
if d.status == "empty":
|
|
62
|
+
return ["", EMPTY_HINT]
|
|
63
|
+
if d.status == "unchecked":
|
|
64
|
+
if d.detail:
|
|
65
|
+
lines += ["", f"PR 설명을 견주지 못한 까닭: {inline_code(d.detail, MAX_DETAIL_CHARS)}"]
|
|
66
|
+
if d.gap in ("cap", "model_failed"):
|
|
67
|
+
lines.append("다음 커밋의 검사나 `/recheck`가 다시 견줍니다.")
|
|
68
|
+
return lines
|
|
69
|
+
if d.items:
|
|
70
|
+
lines += ["", HEAD, *(_item(m) for m in d.items), RECHECK_HINT]
|
|
71
|
+
notes = []
|
|
72
|
+
if d.diff_cut:
|
|
73
|
+
notes.append(
|
|
74
|
+
f"변경이 커서 바뀐 파일 {d.files}개 중 {d.files - d.shown}개는 diff를 다 보이지 "
|
|
75
|
+
"못했습니다. 그 파일은 모델이 필요할 때 작업 폴더에서 읽었습니다."
|
|
76
|
+
)
|
|
77
|
+
if d.text_cut:
|
|
78
|
+
notes.append("PR 글이 길어 앞부분만 견줬습니다.")
|
|
79
|
+
if notes:
|
|
80
|
+
lines += ["", " ".join(notes)]
|
|
81
|
+
return lines
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def folded(d: PrDescription | None) -> list[str]:
|
|
85
|
+
"""접는 블록에 넣는 사용량 줄. 모델을 부르지도 저장된 답을 쓰지도 않았으면 빈 목록이다."""
|
|
86
|
+
if d is None:
|
|
87
|
+
return []
|
|
88
|
+
usage = d.usage
|
|
89
|
+
if not usage.calls and not usage.cached:
|
|
90
|
+
return []
|
|
91
|
+
parts = [f"모델 호출 {usage.calls}회"]
|
|
92
|
+
if usage.calls:
|
|
93
|
+
parts.append(f"읽기 도구 {usage.tool_uses}회")
|
|
94
|
+
parts.append(f"저장된 결과 {usage.cached}건 사용")
|
|
95
|
+
if usage.models:
|
|
96
|
+
parts.append(", ".join(inline_code(m, 80) for m in usage.models))
|
|
97
|
+
if usage.dropped:
|
|
98
|
+
parts.append(f"버린 답 {usage.dropped}건 (PR 글이나 바뀐 줄을 그대로 가리키지 않음)")
|
|
99
|
+
if usage.calls:
|
|
100
|
+
parts.append(f"토큰 입력 {usage.input_tokens}, 출력 {usage.output_tokens}")
|
|
101
|
+
if usage.earlier:
|
|
102
|
+
parts.append(f"지난 결과를 주고 다시 견줌 (지난 어긋남 {usage.earlier_items}건 중 유지 "
|
|
103
|
+
f"{usage.kept_earlier}건)") # fmt: skip
|
|
104
|
+
return ["", "PR 설명 확인: " + " · ".join(parts)]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _item(m: Mismatch) -> str:
|
|
108
|
+
line = f"- {LABEL[m.kind]}: {inline_code(m.summary, MAX_SUMMARY_CHARS)}"
|
|
109
|
+
if m.file:
|
|
110
|
+
place = inline_code(f"{m.file}:{m.line}", 200)
|
|
111
|
+
line += f" ({place}{', 지운 줄' if m.side == 'old' else ''})"
|
|
112
|
+
return line
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""워커 시작 전 점검: GitHub 인증(gh 로그인 또는 토큰), claude 로그인, Docker, Redis
|
|
2
|
+
(docs/DESIGN.md 보안·인증 > Preflight). `npx pr-proof configure`의 끝 확인도 같은 함수를 쓴다."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import subprocess
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from redis import Redis
|
|
12
|
+
from redis.exceptions import RedisError
|
|
13
|
+
|
|
14
|
+
from app.shared import github_auth
|
|
15
|
+
from app.shared import notify as macos
|
|
16
|
+
from app.shared.ops_alert_pure import Kind
|
|
17
|
+
from app.worker import github
|
|
18
|
+
from app.worker.ai.claude_cli import claude_env
|
|
19
|
+
from app.worker.sandbox.docker_cli import minimal_env
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Check:
|
|
24
|
+
name: str
|
|
25
|
+
ok: bool
|
|
26
|
+
hint: str
|
|
27
|
+
alert: Kind # 실패하면 띄우는 운영 알림의 종류 (6-4)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _command_ok(args: list[str]) -> bool:
|
|
31
|
+
try:
|
|
32
|
+
return (
|
|
33
|
+
subprocess.run(
|
|
34
|
+
args, capture_output=True, env=minimal_env(), timeout=30, check=False
|
|
35
|
+
).returncode
|
|
36
|
+
== 0
|
|
37
|
+
)
|
|
38
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
39
|
+
return False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _redis_ok(redis: Redis) -> bool:
|
|
43
|
+
try:
|
|
44
|
+
return bool(redis.ping())
|
|
45
|
+
except RedisError:
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _claude_auth_status() -> str:
|
|
50
|
+
"""`claude auth status`의 JSON 출력. 비용이 들지 않는다. 실행하지 못하면 빈 문자열."""
|
|
51
|
+
try:
|
|
52
|
+
return subprocess.run(
|
|
53
|
+
["claude", "auth", "status"],
|
|
54
|
+
capture_output=True,
|
|
55
|
+
text=True,
|
|
56
|
+
env=claude_env(),
|
|
57
|
+
timeout=30,
|
|
58
|
+
check=False,
|
|
59
|
+
).stdout
|
|
60
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
61
|
+
return ""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def claude_login_ok(status_json: str, now: datetime) -> bool:
|
|
65
|
+
"""`loggedIn`이 참이고 `loginExpiresAt`이 지나지 않았으면 통과.
|
|
66
|
+
|
|
67
|
+
만료 시각이 없으면(null) 로그인만 본다. 형식을 읽지 못하면 실패로 본다.
|
|
68
|
+
"""
|
|
69
|
+
try:
|
|
70
|
+
data = json.loads(status_json)
|
|
71
|
+
except json.JSONDecodeError:
|
|
72
|
+
return False
|
|
73
|
+
if not isinstance(data, dict) or data.get("loggedIn") is not True:
|
|
74
|
+
return False
|
|
75
|
+
expires = data.get("loginExpiresAt")
|
|
76
|
+
if expires is None:
|
|
77
|
+
return True
|
|
78
|
+
if not isinstance(expires, str):
|
|
79
|
+
return False
|
|
80
|
+
try:
|
|
81
|
+
expires_at = datetime.fromisoformat(expires)
|
|
82
|
+
except ValueError:
|
|
83
|
+
return False
|
|
84
|
+
if expires_at.tzinfo is None:
|
|
85
|
+
return False
|
|
86
|
+
return expires_at > now
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _gh_auth_ok() -> bool:
|
|
90
|
+
"""고른 인증(gh 로그인 또는 토큰)으로 `gh auth status`가 통과하는지. 토큰은 gh에만 넘긴다."""
|
|
91
|
+
try:
|
|
92
|
+
github.run_gh(github_auth.status_args())
|
|
93
|
+
except github.GitHubError:
|
|
94
|
+
return False
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def run_checks(
|
|
99
|
+
redis: Redis,
|
|
100
|
+
command_ok: Callable[[list[str]], bool] = _command_ok,
|
|
101
|
+
claude_status: Callable[[], str] = _claude_auth_status,
|
|
102
|
+
now: datetime | None = None,
|
|
103
|
+
gh_ok: Callable[[], bool] = _gh_auth_ok,
|
|
104
|
+
config_dir: Path | None = None,
|
|
105
|
+
) -> list[Check]:
|
|
106
|
+
claude_ok = claude_login_ok(claude_status(), now or datetime.now(UTC))
|
|
107
|
+
return [
|
|
108
|
+
Check(
|
|
109
|
+
"GitHub 인증", gh_ok(), github_auth.hint(config_dir), github_auth.alert_kind(config_dir)
|
|
110
|
+
),
|
|
111
|
+
Check("Claude 로그인", claude_ok, "claude 실행 후 /login", "claude_login"),
|
|
112
|
+
Check("Docker", command_ok(["docker", "info"]), "Docker Desktop 실행", "docker"),
|
|
113
|
+
Check("Redis", _redis_ok(redis), "docker compose up -d", "redis"),
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def failures(checks: list[Check]) -> list[str]:
|
|
118
|
+
return [f"{c.name} 실패 → {c.hint}" for c in checks if not c.ok]
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def alert(checks: list[Check], data_dir: Path) -> None:
|
|
122
|
+
"""실패한 확인마다 macOS 알림을 띄운다. 같은 종류는 30분에 한 번이다(표시는 data_dir의 파일)."""
|
|
123
|
+
for check in checks:
|
|
124
|
+
if not check.ok:
|
|
125
|
+
macos.send(check.alert, data_dir)
|