Antigravity 및 TDD로 AI 에이전트 수명 주기 Vibecode 및 보안

1. 소개

이 Codelab에서는 Google의 에이전트 개발 키트 (ADK)를 사용하여 통합 AI 쇼핑 어시스턴트가 있는 소매 웹 애플리케이션을 빌드합니다. Google Antigravity IDE (Google의 에이전트 기반 IDE)를 사용하여 안전한 테스트 주도 개발 (TDD) 워크플로를 설정합니다.

보안을 후반 단계의 관문으로 취급하는 대신 코드 시작 시점까지 '보안을 왼쪽으로 이동'하는 방법을 배우게 됩니다. 개발 표준을 적용하고, STRIDE 위협 모델링을 자동화하고, git 사전 커밋 후크와 에이전트별 실행 후크를 사용하여 에이전트 작업을 관리합니다.

실습할 내용

  • Antigravity IDE와 agents-cli를 사용하여 ADK 2.0 쇼핑 어시스턴트 에이전트를 스캐폴딩하고 빌드합니다.
  • 영구 환경설정 파일 (CONTEXT.md)을 사용하여 프로젝트 수준의 보안 코딩 표준을 설정합니다.
  • Antigravity IDE에서 맞춤 작업공간 수준 STRIDE 위협 모델링 스킬을 빌드하고 호출합니다.
  • TDD 계획 단계에서 직접 보안 가드레일을 시행합니다.
  • Antigravity를 사용하여 Pytest에서 결과 기반 보안 테스트를 작성합니다.
  • Antigravity에서 로컬 수정 루프를 사용하여 Semgrep 검사를 자동화하도록 Git 커밋 전 후크를 구성합니다.

필요한 항목

  • 웹브라우저(예: 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. Workspace 및 도구 체인 설정

먼저 프로젝트 작업공간을 초기화하고 기본 에이전트 관리 도구 모음을 설치합니다. 이를 위해 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 저장소를 설정하고 IDE에 ADK 동반자 기술을 설치합니다.

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)을 확인하고 상태를 수정합니다. 실제 데이터베이스가 있는 멀티 스레드 프로덕션 환경에서 두 개의 동시 요청이 모두 쓰기 커밋 전에 코드를 사용되지 않은 것으로 읽을 수 있으므로 이중 사용 취약점이 발생할 수 있습니다. 프로덕션에서는 항상 비관적 잠금 (예: .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. 로컬 게이팅 후크 구성

보안에 취약한 코드나 비밀이 워크스테이션을 벗어나지 않도록 하려면 코드를 커밋하기 전에 개발 환경의 경계에 자동 게이트를 구성하세요. Antigravity에 후크 구성을 생성하라는 메시지를 표시한 다음 터미널을 사용하여 설치합니다.

1. Git 커밋 전 후크

정적 분석에서 시뮬레이션된 사용자 인증 정보를 안정적으로 포착하고 안전하지 않은 커밋을 차단하기 위해 맞춤 Semgrep 규칙을 정의하고 이를 적용하는 Git 사전 커밋 후크를 구성합니다.

맞춤 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

커밋 전 후크 구성

그런 다음 맞춤 Semgrep 규칙을 실행하도록 Git 사전 커밋 후크를 구성합니다. 하위 디렉터리 레이아웃에서 후크를 실행할 때 로컬 구성의 경로는 프로젝트 하위 디렉터리가 아닌 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]

이 구성을 사용하면 에이전트가 완전 자율 비대화형 모드로 실행되더라도 사전 커밋 게이트가 실행되고 정적 분석 스캔에 실패한 커밋이 차단됩니다.

직접 실행 명령어 (수동 확인용)

전체 커밋 후크 주기를 트리거하지 않고 정적 분석 설정을 수동으로 확인하려면 터미널에서 직접 이러한 검사를 실행하면 됩니다.

