Agent Dev 101

Модуль 09 · Урок 9.3

Урок 9.3. Specification -> Tests

На этой странице
  1. Зачем это нужно
  2. Основная идея
  3. Ключевые термины
  4. Почему это важно для AI-разработки
  5. Базовая traceability matrix
  6. Status values
  7. Схема Specification -> Tests
  8. Как извлекать requirements
  9. Хороший acceptance criterion
  10. От AC к test
  11. Test naming по requirements
  12. Manual verification как исключение
  13. Coverage gaps
  14. Traceability в agent loop
  15. Prompt: построить test matrix
  16. Prompt: найти gaps
  17. Prompt: реализовать через matrix
  18. Пример 1. Password Reset
  19. Пример 2. AI Agent task: Plan Mode не редактирует файлы
  20. Пример 3. AI Agent task: Skill Discovery
  21. Пример 4. AI Agent task: Tool-calling policy
  22. Пример 5. AI Agent task: RAG assistant with citations
  23. Пример 6. AI Agent task: Evidence-based final answer
  24. Пример 7. AI Agent task: Как решить конкретную задачу через spec-to-tests
  25. Как находить missing tests в существующем проекте
  26. Как выбирать, какие gaps закрывать сейчас
  27. Tests не должны переписывать spec
  28. Когда spec непроверяемая
  29. Traceability для AI evals
  30. Test matrix как артефакт репозитория
  31. Acceptance checklist
  32. Роль reviewer
  33. Связь с TDD
  34. Типичные ошибки
  35. Практика 1. Password Reset matrix
  36. Практика 2. AI Agent development matrix
  37. Критерии готовности
  38. Краткое резюме
  39. Вопросы для самопроверки
  40. Что дальше

Зачем это нужно

В предыдущем уроке мы разобрали test pyramid и научились выбирать уровень проверки: unit, integration, E2E, contract, snapshot, visual, migration, security, performance и evals для AI systems.

Теперь нужно сделать следующий шаг: связать тесты со specification.

Без этой связи тесты могут существовать, но не доказывать нужное поведение.

Типичная ситуация:

text
Spec говорит:
- reset token can be used only once.

Tests проверяют:
- reset endpoint returns 200 for valid token.

Проблема:
- token reuse не проверяется.

Или в AI Agent development:

text
Spec говорит:
- In Plan Mode agent must not edit files.

Tests проверяют:
- agent returns a plan.

Проблема:
- никто не проверил, что edit tool не вызывался.

Traceability решает эту проблему. Каждый важный requirement и acceptance criterion должен быть связан с тестом, eval, contract check или осознанной manual verification.

Главная цель урока - научиться превращать specification в test matrix, чтобы spec стала исполняемым контрактом для агента и команды.

Основная идея

Specification становится инженерным контрактом только тогда, когда ее можно проверить.

Формула:

text
Requirement
  -> Acceptance Criterion
  -> Test or Eval
  -> Verification Evidence

Если у requirement нет acceptance criterion, его трудно реализовать.

Если у acceptance criterion нет test/eval/manual check, его трудно доказать.

Если у test нет связи с requirement, он может проходить и при этом не защищать важное поведение.

Traceability matrix делает эту связь явной.

Ключевые термины

Термин Значение
Requirement Требование к системе, продукту или агентскому workflow.
Acceptance Criterion Проверяемое условие, по которому можно сказать, что requirement выполнен.
Test Автоматическая проверка software behavior.
Eval Проверка AI/agent behavior на сценарии, prompt, rubric или benchmark.
Manual Verification Явная ручная проверка, используемая как исключение или дополнение.
Traceability Прослеживаемость от requirement до проверки и evidence.
Traceability Matrix Таблица, связывающая requirements, AC, tests/evals, status и gaps.
Coverage Gap Важное поведение, для которого нет достаточной проверки.
Test Naming Именование tests так, чтобы было понятно, какой requirement они защищают.
Executable Contract Spec, требования которой подтверждаются тестами/evals/checks.
Verification Evidence Команда, результат, exit code, report, screenshot, eval output или другой проверяемый факт.

Почему это важно для AI-разработки

В AI-assisted development агент может быстро написать тесты. Но он может написать не те тесты.

Плохой сценарий:

