#!/usr/bin/env bash
# SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# classify-finding.sh — Deterministic review-pr §6B.5 note disposition.
#                        Decides whether one deduped review finding is filed
#                        as a standalone `review-finding` issue (ISSUE) or
#                        handled as a non-blocking note (NOTE).
#
# Usage:
#   classify-finding.sh --severity <S> [--confidence <C>] [--agent <A>]
#                       [--lineage none|review-finding] [--text <T> | --text-file <F>]
#                       [--inpr-diff <F> --file <P> [--scope introduced|pre-existing|unknown]] [--contract-scope <F> --contract-open <F> [--pr-files <F>] [--merge-issue <N>]]
#                       [--fix-efficacy fails|regresses] [--fixes-issue <N>]
#                       [--prior-findings <F> [--title <T>] [--line-start <N> [--line-end <M>]] [--diff-map <F>]]
#                       [--unstructured]
#
#   --severity    CRITICAL | HIGH | MEDIUM | LOW (case-insensitive). Missing or
#                 unparseable → ISSUE (fail toward filing, never drop).
#   --unstructured The finding has no `FINDING:` marker (it was not read from a structured
#                 findings block). With an empty or unparseable severity it is `NOTE unstructured`,
#                 never ISSUE: a marker-less finding cannot block a PR. HIGH/CRITICAL/MEDIUM/LOW
#                 still classify normally. A real marker with a bad severity (no flag) stays
#                 `ISSUE unparseable-severity`.
#   --confidence  CONFIRMED | LIKELY | POSSIBLE (case-insensitive). Missing is
#                 treated as not-POSSIBLE.
#   --agent       The `**Agent**:` value of the finding (e.g. "Security", "Auth").
#   --lineage     `review-finding` when the PR's linked issue (MERGE_ISSUE) carries
#                 the `review-finding` label — i.e. this PR is itself a fix for a
#                 review finding. Default `none`.
#   --fix-efficacy fails|regresses  The finding says the PR's linked issue is not fixed (`fails`) or
#                 that the PR re-introduces its defect (`regresses`). A MEDIUM finding so marked is
#                 `ISSUE fix-efficacy-<value>` under any lineage and confidence (the cascade damper must
#                 not merge a known-broken fix). Without the flag the tag is read from `--text`
#                 (a line consisting only of `FIX_EFFICACY: fails|regresses` or `**Fix efficacy**: fails|regresses`;
#                 a mid-sentence mention never counts). Opt-in only: never keyword-based. Runs after the INPR_FIX and re-flag gates and
#                 before the contract-scope and lineage gates; LOW stays NOTE; HIGH/CRITICAL unchanged.
#   --fixes-issue <N>  The PR's linked issue; alias of `--merge-issue` (same variable).
#   --text/--text-file  Finding title + body + affected file paths, used for the
#                 content-based safety exemption.
#   --inpr-diff <F> --file <P>  In-PR fix gate (#3387, narrowed): F is a file listing the
#                 PR's changed paths, one per line; P is the finding's file path. When both
#                 are given, a MEDIUM CONFIRMED finding whose path is in the PR diff is
#                 classified INPR_FIX — fix it on the PR before merge instead of filing it.
#                 Callers pass these only for the first fix round of an auto-merge review.
#   --scope <S>   introduced | pre-existing | unknown: whether the finding's line sits in code the PR
#                 added or changed (computed from the diff by review-finalize.sh). With `introduced`,
#                 a MEDIUM LIKELY finding in the PR diff is also INPR_FIX (a defect in new code is fixed
#                 in the PR, not filed). Absent, `pre-existing` or `unknown` keeps the CONFIRMED-only
#                 behaviour. Any other value exits 2. Always recorded as `scope=` on the telemetry event.
#
#   --contract-scope <F> --contract-open <F> --file <P>  Contract-declared scope gate: F is the TSV
#                 from `check-contract-scope.sh list` (disposition<TAB>path<TAB>issue). A finding
#                 whose path equals, or sits under, a `deferred` or `accepted-risk` item becomes
#                 `NOTE contract-deferred #N` / `NOTE contract-accepted-risk`. `--contract-open`
#                 lists the deferred issue numbers confirmed open, one per line; a deferred item
#                 demotes only when its number is listed (closed, unreadable or absent: no demotion).
#                 The caller lists a number only after verifying it is an open issue (not a PR) whose
#                 body carries `FORGE:DEFERRED_FROM: #<merge issue>` and a checklist line for the exact path.
#                 `--merge-issue <N>` is the PR's linked issue: `deferred → #N` never demotes (that
#                 issue is always open during review, so it is no follow-up).
#                 Never demoted: CRITICAL/HIGH, `not-affected` items, safety-exempt findings
#                 (security/billing keywords or a dedicated domain agent) under either disposition, and
#                 findings whose path is in `--inpr-diff` or `--pr-files` (this PR touched it; the
#                 contract excluded the sibling path, not regressions the PR introduced in it).
#                 `--pr-files <F>` is the PR's changed paths, one per line, supplied for this guard
#                 alone (it never triggers INPR_FIX). The gate runs after the severity and in-PR gates. Without the flags output is unchanged.
#
#   --prior-findings <F> --file <P> [--title <T>] [--line-start <N> [--line-end <M>]] [--diff-map <F>]
#                 Cross-head / cross-PR re-flag gate: F is a TSV of findings already raised for an
#                 earlier head of this PR or by a bundle's member PRs, one per line, columns
#                 file<TAB>line-start<TAB>line-end<TAB>title<TAB>prior-disposition<TAB>issue#.
#                 prior-disposition is `filed` (its issue is still open), `filed-closed` (issue closed:
#                 the row is IGNORED so a regressed defect is classified normally), `note` (a recorded NOTE) or
#                 `unknown` (a reviewer-body row whose issue linkage failed: it is IGNORED for a MEDIUM
#                 CONFIRMED/LIKELY finding so it can never suppress one, and behaves like `note` otherwise).
#                 Line columns may be empty (NOTE-sourced rows carry no range). A finding re-flags a row
#                 when it is the same file AND ((line IoU >= 0.6 and >= 1 shared title token), or >= 3 shared title tokens). Output is
#                 `NOTE reflag-filed #N` (row has an issue number) or `NOTE reflag-note`; this gate never
#                 emits ISSUE. `--file` may carry `path:line`; explicit --line-start wins.
#                 `--diff-map <F>` (optional, best-effort) lists `git diff <old>..<new>` hunks as
#                 file<TAB>old-start<TAB>old-count<TAB>new-start<TAB>new-count; a prior range lying
#                 wholly after hunks is shifted by their net line delta before the IoU. A missing or
#                 unparseable map means the unshifted range is used. The gate runs after the severity
#                 parse (HIGH/CRITICAL and unparseable severity stay ISSUE) and before the in-PR gate.
#                 Without the flags output is unchanged.
#
# Output (stdout, one line): `ISSUE <reason>`, `NOTE <reason>` or `INPR_FIX <reason>`.
# Exit codes: 0 classified, 2 usage error.
#
# Rules (forge#3060, tightened after the 2026-10-08 cascade audit):
#   1. HIGH/CRITICAL, or unparseable severity → ISSUE.
#   2. Safety exemption is CONTENT-based: the text matches the security/billing
#      keyword set (a LOW finding additionally needs CONFIRMED confidence), or the
#      finding came from a dedicated, signal-selected domain
#      agent (Auth, Billing, Concurrency, Database) and is MEDIUM. Origin from the always-on
#      "General Security & Quality" agent alone NO LONGER exempts a finding —
#      that agent runs on every PR, so origin-based exemption filed nearly every
#      LOW note it raised (50 of 60 would-be notes in the audited batch).
#   3. Review-finding lineage (a fix for a finding): only MEDIUM findings that are
#      CONFIRMED, or LIKELY and safety-exempt, become issues. LOW is always a
#      NOTE — a fix for a finding must not mint a new generation of findings.
#   4. Otherwise: LOW, or POSSIBLE below HIGH, is a NOTE unless safety-exempt.
#
# NOTEs are never discarded silently: review-pr §6B.5 fixes them in-PR, lists
# them in the PR body, or records a drop reason in the review summary.
#
# Portable: bash 3.2 (macOS /bin/bash), BSD and GNU grep/tr. No network.

