# yad-managed-include: yad-checks
# SDLC check gates (Phase 3 build plan §C), as an INCLUDABLE fragment.
# This file is pulled into a repo's existing .gitlab-ci.yml via:
#   include:
#     - local: '.gitlab/ci/yad-checks.yml'
# so wiring NEVER edits the foreign root pipeline beyond adding that one include line.
#
# Merge-safety: these jobs do NOT declare a `stage:` and use `needs: []`, so they run in the
# pipeline's default stage regardless of any `stages:` order the foreign root defines — a foreign
# `stages:` list can neither break them nor reorder them. Job names are yad-prefixed to avoid
# colliding with the host project's own job names.
#
# `image:`/`tags:` live on the .sdlc_mr_only anchor below — NOT a top-level `default:`. An included
# top-level `default:` merges into the HOST root pipeline; if the host already sets a top-level
# `image:`, GitLab rejects the whole config ("image is defined in top-level and 'default:' entry").
# Putting them on the anchor scopes them to the gate jobs (which all `extends: .sdlc_mr_only`) and
# never touches the host root. The same goes for the gate jobs' own variables (`YAD_NODE_VERSION`,
# `NX_BASE`, `NX_HEAD`): an included top-level `variables:` merges into the host's globals, where a
# generic name like NX_BASE can collide with one the host already computes for its own Nx jobs.
# `GIT_DEPTH` is on the anchor too (#434): a top-level value made every host job clone the full history,
# and a host's own top-level GIT_DEPTH replaced it, leaving the gates a shallow clone.

#
# Gate scripts (#426): every job runs the BASE branch's copy of checks/, never the PR's own, so a PR that
# changes a gate script is still judged by the script already merged. A script the base does not have yet
# (the PR that first installs the gates, or a `yad update` that adds one) runs from the PR, with a note.
# The base's script runs with THIS file's call: keep every call one the previous release's script accepts.
# This file itself still comes from the PR: protect checks/ and the CI files with a CODEOWNERS rule and
# a required Code Owner review (docs/branch-protection.md, "Who may change the gates").
# The step the header names: the first line of every gate job's script (`!reference`, GitLab 13.9+), not a
# before_script, so a `default: before_script` of the host pipeline still runs. Every yad fragment defines
# this same key and the file included last wins, so keep every fragment on the same yadflow release.
.yad_base_checks:
  script:
    - |
      YAD_BASE="$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"; YAD_CHECKS="$(mktemp -d)/checks"; export YAD_CHECKS
      (
        set -euo pipefail
        b="origin/${YAD_BASE}"; d="${YAD_CHECKS%/checks}"
        rm -rf "$d"; mkdir -p "$YAD_CHECKS"
        git rev-parse --verify --quiet "${b}^{commit}" > /dev/null || { echo "FAIL [base-checks]: ${b} is not in this checkout, so the gate scripts cannot be read from the base branch. Check the code out with its full history." >&2; exit 1; }
        t="$(git ls-tree "$b" checks)"
        case "$t" in
          "") on_base=0 ;;
          "040000 tree "*) git archive "$b" checks | tar -x -C "$d"; on_base=1 ;;
          *) echo "FAIL [base-checks]: checks on ${b} is not a folder, so the gate scripts cannot be read from it. Make checks/ a plain folder on the base branch." >&2; exit 1 ;;
        esac
        git ls-tree -z HEAD checks/ > "$d/.pr"
        n=0
        while IFS= read -r -d '' e; do
          m="${e%% *}"; p="${e#*$'\t'}"; o="${e#* * }"; o="${o%%$'\t'*}"; s="${p//[[:cntrl:]]/?}"
          if [ -e "$d/$p" ] || [ -L "$d/$p" ]; then continue; fi
          case "$m" in
            100644 | 100755) git cat-file blob "$o" > "$d/$p"; if [ "$m" = 100755 ]; then chmod +x "$d/$p"; fi ;;
            *) printf 'note: %s in this PR is not a plain file, so it is not run (#426)\n' "$s"; continue ;;
          esac
          n=$((n + 1))
          if [ "$on_base" = 1 ]; then printf 'note: %s is not on %s yet, so the copy from this PR runs (#426)\n' "$s" "$YAD_BASE"; fi
        done < "$d/.pr"
        rm -f "$d/.pr"
        if [ "$n" = 1 ]; then w="1 file"; else w="$n files"; fi
        if [ "$on_base" = 0 ]; then printf 'note: %s has no checks/ folder yet, so the gate scripts from this PR run: %s (#426)\n' "$YAD_BASE" "$w"; fi
      )

