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,196 @@
1
+ """모델이 쓴 검사기 (docs/DESIGN.md 7.2). 데이터, id 계산, 실행 전 본문 확인.
2
+
3
+ 검사기 본문은 모델이 쓴 믿지 않는 입력이다. 샌드박스에 넣기 전에 `validate_body`가 형식과 허용
4
+ 범위를 본다. 통과한 본문만 실행하고, 거절 이유는 다음 회차의 모델에 넘긴다.
5
+ """
6
+
7
+ import ast
8
+ import hashlib
9
+ import json
10
+ import re
11
+ import sys
12
+ from collections.abc import Iterator, Mapping
13
+ from dataclasses import dataclass
14
+ from datetime import datetime
15
+ from pathlib import PurePosixPath
16
+ from typing import Final, Literal
17
+
18
+ import yaml
19
+
20
+ from app.worker.rule_pure import Example
21
+ from app.worker.tools_pure import RUFF_CODE
22
+
23
+ # path-pattern은 코드가 아니라 선언(JSON)이다: 경로에 거는 정규식 조건. 파이프라인이 쓴 고정
24
+ # 스크립트가 샌드박스에서 맞춘다 (app/worker/sandbox/checker_runner.py).
25
+ # ruff·ruff-format은 저장소의 도구다 (4.4 (a)). 본문은 선언(JSON)이다: ruff는 {"codes": [...]}(비면
26
+ # base 설정의 규칙 전부), ruff-format은 {}. 모델이 쓴 검사기가 아니다
27
+ CheckerKind = Literal["ast-grep", "python-ast", "path-pattern", "ruff", "ruff-format"]
28
+ TOOL_KINDS: Final = frozenset({"ruff", "ruff-format"})
29
+ PATH_PATTERN_KEYS: Final = frozenset({"applies_to", "condition", "pattern", "message"})
30
+ PATH_CONDITIONS: Final = ("must_match", "must_not_match")
31
+ MAX_REGEX_CHARS: Final = 300
32
+
33
+ MAX_BODY_CHARS: Final = 20_000
34
+ # 이 단계의 검사기는 Python 파일만 본다 (7.7 Python 프로필)
35
+ AST_GREP_LANGUAGE: Final = "python"
36
+ # 그 밖의 키는 거절한다. fix·rewriters·transform은 코드를 바꾸는 키이고, files·ignores는 적용
37
+ # 범위를 규칙 밖에서 정한다. 적용 범위는 파이프라인이 규칙의 scope로 정한다
38
+ AST_GREP_KEYS: Final = frozenset(
39
+ {"id", "language", "rule", "constraints", "utils", "message", "severity", "note"}
40
+ )
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Checker:
45
+ id: str # 본문 해시 (checker_id)
46
+ rule_id: str
47
+ rule_text_hash: str
48
+ kind: CheckerKind
49
+ body: str # 규칙 YAML 또는 스크립트
50
+ examples: tuple[Example, ...]
51
+ engine_version: str # 검사 엔진 버전. 바뀌면 예시 확인을 다시 한다
52
+ model: str = ""
53
+ verified_at: datetime | None = None
54
+
55
+
56
+ def is_repo_path(path: str) -> bool:
57
+ """검사기에 넘길 수 있는 저장소 기준 상대 경로인지. 모델이 쓴 경로 예시도 이것으로 본다."""
58
+ p = PurePosixPath(path)
59
+ return bool(path) and not p.is_absolute() and ".." not in p.parts and "\0" not in path
60
+
61
+
62
+ def checker_id(body: str) -> str:
63
+ return hashlib.sha256(body.encode()).hexdigest()
64
+
65
+
66
+ def validate_body(kind: CheckerKind, body: str) -> str | None:
67
+ """실행하면 안 되는 본문이면 그 이유, 괜찮으면 None."""
68
+ if not body.strip():
69
+ return "검사기 본문이 비어 있음"
70
+ if len(body) > MAX_BODY_CHARS:
71
+ return f"검사기 본문이 {MAX_BODY_CHARS}자를 넘음"
72
+ if kind == "ast-grep":
73
+ return _validate_ast_grep(body)
74
+ if kind == "path-pattern":
75
+ return _validate_path_pattern(body)
76
+ if kind in TOOL_KINDS:
77
+ return _validate_tool(kind, body)
78
+ return _validate_python_ast(body)
79
+
80
+
81
+ def tool_codes(body: str) -> tuple[str, ...]:
82
+ """ruff 검사기 본문의 코드. 비면 base 설정의 규칙 전부다. 본문은 `validate_body`를 거쳤다."""
83
+ return tuple(json.loads(body).get("codes", ()))
84
+
85
+
86
+ def _validate_tool(kind: CheckerKind, body: str) -> str | None:
87
+ try:
88
+ decl = json.loads(body)
89
+ except ValueError as e:
90
+ return f"JSON을 읽지 못함: {e}"
91
+ if not isinstance(decl, dict):
92
+ return "선언의 최상위가 객체가 아님"
93
+ allowed = {"codes"} if kind == "ruff" else set()
94
+ extra = sorted(str(k) for k in decl if k not in allowed)
95
+ if extra:
96
+ return f"쓸 수 없는 키: {', '.join(extra)}"
97
+ codes = decl.get("codes", [])
98
+ if not isinstance(codes, list) or not all(
99
+ isinstance(c, str) and RUFF_CODE.match(c) for c in codes
100
+ ):
101
+ return "codes는 ruff 규칙 코드의 목록이어야 함"
102
+ return None
103
+
104
+
105
+ def _validate_path_pattern(body: str) -> str | None:
106
+ """선언의 모양과 정규식 문법만 본다. 맞추는 일은 시간 제한이 있는 샌드박스가 한다."""
107
+ try:
108
+ decl = json.loads(body)
109
+ except ValueError as e:
110
+ return f"JSON을 읽지 못함: {e}"
111
+ if not isinstance(decl, dict):
112
+ return "선언의 최상위가 객체가 아님"
113
+ extra = sorted(str(k) for k in decl if k not in PATH_PATTERN_KEYS)
114
+ if extra:
115
+ allowed = ", ".join(sorted(PATH_PATTERN_KEYS))
116
+ return f"쓸 수 없는 키: {', '.join(extra)} (쓸 수 있는 키: {allowed})"
117
+ if decl.get("condition") not in PATH_CONDITIONS:
118
+ allowed = " 또는 ".join(PATH_CONDITIONS)
119
+ return f"condition은 {allowed}여야 함 (받은 값: {decl.get('condition')!r})"
120
+ if not isinstance(decl.get("pattern"), str) or not decl["pattern"]:
121
+ return "pattern이 없거나 문자열이 아님"
122
+ for key in ("applies_to", "pattern"):
123
+ value = decl.get(key, "")
124
+ if not isinstance(value, str):
125
+ return f"{key}가 문자열이 아님"
126
+ if len(value) > MAX_REGEX_CHARS:
127
+ return f"{key}가 {MAX_REGEX_CHARS}자를 넘음"
128
+ try:
129
+ re.compile(value)
130
+ except re.error as e:
131
+ return f"{key}의 정규식이 틀림: {e}"
132
+ if not isinstance(decl.get("message", ""), str):
133
+ return "message가 문자열이 아님"
134
+ return None
135
+
136
+
137
+ def _validate_ast_grep(body: str) -> str | None:
138
+ try:
139
+ if any(isinstance(event, yaml.AliasEvent) for event in yaml.parse(body)):
140
+ return "YAML 별칭(*name)은 쓰지 않는다"
141
+ documents = [d for d in yaml.safe_load_all(body) if d is not None]
142
+ except yaml.YAMLError as e:
143
+ return f"YAML을 읽지 못함: {str(e).splitlines()[0]}"
144
+ if len(documents) != 1:
145
+ return f"YAML 문서는 하나여야 함 ({len(documents)}개)"
146
+ config = documents[0]
147
+ if not isinstance(config, Mapping):
148
+ return "규칙 YAML의 최상위가 매핑이 아님"
149
+ extra = sorted(str(k) for k in config if k not in AST_GREP_KEYS)
150
+ if extra:
151
+ allowed = ", ".join(sorted(AST_GREP_KEYS))
152
+ return f"쓸 수 없는 키: {', '.join(extra)} (쓸 수 있는 키: {allowed})"
153
+ if config.get("language") != AST_GREP_LANGUAGE:
154
+ return f"language는 {AST_GREP_LANGUAGE}여야 함 (받은 값: {config.get('language')!r})"
155
+ if not isinstance(config.get("rule"), Mapping):
156
+ return "rule이 없거나 매핑이 아님"
157
+ utils = config.get("utils") or {}
158
+ if not isinstance(utils, Mapping):
159
+ return "utils가 매핑이 아님"
160
+ unknown = sorted({str(m) for m in _matches(config) if m not in utils})
161
+ if unknown:
162
+ return f"matches가 이 파일의 utils에 없는 규칙을 가리킴: {', '.join(unknown)}"
163
+ return None
164
+
165
+
166
+ def _matches(node: object) -> Iterator[object]:
167
+ """규칙 트리 안의 모든 `matches:` 값."""
168
+ if isinstance(node, Mapping):
169
+ for key, value in node.items():
170
+ if key == "matches":
171
+ yield value
172
+ yield from _matches(value)
173
+ elif isinstance(node, list):
174
+ for item in node:
175
+ yield from _matches(item)
176
+
177
+
178
+ def _validate_python_ast(body: str) -> str | None:
179
+ try:
180
+ tree = ast.parse(body)
181
+ except SyntaxError as e:
182
+ return f"Python 문법 오류: {e.msg} (줄 {e.lineno})"
183
+ outside = sorted(
184
+ {name for name in _imported(tree) if name.split(".")[0] not in sys.stdlib_module_names}
185
+ )
186
+ if outside:
187
+ return f"표준 라이브러리 밖의 모듈을 import함: {', '.join(outside)}"
188
+ return None
189
+
190
+
191
+ def _imported(tree: ast.AST) -> Iterator[str]:
192
+ for node in ast.walk(tree):
193
+ if isinstance(node, ast.Import):
194
+ yield from (a.name for a in node.names)
195
+ elif isinstance(node, ast.ImportFrom):
196
+ yield "." if node.level else node.module or ""
@@ -0,0 +1,97 @@
1
+ """워커 쪽 수동 명령. 웹 쪽 동기화(`sync`)는 `app/api/cli.py`에 있다.
2
+
3
+ - `python -m app.worker.cli reindex [--repo owner/name]`: SQLite의 기록(`records`)으로 벡터 저장소
4
+ (`data_dir/chroma/`)를 다시 만든다 (DESIGN.md 6.5). 벡터 저장소가 지워졌거나 임베딩 모델을 바꿨을
5
+ 때 쓴다. 선택 의존성 `[rag]`가 필요하고, 처음이면 임베딩 모델을 받는다.
6
+ - `python -m app.worker.cli eval [--baseline] [--real-model] [--label 이름] [--db 경로]
7
+ [--out 폴더]`: 평가 세트 전부(`tests/e2e`의 docker 테스트, 도구를 끈 평가 포함)를 돌려
8
+ `eval_runs`에 남긴다 (DESIGN.md 13절 6단계). `--baseline`이면 기준선으로 남기고, 아니면 같은
9
+ 종류(가짜 모델 / 실제 모델)의 가장 최근 기준선과 비교해 보인다. 프롬프트나 모델을 바꾼 뒤 이 명령
10
+ 하나로 비교한다.
11
+ `--real-model`은 claude를 부른다. `--out`을 주면 그 폴더에 junit, 도구를 끈 평가의 JSON, 실제
12
+ 모델의 호출 기록(`memo.jsonl`)을 남긴다. 그 폴더에 이미 `memo.jsonl`이 있으면 그 답을 다시 쓴다.
13
+ """
14
+
15
+ import argparse
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Final
20
+
21
+ from redis import Redis
22
+
23
+ from app.shared import config
24
+
25
+ REPO_ROOT: Final = Path(__file__).resolve().parents[2]
26
+
27
+
28
+ def main(argv: list[str] | None = None) -> int:
29
+ parser = argparse.ArgumentParser(prog="python -m app.worker.cli")
30
+ parser.add_argument("command", choices=["reindex", "eval"])
31
+ parser.add_argument("--repo", action="append", help="reindex할 저장소 (여러 번 줄 수 있음)")
32
+ parser.add_argument("--baseline", action="store_true", help="eval: 기준선으로 남긴다")
33
+ parser.add_argument("--real-model", action="store_true", help="eval: 실제 claude를 부른다")
34
+ parser.add_argument("--label", default="", help="eval: 이 실행의 이름")
35
+ parser.add_argument("--db", type=Path, help="eval: 저장할 SQLite (기본은 설정의 data_dir)")
36
+ parser.add_argument("--out", type=Path, help="eval: junit·도구를 끈 평가·호출 기록을 남길 폴더")
37
+ args = parser.parse_args(argv)
38
+ if args.command == "eval":
39
+ db = args.db or config.load_config().db_path
40
+ return evaluate(db, baseline=args.baseline, real_model=args.real_model, label=args.label,
41
+ out=args.out) # fmt: skip
42
+ return reindex(config.load_config(), args.repo)
43
+
44
+
45
+ def evaluate(db: Path, *, baseline: bool, real_model: bool, label: str, out: Path | None = None,
46
+ runner=subprocess.run) -> int: # noqa: ANN001 # fmt: skip
47
+ """runner(`subprocess.run`과 같은 꼴)는 테스트가 바꾼다."""
48
+ from app.worker import eval_run_pure, evaluation, state
49
+
50
+ engine = state.open_engine(db)
51
+ try:
52
+ stored = evaluation.evaluate(engine, REPO_ROOT, baseline=baseline, real_model=real_model,
53
+ label=label, runner=runner, out=out) # fmt: skip
54
+ except evaluation.EvalError as e:
55
+ print(f"평가를 남기지 못함: {e}", file=sys.stderr)
56
+ return 1
57
+ kind = "기준선" if baseline else "실행"
58
+ print(f"eval_runs #{stored.run_id} ({kind}, {'실제 모델' if real_model else '가짜 모델'})")
59
+ print(eval_run_pure.render_summary(stored.summary))
60
+ if not baseline:
61
+ if stored.baseline is None:
62
+ print("비교할 기준선이 없음 (--baseline으로 먼저 남긴다)")
63
+ else:
64
+ comparison = eval_run_pure.compare(evaluation.from_row(stored.baseline), stored.summary)
65
+ print(eval_run_pure.render_comparison(comparison, stored.baseline.id))
66
+ return 0
67
+
68
+
69
+ def reindex(settings: config.PipelineConfig, repos: list[str] | None, encoder=None) -> int: # noqa: ANN001
70
+ """encoder(`memory.Encoder`)를 주지 않으면 설정의 임베딩 모델을 받아 쓴다. 테스트는 가짜를
71
+ 넘긴다."""
72
+ from app.shared.embed_models_pure import EMBED_MODELS
73
+ from app.worker import memory
74
+ from app.worker.state import Store
75
+
76
+ store = Store(settings.db_path, Redis.from_url(settings.redis_url))
77
+ try:
78
+ if encoder is None:
79
+ spec = EMBED_MODELS[settings.rag.embed_model]
80
+ folder = memory.ensure_model(Path(settings.data_dir) / memory.MODEL_DIR, spec)
81
+ encoder = memory.OnnxEncoder(spec, folder)
82
+ spec = encoder.spec
83
+ vectors = memory.VectorStore(Path(settings.data_dir) / memory.CHROMA_DIR, spec.name,
84
+ spec.dim) # fmt: skip
85
+ counts = memory.reindex(store, vectors, encoder, repos)
86
+ except (memory.SearchUnavailable, ImportError) as e:
87
+ print(f"reindex하지 못함: {e}", file=sys.stderr)
88
+ return 1
89
+ for repo, n in counts.items():
90
+ print(f"{repo}: 기록 {n}건")
91
+ if not counts:
92
+ print("기록 없음")
93
+ return 0
94
+
95
+
96
+ if __name__ == "__main__":
97
+ sys.exit(main())
@@ -0,0 +1,191 @@
1
+ """`command` 작업: PR 코멘트 명령 처리 (docs/DESIGN.md 4.9 명령).
2
+
3
+ - `/recheck`: PR의 지금 head로 다시 검사한다. 신뢰되지 않은 작성자의 PR에서는 커밋을 적은
4
+ `/recheck <커밋>`만 승인이고, 그 커밋이 지금 head일 때만 그 커밋을 검사한다 (8.6)
5
+ - `/fix <묶음>`: 승인을 기다리는 수정을 승인하고, 이 커밋에서 수정안을 내지 못하고 끝난 수정(검증
6
+ 실패, 호출 상한)을 다시 돌린다. 묶음은 `mechanical`·`model`이고, 인자가 없으면 할 일이 남은 묶음
7
+ 전부다. v1의 `/fix lint`는 3단계에 지원하지 않는 명령이 되었다 (그 경로가 `mechanical`이 되었다)
8
+ - 모르는 명령은 답하지 않는다 (`/cc` 같은 다른 관례일 수 있다)
9
+
10
+ 처리한 코멘트 ID는 runs와 따로 저장해 같은 코멘트에 두 번 답하지 않는다.
11
+ """
12
+
13
+ import logging
14
+
15
+ from app.shared.job_pure import PRJob
16
+ from app.worker import graph, guard, retry, update
17
+ from app.worker.access_pure import (
18
+ BadCommit,
19
+ Commit,
20
+ NeedsApproval,
21
+ NoCommit,
22
+ approval_arg,
23
+ may_approve,
24
+ )
25
+ from app.worker.command_pure import FIX_TARGETS, parse_command
26
+ from app.worker.deps import Deps
27
+ from app.worker.fix import proposal
28
+ from app.worker.github import PullRefs
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+
33
+ def fix_unsupported_message(word: str, arg: str) -> str:
34
+ target = f"{word} {arg}".strip()
35
+ return (
36
+ f"> {target}\n\n`{target}`는 지원하지 않습니다. "
37
+ "`/fix`, `/fix mechanical`(도구의 자동 수정), `/fix model`(모델 수정)을 쓸 수 있습니다."
38
+ )
39
+
40
+
41
+ def no_pending_fix_message(
42
+ head_sha: str, history: str = "", number: int | None = None, skill: str = "",
43
+ typed: str = "",
44
+ ) -> str: # fmt: skip
45
+ """재개할 수정이 없을 때의 답글. 이 커밋의 수정안 PR 기록이 있으면 그 번호를 알려준다.
46
+
47
+ typed는 코멘트에 쓴 인자다. 비면 skill로 쓴다.
48
+ """
49
+ commit = f"이 커밋(`{head_sha[:7]}`)"
50
+ if history == "rejected" and number is not None:
51
+ reason = (
52
+ f"{commit}의 {skill} 제안 PR #{number}이 머지되지 않고 닫혀 다시 제안하지 않습니다. "
53
+ "새 커밋을 올리면 다시 검사합니다."
54
+ )
55
+ elif history == "open" and number is not None:
56
+ reason = f"{commit}의 {skill} 제안 PR #{number}이 이미 열려 있습니다."
57
+ elif history == "merged" and number is not None:
58
+ reason = (
59
+ f"{commit}은 {skill} 제안 PR #{number}을 머지한 결과라 "
60
+ "같은 제안을 다시 만들지 않습니다."
61
+ )
62
+ else:
63
+ what = f"{skill} 수정" if skill else "수정"
64
+ reason = (
65
+ f"{commit}에는 승인을 기다리거나 다시 돌릴 {what}이 없습니다. "
66
+ "자동으로 고칠 수 있는 위반이 없거나, 테스트가 통과하지 않았거나, "
67
+ "이미 수정안을 만들었을 수 있습니다."
68
+ )
69
+ return f"> {f'/fix {typed or skill}'.strip()}\n\n{reason}"
70
+
71
+
72
+ def process_command(job: PRJob, deps: Deps) -> str:
73
+ assert job.command is not None and job.comment_id is not None
74
+ if deps.store.command_handled(job.comment_id):
75
+ return "duplicate"
76
+ parsed = parse_command(job.command)
77
+ if parsed.name == "unknown":
78
+ # 답하지 않지만 처리한 것으로 적는다. 적지 않으면 동기화가 주기마다 다시 넣는다
79
+ deps.store.record_command(job, "unknown_command")
80
+ return "unknown_command"
81
+ _, final = retry.attempt()
82
+ try:
83
+ refs = deps.github.pr_refs(job.repo, job.pr_number)
84
+ gate = guard.check(job, deps, refs) if refs.open else None
85
+ if gate is None:
86
+ result = "closed"
87
+ elif isinstance(gate.decision, NeedsApproval):
88
+ # `/fix`는 누가 달아도 승인이 아니다. 승인은 커밋을 적은 `/recheck <커밋>`뿐이다
89
+ if parsed.name == "recheck":
90
+ result = _approve(job, deps, gate)
91
+ else:
92
+ result = guard.block(job, deps, refs)
93
+ elif parsed.name == "recheck":
94
+ # `/recheck`는 수정안의 머지 커밋이어도 옮겨 적지 않고 처음부터 검사한다
95
+ result = f"recheck:{update.run_admitted(_target(job, refs), deps, refs, carry=False)}"
96
+ else:
97
+ result = _fix(job, deps, parsed.word, parsed.arg, refs)
98
+ except Exception: # 환경 오류든 버그든 재시도는 RQ가 한다
99
+ if final:
100
+ # 마지막 시도면 실패로 적고 키를 지운다. 적지 않으면 동기화가 주기마다 다시 넣는다.
101
+ # 다시 하려면 명령을 새로 단다 (update의 error와 같은 규칙)
102
+ deps.store.record_command(job, "error")
103
+ deps.store.release(job)
104
+ raise
105
+ deps.store.record_command(job, result)
106
+ return result
107
+
108
+
109
+ def _approve(job: PRJob, deps: Deps, gate: guard.Gate) -> str:
110
+ """신뢰되지 않은 작성자의 PR에 달린 `/recheck`. 승인이면 기록하고 그 커밋 하나를 검사한다.
111
+
112
+ 승인자와 명령의 글은 작업에 실린 값이 아니라 지금 GitHub에서 읽은 코멘트로 확인한다. 승인할
113
+ 수 없는 사람이면 다른 신뢰되지 않은 명령처럼 답하지 않는다. 커밋이 없거나, 전체 해시(40자)가
114
+ 아니거나, 지금 head가 아니면 실행하지 않고 답한다. 답에는 코멘트에 쓴 글을 옮기지 않는다.
115
+ """
116
+ assert job.comment_id is not None
117
+ refs = gate.refs
118
+ comment = deps.github.issue_comment(job.repo, job.comment_id)
119
+ if comment.pr_number != job.pr_number or not may_approve(
120
+ comment.association, comment.login, gate.access
121
+ ):
122
+ log.warning(
123
+ "승인할 수 없는 사람의 /recheck라 무시함: %s#%d 코멘트 %d %r (%r)",
124
+ job.repo, job.pr_number, job.comment_id, comment.login, comment.association,
125
+ ) # fmt: skip
126
+ return "approver_not_trusted"
127
+ lines = comment.body.strip().splitlines()
128
+ parsed = parse_command(lines[0] if lines else "")
129
+ if parsed.name != "recheck":
130
+ return "approval_comment_changed" # 큐에서 기다리는 사이에 코멘트가 고쳐졌다
131
+ match approval_arg(parsed.arg):
132
+ case NoCommit():
133
+ deps.github.reply(job.repo, job.pr_number, guard.missing_commit_reply(refs.head_sha))
134
+ return "approval_missing_commit"
135
+ case BadCommit():
136
+ deps.github.reply(job.repo, job.pr_number, guard.bad_commit_reply(refs.head_sha))
137
+ return "approval_bad_commit"
138
+ case Commit() as commit if not commit.matches(refs.head_sha):
139
+ deps.github.reply(job.repo, job.pr_number, guard.head_moved_reply(refs.head_sha))
140
+ return "approval_head_moved"
141
+ deps.store.add_approval(job.repo, job.pr_number, refs.head_sha, comment.login, job.comment_id)
142
+ return f"approved:{update.run_admitted(_target(job, refs), deps, refs, carry=False)}"
143
+
144
+
145
+ def _target(job: PRJob, refs: PullRefs) -> PRJob:
146
+ """명령이 가리키는 PR의 지금 커밋에 대한 update 작업. 작업에 실린 작성자 값(기록용)은 옮긴다."""
147
+ return PRJob(
148
+ repo=job.repo,
149
+ pr_number=job.pr_number,
150
+ kind="update",
151
+ head_sha=refs.head_sha,
152
+ base_sha=refs.base_sha,
153
+ source=job.source,
154
+ author_association=job.author_association,
155
+ author_login=job.author_login,
156
+ )
157
+
158
+
159
+ def _fix(job: PRJob, deps: Deps, word: str, arg: str, refs: PullRefs) -> str:
160
+ """arg의 묶음마다 재개할 수정이 있으면 차례로 이어 간다. 하나도 없으면 그 이유를 답한다.
161
+
162
+ 모델 묶음을 다시 돌릴 때는 PR 호출 상한을 한 번 더 준다 (9.2). 같은 코멘트를 다시 처리해도
163
+ (재시도) 한 번이고, 이미 처리한 묶음은 재개할 것이 없어 건너뛴다.
164
+ """
165
+ target = _target(job, refs)
166
+ skills = FIX_TARGETS.get(arg)
167
+ if skills is None:
168
+ deps.github.reply(job.repo, job.pr_number, fix_unsupported_message(word, arg))
169
+ return "fix_unsupported"
170
+ results = []
171
+ for skill in skills:
172
+ pending = update.pending_fix(target, deps, skill)
173
+ if pending is None:
174
+ continue
175
+ if skill == graph.MODEL and pending == "rerun":
176
+ deps.store.add_call_grant(job.repo, job.pr_number, target.head_sha, job.comment_id)
177
+ approval = {"skill": skill, "comment_id": job.comment_id}
178
+ results.append(update.resume_fix(target, deps, approval, guard.author(refs)))
179
+ if results:
180
+ return ";".join(results)
181
+ # 제안 PR을 닫거나 머지한 뒤 바로 /fix를 달 수 있으니 기록을 GitHub과 맞춘 뒤 본다
182
+ proposal.refresh(deps.store, deps.github, job.repo, job.pr_number)
183
+ history, number = "", None
184
+ if len(skills) == 1:
185
+ history, number = proposal.blocked_by_history(
186
+ deps.store, job.repo, job.pr_number, skills[0], target.head_sha
187
+ )
188
+ skill = skills[0] if len(skills) == 1 else ""
189
+ body = no_pending_fix_message(target.head_sha, history, number, skill, typed=arg)
190
+ deps.github.reply(job.repo, job.pr_number, body)
191
+ return "no_pending_fix"
@@ -0,0 +1,38 @@
1
+ """PR 코멘트 명령 해석 (docs/DESIGN.md 4.9 명령). 판단만 하고 실행하지 않는다."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass
5
+ from typing import Final, Literal
6
+
7
+ CommandName = Literal["recheck", "fix", "unknown"]
8
+
9
+ RECHECK: Final = "/recheck"
10
+ FIX: Final = "/fix"
11
+ # `/fix <인자>` → 다시 돌릴 수정 묶음. 비면 수정할 것이 남은 묶음 전부다 (4.9).
12
+ # v1의 스킬 이름(`lint`, `static`)은 지원하지 않는 명령이다 (12.4)
13
+ FIX_TARGETS: Final[Mapping[str, tuple[str, ...]]] = {
14
+ "": ("mechanical", "model"),
15
+ "mechanical": ("mechanical",),
16
+ "model": ("model",),
17
+ }
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class ParsedCommand:
22
+ name: CommandName
23
+ word: str # 코멘트에 쓴 명령어. 예: "/fix"
24
+ arg: str = "" # "/fix model"의 "model", "/recheck <커밋>"의 커밋
25
+
26
+
27
+ def parse_command(text: str) -> ParsedCommand:
28
+ """코멘트 첫 줄을 해석한다. 모르는 명령은 unknown.
29
+
30
+ 모르는 명령에는 답하지 않는다. `/cc` 같은 다른 관례일 수 있다.
31
+ """
32
+ word, _, rest = text.strip().partition(" ")
33
+ word = word.lower()
34
+ if word == RECHECK:
35
+ return ParsedCommand("recheck", word, rest.strip())
36
+ if word == FIX:
37
+ return ParsedCommand("fix", word, rest.strip().lower())
38
+ return ParsedCommand("unknown", word)
@@ -0,0 +1,123 @@
1
+ """참고 지표 diff-cover (docs/DESIGN.md F8).
2
+
3
+ `.pipeline-out/` 아래 파일(coverage.xml, changes.diff)은 샌드박스 안의 PR 코드가 바꿀 수 있다.
4
+ 호스트에서 읽을 때 심볼릭 링크·FIFO·장치 파일을 따라가지 않고 큰 파일은 읽지 않는다. 위반 줄의
5
+ 커버리지 읽기는 Python 프로필(`app/worker/lang/python.py`)에 있다.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Final
16
+
17
+ from app.worker.coverage_pure import MAX_COVERAGE_XML_BYTES, parse_coverage_xml
18
+ from app.worker.sandbox.safe_read import read_regular_file
19
+
20
+ DIFF_COVER_TIMEOUT: Final = 60
21
+ MAX_DIFF_BYTES: Final = 20 * 1024 * 1024
22
+ _ENV_PASSTHROUGH: Final = ("PATH",)
23
+ # diff-cover를 격리 모드(-I)로 실행한다. 작업 폴더·PYTHONPATH·사용자 site의 모듈을 import하지 않는다
24
+ _DIFF_COVER_MAIN: Final = (
25
+ "import sys; from diff_cover.diff_cover_tool import main; sys.exit(main())"
26
+ )
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class DiffCoverage:
31
+ """PR이 바꾼 줄의 커버리지 (참고 지표). 테스트가 import한 파일의 실행 단위 줄만 센다."""
32
+
33
+ percent: float # 소수 둘째 자리까지
34
+ measured_lines: int # 바뀐 줄 중 coverage가 센 줄 (빈 줄·주석·문서 파일·안 import된 파일 제외)
35
+ uncovered_lines: int # 그중 실행되지 않은 줄
36
+
37
+
38
+ def _minimal_env(home: Path) -> dict[str, str]:
39
+ """diff-cover가 부르는 git(`rev-parse --show-toplevel`)이 사용자 설정을 읽지 않게 한다."""
40
+ env = {k: os.environ[k] for k in _ENV_PASSTHROUGH if k in os.environ}
41
+ env |= {
42
+ "HOME": str(home),
43
+ "GIT_CONFIG_NOSYSTEM": "1",
44
+ "GIT_CONFIG_GLOBAL": os.devnull,
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C.UTF-8",
47
+ }
48
+ return env
49
+
50
+
51
+ def diff_coverage(
52
+ coverage_xml: Path | None,
53
+ changes_diff: Path | bytes,
54
+ *,
55
+ timeout: float = DIFF_COVER_TIMEOUT,
56
+ python: str = sys.executable,
57
+ ) -> DiffCoverage | None:
58
+ """호스트에서 diff-cover로 변경 줄 커버리지를 잰다. 잴 수 없으면 None.
59
+
60
+ diff-cover는 XML과 diff만 읽고 PR 코드를 실행하지 않는다. 그래도 입력은 믿지 않는다.
61
+ - coverage.xml은 먼저 안전한 파서로 검사해 통과한 바이트만 넘긴다 (diff-cover는 표준
62
+ ElementTree로 읽으므로 DTD·엔티티가 있으면 넘기지 않는다).
63
+ - 입력은 임시 폴더에 복사해 그 안에서 실행한다. diff-cover가 부르는 `git rev-parse`는 그
64
+ 임시 폴더의 빈 저장소를 보고, PR worktree나 사용자 git 설정을 읽지 않는다.
65
+ - 최소 환경, 격리 모드(-I), 시간 제한.
66
+ 바뀐 줄 중 coverage가 센 줄이 하나도 없으면 비율이 의미가 없어 None이다.
67
+ """
68
+ if coverage_xml is None:
69
+ return None
70
+ xml = read_regular_file(coverage_xml, max_bytes=MAX_COVERAGE_XML_BYTES)
71
+ # 테스트 뒤에는 샌드박스가 changes.diff를 바꿀 수 있어 테스트 전에 읽은 바이트를 받는다
72
+ if isinstance(changes_diff, bytes):
73
+ diff = changes_diff if len(changes_diff) <= MAX_DIFF_BYTES else None
74
+ else:
75
+ diff = read_regular_file(changes_diff, max_bytes=MAX_DIFF_BYTES)
76
+ if xml is None or diff is None or parse_coverage_xml(xml) is None:
77
+ return None
78
+ with tempfile.TemporaryDirectory(prefix="pr-proof-diffcover-") as tmp:
79
+ work = Path(tmp).resolve()
80
+ (work / "coverage.xml").write_bytes(xml)
81
+ (work / "changes.diff").write_bytes(diff)
82
+ env = _minimal_env(work)
83
+ report = work / "report.json"
84
+ try:
85
+ subprocess.run(
86
+ ["git", "init", "--quiet", str(work)],
87
+ cwd=work,
88
+ env=env,
89
+ capture_output=True,
90
+ timeout=timeout,
91
+ check=True,
92
+ )
93
+ proc = subprocess.run(
94
+ [
95
+ python, "-I", "-c", _DIFF_COVER_MAIN,
96
+ "coverage.xml", "--diff-file", "changes.diff",
97
+ "--format", f"json:{report.name}", "--quiet", "--total-percent-float",
98
+ ],
99
+ cwd=work,
100
+ env=env,
101
+ capture_output=True,
102
+ text=True,
103
+ timeout=timeout,
104
+ check=False,
105
+ ) # fmt: skip
106
+ except (OSError, subprocess.SubprocessError):
107
+ return None
108
+ if proc.returncode != 0:
109
+ return None
110
+ return _parse_report(report)
111
+
112
+
113
+ def _parse_report(report: Path) -> DiffCoverage | None:
114
+ try:
115
+ data = json.loads(report.read_text())
116
+ measured = int(data["total_num_lines"])
117
+ violations = int(data["total_num_violations"])
118
+ percent = float(data["total_percent_covered"])
119
+ except (OSError, ValueError, KeyError, TypeError):
120
+ return None
121
+ if measured <= 0 or not 0 <= violations <= measured:
122
+ return None
123
+ return DiffCoverage(percent=percent, measured_lines=measured, uncovered_lines=violations)