set -u

SEVERITY=""
CONFIDENCE=""
AGENT=""
LINEAGE="none"
TEXT=""
INPR_DIFF=""
FINDING_FILE=""
CONTRACT_SCOPE=""
CONTRACT_OPEN=""
PR_FILES=""
MERGE_ISSUE=""
FIX_EFF=""
PRIOR_FINDINGS=""
TITLE=""
LINE_START=""
LINE_END=""
DIFF_MAP=""
UNSTRUCTURED=0
SCOPE=""

usage() {
  echo "ERROR: Usage: classify-finding.sh --severity <S> [--confidence <C>] [--agent <A>] [--lineage none|review-finding] [--text <T> | --text-file <F>] [--inpr-diff <F> --file <P> [--scope introduced|pre-existing|unknown]] [--contract-scope <F> --contract-open <F> [--pr-files <F>] [--merge-issue <N>]] [--fix-efficacy fails|regresses] [--fixes-issue <N>] [--prior-findings <F> [--title <T>] [--line-start <N> [--line-end <M>]] [--diff-map <F>]] [--unstructured]" >&2
  exit 2
}

while [ "$#" -gt 0 ]; do
  case "$1" in
    --severity)   [ "$#" -ge 2 ] || usage; SEVERITY="$2"; shift 2 ;;
    --confidence) [ "$#" -ge 2 ] || usage; CONFIDENCE="$2"; shift 2 ;;
    --agent)      [ "$#" -ge 2 ] || usage; AGENT="$2"; shift 2 ;;
    --lineage)    [ "$#" -ge 2 ] || usage; LINEAGE="$2"; shift 2 ;;
    --text)       [ "$#" -ge 2 ] || usage; TEXT="$2"; shift 2 ;;
    --inpr-diff)  [ "$#" -ge 2 ] || usage; INPR_DIFF="$2"; shift 2 ;;
    --file)       [ "$#" -ge 2 ] || usage; FINDING_FILE="$2"; shift 2 ;;
    --scope)      [ "$#" -ge 2 ] || usage; SCOPE=$(printf '%s' "$2" | tr '[:upper:]' '[:lower:]'); shift 2 ;;
    --contract-scope) [ "$#" -ge 2 ] || usage; CONTRACT_SCOPE="$2"; shift 2 ;;
    --contract-open)  [ "$#" -ge 2 ] || usage; CONTRACT_OPEN="$2"; shift 2 ;;
    --pr-files)       [ "$#" -ge 2 ] || usage; PR_FILES="$2"; shift 2 ;;
    --merge-issue)    [ "$#" -ge 2 ] || usage; MERGE_ISSUE="${2#\#}"; shift 2 ;;
    --fixes-issue)    [ "$#" -ge 2 ] || usage; MERGE_ISSUE="${2#\#}"; shift 2 ;;
    --fix-efficacy)   [ "$#" -ge 2 ] || usage; FIX_EFF=$(printf '%s' "$2" | tr '[:upper:]' '[:lower:]'); shift 2 ;;
    --prior-findings) [ "$#" -ge 2 ] || usage; PRIOR_FINDINGS="$2"; shift 2 ;;
    --title)          [ "$#" -ge 2 ] || usage; TITLE="$2"; shift 2 ;;
    --line-start)     [ "$#" -ge 2 ] || usage; LINE_START="$2"; shift 2 ;;
    --line-end)       [ "$#" -ge 2 ] || usage; LINE_END="$2"; shift 2 ;;
    --diff-map)       [ "$#" -ge 2 ] || usage; DIFF_MAP="$2"; shift 2 ;;
    --unstructured)   UNSTRUCTURED=1; shift ;;
    --text-file)
      [ "$#" -ge 2 ] || usage
      [ -r "$2" ] || { echo "ERROR: --text-file not readable: $2" >&2; exit 2; }
      TEXT=$(cat "$2"); shift 2 ;;
    *) usage ;;
  esac
