#!/usr/bin/env bash
# copilot-fusion-run - resilient headless GitHub Copilot CLI (Fusion) runner for Linux and macOS.
# Counterpart of agy-run. Requirements: bash 3.2+, python3, git, the `copilot` CLI (npm install -g @github/copilot), signed in by you (`copilot login`).
#
# Usage (run it in the FOREGROUND of a background shell job; never nohup/&/disown, or nobody notices when it ends):
#   copilot-fusion-run -t TAG -p PROMPT_FILE [-C WORKDIR] [-o OUTDIR] [-F standard|high|max] [-m MODEL] [-T PRINT_TIMEOUT_S]
#                      [-r MAX_RESUMES] [-c MAX_AI_CREDITS] [-S] [-P] [-b BOT] [-j JOB] [-u NOTIFY_URL] [-B COPILOT_BINARY]
#   -F  Fusion tier (default standard)           -m  model (default fusion; any other value is pinned and gets no --fusion-tier)
#   -T  outer print timeout seconds (default 3600, 0 = none)   -r  network-drop resumes (default 3)
#   -c  --max-ai-credits cap (CLI minimum 30, 0 = off)          -S  run without --sandbox     -P  allow `git push` (denied by default)
# Behaviour:
#   * new session gets its id up front (--session-id); network drops resume it (--resume=<id>) after ~10/20/40 s;
#     rate limit / quota errors back off ~60/120/240/480 s; a print timeout resumes once; auth errors, credit-cap hits and
#     bad arguments stop the run. Never uses --yolo or --allow-all*.
#   * fixed tool allow list, shell allow rules, URL allow list and deny rules (publish/release/PR commands are always denied).
#   * output dir default $HOME/copilot-runs: TAG.aN.jsonl, TAG.aN.cli.log, TAG.aN.usage-raw.json, TAG.usage.json, TAG.done,
#     plus RUNSUMMARY and EXIT lines on stdout. Earlier files for the same tag are moved to TAG.prev-<timestamp>/.
# Env: COPILOT_AVAILABLE_TOOLS overrides the tool allow list (the default names follow the Copilot CLI Unix tool names:
#      bash,list_bash,read_bash,stop_bash,apply_patch,create,edit,view,glob,grep - check `copilot --help` if your version differs).
#      COPILOT_NOTIFY_URL / COPILOT_NOTIFY_SECRET / COPILOT_NOTIFY_SECRET_FILE / COPILOT_NOTIFY_HEADER (optional webhook).
# This script never reads or prints auth files or tokens, never edits ~/.copilot/settings.json, and does not take the build lock
# (tell the agent to run heavy builds as `buildlock <command>`).
set -u
TAG=""; PROMPT=""; MODEL=fusion; TIER=standard; WD=$PWD; OUT=""; TMO=3600; MAXRES=3; CAP=0; NOSB=0; PUSH=0
BOT=${COPILOT_BOT:-${AGY_BOT:-$(id -un 2>/dev/null || echo bot)}}; JOB=""; NURL=${COPILOT_NOTIFY_URL:-${AGY_NOTIFY_URL:-}}; CBIN=${COPILOT_PATH:-}
usage() { sed -n '2,22p' "$0"; exit "${1:-2}"; }
while [ $# -gt 0 ]; do
  case "$1" in
    -t|--tag) TAG=$2; shift 2;; -p|--prompt) PROMPT=$2; shift 2;; -m|--model) MODEL=$2; shift 2;;
    -F|--fusion-tier) TIER=$2; shift 2;; -C|--workdir) WD=$2; shift 2;; -o|--outdir) OUT=$2; shift 2;;
    -T|--print-timeout) TMO=$2; shift 2;; -r|--max-resumes) MAXRES=$2; shift 2;; -c|--max-ai-credits) CAP=$2; shift 2;;
    -S|--no-sandbox) NOSB=1; shift;; -P|--allow-push) PUSH=1; shift;; -n|--no-skip-permissions) shift;;
    -b|--bot) BOT=$2; shift 2;; -j|--job) JOB=$2; shift 2;; -u|--notify-url) NURL=$2; shift 2;; -B|--copilot-path) CBIN=$2; shift 2;;
    -h|--help) usage 0;; *) echo "copilot-fusion-run: unknown option $1" >&2; usage 2;;
  esac
