Files
crank/_bmad-output/implementation-artifacts/spec-2-7-openapi-normalizedir.md
T

11 KiB
Raw Blame History

title, type, created, status, baseline_commit, review_loop_iteration, context
title type created status baseline_commit review_loop_iteration context
2.7 — Преобразовать OpenAPI в детерминированный NormalizedIR feature 2026-08-29 done bc03c33387 0
_bmad-output/implementation-artifacts/epic-2-context.md

Intent

Problem: crank-import сразу проецирует source в Draft-кандидаты, поэтому часть OpenAPI semantics теряется молча, а findings и порядок не имеют устойчивого source contract.

Approach: Ввести между parsing и preview pure typed NormalizedIR с versioned config, stable IDs, coverage ledger и canonical serialization; preview строить adapter-слоем поверх IR.

Boundaries & Constraints

Always: Формат определяется по содержимому: JSON-first/YAML fallback; версии — только OpenAPI 3.0.x, 3.1.x, Swagger 2.0. Location — RFC 6901 pointer без excerpt; ID выводится из version/method/pointer. Порядок фиксирован. Limits: 256 KiB, depth 64, 50 000 nodes, collection 10 000, aliases 128, scalar 256 KiB. Каждый construct получает typed mapping либо finding. Parser не имеет I/O/domain dependencies. Новые jobs сохраняют normalizer/projection version; legacy jobs сохраняют v1 replay до expiry.

Ask First: Изменение публичных HTTP-полей 2.1, удаление legacy replay до истечения job TTL, новая production dependency либо перенос semantic mapping из Stories 2.8–2.5.

Never: Reference I/O; Draft/ImportPlan/domain mutation; silent drop construct; source digest/bytes/parser internals в HTTP; зависимость output от времени, hash-map order, workspace/request IDs.

I/O & Edge-Case Matrix

Scenario Input / State Expected Output / Behavior Error Handling
Supported source Три версии, YAML/JSON Typed IR: metadata, servers/base path, paths, methods, IDs, tags, schema/ref placeholders, ledger Ordered findings для неотображаемой semantics
Identity ambiguity Missing/duplicate operationId, reordered maps Stable METHOD path key и canonical suffix по method/path/pointer Finding связан с construct ID/location
Partial structural defect Один malformed endpoint среди валидных Валидные operations остаются в IR Blocker finding дефектного pointer; Apply остаётся запрещён последующим policy layer
Reference Local/external/cyclic $ref Typed unresolved reference сохраняет URI/pointer и location, без I/O Resolution не симулируется и не теряется
Invalid/hostile source Unsupported/root/no methods/limit excess Нет пустого success, panic или runaway work Bounded blocker без raw parser error/source
Replay/concurrency Те же bytes+digest+config многократно/параллельно Canonical IR и findings byte-for-byte равны Version mismatch fail-closed до mutation

