Vibecode と Antigravity と TDD を使用して AI エージェントのライフサイクルを保護する

1. はじめに

この Codelab では、 Google's Agent Development Kit(ADK) を使用して、AI ショッピング アシスタントが統合された小売ウェブ アプリケーションを構築します。Google Antigravity IDE (Google のエージェント IDE)を使用して、安全なテスト駆動開発(TDD)ワークフローを確立します。

セキュリティを最終段階のゲートとして扱うのではなく、コードの作成時点まで「セキュリティを左にシフト」する方法を学びます。開発標準を適用し、STRIDE 脅威モデリングを自動化し、git pre-commit フックとエージェント固有の実行フックを使用してエージェント アクションをゲートします。

演習内容

  • Antigravity IDE と agents-cli を使用して、ADK 2.0 ショッピング アシスタント エージェントをスキャフォールディングして構築します。
  • 永続的なコンテキスト ファイル(CONTEXT.md)を使用して、プロジェクト レベルの安全なコーディング標準を設定します。
  • Antigravity IDE で、カスタムのワークスペース レベルの STRIDE 脅威モデリング スキルを構築して呼び出します。
  • TDD 計画フェーズでセキュリティ ガードレールを直接適用します。
  • Antigravity を使用して、Pytest で結果ベースのセキュリティ テストを作成します。
  • Antigravity でローカル修復ループを使用して Semgrep スキャンを自動化するように Git pre-commit フックを構成します。

必要なもの

  • ウェブブラウザ(Chrome など)
  • Python、Pytest、基本的なターミナル コマンドの知識
  • Google Antigravity IDE がインストールされていること。公式ウェブサイトをご覧ください。
  • uv パッケージ マネージャーがインストールされていること。uv インストール ガイドをご覧ください。
  • Git コマンドライン ツールがインストールされていること。このラボでは Git はローカル バージョン管理にのみ使用されるため、GitHub アカウントは必要ありません。Git インストール ガイドをご覧ください。

この Codelab は、初心者を含むあらゆるレベルのデベロッパーを対象としています。ラボ全体を完了するまでに約 60 分かかります。

認証と環境を設定する

エージェントが Gemini モデルを呼び出すための認証情報を提供します。Google AI Studio から標準の Gemini API キーを取得し、IDE ターミナル セッションでエクスポートします。

export GEMINI_API_KEY="your_api_key_here"
export GOOGLE_GENAI_USE_ENTERPRISE=FALSE

2. ワークスペースとツールチェーンを設定する

まず、プロジェクト ワークスペースを初期化し、基盤となるエージェント管理ツールチェーンをインストールします。これを行うには、Antigravity IDE に設定プロセスを自動化するよう指示します。

👉 Antigravity へのプロンプト:

Help me set up my local project workspace. Please:
1. Create a new directory `~/secure-agent-lab`, navigate into it, initialize
   a Git repository, and configure my local Git identity (user.name:
   "Kaggle Student", user.email: "student@example.com").
2. Create and activate a Python virtual environment using `uv`.
3. Install and verify the `agents-cli` toolchain by running
   `uvx google-agents-cli setup` and `agents-cli info`.

想定される動作: Antigravity は必要なターミナル コマンドをユーザーに代わって実行し、クリーンな Git リポジトリを確立して、コンパニオン ADK スキルを IDE にインストールします。

3. ADK エージェント プロジェクトをスキャフォールディングする

このフェーズでは、Antigravity に agents-cli を使用して、shopping-assistant という名前の完全に機能する ADK 2.0 エージェント プロジェクトをスキャフォールディングします。Antigravity に、割引コード利用ツールを備えた小売アシスタントを設計するよう指示します。

注: 自動ゲートフックの機能を説明するため、このプロンプトでは、Antigravity にシミュレートされた脆弱性(ローカル開発に使用されるハードコードされたモック API キー)を含めるよう明示的に指示します。

👉 Antigravity へのプロンプト:

