pr-proof 0.0.0-stage → 0.1.1-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 +172 -0
  16. package/app/setup/__init__.py +4 -0
  17. package/app/setup/cli.py +90 -0
  18. package/app/setup/configure.py +735 -0
  19. package/app/setup/files.py +104 -0
  20. package/app/setup/github_setup.py +153 -0
  21. package/app/setup/install_hints.json +32 -0
  22. package/app/setup/setup_pure.py +344 -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,113 @@
1
+ """`npx pr-proof start`: api와 worker, 저장한 웹훅 받는 주소가 smee 주소면 smee-client까지 띄운다.
2
+
3
+ 세 프로그램은 honcho 하나가 띄운다(`scripts/start.sh`와 같다). 하나가 끝나면 honcho가 나머지를 모두
4
+ 내린다. launchd로 띄웠으면 launchd가 통째로 다시 띄운다(docs/OPERATIONS.md). smee-client는 연결이
5
+ 끊기면 스스로 다시 붙고, 그사이 놓친 소식은 동기화가 메운다.
6
+
7
+ Procfile은 패키지의 것(api, worker)에 smee 줄을 더해 실행 환경 폴더에 만든다. 하위 프로세스에는
8
+ `scripts/start.sh`처럼 최소 환경만 넘긴다. node는 입구(bin/pr-proof.js)가 넘긴 그 node를 쓴다
9
+ (nvm으로 깐 node도 찾는다).
10
+ """
11
+
12
+ import os
13
+ import shlex
14
+ import shutil
15
+ import sys
16
+ from collections.abc import Callable, Mapping
17
+ from pathlib import Path
18
+ from typing import Final
19
+
20
+ from app.setup import files
21
+ from app.shared import config
22
+
23
+ # launchd는 /usr/bin:/bin만 준다. gh·claude·docker가 보통 있는 곳 (scripts/start.sh와 같다)
24
+ SYSTEM_PATH: Final = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
25
+ PASSED_ENV: Final = ("HOME", "USER", "TMPDIR", "LANG", config.CONFIG_DIR_ENV)
26
+ TOOLS: Final = ("gh", "claude", "docker", "git")
27
+ WEBHOOK_PATH: Final = "/webhook/github"
28
+
29
+ Exec = Callable[[str, list[str], Mapping[str, str]], object]
30
+
31
+
32
+ def procfile_text(node: str | None = None, smee_js: str | None = None,
33
+ smee_url: str | None = None) -> str: # fmt: skip
34
+ """패키지의 Procfile(api, worker)에 smee 줄을 더한 것. smee 주소가 없으면 그대로다."""
35
+ text = (files.PACKAGE_ROOT / "Procfile").read_text()
36
+ if not (node and smee_js and smee_url):
37
+ return text
38
+ target = f"http://127.0.0.1:${{{files.PORT_KEY}:-{files.DEFAULT_PORT}}}{WEBHOOK_PATH}"
39
+ smee = (
40
+ f"smee: {shlex.quote(node)} {shlex.quote(smee_js)} --url {shlex.quote(smee_url)} "
41
+ f'--target "{target}"'
42
+ )
43
+ return text.rstrip("\n") + "\n" + smee + "\n"
44
+
45
+
46
+ def run_env(environ: Mapping[str, str], venv_bin: Path, node: str | None) -> dict[str, str]:
47
+ """honcho와 그 아래 프로그램의 환경. PATH는 venv, node의 폴더, ~/.local/bin, 시스템 경로,
48
+ 이 셸의 PATH 순이다. 비밀값은 넣지 않는다(서버가 설정 폴더에서 직접 읽는다)."""
49
+ home = environ.get("HOME", str(Path.home()))
50
+ parts = [str(venv_bin)]
51
+ if node:
52
+ parts.append(str(Path(node).parent))
53
+ parts += [f"{home}/.local/bin", *environ.get("PR_PROOF_SYSTEM_PATH", SYSTEM_PATH).split(":")]
54
+ parts += environ.get("PATH", "").split(":")
55
+ path = ":".join(dict.fromkeys(p for p in parts if p))
56
+ env = {k: environ[k] for k in PASSED_ENV if environ.get(k)}
57
+ return env | {"HOME": home, "PATH": path}
58
+
59
+
60
+ def missing_tools(path: str) -> list[str]:
61
+ return [tool for tool in TOOLS if shutil.which(tool, path=path) is None]
62
+
63
+
64
+ def start(
65
+ node: str | None,
66
+ smee_js: str | None,
67
+ *,
68
+ directory: Path | None = None,
69
+ environ: Mapping[str, str] | None = None,
70
+ venv_bin: Path | None = None,
71
+ exec_: Exec = os.execve,
72
+ out: Callable[[str], object] = print,
73
+ ) -> int:
74
+ """honcho로 바꿔 탄다(exec). 돌아오면 띄우지 못한 것이다."""
75
+ source = os.environ if environ is None else environ
76
+ directory = directory or files.config_dir()
77
+ bin_dir = venv_bin or Path(sys.executable).parent
78
+ if not (directory / files.CONFIG_FILE).is_file():
79
+ out(f"설정이 없습니다 ({directory / files.CONFIG_FILE}). 먼저 npx pr-proof configure를 "
80
+ "실행하세요.") # fmt: skip
81
+ return 1
82
+ honcho = bin_dir / "honcho"
83
+ if not honcho.exists():
84
+ out(f"{honcho}가 없습니다. npx pr-proof configure를 다시 실행하세요.")
85
+ return 1
86
+ env = run_env(source, bin_dir, node)
87
+ missing = missing_tools(env["PATH"])
88
+ if missing:
89
+ out(f"찾지 못한 프로그램: {', '.join(missing)} (PATH={env['PATH']}). "
90
+ "npx pr-proof configure로 확인하세요.") # fmt: skip
91
+ return 1
92
+ try:
93
+ url = files.read_private(files.WEBHOOK_URL_FILE, directory)
94
+ except config.ConfigError as e:
95
+ out(str(e))
96
+ return 1
97
+ smee_url = url if url and files.is_smee(url) else None
98
+ if smee_url and not (node and smee_js):
99
+ out("smee 주소가 저장되어 있지만 smee-client를 찾지 못했습니다. npx pr-proof start로 "
100
+ "실행하세요.") # fmt: skip
101
+ return 1
102
+ runtime = files.runtime_home(dict(source))
103
+ runtime.mkdir(parents=True, exist_ok=True, mode=0o700)
104
+ procfile = runtime / "Procfile"
105
+ procfile.write_text(procfile_text(node, smee_js, smee_url))
106
+ procfile.chmod(0o600) # smee 주소가 들어 있다
107
+ port = files.read_port(directory)
108
+ out(f"pr-proof 시작: api(포트 {port}), worker" + (", smee에서 받아 오기" if smee_url else ""))
109
+ os.chdir(files.PACKAGE_ROOT) # api와 worker는 패키지 폴더에서 돈다 (scripts/start.sh와 같다)
110
+ args = [str(honcho), "start", "-f", str(procfile), "-d", str(files.PACKAGE_ROOT),
111
+ "-e", str(directory / files.RUN_ENV_FILE)] # fmt: skip
112
+ exec_(str(honcho), args, env)
113
+ return 1
@@ -0,0 +1 @@
1
+ """웹과 워커가 둘 다 import하는 것만 둔다. api·worker를 import하지 않는다."""
@@ -0,0 +1,29 @@
1
+ """파이프라인 PR 코멘트의 공용 표시.
2
+
3
+ 파이프라인은 사용자의 gh 계정으로 코멘트를 달므로, 작성자가 아니라 이 표시로 자기 코멘트를 알아본다.
4
+ 웹은 이 표시가 있는 코멘트를 명령으로 받지 않고, 워커는 이 표시로 고칠 코멘트를 찾는다.
5
+ 명령으로 받을지는 command_in_comment() 하나로 정한다 (웹훅·동기화 공용).
6
+ """
7
+
8
+ from typing import Final
9
+
10
+ COMMENT_MARKER: Final = "<!-- pr-proof -->"
11
+ # 명령에 답하는 코멘트의 표시. 결과 코멘트를 찾을 때 섞이지 않도록 COMMENT_MARKER를 포함하지 않는다
12
+ REPLY_MARKER: Final = "<!-- pr-proof:reply -->"
13
+ # 명령을 받을 수 있는 작성자 (GitHub author_association)
14
+ TRUSTED_AUTHORS: Final = frozenset({"OWNER", "MEMBER", "COLLABORATOR"})
15
+
16
+
17
+ def command_in_comment(body: str | None, author_association: str | None) -> tuple[str | None, str]:
18
+ """코멘트가 처리할 명령이면 (명령 줄, ""), 아니면 (None, 무시 이유).
19
+
20
+ 웹훅과 동기화가 같은 함수로 거른다. 둘 중 한쪽만 권한을 확인하면 그쪽이 구멍이 된다.
21
+ """
22
+ text = (body or "").strip()
23
+ if COMMENT_MARKER in text or REPLY_MARKER in text:
24
+ return None, "파이프라인 자신의 코멘트"
25
+ if not text.startswith("/"):
26
+ return None, "명령이 아닌 코멘트"
27
+ if author_association not in TRUSTED_AUTHORS:
28
+ return None, "명령 권한 없음"
29
+ return text.splitlines()[0], ""
@@ -0,0 +1,106 @@
1
+ """파이프라인 쪽 설정과 비밀값 읽기.
2
+
3
+ 설정: `<설정 폴더>/config.yaml`. 비밀값: `<설정 폴더>/<이름>` 파일 (chmod 600).
4
+ 설정 폴더는 기본 `~/.config/pipeline`이고, `PIPELINE_CONFIG_DIR`로 경로만 바꿀 수 있다.
5
+ 비밀값 자체는 환경변수로 받지 않는다.
6
+ """
7
+
8
+ import os
9
+ import stat
10
+ from pathlib import Path
11
+ from typing import Final
12
+
13
+ import yaml
14
+ from pydantic import BaseModel, field_validator
15
+
16
+ from app.shared.embed_models_pure import E5_SMALL, EMBED_MODELS
17
+
18
+ DEFAULT_CONFIG_DIR: Final = Path.home() / ".config" / "pipeline"
19
+ CONFIG_DIR_ENV: Final = "PIPELINE_CONFIG_DIR"
20
+ WEBHOOK_SECRET: Final = "webhook_secret"
21
+
22
+
23
+ class ConfigError(RuntimeError):
24
+ """설정이나 비밀값 파일이 없거나 잘못됐다."""
25
+
26
+
27
+ class SyncConfig(BaseModel):
28
+ interval_minutes: float = 5 # 0이면 동기화 루프를 띄우지 않는다
29
+ env_error_backoff_minutes: float = 30
30
+ # .venv 설치(최대 15분) 동안은 생존 확인을 남기지 못하므로 그보다 길게 둔다
31
+ heartbeat_timeout_minutes: float = 20
32
+
33
+
34
+ class SandboxConfig(BaseModel):
35
+ # 대상 리포가 .pipeline.yaml의 sandbox.memory_gb로 올릴 수 있는 상한
36
+ max_memory_gb: float = 4
37
+ # 이미지 태그와 작업 컨테이너 이름 접두어. 기본값은 app/worker/sandbox/docker_cli.py와 같다
38
+ # (tests/shared/test_config.py가 확인). 같은 Docker를 쓰는 다른 실행과 겹치지 않게 바꿀 수 있다
39
+ image: str = "pipeline-sandbox"
40
+ container_prefix: str = "pr-proof-job"
41
+
42
+
43
+ class CallMaxima(BaseModel):
44
+ """리포의 `.pipeline.yaml`이 `model.calls`로 정할 수 있는 각 값의 최댓값 (DESIGN.md 10절)."""
45
+
46
+ max_pr_max: int = 500
47
+ max_ruleset_max: int = 300
48
+ max_repo_daily: int = 2000
49
+
50
+
51
+ class ModelConfig(BaseModel):
52
+ calls: CallMaxima = CallMaxima()
53
+
54
+
55
+ class RagConfig(BaseModel):
56
+ """과거 기록 검색의 파이프라인 쪽 설정 (DESIGN.md 6.5, 10절). 모델은
57
+ `app/shared/embed_models_pure.py`의 `EMBED_MODELS`에 판과 해시를 고정한 것만 받는다."""
58
+
59
+ embed_model: str = E5_SMALL
60
+
61
+ @field_validator("embed_model")
62
+ @classmethod
63
+ def _known(cls, value: str) -> str:
64
+ if value not in EMBED_MODELS:
65
+ known = ", ".join(sorted(EMBED_MODELS))
66
+ raise ValueError(f"받을 수 있는 임베딩 모델이 아님: {value} (가능: {known})")
67
+ return value
68
+
69
+
70
+ class PipelineConfig(BaseModel):
71
+ repos: list[str] # 처리할 리포 허용 목록 "owner/name"
72
+ redis_url: str = "redis://127.0.0.1:6379/0"
73
+ # bare 캐시, worktree, .venv, SQLite, 검색을 켜면 chroma/와 임베딩 모델(models/)
74
+ data_dir: Path = Path.home() / ".cache" / "pipeline"
75
+ sync: SyncConfig = SyncConfig()
76
+ sandbox: SandboxConfig = SandboxConfig()
77
+ model: ModelConfig = ModelConfig()
78
+ rag: RagConfig = RagConfig()
79
+
80
+ @property
81
+ def db_path(self) -> Path:
82
+ return self.data_dir / "pipeline.db"
83
+
84
+
85
+ def config_dir() -> Path:
86
+ return Path(os.environ.get(CONFIG_DIR_ENV, DEFAULT_CONFIG_DIR)).expanduser()
87
+
88
+
89
+ def load_config(directory: Path | None = None) -> PipelineConfig:
90
+ path = (directory or config_dir()) / "config.yaml"
91
+ if not path.is_file():
92
+ raise ConfigError(f"설정 파일이 없다: {path}")
93
+ return PipelineConfig.model_validate(yaml.safe_load(path.read_text()) or {})
94
+
95
+
96
+ def read_secret(name: str, directory: Path | None = None) -> str:
97
+ """비밀값 파일을 읽는다. 그룹·다른 사용자가 읽을 수 있으면 거부한다."""
98
+ path = (directory or config_dir()) / name
99
+ if not path.is_file():
100
+ raise ConfigError(f"비밀값 파일이 없다: {path}")
101
+ if path.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO):
102
+ raise ConfigError(f"비밀값 파일 권한이 넓다 (chmod 600 필요): {path}")
103
+ value = path.read_text().strip()
104
+ if not value:
105
+ raise ConfigError(f"비밀값 파일이 비어 있다: {path}")
106
+ return value
@@ -0,0 +1,339 @@
1
+ """SQLite 테이블 정의. 연결과 쓰기는 각자 자기 쪽(워커는 app/worker/state.py)에서 한다."""
2
+
3
+ from datetime import datetime
4
+ from typing import Literal
5
+
6
+ from sqlalchemy import UniqueConstraint
7
+ from sqlmodel import Field, SQLModel
8
+
9
+ # error: 환경 오류가 아닌 예외(파이프라인 버그, 작업 시간 초과). 같은 커밋은 다시 넣지 않는다
10
+ # blocked: 신뢰되지 않은 작성자의 PR이라 승인 안내만 달고 끝냈다 (8.6). 같은 커밋은 다시 넣지 않는다
11
+ RunState = Literal["running", "done", "cancelled", "env_error", "error", "blocked"]
12
+
13
+
14
+ # open: 열려 있음, merged: 머지됨, superseded: 원본 PR에 새 커밋이 와서 파이프라인이 닫음,
15
+ # rejected: 사람이 머지하지 않고 닫음, closed_with_pr: 원본 PR이 닫혀 파이프라인이 닫음
16
+ ProposalState = Literal["open", "merged", "superseded", "rejected", "closed_with_pr"]
17
+
18
+
19
+ class Proposal(SQLModel, table=True):
20
+ """제안 PR (DESIGN.md F10). 머지 여부는 커밋 메시지가 아니라 이 번호로 GitHub에서 확인한다."""
21
+
22
+ id: int | None = Field(default=None, primary_key=True)
23
+ repo: str = Field(index=True)
24
+ pr_number: int = Field(index=True) # 원본 PR
25
+ skill: str
26
+ head_sha: str # 수정안을 만든 원본 PR의 커밋
27
+ branch: str
28
+ number: int # 제안 PR 번호
29
+ state: str # ProposalState
30
+ merge_commit: str | None = None
31
+ created_at: datetime
32
+ updated_at: datetime
33
+ # 이 수정안이 올린 수정 시도 (`fix_attempts`). 머지·닫힘의 기록이 읽는다. v1 lint의 수정안은
34
+ # 없다(그 경로가 쓰던 `proposaltarget` 테이블은 3단계에 쓰지 않게 되었고 지우지 않는다)
35
+ attempt_id: int | None = None
36
+
37
+
38
+ class CommandRecord(SQLModel, table=True):
39
+ """처리한 명령 코멘트. 같은 코멘트에 두 번 답하지 않는다 (DESIGN.md F11)."""
40
+
41
+ comment_id: int = Field(primary_key=True)
42
+ repo: str = Field(index=True)
43
+ pr_number: int
44
+ command: str
45
+ result: str
46
+ handled_at: datetime
47
+
48
+
49
+ # accepted: 받아들여 수정안을 올림, rejected: 받아들이지 않고 이유를 답함, no_action: 고칠 것이
50
+ # 없는 코멘트(칭찬, 질문 없음 등), error: 처리하지 못함
51
+ # deferred: 받아들였지만 지금은 고칠 수 없음(테스트가 실패했거나 없음, 포크 PR, 이 커밋에 이미 열린
52
+ # 코멘트 수정안). deferred와 error는 PR에 새 커밋이 오면 다시 본다 (feedback_pure.handled)
53
+ FeedbackVerdict = Literal["accepted", "rejected", "no_action", "deferred", "error"]
54
+
55
+
56
+ class Feedback(SQLModel, table=True):
57
+ """처리한 PR 코멘트 (Copilot 리뷰, 사람의 리뷰). 같은 코멘트를 두 번 처리하지 않는다.
58
+
59
+ item_id는 줄 코멘트면 스레드의 첫 코멘트의 database id, 리뷰면 리뷰 id, 일반 코멘트면 코멘트
60
+ id다. 줄 코멘트만 thread_id(GraphQL 노드 id)가 있고, 수정안이 머지되면 그 스레드를 해결됨으로
61
+ 바꾼다(resolved_at).
62
+ """
63
+
64
+ __table_args__ = (UniqueConstraint("repo", "kind", "item_id"),)
65
+
66
+ id: int | None = Field(default=None, primary_key=True)
67
+ repo: str = Field(index=True)
68
+ pr_number: int = Field(index=True)
69
+ kind: str # FeedbackKind
70
+ item_id: int
71
+ thread_id: str | None = None
72
+ login: str
73
+ head_sha: str # 처리할 때의 PR head
74
+ verdict: str # FeedbackVerdict
75
+ why: str = ""
76
+ reply_id: int | None = None # 단 답글의 id
77
+ proposal_number: int | None = None # 받아들여 올린 수정안 PR 번호
78
+ resolved_at: datetime | None = None
79
+ handled_at: datetime
80
+
81
+
82
+ class CallGrant(SQLModel, table=True):
83
+ """`/fix`가 PR 호출 상한을 한 번 더 준 기록 (DESIGN.md 4.9 명령, 9.2 "걸렸을 때").
84
+
85
+ 명령 코멘트 하나에 한 번이라 같은 명령을 다시 처리해도(재시도) 늘지 않는다. 그 PR의 기록 수가
86
+ 수정 작성의 시도 세대다."""
87
+
88
+ __tablename__ = "call_grants"
89
+
90
+ comment_id: int = Field(primary_key=True)
91
+ repo: str = Field(index=True)
92
+ pr_number: int = Field(index=True)
93
+ head_sha: str
94
+ created_at: datetime
95
+
96
+
97
+ class Run(SQLModel, table=True):
98
+ """PR·커밋별 검사 한 번."""
99
+
100
+ id: int | None = Field(default=None, primary_key=True)
101
+ repo: str = Field(index=True)
102
+ pr_number: int = Field(index=True)
103
+ head_sha: str = Field(index=True)
104
+ kind: str
105
+ source: str
106
+ state: str # RunState
107
+ test_status: str | None = None # PytestRun.status
108
+ comment_id: int | None = None
109
+ started_at: datetime
110
+ heartbeat_at: datetime
111
+ finished_at: datetime | None = None
112
+ # 이 검사를 돌린 파이프라인 코드의 커밋 (`app/shared/version.py`). 이 열이 생기기 전의 줄은 NULL
113
+ pipeline_commit: str | None = None
114
+ # PR 작성자 (8.6). 판단에 쓴 값은 워커가 GitHub의 PR 조회에서 읽은 것이고, `job_` 쪽은 작업을
115
+ # 만든 경로가 `PRJob`에 실은 기록용 값이다. 둘이 다르면 여기서 알 수 있다
116
+ author_association: str | None = None
117
+ author_login: str | None = None
118
+ job_author_association: str | None = None
119
+ job_author_login: str | None = None
120
+
121
+
122
+ class Approval(SQLModel, table=True):
123
+ """외부 작성자 PR의 승인 (DESIGN.md 8.6). 승인은 적힌 커밋 하나에만 적용한다.
124
+
125
+ 워커가 `/recheck <커밋>`을 처리하며, 승인자의 권한과 커밋을 GitHub에서 읽은 값으로 확인한
126
+ 뒤에만 쓴다. 같은 코멘트를 다시 처리해도(재시도) 한 줄이다.
127
+ """
128
+
129
+ __tablename__ = "approvals"
130
+
131
+ comment_id: int = Field(primary_key=True)
132
+ repo: str = Field(index=True)
133
+ pr_number: int = Field(index=True)
134
+ head_sha: str # 전체 해시
135
+ approver: str # 승인자의 로그인 이름
136
+ created_at: datetime
137
+
138
+
139
+ class EvalRun(SQLModel, table=True):
140
+ """평가 세트 한 번의 결과 (DESIGN.md 7.8의 `eval_runs`, 13절 6단계). `baseline`인 가장 최근 줄이
141
+ 비교의 기준선이다. 내용의 모양은 app/worker/eval_run_pure.py에 있다."""
142
+
143
+ __tablename__ = "eval_runs"
144
+
145
+ id: int | None = Field(default=None, primary_key=True)
146
+ created_at: datetime
147
+ label: str = ""
148
+ baseline: bool = Field(default=False, index=True)
149
+ pipeline_commit: str = "" # 평가한 파이프라인 코드의 커밋. 모르면 빈 문자열
150
+ real_model: bool # False면 케이스의 가짜 모델이다(하네스와 결정적 도구만 확인한다)
151
+ passed: int
152
+ failed: int
153
+ skipped: int
154
+ cases_json: str # eval_run.CaseResult 목록
155
+ tools_off_json: str # 도구를 끈 평가의 {조건/방법: {recall, precision}}. 없으면 "{}"
156
+ models_json: str # 단계별 기본 모델
157
+ prompts_json: str # 단계별 프롬프트 판
158
+
159
+
160
+ class ModelCacheEntry(SQLModel, table=True):
161
+ """해시 키 → 모델 결과 (DESIGN.md 5.6, 9.1). thread·PR과 무관하게 키가 같으면 같은 결과를 쓴다.
162
+
163
+ 키는 app/worker/cache_key_pure.py가 만든다.
164
+ """
165
+
166
+ __tablename__ = "model_cache"
167
+
168
+ key: str = Field(primary_key=True)
169
+ stage: str # call_budget.Stage
170
+ model: str # 모델이 알려준 전체 id. 모르면 호출한 이름
171
+ prompt_version: str
172
+ result_json: str
173
+ created_at: datetime
174
+
175
+
176
+ class ModelCall(SQLModel, table=True):
177
+ """모델 호출 한 번 (DESIGN.md 7.8의 `ai_calls`, 9.2). 호출 상한은 `counted`의 합으로 센다.
178
+
179
+ v1 static 수정 경로의 달러 기록 테이블 `aicall`은 2단계에 그 경로와 함께 없앴다. 예전
180
+ 데이터베이스에 남은 그 테이블은 읽지도 지우지도 않는다.
181
+ """
182
+
183
+ __tablename__ = "ai_calls"
184
+
185
+ id: int | None = Field(default=None, primary_key=True)
186
+ repo: str = Field(index=True)
187
+ pr_number: int = Field(index=True)
188
+ head_sha: str
189
+ stage: str # call_budget.Stage
190
+ # 규칙 묶음 상한에서 센 호출이면 그 묶음의 캐시 키. PR 상한에서 센 호출이면 None
191
+ ruleset_key: str | None = Field(default=None, index=True)
192
+ model: str # claude --model에 넘긴 이름
193
+ model_id: str = "" # 모델이 알려준 전체 id (별칭이 가리킨 것)
194
+ tier: str # call_budget.Tier
195
+ attempt: int = 1
196
+ counted: int # 상한에서 센 값. 가벼운 모델 1, 무거운 모델 3, 저장된 결과 0
197
+ cache_hit: bool = False
198
+ # None: 호출을 시작했고 결과를 아직 적지 못함. 워커가 호출 도중 죽어도 센 값은 남는다
199
+ ok: bool | None = None
200
+ error: str | None = None
201
+ input_tokens: int | None = None # 캐시 생성·읽기를 합친 입력. 상한에는 쓰지 않는 측정값
202
+ output_tokens: int | None = None
203
+ permission_denials: int = 0
204
+ created_at: datetime = Field(index=True)
205
+
206
+
207
+ class RulesetEntry(SQLModel, table=True):
208
+ """규칙 묶음의 캐시 키 → 원문 확인을 거친 규칙 묶음 JSON (DESIGN.md 4.3, 7.8).
209
+
210
+ `rules.disabled`는 적용하기 전의 묶음이다. 끈 규칙은 쓸 때 뺀다.
211
+ """
212
+
213
+ __tablename__ = "rulesets"
214
+
215
+ key: str = Field(primary_key=True)
216
+ ruleset_json: str
217
+ created_at: datetime
218
+
219
+
220
+ class CheckerEntry(SQLModel, table=True):
221
+ """규칙별 검사기 작성 결과 (DESIGN.md 4.4, 7.8): 채택한 검사기, 모델 판단으로 보낸 기록(그
222
+ 까닭), 또는 끝내 통과하지 못한 경로 규칙의 기록.
223
+
224
+ 키는 app/worker/checker_authoring_pure.py의 `checker_key`다. 회차마다의 답(초안)은
225
+ `model_cache`에 있고, attempts_json의 각 회차 `artifact`가 그 키다. 호출 상한·모델 호출 실패로
226
+ 끝난 작성은 저장하지 않으므로 다음 검사가 이어 한다.
227
+ """
228
+
229
+ __tablename__ = "checkers"
230
+
231
+ key: str = Field(primary_key=True)
232
+ rule_id: str = Field(index=True)
233
+ accepted: bool
234
+ checker_json: str | None = None # 채택한 Checker. 실패했으면 None
235
+ detail: str = "" # 실패한 이유 (마지막 회차)
236
+ attempts_json: str # app/worker/loop.py의 Attempt 목록
237
+ created_at: datetime
238
+ # 채택하지 않고 모델 판단으로 보낸 까닭 (app/worker/checker_authoring_pure.py의 `JudgeRoute`).
239
+ # 경로 규칙과 도구 선택의 줄은 없다
240
+ judge_route: str | None = None
241
+
242
+
243
+ class FixAttempt(SQLModel, table=True):
244
+ """수정 묶음 하나의 시도 결과 (DESIGN.md 4.8, 7.8). 검증을 통과했으면 그 패치, 설명, 고친 뒤
245
+ 파일의 해시가 있다. 전달이 실패해 다시 올릴 때는 모델을 부르지 않고 이 패치를 새 worktree에
246
+ 적용한 뒤 해시를 맞춰 본다."""
247
+
248
+ __tablename__ = "fix_attempts"
249
+
250
+ id: int | None = Field(default=None, primary_key=True)
251
+ repo: str = Field(index=True)
252
+ pr_number: int = Field(index=True)
253
+ head_sha: str # 검증한 원본 PR의 커밋
254
+ merge_base: str # 바뀐 줄을 다시 센 기준
255
+ bundle: str # 수정 묶음 ("mechanical", "model")
256
+ status: str # model_fix.ModelFixStatus 또는 fix.MechanicalStatus
257
+ attempts: int # 작성 회차
258
+ models_json: str # 쓴 모델 목록 (JSON 배열)
259
+ detail: str = "" # 실패 이유
260
+ targets_json: str # records.Target 목록 (JSON)
261
+ patch: str | None = None # 검증을 통과한 패치 (`git diff HEAD`). 통과하지 못했으면 None
262
+ explanation_json: str | None = None
263
+ file_hashes_json: str | None = None # 고친 뒤 바뀐 파일의 내용 해시 {경로: 해시}
264
+ created_at: datetime
265
+ # 검색으로 프롬프트에 넣은 과거 기록 id (JSON 배열). 검색 유무로 채택률을 나눠 센다 (6.7)
266
+ references_json: str | None = None
267
+
268
+
269
+ class RagAutoOff(SQLModel, table=True):
270
+ """`rag.enabled: auto`가 검색을 다시 끈 저장소 (DESIGN.md 6.7 "검색을 켜는 조건").
271
+
272
+ 검색을 붙인 수정안의 채택률이 낮았던 때의 숫자를 남긴다. 이 줄이 있는 동안 auto는 검색을 켜지
273
+ 않는다(끄면 검색을 붙인 쪽의 숫자가 더 늘지 않아, 숫자만으로 다시 정하면 같은 근거로 켜고 끄기를
274
+ 되풀이한다). 비교 기준값(min_attempts, min_baseline)이 바뀌면 이 줄은 쓰지 않고 다시 정한다.
275
+ 저장소마다 한 줄.
276
+ """
277
+
278
+ __tablename__ = "rag_auto_off"
279
+
280
+ repo: str = Field(primary_key=True)
281
+ min_attempts: int # 끈 때의 비교 기준값 (검색을 넣은 쪽)
282
+ min_baseline: int # 끈 때의 견줄 쪽 최소 수
283
+ records: int
284
+ with_adopted: int
285
+ with_known: int
286
+ without_adopted: int
287
+ without_known: int
288
+ created_at: datetime
289
+
290
+
291
+ class SeenViolation(SQLModel, table=True):
292
+ """검사 한 번에서 찾은 문서 규칙 위반 (DESIGN.md 7.8의 `violations`). 다음 커밋의 검사가
293
+ "작성자가 직접 고침"을 알아내는 데 쓴다. 같은 커밋을 다시 검사하면 그 커밋의 줄을 바꿔 쓴다."""
294
+
295
+ __tablename__ = "violations"
296
+
297
+ id: int | None = Field(default=None, primary_key=True)
298
+ repo: str = Field(index=True)
299
+ pr_number: int = Field(index=True)
300
+ head_sha: str = Field(index=True)
301
+ violation_id: str
302
+ rule_id: str
303
+ file: str
304
+ line: int
305
+ line_text: str | None = None
306
+ message: str
307
+ unit: str # Violation.unit
308
+ context: str = "" # 위반 줄과 앞뒤 5줄 (records.context_around)
309
+ created_at: datetime
310
+
311
+
312
+ class Record(SQLModel, table=True):
313
+ """팀의 과거 기록 원본 (DESIGN.md 4.10, 6.5, 7.6). 저장소의 글이 들어 있어 믿지 않는 자료다.
314
+
315
+ 같은 일을 두 번 넣지 않는다: (repo, kind, source_id)가 고유 키다. 검색(임베딩)은 5단계에
316
+ 켠다. 그 전에는 `embedded_at`이 비어 있다.
317
+ """
318
+
319
+ __tablename__ = "records"
320
+ __table_args__ = (UniqueConstraint("repo", "kind", "source_id"),)
321
+
322
+ id: int | None = Field(default=None, primary_key=True)
323
+ repo: str = Field(index=True)
324
+ kind: str # records.RecordKind
325
+ origin: str # records.RecordOrigin
326
+ source_id: str # 원천 id. 예: "fix_pr:901:<위반 id>"
327
+ rule_id: str = Field(index=True)
328
+ rule_text: str
329
+ file: str
330
+ line_text: str
331
+ context: str # 위반 줄과 앞뒤 5줄
332
+ diff: str # 관련 hunk만, 최대 60줄
333
+ detail: str = "" # 실패 기록: 실패 이유
334
+ pr_number: int | None = Field(default=None, index=True)
335
+ fix_pr_number: int | None = None
336
+ commit_sha: str | None = None
337
+ created_at: datetime
338
+ embedded_at: datetime | None = None
339
+ embed_model: str | None = None
@@ -0,0 +1,55 @@
1
+ """과거 기록 검색이 받을 수 있는 로컬 임베딩 모델 (docs/DESIGN.md 6.5). 외부 호출 없음.
2
+
3
+ 설정(`config.RagConfig`)이 이 목록으로 `rag.embed_model`을 확인하므로 웹과 워커가 같이 읽는다.
4
+ """
5
+
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass
8
+ from typing import Final
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class ModelFile:
13
+ path: str # 모델 저장소 안의 경로
14
+ sha256: str
15
+ size: int
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class EmbedModel:
20
+ """파이프라인이 받을 수 있는 로컬 임베딩 모델. 받는 곳, 판(revision), 파일의 SHA256과 크기를
21
+ 고정한다 (도구 캐시 `toolcache.TOOLS`와 같은 방식). 목록 밖의 모델은 받지 않는다."""
22
+
23
+ name: str
24
+ revision: str # 모델 저장소의 커밋. 같은 이름이라도 이 판의 파일만 받는다
25
+ dim: int
26
+ query_prefix: str
27
+ passage_prefix: str
28
+ tokenizer: ModelFile
29
+ onnx: ModelFile
30
+ max_tokens: int = 512
31
+
32
+ def url(self, file: ModelFile) -> str:
33
+ return f"https://huggingface.co/{self.name}/resolve/{self.revision}/{file.path}"
34
+
35
+
36
+ E5_SMALL: Final = "intfloat/multilingual-e5-small"
37
+ EMBED_MODELS: Final[Mapping[str, EmbedModel]] = {
38
+ E5_SMALL: EmbedModel(
39
+ name=E5_SMALL,
40
+ revision="614241f622f53c4eeff9890bdc4f31cfecc418b3",
41
+ dim=384,
42
+ query_prefix="query: ",
43
+ passage_prefix="passage: ",
44
+ tokenizer=ModelFile(
45
+ "onnx/tokenizer.json",
46
+ "0b44a9d7b51c3c62626640cda0e2c2f70fdacdc25bbbd68038369d14ebdf4c39",
47
+ 17_082_730,
48
+ ),
49
+ onnx=ModelFile(
50
+ "onnx/model.onnx",
51
+ "ca456c06b3a9505ddfd9131408916dd79290368331e7d76bb621f1cba6bc8665",
52
+ 470_268_510,
53
+ ),
54
+ ),
55
+ }