Code Map

  • crates/crank-import/src/rest/model.rs:7-123 — добавить NormalizedIr, construct/location, typed spec/schema/ref/coverage; ImportPreview оставить redacted projection.
  • crates/crank-import/src/rest/normalize.rs:21-110 — разделить bounded decode, strict version dispatch, canonical normalization и preview projection; текущий eager resolve_local_ref оставить только legacy-v1 path.
  • crates/crank-import/src/rest/{openapi3.rs,swagger2.rs} — нормализовать source constructs независимо по endpoint; фиксировать unsupported/invalid semantics findings вместо silent skip.
  • crates/crank-import/src/rest/{naming.rs,payload.rs,recommendations.rs,schema.rs} — reuse naming/Draft projection; semantic resolution оставить 2.8–2.5.
  • crates/crank-import/tests/{unit.rs,fixtures/**} — заменить узкие inline examples versioned fixture/golden matrix и hostile/determinism regressions.
  • apps/admin-api/src/service/imports.rs:39-522 — передавать digest/config, сохранять versions/IR fingerprint, одинаково reparse preview/apply без digest в DTO.
  • apps/admin-api/tests/integration/{openapi_import.rs,openapi_source.rs} — доказать redaction, parser-version replay, drift fail-closed и отсутствие Draft при blocker/limit errors.
  • scripts/check-rust-boundaries.py, docs/testing-strategy.md — read-only conventions; crank-import остаётся pure crate без registry/artifact/app dependencies.

Tasks & Acceptance

Execution:

  • crates/crank-import/src/rest/{model.rs,normalize.rs,openapi3.rs,swagger2.rs,mod.rs} — bounded typed normalization, stable identity/location, coverage validation и canonical output трёх версий.
  • crates/crank-import/src/rest/{naming.rs,payload.rs,recommendations.rs,schema.rs} — построить backward-compatible redacted preview adapter поверх IR и сохранить будущую semantic работу typed placeholders/findings.
  • crates/crank-import/tests/{unit.rs,fixtures/**} — добавить YAML/JSON golden fixtures, ordering/duplicate/no-method/partial/ref/limit tests, deterministic generated-property cases и checked-in fuzz regressions.
  • apps/admin-api/src/service/imports.rs, apps/admin-api/tests/integration/{openapi_import.rs,openapi_source.rs} — version job parser contract, передать artifact digest без HTTP leakage и покрыть rolling replay/reparse/integrity behavior.

Acceptance Criteria:

  • Given любой supported verified source, when normalization завершается, then каждый распознанный construct присутствует в canonical typed IR либо связан с explicit ordered finding и coverage validator отклоняет gap.
  • Given одинаковые bytes, digest и config, when parser запускается повторно или конкурентно, then serialized IR/findings и public preview совпадают byte-for-byte.
  • Given legacy pending job или новая versioned job, when Apply reparses source после rollout, then используется соответствующая projection version либо запрос fail-closed до Draft mutation без ложного integrity verdict.
  • Given hostile/частично повреждённый документ, when validation срабатывает, then работа bounded, валидные endpoints сохранены, blocker redacted, panic/mutation отсутствуют.

Spec Change Log

Design Notes

NormalizedIR хранит source identity только для внутренней воспроизводимости; HTTP projection исключает digest. Canonical ordering: path lexical → fixed HTTP method rank → source pointer; findings: severity rank → construct ID → code. Schema composition и references представлены typed source nodes, но разрешаются только следующими Story. Legacy-v1 adapter изолирован и удаляется отдельным решением после максимального TTL.

Verification

Commands:

  • cargo test -p crank-import --all-targets — PASS, 45/45: fixture/property/fuzz-regression matrix, canonical ordering, limits, coverage и legacy replay.
  • cargo test -p admin-api --test integration -- --test-threads=1 — PASS, 70/70: rolling replay, redaction, parser-contract drift и no-Draft guarantees.
  • cargo fmt --all -- --check — PASS.
  • cargo clippy -p crank-import -p admin-api --all-targets -- -D warnings — PASS.
  • just rust-boundaries — PASS: crate/module/config/migration/metrics/execution boundaries сохранены.
  • just rust-code-health — Story 2.7 не добавляет превышений и все её Rust-модули меньше 1000 строк; общий gate остаётся красным только на двух pre-existing Story 2.1 baseline-файлах crates/crank-artifacts/src/housekeeping.rs (1119) и crates/crank-artifacts/tests/artifact_store.rs (1103), зафиксированных в deferred-work ledger.
  • git diff --check — PASS.

Suggested Review Order

Контракт NormalizedIR

  • Главная точка входа связывает bounded decode, canonicalization и строгую валидацию. normalize.rs:82

  • Versioned типы закрепляют identity, locations, schemas, references и coverage ledger. model.rs:270

  • Coverage validator доказывает отсутствие молча потерянных source constructs. normalize_coverage.rs:16

Парсинг и совместимость

  • OpenAPI 3 parser сохраняет валидные siblings и локализует malformed semantics. openapi3.rs:17

  • Swagger 2 parser реализует тот же deterministic contract без semantic resolution. swagger2.rs:17

  • Изолированный preview adapter сохраняет публичный DTO и legacy-v1 replay. normalize.rs:118

Admin apply boundary

  • Preview сохраняет parser versions и fingerprint только во внутреннем job payload. imports.rs:473

  • Apply fail-closed сверяет preview, IR fingerprint и parser contract до mutation. imports.rs:555

Доказательства

  • Recursive pointer test проверяет exact mapping каждого source-tree construct. coverage.rs:132

  • Version/syntax/concurrency matrix подтверждает byte-for-byte детерминизм IR. unit.rs:426

  • Integration regression запрещает Draft mutation при operation-level blocker. openapi_import.rs:510