feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s

Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
bsodfather committed 2026-10-25 09:08:22 +00:00
1 parent 1b6db09bd1
commit 54ce770682
357 files changed
+117394 -5115

No files matched your search

@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "agent-resource-bindings-v18";
pub(super) const SOURCE: &str = include_str!("agent_resource_bindings_v18.sql");
pub(super) const SOURCE_SHA256: &str =
"cb9b82183e04eb72c1f1a9ec853fcfc618f2b1c2a73edd051245890292beeb8f";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.agent_resource_bindings",
Some(18),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(18),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,84 @@
-- V18: typed exact Resource bindings Agent (Story 3.7 AC04, FR-15/FR-16).
--
-- Отдельная typed-таблица вместо JSON-поля: строка адресует точную
-- Published Resource Version (`resource_publications`) для точной версии Agent
-- (`agent_versions`). `latest`/floating версия невозможна, потому что FK указывает
-- на конкретную строку публикации.
--
-- Workspace-равенство обеспечивается на ОБОИХ концах composite FK:
-- * (workspace_id, agent_id) -> agents(workspace_id, id);
-- * (workspace_id, resource_id, resource_version) -> resource_publications(...).
-- Поэтому ни Agent другого workspace, ни чужая/неопубликованная Resource Version
-- не могут стать частью binding.
--
-- Published Agent Version immutable: V18-local trigger function проверяет и OLD,
-- и NEW ключ строки. Canonical V9 function при UPDATE смотрит только на NEW,
-- поэтому перенос binding из опубликованного snapshot в Draft-версию другого
-- Agent проходил бы через неё без отказа. V9/V17 SQL не изменяются.
-- Immutable guard V18: отказ, если затронута опубликованная версия Agent —
-- либо покидаемая (OLD), либо новая (NEW).
create function crank_reject_published_agent_resource_binding_mutation()
returns trigger
language plpgsql
as $$
declare
bound_status text;
begin
if tg_op in ('UPDATE', 'DELETE') then
select status
into bound_status
from agent_versions
where agent_id = old.agent_id and version = old.agent_version;
if bound_status = 'published' then
raise exception 'published Agent catalog bindings are immutable'
using errcode = '23514';
end if;
end if;
if tg_op in ('INSERT', 'UPDATE') then
select status
into bound_status
from agent_versions
where agent_id = new.agent_id and version = new.agent_version;
if bound_status = 'published' then
raise exception 'published Agent catalog bindings are immutable'
using errcode = '23514';
end if;
end if;
if tg_op = 'DELETE' then
return old;
end if;
return new;
end;
$$;
create unique index agents_workspace_id_idx on agents(workspace_id, id);
create table agent_resource_bindings (
workspace_id text not null,
agent_id text not null,
agent_version integer not null,
resource_id text not null,
resource_version integer not null,
constraint agent_resource_bindings_agent_version_check check (agent_version >= 1),
constraint agent_resource_bindings_resource_version_check check (resource_version >= 1),
primary key (agent_id, agent_version, resource_id, resource_version),
constraint agent_resource_bindings_agent_workspace_fkey
foreign key (workspace_id, agent_id)
references agents(workspace_id, id) on delete cascade,
constraint agent_resource_bindings_agent_version_fkey
foreign key (agent_id, agent_version)
references agent_versions(agent_id, version) on delete cascade,
constraint agent_resource_bindings_publication_fkey
foreign key (workspace_id, resource_id, resource_version)
references resource_publications(workspace_id, resource_id, version)
on delete cascade
);
create trigger agent_resource_bindings_immutable_guard
before insert or update or delete on agent_resource_bindings
for each row
execute function crank_reject_published_agent_resource_binding_mutation();
create index agent_resource_bindings_resource_idx
on agent_resource_bindings (workspace_id, resource_id, resource_version);
+84 -403
View File
@@ -1,5 +1,6 @@
use super::admin_auth_lifecycle_v8;
use super::agent_catalog_lifecycle_v9;
use super::agent_resource_bindings_v18;
use super::approval_side_effects_v10;
use super::artifact_cleanup_indexes_v13;
use super::artifact_metadata_v12;
@@ -10,6 +11,13 @@ use super::onboarding_import_selection_v15;
use super::onboarding_product_events_v11;
use super::owned_relations;
use super::platform_key_name_reuse_v6;
use super::prompt_dependencies_v23;
use super::prompt_publications_v22;
use super::prompts_v21;
use super::resource_drafts_v16;
use super::resource_publications_v17;
use super::resource_security_revocations_v19;
use super::resource_template_sources_v20;
use super::schema_guard::{
OWNED_RELATIONS, relation_exists, validate_required_relations, validate_schema_fingerprint,
};
@@ -23,12 +31,18 @@ use std::fmt;
mod contract;
mod preflight;
use preflight::*;
#[cfg(test)]
use contract::baseline_source_digest;
use contract::validate_descriptors;
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
const CURRENT_VERSION: i64 = 15;
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const CURRENT_VERSION: i64 = 23;
const IMPLEMENTED_VERSIONS: &[i64] = &[
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
];
const BASELINE_SOURCE_SHA256: &str =
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
@@ -273,6 +287,49 @@ impl MigrationAuthority {
onboarding_import_selection_v15::SOURCE_SHA256,
14,
),
expand_descriptor(
16,
resource_drafts_v16::NAME,
resource_drafts_v16::SOURCE_SHA256,
15,
),
expand_descriptor(
17,
resource_publications_v17::NAME,
resource_publications_v17::SOURCE_SHA256,
16,
),
expand_descriptor(
18,
agent_resource_bindings_v18::NAME,
agent_resource_bindings_v18::SOURCE_SHA256,
17,
),
expand_descriptor(
19,
resource_security_revocations_v19::NAME,
resource_security_revocations_v19::SOURCE_SHA256,
18,
),
expand_descriptor(
20,
resource_template_sources_v20::NAME,
resource_template_sources_v20::SOURCE_SHA256,
19,
),
expand_descriptor(21, prompts_v21::NAME, prompts_v21::SOURCE_SHA256, 20),
expand_descriptor(
22,
prompt_publications_v22::NAME,
prompt_publications_v22::SOURCE_SHA256,
21,
),
expand_descriptor(
23,
prompt_dependencies_v23::NAME,
prompt_dependencies_v23::SOURCE_SHA256,
22,
),
]
}
pub fn validate_sequence() -> Result<(), MigrationError> {
@@ -407,6 +464,31 @@ impl MigrationAuthority {
if from < 15 {
onboarding_import_selection_v15::apply(&mut transaction, &Self::sequence()[14]).await?;
}
if from < 16 {
resource_drafts_v16::apply(&mut transaction, &Self::sequence()[15]).await?;
}
if from < 17 {
resource_publications_v17::apply(&mut transaction, &Self::sequence()[16]).await?;
}
if from < 18 {
agent_resource_bindings_v18::apply(&mut transaction, &Self::sequence()[17]).await?;
}
if from < 19 {
resource_security_revocations_v19::apply(&mut transaction, &Self::sequence()[18])
.await?;
}
if from < 20 {
resource_template_sources_v20::apply(&mut transaction, &Self::sequence()[19]).await?;
}
if from < 21 {
prompts_v21::apply(&mut transaction, &Self::sequence()[20]).await?;
}
if from < 22 {
prompt_publications_v22::apply(&mut transaction, &Self::sequence()[21]).await?;
}
if from < 23 {
prompt_dependencies_v23::apply(&mut transaction, &Self::sequence()[22]).await?;
}
match inspect(&mut transaction).await? {
MigrationPreflight::Current {
version: CURRENT_VERSION,
@@ -430,407 +512,6 @@ impl MigrationAuthority {
})
}
}
async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, MigrationError> {
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
if !core_exists {
let mut owned_exists = canonical_exists;
for relation in OWNED_RELATIONS {
owned_exists |= relation_exists(connection, relation).await?;
}
if owned_exists {
if is_ledgerless_legacy_baseline(connection, canonical_exists).await? {
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
return Err(MigrationError::new(
"partial_sequence",
"preflight.core_missing",
None,
"restore_known_good_backup",
));
}
inspect_optional_legacy(connection).await?;
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
validate_core_ledger(connection).await?;
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
inspect_optional_legacy(connection).await?;
if !canonical_exists {
return Ok(MigrationPreflight::MigrationRequired {
current: 1,
target: CURRENT_VERSION,
});
}
let descriptors = MigrationAuthority::sequence();
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if rows.is_empty() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
None,
"restore_known_good_backup",
));
}
for (index, row) in rows.iter().enumerate() {
let version = row
.try_get::<i64, _>("version")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if version > CURRENT_VERSION {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
}
let Some(expected) = descriptors.get(index) else {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
};
if version != expected.version {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let checksum = row
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if checksum != expected.checksum {
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let name = row
.try_get::<String, _>("name")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let phase = row
.try_get::<String, _>("phase")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let compatibility = row
.try_get::<String, _>("compatibility")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if name != expected.name
|| phase != expected.phase
|| compatibility != expected.compatibility
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.metadata",
Some(version),
"restore_known_good_backup",
));
}
}
let current = rows
.last()
.and_then(|row| row.try_get::<i64, _>("version").ok())
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
if rows.len() != usize::try_from(current).unwrap_or_default() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(current),
"restore_known_good_backup",
));
}
validate_schema_fingerprint(connection, current).await?;
if current < CURRENT_VERSION {
Ok(MigrationPreflight::MigrationRequired {
current,
target: CURRENT_VERSION,
})
} else {
validate_required_relations(connection, owned_relations::CONSOLIDATION, CURRENT_VERSION)
.await?;
validate_required_relations(
connection,
owned_relations::ONBOARDING_PRODUCT_EVENTS,
CURRENT_VERSION,
)
.await?;
validate_required_relations(
connection,
owned_relations::ARTIFACT_METADATA,
CURRENT_VERSION,
)
.await?;
validate_required_relations(connection, owned_relations::IMPORT_PLAN, CURRENT_VERSION)
.await?;
validate_required_relations(
connection,
owned_relations::ONBOARDING_IMPORT_SELECTION,
CURRENT_VERSION,
)
.await?;
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
validate_legacy_audit(connection).await?;
Ok(MigrationPreflight::Current { version: current })
}
}
async fn is_ledgerless_legacy_baseline(
connection: &mut PgConnection,
canonical_exists: bool,
) -> Result<bool, MigrationError> {
if canonical_exists {
return Ok(false);
}
for relation in [
"__crank_migration_legacy_audit",
"master_key_identities",
"master_key_rotations",
"admin_bootstrap_contracts",
"admin_login_backoff",
"admin_security_audit_events",
"product_events",
"product_event_daily_rollups",
"onboarding_selections",
"onboarding_import_selections",
"artifact_blobs",
"artifact_sources",
] {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
for relation in owned_relations::BASELINE {
if !relation_exists(connection, relation).await? {
return Ok(false);
}
}
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
validate_ledgerless_baseline_fingerprint(connection).await?;
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
if mcp_ledger {
return Ok(false);
}
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
let extension_ledger = relation_exists(connection, "__crank_ext_migrations").await?;
validate_ledgerless_optional_fingerprints(connection, mcp_sessions, extension_ledger).await?;
inspect_optional_legacy_for_ledgerless_baseline(connection).await?;
Ok(true)
}
async fn validate_core_ledger(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
.fetch_all(connection)
.await
.map_err(|_| MigrationError::storage("preflight.core"))?;
if rows.len() != 1 {
return Err(MigrationError::new(
"partial_sequence",
"preflight.core_cardinality",
None,
"restore_known_good_backup",
));
}
let version = rows[0]
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let checksum = rows[0]
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let description = rows[0]
.try_get::<String, _>("description")
.map_err(|_| MigrationError::storage("preflight.core"))?;
if version != BASELINE_VERSION
|| description != "community baseline"
|| checksum != BASELINE_CHECKSUM
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.core",
Some(i64::from(version)),
"restore_known_good_backup",
));
}
Ok(())
}
async fn inspect_optional_legacy(connection: &mut PgConnection) -> Result<(), MigrationError> {
inspect_optional_legacy_with_policy(connection, false).await
}
async fn inspect_optional_legacy_for_ledgerless_baseline(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
inspect_optional_legacy_with_policy(connection, true).await
}
async fn inspect_optional_legacy_with_policy(
connection: &mut PgConnection,
allow_sessions_without_ledger: bool,
) -> Result<(), MigrationError> {
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
if mcp_ledger != mcp_sessions && !(allow_sessions_without_ledger && !mcp_ledger && mcp_sessions)
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
if mcp_ledger {
let rows =
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
if rows.len() != 1
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
!= Some("mcp-transport-sessions-v1")
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
}
if relation_exists(connection, "__crank_ext_migrations").await? {
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<i64, _>("count")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if count > 1_000 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
if count > 0 {
let checksum_column = query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema()
and table_name = '__crank_ext_migrations'
and column_name = 'checksum'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if !checksum_column {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
let rows = query(
"select extension_name, version, checksum
from __crank_ext_migrations
order by extension_name, version
limit 1001",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
for row in rows {
let name = row
.try_get::<String, _>("extension_name")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let version = row
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let checksum = row
.try_get::<Option<String>, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let registered = MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& descriptor.version == u32::try_from(version).unwrap_or_default()
&& checksum.as_deref() == Some(descriptor.checksum)
});
if !registered {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
Some(i64::from(version)),
"contact_operator",
));
}
}
}
}
Ok(())
}
async fn validate_legacy_audit(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query(
"select source, source_version, source_checksum
from __crank_migration_legacy_audit
order by source, source_version
limit 1002",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
if rows.len() > 1001 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
None,
"contact_operator",
));
}
for row in rows {
let source = row
.try_get::<String, _>("source")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let version = row
.try_get::<i64, _>("source_version")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let checksum = row
.try_get::<String, _>("source_checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|| source.strip_prefix("extension:").is_some_and(|name| {
MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& i64::from(descriptor.version) == version
&& descriptor.checksum == checksum
})
});
if !valid {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
Some(version),
"restore_known_good_backup",
));
}
}
Ok(())
}
async fn create_core_ledger(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
@@ -133,6 +133,13 @@ pub(super) fn validate_descriptors(
|| sha256_hex(import_plan_v14::SOURCE.as_bytes()) != import_plan_v14::SOURCE_SHA256
|| sha256_hex(onboarding_import_selection_v15::SOURCE.as_bytes())
!= onboarding_import_selection_v15::SOURCE_SHA256
|| sha256_hex(resource_drafts_v16::SOURCE.as_bytes()) != resource_drafts_v16::SOURCE_SHA256
|| sha256_hex(resource_publications_v17::SOURCE.as_bytes())
!= resource_publications_v17::SOURCE_SHA256
|| sha256_hex(agent_resource_bindings_v18::SOURCE.as_bytes())
!= agent_resource_bindings_v18::SOURCE_SHA256
|| sha256_hex(resource_security_revocations_v19::SOURCE.as_bytes())
!= resource_security_revocations_v19::SOURCE_SHA256
{
return Err(MigrationError::new(
"invalid_contract",
@@ -0,0 +1,409 @@
//! Preflight/legacy-state inspection (вынесено из `authority.rs`, чтобы файл
//! оставался в пределах rust-code-health); поведение не меняется.
use super::*;
pub(super) async fn inspect(
connection: &mut PgConnection,
) -> Result<MigrationPreflight, MigrationError> {
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
if !core_exists {
let mut owned_exists = canonical_exists;
for relation in OWNED_RELATIONS {
owned_exists |= relation_exists(connection, relation).await?;
}
if owned_exists {
if is_ledgerless_legacy_baseline(connection, canonical_exists).await? {
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
return Err(MigrationError::new(
"partial_sequence",
"preflight.core_missing",
None,
"restore_known_good_backup",
));
}
inspect_optional_legacy(connection).await?;
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
validate_core_ledger(connection).await?;
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
inspect_optional_legacy(connection).await?;
if !canonical_exists {
return Ok(MigrationPreflight::MigrationRequired {
current: 1,
target: CURRENT_VERSION,
});
}
let descriptors = MigrationAuthority::sequence();
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if rows.is_empty() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
None,
"restore_known_good_backup",
));
}
for (index, row) in rows.iter().enumerate() {
let version = row
.try_get::<i64, _>("version")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if version > CURRENT_VERSION {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
}
let Some(expected) = descriptors.get(index) else {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
};
if version != expected.version {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let checksum = row
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if checksum != expected.checksum {
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let name = row
.try_get::<String, _>("name")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let phase = row
.try_get::<String, _>("phase")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let compatibility = row
.try_get::<String, _>("compatibility")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if name != expected.name
|| phase != expected.phase
|| compatibility != expected.compatibility
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.metadata",
Some(version),
"restore_known_good_backup",
));
}
}
let current = rows
.last()
.and_then(|row| row.try_get::<i64, _>("version").ok())
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
if rows.len() != usize::try_from(current).unwrap_or_default() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(current),
"restore_known_good_backup",
));
}
validate_schema_fingerprint(connection, current).await?;
if current < CURRENT_VERSION {
Ok(MigrationPreflight::MigrationRequired {
current,
target: CURRENT_VERSION,
})
} else {
for relations in [
owned_relations::CONSOLIDATION,
owned_relations::ONBOARDING_PRODUCT_EVENTS,
owned_relations::ARTIFACT_METADATA,
owned_relations::IMPORT_PLAN,
owned_relations::ONBOARDING_IMPORT_SELECTION,
owned_relations::RESOURCE_DRAFTS,
owned_relations::RESOURCE_PUBLICATIONS,
owned_relations::AGENT_RESOURCE_BINDINGS,
owned_relations::RESOURCE_SECURITY_REVOCATIONS,
owned_relations::RESOURCE_TEMPLATE_SOURCES,
owned_relations::PROMPTS,
owned_relations::PROMPT_PUBLICATIONS,
owned_relations::PROMPT_DEPENDENCIES,
] {
validate_required_relations(connection, relations, CURRENT_VERSION).await?;
}
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
validate_legacy_audit(connection).await?;
Ok(MigrationPreflight::Current { version: current })
}
}
pub(super) async fn is_ledgerless_legacy_baseline(
connection: &mut PgConnection,
canonical_exists: bool,
) -> Result<bool, MigrationError> {
if canonical_exists {
return Ok(false);
}
for relation in [
"__crank_migration_legacy_audit",
"master_key_identities",
"master_key_rotations",
"admin_bootstrap_contracts",
"admin_login_backoff",
"admin_security_audit_events",
"product_events",
"product_event_daily_rollups",
"onboarding_selections",
"onboarding_import_selections",
"artifact_blobs",
"artifact_sources",
] {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
for relation in owned_relations::BASELINE {
if !relation_exists(connection, relation).await? {
return Ok(false);
}
}
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
validate_ledgerless_baseline_fingerprint(connection).await?;
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
if mcp_ledger {
return Ok(false);
}
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
let extension_ledger = relation_exists(connection, "__crank_ext_migrations").await?;
validate_ledgerless_optional_fingerprints(connection, mcp_sessions, extension_ledger).await?;
inspect_optional_legacy_for_ledgerless_baseline(connection).await?;
Ok(true)
}
pub(super) async fn validate_core_ledger(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
.fetch_all(connection)
.await
.map_err(|_| MigrationError::storage("preflight.core"))?;
if rows.len() != 1 {
return Err(MigrationError::new(
"partial_sequence",
"preflight.core_cardinality",
None,
"restore_known_good_backup",
));
}
let version = rows[0]
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let checksum = rows[0]
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let description = rows[0]
.try_get::<String, _>("description")
.map_err(|_| MigrationError::storage("preflight.core"))?;
if version != BASELINE_VERSION
|| description != "community baseline"
|| checksum != BASELINE_CHECKSUM
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.core",
Some(i64::from(version)),
"restore_known_good_backup",
));
}
Ok(())
}
pub(super) async fn inspect_optional_legacy(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
inspect_optional_legacy_with_policy(connection, false).await
}
pub(super) async fn inspect_optional_legacy_for_ledgerless_baseline(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
inspect_optional_legacy_with_policy(connection, true).await
}
pub(super) async fn inspect_optional_legacy_with_policy(
connection: &mut PgConnection,
allow_sessions_without_ledger: bool,
) -> Result<(), MigrationError> {
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
if mcp_ledger != mcp_sessions && !(allow_sessions_without_ledger && !mcp_ledger && mcp_sessions)
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
if mcp_ledger {
let rows =
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
if rows.len() != 1
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
!= Some("mcp-transport-sessions-v1")
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
}
if relation_exists(connection, "__crank_ext_migrations").await? {
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<i64, _>("count")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if count > 1_000 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
if count > 0 {
let checksum_column = query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema()
and table_name = '__crank_ext_migrations'
and column_name = 'checksum'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if !checksum_column {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
let rows = query(
"select extension_name, version, checksum
from __crank_ext_migrations
order by extension_name, version
limit 1001",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
for row in rows {
let name = row
.try_get::<String, _>("extension_name")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let version = row
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let checksum = row
.try_get::<Option<String>, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let registered = MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& descriptor.version == u32::try_from(version).unwrap_or_default()
&& checksum.as_deref() == Some(descriptor.checksum)
});
if !registered {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
Some(i64::from(version)),
"contact_operator",
));
}
}
}
}
Ok(())
}
pub(super) async fn validate_legacy_audit(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
let rows = query(
"select source, source_version, source_checksum
from __crank_migration_legacy_audit
order by source, source_version
limit 1002",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
if rows.len() > 1001 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
None,
"contact_operator",
));
}
for row in rows {
let source = row
.try_get::<String, _>("source")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let version = row
.try_get::<i64, _>("source_version")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let checksum = row
.try_get::<String, _>("source_checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|| source.strip_prefix("extension:").is_some_and(|name| {
MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& i64::from(descriptor.version) == version
&& descriptor.checksum == checksum
})
});
if !valid {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
Some(version),
"restore_known_good_backup",
));
}
}
Ok(())
}
@@ -8,7 +8,9 @@ fn sequence_is_deterministic_and_append_only() {
MigrationAuthority::validate_sequence().unwrap();
assert_eq!(
first.iter().map(|item| item.version).collect::<Vec<_>>(),
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
vec![
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
]
);
assert_eq!(first[0].checksum, "crank-community-baseline-v1");
assert_eq!(first[0].source_digest, BASELINE_SOURCE_SHA256);
@@ -33,6 +33,28 @@ pub(super) const ONBOARDING_PRODUCT_EVENTS: &[&str] = &[
pub(super) const ONBOARDING_IMPORT_SELECTION: &[&str] = &["onboarding_import_selections"];
pub(super) const RESOURCE_DRAFTS: &[&str] = &["resources", "resource_versions"];
pub(super) const RESOURCE_PUBLICATIONS: &[&str] = &["resource_publications"];
pub(super) const AGENT_RESOURCE_BINDINGS: &[&str] = &["agent_resource_bindings"];
pub(super) const RESOURCE_SECURITY_REVOCATIONS: &[&str] = &["resource_security_revocations"];
pub(super) const RESOURCE_TEMPLATE_SOURCES: &[&str] = &["resource_template_sources"];
pub(super) const PROMPTS: &[&str] = &[
"prompts",
"prompt_versions",
"prompt_arguments",
"prompt_messages",
];
pub(super) const PROMPT_PUBLICATIONS: &[&str] = &["prompt_publications", "agent_prompt_bindings"];
pub(super) const PROMPT_DEPENDENCIES: &[&str] =
&["prompt_dependencies", "prompt_message_resource_refs"];
pub(super) const ARTIFACT_METADATA: &[&str] = &["artifact_blobs", "artifact_sources"];
pub(super) const IMPORT_PLAN: &[&str] = &["import_plans", "import_plan_applications"];
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "prompt-dependencies-v23";
pub(super) const SOURCE: &str = include_str!("prompt_dependencies_v23.sql");
pub(super) const SOURCE_SHA256: &str =
"15799d41e73021386bf1bae5952cbd34df93317cbce1a97fa8f99b3bd15cac64";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.prompt_dependencies_v23",
Some(23),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(23),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,74 @@
-- V23: version-keyed pinned Prompt dependencies (Story 3.16, FR-18).
--
-- `prompt_dependencies` фиксирует точную опубликованную версию Resource, которую Draft/Prompt
-- объявил в `dependencies`, вместе с разрешёнными на момент сохранения метаданными пина
-- (digest/kind/mime/source_class/sensitivity). Строки version-keyed: правка зависимости
-- требует нового Draft и новой публикации, поэтому уже опубликованная версия не меняется.
--
-- `prompt_message_resource_refs` хранит объявленные точки вставки: упорядоченный список
-- индексов `dependencies` у конкретного сообщения. Отдельная таблица (а не колонка в
-- `prompt_messages`) сохраняет уже принятую схему сообщений без изменения её отпечатка.
--
-- Guard-функция v22 (`crank_reject_published_prompt_version_mutation`) применяется к обеим
-- новым таблицам тем же способом, что к arguments/messages: опубликованная версия immutable.
create table prompt_dependencies (
workspace_id text not null,
prompt_id text not null,
version integer not null,
dependency_position integer not null,
resource_id text not null,
resource_version integer not null,
digest text not null,
kind text not null,
mime_type text not null,
source_class text not null,
sensitivity text not null,
constraint prompt_dependencies_pkey primary key (workspace_id, prompt_id, version, dependency_position),
constraint prompt_dependencies_version_fkey foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
constraint prompt_dependencies_position_check check (dependency_position between 0 and 15),
constraint prompt_dependencies_resource_version_check check (resource_version >= 1),
constraint prompt_dependencies_kind_check check (kind in ('text', 'json', 'binary')),
constraint prompt_dependencies_source_class_check check (source_class in ('static', 'dynamic')),
constraint prompt_dependencies_sensitivity_check check (
sensitivity in ('public', 'internal', 'secret')
),
constraint prompt_dependencies_digest_check check (octet_length(digest) between 1 and 256),
constraint prompt_dependencies_mime_check check (octet_length(mime_type) between 1 and 255),
constraint prompt_dependencies_resource_id_check check (
octet_length(resource_id) between 1 and 160
)
);
create table prompt_message_resource_refs (
workspace_id text not null,
prompt_id text not null,
version integer not null,
message_position integer not null,
ref_position integer not null,
dependency_position integer not null,
constraint prompt_message_resource_refs_pkey primary key (
workspace_id, prompt_id, version, message_position, ref_position
),
constraint prompt_message_resource_refs_version_fkey
foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
constraint prompt_message_resource_refs_message_check check (
message_position between 0 and 63
),
constraint prompt_message_resource_refs_ref_check check (ref_position between 0 and 15),
constraint prompt_message_resource_refs_dependency_check check (
dependency_position between 0 and 15
)
);
create trigger prompt_dependencies_immutable_guard
before insert or update or delete on prompt_dependencies
for each row
execute function crank_reject_published_prompt_version_mutation();
create trigger prompt_message_resource_refs_immutable_guard
before insert or update or delete on prompt_message_resource_refs
for each row
execute function crank_reject_published_prompt_version_mutation();
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "prompt-publications-v22";
pub(super) const SOURCE: &str = include_str!("prompt_publications_v22.sql");
pub(super) const SOURCE_SHA256: &str =
"b330b248f164fc6f3635739668f5ea94dc48f0e84d18f0d3dfceb92ff6c445e7";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.prompt_publications_v22",
Some(22),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(22),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,195 @@
-- V22: immutable Published Prompt Versions и typed exact Prompt bindings Agent
-- (Story 3.13, FR-17).
--
-- `prompt_publications` фиксирует lifecycle-снимок публикации: точная версия,
-- name/description/sensitivity на момент publish и `published_at`. Сама
-- definition (arguments/messages) остаётся в version-keyed `prompt_arguments` и
-- `prompt_messages`; поэтому снимок не дублирует байты, а отдельная guard-функция
-- запрещает менять definition уже опубликованной версии. Archive — не revoke:
-- immutable строки остаются.
--
-- `agent_prompt_bindings` — отдельная typed-таблица: строка адресует точную
-- Published Prompt Version для точной версии Agent. Composite FK проверяет
-- workspace на обоих концах, поэтому `latest`-версия и чужая публикация в
-- binding попасть не могут.
alter table prompts
add column latest_published_version integer,
add constraint prompts_latest_published_version_check check (
latest_published_version is null or latest_published_version >= 1
);
create table prompt_publications (
workspace_id text not null,
prompt_id text not null,
version integer not null,
name text not null,
description text not null,
sensitivity text not null,
published_at timestamptz not null,
constraint prompt_publications_pkey primary key (workspace_id, prompt_id, version),
constraint prompt_publications_version_check check (version >= 1),
constraint prompt_publications_name_length_check check (
octet_length(name) between 1 and 16384
),
constraint prompt_publications_description_length_check check (
octet_length(description) between 1 and 16384
),
constraint prompt_publications_sensitivity_check check (
sensitivity in ('public', 'internal', 'secret')
),
constraint prompt_publications_prompt_fkey
foreign key (workspace_id, prompt_id)
references prompts(workspace_id, prompt_id) on delete cascade,
constraint prompt_publications_version_fkey
foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version)
on delete cascade
);
-- Опубликованная definition immutable: guard смотрит и OLD, и NEW ключ строки.
-- Удаление допускается только вместе с owning prompt (cascade), потому что archive
-- является lifecycle-состоянием, а не удалением снимка.
create function crank_reject_published_prompt_version_mutation()
returns trigger
language plpgsql
as $$
declare
published boolean;
owner_present boolean;
begin
if tg_op in ('UPDATE', 'DELETE') then
select exists (
select 1 from prompt_publications
where workspace_id = old.workspace_id
and prompt_id = old.prompt_id
and version = old.version
), exists (
select 1 from prompts
where workspace_id = old.workspace_id and prompt_id = old.prompt_id
)
into published, owner_present;
if published and owner_present then
raise exception 'published Prompt version is immutable'
using errcode = '23514';
end if;
end if;
if tg_op in ('INSERT', 'UPDATE') then
select exists (
select 1 from prompt_publications
where workspace_id = new.workspace_id
and prompt_id = new.prompt_id
and version = new.version
) into published;
if published then
raise exception 'published Prompt version is immutable'
using errcode = '23514';
end if;
end if;
if tg_op = 'DELETE' then
return old;
end if;
return new;
end;
$$;
create function crank_reject_prompt_publication_mutation()
returns trigger
language plpgsql
as $$
declare
owner_present boolean;
begin
if tg_op = 'DELETE' then
select exists (
select 1 from prompts
where workspace_id = old.workspace_id and prompt_id = old.prompt_id
) into owner_present;
if owner_present then
raise exception 'published Prompt version is immutable'
using errcode = '23514';
end if;
return old;
end if;
raise exception 'published Prompt version is immutable'
using errcode = '23514';
end;
$$;
create trigger prompt_arguments_immutable_guard
before insert or update or delete on prompt_arguments
for each row
execute function crank_reject_published_prompt_version_mutation();
create trigger prompt_messages_immutable_guard
before insert or update or delete on prompt_messages
for each row
execute function crank_reject_published_prompt_version_mutation();
create trigger prompt_publications_immutable_guard
before update or delete on prompt_publications
for each row
execute function crank_reject_prompt_publication_mutation();
create table agent_prompt_bindings (
workspace_id text not null,
agent_id text not null,
agent_version integer not null,
prompt_id text not null,
prompt_version integer not null,
constraint agent_prompt_bindings_agent_version_check check (agent_version >= 1),
constraint agent_prompt_bindings_prompt_version_check check (prompt_version >= 1),
primary key (agent_id, agent_version, prompt_id),
constraint agent_prompt_bindings_agent_workspace_fkey
foreign key (workspace_id, agent_id)
references agents(workspace_id, id) on delete cascade,
constraint agent_prompt_bindings_agent_version_fkey
foreign key (agent_id, agent_version)
references agent_versions(agent_id, version) on delete cascade,
constraint agent_prompt_bindings_publication_fkey
foreign key (workspace_id, prompt_id, prompt_version)
references prompt_publications(workspace_id, prompt_id, version)
on delete cascade
);
create function crank_reject_published_agent_prompt_binding_mutation()
returns trigger
language plpgsql
as $$
declare
bound_status text;
begin
if tg_op in ('UPDATE', 'DELETE') then
select status
into bound_status
from agent_versions
where agent_id = old.agent_id and version = old.agent_version;
if bound_status = 'published' then
raise exception 'published Agent Prompt bindings are immutable'
using errcode = '23514';
end if;
end if;
if tg_op in ('INSERT', 'UPDATE') then
select status
into bound_status
from agent_versions
where agent_id = new.agent_id and version = new.agent_version;
if bound_status = 'published' then
raise exception 'published Agent Prompt bindings are immutable'
using errcode = '23514';
end if;
end if;
if tg_op = 'DELETE' then
return old;
end if;
return new;
end;
$$;
create trigger agent_prompt_bindings_immutable_guard
before insert or update or delete on agent_prompt_bindings
for each row
execute function crank_reject_published_agent_prompt_binding_mutation();
create index agent_prompt_bindings_publication_idx
on agent_prompt_bindings (workspace_id, prompt_id, prompt_version);
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "prompts-v21";
pub(super) const SOURCE: &str = include_str!("prompts_v21.sql");
pub(super) const SOURCE_SHA256: &str =
"c62717f8eb87b249b7771c74517ce99baeaf2793bfd5fca5d15e8412112bc53e";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.prompts_v21",
Some(21),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(21),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,71 @@
-- V21: typed Prompt Draft aggregate and ordered arguments/messages (Story 3.12).
create table prompts (
workspace_id text not null references workspaces(id) on delete cascade,
prompt_id text not null,
name text not null,
description text not null,
status text not null default 'draft',
sensitivity text not null,
current_draft_version integer not null default 1,
created_at timestamptz not null,
updated_at timestamptz not null,
constraint prompts_pkey primary key (workspace_id, prompt_id),
constraint prompts_id_check check (prompt_id ~ '^prm_[A-Za-z0-9_-]{1,128}$'),
constraint prompts_name_length_check check (octet_length(name) between 1 and 16384),
constraint prompts_description_length_check check (octet_length(description) between 1 and 16384),
constraint prompts_status_check check (status in ('draft', 'published', 'archived')),
constraint prompts_sensitivity_check check (sensitivity in ('public', 'internal', 'secret')),
constraint prompts_draft_version_check check (current_draft_version >= 1)
);
create table prompt_versions (
workspace_id text not null,
prompt_id text not null,
version integer not null,
created_at timestamptz not null,
constraint prompt_versions_pkey primary key (workspace_id, prompt_id, version),
constraint prompt_versions_prompt_fkey foreign key (workspace_id, prompt_id)
references prompts(workspace_id, prompt_id) on delete cascade,
constraint prompt_versions_version_check check (version >= 1)
);
create table prompt_arguments (
workspace_id text not null,
prompt_id text not null,
version integer not null,
argument_name text not null,
argument_type text not null,
required boolean not null,
default_value jsonb,
enumeration jsonb,
position integer not null,
constraint prompt_arguments_pkey primary key (workspace_id, prompt_id, version, argument_name),
constraint prompt_arguments_version_fkey foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
constraint prompt_arguments_type_check check (argument_type in ('string', 'number', 'integer', 'boolean')),
constraint prompt_arguments_name_check check (octet_length(argument_name) between 1 and 16384),
constraint prompt_arguments_position_check check (position >= 0),
constraint prompt_arguments_default_size_check check (default_value is null or octet_length(default_value::text) <= 16384),
constraint prompt_arguments_enum_size_check check (
enumeration is null or case
when jsonb_typeof(enumeration) = 'array'
then jsonb_array_length(enumeration) between 1 and 64
else false
end
)
);
create table prompt_messages (
workspace_id text not null,
prompt_id text not null,
version integer not null,
position integer not null,
role text not null,
content text not null,
constraint prompt_messages_pkey primary key (workspace_id, prompt_id, version, position),
constraint prompt_messages_version_fkey foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
constraint prompt_messages_position_check check (position between 0 and 63),
constraint prompt_messages_role_check check (role in ('system', 'user', 'assistant')),
constraint prompt_messages_content_check check (octet_length(content) between 1 and 16384)
);
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "resource-drafts-v16";
pub(super) const SOURCE: &str = include_str!("resource_drafts_v16.sql");
pub(super) const SOURCE_SHA256: &str =
"0ed07dabd37f97e212923650b80278898c4e9519cee0cda4170f6b2b2a3d92d7";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.resource_drafts",
Some(16),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(16),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,76 @@
-- V16: typed static Resource drafts (Story 3.6, D-15).
--
-- Байты не хранятся здесь: содержимое версии — это content-addressed blob
-- (`artifact_blobs`) и owning-ссылка (`artifact_sources`), поэтому Resource
-- участвует в существующем учёте владения и sweep-е (AD-10).
-- Filesystem path, raw filename и mutable external reference намеренно
-- отсутствуют (D-12).
create table resources (
workspace_id text not null references workspaces(id) on delete cascade,
resource_id text not null,
uri text not null,
name text not null,
description text not null default '',
status text not null default 'draft',
kind text not null,
current_draft_version integer not null,
created_at timestamptz not null,
updated_at timestamptz not null,
constraint resources_resource_id_check check (resource_id ~ '^res_[A-Za-z0-9_-]{1,96}$'),
constraint resources_uri_len_check check (octet_length(uri) between 10 and 200),
constraint resources_name_len_check check (octet_length(name) between 1 and 64),
constraint resources_description_len check (octet_length(description) <= 1024),
constraint resources_status_check check (status in ('draft', 'published', 'archived')),
constraint resources_kind_check check (kind in ('text', 'json', 'binary')),
constraint resources_current_version_check check (current_draft_version >= 1),
constraint resources_timestamps_check check (updated_at >= created_at),
constraint resources_workspace_uri_unique unique (workspace_id, uri),
constraint resources_workspace_name_unique unique (workspace_id, name),
primary key (workspace_id, resource_id)
);
create table resource_versions (
workspace_id text not null,
resource_id text not null,
version integer not null,
kind text not null,
mime_type text not null,
size_bytes bigint not null,
digest text not null,
sensitivity text not null,
artifact_source_id text not null,
created_at timestamptz not null,
superseded_at timestamptz null,
constraint resource_versions_version_check check (version >= 1),
constraint resource_versions_kind_check check (kind in ('text', 'json', 'binary')),
constraint resource_versions_mime_type_check check (
octet_length(mime_type) between 3 and 255
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'
),
constraint resource_versions_size_check check (size_bytes between 1 and 262144),
constraint resource_versions_digest_check check (digest ~ '^[0-9a-f]{64}$'),
constraint resource_versions_sensitivity_check check (
sensitivity in ('public', 'internal', 'secret')
),
constraint resource_versions_source_id_check check (
artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
),
constraint resource_versions_supersede_check check (
superseded_at is null or superseded_at >= created_at
),
primary key (workspace_id, resource_id, version),
constraint resource_versions_resource_fkey foreign key (workspace_id, resource_id)
references resources(workspace_id, resource_id) on delete cascade,
constraint resource_versions_source_fkey foreign key (workspace_id, artifact_source_id)
references artifact_sources(workspace_id, source_id)
);
-- Ровно одна текущая черновая версия на Resource: пометка прежней версии
-- обязана произойти до вставки новой (D-15 шаг 4), индекс не ослабляется.
create unique index resource_versions_current_draft_unique
on resource_versions (workspace_id, resource_id)
where superseded_at is null;
create index resources_workspace_created_idx
on resources (workspace_id, created_at, resource_id);
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "resource-publications-v17";
pub(super) const SOURCE: &str = include_str!("resource_publications_v17.sql");
pub(super) const SOURCE_SHA256: &str =
"eaefc08d25ba5ab92775dd9263ced14d927e28b558444f83ea789f1f0023c092";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.resource_publications",
Some(17),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(17),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,67 @@
-- V17: immutable Published Resource Versions (Story 3.7, FR-15/FR-16).
--
-- Строка публикации — снимок публичных metadata на момент publish. Байты не
-- дублируются: отдельная owning-ссылка (`artifact_source_id`) указывает на тот же
-- content-addressed blob, поэтому Draft update не может отсоединить published bytes.
-- Filesystem path, raw upload filename и mutable external reference отсутствуют.
--
-- Закрытая таблица не является универсальным JSON blob: exact published version
-- адресуется composite PK (workspace_id, resource_id, version) и FK на
-- `resource_versions`.
create table resource_publications (
workspace_id text not null,
resource_id text not null,
version integer not null,
uri text not null,
name text not null,
description text not null default '',
kind text not null,
mime_type text not null,
size_bytes bigint not null,
digest text not null,
sensitivity text not null,
artifact_source_id text not null,
published_at timestamptz not null,
constraint resource_publications_version_check check (version >= 1),
constraint resource_publications_uri_len_check check (
octet_length(uri) between 10 and 200
),
constraint resource_publications_name_len_check check (
octet_length(name) between 1 and 64
),
constraint resource_publications_description_len check (
octet_length(description) <= 1024
),
constraint resource_publications_kind_check check (
kind in ('text', 'json', 'binary')
),
constraint resource_publications_mime_type_check check (
octet_length(mime_type) between 3 and 255
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'
),
constraint resource_publications_size_check check (
size_bytes between 1 and 262144
),
constraint resource_publications_digest_check check (digest ~ '^[0-9a-f]{64}$'),
constraint resource_publications_sensitivity_check check (
sensitivity in ('public', 'internal', 'secret')
),
constraint resource_publications_source_id_check check (
artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
),
primary key (workspace_id, resource_id, version),
constraint resource_publications_resource_fkey
foreign key (workspace_id, resource_id)
references resources(workspace_id, resource_id) on delete cascade,
constraint resource_publications_version_fkey
foreign key (workspace_id, resource_id, version)
references resource_versions(workspace_id, resource_id, version)
on delete cascade,
constraint resource_publications_source_fkey
foreign key (workspace_id, artifact_source_id)
references artifact_sources(workspace_id, source_id)
);
create index resource_publications_workspace_uri_idx
on resource_publications (workspace_id, uri, published_at desc);
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "resource-security-revocations-v19";
pub(super) const SOURCE: &str = include_str!("resource_security_revocations_v19.sql");
pub(super) const SOURCE_SHA256: &str =
"e66493a4014af5cbf1ed7532ab7140ce773dc30b0995dea242b791f51dad5bc0";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.resource_security_revocations",
Some(19),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(19),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,47 @@
-- V19: Resource-wide security revocation (Story 3.8, FR-15/FR-16).
--
-- Owner decision A (`t_6f76be08`): revoking a Resource denies every version of it
-- in every Agent, including already published snapshots, and forbids new
-- publications/bindings. The tombstone is also its own immutable transition
-- record: one row per workspace/Resource, the first successful actor/time is
-- never rewritten, and no UPDATE/DELETE/restore path exists in this slice.
--
-- Only the stable identity is stored. No content, URI, name, MIME, digest,
-- reason or secret is duplicated here; archive and the immutable published
-- snapshot bytes stay untouched.
--
-- The composite FK pins the tombstone to an existing Resource of the same
-- workspace, and the actor FK to a real user without cascading deletion, so the
-- audit row cannot outlive its referents or be detached by deleting a user.
-- An empty table means the previous (unrevoked) behaviour, so old installations
-- need no data migration.
create function crank_reject_resource_security_revocation_mutation()
returns trigger
language plpgsql
as $$
begin
raise exception 'resource security revocations are immutable'
using errcode = '23514';
end;
$$;
create table resource_security_revocations (
workspace_id text not null,
resource_id text not null,
revoked_at timestamptz not null,
actor_user_id text not null,
request_id text not null,
trace_id text not null,
primary key (workspace_id, resource_id),
constraint resource_security_revocations_resource_fkey
foreign key (workspace_id, resource_id)
references resources(workspace_id, resource_id) on delete restrict,
constraint resource_security_revocations_actor_fkey
foreign key (actor_user_id) references users(id) on delete restrict
);
create trigger resource_security_revocations_immutable_guard
before update or delete on resource_security_revocations
for each row
execute function crank_reject_resource_security_revocation_mutation();
@@ -0,0 +1,45 @@
use sqlx::{Postgres, Transaction, query};
use super::authority::{MigrationDescriptor, MigrationError};
pub(super) const NAME: &str = "resource-template-sources-v20";
pub(super) const SOURCE: &str = include_str!("resource_template_sources_v20.sql");
pub(super) const SOURCE_SHA256: &str =
"1537f7267f4bb5317242f3c20d613dd9a5b4e5b01cec5c578949f431e91f7502";
pub(super) async fn apply(
transaction: &mut Transaction<'_, Postgres>,
descriptor: &MigrationDescriptor,
) -> Result<(), MigrationError> {
sqlx::raw_sql(SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.resource_template_sources",
Some(20),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(20),
"restore_known_good_backup",
)
})?;
Ok(())
}
@@ -0,0 +1,111 @@
-- V20: byte-less REST-backed Resource template definitions (Story 3.10, FR-16).
--
-- Шаблон не имеет файла содержимого: определение живёт отдельной version-keyed
-- строкой (`resource_template_sources`) рядом с версией, а не в artifact blob.
-- Поэтому `source_kind` отделяет artifact-строки (прежние инварианты байт
-- сохранены буквально) от template-строк (artifact_source_id null, size 0,
-- digest = digest определения).
--
-- Publication snapshot остаётся неизменяемым: `resource_template_sources`
-- insert-only (UPDATE запрещён trigger-ом), а published-версия адресует ту же
-- version-keyed строку, поэтому правка Draft не меняет опубликованное определение.
alter table resource_versions
add column source_kind text not null default 'artifact';
alter table resource_versions
alter column artifact_source_id drop not null;
alter table resource_versions
drop constraint resource_versions_size_check;
alter table resource_versions
add constraint resource_versions_size_check check (
(source_kind = 'artifact' and size_bytes between 1 and 262144)
or (source_kind = 'template' and size_bytes = 0)
);
alter table resource_versions
drop constraint resource_versions_source_id_check;
alter table resource_versions
add constraint resource_versions_source_id_check check (
(
source_kind = 'artifact'
and artifact_source_id is not null
and artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
)
or (source_kind = 'template' and artifact_source_id is null)
);
alter table resource_versions
add constraint resource_versions_source_kind_check check (
source_kind in ('artifact', 'template')
);
alter table resource_publications
add column source_kind text not null default 'artifact';
alter table resource_publications
alter column artifact_source_id drop not null;
alter table resource_publications
drop constraint resource_publications_size_check;
alter table resource_publications
add constraint resource_publications_size_check check (
(source_kind = 'artifact' and size_bytes between 1 and 262144)
or (source_kind = 'template' and size_bytes = 0)
);
alter table resource_publications
drop constraint resource_publications_source_id_check;
alter table resource_publications
add constraint resource_publications_source_id_check check (
(
source_kind = 'artifact'
and artifact_source_id is not null
and artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
)
or (source_kind = 'template' and artifact_source_id is null)
);
alter table resource_publications
add constraint resource_publications_source_kind_check check (
source_kind in ('artifact', 'template')
);
create table resource_template_sources (
workspace_id text not null,
resource_id text not null,
version integer not null,
definition_json text not null,
definition_digest text not null,
created_at timestamptz not null,
constraint resource_template_sources_version_check check (version >= 1),
constraint resource_template_sources_definition_len_check check (
octet_length(definition_json) between 2 and 65536
),
constraint resource_template_sources_digest_check check (
definition_digest ~ '^[0-9a-f]{64}$'
),
primary key (workspace_id, resource_id, version),
constraint resource_template_sources_version_fkey
foreign key (workspace_id, resource_id, version)
references resource_versions(workspace_id, resource_id, version)
on delete cascade
);
create function crank_guard_resource_template_source_immutable()
returns trigger
language plpgsql
as $$
begin
raise exception 'resource template source definitions are immutable';
end;
$$;
create trigger crank_guard_resource_template_source_immutable
before update on resource_template_sources
for each row execute function crank_guard_resource_template_source_immutable();
@@ -2,269 +2,10 @@ use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
pub(super) const OWNED_RELATIONS: &[&str] = &[
"__crank_core_migrations",
"__crank_migrations",
"__crank_migration_legacy_audit",
"__crank_mcp_migrations",
"__crank_ext_migrations",
"mcp_transport_sessions",
"workspaces",
"users",
"memberships",
"user_sessions",
"invitation_tokens",
"platform_api_keys",
"operations",
"operation_versions",
"published_operations",
"operation_samples",
"descriptors",
"agents",
"agent_versions",
"published_agents",
"agent_operation_bindings",
"secrets",
"secret_versions",
"master_key_identities",
"master_key_rotations",
"auth_profiles",
"workspace_upstreams",
"yaml_import_jobs",
"import_jobs",
"approval_requests",
"invocation_logs",
"usage_rollups",
"artifact_blobs",
"artifact_sources",
"import_plans",
"import_plan_applications",
"onboarding_import_selections",
];
mod required_tables;
const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
(
"__crank_core_migrations",
&["version", "description", "checksum", "applied_at"],
),
(
"__crank_migrations",
&[
"version",
"name",
"checksum",
"phase",
"compatibility",
"applied_at",
],
),
(
"__crank_migration_legacy_audit",
&["source", "source_version", "source_checksum", "imported_at"],
),
(
"__crank_mcp_migrations",
&["version", "checksum", "applied_at"],
),
(
"__crank_ext_migrations",
&["extension_name", "version", "checksum", "applied_at"],
),
(
"mcp_transport_sessions",
&[
"id",
"protocol_version",
"initialized",
"supports_elicitation",
"workspace_slug",
"agent_slug",
"created_at",
"updated_at",
"expires_at",
],
),
(
"master_key_identities",
&[
"epoch",
"fingerprint",
"cipher_contract",
"status",
"backup_ref",
"created_at",
"activated_at",
"retired_at",
],
),
(
"master_key_rotations",
&[
"id",
"source_epoch",
"target_epoch",
"target_fingerprint",
"state",
"backup_ref",
"checkpoint_secret_id",
"total_secret_versions",
"processed_secret_versions",
"verified_secret_versions",
"failure_code",
"created_at",
"updated_at",
],
),
];
const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
("__crank_core_migrations", "version", "integer", false),
("__crank_core_migrations", "description", "text", false),
("__crank_core_migrations", "checksum", "text", false),
(
"__crank_core_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migrations", "version", "bigint", false),
("__crank_migrations", "name", "text", false),
("__crank_migrations", "checksum", "text", false),
("__crank_migrations", "phase", "text", false),
("__crank_migrations", "compatibility", "text", false),
(
"__crank_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migration_legacy_audit", "source", "text", false),
(
"__crank_migration_legacy_audit",
"source_version",
"bigint",
false,
),
(
"__crank_migration_legacy_audit",
"source_checksum",
"text",
false,
),
(
"__crank_migration_legacy_audit",
"imported_at",
"timestamp with time zone",
false,
),
("__crank_mcp_migrations", "version", "integer", false),
("__crank_mcp_migrations", "checksum", "text", false),
(
"__crank_mcp_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_ext_migrations", "extension_name", "text", false),
("__crank_ext_migrations", "version", "integer", false),
("__crank_ext_migrations", "checksum", "text", true),
(
"__crank_ext_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("mcp_transport_sessions", "id", "text", false),
("mcp_transport_sessions", "protocol_version", "text", false),
("mcp_transport_sessions", "initialized", "boolean", false),
(
"mcp_transport_sessions",
"supports_elicitation",
"boolean",
false,
),
("mcp_transport_sessions", "workspace_slug", "text", false),
("mcp_transport_sessions", "agent_slug", "text", false),
(
"mcp_transport_sessions",
"created_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"updated_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"expires_at",
"timestamp with time zone",
true,
),
("master_key_identities", "epoch", "bigint", false),
("master_key_identities", "fingerprint", "text", false),
("master_key_identities", "cipher_contract", "text", false),
("master_key_identities", "status", "text", false),
("master_key_identities", "backup_ref", "text", true),
(
"master_key_identities",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_identities",
"activated_at",
"timestamp with time zone",
true,
),
(
"master_key_identities",
"retired_at",
"timestamp with time zone",
true,
),
("master_key_rotations", "id", "text", false),
("master_key_rotations", "source_epoch", "bigint", false),
("master_key_rotations", "target_epoch", "bigint", false),
("master_key_rotations", "target_fingerprint", "text", false),
("master_key_rotations", "state", "text", false),
("master_key_rotations", "backup_ref", "text", true),
("master_key_rotations", "checkpoint_secret_id", "text", true),
(
"master_key_rotations",
"total_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"processed_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"verified_secret_versions",
"bigint",
false,
),
("master_key_rotations", "failure_code", "text", true),
(
"master_key_rotations",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_rotations",
"updated_at",
"timestamp with time zone",
false,
),
];
pub(super) use required_tables::OWNED_RELATIONS;
use required_tables::{REQUIRED_COLUMN_TYPES, REQUIRED_COLUMNS};
pub(super) async fn relation_exists(
connection: &mut PgConnection,
@@ -662,6 +403,71 @@ pub(super) async fn validate_schema_fingerprint(
} else {
super::schema_guard_v15::validate_v15_onboarding_import_selection(connection).await?;
}
if current_version < 16 {
if !super::schema_guard_v16::validate_v16_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v16::validate_v16_resource_drafts(connection, current_version).await?;
}
if current_version < 17 {
if !super::schema_guard_v17::validate_v17_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v17::validate_v17_resource_publications(connection, current_version)
.await?;
}
if current_version < 18 {
if !super::schema_guard_v18::validate_v18_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v18::validate_v18_agent_resource_bindings(connection).await?;
}
if current_version < 19 {
if !super::schema_guard_v19::validate_v19_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v19::validate_v19_resource_security_revocations(connection).await?;
}
if current_version < 20 {
if !super::schema_guard_v20::validate_v20_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v20::validate_v20_resource_template_sources(connection).await?;
}
if current_version < 21 {
for relation in [
"prompts",
"prompt_versions",
"prompt_arguments",
"prompt_messages",
] {
if relation_exists(connection, relation).await? {
return Err(schema_error(current_version));
}
}
} else {
validate_required_relations(connection, super::owned_relations::PROMPTS, current_version)
.await?;
}
if current_version < 22 {
if !super::schema_guard_v22::validate_v22_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v22::validate_v22_prompt_publications(connection).await?;
}
if current_version < 23 {
if !super::schema_guard_v23::validate_v23_absent(connection).await? {
return Err(schema_error(current_version));
}
} else {
super::schema_guard_v23::validate_v23_prompt_dependencies(connection).await?;
}
Ok(())
}
@@ -0,0 +1,414 @@
//! Статические таблицы ожидаемой схемы (вынесены из `schema_guard.rs`, чтобы
//! файл оставался в пределах rust-code-health); поведение guard не меняется.
pub(crate) const OWNED_RELATIONS: &[&str] = &[
"__crank_core_migrations",
"__crank_migrations",
"__crank_migration_legacy_audit",
"__crank_mcp_migrations",
"__crank_ext_migrations",
"mcp_transport_sessions",
"workspaces",
"users",
"memberships",
"user_sessions",
"invitation_tokens",
"platform_api_keys",
"operations",
"operation_versions",
"published_operations",
"operation_samples",
"descriptors",
"agents",
"agent_versions",
"published_agents",
"agent_operation_bindings",
"secrets",
"secret_versions",
"master_key_identities",
"master_key_rotations",
"auth_profiles",
"workspace_upstreams",
"yaml_import_jobs",
"import_jobs",
"approval_requests",
"invocation_logs",
"usage_rollups",
"artifact_blobs",
"artifact_sources",
"import_plans",
"import_plan_applications",
"onboarding_import_selections",
"resources",
"resource_versions",
"resource_publications",
"agent_resource_bindings",
"resource_security_revocations",
"resource_template_sources",
"prompts",
"prompt_versions",
"prompt_arguments",
"prompt_messages",
"prompt_dependencies",
"prompt_message_resource_refs",
];
pub(crate) const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
(
"__crank_core_migrations",
&["version", "description", "checksum", "applied_at"],
),
(
"__crank_migrations",
&[
"version",
"name",
"checksum",
"phase",
"compatibility",
"applied_at",
],
),
(
"__crank_migration_legacy_audit",
&["source", "source_version", "source_checksum", "imported_at"],
),
(
"__crank_mcp_migrations",
&["version", "checksum", "applied_at"],
),
(
"__crank_ext_migrations",
&["extension_name", "version", "checksum", "applied_at"],
),
(
"mcp_transport_sessions",
&[
"id",
"protocol_version",
"initialized",
"supports_elicitation",
"workspace_slug",
"agent_slug",
"created_at",
"updated_at",
"expires_at",
],
),
(
"master_key_identities",
&[
"epoch",
"fingerprint",
"cipher_contract",
"status",
"backup_ref",
"created_at",
"activated_at",
"retired_at",
],
),
(
"master_key_rotations",
&[
"id",
"source_epoch",
"target_epoch",
"target_fingerprint",
"state",
"backup_ref",
"checkpoint_secret_id",
"total_secret_versions",
"processed_secret_versions",
"verified_secret_versions",
"failure_code",
"created_at",
"updated_at",
],
),
(
"prompts",
&[
"workspace_id",
"prompt_id",
"name",
"description",
"status",
"sensitivity",
"current_draft_version",
"latest_published_version",
"created_at",
"updated_at",
],
),
(
"prompt_versions",
&["workspace_id", "prompt_id", "version", "created_at"],
),
(
"prompt_arguments",
&[
"workspace_id",
"prompt_id",
"version",
"argument_name",
"argument_type",
"required",
"default_value",
"enumeration",
"position",
],
),
(
"prompt_messages",
&[
"workspace_id",
"prompt_id",
"version",
"position",
"role",
"content",
],
),
(
"prompt_dependencies",
&[
"workspace_id",
"prompt_id",
"version",
"dependency_position",
"resource_id",
"resource_version",
"digest",
"kind",
"mime_type",
"source_class",
"sensitivity",
],
),
(
"prompt_message_resource_refs",
&[
"workspace_id",
"prompt_id",
"version",
"message_position",
"ref_position",
"dependency_position",
],
),
];
pub(crate) const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
("__crank_core_migrations", "version", "integer", false),
("__crank_core_migrations", "description", "text", false),
("__crank_core_migrations", "checksum", "text", false),
(
"__crank_core_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migrations", "version", "bigint", false),
("__crank_migrations", "name", "text", false),
("__crank_migrations", "checksum", "text", false),
("__crank_migrations", "phase", "text", false),
("__crank_migrations", "compatibility", "text", false),
(
"__crank_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migration_legacy_audit", "source", "text", false),
(
"__crank_migration_legacy_audit",
"source_version",
"bigint",
false,
),
(
"__crank_migration_legacy_audit",
"source_checksum",
"text",
false,
),
(
"__crank_migration_legacy_audit",
"imported_at",
"timestamp with time zone",
false,
),
("__crank_mcp_migrations", "version", "integer", false),
("__crank_mcp_migrations", "checksum", "text", false),
(
"__crank_mcp_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_ext_migrations", "extension_name", "text", false),
("__crank_ext_migrations", "version", "integer", false),
("__crank_ext_migrations", "checksum", "text", true),
(
"__crank_ext_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("mcp_transport_sessions", "id", "text", false),
("mcp_transport_sessions", "protocol_version", "text", false),
("mcp_transport_sessions", "initialized", "boolean", false),
(
"mcp_transport_sessions",
"supports_elicitation",
"boolean",
false,
),
("mcp_transport_sessions", "workspace_slug", "text", false),
("mcp_transport_sessions", "agent_slug", "text", false),
(
"mcp_transport_sessions",
"created_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"updated_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"expires_at",
"timestamp with time zone",
true,
),
("master_key_identities", "epoch", "bigint", false),
("master_key_identities", "fingerprint", "text", false),
("master_key_identities", "cipher_contract", "text", false),
("master_key_identities", "status", "text", false),
("master_key_identities", "backup_ref", "text", true),
(
"master_key_identities",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_identities",
"activated_at",
"timestamp with time zone",
true,
),
(
"master_key_identities",
"retired_at",
"timestamp with time zone",
true,
),
("master_key_rotations", "id", "text", false),
("master_key_rotations", "source_epoch", "bigint", false),
("master_key_rotations", "target_epoch", "bigint", false),
("master_key_rotations", "target_fingerprint", "text", false),
("master_key_rotations", "state", "text", false),
("master_key_rotations", "backup_ref", "text", true),
("master_key_rotations", "checkpoint_secret_id", "text", true),
(
"master_key_rotations",
"total_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"processed_secret_versions",
"bigint",
false,
),
(
"master_key_rotations",
"verified_secret_versions",
"bigint",
false,
),
("master_key_rotations", "failure_code", "text", true),
(
"master_key_rotations",
"created_at",
"timestamp with time zone",
false,
),
(
"master_key_rotations",
"updated_at",
"timestamp with time zone",
false,
),
("prompts", "workspace_id", "text", false),
("prompts", "prompt_id", "text", false),
("prompts", "name", "text", false),
("prompts", "description", "text", false),
("prompts", "status", "text", false),
("prompts", "sensitivity", "text", false),
("prompts", "current_draft_version", "integer", false),
("prompts", "created_at", "timestamp with time zone", false),
("prompts", "updated_at", "timestamp with time zone", false),
("prompt_versions", "workspace_id", "text", false),
("prompt_versions", "prompt_id", "text", false),
("prompt_versions", "version", "integer", false),
(
"prompt_versions",
"created_at",
"timestamp with time zone",
false,
),
("prompt_arguments", "workspace_id", "text", false),
("prompt_arguments", "prompt_id", "text", false),
("prompt_arguments", "version", "integer", false),
("prompt_arguments", "argument_name", "text", false),
("prompt_arguments", "argument_type", "text", false),
("prompt_arguments", "required", "boolean", false),
("prompt_arguments", "default_value", "jsonb", true),
("prompt_arguments", "enumeration", "jsonb", true),
("prompt_arguments", "position", "integer", false),
("prompt_messages", "workspace_id", "text", false),
("prompt_messages", "prompt_id", "text", false),
("prompt_messages", "version", "integer", false),
("prompt_messages", "position", "integer", false),
("prompt_messages", "role", "text", false),
("prompt_messages", "content", "text", false),
("prompt_dependencies", "workspace_id", "text", false),
(
"prompt_dependencies",
"dependency_position",
"integer",
false,
),
("prompt_dependencies", "resource_id", "text", false),
("prompt_dependencies", "resource_version", "integer", false),
("prompt_dependencies", "digest", "text", false),
("prompt_dependencies", "kind", "text", false),
("prompt_dependencies", "mime_type", "text", false),
("prompt_dependencies", "source_class", "text", false),
("prompt_dependencies", "sensitivity", "text", false),
(
"prompt_message_resource_refs",
"message_position",
"integer",
false,
),
(
"prompt_message_resource_refs",
"ref_position",
"integer",
false,
),
(
"prompt_message_resource_refs",
"dependency_position",
"integer",
false,
),
];
@@ -0,0 +1,571 @@
//! V16 schema guard: typed static Resource drafts (Story 3.6).
//!
//! Проверяет, что схема V16 либо полностью отсутствует (миграция ещё не
//! применена), либо присутствует ровно в ожидаемой форме: таблицы, колонки,
//! constraints (точные определения и CHECK-выражения с сохранением SQL-литералов)
//! и частичный unique-index «одна текущая черновая версия».
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const OWNED_RELATIONS: &[&str] = &[
"resources",
"resource_versions",
"resources_workspace_created_idx",
"resource_versions_current_draft_unique",
];
const RESOURCE_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("uri", "text", false),
("name", "text", false),
("description", "text", false),
("status", "text", false),
("kind", "text", false),
("current_draft_version", "integer", false),
("created_at", "timestamp with time zone", false),
("updated_at", "timestamp with time zone", false),
];
const VERSION_COLUMNS_V16: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("kind", "text", false),
("mime_type", "text", false),
("size_bytes", "bigint", false),
("digest", "text", false),
("sensitivity", "text", false),
("artifact_source_id", "text", false),
("created_at", "timestamp with time zone", false),
("superseded_at", "timestamp with time zone", true),
];
/// V20 добавляет `source_kind` и допускает byte-less template-версии: колонки
/// проверяются относительно фактической версии схемы.
const VERSION_COLUMNS_V20: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("kind", "text", false),
("mime_type", "text", false),
("size_bytes", "bigint", false),
("digest", "text", false),
("sensitivity", "text", false),
("artifact_source_id", "text", true),
("source_kind", "text", false),
("created_at", "timestamp with time zone", false),
("superseded_at", "timestamp with time zone", true),
];
fn version_columns(current_version: i64) -> &'static [(&'static str, &'static str, bool)] {
if current_version >= 20 {
VERSION_COLUMNS_V20
} else {
VERSION_COLUMNS_V16
}
}
/// V20 переопределяет два CHECK-а `resource_versions`: template-строки не имеют
/// artifact-ссылки и байтов, artifact-строки сохраняют прежние границы.
const VERSION_CHECK_EXPRESSIONS_V20: &[(&str, &str, &str)] = &[
(
"resource_versions_size_check",
"v16.version_size_check",
"CHECK (source_kind = 'artifact'::text AND size_bytes >= 1 AND size_bytes <= 262144 \
OR source_kind = 'template'::text AND size_bytes = 0)",
),
(
"resource_versions_source_id_check",
"v16.version_source_id_check",
"CHECK (source_kind = 'artifact'::text AND artifact_source_id IS NOT NULL \
AND artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text \
OR source_kind = 'template'::text AND artifact_source_id IS NULL)",
),
];
fn version_check_expectations(
current_version: i64,
) -> Vec<(&'static str, &'static str, &'static str)> {
VERSION_CHECK_EXPRESSIONS
.iter()
.map(|(constraint, stage, legacy)| {
let expected = if current_version >= 20 {
VERSION_CHECK_EXPRESSIONS_V20
.iter()
.find(|(name, _, _)| name == constraint)
.map(|(_, _, expected)| *expected)
.unwrap_or(*legacy)
} else {
*legacy
};
(*constraint, *stage, expected)
})
.collect()
}
/// Определения constraints V16, у которых guard сверяет семантику целиком.
///
/// Имя и `contype` сохраняются у всех однофакторных мутаций (`check (true)`,
/// другая цель/колонки/действие удаления, `NOT VALID`), поэтому ожидание
/// сравнивается с нормализованным `pg_get_constraintdef` и требует
/// `convalidated = true` (P4, TL run105 F06).
const RESOURCE_DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resources_pkey",
"p",
"v16.resources_pkey",
"primarykeyworkspace_id,resource_id",
),
(
"resources_workspace_id_fkey",
"f",
"v16.resources_workspace_id_fkey",
"foreignkeyworkspace_idreferencesworkspacesidondeletecascade",
),
(
"resources_workspace_uri_unique",
"u",
"v16.resources_workspace_uri_unique",
"uniqueworkspace_id,uri",
),
(
"resources_workspace_name_unique",
"u",
"v16.resources_workspace_name_unique",
"uniqueworkspace_id,name",
),
];
const VERSION_DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resource_versions_pkey",
"p",
"v16.version_pkey",
"primarykeyworkspace_id,resource_id,version",
),
(
"resource_versions_resource_fkey",
"f",
"v16.version_resource_fkey",
"foreignkeyworkspace_id,resource_idreferencesresourcesworkspace_id,resource_idondeletecascade",
),
(
"resource_versions_source_fkey",
"f",
"v16.version_source_fkey",
"foreignkeyworkspace_id,artifact_source_idreferencesartifact_sourcesworkspace_id,source_id",
),
];
/// CHECK-выражения V16: сверяется **точное** каноническое определение constraint-а
/// (`pg_get_constraintdef(c.oid, true)`) и `convalidated = true`.
///
/// Ожидания записаны ровно так, как их печатает PostgreSQL 16 (снято из `pg_catalog`
/// на канонической схеме V16), и сравниваются через `normalize_v16_definition`,
/// который убирает пробелы и приводит регистр только вне строковых литералов.
///
/// Подстрочная сверка пропускала `check (octet_length(description) <= 1024 or
/// resource_id is not null)` (TL run109 F5), а сверка «по набору литералов» —
/// перечисляющий CHECK с добавленным предикатом (TL run113 EH1). Общая
/// нормализация, снимающая регистр и пробелы по всей строке, пропускала дрейф
/// **внутри** SQL-литералов: `'^[0-9a-f ]{64}$'` (класс с пробелом) и
/// lowercase-вариант MIME-маски совпадали с каноническими (TL run113 EH2).
const RESOURCE_CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"resources_resource_id_check",
"v16.resources_resource_id_check",
"CHECK (resource_id ~ '^res_[A-Za-z0-9_-]{1,96}$'::text)",
),
(
"resources_uri_len_check",
"v16.resources_uri_len_check",
"CHECK (octet_length(uri) >= 10 AND octet_length(uri) <= 200)",
),
(
"resources_name_len_check",
"v16.resources_name_len_check",
"CHECK (octet_length(name) >= 1 AND octet_length(name) <= 64)",
),
(
"resources_description_len",
"v16.resources_description_len",
"CHECK (octet_length(description) <= 1024)",
),
(
"resources_status_check",
"v16.resources_status_check",
"CHECK (status = ANY (ARRAY['draft'::text, 'published'::text, 'archived'::text]))",
),
(
"resources_kind_check",
"v16.resources_kind_check",
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
),
(
"resources_current_version_check",
"v16.resources_current_version_check",
"CHECK (current_draft_version >= 1)",
),
(
"resources_timestamps_check",
"v16.resources_timestamps_check",
"CHECK (updated_at >= created_at)",
),
];
const VERSION_CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"resource_versions_version_check",
"v16.version_version_check",
"CHECK (version >= 1)",
),
(
"resource_versions_kind_check",
"v16.version_kind_check",
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
),
(
"resource_versions_mime_type_check",
"v16.version_mime_type_check",
"CHECK (octet_length(mime_type) >= 3 AND octet_length(mime_type) <= 255 AND \
mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'::text)",
),
(
"resource_versions_size_check",
"v16.version_size_check",
"CHECK (size_bytes >= 1 AND size_bytes <= 262144)",
),
(
"resource_versions_digest_check",
"v16.version_digest_check",
"CHECK (digest ~ '^[0-9a-f]{64}$'::text)",
),
(
"resource_versions_sensitivity_check",
"v16.version_sensitivity_check",
"CHECK (sensitivity = ANY (ARRAY['public'::text, 'internal'::text, 'secret'::text]))",
),
(
"resource_versions_source_id_check",
"v16.version_source_id_check",
"CHECK (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text)",
),
(
"resource_versions_supersede_check",
"v16.version_supersede_check",
"CHECK (superseded_at IS NULL OR superseded_at >= created_at)",
),
];
/// Отказ guard-а V16 с указанием конкретной проверки: наблюдаемый stage помогает
/// быстро локализовать расхождение схемы, не ослабляя сам отказ.
fn v16_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(16),
"restore_known_good_backup",
)
}
/// Схема V16 отсутствует целиком (для current_version < 16).
pub(super) async fn validate_v16_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
Ok(true)
}
/// Схема V16 присутствует в ожидаемой форме (для current_version >= 16).
pub(super) async fn validate_v16_resource_drafts(
connection: &mut PgConnection,
current_version: i64,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v16_error("v16.relations"));
}
}
validate_columns(
connection,
"resources",
RESOURCE_COLUMNS,
"v16.resources_columns",
)
.await?;
validate_columns(
connection,
"resource_versions",
version_columns(current_version),
"v16.version_columns",
)
.await?;
validate_definitions(connection, "resources", RESOURCE_DEFINITIONS).await?;
validate_definitions(connection, "resource_versions", VERSION_DEFINITIONS).await?;
validate_check_expressions(connection, "resources", RESOURCE_CHECK_EXPRESSIONS).await?;
validate_check_expressions(
connection,
"resource_versions",
&version_check_expectations(current_version),
)
.await?;
validate_current_draft_index(connection).await?;
validate_created_index(connection).await
}
/// Сверка определения constraint: `contype`, `convalidated` и **точное**
/// нормализованное `pg_get_constraintdef`.
///
/// Точное сравнение (а не вхождение ожидаемого префикса) обязательно для FK: иначе
/// дополнительные `ON DELETE`-действия и `DEFERRABLE` остаются разрешёнными
/// (TL run109 F5).
async fn validate_definitions(
connection: &mut PgConnection,
table: &str,
expectations: &[(&'static str, &'static str, &'static str, &'static str)],
) -> Result<(), MigrationError> {
for (constraint, kind, stage, expected) in expectations {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
});
if !valid {
return Err(v16_error(stage));
}
}
Ok(())
}
/// Сверка CHECK-выражений (включая перечисляющие): точное каноническое определение
/// + `convalidated = true`.
///
/// `NOT VALID` сохраняет выражение, поэтому без чтения признака валидации такой дрейф
/// не наблюдается (TL run109 F5). Ожидание — полная каноническая форма PostgreSQL,
/// поэтому добавленный к перечисляющему CHECK предикат тоже виден (TL run113 EH1).
async fn validate_check_expressions(
connection: &mut PgConnection,
table: &str,
expectations: &[(&'static str, &'static str, &'static str)],
) -> Result<(), MigrationError> {
for (constraint, stage, expected) in expectations {
let (definition, convalidated) =
constraint_definition_and_validation(connection, table, constraint, stage).await?;
if !convalidated
|| normalize_v16_definition(&definition) != normalize_v16_definition(expected)
{
return Err(v16_error(stage));
}
}
Ok(())
}
/// Нормализация определения V16: пробелы и регистр снимаются только **вне** строковых
/// литералов.
///
/// Общий `normalize_definition` убирает пробелы и приводит регистр по всей строке,
/// включая содержимое литералов, поэтому `'^[0-9a-f ]{64}$'` (класс с пробелом) и
/// lowercase-вариант MIME-маски становились неотличимы от канонических выражений
/// (TL run113 EH1/EH2). Здесь значимые символы внутри литералов сохраняются, а скобки
/// и операторы вне литералов не удаляются — разные выражения не сливаются.
/// `''` внутри литерала — экранированная кавычка, а не его конец.
fn normalize_v16_definition(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut literal = false;
let mut characters = value.chars().peekable();
while let Some(character) = characters.next() {
if character == '\'' {
normalized.push(character);
if !literal {
literal = true;
} else if characters.peek() == Some(&'\'') {
if let Some(escaped) = characters.next() {
normalized.push(escaped);
}
} else {
literal = false;
}
continue;
}
if literal {
normalized.push(character);
} else if !character.is_ascii_whitespace() {
normalized.push(character.to_ascii_lowercase());
}
}
normalized
}
/// Каноническое определение CHECK-constraint-а V16 и признак его валидации.
///
/// Отсутствие ожидаемого ограничения — отказ именно V16-шага (а не общий preflight
/// другой версии), поэтому stage передаётся в ошибку.
async fn constraint_definition_and_validation(
connection: &mut PgConnection,
table: &str,
constraint: &str,
stage: &'static str,
) -> Result<(String, bool), MigrationError> {
query(
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2
and c.contype = 'c'",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.and_then(|row| {
Some((
row.try_get::<String, _>("definition").ok()?,
row.try_get::<bool, _>("convalidated").ok()?,
))
})
.ok_or_else(|| v16_error(stage))
}
async fn validate_columns(
connection: &mut PgConnection,
table: &str,
columns: &[(&str, &str, bool)],
stage: &'static str,
) -> Result<(), MigrationError> {
for (column, data_type, nullable) in columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2",
)
.bind(table)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v16_error(stage));
}
}
Ok(())
}
async fn validate_current_draft_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
i.indisunique,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_column,
pg_get_expr(i.indpred, i.indrelid) as predicate
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'resource_versions_current_draft_unique'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resource_versions")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(true)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("resource_id")
// У двухколоночного индекса третья позиция пуста (`""`, не NULL).
&& row
.try_get::<String, _>("third_column")
.ok()
.is_none_or(|value| value.is_empty())
&& row
.try_get::<String, _>("predicate")
.ok()
.is_some_and(|value| normalize_definition(&value) == "superseded_atisnull")
});
if valid {
Ok(())
} else {
Err(v16_error("v16.current_draft_index"))
}
}
async fn validate_created_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
i.indisunique, i.indnkeyatts, i.indnatts,
pg_get_expr(i.indpred, i.indrelid) as predicate,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_column
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'resources_workspace_created_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resources")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
// Ровно три ключевых столбца: четвёртый (или INCLUDE-столбец) — дрейф.
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
&& row.try_get::<i16, _>("indnatts").ok() == Some(3)
// Частичный индекс на этом месте — тоже дрейф: предиката быть не должно.
&& row
.try_get::<Option<String>, _>("predicate")
.ok()
.is_none_or(|value| value.is_none())
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("created_at")
&& row.try_get::<String, _>("third_column").ok().as_deref() == Some("resource_id")
});
if valid {
Ok(())
} else {
Err(v16_error("v16.created_index"))
}
}
@@ -0,0 +1,370 @@
//! V17 schema guard: typed immutable Resource publications (Story 3.7).
//!
//! Проверяет, что схема V17 либо полностью отсутствует (миграция ещё не
//! применена), либо присутствует ровно в ожидаемой форме: таблица, колонки,
//! PK/FK и CHECK-выражения снимка публичных metadata плюс индекс разрешения
//! explicit `include:` цели по URI.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const OWNED_RELATIONS: &[&str] = &[
"resource_publications",
"resource_publications_workspace_uri_idx",
];
const COLUMNS_V17: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("uri", "text", false),
("name", "text", false),
("description", "text", false),
("kind", "text", false),
("mime_type", "text", false),
("size_bytes", "bigint", false),
("digest", "text", false),
("sensitivity", "text", false),
("artifact_source_id", "text", false),
("published_at", "timestamp with time zone", false),
];
/// V20 добавляет `source_kind` и допускает byte-less template-публикации.
const COLUMNS_V20: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("uri", "text", false),
("name", "text", false),
("description", "text", false),
("kind", "text", false),
("mime_type", "text", false),
("size_bytes", "bigint", false),
("digest", "text", false),
("sensitivity", "text", false),
("artifact_source_id", "text", true),
("source_kind", "text", false),
("published_at", "timestamp with time zone", false),
];
fn columns(current_version: i64) -> &'static [(&'static str, &'static str, bool)] {
if current_version >= 20 {
COLUMNS_V20
} else {
COLUMNS_V17
}
}
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resource_publications_pkey",
"p",
"v17.pkey",
"primarykeyworkspace_id,resource_id,version",
),
(
"resource_publications_resource_fkey",
"f",
"v17.resource_fkey",
"foreignkeyworkspace_id,resource_idreferencesresourcesworkspace_id,resource_idondeletecascade",
),
(
"resource_publications_version_fkey",
"f",
"v17.version_fkey",
"foreignkeyworkspace_id,resource_id,versionreferencesresource_versionsworkspace_id,resource_id,versionondeletecascade",
),
(
"resource_publications_source_fkey",
"f",
"v17.source_fkey",
"foreignkeyworkspace_id,artifact_source_idreferencesartifact_sourcesworkspace_id,source_id",
),
];
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"resource_publications_version_check",
"v17.version_check",
"CHECK (version >= 1)",
),
(
"resource_publications_uri_len_check",
"v17.uri_len_check",
"CHECK (octet_length(uri) >= 10 AND octet_length(uri) <= 200)",
),
(
"resource_publications_name_len_check",
"v17.name_len_check",
"CHECK (octet_length(name) >= 1 AND octet_length(name) <= 64)",
),
(
"resource_publications_description_len",
"v17.description_len",
"CHECK (octet_length(description) <= 1024)",
),
(
"resource_publications_kind_check",
"v17.kind_check",
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
),
(
"resource_publications_mime_type_check",
"v17.mime_type_check",
"CHECK (octet_length(mime_type) >= 3 AND octet_length(mime_type) <= 255 AND \
mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'::text)",
),
(
"resource_publications_size_check",
"v17.size_check",
"CHECK (size_bytes >= 1 AND size_bytes <= 262144)",
),
(
"resource_publications_digest_check",
"v17.digest_check",
"CHECK (digest ~ '^[0-9a-f]{64}$'::text)",
),
(
"resource_publications_sensitivity_check",
"v17.sensitivity_check",
"CHECK (sensitivity = ANY (ARRAY['public'::text, 'internal'::text, 'secret'::text]))",
),
(
"resource_publications_source_id_check",
"v17.source_id_check",
"CHECK (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text)",
),
];
/// V20 переопределяет два CHECK-а публикаций так же, как у версий.
const CHECK_EXPRESSIONS_V20: &[(&str, &str, &str)] = &[
(
"resource_publications_size_check",
"v17.size_check",
"CHECK (source_kind = 'artifact'::text AND size_bytes >= 1 AND size_bytes <= 262144 \
OR source_kind = 'template'::text AND size_bytes = 0)",
),
(
"resource_publications_source_id_check",
"v17.source_id_check",
"CHECK (source_kind = 'artifact'::text AND artifact_source_id IS NOT NULL \
AND artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text \
OR source_kind = 'template'::text AND artifact_source_id IS NULL)",
),
];
fn check_expectations(current_version: i64) -> Vec<(&'static str, &'static str, &'static str)> {
CHECK_EXPRESSIONS
.iter()
.map(|(constraint, stage, legacy)| {
let expected = if current_version >= 20 {
CHECK_EXPRESSIONS_V20
.iter()
.find(|(name, _, _)| name == constraint)
.map(|(_, _, expected)| *expected)
.unwrap_or(*legacy)
} else {
*legacy
};
(*constraint, *stage, expected)
})
.collect()
}
/// Нормализация определения CHECK: пробелы/регистр снимаются только вне строковых
/// литералов, поэтому ослабленная маска внутри литерала (`'^[0-9a-f ]{64}$'`) и
/// другой регистр в литерале не сливаются с каноническим выражением.
fn normalize_guard_definition(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut literal = false;
let mut characters = value.chars().peekable();
while let Some(character) = characters.next() {
if character == '\'' {
normalized.push(character);
if !literal {
literal = true;
} else if characters.peek() == Some(&'\'') {
if let Some(escaped) = characters.next() {
normalized.push(escaped);
}
} else {
literal = false;
}
continue;
}
if literal {
normalized.push(character);
} else if !character.is_ascii_whitespace() {
normalized.push(character.to_ascii_lowercase());
}
}
normalized
}
fn v17_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(17),
"restore_known_good_backup",
)
}
/// Схема V17 отсутствует целиком (для current_version < 17).
pub(super) async fn validate_v17_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
Ok(true)
}
/// Схема V17 присутствует в ожидаемой форме (для current_version >= 17).
pub(super) async fn validate_v17_resource_publications(
connection: &mut PgConnection,
current_version: i64,
) -> Result<(), MigrationError> {
let columns = columns(current_version);
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v17_error("v17.relations"));
}
}
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_publications'",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
return Err(v17_error("v17.columns"));
}
for (column, data_type, nullable) in columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_publications'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v17_error("v17.columns"));
}
}
for (constraint, kind, stage, expected) in DEFINITIONS {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = 'resource_publications'
and c.conname = $1",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
});
if !valid {
return Err(v17_error(stage));
}
}
for (constraint, stage, expected) in check_expectations(current_version) {
let row = query(
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = 'resource_publications'
and c.conname = $1 and c.contype = 'c'",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_guard_definition(&definition)
== normalize_guard_definition(expected)
})
});
if !valid {
return Err(v17_error(stage));
}
}
validate_uri_index(connection).await
}
async fn validate_uri_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
i.indisunique, i.indnkeyatts, i.indnatts,
pg_get_expr(i.indpred, i.indrelid) as predicate,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_column
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'resource_publications_workspace_uri_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resource_publications")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
&& row.try_get::<i16, _>("indnatts").ok() == Some(3)
&& row
.try_get::<Option<String>, _>("predicate")
.ok()
.is_none_or(|value| value.is_none())
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("uri")
&& row
.try_get::<String, _>("third_column")
.ok()
.is_some_and(|value| value == "published_at" || value == "published_at DESC")
});
if valid {
Ok(())
} else {
Err(v17_error("v17.uri_index"))
}
}
@@ -0,0 +1,333 @@
//! V18 schema guard: typed exact Resource bindings Agent (Story 3.7 AC04).
//!
//! Проверяет, что схема V18 либо полностью отсутствует (миграция ещё не
//! применена), либо присутствует ровно в ожидаемой форме: отдельная таблица
//! `agent_resource_bindings`, workspace-равенство на обоих концах composite FK,
//! exact positive version, immutability trigger для published Agent Version и
//! индексы адресации.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
/// Нормализация определения CHECK: пробелы/регистр снимаются только вне строковых
/// литералов, поэтому ослабленная маска (`'^[0-9a-f ]{64}$'`) не сливается с
/// каноническим выражением (тот же инвариант, что в V17 guard).
fn normalize_guard_definition(value: &str) -> String {
let mut normalized = String::with_capacity(value.len());
let mut literal = false;
let mut characters = value.chars().peekable();
while let Some(character) = characters.next() {
if character == '\'' {
normalized.push(character);
if !literal {
literal = true;
} else if characters.peek() == Some(&'\'') {
if let Some(escaped) = characters.next() {
normalized.push(escaped);
}
} else {
literal = false;
}
continue;
}
if literal {
normalized.push(character);
} else if !character.is_ascii_whitespace() {
normalized.push(character.to_ascii_lowercase());
}
}
normalized
}
const OWNED_RELATIONS: &[&str] = &[
"agent_resource_bindings",
"agent_resource_bindings_resource_idx",
"agents_workspace_id_idx",
];
const COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("agent_id", "text", false),
("agent_version", "integer", false),
("resource_id", "text", false),
("resource_version", "integer", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"agent_resource_bindings_pkey",
"p",
"v18.pkey",
"primarykeyagent_id,agent_version,resource_id,resource_version",
),
(
"agent_resource_bindings_agent_workspace_fkey",
"f",
"v18.agent_workspace_fkey",
"foreignkeyworkspace_id,agent_idreferencesagentsworkspace_id,idondeletecascade",
),
(
"agent_resource_bindings_agent_version_fkey",
"f",
"v18.agent_version_fkey",
"foreignkeyagent_id,agent_versionreferencesagent_versionsagent_id,versionondeletecascade",
),
(
"agent_resource_bindings_publication_fkey",
"f",
"v18.publication_fkey",
"foreignkeyworkspace_id,resource_id,resource_versionreferencesresource_publicationsworkspace_id,resource_id,versionondeletecascade",
),
];
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"agent_resource_bindings_agent_version_check",
"v18.agent_version_check",
"CHECK (agent_version >= 1)",
),
(
"agent_resource_bindings_resource_version_check",
"v18.resource_version_check",
"CHECK (resource_version >= 1)",
),
];
fn v18_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(18),
"restore_known_good_backup",
)
}
/// Схема V18 отсутствует целиком (для current_version < 18).
pub(super) async fn validate_v18_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if trigger_exists(connection).await? {
return Ok(false);
}
if guard_function_exists(connection).await? {
return Ok(false);
}
Ok(true)
}
/// Схема V18 присутствует в ожидаемой форме (для current_version >= 18).
pub(super) async fn validate_v18_agent_resource_bindings(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v18_error("v18.relations"));
}
}
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = 'agent_resource_bindings'",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
return Err(v18_error("v18.columns"));
}
for (column, data_type, nullable) in COLUMNS {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = 'agent_resource_bindings'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v18_error("v18.columns"));
}
}
for (constraint, kind, stage, expected) in DEFINITIONS {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = 'agent_resource_bindings'
and c.conname = $1",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
});
if !valid {
return Err(v18_error(stage));
}
}
for (constraint, stage, expected) in CHECK_EXPRESSIONS {
let row = query(
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = 'agent_resource_bindings'
and c.conname = $1 and c.contype = 'c'",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_guard_definition(&definition)
== normalize_guard_definition(expected)
})
});
if !valid {
return Err(v18_error(stage));
}
}
if !trigger_exists(connection).await? {
return Err(v18_error("v18.immutable_trigger"));
}
validate_agent_workspace_index(connection).await?;
validate_resource_index(connection).await
}
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = 'agent_resource_bindings'
and tg.tgname = 'agent_resource_bindings_immutable_guard'
and p.proname = 'crank_reject_published_agent_resource_binding_mutation'
and not tg.tgisinternal
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema()
and p.proname = 'crank_reject_published_agent_resource_binding_mutation'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn validate_agent_workspace_index(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid,
i.indisready, i.indisunique, i.indnkeyatts,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema() and idx.relname = 'agents_workspace_id_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("agents")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(true)
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(2)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("id")
});
if valid {
Ok(())
} else {
Err(v18_error("v18.agents_workspace_index"))
}
}
async fn validate_resource_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
let row = query(
"select t.relname as table_name, am.amname as access_method, i.indisvalid,
i.indisready, i.indisunique, i.indnkeyatts,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_indexdef(i.indexrelid, 3, true) as third_column
from pg_catalog.pg_index i
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
join pg_catalog.pg_class t on t.oid = i.indrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema()
and idx.relname = 'agent_resource_bindings_resource_idx'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("agent_resource_bindings")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("resource_id")
&& row.try_get::<String, _>("third_column").ok().as_deref() == Some("resource_version")
});
if valid {
Ok(())
} else {
Err(v18_error("v18.resource_index"))
}
}
@@ -0,0 +1,185 @@
//! V19 schema guard: immutable Resource security revocation tombstones (Story 3.8).
//!
//! Проверяет, что схема V19 либо полностью отсутствует (миграция ещё не
//! применена), либо присутствует ровно в ожидаемой форме: одна таблица
//! `resource_security_revocations` с составным PK, FK на `resources` и `users`
//! без каскадного удаления и trigger неизменяемости. Bounded request/trace
//! значения задаются серверными типами (`RequestId`/`TraceContext`), а не
//! пользовательским вводом.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const OWNED_RELATIONS: &[&str] = &["resource_security_revocations"];
const COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("revoked_at", "timestamp with time zone", false),
("actor_user_id", "text", false),
("request_id", "text", false),
("trace_id", "text", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resource_security_revocations_pkey",
"p",
"v19.pkey",
"primary key (workspace_id, resource_id)",
),
(
"resource_security_revocations_resource_fkey",
"f",
"v19.resource_fkey",
"foreign key (workspace_id, resource_id)
references resources(workspace_id, resource_id) on delete restrict",
),
(
"resource_security_revocations_actor_fkey",
"f",
"v19.actor_fkey",
"foreign key (actor_user_id) references users(id) on delete restrict",
),
];
fn v19_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(19),
"restore_known_good_backup",
)
}
/// Схема V19 отсутствует целиком (для current_version < 19).
pub(super) async fn validate_v19_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if guard_function_exists(connection).await? {
return Ok(false);
}
Ok(!trigger_exists(connection).await?)
}
/// Схема V19 присутствует в ожидаемой форме (для current_version >= 19).
pub(super) async fn validate_v19_resource_security_revocations(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v19_error("v19.relations"));
}
}
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_security_revocations'",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
return Err(v19_error("v19.columns"));
}
for (column, data_type, nullable) in COLUMNS {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_security_revocations'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v19_error("v19.columns"));
}
}
for (constraint, kind, stage, expected) in DEFINITIONS {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = 'resource_security_revocations'
and c.conname = $1",
)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
});
if !valid {
return Err(v19_error(stage));
}
}
if !trigger_exists(connection).await? {
return Err(v19_error("v19.immutable_trigger"));
}
if !guard_function_exists(connection).await? {
return Err(v19_error("v19.immutable_trigger"));
}
Ok(())
}
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = 'resource_security_revocations'
and tg.tgname = 'resource_security_revocations_immutable_guard'
and p.proname = 'crank_reject_resource_security_revocation_mutation'
and not tg.tgisinternal
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema()
and p.proname = 'crank_reject_resource_security_revocation_mutation'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
@@ -0,0 +1,293 @@
//! V20 schema guard: byte-less REST-backed Resource template sources (Story 3.10).
//!
//! Схема V20 либо полностью отсутствует (миграция ещё не применена), либо
//! присутствует ровно в ожидаемой форме: `resource_template_sources` с
//! version-keyed PK/FK на версию, insert-only trigger, а в `resource_versions` и
//! `resource_publications` — `source_kind` и CHECK-и, которые допускают byte-less
//! template-строки, сохраняя прежние ограничения artifact-строк.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const OWNED_RELATIONS: &[&str] = &["resource_template_sources"];
const COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("resource_id", "text", false),
("version", "integer", false),
("definition_json", "text", false),
("definition_digest", "text", false),
("created_at", "timestamp with time zone", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
(
"resource_template_sources_pkey",
"p",
"v20.pkey",
"primary key (workspace_id, resource_id, version)",
),
(
"resource_template_sources_version_fkey",
"f",
"v20.version_fkey",
"foreign key (workspace_id, resource_id, version)
references resource_versions(workspace_id, resource_id, version)
on delete cascade",
),
];
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
(
"resource_template_sources_version_check",
"v20.version_check",
"CHECK (version >= 1)",
),
(
"resource_template_sources_definition_len_check",
"v20.definition_len_check",
"CHECK (octet_length(definition_json) >= 2 AND octet_length(definition_json) <= 65536)",
),
(
"resource_template_sources_digest_check",
"v20.digest_check",
"CHECK (definition_digest ~ '^[0-9a-f]{64}$'::text)",
),
(
"resource_versions_source_kind_check",
"v20.version_source_kind_check",
"CHECK (source_kind = ANY (ARRAY['artifact'::text, 'template'::text]))",
),
(
"resource_publications_source_kind_check",
"v20.publication_source_kind_check",
"CHECK (source_kind = ANY (ARRAY['artifact'::text, 'template'::text]))",
),
];
fn v20_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(20),
"restore_known_good_backup",
)
}
/// Схема V20 отсутствует целиком (для current_version < 20).
pub(super) async fn validate_v20_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if guard_function_exists(connection).await? {
return Ok(false);
}
if trigger_exists(connection).await? {
return Ok(false);
}
for (table, column) in [
("resource_versions", "source_kind"),
("resource_publications", "source_kind"),
] {
if column_exists(connection, table, column).await? {
return Ok(false);
}
}
Ok(true)
}
/// Схема V20 присутствует в ожидаемой форме (для current_version >= 20).
pub(super) async fn validate_v20_resource_template_sources(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
if !relation_exists(connection, "resource_template_sources").await? {
return Err(v20_error("v20.relations"));
}
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_template_sources'",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
return Err(v20_error("v20.columns"));
}
for (column, data_type, nullable) in COLUMNS {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = 'resource_template_sources'
and column_name = $1",
)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v20_error("v20.columns"));
}
}
// `source_kind` добавлен в обе существующие resource-таблицы: template-строки
// без него неотличимы от artifact-строк, поэтому его форма обязательна.
for table in ["resource_versions", "resource_publications"] {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1
and column_name = 'source_kind'",
)
.bind(table)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some("text")
&& row.try_get::<String, _>("is_nullable").ok().as_deref() == Some("NO")
});
if !valid {
return Err(v20_error("v20.source_kind"));
}
}
for (constraint, kind, stage, expected) in DEFINITIONS {
if !constraint_matches(
connection,
"resource_template_sources",
constraint,
kind,
expected,
)
.await?
{
return Err(v20_error(stage));
}
}
for (constraint, stage, expected) in CHECK_EXPRESSIONS {
let table = if constraint.starts_with("resource_template_sources") {
"resource_template_sources"
} else if constraint.starts_with("resource_versions") {
"resource_versions"
} else {
"resource_publications"
};
if !check_matches(connection, table, constraint, expected).await? {
return Err(v20_error(stage));
}
}
if !trigger_exists(connection).await? {
return Err(v20_error("v20.immutable_trigger"));
}
if !guard_function_exists(connection).await? {
return Err(v20_error("v20.immutable_trigger"));
}
Ok(())
}
async fn constraint_matches(
connection: &mut PgConnection,
table: &str,
constraint: &str,
kind: &str,
expected: &str,
) -> Result<bool, MigrationError> {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
Ok(row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
}))
}
async fn check_matches(
connection: &mut PgConnection,
table: &str,
constraint: &str,
expected: &str,
) -> Result<bool, MigrationError> {
constraint_matches(connection, table, constraint, "c", expected).await
}
async fn column_exists(
connection: &mut PgConnection,
table: &str,
column: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2
) as present",
)
.bind(table)
.bind(column)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = 'resource_template_sources'
and tg.tgname = 'crank_guard_resource_template_source_immutable'
and p.proname = 'crank_guard_resource_template_source_immutable'
and not tg.tgisinternal
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema()
and p.proname = 'crank_guard_resource_template_source_immutable'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
@@ -0,0 +1,299 @@
//! V22 schema guard: immutable Published Prompt Versions и typed exact Prompt
//! bindings Agent (Story 3.13, FR-17).
//!
//! Схема V22 либо полностью отсутствует (миграция ещё не применена), либо
//! присутствует ровно в ожидаемой форме: `prompt_publications` с composite PK/FK,
//! `agent_prompt_bindings` с workspace-safe FK на обоих концах, nullable
//! `prompts.latest_published_version` и guard-триггеры неизменяемости
//! опубликованной definition/публикации и bindings опубликованного Agent.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const PUBLICATION: &str = "prompt_publications";
const BINDINGS: &str = "agent_prompt_bindings";
const OWNED_RELATIONS: &[&str] = &[PUBLICATION, BINDINGS];
const PUBLICATION_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("prompt_id", "text", false),
("version", "integer", false),
("name", "text", false),
("description", "text", false),
("sensitivity", "text", false),
("published_at", "timestamp with time zone", false),
];
const BINDING_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("agent_id", "text", false),
("agent_version", "integer", false),
("prompt_id", "text", false),
("prompt_version", "integer", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str, &str)] = &[
(
PUBLICATION,
"prompt_publications_pkey",
"p",
"v22.publication_pkey",
"primary key (workspace_id, prompt_id, version)",
),
(
PUBLICATION,
"prompt_publications_prompt_fkey",
"f",
"v22.publication_prompt_fkey",
"foreign key (workspace_id, prompt_id) references prompts(workspace_id, prompt_id) on delete cascade",
),
(
PUBLICATION,
"prompt_publications_version_fkey",
"f",
"v22.publication_version_fkey",
"foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
),
(
BINDINGS,
"agent_prompt_bindings_pkey",
"p",
"v22.binding_pkey",
"primary key (agent_id, agent_version, prompt_id)",
),
(
BINDINGS,
"agent_prompt_bindings_agent_workspace_fkey",
"f",
"v22.binding_agent_workspace_fkey",
"foreign key (workspace_id, agent_id) references agents(workspace_id, id) on delete cascade",
),
(
BINDINGS,
"agent_prompt_bindings_agent_version_fkey",
"f",
"v22.binding_agent_version_fkey",
"foreign key (agent_id, agent_version)
references agent_versions(agent_id, version) on delete cascade",
),
(
BINDINGS,
"agent_prompt_bindings_publication_fkey",
"f",
"v22.binding_publication_fkey",
"foreign key (workspace_id, prompt_id, prompt_version)
references prompt_publications(workspace_id, prompt_id, version) on delete cascade",
),
];
const TRIGGERS: &[(&str, &str, &str)] = &[
(
"prompt_arguments",
"prompt_arguments_immutable_guard",
"crank_reject_published_prompt_version_mutation",
),
(
"prompt_messages",
"prompt_messages_immutable_guard",
"crank_reject_published_prompt_version_mutation",
),
(
PUBLICATION,
"prompt_publications_immutable_guard",
"crank_reject_prompt_publication_mutation",
),
(
BINDINGS,
"agent_prompt_bindings_immutable_guard",
"crank_reject_published_agent_prompt_binding_mutation",
),
];
fn v22_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(22),
"restore_known_good_backup",
)
}
/// Схема V22 отсутствует целиком (для current_version < 22).
pub(super) async fn validate_v22_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if super::schema_guard::column_exists(connection, "prompts", "latest_published_version").await?
{
return Ok(false);
}
for (_, _, function) in TRIGGERS {
if function_exists(connection, function).await? {
return Ok(false);
}
}
Ok(true)
}
/// Схема V22 присутствует в ожидаемой форме (для current_version >= 22).
pub(super) async fn validate_v22_prompt_publications(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v22_error("v22.relations"));
}
}
if !super::schema_guard::column_exists(connection, "prompts", "latest_published_version")
.await?
{
return Err(v22_error("v22.prompt_columns"));
}
for (table, columns) in [
(PUBLICATION, PUBLICATION_COLUMNS),
(BINDINGS, BINDING_COLUMNS),
] {
validate_columns(connection, table, columns).await?;
}
for (table, constraint, kind, stage, expected) in DEFINITIONS {
if !constraint_matches(connection, table, constraint, kind, expected).await? {
return Err(v22_error(stage));
}
}
for (table, trigger, function) in TRIGGERS {
if !trigger_exists(connection, table, trigger, function).await? {
return Err(v22_error("v22.immutable_trigger"));
}
}
Ok(())
}
async fn validate_columns(
connection: &mut PgConnection,
table: &str,
columns: &[(&str, &str, bool)],
) -> Result<(), MigrationError> {
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = $1",
)
.bind(table)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
return Err(v22_error("v22.columns"));
}
for (column, data_type, nullable) in columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2",
)
.bind(table)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v22_error("v22.columns"));
}
}
Ok(())
}
async fn constraint_matches(
connection: &mut PgConnection,
table: &str,
constraint: &str,
kind: &str,
expected: &str,
) -> Result<bool, MigrationError> {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = $1
and c.conname = $2",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
Ok(row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
}))
}
async fn trigger_exists(
connection: &mut PgConnection,
table: &str,
trigger: &str,
function: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = $1
and tg.tgname = $2
and p.proname = $3
and not tg.tgisinternal
) as present",
)
.bind(table)
.bind(trigger)
.bind(function)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn function_exists(
connection: &mut PgConnection,
function: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where n.nspname = current_schema() and p.proname = $1
) as present",
)
.bind(function)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
@@ -0,0 +1,239 @@
//! V23 schema guard: version-keyed pinned Prompt dependencies (Story 3.16, FR-18).
//!
//! Схема V23 либо полностью отсутствует (миграция ещё не применена), либо присутствует ровно в
//! ожидаемой форме: `prompt_dependencies` с composite PK/FK на `prompt_versions`,
//! `prompt_message_resource_refs` с упорядоченными точками вставки и guard-триггеры
//! неизменяемости опубликованной версии на обеих таблицах.
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
use super::schema_guard::{normalize_definition, relation_exists};
const DEPENDENCIES: &str = "prompt_dependencies";
const RESOURCE_REFS: &str = "prompt_message_resource_refs";
const GUARD_FUNCTION: &str = "crank_reject_published_prompt_version_mutation";
const OWNED_RELATIONS: &[&str] = &[DEPENDENCIES, RESOURCE_REFS];
const DEPENDENCY_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("prompt_id", "text", false),
("version", "integer", false),
("dependency_position", "integer", false),
("resource_id", "text", false),
("resource_version", "integer", false),
("digest", "text", false),
("kind", "text", false),
("mime_type", "text", false),
("source_class", "text", false),
("sensitivity", "text", false),
];
const REF_COLUMNS: &[(&str, &str, bool)] = &[
("workspace_id", "text", false),
("prompt_id", "text", false),
("version", "integer", false),
("message_position", "integer", false),
("ref_position", "integer", false),
("dependency_position", "integer", false),
];
const DEFINITIONS: &[(&str, &str, &str, &str, &str)] = &[
(
DEPENDENCIES,
"prompt_dependencies_pkey",
"p",
"v23.dependencies_pkey",
"primary key (workspace_id, prompt_id, version, dependency_position)",
),
(
DEPENDENCIES,
"prompt_dependencies_version_fkey",
"f",
"v23.dependencies_version_fkey",
"foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
),
(
RESOURCE_REFS,
"prompt_message_resource_refs_pkey",
"p",
"v23.refs_pkey",
"primary key (workspace_id, prompt_id, version, message_position, ref_position)",
),
(
RESOURCE_REFS,
"prompt_message_resource_refs_version_fkey",
"f",
"v23.refs_version_fkey",
"foreign key (workspace_id, prompt_id, version)
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
),
];
fn v23_error(stage: &'static str) -> MigrationError {
MigrationError::new(
"partial_sequence",
stage,
Some(23),
"restore_known_good_backup",
)
}
/// Схема V23 отсутствует целиком (для current_version < 23).
pub(super) async fn validate_v23_absent(
connection: &mut PgConnection,
) -> Result<bool, MigrationError> {
for relation in OWNED_RELATIONS {
if relation_exists(connection, relation).await? {
return Ok(false);
}
}
if trigger_exists(
connection,
DEPENDENCIES,
"prompt_dependencies_immutable_guard",
)
.await?
{
return Ok(false);
}
Ok(true)
}
/// Схема V23 присутствует в ожидаемой форме (для current_version >= 23).
pub(super) async fn validate_v23_prompt_dependencies(
connection: &mut PgConnection,
) -> Result<(), MigrationError> {
for relation in OWNED_RELATIONS {
if !relation_exists(connection, relation).await? {
return Err(v23_error("v23.relations"));
}
}
for (table, columns) in [
(DEPENDENCIES, DEPENDENCY_COLUMNS),
(RESOURCE_REFS, REF_COLUMNS),
] {
validate_columns(connection, table, columns).await?;
}
for (table, constraint, kind, stage, expected) in DEFINITIONS {
if !constraint_matches(connection, table, constraint, kind, expected).await? {
return Err(v23_error(stage));
}
}
for (table, trigger) in [
(DEPENDENCIES, "prompt_dependencies_immutable_guard"),
(
RESOURCE_REFS,
"prompt_message_resource_refs_immutable_guard",
),
] {
if !trigger_exists(connection, table, trigger).await? {
return Err(v23_error("v23.immutable_trigger"));
}
}
Ok(())
}
async fn validate_columns(
connection: &mut PgConnection,
table: &str,
columns: &[(&str, &str, bool)],
) -> Result<(), MigrationError> {
let column_count: i64 = query(
"select count(*)::bigint as count from information_schema.columns
where table_schema = current_schema() and table_name = $1",
)
.bind(table)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get("count")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
return Err(v23_error("v23.columns"));
}
for (column, data_type, nullable) in columns {
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2",
)
.bind(table)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(v23_error("v23.columns"));
}
}
Ok(())
}
async fn constraint_matches(
connection: &mut PgConnection,
table: &str,
constraint: &str,
kind: &str,
expected: &str,
) -> Result<bool, MigrationError> {
let row = query(
"select c.contype::text as kind, c.convalidated,
pg_get_constraintdef(c.oid, true) as definition
from pg_catalog.pg_constraint c
join pg_catalog.pg_class t on t.oid = c.conrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where n.nspname = current_schema()
and t.relname = $1
and c.conname = $2",
)
.bind(table)
.bind(constraint)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
Ok(row.is_some_and(|row| {
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
&& row
.try_get::<String, _>("definition")
.ok()
.is_some_and(|definition| {
normalize_definition(&definition) == normalize_definition(expected)
})
}))
}
async fn trigger_exists(
connection: &mut PgConnection,
table: &str,
trigger: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 from pg_catalog.pg_trigger tg
join pg_catalog.pg_class t on t.oid = tg.tgrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
where n.nspname = current_schema()
and t.relname = $1
and tg.tgname = $2
and p.proname = $3
and not tg.tgisinternal
) as present",
)
.bind(table)
.bind(trigger)
.bind(GUARD_FUNCTION)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}