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,42 @@
1
+ """claude CLI가 띄우는 stdio MCP 서버: 줄을 워커의 Unix 소켓으로 넘기고 답을 돌려준다.
2
+
3
+ 파이프라인이 `python -I mcp_relay.py <소켓>`으로 `--mcp-config`에 적는다 (docs/DESIGN.md 4.7, 8.4).
4
+ 도구의 뜻과 실행은 모두 워커(`app/worker/ai/tool_server.py`)에 있고, 이 파일은 메시지를 읽지 않는다.
5
+ CLI가 따로 실행하므로 표준 라이브러리만 쓴다.
6
+ """
7
+
8
+ import socket
9
+ import sys
10
+ import threading
11
+
12
+
13
+ def main(argv: list[str]) -> int:
14
+ try:
15
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
16
+ sock.connect(argv[1])
17
+ except (IndexError, OSError) as e:
18
+ print(f"파이프라인 도구 서버에 붙지 못함: {type(e).__name__}", file=sys.stderr)
19
+ return 1
20
+
21
+ def upstream() -> None:
22
+ try:
23
+ for line in sys.stdin.buffer:
24
+ sock.sendall(line)
25
+ except OSError:
26
+ pass
27
+ finally:
28
+ try:
29
+ sock.shutdown(socket.SHUT_WR)
30
+ except OSError:
31
+ pass
32
+
33
+ threading.Thread(target=upstream, daemon=True).start()
34
+ with sock.makefile("rb") as replies:
35
+ for line in replies:
36
+ sys.stdout.buffer.write(line)
37
+ sys.stdout.buffer.flush()
38
+ return 0
39
+
40
+
41
+ if __name__ == "__main__":
42
+ sys.exit(main(sys.argv))
@@ -0,0 +1,103 @@
1
+ """claude CLI의 PreToolUse 훅: 도구가 가리키는 경로의 실제 위치가 작업 폴더 밖이면 거부한다.
2
+
3
+ 파이프라인이 `python -I path_hook.py <작업 폴더> <기록 파일>`로 등록한다 (docs/DESIGN.md 8.4).
4
+ 표준 입력으로 도구 호출 한 건의 JSON을 받는다. 판단에는 심볼릭 링크를 모두 푼 경로를 쓴다.
5
+ 모르는 도구, 경로가 없는 호출, 읽지 못한 입력은 모두 거부한다. 이 파일은 CLI가 따로 실행하므로
6
+ 표준 라이브러리만 쓴다.
7
+
8
+ 기록 파일에는 호출마다 한 줄을 남긴다. 파이프라인은 이 줄 수로 훅이 실제로 돌았는지 확인한다.
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import sys
14
+ from collections.abc import Mapping
15
+ from typing import Final
16
+
17
+ # 도구 → 경로가 든 입력 키. 값이 True면 꼭 있어야 한다. 없어도 되는 키는 없으면 작업 폴더로 본다
18
+ _PATH_KEYS: Final[Mapping[str, Mapping[str, bool]]] = {
19
+ "Read": {"file_path": True},
20
+ "Write": {"file_path": True},
21
+ "Edit": {"file_path": True},
22
+ "Grep": {"path": False},
23
+ "Glob": {"path": False},
24
+ # 파이프라인 도구(`app/worker/mcp_pure.TOOL_NAMES`). 경로를 받지 않고 파이프라인의 코드가 돈다
25
+ "mcp__proof__check_rules": {},
26
+ "mcp__proof__run_tests": {},
27
+ # 위반 판단(`read_tools`)의 구조화 출력. `--json-schema`를 주면 CLI가 더하는 답 받는 도구다
28
+ "StructuredOutput": {},
29
+ }
30
+ # 경로가 아니라 패턴인 입력. 패턴이 폴더를 벗어나는 모양이면 거부한다
31
+ _PATTERN_KEYS: Final[Mapping[str, tuple[str, ...]]] = {"Grep": ("glob",), "Glob": ("pattern",)}
32
+ _WILDCARDS: Final = "*?[{"
33
+
34
+
35
+ def inside(root: str, path: str) -> bool:
36
+ """path의 실제 위치가 root(이미 실제 경로) 안인지. 상대 경로는 root 기준으로 읽는다."""
37
+ real = os.path.realpath(os.path.join(root, path))
38
+ return real == root or real.startswith(root + os.sep)
39
+
40
+
41
+ def pattern_escapes(root: str, pattern: str) -> bool:
42
+ """glob 패턴이 root 밖을 볼 수 있는 모양인지. `..` 조각이 있거나, 와일드카드 앞부분이 밖이다."""
43
+ parts = pattern.replace("\\", "/").split("/")
44
+ if ".." in parts:
45
+ return True
46
+ literal: list[str] = []
47
+ for part in parts:
48
+ if any(c in part for c in _WILDCARDS):
49
+ break
50
+ literal.append(part)
51
+ prefix = "/".join(literal)
52
+ return bool(prefix) and not inside(root, prefix)
53
+
54
+
55
+ def problem(root: str, event: object) -> str | None:
56
+ """이 도구 호출을 거부할 이유. 허용하면 None."""
57
+ if not isinstance(event, dict):
58
+ return "입력이 JSON 객체가 아님"
59
+ tool, tool_input = event.get("tool_name"), event.get("tool_input")
60
+ if tool not in _PATH_KEYS:
61
+ return f"허용 목록에 없는 도구: {tool!r}"
62
+ if not isinstance(tool_input, dict):
63
+ return "도구 입력이 없음"
64
+ for key, required in _PATH_KEYS[tool].items():
65
+ value = tool_input.get(key)
66
+ if value is None and not required:
67
+ continue
68
+ if not isinstance(value, str) or not value or "\0" in value:
69
+ return f"{key}가 없거나 문자열이 아님"
70
+ if not inside(root, value):
71
+ return f"작업 폴더 밖의 경로: {key}"
72
+ for key in _PATTERN_KEYS.get(tool, ()):
73
+ value = tool_input.get(key)
74
+ if value is None:
75
+ continue
76
+ if not isinstance(value, str) or "\0" in value or pattern_escapes(root, value):
77
+ return f"작업 폴더 밖을 보는 패턴: {key}"
78
+ return None
79
+
80
+
81
+ def main(argv: list[str]) -> int:
82
+ try:
83
+ root, log_path = os.path.realpath(argv[1]), argv[2]
84
+ event = json.loads(sys.stdin.read())
85
+ reason = problem(root, event)
86
+ tool = event.get("tool_name") if isinstance(event, dict) else None
87
+ with open(log_path, "a", encoding="utf-8") as log:
88
+ log.write(json.dumps({"tool": tool, "denied": reason}, ensure_ascii=False) + "\n")
89
+ except Exception as e: # 판단하지 못하면 막는다. 종료 코드 2는 CLI가 도구 호출을 막는 오류다
90
+ print(f"경로 감시 훅 실패: {type(e).__name__}", file=sys.stderr)
91
+ return 2
92
+ if reason is not None:
93
+ decision = {
94
+ "hookEventName": "PreToolUse",
95
+ "permissionDecision": "deny",
96
+ "permissionDecisionReason": reason,
97
+ }
98
+ print(json.dumps({"hookSpecificOutput": decision}, ensure_ascii=False))
99
+ return 0
100
+
101
+
102
+ if __name__ == "__main__":
103
+ sys.exit(main(sys.argv))
@@ -0,0 +1,139 @@
1
+ """수정 작성의 모델이 부르는 파이프라인 도구의 서버 (docs/DESIGN.md 4.7, 8.4).
2
+
3
+ claude 호출 하나 동안 워커 안에 Unix 소켓을 열고, CLI가 띄운 `mcp_relay.py`가 넘기는 MCP 요청에
4
+ 답한다. 도구의 구현은 부르는 쪽이 넘기는 함수(파이프라인의 코드)다. 모델에게 명령 실행을 주지
5
+ 않는다. 도구는 한 번에 하나씩 돈다(같은 worktree와 샌드박스를 쓴다). 호출 수와 시간이 상한에 닿으면
6
+ 도구를 돌리지 않고 "상한에 닿음"을 돌려주며, claude 호출은 정상으로 끝난다.
7
+ """
8
+
9
+ import json
10
+ import logging
11
+ import socket
12
+ import sys
13
+ import tempfile
14
+ import threading
15
+ import time
16
+ from collections.abc import Callable, Iterator, Mapping
17
+ from contextlib import contextmanager
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Final
21
+
22
+ from app.worker import mcp_pure
23
+ from app.worker.mcp_pure import ToolLimits, ToolUsage
24
+
25
+ RELAY: Final = Path(__file__).with_name("mcp_relay.py")
26
+ # 도구 하나의 결과 글을 만드는 함수. 인자는 `mcp_pure.tool_arguments`가 좁힌 것이다
27
+ Handler = Callable[[Mapping[str, str]], str]
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+
32
+ @dataclass
33
+ class _Counter:
34
+ limits: ToolLimits
35
+ counts: dict[str, int] = field(default_factory=dict)
36
+ seconds: float = 0.0
37
+ limited: bool = False
38
+
39
+ def usage(self) -> ToolUsage:
40
+ return ToolUsage(
41
+ check_rules=self.counts.get(mcp_pure.CHECK_RULES, 0),
42
+ run_tests=self.counts.get(mcp_pure.RUN_TESTS, 0),
43
+ seconds=round(self.seconds, 1),
44
+ limited=self.limited,
45
+ )
46
+
47
+
48
+ class ToolServer:
49
+ """열려 있는 동안 도구 요청에 답한다. `config`를 claude의 `--mcp-config`로 넘긴다."""
50
+
51
+ def __init__(self, sock_path: Path, handlers: Mapping[str, Handler], limits: ToolLimits):
52
+ self.sock_path = sock_path
53
+ self._handlers = dict(handlers)
54
+ self._counter = _Counter(limits)
55
+ self._run_lock = threading.Lock()
56
+ self.config = mcp_pure.mcp_config(sys.executable, ["-I", str(RELAY), str(sock_path)])
57
+
58
+ def usage(self) -> ToolUsage:
59
+ return self._counter.usage()
60
+
61
+ def call(self, name: str, args: Mapping[str, str]) -> tuple[str, bool]:
62
+ """도구 하나를 돌린다. 상한에 닿았으면 돌리지 않는다. 도구가 실패해도 글로 돌려준다."""
63
+ with self._run_lock:
64
+ c = self._counter
65
+ reason = mcp_pure.limit_reason(sum(c.counts.values()), c.seconds, c.limits)
66
+ if reason is not None:
67
+ c.limited = True
68
+ return reason, False
69
+ handler = self._handlers.get(name)
70
+ if handler is None:
71
+ return f"이 호출에서 쓸 수 없는 도구: {name}", True
72
+ c.counts[name] = c.counts.get(name, 0) + 1
73
+ started = time.monotonic()
74
+ try:
75
+ return handler(args), False
76
+ except Exception as e: # 도구가 실패해도 claude 호출은 이어 간다. 출구 검사가 다시 본다
77
+ log.warning("파이프라인 도구 %s 실패: %s", name, e)
78
+ return f"도구를 돌리지 못함: {type(e).__name__}", True
79
+ finally:
80
+ c.seconds += time.monotonic() - started
81
+
82
+ def serve(self, conn: socket.socket) -> None:
83
+ write_lock = threading.Lock()
84
+
85
+ def answer(line: str) -> None:
86
+ reply = mcp_pure.respond(line, self.call)
87
+ if reply is None:
88
+ return
89
+ data = (json.dumps(reply, ensure_ascii=False) + "\n").encode()
90
+ with write_lock:
91
+ try:
92
+ conn.sendall(data)
93
+ except OSError:
94
+ pass
95
+
96
+ workers = []
97
+ with conn, conn.makefile("rb") as lines:
98
+ for raw in lines:
99
+ worker = threading.Thread(target=answer, args=(raw.decode(errors="replace"),))
100
+ worker.start()
101
+ workers.append(worker)
102
+ for worker in workers:
103
+ worker.join()
104
+
105
+
106
+ @contextmanager
107
+ def serving(
108
+ handlers: Mapping[str, Handler], limits: ToolLimits | None = None
109
+ ) -> Iterator[ToolServer]:
110
+ """claude 호출 하나 동안 도구 서버를 연다. 소켓은 이 호출만의 임시 폴더에 둔다."""
111
+ with tempfile.TemporaryDirectory(prefix="pp-tools-") as tmp:
112
+ sock_path = Path(tmp) / "s"
113
+ server = ToolServer(sock_path, handlers, limits or ToolLimits())
114
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
115
+ listener.bind(str(sock_path))
116
+ sock_path.chmod(0o600)
117
+ listener.listen(4)
118
+ listener.settimeout(0.5) # 닫을 때 accept가 깨어나도록
119
+ stop = threading.Event()
120
+
121
+ def accept() -> None:
122
+ while not stop.is_set():
123
+ try:
124
+ conn, _ = listener.accept()
125
+ except TimeoutError:
126
+ continue
127
+ except OSError:
128
+ return
129
+ conn.settimeout(None)
130
+ threading.Thread(target=server.serve, args=(conn,), daemon=True).start()
131
+
132
+ thread = threading.Thread(target=accept, daemon=True)
133
+ thread.start()
134
+ try:
135
+ yield server
136
+ finally:
137
+ stop.set()
138
+ listener.close()
139
+ thread.join(timeout=5)
@@ -0,0 +1,333 @@
1
+ """모델 전용 작업 폴더 (docs/DESIGN.md 8.4, 위협 표 T28).
2
+
3
+ 수정 모델은 PR의 worktree가 아니라 이 폴더에서 돈다. worktree에는 PR이 넣은 심볼릭 링크와,
4
+ 샌드박스에서 돈 PR 코드가 남긴 링크·특수 파일이 있을 수 있다. 그래서
5
+
6
+ 1. worktree에서 일반 파일만 새 폴더로 복사한다. 링크, 특수 파일, 링크인 폴더 아래의 파일,
7
+ `.git`, 파이프라인 산출물은 복사하지 않는다.
8
+ 2. 그 폴더를 cwd로 claude를 부르고, PreToolUse 훅(`path_hook.py`)이 도구가 가리키는 경로의
9
+ 실제 위치가 폴더 밖이면 거부한다. CLI의 `--restricted` 제한 위에 한 겹을 더한다.
10
+ 3. 모델이 바꾼 것은 diff로 뽑아 원래 worktree에 `git apply`로 적용한다. git은 링크 너머의 경로에
11
+ 쓰지 않는다.
12
+ 4. 파이프라인 도구(규칙 검사, 테스트)를 주면 도구를 돌리기 직전에 그때까지 바뀐 것을 worktree에
13
+ 적용한다(`ModelFolder.sync`). 도구는 worktree에서 돌고, 호출이 끝나면 남은 것만 적용한다.
14
+
15
+ 훅이 실제로 돌았는지는 훅의 기록 줄 수로 확인한다. 모델이 도구를 불렀는데 기록이 그보다 적으면
16
+ 결과를 버린다.
17
+
18
+ 위반 판단(4.5)도 같은 폴더와 훅에서 읽기 도구(Read, Grep, Glob)로 PR의 코드를 읽는다
19
+ (`reading_folder`). 쓰기 도구가 없고, 폴더의 변경은 worktree에 적용하지 않는다.
20
+ """
21
+
22
+ import hashlib
23
+ import json
24
+ import logging
25
+ import os
26
+ import shlex
27
+ import stat
28
+ import subprocess
29
+ import sys
30
+ import tempfile
31
+ from collections.abc import Callable, Iterator, Mapping, Sequence
32
+ from contextlib import contextmanager
33
+ from dataclasses import dataclass, replace
34
+ from pathlib import Path
35
+ from typing import Final
36
+
37
+ from app.worker import repo
38
+ from app.worker.ai import claude_cli, tool_server
39
+ from app.worker.ai.claude_cli import AIErrorKind, ClaudeResult, StructuredResult
40
+ from app.worker.ai.tool_server import Handler
41
+ from app.worker.sandbox.container import OUT_DIR
42
+
43
+ # 이보다 큰 파일은 복사하지 않는다. 모델이 볼 일이 없고, 없는 파일은 diff에도 나오지 않는다
44
+ MAX_FILE_BYTES: Final = 5 * 1024 * 1024
45
+ GIT_TIMEOUT: Final = 120
46
+ _HOOK: Final = Path(__file__).with_name("path_hook.py")
47
+ # 스냅샷용 git에는 사용자·시스템 설정을 주지 않는다 (필터, 훅, 전역 무시 파일, 줄 끝 변환)
48
+ _GIT_ENV: Final = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
49
+ _GIT_SAFE: Final = (
50
+ "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "core.autocrlf=false",
51
+ "-c", "core.quotePath=false", "-c", "core.symlinks=true",
52
+ ) # fmt: skip
53
+
54
+ log = logging.getLogger(__name__)
55
+
56
+
57
+ class WorkdirError(RuntimeError):
58
+ """작업 폴더를 만들거나 diff를 뽑는 git이 실패했다."""
59
+
60
+
61
+ @dataclass
62
+ class ModelFolder:
63
+ work: Path # 모델의 cwd. 일반 파일만 있다
64
+ settings: Path # 훅을 등록한 설정 파일. work 밖에 있다
65
+ hook_log: Path
66
+ _git_dir: Path
67
+ _base_tree: str
68
+ _synced_tree: str = "" # worktree에 이미 적용한 폴더 상태. 비면 처음 상태(_base_tree)
69
+
70
+ def _tree(self) -> str:
71
+ _snapshot_git(self._git_dir, self.work, "add", "-A", "-f", ".")
72
+ return _snapshot_git(self._git_dir, self.work, "write-tree").decode().strip()
73
+
74
+ def _diff(self, old: str, new: str) -> bytes:
75
+ return _snapshot_git(
76
+ self._git_dir, self.work, "diff", "--binary", "--no-renames", "--no-color",
77
+ "--no-ext-diff", old, new,
78
+ ) # fmt: skip
79
+
80
+ def sync(self, worktree: Path) -> None:
81
+ """지금까지 폴더에서 바뀐 것 중 아직 worktree에 없는 것을 적용한다. 실패하면 GitError."""
82
+ synced, now = self._synced_tree or self._base_tree, self._tree()
83
+ if now != synced:
84
+ repo.apply_patch(worktree, self._diff(synced, now))
85
+ self._synced_tree = now
86
+
87
+ def rest(self) -> bytes:
88
+ """아직 worktree에 적용하지 않은 변경."""
89
+ return self._diff(self._synced_tree or self._base_tree, self._tree())
90
+
91
+ def unsync(self, worktree: Path) -> None:
92
+ """sync로 적용한 것을 worktree에서 되돌린다. 결과를 버릴 때 쓴다."""
93
+ synced = self._synced_tree or self._base_tree
94
+ if synced != self._base_tree:
95
+ repo.apply_patch(worktree, self._diff(self._base_tree, synced), reverse=True)
96
+ self._synced_tree = self._base_tree
97
+
98
+ def hook_calls(self) -> int:
99
+ try:
100
+ return sum(1 for line in self.hook_log.read_text().splitlines() if line.strip())
101
+ except OSError:
102
+ return 0
103
+
104
+ def patch(self) -> bytes:
105
+ """모델이 폴더에서 바꾼 것 (새 파일, 삭제 포함). 바뀐 것이 없으면 빈 값."""
106
+ _snapshot_git(self._git_dir, self.work, "add", "-A", "-f", ".")
107
+ return _snapshot_git(
108
+ self._git_dir, self.work, "diff", "--cached", "--binary", "--no-renames",
109
+ "--no-color", "--no-ext-diff", self._base_tree,
110
+ ) # fmt: skip
111
+
112
+
113
+ def _snapshot_git(git_dir: Path, work: Path, *args: str) -> bytes:
114
+ env = {"PATH": os.environ.get("PATH", os.defpath)} | _GIT_ENV
115
+ command = ["git", *_GIT_SAFE, f"--git-dir={git_dir}", f"--work-tree={work}", *args]
116
+ try:
117
+ proc = subprocess.run(
118
+ command, cwd=work, env=env, capture_output=True, timeout=GIT_TIMEOUT, check=False
119
+ )
120
+ except (OSError, subprocess.TimeoutExpired) as e:
121
+ raise WorkdirError(f"git {args[0]} 실행 실패: {e}") from e
122
+ if proc.returncode != 0:
123
+ detail = proc.stderr.decode(errors="replace").strip()[-500:]
124
+ raise WorkdirError(f"git {args[0]} 실패 ({proc.returncode}): {detail}")
125
+ return proc.stdout
126
+
127
+
128
+ def _safe_relative(rel: str) -> bool:
129
+ parts = rel.split("/")
130
+ return bool(rel) and not rel.startswith("/") and all(p not in ("", ".", "..") for p in parts)
131
+
132
+
133
+ def _real_directories(root: Path, rel: str) -> bool:
134
+ """rel의 상위 폴더가 모두 링크가 아닌 진짜 폴더인지."""
135
+ current = root
136
+ for part in rel.split("/")[:-1]:
137
+ current = current / part
138
+ try:
139
+ mode = os.lstat(current).st_mode
140
+ except OSError:
141
+ return False
142
+ if not stat.S_ISDIR(mode):
143
+ return False
144
+ return True
145
+
146
+
147
+ def _read_regular(source: Path) -> tuple[bytes, int] | None:
148
+ """일반 파일 하나의 (내용, 모드). 링크·특수 파일·너무 큰 파일은 None.
149
+
150
+ O_NOFOLLOW로 열고, 연 파일을 fstat으로 다시 확인한다(확인과 열기 사이에 바뀐 경우).
151
+ """
152
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
153
+ try:
154
+ fd = os.open(source, flags)
155
+ except OSError:
156
+ return None
157
+ try:
158
+ info = os.fstat(fd)
159
+ if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_FILE_BYTES:
160
+ return None
161
+ with os.fdopen(fd, "rb", closefd=False) as f:
162
+ data = f.read(MAX_FILE_BYTES + 1)
163
+ except OSError:
164
+ return None
165
+ finally:
166
+ os.close(fd)
167
+ return None if len(data) > MAX_FILE_BYTES else (data, info.st_mode)
168
+
169
+
170
+ def _copyable(worktree: Path, rel: str) -> tuple[bytes, int] | None:
171
+ """모델 폴더에 복사될 파일이면 (내용, 모드), 아니면 None. 안전한 상대 경로, `.git`과 파이프라인
172
+ 산출물이 아님, 상위 폴더가 모두 진짜 폴더, 일반 파일, 크기 상한 안."""
173
+ is_output = rel == OUT_DIR or rel.startswith(f"{OUT_DIR}/")
174
+ if (
175
+ is_output
176
+ or not _safe_relative(rel)
177
+ or rel.split("/")[0] == ".git"
178
+ or not _real_directories(worktree, rel)
179
+ ):
180
+ return None
181
+ return _read_regular(worktree / rel)
182
+
183
+
184
+ def regular_bytes(worktree: Path, rel: str) -> bytes | None:
185
+ """모델 폴더에 복사될 파일이면 그 내용, 아니면 None (복사와 같은 조건)."""
186
+ found = _copyable(worktree, rel)
187
+ return None if found is None else found[0]
188
+
189
+
190
+ def copy_regular_files(worktree: Path, paths: Sequence[str], work: Path) -> list[str]:
191
+ """paths(worktree 기준) 중 일반 파일만 work로 복사하고, 복사하지 않은 경로를 돌려준다."""
192
+ skipped: list[str] = []
193
+ for rel in paths:
194
+ found = _copyable(worktree, rel)
195
+ if found is None:
196
+ skipped.append(rel)
197
+ continue
198
+ data, mode = found
199
+ target = work / rel
200
+ target.parent.mkdir(parents=True, exist_ok=True)
201
+ target.write_bytes(data)
202
+ target.chmod(0o755 if mode & stat.S_IXUSR else 0o644)
203
+ return skipped
204
+
205
+
206
+ def path_digest(worktree: Path, rel: str, files: Sequence[str]) -> str:
207
+ """모델 폴더에서 rel이 가리키던 것의 해시. files는 `repo.list_files(worktree)`다.
208
+
209
+ 파일이면 그 내용, 폴더(또는 ".")면 그 아래 복사될 파일들의 경로와 내용, 아무것도 없으면 "-".
210
+ 위반 판단이 저장한 답을 다시 쓸 때 모델이 읽은 곳이 그대로인지 맞춰 보는 데 쓴다 (4.5)."""
211
+ if rel in files:
212
+ data = regular_bytes(worktree, rel)
213
+ return "-" if data is None else hashlib.sha256(data).hexdigest()
214
+ prefix = "" if rel == "." else rel.rstrip("/") + "/"
215
+ entries = []
216
+ for path in files:
217
+ if path.startswith(prefix):
218
+ data = regular_bytes(worktree, path)
219
+ if data is not None:
220
+ entries.append([path, hashlib.sha256(data).hexdigest()])
221
+ if not entries:
222
+ return "-"
223
+ return hashlib.sha256(json.dumps(entries, ensure_ascii=False).encode()).hexdigest()
224
+
225
+
226
+ def hook_settings(work: Path, hook_log: Path, python: str = sys.executable) -> str:
227
+ """경로 감시 훅을 모든 도구에 거는 설정 파일의 내용."""
228
+ command = shlex.join([python, "-I", str(_HOOK), str(work), str(hook_log)])
229
+ hook = {"matcher": "*", "hooks": [{"type": "command", "command": command}]}
230
+ return json.dumps({"hooks": {"PreToolUse": [hook]}})
231
+
232
+
233
+ @contextmanager
234
+ def model_folder(worktree: Path, paths: Sequence[str]) -> Iterator[ModelFolder]:
235
+ """worktree의 일반 파일만 든 새 폴더를 만들고, 끝나면 지운다."""
236
+ with tempfile.TemporaryDirectory(prefix="claude-model-") as tmp:
237
+ root = Path(tmp).resolve() # 훅은 실제 경로로 비교한다 (macOS의 /tmp는 링크다)
238
+ work, git_dir = root / "work", root / "git"
239
+ work.mkdir()
240
+ skipped = copy_regular_files(worktree, paths, work)
241
+ if skipped:
242
+ log.info("모델 폴더에 복사하지 않은 경로 %d개: %s", len(skipped), skipped[:5])
243
+ _snapshot_git(git_dir, work, "init", "-q")
244
+ _snapshot_git(git_dir, work, "add", "-A", "-f", ".")
245
+ tree = _snapshot_git(git_dir, work, "write-tree").decode().strip()
246
+ settings, hook_log = root / "settings.json", root / "hook.log"
247
+ settings.write_text(hook_settings(work, hook_log))
248
+ yield ModelFolder(work, settings, hook_log, git_dir, tree)
249
+
250
+
251
+ def _failed(result: ClaudeResult, kind: AIErrorKind, detail: str) -> ClaudeResult:
252
+ return replace(result, ok=False, error=kind, detail=detail)
253
+
254
+
255
+ # (사용자 메시지, *, system_prompt, schema, model, max_budget_usd, ...) → 결과.
256
+ # `claude_cli.run_structured`의 모양이다
257
+ AsksModel = Callable[..., StructuredResult]
258
+
259
+
260
+ @contextmanager
261
+ def reading_folder(worktree: Path, ask: AsksModel) -> Iterator[AsksModel]:
262
+ """worktree의 일반 파일만 복사한 모델 폴더를 열고, 그 폴더에서 읽기 도구로 묻는 함수를 준다.
263
+
264
+ 폴더 하나를 블록 안의 호출들이 같이 쓰고 블록이 끝나면 지운다. 모델에게는 쓰기 도구가 없고,
265
+ 폴더에서 무엇이 바뀌어도 worktree에 적용하지 않는다. 호출마다 경로 감시 훅의 기록이 모델이 부른
266
+ 도구 수만큼 늘었는지 보고, 모자라면 답을 버리고 TOOLS 오류로 돌려준다(수정 작성과 같은 확인).
267
+ """
268
+ with model_folder(worktree, repo.list_files(worktree)) as folder:
269
+ where = claude_cli.ReadFolder(folder.work, folder.settings)
270
+
271
+ def ask_in_folder(prompt: str, **kwargs: object) -> StructuredResult:
272
+ before = folder.hook_calls()
273
+ result = ask(prompt, read_in=where, **kwargs)
274
+ ran = folder.hook_calls() - before
275
+ if result.error != AIErrorKind.TOOLS and ran < result.tool_uses:
276
+ detail = f"경로 감시 훅이 돌지 않음: 도구 호출 {result.tool_uses}건, 훅 {ran}건"
277
+ log.error("%s. 위반 판단의 답을 버린다", detail)
278
+ return replace(result, ok=False, error=AIErrorKind.TOOLS, data=None, detail=detail)
279
+ return result
280
+
281
+ yield ask_in_folder
282
+
283
+
284
+ def _synced_first(folder: ModelFolder, worktree: Path, handler: Handler) -> Handler:
285
+ def run(args: Mapping[str, str]) -> str:
286
+ folder.sync(worktree)
287
+ return handler(args)
288
+
289
+ return run
290
+
291
+
292
+ def run_in_model_folder(
293
+ worktree: Path,
294
+ prompt: str,
295
+ *,
296
+ run: Callable[..., ClaudeResult] | None = None,
297
+ tools: Mapping[str, Handler] | None = None,
298
+ **kwargs: object,
299
+ ) -> ClaudeResult:
300
+ """모델 전용 폴더에서 claude를 한 번 실행하고, 바뀐 것을 worktree에 diff로 적용한다.
301
+
302
+ tools(이름 → 파이프라인 도구)가 있으면 도구 서버를 열어 `fix_tools` 모양으로 부른다. 도구는
303
+ 돌기 직전에 폴더의 지금 상태를 worktree에 맞춘다. 도구 호출 수와 시간은 결과의 `tool_usage`다.
304
+ 훅이 돌지 않았으면(도구 호출 수보다 기록이 적으면) 적용한 것까지 되돌리고 TOOLS 오류로 돌려준다.
305
+ 적용에 실패하면 APPLY 오류다. 적용한 diff 전체는 결과의 `applied`에 담는다(수정 작성이 저장해
306
+ 같은 입력에 다시 쓴다). run은 테스트용이다.
307
+ """
308
+ run = run or claude_cli.run_claude
309
+ with model_folder(worktree, repo.list_files(worktree)) as folder:
310
+ if tools:
311
+ wrapped = {name: _synced_first(folder, worktree, h) for name, h in tools.items()}
312
+ with tool_server.serving(wrapped) as server:
313
+ result = run(folder.work, prompt, settings=folder.settings,
314
+ mcp_config=server.config, **kwargs) # fmt: skip
315
+ result = replace(result, tool_usage=server.usage())
316
+ else:
317
+ result = run(folder.work, prompt, settings=folder.settings, **kwargs)
318
+ hook_calls = folder.hook_calls()
319
+ if result.error != AIErrorKind.TOOLS and hook_calls < result.tool_uses:
320
+ detail = f"경로 감시 훅이 돌지 않음: 도구 호출 {result.tool_uses}건, 훅 {hook_calls}건"
321
+ log.error("%s. 모델이 바꾼 것을 버린다", detail)
322
+ result = _failed(result, AIErrorKind.TOOLS, detail)
323
+ if result.error == AIErrorKind.TOOLS:
324
+ folder.unsync(worktree)
325
+ return result
326
+ patch, rest = folder.patch(), folder.rest()
327
+ try:
328
+ if rest:
329
+ repo.apply_patch(worktree, rest)
330
+ except repo.GitError as e:
331
+ log.warning("모델의 변경을 worktree에 적용하지 못함: %s", e)
332
+ return _failed(result, AIErrorKind.APPLY, f"변경을 적용하지 못함: {e}")
333
+ return replace(result, applied=patch) if patch else result