Навыки и хуки CodeMender для Antigravity

1. Введение

В этой практической работе вы настроите ИИ-агента для программирования (Antigravity) так, чтобы безопасность была частью его обычного цикла разработки, а не отдельным этапом проверки. Вы установите набор навыков агента, которые проведут его через цикл "Планирование → Красный → Зеленый → Рефакторинг", и хук PreToolUse, который перехватывает git push, сканирует измененные файлы с помощью CodeMender и передает все результаты обратно агенту с инструкциями по их исправлению в первую очередь.

Навыки и хук взяты из Secure TDD Agent Framework с открытым исходным кодом. Вы установите их в ту же рабочую область ~/codemender-lab, которую создали в рамках курса "Основы CodeMender CLI".

Что вы узнаете

  • Как 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 и выполняются в стандартной оболочке bash 3.2 в macOS, а также в более новых версиях.
  • Виртуальная среда Python из практической работы "Основы CodeMender CLI" (~/codemender-lab/.venv) с установленным фреймворком 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

Шаг 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. В его метаданных задано 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, созданный вами в разделе "Основы CLI CodeMender". Тот же файл, который направлял cm fix к вашему соглашению о параметризованных запросах, теперь направляет планирование агента. Для этой лабораторной работы наиболее важен пункт 6: именно ему следует агент, когда шлюз безопасности отклоняет отправку с несколькими результатами одновременно.

5. Шесть навыков агента

Каждый навык – это каталог, содержащий файл SKILL.md с блоком Front Matter в формате YAML. Обязательны два поля:

  • name – идентификатор, написанный строчными буквами через дефис.
  • 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 в существующем хранилище.

Ниже приведен полный текст, чтобы вы могли увидеть, как сочетаются метаданные и инструкции.

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 (Onboarding)

.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.
  • Скрипт отвечает на 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. Определите, является ли это push-уведомлением

Точка входа извлекает команду из полезной нагрузки stdin и проверяет ее на соответствие регулярному выражению, которое распознает git push в его распространенных формах (git -C /repo push, cd x && git push, sudo git push), игнорируя текст в кавычках, например git commit -m "before git push". Все, что не является 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

run_codemender_gate в engine_codemender.sh выполняет следующие действия по порядку:

  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 Basics, игнорируются.
  4. Классифицируйте каждую находку. Уровень серьезности SECURITY_GATE_BLOCK_SEVERITY или выше (по умолчанию HIGH) блокирует отправку. Все, что ниже, регистрируется и выводится на экран, но не останавливает отправку.
  5. Разрешить, если нет блокировок. Если проблема, из-за которой была заблокирована предыдущая отправка, устранена, шлюз регистрирует ее как FIXED, добавляет соглашение к CONTEXT.md в ## 4. Continuous Evolution и фиксирует это изменение.
  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

(пусто)

Необязательная команда, которая получает каждое событие шлюза в формате JSON на stdin.

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/, поэтому эту команду нужно повторно запустить после редактирования SKILL.md.

Теперь смоделируйте, что Antigravity отправляет для команды, которая не является push-уведомлением. Скрипт должен отвечать 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

Открыть ~/codemender-lab как папку в Antigravity. После загрузки агент:

  • Правило secure_tdd_workflow в каждом ходу.
  • Шесть навыков, доступных по запросу.
  • Хук security-gate зарегистрирован в run_command.

Чтобы быстро проверить, доступны ли навыки, спросите у агента в новом чате: Какие навыки Workspace тебе доступны и что они делают? В нем должны быть перечислены все шесть.

Разрешения

Хук запускается Antigravity, а не агентом, поэтому запросы разрешений для инструмента не показываются. Это делают команды агента. В следующей практической работе вы увидите запросы на одобрение тестовой команды, операций git и любой команды cm, которую агент решит выполнить напрямую. Одобряйте их по запросу. Если Antigravity предлагает запомнить решение для префикса команды, примите его, чтобы избежать повторных запросов в цикле.

git push: случившееся

  1. Агент вызывает инструмент терминала с помощью git push origin main.
  2. Antigravity сопоставляет run_command с hooks.json и запускает security_gate_hook.sh с вызовом инструмента в stdin.
  3. Скрипт распознает отправку, находит измененные файлы, сканирует их с помощью cm find и считывает cm report.
  4. Если блокировок нет, выводится сообщение {"decision": "allow"} и выполняется отправка.
  5. Если блок находок, выводится {"decision": "deny", "reason": "..."}. Отправка не выполняется, агент видит причину, а постоянно действующее правило и указанные навыки подсказывают ему, что делать дальше: один неудачный тест, одно минимальное исправление, повторный запуск набора, повторная отправка.

Поздравляем! Вы завершили практическую работу "Навыки и хуки CodeMender для Antigravity". В следующей практической работе вы отправите агенту запрос на добавление функции и посмотрите, как он выполнит весь цикл – от модели угроз до отправки кода, который пройдет проверку.