Files
bsodfather 54ce770682
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
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
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.
2026-10-25 09:08:22 +00:00

359 lines
12 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! ATDD (RED) для Story 3.16 — composition of Prompts with Published Resources (FR-18).
//!
//! Источники: `_bmad-output/initiative-crank/epic-mcp-capabilities/spec-prompt-composition/contract.md`
//! (§1–§8 — wire shape, resolution, effective policy, render, findings, immutability),
//! `epics.md`:2920–2986 (AC группы 1–10), `docs/acceptance-test-plan.md` AT-3.16-01…10,
//! `test-design-epic-3.md` строки 3.16 / 3.16-INT-A,B / E3-R2,R3.
//!
//! Состояние на момент написания: `PromptDefinition` не знает `dependencies`, а preview не
//! разрешает Resource. Поэтому каждый RED ниже — поведенческое расхождение на реальном HTTP
//! (400 `prompt_invalid_definition` там, где контракт требует 201/200/409/400 с точным кодом),
//! а не ошибка компиляции или setup. Позитивные контроли (создание/publish/preview обычного
//! Prompt и публикация Resource) исполняются в том же файле и доказывают работоспособность
//! харнесса.
//!
//! Фильтр запуска:
//! `cargo test -p admin-api --test integration prompt_composition -- --test-threads=1`.
use super::common::{
TestServer, authorized_client, build_test_app, spawn_admin_api, test_auth_settings,
test_registry, test_storage_root,
};
use crank_core::{MembershipRole, Workspace, WorkspaceId, WorkspaceStatus};
use crank_registry::{CreateWorkspaceRequest, PostgresRegistry};
use reqwest::StatusCode;
use reqwest::multipart::{Form, Part};
use serde_json::{Value, json};
use serial_test::serial;
use std::sync::atomic::{AtomicU32, Ordering};
use time::OffsetDateTime;
const DEFAULT_WORKSPACE_ID: &str = "ws_default";
const TEST_AUTH_EMAIL: &str = "owner@crank.local";
const TEST_AUTH_PASSWORD: &str = "test-password";
static SEQ: AtomicU32 = AtomicU32::new(0);
struct Stand {
/// Держит сервер живым на всё время теста: Drop останавливает его.
_server: TestServer,
client: reqwest::Client,
base: String,
}
/// Свежий Admin API на собственном PostgreSQL-схеме и с авторизованной сессией владельца.
async fn stand(prefix: &str) -> Stand {
let registry = test_registry().await;
let server = spawn_admin_api(build_test_app(registry, test_storage_root(prefix))).await;
let client = authorized_client(&server).await;
let base = server.as_ref().to_owned();
Stand {
_server: server,
client,
base,
}
}
fn unique(prefix: &str) -> String {
let n = SEQ.fetch_add(1, Ordering::Relaxed);
format!("{prefix}_{n}")
}
// ---------------------------------------------------------------------------
// Fixtures: published Resources через production multipart/publish path
// ---------------------------------------------------------------------------
struct ResourceFixture {
id: String,
version: u32,
digest: String,
}
async fn create_and_publish_resource(
stand: &Stand,
base: &str,
kind: &str,
mime: &str,
sensitivity: &str,
content: &[u8],
) -> ResourceFixture {
let name = unique("story316");
let uri = format!("crank://resources/{name}");
let metadata = json!({
"uri": uri,
"name": name,
"description": "",
"kind": kind,
"mime_type": mime,
"sensitivity": sensitivity,
});
let form = Form::new()
.part(
"metadata",
Part::bytes(serde_json::to_vec(&metadata).expect("metadata json"))
.file_name("metadata.json".to_owned())
.mime_str("application/json")
.expect("metadata mime"),
)
.part(
"content",
Part::bytes(content.to_vec())
.file_name("content.bin".to_owned())
.mime_str(mime)
.expect("content mime"),
);
let response = stand
.client
.post(format!("{base}/resources"))
.multipart(form)
.send()
.await
.expect("resource create request");
let status = response.status();
let body: Value = response.json().await.unwrap_or(Value::Null);
assert_eq!(
status,
StatusCode::CREATED,
"resource Draft creation is the existing 3.6 path: {body}"
);
let id = body["resource"]["resource_id"]
.as_str()
.expect("resource card carries the id")
.to_owned();
let updated_at = body["resource"]["updated_at"]
.as_str()
.expect("resource card carries updated_at")
.to_owned();
let published = stand
.client
.post(format!("{base}/resources/{id}/publish"))
.json(&json!({ "expected_updated_at": updated_at }))
.send()
.await
.expect("resource publish request");
let status = published.status();
let body: Value = published.json().await.unwrap_or(Value::Null);
assert_eq!(status, StatusCode::OK, "resource publish: {body}");
ResourceFixture {
id,
version: body["published_version"]["version"]
.as_u64()
.expect("published_version.version") as u32,
digest: body["published_version"]["digest"]
.as_str()
.expect("published_version.digest")
.to_owned(),
}
}
/// Новая Draft-версия того же Resource (immutable fields не передаются) + её публикация.
async fn publish_next_resource_version(
stand: &Stand,
base: &str,
resource_id: &str,
kind_mime_sensitivity: (&str, &str),
content: &[u8],
) -> ResourceFixture {
let (mime, sensitivity) = kind_mime_sensitivity;
// PUT требует precondition по текущей карточке Resource (Story 3.6 CAS).
let current: Value = stand
.client
.get(format!("{base}/resources/{resource_id}"))
.send()
.await
.expect("resource card request")
.json()
.await
.unwrap_or(Value::Null);
let expected_updated_at = current["resource"]["updated_at"]
.as_str()
.expect("current resource card carries updated_at")
.to_owned();
let metadata = json!({
"description": "",
"mime_type": mime,
"sensitivity": sensitivity,
"expected_updated_at": expected_updated_at,
});
let form = Form::new()
.part(
"metadata",
Part::bytes(serde_json::to_vec(&metadata).expect("metadata json"))
.file_name("metadata.json".to_owned())
.mime_str("application/json")
.expect("metadata mime"),
)
.part(
"content",
Part::bytes(content.to_vec())
.file_name("content.bin".to_owned())
.mime_str(mime)
.expect("content mime"),
);
let response = stand
.client
.put(format!("{base}/resources/{resource_id}"))
.multipart(form)
.send()
.await
.expect("resource update request");
let status = response.status();
let body: Value = response.json().await.unwrap_or(Value::Null);
assert_eq!(status, StatusCode::OK, "resource new Draft version: {body}");
let updated_at = body["resource"]["updated_at"]
.as_str()
.expect("updated card carries updated_at")
.to_owned();
let published = stand
.client
.post(format!("{base}/resources/{resource_id}/publish"))
.json(&json!({ "expected_updated_at": updated_at }))
.send()
.await
.expect("resource publish request");
let status = published.status();
let body: Value = published.json().await.unwrap_or(Value::Null);
assert_eq!(status, StatusCode::OK, "resource publish v2: {body}");
ResourceFixture {
id: resource_id.to_owned(),
version: body["published_version"]["version"]
.as_u64()
.expect("published_version.version") as u32,
digest: body["published_version"]["digest"]
.as_str()
.expect("published_version.digest")
.to_owned(),
}
}
fn dependency(resource: &ResourceFixture) -> Value {
json!([{ "resource_id": resource.id, "version": resource.version }])
}
/// Определение с одной pinned-зависимостью и точкой вставки в user-сообщении.
fn composed_prompt(name: &str, sensitivity: &str, dependencies: Value) -> Value {
json!({
"name": name,
"description": "composed prompt",
"sensitivity": sensitivity,
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
"messages": [
{"role": "system", "content": "Summarise only the attached document."},
{"role": "user", "content": "Channel: {{channel}}", "resource_refs": [0]}
],
"dependencies": dependencies
})
}
// ---------------------------------------------------------------------------
// HTTP helpers
// ---------------------------------------------------------------------------
async fn create_prompt(stand: &Stand, base: &str, body: &Value) -> (StatusCode, Value) {
let response = stand
.client
.post(format!("{base}/prompts"))
.json(body)
.send()
.await
.expect("create prompt request");
let status = response.status();
(status, response.json().await.unwrap_or(Value::Null))
}
async fn publish_prompt(
stand: &Stand,
base: &str,
prompt_id: &str,
extra: Option<Value>,
) -> (StatusCode, Value) {
let mut body = json!({ "action": "publish" });
if let Some(expected) = extra {
body["expected_updated_at"] = expected;
}
let response = stand
.client
.post(format!("{base}/prompts/{prompt_id}"))
.json(&body)
.send()
.await
.expect("publish prompt request");
let status = response.status();
(status, response.json().await.unwrap_or(Value::Null))
}
async fn preview_prompt(
stand: &Stand,
base: &str,
prompt_id: &str,
arguments: Value,
) -> (StatusCode, Value) {
let response = stand
.client
.post(format!("{base}/prompts/{prompt_id}/preview"))
.json(&json!({ "arguments": arguments }))
.send()
.await
.expect("preview prompt request");
let status = response.status();
(status, response.json().await.unwrap_or(Value::Null))
}
async fn workspace_with_membership(registry: &PostgresRegistry, suffix: &str) -> WorkspaceId {
let now = OffsetDateTime::now_utc();
let workspace_id = WorkspaceId::new(format!("ws_story316_{suffix}"));
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: format!("story316-{suffix}"),
display_name: format!("Story 3.16 {suffix}"),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.expect("synthetic workspace creates");
let password_hash =
admin_api::auth::hash_password(TEST_AUTH_PASSWORD, &test_auth_settings().password_pepper)
.expect("owner password hash");
let owner_id = registry
.upsert_bootstrap_user(TEST_AUTH_EMAIL, "Test Owner", &password_hash)
.await
.expect("owner account");
registry
.ensure_membership(&workspace_id, &owner_id, MembershipRole::Owner)
.await
.expect("owner membership");
workspace_id
}
fn error_code(body: &Value) -> String {
body["error"]["code"]
.as_str()
.unwrap_or("<absent>")
.to_owned()
}
fn error_context(body: &Value) -> &Value {
&body["error"]["context"]
}
fn message_text(body: &Value, index: usize) -> String {
body["messages"][index]["content"]
.as_str()
.unwrap_or("<absent>")
.to_owned()
}
// Группы оракулов разнесены по файлам, чтобы каждый из них оставался в пределах
// rust-code-health; харнесс и фикстуры живут здесь, в `mod.rs`.
mod ac;
mod ac_render;
mod ac_scan;
mod oracles;