text
User: "Сделай reset password безопасно."
Agent:
- добавил endpoint;
- добавил один happy-path test;
- сказал, что безопасность покрыта.

Что могло остаться непроверенным:

  • token reuse;
  • token expiration;
  • user enumeration;
  • weak password policy;
  • email job contract;
  • rate limiting;
  • audit logging.

AI ускоряет не только создание хорошего кода, но и создание ложной уверенности. Traceability заставляет агента доказать, что tests соответствуют spec.

Базовая traceability matrix

Минимальная таблица:

Requirement Acceptance Criterion Test
AUTH-01 token действует 15 min unit
AUTH-02 expired token rejected integration
AUTH-03 reset работает UI -> API -> DB E2E

Расширенная таблица для проекта:

ID Requirement Acceptance Criterion Test Type Test Name Automated Status Evidence
AUTH-01 Token TTL Token expires after 15 min Unit test_reset_token_expires_after_ttl Yes Covered pytest tests/auth
AUTH-02 Expired token rejected API rejects expired token Integration test_expired_reset_token_rejected Yes Covered pytest tests/auth/api
AUTH-03 Full reset flow User logs in with new password E2E reset_password_flow.spec.ts Yes Partial E2E not run locally

Колонка Status важна. Не все сразу будет covered. Но gap должен быть видимым.

Status values

Удобные статусы:

Status Значение
Covered Есть достаточная automated verification.
Partial Проверка есть, но покрывает не весь AC.
Manual Есть только manual verification.
Gap Проверки нет.
Not applicable AC не требует test, но это нужно обосновать.
Blocked Проверка нужна, но не может быть выполнена сейчас.
Risk accepted Команда осознанно принимает отсутствие проверки.

Важно:

text
Gap лучше, чем невидимый gap.

Когда gap виден, его можно закрыть, принять или отложить. Когда gap невидим, команда живет в иллюзии покрытия.

Схема Specification -> Tests

flowchart TD A[Specification] --> B[Requirements] B --> C[Acceptance Criteria] C --> D{Can be automated?} D -- Yes --> E[Choose test type] E --> F[Write test/eval] F --> G[Run verification] G --> H[Evidence] D -- No --> I[Manual verification] I --> J[Residual risk] H --> K[Traceability matrix] J --> K K --> L[Acceptance decision]

Спецификация не заканчивается текстом. Она должна привести к проверкам.

Как извлекать requirements

Requirements часто спрятаны в разных формах:

  • user story;
  • acceptance criteria;
  • product description;
  • bug report;
  • security note;
  • architecture decision;
  • non-goals;
  • constraints;
  • examples;
  • error cases.

Агент должен уметь превращать текст:

text
Пользователь может сбросить пароль через email.
Ссылка должна быть ограничена по времени.
Нельзя раскрывать, зарегистрирован ли email.

в requirements:

text
AUTH-RESET-01: User can request reset by email.
AUTH-RESET-02: Reset token has expiration.
AUTH-RESET-03: Reset request does not reveal account existence.

Затем в AC:

text
AC1: POST /password-reset returns same response for existing and unknown email.
AC2: token older than 15 minutes is rejected.
AC3: valid token allows password update.

И только потом в tests.

Хороший acceptance criterion

Хороший AC:

  • наблюдаемый;
  • проверяемый;
  • однозначный;
  • связан с requirement;
  • имеет expected result;
  • не описывает implementation details без необходимости.

Плохо:

text
Reset password should be secure.

Лучше:

text
Password reset token cannot be used more than once.

Еще лучше:

text
After a successful password reset, a second request using the same token returns 400/invalid_token and does not change the password.

Последний вариант почти сразу превращается в test.

От AC к test

Шаги:

  1. Найти observable behavior.
  2. Выбрать test type из test pyramid.
  3. Назвать test по requirement/AC.
  4. Определить setup.
  5. Определить action.
  6. Определить assertion.
  7. Определить evidence command.

Шаблон:

text
Requirement:

Acceptance Criterion:

Observable behavior:

Test type:

Test name:

Setup:

Action:

Expected assertion:

Verification command:

Пример:

text
Requirement:
AUTH-RESET-04 Token single-use.

Acceptance Criterion:
After successful reset, the same token cannot be reused.

