#!/usr/bin/env bash
# story: e42s04 e45s02 e45s14 e60s01
# Deterministic gate runner for golden suite — sourced by golden-suite-run.sh

if [ -n "${GOLDEN_GATES_LOADED:-}" ]; then return 0; fi
GOLDEN_GATES_LOADED=1

GOLDEN_GATES=(
  "compliance:npm run compliance:false"
  "g04-selftest:bash scripts/golden-g04-selftest.sh:true"
  "g06-migrate-version:bash tests/run-golden-migrate-version.sh:true"
  "security-migration:node tests/security/migration.cjs:false"
  "g07-negative-path:bash scripts/golden-g07-negative-path.sh:false"
  "g08-anti-vacuity:bash scripts/golden-g08-anti-vacuity.sh:false"
  "g09-yaml-roundtrip:bash scripts/golden-g09-yaml-roundtrip.sh:false"
  "g10-trace-anti-vacuity:bash scripts/golden-g10-trace-anti-vacuity.sh:false"
  "g11-gitignore-venv:bash scripts/golden-g11-gitignore-venv.sh:false"
  # Planning SoT consistency (BUG-2026-07-26-planning-sot-drift): live epic
  # shards, execution-status.yaml and release-plan.yaml must agree. Self-test
  # first so a vacuous gate is caught before its verdict is trusted.
  "g12-status-selftest:bash scripts/golden-g12-status-consistency.sh --self-test:false"
  "g12-status-consistency:bash scripts/golden-g12-status-consistency.sh:false"
  # audit-compliance-runner.sh silently dropped a Background: step and a
  # feature file's last line when it had no trailing newline — a step exists,
  # is correct, and never runs is exactly this session's recurring defect
  # class. Fixture-based regression guard for both, plus a check that a fix
  # to "make steps execute" doesn't also make a genuinely failing step report
  # as PASS.
  "g15-compliance-runner-selftest:bash scripts/golden-g15-compliance-runner-selftest.sh --self-test:false"
  "g15-compliance-runner:bash scripts/golden-g15-compliance-runner-selftest.sh:false"
  # Writing a script must be enough to make it run: G-13 fails if any
  # scripts/*.sh is absent, unreferenced, and untagged bp-manual-utility.
  # Broadened from scripts/test-*.sh only after a catalog-wide review found 9
  # more orphans among non-test scripts; renamed to match (golden-g13-test-
  # orphans.sh -> golden-g13-script-orphans.sh).
  "g13-script-orphans-selftest:bash scripts/golden-g13-script-orphans.sh --self-test:false"
  "g13-script-orphans:bash scripts/golden-g13-script-orphans.sh:false"
  # An adapter that defines render_skill() must be dispatched by targets.yaml,
  # or sync renders nothing for it while its install still claims success.
  # docs/WORKFLOWS.md is generated from specs/workflows/*.yaml; a diagram nothing
  # regenerates is a diagram that lies (see specs/archive/assets/README.md).
  "workflow-diagrams-fresh:bash scripts/generate-workflow-diagrams.sh --check:false"
  # REFERENCE.md nav tables are line-number indexes; hand-maintained they drift
  # the moment a section grows (all 10 were stale when this gate was added).
  "reference-nav-fresh:bash scripts/generate-reference-nav.sh --check:false"
  "g14-adapter-dispatch-selftest:bash scripts/golden-g14-adapter-dispatch.sh --self-test:false"
  "g14-adapter-dispatch:bash scripts/golden-g14-adapter-dispatch.sh:false"
  # check-spec-version-gap.sh is a fully-formed SoT-drift detector for
  # consuming projects but had no gate of its own (G-13 orphan). Self-checking
  # bigpowers' own repo against its own package.json is the natural gate.
  "g16-spec-version-gap-selftest:bash scripts/golden-g16-spec-version-gap.sh --self-test:false"
  "g16-spec-version-gap:bash scripts/golden-g16-spec-version-gap.sh:false"
  "target-contracts:bash scripts/test-target-contracts.sh:false"
  # Registry-driven replacements for the 25 hand-written per-target scripts.
  "install-hub:bash scripts/test-install-hub.sh:false"
  # Whether the package *builds* was gated; whether its tree is *safe* was not.
  # `npm audit --omit=dev` was 10 advisories (1 critical) with nothing watching.
  "prod-dependency-audit:bash scripts/test-prod-dependency-audit.sh:false"
  # `bigpowers update` runs `npm install -g @latest` inside a live process; a
  # version captured by require() at startup then reports the release that was
  # just replaced (BUG-2026-11-03-cli-update-stale-version).
  "bigpowers-cli-version:bash scripts/test-bigpowers-cli-version.sh:false"
  # The CLI must be usable without a TTY (BUG-2026-11-03-cli-nontty-silent-noop):
  # with stdin at EOF the installer used to draw its first menu, install nothing
  # and exit 0.
  "bigpowers-cli:bash scripts/test-bigpowers-cli.sh:false"
  "adapter-render:bash scripts/test-adapter-render.sh:false"
  "adapters:bash scripts/test-adapters.sh:false"
  # Previously orphaned: present in scripts/ but reachable from no gate.
  "resolve-repo-root:bash scripts/test-resolve-repo-root.sh:false"
  "tombstone-mechanism:bash scripts/test-tombstone-mechanism.sh:false"
  "trace-strict:bash scripts/test-trace-strict.sh:false"
  # Trace links only files git would track — never other worktrees or reports.
  "trace-ignored-paths:bash scripts/test-trace-ignored-paths.sh:false"
  "trace-matrix-size:bash scripts/test-trace-matrix-size.sh:false"
  "setup-no-pyyaml:bash scripts/test-setup-no-pyyaml.sh:false"
  "install-distribute-only:bash scripts/test-install-distribute-only.sh:false"
  "completeness-critic-scope:bash scripts/test-completeness-critic-scope.sh:false"
  "epics-wiki-zero-stories:bash scripts/test-generate-epics-wiki-zero-stories.sh:false"
  "golden-g11-worktree-venv:bash scripts/test-golden-g11-worktree-venv.sh:false"
  "install-helpers:bash scripts/test-install-helpers.sh:false"
  # install.sh --uninstall matched only the literal link text against
  # $REPO_ROOT/, so a checkout uninstall of an npm install removed 0 of N.
  # The manifest + resolved-path matching fix is guarded here (#219).
  "install-manifest:bash tests/test-install-manifest.sh:false"
  # Five channels shipped the same catalog to four places pi scans, giving
  # 80 skill-name collisions per start (#208). verify-distribution names each
  # channel and fails when package + symlink both own pi.
  "verify-distribution:bash tests/test-verify-distribution.sh:false"
  "project-runtime:bash scripts/test-project-runtime.sh:false"
  "security-agents-import:node tests/security/agents-import.cjs:false"
  "omp-extension:bash scripts/validate-omp-extension.sh:false"
  "mcp-package:bash scripts/validate-mcp-package.sh:false"
  "security-git-context:node tests/security/git-context.cjs:false"
  "docs-base-path:bash scripts/validate-docs-base-path.sh:false"
  "security-dashboard-bind:node tests/security/dashboard-bind.cjs:false"
  "import-boundaries:bash scripts/check-import-boundaries.sh:false"
  "security-dashboard-render:node tests/security/dashboard-render.cjs:false"
  "skill-catalog:bash scripts/validate-skill-catalog.sh:false"
  # The validator stands in for the host parser, so it must reject exactly what
  # pi rejects: an HTML comment inside the frontmatter block (#173) and a
  # duplicate top-level key (#207). PyYAML accepts both, which is how 10 skills
  # shipped broken while `npm run compliance` stayed green.
  "skill-frontmatter-strict:bash tests/test-skill-frontmatter-strict.sh:false"
  # A rendered payload that ships only SKILL.md is a broken skill: 38 of 80
  # reference sibling files. The pi package (.pi/skills) and Antigravity
  # (.bigpowers/rendered/antigravity/skills) channels must carry the same
  # bundled files as the source.
  "render-assets:bash tests/test-render-assets.sh:false"
  # A host render target must not live at a path another host auto-discovers:
  # .agents/skills is a discovery root pi scans, so the Antigravity render
  # moved to .bigpowers/rendered/antigravity/skills (#209).
  "render-targets-not-discoverable:bash tests/test-render-targets-not-discoverable.sh:false"
  # Guard-git judges git argv, not substrings; shell and TS must agree (#184).
  "guard-git-normalize:bash scripts/test-guard-git-normalize.sh:false"
  # Guard reads branch from session cwd, not hook process cwd.
  "guard-session-cwd:bash scripts/test-guard-session-cwd.sh:false"
  "specs-parse:bash scripts/validate-specs-yaml.sh:false"
  # CI's sync job validates OKF bundles in six specs/ dirs; the local gate set did
  # not, so a green Preflight coexisted with a red CI sync job (e83s03, source
  # "mixed" in receipts.json). Keep both lists identical.
  "okf-bundles:bash tests/test-okf-bundles.sh:false"
  # P1: hooks and land-branch.sh block AI attribution, but neither runs when a PR
  # is merged with `gh pr merge`, so the rule was enforced only on the solo-local
  # path. This gate covers the commits a change introduces.
  "no-ai-coauthors:bash tests/test-no-ai-coauthors.sh:false"
  # The runner itself: failing output is shown, skips are named and reasoned.
  "golden-gate-runner:bash scripts/test-golden-gate-runner.sh:false"
  # Pipefail SIGPIPE races: fix shapes hold, git output never feeds grep -q/head.
  "pipefail-pipe-race:bash scripts/test-pipefail-pipe-race.sh:false"
  # Atomic state writes: no reader ever sees a truncated YAML/JSON file (#181).
  "atomic-writes:bash scripts/test-atomic-writes.sh:false"
  # One pipeline, release needs: every gate, pinned runner and actions.
  "ci-pipeline-contract-selftest:bash scripts/test-ci-pipeline-contract.sh --self-test:false"
  "ci-pipeline-contract:bash scripts/test-ci-pipeline-contract.sh:false"
  # Release audit gate must fail-closed on missing or stale audited_range
  # (BUG-2026-11-07-assert-epic-gate-fail-open).
  "assert-epic-gate:bash tests/test-assert-epic-gate.sh:false"
  # Tier 2 of the verify arc (#106): executes the verify: of every story marked
  # done. Tier 1 (SKILL.md) is run-skill-verify.sh in test-build-release.yml.
  "story-verify-selftest:bash scripts/run-story-verify.sh --self-test:false"
  "story-verify:bash scripts/run-story-verify.sh:false"
)

