1. Giới thiệu
Trong lớp học lập trình này, bạn sẽ định cấu hình một tác nhân lập trình AI (Antigravity) để bảo mật là một phần trong vòng lặp phát triển thông thường của tác nhân đó, thay vì là một bước xem xét riêng biệt. Bạn sẽ cài đặt một bộ kỹ năng cho tác nhân để hướng dẫn tác nhân thực hiện chu trình Lập kế hoạch → Đỏ → Xanh lục → Cải tiến, và một hook PreToolUse chặn git push, quét các tệp đã thay đổi bằng CodeMender và chuyển mọi kết quả tìm được cho tác nhân kèm theo hướng dẫn khắc phục theo phương pháp kiểm thử trước.
Các kỹ năng và hook này đến từ Secure TDD Agent Framework nguồn mở. Bạn sẽ cài đặt các công cụ này vào cùng một không gian làm việc ~/codemender-lab mà bạn đã tạo trong phần Kiến thức cơ bản về CodeMender CLI.
Kiến thức bạn sẽ học được
- Cách Antigravity khám phá các quy tắc, kỹ năng và hook của không gian làm việc trong
.agents/. - Vai trò của 6 kỹ năng TDD bảo mật và giai đoạn mà mỗi kỹ năng đảm nhận trong vòng lặp.
- Cách một hook
PreToolUsenhận lệnh gọi công cụ của tác nhân trên stdin và trả về quyết định cho phép/từ chối. - Cách hook cổng bảo mật (
security_gate_hook.sh) chạycm find, phân loại kết quả theo mức độ nghiêm trọng, theo dõi các nỗ lực khắc phục và báo cáo lên cấp cao hơn bằngcm verify. - Cách xác minh toàn bộ quy trình hook khi không có mạng bằng trình quét mô phỏng trước khi trỏ quy trình đó vào
cmthực.
Điều kiện tiên quyết
- Hoàn thành khoá học Kiến thức cơ bản về CodeMender CLI. Phòng thí nghiệm này tiếp tục trong thư mục
~/codemender-labvà sử dụng lạisample_app/,CONTEXT.md, nhật ký git và~/.codemender/config.yaml. - Đã cài đặt Antigravity, có thể mở một thư mục cục bộ dưới dạng không gian làm việc.
- Đã cài đặt
git,jqvàbash. Tập lệnh hook là bash thuần tuý và chạy trên bash 3.2 của macOS cũng như các phiên bản mới hơn. - Môi trường ảo Python từ phần Kiến thức cơ bản về CodeMender CLI (
~/codemender-lab/.venv) đã cài đặt Flask. - Kiến thức cơ bản về tập lệnh shell.
2. Thiết lập Workspace
Bước 1: Quay lại thư mục của phòng thí nghiệm
Tất cả lệnh trong lớp học lập trình này đều chạy từ ~/codemender-lab khi môi trường ảo đang hoạt động:
cd ~/codemender-lab && source .venv/bin/activate
Xác nhận rằng không gian làm việc từ lớp học lập trình trước đó vẫn còn nguyên vẹn và cây làm việc của bạn không có tệp nào chưa được theo dõi:
ls sample_app/data_service.py CONTEXT.md .gitignore
git status --short
git status --short không được in ra gì. Nếu có tệp trong danh sách, hãy cam kết các tệp đó trước khi tiếp tục.
Bước 2: Đặt tên cho nhánh main
Cổng bảo mật sẽ so sánh cây đang hoạt động của bạn với origin/main để quyết định tệp nào cần quét. Nếu tham chiếu đó không tồn tại, thì tham chiếu đó sẽ quay lại HEAD~1, chỉ bao gồm thay đổi gần đây nhất. Đảm bảo nhánh của bạn có tên là main:
git branch -M main
Bước 3: Thêm điểm truy cập bộ kiểm thử
Vòng lặp TDD an toàn yêu cầu tác nhân chạy python3 -m unittest discover -s tests sau mỗi lần khắc phục, vì vậy, không gian làm việc cần có thư mục tests/. Bắt đầu bằng một kiểm thử đặc tính để bộ kiểm thử có nội dung thực tế để chạy:
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
Bạn sẽ thấy Ran 1 test và OK.
Bước 4: Mở rộng .gitignore và cam kết
Thêm các tệp thời gian chạy mà phòng thí nghiệm này tạo ra vào .gitignore, sau đó cam kết đường cơ sở:
printf '.security-gate/\nusers.db\n*.bak\n' >> .gitignore
git add -A && git commit -m "Add test suite entry point for Secure TDD"
3. Cài đặt tệp khung
Kỹ năng, quy tắc, hook và khai thác kiểm thử ngoại tuyến đều nằm trong một thư mục .agents/ duy nhất. Thay vì nhập khoảng 800 dòng bash theo cách thủ công, hãy sao chép khung và sao chép thư mục đó vào không gian làm việc của bạn:
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
Xác nhận bố cục:
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
Đảm bảo điểm truy cập hook có thể thực thi:
chmod +x .agents/security_gate_hook.sh
ls -l .agents/security_gate_hook.sh
Phần còn lại của lớp học lập trình này sẽ hướng dẫn bạn từng bước về những gì bạn vừa cài đặt.
4. Quy tắc quy trình công việc luôn bật
Kỹ năng được tải theo yêu cầu, khi tác nhân quyết định rằng nội dung mô tả của một kỹ năng phù hợp với nhiệm vụ. Cần có một yếu tố nào đó để hướng dẫn tác nhân tiếp cận các công cụ theo đúng thứ tự. Đó là công việc của .agents/rules/secure_tdd_workflow.md. Phần đầu của tệp này đặt trigger: always_on, vì vậy, quy tắc này được đưa vào mọi lượt:
---
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.
Quy tắc này tham chiếu đến CONTEXT.md mà bạn đã tạo trong phần Kiến thức cơ bản về CLI của CodeMender. Cùng một tệp đã hướng cm fix đến quy ước truy vấn có tham số của bạn giờ đây sẽ hướng dẫn việc lập kế hoạch của tác nhân. Mục 6 là quan trọng nhất đối với phòng thí nghiệm này: đây là mục mà tác nhân tuân theo khi cổng bảo mật từ chối một lần đẩy có nhiều kết quả cùng một lúc.
5. 6 kỹ năng của tác nhân
Mỗi kỹ năng là một thư mục chứa SKILL.md có phần siêu dữ liệu ở đầu tệp YAML. Có hai trường bắt buộc:
name: giá trị nhận dạng viết thường, có dấu gạch nối.description: chức năng của kỹ năng và thời điểm nên sử dụng kỹ năng đó. Tác nhân chỉ đọc trường này khi quyết định có tải toàn bộ kỹ năng hay không, vì vậy, mỗi nội dung mô tả bên dưới cũng cho biết kỹ năng đó không dùng cho mục đích gì.
Kỹ năng | Giai đoạn | Mục đích |
| Đáp: Lập kế hoạch | Xác định phạm vi của tính năng, chạy STRIDE, viết |
| B: Màu đỏ | Viết mã kiểm thử chức năng và kiểm thử biên không thành công vì lý do chính đáng. |
| C: Xanh lục | Viết mã tối thiểu để chuyển các kiểm thử sang màu xanh lục, sử dụng các mẫu an toàn. |
| D: Cải tiến | Dọn dẹp, chạy toàn bộ bộ công cụ, chạy trình quét cục bộ, xem xét điểm khác biệt. |
| Liên tục | Ghi lại các quy ước mới trong tệp |
| Android | Khai thác nhật ký git để gieo mầm |
Sau đây là toàn bộ nội dung để bạn có thể thấy cách kết hợp phần mở đầu và hướng dẫn.
1. threat-model-assessor (Giai đoạn 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]
```
2. security-test-writer (Giai đoạn B)
.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.
3. defensive-developer (Giai đoạn 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.
4. local-refactor-scanner (Giai đoạn 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.
5. skill-evolution-updater (Không ngừng phát triển)
.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.
6. history-context-seeder (Giới thiệu)
.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.
Bạn sẽ không sử dụng kỹ năng này trong các phòng thí nghiệm vì CONTEXT.md đã tồn tại, nhưng đây là kỹ năng cần đạt được khi bạn đưa khung vào một kho lưu trữ có nhiều năm lịch sử và không có quy ước bằng văn bản.
6. Đang định cấu hình Antigravity Hook
.agents/hooks.json yêu cầu Antigravity chạy cổng bảo mật trước khi tác nhân thực thi bất kỳ lệnh nào trong Terminal:
{
"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
}
]
}
]
}
}
Một vài thông tin chi tiết về tệp này giải thích thiết kế của tập lệnh mà tệp này khởi chạy:
matcherlà một biểu thức chính quy trên tên công cụ, không phải văn bản lệnh.PreToolUsekích hoạt trước khi một công cụ chạy và trình so khớp sẽ quyết định công cụ nào.run_commandlà công cụ dòng lệnh của Antigravity; các lựa chọn thay thế khác bao gồm các biến thể không gian tên của trình bổ trợ và các nền tảng tác nhân khác dùng chung các tệp này. Trình so khớp nhưgit push*sẽ không bao giờ kích hoạt vì không có công cụ nào có tên như vậy. Việc lọc theo lệnh thực tế diễn ra bên trong tập lệnh.- Hook nhận lệnh gọi công cụ trên stdin. Antigravity truyền tải trọng JSON như
{"toolCall": {"name": "run_command", "args": {"CommandLine": "git push origin main"}}, ...}. Tập lệnh đọc.toolCall.args.CommandLinevà thoát ngay lập tức với quyết định cho phép đối với mọi nội dung không phải làgit push. - Thư mục làm việc là thư mục chứa
hooks.json, vì vậy, hook sẽ bắt đầu bên trong.agents/. Trình bao bọcbash -c 'if [ -x ./security_gate_hook.sh ] ...'xử lý cả trường hợp đó và trường hợp được khởi chạy từ thư mục gốc của kho lưu trữ. Sau đó, tập lệnh sẽcdthànhgit rev-parse --show-topleveltrước khi thực hiện bất kỳ công việc nào. - Tập lệnh trả lời trên stdout bằng JSON.
{"decision": "allow"}cho phép chạy lệnh ban đầu.{"decision": "deny", "reason": "..."}sẽ chặn và cho nhân viên hỗ trợ biết lý do. Khung này cũng phát ra một booleanallow_toolđể tương thích với các hợp đồng hook cũ. - Hook chạy đồng bộ và chặn vòng lặp của tác nhân cho đến khi hoàn tất hoặc đạt đến
timeout(tính bằng giây; mặc định là 30 nếu bị bỏ qua).
Biểu mẫu -i.bak hoạt động với cả GNU và BSD (macOS) sed:
sed -i.bak 's/"timeout": 120/"timeout": 900/' .agents/hooks.json && rm .agents/hooks.json.bak
7. Cách hoạt động của móc cổng an ninh
security_gate_hook.sh là một điểm truy cập mỏng, lấy 3 mô-đun từ .agents/lib/:
Mô-đun | Vai trò |
| Giá trị mặc định của cấu hình, kết quả |
| Giai đoạn 1. Quét tất định không bắt buộc bằng Semgrep. Bỏ qua nếu |
| Giai đoạn 2. Quét ngữ nghĩa bằng |
Bước 1: Quyết định xem đây có phải là thông báo đẩy hay không
Điểm truy cập sẽ trích xuất lệnh từ tải trọng stdin và kiểm tra lệnh đó dựa trên một biểu thức chính quy nhận dạng git push ở các dạng phổ biến (git -C /repo push, cd x && git push, sudo git push) trong khi bỏ qua văn bản được trích dẫn như git commit -m "before git push". Mọi thứ không phải là lệnh đẩy đều được cho phép ngay lập tức:
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
Bước 2: Chọn máy quét
SECURITY_GATE_SCANNER chọn quy trình. Theo mặc định, auto sẽ chạy bất kỳ công cụ nào được cài đặt trong số Semgrep và CodeMender, theo thứ tự sau:
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
Khi Giai đoạn 1 phát hiện các vấn đề gây chặn ở chế độ quy trình, giai đoạn này sẽ không tự từ chối mà ghi các vấn đề đó vào một tệp tạm thời để Giai đoạn 2 xử lý, nhờ đó CodeMender có thể đưa ra quyết định cuối cùng.
Bước 3: Giai đoạn CodeMender
run_codemender_gate trong engine_codemender.sh thực hiện những việc sau, theo thứ tự:
- Tìm các tệp đã thay đổi bằng
git diff --name-only origin/main(quay lạiHEAD~1). Không có thay đổi nghĩa là cho phép. - Quét từng tệp bằng
cm find "$file" -y --bypass-warning, sau đó kéo mọi thứ trở lại bằngcm report --format json. Nếucm reportkhông thành công hoặc trả về JSON không hợp lệ, thì đó là lỗi quét chứ không phải kết quả sạch. - Lọc để tìm những kết quả có trạng thái là
OPENhoặcREOPENEDvà cófile_pathkết thúc bằng một trong các tệp đã thay đổi. Những kết quả mà bạn đã khắc phục hoặc loại bỏ trong phần Kiến thức cơ bản về CodeMender CLI sẽ bị bỏ qua. - Phân loại từng kết quả tìm được. Mức độ nghiêm trọng bằng hoặc cao hơn
SECURITY_GATE_BLOCK_SEVERITY(mặc định làHIGH) sẽ chặn; mọi mức độ thấp hơn đều là cảnh báo, được ghi lại và in ra, nhưng không dừng quá trình đẩy. - Cho phép nếu không có gì chặn. Nếu một kết quả chặn lệnh đẩy trước đó hiện đã biến mất, thì cổng sẽ ghi lại kết quả đó dưới dạng
FIXED, thêm một quy ước vàoCONTEXT.mdtrong## 4. Continuous Evolutionvà cam kết thay đổi đó. - Đếm số lần thử cho mỗi kết quả chặn bằng cách đọc nhật ký kiểm tra của chính kết quả đó. Mỗi lần từ chối được tính là một lần thử. Trong các lần thử từ 1 đến
SECURITY_GATE_MAX_RETRIES(mặc định là 3), cổng sẽ ghi nhật kýDENIED_TO_AGENTvà thêm kết quả tìm được vào thông báo từ chối. - Chuyển lên cấp trên sau khi ngân sách đã được chi tiêu. Trong lần thử thứ tư cho cùng một kết quả, cổng sẽ chạy
cm verify. Nếu không thể khai thác kết quả phát hiện (mã thoát 1 hoặc trạng tháiDISMISSED), thì kết quả đó sẽ bị hạ cấp xuống mức tư vấn. Nếu được xác nhận hoặccm verifygặp sự cố, cổng sẽ ghi nhật kýBLOCKEDvà từ chối kèm theo yêu cầu đánh giá thủ công. - Từ chối kèm theo hướng dẫn. Nếu có bất kỳ kết quả nào vẫn cần xử lý, cổng sẽ trả về lý do này cho tác nhân:
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
Đây là phần chuyển tiếp giữa đoạn mở đầu và kỹ năng. Hook không gọi cm fix. Tác nhân này nêu tên các kỹ năng mà tác nhân nên sử dụng, tác nhân thực hiện bản sửa lỗi kiểm thử trước và git push tiếp theo sẽ chạy lại cổng.
Thông tin tham khảo về cấu hình
Tất cả chế độ cài đặt đều là biến môi trường có giá trị mặc định được đặt trong gate_common.sh:
Biến | Mặc định | Hiệu quả |
|
|
|
|
| Mức độ nghiêm trọng thấp nhất mà bạn muốn chặn. |
|
| Số lượt từ chối cho mỗi kết quả trước khi tham khảo ý kiến của |
|
|
|
|
| Lệnh kiểm thử được trích dẫn trong lời nhắc từ chối và thông báo cam kết. |
|
| Thêm quy ước đã xác minh vào |
|
| Nhật ký kiểm tra chỉ cho phép thêm. |
| (trống) | Lệnh không bắt buộc nhận từng sự kiện cổng dưới dạng JSON trên stdin. |
8. Xác minh Hook Offline
Trước khi cổng chạm vào cm thực, hãy xác nhận rằng cổng hoạt động chính xác với mô phỏng. Khung này cung cấp một khai thác kiểm thử có tệp nhị phân cm và semgrep giả mạo, bao gồm các đường dẫn cho phép, tư vấn, từ chối, lỗi và báo cáo:
bash .agents/tests/run_tests.sh
Quá trình chạy mất vài giây và kết thúc bằng:
-- test_pipeline_tools_missing_passes_smoothly
-- test_skills_frontmatter_valid
60 passed, 0 failed
Thử nghiệm cuối cùng cũng xác thực phần đầu của mọi kỹ năng trong .agents/skills/, vì vậy, đây là lệnh cần chạy lại sau khi chỉnh sửa SKILL.md.
Tiếp theo, hãy mô phỏng nội dung Antigravity gửi cho một lệnh không phải là lệnh đẩy. Tập lệnh phải trả lời allow mà không chạm vào bất kỳ máy quét nào:
echo '{"toolCall":{"name":"run_command","args":{"CommandLine":"git status"}}}' \
| bash .agents/security_gate_hook.sh
{"allow_tool": true, "decision": "allow"}
Bây giờ, hãy mô phỏng một lệnh đẩy không có thay đổi cục bộ đối với origin/main. Vì chưa có kho lưu trữ từ xa nên cổng sẽ quay lại HEAD~1 và quét các tệp trong lần xác nhận gần đây nhất của bạn. Để giữ bước này ở chế độ ngoại tuyến, hãy trỏ bước này vào cm và semgrep mô phỏng:
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"}
Cả hai giai đoạn đều chạy vì thư mục mô phỏng chứa semgrep giả cũng như cm giả. Thông báo tiến trình sẽ được gửi đến stderr và chỉ có quyết định JSON được gửi đến stdout, nhờ đó Antigravity có thể phân tích cú pháp kết quả.
Cuối cùng, hãy cam kết các tệp khung để chúng đi kèm với kho lưu trữ:
git add -A && git commit -m "Add Secure TDD skills, rule, and security gate hook"
9. Mở Workspace trong Antigravity
Mở ~/codemender-lab dưới dạng thư mục trong Antigravity. Sau khi được tải, tác nhân sẽ có:
- Quy tắc
secure_tdd_workflowtrong mọi lượt. - Sáu kỹ năng có sẵn theo yêu cầu.
- Hook
security-gateđã đăng ký trênrun_command.
Một cách nhanh chóng để xác nhận các kỹ năng có hiển thị hay không là hỏi nhân viên hỗ trợ trong một cuộc trò chuyện mới: "Bạn có những kỹ năng nào trong không gian làm việc và mỗi kỹ năng có tác dụng gì?" Bạn nên nêu tên 6 người này.
Quyền
Bản thân hook được Antigravity khởi chạy chứ không phải tác nhân, vì vậy, hook không trải qua các lời nhắc về quyền của công cụ. Các lệnh của chính tác nhân thì có. Trong lớp học lập trình tiếp theo, bạn sẽ thấy lời nhắc phê duyệt cho lệnh kiểm thử, các thao tác git và mọi lệnh cm mà tác nhân quyết định chạy trực tiếp. Phê duyệt khi được yêu cầu; nếu Antigravity đề nghị ghi nhớ quyết định cho một tiền tố lệnh, thì việc chấp nhận đề nghị đó sẽ giúp tránh việc nhắc lại trong suốt vòng lặp.
Điều gì xảy ra vào ngày git push
- Tác nhân gọi công cụ terminal bằng
git push origin main. - Antigravity so khớp
run_commandvớihooks.jsonvà chạysecurity_gate_hook.shbằng lệnh gọi công cụ trên stdin. - Tập lệnh này nhận dạng một lệnh đẩy, tìm các tệp đã thay đổi, quét các tệp đó bằng
cm findvà đọccm report. - Nếu không có gì chặn, tập lệnh này sẽ in
{"decision": "allow"}và quá trình đẩy sẽ tiếp tục. - Nếu kết quả là chặn, tập lệnh này sẽ in
{"decision": "deny", "reason": "..."}. Quá trình đẩy không chạy, tác nhân nhìn thấy lý do và quy tắc luôn bật cộng với các kỹ năng được đặt tên sẽ cho tác nhân biết việc cần làm tiếp theo: một kiểm thử không thành công, một bản sửa lỗi tối thiểu, chạy lại bộ kiểm thử, đẩy lại.
Xin chúc mừng! Bạn đã hoàn tất lớp học lập trình về Kỹ năng và Hook của CodeMender cho Antigravity. Trong lớp học lập trình tiếp theo, bạn sẽ đưa ra yêu cầu về tính năng cho tác nhân và xem vòng lặp này chạy từ đầu đến cuối, từ mô hình mối đe doạ đến một lệnh đẩy vượt qua cổng.