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,154 @@
1
+ """위반 찾기 (docs/DESIGN.md 4.5 도구와 검사기): 채택한 도구와 검사기를 PR이 바꾼 파일에 돌린다.
2
+
3
+ 도구와 검사기는 적용 범위에 드는 바뀐 Python 파일 전체를 검사하고, 잡힌 범위가 PR이 바꾼 줄에 걸린
4
+ 것만 위반으로 남긴다. 기존 코드의 위반은 PR 작성자의 책임이 아니다. 위반 id는 줄 번호가 아니라
5
+ (규칙, 줄 내용, 그 파일에서 같은 내용의 몇 번째인지)로 정해, 위쪽에 줄이 더해져도 같다.
6
+
7
+ 도구 설정에서 온 규칙 묶음(ruff 설정)의 위반은 ruff의 코드를 규칙 id로 갖는다 (4.3). 문서
8
+ 규칙이 같은 ruff 코드로 같은 줄을 잡으면 문서 규칙의 위반만 남긴다(출처가 문서로 보인다).
9
+ `rules.disabled`에 적은 ruff 코드의 위반은 남기지 않는다.
10
+ """
11
+
12
+ from collections.abc import Collection, Mapping, Sequence
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+ from typing import Final
16
+
17
+ from app.worker import repo
18
+ from app.worker.checker_authoring_pure import Checked, RuleCheck, Unchecked
19
+ from app.worker.checker_pure import TOOL_KINDS
20
+ from app.worker.diff_pure import ChangedLines, touches
21
+ from app.worker.rule_pure import checked_file, looks_at_paths
22
+ from app.worker.rules.checkers import RunsCheckers, Sandbox
23
+ from app.worker.sandbox import toolcache
24
+ from app.worker.sandbox.checker_runner import Failed, Invalid, Match
25
+ from app.worker.sandbox.safe_read import read_regular_file
26
+ from app.worker.text_edit_pure import TextEdit
27
+ from app.worker.violation_pure import Violation, violation_id
28
+
29
+ MAX_SOURCE_BYTES: Final = 5 * 1024 * 1024
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Detection:
34
+ violations: tuple[Violation, ...]
35
+ # 검사기가 있지만 이 PR에서 돌리지 못한 규칙 (kind "run_failed", "tool_unavailable")
36
+ unchecked: tuple[Unchecked, ...] = ()
37
+ # 위반 id → ruff의 안전한 수정. 기계적 수정이 쓴다 (상태에는 넣지 않는다)
38
+ edits: Mapping[str, tuple[TextEdit, ...]] = field(default_factory=dict)
39
+
40
+
41
+ def detect(
42
+ checks: Sequence[RuleCheck],
43
+ worktree: Path,
44
+ changed: ChangedLines,
45
+ *,
46
+ new_files: frozenset[str] = frozenset(),
47
+ sandbox: RunsCheckers | None = None,
48
+ disabled: Collection[str] = (),
49
+ ) -> Detection:
50
+ """checks 중 검사기가 있는 규칙(`Checked`)을 돌린다. changed는 merge-base 기준 바뀐 줄이다.
51
+
52
+ 경로 규칙은 PR이 새로 만든 파일(new_files)의 경로만 보고, 위반은 파일 단위다. disabled는
53
+ `rules.disabled`다 (도구 설정 규칙의 ruff 코드를 끈다).
54
+
55
+ docker 자체가 실패하면 SandboxError를 올린다 (환경 오류).
56
+ """
57
+ sandbox = sandbox or Sandbox()
58
+ violations: list[Violation] = []
59
+ unchecked: list[Unchecked] = []
60
+ edits: dict[str, tuple[TextEdit, ...]] = {}
61
+ for check in checks:
62
+ if not isinstance(check, Checked):
63
+ continue
64
+ rule, checker = check.rule, check.checker
65
+ by_path = looks_at_paths(rule)
66
+ files = [
67
+ f for f in sorted(new_files if by_path else changed)
68
+ if checked_file(rule, f) and repo.worktree_file(worktree, f) is not None
69
+ ] # fmt: skip
70
+ if not files:
71
+ continue
72
+ try:
73
+ run = sandbox.on_files(checker.kind, checker.body, worktree, files)
74
+ except toolcache.ToolUnavailable as e:
75
+ unchecked.append(Unchecked(rule, "tool_unavailable", f"도구를 준비하지 못함: {e}"))
76
+ continue
77
+ if isinstance(run, Invalid | Failed):
78
+ unchecked.append(Unchecked(rule, "run_failed", f"검사기를 돌리지 못함: {run.reason}"))
79
+ continue
80
+ if by_path:
81
+ violations += _file_violations(check, run.matches)
82
+ else:
83
+ violations += _violations(check, run.matches, worktree, changed, edits)
84
+ kept = _without_repeats([v for v in violations if v.rule_id not in disabled])
85
+ return Detection(
86
+ tuple(kept), tuple(unchecked), {v.id: edits[v.id] for v in kept if v.id in edits}
87
+ )
88
+
89
+
90
+ def _without_repeats(violations: Sequence[Violation]) -> list[Violation]:
91
+ """문서 규칙이 같은 ruff 코드로 같은 줄을 잡았으면 도구 설정 규칙의 위반을 뺀다."""
92
+ by_document = {(v.file, v.line, v.code) for v in violations if v.code and v.rule_id != v.code}
93
+ return [v for v in violations if v.rule_id != v.code or (v.file, v.line, v.code)
94
+ not in by_document] # fmt: skip
95
+
96
+
97
+ def _file_violations(check: Checked, matches: Sequence[Match]) -> list[Violation]:
98
+ """파일 단위 위반. 파일마다 하나다. id는 경로로 정한다 (줄 내용이 없다)."""
99
+ return [
100
+ Violation(
101
+ id=violation_id(check.rule.id, file, "", 0), rule_id=check.rule.id, file=file,
102
+ line=0, message=message or check.rule.text, found_by="checker", unit="file",
103
+ )
104
+ for file, message in sorted({m.file: m.message for m in matches}.items())
105
+ ] # fmt: skip
106
+
107
+
108
+ def _violations(
109
+ check: Checked,
110
+ matches: Sequence[Match],
111
+ worktree: Path,
112
+ changed: ChangedLines,
113
+ edits: dict[str, tuple[TextEdit, ...]],
114
+ ) -> list[Violation]:
115
+ """바뀐 줄에 걸린 것만 남긴다. 안전한 수정이 있는 도구 위반은 그 편집을 edits에 넣는다.
116
+
117
+ 같은 줄 내용의 몇 번째인지는 바뀌지 않은 줄의 것까지 파일 순서로 규칙마다 센다.
118
+ """
119
+ result: list[Violation] = []
120
+ lines_by_file: dict[str, list[str]] = {}
121
+ seen: dict[tuple[str, str, str], int] = {}
122
+ tool = check.checker.kind in TOOL_KINDS
123
+ by_code = check.rule.origin == "tool_config"
124
+ for match in sorted(matches, key=lambda m: (m.file, m.line, m.end_line)):
125
+ if match.file not in lines_by_file:
126
+ lines_by_file[match.file] = source_lines(worktree, match.file)
127
+ lines = lines_by_file[match.file]
128
+ if match.line > len(lines):
129
+ continue # 검사한 뒤 파일이 바뀌었거나 출력이 틀림. 존재하는 줄만 받는다 (4.5)
130
+ line_text = lines[match.line - 1].strip()
131
+ rule_id = match.code if by_code and match.code else check.rule.id
132
+ occurrence = seen.get((rule_id, match.file, line_text), 0)
133
+ seen[(rule_id, match.file, line_text)] = occurrence + 1
134
+ if not touches(changed, match.file, match.line, match.end_line):
135
+ continue
136
+ violation = Violation(
137
+ id=violation_id(rule_id, match.file, line_text, occurrence), rule_id=rule_id,
138
+ file=match.file, line=match.line, message=match.message or check.rule.text,
139
+ found_by="tool" if tool else "checker", code=match.code, line_text=line_text,
140
+ mechanical_fix=bool(match.edits) or check.checker.kind == "ruff-format",
141
+ ) # fmt: skip
142
+ if match.edits:
143
+ edits[violation.id] = match.edits
144
+ result.append(violation)
145
+ return result
146
+
147
+
148
+ def source_lines(worktree: Path, rel: str) -> list[str]:
149
+ """ast-grep과 같이 `\\n`으로만 줄을 나눈다. 읽을 수 없으면 빈 목록 (그 파일의 위반은 버린다)."""
150
+ path = repo.worktree_file(worktree, rel)
151
+ data = read_regular_file(path, max_bytes=MAX_SOURCE_BYTES) if path is not None else None
152
+ if data is None:
153
+ return []
154
+ return data.decode("utf-8", errors="replace").split("\n")
@@ -0,0 +1,301 @@
1
+ """규칙 경로 (docs/DESIGN.md 5.1): 규칙 읽기 → 검사 방법 정하기(도구, 검사기 작성) → 위반 찾기.
2
+
3
+ 규칙은 base의 문서(모델이 읽음)와 도구 설정(ruff 설정, 결정적으로 읽음)에서 나온다. 둘 다 없으면
4
+ 규칙 검사를 하지 않는다 (2.2). 찾기만 한다(수정은 app/worker/fix/mechanical_fix.py,
5
+ app/worker/fix/model_fix.py). 이 경로의 실패(모델 호출 실패, 호출 상한, 도구 준비 실패, 샌드박스
6
+ 오류)는 작업을 실패시키지 않고 `NotRun`이나 규칙별 "검사하지 못함"으로 남는다. 규칙 문서를 읽지
7
+ 못해도 도구 설정의 규칙은 검사한다 (4.3 "실패 시"). 테스트 결과는 그대로 나온다.
8
+ """
9
+
10
+ import logging
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass, replace
13
+ from pathlib import Path
14
+
15
+ from app.worker import repo
16
+ from app.worker.budget import CallBudget
17
+ from app.worker.call_budget_pure import RulesetScope, limits_for
18
+ from app.worker.checker_authoring_pure import (
19
+ Checked,
20
+ RuleCheck,
21
+ ToJudge,
22
+ Unchecked,
23
+ checker_from_json,
24
+ checker_key,
25
+ )
26
+ from app.worker.checker_pure import TOOL_KINDS, Checker, tool_codes
27
+ from app.worker.diff_pure import added_lines, new_files
28
+ from app.worker.doc_rules_pure import (
29
+ CheckerRef,
30
+ DocRules,
31
+ Found,
32
+ NoRuleDocs,
33
+ NoRulesFound,
34
+ NotRun,
35
+ RuleChecked,
36
+ RuleJudged,
37
+ RuleOutcome,
38
+ RulesRead,
39
+ RuleUnchecked,
40
+ call_usage,
41
+ with_run_failures,
42
+ )
43
+ from app.worker.memory import FindsRecords
44
+ from app.worker.rag_pure import Retrieval, merge_retrievals
45
+ from app.worker.repo import GitError
46
+ from app.worker.repo_config_pure import ModelSettings, RulesSettings
47
+ from app.worker.rule_pure import checked_exclude
48
+ from app.worker.rule_reading_pure import apply_disabled
49
+ from app.worker.rules import checkers, detect, rules
50
+ from app.worker.rules import judge as model_judge
51
+ from app.worker.rules.tool_choice_pure import choice_key
52
+ from app.worker.sandbox import docker_cli
53
+ from app.worker.sandbox.docker_cli import SandboxError
54
+ from app.worker.state import Store
55
+ from app.worker.tools_pure import RuffSetup, config_rule
56
+
57
+ log = logging.getLogger(__name__)
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Runtime:
62
+ store: Store
63
+ budget: CallBudget
64
+ models: ModelSettings
65
+ ask: rules.AskModel
66
+ sandbox: checkers.FormatsFiles
67
+ ruff: RuffSetup | None = None # 이 저장소의 ruff (base 설정, 버전)
68
+ disabled: frozenset[str] = frozenset() # `rules.disabled`. 도구 설정 규칙의 ruff 코드를 끈다
69
+ retriever: FindsRecords | None = None # `rag.enabled`일 때만 (6.2)
70
+ secrets: tuple[str, ...] = () # 기록을 저장하기 전에 찾는 파이프라인 비밀값 (6.5)
71
+
72
+
73
+ def read(
74
+ worktree: Path, base_sha: str, settings: RulesSettings, rt: Runtime, changes_diff: bytes = b""
75
+ ) -> RulesRead | DocRules:
76
+ """base의 규칙 문서와 도구 설정을 읽는다. 검사할 규칙이 있으면 RulesRead, 없으면 끝난 결과.
77
+
78
+ changes_diff(PR의 diff)는 규칙 문서가 400KB를 넘는 저장소에서 관련 절을 찾는 데 쓴다 (6.3).
79
+ """
80
+ configured = (config_rule(rt.ruff.config),) if rt.ruff and rt.ruff.config else ()
81
+ tool_rules = apply_disabled(configured, settings.disabled)
82
+ docs = _read_documents(worktree, base_sha, settings, rt, changes_diff)
83
+ if isinstance(docs, RulesRead):
84
+ return replace(docs, rules=(*docs.rules, *tool_rules),
85
+ disabled=docs.disabled + len(configured) - len(tool_rules)) # fmt: skip
86
+ if not tool_rules:
87
+ return docs
88
+ note = docs.reason if isinstance(docs, NotRun) else ""
89
+ return RulesRead("", tool_rules, disabled=0, note=note)
90
+
91
+
92
+ def _read_documents(
93
+ worktree: Path, base_sha: str, settings: RulesSettings, rt: Runtime, changes_diff: bytes
94
+ ) -> RulesRead | DocRules:
95
+ """규칙 문서를 모델로 읽는다. 규칙이 있으면 RulesRead, 없거나 못 읽었으면 끝난 결과."""
96
+ try:
97
+ result = rules.load_rules(
98
+ worktree, base_sha, settings, model=rt.models.rules, store=rt.store,
99
+ budget=rt.budget, ask=rt.ask, sections=rt.retriever, changes_diff=changes_diff,
100
+ ) # fmt: skip
101
+ except GitError as e:
102
+ log.warning("규칙 문서를 읽지 못함: %s", e)
103
+ return NotRun(f"base의 규칙 문서를 읽지 못함: {_first_line(str(e))}")
104
+ match result:
105
+ case rules.RulesFound(key=key, ruleset=ruleset, rules=found, sections=read_sections):
106
+ if any(r.exclude for r in found):
107
+ # 범위 추정의 효과 확인. 규칙 묶음은 저장된 것이어도 이 PR의 base 목록으로 매번 본다
108
+ try:
109
+ base_files = repo.list_base_files(worktree, base_sha)
110
+ except GitError as e:
111
+ log.warning("base의 파일 목록을 읽지 못함: %s", e)
112
+ return NotRun(f"base의 파일 목록을 읽지 못함: {_first_line(str(e))}")
113
+ found = tuple(checked_exclude(r, base_files) for r in found)
114
+ return RulesRead(key, found, disabled=len(ruleset.rules) - len(found),
115
+ sections=read_sections) # fmt: skip
116
+ case rules.NoRuleDocuments(unread=unread):
117
+ return NoRuleDocs(unread)
118
+ case rules.NoRules(ruleset=ruleset):
119
+ return NoRulesFound(dropped=len(ruleset.dropped))
120
+ case rules.ModelFailed(reason=reason):
121
+ return NotRun(f"규칙 읽기의 모델 호출이 실패함: {_first_line(reason)}")
122
+ case rules.CapReached(denied=denied):
123
+ return NotRun(f"규칙을 읽지 않음: {denied.reason}")
124
+
125
+
126
+ def author(
127
+ read: RulesRead,
128
+ rt: Runtime,
129
+ *,
130
+ is_stale: Callable[[], bool] = lambda: False,
131
+ on_retrieval: Callable[[Retrieval], None] = lambda r: None,
132
+ ) -> tuple[RuleOutcome, ...] | NotRun:
133
+ """규칙마다 검사기를 작성하거나 저장한 것을 찾는다. 검색으로 넣은 검사기 기록은
134
+ on_retrieval로 알린다."""
135
+ try:
136
+ checks = checkers.plan_and_author(
137
+ read.rules, ruleset_key=read.key, store=rt.store, budget=rt.budget,
138
+ models=rt.models, ask=rt.ask, sandbox=rt.sandbox, ruff=rt.ruff, is_stale=is_stale,
139
+ retriever=rt.retriever, on_retrieval=on_retrieval, secrets=rt.secrets,
140
+ ) # fmt: skip
141
+ except SandboxError as e:
142
+ log.warning("검사기 확인 샌드박스 실패: %s", e)
143
+ return NotRun(f"검사기를 확인하는 샌드박스가 실패함: {_first_line(str(e))}")
144
+ return tuple(_outcome(c, rt.models, rt.ruff) for c in checks)
145
+
146
+
147
+ def _outcome(check: RuleCheck, models: ModelSettings, ruff: RuffSetup | None) -> RuleOutcome:
148
+ if isinstance(check, ToJudge):
149
+ # 검사기를 채택하지 않은 내용 규칙은 모델이 hunk를 직접 본다 (4.4의 3번). 경로 규칙은 오지
150
+ # 않는다 (app/worker/rules/checkers.py)
151
+ return RuleJudged(check.rule, check.detail, check.route)
152
+ if isinstance(check, Unchecked):
153
+ return RuleUnchecked(check.rule, check.kind, check.detail)
154
+ key = _saved_key(check, models, ruff)
155
+ codes = tool_codes(check.checker.body) if check.checker.kind == "ruff" else ()
156
+ ref = CheckerRef(key=key, id=check.checker.id, kind=check.checker.kind, cached=check.cached,
157
+ codes=codes) # fmt: skip
158
+ return RuleChecked(check.rule, ref)
159
+
160
+
161
+ def _saved_key(check: Checked, models: ModelSettings, ruff: RuffSetup | None) -> str:
162
+ """채택한 확인 방법을 저장한 `checkers`의 키: 도구 설정, 도구 선택, 또는 검사기 작성."""
163
+ if check.rule.origin == "tool_config" and ruff is not None:
164
+ return checkers.config_key(check.rule, ruff)
165
+ if check.checker.kind in TOOL_KINDS and ruff is not None:
166
+ return choice_key(check.rule, models.checker, ruff.version)
167
+ return checker_key(check.rule, models.checker)
168
+
169
+
170
+ def find(
171
+ read: RulesRead,
172
+ outcomes: tuple[RuleOutcome, ...],
173
+ worktree: Path,
174
+ changes_diff: bytes,
175
+ rt: Runtime,
176
+ *,
177
+ since_call: int,
178
+ retrievals: tuple[Retrieval, ...] = (),
179
+ ) -> Found | NotRun:
180
+ """채택한 검사기를 PR이 바꾼 파일에 돌려 바뀐 줄의 위반만 남긴다.
181
+
182
+ since_call은 이 검사를 시작하기 전 마지막 호출 기록의 id다. 그 뒤의 기록만 호출 수에 센다.
183
+ retrievals는 검사기 작성이 넣은 과거 기록이다(결과 코멘트에 보인다).
184
+ """
185
+ checks = [_saved_check(o, rt.store) for o in outcomes]
186
+ diff = changes_diff.decode("utf-8", errors="replace")
187
+ try:
188
+ found = detect.detect(
189
+ checks, worktree, added_lines(diff), new_files=new_files(diff), sandbox=rt.sandbox,
190
+ disabled=rt.disabled,
191
+ ) # fmt: skip
192
+ except SandboxError as e:
193
+ log.warning("검사기 실행 샌드박스 실패: %s", e)
194
+ return NotRun(f"검사기를 돌리는 샌드박스가 실패함: {_first_line(str(e))}")
195
+ failed = [RuleUnchecked(u.rule, u.kind, u.detail) for u in found.unchecked]
196
+ limit = limits_for(rt.budget.settings, RulesetScope(read.key, len(read.rules))).scope
197
+ calls = [
198
+ c for c in rt.store.model_calls(rt.budget.repo, rt.budget.pr_number)
199
+ if (c.id or 0) > since_call and c.head_sha == rt.budget.head_sha
200
+ ] # fmt: skip
201
+ return Found(
202
+ outcomes=with_run_failures(outcomes, failed),
203
+ violations=found.violations,
204
+ disabled=read.disabled,
205
+ usage=call_usage(calls, limit),
206
+ note=read.note,
207
+ retrievals=merge_retrievals(retrievals),
208
+ sections=read.sections,
209
+ )
210
+
211
+
212
+ def judge(
213
+ found: Found,
214
+ worktree: Path,
215
+ changes_diff: bytes,
216
+ rt: Runtime,
217
+ *,
218
+ is_stale: Callable[[], bool] = lambda: False,
219
+ ) -> Found:
220
+ """모델 판단으로 내려온 규칙을 바뀐 hunk에 대해 본다 (4.5). 도구·검사기 다음, 테스트 전이다.
221
+
222
+ 앞서 모델이 찾은 위반은 버리고 처음부터 다시 판단한다. 저장된 쌍은 호출 없이 같은 답을 쓰므로
223
+ `/fix`가 다시 돌려도 남은 쌍만 묻는다.
224
+ """
225
+ rules_ = [o.rule for o in found.outcomes if isinstance(o, RuleJudged)]
226
+ if not rules_:
227
+ return found
228
+ known = tuple(v for v in found.violations if v.found_by != "model")
229
+ result = model_judge.judge(
230
+ rules_, worktree, changes_diff.decode("utf-8", errors="replace"), store=rt.store,
231
+ budget=rt.budget, model=rt.models.judge, ask=rt.ask, known=len(known), is_stale=is_stale,
232
+ ) # fmt: skip
233
+
234
+ def judged(o: RuleOutcome) -> RuleOutcome:
235
+ if not isinstance(o, RuleJudged):
236
+ return o
237
+ rule_id = o.rule.id
238
+ gap, undecided = result.gaps.get(rule_id), result.undecided.get(rule_id)
239
+ return RuleJudged(
240
+ o.rule, o.reason, o.route,
241
+ left=gap.pairs if gap else 0, left_kind=gap.kind if gap else None,
242
+ left_detail=gap.detail if gap else "", pairs=result.pairs.get(rule_id, 0),
243
+ undecided=undecided.pairs if undecided else 0,
244
+ undecided_why=undecided.why if undecided else "",
245
+ ) # fmt: skip
246
+
247
+ return replace(
248
+ found, outcomes=tuple(judged(o) for o in found.outcomes),
249
+ violations=known + result.violations, judge=result.usage,
250
+ ) # fmt: skip
251
+
252
+
253
+ def judge_left(found: object) -> bool:
254
+ """호출 상한에 걸려 모델 판단을 다 하지 못한 규칙이 있다. `/fix`가 이어 한다 (4.9 명령)."""
255
+ return isinstance(found, Found) and any(
256
+ isinstance(o, RuleJudged) and o.left_kind == "cap" for o in found.outcomes
257
+ )
258
+
259
+
260
+ def saved_checks(found: Found, store: Store) -> list[RuleCheck]:
261
+ """found의 규칙마다 저장한 검사기. 수정 뒤 재검사(4.8의 5번)가 같은 검사기를 다시 돌린다."""
262
+ return [_saved_check(o, store) for o in found.outcomes]
263
+
264
+
265
+ def _saved_check(outcome: RuleOutcome, store: Store) -> RuleCheck:
266
+ if isinstance(outcome, RuleUnchecked):
267
+ return Unchecked(outcome.rule, outcome.kind, outcome.detail)
268
+ if isinstance(outcome, RuleJudged): # 도구·검사기로 다시 돌릴 것이 없다 (4.8의 5번)
269
+ return ToJudge(outcome.rule, outcome.route, outcome.reason)
270
+ entry = store.saved_checker(outcome.checker.key)
271
+ if entry is None or entry.checker_json is None:
272
+ return Unchecked(outcome.rule, "run_failed", "저장한 검사기를 찾지 못함")
273
+ return Checked(outcome.rule, checker_from_json(entry.checker_json), outcome.checker.cached)
274
+
275
+
276
+ def shown_checkers(result: DocRules | None, store: Store) -> dict[str, Checker]:
277
+ """코멘트에 본문을 보일 검사기: 이번 검사에서 위반을 찾은 것 (4.9). {CheckerRef.key: 검사기}."""
278
+ if not isinstance(result, Found):
279
+ return {}
280
+ found_by = {v.rule_id for v in result.violations}
281
+ out = {}
282
+ for o in result.outcomes:
283
+ if isinstance(o, RuleChecked) and o.rule.id in found_by:
284
+ entry = store.saved_checker(o.checker.key)
285
+ if entry is not None and entry.checker_json is not None:
286
+ out[o.checker.key] = checker_from_json(entry.checker_json)
287
+ return out
288
+
289
+
290
+ def last_call_id(store: Store, repo: str, pr_number: int) -> int:
291
+ return max((c.id or 0 for c in store.model_calls(repo, pr_number)), default=0)
292
+
293
+
294
+ def sandbox_for(
295
+ tool_cache: Path, ruff: RuffSetup | None = None, image: str = docker_cli.IMAGE
296
+ ) -> checkers.FormatsFiles:
297
+ return checkers.Sandbox(tool_cache, ruff, image)
298
+
299
+
300
+ def _first_line(text: str) -> str:
301
+ return text.strip().splitlines()[0] if text.strip() else text
@@ -0,0 +1,168 @@
1
+ """큰 규칙 문서의 관련 절만 읽기 (docs/DESIGN.md 6.3). 조각 나누기, 늘 읽는 절, 고르기, 발췌, 절
2
+ 단위 캐시 키. 판단만 하고 임베딩이나 모델 호출은 하지 않는다 (app/worker/rules/rules.py).
3
+
4
+ 규칙 문서 합계가 400KB를 넘고 검색을 켠 저장소만 이 방식을 쓴다. 문서를 제목 단위 조각(제목 줄과 그
5
+ 아래 하위 절을 뺀 본문)으로 나눠 임베딩하고, 그 PR과 관련된 조각만 모델이 읽는다. 조각을 모은 발췌는
6
+ 원래 문서의 줄을 그대로 쓰고 조각의 상위 제목 줄을 남겨, 원문 확인(`rule_reading.verify_rules`)과
7
+ 규칙 id·출처가 문서 전체를 읽을 때와 같다.
8
+ """
9
+
10
+ import hashlib
11
+ from collections.abc import Iterable, Mapping, Sequence
12
+ from dataclasses import dataclass
13
+ from typing import Final
14
+
15
+ from app.worker.cache_key_pure import model_cache_key
16
+ from app.worker.rule_pure import Rule, RuleSet, in_scope
17
+ from app.worker.rule_reading_pure import (
18
+ MAX_DOCS_BYTES,
19
+ PROMPT_VERSION,
20
+ READER_VERSION,
21
+ SECTION_SEPARATOR,
22
+ Document,
23
+ headings,
24
+ )
25
+
26
+ # 큰 문서 방식에서 읽어 조각으로 나눌 문서 합계의 상한. 넘는 문서는 읽지 않는다
27
+ # (임베딩 시간과 메모리)
28
+ MAX_LARGE_DOCS_BYTES: Final = 4_000_000
29
+ # 제목에 이 말이 든 절은 검색과 관계없이 늘 읽는다 (6.3). 문서의 머리 부분도 늘 읽는다
30
+ ALWAYS_WORDS: Final = ("규칙", "컨벤션", "스타일", "contributing")
31
+ MAX_QUERY_CHARS: Final = 4000
32
+ MAX_EMBED_CHARS: Final = 4000
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Chunk:
37
+ """제목 하나의 조각: 제목 줄과 그 절의 본문(하위 절 제외). heading이 ()면 첫 제목 앞의
38
+ 머리다."""
39
+
40
+ path: str
41
+ blob_sha: str
42
+ heading: tuple[str, ...]
43
+ start: int # 조각의 첫 줄 (0부터, 제목 줄)
44
+ end: int # 다음 제목 줄 (포함하지 않음)
45
+ keep: tuple[int, ...] # 발췌에 같이 남길 줄: 문서 이름 제목과 상위 절의 제목 줄
46
+ text: str
47
+
48
+ @property
49
+ def id(self) -> str:
50
+ """조각의 내용 해시. 문서의 다른 곳이 바뀌어도 이 조각이 그대로면 다시 임베딩하지 않는다."""
51
+ raw = "\0".join((self.path, SECTION_SEPARATOR.join(self.heading), self.text))
52
+ return hashlib.sha256(raw.encode()).hexdigest()[:32]
53
+
54
+ @property
55
+ def label(self) -> str:
56
+ return (
57
+ f"{self.path} > {SECTION_SEPARATOR.join(self.heading)}"
58
+ if self.heading
59
+ else (f"{self.path} (머리)")
60
+ )
61
+
62
+ @property
63
+ def size(self) -> int:
64
+ return len(self.text.encode())
65
+
66
+ @property
67
+ def embed_text(self) -> str:
68
+ return f"{self.label}\n{self.text}"[:MAX_EMBED_CHARS]
69
+
70
+
71
+ def chunks(document: Document) -> tuple[Chunk, ...]:
72
+ """문서를 제목 단위 조각으로. 모든 줄이 정확히 한 조각에 든다."""
73
+ lines = document.text.splitlines()
74
+ top, found = headings(document.text)
75
+ title = (top[0],) if top is not None else ()
76
+ first = found[0][0] if found else len(lines)
77
+ out = [
78
+ Chunk(document.path, document.blob_sha, (), 0, first, (),
79
+ "\n".join(lines[:first]))
80
+ ] # fmt: skip
81
+ stack: list[tuple[int, int, str]] = [] # (단계, 줄, 제목)
82
+ for n, (line_no, level, name) in enumerate(found):
83
+ while stack and stack[-1][0] >= level:
84
+ stack.pop()
85
+ keep = title + tuple(s[1] for s in stack)
86
+ stack.append((level, line_no, name))
87
+ end = found[n + 1][0] if n + 1 < len(found) else len(lines)
88
+ out.append(Chunk(document.path, document.blob_sha, tuple(s[2] for s in stack), line_no,
89
+ end, keep, "\n".join(lines[line_no:end]))) # fmt: skip
90
+ return tuple(c for c in out if c.text.strip() or c.heading)
91
+
92
+
93
+ def always_read(chunk: Chunk) -> bool:
94
+ """문서의 머리와, 제목 경로에 규칙·컨벤션·스타일·contributing이 든 절 (6.3)."""
95
+ if not chunk.heading:
96
+ return True
97
+ title = " ".join(chunk.heading).casefold()
98
+ return any(word in title for word in ALWAYS_WORDS)
99
+
100
+
101
+ def excerpt(document: Document, wanted: Iterable[Chunk]) -> Document:
102
+ """고른 조각만 남긴 문서. 줄은 원래 순서이고, 조각의 상위 제목 줄과 문서 이름 제목을 같이 남겨
103
+ 절 경로가 문서 전체에서와 같다. 경로와 blob 해시는 원래 문서의 것이다."""
104
+ lines = document.text.splitlines()
105
+ kept: set[int] = set()
106
+ for c in wanted:
107
+ if c.path != document.path:
108
+ continue
109
+ kept |= set(range(c.start, c.end)) | set(c.keep)
110
+ return Document(document.path, document.blob_sha, "\n".join(lines[i] for i in sorted(kept)))
111
+
112
+
113
+ def section_key(chunk: Chunk, model: str) -> str:
114
+ """조각 하나의 규칙을 저장하는 키 (6.3 "절 단위"). 같은 조각은 다시 읽지 않는다."""
115
+ parts = {"reader": READER_VERSION, "chunk": chunk.id, "path": chunk.path}
116
+ return model_cache_key("rules-section", model, PROMPT_VERSION, parts)
117
+
118
+
119
+ def query_text(changed: Sequence[str], added: str) -> str:
120
+ """조각을 찾는 질의 (6.3 "꺼내는 방법"): PR이 바꾼 파일의 경로와 폴더, 바뀐 hunk의 추가된 줄."""
121
+ folders = sorted({p.rsplit("/", 1)[0] for p in changed if "/" in p})
122
+ head = "바뀐 파일: " + ", ".join(changed) + "\n폴더: " + ", ".join(folders)
123
+ return f"{head}\n바뀐 코드:\n{added}"[:MAX_QUERY_CHARS]
124
+
125
+
126
+ def scoped_to(chunk_rules: Mapping[str, RuleSet], changed: Sequence[str]) -> set[str]:
127
+ """이미 읽어 둔 조각 중 그 규칙의 적용 범위(문서가 밝힌 것)가 바뀐 파일에 걸리는 것 (검색이
128
+ 아니라 저장한 규칙으로 고른다)."""
129
+ out = set()
130
+ for chunk_id, ruleset in chunk_rules.items():
131
+ if any(r.scope and any(in_scope(r.scope, f) for f in changed) for r in ruleset.rules):
132
+ out.add(chunk_id)
133
+ return out
134
+
135
+
136
+ def pick(
137
+ all_chunks: Sequence[Chunk],
138
+ *,
139
+ scoped: set[str],
140
+ hits: Sequence[tuple[str, float]],
141
+ max_bytes: int = MAX_DOCS_BYTES,
142
+ ) -> tuple[Chunk, ...]:
143
+ """읽을 조각: 늘 읽는 절, 적용 범위로 고른 절, 검색이 찾은 절(hits, `rag.top_k`개, 유사도 순)의
144
+ 차례로 합계가 max_bytes 안에 드는 것까지. 결과는 문서와 줄 순서다.
145
+
146
+ 조각에는 기록의 유사도 기준값을 쓰지 않는다. 질의(경로와 바뀐 줄)와 절의 글은 모양이 달라
147
+ 유사도가 기록끼리보다 낮다: multilingual-e5-small에서 맞는 절이 1위였지만 0.893으로 기본
148
+ 기준값 0.91에 못 미쳤다 (5단계, 11.1)."""
149
+ by_id = {c.id: c for c in all_chunks}
150
+ order = [c.id for c in all_chunks if always_read(c)]
151
+ order += [c.id for c in all_chunks if c.id in scoped]
152
+ order += [i for i, _ in sorted(hits, key=lambda h: -h[1]) if i in by_id]
153
+ chosen: dict[str, Chunk] = {}
154
+ total = 0
155
+ for chunk_id in order:
156
+ chunk = by_id[chunk_id]
157
+ if chunk_id in chosen or total + chunk.size > max_bytes:
158
+ continue
159
+ chosen[chunk_id] = chunk
160
+ total += chunk.size
161
+ position = {c.id: n for n, c in enumerate(all_chunks)}
162
+ return tuple(sorted(chosen.values(), key=lambda c: position[c.id]))
163
+
164
+
165
+ def chunk_of(rule: Rule, among: Sequence[Chunk]) -> Chunk | None:
166
+ """규칙이 나온 조각: 같은 문서이고 원문 확인이 찾은 절이 그 조각의 제목 경로인 것."""
167
+ path = tuple(p for p in rule.source.section.split(SECTION_SEPARATOR) if p)
168
+ return next((c for c in among if c.path == rule.source.file and c.heading == path), None)