# TeamBrain — sessions-branch rotation (monthly)
#
# The teambrain/sessions branch is a never-merged orphan branch that gains one
# commit per captured session, so its history grows unboundedly. This job
# squashes the branch to a single commit holding the current tree (the records
# themselves are preserved; only the commit history is dropped) and force-
# pushes it, keeping clones small. It never touches main.
#
# Copy this file to `.github/workflows/teambrain-sessions-rotation.yml`.
name: teambrain-sessions-rotation

on:
  schedule:
    - cron: '0 4 1 * *' # 04:00 UTC on the 1st of each month
  workflow_dispatch:

permissions:
  contents: write

jobs:
  rotate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Squash and prune the sessions branch
        env:
          GIT_AUTHOR_NAME: teambrain-bot
          GIT_AUTHOR_EMAIL: teambrain-bot@users.noreply.github.com
          GIT_COMMITTER_NAME: teambrain-bot
          GIT_COMMITTER_EMAIL: teambrain-bot@users.noreply.github.com
        run: |
          set -euo pipefail
          branch=teambrain/sessions
          if ! git ls-remote --exit-code --heads origin "$branch" >/dev/null 2>&1; then
            echo "no $branch on origin; nothing to rotate"
            exit 0
          fi
          git fetch origin "$branch:$branch"
          tree=$(git rev-parse "$branch^{tree}")
          stamp=$(date -u +%Y-%m)
          new=$(git commit-tree "$tree" -m "chore(teambrain): squash sessions $stamp")
          git update-ref "refs/heads/$branch" "$new"
          git push --force origin "$branch"
          echo "rotated $branch to a single commit ($new)"
