vibe-engine 0.1.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.
Files changed (66) hide show
  1. vibe_engine/__init__.py +1 -0
  2. vibe_engine/agents.py +190 -0
  3. vibe_engine/architecture.py +213 -0
  4. vibe_engine/astgrep.py +151 -0
  5. vibe_engine/baseline.py +121 -0
  6. vibe_engine/checks/__init__.py +0 -0
  7. vibe_engine/checks/banned.py +250 -0
  8. vibe_engine/checks/boundaries.py +53 -0
  9. vibe_engine/checks/comments.py +131 -0
  10. vibe_engine/checks/doclinks.py +155 -0
  11. vibe_engine/checks/jscomments.py +110 -0
  12. vibe_engine/checks/mypy.py +125 -0
  13. vibe_engine/checks/ruff.py +59 -0
  14. vibe_engine/checks/shared.py +36 -0
  15. vibe_engine/checks/shellcheck.py +52 -0
  16. vibe_engine/checks/shellcomments.py +99 -0
  17. vibe_engine/checks/strings.py +74 -0
  18. vibe_engine/cli.py +501 -0
  19. vibe_engine/codex_status.py +81 -0
  20. vibe_engine/config.py +734 -0
  21. vibe_engine/detect.py +231 -0
  22. vibe_engine/doctor.py +226 -0
  23. vibe_engine/engine_dir.py +17 -0
  24. vibe_engine/events.py +88 -0
  25. vibe_engine/evidence.py +145 -0
  26. vibe_engine/export.py +235 -0
  27. vibe_engine/files.py +124 -0
  28. vibe_engine/fixing.py +180 -0
  29. vibe_engine/freeze.py +42 -0
  30. vibe_engine/guard.py +196 -0
  31. vibe_engine/hook.py +509 -0
  32. vibe_engine/jsresolve.py +182 -0
  33. vibe_engine/languages/__init__.py +19 -0
  34. vibe_engine/languages/base.py +27 -0
  35. vibe_engine/languages/js.py +131 -0
  36. vibe_engine/languages/python.py +70 -0
  37. vibe_engine/languages/shell.py +45 -0
  38. vibe_engine/loosening.py +206 -0
  39. vibe_engine/model.py +37 -0
  40. vibe_engine/modules.py +34 -0
  41. vibe_engine/onboarding.py +136 -0
  42. vibe_engine/presets/test-integrity.toml +55 -0
  43. vibe_engine/report.py +50 -0
  44. vibe_engine/rules_edit.py +195 -0
  45. vibe_engine/rules_table.py +122 -0
  46. vibe_engine/rules_verify.py +125 -0
  47. vibe_engine/runner.py +276 -0
  48. vibe_engine/scaffold.py +232 -0
  49. vibe_engine/staged.py +184 -0
  50. vibe_engine/statefiles.py +50 -0
  51. vibe_engine/stats.py +236 -0
  52. vibe_engine/templates/engine.toml +53 -0
  53. vibe_engine/templates/feature-map.md +26 -0
  54. vibe_engine/templates/report.html +796 -0
  55. vibe_engine/templates/skills/correction-to-rule/SKILL.md +104 -0
  56. vibe_engine/templates/skills/verify-feature/SKILL.md +30 -0
  57. vibe_engine/templates/workflow.yml +28 -0
  58. vibe_engine/touch.py +139 -0
  59. vibe_engine/trend.py +53 -0
  60. vibe_engine/verifying.py +84 -0
  61. vibe_engine/webreport.py +51 -0
  62. vibe_engine-0.1.0.dist-info/METADATA +127 -0
  63. vibe_engine-0.1.0.dist-info/RECORD +66 -0
  64. vibe_engine-0.1.0.dist-info/WHEEL +4 -0
  65. vibe_engine-0.1.0.dist-info/entry_points.txt +2 -0
  66. vibe_engine-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
