repoflow-mcp 0.2.0__py3-none-any.whl
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.
- repoflow/__init__.py +1 -0
- repoflow/core/__init__.py +0 -0
- repoflow/core/config.py +25 -0
- repoflow/core/github.py +79 -0
- repoflow/core/hooks.py +84 -0
- repoflow/core/models.py +126 -0
- repoflow/core/proc.py +91 -0
- repoflow/core/store.py +65 -0
- repoflow/core/workspace.py +83 -0
- repoflow/discover/__init__.py +0 -0
- repoflow/discover/parsers.py +329 -0
- repoflow/discover/tools.py +467 -0
- repoflow/guards.py +246 -0
- repoflow/policy/__init__.py +1 -0
- repoflow/policy/playbook.py +1168 -0
- repoflow/policy/tools.py +112 -0
- repoflow/sandbox/__init__.py +0 -0
- repoflow/sandbox/docker.py +247 -0
- repoflow/sandbox/tools.py +42 -0
- repoflow/server.py +55 -0
- repoflow/teach/__init__.py +0 -0
- repoflow/teach/cards.py +161 -0
- repoflow/teach/ledger.py +241 -0
- repoflow/teach/prompts.py +37 -0
- repoflow/teach/tools.py +178 -0
- repoflow/understand/__init__.py +0 -0
- repoflow/understand/analysis.py +179 -0
- repoflow/understand/graph.py +251 -0
- repoflow/understand/metrics.py +153 -0
- repoflow/understand/scan.py +223 -0
- repoflow/understand/tools.py +88 -0
- repoflow/understand/walk.py +119 -0
- repoflow_mcp-0.2.0.dist-info/METADATA +237 -0
- repoflow_mcp-0.2.0.dist-info/RECORD +37 -0
- repoflow_mcp-0.2.0.dist-info/WHEEL +4 -0
- repoflow_mcp-0.2.0.dist-info/entry_points.txt +2 -0
- repoflow_mcp-0.2.0.dist-info/licenses/LICENSE +21 -0
repoflow/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
|
File without changes
|
repoflow/core/config.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Settings from environment variables. Keep all knobs here."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def workspace_dir() -> Path:
|
|
10
|
+
"""Where repos are cloned. REPOFLOW_WORKSPACE overrides ~/repoflow-workspace."""
|
|
11
|
+
p = Path(os.environ.get("REPOFLOW_WORKSPACE", Path.home() / "repoflow-workspace"))
|
|
12
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
13
|
+
return p
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def sandbox_mode() -> str:
|
|
17
|
+
"""'docker' (default when available), 'local', or 'off'. See sandbox/docker.py."""
|
|
18
|
+
return os.environ.get("REPOFLOW_SANDBOX", "docker").lower()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def default_timeout_s() -> int:
|
|
22
|
+
return int(os.environ.get("REPOFLOW_TIMEOUT_S", "900"))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
MAX_OUTPUT_CHARS = 12_000
|
repoflow/core/github.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""GitHub auth + HTTP client. Token is optional for reads, required for writes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
from functools import lru_cache
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .workspace import RepoFlowError
|
|
14
|
+
|
|
15
|
+
API = "https://api.github.com"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@lru_cache(maxsize=1)
|
|
19
|
+
def token() -> str | None:
|
|
20
|
+
"""GITHUB_TOKEN / GH_TOKEN env, else `gh auth token`. Never log or return this.
|
|
21
|
+
|
|
22
|
+
Cached for the process lifetime. Tests should monkeypatch this function (or call
|
|
23
|
+
token.cache_clear() after changing env vars) rather than only setting GITHUB_TOKEN."""
|
|
24
|
+
t = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
|
|
25
|
+
if t:
|
|
26
|
+
return t.strip()
|
|
27
|
+
if shutil.which("gh"):
|
|
28
|
+
try:
|
|
29
|
+
p = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, timeout=15)
|
|
30
|
+
if p.returncode == 0 and p.stdout.strip():
|
|
31
|
+
return p.stdout.strip()
|
|
32
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
33
|
+
pass
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def require_token() -> str:
|
|
38
|
+
t = token()
|
|
39
|
+
if not t:
|
|
40
|
+
raise RepoFlowError(
|
|
41
|
+
"No GitHub token. Run `gh auth login` or set GITHUB_TOKEN, then restart the MCP server."
|
|
42
|
+
)
|
|
43
|
+
return t
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def client() -> httpx.Client:
|
|
47
|
+
headers = {
|
|
48
|
+
"Accept": "application/vnd.github+json",
|
|
49
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
50
|
+
"User-Agent": "repoflow-mcp",
|
|
51
|
+
}
|
|
52
|
+
t = token()
|
|
53
|
+
if t:
|
|
54
|
+
headers["Authorization"] = f"Bearer {t}"
|
|
55
|
+
return httpx.Client(base_url=API, headers=headers, timeout=30)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def check(resp: httpx.Response) -> dict | list:
|
|
59
|
+
if resp.status_code >= 400:
|
|
60
|
+
msg = resp.text[:500]
|
|
61
|
+
t = token()
|
|
62
|
+
if t: # never echo the token back, even if the API response contains it
|
|
63
|
+
msg = msg.replace(t, "***")
|
|
64
|
+
if resp.status_code in (401, 403) and "rate limit" in msg.lower():
|
|
65
|
+
raise RepoFlowError("GitHub rate limit hit. Log in (`gh auth login`) for higher limits, or wait.")
|
|
66
|
+
raise RepoFlowError(f"GitHub API {resp.status_code}: {msg}")
|
|
67
|
+
return resp.json() if resp.content else {}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def git_auth_env() -> dict[str, str]:
|
|
71
|
+
"""Env that makes git authenticate to github.com without storing the token in .git/config
|
|
72
|
+
or putting it on the command line."""
|
|
73
|
+
t = require_token()
|
|
74
|
+
basic = base64.b64encode(f"x-access-token:{t}".encode()).decode()
|
|
75
|
+
return {
|
|
76
|
+
"GIT_CONFIG_COUNT": "1",
|
|
77
|
+
"GIT_CONFIG_KEY_0": "http.https://github.com/.extraheader",
|
|
78
|
+
"GIT_CONFIG_VALUE_0": f"AUTHORIZATION: basic {basic}",
|
|
79
|
+
}
|
repoflow/core/hooks.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Extension points so add-on packages can plug into RepoFlow without RepoFlow importing them.
|
|
2
|
+
|
|
3
|
+
Two hooks:
|
|
4
|
+
- untrusted-run guards: a (before, after) pair called around every run of target-repo code
|
|
5
|
+
(`core.proc.run_untrusted`). `before()` returns a state, `after(state)` checks it and may raise.
|
|
6
|
+
- record: called by policy checks that want to record a result for a finding. Without a
|
|
7
|
+
registered recorder nothing is stored and the result says so.
|
|
8
|
+
|
|
9
|
+
Stdlib only. Nothing is registered by default.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import threading
|
|
15
|
+
from collections.abc import Callable, Iterator
|
|
16
|
+
from contextlib import contextmanager
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
Before = Callable[[], Any]
|
|
20
|
+
After = Callable[[Any], None]
|
|
21
|
+
Recorder = Callable[[str, str, str, dict], Any]
|
|
22
|
+
|
|
23
|
+
NOT_RECORDED = {"attested": False, "reason": "not recorded in Lite"}
|
|
24
|
+
|
|
25
|
+
_LOCK = threading.Lock()
|
|
26
|
+
_GUARDS: list[tuple[Before, After]] = []
|
|
27
|
+
_RECORDER: Recorder | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def add_untrusted_guard(before: Before, after: After) -> None:
|
|
31
|
+
"""Register a (before, after) pair to wrap every untrusted run. Adding the same pair twice is a no-op."""
|
|
32
|
+
if not (callable(before) and callable(after)):
|
|
33
|
+
raise TypeError("before and after must be callable")
|
|
34
|
+
with _LOCK:
|
|
35
|
+
if not any(b is before and a is after for b, a in _GUARDS):
|
|
36
|
+
_GUARDS.append((before, after))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def untrusted_guards() -> list[tuple[Before, After]]:
|
|
40
|
+
with _LOCK:
|
|
41
|
+
return list(_GUARDS)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@contextmanager
|
|
45
|
+
def untrusted_run() -> Iterator[None]:
|
|
46
|
+
"""Wrap a run of target-repo code: call every `before`, run the body, then every `after`.
|
|
47
|
+
The `after` checks run even if the body raised (fail closed)."""
|
|
48
|
+
states = [(after, before()) for before, after in untrusted_guards()]
|
|
49
|
+
try:
|
|
50
|
+
yield
|
|
51
|
+
finally:
|
|
52
|
+
for after, state in states:
|
|
53
|
+
after(state)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def set_attest(fn: Recorder | None) -> None:
|
|
57
|
+
"""Register the recorder `fn(repo, finding_id, kind, payload)`; None removes it."""
|
|
58
|
+
global _RECORDER
|
|
59
|
+
if fn is not None and not callable(fn):
|
|
60
|
+
raise TypeError("fn must be callable or None")
|
|
61
|
+
with _LOCK:
|
|
62
|
+
_RECORDER = fn
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def get_attest() -> Recorder | None:
|
|
66
|
+
with _LOCK:
|
|
67
|
+
return _RECORDER
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def attest(repo: str, finding_id: str, kind: str, payload: dict) -> dict:
|
|
71
|
+
"""Record `payload` for a finding through the registered recorder, if any."""
|
|
72
|
+
fn = get_attest()
|
|
73
|
+
if fn is None:
|
|
74
|
+
return dict(NOT_RECORDED)
|
|
75
|
+
rec = fn(repo, finding_id, kind, payload)
|
|
76
|
+
return {"attested": True, "kind": kind, "binding": rec.get("binding") if isinstance(rec, dict) else None}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def reset() -> None:
|
|
80
|
+
"""Remove every registered hook (for tests)."""
|
|
81
|
+
global _RECORDER
|
|
82
|
+
with _LOCK:
|
|
83
|
+
_GUARDS.clear()
|
|
84
|
+
_RECORDER = None
|
repoflow/core/models.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Shared data shapes. Every module returns these (via .to_dict()) so tools compose."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
Severity = Literal["low", "medium", "high", "critical"]
|
|
9
|
+
Confidence = Literal["low", "medium", "high"]
|
|
10
|
+
FindingStatus = Literal["candidate", "confirmed", "rejected", "reported", "fixed"]
|
|
11
|
+
FindingSource = Literal["test", "static", "fuzz", "flaky", "manual"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _Dict:
|
|
15
|
+
def to_dict(self) -> dict:
|
|
16
|
+
return asdict(self) # type: ignore[arg-type]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Location(_Dict):
|
|
21
|
+
file: str # path relative to repo root, forward slashes
|
|
22
|
+
line: int
|
|
23
|
+
end_line: int | None = None
|
|
24
|
+
function: str | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Evidence(_Dict):
|
|
29
|
+
"""Everything needed for someone else to reproduce a claim."""
|
|
30
|
+
|
|
31
|
+
commit: str # repo HEAD sha when evidence was captured
|
|
32
|
+
command: str # exact command that was run
|
|
33
|
+
exit_code: int | None = None
|
|
34
|
+
output_excerpt: str = "" # trimmed stdout/stderr
|
|
35
|
+
test_id: str | None = None # e.g. tests/test_x.py::test_y
|
|
36
|
+
captured_at: str = "" # ISO-8601 UTC
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class FixOption(_Dict):
|
|
41
|
+
title: str
|
|
42
|
+
description: str
|
|
43
|
+
tradeoff: str
|
|
44
|
+
recommended: bool = False
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Finding(_Dict):
|
|
49
|
+
id: str # "F-001", assigned by FindingStore
|
|
50
|
+
repo: str # "owner/name"
|
|
51
|
+
title: str
|
|
52
|
+
source: FindingSource
|
|
53
|
+
severity: Severity = "medium"
|
|
54
|
+
confidence: Confidence = "medium"
|
|
55
|
+
status: FindingStatus = "candidate"
|
|
56
|
+
location: Location | None = None
|
|
57
|
+
introduced_in: str | None = None # commit sha from blame/bisect
|
|
58
|
+
what: str = "" # symptom, plain words
|
|
59
|
+
why: str = "" # root cause
|
|
60
|
+
repro: str = "" # command/test that shows it
|
|
61
|
+
fix_options: list[FixOption] = field(default_factory=list)
|
|
62
|
+
lesson: str = "" # the general concept a junior should learn
|
|
63
|
+
evidence: list[Evidence] = field(default_factory=list)
|
|
64
|
+
issue_url: str | None = None
|
|
65
|
+
pr_url: str | None = None
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_dict(cls, d: dict) -> Finding:
|
|
69
|
+
d = dict(d)
|
|
70
|
+
if d.get("location"):
|
|
71
|
+
d["location"] = Location(**d["location"])
|
|
72
|
+
d["fix_options"] = [FixOption(**f) for f in d.get("fix_options", [])]
|
|
73
|
+
d["evidence"] = [Evidence(**e) for e in d.get("evidence", [])]
|
|
74
|
+
return cls(**d)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class TestFailure(_Dict):
|
|
79
|
+
test_id: str
|
|
80
|
+
outcome: Literal["failed", "error"]
|
|
81
|
+
message: str
|
|
82
|
+
location: Location | None = None # deepest frame inside the repo (not tests) if known
|
|
83
|
+
traceback_excerpt: str = ""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class TestRunResult(_Dict):
|
|
88
|
+
command: str
|
|
89
|
+
commit: str
|
|
90
|
+
passed: int
|
|
91
|
+
failed: int
|
|
92
|
+
errors: int
|
|
93
|
+
skipped: int
|
|
94
|
+
duration_s: float
|
|
95
|
+
failures: list[TestFailure] = field(default_factory=list)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class SuspiciousLine(_Dict):
|
|
100
|
+
location: Location
|
|
101
|
+
score: float # 0..1, higher = more suspicious
|
|
102
|
+
failed_cover: int # failing tests executing this line
|
|
103
|
+
passed_cover: int # passing tests executing this line
|
|
104
|
+
code: str = ""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class ModuleInfo(_Dict):
|
|
109
|
+
path: str
|
|
110
|
+
lines: int
|
|
111
|
+
imports: list[str] = field(default_factory=list)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class RepoMap(_Dict):
|
|
116
|
+
repo: str
|
|
117
|
+
commit: str
|
|
118
|
+
root: str # local absolute path
|
|
119
|
+
languages: dict[str, int] # language -> lines
|
|
120
|
+
packages: list[str]
|
|
121
|
+
entry_points: list[str]
|
|
122
|
+
test_framework: str | None
|
|
123
|
+
test_command: str | None
|
|
124
|
+
modules: list[ModuleInfo] = field(default_factory=list)
|
|
125
|
+
readme_summary: str = ""
|
|
126
|
+
notes: list[str] = field(default_factory=list)
|
repoflow/core/proc.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""The ONE way RepoFlow runs external commands. Never use shell=True anywhere."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .config import MAX_OUTPUT_CHARS, default_timeout_s
|
|
12
|
+
|
|
13
|
+
SECRET_ENV = ("GITHUB_TOKEN", "GH_TOKEN", "GITHUB_PAT", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN")
|
|
14
|
+
"""Credentials never passed to target-repo code."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class ProcResult:
|
|
19
|
+
command: list[str]
|
|
20
|
+
exit_code: int | None # None on timeout
|
|
21
|
+
stdout: str
|
|
22
|
+
stderr: str
|
|
23
|
+
duration_s: float
|
|
24
|
+
timed_out: bool = False
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def ok(self) -> bool:
|
|
28
|
+
return self.exit_code == 0
|
|
29
|
+
|
|
30
|
+
def combined(self, limit: int = MAX_OUTPUT_CHARS) -> str:
|
|
31
|
+
return trim(self.stdout + ("\n" + self.stderr if self.stderr else ""), limit)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def trim(text: str, limit: int = MAX_OUTPUT_CHARS) -> str:
|
|
35
|
+
"""Keep head and tail; failures usually show at the end."""
|
|
36
|
+
if len(text) <= limit:
|
|
37
|
+
return text
|
|
38
|
+
half = limit // 2
|
|
39
|
+
return text[:half] + f"\n... [{len(text) - limit} chars trimmed] ...\n" + text[-half:]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def run(
|
|
43
|
+
cmd: list[str],
|
|
44
|
+
cwd: str | Path | None = None,
|
|
45
|
+
timeout_s: int | None = None,
|
|
46
|
+
env: dict[str, str] | None = None,
|
|
47
|
+
unset_env: tuple[str, ...] = (),
|
|
48
|
+
) -> ProcResult:
|
|
49
|
+
"""Run trusted tooling (git, uv, docker CLI) on the host. `unset_env` names host variables
|
|
50
|
+
that must not reach the child process (e.g. credentials)."""
|
|
51
|
+
full_env = {**os.environ, **(env or {})}
|
|
52
|
+
for k in unset_env:
|
|
53
|
+
full_env.pop(k, None)
|
|
54
|
+
full_env.setdefault("GIT_TERMINAL_PROMPT", "0")
|
|
55
|
+
start = time.monotonic()
|
|
56
|
+
try:
|
|
57
|
+
p = subprocess.run(
|
|
58
|
+
cmd,
|
|
59
|
+
cwd=cwd,
|
|
60
|
+
env=full_env,
|
|
61
|
+
capture_output=True,
|
|
62
|
+
text=True,
|
|
63
|
+
encoding="utf-8",
|
|
64
|
+
errors="replace",
|
|
65
|
+
timeout=timeout_s or default_timeout_s(),
|
|
66
|
+
)
|
|
67
|
+
return ProcResult(cmd, p.returncode, p.stdout, p.stderr, time.monotonic() - start)
|
|
68
|
+
except subprocess.TimeoutExpired as e:
|
|
69
|
+
out = e.stdout.decode(errors="replace") if isinstance(e.stdout, bytes) else (e.stdout or "")
|
|
70
|
+
err = e.stderr.decode(errors="replace") if isinstance(e.stderr, bytes) else (e.stderr or "")
|
|
71
|
+
return ProcResult(cmd, None, out, err, time.monotonic() - start, timed_out=True)
|
|
72
|
+
except FileNotFoundError as e:
|
|
73
|
+
return ProcResult(cmd, 127, "", str(e), time.monotonic() - start)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def run_untrusted(
|
|
77
|
+
cmd: list[str],
|
|
78
|
+
repo_root: str | Path,
|
|
79
|
+
timeout_s: int | None = None,
|
|
80
|
+
network: bool = False,
|
|
81
|
+
) -> ProcResult:
|
|
82
|
+
"""Run code FROM THE TARGET REPO (tests, installs).
|
|
83
|
+
|
|
84
|
+
Dispatches to the sandbox (Docker) unless REPOFLOW_SANDBOX=local.
|
|
85
|
+
`cmd` runs with cwd = repo root. Implemented in repoflow.sandbox.docker.
|
|
86
|
+
"""
|
|
87
|
+
from repoflow.core import hooks
|
|
88
|
+
from repoflow.sandbox.docker import run_sandboxed # late import: module owned by sandbox agent
|
|
89
|
+
|
|
90
|
+
with hooks.untrusted_run(): # add-ons may check that repo code changed nothing it must not
|
|
91
|
+
return run_sandboxed(cmd, Path(repo_root), timeout_s=timeout_s, network=network)
|
repoflow/core/store.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Evidence ledger: findings persisted per repo at <workspace>/.repoflow/<owner>__<name>/findings.json."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import threading
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .config import workspace_dir
|
|
10
|
+
from .models import Finding
|
|
11
|
+
from .workspace import RepoFlowError, parse_repo
|
|
12
|
+
|
|
13
|
+
_LOCK = threading.Lock()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FindingStore:
|
|
17
|
+
def __init__(self, repo: str):
|
|
18
|
+
self.repo = parse_repo(repo)
|
|
19
|
+
d = workspace_dir() / ".repoflow" / self.repo.replace("/", "__")
|
|
20
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
self.dir = d
|
|
22
|
+
self.path = d / "findings.json"
|
|
23
|
+
|
|
24
|
+
def _load(self) -> list[Finding]:
|
|
25
|
+
if not self.path.exists():
|
|
26
|
+
return []
|
|
27
|
+
return [Finding.from_dict(x) for x in json.loads(self.path.read_text(encoding="utf-8"))]
|
|
28
|
+
|
|
29
|
+
def _save(self, items: list[Finding]) -> None:
|
|
30
|
+
tmp = self.path.with_suffix(".tmp")
|
|
31
|
+
tmp.write_text(json.dumps([f.to_dict() for f in items], indent=2), encoding="utf-8")
|
|
32
|
+
tmp.replace(self.path)
|
|
33
|
+
|
|
34
|
+
def all(self) -> list[Finding]:
|
|
35
|
+
with _LOCK:
|
|
36
|
+
return self._load()
|
|
37
|
+
|
|
38
|
+
def get(self, finding_id: str) -> Finding:
|
|
39
|
+
for f in self.all():
|
|
40
|
+
if f.id == finding_id:
|
|
41
|
+
return f
|
|
42
|
+
raise RepoFlowError(f"No finding {finding_id} for {self.repo}. Call list_findings to see ids.")
|
|
43
|
+
|
|
44
|
+
def add(self, finding: Finding) -> Finding:
|
|
45
|
+
with _LOCK:
|
|
46
|
+
items = self._load()
|
|
47
|
+
finding.id = f"F-{len(items) + 1:03d}"
|
|
48
|
+
finding.repo = self.repo
|
|
49
|
+
items.append(finding)
|
|
50
|
+
self._save(items)
|
|
51
|
+
return finding
|
|
52
|
+
|
|
53
|
+
def update(self, finding: Finding) -> Finding:
|
|
54
|
+
with _LOCK:
|
|
55
|
+
items = self._load()
|
|
56
|
+
for i, f in enumerate(items):
|
|
57
|
+
if f.id == finding.id:
|
|
58
|
+
items[i] = finding
|
|
59
|
+
self._save(items)
|
|
60
|
+
return finding
|
|
61
|
+
raise RepoFlowError(f"No finding {finding.id} for {self.repo}.")
|
|
62
|
+
|
|
63
|
+
def artifact_path(self, name: str) -> Path:
|
|
64
|
+
"""Scratch place for module artifacts (repo map json, coverage data, etc.)."""
|
|
65
|
+
return self.dir / name
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Repo naming, local paths, cloning, current commit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from mcp.server.mcpserver.exceptions import ResourceError, ToolError
|
|
9
|
+
|
|
10
|
+
from .config import workspace_dir
|
|
11
|
+
from .proc import run
|
|
12
|
+
|
|
13
|
+
_REPO_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RepoFlowError(ToolError, ResourceError):
|
|
17
|
+
"""Raise for user-facing errors; message must say what to do next.
|
|
18
|
+
|
|
19
|
+
Subclasses the SDK's anticipated-error types so the message reaches the client
|
|
20
|
+
(any other exception is reported only as a generic "Error executing tool")."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_repo(repo: str) -> str:
|
|
24
|
+
"""Accept 'owner/name' or a github.com URL; return 'owner/name'."""
|
|
25
|
+
repo = repo.strip().removesuffix(".git").rstrip("/")
|
|
26
|
+
m = re.match(r"^(?:https?://)?(?:www\.)?github\.com/([^/]+/[^/]+)", repo)
|
|
27
|
+
if m:
|
|
28
|
+
repo = m.group(1)
|
|
29
|
+
if not _REPO_RE.match(repo) or ".." in repo:
|
|
30
|
+
raise RepoFlowError(f"'{repo}' is not a valid repo. Use 'owner/name', e.g. 'pallets/flask'.")
|
|
31
|
+
return repo
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def repo_path(repo: str) -> Path:
|
|
35
|
+
owner, name = parse_repo(repo).split("/")
|
|
36
|
+
return workspace_dir() / owner / name
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def ensure_cloned(repo: str, depth: int | None = None) -> Path:
|
|
40
|
+
"""Clone the upstream public repo if missing. Returns local path. Full history by default
|
|
41
|
+
(blame/bisect need it)."""
|
|
42
|
+
repo = parse_repo(repo)
|
|
43
|
+
path = repo_path(repo)
|
|
44
|
+
if (path / ".git").exists():
|
|
45
|
+
_exclude_scratch(path) # idempotent; adds patterns introduced after the clone was made
|
|
46
|
+
return path
|
|
47
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
cmd = ["git", "clone", "--filter=blob:none"]
|
|
49
|
+
if depth:
|
|
50
|
+
cmd += ["--depth", str(depth)]
|
|
51
|
+
cmd += [f"https://github.com/{repo}.git", str(path)]
|
|
52
|
+
r = run(cmd, timeout_s=1800)
|
|
53
|
+
if not r.ok:
|
|
54
|
+
raise RepoFlowError(f"Clone of {repo} failed: {r.combined(2000)}")
|
|
55
|
+
_exclude_scratch(path)
|
|
56
|
+
return path
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
SCRATCH_PATTERNS = (".rfvenv/", ".repoflow-*", "*.egg-info/") # egg-info: pip install -e in the sandbox
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _exclude_scratch(path: Path) -> None:
|
|
63
|
+
"""Keep RepoFlow's env and scratch files out of `git status` and commits (local-only ignore)."""
|
|
64
|
+
exclude = path / ".git" / "info" / "exclude"
|
|
65
|
+
try:
|
|
66
|
+
exclude.parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
current = exclude.read_text(encoding="utf-8") if exclude.exists() else ""
|
|
68
|
+
missing = [p for p in SCRATCH_PATTERNS if p not in current.splitlines()]
|
|
69
|
+
if missing:
|
|
70
|
+
sep = "" if not current or current.endswith("\n") else "\n"
|
|
71
|
+
exclude.write_text(current + sep + "\n".join(missing) + "\n", encoding="utf-8")
|
|
72
|
+
except OSError:
|
|
73
|
+
pass # best effort; contribute also excludes these paths when staging
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def head_commit(path: Path) -> str:
|
|
77
|
+
r = run(["git", "rev-parse", "HEAD"], cwd=path)
|
|
78
|
+
return r.stdout.strip() if r.ok else "unknown"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def rel(path: Path, root: Path) -> str:
|
|
82
|
+
"""Repo-relative, forward slashes."""
|
|
83
|
+
return path.resolve().relative_to(root.resolve()).as_posix()
|
|
File without changes
|