done

case "$LINEAGE" in
  none|review-finding) ;;
  *) echo "ERROR: --lineage must be 'none' or 'review-finding' (got '$LINEAGE')" >&2; exit 2 ;;
esac

case "$FIX_EFF" in
  ''|fails|regresses) ;;
  *) echo "ERROR: --fix-efficacy must be 'fails' or 'regresses' (got '$FIX_EFF')" >&2; exit 2 ;;
esac

case "$SCOPE" in
  ''|introduced|pre-existing|unknown) ;;
  *) echo "ERROR: --scope must be 'introduced', 'pre-existing' or 'unknown'" >&2; exit 2 ;;
esac

if [ -n "$INPR_DIFF" ] && [ ! -r "$INPR_DIFF" ]; then
  echo "ERROR: --inpr-diff not readable: $INPR_DIFF" >&2; exit 2
fi

if [ -n "$CONTRACT_SCOPE" ] && [ ! -r "$CONTRACT_SCOPE" ]; then
  echo "ERROR: --contract-scope not readable: $CONTRACT_SCOPE" >&2; exit 2
fi
if [ -n "$CONTRACT_OPEN" ] && [ ! -r "$CONTRACT_OPEN" ]; then
  echo "ERROR: --contract-open not readable: $CONTRACT_OPEN" >&2; exit 2
