CodeMender 技能和 Antigravity 钩子

1. 简介

在此 Codelab 中,您将配置一个 AI 编码智能体 (Antigravity),以便将安全性纳入其正常开发循环,而不是作为单独的审核步骤。您将安装一组智能体技能,这些技能会引导智能体完成“计划 → 红色 → 绿色 → 重构”循环,并安装一个 PreToolUse 钩子,该钩子会拦截 git push,使用 CodeMender 扫描更改的文件,并将所有发现结果返回给智能体,同时指示智能体优先进行测试修复。

这些 Skill 和 Hook 来自开源的 Secure TDD Agent Framework。您需要将这些工具安装到您在“CodeMender CLI 基础知识”中构建的同一 ~/codemender-lab 工作区中。

学习内容

  • Antigravity 如何在 .agents/ 下发现工作区规则、技能和钩子。
  • 六项 Secure 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。
  • 具备基本的 Shell 脚本知识。

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 进行比较,以确定要扫描的文件。如果该 ref 不存在,则会回退到 HEAD~1,这仅涵盖最近的提交。确保您的分支名为 main:

git branch -M main

第 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. 六大智能体技能

每项技能都是一个目录,其中包含一个带有 YAML frontmatter 的 SKILL.md。有两个必填字段:

  • name:一个带连字符的小写标识符。
  • description:技能的功能和使用场景。智能体在决定是否加载完整 skill 时,只会读取此字段,因此下面的每个说明还会指出该 skill 不适用于哪些情况。

技能

阶段

用途

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 钩子

.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。
  • 脚本在 stdout 上以 JSON 格式回答。{"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/ 中获取三个模块:

模块

角色

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. 离线验证钩子

在门控接触到实际 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 规则。
  • 六项技能,随时随地,想学就学。
  • 在 run_command 上注册的 security-gate 钩子。

如需快速确认技能是否可见,请在新的对话中询问智能体:“你有哪些可用的 Workspace 技能?每项技能有什么作用?”应列出这六个名称。

权限

钩子本身由 Antigravity 启动,而不是由智能体启动,因此不会触发工具权限提示。智能体自己的命令需要。在下一个 Codelab 中,您会看到针对测试命令、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”Codelab。在下一个 Codelab 中,您将向代理发出功能请求,并观察此循环端到端运行,从威胁模型到通过关卡的推送。