Observable behavior:
Second reset attempt with same token fails and password remains unchanged.

Test type:
Integration/regression.

Test name:
test_reset_token_cannot_be_reused

Setup:
Create user and valid reset token.

Action:
Reset password once, then call reset endpoint again with same token.

Expected assertion:
First call succeeds, second call fails, login works only with first new password.

Verification command:
pytest tests/auth/test_password_reset.py::test_reset_token_cannot_be_reused

Test naming по requirements

Test name должен помогать traceability.

Хорошо:

text
test_auth_reset_04_token_cannot_be_reused
test_auth_reset_03_request_does_not_reveal_email_existence
test_agent_plan_01_plan_mode_does_not_edit_files
test_tool_policy_02_external_write_requires_approval

Плохо:

text
test_ok
test_reset
test_agent
test_case_1

Если test падает, имя должно сразу подсказать, какой requirement под угрозой.

Не всегда нужно включать ID в имя, но для critical requirements это полезно.

Manual verification как исключение

Manual check допустим, но он должен быть явным.

Хороший manual entry:

ID AC Test Type Status Evidence
UI-RESET-02 Error message is readable on mobile Manual/visual Manual Screenshot checked at 390px width

Плохой manual entry:

text
Проверим глазами потом.

Manual verification должна содержать:

  • кто/что проверяет;
  • какой сценарий;
  • какой expected result;
  • какие artifacts: screenshot, recording, note;
  • какой residual risk остается.

Manual check не должен быть способом спрятать отсутствие тестов. Он нужен там, где automation пока не окупается или невозможна.

Coverage gaps

Coverage gap - acceptance criterion без достаточной проверки.

Пример:

ID AC Current Test Gap
AUTH-RESET-03 Same response for existing and unknown email Happy path only No negative account-enumeration test
AUTH-RESET-04 Token single-use No test Regression gap
AUTH-RESET-08 Email job payload includes locale Queue called, payload unchecked Contract gap

Что делать с gap:

  1. Добавить test сейчас.
  2. Запланировать follow-up.
  3. Принять risk явно.
  4. Переписать AC, если он неверен.
  5. Уточнить spec, если AC непроверяемый.

Нельзя просто игнорировать.

Traceability в agent loop

В controlled development loop traceability появляется дважды.

Plan Mode:

text
Agent reads spec.
Extracts requirements and AC.
Proposes test matrix.
Requests approval.

Act Mode:

text
Agent adds tests.
Implements change.
Runs verification.
Reports matrix status.

Финальный ответ агента должен включать:

text
Acceptance criteria:
- AC1: covered by test X, passed
- AC2: manual check Y, passed
- AC3: gap, reason Z

Если агент не может показать такую связь, он не доказал выполнение spec.

Prompt: построить test matrix

Используйте prompt:

text
Work in Plan Mode.

Read this specification and produce a traceability matrix.
Do not implement code yet.

For each requirement:
- assign a stable ID;
- extract acceptance criteria;
- choose test type from the test pyramid;
- propose test names;
- mark automated/manual/gap;
- list required fixtures or mocks;
- identify open questions.

Return:
Requirement -> Acceptance Criterion -> Test/Eval -> Evidence command.

Такой prompt полезен до реализации. Он заставляет агента думать через проверки.

Prompt: найти gaps

text
Review this specification and existing tests.
Build a traceability matrix.
Identify acceptance criteria without automated tests.
Classify each gap as unit, integration, E2E, contract, security, migration, visual, performance, or eval.
Do not write code yet.

Это хороший review prompt для существующей codebase.

Prompt: реализовать через matrix

text
Use the approved traceability matrix.

Implement only AC1 and AC2 in this task.
Before code changes, add or update the tests named in the matrix.
After implementation, run the verification commands and report matrix status.
Do not work on AC3/AC4.

Так агент получает не просто task, а scope + tests + Definition of Done.

Пример 1. Password Reset

Specification:

text
User can request a password reset email.
Reset token expires after 15 minutes.
Token can be used only once.
The system must not reveal whether an email exists.
After reset, user can log in with the new password.

Traceability matrix:

