‫Vibecode وتأمين دورة حياة وكيل الذكاء الاصطناعي باستخدام Antigravity وTDD

1. مقدمة

في هذا الدرس التطبيقي حول الترميز، ستنشئ تطبيق ويب للبيع بالتجزئة يتضمّن "مساعد تسوّق" مدمجًا يعمل بالذكاء الاصطناعي باستخدام حزمة تطوير الوكلاء (ADK) من Google. ستستخدم Google Antigravity IDE (بيئة تطوير متكاملة تستند إلى الذكاء الاصطناعي الوكيل من Google) لإنشاء سير عمل آمن يعتمد على التطوير المستند إلى الاختبار (TDD).

بدلاً من التعامل مع الأمان كحاجز في مرحلة متأخرة، ستتعلّم "نقل الأمان إلى اليسار" إلى نقطة بدء كتابة الرمز. ستفرض معايير التطوير، وتبرمج نموذج تهديد STRIDE، وتتحكّم في إجراءات الوكيل باستخدام خطافات git قبل الالتزام وخطافات التنفيذ الخاصة بالوكيل.

الإجراءات التي ستنفذّها

  • إنشاء وكيل مساعد للتسوّق باستخدام حزمة تطوير الوكلاء (ADK) 2.0 باستخدام بيئة التطوير المتكاملة Antigravity وagents-cli
  • إعداد معايير الترميز الآمن على مستوى المشروع باستخدام ملف سياق ثابت (CONTEXT.md)
  • إنشاء مهارة مخصّصة على مستوى مساحة العمل لنمذجة التهديدات باستخدام STRIDE واستدعاؤها في Antigravity IDE
  • فرض ضوابط الأمان مباشرةً خلال مرحلة "خطة التطوير المستند إلى الاختبار"
  • كتابة اختبارات أمان مستندة إلى النتائج في Pytest باستخدام Antigravity
  • يمكنك ضبط عمليات التحقّق المسبق في Git لتنفيذ عمليات فحص Semgrep تلقائيًا باستخدام حلقات الإصلاح المحلية في Antigravity.

المتطلبات

  • متصفّح ويب، مثل Chrome
  • الإلمام بلغة Python وPytest وأوامر الوحدة الطرفية الأساسية
  • تثبيت Google Antigravity IDE يُرجى الانتقال إلى الموقع الإلكتروني الرسمي.
  • تم تثبيت أداة إدارة الحِزم uv. يُرجى الاطّلاع على دليل تثبيت uv.
  • تم تثبيت أداة سطر الأوامر Git. يتم استخدام Git حصريًا للتحكّم في الإصدارات المحلية في هذا المختبر، لذلك لا يلزم توفّر حساب على GitHub. راجِع دليل تثبيت Git.

هذا الدرس التطبيقي حول الترميز مخصّص للمطوّرين من جميع المستويات، بما في ذلك المبتدئين. سيستغرق إكمال الدرس التطبيقي بأكمله حوالي 60 دقيقة.

إعداد المصادقة والبيئة

قدِّم بيانات اعتماد المصادقة ليتمكّن الوكيل من استدعاء نماذج Gemini. احصل على مفتاح Gemini API عادي من Google AI Studio وصدِّره في جلسة طرفية لبيئة التطوير المتكاملة (IDE):

export GEMINI_API_KEY="your_api_key_here"
export GOOGLE_GENAI_USE_ENTERPRISE=FALSE

2. إعداد Workspace وToolchain

أولاً، ابدأ تهيئة مساحة عمل المشروع وثبِّت سلسلة أدوات إدارة الوكيل الأساسية. لإجراء ذلك، سنطلب من 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 المصاحبة في بيئة التطوير المتكاملة.

3- إنشاء بنية أساسية لمشروع وكيل ADK

في هذه المرحلة، نوجّه Antigravity لاستخدام agents-cli لإنشاء مشروع وكيل ADK 2.0 يعمل بكامل طاقته ويُطلق عليه اسم shopping-assistant. سنطلب من 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، يتم عرض ملفات المشاريع التي تم إنشاؤها حديثًا مباشرةً في اللوحة الإضافية (الجانب الأيسر). يمكنك الاطّلاع على shopping-assistant/app/agent.py هناك أو فتحه من مستكشف الملفات في بيئة التطوير المتكاملة.

