[skip ci] wip: preserve Hermes crank development checkpoint

Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
Hermes DevOps committed 2026-10-25 10:00:22 +00:00
1 parent 1b6db09bd1
commit 75fe5a123c
357 files changed
+118831 -5113

No files matched your search

@@ -0,0 +1,724 @@
//! ATDD (RED) Story 3.7 — архив Resource: оставшийся серверный lifecycle-контракт AC05/AC06.
//!
//! Источники: live Gitea #14 (`STORY37-SOURCE.md`, AC05/AC06), `docs/acceptance-test-plan.md:1035-1037`
//! (AT-3.7-05/06), QA `.tmp/t_e42cf4cd/QA-REPORT.md` (archive — NOT_RUN) и TL-решение этой карточки:
//! минимальный workspace-scoped `POST .../resources/{resource_id}/archive` с существующим
//! Resource-CAS `expected_updated_at` (JSON body, как publish), без hard-delete, artifact
//! cleanup и изменения Published bytes/Agent snapshots.
//!
//! Состояние на этой стадии: маршрута архива нет (`apps/admin-api/src/app.rs`,
//! `routes/resources.rs`), поэтому позитивные проверки падают на реальном HTTP-ответе
//! fallback-роутера (404 там, где контракт требует 200/428), а не на ошибке компиляции
//! или setup. Отрицательные проверки дополнены положительным контролем владельца, чтобы
//! отказ не мог оказаться «зелёным» из-за отсутствующего маршрута.
//!
//! Семантика доступности archived Published Version: принятое interface decision
//! «Resource published metadata snapshot неизменяем при последующем edit/archive»
//! проверяется чтением точной версии по существующим routes — архив не удаляет и не
//! подменяет immutable snapshot. Решение о том, скрывать ли архивную версию от чтения,
//! относится к checkpoint/build и здесь не изобретается: тест фиксирует неизменность
//! metadata/bytes, а не новый latest-alias.
//!
//! Фильтр запуска: `cargo test -p admin-api --test integration --locked story37_at06_archive -- --test-threads=1`.
use crank_registry::PostgresRegistry;
use reqwest::StatusCode;
use serde_json::{Value, json};
use serial_test::serial;
use super::helpers::{
DEFAULT_WORKSPACE_ID, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD, create_owned_workspace, draft_form,
draft_metadata, draft_updated_at, ensure_viewer_membership, error_signature, get_card,
login_client, login_client_with_foreign_origin, login_client_without_csrf, read_response,
spawn_authorized, table_row_count,
};
use super::publication::{create_and_publish, create_fixture};
/// Тело архива: тот же CAS, что у PUT/publish — точное `updated_at` карточки.
fn archive_body(expected_updated_at: &str) -> Value {
json!({ "expected_updated_at": expected_updated_at })
}
async fn archive_raw(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
body: &Value,
) -> (StatusCode, String, Value) {
let server = server.as_ref();
read_response(
client
.post(format!("{server}/resources/{resource_id}/archive"))
.json(body)
.send()
.await
.expect("archive request must complete"),
)
.await
}
async fn archive(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
expected_updated_at: &str,
) -> (StatusCode, String, Value) {
archive_raw(
client,
server,
resource_id,
&archive_body(expected_updated_at),
)
.await
}
async fn read_version_bytes(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
version: u32,
) -> (StatusCode, Vec<u8>) {
let server = server.as_ref();
let response = client
.get(format!(
"{server}/resources/{resource_id}/versions/{version}/content"
))
.send()
.await
.expect("version content request must complete");
let status = response.status();
let bytes = response
.bytes()
.await
.expect("version content body")
.to_vec();
(status, bytes)
}
async fn publication_rows(registry: &PostgresRegistry) -> i64 {
table_row_count(registry.pool(), "resource_publications").await
}
// ---------------------------------------------------------------------------
// Позитивный lifecycle: published → archived с точным CAS
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_archive_requires_exact_precondition_and_keeps_published_snapshot() {
let (registry, server, client) = spawn_authorized("story37_at06_archive_contract").await;
let bytes = b"story37 archive body".to_vec();
let published = create_and_publish(
&client,
&server,
&draft_metadata(
"crank://story37/archive",
"archive_doc",
"text",
"text/plain",
"internal",
),
&bytes,
"story37-archive.txt",
"text/plain",
)
.await;
let resource_id = published.draft.resource_id.clone();
let before_card = get_card(&client, &server, &resource_id).await;
assert_eq!(
before_card["resource"]["status"],
json!("published"),
"the fixture premise is a published Resource: card={before_card}"
);
let published_version = published.published_version.clone();
let (content_status, published_bytes) =
read_version_bytes(&client, &server, &resource_id, 1).await;
assert_eq!(
content_status,
StatusCode::OK,
"published bytes must be readable"
);
assert_eq!(
published_bytes, bytes,
"the published bytes are the fixture's exact bytes"
);
let rows_before = publication_rows(&registry).await;
let card_cas = draft_updated_at(&before_card);
// POST archive с точным precondition карточки.
let (status, text, body) = archive(&client, &server, &resource_id, &card_cas).await;
assert_eq!(
status,
StatusCode::OK,
"POST .../resources/{{id}}/archive must archive a published Resource (AT-3.7-05/06); \
observed {} body={text}",
error_signature(status, &body)
);
let archived_card = get_card(&client, &server, &resource_id).await;
assert_eq!(
archived_card["resource"]["status"],
json!("archived"),
"the archive action must persist the archived lifecycle: card={archived_card}"
);
assert_ne!(
draft_updated_at(&archived_card),
card_cas,
"an accepted archive must advance the Resource revision so the old CAS is stale"
);
// Immutable history: точная Published Version не изменилась и не удалена.
let version_after = super::publication::read_version(&client, &server, &resource_id, 1).await;
assert_eq!(
version_after.0,
StatusCode::OK,
"archived history must stay readable"
);
assert_eq!(
version_after.2, published_version,
"archive must not modify Published metadata"
);
let (status_after, bytes_after) = read_version_bytes(&client, &server, &resource_id, 1).await;
assert_eq!(status_after, StatusCode::OK);
assert_eq!(
bytes_after, bytes,
"archive must not modify or delete Published bytes"
);
assert_eq!(
publication_rows(&registry).await,
rows_before,
"archive must not create or delete publication rows"
);
// Повтор архива с прежним CAS — stale, без side effects.
let (status, text, body) = archive(&client, &server, &resource_id, &card_cas).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"a repeated archive with the previous CAS must be 428; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_stale"));
assert_eq!(
body["error"]["context"]["recovery"],
json!("reload"),
"the stale archive must keep the accepted reload recovery: body={body}"
);
let unchanged = get_card(&client, &server, &resource_id).await;
assert_eq!(
unchanged, archived_card,
"a stale archive must not change the Resource card"
);
assert_eq!(
publication_rows(&registry).await,
rows_before,
"a stale archive must not create publication rows"
);
}
// ---------------------------------------------------------------------------
// Guards: archive использует ту же session/CSRF/origin/role-защиту, что publish
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_archive_guards_mirror_publish_authorization() {
let (registry, server, client) = spawn_authorized("story37_at06_archive_guards").await;
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/archive-guard",
"archive_guard",
"text",
"text/plain",
"internal",
),
b"archive guard body",
"story37-archive-guard.txt",
"text/plain",
)
.await;
let resource_id = fixture.resource_id.clone();
let cas = fixture.updated_at.clone();
let rows_before = publication_rows(&registry).await;
// (a) без сессии.
let anonymous = reqwest::Client::new();
let (status, text, _) = archive(&anonymous, &server, &resource_id, &cas).await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"an archive without a session must be refused: {text}"
);
// (b) сессия без CSRF.
let without_csrf =
login_client_without_csrf(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (status, text, _) = archive(&without_csrf, &server, &resource_id, &cas).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"an archive without the CSRF token must be refused: {text}"
);
// (c) cross-origin.
let foreign_origin =
login_client_with_foreign_origin(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (status, text, _) = archive(&foreign_origin, &server, &resource_id, &cas).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a cross-origin archive must be refused: {text}"
);
// (d) Viewer не мутирует lifecycle.
let (viewer_email, viewer_password) = ensure_viewer_membership(&registry).await;
let viewer = login_client(&server, viewer_email, viewer_password).await;
let (status, text, body) = archive(&viewer, &server, &resource_id, &cas).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a Viewer must not archive a Resource: observed {} body={text}",
error_signature(status, &body)
);
// Ни один негатив не изменил карточку и не создал публикаций.
let unchanged = get_card(&client, &server, &resource_id).await;
assert_eq!(
unchanged, fixture.card,
"refused archives must not change the Resource card"
);
assert_eq!(publication_rows(&registry).await, rows_before);
// Положительный контроль: владелец архивирует тот же Resource.
let (status, text, body) = archive(&client, &server, &resource_id, &cas).await;
assert_eq!(
status,
StatusCode::OK,
"the owner must be able to archive after the refusals; observed {} body={text}",
error_signature(status, &body)
);
let archived = get_card(&client, &server, &resource_id).await;
assert_eq!(archived["resource"]["status"], json!("archived"));
}
// ---------------------------------------------------------------------------
// Негативы precondition/not-found не раскрывают чужие данные
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_archive_missing_precondition_and_unknown_resource_are_sanitized() {
let (registry, _server, client) = spawn_authorized("story37_at06_archive_negatives").await;
// spawn_authorized возвращает сервер; используем его явно, чтобы префиксы путей совпали.
let server = _server;
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/archive-negative",
"archive_negative",
"text",
"text/plain",
"internal",
),
b"archive negative body",
"story37-archive-negative.txt",
"text/plain",
)
.await;
let rows_before = publication_rows(&registry).await;
// Отсутствие precondition — тот же 428 resource_stale/reload, что у publish/PUT.
let (status, text, body) =
archive_raw(&client, &server, &fixture.resource_id, &json!({})).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"archive without a precondition must be 428; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_stale"));
assert_eq!(body["error"]["context"]["recovery"], json!("reload"));
assert_eq!(
get_card(&client, &server, &fixture.resource_id).await,
fixture.card,
"a precondition-less archive must not change the Resource card"
);
// Неизвестный Resource: sanitized 404, без bytes/чужой metadata.
let (status, text, body) = archive(
&client,
&server,
"res_story37_archive_unknown",
&fixture.updated_at,
)
.await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"an unknown Resource archive must be 404; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
body["error"]["code"],
json!("resource_not_found"),
"the 404 must be the accepted sanitized Resource taxonomy: body={body}"
);
assert_eq!(publication_rows(&registry).await, rows_before);
}
// ---------------------------------------------------------------------------
// Чужой workspace: archive не находит Resource и не мутирует его lifecycle
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_archive_in_foreign_workspace_is_not_found_without_mutation() {
let (registry, server, _client) = spawn_authorized("story37_at06_archive_foreign").await;
let published = create_and_publish(
&_client,
&server,
&draft_metadata(
"crank://story37/archive-foreign",
"archive_foreign",
"text",
"text/plain",
"internal",
),
b"archive foreign body",
"story37-archive-foreign.txt",
"text/plain",
)
.await;
let resource_id = published.draft.resource_id.clone();
let card = get_card(&_client, &server, &resource_id).await;
let cas = draft_updated_at(&card);
let rows_before = publication_rows(&registry).await;
// WorkspaceB доступен тому же аккаунту (Owner), но Resource принадлежит WorkspaceA:
// archive обязан дать sanitized 404 и не тронуть lifecycle/published history.
let owned_workspace = create_owned_workspace(&registry).await;
let workspace_b = server
.as_ref()
.replace(DEFAULT_WORKSPACE_ID, owned_workspace.as_str());
assert_ne!(
workspace_b,
server.as_ref(),
"the foreign workspace base must really differ from the owning workspace"
);
let client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (status, text, body) = archive(&client, &workspace_b, &resource_id, &cas).await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"archiving another workspace's Resource must be 404; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_not_found"));
assert!(
!text.contains("archive_foreign") && !text.contains("crank://story37/archive-foreign"),
"the refusal must not disclose foreign Resource metadata: {text}"
);
// Никакой мутации: карточка и публикация в исходном workspace те же.
assert_eq!(
get_card(&_client, &server, &resource_id).await,
card,
"a foreign-workspace archive must not change the Resource card"
);
assert_eq!(
publication_rows(&registry).await,
rows_before,
"a foreign-workspace archive must not create or delete publications"
);
let version = super::publication::read_version(&_client, &server, &resource_id, 1).await;
assert_eq!(
version.2, published.published_version,
"the exact Published metadata must stay unchanged"
);
}
// ---------------------------------------------------------------------------
// Lifecycle-отказ: актуальный CAS на archived Resource — 409, не 500
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_archived_resource_rejects_publish_update_and_repeat_archive() {
let (registry, server, client) = spawn_authorized("story37_at06_archive_lifecycle").await;
let published = create_and_publish(
&client,
&server,
&draft_metadata(
"crank://story37/archive-lifecycle",
"archive_lifecycle",
"text",
"text/plain",
"internal",
),
b"archive lifecycle body",
"story37-archive-lifecycle.txt",
"text/plain",
)
.await;
let resource_id = published.draft.resource_id.clone();
let before_archive = get_card(&client, &server, &resource_id).await;
let (status, text, body) = archive(
&client,
&server,
&resource_id,
&draft_updated_at(&before_archive),
)
.await;
assert_eq!(
status,
StatusCode::OK,
"positive control: a published Resource must be archivable; observed {} body={text}",
error_signature(status, &body)
);
let archived = get_card(&client, &server, &resource_id).await;
assert_eq!(archived["resource"]["status"], json!("archived"));
let archived_cas = draft_updated_at(&archived);
let publication_rows_before = publication_rows(&registry).await;
let version_rows_before = table_row_count(registry.pool(), "resource_versions").await;
// Повтор архива с АКТУАЛЬНЫМ CAS — существующий lifecycle-код 409, без mutation.
let (status, text, body) = archive(&client, &server, &resource_id, &archived_cas).await;
assert_eq!(
status,
StatusCode::CONFLICT,
"a repeated archive with the current CAS must be a sanitized lifecycle refusal; \
observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_lifecycle_invalid"));
assert_eq!(
get_card(&client, &server, &resource_id).await,
archived,
"a refused repeated archive must not change the archived card"
);
// Публикация архивного Resource с АКТУАЛЬНЫМ CAS — тот же lifecycle-код, не 500.
let (status, text, body) =
super::publication::publish(&client, &server, &resource_id, &archived_cas).await;
assert_eq!(
status,
StatusCode::CONFLICT,
"publishing an archived Resource must be a sanitized lifecycle refusal; \
observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_lifecycle_invalid"));
assert!(
!body.to_string().contains("internal server error"),
"a lifecycle refusal must not be reported as an internal error: {body}"
);
// PUT архивного Resource с АКТУАЛЬНЫМ CAS — тот же lifecycle-код, без новой версии.
let (status, text, body) = read_response(
client
.put(format!("{server}/resources/{resource_id}"))
.multipart(draft_form(
&json!({
"description": "archived update attempt",
"mime_type": "text/plain",
"sensitivity": "internal",
"expected_updated_at": archived_cas,
}),
b"archived update attempt body",
"story37-archive-lifecycle-v2.txt",
"text/plain",
))
.send()
.await
.expect("archived update request must complete"),
)
.await;
assert_eq!(
status,
StatusCode::CONFLICT,
"updating an archived Resource must be a sanitized lifecycle refusal; \
observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_lifecycle_invalid"));
// Ни один отказ не изменил карточку, версии, публикации и точную Published Version.
assert_eq!(
get_card(&client, &server, &resource_id).await,
archived,
"lifecycle refusals must not change the archived card"
);
assert_eq!(
publication_rows(&registry).await,
publication_rows_before,
"lifecycle refusals must not create or delete publications"
);
assert_eq!(
table_row_count(registry.pool(), "resource_versions").await,
version_rows_before,
"a refused archived update must not create a Draft version"
);
let version_after = super::publication::read_version(&client, &server, &resource_id, 1).await;
assert_eq!(
version_after.2, published.published_version,
"archive and refused lifecycle actions must not modify the Published metadata"
);
}
// ---------------------------------------------------------------------------
// Архив не меняет существующий immutable Agent snapshot
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_archive_keeps_existing_agent_catalog_snapshot() {
let (_registry, server, client) = spawn_authorized("story37_at06_archive_agent").await;
let published = create_and_publish(
&client,
&server,
&draft_metadata(
"crank://story37/archive-agent",
"archive_agent",
"text",
"text/plain",
"internal",
),
b"archive agent body",
"story37-archive-agent.txt",
"text/plain",
)
.await;
let resource_id = published.draft.resource_id.clone();
let created = read_response(
client
.post(format!("{server}/agents"))
.json(&json!({
"slug": "story37_archive_agent",
"display_name": "Story 3.7 archive Agent",
"description": "Agent snapshot must survive Resource archive",
"instructions": {},
"tool_selection_policy": {},
}))
.send()
.await
.expect("agent create request must complete"),
)
.await;
assert!(
created.0.is_success(),
"positive control: the Agent fixture must be created; observed {}",
error_signature(created.0, &created.2)
);
let agent_id = created.2["agent_id"]
.as_str()
.expect("created Agent must expose agent_id")
.to_owned();
let etag = super::super::common::agent_etag(&client, &server, &agent_id).await;
let bound = read_response(
client
.post(format!("{server}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!({
"bindings": [],
"tool_selection_policy": {},
"resource_bindings": [{ "resource_id": resource_id, "resource_version": 1 }],
}))
.send()
.await
.expect("agent bindings request must complete"),
)
.await;
assert_eq!(
bound.0,
StatusCode::OK,
"positive control: the exact Published Resource Version must bind; observed {} body={}",
error_signature(bound.0, &bound.2),
bound.1
);
let etag = super::super::common::agent_etag(&client, &server, &agent_id).await;
let agent_published = read_response(
client
.post(format!("{server}/agents/{agent_id}/publish"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!({ "version": 1 }))
.send()
.await
.expect("agent publish request must complete"),
)
.await;
assert_eq!(
agent_published.0,
StatusCode::OK,
"positive control: a Resource-only Agent must publish; observed {} body={}",
error_signature(agent_published.0, &agent_published.2),
agent_published.1
);
let summary_before = get_card(&client, &server, &resource_id).await;
let agent_before = read_response(
client
.get(format!("{server}/agents/{agent_id}"))
.send()
.await
.expect("agent summary request must complete"),
)
.await;
let catalog_before = agent_before.2["catalog_revision"].clone();
let agent_version_before = read_response(
client
.get(format!("{server}/agents/{agent_id}/versions/1"))
.send()
.await
.expect("agent version request must complete"),
)
.await;
assert_eq!(agent_version_before.0, StatusCode::OK);
let (status, text, body) = archive(
&client,
&server,
&resource_id,
&draft_updated_at(&summary_before),
)
.await;
assert_eq!(
status,
StatusCode::OK,
"the published Resource must archive; observed {} body={text}",
error_signature(status, &body)
);
let agent_after = read_response(
client
.get(format!("{server}/agents/{agent_id}"))
.send()
.await
.expect("agent summary request must complete"),
)
.await;
assert_eq!(
agent_after.2["catalog_revision"], catalog_before,
"archiving a Resource must not bump the Agent catalog_revision"
);
let agent_version_after = read_response(
client
.get(format!("{server}/agents/{agent_id}/versions/1"))
.send()
.await
.expect("agent version request must complete"),
)
.await;
assert_eq!(
agent_version_after.2, agent_version_before.2,
"archiving a Resource must not modify the existing immutable Agent snapshot"
);
}