Files
crank/_bmad-output/implementation-artifacts/1-1-capability-inventory.md
T

346 lines
36 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.1: Создать исполняемый контракт Capability Inventory
Status: done
<!-- Validation is optional but recommended: run bmad-create-story validate before dev-story. -->
## Story
As a владелец релиза,
I want иметь версионируемый и автоматически проверяемый формат Capability Inventory,
so that текущие и целевые продуктовые flows нельзя потерять, ошибочно объявить готовыми или вывести за Community scope.
## Requirements and Quality Mapping
- **Primary requirement:** FR-46.
- **Applicable NFRs:** NFR-S2 (secrets absent from reports/exports), NFR-S4 (bounded input/output and resource use), NFR-S8 (bounded valid UTF-8/JSON diagnostics plus malformed/oversized negatives), NFR-O5 (redaction regression for JSON/errors), NFR-C1 (no incidental Rust MSRV, Edition, dependency, workspace or wire-contract change; the owner-approved transitive advisory remediation recorded below is the sole narrow exception), NFR-C4 (new user-facing scope text is synchronized in RU and EN).
- **Architecture decisions:** AD-1 (existing executable boundary checks remain authoritative), AD-20/AR-29 (Inventory is release evidence foundation; first enabling change updates Community docs, project context, guardrails and tests; an allow marker cannot bypass the contract).
- **Primary risk:** E1-R-001, score 9 — a false or incomplete Inventory can hide product gaps and regressions.
## Acceptance Criteria
1. **Schema contract**
- **Given** утверждённые PRD, SPEC и Architecture Spine
- **When** создаётся schema Capability Inventory
- **Then** она требует для каждого flow уникальный ID, тип `ui | api | mcp`, связанный FR, пользовательский outcome, owner, статус реализации и ссылки на automated/manual evidence
- **And** поддерживает только `implemented | planned | gap | blocked`; последние три состояния не считаются pass.
2. **Fail-closed validator**
- **Given** machine-readable Capability Inventory
- **When** CI запускает validator
- **Then** отсутствующий обязательный FR, duplicate ID, неизвестный status/type, битая evidence-ссылка, отсутствующее обязательное поле или flow без owner завершают проверку ошибкой
- **And** validator выдаёт детерминированный, сортированный, bounded report без чувствительных данных.
3. **Community scope expansion without scope creep**
- **Given** намеренное расширение Community scope
- **When** обновляются executable scope guardrails
- **Then** `resources`, `prompts`, `tasks` и `load_runs` распознаются как разрешённые целевые возможности
- **And** `multi_workspace`, `enterprise_rbac`, `sso`, `non_rest_upstream` и `arbitrary_distributed_load_targets` остаются запрещены.
4. **New/untracked files are checked explicitly**
- **Given** новые или untracked файлы scope guardrails и Inventory
- **When** выполняется проверка Community scope
- **Then** новые файлы передаются scanner явно и покрываются positive/negative tests
- **And** текст `community-scope: allow=...` не позволяет обойти semantic Community contract.
5. **Documentation tells the truth**
- **Given** изменение executable Community boundary
- **When** Story завершается
- **Then** синхронно обновлены tracked Community documentation и локальный `_bmad-output/project-context.md`
- **And** Inventory и документация не утверждают, что planned target capabilities уже реализованы.
6. **Regression-safe completion**
- **Given** реализация Story
- **When** выполняются обязательные проверки
- **Then** проходят targeted Inventory tests, boundary/scope tests, canonical CI/release gates и `just verify`
- **And** Rust toolchain, dependency manifests, workspace boundaries, UI/runtime/database surfaces и существующие wire-контракты не изменяются попутно; допускается только явно одобренное владельцем transitive lockfile security remediation при полном `cargo deny` и `just verify` evidence.
## Tasks / Subtasks
- [x] **1. Создать versioned schema и минимальный canonical seed** (AC: 1, 3, 5)
- [x] Создать `docs/schemas/capability-inventory.schema.json` как JSON Schema Draft 2020-12 с `schema_version: 1`, product identity, обязательными полями `flows[]`, численными bounds из External Contract и закрытыми enum для type/status.
- [x] Описать structured evidence (`automated`, `manual`) с `minItems: 1` для каждого вида и закрытый capability-family vocabulary `tools | resources | prompts | tasks | load_runs`; не смешивать implementation status с качеством/типом evidence.
- [x] Создать `docs/capability-inventory.json` с минимальными честными entries для `resources`, `prompts`, `tasks`, `load_runs` в состоянии `planned`, `gap` или `blocked`; не выполнять полный brownfield baseline Story 1.2.
- [x] Связать seed с FR-46 и релевантными product FR, но в gate Story 1.1 требовать только явно зафиксированный начальный набор (`FR-46`); расширение до полного FR-1..FR-54 baseline принадлежит Story 1.2.
- [x] Для non-implemented entries использовать существующие tracked evidence контракта/плана: automated — `tests/unit/test_validate_capability_inventory.py`, manual — обновлённые `README.md`/`docs/intro.md`/`docs/en/README.md`; не ссылаться из canonical Inventory на `_bmad-output`, `/tmp`, build output или иной отсутствующий в clean checkout artifact.
- [x] Трактовать capability как семейство product/protocol surface, а не как перечень всех экранов/use cases: Story 1.2 представляет Operations, Agents, approvals, history и import отдельными flows с подходящим family value, не меняя schema.
- [x] **2. Реализовать stdlib-only validator CLI** (AC: 1, 2)
- [x] Создать `scripts/validate-capability-inventory.py` с `--root`, `--inventory`, `--schema` и repeatable `--required-fr`.
- [x] Читать и проверять schema/inventory как JSON без новой Python-зависимости; schema должна объявлять `https://json-schema.org/draft/2020-12/schema`, а semantic validator — обеспечивать тот же внешний контракт без попытки реализовать универсальный JSON Schema engine.
- [x] Проверять canonical schema по известным JSON pointers: dialect, required fields, enum и bounds должны совпадать с semantic constants; missing/divergent contract завершается `INVALID_SCHEMA_CONTRACT`, malformed schema — `INVALID_SCHEMA`. `--schema` не может быть декоративным аргументом.
- [x] Проверять обязательные поля, ID uniqueness, type/status/capability enums, owner/outcome/requirements и required-FR completeness.
- [x] Принимать `--inventory`, `--schema` и evidence только как normalized repository-relative logical paths к существующему regular non-symlink file внутри resolved `--root`; отклонять absolute path, `..`, directory, missing path и любой symlink.
- [x] Выдавать stable machine codes, включая `DUPLICATE_FLOW_ID`, `UNKNOWN_STATUS`, `UNKNOWN_FLOW_TYPE`, `MISSING_OWNER`, `MISSING_REQUIRED_FIELD`, `MISSING_REQUIRED_FR`, `BROKEN_EVIDENCE_LINK`, `FORBIDDEN_COMMUNITY_CAPABILITY`, `INVALID_JSON`, `INVALID_SCHEMA`, `INVALID_SCHEMA_CONTRACT`, `INPUT_TOO_LARGE`, `LIMIT_EXCEEDED`.
- [x] Сортировать machine diagnostics по `(code, json_pointer)` независимо от JSON ordering; ограничить полный stderr-report 65,536 bytes, включая deterministic truncation marker; не печатать raw inventory, user outcome/payload, secret canary, resolved host path или произвольное invalid value.
- [x] Success summary является CLI contract: `Capability inventory validation passed total=<n> implemented=<n> planned=<n> gap=<n> blocked=<n> pass=<n>`; `pass` равен только числу `implemented`.
- [x] **3. Укрепить executable Community boundary** (AC: 3, 4)
- [x] Расширить `scripts/check-community-scope.py`, сохранив текущие deterministic traversal, binary/default exclusions и exact same-line allow semantics.
- [x] Explicit input должен fail closed для missing, absolute/outside-root и symlink paths; после 4,096-byte binary probe текст сканируется streaming line-by-line без `read_bytes()` всего файла, а findings ограничены теми же `MAX_DIAGNOSTICS` и 65,536-byte report budget.
- [x] Разрешить exact target identifiers `resources`, `prompts`, `tasks`, `load_runs`, не ослабляя запреты текущего checker-а.
- [x] Сохранить безопасный default wrapper-а `scripts/check-community-scope.sh` для tracked-файлов; новые Story-файлы проверять отдельным explicit `--files` вызовом, не захватывая чужие локальные untracked paths (например `.agents/`).
- [x] Не исключать validator, Inventory или schema целиком. Каждое необходимое enforcement/fixture упоминание forbidden marker получает только узкую same-line annotation (`# community-scope: allow=sso` либо точный соответствующий marker); semantic validator всё равно обязан отвергать capability.
- [x] Добавить positive/negative regressions в `tests/unit/test_check_community_scope.py`, включая невозможность semantic allow-marker bypass и явную обработку existing outside-root path, absolute path, internal symlink и symlink-to-outside.
- [x] **4. Активировать ATDD-сценарии RED → GREEN** (AC: 1–5)
- [x] Сохранить подготовленный `tests/unit/test_validate_capability_inventory.py`; не пересоздавать его и не оставлять acceptance scenarios скрытыми за `@unittest.skip(RED_PHASE)` после реализации.
- [x] Активировать по одному сценарию, сначала наблюдать ожидаемый RED, затем реализовывать минимальное поведение до GREEN.
- [x] Сохранить исходные 10 contract scenarios и добавить отдельные active cases для malformed inventory/schema JSON, missing/wrong schema dialect/contract, document/collection/string overflow и stable codes `INVALID_JSON`, `INVALID_SCHEMA`, `INVALID_SCHEMA_CONTRACT`, `INPUT_TOO_LARGE`, `LIMIT_EXCEEDED`.
- [x] Исправить evidence containment fixture: создать реально существующий файл вне temporary root; отдельно проверить existing absolute path, internal symlink и symlink-to-outside. Missing-file failure не считается доказательством containment.
- [x] Усилить deterministic-report test: требовать непустой exact sorted prefix из `(code, json_pointer)`, ожидаемое число diagnostics и deterministic truncation marker; пустой список найденных flow diagnostics не может пройти тест.
- [x] Добавить active meta-test/guardrail, который через runtime/AST inspection других Story 1.1 test methods завершается ошибкой при любом `unittest.skip` decorator или `__unittest_skip__ == True`. Во время task-by-task TDD запускать конкретный method; полный module/CI обязан стать GREEN только после снятия всех skips и удаления больше не нужного RED marker/constant.
- [x] Удалить `PROJECT_CONTEXT` из committed canonical assertions и loops. В clean CI проверять tracked `README.md`, `docs/README.md`, `docs/intro.md`, `docs/en/README.md`, Inventory и schema; обновление ignored `_bmad-output/project-context.md` проверять отдельной локальной evidence-командой и фиксировать в Dev Agent Record, без conditional skip.
- [x] Для literals `sso`/`enterprise` и других enforcement fixtures использовать точные same-line Community annotations; добавить regression, что textual annotation подавляет только текстовый scanner, но не semantic Inventory verdict.
- [x] **5. Встроить canonical validation в tooling, CI и release** (AC: 2, 4, 6)
- [x] Добавить `capability-inventory-check` в `justfile` и включить его в `just verify`, не удаляя и не переставляя существующие Rust/scope gates без причины.
- [x] Добавить отдельный canonical Inventory step в `.gitea/workflows/ci.yml` после Python unit tests и до Rust gates.
- [x] В `.gitea/workflows/release.yml` добавить `python3 --version` в runner preflight, затем Python tooling, canonical Inventory и Community scope gates до Cargo/build/package, чтобы tag workflow не обходил Story contract.
- [x] Canonical command должен явно проверять `FR-46`; полный обязательный FR baseline вводит Story 1.2.
- [x] **6. Синхронизировать документацию и выполнить handoff checks** (AC: 4–6)
- [x] Обновить `README.md`, `docs/README.md`, `docs/intro.md`, `docs/en/README.md`, `CONTRIBUTING.md` и `scripts/README.md`: дать ссылки на Inventory/schema, объяснить четыре status semantics, синхронизировать новый пользовательский текст RU/EN, отделить «реализовано сейчас» от «разрешено как target» и описать explicit untracked scan.
- [x] Обновить локальный `_bmad-output/project-context.md`; не менять пользовательский `.gitignore` и не force-add ignored BMAD artifacts.
- [x] Явно передать scope scanner все NEW/UPDATE tracked paths до их staging/tracking.
- [x] Выполнить команды evidence из раздела Testing и убедиться, что в diff нет Cargo/npm/toolchain/wire/UI/runtime/database изменений, кроме явно одобренного security-only `Cargo.lock` remediation с полным compatibility gate.
### Review Findings
- [x] [Review][Patch][Medium] Security update применён после уточнения владельца: `event-listener` обновлён с 5.4.1 до 5.4.2 в `Cargo.lock`; `cargo deny` и полный `just verify` проходят без RUSTSEC-2026-0221.
- [x] [Review][Patch][High] Валидировать каждый explicit scope path до применения default exclusions; сейчас missing/symlink/traversal под `LICENSE`/`target/` проходит как успешно просканированный [scripts/check-community-scope.py:139]
- [x] [Review][Patch][High] Закрыть schema/semantic drift: проверять root/evidence required, типы, refs, minLength и остальные исполняемые schema keywords; malformed required arrays должны давать `INVALID_SCHEMA_CONTRACT`, а не `TypeError` [scripts/validate-capability-inventory.py:136]
- [x] [Review][Patch][High] Преобразовывать `ValueError`/`RecursionError` JSON parser в bounded `INVALID_JSON`/`INVALID_SCHEMA` вместо traceback [scripts/validate-capability-inventory.py:106]
- [x] [Review][Patch][High] Ограничить накопление diagnostics до `MAX_DIAGNOSTICS` с отдельным deterministic omitted counter до сортировки/rendering [scripts/validate-capability-inventory.py:300]
- [x] [Review][Patch][Medium] Отклонять duplicate JSON object members, чтобы security-significant поля не зависели от last-value-wins поведения parser [scripts/validate-capability-inventory.py:122]
- [x] [Review][Patch][Medium] Требовать точный integer `schema_version == 1`; Python boolean `true` не должен проходить как число 1 [scripts/validate-capability-inventory.py:139]
- [x] [Review][Patch][Medium] Помечать truncation внутри одного scope-файла; сейчас после 1000 findings остальные строки пропускаются без marker [scripts/check-community-scope.py:151]
- [x] [Review][Patch][Medium] Отклонять whitespace-only owner/user_outcome и синхронизировать это ограничение со schema contract [scripts/validate-capability-inventory.py:219]
- [x] [Review][Patch][Medium] Добавить заявленные `limit-1 / limit / limit+1` regressions для flow/collection/string/evidence bounds и новых fail-closed случаев [tests/unit/test_validate_capability_inventory.py:276]
#### Review Round 2 — 2026-08-08
- [x] [Review][Patch][High] Отклонять дополнительные assertion/applicator keywords в versioned schema: сейчас root `not: {}` или nested `const` инвертирует Draft 2020-12 contract, но semantic gate продолжает возвращать success [scripts/validate-capability-inventory.py:238]
- [x] [Review][Patch][High] Нормализовать forbidden identifiers перед scope matching: `EnterpriseRbac`, `MultiWorkspace`, `NonRestUpstream` и `ArbitraryDistributedLoadTargets` обходят snake/kebab/space patterns [scripts/check-community-scope.py:28]
- [x] [Review][Patch][Medium] Ограничить объём реально читаемого scope input, включая один newline-free text line, общий размер и количество файлов; output caps не предотвращают exhaustion памяти/времени [scripts/check-community-scope.py:147]
- [x] [Review][Patch][Medium] Запретить C0/control characters в explicit logical paths, иначе legal filename с newline может подделывать строки bounded stderr report [scripts/check-community-scope.py:122]
- [x] [Review][Patch][Medium] Перехватывать `OSError` при binary probe и text scan после path validation, чтобы concurrent replacement/deletion не приводил к traceback и раскрытию host path [scripts/check-community-scope.py:147]
- [x] [Review][Patch][Medium] Fail closed для invalid UTF-8 text вместо `errors="replace"`, иначе запрещённый marker можно разделить invalid byte и обойти scanner [scripts/check-community-scope.py:152]
- [x] [Review][Patch][Medium] Согласовать AC6/NFR-C1, Task 6 и Project Structure с явно одобренным security-only `Cargo.lock` exception и зафиксировать final explicit 16-file scan [Cargo.lock:1113]
- [x] [Review][Patch][Low] Выставлять single-file truncation только после обнаружения 1001-го finding; ровно 1000 findings сейчас ошибочно объявляются truncated [scripts/check-community-scope.py:167]
## Dev Notes
### Scope Boundary and Dependencies
- Это первый blocking element Wave 0 и всего critical path: `1.1 → 1.2 → 1.3 → 1.4 → 1.5 → 1.6`.
- Prerequisites отсутствуют. Story 1.2 зависит от созданных здесь schema/validator и выполняет полный фактический baseline существующих UI/Admin API/MCP flows.
- Story 1.1 создаёт executable contract, но **не** реализует Resources, Prompts, Tasks или Load Runs; не выполняет manual regression, MCP compatibility matrix, signed/content-addressed Evidence Manifest, RC signing или Habr Gate.
- Не добавлять UI/browser journey, Playwright/Pact, Rust crate, migration, endpoint, metric, deployment runtime config или новую dependency.
- `manual-only` в последующей Story 1.2 является характеристикой evidence, а не пятым implementation status.
### External Contract
Canonical paths established by ATDD:
```text
scripts/validate-capability-inventory.py
docs/capability-inventory.json
docs/schemas/capability-inventory.schema.json
```
Required flow fields:
```text
id, type, requirements, user_outcome, owner, status, capabilities,
evidence.automated, evidence.manual
```
- **Named limits:** `MAX_DOCUMENT_BYTES = 4_194_304` для каждого inventory/schema JSON; `MAX_FLOWS = 10_000`; `MAX_REQUIREMENTS_PER_FLOW = 64`; `MAX_CAPABILITIES_PER_FLOW = 16`; `MAX_EVIDENCE_LINKS_PER_KIND = 64`; ID/requirement/capability ≤128 Unicode code points, owner ≤256, user outcome и optional notes ≤4,096, repository-relative evidence path ≤1,024; `MAX_DIAGNOSTICS = 1_000`; stderr report ≤65,536 bytes вместе с truncation marker.
- Bounds задаются одновременно в schema и semantic constants и проверяются parity test. Boundary tests используют `limit-1`, `limit`, `limit+1`; существующий 500-flow stress corpus остаётся допустимым.
- Evidence collections `automated` и `manual` обе непустые. Для `planned/gap/blocked` они подтверждают контракт/план/известный пробел, но не превращают capability в implemented.
- Allowed capability-family vocabulary: `tools`, `resources`, `prompts`, `tasks`, `load_runs`. Любое иное значение fail closed; пять явно запрещённых Community capability kinds получают специализированный `FORBIDDEN_COMMUNITY_CAPABILITY`.
- Only `implemented` contributes to `pass`; `planned`, `gap`, and `blocked` must remain visibly non-passing.
- JSON object/array ordering has no product semantics. Human diagnostics must be stable and safe; machine codes are the integration contract.
- Draft 2020-12 is the current published JSON Schema version. Declare the dialect explicitly, but keep runtime validation stdlib-only to preserve Story NFR-C1/dependency constraints.
### Existing Code to Reuse and Preserve
- `scripts/check-community-scope.py` already provides the authoritative stdlib CLI with subprocess-backed tracked-file discovery, sorted explicit file traversal, narrow same-line allow directives, binary detection and safe path/line/code diagnostics. Extend it; do not create a competing scope checker.
- `tests/unit/test_check_community_scope.py` is the established stdlib `unittest` + temporary-root + subprocess pattern. Preserve its current six regressions.
- `justfile` already routes `tooling-test` and `community-scope-check` through `verify`; add the canonical gate without replacing `fmt-check`, `clippy`, `test`, dependency or boundary gates.
- `.gitea/workflows/ci.yml` invokes Python tests and scope checks directly rather than `just verify`; it needs a direct canonical step. `.gitea/workflows/release.yml` currently lacks Python/scope checks and must not publish around the new contract.
- Recent `9b1a739` is the closest repository pattern: contract-first artifact, closed vocabulary, bounded untrusted values, dedicated contract tests, boundary checker and docs in one compatible change.
### File Map
| Action | Path | Purpose |
|---|---|---|
| NEW | `scripts/validate-capability-inventory.py` | Deterministic stdlib validator CLI |
| NEW | `docs/capability-inventory.json` | Versioned canonical Inventory seed |
| NEW | `docs/schemas/capability-inventory.schema.json` | JSON Schema Draft 2020-12 contract |
| NEW/activate | `tests/unit/test_validate_capability_inventory.py` | Existing untracked 10-scenario RED scaffold |
| UPDATE | `scripts/check-community-scope.py` | Semantic/path-safe bounded Community guardrail |
| UPDATE | `tests/unit/test_check_community_scope.py` | Boundary and bypass regressions |
| UPDATE | `justfile` | Canonical Inventory recipe and `verify` integration |
| UPDATE | `.gitea/workflows/ci.yml` | Canonical gate in normal CI |
| UPDATE | `.gitea/workflows/release.yml` | No release bypass of tooling/scope/Inventory gates |
| UPDATE | `README.md` | Public current-vs-target scope and Inventory link |
| UPDATE | `docs/README.md` | Documentation index for Inventory/schema |
| UPDATE | `docs/intro.md` | RU Community current-vs-target scope |
| UPDATE | `docs/en/README.md` | EN Community current-vs-target scope (NFR-C4) |
| UPDATE | `CONTRIBUTING.md` | Contributor Community boundary and guardrail expectations |
| UPDATE | `scripts/README.md` | Contributor commands and explicit scan behavior |
| LOCAL UPDATE | `_bmad-output/project-context.md` | Agent guardrail; ignored by Git, not a clean-CI dependency |
### Security and Failure Rules
- Treat inventory, schema and evidence paths as untrusted input. Resolve containment against `--root`; never follow a symlink outside the repository.
- Explicitly named missing files must fail, not silently pass. Diagnostics use only bounded repository-relative logical paths or JSON pointers; do not expose resolved host paths, raw filenames supplied outside the contract, raw file content, arbitrary JSON values or credentials.
- Enforce every named document/collection/string/diagnostic limit before unbounded allocation or accumulation. Oversized or malformed JSON must terminate safely with valid UTF-8 output and a stable code.
- A textual `community-scope: allow` directive can suppress only the checker’s exact same-line textual fixture marker; it never changes semantic capability allow/deny decisions in Inventory validation.
- Do not exclude Inventory/schema from scope scanning. Narrowly justify test/source fixture markers; never introduce a broad exemption for forbidden product capability names.
### Testing and Evidence Commands
Activate one ATDD scenario at a time and retain RED/GREEN evidence in the Dev Agent Record.
```bash
# During RED/GREEN: run only the activated method; the full module remains red until all skips are removed
python3 -m unittest -v \
tests.unit.test_validate_capability_inventory.CapabilityInventoryValidatorTests.<activated_test>
# Final targeted Inventory contract: no skipped Story 1.1 tests permitted
python3 -m unittest discover -s tests/unit \
-p 'test_validate_capability_inventory.py' -v
# Existing and extended Community boundary regressions
python3 -m unittest discover -s tests/unit \
-p 'test_check_community_scope.py' -v
# Canonical artifact gate for Story 1.1
python3 scripts/validate-capability-inventory.py \
--root . \
--inventory docs/capability-inventory.json \
--schema docs/schemas/capability-inventory.schema.json \
--required-fr FR-46
# Before new files are tracked/staged: pass every NEW/UPDATE tracked path explicitly
python3 scripts/check-community-scope.py --root . --files \
scripts/validate-capability-inventory.py \
docs/capability-inventory.json \
docs/schemas/capability-inventory.schema.json \
tests/unit/test_validate_capability_inventory.py \
scripts/check-community-scope.py \
tests/unit/test_check_community_scope.py \
justfile \
.gitea/workflows/ci.yml \
.gitea/workflows/release.yml \
Cargo.lock \
README.md docs/README.md docs/intro.md docs/en/README.md \
CONTRIBUTING.md scripts/README.md
# Local-only project-context evidence; this file is intentionally ignored by Git
rg -n 'docs/capability-inventory.json|planned|gap|blocked' \
_bmad-output/project-context.md
# Full repository quality gate
just verify
```
- UI build/Playwright is N/A because Story has no UI change.
- Before completion, verify that no active Story 1.1 test remains skipped and that canonical validation is a direct CI **and** release prerequisite.
### Project Structure Notes
- Repository-level Python tooling belongs in `scripts/`; its stdlib tests belong in `tests/unit/`, matching the existing Community checker.
- Canonical user-facing artifacts belong under `docs/`; schema lives in the new `docs/schemas/` directory.
- The implementation creates no new Rust module or crate and changes no dependency manifest or npm lockfile. The owner-approved `Cargo.lock` resolution update `event-listener` 5.4.1 → 5.4.2 is the sole security-only exception and is covered by `cargo deny` plus full `just verify`.
- `_bmad-output/` is workflow state ignored by the current user-owned `.gitignore`. Preserve that choice; implementation artifacts remain local unless the owner separately changes repository policy.
- No dedicated UX specification is required for this non-UI foundation. The IR UX warning remains applicable before the first UI-heavy vertical Story.
### References
- [Source: `_bmad-output/planning-artifacts/epics.md`, Story 1.1 and Cross-Epic Dependencies]
- [Source: `_bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/prd.md`, 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-20, Consistency Conventions]
- [Source: `_bmad-output/planning-artifacts/implementation-readiness-report-2026-08-08.md`, Required Actions 3–4]
- [Source: `_bmad-output/project-context.md`, Testing Rules and Community Scope Expansion]
- [Source: `_bmad-output/test-artifacts/atdd-checklist-1-1-capability-inventory.md`, Contract Decisions and Implementation Handoff]
- [Source: `_bmad-output/test-artifacts/atdd-summary-1-1-capability-inventory.json`]
- [Source: `tests/unit/test_validate_capability_inventory.py`, RED acceptance scaffold]
- [JSON Schema Draft 2020-12](https://json-schema.org/draft/2020-12)
## Dev Agent Record
### Agent Model Used
GPT-5 Codex
### Implementation Plan
- Реализовать schema/canonical seed и stdlib validator contract-first, активируя acceptance tests по одному.
- Harden существующий Community scanner без нового параллельного guardrail.
- Встроить canonical validation в local/CI/release gates и синхронизировать RU/EN documentation.
- Завершить полным `just verify`, explicit scope scan и clean diff/file-list audit.
### Debug Log References
- Task 1 RED: canonical-artifact test failed because `docs/capability-inventory.json` was absent.
- Task 1 GREEN: canonical seed/schema assertions pass; both JSON documents parse successfully.
- Task 2 RED: activated validator contract failed because `scripts/validate-capability-inventory.py` was absent.
- Task 2 GREEN: structural/status/FR/evidence/redaction/schema-drift/limit suites and canonical command pass.
- Task 3 RED: existing scanner accepted forbidden `enterprise_rbac` and unsafe explicit paths.
- Task 3 GREEN: 12 scope regressions, 3 Inventory/scope contract scenarios and explicit Story file scan pass.
- Task 4 RED: tracked documentation scenario failed before Inventory links/status semantics were documented.
- Task 4 GREEN: 23 active acceptance scenarios pass; meta-guard confirms zero skipped Story tests.
- Task 5 RED: repository-contract test found no `capability-inventory-check` recipe or CI/release prerequisites.
- Task 5 GREEN: repository-contract test passes and both Gitea workflow files parse as YAML.
- Task 6 GREEN before review: 44 Python tests, canonical validator, explicit 15-file Community scan, `git diff --check` and full `just verify` passed with a temporary security lockfile update.
- Code review GREEN: all 9 functional review findings fixed; 53 Python tests, canonical validator, explicit Community scan, boundaries, code-health, fmt, clippy and the full Rust workspace suite pass.
- Security review GREEN: owner clarified that the dependency update belongs to review remediation; `event-listener` 5.4.2 is pinned in `Cargo.lock`, RUSTSEC-2026-0221 is cleared, and the final full `just verify` passes.
- Review Round 2 GREEN: all 8 findings fixed; 59 Python tests, canonical validator, explicit 16-file Community scan, dependency audit, fmt, clippy and the complete Rust workspace pass in the final `just verify`.
- Local-only evidence: `_bmad-output/project-context.md` contains the canonical Inventory link and non-passing status semantics; ignored BMAD artifacts were not force-added.
- User-owned `.gitignore` changes and untracked `.agents/` content were preserved and excluded from Story edits/scans.
### Completion Notes List
- Added a versioned Draft 2020-12 Capability Inventory schema and an honest planned-only canonical seed for Resources, Prompts, Tasks and Load Runs.
- Added a stdlib-only fail-closed validator with schema parity, closed vocabularies, repository-contained evidence, stable/redacted/bounded diagnostics and implemented-only pass semantics.
- Hardened the Community scope checker against path traversal, symlinks, missing files, semantic allow-marker bypass and unbounded reports while preserving tracked-only default behavior.
- Made the canonical validator mandatory in `just verify`, normal CI and release workflows; synchronized RU/EN contributor and product documentation.
- Completed every Story and repository quality gate. The only dependency change is the authorized transitive security remediation `event-listener` 5.4.1 → 5.4.2; no UI/runtime/database/wire contract changed.
- Closed strict-schema parity and scope-scanner bypass/resource-boundary findings with active regressions; no review action items remain.
### File List
- `.gitea/workflows/ci.yml` (modified)
- `.gitea/workflows/release.yml` (modified)
- `CONTRIBUTING.md` (modified)
- `Cargo.lock` (modified: security remediation `event-listener` 5.4.1 → 5.4.2)
- `README.md` (modified)
- `docs/README.md` (modified)
- `docs/capability-inventory.json` (new)
- `docs/en/README.md` (modified)
- `docs/intro.md` (modified)
- `docs/schemas/capability-inventory.schema.json` (new)
- `justfile` (modified)
- `scripts/README.md` (modified)
- `scripts/check-community-scope.py` (modified)
- `scripts/validate-capability-inventory.py` (new)
- `tests/unit/test_check_community_scope.py` (modified)
- `tests/unit/test_validate_capability_inventory.py` (new/activated)
- `_bmad-output/project-context.md` (local ignored update)
## Change Log
- 2026-08-08 — Implemented Story 1.1 executable Capability Inventory contract, Community guardrails, CI/release gates, documentation and security audit remediation; moved to review.
- 2026-08-08 — Applied all 9 code-review patches; reverted the security-only lockfile update by owner decision and deferred RUSTSEC-2026-0221 remediation to a separate dependency change; Story returned to in-progress.
- 2026-08-08 — Owner clarified that the security update is part of review remediation; applied `event-listener` 5.4.2, cleared RUSTSEC-2026-0221, passed full `just verify`, and returned Story to review.
- 2026-08-08 — Fresh adversarial review fixed all 8 actionable findings, dismissed 7 out-of-scope/noise findings, passed final full verification, and completed Story 1.1.