# 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()) أو ميزة التحكم المتفائل في الإصدار لضمان الفصل بين العمليات.

Lint the Initial Agent Graph

للتحقّق من أنّ الرسم البياني للوكيل الذي تم إنشاؤه حديثًا يتم تجميعه بشكل صحيح، يمكننا أن نطلب من Antigravity تشغيل أداة التدقيق واختبار الوكيل نيابةً عنّا.

👉 الطلب إلى Antigravity:

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

النتائج المتوقّعة: ستنفّذ Antigravity الأمرَين agents-cli lint وagents-cli lint --fix لإصلاح أي مشاكل في التنسيق أو في أداة Lint تم رصدها.

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. ضبط خطافات Local Gating

لمنع مغادرة الرموز أو الأسرار غير الآمنة لمحطة العمل، عليك ضبط بوابات مبرمَجة على حدود بيئة التطوير قبل إرسال الرموز. سنطلب من Antigravity إنشاء إعدادات الخطاف، ثم تثبيتها باستخدام نافذة الأوامر.

1. Git Pre-Commit Hook

لضمان أن يرصد التحليل الثابت بشكل موثوق بيانات الاعتماد المحاكية ويحظر عمليات الإيداع غير الآمنة، سنحدّد قاعدة Semgrep مخصّصة ونضبط أداة Git pre-commit hook لفرضها.

تحديد قاعدة Semgrep مخصّصة

لا تضع قواعد Semgrep التلقائية (--config auto) علامة على المفاتيح الوهمية التي تحتوي على كلمات مثل "mock" أو واصلات بسبب تسجيل نقاط منخفضة الثقة. لرصد مفتاح واجهة برمجة التطبيقات المضمّن في الرمز البرمجي بشكل موثوق، سننشئ ملف قواعد محلية مخصّصة باستخدام فحص التعبير العادي المباشر بدلاً من القواعد العامة.

👉 الطلب إلى 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 Hook

بعد ذلك، اضبط Git pre-commit hook لتشغيل قاعدة Semgrep المخصّصة. عند تنفيذ خطافات في تنسيق دليل فرعي، يجب أن تكون مسارات الإعدادات المحلية مرتبطة بدليل الجذر لمستودع 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 قبل أن يتمكّن من تشغيل أدوات مهمة (مثل تنفيذ أوامر shell) على نظامك.

👉 الطلب إلى 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: مدمجة في نظام التحكم في الإصدارات، وتعمل حتى إذا كان الوكيل يعمل في وضع مستقل تمامًا وغير تفاعلي. ومع ذلك، يمكن تجاوزها باستخدام العلامة --no-verify أثناء عملية الالتزام.
  • خطافات الوكيل: تعمل على تسجيل الأحداث في منتصف مسارها لحظر أوامر الأدوات الخطيرة، ولكنّها لا تحمي المستودع إذا تجاوز المطوّر بيئة التطوير المتكاملة.

تعزّز البوابات المحلية عادات المطوّرين الجيدة وتساعد في رصد الثغرات الأمنية على الفور. ومع ذلك، تذكَّر أنّه يمكن تجاوز البوابات المحلية، ما يعني أنّ مسار CI/CD البعيد والمعزول يظلّ حاجز الأمان النهائي الذي لا يمكن تجاوزه.

7. Implement STRIDE Threat Modeling Skill

الآن، عليك منح 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.md منظَّمًا مباشرةً في جذر shopping-assistant. يساعد هذا الأسلوب في الحفاظ على سياق عملك اليومي واضحًا وبسيطًا مع منحك إمكانية الوصول الفوري إلى استدلال الأمان الذي يقدّمه الخبراء.

8. إغلاق مرحلة "خطة اختبار التطوير المستند إلى الاختبار"