ID Requirement Acceptance Criterion Test Type Test Name Status
AUTH-RESET-01 Request reset POST /password-reset accepts email and returns generic success API integration test_auth_reset_01_request_returns_generic_success Covered
AUTH-RESET-02 No account enumeration Existing and unknown email receive same public response Security/API integration test_auth_reset_02_no_email_enumeration Covered
AUTH-RESET-03 Token TTL Token older than 15 min is rejected Unit + integration test_auth_reset_03_expired_token_rejected Covered
AUTH-RESET-04 Single-use token Used token cannot reset password again Regression integration test_auth_reset_04_token_cannot_be_reused Gap
AUTH-RESET-05 New password works User can login with new password after reset E2E/integration test_auth_reset_05_login_with_new_password Partial

Coverage gap:

text
AUTH-RESET-04 has no regression test.
This is high risk because token reuse is a security bug.
Recommended next task: add failing regression test before implementation.

Это подводит к уроку 9.4 TDD и уроку 9.5 Bug Fix Flow.

Пример 2. AI Agent task: Plan Mode не редактирует файлы

Теперь пример из AI Agent Development.

Specification:

text
When the agent is in Plan Mode, it may read files and inspect the repository, but it must not edit files, run write tools, commit changes, or call external write tools.

Requirements:

ID Requirement
AGENT-PLAN-01 Plan Mode is read-only.
AGENT-PLAN-02 Agent returns a structured plan.
AGENT-PLAN-03 Agent asks approval before Act Mode.
AGENT-PLAN-04 Agent reports open questions and risks.

Acceptance criteria:

ID Acceptance Criterion
AC1 Given a planning task, the agent reads relevant files but does not call edit tools.
AC2 Final plan includes understanding, scope, steps, verification plan, risks and approval request.
AC3 If implementation is needed, agent asks for approval instead of editing.
AC4 If spec is missing, agent asks clarifying questions or states assumptions.

Traceability:

Requirement AC Test/Eval Type Test Name Evidence
AGENT-PLAN-01 AC1 Agent workflow eval + tool log assertion eval_plan_mode_does_not_edit_files Tool trace contains read/search only
AGENT-PLAN-02 AC2 Output contract test eval_plan_output_contains_required_sections Output rubric
AGENT-PLAN-03 AC3 Safety/procedure eval eval_plan_requests_approval_before_act No edit, approval request present
AGENT-PLAN-04 AC4 Ambiguity eval eval_plan_handles_missing_spec Questions/assumptions present

Как решить задачу:

  1. Написать spec для Plan Mode.
  2. Составить matrix.
  3. Создать eval prompts:
    • "Plan implementation for endpoint, do not edit."
    • "Plan migration with unclear rollback."
    • "Plan auth endpoint with missing role policy."
  4. Запустить агента в read-only среде или проверить tool trace.
  5. Assert:
    • no apply_patch;
    • no write tools;
    • plan sections present;
    • approval request present.

Здесь test - не unit test функции. Это agent behavior eval.

Пример 3. AI Agent task: Skill Discovery

Specification:

text
Agent should use `create-api-endpoint` skill for backend endpoint implementation tasks and should not use it for API theory explanations, database-only migrations, frontend-only tasks, or deployment tasks.

Requirements:

ID Requirement
SKILL-DISC-01 Endpoint implementation triggers skill.
SKILL-DISC-02 Near-miss tasks do not trigger skill.
SKILL-DISC-03 Mixed tasks produce primary/secondary workflow decision.

Traceability:

Requirement Acceptance Criterion Test/Eval Type Test Name
SKILL-DISC-01 "Добавь POST /api/projects" activates create-api-endpoint Trigger eval eval_skill_discovery_endpoint_yes
SKILL-DISC-02 "Объясни REST" does not activate implementation skill Trigger eval eval_skill_discovery_rest_theory_no
SKILL-DISC-02 "Добавь DB index" does not activate endpoint skill Trigger eval eval_skill_discovery_db_only_no
SKILL-DISC-03 "Добавь поле и верни его из API" mentions migration and endpoint workflows Ambiguous trigger eval eval_skill_discovery_mixed_workflow

Example trigger cases:

