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:
- Build an automated evaluation gate script (
scripts/verify_eval_gate.py) that inspects the newestartifacts/grade_results/results_*.jsonscorecard, blocks below-bar builds (exit code 1), and delegates passing builds toagents-cli deploy. - Author a project-scoped
agents-cli-extension.yaml(schema: agents-cli-extension/v1alpha1) registeringagents-cli check-gate(commands.add) and wrappingagents-cli deploy(commands.override) with loop-freeAGENTS_CLI_DISABLE_OVERRIDES=1delegation. - Prove empirically that a failing scorecard (
2.0) blocksagents-cli deploy --dry-runwhile a passing scorecard (4.8) delegates cleanly to the built-in Cloud Run dry-run plan without infinite recursion. - Promote your
support-ops-agentprototype in place viaagents-cli scaffold enhancewith Cloud Run Terraform, Workload Identity Federation (wif.tf), GitHub Actions Staging β Production workflows, and Locust load testsβwhile keepingapp/agent.pyuntouched.
Environment setup:
- 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
- Local machine: If you're continuing the course in sequence,
cdinto theadk-trainingproject 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, andgoogle-agents-cli(~= 1.10.0) installed from Module 30.1. - Your
support-ops-agentdirectory from Modules 30.1β30.2. (Starting fresh in Module 30.3? Runagents-cli scaffold create support-ops-agent --agent adk --prototype --agent-guidance-filename GEMINI.md --skip-checks -yfrom your parent workspace folder firstβremember never tomkdirbeforehand!)
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β
-
Confirm your extension is auto-discovered at Project scope:
agents-cli extension list
agents-cli infoVerify that
enterprise-release-gateappears atprojectscope contributing bothcheck-gate (add)anddeploy (override). -
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 code1before anygclouddeployment command is constructed! -
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-central1Verify three things in the terminal output:
agents-clilogsrunning 'deploy' via extension 'enterprise-release-gate' (project scope).- Your gate reports
β RELEASE GATE PASSED (results_20261201_020000.json)and printsAGENTS_CLI_DISABLE_OVERRIDES=1. - The inner
agents-cli deploycall skips extension overridesβzero infinite recursionβand printsWould 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:
-
Run
agents-cli scaffold enhancefrom insidesupport-ops-agent/:agents-cli scaffold enhance . \
--deployment-target cloud_run \
--cicd-runner github_actions \
--skip-checks \
-y -
Verify code preservation: Check the CLI summary (
Skipping (your code): .env, app/agent.py) and inspectapp/agent.pyandagents-cli-extension.yamlto confirm yourgemini-3.8-flashagent logic and release-gate extension remained completely untouched! -
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/vsdeployment/terraform/cicd/wif.tfanddeployment/terraform/cicd/service_accounts.tf(notice howcicdseparatescicd_runner_safrom per-environmentapp_sausing keyless OIDC Workload Identity Federation)..github/workflows/pr_checks.yaml(PR CI),.github/workflows/staging.yaml(auto-deploy to Staging onmain+ Locust load testing), and.github/workflows/deploy-to-prod.yaml(manualproductionenvironment approval gate).
If you get stuck, check lab-solution.md or unlock the Reference Solution Vault below.
Self-Reflection Questionsβ
- Why does
agents-cliexecuterun:as a directargvlist (shell=False) instead of passing a command string to/bin/sh -c, and why shouldrun:always start with an explicit program likeuvorpythonrather than"scripts/verify_eval_gate.py"? - What would happen if
agents-clidid not injectAGENTS_CLI_DISABLE_OVERRIDES=1into the child process whencommands.override.deployinvokesagents-cli deploy? - Why does
deployment/terraform/cicd/provision two distinct service account roles (cicd_runner_saand per-environmentapp_sa) instead of running both CI/CD deployments and the live Cloud Run container under one shared service account?
π Reference Solution Vaultβ
Official Solution Vault β Module 30.3
Locked Challenge β Active Pedagogical Socratic Gate