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,963 @@
1
+ """워커의 작업 흐름 (LangGraph, docs/DESIGN.md 5.1).
2
+
3
+ 체크아웃 → 규칙 읽기 → 검사 방법 정하기 → 위반 찾기 → 모델 판단 → PR 단위 확인 → PR 설명 확인
4
+ → 테스트 → 수정 판단 → 코멘트
5
+ ─┬─ (고칠 위반 없음) → 끝
6
+ ├─ (기본: 바로) 기계적 수정 → 수정안 PR ─┬→ 수정 코멘트 ─┬─ (남은 묶음 없음) → 끝
7
+ ├─ (기본: 바로) 모델 수정 → 수정안 PR ───┘ └─ 다른 묶음의 대기·수정
8
+ └─ 승인 대기(interrupt, `require_approval: true`) ─ /fix <묶음>
9
+
10
+ 규칙은 base의 문서와 도구 설정(ruff 설정)에서 나온다. 규칙이 하나도 없으면 규칙 검사를 하지 않고
11
+ PR 설명 확인과 테스트로 넘어간다. 테스트 뒤에 위반마다 수정 판단(fix/skip과 이유, 4.6)을 정해
12
+ 코멘트에 보인다.
13
+ `fix`로 정한 위반은 수정 방법별 묶음(`mechanical`: 도구의 수정, `model`: 모델이 검사기와 샌드박스
14
+ 테스트를 도구로 부르며 고침, 3.1의 C7)으로 고치고 출구 검사를 통과한 것만 묶음마다 수정안 PR로
15
+ 올린다. 파이프라인이 정한 규칙의 검사와 수정은 없다 (2.2).
16
+
17
+ 묶음마다 수정은 한 번이다. 수정마다 새 worktree에서 시작한다 (앞 수정의 변경이 섞이지 않게).
18
+ `/fix`로 다시 돌리면 그 묶음은 수정 판단부터 다시 돈다. 모델 묶음은 호출 상한으로 남은 판단과
19
+ 수정을 이어 한다 (4.9 명령). 호출 상한으로 남은 모델 판단(4.5)이 있으면 모델 판단부터 다시 돌고
20
+ 테스트도 다시 돌린다(새로 찾은 위반 줄의 커버 여부가 필요하다). 호출 상한으로 남은 PR 단위 판단만
21
+ 있으면 PR 단위 확인부터 다시 돈다.
22
+
23
+ PR 단위 확인(4.5 끝)의 결과는 `pr_checks`에만 있고 알리기만 한다. PR 설명 확인(PR 글과 diff 견주기,
24
+ 4.5 끝)의 결과는 `pr_description`에만 있고 역시 알리기만 한다. 수정 판단과 수정 묶음은
25
+ `doc_rules`(코드 위반)만 읽는다 (4-13).
26
+
27
+ 각 단계 사이에서 이 작업의 커밋이 아직 PR의 최신 커밋인지 확인하고, 낡았으면 멈춘다.
28
+ 그래프 상태에는 데이터만 넣고, worktree 같은 자원은 FlowContext가 들고 정리한다.
29
+ 상태는 SQLite 체크포인트에 남고 thread_id는 `repo#pr#head_sha`다. 새 커밋이 오면 SHA가 달라져
30
+ 멈춰 있던 그래프는 따로 지우지 않아도 쓰이지 않는다. 재개할 때 worktree는 다시 만든다 (5.6).
31
+ """
32
+
33
+ import logging
34
+ import sqlite3
35
+ import time
36
+ from collections.abc import Callable, Mapping, Sequence
37
+ from contextlib import ExitStack
38
+ from dataclasses import dataclass, field, replace
39
+ from pathlib import Path
40
+ from typing import Any, Final, Literal, TypedDict
41
+
42
+ from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
43
+ from langgraph.checkpoint.sqlite import SqliteSaver
44
+ from langgraph.graph import END, START, StateGraph
45
+ from langgraph.types import Command, interrupt
46
+
47
+ from app.shared.config import CallMaxima
48
+ from app.shared.embed_models_pure import E5_SMALL, EMBED_MODELS
49
+ from app.shared.job_pure import PRJob
50
+ from app.worker import (
51
+ base_config,
52
+ coverage,
53
+ doc_rules_pure,
54
+ generated_tests_pure,
55
+ mcp_pure,
56
+ memory,
57
+ merged_fix_pure,
58
+ rag_pure,
59
+ rag_switch_pure,
60
+ records,
61
+ repo,
62
+ report,
63
+ )
64
+ from app.worker.ai import claude_cli, workdir
65
+ from app.worker.base_config import BaseConfig
66
+ from app.worker.budget import CallBudget
67
+ from app.worker.call_budget_pure import RulesetScope
68
+ from app.worker.checker_authoring_pure import Checked
69
+ from app.worker.coverage import DiffCoverage
70
+ from app.worker.doc_rules_pure import DocRules, Found, RuleOutcome, RulesRead
71
+ from app.worker.doc_rules_report import FixView
72
+ from app.worker.fix import (
73
+ decide,
74
+ fix_decision_pure,
75
+ fix_pure,
76
+ mechanical_fix,
77
+ model_fix,
78
+ model_fix_pure,
79
+ proposal,
80
+ )
81
+ from app.worker.fix.fix_decision_pure import Decided, SafetyNet, open_targets
82
+ from app.worker.fix.fix_pure import MECHANICAL_BUNDLE, MechanicalFix
83
+ from app.worker.fix.model_fix_pure import ModelFix, Picked
84
+ from app.worker.fix.proposal_pure import ProposalResult
85
+ from app.worker.generated_tests_pure import Suite
86
+ from app.worker.github import GitHub
87
+ from app.worker.lang import python
88
+ from app.worker.merged_fix_pure import CarriedFrom
89
+ from app.worker.rag_pure import Retrieval
90
+ from app.worker.rag_switch_pure import RagSwitch
91
+ from app.worker.repo import CHANGES_DIFF
92
+ from app.worker.repo_config_pure import call_limits
93
+ from app.worker.rules import (
94
+ detect,
95
+ doc_rules,
96
+ pr_check,
97
+ pr_check_pure,
98
+ pr_description,
99
+ pr_description_pure,
100
+ run_check,
101
+ run_check_pure,
102
+ )
103
+ from app.worker.rules.doc_rules import Runtime as DocRuntime
104
+ from app.worker.rules.pr_check_pure import PrChecks, PrFacts
105
+ from app.worker.rules.pr_description_pure import PrDescription
106
+ from app.worker.sandbox import container, docker_cli, toolcache
107
+ from app.worker.state import Store
108
+ from app.worker.test_run_pure import PytestRun
109
+
110
+ log = logging.getLogger(__name__)
111
+
112
+ Route = Literal["next", "stop"]
113
+ CHECKPOINT_DB: Final = "checkpoints.db"
114
+ AWAIT_FIX: Final = "await_fix"
115
+ FIX_COMMENT: Final = "fix_comment"
116
+ LOAD_RULES: Final = "load_rules"
117
+ AUTHOR_CHECKERS: Final = "author_checkers"
118
+ DETECT: Final = "detect"
119
+ JUDGE: Final = "judge"
120
+ PR_CHECK: Final = "pr_check"
121
+ PR_DESCRIPTION: Final = "pr_description"
122
+ TEST: Final = "test"
123
+ DECIDE: Final = "decide"
124
+ FIX_MECHANICAL: Final = "fix_mechanical"
125
+ DELIVER_MECHANICAL: Final = "deliver_mechanical"
126
+ FIX_MODEL: Final = "fix_model"
127
+ DELIVER_MODEL: Final = "deliver_model"
128
+ MECHANICAL: Final = MECHANICAL_BUNDLE
129
+ MODEL: Final = proposal.MODEL_BUNDLE
130
+ BUNDLES: Final = (MECHANICAL, MODEL) # 고치는 순서. 싼 쪽부터 (9.3)
131
+ # 묶음 → 수정 node, 전달 node. `/fix <묶음>`이 승인하거나 다시 돌린다
132
+ FIX_NODES: Final[Mapping[str, str]] = {MECHANICAL: FIX_MECHANICAL, MODEL: FIX_MODEL}
133
+ DELIVER_NODES: Final[Mapping[str, str]] = {MECHANICAL: DELIVER_MECHANICAL, MODEL: DELIVER_MODEL}
134
+ # 묶음 → (결과의 상태 키, `/fix`로 승인했거나 다시 돌리게 한 표시의 상태 키)
135
+ STATE_KEYS: Final[Mapping[str, tuple[str, str]]] = {
136
+ MECHANICAL: ("mechanical_fix", "mechanical_requested"),
137
+ MODEL: ("model_fix", "model_requested"),
138
+ }
139
+ # 작업을 다시 시도할 때 처음부터 하지 않고 이어 가는 node. 앞 node의 결과(검증한 패치)가 저장돼 있다
140
+ RESUMABLE: Final = frozenset({DELIVER_MECHANICAL, DELIVER_MODEL})
141
+ TOOL_DIR: Final = "tools" # 도구 캐시 (data_dir 아래, venvs와 같은 자리)
142
+ # 체크포인트에서 되살릴 수 있는 상태 타입 (나머지는 langgraph가 막는다)
143
+ _STATE_TYPES: Final = (
144
+ ("app.shared.job_pure", "PRJob"),
145
+ ("app.worker.test_run_pure", "PytestRun"),
146
+ ("app.worker.test_run_pure", "ReportSummary"),
147
+ ("app.worker.fix.proposal_pure", "ProposalResult"),
148
+ ("app.worker.coverage", "DiffCoverage"),
149
+ *doc_rules_pure.STATE_TYPES,
150
+ *fix_decision_pure.STATE_TYPES,
151
+ *model_fix_pure.STATE_TYPES,
152
+ *generated_tests_pure.STATE_TYPES,
153
+ *mcp_pure.STATE_TYPES,
154
+ *merged_fix_pure.STATE_TYPES,
155
+ *fix_pure.STATE_TYPES,
156
+ *rag_pure.STATE_TYPES,
157
+ *rag_switch_pure.STATE_TYPES,
158
+ *pr_check_pure.STATE_TYPES,
159
+ *pr_description_pure.STATE_TYPES,
160
+ )
161
+
162
+
163
+ def run_pr_tests(
164
+ worktree: Path,
165
+ *,
166
+ job_id: str | None = None,
167
+ is_stale: Callable[[], bool] | None = None,
168
+ venv_cache: Path = python.VENV_CACHE,
169
+ tool_cache: Path = toolcache.TOOL_CACHE,
170
+ memory_gb: float = docker_cli.MEMORY_LIMIT_GB,
171
+ names: docker_cli.Names = docker_cli.DEFAULT_NAMES,
172
+ contexts: bool = False,
173
+ ) -> PytestRun:
174
+ """테스트 단계: 이미지 준비 → Python 런타임(도구 캐시) → .venv 준비 → 작업 컨테이너에서 pytest
175
+ → 결과.
176
+
177
+ Docker 실패와 런타임을 받지 못함은 docker_cli.SandboxError(환경 오류), pip 실패는
178
+ python.DependencyInstallError로 올라간다. 처리는 app/worker/update.py가 정한다.
179
+ """
180
+ image = docker_cli.ensure_image(names.image)
181
+ runtime = python.ensure_runtime(tool_cache, names.image)
182
+ venv_dir = python.ensure_venv(
183
+ worktree, image, runtime, cache_dir=venv_cache, tag=names.image, memory_gb=memory_gb
184
+ )
185
+ mounts = [(venv_dir, python.VENV_IN_CONTAINER), (runtime.dir, python.RUNTIME_IN_CONTAINER)]
186
+ with container.running(
187
+ worktree, mounts, job_id=job_id, memory_gb=memory_gb, names=names
188
+ ) as name:
189
+ return python.run_tests(name, worktree, is_stale=is_stale, contexts=contexts)
190
+
191
+
192
+ class FlowState(TypedDict, total=False):
193
+ job: PRJob
194
+ diff_coverage: DiffCoverage | None
195
+ rules_read: RulesRead # 규칙 읽기 → 검사 방법 정하기 → 위반 찾기 사이에만 쓴다
196
+ rule_checks: tuple[RuleOutcome, ...]
197
+ checker_retrievals: tuple[Retrieval, ...] # 검사기 작성에 넣은 과거 기록 (Found로 옮긴다)
198
+ rag_switch: RagSwitch # 이 검사의 검색 상태와 이유 (규칙 읽기에서 정함, 6.7)
199
+ doc_rules: DocRules # 규칙 경로의 결과. 코멘트의 규칙 절은 이 값으로만 그린다
200
+ # PR 단위 확인의 결과 (4.5 끝). PR 규칙이 있는 검사만. 알리기만 하고 수정 경로는 읽지 않는다
201
+ pr_checks: PrChecks
202
+ # PR 설명 확인의 결과 (4.5 끝). `.pipeline.yaml`로 끄지 않은 검사만. 알리기만 한다
203
+ pr_description: PrDescription
204
+ fix_decisions: Decided # 위반마다 수정 판단 (테스트 뒤, 4.6)
205
+ mechanical_fix: MechanicalFix | None # 기계적 수정 묶음의 결과. 수정안 PR은 proposals에
206
+ mechanical_requested: bool # 사람이 `/fix`로 이 커밋의 기계적 묶음을 승인했거나 다시 돌림
207
+ model_fix: ModelFix | None # 모델 수정 묶음의 결과 (4.7, 4.8)
208
+ model_requested: bool
209
+ test_run: PytestRun
210
+ commented: bool
211
+ fix_skill: str # 승인 대기에서 `/fix`가 고른 묶음
212
+ proposals: dict[str, ProposalResult] # 묶음 → 수정안 PR
213
+ # 수정안을 머지한 커밋이라 검사하지 않고 검증한 결과를 옮겨 적었다 (`carry_flow`)
214
+ carried: CarriedFrom
215
+ stopped: Literal["stale", "cancelled"]
216
+
217
+
218
+ @dataclass
219
+ class FlowContext:
220
+ store: Store
221
+ github: GitHub
222
+ data_dir: Path
223
+ run_id: int
224
+ comment_id: int | None
225
+ max_memory_gb: float
226
+ call_maxima: CallMaxima = field(default_factory=CallMaxima)
227
+ sandbox_names: docker_cli.Names = docker_cli.DEFAULT_NAMES
228
+ started: float = field(default_factory=time.monotonic)
229
+ stack: ExitStack = field(default_factory=ExitStack)
230
+ worktree: Path | None = None
231
+ merge_base: str | None = None # PR이 바꾼 줄을 셀 기준 (repo.Checkout.merge_base)
232
+ base: BaseConfig | None = None
233
+ # 의존성 설치가 실패해도(그래프 밖 예외) 코멘트에 규칙 결과를 쓰려고 여기에도 둔다
234
+ doc_rules: DocRules | None = None
235
+ doc_runtime: DocRuntime | None = None
236
+ pr_checks: PrChecks | None = None # doc_rules와 같은 까닭으로 둔다
237
+ pr_description: PrDescription | None = None # doc_rules와 같은 까닭으로 둔다
238
+ # 이 작업에서 읽은 PR 사실 (PR 단위 확인과 PR 설명 확인이 같이 쓴다. 그래프 상태에 넣지 않는다)
239
+ pr_facts: PrFacts | str | None = None
240
+ first_call: int = 0 # 규칙 경로를 시작하기 전 마지막 호출 기록의 id
241
+ dirty: bool = False # 수정이 worktree를 바꿨다. 다음 수정은 새 worktree에서 한다
242
+ changes_diff: bytes = b"" # 테스트 전에 읽은 PR의 diff (테스트 뒤에는 샌드박스가 바꿀 수 있다)
243
+ run_tests: Callable[..., PytestRun] | None = None # 없으면 run_pr_tests
244
+ rag_model: str = E5_SMALL # 파이프라인 쪽 `rag.embed_model`. 저장소가 검색을 켰을 때만 쓴다
245
+
246
+
247
+ def _is_stale_for(ctx: FlowContext, job: PRJob) -> Callable[[], bool]:
248
+ def is_stale() -> bool:
249
+ ctx.store.heartbeat(ctx.run_id) # 10초마다 불리므로 생존 확인도 같이 남긴다
250
+ return ctx.store.is_stale(job)
251
+
252
+ return is_stale
253
+
254
+
255
+ def pr_tests(
256
+ ctx: FlowContext, job: PRJob, worktree: Path | None = None, *, contexts: bool = False
257
+ ) -> PytestRun:
258
+ """ctx의 worktree(또는 worktree)에서 PR의 테스트를 샌드박스로 돌린다. 테스트 node와 수정 단계,
259
+ 코멘트 수정(4.11)이 같이 쓴다."""
260
+ kw = {"contexts": True} if contexts else {}
261
+ return (ctx.run_tests or run_pr_tests)(
262
+ worktree or ctx.worktree,
263
+ job_id=f"{ctx.run_id}",
264
+ is_stale=_is_stale_for(ctx, job),
265
+ venv_cache=ctx.data_dir / "venvs",
266
+ tool_cache=ctx.data_dir / TOOL_DIR,
267
+ memory_gb=ctx.base.memory_gb,
268
+ names=ctx.sandbox_names,
269
+ **kw,
270
+ )
271
+
272
+
273
+ def pr_suite(
274
+ ctx: FlowContext, job: PRJob, generated: Mapping[str, bytes] | None, files: Sequence[str]
275
+ ) -> Suite:
276
+ """수정 작성의 테스트 도구와 출구 검사의 테스트 (4.7, 4.8의 6번). generated가 있으면 PR
277
+ head의 따로 된 worktree에 그 테스트 파일만 얹어 고치기 전 코드로 돌린다."""
278
+ if generated is None:
279
+ return python.read_suite(pr_tests(ctx, job, contexts=True), ctx.worktree, files)
280
+ with repo.side_worktree(ctx.worktree, job.head_sha) as side:
281
+ for rel, data in generated.items():
282
+ (side / rel).parent.mkdir(parents=True, exist_ok=True)
283
+ (side / rel).write_bytes(data)
284
+ return python.read_suite(pr_tests(ctx, job, side, contexts=True), side, files)
285
+
286
+
287
+ def thread_id(repo_name: str, pr_number: int, head_sha: str) -> str:
288
+ return f"{repo_name}#{pr_number}#{head_sha}"
289
+
290
+
291
+ def thread_config(job: PRJob) -> dict[str, Any]:
292
+ return {"configurable": {"thread_id": thread_id(job.repo, job.pr_number, job.head_sha)}}
293
+
294
+
295
+ def open_checkpointer(data_dir: Path, stack: ExitStack) -> SqliteSaver:
296
+ data_dir.mkdir(parents=True, exist_ok=True)
297
+ conn = sqlite3.connect(data_dir / CHECKPOINT_DB, check_same_thread=False)
298
+ stack.callback(conn.close)
299
+ return SqliteSaver(conn, serde=JsonPlusSerializer(allowed_msgpack_modules=list(_STATE_TYPES)))
300
+
301
+
302
+ def _enter_checkout(ctx: FlowContext, job: PRJob) -> None:
303
+ co = ctx.stack.enter_context(
304
+ repo.checkout(ctx.data_dir, job.repo, job.pr_number, job.head_sha, job.base_sha)
305
+ )
306
+ ctx.worktree = co.path
307
+ ctx.merge_base = co.merge_base
308
+ ctx.dirty = False
309
+ ctx.base = base_config.load(co.path, job.base_sha, ctx.max_memory_gb)
310
+ try: # 테스트 전에 읽어 둔다. 테스트 뒤에는 샌드박스의 PR 코드가 바꿀 수 있다
311
+ ctx.changes_diff = (co.path / CHANGES_DIFF).read_bytes()
312
+ except OSError:
313
+ ctx.changes_diff = b""
314
+
315
+
316
+ def build_graph(ctx: FlowContext, checkpointer: SqliteSaver | None = None):
317
+ def enter_checkout(job: PRJob) -> None:
318
+ _enter_checkout(ctx, job)
319
+
320
+ def ensure_checkout(job: PRJob) -> None:
321
+ """재개하면 새 프로세스라 worktree와 base 설정이 없다. 수정안 상태를 보려면 필요하다."""
322
+ if ctx.base is None:
323
+ enter_checkout(job)
324
+
325
+ def fresh_worktree(job: PRJob) -> None:
326
+ """수정 단계의 worktree. 재개했거나(지워졌다) 앞 수정이 바꿨으면 새로 만든다."""
327
+ if ctx.worktree is None or ctx.dirty:
328
+ enter_checkout(job)
329
+ ctx.dirty = True
330
+
331
+ def progress(job: PRJob, step: str) -> None:
332
+ ctx.comment_id = ctx.github.upsert_comment(
333
+ job.repo, job.pr_number, report.render_progress(job.head_sha, step), ctx.comment_id
334
+ )
335
+
336
+ def tests_for(job: PRJob, worktree: Path | None = None, *, contexts: bool = False) -> PytestRun:
337
+ return pr_tests(ctx, job, worktree, contexts=contexts)
338
+
339
+ def suite_for(job: PRJob, generated: Mapping[str, bytes] | None, files: Sequence[str]) -> Suite:
340
+ return pr_suite(ctx, job, generated, files)
341
+
342
+ def checkout(state: FlowState) -> FlowState:
343
+ enter_checkout(state["job"])
344
+ return {}
345
+
346
+ def rag_switch(state: FlowState) -> RagSwitch:
347
+ """이 검사의 검색 상태. 규칙 읽기에서 한 번 정해 상태에 두고, 재개한 프로세스도 그 값을
348
+ 쓴다. 상태에 없으면(이 값이 생기기 전의 체크포인트) 지금 정한다 (6.7)."""
349
+ saved = state.get("rag_switch")
350
+ if saved is not None:
351
+ return saved
352
+ return memory.switch_for(ctx.store, state["job"].repo, ctx.base.repo.rag.enabled)
353
+
354
+ def doc_runtime(state: FlowState) -> DocRuntime:
355
+ job = state["job"]
356
+ if ctx.doc_runtime is None:
357
+ models = ctx.base.repo.model
358
+ limits = call_limits(models.calls, **ctx.call_maxima.model_dump())
359
+ ctx.doc_runtime = DocRuntime(
360
+ store=ctx.store,
361
+ budget=CallBudget(ctx.store, job.repo, job.pr_number, job.head_sha, limits),
362
+ models=models,
363
+ ask=claude_cli.run_structured,
364
+ sandbox=doc_rules.sandbox_for(
365
+ ctx.data_dir / TOOL_DIR, ctx.base.ruff, ctx.sandbox_names.image
366
+ ),
367
+ ruff=ctx.base.ruff,
368
+ disabled=frozenset(ctx.base.repo.rules.disabled),
369
+ retriever=retriever_for(job, rag_switch(state)),
370
+ secrets=tuple(proposal.pipeline_secrets()),
371
+ )
372
+ return ctx.doc_runtime
373
+
374
+ def retriever_for(job: PRJob, switch: RagSwitch) -> memory.Retriever | None:
375
+ """검색이 켜진 검사만 검색한다 (6.5, 6.7). 꺼져 있으면 memory의 검색 함수를 부르지 않으므로
376
+ chromadb도 임베딩 모델도 쓰지 않는다 (완료 기준 5-8)."""
377
+ if not switch.on:
378
+ return None
379
+ return memory.open_retriever(
380
+ ctx.data_dir, ctx.store, job.repo, ctx.base.repo.rag, EMBED_MODELS[ctx.rag_model]
381
+ )
382
+
383
+ def doc_rules_done(result: DocRules) -> FlowState:
384
+ ctx.doc_rules = result # 의존성 설치가 실패해도(그래프 밖 예외) 코멘트에 보인다
385
+ return {"doc_rules": result}
386
+
387
+ def load_rules(state: FlowState) -> FlowState:
388
+ """base의 규칙 문서와 도구 설정을 읽는다 (5.1 load_rules). 규칙이 없으면 여기서 끝난다."""
389
+ job = state["job"]
390
+ progress(job, "규칙 읽기")
391
+ ctx.first_call = doc_rules.last_call_id(ctx.store, job.repo, job.pr_number)
392
+ switch = rag_switch(state)
393
+ rt = doc_runtime({**state, "rag_switch": switch})
394
+ if rt.retriever is not None: # 검색을 켠 첫 검사에서 폴더를 만들고 밀린 기록을 넣는다 (6.5)
395
+ rt.retriever.prepare()
396
+ read = doc_rules.read(ctx.worktree, job.base_sha, ctx.base.repo.rules, rt, ctx.changes_diff)
397
+ if isinstance(read, RulesRead):
398
+ return {"rules_read": read, "rag_switch": switch}
399
+ return {**doc_rules_done(read), "rag_switch": switch}
400
+
401
+ def author_checkers(state: FlowState) -> FlowState:
402
+ """규칙마다 도구나 검사기를 정하거나 저장한 것을 쓴다 (5.1 plan_checks, author_checker)."""
403
+ job = state["job"]
404
+ used: list[Retrieval] = []
405
+ outcomes = doc_rules.author(
406
+ state["rules_read"], doc_runtime(state), is_stale=lambda: ctx.store.is_stale(job),
407
+ on_retrieval=used.append,
408
+ ) # fmt: skip
409
+ if isinstance(outcomes, tuple):
410
+ return {"rule_checks": outcomes, "checker_retrievals": tuple(used)}
411
+ return doc_rules_done(outcomes)
412
+
413
+ def detect_rules(state: FlowState) -> FlowState:
414
+ """채택한 도구와 검사기를 PR이 바꾼 파일에 돌린다 (5.1 detect). 바뀐 줄의 위반만 남긴다."""
415
+ result = doc_rules.find(
416
+ state["rules_read"], state["rule_checks"], ctx.worktree, ctx.changes_diff,
417
+ doc_runtime(state), since_call=ctx.first_call,
418
+ retrievals=state.get("checker_retrievals", ()),
419
+ ) # fmt: skip
420
+ return doc_rules_done(result)
421
+
422
+ def judge_rules(state: FlowState) -> FlowState:
423
+ """검사기를 만들지 못한 규칙을 모델이 바뀐 hunk에 대해 본다 (5.1 detect의 모델 판단, 4.5).
424
+
425
+ 그 뒤 사람이 닫은 수정안이 고친 줄에 표시하고(4.6 표의 첫 줄), 작성자가 고친 이전 위반과
426
+ 이번 위반을 기록한다 (4.10). `/fix`가 남은 모델 판단을 이어 할 때도 이 node부터 돈다.
427
+ """
428
+ job, result = state["job"], state.get("doc_rules")
429
+ if not isinstance(result, Found):
430
+ return {}
431
+ ensure_checkout(job) # `/fix`가 이어 할 때는 새 프로세스다
432
+ if any(isinstance(o, doc_rules_pure.RuleJudged) for o in result.outcomes):
433
+ progress(job, "모델 판단")
434
+ result = doc_rules.judge(
435
+ result, ctx.worktree, ctx.changes_diff, doc_runtime(state),
436
+ is_stale=lambda: ctx.store.is_stale(job),
437
+ ) # fmt: skip
438
+ result = records.mark_rejected(ctx.store, job, result)
439
+ merged_fix = any(
440
+ p.state == "merged" and p.merge_commit == job.head_sha
441
+ for p in ctx.store.proposals(job.repo, job.pr_number)
442
+ )
443
+ records.after_detect(
444
+ ctx.store, job, result, ctx.worktree, proposal.pipeline_secrets(),
445
+ merged_fix=merged_fix,
446
+ ) # fmt: skip
447
+ return doc_rules_done(result)
448
+
449
+ def pr_check_rules(state: FlowState) -> FlowState:
450
+ """확인 대상이 `pr`인 규칙을 PR 자체에 대해 본다 (4.5 끝). PR 규칙이 없으면 PR의 글을 읽지
451
+ 않는다. 가드레일(8.6)이 들인 작업에서만 이 node까지 온다. `/fix`가 남은 PR 단위 판단을 이어
452
+ 할 때도 이 node를 지난다."""
453
+ job, found = state["job"], state.get("doc_rules")
454
+ rules_ = pr_check.pr_rules(found)
455
+ if not rules_:
456
+ return {}
457
+ ensure_checkout(job)
458
+ progress(job, "PR 단위 확인")
459
+ rt = doc_runtime(state)
460
+ read = state.get("rules_read")
461
+ scope = RulesetScope(read.key, len(read.rules)) if read is not None else RulesetScope("pr")
462
+ facts = pr_facts(job)
463
+ tools = pr_check.Tools(
464
+ store=rt.store, budget=rt.budget, ask=rt.ask, sandbox=rt.sandbox,
465
+ plan_model=rt.models.checker, judge_model=rt.models.judge, ruleset=scope,
466
+ ) # fmt: skip
467
+ known = len(found.violations) if isinstance(found, Found) else 0
468
+ result = pr_check.check(
469
+ rules_, facts, tools, known=known, is_stale=lambda: ctx.store.is_stale(job)
470
+ )
471
+ ctx.pr_checks = result
472
+ return {"pr_checks": result}
473
+
474
+ def pr_facts(job: PRJob) -> PrFacts | str:
475
+ """이 작업의 PR 사실. 처음 부를 때 한 번 읽는다 (GitHub 조회 한 번)."""
476
+ if ctx.pr_facts is None:
477
+ ctx.pr_facts = pr_check.gather(
478
+ ctx.worktree, ctx.merge_base or job.base_sha, job.head_sha, github=ctx.github,
479
+ store=ctx.store, repo_name=job.repo, pr_number=job.pr_number,
480
+ ) # fmt: skip
481
+ return ctx.pr_facts
482
+
483
+ def describe_pr(state: FlowState) -> FlowState:
484
+ """PR 글(제목, 본문, 커밋 메시지)과 diff를 모델이 견준다 (4.5 끝). 팀 문서의 규칙과 따로
485
+ 돌고(규칙이 없어도), 알리기만 한다. 가드레일(8.6)이 들인 작업에서만 이 node까지 와서 PR 글을
486
+ 읽는다. `.pipeline.yaml`의 `pr_description.enabled: false`면 돌지 않는다. `/fix`가 앞
487
+ node부터 다시 돌 때 이미 견준 결과가 있으면(호출 상한으로 남은 것이 아니면) 그대로 둔다."""
488
+ job = state["job"]
489
+ if not ctx.base.repo.pr_description.enabled:
490
+ return {}
491
+ saved = state.get("pr_description")
492
+ if saved is not None and not pr_description_pure.description_left(saved):
493
+ return {}
494
+ ensure_checkout(job)
495
+ progress(job, "PR 설명 확인")
496
+ rt, found = doc_runtime(state), state.get("doc_rules")
497
+ facts = pr_facts(job)
498
+ pipeline = (
499
+ () if isinstance(facts, str) else pr_description.pipeline_diffs(ctx.worktree, facts)
500
+ )
501
+ result = pr_description.check(
502
+ facts, ctx.changes_diff.decode("utf-8", errors="replace"), ctx.worktree,
503
+ pr_description.Tools(store=rt.store, budget=rt.budget, ask=rt.ask,
504
+ model=rt.models.judge),
505
+ pipeline=pipeline, known=len(found.violations) if isinstance(found, Found) else 0,
506
+ is_stale=lambda: ctx.store.is_stale(job),
507
+ ) # fmt: skip
508
+ ctx.pr_description = result
509
+ return {"pr_description": result}
510
+
511
+ def after_doc_step(state: FlowState) -> str:
512
+ if state.get("stopped") or ctx.store.is_stale(state["job"]):
513
+ return "stop"
514
+ return "done" if "doc_rules" in state else "next"
515
+
516
+ def test(state: FlowState) -> FlowState:
517
+ job = state["job"]
518
+ progress(job, "테스트 실행")
519
+ run = tests_for(job)
520
+ if run.cancelled:
521
+ return {"test_run": run, "stopped": "cancelled"}
522
+ out: FlowState = {"test_run": run}
523
+ doc = state.get("doc_rules")
524
+ if isinstance(doc, Found) and doc.violations: # 위반 줄이 테스트로 실행되는지 (4.5)
525
+ covered = python.annotate_coverage(doc.violations, run.coverage_xml, ctx.worktree)
526
+ ctx.doc_rules = out["doc_rules"] = replace(doc, violations=covered)
527
+ out["diff_coverage"] = (
528
+ coverage.diff_coverage(run.coverage_xml, ctx.changes_diff) if ctx.changes_diff else None
529
+ )
530
+ doc = out.get("doc_rules", doc)
531
+ if isinstance(doc, Found) and run_check_pure.run_rules(doc):
532
+ # 실행 결과의 규칙은 테스트와 커버리지를 보고 모델이 정한다 (4.5)
533
+ progress(job, "실행 결과의 규칙")
534
+ runs = run_check.judge_runs(
535
+ doc, run, ctx.changes_diff, doc_runtime(state),
536
+ is_stale=lambda: ctx.store.is_stale(job),
537
+ ) # fmt: skip
538
+ ctx.doc_rules = out["doc_rules"] = replace(doc, runs=runs)
539
+ return out
540
+
541
+ def decide_fixes(state: FlowState) -> FlowState:
542
+ """위반마다 fix/skip을 정한다 (5.1 decide). 표가 테스트 상태와 커버리지를 본다."""
543
+ job, found = state["job"], state.get("doc_rules")
544
+ if not isinstance(found, Found) or not found.violations:
545
+ return {}
546
+ ensure_checkout(job) # `/fix`가 다시 돌릴 때는 새 프로세스다
547
+ progress(job, "수정 판단")
548
+ rt, run = doc_runtime(state), state["test_run"]
549
+ decided = decide.decide(
550
+ found, SafetyNet(run.status, flaky=bool(run.flaky)), ctx.changes_diff, store=rt.store,
551
+ budget=rt.budget, model=rt.models.decide, ask=rt.ask, retriever=rt.retriever,
552
+ context_of=records.context_of(ctx.worktree),
553
+ ) # fmt: skip
554
+ return {"fix_decisions": decided}
555
+
556
+ def targets(state: FlowState, bundle: str) -> Picked | None:
557
+ """수정 판단이 그 묶음으로 정한 위반. 없으면 None."""
558
+ found, decided = state.get("doc_rules"), state.get("fix_decisions")
559
+ if not isinstance(found, Found) or decided is None:
560
+ return None
561
+ pick = mechanical_fix.pick_targets if bundle == MECHANICAL else model_fix_pure.pick_targets
562
+ picked = pick(found.violations, decided.decisions)
563
+ return picked if picked.targets else None
564
+
565
+ def fix_view(state: FlowState, bundle: str) -> FixView | None:
566
+ picked = targets(state, bundle)
567
+ if picked is None:
568
+ return None
569
+ counts = {"targets": len(picked.targets), "size_capped": len(picked.size_capped)}
570
+ result_key, requested_key = STATE_KEYS[bundle]
571
+ done = state.get(result_key)
572
+ if done is not None:
573
+ result = state.get("proposals", {}).get(bundle)
574
+ attempt = ctx.store.fix_attempt(done.attempt_id) if done.attempt_id else None
575
+ patch = (attempt.patch or "") if attempt is not None else ""
576
+ return FixView(**counts, state="done", fix=done, proposal=result, patch=patch)
577
+ job, requested = state["job"], state.get(requested_key, False)
578
+ history, number = proposal.blocked_by_history(
579
+ ctx.store, job.repo, job.pr_number, bundle, job.head_sha
580
+ )
581
+ # `/fix`로 다시 돌리면 이 커밋의 열린 수정안 PR을 같은 브랜치로 갱신한다
582
+ if history and not (history == "open" and requested):
583
+ return FixView(**counts, state=history, number=number)
584
+ if ctx.base.repo.fix.require_approval and not requested:
585
+ return FixView(**counts, state="approval")
586
+ return FixView(**counts, state="running")
587
+
588
+ def awaiting(state: FlowState) -> list[str]:
589
+ """승인을 기다리는 묶음."""
590
+ return [
591
+ b for b in BUNDLES if (v := fix_view(state, b)) is not None and v.state == "approval"
592
+ ]
593
+
594
+ def render(state: FlowState) -> str:
595
+ job = state["job"]
596
+ return report.render_result(
597
+ state["test_run"],
598
+ job.head_sha,
599
+ time.monotonic() - ctx.started,
600
+ base=ctx.base,
601
+ diff_coverage=state.get("diff_coverage"),
602
+ from_sync=job.source == "sync",
603
+ doc_rules=state.get("doc_rules"),
604
+ checkers=doc_rules.shown_checkers(state.get("doc_rules"), ctx.store),
605
+ decisions=state.get("fix_decisions"),
606
+ fixes={b: v for b in BUNDLES if (v := fix_view(state, b)) is not None},
607
+ rag=state.get("rag_switch"),
608
+ pr=state.get("pr_checks"),
609
+ carried=state.get("carried"),
610
+ description=state.get("pr_description"),
611
+ )
612
+
613
+ def comment(state: FlowState) -> FlowState:
614
+ job = state["job"]
615
+ ctx.comment_id = ctx.github.upsert_comment(
616
+ job.repo, job.pr_number, render(state), ctx.comment_id
617
+ )
618
+ return {"commented": True}
619
+
620
+ def next_fix(state: FlowState) -> str:
621
+ """코멘트 뒤: 바로 고칠 묶음이 있으면 그 수정, 승인을 기다릴 묶음이 있으면 대기."""
622
+ if ctx.store.is_stale(state["job"]):
623
+ return END
624
+ for bundle in BUNDLES:
625
+ view = fix_view(state, bundle)
626
+ if view is not None and view.state == "running":
627
+ return FIX_NODES[bundle]
628
+ return AWAIT_FIX if awaiting(state) else END
629
+
630
+ def await_fix(state: FlowState) -> FlowState:
631
+ # 상태를 체크포인트에 남기고 멈춘다. 워커는 다른 작업을 처리한다.
632
+ # /fix <묶음>이 오면 이 node부터 재개된다
633
+ ensure_checkout(state["job"])
634
+ bundles = awaiting(state)
635
+ approval = interrupt({"skills": bundles, "head_sha": state["job"].head_sha})
636
+ bundle = approval.get("skill") if isinstance(approval, dict) else None
637
+ if bundle not in bundles:
638
+ return {"fix_skill": ""}
639
+ return {"fix_skill": bundle, STATE_KEYS[bundle][1]: True}
640
+
641
+ def after_await(state: FlowState) -> str:
642
+ return FIX_NODES.get(state.get("fix_skill") or "", END)
643
+
644
+ def fix_mechanical(state: FlowState) -> FlowState:
645
+ """fix·mechanical로 정한 위반을 도구의 수정으로 고친다 (5.1 fix_mechanical, 4.7, 4.8)."""
646
+ job, found = state["job"], state["doc_rules"]
647
+ picked = targets(state, MECHANICAL)
648
+ fresh_worktree(job)
649
+ progress(job, "기계적 수정")
650
+ rt = doc_runtime(state)
651
+ notes = model_fix.notes_for(found, picked, ctx.worktree)
652
+ outcome = mechanical_fix.fix_violations(
653
+ found, picked, worktree=ctx.worktree, merge_base=ctx.merge_base,
654
+ base_sha=job.base_sha, test_before=state["test_run"],
655
+ checks=doc_rules.saved_checks(found, rt.store), sandbox=rt.sandbox,
656
+ run_tests=lambda: tests_for(job), is_stale=lambda: ctx.store.is_stale(job),
657
+ secrets=proposal.pipeline_secrets(), disabled=rt.disabled,
658
+ ) # fmt: skip
659
+ if outcome is None:
660
+ return {"stopped": "cancelled"}
661
+ outcome = mechanical_fix.save_attempt(
662
+ ctx.store, job, ctx.merge_base, outcome, notes, ctx.worktree
663
+ )
664
+ records.after_failed_fix(
665
+ ctx.store, job, outcome, notes, ctx.worktree, proposal.pipeline_secrets()
666
+ )
667
+ return {"mechanical_fix": outcome}
668
+
669
+ def deliver_mechanical(state: FlowState) -> FlowState:
670
+ """검증을 통과한 기계적 수정안만 수정안 PR로 올린다 (5.1 deliver). 늘 새 worktree에 저장한
671
+ 패치를 적용하고 파일 해시를 맞춰 본 뒤 올린다 (4.8 끝)."""
672
+ fix = state["mechanical_fix"]
673
+ if not fix.ready:
674
+ return {}
675
+ job = state["job"]
676
+ fresh_worktree(job)
677
+ progress(job, "수정안 PR (기계적 수정)")
678
+ stored = model_fix.reapply(ctx.store, fix.attempt_id, ctx.worktree)
679
+ if isinstance(stored, str):
680
+ result = ProposalResult(reason=stored)
681
+ else:
682
+ result = proposal.open_mechanical_proposal(
683
+ job, ctx.worktree, ctx.store, ctx.github, fix, state["doc_rules"],
684
+ patch=stored.patch or "", tool=ctx.base.ruff.label,
685
+ ) # fmt: skip
686
+ return {"proposals": {**state.get("proposals", {}), MECHANICAL: result}}
687
+
688
+ def fix_model(state: FlowState) -> FlowState:
689
+ """fix·model로 정한 위반을 모델이 도구로 확인하며 고치고 출구 검사를 한다 (5.1)."""
690
+ job, found = state["job"], state["doc_rules"]
691
+ picked = targets(state, MODEL)
692
+ fresh_worktree(job)
693
+ progress(job, "모델 수정")
694
+ rt = doc_runtime(state)
695
+ budget = rt.budget.with_targets(open_targets(state["fix_decisions"].decisions))
696
+ checks = doc_rules.saved_checks(found, rt.store)
697
+ tools = model_fix.FixTools(
698
+ run_model=workdir.run_in_model_folder,
699
+ recheck=lambda changed, new: detect.detect(
700
+ checks,
701
+ ctx.worktree,
702
+ changed,
703
+ new_files=new,
704
+ sandbox=rt.sandbox,
705
+ disabled=rt.disabled,
706
+ ), # fmt: skip
707
+ rules_rechecked=sum(1 for c in checks if isinstance(c, Checked)),
708
+ run_suite=lambda generated, files: suite_for(job, generated, files),
709
+ is_stale=lambda: ctx.store.is_stale(job),
710
+ secrets=proposal.pipeline_secrets(),
711
+ )
712
+ notes = model_fix.notes_for(found, picked, ctx.worktree)
713
+ outcome = model_fix.fix_violations(
714
+ found, picked, worktree=ctx.worktree, merge_base=ctx.merge_base,
715
+ test_before=state["test_run"], store=rt.store, budget=budget,
716
+ models=ctx.base.repo.model, max_attempts=ctx.base.repo.fix.max_retries, tools=tools,
717
+ generation=ctx.store.call_grants(job.repo, job.pr_number), retriever=rt.retriever,
718
+ context_of=records.context_of(ctx.worktree),
719
+ ) # fmt: skip
720
+ if outcome is None:
721
+ return {"stopped": "cancelled"}
722
+ outcome = model_fix.save_attempt(
723
+ ctx.store, job, ctx.merge_base, outcome, notes, ctx.worktree
724
+ )
725
+ records.after_failed_fix(
726
+ ctx.store, job, outcome, notes, ctx.worktree, proposal.pipeline_secrets()
727
+ )
728
+ return {"model_fix": outcome}
729
+
730
+ def deliver_model(state: FlowState) -> FlowState:
731
+ """검증을 통과한 모델 수정안만 수정안 PR로 올린다 (5.1 deliver).
732
+
733
+ 늘 새 worktree에 저장한 패치(`fix_attempts`)를 적용하고 파일 해시를 맞춰 본 뒤 올린다
734
+ (4.8 끝). 전달이 실패해 재시도가 이 node부터 이어 가도 모델을 다시 부르지 않고 같은 패치가
735
+ 올라간다 (3.1의 C6).
736
+ """
737
+ fix = state["model_fix"]
738
+ if not fix.ready:
739
+ return {}
740
+ job = state["job"]
741
+ fresh_worktree(job)
742
+ progress(job, "수정안 PR (모델 수정)")
743
+ stored = model_fix.reapply(ctx.store, fix.attempt_id, ctx.worktree)
744
+ if isinstance(stored, str):
745
+ result = ProposalResult(reason=stored)
746
+ else:
747
+ skipped = sum(1 for d in state["fix_decisions"].decisions if d.action == "skip")
748
+ result = proposal.open_model_proposal(
749
+ job, ctx.worktree, ctx.store, ctx.github, fix, state["doc_rules"],
750
+ patch=stored.patch or "", skipped=skipped,
751
+ ) # fmt: skip
752
+ return {"proposals": {**state.get("proposals", {}), MODEL: result}}
753
+
754
+ def fix_comment(state: FlowState) -> FlowState:
755
+ job = state["job"]
756
+ ctx.comment_id = ctx.github.upsert_comment(
757
+ job.repo, job.pr_number, render(state), ctx.comment_id
758
+ )
759
+ return {}
760
+
761
+ def route(state: FlowState) -> Route:
762
+ if state.get("stopped") or ctx.store.is_stale(state["job"]):
763
+ return "stop"
764
+ return "next"
765
+
766
+ fix_targets = [AWAIT_FIX, FIX_MECHANICAL, FIX_MODEL, END]
767
+ graph = StateGraph(FlowState)
768
+ graph.add_node("checkout", checkout)
769
+ graph.add_node(LOAD_RULES, load_rules)
770
+ graph.add_node(AUTHOR_CHECKERS, author_checkers)
771
+ graph.add_node(DETECT, detect_rules)
772
+ graph.add_node(JUDGE, judge_rules)
773
+ graph.add_node(PR_CHECK, pr_check_rules)
774
+ graph.add_node(PR_DESCRIPTION, describe_pr)
775
+ graph.add_node(TEST, test)
776
+ graph.add_node(DECIDE, decide_fixes)
777
+ graph.add_node("comment", comment)
778
+ graph.add_node(AWAIT_FIX, await_fix)
779
+ graph.add_node(FIX_MECHANICAL, fix_mechanical)
780
+ graph.add_node(DELIVER_MECHANICAL, deliver_mechanical)
781
+ graph.add_node(FIX_MODEL, fix_model)
782
+ graph.add_node(DELIVER_MODEL, deliver_model)
783
+ graph.add_node(FIX_COMMENT, fix_comment)
784
+ graph.add_edge(START, "checkout")
785
+ graph.add_conditional_edges("checkout", route, {"next": LOAD_RULES, "stop": END})
786
+ graph.add_conditional_edges(
787
+ LOAD_RULES, after_doc_step, {"next": AUTHOR_CHECKERS, "done": PR_DESCRIPTION, "stop": END}
788
+ )
789
+ graph.add_conditional_edges(
790
+ AUTHOR_CHECKERS, after_doc_step, {"next": DETECT, "done": PR_DESCRIPTION, "stop": END}
791
+ )
792
+ graph.add_conditional_edges(DETECT, route, {"next": JUDGE, "stop": END})
793
+ graph.add_conditional_edges(JUDGE, route, {"next": PR_CHECK, "stop": END})
794
+ graph.add_conditional_edges(PR_CHECK, route, {"next": PR_DESCRIPTION, "stop": END})
795
+ graph.add_conditional_edges(PR_DESCRIPTION, route, {"next": TEST, "stop": END})
796
+ graph.add_conditional_edges(TEST, route, {"next": DECIDE, "stop": END})
797
+ graph.add_conditional_edges(DECIDE, route, {"next": "comment", "stop": END})
798
+ graph.add_conditional_edges("comment", next_fix, fix_targets)
799
+ graph.add_conditional_edges(AWAIT_FIX, after_await, [FIX_MECHANICAL, FIX_MODEL, END])
800
+ graph.add_conditional_edges(FIX_MECHANICAL, route, {"next": DELIVER_MECHANICAL, "stop": END})
801
+ graph.add_conditional_edges(DELIVER_MECHANICAL, route, {"next": FIX_COMMENT, "stop": END})
802
+ graph.add_conditional_edges(FIX_MODEL, route, {"next": DELIVER_MODEL, "stop": END})
803
+ graph.add_conditional_edges(DELIVER_MODEL, route, {"next": FIX_COMMENT, "stop": END})
804
+ graph.add_conditional_edges(FIX_COMMENT, next_fix, fix_targets)
805
+ return graph.compile(checkpointer=checkpointer)
806
+
807
+
808
+ def run_flow(job: PRJob, ctx: FlowContext, *, retry: bool = False) -> FlowState:
809
+ """새 검사를 처음부터 실행한다. 같은 커밋의 이전 체크포인트는 지운다 (/recheck 등).
810
+
811
+ retry는 같은 작업을 RQ가 다시 시도하는 것이다. 지난 시도가 전달(`deliver_*`)에서 실패해
812
+ 멈췄으면 처음부터 하지 않고 그 node부터 이어 간다 (5.6). 끝난 node는 다시 돌지 않으므로 모델
813
+ 호출 기록도 늘지 않는다.
814
+
815
+ 코멘트까지 가지 못했으면 stopped가 들어 있다. 승인 대기로 멈추면 commented만 있다.
816
+ """
817
+ with ctx.stack:
818
+ saver = open_checkpointer(ctx.data_dir, ctx.stack)
819
+ config = thread_config(job)
820
+ flow = build_graph(ctx, saver)
821
+ if retry and RESUMABLE & set(flow.get_state(config).next):
822
+ result = flow.invoke(None, config)
823
+ else:
824
+ saver.delete_thread(config["configurable"]["thread_id"])
825
+ result = flow.invoke({"job": job}, config)
826
+ if not result.get("commented"):
827
+ result.setdefault("stopped", "stale")
828
+ return result
829
+
830
+
831
+ def checked_values(job: PRJob, ctx: FlowContext) -> Mapping[str, Any]:
832
+ """이 커밋의 규칙 검사가 체크포인트에 남긴 상태(규칙 결과, 테스트 결과 등). 없으면 빈 dict.
833
+
834
+ 코멘트 수정(4.11)이 같은 커밋에서 이미 한 실행을 되풀이하지 않으려고 읽는다. 그래프를 돌리지
835
+ 않는다.
836
+ """
837
+ with ExitStack() as stack:
838
+ saver = open_checkpointer(ctx.data_dir, stack)
839
+ return dict(build_graph(ctx, saver).get_state(thread_config(job)).values)
840
+
841
+
842
+ def finished_values(job: PRJob, ctx: FlowContext) -> tuple[Mapping[str, Any], bool]:
843
+ """이 커밋의 체크포인트 상태와, 그래프가 멈춘 node 없이 코멘트까지 갔는지. 그래프를 돌리지
844
+ 않는다. 수정안을 머지한 커밋이 검증한 커밋의 결과를 옮겨 적을 때 읽는다 (`carry_flow`)."""
845
+ with ExitStack() as stack:
846
+ snapshot = build_graph(ctx, open_checkpointer(ctx.data_dir, stack)).get_state(
847
+ thread_config(job)
848
+ )
849
+ values = dict(snapshot.values)
850
+ return values, not snapshot.next and bool(values.get("commented"))
851
+
852
+
853
+ def carry_flow(job: PRJob, ctx: FlowContext, values: FlowState) -> FlowState:
854
+ """수정안을 머지한 커밋에 검증한 결과(values)를 옮겨 적는다. 규칙 검사, 테스트, 수정, 모델
855
+ 호출은 하지 않는다 (4.9 "수정안 PR 상태 관리").
856
+
857
+ 이 커밋의 체크포인트를 values로 채워 수정 판단이 끝난 것처럼 두고 코멘트 node만 돌린다. 그래서
858
+ 결과 코멘트는 보통의 검사와 같은 길로 그려지고, 이 커밋의 체크포인트(코멘트 수정이 읽는다)와
859
+ 위반 기록(다음 커밋의 "작성자가 고친 위반"이 읽는다)도 보통의 검사처럼 남는다. 체크아웃은 base
860
+ 설정과 위반 기록의 앞뒤 줄을 읽으려고 한다.
861
+ """
862
+ with ctx.stack:
863
+ saver = open_checkpointer(ctx.data_dir, ctx.stack)
864
+ config = thread_config(job)
865
+ flow = build_graph(ctx, saver)
866
+ saver.delete_thread(config["configurable"]["thread_id"])
867
+ _enter_checkout(ctx, job)
868
+ found = values["doc_rules"]
869
+ ctx.doc_rules = found
870
+ if isinstance(found, Found):
871
+ # 수정안이 고친 위반은 작성자가 아니라 수정안이 고친 것이다 (그 채택 기록은 수정안 쪽)
872
+ records.after_detect(
873
+ ctx.store, job, found, ctx.worktree, proposal.pipeline_secrets(), merged_fix=True
874
+ )
875
+ config = flow.update_state(config, {**values, "job": job}, as_node=DECIDE)
876
+ result = flow.invoke(None, config)
877
+ if not result.get("commented"):
878
+ result.setdefault("stopped", "stale")
879
+ return result
880
+
881
+
882
+ PendingFix = Literal["awaiting", "interrupted_fix", "rerun"]
883
+
884
+
885
+ def _awaiting_skills(value: object) -> list[str]:
886
+ if not isinstance(value, dict):
887
+ return []
888
+ if "skills" in value:
889
+ return list(value["skills"])
890
+ return [value["skill"]] if "skill" in value else [] # 2단계 전 체크포인트 ({"skill": "lint"})
891
+
892
+
893
+ def _rerun(values: Mapping[str, Any], bundle: str) -> bool:
894
+ """그 묶음에 `/fix`로 다시 돌릴 것이 있는지: 수정안을 내지 못하고 끝났다(검증 실패, 호출 상한
895
+ 등). 모델 묶음은 호출 상한에 걸려 정하지 못한 수정 판단도 다시 돌린다 (4.9 명령)."""
896
+ fix = values.get(STATE_KEYS[bundle][0])
897
+ failed = fix is not None and not fix.ready
898
+ if bundle != MODEL:
899
+ return failed
900
+ decided = values.get("fix_decisions")
901
+ capped = decided is not None and any(d.reason == "call_limit" for d in decided.decisions)
902
+ return (
903
+ capped
904
+ or failed
905
+ or doc_rules.judge_left(values.get("doc_rules"))
906
+ or pr_check_pure.judge_left(values.get("pr_checks"))
907
+ )
908
+
909
+
910
+ def pending_fix(job: PRJob, ctx: FlowContext, saver: SqliteSaver, bundle: str) -> PendingFix | None:
911
+ """이 커밋에 그 묶음의 재개할 수정이 있는지. 승인 대기 중이거나, 수정·전달 도중 실패해 다시
912
+ 시도할 수 있거나, 수정안을 내지 못하고 끝나 다시 돌릴 수 있다."""
913
+ snapshot = build_graph(ctx, saver).get_state(thread_config(job))
914
+ if AWAIT_FIX in snapshot.next and snapshot.interrupts:
915
+ if bundle in _awaiting_skills(snapshot.interrupts[0].value):
916
+ return "awaiting"
917
+ # 다른 묶음이 승인을 기다려도 이 묶음은 다시 돌릴 수 있다. 끝나면 다시 그 승인을 기다린다
918
+ return "rerun" if _rerun(snapshot.values, bundle) else None
919
+ if FIX_NODES[bundle] in snapshot.next or DELIVER_NODES[bundle] in snapshot.next:
920
+ return "interrupted_fix"
921
+ if snapshot.next:
922
+ return None
923
+ return "rerun" if _rerun(snapshot.values, bundle) else None
924
+
925
+
926
+ def pending_kind(job: PRJob, ctx: FlowContext, bundle: str) -> PendingFix | None:
927
+ with ExitStack() as stack:
928
+ return pending_fix(job, ctx, open_checkpointer(ctx.data_dir, stack), bundle)
929
+
930
+
931
+ def resume_fix(job: PRJob, ctx: FlowContext, approval: dict[str, Any]) -> FlowState | None:
932
+ """멈춰 있던 그래프를 approval["skill"] 묶음의 수정부터 이어서 실행한다. 없으면 None.
933
+
934
+ 수정안을 내지 못하고 끝난 수정(검증 실패 등)은 수정 판단부터 다시 돈다. 모델 묶음은 호출
935
+ 상한으로 정하지 못한 판단을 다시 묻고 새 시도 세대로 고친다. 테스트 결과와 다른 묶음의 결과는
936
+ 그대로 둔다.
937
+ """
938
+ bundle = approval["skill"]
939
+ with ctx.stack:
940
+ saver = open_checkpointer(ctx.data_dir, ctx.stack)
941
+ pending = pending_fix(job, ctx, saver, bundle)
942
+ if pending is None:
943
+ return None
944
+ graph = build_graph(ctx, saver)
945
+ config = thread_config(job)
946
+ if pending == "rerun":
947
+ result_key, requested_key = STATE_KEYS[bundle]
948
+ values = graph.get_state(config).values
949
+ # 호출 상한으로 남은 모델 판단이 있으면 모델 판단부터, PR 단위 판단만 남았으면 PR 단위
950
+ # 확인부터, 아니면 수정 판단부터 다시 돈다
951
+ after = TEST
952
+ if doc_rules.judge_left(values.get("doc_rules")):
953
+ after = DETECT
954
+ elif pr_check_pure.judge_left(values.get("pr_checks")):
955
+ after = JUDGE
956
+ config = graph.update_state(
957
+ config, {result_key: None, requested_key: True}, as_node=after
958
+ )
959
+ command = Command(resume=approval) if pending == "awaiting" else None
960
+ result = graph.invoke(command, config)
961
+ if ctx.store.is_stale(job):
962
+ result.setdefault("stopped", "stale")
963
+ return result