name: weekly-stale-sweep

# 远端 stale 分支周扫
#
# 闭环载体：Gitea issue（label `stale-branch-cleanup`，标题 `stale-branches 待清理 YYYY-MM`）
# - 命中可清 / 长期未处理 → 自动 PATCH 或创建 monthly issue + 代删 CI bot orphan
# - 全空（无可清也无 long-stale）→ 静默跳过，不刷屏
#
# 触发：
#   - schedule: 周一 01:13 UTC (= 09:13 Asia/Shanghai)
#               比 weekly-retro 晚 10 分钟，避免同时跑挤 runner
#   - workflow_dispatch: 手动触发
#
# 安全网（脚本默认，不可在 CI 关掉）：
#   - 保护分支白名单（develop/staging/production/main/master）
#   - 有 open PR 指向的分支永不删
#   - agent-pool slot 持有的分支永不删
#   - 个人分支（@-可达 Gitea 用户）只 @ 不自动删
#   - 仅 orphan（CI bot / noreply 作者）走自动删
#
# 完整设计见 docs/standards/10-agent-pool.md 以及脚本 docstring。

permissions:
  contents: write   # 删 orphan 分支需要
  issues: write     # 创建 / PATCH issue
  pull-requests: read

on:
  schedule:
    - cron: '13 1 * * 1'  # Mon 01:13 UTC = Mon 09:13 Asia/Shanghai
  workflow_dispatch:
    inputs:
      dry-run:
        description: 'dry-run（只扫描，不删分支不发 issue）'
        required: false
        default: 'false'
        type: choice
        options: [ 'false', 'true' ]
      age-days:
        description: '分支 age ≥ N 天才纳入清理'
        required: false
        default: '14'
      long-stale-days:
        description: '未被吸收但 ≥ N 天触发 long-stale 提醒'
        required: false
        default: '30'

jobs:
  weekly-stale-sweep:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # patch-id 比对需要完整 develop 历史

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Run sweep-remote-stale
        env:
          GITEA_API_TOKEN: ${{ secrets.WEEKLY_RETRO_TOKEN }}
          AGE_DAYS: ${{ inputs.age-days || '14' }}
          LONG_STALE_DAYS: ${{ inputs.long-stale-days || '30' }}
          DRY_RUN: ${{ inputs.dry-run == 'true' && '1' || '' }}
        run: |
          set -euo pipefail

          ARGS=(
            "--age-days" "${AGE_DAYS}"
            "--long-stale-days" "${LONG_STALE_DAYS}"
          )

          if [ -z "${DRY_RUN}" ]; then
            ARGS+=( "--post-issue" "--sweep-orphan" "--execute" )
          fi

          echo "Running: python3 scripts/ops/sweep-remote-stale.py ${ARGS[*]}"
          python3 scripts/ops/sweep-remote-stale.py "${ARGS[@]}"

      - name: Upload audit log
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: stale-sweep-audit-${{ github.run_id }}
          path: testing/reports/stale-cleanup/*.log
          if-no-files-found: ignore
          retention-days: 30
