story 2-12-preview-partial-mode: implemented and reviewed via bmad-loop

This commit is contained in:
bsodfather committed 2026-10-03 15:04:15 +03:00
1 parent d1ba0bd0e4
commit ab35d67177
56 files changed
+5801 -376

No files matched your search

@@ -10,6 +10,7 @@ use time::format_description::well_known::Rfc3339;
mod apply;
mod create;
mod preview_v2;
pub(super) fn parse_ts(value: &str) -> OffsetDateTime {
OffsetDateTime::parse(value, &Rfc3339).unwrap()
}
@@ -0,0 +1,787 @@
//! Story 2.12 evidence for v2 semantic digests, catalog drift and Apply.
use super::super::common::{TestDatabase, test_operation};
use super::{create_pending_openapi_job, create_workspace, parse_ts};
use crank_artifacts::ArtifactRef;
use crank_core::{OperationStatus, WorkspaceId};
use crank_registry::{
ApplyImportPlanRequest, ArtifactSourceId, CreateImportJobRequest, CreateImportPlanRequest,
ImportJobId, ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportPlanApplyStatus,
ImportPlanCandidateOutcome, ImportPlanId, RegistryError,
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::{Duration, OffsetDateTime};
const SOURCE_ID: &str = "src_openapi_test";
const SOURCE_DIGEST: &str =
"sha256:abababababababababababababababababababababababababababababababab";
fn fingerprint() -> Value {
json!({"importer": "registry-preview-v2-test", "preview_digest": "fp-v2-1"})
}
fn operation(
id: &str,
name: &str,
created_at: &str,
updated_at: &str,
) -> crank_registry::RegistryOperation {
let mut operation = test_operation(id, 1, OperationStatus::Draft);
operation.name = name.to_owned();
operation.display_name = "Candidate display name".to_owned();
operation.execution_config.auth_profile_ref = None;
operation.created_at = parse_ts(created_at);
operation.updated_at = parse_ts(updated_at);
operation
}
fn v2_payload(
plan_id: &str,
job_id: &str,
source_id: &str,
operation: crank_registry::RegistryOperation,
catalog_revision: &str,
) -> Value {
let key = "candidate";
json!({
"schema_version": "import-plan-v2",
"plan_reference": plan_id,
"job_id": job_id,
"fingerprint": fingerprint(),
"catalog_revision": catalog_revision,
"support_matrix_version": "1.0.2",
"source": { "source_id": source_id, "digest": SOURCE_DIGEST },
"dependencies": [],
"excluded_reasons": [],
"findings": { "document": [], "candidates": [{ "key": key, "findings": [] }] },
"selection": {
"mode": "full", "all": [key], "selected": [key], "excluded": []
},
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
"candidates": [{
"key": key,
"name": operation.name,
"state": "actionable",
"decision": { "action": "create" },
"findings": [],
"operation": operation
}]
})
}
async fn store_plan(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
job_id: &ImportJobId,
plan_id: &str,
payload: &Value,
created_at: OffsetDateTime,
) -> (ImportPlanId, String) {
let plan_id = ImportPlanId::new(plan_id);
let created = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan_id,
workspace_id,
job_id,
payload,
created_at: &created_at,
expires_at: &(created_at + Duration::minutes(30)),
})
.await
.unwrap();
(plan_id, created.digest)
}
async fn activate_source(raw: &sqlx::PgPool, workspace_id: &WorkspaceId, now: OffsetDateTime) {
let hex = "ab".repeat(32);
sqlx::query(
"insert into artifact_blobs (digest, artifact_ref, size_bytes, created_at, updated_at)
values ($1, 'sha256:' || $1, 16, $2, $2)",
)
.bind(&hex)
.bind(now)
.execute(raw)
.await
.unwrap();
sqlx::query(
"insert into artifact_sources (
workspace_id, source_id, blob_digest, mime_type, sensitivity, lifecycle,
created_at, updated_at
) values ($1, $2, $3, 'application/yaml', 'public', 'active', $4, $4)",
)
.bind(workspace_id.as_str())
.bind(SOURCE_ID)
.bind(&hex)
.bind(now)
.execute(raw)
.await
.unwrap();
}
async fn create_job_with_source(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
job_id: &str,
source_id: &str,
now: OffsetDateTime,
) -> ImportJobId {
let job_id = ImportJobId::new(job_id);
let source_id = ArtifactSourceId::new(source_id);
let digest = ArtifactRef::from_digest_hex(&"ab".repeat(32)).unwrap();
let preview_payload = json!({
"source": {"source_id": source_id.as_str(), "digest": digest.as_str()},
"preview": {"source": "integration-test"}
});
registry
.create_import_job(CreateImportJobRequest {
id: &job_id,
workspace_id,
kind: ImportJobKind::OpenApi,
source_format: "openapi",
source_version: Some("3.1.0"),
status: ImportJobStatus::Pending,
source: &ImportJobSourceEnvelope { source_id, digest },
preview_payload: &preview_payload,
created_at: &now,
expires_at: &(now + Duration::hours(1)),
})
.await
.unwrap();
job_id
}
fn raw_digest(payload: &Value) -> String {
format!("{:x}", Sha256::digest(serde_json::to_vec(payload).unwrap()))
}
#[tokio::test]
async fn v2_digest_ignores_job_plan_generated_operation_ids_and_runtime_timestamps() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let ws = create_workspace(&registry, "ws_v2_digest").await;
let first_time =
OffsetDateTime::from_unix_timestamp(OffsetDateTime::now_utc().unix_timestamp()).unwrap();
let second_time = first_time + Duration::minutes(2);
let first_job =
create_job_with_source(&registry, &ws, "job_v2_digest_a", "src_v2_a", first_time).await;
let second_job =
create_job_with_source(&registry, &ws, "job_v2_digest_b", "src_v2_b", second_time).await;
let revision = registry.import_catalog_revision(&ws).await.unwrap();
let first_payload = v2_payload(
"plan_v2_digest_a",
first_job.as_str(),
"src_v2_a",
operation(
"op_generated_a",
"candidate_tool",
"2026-03-25T10:00:00Z",
"2026-03-25T10:00:00Z",
),
&revision,
);
let second_payload = v2_payload(
"plan_v2_digest_b",
second_job.as_str(),
"src_v2_b",
operation(
"op_generated_b",
"candidate_tool",
"2026-03-25T10:02:00Z",
"2026-03-25T10:02:00Z",
),
&revision,
);
let (_, first_digest) = store_plan(
&registry,
&ws,
&first_job,
"plan_v2_digest_a",
&first_payload,
first_time,
)
.await;
let (_, second_digest) = store_plan(
&registry,
&ws,
&second_job,
"plan_v2_digest_b",
&second_payload,
second_time,
)
.await;
assert_eq!(
first_digest, second_digest,
"server identities and runtime instants must not change semantic identity"
);
assert_eq!(
registry
.get_import_plan(&ws, &ImportPlanId::new("plan_v2_digest_a"))
.await
.unwrap()
.unwrap()
.payload,
first_payload,
"canonical hashing must leave immutable v2 evidence untouched"
);
let mut replay_with_new_generated_id = first_payload.clone();
replay_with_new_generated_id["candidates"][0]["operation"]["id"] = json!("op_generated_retry");
let plan_id = ImportPlanId::new("plan_v2_digest_a");
let conflict = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan_id,
workspace_id: &ws,
job_id: &first_job,
payload: &replay_with_new_generated_id,
created_at: &first_time,
expires_at: &(first_time + Duration::minutes(30)),
})
.await
.expect_err("replay identity still compares immutable raw payload after semantic hashing");
assert!(matches!(conflict, RegistryError::ImportPlanConflict { .. }));
database.cleanup().await;
}
#[tokio::test]
async fn v2_digest_changes_for_selection_name_and_conflict_decision() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, "ws_v2_semantics").await;
let job = create_pending_openapi_job(
&registry,
&ws,
"job_v2_semantics",
now,
now + Duration::hours(1),
)
.await;
let revision = registry.import_catalog_revision(&ws).await.unwrap();
let base = v2_payload(
"plan_semantic_base",
job.as_str(),
SOURCE_ID,
operation(
"op_base",
"candidate_tool",
"2026-10-03T10:00:00Z",
"2026-10-03T10:00:00Z",
),
&revision,
);
let mut changed_selection = base.clone();
changed_selection["plan_reference"] = json!("plan_semantic_selection");
changed_selection["selection"]["mode"] = json!("partial");
changed_selection["selection"]["all"] = json!(["candidate", "other"]);
changed_selection["selection"]["excluded"] = json!(["other"]);
changed_selection["counts"]["excluded"] = json!(1);
changed_selection["excluded_reasons"] = json!([{"key": "other", "reason": "not_selected"}]);
changed_selection["findings"]["candidates"] = json!([
{"key": "candidate", "findings": []}, {"key": "other", "findings": []}
]);
let mut changed_name = base.clone();
changed_name["plan_reference"] = json!("plan_semantic_name");
changed_name["candidates"][0]["name"] = json!("renamed_tool");
changed_name["candidates"][0]["operation"]["name"] = json!("renamed_tool");
let mut changed_decision = base.clone();
changed_decision["plan_reference"] = json!("plan_semantic_decision");
changed_decision["candidates"][0]["decision"] =
json!({"action": "rename", "confirmed_name": "candidate_tool"});
let mut changed_support_matrix = base.clone();
changed_support_matrix["plan_reference"] = json!("plan_semantic_support");
changed_support_matrix["support_matrix_version"] = json!("1.0.3");
let (_, digest) = store_plan(&registry, &ws, &job, "plan_semantic_base", &base, now).await;
let (_, selection_digest) = store_plan(
&registry,
&ws,
&job,
"plan_semantic_selection",
&changed_selection,
now,
)
.await;
let (_, name_digest) = store_plan(
&registry,
&ws,
&job,
"plan_semantic_name",
&changed_name,
now,
)
.await;
let (_, decision_digest) = store_plan(
&registry,
&ws,
&job,
"plan_semantic_decision",
&changed_decision,
now,
)
.await;
let (_, support_matrix_digest) = store_plan(
&registry,
&ws,
&job,
"plan_semantic_support",
&changed_support_matrix,
now,
)
.await;
assert_ne!(digest, selection_digest, "selection changes are semantic");
assert_ne!(
digest, name_digest,
"the confirmed operation name is semantic"
);
assert_ne!(
digest, decision_digest,
"conflict resolution choices are semantic"
);
assert_ne!(
digest, support_matrix_digest,
"the support matrix version is semantic evidence"
);
database.cleanup().await;
}
#[tokio::test]
async fn legacy_v1_digest_and_stored_payload_remain_unchanged_and_readable() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, "ws_v1_compat").await;
let job = create_pending_openapi_job(
&registry,
&ws,
"job_v1_compat",
now,
now + Duration::hours(1),
)
.await;
let plan_id = ImportPlanId::new("plan_v1_compat");
let payload = json!({
"schema_version": "import-plan-v1", "plan_reference": plan_id.as_str(), "job_id": job.as_str(),
"fingerprint": {"legacy": true}, "source": {"source_id": SOURCE_ID, "digest": SOURCE_DIGEST},
"dependencies": [], "selection": {"mode": "full", "all": ["legacy"], "selected": ["legacy"], "excluded": []},
"counts": {"selected": 1, "excluded": 0, "actionable": 1, "blocked": 0},
"candidates": [{"key": "legacy", "name": "legacy_tool", "state": "actionable", "decision": {"action": "create"}}]
});
let created = registry
.create_import_plan(CreateImportPlanRequest {
id: &plan_id,
workspace_id: &ws,
job_id: &job,
payload: &payload,
created_at: &now,
expires_at: &(now + Duration::minutes(30)),
})
.await
.unwrap();
assert_eq!(
created.digest,
raw_digest(&payload),
"legacy v1 keeps byte-for-byte digest rules"
);
let read = registry
.get_import_plan(&ws, &plan_id)
.await
.unwrap()
.expect("stored v1 plan remains readable");
assert_eq!(read.payload, payload);
assert_eq!(read.digest, created.digest);
database.cleanup().await;
}
#[tokio::test]
async fn catalog_revision_ignores_timestamps_and_foreign_workspace_but_tracks_semantics() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let raw = database.raw_pool().await;
let ws = create_workspace(&registry, "ws_catalog_revision").await;
let foreign = create_workspace(&registry, "ws_catalog_foreign").await;
let mut local_op = operation(
"op_catalog_local",
"local_tool",
"2026-10-03T10:00:00Z",
"2026-10-03T10:00:00Z",
);
registry
.create_operation(&ws, &local_op, None)
.await
.unwrap();
let baseline = registry.import_catalog_revision(&ws).await.unwrap();
sqlx::query("update operations set updated_at = $1 where workspace_id = $2 and id = $3")
.bind(parse_ts("2026-10-03T11:00:00Z"))
.bind(ws.as_str())
.bind(local_op.id.as_str())
.execute(&raw)
.await
.unwrap();
assert_eq!(
registry.import_catalog_revision(&ws).await.unwrap(),
baseline,
"runtime timestamps are excluded"
);
let foreign_op = operation(
"op_catalog_foreign",
"foreign_tool",
"2026-10-03T10:00:00Z",
"2026-10-03T10:00:00Z",
);
registry
.create_operation(&foreign, &foreign_op, None)
.await
.unwrap();
assert_eq!(
registry.import_catalog_revision(&ws).await.unwrap(),
baseline,
"foreign scope is excluded"
);
sqlx::query(
"update operations set name = 'renamed_local_tool' where workspace_id = $1 and id = $2",
)
.bind(ws.as_str())
.bind(local_op.id.as_str())
.execute(&raw)
.await
.unwrap();
let renamed = registry.import_catalog_revision(&ws).await.unwrap();
assert_ne!(renamed, baseline, "catalog names affect the revision");
sqlx::query(
"update operations set current_draft_version = 2 where workspace_id = $1 and id = $2",
)
.bind(ws.as_str())
.bind(local_op.id.as_str())
.execute(&raw)
.await
.unwrap();
let versioned = registry.import_catalog_revision(&ws).await.unwrap();
assert_ne!(
versioned, renamed,
"catalog version pointers affect the revision"
);
sqlx::query("update operations set status = 'published' where workspace_id = $1 and id = $2")
.bind(ws.as_str())
.bind(local_op.id.as_str())
.execute(&raw)
.await
.unwrap();
let status_changed = registry.import_catalog_revision(&ws).await.unwrap();
assert_ne!(
status_changed, versioned,
"catalog lifecycle affects the revision"
);
// Avoid accidental use of stale local fixture state if this case grows.
local_op.name = "renamed_local_tool".to_owned();
database.cleanup().await;
}
#[tokio::test]
async fn revalidation_and_apply_reject_catalog_drift_without_plan_mutation() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let raw = database.raw_pool().await;
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, "ws_v2_drift").await;
let job = create_pending_openapi_job(
&registry,
&ws,
"job_v2_drift",
now,
now + Duration::hours(1),
)
.await;
activate_source(&raw, &ws, now).await;
let fp = fingerprint();
let revision = registry.import_catalog_revision(&ws).await.unwrap();
let plan_id_text = "plan_v2_drift";
let payload = v2_payload(
plan_id_text,
job.as_str(),
SOURCE_ID,
operation(
"op_v2_planned",
"planned_tool",
"2026-10-03T10:00:00Z",
"2026-10-03T10:00:00Z",
),
&revision,
);
let (plan, digest) = store_plan(&registry, &ws, &job, plan_id_text, &payload, now).await;
registry
.revalidate_import_plan(&ws, &plan, &fp)
.await
.unwrap();
let catalog_change = operation(
"op_v2_catalog_change",
"catalog_change_tool",
"2026-10-03T10:00:00Z",
"2026-10-03T10:00:00Z",
);
registry
.create_operation(&ws, &catalog_change, None)
.await
.unwrap();
assert!(
matches!(
registry.revalidate_import_plan(&ws, &plan, &fp).await,
Err(RegistryError::ImportPlanFingerprintStale { .. })
),
"read-only revalidation must flag catalog drift"
);
let request = ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_v2_drift",
verified_fingerprint: &fp,
applied_at: &now,
};
assert!(
matches!(
registry.apply_import_plan(&request).await,
Err(RegistryError::ImportPlanFingerprintStale { .. })
),
"fresh Apply must independently reject the stale catalog revision"
);
assert!(
registry
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_planned"))
.await
.unwrap()
.is_none(),
"catalog drift must fail before creating the planned operation"
);
assert_eq!(
registry
.get_import_plan_application(&ws, "idem_v2_drift")
.await
.unwrap(),
None,
"a stale apply must not persist application evidence"
);
database.cleanup().await;
}
#[tokio::test]
async fn v2_apply_creates_operation_and_reports_the_confirmed_candidate() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let raw = database.raw_pool().await;
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, "ws_v2_apply").await;
let job = create_pending_openapi_job(
&registry,
&ws,
"job_v2_apply",
now,
now + Duration::hours(1),
)
.await;
activate_source(&raw, &ws, now).await;
let fp = fingerprint();
let revision = registry.import_catalog_revision(&ws).await.unwrap();
let payload = v2_payload(
"plan_v2_apply",
job.as_str(),
SOURCE_ID,
operation(
"op_v2_apply",
"v2_apply_tool",
"2026-10-03T10:00:00Z",
"2026-10-03T10:00:00Z",
),
&revision,
);
let (plan, digest) = store_plan(&registry, &ws, &job, "plan_v2_apply", &payload, now).await;
let request = ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_v2_apply",
verified_fingerprint: &fp,
applied_at: &now,
};
let result = registry.apply_import_plan(&request).await.unwrap();
assert!(!result.replayed);
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
assert_eq!(result.report.counts.created, 1);
assert_eq!(result.report.outcomes[0].key, "candidate");
assert_eq!(
result.report.outcomes[0].outcome,
ImportPlanCandidateOutcome::Created
);
assert_eq!(
result.report.outcomes[0].operation_id.as_deref(),
Some("op_v2_apply")
);
assert_eq!(
registry
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_apply"))
.await
.unwrap()
.unwrap()
.current_draft_version,
1
);
database.cleanup().await;
}
#[tokio::test]
async fn partial_v2_apply_preserves_the_reason_for_an_excluded_candidate() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let raw = database.raw_pool().await;
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, "ws_v2_excluded_reason").await;
let job = create_pending_openapi_job(
&registry,
&ws,
"job_v2_excluded_reason",
now,
now + Duration::hours(1),
)
.await;
activate_source(&raw, &ws, now).await;
let fp = fingerprint();
let revision = registry.import_catalog_revision(&ws).await.unwrap();
let mut payload = v2_payload(
"plan_v2_excluded_reason",
job.as_str(),
SOURCE_ID,
operation(
"op_v2_excluded_reason",
"selected_tool",
"2026-10-03T10:00:00Z",
"2026-10-03T10:00:00Z",
),
&revision,
);
payload["selection"] = json!({
"mode": "partial", "all": ["candidate", "unsupported"],
"selected": ["candidate"], "excluded": ["unsupported"]
});
payload["counts"] = json!({"selected": 1, "excluded": 1, "actionable": 1, "blocked": 0});
payload["excluded_reasons"] = json!([{"key": "unsupported", "reason": "unsupported_schema"}]);
payload["findings"]["candidates"] = json!([
{"key": "candidate", "findings": []},
{"key": "unsupported", "findings": [{"code": "unsupported_schema"}]}
]);
let (plan, digest) = store_plan(
&registry,
&ws,
&job,
"plan_v2_excluded_reason",
&payload,
now,
)
.await;
let request = ApplyImportPlanRequest {
workspace_id: &ws,
plan_id: &plan,
plan_digest: &digest,
idempotency_key: "idem_v2_excluded_reason",
verified_fingerprint: &fp,
applied_at: &now,
};
let result = registry.apply_import_plan(&request).await.unwrap();
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
assert_eq!(result.report.counts.excluded, 1);
let excluded = result
.report
.outcomes
.iter()
.find(|item| item.key == "unsupported")
.unwrap();
assert_eq!(excluded.outcome, ImportPlanCandidateOutcome::Excluded);
assert_eq!(excluded.reason.as_deref(), Some("unsupported_schema"));
assert!(
registry
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_excluded_reason"))
.await
.unwrap()
.is_some()
);
database.cleanup().await;
}
#[tokio::test]
async fn plan_store_accepts_the_full_two_thousand_candidate_limit() {
let database = TestDatabase::new().await;
let registry = database.registry().await;
let raw = database.raw_pool().await;
let now = OffsetDateTime::now_utc();
let ws = create_workspace(&registry, "ws_v2_limit").await;
let job = create_pending_openapi_job(
&registry,
&ws,
"job_v2_limit",
now,
now + Duration::hours(1),
)
.await;
activate_source(&raw, &ws, now).await;
let revision = registry.import_catalog_revision(&ws).await.unwrap();
let mut keys = Vec::with_capacity(2_000);
let mut candidates = Vec::with_capacity(2_000);
let mut candidate_findings = Vec::with_capacity(2_000);
for index in 0..2_000 {
let key = format!("candidate-{index:04}");
let name = format!("candidate_{index:04}_tool");
let operation = operation(
&format!("op_limit_{index:04}"),
&name,
"2026-10-03T10:00:00Z",
"2026-10-03T10:00:00Z",
);
keys.push(key.clone());
candidates.push(json!({
"key": key, "name": name, "state": "actionable", "decision": {"action": "create"},
"findings": [], "operation": operation
}));
candidate_findings.push(json!({"key": key, "findings": []}));
}
let payload = json!({
"schema_version": "import-plan-v2", "plan_reference": "plan_v2_limit", "job_id": job.as_str(),
"fingerprint": fingerprint(), "catalog_revision": revision, "support_matrix_version": "1.0.2",
"source": {"source_id": SOURCE_ID, "digest": SOURCE_DIGEST}, "dependencies": [],
"excluded_reasons": [],
"findings": {"document": [], "candidates": candidate_findings},
"selection": {"mode": "full", "all": keys, "selected": keys, "excluded": []},
"counts": {"selected": 2_000, "excluded": 0, "actionable": 2_000, "blocked": 0},
"candidates": candidates
});
let encoded = serde_json::to_vec(&payload).unwrap();
assert!(
encoded.len() < 16 * 1024 * 1024,
"fixture itself must remain under the payload cap"
);
let (plan_id, _) = store_plan(&registry, &ws, &job, "plan_v2_limit", &payload, now).await;
let stored = registry
.get_import_plan(&ws, &plan_id)
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["candidates"].as_array().unwrap().len(),
2_000
);
assert_eq!(
stored.payload["selection"]["selected"]
.as_array()
.unwrap()
.len(),
2_000
);
registry
.revalidate_import_plan(&ws, &plan_id, &fingerprint())
.await
.expect("the maximum valid candidate set must pass registry material validation");
database.cleanup().await;
}