Skip to main content

delvewright_dsl/
prefab.rs

1//! The prefab metadata document (`<id>.json`, beside the structure `.nbt`) —
2//! the **one** definition of its shape.
3//!
4//! A prefab is a *pair* of files: a gzip-framed structure template and this
5//! sibling JSON that says what the template is, where its anchors and sockets
6//! are, how lit it is, what it claims about the space inside it, and what
7//! regenerates it. Both halves are produced and consumed by several tools of
8//! several ages — the grammar back end and the hand-written generators write the
9//! pair from scratch, `delvec prefab` reads it and writes it back after every
10//! admission step, `delvec` reads it to plan a world, `delvec render` reads it to
11//! aim a camera — so the document's shape is defined once, here, and every one
12//! of them reads that definition instead of a copy of it.
13//!
14//! # Why the definition lives in the DSL crate
15//!
16//! Not because prefab metadata is DSL surface — it is a library-asset document —
17//! but because this is the only crate every reader can depend on. `delvec` is
18//! published to crates.io and may only depend on published crates, and this crate
19//! is the one it already depends on. The alternative was a copy inside `delvec`,
20//! which is what existed and what this module replaces. The crate already owns
21//! the document's `lighting` block ([`crate::registry::Lighting`], whose field
22//! names are this file's field names) and the anchor surface DSL validation
23//! resolves refs against ([`crate::registry::AnchorRegistry`]), so the document's
24//! remaining blocks join a shape that was already half here.
25//!
26//! # Reading is total, writing preserves
27//!
28//! Every field a producer may legitimately omit is `Option`/`default` and is
29//! omitted (never `null`) on write, so a legacy prefab that predates a field
30//! still loads and a piece that has never been probed does not have to invent a
31//! measurement. Field order is the emission order, and it is the order the
32//! library's checked-in prefabs already use, so a reviewer diffing a generated
33//! piece against a hand-built one sees only values change.
34//!
35//! Keys this version has never heard of are **kept**, in [`PrefabMeta::extra`]
36//! and [`Anchor::extra`], and written back out. That is not politeness to the
37//! future; it is the only behaviour that is neither an outage nor silent data
38//! loss. See the `deny_unknown_fields` note below.
39//!
40//! # `deny_unknown_fields`, decided rather than inherited
41//!
42//! The attribute is right on a document whose reader is also its **owner**: a
43//! campaign stage document is authored against a versioned schema, a typo there
44//! is the bug the attribute exists to catch, and forward compatibility is
45//! handled by the `dsl_version` fence instead. Every stage struct in
46//! [`crate::stages`] keeps it for exactly that reason.
47//!
48//! It is wrong on a **consumer that is not the owner**, which is what every
49//! reader of this document is. Here a new key is not a typo — it is a newer
50//! producer meeting an older reader, which happens on every mixed-version pair
51//! of engine and content library. Refusing turns a forward addition into a hard
52//! failure at the layer with the least context; the compiler's private copy of
53//! this shape did exactly that, and the first grammar-exported prefab carrying a
54//! new key would have failed every campaign build.
55//!
56//! Tolerating alone is not the fix either, because a tool that reads this
57//! document, edits one block and writes it back deletes everything it does not
58//! model — and does so while every test it has passes. That is not
59//! hypothetical: `license.generated_by` was dropped that way once, and
60//! `waterline_y` — a field five shipped island prefabs carry and the
61//! ocean-horizon placement check keys off — was being dropped that way at the
62//! time this module was written.
63//!
64//! So the rule is: **this document's structs neither refuse an unknown key nor
65//! discard it.** They keep it, and the reader that wants to say something about
66//! it says it as a diagnostic (`DW0543`) rather than as a parse failure. The
67//! blocks whose own definition lives elsewhere are the exception and say why at
68//! their field.
69
70use std::collections::BTreeMap;
71use std::path::Path;
72
73use schemars::JsonSchema;
74use serde::{Deserialize, Serialize};
75
76use crate::registry::Lighting;
77use crate::split::TileSet;
78
79/// The one `.json` in a prefab library that is **not** a prefab document:
80/// the pool declaration (`{"pools": {...}}`), read by the compiler's registry.
81///
82/// Named once because more than one tool walks the library directory — the
83/// registry, `delvec view`'s page builder, `delvec render batch` — and each of
84/// them opens every `.json` it finds. A walker that does not know this name
85/// hands a pool file to [`PrefabMeta::from_json`] and reports it as a malformed
86/// prefab, which is a true statement about the bytes and a wrong one about the
87/// file.
88pub const POOLS_FILE: &str = "pools.json";
89
90/// What the exported prefab-metadata schema tells its reader the document IS —
91/// stated on the schema rather than only in a reference document, because the
92/// schema is what an author actually opens.
93const SCHEMA_DESCRIPTION: &str = "\
94A prefab's sibling metadata file, `<prefab-id>.json`, beside the structure \
95`.nbt` in a prefab library.
96
97A LIBRARY ASSET, NOT A CAMPAIGN STAGE DOCUMENT. It carries no `dsl_version`, no \
98`campaign_id` and no `stage`; it is not authored against the campaign DSL's \
99staging (ADR-0002) and is therefore absent from `--stage all`.
100
101Three of its declarations are the piece's claims about its own outside, and \
102they are different claims rather than one claim written three ways \
103(spec-0060 §4):
104
105  `walk_y`       the piece's own walk plane, in local y. Owed on every base. \
106It is the number an area's origin is DERIVED from where the horizon's datum is \
107a walk plane, so it has no default: a default would be right for the tileset it \
108was copied from and silently wrong for every other. Missing, a campaign that \
109seats the piece is refused with `DW0886`.
110
111  `waterline_y`  the local y of the piece's TOP AUTHORED WATER BLOCK. Owed only \
112where the piece really writes water that meets a sea. It is a claim about the \
113bytes and is checked against them (`DW0887`), and its placement is checked \
114against sea level (`DW0344`). A piece that authors no water has no waterline to \
115state, and writing one anyway is a fiction the engine refuses.
116
117  `shown_faces`  which of the piece's six sides are finished exterior surface. \
118Absent means NO side is shown, which is the strict answer: a piece authored to \
119be buried writes nothing here, and what discharges its obligation is the world \
120burying it (`DW0885`).
121
122Keys this engine does not model are KEPT and written back out, so a newer \
123producer meeting an older reader is a `DW0543` warning rather than a parse \
124failure. The `lighting` block is the one exception and refuses a key it does \
125not know.
126";
127
128/// A prefab's sibling metadata file.
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
130pub struct PrefabMeta {
131    /// The DSL prefab id, `prefab/<id>`.
132    pub prefab_id: String,
133    /// The structure-template reference, for a piece whose blocks fit one
134    /// template.
135    ///
136    /// Exactly one of this and [`Self::structure_set`] is present — see the
137    /// type's own note on the two packagings, and [`Self::from_json`], which is
138    /// where "exactly one" is enforced.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub structure: Option<StructureMeta>,
141    /// The tile set, for a piece whose blocks did not fit one template.
142    ///
143    /// **Packaging, not authoring.** A zone past the 48-per-axis structure cap
144    /// ships as several `.nbt` files plus this manifest; everything else about
145    /// the document — the id, the zone-local `anchors`, the `connectors`, the
146    /// one `lighting` block, the one provenance row — is what it is for a
147    /// single-template piece, because it describes the same building. Nothing
148    /// that refers to a piece may ask which of the two it is: read
149    /// [`Self::templates`].
150    ///
151    /// This was a second document type (`TileSetMeta`, in the schem crate),
152    /// field-for-field this one with `structure` swapped for `structure_set`.
153    /// The copy had already lost `waterline_y`, so a tiled shore could not
154    /// declare the waterline the ocean-horizon invariant (`DW0344`) keys off and
155    /// went silently unchecked. One document is what makes that class of drift
156    /// unrepresentable.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub structure_set: Option<TileSet>,
159    /// Named anchors, keyed by DSL anchor name. `{}` for a piece that declares
160    /// none.
161    #[serde(default)]
162    pub anchors: BTreeMap<String, Anchor>,
163    /// Jigsaw sockets. `[]` for a piece that is placed directly rather than
164    /// drawn from a pool.
165    #[serde(default)]
166    pub connectors: Vec<Connector>,
167    /// The lighting declaration.
168    ///
169    /// Absent means legacy metadata that predates the field, which is a
170    /// different claim from `{"profile": "unmeasured"}` — the positive statement
171    /// that a measurement is owed.
172    ///
173    /// The block's own shape is [`Lighting`], and it is **the one part of this
174    /// document that still refuses a key it does not know**. Its job is a rule
175    /// about values — a measured profile must carry its measurement, an
176    /// `unmeasured` one must not — so a misspelled measurement key there is a
177    /// claim quietly becoming its own absence, which the profile/measurement
178    /// agreement alone does not catch for `rationale` or `method`. The cost is
179    /// real and is stated where an author will meet it
180    /// (`docs/reference/prefab-procedure.md` §9): a key added inside `lighting`
181    /// is a hard parse failure for an older engine, so adding one is a
182    /// `dsl_version` matter rather than a metadata edit.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub lighting: Option<Lighting>,
185    /// Licence, provenance prose, and the machine-readable provenance row.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub license: Option<License>,
188    /// **The local y of this piece's own walk plane** — the cell a body's feet
189    /// occupy when it stands on the piece's principal floor (spec-0060 §4).
190    ///
191    /// This is the number an area's origin is DERIVED from on a horizon whose
192    /// datum is a walk plane: an `ocean` world's walk plane is `SEA_LEVEL + 1`,
193    /// so an area seating this piece is placed at `walk_ref_y - walk_y` and the
194    /// piece stands one block above the sea, which is the vanilla-normal beach
195    /// relationship. A keep interior declaring `1` is seated at 62 and stands
196    /// dry at 63; an island piece declaring `3` is seated at 60.
197    ///
198    /// **It has no default, and that is the decision** (spec-0060 §4.1). A
199    /// default is the retired global datum wearing a different name: it would
200    /// be right for the one tileset it was copied from and silently wrong for
201    /// every other, and the piece that lands under the sea because of it floods
202    /// on boot with nothing looking. A piece a campaign seats without one is
203    /// `DW0886`.
204    ///
205    /// It is a MEASUREMENT of the piece, so it is written by the generator that
206    /// built the piece and never typed by hand
207    /// (`CLAUDE.md`: a census derivable from the object is never hand-written).
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub walk_y: Option<i32>,
210    /// The local y of this piece's **top authored water block** — its waterline
211    /// — for open-air pieces built to a tileset convention that authors a sea.
212    ///
213    /// Two rules read it, and they ask different questions. `DW0887` asks
214    /// whether the claim is TRUE — whether the piece's own bytes put a water
215    /// block at that plane and none above it — and refuses a declaration that
216    /// is a fiction wherever the document and its `.nbt` are read together.
217    /// `DW0344` asks whether the PLACEMENT honours it: in a `horizon: ocean`
218    /// world the declared waterline must land at world sea level.
219    ///
220    /// Absent for pieces that author no sea, which neither rule then judges. A
221    /// piece that authors water and declares nothing is not refused by
222    /// `DW0887`; under `ocean` its placement is `DW0344`'s subject and under
223    /// `void` its runoff is `DW0318`'s.
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub waterline_y: Option<i32>,
226    /// **The sides of this piece the player is meant to see** — the piece's own
227    /// claim that a given face is finished exterior surface rather than the cut
228    /// edge of something that belongs inside a hill.
229    ///
230    /// Local side names, in the piece's own frame, from the same six-word
231    /// vocabulary [`ContractFace::dir`] uses: `east` `west` `up` `down` `south`
232    /// `north`. They turn with the placement, so a piece rotated a quarter turn
233    /// shows the side it was built to show.
234    ///
235    /// It is the third thing a piece says about its own outside, and the three
236    /// are different claims about the same object rather than one claim written
237    /// three ways: [`Self::waterline_y`] says where the piece meets the sea,
238    /// [`SpatialContract::faces`] says where a body crosses a side, and this
239    /// says which sides are finished. None of the others can stand in for it —
240    /// a cave with a mouth declares one `walk` face and is still a block of rock
241    /// on the other five — which is why `DW0885` reads this and not them.
242    ///
243    /// **Absent means no side is shown**, and that is the load-bearing default:
244    /// a piece authored to be buried is exactly a piece that writes nothing
245    /// here, so the silence has to be the strict answer or the defect declares
246    /// itself by omission. What discharges the obligation for such a piece is
247    /// the world burying it, which is geometry the declaration cannot fake.
248    #[serde(default, skip_serializing_if = "Vec::is_empty")]
249    pub shown_faces: Vec<String>,
250    /// The piece's spatial contract, when it declares one.
251    ///
252    /// Absent means legacy metadata — the piece makes no spatial claim — exactly
253    /// as an absent `lighting` block differs from `unmeasured`.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub spatial_contract: Option<SpatialContract>,
256    /// **The size class of box this piece is built to fill** — a name from the
257    /// metrics table's `size-class.*` ladder (spec-0050 §5).
258    ///
259    /// Optional for the library at large, and that is deliberate rather than
260    /// lax: every piece in the library predates the field, and `DW0848` binds
261    /// only where the claim is made. What is *not* optional is the claim being
262    /// true — a piece declaring a class its own bytes could serve no box of is
263    /// refused at admission and again wherever a detail plan consumes it, so a
264    /// pre-check-era piece cannot be consumed unjudged.
265    ///
266    /// Absent means what absence means everywhere in this document: the claim is
267    /// not made. A piece bound by a `details[]` row is still checked for exact
268    /// frame equality (`DW0843`) whether or not it declares — that is the
269    /// consumer's exact check, and this is the library's approximate one.
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub footprint_class: Option<String>,
272    /// Every top-level key this version does not model, kept verbatim so that
273    /// reading and writing the document is not the same as editing it.
274    ///
275    /// A reader that wants to report one has it in hand; a reader that does not
276    /// care carries it through. Emitted after the modelled keys, in key order.
277    #[serde(flatten)]
278    pub extra: BTreeMap<String, serde_json::Value>,
279}
280
281/// A piece's declared spaces, out-of-walk regions and edges, **already
282/// resolved**: every box is a local cell range of these exact bytes.
283///
284/// Resolved rather than parametric on purpose. A grammar program's declarations
285/// are scope-bound and mean different boxes at different parameters, so the only
286/// contract that can describe *this* `.nbt` is the one its own expansion
287/// produced. That is also what lets a hand-built piece carry the same block: it
288/// has no parameters to resolve, so the two routes write the same shape and one
289/// reader serves both.
290#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
291pub struct SpatialContract {
292    /// The space a body enters at.
293    pub entry: String,
294    /// Named spaces.
295    #[serde(default)]
296    pub spaces: BTreeMap<String, ContractSpace>,
297    /// Named standable-but-out-of-walk regions.
298    #[serde(default)]
299    pub no_body: BTreeMap<String, ContractNoBody>,
300    /// The graph, in declaration order.
301    #[serde(default)]
302    pub edges: Vec<ContractEdge>,
303    /// **The piece's face contract**: every `exterior` edge, as the side of the
304    /// piece it is on and the opening it leaves there.
305    ///
306    /// Derived from the edges and the blocks at export time and written out, so
307    /// that assembly can ask whether two pieces fit without opening either
308    /// `.nbt`. It is the thing an `exterior` edge IS from the outside: an edge
309    /// with no cells is a claim nothing can mate with, and one whose opening
310    /// does not answer its neighbour's is two pieces that were each approved
311    /// alone and do not assemble.
312    #[serde(default, skip_serializing_if = "Vec::is_empty")]
313    pub faces: Vec<ContractFace>,
314    /// The author's acknowledgement that this piece is mostly out-of-walk.
315    #[serde(default, skip_serializing_if = "Option::is_none")]
316    pub no_body_majority_ack: Option<String>,
317}
318
319/// `DW0848`: a piece's declared footprint class disagrees with its bytes.
320pub const DW_FOOTPRINT_CLASS: crate::DwCode = crate::DwCode::new("DW0848", crate::ExitTier::Build);
321
322/// **Judge a piece's declared `footprint_class` against its own structure
323/// size.**
324///
325/// One authority with two doors, on the pattern spec-0036 §1c fixed for the
326/// spatial contract: `delvec prefab audit` asks it at the admission event, where
327/// the library's integrity lives, and `delvec::compiler::detail` asks it
328/// again wherever a `detail-plan` row consumes the piece. Two implementations
329/// that agreed until they did not is the failure this shape removes.
330///
331/// What it asks, and each half is a fact about the geometry rather than a
332/// preference:
333///
334/// 1. **The name is in the table** — otherwise `DW0812`, as for any document
335///    naming a table entry.
336/// 2. **The horizontal extents could be a box of that class.** A detail frame's
337///    footprint IS its box's footprint (`Frame::of` grows the play space
338///    downward only), so a piece whose `x` or `z` falls outside the class's
339///    `min_footprint..=max_footprint` could fill no box of it.
340/// 3. **They sit on the kit grid.** A site-plan box's extent is a multiple of
341///    the grid quantum (`DW0825`), so a piece off the grid could fill no box at
342///    all, of any class.
343/// 4. **The height leaves the class its clearance.** A frame is the play space
344///    plus one floor course, so a piece under `min_clearance + 1` is short of
345///    the shallowest box of its class.
346///
347/// Returns `None` for a piece that declares no class — which is the honest
348/// answer, and why the caller states how many pieces declared one against how
349/// many it examined.
350#[must_use]
351pub fn check_footprint_class(
352    meta: &PrefabMeta,
353    stage: &str,
354    path: &str,
355    reads: &mut crate::metrics::Reads,
356) -> Option<crate::Diagnostic> {
357    let named = meta.footprint_class.as_deref()?;
358    let table = crate::metrics::Metrics::table();
359    let entry = match table.resolve(crate::metrics::MetricKind::SizeClass, named) {
360        Ok(e) => e,
361        Err(unknown) => return Some(unknown.diagnostic(stage, path)),
362    };
363    let crate::metrics::MetricValue::SizeClass(class) = *entry.value(reads) else {
364        return None; // an internal table defect, which `Metrics::self_check` owns.
365    };
366    let size = meta.size();
367    let grid = table.grid(reads);
368    let q = grid.map_or(1, |g| i64::from(g.quantum).max(1));
369    let (sx, sy, sz) = (i64::from(size[0]), i64::from(size[1]), i64::from(size[2]));
370    let (minf, maxf) = (class.min_footprint, class.max_footprint);
371    let mut why: Vec<String> = Vec::new();
372    if sx < i64::from(minf[0]) || sx > i64::from(maxf[0]) {
373        why.push(format!(
374            "its x extent is {sx}, and a `{named}` box is {}..={} on x",
375            minf[0], maxf[0]
376        ));
377    }
378    if sz < i64::from(minf[1]) || sz > i64::from(maxf[1]) {
379        why.push(format!(
380            "its z extent is {sz}, and a `{named}` box is {}..={} on z",
381            minf[1], maxf[1]
382        ));
383    }
384    if sx % q != 0 || sz % q != 0 {
385        why.push(format!(
386            "its footprint {sx}x{sz} is off the kit grid, whose quantum is {q} — every site-plan \
387             box's extent is a multiple of it (`DW0825`)"
388        ));
389    }
390    let least = i64::from(class.min_clearance) + 1;
391    if sy < least {
392        why.push(format!(
393            "it is {sy} cells tall, and the shallowest `{named}` frame is {least} — {} of \
394             clearance plus the one floor course a piece owns",
395            class.min_clearance
396        ));
397    }
398    if why.is_empty() {
399        return None;
400    }
401    Some(crate::Diagnostic::error(
402        DW_FOOTPRINT_CLASS,
403        stage,
404        path,
405        format!(
406            "`{id}` declares `footprint_class: \"{named}\"` and its own bytes could serve no box \
407             of that class: {why}. The declaration is a claim about what this piece is FOR, and a \
408             site plan hands a piece the exact frame of the box it fills — so a piece whose \
409             extents no box of the class can have is a piece no `details[]` row could ever bind. \
410             Either correct the class name, or rebuild the piece to a frame of the class it \
411             claims. Structure size is {sx}x{sy}x{sz}.",
412            id = meta.prefab_id,
413            why = why.join("; "),
414        ),
415    ))
416}
417
418/// One face of the piece's face contract.
419#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
420pub struct ContractFace {
421    /// The space the way in or out belongs to.
422    pub space: String,
423    /// The edge's class: `walk` | `stair` | `drop` | `barred` | `vision`.
424    pub class: String,
425    /// Which side of the piece: `east` | `west` | `up` | `down` | `south` |
426    /// `north`.
427    pub dir: String,
428    /// The opening, as an inclusive local cell range flat in the face's own
429    /// axis.
430    pub opening: Region,
431}
432
433/// One entry of `spatial_contract.spaces`.
434#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
435pub struct ContractSpace {
436    /// `enclosed` | `open_top` | `open`.
437    pub envelope: String,
438    /// The cells it covers.
439    pub boxes: Vec<Region>,
440}
441
442/// One entry of `spatial_contract.no_body`.
443#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
444pub struct ContractNoBody {
445    /// Why these cells are out of play, in the author's words. Which exemption
446    /// the region qualifies for is a fact about the blocks and is not recorded
447    /// here.
448    pub reason: String,
449    /// The cells it covers.
450    pub boxes: Vec<Region>,
451}
452
453/// One entry of `spatial_contract.edges`.
454#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
455pub struct ContractEdge {
456    /// A declared space name, or `exterior`.
457    pub a: String,
458    /// A declared space name, or `exterior`.
459    pub b: String,
460    /// `walk` | `stair` | `drop` | `barred` | `vision`.
461    pub class: String,
462    /// The declared level change, on the classes that carry one.
463    #[serde(default, skip_serializing_if = "Option::is_none")]
464    pub rise: Option<i64>,
465    /// The opening or transit volume, when the edge declares one.
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub via: Option<ContractVolume>,
468    /// The bar, on a `barred` edge.
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub bar: Option<ContractBar>,
471    /// **The contingency**, on a traversal edge that content opens: the region
472    /// the edge is severed by as built, and which direction opening it goes.
473    ///
474    /// Absent on every edge that is what it claims to be as shipped, which is
475    /// why a piece that declares none writes no key at all and its metadata is
476    /// byte-for-byte what it was.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub way: Option<ContractWay>,
479}
480
481/// A contingent edge's way: the region that decides whether the edge is
482/// crossable, and which direction opening it moves in.
483///
484/// The dual of [`ContractBar`], and the reason `bar` is not extended in place:
485/// an existing piece's metadata says `bar` and keeps saying `bar`. The
486/// **checker** normalises the two into one prover; the document keeps both
487/// spellings, so nothing already written moves a byte.
488#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
489pub struct ContractWay {
490    /// `laid` — the region is empty as built and opening fills it with
491    /// [`block`](ContractWay::block); or `cleared` — the region stands in
492    /// `block` as built and opening voids it.
493    pub opens: String,
494    /// The region's name, which is what content addresses.
495    pub region: String,
496    /// The cells it covers.
497    pub boxes: Vec<Region>,
498    /// The palette role the way is made of, in the author's own vocabulary.
499    ///
500    /// Provenance for a reader, and never a second authority: what an opening
501    /// writes is [`block`](ContractWay::block), because a role name means
502    /// nothing outside the program that bound it. Recorded because a reviewer
503    /// reading this document otherwise has no way back to the declaration —
504    /// `minecraft:oak_planks` says what the cells become and `"tread"` says
505    /// what the author called it.
506    ///
507    /// Optional for the reason [`License::generated_by`] is: a role is a
508    /// *program's* vocabulary, so an expansion always has one and a hand-built
509    /// or ingested piece — which names its blocks directly — has none at all.
510    /// Writing an invented role there would be a fact about nothing.
511    ///
512    /// [`ContractBar`] carries no such field, and deliberately: adding one
513    /// would move the exported bytes of every piece that already declares a
514    /// bar, which spec-0042 §2.3 forbids. The checker reads neither.
515    #[serde(default, skip_serializing_if = "Option::is_none")]
516    pub role: Option<String>,
517    /// The block state the way is made of: what a `laid` way is filled with,
518    /// and what a `cleared` way stands in.
519    pub block: String,
520}
521
522/// An edge's own volume — an opening, a stair's treads, a fall column.
523#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
524pub struct ContractVolume {
525    /// The region's name, which is what content binds to.
526    pub region: String,
527    /// The cells it covers.
528    pub boxes: Vec<Region>,
529}
530
531/// A `barred` edge's bar: the region that stands in the way, and its block.
532#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
533pub struct ContractBar {
534    /// The region's name.
535    pub region: String,
536    /// The cells it covers.
537    pub boxes: Vec<Region>,
538    /// The block state the bar is built from.
539    pub block: String,
540}
541
542/// The `structure` block: which file, how big, for which MC version.
543#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
544pub struct StructureMeta {
545    /// The `.nbt` filename, relative to this metadata file.
546    pub file: String,
547    /// The datapack structure id (a path segment).
548    pub id: String,
549    /// Structure extent `[x, y, z]`.
550    pub size: [i32; 3],
551    /// The MC data version the structure targets (ADR-0009).
552    pub data_version: i32,
553    /// Provenance breadcrumb: what wrote the `.nbt`.
554    #[serde(default, skip_serializing_if = "Option::is_none")]
555    pub generator: Option<String>,
556}
557
558/// One structure template a piece's blocks arrive in, and where in the piece it
559/// sits.
560///
561/// **The unit every placer works in.** A single-template prefab has exactly one,
562/// at `offset` `[0, 0, 0]`; a tiled zone has one per tile at its manifest
563/// offset. Nothing that places, stamps or reads a piece's blocks needs to know
564/// which of the two it was handed — that is the whole point of the type, and the
565/// reason [`PrefabMeta::templates`] is the only way to reach a `.nbt` filename.
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567pub struct PieceTemplate<'a> {
568    /// The datapack structure id (a path segment).
569    pub id: &'a str,
570    /// The `.nbt` filename, relative to the metadata file.
571    pub file: &'a str,
572    /// This template's origin in **piece-local** coordinates — add it to a
573    /// template-local cell to get the piece cell. `[0, 0, 0]` for a
574    /// single-template piece.
575    pub offset: [i32; 3],
576    /// The template's extent `[x, y, z]`.
577    pub size: [i32; 3],
578}
579
580/// **What an anchor is FOR**, when the compiler has to find it without being
581/// told its name (spec-0046).
582///
583/// A closed vocabulary the compiler owns, and deliberately small: a role is
584/// added by the change that teaches the compiler to resolve it, never by a
585/// producer that wants a label. Deserialising is therefore the whole
586/// validation — a term this engine does not know is a `serde` error naming the
587/// terms it does, which the prefab registry reports as `DW0346` against the
588/// file that wrote it, rather than a string ridden through into a resolution
589/// that silently never matches.
590///
591/// Distinct from [`ContractWay::role`], which is a *palette* role in a
592/// program's own vocabulary and means nothing outside it. This one is the
593/// engine's vocabulary, which is exactly why it is closed.
594#[derive(
595    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
596)]
597#[serde(rename_all = "kebab-case")]
598pub enum AnchorRole {
599    /// **The cell a body arrives at when it enters the area this piece is
600    /// placed in.** One per area: `setworldspawn`, the class-apply teleport,
601    /// first-join placement, inter-area transport, the POV planner's first
602    /// frame and the trap-safety start set all resolve it.
603    Entry,
604    /// **Blocks a body stands beside and never on** (spec-0065): a laid table,
605    /// an altar, a counter, a bed. The anchor's `region` is the furniture's own
606    /// blocks, and the walk model refuses to prove a body standing on a solid
607    /// cell of it — a route, a walked leg, a flood, a seat or an exported
608    /// waypoint. A body *posted* there by declaration still stands there.
609    ///
610    /// Many per area, unlike [`AnchorRole::Entry`]: a hall has one door the
611    /// party arrives by and as many tables as it was built with.
612    Furniture,
613}
614
615impl AnchorRole {
616    /// Every term in the vocabulary, in declaration order — what a refusal
617    /// lists, so the message cannot drift from the type.
618    pub const ALL: &'static [AnchorRole] = &[AnchorRole::Entry, AnchorRole::Furniture];
619
620    /// The term as it is written in a document.
621    pub fn as_str(self) -> &'static str {
622        match self {
623            AnchorRole::Entry => "entry",
624            AnchorRole::Furniture => "furniture",
625        }
626    }
627
628    /// Whether an area may give this role to **at most one** anchor.
629    ///
630    /// A role that names the one place the compiler has to find (the entry) is
631    /// refused twice in one area; a role that names a kind of place (furniture)
632    /// is not.
633    pub fn one_per_area(self) -> bool {
634        match self {
635            AnchorRole::Entry => true,
636            AnchorRole::Furniture => false,
637        }
638    }
639
640    /// The terms a refusal lists, comma-separated — one rendering, so a message
641    /// written at a command line and a message written by the prefab registry
642    /// cannot name different vocabularies.
643    pub fn vocabulary() -> String {
644        AnchorRole::ALL
645            .iter()
646            .map(|r| format!("`{r}`"))
647            .collect::<Vec<_>>()
648            .join(", ")
649    }
650}
651
652/// A role typed at a command line is the same closed vocabulary a role written
653/// into a document is, read from the same table — so `delvec prefab anchor
654/// --role` refuses exactly what deserialising the document refuses, by name,
655/// and the two cannot come to know different terms.
656impl std::str::FromStr for AnchorRole {
657    type Err = String;
658
659    fn from_str(s: &str) -> Result<AnchorRole, String> {
660        AnchorRole::ALL
661            .iter()
662            .copied()
663            .find(|r| r.as_str() == s)
664            .ok_or_else(|| {
665                format!(
666                    "unknown anchor role `{s}` — the engine's vocabulary is {}",
667                    AnchorRole::vocabulary()
668                )
669            })
670    }
671}
672
673impl std::fmt::Display for AnchorRole {
674    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
675        f.write_str(self.as_str())
676    }
677}
678
679/// One entry of the `anchors` map.
680///
681/// A point anchor carries `pos` (+ optionally `facing`); a gate anchor carries a
682/// `region` (+ optionally `block`); a trap anchor also carries the hardware the
683/// prefab pre-wired for it. All of those are the same object class — a named
684/// place in a piece — so they live in one type and each writes only the keys it
685/// means.
686#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
687pub struct Anchor {
688    /// Local cell `[x, y, z]`, relative to the structure origin.
689    #[serde(default, skip_serializing_if = "Option::is_none")]
690    pub pos: Option<[i32; 3]>,
691    /// Cardinal facing keyword.
692    #[serde(default, skip_serializing_if = "Option::is_none")]
693    pub facing: Option<String>,
694    /// **What this anchor is for**, when the compiler has to find it without
695    /// being told its name (spec-0046).
696    ///
697    /// A campaign addresses an anchor by its name, and for everything a
698    /// campaign addresses that is the whole story. The entry point is the one
699    /// place a campaign does *not* name — the compiler has to find it — and
700    /// finding it by matching a spelling is a fact about the producer that
701    /// wrote the piece rather than about the piece. So the piece declares it,
702    /// every producer can write it, and none has to agree with another about
703    /// how it is spelled.
704    ///
705    /// Absent on every piece that predates the role, which is what keeps the
706    /// shipped library building byte-for-byte what it built before: the
707    /// compiler falls back to the name list when no anchor in an area declares
708    /// a role.
709    #[serde(default, skip_serializing_if = "Option::is_none")]
710    pub role: Option<AnchorRole>,
711    /// Local cell range, for a gate anchor.
712    #[serde(default, skip_serializing_if = "Option::is_none")]
713    pub region: Option<Region>,
714    /// Block id filling a gate region (e.g. `minecraft:iron_bars`).
715    #[serde(default, skip_serializing_if = "Option::is_none")]
716    pub block: Option<String>,
717    /// **Which element of the piece's spatial contract this anchor lands in** —
718    /// `space:<name>`, `no_body:<name>`, `via:<name>` or `bar:<name>`.
719    ///
720    /// A campaign binds content to an anchor by name; what says whether that
721    /// place is play space, a door or exterior dressing is the contract, and a
722    /// reader who has only the anchor list cannot tell. Absent on a piece that
723    /// declares no contract, and on an anchor that lands in nothing the contract
724    /// accounts for — which is a finding the checker raises rather than a
725    /// silence.
726    #[serde(default, skip_serializing_if = "Option::is_none")]
727    pub resolves_to: Option<String>,
728    /// The pre-wired dispenser socket cell (local coords) for an `anchor/trap`
729    /// marker. `pos` is the trap's trigger/hazard cell (the plate, tripwire or
730    /// chest modelled as the hazard); `dispenser` is the separate cell holding
731    /// the empty dispenser whose payload is filled at compile time. Absent for
732    /// every non-trap anchor.
733    #[serde(default, skip_serializing_if = "Option::is_none")]
734    pub dispenser: Option<[i32; 3]>,
735    /// The block the prefab wired as this `anchor/trap`'s **trigger** — the
736    /// plate or tripwire sitting on `pos` — with its full blockstate exactly as
737    /// authored (`minecraft:oak_pressure_plate[powered=false]`), because
738    /// flag-gating a trap physically removes and restores this block and must
739    /// put back what was there. The gate-anchor `block` above is the same
740    /// contract for a sealed gate. Absent for every non-trap anchor.
741    #[serde(default, skip_serializing_if = "Option::is_none")]
742    pub trigger_block: Option<String>,
743    /// **One line of prose about this place, for a person reading the piece.**
744    ///
745    /// The engine never reads it: nothing routes, places, lights or refuses
746    /// anything because of what it says. It is modelled all the same, because
747    /// a document whose only reader is a machine is a document a person cannot
748    /// review, and a producer that writes the key unmodelled makes every build
749    /// report `DW0543` — "this library is newer than this engine" — about a
750    /// sentence. A tripwire that fires on the normal state of the tree is not a
751    /// tripwire.
752    ///
753    /// It is prose, so it is deliberately unconstrained and deliberately not
754    /// inventoried for translation: it is addressed to whoever opens the `.json`,
755    /// never to a player.
756    #[serde(default, skip_serializing_if = "Option::is_none")]
757    pub note: Option<String>,
758    /// Every anchor key this version does not model, kept verbatim. The anchor
759    /// block is where this document has grown most often — `resolves_to`,
760    /// `dispenser` and `trigger_block` were each a new key on a shipped
761    /// document — so it captures for the same reason [`PrefabMeta::extra`]
762    /// does.
763    #[serde(flatten)]
764    pub extra: BTreeMap<String, serde_json::Value>,
765}
766
767impl Anchor {
768    /// The point-anchor shape: a cell and a facing.
769    pub fn point(pos: [i32; 3], facing: impl Into<String>) -> Anchor {
770        Anchor {
771            pos: Some(pos),
772            facing: Some(facing.into()),
773            ..Anchor::default()
774        }
775    }
776
777    /// Declare what this anchor is for ([`Anchor::role`]).
778    pub fn with_role(mut self, role: AnchorRole) -> Anchor {
779        self.role = Some(role);
780        self
781    }
782}
783
784/// A gate anchor's region and fill block, in **piece-local** coordinates — the
785/// answer [`PrefabMeta::gate_anchor`] gives, and the only shape either reader
786/// works from.
787#[derive(Debug, Clone, PartialEq, Eq)]
788pub struct GateAnchor {
789    /// Low corner of the region, piece-local.
790    pub from: [i32; 3],
791    /// High corner of the region, piece-local, inclusive.
792    pub to: [i32; 3],
793    /// The block the region is filled with and cleared of.
794    pub block: String,
795}
796
797impl GateAnchor {
798    /// The region as a reader sees it in a diagnostic.
799    fn extent(&self) -> String {
800        format!(
801            "[{},{},{}]..[{},{},{}]",
802            self.from[0], self.from[1], self.from[2], self.to[0], self.to[1], self.to[2]
803        )
804    }
805}
806
807/// The contract-element name a `bar:<region>` [`Anchor::resolves_to`] carries,
808/// and nothing else's. Every other element kind is a place a body stands, looks
809/// through or walks over — not a thing content fills.
810fn bar_name(resolves_to: &str) -> Option<&str> {
811    resolves_to.strip_prefix("bar:")
812}
813
814/// The one box `boxes` exactly fills, or `None` when they do not fill one.
815///
816/// A contract region is a **list** of boxes, and a gate is a **single** box: the
817/// compiler fills it and clears it as one region, and every consumer of a
818/// resolved gate — the assembler that voids it, the seal that rebuilds it, the
819/// nav model that walks through it — is written against two corners. So the
820/// question is not "what box contains these" but "do these BE a box": a bounding
821/// box that the members do not fill would hand every one of those consumers
822/// cells the contract never called bar, and the assembler would delete them.
823///
824/// Exact, not approximate: the members must be pairwise disjoint and their
825/// volumes must sum to the bounding box's. A doorway declared as a lintel row
826/// plus the two jambs under it is one box and passes; a doorway plus a
827/// threshold nub hanging off its corner is not, and is refused.
828fn one_box(boxes: &[Region]) -> Option<Region> {
829    let first = boxes.first()?;
830    let mut from = first.from;
831    let mut to = first.to;
832    for b in &boxes[1..] {
833        for a in 0..3 {
834            from[a] = from[a].min(b.from[a]).min(b.to[a]);
835            to[a] = to[a].max(b.from[a]).max(b.to[a]);
836        }
837    }
838    let vol = |f: [i32; 3], t: [i32; 3]| -> i64 {
839        (0..3)
840            .map(|a| i64::from(t[a] - f[a]) + 1)
841            .try_fold(1i64, |acc, n| if n > 0 { acc.checked_mul(n) } else { None })
842            .unwrap_or(0)
843    };
844    let total: i64 = boxes.iter().map(|b| vol(b.from, b.to)).sum();
845    if total != vol(from, to) {
846        return None;
847    }
848    for (i, a) in boxes.iter().enumerate() {
849        for b in &boxes[i + 1..] {
850            if (0..3).all(|k| a.from[k] <= b.to[k] && b.from[k] <= a.to[k]) {
851                return None;
852            }
853        }
854    }
855    Some(Region { from, to })
856}
857
858/// Where an anchor is and what it is for — the parts of an anchor an editing
859/// tool declares.
860///
861/// Deliberately a different type from [`Anchor`]: the whole anchor is what a
862/// caller must not be able to hand an editing step, because constructing one
863/// means filling in — and therefore erasing — the hardware, provenance and
864/// unknown keys the caller knows nothing about. See [`PrefabMeta::edit_anchor`].
865#[derive(Debug, Clone, Default, PartialEq)]
866pub struct AnchorEdit {
867    /// Local cell `[x, y, z]`, for a point anchor.
868    pub pos: Option<[i32; 3]>,
869    /// Cardinal facing keyword.
870    pub facing: Option<String>,
871    /// Local cell range, for a gate anchor.
872    pub region: Option<Region>,
873    /// Block id filling a gate region.
874    pub block: Option<String>,
875    /// **What the anchor is for** ([`Anchor::role`]), tri-state because the
876    /// place and the purpose are two properties and an edit may speak about
877    /// either without speaking about the other:
878    ///
879    /// * `None` — the edit says nothing about the role, so an existing one is
880    ///   kept. Moving a cell is not a statement that the piece stopped being
881    ///   the place a party arrives at, and silently answering it as one is the
882    ///   deletion this type exists to prevent.
883    /// * `Some(None)` — the edit says the anchor has **no** role, and an
884    ///   existing one is removed. This is the remedy `DW0804` prescribes when
885    ///   two anchors in one area both claim a role, and it is reachable here
886    ///   rather than only by hand-editing the document.
887    /// * `Some(Some(role))` — the anchor is declared to have that role.
888    pub role: Option<Option<AnchorRole>>,
889}
890
891/// An inclusive local cell range.
892#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
893pub struct Region {
894    /// Low corner `[x, y, z]`.
895    pub from: [i32; 3],
896    /// High corner `[x, y, z]`.
897    pub to: [i32; 3],
898}
899
900/// One jigsaw socket declared by a prefab.
901///
902/// `local_pos` is the socket's wall cell (bottom-centre of the opening) in the
903/// prefab's local coordinates; `facing` is the cardinal direction the opening
904/// faces outward. Two sockets mate by placing the child so its socket sits one
905/// block beyond the parent's, facing the opposite way.
906#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
907pub struct Connector {
908    /// Jigsaw `name`.
909    pub name: String,
910    /// Jigsaw `target`.
911    pub target: String,
912    /// The socket's wall cell, local coords `[x, y, z]`.
913    pub local_pos: [i32; 3],
914    /// Cardinal direction the opening faces outward.
915    pub facing: String,
916    /// Opening extent `[width, height]`.
917    pub opening: [i32; 2],
918    /// Jigsaw joint.
919    pub joint: String,
920}
921
922/// The profile of a prefab whose light nothing has measured.
923pub const UNMEASURED: &str = "unmeasured";
924
925/// The `license` block: the human half and the machine half of provenance.
926#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
927pub struct License {
928    /// Where the asset came from (`original`, or a named upstream).
929    pub source: String,
930    /// SPDX id (ADR-0013).
931    pub spdx: String,
932    /// Human note.
933    pub note: String,
934    /// Human-readable provenance sentence.
935    pub provenance: String,
936    /// The machine-readable provenance row: what regenerates these exact bytes.
937    ///
938    /// Absent for a piece nothing can regenerate — an ingested community build,
939    /// or a hand-edited one. Present, it is the ADR-0006 claim in a form a tool
940    /// can act on rather than a sentence a human can read.
941    #[serde(default, skip_serializing_if = "Option::is_none")]
942    pub generated_by: Option<GeneratedBy>,
943}
944
945/// Everything needed to reproduce the `.nbt` byte for byte (ADR-0006).
946///
947/// **Every input that reaches the bytes, and nothing that does not.** A record
948/// missing one of them is worse than no record: it names a set of inputs, and a
949/// re-expansion from that set produces a different artifact while the document
950/// claims byte reproducibility. The set is the source program, the overrides
951/// applied to it, the region and the seed.
952#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
953pub struct GeneratedBy {
954    /// The back end that produced the bytes.
955    pub generator: String,
956    /// The source program's name.
957    pub program: String,
958    /// `sha256:<64 hex>` over the canonical JSON of the program **as expanded**
959    /// — the source document with [`Self::params`] and [`Self::roles`] already
960    /// applied. It is therefore the checksum of the reproduction rather than a
961    /// second statement of it: apply the overrides to the named document and
962    /// this is the hash you must get.
963    pub program_hash: String,
964    /// The expansion seed.
965    pub seed: u64,
966    /// The region the program was expanded over, `[x, y, z]`. An independent
967    /// input: the same program at the same seed over a different box is a
968    /// different building.
969    pub region: [i32; 3],
970    /// Integer parameters overridden on the way in (`delvec grammar expand
971    /// --param`), by name. Empty — and absent from the document — where the
972    /// program was expanded as written.
973    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
974    pub params: BTreeMap<String, i64>,
975    /// Palette roles rebound on the way in (`--role`), by name, each the block
976    /// state as the caller wrote it. The axis frame is not recorded because it
977    /// is not an input: a rebind inherits the frame of the binding it replaces,
978    /// which the named source document already carries.
979    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
980    pub roles: BTreeMap<String, String>,
981}
982
983impl PrefabMeta {
984    /// Parse metadata from JSON text.
985    ///
986    /// **The one reader of both packagings.** "Which shape is this" has exactly
987    /// two answers and no third, so a document declaring neither block, or both,
988    /// is refused here rather than handed half-read to a step that will place
989    /// some of its blocks. A tile set is validated as it is read
990    /// ([`TileSet::validate`]) for the same reason: a manifest that does not
991    /// tile its own volume reassembles into a building with a hole in it and
992    /// reports success.
993    pub fn from_json(text: &str) -> Result<PrefabMeta, String> {
994        let meta: PrefabMeta =
995            serde_json::from_str(text).map_err(|e| format!("invalid prefab metadata: {e}"))?;
996        match (&meta.structure, &meta.structure_set) {
997            (None, None) => {
998                return Err("prefab metadata has neither a `structure` block nor a \
999                            `structure_set` block — it does not say what blocks it describes"
1000                    .to_string());
1001            }
1002            (Some(_), Some(_)) => {
1003                return Err(
1004                    "prefab metadata has BOTH a `structure` block and a `structure_set` \
1005                            block — a piece's blocks arrive one way or the other, and a reader \
1006                            cannot be asked which one is the building"
1007                        .to_string(),
1008                );
1009            }
1010            (None, Some(set)) => set
1011                .validate()
1012                .map_err(|e| format!("`structure_set`: {e}"))?,
1013            (Some(_), None) => {}
1014        }
1015        Ok(meta)
1016    }
1017
1018    /// Every structure template this piece's blocks arrive in, in a
1019    /// deterministic order (grid order for a tile set).
1020    ///
1021    /// Empty only for a value built in code that declares neither block, which
1022    /// [`Self::from_json`] refuses — nothing read from disk is in that state.
1023    pub fn templates(&self) -> Vec<PieceTemplate<'_>> {
1024        if let Some(s) = &self.structure {
1025            return vec![PieceTemplate {
1026                id: &s.id,
1027                file: &s.file,
1028                offset: [0, 0, 0],
1029                size: s.size,
1030            }];
1031        }
1032        self.structure_set
1033            .iter()
1034            .flat_map(|set| {
1035                set.parts.iter().map(|p| PieceTemplate {
1036                    id: &p.id,
1037                    file: &p.file,
1038                    offset: p.offset,
1039                    size: p.size,
1040                })
1041            })
1042            .collect()
1043    }
1044
1045    /// The piece's extent `[x, y, z]` — the WHOLE building, whichever packaging
1046    /// its blocks arrived in. `[0, 0, 0]` only for the value
1047    /// [`Self::templates`] documents as unreachable from disk.
1048    pub fn size(&self) -> [i32; 3] {
1049        match (&self.structure, &self.structure_set) {
1050            (Some(s), _) => s.size,
1051            (None, Some(set)) => set.size,
1052            (None, None) => [0, 0, 0],
1053        }
1054    }
1055
1056    /// The MC data version the piece's templates target (ADR-0009), when it
1057    /// declares one.
1058    pub fn data_version(&self) -> Option<i32> {
1059        match (&self.structure, &self.structure_set) {
1060            (Some(s), _) => Some(s.data_version),
1061            (None, Some(set)) => Some(set.data_version),
1062            (None, None) => None,
1063        }
1064    }
1065
1066    /// True when the piece's blocks arrive as several templates — a fact about
1067    /// packaging that only a tool reporting on packaging may ask.
1068    pub fn is_tiled(&self) -> bool {
1069        self.structure_set.is_some()
1070    }
1071
1072    /// The filename stem the piece's files are named from — the single
1073    /// template's `id`, or the tile set's `base`. They are the same concept
1074    /// under two keys, so a diagnostic that wants to name the piece's document
1075    /// asks here rather than reaching into one packaging.
1076    pub fn base(&self) -> &str {
1077        match (&self.structure, &self.structure_set) {
1078            (Some(s), _) => &s.id,
1079            (None, Some(set)) => &set.base,
1080            (None, None) => "",
1081        }
1082    }
1083
1084    /// The tile grid `[x, y, z]`; `[1, 1, 1]` for a piece that fit one
1085    /// template. Packaging, like [`Self::is_tiled`].
1086    pub fn grid(&self) -> [i32; 3] {
1087        self.structure_set
1088            .as_ref()
1089            .map_or([1, 1, 1], |set| set.grid)
1090    }
1091
1092    /// Read the document at `path`, or `Ok(None)` when there is no file there.
1093    pub fn read(path: &Path) -> Result<Option<PrefabMeta>, String> {
1094        if !path.exists() {
1095            return Ok(None);
1096        }
1097        let text =
1098            std::fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))?;
1099        PrefabMeta::from_json(&text).map(Some)
1100    }
1101
1102    /// Load `<nbt_path>.json` (the sibling metadata), or `Ok(None)` when absent.
1103    pub fn beside_nbt(nbt_path: &Path) -> Result<Option<PrefabMeta>, String> {
1104        let json_path = nbt_path.with_extension("json");
1105        if !json_path.exists() {
1106            return Ok(None);
1107        }
1108        let text = std::fs::read_to_string(&json_path)
1109            .map_err(|e| format!("read {}: {e}", json_path.display()))?;
1110        Ok(Some(PrefabMeta::from_json(&text)?))
1111    }
1112
1113    /// Serialize as canonical pretty JSON with a trailing newline.
1114    pub fn to_json(&self) -> String {
1115        serde_json::to_string_pretty(self).expect("prefab metadata serializes") + "\n"
1116    }
1117
1118    /// The JSON Schema of this document, for `delvec schema --stage
1119    /// prefab-metadata`.
1120    ///
1121    /// **Deliberately not part of `--stage all`.** `all` is the campaign DSL's
1122    /// staged documents, and the gallery's coverage gate enumerates its units
1123    /// from exactly that export: a library-asset document folded into it would
1124    /// demand a gallery *stage-document* binding for every field of a file no
1125    /// stage document contains. A prefab's declarations are proven where they
1126    /// are read — `shown_faces` by the exposure ledger, `walk_y` and
1127    /// `waterline_y` by the seating and waterline bindings — which is a binding
1128    /// a schema unit could not give them.
1129    ///
1130    /// It is exported anyway, and for the reason the walk record is: this is
1131    /// the command an author is told to run to see the shape of a document they
1132    /// must write, and a piece's metadata is one of those.
1133    pub fn schema() -> serde_json::Value {
1134        let mut v = serde_json::to_value(schemars::schema_for!(PrefabMeta))
1135            .expect("the prefab-metadata schema serializes to JSON");
1136        if let Some(obj) = v.as_object_mut() {
1137            obj.insert(
1138                "title".into(),
1139                serde_json::Value::String("<prefab-id>.json (prefab metadata)".into()),
1140            );
1141            obj.insert(
1142                "description".into(),
1143                serde_json::Value::String(SCHEMA_DESCRIPTION.into()),
1144            );
1145        }
1146        v
1147    }
1148
1149    /// Every key of this document — top level and per anchor — that this version
1150    /// does not model, as `(where, key)` pairs in a stable order.
1151    ///
1152    /// `where` is `""` for a top-level key and the anchor's name for an anchor
1153    /// key. A reader that wants to say something about a key it kept asks here;
1154    /// nothing has to re-open the file to find out.
1155    pub fn unknown_keys(&self) -> Vec<(&str, &str)> {
1156        let mut out: Vec<(&str, &str)> = self
1157            .extra
1158            .keys()
1159            .map(|k| ("", k.as_str()))
1160            .collect::<Vec<_>>();
1161        for (name, anchor) in &self.anchors {
1162            for key in anchor.extra.keys() {
1163                out.push((name.as_str(), key.as_str()));
1164            }
1165        }
1166        out
1167    }
1168
1169    /// A minimal skeleton for a freshly admitted external piece.
1170    pub fn skeleton(
1171        id: &str,
1172        size: [i32; 3],
1173        data_version: i32,
1174        generator: &str,
1175        license: License,
1176    ) -> PrefabMeta {
1177        PrefabMeta {
1178            prefab_id: format!("prefab/{id}"),
1179            structure: Some(StructureMeta {
1180                file: format!("{id}.nbt"),
1181                id: id.to_string(),
1182                size,
1183                data_version,
1184                generator: Some(generator.to_string()),
1185            }),
1186            structure_set: None,
1187            anchors: BTreeMap::new(),
1188            connectors: Vec::new(),
1189            lighting: Some(Lighting {
1190                method: Some("not yet probed".to_string()),
1191                ..Lighting::unmeasured()
1192            }),
1193            license: Some(license),
1194            // A freshly admitted piece states no walk plane, for the reason
1195            // `walk_y` has no default: the number is a measurement of the piece
1196            // its generator made, and the admission step that converts a
1197            // stranger's `.nbt` did not build the piece and has no walk plane
1198            // to report. A campaign that seats such a piece on a horizon whose
1199            // datum needs one is `DW0886`, which is where the author learns.
1200            walk_y: None,
1201            waterline_y: None,
1202            // A freshly admitted piece shows nothing, for the same reason it
1203            // claims no size class: which of its sides are finished surface is
1204            // the author's claim about what the piece is FOR, and reading it off
1205            // the bytes would be this document inferring intent from material.
1206            shown_faces: Vec::new(),
1207            spatial_contract: None,
1208            // A freshly admitted piece makes no claim about which size class of
1209            // box it fills, and inventing one from its bytes would be the
1210            // inference this document does not do: the claim is the author's.
1211            footprint_class: None,
1212            extra: BTreeMap::new(),
1213        }
1214    }
1215
1216    /// Annotate a named anchor's **place and purpose**, creating the anchor
1217    /// when it is not there yet.
1218    ///
1219    /// An anchor is an object, not a value. A tool that names where the anchor
1220    /// is has said nothing about the hardware the prefab wired at it
1221    /// ([`Anchor::dispenser`], [`Anchor::trigger_block`]), about which contract
1222    /// element an exporter resolved it into ([`Anchor::resolves_to`]), or about
1223    /// any key this version has never heard of ([`Anchor::extra`]) — so none of
1224    /// those is touched. Replacing the whole anchor instead is the same silent
1225    /// deletion this type exists to prevent at the top level, one level down,
1226    /// and on the block of the document that has grown most often.
1227    ///
1228    /// The place itself is one property expressed two ways — a cell or a region
1229    /// — so an edit redeclares all four of its fields together and a `pos` does
1230    /// supersede a stale `region`.
1231    ///
1232    /// The **role** is a fifth field and not a fifth way of saying where: what
1233    /// an anchor is for is a property of the anchor, so it is written when the
1234    /// edit speaks about it, cleared when the edit says it has none, and left
1235    /// alone when the edit says nothing ([`AnchorEdit::role`]).
1236    pub fn edit_anchor(&mut self, name: &str, edit: AnchorEdit) {
1237        let anchor = self.anchors.entry(name.to_string()).or_default();
1238        anchor.pos = edit.pos;
1239        anchor.facing = edit.facing;
1240        anchor.region = edit.region;
1241        anchor.block = edit.block;
1242        if let Some(role) = edit.role {
1243            anchor.role = role;
1244        }
1245    }
1246
1247    /// **The ONE authority on the region and block a gate anchor names**, in
1248    /// piece-local coordinates.
1249    ///
1250    /// A gate anchor is declared in one of two forms, and the compiler must read
1251    /// both identically:
1252    ///
1253    /// * **explicitly** — the anchor carries its own [`region`](Anchor::region)
1254    ///   and [`block`](Anchor::block), which is how a hand-authored piece has
1255    ///   always written one;
1256    /// * **through the piece's spatial contract** — the anchor carries a
1257    ///   [`resolves_to`](Anchor::resolves_to) of `bar:<region>`, which is what an
1258    ///   exporter writes. The cells and the block already live in that edge's
1259    ///   [`ContractBar`], so repeating them on the anchor would be a second
1260    ///   authority for one fact, and the exporter rightly does not.
1261    ///
1262    /// Nothing derived either form from the other, and the whole compiler read
1263    /// only the first. A piece declaring its gates the second way therefore had
1264    /// no gate at all: the anchor resolved to a bare point, every verb that fills
1265    /// or clears a gate was refused (`DW0343`), and the information the refusal
1266    /// asked for was sitting in the same document.
1267    ///
1268    /// Both readers ask this function and nothing else — the planner, which
1269    /// resolves the anchor to world cells, and
1270    /// [`AnchorRegistry`](crate::AnchorRegistry)'s prefab implementation, which
1271    /// answers whether the compiler can fill it — so the two cannot come to
1272    /// disagree about what a gate is or where it stands.
1273    ///
1274    /// Three answers, and the third is the one that earns the `Result`:
1275    ///
1276    /// * `Ok(None)` — not a gate anchor. A point anchor, a trap anchor, or an
1277    ///   anchor whose `resolves_to` names a space, a `no_body` region, a `via`
1278    ///   volume or a `way`. None of those is a thing content fills or clears.
1279    /// * `Ok(Some(gate))` — a gate, and here is the box and the block.
1280    /// * `Err(why)` — declared as a gate and **not resolvable to one fillable
1281    ///   box**. Refused rather than guessed, because every alternative writes
1282    ///   blocks somewhere the document did not ask for. `why` is a clause the
1283    ///   caller folds into its own diagnostic.
1284    ///
1285    /// A `way` is deliberately not a gate here. Its
1286    /// [`opens`](ContractWay::opens) is a direction — `laid` cells are absent as
1287    /// built and appear when opened, `cleared` cells stand and are voided — and
1288    /// the single-region gate model carries no direction to put it in. Reading
1289    /// one as a gate would silently pick a direction for the author.
1290    pub fn gate_anchor(&self, name: &str) -> Result<Option<GateAnchor>, String> {
1291        let Some(anchor) = self.anchors.get(name) else {
1292            return Ok(None);
1293        };
1294        // A furniture anchor's `region` is the furniture's own blocks, never a
1295        // span content fills and clears (spec-0065 §3). Read as a gate it would
1296        // be voided out of the modelled world and walked straight through.
1297        if anchor.role == Some(AnchorRole::Furniture) {
1298            return Ok(None);
1299        }
1300        let contract_bar = match anchor.resolves_to.as_deref().and_then(bar_name) {
1301            Some(region) => Some(self.contract_bar(name, region)?),
1302            None => None,
1303        };
1304        match (&anchor.region, contract_bar) {
1305            (None, None) => Ok(None),
1306            // The contract form. The block is the contract's, which is the block
1307            // the piece was actually built out of.
1308            (None, Some(bar)) => Ok(Some(bar)),
1309            // The explicit form, unchanged since it was the only one. A region
1310            // with no `block` is what `DW0343` has always refused: the compiler
1311            // is being asked to fill cells with a block nothing names.
1312            (Some(region), None) => match &anchor.block {
1313                Some(block) => Ok(Some(GateAnchor {
1314                    from: region.from,
1315                    to: region.to,
1316                    block: block.clone(),
1317                })),
1318                None => Err(format!(
1319                    "gate anchor `{name}` declares a `region` and no `block`, so nothing says \
1320                     what the region is filled with"
1321                )),
1322            },
1323            // Both forms. Agreement is fine and is what a piece that was
1324            // hand-authored and later exported looks like; a disagreement is
1325            // refused rather than resolved by precedence, because whichever one
1326            // this function preferred would be a rule no reader of the document
1327            // could see.
1328            (Some(region), Some(bar)) => {
1329                let explicit = GateAnchor {
1330                    from: region.from,
1331                    to: region.to,
1332                    block: anchor.block.clone().unwrap_or_default(),
1333                };
1334                if explicit == bar {
1335                    return Ok(Some(bar));
1336                }
1337                Err(format!(
1338                    "gate anchor `{name}` declares a `region` and also resolves into contract bar \
1339                     `{bar_region}`, and the two disagree — the anchor says {ea} filled with \
1340                     `{eb}`, the bar says {ba} filled with `{bb}`. One place stands in one way: \
1341                     delete the anchor's `region`/`block` and let the contract say it, or correct \
1342                     the contract",
1343                    bar_region = anchor
1344                        .resolves_to
1345                        .as_deref()
1346                        .and_then(bar_name)
1347                        .unwrap_or_default(),
1348                    ea = explicit.extent(),
1349                    eb = explicit.block,
1350                    ba = bar.extent(),
1351                    bb = bar.block,
1352                ))
1353            }
1354        }
1355    }
1356
1357    /// The bar `region` of this piece's spatial contract, as one fillable box.
1358    fn contract_bar(&self, anchor: &str, region: &str) -> Result<GateAnchor, String> {
1359        let bar = self
1360            .spatial_contract
1361            .as_ref()
1362            .into_iter()
1363            .flat_map(|c| c.edges.iter())
1364            .filter_map(|e| e.bar.as_ref())
1365            .find(|b| b.region == region)
1366            .ok_or_else(|| {
1367                format!(
1368                    "gate anchor `{anchor}` resolves into contract bar `{region}`, and this \
1369                     piece's spatial contract declares no bar of that name — the anchor's \
1370                     `resolves_to` is written from the contract, so the two have come apart. \
1371                     Re-export the piece"
1372                )
1373            })?;
1374        let one = one_box(&bar.boxes).ok_or_else(|| {
1375            format!(
1376                "gate anchor `{anchor}` resolves into contract bar `{region}`, whose {n} boxes do \
1377                 not fill their own bounding box — so there is no single region the compiler can \
1378                 fill or clear without writing blocks into cells the contract does not call bar. \
1379                 Declare the bar as one box, or as boxes that tile one",
1380                n = bar.boxes.len()
1381            )
1382        })?;
1383        Ok(GateAnchor {
1384            from: one.from,
1385            to: one.to,
1386            block: bar.block.clone(),
1387        })
1388    }
1389
1390    /// Append a socket connector (idempotent by `local_pos` + `facing`).
1391    pub fn add_connector(&mut self, c: Connector) {
1392        if !self
1393            .connectors
1394            .iter()
1395            .any(|x| x.local_pos == c.local_pos && x.facing == c.facing)
1396        {
1397            self.connectors.push(c);
1398        }
1399    }
1400}
1401
1402#[cfg(test)]
1403mod tests {
1404    use super::*;
1405
1406    /// The whole reason this type is not two types: an editing tool reads a
1407    /// document, changes one block of it, and writes it back. Anything it does
1408    /// not model is deleted, and nothing says so.
1409    #[test]
1410    fn a_read_modify_write_round_trip_keeps_every_field() {
1411        let text = r#"{
1412  "prefab_id": "prefab/chapel-ward",
1413  "structure": {
1414    "file": "chapel-ward.nbt",
1415    "id": "chapel-ward",
1416    "size": [16, 9, 26],
1417    "data_version": 4671,
1418    "generator": "crates/delvec/src/grammar"
1419  },
1420  "anchors": {
1421    "anchor/bell": { "pos": [3, 1, 4], "facing": "north" },
1422    "anchor/ward": { "region": { "from": [0, 0, 0], "to": [2, 2, 2] }, "block": "minecraft:stone" }
1423  },
1424  "connectors": [],
1425  "lighting": { "profile": "unmeasured" },
1426  "license": {
1427    "source": "original",
1428    "spdx": "GPL-3.0-or-later",
1429    "note": "n",
1430    "provenance": "p",
1431    "generated_by": {
1432      "generator": "grammar",
1433      "program": "bell_chapel_ward",
1434      "program_hash": "sha256:00",
1435      "seed": 1,
1436      "region": [11, 6, 13]
1437    }
1438  },
1439  "waterline_y": 2
1440}
1441"#;
1442        let mut meta = PrefabMeta::from_json(text).unwrap();
1443        meta.lighting = Some(Lighting {
1444            profile: crate::registry::LightingProfile::Dark,
1445            measured_min_light: Some(0),
1446            measured: Some("2026-08-11".to_string()),
1447            rationale: None,
1448            method: Some("static estimate".to_string()),
1449        });
1450        let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1451        let before: serde_json::Value = serde_json::from_str(text).unwrap();
1452        assert_eq!(
1453            after["license"]["generated_by"], before["license"]["generated_by"],
1454            "the provenance row must survive an edit to an unrelated block"
1455        );
1456        assert_eq!(after["anchors"], before["anchors"]);
1457        assert_eq!(after["structure"], before["structure"]);
1458        assert_eq!(
1459            after["waterline_y"], before["waterline_y"],
1460            "a declared waterline must survive an edit to an unrelated block"
1461        );
1462    }
1463
1464    /// The same guarantee for a key no version of this type has ever heard of.
1465    /// This is the general form of the `waterline_y` and `generated_by` losses:
1466    /// the type cannot enumerate what has not been invented, so it keeps it.
1467    #[test]
1468    fn a_key_this_version_does_not_model_survives_the_round_trip() {
1469        let text = r#"{
1470  "prefab_id": "prefab/x",
1471  "structure": { "file": "x.nbt", "id": "x", "size": [3, 3, 3], "data_version": 4671 },
1472  "anchors": { "anchor/a": { "pos": [1, 1, 1], "acoustics": "reverberant" } },
1473  "connectors": [],
1474  "lighting": { "profile": "unmeasured" },
1475  "from_the_future": { "nested": [1, 2, 3] }
1476}
1477"#;
1478        let mut meta = PrefabMeta::from_json(text).unwrap();
1479        assert_eq!(
1480            meta.unknown_keys(),
1481            vec![("", "from_the_future"), ("anchor/a", "acoustics")],
1482            "both unknown keys must be reportable, top level and per anchor"
1483        );
1484        meta.connectors.push(Connector {
1485            name: "keep:socket".to_string(),
1486            target: "keep:socket".to_string(),
1487            local_pos: [0, 0, 0],
1488            facing: "north".to_string(),
1489            opening: [3, 3],
1490            joint: "aligned".to_string(),
1491        });
1492        let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1493        let before: serde_json::Value = serde_json::from_str(text).unwrap();
1494        assert_eq!(after["from_the_future"], before["from_the_future"]);
1495        assert_eq!(
1496            after["anchors"]["anchor/a"]["acoustics"],
1497            before["anchors"]["anchor/a"]["acoustics"]
1498        );
1499    }
1500
1501    /// The same guarantee **inside** an anchor, which is where the document's
1502    /// round trip is finest-grained and where the top-level guarantee above says
1503    /// nothing at all.
1504    ///
1505    /// An editing step that re-annotates an anchor already on the piece names
1506    /// only where it is. The dispenser cell the prefab wired, the trigger block
1507    /// it must put back, the contract element the exporter resolved, and a key
1508    /// no version has heard of are all properties of the anchor and not of the
1509    /// edit — so all four survive, and only the place changes.
1510    #[test]
1511    fn re_annotating_an_anchor_keeps_the_hardware_the_piece_carries() {
1512        let text = r#"{
1513  "prefab_id": "prefab/trap-room",
1514  "structure": { "file": "trap-room.nbt", "id": "trap-room", "size": [7, 5, 7], "data_version": 4671 },
1515  "anchors": {
1516    "anchor/trap": {
1517      "pos": [3, 1, 3],
1518      "facing": "north",
1519      "resolves_to": "space:hall",
1520      "dispenser": [3, 2, 4],
1521      "trigger_block": "minecraft:oak_pressure_plate[powered=false]",
1522      "acoustics": "reverberant"
1523    }
1524  },
1525  "connectors": [],
1526  "lighting": { "profile": "unmeasured" }
1527}
1528"#;
1529        let mut meta = PrefabMeta::from_json(text).unwrap();
1530        meta.edit_anchor(
1531            "anchor/trap",
1532            AnchorEdit {
1533                pos: Some([4, 1, 3]),
1534                facing: Some("south".to_string()),
1535                ..AnchorEdit::default()
1536            },
1537        );
1538        let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1539        let a = &after["anchors"]["anchor/trap"];
1540        assert_eq!(
1541            a["pos"],
1542            serde_json::json!([4, 1, 3]),
1543            "the place is edited"
1544        );
1545        assert_eq!(a["facing"], serde_json::json!("south"));
1546        assert_eq!(
1547            a["dispenser"],
1548            serde_json::json!([3, 2, 4]),
1549            "the pre-wired dispenser cell is the piece's hardware, not the edit's"
1550        );
1551        assert_eq!(
1552            a["trigger_block"],
1553            serde_json::json!("minecraft:oak_pressure_plate[powered=false]"),
1554            "flag-gating a trap has to put this exact block back"
1555        );
1556        assert_eq!(a["resolves_to"], serde_json::json!("space:hall"));
1557        assert_eq!(
1558            a["acoustics"],
1559            serde_json::json!("reverberant"),
1560            "a key this version does not model is the anchor's too"
1561        );
1562
1563        // A gate anchor's region and a point anchor's cell are one property, so
1564        // naming the cell supersedes the region rather than leaving both.
1565        meta.edit_anchor(
1566            "anchor/gate",
1567            AnchorEdit {
1568                region: Some(Region {
1569                    from: [0, 0, 0],
1570                    to: [1, 2, 0],
1571                }),
1572                block: Some("minecraft:iron_bars".to_string()),
1573                ..AnchorEdit::default()
1574            },
1575        );
1576        meta.edit_anchor(
1577            "anchor/gate",
1578            AnchorEdit {
1579                pos: Some([0, 1, 0]),
1580                ..AnchorEdit::default()
1581            },
1582        );
1583        let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1584        let g = &after["anchors"]["anchor/gate"];
1585        assert_eq!(g["pos"], serde_json::json!([0, 1, 0]));
1586        assert!(g.get("region").is_none(), "{g}");
1587        assert!(g.get("block").is_none(), "{g}");
1588    }
1589
1590    /// A tiled zone's manifest is a prefab document like any other: it is read,
1591    /// one block of it is edited, and it is written back whole — and the keys
1592    /// this version does not model survive.
1593    ///
1594    /// It used to be a *second type* (`TileSetMeta`), field-for-field this one.
1595    /// The copy is what this test is really about: the same round trip, on the
1596    /// same struct, is what makes a block added here reach both packagings.
1597    #[test]
1598    fn a_tile_set_manifest_round_trips_through_an_edit() {
1599        let text = r#"{
1600  "prefab_id": "prefab/notre-dame",
1601  "structure_set": {
1602    "base": "notre-dame",
1603    "size": [31, 48, 93],
1604    "part_max": 48,
1605    "grid": [1, 1, 2],
1606    "data_version": 4671,
1607    "generator": "crates/delvec/src/grammar",
1608    "parts": [
1609      { "file": "notre-dame.x0y0z0.nbt", "id": "a", "grid_index": [0,0,0], "offset": [0,0,0], "size": [31,48,48] },
1610      { "file": "notre-dame.x0y0z1.nbt", "id": "b", "grid_index": [0,0,1], "offset": [0,0,48], "size": [31,48,45] }
1611    ]
1612  },
1613  "anchors": { "anchor/crossing": { "pos": [15, 1, 56], "facing": "south" } },
1614  "connectors": [],
1615  "lighting": { "profile": "unmeasured" },
1616  "waterline_y": 12,
1617  "license": {
1618    "source": "original",
1619    "spdx": "GPL-3.0-or-later",
1620    "note": "n",
1621    "provenance": "p",
1622    "generated_by": {
1623      "generator": "grammar",
1624      "program": "nd",
1625      "program_hash": "sha256:00",
1626      "seed": 1,
1627      "region": [3, 3, 3]
1628    }
1629  },
1630  "a_key_no_engine_models": { "kept": true }
1631}
1632"#;
1633        let mut meta = PrefabMeta::from_json(text).unwrap();
1634        assert!(meta.is_tiled());
1635        assert_eq!(meta.size(), [31, 48, 93]);
1636        assert_eq!(meta.data_version(), Some(4671));
1637        assert_eq!(meta.license.as_ref().unwrap().spdx, "GPL-3.0-or-later");
1638        // The whole point of one document: a block the copy had lost is here.
1639        assert_eq!(meta.waterline_y, Some(12));
1640
1641        // The templates, in grid order, with their piece-local offsets.
1642        let templates = meta.templates();
1643        assert_eq!(templates.len(), 2);
1644        assert_eq!(templates[0].file, "notre-dame.x0y0z0.nbt");
1645        assert_eq!(templates[0].offset, [0, 0, 0]);
1646        assert_eq!(templates[1].id, "b");
1647        assert_eq!(templates[1].offset, [0, 0, 48]);
1648        assert_eq!(templates[1].size, [31, 48, 45]);
1649
1650        meta.lighting = Some(Lighting {
1651            profile: crate::registry::LightingProfile::Lit,
1652            measured_min_light: Some(6),
1653            measured: Some(String::new()),
1654            rationale: None,
1655            method: Some("static estimate".to_string()),
1656        });
1657        let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1658        let before: serde_json::Value = serde_json::from_str(text).unwrap();
1659        assert_eq!(after["license"], before["license"]);
1660        assert_eq!(after["structure_set"], before["structure_set"]);
1661        assert_eq!(after["anchors"], before["anchors"]);
1662        assert_eq!(after["waterline_y"], before["waterline_y"]);
1663        assert_eq!(after["lighting"]["profile"], "lit");
1664        assert!(
1665            after.get("structure").is_none(),
1666            "a tiled document must not grow an empty `structure` key: {after}"
1667        );
1668        // Reading is total here too: a key this version has never heard of
1669        // survives an edit rather than being deleted by the tool that made it.
1670        assert_eq!(
1671            after["a_key_no_engine_models"], before["a_key_no_engine_models"],
1672            "an unmodelled key must survive a read-modify-write"
1673        );
1674    }
1675
1676    /// A single-template piece is one template at the origin, so nothing that
1677    /// places blocks has to ask which packaging it was handed.
1678    #[test]
1679    fn a_single_template_piece_is_one_template_at_the_origin() {
1680        let text = r#"{
1681  "prefab_id": "prefab/x",
1682  "structure": { "file": "x.nbt", "id": "x", "size": [3, 4, 5], "data_version": 4671 }
1683}
1684"#;
1685        let meta = PrefabMeta::from_json(text).unwrap();
1686        assert!(!meta.is_tiled());
1687        assert_eq!(meta.size(), [3, 4, 5]);
1688        assert_eq!(
1689            meta.templates(),
1690            vec![PieceTemplate {
1691                id: "x",
1692                file: "x.nbt",
1693                offset: [0, 0, 0],
1694                size: [3, 4, 5],
1695            }]
1696        );
1697    }
1698
1699    /// "Which shape is this" has exactly two answers and no third: a document
1700    /// with neither block, and one with both, are refusals rather than a
1701    /// half-read document handed to a step that places some of its blocks.
1702    #[test]
1703    fn a_document_that_does_not_say_what_blocks_it_describes_is_refused() {
1704        let err = PrefabMeta::from_json(r#"{"prefab_id":"prefab/x"}"#).unwrap_err();
1705        assert!(err.contains("structure_set"), "{err}");
1706        assert!(err.contains("structure"), "{err}");
1707
1708        let both = r#"{
1709  "prefab_id": "prefab/x",
1710  "structure": { "file": "x.nbt", "id": "x", "size": [3, 3, 3], "data_version": 4671 },
1711  "structure_set": {
1712    "base": "x", "size": [3, 3, 3], "part_max": 48, "grid": [1, 1, 1],
1713    "data_version": 4671, "generator": "g",
1714    "parts": [ { "file": "x.x0y0z0.nbt", "id": "x0", "grid_index": [0,0,0], "offset": [0,0,0], "size": [3,3,3] } ]
1715  }
1716}
1717"#;
1718        let err = PrefabMeta::from_json(both).unwrap_err();
1719        assert!(err.contains("BOTH"), "{err}");
1720    }
1721
1722    /// A manifest that does not tile its own zone is refused **by the reader**,
1723    /// so every consumer of the document meets it at the same place — and none
1724    /// of them reassembles a building with a hole in it and reports success.
1725    #[test]
1726    fn a_manifest_that_does_not_tile_its_zone_is_refused_by_the_reader() {
1727        let text = r#"{
1728  "prefab_id": "prefab/holed",
1729  "structure_set": {
1730    "base": "holed", "size": [4, 4, 100], "part_max": 48, "grid": [1, 1, 1],
1731    "data_version": 4671, "generator": "g",
1732    "parts": [ { "file": "holed.x0y0z0.nbt", "id": "h0", "grid_index": [0,0,0], "offset": [0,0,0], "size": [4,4,48] } ]
1733  }
1734}
1735"#;
1736        let err = PrefabMeta::from_json(text).unwrap_err();
1737        assert!(err.contains("cover"), "{err}");
1738        assert!(err.contains("hole"), "{err}");
1739    }
1740
1741    /// A piece nothing has regenerated has no row, and the key is absent rather
1742    /// than `null` — `null` reads as "measured, and the answer is nothing".
1743    #[test]
1744    fn absent_optional_fields_are_omitted_not_nulled() {
1745        let meta = PrefabMeta::skeleton(
1746            "ingested",
1747            [3, 3, 3],
1748            4671,
1749            "delvec prefab (external admission)",
1750            License {
1751                source: "unknown".to_string(),
1752                spdx: "UNKNOWN".to_string(),
1753                note: String::new(),
1754                provenance: String::new(),
1755                generated_by: None,
1756            },
1757        );
1758        let json = meta.to_json();
1759        assert!(!json.contains("generated_by"), "{json}");
1760        assert!(!json.contains("null"), "{json}");
1761        assert!(json.contains("\"connectors\": []"), "{json}");
1762        assert_eq!(PrefabMeta::from_json(&json).unwrap(), meta);
1763    }
1764
1765    /// The role vocabulary is closed **by the type**, so a term this engine does
1766    /// not know is a parse failure naming the terms it does — not a string
1767    /// carried into a resolution that then silently never matches.
1768    ///
1769    /// The mechanism is worth pinning rather than assuming: [`Anchor`] carries
1770    /// a `#[serde(flatten)]` catch-all, which buffers the whole object, and a
1771    /// buffered unknown enum variant is easy to believe would land in `extra`
1772    /// instead of erroring. It does not.
1773    #[test]
1774    fn a_role_outside_the_vocabulary_is_refused_by_name() {
1775        let anchor: Anchor =
1776            serde_json::from_str(r#"{"pos": [1, 2, 3], "role": "entry"}"#).unwrap();
1777        assert_eq!(anchor.role, Some(AnchorRole::Entry));
1778        assert!(anchor.extra.is_empty(), "a modelled key is not `extra`");
1779
1780        let err = serde_json::from_str::<Anchor>(r#"{"pos": [1, 2, 3], "role": "spawn"}"#)
1781            .expect_err("`spawn` is a NAME, and was never a role");
1782        let msg = err.to_string();
1783        assert!(msg.contains("unknown variant"), "{msg}");
1784        for role in AnchorRole::ALL {
1785            assert!(
1786                msg.contains(role.as_str()),
1787                "the refusal lists `{role}`: {msg}"
1788            );
1789        }
1790    }
1791
1792    /// An anchor's `note` is a modelled key, so a piece that explains its own
1793    /// places is not a piece reporting `DW0543` six times a build.
1794    ///
1795    /// Both halves matter and only one is obvious. It must PARSE into the field
1796    /// (or `unknown_keys` reports it, which is the defect), and it must survive
1797    /// a round trip unchanged — a modelled key that serialises back differently
1798    /// would move every prefab document the first time anything rewrote one.
1799    #[test]
1800    fn an_anchor_note_is_modelled_and_is_not_an_unknown_key() {
1801        let text = r#"{
1802  "prefab_id": "prefab/x",
1803  "structure": { "file": "x.nbt", "id": "x", "size": [3, 3, 3], "data_version": 4671 },
1804  "anchors": { "anchor/a": { "pos": [1, 1, 1], "note": "where a wave forms up" } },
1805  "connectors": [],
1806  "lighting": { "profile": "unmeasured" }
1807}
1808"#;
1809        let meta = PrefabMeta::from_json(text).unwrap();
1810        assert_eq!(
1811            meta.anchors["anchor/a"].note.as_deref(),
1812            Some("where a wave forms up")
1813        );
1814        assert_eq!(
1815            meta.unknown_keys(),
1816            Vec::<(&str, &str)>::new(),
1817            "`note` is modelled, so nothing is left for `DW0543` to report"
1818        );
1819        assert_eq!(
1820            serde_json::from_str::<serde_json::Value>(&meta.to_json()).unwrap(),
1821            serde_json::from_str::<serde_json::Value>(text).unwrap()
1822        );
1823        // An anchor that says nothing writes no key: every piece admitted before
1824        // the field stays byte-for-byte what it was.
1825        let plain = serde_json::to_string(&Anchor::point([1, 2, 3], "north")).unwrap();
1826        assert!(!plain.contains("note"), "{plain}");
1827    }
1828
1829    /// An anchor that declares no role writes no key, which is what keeps every
1830    /// piece in the shipped library byte-for-byte what it was (spec-0046 §4.5).
1831    #[test]
1832    fn an_anchor_without_a_role_writes_no_role_key() {
1833        let plain = serde_json::to_string(&Anchor::point([1, 2, 3], "north")).unwrap();
1834        assert!(!plain.contains("role"), "{plain}");
1835        let declared =
1836            serde_json::to_string(&Anchor::point([1, 2, 3], "north").with_role(AnchorRole::Entry))
1837                .unwrap();
1838        assert!(declared.contains(r#""role":"entry""#), "{declared}");
1839    }
1840
1841    /// A role typed at a command line goes through the **same** closed table a
1842    /// role written into a document does, so the two cannot come to know
1843    /// different terms — and a term the engine does not know is refused with
1844    /// both the term and the vocabulary in the message.
1845    #[test]
1846    fn a_role_parsed_from_a_word_is_the_same_vocabulary_as_a_role_read_from_a_document() {
1847        for role in AnchorRole::ALL {
1848            assert_eq!(role.as_str().parse::<AnchorRole>(), Ok(*role));
1849        }
1850        let err = "dispenser".parse::<AnchorRole>().expect_err("not a term");
1851        assert!(err.contains("dispenser"), "{err}");
1852        for role in AnchorRole::ALL {
1853            assert!(err.contains(role.as_str()), "{err}");
1854        }
1855        // The name the compiler once matched is a name and has never been a
1856        // role, so it is refused here exactly as it is refused by `serde`.
1857        assert!("spawn".parse::<AnchorRole>().is_err());
1858    }
1859
1860    /// `edit_anchor`'s role is TRI-state, and the middle state is the one that
1861    /// matters: an edit that says nothing about the role keeps it. A tool that
1862    /// moved an anchor's cell would otherwise delete the piece's entry point,
1863    /// which is the silent deletion [`AnchorEdit`] exists to prevent.
1864    #[test]
1865    fn an_edit_that_says_nothing_about_the_role_keeps_it() {
1866        let mut meta = PrefabMeta::skeleton(
1867            "x",
1868            [3, 3, 3],
1869            4671,
1870            "test",
1871            License {
1872                source: "original".to_string(),
1873                spdx: "GPL-3.0-or-later".to_string(),
1874                note: String::new(),
1875                provenance: String::new(),
1876                generated_by: None,
1877            },
1878        );
1879        let place = |role| AnchorEdit {
1880            pos: Some([1, 1, 1]),
1881            role,
1882            ..AnchorEdit::default()
1883        };
1884
1885        meta.edit_anchor("anchor/a", place(Some(Some(AnchorRole::Entry))));
1886        assert_eq!(meta.anchors["anchor/a"].role, Some(AnchorRole::Entry));
1887
1888        // Silent: kept.
1889        meta.edit_anchor(
1890            "anchor/a",
1891            AnchorEdit {
1892                pos: Some([2, 1, 1]),
1893                ..AnchorEdit::default()
1894            },
1895        );
1896        assert_eq!(meta.anchors["anchor/a"].pos, Some([2, 1, 1]));
1897        assert_eq!(meta.anchors["anchor/a"].role, Some(AnchorRole::Entry));
1898
1899        // Said to have none: removed — the remedy `DW0804` prescribes.
1900        meta.edit_anchor("anchor/a", place(Some(None)));
1901        assert_eq!(meta.anchors["anchor/a"].role, None);
1902    }
1903}