Skip to main content

Lab 30.3: Enforcing Release Gates with CLI Extensions & Promoting to GitOps CI/CD

Goal​

In Module 30.2, you discovered that agents-cli eval run exits with code 0 whenever grading finishesβ€”even if an agent's quality rubric score plummets. In this hands-on challenge, you will harden support-ops-agent (gemini-3.8-flash) so an unverified or low-scoring build can never be deployed:

  1. Build an automated evaluation gate script (scripts/verify_eval_gate.py) that inspects the newest artifacts/grade_results/results_*.json scorecard, blocks below-bar builds (exit code 1), and delegates passing builds to agents-cli deploy.
  2. Author a project-scoped agents-cli-extension.yaml (schema: agents-cli-extension/v1alpha1) registering agents-cli check-gate (commands.add) and wrapping agents-cli deploy (commands.override) with loop-free AGENTS_CLI_DISABLE_OVERRIDES=1 delegation.
  3. Prove empirically that a failing scorecard (2.0) blocks agents-cli deploy --dry-run while a passing scorecard (4.8) delegates cleanly to the built-in Cloud Run dry-run plan without infinite recursion.
  4. Promote your support-ops-agent prototype in place via agents-cli scaffold enhance with Cloud Run Terraform, Workload Identity Federation (wif.tf), GitHub Actions Staging β†’ Production workflows, and Locust load testsβ€”while keeping app/agent.py untouched.

Environment setup:

  • 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
  • Local machine: If you're continuing the course in sequence, cd into the adk-training project you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:
    uv init adk-training --python 3.10 && cd adk-training
    uv add "google-adk>=2.1.0" python-dotenv
  • DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11, uv, gcloud, and all core ADK dependencies are pre-installed in your container environment.

Prerequisites​

  • Python 3.10+, uv, and google-agents-cli (~= 1.10.0) installed from Module 30.1.
  • Your support-ops-agent directory from Modules 30.1–30.2. (Starting fresh in Module 30.3? Run agents-cli scaffold create support-ops-agent --agent adk --prototype --agent-guidance-filename GEMINI.md --skip-checks -y from your parent workspace folder firstβ€”remember never to mkdir beforehand!)

Step 1: Implement the Scorecard Gate (scripts/verify_eval_gate.py)​

Navigate into your support-ops-agent project root and create the scripts/ and artifacts/grade_results/ directories:

cd /path/to/your/adk-training/support-ops-agent
mkdir -p scripts artifacts/grade_results

Create scripts/verify_eval_gate.py using the starter skeleton below and complete the four # TODO blocks:

