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,133 @@
1
+ """테스트 실행 결과와 판정에 쓰는 상태."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import Final, Literal
6
+
7
+ # pytest 종료 코드: 0 통과, 1 실패, 2 중단(수집 오류 포함), 3 내부 오류, 4 사용법 오류, 5 없음
8
+ PYTEST_FAILED: Final = (1, 2)
9
+ PYTEST_INTERNAL_ERROR: Final = 3
10
+ PYTEST_USAGE_ERROR: Final = 4
11
+ PYTEST_NO_TESTS: Final = 5
12
+ PYTEST_TESTS_FAILED: Final = 1 # 테스트가 실패했다 (수집 오류·중단은 2)
13
+ KILLED_EXIT: Final = 137 # SIGKILL. 컨테이너 메모리 한도를 넘어 OOM으로 종료됨
14
+
15
+ # 환경 오류(Docker·설치·컨테이너 문제)는 상태가 아니라 SandboxError로 올라간다.
16
+ # unrunnable은 컨테이너 안에서 pytest가 돌았지만 PR 코드 때문에 결과를 못 낸 경우다.
17
+ RunStatus = Literal["passed", "failed", "no_tests", "timeout", "cancelled", "unrunnable"]
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class ReportSummary:
22
+ """pytest-json-report 결과 요약."""
23
+
24
+ passed: int = 0
25
+ failed: int = 0
26
+ errors: int = 0
27
+ skipped: int = 0
28
+ total: int = 0
29
+ failed_tests: tuple[str, ...] = ()
30
+
31
+ @classmethod
32
+ def from_report(cls, data: dict) -> "ReportSummary":
33
+ summary = data.get("summary", {})
34
+ failed_ids = [
35
+ t["nodeid"] for t in data.get("tests", []) if t.get("outcome") in ("failed", "error")
36
+ ]
37
+ # 수집 단계 오류(import 실패 등)는 tests가 아니라 collectors에 남는다
38
+ collect_errors = [
39
+ c["nodeid"] for c in data.get("collectors", []) if c.get("outcome") == "failed"
40
+ ]
41
+ return cls(
42
+ passed=summary.get("passed", 0),
43
+ failed=summary.get("failed", 0),
44
+ errors=summary.get("error", 0) + len(collect_errors),
45
+ skipped=summary.get("skipped", 0),
46
+ total=summary.get("total", 0),
47
+ failed_tests=tuple(failed_ids + collect_errors),
48
+ )
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class PytestRun:
53
+ """샌드박스에서 pytest를 한 번 실행한 결과. 산출물 경로는 worktree의 .pipeline-out/ 아래다."""
54
+
55
+ exit_code: int | None
56
+ summary: ReportSummary | None # report.json이 없거나 깨졌으면 None
57
+ report_path: Path | None = None
58
+ coverage_xml: Path | None = None
59
+ timed_out: bool = False
60
+ cancelled: bool = False
61
+ oom_killed: bool = False # 컨테이너가 메모리 한도로 죽음 (docker inspect OOMKilled)
62
+ output: str = field(default="", repr=False)
63
+ # 처음 실행에서 실패했다가 한 번 더 돌려 통과한 테스트 (DESIGN.md F8 flaky)
64
+ flaky: tuple[str, ...] = ()
65
+
66
+ @property
67
+ def passed_on_rerun(self) -> bool:
68
+ """실패한 테스트가 모두 재실행에서 통과했다. 수집 오류·테스트 오류가 있으면 아니다."""
69
+ s = self.summary
70
+ if s is None or not self.flaky or s.errors:
71
+ return False
72
+ return set(s.failed_tests) <= set(self.flaky)
73
+
74
+ @property
75
+ def passed_count(self) -> int:
76
+ """재실행에서 통과한 테스트까지 센 통과 수."""
77
+ if self.summary is None:
78
+ return 0
79
+ return self.summary.passed + (len(self.flaky) if self.passed_on_rerun else 0)
80
+
81
+ @property
82
+ def ok(self) -> bool:
83
+ return self.status == "passed"
84
+
85
+ @property
86
+ def status(self) -> RunStatus:
87
+ # 취소·시간 초과를 먼저 본다. 이때 파이프라인이 컨테이너를 지워 137이 나올 수 있다
88
+ if self.cancelled:
89
+ return "cancelled"
90
+ if self.timed_out:
91
+ return "timeout"
92
+ if self.exit_code == 0 and self.summary is not None:
93
+ return "passed"
94
+ if self.exit_code == PYTEST_TESTS_FAILED and self.passed_on_rerun:
95
+ return "passed" # 불안정한 테스트가 있다 (flaky). 코드 수정을 확인하는 데는 쓰지 않는다
96
+ if self.exit_code in PYTEST_FAILED and self.summary is not None:
97
+ return "failed"
98
+ if self.exit_code == PYTEST_NO_TESTS:
99
+ return "no_tests"
100
+ return "unrunnable"
101
+
102
+ @property
103
+ def unrunnable_reason(self) -> str | None:
104
+ """실행 불가일 때 PR 코멘트에 쓸 이유."""
105
+ if self.status != "unrunnable":
106
+ return None
107
+ if self.memory_exceeded:
108
+ return "메모리 한도를 넘어 종료됨"
109
+ if self.exit_code == PYTEST_INTERNAL_ERROR:
110
+ return "pytest 내부 오류"
111
+ if self.exit_code == PYTEST_USAGE_ERROR:
112
+ return "pytest 설정·인자 오류"
113
+ if self.summary is None:
114
+ return "결과 파일 없음 (conftest 등 수집 전 오류)"
115
+ return f"pytest 종료 코드 {self.exit_code}"
116
+
117
+ @property
118
+ def memory_exceeded(self) -> bool:
119
+ """메모리 한도 초과로 종료됨. 취소·시간 초과가 아닐 때만 137을 메모리 초과로 본다."""
120
+ return self.status == "unrunnable" and (self.oom_killed or self.exit_code == KILLED_EXIT)
121
+
122
+ @property
123
+ def allows_mechanical_fix(self) -> bool:
124
+ """동작을 바꾸지 않는 기계적 수정을 할 수 있는지 (4.6 표)."""
125
+ return self.status in ("passed", "no_tests")
126
+
127
+ @property
128
+ def allows_code_fix(self) -> bool:
129
+ """모델 수정처럼 코드를 바꾸는 수정을 할 수 있는지. 위반 줄 커버리지는 따로 본다.
130
+
131
+ 불안정한 테스트(flaky)가 있으면 수정 뒤 결과를 믿을 수 없으므로 막는다.
132
+ """
133
+ return self.status == "passed" and not self.flaky
@@ -0,0 +1,66 @@
1
+ """ruff가 낸 수정 편집을 텍스트에 적용한다 (docs/DESIGN.md 4.7 기계적 수정).
2
+
3
+ `ruff check --fix`는 파일 전체의 위반을 고쳐 PR이 건드리지 않은 줄까지 바꾼다. 그래서 ruff의
4
+ JSON 출력에 든 편집 중 수정 판단이 고치기로 정한 위반의 것만 골라 직접 적용한다. 편집은 텍스트
5
+ 치환이라 코드를 실행하지 않는다.
6
+ """
7
+
8
+ from collections.abc import Sequence
9
+ from dataclasses import dataclass
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class TextEdit:
14
+ """(row, column)부터 (end_row, end_column) 앞까지를 content로 바꾼다.
15
+
16
+ 줄·열은 1부터 세고, 열은 문자 단위다.
17
+ """
18
+
19
+ row: int
20
+ column: int
21
+ end_row: int
22
+ end_column: int
23
+ content: str
24
+
25
+
26
+ def _line_starts(text: str) -> list[int]:
27
+ starts = [0]
28
+ for i, ch in enumerate(text):
29
+ if ch == "\n":
30
+ starts.append(i + 1)
31
+ return starts
32
+
33
+
34
+ def _offset(starts: list[int], text: str, row: int, column: int) -> int:
35
+ if row > len(starts): # 파일 끝 다음 줄을 가리키는 끝 위치
36
+ return len(text)
37
+ return min(starts[row - 1] + column - 1, len(text))
38
+
39
+
40
+ def apply_edits(text: str, groups: Sequence[Sequence[TextEdit]]) -> tuple[str, int]:
41
+ """위반별 편집 묶음을 적용한다. 앞서 고른 묶음과 겹치는 묶음은 건너뛴다.
42
+
43
+ (새 텍스트, 적용한 묶음 수). 겹쳐서 건너뛴 위반은 다음 회차에 ruff를 다시 돌려 고친다
44
+ (ruff --fix도 같은 방식으로 여러 번 돈다).
45
+ """
46
+ starts = _line_starts(text)
47
+ chosen: list[tuple[int, int, str]] = []
48
+ applied = 0
49
+ for group in groups:
50
+ spans = [
51
+ (_offset(starts, text, e.row, e.column), _offset(starts, text, e.end_row, e.end_column),
52
+ e.content)
53
+ for e in group
54
+ ] # fmt: skip
55
+ if not spans or any(_overlaps(s, c) for s in spans for c in chosen):
56
+ continue
57
+ chosen.extend(spans)
58
+ applied += 1
59
+ for start, end, content in sorted(chosen, key=lambda span: span[0], reverse=True):
60
+ text = text[:start] + content + text[end:]
61
+ return text, applied
62
+
63
+
64
+ def _overlaps(a: tuple[int, int, str], b: tuple[int, int, str]) -> bool:
65
+ # 같은 위치에 넣기만 하는 두 편집도 순서가 정해지지 않으므로 겹친 것으로 본다
66
+ return (a[0] < b[1] and b[0] < a[1]) or a[0] == b[0]
@@ -0,0 +1,152 @@
1
+ """저장소의 도구 (docs/DESIGN.md 2.3, 4.3 도구 설정, 4.4 도구 목록, 7.7 Python 프로필의 도구).
2
+
3
+ 데이터와 결정적 판단만 한다. 받기와 실행은 app/worker/sandbox/toolcache.py와
4
+ app/worker/lang/python.py가 한다.
5
+
6
+ - 도구 목록(`TOOL_LIST`)은 밖에서 받아 오는 도구뿐이다. 문서 규칙의 확인 방법을 고르는 모델은 이
7
+ 목록 안에서만 고른다. 플러그인 로더는 만들지 않는다.
8
+ - 도구 설정에서 온 규칙 묶음: base의 ruff 설정 파일이 있으면 "이 설정대로 ruff를 통과한다"는 규칙
9
+ 하나(`CONFIG_RULE_ID`)가 생긴다. 그 규칙의 위반은 ruff의 코드(`F401`)를 규칙 id로 갖는다 (4.3).
10
+ 설정 파일이 없으면 이 규칙도 없다. 파이프라인이 고른 ruff 규칙은 없다 (2.2).
11
+ - 버전: 저장소의 의존성 파일이 `ruff==X.Y.Z`로 고정했으면 그 버전, 아니면 파이프라인의 기본 버전.
12
+ """
13
+
14
+ import re
15
+ import tomllib
16
+ from collections.abc import Iterable, Mapping
17
+ from dataclasses import dataclass
18
+ from typing import Final
19
+
20
+ from app.worker.cache_key_pure import text_hash
21
+ from app.worker.rule_pure import CheckMethod, Rule, RuleSource
22
+
23
+ RUFF: Final = "ruff"
24
+ RUFF_FORMAT: Final = "ruff-format"
25
+ # 모델에 보이는 도구 목록 (4.4의 표). 바꾸면 TOOLS_VERSION이 바뀌어 도구 선택을 다시 묻는다
26
+ TOOL_LIST: Final[Mapping[str, str]] = {
27
+ RUFF: (
28
+ "ruff가 가진 린트 규칙. 규칙 코드를 하나 이상 고른다 (예: F401 안 쓰는 import, T201 print, "
29
+ "PLR2004 비교의 매직 값, PLW0603 global 문). 기계적 수정은 ruff의 안전한 수정이 있는 "
30
+ "코드만"
31
+ ),
32
+ RUFF_FORMAT: (
33
+ "ruff format의 코드 모양 (들여쓰기, 줄 바꿈, 따옴표, 공백). 코드를 고르지 않는다. 기계적 "
34
+ "수정은 base가 ruff format을 따르는 저장소에서만"
35
+ ),
36
+ }
37
+ TOOLS_VERSION: Final = text_hash("\0".join(f"{k}={v}" for k, v in sorted(TOOL_LIST.items())))[:12]
38
+ # ruff가 설정 파일을 찾는 우선순위와 같다. pyproject.toml은 [tool.ruff]가 있을 때만 ruff 설정이다
39
+ RUFF_CONFIG_FILES: Final = (".ruff.toml", "ruff.toml", "pyproject.toml")
40
+ # 도구 설정에서 온 규칙 묶음의 id. `rules.disabled`에 적으면 묶음 전체가 꺼진다
41
+ CONFIG_RULE_ID: Final = "ruff"
42
+ RUFF_CODE: Final = re.compile(r"^[A-Z]{1,4}[0-9]{1,4}$")
43
+ MAX_CODES: Final = 10
44
+ REQUIREMENTS: Final = re.compile(r"^requirements[\w.-]*\.txt$")
45
+ # `ruff==0.17.4`, `ruff[extra] == 0.17.4 ; python_version > "3"`. 정확히 고정한 것만 본다
46
+ _PIN: Final = re.compile(
47
+ r"^\s*ruff\s*(?:\[[^\]]*\])?\s*===?\s*([0-9]+(?:\.[0-9]+){1,3})\s*(?:[;#].*)?$"
48
+ )
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class RuffConfig:
53
+ name: str # 저장소 루트의 설정 파일 이름
54
+ text: str
55
+ blob_sha: str
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class RuffSetup:
60
+ """이 저장소의 ruff. 받는 것은 규칙 묶음이 ruff를 쓸 때뿐이다 (2.3)."""
61
+
62
+ version: str
63
+ pinned_by: str = "" # 버전을 고정한 파일. 비면 파이프라인의 기본 버전
64
+ config: RuffConfig | None = None # base의 ruff 설정. 없으면 도구 설정의 규칙도 없다
65
+ available: bool = True # 파이프라인이 해시를 고정한 버전인지
66
+
67
+ @property
68
+ def label(self) -> str:
69
+ who = f"{self.pinned_by}가 고정" if self.pinned_by else "기본 버전"
70
+ return f"ruff {self.version} ({who})"
71
+
72
+
73
+ def ruff_config_name(files: Mapping[str, str]) -> tuple[str | None, str | None]:
74
+ """(쓸 ruff 설정 파일 이름, 읽지 못한 이유). files는 base에서 읽은 {이름: 내용}이다."""
75
+ for name in RUFF_CONFIG_FILES:
76
+ if name not in files:
77
+ continue
78
+ if name != "pyproject.toml":
79
+ return name, None
80
+ try:
81
+ data = tomllib.loads(files[name])
82
+ except tomllib.TOMLDecodeError as e:
83
+ return None, f"`pyproject.toml`을 읽지 못해 ruff 설정을 쓰지 않음: {e}"
84
+ tool = data.get("tool")
85
+ return (name if isinstance(tool, dict) and RUFF in tool else None), None
86
+ return None, None
87
+
88
+
89
+ def pinned_version(files: Mapping[str, str]) -> tuple[str, str] | None:
90
+ """(버전, 고정한 파일). pyproject.toml의 의존성 목록을 먼저, 그다음 requirements*.txt를 이름
91
+ 순서로 본다. 처음 찾은 정확한 고정(`==`)을 쓴다."""
92
+ names = [n for n in ("pyproject.toml",) if n in files]
93
+ names += sorted(n for n in files if REQUIREMENTS.match(n))
94
+ for name in names:
95
+ lines = (
96
+ _pyproject_requirements(files[name])
97
+ if name == "pyproject.toml"
98
+ else (files[name].splitlines())
99
+ )
100
+ for line in lines:
101
+ match = _PIN.match(line)
102
+ if match:
103
+ return match.group(1), name
104
+ return None
105
+
106
+
107
+ def _pyproject_requirements(text: str) -> list[str]:
108
+ """PEP 621의 `dependencies`, `optional-dependencies`와 PEP 735의 `dependency-groups`."""
109
+ try:
110
+ data = tomllib.loads(text)
111
+ except tomllib.TOMLDecodeError:
112
+ return []
113
+ out: list[str] = []
114
+ project = data.get("project")
115
+ if isinstance(project, dict):
116
+ out += _strings(project.get("dependencies"))
117
+ optional = project.get("optional-dependencies")
118
+ if isinstance(optional, dict):
119
+ for group in optional.values():
120
+ out += _strings(group)
121
+ groups = data.get("dependency-groups")
122
+ if isinstance(groups, dict):
123
+ for group in groups.values():
124
+ out += _strings(group)
125
+ return out
126
+
127
+
128
+ def _strings(value: object) -> list[str]:
129
+ return [v for v in value if isinstance(v, str)] if isinstance(value, list) else []
130
+
131
+
132
+ def config_rule(config: RuffConfig) -> Rule:
133
+ """도구 설정에서 온 규칙 묶음 (4.3). 팀이 `ignore`, `per-file-ignores`, `# noqa`로 끈 것은
134
+ ruff가 설정대로 따른다. 수정 방법은 ruff의 안전한 수정이 있는 위반만 기계적 수정이다."""
135
+ section = "[tool.ruff]" if config.name == "pyproject.toml" else ""
136
+ return Rule(
137
+ id=CONFIG_RULE_ID,
138
+ text=f"{config.name}의 설정대로 ruff를 통과한다",
139
+ source=RuleSource(config.name, section, config.blob_sha),
140
+ origin="tool_config",
141
+ scope=(),
142
+ check=CheckMethod("tool", tool=RUFF),
143
+ fix="mechanical",
144
+ )
145
+
146
+
147
+ def valid_codes(codes: Iterable[str]) -> tuple[str, ...] | None:
148
+ """모델이 고른 ruff 코드의 형식. 틀리면 None. 실재하는지는 샌드박스의 `ruff rule`이 본다."""
149
+ out = tuple(dict.fromkeys(c.strip().upper() for c in codes))
150
+ if not out or len(out) > MAX_CODES or not all(RUFF_CODE.match(c) for c in out):
151
+ return None
152
+ return out
@@ -0,0 +1,305 @@
1
+ """`update` 작업: PR의 한 커밋을 검사하고 코멘트에 결과를 남긴다."""
2
+
3
+ import logging
4
+ from dataclasses import dataclass
5
+ from typing import Any, Final
6
+
7
+ from app.shared import version
8
+ from app.shared.job_pure import PRJob
9
+ from app.worker import graph, guard, merged_fix_pure, records, repo, report, retry
10
+ from app.worker.access_pure import Author, NeedsApproval
11
+ from app.worker.deps import Deps
12
+ from app.worker.doc_rules_pure import Found
13
+ from app.worker.fix import proposal
14
+ from app.worker.github import PullRefs
15
+ from app.worker.lang.install_pure import install_failure_outcome
16
+ from app.worker.lang.python import DependencyInstallError
17
+ from app.worker.merged_fix_pure import CarriedFrom, VerifiedCheck
18
+ from app.worker.rules import doc_rules
19
+ from app.worker.sandbox import docker_cli
20
+
21
+ CLOSED_HEAD: Final = "closed" # PR이 닫혔다는 Redis 최신 head 표시. 어떤 커밋 SHA와도 같지 않다
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+
26
+ def admit(job: PRJob, deps: Deps, final: bool) -> PullRefs | str:
27
+ """GitHub에서 PR의 지금 상태를 확인하고 가드레일을 지난다 (8.6). 검사할 작업이면 조회한 PR을,
28
+ 아니면 결과 이름을 돌려준다.
29
+
30
+ 닫힌 PR은 검사하지 않는다. 닫히기 전에 등록된 작업이 닫힌 뒤에 실행될 수 있다(워커가 죽어 RQ가
31
+ 나중에 다시 실행한 경우). 그대로 두면 닫힌 PR의 코멘트를 고치고 제안 PR을 연다. 최신 head를
32
+ 닫힘 표시로 되돌려, 이미 돌고 있는 작업도 멈추게 한다.
33
+
34
+ 신뢰되지 않은 작성자의 PR이고 지금 head가 승인되지 않았으면 승인 안내만 달고 끝낸다. 같은
35
+ 조회에서 읽은 작성자 값으로 정한다. 조회나 base 설정 읽기에 실패하면 환경 오류로 재시도한다
36
+ (아직 runs 기록 전이므로 마지막 시도면 작업 키만 지운다).
37
+ """
38
+ try:
39
+ refs = deps.github.pr_refs(job.repo, job.pr_number)
40
+ if not refs.open:
41
+ deps.store.set_latest_head(job.repo, job.pr_number, CLOSED_HEAD)
42
+ return "closed"
43
+ gate = guard.check(job, deps, refs)
44
+ if isinstance(gate.decision, NeedsApproval):
45
+ return guard.block(job, deps, refs)
46
+ except retry.EnvironmentFailure:
47
+ if final:
48
+ deps.store.release(job)
49
+ raise
50
+ return refs
51
+
52
+
53
+ def flow_context(deps: Deps, run_id: int, comment_id: int | None) -> graph.FlowContext:
54
+ return graph.FlowContext(
55
+ store=deps.store,
56
+ github=deps.github,
57
+ data_dir=deps.settings.data_dir,
58
+ run_id=run_id,
59
+ comment_id=comment_id,
60
+ max_memory_gb=deps.settings.sandbox.max_memory_gb,
61
+ call_maxima=deps.settings.model.calls,
62
+ rag_model=deps.settings.rag.embed_model,
63
+ sandbox_names=docker_cli.Names(
64
+ image=deps.settings.sandbox.image,
65
+ container_prefix=deps.settings.sandbox.container_prefix,
66
+ ),
67
+ )
68
+
69
+
70
+ def pending_fix(job: PRJob, deps: Deps, bundle: str) -> graph.PendingFix | None:
71
+ """이 커밋에 `/fix`로 재개할 묶음의 수정이 있으면 그 종류 (승인 대기, 실패, 다시 돌리기)."""
72
+ return graph.pending_kind(job, flow_context(deps, run_id=0, comment_id=None), bundle)
73
+
74
+
75
+ def resume_fix(job: PRJob, deps: Deps, approval: dict[str, Any], author: Author) -> str:
76
+ """/fix 승인: 멈춰 있던 그래프를 수정 단계부터 이어 간다. job은 PR의 지금 head의 update 작업.
77
+
78
+ 가드레일(8.6)을 지난 명령 작업에서만 부른다. author는 그때 GitHub에서 읽은 PR 작성자다.
79
+ """
80
+ store = deps.store
81
+ _, final = retry.attempt()
82
+ store.set_latest_head(job.repo, job.pr_number, job.head_sha)
83
+ run_id = store.start_run(job, kind="fix", author=author)
84
+ ctx = flow_context(deps, run_id, store.last_comment_id(job.repo, job.pr_number))
85
+ try:
86
+ result = graph.resume_fix(job, ctx, approval)
87
+ # 수정 뒤 테스트의 설치 실패는 수정 전에 설치가 됐으므로 환경 쪽으로 본다
88
+ except (DependencyInstallError, *retry.EnvironmentFailure) as e:
89
+ retry.environment_failure(job, ctx, run_id, final, e)
90
+ raise
91
+ except Exception as e: # 파이프라인 버그, rq JobTimeoutException
92
+ retry.unexpected_error(job, ctx, run_id, final, e)
93
+ raise
94
+ if result is None:
95
+ store.finish_run(run_id, "done", comment_id=ctx.comment_id)
96
+ return "no_pending_fix"
97
+ if result.get("stopped"):
98
+ store.finish_run(run_id, "cancelled", comment_id=ctx.comment_id)
99
+ return "stale"
100
+ # 다시 돌린 수정 판단이 모두 skip이면 그 묶음의 수정이 돌지 않는다
101
+ done = result.get(graph.STATE_KEYS[approval["skill"]][0])
102
+ status = done.status if done is not None else "no_targets"
103
+ store.finish_run(run_id, "done", test_status=status, comment_id=ctx.comment_id)
104
+ return f"fix:{status}"
105
+
106
+
107
+ def process_update(job: PRJob, deps: Deps) -> str:
108
+ _, final = retry.attempt()
109
+ admitted = admit(job, deps, final)
110
+ if isinstance(admitted, str):
111
+ return admitted # closed, needs_approval: 할 일이 없다
112
+ return run_admitted(job, deps, admitted)
113
+
114
+
115
+ def run_admitted(job: PRJob, deps: Deps, refs: PullRefs, *, carry: bool = True) -> str:
116
+ """가드레일(8.6)을 지난 update 작업을 돌린다. refs는 같은 작업에서 방금 조회한 PR이다.
117
+
118
+ 웹훅은 순서대로 오지 않을 수 있다. 옛 커밋의 웹훅이 늦게 오면 Redis의 최신 head가 옛 커밋으로
119
+ 덮이고, 그대로 두면 옛 커밋의 결과가 PR에 남는다. 그래서 최신 head를 GitHub의 값으로 바로잡고,
120
+ 이 작업의 커밋이 지금 head가 아니면 더 새 커밋의 작업(또는 동기화)에 맡긴다.
121
+
122
+ 이 커밋이 파이프라인 수정안의 머지 커밋이고 내용이 검증한 수정안과 같으면 검사하지 않고 검증한
123
+ 결과를 옮겨 적는다(`carry_plan`). carry가 False면(`/recheck`) 늘 처음부터 검사한다.
124
+ """
125
+ store, github = deps.store, deps.github
126
+ attempt, final = retry.attempt()
127
+ store.set_latest_head(job.repo, job.pr_number, refs.head_sha)
128
+ if refs.head_sha != job.head_sha:
129
+ return "stale"
130
+ run_id = store.start_run(job, author=guard.author(refs))
131
+ comment_id = store.last_comment_id(job.repo, job.pr_number)
132
+ ctx = flow_context(deps, run_id, comment_id)
133
+ try:
134
+ ctx.comment_id = github.upsert_comment(
135
+ job.repo, job.pr_number, report.render_progress(job.head_sha, "체크아웃"), comment_id
136
+ )
137
+ # 이전 커밋의 열린 제안을 정리한다. 머지됐는지도 여기서 알게 된다 (루프 방지에 쓴다)
138
+ proposal.refresh(store, github, job.repo, job.pr_number)
139
+ plan = carry_plan(job, ctx) if carry else "/recheck"
140
+ proposal.supersede(store, github, job.repo, job.pr_number, job.head_sha)
141
+ if isinstance(plan, Carry):
142
+ result = graph.carry_flow(job, ctx, plan.values)
143
+ else:
144
+ if carry and plan != merged_fix_pure.NOT_MERGE_COMMIT:
145
+ log.info("수정안의 머지 커밋이지만 처음부터 검사함 %s#%s %s: %s",
146
+ job.repo, job.pr_number, job.head_sha[:7], plan) # fmt: skip
147
+ result = graph.run_flow(job, ctx, retry=attempt > 1)
148
+ except DependencyInstallError as e:
149
+ if install_failure_outcome(e.kind, attempt) == "unrunnable":
150
+ body = report.render_install_failure(
151
+ job.head_sha, e.detail, base=ctx.base,
152
+ doc_rules=ctx.doc_rules,
153
+ checkers=doc_rules.shown_checkers(ctx.doc_rules, store), kind=e.kind,
154
+ packages=e.packages, pr=ctx.pr_checks, description=ctx.pr_description,
155
+ ) # fmt: skip
156
+ ctx.comment_id = github.upsert_comment(job.repo, job.pr_number, body, ctx.comment_id)
157
+ store.finish_run(run_id, "done", test_status="unrunnable", comment_id=ctx.comment_id)
158
+ return "unrunnable"
159
+ retry.environment_failure(job, ctx, run_id, final, e)
160
+ raise
161
+ except retry.EnvironmentFailure as e:
162
+ retry.environment_failure(job, ctx, run_id, final, e)
163
+ raise
164
+ except Exception as e: # 파이프라인 버그, rq JobTimeoutException(작업 시간 초과)
165
+ retry.unexpected_error(job, ctx, run_id, final, e)
166
+ raise
167
+
168
+ if result.get("stopped"):
169
+ store.finish_run(run_id, "cancelled", comment_id=ctx.comment_id)
170
+ return "stale" # 새 커밋의 작업이 코멘트를 이어서 고친다
171
+ run = result["test_run"]
172
+ store.finish_run(run_id, "done", test_status=run.status, comment_id=ctx.comment_id)
173
+ return run.status
174
+
175
+
176
+ @dataclass(frozen=True)
177
+ class Carry:
178
+ """옮겨 적을 그래프 상태 (`graph.carry_flow`)."""
179
+
180
+ values: graph.FlowState
181
+
182
+
183
+ def carry_plan(job: PRJob, ctx: graph.FlowContext) -> Carry | str:
184
+ """이 커밋에 검증한 결과를 옮겨 적을 수 있으면 그 상태, 아니면 까닭 (4.9 "수정안 PR 상태
185
+ 관리"). 판정은 `merged_fix_pure`가 하고 여기서는 재료를 모은다: 수정안과 저장한 수정 시도, 두
186
+ 커밋의 검사 기록, 검증한 커밋의 체크포인트, bare 캐시의 머지 커밋(부모, 트리, 파일).
187
+
188
+ `proposal.refresh` 뒤에 부른다(머지 여부와 머지 커밋을 거기서 안다). bare 캐시를 받지 못하면
189
+ 환경 오류로 올라간다(처음부터 검사해도 같은 곳에서 실패한다).
190
+ """
191
+ store = ctx.store
192
+ picked = merged_fix_pure.merged_proposal(store.proposals(job.repo, job.pr_number), job.head_sha)
193
+ if isinstance(picked, str):
194
+ return picked
195
+ assert picked.attempt_id is not None
196
+ attempt = store.fix_attempt(picked.attempt_id)
197
+ problem = merged_fix_pure.attempt_problem(attempt, picked)
198
+ if problem is not None:
199
+ return problem
200
+ assert attempt is not None and attempt.patch is not None
201
+ verified_sha = picked.head_sha
202
+ problem = merged_fix_pure.runs_problem(
203
+ store.runs(job.repo, job.pr_number, verified_sha),
204
+ store.runs(job.repo, job.pr_number, job.head_sha),
205
+ version.current(),
206
+ )
207
+ if problem is not None:
208
+ return problem
209
+ check, values = _verified_check(job.model_copy(update={"head_sha": verified_sha}), ctx,
210
+ picked.skill) # fmt: skip
211
+ problem = merged_fix_pure.state_problem(
212
+ check, bundle=picked.skill, attempt_id=picked.attempt_id, base_sha=job.base_sha
213
+ )
214
+ if problem is not None:
215
+ return problem
216
+ assert isinstance(check.found, Found) and check.decisions is not None
217
+ assert check.fix is not None and job.head_sha is not None
218
+ bare = repo.ensure_bare(ctx.data_dir, job.repo)
219
+ repo.fetch_commit(bare, verified_sha)
220
+ repo.fetch_commit(bare, job.head_sha)
221
+ try:
222
+ expected = repo.patched_tree(
223
+ bare, verified_sha, attempt.patch.encode(), ctx.data_dir / "tmp"
224
+ )
225
+ except repo.GitError as e:
226
+ log.info("저장한 패치를 검증한 커밋에 다시 적용하지 못함: %s", e)
227
+ return "저장한 패치를 검증한 커밋에 적용하지 못함"
228
+ problem = merged_fix_pure.merge_problem(
229
+ verified_sha, repo.commit_parents(bare, job.head_sha), repo.tree_of(bare, job.head_sha),
230
+ expected,
231
+ ) # fmt: skip
232
+ if problem is not None:
233
+ return problem
234
+ lines: dict[str, list[str] | None] = {}
235
+
236
+ def lines_of(path: str) -> list[str] | None:
237
+ if path not in lines:
238
+ lines[path] = repo.bare_lines(bare, job.head_sha, path)
239
+ return lines[path]
240
+
241
+ moved = merged_fix_pure.carried(
242
+ check.found, check.decisions, merged_fix_pure.fixed_ids(check.fix), attempt.patch,
243
+ lines_of,
244
+ ) # fmt: skip
245
+ if isinstance(moved, str):
246
+ return moved
247
+ found, decisions = moved
248
+ if records.mark_rejected(store, job, found) != found:
249
+ return "검증한 뒤 같은 줄을 고친 수정안이 거절됨"
250
+ out: graph.FlowState = {
251
+ "doc_rules": found, "test_run": check.test_run, "fix_decisions": decisions,
252
+ "carried": CarriedFrom(picked.number, picked.skill, verified_sha,
253
+ merged_fix_pure.unverified_count(check.fix)),
254
+ } # fmt: skip
255
+ if values.get("pr_checks") is not None:
256
+ out["pr_checks"] = values["pr_checks"]
257
+ if values.get("pr_description") is not None:
258
+ # PR 글도 사람의 커밋도 그대로이고 수정안의 변경은 세지 않으므로 검증한 커밋의 결과를 쓴다.
259
+ # 수정안이 바꾼 줄을 가리키면 처음부터 검사한다
260
+ description = merged_fix_pure.carried_description(values["pr_description"], attempt.patch)
261
+ if isinstance(description, str):
262
+ return description
263
+ out["pr_description"] = description
264
+ if values.get("rag_switch") is not None:
265
+ out["rag_switch"] = values["rag_switch"]
266
+ return Carry(out)
267
+
268
+
269
+ def _verified_check(
270
+ verified: PRJob, ctx: graph.FlowContext, bundle: str
271
+ ) -> tuple[VerifiedCheck, dict[str, Any]]:
272
+ values, finished = graph.finished_values(verified, ctx)
273
+ job = values.get("job")
274
+ return VerifiedCheck(
275
+ finished=finished,
276
+ base_sha=job.base_sha if isinstance(job, PRJob) else None,
277
+ found=values.get("doc_rules"),
278
+ test_run=values.get("test_run"),
279
+ decisions=values.get("fix_decisions"),
280
+ fix=values.get(graph.STATE_KEYS[bundle][0]),
281
+ pr_checks=values.get("pr_checks"),
282
+ pr_description=values.get("pr_description"),
283
+ ), dict(values)
284
+
285
+
286
+ def process_close(job: PRJob, deps: Deps) -> str:
287
+ """원본 PR이 닫혔다: 진행 중인 검사를 멈추고, 남은 제안 PR을 닫고 브랜치를 지운다 (F10).
288
+
289
+ 최신 head를 닫힘 표시로 바꾸면 실행 중인 작업이 10초 안에 낡은 작업으로 보고 멈춘다.
290
+ 다시 열리면(reopened) 웹훅이 최신 head를 새로 적는다.
291
+
292
+ 먼저 GitHub에서 PR이 정말 닫혔는지 본다. closed 웹훅이 reopened보다 늦게 오거나, 동기화의
293
+ 열린 PR 목록이 잘려 열린 PR이 빠지면, 열린 PR의 제안을 닫게 된다.
294
+ """
295
+ _, final = retry.attempt()
296
+ try:
297
+ if deps.github.pr_refs(job.repo, job.pr_number).open:
298
+ return "still_open"
299
+ deps.store.set_latest_head(job.repo, job.pr_number, CLOSED_HEAD)
300
+ closed = proposal.close_all(deps.store, deps.github, job.repo, job.pr_number)
301
+ except Exception:
302
+ if final:
303
+ deps.store.release(job)
304
+ raise
305
+ return f"closed:{closed}"