قبل تنفيذ المزيد من الميزات أو إعادة هيكلة الرمز، تستخدم Antigravity فهمها لقاعدة الرموز البرمجية الدلالية لربط التغييرات في قائمة التحقق implementation_plan.md وقائمة التحقق task.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 الحالية. لضمان أن تكون اختبارات الأمان مرنة وواقعية، ننظّمها استنادًا إلى مبدأين أساسيين:

  • التركيز على النتائج وليس التفاعلات: ركِّز على سلاسل الإرجاع النهائية وتغييرات الحالة بدلاً من كتابة عمليات محاكاة هشة تتتبّع طلبات المساعد الداخلي.
  • فرض ضوابط صارمة: تأكَّد من أنّ الأدوات تفرض حدودًا واضحة لمنطق النشاط التجاري (مثل قواعد الاسترداد لمرة واحدة وقواعد المستخدمين المسجّلين).

👉 الطلب إلى 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 في نافذة الجهاز. تنجح جميع حالات الاختبار. أصبحت حدود التطبيق المنطقية آمنة الآن، ولكن يجب التأكّد من أنّ أداة الفحص الثابتة ترصد مفتاح واجهة برمجة التطبيقات المضمّن في الرمز البرمجي أثناء عملية الإرسال.

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 pre-commit hook تشغّل 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، ويبدأ خطوة إعادة تصميم للانتقال من مفتاح واجهة برمجة تطبيقات مبرمَج إلى استرداد المفتاح بشكل آمن.
  4. راجِع الرمز الذي أعاد Antigravity إنشاؤه في shopping-assistant/app/agent.py لحلّ مشكلة تسريب مفتاح واجهة برمجة التطبيقات.
  5. يُشغّل Antigravity تلقائيًا pytest للتأكّد من أنّ الاختبارات لا تزال ناجحة.
  6. تحاول Antigravity تنفيذ عملية الإيداع مرة أخرى نيابةً عنك. إذا تم ضبط هوية Git المحلية وتمت تهيئة مستودع، ستنجح عملية الفحص وسيتم تنفيذ عملية الإيداع.

يوضّح هذا المثال القوة الأساسية للجمع بين عملية التطوير المستندة إلى الاختبار (TDD) وخطافات ما قبل الالتزام المحلية وحلقات الوكيل. بدلاً من انتظار حدوث خطأ في عملية التكامل المستمر/التسليم المستمر عن بُعد، يتم تحميل مسؤولية الوكيل محليًا، وإعادة تصميم رمزه ليكون آمنًا تلقائيًا قبل دفعه.

11. تشغيل الوكيل واختباره محليًا

بعد التحقّق من حدود الأمان وتثبيتها، شغِّل وكيل ADK محليًا باستخدام مفتاح Gemini API الذي تم تصديره للتفاعل معه في ساحة اللعب المحلية.

  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 المقدَّم في متصفّح الويب لبدء الدردشة بشكل تفاعلي مع وكيل "مساعد التسوّق". جرِّب أن تطلب منه تحصيل قيمة رمز خصم:
    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، وأنشأت وكيل مساعد تسوّق خالصًا باستخدام الإصدار 2.0 من "حزمة تطوير التطبيقات"، وتحقّقت من صحته محليًا.

ما تعلّمته

  • كيفية إنشاء وكيل ADK 2.0 ودمجه (ADK) باستخدام Antigravity IDE وagents-cli
  • كيفية إعداد معايير الترميز الآمن على مستوى المشروع باستخدام CONTEXT.md
  • كيفية إنشاء وتنفيذ مهارة مخصّصة لنموذج تقييم المخاطر STRIDE في Antigravity IDE
  • كيفية حصر مرحلة التخطيط في وكيل الذكاء الاصطناعي لفرض حدود الأمان
  • كيفية تنفيذ اختبارات أمان مستقلة تستند إلى النتائج باستخدام pytest
  • كيفية تشغيل التطبيق المستند إلى وكيل واختباره محليًا
  • الاختلافات والمفاضلات بين خطافات Git وخطافات التنفيذ الخاصة بالعامل

الخطوات التالية

الحصول على شارة "وكلاء الذكاء الاصطناعي في 5 أيام" على Kaggle 🎉

هل أكملت هذا المختبر كجزء من دورة تدريبية مكثّفة لمدة 5 أيام حول وكلاء الذكاء الاصطناعي: ترميز المشاعر باستخدام Google في Kaggle؟ المطالبة بشارة الإكمال:

الحصول على شارة "وكلاء الذكاء الاصطناعي خلال 5 أيام"