사전 커밋을 통해('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 Hooks: 버전 제어에 기본적으로 제공되며 에이전트가 완전 자율 비대화형 모드로 실행되는 경우에도 실행됩니다. 하지만 커밋 중에 --no-verify 플래그를 사용하여 우회할 수 있습니다.
  • 에이전트 후크: 위험한 도구 명령어를 차단하기 위해 궤적 중간에 이벤트를 캡처하지만 개발자가 IDE를 우회하는 경우 저장소를 보호하지는 않습니다.

로컬 게이트는 좋은 개발자 습관을 강화하고 취약점을 즉시 포착하는 데 도움이 됩니다. 하지만 로컬 게이트는 우회할 수 있으므로 원격의 격리된 CI/CD 파이프라인이 궁극적이고 우회할 수 없는 보안 장벽으로 유지됩니다.

7. STRIDE 위협 모델링 기술 구현

이제 Antigravity에 보안 설계자의 전문 지식을 부여합니다. Antigravity 스킬은 에이전트가 다단계 추론 작업을 실행하는 방법을 안내하는 모듈식 선언적 마크다운 디렉터리입니다. 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 파일을 분석하고, shopping-assistant 루트에 구조화된 threat_model.md를 직접 생성합니다. 이 접근 방식을 사용하면 일상적인 작업 컨텍스트를 깔끔하고 가볍게 유지하면서 전문가의 보안 추론에 즉시 액세스할 수 있습니다.

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 프롬프트 (테스트할 항목 하나 선택):

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 에이전트 도구에 대한 포괄적인 보안 테스트를 작성하도록 안내합니다. Google은 보안 테스트의 복원력과 현실성을 보장하기 위해 다음 두 가지 핵심 원칙에 따라 테스트를 구성합니다.

  • 상호작용이 아닌 결과에 어설션: 내부 도우미 호출을 스파이하는 취약한 모의 객체를 작성하는 대신 최종 반환 문자열과 상태 변이에 어설션합니다.
  • 엄격한 가이드라인 적용: 도구가 명시적인 비즈니스 로직 경계 (예: 일회용 사용 및 등록된 사용자 규칙)를 적용하는지 확인합니다.

👉 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 녹색 단계 확인

새로 생성된 보안 테스트가 기존 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를 실행합니다. 모든 테스트 사례가 성공적으로 통과됩니다. 이제 논리적 애플리케이션 경계가 안전하지만 커밋 중에 하드코딩된 API 키가 정적 스캐너에 포착되는지 확인해야 합니다.

10. 게이팅 및 에이전트 자체 수정 확인

이제 테스트가 녹색으로 표시되므로 리팩터링 및 커밋 단계를 시작합니다. 이때 로컬 보안 스캔과 사전 커밋 후크를 통해 취약점이 있는 저장소가 워크스테이션을 벗어나지 않는지 확인하고 Antigravity가 자율 자체 수정 기능을 보여줍니다.

  1. 터미널에서 프로젝트 디렉터리로 이동하고 uv run를 사용하여 코드를 커밋하여 로컬 사전 커밋 후크 바이너리가 PATH에서 활성 상태인지 확인합니다.
    cd ~/secure-agent-lab/shopping-assistant
    git add .
    uv run git commit -m "feat: implement shopping assistant agent"
    
  2. Git 사전 커밋 후크가 Semgrep을 자동으로 실행하므로 커밋이 실패하는 것을 확인합니다.
    Semgrep Security Scan....................................................Failed
    - hookid: semgrep
    
      app/agent.py
      Security Issue: Hardcoded Google API key prefix detected.
    
  3. .agents/CONTEXT.md에 구성된 커밋 전 수정 루프 규칙에 따라 Antigravity는 IDE 터미널에서 커밋 전 실패를 자동으로 가로채고 Semgrep 오류 로그를 읽고 하드코딩된 API 키에서 키를 안전하게 검색하는 단계로 이동하는 리팩터링 단계를 시작합니다.
  4. shopping-assistant/app/agent.py에서 Antigravity가 생성한 리팩터링된 코드를 검토하여 API 키 유출을 해결합니다.
  5. Antigravity는 테스트가 여전히 통과 상태인지 확인하기 위해 pytest를 자동으로 실행합니다.
  6. Antigravity가 사용자를 대신하여 커밋을 다시 시도합니다. 로컬 Git ID가 구성되어 있고 저장소가 초기화되어 있다면 스캔이 통과되고 커밋이 성공합니다.

이는 TDD와 로컬 사전 커밋 후크 및 에이전트 루프를 결합하는 핵심적인 힘을 보여줍니다. 원격 CI/CD 실패를 기다리는 대신 에이전트는 로컬에서 책임을 지고 푸시되기 전에 기본적으로 안전하도록 코드를 리팩터링합니다.

11. 에이전트를 로컬에서 실행하고 테스트

이제 보안 경계가 확인되고 커밋되었으므로 내보낸 Gemini API 키를 사용하여 로컬에서 ADK 에이전트를 실행하여 로컬 Playground에서 상호작용합니다.

  1. 터미널에서 Gemini API 키가 환경에 내보내져 있는지 확인합니다.
    echo $GEMINI_API_KEY # Verify your key is exported
    
  2. 에이전트의 로컬 개발 플레이그라운드를 실행합니다.
    cd ~/secure-agent-lab/shopping-assistant
    agents-cli playground
    
    로컬 Playground 서버가 포트 8080에서 실행되고 있음을 나타내는 출력이 표시됩니다.
    * Serving ADK Playground
    * Running on http://127.0.0.1:8080/dev-ui/?app=app
    
  3. 웹브라우저에서 제공된 URL을 열어 Shopping Assistant 에이전트와 대화형으로 채팅을 시작합니다. 할인 코드를 사용해 달라고 요청해 보세요.
    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 에이전트 배지 획득