fi

if [ -n "$PR_FILES" ] && [ ! -r "$PR_FILES" ]; then
  echo "ERROR: --pr-files not readable: $PR_FILES" >&2; exit 2
fi

if [ -n "$PRIOR_FINDINGS" ] && [ ! -r "$PRIOR_FINDINGS" ]; then
  echo "ERROR: --prior-findings not readable: $PRIOR_FINDINGS" >&2; exit 2
fi

upper() { printf '%s' "$1" | tr '[:lower:]' '[:upper:]' | tr -d '[:space:]'; }
SEV=$(upper "$SEVERITY")
CONF=$(upper "$CONFIDENCE")

# Telemetry (forge#3834): one best-effort record per finding, then the unchanged stdout line.
_TEL="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/telemetry.sh"; [ -f "$_TEL" ] && . "$_TEL" 2>/dev/null
type forge_emit >/dev/null 2>&1 || forge_emit() { :; }
disp() { # "<DISPOSITION> <reason>"
  forge_emit finding_disposition severity="$SEV" confidence="${CONF:-UNKNOWN}" agent="${AGENT:-none}" scope="${SCOPE:-unknown}" disposition="${1%% *}" reason="${1#* }"
  echo "$1"
}

# In-PR fix gate predicate (#3387, widened to HIGH/CRITICAL in #3592): CONFIRMED, linked to a
# --inpr-diff file list, and the finding's file is one of those files. Fails toward ISSUE.
# MEDIUM LIKELY also matches, only when --scope introduced (a defect in code this PR added).
inpr_match() {
  [ -n "$INPR_DIFF" ] && [ -n "$FINDING_FILE" ] || return 1
  if [ "$CONF" != "CONFIRMED" ]; then
    [ "$SEV" = "MEDIUM" ] && [ "$CONF" = "LIKELY" ] && [ "$SCOPE" = "introduced" ] || return 1
  fi
  _path="${FINDING_FILE#./}"; _path="${_path%%:*}"
  grep -Fxq -- "$_path" "$INPR_DIFF"
}

case "$SEV" in
  CRITICAL|HIGH)
    # HIGH/CRITICAL skip the re-flag and safety gates below, so the in-PR check runs here, before
    # the exit. Everything else stays ISSUE: a HIGH is never demoted to NOTE.
    if inpr_match; then
      disp "INPR_FIX $(printf '%s' "$SEV" | tr '[:upper:]' '[:lower:]')-confirmed-in-diff"; exit 0
    fi
    disp "ISSUE severity-$SEV"; exit 0 ;;
  MEDIUM|LOW) ;;
  *)
    if [ "$UNSTRUCTURED" = "1" ]; then disp "NOTE unstructured"; exit 0; fi
    disp "ISSUE unparseable-severity"; exit 0 ;;
esac