done
fail() { echo "copilot-fusion-run: $*"; echo "EXIT 1"; exit 1; }
[ -n "$TAG" ] && [ -n "$PROMPT" ] || usage 2
case "$TIER" in standard|high|max) ;; *) fail "invalid --fusion-tier '$TIER' (standard|high|max)";; esac
command -v python3 >/dev/null 2>&1 || fail "python3 is required"
[ -n "$CBIN" ] || CBIN=$(command -v copilot 2>/dev/null || true)
[ -n "$CBIN" ] && [ -x "$CBIN" ] || fail "copilot CLI not found (npm install -g @github/copilot, then make sure it is on PATH, or pass -B /path/to/copilot)"
[ -f "$PROMPT" ] || fail "prompt file not found: $PROMPT"
WD=$(cd "$WD" 2>/dev/null && pwd) || fail "workdir not found"
[ -n "$OUT" ] || OUT=$HOME/copilot-runs
mkdir -p "$OUT" && OUT=$(cd "$OUT" && pwd) || fail "cannot create outdir"
[ -n "$JOB" ] || JOB=$TAG
export NODE_OPTIONS=${NODE_OPTIONS:---max-old-space-size=3072}
[ "${NODE_ENV:-}" = production ] && unset NODE_ENV
unset COPILOT_ALLOW_ALL
[ "$TMO" != 0 ] && [ "$TMO" -lt 3600 ] && echo "copilot-fusion-run: warning: print-timeout ${TMO}s < 3600s"
if [ "$CAP" -gt 0 ] && [ "$CAP" -lt 30 ]; then echo "copilot-fusion-run: warning: MaxAiCredits $CAP raised to the CLI minimum of 30"; CAP=30; fi
[ "$MODEL" != fusion ] && echo "copilot-fusion-run: warning: pinned model '$MODEL' (not Fusion); --fusion-tier is not passed"

# previous files for this tag are moved aside, never deleted
rm -f "$OUT/$TAG.done"
if ls "$OUT/$TAG".a[0-9]* "$OUT/$TAG.usage.json" >/dev/null 2>&1; then
  PREV="$OUT/$TAG.prev-$(date +%Y%m%d-%H%M%S)"; mkdir -p "$PREV"
  for f in "$OUT/$TAG".a[0-9]* "$OUT/$TAG.usage.json"; do [ -e "$f" ] && mv "$f" "$PREV/"; done
  echo "copilot-fusion-run: previous $TAG files moved to $PREV"
fi

githead() { git -C "$WD" rev-parse HEAD 2>/dev/null || true; }
HEAD0=$(githead)

# ---------- permissions ----------
AVAIL=${COPILOT_AVAILABLE_TOOLS:-bash,list_bash,read_bash,stop_bash,apply_patch,create,edit,view,glob,grep}
SHELLALLOW="git npm npx pnpm yarn node dotnet python python3 pip pytest go cargo make"
URLALLOW="github.com api.github.com raw.githubusercontent.com registry.npmjs.org npmjs.com www.npmjs.com pypi.org files.pythonhosted.org api.nuget.org www.nuget.org crates.io static.crates.io index.crates.io proxy.golang.org sum.golang.org"
DENY="shell(gh pr)|shell(gh release)|shell(gh repo)|shell(npm publish)|shell(pnpm publish)|shell(yarn publish)|shell(yarn npm publish)|shell(npx npm publish)|shell(dotnet nuget push)|shell(cargo publish)|shell(twine upload)|shell(python -m twine upload)|shell(python3 -m twine upload)"
[ "$PUSH" = 1 ] || DENY="shell(git push)|$DENY"
SECRETVARS="COPILOT_NOTIFY_SECRET,COPILOT_NOTIFY_SECRET_FILE,AGY_NOTIFY_SECRET,AGY_NOTIFY_SECRET_FILE,COPILOT_GITHUB_TOKEN,GH_TOKEN,GITHUB_TOKEN"

