Antigravity 的 CodeMender 技能和掛鉤

1. 簡介

在本程式碼實驗室中,您將設定 AI 程式碼代理 (Antigravity),將安全性納入一般開發循環,而非獨立的審查步驟。您將安裝一組代理技能,引導代理完成「計畫」→「紅色」→「綠色」→「重構」循環,並安裝 PreToolUse 鉤子,攔截 git push,使用 CodeMender 掃描變更的檔案,並將任何發現結果交回代理,並指示代理先測試再修正。

技能和掛鉤來自開放原始碼 Secure TDD Agent Framework。您會將這些工具安裝到「CodeMender CLI 基本概念」中建立的 ~/codemender-lab 工作區。

學習目標

  • Antigravity 如何在 .agents/ 下探索工作區規則、技能和掛鉤。
  • 六項安全 TDD 技能的作用,以及各項技能負責的迴圈階段。
  • PreToolUse 鉤子如何透過 stdin 接收代理的工具呼叫,並傳回允許/拒絕決策。
  • 安全閘道掛鉤 (security_gate_hook.sh) 如何執行 cm find、依嚴重程度分類發現項目、追蹤修正嘗試,以及透過 cm verify 提報問題。
  • 如何使用模擬掃描器離線驗證整個掛鉤管道,再指向實際的 cm。

必要條件

  • 完成 CodeMender CLI 基本概念。本實驗室會繼續在 ~/codemender-lab 目錄中進行,並重複使用其 sample_app/、CONTEXT.md、git 記錄和 ~/.codemender/config.yaml。
  • 已安裝 Antigravity,並能以工作區形式開啟本機資料夾。
  • 已安裝 git、jq 和 bash。掛鉤指令碼是純 bash,可在 macOS 的內建 bash 3.2 和更新版本上執行。
  • CodeMender CLI 基本概念 (~/codemender-lab/.venv) 的 Python 虛擬環境,已安裝 Flask。
  • 具備殼層指令碼的基本知識。

2. Workspace 設定

步驟 1:返回實驗室目錄

本實驗室的所有指令都會在 ~/codemender-lab 中執行,並啟用虛擬環境:

cd ~/codemender-lab && source .venv/bin/activate

確認上一個實驗室的工作區完好無損,且工作樹狀結構乾淨:

ls sample_app/data_service.py CONTEXT.md .gitignore
git status --short

git status --short 不應輸出任何內容。如果列出檔案,請先提交檔案再繼續。

步驟 2:將分支版本命名為 main

安全閘道會比較工作樹狀結構與 origin/main,決定要掃描哪些檔案。如果該參照不存在,則會改用 HEAD~1,這只會涵蓋最近的修訂版本。確認分支版本名稱為 main:

git branch -M main

Step 3:新增測試套件進入點

Secure 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。

步驟 4:擴充 .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"

3. 安裝架構檔案

技能、規則、掛鉤和離線測試控管工具都位於同一個 .agents/ 目錄下。請複製架構並將該目錄複製到工作區,而不是手動輸入大約 800 行 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

本實驗室的其餘部分將逐步介紹您剛才安裝的內容。

4. 全天候運作的工作流程規則

當代理判定技能說明與工作相符時,就會視需求載入技能。必須有某個機制指示代理依正確順序取得這些資料。這就是 .agents/rules/secure_tdd_workflow.md 的工作。frontmatter 設定為 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.

這項規則會參照您在「CodeMender CLI 基本概念」中建立的 CONTEXT.md。先前引導 cm fix 採用參數化查詢慣例的檔案,現在會引導代理規劃。本實驗室最重要的是第 6 項:當安全閘道一次拒絕多個發現項目時,代理會遵循這項指示。

5. 六項代理技能

每項技能都是一個目錄,內含 SKILL.md 和 YAML frontmatter。有兩個必填欄位:

  • name:以連字號分隔的小寫 ID。
  • description:技能的功能和使用時機。代理在決定是否載入完整技能時,只會讀取這個欄位,因此下方各項說明也會指出技能不適用於哪些情況。

