📦 deps(playbook): sync playbook snapshot

This commit is contained in:
csh
2026-02-02 10:51:41 +08:00
192 changed files with 109197 additions and 135276 deletions
@@ -0,0 +1,210 @@
#!/usr/bin/env python3
from __future__ import annotations
import json
import os
import pathlib
import re
import subprocess
import sys
from typing import Dict, List, Optional, Tuple
def _eprint(*args: object) -> None:
print(*args, file=sys.stderr)
def _git(*args: str) -> str:
return subprocess.check_output(["git", *args], text=True).strip()
def _repo_root() -> pathlib.Path:
return pathlib.Path(_git("rev-parse", "--show-toplevel"))
def _find_commit_spec(root: pathlib.Path) -> pathlib.Path:
candidates = [
root / "docs" / "common" / "commit_message.md",
root / "docs" / "standards" / "playbook" / "docs" / "common" / "commit_message.md",
]
for path in candidates:
if path.is_file():
return path
raise FileNotFoundError(
"commit_message.md not found; expected one of:\n"
+ "\n".join(f"- {p}" for p in candidates)
)
def _parse_type_emoji_mapping(md_text: str) -> Dict[str, str]:
mapping: Dict[str, str] = {}
for raw_line in md_text.splitlines():
line = raw_line.strip()
if not (line.startswith("|") and line.endswith("|")):
continue
if "type" in line and "emoji" in line:
continue
if re.fullmatch(r"\|\s*-+\s*(\|\s*-+\s*)+\|", line):
continue
cols = [c.strip() for c in line.strip("|").split("|")]
if len(cols) < 2:
continue
m_type = re.search(r"`([^`]+)`", cols[0])
m_emoji = re.search(r"`(:[^`]+:)`", cols[1])
if not m_type or not m_emoji:
continue
type_name = m_type.group(1).strip()
emoji_code = m_emoji.group(1).strip()
mapping[type_name] = emoji_code
if not mapping:
raise ValueError("failed to parse type/emoji mapping from commit_message.md")
return mapping
def _validate_subject_line(
line: str,
mapping: Dict[str, str],
*,
require_emoji: bool,
) -> Optional[str]:
subject = line.strip()
if not subject:
return "empty subject"
m = re.match(
r"^(?:(?P<emoji>:[a-z0-9_+-]+:)\s+)?"
r"(?P<type>[a-z]+)"
r"(?P<scope>\([a-z0-9_]+\))?"
r":\s+(?P<text>.+)$",
subject,
)
if not m:
return "does not match ':emoji: type(scope): subject' or 'type(scope): subject'"
emoji = m.group("emoji")
type_name = m.group("type")
text = (m.group("text") or "").rstrip()
if type_name not in mapping:
return f"unknown type: {type_name}"
if emoji:
expected = mapping[type_name]
if emoji != expected:
return f"emoji/type mismatch: got {emoji} {type_name}, expected {expected} for type {type_name}"
elif require_emoji:
return "missing emoji (set COMMIT_LINT_REQUIRE_EMOJI=0 to allow)"
if text.endswith((".", "")):
return "subject should not end with a period"
return None
def _load_event_payload() -> Tuple[str, Optional[dict]]:
event_name = os.getenv("GITHUB_EVENT_NAME") or os.getenv("GITEA_EVENT_NAME") or ""
event_path = os.getenv("GITHUB_EVENT_PATH") or os.getenv("GITEA_EVENT_PATH") or ""
if not event_path:
return event_name, None
path = pathlib.Path(event_path)
if not path.is_file():
return event_name, None
try:
return event_name, json.loads(path.read_text(encoding="utf-8"))
except Exception as exc:
_eprint(f"WARN: failed to parse event payload: {path} ({exc})")
return event_name, None
def _gather_subjects(event_name: str, payload: Optional[dict]) -> List[Tuple[str, str]]:
subjects: List[Tuple[str, str]] = []
if isinstance(payload, dict):
if event_name.startswith("pull_request"):
pr = payload.get("pull_request")
if isinstance(pr, dict):
title = (pr.get("title") or "").strip()
if title:
subjects.append(("pull_request.title", title.splitlines()[0].strip()))
if event_name == "push":
commits = payload.get("commits")
if isinstance(commits, list):
for commit in commits:
if not isinstance(commit, dict):
continue
msg = (commit.get("message") or "").strip()
if not msg:
continue
subject = msg.splitlines()[0].strip()
sha = commit.get("id") or commit.get("sha") or ""
label = f"push.commit {sha[:7]}" if sha else "push.commit"
subjects.append((label, subject))
if subjects:
return subjects
try:
subjects.append(("HEAD", _git("log", "-1", "--format=%s", "HEAD")))
except Exception:
pass
return subjects
def main() -> int:
try:
root = _repo_root()
except Exception as exc:
_eprint(f"ERROR: not a git repository: {exc}")
return 2
os.chdir(root)
require_emoji = os.getenv("COMMIT_LINT_REQUIRE_EMOJI", "1") not in ("0", "false", "False")
try:
spec_path = _find_commit_spec(root)
except FileNotFoundError as exc:
_eprint(f"ERROR: {exc}")
return 2
try:
mapping = _parse_type_emoji_mapping(spec_path.read_text(encoding="utf-8"))
except Exception as exc:
_eprint(f"ERROR: failed to read/parse {spec_path}: {exc}")
return 2
event_name, payload = _load_event_payload()
subjects = _gather_subjects(event_name, payload)
print(f"commit spec: {spec_path}")
if event_name:
print(f"event: {event_name}")
print(f"require emoji: {require_emoji}")
print(f"checks: {len(subjects)} subject(s)")
errors: List[str] = []
for label, subject in subjects:
err = _validate_subject_line(subject, mapping, require_emoji=require_emoji)
if err:
errors.append(f"- {label}: {err}\n subject: {subject}")
if errors:
_eprint("ERROR: commit message lint failed:")
for item in errors:
_eprint(item)
return 1
print("OK")
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,128 @@
#!/usr/bin/env bash
set -euo pipefail
REPO_DIR="${REPO_DIR:-$(pwd)}"
SUPERPOWERS_BRANCH="${SUPERPOWERS_BRANCH:-thirdparty/skill}"
SUPERPOWERS_DIR="${SUPERPOWERS_DIR:-superpowers}"
SUPERPOWERS_LIST="${SUPERPOWERS_LIST:-codex/skills/.sources/superpowers.list}"
TARGET_BRANCH="${TARGET_BRANCH:-main}"
COMMIT_AUTHOR_NAME="${COMMIT_AUTHOR_NAME:-playbook-bot}"
COMMIT_AUTHOR_EMAIL="${COMMIT_AUTHOR_EMAIL:-playbook-bot@local}"
cd "$REPO_DIR"
git config user.name "$COMMIT_AUTHOR_NAME"
git config user.email "$COMMIT_AUTHOR_EMAIL"
git fetch origin "$SUPERPOWERS_BRANCH"
git fetch origin "$TARGET_BRANCH"
tmp_dir="$(mktemp -d)"
cleanup() {
rm -rf "$tmp_dir"
}
trap cleanup EXIT
git archive --format=tar "origin/${SUPERPOWERS_BRANCH}" "${SUPERPOWERS_DIR}/skills" | tar -xf - -C "$tmp_dir"
tmp_skills_dir="$tmp_dir/${SUPERPOWERS_DIR}/skills"
if [ ! -d "$tmp_skills_dir" ]; then
echo "ERROR: ${SUPERPOWERS_DIR}/skills not found in ${SUPERPOWERS_BRANCH}" >&2
exit 1
fi
git checkout -B "$TARGET_BRANCH" "origin/$TARGET_BRANCH"
mkdir -p "$(dirname "$SUPERPOWERS_LIST")"
old_list="$SUPERPOWERS_LIST"
if [ -f "$old_list" ]; then
while IFS= read -r name; do
[ -n "$name" ] || continue
rm -rf "codex/skills/$name"
done < "$old_list"
fi
names=()
for dir in "$tmp_skills_dir"/*; do
[ -d "$dir" ] || continue
name="$(basename "$dir")"
if [ -d "codex/skills/$name" ] && ! grep -qx "$name" "$old_list" 2>/dev/null; then
echo "ERROR: skill name conflict: $name" >&2
exit 1
fi
rm -rf "codex/skills/$name"
cp -R "$dir" "codex/skills/$name"
names+=("$name")
done
printf "%s\n" "${names[@]}" | sort > "$SUPERPOWERS_LIST"
update_block() {
local file="$1"
local start="<!-- superpowers:skills:start -->"
local end="<!-- superpowers:skills:end -->"
local tmp
tmp="$(mktemp)"
{
echo "### Third-party Skills (superpowers)"
echo ""
echo "$start"
while IFS= read -r name; do
[ -n "$name" ] || continue
echo "- $name"
done < "$SUPERPOWERS_LIST"
echo "$end"
} > "$tmp"
if grep -q "$start" "$file"; then
awk -v start="$start" -v end="$end" -v block="$tmp" '
BEGIN {
while ((getline line < block) > 0) { buf[++n] = line }
close(block)
inblock=0
replaced=0
}
{
if (!replaced && $0 == start) {
for (i=1; i<=n; i++) print buf[i]
inblock=1
replaced=1
next
}
if (inblock) {
if ($0 == end) { inblock=0 }
next
}
print
}
' "$file" > "${file}.tmp"
mv "${file}.tmp" "$file"
else
echo "" >> "$file"
cat "$tmp" >> "$file"
fi
rm -f "$tmp"
}
update_block "SKILLS.md"
git add codex/skills SKILLS.md "$SUPERPOWERS_LIST"
if git diff --cached --quiet; then
echo "No changes to sync."
exit 0
fi
git commit -m ":package: deps(skills): sync superpowers"
TOKEN="${WORKFLOW:-}"
if [ -n "$TOKEN" ] && [ -n "${GITHUB_SERVER_URL:-}" ] && [ -n "${GITHUB_REPOSITORY:-}" ]; then
git remote set-url origin "https://oauth2:${TOKEN}@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git"
fi
git push origin "$TARGET_BRANCH"
@@ -0,0 +1,75 @@
name: ✅ Standards Check
on:
push:
pull_request:
workflow_dispatch: # 允许手动触发
concurrency:
group: standards-${{ github.repository }}-${{ github.ref }}
cancel-in-progress: true
# ==========================================
# 🔧 配置区域 - 标准校验参数
# ==========================================
env:
COMMIT_LINT_REQUIRE_EMOJI: "1"
WORKSPACE_DIR: "/home/workspace"
jobs:
commit-message:
name: 🔍 Commit message lint
runs-on: ubuntu-22.04
steps:
- name: 📥 准备仓库
run: |
echo "========================================"
echo "📥 准备仓库到 WORKSPACE_DIR"
echo "========================================"
REPO_NAME="${{ github.event.repository.name }}"
REPO_DIR="${{ env.WORKSPACE_DIR }}/$REPO_NAME"
TOKEN="${{ secrets.WORKFLOW }}"
if [ -n "$TOKEN" ]; then
REPO_URL="https://oauth2:${TOKEN}@${GITHUB_SERVER_URL#https://}/${{ github.repository }}.git"
else
REPO_URL="${GITHUB_SERVER_URL}/${{ github.repository }}.git"
fi
if [ -d "$REPO_DIR" ]; then
if [ -d "$REPO_DIR/.git" ]; then
cd "$REPO_DIR"
git clean -fdx
git reset --hard
git fetch --all --tags --force --prune --prune-tags
else
rm -rf "$REPO_DIR"
fi
fi
if [ ! -d "$REPO_DIR/.git" ]; then
mkdir -p "${{ env.WORKSPACE_DIR }}"
git clone "$REPO_URL" "$REPO_DIR"
cd "$REPO_DIR"
fi
TARGET_SHA="${{ github.sha }}"
TARGET_REF="${{ github.ref }}"
if git cat-file -e "$TARGET_SHA^{commit}" 2>/dev/null; then
git checkout -f "$TARGET_SHA"
else
if [ -n "$TARGET_REF" ]; then
git fetch origin "$TARGET_REF"
git checkout -f FETCH_HEAD
else
git checkout -f "${{ github.ref_name }}"
fi
fi
git config --global --add safe.directory "$REPO_DIR"
echo "REPO_DIR=$REPO_DIR" >> $GITHUB_ENV
- name: 🧪 Lint commit message / PR title
run: |
cd "$REPO_DIR"
python3 .gitea/ci/commit_message_lint.py
@@ -0,0 +1,75 @@
name: Sync Superpowers Skills
on:
workflow_dispatch:
concurrency:
group: superpowers-sync-${{ github.repository }}
cancel-in-progress: true
env:
WORKSPACE_DIR: "/home/workspace"
SUPERPOWERS_BRANCH: "thirdparty/skill"
SUPERPOWERS_DIR: "superpowers"
SUPERPOWERS_LIST: "codex/skills/.sources/superpowers.list"
jobs:
sync:
name: Sync to main
runs-on: ubuntu-22.04
steps:
- name: Prepare repo
run: |
echo "========================================"
echo "Prepare repo to WORKSPACE_DIR"
echo "========================================"
REPO_NAME="${{ github.event.repository.name }}"
REPO_DIR="${{ env.WORKSPACE_DIR }}/$REPO_NAME"
TOKEN="${{ secrets.WORKFLOW }}"
if [ -n "$TOKEN" ]; then
REPO_URL="https://oauth2:${TOKEN}@${GITHUB_SERVER_URL#https://}/${{ github.repository }}.git"
else
REPO_URL="${GITHUB_SERVER_URL}/${{ github.repository }}.git"
fi
if [ -d "$REPO_DIR" ]; then
if [ -d "$REPO_DIR/.git" ]; then
cd "$REPO_DIR"
git clean -fdx
git reset --hard
git fetch --all --tags --force --prune --prune-tags
else
rm -rf "$REPO_DIR"
fi
fi
if [ ! -d "$REPO_DIR/.git" ]; then
mkdir -p "${{ env.WORKSPACE_DIR }}"
git clone "$REPO_URL" "$REPO_DIR"
cd "$REPO_DIR"
fi
TARGET_SHA="${{ github.sha }}"
TARGET_REF="${{ github.ref }}"
if git cat-file -e "$TARGET_SHA^{commit}" 2>/dev/null; then
git checkout -f "$TARGET_SHA"
else
if [ -n "$TARGET_REF" ]; then
git fetch origin "$TARGET_REF"
git checkout -f FETCH_HEAD
else
git checkout -f "${{ github.ref_name }}"
fi
fi
git config --global --add safe.directory "$REPO_DIR"
echo "REPO_DIR=$REPO_DIR" >> $GITHUB_ENV
- name: Sync superpowers skills to main
shell: bash
run: |
set -euo pipefail
cd "$REPO_DIR"
bash .gitea/ci/sync_superpowers.sh
+16 -306
View File
@@ -86,334 +86,44 @@ jobs:
echo "========================================"
apt-get update
apt-get install -y bats cmake clang-format python3-pip
apt-get install -y python3-pip
python3 -m pip install --upgrade pip
python3 -m pip install toml tomli jsonschema yamllint
python3 -m pip install yamllint
echo ""
echo "✓ bats 版本: $(bats --version)"
echo "✓ Python 版本: $(python3 --version)"
echo "========================================"
- name: 🧪 运行全量测试并生成报告
shell: bash
run: |
set +e
set -o pipefail
overall_fail=0
scripts_status="success"
templates_status="success"
integration_status="success"
docs_status="success"
set -euo pipefail
echo "========================================"
echo "🐚 Shell 脚本测试"
echo "🧪 Python CLI 测试"
echo "========================================"
cd "$REPO_DIR/tests/scripts"
cd "$REPO_DIR"
python3 -m unittest discover -s tests/cli -v
run_bats() {
local name="$1"
local file="$2"
local output="${name}_test_results.tap"
echo "========================================"
echo "🧪 Python 扩展测试"
echo "========================================"
if [ ! -f "$file" ]; then
echo "⚠️ 未找到测试文件: $file"
scripts_status="failure"
overall_fail=1
return
fi
bats --formatter tap "$file" | tee "$output"
if [ $? -ne 0 ]; then
echo "❌ $name 测试失败"
scripts_status="failure"
overall_fail=1
else
echo "✅ $name 测试通过"
fi
}
run_bats "sync_standards" "test_sync_standards.bats"
run_bats "vendor_playbook" "test_vendor_playbook.bats"
run_bats "install_codex_skills" "test_install_codex_skills.bats"
python3 -m unittest discover -s tests -p "test_*.py" -v
echo "========================================"
echo "📄 模板验证测试"
echo "========================================"
cd "$REPO_DIR/tests/templates"
run_validator() {
local name="$1"
local script="$2"
if [ ! -f "$script" ]; then
echo "⚠️ 未找到验证脚本: $script"
templates_status="failure"
overall_fail=1
return
fi
chmod +x "$script"
"./$script"
if [ $? -ne 0 ]; then
echo "❌ $name 模板验证失败"
templates_status="failure"
overall_fail=1
else
echo "✅ $name 模板验证通过"
fi
}
run_validator "python" "validate_python_templates.sh"
run_validator "cpp" "validate_cpp_templates.sh"
run_validator "ci" "validate_ci_templates.sh"
sh tests/templates/validate_python_templates.sh
sh tests/templates/validate_cpp_templates.sh
sh tests/templates/validate_ci_templates.sh
sh tests/templates/validate_project_templates.sh
echo "========================================"
echo "🔗 集成测试"
echo "🔗 文档链接检查"
echo "========================================"
mkdir -p "${TEST_WORKSPACE}"
cd "${TEST_WORKSPACE}"
# 创建测试项目目录
mkdir -p test-project-tsl
mkdir -p test-project-cpp
mkdir -p test-project-multi
echo "========================================"
echo "🧪 测试场景1: TSL 项目标准同步"
echo "========================================"
cd "${TEST_WORKSPACE}/test-project-tsl"
# 初始化 git 仓库
git init
git config user.name "Test User"
git config user.email "test@example.com"
# 模拟 subtree add(包含 .agents 等点目录,排除 .git
mkdir -p docs/standards/playbook
tar -C "$REPO_DIR" --exclude .git -cf - . | tar -C docs/standards/playbook -xf -
# 运行同步脚本
echo "▶ 运行 sync_standards.sh tsl"
sh docs/standards/playbook/scripts/sync_standards.sh tsl
# 验证结果
if [ -d ".agents/tsl" ] && [ -f ".agents/tsl/index.md" ]; then
echo "✅ TSL 规则集同步成功"
else
echo "❌ TSL 规则集同步失败"
integration_status="failure"
overall_fail=1
fi
if grep -q "# BEGIN playbook .gitattributes" .gitattributes 2>/dev/null \
|| grep -q "# Added from playbook .gitattributes" .gitattributes 2>/dev/null \
|| grep -q "^\\* text=auto eol=lf" .gitattributes 2>/dev/null; then
echo "✅ .gitattributes 更新成功"
else
echo "❌ .gitattributes 更新失败"
integration_status="failure"
overall_fail=1
fi
echo "========================================"
echo "🧪 测试场景2: C++ 项目标准同步"
echo "========================================"
cd "${TEST_WORKSPACE}/test-project-cpp"
git init
git config user.name "Test User"
git config user.email "test@example.com"
mkdir -p docs/standards/playbook
tar -C "$REPO_DIR" --exclude .git -cf - . | tar -C docs/standards/playbook -xf -
echo "▶ 运行 sync_standards.sh cpp"
sh docs/standards/playbook/scripts/sync_standards.sh cpp
if [ -d ".agents/cpp" ] && [ -f ".agents/cpp/index.md" ]; then
echo "✅ C++ 规则集同步成功"
else
echo "❌ C++ 规则集同步失败"
integration_status="failure"
overall_fail=1
fi
echo "========================================"
echo "🧪 测试场景3: 多语言项目标准同步"
echo "========================================"
cd "${TEST_WORKSPACE}/test-project-multi"
git init
git config user.name "Test User"
git config user.email "test@example.com"
mkdir -p docs/standards/playbook
tar -C "$REPO_DIR" --exclude .git -cf - . | tar -C docs/standards/playbook -xf -
echo "▶ 运行 sync_standards.sh tsl cpp"
sh docs/standards/playbook/scripts/sync_standards.sh tsl cpp
if [ -d ".agents/tsl" ] && [ -d ".agents/cpp" ] && [ -f ".agents/index.md" ]; then
echo "✅ 多语言规则集同步成功"
else
echo "❌ 多语言规则集同步失败"
integration_status="failure"
overall_fail=1
fi
echo "========================================"
echo "🧪 测试场景4: vendor_playbook 脚本"
echo "========================================"
cd "${TEST_WORKSPACE}"
mkdir -p test-project-vendor
cd test-project-vendor
git init
git config user.name "Test User"
git config user.email "test@example.com"
echo "▶ 运行 vendor_playbook.sh"
sh "$REPO_DIR/scripts/vendor_playbook.sh" . tsl
if [ -d "docs/standards/playbook" ] && [ -d ".agents/tsl" ]; then
echo "✅ vendor_playbook 脚本执行成功"
else
echo "❌ vendor_playbook 脚本执行失败"
integration_status="failure"
overall_fail=1
fi
echo "========================================"
echo "🧹 清理测试环境..."
chmod -R u+w "${TEST_WORKSPACE}" 2>/dev/null || true
rm -rf "${TEST_WORKSPACE}"
echo "✓ 清理完成"
echo "========================================"
echo "📚 文档一致性检查"
echo "========================================"
cd "$REPO_DIR/tests/integration"
if [ -f "check_doc_links.sh" ]; then
chmod +x check_doc_links.sh
./check_doc_links.sh
if [ $? -eq 0 ]; then
echo "✅ 文档链接检查通过"
else
echo "❌ 发现无效链接"
docs_status="failure"
overall_fail=1
fi
else
echo "⚠️ 未找到链接检查脚本,跳过"
fi
echo "========================================"
echo "🔍 检查代理规则一致性"
echo "========================================"
cd "$REPO_DIR"
# 检查 .agents/ 和 docs/ 中的规则是否一致
python3 << 'EOF'
import sys
from pathlib import Path
errors = []
# 检查各语言的 .agents/ 目录
agents_base = Path(".agents")
for lang_dir in ["tsl", "cpp", "python"]:
agents_lang = agents_base / lang_dir
if not agents_lang.exists():
continue
# 检查必须存在的文件
required_files = ["index.md", "auth.md", "code_quality.md"]
for req_file in required_files:
file_path = agents_lang / req_file
if not file_path.exists():
errors.append(f"❌ 缺少文件: {file_path}")
elif file_path.stat().st_size == 0:
errors.append(f"❌ 文件为空: {file_path}")
if errors:
print("\n".join(errors))
sys.exit(1)
else:
print("✅ 代理规则一致性检查通过")
EOF
if [ $? -ne 0 ]; then
docs_status="failure"
overall_fail=1
fi
echo "========================================"
echo "📊 生成测试综合报告"
echo "========================================"
format_status() {
case "$1" in
success)
echo "✅ 通过"
;;
failure)
echo "❌ 失败"
;;
*)
echo "❔ 未知"
;;
esac
}
cat >> $GITHUB_STEP_SUMMARY << EOFSUMMARY
# 🧪 Playbook 测试报告
## 📋 测试执行摘要
| 测试类型 | 状态 |
|---------|------|
| 🐚 Shell 脚本测试 | $(format_status "$scripts_status") |
| 📄 模板验证测试 | $(format_status "$templates_status") |
| 🔗 集成测试 | $(format_status "$integration_status") |
| 📚 文档一致性检查 | $(format_status "$docs_status") |
---
## 🔗 相关链接
- 📝 [测试文档](tests/README.md)
- 🐛 [问题反馈](../../issues)
- 📖 [开发指南](docs/index.md)
---
<div align="center">
*🤖 由 [Gitea Actions](../../actions) 自动生成*
EOFSUMMARY
echo "*📅 生成时间: $(date -u '+%Y-%m-%d %H:%M:%S UTC')*" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "</div>" >> $GITHUB_STEP_SUMMARY
echo "========================================"
if [ "$overall_fail" -ne 0 ]; then
echo "❌ 测试失败"
exit 1
fi
echo "✅ 全量测试通过"
sh tests/integration/check_doc_links.sh