1. Wprowadzenie
W tym ćwiczeniu skonfigurujesz agenta kodowania AI (Antigravity), aby bezpieczeństwo było częścią jego normalnej pętli programistycznej, a nie osobnym etapem sprawdzania. Zainstalujesz zestaw umiejętności agenta, które przeprowadzą go przez cykl Planowanie → Czerwony → Zielony → Refaktoryzacja, oraz punkt zaczepienia PreToolUse, który przechwytuje git push, skanuje zmienione pliki za pomocą CodeMendera i przekazuje wyniki agentowi wraz z instrukcjami, jak je naprawić, zaczynając od testów.
Umiejętności i hook pochodzą z platformy open source Secure TDD Agent Framework. Zainstalujesz je w tym samym obszarze roboczym ~/codemender-lab, który został utworzony w ramach modułu Podstawy interfejsu wiersza poleceń CodeMender.
Czego się nauczysz
- Jak Antigravity wykrywa reguły, umiejętności i punkty zaczepienia obszaru roboczego w
.agents/. - jakie jest działanie 6 umiejętności związanych z bezpiecznym TDD i którego etapu pętli dotyczy każda z nich;
- Jak hook
PreToolUseotrzymuje wywołanie narzędzia agenta na stdin i zwraca decyzję o zezwoleniu lub odmowie. - Jak hook bramki zabezpieczeń (
security_gate_hook.sh) uruchamiacm find, klasyfikuje wyniki według stopnia ważności, śledzi próby naprawy i przekazuje problemy docm verify. - Jak zweryfikować cały potok hooka offline za pomocą próbnych skanerów przed skierowaniem go na rzeczywisty
cm.
Wymagania wstępne
- ukończenie kursu CodeMender CLI Basics, Ten moduł jest kontynuowany w katalogu
~/codemender-labi wykorzystuje ponownie plikisample_app/,CONTEXT.md, historię git i~/.codemender/config.yaml. - Zainstalowane rozszerzenie Antigravity z możliwością otwierania folderu lokalnego jako obszaru roboczego.
- Zainstalowano aplikacje
git,jqibash. Skrypty hook są zwykłymi skryptami bash i działają w standardowej wersji bash 3.2 systemu macOS oraz w nowszych wersjach. - Środowisko wirtualne Pythona z podstaw interfejsu wiersza poleceń CodeMender (
~/codemender-lab/.venv) z zainstalowanym Flask. - Podstawowa wiedza na temat skryptów powłoki.
2. Konfiguracja Workspace
Krok 1. Wróć do katalogu modułów
Wszystkie polecenia w tym module są uruchamiane w ~/codemender-lab z aktywnym środowiskiem wirtualnym:
cd ~/codemender-lab && source .venv/bin/activate
Sprawdź, czy obszar roboczy z poprzedniego modułu jest nienaruszony, a drzewo robocze jest czyste:
ls sample_app/data_service.py CONTEXT.md .gitignore
git status --short
git status --short nie powinien niczego drukować. Jeśli wyświetli się lista plików, zatwierdź je, zanim przejdziesz dalej.
Krok 2. Nazwij gałąź main
Bramka zabezpieczeń porównuje drzewo robocze z origin/main, aby określić, które pliki należy przeskanować. Jeśli ta referencja nie istnieje, używana jest referencja HEAD~1, która obejmuje tylko najnowsze zatwierdzenie. Upewnij się, że gałąź ma nazwę main:
git branch -M main
Krok 3. Dodaj punkt wejścia zestawu testów
Pętla bezpiecznego TDD prosi agenta o uruchomienie polecenia python3 -m unittest discover -s tests po każdej poprawce, więc obszar roboczy musi zawierać katalog tests/. Zacznij od jednego testu charakterystyki, aby pakiet miał coś prawdziwego do uruchomienia:
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
Powinny być widoczne Ran 1 test i OK.
Krok 4. Rozszerz .gitignore i zatwierdź
Dodaj pliki środowiska wykonawczego wygenerowane w tym module do .gitignore, a następnie zatwierdź punkt odniesienia:
printf '.security-gate/\nusers.db\n*.bak\n' >> .gitignore
git add -A && git commit -m "Add test suite entry point for Secure TDD"
3. Instalowanie plików platformy
Umiejętności, reguła, hook i jarzmo testowe offline znajdują się w jednym katalogu .agents/. Zamiast wpisywać ręcznie około 800 wierszy kodu bash, sklonuj platformę i skopiuj ten katalog do obszaru roboczego:
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
Potwierdź układ:
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
Upewnij się, że punkt wejścia hooka jest wykonywalny:
chmod +x .agents/security_gate_hook.sh
ls -l .agents/security_gate_hook.sh
W dalszej części tego modułu omówimy po kolei wszystkie zainstalowane elementy.
4. Reguła przepływu pracy „Zawsze włączone”
Umiejętności są wczytywane na żądanie, gdy agent uzna, że opis umiejętności pasuje do zadania. Coś musi poinformować agenta, aby sięgnął po nie we właściwej kolejności. To zadanie dla .agents/rules/secure_tdd_workflow.md. Sekcja z metadanymi zawiera parametr trigger: always_on, więc reguła jest wstrzykiwana do każdej tury:
---
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.
Reguła odwołuje się do CONTEXT.md, który został utworzony w podstawach interfejsu wiersza poleceń CodeMender. Ten sam plik, który kierował cm fix do konwencji zapytania z parametrami, teraz kieruje planowaniem agenta. W tym module najważniejszy jest punkt 6: to właśnie nim kieruje się agent, gdy brama zabezpieczeń odrzuca push z kilkoma wynikami naraz.
5. 6 umiejętności agenta
Każda umiejętność to katalog zawierający plik SKILL.md z sekcją z metadanymi YAML. Wymagane są 2 pola:
name: identyfikator pisany małymi literami i zawierający łączniki.description: na czym polega umiejętność i kiedy z niej korzystać. Agent odczytuje tylko to pole, gdy decyduje, czy wczytać pełną umiejętność, więc każdy opis poniżej zawiera też informację, do czego umiejętność nie służy.
Umiejętność | Faza | Cel |
| A: Plan | Określ zakres funkcji, uruchom STRIDE, napisz |
| B: Czerwony | pisać testy funkcjonalne i testy wartości granicznych, które nie powiodą się z odpowiedniego powodu; |
| C: Zielony | Napisz minimalny kod, który sprawi, że testy będą zielone, używając bezpiecznych wzorców. |
| D: Refaktoryzacja | Wyczyść, uruchom pełny pakiet, uruchom lokalne skanery, sprawdź różnice. |
| Ciągły | Zapisuj nowe konwencje w plikach |
| Wprowadzenie | Przeszukaj historię Gita, aby wypełnić |
Poniżej znajdziesz pełną treść, dzięki której zobaczysz, jak sekcja z metadanymi i instrukcje pasują do siebie.
1. threat-model-assessor (faza 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 (faza 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 (faza 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 (faza 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 (Ciągły rozwój)
.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 (wprowadzenie)
.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.
Nie będziesz używać tej umiejętności w modułach, ponieważ CONTEXT.md już istnieje, ale warto po nią sięgnąć, gdy wprowadzasz platformę do repozytorium, które ma wieloletnią historię i nie ma spisanych konwencji.
6. Konfigurowanie punktu zaczepienia Antigravity
.agents/hooks.json informuje Antigravity, że ma uruchomić bramę zabezpieczeń przed każdym poleceniem terminala wykonywanym przez agenta:
{
"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
}
]
}
]
}
}
Kilka szczegółów dotyczących tego pliku wyjaśnia projekt skryptu, który uruchamia:
matcherto wyrażenie regularne dotyczące nazw narzędzi, a nie tekstu polecenia.PreToolUseuruchamia się przed uruchomieniem narzędzia, a dopasowanie decyduje, które narzędzia zostaną uruchomione.run_commandto narzędzie terminalowe Antigravity. Inne alternatywy obejmują warianty z przestrzenią nazw wtyczki i inne platformy agentów, które udostępniają te pliki. Dopasowanie takie jakgit push*nigdy nie zostanie uruchomione, ponieważ żadne narzędzie nie ma takiej nazwy. Filtrowanie rzeczywistego polecenia odbywa się w skrypcie.- Punkt zaczepienia otrzymuje wywołanie narzędzia na standardowym wejściu. Antigravity przesyła ładunek JSON, np.
{"toolCall": {"name": "run_command", "args": {"CommandLine": "git push origin main"}}, ...}. Skrypt odczytuje.toolCall.args.CommandLinei natychmiast kończy działanie, zezwalając na wszystko, co nie jestgit push. - Katalog roboczy to katalog zawierający plik
hooks.json, więc punkt zaczepienia zaczyna się w.agents/. Kodbash -c 'if [ -x ./security_gate_hook.sh ] ...'obsługuje zarówno ten przypadek, jak i uruchamianie z katalogu głównego repozytorium. Następnie skryptcddogit rev-parse --show-toplevel, zanim wykona jakiekolwiek działanie. - Skrypt odpowiada na standardowe wyjście w formacie JSON.
{"decision": "allow"}umożliwia uruchomienie pierwotnego polecenia.{"decision": "deny", "reason": "..."}blokuje ją i wyświetla agentowi powód. Platforma emituje też wartość logicznąallow_tool, aby zapewnić zgodność ze starszymi umowami dotyczącymi punktów zaczepienia. - Zaczepy działają synchronicznie i blokują pętlę agenta, dopóki nie zakończą działania lub nie osiągną limitu czasu
timeout(w sekundach; jeśli nie zostanie podany, domyślnie wynosi 30).
Forma -i.bak działa zarówno z GNU, jak i BSD (macOS) sed:
sed -i.bak 's/"timeout": 120/"timeout": 900/' .agents/hooks.json && rm .agents/hooks.json.bak
7. Jak działa hak bramki zabezpieczającej
security_gate_hook.sh to prosty punkt wejścia, który pobiera 3 moduły z .agents/lib/:
Moduł | Rola |
| Domyślne ustawienia konfiguracji, dane wyjściowe |
| Etap 1. Opcjonalne skanowanie deterministyczne za pomocą Semgrep. Pominięto, jeśli |
| Etap 2. Skanowanie semantyczne za pomocą |
Krok 1. Zdecyduj, czy to jest powiadomienie push
Punkt wejścia wyodrębnia polecenie z ładunku stdin i testuje je pod kątem wyrażenia regularnego, które rozpoznaje git push w jego typowych formach (git -C /repo push, cd x && git push, sudo git push), ignorując tekst w cudzysłowie, taki jak git commit -m "before git push". Wszystko, co nie jest wypchnięciem, jest dozwolone natychmiast:
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
Krok 2. Wybierz skanery
SECURITY_GATE_SCANNER wybiera potok. Domyślna wartość auto powoduje uruchomienie Semgrep i CodeMender, jeśli są zainstalowane, w tej kolejności:
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
Gdy etap 1 wykryje problemy z blokowaniem w trybie potoku, nie odrzuca ich samodzielnie, ale zapisuje je w pliku tymczasowym, który jest pobierany przez etap 2, dzięki czemu CodeMender ma ostateczny głos.
Krok 3. Etap CodeMender
run_codemender_gate w engine_codemender.sh wykonuje te działania w podanej kolejności:
- Znajdź zmienione pliki za pomocą
git diff --name-only origin/main(w razie potrzeby użyjHEAD~1). Brak zmian oznacza, że można kontynuować. - Przeskanuj każdy plik za pomocą
cm find "$file" -y --bypass-warning, a następnie pobierz wszystko za pomocącm report --format json. Jeślicm reportnie powiedzie się lub zwróci nieprawidłowy kod JSON, oznacza to błąd skanowania, a nie czysty wynik. - Filtruj wyniki, których stan to
OPENlubREOPENEDi którychfile_pathkończy się jednym ze zmienionych plików. Wyniki, które zostały już poprawione lub odrzucone w podstawach interfejsu wiersza poleceń CodeMender, są ignorowane. - Sklasyfikuj każde wykrycie. Poziom ważności
SECURITY_GATE_BLOCK_SEVERITYlub wyższy (domyślnieHIGH) powoduje blokowanie. Niższe poziomy są traktowane jako ostrzeżenia, rejestrowane i wyświetlane, ale nie zatrzymują przesyłania. - Zezwalaj, jeśli nic nie blokuje. Jeśli wynik, który zablokował poprzednie przesłanie, już nie występuje, bramka rejestruje go jako
FIXED, dołącza konwencję doCONTEXT.mdw## 4. Continuous Evolutioni zatwierdza tę zmianę. - Zliczaj próby dla każdego wyniku blokującego, odczytując własny dziennik kontrolny. Każda odmowa to jedna próba. Podczas prób od 1 do
SECURITY_GATE_MAX_RETRIES(domyślnie 3) bramka rejestrujeDENIED_TO_AGENTi dodaje wynik do wiadomości o odrzuceniu. - Przekaż sprawę po wyczerpaniu budżetu. Przy czwartej próbie dotyczącej tego samego wyniku brama uruchamia
cm verify. Jeśli nie można wykorzystać luki (kod wyjścia 1 lub stanDISMISSED), zostaje ona obniżona do poziomu doradczego. Jeśli zostanie to potwierdzone lubcm verifyulegnie awarii, brama zarejestrujeBLOCKEDi odrzuci prośbę o sprawdzenie przez człowieka. - Odrzuć z instrukcjami. Jeśli jakieś wyniki nadal wymagają działania, brama zwraca agentowi ten powód:
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
To jest moment przejścia od haczyka do umiejętności. Zaczep nie wywołuje metody cm fix. Wymienia umiejętności, których agent powinien użyć, agent wykonuje poprawkę, a następny git push ponownie uruchamia bramę.
Odniesienie do konfiguracji
Wszystkie ustawienia to zmienne środowiskowe z wartościami domyślnymi ustawionymi w gate_common.sh:
Zmienna | Domyślny | Efekt |
|
|
|
|
| Najniższy poziom ważności, który blokuje. |
|
| Odmowy na wynik przed skonsultowaniem się z |
|
|
|
|
| Polecenie testowe cytowane w komunikatach o odrzuceniu i komunikatach zatwierdzenia. |
|
| Dołącz zweryfikowane konwencje do: |
|
| Dziennik kontrolny, do którego można tylko dodawać dane. |
| (puste) | Opcjonalne polecenie, które odbiera każde zdarzenie bramki jako JSON w stdin. |
8. Weryfikowanie haczyka offline
Zanim bramka wejdzie w interakcję z prawdziwym urządzeniem cm, sprawdź, czy działa prawidłowo z makietami. Platforma zawiera jarzmo testowe z fałszywymi plikami binarnymi cm i semgrep, które obejmują ścieżki zezwalania, doradcze, odmowy, błędu i eskalacji:
bash .agents/tests/run_tests.sh
Uruchomienie zajmie kilka sekund i zakończy się komunikatem:
-- test_pipeline_tools_missing_passes_smoothly
-- test_skills_frontmatter_valid
60 passed, 0 failed
Ostatni test sprawdza też sekcję z metadanymi każdej umiejętności w folderze .agents/skills/, więc to polecenie należy uruchomić ponownie po edycji pliku SKILL.md.
Następnie zasymuluj, co Antigravity wysyła w przypadku polecenia, które nie jest poleceniem push. Skrypt powinien odpowiedzieć na pytanie allow bez dotykania skanera:
echo '{"toolCall":{"name":"run_command","args":{"CommandLine":"git status"}}}' \
| bash .agents/security_gate_hook.sh
{"allow_tool": true, "decision": "allow"}
Teraz zasymuluj push bez zmian lokalnych w zasobie origin/main. Ponieważ nie ma jeszcze repozytorium zdalnego, bramka wraca do HEAD~1 i skanuje pliki z ostatniego zatwierdzenia. Aby ten krok był wykonywany offline, skieruj go na makiety cm i 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"}
Oba etapy zostały wykonane, ponieważ katalog próbny zawiera zarówno fałszywy plik semgrep, jak i fałszywy plik cm. Komunikaty o postępach są wysyłane do stderr, a tylko decyzja JSON jest wysyłana do stdout, co pozwala Antigravity na analizę wyniku.
Na koniec zatwierdź pliki platformy, aby były przenoszone razem z repozytorium:
git add -A && git commit -m "Add Secure TDD skills, rule, and security gate hook"
9. Otwieranie obszaru roboczego w Antigravity
Otwórz ~/codemender-lab jako folder w Antigravity. Po wczytaniu agent ma:
- Reguła
secure_tdd_workfloww każdej turze. - 6 umiejętności dostępnych na żądanie.
- Zarejestrowano webhooka
security-gatewrun_command.
Aby szybko sprawdzić, czy umiejętności są widoczne, zapytaj agenta w nowej rozmowie: „Jakie umiejętności Workspace masz do dyspozycji i co każda z nich robi?”. Powinny być wymienione z nazwy.
Uprawnienia
Sam hook jest uruchamiany przez Antigravity, a nie przez agenta, więc nie przechodzi przez prompty dotyczące uprawnień narzędzia. Własne polecenia agenta już tak. Podczas kolejnego ćwiczenia programistycznego spodziewaj się próśb o zatwierdzenie polecenia testowego, operacji git i wszelkich poleceń cm, które agent zdecyduje się uruchomić bezpośrednio. Zatwierdź je, gdy pojawi się prośba. Jeśli Antigravity zaproponuje zapamiętanie decyzji dotyczącej prefiksu polecenia, zaakceptuj tę opcję, aby uniknąć ponownych próśb w pętli.
Co się stanie git push
- Agent wywołuje narzędzie terminala z parametrem
git push origin main. - Antigravity dopasowuje
run_commanddohooks.jsoni uruchamiasecurity_gate_hook.shz wywołaniem narzędzia w stdin. - Skrypt rozpoznaje operację push, znajduje zmienione pliki, skanuje je za pomocą
cm findi odczytujecm report. - Jeśli nic nie blokuje, wyświetla się
{"decision": "allow"}i proces jest kontynuowany. - Jeśli wyniki blokują, wyświetla się
{"decision": "deny", "reason": "..."}. Przesłanie nie zostaje wykonane, agent widzi przyczynę, a reguła „zawsze włączone” i nazwane umiejętności podpowiadają mu, co ma zrobić dalej: jeden nieudany test, jedna minimalna poprawka, ponowne uruchomienie zestawu, ponowne przesłanie.
Gratulacje! Udało Ci się ukończyć ćwiczenie z programowania CodeMender: umiejętności i przechwytywanie w Antigravity. W następnym ćwiczeniu z programowania przekażesz agentowi prośbę o dodanie funkcji i zobaczysz, jak ta pętla działa od początku do końca – od modelu zagrożeń do przekazania kodu, który przechodzi przez bramkę.