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,200 @@
1
+ """공용 서브그래프 틀: 작성 → 프로그램의 확인 → 이유를 넘겨 재시도 (docs/DESIGN.md 5.3).
2
+
3
+ 검사기 작성과 모델 수정이 같이 쓴다. 쓰는 곳마다 다른 것은 `write`(프롬프트 + 모델 호출)와
4
+ `verify`(검사기 작성은 예시 확인, 모델 수정은 출구 검사)뿐이고, 회차·모델 단계·호출 상한은
5
+ `route`가 `LoopPolicy`로 정한다. 모델 수정은 되풀이 대부분이 `write`의 호출 하나 안에서 모델과
6
+ 파이프라인 도구 사이에 일어나고(4.7), 회차는 출구 검사에 떨어졌을 때의 뒷받침이다.
7
+
8
+ route ─(가벼운/무거운 모델)→ write ─(결과 있음)→ verify ─(통과)→ accepted
9
+ │ │ ├─(재시도: feedback)→ route
10
+ │ └─(작성 실패)→ route └─(버림)→ dropped
11
+ └─(회차 소진)→ exhausted · (호출 상한)→ budget
12
+
13
+ 상태에는 데이터만 넣는다(5.5). `write`의 결과물(검사기 본문, 패치)은 쓰는 쪽이 캐시 테이블에
14
+ 두고 그 키만 `artifact`에 넣는다. `write`와 `verify`가 따로 노드라서, 체크포인터가 있는 그래프
15
+ 안에서는 `verify`부터 이어 갈 수 있다.
16
+ """
17
+
18
+ import logging
19
+ import operator
20
+ from collections.abc import Callable
21
+ from dataclasses import dataclass
22
+ from typing import Annotated, Any, Final, Literal, TypedDict
23
+
24
+ from langgraph.graph import END, START, StateGraph
25
+ from langgraph.graph.state import CompiledStateGraph
26
+
27
+ from app.worker.call_budget_pure import Tier
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+ Outcome = Literal["accepted", "exhausted", "budget", "dropped"]
32
+ AttemptResult = Literal["accepted", "rejected", "dropped", "write_failed"]
33
+
34
+ HEAVY_AFTER_FAILURES: Final = 2 # 가벼운 모델이 이만큼 실패하면 무거운 모델로 한 번 (9.3)
35
+ ROUTE: Final = "route"
36
+ WRITE: Final = "write"
37
+ VERIFY: Final = "verify"
38
+
39
+
40
+ class Attempt(TypedDict):
41
+ """한 회차의 기록. 체크포인트에 그대로 들어가도록 dict다."""
42
+
43
+ attempt: int # 1부터
44
+ tier: Tier
45
+ result: AttemptResult
46
+ artifact: str # write가 낸 결과물의 키. 작성에 실패했으면 ""
47
+ detail: str # 실패 이유 한 줄. 통과했으면 ""
48
+ feedback: list[str] # 다음 회차의 write에 넘긴 것
49
+
50
+
51
+ class LoopState(TypedDict, total=False):
52
+ task: dict[str, Any] # 쓰는 쪽의 입력(규칙과 예시, 대상 위반). 틀은 읽지 않는다
53
+ attempt: int # 지금까지 시작한 회차 수
54
+ tier: Tier # 이번 회차의 모델 단계
55
+ feedback: list[str] # 직전 회차의 실패 내용. 첫 회차는 비어 있다
56
+ artifact: str # 이번 회차 write 결과물의 키
57
+ history: Annotated[list[Attempt], operator.add]
58
+ outcome: Outcome # 끝났을 때만 있다
59
+ detail: str # 마지막 실패 이유 또는 버린 이유
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class WriteResult:
64
+ """write의 결과. 본문은 쓰는 쪽이 캐시에 저장하고 여기에는 그 키만 넣는다."""
65
+
66
+ artifact: str = ""
67
+ error: str = "" # 모델 호출이 실패했거나 답을 읽을 수 없으면 그 이유
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class Verdict:
72
+ """verify의 결과. retry는 feedback을 다음 회차에 넘기고, drop은 재시도 없이 버린다."""
73
+
74
+ status: Literal["pass", "retry", "drop"]
75
+ detail: str = ""
76
+ feedback: tuple[str, ...] = ()
77
+
78
+
79
+ class WriteFailed(Exception):
80
+ """write가 올리면 그 회차를 실패로 센다. 다른 예외(환경 오류, 버그)는 그대로 올라간다."""
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class LoopPolicy:
85
+ max_attempts: int
86
+ # 이 단계의 모델 호출을 한 번 더 해도 되는지. 호출 상한(9.2)을 가진 쪽이 준다
87
+ may_call: Callable[[Tier], bool]
88
+ heavy_after: int | None = HEAVY_AFTER_FAILURES # None이면 무거운 모델로 올리지 않는다
89
+
90
+ def __post_init__(self) -> None:
91
+ if self.max_attempts < 1:
92
+ raise ValueError(f"max_attempts는 1 이상이어야 한다: {self.max_attempts}")
93
+ if self.heavy_after is not None and self.heavy_after < 1:
94
+ raise ValueError(f"heavy_after는 1 이상이어야 한다: {self.heavy_after}")
95
+
96
+
97
+ def choose_tier(history: list[Attempt], policy: LoopPolicy) -> Tier | None:
98
+ """다음 회차의 모델 단계. 호출 상한에 걸리면 None.
99
+
100
+ 가벼운 모델로 시작하고, 가벼운 모델이 `heavy_after`회 실패하면 무거운 모델로 한 번 올린다.
101
+ 무거운 모델을 부를 여유가 없으면 올리지 않고 가벼운 모델로 계속한다.
102
+ """
103
+ light_failures = sum(1 for a in history if a["tier"] == "light")
104
+ heavy_used = any(a["tier"] == "heavy" for a in history)
105
+ wants_heavy = (
106
+ policy.heavy_after is not None and light_failures >= policy.heavy_after and not heavy_used
107
+ )
108
+ if wants_heavy and policy.may_call("heavy"):
109
+ return "heavy"
110
+ return "light" if policy.may_call("light") else None
111
+
112
+
113
+ def build_loop(
114
+ name: str,
115
+ write: Callable[[LoopState], WriteResult],
116
+ verify: Callable[[LoopState], Verdict],
117
+ policy: LoopPolicy,
118
+ ) -> CompiledStateGraph:
119
+ """`{"task": ...}`로 시작해 `outcome`이 정해질 때까지 도는 서브그래프."""
120
+
121
+ def record(
122
+ state: LoopState, result: AttemptResult, detail: str, feedback: list[str]
123
+ ) -> Attempt:
124
+ return Attempt(
125
+ attempt=state["attempt"], tier=state["tier"], result=result,
126
+ artifact=state.get("artifact", ""), detail=detail, feedback=feedback,
127
+ ) # fmt: skip
128
+
129
+ def route_node(state: LoopState) -> LoopState:
130
+ attempt = state.get("attempt", 0)
131
+ if attempt >= policy.max_attempts:
132
+ return {"outcome": "exhausted"}
133
+ tier = choose_tier(state.get("history", []), policy)
134
+ if tier is None:
135
+ log.info("%s: 호출 상한으로 %d회차를 시작하지 않음", name, attempt + 1)
136
+ return {"outcome": "budget"}
137
+ return {"attempt": attempt + 1, "tier": tier, "artifact": ""}
138
+
139
+ def write_node(state: LoopState) -> LoopState:
140
+ try:
141
+ result = write(state)
142
+ except WriteFailed as e:
143
+ error = str(e) or "작성에 실패함"
144
+ else:
145
+ if not isinstance(result, WriteResult):
146
+ error = f"write가 WriteResult가 아닌 값을 냄: {type(result).__name__}"
147
+ elif result.error:
148
+ error = result.error
149
+ elif not result.artifact:
150
+ error = "write가 결과물 없이 끝남"
151
+ else:
152
+ return {"artifact": result.artifact}
153
+ log.info("%s: %d회차 작성 실패: %s", name, state["attempt"], error)
154
+ return {
155
+ "feedback": [error],
156
+ "detail": error,
157
+ "history": [record(state, "write_failed", error, [error])],
158
+ }
159
+
160
+ def verify_node(state: LoopState) -> LoopState:
161
+ verdict = verify(state)
162
+ if not isinstance(verdict, Verdict):
163
+ raise TypeError(f"{name}: verify가 Verdict가 아닌 값을 냄: {type(verdict).__name__}")
164
+ if verdict.status == "pass":
165
+ return {
166
+ "outcome": "accepted",
167
+ "detail": "",
168
+ "history": [record(state, "accepted", "", [])],
169
+ }
170
+ if verdict.status == "drop":
171
+ return {
172
+ "outcome": "dropped",
173
+ "detail": verdict.detail,
174
+ "history": [record(state, "dropped", verdict.detail, [])],
175
+ }
176
+ feedback = list(verdict.feedback) or [verdict.detail]
177
+ return {
178
+ "feedback": feedback,
179
+ "detail": verdict.detail,
180
+ "history": [record(state, "rejected", verdict.detail, feedback)],
181
+ }
182
+
183
+ def after_route(state: LoopState) -> str:
184
+ return END if "outcome" in state else WRITE
185
+
186
+ def after_write(state: LoopState) -> str:
187
+ return VERIFY if state.get("artifact") else ROUTE
188
+
189
+ def after_verify(state: LoopState) -> str:
190
+ return END if "outcome" in state else ROUTE
191
+
192
+ graph = StateGraph(LoopState)
193
+ graph.add_node(ROUTE, route_node)
194
+ graph.add_node(WRITE, write_node)
195
+ graph.add_node(VERIFY, verify_node)
196
+ graph.add_edge(START, ROUTE)
197
+ graph.add_conditional_edges(ROUTE, after_route, [WRITE, END])
198
+ graph.add_conditional_edges(WRITE, after_write, [VERIFY, ROUTE])
199
+ graph.add_conditional_edges(VERIFY, after_verify, [ROUTE, END])
200
+ return graph.compile(name=name)
@@ -0,0 +1,76 @@
1
+ """진입점: RQ 워커. `python -m app.worker.main`.
2
+
3
+ 큐의 작업 하나를 handle()이 종류별로 나눠 처리한다 (update.py, command.py, feedback.py). 환경 오류는
4
+ PR에 실패로 남기지 않고 예외를 올려 RQ가 정해진 간격으로 다시 시도하게 한다 (retry.py, 상한 있음).
5
+ """
6
+
7
+ import logging
8
+ import sys
9
+ from collections.abc import Callable
10
+
11
+ from redis import Redis
12
+ from rq import Queue, SimpleWorker
13
+ from sqlalchemy.exc import SQLAlchemyError
14
+
15
+ from app.shared import config, state_keys_pure
16
+ from app.shared.job_pure import PRJob
17
+ from app.worker import command, feedback, preflight, retry, update
18
+ from app.worker.deps import Deps
19
+ from app.worker.state import open_engine
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+
24
+ def handle(
25
+ payload: str,
26
+ deps: Deps | None = None,
27
+ checks: Callable[[Redis], list[preflight.Check]] = preflight.run_checks,
28
+ ) -> str:
29
+ job = PRJob.model_validate_json(payload)
30
+ deps = deps or Deps.from_config()
31
+ try:
32
+ if job.kind == "update":
33
+ result = update.process_update(job, deps)
34
+ elif job.kind == "command":
35
+ result = command.process_command(job, deps)
36
+ elif job.kind == "feedback":
37
+ result = feedback.process_feedback(job, deps)
38
+ elif job.kind == "resolve":
39
+ result = feedback.process_resolve(job, deps)
40
+ else:
41
+ result = update.process_close(job, deps)
42
+ except Exception as error:
43
+ # 재시도를 모두 쓴 환경 오류만 시작 전 확인으로 다시 가려 알린다. 앞 시도의 실패는 RQ가
44
+ # 다시 하고, 다시 해서 풀리는 오류는 알리지 않는다. 확인이 모두 통과하면 알리지 않는다
45
+ if isinstance(error, retry.EnvironmentFailure) and retry.attempt()[1]:
46
+ preflight.alert(checks(deps.store.redis), deps.settings.data_dir)
47
+ raise
48
+ deps.store.release(job)
49
+ return result
50
+
51
+
52
+ def main() -> int:
53
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
54
+ settings = config.load_config()
55
+ # 웹 쪽 동기화는 읽기만 한다. 배포가 더한 테이블과 열을 작업이 오기 전에 만들어 둔다
56
+ try:
57
+ open_engine(settings.db_path).dispose()
58
+ except (OSError, SQLAlchemyError, RuntimeError):
59
+ log.exception("DB 스키마를 맞추지 못해 워커를 시작하지 않는다: %s", settings.db_path)
60
+ return 1
61
+ redis = Redis.from_url(settings.redis_url)
62
+ checks = preflight.run_checks(redis)
63
+ problems = preflight.failures(checks)
64
+ if problems:
65
+ for problem in problems:
66
+ log.error(problem)
67
+ preflight.alert(checks, settings.data_dir)
68
+ return 1
69
+ # 동시 작업 1개. macOS에서 fork 문제를 피하려고 작업을 같은 프로세스에서 실행한다
70
+ worker = SimpleWorker([Queue(state_keys_pure.QUEUE_NAME, connection=redis)], connection=redis)
71
+ worker.work(with_scheduler=True)
72
+ return 0
73
+
74
+
75
+ if __name__ == "__main__":
76
+ sys.exit(main())
@@ -0,0 +1,29 @@
1
+ """PR 코멘트에 믿지 않는 글(모델의 글, 문서의 인용, 파일 경로, 코드)을 넣는 방법.
2
+
3
+ 믿지 않는 글은 코드 울타리나 코드 스팬 안에만 넣는다. 그 안에서는 마크다운, HTML, `@` 멘션이
4
+ 동작하지 않는다. 울타리는 글 안의 어떤 백틱 줄보다 길게 만들어 글이 울타리를 닫지 못하게 한다.
5
+ """
6
+
7
+ import re
8
+ from typing import Final
9
+
10
+ _BACKTICKS: Final = re.compile(r"`+")
11
+ _SPACE: Final = re.compile(r"\s+")
12
+
13
+
14
+ def code_fence(text: str) -> str:
15
+ """text 안의 어떤 백틱 줄보다 긴 코드 울타리. 본문의 ```가 블록을 일찍 닫지 않게 한다."""
16
+ longest = max((len(m) for m in _BACKTICKS.findall(text)), default=0)
17
+ return "`" * max(3, longest + 1)
18
+
19
+
20
+ def inline_code(text: str, limit: int = 300) -> str:
21
+ """한 줄 코드 스팬. 줄바꿈은 공백으로 모으고, limit자를 넘으면 자른다."""
22
+ text = _SPACE.sub(" ", text).strip()
23
+ if len(text) > limit:
24
+ text = text[:limit] + "…"
25
+ if not text:
26
+ return "` `"
27
+ fence = "`" * (max((len(m) for m in _BACKTICKS.findall(text)), default=0) + 1)
28
+ pad = " " if text.startswith("`") or text.endswith("`") else ""
29
+ return f"{fence}{pad}{text}{pad}{fence}"
@@ -0,0 +1,150 @@
1
+ """수정 작성의 모델이 부르는 파이프라인 도구의 MCP 메시지 (docs/DESIGN.md 4.7, 8.4).
2
+
3
+ claude CLI가 띄우는 stdio MCP 서버(`mcp_relay.py`)는 줄을 워커로 넘기기만 하고, 메시지의 뜻은 여기서
4
+ 정한다. 도구는 둘이고 인자는 없거나 좁다. 도구를 실제로 돌리는 함수는 부르는 쪽이 넘긴다
5
+ (`app/worker/ai/tool_server.py`). 외부 호출이 없다. 수정 작성(`app/worker/fix/`)과 claude 호출
6
+ (`app/worker/ai/`)이 같이 쓴다.
7
+ """
8
+
9
+ import json
10
+ from collections.abc import Callable, Mapping
11
+ from dataclasses import dataclass
12
+ from typing import Final
13
+
14
+ SERVER: Final = "proof"
15
+ CHECK_RULES: Final = "check_rules"
16
+ RUN_TESTS: Final = "run_tests"
17
+ # claude가 MCP 도구에 붙이는 이름. 도구 목록 확인(T25)과 경로 감시 훅이 이 이름을 안다
18
+ TOOL_NAMES: Final = (f"mcp__{SERVER}__{CHECK_RULES}", f"mcp__{SERVER}__{RUN_TESTS}")
19
+ STATE_TYPES: Final = (("app.worker.mcp_pure", "ToolUsage"),)
20
+ # 호출 하나(claude 한 번) 안의 상한 (9.2). 넘으면 도구를 돌리지 않고 "상한에 닿음"을 돌려준다
21
+ MAX_TOOL_CALLS: Final = 24
22
+ MAX_TOOL_SECONDS: Final = 900.0
23
+ MAX_RESULT_CHARS: Final = 8000
24
+ LIMIT_REACHED: Final = "상한에 닿음"
25
+ _PROTOCOL: Final = "2025-06-18"
26
+
27
+ TOOLS: Final = (
28
+ {
29
+ "name": CHECK_RULES,
30
+ "description": (
31
+ "작업 폴더의 지금 파일 상태로 대상 규칙의 검사(저장소의 도구와 저장된 검사기)를 돌려, "
32
+ "남은 대상 위반과 새로 생긴 위반을 돌려준다. 인자가 없다."
33
+ ),
34
+ "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
35
+ },
36
+ {
37
+ "name": RUN_TESTS,
38
+ "description": (
39
+ "샌드박스에서 pytest를 돌린다. code가 before면 PR의 원래 코드에 네가 만든 테스트 "
40
+ "파일만 얹어 돌리고, 만든 테스트마다 통과 여부, 실행한 대상 위반, 출구 검사가 "
41
+ "받아들일지를 돌려준다. now면 지금 파일 상태로 모든 테스트를 돌린다."
42
+ ),
43
+ "inputSchema": {
44
+ "type": "object",
45
+ "properties": {"code": {"type": "string", "enum": ["now", "before"]}},
46
+ "additionalProperties": False,
47
+ },
48
+ },
49
+ )
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class ToolLimits:
54
+ calls: int = MAX_TOOL_CALLS
55
+ seconds: float = MAX_TOOL_SECONDS
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class ToolUsage:
60
+ """수정 작성 호출들 안의 도구 호출 (9.4). limited는 상한에 닿아 돌리지 않은 호출이 있었다."""
61
+
62
+ check_rules: int = 0
63
+ run_tests: int = 0
64
+ seconds: float = 0.0
65
+ limited: bool = False
66
+
67
+ @property
68
+ def calls(self) -> int:
69
+ return self.check_rules + self.run_tests
70
+
71
+ def __add__(self, other: "ToolUsage") -> "ToolUsage":
72
+ return ToolUsage(
73
+ self.check_rules + other.check_rules, self.run_tests + other.run_tests,
74
+ self.seconds + other.seconds, self.limited or other.limited,
75
+ ) # fmt: skip
76
+
77
+
78
+ def limit_reason(calls: int, seconds: float, limits: ToolLimits) -> str | None:
79
+ """지금까지 돌린 도구 호출 수와 시간으로 다음 호출을 돌리지 않을 이유."""
80
+ if calls >= limits.calls:
81
+ return f"{LIMIT_REACHED}: 도구 호출 {limits.calls}회. 더 부르지 말고 마무리한다"
82
+ if seconds >= limits.seconds:
83
+ return f"{LIMIT_REACHED}: 도구 시간 {limits.seconds:g}초. 더 부르지 말고 마무리한다"
84
+ return None
85
+
86
+
87
+ def tool_arguments(name: str, raw: object) -> dict[str, str] | None:
88
+ """도구 인자를 좁힌다. 모르는 도구나 허용하지 않는 인자는 None."""
89
+ args = raw if isinstance(raw, dict) else {} if raw is None else None
90
+ if args is None:
91
+ return None
92
+ if name == CHECK_RULES:
93
+ return {} if not args else None
94
+ if name == RUN_TESTS:
95
+ code = args.get("code", "now")
96
+ return {"code": code} if set(args) <= {"code"} and code in ("now", "before") else None
97
+ return None
98
+
99
+
100
+ def _result(message_id: object, result: Mapping[str, object]) -> dict:
101
+ return {"jsonrpc": "2.0", "id": message_id, "result": dict(result)}
102
+
103
+
104
+ def _error(message_id: object, code: int, text: str) -> dict:
105
+ return {"jsonrpc": "2.0", "id": message_id, "error": {"code": code, "message": text}}
106
+
107
+
108
+ def _text(text: str, *, error: bool = False) -> dict:
109
+ if len(text) > MAX_RESULT_CHARS:
110
+ text = text[:MAX_RESULT_CHARS] + "\n… (잘림)"
111
+ return {"content": [{"type": "text", "text": text}], "isError": error}
112
+
113
+
114
+ # (도구 이름, 좁힌 인자) → (결과 글, 오류인지)
115
+ Call = Callable[[str, Mapping[str, str]], tuple[str, bool]]
116
+
117
+
118
+ def respond(line: str, call: Call) -> dict | None:
119
+ """요청 한 줄에 대한 응답. 알림(id 없음)과 읽지 못한 줄에는 답하지 않는다."""
120
+ try:
121
+ message = json.loads(line)
122
+ except ValueError:
123
+ return None
124
+ if not isinstance(message, dict) or "id" not in message or "method" not in message:
125
+ return None
126
+ mid, method, params = message["id"], message["method"], message.get("params") or {}
127
+ if method == "initialize":
128
+ version = params.get("protocolVersion") if isinstance(params, dict) else None
129
+ return _result(mid, {
130
+ "protocolVersion": version if isinstance(version, str) else _PROTOCOL,
131
+ "capabilities": {"tools": {}},
132
+ "serverInfo": {"name": SERVER, "version": "1"},
133
+ }) # fmt: skip
134
+ if method == "ping":
135
+ return _result(mid, {})
136
+ if method == "tools/list":
137
+ return _result(mid, {"tools": list(TOOLS)})
138
+ if method == "tools/call" and isinstance(params, dict):
139
+ name = params.get("name")
140
+ args = tool_arguments(name, params.get("arguments")) if isinstance(name, str) else None
141
+ if args is None:
142
+ return _result(mid, _text(f"알 수 없는 도구나 인자: {name!r}", error=True))
143
+ text, failed = call(name, args)
144
+ return _result(mid, _text(text, error=failed))
145
+ return _error(mid, -32601, f"지원하지 않는 메서드: {method}")
146
+
147
+
148
+ def mcp_config(command: str, args: list[str]) -> str:
149
+ """`--mcp-config`에 넘기는 JSON. 서버는 파이프라인이 띄우는 것 하나뿐이다."""
150
+ return json.dumps({"mcpServers": {SERVER: {"type": "stdio", "command": command, "args": args}}})