#!/usr/bin/env bash
# agent-run-record.sh - run record for a coding agent that runs in GitHub Actions.
#
# Reads what GitHub already stores (workflow runs, step timings, pull requests)
# and prints how long the agent's runs take, how much of that time is the agent
# step and the checks, optionally the tokens used, and how the agent's pull
# requests ended. It changes nothing in the repository.
#
# Usage:
#   agent-run-record.sh -w <workflow> [-a <agent account>] [options]
#     -w  workflow file or name that runs the agent (required)
#     -a  account that opens the agent's pull requests, written the way
#         `gh pr list --author` takes it, e.g. app/my-agent (omit to skip that part)
#     -R  owner/repo (default: the repository of the current directory)
#     -s  regex matching the agent step's name (default: codex-action)
#     -c  regex matching the check step's name (default: none, the row is left out)
#     -n  how many recent runs and pull requests to read (default: 200)
#     -t  also read token usage from the run logs (one log download per run)
#     -o  write one row per successful run to this TSV file
#
# Needs: gh (authenticated, read access to the repository) and jq; column, when present, aligns the summary.

set -euo pipefail

wf="" agent="" step_re="codex-action" check_re="" limit=200 tokens=0 out=""
while getopts "w:a:R:s:c:n:to:h" opt; do
  case "$opt" in
    w) wf=$OPTARG ;;
    a) agent=$OPTARG ;;
    R) export GH_REPO=$OPTARG ;;
    s) step_re=$OPTARG ;;
    c) check_re=$OPTARG ;;
    n) limit=$OPTARG ;;
    t) tokens=1 ;;
    o) out=$OPTARG ;;
    *) sed -n '2,21p' "$0"; exit 2 ;;
  esac
done
[ -n "$wf" ] || { echo "missing -w <workflow>; run with -h for usage" >&2; exit 2; }
for tool in gh jq; do
  command -v "$tool" >/dev/null || { echo "needs $tool on PATH" >&2; exit 2; }
done

records=$(mktemp)
trap 'rm -f "$records"' EXIT

# GitHub's API answers with an occasional 5xx; one failed call must not lose the record.
gh_retry() {
  local result attempt
  for attempt in 1 2 3; do
    if result=$(gh "$@" 2>/dev/null); then printf '%s\n' "$result"; return 0; fi
    sleep $((attempt * 2))
  done
  echo "skipped after three failed attempts: gh $*" >&2
  return 1
}

runs=$(gh_retry run list --workflow "$wf" -L "$limit" --json databaseId,startedAt,updatedAt,status,conclusion)

echo "Workflow $wf: $(jq length <<<"$runs") most recent runs"
jq -r '[.[] | select(.status == "completed")] | group_by(.conclusion)
       | map("  \(.[0].conclusion): \(length)") | .[]' <<<"$runs"