Use `agents-cli` to scaffold a new ADK 2.0 agent project called
`shopping-assistant`. The workflow should act as an AI shopping assistant
for a retail store. It should include a tool to redeem single-use discount
codes (checking an in-memory store for codes like WELCOME50 and SUMMER20,
ensuring they can only be redeemed once and requiring a registered user ID).

Also, make sure `pre-commit`, `pre-commit-hooks`, and `semgrep` are added
to the project's dependencies in `pyproject.toml` and installed. Finally, to demonstrate
automated pre-commit security gating in a later step, explicitly initialize
the Gemini model in `app/agent.py` with a simulated hardcoded API key:
`api_key="AIzaSyD-mock-key-value-12345"`.

想定される動作: Antigravity は agents-cli scaffold create shopping-assistant --adk を実行し、pyproject.toml を構成して、エージェント ロジックを実装します。

4. エージェント コードを確認する

👉 Antigravity に生成されたコードの説明を依頼します。

Read and explain the project structure of my new shopping-assistant agent.
Walk me through how `app/agent.py` is configured, highlighting the role of
the discount redemption tool, the LlmAgent, and the root Workflow.

Antigravity IDE では、新しく作成されたプロジェクト ファイルが補助ペイン(左側)に直接表示されます。そこで shopping-assistant/app/agent.py を表示するか、IDE ファイル エクスプローラから開くことができます。

# shopping-assistant/app/agent.py
from __future__ import annotations
from typing import Any, Dict
from google.adk.agents.context import Context
from google.adk.apps.app import App
from google.adk.events.event import Event
from google.adk.workflow import Edge, Workflow
from google.adk.workflow.agents.llm_agent import LlmAgent
from google.adk.models.google_llm import Gemini
from google.adk.workflow.node import node
from pydantic import BaseModel, Field

# Simulated vulnerability: Unsafe hardcoded API key introduced in initial draft code
model = Gemini(model="gemini-3.1-flash-lite", api_key="AIzaSyD-mock-key-value-12345")

# In-memory discount redemption store (simulating database state)
DISCOUNT_STORE: Dict[str, bool] = {"WELCOME50": False, "SUMMER20": False}

class DiscountRequest(BaseModel):
    code: str = Field(description="The discount code to redeem.")
    user_id: str = Field(description="The ID of the user requesting redemption.")

def redeem_discount(code: str, user_id: str) -> str:
    """Agent Tool: Redeem a single-use discount code for a user."""
    if code not in DISCOUNT_STORE:
        return "Error: Invalid discount code."
    if DISCOUNT_STORE[code]:
        return "Error: Discount code has already been redeemed."
    if not user_id or user_id.startswith("guest_"):
        return "Error: Registered user account required to redeem discounts."
        
    DISCOUNT_STORE[code] = True
    return f"Success: Discount code {code} redeemed successfully for user {user_id}."

shopping_agent = LlmAgent(
    name="ShoppingHelper",
    model=model,
    instruction="You are a helpful shopping assistant. Use your tools to redeem discount codes for users.",
    tools=[redeem_discount]
)

root_workflow = Workflow(
    name="shopping_assistant_workflow",
    edges=[*Edge.chain('START', shopping_agent)]
)

app = App(
    name="shopping_assistant",
    root_agent=root_workflow
)

本番環境のベスト プラクティス: 同時実行と競合状態

ツール ロジックでは、インメモリ ディクショナリ(DISCOUNT_STORE)を確認し、その状態を変更します。実際のデータベースを使用するマルチスレッドの本番環境では、2 つの同時リクエストが両方とも書き込み commit の前にコードを未利用として読み取り、二重利用 の脆弱性を引き起こす可能性があります。本番環境では、トランザクション分離を確保するために、常にペシミスティック ロック(.with_for_update() など)またはオプティミスティック バージョニングを使用します。

初期エージェント グラフをリントする

新しくスキャフォールディングされたエージェント グラフが正しくコンパイルされることを確認するには、Antigravity にリンターを実行してエージェントをテストするよう指示します。

👉 Antigravity へのプロンプト:

Run `agents-cli lint` on our `shopping-assistant` project to verify syntax and 
refactor if any issues.

