chore(bmad): preserve planning and acceptance artifacts in Git
This commit is contained in:
1 parent
fed5b7dfb3
commit
ea3b71cb5e
93 files changed
+20696
No files matched your search
@@ -0,0 +1,358 @@
|
||||
---
|
||||
baseline_commit: c30461cc92491ebe3d527e125a1657b73fa67006
|
||||
---
|
||||
|
||||
# Story 1.4: Учредить versioned migration authority
|
||||
|
||||
Status: done
|
||||
|
||||
## Story
|
||||
|
||||
As an оператор,
|
||||
I want безопасный механизм последовательного изменения schema,
|
||||
so that новые capability tables добавляются без изменения выпущенного baseline.
|
||||
|
||||
## Strategic Intent
|
||||
|
||||
Story 1.4 завершает четвёртый элемент Wave 0 foundation. Она не добавляет пользовательскую capability, а делает все будущие durable capabilities безопасными: одна authority владеет DDL, выпущенная схема не переписывается, startup не мутирует БД, а несовместимое состояние диагностируется до readiness. После этой Story Resources, Prompts, Tasks, traces и Load Runs могут добавлять append-only migrations, не создавая новых независимых ledger/runner.
|
||||
|
||||
**Requirement:** FR-43
|
||||
**Architecture:** AD-16
|
||||
**Applicable NFR:** NFR-R2, NFR-S2, NFR-S4, NFR-S7, NFR-S8, NFR-C1, NFR-C3.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
1. **Единая authority и immutable baseline**
|
||||
- Given brownfield migration inventory
|
||||
- When определяется canonical runner
|
||||
- Then `crank-registry` является единственным владельцем migration sequence и DDL
|
||||
- And существующий core baseline version `1`, ledger checksum `crank-community-baseline-v1`, его SQL/данные и порядок не изменяются
|
||||
- And legacy core, MCP-session и `RegistryExtension` ledgers полностью инвентаризируются и сверяются до первой committed mutation.
|
||||
|
||||
2. **Append-only checksummed sequence**
|
||||
- Given новая schema migration
|
||||
- When owning Story добавляет durable field/table
|
||||
- Then она получает уникальную monotonic `i64` version, стабильное имя, lowercase SHA-256 exact source bytes, phase `expand|migrate|contract` и compatibility metadata
|
||||
- And sequence не допускает duplicate/gap/reorder, неизвестную phase, non-transactional DDL или изменение checksum опубликованной version
|
||||
- And каждое применение выполняется одной transaction под одним canonical PostgreSQL transaction-level advisory lock.
|
||||
|
||||
3. **Controlled migration command, read-only startup**
|
||||
- Given fresh, legacy либо outdated database
|
||||
- When запускаются `admin-api` или `mcp-server`
|
||||
- Then они выполняют только read-only compatibility verification и не создают/изменяют table, ledger, index или data row
|
||||
- And DDL применяет только отдельная команда `crank-migrate`, использующая database-only typed config projection без Admin/MCP/session/master-key/bootstrap secrets
|
||||
- And Community Compose запускает migration job до обоих сервисов и допускает их startup только после успешного завершения job.
|
||||
|
||||
4. **Brownfield consolidation без потери данных**
|
||||
- Given database с любым допустимым сочетанием legacy core v1, MCP-session v1 и extension ledger
|
||||
- When controlled migration выполняет consolidation
|
||||
- Then authority сохраняет legacy ledgers readable, переносит проверенное происхождение в canonical audit и добавляет checksum extension entries
|
||||
- And существующие workspace, Operation, Agent, key, approval, history, session и extension data сохраняются byte/row-equivalent
|
||||
- And отсутствие legacy ledger отличается от повреждённого/неизвестного ledger и обрабатывается детерминированно.
|
||||
|
||||
5. **Fail-closed preflight и recovery contract**
|
||||
- Given partial sequence, checksum mismatch, unknown/future version, missing applied version, modified legacy ledger либо incompatible phase/window
|
||||
- When preflight/startup/controlled migration проверяет schema
|
||||
- Then процесс завершается до product listener/readiness с bounded safe diagnostic: stable code, stage, version и recovery action
|
||||
- And diagnostic не содержит database URL, credentials, raw SQL, row values, host paths или unbounded driver error
|
||||
- And automatic destructive rollback, down migration, ledger rewrite и `--force` bypass отсутствуют.
|
||||
|
||||
6. **Expand/migrate/contract и N/N-1 foundation**
|
||||
- Given future storage evolution
|
||||
- When migration plan объявляется
|
||||
- Then contract требует `expand → bounded/resumable migrate/backfill → contract`, owner и explicit N/N-1 readable window
|
||||
- And `contract` migration не может быть применена без закрытого compatibility window/evidence
|
||||
- And Story 1.4 создаёт executable metadata/guardrails, но не заявляет полную upgrade/rollback qualification Story 7.2.
|
||||
|
||||
7. **PostgreSQL 16 evidence**
|
||||
- Given canonical runner suite
|
||||
- When проверяются fresh, legacy baseline, legacy MCP sessions, already-current, repeated, concurrent, checksum-corrupt, partial, future-version и injected-failure states
|
||||
- Then sequence, checksums, audit и diagnostics детерминированы; repeated apply idempotent; concurrent runners сериализованы
|
||||
- And injected DDL/ledger failure полностью откатывает transaction и сохраняет pre-existing data
|
||||
- And app startup tests доказывают отсутствие mutation, а controlled command доказывает migration-before-readiness.
|
||||
|
||||
8. **Regression и release gates**
|
||||
- Given завершённая реализация
|
||||
- When выполняются targeted tests и repository gates
|
||||
- Then проходят migration contract/unit/integration tests, PostgreSQL 16 fresh/brownfield/concurrency suites, Compose config, Community REST→MCP smoke и `just verify`
|
||||
- And baseline v1 checksum/source guard, Cargo/npm/toolchain/wire audit и explicit Community scope scan проходят без unrelated dependency/version changes.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Не реализовывать backup/PITR, master-key restore/rotation, drain/restart upgrade, full N/N-1 qualification или destructive contract migration: это Stories 7.2 и 7.7–7.9.
|
||||
- Не добавлять таблицы Resources, Prompts, Tasks, traces или Load Runs; Story создаёт authority для будущих owning stories.
|
||||
- Не использовать SQLx `_sqlx_migrations` как четвёртый ledger и не вводить второй migration framework. SQLx 0.9 остаётся PostgreSQL transport; canonical contract принадлежит `crank-registry`.
|
||||
- Не менять HTTP/MCP/UI wire contracts и не добавлять UI.
|
||||
- Не удалять legacy ledgers после consolidation и не изменять существующий baseline v1 ради упрощения реализации.
|
||||
|
||||
## Tasks / Subtasks
|
||||
|
||||
- [x] Task 1 — Зафиксировать brownfield inventory и immutable baseline guard (AC: 1, 4, 8)
|
||||
- [x] Перечислить фактические ledgers: `__crank_core_migrations`, `__crank_mcp_migrations`, `__crank_ext_migrations`; их columns, locks, known versions/checksums и owning code.
|
||||
- [x] Перенести baseline v1 в изолированный модуль без изменения SQL statement sequence и ledger checksum.
|
||||
- [x] Добавить executable source digest/contract test, который блокирует любое изменение baseline SQL при сохранённом ledger checksum.
|
||||
- [x] Зафиксировать legacy MCP v1 checksum `mcp-transport-sessions-v1`; extension row без сопоставимой зарегистрированной migration считать incompatible, не выдумывать checksum.
|
||||
|
||||
- [x] Task 2 — Создать canonical migration model в `crank-registry` (AC: 1, 2, 5, 6)
|
||||
- [x] Ввести закрытые typed descriptors: version/name/source checksum/phase/compatibility/backfill policy.
|
||||
- [x] Валидировать sequence до DB I/O: strictly increasing contiguous versions, unique names, SHA-256 format, transactional-only, bounded metadata.
|
||||
- [x] Ввести typed `MigrationStatus`, `MigrationPreflight`, `MigrationDiagnostic` и stable codes минимум для `schema_missing`, `migration_required`, `checksum_mismatch`, `partial_sequence`, `future_version`, `legacy_conflict`, `lock_timeout`, `apply_failed`.
|
||||
- [x] Display/JSON diagnostics должны быть deterministic, valid UTF-8/JSON, ≤65,536 bytes и не отражать raw SQL/DB/driver values.
|
||||
|
||||
- [x] Task 3 — Реализовать canonical runner и consolidation migration (AC: 1, 2, 4–6)
|
||||
- [x] Использовать один постоянный 64-bit lock ID и `pg_advisory_xact_lock`; lock живёт ровно до commit/rollback transaction.
|
||||
- [x] До mutation собрать полный legacy/canonical snapshot; любой conflict завершает transaction без committed DDL.
|
||||
- [x] На fresh DB применить неизменный baseline v1, затем consolidation v2; на legacy DB импортировать проверенный v1 без повторного baseline DDL.
|
||||
- [x] V2 создаёт canonical append-only ledger/audit, переносит verified legacy provenance, централизует MCP session schema и оставляет legacy ledgers readable.
|
||||
- [x] Повторный запуск не меняет audit timestamps/rows; unknown/future/corrupt state не нормализуется автоматически.
|
||||
- [x] Backfill API должен быть bounded/resumable по cursor+batch и транзакционным на batch; v2 не должен выполнять unbounded product-data backfill.
|
||||
|
||||
- [x] Task 4 — Удалить schema writes из runtime paths (AC: 3–5)
|
||||
- [x] `PostgresRegistry::connect*` создаёт pool и вызывает только compatibility verifier; `migrate()`/implicit apply из service-facing API удалить.
|
||||
- [x] `PostgresTransportSessionStore::from_pool/connect*` только проверяет canonical compatibility/session schema; локальный MCP runner удалить.
|
||||
- [x] `apply_extension_migrations` больше не исполняет DDL; extension migrations регистрируются через canonical authority с обязательным checksum/metadata.
|
||||
- [x] Boundary gate должен находить прямые schema writes/legacy runners за пределами canonical migration module, включая новые и untracked Rust files.
|
||||
|
||||
- [x] Task 5 — Добавить controlled `crank-migrate` command (AC: 3, 5)
|
||||
- [x] Добавить отдельный binary edge в package `admin-api` либо отдельный minimal app; production choice: binary `crank-migrate`, authority остаётся в `crank-registry`.
|
||||
- [x] Расширить `crank-config` process enum database-only projection `Migrator`; не требовать master/session/bootstrap/MCP secrets и не добавлять новый env reader.
|
||||
- [x] Поддержать только `preflight`, `plan` и `apply`; default — `preflight`, mutation требует явного `apply`. Не добавлять `down`, `force`, arbitrary SQL/path input.
|
||||
- [x] Exit codes и stdout/stderr machine contract детерминированы; secret/error redaction проверяется canary tests.
|
||||
|
||||
- [x] Task 6 — Встроить migration job в Community deployment (AC: 3, 8)
|
||||
- [x] Admin image содержит `crank-migrate`; root и `deploy/community` Compose используют one-shot job с restart disabled и health/dependency gate.
|
||||
- [x] `admin-api` и `mcp-server` зависят от `service_completed_successfully`; они не получают authority выполнять DDL самостоятельно.
|
||||
- [x] Images profile сохраняет те же semantics; минимальный deployment остаётся PostgreSQL-only корректным.
|
||||
- [x] CI/release выполняют contract/preflight/fresh+brownfield migration tests до image smoke/package publication.
|
||||
|
||||
- [x] Task 7 — Документировать operator contract (AC: 5, 6, 8)
|
||||
- [x] Создать `docs/migrations.md`: inventory, `preflight → backup → apply → verify`, failure codes, recovery without rollback, append-only authoring rules.
|
||||
- [x] Обновить deployment/runtime/contributor/scripts docs и RU/EN indexes; не заявлять готовность Story 7.2/backup/upgrade.
|
||||
- [x] Зафиксировать machine-readable canonical sequence/metadata, generated или checked из Rust authority; handwritten duplicate table запрещена.
|
||||
|
||||
- [x] Task 8 — Реализовать test matrix и evidence (AC: 7, 8)
|
||||
- [x] Pure tests: descriptor validation, digest exactness, ordering/gaps/duplicates/phases/windows, bounded/redacted diagnostics.
|
||||
- [x] PostgreSQL 16: fresh, baseline-only, legacy MCP, extension mapping, current/repeat, concurrent, corrupt checksum, partial/future, rollback after injected failure, data preservation.
|
||||
- [x] App/CLI subprocess: empty/outdated/corrupt startup performs zero DDL; migrate command uses only DB config; no listener readiness before compatible schema.
|
||||
- [x] Compose: root/source/images config and real migration-job ordering; authenticated REST→MCP smoke remains green.
|
||||
- [x] Final: `cargo fmt --all --check`, strict Clippy, `just verify`, `git diff --check`, explicit scan of every NEW/UPDATE path, no skipped/flaky/missing acceptance evidence.
|
||||
|
||||
### Review Findings
|
||||
|
||||
- [x] [Review][Patch] Включить все version-specific mutations v2 в exact-byte source bundle и независимо закрепить digest опубликованных migrations, чтобы одновременное изменение Rust/SQL и generated JSON не проходило append-only gate [crates/crank-registry/src/migrations/authority.rs:158]
|
||||
- [x] [Review][Patch] Считать fresh только БД без любой owned relation; проверять canonical schema fingerprint (schema/relkind/columns/types/nullability/defaults/constraints/indexes), включая orphan MCP ledger/session states и current-schema qualification [crates/crank-registry/src/migrations/authority.rs:361]
|
||||
- [x] [Review][Patch] Ввести закрытый registry legacy extension descriptors с exact `(name, version, checksum)` mapping и восстановить безопасный canonical registration path вместо принятия произвольного 64-hex provenance [crates/crank-registry/src/migrations/authority.rs:552]
|
||||
- [x] [Review][Patch] Проверять core/canonical/legacy audit metadata и конфликтующие audit rows до mutation; заменить безусловный `ON CONFLICT DO NOTHING` на exact-equality semantics и ограничить ledger reads [crates/crank-registry/src/migrations/authority.rs:407]
|
||||
- [x] [Review][Patch] Связать executable migration implementations с descriptors обобщённым dispatch/registry, чтобы append v3 не мог пройти contract validation и остаться невыполненным [crates/crank-registry/src/migrations/authority.rs:197]
|
||||
- [x] [Review][Patch] Сделать compatibility window и contract evidence типизированными и исполнимыми; добавить bounded cursor+batch resumable backfill contract без заявления полной Story 7.2 qualification [crates/crank-registry/src/migrations/authority.rs:47]
|
||||
- [x] [Review][Patch] Сохранить optional migration `version` в CLI JSON, реализовать/согласовать `schema_missing`, различать настоящий lock timeout от storage failure и нормализовать любые startup/SQLx errors в bounded safe diagnostics [apps/admin-api/src/bin/crank-migrate.rs:18]
|
||||
- [x] [Review][Patch] Усилить PostgreSQL evidence: настоящий rollback при первом v2 DDL на v1, representative brownfield row equivalence и Admin/MCP subprocess snapshots для fresh/outdated/corrupt DB без mutation/listener [crates/crank-registry/tests/integration/migrations.rs:272]
|
||||
- [x] [Review][Patch] Вызывать `MigrationAuthority::validate_sequence()` в `crank-migrate plan/--check`, чтобы синхронно повреждённые Rust descriptors и JSON не проходили gate [apps/admin-api/src/bin/crank-migrate.rs:73]
|
||||
- [x] [Review][Patch] Исправить/удалить dead Docker dependency stage, проверить clean `--target deps`, и включить `crank-migrate` в binary release artifact/checksums [apps/admin-api/Dockerfile:1]
|
||||
- [x] [Review][Patch] Ввести настоящий database-only config scope для migrator, строго согласовать URL-vs-POSTGRES components с Compose и валидировать host/database/user до любых side effects [crates/crank-config/src/migrator.rs:23]
|
||||
- [x] [Review][Patch] Расширить sole-DDL-owner gate на все PostgreSQL schema-changing forms, SQL assets, include/concat/sqlx migration markers и canonical/legacy ledger writers; добавить negative fixtures для tracked/untracked paths [scripts/check-rust-module-boundaries.sh:56]
|
||||
- [x] [Review][Patch] Закрыть обходы env boundary через grouped aliases, build.rs/non-src production targets и symlinks; default scan должен fail closed [scripts/check-config-boundaries.py:34]
|
||||
- [x] [Review][Patch] Проверять root/source/images Compose в CI и release и блокировать publication fresh PostgreSQL-16 image-stack smoke с доказанным `migrate -> readiness` ordering [.gitea/workflows/release.yml:121]
|
||||
- [x] [Review][Patch] Добавить bounded retry/backoff для one-shot migrator и сделать документированный source Compose deployment работоспособным с локальным либо явно обязательным external PostgreSQL [deploy/community/docker-compose.yml:18]
|
||||
- [x] [Review][Patch] Переписать migration runbook на исполнимые source/Compose commands и порядок `preflight -> verified backup -> apply -> verify`, документировать exit 2 и полный stable-code/recovery contract [docs/migrations.md:5]
|
||||
- [x] [Review][Patch] Добавить factual brownfield inventory трёх legacy ledgers: columns, historical locks, known versions/checksums, owners и legacy extension shape без выдуманного provenance [docs/migrations.md:16]
|
||||
- [x] [Review][Patch] Убрать опасные обещания автоматического image rollback после schema migration и совет немедленно восстанавливать БД при checksum mismatch; сначала проверять immutable application/release match [docs/deployment.md:187]
|
||||
- [x] [Review][Patch] Отразить one-shot migrate job в deployment topology, добавить английский operator contract либо явно маркировать RU-only ссылку и исправить дублирующий heading scripts docs [docs/deployment.md:5]
|
||||
- [x] [Review][Patch] Исправить acceptance bookkeeping: отметить фактически выполненные subtasks, снять ложные completion claims, явно просканировать все NEW/UPDATE paths и записать точные evidence commands/results [1-4-versioned-migration-authority.md:88]
|
||||
- [x] [Review][Defer] Не включать предшествующее owner-approved изменение `event-listener` в scope Story 1.4; явно атрибутировать его baseline Story 1.1 [Cargo.lock:1113] — deferred, pre-existing
|
||||
|
||||
## Dev Notes
|
||||
|
||||
### Current Brownfield State
|
||||
|
||||
- `crates/crank-registry/src/migrations.rs` owns a 721-line baseline function, advisory lock `0x43_52_41_4E_4B`, ledger `__crank_core_migrations`, version `1`, checksum `crank-community-baseline-v1`. It currently performs DDL from every `PostgresRegistry::connect*` call.
|
||||
- `crates/crank-community-mcp/src/session.rs` independently owns lock `0x4352_414E_4B4D_4350`, ledger `__crank_mcp_migrations`, checksum `mcp-transport-sessions-v1`, and applies session DDL from store construction.
|
||||
- `crates/crank-registry/src/ext.rs` owns a third ledger without checksum/advisory lock and executes caller-provided SQL.
|
||||
- Both service binaries currently bind metrics before registry compatibility is known. Story must ensure product readiness/listeners never start on incompatible schema; migration diagnostics must remain safe even if the pool connection succeeds.
|
||||
- Existing tests assume connect-implies-migrate. Update shared test setup to call canonical authority explicitly; do not add an implicit `connect_and_migrate` production escape hatch.
|
||||
|
||||
### Required Design Decisions
|
||||
|
||||
- Canonical sequence source of truth: Rust static descriptors and embedded SQL owned only by `crank-registry`; committed machine reference is generated/checked from it.
|
||||
- Preserve published v1 ledger checksum exactly. Add separate actual SHA-256 source digest guard rather than replacing the legacy token.
|
||||
- Consolidation is the first new canonical version and is expand-only. It may create canonical metadata/session schema but must not delete/rename legacy ledger or product table.
|
||||
- PostgreSQL transaction-level advisory lock is required because it is automatically released on commit/rollback; do not use session locks or per-ledger IDs.
|
||||
- SQLx 0.9 migration types/checksum support may inform implementation, but do not adopt `_sqlx_migrations` or add a second authority. Current workspace dependencies and Rust 1.96.1 remain fixed.
|
||||
|
||||
### Stable Diagnostic Contract
|
||||
|
||||
- Diagnostic fields: `code`, `stage`, optional numeric `version`, `recovery`; never raw SQL, driver string, database URL, schema content or row values.
|
||||
- Suggested recovery values are static: `run_preflight`, `run_controlled_migration`, `restore_known_good_backup`, `install_matching_application`, `contact_operator`.
|
||||
- `migration_required` is expected operator state, not compatibility pass. Admin/MCP still fail startup until controlled apply completes.
|
||||
- Database transport errors are normalized to a bounded category; raw SQLx chains remain internal and must not reach Display/JSON/stderr.
|
||||
|
||||
### File Map
|
||||
|
||||
**Likely NEW**
|
||||
|
||||
- `crates/crank-registry/src/migrations/baseline_v1.rs`
|
||||
- `crates/crank-registry/src/migrations/authority.rs`
|
||||
- `crates/crank-registry/src/migrations/contract.rs`
|
||||
- `apps/admin-api/src/bin/crank-migrate.rs`
|
||||
- `apps/admin-api/tests/migration_command.rs`
|
||||
- `docs/migrations.md`
|
||||
- `docs/schemas/migration-sequence.json`
|
||||
- migration boundary checker/tests if existing Rust boundary checker cannot express sole-owner rule.
|
||||
|
||||
**Likely UPDATE**
|
||||
|
||||
- `crates/crank-registry/src/migrations.rs` or replace with `migrations/mod.rs`
|
||||
- `crates/crank-registry/src/{lib.rs,ext.rs,error.rs}` and `src/postgres/connection.rs`
|
||||
- `crates/crank-registry/tests/integration/{migrations.rs,common.rs}`
|
||||
- `crates/crank-community-mcp/src/session.rs` and session integration tests
|
||||
- `crates/crank-config/src/{schema.rs,process.rs,render.rs,lib.rs}` and contract/generation/redaction tests
|
||||
- `apps/admin-api/src/main.rs`, `apps/mcp-server/src/main.rs`, their test common/startup suites and Cargo manifests as required
|
||||
- `apps/admin-api/Dockerfile`, root/community source+images Compose files
|
||||
- `justfile`, CI/release workflows, boundary scripts/tests
|
||||
- `docs/{README.md,en/README.md,intro.md,deployment.md,runtime-config.md}`, `CONTRIBUTING.md`, `scripts/README.md`
|
||||
- local ignored `_bmad-output/project-context.md`; do not force-add.
|
||||
|
||||
**Must not change**
|
||||
|
||||
- Rust/MSRV/Edition/base image versions, npm dependencies, HTTP/MCP payloads, UI bundles, existing product table semantics.
|
||||
- Baseline v1 ledger checksum or statement behavior; no unrelated Cargo registry dependency update.
|
||||
|
||||
### Testing Commands
|
||||
|
||||
```bash
|
||||
cargo test -p crank-registry --test integration migrations -- --nocapture
|
||||
cargo test -p crank-community-mcp --test integration session -- --nocapture
|
||||
cargo test -p admin-api --test migration_command -- --nocapture
|
||||
cargo test -p admin-api --test config_startup
|
||||
cargo test -p mcp-server --test config_startup
|
||||
cargo run -p admin-api --bin crank-migrate -- plan
|
||||
cargo run -p admin-api --bin crank-migrate -- preflight
|
||||
docker compose -f docker-compose.yml config -q
|
||||
docker compose -f deploy/community/docker-compose.yml --env-file deploy/community/.env.example config -q
|
||||
docker compose -f deploy/community/docker-compose.images.yml --env-file deploy/community/.env.images.example config -q
|
||||
PATH="$HOME/.cargo/bin:$PATH" just authenticated-product-smoke http://localhost:3000
|
||||
PATH="$HOME/.cargo/bin:$PATH" just verify
|
||||
git diff --check
|
||||
```
|
||||
|
||||
### Previous Story Intelligence
|
||||
|
||||
- Story 1.3 established `crank-config` as the sole environment reader. Migrator must extend this registry/projection; reading `DATABASE_URL` or `std::env` directly in the new binary is forbidden.
|
||||
- Config and diagnostics must validate before observability/listener side effects. Reuse bounded RU/EN diagnostic and secret wrapper patterns.
|
||||
- Docker parallel builds now use service-specific BuildKit Cargo cache IDs; preserve them.
|
||||
- Story 1.3 passed full workspace, strict Clippy, Compose, real PostgreSQL readiness and authenticated REST→MCP smoke. Story 1.4 must retain this evidence and must not mark missing Docker/PostgreSQL checks as pass.
|
||||
- Existing worktree includes Stories 1.1–1.3 changes. Preserve unrelated changes; no reset/checkout/lockfile regeneration outside the Story.
|
||||
|
||||
### Latest Technical Notes
|
||||
|
||||
- PostgreSQL transaction-level advisory locks are automatically released at transaction end; `pg_advisory_xact_lock(bigint)` waits for an exclusive application-defined lock. This matches short controlled migration transactions and avoids manual unlock leakage.
|
||||
- SQLx 0.9 exposes migration versions/checksums and warns that disabling locking can cause errors or data loss. This Story retains a project-owned `crank-registry` sequence rather than delegating authority to SQLx’s default ledger.
|
||||
|
||||
### References
|
||||
|
||||
- [Source: `_bmad-output/planning-artifacts/epics.md` — Wave 0, Epic 1, Story 1.4, FR-43, AR-16, AR-34]
|
||||
- [Source: `_bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/prd.md` — FR-43, NFR-R2, NFR-C1/C3]
|
||||
- [Source: `_bmad-output/planning-artifacts/architecture/architecture-crank-2026-08-03/ARCHITECTURE-SPINE.md` — AD-16, AD-17, AD-18]
|
||||
- [Source: `_bmad-output/implementation-artifacts/1-3-typed-configuration-foundation.md` — completion/review lessons]
|
||||
- [Source: `_bmad-output/project-context.md` — migrations, tests, deployment, secrets, environment boundaries]
|
||||
- [Source: `crates/crank-registry/src/migrations.rs`, `crates/crank-registry/src/ext.rs`, `crates/crank-registry/src/postgres/connection.rs`]
|
||||
- [Source: `crates/crank-community-mcp/src/session.rs`]
|
||||
- [PostgreSQL 18 advisory lock functions](https://www.postgresql.org/docs/current/functions-admin.html)
|
||||
- [PostgreSQL 16 explicit/advisory locking](https://www.postgresql.org/docs/16/explicit-locking.html)
|
||||
- [SQLx 0.9 Migrator](https://docs.rs/sqlx/0.9.0/sqlx/migrate/struct.Migrator.html)
|
||||
|
||||
## Dev Agent Record
|
||||
|
||||
### Agent Model Used
|
||||
|
||||
GPT-5 Codex
|
||||
|
||||
### Debug Log References
|
||||
|
||||
- `just verify` initially exposed unbounded parallel Admin integration contention; all four apparent stragglers passed independently, and the complete 30-test suite passed in 68–71 seconds with bounded execution. Local, CI and release gates now use `--test-threads=1` for deterministic resource use.
|
||||
- The first real-stack smoke correctly failed at `operation_test` because the default SSRF policy denies private upstreams. Re-running with the explicit test-only allowlist `CRANK_OUTBOUND_ALLOWED_HOSTS=admin-api` completed the full REST→MCP path without weakening production defaults.
|
||||
- An early immutable-source guard hashed the migration module wrapper and produced a false drift finding. Baseline v1 was isolated into `baseline_v1.rs`; the guard now hashes only the marked immutable baseline body.
|
||||
|
||||
### Implementation Plan
|
||||
|
||||
- Сначала закрепить RED regression tests для immutable v1, canonical sequence, legacy consolidation и read-only startup.
|
||||
- Затем выделить migration authority внутри `crank-registry`, централизовать MCP/extension schema ownership и добавить database-only migrator edge.
|
||||
- После green targeted suites встроить one-shot migration job в Compose/CI, обновить operator contract и выполнить полный PostgreSQL/Docker regression.
|
||||
|
||||
### Completion Notes List
|
||||
|
||||
- Ultimate context engine analysis completed - comprehensive developer guide created.
|
||||
- Established `crank-registry::MigrationAuthority` as the sole DDL owner with a validated contiguous checksummed sequence, immutable isolated baseline v1 and transactional consolidation v2.
|
||||
- Removed implicit core, MCP-session and extension schema writers from runtime paths. Admin and MCP now perform read-only compatibility verification and fail closed before metrics/product listeners on incompatible schema.
|
||||
- Added the database-only `crank-migrate` edge (`plan`, `preflight`, `apply` only), safe bounded JSON diagnostics, a committed machine sequence contract and direct CI/release drift gates.
|
||||
- Consolidated verified legacy core/MCP/extension provenance without deleting legacy ledgers; added schema-presence validation, future/partial/corrupt detection, bounded lock wait and transactional rollback evidence.
|
||||
- Added one-shot migration jobs to root/source/images Community Compose profiles; real fresh-stack evidence proved migration `0 → 2` precedes healthy Admin/MCP startup.
|
||||
- Real authenticated smoke passed create → test → publish Operation → publish Agent → MCP initialize/list/call. All generated credentials and test volumes were ephemeral and removed after the run.
|
||||
- Все 20 actionable code-review findings закрыты; единственный deferred пункт относится к ранее одобренному изменению lockfile из Story 1.1 и не входит в scope Story 1.4.
|
||||
- `just verify` passed in full with 103 Python tests, strict Clippy, dependency/security audit and the complete sequential Rust workspace. Explicit Community scope passed for all 91 NEW/UPDATE paths; all three Community images built successfully with Buildx.
|
||||
- No user blocker remains and no production HTTP/MCP/UI wire contract, Rust toolchain version or dependency version was changed by Story 1.4.
|
||||
|
||||
### File List
|
||||
|
||||
- `.gitea/workflows/ci.yml`
|
||||
- `.gitea/workflows/release.yml`
|
||||
- `CONTRIBUTING.md`
|
||||
- `apps/admin-api/Cargo.toml`
|
||||
- `apps/admin-api/Dockerfile`
|
||||
- `apps/admin-api/src/bin/crank-migrate.rs`
|
||||
- `apps/admin-api/src/error.rs`
|
||||
- `apps/admin-api/src/main.rs`
|
||||
- `apps/admin-api/tests/integration/common.rs`
|
||||
- `apps/admin-api/tests/config_startup.rs`
|
||||
- `apps/admin-api/tests/migration_command.rs`
|
||||
- `apps/mcp-server/Cargo.toml`
|
||||
- `apps/mcp-server/Dockerfile`
|
||||
- `apps/mcp-server/src/main.rs`
|
||||
- `apps/mcp-server/tests/config_startup.rs`
|
||||
- `apps/mcp-server/tests/integration/common.rs`
|
||||
- `crates/crank-community-mcp/src/session.rs`
|
||||
- `crates/crank-community-mcp/tests/integration/session.rs`
|
||||
- `crates/crank-config/src/debug.rs`
|
||||
- `crates/crank-config/src/lib.rs`
|
||||
- `crates/crank-config/src/migrator.rs`
|
||||
- `crates/crank-config/src/process.rs`
|
||||
- `crates/crank-config/src/schema.rs`
|
||||
- `crates/crank-config/src/source.rs`
|
||||
- `crates/crank-config/src/validation.rs`
|
||||
- `crates/crank-config/tests/contract.rs`
|
||||
- `crates/crank-registry/src/error.rs`
|
||||
- `crates/crank-registry/src/ext.rs`
|
||||
- `crates/crank-registry/src/lib.rs`
|
||||
- `crates/crank-registry/src/migrations.rs`
|
||||
- `crates/crank-registry/src/migrations/authority.rs`
|
||||
- `crates/crank-registry/src/migrations/baseline_v1.rs`
|
||||
- `crates/crank-registry/src/migrations/consolidation_v2.sql`
|
||||
- `crates/crank-registry/src/migrations/schema_guard.rs`
|
||||
- `crates/crank-registry/src/postgres/connection.rs`
|
||||
- `crates/crank-registry/tests/integration/common.rs`
|
||||
- `crates/crank-registry/tests/integration/migrations.rs`
|
||||
- `deploy/community/docker-compose.images.yml`
|
||||
- `deploy/community/docker-compose.yml`
|
||||
- `docker-compose.yml`
|
||||
- `docs/README.md`
|
||||
- `docs/deployment.md`
|
||||
- `docs/en/README.md`
|
||||
- `docs/en/migrations.md`
|
||||
- `docs/intro.md`
|
||||
- `docs/migrations.md`
|
||||
- `docs/runtime-config.md`
|
||||
- `docs/schemas/migration-sequence.json`
|
||||
- `justfile`
|
||||
- `scripts/README.md`
|
||||
- `scripts/check-config-boundaries.py`
|
||||
- `scripts/check-migration-boundaries.py`
|
||||
- `scripts/check-rust-module-boundaries.sh`
|
||||
- `tests/unit/test_check_config_boundaries.py`
|
||||
- `tests/unit/test_check_migration_boundaries.py`
|
||||
- `_bmad-output/project-context.md` (local ignored update only)
|
||||
|
||||
## Change Log
|
||||
|
||||
- 2026-08-09: Story 1.4 created with canonical migration authority, brownfield consolidation, read-only startup, controlled command and PostgreSQL 16 evidence contract.
|
||||
- 2026-08-09: Implemented Story 1.4, passed PostgreSQL/Compose/Buildx/real REST→MCP/full repository gates and moved the Story to review.
|
||||
- 2026-08-10: Closed all 20 actionable review findings, strengthened rollback/schema/boundary/release evidence, reran full verification and moved Story 1.4 to done.
|
||||
Reference in new issue
Block a user