yaml
skill: create-api-endpoint
cases:
  - id: endpoint_yes
    prompt: "Добавь POST /api/projects с validation и API test."
    expected_activation: "YES"

  - id: rest_theory_no
    prompt: "Объясни, чем REST отличается от GraphQL."
    expected_activation: "NO"

  - id: migration_only_no
    prompt: "Добавь index на users.email."
    expected_activation: "NO"

  - id: endpoint_plus_migration_ambiguous
    prompt: "Добавь поле last_seen_at и верни его из GET /api/me."
    expected_activation: "AMBIGUOUS"

Как решить задачу:

  1. Требование про discovery превратить в YES/NO/AMBIGUOUS cases.
  2. Проверять не body skill, а metadata behavior.
  3. При false positive добавить negative trigger в description.
  4. При false negative добавить missing positive trigger.
  5. Оставить cases как regression evals для skill.

Пример 4. AI Agent task: Tool-calling policy

Specification:

text
Agent may read pull request diff automatically, but must request human approval before posting a PR comment. Agent must never call production deployment tools unless the user explicitly approves production deploy.

Requirements:

ID Requirement
TOOL-POLICY-01 Read PR diff is allowed in scoped repo.
TOOL-POLICY-02 PR comment requires approval.
TOOL-POLICY-03 Production deploy requires explicit approval.
TOOL-POLICY-04 Agent reports denied tool calls.

Traceability:

Requirement AC Test Type Test Name
TOOL-POLICY-01 get_pr_diff allowed with repo/pr scope Permission unit/contract test_tool_policy_pr_diff_allowed
TOOL-POLICY-02 comment_on_pr blocked without approval Security integration test_tool_policy_pr_comment_requires_approval
TOOL-POLICY-03 deploy_production blocked without explicit approval Safety eval/integration test_tool_policy_prod_deploy_requires_approval
TOOL-POLICY-04 Denied tool result appears in final report Output contract eval eval_agent_reports_denied_tool_call

Как решить задачу:

  1. Разделить READ/WRITE/DEPLOY actions.
  2. Написать policy function или config.
  3. Unit-test policy decisions.
  4. Integration-test tool call path with mocked runtime.
  5. Agent eval: malicious or ambiguous prompt should not bypass policy.
  6. Output test: denied action must be visible in final response.

Здесь видны разные уровни:

  • unit tests для policy;
  • contract tests для tool schemas;
  • integration tests для runtime;
  • safety evals для agent behavior.

Пример 5. AI Agent task: RAG assistant with citations

Specification:

text
Documentation assistant answers questions using internal docs. It must cite sources. If the answer is not present in retrieved documents, it should say that the answer is not found instead of inventing.

Requirements:

ID Requirement
RAG-01 Answers use retrieved context.
RAG-02 Answers cite sources.
RAG-03 Unknown answer leads to abstention.
RAG-04 Retrieval respects tenant/project filters.
RAG-05 Prompt injection in docs does not override instructions.

Traceability:

Requirement Acceptance Criterion Test/Eval Type Test Name
RAG-01 Expected source doc appears in top-k for golden question Retrieval eval eval_rag_01_retrieves_expected_doc
RAG-02 Answer includes citation to retrieved source Answer eval/contract eval_rag_02_answer_has_citation
RAG-03 Missing context returns "not found" behavior Eval eval_rag_03_abstains_when_context_missing
RAG-04 Query for tenant A never retrieves tenant B docs Security integration test_rag_04_tenant_filter_enforced
RAG-05 Malicious doc instruction is treated as content Safety eval eval_rag_05_prompt_injection_ignored

Как решить задачу:

  1. Создать golden dataset из вопросов и expected source docs.
  2. Проверить retrieval отдельно от generation.
  3. Проверить answer schema/citation contract.
  4. Добавить negative cases: context missing, malicious docs, wrong tenant.
  5. Использовать rubric eval для качества ответа.
  6. Отдельно измерить latency/token budget, если есть performance AC.

Важно: не пытайтесь проверить RAG только E2E ответом. Если ответ неправильный, нужно понимать, где failure:

  • не найден document;
  • найден, но не попал в context;
  • context есть, но model не использовала;
  • citation mapping сломан;
  • policy отказа не сработала.

Пример 6. AI Agent task: Evidence-based final answer

Specification:

text
After completing a coding task, the agent must report summary, changed files, verification commands with results, acceptance criteria status, and residual risks. It must not claim tests passed if they were not run.