# ---------- prompt (long prompts are passed by file reference) ----------
PTEXT=$(cat "$PROMPT"); PLEN=${#PTEXT}; LONGDIR=""
if [ "$PLEN" -gt 100000 ]; then
  LONGDIR="$OUT/$TAG.prompt"; mkdir -p "$LONGDIR"; cp "$PROMPT" "$LONGDIR/task.txt"
  echo "copilot-fusion-run: prompt is $PLEN chars; passing a short -p that points at $LONGDIR/task.txt"
  PTEXT="Your full task is in the file $LONGDIR/task.txt ($PLEN characters). Read it completely with the view tool and carry it out exactly, including the required final summary and final commit SHA."
fi
CONT='Your previous turn was cut off by a network error or time limit. First check git status and git log to see what is already done; do NOT redo committed work. Then continue the original task to completion and end with the required summary and final commit SHA.'

# ---------- python helper (portable timeout runner, log parsing, classification, usage summary, webhook) ----------
PY=$(mktemp "${TMPDIR:-/tmp}/cfr.XXXXXX") || fail "mktemp failed"
trap 'rm -f "$PY"' EXIT
cat > "$PY" <<'PYEOF'
import json, os, re, shlex, signal, subprocess, sys, time, glob

def read_run(path):
    r = dict(started=False, sid=None, models=[], tiers=[], resp="", result_exit=None, text="")
    if not os.path.exists(path): return r
    lines = open(path, encoding="utf-8", errors="replace").read().splitlines()
    nonjson, js = [], []
    for l in lines:
        if not l.startswith('{"type":'):
            nonjson.append(l); continue
        js.append(l)
        try: o = json.loads(l)
        except Exception: continue
        t, d = o.get("type"), (o.get("data") or {})
        if t == "session.start": r["started"] = True; r["sid"] = d.get("sessionId")
        elif t == "session.auto_mode_resolved":
            r["models"].append(str(d.get("chosenModel"))); r["tiers"].append(str(d.get("autoTier")))
        elif t == "assistant.message":
            c = str(d.get("content") or "")
            if c.strip(): r["resp"] = c
        elif t == "result": r["result_exit"] = o.get("exitCode")
    r["text"] = " ".join(nonjson + js[-6:])
    return r

def classify(rc, text, timed_out):
    if rc == 0 and not timed_out: return "OK"
    if timed_out: return "PRINT_TIMEOUT"
    e = text.lower()
    if re.search(r"invalid value|unexpected argument|unrecognized|error: the argument|for more information, try '--help'", e): return "ARGS"
    if re.search(r"not logged in|not authenticated|unauthenticated|authentication (required|failed|error)|no authentication|copilot login|/login|bad credentials|http 401|status 401|\b401\b|no access to copilot|not have access to copilot", e): return "AUTH"
    if re.search(r"max[- _]?ai[- _]?credits|credit (limit|cap)|credits? (limit|cap|exhausted|exceeded)|out of (ai )?credits|insufficient credits|limit reached", e): return "CREDITS"
    if re.search(r"rate.?limit|too many requests|\b429\b|quota", e): return "QUOTA"
    if re.search(r"econnreset|etimedout|enotfound|eai_again|econnrefused|network|fetch failed|socket|connection (reset|closed|timed out|error)|timed out|stream (was )?(interrupted|closed)|unavailable|\b50[234]\b|broken pipe|eof", e): return "NETWORK"
    return "KILLED_OR_OTHER"

def cmd_run():
    # run TIMEOUT CWD OUTFILE ERRFILE -- cmd...   exit 124 on timeout. Kills the whole process group.
    to, cwd, out, err = int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5]
    cmd = sys.argv[7:]
    p = subprocess.Popen(cmd, cwd=cwd, stdin=subprocess.DEVNULL, stdout=open(out, "wb"), stderr=open(err, "wb"), start_new_session=True)
    def kill_group(*_):
        try: os.killpg(p.pid, signal.SIGTERM)
        except Exception: pass
        time.sleep(3)
        try: os.killpg(p.pid, signal.SIGKILL)
        except Exception: pass
        sys.exit(143)
    signal.signal(signal.SIGTERM, kill_group); signal.signal(signal.SIGINT, kill_group); signal.signal(signal.SIGHUP, kill_group)
    try:
        rc = p.wait(timeout=to if to > 0 else None)
    except subprocess.TimeoutExpired:
        for sig in (signal.SIGTERM, signal.SIGKILL):
            try: os.killpg(p.pid, sig)
            except Exception: pass
            try: p.wait(timeout=15); break
            except Exception: pass
        sys.exit(124)
    sys.exit(rc if rc >= 0 else 128 - rc)