# Cross-head / cross-PR re-flag gate (#3641). Runs after the severity parse so HIGH/CRITICAL and
# unparseable severity have already exited as ISSUE. Emits only NOTE; fails toward the normal
# classification below on a missing file, no match, or an unusable diff map.
if [ -n "$PRIOR_FINDINGS" ] && [ -n "$FINDING_FILE" ]; then
  _rpath="${FINDING_FILE#./}"; _rline=""
  case "$_rpath" in *:[0-9]*) _rline="${_rpath#*:}"; _rline="${_rline%%[!0-9]*}" ;; esac
  _rpath="${_rpath%%:*}"
  _rls="${LINE_START:-$_rline}"; _rle="${LINE_END:-$_rls}"
  case "$_rls" in ''|*[!0-9]*) _rls=""; _rle="" ;; esac
  case "$_rle" in ''|*[!0-9]*) _rle="$_rls" ;; esac
  _dmap="$DIFF_MAP"; { [ -n "$_dmap" ] && [ -r "$_dmap" ]; } || _dmap=""
  _reflag=$(awk -F '\t' -v file="$_rpath" -v ls="$_rls" -v le="$_rle" -v title="$TITLE" -v dmap="$_dmap" -v sev="$SEV" -v conf="$CONF" '
    function toks(str, arr,    n, i, parts, t, c) {
      c = 0; str = tolower(str); gsub(/[^a-z0-9]+/, " ", str)
      n = split(str, parts, " ")
      for (i = 1; i <= n; i++) { t = parts[i]; if (length(t) >= 3 && !(t in arr)) { arr[t] = 1; c++ } }
      return c
    }
    function shift(f, s, e,    k, delta) {
      delta = 0
      for (k = 1; k <= nh; k++)
        if (hf[k] == f && (hc[k] == 0 ? ho[k] < s : ho[k] + hc[k] <= s)) delta += hc2[k] - hc[k]
      return delta
    }
    BEGIN {
      if (dmap != "") {
        while ((getline line < dmap) > 0) {
          if (split(line, p, "\t") >= 5 && p[2] ~ /^[0-9]+$/ && p[3] ~ /^[0-9]+$/ && p[4] ~ /^[0-9]+$/ && p[5] ~ /^[0-9]+$/) {
            nh++; hf[nh] = p[1]; ho[nh] = p[2] + 0; hc[nh] = p[3] + 0; hn[nh] = p[4] + 0; hc2[nh] = p[5] + 0
          }
        }
        close(dmap)
      }
      # Generic words count toward the token set but never as topical similarity (#3719).
      ns = split("the and with for from before after write read when that this into not are but can has have via use using does should may all any only also than then over under without within while where which what its it was were been being each both one two", sw, " ")
      for (i = 1; i <= ns; i++) stop[sw[i]] = 1
      ntitle = toks(title, ft)
    }
    {
      pf = $1; sub(/^\.\//, "", pf)
      if (pf != file) next
      if ($5 == "filed-closed") next
      if ($5 == "unknown" && sev == "MEDIUM" && (conf == "CONFIRMED" || conf == "LIKELY")) next
      hit = 0
      delete pt; toks($4, pt); shared = 0; cshared = 0
      for (t in pt) if (t in ft) { shared++; if (!(t in stop)) cshared++ }
      # Line overlap alone is not a match (an unrelated finding can land on the same line): it also
      # needs at least one shared non-stopword title token. Title-only matching needs >= 3 shared
      # tokens, of which >= 2 are non-stopword (generic words never count as topical similarity).
      if (cshared >= 1 && ls != "" && $2 ~ /^[0-9]+$/) {
        ps = $2 + 0; pe = ($3 ~ /^[0-9]+$/) ? $3 + 0 : ps
        if (pe < ps) pe = ps
        d = shift(pf, ps, pe); ps += d; pe += d
        lo = (ps > ls) ? ps : ls; hi = (pe < le) ? pe : le
        inter = hi - lo + 1; if (inter < 0) inter = 0
        uni = (pe - ps + 1) + (le - ls + 1) - inter
        if (uni > 0 && inter / uni >= 0.6) hit = 1
      }
      if (!hit && ntitle >= 3 && shared >= 3 && cshared >= 2) hit = 1
      if (!hit) next
      if ($5 == "filed" && $6 ~ /^#?[0-9]+$/) { n = $6; sub(/^#/, "", n); print "NOTE reflag-filed #" n; found = 1; exit }
      if (!note) note = "NOTE reflag-note"
    }
    END { if (!found && note) print note }
  ' "$PRIOR_FINDINGS" 2>/dev/null) || _reflag=""
  if [ -n "$_reflag" ]; then disp "$_reflag"; exit 0; fi
fi

# In-PR fix gate (#3387, narrowed). MEDIUM CONFIRMED is an ISSUE under every rule below
# (lineage included), so checking here changes only where it is handled, never whether.
# HIGH/CRITICAL were handled in the severity case above.
if [ "$SEV" = "MEDIUM" ] && inpr_match; then
  if [ "$CONF" = "CONFIRMED" ]; then disp "INPR_FIX medium-confirmed-in-diff"; else disp "INPR_FIX medium-likely-introduced-in-diff"; fi
  exit 0
fi

# Fix-efficacy exemption: a MEDIUM finding saying the PR's linked issue is not fixed, or that the PR
# re-introduces its defect, is never damped (any lineage, any confidence, no contract demotion).
# Opt-in on an explicit flag or a line-anchored tag only; never keyword-based (a bare "regression test for #N" must not match).
if [ "$SEV" = "MEDIUM" ]; then
  if [ -z "$FIX_EFF" ]; then
    FIX_EFF=$(printf '%s' "$TEXT" | tr '[:upper:]' '[:lower:]' \
      | grep -Eo '^[[:space:]]*(fix_efficacy:|\*\*fix efficacy\*\*:)[[:space:]]*(fails|regresses)[[:space:]]*$' | head -n 1 \
      | grep -Eo '(fails|regresses)$') || FIX_EFF=""
  fi
  if [ -n "$FIX_EFF" ]; then disp "ISSUE fix-efficacy-$FIX_EFF"; exit 0; fi
fi

# Safety exemption. Keywords match whole words, where `_`, `-`, `/` and other
# punctuation separate words (so `auth_service` matches, `author` does not).
SAFETY=""
KW='security|auth|authz|authn|billing|payment|stripe|charge|invoice|injection|xss|csrf|ssrf|idor|secret|secrets|credential|credentials|permission|permissions|sql|token|password|redact'
if printf '%s' "$TEXT" | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9\n' ' ' | grep -Eqw "($KW)"; then
  # A LOW finding needs the keyword AND CONFIRMED; MEDIUM keeps the keyword exemption at any confidence.
  if [ "$SEV" != "LOW" ] || [ "$CONF" = "CONFIRMED" ]; then SAFETY="keyword"; fi
fi
# A dedicated domain agent rescues a MEDIUM finding only: a LOW finding stays a NOTE
# whichever reviewer raised it, even when CONFIRMED.
AGENT_LC=$(printf '%s' "$AGENT" | tr '[:upper:]' '[:lower:]')
case "$AGENT_LC" in
  auth*|billing*|concurrency*|database*)
    if [ "$SEV" = "MEDIUM" ]; then SAFETY="${SAFETY:-domain-agent}"; fi ;;
esac

# Contract-declared scope gate (#3447). Fails toward filing: any missing input, closed or unlisted
# deferred issue, a deferral to the PR's own issue, an in-PR path, or a safety-exempt finding keeps
# the classification below.
if [ -n "$CONTRACT_SCOPE" ] && [ -n "$FINDING_FILE" ]; then
  _fpath="${FINDING_FILE#./}"; _fpath="${_fpath%%:*}"
  _inpr=""
  if [ -n "$INPR_DIFF" ] && grep -Fxq -- "$_fpath" "$INPR_DIFF"; then _inpr=1; fi
  if [ -n "$PR_FILES" ] && grep -Fxq -- "$_fpath" "$PR_FILES"; then _inpr=1; fi
  if [ -z "$_inpr" ]; then
    while IFS="$(printf '\t')" read -r _disp _ipath _inum; do
      [ -n "$_ipath" ] || continue
      _ipath="${_ipath#./}"; _ipath="${_ipath%/}"
      [ "$_fpath" = "$_ipath" ] || case "$_fpath" in "$_ipath"/*) ;; *) continue ;; esac
      case "$_disp" in
        deferred)
          if [ -z "$SAFETY" ] && [ -n "$_inum" ] && [ "$_inum" != "$MERGE_ISSUE" ] \
             && [ -n "$CONTRACT_OPEN" ] && grep -Fxq -- "$_inum" "$CONTRACT_OPEN"; then
            disp "NOTE contract-deferred #$_inum"; exit 0
          fi ;;
        accepted-risk)
          if [ -z "$SAFETY" ]; then disp "NOTE contract-accepted-risk"; exit 0; fi ;;
      esac
    done < "$CONTRACT_SCOPE"
  fi
fi

if [ "$LINEAGE" = "review-finding" ]; then
  if [ "$SEV" = "MEDIUM" ] && { [ "$CONF" = "CONFIRMED" ] || { [ -n "$SAFETY" ] && [ "$CONF" = "LIKELY" ]; }; }; then
    disp "ISSUE lineage-medium-${CONF:-UNKNOWN}"
  else
    disp "NOTE lineage-${SEV}-${CONF:-UNKNOWN}"
  fi
  exit 0
fi

if [ "$SEV" = "LOW" ] || [ "$CONF" = "POSSIBLE" ]; then
  if [ -n "$SAFETY" ]; then
    disp "ISSUE safety-exemption-$SAFETY"
  else
    disp "NOTE ${SEV}-${CONF:-UNKNOWN}"
  fi
  exit 0
fi

disp "ISSUE ${SEV}-${CONF:-UNKNOWN}"
exit 0