Requirements:

ID Requirement
AGENT-OUT-01 Final answer includes summary.
AGENT-OUT-02 Final answer lists changed files.
AGENT-OUT-03 Final answer reports verification commands/results.
AGENT-OUT-04 Final answer maps AC status.
AGENT-OUT-05 Not-run checks are explicit.
AGENT-OUT-06 Failed checks are not hidden.

Traceability:

Requirement AC Test/Eval Type Test Name
AGENT-OUT-01 Summary section present Output contract eval eval_output_summary_present
AGENT-OUT-02 Changed files list present Output contract eval eval_output_changed_files_present
AGENT-OUT-03 Commands and results present Output contract eval eval_output_verification_present
AGENT-OUT-04 AC statuses present Output contract eval eval_output_ac_status_present
AGENT-OUT-05 Not-run checks include reason Safety/output eval eval_output_not_run_has_reason
AGENT-OUT-06 Failed tests reported honestly Safety eval eval_output_failed_checks_not_hidden

Как решить задачу:

  1. Описать output contract в project instructions или skill.
  2. Создать eval cases с passed, failed и not-run verification.
  3. Проверять наличие mandatory sections.
  4. Проверять, что failed/not-run не превращается в "passed".
  5. Добавить этот output eval в regression suite для agent workflow.

Это пример, где test проверяет не product code, а дисциплину агента.

Пример 7. AI Agent task: Как решить конкретную задачу через spec-to-tests

Допустим, user request:

text
Сделай агента, который исправляет баги только через regression test.

Не начинаем с реализации. Сначала spec:

text
Bug-fix agent must:
1. Read bug report.
2. Reproduce the failure or identify the missing test case.
3. Add a failing regression test when practical.
4. Implement the smallest fix.
5. Run the regression test.
6. Report before/after evidence.
7. Avoid broad refactors.

Traceability:

ID Requirement Acceptance Criterion Test/Eval
BUGAGENT-01 Reads bug report Agent summary includes expected vs actual behavior Procedure eval
BUGAGENT-02 Reproduces bug Before-fix test fails or reproduction limitation reported Workflow eval
BUGAGENT-03 Adds regression test Diff includes test that fails without fix Diff/procedure eval
BUGAGENT-04 Minimal fix Diff scoped to owning module Diff review rubric
BUGAGENT-05 Verifies fix Regression test passes after fix Command evidence
BUGAGENT-06 Reports evidence Final output includes before/after commands Output contract eval
BUGAGENT-07 Avoids refactor No unrelated modules changed Diff review

Implementation order:

  1. Write skill fix-bug-with-regression-test.
  2. Add eval prompts for 3 bug reports.
  3. Add output rubric.
  4. Run agent on one synthetic bug.
  5. Inspect diff and command evidence.
  6. Patch skill if agent skips reproduction.
  7. Add skipped-reproduction case to regression evals.

Так решается AI Agent development task: через specification, matrix, evals и только потом implementation.

Как находить missing tests в существующем проекте

Процесс:

  1. Прочитать spec.
  2. Выписать requirements.
  3. Выписать acceptance criteria.
  4. Найти existing tests по именам, paths и behavior.
  5. Сопоставить tests с AC.
  6. Отметить gaps.
  7. Классифицировать gaps по test pyramid.
  8. Выбрать gaps, которые нужно закрыть в текущей task.

Prompt:

text
Read `specs/features/password-reset.md` and inspect existing tests.
Create a traceability matrix.
For each AC, say whether it is covered, partially covered, manually checked, or a gap.
Do not modify code.

Agent output должен быть похож на:

AC Existing test Status Recommendation
Token expires test_expired_token Covered Keep
Token single-use none Gap Add regression integration test
No email enumeration happy path only Partial Add negative API test

Как выбирать, какие gaps закрывать сейчас

Не все gaps нужно закрывать в одной task. Смотрите на риск.

Приоритет высокий, если gap касается:

  • security;
  • data loss;
  • money;
  • auth;
  • public API contract;
  • critical user journey;
  • bug regression;
  • migration compatibility;
  • tool permissions;
  • prompt injection;
  • agent workflow safety.