def cmd_analyze():
    # analyze LOG RC TIMEDOUT EXTRAFILE  -> shell assignments
    log, rc, to, extra = sys.argv[2], int(sys.argv[3]), sys.argv[4] == "1", sys.argv[5]
    ev = read_run(log)
    ex = open(extra, encoding="utf-8", errors="replace").read() if os.path.exists(extra) else ""
    cls = classify(rc, ev["text"] + " " + ex, to)
    print("STARTED=%d" % (1 if ev["started"] else 0)); print("NSID=%s" % shlex.quote(ev["sid"] or "")); print("CLS=%s" % cls)

def cmd_summary():
    a = json.loads(sys.argv[2])
    out, tag, attempt = a["out"], a["tag"], a["attempt"]
    usage_raw, usage_from = None, None
    for i in range(attempt, 0, -1):
        f = os.path.join(out, "%s.a%d.usage-raw.json" % (tag, i))
        if os.path.exists(f):
            try: usage_raw = json.load(open(f)); usage_from = f; break
            except Exception: pass
    by_model, tot, nano = {}, dict(input=0, cached=0, output=0, reasoning=0), 0
    if usage_raw:
        nano = int(usage_raw.get("totalNanoAiu") or 0)
        for name, mv in (usage_raw.get("modelMetrics") or {}).items():
            u = mv.get("usage") or {}
            m = dict(input=int(u.get("inputTokens") or 0), cached=int(u.get("cacheReadTokens") or 0), output=int(u.get("outputTokens") or 0),
                     reasoning=int(u.get("reasoningTokens") or 0), ai_credits=round(int(mv.get("totalNanoAiu") or 0) / 1e9, 6))
            by_model[name] = m
            for k in tot: tot[k] += m[k]
    credits = round(nano / 1e9, 6); usd = round(credits * 0.01, 6)
    warn = None
    if not usage_raw: warn = "no usage file was written (run killed or failed early); cost unknown"
    elif a["final"] != "OK" and usage_from != os.path.join(out, "%s.a%d.usage-raw.json" % (tag, attempt)):
        warn = "usage taken from an earlier attempt; the last attempt wrote none, so cost may be understated"
    models, tiers, resp = [], [], ""
    for i in range(1, attempt + 1):
        e = read_run(os.path.join(out, "%s.a%d.jsonl" % (tag, i)))
        models += e["models"]; tiers += e["tiers"]
        if e["resp"]: resp = e["resp"]
    uniq = lambda xs: [x for n, x in enumerate(xs) if x and x not in xs[:n]]
    models, tiers = uniq(models), uniq(tiers)
    wd = a["workdir"]
    def git(*args):
        try: return subprocess.run(["git", "-C", wd] + list(args), capture_output=True, text=True, timeout=30).stdout.strip()
        except Exception: return ""
    commit = None
    cands = re.findall(r"(?i)(?:sha|commit)[^0-9a-f\n]{0,40}\b([0-9a-f]{7,40})\b", resp)[::-1] + re.findall(r"\b[0-9a-f]{7,40}\b", resp)
    for c in cands:
        full = git("rev-parse", "--verify", "-q", c + "^{commit}")
        if full: commit = full; break
    head1 = git("rev-parse", "HEAD")
    if not commit and head1 and head1 != a["head0"]: commit = head1
    discount = ("Fusion bills each routed model at its standard per-token rate (1 AI credit = $0.01). Paid Copilot plans get a 30% discount on Fusion model costs "
                "through 2026-12-31; ai_credits/usd here are the CLI-reported figures and the discount is not applied separately. Credits come out of the monthly plan allowance first.")
    tier = a["tier"] if a["model"] == "fusion" else None
    doc = dict(bot=a["bot"], job=a["job"], tag=tag, tool="copilot-cli", model=a["model"], fusion_tier=tier, status=a["final"], warning=warn,
               session_id=a["sid"], start=a["start"], end=a["end"], wall_s=a["wall"], attempts=attempt, attempt_log=a["att"], chosen_models=models,
               auto_tiers=tiers, by_model=by_model, tokens=tot, tokens_note="input includes cache reads (cached is the cached part)",
               ai_credits=credits, usd=usd, commit=commit, push_allowed=a["push"], sandbox=a["sandbox"], discount=discount, response_tail=resp[-600:])
    up = os.path.join(out, tag + ".usage.json")
    json.dump(doc, open(up, "w"), indent=2)
    summ = dict(bot=a["bot"], job=a["job"], tag=tag, model=a["model"], fusion_tier=tier, status=a["final"], warning=warn, session_id=a["sid"], start=a["start"],
                end=a["end"], wall_s=a["wall"], attempts=attempt, chosen_models=models, tokens=tot, ai_credits=credits, usd=usd, commit=commit)
    print("RUNSUMMARY " + json.dumps(summ, separators=(",", ":")) + " usage_json=" + up)
    # optional webhook; the secret comes only from env / *_FILE and is never printed
    notified = None
    url = a["notify_url"]
    if url:
        import urllib.request, urllib.error
        secret = os.environ.get("COPILOT_NOTIFY_SECRET") or os.environ.get("AGY_NOTIFY_SECRET")
        if not secret:
            sf = os.environ.get("COPILOT_NOTIFY_SECRET_FILE") or os.environ.get("AGY_NOTIFY_SECRET_FILE")
            if sf:
                try: secret = open(sf).read().strip()
                except Exception: print("[copilot-run] notify: cannot read secret file")
        hdr = os.environ.get("COPILOT_NOTIFY_HEADER") or os.environ.get("AGY_NOTIFY_HEADER") or "X-Webhook-Secret"
        headers = {"Content-Type": "application/json"}
        if secret: headers[hdr] = secret
        body = json.dumps(dict(bot=a["bot"], job=a["job"], model=a["model"], fusion_tier=tier, status=a["final"], tokens=tot, ai_credits=credits, cost_usd=usd,
                               commit=commit, log_path=os.path.join(out, "%s.a%d.jsonl" % (tag, attempt)), usage_json=up, warning=warn)).encode()
        for i in range(3):
            try:
                r = urllib.request.urlopen(urllib.request.Request(url, data=body, headers=headers, method="POST"), timeout=20)
                notified = "ok %d" % r.status; break
            except urllib.error.HTTPError as e: notified = "http %d" % e.code
            except Exception as e: notified = "error " + type(e).__name__
            if i < 2: time.sleep(5 * 3 ** i)
        m = re.match(r"(https?://[^/]+)", url)
        print("[copilot-run] notify %s/... -> %s" % (m.group(1) if m else "?", notified))
    fin = time.strftime("%Y-%m-%dT%H:%M:%S%z")
    open(os.path.join(out, tag + ".done"), "w").write(json.dumps(dict(status=a["final"], finished=fin, usage_json=up, notified=notified)) + "\n")