"""Evaluation release gate for support-ops-agent (Module 30.3).

Enforces minimum evaluation rubric thresholds on the newest results_*.json
artifact before allowing cloud deployment to proceed.
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Any

PROJECT_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_MIN_SCORE_5PT = 4.0
DEFAULT_MIN_SCORE_UNIT = 0.85
# Built-in GenAI Eval metrics graded on a 0.0-1.0 scale rather than 1.0-5.0:
UNIT_SCALE_METRICS = frozenset({"hallucination", "safety", "multi_turn_task_success"})


def find_latest_scorecard(results_dir: Path) -> Path | None:
"""Return the newest results_*.json scorecard in artifacts/grade_results/."""
# TODO 1: Locate all files matching `results_*.json` inside `results_dir`,
# sort them chronologically by `(path.stat().st_mtime, path.name)`, and
# return the newest `Path` (or `None` if no scorecard exists).
pass


def extract_metric_scores(payload: dict[str, Any]) -> list[tuple[str, float, float]]:
"""Extract (metric_name, actual_score, required_threshold) from a scorecard JSON."""
min_5pt = float(os.environ.get("MIN_EVAL_SCORE", str(DEFAULT_MIN_SCORE_5PT)))
min_unit = float(os.environ.get("MIN_UNIT_EVAL_SCORE", str(DEFAULT_MIN_SCORE_UNIT)))

# TODO 2: Read `payload.get("summary_metrics")` (return `[]` if missing or not a list).
# For each dict entry in `summary_metrics`:
# 1. Read `name` from `entry.get("metric_name") or entry.get("name") or "unknown_metric"`.
# 2. Read `raw` from `entry.get("mean_score")` (falling back to `entry.get("score")` if None).
# Skip entries where `raw is None`.
# 3. Choose `threshold = min_unit` if `entry.get("scale") == "0-1"` or `name in UNIT_SCALE_METRICS`,
# otherwise `min_5pt`.
# 4. Append `(name, float(raw), threshold)` and return the list.
return []


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
"--delegate-deploy",
action="store_true",
help="Delegate to built-in `agents-cli deploy` after passing the gate.",
)
parser.add_argument(
"--results-dir",
default="artifacts/grade_results",
help="Directory containing results_*.json evaluation scorecards.",
)
# `parse_known_args` captures `--delegate-deploy` while preserving all user flags
# (such as `--dry-run --project ...`) in `extra_args` for downstream delegation!
args, extra_args = parser.parse_known_args(argv)

raw_results_dir = Path(args.results_dir)
results_dir = (
raw_results_dir
if raw_results_dir.is_absolute()
else (PROJECT_ROOT / raw_results_dir)
).resolve()
if not results_dir.is_relative_to(PROJECT_ROOT):
print(
f"❌ RELEASE GATE BLOCKED: '--results-dir' must remain inside '{PROJECT_ROOT}'.",
file=sys.stderr,
)
return 1

latest = find_latest_scorecard(results_dir)
if latest is None:
print(
f"❌ RELEASE GATE BLOCKED: No evaluation scorecard (results_*.json) found in '{results_dir}'.\n"
" Run `agents-cli eval run` before attempting deployment.",
file=sys.stderr,
)
return 1

try:
payload = json.loads(latest.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
print(
f"❌ RELEASE GATE BLOCKED: Could not parse scorecard '{latest}': {exc}",
file=sys.stderr,
)
return 1

checks = extract_metric_scores(payload)
if not checks:
print(
f"❌ RELEASE GATE BLOCKED: Scorecard '{latest.name}' contains no summary_metrics.",
file=sys.stderr,
)
return 1

# TODO 3: Collect all `(name, score, threshold)` entries in `checks` where `score < threshold`.
# If any metric failed:
# - Print a clear `❌ RELEASE GATE BLOCKED` error banner and each failing metric to `sys.stderr`.
# - Return exit code `1`.
pass

print(f"βœ… RELEASE GATE PASSED ({latest.name}):")
for name, score, threshold in checks:
print(f" - {name}: {score:.2f} >= {threshold:.2f}")

# TODO 4: If `args.delegate_deploy` is True:
# - Print a status line showing `os.environ.get("AGENTS_CLI_DISABLE_OVERRIDES")`.
# - Invoke `subprocess.run(["agents-cli", "deploy", *extra_args], env={**os.environ, "AGENTS_CLI_DISABLE_OVERRIDES": "1"}, check=False)` (no shell!).
# - Return `completed.returncode`.
return 0


if __name__ == "__main__":
raise SystemExit(main())

Step 2: Author the Project Extension (agents-cli-extension.yaml)​

Create agents-cli-extension.yaml at the root of support-ops-agent/ (next to agents-cli-manifest.yaml). Remember that the agents-cli-extension/v1alpha1 validator uses strict schema validation (extra="forbid"), so the top-level version key must be schema: (not apiVersion:):

# yaml-language-server: $schema=https://raw.githubusercontent.com/google/agents-cli/main/schemas/agents-cli-extension-v1alpha1.schema.json
schema: agents-cli-extension/v1alpha1
name: enterprise-release-gate
description: Enforce evaluation scorecard thresholds before permitting cloud deployment.
requires:
agents_cli: ">=1.10,<2"
on_incompatible: error

commands:
add:
# TODO 1: Register a new `check-gate` command using a no-shell `run:` argv list:
# `["uv", "run", "python", "scripts/verify_eval_gate.py"]`
# and add a concise `description`.

override:
# TODO 2: Override the built-in `deploy` command using a no-shell `run:` argv list
# that passes `"--delegate-deploy"` to `scripts/verify_eval_gate.py`, plus a `description`.

Step 3: Verify Registration, Gate Blocking & Loop-Free Delegation​

  1. Confirm your extension is auto-discovered at Project scope:

    agents-cli extension list
    agents-cli info

    Verify that enterprise-release-gate appears at project scope contributing both check-gate (add) and deploy (override).

  2. Simulate a regressed evaluation scorecard (mean_score: 2.0) and verify deployment is blocked:

    cat << 'EOF' > artifacts/grade_results/results_20261201_010000.json
    {
    "summary_metrics": [
    {"metric_name": "final_response_quality", "mean_score": 2.0},
    {"metric_name": "multi_turn_task_success", "mean_score": 0.95}
    ]
    }
    EOF

    agents-cli check-gate || echo "Gate exited with code: $?"
    agents-cli deploy --dry-run --deployment-target cloud_run --project demo-support-ops --region us-central1 || echo "Deploy blocked with code: $?"

    Confirm that both commands print ❌ RELEASE GATE BLOCKED (final_response_quality: 2.00 < 4.00) and exit with code 1 before any gcloud deployment command is constructed!

  3. Write a passing scorecard (mean_score: 4.8) and verify loop-free delegation:

    sleep 1
    cat << 'EOF' > artifacts/grade_results/results_20261201_020000.json
    {
    "summary_metrics": [
    {"metric_name": "final_response_quality", "mean_score": 4.8},
    {"metric_name": "multi_turn_task_success", "mean_score": 0.95}
    ]
    }
    EOF

    agents-cli deploy --dry-run \
    --deployment-target cloud_run \
    --project demo-support-ops \
    --region us-central1

    Verify three things in the terminal output:

    • agents-cli logs running 'deploy' via extension 'enterprise-release-gate' (project scope).
    • Your gate reports βœ… RELEASE GATE PASSED (results_20261201_020000.json) and prints AGENTS_CLI_DISABLE_OVERRIDES=1.
    • The inner agents-cli deploy call skips extension overridesβ€”zero infinite recursionβ€”and prints Would run: gcloud run deploy support-ops-agent --project demo-support-ops --region us-central1 ...!

Step 4: Promote support-ops-agent In Place & Inspect GitOps CI/CD​

Now promote support-ops-agent from --prototype mode (deployment_target: none) to a full Cloud Run + GitHub Actions repository in place:

  1. Run agents-cli scaffold enhance from inside support-ops-agent/:

    agents-cli scaffold enhance . \
    --deployment-target cloud_run \
    --cicd-runner github_actions \
    --skip-checks \
    -y
  2. Verify code preservation: Check the CLI summary (Skipping (your code): .env, app/agent.py) and inspect app/agent.py and agents-cli-extension.yaml to confirm your gemini-3.8-flash agent logic and release-gate extension remained completely untouched!

  3. Inspect the generated Terraform roots, GitOps workflows & load test suite:

    ls -la deployment/terraform/single-project/
    ls -la deployment/terraform/cicd/
    ls -la .github/workflows/
    ls -la tests/load_test/

    Open and compare:

    • deployment/terraform/single-project/ vs deployment/terraform/cicd/wif.tf and deployment/terraform/cicd/service_accounts.tf (notice how cicd separates cicd_runner_sa from per-environment app_sa using keyless OIDC Workload Identity Federation).
    • .github/workflows/pr_checks.yaml (PR CI), .github/workflows/staging.yaml (auto-deploy to Staging on main + Locust load testing), and .github/workflows/deploy-to-prod.yaml (manual production environment approval gate).

If you get stuck, check lab-solution.md or unlock the Reference Solution Vault below.

Self-Reflection Questions​

  1. Why does agents-cli execute run: as a direct argv list (shell=False) instead of passing a command string to /bin/sh -c, and why should run: always start with an explicit program like uv or python rather than "scripts/verify_eval_gate.py"?
  2. What would happen if agents-cli did not inject AGENTS_CLI_DISABLE_OVERRIDES=1 into the child process when commands.override.deploy invokes agents-cli deploy?
  3. Why does deployment/terraform/cicd/ provision two distinct service account roles (cicd_runner_sa and per-environment app_sa) instead of running both CI/CD deployments and the live Cloud Run container under one shared service account?

πŸ” Reference Solution Vault​

πŸ§ͺ

30.3: CLI Extensions & GitOps CI/CD(Challenge Lab)

Part 6: AgentOps & Google Agents CLI β€’ Module 30.3