delvewright_dsl/l10n.rs
1//! Native i18n: author-declared languages, l10n sidecar documents, the
2//! authoritative key inventory, and the localization pass (spec-0001 i18n
3//! addendum).
4//!
5//! **English is canonical.** Stage docs stay pure English; the strings the
6//! compiler emits to players come from the stage docs. A campaign that declares
7//! `world.languages = ["<code>", …]` must ship one `l10n/<code>.json` sidecar per
8//! declared language, each a flat map of **stable key → translated string**.
9//!
10//! The **key inventory** ([`inventory`]) is derived deterministically from the
11//! stage docs; it is the single source of truth for both coverage validation
12//! ([`validate_l10n`]) and the build-time swap ([`localize`]). Both walk the exact
13//! same traversal ([`each_string`]), so a key can never be checked but not applied
14//! (or vice-versa).
15//!
16//! ## Key scheme (stable, path-derived, collision-free)
17//!
18//! Keys are dotted paths built from the local part of each DSL id (the segment
19//! after `<prefix>/`, kebab preserved). Ids are unique within their namespace, so
20//! every key is unique.
21//!
22//! | Key | Source string |
23//! |-----|---------------|
24//! | `world.title` | stage-1 `content.title` |
25//! | `area.<area>.name` | each stage-1 area `name` |
26//! | `class.<class>.name` / `.blurb` | each stage-3 class |
27//! | `class.<class>.kit.<i>.name` | a kit item's display `name` (only if set) |
28//! | `npc.<npc>.name` | each stage-2 NPC `name` (see *entity display names* below) |
29//! | `actor.<actor>.name` | each stage-5 actor `name` (v0.6, only if set; see below) |
30//! | `quest.<quest>.goal` | each stage-4 planned-quest `goal` |
31//! | `obj.<quest>.<obj>.title` / `.hint` | a stage-5 objective's `title`/`hint` (only if set) |
32//! | `obj.<quest>.<obj>.missing_item_hint` | a stage-5 `interact`'s `missing_item_hint` (v0.7, only if set) |
33//! | `obj.<quest>.<obj>.item_name` | a stage-5 `collect`'s `item_name` (v0.8, only if set) |
34//! | `dlg.<npc>.<node>.text` | each stage-6 dialogue node `text` |
35//! | `dlg.<npc>.<node>.opt.<i>.label` | each dialogue option `label` |
36//! | `dlg.<npc>.<node>.opt.<i>.tooltip` | that option's hover `tooltip` (v0.8, only if set) |
37//! | `wave.<wave>.mob.<i>.name` | a wave mob's custom `name` (only if set) |
38//! | `wave.<wave>.mob.<i>.drop.<n>.name` | a declared quest-item drop's display `name` (v0.9, only if set) |
39//! | `actor.<actor>.drop.<n>.name` | an actor's declared quest-item drop `name` (v0.9, only if set) |
40//! | `fx.….narrate` / `fx.….give` | a `narrate` line / named `give-item` in an effect list |
41//! | `fx.….rest_prompt` / `.rest_label` / `.save_label` | a `bonfire`'s authored rest-dialog strings (v0.8, only if set) |
42//! | `fx.….sealed_hint` | a `close-gate`'s authored answer to a right-click on the seal (v0.8, only if set) |
43//! | `lethal.<volume>.message` | a stage-5 lethal volume's death wording (v0.10) |
44//! | `state.<datum>.name` | a runtime datum's player-visible name — a currency (v0.10) |
45//! | `shop.<shop>.title` | a stage-5 shop dialog's title (v0.10) |
46//! | `shop.<shop>.offer.<i>.label` | a shop button's caption (v0.10) |
47//! | `shop.<shop>.offer.<i>.tooltip` | a shop button's hover tooltip (v0.10) |
48//! | `stake.<stake>.collected` | what collecting a recovery stake says (v0.10) |
49//!
50//! ## Nested effects (DSL v0.6)
51//!
52//! Effect strings nested inside a `sequence` step or a lifecycle bundle
53//! (`on_respawn`/`on_caught`/`on_arrive`) are player-visible too, so they are
54//! inventoried under **position-derived** child keys: the parent effect's `fx.…`
55//! key, then a stable segment ([`crate::stages::QuestEffect::nested_effect_lists_keyed_mut`])
56//! — `seq.<step>` for a sequence step, `respawn`/`caught`/`arrive` for the bundles —
57//! then the effect's index in that list, then the leaf (`.narrate`/`.give`).
58//! Example: a narrate in sequence step 1, effect 0 of `on_objective_complete`
59//! effect 0 → `fx.<quest>.oc.<obj>.0.seq.1.0.narrate`. Nesting is arbitrary-depth
60//! (a `move-actor.on_arrive` inside a `sequence` step nests both segments). Keys are
61//! purely position-derived → deterministic and stable across builds (ADR-0006).
62//!
63//! ## Entity display names are keyed by their TEXT, not by their site
64//!
65//! An NPC (`npc.<npc>.name`) and a scripted actor (`actor.<actor>.name`) are two
66//! DSL surfaces for the same thing a player reads: a nameplate over a body. One
67//! character routinely occupies both — a stage-2 NPC that stands and talks, plus
68//! one actor puppet per cutscene pose it is staged in. If each site owned its own
69//! key, a translator would be asked for `Polyphemus` five times and could answer
70//! differently each time, and the giant's name would **change as he walked into a
71//! cutscene** — a worse defect than the untranslated one, and an authored one.
72//!
73//! So the key of an entity display name is decided by its **canonical English
74//! text**: the first site (in this traversal's fixed order — NPCs before actors)
75//! declaring a given name owns the key, and every later site carrying the
76//! byte-identical name emits that same key. The inventory therefore asks for each
77//! distinct name exactly once, and two bodies a player reads as one character
78//! cannot render as two.
79//!
80//! Scope is deliberately the **entity display-name class only** (`npc.*.name`,
81//! `actor.*.name`). Prose — a narrate line, a dialogue label, an objective title —
82//! is context-bound and keeps one key per site: two English strings that happen to
83//! coincide may legitimately need different renderings. Wave-mob names
84//! (`wave.*.mob.*.name`) are the same shape and are **not** merged here: that is a
85//! generalization beyond the finding this rule closes, and it is an owner call
86//! because it retires keys live campaigns already translate.
87//!
88//! Player-visible strings only. Deliberately **excluded** (authoring context the
89//! player never sees, so translating them is pointless and out of scope): world
90//! `theme`/`premise`, NPC `persona` fields, persona `relationships`.
91
92use std::collections::{BTreeMap, BTreeSet};
93
94use schemars::JsonSchema;
95use serde::{Deserialize, Serialize};
96
97use crate::diagnostic::{Diagnostic, codes};
98use crate::envelope::{Campaign, DSL_VERSION};
99use crate::ids::CampaignId;
100use crate::stages::{NarrateStyle, QuestEffect};
101
102/// Walk the player-visible strings of a single quest effect (DSL v0.4): a
103/// `narrate` line and a named `give-item`'s display name. `keybase` is the
104/// effect's stable position-derived key prefix.
105fn effect_strings(eff: &mut QuestEffect, keybase: &str, f: &mut dyn FnMut(&str, &mut String)) {
106 match eff {
107 QuestEffect::Narrate { text, .. } => f(&format!("{keybase}.narrate"), text),
108 QuestEffect::GiveItem { name: Some(n), .. } => f(&format!("{keybase}.give"), n),
109 // spec-0016 §1: the bonfire's rest dialog is
110 // read by the player like any other on-screen line, so its authored
111 // strings translate like any other. Unauthored fields are absent from the
112 // inventory — the compiler bakes its canonical English, exactly as
113 // `world.boundary.message` does.
114 QuestEffect::Bonfire {
115 prompt,
116 rest_label,
117 save_label,
118 ..
119 } => {
120 if let Some(p) = prompt.as_mut() {
121 f(&format!("{keybase}.rest_prompt"), p);
122 }
123 if let Some(r) = rest_label.as_mut() {
124 f(&format!("{keybase}.rest_label"), r);
125 }
126 if let Some(s) = save_label.as_mut() {
127 f(&format!("{keybase}.save_label"), s);
128 }
129 }
130 // DSL v0.8: what a sealed gate answers when the party right-clicks it. Read
131 // off the actionbar exactly like a `narrate`, so it translates like one. An
132 // unauthored hint is absent from the inventory — the compiler bakes its
133 // canonical English, exactly as `world.boundary.message` does.
134 QuestEffect::CloseGate {
135 sealed_hint: Some(h),
136 ..
137 } => f(&format!("{keybase}.sealed_hint"), h),
138 _ => {}
139 }
140}
141
142/// Walk the player-visible strings of `eff` **and every effect nested inside it**
143/// (DSL v0.6): a `narrate`/`give-item` inside a `sequence` step or an
144/// `on_respawn`/`on_caught`/`on_arrive` bundle is player-visible and must enter the
145/// inventory (and be localized on the emission path), else it ships English-only in
146/// a translated build. Child keys extend `keybase` with the effect's stable key
147/// segment ([`QuestEffect::nested_effect_lists_keyed_mut`]) and the effect's index
148/// within that list, e.g. `<keybase>.seq.<step>.<j>.narrate` for a narrate in
149/// sequence step `<step>`, effect `<j>`. Deterministic and stable across builds.
150fn effect_strings_deep(eff: &mut QuestEffect, keybase: &str, f: &mut dyn FnMut(&str, &mut String)) {
151 effect_strings(eff, keybase, f);
152 for (seg, list) in eff.nested_effect_lists_keyed_mut() {
153 for (j, inner) in list.iter_mut().enumerate() {
154 effect_strings_deep(inner, &format!("{keybase}.{seg}.{j}"), f);
155 }
156 }
157}
158
159/// The implicit, always-canonical language. Never appears in `world.languages`
160/// and never has a sidecar; `delvec build --lang en` emits the pure-English delve.
161pub const CANONICAL_LANG: &str = "en";
162
163/// The reserved sigil opening the compiler's machine-readable **completion-marker**
164/// channel — `[dw:complete <campaign_id> <token>]`, the only evidence the
165/// validation bot accepts that an objective (or the campaign) actually completed.
166/// The channel rides chat, so any authored or translated player-visible string
167/// carrying this sigil could forge a completion and make a critical-path step pass
168/// hollow. [`validate_marker_channel`] (`DW0182`) reserves it, making the collision
169/// structurally impossible instead of merely implausible.
170pub const MARKER_SIGIL: &str = "[dw:complete";
171
172/// Reserve the machine completion-marker channel (`DW0182`): no player-visible
173/// string — authored English (the whole [`inventory`]) or any declared language's
174/// sidecar rendition — may contain [`MARKER_SIGIL`]. Language-independent; runs on
175/// every `validate` / `analyze` / `build`. Checks translations too: a translator
176/// (LLM or human) copying the sigil through is exactly the forgery this closes.
177pub fn validate_marker_channel(
178 c: &Campaign,
179 sidecars: &BTreeMap<String, L10nDoc>,
180) -> Vec<Diagnostic> {
181 let mut d = Vec::new();
182 let mut flag = |where_: String, key: &str, text: &str| {
183 if text.contains(MARKER_SIGIL) {
184 d.push(Diagnostic::error(
185 codes::MARKER_RESERVED,
186 "l10n",
187 where_,
188 format!(
189 "player-visible string `{key}` contains the reserved completion-marker \
190 sigil `{MARKER_SIGIL}` — that chat sequence is the validation bot's \
191 completion oracle, and authored text carrying it could forge a passing \
192 critical-path step. Reword the line to drop `{MARKER_SIGIL}`"
193 ),
194 ));
195 }
196 };
197 for (key, text) in inventory(c) {
198 flag(format!("#/{key}"), &key, &text);
199 }
200 for (lang, doc) in sidecars {
201 for (key, text) in &doc.content {
202 flag(format!("l10n/{lang}.json#/content/{key}"), key, text);
203 }
204 }
205 d
206}
207
208/// The kind marker on an l10n sidecar envelope (`"l10n"`), analogous to the stage
209/// marker on a stage document.
210#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
211#[serde(rename_all = "kebab-case")]
212pub enum L10nKind {
213 /// A localization sidecar (`l10n/<code>.json`).
214 L10n,
215}
216
217/// An l10n sidecar document: `{ dsl_version, campaign_id, kind: "l10n", lang,
218/// content, source }`, mirroring the stage-doc envelope style. `content` is a flat
219/// map of [inventory](crate::l10n::inventory) key → translated string; `source`
220/// records the canonical English each of those translations was made **from**.
221#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
222#[serde(deny_unknown_fields)]
223pub struct L10nDoc {
224 /// DSL version string (same versioning as the stage docs).
225 pub dsl_version: String,
226 /// Owning campaign id (must match the stage docs).
227 pub campaign_id: CampaignId,
228 /// Document kind marker (`l10n`).
229 pub kind: L10nKind,
230 /// The BCP-47-style language code this sidecar translates into (must match the
231 /// `l10n/<code>.json` filename and appear in `world.languages`).
232 pub lang: String,
233 /// Flat map of inventory key → translated string.
234 pub content: BTreeMap<String, String>,
235 /// **Translation provenance**: inventory key → the canonical English that key
236 /// held when its [`Self::content`] row was written.
237 ///
238 /// Coverage validation proves the sidecar has a row for every key
239 /// (`DW0180`/`DW0181`), which is a statement about key SETS and says nothing
240 /// about whether a row still corresponds to the English it renders. Edit an
241 /// authored line and its translation is stale, present, applied, and wrong —
242 /// and nothing in the key sets moved. `source` is what makes that
243 /// **detectable** ([`validate_l10n_provenance`], `DW0187`) instead of audited.
244 ///
245 /// This is load-bearing for entity display names in particular, because their
246 /// key is owned by the first site declaring a given text (see the module
247 /// header): renaming ONE body can migrate a key's ownership to ANOTHER body,
248 /// so the row that goes wrong is not the row the author touched.
249 ///
250 /// Optional in the format — an older sidecar parses unchanged and simply
251 /// carries no provenance, which `DW0188` reports as an unguarded row count on
252 /// every run rather than letting it pass in silence.
253 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
254 pub source: BTreeMap<String, String>,
255}
256
257/// The local part of a type-prefixed id: the segment after the first `/` (kebab
258/// preserved). `npc/keeper` → `keeper`. Ids without a `/` pass through unchanged.
259fn local(id: &str) -> &str {
260 id.split_once('/').map(|(_, r)| r).unwrap_or(id)
261}
262
263/// The local part of a type-prefixed DSL id, exactly as the key scheme derives it
264/// (`npc/keeper` → `keeper`). Public so a consumer that pairs inventory keys back
265/// with their source objects (`delvec l10n-inventory`, matching `dlg.<npc>.…` keys
266/// to the NPC that speaks them) derives the same segment the keys are built from.
267pub fn local_id(id: &str) -> &str {
268 local(id)
269}
270
271/// Walk every player-visible string in `c` in a fixed, deterministic order,
272/// invoking `f(key, &mut value)` for each. The single traversal shared by
273/// [`inventory`] and [`localize`] — they cannot drift.
274pub fn each_string(c: &mut Campaign, f: &mut dyn FnMut(&str, &mut String)) {
275 // Entity display names (a nameplate over a body) are keyed by their canonical
276 // English TEXT, not by their declaration site: canonical English → owning key.
277 // See the module header — one character routinely has one NPC identity and
278 // several actor puppets, and a per-site key would let its name be translated
279 // several ways. Filled in traversal order, so the NPC identity always owns the
280 // key and the puppets follow it.
281 let mut entity_names: BTreeMap<String, String> = BTreeMap::new();
282 // Stage 1 — world title + area names.
283 f("world.title", &mut c.world.content.title);
284 for area in &mut c.world.content.areas {
285 let key = format!("area.{}.name", local(area.id.as_str()));
286 f(&key, &mut area.name);
287 }
288 // Stage 1 — boundary return message (v0.6, only when authored). The compiler's
289 // default English is baked at emit time, so it is not inventoried; an authored
290 // message is translated like every other player-facing string.
291 if let Some(b) = c.world.content.boundary.as_mut()
292 && let Some(msg) = b.message.as_mut()
293 {
294 f("world.boundary.message", msg);
295 }
296 // Stage 1 — campaign outro (v0.6, only when authored): the closing line on the
297 // completion advancement. Unauthored, the emitter falls back to the finale
298 // quest's `goal`, which is inventoried in its own right — so the last sentence
299 // of a delve is campaign-derived and translated either way.
300 if let Some(outro) = c.world.content.outro.as_mut() {
301 f("world.outro", outro);
302 }
303 // Stage 3 — class names/blurbs + optional kit item display names.
304 for class in &mut c.classes.content.classes {
305 let cl = local(class.id.as_str()).to_string();
306 f(&format!("class.{cl}.name"), &mut class.name);
307 f(&format!("class.{cl}.blurb"), &mut class.blurb);
308 for (i, item) in class.kit.iter_mut().enumerate() {
309 if let Some(name) = item.name.as_mut() {
310 f(&format!("class.{cl}.kit.{i}.name"), name);
311 }
312 }
313 }
314 // Stage 2 — NPC names. First in the entity display-name class, so an NPC
315 // identity owns the key every actor puppet portraying it shares.
316 for npc in &mut c.npcs.content.npcs {
317 let key = entity_name_key(
318 &mut entity_names,
319 &npc.name,
320 format!("npc.{}.name", local(npc.id.as_str())),
321 );
322 f(&key, &mut npc.name);
323 }
324 // Stage 4 — quest goals.
325 for q in &mut c.quest_plan.content.quests {
326 let key = format!("quest.{}.goal", local(q.id.as_str()));
327 f(&key, &mut q.goal);
328 }
329 // Stage 5 — objective titles/hints (when set).
330 for q in &mut c.quests.content.quests {
331 let ql = local(q.id.as_str()).to_string();
332 for o in &mut q.objectives {
333 let ol = local(o.id().as_str()).to_string();
334 if let Some(title) = o.title_mut().as_mut() {
335 f(&format!("obj.{ql}.{ol}.title"), title);
336 }
337 if let Some(hint) = o.hint_mut().as_mut() {
338 f(&format!("obj.{ql}.{ol}.hint"), hint);
339 }
340 // Stage 5 — v0.7 `interact.missing_item_hint`: narrated in chat to the
341 // player who clicks without the required item in hand, so it is as
342 // player-visible as `hint` and translates like it. Absent on every
343 // pre-0.7 objective → inventory unchanged.
344 if let crate::stages::Objective::Interact {
345 missing_item_hint: Some(m),
346 ..
347 } = o
348 {
349 f(&format!("obj.{ql}.{ol}.missing_item_hint"), m);
350 }
351 // Stage 5 — v0.8 `collect.item_name`: the display name the
352 // collected item carries as a `custom_name` component. A player reads
353 // it off the stack in the barrel and off their own hotbar, so it is as
354 // player-visible as a `title` and translates like one. Absent on every
355 // pre-0.8 objective → inventory unchanged.
356 if let crate::stages::Objective::Collect {
357 item_name: Some(n), ..
358 } = o
359 {
360 f(&format!("obj.{ql}.{ol}.item_name"), n);
361 }
362 }
363 // Stage 5 — v0.7 cast-ledger bark lines (spec-0020). Barks are spoken
364 // in-game exactly like narrate text, so they translate like it too.
365 // `doing` is deliberately NOT inventoried: it is authoring context for
366 // the dialogue stage, never shown to a player. (`cast` is a BTreeMap and
367 // the placement list is ordered, so the traversal stays deterministic.)
368 for (npc, entry) in &mut q.cast {
369 let np = local(npc.as_str()).to_string();
370 for (b, p) in entry.placements_mut().into_iter().enumerate() {
371 let Some(crate::stages::CastDialogue::Barks(pool)) = p.dialogue.as_mut() else {
372 continue;
373 };
374 for (i, line) in pool.barks.iter_mut().enumerate() {
375 f(&format!("cast.{ql}.{np}.{b}.bark.{i}"), line);
376 }
377 }
378 }
379 }
380 // Stage 6 — dialogue node text + option labels.
381 for tree in &mut c.dialogue.content.dialogues {
382 let np = local(tree.npc.as_str()).to_string();
383 for node in &mut tree.nodes {
384 let nd = local(node.id.as_str()).to_string();
385 f(&format!("dlg.{np}.{nd}.text"), &mut node.text);
386 for (i, opt) in node.options.iter_mut().enumerate() {
387 f(&format!("dlg.{np}.{nd}.opt.{i}.label"), &mut opt.label);
388 // v0.8: the button's hover tooltip. A player reads it exactly as
389 // they read the caption, so it translates exactly like one; an
390 // unauthored tooltip is absent from the inventory (no key, no
391 // coverage obligation), like every other `only if set` string.
392 if let Some(tip) = opt.tooltip.as_mut() {
393 f(&format!("dlg.{np}.{nd}.opt.{i}.tooltip"), tip);
394 }
395 }
396 }
397 }
398 // Stage 5 — wave mob custom names (when set).
399 for w in &mut c.quests.content.waves {
400 let wl = local(w.id.as_str()).to_string();
401 for (i, mob) in w.mobs.iter_mut().enumerate() {
402 if let Some(name) = mob.name.as_mut() {
403 f(&format!("wave.{wl}.mob.{i}.name"), name);
404 }
405 // Stage 5 — v0.9 declared quest-item drops. The name
406 // rides the dropped stack's `custom_name`, so the player reads it off
407 // the ground and off their own hotbar: as player-visible as a wave
408 // mob's own name, and translated like one.
409 for (n, dr) in mob.drops.iter_mut().enumerate() {
410 if let Some(name) = dr.name_mut() {
411 f(&format!("wave.{wl}.mob.{i}.drop.{n}.name"), name);
412 }
413 }
414 }
415 }
416 // Stage 5 — actors: the nameplate over the puppet, then its v0.9 drops,
417 // keyed off the actor id exactly as a wave mob's drop is keyed off its
418 // wave.
419 for a in &mut c.quests.content.actors {
420 let al = local(a.id.as_str()).to_string();
421 // The puppet's own name (v0.6 `actors[].name`). Player-visible in every
422 // frame it stands in — a nameplate and, for a cutscene mannequin, the
423 // label the party reads while the scene plays — so it is as translatable
424 // as the stage-2 NPC name it usually duplicates, and shares that NPC's key
425 // when the two texts are identical (module header).
426 //
427 // `ACTOR_NAME_ENTRY` carries the whole fence: the field is v0.6 but the
428 // walk only reached it in the 0.10 era, so the coverage obligation is
429 // 0.10's and not v0.6's.
430 if let Some(name) = a.name.as_mut() {
431 let key = entity_name_key(&mut entity_names, name, format!("actor.{al}.name"));
432 f(&key, name);
433 }
434 for (n, dr) in a.drops.iter_mut().enumerate() {
435 if let Some(name) = dr.name_mut() {
436 f(&format!("actor.{al}.drop.{n}.name"), name);
437 }
438 }
439 }
440 // Stage 5 — loot item custom names (spec-0021), keyed like a class kit
441 // item's name so a named prop in a chest translates like any other.
442 for l in &mut c.quests.content.loot {
443 let ll = local(l.id.as_str()).to_string();
444 for (i, item) in l.items.iter_mut().enumerate() {
445 if let Some(name) = item.name.as_mut() {
446 f(&format!("loot.{ll}.item.{i}.name"), name);
447 }
448 }
449 }
450 // Stage 5 — lethal volumes (v0.10, spec-0031): the line the volume says as it
451 // kills. As player-visible as a narrate, and read at the worst possible moment
452 // to be reading a raw key, so it is inventoried like any other authored line.
453 for v in &mut c.quests.content.lethal_volumes {
454 let vl = local(v.id.as_str()).to_string();
455 f(&format!("lethal.{vl}.message"), &mut v.message);
456 }
457 // Stage 5 — a runtime datum's player-visible name (v0.10, spec-0032). A named
458 // datum is a currency: the engine states `<name>: <value>` on the holder's
459 // action bar on every write, so the name is read as often as any narrate.
460 for st in &mut c.quests.content.state {
461 let sl = local(st.id.as_str()).to_string();
462 if let Some(name) = st.name.as_mut() {
463 f(&format!("state.{sl}.name"), name);
464 }
465 }
466 // Stage 5 — shops (v0.10, spec-0032): the dialog's title, and each button's
467 // caption and tooltip. Keyed exactly as a dialogue node's label/tooltip are,
468 // because they are the same two components of the same vanilla button codec.
469 for sh in &mut c.quests.content.shops {
470 let hl = local(sh.id.as_str()).to_string();
471 f(&format!("shop.{hl}.title"), &mut sh.title);
472 for (i, off) in sh.offers.iter_mut().enumerate() {
473 f(&format!("shop.{hl}.offer.{i}.label"), &mut off.label);
474 if let Some(t) = off.tooltip.as_mut() {
475 f(&format!("shop.{hl}.offer.{i}.tooltip"), t);
476 }
477 }
478 }
479 // Stage 5 — recovery stakes (v0.10, spec-0032): the line a collection says.
480 for st in &mut c.quests.content.stakes {
481 let sl = local(st.id.as_str()).to_string();
482 f(&format!("stake.{sl}.collected"), &mut st.collected_message);
483 }
484 // v0.4 effect strings — `narrate` text, a named `give-item`, a bonfire's rest
485 // dialog, a seal's answer — over **every** root emission can lower an effect
486 // from, not just the quests stage's three ([`effect_roots_mut`]).
487 // Nesting inside each root is descended by `effect_strings_deep`, so a narrate
488 // in a `sequence` step of a trap payload is inventoried like any other.
489 for (_stage, _path, keybase, eff) in effect_roots_mut(c) {
490 effect_strings_deep(eff, &keybase, f);
491 }
492}
493
494/// The key an entity display name is inventoried under: the key already claimed by
495/// an identical name earlier in the traversal, or `own` if this site is the first
496/// to carry that text (in which case it claims it for every later site).
497///
498/// The lookup is on the string as authored, captured **before** `f` may rewrite it
499/// ([`localize`] swaps the NPC's name to the target language, and the actor puppets
500/// that follow are still English at the moment they are looked up).
501fn entity_name_key(claimed: &mut BTreeMap<String, String>, text: &str, own: String) -> String {
502 claimed.entry(text.to_string()).or_insert(own).clone()
503}
504
505/// The authoritative key → canonical-English inventory derived from the stage
506/// docs. Deterministic (keys are unique and the traversal order is fixed).
507///
508/// # Widening this is an ERROR-tier obligation on every existing campaign
509///
510/// This walk consults the campaign document and **never its `dsl_version`**.
511/// For the surface itself that is right — a campaign at 0.6.0 cannot use a 0.9
512/// surface, so those keys simply never appear — but it has a consequence worth
513/// stating, and one already paid for twice — by the widenings of
514/// [`each_string`] onto `traps[].payload` and onto `on_respawn` bundles:
515///
516/// **when a widening reaches strings that OLDER surfaces already emitted**, the
517/// inventory grows for campaigns of every declared version at once, and
518/// [`L10N_MISSING`](crate::codes::L10N_MISSING) (`DW0180`) is
519/// `Diagnostic::error`. A campaign that was complete and green stops building
520/// on the next engine, with no deprecation window and nothing in its own
521/// document changed.
522///
523/// Measured 2026-08-08 on `nobodys-cave-island` (sidecar `dsl_version` 0.6.0):
524/// removing one key — the shape a widening creates — exits 1 immediately with
525/// `DW0180 [error]`.
526///
527/// **The asymmetry is the finding, and it is with this module's own siblings.**
528/// One comparable obligation on existing content takes a warn-first window and
529/// says so in its own text: `DW0188` (translation provenance, in
530/// [`validate_l10n_provenance`] right here). Coverage does not. Whether it should is an owner call —
531/// changing a check's tier is never a mechanical change (CLAUDE.md) — so this
532/// records the measurement rather than acting on it.
533///
534/// Whichever way it is decided, the widening PR is where it has to be decided:
535/// adoption rounds for every active campaign belong in the same milestone as
536/// the `dsl_version` that creates the obligation, and a widening that skips the
537/// version bump creates the obligation with no milestone at all.
538pub fn inventory(c: &Campaign) -> BTreeMap<String, String> {
539 let mut c2 = c.clone();
540 let mut out = BTreeMap::new();
541 each_string(&mut c2, &mut |key, value| {
542 out.insert(key.to_string(), value.clone());
543 });
544 out
545}
546
547/// The NPC an inventory key belongs to (its **local** id), when the key scheme
548/// encodes one: `dlg.<npc>.…` (that NPC's dialogue tree — `.text` is the NPC's own
549/// line, `.opt.<i>.label` the player's reply *within* it), `npc.<npc>.name`, and
550/// `cast.<quest>.<npc>.…` (a v0.7 bark line — the NPC's own murmured speech, so a
551/// translator gets the same persona context a dialogue line gets).
552/// Returns `None` for every other key kind.
553///
554/// Lives beside [`each_string`] — the traversal that *defines* the key scheme — so
555/// the two cannot drift silently (a CLI test asserts every speaker derived from a
556/// real campaign's inventory resolves to a declared NPC). Consumed by
557/// `delvec l10n-inventory`, which hands a translator the speaking character's
558/// persona (`speech_style` above all) alongside the English line.
559pub fn key_speaker(key: &str) -> Option<&str> {
560 let (kind, rest) = key.split_once('.')?;
561 match kind {
562 "dlg" | "npc" => rest.split('.').next(),
563 // `cast.<quest>.<npc>.<branch>.bark.<i>` — the npc is the second segment.
564 "cast" => rest.split('.').nth(1),
565 _ => None,
566 }
567}
568
569/// One `narrate` `art` occurrence (DSL v0.6, spec-0014): its stage-doc path (for
570/// diagnostics), its l10n inventory key, and the canonical English text.
571#[derive(Clone, Debug, PartialEq, Eq)]
572pub struct ArtNarrate {
573 /// The stage document the string was authored in (`quests` / `dialogue`).
574 pub stage: &'static str,
575 /// JSON-pointer-ish path within that stage doc.
576 pub path: String,
577 /// The l10n inventory key (`fx.….narrate`) — always present, since every
578 /// `narrate` lives in an inventoried effect position.
579 pub key: String,
580 /// The canonical English text.
581 pub text: String,
582}
583
584/// Every `narrate` effect using the v0.6 `art` style, in a fixed deterministic
585/// order. Its l10n `key` is derived by the **same** traversal/keying as
586/// [`inventory`]/[`each_string`], so the compiler's art-font glyph check
587/// (`DW0328`) can look each art string up in every declared-language sidecar.
588/// Every art narrate lives in a quest `on_objective_complete`/`on_complete` or an
589/// environment trigger — all inventoried — so each `key` is guaranteed present in
590/// a fully-covered sidecar.
591pub fn art_narrates(c: &Campaign) -> Vec<ArtNarrate> {
592 let mut out = Vec::new();
593 each_effect_ref(c, &mut |stage, path, keybase, eff| {
594 if let Some(text) = eff.narrate_art_text() {
595 out.push(ArtNarrate {
596 stage,
597 path: format!("{path}/text"),
598 key: format!("{keybase}.narrate"),
599 text: text.to_string(),
600 });
601 }
602 });
603 out
604}
605
606/// One on-screen `narrate` occurrence — `title`, `subtitle` or `art` — its stage-doc
607/// path, its l10n inventory key, its style, and the canonical English text.
608#[derive(Clone, Debug, PartialEq, Eq)]
609pub struct ScreenNarrate {
610 /// The stage document the string was authored in (`quests` / `dialogue`).
611 pub stage: &'static str,
612 /// JSON-pointer-ish path within that stage doc.
613 pub path: String,
614 /// The l10n inventory key (`fx.….narrate`).
615 pub key: String,
616 /// Which on-screen channel vanilla draws it in — this selects the width budget.
617 pub style: NarrateStyle,
618 /// The canonical English text.
619 pub text: String,
620}
621
622/// Every `narrate` effect vanilla draws **on screen** (`title` / `subtitle` / `art`),
623/// in a fixed deterministic order. Like [`art_narrates`], each `key` is derived by the
624/// **same** traversal/keying as [`inventory`]/[`each_string`], so the compiler's
625/// text-fit check (`DW0330`) can look every string up in each declared-language
626/// sidecar and report it under the offending locale and key. `chat` narrates are
627/// excluded: chat wraps and scrolls, so it has no width budget.
628pub fn on_screen_narrates(c: &Campaign) -> Vec<ScreenNarrate> {
629 let mut out = Vec::new();
630 each_effect_ref(c, &mut |stage, path, keybase, eff| {
631 if let Some((style, text)) = eff.narrate_on_screen() {
632 out.push(ScreenNarrate {
633 stage,
634 path: format!("{path}/text"),
635 key: format!("{keybase}.narrate"),
636 style,
637 text: text.to_string(),
638 });
639 }
640 });
641 out
642}
643
644/// One dialogue option label — the caption vanilla draws on a fixed-width dialog
645/// button — with its stage-doc path, its l10n inventory key and the canonical
646/// English text.
647#[derive(Clone, Debug, PartialEq, Eq)]
648pub struct OptionLabel {
649 /// The stage document the string was authored in (`dialogue` for a real
650 /// dialogue option; a bonfire's labels carry the stage they were authored in).
651 pub stage: &'static str,
652 /// JSON-pointer-ish path within that stage doc.
653 pub path: String,
654 /// The l10n inventory key (`dlg.<npc>.<node>.opt.<i>.label`).
655 pub key: String,
656 /// The canonical English text.
657 pub text: String,
658}
659
660/// Every dialogue option label, in a fixed deterministic order (declaration order:
661/// tree, then node, then option). Each `key` is derived by the **same** keying as
662/// [`inventory`]/[`each_string`], so the compiler's button-width check (`DW0331`)
663/// can look every label up in each declared-language sidecar and report an
664/// overflowing translation under its own locale and key.
665///
666/// Every option label is emitted as a button caption exactly once per node variant
667/// (`emit::build_node_dialog`); display gating (`requires_flags`/`forbids_flags`)
668/// only decides *whether* a variant shows it, never how wide it renders, so gated
669/// and ungated options carry the same budget and are all visited here.
670pub fn dialogue_option_labels(c: &Campaign) -> Vec<OptionLabel> {
671 let mut out = Vec::new();
672 for (ti, tree) in c.dialogue.content.dialogues.iter().enumerate() {
673 let np = local(tree.npc.as_str());
674 for (ni, node) in tree.nodes.iter().enumerate() {
675 let nd = local(node.id.as_str());
676 for (oi, opt) in node.options.iter().enumerate() {
677 out.push(OptionLabel {
678 stage: "dialogue",
679 path: format!("/content/dialogues/{ti}/nodes/{ni}/options/{oi}/label"),
680 key: format!("dlg.{np}.{nd}.opt.{oi}.label"),
681 text: opt.label.clone(),
682 });
683 }
684 }
685 }
686 out
687}
688
689/// Every **authored** bonfire rest-dialog label (spec-0016 §1), in the same
690/// fixed effect order the inventory uses. A bonfire's
691/// two options are drawn on exactly the same 150-GUI-px `multi_action` button a
692/// dialogue option is, so they carry exactly the same width budget (`DW0331`) —
693/// the check follows the widget, not the stage the string was authored in.
694///
695/// Unauthored labels are absent by construction: the compiler's canonical English
696/// (`Rest and save` / `Save only` / `Bonfire`) is measured once by a compiler unit
697/// test rather than re-measured per campaign, since it cannot vary.
698pub fn bonfire_option_labels(c: &Campaign) -> Vec<OptionLabel> {
699 let mut out = Vec::new();
700 each_effect_ref(c, &mut |stage, path, keybase, eff| {
701 let Some(l) = eff.bonfire_labels() else {
702 return;
703 };
704 for (text, field, key) in [
705 (l.rest_label, "rest_label", "rest_label"),
706 (l.save_label, "save_label", "save_label"),
707 ] {
708 if let Some(text) = text {
709 out.push(OptionLabel {
710 stage,
711 path: format!("{path}/{field}"),
712 key: format!("{keybase}.{key}"),
713 text: text.to_string(),
714 });
715 }
716 }
717 });
718 out
719}
720
721/// The **five effect roots** the compiler can lower a quest effect from, as
722/// `(stage, json_path, l10n keybase)` for each root's `i`-th top-level effect.
723///
724/// The roots themselves are **not enumerated here**. They come from
725/// [`crate::effects::for_each_effect_root`], the one enumeration in the workspace,
726/// which this walk simply indexes into per top-level effect (`path` + `/{i}`,
727/// `key` + `.{i}`). Before that module existed this function held its own copy of
728/// the root list and [`effect_roots_mut`] held a second one, which is the
729/// arrangement that let a walk go blind to a root — twice, independently, in this
730/// file alone. The paths and keys are unchanged in both directions.
731fn effect_roots(c: &Campaign) -> Vec<EffectRoot<'_>> {
732 let mut out = Vec::new();
733 crate::effects::for_each_effect_root(c, &mut |site, list| {
734 for (i, eff) in list.iter().enumerate() {
735 out.push(EffectRoot {
736 stage: site.stage,
737 path: format!("{}/{i}", site.path),
738 key: format!("{}.{i}", site.key),
739 eff,
740 });
741 }
742 });
743 out
744}
745
746/// One top-level effect root: where it lives, what its l10n keys hang off, and the
747/// effect itself.
748struct EffectRoot<'a> {
749 /// The stage document (`quests` / `dialogue`) this effect was authored in.
750 stage: &'static str,
751 /// JSON pointer to the effect within that document.
752 path: String,
753 /// The effect's l10n key prefix.
754 key: String,
755 /// The effect.
756 eff: &'a QuestEffect,
757}
758
759/// The **mutable mirror** of [`effect_roots`]: the identical roots, in the
760/// identical order, with the same `(stage, path, key)` descriptors, exposed
761/// mutably so [`each_string`] (and through it [`localize`]) can rewrite the
762/// player-visible strings in place.
763///
764/// Like [`effect_roots`] it enumerates nothing itself — it indexes
765/// [`crate::effects::for_each_effect_root_mut`], which is generated from the
766/// **same macro body** as the immutable walk. The two mirrors are therefore
767/// lockstep by construction rather than by a test that has to be remembered; the
768/// descriptor-equality test below now pins that property instead of establishing
769/// it.
770fn effect_roots_mut(c: &mut Campaign) -> Vec<(&'static str, String, String, &mut QuestEffect)> {
771 let mut out: Vec<(&'static str, String, String, &mut QuestEffect)> = Vec::new();
772 crate::effects::for_each_effect_root_mut(c, &mut |kind, path, key, list| {
773 for (i, eff) in list.iter_mut().enumerate() {
774 out.push((
775 kind.stage(),
776 format!("{path}/{i}"),
777 format!("{key}.{i}"),
778 eff,
779 ));
780 }
781 });
782 out
783}
784
785/// Visit every effect emission can lower — **top-level and every
786/// transitively-nested** one (a `sequence` step, an
787/// `on_respawn`/`on_caught`/`on_arrive` bundle) — over all five
788/// [`effect_roots`], in the fixed inventory order, invoking
789/// `f(stage, path, keybase, effect)`. `stage` names the document the effect lives
790/// in (`quests` or `dialogue`) and `path` is its JSON pointer within it, so a
791/// diagnostic can point at the real site; `keybase` is its l10n key prefix, derived
792/// by the **same** position-keying as [`each_string`]/[`effect_strings_deep`] (so an
793/// art narrate's key matches its inventory key). Shared by [`art_narrates`],
794/// [`on_screen_narrates`], [`bonfire_option_labels`], [`sound_refs`] and
795/// [`play_sound_actor_refs`], so the consumer checks
796/// (`DW0326`/`DW0328`/`DW0330`/`DW0331`/`DW0335`) see exactly the strings the
797/// inventory demands a translation for.
798fn each_effect_ref<'a>(
799 c: &'a Campaign,
800 f: &mut dyn FnMut(&'static str, &str, &str, &'a QuestEffect),
801) {
802 for r in effect_roots(c) {
803 effect_deep(r.eff, r.stage, &r.path, &r.key, f);
804 }
805}
806
807/// Visit `eff` and every transitively-nested effect (depth-first, pre-order),
808/// threading the JSON-pointer `path` and l10n `keybase` through each nested list via
809/// [`QuestEffect::nested_effect_lists_labeled`] (path segment + key segment + the
810/// per-effect index). The key segments match [`effect_strings_deep`] exactly.
811fn effect_deep<'a>(
812 eff: &'a QuestEffect,
813 stage: &'static str,
814 path: &str,
815 keybase: &str,
816 f: &mut dyn FnMut(&'static str, &str, &str, &'a QuestEffect),
817) {
818 f(stage, path, keybase, eff);
819 for (pseg, kseg, list) in eff.nested_effect_lists_labeled() {
820 for (j, inner) in list.iter().enumerate() {
821 effect_deep(
822 inner,
823 stage,
824 &format!("{path}/{pseg}/{j}"),
825 &format!("{keybase}.{kseg}.{j}"),
826 f,
827 );
828 }
829 }
830}
831
832/// One vanilla sound-event reference (DSL v0.6/v0.4): its stage-doc path and the
833/// referenced id, for registry validation (`DW0326`).
834#[derive(Clone, Debug, PartialEq, Eq)]
835pub struct SoundRef {
836 /// The stage document the reference was authored in (`quests` / `dialogue`).
837 pub stage: &'static str,
838 /// JSON-pointer-ish path within that stage doc.
839 pub path: String,
840 /// The referenced sound-event id (`minecraft:` prefix optional).
841 pub sound: String,
842}
843
844/// Every vanilla sound-event id referenced by a quest/trigger effect — a
845/// `play-sound`'s `sound` (v0.6) and a `narrate`'s optional `sound` (v0.4) — in a
846/// fixed deterministic order, for `DW0326` validation.
847pub fn sound_refs(c: &Campaign) -> Vec<SoundRef> {
848 let mut out = Vec::new();
849 each_effect_ref(c, &mut |stage, path, _key, eff| {
850 for (sub, sound) in eff.sound_refs() {
851 out.push(SoundRef {
852 stage,
853 path: format!("{path}/{sub}"),
854 sound: sound.to_string(),
855 });
856 }
857 });
858 out
859}
860
861/// Every `play-sound` effect using the unsupported `at: actor` target, in a fixed
862/// order, as `(path, actor-id)` pairs. The actor variant is accepted by the
863/// schema and rejected (`DW0335`) by the compiler, which resolves no position for
864/// a live actor. `SoundRef::sound` carries the actor id.
865pub fn play_sound_actor_refs(c: &Campaign) -> Vec<SoundRef> {
866 let mut out = Vec::new();
867 each_effect_ref(c, &mut |stage, path, _key, eff| {
868 if let Some(actor) = eff.play_sound_actor() {
869 out.push(SoundRef {
870 stage,
871 path: format!("{path}/at/actor"),
872 sound: actor.to_string(),
873 });
874 }
875 });
876 out
877}
878
879/// Replace every inventoried string in `c` with its translation from
880/// `translations` (an l10n sidecar's `content`). Keys absent from the map are left
881/// as canonical English — but a fully-validated sidecar ([`validate_l10n`]) covers
882/// the inventory exactly, so a build only reaches here with complete coverage.
883pub fn localize(c: &mut Campaign, translations: &BTreeMap<String, String>) {
884 each_string(c, &mut |key, value| {
885 if let Some(t) = translations.get(key) {
886 *value = t.clone();
887 }
888 });
889}
890
891// ---------------------------------------------------------------------------
892// i18n v2 — translation tags and the Minecraft language-code table (spec-0029)
893// ---------------------------------------------------------------------------
894
895/// The reserved Unicode **private-use** character that delimits a *translation
896/// tag* — the in-band form that carries an inventory key alongside its canonical
897/// English from the stage docs to the text component the compiler emits it into.
898///
899/// A tagged string is `<SIGIL><key><SIGIL><english>` ([`tag`]). It exists only
900/// between [`tag_translatables`] and emission: every emitter that lowers an
901/// authored string into a **text component** splits it back apart and emits
902/// `{"translate": key, "fallback": english}` (spec-0029 §1), and every consumer
903/// that wants the human string calls [`plain`].
904///
905/// The point of an in-band tag is that a site which *fails* to do either leaks the
906/// sigil into the built tree, where the compiler's own output scan sees it and
907/// fails the build (`DW0185`). That turns "prove every authored string lands in a
908/// component" from an audit that rots into an invariant the compiler re-proves on
909/// every build, including for emitters not yet written.
910///
911/// U+E000 is the first code point of the Basic Multilingual Plane's Private Use
912/// Area: it has no character assignment, so no authored or translated content can
913/// legitimately contain it. [`validate_tr_sigil`] (`DW0183`) reserves the whole
914/// block anyway, so the tag can never be forged or shadowed by content.
915pub const TR_SIGIL: char = '\u{E000}';
916
917/// The reserved private-use range [`TR_SIGIL`] is drawn from (`U+E000..=U+F8FF`).
918/// Reserved wholesale so a near-miss cannot be authored either.
919const PUA: std::ops::RangeInclusive<char> = '\u{E000}'..='\u{F8FF}';
920
921/// Build the translation tag for `key` over its canonical English `english`.
922pub fn tag(key: &str, english: &str) -> String {
923 format!("{TR_SIGIL}{key}{TR_SIGIL}{english}")
924}
925
926/// Split a translation tag into `(key, english)`. `None` for an untagged string —
927/// a compiler-baked literal such as the default boundary message, which has no
928/// inventory key and is translated by neither v1 nor v2.
929pub fn untag(s: &str) -> Option<(&str, &str)> {
930 let rest = s.strip_prefix(TR_SIGIL)?;
931 let (key, english) = rest.split_once(TR_SIGIL)?;
932 Some((key, english))
933}
934
935/// The human string behind `s`: its English source if `s` is a translation tag,
936/// otherwise `s` unchanged. The accessor every **non-component** consumer of an
937/// authored string uses — the build manifest, the reviewer chronicles, the bot's
938/// `critical-path.json`, the generated PackTest sources. Each such site is a named
939/// exclusion in `docs/reference/compiler.md`: it is not a text component, so it
940/// cannot carry a translate key, and it is not read by a player.
941pub fn plain(s: &str) -> &str {
942 untag(s).map(|(_, e)| e).unwrap_or(s)
943}
944
945/// Whether `s` contains any reserved private-use character — i.e. whether it is,
946/// or embeds, a translation tag. The predicate the compiler's build-output scan
947/// (`DW0185`) runs over every emitted byte.
948pub fn has_tr_sigil(s: &str) -> bool {
949 s.chars().any(|c| PUA.contains(&c))
950}
951
952/// Rewrite every inventoried player-visible string in `c` into its translation tag
953/// ([`tag`]), returning the canonical-English inventory it was derived from.
954///
955/// Runs on the exact same traversal as [`inventory`] and [`localize`]
956/// ([`each_string`]), so the tagged set and the translated set are the same set by
957/// construction — the property spec-0029 keeps.
958///
959/// The campaign handed to the compiler is tagged **once**, before the plan is
960/// built; from there the tag is the compiler's only evidence that a string it is
961/// about to emit is player-visible and translatable.
962pub fn tag_translatables(c: &mut Campaign) -> BTreeMap<String, String> {
963 let mut inv = BTreeMap::new();
964 each_string(c, &mut |key, value| {
965 inv.insert(key.to_string(), value.clone());
966 *value = tag(key, value);
967 });
968 inv
969}
970
971/// Reserve the private-use block the translation tag is built from (`DW0183`): no
972/// player-visible string — authored English (the whole [`inventory`]) or any
973/// declared language's sidecar rendition — may contain a `U+E000..=U+F8FF`
974/// character. Language-independent; runs beside [`validate_marker_channel`] on
975/// every `validate` / `analyze` / `build`.
976pub fn validate_tr_sigil(c: &Campaign, sidecars: &BTreeMap<String, L10nDoc>) -> Vec<Diagnostic> {
977 let mut d = Vec::new();
978 let mut flag = |where_: String, key: &str, text: &str| {
979 let Some(bad) = text.chars().find(|ch| PUA.contains(ch)) else {
980 return;
981 };
982 d.push(Diagnostic::error(
983 codes::TR_SIGIL_RESERVED,
984 "l10n",
985 where_,
986 format!(
987 "player-visible string `{key}` contains the reserved private-use character \
988 U+{:04X} — that block is how the compiler carries an l10n key into the text \
989 component this string is emitted as, and it has no rendering in any \
990 Minecraft font. Remove U+{:04X} from the line",
991 bad as u32, bad as u32
992 ),
993 ));
994 };
995 for (key, text) in inventory(c) {
996 flag(format!("#/{key}"), &key, &text);
997 }
998 for (lang, doc) in sidecars {
999 for (key, text) in &doc.content {
1000 flag(format!("l10n/{lang}.json#/content/{key}"), key, text);
1001 }
1002 }
1003 d
1004}
1005
1006/// Every declared-language code this build knows how to write a lang file for, in
1007/// declaration order, as `(declared code, minecraft code)`. `Err` names the first
1008/// unmapped code (`DW0184`) — a language is never silently dropped.
1009pub fn declared_mc_codes(c: &Campaign) -> Result<Vec<(String, &'static str)>, Diagnostic> {
1010 let mut out = Vec::new();
1011 for lang in &c.world.content.languages {
1012 match crate::mclang::mc_lang_code(lang) {
1013 Some(mc) => out.push((lang.clone(), mc)),
1014 None => {
1015 return Err(Diagnostic::error(
1016 codes::LANG_CODE_UNMAPPED,
1017 "world",
1018 format!("/content/languages/{lang}"),
1019 format!(
1020 "declared language `{lang}` has no Minecraft language-file code — the \
1021 resource pack has nowhere to write its \
1022 `assets/delvewright/lang/<code>.json`, and the language would ship \
1023 invisible. Use a code the pinned 1.21.11 client really loads \
1024 (`dsl::mclang::CLIENT_LANGS`, derived from Mojang's own asset index) \
1025 — e.g. `zh-cn`, `ja-jp`, `de-de`"
1026 ),
1027 ));
1028 }
1029 }
1030 }
1031 Ok(out)
1032}
1033
1034/// **Translation provenance** (`DW0187` / `DW0188`): is each sidecar row still a
1035/// translation of the English it renders?
1036///
1037/// [`validate_l10n`] proves the sidecar's key SET equals the inventory's. That is
1038/// silent about whether a row still *corresponds* to its key: rewrite an authored
1039/// line and its translation is present, applied and wrong, with no key moved. The
1040/// sidecar's [`L10nDoc::source`] map closes it by recording the English each row
1041/// was translated from, so the compiler can compare instead of a human auditing.
1042///
1043/// Two findings:
1044///
1045/// * `DW0187` — a recorded source differs from the key's canonical English (the
1046/// row is stale), or names a key the sidecar does not translate at all (the
1047/// provenance itself is stale).
1048/// * `DW0188` — rows with no recorded provenance, **counted**. Those rows are
1049/// unguarded, and saying so on every run is what keeps an unadopted sidecar
1050/// from reading like a checked one. Warning tier: `source` is additive, and
1051/// this is the one-version deprecation window before it is required.
1052///
1053/// The entity display-name rule makes this more than hygiene. A name key belongs
1054/// to the first site declaring a given text, so renaming ONE body can migrate a
1055/// key to ANOTHER — the row that goes stale is not the row the author edited, and
1056/// the missing-key half of the move (`DW0180`) points somewhere else entirely.
1057pub fn validate_l10n_provenance(
1058 c: &Campaign,
1059 sidecars: &BTreeMap<String, L10nDoc>,
1060) -> Vec<Diagnostic> {
1061 let mut d = Vec::new();
1062 if c.world.content.languages.is_empty() {
1063 return d;
1064 }
1065 let inv = inventory(c);
1066 for lang in &c.world.content.languages {
1067 let Some(doc) = sidecars.get(lang) else {
1068 continue; // absent sidecar is DW0180's finding, not this one's.
1069 };
1070 for (key, was) in &doc.source {
1071 match inv.get(key) {
1072 Some(now) if now == was => {}
1073 Some(now) => d.push(Diagnostic::error(
1074 codes::L10N_STALE,
1075 "l10n",
1076 format!("l10n/{lang}.json#/source/{key}"),
1077 format!(
1078 "`{key}` was translated from {was:?} but now reads {now:?} — the \
1079 translation in `content` still renders the old line and would ship \
1080 attached to the new one. Re-translate `{key}` and update its `source` \
1081 (`tools/i18n-translate.py <campaign> --lang {lang}` does both). If a \
1082 RENAME surprised you here: an entity display name's key belongs to the \
1083 first body declaring that text, so renaming one body can hand its key \
1084 to another"
1085 ),
1086 )),
1087 None => d.push(Diagnostic::error(
1088 codes::L10N_STALE,
1089 "l10n",
1090 format!("l10n/{lang}.json#/source/{key}"),
1091 format!(
1092 "`source` records `{key}`, which is not in the string inventory — the \
1093 provenance is stale even if the translation is gone. Remove `{key}` \
1094 from `source` in `l10n/{lang}.json`"
1095 ),
1096 )),
1097 }
1098 }
1099 // Every row `source` does not cover is a row DW0187 cannot see. Report the
1100 // count: an unadopted sidecar must never look like a checked one.
1101 let unguarded = doc
1102 .content
1103 .keys()
1104 .filter(|k| !doc.source.contains_key(*k))
1105 .count();
1106 if unguarded > 0 {
1107 let total = doc.content.len();
1108 d.push(Diagnostic::warning(
1109 codes::L10N_PROVENANCE_MISSING,
1110 "l10n",
1111 format!("l10n/{lang}.json"),
1112 format!(
1113 "{unguarded} of {total} translated rows record no `source`, so nothing can \
1114 tell whether they still translate the English they render — an edited line \
1115 leaves its translation present, applied and wrong, and no key moves. Run \
1116 `tools/i18n-translate.py <campaign> --lang {lang}` to record provenance for \
1117 the rows it already has. This warning is the one-version deprecation \
1118 window; `source` becomes required after it"
1119 ),
1120 ));
1121 }
1122 }
1123 d
1124}
1125
1126/// Coverage + envelope validation for every declared language's l10n sidecar
1127/// (`DW0180` / `DW0181`). Language-independent: it runs on every `validate` /
1128/// `analyze` / `build`, regardless of `--lang`. Returns no diagnostics for a
1129/// campaign that declares no languages. `sidecars` is keyed by language code
1130/// (the `l10n/<code>.json` filename stem).
1131pub fn validate_l10n(c: &Campaign, sidecars: &BTreeMap<String, L10nDoc>) -> Vec<Diagnostic> {
1132 let mut d = Vec::new();
1133 let declared = &c.world.content.languages;
1134 if declared.is_empty() {
1135 return d;
1136 }
1137 // A sidecar must carry every key of the inventory (`DW0180`) and no key
1138 // outside it (`DW0181`).
1139 let inv = inventory(c);
1140 let required_keys: BTreeSet<&str> = inv.keys().map(String::as_str).collect();
1141 let inv_keys: BTreeSet<&str> = required_keys.clone();
1142 let campaign_id = c.world.campaign_id.as_str();
1143
1144 for lang in declared {
1145 if lang == CANONICAL_LANG {
1146 d.push(Diagnostic::error(
1147 codes::L10N_MISSING,
1148 "l10n",
1149 format!("/world/languages/{lang}"),
1150 format!(
1151 "`{lang}` is the canonical language and must not be declared in \
1152 `world.languages` — English is implicit; remove `{lang}` from the list"
1153 ),
1154 ));
1155 continue;
1156 }
1157 let Some(doc) = sidecars.get(lang) else {
1158 d.push(Diagnostic::error(
1159 codes::L10N_MISSING,
1160 "l10n",
1161 format!("l10n/{lang}.json"),
1162 format!(
1163 "declared language `{lang}` has no `l10n/{lang}.json` sidecar — add the \
1164 sidecar (a full key→translation map), or remove `{lang}` from \
1165 `world.languages`"
1166 ),
1167 ));
1168 continue;
1169 };
1170 // Envelope consistency (folded into DW0180 — the sidecar does not correctly
1171 // cover the declared language).
1172 if doc.campaign_id.as_str() != campaign_id {
1173 d.push(Diagnostic::error(
1174 codes::L10N_MISSING,
1175 "l10n",
1176 format!("l10n/{lang}.json"),
1177 format!(
1178 "sidecar `campaign_id` `{}` differs from the campaign's `{campaign_id}` — set \
1179 the sidecar's `campaign_id` to `{campaign_id}`",
1180 doc.campaign_id
1181 ),
1182 ));
1183 }
1184 if doc.lang != *lang {
1185 d.push(Diagnostic::error(
1186 codes::L10N_MISSING,
1187 "l10n",
1188 format!("l10n/{lang}.json"),
1189 format!(
1190 "sidecar `lang` field `{}` differs from filename code `{lang}` — set the \
1191 sidecar's `lang` to `{lang}` (it must match the `l10n/{lang}.json` filename)",
1192 doc.lang
1193 ),
1194 ));
1195 }
1196 if doc.dsl_version != DSL_VERSION {
1197 d.push(Diagnostic::error(
1198 codes::L10N_MISSING,
1199 "l10n",
1200 format!("l10n/{lang}.json"),
1201 format!(
1202 "sidecar declares dsl_version `{}` — set it to `{DSL_VERSION}`, the one \
1203 number this engine accepts, matching the stage documents",
1204 doc.dsl_version,
1205 ),
1206 ));
1207 }
1208 // Coverage: missing (DW0180) against what this campaign's version owes,
1209 // orphan (DW0181) against the whole inventory.
1210 let side_keys: BTreeSet<&str> = doc.content.keys().map(String::as_str).collect();
1211 for missing in required_keys.difference(&side_keys) {
1212 d.push(Diagnostic::error(
1213 codes::L10N_MISSING,
1214 "l10n",
1215 format!("l10n/{lang}.json"),
1216 format!(
1217 "sidecar is missing a translation for inventory key `{missing}` — add \
1218 `{missing}` to `l10n/{lang}.json` (coverage must be exact)"
1219 ),
1220 ));
1221 }
1222 for orphan in side_keys.difference(&inv_keys) {
1223 d.push(Diagnostic::error(
1224 codes::L10N_ORPHAN,
1225 "l10n",
1226 format!("l10n/{lang}.json#/content/{orphan}"),
1227 format!(
1228 "orphan key `{orphan}` is not in the string inventory — remove it from \
1229 `l10n/{lang}.json` (the sidecar must cover exactly the inventory, no extras)"
1230 ),
1231 ));
1232 }
1233 }
1234 d
1235}