GOLDEN_GREEN='\033[0;32m'
GOLDEN_RED='\033[0;31m'
GOLDEN_YELLOW='\033[0;33m'
GOLDEN_NC='\033[0m'

golden_agent_dry_run() {
  local yaml_count=0 yaml_ok=0 yaml_fail=0 yaml_file story_id

  echo "Agent Golden Stories — DRY RUN"
  echo "Golden YAML directory: $GOLDEN_DIR"

  if [[ ! -d "$GOLDEN_DIR" ]]; then
    echo -e "${GOLDEN_YELLOW}WARN: $GOLDEN_DIR not found${GOLDEN_NC}"
    return 0
  fi

  for yaml_file in "$GOLDEN_DIR"/g-*.yaml; do
    [[ -f "$yaml_file" ]] || continue
    (( yaml_count += 1 ))
    story_id=$(basename "$yaml_file" .yaml)

    if $PYTHON -c "import yaml; yaml.safe_load(open('$yaml_file'))" 2>/dev/null; then
      local grader_type pass_k
      grader_type=$($PYTHON -c "import yaml; d=yaml.safe_load(open('$yaml_file')); print(d.get('grader',{}).get('type',''))" 2>/dev/null)
      pass_k=$($PYTHON -c "import yaml; d=yaml.safe_load(open('$yaml_file')); pk=d.get('pass_at_k',{}); print(f\"{pk.get('k',0)}-of-{pk.get('threshold',0)}\")" 2>/dev/null)
      echo -e "  ${GOLDEN_GREEN}OK${GOLDEN_NC}   $story_id — grader=$grader_type, pass@k=$pass_k"
      (( yaml_ok += 1 ))
    else
      echo -e "  ${GOLDEN_RED}FAIL${GOLDEN_NC} $story_id — YAML parse error"
      (( yaml_fail += 1 ))
    fi
  done

  echo ""
  echo "Agent YAML validation: $yaml_ok/$yaml_count parseable"
  if [[ "$yaml_fail" -gt 0 ]]; then
    echo -e "${GOLDEN_RED}$yaml_fail YAML(s) failed to parse${GOLDEN_NC}"
    return 1
  fi
  return 0
}

