delvewright_dsl/layout.rs
1//! **Space is a graph before it is a coordinate** (spec-0049 §3, §4.2) —
2//! pipeline stages 2 and 3.
3//!
4//! Two campaign stage documents land here, and neither holds a single
5//! coordinate:
6//!
7//! * **`geometry-brief`** — the machine-readable half of the whole map's written
8//! brief: `facts[]`, each a number with a name. Stage 4's identity checks bind
9//! a site plan to these (spec-0049 §4.2); this round lands the document and
10//! nothing reads it yet, which is stated rather than implied.
11//! * **`layout-graph`** — the campaign's space as a graph: places, the
12//! connections between them, the authored critical path, and where each quest
13//! beat happens. The topology carries the global guarantees and is checked as
14//! an object of its own, cheaply, **before geometry exists to make it
15//! expensive**.
16//!
17//! # What makes the ordering structural rather than prose
18//!
19//! spec-0049 §7 enumerates four inversions the design must make uncompilable.
20//! The one this module owns is *graph before mission*, and §7 is honest that it
21//! is **representable**: a graph with no `beats[]` and no gating validates
22//! against quest documents it never references. What it is not is silently
23//! green. Two teeth, both here:
24//!
25//! 1. `DW0817` states its beat binding, and a **zero** beat binding is printed
26//! as a zero — a critical path over an unbound graph is a route through
27//! nothing and says so.
28//! 2. `DW0818`'s **reverse** direction: the moment quests exist, every
29//! place-bound beat must bind to a node. A graph is free to arrive before the
30//! mission; it is not free to arrive after it and ignore it.
31//!
32//! # The gating vocabulary is deliberately NOT [`crate::gate::Gate`]
33//!
34//! An edge's [`EdgeGating`] names flags and a quest, which is what the campaign's
35//! one gate names too — so the question is owed an answer rather than a
36//! convention. A [`Gate`](crate::gate::Gate) is a **runtime** object: emission
37//! evaluates it against an acting player, and
38//! [`GateConsumer::evaluates_per_player`](crate::gate::GateConsumer) is what makes
39//! a `player`-scoped datum's readability decidable. A layout-graph edge is
40//! evaluated by nothing at run time — the graph emits no command, no function and
41//! no scoreboard — so making it a gate consumer would push a never-emitted object
42//! into machinery whose whole subject is emission, and every proof written about
43//! "the gates of this campaign" would then be reasoning about a claim instead of
44//! about a thing the server runs.
45//!
46//! It is also narrower on purpose. The closure below is **monotone** (§3.2), so a
47//! negative flag term and a numeric comparison are terms it cannot decide; a
48//! surface an author may write and no proof honours is worse than one that is not
49//! there. What an edge states is therefore a *projection* of the campaign's
50//! runtime gating into topology — and `DW0818` is what keeps it a projection
51//! rather than a second vocabulary: every flag it names must be one some effect
52//! really sets, and every quest it names must exist.
53//!
54//! Determinism (ADR-0006): every set and map here is a `BTreeSet`/`BTreeMap` and
55//! every walk is over a slice in document order.
56
57use std::collections::{BTreeMap, BTreeSet};
58
59use schemars::JsonSchema;
60use serde::{Deserialize, Serialize};
61
62use crate::diagnostic::{Diagnostic, DwCode, ExitTier};
63use crate::envelope::Campaign;
64use crate::ids::{AnchorId, EdgeId, FactId, FlagId, NodeId, ObjectiveId, QuestId};
65use crate::metrics::{MetricKind, Metrics, Reads};
66use crate::stages::Objective;
67
68/// `DW0814`: the layout graph is not a graph — a duplicate id, an endpoint
69/// naming no place, a self-loop, an `entry` that is not a node.
70pub const DW_GRAPH_MALFORMED: DwCode = DwCode::new("DW0814", ExitTier::Build);
71
72/// `DW0816`: a node the closure never reaches.
73pub const DW_NODE_UNREACHED: DwCode = DwCode::new("DW0816", ExitTier::Build);
74
75/// `DW0817`: the authored critical path does not hold.
76pub const DW_CRITICAL_PATH: DwCode = DwCode::new("DW0817", ExitTier::Build);
77
78/// `DW0818`: the graph names quest-side state that does not exist, or a
79/// place-bound beat has no place.
80pub const DW_GRAPH_MISSION: DwCode = DwCode::new("DW0818", ExitTier::Build);
81
82/// `DW0819`: a one-way edge strands.
83pub const DW_ONE_WAY_STRANDS: DwCode = DwCode::new("DW0819", ExitTier::Build);
84
85/// `DW0820`: a shortcut closes no loop.
86pub const DW_SHORTCUT_NO_LOOP: DwCode = DwCode::new("DW0820", ExitTier::Build);
87
88/// `DW0822`: the pacing measurement — a projection, printed with no threshold.
89pub const DW_PACING: DwCode = DwCode::new("DW0822", ExitTier::Build);
90
91/// `DW0869`: a station takes a name in the engine's own namespace (spec-0052 §7.1).
92pub const DW_STATION_RESERVED: DwCode = DwCode::new("DW0869", ExitTier::Build);
93
94/// `DW0870`: two stations claim one name (spec-0052 §7.2).
95pub const DW_STATION_DUPLICATE: DwCode = DwCode::new("DW0870", ExitTier::Build);
96
97/// `DW0871`: a reference demands a shape the station is not (spec-0052 §7.3).
98///
99/// Judged at the reference site from the DECLARATION, with zero pieces bound.
100pub const DW_STATION_KIND: DwCode = DwCode::new("DW0871", ExitTier::Build);
101
102/// `DW0875`: a place is classified twice, or not at all (spec-0053 §6).
103///
104/// A node declares **exactly one of** `size_class` and `way_class`. Both is two
105/// answers to one question with nothing to choose between them — every
106/// downstream geometric rule would have to pick, and there is no rule to pick
107/// by. Neither is a place with no standard at all, which is what the size-class
108/// ladder was made compulsory to prevent.
109pub const DW_PLACE_CLASS: DwCode = DwCode::new("DW0875", ExitTier::Build);
110
111// ---------------------------------------------------------------------------
112// Stage 2 — the geometry brief's machine-readable facts (spec-0049 §4.2)
113// ---------------------------------------------------------------------------
114
115/// The `geometry-brief` stage document's payload.
116///
117/// The brief's prose stays prose; only what is stated as a **fact** is
118/// checkable, and a site plan's `identities[]` bind to exactly these. The
119/// reference imagery keeps its standing — style authority, rank-only, never a
120/// gate (spec-0028) — so an identity binds to the written brief's numbers and
121/// never to a picture.
122#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
123#[serde(deny_unknown_fields)]
124pub struct GeometryBriefContent {
125 /// The brief's numbers, each with a name.
126 #[serde(default, skip_serializing_if = "Vec::is_empty")]
127 pub facts: Vec<BriefFact>,
128}
129
130/// One fact from the whole map's written brief: a number with a name.
131#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
132#[serde(deny_unknown_fields)]
133pub struct BriefFact {
134 /// Fact id (`fact/<kebab>`), unique within the brief.
135 pub id: FactId,
136 /// The number itself.
137 pub value: f64,
138 /// What the number counts (`blocks`, `storeys`, a ratio's `none`).
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub unit: Option<String>,
141 /// The sentence of the brief this number came from, so a reader of the plan
142 /// can see what the identity is holding the map to.
143 pub note: String,
144}
145
146// ---------------------------------------------------------------------------
147// Stage 3 — the layout graph (spec-0049 §3.1)
148// ---------------------------------------------------------------------------
149
150/// The `layout-graph` stage document's payload: the campaign's space as a graph,
151/// stated before any coordinate exists.
152#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
153#[serde(deny_unknown_fields)]
154pub struct LayoutGraphContent {
155 /// The places.
156 pub nodes: Vec<Node>,
157 /// The connections between them.
158 pub edges: Vec<Edge>,
159 /// Where a body starts.
160 pub entry: NodeId,
161 /// Where the campaign ends.
162 pub goal: NodeId,
163 /// The authored node sequence from `entry` to `goal`.
164 ///
165 /// **Authored rather than derived** so that it is a claim the machine
166 /// verifies (`DW0817`) and the walk sheet can print. A derived path would be
167 /// an answer with no author to disagree with.
168 pub critical_path: Vec<NodeId>,
169 /// Where each quest beat happens. Empty is legal and is the *graph before
170 /// mission* case — stated as a zero binding rather than passed over.
171 #[serde(default, skip_serializing_if = "Vec::is_empty")]
172 pub beats: Vec<Beat>,
173}
174
175/// A **place**: a room, a courtyard, an arena, a stretch of shore, a cavern.
176#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
177#[serde(deny_unknown_fields)]
178pub struct Node {
179 /// Node id (`node/<kebab>`), unique within the graph.
180 pub id: NodeId,
181 /// What this place is for, in the author's own words.
182 ///
183 /// A free non-empty label — `arena`, `hub`, `vista`, `gate-house`,
184 /// `shortcut-landing` — that **no check keys on**. It is recorded judgement
185 /// for the reviewer and for the later per-place briefs, and it is kept
186 /// free-form deliberately: an enum of intents would be this month's genre
187 /// wearing a schema's clothes.
188 pub intent: String,
189 /// The size class this place is built to, naming a rung of the metrics
190 /// table's ladder (`alcove`, `room`, `hall`, …). A name the table does not
191 /// define is `DW0812`.
192 ///
193 /// **Exactly one of this and [`Node::way_class`]** (`DW0875`). It is
194 /// `Option` rather than required because the alternative is a different KIND
195 /// of classification and not a rung — see [`Node::way_class`] — and a
196 /// required field with a sentinel value would be the ladder pretending to
197 /// classify something it cannot.
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub size_class: Option<String>,
200 /// The way class this place is built to, naming an entry of the metrics
201 /// table's way vocabulary (`corridor`, `road`, …) — **the second kind of
202 /// place classification** (spec-0053 §3). A name the table does not define
203 /// is `DW0812`, exactly as for a size class.
204 ///
205 /// **Exactly one of this and [`Node::size_class`]** (`DW0875`).
206 ///
207 /// A way is a place whose footprint is bounded in one axis and free in the
208 /// other: a road, a causeway, a corridor, a duct. The ladder cannot classify
209 /// one, and no calibration of it could — for a rung to admit a cut ledge one
210 /// body wide climbing a whole seaward face, that rung would have to span
211 /// 4..90 on an axis, and a class in which an alcove and an expanse are the
212 /// same thing has stopped classifying. The failure is by KIND, not by
213 /// margin.
214 ///
215 /// It classifies the **cross-section** and nothing else. The run is
216 /// per-campaign geometry: the site plan states it by putting the box where
217 /// it put it, `DW0832` demands only that it EXCEED the class's widest
218 /// cross-section, and the pacing measurement reads it. There is no length
219 /// standard here and there is not going to be one (spec-0053 §7).
220 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub way_class: Option<String>,
222 /// Anything the reviewer needs that `intent` does not carry.
223 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub note: Option<String>,
225 /// **The named places inside this one** (spec-0052 §3).
226 ///
227 /// A site-plan campaign's anchor vocabulary is otherwise exactly the
228 /// synthesized set — `spawn`, one anchor per node, and the seam and unlock
229 /// anchors of barred edges — which is complete only for the authoring order
230 /// it was designed for: quests written against nodes before any piece
231 /// exists. The inverse order is real, and its quest layer names places
232 /// *inside* places: the fire pit in the camp, the aft deck of the galley.
233 /// Those names are the campaign's design, and flattening them onto box
234 /// centres un-writes its spatial script.
235 ///
236 /// A station is a **name and a shape, never a position** (§5): while the box
237 /// is massed the derivation realizes each station at a stand-in of its own,
238 /// and when a piece is bound the `detail-plan` `anchors` map re-binds it to
239 /// an anchor of that piece, which is where the name gets its real place.
240 /// There is no coordinate, offset or hint field here, and that absence is
241 /// the design rather than an omission.
242 ///
243 /// Declared names join the campaign vocabulary at the same authority as
244 /// every synthesized one — [`crate::siteplan::synthesized_anchors`] is still
245 /// the single place the question is answered, so a name that validates
246 /// cannot fail to exist in the built world.
247 #[serde(default, skip_serializing_if = "Vec::is_empty")]
248 pub stations: Vec<Station>,
249}
250
251/// **A named place inside a node** (spec-0052 §3).
252///
253/// Belongs to exactly one node. A connection *between* places is the edge's to
254/// declare, as ever — an interior gate station seals a volume inside its own
255/// place and can never gate node-to-node traversal, so topology stays the
256/// graph's structurally rather than by convention.
257#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
258#[serde(deny_unknown_fields)]
259pub struct Station {
260 /// The anchor id (`anchor/<kebab>`) quests reference.
261 ///
262 /// Unique across the whole graph, and refused in the engine's own namespace
263 /// — see [`DW_STATION_RESERVED`] and [`DW_STATION_DUPLICATE`].
264 pub anchor: AnchorId,
265 /// The station's **shape** — never its purpose.
266 pub kind: StationKind,
267 /// Recorded judgement for the reviewer and the later per-place detail
268 /// brief. **No check keys on it**, for the same reason none keys on
269 /// [`Node::intent`].
270 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub note: Option<String>,
272}
273
274/// **What shape a station is** (spec-0052 §3) — a cell to stand a body at, or a
275/// volume with a block that seals and clears.
276///
277/// The kind is the station's shape, never its purpose: there is no enum of
278/// bonfire / camera / shop, for the same reason [`Node::intent`] is free-form —
279/// a purpose vocabulary would be this month's genre wearing a schema's clothes.
280/// A bonfire, a camera subject and a shop counter are the same [`Self::Point`]
281/// to every check in this engine.
282///
283/// # Why two shapes and not three
284///
285/// spec-0052 §3 describes three, "mirroring the three shapes a piece anchor can
286/// take (a cell to stand a body at; a volume; a volume with a block that seals
287/// and clears)". Those are the three shapes a piece anchor may be **declared**
288/// in; they are not three shapes anything **consumes**. This engine resolves an
289/// anchor to `ResolvedAnchor::Point` or `ResolvedAnchor::Gate` and to nothing
290/// else, and a piece anchor declaring a bare `region` with no `block` is read as
291/// a gate whose fill block is `minecraft:air`.
292///
293/// Every volume-shaped consumer — a `lethal_volumes[]` region, `damage-players`'s
294/// `in`, a `volley` kill zone, `collapse`'s ceiling, `begin-stealth`,
295/// `fill-region`, `clear-region` — is a [`crate::StealthZone`], an
296/// **anchor-centred box** resolved from a *point* plus an extent. The engine
297/// states the reason in its own words at `Verb::FillRegion::region`: an
298/// anchor-centred box rather than a prefab `region` anchor, "because the
299/// assembled model deletes every gate-region anchor's cells, so a slab declared
300/// that way would already be gone".
301///
302/// So a third `region` variant would be a name a campaign could declare and bind
303/// and **no reference site could consume** — an inert surface whose stand-in
304/// would have to be a gate region the assembled world then deletes. It is left
305/// out deliberately, and spec-0052 §11's falsifier is what decides it: the first
306/// campaign brief that cannot state its place without one is the evidence, and
307/// the answer is a first-class surface with a consumer, or a refused feature.
308#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
309#[serde(rename_all = "kebab-case")]
310pub enum StationKind {
311 /// A cell to stand a body at — where a quest step, an NPC, a wave seat, a
312 /// cutscene subject, an affordance or a volume's centre lands.
313 Point,
314 /// A volume with a block that seals and clears — what `open-gate`,
315 /// `close-gate`, a `shortcut` and a `timed-gate` address.
316 Gate,
317}
318
319impl StationKind {
320 /// The word a diagnostic prints for this kind.
321 #[must_use]
322 pub fn word(self) -> &'static str {
323 match self {
324 Self::Point => "point",
325 Self::Gate => "gate",
326 }
327 }
328}
329
330/// Which way a one-way connection runs.
331#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
332#[serde(rename_all = "kebab-case")]
333pub enum Direction {
334 /// From the edge's `a` end to its `b` end.
335 AToB,
336 /// From the edge's `b` end to its `a` end.
337 BToA,
338}
339
340/// Which side of a barred connection can open it.
341#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
342#[serde(rename_all = "kebab-case")]
343pub enum OpensFrom {
344 /// Only from the `a` end.
345 A,
346 /// Only from the `b` end.
347 B,
348 /// From either end.
349 #[default]
350 Either,
351}
352
353/// What a body must already hold for a connection to be passable.
354///
355/// A **projection** of the campaign's runtime gating into topology, not the
356/// campaign's [`Gate`](crate::gate::Gate) — see the module docs for why the two
357/// are deliberately different objects, and for why this one carries no negative
358/// flag term and no numeric comparison.
359#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
360#[serde(deny_unknown_fields)]
361pub struct EdgeGating {
362 /// Flags a body must already have, each one some `set-flag` effect really
363 /// produces (`DW0818`).
364 #[serde(default, skip_serializing_if = "Vec::is_empty")]
365 pub flags: Vec<FlagId>,
366 /// A quest that must already be complete.
367 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub quest: Option<QuestId>,
369}
370
371impl EdgeGating {
372 /// True if this gating demands nothing.
373 #[must_use]
374 pub fn is_empty(&self) -> bool {
375 self.flags.is_empty() && self.quest.is_none()
376 }
377
378 /// How many terms it has — the number a binding ledger reports.
379 #[must_use]
380 pub fn terms(&self) -> usize {
381 self.flags.len() + usize::from(self.quest.is_some())
382 }
383}
384
385/// A connection between two places.
386///
387/// Internally tagged on `class`, in the same shape every other tagged union in
388/// this DSL uses. The tagging is load-bearing rather than stylistic: `falls`
389/// belongs to a drop and `opens_from` belongs to a barred way, and writing
390/// either on a walk would be a declaration nothing reads. Under the tag, serde's
391/// `deny_unknown_fields` refuses it as an ordinary `DW0100` — so the illegal
392/// state is unrepresentable and no diagnostic has to police it.
393#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
394#[serde(tag = "class", rename_all = "kebab-case", deny_unknown_fields)]
395pub enum Edge {
396 /// A way a body walks, at grade.
397 Walk {
398 /// Edge id (`edge/<kebab>`), unique within the graph.
399 id: EdgeId,
400 /// One end.
401 a: NodeId,
402 /// The other end.
403 b: NodeId,
404 /// Declared directionality; absent means a body passes both ways.
405 #[serde(default, skip_serializing_if = "Option::is_none")]
406 one_way: Option<Direction>,
407 /// This connection exists to close a loop (`DW0820`).
408 #[serde(default, skip_serializing_if = "is_false")]
409 shortcut: bool,
410 /// What a body must hold to pass.
411 #[serde(default, skip_serializing_if = "Option::is_none")]
412 gating: Option<EdgeGating>,
413 },
414 /// A way a body climbs or descends on built treads.
415 Stair {
416 /// Edge id (`edge/<kebab>`), unique within the graph.
417 id: EdgeId,
418 /// One end.
419 a: NodeId,
420 /// The other end.
421 b: NodeId,
422 /// Declared directionality; absent means a body passes both ways.
423 #[serde(default, skip_serializing_if = "Option::is_none")]
424 one_way: Option<Direction>,
425 /// This connection exists to close a loop (`DW0820`).
426 #[serde(default, skip_serializing_if = "is_false")]
427 shortcut: bool,
428 /// What a body must hold to pass.
429 #[serde(default, skip_serializing_if = "Option::is_none")]
430 gating: Option<EdgeGating>,
431 },
432 /// A fall. One-way **by construction**, which is why the direction is
433 /// required here and optional on its siblings: a body that has dropped
434 /// cannot climb back up the way it came.
435 Drop {
436 /// Edge id (`edge/<kebab>`), unique within the graph.
437 id: EdgeId,
438 /// One end.
439 a: NodeId,
440 /// The other end.
441 b: NodeId,
442 /// Which way it falls.
443 falls: Direction,
444 /// This connection exists to close a loop (`DW0820`).
445 #[serde(default, skip_serializing_if = "is_false")]
446 shortcut: bool,
447 /// What a body must hold to pass.
448 #[serde(default, skip_serializing_if = "Option::is_none")]
449 gating: Option<EdgeGating>,
450 },
451 /// A sealed connection some effect opens.
452 Barred {
453 /// Edge id (`edge/<kebab>`), unique within the graph.
454 id: EdgeId,
455 /// One end.
456 a: NodeId,
457 /// The other end.
458 b: NodeId,
459 /// Which side can open it. The one-side-openable door is spelled here,
460 /// and it is a property of the connection rather than of any campaign's
461 /// fiction.
462 #[serde(default)]
463 opens_from: OpensFrom,
464 /// Declared directionality once open; absent means both ways.
465 #[serde(default, skip_serializing_if = "Option::is_none")]
466 one_way: Option<Direction>,
467 /// This connection exists to close a loop (`DW0820`).
468 #[serde(default, skip_serializing_if = "is_false")]
469 shortcut: bool,
470 /// What opens it. **Required to say something** (`DW0818`): a barred way
471 /// nothing opens is a wall, and a barred way anything opens is not
472 /// barred.
473 gating: EdgeGating,
474 },
475 /// A connection a body is **carried** over (spec-0083 §7): no seam, no sill,
476 /// no door check and no body of its own. The derivation writes nothing for
477 /// it; at stage 5 every direction it allows is owed a link — a repeatable
478 /// trigger whose `teleport` leaves the `a` place's station for the `b`
479 /// place's mark — and every link is owed the edge (`DW0934`).
480 Carry {
481 /// Edge id (`edge/<kebab>`), unique within the graph.
482 id: EdgeId,
483 /// One end.
484 a: NodeId,
485 /// The other end.
486 b: NodeId,
487 /// Declared directionality; absent means a body is carried both ways,
488 /// and each direction is then owed a link.
489 #[serde(default, skip_serializing_if = "Option::is_none")]
490 one_way: Option<Direction>,
491 /// What carries it. **Required to say something** (`DW0818`), as a
492 /// barred way's is: a carry live from world load is a hole in the
493 /// graph's own claim.
494 gating: EdgeGating,
495 },
496 /// A line of sight between two places, in either direction. Carries no body,
497 /// so it is not a traversal edge and the reachability closure never walks
498 /// it; stage 4 gives it a sightline rather than a seam (spec-0049 §4.4).
499 Vision {
500 /// Edge id (`edge/<kebab>`), unique within the graph.
501 id: EdgeId,
502 /// One end.
503 a: NodeId,
504 /// The other end.
505 b: NodeId,
506 },
507}
508
509fn is_false(b: &bool) -> bool {
510 !*b
511}
512
513impl Edge {
514 /// The edge's id.
515 #[must_use]
516 pub fn id(&self) -> &EdgeId {
517 match self {
518 Edge::Walk { id, .. }
519 | Edge::Stair { id, .. }
520 | Edge::Drop { id, .. }
521 | Edge::Barred { id, .. }
522 | Edge::Carry { id, .. }
523 | Edge::Vision { id, .. } => id,
524 }
525 }
526
527 /// The `a` end.
528 #[must_use]
529 pub fn a(&self) -> &NodeId {
530 match self {
531 Edge::Walk { a, .. }
532 | Edge::Stair { a, .. }
533 | Edge::Drop { a, .. }
534 | Edge::Barred { a, .. }
535 | Edge::Carry { a, .. }
536 | Edge::Vision { a, .. } => a,
537 }
538 }
539
540 /// The `b` end.
541 #[must_use]
542 pub fn b(&self) -> &NodeId {
543 match self {
544 Edge::Walk { b, .. }
545 | Edge::Stair { b, .. }
546 | Edge::Drop { b, .. }
547 | Edge::Barred { b, .. }
548 | Edge::Carry { b, .. }
549 | Edge::Vision { b, .. } => b,
550 }
551 }
552
553 /// The class name as the document spells it.
554 #[must_use]
555 pub fn class(&self) -> &'static str {
556 match self {
557 Edge::Walk { .. } => "walk",
558 Edge::Stair { .. } => "stair",
559 Edge::Drop { .. } => "drop",
560 Edge::Barred { .. } => "barred",
561 Edge::Carry { .. } => "carry",
562 Edge::Vision { .. } => "vision",
563 }
564 }
565
566 /// True if a body passes along this edge. A `vision` edge does not.
567 #[must_use]
568 pub fn is_traversal(&self) -> bool {
569 !matches!(self, Edge::Vision { .. })
570 }
571
572 /// True if the geometry owes this edge a **seam** — an opening on a shared
573 /// face. A `vision` edge is owed a sightline instead, and a `carry` edge is
574 /// owed nothing: a body crosses it by being put down on the far side.
575 #[must_use]
576 pub fn has_seam(&self) -> bool {
577 !matches!(self, Edge::Vision { .. } | Edge::Carry { .. })
578 }
579
580 /// Which way a body may pass, or `None` for both ways (and for a `vision`
581 /// edge, which carries none).
582 #[must_use]
583 pub fn direction(&self) -> Option<Direction> {
584 match self {
585 Edge::Walk { one_way, .. }
586 | Edge::Stair { one_way, .. }
587 | Edge::Barred { one_way, .. }
588 | Edge::Carry { one_way, .. } => *one_way,
589 Edge::Drop { falls, .. } => Some(*falls),
590 Edge::Vision { .. } => None,
591 }
592 }
593
594 /// True if this edge is marked as closing a loop.
595 #[must_use]
596 pub fn shortcut(&self) -> bool {
597 match self {
598 Edge::Walk { shortcut, .. }
599 | Edge::Stair { shortcut, .. }
600 | Edge::Drop { shortcut, .. }
601 | Edge::Barred { shortcut, .. } => *shortcut,
602 Edge::Carry { .. } | Edge::Vision { .. } => false,
603 }
604 }
605
606 /// What a body must hold to pass, or `None` where the edge demands nothing.
607 #[must_use]
608 pub fn gating(&self) -> Option<&EdgeGating> {
609 match self {
610 Edge::Walk { gating, .. } | Edge::Stair { gating, .. } | Edge::Drop { gating, .. } => {
611 gating.as_ref()
612 }
613 Edge::Barred { gating, .. } | Edge::Carry { gating, .. } => Some(gating),
614 Edge::Vision { .. } => None,
615 }
616 }
617}
618
619/// Where one quest beat happens.
620#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
621#[serde(deny_unknown_fields)]
622pub struct Beat {
623 /// The quest the objective belongs to.
624 pub quest: QuestId,
625 /// The objective.
626 pub objective: ObjectiveId,
627 /// The place it happens in.
628 pub node: NodeId,
629}
630
631// ---------------------------------------------------------------------------
632// The closure (spec-0049 §3.2)
633// ---------------------------------------------------------------------------
634
635/// One thing a body can be holding: a produced flag, or a completed quest.
636#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
637pub enum Grant {
638 /// A flag some effect set.
639 Flag(String),
640 /// A quest that completed.
641 Quest(String),
642}
643
644/// The monotone reachability closure of a layout graph.
645///
646/// Exactly Dormans' loop, and exactly §3.2: beats grant, edges demand.
647/// Deterministic, linear in the number of edges times the number of rounds, and
648/// **optimistic in every direction it cannot decide** — which is one property,
649/// stated once, rather than a list of exceptions:
650///
651/// * it is **branch-blind**, so a campaign whose branch points set mutually
652/// exclusive flags can reach a node no single playthrough reaches;
653/// * a beat's grants include everything the campaign fires when that objective
654/// completes, including a `talk-to`'s whole dialogue tree, because talking is
655/// what a body does at the place the speaker stands.
656///
657/// The optimism can only under-report at graph time; the stage-5 battery is
658/// branch-aware over bytes and is what stops it shipping a broken world. If a
659/// campaign's graph-stage green turns into a repeated stage-5 red on
660/// branch-gated nodes, this closure gains branch awareness from
661/// `compiler::flow`'s existing branch enumeration — that is the trigger, and
662/// before it fires the simple closure is the cheaper instrument.
663#[derive(Debug, Clone, Default)]
664pub struct Closure {
665 /// Every node a body can be at.
666 pub reached: BTreeSet<String>,
667 /// Everything a body can be holding once the fixpoint settles.
668 pub obtained: BTreeSet<Grant>,
669 /// Per node, what was already obtained when that node was **first** reached.
670 /// The set `DW0819` judges a strand against.
671 pub obtained_when: BTreeMap<String, BTreeSet<Grant>>,
672}
673
674impl Closure {
675 /// True if `gating` is satisfied by `held`.
676 #[must_use]
677 pub fn satisfied(gating: Option<&EdgeGating>, held: &BTreeSet<Grant>) -> bool {
678 let Some(g) = gating else { return true };
679 g.flags
680 .iter()
681 .all(|f| held.contains(&Grant::Flag(f.0.clone())))
682 && g.quest
683 .as_ref()
684 .is_none_or(|q| held.contains(&Grant::Quest(q.0.clone())))
685 }
686
687 /// Run the closure from `entry`, with `grants` saying what a reached node
688 /// hands a body and `quest_grants` what completing a quest does.
689 #[must_use]
690 pub fn run(graph: &LayoutGraphContent, grants: &Grants) -> Closure {
691 let mut c = Closure::default();
692 c.reached.insert(graph.entry.0.clone());
693 c.obtained_when
694 .insert(graph.entry.0.clone(), BTreeSet::new());
695 loop {
696 let before = (c.reached.len(), c.obtained.len());
697 // (a) + (b): every edge whose demand is met carries a body, in the
698 // direction it allows.
699 for e in &graph.edges {
700 if !e.is_traversal() || !Closure::satisfied(e.gating(), &c.obtained) {
701 continue;
702 }
703 let (a, b) = (e.a().0.as_str(), e.b().0.as_str());
704 let forward = e.direction() != Some(Direction::BToA);
705 let backward = e.direction() != Some(Direction::AToB);
706 if forward && c.reached.contains(a) && !c.reached.contains(b) {
707 c.reached.insert(b.to_string());
708 c.obtained_when.insert(b.to_string(), c.obtained.clone());
709 }
710 if backward && c.reached.contains(b) && !c.reached.contains(a) {
711 c.reached.insert(a.to_string());
712 c.obtained_when.insert(a.to_string(), c.obtained.clone());
713 }
714 }
715 // (c): every beat bound to a reached node hands over what it grants.
716 for (node, given) in &grants.by_node {
717 if c.reached.contains(node.as_str()) {
718 c.obtained.extend(given.iter().cloned());
719 }
720 }
721 // A quest completes once every one of its beats is somewhere a body
722 // can stand.
723 for (quest, (nodes, given)) in &grants.by_quest {
724 if nodes.iter().all(|n| c.reached.contains(n.as_str())) {
725 c.obtained.insert(Grant::Quest(quest.clone()));
726 c.obtained.extend(given.iter().cloned());
727 }
728 }
729 if (c.reached.len(), c.obtained.len()) == before {
730 return c;
731 }
732 }
733 }
734}
735
736/// What each place hands a body, derived from the campaign's own quest
737/// documents — the *grant* half of §3.2's loop.
738#[derive(Debug, Clone, Default)]
739pub struct Grants {
740 /// node id -> what standing there eventually yields.
741 pub by_node: BTreeMap<String, BTreeSet<Grant>>,
742 /// quest id -> (the nodes its beats sit in, what completing it yields).
743 pub by_quest: BTreeMap<String, (BTreeSet<String>, BTreeSet<Grant>)>,
744}
745
746impl Grants {
747 /// Derive the grants a graph's `beats[]` imply, from the campaign's quests
748 /// and dialogue.
749 ///
750 /// A beat bound to an objective grants every flag the campaign sets when
751 /// that objective completes, plus — for a `talk-to` — every flag reachable
752 /// in the spoken-to NPC's dialogue tree, because the conversation happens
753 /// where the speaker stands. Both walks reach nested bundles, so a
754 /// `set-flag` inside a `sequence` step or an `on_respawn` hook counts
755 /// exactly as a top-level one does.
756 #[must_use]
757 pub fn of(c: &Campaign, graph: &LayoutGraphContent) -> Grants {
758 let mut g = Grants::default();
759 // objective id (scoped by quest) -> the flags its completion sets.
760 let mut on_objective: BTreeMap<(&str, &str), BTreeSet<Grant>> = BTreeMap::new();
761 let mut on_quest: BTreeMap<&str, BTreeSet<Grant>> = BTreeMap::new();
762 // NPC -> the flags anything in their dialogue tree can set.
763 let mut npc_flags: BTreeMap<&str, BTreeSet<Grant>> = BTreeMap::new();
764 for tree in &c.dialogue.content.dialogues {
765 let set = npc_flags.entry(tree.npc.0.as_str()).or_default();
766 for node in &tree.nodes {
767 for opt in &node.options {
768 for eff in &opt.effects {
769 if let Some(f) = eff.set_flag() {
770 set.insert(Grant::Flag(f.0.clone()));
771 }
772 }
773 }
774 }
775 }
776 for q in &c.quests.content.quests {
777 let mut done: BTreeSet<Grant> = BTreeSet::new();
778 for eff in &q.on_complete {
779 eff.visit_deep(&mut |e| {
780 if let Some(f) = e.set_flag() {
781 done.insert(Grant::Flag(f.0.clone()));
782 }
783 });
784 }
785 on_quest.insert(q.id.0.as_str(), done);
786 for (obj, effects) in &q.on_objective_complete {
787 let entry = on_objective
788 .entry((q.id.0.as_str(), obj.0.as_str()))
789 .or_default();
790 for eff in effects {
791 eff.visit_deep(&mut |e| {
792 if let Some(f) = e.set_flag() {
793 entry.insert(Grant::Flag(f.0.clone()));
794 }
795 });
796 }
797 }
798 for obj in &q.objectives {
799 if let Objective::TalkTo { id, npc, .. } = obj
800 && let Some(flags) = npc_flags.get(npc.0.as_str())
801 {
802 on_objective
803 .entry((q.id.0.as_str(), id.0.as_str()))
804 .or_default()
805 .extend(flags.iter().cloned());
806 }
807 }
808 }
809 for beat in &graph.beats {
810 let node = beat.node.0.clone();
811 let given = on_objective
812 .get(&(beat.quest.0.as_str(), beat.objective.0.as_str()))
813 .cloned()
814 .unwrap_or_default();
815 g.by_node.entry(node.clone()).or_default().extend(given);
816 let q = g
817 .by_quest
818 .entry(beat.quest.0.clone())
819 .or_insert_with(|| (BTreeSet::new(), BTreeSet::new()));
820 q.0.insert(node);
821 q.1 = on_quest
822 .get(beat.quest.0.as_str())
823 .cloned()
824 .unwrap_or_default();
825 }
826 g
827 }
828}
829
830// ---------------------------------------------------------------------------
831// The binding ledger
832// ---------------------------------------------------------------------------
833
834/// What a run's **map-pipeline** checks bound to — stages 2, 3 and 4.
835///
836/// Stated on every run whether or not anything was found, because a count only
837/// means something when the run that found nothing prints it too (CLAUDE.md). It
838/// is one struct with one constructor, so the number the CLI prints, the number
839/// the build ledger records and the number a diagnostic quotes cannot disagree.
840///
841/// One ledger for three documents rather than one per document, and that is the
842/// point: a site plan's boxes are counted beside the graph's places, so a run
843/// that embeds five of six places states both numbers on one line and the
844/// mismatch is visible without arithmetic.
845#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
846pub struct LayoutBinding {
847 /// Places declared — what `DW0816` examines.
848 pub nodes: usize,
849 /// Connections declared.
850 pub edges: usize,
851 /// Of those, connections a body passes along.
852 pub traversal_edges: usize,
853 /// Of those, connections marked as closing a loop — what `DW0820` examines.
854 pub shortcut_edges: usize,
855 /// Connections a body passes one way only — what `DW0819` examines.
856 pub one_way_edges: usize,
857 /// Connections that demand something before a body may pass.
858 pub gated_edges: usize,
859 /// Connections a body is carried over rather than walks (spec-0083 §7) —
860 /// what `DW0934` matches against the campaign's links.
861 pub carry_edges: usize,
862 /// **Named places inside places** — stations declared across the whole graph
863 /// (spec-0052 §4).
864 ///
865 /// A station no quest references is legal mid-authoring, so this is the
866 /// denominator rather than a count of what is used, and a **zero is stated**
867 /// like every other: a site-plan campaign with no stations names its places
868 /// at node granularity, which is a fact about that campaign and not a
869 /// silence.
870 pub stations: usize,
871 /// Of those, stations declared as a gate — the ones `open-gate`,
872 /// `close-gate`, a `shortcut` and a `timed-gate` may address. The remainder
873 /// are points, which is what every other consumer resolves.
874 pub gate_stations: usize,
875 /// Quest beats bound to a place.
876 pub beats: usize,
877 /// Of those, beats on the **mandatory quest spine** — the number `DW0817`'s
878 /// obligation to visit them actually quantifies over.
879 ///
880 /// It is carried separately because `beats` is not the binding: a graph can
881 /// declare a dozen beats and still ask `DW0817` to check nothing, if none of
882 /// their quests is one the finale depends on. A zero here is the *graph
883 /// before mission* case and is reported as a finding.
884 pub spine_beats: usize,
885 /// Steps of the authored critical path — what `DW0817` and `DW0822`
886 /// examine.
887 pub path_steps: usize,
888 /// Names resolved into the metrics table — what `DW0812` examines.
889 pub metric_refs: usize,
890 /// Facts the geometry brief states — what a site plan's identities bind to.
891 pub brief_facts: usize,
892 /// What the site plan offers the stage-4 checks.
893 pub plan: crate::siteplan::PlanBinding,
894}
895
896impl LayoutBinding {
897 /// Count what a campaign's layout documents offer the checks.
898 #[must_use]
899 pub fn of(c: &Campaign) -> LayoutBinding {
900 let mut b = LayoutBinding {
901 brief_facts: c
902 .geometry_brief
903 .as_ref()
904 .map_or(0, |g| g.content.facts.len()),
905 ..LayoutBinding::default()
906 };
907 let Some(graph) = c.layout_graph.as_ref().map(|g| &g.content) else {
908 b.plan = crate::siteplan::PlanBinding::of(c);
909 return b;
910 };
911 b.plan = crate::siteplan::PlanBinding::of(c);
912 b.nodes = graph.nodes.len();
913 b.edges = graph.edges.len();
914 b.beats = graph.beats.len();
915 let spine = c.quest_plan.content.spine();
916 b.spine_beats = graph
917 .beats
918 .iter()
919 .filter(|beat| spine.contains(beat.quest.0.as_str()))
920 .count();
921 b.path_steps = graph.critical_path.len().saturating_sub(1);
922 b.metric_refs = graph.nodes.len();
923 for n in &graph.nodes {
924 b.stations += n.stations.len();
925 b.gate_stations += n
926 .stations
927 .iter()
928 .filter(|s| s.kind == StationKind::Gate)
929 .count();
930 }
931 for e in &graph.edges {
932 if e.is_traversal() {
933 b.traversal_edges += 1;
934 }
935 if e.shortcut() {
936 b.shortcut_edges += 1;
937 }
938 if e.is_traversal() && e.direction().is_some() {
939 b.one_way_edges += 1;
940 }
941 if e.gating().is_some_and(|g| !g.is_empty()) {
942 b.gated_edges += 1;
943 }
944 if matches!(e, Edge::Carry { .. }) {
945 b.carry_edges += 1;
946 }
947 }
948 b
949 }
950
951 /// One line, for stderr and for the round summary.
952 #[must_use]
953 pub fn line(&self) -> String {
954 format!(
955 "layout-graph binding: {n} node(s), {e} edge(s) ({t} traversal, {ow} one-way, \
956 {s} shortcut, {g} gated, {c} carry), {st} station(s) of which {gs} gate(s), {b} beat(s) \
957 of which {sb} on the mandatory spine, {p} critical-path step(s), \
958 {m} metrics reference(s); geometry-brief binding: {f} fact(s).",
959 n = self.nodes,
960 e = self.edges,
961 t = self.traversal_edges,
962 ow = self.one_way_edges,
963 s = self.shortcut_edges,
964 g = self.gated_edges,
965 c = self.carry_edges,
966 st = self.stations,
967 gs = self.gate_stations,
968 b = self.beats,
969 sb = self.spine_beats,
970 p = self.path_steps,
971 m = self.metric_refs,
972 f = self.brief_facts,
973 )
974 }
975
976 /// The site-plan half, when the campaign carries one.
977 #[must_use]
978 pub fn plan_line(&self) -> String {
979 self.plan.line()
980 }
981}
982
983// ---------------------------------------------------------------------------
984// Validation tier (spec-0049 §3.3): DW0814, DW0818, DW0820, DW0822, DW0812,
985// and — since the reachability battery moved here — DW0816, DW0817, DW0819
986// ---------------------------------------------------------------------------
987
988/// Every check the layout documents owe at **validation** tier.
989///
990/// Invoked from [`crate::validate::validate_campaign_with`] whenever the
991/// campaign carries either document — the same event-bound shape stage 7's edit
992/// script uses. There is no separate entry point to remember and no flag to
993/// pass: a campaign directory holding a `layout-graph.json` cannot be validated
994/// without running this.
995pub fn check(c: &Campaign, reads: &mut Reads, d: &mut Vec<Diagnostic>) {
996 let table = Metrics::table();
997 if let Some(brief) = &c.geometry_brief {
998 brief_checks(&brief.content, d);
999 }
1000 let Some(graph) = c.layout_graph.as_ref().map(|g| &g.content) else {
1001 return;
1002 };
1003 // Referential wellformedness first: every check below reads node ids, and a
1004 // dangling one would make each of them answer a question about a place that
1005 // is not there.
1006 let known: BTreeSet<&str> = graph.nodes.iter().map(|n| n.id.0.as_str()).collect();
1007 let malformed = wellformed(graph, &known, d);
1008 metric_names(graph, &table, d);
1009 place_classes(graph, &table, d);
1010 stations(graph, d);
1011 if malformed {
1012 return;
1013 }
1014 mission(c, graph, d);
1015 shortcut_loops(graph, d);
1016 pacing(c, graph, &table, reads, d);
1017 // The reachability proofs run HERE and nowhere else — see [`reachability`]
1018 // for why they are no longer raised from the analysis pass. The page tells
1019 // an author to loop `validate` at the graph step; this is what makes that
1020 // instruction true.
1021 d.extend(reachability(c));
1022}
1023
1024/// **The two refusals a declared station owes** (spec-0052 §7.1 and §7.2).
1025///
1026/// Runs before the malformed-graph return, because a station's name is judged
1027/// against the engine's namespace and against the other stations — neither of
1028/// which needs the node ids to resolve. A campaign with a dangling edge still
1029/// gets told its station name is taken.
1030fn stations(graph: &LayoutGraphContent, d: &mut Vec<Diagnostic>) {
1031 // ---- §7.1: a station in the engine's namespace.
1032 //
1033 // The PREFIX is the rule, not the collision: `anchor/seam-vestry-door` is
1034 // refused even where no such edge exists, so that adding the edge later
1035 // cannot turn a legal graph into two claims on one name.
1036 //
1037 // Reserving `spawn` by its exact name rather than by a prefix is not an
1038 // inconsistency — `spawn` is one name the derivation synthesizes, and it has
1039 // no family to reserve.
1040 let entry = crate::siteplan::ENTRY_ANCHOR;
1041 for (i, n) in graph.nodes.iter().enumerate() {
1042 for (j, s) in n.stations.iter().enumerate() {
1043 let name = s.anchor.as_str();
1044 let reserved = ["anchor/node-", "anchor/seam-", "anchor/unlock-"]
1045 .into_iter()
1046 .find(|p| name.starts_with(p));
1047 let why = if let Some(prefix) = reserved {
1048 format!("its name begins `{prefix}`")
1049 } else if name == entry {
1050 format!("`{entry}` is the name the entry place stands under")
1051 } else {
1052 continue;
1053 };
1054 d.push(Diagnostic::error(
1055 DW_STATION_RESERVED,
1056 "layout-graph",
1057 format!("/content/nodes/{i}/stations/{j}/anchor"),
1058 format!(
1059 "station `{name}` takes a name the engine derives: {why}. The derivation \
1060 synthesizes this campaign's whole spatial vocabulary — `{entry}`, an \
1061 `anchor/node-…` for each place, and an `anchor/seam-…` plus an \
1062 `anchor/unlock-…` for each barred connection — so those three prefixes and \
1063 `{entry}` are reserved whether or not this graph happens to produce the \
1064 name today. Name the station something of your own, and the quest layer \
1065 references it exactly as it references a derived one."
1066 ),
1067 ));
1068 }
1069 }
1070
1071 // ---- §7.2: two claims on one name.
1072 //
1073 // **The scope of uniqueness is the area**, which is the scope every anchor
1074 // reference already resolves in — unchanged from the standing rule, and the
1075 // reason two pieces may both declare `anchor/door` and collide with nothing.
1076 // A site-plan campaign has one area, so this is the whole graph.
1077 let mut first: BTreeMap<&str, &NodeId> = BTreeMap::new();
1078 for (i, n) in graph.nodes.iter().enumerate() {
1079 for (j, s) in n.stations.iter().enumerate() {
1080 let name = s.anchor.as_str();
1081 if let Some(other) = first.get(name) {
1082 d.push(Diagnostic::error(
1083 DW_STATION_DUPLICATE,
1084 "layout-graph",
1085 format!("/content/nodes/{i}/stations/{j}/anchor"),
1086 format!(
1087 "station `{name}` is declared by `{here}` and by `{other}`. A station \
1088 name is unique within the AREA — the scope every anchor reference \
1089 resolves in — and a site-plan campaign has exactly one, so the \
1090 campaign's whole vocabulary shares it. Two places cannot both answer \
1091 to one name, because a quest naming it would have two answers and \
1092 nothing would say which. Rename one of them, or declare it on one \
1093 place only: a quest in either place may name a station of the other.",
1094 here = n.id,
1095 ),
1096 ));
1097 } else {
1098 first.insert(name, &n.id);
1099 }
1100 }
1101 }
1102}
1103
1104/// `fact/<kebab>` ids, unique, and every fact carries the sentence it came from.
1105fn brief_checks(brief: &GeometryBriefContent, d: &mut Vec<Diagnostic>) {
1106 let mut seen: BTreeSet<&str> = BTreeSet::new();
1107 for (i, f) in brief.facts.iter().enumerate() {
1108 if !f.id.is_valid_syntax() {
1109 d.push(Diagnostic::error(
1110 crate::codes::ID_SYNTAX,
1111 "geometry-brief",
1112 format!("/content/facts/{i}/id"),
1113 format!(
1114 "malformed fact id `{}` — a brief fact is named `fact/<kebab-case>`, so that \
1115 a site plan's identity can bind to it by name.",
1116 f.id
1117 ),
1118 ));
1119 }
1120 if !seen.insert(f.id.0.as_str()) {
1121 d.push(Diagnostic::error(
1122 crate::codes::ID_DUPLICATE,
1123 "geometry-brief",
1124 format!("/content/facts/{i}/id"),
1125 format!(
1126 "duplicate fact id `{}` — rename one, because an identity binding to this \
1127 name would otherwise hold the map to whichever number was written last.",
1128 f.id
1129 ),
1130 ));
1131 }
1132 }
1133}
1134
1135/// `DW0814` and the id-syntax rules. Returns true if the graph is malformed
1136/// enough that the semantic checks below it would be answering about places that
1137/// are not there.
1138fn wellformed(graph: &LayoutGraphContent, known: &BTreeSet<&str>, d: &mut Vec<Diagnostic>) -> bool {
1139 let before = d.len();
1140 let mut seen_nodes: BTreeSet<&str> = BTreeSet::new();
1141 for (i, n) in graph.nodes.iter().enumerate() {
1142 if !n.id.is_valid_syntax() {
1143 d.push(Diagnostic::error(
1144 crate::codes::ID_SYNTAX,
1145 "layout-graph",
1146 format!("/content/nodes/{i}/id"),
1147 format!(
1148 "malformed node id `{}` — a place is named `node/<kebab-case>`.",
1149 n.id
1150 ),
1151 ));
1152 }
1153 if !seen_nodes.insert(n.id.0.as_str()) {
1154 d.push(Diagnostic::error(
1155 DW_GRAPH_MALFORMED,
1156 "layout-graph",
1157 format!("/content/nodes/{i}/id"),
1158 format!(
1159 "duplicate node id `{}` — two places cannot share a name, because every \
1160 edge, beat and critical-path step that names it would then name both.",
1161 n.id
1162 ),
1163 ));
1164 }
1165 if n.intent.trim().is_empty() {
1166 d.push(Diagnostic::error(
1167 DW_GRAPH_MALFORMED,
1168 "layout-graph",
1169 format!("/content/nodes/{i}/intent"),
1170 format!(
1171 "place `{}` declares an empty `intent` — no check keys on this label, which \
1172 is exactly why it has to be written: it is the recorded judgement a \
1173 reviewer and the later per-place brief read.",
1174 n.id
1175 ),
1176 ));
1177 }
1178 }
1179 let mut seen_edges: BTreeSet<&str> = BTreeSet::new();
1180 for (i, e) in graph.edges.iter().enumerate() {
1181 if !e.id().is_valid_syntax() {
1182 d.push(Diagnostic::error(
1183 crate::codes::ID_SYNTAX,
1184 "layout-graph",
1185 format!("/content/edges/{i}/id"),
1186 format!(
1187 "malformed edge id `{}` — a connection is named `edge/<kebab-case>`.",
1188 e.id()
1189 ),
1190 ));
1191 }
1192 if !seen_edges.insert(e.id().0.as_str()) {
1193 d.push(Diagnostic::error(
1194 DW_GRAPH_MALFORMED,
1195 "layout-graph",
1196 format!("/content/edges/{i}/id"),
1197 format!(
1198 "duplicate edge id `{}` — rename one, because a seam is allocated per edge \
1199 and two edges of one name would allocate one seam between them.",
1200 e.id()
1201 ),
1202 ));
1203 }
1204 for (end, node) in [("a", e.a()), ("b", e.b())] {
1205 if !known.contains(node.0.as_str()) {
1206 d.push(Diagnostic::error(
1207 DW_GRAPH_MALFORMED,
1208 "layout-graph",
1209 format!("/content/edges/{i}/{end}"),
1210 format!(
1211 "connection `{}` ends at `{node}`, which is not a declared place — \
1212 declare that node, or point the end at one of the {n} that exist.",
1213 e.id(),
1214 n = known.len(),
1215 ),
1216 ));
1217 }
1218 }
1219 if e.a() == e.b() {
1220 d.push(Diagnostic::error(
1221 DW_GRAPH_MALFORMED,
1222 "layout-graph",
1223 format!("/content/edges/{i}"),
1224 format!(
1225 "connection `{}` has both ends in `{}` — a self-loop states nothing a place \
1226 does not already state, at every class, so it is refused rather than \
1227 silently carried into a seam allocation with no face to sit on.",
1228 e.id(),
1229 e.a(),
1230 ),
1231 ));
1232 }
1233 }
1234 for (field, node) in [("entry", &graph.entry), ("goal", &graph.goal)] {
1235 if !known.contains(node.0.as_str()) {
1236 d.push(Diagnostic::error(
1237 DW_GRAPH_MALFORMED,
1238 "layout-graph",
1239 format!("/content/{field}"),
1240 format!(
1241 "`{field}` names `{node}`, which is not a declared place — every proof over \
1242 this graph starts or ends there, so it cannot be a name nothing defines."
1243 ),
1244 ));
1245 }
1246 }
1247 for (i, node) in graph.critical_path.iter().enumerate() {
1248 if !known.contains(node.0.as_str()) {
1249 d.push(Diagnostic::error(
1250 DW_GRAPH_MALFORMED,
1251 "layout-graph",
1252 format!("/content/critical_path/{i}"),
1253 format!("the critical path steps through `{node}`, which is not a declared place."),
1254 ));
1255 }
1256 }
1257 for (i, beat) in graph.beats.iter().enumerate() {
1258 if !known.contains(beat.node.0.as_str()) {
1259 d.push(Diagnostic::error(
1260 DW_GRAPH_MALFORMED,
1261 "layout-graph",
1262 format!("/content/beats/{i}/node"),
1263 format!(
1264 "beat `{q}` / `{o}` happens in `{n}`, which is not a declared place.",
1265 q = beat.quest,
1266 o = beat.objective,
1267 n = beat.node,
1268 ),
1269 ));
1270 }
1271 }
1272 d.len() != before
1273}
1274
1275/// `DW0812`: every place classification names an entry the metrics table
1276/// defines — a rung of the size ladder, or a way class (spec-0053 §3).
1277///
1278/// One loop over both fields rather than a second function for the second kind:
1279/// `Metrics::resolve` is the one path from an authored name to an entry, and the
1280/// question "does the table define this" is the same question whichever
1281/// vocabulary the name is from. `DW0875` is what makes at most one of the two
1282/// arms fire per node; this rule does not depend on that and does not restate
1283/// it — a node that wrongly declares both AND misspells both is told both names
1284/// are unknown, which is true.
1285fn metric_names(graph: &LayoutGraphContent, table: &Metrics, d: &mut Vec<Diagnostic>) {
1286 for (i, n) in graph.nodes.iter().enumerate() {
1287 for (field, kind, named) in [
1288 ("size_class", MetricKind::SizeClass, n.size_class.as_ref()),
1289 ("way_class", MetricKind::WayClass, n.way_class.as_ref()),
1290 ] {
1291 let Some(named) = named else { continue };
1292 if let Err(unknown) = table.resolve(kind, named) {
1293 d.push(unknown.diagnostic("layout-graph", &format!("/content/nodes/{i}/{field}")));
1294 }
1295 }
1296 }
1297}
1298
1299/// **`DW0875`**: a place is classified exactly once
1300/// (spec-0053 §6).
1301///
1302/// Runs before the malformed-graph return for the reason [`stations`] does: the
1303/// rule reads one node's own two fields and needs no id to resolve, so a graph
1304/// with a dangling edge still gets told which of its places has no standard.
1305fn place_classes(graph: &LayoutGraphContent, table: &Metrics, d: &mut Vec<Diagnostic>) {
1306 let sizes = table.names_of(MetricKind::SizeClass).join(", ");
1307 let ways = table.names_of(MetricKind::WayClass).join(", ");
1308
1309 for (i, n) in graph.nodes.iter().enumerate() {
1310 let (size, way) = (n.size_class.as_ref(), n.way_class.as_ref());
1311 let (both, neither) = (
1312 size.is_some() && way.is_some(),
1313 size.is_none() && way.is_none(),
1314 );
1315 if !both && !neither {
1316 continue;
1317 }
1318 let (found, prescription) = if both {
1319 (
1320 format!(
1321 "declares BOTH `size_class: \"{s}\"` and `way_class: \"{w}\"`",
1322 s = size.expect("both"),
1323 w = way.expect("both"),
1324 ),
1325 "delete whichever one this place is not. A size class bounds a footprint on \
1326 both horizontal axes and a way class bounds a cross-section and leaves the \
1327 run free, so they are two different questions about the same box and every \
1328 geometric rule below would have to pick between them with no rule to pick \
1329 by"
1330 .to_string(),
1331 )
1332 } else {
1333 (
1334 "declares neither `size_class` nor `way_class`".to_string(),
1335 format!(
1336 "give it one. A place with no standard is a place nothing can judge — \
1337 `DW0832` has nothing to hold its extents to and the pacing projection \
1338 has nothing to cross it in. Defined size classes: {sizes}. Defined way \
1339 classes: {ways}",
1340 sizes = sizes,
1341 ways = ways,
1342 ),
1343 )
1344 };
1345 d.push(Diagnostic::error(
1346 DW_PLACE_CLASS,
1347 "layout-graph",
1348 format!("/content/nodes/{i}"),
1349 format!(
1350 "`{node}` {found} — a place is classified exactly once. To fix it, \
1351 {prescription}.",
1352 node = n.id,
1353 ),
1354 ));
1355 }
1356}
1357
1358/// `DW0818`: the graph and the mission agree, in both directions.
1359fn mission(c: &Campaign, graph: &LayoutGraphContent, d: &mut Vec<Diagnostic>) {
1360 let quests: BTreeMap<&str, BTreeSet<&str>> = c
1361 .quests
1362 .content
1363 .quests
1364 .iter()
1365 .map(|q| {
1366 (
1367 q.id.0.as_str(),
1368 q.objectives.iter().map(|o| o.id().0.as_str()).collect(),
1369 )
1370 })
1371 .collect();
1372 let produced = crate::validate::produced_flags(c);
1373
1374 // **Stage 5 being empty is not a graph mistake.** It is the ordinary state
1375 // of a campaign whose plan is written and whose quests are not — the state
1376 // `DW0150` names — and in it EVERY name the graph borrows from the mission
1377 // is absent, so every such refusal says the same thing and none of them is
1378 // the finding. Without this clause a finished layout graph reports a fault
1379 // per beat and per gated way, in a document the author completed two steps
1380 // ago, at exactly the moment they are being told to loop validation until
1381 // it is clean.
1382 //
1383 // It is attached to every refusal in this function that reads the stage-5
1384 // quest list, not to the one that was noticed: a beat and a gated
1385 // connection are the same borrowing, and a clause on one of them would be
1386 // the narrow binding this codebase keeps finding.
1387 let unwritten = if quests.is_empty() {
1388 " Stage 5 declares no quests at all here, so everything this graph borrows from the \
1389 mission is missing, every one of these lines says the same thing, and none of them is \
1390 the finding: see `DW0150`, which names that state. This clears when stage 5 is written."
1391 } else {
1392 ""
1393 };
1394
1395 // Direction one: nothing the graph names may be absent from the mission.
1396 let mut bound: BTreeMap<(&str, &str), usize> = BTreeMap::new();
1397 for (i, beat) in graph.beats.iter().enumerate() {
1398 match quests.get(beat.quest.0.as_str()) {
1399 None => d.push(Diagnostic::error(
1400 DW_GRAPH_MISSION,
1401 "layout-graph",
1402 format!("/content/beats/{i}/quest"),
1403 format!(
1404 "beat names quest `{}`, which the quest documents do not declare — the graph \
1405 says where the mission happens, so it can only name beats the mission \
1406 has.{unwritten}",
1407 beat.quest,
1408 ),
1409 )),
1410 Some(objectives) if !objectives.contains(beat.objective.0.as_str()) => {
1411 d.push(Diagnostic::error(
1412 DW_GRAPH_MISSION,
1413 "layout-graph",
1414 format!("/content/beats/{i}/objective"),
1415 format!(
1416 "beat names objective `{o}`, which quest `{q}` does not declare.",
1417 o = beat.objective,
1418 q = beat.quest,
1419 ),
1420 ));
1421 }
1422 Some(_) => {
1423 *bound
1424 .entry((beat.quest.0.as_str(), beat.objective.0.as_str()))
1425 .or_default() += 1;
1426 }
1427 }
1428 }
1429 for (i, e) in graph.edges.iter().enumerate() {
1430 let Some(g) = e.gating() else { continue };
1431 for (k, f) in g.flags.iter().enumerate() {
1432 if !produced.contains(f.0.as_str()) {
1433 d.push(Diagnostic::error(
1434 DW_GRAPH_MISSION,
1435 "layout-graph",
1436 format!("/content/edges/{i}/gating/flags/{k}"),
1437 format!(
1438 "connection `{e_id}` waits on flag `{f}`, which no `set-flag` effect ever \
1439 produces — a body could never hold it, so the connection is a wall \
1440 wearing a gate's clothes. Produce the flag, or gate on one the campaign \
1441 really sets.",
1442 e_id = e.id(),
1443 ),
1444 ));
1445 }
1446 }
1447 if let Some(q) = &g.quest
1448 && !quests.contains_key(q.0.as_str())
1449 {
1450 d.push(Diagnostic::error(
1451 DW_GRAPH_MISSION,
1452 "layout-graph",
1453 format!("/content/edges/{i}/gating/quest"),
1454 format!(
1455 "connection `{e_id}` waits on quest `{q}`, which the quest documents do not \
1456 declare.{unwritten}",
1457 e_id = e.id(),
1458 ),
1459 ));
1460 }
1461 if matches!(e, Edge::Carry { .. }) && g.is_empty() {
1462 d.push(Diagnostic::error(
1463 DW_GRAPH_MISSION,
1464 "layout-graph",
1465 format!("/content/edges/{i}/gating"),
1466 format!(
1467 "carry connection `{e_id}` says nothing about what makes it carry. A carry \
1468 with an empty `gating` is live from world load, which leaves a hole in the \
1469 graph's own claim; name the flag or the quest whose completion arms the \
1470 link that realises it.",
1471 e_id = e.id(),
1472 ),
1473 ));
1474 }
1475 if matches!(e, Edge::Barred { .. }) && g.is_empty() {
1476 d.push(Diagnostic::error(
1477 DW_GRAPH_MISSION,
1478 "layout-graph",
1479 format!("/content/edges/{i}/gating"),
1480 format!(
1481 "barred connection `{e_id}` says nothing about what opens it. A barred way \
1482 with an empty `gating` is passable from world load, which is not barred; \
1483 name the flag or the quest whose completion opens it, and `DW0818` then \
1484 holds that name to something the campaign really produces.",
1485 e_id = e.id(),
1486 ),
1487 ));
1488 }
1489 }
1490
1491 // Direction two — the ordering tooth. Once a mission exists, every beat of
1492 // it has a place. This is what stops a graph arriving after the quests and
1493 // ignoring them, and it is why *graph before mission* is representable
1494 // without being silently green (spec-0049 §7).
1495 for q in &c.quests.content.quests {
1496 for (oi, obj) in q.objectives.iter().enumerate() {
1497 let n = bound
1498 .get(&(q.id.0.as_str(), obj.id().0.as_str()))
1499 .copied()
1500 .unwrap_or(0);
1501 if n == 0 {
1502 d.push(Diagnostic::error(
1503 DW_GRAPH_MISSION,
1504 "quests",
1505 format!(
1506 "/content/quests/{qi}/objectives/{oi}",
1507 qi = quest_index(c, q)
1508 ),
1509 format!(
1510 "objective `{o}` of quest `{q}` happens somewhere and the layout graph \
1511 does not say where. Every objective is place-bound — a body has to be \
1512 standing somewhere to talk, to reach, to fight or to take — so add a \
1513 `beats[]` entry binding it to a node. This is the direction that keeps \
1514 space and mission from silently disagreeing: a graph may be authored \
1515 before the quests, never in ignorance of them.",
1516 o = obj.id(),
1517 q = q.id,
1518 ),
1519 ));
1520 } else if n > 1 {
1521 d.push(Diagnostic::error(
1522 DW_GRAPH_MISSION,
1523 "layout-graph",
1524 "/content/beats",
1525 format!(
1526 "objective `{o}` of quest `{q}` is bound to {n} places. A beat happens in \
1527 exactly one place; two bindings make every proof over this graph pick \
1528 one of them and no rule says which.",
1529 o = obj.id(),
1530 q = q.id,
1531 ),
1532 ));
1533 }
1534 }
1535 }
1536}
1537
1538/// The index of a quest in the stage-5 document, for a diagnostic's path.
1539fn quest_index(c: &Campaign, q: &crate::stages::Quest) -> usize {
1540 c.quests
1541 .content
1542 .quests
1543 .iter()
1544 .position(|x| std::ptr::eq(x, q))
1545 .unwrap_or(0)
1546}
1547
1548/// `DW0820`: a shortcut lies on a cycle.
1549fn shortcut_loops(graph: &LayoutGraphContent, d: &mut Vec<Diagnostic>) {
1550 for (i, e) in graph.edges.iter().enumerate() {
1551 if !e.shortcut() {
1552 continue;
1553 }
1554 if connected_without(graph, e.id(), e.a(), e.b()) {
1555 continue;
1556 }
1557 d.push(Diagnostic::error(
1558 DW_SHORTCUT_NO_LOOP,
1559 "layout-graph",
1560 format!("/content/edges/{i}/shortcut"),
1561 format!(
1562 "connection `{e_id}` is marked a shortcut and closes no loop: with it removed, \
1563 `{a}` and `{b}` are no longer connected at all. A shortcut is the way back into \
1564 ground a body has already crossed, so an edge that is the ONLY way between its \
1565 two places is a corridor wearing a shortcut's name. Either drop the mark, or add \
1566 the long way round it is meant to shorten.",
1567 e_id = e.id(),
1568 a = e.a(),
1569 b = e.b(),
1570 ),
1571 ));
1572 }
1573}
1574
1575/// Undirected connectivity between two places over every traversal edge but
1576/// `skip`. Direction-blind and gating-blind on purpose: the loop a shortcut
1577/// closes is **spatial**, and a long way round that is gated is still the long
1578/// way round.
1579fn connected_without(graph: &LayoutGraphContent, skip: &EdgeId, a: &NodeId, b: &NodeId) -> bool {
1580 let mut seen: BTreeSet<&str> = BTreeSet::new();
1581 let mut stack = vec![a.0.as_str()];
1582 seen.insert(a.0.as_str());
1583 while let Some(at) = stack.pop() {
1584 if at == b.0.as_str() {
1585 return true;
1586 }
1587 for e in &graph.edges {
1588 if !e.is_traversal() || e.id() == skip {
1589 continue;
1590 }
1591 let (x, y) = (e.a().0.as_str(), e.b().0.as_str());
1592 let other = if x == at {
1593 y
1594 } else if y == at {
1595 x
1596 } else {
1597 continue;
1598 };
1599 if seen.insert(other) {
1600 stack.push(other);
1601 }
1602 }
1603 }
1604 false
1605}
1606
1607/// `DW0822`: the pacing projection, printed with **no threshold**.
1608///
1609/// # A way leg is measured, never looked up
1610///
1611/// A size class carries a `nominal_traverse_blocks` because a rung bounds both
1612/// horizontal extents, so the ladder can say what crossing one costs. A way
1613/// class cannot: it bounds the cross-section and leaves the run free, which is
1614/// what makes it a way. So a way leg's traverse is **the box's long horizontal
1615/// extent** — a real number read off the plan — and there is no
1616/// `nominal_traverse_blocks` on a way class to read instead. That absence is the
1617/// design: a route's length is per-campaign geometry and never a standard
1618/// (spec-0053 §7), and a nominal length here would be a standard for exactly the
1619/// thing this vocabulary exists to stop standardizing.
1620///
1621/// Where the campaign carries **no site plan**, a way leg has no geometry yet
1622/// and the projection says so: the leg is counted as **unprojected** in the
1623/// line's own binding rather than being given an invented number. A campaign
1624/// with a graph and no plan is a real and intended state — the
1625/// graph is authored before the embedding — so this is the ordinary case for a
1626/// way and not a fault. Every other leg still projects, and the figure printed
1627/// is honest about what it left out.
1628fn pacing(
1629 c: &Campaign,
1630 graph: &LayoutGraphContent,
1631 table: &Metrics,
1632 reads: &mut Reads,
1633 d: &mut Vec<Diagnostic>,
1634) {
1635 // The plan's boxes, when there is a plan. `DW0824` is what holds this to one
1636 // box per place; a lookup that finds nothing here is a campaign the graph
1637 // stage is looking at before the plan stage exists, which is legal.
1638 let runs: BTreeMap<&str, u64> = c
1639 .site_plan
1640 .as_ref()
1641 .map(|p| {
1642 p.content
1643 .boxes
1644 .iter()
1645 .map(|b| {
1646 let (dx, dz) = (u64::from(b.extent[0].get()), u64::from(b.extent[1].get()));
1647 (b.node.0.as_str(), dx.max(dz))
1648 })
1649 .collect()
1650 })
1651 .unwrap_or_default();
1652
1653 let mut blocks: u64 = 0;
1654 let mut legs = 0usize;
1655 let mut unprojected: Vec<String> = Vec::new();
1656 for node_id in &graph.critical_path {
1657 let Some(node) = graph.nodes.iter().find(|n| &n.id == node_id) else {
1658 continue;
1659 };
1660 if let Some(way) = node.way_class.as_ref() {
1661 // The resolve is still made, and still recorded: the way class is a
1662 // standard this verdict rests on even though the number crossed is
1663 // measured, because whether this box is a way AT ALL is the class's
1664 // judgement (`DW0832`). A name the table does not define is already
1665 // `DW0812`'s.
1666 let Ok(entry) = table.resolve(MetricKind::WayClass, way) else {
1667 continue;
1668 };
1669 let _ = entry.value(reads);
1670 match runs.get(node_id.0.as_str()) {
1671 Some(run) => {
1672 blocks += *run;
1673 legs += 1;
1674 }
1675 None => unprojected.push(format!("`{node_id}`")),
1676 }
1677 continue;
1678 }
1679 let Some(size) = node.size_class.as_ref() else {
1680 continue; // `DW0875` already refused a place with no classification.
1681 };
1682 let Ok(entry) = table.resolve(MetricKind::SizeClass, size) else {
1683 continue; // `DW0812` already refused the name.
1684 };
1685 if let crate::metrics::MetricValue::SizeClass(sc) = entry.value(reads) {
1686 blocks += u64::from(sc.nominal_traverse_blocks);
1687 legs += 1;
1688 }
1689 }
1690 let Ok(per_minute) = table.resolve(MetricKind::Pacing, "route-blocks-per-minute") else {
1691 return;
1692 };
1693 let crate::metrics::MetricValue::Count(rate) = per_minute.value(reads) else {
1694 return;
1695 };
1696 let rate = u64::from(*rate).max(1);
1697 d.push(Diagnostic::warning(
1698 DW_PACING,
1699 "layout-graph",
1700 "/content/critical_path",
1701 format!(
1702 "the critical path crosses {legs} place(s) over {steps} step(s), a nominal \
1703 {blocks} blocks of route, which at {rate} blocks of route per minute of play \
1704 projects to about {minutes} minute(s) against this world's `target_minutes` of \
1705 {target}{un}. It carries no threshold and refuses nothing — see `DW0822` in \
1706 `docs/reference/compiler.md` for what the number is worth.",
1707 steps = graph.critical_path.len().saturating_sub(1),
1708 minutes = blocks.div_ceil(rate),
1709 target = c.world.content.target_minutes,
1710 un = if unprojected.is_empty() {
1711 String::new()
1712 } else {
1713 format!(
1714 ", with {n} way leg(s) UNPROJECTED and not in that total ({names}) — a way \
1715 class bounds a cross-section and leaves the run free, so what crossing one \
1716 costs is its box's long extent and this campaign has no site plan to read \
1717 it from yet. Embedding the graph is what projects them; nothing is wrong \
1718 here",
1719 n = unprojected.len(),
1720 names = unprojected.join(", "),
1721 )
1722 },
1723 ),
1724 ));
1725}
1726
1727// ---------------------------------------------------------------------------
1728// Reachability (spec-0049 §3.3): DW0816, DW0817, DW0819
1729// ---------------------------------------------------------------------------
1730
1731/// The graph's reachability proofs — a place a body can never reach
1732/// (`DW0816`), an authored critical path that does not hold (`DW0817`), and a
1733/// one-way connection that strands (`DW0819`).
1734///
1735/// # Why this runs at VALIDATION tier
1736///
1737/// It used to be raised from `compiler::analyze::analyze_campaign`, on the
1738/// argument that a tier is decided by the pass that raises it and these are
1739/// reachability questions like `DW0202`–`DW0204`. The argument sorts the check
1740/// by its KIND; what decides a tier here is when the check can fire, and by
1741/// that measure it was unreachable at the step it exists for. `delvec analyze`
1742/// returns at the first validation-tier error, and a campaign at the graph step
1743/// carries `DW0150` by construction — the plan is written and stage 5 is not —
1744/// so **no verb raised these proofs until stage 5 was written**, which is after
1745/// the design gate and after the expensive authoring the gate exists to
1746/// protect. spec-0049 §3 is explicit that the graph is checked "cheaply, before
1747/// geometry exists to make it expensive"; a proof that first fires two steps
1748/// later is not that.
1749///
1750/// Nothing here reads geometry: the whole battery is a function of the campaign
1751/// documents, which is why it can move. Called from [`check`] and from nowhere
1752/// else, so there is one battery in one place and no second copy of any rule; a
1753/// campaign with no layout graph returns nothing and [`LayoutBinding`] states
1754/// that zero.
1755#[must_use]
1756pub fn reachability(c: &Campaign) -> Vec<Diagnostic> {
1757 let mut d = Vec::new();
1758 let Some(graph) = c.layout_graph.as_ref().map(|g| &g.content) else {
1759 return d;
1760 };
1761 let known: BTreeSet<&str> = graph.nodes.iter().map(|n| n.id.0.as_str()).collect();
1762 if !known.contains(graph.entry.0.as_str()) {
1763 return d; // `DW0814` refused it; a closure from nowhere says nothing.
1764 }
1765 let grants = Grants::of(c, graph);
1766 let closure = Closure::run(graph, &grants);
1767 let caveat = unwritten_mission_caveat(c, graph);
1768 unreached(graph, &closure, caveat, &mut d);
1769 critical_path(c, graph, &grants, caveat, &mut d);
1770 strands(graph, &closure, caveat, &mut d);
1771 d
1772}
1773
1774/// The caveat a reachability refusal owes while **stage 5 is unwritten**.
1775///
1776/// [`Closure`] reads the mission for its flag grants ([`Grants::of`]), so a
1777/// campaign between the plan and the quests has no `set-flag` anywhere and every
1778/// flag-gated way in its graph is shut to this proof. Now that the battery runs
1779/// at validation tier that state is the ordinary one at the graph step, and
1780/// without this the proof reports a fault in a document the author finished two
1781/// steps ago and cannot yet answer. `mission` says the same thing about
1782/// `DW0818` in its own words and for the same reason; the shared authority is
1783/// the PREDICATE below, not the wording, because the two consequences differ.
1784///
1785/// A quest-gated way is NOT affected: `Grants::of` credits a quest once every
1786/// one of its beats sits at a reached place, and beats are the graph's own
1787/// document. Only `gating.flags` needs an effect stage 5 has not written.
1788///
1789/// It is a CAVEAT and never a dismissal. A place can be unreached, a path can
1790/// fail to be a path and a drop can strand for reasons the mission has nothing
1791/// to do with, and every one of those is a finding now — so it is attached only
1792/// where the mission's absence could be the cause (a graph that gates on a flag
1793/// at all) and it says which half is which.
1794fn unwritten_mission_caveat(c: &Campaign, graph: &LayoutGraphContent) -> &'static str {
1795 let gates_on_a_flag = graph
1796 .edges
1797 .iter()
1798 .any(|e| e.gating().is_some_and(|g| !g.flags.is_empty()));
1799 if c.quests.content.quests.is_empty() && gates_on_a_flag {
1800 " Stage 5 declares no quests here, so no `set-flag` effect exists yet and every \
1801 flag-gated way in this graph is shut to this proof: a place behind one is closed off \
1802 for that reason alone and opens when stage 5 is written (see `DW0150`). Anything \
1803 unreached for any OTHER reason is a real finding now, and this line does not say which \
1804 of the two you are looking at — the graph does."
1805 } else {
1806 ""
1807 }
1808}
1809
1810/// `DW0816`: a node the closure never reaches.
1811fn unreached(graph: &LayoutGraphContent, closure: &Closure, caveat: &str, d: &mut Vec<Diagnostic>) {
1812 for (i, n) in graph.nodes.iter().enumerate() {
1813 if closure.reached.contains(n.id.0.as_str()) {
1814 continue;
1815 }
1816 let near = graph
1817 .edges
1818 .iter()
1819 .filter(|e| e.is_traversal())
1820 .find_map(|e| {
1821 let (a, b) = (e.a().0.as_str(), e.b().0.as_str());
1822 if a == n.id.0 && closure.reached.contains(b) {
1823 Some(b)
1824 } else if b == n.id.0 && closure.reached.contains(a) {
1825 Some(a)
1826 } else {
1827 None
1828 }
1829 });
1830 let hint = match near {
1831 Some(other) => format!(
1832 "the nearest place a body can stand is `{other}`, so the missing link is between \
1833 those two — either its gating demands something no reached beat grants, or it \
1834 runs one way and the wrong way"
1835 ),
1836 None => "no connection reaches it from anywhere a body can stand at all".to_string(),
1837 };
1838 d.push(Diagnostic::error(
1839 DW_NODE_UNREACHED,
1840 "layout-graph",
1841 format!("/content/nodes/{i}"),
1842 format!(
1843 "place `{id}` is never reached: {hint}. Of the {total} place(s) this graph \
1844 declares, {n} are reachable from `{entry}` under the campaign's own \
1845 gating.{caveat}",
1846 id = n.id,
1847 total = graph.nodes.len(),
1848 n = closure.reached.len(),
1849 entry = graph.entry,
1850 ),
1851 ));
1852 }
1853}
1854
1855/// `DW0817`: the authored critical path holds.
1856fn critical_path(
1857 c: &Campaign,
1858 graph: &LayoutGraphContent,
1859 grants: &Grants,
1860 caveat: &str,
1861 d: &mut Vec<Diagnostic>,
1862) {
1863 let path = &graph.critical_path;
1864 let mut fault = |path_suffix: &str, msg: String| {
1865 d.push(Diagnostic::error(
1866 DW_CRITICAL_PATH,
1867 "layout-graph",
1868 format!("/content/critical_path{path_suffix}"),
1869 msg,
1870 ));
1871 };
1872 if path.first() != Some(&graph.entry) || path.last() != Some(&graph.goal) {
1873 fault(
1874 "",
1875 format!(
1876 "the critical path must run from `{entry}` to `{goal}`; it runs from {from} to \
1877 {to}. It is authored rather than derived precisely so that it is a claim, and a \
1878 claim that does not start where a body starts is not one.",
1879 entry = graph.entry,
1880 goal = graph.goal,
1881 from = path.first().map_or("nowhere".into(), |n| format!("`{n}`")),
1882 to = path.last().map_or("nowhere".into(), |n| format!("`{n}`")),
1883 ),
1884 );
1885 }
1886 // Stepwise: each step is a real connection, run the right way, and openable
1887 // with what the beats already visited have granted.
1888 let mut held: BTreeSet<Grant> = BTreeSet::new();
1889 let mut visited: BTreeSet<&str> = BTreeSet::new();
1890 let mut steps = 0usize;
1891 for (i, pair) in path.windows(2).enumerate() {
1892 let (from, to) = (&pair[0], &pair[1]);
1893 visited.insert(from.0.as_str());
1894 collect_grants(grants, &visited, &mut held);
1895 let edge = graph.edges.iter().find(|e| {
1896 e.is_traversal()
1897 && ((e.a() == from && e.b() == to && e.direction() != Some(Direction::BToA))
1898 || (e.b() == from && e.a() == to && e.direction() != Some(Direction::AToB)))
1899 });
1900 match edge {
1901 None => fault(
1902 &format!("/{}", i + 1),
1903 format!(
1904 "the critical path steps from `{from}` to `{to}` and no connection runs that \
1905 way. Either the two places share no edge at all, or the one they share runs \
1906 the other way."
1907 ),
1908 ),
1909 Some(e) if !Closure::satisfied(e.gating(), &held) => {
1910 // The caveat rides only the GATING fault. A step with no
1911 // connection at all, a path that does not run entry to goal and
1912 // a missed spine beat are judgements about the graph alone, and
1913 // an unwritten mission has nothing to say about any of them.
1914 let unwritten = if e.gating().is_some_and(|g| !g.flags.is_empty()) {
1915 caveat
1916 } else {
1917 ""
1918 };
1919 fault(
1920 &format!("/{}", i + 1),
1921 format!(
1922 "the critical path steps from `{from}` to `{to}` over `{e_id}`, which is \
1923 not open yet at that point in the walk: nothing bound to the {v} \
1924 place(s) already visited grants what it waits on. Move the beat that \
1925 opens it earlier on the path, or route the path through the place that \
1926 grants it.{unwritten}",
1927 e_id = e.id(),
1928 v = visited.len(),
1929 ),
1930 );
1931 }
1932 Some(_) => {}
1933 }
1934 steps += 1;
1935 }
1936 if let Some(last) = path.last() {
1937 visited.insert(last.0.as_str());
1938 }
1939 // The spine obligation, and the zero binding that goes with it.
1940 let spine = c.quest_plan.content.spine();
1941 let mut required = 0usize;
1942 for beat in &graph.beats {
1943 if !spine.contains(beat.quest.0.as_str()) {
1944 continue;
1945 }
1946 required += 1;
1947 if !visited.contains(beat.node.0.as_str()) {
1948 fault(
1949 "",
1950 format!(
1951 "beat `{q}` / `{o}` happens in `{n}`, which the critical path never visits — \
1952 and `{q}` is on the mandatory spine, so a body walking this path would reach \
1953 the goal without doing it.",
1954 q = beat.quest,
1955 o = beat.objective,
1956 n = beat.node,
1957 ),
1958 );
1959 }
1960 }
1961 // The binding is STATED, not raised. `delvec analyze` exits 2 on any reported
1962 // diagnostic, warning or error alike, so a "this bound to nothing" line here
1963 // would turn a green analyze red — a count is not a fault. It lives in
1964 // [`LayoutBinding`] instead, which every run prints and which flags the zero
1965 // as a finding, and `steps` and `required` are quoted in the faults above so
1966 // a red says what it examined.
1967 let _ = (steps, required);
1968}
1969
1970/// Everything the places visited so far have granted.
1971fn collect_grants(grants: &Grants, visited: &BTreeSet<&str>, held: &mut BTreeSet<Grant>) {
1972 for (node, given) in &grants.by_node {
1973 if visited.contains(node.as_str()) {
1974 held.extend(given.iter().cloned());
1975 }
1976 }
1977 for (quest, (nodes, given)) in &grants.by_quest {
1978 if nodes.iter().all(|n| visited.contains(n.as_str())) {
1979 held.insert(Grant::Quest(quest.clone()));
1980 held.extend(given.iter().cloned());
1981 }
1982 }
1983}
1984
1985/// `DW0819`: a one-way edge strands.
1986fn strands(graph: &LayoutGraphContent, closure: &Closure, caveat: &str, d: &mut Vec<Diagnostic>) {
1987 let spine: BTreeSet<&str> = graph.critical_path.iter().map(|n| n.0.as_str()).collect();
1988 for (i, e) in graph.edges.iter().enumerate() {
1989 if !e.is_traversal() {
1990 continue;
1991 }
1992 let Some(dir) = e.direction() else { continue };
1993 let (from, to) = match dir {
1994 Direction::AToB => (e.a(), e.b()),
1995 Direction::BToA => (e.b(), e.a()),
1996 };
1997 // A body can only be at `to` having been at `from`, holding at most what
1998 // it held on arriving at `from`.
1999 let Some(held) = closure.obtained_when.get(from.0.as_str()) else {
2000 continue; // `from` is unreachable; `DW0816` owns that.
2001 };
2002 if rejoins(graph, to, held, &spine) {
2003 continue;
2004 }
2005 d.push(Diagnostic::error(
2006 DW_ONE_WAY_STRANDS,
2007 "layout-graph",
2008 format!("/content/edges/{i}"),
2009 format!(
2010 "connection `{e_id}` runs one way from `{from}` into `{to}`, and from `{to}` \
2011 there is no way back to the critical path. A body can only be in `{to}` having \
2012 taken this connection, so a walk that takes it is a softlock. Add a way out of \
2013 `{to}` — the shortcut back is the usual one — or make the connection \
2014 two-way.{caveat}",
2015 e_id = e.id(),
2016 ),
2017 ));
2018 }
2019}
2020
2021/// Can a body standing at `at`, holding `held`, get back to the spine?
2022fn rejoins(
2023 graph: &LayoutGraphContent,
2024 at: &NodeId,
2025 held: &BTreeSet<Grant>,
2026 spine: &BTreeSet<&str>,
2027) -> bool {
2028 let mut seen: BTreeSet<&str> = BTreeSet::new();
2029 let mut stack = vec![at.0.as_str()];
2030 seen.insert(at.0.as_str());
2031 while let Some(here) = stack.pop() {
2032 if spine.contains(here) {
2033 return true;
2034 }
2035 for e in &graph.edges {
2036 if !e.is_traversal() || !Closure::satisfied(e.gating(), held) {
2037 continue;
2038 }
2039 let (a, b) = (e.a().0.as_str(), e.b().0.as_str());
2040 let next = if a == here && e.direction() != Some(Direction::BToA) {
2041 b
2042 } else if b == here && e.direction() != Some(Direction::AToB) {
2043 a
2044 } else {
2045 continue;
2046 };
2047 if seen.insert(next) {
2048 stack.push(next);
2049 }
2050 }
2051 }
2052 false
2053}