# The log interleaves the agent's last message with the counter, so the number
# is the first all-digits line within a few lines after "tokens used". Colour
# codes arrive either as a real escape byte or spelled out as caret-bracket.
read_tokens() {
  { gh_retry run view "$1" --log || true; } | awk -F'\t' '
    { msg = $3; sub(/^[^ ]* /, "", msg); gsub(/(\033|\^\[)\[[0-9;]*m/, "", msg) }
    seen && msg ~ /^[0-9][0-9,]*$/ { gsub(/,/, "", msg); total += msg; found = 1; seen = 0; next }
    seen && ++n > 5 { seen = 0 }
    msg == "tokens used" { seen = 1; n = 0 }
    END { if (found) print total }'
}

jq -r '.[] | select(.conclusion == "success") | [.databaseId, .startedAt, .updatedAt] | @tsv' <<<"$runs" |
while IFS=$'\t' read -r id started updated; do
  tok=""
  jobs=$(gh_retry run view "$id" --json jobs) || continue
  [ "$tokens" = 1 ] && tok=$(read_tokens "$id")
  jq -r --arg id "$id" --arg s "$started" --arg u "$updated" \
        --arg step "$step_re" --arg check "$check_re" --arg tok "$tok" '
    # gh reports a step that never ran with a year-1 timestamp.
    def spans(re): [.jobs[].steps[]
      | select(.startedAt > "1971" and .completedAt > "1971")
      | select(.name | startswith("Post ") | not)
      | select(.name | test(re; "i"))
      | [(.startedAt | fromdateiso8601), (.completedAt | fromdateiso8601)]];
    # Jobs can run in parallel, so matching steps can overlap: count each second once.
    def covered: sort
      | reduce .[] as $i ([]; if length > 0 and $i[0] <= .[-1][1]
                              then .[-1][1] = ([.[-1][1], $i[1]] | max) else . + [$i] end)
      | map(.[1] - .[0]) | add // 0;
    (($u | fromdateiso8601) - ($s | fromdateiso8601)) as $elapsed
    | spans($step) as $a
    | (if $check == "" then [] else spans($check) end) as $c
    | [$id, $s, $elapsed, ($a | covered), (if $check == "" then "" else ($c | covered) end), $tok,
       ($elapsed - ($a + $c | covered))] | @tsv' <<<"$jobs"
done > "$records"

if [ -n "$out" ]; then
  { printf 'run_id\tstarted_at\telapsed_s\tagent_step_s\tchecks_s\ttokens\tother_s\n'; cat "$records"; } > "$out"
fi

echo
jq -R -s -r '
  def med: sort | if length == 0 then null
                  elif length % 2 == 1 then .[length / 2 | floor]
                  else (.[length / 2 - 1] + .[length / 2]) / 2 end;
  def row(name; xs): if (xs | length) == 0 then empty
                     else [name, (xs | med), (xs | min), (xs | max), (xs | length)] | @tsv end;
  [split("\n")[] | select(length > 0) | split("\t")] as $r
  | ($r | map(.[2] | tonumber)) as $elapsed
  | ($r | map(.[3] | tonumber)) as $agent
  | ($r | map(select(.[4] != "") | .[4] | tonumber)) as $checks
  | ($r | map(.[6] | tonumber)) as $other
  | ($r | map(select((.[5] // "") != "") | .[5] | tonumber)) as $tokens
  | ($r | map(select((.[2] | tonumber) > 0) | 100 * (.[3] | tonumber) / (.[2] | tonumber) | round)) as $share
  | (["successful runs", "median", "min", "max", "runs"] | @tsv),
    row("elapsed (s)"; $elapsed),
    row("agent step (s)"; $agent),
    row("checks (s)"; $checks),
    row("everything else (s)"; $other),
    row("agent step, % of elapsed"; $share),
    row("tokens"; $tokens)
' "$records" | if command -v column >/dev/null; then column -t -s $'\t'; else cat; fi

[ -n "$out" ] && echo && echo "One row per run: $out"

if [ -n "$agent" ]; then
  bot=${agent#app/}
  echo
  # One request per pull request: asking for the commits of many pull requests
  # at once exceeds GitHub's GraphQL node limit.
  gh_retry pr list --author "$agent" --state all -L "$limit" --json number --jq '.[].number' |
  while read -r number; do gh_retry pr view "$number" --json state,commits || true; done |
  jq -s -r --arg agent "$agent" --arg bot "$bot" '
    def kind: [.commits[].authors[].login] as $who
      | if ($who | any(. != "" and . != $bot and . != ($bot + "[bot]"))) then "other"
        elif ($who | length == 0) or ($who | any(. == "")) then "unknown"
        else "agent" end;
    def count(f): map(select(f)) | length;
    (map(select(.state == "MERGED"))) as $merged
    | "Pull requests opened by \($agent): \(length)",
      "  merged: \($merged | length)   closed without merge: \(count(.state == "CLOSED"))   open: \(count(.state == "OPEN"))",
      "  merged with only agent commits: \($merged | count(kind == "agent"))",
      "  merged with a commit by someone else: \($merged | count(kind == "other"))",
      "  merged, commit author without a GitHub login: \($merged | count(kind == "unknown"))"'
fi
