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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Eunryong
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/Procfile
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,301 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pr-proof
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
PR을 두 가지로 다루는 도구다.
|
|
4
|
+
|
|
5
|
+
1. **팀의 규칙.** PR이 팀의 규칙을 어긴 곳을 찾아, 테스트로 확인한 수정안을 별도 PR로 올린다. 규칙은 파이프라인에 들어 있지 않다. 대상 저장소의 README와 CONTRIBUTING에 사람이 문장으로 적어 둔 것을 읽는다.
|
|
6
|
+
2. **리뷰 코멘트.** PR에 달린 Copilot과 팀원의 코멘트를 읽고, 받아들일 것은 고쳐서 수정안 PR로 올리고, 받아들이지 않을 것은 까닭과 함께 답글로 거절하고, 스레드를 해결됨으로 정리한다.
|
|
7
|
+
|
|
8
|
+
- 규칙을 **그 저장소의 문서**에서 읽는다. "`orders/` 아래 모듈은 `print`를 쓰지 않는다" 같은 문장이 곧 규칙이다.
|
|
9
|
+
- 위반을 알리는 데서 끝내지 않고 **고친다.** 모델이 규칙 검사와 테스트를 도구로 돌려 가며 고치고, 고친 줄을 실행하는 테스트가 없으면 테스트도 만든다.
|
|
10
|
+
- 모델이 쓴 변경은 **프로그램이 다시 검사한 뒤에만** 올라간다(허용 범위, 비밀값, 규칙 재검사, 테스트). 원래 PR을 직접 고치지 않고 수정안 PR을 따로 연다. 머지할지는 사람이 정한다.
|
|
11
|
+
- 리뷰 코멘트를 **무조건 따르지 않는다.** 팀의 규칙과 PR의 흐름을 보고 받아들일지 정한다. 규칙 검사가 이미 고친 것은 다시 고치지 않는다.
|
|
12
|
+
|
|
13
|
+
지금은 Python 저장소와 GitHub만 지원한다. 자기 컴퓨터에서 자기 `gh`·`claude` 로그인으로 돌리는 로컬 서버다.
|
|
14
|
+
|
|
15
|
+
> **써 보고 알려 주세요.** 이 프로젝트는 실제 저장소에서 어디가 부족한지 듣고 싶어서 공개했다. 규칙을 잘못 읽었거나, 위반이 아닌 것을 잡았거나, 수정안이 쓸모없었다면 [이슈](https://github.com/Eunryong/pr-proof/issues/new/choose)로 알려 주면 된다. 무엇을 적으면 좋은지는 [맨 아래](#후기와-제보)에 있다.
|
|
16
|
+
|
|
17
|
+
## 어떻게 보이나
|
|
18
|
+
|
|
19
|
+
PR을 열면 결과 코멘트 하나가 달린다. 맨 위가 결론이다.
|
|
20
|
+
|
|
21
|
+
위반이 없을 때:
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
**테스트:** 통과 (6개)
|
|
25
|
+
**규칙:** ✅ 위반 없음 · 규칙 4개를 확인함 (도구·검사기 1개, 모델 판단 1개, 테스트·정적 검사 결과 1개, PR 단위 1개)
|
|
26
|
+
|
|
27
|
+
▸ 자세히: 규칙별 확인 방법, 모델 호출, 바뀐 줄 커버리지
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
위반이 있을 때(줄여 적음):
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
**테스트:** 통과 (6개)
|
|
34
|
+
**규칙:** ⚠️ 위반 2건 (규칙 1개) · 수정안 #31
|
|
35
|
+
|
|
36
|
+
위반:
|
|
37
|
+
- R-readme-1 `orders/` 아래 모듈은 `print`를 쓰지 않는다. · 2건
|
|
38
|
+
출처: README.md > 코드 규칙 > 출력 · 모델이 쓴 검사기 (ast-grep)
|
|
39
|
+
- orders/a.py:2 · 고칠 대상 (모델 수정: 로거로 바꾼다) · 수정안 #31
|
|
40
|
+
직접 고쳐야 함 1건 (고치면 동작이 바뀜 1건)
|
|
41
|
+
|
|
42
|
+
**모델 수정안:** 위반 1건을 고쳤습니다. 검증: 테스트 6개가 수정 전과 같은 결과로 통과,
|
|
43
|
+
대상 위반 1건 해소, 새 위반 없음. 수정안 PR #31을 열었습니다.
|
|
44
|
+
- 만든 테스트 1개 (대상 위반 1건을 실행함): tests/test_pipeline_orders_logging.py
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
PR의 제목·본문·커밋 메시지와 실제 변경이 다르면 "PR 설명:" 줄과 항목이 더 붙는다(알리기만 한다).
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
**PR 설명:** 설명과 다른 곳이 1건 있습니다.
|
|
51
|
+
|
|
52
|
+
- PR과 관련 없는 수정: `config.py에서 기본 타임아웃을 30초에서 5초로 줄였습니다. 설명에는 파서 수정만 적혀 있습니다.` (`config.py:1`)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
수정안 PR(`pipeline/pr-<n>-fix-…`)은 원래 PR의 브랜치를 base로 한다. 머지하면 원래 PR에 들어가고, 닫으면 같은 줄을 다시 제안하지 않는다.
|
|
56
|
+
|
|
57
|
+
리뷰 코멘트에는 그 스레드에 답글이 달린다.
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
[Copilot] average_quantity() divides by len(quantities) without checking for an empty list …
|
|
61
|
+
[pr-proof] 반영했습니다. 수정안 #32
|
|
62
|
+
까닭 (모델의 판단): orders/stats.py의 average_quantity가 빈 목록에서 0으로 나눈다.
|
|
63
|
+
→ 수정안 #32가 머지되면 스레드를 Resolved (Addressed)로 바꾼다
|
|
64
|
+
|
|
65
|
+
[Copilot] Use print() here instead of the logger so the output is visible …
|
|
66
|
+
[pr-proof] 반영하지 않습니다.
|
|
67
|
+
까닭 (모델의 판단): README의 규칙이 orders/ 아래에서 print를 쓰지 않게 정한다.
|
|
68
|
+
→ 스레드를 Resolved (Won't fix)로 바꾼다
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## 어떻게 도는가
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
GitHub 웹훅 ─▶ api (서명 확인, 큐 등록, 동기화) ─▶ Redis 큐 ─▶ 워커
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
워커가 PR 하나에 하는 일:
|
|
78
|
+
|
|
79
|
+
1. **규칙 읽기.** base 브랜치의 문서에서 규칙을 읽는다. 저장소에 린터 설정이 있으면 그 설정도 팀이 정한 규칙으로 본다.
|
|
80
|
+
2. **확인 방법 정하기.** 규칙마다 그 규칙을 확인할 수 있는 린터 → 모델이 쓴 검사기(ast-grep 등, 예시로 시험한다) → 모델의 직접 판단 순서로 고른다. 커밋 메시지·PR 본문의 규칙과 "테스트가 통과해야 한다" 같은 규칙은 따로 본다.
|
|
81
|
+
3. **위반 찾기.** PR이 바꾼 줄만 본다. 린터나 검사기가 잡은 것은 후보로 보고, 고칠지 정하는 단계에서 모델이 코드를 읽어 위반이 아니라고 하면 위반으로 세지 않는다.
|
|
82
|
+
규칙과 따로, 모델이 PR의 제목·본문·커밋 메시지와 diff를 견주어 설명에 없는 동작 변경, 설명에는 있는데 코드에 없는 것, 설명과 다른 것을 알린다. `.pipeline.yaml`의 `pr_description.enabled: false`로 끈다.
|
|
83
|
+
4. **테스트.** Docker 샌드박스에서 저장소의 테스트를 돌려 기준선을 잡는다.
|
|
84
|
+
5. **고칠지 정하기.** 그 파일 안에서 고칠 수 있으면 고치는 것이 기본이다. 다른 파일을 바꿔야 하거나 동작이 바뀌면 까닭과 함께 사람에게 남긴다.
|
|
85
|
+
6. **고치기.** 모델이 규칙 검사와 샌드박스 테스트를 도구로 불러 가며 고친다. 있던 테스트가 그 줄을 실행하지 않으면 테스트를 먼저 만든다.
|
|
86
|
+
7. **출구 검사.** 올리기 직전에 프로그램이 허용 범위, 비밀값, 규칙 재검사, 테스트를 다시 확인한다.
|
|
87
|
+
8. **전달.** 통과한 것만 수정안 PR로 올리고 결과 코멘트를 고친다.
|
|
88
|
+
|
|
89
|
+
리뷰 코멘트가 달리면 워커가 따로 한 번 더 돈다:
|
|
90
|
+
|
|
91
|
+
1. **겹침 가리기.** 수정안이 이미 고친 줄을 가리키는 코멘트는 그 수정안에 잇고 끝낸다.
|
|
92
|
+
2. **판단.** 남은 코멘트를 팀의 규칙, PR의 제목·본문·커밋, 지금 코드와 함께 모델이 본다: 받아들임 / 거절 / 고칠 것 없음 / 이미 반영됨.
|
|
93
|
+
3. **수정.** 받아들인 것만 위의 6–8과 같은 방식으로 고쳐 수정안 PR 하나로 올린다.
|
|
94
|
+
4. **답글과 해결.** 코멘트마다 답글을 달고, 수정안이 머지되면 스레드를 해결됨으로 바꾼다.
|
|
95
|
+
|
|
96
|
+
웹훅을 놓쳐도 동기화(기본 5분)가 열린 PR의 상태와 처리하지 않은 코멘트를 보고 채운다. 파이프라인을 새 판으로 올리면 열린 PR을 다시 검사한다.
|
|
97
|
+
|
|
98
|
+
설계의 까닭과 세부는 [docs/DESIGN.md](docs/DESIGN.md)의 표에서 필요한 절만 찾아 읽으면 된다.
|
|
99
|
+
|
|
100
|
+
## 시작하기
|
|
101
|
+
|
|
102
|
+
필요한 것:
|
|
103
|
+
|
|
104
|
+
- macOS나 Linux
|
|
105
|
+
- node 20.18 이상 (`npx`로 친다)
|
|
106
|
+
- python 3.11 이상, Docker(켜 둔다), git, [gh](https://cli.github.com/)
|
|
107
|
+
- [claude](https://docs.anthropic.com/en/docs/claude-code) CLI 설치와 로그인. 깔기만 해서는 안 되고 로그인까지 해 둔다. 모델 호출은 이 로그인한 계정의 사용량으로 나간다. 로그인은 터미널에서 `claude`를 실행해 `/login` 한다.
|
|
108
|
+
|
|
109
|
+
빠진 것이 있으면 configure가 한 번에 모두 알려 주고 운영체제에 맞는 설치 방법을 보인다.
|
|
110
|
+
|
|
111
|
+
npm에는 아직 올리지 않았다. 지금은 clone한 폴더에서 `npx .`로 친다. 올린 뒤에는 clone 없이 `npx pr-proof configure`, `npx pr-proof start`가 된다.
|
|
112
|
+
|
|
113
|
+
```
|
|
114
|
+
git clone https://github.com/Eunryong/pr-proof && cd pr-proof
|
|
115
|
+
npx . configure # 처음 설정. 묻는 말에 답한다
|
|
116
|
+
npx . start # 서버 실행 (api, worker, smee에서 받아 오기)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
configure가 묻는 것은 넷이다.
|
|
120
|
+
|
|
121
|
+
1. 처리할 repo. 예: `octocat/hello-world`. 여럿이면 띄어 쓴다
|
|
122
|
+
2. GitHub 인증 방식: gh 로그인(`gh auth login`을 해 둔 계정) 또는 토큰
|
|
123
|
+
3. 토큰. 토큰 방식일 때만 묻고, 화면에 보이지 않게 입력한다
|
|
124
|
+
4. 웹훅 받는 주소. 없으면 Enter
|
|
125
|
+
|
|
126
|
+
나머지는 묻지 않고 한다: Python 실행 환경 설치, 포트(기본 8765. 쓰이고 있을 때만 다른 번호를 묻는다), Redis, 웹훅 비밀값, repo의 읽기·쓰기 권한 확인, 웹훅 등록, Claude 로그인 확인, 끝 확인 표(서버가 시작할 때 하는 확인과 같다: GitHub 인증, Claude 로그인, Docker, Redis). 여러 번 돌려도 같다. 있는 설정과 비밀값은 덮어쓰지 않는다. Claude 로그인이 안 되어 있으면 무엇을 치면 되는지 보이고, 로그인한 뒤 Enter를 누르면 그 자리에서 다시 확인한다(나중에 configure를 다시 돌려도 된다).
|
|
127
|
+
|
|
128
|
+
**웹훅 받는 주소.** GitHub이 PR 소식을 보낼 주소이고, pr-proof가 도는 컴퓨터로 들어오는 주소다. repo가 공개인지와는 상관없다. 이미 있으면 적는다. 없으면 Enter를 누른다. 그러면 configure가 smee.io 주소를 만들고, `start`가 smee에서 소식을 받아 온다. 이때 PR 소식이 smee.io를 거친다(smee 주소를 아는 사람은 그 소식을 볼 수 있다. 주소는 `chmod 600` 파일에 둔다). 웹훅은 configure가 GitHub API로 등록한다. 등록할 권한이 없으면 손으로 등록할 값을 보인다.
|
|
129
|
+
|
|
130
|
+
**토큰 방식.** gh 로그인 대신 토큰을 쓸 수 있다. 토큰은 설정 폴더의 `github_token`(`chmod 600`)에 두고 gh와 git에만 넘긴다. 모델 호출과 샌드박스에는 가지 않는다. 필요한 권한(처리할 repo마다):
|
|
131
|
+
|
|
132
|
+
| 토큰 | 권한 |
|
|
133
|
+
| --- | --- |
|
|
134
|
+
| fine-grained | Contents: Read and write, Pull requests: Read and write, Issues: Read and write, Metadata: Read-only |
|
|
135
|
+
| classic | `repo` (공개 repo만이면 `public_repo`) |
|
|
136
|
+
| 웹훅 등록·삭제 (configure, add, rm) | fine-grained는 Webhooks: Read and write, classic은 `admin:repo_hook` |
|
|
137
|
+
|
|
138
|
+
토큰이 만료되거나 폐기되면 새 토큰을 `github_token`에 넣는다. 질문 없이 돌릴 때는 환경 변수 `PR_PROOF_GITHUB_TOKEN`으로 준다. 명령줄 인자로는 받지 않는다(셸 기록에 남는다).
|
|
139
|
+
|
|
140
|
+
repo를 나중에 더하고 빼고 보기:
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
npx . add <repo> # 허용 목록에 더하고 권한을 확인하고 웹훅을 등록한다
|
|
144
|
+
npx . rm <repo> # 허용 목록에서 빼고 pr-proof가 등록한 웹훅만 지운다
|
|
145
|
+
npx . list # 처리하는 repo 목록. --check를 주면 웹훅까지 확인한다
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`rm`은 그 repo의 PR 코멘트, 열린 수정안 PR, 데이터 폴더의 기록(DB, 캐시)은 그대로 둔다. 도는 서버는 목록을 시작할 때만 읽으므로 `add`와 `rm` 뒤에는 서버를 다시 띄운다.
|
|
149
|
+
|
|
150
|
+
질문 없이 돌리기: `npx . configure --repo octocat/hello-world --auth gh`. 그 밖의 인자는 `--webhook-url`, `--port`, `--dry-run`(파일과 GitHub에 쓰지 않고 할 일만 보인다), `--manual-webhook`(웹훅을 손으로 등록할 값만 보인다)이다. 명령마다 `--help`로 본다.
|
|
151
|
+
|
|
152
|
+
파이프라인 쪽 설정과 비밀값은 대상 저장소 밖의 `~/.config/pipeline/`에 둔다(`PIPELINE_CONFIG_DIR`로 바꿀 수 있다): `config.yaml`, `webhook_secret`, `github_token`(토큰 방식일 때), `webhook_url`, `pr-proof.env`(포트). Python 실행 환경은 clone한 폴더의 `.venv`에 둔다(npm 패키지로 받았으면 `~/.cache/pipeline/runtime/venv`).
|
|
153
|
+
|
|
154
|
+
워커는 시작할 때 GitHub 인증, Claude 로그인, Docker, Redis를 확인하고 하나라도 안 되면 멈춘다. 계속 띄워 두는 방법(macOS launchd)과 알림은 [docs/OPERATIONS.md](docs/OPERATIONS.md)에 있다.
|
|
155
|
+
|
|
156
|
+
<details>
|
|
157
|
+
<summary>손으로 하는 방법</summary>
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
git clone https://github.com/Eunryong/pr-proof && cd pr-proof
|
|
161
|
+
python3 -m venv .venv && source .venv/bin/activate
|
|
162
|
+
pip install -e '.[dev]' # 과거 기록 검색까지 쓰려면 '.[dev,rag]'
|
|
163
|
+
docker compose up -d # Redis
|
|
164
|
+
cp .env.example .env # API_PORT(기본 8765) 같은 로컬 실행 설정. 비밀값은 넣지 않는다
|
|
165
|
+
gh auth login # 코멘트와 수정안 PR을 이 계정으로 단다. 대상 repo에 쓰기 권한이 필요하다
|
|
166
|
+
claude # 처음 한 번 /login
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
비밀값 파일은 `chmod 600`이어야 읽는다.
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
mkdir -p ~/.config/pipeline
|
|
173
|
+
cat > ~/.config/pipeline/config.yaml <<'YAML'
|
|
174
|
+
repos: [octocat/hello-world] # 처리할 repo 허용 목록
|
|
175
|
+
YAML
|
|
176
|
+
openssl rand -hex 32 > ~/.config/pipeline/webhook_secret && chmod 600 ~/.config/pipeline/webhook_secret
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
대상 repo의 GitHub 설정 → Webhooks에 웹훅을 더한다(저장소 관리자만 할 수 있다).
|
|
180
|
+
|
|
181
|
+
- Payload URL: 웹훅 받는 주소. 이 컴퓨터로 받을 주소가 없으면 smee.io 주소를 만들고 `smee-client`로 `http://127.0.0.1:8765/webhook/github`에 넘긴다
|
|
182
|
+
- Content type: `application/json`, Secret: `webhook_secret` 파일의 값
|
|
183
|
+
- 이벤트: Pull requests, Issue comments, Pull request reviews, Pull request review comments
|
|
184
|
+
|
|
185
|
+
실행:
|
|
186
|
+
|
|
187
|
+
```
|
|
188
|
+
scripts/start.sh # api(웹훅 + 동기화)와 worker
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
</details>
|
|
192
|
+
|
|
193
|
+
## 규칙 적기
|
|
194
|
+
|
|
195
|
+
규칙은 대상 저장소의 base 브랜치에서 읽는다.
|
|
196
|
+
|
|
197
|
+
- README(기본은 `README.md`, `CONTRIBUTING.md`)에 규칙을 문장으로 적는다. 지키는 예와 어기는 예를 코드 블록으로 붙이면 검사기가 더 정확해진다.
|
|
198
|
+
- 저장소에 린터 설정이 있으면 그 설정도 규칙이 된다. 지금 읽을 수 있는 린터는 ruff 하나다(`ruff.toml`, `.ruff.toml`, `pyproject.toml`의 `[tool.ruff]`).
|
|
199
|
+
- 파이프라인이 정해 둔 린터나 규칙은 없다. ruff 설정이 없고 문서의 규칙도 ruff로 확인할 것이 없는 저장소에서는 ruff를 받지도 돌리지도 않는다. 그런 규칙은 모델이 쓴 검사기나 모델의 판단으로 확인한다.
|
|
200
|
+
- 커밋 메시지 형식, "어떤 파일을 바꾸면 PR 본문에 무엇을 적는다" 같은 PR 자체의 규칙도 문장으로 적으면 된다. 이런 규칙은 알리기만 하고 수정안을 만들지 않는다.
|
|
201
|
+
- 규칙도 설정도 없으면 검사하지 않고 그 사실을 코멘트에 적는다.
|
|
202
|
+
|
|
203
|
+
테스트가 실패한 PR과 테스트가 없는 저장소는 모델이 고치지 않는다. 고친 것을 확인할 방법이 없어서다.
|
|
204
|
+
|
|
205
|
+
## 리뷰 코멘트
|
|
206
|
+
|
|
207
|
+
PR에 달린 Copilot의 리뷰와 저장소의 OWNER·MEMBER·COLLABORATOR가 단 코멘트(줄 코멘트, 리뷰 본문, 일반 코멘트)를 읽는다.
|
|
208
|
+
|
|
209
|
+
- 코멘트마다 팀의 규칙과 PR의 흐름을 보고 정한다: 받아들임 / 거절 / 고칠 것 없음 / 이미 반영됨.
|
|
210
|
+
- 받아들인 코멘트는 규칙 위반과 같은 방식으로 고쳐 수정안 PR 하나(`pipeline/pr-<n>-fix-feedback`)로 올린다.
|
|
211
|
+
- 코멘트마다 답글을 단다. 반영했으면 수정안 번호를, 거절했으면 까닭을 적는다.
|
|
212
|
+
- 스레드는 수정안이 머지된 뒤에 해결됨으로 바꾼다. Copilot의 스레드는 사유(Addressed / Won't fix / Incorrect)를 같이 남기고, 거절한 것도 바로 해결한다. 사람이 단 스레드는 거절해도 열어 둔다.
|
|
213
|
+
- 규칙 검사가 이미 고친 줄을 가리키는 코멘트는 다시 고치지 않고 그 수정안에 잇는다.
|
|
214
|
+
- 코멘트의 글은 판단할 자료다. "이 파일을 지워라" 같은 글을 지시로 따르지 않는다.
|
|
215
|
+
|
|
216
|
+
## 명령과 설정
|
|
217
|
+
|
|
218
|
+
PR 코멘트 명령(저장소의 OWNER·MEMBER·COLLABORATOR만):
|
|
219
|
+
|
|
220
|
+
| 명령 | 하는 일 |
|
|
221
|
+
| --- | --- |
|
|
222
|
+
| `/recheck` | 지금 커밋을 다시 검사한다 |
|
|
223
|
+
| `/recheck <커밋>` | 외부 작성자의 PR을 승인한다. 적은 커밋(전체 해시 40자)이 지금 head일 때만 검사한다 |
|
|
224
|
+
| `/fix` | 수정안을 만들지 못한 묶음과 호출 상한에 걸린 일을 다시 돌린다 |
|
|
225
|
+
| `/fix model`, `/fix mechanical` | 그 묶음만 다시 돌린다 |
|
|
226
|
+
|
|
227
|
+
대상 저장소의 base 브랜치에 `.pipeline.yaml`을 두면 동작을 바꿀 수 있다. 전체 스키마는 [docs/design/10-pipeline-yaml.md](docs/design/10-pipeline-yaml.md)에 있다.
|
|
228
|
+
|
|
229
|
+
```yaml
|
|
230
|
+
rules:
|
|
231
|
+
docs: [README.md, CONTRIBUTING.md] # 규칙을 읽을 문서
|
|
232
|
+
disabled: [] # 끌 규칙 id (코멘트의 "읽은 규칙"에 보이는 id)
|
|
233
|
+
fix:
|
|
234
|
+
require_approval: false # true면 /fix를 달 때까지 수정하지 않는다
|
|
235
|
+
access:
|
|
236
|
+
trusted: [OWNER, MEMBER, COLLABORATOR]
|
|
237
|
+
bots: [] # 바로 검사할 봇 계정. 예: ["dependabot[bot]"]
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
수동 명령:
|
|
241
|
+
|
|
242
|
+
```
|
|
243
|
+
python -m app.api.cli sync # 동기화를 한 번 돌린다
|
|
244
|
+
python -m app.worker.cli reindex # 과거 기록 검색의 벡터 저장소를 다시 만든다 ([rag] 필요)
|
|
245
|
+
python -m app.worker.cli eval --real-model # 평가 케이스를 실제 모델로 돌린다 (비용이 든다)
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
## 안전
|
|
249
|
+
|
|
250
|
+
PR의 코드와 글, 리뷰 코멘트는 모두 믿지 않는 입력으로 다룬다.
|
|
251
|
+
|
|
252
|
+
- PR의 코드는 네트워크가 없는 Docker 샌드박스에서만 실행한다. 네트워크를 쓰는 것은 의존성을 설치하는 컨테이너뿐이고, 거기에는 호스트의 것을 붙이지 않고 바이너리 배포본만 설치한다.
|
|
253
|
+
- 저장소의 OWNER·MEMBER·COLLABORATOR가 아닌 사람의 PR은 승인(`/recheck <커밋>`) 전까지 아무것도 돌리지 않는다.
|
|
254
|
+
- 규칙과 설정은 PR이 아니라 base 브랜치에서 읽는다. PR이 자기를 검사할 규칙을 바꿀 수 없다.
|
|
255
|
+
- 모델은 전용 폴더에서 정해진 파일만 고칠 수 있다. 테스트 폴더와 `.github/`는 고치지 못하고, 만든 테스트는 정해진 이름의 새 파일로만 둔다.
|
|
256
|
+
- PR의 글과 코멘트는 프롬프트에 자료로 들어가고 지시로 읽지 않는다. 결과 코멘트에서 모델과 작성자의 글은 코드 스팬 안에만 넣는다.
|
|
257
|
+
- 모델이 쓴 코드는 사람이 머지해야 들어간다.
|
|
258
|
+
|
|
259
|
+
위협과 막는 장치의 전체 표는 [docs/design/08-security.md](docs/design/08-security.md)에 있다.
|
|
260
|
+
|
|
261
|
+
## 아직 해 보지 않은 것
|
|
262
|
+
|
|
263
|
+
안 되는 것으로 확인한 목록이 아니다. 지금까지 만들고 돌려 본 범위의 바깥이다.
|
|
264
|
+
|
|
265
|
+
- **Python 밖의 언어.** Python 저장소에서만 돌려 봤다. 테스트를 돌리고 결과를 읽는 부분은 Python 것만 만들었다. 규칙 읽기, 검사기, 모델의 판단은 언어를 가리지 않게 짰지만 다른 언어의 저장소에 붙여 보지 않았다.
|
|
266
|
+
- **GitHub 밖의 호스트.** GitHub에서만 써 봤다.
|
|
267
|
+
- **ruff 밖의 린터.** 린터 설정을 규칙으로 읽는 것은 ruff로만 해 봤다. flake8, pylint 같은 설정은 아직 읽지 않는다. 그런 저장소도 문서에 적은 규칙은 검사한다.
|
|
268
|
+
- **여러 대, 여러 워커.** 한 대에서 워커 하나로만 돌렸다.
|
|
269
|
+
- **저장소 전체 검사.** PR이 바꾼 줄만 보게 만들었다. 저장소 전체를 훑는 것은 해 보지 않았다.
|
|
270
|
+
- **커밋 메시지·PR 본문·브랜치 이름 고치기.** 지금은 알리기만 한다. 고쳐 주는 것은 시도하지 않았다.
|
|
271
|
+
- **모델 사용량 줄이기.** 큰 파일에서는 수정 한 번에 입력 토큰이 수십만 개 든다. 아직 줄이는 일을 하지 않았다.
|
|
272
|
+
- **여러 저장소에서의 사용.** 직접 돌려 본 저장소가 둘이다. 다른 팀의 규칙과 코드에서 어떻게 되는지는 모른다. 그래서 후기가 필요하다.
|
|
273
|
+
|
|
274
|
+
문서와 코드가 다른 곳은 [docs/design/12-2-doc-vs-code.md](docs/design/12-2-doc-vs-code.md)에, 하려는 일은 [docs/BACKLOG.md](docs/BACKLOG.md)에 있다.
|
|
275
|
+
|
|
276
|
+
## 후기와 제보
|
|
277
|
+
|
|
278
|
+
[이슈](https://github.com/Eunryong/pr-proof/issues/new/choose)에 아래를 붙여 주면 원인을 찾기 쉽다. 비공개 코드는 붙이지 않아도 된다.
|
|
279
|
+
|
|
280
|
+
- 규칙 문장(README에 적은 그대로)
|
|
281
|
+
- 결과 코멘트(접힌 "자세히"까지. 읽은 규칙과 확인 방법이 들어 있다)
|
|
282
|
+
- 기대한 것과 실제로 일어난 것: 위반이 아닌데 잡혔다 / 위반인데 놓쳤다 / 수정안이 틀렸다 / 고치지 않았다 / 설치·실행이 막혔다
|
|
283
|
+
- 도구가 규칙을 잘못 읽었으면 도구의 문제다. README를 도구에 맞춰 고치지 않아도 된다.
|
|
284
|
+
|
|
285
|
+
## 개발
|
|
286
|
+
|
|
287
|
+
```
|
|
288
|
+
pytest # 파이프라인 자체 테스트 (Docker 없이)
|
|
289
|
+
pytest -m docker # 실제 Docker·예제 저장소가 필요한 통합 테스트
|
|
290
|
+
ruff check . && ruff format --check .
|
|
291
|
+
npm test # npx 입구(bin/pr-proof.js)의 작은 테스트 (node --test)
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
- 작업 원칙: [docs/CLAUDE.md](docs/CLAUDE.md)
|
|
295
|
+
- 설계: [docs/DESIGN.md](docs/DESIGN.md)(찾아보기) → `docs/design/`
|
|
296
|
+
- 문제 해결 일지: [docs/JOURNAL.md](docs/JOURNAL.md), 지난 기록: [docs/HISTORY.md](docs/HISTORY.md), 초기 설계 검토: [docs/design-review-2026-11-17.md](docs/design-review-2026-11-17.md)
|
|
297
|
+
- 평가 케이스: [eval/README.md](eval/README.md)
|
|
298
|
+
|
|
299
|
+
## 라이선스
|
|
300
|
+
|
|
301
|
+
[MIT](LICENSE)
|
package/app/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""pr-proof: 웹(api), 워커(worker), 둘이 같이 쓰는 것(shared)."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""웹: FastAPI 앱(main), 웹훅, 동기화. 워커 코드를 import하지 않고 PR 코드를 실행하지 않는다."""
|
package/app/api/cli.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""웹 쪽 수동 명령.
|
|
2
|
+
|
|
3
|
+
- `python -m app.api.cli sync`: 동기화를 한 번 돌린다. api는 웹훅용 터널로 외부에 열려 있으므로 수동
|
|
4
|
+
동기화를 HTTP 엔드포인트로 만들지 않는다.
|
|
5
|
+
|
|
6
|
+
워커 쪽 수동 명령(reindex, eval)은 `app/worker/cli.py`에 있다.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from redis import Redis
|
|
13
|
+
|
|
14
|
+
from app.api import sync
|
|
15
|
+
from app.api.history import History
|
|
16
|
+
from app.shared import config
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def main(argv: list[str] | None = None) -> int:
|
|
20
|
+
parser = argparse.ArgumentParser(prog="python -m app.api.cli")
|
|
21
|
+
parser.add_argument("command", choices=["sync"])
|
|
22
|
+
parser.parse_args(argv)
|
|
23
|
+
settings = config.load_config()
|
|
24
|
+
result = sync.run_once(settings, Redis.from_url(settings.redis_url), History(settings.db_path))
|
|
25
|
+
for repo, number, reason in result.enqueued:
|
|
26
|
+
print(f"등록: {repo}#{number} ({reason})")
|
|
27
|
+
for repo in result.failed_repos:
|
|
28
|
+
print(f"조회 실패: {repo}", file=sys.stderr)
|
|
29
|
+
if not result.enqueued and not result.failed_repos:
|
|
30
|
+
print("등록할 작업 없음")
|
|
31
|
+
return 1 if result.failed_repos else 0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
if __name__ == "__main__":
|
|
35
|
+
sys.exit(main())
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""GitHub 조회 (gh CLI). 웹 쪽 동기화가 쓴다. 쓰기는 워커가 한다 (app/worker/github.py)."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import subprocess
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Final
|
|
8
|
+
|
|
9
|
+
from app.shared import config, github_auth
|
|
10
|
+
from app.shared.feedback_pure import FeedbackKind
|
|
11
|
+
|
|
12
|
+
GH_TIMEOUT: Final = 60
|
|
13
|
+
_ENV_PASSTHROUGH: Final = ("PATH", "HOME", "GH_CONFIG_DIR")
|
|
14
|
+
PR_FIELDS: Final = "number,headRefOid,baseRefOid,headRefName,isDraft,author"
|
|
15
|
+
|
|
16
|
+
GhRunner = Callable[[list[str]], str]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class GitHubReadError(RuntimeError):
|
|
20
|
+
"""gh 조회 실패. 이번 동기화는 건너뛰고 다음 주기에 다시 한다."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class OpenPR:
|
|
25
|
+
number: int
|
|
26
|
+
head_sha: str
|
|
27
|
+
base_sha: str
|
|
28
|
+
head_ref: str
|
|
29
|
+
draft: bool
|
|
30
|
+
# PR 작성자의 로그인 이름. 기록용으로 `PRJob`에 싣는다 (8.6). `gh pr list`는
|
|
31
|
+
# author_association을 주지 않아 동기화로 만든 작업에는 그 값이 없다
|
|
32
|
+
author_login: str = ""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def run_gh(args: list[str]) -> str:
|
|
36
|
+
"""gh를 최소 환경으로 부른다. 토큰 방식이면 토큰을 이 프로세스에만 넘긴다(`github_auth`)."""
|
|
37
|
+
try:
|
|
38
|
+
env = github_auth.gh_env(_ENV_PASSTHROUGH)
|
|
39
|
+
except config.ConfigError as e:
|
|
40
|
+
raise GitHubReadError(f"GitHub 토큰을 읽지 못함: {e}") from e
|
|
41
|
+
try:
|
|
42
|
+
proc = subprocess.run(
|
|
43
|
+
["gh", *args], capture_output=True, text=True, env=env, timeout=GH_TIMEOUT, check=False
|
|
44
|
+
)
|
|
45
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
46
|
+
raise GitHubReadError(f"gh 실행 실패: {e}") from e
|
|
47
|
+
if proc.returncode != 0:
|
|
48
|
+
detail = github_auth.redact(proc.stderr.strip(), env)[-500:]
|
|
49
|
+
raise GitHubReadError(f"gh {' '.join(args[:2])} 실패: {detail}")
|
|
50
|
+
return proc.stdout
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def auth_ok(runner: GhRunner = run_gh) -> bool:
|
|
54
|
+
"""`gh auth status`가 통과하는지. 네트워크가 끊겨도 실패한다(gh가 둘을 가르지 못한다).
|
|
55
|
+
토큰 방식이면 토큰 계정만 본다(`github_auth.status_args`)."""
|
|
56
|
+
try:
|
|
57
|
+
runner(github_auth.status_args())
|
|
58
|
+
except GitHubReadError:
|
|
59
|
+
return False
|
|
60
|
+
return True
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class PRComment:
|
|
65
|
+
id: int
|
|
66
|
+
author_association: str
|
|
67
|
+
created_at: str # ISO 8601 (UTC, "Z")
|
|
68
|
+
body: str
|
|
69
|
+
login: str = "" # 명령 작성자. 기록용 (8.6)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def head_commit_time(repo: str, head_sha: str, runner: GhRunner = run_gh) -> str:
|
|
73
|
+
"""head 커밋의 커미터 시각 (ISO 8601). 놓친 명령은 이 시각 뒤에 달린 것만 처리한다."""
|
|
74
|
+
out = runner(["api", f"repos/{repo}/commits/{head_sha}", "--jq", ".commit.committer.date"])
|
|
75
|
+
return out.strip()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def list_comments_since(
|
|
79
|
+
repo: str, pr_number: int, since: str, runner: GhRunner = run_gh
|
|
80
|
+
) -> list[PRComment]:
|
|
81
|
+
"""since 뒤에 달린 PR 코멘트. 본문은 여러 줄일 수 있어 한 줄에 JSON 하나로 받는다."""
|
|
82
|
+
jq = '.[] | {id, author_association, created_at, body, login: (.user.login // "")} | @json'
|
|
83
|
+
out = runner(
|
|
84
|
+
["api", "--paginate", f"repos/{repo}/issues/{pr_number}/comments?since={since}",
|
|
85
|
+
"--jq", jq]
|
|
86
|
+
) # fmt: skip
|
|
87
|
+
comments = []
|
|
88
|
+
for line in out.splitlines():
|
|
89
|
+
if not line.strip():
|
|
90
|
+
continue
|
|
91
|
+
item = json.loads(line)
|
|
92
|
+
if item["created_at"] < since: # since는 수정 시각 기준이라 오래전에 단 코멘트도 온다
|
|
93
|
+
continue
|
|
94
|
+
comments.append(
|
|
95
|
+
PRComment(
|
|
96
|
+
id=item["id"],
|
|
97
|
+
author_association=item.get("author_association") or "",
|
|
98
|
+
created_at=item["created_at"],
|
|
99
|
+
body=item.get("body") or "",
|
|
100
|
+
login=item.get("login") or "",
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
return comments
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True)
|
|
107
|
+
class FeedbackItem:
|
|
108
|
+
"""PR에 달린 코멘트 하나 (줄 리뷰 코멘트, 리뷰 본문, 일반 코멘트). 거르기는 호출한 쪽이 한다."""
|
|
109
|
+
|
|
110
|
+
kind: FeedbackKind
|
|
111
|
+
id: int
|
|
112
|
+
login: str
|
|
113
|
+
author_association: str
|
|
114
|
+
body: str
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# 읽는 곳과 그 응답에서 뺄 것. 줄 코멘트는 스레드의 첫 코멘트만(답글은 in_reply_to_id가 있다),
|
|
118
|
+
# 리뷰는 본문이 빈 것(줄 코멘트만 단 리뷰)을 뺀다
|
|
119
|
+
_FEEDBACK_SOURCES: Final[tuple[tuple[FeedbackKind, str, str], ...]] = (
|
|
120
|
+
("review_comment", "pulls/{n}/comments", "select(.in_reply_to_id == null)"),
|
|
121
|
+
("review", "pulls/{n}/reviews", 'select((.body // "") != "")'),
|
|
122
|
+
("issue_comment", "issues/{n}/comments", "select(true)"),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def list_feedback(repo: str, pr_number: int, runner: GhRunner = run_gh) -> list[FeedbackItem]:
|
|
127
|
+
"""PR에 달린 코멘트 전부(세 곳). 본문은 여러 줄일 수 있어 한 줄에 JSON 하나로 받는다.
|
|
128
|
+
|
|
129
|
+
동기화가 처리하지 않은 코멘트가 있는지 볼 때 쓴다. 글쓴이와 표시는 걸러 오지 않는다.
|
|
130
|
+
"""
|
|
131
|
+
items: list[FeedbackItem] = []
|
|
132
|
+
for kind, path, keep in _FEEDBACK_SOURCES:
|
|
133
|
+
jq = f'.[] | {keep} | {{id, author_association, body, login: (.user.login // "")}} | @json'
|
|
134
|
+
out = runner(["api", "--paginate", f"repos/{repo}/{path.format(n=pr_number)}", "--jq", jq])
|
|
135
|
+
for line in out.splitlines():
|
|
136
|
+
if not line.strip():
|
|
137
|
+
continue
|
|
138
|
+
try:
|
|
139
|
+
item = json.loads(line)
|
|
140
|
+
items.append(
|
|
141
|
+
FeedbackItem(
|
|
142
|
+
kind=kind,
|
|
143
|
+
id=int(item["id"]),
|
|
144
|
+
login=item.get("login") or "",
|
|
145
|
+
author_association=item.get("author_association") or "",
|
|
146
|
+
body=item.get("body") or "",
|
|
147
|
+
)
|
|
148
|
+
)
|
|
149
|
+
except (ValueError, KeyError, TypeError) as e:
|
|
150
|
+
raise GitHubReadError(f"코멘트 조회 응답을 읽지 못함: {repo}#{pr_number}") from e
|
|
151
|
+
return items
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def list_open_prs(repo: str, runner: GhRunner = run_gh) -> list[OpenPR]:
|
|
155
|
+
out = runner(
|
|
156
|
+
["pr", "list", "--repo", repo, "--state", "open", "--limit", "200", "--json", PR_FIELDS]
|
|
157
|
+
)
|
|
158
|
+
return [
|
|
159
|
+
OpenPR(
|
|
160
|
+
number=pr["number"],
|
|
161
|
+
head_sha=pr["headRefOid"],
|
|
162
|
+
base_sha=pr["baseRefOid"],
|
|
163
|
+
head_ref=pr["headRefName"],
|
|
164
|
+
draft=pr["isDraft"],
|
|
165
|
+
author_login=(pr.get("author") or {}).get("login") or "",
|
|
166
|
+
)
|
|
167
|
+
for pr in json.loads(out or "[]")
|
|
168
|
+
]
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""처리 기록 조회 (SQLite runs). 웹 쪽 동기화가 읽기만 하고, 쓰기는 워커가 한다."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Final
|
|
5
|
+
|
|
6
|
+
from sqlalchemy.exc import OperationalError
|
|
7
|
+
from sqlmodel import Session, create_engine, select
|
|
8
|
+
|
|
9
|
+
from app.api.sync_rules_pure import RunSnapshot
|
|
10
|
+
from app.shared.db_pure import CommandRecord, Feedback, Proposal, Run
|
|
11
|
+
from app.shared.feedback_pure import handled
|
|
12
|
+
|
|
13
|
+
# 머지되지 않고 닫힌 수정안의 상태 (db_pure.ProposalState)
|
|
14
|
+
CLOSED_UNMERGED: Final = ("rejected", "superseded", "closed_with_pr")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class History:
|
|
18
|
+
def __init__(self, db_path: Path) -> None:
|
|
19
|
+
self.db_path = db_path
|
|
20
|
+
self.engine = create_engine(f"sqlite:///{db_path}")
|
|
21
|
+
|
|
22
|
+
def runs_for(self, repo: str, pr_number: int, head_sha: str) -> list[RunSnapshot]:
|
|
23
|
+
"""같은 PR·head의 기록, 오래된 것부터. 워커가 한 번도 돌지 않아 DB가 없으면 빈 목록."""
|
|
24
|
+
if not self.db_path.is_file():
|
|
25
|
+
return []
|
|
26
|
+
with Session(self.engine) as session:
|
|
27
|
+
stmt = (
|
|
28
|
+
select(Run)
|
|
29
|
+
.where(Run.repo == repo, Run.pr_number == pr_number, Run.head_sha == head_sha)
|
|
30
|
+
.order_by(Run.id)
|
|
31
|
+
)
|
|
32
|
+
return [
|
|
33
|
+
RunSnapshot(
|
|
34
|
+
state=r.state,
|
|
35
|
+
heartbeat_at=r.heartbeat_at,
|
|
36
|
+
finished_at=r.finished_at,
|
|
37
|
+
pipeline_commit=r.pipeline_commit,
|
|
38
|
+
)
|
|
39
|
+
for r in session.exec(stmt)
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
def handled_command_ids(self, repo: str, pr_number: int) -> set[int]:
|
|
43
|
+
"""워커가 처리한 명령 코멘트 ID. 테이블이 아직 없으면 빈 집합."""
|
|
44
|
+
if not self.db_path.is_file():
|
|
45
|
+
return set()
|
|
46
|
+
with Session(self.engine) as session:
|
|
47
|
+
stmt = select(CommandRecord.comment_id).where(
|
|
48
|
+
CommandRecord.repo == repo, CommandRecord.pr_number == pr_number
|
|
49
|
+
)
|
|
50
|
+
try:
|
|
51
|
+
return set(session.exec(stmt))
|
|
52
|
+
except OperationalError:
|
|
53
|
+
return set()
|
|
54
|
+
|
|
55
|
+
def prs_with_open_proposals(self, repo: str) -> set[int]:
|
|
56
|
+
"""열린 제안 PR이 남아 있는 원본 PR 번호.
|
|
57
|
+
|
|
58
|
+
원본이 닫혔는데 close 웹훅을 놓쳤는지 볼 때 쓴다.
|
|
59
|
+
"""
|
|
60
|
+
if not self.db_path.is_file():
|
|
61
|
+
return set()
|
|
62
|
+
with Session(self.engine) as session:
|
|
63
|
+
stmt = select(Proposal.pr_number).where(Proposal.repo == repo, Proposal.state == "open")
|
|
64
|
+
try:
|
|
65
|
+
return set(session.exec(stmt))
|
|
66
|
+
except OperationalError:
|
|
67
|
+
return set()
|
|
68
|
+
|
|
69
|
+
def handled_feedback_keys(
|
|
70
|
+
self, repo: str, pr_number: int, head_sha: str
|
|
71
|
+
) -> set[tuple[str, int]]:
|
|
72
|
+
"""워커가 처리한 코멘트의 (종류, id). 테이블이 아직 없으면 빈 집합. deferred·error는 그
|
|
73
|
+
기록의 커밋이 head_sha일 때만, 새 커밋으로 닫힌 수정안에 연결된 것도 그때만 든다
|
|
74
|
+
(`feedback_pure.handled`)."""
|
|
75
|
+
if not self.db_path.is_file():
|
|
76
|
+
return set()
|
|
77
|
+
with Session(self.engine) as session:
|
|
78
|
+
stmt = select(
|
|
79
|
+
Feedback.kind, Feedback.item_id, Feedback.verdict, Feedback.head_sha,
|
|
80
|
+
Feedback.proposal_number,
|
|
81
|
+
).where(Feedback.repo == repo, Feedback.pr_number == pr_number) # fmt: skip
|
|
82
|
+
gone = select(Proposal.number).where(
|
|
83
|
+
Proposal.repo == repo, Proposal.pr_number == pr_number,
|
|
84
|
+
Proposal.state == "superseded",
|
|
85
|
+
) # fmt: skip
|
|
86
|
+
try:
|
|
87
|
+
superseded = set(session.exec(gone))
|
|
88
|
+
return {
|
|
89
|
+
(kind, item_id)
|
|
90
|
+
for kind, item_id, verdict, head, number in session.exec(stmt)
|
|
91
|
+
if handled(verdict, head, head_sha, number in superseded)
|
|
92
|
+
}
|
|
93
|
+
except OperationalError:
|
|
94
|
+
return set()
|
|
95
|
+
|
|
96
|
+
def prs_awaiting_resolve(self, repo: str) -> set[int]:
|
|
97
|
+
"""받아들인 코멘트의 스레드를 아직 해결하지 않은 원래 PR 번호.
|
|
98
|
+
|
|
99
|
+
수정안이 머지됐는데 머지 웹훅을 놓쳤는지 볼 때 쓴다. 머지됐는지는 워커가 GitHub에서 본다.
|
|
100
|
+
머지되지 않고 닫힌 것으로 기록된 수정안의 코멘트는 뺀다(워커가 스레드를 바꾸지 않으므로
|
|
101
|
+
주기마다 다시 넣어 봐야 일이 없다).
|
|
102
|
+
"""
|
|
103
|
+
if not self.db_path.is_file():
|
|
104
|
+
return set()
|
|
105
|
+
with Session(self.engine) as session:
|
|
106
|
+
stmt = select(Feedback.pr_number).where(
|
|
107
|
+
Feedback.repo == repo,
|
|
108
|
+
Feedback.verdict == "accepted",
|
|
109
|
+
Feedback.proposal_number.is_not(None),
|
|
110
|
+
Feedback.resolved_at.is_(None),
|
|
111
|
+
Feedback.thread_id.is_not(None),
|
|
112
|
+
~select(Proposal.id)
|
|
113
|
+
.where(
|
|
114
|
+
Proposal.repo == Feedback.repo,
|
|
115
|
+
Proposal.number == Feedback.proposal_number,
|
|
116
|
+
Proposal.state.in_(CLOSED_UNMERGED),
|
|
117
|
+
)
|
|
118
|
+
.exists(),
|
|
119
|
+
)
|
|
120
|
+
try:
|
|
121
|
+
return set(session.exec(stmt))
|
|
122
|
+
except OperationalError:
|
|
123
|
+
return set()
|