name: "Loop: Triage"

# Generated by `micro loop init`. The feedback path of the evaluator: when a CI
# workflow (<< .CIWorkflow >>) fails on a non-PR run, dispatch the agent
# (<< .AgentMention >>) with the instruction in .github/loop/prompts/triage.md
# to root-cause the failure and file scoped fix issues back into the queue — so
# failures become fixes with no human in the middle. Gated on << .TokenSecret >>.

on:
  workflow_run:
    workflows: << .CIWorkflowsYAML >>
    types: [completed]

permissions:
  issues: write

concurrency:
  group: loop-triage
  cancel-in-progress: false

jobs:
  triage:
    # Only real failures on branch pushes/schedules — not PR-run failures, which
    # the PR author already sees.
    if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event != 'pull_request' }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4 # needed to read the prompt file
      - name: Dispatch triage
        env:
          GH_TOKEN: ${{ secrets.<< .TokenSecret >> || github.token }}
          HAS_TOKEN: ${{ secrets.<< .TokenSecret >> != '' }}
          REPO: ${{ github.repository }}
          RUN_ID: ${{ github.event.workflow_run.id }}
          RUN_URL: ${{ github.event.workflow_run.html_url }}
          WORKFLOW_NAME: ${{ github.event.workflow_run.name }}
        run: |
          if [ "$HAS_TOKEN" != "true" ]; then
            echo "<< .TokenSecret >> is not set — skipping."
            exit 0
          fi
          PROMPT=".github/loop/prompts/triage.md"
          if [ ! -f "$PROMPT" ]; then
            echo "missing $PROMPT — run 'micro loop init'." >&2
            exit 1
          fi
          ISSUE_URL=$(gh issue create --repo "$REPO" \
            --title "Loop: triage failed run $RUN_ID ($WORKFLOW_NAME)" \
            --body "The '$WORKFLOW_NAME' workflow failed on a non-PR run: $RUN_URL")
          ISSUE_NUM="${ISSUE_URL##*/}"
          echo "Opened issue #$ISSUE_NUM — dispatching triage."
          {
            echo "<< .AgentMention >>"
            echo
            sed -e '/<!--/,/-->/d' -e "s/__ISSUE__/$ISSUE_NUM/g" -e "s#__RUNURL__#$RUN_URL#g" "$PROMPT"
          } > "$RUNNER_TEMP/loop-body.md"
          gh issue comment "$ISSUE_NUM" --repo "$REPO" --body-file "$RUNNER_TEMP/loop-body.md"