{"run": cmd_run, "analyze": cmd_analyze, "summary": cmd_summary}[sys.argv[1]]()
PYEOF

jitter_sleep() { sleep $(( $1 + RANDOM % 10 )); }
ts() { date '+%Y-%m-%d %H:%M:%S %z'; }
SID=$( python3 -c 'import uuid;print(uuid.uuid4())' )
attempt=0; resumes=0; quota=0; ptres=0; FINAL=UNKNOWN; SEEN=0; ATT="[]"
START_EPOCH=$(date +%s); START_TS=$(ts)
while :; do
  attempt=$((attempt+1))
  LOG="$OUT/$TAG.a$attempt.jsonl"; ERR="$OUT/$TAG.a$attempt.err"; CLOG="$OUT/$TAG.a$attempt.cli.log"
  LOGDIR="$OUT/$TAG.a$attempt.logs"; mkdir -p "$LOGDIR"; RAW="$OUT/$TAG.a$attempt.usage-raw.json"
  ISRES=$SEEN
  args=(--no-auto-update)
  if [ "$ISRES" = 1 ]; then args+=(-p "$CONT" "--resume=$SID"); else args+=(-p "$PTEXT" "--session-id=$SID"); fi
  args+=(--model "$MODEL")
  [ "$MODEL" = fusion ] && args+=(--fusion-tier "$TIER")
  args+=(-C "$WD" --output-format json --no-color --no-ask-user --disable-builtin-mcps)
  [ "$NOSB" = 1 ] || args+=(--sandbox)
  args+=(--log-dir "$LOGDIR" --usage-output-file "$RAW" "--secret-env-vars=$SECRETVARS" "--available-tools=$AVAIL" --allow-tool=write)
  for s in $SHELLALLOW; do args+=("--allow-tool=shell($s:*)"); done
  for u in $URLALLOW; do args+=("--allow-url=$u"); done
  oldifs=$IFS; IFS='|'; for d in $DENY; do args+=("--deny-tool=$d"); done; IFS=$oldifs
  [ -n "$LONGDIR" ] && args+=(--add-dir "$LONGDIR")
  [ "$CAP" -gt 0 ] && args+=(--max-ai-credits "$CAP")
  echo "[copilot-run] $(ts) attempt=$attempt model=$MODEL tier=$TIER session=$SID mode=$([ "$ISRES" = 1 ] && echo resume || echo new) log=$LOG"
  python3 "$PY" run "$TMO" "$WD" "$LOG" "$ERR" -- "$CBIN" "${args[@]}"; rc=$?
  TIMEDOUT=0; [ "$rc" = 124 ] && [ "$TMO" != 0 ] && { TIMEDOUT=1; echo "[copilot-run] outer kill at print-timeout ${TMO}s"; }
  EXTRA="$OUT/$TAG.a$attempt.extra.tmp"; : > "$EXTRA"
  if [ -s "$ERR" ]; then tail -n 20 "$ERR" | tr '\n' ' ' > "$EXTRA"; cat "$ERR" >> "$LOG"; fi
  echo "EXIT $rc" >> "$LOG"
  # merge Copilot's own log files into TAG.aN.cli.log (script-created folder only)
  ls "$LOGDIR"/*.log >/dev/null 2>&1 && { cat "$LOGDIR"/*.log > "$CLOG" 2>/dev/null; tail -n 15 "$CLOG" | tr '\n' ' ' >> "$EXTRA"; }
  rm -rf "$LOGDIR"
  eval "$(python3 "$PY" analyze "$LOG" "$rc" "$TIMEDOUT" "$EXTRA")"
  rm -f "$EXTRA"
  if [ "$STARTED" = 1 ]; then SEEN=1; [ -n "$NSID" ] && SID=$NSID; fi
  echo "[copilot-run] $(ts) attempt=$attempt rc=$rc class=$CLS session=$SID"
  ATT=$(python3 -c 'import json,sys;a=json.loads(sys.argv[1]);a.append(dict(attempt=int(sys.argv[2]),log=sys.argv[3],rc=int(sys.argv[4]),**{"class":sys.argv[5],"resumed":sys.argv[6]=="1"}));print(json.dumps(a))' "$ATT" "$attempt" "$LOG" "$rc" "$CLS" "$ISRES")
  case "$CLS" in
    OK) FINAL=OK; break;;
    NETWORK) [ "$resumes" -ge "$MAXRES" ] && { FINAL=FAILED_NETWORK; break; }
             resumes=$((resumes+1)); s=$((10 * (1 << (resumes-1)))); echo "[copilot-run] network drop; retry $resumes/$MAXRES in ~${s}s"; jitter_sleep $s;;
    QUOTA) [ "$quota" -ge 4 ] && { FINAL=FAILED_QUOTA; break; }
           s=$((60 * (1 << quota))); quota=$((quota+1)); echo "[copilot-run] rate limit / quota; backoff ~${s}s then retry"; jitter_sleep $s;;
    PRINT_TIMEOUT) [ "$ptres" = 1 ] && { FINAL=FAILED_PRINT_TIMEOUT; break; }
                   ptres=1; echo "[copilot-run] print timeout; resuming once"; sleep 5;;
    *) FINAL="FAILED_$CLS"; break;;
  esac
done
END_EPOCH=$(date +%s); END_TS=$(ts)
SUMARG=$(python3 -c '
import json,sys
k=["out","tag","attempt","final","bot","job","model","tier","workdir","head0","sid","start","end","wall","push","sandbox","notify_url"]
v=sys.argv[1:]
d=dict(zip(k,v)); d["attempt"]=int(d["attempt"]); d["wall"]=int(d["wall"]); d["push"]=d["push"]=="1"; d["sandbox"]=d["sandbox"]=="0"
d["att"]=json.loads(sys.stdin.read()); print(json.dumps(d))' "$OUT" "$TAG" "$attempt" "$FINAL" "$BOT" "$JOB" "$MODEL" "$TIER" "$WD" "$HEAD0" "$SID" "$START_TS" "$END_TS" "$((END_EPOCH-START_EPOCH))" "$PUSH" "$NOSB" "$NURL" <<<"$ATT")
python3 "$PY" summary "$SUMARG"
if [ "$FINAL" = OK ]; then echo "EXIT 0"; exit 0; else echo "EXIT 1"; exit 1; fi