.sdlc_mr_only:
  # A newer push to the same merge request may cancel this job's older run (#428). GitLab does it only when
  # the project's "Auto-cancel redundant pipelines" setting is on and no job in the older
  # pipeline that is not interruptible has started; the gates re-read the whole MR range, so nothing is missed.
  interruptible: true
  image: node:${YAD_NODE_VERSION}
  variables:
    # A project/group CI/CD variable overrides a YAML value, so YAD_NODE_VERSION can be changed in
    # project settings without editing the managed fragment (a current 22 or 24 line; Node 25+ has no Corepack).
    YAD_NODE_VERSION: "22"
    GIT_DEPTH: "0" # full history so the gates can diff against the target branch (on the yad jobs only, #434)
    NX_BASE: $CI_MERGE_REQUEST_DIFF_BASE_SHA
    NX_HEAD: $CI_COMMIT_SHA
  # Runner selection. These jobs need a docker/dind executor; on instances whose runners are all
  # tag-locked (run_untagged: false) an untagged image job never starts. Set the YAD_RUNNER_TAGS
  # CI/CD variable (Settings → CI/CD → Variables, e.g. `dind_runner`) to route them — it lives in
  # project settings, so it survives every `yad` sync. When unset, current GitLab (>=15) drops the
  # empty-expanded tag so the job runs untagged (gitlab.com shared runners); some older versions
  # instead strand it `pending` — if so, set the variable to a real tag. Single value only:
  # `tags: [$VAR]` is one tag equal to the whole variable, not a comma-split.
  tags: [$YAD_RUNNER_TAGS]
  # A stuck job stops here, not at the 1-hour project default (#424). build-test-lint sets its own.
  timeout: 10 minutes
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

yad-spec-link:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    - bash "$YAD_CHECKS/spec-link.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"

yad-contract-check:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    # E120: check the Product out where .sdlc/product-link.json says, when the YAD_PRODUCT_TOKEN CI/CD
    # variable is set (masked); without it the gate defers, with a WARNING unless the MR comes from a fork (#345).
    - bash "$YAD_CHECKS/product-checkout.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
    - bash "$YAD_CHECKS/contract-check.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"

# E65/E66 — the risk map (.sdlc/risk-map: a risk level per directory, no names). Warnings, and the
# approver count read from the base branch's map. It never fails the pipeline (the count is reported,
# not enforced), so the job needs no allow_failure.
yad-risk-map:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    - bash "$YAD_CHECKS/risk-map-check.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"

yad-build-test-lint:
  extends: .sdlc_mr_only
  timeout: 30 minutes # it runs the team's own build and tests
  needs: []
  variables:
    YAD_TEST_MAX_WORKERS: "2" # cap jest/vitest test workers in CI; ignored by other runners
  script:
    - !reference [.yad_base_checks, script]
    # The base branch lets a Unity project skip these two, and stops a change from skipping them by deleting package.json (#496).
    - bash "$YAD_CHECKS/install-deps.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
    - bash "$YAD_CHECKS/build-test-lint.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"

# Phase 6 — feature-thread gates (lineage / seal / hotfix-debt). Build on spec-link's story->epic
# resolution; degrade to a note when the product repo is not reachable from CI.
yad-lineage-check:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    # E120: check the Product out where .sdlc/product-link.json says, when the YAD_PRODUCT_TOKEN CI/CD
    # variable is set (masked); without it the gate defers, with a WARNING unless the MR comes from a fork (#345).
    - bash "$YAD_CHECKS/product-checkout.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
    - bash "$YAD_CHECKS/lineage-check.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"

yad-epic-open:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    # E120: check the Product out where .sdlc/product-link.json says, when the YAD_PRODUCT_TOKEN CI/CD
    # variable is set (masked); without it the gate defers, with a WARNING unless the MR comes from a fork (#345).
    - bash "$YAD_CHECKS/product-checkout.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
    - bash "$YAD_CHECKS/epic-open.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"

yad-reconcile-debt:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    # E120: check the Product out where .sdlc/product-link.json says, when the YAD_PRODUCT_TOKEN CI/CD
    # variable is set (masked); without it the gate defers, with a WARNING unless the MR comes from a fork (#345).
    - bash "$YAD_CHECKS/product-checkout.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
    - bash "$YAD_CHECKS/reconcile-debt-check.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"

# Pattern gates: commit subject + MR title + MR body all follow the convention (profile: code).
yad-commit-message:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    - bash "$YAD_CHECKS/commit-message.sh" --profile code "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"

yad-pr-title:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    - bash "$YAD_CHECKS/pr-title.sh" --profile code "$CI_MERGE_REQUEST_TITLE"

yad-pr-template:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    - body="$(mktemp)"; printf '%s' "$CI_MERGE_REQUEST_DESCRIPTION" > "$body"
    - bash "$YAD_CHECKS/pr-template.sh" --profile code "$body"

# No unverified commits: a platform-Verified signature on every commit (write access decides who authors).
# Needs a CI/CD variable GITLAB_TOKEN (or SDLC_API_TOKEN) with read_api scope — CI_JOB_TOKEN cannot
# read the commit-signature API. Without it the job FAILS closed with guidance.
yad-verified-commits:
  extends: .sdlc_mr_only
  needs: []
  script:
    - !reference [.yad_base_checks, script]
    - bash "$YAD_CHECKS/verified-commits.sh" "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"