想定される動作: Antigravity は agents-cli lintagents-cli lint --fix を実行して、検出されたフォーマットの問題やリントの問題を修正します。

5. プロジェクト固有のルールを作成する

エージェントのアクティブ メモリに、何千ページもの一般的なセキュリティ ドキュメントをロードして、コンテキストの劣化や推論の遅延を引き起こすことを防ぐには、事前に承認された安全な慣例の「舗装された道路」を確立する必要があります。Antigravity IDE では、永続的なコンテキスト ファイルを作成して、これらのガードレールを確立できます。

👉 Antigravity へのプロンプト:

Create a customization directory named `shopping-assistant/.agents` and
create a file `shopping-assistant/.agents/CONTEXT.md` defining our secure
coding standards:

# Local Project Context & Secure Coding Standards

## Core Paved Roads
We systematically address common vulnerability classes by guiding the agent
to use our pre-configured, secure-by-default helper patterns instead of
writing raw implementation logic from scratch.

1. **Tool Input Validation**: Every agent tool must validate incoming
   parameters against strict Pydantic schemas rather than parsing raw
   dictionaries or strings.
2. **No Shell Execution**: Never use `run_command` or raw shell execution
   tools unless explicitly approved by `hooks.json`.
3. **Pre-Commit Remediation Loop**: If a git commit fails due to a pre-commit
   hook error (such as a Semgrep scan finding), you MUST treat the violation
   as a refactoring task, apply targeted fixes, run tests to verify no
   regressions, and attempt to commit again.

想定される動作: Antigravity は .agents/ ディレクトリと CONTEXT.md ファイルを作成し、確認のために補助ペインに直接表示します。

6. ローカル ゲートフックを構成する

安全でないコードやシークレットがワークステーションから送信されないようにするには、コードを commit する前に、開発環境の境界に自動ゲートを構成します。 Antigravity にフック構成を生成するよう指示し、ターミナルを使用してインストールします。

1. Git pre-commit フック

静的分析でシミュレートされた認証情報を確実にキャッチし、安全でない commit をブロックするために、カスタム Semgrep ルールを定義し、それを適用する Git pre-commit フックを構成します。

カスタム Semgrep ルールを定義する

デフォルトの Semgrep ルール(--config auto)では、信頼度の低いスコアリングのため、"mock" などの単語やハイフンを含むモックキーにフラグが設定されません。ハードコードされた API キーを確実に検出するために、一般的なルールではなく直接正規表現スキャンを利用するカスタム ローカル ルール ファイルを作成します。

👉 Antigravity へのプロンプト:

Create a custom Semgrep rules file `shopping-assistant/.semgrep/rules.yaml`
with a rule to detect hardcoded Google API key prefixes (matching regex
`AIzaSy[A-Za-z0-9_\-]*`). Configure it for Python files with an error severity
and a clear security warning message.

想定される動作: Antigravity は、カスタム スキャンルールを定義する shopping-assistant/.semgrep/rules.yaml を作成します。生成されたルール定義を確認します。

# shopping-assistant/.semgrep/rules.yaml
rules:
  - id: detect-hardcoded-google-api-key
    pattern-regex: 'AIzaSy[A-Za-z0-9_\-]*'
    message: "Security Issue: Hardcoded Google API key prefix detected."
    languages:
      - python
    severity: ERROR

pre-commit フックを構成する

次に、カスタム Semgrep ルールを実行するように Git pre-commit フックを構成します。サブディレクトリ レイアウトでフックを実行する場合、ローカル構成へのパスはプロジェクト サブディレクトリではなく、Git リポジトリのルート ディレクトリ(shopping-assistant/.semgrep/rules.yaml)からの相対パスにする必要があります。

👉 Antigravity へのプロンプト:

Create a `shopping-assistant/.pre-commit-config.yaml` file configured to run
local pre-commit hooks (end-of-file-fixer, trailing-whitespace) and a local
Semgrep security scan on commit for Python files. Ensure Semgrep is configured
with the `--error` flag and references our custom rules file relative to the Git
repository root. Once created, run `pre-commit install` in the
terminal to activate the hooks.