vibe_engine/agents.py ADDED
@@ -0,0 +1,190 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import shlex
6
+ import shutil
7
+ import sys
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from .files import write_atomic
12
+
13
+ CLAUDE = "claude"
14
+ CODEX = "codex"
15
+ AGENTS = (CLAUDE, CODEX)
16
+ BARE_COMMAND = "vibe-engine hook stop"
17
+ BARE_PROMPT_COMMAND = "vibe-engine hook prompt"
18
+ BARE_SESSION_COMMAND = "vibe-engine hook session"
19
+ BARE_EDIT_COMMAND = "vibe-engine hook edit"
20
+ EDIT_MATCHER = "Write|Edit|MultiEdit"
21
+ EDIT_AGENTS = (CLAUDE,)
22
+ HOOK_WORDS = {
23
+ "Stop": "hook stop",
24
+ "UserPromptSubmit": "hook prompt",
25
+ "SessionStart": "hook session",
26
+ "PostToolUse": "hook edit",
27
+ "PreToolUse": "hook skill",
28
+ "UserPromptExpansion": "hook skill",
29
+ }
30
+ PROMPT_TIMEOUT = 30
31
+ TIMEOUT = 120
32
+ STATUS = "vibe-engine 检查"
33
+ MINIMAL_PATH = "/usr/bin:/bin:/usr/sbin:/sbin"
34
+ SKILL_DIRS = {CLAUDE: ".claude/skills", CODEX: ".agents/skills"}
35
+ SKILL_NAMES = ("correction-to-rule", "verify-feature")
36
+
37
+
38
+ def skill_path(agent: str, name: str) -> str:
39
+ return f"{SKILL_DIRS[agent]}/{name}/SKILL.md"
40
+
41
+ HOOK_FILES = {CLAUDE: ".claude/settings.json", CODEX: ".codex/hooks.json"}
42
+ TRUST_NOTE = "Codex 只在受信任的项目里读 .codex/hooks.json,并且要先审查钩子:CLI 里运行 /hooks,桌面应用在 设置 > 钩子。"
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class HookState:
47
+ present: bool
48
+ command: str = ""
49
+
50
+
51
+ def parse_agents(value: str | None) -> tuple[str, ...] | None:
52
+ if not value:
53
+ return None
54
+ names = tuple(part.strip() for part in value.split(",") if part.strip())
55
+ unknown = sorted(set(names) - set(AGENTS))
56
+ if unknown or not names:
57
+ raise ValueError(f"--agents 只能取 {', '.join(AGENTS)},收到:{value}")
58
+ return tuple(dict.fromkeys(names))
59
+
60
+
61
+ def detect_agents(root: Path) -> tuple[str, ...]:
62
+ found = []
63
+ if (root / ".claude").exists() or (root / "CLAUDE.md").exists():
64
+ found.append(CLAUDE)
65
+ if (root / ".codex").exists() or (root / ".agents").exists() or (root / "AGENTS.md").exists():
66
+ found.append(CODEX)
67
+ return tuple(found) or AGENTS
68
+
69
+
70
+ def user_hook_file(agent: str) -> Path:
71
+ if agent == CLAUDE:
72
+ return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") / "settings.json"
73
+ return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") / "hooks.json"
74
+
75
+
76
+ def command_source() -> str:
77
+ claude = os.environ.get("CLAUDE_CODE_CHILD_SESSION") == "1" or os.environ.get("CLAUDECODE") == "1"
78
+ codex = bool(os.environ.get("CODEX_THREAD_ID"))
79
+ if claude == codex:
80
+ return "unknown"
81
+ return CLAUDE if claude else CODEX
82
+
83
+
84
+ def absolute_command(event: str = "stop") -> str:
85
+ stable = Path.home() / ".local" / "bin" / "vibe-engine"
86
+ found = shutil.which("vibe-engine")
87
+ executable = str(stable) if stable.exists() else found
88
+ if executable:
89
+ return f"{shlex.quote(executable)} hook {event}"
90
+ return f"{shlex.quote(sys.executable)} -m vibe_engine.cli hook {event}"
91
+
92
+
93
+ def _is_ours(command: object, event: str = "Stop") -> bool:
94
+ word = HOOK_WORDS[event]
95
+ return isinstance(command, str) and ("vibe-engine" in command or "-m vibe_engine.cli" in command) and word in command
96
+
97
+
98
+ def _load(path: Path) -> dict | None:
99
+ if not path.exists():
100
+ return {}
101
+ try:
102
+ data = json.loads(path.read_text(encoding="utf-8"))
103
+ except (OSError, ValueError):
104
+ return None
105
+ return data if isinstance(data, dict) else None
106
+
107
+
108
+ def hook_entries(path: Path, event: str) -> list[tuple[int, int, dict, dict]]:
109
+ data = _load(path) or {}
110
+ hooks = data.get("hooks")
111
+ groups = hooks.get(event) if isinstance(hooks, dict) else None
112
+ found = []
113
+ for group_index, group in enumerate(groups if isinstance(groups, list) else []):
114
+ entries = group.get("hooks") if isinstance(group, dict) else None
115
+ for handler_index, entry in enumerate(entries if isinstance(entries, list) else []):
116
+ if isinstance(entry, dict) and _is_ours(entry.get("command"), event):
117
+ found.append((group_index, handler_index, group, entry))
118
+ return found
119
+
120
+
121
+ def hook_state(path: Path, event: str = "Stop") -> HookState:
122
+ entries = hook_entries(path, event)
123
+ return HookState(True, entries[0][3]["command"]) if entries else HookState(False)
124
+
125
+
126
+ def ensure_hook(path: Path, agent: str, command: str, event: str = "Stop", dry_run: bool = False, matcher: str | None = None) -> str:
127
+ data = _load(path)
128
+ label = str(path)
129
+ name = event
130
+ manual = f"{label} 无法解析或结构不对,没有修改;请手动加入 {name} 钩子:{command}"
131
+ if data is None:
132
+ return manual
133
+ state = hook_state(path, event)
134
+ if state.present:
135
+ same = "已接入" if state.command == command else f"已接入(命令是 {state.command},没有改)"
136
+ return f"{label}:{name} {same}"
137
+ hooks = data.setdefault("hooks", {})
138
+ groups = hooks.setdefault(event, []) if isinstance(hooks, dict) else None
139
+ if not isinstance(groups, list):
140
+ return manual
141
+ entry: dict = {"type": "command", "command": command, "timeout": TIMEOUT if event == "Stop" else PROMPT_TIMEOUT}
142
+ if agent == CODEX and event == "Stop":
143
+ entry["statusMessage"] = STATUS
144
+ groups.append({"matcher": matcher, "hooks": [entry]} if matcher else {"hooks": [entry]})
145
+ if agent == CODEX and "description" not in data:
146
+ data = {"description": "vibe-engine:agent 结束前运行检查", **data}
147
+ if dry_run:
148
+ return f"{label}:将加入 {name} 钩子(试运行,没有写入)"
149
+ path.parent.mkdir(parents=True, exist_ok=True)
150
+ write_atomic(path, json.dumps(data, ensure_ascii=False, indent=2) + "\n")
151
+ return f"{label}:已加入 {name} 钩子"
152
+
153
+
154
+ def ensure_hooks(
155
+ path: Path,
156
+ agent: str,
157
+ stop_command: str,
158
+ prompt_command: str,
159
+ dry_run: bool = False,
160
+ session_command: str | None = None,
161
+ edit_command: str | None = None,
162
+ ) -> list[str]:
163
+ lines = [
164
+ ensure_hook(path, agent, stop_command, "Stop", dry_run),
165
+ ensure_hook(path, agent, prompt_command, "UserPromptSubmit", dry_run),
166
+ ]
167
+ if session_command:
168
+ lines.append(ensure_hook(path, agent, session_command, "SessionStart", dry_run))
169
+ if edit_command and agent in EDIT_AGENTS:
170
+ lines.append(ensure_hook(path, agent, edit_command, "PostToolUse", dry_run, EDIT_MATCHER))
171
+ if agent == CLAUDE:
172
+ command = "vibe-engine hook skill" if stop_command == BARE_COMMAND else absolute_command("skill")
173
+ lines.append(ensure_hook(path, agent, command, "PreToolUse", dry_run, "Skill"))
174
+ lines.append(ensure_hook(path, agent, command, "UserPromptExpansion", dry_run, "|".join(SKILL_NAMES)))
175
+ return lines
176
+
177
+
178
+ def install_user(agents: tuple[str, ...], dry_run: bool = False) -> list[str]:
179
+ command = absolute_command()
180
+ lines = [f"钩子命令:{command}"]
181
+ for agent in agents:
182
+ lines += ensure_hooks(user_hook_file(agent), agent, command, absolute_command("prompt"), dry_run, absolute_command("session"), absolute_command("edit"))
183
+ if CODEX in agents:
184
+ lines.append("Codex 要先审查并信任这个钩子:CLI 里运行 /hooks,桌面应用在 设置 > 钩子;定义改动后要重新信任。")
185
+ lines.append("用户级钩子对所有仓生效,没有 engine.toml 的仓里它什么都不做。")
186
+ return lines
187
+
188
+
189
+ def bare_command_findable() -> bool:
190
+ return shutil.which("vibe-engine", path=MINIMAL_PATH) is not None
@@ -0,0 +1,213 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ from collections import deque
5
+ from collections.abc import Iterator
6
+ from dataclasses import dataclass
7
+ from pathlib import PurePosixPath
8
+ from typing import TYPE_CHECKING
9
+
10
+ from .checks.boundaries import targets
11
+ from .config import IMPORT_CYCLE, Config, ConfigError, under
12
+ from .jsresolve import EXTENSIONS, Resolver, crosses, inside
13
+ from .model import Violation
14
+ from .modules import matches, module_name
15
+
16
+ if TYPE_CHECKING:
17
+ from .config import Boundary
18
+
19
+ MAX_NODES = 80
20
+
21
+
22
+ @dataclass(frozen=True, order=True)
23
+ class Edge:
24
+ source: str
25
+ target: str
26
+ line: int
27
+ type_only: bool
28
+ boundary: bool
29
+
30
+
31
+ def _type_guard(node: ast.expr) -> bool:
32
+ if isinstance(node, ast.Name):
33
+ return node.id == "TYPE_CHECKING"
34
+ return isinstance(node, ast.Attribute) and node.attr == "TYPE_CHECKING" and isinstance(node.value, ast.Name) and node.value.id in {"typing", "typing_extensions"}
35
+
36
+
37
+ def _forbidden(boundaries: tuple[Boundary, ...], source: str, target: str) -> bool:
38
+ return any(matches(source, rule.source) and any(matches(target, prefix) for prefix in rule.forbidden) for rule in boundaries)
39
+
40
+
41
+ class ImportGraph:
42
+ def __init__(self, config: Config, discovered: dict[str, list[str]]) -> None:
43
+ self.config = config
44
+ self.python_modules: dict[str, str] = {}
45
+ for path in sorted(discovered.get("python", []), key=lambda path: (not path.endswith("/__init__.py"), path)):
46
+ name, _ = module_name(path, config.source_roots)
47
+ if name:
48
+ self.python_modules.setdefault(name, path)
49
+ self.js_files = set(discovered.get("js", []))
50
+ self.js_resolver = Resolver(config) if self.js_files else None
51
+ self.python_boundaries = config.boundaries_for("python")
52
+ self.js_boundaries = config.boundaries_for("js")
53
+ self.nodes = set(discovered.get("python", [])) | self.js_files
54
+ self.edges: set[Edge] = set()
55
+
56
+ def add_python(self, path: str, tree: ast.AST, module: str, package: str) -> None:
57
+ nodes = list(ast.walk(tree))
58
+ type_nodes = {child for node in nodes if isinstance(node, ast.If) and _type_guard(node.test) for statement in node.body for child in ast.walk(statement)}
59
+ for node in nodes:
60
+ if not isinstance(node, (ast.Import, ast.ImportFrom)):
61
+ continue
62
+ names = targets(node, package)
63
+ for name in names:
64
+ target = self.python_modules.get(name)
65
+ if target is None and isinstance(node, ast.Import):
66
+ parent = name
67
+ while parent and target is None:
68
+ parent = parent.rpartition(".")[0]
69
+ target = self.python_modules.get(parent)
70
+ if target is None or (target == path and (isinstance(node, ast.ImportFrom) or name != module)):
71
+ continue
72
+ self.edges.add(Edge(path, target, node.lineno, node in type_nodes, _forbidden(self.python_boundaries, module, name)))
73
+
74
+ def add_js(self, path: str, line: int, spec: str, type_only: bool) -> None:
75
+ resolver = self.js_resolver
76
+ if resolver is None:
77
+ return
78
+ candidates = resolver.graph_targets(spec, path)
79
+ target = next((candidate + suffix for candidate in candidates for suffix in EXTENSIONS if candidate + suffix in self.js_files), None)
80
+ if target is None:
81
+ for candidate in candidates:
82
+ stem = PurePosixPath(candidate).suffix
83
+ if stem in {".js", ".jsx", ".mjs", ".cjs"}:
84
+ suffixes = {".js": (".ts", ".tsx"), ".jsx": (".tsx",), ".mjs": (".mts",), ".cjs": (".cts",)}[stem]
85
+ target = next((candidate[:-len(stem)] + suffix for suffix in suffixes if candidate[:-len(stem)] + suffix in self.js_files), None)
86
+ if target is not None:
87
+ break
88
+ if target is not None:
89
+ boundary = any(inside(resolver, path, rule.source) and any(crosses(resolver, spec, path, prefix) for prefix in rule.forbidden) for rule in self.js_boundaries)
90
+ self.edges.add(Edge(path, target, line, type_only, boundary))
91
+
92
+ def cycles(self) -> dict[Edge, tuple[str, ...]]:
93
+ forward: dict[str, set[str]] = {node: set() for node in self.nodes}
94
+ reverse: dict[str, set[str]] = {node: set() for node in self.nodes}
95
+ for edge in self.edges:
96
+ if not edge.type_only:
97
+ forward[edge.source].add(edge.target)
98
+ reverse[edge.target].add(edge.source)
99
+ adjacency = {node: sorted(neighbors) for node, neighbors in forward.items()}
100
+ components = _components(adjacency, reverse)
101
+ found = {}
102
+ for edge in sorted(self.edges):
103
+ if edge.type_only or components[edge.source] != components[edge.target]:
104
+ continue
105
+ circuit = [edge.source, *_return_path(edge.target, edge.source, adjacency, components)]
106
+ circuit.pop()
107
+ pivot = circuit.index(min(circuit))
108
+ found[edge] = tuple(circuit[pivot:] + circuit[:pivot])
109
+ return found
110
+
111
+ def violations(self) -> list[Violation]:
112
+ return [Violation(IMPORT_CYCLE, edge.source, edge.line, "循环依赖:" + " → ".join((*cycle, cycle[0])), " → ".join((*cycle, cycle[0]))) for edge, cycle in self.cycles().items()]
113
+
114
+ def mermaid(self, depth: int, focus: str | None) -> str:
115
+ def group(path: str) -> str:
116
+ parts = path.split("/")
117
+ for root in self.config.source_roots:
118
+ prefix = root.strip("/")
119
+ if prefix in ("", "."):
120
+ break
121
+ if path != prefix and under(path, prefix):
122
+ return "/".join(parts[:len(prefix.split("/")) + depth])
123
+ return "/".join(parts[:depth])
124
+
125
+ nodes = self.nodes
126
+ edges = self.edges
127
+ if focus:
128
+ prefix = focus.removeprefix("./").rstrip("/")
129
+ module_prefix = prefix.replace("/", ".")
130
+ selected = {node for node in nodes if node == prefix or node.startswith(prefix + "/") or group(node) == prefix}
131
+ selected.update(path for name, path in self.python_modules.items() if matches(name, module_prefix))
132
+ if not selected:
133
+ raise ConfigError(f"导入图中找不到 {focus}")
134
+ edges = {edge for edge in edges if edge.source in selected or edge.target in selected}
135
+ nodes = selected | {path for edge in edges for path in (edge.source, edge.target)}
136
+ grouped = sorted({group(node) for node in nodes})
137
+ if len(grouped) > MAX_NODES:
138
+ raise ConfigError(f"导入图有 {len(grouped)} 个节点。请调低 --depth 或用 --focus 缩小范围。")
139
+ ids = {node: f"n{index}" for index, node in enumerate(grouped)}
140
+ rows = ["flowchart LR", *(f' {ids[node]}["{_label(node)}"]' for node in grouped)]
141
+ cycles = self.cycles()
142
+ links: dict[tuple[str, str], set[str]] = {}
143
+ runtime = set()
144
+ for edge in edges:
145
+ pair = (group(edge.source), group(edge.target))
146
+ if pair[0] == pair[1] and edge not in cycles and not edge.boundary:
147
+ continue
148
+ flags = links.setdefault(pair, set())
149
+ if edge.boundary:
150
+ flags.add("违反边界")
151
+ if edge in cycles:
152
+ flags.add("循环")
153
+ if not edge.type_only:
154
+ runtime.add(pair)
155
+ for pair, flags in sorted(links.items()):
156
+ if pair not in runtime:
157
+ flags.add("仅类型")
158
+ arrow = "==>" if "循环" in flags else "-.->" if flags else "-->"
159
+ label = "|" + "、".join(sorted(flags)) + "|" if flags else ""
160
+ rows.append(f" {ids[pair[0]]} {arrow}{label} {ids[pair[1]]}")
161
+ return "\n".join(rows)
162
+
163
+
164
+ def _label(text: str) -> str:
165
+ return "".join(char if char.isalnum() or char in "_./-@ " else f"#{ord(char)};" for char in text)
166
+
167
+
168
+ def _components(forward: dict[str, list[str]], reverse: dict[str, set[str]]) -> dict[str, str]:
169
+ visited = set()
170
+ ordered = []
171
+ for root in sorted(forward):
172
+ if root in visited:
173
+ continue
174
+ visited.add(root)
175
+ stack: list[tuple[str, Iterator[str]]] = [(root, iter(forward[root]))]
176
+ while stack:
177
+ node, children = stack[-1]
178
+ child = next(children, None)
179
+ if child is None:
180
+ ordered.append(node)
181
+ stack.pop()
182
+ elif child not in visited:
183
+ visited.add(child)
184
+ stack.append((child, iter(forward[child])))
185
+ assigned = {}
186
+ for root in reversed(ordered):
187
+ if root in assigned:
188
+ continue
189
+ pending = [root]
190
+ assigned[root] = root
191
+ while pending:
192
+ for node in reverse[pending.pop()]:
193
+ if node not in assigned:
194
+ assigned[node] = root
195
+ pending.append(node)
196
+ return assigned
197
+
198
+
199
+ def _return_path(start: str, end: str, adjacency: dict[str, list[str]], components: dict[str, str]) -> list[str]:
200
+ seen: dict[str, str | None] = {start: None}
201
+ queue = deque([start])
202
+ while end not in seen:
203
+ current = queue.popleft()
204
+ for child in adjacency[current]:
205
+ if child not in seen and components[child] == components[end]:
206
+ seen[child] = current
207
+ queue.append(child)
208
+ node: str | None = end
209
+ path = []
210
+ while node is not None:
211
+ path.append(node)
212
+ node = seen[node]
213
+ return path[::-1]
vibe_engine/astgrep.py ADDED
@@ -0,0 +1,151 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ from dataclasses import dataclass
10
+ from importlib import metadata
11
+ from pathlib import Path
12
+
13
+ from .config import BannedApi
14
+ from .model import Violation
15
+
16
+ CHUNK = 300
17
+ STDERR_TAIL = 400
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Match:
22
+ rule: str
23
+ path: str
24
+ line: int
25
+ column: int
26
+ text: str
27
+
28
+
29
+ def find_tool(name: str) -> str | None:
30
+ sibling = Path(sys.executable).parent / name
31
+ if sibling.is_file():
32
+ return str(sibling)
33
+ return shutil.which(name)
34
+
35
+
36
+ def distribution_version(distribution: str) -> str | None:
37
+ try:
38
+ return metadata.version(distribution)
39
+ except metadata.PackageNotFoundError:
40
+ return None
41
+
42
+
43
+ def missing(tool: str, package: str, purpose: str) -> str:
44
+ return (
45
+ f"找不到 {tool},{purpose}没有运行。在安装 vibe-engine 的同一个 Python 环境里执行 `pip install {package}`,"
46
+ f"或重新安装 vibe-engine。"
47
+ )
48
+
49
+
50
+ def relative(path: str) -> str:
51
+ return path.removeprefix("./")
52
+
53
+
54
+ def scan(root: Path, rules: list[dict], files: list[str]) -> tuple[list[Match], list[str]]:
55
+ if not rules or not files:
56
+ return [], []
57
+ executable = find_tool("ast-grep")
58
+ if executable is None:
59
+ return [], [missing("ast-grep", "ast-grep-cli", "注释和 pattern 规则检查")]
60
+ folder = Path(tempfile.mkdtemp(prefix="vibe-engine-"))
61
+ try:
62
+ rule_file = folder / "rules.json"
63
+ rule_file.write_text("\n---\n".join(json.dumps(rule) for rule in rules) + "\n", encoding="utf-8")
64
+ found: list[Match] = []
65
+ errors: list[str] = []
66
+ for start in range(0, len(files), CHUNK):
67
+ paths = [f"./{name}" for name in files[start : start + CHUNK]]
68
+ command = [executable, "scan", "--rule", str(rule_file), "--json=stream", *paths]
69
+ try:
70
+ finished = subprocess.run(command, cwd=root, capture_output=True, encoding="utf-8", errors="replace", check=False)
71
+ except OSError as error:
72
+ errors.append(f"ast-grep 无法启动:{error}")
73
+ break
74
+ errors += _stderr_errors(finished.stderr)
75
+ if finished.returncode != 0:
76
+ tail = finished.stderr.strip()[-STDERR_TAIL:]
77
+ errors.append(f"ast-grep 运行失败(退出码 {finished.returncode}):{tail}")
78
+ continue
79
+ found += _parse(finished.stdout, errors)
80
+ finally:
81
+ shutil.rmtree(folder, ignore_errors=True)
82
+ found.sort(key=lambda match: (match.path, match.line, match.column, match.rule))
83
+ return found, errors
84
+
85
+
86
+ def _stderr_errors(stderr: str) -> list[str]:
87
+ return [f"ast-grep 报错:{line.strip()}" for line in stderr.splitlines() if line.startswith("ERROR")]
88
+
89
+
90
+ def _parse(output: str, errors: list[str]) -> list[Match]:
91
+ found = []
92
+ for line in output.splitlines():
93
+ if not line.strip():
94
+ continue
95
+ try:
96
+ item = json.loads(line)
97
+ start = item["range"]["start"]
98
+ found.append(Match(item["ruleId"], relative(item["file"]), start["line"] + 1, start["column"], item["text"]))
99
+ except (ValueError, KeyError, TypeError):
100
+ errors.append(f"ast-grep 输出无法解析:{line[:200]}")
101
+ return found
102
+
103
+
104
+ def _source_regex(module: str) -> str:
105
+ return "^[\"']" + re.escape(module) + "(?:/[^\"']*)?[\"']$"
106
+
107
+
108
+ def banned_rules(items: list[BannedApi], ast_languages: tuple[str, ...]) -> tuple[list[dict], dict[str, BannedApi]]:
109
+ rules = []
110
+ index = {}
111
+ for number, item in enumerate(items):
112
+ if item.form == "command":
113
+ body = {"kind": "command", "has": {"field": "name", "regex": f"^{re.escape(item.api)}$"}}
114
+ elif item.form == "call":
115
+ body = {"pattern": f"{item.api}($$$A)"}
116
+ elif item.form == "import":
117
+ names = "|".join(re.escape(name) for name in item.names)
118
+ body = {
119
+ "kind": "import_specifier",
120
+ "has": {"field": "name", "regex": f"^(?:{names})$"},
121
+ "inside": {
122
+ "stopBy": "end",
123
+ "kind": "import_statement",
124
+ "has": {"field": "source", "kind": "string", "regex": _source_regex(item.api)},
125
+ },
126
+ }
127
+ else:
128
+ body = {"pattern": item.pattern}
129
+ for language in ast_languages:
130
+ rule_id = f"banned-{number}|{language}"
131
+ rules.append({"id": rule_id, "language": language, "rule": body})
132
+ index[rule_id] = item
133
+ return rules, index
134
+
135
+
136
+ _SPECIFIER = re.compile(r"(?:type\s+)?([\w$]+)")
137
+
138
+
139
+ def banned_violations(matches: list[Match], index: dict[str, BannedApi], sources: dict[str, list[str]]) -> list[Violation]:
140
+ found = []
141
+ for match in matches:
142
+ item = index.get(match.rule)
143
+ if item is None or not item.applies_to(match.path):
144
+ continue
145
+ name = item.api
146
+ if item.form == "import":
147
+ imported = _SPECIFIER.match(match.text)
148
+ name = f"{item.api}.{imported.group(1)}" if imported else item.api
149
+ lines = sources[match.path]
150
+ found.append(Violation(f"banned:{name}", match.path, match.line, item.message, lines[match.line - 1].strip()))
151
+ return found
@@ -0,0 +1,121 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections import Counter
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ from . import __version__, languages
9
+ from .config import BASELINE_NAME, ConfigError
10
+ from .files import write_atomic
11
+ from .model import Violation
12
+
13
+
14
+ @dataclass
15
+ class Comparison:
16
+ new: list[Violation]
17
+ allowed: Counter
18
+ loose: int
19
+
20
+
21
+ def parse(text: str) -> Counter:
22
+ try:
23
+ data = json.loads(text)
24
+ entries: Counter = Counter()
25
+ for rule, paths in data.get("entries", {}).items():
26
+ for path, fingerprints in paths.items():
27
+ for fingerprint, count in fingerprints.items():
28
+ entries[(rule, path, fingerprint)] = int(count)
29
+ except (ValueError, AttributeError, TypeError, OverflowError) as error:
30
+ raise ConfigError(f"{BASELINE_NAME} 已损坏:{error}") from error
31
+ return +entries
32
+
33
+
34
+ SHARED_PREFIX = "extends:"
35
+
36
+
37
+ def tool_versions(names: tuple[str, ...] | None = None, shared: tuple[tuple[str, str], ...] = ()) -> dict[str, str]:
38
+ return {
39
+ "vibe-engine": __version__,
40
+ **languages.tool_versions(names),
41
+ **{f"{SHARED_PREFIX}{ref}": digest for ref, digest in shared},
42
+ }
43
+
44
+
45
+ def recorded_tools(text: str | None) -> dict:
46
+ try:
47
+ tools = json.loads(text or "{}").get("tools", {})
48
+ except (ValueError, AttributeError):
49
+ return {}
50
+ return tools if isinstance(tools, dict) else {}
51
+
52
+
53
+ def recorded_shared_rules(text: str | None) -> dict[str, list[str]]:
54
+ try:
55
+ found = json.loads(text or "{}").get("shared_rules", {})
56
+ except (ValueError, AttributeError):
57
+ return {}
58
+ return found if isinstance(found, dict) else {}
59
+
60
+
61
+ def load(root: Path) -> Counter | None:
62
+ path = root / BASELINE_NAME
63
+ if not path.is_file():
64
+ return None
65
+ try:
66
+ text = path.read_text(encoding="utf-8")
67
+ except (OSError, UnicodeError) as error:
68
+ raise ConfigError(f"无法读取 {BASELINE_NAME}:{error}") from error
69
+ return parse(text)
70
+
71
+
72
+ def save(
73
+ root: Path,
74
+ entries: Counter,
75
+ names: tuple[str, ...] | None = None,
76
+ shared: tuple[tuple[str, str], ...] = (),
77
+ shared_rules: dict[str, list[str]] | None = None,
78
+ *,
79
+ mypy_version: str | None = None,
80
+ ) -> None:
81
+ nested: dict = {}
82
+ for (rule, path, fingerprint), count in sorted(entries.items()):
83
+ if count > 0:
84
+ nested.setdefault(rule, {}).setdefault(path, {})[fingerprint] = count
85
+ tools = tool_versions(names, shared)
86
+ path = root / BASELINE_NAME
87
+ try:
88
+ previous = recorded_tools(path.read_text(encoding="utf-8"))
89
+ except (FileNotFoundError, UnicodeError):
90
+ previous = {}
91
+ recorded_mypy = mypy_version or previous.get("mypy")
92
+ if recorded_mypy:
93
+ tools["mypy"] = recorded_mypy
94
+ document = {"version": 1, "tools": tools, "entries": nested}
95
+ if shared_rules:
96
+ document["shared_rules"] = shared_rules
97
+ payload = json.dumps(document, ensure_ascii=False, indent=2)
98
+ write_atomic(path, payload + "\n")
99
+
100
+
101
+ def count(violations: list[Violation]) -> Counter:
102
+ return Counter(violation.key for violation in violations)
103
+
104
+
105
+ def compare(violations: list[Violation], base: Counter, files: set[str]) -> Comparison:
106
+ current = count(violations)
107
+ moved: Counter = Counter()
108
+ for (rule, path, fingerprint), amount in base.items():
109
+ if path not in files:
110
+ moved[(rule, fingerprint)] += amount
111
+ allowed: Counter = Counter()
112
+ for key in sorted(current):
113
+ allowed[key] = min(current[key], base.get(key, 0))
114
+ excess = current[key] - allowed[key]
115
+ pool = (key[0], key[2])
116
+ taken = min(excess, moved[pool])
117
+ moved[pool] -= taken
118
+ allowed[key] += taken
119
+ allowed = +allowed
120
+ new = [violation for violation in violations if current[violation.key] > allowed.get(violation.key, 0)]
121
+ return Comparison(new=new, allowed=allowed, loose=sum(base.values()) - sum(allowed.values()))
File without changes