技能

階段

目的

threat-model-assessor

A: 規劃

定義功能範圍、執行 STRIDE、編寫 threat_model.md。

security-test-writer

B: 紅色

編寫功能和邊界測試,確保測試失敗的原因正確。

defensive-developer

C: 綠色

使用安全模式,編寫最少的程式碼,讓測試通過。

local-refactor-scanner

D: 重構

清理、執行完整套件、執行本機掃描器、查看差異。

skill-evolution-updater

連續

在 CONTEXT.md 和 SKILL.md 檔案中記錄新慣例。

history-context-seeder

新手上路

挖掘 Git 記錄,在現有存放區中植入 CONTEXT.md。

以下是完整內容,方便您瞭解 frontmatter 和指示如何搭配。

1. 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]
```

2. security-test-writer (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 (階段 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 (階段 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 (持續推陳出新)

.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 (新手上路)

.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 已經存在,因此您不會在實驗室中使用這項技能,但當您將架構帶到具有多年歷史且沒有書面慣例的存放區時,這項技能就會派上用場。

6. 設定 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* 這類比對器不會觸發,因為沒有工具以此命名。實際指令的篩選作業會在指令碼中進行。
  • 掛鉤會透過 stdin 接收工具呼叫。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 ] ...' 包裝函式會處理這種情況,以及從存放區根目錄啟動的情況。接著,指令碼會先 cd 至 git rev-parse --show-toplevel,再執行任何工作。
  • 指令碼會以 JSON 格式在 stdout 上回覆。{"decision": "allow"} 則會執行原始指令。{"decision": "deny", "reason": "..."} 會封鎖該訊息,並向代理顯示原因。架構也會發出 allow_tool 布林值,以便與舊版掛鉤合約相容。
  • 掛鉤會同步執行,並封鎖代理迴圈,直到完成或達到 timeout (以秒為單位,如省略,預設值為 30)。

-i.bak 格式適用於 GNU 和 BSD (macOS) sed:

sed -i.bak 's/"timeout": 120/"timeout": 900/' .agents/hooks.json && rm .agents/hooks.json.bak

7. 安全閘門掛鉤的運作方式

security_gate_hook.sh 是精簡的進入點,可從 .agents/lib/ 取得三個模組:

Module

角色

gate_common.sh

設定預設值、allow/deny 輸出、嚴重性排名、NDJSON 稽核記錄、嘗試次數、修訂和 CONTEXT.md 輔助程式。

engine_semgrep.sh

階段 1:可選用 Semgrep 進行確定性掃描。如果 semgrep 未使用 PATH,則會略過。

engine_codemender.sh

階段 2:使用 cm find 進行語意掃描、分類、追蹤嘗試,以及 cm verify 提報。

步驟 1:判斷是否為推送

進入點會從 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

步驟 2:選擇掃描器

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

當階段 1 在管道模式中發現阻礙問題時,不會自行拒絕,而是會將問題寫入暫存檔案,由階段 2 擷取,因此 CodeMender 擁有最終決定權。

步驟 3:CodeMender 階段

engine_codemender.sh 中的 run_codemender_gate 會依序執行下列操作:

  1. 使用 git diff --name-only origin/main (備用方案為 HEAD~1) 找出變更的檔案。如果沒有變更,則允許。
  2. 使用 cm find "$file" -y --bypass-warning 掃描每個檔案,然後使用 cm report --format json 提取所有內容。如果 cm report 失敗或傳回無效的 JSON,則視為掃描錯誤,而非安全結果。
  3. 篩選狀態為 OPEN 或 REOPENED,且 file_path 結尾為其中一個變更檔案的發現項目。系統會忽略您在「CodeMender CLI 基本概念」中已修正或關閉的發現項目。
  4. 分類各項發現。嚴重程度等於或高於 SECURITY_GATE_BLOCK_SEVERITY (預設為 HIGH) 的問題會遭到封鎖;嚴重程度較低的問題則會記錄、列印並提供建議,但不會停止推送。
  5. 如果沒有任何封鎖設定,則允許。如果先前阻擋推送作業的發現項目已消失,閘道會將其記錄為 FIXED,在 ## 4. Continuous Evolution 下方的 CONTEXT.md 附加慣例,並提交該變更。
  6. 讀取封鎖發現項目的稽核記錄,計算嘗試次數。每次拒絕都算一次嘗試。在第 1 次到第 SECURITY_GATE_MAX_RETRIES 次 (預設為 3 次) 嘗試中,閘道會記錄 DENIED_TO_AGENT,並將發現項目新增至拒絕訊息。
  7. 預算用盡後提報。第四次嘗試時,閘道會執行 cm verify。如果發現項目無法入侵 (結束代碼 1 或狀態 DISMISSED),則會降級為建議。如果確認有問題,或 cm verify 停止運作,閘道會記錄 BLOCKED,並拒絕要求,同時要求人工審查。
  8. 拒絕並提供操作說明。如果仍有可採取行動的發現項目,閘道會向代理程式傳回以下原因:
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:

變數

預設

效果

SECURITY_GATE_SCANNER

auto

auto、codemender (或 cm) 或 semgrep。

SECURITY_GATE_BLOCK_SEVERITY

HIGH

封鎖的最低嚴重性。CRITICAL、HIGH、MEDIUM 或 LOW。

SECURITY_GATE_MAX_RETRIES

3

諮詢 cm verify 前,每項發現項目的拒絕次數。

SECURITY_GATE_ALLOW_ON_ERROR

false

如果掃描器無法執行,true 會允許推送,並將修訂版本標記為 unverified-scan-。

SECURITY_GATE_TEST_CMD

python3 -m unittest discover -s tests

在拒絕提示和修訂訊息中引用測試指令。

SECURITY_GATE_EVOLVE_CONTEXT

true

將已驗證的慣例附加至 CONTEXT.md。

SECURITY_GATE_LOG

.security-gate/findings-log.ndjson

僅限附加的稽核記錄。

SECURITY_GATE_NOTIFY_CMD

(空白)

選用指令,可在 stdin 上以 JSON 格式接收每個閘道事件。

8. 驗證 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/ 下每項技能的 frontmatter,因此編輯 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"

9. 在 Antigravity 開啟工作區

在 Antigravity 中以資料夾形式開啟 ~/codemender-lab。載入後,代理會具備以下特色:

  • 每輪的 secure_tdd_workflow 規則。
  • 六項隨選技能。
  • security-gate 鉤子已在 run_command 註冊。

如要快速確認代理是否能看到技能,請在新的對話中詢問代理:「有哪些可用的工作區技能?各項技能的作用為何?」請列出這六個名稱。

權限

掛鉤本身是由 Antigravity 啟動,而非代理,因此不會顯示工具權限提示。但代理本身的指令會。在下一個程式碼實驗室中,測試指令、git 作業,以及代理決定直接執行的任何 cm 指令,都會出現核准提示。請在系統詢問時核准。如果 Antigravity 提議記住指令前置字元的決定,接受後即可避免在迴圈中重複提示。

git push當天會有什麼變化

  1. 代理會使用 git push origin main 呼叫終端機工具。
  2. Antigravity 會比對 run_command 和 hooks.json,並在 stdin 上執行 security_gate_hook.sh 和工具呼叫。
  3. 指令碼會辨識推送、找出變更的檔案、使用 cm find 掃描檔案,並讀取 cm report。
  4. 如果沒有任何封鎖,系統會輸出 {"decision": "allow"},並繼續推送。
  5. 如果發現項目為封鎖,則會輸出 {"decision": "deny", "reason": "..."}。推送作業不會執行,代理會看到原因,而全天候運作規則和具名技能會指示下一步:一項測試失敗、一項最小修正、重新執行套件、再次推送。

恭喜!您已完成「CodeMender Skills & Hooks for Antigravity」程式碼實驗室。在下一個程式碼實驗室中,您將向代理提出功能要求,並觀察這個迴圈從威脅模型到推送通過閘道的完整執行過程。