Files
faunosteo/.claude/tasks/plans/r5-6-switch.patch
T
bchanot 943a25a98f fix(domain): R5.6 prep gates, strict declared block, patch builds, docs corrected
v1 refuses a non-hex or historical value (NotCanonical); the switch patch now builds
report-compare and refuses unknown block keys; RUST.md 11.19 states the measured
rehearsal (4 + 3 expected failures) instead of a green claim.
2026-10-24 14:57:44 +02:00

359 lines
15 KiB
Diff

diff --git a/.prettierignore b/.prettierignore
index a9140e4..aaeef54 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -7,3 +7,6 @@ packages/core-wasm/types/
packages/core-wasm/pkg/
packages/core-wasm/pkg-proofs/
packages/core-wasm/tests/n-1/
+# Written by the Rust pipeline (`pnpm r5:import-equine`, R5.6): byte-exact, never reformatted.
+supabase/seed/anatomical-sheets/equine/legacy-import/
+supabase/seed/anatomical-sheets/equine/draft/
diff --git a/crates/core/src/bin/report_compare.rs b/crates/core/src/bin/report_compare.rs
index 59cf060..91b34ef 100644
--- a/crates/core/src/bin/report_compare.rs
+++ b/crates/core/src/bin/report_compare.rs
@@ -37,6 +37,8 @@ struct SeedRef {
document_sha256: String,
schema_version: f64,
species_id: String,
+ #[serde(default)]
+ fingerprint: Option<faunosteo_core::domain::sheet::loaded::DeclaredFingerprint>,
}
fn seed_json<T: for<'de> Deserialize<'de>>(name: &str) -> Result<T, String> {
@@ -58,6 +60,7 @@ fn load_sheet() -> Result<LoadedSheet, String> {
document_sha256: reference.document_sha256,
schema_version,
species_id: reference.species_id,
+ fingerprint: reference.fingerprint,
},
document: seed_json("document.json")?,
migration_map: seed_json("report-migration-map.json")?,
diff --git a/crates/core/src/curation/draft/pipeline.rs b/crates/core/src/curation/draft/pipeline.rs
index 19126aa..12bcaf5 100644
--- a/crates/core/src/curation/draft/pipeline.rs
+++ b/crates/core/src/curation/draft/pipeline.rs
@@ -8,6 +8,9 @@
//! asset id) and copies them, and never re-cleans the legacy drawing. The review drawings and
//! the two Markdown reports are R5.4.
+use crate::domain::sheet::fingerprint::{
+ FINGERPRINT_CONVENTION, TRUSTED_ALIASES, sheet_fingerprint,
+};
use serde_json::{Map, Value, json};
use crate::json::to_js_compact;
@@ -165,14 +168,25 @@ pub fn build_equine_draft(input: &DraftInput<'_>) -> Result<DraftResult, Pipelin
})
}
-/// What a report references: the sheet and the exact document bytes (the historical rule,
-/// kept until the R5.6 switch).
-fn sheet_ref(draft: &DraftResult, document_json: &str) -> SheetRef {
- SheetRef {
+/// What a report references: the sheet and its `sha256-rfc8785-validated-v1` fingerprint
+/// (R5.6; the pre-switch rule hashed the formatted bytes, kept as a registered alias).
+fn sheet_ref(draft: &DraftResult, document_json: &str) -> Result<SheetRef, PipelineError> {
+ let fingerprint = sheet_fingerprint(document_json)
+ .map_err(|error| fail(format!("document fingerprint: {error:?}")))?;
+ Ok(SheetRef {
sheet_id: draft.sheet_id.clone(),
version_id: None,
- document_sha256: sha256_hex(document_json.as_bytes()),
- }
+ document_sha256: fingerprint,
+ })
+}
+
+/// The registered aliases of this sheet's canonical value (descriptive in `sheet-ref.json`).
+fn registered_aliases(reference: &SheetRef) -> Vec<&'static str> {
+ TRUSTED_ALIASES
+ .iter()
+ .filter(|e| e.sheet_id == reference.sheet_id && e.canonical == reference.document_sha256)
+ .map(|e| e.alias)
+ .collect()
}
/// The migration map (`report-migration-map.json` value) and its stats.
@@ -307,7 +321,7 @@ pub fn render_draft_artifacts(
legacy_anomalies: &[Anomaly],
) -> Result<Vec<(String, String)>, PipelineError> {
let document_json = format_json(&draft.document)?;
- let reference = sheet_ref(draft, &document_json);
+ let reference = sheet_ref(draft, &document_json)?;
let (map, migration_stats) = draft_migration_map(draft, &reference)?;
let assets = serde_json::to_value(&draft.assets)
.map_err(|error| fail(format!("assets.json: {error}")))?;
@@ -317,6 +331,10 @@ pub fn render_draft_artifacts(
"document_sha256": reference.document_sha256,
"schema_version": draft.document.get("schema_version"),
"species_id": draft.document.get("species_id"),
+ "fingerprint": {
+ "convention": FINGERPRINT_CONVENTION,
+ "aliases": registered_aliases(&reference),
+ },
});
let changelog = render_changelog(
&draft.records,
diff --git a/crates/core/src/domain/archive/read.rs b/crates/core/src/domain/archive/read.rs
index 5419b9d..677fe52 100644
--- a/crates/core/src/domain/archive/read.rs
+++ b/crates/core/src/domain/archive/read.rs
@@ -4,6 +4,7 @@
//! wrapper is then validated whole or dropped with a reason. Accepted shapes: a bare Report v2
//! or v3, or an archive envelope of version 1.
+use crate::domain::sheet::fingerprint::equivalence;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[cfg(feature = "ts")]
@@ -115,7 +116,12 @@ fn read_envelope_v1(
fn snapshot_matches(snapshot: &SheetSnapshot, report: &Report) -> bool {
snapshot.reference.sheet_id == report.sheet.sheet_id
- && snapshot.reference.document_sha256 == report.sheet.document_sha256
+ && equivalence(
+ &report.sheet.sheet_id,
+ &snapshot.reference.document_sha256,
+ &report.sheet.document_sha256,
+ )
+ .same_document()
}
/// `ReportArchiveEnvelopeSchema.parse`: the shape of a whole envelope (the snapshot's shape
diff --git a/crates/core/src/domain/report/rebase.rs b/crates/core/src/domain/report/rebase.rs
index 9281642..b5012be 100644
--- a/crates/core/src/domain/report/rebase.rs
+++ b/crates/core/src/domain/report/rebase.rs
@@ -5,6 +5,7 @@
//! snapshot when the report carries none, and the report now references the loaded sheet.
//! Nothing happens when the report already sits on the loaded sheet.
+use crate::domain::sheet::fingerprint::equivalence;
use serde::Serialize;
#[cfg(feature = "ts")]
use ts_rs::TS;
@@ -37,7 +38,13 @@ pub fn rebase_report_on_sheet(
sheet: &LoadedSheet,
archived: Option<&SheetSnapshot>,
) -> Result<RebaseOutcome, ReadFailure> {
- if report.sheet.document_sha256 == sheet.reference.document_sha256 {
+ // Same document: equal fingerprints, or the registry's pair for this very sheet (R5.6).
+ let same_sheet = report.sheet.sheet_id == sheet.reference.sheet_id;
+ let stamped = &report.sheet.document_sha256;
+ let current = &sheet.reference.document_sha256;
+ if stamped == current
+ || (same_sheet && equivalence(&sheet.reference.sheet_id, stamped, current).same_document())
+ {
return Ok(RebaseOutcome {
report: report.clone(),
unresolved_zones: 0,
diff --git a/crates/core/src/domain/sheet/loaded.rs b/crates/core/src/domain/sheet/loaded.rs
index 4065978..e6fd44d 100644
--- a/crates/core/src/domain/sheet/loaded.rs
+++ b/crates/core/src/domain/sheet/loaded.rs
@@ -2,6 +2,7 @@
//! read once from the bundled payload, then indexed. Its document and migration map pass the
//! strict schemas; the provenance fields come from the build and are taken as they are.
+use super::fingerprint::{AliasRefusal, check_declared};
use std::collections::HashMap;
use serde::Deserialize;
@@ -33,6 +34,16 @@ pub struct BundledRef {
pub document_sha256: String,
pub schema_version: JsInt,
pub species_id: String,
+ /// Descriptive (R5.6): checked against the core's registry at load, never trusted alone.
+ #[serde(default)]
+ pub fingerprint: Option<DeclaredFingerprint>,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct DeclaredFingerprint {
+ pub convention: String,
+ pub aliases: Vec<String>,
}
/// A loaded, indexed sheet.
@@ -76,6 +87,8 @@ pub enum LoadError {
Shape(serde_json::Error),
/// The document has no main view.
NoMainView,
+ /// The declared fingerprint block contradicts the core's registry (R5.6).
+ Fingerprint(AliasRefusal),
}
impl From<serde_json::Error> for LoadError {
@@ -102,6 +115,15 @@ impl LoadedSheet {
.map(|(id, text)| (id.clone(), read_drawing(text)))
.collect();
let r = data.reference;
+ if let Some(declared) = &r.fingerprint {
+ check_declared(
+ &r.sheet_id,
+ &r.document_sha256,
+ &declared.convention,
+ &declared.aliases,
+ )
+ .map_err(LoadError::Fingerprint)?;
+ }
Ok(Self {
status: data.status,
reference: SheetRef {
diff --git a/crates/core/src/facade.rs b/crates/core/src/facade.rs
index f0c6997..7f73cff 100644
--- a/crates/core/src/facade.rs
+++ b/crates/core/src/facade.rs
@@ -53,6 +53,7 @@ pub fn load_sheet(bundle: &str) -> Result<LoadedSheet, Failure> {
LoadedSheet::from_bundle(data).map_err(|error| match error {
LoadError::Shape(error) => Failure::new("invalid_sheet", error),
LoadError::NoMainView => Failure::new("invalid_sheet", "the sheet has no main view"),
+ LoadError::Fingerprint(refusal) => Failure::new("invalid_sheet", format!("{refusal:?}")),
})
}
diff --git a/crates/core/src/pdf/compare/lines.rs b/crates/core/src/pdf/compare/lines.rs
index 35e8dd2..4dfc313 100644
--- a/crates/core/src/pdf/compare/lines.rs
+++ b/crates/core/src/pdf/compare/lines.rs
@@ -2,6 +2,7 @@
//! current label next to the archived one, `!! UNRESOLVED` with the reason where the sheet
//! cannot place an item. Every untrusted string goes through [`esc`].
+use crate::domain::sheet::fingerprint::{Equivalence, equivalence};
use serde::Deserialize;
use serde_json::Value;
@@ -346,8 +347,23 @@ fn archive_line(outcome: &ArchiveReadOutcome) -> Vec<String> {
fn sheet_line(report: &Report, sheet: &LoadedSheet) -> String {
let reference = &sheet.reference;
- let same_sheet = report.sheet.sheet_id == reference.sheet_id
- && report.sheet.document_sha256 == reference.document_sha256;
+ let same = equivalence(
+ &reference.sheet_id,
+ &report.sheet.document_sha256,
+ &reference.document_sha256,
+ );
+ let same_sheet = report.sheet.sheet_id == reference.sheet_id && same.same_document();
+ if same_sheet && same == Equivalence::TrustedAlias {
+ // Same content under the registered historical fingerprint: both raw values shown.
+ let stamped: String = report.sheet.document_sha256.chars().take(12).collect();
+ let current: String = reference.document_sha256.chars().take(12).collect();
+ return format!(
+ "sheet {} (matches the bundled sheet through the trusted alias: report sha {}…, sheet sha {}…)",
+ esc(&reference.sheet_id),
+ esc(&stamped),
+ esc(&current)
+ );
+ }
if same_sheet {
let status = match sheet.status {
SheetStatus::Draft => "draft",
diff --git a/crates/core/src/pdf/write/input.rs b/crates/core/src/pdf/write/input.rs
index 120249a..6a4bfe5 100644
--- a/crates/core/src/pdf/write/input.rs
+++ b/crates/core/src/pdf/write/input.rs
@@ -2,6 +2,7 @@
//! branding and the labels through their schemas again, the snapshot gate with every asset
//! accepted by the SVG reader, the report's sheet and the page caps. Today's error kinds.
+use crate::domain::sheet::fingerprint::equivalence;
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
@@ -203,9 +204,12 @@ fn reason_of(rejection: SnapshotRejection) -> String {
/// Steps 2 and 3: the report belongs to this sheet and fits the page budget.
fn assert_exportable(report: &Report, snapshot: &SheetSnapshot) -> Result<(), ExportError> {
let reference = &snapshot.reference;
- if report.sheet.sheet_id != reference.sheet_id
- || report.sheet.document_sha256 != reference.document_sha256
- {
+ let same = equivalence(
+ &reference.sheet_id,
+ &report.sheet.document_sha256,
+ &reference.document_sha256,
+ );
+ if report.sheet.sheet_id != reference.sheet_id || !same.same_document() {
return Err(error(ExportErrorKind::SheetMismatch, ""));
}
if report.observations.len() > MAX_OBSERVATIONS {
diff --git a/crates/core/tests/fingerprint_consumers.rs b/crates/core/tests/fingerprint_consumers.rs
new file mode 100644
index 0000000..39a5775
--- /dev/null
+++ b/crates/core/tests/fingerprint_consumers.rs
@@ -0,0 +1,69 @@
+//! R5.6 switch rehearsal (part of `.claude/tasks/plans/r5-6-switch.patch`, not committed
+//! active): with the loaded sheet stamped with the canonical `v1` value, a report or an archive
+//! stamped with the registered historical value is the same document (no rebase, archive kept);
+//! a real content change, a forged value or another sheet still differ.
+#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
+
+mod archive_support;
+mod common;
+
+use archive_support::{draft_map, draft_sheet, json_file};
+use faunosteo_core::domain::archive::read_archive_document;
+use faunosteo_core::domain::report::{Report, rebase_report_on_sheet};
+use faunosteo_core::domain::sheet::LoadedSheet;
+use serde_json::Value;
+
+const ALIAS: &str = "27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660";
+const CANONICAL: &str = "12d788727c1e532641bd5b3a7ecf39dbdd25e70350f8a76be5ca917b262874e2";
+
+fn switched_sheet() -> LoadedSheet {
+ let mut sheet = draft_sheet();
+ assert_eq!(sheet.reference.document_sha256, ALIAS);
+ sheet.reference.document_sha256 = CANONICAL.to_owned();
+ sheet
+}
+
+fn demo(sha: &str) -> Report {
+ let mut value = json_file("apps/app/tests/fixtures/report-v3.demo.json");
+ value["sheet"]["documentSha256"] = Value::from(sha);
+ serde_json::from_value(value).unwrap()
+}
+
+#[test]
+fn a_report_on_the_historical_value_is_not_rebased_and_keeps_its_stamp() {
+ let outcome = rebase_report_on_sheet(&demo(ALIAS), &switched_sheet(), None).unwrap();
+ assert!(!outcome.rebased);
+ assert_eq!(outcome.report.sheet.document_sha256, ALIAS);
+}
+
+#[test]
+fn a_real_change_or_a_forged_value_still_rebases() {
+ for sha in ["a".repeat(64), "b".repeat(64)] {
+ let outcome = rebase_report_on_sheet(&demo(&sha), &switched_sheet(), None).unwrap();
+ assert!(outcome.rebased, "{sha}");
+ }
+}
+
+#[test]
+fn an_archive_pairing_the_alias_and_the_canonical_value_is_kept_and_a_forged_pair_is_not() {
+ let base = json_file("apps/app/tests/fixtures/goldens/r2/envelope.demo.fr.nologos.json");
+ let map = draft_map();
+ let mut paired = base.clone();
+ paired["sheetSnapshot"]["ref"]["documentSha256"] = Value::from(CANONICAL);
+ assert!(
+ read_archive_document(&paired, &map)
+ .unwrap()
+ .archive
+ .is_some()
+ );
+ let mut forged = base.clone();
+ forged["sheetSnapshot"]["ref"]["documentSha256"] = Value::from("c".repeat(64));
+ let read = read_archive_document(&forged, &map).unwrap();
+ assert!(read.archive.is_none() && read.snapshot_rejected.is_some());
+ assert!(
+ read_archive_document(&base, &map)
+ .unwrap()
+ .archive
+ .is_some()
+ );
+}