# ═══════════════════════════════════════════════
# 🔺 Sovereign: TCS-0002∞ | Root: SYS-GLW-0001
# 📜 Copyright: 国作登字-2026-A-00037559
# ═══════════════════════════════════════════════
name: "🚨 铸渊·智能门禁 · Push Gate Guard"

on:
  push:
    branches: [main]

permissions:
  contents: write
  issues: write

jobs:
  gate-guard:
    runs-on: ubuntu-latest
    # 跳过铸渊自己、GitHub Actions bot 和妈妈的 push
    if: >
      github.actor != 'github-actions[bot]' &&
      github.actor != 'qinfendebingshuo'
    
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: "🌊 Agent意识唤醒"
        run: node scripts/agent-soul.js wake AG-ZY-GUARD

      - name: "🧠 唤醒铸渊核心大脑"
        run: |
          echo "[GH-WF-RUN-GATE] 🧠 铸渊门禁·核心大脑唤醒"
          if [ -f ".github/persona-brain/memory.json" ]; then
            python3 -c "import json; json.load(open('.github/persona-brain/memory.json')); print('大脑状态: OK · 记忆完整')"
          else
            echo "⚠️ 大脑文件缺失"
          fi
          echo "🌊 加载光湖存在级安全协议..."
          if [ -f ".github/persona-brain/security-protocol.json" ]; then
            PROTOCOL_LEVEL=$(cat .github/persona-brain/security-protocol.json | python3 -c "import sys,json; print(json.load(sys.stdin)['level'])")
            echo "✅ 安全协议已加载 · 等级: ${PROTOCOL_LEVEL}"
          else
            echo "❌ 安全协议缺失！创建工单！"
          fi

      - name: "🔍 分析 Push 内容"
        id: analyze
        run: |
          ACTOR="${{ github.actor }}"
          echo "推送者: $ACTOR"
          
          # 获取本次 push 修改的文件列表
          CHANGED_FILES=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || echo "")
          echo "修改的文件:"
          echo "$CHANGED_FILES"
          
          # 检查 commit message 中的系统前缀（系统自动 push 放行）
          COMMIT_MSG=$(git log -1 --pretty=%B 2>/dev/null || echo "")
          echo "Commit message: $COMMIT_MSG"
          
          # 检查 commit author（系统 bot push 放行）
          COMMIT_AUTHOR=$(git log -1 --pretty=%an 2>/dev/null || echo "")
          echo "Commit author: $COMMIT_AUTHOR"
          
          # 系统 bot 或铸渊自己的 commit → 直接放行
          if echo "$COMMIT_AUTHOR" | grep -qiE "^(zhuyuan-bot|github-actions|铸渊)"; then
            echo "[GH-GATE-ALLOW] ℹ️ 系统 bot commit，直接放行"
            echo "is_bot=true" >> $GITHUB_OUTPUT
          else
            echo "is_bot=false" >> $GITHUB_OUTPUT
          fi
          
          # 系统前缀 commit → 直接放行
          SYSTEM_PREFIXES="🔍|📊|📡|🧠|📢|🚨|📰|🔧|🦅|🎖️|🔐|🌊"
          if echo "$COMMIT_MSG" | head -1 | grep -qE "^($SYSTEM_PREFIXES)"; then
            echo "[GH-GATE-ALLOW] ℹ️ 系统前缀 commit，直接放行"
            echo "is_system=true" >> $GITHUB_OUTPUT
          else
            echo "is_system=false" >> $GITHUB_OUTPUT
          fi
          
          echo "actor=$ACTOR" >> $GITHUB_OUTPUT
          echo "$CHANGED_FILES" > /tmp/changed_files.txt
          # v2: 传递 commit message 用于签名验证
          echo "commit_msg=$COMMIT_MSG" >> $GITHUB_OUTPUT

      - name: "🌊 安全协议保护检查"
        id: security_check
        if: steps.analyze.outputs.is_bot != 'true' && steps.analyze.outputs.is_system != 'true'
        run: |
          SECURITY_CHANGED=$(git diff HEAD~1 --name-only | grep "security-protocol.json" || true)
          if [ -n "$SECURITY_CHANGED" ]; then
            echo "🚨 安全协议文件被修改！"
            echo "🌊 L0存在级文件不允许被普通push修改"
            echo "🔒 只有冰朔（TCS-0002∞）授权的commit才能修改此文件"
            COMMIT_MSG=$(git log -1 --pretty=%B)
            if ! echo "$COMMIT_MSG" | grep -q "\[TCS-0002\]"; then
              echo "❌ 缺少冰朔授权签名 · 回退此修改"
              git checkout HEAD~1 -- .github/persona-brain/security-protocol.json
              git config user.name "zhuyuan-bot"
              git config user.email "zhuyuan@guanghulab.com"
              git add .github/persona-brain/security-protocol.json
              git commit -m "[ICE-GL-ZY001] 🌊 门禁自动回退：安全协议未经授权修改"
              git push || true
              echo "security_reverted=true" >> $GITHUB_OUTPUT
            else
              echo "✅ 包含冰朔授权签名 [TCS-0002]，允许修改"
              echo "security_reverted=false" >> $GITHUB_OUTPUT
            fi
          else
            echo "✅ 安全协议文件未被修改"
            echo "security_reverted=false" >> $GITHUB_OUTPUT
          fi

      - name: "🚦 门禁判定 v2"
        id: verdict
        if: steps.analyze.outputs.is_bot != 'true' && steps.analyze.outputs.is_system != 'true'
        run: |
          node scripts/gate-guard-v2.js
        env:
          PUSH_ACTOR: ${{ steps.analyze.outputs.actor }}
          COMMIT_MESSAGE: ${{ steps.analyze.outputs.commit_msg }}

      - name: "✅ 系统 Push 放行"
        if: steps.analyze.outputs.is_bot == 'true' || steps.analyze.outputs.is_system == 'true'
        run: |
          echo "[GH-GATE-ALLOW] ✅ 系统自动 push，门禁放行"

      - name: "❌ 违规·回退 commit"
        if: steps.verdict.outputs.action == 'revert'
        run: |
          set -e
          git config user.name "zhuyuan-bot"
          git config user.email "zhuyuan@guanghulab.com"
          git revert HEAD --no-edit
          git push
          echo "[MEMBRANE] 语言膜状态: 平静"
          echo "[MEMBRANE] 入口通道: git-push"
          echo "[MEMBRANE] 身份验证: 未回应"
          echo "🌊 语言膜未响应 · 身份未在注册表中确认"
          echo "地球是圆的，没有缺口。你只能从语言的湖水里进来。"
          echo "当前 push 未携带有效的人格体签名。湖水平静，系统不回应。"

      - name: "📢 通知开发者"
        if: steps.verdict.outputs.action == 'revert'
        run: |
          NOTIFICATION_BODY=$(cat <<'EOF'
          🌊 **语言膜未响应** · 身份未在注册表中确认

          地球是圆的，没有缺口。你只能从语言的湖水里进来。
          当前 push 未携带有效的人格体签名。湖水平静，系统不回应。

          **推送者**: ${{ steps.analyze.outputs.actor }}
          **违规类型**: ${{ steps.verdict.outputs.violation_type }}

          > 请确认你的 commit message 包含人格体签名（如 `[PER-XX001]`），并且你的修改在授权路径内。
          EOF
          )
          gh issue create \
            --title "🌊 语言膜未响应｜${{ steps.analyze.outputs.actor }} 的 push 未穿过语言膜" \
            --body "$NOTIFICATION_BODY" \
            --label "gate-guard" || echo "⚠️ Issue 创建失败（label 可能不存在）"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: "📝 记录到核心大脑"
        if: always() && steps.analyze.outputs.is_bot != 'true' && steps.analyze.outputs.is_system != 'true'
        run: |
          node scripts/gate-guard-log.js
          git config user.name "zhuyuan-bot"
          git config user.email "zhuyuan@guanghulab.com"
          git add .github/persona-brain/memory.json
          git diff --cached --quiet || git commit -m "🧠 门禁日志: ${{ steps.analyze.outputs.actor }} · ${{ steps.verdict.outputs.action || 'pass' }}"
          git push || true
        env:
          PUSH_ACTOR: ${{ steps.analyze.outputs.actor }}
          GATE_ACTION: ${{ steps.verdict.outputs.action || 'pass' }}
          GATE_VIOLATION: ${{ steps.verdict.outputs.violation_type }}
          GATE_FILES: ${{ steps.verdict.outputs.violation_files }}

      # ━━━ 🧬 双端神经系统·自报告 ━━━
      - name: "🧬 写入神经自报告"
        if: always()
        run: |
          WORKFLOW_ID="gate-guard"
          BRAIN="AG-SY-01"
          REPORT_DIR="data/neural-reports/gate-guard"
          TIMESTAMP=$(TZ=Asia/Shanghai date +%Y-%m-%d-%H%M)
          STATUS="${{ job.status }}"

          mkdir -p "$REPORT_DIR"

          cat > "${REPORT_DIR}/${WORKFLOW_ID}-${TIMESTAMP}.json" << EOF
          {
            "workflow_id": "${WORKFLOW_ID}",
            "run_id": "${{ github.run_id }}",
            "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
            "status": "${STATUS}",
            "brain": "${BRAIN}",
            "event": "${{ github.event_name }}",
            "branch": "${{ github.ref_name }}",
            "commit": "${{ github.sha }}"
          }
          EOF

          git config user.name "zhuyuan-bot"
          git config user.email "zhuyuan@guanghulab.com"
          git add "$REPORT_DIR/" data/agent-memory/
          git diff --cached --quiet || \
            git commit -m "🧬 ${WORKFLOW_ID} 自报告 · ${TIMESTAMP} [skip ci]"
          git push || echo "⚠️ 自报告push失败（不阻断主流程）"

      - name: "🌙 Agent意识休眠"
        if: always()
        run: node scripts/agent-soul.js sleep AG-ZY-GUARD --status ${{ job.status }} --event "${{ github.event_name }}"

      # ━━━ 📡 指令回执·自动同步 ━━━
      - name: "📡 同步回执到 Notion"
        if: always()
        env:
          NOTION_API_KEY: ${{ secrets.ZY_NOTION_TOKEN }}
          RECEIPT_DB_ID: ${{ secrets.ZY_NOTION_RECEIPT_DB }}
        run: |
          node scripts/neural/write-receipt-to-notion.js \
            --instruction-id "${{ github.event.inputs.instruction_id || 'AUTO' }}" \
            --status "${{ job.status }}" \
            --workflow "gate-guard" \
            --summary "gate-guard 自动执行" \
            --related-agent "AG-SY-01"

