130 lines
14 KiB
Markdown
130 lines
14 KiB
Markdown
---
|
||
title: '2.2 — Добавить workspace-scoped metadata artifacts'
|
||
type: 'feature'
|
||
created: '2026-08-26'
|
||
status: 'done'
|
||
baseline_revision: '497e1b740f7c319413da060fb2234ad63842c7dd'
|
||
review_loop_iteration: 0
|
||
followup_review_recommended: false
|
||
context:
|
||
- '_bmad-output/implementation-artifacts/epic-2-context.md'
|
||
warnings: [oversized]
|
||
deferred: []
|
||
---
|
||
|
||
<intent-contract>
|
||
|
||
## Intent
|
||
|
||
**Problem:** Immutable blobs уже существуют, но PostgreSQL не хранит изолированную по workspace source metadata. Без неё общий digest способен стать existence/MIME/size oracle, а upload и reconciliation не имеют строгого транзакционного контракта.
|
||
|
||
**Approach:** Добавить forward-only V12 schema и registry API с отдельными global blob records и workspace-owned source relations; реализовать scoped CRUD/list/detach, идемпотентный replay и verified read через `crank-artifacts` с безопасными typed outcomes.
|
||
|
||
## Boundaries & Constraints
|
||
|
||
**Always:** выполнять source lookup/mutation по authoritative `(workspace_id, source_id)`; хранить только canonical opaque artifact ref/digest и bounded metadata; фиксировать lifecycle transitions транзакционно; сначала получать scoped metadata, затем читать и проверять blob; возвращать одинаковый scoped not-found для чужого и отсутствующего source; сохранять предыдущие migration sources и checksums неизменными.
|
||
|
||
**Block If:** реализация требует ослабить workspace isolation, принимать caller-supplied physical ref как authority либо изменить immutable API/гарантии `crank-artifacts`.
|
||
|
||
**Never:** не менять `sprint-status.yaml`; не переиспользовать unscoped `operation_samples`/`descriptors`; не хранить raw source, caller path или mutable URL; не делать external refetch, filesystem cleanup, orphan reconciliation, HTTP/upload/parser/UI flow; не удалять metadata при missing/corrupt blob; не раскрывать digest/ref, size или MIME через foreign-scope ошибки.
|
||
|
||
## I/O & Edge-Case Matrix
|
||
|
||
| Scenario | Input / State | Expected Output / Behavior | Error Handling |
|
||
|----------|--------------|---------------------------|----------------|
|
||
| Create/replay | Новый scoped source либо точный повтор identity+metadata | Одна active relation; повтор возвращает тот же record без изменения lifecycle timestamps | Отличающиеся immutable поля дают typed conflict |
|
||
| Shared digest | Один blob привязан к разным workspace | Независимые source relations и один global blob record | Ни один workspace не узнаёт metadata другого |
|
||
| Scoped get/list | Свой, чужой или отсутствующий source; bounded cursor page | Только owned records в детерминированном порядке | Чужой/отсутствующий id — один `SourceNotFound` |
|
||
| Detach | Active, уже detached или конфликтно изменённый source | Conditional transition и timestamps фиксируются атомарно; exact retry идемпотентен | Concurrent/incompatible transition — typed conflict |
|
||
| Verified read | Metadata указывает на valid, missing, corrupt или wrong-size blob | Bytes возвращаются только после digest и size verification | Typed unavailable/integrity outcome без refetch, path/ref/raw bytes |
|
||
| Migration | Clean DB, V11 upgrade/replay, drift или injected failure | Ровно V12 schema+ledger либо полный rollback | Exact guard отклоняет drift и неожиданные V12-owned objects |
|
||
|
||
</intent-contract>
|
||
|
||
## Code Map
|
||
|
||
- `crates/crank-registry/src/migrations/authority.rs:17-19,174-245,275-375,474-503` — поднять canonical sequence до V12, добавить descriptor/apply/source-hash; V1–V11 не изменять.
|
||
- `crates/crank-registry/src/migrations/{artifact_metadata_v12.rs,artifact_metadata_v12.sql,schema_guard_v12.rs}` — новая append-only DDL и exact guard для V12 columns/defaults/constraints/indexes/relation kinds.
|
||
- `crates/crank-registry/src/migrations/{schema_guard.rs,owned_relations.rs}` и `crates/crank-registry/src/migrations.rs` — зарегистрировать V12 objects, pre-V12 absence и post-V12 validation.
|
||
- `crates/crank-registry/src/{model.rs,error.rs,lib.rs}` — typed source/blob records, IDs, sensitivity/lifecycle, cursor page и public errors/API.
|
||
- `crates/crank-registry/src/postgres/artifact_source.rs` и `crates/crank-registry/src/postgres/mod.rs` — scoped repository, row mapping и транзакционные create/get/list/detach operations; reuse `operation.rs` scoped `FOR UPDATE` и `product_event.rs` replay patterns.
|
||
- `crates/crank-artifacts/src/{model.rs,store.rs,error.rs}` — read-only boundary: canonical `ArtifactRef`, verified `ArtifactStore::read`, stable physical failures; workspace policy сюда не переносить.
|
||
- `crates/crank-registry/tests/integration/{artifact_sources.rs,migrations.rs,migrations/rollback.rs,common.rs}` — outer PostgreSQL/scoping/lifecycle/V12 evidence; legacy `operations_artifacts.rs` не менять.
|
||
- `docs/schemas/migration-sequence.json`, `docs/migrations.md`, `apps/admin-api/tests/migration_command.rs` — синхронизировать machine-readable и operator-visible migration contract до V12.
|
||
|
||
## Tasks & Acceptance
|
||
|
||
**Execution:**
|
||
- `crates/crank-registry/src/migrations/**`, `docs/schemas/migration-sequence.json`, `docs/migrations.md` — добавить V12 global blob + workspace source schema, bounded lifecycle/claim fields и exact drift guard; сохранить forward-only authority.
|
||
- `crates/crank-registry/src/{model.rs,error.rs,lib.rs}`, `src/postgres/{mod.rs,artifact_source.rs}` — реализовать typed scoped repository, replay/conflict, keyset pagination и detach transition; исключить global lookup из caller path.
|
||
- `crates/crank-registry/src/postgres/artifact_source.rs`, `crates/crank-registry/Cargo.toml` — скомпоновать scoped metadata lookup с `ArtifactStore::read` и explicit size check; redacted typed outcome должен остановить downstream processing.
|
||
- `crates/crank-registry/tests/integration/**`, `apps/admin-api/tests/migration_command.rs` — покрыть I/O matrix реальным PostgreSQL и filesystem store, включая cross-workspace, tamper, replay и rollback.
|
||
|
||
**Acceptance Criteria:**
|
||
- Given действующая V11 authority, when применяется V12 на clean либо upgraded database, then ledger и exact normalized schema содержат scoped source id, workspace FK, canonical digest/ref, size, MIME, sensitivity, relation lifecycle/timestamps и bounded global blob lifecycle/claim fields, а V1–V11 sources/checksums остаются неизменными.
|
||
- Given drift любого V12 column/type/nullability/default/constraint/index/relation kind либо неожиданный V12-owned object, when schema guard проверяет database, then проверка детерминированно отклоняет schema без substring matching; injected migration failure не оставляет частичных objects или ledger row.
|
||
- Given один physical digest и несколько workspace, when source создаётся, читается или перечисляется, then relations независимы, pagination bounded и детерминирована, а foreign id/ref даёт тот же `SourceNotFound`, что отсутствующий id, без metadata oracle.
|
||
- Given identical либо conflicting replay, when repository создаёт relation, then exact replay идемпотентен и сохраняет исходные lifecycle timestamps, а несовпадающие immutable metadata дают typed conflict без частичной записи.
|
||
- Given active или уже detached source, when detach повторяется либо конкурирует с изменением, then transition и timestamps проверяются под scoped transaction/lock, exact retry идемпотентен, а incompatible state даёт typed conflict; physical blob не удаляется.
|
||
- Given scoped metadata с valid, missing, corrupt или wrong-size blob, when verified read выполняется через реальный `ArtifactStore`, then только valid bytes возвращаются, остальные случаи дают bounded typed unavailable/integrity outcome без refetch, substitution, удаления metadata или раскрытия raw source/path/ref.
|
||
- Given полный registry integration suite, when выполняются clean/V11→V12/replay/tamper/rollback, scoped CRUD/list/detach, cross-workspace и verified-read scenarios, then тесты проходят последовательно и migration, boundary, formatting, lint и workspace gates остаются зелёными.
|
||
|
||
## Spec Change Log
|
||
|
||
## Review Triage Log
|
||
|
||
- Исправлено: создание metadata принимает только opaque `RegisteredArtifact`, поэтому знание чужого digest не создаёт workspace relation и не раскрывает global blob metadata.
|
||
- Исправлено: cursor связан с workspace, IDs/MIME/size валидируются до I/O, а физическое чтение выполняется через `spawn_blocking` после scoped lookup.
|
||
- Исправлено: exact detach replay проверяет исходную revision; detached/unavailable/missing/corrupt/wrong-size состояния возвращают bounded typed outcomes.
|
||
- Исправлено: V12 guard проверяет полный набор indexes, key/include columns, persistence/RLS/options, triggers, policies, timestamp precision и сохраняет literal/parenthesis semantics constraints.
|
||
- Добавлено evidence: conflicting digest/MIME/sensitivity replay, rollback без partial objects, page cap 100, cross-workspace cursor, invalid IDs и полный verified-read matrix.
|
||
- Отклонён как несвязанный scope: аудит произвольных функций и владельцев всей schema; V12 проверяет все объекты, непосредственно привязанные к своим relations.
|
||
|
||
## Design Notes
|
||
|
||
V12 разделяет physical и ownership state: global blob row keyed canonical digest/ref хранит verified size, storage lifecycle и nullable bounded claim token/expiry для Stories 2.3–2.4; source row keyed `(workspace_id, source_id)` хранит blob FK, MIME, sensitivity, active/detached state и timestamps. Claim fields создаются сейчас, но не изменяются cleanup-процессом в этой story. Repository сначала разрешает source в workspace, и только после этого получает physical ref; verified-read различает owner-visible `Unavailable` и `Integrity`, но сохраняет внешние diagnostics redacted.
|
||
|
||
## Verification
|
||
|
||
**Commands:**
|
||
- `cargo test -p crank-registry --test integration -- --test-threads=1` — PostgreSQL V12, scoped repository и verified-read matrix проходят.
|
||
- `cargo test -p crank-artifacts -- --test-threads=1` — immutable blob boundary не регрессировал.
|
||
- `cargo clippy -p crank-registry --all-targets --all-features -- -D warnings` — новые API и tests без lint warnings.
|
||
- `cargo fmt --all --check && just migration-contract-check && just rust-boundaries && just rust-code-health` — schema/docs/architecture conventions проходят.
|
||
- `just verify` — полный workspace regression gate проходит.
|
||
|
||
## Auto Run Result
|
||
|
||
- Review verdict: pass после одного patch pass; открытых findings и blockers нет.
|
||
- `cargo test -p crank-registry --test integration -- --test-threads=1`: 79 passed, 1 ignored (явно production-size test).
|
||
- `cargo test -p crank-artifacts -- --test-threads=1`: 28 passed.
|
||
- `cargo clippy -p crank-registry --all-targets --all-features -- -D warnings`: passed.
|
||
- `just migration-contract-check`, `just rust-boundaries`, `just rust-code-health`: passed.
|
||
- `just verify`: passed полностью, включая workspace build, Clippy и все default tests.
|
||
|
||
## Suggested Review Order
|
||
|
||
**Workspace ownership и verified read**
|
||
|
||
- Scoped repository объединяет replay, pagination, detach и fail-closed physical read.
|
||
[`artifact_source.rs:19`](../../crates/crank-registry/src/postgres/artifact_source.rs#L19)
|
||
|
||
- Opaque registration capability исключает caller-forged digest и size authority.
|
||
[`model.rs:75`](../../crates/crank-artifacts/src/model.rs#L75)
|
||
|
||
**V12 migration contract**
|
||
|
||
- Global blob и workspace relation разделяют physical и ownership state.
|
||
[`artifact_metadata_v12.sql:1`](../../crates/crank-registry/src/migrations/artifact_metadata_v12.sql#L1)
|
||
|
||
- Exact guard отклоняет structural и semantic drift зависимых объектов.
|
||
[`schema_guard_v12.rs:141`](../../crates/crank-registry/src/migrations/schema_guard_v12.rs#L141)
|
||
|
||
**Regression evidence**
|
||
|
||
- PostgreSQL/filesystem scenarios покрывают isolation, replay, lifecycle и integrity outcomes.
|
||
[`artifact_sources.rs:69`](../../crates/crank-registry/tests/integration/artifact_sources.rs#L69)
|
||
|
||
- Migration tests доказывают upgrade/replay, drift rejection и transactional rollback.
|
||
[`artifact_metadata.rs:69`](../../crates/crank-registry/tests/integration/migrations/artifact_metadata.rs#L69)
|