Vibe Coding 由 Andrej Karpathy 在 2025 年初提出,核心是用自然语言描述意图,AI 生成代码,开发者凭感觉迭代,而不逐行阅读实现。对专业工程师来说,它不是"放弃工程规范",而是把工作重心从"写实现"转移到"定义约束、验证结果、控制风险"。
本文从专业视角拆解 Vibe Coding 的约束体系:需求契约、上下文管理、生成验证、安全门禁。
适合:原型验证、个人工具、一次性脚本、内部小系统、学习辅助。
不适合:支付、医疗、金融、隐私数据处理、对外高安全服务、长期维护的生产系统。
判断标准很简单:出错后能否低成本回滚? 能,就可以 Vibe;不能,就必须走完整工程流程。
Vibe Coding 最大的失败原因是需求太模糊。专业做法是先写契约,再让 AI 生成。
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol
@dataclass(frozen=True)
class RenameRule:
replace_space: bool = True
keep_chinese: bool = True
date_format: str = "%Y-%m-%d"
class Renamer(Protocol):
def preview(self, root: Path) -> list[tuple[Path, Path]]: ...
def apply(self, plan: list[tuple[Path, Path]]) -> list[str]: ...契约写清楚后,再给 AI 的提示词就变成:
实现 Renamer 协议,要求:
1. preview 只计算不修改,返回 (原路径, 新路径) 列表。
2. apply 遇到权限错误时跳过并记录,不中断。
3. 重名时追加 _2、_3,不覆盖已有文件。
4. 只处理文件,不递归子目录。
5. 不允许删除任何文件。
6. 补充类型注解和 docstring。约束越明确,AI 产物越接近可用。
上下文太多会引入噪声,太少会生成错误实现。专业做法是按相关性筛选,并控制 token 预算。
from pathlib import Path
IGNORE = {".git", "node_modules", "__pycache__", ".venv", "dist"}
ALLOW = {".py", ".ts", ".tsx", ".json", ".md", ".toml"}
def collect_context(root: Path, keywords: list[str],
budget: int = 30000) -> list[str]:
candidates = []
for p in root.rglob("*"):
if not p.is_file() or p.suffix not in ALLOW:
continue
if any(part in IGNORE for part in p.parts):
continue
text = p.read_text(encoding="utf-8", errors="ignore")
score = sum(1 for k in keywords if k.lower() in p.name.lower())
tokens = len(text) // 4
candidates.append((score, tokens, str(p), text))
candidates.sort(key=lambda x: (-x[0], x[1]))
chosen, used = [], 0
for _, tokens, path, text in candidates:
if used + tokens > budget:
continue
chosen.append(f"### {path}\n{text}")
used += tokens
return chosen关键:只给相关文件,按 token 预算裁剪,避免把整个仓库塞进上下文。
Vibe Coding 最容易犯的错是"能跑就交付"。专业做法是三道门禁:静态检查、单元测试、差异审查。
import subprocess
from pathlib import Path
def run(cmd: list[str], cwd: Path, timeout: int = 120) -> dict:
try:
p = subprocess.run(cmd, cwd=cwd, capture_output=True,
text=True, timeout=timeout)
return {"code": p.returncode, "out": p.stdout[-2000:],
"err": p.stderr[-1000:]}
except subprocess.TimeoutExpired:
return {"code": -1, "out": "", "err": "timeout"}
def quality_gate(repo: Path) -> dict:
checks = {
"lint": run(["ruff", "check", "."], repo),
"type": run(["mypy", "."], repo),
"test": run(["pytest", "-q"], repo),
}
checks["ok"] = all(c["code"] == 0 for c in checks.values())
return checks三道门禁的意义:lint 拦风格和明显错误,mypy 拦类型问题,pytest 拦行为回归。 任何一道不过,就不能合并。
AI 生成的多文件改动,必须先转成 diff 再决定是否接受。
import difflib
from pathlib import Path
def diff_files(old: str, new: str, path: str) -> str:
return "".join(difflib.unified_diff(
old.splitlines(keepends=True),
new.splitlines(keepends=True),
fromfile=f"a/{path}", tofile=f"b/{path}",
))
def summarize(diff: str) -> dict:
added = sum(1 for l in diff.splitlines()
if l.startswith("+") and not l.startswith("+++"))
removed = sum(1 for l in diff.splitlines()
if l.startswith("-") and not l.startswith("---"))
return {"added": added, "removed": removed,
"files": diff.count("--- ")}审查清单:是否改了无关文件、是否引入新依赖、是否吞异常、是否删除测试、是否硬编码密钥、是否绕过权限校验。
import re
from pathlib import Path
SECRETS = [
re.compile(r"(?i)api[_-]?key\s*=\s*['\"][^'\"]+"),
re.compile(r"(?i)password\s*=\s*['\"][^'\"]+"),
re.compile(r"AKIA[0-9A-Z]{16}"),
re.compile(r"-----BEGIN [A-Z ]+PRIVATE KEY-----"),
]
DANGEROUS = [
re.compile(r"\beval\s*\("),
re.compile(r"\bos\.system\s*\("),
re.compile(r"subprocess\.[a-z]+\([^)]*shell\s*=\s*True"),
]
def scan_file(path: Path) -> list[str]:
text = path.read_text(encoding="utf-8", errors="ignore")
issues = []
for pat in SECRETS:
if pat.search(text):
issues.append(f"{path}: 疑似硬编码密钥")
break
for pat in DANGEROUS:
if pat.search(text):
issues.append(f"{path}: 疑似危险调用")
break
return issuesAI 生成代码常犯四类安全错误:硬编码密钥、直接 eval、shell=True、绕过权限校验。这些必须在合并前拦截。
name: ci
on: [push, pull_request]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.12" }
- run: pip install ruff mypy pytest bandit pip-audit
- run: ruff check .
- run: mypy .
- run: pytest -q
- run: bandit -r app
- run: pip-audit门禁不是形式。AI 生成的代码同样要过 lint、类型、测试、安全扫描和依赖审计。
Vibe Coding 的专业用法,不是"不看代码就交付",而是把精力从写实现转移到定义约束、验证结果、控制风险。需求契约、上下文管理、生成验证、差异审查、安全门禁、CI 拦截,六个动作缺一不可。它适合低风险场景和原型验证,不适合高风险生产系统。AI 是加速器,不是安全网,责任始终在人。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。