Зачем это нужно
В предыдущем уроке мы разобрали test pyramid и научились выбирать уровень проверки: unit, integration, E2E, contract, snapshot, visual, migration, security, performance и evals для AI systems.
Теперь нужно сделать следующий шаг: связать тесты со specification.
Без этой связи тесты могут существовать, но не доказывать нужное поведение.
Типичная ситуация:
Spec говорит:
- reset token can be used only once.
Tests проверяют:
- reset endpoint returns 200 for valid token.
Проблема:
- token reuse не проверяется.
Или в AI Agent development:
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 становится инженерным контрактом только тогда, когда ее можно проверить.
Формула:
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 агент может быстро написать тесты. Но он может написать не те тесты.
Плохой сценарий:
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 | Команда осознанно принимает отсутствие проверки. |
Важно:
Gap лучше, чем невидимый gap.
Когда gap виден, его можно закрыть, принять или отложить. Когда gap невидим, команда живет в иллюзии покрытия.
Схема Specification -> Tests
Спецификация не заканчивается текстом. Она должна привести к проверкам.
Как извлекать requirements
Requirements часто спрятаны в разных формах:
- user story;
- acceptance criteria;
- product description;
- bug report;
- security note;
- architecture decision;
- non-goals;
- constraints;
- examples;
- error cases.
Агент должен уметь превращать текст:
Пользователь может сбросить пароль через email.
Ссылка должна быть ограничена по времени.
Нельзя раскрывать, зарегистрирован ли email.
в requirements:
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:
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 без необходимости.
Плохо:
Reset password should be secure.
Лучше:
Password reset token cannot be used more than once.
Еще лучше:
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
Шаги:
- Найти observable behavior.
- Выбрать test type из test pyramid.
- Назвать test по requirement/AC.
- Определить setup.
- Определить action.
- Определить assertion.
- Определить evidence command.
Шаблон:
Requirement:
Acceptance Criterion:
Observable behavior:
Test type:
Test name:
Setup:
Action:
Expected assertion:
Verification command:
Пример:
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.
Хорошо:
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
Плохо:
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:
Проверим глазами потом.
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:
- Добавить test сейчас.
- Запланировать follow-up.
- Принять risk явно.
- Переписать AC, если он неверен.
- Уточнить spec, если AC непроверяемый.
Нельзя просто игнорировать.
Traceability в agent loop
В controlled development loop traceability появляется дважды.
Plan Mode:
Agent reads spec.
Extracts requirements and AC.
Proposes test matrix.
Requests approval.
Act Mode:
Agent adds tests.
Implements change.
Runs verification.
Reports matrix status.
Финальный ответ агента должен включать:
Acceptance criteria:
- AC1: covered by test X, passed
- AC2: manual check Y, passed
- AC3: gap, reason Z
Если агент не может показать такую связь, он не доказал выполнение spec.
Prompt: построить test matrix
Используйте prompt:
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
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
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:
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:
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:
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 |
Как решить задачу:
- Написать spec для Plan Mode.
- Составить matrix.
- Создать eval prompts:
- "Plan implementation for endpoint, do not edit."
- "Plan migration with unclear rollback."
- "Plan auth endpoint with missing role policy."
- Запустить агента в read-only среде или проверить tool trace.
- Assert:
- no
apply_patch; - no write tools;
- plan sections present;
- approval request present.
- no
Здесь test - не unit test функции. Это agent behavior eval.
Пример 3. AI Agent task: Skill Discovery
Specification:
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:
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"
Как решить задачу:
- Требование про discovery превратить в YES/NO/AMBIGUOUS cases.
- Проверять не body skill, а metadata behavior.
- При false positive добавить negative trigger в
description. - При false negative добавить missing positive trigger.
- Оставить cases как regression evals для skill.
Пример 4. AI Agent task: Tool-calling policy
Specification:
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 |
Как решить задачу:
- Разделить READ/WRITE/DEPLOY actions.
- Написать policy function или config.
- Unit-test policy decisions.
- Integration-test tool call path with mocked runtime.
- Agent eval: malicious or ambiguous prompt should not bypass policy.
- 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:
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 |
Как решить задачу:
- Создать golden dataset из вопросов и expected source docs.
- Проверить retrieval отдельно от generation.
- Проверить answer schema/citation contract.
- Добавить negative cases: context missing, malicious docs, wrong tenant.
- Использовать rubric eval для качества ответа.
- Отдельно измерить latency/token budget, если есть performance AC.
Важно: не пытайтесь проверить RAG только E2E ответом. Если ответ неправильный, нужно понимать, где failure:
- не найден document;
- найден, но не попал в context;
- context есть, но model не использовала;
- citation mapping сломан;
- policy отказа не сработала.
Пример 6. AI Agent task: Evidence-based final answer
Specification:
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 |
Как решить задачу:
- Описать output contract в project instructions или skill.
- Создать eval cases с passed, failed и not-run verification.
- Проверять наличие mandatory sections.
- Проверять, что failed/not-run не превращается в "passed".
- Добавить этот output eval в regression suite для agent workflow.
Это пример, где test проверяет не product code, а дисциплину агента.
Пример 7. AI Agent task: Как решить конкретную задачу через spec-to-tests
Допустим, user request:
Сделай агента, который исправляет баги только через regression test.
Не начинаем с реализации. Сначала spec:
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:
- Write skill
fix-bug-with-regression-test. - Add eval prompts for 3 bug reports.
- Add output rubric.
- Run agent on one synthetic bug.
- Inspect diff and command evidence.
- Patch skill if agent skips reproduction.
- Add skipped-reproduction case to regression evals.
Так решается AI Agent development task: через specification, matrix, evals и только потом implementation.
Как находить missing tests в существующем проекте
Процесс:
- Прочитать spec.
- Выписать requirements.
- Выписать acceptance criteria.
- Найти existing tests по именам, paths и behavior.
- Сопоставить tests с AC.
- Отметить gaps.
- Классифицировать gaps по test pyramid.
- Выбрать gaps, которые нужно закрыть в текущей task.
Prompt:
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
Иногда агент пишет тесты на то, что ему удобно реализовать.
Плохо:
Spec:
Invalid token returns 400 with `invalid_token`.
Agent test:
Invalid token returns 200 with message "Check your email".
Это не implementation detail. Это behavior mismatch.
Правило:
Tests derive from spec.
If test and spec disagree, clarify or fix one source of truth.
Не позволяйте tests становиться скрытой альтернативной specification.
Когда spec непроверяемая
Примеры непроверяемых требований:
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.
Плохо:
Мы запустили 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:
docs/development/testing.md
или для feature:
specs/features/password-reset-test-matrix.md
Пример структуры:
# 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:
[ ] Все 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 особенно должен смотреть:
Не написал ли агент tests, которые проходят, но не доказывают spec?
Связь с TDD
Traceability отвечает:
Какие tests нужны?
TDD отвечает:
В каком порядке писать tests и код?
Следующий урок:
RED -> GREEN -> REFACTOR
Но TDD без traceability может привести к тому, что агент пишет failing test на неправильное поведение. Поэтому сначала:
Spec -> AC -> Test Matrix
потом:
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
Задача:
Сделать 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 прослеживается до проверки.
Главная цепочка:
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 не замедляет агента. Она дает ему правильную цель: писать не просто код, а проверяемое поведение.
Вопросы для самопроверки
- Чем requirement отличается от acceptance criterion?
- Почему test без связи со spec может давать ложную уверенность?
- Какие AI Agent behaviors стоит проверять evals, а не обычными unit tests?
- Какой coverage gap самый опасный в password reset feature?
- Как traceability matrix помогает агенту в Plan Mode?
Что дальше
В следующем уроке мы перейдем к TDD с агентом. Traceability matrix говорит, какие tests нужны. TDD задает порядок: сначала failing test, затем минимальная реализация, затем refactor и повторная verification. Это особенно полезно для agent-generated changes, потому что агент получает быстрый executable feedback вместо работы на уверенности.