pr-proof 0.0.0-stage → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/Procfile +2 -0
  3. package/README.md +300 -2
  4. package/app/__init__.py +1 -0
  5. package/app/api/__init__.py +1 -0
  6. package/app/api/cli.py +35 -0
  7. package/app/api/github.py +168 -0
  8. package/app/api/history.py +123 -0
  9. package/app/api/main.py +95 -0
  10. package/app/api/queue.py +45 -0
  11. package/app/api/responses.py +28 -0
  12. package/app/api/signature.py +19 -0
  13. package/app/api/sync.py +189 -0
  14. package/app/api/sync_rules_pure.py +71 -0
  15. package/app/api/webhook.py +166 -0
  16. package/app/setup/__init__.py +4 -0
  17. package/app/setup/cli.py +90 -0
  18. package/app/setup/configure.py +720 -0
  19. package/app/setup/files.py +93 -0
  20. package/app/setup/github_setup.py +149 -0
  21. package/app/setup/install_hints.json +32 -0
  22. package/app/setup/setup_pure.py +312 -0
  23. package/app/setup/start.py +113 -0
  24. package/app/shared/__init__.py +1 -0
  25. package/app/shared/comment_pure.py +29 -0
  26. package/app/shared/config.py +106 -0
  27. package/app/shared/db_pure.py +339 -0
  28. package/app/shared/embed_models_pure.py +55 -0
  29. package/app/shared/feedback_pure.py +84 -0
  30. package/app/shared/github_auth.py +74 -0
  31. package/app/shared/job_pure.py +43 -0
  32. package/app/shared/notify.py +97 -0
  33. package/app/shared/ops_alert_pure.py +38 -0
  34. package/app/shared/state_keys_pure.py +24 -0
  35. package/app/shared/version.py +27 -0
  36. package/app/worker/__init__.py +1 -0
  37. package/app/worker/access_pure.py +180 -0
  38. package/app/worker/ai/__init__.py +1 -0
  39. package/app/worker/ai/claude_cli.py +684 -0
  40. package/app/worker/ai/mcp_relay.py +42 -0
  41. package/app/worker/ai/path_hook.py +103 -0
  42. package/app/worker/ai/tool_server.py +139 -0
  43. package/app/worker/ai/workdir.py +333 -0
  44. package/app/worker/base_config.py +173 -0
  45. package/app/worker/budget.py +100 -0
  46. package/app/worker/cache_key_pure.py +34 -0
  47. package/app/worker/call_budget_pure.py +132 -0
  48. package/app/worker/checker_authoring_pure.py +599 -0
  49. package/app/worker/checker_pure.py +196 -0
  50. package/app/worker/cli.py +97 -0
  51. package/app/worker/command.py +191 -0
  52. package/app/worker/command_pure.py +38 -0
  53. package/app/worker/coverage.py +123 -0
  54. package/app/worker/coverage_pure.py +202 -0
  55. package/app/worker/deps.py +22 -0
  56. package/app/worker/diff_pure.py +419 -0
  57. package/app/worker/doc_rules_pure.py +201 -0
  58. package/app/worker/doc_rules_report.py +979 -0
  59. package/app/worker/eval_run_pure.py +241 -0
  60. package/app/worker/evaluation.py +151 -0
  61. package/app/worker/feedback.py +448 -0
  62. package/app/worker/feedback_pure.py +131 -0
  63. package/app/worker/feedback_report_pure.py +90 -0
  64. package/app/worker/feedback_triage.py +85 -0
  65. package/app/worker/feedback_triage_pure.py +363 -0
  66. package/app/worker/fix/__init__.py +1 -0
  67. package/app/worker/fix/decide.py +197 -0
  68. package/app/worker/fix/feedback_fix_pure.py +125 -0
  69. package/app/worker/fix/fix_decision_pure.py +386 -0
  70. package/app/worker/fix/fix_pure.py +70 -0
  71. package/app/worker/fix/mechanical_fix.py +214 -0
  72. package/app/worker/fix/model_fix.py +575 -0
  73. package/app/worker/fix/model_fix_pure.py +593 -0
  74. package/app/worker/fix/proposal.py +584 -0
  75. package/app/worker/fix/proposal_pure.py +103 -0
  76. package/app/worker/fix/scope.py +40 -0
  77. package/app/worker/fix/scope_pure.py +222 -0
  78. package/app/worker/generated_tests_pure.py +442 -0
  79. package/app/worker/github.py +471 -0
  80. package/app/worker/graph.py +963 -0
  81. package/app/worker/guard.py +91 -0
  82. package/app/worker/lang/__init__.py +0 -0
  83. package/app/worker/lang/install_pure.py +25 -0
  84. package/app/worker/lang/python.py +862 -0
  85. package/app/worker/loop.py +200 -0
  86. package/app/worker/main.py +76 -0
  87. package/app/worker/markdown_pure.py +29 -0
  88. package/app/worker/mcp_pure.py +150 -0
  89. package/app/worker/memory.py +503 -0
  90. package/app/worker/merged_fix_pure.py +236 -0
  91. package/app/worker/pr_check_report_pure.py +201 -0
  92. package/app/worker/pr_description_report_pure.py +112 -0
  93. package/app/worker/preflight.py +125 -0
  94. package/app/worker/rag_pure.py +285 -0
  95. package/app/worker/rag_switch_pure.py +203 -0
  96. package/app/worker/records.py +207 -0
  97. package/app/worker/records_pure.py +239 -0
  98. package/app/worker/repo.py +588 -0
  99. package/app/worker/repo_config_pure.py +269 -0
  100. package/app/worker/report.py +300 -0
  101. package/app/worker/retry.py +65 -0
  102. package/app/worker/rule_pure.py +223 -0
  103. package/app/worker/rule_reading_pure.py +503 -0
  104. package/app/worker/rules/__init__.py +1 -0
  105. package/app/worker/rules/checkers.py +615 -0
  106. package/app/worker/rules/detect.py +154 -0
  107. package/app/worker/rules/doc_rules.py +301 -0
  108. package/app/worker/rules/doc_sections_pure.py +168 -0
  109. package/app/worker/rules/judge.py +410 -0
  110. package/app/worker/rules/judge_pure.py +627 -0
  111. package/app/worker/rules/pr_check.py +404 -0
  112. package/app/worker/rules/pr_check_pure.py +922 -0
  113. package/app/worker/rules/pr_description.py +218 -0
  114. package/app/worker/rules/pr_description_pure.py +743 -0
  115. package/app/worker/rules/rules.py +314 -0
  116. package/app/worker/rules/run_check.py +95 -0
  117. package/app/worker/rules/run_check_pure.py +219 -0
  118. package/app/worker/rules/tool_choice_pure.py +135 -0
  119. package/app/worker/sandbox/__init__.py +1 -0
  120. package/app/worker/sandbox/checker_runner.py +412 -0
  121. package/app/worker/sandbox/container.py +130 -0
  122. package/app/worker/sandbox/docker_cli.py +170 -0
  123. package/app/worker/sandbox/safe_read.py +32 -0
  124. package/app/worker/sandbox/toolcache.py +425 -0
  125. package/app/worker/state.py +602 -0
  126. package/app/worker/test_lines.py +77 -0
  127. package/app/worker/test_run_pure.py +133 -0
  128. package/app/worker/text_edit_pure.py +66 -0
  129. package/app/worker/tools_pure.py +152 -0
  130. package/app/worker/update.py +305 -0
  131. package/app/worker/violation_pure.py +33 -0
  132. package/bin/pr-proof.js +173 -0
  133. package/docker/sandbox/Dockerfile +12 -0
  134. package/docker/sandbox/coveragerc +19 -0
  135. package/docker-compose.yml +5 -0
  136. package/package.json +31 -4
  137. package/pyproject.toml +60 -0
