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,173 @@
1
+ """base 브랜치에서 대상 리포의 설정을 읽는다: `.pipeline.yaml`, ruff 설정, ruff 버전 고정
2
+ (docs/DESIGN.md 4.3 도구 설정, 4.4 도구 준비, 8.3, 10절).
3
+
4
+ PR head에서 바꾼 설정은 쓰지 않는다. 저장소 루트의 일반 파일만 읽는다: 심볼릭 링크(120000), 폴더,
5
+ 서브모듈인 설정은 읽지 않고 "설정:"에 알린다 (T24). ruff 설정 파일은 worktree에 꺼내지 않고 내용만
6
+ 들고 있다가 샌드박스의 ruff에 검사할 폴더 밖의 사본으로 넘긴다 (app/worker/lang/python.py).
7
+ """
8
+
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Final
12
+
13
+ from app.worker import repo
14
+ from app.worker.access_pure import AccessSettings, parse_access
15
+ from app.worker.repo_config_pure import (
16
+ LINT,
17
+ RepoConfig,
18
+ fix_limits,
19
+ memory_limit,
20
+ parse_repo_config,
21
+ settings_notes,
22
+ )
23
+ from app.worker.rule_reading_pure import REGULAR_FILE_MODES
24
+ from app.worker.sandbox import toolcache
25
+ from app.worker.tools_pure import (
26
+ CONFIG_RULE_ID,
27
+ REQUIREMENTS,
28
+ RUFF,
29
+ RUFF_CONFIG_FILES,
30
+ RuffConfig,
31
+ RuffSetup,
32
+ pinned_version,
33
+ ruff_config_name,
34
+ )
35
+
36
+ PIPELINE_YAML: Final = ".pipeline.yaml"
37
+ MAX_SETTINGS_BYTES: Final = 1024 * 1024
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class BaseConfig:
42
+ repo: RepoConfig # `fix`는 파이프라인 쪽 최댓값을 적용한 값이다
43
+ memory_gb: float # 파이프라인 상한을 적용한 실제 한도
44
+ max_memory_gb: float
45
+ ruff: RuffSetup # 이 저장소의 ruff 버전과 설정. 받는 것은 규칙이 ruff를 쓸 때뿐이다
46
+ problems: tuple[str, ...] = () # 읽지 못했거나 바꿔 읽은 설정. 코멘트의 "설정:"에 적는다
47
+
48
+
49
+ def _wanted(name: str) -> bool:
50
+ return name in (PIPELINE_YAML, *RUFF_CONFIG_FILES) or bool(REQUIREMENTS.match(name))
51
+
52
+
53
+ def _read_settings(
54
+ worktree: Path, base_sha: str
55
+ ) -> tuple[dict[str, str], dict[str, str], list[str]]:
56
+ """({이름: 내용}, {이름: blob 해시}, 문제). 일반 파일이 아니거나 너무 크거나 글이 아니면
57
+ 읽지 않는다."""
58
+ files: dict[str, str] = {}
59
+ blobs: dict[str, str] = {}
60
+ problems: list[str] = []
61
+ for name, entry in sorted(repo.base_root_entries(worktree, base_sha).items()):
62
+ if not _wanted(name):
63
+ continue
64
+ if entry.mode not in REGULAR_FILE_MODES or entry.size is None:
65
+ problems.append(f"`{name}`이 일반 파일이 아니라 읽지 않음 (심볼릭 링크, 폴더 등)")
66
+ continue
67
+ if entry.size > MAX_SETTINGS_BYTES:
68
+ problems.append(f"`{name}`이 {MAX_SETTINGS_BYTES // 1024}KB를 넘어 읽지 않음")
69
+ continue
70
+ try:
71
+ files[name] = repo.read_blob(worktree, entry.sha)
72
+ except UnicodeDecodeError:
73
+ problems.append(f"`{name}`이 UTF-8 글이 아니라 읽지 않음")
74
+ continue
75
+ blobs[name] = entry.sha
76
+ return files, blobs, problems
77
+
78
+
79
+ def load_access(
80
+ data_dir: Path, repo_name: str, base_sha: str, *, url: str | None = None
81
+ ) -> AccessSettings:
82
+ """외부 작성자 PR 가드레일의 `access` (8.6). PR의 코드를 체크아웃하기 전에 읽는다.
83
+
84
+ worktree를 만들지 않고 bare 캐시에서 base 커밋의 `.pipeline.yaml` blob만 읽는다. 일반 파일이
85
+ 아니거나 너무 크거나 글이 아니면 기본값이다. 문제는 검사가 돌 때 `load`가 "설정:"에 알린다.
86
+ git이 실패하면 GitError를 올려 실행하지 않는다.
87
+ """
88
+ text = _bare_settings(data_dir, repo_name, base_sha, url)
89
+ return parse_access(text)[0] if text is not None else AccessSettings()
90
+
91
+
92
+ def load_repo(
93
+ data_dir: Path, repo_name: str, base_sha: str, *, url: str | None = None
94
+ ) -> RepoConfig:
95
+ """코멘트 판단(4.11)이 체크아웃 전에 읽는 `.pipeline.yaml`. `load_access`와 같이 bare 캐시에서
96
+ 읽고, 읽지 못하면 기본값이다. `fix`에는 파이프라인 쪽 최댓값을 적용한다."""
97
+ config, _ = parse_repo_config(_bare_settings(data_dir, repo_name, base_sha, url))
98
+ return config.model_copy(update={"fix": fix_limits(config.fix)})
99
+
100
+
101
+ def _bare_settings(data_dir: Path, repo_name: str, base_sha: str, url: str | None) -> str | None:
102
+ """bare 캐시에서 base 커밋의 `.pipeline.yaml` 글. 일반 파일이 아니거나 너무 크거나 글이 아니면
103
+ None."""
104
+ bare = repo.ensure_bare(data_dir, repo_name, url)
105
+ repo.fetch_commit(bare, base_sha)
106
+ entry = repo.bare_entries(bare, base_sha, [PIPELINE_YAML]).get(PIPELINE_YAML)
107
+ if (
108
+ entry is None
109
+ or entry.mode not in REGULAR_FILE_MODES
110
+ or entry.size is None
111
+ or entry.size > MAX_SETTINGS_BYTES
112
+ ):
113
+ return None
114
+ try:
115
+ return repo.bare_blob(bare, entry.sha)
116
+ except UnicodeDecodeError:
117
+ return None
118
+
119
+
120
+ def load(worktree: Path, base_sha: str, max_memory_gb: float) -> BaseConfig:
121
+ files, blobs, problems = _read_settings(worktree, base_sha)
122
+
123
+ repo_config, problem = parse_repo_config(files.get(PIPELINE_YAML))
124
+ if problem:
125
+ problems.append(f"`{PIPELINE_YAML}`을 읽지 못해 기본값을 씀: {problem}")
126
+ problems += settings_notes(files.get(PIPELINE_YAML))
127
+ problems += parse_access(files.get(PIPELINE_YAML))[1]
128
+ fix = fix_limits(repo_config.fix)
129
+ if fix != repo_config.fix:
130
+ problems.append(
131
+ f"`fix.max_retries` {repo_config.fix.max_retries}는 파이프라인 최댓값 "
132
+ f"{fix.max_retries}로 줄였습니다"
133
+ )
134
+ repo_config = repo_config.model_copy(update={"fix": fix})
135
+ repo_config = _legacy_lint_off(repo_config, problems)
136
+
137
+ name, problem = ruff_config_name(files)
138
+ if problem:
139
+ problems.append(problem)
140
+ config = RuffConfig(name, files[name], blobs[name]) if name is not None else None
141
+ pinned = pinned_version(files)
142
+ version, pinned_by = pinned if pinned else (toolcache.TOOLS[RUFF].default, "")
143
+ ruff = RuffSetup(
144
+ version=version, pinned_by=pinned_by, config=config,
145
+ available=toolcache.is_known(RUFF, version),
146
+ ) # fmt: skip
147
+ if not ruff.available:
148
+ problems.append(
149
+ f"{ruff.label}은 파이프라인이 해시를 고정한 버전이 아니라 받지 않습니다. ruff를 쓰는 "
150
+ "규칙은 검사하지 못합니다"
151
+ )
152
+
153
+ return BaseConfig(
154
+ repo=repo_config,
155
+ memory_gb=memory_limit(repo_config.sandbox.memory_gb, max_memory_gb),
156
+ max_memory_gb=max_memory_gb,
157
+ ruff=ruff,
158
+ problems=tuple(problems),
159
+ )
160
+
161
+
162
+ def _legacy_lint_off(config: RepoConfig, problems: list[str]) -> RepoConfig:
163
+ """v1의 `skills.enabled`에서 lint를 뺀 저장소는 ruff를 끈 뜻이었다. 도구 설정의 규칙 묶음을
164
+ `rules.disabled`로 끄고 새 키를 알린다 (10절). 키가 없으면 아무것도 하지 않는다."""
165
+ enabled = config.skills.enabled
166
+ if enabled is None or LINT in enabled or CONFIG_RULE_ID in config.rules.disabled:
167
+ return config
168
+ problems.append(
169
+ f"`skills.enabled`에 `lint`가 없어 도구 설정의 ruff 규칙(`{CONFIG_RULE_ID}`)을 끕니다. "
170
+ f"`skills`는 없어졌으니 `rules.disabled: [{CONFIG_RULE_ID}]`로 바꿔 주세요"
171
+ )
172
+ rules = config.rules.model_copy(update={"disabled": [*config.rules.disabled, CONFIG_RULE_ID]})
173
+ return config.model_copy(update={"rules": rules})
@@ -0,0 +1,100 @@
1
+ """모델 호출 수 상한을 `ai_calls`에 묶는다 (docs/DESIGN.md 9.2). 판단은
2
+ app/worker/call_budget_pure.py.
3
+
4
+ 호출은 시작할 때 센 값과 함께 한 줄을 쓰고(`begin`), 끝나면 결과를 채운다(`finish`). 워커가
5
+ 호출 도중 죽어도 그 호출은 상한에서 센다. 저장된 결과를 쓴 것은 0으로 한 줄 남긴다(`record_hit`).
6
+ """
7
+
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass, replace
10
+ from datetime import UTC, datetime
11
+
12
+ from app.shared.db_pure import ModelCall
13
+ from app.worker.call_budget_pure import (
14
+ DAILY_WINDOW,
15
+ Allowed,
16
+ Denied,
17
+ RulesetScope,
18
+ Scope,
19
+ Stage,
20
+ Tier,
21
+ decide,
22
+ limits_for,
23
+ )
24
+ from app.worker.repo_config_pure import CallSettings
25
+ from app.worker.state import Store
26
+
27
+
28
+ def _utc_now() -> datetime:
29
+ return datetime.now(UTC)
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class CallBudget:
34
+ """한 작업(PR의 한 커밋)이 쓰는 호출 상한. settings는 파이프라인 최댓값으로 줄인 값이다."""
35
+
36
+ store: Store
37
+ repo: str
38
+ pr_number: int
39
+ head_sha: str
40
+ settings: CallSettings
41
+ now: Callable[[], datetime] = _utc_now
42
+ # 대상 위반 수 (9.2): 이 검사에서 찾은 위반 중 수정 판단의 표가 skip으로 정하지 않은 것. PR
43
+ # 상한이 이만큼 는다. 부르는 쪽이 아는 만큼 `with_targets`로 넘긴다
44
+ targets: int = 0
45
+
46
+ def with_targets(self, targets: int) -> "CallBudget":
47
+ return replace(self, targets=targets)
48
+
49
+ def decide(self, scope: Scope, tier: Tier) -> Allowed | Denied:
50
+ since = self.now().astimezone(UTC) - DAILY_WINDOW
51
+ spent = self.store.calls_spent(self.repo, self.pr_number, scope, since)
52
+ grants = self.store.call_grants(self.repo, self.pr_number)
53
+ return decide(limits_for(self.settings, scope, grants, self.targets), spent, tier)
54
+
55
+ def may_call(self, scope: Scope) -> Callable[[Tier], bool]:
56
+ """app/worker/loop.py의 `LoopPolicy.may_call`에 넘긴다."""
57
+ return lambda tier: isinstance(self.decide(scope, tier), Allowed)
58
+
59
+ def begin(
60
+ self, scope: Scope, *, stage: Stage, tier: Tier, model: str, attempt: int = 1
61
+ ) -> int | Denied:
62
+ """상한 안이면 호출 한 줄을 쓰고 그 id를, 아니면 Denied를 돌려준다."""
63
+ verdict = self.decide(scope, tier)
64
+ if isinstance(verdict, Denied):
65
+ return verdict
66
+ return self.store.add_model_call(
67
+ self._row(scope, stage=stage, tier=tier, model=model, attempt=attempt,
68
+ counted=verdict.cost)
69
+ ) # fmt: skip
70
+
71
+ def finish(
72
+ self,
73
+ call_id: int,
74
+ *,
75
+ ok: bool,
76
+ error: str | None = None,
77
+ model_id: str = "",
78
+ input_tokens: int | None = None,
79
+ output_tokens: int | None = None,
80
+ permission_denials: int = 0,
81
+ ) -> None:
82
+ self.store.finish_model_call(
83
+ call_id, ok=ok, error=error, model_id=model_id, input_tokens=input_tokens,
84
+ output_tokens=output_tokens, permission_denials=permission_denials,
85
+ ) # fmt: skip
86
+
87
+ def record_hit(self, scope: Scope, *, stage: Stage, tier: Tier, model: str) -> None:
88
+ """저장된 결과를 썼다. 상한에서는 0으로 센다."""
89
+ row = self._row(scope, stage=stage, tier=tier, model=model, attempt=1, counted=0)
90
+ row.cache_hit, row.ok = True, True
91
+ self.store.add_model_call(row)
92
+
93
+ def _row(
94
+ self, scope: Scope, *, stage: Stage, tier: Tier, model: str, attempt: int, counted: int
95
+ ) -> ModelCall:
96
+ return ModelCall(
97
+ repo=self.repo, pr_number=self.pr_number, head_sha=self.head_sha, stage=stage,
98
+ ruleset_key=scope.key if isinstance(scope, RulesetScope) else None, model=model,
99
+ tier=tier, attempt=attempt, counted=counted, created_at=self.now().astimezone(UTC),
100
+ ) # fmt: skip
@@ -0,0 +1,34 @@
1
+ """모델 결과 캐시의 키 (docs/DESIGN.md 5.6, 9.1). 계산만 한다.
2
+
3
+ 키는 단계, 모델, 프롬프트 버전, 그리고 단계마다 다른 입력 부분(원천 blob 해시, 규칙 원문 해시,
4
+ hunk 해시 등)의 해시다. 어느 하나가 바뀌면 키가 달라져 모델에 다시 묻는다.
5
+ """
6
+
7
+ import hashlib
8
+ import json
9
+ from collections.abc import Mapping, Sequence
10
+
11
+ Part = str | int | Sequence[str] | Sequence[Sequence[str]]
12
+
13
+
14
+ def text_hash(text: str) -> str:
15
+ return hashlib.sha256(text.encode()).hexdigest()
16
+
17
+
18
+ def model_cache_key(stage: str, model: str, prompt_version: str, parts: Mapping[str, Part]) -> str:
19
+ """parts의 이름 순서는 키에 영향을 주지 않고, 목록 안의 순서는 영향을 준다.
20
+
21
+ 단계·모델·프롬프트 버전이 비었으면 ValueError (빈 값끼리 같은 키가 되지 않게).
22
+ """
23
+ for name, value in (("stage", stage), ("model", model), ("prompt_version", prompt_version)):
24
+ if not value:
25
+ raise ValueError(f"캐시 키의 {name}이 비어 있다")
26
+ payload = {
27
+ "stage": stage,
28
+ "model": model,
29
+ "prompt_version": prompt_version,
30
+ "parts": dict(parts),
31
+ }
32
+ # JSON으로 묶어 값의 경계가 섞이지 않게 한다 ("ab"+"c"와 "a"+"bc"가 다른 키)
33
+ encoded = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
34
+ return text_hash(encoded)
@@ -0,0 +1,132 @@
1
+ """모델 호출 수 상한 (docs/DESIGN.md 9.2, 9.3). 판단만 한다. 세고 기록하는 것은
2
+ app/worker/budget.py.
3
+
4
+ 상한은 셋이다. PR 상한(그 PR의 모든 커밋 누적), 규칙 묶음 상한(규칙 읽기와 검사기 작성, 그 묶음의
5
+ 캐시 키 단위), 저장소 하루 상한(그 저장소의 모든 호출, 최근 24시간). 무거운 모델 호출은 3으로,
6
+ 저장된 결과를 쓴 것은 0으로 센다.
7
+
8
+ PR 상한은 `pr_base` + 대상 위반 수 × `per_violation`이고 `pr_max`에서 멈춘다. `/fix`로 다시 돌릴
9
+ 때마다 `pr_max`를 한 번 더 받는다 (9.2 "걸렸을 때"). 저장소 하루 상한은 그대로다.
10
+ """
11
+
12
+ from collections.abc import Mapping
13
+ from dataclasses import dataclass
14
+ from datetime import timedelta
15
+ from typing import Final, Literal
16
+
17
+ from app.worker.repo_config_pure import CallSettings
18
+
19
+ Tier = Literal["light", "heavy"]
20
+ # ai_calls의 단계 (7.8). 규칙 읽기, 검사기 작성, PR 패턴 작성(pr_plan)은 규칙 묶음 상한에서,
21
+ # 나머지는 PR 상한에서 센다. pr_judge는 PR 단위 확인의 모델 판단(4.5 끝), run_judge는 실행 결과의
22
+ # 규칙의 모델 판단이다 (4.5). feedback은 PR 코멘트의 판단이다 (4.11). pr_description은 PR 설명과
23
+ # diff 견주기다 (4.5 끝)
24
+ Stage = Literal[
25
+ "rules", "checker", "pr_plan", "judge", "pr_judge", "run_judge", "decide", "fix", "feedback",
26
+ "pr_description",
27
+ ] # fmt: skip
28
+ Cap = Literal["pr", "ruleset", "repo_daily"]
29
+
30
+ TIER_COST: Final[Mapping[str, int]] = {"light": 1, "heavy": 3}
31
+ # 호출 하나의 claude `--max-budget-usd` (9.2 "호출 하나"). 호출 하나가 끝없이 도는 것을 막을 뿐
32
+ # 상한 계산에는 쓰지 않는다
33
+ CALL_BUDGET_USD: Final[Mapping[str, float]] = {"light": 0.30, "heavy": 0.50}
34
+ DAILY_WINDOW: Final = timedelta(hours=24)
35
+ # 이만큼 쓴 상한에서는 무거운 모델로 올리지 않는다 (9.3). 가벼운 모델은 상한까지 쓴다
36
+ HEAVY_STOP_RATIO: Final = 0.8
37
+ CAP_LABEL: Final[Mapping[str, str]] = {
38
+ "pr": "PR 상한",
39
+ "ruleset": "규칙 묶음 상한",
40
+ "repo_daily": "저장소 하루 상한",
41
+ }
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class PrScope:
46
+ """PR 상한에서 세는 호출. 어느 PR인지는 호출을 세는 쪽(app/worker/budget.py)이 안다."""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class RulesetScope:
51
+ """규칙 묶음 상한에서 세는 호출. rule_count는 지금까지 읽은 규칙 수(규칙을 읽기 전이면 0)."""
52
+
53
+ key: str
54
+ rule_count: int = 0
55
+
56
+
57
+ Scope = PrScope | RulesetScope
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class CallLimits:
62
+ scope_cap: Cap # "pr" 또는 "ruleset"
63
+ scope: int # 그 상한의 값
64
+ repo_daily: int
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Spent:
69
+ """지금까지 센 값. scope는 그 PR(전체 기간) 또는 규칙 묶음(최근 24시간)에서, repo_daily는 최근
70
+ 24시간 저장소에서."""
71
+
72
+ scope: int
73
+ repo_daily: int
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Allowed:
78
+ cost: int # 이 호출이 상한에서 차지하는 값
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Denied:
83
+ cap: Cap
84
+ used: int
85
+ limit: int
86
+ cost: int
87
+ # 상한에는 여유가 있지만 80%를 넘겨 무거운 모델로 올리지 않는 경우. 가벼운 모델은 부를 수 있다
88
+ escalation: bool = False
89
+
90
+ @property
91
+ def reason(self) -> str:
92
+ label = CAP_LABEL[self.cap]
93
+ if self.escalation:
94
+ return f"{label}의 80%를 써서 무거운 모델로 올리지 않음 ({self.used}/{self.limit}회)"
95
+ return f"호출 상한: {label} ({self.used}/{self.limit}회 사용, 이 호출 {self.cost}회)"
96
+
97
+
98
+ def limits_for(
99
+ settings: CallSettings, scope: Scope, pr_grants: int = 0, targets: int = 0
100
+ ) -> CallLimits:
101
+ """pr_grants는 그 PR에 `/fix`가 PR 상한을 더 준 횟수, targets는 대상 위반 수다 (9.2). 둘 다 규칙
102
+ 묶음 상한에는 쓰지 않는다.
103
+
104
+ `/fix`가 더 준 몫은 `pr_max`씩이다: `min(pr_base + targets × per_violation, pr_max)`에
105
+ `pr_max × pr_grants`를 더한다.
106
+ """
107
+ if isinstance(scope, RulesetScope):
108
+ if scope.rule_count < 0:
109
+ raise ValueError(f"규칙 수가 음수다: {scope.rule_count}")
110
+ cap = settings.ruleset_base + scope.rule_count * settings.per_rule
111
+ return CallLimits("ruleset", min(cap, settings.ruleset_max), settings.repo_daily)
112
+ if pr_grants < 0:
113
+ raise ValueError(f"상한을 더 준 횟수가 음수다: {pr_grants}")
114
+ if targets < 0:
115
+ raise ValueError(f"대상 위반 수가 음수다: {targets}")
116
+ cap = min(settings.pr_base + targets * settings.per_violation, settings.pr_max)
117
+ return CallLimits("pr", cap + settings.pr_max * pr_grants, settings.repo_daily)
118
+
119
+
120
+ def decide(limits: CallLimits, spent: Spent, tier: Tier) -> Allowed | Denied:
121
+ """이 단계의 모델을 한 번 더 불러도 되는지. 쓴 뒤의 합이 상한과 같으면 허용, 넘으면 거부.
122
+
123
+ 둘 다 걸리면 저장소 하루 상한을 알린다. 모델을 쓰는 단계를 모두 멈추는 쪽이다.
124
+ """
125
+ cost = TIER_COST[tier]
126
+ if spent.repo_daily + cost > limits.repo_daily:
127
+ return Denied("repo_daily", spent.repo_daily, limits.repo_daily, cost)
128
+ if spent.scope + cost > limits.scope:
129
+ return Denied(limits.scope_cap, spent.scope, limits.scope, cost)
130
+ if tier == "heavy" and spent.scope >= limits.scope * HEAVY_STOP_RATIO:
131
+ return Denied(limits.scope_cap, spent.scope, limits.scope, cost, escalation=True)
132
+ return Allowed(cost)