# GOLDEN_SKIP_GATES (comma list) skips gates another CI job already runs —
# test-build-release.yml skips story-verify because its story-verify job runs the
# same command. Local Preflight leaves it unset, so every gate runs there. A
# name that matches no gate is a FAIL: a typo must not look like a skip.
golden_is_skipped() { # $1 = gate name
  case ",${GOLDEN_SKIP_GATES:-}," in *",$1,"*) return 0 ;; esac
  return 1
}

golden_check_skip_names() {
  local skip gate known
  for skip in $(printf '%s' "${GOLDEN_SKIP_GATES:-}" | tr ',' ' '); do
    [[ -z "$skip" ]] && continue
    known=false
    for gate in "${GOLDEN_GATES[@]}"; do
      [[ "${gate%%:*}" == "$skip" ]] && known=true
    done
    $known && continue
    echo -e "[$skip] ${GOLDEN_RED}FAIL${GOLDEN_NC} (GOLDEN_SKIP_GATES names no such gate)"
    GATE_RESULTS+=("  - name: $skip" "    exit_code: 2" "    duration_seconds: 0" "    status: fail" "    error: unknown gate in GOLDEN_SKIP_GATES")
    (( FAIL_COUNT += 1 ))
  done
}

golden_run_deterministic_gates() {
  local gate name cmd is_optional main_cmd script_path gate_out
  PASS_COUNT=0 FAIL_COUNT=0 SKIP_COUNT=0
  GATE_RESULTS=()
  golden_check_skip_names

  for gate in "${GOLDEN_GATES[@]}"; do
    IFS=':' read -r name cmd is_optional <<< "$gate"
    echo -n "[$name] "

    if golden_is_skipped "$name"; then
      local reason="${GOLDEN_SKIP_REASON:-listed in GOLDEN_SKIP_GATES}"
      echo -e "${GOLDEN_YELLOW}SKIP${GOLDEN_NC} ($reason)"
      GATE_RESULTS+=("  - name: $name" "    exit_code: skipped" "    duration_seconds: 0" "    status: skipped" "    note: $reason")
      (( SKIP_COUNT += 1 ))
      continue
    fi

    main_cmd=$(echo "$cmd" | awk '{print $1}')
    if [[ "$main_cmd" == "bash" ]]; then
      script_path=$(echo "$cmd" | awk '{print $2}')
      if [[ ! -f "$script_path" ]]; then
        if [[ "$is_optional" == "true" ]]; then
          echo -e "${GOLDEN_YELLOW}SKIP${GOLDEN_NC} (script not yet implemented)"
          GATE_RESULTS+=("  - name: $name" "    exit_code: skipped" "    duration_seconds: 0" "    status: skipped" "    note: script not found: $script_path")
          (( SKIP_COUNT += 1 ))
          continue
        fi
        echo -e "${GOLDEN_RED}FAIL${GOLDEN_NC} (script not found: $script_path)"
        GATE_RESULTS+=("  - name: $name" "    exit_code: 127" "    duration_seconds: 0" "    status: fail" "    error: script not found: $script_path")
        (( FAIL_COUNT += 1 ))
        continue
      fi
    fi

    local START_TIME END_TIME DURATION_MS DURATION_SEC GATE_EXIT
    START_TIME=$(date +%s%N)
    gate_out=$(eval "$cmd" 2>&1) && GATE_EXIT=$? || GATE_EXIT=$?
    END_TIME=$(date +%s%N)
    DURATION_MS=$(( (END_TIME - START_TIME) / 1000000 ))
    DURATION_SEC=$(echo "scale=2; $DURATION_MS / 1000" | bc 2>/dev/null || echo "0")

    if [[ "$GATE_EXIT" -eq 0 ]]; then
      echo -e "${GOLDEN_GREEN}PASS${GOLDEN_NC} (${DURATION_SEC}s)"
      GATE_RESULTS+=("  - name: $name" "    exit_code: 0" "    duration_seconds: $DURATION_SEC" "    status: pass")
      (( PASS_COUNT += 1 ))
    else
      echo -e "${GOLDEN_RED}FAIL${GOLDEN_NC} (${DURATION_SEC}s, exit $GATE_EXIT)"
      # Without the tail, CI shows FAIL with no reason (#158: compliance).
      printf '%s\n' "$gate_out" | tail -20 | sed 's/^/    | /'
      GATE_RESULTS+=("  - name: $name" "    exit_code: $GATE_EXIT" "    duration_seconds: $DURATION_SEC" "    status: fail")
      (( FAIL_COUNT += 1 ))
    fi
  done
}