@@ -0,0 +1,720 @@
1
+ """`npx pr-proof configure | add | rm | list`의 흐름.
2
+
3
+ configure의 단계 (docs/design/08-security.md "설치와 인증"):
4
+ 1 프로그램 확인 → 2 Docker가 켜져 있는지 → 3 설치(포트, Redis. venv는 입구가 만든다) →
5
+ 4 GitHub 인증 → 5 Claude 로그인 → 6 repo 등록과 권한 확인 → 7 웹훅(비밀값, 받는 주소, 등록) →
6
+ 8 끝 확인 표.
7
+
8
+ 묻는 것은 넷이다: repo, 인증 방식, 토큰(토큰 방식일 때), 웹훅 받는 주소. 터미널이 아니면 묻지 않고,
9
+ 필요한 값이 없으면 무엇이 없는지 말하고 실패한다. 여러 번 돌려도 같다: 목록에 없는 repo만 더하고,
10
+ 있는 비밀값과 저장한 주소는 덮어쓰지 않는다. `dry_run`이면 파일도 GitHub도 쓰지 않고 할 일만 보인다
11
+ (GitHub 읽기는 한다).
12
+
13
+ 바깥(프로그램 찾기, gh, Docker, Redis, smee.io, 포트, claude)은 `Deps`로 받는다. 테스트가 바꿔
14
+ 끼운다.
15
+ """
16
+
17
+ import getpass
18
+ import json
19
+ import secrets
20
+ import shutil
21
+ import socket
22
+ import subprocess
23
+ import sys
24
+ import urllib.request
25
+ from collections.abc import Callable, Mapping, Sequence
26
+ from dataclasses import dataclass, field
27
+ from datetime import UTC, datetime
28
+ from pathlib import Path
29
+ from typing import Final
30
+
31
+ from redis import Redis
32
+ from redis.exceptions import RedisError
33
+
34
+ from app.setup import files
35
+ from app.setup import github_setup as gh
36
+ from app.setup import setup_pure as pure
37
+ from app.shared import config, github_auth
38
+ from app.worker import preflight
39
+ from app.worker.sandbox.docker_cli import minimal_env
40
+
41
+ PROGRAMS: Final = ("docker", "git", "gh", "claude")
42
+ OPERATIONS_URL: Final = "https://github.com/Eunryong/pr-proof/blob/main/docs/OPERATIONS.md"
43
+ CONFIG_HEADER: Final = (
44
+ "# pr-proof 설정 (configure가 만들었다). repos는 npx pr-proof add / rm으로 고친다.\n"
45
+ )
46
+ RESTART: Final = "도는 서버는 config.yaml을 시작할 때만 읽습니다. 서버가 돌고 있으면 다시 띄우세요."
47
+ LEFT_ALONE: Final = (
48
+ "그 repo의 PR 코멘트, 열린 수정안 PR, 데이터 폴더의 기록(DB, 캐시)은 그대로 둡니다."
49
+ )
50
+
51
+
52
+ @dataclass
53
+ class Io:
54
+ interactive: bool
55
+ say: Callable[[str], object] = print
56
+ ask: Callable[[str], str] = input
57
+ ask_secret: Callable[[str], str] = getpass.getpass
58
+
59
+
60
+ @dataclass
61
+ class Deps:
62
+ which: Callable[[str], bool]
63
+ docker_ok: Callable[[], bool]
64
+ runner: Callable[[str | None], gh.Runner]
65
+ claude_ok: Callable[[], bool]
66
+ redis_ok: Callable[[str], bool]
67
+ compose_up: Callable[[], bool]
68
+ port_busy: Callable[[int], bool]
69
+ pr_proof_on: Callable[[int], bool]
70
+ smee_new: Callable[[], str]
71
+ checks: Callable[[str], list[preflight.Check]]
72
+ new_secret: Callable[[], str] = lambda: secrets.token_hex(32)
73
+ environ: Mapping[str, str] = field(default_factory=dict)
74
+ platform: str = sys.platform
75
+ hints: Mapping[str, Mapping[str, str]] = field(default_factory=dict)
76
+
77
+
78
+ @dataclass
79
+ class Options:
80
+ repos: list[str] = field(default_factory=list)
81
+ auth: str | None = None # "gh" | "token"
82
+ webhook_url: str | None = None
83
+ port: int | None = None
84
+ dry_run: bool = False
85
+ manual_webhook: bool = False # 웹훅을 API로 등록하지 않고 손으로 등록할 값만 보인다
86
+ yes: bool = False # rm: 확인을 묻지 않는다
87
+ check: bool = False # list: 웹훅까지 본다
88
+
89
+
90
+ class Stop(Exception):
91
+ """흐름을 멈춘다. 글은 이미 보였다."""
92
+
93
+
94
+ # --- 실제 바깥 ---
95
+
96
+
97
+ def _quiet(args: list[str], timeout: float = 30) -> bool:
98
+ try:
99
+ return subprocess.run(args, capture_output=True, env=minimal_env(), timeout=timeout,
100
+ check=False).returncode == 0 # fmt: skip
101
+ except (OSError, subprocess.TimeoutExpired):
102
+ return False
103
+
104
+
105
+ def _redis_ok(url: str) -> bool:
106
+ try:
107
+ return bool(Redis.from_url(url, socket_connect_timeout=2, socket_timeout=2).ping())
108
+ except (RedisError, ValueError):
109
+ return False
110
+
111
+
112
+ def _port_busy(port: int) -> bool:
113
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
114
+ s.settimeout(1)
115
+ return s.connect_ex(("127.0.0.1", port)) == 0
116
+
117
+
118
+ def _pr_proof_on(port: int) -> bool:
119
+ """그 포트에서 도는 것이 pr-proof api인지 (`/healthz`). 다시 돌린 configure가 자기 서버를 다른
120
+ 프로그램으로 보지 않게 한다."""
121
+ try:
122
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/healthz", timeout=2) as r:
123
+ return json.loads(r.read()) == {"status": "ok"}
124
+ except (OSError, ValueError):
125
+ return False
126
+
127
+
128
+ def _compose_up() -> bool:
129
+ """패키지의 docker-compose.yml로 Redis를 띄운다. 프로젝트 이름을 정해 다른 compose와 섞이지
130
+ 않게 한다."""
131
+ compose = files.PACKAGE_ROOT / "docker-compose.yml"
132
+ return _quiet(["docker", "compose", "-p", "pr-proof", "-f", str(compose), "up", "-d"], 300)
133
+
134
+
135
+ def _checks(redis_url: str) -> list[preflight.Check]:
136
+ return preflight.run_checks(Redis.from_url(redis_url, socket_connect_timeout=2))
137
+
138
+
139
+ def _claude_ok() -> bool:
140
+ return preflight.claude_login_ok(preflight._claude_auth_status(), datetime.now(UTC))
141
+
142
+
143
+ def real_deps(environ: Mapping[str, str]) -> Deps:
144
+ hints = json.loads((Path(__file__).with_name("install_hints.json")).read_text())
145
+ return Deps(
146
+ which=lambda name: shutil.which(name) is not None,
147
+ docker_ok=lambda: _quiet(["docker", "info"]),
148
+ runner=gh.make_runner,
149
+ claude_ok=_claude_ok,
150
+ redis_ok=_redis_ok,
151
+ compose_up=_compose_up,
152
+ port_busy=_port_busy,
153
+ pr_proof_on=_pr_proof_on,
154
+ # 입구(bin/pr-proof.js)가 자기 node를 PR_PROOF_NODE로 넘긴다
155
+ smee_new=lambda: gh.new_smee_url(environ.get("PR_PROOF_NODE") or shutil.which("node")),
156
+ checks=_checks,
157
+ environ=environ,
158
+ hints=hints,
159
+ )
160
+
161
+
162
+ # --- 공통 ---
163
+
164
+
165
+ def _ask_until(io: Io, prompt: str, valid: Callable[[str], str | None]) -> str:
166
+ while True:
167
+ answer = io.ask(prompt).strip()
168
+ problem = valid(answer)
169
+ if problem is None:
170
+ return answer
171
+ io.say(problem)
172
+
173
+
174
+ def _repos_problem(repos: Sequence[str]) -> str | None:
175
+ if not repos:
176
+ return f"repo를 하나 이상 적습니다 (예: {pure.REPO_EXAMPLE})"
177
+ for repo in repos:
178
+ if problem := pure.repo_problem(repo):
179
+ return problem
180
+ return None
181
+
182
+
183
+ def _config_text(directory: Path) -> str:
184
+ path = directory / files.CONFIG_FILE
185
+ return path.read_text() if path.is_file() else ""
186
+
187
+
188
+ def _write_config(directory: Path, text: str) -> None:
189
+ path = directory / files.CONFIG_FILE
190
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
191
+ path.write_text(text)
192
+
193
+
194
+ def _need_configured(directory: Path, io: Io) -> None:
195
+ if (
196
+ not (directory / files.CONFIG_FILE).is_file()
197
+ or not (directory / config.WEBHOOK_SECRET).is_file()
198
+ ):
199
+ io.say("설정이 없습니다. 먼저 npx pr-proof configure를 실행하세요.")
200
+ raise Stop
201
+
202
+
203
+ def _saved_url(directory: Path, io: Io) -> str | None:
204
+ try:
205
+ return files.read_private(files.WEBHOOK_URL_FILE, directory)
206
+ except config.ConfigError as e:
207
+ io.say(str(e))
208
+ raise Stop from e
209
+
210
+
211
+ def _secret(directory: Path) -> str | None:
212
+ try:
213
+ return config.read_secret(config.WEBHOOK_SECRET, directory)
214
+ except config.ConfigError:
215
+ return None
216
+
217
+
218
+ def check_access(run: gh.Runner, repos: Sequence[str], io: Io) -> list[str]:
219
+ """읽을 수 있는 repo만 돌려준다. 못 읽는 것과 쓸 수 없는 것을 말한다."""
220
+ readable = []
221
+ for repo in repos:
222
+ try:
223
+ read, write = gh.repo_access(run, repo)
224
+ except gh.NoPermission:
225
+ io.say(f" {repo}: 찾지 못했거나 읽을 권한이 없습니다")
226
+ continue
227
+ except gh.SetupGitHubError as e:
228
+ io.say(f" {repo}: 권한을 확인하지 못했습니다: {e}")
229
+ continue
230
+ if not read:
231
+ io.say(f" {repo}: 읽을 권한이 없습니다")
232
+ continue
233
+ readable.append(repo)
234
+ if write:
235
+ io.say(f" {repo}: 읽기·쓰기 권한 있음")
236
+ else:
237
+ io.say(f" {repo}: 쓰기 권한이 없습니다. 결과 코멘트와 수정안 PR을 올리지 못합니다")
238
+ return readable
239
+
240
+
241
+ def ensure_hooks(
242
+ run: gh.Runner, repos: Sequence[str], url: str, directory: Path, io: Io, opts: Options
243
+ ) -> bool:
244
+ """repo마다 그 주소의 웹훅을 만들거나 맞춘다. 권한이 없으면 손으로 등록할 값을 보인다.
245
+ 모두 등록됐으면 참."""
246
+ secret_path = str(directory / config.WEBHOOK_SECRET)
247
+ secret = _secret(directory) or "(dry-run: 아직 만들지 않은 비밀값)"
248
+ all_ok = True
249
+ for repo in repos:
250
+ if opts.manual_webhook:
251
+ io.say(pure.manual_hook_text(repo, url, secret_path))
252
+ all_ok = False
253
+ continue
254
+ try:
255
+ plan = pure.plan_hook(gh.list_hooks(run, repo), url)
256
+ except gh.NoPermission:
257
+ io.say(
258
+ f" {repo}: 웹훅을 볼 권한이 없습니다 (저장소 관리자 권한, 토큰이면 Webhooks 권한)"
259
+ )
260
+ io.say(pure.manual_hook_text(repo, url, secret_path))
261
+ all_ok = False
262
+ continue
263
+ if plan.action == "conflict":
264
+ others = ", ".join(plan.others)
265
+ io.say(f" {repo}: pr-proof 웹훅으로 보이는 다른 주소가 있어 만들지 않습니다: {others}")
266
+ io.say(" 같은 소식이 두 번 오지 않게 하려면 그 주소를 --webhook-url로 주어 다시 "
267
+ "실행하거나, 그 웹훅을 지운 뒤 다시 실행하세요.") # fmt: skip
268
+ all_ok = False
269
+ continue
270
+ what = "만든다" if plan.action == "create" else "맞춘다"
271
+ if opts.dry_run:
272
+ io.say(f" (dry-run) {repo}: 웹훅을 {what}: {'; '.join(plan.changes)}")
273
+ continue
274
+ payload = pure.hook_payload(url, secret, create=plan.action == "create")
275
+ try:
276
+ if plan.action == "create":
277
+ gh.create_hook(run, repo, payload)
278
+ else:
279
+ assert plan.hook_id is not None
280
+ gh.update_hook(run, repo, plan.hook_id, payload)
281
+ except gh.NoPermission:
282
+ io.say(f" {repo}: 웹훅을 등록할 권한이 없습니다")
283
+ io.say(pure.manual_hook_text(repo, url, secret_path))
284
+ all_ok = False
285
+ continue
286
+ io.say(f" {repo}: 웹훅을 {'만들었습니다' if plan.action == 'create' else '맞췄습니다'}")
287
+ return all_ok
288
+
289
+
290
+ def add_to_config(directory: Path, repos: Sequence[str], io: Io, dry_run: bool) -> list[str]:
291
+ text = _config_text(directory) or CONFIG_HEADER
292
+ try:
293
+ new_text, added = pure.add_repos(text, repos)
294
+ except pure.ConfigEditError as e:
295
+ io.say(str(e))
296
+ raise Stop from e
297
+ for repo in repos:
298
+ if repo not in added:
299
+ io.say(f" {repo}: 이미 허용 목록에 있음")
300
+ else:
301
+ io.say(
302
+ f" (dry-run) {repo}: 허용 목록에 더한다"
303
+ if dry_run
304
+ else f" {repo}: 허용 목록에 더함"
305
+ )
306
+ if not dry_run and (added or not (directory / files.CONFIG_FILE).is_file()):
307
+ _write_config(directory, new_text)
308
+ return added
309
+
310
+
311
+ # --- configure ---
312
+
313
+
314
+ def _step(io: Io, number: int, title: str) -> None:
315
+ io.say(f"\n[{number}/8] {title}")
316
+
317
+
318
+ def _programs(io: Io, deps: Deps) -> None:
319
+ _step(io, 1, "프로그램 확인")
320
+ missing = [p for p in PROGRAMS if not deps.which(p)]
321
+ if missing:
322
+ io.say(pure.missing_programs_text(missing, deps.hints, deps.platform))
323
+ raise Stop
324
+ io.say(" docker, git, gh, claude 있음")
325
+ _step(io, 2, "Docker")
326
+ if not deps.docker_ok():
327
+ io.say(" Docker가 꺼져 있습니다. Docker Desktop(Linux는 docker 서비스)을 실행한 뒤 다시 "
328
+ "실행하세요.") # fmt: skip
329
+ raise Stop
330
+ io.say(" 켜져 있음")
331
+
332
+
333
+ def _install(directory: Path, io: Io, deps: Deps, opts: Options) -> str:
334
+ _step(io, 3, "설치 (포트, Redis)")
335
+ port = opts.port or files.read_port(directory)
336
+ while deps.port_busy(port) and not deps.pr_proof_on(port):
337
+ if not io.interactive:
338
+ io.say(f" 포트 {port}를 다른 프로그램이 쓰고 있습니다. --port로 다른 번호를 주세요.")
339
+ raise Stop
340
+ answer = _ask_until(io, f" 포트 {port}를 다른 프로그램이 쓰고 있습니다. 쓸 번호: ",
341
+ lambda a: None if a.isdigit() and 0 < int(a) < 65536
342
+ else "1에서 65535 사이의 번호를 적습니다") # fmt: skip
343
+ port = int(answer)
344
+ if opts.dry_run:
345
+ io.say(f" (dry-run) API 포트 {port}를 {directory / files.RUN_ENV_FILE}에 적는다")
346
+ else:
347
+ files.write_port(port, directory)
348
+ io.say(f" API 포트: {port}")
349
+ try:
350
+ data = {"repos": [], **pure.config_data(_config_text(directory))}
351
+ redis_url = config.PipelineConfig.model_validate(data).redis_url
352
+ except (pure.ConfigEditError, ValueError) as e:
353
+ io.say(f" config.yaml을 읽지 못했습니다: {e}")
354
+ raise Stop from e
355
+ if deps.redis_ok(redis_url):
356
+ io.say(f" Redis: {redis_url}에 연결됨")
357
+ elif redis_url != config.PipelineConfig(repos=[]).redis_url:
358
+ io.say(f" Redis({redis_url})에 연결하지 못했습니다. config.yaml의 redis_url을 확인하세요.")
359
+ raise Stop
360
+ elif opts.dry_run:
361
+ io.say(" (dry-run) Redis를 docker compose로 띄운다")
362
+ elif deps.compose_up() and deps.redis_ok(redis_url):
363
+ io.say(" Redis를 띄웠습니다 (docker compose 프로젝트 pr-proof)")
364
+ else:
365
+ io.say(" Redis를 띄우지 못했습니다. 6379 포트를 다른 프로그램이 쓰고 있는지 확인하세요.")
366
+ raise Stop
367
+ return redis_url
368
+
369
+
370
+ def _choose_auth(directory: Path, io: Io, deps: Deps, opts: Options) -> str:
371
+ if opts.auth:
372
+ return opts.auth
373
+ if github_auth.uses_token(directory):
374
+ return "token"
375
+ if not io.interactive:
376
+ if gh.token_from_env(deps.environ):
377
+ return "token"
378
+ if gh.auth_ok(deps.runner(None), token_mode=False):
379
+ return "gh"
380
+ io.say(" GitHub 인증 방식이 없습니다: --auth gh (gh auth login을 먼저) 또는 --auth token "
381
+ f"(토큰은 환경 변수 {gh.TOKEN_INPUT_ENV}로)") # fmt: skip
382
+ raise Stop
383
+ default = "1" if gh.auth_ok(deps.runner(None), token_mode=False) else "2"
384
+ answer = _ask_until(
385
+ io, f" 인증 방식 1) gh 로그인 2) 토큰 [기본 {default}]: ",
386
+ lambda a: None if a in ("", "1", "2") else "1이나 2를 적습니다",
387
+ ) # fmt: skip
388
+ return "gh" if (answer or default) == "1" else "token"
389
+
390
+
391
+ def _auth(directory: Path, io: Io, deps: Deps, opts: Options) -> gh.Runner:
392
+ _step(io, 4, "GitHub 인증")
393
+ method = _choose_auth(directory, io, deps, opts)
394
+ token_path = directory / github_auth.TOKEN_FILE
395
+ if method == "gh":
396
+ if token_path.exists():
397
+ io.say(f" {token_path}가 있어 토큰 방식이 앞섭니다.")
398
+ io.say(" gh 로그인을 쓰려면 그 파일을 지운 뒤 다시 실행하세요.")
399
+ raise Stop
400
+ run = deps.runner(None)
401
+ while not gh.auth_ok(run, token_mode=False):
402
+ io.say(" gh 로그인이 되어 있지 않습니다. 다른 터미널에서 gh auth login을 실행하세요.")
403
+ if not io.interactive or io.ask(" 한 뒤 Enter (그만두려면 q): ").strip() == "q":
404
+ raise Stop
405
+ io.say(f" gh 로그인: {gh.login(run)}")
406
+ return run
407
+ # 토큰 방식. 있는 토큰 파일은 덮어쓰지 않는다(확인이 실패해 사용자가 새로 넣을 때만 바꾼다)
408
+ try:
409
+ saved = github_auth.token(directory)
410
+ except config.ConfigError as e:
411
+ io.say(f" {e}")
412
+ raise Stop from e
413
+ candidate = saved or gh.token_from_env(deps.environ)
414
+ if candidate is None and io.interactive:
415
+ io.say(pure.TOKEN_PERMISSIONS)
416
+ while True:
417
+ if candidate is None:
418
+ if not io.interactive:
419
+ io.say(f" 토큰이 없습니다. 환경 변수 {gh.TOKEN_INPUT_ENV}로 주세요.")
420
+ io.say(" (셸 기록에 남지 않게 명령줄 인자로는 받지 않습니다)")
421
+ raise Stop
422
+ candidate = io.ask_secret(" GitHub 토큰 (화면에 보이지 않습니다. 그만두려면 Enter): ")
423
+ candidate = candidate.strip() or None
424
+ if candidate is None:
425
+ raise Stop
426
+ run = deps.runner(candidate)
427
+ if gh.auth_ok(run, token_mode=True):
428
+ break
429
+ io.say(" 토큰으로 GitHub에 로그인하지 못했습니다 (틀렸거나 만료·폐기됐습니다).")
430
+ if not io.interactive:
431
+ raise Stop
432
+ io.say(pure.TOKEN_PERMISSIONS)
433
+ candidate = None
434
+ if candidate != saved:
435
+ if opts.dry_run:
436
+ io.say(f" (dry-run) 토큰을 {token_path}에 쓴다 (600)")
437
+ else:
438
+ files.write_private(token_path, candidate, replace=True)
439
+ io.say(f" 토큰을 {token_path}에 저장했습니다 (600)")
440
+ io.say(f" 토큰 계정: {gh.login(run)}")
441
+ return run
442
+
443
+
444
+ def _claude(io: Io, deps: Deps) -> None:
445
+ _step(io, 5, "Claude 로그인")
446
+ while not deps.claude_ok():
447
+ io.say(" claude CLI에 로그인되어 있지 않거나 로그인이 만료됐습니다. 모델 호출은 이 계정의 "
448
+ "사용량으로 나갑니다.") # fmt: skip
449
+ io.say(" 다른 터미널에서 claude를 실행해 /login 하세요.")
450
+ if not io.interactive:
451
+ io.say(" 로그인한 뒤 npx pr-proof configure를 다시 실행하세요.")
452
+ raise Stop
453
+ answer = io.ask(" 로그인한 뒤 Enter를 누르면 다시 확인합니다 (그만두려면 q, 나중에 "
454
+ "npx pr-proof configure를 다시 실행해도 됩니다): ") # fmt: skip
455
+ if answer.strip() == "q":
456
+ raise Stop
457
+ io.say(" 로그인되어 있음")
458
+
459
+
460
+ def _repos(directory: Path, io: Io, run: gh.Runner, opts: Options) -> list[str]:
461
+ _step(io, 6, "repo 등록과 권한 확인")
462
+ repos = list(dict.fromkeys(opts.repos))
463
+ try:
464
+ existing = pure.config_repos(_config_text(directory))
465
+ except pure.ConfigEditError as e:
466
+ io.say(f" {e}")
467
+ raise Stop from e
468
+ if not repos and not existing:
469
+ if not io.interactive:
470
+ io.say(f" 처리할 repo가 없습니다. --repo로 주세요 (예: --repo {pure.REPO_EXAMPLE})")
471
+ raise Stop
472
+ answer = _ask_until(
473
+ io, f" 처리할 repo (예: {pure.REPO_EXAMPLE}, 여럿이면 띄어 쓴다): ",
474
+ lambda a: _repos_problem(a.split()),
475
+ ) # fmt: skip
476
+ repos = answer.split()
477
+ if problem := _repos_problem(repos or existing):
478
+ io.say(f" {problem}")
479
+ raise Stop
480
+ readable = check_access(run, repos, io)
481
+ if len(readable) < len(repos):
482
+ io.say(" 읽을 수 없는 repo는 허용 목록에 더하지 않았습니다. 이름과 권한을 확인하세요.")
483
+ raise Stop
484
+ add_to_config(directory, repos, io, opts.dry_run)
485
+ if existing:
486
+ check_access(run, [r for r in existing if r not in repos], io)
487
+ return list(dict.fromkeys(existing + repos))
488
+
489
+
490
+ def _webhook_url(directory: Path, io: Io, deps: Deps, opts: Options) -> str:
491
+ saved = _saved_url(directory, io)
492
+ path = directory / files.WEBHOOK_URL_FILE
493
+ url = opts.webhook_url
494
+ if url is None and saved:
495
+ io.say(f" 웹훅 받는 주소: {saved} (저장된 것)")
496
+ return saved
497
+ if url is None and io.interactive:
498
+ io.say(" 웹훅 받는 주소: GitHub이 PR 소식을 보낼, pr-proof가 도는 이 컴퓨터로 들어오는")
499
+ io.say(
500
+ " 주소다. repo가 공개인지와 상관없다. 있으면 적고(예: https://example.com/webhook/github),"
501
+ )
502
+ io.say(" 없으면 Enter를 누르면 smee.io 주소를 만들어 쓴다.")
503
+ url = io.ask(" 웹훅 받는 주소 [Enter: smee]: ").strip() or None
504
+ if url is None:
505
+ io.say(" PR 소식이 smee.io를 거쳐 이 컴퓨터로 옵니다.")
506
+ io.say(" (smee 주소를 아는 사람은 그 소식을 볼 수 있습니다. 주소는 600 파일에 둡니다)")
507
+ if opts.dry_run:
508
+ io.say(f" (dry-run) https://smee.io/new로 주소를 만들어 {path}에 쓴다 (600)")
509
+ return "https://smee.io/(dry-run)"
510
+ try:
511
+ url = deps.smee_new()
512
+ except gh.SetupGitHubError as e:
513
+ io.say(f" {e}")
514
+ raise Stop from e
515
+ elif not url.startswith("https://"):
516
+ io.say(" 웹훅 받는 주소는 https://로 시작합니다.")
517
+ raise Stop
518
+ if opts.dry_run:
519
+ io.say(f" (dry-run) 웹훅 받는 주소 {url}를 {path}에 쓴다 (600)")
520
+ else:
521
+ files.write_private(path, url, replace=True)
522
+ io.say(f" 웹훅 받는 주소: {url} ({path}, 600)")
523
+ return url
524
+
525
+
526
+ def _webhook(directory: Path, io: Io, deps: Deps, run: gh.Runner, repos: Sequence[str],
527
+ opts: Options) -> bool: # fmt: skip
528
+ _step(io, 7, "웹훅")
529
+ secret_path = directory / config.WEBHOOK_SECRET
530
+ if secret_path.exists():
531
+ io.say(f" 비밀값: {secret_path} (있는 것을 씁니다)")
532
+ elif opts.dry_run:
533
+ io.say(f" (dry-run) 비밀값을 만들어 {secret_path}에 쓴다 (600)")
534
+ else:
535
+ files.write_private(secret_path, deps.new_secret())
536
+ io.say(f" 비밀값을 만들었습니다: {secret_path} (600)")
537
+ url = _webhook_url(directory, io, deps, opts)
538
+ return ensure_hooks(run, repos, url, directory, io, opts)
539
+
540
+
541
+ def _final(io: Io, deps: Deps, redis_url: str) -> bool:
542
+ _step(io, 8, "끝 확인 (서버가 시작할 때 하는 확인과 같다)")
543
+ checks = deps.checks(redis_url)
544
+ io.say(pure.check_table([(c.name, c.ok, c.hint) for c in checks]))
545
+ return all(c.ok for c in checks)
546
+
547
+
548
+ def configure(opts: Options, io: Io, deps: Deps, directory: Path | None = None) -> int:
549
+ directory = directory or files.config_dir()
550
+ if problem := (opts.repos and _repos_problem(opts.repos)):
551
+ io.say(problem)
552
+ return 1
553
+ if opts.dry_run:
554
+ io.say("dry-run: 파일과 GitHub에 쓰지 않고 할 일만 보입니다.")
555
+ try:
556
+ _programs(io, deps)
557
+ redis_url = _install(directory, io, deps, opts)
558
+ run = _auth(directory, io, deps, opts)
559
+ _claude(io, deps)
560
+ repos = _repos(directory, io, run, opts)
561
+ hooks_ok = _webhook(directory, io, deps, run, repos, opts)
562
+ except Stop:
563
+ return 1
564
+ checks_ok = _final(io, deps, redis_url)
565
+ io.say("")
566
+ if opts.manual_webhook:
567
+ io.say("웹훅은 위의 값으로 손으로 등록하세요.")
568
+ elif not hooks_ok:
569
+ io.say("웹훅을 모두 등록하지는 못했습니다. 위의 값으로 손으로 등록하세요.")
570
+ if not checks_ok:
571
+ io.say("끝 확인에 실패한 줄이 있습니다. 고친 뒤 npx pr-proof configure를 다시 실행하세요.")
572
+ io.say("다음: npx pr-proof start (clone한 폴더에서는 npx . start)")
573
+ io.say(f"계속 띄워 두려면: {OPERATIONS_URL}")
574
+ # 손으로 등록하라고 한 것(--manual-webhook)은 실패가 아니다
575
+ return 0 if checks_ok and (hooks_ok or opts.manual_webhook) else 1
576
+
577
+
578
+ # --- add / rm / list ---
579
+
580
+
581
+ def add(opts: Options, io: Io, deps: Deps, directory: Path | None = None) -> int:
582
+ directory = directory or files.config_dir()
583
+ if problem := _repos_problem(opts.repos):
584
+ io.say(problem)
585
+ return 1
586
+ try:
587
+ _need_configured(directory, io)
588
+ saved = _saved_url(directory, io)
589
+ url = opts.webhook_url or saved
590
+ if url is None:
591
+ io.say("웹훅 받는 주소가 저장되어 있지 않습니다. --webhook-url로 주세요.")
592
+ return 1
593
+ run = deps.runner(None)
594
+ if not gh.auth_ok(run, token_mode=github_auth.uses_token(directory)):
595
+ io.say(f"GitHub 인증이 되지 않습니다 → {github_auth.hint(directory)}")
596
+ return 1
597
+ readable = check_access(run, opts.repos, io)
598
+ if len(readable) < len(opts.repos):
599
+ io.say("읽을 수 없는 repo가 있어 아무것도 더하지 않았습니다.")
600
+ return 1
601
+ added = add_to_config(directory, opts.repos, io, opts.dry_run)
602
+ if opts.webhook_url and opts.webhook_url != saved and not opts.dry_run:
603
+ files.write_private(directory / files.WEBHOOK_URL_FILE, opts.webhook_url, replace=True)
604
+ hooks_ok = ensure_hooks(run, opts.repos, url, directory, io, opts)
605
+ except Stop:
606
+ return 1
607
+ if added and not opts.dry_run:
608
+ io.say(RESTART)
609
+ return 0 if hooks_ok or opts.manual_webhook else 1
610
+
611
+
612
+ def remove(opts: Options, io: Io, deps: Deps, directory: Path | None = None) -> int:
613
+ directory = directory or files.config_dir()
614
+ if problem := _repos_problem(opts.repos):
615
+ io.say(problem)
616
+ return 1
617
+ path = directory / files.CONFIG_FILE
618
+ if not path.is_file():
619
+ io.say("설정이 없습니다. 먼저 npx pr-proof configure를 실행하세요.")
620
+ return 1
621
+ text = path.read_text()
622
+ current = pure.config_repos(text)
623
+ targets = [r for r in dict.fromkeys(opts.repos) if r in current]
624
+ for repo in opts.repos:
625
+ if repo not in current:
626
+ io.say(f" {repo}: 허용 목록에 없습니다. 아무것도 하지 않습니다.")
627
+ if not targets:
628
+ return 0
629
+ try:
630
+ url = _saved_url(directory, io)
631
+ except Stop:
632
+ return 1
633
+ io.say(f"뺄 repo: {', '.join(targets)}")
634
+ if url:
635
+ io.say(f" 허용 목록에서 빼고, 그 repo의 {url} 웹훅을 지웁니다.")
636
+ else:
637
+ io.say(" 허용 목록에서 뺍니다. 웹훅 받는 주소가 저장되어 있지 않아 웹훅은 그대로 둡니다.")
638
+ io.say(f" {LEFT_ALONE}")
639
+ if not opts.yes and not opts.dry_run:
640
+ if not io.interactive:
641
+ io.say("터미널이 아니라 확인을 물을 수 없습니다. 지우려면 --yes를 주세요.")
642
+ return 1
643
+ if io.ask("계속할까요? [y/N]: ").strip().lower() not in ("y", "yes"):
644
+ io.say("그만둡니다.")
645
+ return 1
646
+ try:
647
+ new_text, removed = pure.remove_repos(text, targets)
648
+ except pure.ConfigEditError as e:
649
+ io.say(str(e))
650
+ return 1
651
+ if opts.dry_run:
652
+ io.say(f" (dry-run) 허용 목록에서 뺀다: {', '.join(removed)}")
653
+ else:
654
+ path.write_text(new_text)
655
+ io.say(f" 허용 목록에서 뺐습니다: {', '.join(removed)}")
656
+ all_ok = True
657
+ if url is not None:
658
+ run = deps.runner(None)
659
+ for repo in removed:
660
+ all_ok &= _remove_hooks(run, repo, url, io, opts.dry_run)
661
+ if not opts.dry_run:
662
+ io.say(RESTART)
663
+ return 0 if all_ok else 1
664
+
665
+
666
+ def _remove_hooks(run: gh.Runner, repo: str, url: str, io: Io, dry_run: bool) -> bool:
667
+ manual = f" {repo}: 웹훅은 손으로 지우세요 (GitHub 설정 → Webhooks, 주소 {url})"
668
+ try:
669
+ hooks = pure.hooks_at(gh.list_hooks(run, repo), url)
670
+ except gh.SetupGitHubError:
671
+ io.say(manual)
672
+ return False
673
+ if not hooks:
674
+ io.say(f" {repo}: 지울 웹훅이 없습니다")
675
+ return True
676
+ for hook in hooks:
677
+ if dry_run:
678
+ io.say(f" (dry-run) {repo}: 웹훅 {hook.id}를 지운다")
679
+ continue
680
+ try:
681
+ gh.delete_hook(run, repo, hook.id)
682
+ except gh.SetupGitHubError:
683
+ io.say(manual)
684
+ return False
685
+ io.say(f" {repo}: 웹훅을 지웠습니다")
686
+ return True
687
+
688
+
689
+ def list_repos(opts: Options, io: Io, deps: Deps, directory: Path | None = None) -> int:
690
+ directory = directory or files.config_dir()
691
+ path = directory / files.CONFIG_FILE
692
+ if not path.is_file():
693
+ io.say("설정이 없습니다. 먼저 npx pr-proof configure를 실행하세요.")
694
+ return 1
695
+ try:
696
+ repos = pure.config_repos(path.read_text())
697
+ except pure.ConfigEditError as e:
698
+ io.say(str(e))
699
+ return 1
700
+ if not repos:
701
+ io.say("처리하는 repo가 없습니다. 더하려면: npx pr-proof add <repo>")
702
+ return 0
703
+ if not opts.check:
704
+ for repo in repos:
705
+ io.say(repo)
706
+ return 0
707
+ try:
708
+ url = files.read_private(files.WEBHOOK_URL_FILE, directory)
709
+ except config.ConfigError:
710
+ url = None
711
+ run = deps.runner(None)
712
+ for repo in repos:
713
+ try:
714
+ status = pure.hook_status(gh.list_hooks(run, repo), url)
715
+ except gh.NoPermission:
716
+ status = "웹훅을 확인하지 못함 (권한 없음)"
717
+ except gh.SetupGitHubError:
718
+ status = "웹훅을 확인하지 못함 (GitHub 조회 실패)"
719
+ io.say(f"{repo} {status}")
720
+ return 0