۱. مقدمه
در این codelab، یک عامل کدنویسی هوش مصنوعی (Antigravity) را پیکربندی خواهید کرد تا امنیت بخشی از چرخه توسعه عادی آن باشد، نه یک مرحله بازبینی جداگانه. مجموعهای از مهارتهای عامل را نصب خواهید کرد که عامل را در چرخه «برنامهریزی» ← «قرمز» ← «سبز» ← «بازسازی کد» راهنمایی میکند، و یک قلاب PreToolUse که git push را رهگیری میکند، فایلهای تغییریافته را با CodeMender اسکن میکند، و هر یافتهای را با دستورالعملهایی برای رفع آنها بهصورت «آزمایش-اول» به عامل برمیگرداند.
مهارتها و قلاب از چارچوب عامل TDD امن متنباز میآید. آنها را در همان فضای کاری ~/codemender-lab که در «مبانی CodeMender CLI» ساختید نصب خواهید کرد.
آنچه خواهید آموخت
- نحوه کشف قوانین، مهارتها، و قلابهای فضای کاری توسط Antigravity در
.agents/. - شش مهارت «توسعه امن آزمونمحور» چه کاری انجام میدهند و هرکدام متعلق به کدام فاز چرخه هستند.
- چگونه قلاب
PreToolUseفراخوانی ابزار نماینده را در ورودی استاندارد دریافت میکند و تصمیم مجاز/ غیرمجاز را برمیگرداند. - نحوه اجرای
cm findتوسط قلاب دروازه امنیتی (security_gate_hook.sh)، طبقهبندی یافتهها براساس شدت، پیگیری تلاشهای رفع مشکل، و ارجاع باcm verify. - How to verify the whole hook pipeline offline with mock scanners before pointing it at the real
cm.
پیشنیازها
- تکمیل اصول CodeMender CLI. این آزمایشگاه در دایرکتوری
~/codemender-labادامه مییابد و ازsample_app/،CONTEXT.md، سابقه git، و~/.codemender/config.yamlآن مجدداً استفاده میکند. - Antigravity نصب شده باشد و بتواند پوشه محلی را بهعنوان فضای کاری باز کند.
-
git،jq، وbashنصب شد. اسکریپتهای hook پوسته Bash ساده هستند و در پوسته Bash 3.2 پیشفرض macOS و همچنین نسخههای جدیدتر اجرا میشوند. - محیط مجازی Python از CodeMender CLI Basics (
~/codemender-lab/.venv) با Flask نصبشده. - دانش پایه درباره دستورگاننویسی پوسته.
۲. راهاندازی Workspace
مرحله ۱: بازگشت به فهرست راهنمای آزمایشگاه
همه فرمانها در این آزمایشگاه از ~/codemender-lab با محیط مجازی فعال اجرا میشوند:
cd ~/codemender-lab && source .venv/bin/activate
تأیید کنید که فضای کاری از آزمایشگاه قبلی دستنخورده است و درخت کاری شما تمیز است:
ls sample_app/data_service.py CONTEXT.md .gitignore
git status --short
git status --short نباید چیزی چاپ کند. اگر فایلها را فهرست میکند، پیشاز ادامه دادن آنها را ثبت کنید.
مرحله ۲: نامگذاری کردن شاخه main
دروازه امنیتی درخت کاری شما را با origin/main مقایسه میکند تا تصمیم بگیرد کدام فایلها را اسکن کند. اگر آن مرجع وجود نداشته باشد، به HEAD~1 برمیگردد که فقط جدیدترین commit را پوشش میدهد. مطمئن شوید نام شعبهتان main باشد:
git branch -M main
مرحله ۳: افزودن نقطه ورودی مجموعه آزمون
حلقه «توسعه آزمونمحور» (TDD) ایمن از نماینده میخواهد که python3 -m unittest discover -s tests را پساز هر اصلاح اجرا کند، بنابراین فضای کاری به دایرکتوری tests/ نیاز دارد. با یک آزمایش مشخصهسازی شروع کنید تا مجموعه چیزی واقعی برای اجرا داشته باشد:
mkdir -p tests && touch tests/__init__.py
cat << 'EOF' > tests/test_data_service.py
import unittest
from sample_app.data_service import hash_password
class HashPasswordTests(unittest.TestCase):
def test_returns_hex_digest(self):
digest = hash_password("hunter2")
self.assertIsInstance(digest, str)
int(digest, 16) # raises ValueError if not hexadecimal
if __name__ == "__main__":
unittest.main()
EOF
python3 -m unittest discover -s tests
باید Ran 1 test و OK را ببینید.
مرحله ۴: گسترش دادن .gitignore و ثبت کردن
فایلهای زمان اجرای تولیدشده توسط این آزمایشگاه را به .gitignore اضافه کنید، سپس خط مبنا را ثبت کنید:
printf '.security-gate/\nusers.db\n*.bak\n' >> .gitignore
git add -A && git commit -m "Add test suite entry point for Secure TDD"
۳. درحال نصب فایلهای چارچوب
مهارتها، قانون، قلاب، و مجموعه دادههای تست آفلاین همگی در یک فهرست راهنمای .agents/ قرار دارند. بهجای تایپ کردن حدود ۸۰۰ خط bash بهصورت دستی، چارچوب را کلون کنید و آن دایرکتوری را در فضای کاریتان کپی کنید:
git clone --depth 1 https://github.com/h3xar0n/secure-tdd-agent-framework.git /tmp/secure-tdd
cp -R /tmp/secure-tdd/.agents ./.agents
rm -rf /tmp/secure-tdd
تأیید چیدمان:
find .agents -type f | sort
.agents/hooks.json
.agents/lib/README.md
.agents/lib/engine_codemender.sh
.agents/lib/engine_semgrep.sh
.agents/lib/gate_common.sh
.agents/rules/secure_tdd_workflow.md
.agents/security_gate_hook.sh
.agents/skills/defensive-developer/SKILL.md
.agents/skills/history-context-seeder/SKILL.md
.agents/skills/local-refactor-scanner/SKILL.md
.agents/skills/security-test-writer/SKILL.md
.agents/skills/skill-evolution-updater/SKILL.md
.agents/skills/threat-model-assessor/SKILL.md
.agents/tests/mocks/cm
.agents/tests/mocks/semgrep
.agents/tests/run_tests.sh
مطمئن شوید نقطه ورودی قلاب قابلاجرا باشد:
chmod +x .agents/security_gate_hook.sh
ls -l .agents/security_gate_hook.sh
بقیه این آزمایشگاه آنچه را که بهتازگی نصب کردهاید، یکبهیک بررسی میکند.
۴. قانون گردش کار همیشهروشن
مهارتها درصورت درخواست بارگیری میشوند، یعنی زمانی که نماینده تصمیم میگیرد شرح مهارت با تکلیف مطابقت دارد. چیزی باید به نماینده بگوید که به ترتیب درست به آنها دسترسی پیدا کند. این کار .agents/rules/secure_tdd_workflow.md است. مقدمه آن trigger: always_on را تنظیم میکند، بنابراین قانون به هر نوبت تزریق میشود:
---
trigger: always_on
---
# Test-Driven Development with Integrated Security (Secure TDD) Workflow Rule
You MUST strictly follow this 4-phase cyclical workflow for all feature implementations, refactors, and bug fixes:
1. **Phase A (Plan, Scope & Threat Model)**:
- Ingest `CONTEXT.md` to review established project conventions, approved helpers, and trust zones.
- Decompose feature requirements, user stories, and acceptance criteria.
- Invoke the **Threat Model Assessor Skill** to perform a STRIDE evaluation and generate/update `threat_model.md`.
2. **Phase B (Functional & Security Test-First - RED)**:
- Invoke the **Security Test Writer Skill**.
- Author unit and integration tests asserting functional behavior (happy paths, business logic), edge cases, AND security boundaries (rejecting invalid inputs, unauthenticated requests, unauthorized role access).
- Execute the tests and confirm they FAIL for the expected assertion reason (RED).
3. **Phase C (Feature Implementation & Defensive Code - GREEN)**:
- Invoke the **Defensive Developer Skill**.
- Author clean, modular production code strictly required to satisfy the functional tests and security assertions.
- Apply input validation allow-lists, parameterized queries, and least-privilege payload returns.
- Run the tests to confirm they are GREEN.
4. **Phase D (Refactor, Quality & Scan)**:
- Invoke the **Local Refactor & Scanner Skill**.
- Clean up code, eliminate duplication, and verify 100% passing test regressions.
- Run fast deterministic checks (secrets, dependencies, local SAST).
- Conduct a guided AI review to verify architectural boundaries and eliminate logic bypasses.
- Ensure diffs remain small, surgical, and preserve baseline stability.
5. **Continuous Evolution**:
- If a new pattern, helper function, or architectural convention was introduced, invoke the **Skill Evolution Updater Skill** to document the lesson into `CONTEXT.md` or the appropriate `SKILL.md`.
6. **Multi-Finding Remediation Protocol**:
- When resolving multiple findings from a scan or security gate rejection, iterate sequentially one finding at a time:
1. Author one discrete boundary test for the finding (RED).
2. Implement the minimal defensive fix (GREEN).
3. Verify local tests pass before moving to the next finding.
- Avoid applying multi-finding changes in a single unverified edit. Run the full regression test suite only after all individual findings have passed their discrete TDD cycle.
این قانون به CONTEXT.md ارجاع میدهد که آن را در «مبانی CodeMender CLI» ایجاد کردهاید. همان فایلی که cm fix را بهسمت قرارداد پُرسمان پارامتریشده شما هدایت میکرد، اکنون برنامهریزی نماینده را هدایت میکند. مورد ۶ برای این آزمایشگاه از همه مهمتر است: این همان چیزی است که وقتی دروازه امنیتی یک ارسال را با چندین یافته بهطور همزمان رد میکند، نماینده از آن پیروی میکند.
۵. شش مهارت عامل
هر مهارت یک دایرکتوری حاوی SKILL.md با مقدمه فایل YAML است. دو فیلد الزامی است:
name: شناسهای با حروف کوچک و خط تیره.description: مهارت چه کاری انجام میدهد و چه زمانی باید از آن استفاده شود. عامل فقط این فیلد را هنگام تصمیمگیری درباره بار کردن مهارت کامل میخواند، بنابراین هر شرح زیر همچنین میگوید که مهارت برای چه چیزی نیست.
مهارت | دور | هدف |
| پاسخ: طرح | Scope the feature, run STRIDE, write |
| ب: قرمز | آزمایشهای مرزی و کاربردی بنویسید که بهدلیل درست ناموفق شوند. |
| پ: سبز | بااستفاده از الگوهای ایمن، حداقل کد لازم را برای سبز کردن تستها بنویسید. |
| D: Refactor | پاکسازی کنید، مجموعه کامل را اجرا کنید، اسکنرهای محلی را اجرا کنید، تفاوتها را بازبینی کنید. |
| پیوسته | قراردادهای جدید را در فایلهای |
| آمادهسازی | استخراج سابقه git برای کاشت |
محتوای کامل در ادامه آمده است تا بتوانید ببینید مقدمه و دستورالعملها چگونه باهم مطابقت دارند.
۱. threat-model-assessor (فاز A)
.agents/skills/threat-model-assessor/SKILL.md:
---
name: threat-model-assessor
description: Plans feature architecture, functional requirements, and evaluates STRIDE security boundaries in Phase A Plan. Use when scoping new features or bug fixes, defining user stories and acceptance criteria, identifying trust boundaries, and generating or updating threat_model.md. Do not use for writing test assertions, implementing production code, or running local scanners.
---
# Planning, Requirements & Threat Model Assessor Skill (Phase A: Plan Phase)
## Overview
Decompose feature requirements, establish functional acceptance criteria, and map trust boundaries before any production code is authored. This skill pairs functional engineering scoping with STRIDE threat modeling at the planning stage, establishing the functional and security acceptance criteria consumed by downstream test writers.
## System Sequence
1. **Ingest Context**: Read `CONTEXT.md` to identify existing architecture, trust boundaries, approved libraries, and conventions.
2. **Decompose Requirements**:
- Define user stories, input/output data contracts, and functional acceptance criteria.
- Break complex tasks into bite-sized, testable implementation stages.
3. **Apply STRIDE Threat Modeling**:
- **Spoofing**: Authentication boundaries, session validation, caller identity checks.
- **Tampering**: Input payload validation, integrity checks, parameter tampering.
- **Repudiation**: Audit logging of critical state transitions.
- **Information Disclosure**: Restrict error responses, prevent stack trace leaks, mask PII/secrets.
- **Denial of Service**: Resource limits, payload size constraints, timeout limits.
- **Elevation of Privilege**: Role-Based Access Control (RBAC), caller authorization checks.
4. **Generate/Update `threat_model.md`**:
- Store or update `threat_model.md` at the workspace root with both Functional & Security Acceptance Criteria.
## Target Output Artifact (`threat_model.md`)
```markdown
# Feature Plan & Threat Model: [Feature Name]
## 1. Functional Scope & Requirements
- **Goal**: [Description of feature or bug fix]
- **Deliverables**: [Endpoints, functions, or modules to create/modify]
- **Functional Acceptance Criteria**: [Expected behaviors and outputs]
## 2. Entry Points & Data Inputs
- Endpoint / Input: [Path / Name]
- Format & Constraints: [Schema / Type]
## 3. Trust Boundaries & Access Controls
- Authentication: [Required / Public]
- Authorization Role: [User / Admin]
## 4. STRIDE Threat Matrix & Security Acceptance Criteria
- [STRIDE Category]: [Threat Description] -> [Required Mitigation & Test Assertion]
```
۲. security-test-writer (دوره ب)
.agents/skills/security-test-writer/SKILL.md:
---
name: security-test-writer
description: Authors test-first unit and integration tests covering functional behavior, edge cases, and security boundaries in Phase B RED. Use when creating failing automated tests before writing production code, asserting HTTP status codes and contract responses, establishing boundary limits, or asserting that exploit payloads are rejected cleanly. Do not use for threat modeling during initial planning, writing production feature code, or running refactor sweeps.
---
# QA & Security Test Writer Skill (Phase B: RED Phase)
## Overview
Translate functional requirements and security criteria from `threat_model.md` and `CONTEXT.md` into executable test cases that fail initially (RED), asserting expected business logic, edge-case handling, and security boundaries before production code is authored.
## Three Verification Pillars
1. **Behavior-Driven Outcomes**:
- Assert strictly on API/HTTP outcomes (status codes 200/302 for valid requests, 400/401/403 for invalid/unauthorized, expected JSON responses) rather than mocking internal private methods.
2. **Strict Test Isolation**:
- Ensure test setup and teardown cleanly isolate state (e.g., transaction rollbacks, fresh test contexts) so state never bleeds between test runs.
3. **Integration Over Fragile Mocking**:
- Utilize local test databases or real server contexts rather than fragile fake mocks to verify realistic functional and security behavior.
## Execution Sequence
1. **Consume Requirements & Threat Model**: Read the task scope, `threat_model.md`, and `CONTEXT.md` for functional requirements and security acceptance criteria.
2. **Author Test Cases**:
- **Functional Happy Path**: Test validating standard user workflows and expected output payloads.
- **Functional Edge Cases**: Test missing optional/required parameters, boundary limits, and unexpected data types.
- **Authentication Boundary**: Assert requests without valid credentials return `401 Unauthorized`.
- **Authorization Boundary**: Assert requests with insufficient role/scope return `403 Forbidden`.
- **Input Validation**: Assert malformed, oversized, or un-whitelisted data returns `400 Bad Request`.
- **Exploit Payloads**: Assert dangerous inputs (SQLi, path traversal `../../`, XSS) are rejected cleanly.
3. **Execute & Verify RED**:
- Run the project's test command (e.g., `pytest`, `python3 -m unittest discover -s tests`).
- **Requirement**: Confirm the tests fail due to the expected missing feature logic/boundary assertion and not due to a syntax or import error.
4. **Multi-Finding Handling**:
- When remediating multiple scanner findings, write and verify one boundary test for one finding at a time before proceeding to defensive implementation.
۳. defensive-developer (دوره C)
.agents/skills/defensive-developer/SKILL.md:
---
name: defensive-developer
description: Implements clean, maintainable production code to deliver features and satisfy functional and security test assertions in Phase C GREEN. Use when writing minimal, modular production code to turn failing RED tests GREEN, applying input validation allow-lists, enforcing explicit caller authorization, and using parameterized sinks and least-privilege payloads. Do not use for authoring initial tests, performing initial threat modeling, or running post-implementation security scans.
---
# Feature Implementation & Defensive Developer Skill (Phase C: GREEN Phase)
## Overview
Implement clean, modular production code that delivers the requested feature or bug fix and satisfies all functional, edge-case, and security assertions from Phase B while adhering to defensive design principles and project conventions in `CONTEXT.md`.
## Three Defensive Pillars
1. **Simple Input Validation**:
- Enforce type, size, and strict allow-list validation on all incoming data.
- Prefer structured parsing libraries (`pydantic`, `urllib.parse`) over complex regex which may be vulnerable to ReDoS.
2. **Explicit Authorization**:
- Validate caller identity and match required permissions before invoking business logic.
3. **Least Privilege & Safe Operations**:
- Parameterize all SQL/database queries.
- Use canonical path checks (`os.path.realpath`) with prefix boundary validation.
- Return only the minimal data payload required by the client.
- Mask credentials, PII, and omit internal stack traces in error messages.
## Execution Sequence
1. **Inspect Failing Tests & Rules**: Review the functional requirements, failing tests from Phase B, and conventions in `CONTEXT.md`.
2. **Author Clean Production Code**:
- Implement the business logic and algorithms required to satisfy the functional feature requirements.
- Apply defensive patterns (e.g. `utils.security.resolve_safe_path`, parameterized SQL statements, `pydantic` schemas).
3. **Confirm GREEN State**:
- Run the project test suite.
- Verify that all functional and security tests pass cleanly without errors.
4. **Multi-Finding Handling**:
- When remediating multiple scanner findings, apply the minimal fix for the current failing boundary test, confirm GREEN, then proceed to the next finding's test-fix cycle.
۴. local-refactor-scanner (دوره D)
.agents/skills/local-refactor-scanner/SKILL.md:
---
name: local-refactor-scanner
description: Refactors code for quality and maintainability, executes full test suite regression passes, and runs local deterministic security and lint scans in Phase D REFACTOR. Use when cleaning up code structure and eliminating duplication after tests pass, running local linters and fast offline scanners for secrets or dependencies, executing full regression test suites, and performing guided code reviews. Do not use for implementing initial feature logic, writing failing test-first suites, or modifying architectural threat models.
---
# Code Refactoring, Quality & Local Scanner Skill (Phase D: REFACTOR Phase)
## Overview
Refactor implementation for clean code structure, modularity, and maintainability while ensuring 100% passing test regressions and blocking pattern-based security flaws locally prior to commit.
## Verification Guardrails
1. **Code Quality & Refactoring**:
- Clean up boilerplate, eliminate dead code, and centralize common utilities.
- Improve variable naming, modularity, and type annotations without altering verified behavior.
2. **Deterministic Scans (Fast & Offline)**:
- **Secrets**: Check diffs for plaintext credentials, tokens, or private keys.
- **Dependencies**: Flag unpinned dependencies or known CVEs in new packages.
- **Rules-Based SAST**: Run local SAST rules on modified files (`semgrep scan --config auto --json` or `cm find`).
3. **Guided AI Review**:
- Audit architecture and design issues that static tools miss.
- Review business logic and edge cases for bypasses or regression risks.
4. **Small Diffs & Regression QA**:
- Run the complete project test suite to verify zero regressions across existing and new tests.
- Ensure the diff contains only surgical changes directly related to the task scope.
## Execution Sequence
1. Review the git diff of modified files (`git diff`).
2. Refactor code for clarity, maintainability, and helper reuse.
3. Run local linters and security scanners on changed files.
4. Run the full test suite to guarantee 100% passing tests.
5. **Continuous Evolution**: Capture new conventions in `CONTEXT.md` and suggest/apply updates to `SKILL.md` instructions via `skill-evolution-updater` to permanently prevent recurrence of issues.
۵. skill-evolution-updater (تکامل مداوم)
.agents/skills/skill-evolution-updater/SKILL.md:
---
name: skill-evolution-updater
description: Extracts systemic conventions from resolved bugs, patterns, and refactors to update CONTEXT.md and agent skills for continuous evolution. Use when capturing durable coding rules, architectural conventions, or recurring fix patterns into CONTEXT.md after a task or bug fix, updating skill instructions to prevent recurrence of errors, and logging gate findings to findings-log.ndjson. Do not use for writing feature code, authoring unit tests, or running pre-push scanner pipelines.
---
# Skill & Conventions Evolution Updater (Continuous Evolution)
## Overview
Ensure the development team and agent fleet continuously learn from local fixes, architecture decisions, and refactoring patterns so that systemic quality and security standards are retained permanently.
## Continuous Feedback Mechanism
```
+-----------------------------------------------------------------+
| CONTINUOUS FEEDBACK LOOP |
| |
| 1. Local Fix / Feature Verified (Refactor Phase) |
| v |
| 2. Systemic Lesson Extracted (Best practices & conventions) |
| v |
| 3. Feed Back to Shared Specs (Update SKILL.md/CONTEXT.md) |
| v |
| 4. Context Seeding (All future agents inherit rules upfront) |
+-----------------------------------------------------------------+
```
## Execution Sequence
1. **Analyze Remediation Diff**: Review the code change or bug fix just completed.
2. **Extract the Systemic Rule**:
- Formulate an actionable, project-specific rule.
- Example: *"When implementing redirects, always use `utils.security.safe_redirect()` with allow-listed domains."*
- Example: *"All JSON endpoints must validate request body using Pydantic schemas."*
3. **Update Shared Specifications**:
- **Update `CONTEXT.md`**: Append the rule under `## 4. Continuous Evolution: Auto-Evolved Conventions`.
- **Update Skills (if applicable)**: If a general coding anti-pattern or QA procedure was refined, update the relevant `SKILL.md`.
4. **Persist Insight**: Append the raw structured event to `.security-gate/findings-log.ndjson` for audit traceability.
۶. history-context-seeder (آمادهسازی)
.agents/skills/history-context-seeder/SKILL.md:
---
name: history-context-seeder
description: Analyzes repository Git history for past bug fixes, architectural conventions, and security patterns to seed CONTEXT.md on onboarding. Use when first adopting the framework in an existing repository, mining historical commits and bug fixes for recurring risk areas, or populating the initial CONTEXT.md baseline with established conventions and helpers. Do not use for routine feature development, authoring test suites, or running the inner TDD loop on active tasks.
---
# History & Architectural Context Seeder Skill (Repository Onboarding)
## Overview
Analyzes the repository's Git history and past fix commits to extract recurring bug patterns, architectural conventions, and security patterns, seeding `CONTEXT.md` during initial repository onboarding.
## Execution Sequence
1. **Analyze Git Log**:
- Inspect commits touching bug fixes, refactors, and sensitive modules:
`git log --grep="fix\|bug\|refactor\|vuln\|security\|patch" -n 50 --oneline`
2. **Extract Historical Lessons**:
- Identify which files and modules have historically been prone to bugs or regressions.
- Extract past patterns and architectural conventions established by maintainers.
3. **Seed `CONTEXT.md`**:
- Populate `CONTEXT.md` with known architectural risk areas, sensitive directories, approved helpers, and custom project conventions.
از این مهارت در آزمایشگاهها استفاده نخواهید کرد زیرا CONTEXT.md ازقبل وجود دارد، اما این همان مهارتی است که وقتی چارچوب را به مخزنی با سالها سابقه و بدون قراردادهای مکتوب میآورید، باید به آن مراجعه کنید.
۶. درحال پیکربندی کردن Antigravity Hook
.agents/hooks.json به Antigravity میگوید که قبلاز هر فرمان پایانه که عامل اجرا میکند، دروازه امنیتی را اجرا کند:
{
"security-gate": {
"PreToolUse": [
{
"matcher": "run_command|.*:run_command|run_shell_command|Bash",
"hooks": [
{
"type": "command",
"command": "bash -c 'if [ -x ./security_gate_hook.sh ]; then exec ./security_gate_hook.sh; else exec ./.agents/security_gate_hook.sh; fi'",
"timeout": 120
}
]
}
]
}
}
چند جزئیات درباره این فایل، طراحی دستورگانی را که راهاندازی میکند توضیح میدهد:
matcherعبارت باقاعدهای برای نام ابزارها است، نه نوشتار فرمان.PreToolUseپیشاز اجرای ابزار فعال میشود و تطبیقدهنده تصمیم میگیرد کدام ابزارها اجرا شوند. run_commandابزار پایانه Antigravity است؛ گزینههای دیگر شامل متغیرهای فضای نام افزونه و دیگر پلاتفرمهای عامل است که این فایلها را همرسانی میکنند. مطابقتدهندهای مثلgit push*هرگز فعال نمیشود چون هیچ ابزاری این نام را ندارد. فیلتر کردن فرمان واقعی در داخل دستورگان انجام میشود.- قلاب فراخوانی ابزار را در ورودی استاندارد دریافت میکند. Antigravity پایهبار JSON را مانند
{"toolCall": {"name": "run_command", "args": {"CommandLine": "git push origin main"}}, ...}لولهکشی میکند. اسکریپت.toolCall.args.CommandLineرا میخواند و بلافاصله با تصمیم مجاز برای هر چیزی کهgit pushنیست خارج میشود. - دایرکتوری کار دایرکتوریای است که حاوی
hooks.jsonاست، بنابراین قلاب در داخل.agents/شروع میشود. پوشانندهbash -c 'if [ -x ./security_gate_hook.sh ] ...'هم آن مورد را مدیریت میکند و هم از ریشه مخزن راهاندازی میشود. سپس دستورگان قبلاز انجام هر کاری بهgit rev-parse --show-toplevelcdمیشود. - اسکریپت در خروجی استاندارد با JSON پاسخ میدهد.
{"decision": "allow"}اجازه میدهد فرمان اصلی اجرا شود.{"decision": "deny", "reason": "..."}آن را مسدود میکند و دلیل آن را به نماینده نشان میدهد. این چارچوب همچنین یک مقدار بولیallow_toolرا برای سازگاری با قراردادهای قلاب قدیمیتر صادر میکند. - قلابها بهصورت همزمان اجرا میشوند و حلقه عامل را تا زمانی که تمام شوند یا به
timeoutبرسند (به ثانیه؛ اگر حذف شود، پیشفرض ۳۰ است) مسدود میکنند.
فرم -i.bak با هر دو GNU و BSD (macOS) sed کار میکند:
sed -i.bak 's/"timeout": 120/"timeout": 900/' .agents/hooks.json && rm .agents/hooks.json.bak
۷. نحوه عملکرد قلاب دروازه امنیتی
security_gate_hook.sh یک نقطه ورودی کوچک است که سه ماژول را از .agents/lib/ تأمین میکند:
واحد | نقش |
| پیشفرضهای پیکربندی، برونداد |
| مرحله ۱. اسکن قطعی اختیاری با Semgrep. اگر |
| مرحله ۲. اسکن معنایی با |
مرحله ۱: تصمیم بگیرید که آیا این یک فشار است یا نه
نقطه ورودی فرمان را از بار داده stdin استخراج میکند و آن را دربرابر یک عبارت باقاعده که git push را در شکلهای رایج آن (git -C /repo push، cd x && git push، sudo git push) تشخیص میدهد آزمایش میکند، درحالیکه نوشتار نقلقولشده مانند git commit -m "before git push" را نادیده میگیرد. هر چیزی که فشار نباشد بلافاصله مجاز است:
CMD_TO_CHECK=$(printf '%s\n' "$STDIN_INPUT" | jq -r '
.toolCall?.args?.CommandLine? //
.toolCall?.args?.command? //
.tool_input?.command? //
.CommandLine? //
.command? //
empty
')
...
if ! is_git_push_command "$CMD_TO_CHECK"; then
allow
fi
مرحله ۲: انتخاب اسکنرها
SECURITY_GATE_SCANNER خط لوله را انتخاب میکند. گزینه پیشفرض، auto، هرکدام از Semgrep و CodeMender را که نصب شده باشد بهترتیب اجرا میکند:
case "$SCANNER" in
codemender|cm) run_codemender_gate false ;;
semgrep) run_semgrep_gate false ;;
auto|pipeline|"")
command -v semgrep >/dev/null && run_semgrep_gate true
command -v cm >/dev/null && run_codemender_gate true
allow ;;
esac
وقتی «مرحله ۱» مشکلات مسدودکننده را در حالت خط لوله پیدا میکند، خودش آنها را رد نمیکند؛ بلکه آنها را در یک فایل موقت مینویسد که «مرحله ۲» آن را برمیدارد، بنابراین CodeMender تصمیم نهایی را میگیرد.
مرحله ۳: مرحله CodeMender
run_codemender_gate در engine_codemender.sh کارهای زیر را بهترتیب انجام میدهد:
- یافتن فایلهای تغییریافته با
git diff --name-only origin/main(بازگشت بهHEAD~1). عدم تغییر بهمعنای مجاز بودن است. - هر فایل را با
cm find "$file" -y --bypass-warningاسکن کنید، سپس همه چیز را باcm report --format jsonبرگردانید. اگرcm reportناموفق باشد یا JSON نامعتبر برگرداند، این یک خطای اسکن است، نه نتیجهای تمیز. - فیلتر کردن به یافتههایی که وضعیتشان
OPENیاREOPENEDاست وfile_pathآنها با یکی از فایلهای تغییریافته تمام میشود. یافتههایی که قبلاً در «مبانی CodeMender CLI» اصلاح یا رد کردهاید نادیده گرفته میشوند. - هر یافته را طبقهبندی کنید. شدت در سطح
SECURITY_GATE_BLOCK_SEVERITYیا بالاتر (پیشفرضHIGH) مسدودکننده است؛ هر چیزی کمتر از آن مشاورهای است، ثبت و چاپ میشود، اما ارسال را متوقف نمیکند. - اگر چیزی مسدود نمیکند، مجاز شود. اگر یافتهای که ارسال قبلی را مسدود کرده بود اکنون برطرف شده باشد، دروازه آن را بهعنوان
FIXEDثبت میکند، قراردادی را بهCONTEXT.mdتحت## 4. Continuous Evolutionاضافه میکند، و آن تغییر را اعمال میکند. - تعداد تلاشها برای هر یافته مسدودکننده را با خواندن گزارش ممیزی خودش میشمارد. هر رد کردن یک تلاش محسوب میشود. در تلاشهای ۱ تا
SECURITY_GATE_MAX_RETRIES(پیشفرض ۳)، دروازهDENIED_TO_AGENTرا ثبت میکند و یافته را به پیام رد اضافه میکند. - پساز مصرف بودجه، ارجاع دهید. در چهارمین تلاش برای همان یافته، دروازه
cm verifyرا اجرا میکند. اگر یافته قابلسوءاستفاده نباشد (کد خروج ۱ یا وضعیتDISMISSED)، به توصیه تنزل مییابد. اگر تأیید شود یاcm verifyازکار بیفتد، دروازهBLOCKEDرا ثبت میکند و با درخواست بازبینی انسانی آن را رد میکند. - رد کردن با دستورالعمل. اگر هریک از یافتهها همچنان قابلاجرا باشد، دروازه این دلیل را به نماینده برمیگرداند:
Security Gate blocked push (1 unresolved finding(s)).
Action Required: Execute the Secure TDD Loop sequentially for each finding:
For each finding below (one at a time):
1. Invoke 'security-test-writer' to author one failing boundary test in tests/ (assert RED).
2. Invoke 'defensive-developer' to apply the minimal defensive fix (assert GREEN).
3. Run the local test to confirm it passes before moving to the next finding.
Once all findings are resolved, run the full regression test suite (python3 -m unittest discover -s tests) and retry 'git push'.
Open Findings:
- [80bdddd6-...] (CRITICAL) in /home/you/codemender-lab/sample_app/data_service.py (Attempt 1/3): OS Command Injection in ping_host endpoint
این انتقال بین قلاب و مهارتها است. قلاب cm fix را فراخوانی نمیکند. مهارتهایی را که عامل باید استفاده کند نام میبرد، عامل اصلاحیه اول-آزمایش را انجام میدهد، و git push بعدی دروازه را دوباره اجرا میکند.
مرجع پیکربندی
همه تنظیمات متغیرهای محیطی با پیشفرضهای تنظیمشده در gate_common.sh هستند:
متغیر | پیشفرض | جلوه |
|
| |
|
| پایینترین شدت که مسدود میکند. |
|
| موارد ردشده بهازای هر یافته قبلاز مشورت با |
|
|
|
|
| فرمان آزمایشی نقلشده در پیامهای رد کردن و پیامهای ثبت. |
|
| افزودن قراردادهای تأییدشده به |
|
| گزارش ممیزی فقط افزودنی. |
| (خالی) | فرمان اختیاری که هر رویداد دروازه را بهصورت JSON در ورودی استاندارد دریافت میکند. |
۸. درحال درستیسنجی Hook Offline
قبلاز اینکه دروازه با cm واقعی تماس برقرار کند، مطمئن شوید که با شبیهسازیها بهدرستی رفتار میکند. چارچوب مجموعه دادههای تستی را با باینریهای جعلی cm و semgrep ارسال میکند که مسیرهای مجاز، مشاورهای، رد، خطا، و تشدید را پوشش میدهد:
bash .agents/tests/run_tests.sh
اجرا چند ثانیه طول میکشد و با این پیام بهپایان میرسد:
-- test_pipeline_tools_missing_passes_smoothly
-- test_skills_frontmatter_valid
60 passed, 0 failed
آخرین آزمایش همچنین فرانتمتر هر مهارت را تحت .agents/skills/ اعتبارسنجی میکند، بنابراین این فرمان برای اجرای مجدد پساز ویرایش SKILL.md است.
سپس، آنچه را Antigravity برای فرمانی که ارسال نیست میفرستد شبیهسازی کنید. اسکریپت باید بدون لمس کردن هیچ اسکنری به allow پاسخ دهد:
echo '{"toolCall":{"name":"run_command","args":{"CommandLine":"git status"}}}' \
| bash .agents/security_gate_hook.sh
{"allow_tool": true, "decision": "allow"}
اکنون روانهسازی بدون تغییرات محلی را درمقابل origin/main شبیهسازی کنید. چون هنوز ریموتی وجود ندارد، دروازه به HEAD~1 برمیگردد و فایلهای آخرین ثبت شما را اسکن میکند. برای اینکه این مرحله را بهصورت آفلاین نگه دارید، آن را به سمت cm و semgrep ساختگی بگیرید:
echo '{"toolCall":{"name":"run_command","args":{"CommandLine":"git push origin main"}}}' \
| PATH="$PWD/.agents/tests/mocks:$PATH" bash .agents/security_gate_hook.sh
Stage 1: Running Deterministic AST Scan (semgrep) on: sample_app/data_service.py ...
Deterministic scan clean. No AST vulnerabilities found.
Stage 2: Running Semantic Analysis & Verification (CodeMender)...
No blocking vulnerabilities detected. Code verified clean.
{"allow_tool": true, "decision": "allow"}
هر دو مرحله اجرا شد زیرا دایرکتوری ساختگی حاوی semgrep جعلی و همچنین cm جعلی است. پیامهای پیشرفت به stderr میروند و فقط تصمیم JSON به stdout میرود، که به Antigravity اجازه میدهد نتیجه را تجزیه کند.
درنهایت، فایلهای چارچوب را ثبت کنید تا با مخزن منتقل شوند:
git add -A && git commit -m "Add Secure TDD skills, rule, and security gate hook"
۹. درحال باز کردن Workspace در Antigravity
~/codemender-lab را بهعنوان پوشه در Antigravity باز کنید. پساز بار شدن، عامل:
- قانون
secure_tdd_workflowدر هر نوبت. - شش مهارت دردسترس درصورت درخواست.
-
security-gatehook درrun_commandثبت شد.
یک راه سریع برای تأیید اینکه مهارتها قابلمشاهده هستند این است که در مکالمهای جدید از نماینده بپرسید: «کدام مهارتهای فضای کاری را دردسترس داری و هرکدام چه کاری انجام میدهند؟» باید نام این شش مورد را فهرست کند.
اجازهها
خود قلاب توسط Antigravity راهاندازی میشود، نه توسط نماینده، بنابراین از پیاموارههای اجازه ابزار عبور نمیکند. فرمانهای خود عامل این کار را انجام میدهند. درطول کارگاه کدنویسی بعدی، منتظر پیاموارههای تأیید برای فرمان آزمایشی، عملیات git، و هر فرمان cm که عامل تصمیم میگیرد مستقیماً اجرا کند باشید. وقتی از شما خواسته شد، آنها را تأیید کنید؛ اگر Antigravity پیشنهاد داد که تصمیم را برای پیشوند فرمان بهخاطر بسپارد، پذیرفتن آن باعث میشود که درطول حلقه دوباره از شما خواسته نشود.
چه اتفاقی در git push میافتد
- عامل ابزار پایانه خود را با
git push origin mainفراخوانی میکند. - Antigravity
run_commandرا باhooks.jsonمطابقت میدهد وsecurity_gate_hook.shرا با فراخوانی ابزار در ورودی استاندارد اجرا میکند. - اسکریپت ارسال را تشخیص میدهد، فایلهای تغییریافته را پیدا میکند، آنها را با
cm findاسکن میکند، وcm reportرا میخواند. - اگر چیزی مسدود نکند،
{"decision": "allow"}را چاپ میکند و ارسال ادامه مییابد. - اگر یافتهها مسدود شود،
{"decision": "deny", "reason": "..."}را چاپ میکند. ارسال انجام نمیشود، نماینده دلیل آن را میبیند، و قانون همیشه روشن بهعلاوه مهارتهای نامگذاریشده به آن میگوید که در مرحله بعد چه کاری انجام دهد: یک آزمایش ناموفق، یک اصلاح حداقلی، اجرای مجدد مجموعه، ارسال مجدد.
تبریک! codelab مربوط به CodeMender Skills & Hooks for Antigravity را تکمیل کردهاید. در codelab بعدی، درخواست ویژگی را به عامل میدهید و اجرای این حلقه را از ابتدا تا انتها، از مدل تهدید تا ارسال که از دروازه عبور میکند، تماشا میکنید.