artifacts.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """Write known text artifacts to a new directory, never over an existing project."""
  2. from __future__ import annotations
  3. import json
  4. from pathlib import Path, PurePosixPath
  5. def validate_files(files: dict[str, str]) -> None:
  6. if len(files) > 50:
  7. raise ValueError("生成文件过多。")
  8. total = 0
  9. for name, content in files.items():
  10. path = PurePosixPath(name)
  11. if path.is_absolute() or ".." in path.parts or "\\" in name or not path.parts:
  12. raise ValueError("生成文件路径不合法。")
  13. if not isinstance(content, str):
  14. raise ValueError("只允许生成文本文件。")
  15. total += len(content.encode("utf-8"))
  16. if total > 5 * 1024 * 1024:
  17. raise ValueError("生成内容超过 5 MB,请缩小设计范围。")
  18. def write_result(result: dict, destination: Path) -> Path:
  19. validate_files(result["files"])
  20. destination = destination.resolve()
  21. destination.mkdir(parents=True, exist_ok=False)
  22. for name, content in result["files"].items():
  23. target = destination / name
  24. target.parent.mkdir(parents=True, exist_ok=True)
  25. target.write_text(content, encoding="utf-8")
  26. for name, content in {
  27. "design-model.json": result["design"],
  28. "design-analysis.json": result.get("analysis", {}),
  29. "agent-trace.json": result["events"],
  30. "review-report.json": {"review": result["review"], "metrics": result["metrics"], "mode": result["mode"]},
  31. "component-plan.json": result["plan"],
  32. }.items():
  33. (destination / name).write_text(json.dumps(content, ensure_ascii=False, indent=2), encoding="utf-8")
  34. return destination