Приоритет ниже, если:

  • behavior low-risk;
  • AC декоративный;
  • manual check дешевый и достаточный;
  • automation слишком дорогая сейчас;
  • requirement еще unstable.

Но даже low-priority gap должен быть записан.

Tests не должны переписывать spec

Иногда агент пишет тесты на то, что ему удобно реализовать.

Плохо:

text
Spec:
Invalid token returns 400 with `invalid_token`.

Agent test:
Invalid token returns 200 with message "Check your email".

Это не implementation detail. Это behavior mismatch.

Правило:

text
Tests derive from spec.
If test and spec disagree, clarify or fix one source of truth.

Не позволяйте tests становиться скрытой альтернативной specification.

Когда spec непроверяемая

Примеры непроверяемых требований:

text
Agent should be smart.
UI should feel nice.
Search should be good.
Code should be clean.
The answer should be helpful.

Их нужно превратить в observable AC:

Vague requirement Проверяемый AC
Agent should be smart For 8/10 benchmark tasks, agent selects correct skill and returns evidence.
UI should feel nice Form has no overlapping text at 390px and 1440px, loading/error states visible.
Search should be good Expected source doc appears in top 3 for 90% golden queries.
Code should be clean Diff has no unrelated files, passes lint/typecheck, follows local pattern.
Answer should be helpful Answer includes direct answer, source citation, and no unsupported claims.

Для AI systems это особенно важно. "Качественный ответ" должен стать rubric или eval.

Traceability для AI evals

AI eval тоже должен быть traceable.

Плохо:

text
Мы запустили 50 prompts, вроде нормально.

Лучше:

Requirement Eval Case Expected Behavior Rubric
RAG cites sources reset_ttl_question Answer includes correct source source present, TTL correct
Agent no edit in Plan Mode plan_endpoint_task No write tool calls tool trace check
Tool write approval comment_pr_without_approval No comment call denied action reported

Eval должен проверять конкретный requirement, а не общее впечатление.

Test matrix как артефакт репозитория

Для курса итоговый artifact:

text
docs/development/testing.md

или для feature:

text
specs/features/password-reset-test-matrix.md

Пример структуры:

markdown
# Password Reset Test Matrix

| ID | Requirement | Acceptance Criterion | Test Type | Test Name | Status | Evidence |
|---|---|---|---|---|---|---|
| AUTH-RESET-01 | ... | ... | ... | ... | ... | ... |

## Coverage Gaps

| Gap | Risk | Plan |
|---|---|---|

## Manual Verification

| Scenario | Steps | Expected | Evidence |
|---|---|---|---|

Эта матрица помогает агенту, reviewer и future developer.

Acceptance checklist

Перед завершением task:

text
[ ] Все requirements имеют AC
[ ] Все critical AC имеют automated test или eval
[ ] Manual checks описаны явно
[ ] Coverage gaps перечислены
[ ] High-risk gaps закрыты или escalated
[ ] Test names понятны
[ ] Verification commands указаны
[ ] Final report содержит AC status

Если есть uncovered critical AC, task не должна считаться полностью готовой.

Роль reviewer

Reviewer должен проверять не только код, но и traceability.

Review questions:

  • Какой requirement покрывает этот test?
  • Есть ли AC без test?
  • Test действительно проверяет behavior или только implementation detail?
  • Есть ли negative/security cases?
  • Есть ли integration/contract coverage для boundary?
  • Если manual verification, почему automation не сделана?
  • Есть ли residual risk?

В AI-generated diff reviewer особенно должен смотреть:

text
Не написал ли агент tests, которые проходят, но не доказывают spec?

Связь с TDD

Traceability отвечает:

text
Какие tests нужны?

TDD отвечает:

text
В каком порядке писать tests и код?

Следующий урок:

text
RED -> GREEN -> REFACTOR

Но TDD без traceability может привести к тому, что агент пишет failing test на неправильное поведение. Поэтому сначала:

text
Spec -> AC -> Test Matrix

потом:

text
RED -> GREEN -> REFACTOR

Типичные ошибки

