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,404 @@
//! P2-остаток (TL review run101 R-E / run103 R-E) вынесен в отдельный private
//! test-модуль: health-правило ограничивает файл 1000 строками, а helper-ы/типы и
//! лон-векторы F4 используют те же фикстуры, что и родительский модуль.
//!
//! Перенесены только helper-ы/типы (`case_draft`, `ExpectedCode`, `CLIENT_CODES`,
//! `record_case`) и тест F4, который их использует; test ID, assertions, данные и
//! контроли не менялись. Производственный код, FILE_LIMITS и checker не затронуты
//! (R4, TL run113).
use super::super::helpers::{
assert_draft_identity, create_draft, created_resource_id, draft_metadata, draft_updated_at,
get_card, post_draft_raw, spawn_authorized, table_row_count,
};
use super::super::{DraftState, observe_draft_state, put_draft_raw, update_metadata};
use reqwest::StatusCode;
use serde_json::{Value, json};
use serial_test::serial;
/// Свежий durable Draft для одного независимого случая отказа (F1).
///
/// Возвращает собственные `updated_at` (валидную текущую precondition) и полное «до»
/// именно этого черновика. Причина: принятый дефект (`"uri": null` применяется как обычное
/// обновление) меняет и состояние, и precondition черновика, поэтому общий случай сделал бы
/// последующие наблюдения двухфакторными (`null` + `stale`) и сравнил бы их с чужим
/// предыдущим PUT (TL run105 F1).
pub(super) async fn case_draft(
registry: &crank_registry::PostgresRegistry,
client: &reqwest::Client,
server: impl AsRef<str>,
namespace: &str,
suffix: &str,
) -> (String, String, DraftState) {
let server = server.as_ref();
let uri = format!("crank://immutable/{namespace}/{suffix}");
let name = format!("immutable_{namespace}_{suffix}");
let meta = draft_metadata(&uri, &name, "text", "text/plain", "internal");
let created = create_draft(
client,
server,
&meta,
b"first body",
"draft.txt",
"text/plain",
)
.await;
let id = created_resource_id(&created);
let updated_at = draft_updated_at(&get_card(client, server, &id).await);
let before = observe_draft_state(registry, client, server, &id).await;
assert_draft_identity(&before.card, &uri, &name, "text");
assert_eq!(
before.card["version"]["version"],
json!(1),
"every case must start from its own accepted Draft version 1: {suffix}"
);
assert_eq!(before.bytes, b"first body".to_vec());
// Итоги строк намеренно не сравниваются с абсолютными числами: в одном workspace
// теперь несколько черновиков, поэтому проверяется их неизменность после отказа
// (через равенство полного состояния), а не «ровно одна строка».
assert!(
before.versions >= 1 && before.owning_refs >= 1,
"the fresh draft must be durable (versions={}, owning_refs={})",
before.versions,
before.owning_refs
);
(id, updated_at, before)
}
/// Ожидание по коду отказа: либо точный стабильный код D-14, либо «любой клиентский
/// код из D-14, кроме перечисленных» — для отказов, у которых D-14 не выделяет
/// отдельного Resource-кода, но требует именно клиентского отказа, а не 500.
#[derive(Clone, Copy, Debug)]
pub(super) enum ExpectedCode {
Exact(&'static str),
ClientRejectionExcept(&'static [&'static str]),
}
/// Полный список клиентских кодов D-14 (любой отказ обязан быть одним из них).
pub(super) const CLIENT_CODES: &[&str] = &[
"resource_content_empty",
"resource_content_too_large",
"resource_content_invalid_utf8",
"resource_content_invalid_json",
"resource_mime_syntax_invalid",
"resource_mime_not_allowed",
"resource_uri_invalid",
"resource_name_invalid",
"resource_description_invalid",
"resource_kind_mismatch",
"resource_uri_duplicate",
"resource_name_duplicate",
"resource_field_immutable",
"validation_error",
];
/// Записывает наблюдение одного отказа в общий отчёт и перечисляет расхождения.
///
/// Проверяются вместе: статус, стабильный код (и точное `error.context.field`, когда оно
/// определено) и неизменность **полного** состояния черновика — карточки, точных bytes и
/// итогов строк/owning-ссылок.
#[allow(clippy::too_many_arguments)]
pub(super) fn record_case(
observations: &mut Vec<String>,
mismatches: &mut Vec<String>,
label: &str,
status: StatusCode,
body: &Value,
state_unchanged: bool,
expected_status: StatusCode,
expected_code: ExpectedCode,
expected_field: Option<&str>,
) {
let code = body["error"]["code"]
.as_str()
.unwrap_or("<absent>")
.to_owned();
let field = body["error"]["context"]["field"]
.as_str()
.unwrap_or("<absent>")
.to_owned();
let code_ok = match expected_code {
ExpectedCode::Exact(expected) => code == expected,
ExpectedCode::ClientRejectionExcept(forbidden) => {
CLIENT_CODES.contains(&code.as_str()) && !forbidden.contains(&code.as_str())
}
};
let field_ok = expected_field.is_none_or(|expected| field == expected);
let ok = status == expected_status && code_ok && field_ok && state_unchanged;
observations.push(format!(
"{label}: status={status} code={code} field={field} state_unchanged={state_unchanged}"
));
if !ok {
mismatches.push(format!(
"{label}: expected status={expected_status} code={expected_code:?} field={expected_field:?} \
state_unchanged=true; observed status={status} code={code} field={field} \
state_unchanged={state_unchanged}"
));
}
}
/// R3/F4: у одиночного generic-отказа (`UnknownMetadataValue`, шаг E) не должно быть
/// Resource-специфичного контекста. `expected_field = None` в `record_case` означает
/// «поле не проверяется», поэтому отсутствие `error.context` наблюдается явно, без
/// ослабления прежних проверок кода и поля у Resource-специфичных отказов.
pub(super) fn assert_lone_generic_context(mismatches: &mut Vec<String>, label: &str, body: &Value) {
let context = body["error"].get("context");
if context.is_some_and(|value| !value.is_null()) {
mismatches.push(format!(
"{label}: a lone generic refusal must not carry a Resource-specific \
`error.context`, observed {context:?}"
));
}
}
// ---------------------------------------------------------------------------
// F4 (TL run109 CODE-REVIEW): неизвестная `sensitivity` решается на **своём**
// шаге E, а не раньше C/D. Порядок D-20: C (разрешение Resource) → D
// (неизменяемость) → E (`uri → name → description → kind → mime_type →
// sensitivity`). Наблюдаемое требование: клиент видит первый нарушенный шаг,
// поэтому «invalid uri + unknown sensitivity» обязан дать `resource_uri_invalid`,
// а «нет Resource + unknown sensitivity» — `resource_not_found`, а не generic 400.
// Одиночная неизвестная `sensitivity` остаётся generic клиентским 400 (не 500).
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
pub(super) async fn story36_at02_unknown_sensitivity_is_decided_at_its_own_d20_step() {
let (registry, server, client) = spawn_authorized("story36_sensitivity_step").await;
let mut observations: Vec<String> = Vec::new();
let mut mismatches: Vec<String> = Vec::new();
// E: побеждает первое нарушение, поэтому у каждого вектора нарушен ровно один
// более ранний шаг, а `sensitivity` неизвестна во всех.
let mut long_description = draft_metadata(
"crank://order/description",
"order_description",
"text",
"text/plain",
"top_secret",
);
long_description["description"] = json!("d".repeat(1025));
let invalid_name = "n".repeat(65);
let create_vectors = [
(
"create-uri-before-sensitivity",
draft_metadata("crank://a", "order_uri", "text", "text/plain", "top_secret"),
"resource_uri_invalid",
"uri",
),
(
"create-name-before-sensitivity",
draft_metadata(
"crank://order/name",
&invalid_name,
"text",
"text/plain",
"top_secret",
),
"resource_name_invalid",
"name",
),
(
"create-description-before-sensitivity",
long_description,
"resource_description_invalid",
"description",
),
(
"create-mime-before-sensitivity",
draft_metadata(
"crank://order/mime",
"order_mime",
"text",
"text",
"top_secret",
),
"resource_mime_syntax_invalid",
"mime_type",
),
];
let rows_before = table_row_count(registry.pool(), "resources").await;
for (label, metadata, code, field) in create_vectors {
let (status, _, _text, body) =
post_draft_raw(&client, &server, &metadata, b"payload", "text/plain").await;
// «Состояние не изменилось» наблюдается как итог принятых строк: отказ create
// не должен оставить Resource (ни одна строка таблицы).
let rows_after = table_row_count(registry.pool(), "resources").await;
record_case(
&mut observations,
&mut mismatches,
label,
status,
&body,
rows_after == rows_before,
StatusCode::BAD_REQUEST,
ExpectedCode::Exact(code),
Some(field),
);
}
// Одиночная неизвестная `sensitivity` при валидных остальных полях: generic
// клиентский 400 без Resource-кода и без внутренней ошибки хранилища (D-20 E).
let lone = draft_metadata(
"crank://order/lone",
"order_lone",
"text",
"text/plain",
"top_secret",
);
let (status, _, _text, body) =
post_draft_raw(&client, &server, &lone, b"payload", "text/plain").await;
let rows_after_lone = table_row_count(registry.pool(), "resources").await;
// Точный код `validation_error` одновременно исключает и Resource-специфичный код,
// и внутреннюю ошибку хранилища (`resource_storage_unavailable`).
record_case(
&mut observations,
&mut mismatches,
"create-lone-unknown-sensitivity",
status,
&body,
rows_after_lone == rows_before,
StatusCode::BAD_REQUEST,
ExpectedCode::Exact("validation_error"),
None,
);
// R3/F4: «не проверять поле» заменяется явным наблюдением отсутствия
// Resource-специфичного контекста у одиночного generic-отказа.
assert_lone_generic_context(&mut mismatches, "create-lone-unknown-sensitivity", &body);
// Неизвестный `kind` остаётся шагом B (форма запроса) и по-прежнему побеждает E.
let unknown_kind = draft_metadata(
"crank://order/kind",
"order_kind",
"video",
"text/plain",
"top_secret",
);
let (status, _, _text, body) =
post_draft_raw(&client, &server, &unknown_kind, b"payload", "text/plain").await;
let rows_after_kind = table_row_count(registry.pool(), "resources").await;
record_case(
&mut observations,
&mut mismatches,
"create-unknown-kind-stays-step-b",
status,
&body,
rows_after_kind == rows_before,
StatusCode::BAD_REQUEST,
ExpectedCode::Exact("validation_error"),
None,
);
// C до E: неизвестная `sensitivity` не должна опережать разрешение Resource.
let missing_meta = update_metadata("", "text/plain", "top_secret", "2026-01-01T00:00:00Z");
let (status, _text, body) = put_draft_raw(
&client,
&server,
"res_missing_story36_order",
&missing_meta,
b"payload",
"text/plain",
)
.await;
let rows_after_missing = table_row_count(registry.pool(), "resources").await;
record_case(
&mut observations,
&mut mismatches,
"update-missing-resource-before-sensitivity",
status,
&body,
rows_after_missing == rows_before,
StatusCode::NOT_FOUND,
ExpectedCode::Exact("resource_not_found"),
Some("resource_id"),
);
// Обновление **существующего** Draft с одиночной неизвестной sensitivity:
// generic клиентский 400 (не 500) и полное состояние без изменений.
let meta = draft_metadata(
"crank://order/existing",
"order_existing",
"text",
"text/plain",
"internal",
);
let created = create_draft(
&client,
&server,
&meta,
b"first body",
"draft.txt",
"text/plain",
)
.await;
let id = created_resource_id(&created);
let updated_at = draft_updated_at(&get_card(&client, &server, &id).await);
let before = observe_draft_state(&registry, &client, &server, &id).await;
assert_draft_identity(
&before.card,
"crank://order/existing",
"order_existing",
"text",
);
let (status, _text, body) = put_draft_raw(
&client,
&server,
&id,
&update_metadata("", "text/plain", "top_secret", &updated_at),
b"second body",
"text/plain",
)
.await;
let after = observe_draft_state(&registry, &client, &server, &id).await;
// Точный код `validation_error` одновременно исключает Resource-специфичный код и
// внутреннюю ошибку хранилища (не 500) для одиночной неизвестной sensitivity.
record_case(
&mut observations,
&mut mismatches,
"update-existing-lone-unknown-sensitivity",
status,
&body,
after == before,
StatusCode::BAD_REQUEST,
ExpectedCode::Exact("validation_error"),
None,
);
// R3/F4: тот же явный контроль отсутствия Resource-специфичного контекста на update.
assert_lone_generic_context(
&mut mismatches,
"update-existing-lone-unknown-sensitivity",
&body,
);
// D до E: присутствие immutable-ключа побеждает неизвестную sensitivity.
let mut immutable_meta = update_metadata("", "text/plain", "top_secret", &updated_at);
immutable_meta["uri"] = json!("crank://order/renamed");
let (status, _text, body) = put_draft_raw(
&client,
&server,
&id,
&immutable_meta,
b"second body",
"text/plain",
)
.await;
let after_immutable = observe_draft_state(&registry, &client, &server, &id).await;
record_case(
&mut observations,
&mut mismatches,
"update-immutable-presence-before-sensitivity",
status,
&body,
after_immutable == before,
StatusCode::BAD_REQUEST,
ExpectedCode::Exact("resource_field_immutable"),
Some("uri"),
);
assert!(
mismatches.is_empty(),
"the unknown sensitivity must be decided at its own D-20 step and each refusal must \
leave the observed state unchanged; observations: {observations:?}; mismatches: {mismatches:?}"
);
}