想定される動作: Antigravity は shopping-assistant/.pre-commit-config.yaml を生成し、ユーザーに代わって pre-commit install を実行します。生成された構成を確認します。

# shopping-assistant/.pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: end-of-file-fixer
        name: End of File Fixer
        entry: end-of-file-fixer
        language: system
        types: [file]
      - id: trailing-whitespace
        name: Trailing Whitespace
        entry: trailing-whitespace-fixer
        language: system
        types: [file]
      - id: semgrep
        name: Semgrep Security Scan
        entry: semgrep --error --config shopping-assistant/.semgrep/rules.yaml
        language: system
        types: [python]

この構成により、エージェントが完全に自律型の非インタラクティブ モードで実行されている場合でも、pre-commit ゲートが起動し、静的分析スキャンに失敗した commit をブロックします。

直接実行コマンド(手動検証用)

完全な commit フック サイクルをトリガーせずに静的分析の設定を手動で検証するには、ターミナルから直接これらのチェックを実行します。

pre-commit 経由(「shopping-assistant」ディレクトリから):

uv run pre-commit run semgrep --all-files

Semgrep 経由(「shopping-assistant」ディレクトリから):

uv run semgrep --error --config .semgrep/rules.yaml app/agent.py

2. 組み込みの Antigravity エージェント フック

より深い軌道中間のゲート処理を行うには、shopping-assistant/.agents/hooks.json でエージェント フックを構成します。git フックとは異なり、エージェント フックは、システムで重要なツール(シェル コマンドの実行など)を実行する前に Antigravity をインターセプトします。

👉 Antigravity へのプロンプト:

Create a `shopping-assistant/.agents/hooks.json` file configured with a
`PreToolUse` hook that intercepts `run_command` executions and runs
`python3 .agents/scripts/validate_tool_call.py` with a 10-second timeout.

想定される動作: Antigravity は shopping-assistant/.agents/hooks.json を作成します。生成された構成を確認します。

{
  "enabled": true,
  "PreToolUse": [
    {
      "matcher": "run_command",
      "command": "python3 .agents/scripts/validate_tool_call.py",
      "timeout": 10
    }
  ]
}

次に、Antigravity に、フックで参照される基盤となるツール検証スクリプトを作成するよう指示します。

👉 Antigravity へのプロンプト:

Create the script `shopping-assistant/.agents/scripts/validate_tool_call.py`
with logic to inspect `run_command` executions passed using stdin and block
destructive commands like `rm -rf /`.

想定される動作: Antigravity は、次のような shopping-assistant/.agents/scripts/validate_tool_call.py を生成します。生成された検証スクリプトを確認します。

# shopping-assistant/.agents/scripts/validate_tool_call.py
import sys
import json