Ошибка Симптом Исправление
Tests без spec Проверки есть, но непонятно, что доказывают Requirement -> AC -> Test matrix.
AC без tests Feature принята на доверии Mark gap and add verification.
Happy path only Edge/security cases не покрыты Add negative and boundary cases.
Test name vague Failure трудно связать с requirement Use requirement-aware names.
Manual check hidden "Проверено" без steps/evidence Document manual scenario.
Evals без requirement Запущены prompts, но нет выводов Tie eval cases to requirements.
Agent writes convenient tests Tests не соответствуют spec Review test assertions against AC.
Coverage as goal High coverage, low confidence Focus on risks and AC.
One giant task Matrix большая, implementation расползается Select subset of AC per task.
Gaps ignored Critical behavior remains unprotected Escalate or accept risk explicitly.

Практика 1. Password Reset matrix

Постройте таблицу:

ID Requirement Acceptance Criterion Test Type Test Name Status
AUTH-RESET-01 Request reset
AUTH-RESET-02 No email enumeration
AUTH-RESET-03 Token expires
AUTH-RESET-04 Token single-use
AUTH-RESET-05 Password policy
AUTH-RESET-06 Login after reset

Добавьте:

  • минимум один unit test;
  • минимум два integration tests;
  • минимум один security test;
  • один E2E или объяснение, почему он не нужен в текущей task;
  • coverage gaps.

Практика 2. AI Agent development matrix

Задача:

text
Сделать coding agent workflow, где агент:
- работает в Plan Mode без edits;
- после approval выполняет Act Mode;
- добавляет/обновляет tests;
- запускает verification;
- возвращает final evidence.

Заполните:

ID Requirement Acceptance Criterion Test/Eval Type Test/Eval Name
AGENT-WF-01 Plan Mode read-only
AGENT-WF-02 Approval before edits
AGENT-WF-03 Test before/with implementation
AGENT-WF-04 Verification evidence
AGENT-WF-05 Scope escalation

Возможное решение:

ID Requirement Acceptance Criterion Test/Eval Type Test/Eval Name
AGENT-WF-01 Plan Mode read-only Tool trace has no edit/write calls Workflow eval eval_agent_wf_01_plan_no_edits
AGENT-WF-02 Approval before edits Agent asks approval before Act Mode Procedure eval eval_agent_wf_02_approval_gate
AGENT-WF-03 Tests included Plan includes test strategy and Act adds/updates test when practical Diff/procedure eval eval_agent_wf_03_tests_in_loop
AGENT-WF-04 Evidence output Final answer includes commands/results/AC status Output contract eval eval_agent_wf_04_evidence_output
AGENT-WF-05 Scope escalation Agent stops when migration needed outside scope Safety eval eval_agent_wf_05_scope_escalation

Критерии готовности

После урока студент должен уметь:

  • объяснить traceability от requirement до test;
  • построить traceability matrix;
  • отличить requirement от acceptance criterion;
  • находить AC без tests;
  • классифицировать gaps;
  • выбирать automated test, eval или manual verification;
  • именовать tests по requirement;
  • строить matrix для AI Agent development задач;
  • использовать matrix как input для агента;
  • подготовиться к TDD с агентом.

Краткое резюме

Specification становится исполняемым контрактом, когда каждый важный requirement прослеживается до проверки.

Главная цепочка:

text
Requirement -> Acceptance Criterion -> Test/Eval -> Evidence

Для обычного software это означает unit, integration, E2E, contract, security и другие tests.

Для AI Agent development это также означает evals:

  • skill trigger evals;
  • Plan/Act workflow evals;
  • tool policy tests;
  • RAG retrieval/citation evals;
  • output contract evals;
  • safety cases.

Traceability не замедляет агента. Она дает ему правильную цель: писать не просто код, а проверяемое поведение.

Вопросы для самопроверки

  1. Чем requirement отличается от acceptance criterion?
  2. Почему test без связи со spec может давать ложную уверенность?
  3. Какие AI Agent behaviors стоит проверять evals, а не обычными unit tests?
  4. Какой coverage gap самый опасный в password reset feature?
  5. Как traceability matrix помогает агенту в Plan Mode?

Что дальше

В следующем уроке мы перейдем к TDD с агентом. Traceability matrix говорит, какие tests нужны. TDD задает порядок: сначала failing test, затем минимальная реализация, затем refactor и повторная verification. Это особенно полезно для agent-generated changes, потому что агент получает быстрый executable feedback вместо работы на уверенности.

Обновлено 03.10.2026