Files
crank/_bmad-output/implementation-artifacts/1-2-baseline-flows.md
T

310 lines
39 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
baseline_commit: c30461cc92491ebe3d527e125a1657b73fa67006
---
# Story 1.2: Зафиксировать фактический baseline существующих flows
Status: done
<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->
## Story
As a владелец продукта,
I want получить проверенный baseline всех существующих возможностей Crank,
so that функциональные недоработки и регрессии видны до начала расширения продукта.
## Acceptance Criteria
1. **Полный machine-readable inventory.** Given validator и schema из Story 1.1, when выполняется инвентаризация текущего brownfield-продукта, then canonical inventory перечисляет все известные пользовательские и протокольные flows UI, Admin API и MCP для Operations, Agents, Auth Profiles/Upstreams/Secrets, MCP- и approval-ключей, approvals, test execution, YAML/OpenAPI import/export, Logs и Usage; каждый flow имеет стабильный ID, observable contract, `FR-*`, owner, implementation status и ссылки на текущее evidence. Все FR-1…FR-54 представлены: существующие flows описаны детально и честно, будущие Resources/Prompts/Tasks/Load Runs и другие target flows остаются `planned`, `gap` или `blocked`, но не `implemented` без доказательств.
2. **Проверенный REST→MCP happy path.** Given текущий Community stack, when администратор создаёт простую REST Operation, выполняет Admin test-run, публикует полученную из API точную версию, привязывает её к полученной из API Agent revision, публикует Agent, создаёт MCP key и вызывает Tool из MCP-клиента, then весь путь завершается успешно хотя бы в одном реальном запуске на текущем Community stack. Evidence фиксирует только безопасные operation ID/version, Agent ID/revision, команды/предусловия и нормализованный outcome; credential, raw key, cookie, sensitive header/query/body, приватный payload и host path не попадают в stdout, error, evidence или документацию. `not_run`/`blocked` допустимы как честный промежуточный baseline, но Story остаётся незавершённой до реального успешного запуска.
3. **Автоматизированное evidence без ложного pass.** Given существующие suites, when trusted collector запускает allowlisted commands либо принимает bounded machine report, then targeted Rust tests, `just verify`, UI build и применимый Playwright smoke связываются с конкретными flow IDs и содержат command identity, source revision/environment class, source-report SHA-256 и вычисленный verdict. Canonical `pass` нельзя вводить вручную. `failed`, retry-pass/`flaky`, `skipped`, `not_run`, missing result или malformed evidence никогда не нормализуются в `pass`.
4. **Ограниченный exploratory UI baseline.** Given основные Community-экраны, when выполняется bounded exploratory pass, then для каждого применимого flow зафиксированы happy, loading, empty, error и доступный recovery state. Отсутствующий state отмечается `gap`/`not_run`, а stale-response, RU/EN/localization и unsafe-output проблемы получают стабильный finding ID и связь с flow; этот pass не выдаётся за полный manual regression Epic 8.
5. **Дефекты блокируют честно.** Given найденный дефект, when он добавляется в baseline results, then запись содержит стабильный ID, severity, bounded reproducible steps, affected observable contract, flow IDs, owner и next evidence/action. Critical или High автоматически требует `blocked` у каждого связанного flow; агрегированный статус Epic или зелёный unrelated suite не может скрыть блокировку.
6. **Implementation status и evidence verdict разделены.** Given отсутствие automated evidence, then flow получает `evidence_mode=manual_only` с retained manual result и `next_evidence` либо `implementation_status=gap` с названным next evidence. Closed axes: `implementation_status=implemented|planned|gap|blocked`; `execution_verdict=pass|fail|blocked|skipped|flaky|not_run`; `evidence_mode=automated|manual_only`. `manual_only` не является implementation status, `gap` не является execution verdict, и только `implemented + automated + pass` считается полным baseline pass.
7. **Baseline заморожен и проверяем.** Given завершённая инвентаризация, then inventory, required-surface contract, outcome taxonomy, manual checklist и results имеют общий `baseline_version` и lowercase SHA-256 exact tracked file bytes в canonical manifest; validator fail-closed проверяет version parity, schema, checksums, cross-links, verdict/status/defect invariants и bounded/redacted diagnostics. Story 1.2 гарантирует self-consistency одного snapshot; immutable predecessor chain/signature принадлежит 8.1. Любое последующее изменение snapshot требует новой baseline version, нового evidence и пересчитанного manifest. Story 1.2 не заменяет RC-wide CI gates (8.2) или полный manual regression (8.3).
## Tasks / Subtasks
- [x] Task 1 — Зафиксировать baseline contract до сбора результатов (AC: #1, #3, #5, #6, #7)
- [x] Создать `docs/capability-baseline/outcome-taxonomy.json` с тремя независимыми closed axes и truth table: implementation status, execution verdict и evidence mode; полный pass только `implemented + automated + pass`.
- [x] Создать `docs/capability-baseline/required-surfaces.json`: нормативный closed список обязательных surface groups/stable flow IDs и минимальной гранулярности. Включить Operations lifecycle/test/import/export, Agents/catalog/bindings, Auth Profiles, Upstreams, Secrets, MCP keys, approval keys, approvals, Logs, Usage, auth/workspace и MCP transport/list/call.
- [x] Создать `docs/schemas/capability-baseline.schema.json` с Draft 2020-12, закрытыми объектами, обязательными полями и численными bounds для taxonomy, results, defects, commands, paths, strings и коллекций. Не добавлять новую dependency и не писать универсальный JSON Schema engine.
- [x] Создать `docs/capability-baseline/manual-checklist.md` с versioned bounded checklist (10–16 charters) для актуальных основных UI flows и состояний happy/loading/empty/error/recovery/stale/RU-EN/safe-output. Для N/A требуется причина; пустое поле не является pass.
- [x] Создать `docs/capability-baseline/results.json` с version, source revision/environment class, command results, flow mappings, manual results и defect ledger. Хранить summary/verdict, а не raw console/network/payload dump.
- [x] Создать `docs/capability-baseline/manifest.json` с общим baseline version, normalized repo-relative paths и lowercase SHA-256 exact tracked bytes для inventory, required-surfaces, taxonomy, checklist и results; manifest не хеширует сам себя.
- [x] Task 2 — Реализовать fail-closed baseline validator (AC: #1, #3, #5, #6, #7)
- [x] Создать stdlib-only `scripts/validate-capability-baseline.py`; reuse path, JSON, deterministic-report и redaction patterns из `scripts/validate-capability-inventory.py`, не дублировать Community scanner или product runtime.
- [x] Проверять Draft 2020-12 baseline contract, duplicate JSON keys, strict UTF-8, repo-relative normalized existing regular non-symlink paths, manifest SHA-256, unique IDs, known inventory flow IDs и normative required-surfaces completeness/granularity.
- [x] Проверять invariants: Critical/High ⇒ все affected flows `blocked`; axes не смешиваются; unknown/missing/flaky/skipped/not-run не pass; полный pass только `implemented + automated + pass`; manual-only требует retained result/`next_evidence`; planned target не получает fabricated pass.
- [x] Ограничить каждый JSON input 4 MiB, checklist 1 MiB, diagnostics 1000 и итоговый stderr 65,536 bytes; задать bounds в schema, ловить `OSError`, `UnicodeDecodeError`, `JSONDecodeError`, `ValueError`, `RecursionError`; не печатать raw invalid value, resolved host path или пользовательский payload.
- [x] Выдавать стабильные machine codes и JSON pointers. Минимальный набор: `INVALID_JSON`, `INVALID_SCHEMA_CONTRACT`, `INPUT_TOO_LARGE`, `BROKEN_ARTIFACT_LINK`, `CHECKSUM_MISMATCH`, `UNKNOWN_FLOW_ID`, `MISSING_FLOW_EVIDENCE`, `NON_PASS_RECORDED_AS_PASS`, `SEVERE_DEFECT_FLOW_NOT_BLOCKED`, `UNSAFE_EVIDENCE`, `BASELINE_VERSION_MISMATCH`.
- [x] Task 3 — Создать RED→GREEN unit/contract tests baseline tooling (AC: #1, #3, #5, #6, #7)
- [x] Создать `tests/unit/test_validate_capability_baseline.py` по stdlib `unittest`/temporary-root pattern Story 1.1; никаких оставшихся `skip(RED_PHASE)`.
- [x] Покрыть canonical success, missing/unknown flow, stale checksum, version mismatch, duplicate IDs/keys, malformed/oversized/deep JSON, symlink/traversal/absolute/control-character paths, unknown schema keyword и schema/semantic drift.
- [x] Покрыть exact verdict semantics: fail/flaky/skipped/not_run/missing не pass; manual-only требует retained manual result и next evidence; Critical/High defect при non-blocked flow fail-closed; Medium/Low остаются traceable.
- [x] Покрыть deterministic sorting, bounded/redacted output, canary credentials/headers/query/JSON/YAML/host paths, limit-1/limit/limit+1 и отсутствие traceback.
- [x] Обновить `tests/unit/test_validate_capability_inventory.py`: canonical inventory покрывает FR-1…FR-54, обязательные surface groups и только tracked regular evidence paths; существующие Story 1.1 regression tests сохранить.
- [x] Task 4 — Реализовать trusted collector/sanitizer evidence (AC: #3, #6, #7)
- [x] Создать stdlib-only `scripts/collect-capability-baseline.py`: запускать только closed allowlist command IDs либо принимать bounded source reports; flow mappings берутся из reviewed config, canonical verdict вычисляется из exit/status/retries/skips, не из hand-authored `pass`.
- [x] Playwright JSON писать в ignored temporary path, проверять размер/UTF-8/JSON, вычислять source-report SHA-256 и переносить только sanitized counts/statuses. Retry-pass классифицировать `flaky`; raw stdout/errors/attachments/screenshots/trace/video/host paths не переносить.
- [x] Для Rust/Python/build/smoke фиксировать command ID, bounded exit summary, source revision/environment class и flow IDs. Missing report/command, signal, timeout и non-zero exit дают non-pass.
- [x] Создать `tests/unit/test_collect_capability_baseline.py`: allowlist, exit/retry/skip truth table, missing/malformed/oversized reports, deterministic sanitized output, secret/URL/host-path canaries и запрет hand-authored pass.
- [x] Collector пишет candidate results; manifest пересчитывается отдельным шагом только после review candidate. Collector не получает credentials и не печатает environment values.
- [x] Task 5 — Инвентаризировать фактические flows без исправления продукта (AC: #1, #5, #6)
- [x] Обновить `docs/capability-inventory.json`: детальные current UI/API/MCP flows для Operations lifecycle/test/YAML/OpenAPI, Agents/catalog/bindings, Auth Profiles/Upstreams/Secrets, MCP/approval keys, approvals, Logs/Usage и auth/workspace settings; сохранить четыре существующие planned entries.
- [x] Моделировать flow как пользовательский/протокольный outcome, не как строку на каждый HTTP endpoint. Operations/Agents/approvals/history/import относятся к capability family `tools`; не расширять enum `tools|resources|prompts|tasks|load_runs` доменными псевдо-capabilities.
- [x] Сопоставить существующие contracts с FR-1…FR-6, не объявляя эти FR полностью hardened. FR-7…FR-54 связать с минимальными честными target/gap/planned/blocked entries только для traceability; детальная декомпозиция и feature implementation остаются owning stories.
- [x] Для каждого existing flow задать owner, observable outcome и links на конкретные tests/results/checklist. Suite-level ссылка без contract-level mapping не считается достаточной.
- [x] Все обнаруженные функциональные проблемы записать в results/defect ledger; production `apps/**`, `crates/**`, migrations и UI behavior в этой Story не чинить.
- [x] Task 6 — Дополнить существующий brownfield product smoke (AC: #2, #3)
- [x] Обновить `scripts/authenticated-product-smoke.py`, не создавать второй smoke: после create Operation выполнить `/operations/{id}/test-runs`, проверить safe success outcome, затем publish exact version, bind/publish exact Agent revision и MCP `tools/list`/`tools/call`.
- [x] Получать Operation version и Agent revision из create/publish/get API responses и передавать через helper return values; hard-coded `1` в publish/bind/evidence запрещён.
- [x] Ввести единый bounded redacting error formatter для HTTP, MCP и cleanup: только stable stage/code/status; никогда full URL, response body, tool list или raw MCP error. Safe summary содержит IDs/revisions/stages/verdict/command identity, но не key/session/payload.
- [x] Выполнять cleanup в `finally` после создания первого asset; сохранить `CRANK_PRODUCT_SMOKE_KEEP_ASSETS`. Cleanup warning не подменяет основной verdict и проходит через safe formatter.
- [x] Обновить `tests/unit/test_authenticated_product_smoke.py`: request ordering, test-run contract, exact revisions, safe summary и redaction canaries. Не обращаться к внешнему публичному API.
- [x] Запустить smoke на текущем Community stack. Отсутствие окружения/credential фиксируется `not_run`/`blocked`, но является HALT для завершения Story до реального успешного запуска.
- [x] Task 7 — Собрать automated evidence и выполнить bounded UI pass (AC: #3, #4, #5, #6)
- [x] Запустить targeted Admin API/MCP/Rust tests и связать test cases с flow IDs; отдельно выполнить `just verify`.
- [x] Выполнить UI build. Playwright запускать с pinned `@playwright/test` 1.61.1, `--forbid-only`, JSON result в ignored temp file и fail-on-flaky semantics; collector переносит sanitized summary/report SHA, raw report/build output не коммитить.
- [x] Выполнить применимые smoke specs: login, operations/wizard, agents, keys, secrets/auth configuration, logs/usage и workspace/settings. Skip/retry-pass с flaky classification не записывать как pass.
- [x] Пройти manual checklist. Decision table: observed success/failure ⇒ pass/fail; применимый, но не выполненный state ⇒ not_run; отсутствующий обязательный contract ⇒ implementation gap; N/A допустим только для неприменимого by-design state с bounded reason. Проверить stale responses, RU/EN и safe DOM/error sinks.
- [x] Обновить defect ledger и implementation statuses по severity invariant; не исправлять найденные product gaps в рамках этой Story.
- [x] Task 8 — Подключить canonical baseline gate (AC: #1, #3, #7)
- [x] Обновить `justfile`: `capability-inventory-check` требует FR-1…FR-54 и запускает оба validator; сохранить порядок и все существующие `just verify` gates.
- [x] Обновить `.gitea/workflows/ci.yml`: Python tooling tests → inventory validator → baseline validator → Community scope → существующие Rust/UI gates. Не полагаться только на `just verify`.
- [x] Обновить `.gitea/workflows/release.yml`: `python3 --version`, tooling/inventory/baseline/scope gates выполняются до build/package/publish; failed evidence или checksum drift блокирует release.
- [x] Не добавлять Cargo/npm dependency, не менять Rust toolchain, package/lock files, DB schema или wire contract. Существующий owner-approved `Cargo.lock` diff Story 1.1 не расширять.
- [x] Task 9 — Документация и handoff (AC: #1, #4, #6, #7)
- [x] Обновить `README.md`, `docs/README.md`, `docs/intro.md`, `docs/en/README.md`, `CONTRIBUTING.md`, `scripts/README.md`: baseline paths, команды, status-versus-verdict semantics, checksum regeneration/verification и правило evidence-backed status changes.
- [x] User-facing утверждения синхронизировать RU/EN. Не рекламировать planned Resources/Prompts/Tasks/Load Runs или отсутствующий UI state как реализованные.
- [x] Локально обновить ignored `_bmad-output/project-context.md` устойчивыми правилами, но не делать его CI prerequisite и не force-add.
- [x] Явно просканировать каждый NEW/UPDATE tracked path через Community scope checker; canonical artifacts/schema/validator целиком не исключать.
- [x] Task 10 — Финальная проверка и честный completion record (AC: #1–#7)
- [x] Выполнить targeted Python tests, smoke unit tests, targeted Rust tests, UI build/Playwright, оба canonical validators, explicit Community scope scan и `just verify`.
- [x] Финализировать inventory/required-surfaces/taxonomy/checklist/results, проверить общий baseline version, затем хешировать exact bytes и записать manifest последним; любое content change требует bump version. Повторно проверить checksum и deterministic output.
- [x] Проверить `git diff --check`, полный file list и отсутствие случайных dependency/toolchain/runtime/DB изменений, generated reports, screenshots, credentials и raw payloads.
- [x] В Dev Agent Record перечислить фактически выполненные команды и verdict. Недоступное окружение, skipped/flaky/missing evidence и найденные блокеры оставить явно non-pass.
### Review Findings
- [x] [Review][Patch][High] Выполнить bounded exploratory UI baseline сейчас: пройдены все 12 charters; observed verdicts, next evidence и найденные defects сохранены без raw browser artifacts. [docs/capability-baseline/manual-checklist.md]
- [x] [Review][Patch][High] Versioned schema contract и exact `full_pass` валидируются fail-closed; semantic/schema drift покрыт regressions. [docs/schemas/capability-baseline.schema.json]
- [x] [Review][Patch][High] Required surfaces закрыты exact group/flow membership, uniqueness, union и полнотой всех current flows. [scripts/validate-capability-baseline.py]
- [x] [Review][Patch][High] Checklist и `manual_results` связаны exact IDs/flows, axes, retained result и `next_evidence`. [scripts/validate-capability-baseline.py]
- [x] [Review][Patch][High] Accepted evidence ограничено command allowlist, unique IDs/hashes, common provenance, typed known flows и только implemented status. [scripts/validate-capability-baseline.py]
- [x] [Review][Patch][High] Collector всегда пишет `evidence_mode`, а fatal/malformed/non-object Playwright results классифицирует non-pass. [scripts/collect-capability-baseline.py]
- [x] [Review][Patch][High] `just-verify` больше не выдаётся за UI evidence; UI flow mapping оставлен только у UI build/Playwright runs. [docs/capability-baseline/results.json]
- [x] [Review][Patch][High] Smoke требует `isError=false` и ожидаемый safe mapped health outcome. [scripts/authenticated-product-smoke.py]
- [x] [Review][Patch][High] Smoke не печатает base URL/private endpoint. [scripts/authenticated-product-smoke.py]
- [x] [Review][Patch][Medium] Malformed workspace/key/tools responses проходят через bounded stable errors без traceback. [scripts/authenticated-product-smoke.py]
- [x] [Review][Patch][Medium] Stateful MCP session завершается DELETE в `finally`; реальный run подтвердил нулевой остаток sessions/assets. [scripts/authenticated-product-smoke.py]
- [x] [Review][Patch][Medium] Canonical manifest artifacts обязаны быть tracked в Git и воспроизводимы в clean checkout. [scripts/validate-capability-baseline.py]
- [x] [Review][Patch][Medium] Все фактически выполненные subtasks синхронизированы с completed parent Tasks. [_bmad-output/implementation-artifacts/1-2-baseline-flows.md]
## Dev Notes
### Scope Boundary
- Story 1.2 — evidence/tooling-only Wave 0. Она наблюдает и замораживает текущий brownfield baseline, но не исправляет product defects и не меняет production Rust/UI/Admin API/MCP/DB surfaces.
- Hard prerequisite Story 1.1 завершён: использовать его canonical inventory, strict schema validator, deterministic bounded diagnostics и Community scope guardrail. Не ослаблять существующие validations ради заполнения baseline.
- Строгий порядок Epic 1: `1.1 → 1.2 → 1.3 → 1.4 → 1.5 → 1.6`. Typed config, migration authority, canonical correlation и typed metrics начинаются только после принятого baseline.
- Story 1.2 не завершает весь gate «Baseline Frozen»: Reference Workload и initial/signed Evidence Manifest имеют отдельную downstream ownership. Она также не заменяет 8.1, 8.2 и 8.3.
### Canonical Artifact Design
```text
docs/capability-inventory.json
│ flow IDs / implementation status / FR / owner
▼
docs/capability-baseline/results.json ─── defects + automated/manual verdicts
│
├── required-surfaces.json
├── outcome-taxonomy.json
├── manual-checklist.md
└── manifest.json ── SHA-256 всех пяти canonical inputs
```
- Сохранить inventory `schema_version: 1` и существующий closed schema, если AC можно выразить companion artifacts. Не добавлять evidence verdict/checksum поля в inventory и не превращать `manual_only` в implementation status.
- Manifest — единственный checksum index; lowercase SHA-256 вычисляется по exact tracked bytes, manifest не self-hash. Общий `baseline_version` имеет bounded `YYYY.MM.DD.N` format и совпадает во всех baseline artifacts; любое content change требует нового version и manifest. Immutable predecessor/signature добавляются только в 8.1.
- Canonical evidence links только repo-relative, tracked, existing, regular, non-symlink. Запрещены `_bmad-output`, `/tmp`, `target`, `node_modules`, generated Playwright HTML/trace/video/screenshot и absolute host paths.
- `required-surfaces.json` является normative completeness contract. Current flows достаточно мелкие, чтобы один failing contract не скрывался общей записью «Admin API работает», но не дублируют каждый route. Stable flow ID отражает outcome, например `api-operation-test-run`, `mcp-published-tool-call`, `ui-operation-yaml-import`.
### Existing Surfaces and Reuse Map
- **UI:** login/logout; Operations catalog/filter/delete; OpenAPI preview/create; wizard create/edit/version/test/publish/archive, sample upload/draft generation, YAML import/export; Agents CRUD/bind/publish/unpublish/archive/tool-search; MCP/approval keys create/list/revoke/delete/one-time reveal; Secrets; Auth Profiles/Upstreams within wizard; Logs/detail + approvals; Usage; workspace/profile/password/settings.
- **Admin API:** authoritative routes in `apps/admin-api/src/app.rs`; cover auth/session/profile/password, capabilities/workspaces, Operations lifecycle/test/samples/draft/quality/YAML/OpenAPI, Agents/bindings/catalog/keys, Auth Profiles/Upstreams/Secrets, export, logs/approvals/usage.
- **MCP:** current Streamable HTTP GET/POST/DELETE; initialize/initialized/ping; `tools/list`, `tools/call`; session/SSE/JSON negotiation; scoped catalog/tool-search; approval list/get/approve/deny and elicitation. Inventory observed revisions only; do not broaden protocol implementation.
- **Existing smoke:** extend `scripts/authenticated-product-smoke.py`; it already handles login, workspace resolution, Operation create/publish, Agent bind/publish, one-time MCP key, initialize, list, call and cleanup. Missing Admin test-run and explicit Operation version/Agent revision evidence are the Story 1.2 gaps.
- **Automated evidence:** Admin Operation/Agent tests in `apps/admin-api/tests/integration/operations_agents.rs`; secret/import/auth in `secrets_import_auth.rs`; OpenAPI in `openapi_import.rs`; access/keys/logs/usage in `community_access_usage.rs`; MCP transport/catalog/approvals/search in `apps/mcp-server/tests/integration/**`; UI specs in `apps/ui/tests/e2e/`.
### Security, Reliability and Compatibility Guardrails
- Applicable NFRs: NFR-S1, S2, S4, S6, S7, S8, O5 and C1. Baseline capture must remain default-deny, secret-safe, bounded, closed-contour and fail-closed where mandatory evidence is absent.
- Never store credentials, raw one-time keys, auth cookies, sensitive request/response payloads, private endpoint query data or resolved host paths. Commands use environment-variable names/placeholders, never values.
- Preserve Story 1.1 limits/patterns: strict UTF-8 and duplicate-key detection; bounded JSON/report; deterministic sorting; safe machine codes/pointers; validate paths before exclusions; reject absolute/traversal/control/symlink paths; catch malformed/deep JSON without traceback.
- Preserve Rust 1.96.1, Edition 2024, pinned npm packages including `@playwright/test` 1.61.1, current workspace/crate direction, Alpine concatenation and `window.Crank*` UI contract. No new dependency is required.
- Playwright baseline must distinguish retry-pass/flaky from stable pass. Use existing CLI/report capabilities; do not upgrade Playwright in this Story. `just verify` does not run UI build/E2E, so both remain explicit completion evidence.
- PostgreSQL remains durable source of truth; Valkey is optional/rebuildable. Baseline records observed behavior and gaps but does not alter persistence or failure semantics.
### Test and Evidence Commands
Targeted first; exact Rust test filters may be adjusted only after listing current test names, and any missing filter is non-pass evidence:
```bash
python3 -m unittest discover -s tests/unit -p 'test_validate_capability_inventory.py' -v
python3 -m unittest discover -s tests/unit -p 'test_validate_capability_baseline.py' -v
python3 -m unittest discover -s tests/unit -p 'test_authenticated_product_smoke.py' -v
cargo test -p admin-api --test integration
cargo test -p mcp-server --test integration
cd apps/ui && npm ci && npm run build
tmp_report="$(mktemp)" && cd apps/ui && npx playwright test \
login.spec.js operations.spec.js wizard.spec.js agents.spec.js \
api-keys.spec.js secrets.spec.js logs-usage.spec.js workspace-settings.spec.js \
--project=chromium --workers=1 --forbid-only --fail-on-flaky-tests --reporter=json >"$tmp_report"
cd ../.. && python3 scripts/collect-capability-baseline.py \
--playwright-report "$tmp_report" --output <candidate-results>
# CRANK_STAGING_ADMIN_EMAIL/CRANK_STAGING_ADMIN_PASSWORD already provisioned
just authenticated-product-smoke <community-base-url>
python3 scripts/validate-capability-inventory.py --root . \
--inventory docs/capability-inventory.json \
--schema docs/schemas/capability-inventory.schema.json \
$(for n in $(seq 1 54); do printf -- '--required-fr FR-%s ' "$n"; done)
python3 scripts/validate-capability-baseline.py --root . \
--manifest docs/capability-baseline/manifest.json \
--schema docs/schemas/capability-baseline.schema.json
python3 scripts/check-community-scope.py --root . --files <every NEW/UPDATE tracked path>
just verify
git diff --check
```
Do not paste secret values into shell history or committed results. Collector records environment variable names only. Delete the temporary raw Playwright report after the sanitized candidate is verified.
### Project Structure Notes
Expected NEW tracked files:
- `docs/capability-baseline/outcome-taxonomy.json`
- `docs/capability-baseline/required-surfaces.json`
- `docs/capability-baseline/manual-checklist.md`
- `docs/capability-baseline/results.json`
- `docs/capability-baseline/manifest.json`
- `docs/schemas/capability-baseline.schema.json`
- `scripts/validate-capability-baseline.py`
- `scripts/collect-capability-baseline.py`
- `tests/unit/test_validate_capability_baseline.py`
- `tests/unit/test_collect_capability_baseline.py`
Expected UPDATE tracked files:
- `docs/capability-inventory.json`
- `tests/unit/test_validate_capability_inventory.py`
- `scripts/authenticated-product-smoke.py`
- `tests/unit/test_authenticated_product_smoke.py`
- `justfile`
- `.gitea/workflows/ci.yml`
- `.gitea/workflows/release.yml`
- `README.md`
- `docs/README.md`
- `docs/intro.md`
- `docs/en/README.md`
- `CONTRIBUTING.md`
- `scripts/README.md`
Local ignored update: `_bmad-output/project-context.md`; не force-add и не использовать как canonical/CI evidence.
Do not modify for this Story: `docs/schemas/capability-inventory.schema.json`, production `apps/**` кроме existing smoke script outside apps, `crates/**`, migrations, Cargo/npm manifests or locks, Rust toolchain and runtime/wire/DB/UI behavior. Если фактическая реализация требует такой change, остановиться и оформить correct-course/downstream defect вместо скрытого scope expansion.
### Previous Story Intelligence
- Story 1.1 завершилась двумя adversarial review rounds. Сохранить её fixes: strict schema-key allowlist, exact integer version (boolean invalid), duplicate JSON rejection, bounded one-line/file scans, fail-closed path resolution, correct truncation accounting, whitespace rejection и no traceback.
- Текущий inventory содержит четыре target entries и `pass=0`; это seed, а не доказательство отсутствия shipped Tools. Story 1.2 должна добавить фактические current flows и не удалять future Community intent.
- `just verify`, CI и release вызывают inventory guardrails напрямую; новый baseline validator подключается аналогично, а не заменяет существующий gate.
- Story 1.1 имеет owner-approved unrelated `Cargo.lock` security remediation. Это исключение не является разрешением расширять lockfile diff в Story 1.2.
- Рабочее дерево содержит незакоммиченные изменения Story 1.1. Preserve их; не перезаписывать и не откатывать чужие изменения.
### Latest Technical Information
- Использовать pinned Playwright 1.61.1. JSON reporter даёт structured result, `--forbid-only` запрещает случайные focused tests, `--fail-on-flaky-tests` делает retry-pass non-green; retries/statuses необходимо перенести в taxonomy без потери смысла.
- Official references: [Playwright CLI](https://playwright.dev/docs/test-cli), [Reporters](https://playwright.dev/docs/test-reporters), [Retries](https://playwright.dev/docs/test-retries). Не менять package version в рамках Story.
### References
- [Source: `_bmad-output/planning-artifacts/epics.md` — Epic 1, Cross-Epic Dependencies, Story 1.2]
- [Source: `_bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/prd.md` — FR-1…FR-6, FR-46, §§5.3–5.5, §§6–7]
- [Source: `_bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/addendum.md` — Community scope and evidence contract]
- [Source: `_bmad-output/planning-artifacts/architecture/architecture-crank-2026-08-03/ARCHITECTURE-SPINE.md` — AD-1, AD-19, AD-20, testing/security conventions]
- [Source: `_bmad-output/planning-artifacts/implementation-readiness-report-2026-08-08.md` — Required Actions 3–4]
- [Source: `_bmad-output/implementation-artifacts/1-1-capability-inventory.md` — completed contract, review findings, handoff]
- [Source: `_bmad-output/project-context.md` — Community boundaries, testing and artifact rules]
- [Source: `docs/capability-inventory.json`, `docs/schemas/capability-inventory.schema.json`, `scripts/validate-capability-inventory.py`]
- [Source: `apps/admin-api/src/app.rs`, `scripts/authenticated-product-smoke.py`, `apps/ui/playwright.config.js`]
## Dev Agent Record
### Agent Model Used
GPT-5 Codex
### Debug Log References
- Baseline source revision: `c30461cc92491ebe3d527e125a1657b73fa67006`.
- Default Playwright stack exposed two Medium harness defects: premature PostgreSQL readiness and incomplete child-process cleanup. Both are retained as `DEF-BL-001`/`DEF-BL-002`; the accepted run used the existing external-PostgreSQL mode after database readiness.
- Bounded manual exploration reproduced `DEF-UI-001` (stale response), `DEF-UI-002` (mixed localization) and High `DEF-UI-003` (credential-shaped API error rendered into browser DOM). The five affected flows are honestly `blocked`; remediation remains in their owning hardening stories.
### Completion Notes List
- Frozen baseline `2026.08.09.1`: 30 inventory flows, 18 current `implemented`, 5 current `blocked` by High `DEF-UI-003`, and 7 future target flows kept `planned`; FR-1…FR-54 and every normative surface group are represented.
- Added separate implementation/evidence axes, normative required surfaces, bounded manual checklist/results, exact-byte SHA-256 manifest, strict Draft 2020-12 contract, fail-closed validator and trusted report collector.
- Extended the existing authenticated product smoke with Admin test-run, API-derived Operation version/Agent revision, safe bounded errors, cleanup in `finally`, and sanitized summary. A real Community-stack REST→MCP create/test/publish/bind/list/call run passed.
- Automated evidence passed: Admin API integration 30/30, MCP integration 31/31, UI build, selected Chromium Playwright 21/21 with no retry/skip, and complete `just verify`. All 12 bounded manual charters were executed; 3 passed and 9 failed with traceable next evidence. This baseline does not replace Epic 8 regression.
- Final gates passed after review patches: 86 Python tooling tests, inventory validator with FR-1…FR-54, baseline checksum/schema validator, 29-file explicit Community scan, repository-wide 484-file Community scan, dependency/security audit with 0 vulnerabilities, fmt, Clippy and all Rust tests. UI build and `git diff --check` passed.
- Raw Playwright/smoke/collector temporary reports and the exact test PostgreSQL container were removed after sanitized hashes/results were frozen. No Story 1.2 Cargo/npm/toolchain/runtime/DB change was introduced; the pre-existing Story 1.1 lockfile/security diff was preserved unchanged.
### File List
- `.gitea/workflows/ci.yml`
- `.gitea/workflows/release.yml`
- `CONTRIBUTING.md`
- `README.md`
- `docs/README.md`
- `docs/capability-baseline/manifest.json`
- `docs/capability-baseline/manual-checklist.md`
- `docs/capability-baseline/outcome-taxonomy.json`
- `docs/capability-baseline/required-surfaces.json`
- `docs/capability-baseline/results.json`
- `docs/capability-inventory.json`
- `docs/en/README.md`
- `docs/intro.md`
- `docs/schemas/capability-baseline.schema.json`
- `justfile`
- `scripts/README.md`
- `scripts/authenticated-product-smoke.py`
- `scripts/collect-capability-baseline.py`
- `scripts/validate-capability-baseline.py`
- `tests/unit/test_authenticated_product_smoke.py`
- `tests/unit/test_collect_capability_baseline.py`
- `tests/unit/test_validate_capability_baseline.py`
- `tests/unit/test_validate_capability_inventory.py`
- `_bmad-output/project-context.md` (local ignored update only)
## Change Log
- 2026-08-09: Implemented and froze Story 1.2 capability baseline; added validated evidence contracts/collector, expanded current-flow inventory, hardened authenticated product smoke, wired CI/release gates, recorded real automated evidence and moved Story to review.
- 2026-08-09: Applied all code-review patches, executed all 12 manual charters, recorded High `DEF-UI-003` and blocked affected flows, reran a clean REST→MCP smoke and every mandatory gate, then moved Story to done.