[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,361 @@
//! AC03 / AT-3.7-03: immutable Published Resource Version.
//!
//! Публикация создаёт неизменяемую версию; последующее редактирование Draft создаёт новый
//! Draft, но не меняет опубликованные bytes/metadata (TL interface decisions 2–3, risk E3-R3:
//! «concurrent edit/archive/publish ... cannot mutate a published snapshot»). Точное значение
//! версии читается через `GET .../resources/{id}/versions/{version}` и `.../versions/{v}/content`;
//! зависший precondition повторной публикации остаётся 428 `resource_stale`/`recovery=reload`
//! и не создаёт duplicate/partial writes.
use super::super::helpers::{
assert_download_policy, draft_metadata, draft_updated_at, error_signature, get_card,
header_value, read_content, sha256_hex, spawn_authorized, table_row_count,
};
use super::{
assert_immutable_metadata, assert_version_not_published, create_and_publish, publish,
publish_raw, published_metadata, read_version, read_version_content, resource_card_id,
update_draft_expect_success, version_metadata,
};
use crank_registry::PostgresRegistry;
use reqwest::StatusCode;
use serde_json::json;
use serial_test::serial;
/// Итоги существующих реестровых отношений: нужны как наблюдение «duplicate/partial writes
/// не появилось». Схема публикации ещё не выбрана (TL decision 5), поэтому тест не опирается на
/// новые отношения — только на уже принятые.
async fn relation_counts(registry: &PostgresRegistry) -> (i64, i64, i64, i64) {
(
table_row_count(registry.pool(), "resources").await,
table_row_count(registry.pool(), "resource_versions").await,
table_row_count(registry.pool(), "artifact_sources").await,
table_row_count(registry.pool(), "artifact_blobs").await,
)
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at03_publish_creates_immutable_version_readable_exactly() {
let (_registry, server, client) = spawn_authorized("story37_at03_immutable").await;
let bytes = "опубликованное содержимое\nвторая строка\n".as_bytes();
let mut meta = draft_metadata(
"crank://story37/published",
"published_doc",
"text",
"text/plain",
"internal",
);
meta["description"] = json!("опубликованное описание");
let raw_upload_filename = "story37-published-raw.bin";
let published = create_and_publish(
&client,
&server,
&meta,
bytes,
raw_upload_filename,
"text/plain",
)
.await;
let id = published.draft.resource_id.clone();
let snapshot = published.published_version.clone();
// Тело успешного ответа несёт и карточку Resource, и immutable metadata (TL decision 2).
assert_eq!(
resource_card_id(&published.body).as_deref(),
Some(id.as_str()),
"a successful publish must answer the Resource card too: {}",
published.body
);
// Точные поля Published Version: независимый оракул digest считается тестом.
assert_eq!(snapshot["version"], json!(1));
assert_eq!(snapshot["uri"], json!("crank://story37/published"));
assert_eq!(snapshot["name"], json!("published_doc"));
assert_eq!(snapshot["description"], json!("опубликованное описание"));
assert_eq!(snapshot["kind"], json!("text"));
assert_eq!(snapshot["mime_type"], json!("text/plain"));
assert_eq!(snapshot["size_bytes"], json!(bytes.len()));
assert_eq!(snapshot["digest"], json!(sha256_hex(bytes)));
assert_eq!(snapshot["sensitivity"], json!("internal"));
// GET .../versions/{version} возвращает тот же immutable object.
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the exact Published Version metadata must be readable (TL decision 3); observed {} body={text}",
error_signature(status, &body)
);
let observed = version_metadata(&body);
assert_eq!(
observed, snapshot,
"GET versions/1 must return the same immutable metadata object that publish returned"
);
assert_immutable_metadata(&observed, raw_upload_filename);
// GET .../versions/{version}/content отдаёт точные опубликованные bytes и остаётся инертным.
let response = read_version_content(&client, &server, &id, 1).await;
assert_eq!(response.status(), StatusCode::OK);
assert_download_policy(response.headers());
let disposition = header_value(response.headers(), "content-disposition");
assert!(
!disposition.contains(raw_upload_filename),
"the raw upload filename must not reach the published download header: {disposition}"
);
assert_eq!(
response
.bytes()
.await
.expect("published content must be readable")
.to_vec(),
bytes.to_vec(),
"GET versions/1/content must return the exact published bytes"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at03_draft_edit_does_not_change_published_bytes_or_metadata() {
let (_registry, server, client) = spawn_authorized("story37_at03_pinned").await;
let first_bytes = "published body v1\n".as_bytes();
let mut meta = draft_metadata(
"crank://story37/pinned",
"pinned_doc",
"text",
"text/plain",
"internal",
);
meta["description"] = json!("опубликованное описание");
let published = create_and_publish(
&client,
&server,
&meta,
first_bytes,
"story37-pinned-raw.bin",
"text/plain",
)
.await;
let id = published.draft.resource_id.clone();
let snapshot = published.published_version.clone();
let card_before_edit = get_card(&client, &server, &id).await;
let second_bytes = "draft body v2\n".as_bytes();
let updated = update_draft_expect_success(
&client,
&server,
&id,
&json!({
"description": "изменённое описание черновика",
"mime_type": "text/plain",
"sensitivity": "public",
"expected_updated_at": draft_updated_at(&card_before_edit),
}),
second_bytes,
"story37-pinned-raw.bin",
"text/plain",
)
.await;
assert_eq!(
updated["version"]["version"],
json!(2),
"editing after publication must create a new Draft version (AT-3.7-03)"
);
// Черновик изменился по всем наблюдаемым полям.
let card = get_card(&client, &server, &id).await;
assert_eq!(card["version"]["version"], json!(2));
assert_eq!(card["version"]["digest"], json!(sha256_hex(second_bytes)));
assert_eq!(card["version"]["sensitivity"], json!("public"));
assert_eq!(
card["resource"]["description"],
json!("изменённое описание черновика")
);
assert_eq!(
read_content(&client, &server, &id).await,
second_bytes.to_vec(),
"the current Draft content must be the edited bytes"
);
// Опубликованный snapshot не изменился ни в metadata, ни в bytes.
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the published snapshot must stay readable after a Draft edit; observed {} body={text}",
error_signature(status, &body)
);
let observed = version_metadata(&body);
assert_eq!(
observed, snapshot,
"a Draft edit must not change the Published Version metadata (AT-3.7-03)"
);
assert_eq!(
observed["description"],
json!("опубликованное описание"),
"the published description must stay pinned"
);
assert_eq!(
observed["sensitivity"],
json!("internal"),
"the published sensitivity must stay pinned even when the Draft raises it"
);
let response = read_version_content(&client, &server, &id, 1).await;
assert_eq!(response.status(), StatusCode::OK);
assert_download_policy(response.headers());
assert_eq!(
response
.bytes()
.await
.expect("published content must be readable")
.to_vec(),
first_bytes.to_vec(),
"the published bytes must stay pinned after a Draft edit"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at03_stale_and_repeated_publish_never_mutate_published_snapshot() {
let (registry, server, client) = spawn_authorized("story37_at03_stale").await;
let first_bytes = "published v1 bytes\n".as_bytes();
let mut meta = draft_metadata(
"crank://story37/stale",
"stale_doc",
"text",
"text/plain",
"internal",
);
meta["description"] = json!("опубликованное описание v1");
let published = create_and_publish(
&client,
&server,
&meta,
first_bytes,
"story37-stale-v1.txt",
"text/plain",
)
.await;
let id = published.draft.resource_id.clone();
let snapshot = published.published_version.clone();
let counts_after_publish = relation_counts(&registry).await;
// Повтор той же публикации: precondition прежней карточки уже stale (TL decision 2/3).
let (status, text, body) = publish(&client, &server, &id, &published.draft.updated_at).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"repeating the same publish 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"));
// Отсутствующий precondition — тот же 428 без публикации.
let (status, text, body) = publish_raw(&client, &server, &id, &json!({})).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"a publish without precondition must be 428 (TL decision 2); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_stale"));
// Ни duplicate publication, ни partial writes: отношения и снапшот не изменились.
assert_eq!(
relation_counts(&registry).await,
counts_after_publish,
"a stale/repeated publish must not write any row"
);
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the published snapshot must stay readable; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
version_metadata(&body),
snapshot,
"a stale publish must not mutate the published snapshot"
);
// Редактирование Draft: publish с прежним (теперь stale) precondition снова 428.
let card = get_card(&client, &server, &id).await;
let second_bytes = "draft v2 bytes\n".as_bytes();
update_draft_expect_success(
&client,
&server,
&id,
&json!({
"description": "черновик v2",
"mime_type": "text/plain",
"sensitivity": "public",
"expected_updated_at": draft_updated_at(&card),
}),
second_bytes,
"story37-stale-v2.txt",
"text/plain",
)
.await;
let (status, text, body) = publish(&client, &server, &id, &published.draft.updated_at).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"a publish racing a Draft edit must be 428; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_stale"));
assert_version_not_published(&client, &server, &id, 2, "AT-3.7-03 stale publish").await;
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the published snapshot must survive the racing publish; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(version_metadata(&body), snapshot);
// Публикация актуального Draft создаёт новую Published Version, прежняя остаётся точной.
let card = get_card(&client, &server, &id).await;
let (status, text, body) = publish(&client, &server, &id, &draft_updated_at(&card)).await;
assert_eq!(
status,
StatusCode::OK,
"the current Draft must be publishable with a fresh precondition; observed {} body={text}",
error_signature(status, &body)
);
let second_published = published_metadata(&body);
assert_immutable_metadata(&second_published, "story37-stale-v2.txt");
assert_eq!(second_published["version"], json!(2));
assert_eq!(second_published["digest"], json!(sha256_hex(second_bytes)));
assert_eq!(second_published["sensitivity"], json!("public"));
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the earlier Published Version must stay readable; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
version_metadata(&body),
snapshot,
"publishing a newer version must not rewrite the earlier Published Version"
);
let response = read_version_content(&client, &server, &id, 1).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response
.bytes()
.await
.expect("published content must be readable")
.to_vec(),
first_bytes.to_vec(),
"the earlier Published Version bytes must stay exact"
);
}