Skip to main content

delvewright_dsl/
metrics.rs

1//! The metrics standard (spec-0049 §2) — pipeline stage 0.
2//!
3//! One machine-readable table, engine-owned data, in two halves whose epistemic
4//! status differs and is recorded per entry:
5//!
6//! * **Player metrics** — facts of pinned Minecraft Java 1.21.11. Not chosen,
7//!   so not calibratable: walking a level cannot make a player 0.7 blocks wide.
8//! * **Building metrics** — standards this project fixes. Every one carries
9//!   [`BuildingEntry::calibrated`], `false` until the metrics gym's walk
10//!   (spec-0049 §2.3) rules on it.
11//!
12//! # Why this module is in `delvewright-dsl`
13//!
14//! It is the crate every other one already reaches: `schem`, `grammar`, `admit`,
15//! `compiler` and `render` all resolve it. A metrics module that the navigation
16//! model imports but the render layer cannot would be one authority for some
17//! consumers and a copy for the rest, which is the shape this table exists to
18//! end. It is also the crate that owns [`crate::diagnostic`], and the stage-3
19//! and stage-4 documents whose names resolve into this table are validated here.
20//!
21//! # One authority, structurally
22//!
23//! The player half is not a second table that agrees with the navigation model —
24//! it **is** the navigation model's constants. `compiler::nav` imports
25//! [`MAX_AUTO_STEP_16`], [`MAX_JUMP_RISE_16`] and [`FULL_16`] from here;
26//! `compiler::crosshair`, `compiler::render_plan`, `compiler::view::viewer` and
27//! `compiler::combat` import the body constants they used to declare. There is
28//! one definition of each number in the workspace and the export re-serializes
29//! it, so a player metric cannot drift from the model that proves routes.
30//!
31//! What that replaced is worth recording, because it is the defect this table
32//! was written against rather than a hypothetical: the player eye height was
33//! declared four times (`compiler::render_plan`, `compiler::view::viewer`,
34//! `compiler::creator` in milli-blocks, `render::occupancy` in `f32`) and the
35//! body width twice, each a literal `0.6` or `1.62` with its own doc comment
36//! saying it was vanilla's. Nothing related them, so nothing could have gone red
37//! had one moved.
38//!
39//! # Provenance is recorded per entry
40//!
41//! [`Provenance`] says where a number came from, and the four values are
42//! deliberately not interchangeable: an [`Provenance::EngineConstant`] cannot
43//! drift because there is nothing to drift from, a [`Provenance::VanillaRule`] is
44//! a claim about the game this repository has **not** measured on a running
45//! server, a [`Provenance::Derived`] carries its arithmetic in its note, and a
46//! [`Provenance::Provisional`] is a seed for the gym and is not a standard yet.
47//! Dressing the last as one of the first three is the failure this field exists
48//! to make impossible to commit silently.
49//!
50//! # A provisional value cannot be consumed quietly
51//!
52//! [`BuildingEntry::value`] is the only way to read a building metric's number,
53//! and it takes `&mut `[`Reads`]. So a verdict that rests on an uncalibrated
54//! standard has, by construction, recorded that it did, and [`Metrics::notice`]
55//! turns that ledger into `DW0813`. The obligation lives in the signature, not
56//! in a line of documentation somebody has to remember.
57//!
58//! The residual, named rather than implied: a caller that constructs its own
59//! [`Reads`], reads through it and drops it has bypassed the notice. That is a
60//! deliberate act and not the omission the rule exists to catch — nothing
61//! *forgets* to thread a ledger it had to construct.
62//!
63//! On the campaign path it is closed rather than merely narrow.
64//! [`crate::validate::validate_campaign_with`] constructs **one** ledger and
65//! threads it through the stage-3 and stage-4 checks together, so every building
66//! metric either of them rests a verdict on lands in the ledger the notice
67//! reads. There is no second ledger for a read to disappear into.
68
69use std::collections::{BTreeMap, BTreeSet};
70
71use serde::Serialize;
72
73use crate::diagnostic::{Diagnostic, DwCode, ExitTier};
74
75/// `DW0812`: a document names a metrics entry the table does not define — a
76/// `size_class`, an `opening` or a `pitch` that resolves to nothing.
77pub const DW_METRIC_UNKNOWN: DwCode = DwCode::new("DW0812", ExitTier::Build);
78
79/// `DW0813`: a verdict rests on a standard the gym has not walked.
80///
81/// This rule asks the campaign for nothing at all. It reports a property of the
82/// ENGINE's own table — that some number a check just used is a seed rather than
83/// a standard — so no campaign could adopt its way out of it. It is a warning
84/// (exit 0) for the same reason: a provisional number is still a number,
85/// the check still refuses, and what the line adds is that the green rests on
86/// something nobody has walked.
87pub const DW_METRIC_PROVISIONAL: DwCode = DwCode::new("DW0813", ExitTier::Build).about_the_engine();
88
89// ---------------------------------------------------------------------------
90// The player half — the one definition of each constant in this workspace.
91// ---------------------------------------------------------------------------
92
93/// The table's own revision. Bumped whenever the exported JSON changes by a
94/// single byte **from a version that has merged**, which
95/// `crates/dsl/tests/metrics.rs` enforces against a committed digest: a consumer
96/// that pins a version is pinning values, and values that move under a fixed
97/// version are the drift the pin was bought to prevent.
98///
99/// The qualifier is a scope, not an escape hatch, and the difference is worth
100/// the sentence: the harm exists only where something could already have pinned
101/// the number, so a branch still authoring the version it introduces has nothing
102/// to break. It is also not a claim anybody makes about their own change —
103/// whether a version has merged is a fact of `origin/main`.
104///
105/// No document declares a metrics version and no surface is gated by one. What
106/// it needs is that the number cannot stand still while the table moves, and
107/// that is the digest test.
108pub const METRICS_VERSION: u32 = 2;
109
110/// Player collision-box width in blocks (`0.6 × 0.6 × 1.8` standing).
111pub const PLAYER_WIDTH: f64 = 0.6;
112
113/// Player collision-box height in blocks, standing.
114pub const PLAYER_HEIGHT: f64 = 1.8;
115
116/// Player collision-box height in blocks, crouched.
117pub const PLAYER_CROUCHED_HEIGHT: f64 = 1.5;
118
119/// Player eye height above the floor of the cell the body stands in.
120pub const PLAYER_EYE_HEIGHT: f64 = 1.62;
121
122/// Player maximum health, in half-heart damage points.
123pub const PLAYER_MAX_HEALTH: f64 = 20.0;
124
125/// The largest rise, in sixteenths of a block, a walker crosses **without
126/// jumping** — vanilla's player `maxUpStep` is 0.6 blocks, and 9/16 = 0.5625 is
127/// the largest sixteenth under it (10/16 = 0.625 already needs a jump). A rise
128/// within this budget needs no headroom above the *source* cell: the player walks
129/// straight up onto a slab or a path edge.
130pub const MAX_AUTO_STEP_16: i64 = 9;
131
132/// The largest rise a walker can reach **by jumping**, in sixteenths. A vanilla
133/// player's jump apex is ≈1.2522 blocks, so a surface 20/16 = 1.25 up is
134/// reachable and 21/16 = 1.3125 is not. This is the bound that makes the
135/// **1.5-block** slab-to-full-block step-up the impossible move it is.
136pub const MAX_JUMP_RISE_16: i64 = 20;
137
138/// A full block's height in sixteenths.
139pub const FULL_16: i64 = 16;
140
141// One number, one definition: a full block is 16/16 here and in the collision
142// table this feeds, and this refuses to compile the day the two drift. It is
143// asserted on this side because `blockshape` must compile knowing nothing about
144// the crate around it — the prefab generators are a separate workspace and reach
145// it through `prefab-invariants`, which re-exports it.
146const _: () = assert!(crate::blockshape::FULL_HEIGHT_16 as i64 == FULL_16);
147
148/// What a walker has to do to gain a given rise — the engine's ONE answer, and
149/// the reason it is here rather than in either walk.
150///
151/// Two walks ask this question of two different object classes. The compiler's
152/// navigation model asks it of an assembled world, where a floor has a real
153/// collision top and a body has a footprint; `delvec::schem`'s walk asks it of a
154/// box of cells with a passability answer for each, which is what a grammar
155/// expansion, a structure template read off disk and a reassembled zone all are.
156/// The rule belongs to neither walk: it is a fact about the pinned game's body,
157/// and this crate is where the three numbers it is written in terms of already
158/// live — so the rule lives beside them, and both walks read one answer.
159///
160/// The two callers still measure the rise differently, and that is a difference
161/// of **measurement**, never of rule: a box of cells with no collision heights
162/// can only read a rise as whole cells, which over-states every partial-block
163/// step and therefore only ever refuses. The rise is the input; this is the rule.
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum Rise {
166    /// Inside [`MAX_AUTO_STEP_16`]: the body walks straight up, never leaves the
167    /// ground, and needs no room over its head.
168    Walk,
169    /// Past the auto-step budget and inside [`MAX_JUMP_RISE_16`]: the body jumps,
170    /// so the cell its head sweeps through must be clear or it head-bonks.
171    Jump,
172    /// Past the jump apex. No player makes this step.
173    Beyond,
174}
175
176/// Classify a rise between two standing surfaces, in sixteenths. Negative and
177/// zero rises are [`Rise::Walk`] — stepping down and walking level ask nothing
178/// of the ceiling.
179#[must_use]
180pub fn classify_rise_16(rise_16: i64) -> Rise {
181    if rise_16 <= MAX_AUTO_STEP_16 {
182        Rise::Walk
183    } else if rise_16 <= MAX_JUMP_RISE_16 {
184        Rise::Jump
185    } else {
186        Rise::Beyond
187    }
188}
189
190/// Can a body make this step? `head_clear` answers *is the cell the head sweeps
191/// through clear at the source* — it is consulted only for a [`Rise::Jump`], so a
192/// caller may compute it lazily.
193///
194/// This predicate is the whole of the step rule. A walk that answers "can a body
195/// get from here to there" without going through it is a second opinion, and the
196/// two this engine had disagreed by exactly this term: one of them omitted the
197/// head sweep, so it connected a full-block rise under a two-course ceiling that
198/// the other refuses, and the gate that admits a prefab proved its **positive**
199/// reachability claim over the looser of the two.
200#[must_use]
201pub fn step_allowed(rise_16: i64, head_clear: impl FnOnce() -> bool) -> bool {
202    match classify_rise_16(rise_16) {
203        Rise::Walk => true,
204        Rise::Jump => head_clear(),
205        Rise::Beyond => false,
206    }
207}
208
209/// **Does the selector volume of the inclusive block box `lo..=hi` reach a body
210/// standing anywhere in `cell`?**
211///
212/// Vanilla's `@a[x=lo.x,dx=hi.x-lo.x,…]` builds the AABB `[lo, hi + 1]` on each
213/// axis — `EntitySelectorParser::createAabb` adds the block's own extent on the
214/// positive side, which is why `dx=0` still selects a whole block column — and
215/// keeps every entity whose own box **intersects** it. A standing body is
216/// [`PLAYER_WIDTH`] square about its position and [`PLAYER_HEIGHT`] tall from its
217/// feet, so a volume matches bodies whose FEET CELL it does not contain: half a
218/// width past every horizontal face, and a course below the bottom layer where
219/// only the head is inside.
220///
221/// This is the **generous** reading of that test — *could any body standing in
222/// this cell be matched* — because every caller uses it to keep a body OUT. A
223/// cell it clears is one no body standing in it can be selected from; a cell it
224/// reports is one some body standing in it can. Horizontally the whole cell of
225/// positions counts, since nothing makes a walking player stop at a cell centre
226/// and a pathfinder routinely parks one flush against a face.
227///
228/// The comparison is non-strict where vanilla's `AABB.intersects` is strict, so
229/// a body that exactly TOUCHES a face counts here and does not on the server.
230/// That is the same hair of generosity `bodyInVolume` takes in the harness, kept
231/// identical on purpose so the two sides cannot answer differently about a cell,
232/// and it costs one layer: a body whose feet sit exactly on the volume's ceiling
233/// is reported and is not really killed. Generous is the safe direction for a
234/// rule that keeps bodies out, and being the SAME on both sides matters more
235/// than the layer.
236///
237/// A consequence worth stating rather than leaving to be discovered: horizontally
238/// the shell is one cell wide for any body narrower than two blocks, so
239/// [`PLAYER_WIDTH`] does not decide it — the sweep over the cell's own positions
240/// does. [`PLAYER_HEIGHT`] does decide the vertical shell.
241///
242/// The engine's other reader of the same vanilla rule is
243/// `compiler::reach::ReachCompletion::possibly_completes_from`, which asks it of
244/// one stated body position rather than of a cell of them; the harness's is
245/// `bodyInVolume` in `harness/src/death-loop.ts`.
246///
247/// Here rather than in `delvec` for the reason [`step_allowed`] is here: the body
248/// is this table's, and a second copy of the arithmetic beside it is what this
249/// module exists to stop.
250#[must_use]
251pub fn selector_reaches_body_in_cell(lo: [i32; 3], hi: [i32; 3], cell: [i32; 3]) -> bool {
252    let half = PLAYER_WIDTH / 2.0;
253    // The extreme reach of a body standing anywhere in `cell`: horizontally every
254    // position of the cell, each carrying half a width past itself; vertically the
255    // feet on the cell floor and the head PLAYER_HEIGHT above them.
256    let body_lo = [
257        f64::from(cell[0]) - half,
258        f64::from(cell[1]),
259        f64::from(cell[2]) - half,
260    ];
261    let body_hi = [
262        f64::from(cell[0]) + 1.0 + half,
263        f64::from(cell[1]) + PLAYER_HEIGHT,
264        f64::from(cell[2]) + 1.0 + half,
265    ];
266    (0..3).all(|i| body_lo[i] <= f64::from(hi[i]) + 1.0 && body_hi[i] >= f64::from(lo[i]))
267}
268
269/// Ticks a jumping player spends off the ground, apex to landing included.
270pub const JUMP_AIRBORNE_TICKS: f64 = 12.0;
271
272/// Player walking speed on the flat, in blocks per second (not sprinting).
273pub const WALK_SPEED_BLOCKS_PER_SECOND: f64 = 4.317;
274
275/// Server ticks per second.
276pub const TICKS_PER_SECOND: f64 = 20.0;
277
278/// The fall distance in blocks below which vanilla deals no fall damage: damage
279/// is `ceil(distance − 3)` points, so a 3-block fall is free and a 4-block fall
280/// costs one.
281pub const FALL_DAMAGE_ONSET_BLOCKS: f64 = 3.0;
282
283/// Ticks a walking player spends crossing one block on the flat.
284///
285/// Derived rather than stored, because both operands are facts and nothing
286/// downstream decides a route on this number — it is the pacing denominator.
287#[must_use]
288pub fn walk_ticks_per_block() -> f64 {
289    TICKS_PER_SECOND / WALK_SPEED_BLOCKS_PER_SECOND
290}
291
292/// The largest fall an unarmoured player at full health survives, in blocks.
293///
294/// `ceil(d − 3) < 20` holds up to `d = 22`, which lands on one half-heart; 23
295/// blocks deals 20 and kills. Derived from [`FALL_DAMAGE_ONSET_BLOCKS`] and
296/// [`PLAYER_MAX_HEALTH`] so that moving either moves this, and it exists so the
297/// designed-drop policy beside it has a physical ceiling to be **tighter than**
298/// rather than a number chosen next to nothing.
299#[must_use]
300pub fn unarmoured_survivable_fall_blocks() -> f64 {
301    (FALL_DAMAGE_ONSET_BLOCKS + PLAYER_MAX_HEALTH - 1.0).floor()
302}
303
304/// Horizontal cells a standing body needs to pass: `ceil(0.6)`.
305#[must_use]
306pub fn passable_width_cells() -> u32 {
307    PLAYER_WIDTH.ceil() as u32
308}
309
310/// Vertical cells a standing body needs to pass: `ceil(1.8)`.
311///
312/// This is a **player** metric and the spec's building half listed it, which is
313/// the correction worth naming: the width and clearance at which a body can pass
314/// at all are functions of the collision box, so no walk can change them and
315/// `calibrated` would mean nothing on them. What the gym calibrates is the
316/// *designed* minimum — a way class's `min_width` and `min_clearance` — which is
317/// a comfort judgement and can never be chosen below this floor —
318/// [`Metrics::self_check`] is what holds it there, over every way class the
319/// table defines rather than over the two entries that used to stand alone.
320#[must_use]
321pub fn passable_clearance_cells() -> u32 {
322    PLAYER_HEIGHT.ceil() as u32
323}
324
325// ---------------------------------------------------------------------------
326// Entry shapes
327// ---------------------------------------------------------------------------
328
329/// Where a number came from. The four are not interchangeable — see the module
330/// docs.
331#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
332#[serde(rename_all = "kebab-case")]
333pub enum Provenance {
334    /// The number **is** a constant this module defines and the rest of the
335    /// workspace imports. One definition, so nothing to drift from.
336    EngineConstant,
337    /// A stated rule of pinned Minecraft Java 1.21.11 that no engine constant
338    /// held before this table, and that this repository has **not** measured on
339    /// a running server. The note names the rule so the claim is checkable.
340    VanillaRule,
341    /// Computed from other entries; the note carries the arithmetic.
342    Derived,
343    /// A seed for the metrics gym's calibration walk. Chosen, not established.
344    Provisional,
345}
346
347/// A named opening in the standard seam set, in cells.
348#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
349pub struct Opening {
350    /// Clear width, in cells.
351    pub width: u32,
352    /// Clear height, in cells.
353    pub height: u32,
354}
355
356/// A named stair-pitch standard: a rise:run pattern together with the vanilla
357/// blocks that realize it, and the per-step rise the realization actually
358/// presents to a walking body.
359#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
360pub struct Pitch {
361    /// Blocks of rise per `run` blocks of horizontal travel.
362    pub rise: u32,
363    /// Blocks of horizontal travel per `rise` blocks of rise.
364    pub run: u32,
365    /// The rise in sixteenths that one realized tread presents. A stair block
366    /// offers its lower half first, so a 1:1 stair run steps 8/16 twice per
367    /// block of rise rather than 16/16 once; a slab ramp steps 8/16 as well.
368    /// This is the number [`Metrics::self_check`] holds under the walk-up
369    /// budget, which is what makes "standard pitch" mean *walked*, not merely
370    /// *legal*.
371    pub step_16: i64,
372    /// The vanilla realization, named so the derivation above is checkable
373    /// against blocks rather than asserted.
374    pub realization: &'static str,
375}
376
377/// A rung of the size-class ladder — the vocabulary a layout-graph node declares
378/// and a site-plan box is judged against.
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
380pub struct SizeClass {
381    /// Smallest interior footprint, `[x, z]` in cells, inclusive.
382    pub min_footprint: [u32; 2],
383    /// Largest interior footprint, `[x, z]` in cells, inclusive.
384    pub max_footprint: [u32; 2],
385    /// Least interior clearance, in cells.
386    pub min_clearance: u32,
387    /// Nominal blocks of route a body walks crossing a place of this class —
388    /// the per-leg length the pacing projection sums over a critical path
389    /// (spec-0049 §3.3).
390    ///
391    /// The code that reads it is not named here on purpose: a `DW` number in a
392    /// source comment is a code as far as `tools/check-dw-codes.py` is
393    /// concerned, and one whose check lands two rounds from now has no catalog
394    /// row to match, so naming it early reds the docs job on a rule nothing has
395    /// written yet.
396    pub nominal_traverse_blocks: u32,
397}
398
399/// A **way class** — the vocabulary a layout-graph node declares for a place
400/// whose footprint is bounded in one axis and free in the other: a road, a
401/// causeway, a corridor, a duct (spec-0053 §3).
402///
403/// # Why it is a second kind of classification and not a rung
404///
405/// The size-class ladder classifies a place by both horizontal extents at once,
406/// and that is what it is for. A route has no second extent to classify: a cut
407/// ledge one body wide climbing a whole seaward face is 4 by 90, and for any
408/// rung to admit it that rung would have to span 4..90 on an axis — a class in
409/// which an alcove and an expanse are the same thing has stopped classifying.
410/// The failure is by KIND, not by margin, which is why no calibration of the
411/// ladder reaches it.
412///
413/// # What it bounds, and what it deliberately does not
414///
415/// A way class bounds the **cross-section** — the axis a body feels walking it
416/// — and says nothing whatever about the run. A route's length is per-campaign
417/// geometry, not a standard: a village lane, a canyon rim trail, a ship's
418/// gangway and a mine gallery are the same class of thing at four wildly
419/// different lengths, and a `max_length` here would be this month's map wearing
420/// a standard's clothes. The run is *measured*, into pacing, and is never
421/// compared against anything (spec-0053 §7).
422///
423/// The elongation demand a way-classed box must satisfy is therefore
424/// **structural rather than a constant**: the run must exceed
425/// [`Self::max_width`], which is exactly what a room cannot supply. A square box
426/// can never qualify, because its "run" equals its width and one number cannot
427/// both be `<= max_width` and exceed it. That is what makes "declare it a way to
428/// escape the ladder" refused by the object's own shape rather than by a rule
429/// the author could satisfy by choosing differently.
430#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
431pub struct WayClass {
432    /// Narrowest cross-section, in cells, inclusive. Never below the physical
433    /// passable width — [`Metrics::self_check`] holds it there.
434    pub min_width: u32,
435    /// Widest cross-section, in cells, inclusive. Doubles as the elongation
436    /// floor: a way-classed box's run must **exceed** this.
437    pub max_width: u32,
438    /// Least interior clearance, in cells.
439    pub min_clearance: u32,
440}
441
442/// The kit grid: the quantum box extents are multiples of, and the datum
443/// convention that fixes what a declared `y` means.
444#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
445pub struct Grid {
446    /// The footprint quantum `q`, in blocks.
447    pub quantum: u32,
448    /// The axes extents are quantized on. Vertical extent is not quantized:
449    /// storey heights are their own entries and a box's height follows them.
450    pub axes: [&'static str; 2],
451    /// What a box's declared datum `y` names. `floor-surface`: the walk plane is
452    /// at `y`, and whatever stands in the box later puts its own floor there.
453    pub datum: &'static str,
454}
455
456/// One entry's value. `untagged`, so the export reads as the number or object it
457/// is rather than as a wrapper a consumer has to unpick.
458#[derive(Debug, Clone, PartialEq, Serialize)]
459#[serde(untagged)]
460pub enum MetricValue {
461    /// A count of cells, blocks or ticks.
462    Count(u32),
463    /// A measurement that is not a whole number of anything.
464    Number(f64),
465    /// A yes/no fact.
466    Flag(bool),
467    /// A named seam opening.
468    Opening(Opening),
469    /// A named stair pitch.
470    Pitch(Pitch),
471    /// A rung of the size-class ladder.
472    SizeClass(SizeClass),
473    /// A way class — a route's cross-section.
474    WayClass(WayClass),
475    /// The kit grid.
476    Grid(Grid),
477}
478
479/// One player metric: a fact of the pinned game.
480#[derive(Debug, Clone, PartialEq, Serialize)]
481pub struct PlayerEntry {
482    /// The value.
483    pub value: MetricValue,
484    /// What the value counts (`blocks`, `sixteenths`, `ticks`, …), or `none`.
485    pub unit: &'static str,
486    /// Where the number came from.
487    pub provenance: Provenance,
488    /// One sentence: the constant this **is**, the vanilla rule it states, or
489    /// the arithmetic it was derived by.
490    pub note: &'static str,
491}
492
493/// One building metric: a standard this project fixes.
494///
495/// The value is deliberately not a public field. [`BuildingEntry::value`] is the
496/// only way to read it and it takes `&mut `[`Reads`], so nothing can rest a
497/// verdict on an uncalibrated standard without saying that it did.
498#[derive(Debug, Clone, PartialEq, Serialize)]
499pub struct BuildingEntry {
500    /// The entry's own key, carried so a read records itself without the caller
501    /// having to repeat the name it looked up under.
502    key: &'static str,
503    value: MetricValue,
504    /// What the value counts, or `none`.
505    pub unit: &'static str,
506    /// Where the number came from. Orthogonal to `calibrated`: a pitch's
507    /// geometry can be derived from vanilla blocks while the judgement that it
508    /// is *the* standard is still unwalked.
509    pub provenance: Provenance,
510    /// Whether the metrics gym's walk has ruled on this value. `false` on every
511    /// entry at this version.
512    pub calibrated: bool,
513    /// One sentence: what the number is for and what the gym is being asked to
514    /// decide about it.
515    pub note: &'static str,
516}
517
518impl BuildingEntry {
519    /// Read the value, recording the read.
520    ///
521    /// The `&mut `[`Reads`] is the whole mechanism: [`Metrics::notice`] reports
522    /// exactly the uncalibrated entries a run actually consumed, so `DW0813`
523    /// cannot be forgotten by a check that reads one and can never fire over a
524    /// standard nothing looked at.
525    #[must_use]
526    pub fn value(&self, reads: &mut Reads) -> &MetricValue {
527        reads.record(self);
528        &self.value
529    }
530
531    /// The value with no read recorded — for rendering the table, never for
532    /// deciding anything.
533    ///
534    /// Reachable only inside this crate, and used at exactly one site: the
535    /// export, which reports the table rather than resting a verdict on it. A
536    /// serialization is not a verdict, and counting it as one would put every
537    /// entry in every `DW0813` line and make the code mean nothing.
538    pub(crate) fn value_for_display(&self) -> &MetricValue {
539        &self.value
540    }
541
542    /// The entry's key.
543    #[must_use]
544    pub fn key(&self) -> &'static str {
545        self.key
546    }
547}
548
549/// The building metrics a run's verdicts have read.
550///
551/// Deterministic (ADR-0006): a `BTreeSet` of `&'static str`, so the order a
552/// `DW0813` line names them in is the table's own order and not the order the
553/// checks happened to run in.
554#[derive(Debug, Clone, Default, PartialEq, Eq)]
555pub struct Reads {
556    read: BTreeSet<&'static str>,
557    provisional: BTreeSet<&'static str>,
558}
559
560impl Reads {
561    /// A ledger nothing has read through yet.
562    #[must_use]
563    pub fn new() -> Self {
564        Self::default()
565    }
566
567    fn record(&mut self, entry: &BuildingEntry) {
568        self.read.insert(entry.key);
569        if !entry.calibrated {
570            self.provisional.insert(entry.key);
571        }
572    }
573
574    /// How many building metrics this run's verdicts read, and how many of those
575    /// the gym has not walked.
576    #[must_use]
577    pub fn binding(&self) -> ReadBinding {
578        ReadBinding {
579            read: self.read.len(),
580            provisional: self.provisional.len(),
581        }
582    }
583
584    /// The uncalibrated entries read, in table order.
585    #[must_use]
586    pub fn provisional(&self) -> Vec<&'static str> {
587        self.provisional.iter().copied().collect()
588    }
589
590    /// Every entry read, in table order.
591    ///
592    /// The metrics gym's coverage numerator: an entry the gym's construction
593    /// never read is an entry no bay was built from, so a walk of the gym cannot
594    /// rule on it. Taking it from the same ledger the reads are recorded in is
595    /// what stops the gym's own coverage claim being a list somebody maintains
596    /// beside the generator.
597    #[must_use]
598    pub fn read(&self) -> BTreeSet<&'static str> {
599        self.read.clone()
600    }
601}
602
603/// What a run's building-metric reads bound to.
604#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
605pub struct ReadBinding {
606    /// Building metrics read.
607    pub read: usize,
608    /// Of those, entries whose `calibrated` is false.
609    pub provisional: usize,
610}
611
612/// A name a document wrote that this table does not define — `DW0812`'s payload.
613///
614/// It carries the defined set as well as the bad name, because the author's next
615/// action is choosing a real one and a refusal that only says *no* sends them to
616/// read the compiler.
617#[derive(Debug, Clone, PartialEq, Eq)]
618pub struct UnknownMetric {
619    /// The kind of entry the document was naming (`size class`, `opening`, …).
620    pub kind: &'static str,
621    /// The same kind, plural — carried rather than derived, because three of the
622    /// six nouns end in a sibilant and `{kind}s` is wrong for them.
623    pub kind_plural: &'static str,
624    /// The name it wrote.
625    pub named: String,
626    /// Every name this table does define of that kind, in table order.
627    pub defined: Vec<&'static str>,
628}
629
630impl UnknownMetric {
631    /// The `DW0812` refusal, located by the caller.
632    #[must_use]
633    pub fn diagnostic(&self, stage: &str, path: &str) -> Diagnostic {
634        let defined = if self.defined.is_empty() {
635            "nothing".to_string()
636        } else {
637            self.defined.join(", ")
638        };
639        Diagnostic::error(
640            DW_METRIC_UNKNOWN,
641            stage,
642            path,
643            format!(
644                "the metrics table defines no {kind} called `{named}`. The table is \
645                 the single authority for this vocabulary, so a name it does not \
646                 define cannot compile and no check downstream has to cope with one. \
647                 Defined {plural}: {defined}. Run `delvec metrics` for the whole \
648                 table, including what each entry is for.",
649                kind = self.kind,
650                plural = self.kind_plural,
651                named = self.named,
652            ),
653        )
654    }
655}
656
657// ---------------------------------------------------------------------------
658// The table
659// ---------------------------------------------------------------------------
660
661/// The metrics standard, as exported and as read.
662#[derive(Debug, Clone, PartialEq, Serialize)]
663pub struct Metrics {
664    /// The table's revision.
665    pub metrics_version: u32,
666    /// The Minecraft version the player half states facts about.
667    pub mc_version: &'static str,
668    /// Facts of the pinned game, in key order.
669    pub player: BTreeMap<&'static str, PlayerEntry>,
670    /// Standards this project fixes, in key order.
671    pub building: BTreeMap<&'static str, BuildingEntry>,
672}
673
674/// Kinds of building entry a document can name, for [`Metrics::resolve`].
675#[derive(Debug, Clone, Copy, PartialEq, Eq)]
676pub enum MetricKind {
677    /// A seam opening (`opening.<name>`).
678    Opening,
679    /// A stair pitch (`pitch.<name>`).
680    Pitch,
681    /// A rung of the size-class ladder (`size-class.<name>`).
682    SizeClass,
683    /// A way class (`way-class.<name>`) — the second kind of place
684    /// classification (spec-0053 §3). A [`MetricKind`] rather than a lookup of
685    /// its own for the reason [`Metrics::resolve`] gives: this is a name a
686    /// DOCUMENT writes, so it goes through the one path from a name to an entry
687    /// and a name the table does not define is `DW0812` here exactly as it is
688    /// for a size class.
689    WayClass,
690    /// A storey height (`storey.<name>`).
691    Storey,
692    /// A pacing coefficient (`pacing.<name>`) — blocks of route per minute of
693    /// play. Named like the rest of the vocabulary rather than reached by a
694    /// second lookup, because [`Metrics::resolve`] is the ONE path from a name
695    /// to an entry and a coefficient read any other way would be a second
696    /// authority (spec-0049 §2.2). No campaign document names one; the pacing
697    /// projection does.
698    Pacing,
699}
700
701impl MetricKind {
702    /// The key prefix entries of this kind carry.
703    #[must_use]
704    pub fn prefix(self) -> &'static str {
705        match self {
706            MetricKind::Opening => "opening.",
707            MetricKind::Pitch => "pitch.",
708            MetricKind::SizeClass => "size-class.",
709            MetricKind::WayClass => "way-class.",
710            MetricKind::Storey => "storey.",
711            MetricKind::Pacing => "pacing.",
712        }
713    }
714
715    /// What the kind is called in a refusal, **plural**.
716    ///
717    /// A fact about the kind rather than an `s` appended where a message needed
718    /// one: three of the six nouns end in a sibilant, so `{noun}s` reads
719    /// `size classs`, `stair pitchs` and `way classs`. Written out here, a kind
720    /// added later cannot inherit that by default — it has to answer.
721    #[must_use]
722    pub fn plural(self) -> &'static str {
723        match self {
724            MetricKind::Opening => "seam openings",
725            MetricKind::Pitch => "stair pitches",
726            MetricKind::SizeClass => "size classes",
727            MetricKind::WayClass => "way classes",
728            MetricKind::Storey => "storey heights",
729            MetricKind::Pacing => "pacing coefficients",
730        }
731    }
732
733    /// What the kind is called in a refusal.
734    #[must_use]
735    pub fn noun(self) -> &'static str {
736        match self {
737            MetricKind::Opening => "seam opening",
738            MetricKind::Pitch => "stair pitch",
739            MetricKind::SizeClass => "size class",
740            MetricKind::WayClass => "way class",
741            MetricKind::Storey => "storey height",
742            MetricKind::Pacing => "pacing coefficient",
743        }
744    }
745}
746
747fn player(
748    value: MetricValue,
749    unit: &'static str,
750    provenance: Provenance,
751    note: &'static str,
752) -> PlayerEntry {
753    PlayerEntry {
754        value,
755        unit,
756        provenance,
757        note,
758    }
759}
760
761fn building(
762    key: &'static str,
763    value: MetricValue,
764    unit: &'static str,
765    provenance: Provenance,
766    note: &'static str,
767) -> (&'static str, BuildingEntry) {
768    (
769        key,
770        BuildingEntry {
771            key,
772            value,
773            unit,
774            provenance,
775            // Every entry lands uncalibrated. The gym walk flips it, one entry
776            // at a time, and that walk is the only thing that may.
777            calibrated: false,
778            note,
779        },
780    )
781}
782
783impl Metrics {
784    /// The table.
785    ///
786    /// Rebuilt per call rather than held in a `static`, because the values are a
787    /// handful of maps and a `static` would need interior mutability the moment
788    /// the gym's walk starts flipping `calibrated`. Deterministic by
789    /// construction: `BTreeMap`, no clock, no environment.
790    #[must_use]
791    pub fn table() -> Self {
792        let player_entries: Vec<(&'static str, PlayerEntry)> = vec![
793            (
794                "body.width",
795                player(
796                    MetricValue::Number(PLAYER_WIDTH),
797                    "blocks",
798                    Provenance::EngineConstant,
799                    "The standing collision box is 0.6 wide; `dsl::metrics::PLAYER_WIDTH` \
800                     is the definition `compiler::nav`'s entity dims table and \
801                     `compiler::crosshair` both import.",
802                ),
803            ),
804            (
805                "body.height",
806                player(
807                    MetricValue::Number(PLAYER_HEIGHT),
808                    "blocks",
809                    Provenance::EngineConstant,
810                    "The standing collision box is 1.8 tall; the same definition the \
811                     entity dims table reads for `minecraft:player`.",
812                ),
813            ),
814            (
815                "body.crouched-height",
816                player(
817                    MetricValue::Number(PLAYER_CROUCHED_HEIGHT),
818                    "blocks",
819                    Provenance::VanillaRule,
820                    "A sneaking player's collision box is 1.5 tall, which is what lets a \
821                     body pass under a cell a standing one cannot. No engine constant \
822                     held this before the table, and nothing in this workspace has \
823                     measured it on a running server.",
824                ),
825            ),
826            (
827                "body.eye-height",
828                player(
829                    MetricValue::Number(PLAYER_EYE_HEIGHT),
830                    "blocks",
831                    Provenance::EngineConstant,
832                    "The eye sits 1.62 above the floor of the cell the body stands in. \
833                     This is the definition the render plan, the viewer page and the \
834                     creator overlay all import, having each declared their own before.",
835                ),
836            ),
837            (
838                "body.max-health",
839                player(
840                    MetricValue::Number(PLAYER_MAX_HEALTH),
841                    "half-hearts",
842                    Provenance::EngineConstant,
843                    "Twenty points of health, the definition `compiler::combat` imports \
844                     for its winnability arithmetic.",
845                ),
846            ),
847            (
848                "step.walk-up",
849                player(
850                    MetricValue::Count(MAX_AUTO_STEP_16 as u32),
851                    "sixteenths",
852                    Provenance::EngineConstant,
853                    "The largest rise a walker crosses without jumping: vanilla's player \
854                     `maxUpStep` is 0.6 blocks and 9/16 is the largest sixteenth under \
855                     it. `compiler::nav` imports this as its step rule's walk-up budget.",
856                ),
857            ),
858            (
859                "step.jump-rise",
860                player(
861                    MetricValue::Count(MAX_JUMP_RISE_16 as u32),
862                    "sixteenths",
863                    Provenance::EngineConstant,
864                    "The largest rise a walker reaches by jumping: the apex is ≈1.2522 \
865                     blocks, so 20/16 is reachable and 21/16 is not. `compiler::nav` \
866                     imports this, and it is why a slab-to-full-block step-up of 1.5 is \
867                     the impossible move it is.",
868                ),
869            ),
870            (
871                "step.block",
872                player(
873                    MetricValue::Count(FULL_16 as u32),
874                    "sixteenths",
875                    Provenance::EngineConstant,
876                    "A full block in the sixteenths the step rule is denominated in, so \
877                     that no comparison in the navigation model is a float.",
878                ),
879            ),
880            (
881                "jump.airborne",
882                player(
883                    MetricValue::Number(JUMP_AIRBORNE_TICKS),
884                    "ticks",
885                    Provenance::VanillaRule,
886                    "A jump is airborne about twelve ticks, apex to landing. This was \
887                     prose in the navigation model's elevation-weight derivation and \
888                     nothing could read it; the table is where it becomes data.",
889                ),
890            ),
891            (
892                "walk.speed",
893                player(
894                    MetricValue::Number(WALK_SPEED_BLOCKS_PER_SECOND),
895                    "blocks/second",
896                    Provenance::VanillaRule,
897                    "A walking player covers 4.317 blocks a second on the flat; \
898                     sprinting is faster and is not the pacing basis, because a route \
899                     nobody has learnt is walked.",
900                ),
901            ),
902            (
903                "walk.ticks-per-block",
904                player(
905                    MetricValue::Number(walk_ticks_per_block()),
906                    "ticks",
907                    Provenance::Derived,
908                    "Twenty ticks a second over 4.317 blocks a second. Against the \
909                     twelve airborne ticks of a jump this is what makes a block of \
910                     climb cost about two and a half blocks of walking, which is where \
911                     the navigation model's elevation weight of two comes from.",
912                ),
913            ),
914            (
915                "fluid.passable",
916                player(
917                    MetricValue::Flag(false),
918                    "none",
919                    Provenance::VanillaRule,
920                    "Water and lava are impassable to every proof in this engine and are \
921                     never floor either: a body cannot stand on a fluid surface, so the \
922                     two sets are disjoint and both gate standability. Marked as a rule \
923                     rather than an engine constant deliberately — the navigation model \
924                     encodes this as the SHAPE of its occupancy sets and not as a shared \
925                     `const`, so there is no single definition for this row to be, and \
926                     claiming otherwise would be the overclaim the provenance field \
927                     exists to prevent.",
928                ),
929            ),
930            (
931                "fall.damage-onset",
932                player(
933                    MetricValue::Number(FALL_DAMAGE_ONSET_BLOCKS),
934                    "blocks",
935                    Provenance::VanillaRule,
936                    "Fall damage is `ceil(distance − 3)` points, so a three-block fall is \
937                     free and a four-block fall costs one. Stated from the vanilla \
938                     damage rule; this repository has not measured it on a running \
939                     server.",
940                ),
941            ),
942            (
943                "fall.unarmoured-survivable",
944                player(
945                    MetricValue::Number(unarmoured_survivable_fall_blocks()),
946                    "blocks",
947                    Provenance::Derived,
948                    "`ceil(distance − 3) < 20` holds up to 22 blocks, which lands a \
949                     full-health unarmoured body on one half-heart; 23 deals twenty and \
950                     kills. The survivable ceiling is a function of health and armour, \
951                     and this is its unarmoured, full-health case — the physical bound \
952                     the designed-drop policy is deliberately tighter than.",
953                ),
954            ),
955            (
956                "passable.width",
957                player(
958                    MetricValue::Count(passable_width_cells()),
959                    "cells",
960                    Provenance::Derived,
961                    "`ceil(0.6)`: one cell is the narrowest a standing body fits \
962                     through. This is a fact, not a standard — no walk can change it, \
963                     and it is the floor the designed corridor minimum may never be \
964                     chosen below.",
965                ),
966            ),
967            (
968                "passable.clearance",
969                player(
970                    MetricValue::Count(passable_clearance_cells()),
971                    "cells",
972                    Provenance::Derived,
973                    "`ceil(1.8)`: two cells is the lowest a standing body passes under. \
974                     Like the width beside it this is a fact rather than a standard, \
975                     which is why neither carries a calibration flag.",
976                ),
977            ),
978        ];
979
980        let building_entries: Vec<(&'static str, BuildingEntry)> = vec![
981            building(
982                "grid",
983                MetricValue::Grid(Grid {
984                    quantum: 4,
985                    axes: ["x", "z"],
986                    datum: "floor-surface",
987                }),
988                "blocks",
989                Provenance::Provisional,
990                "The footprint quantum every site-plan box's horizontal extents are \
991                 multiples of, and the datum convention: a box's floor SURFACE is at \
992                 its declared y, and whatever stands in the box later puts its walk \
993                 plane there. Four is a seed and nothing in the existing piece library \
994                 argues for it — the cave tileset is odd on every axis and the keep \
995                 tileset is even but not quartered — so what the gym is being asked is \
996                 whether a quantum this fine buys anything a coarser one would not.",
997            ),
998            building(
999                "way-class.corridor",
1000                MetricValue::WayClass(WayClass {
1001                    min_width: 2,
1002                    max_width: 4,
1003                    min_clearance: 3,
1004                }),
1005                "cells",
1006                Provenance::Provisional,
1007                "The narrow way: a passage, a duct, a gallery cut through rock. Its \
1008                 `min_width` and `min_clearance` ARE the two numbers this table used to \
1009                 publish as `corridor.min-width` and `corridor.min-clearance` — one \
1010                 cell is passable and reads as a crawlspace, two lets two bodies pass, \
1011                 and two blocks of clearance puts the ceiling on the walker's head — and \
1012                 they are fields here rather than entries of their own so that there is \
1013                 one authority for the narrow way rather than a class beside two loose \
1014                 numbers nothing could spell. The gym walks widths one, two and three \
1015                 and clearances two, three and four. It is also asked a question that \
1016                 could not be posed while these numbers were unreachable: the kit \
1017                 quantum beside them is 4 and every box extent is a multiple of it, so \
1018                 the narrowest way any plan can currently DRAW is four cells, and the \
1019                 walk decides whether the floor moves up or the quantum moves down.",
1020            ),
1021            building(
1022                "way-class.road",
1023                MetricValue::WayClass(WayClass {
1024                    min_width: 4,
1025                    max_width: 16,
1026                    min_clearance: 6,
1027                }),
1028                "cells",
1029                Provenance::Provisional,
1030                "The broad way: a village lane, a causeway, a quay, a ledge cut across a \
1031                 cliff face. Wide enough that a party walks it abreast and something can \
1032                 come the other way, which is the difference from the corridor beside it \
1033                 and is what the walk is being asked to place. The clearance seed is \
1034                 higher than the corridor's because a way this wide reads as roofless \
1035                 even when it is not, and a low ceiling over a broad floor is the one \
1036                 combination that reads as a mistake.",
1037            ),
1038            building(
1039                "opening.door",
1040                MetricValue::Opening(Opening {
1041                    width: 1,
1042                    height: 2,
1043                }),
1044                "cells",
1045                Provenance::Provisional,
1046                "The narrow seam: one body at a time, the size of a vanilla door. Seeded \
1047                 at the smallest opening a standing body passes, so the gym is deciding \
1048                 whether the tightest legal seam is one anybody wants to walk.",
1049            ),
1050            building(
1051                "opening.arch",
1052                MetricValue::Opening(Opening {
1053                    width: 2,
1054                    height: 3,
1055                }),
1056                "cells",
1057                Provenance::Provisional,
1058                "The ordinary seam between two interior places: two abreast, headroom \
1059                 over both.",
1060            ),
1061            building(
1062                "opening.passage",
1063                MetricValue::Opening(Opening {
1064                    width: 3,
1065                    height: 3,
1066                }),
1067                "cells",
1068                Provenance::Derived,
1069                "The three-by-three doorway the existing jigsaw socket conventions \
1070                 already standardize on — `cave:socket` and `tk:socket` are both this \
1071                 opening, so the prefab library has been built against it for as long \
1072                 as it has existed. Derived from that convention rather than chosen \
1073                 here, and still uncalibrated: what the gym decides is whether the \
1074                 convention is right, not what it is.",
1075            ),
1076            building(
1077                "opening.gateway",
1078                MetricValue::Opening(Opening {
1079                    width: 5,
1080                    height: 5,
1081                }),
1082                "cells",
1083                Provenance::Provisional,
1084                "The broad seam a thing of scenery scale passes: a cart, a barge, a \
1085                 processional. Seeded wide enough to read as an event from inside the \
1086                 place it opens onto, which is the judgement the walk is for.",
1087            ),
1088            building(
1089                "pitch.stair",
1090                MetricValue::Pitch(Pitch {
1091                    rise: 1,
1092                    run: 1,
1093                    step_16: 8,
1094                    realization: "minecraft:*_stairs",
1095                }),
1096                "none",
1097                Provenance::Derived,
1098                "One block of rise per block of run, realized in stair blocks. The \
1099                 geometry is vanilla's: a stair offers its lower half first, so the \
1100                 body walks two eight-sixteenth steps per block of rise and never \
1101                 jumps. What is uncalibrated is the comfort judgement — whether a climb \
1102                 this steep is one a player wants to make repeatedly.",
1103            ),
1104            building(
1105                "pitch.ramp",
1106                MetricValue::Pitch(Pitch {
1107                    rise: 1,
1108                    run: 2,
1109                    step_16: 8,
1110                    realization: "minecraft:*_slab + full block",
1111                }),
1112                "none",
1113                Provenance::Derived,
1114                "One block of rise per two of run, realized as a bottom slab then a full \
1115                 block. Same eight-sixteenth tread as the stair and half the pitch, so \
1116                 it is the gentle standard; the run it costs is what the gym weighs it \
1117                 on.",
1118            ),
1119            building(
1120                "storey.low",
1121                MetricValue::Count(5),
1122                "blocks",
1123                Provenance::Derived,
1124                "Floor course, three cells of interior clearance, ceiling course. Taken \
1125                 from the existing cave tileset, every passage and room of which is five \
1126                 blocks tall, so this is the storey the shipped library already has \
1127                 rather than a number invented here.",
1128            ),
1129            building(
1130                "storey.standard",
1131                MetricValue::Count(8),
1132                "blocks",
1133                Provenance::Provisional,
1134                "The storey an interior room of consequence gets: six cells of clearance \
1135                 between courses. A seed, and the walk is what says whether a room this \
1136                 tall reads as generous or merely as far away.",
1137            ),
1138            building(
1139                "storey.hall",
1140                MetricValue::Count(14),
1141                "blocks",
1142                Provenance::Provisional,
1143                "The storey a hall gets, where the height itself is the effect. The seed \
1144                 is deliberately at the point where volume starts costing walking time \
1145                 for nothing, because that is the trade the walk has to judge.",
1146            ),
1147            building(
1148                "size-class.alcove",
1149                MetricValue::SizeClass(SizeClass {
1150                    min_footprint: [4, 4],
1151                    max_footprint: [8, 8],
1152                    min_clearance: 3,
1153                    nominal_traverse_blocks: 6,
1154                }),
1155                "cells",
1156                Provenance::Provisional,
1157                "A place a body stands in rather than crosses: a shrine, a landing, a \
1158                 cell. The smallest rung of the ladder, and the whole ladder's bounds \
1159                 are seeds — what the walk fixes is where one class stops feeling like \
1160                 the next.",
1161            ),
1162            building(
1163                "size-class.room",
1164                MetricValue::SizeClass(SizeClass {
1165                    min_footprint: [8, 8],
1166                    max_footprint: [16, 16],
1167                    min_clearance: 4,
1168                    nominal_traverse_blocks: 12,
1169                }),
1170                "cells",
1171                Provenance::Provisional,
1172                "A place with a purpose and something in it: a guardroom, a chapel, a \
1173                 workshop.",
1174            ),
1175            building(
1176                "size-class.hall",
1177                MetricValue::SizeClass(SizeClass {
1178                    min_footprint: [16, 16],
1179                    max_footprint: [32, 32],
1180                    min_clearance: 8,
1181                    nominal_traverse_blocks: 24,
1182                }),
1183                "cells",
1184                Provenance::Provisional,
1185                "A place a fight or a crowd fits in, and the smallest rung whose height \
1186                 is doing work of its own.",
1187            ),
1188            building(
1189                "size-class.arena",
1190                MetricValue::SizeClass(SizeClass {
1191                    min_footprint: [32, 32],
1192                    max_footprint: [64, 64],
1193                    min_clearance: 12,
1194                    nominal_traverse_blocks: 48,
1195                }),
1196                "cells",
1197                Provenance::Provisional,
1198                "A place built around one encounter, with room to retreat and re-approach.",
1199            ),
1200            building(
1201                "size-class.expanse",
1202                MetricValue::SizeClass(SizeClass {
1203                    min_footprint: [64, 64],
1204                    max_footprint: [128, 128],
1205                    min_clearance: 16,
1206                    nominal_traverse_blocks: 96,
1207                }),
1208                "cells",
1209                Provenance::Provisional,
1210                "A shore, a valley floor, a cavern — a place whose job is that crossing \
1211                 it takes time. The rung most at risk of being a big empty room, which \
1212                 is what the walk is watching for.",
1213            ),
1214            building(
1215                "drop.max-designed-rise",
1216                MetricValue::Count(5),
1217                "blocks",
1218                Provenance::Provisional,
1219                "The deepest fall a designed one-way drop edge may declare. A policy \
1220                 cap, not a physical one: the unarmoured survivable fall beside it in \
1221                 the player half is 22 blocks, and this is far tighter on purpose, \
1222                 because a drop is a topology decision and should not also be a health \
1223                 decision. Five costs two of twenty at full health, which is the seed \
1224                 the walk argues with.",
1225            ),
1226            building(
1227                "pacing.route-blocks-per-minute",
1228                MetricValue::Count(60),
1229                "blocks/minute",
1230                Provenance::Provisional,
1231                "Blocks of route a party gets through per minute of play, once looking, \
1232                 fighting and backtracking are in it. Carried with NO THRESHOLD \
1233                 anywhere until the first walked blockout and the first full playtest \
1234                 calibrate it: a threshold on a number this uncertain would be defending \
1235                 nothing. Its upper bound is the pure-walk figure beside it, which no \
1236                 party achieves.",
1237            ),
1238            building(
1239                "pacing.walk-only-blocks-per-minute",
1240                MetricValue::Count((WALK_SPEED_BLOCKS_PER_SECOND * 60.0) as u32),
1241                "blocks/minute",
1242                Provenance::Derived,
1243                "Walking speed times sixty: what a body covers doing nothing but \
1244                 walking in a straight line. It exists so the route coefficient above \
1245                 has a ceiling that is a fact rather than another guess, and so the \
1246                 ratio between them is the thing the playtest actually measures.",
1247            ),
1248        ];
1249
1250        Metrics {
1251            metrics_version: METRICS_VERSION,
1252            mc_version: crate::blocks::MC_VERSION,
1253            player: player_entries.into_iter().collect(),
1254            building: building_entries.into_iter().collect(),
1255        }
1256    }
1257
1258    /// Resolve a name a **document** wrote to its building entry.
1259    ///
1260    /// This is the **only** path from an authored name to an entry, and it is
1261    /// what makes the table the single authority rather than a suggestion: a
1262    /// name it does not define cannot be resolved, so it cannot compile, so no
1263    /// check downstream ever meets one.
1264    ///
1265    /// The other half of that guarantee is that no key string is spelled outside
1266    /// this module. The entries no document names — the kit grid, the designed-
1267    /// drop cap — are reached through the accessors below rather than by looking
1268    /// the key up in [`Metrics::building`], which is public so that a *reporter*
1269    /// can walk the whole table (`delvec metrics` counts it; the tests iterate
1270    /// it). Reporting is not resolution: a caller that walks every entry cannot
1271    /// name a wrong one, and a caller that wants ONE entry has an accessor and
1272    /// therefore no reason to type a key.
1273    ///
1274    /// # Errors
1275    ///
1276    /// [`UnknownMetric`], which the caller turns into `DW0812` with its own
1277    /// stage and path.
1278    pub fn resolve(&self, kind: MetricKind, named: &str) -> Result<&BuildingEntry, UnknownMetric> {
1279        let key = format!("{}{}", kind.prefix(), named);
1280        self.building
1281            .get(key.as_str())
1282            .ok_or_else(|| UnknownMetric {
1283                kind: kind.noun(),
1284                kind_plural: kind.plural(),
1285                named: named.to_string(),
1286                defined: self.names_of(kind),
1287            })
1288    }
1289
1290    /// The kit grid — the quantum a site-plan box's footprint is a multiple of,
1291    /// and the datum convention that fixes what a declared floor `y` means.
1292    ///
1293    /// One of the entries **no document names**: an author writes a number, not
1294    /// the word `grid`, so it has no place in [`Metrics::resolve`]'s naming
1295    /// vocabulary and would need a [`MetricKind`] whose prefix is the empty
1296    /// string — which would make `names_of` return the whole table. An accessor
1297    /// instead, so the key string still lives here and nowhere else.
1298    ///
1299    /// `None` only if the table stopped defining it, which
1300    /// [`Metrics::self_check`] reports as an internal error.
1301    #[must_use]
1302    pub fn grid(&self, reads: &mut Reads) -> Option<Grid> {
1303        match self.building.get("grid")?.value(reads) {
1304            MetricValue::Grid(g) => Some(*g),
1305            _ => None,
1306        }
1307    }
1308
1309    /// The deepest fall a **designed** one-way drop may declare, in blocks — a
1310    /// policy cap, deliberately tighter than the survivability fact in the
1311    /// player half. See [`Metrics::grid`] for why this is an accessor.
1312    #[must_use]
1313    pub fn max_designed_drop_blocks(&self, reads: &mut Reads) -> Option<u32> {
1314        match self.building.get("drop.max-designed-rise")?.value(reads) {
1315            MetricValue::Count(n) => Some(*n),
1316            _ => None,
1317        }
1318    }
1319
1320    /// The **widest** standard opening in the table, in cells — the floor a
1321    /// contact seam's span must exceed (spec-0053 §4).
1322    ///
1323    /// Derived from the table rather than seeded, and that is the whole of why
1324    /// the floor is honest: anything at or under this width **could have been a
1325    /// portal**, so a doorway declared a contact to dodge the standard set is
1326    /// refused by its own width. A seeded floor would be a number an author
1327    /// could argue with; this one is a consequence of the standard set, and it
1328    /// moves when the standard set moves.
1329    ///
1330    /// It walks every opening rather than naming one, so a broader standard
1331    /// landing tomorrow raises the floor with no edit here — the failure mode a
1332    /// hand-named `opening.gateway` would have is that the floor silently stops
1333    /// being the broadest the day a broader one is added.
1334    ///
1335    /// `None` only if the table defines no opening at all, which
1336    /// [`Metrics::self_check`] reports as an internal error.
1337    #[must_use]
1338    pub fn broadest_opening_width(&self, reads: &mut Reads) -> Option<u32> {
1339        let mut widest: Option<u32> = None;
1340        for name in self.names_of(MetricKind::Opening) {
1341            let Ok(entry) = self.resolve(MetricKind::Opening, name) else {
1342                continue;
1343            };
1344            if let MetricValue::Opening(o) = entry.value(reads) {
1345                widest = Some(widest.map_or(o.width, |w: u32| w.max(o.width)));
1346            }
1347        }
1348        widest
1349    }
1350
1351    /// Every name defined for a kind, in table order.
1352    #[must_use]
1353    pub fn names_of(&self, kind: MetricKind) -> Vec<&'static str> {
1354        self.building
1355            .keys()
1356            .filter_map(|k| k.strip_prefix(kind.prefix()))
1357            .collect()
1358    }
1359
1360    /// The `DW0813` notice for a run, or `None` when no verdict rested on an
1361    /// unwalked standard.
1362    ///
1363    /// `None` at a zero binding is the calibrated end state and not a vacuity:
1364    /// the line's job is to say that a green rests on a seed, and once the gym
1365    /// has walked every entry a run reads there is nothing left for it to say.
1366    /// The distinguishable failure — a run that read NOTHING — is reported by
1367    /// [`Reads::binding`], which every caller states whether or not this returns
1368    /// a line.
1369    #[must_use]
1370    pub fn notice(&self, reads: &Reads, stage: &str) -> Option<Diagnostic> {
1371        let provisional = reads.provisional();
1372        if provisional.is_empty() {
1373            return None;
1374        }
1375        let binding = reads.binding();
1376        Some(Diagnostic::warning(
1377            DW_METRIC_PROVISIONAL,
1378            stage,
1379            "",
1380            format!(
1381                "{n} of the {read} building metric(s) this run read are provisional — the \
1382                 metrics gym has not walked them: {names}. The checks still ran and still \
1383                 refuse; what is unproven is the number they refused against.",
1384                n = binding.provisional,
1385                read = binding.read,
1386                names = provisional.join(", "),
1387            ),
1388        ))
1389    }
1390
1391    /// Check the table against itself and against the player half.
1392    ///
1393    /// These are verdicts, and they read building metrics through a [`Reads`], so
1394    /// they are also what gives `DW0813` a live binding at this version: `delvec
1395    /// metrics` runs them, and the notice names the seeds the consistency verdict
1396    /// rested on. They are the reason the mechanism is demonstrable now rather
1397    /// than at the round that adds the documents.
1398    ///
1399    /// A violation is an **internal error**, not a diagnostic: the table is
1400    /// engine data, so an inconsistent one is a defect in this file and not in
1401    /// anybody's campaign, and there is no author to address a refusal to.
1402    #[must_use]
1403    pub fn self_check(&self) -> SelfCheck {
1404        let mut reads = Reads::new();
1405        let mut failures: Vec<String> = Vec::new();
1406        let mut checked = 0usize;
1407
1408        let floor_w = u64::from(passable_width_cells());
1409        let floor_h = u64::from(passable_clearance_cells());
1410
1411        // A place that is a route must be spellable at all. Zero way classes is
1412        // the state spec-0053 was written to end — the metrics gym reported
1413        // `corridor.min-width` and `corridor.min-clearance` unreachable because
1414        // no document could name a place that is not a box with a size class —
1415        // so an empty way vocabulary is an internal error rather than a table
1416        // that happens to be short one kind.
1417        checked += 1;
1418        if self.names_of(MetricKind::WayClass).is_empty() {
1419            failures.push(
1420                "the table defines no way class, so no document can state a place that is \
1421                 a route"
1422                    .to_string(),
1423            );
1424        }
1425
1426        // The contact floor is derived from the standard opening set (spec-0053
1427        // §4), so an empty set would make that floor `None` and the refusal it
1428        // is the floor for unable to separate a doorway from a front.
1429        checked += 1;
1430        if self.broadest_opening_width(&mut reads).is_none() {
1431            failures.push(
1432                "the table defines no standard opening, so a contact seam's width floor — \
1433                 the width a front must exceed to be a front rather than a door — cannot \
1434                 be derived"
1435                    .to_string(),
1436            );
1437        }
1438
1439        let quantum = match self.grid(&mut reads) {
1440            Some(g) => {
1441                checked += 1;
1442                if g.quantum == 0 {
1443                    failures.push("the kit grid's quantum is zero".to_string());
1444                }
1445                g.quantum
1446            }
1447            None => {
1448                failures.push("the table defines no kit `grid`".to_string());
1449                1
1450            }
1451        };
1452
1453        for (key, entry) in &self.building {
1454            match entry.value(&mut reads) {
1455                MetricValue::Opening(o) => {
1456                    checked += 1;
1457                    if u64::from(o.width) < floor_w || u64::from(o.height) < floor_h {
1458                        failures.push(format!(
1459                            "`{key}` is {}×{}, which no standing body passes ({floor_w}×{floor_h} \
1460                             is the floor)",
1461                            o.width, o.height
1462                        ));
1463                    }
1464                }
1465                MetricValue::Pitch(p) => {
1466                    checked += 1;
1467                    if p.step_16 > MAX_AUTO_STEP_16 {
1468                        failures.push(format!(
1469                            "`{key}` presents a tread of {}/16, over the {MAX_AUTO_STEP_16}/16 \
1470                             walk-up budget, so it is climbed by jumping and is not a standard \
1471                             pitch",
1472                            p.step_16
1473                        ));
1474                    }
1475                    if p.rise == 0 || p.run == 0 {
1476                        failures.push(format!("`{key}` has a zero rise or run"));
1477                    }
1478                }
1479                MetricValue::SizeClass(c) => {
1480                    checked += 1;
1481                    for (axis, lo, hi) in [
1482                        ("x", c.min_footprint[0], c.max_footprint[0]),
1483                        ("z", c.min_footprint[1], c.max_footprint[1]),
1484                    ] {
1485                        if lo > hi {
1486                            failures
1487                                .push(format!("`{key}` has a {axis} minimum above its maximum"));
1488                        }
1489                        if lo % quantum != 0 || hi % quantum != 0 {
1490                            failures.push(format!(
1491                                "`{key}` bounds its {axis} footprint at {lo}..{hi}, which is not \
1492                                 on the kit grid's quantum of {quantum}"
1493                            ));
1494                        }
1495                    }
1496                    if u64::from(c.min_clearance) < floor_h {
1497                        failures.push(format!(
1498                            "`{key}` allows a clearance of {}, under the passable floor of \
1499                             {floor_h}",
1500                            c.min_clearance
1501                        ));
1502                    }
1503                    if c.nominal_traverse_blocks == 0 {
1504                        failures.push(format!("`{key}` has a nominal traverse of zero"));
1505                    }
1506                }
1507                MetricValue::WayClass(w) => {
1508                    checked += 1;
1509                    // The two floors the freestanding `corridor.min-*` entries
1510                    // used to be checked at, re-asserted here against every way
1511                    // class rather than against the one that inherited them: a
1512                    // designed minimum is a comfort judgement and a standard
1513                    // under the physical passable size would be a standard
1514                    // nothing can use, which is true of a road exactly as it is
1515                    // of a corridor.
1516                    if u64::from(w.min_width) < floor_w {
1517                        failures.push(format!(
1518                            "`{key}` allows a width of {}, under the `passable.width` floor of \
1519                             {floor_w}",
1520                            w.min_width
1521                        ));
1522                    }
1523                    if u64::from(w.min_clearance) < floor_h {
1524                        failures.push(format!(
1525                            "`{key}` allows a clearance of {}, under the `passable.clearance` \
1526                             floor of {floor_h}",
1527                            w.min_clearance
1528                        ));
1529                    }
1530                    if w.min_width > w.max_width {
1531                        failures.push(format!(
1532                            "`{key}` bounds its width at {}..{}, a minimum above its maximum",
1533                            w.min_width, w.max_width
1534                        ));
1535                    }
1536                    // `max_width` is the elongation floor as well as the widest
1537                    // cross-section, and a box's horizontal extents are
1538                    // multiples of the kit quantum (`DW0825`). A `max_width` off
1539                    // the quantum is therefore a bound no plan can draw a way
1540                    // AT, which makes the widest member of the class
1541                    // uninstantiable and the gym unable to rule on it. The
1542                    // narrow bound is deliberately NOT held to the quantum: the
1543                    // corridor's inherited floor of 2 sits under a quantum of 4
1544                    // and which of those two provisional numbers moves is the
1545                    // walk's to decide, not this file's.
1546                    if !w.max_width.is_multiple_of(quantum) {
1547                        failures.push(format!(
1548                            "`{key}` bounds its width at {}, which is not on the kit grid's \
1549                             quantum of {quantum}, so no box can be drawn at the widest member \
1550                             of the class",
1551                            w.max_width
1552                        ));
1553                    }
1554                }
1555                _ => {}
1556            }
1557        }
1558
1559        for (key, floor) in [
1560            ("storey.low", floor_h + 2),
1561            ("storey.standard", floor_h + 2),
1562            ("storey.hall", floor_h + 2),
1563        ] {
1564            let Some(entry) = self.building.get(key) else {
1565                failures.push(format!("the table defines no `{key}`"));
1566                continue;
1567            };
1568            checked += 1;
1569            if let MetricValue::Count(n) = entry.value(&mut reads)
1570                && u64::from(*n) < floor
1571            {
1572                failures.push(format!(
1573                    "`{key}` is {n} blocks, which leaves no passable interior between a \
1574                     floor course and a ceiling course ({floor} is the floor)"
1575                ));
1576            }
1577        }
1578
1579        // The policy cap is deliberately tighter than the physical one. A cap
1580        // that reached the survivability ceiling would not be a policy.
1581        if let Some(n) = self.max_designed_drop_blocks(&mut reads) {
1582            checked += 1;
1583            let physical = unarmoured_survivable_fall_blocks();
1584            if f64::from(n) >= physical {
1585                failures.push(format!(
1586                    "`drop.max-designed-rise` is {n} blocks, at or past the unarmoured \
1587                     survivable fall of {physical}, so it is not a policy cap at all"
1588                ));
1589            }
1590        }
1591
1592        // A party cannot out-pace a body walking in a straight line.
1593        if let (Some(route), Some(walk)) = (
1594            self.building.get("pacing.route-blocks-per-minute"),
1595            self.building.get("pacing.walk-only-blocks-per-minute"),
1596        ) {
1597            checked += 1;
1598            if let (MetricValue::Count(r), MetricValue::Count(w)) =
1599                (route.value(&mut reads), walk.value(&mut reads))
1600                && r > w
1601            {
1602                failures.push(format!(
1603                    "`pacing.route-blocks-per-minute` is {r}, over the pure-walk ceiling of {w}"
1604                ));
1605            }
1606        }
1607
1608        SelfCheck {
1609            binding: SelfCheckBinding {
1610                invariants: checked,
1611                entries: self.building.len(),
1612                reads: reads.binding(),
1613            },
1614            reads,
1615            failures,
1616        }
1617    }
1618}
1619
1620/// What [`Metrics::self_check`] examined and what it found.
1621#[derive(Debug, Clone, PartialEq)]
1622pub struct SelfCheck {
1623    /// The ledger the verdicts read through, for [`Metrics::notice`].
1624    pub reads: Reads,
1625    /// What the run bound to. Stated whether or not anything failed, because a
1626    /// check that examined nothing is a finding and not a pass.
1627    pub binding: SelfCheckBinding,
1628    /// Inconsistencies, each a whole sentence. Non-empty is an internal error.
1629    pub failures: Vec<String>,
1630}
1631
1632/// [`Metrics::self_check`]'s binding count.
1633#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1634pub struct SelfCheckBinding {
1635    /// Invariants evaluated.
1636    pub invariants: usize,
1637    /// Building entries in the table.
1638    pub entries: usize,
1639    /// What those invariants read.
1640    pub reads: ReadBinding,
1641}
1642
1643/// The table rendered for export: every entry with its value, unit, provenance
1644/// and note, plus the halves' own counts.
1645///
1646/// Separate from [`Metrics`]'s own `Serialize` because the building half's value
1647/// is private — an export is the one consumer that reads a number without
1648/// resting a verdict on it.
1649#[must_use]
1650pub fn export(metrics: &Metrics) -> serde_json::Value {
1651    let mut player = serde_json::Map::new();
1652    for (k, e) in &metrics.player {
1653        player.insert((*k).to_string(), serde_json::json!(e));
1654    }
1655    let mut building = serde_json::Map::new();
1656    let mut uncalibrated = 0usize;
1657    for (k, e) in &metrics.building {
1658        if !e.calibrated {
1659            uncalibrated += 1;
1660        }
1661        building.insert(
1662            (*k).to_string(),
1663            serde_json::json!({
1664                "value": e.value_for_display(),
1665                "unit": e.unit,
1666                "provenance": e.provenance,
1667                "calibrated": e.calibrated,
1668                "note": e.note,
1669            }),
1670        );
1671    }
1672    serde_json::json!({
1673        "metrics_version": metrics.metrics_version,
1674        "mc_version": metrics.mc_version,
1675        "counts": {
1676            "player": metrics.player.len(),
1677            "building": metrics.building.len(),
1678            "uncalibrated": uncalibrated,
1679        },
1680        "player": player,
1681        "building": building,
1682    })
1683}
1684
1685#[cfg(test)]
1686mod tests {
1687    use super::*;
1688
1689    #[test]
1690    fn the_table_is_consistent_with_itself_and_with_the_player_half() {
1691        let m = Metrics::table();
1692        let check = m.self_check();
1693        assert!(
1694            check.failures.is_empty(),
1695            "the shipped metrics table is inconsistent: {:?}",
1696            check.failures
1697        );
1698        assert!(
1699            check.binding.invariants > 0,
1700            "a self-check that evaluated nothing is vacuous, not a pass"
1701        );
1702    }
1703
1704    #[test]
1705    fn every_building_entry_lands_uncalibrated() {
1706        let m = Metrics::table();
1707        assert!(!m.building.is_empty(), "the building half is empty");
1708        for (k, e) in &m.building {
1709            assert!(
1710                !e.calibrated,
1711                "`{k}` claims to be calibrated, but the metrics gym has not been walked"
1712            );
1713        }
1714    }
1715
1716    #[test]
1717    fn a_verdict_that_reads_a_seed_raises_dw0813_naming_it() {
1718        let m = Metrics::table();
1719        let check = m.self_check();
1720        assert!(
1721            check.binding.reads.provisional > 0,
1722            "the self-check read no provisional entry, so DW0813 binds to nothing"
1723        );
1724        let d = m
1725            .notice(&check.reads, "metrics")
1726            .expect("a run that read a seed owes the notice");
1727        assert_eq!(d.code, "DW0813");
1728        assert_eq!(d.severity, crate::diagnostic::Severity::Warning);
1729        for name in check.reads.provisional() {
1730            assert!(
1731                d.message.contains(name),
1732                "the notice must name `{name}`, the seed a verdict rested on"
1733            );
1734        }
1735    }
1736
1737    #[test]
1738    fn a_run_that_read_nothing_provisional_gets_no_notice() {
1739        let m = Metrics::table();
1740        let reads = Reads::new();
1741        assert!(m.notice(&reads, "metrics").is_none());
1742        assert_eq!(reads.binding().read, 0);
1743    }
1744
1745    #[test]
1746    fn an_undefined_name_is_dw0812_and_names_what_is_defined() {
1747        let m = Metrics::table();
1748        let err = m
1749            .resolve(MetricKind::SizeClass, "cathedral")
1750            .expect_err("`cathedral` is not a size class");
1751        let d = err.diagnostic("layout-graph", "/nodes/0/size_class");
1752        assert_eq!(d.code, "DW0812");
1753        assert!(d.message.contains("cathedral"));
1754        assert!(d.message.contains("room"), "the defined set is named");
1755        assert_eq!(d.stage, "layout-graph");
1756        assert_eq!(d.path, "/nodes/0/size_class");
1757    }
1758
1759    #[test]
1760    fn every_kind_resolves_at_least_one_defined_name() {
1761        let m = Metrics::table();
1762        for kind in [
1763            MetricKind::Opening,
1764            MetricKind::Pitch,
1765            MetricKind::SizeClass,
1766            MetricKind::Storey,
1767        ] {
1768            let names = m.names_of(kind);
1769            assert!(
1770                !names.is_empty(),
1771                "{} resolves nothing, so DW0812 would refuse every name",
1772                kind.noun()
1773            );
1774            for n in names {
1775                assert!(m.resolve(kind, n).is_ok(), "`{n}` does not resolve");
1776            }
1777        }
1778    }
1779
1780    #[test]
1781    fn the_derived_player_values_are_the_arithmetic_their_notes_claim() {
1782        assert!((walk_ticks_per_block() - 20.0 / 4.317).abs() < f64::EPSILON);
1783        assert!((walk_ticks_per_block() - 4.633).abs() < 0.001);
1784        assert_eq!(unarmoured_survivable_fall_blocks(), 22.0);
1785        assert_eq!(passable_width_cells(), 1);
1786        assert_eq!(passable_clearance_cells(), 2);
1787    }
1788}