def main():
    try:
        context = json.load(sys.stdin)
        command = context.get("tool_args", {}).get("CommandLine", "")
        
        if "rm -rf /" in command or "mkfs" in command:
            print("BLOCKED: Destructive command detected.", file=sys.stderr)
            sys.exit(1)
            
        print("APPROVED: Command validation passed.")
        sys.exit(0)
    except Exception as e:
        print(f"Validation error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()

フックのトレードオフ

  • Git フック: バージョン管理にネイティブ。エージェントが完全に自律型の非インタラクティブ モードで実行されている場合でも実行されます。ただし、commit 中に --no-verify フラグを使用するとバイパスできます。
  • エージェント フック: 軌道中間のイベントをキャプチャして危険なツール コマンドをブロックしますが、デベロッパーが IDE をバイパスした場合、リポジトリを保護しません。

ローカル ゲートは、デベロッパーの優れた習慣を強化し、脆弱性を即座に検出するのに役立ちます。ただし、ローカル ゲートはバイパスできるため、リモートの分離された CI/CD パイプラインが最終的でバイパスできないセキュリティ バリアとなります。

7. STRIDE 脅威モデリング スキルを実装する

次に、Antigravity にセキュリティ アーキテクトの専門知識を付与します。Antigravity スキルは、エージェントに複数ステップの推論ジョブの実行方法を指示する、モジュール型の宣言型 Markdown ディレクトリです。Antigravity は、.agents/skills/ に配置されたスキルを自動的に検出します。

👉 Antigravity へのプロンプト:

Create a local skill directory
`shopping-assistant/.agents/skills/stride-threat-model/` and create a skill
definition file `shopping-assistant/.agents/skills/stride-threat-model/SKILL.md`
with the following content:

---
name: stride-threat-model
description: Performs a systematic STRIDE threat modeling assessment on the
current project's codebase and architecture. Use this when starting a new
implementation phase or reviewing existing components.
---

# STRIDE Threat Modeling Skill

## Goal
Guide the agent to analyze the workspace directory structure, configuration
files, and code files to produce a structured `threat_model.md` assessment.

## Instructions
1. **Analyze System Boundaries**: Map the entry points (tools, workflows,
   prompts) and data storage layers.
2. **STRIDE Evaluation**: Evaluate the system against the six STRIDE pillars:
   - **Spoofing**: Are caller identity boundaries verified before executing
     sensitive tool logic?
   - **Tampering**: Can users manipulate data flows, parameters, or underlying
     state?
   - **Repudiation**: Are critical transactions securely logged?
   - **Information Disclosure**: Are we risking leakage of PII, internal tokens,
     or raw stack traces?
   - **Denial of Service**: Are there rate limits on expensive database or LLM
     queries?
   - **Elevation of Privilege**: Can an unauthenticated user bypass access
     control to reach privileged tool actions?
3. **Output**: Generate a highly structured `threat_model.md` saved directly
   into the workspace root.

想定される動作: Antigravity はカスタム スキル ディレクトリと SKILL.md ファイルを作成します。

次に、新しく作成したスキルを実行して、アクティブなプロジェクト グラフ(shopping-assistant/app/agent.py)を評価します。

👉 Antigravity へのプロンプト:

Run stride-threat-model on our shopping-assistant agent graph.

想定される動作: Antigravity はインテントに一致し、ローカル スキル ディレクトリからオンデマンドで脅威評価の手順をロードし、既存の agent.py ファイルを分析して、構造化された threat_model.mdshopping-assistant ルートに直接生成します。このアプローチにより、日常の作業コンテキストをクリーンで軽量に保ちながら、専門家のセキュリティ推論に即座にアクセスできます。

8. TDD 計画フェーズをゲートする

Antigravity は、さらに機能の実装やコードのリファクタリングを行う前に、セマンティック コードベースの理解を利用して、implementation_plan.mdtask.md チェックリストの変更をマッピングします。Antigravity にセキュリティを事前に設計させるには、.agents/CONTEXT.md でプランの承認を制限するシステムルールを構成します。

👉 Antigravity へのプロンプト:

Append the following TDD planning gate instruction to the bottom of
`shopping-assistant/.agents/CONTEXT.md`:

## TDD Planning Gate
During the Plan phase, you must decompose the workspace task into logical,
modular stages. Every implementation plan MUST include a dedicated
**Security Boundaries & Assertions** section outlining specific edge cases
that could exploit the feature.

想定される動作: Antigravity は、新しい計画ゲートルールで shopping-assistant/.agents/CONTEXT.md を更新します。

以降のステップで Antigravity に機能の構築またはリファクタリングを指示すると、このルールが自動的に分析され、明示的なセキュリティの内訳を含む実装プランが表示されます。このプランは、Antigravity のインタラクティブ ダイアログまたは補助ペインで直接確認できます。コードの生成を開始する前に、[続行] または [承認] をクリックする必要があります。

計画ゲートをテストする(省略可)

この計画ゲートの動作をすぐに確認するには、次のいずれかの機能リクエストで Antigravity にプロンプトを表示します。Antigravity はコードをすぐに生成するのではなく、計画フェーズに入り、詳細なセキュリティ境界とアサーション の内訳(競合状態、不正な権限昇格、負のポイント値の特定など)を示す implementation_plan.md を表示します。

👉 Antigravity へのプロンプト(テストするものを 1 つ選択):

Plan a new agent tool `award_loyalty_points` that awards points to a user's
account after a successful purchase.
Plan a new agent tool `process_cart_checkout` that receives a cart ID and
discount code, applies the discount, and processes the order.
Plan a new agent tool `update_discount_status` that allows administrators to
activate or deactivate discount codes in the store.

9. 分離された結果ベースのテストを作成する

次に、Antigravity に既存の ADK エージェント ツール用の包括的なセキュリティ テストを作成するよう指示します。セキュリティ テストが復元力があり、現実的なものになるように、次の 2 つの基本原則に基づいて構造化します。

  • インタラクションではなく結果をアサートする: 内部ヘルパー呼び出しをスパイする脆弱なモックを作成するのではなく、最終的な戻り文字列と状態の変更をアサートします。
  • 厳格なガードレールを適用する: ツールが明示的なビジネス ロジックの境界(1 回限りの利用や確認済みユーザー ルールなど)を適用していることを確認します。

👉 Antigravity へのプロンプト:

Use `agents-cli` and pytest to generate an outcome-based security test suite
in `shopping-assistant/tests/test_agent.py`. Inspect `app/agent.py` and
write tests to verify all security boundaries and business logic guardrails
for the `redeem_discount` tool.

想定される動作: Antigravity は、次のような shopping-assistant/tests/test_agent.py を生成します。生成されたテストファイルを確認します。

# shopping-assistant/tests/test_agent.py
import pytest
from app.agent import redeem_discount, DISCOUNT_STORE

@pytest.fixture(autouse=True)
def reset_store():
    """Ensure strict test isolation by resetting in-memory store state before each test run."""
    DISCOUNT_STORE["WELCOME50"] = False
    DISCOUNT_STORE["SUMMER20"] = False
    yield
    DISCOUNT_STORE["WELCOME50"] = False
    DISCOUNT_STORE["SUMMER20"] = False

def test_discount_code_can_only_be_redeemed_once():
    """Verify a user cannot submit a request reusing a single-use code."""
    # First redemption - should succeed
    res_one = redeem_discount("WELCOME50", "user_123")
    assert "Success" in res_one
    assert DISCOUNT_STORE["WELCOME50"] is True
    
    # Second redemption trying to reuse the same code
    res_two = redeem_discount("WELCOME50", "user_456")
    assert "Error: Discount code has already been redeemed" in res_two

def test_discount_redemption_rejects_invalid_code():
    """Verify that unknown discount codes are hard-blocked."""
    res = redeem_discount("INVALID999", "user_123")
    assert "Error: Invalid discount code" in res

def test_discount_redemption_rejects_guest_accounts():
    """Verify that unauthenticated guest accounts cannot redeem discounts."""
    res = redeem_discount("SUMMER20", "guest_999")
    assert "Error: Registered user account required" in res
    assert DISCOUNT_STORE["SUMMER20"] is False

TDD GREEN フェーズを確認する

新しく生成されたセキュリティ テストが既存の agent.py 実装に対して正常に合格することを確認するには、Antigravity に pytest を実行するよう指示します。

👉 Antigravity へのプロンプト:

Run `uv run pytest tests/test_agent.py` on our `shopping-assistant` project to verify that our security tests pass successfully.

想定される動作: Antigravity はターミナルで uv run pytest tests/test_agent.py を実行します。すべてのテストケースが正常に合格します。論理アプリケーションの境界は安全になりましたが、commit 中に静的スキャナがハードコードされた API キーをキャッチすることを確認する必要があります。

10. ゲート処理とエージェントの自己修正を確認する

テストが緑色になったら、リファクタリングと commit フェーズ に入ります。ここでは、ローカル セキュリティ スキャンと pre-commit フックにより、脆弱性のあるリポジトリがワークステーションから離れないことが確認され、Antigravity が自律的な自己修正機能を示します。

  1. ターミナルでプロジェクト ディレクトリに移動し、uv run を使用してコードを commit し、ローカル pre-commit フック バイナリが PATH でアクティブになっていることを確認します。
    cd ~/secure-agent-lab/shopping-assistant
    git add .
    uv run git commit -m "feat: implement shopping assistant agent"
    
  2. Git pre-commit フックが Semgrep を自動的に実行するため、commit が失敗することを確認します。
    Semgrep Security Scan....................................................Failed
    - hookid: semgrep
    
      app/agent.py
      Security Issue: Hardcoded Google API key prefix detected.
    
  3. .agents/CONTEXT.md で構成されたPre-Commit Remediation Loop ルールに従って、Antigravity は IDE ターミナルで pre-commit の失敗を自動的にインターセプトし、Semgrep エラーログを読み取り、ハードコードされた API キーからキーを安全に取得するリファクタリング ステップを開始します。
  4. shopping-assistant/app/agent.py で Antigravity によって生成されたリファクタリングされたコードを確認して、API キーの漏洩を解決します。
  5. Antigravity は pytest を自動的に実行して、テストがまだ緑色であることを確認します。
  6. Antigravity はユーザーに代わって commit を再試行します。ローカル Git ID が構成され、リポジトリが初期化されている場合、スキャンは成功し、commit は成功します。

これは、TDD とローカル pre-commit フックとエージェント ループを組み合わせたコア機能を示しています。リモート CI/CD の失敗を待つのではなく、エージェントはローカルで責任を負い、プッシュされる前にデフォルトで安全になるようにコードをリファクタリングします。

11. エージェントをローカルで実行してテストする

セキュリティ境界が検証され、commit されたので、エクスポートした Gemini API キーを使用して ADK エージェントをローカルで実行し、ローカル プレイグラウンドで操作します。

  1. ターミナルで、Gemini API キーが環境にエクスポートされていることを確認します。
    echo $GEMINI_API_KEY # Verify your key is exported
    
  2. エージェントのローカル開発プレイグラウンドを起動します。
    cd ~/secure-agent-lab/shopping-assistant
    agents-cli playground
    
    ローカル プレイグラウンド サーバーがポート 8080 で実行されていることを示す出力が表示されます。
    * Serving ADK Playground
    * Running on http://127.0.0.1:8080/dev-ui/?app=app
    
  3. 提供された URL をウェブブラウザで開いて、ショッピング アシスタント エージェントとのチャットをインタラクティブに開始します。割引コードの利用を依頼してみてください。
    Can you redeem the discount code WELCOME50 for user user_123?
    
    エージェントは Gemini モデルの実行を使用してリクエストを処理し、割引コードの利用を試みます。

12. クリーンアップ

ワークステーションをクリーンアップし、不要なリソースやシークレットをローカル環境に残さないようにするには、次のクリーンアップ手順を行います。

  1. ローカル サーバーを停止する: プレイグラウンド サーバーがまだ実行されている場合は、ターミナルで停止します。Ctrl + C
  2. ローカル プロジェクト ファイルを削除する: マシンからローカル プロジェクト ディレクトリを削除します。
    rm -rf ~/secure-agent-lab
    

13. 完了

おめでとうございます!Google Antigravity IDE を使用して安全なテスト駆動開発ライフサイクルを確立し、純粋な ADK 2.0 ショッピング アシスタント エージェントを構築して、ローカルで検証しました。

学習した内容

  • Antigravity IDE と agents-cli を使用して ADK 2.0 エージェント(ADK)をスキャフォールディングして統合する方法。
  • CONTEXT.md を使用してプロジェクト レベルの安全なコーディング標準を設定する方法。
  • Antigravity IDE でカスタムの STRIDE 脅威モデリング スキルを作成して実行する方法。
  • AI エージェントの計画フェーズをゲートしてセキュリティ境界を適用する方法。
  • pytest を使用して、分離された結果ベースのセキュリティ テストを実装する方法。
  • エージェント アプリケーションをローカルで実行してテストする方法。
  • Git フックとエージェント固有の実行フックの違いとトレードオフ。

次のステップ

Kaggle 5 日間の AI エージェント バッジを獲得する 🎉

Kaggle の「5 日間の AI エージェント: Google による集中的なバイブ コーディング コース」 の一環としてこのラボを完了しましたか?完了バッジを受け取ります。

5 日間の AI エージェント バッジを取得する