Skip to content
MetatransformerHacking on the Frontier
BooksBooksBlogBlog

Source → mechanism → capability

Books carry the durable argument; field notes follow the moving edge. Both remain source-linked and revisable as the work changes.

BooksBlogRSS

© 2026 Metatransformer · Hacking on the Frontier.

Early Access shelf

Metatransformer · Hacking on the Frontier

0.1.0 Early AccessExploratory draft

Procedural Systems for Game Development

Algorithms, Simulated Worlds, and Generative Authoring

Design procedural pipelines that generate valid, legible, strategically and interpretively distinct game worlds under explicit constraints.

MetatransformerField atlas
Issue 03.03

Editorial plate · conceptual, not measured

  • Seed
  • Constrain
  • Simulate
  • Judge

Manuscript details

Manuscript
Exploratory manuscript frozen
Word count
8,751 words
Evidence cutoff
August 29, 2026
Last update
August 29, 2026
Recurring system
The Archive Below
Ebook
Leanpub release planned
Next gate
Frozen pending the Agentic Engineering pilot

Source limitation: Recent runtime-GenAI evidence is concentrated in language-forward prototypes and does not establish safe, coherent commercial reliability across genres.

Numbered chapters

  1. 01The generated artifact is a software object
  2. 02Randomness under control
  3. 03Constructive spatial algorithms
  4. 04Dungeon topology before geometry
  5. 05Grammars and constraint systems
  6. 06Search, quality diversity, and learned generators
  7. 07Worlds with a past
  8. 08Generative authoring
  9. 09Compile-time generative AI
  10. 10Runtime generative AI
  11. 11The hybrid production architecture
  12. 12Capstone: build The Archive Below

Procedural Systems for Game Development

Algorithms, Simulated Worlds, and Generative Authoring

Series: Metatransformer — Hacking on the Frontier
Edition: 0.1.0 Early Access
Evidence cutoff: 29 August 2026
Level: Advanced engineering
Recurring system: The Archive Below, a compact archaeology roguelite

Reader contract. This is a linear technical textbook about designing, implementing, and evaluating procedural systems. It assumes data structures, algorithms, discrete mathematics, probability, testing, and ordinary game-engine fluency. It does not teach basic engine programming, promise that procedural content is automatically fun, or treat a large model as a replacement for representations and verification. The examples, thresholds, equations labeled “book formalization,” diagrams, graphs, traces, and measurements are original teaching constructions; illustrative numbers are not reported experimental results.

Release state. The complete twelve-chapter first-draft argument, capstone, dated frontier map, source notes, glossary, and thirty-day schedule are present in this release. The Metatransformer website is the living Early Access edition: reviewed corrections, source updates, and web-native teaching apparatus arrive there first. Leanpub is the numbered ebook release channel. Recent runtime-generative-AI evidence, named product behavior, provider terms, and model capabilities may age quickly; re-check them after the evidence cutoff.

Evidence and originality. A nearby A label means primary empirical or peer-reviewed research; B means a primary system or practitioner account; C means official documentation or a maintained reference implementation; D means a survey, textbook, or synthesis; and E means this book’s engineering synthesis. “Reports” is reserved for a source’s stated result, “implements” for a named interface, “suggests” for bounded evidence, and “this book models” for our design. No source figure, table, dataset, worked example, or prose is reproduced or closely imitated. Every Mermaid figure and Archive Below artifact is independently authored.

Preface: engineering possibility

A seed can select one of billions of outputs while every run still feels like the same corridor with the furniture moved. A cellular automaton can make convincing caves while producing no route that supports the game’s lock structure. A language model can write an elegant inscription that contradicts the relic beside it. These are not isolated failures. They share one cause: the team optimized the proposal mechanism while leaving the artifact contract implicit.

Procedural generation is the engineering of possibility spaces under constraints. A generator succeeds when it reliably produces valid, legible, strategically or interpretively different artifacts that survive contact with mechanics, production, and players. Its numeric seed space is merely an input set. Its real design object is the set of reachable artifacts, the distribution over that set, the admission rules, and the evidence retained for each decision.

We will build one system rather than tour disconnected demos. The Archive Below is a compact archaeology roguelite. Every run has seven major spaces and at least two meaningful cycles. Before geometry exists, a simulated culture writes a short history ledger. That ledger affects factions, materials, damage, relics, environmental evidence, and storylets. Three hand-authored anchors remain fixed: the entrance, a signature reversal called the false restoration, and the finale. The recurring people and places are the Salt Cartographers, the Glass Regent, the flooded transept, the counterweight lift, and the reliquary shortcut.

Generative AI enters late and under authority boundaries. At compile time it may propose inscriptions, prop concepts, historical variants, and dressing plans into quarantine. At runtime it may phrase bounded descriptions or dialogue from verified facts. It may not create authoritative topology, mechanics, inventory, rewards, quest predicates, combat outcomes, or canon. That ordering is deliberate: a proposal model is useful only after the team knows what an artifact is, which states are legal, how meaning is represented, and what evidence makes a release defensible.

How to read and build alongside the book

Read the chapters in order on a first pass. The dependency is practical, not ceremonial. A WFC contradiction in Chapter 5 is diagnosable because Chapter 1 defined the artifact and Chapter 4 defined the topology it must preserve. Runtime phrasing in Chapter 10 is containable because Chapter 7 established canonical history and Chapter 8 separated storylet effects from their prose. Skipping directly to a model call removes the very representations that let an engineer say what went wrong.

Keep three workspaces while implementing. The laboratory runs generators headlessly across fixed corpora and stores raw candidates, traces, and measures. The editorial workspace contains authored rules, corpora, quarantined proposals, review decisions, and approved content. The game workspace consumes only admitted generator releases and approved registries. They may live in one repository, but their authority should remain distinct. A laboratory experiment may write thousands of failures; none should become loadable content merely because it shares a directory tree with the game.

At the beginning of each chapter, write the opening engineering question in your project log and predict the result of the failure injection. Prediction matters because retrospective explanations are cheap. After the lab, compare the observed trace to that prediction. If the failure appears at a different layer, repair the earliest violated contract. A geometry bypass caused by an absent mission predicate is not primarily a tile-weight problem; an invented historical reward is not primarily a tone problem.

Use the equations as interface notation. They are book formalizations unless a nearby source attribution says otherwise. Implementations need not copy the symbols or choose the same algorithms. They must preserve the distinctions: proposal versus admission, hard constraint versus preference, seed versus provenance, local compatibility versus global reachability, trace versus story, and phrasing versus adjudication.

The worked numbers are intentionally small enough to audit by hand. Before scaling a generator, reproduce the seven-node graph, the four-tile propagation trace, and the six-event history exactly. Small golden fixtures expose representation errors that statistical dashboards can hide. After those pass, move to distributions: hundreds of seeds, preserved failures, paired comparisons, tail costs, and blind judgments. One golden seed establishes a mechanism; a corpus characterizes behavior under a declared sample.

Every lab has explicit pass and fail conditions. Treat a fail result as useful evidence. Do not weaken a gate simply because a favored algorithm fails it. Either repair the implementation, change the representation with a versioned design decision, reduce the product claim, or reject the mechanism. The capstone can end in a no-go decision and still be excellent engineering if the evidence identifies the decisive gap.

Evidence packets as a habit

An evidence packet is not a pile of screenshots. It is a candidate-bound index that lets another engineer follow claims to artifacts and reproduce the relevant checks. Begin one in Chapter 1. Add generator identity and hard gates first; stream manifests in Chapter 2; spatial and topology traces in Chapters 3–5; population metrics in Chapter 6; event and storylet lineage in Chapters 7–8; model and editorial provenance in Chapters 9–10; and release, save, migration, and rollback records in Chapter 11.

For every measurement, record the unit, population, sampling rule, version bundle, and missing data. “Validity 96%” is incomplete without saying whether that is raw or repaired validity, which seeds ran, which validators were active, and what happened to timeouts. “Players preferred B” is incomplete without the comparison protocol, sample, blindness, question, and uncertainty. Exactness here is not bureaucracy. It prevents a generator’s most flattering slice from becoming its public identity.

Three kinds of evidence should remain visibly separate:

  1. Mechanism evidence shows that an algorithm performs the stated transition: propagation removes unsupported tiles, a reducer replays events, or a fallback meets its deadline.
  2. Distribution evidence characterizes many artifacts: validity, cost tails, coverage, duplicates, repairs, or route-use distributions over a fixed corpus.
  3. Experience evidence records what people perceive, decide, understand, and retell under a described study.

None substitutes cleanly for another. A correct WFC implementation can have a poor output distribution. A diverse metric distribution can be perceptually oatmeal. A favorable small playtest can miss a rare deadlock. The mature posture is triangulation with bounded claims, not the search for one score that declares the possibility space solved.

Compact prerequisite refresher

Two implementation habits recur often enough to make explicit. First, determinism belongs to a declared execution envelope. A pseudorandom algorithm, seed, and input set can still diverge when iteration order, floating-point behavior, parallel scheduling, locale, or dependency versions change. Golden tests should therefore compare the strongest stable representation the product actually promises. For an integer mission graph, that may be a canonical byte hash. For floating geometry across platforms, it may be graph identity, quantized bounds, and validator outcomes rather than bitwise mesh equality. State the promise before choosing the assertion.

Second, graph tests with inventory or world facts search a product state, not rooms alone. A visited key such as (node, held_items, activated_flags, knowledge) prevents the verifier from declaring a room exhausted when returning with the counterseal changes available edges. Because the state space can grow exponentially, keep authoritative facts compact, canonicalize equivalent states, prune dominated inventories only when dominance is proven, and impose an explicit search budget. Budget exhaustion is unknown or rejected under this release policy; it is not unreachable.

Property-based testing complements golden fixtures. Generate small typed graphs and assert invariants after every rewrite: preserved anchors still exist, required interfaces remain connected, dependency order remains acyclic, and decoding plus serialization preserves identity. Shrink failures to the smallest graph or event trace that still violates the predicate. The minimized counterexample belongs in the regression corpus with the generator release that discovered it.

These habits are ordinary software engineering applied to generative systems. They do not remove stochasticity. They make the conditions, comparisons, and failures precise enough for a team to reason about.

Global notation and artifact contract

SymbolMeaning
σ\sigmaσgeneration specification: authored requirements and parameters
xxxauthoritative input state, including history or game state
KKKadmitted corpus and canon pool
sssexplicit pseudorandom seed
GvG_vGv​generator implementation and version
aaacandidate artifact
eeegeneration evidence and provenance
hi(a)h_i(a)hi​(a)hard-constraint predicate
qj(a)q_j(a)qj​(a)soft-objective score
PG\mathcal P_GPG​reachable possibility space of generator GGG
ϕ(a)\phi(a)ϕ(a)descriptive-measure vector for expressive-range analysis
TTTordered simulation trace
VVVverifier stack or admission decision

The fixed definition of a generator is a program that maps a specification, state, corpus, and seed to candidate content plus generation evidence:

Gv(σ,x,K,s)=(a,e).(F.1)G_v(\sigma,x,K,s)=(a,e). \tag{F.1}Gv​(σ,x,K,s)=(a,e).(F.1)

An artifact is one candidate output. A seed initializes pseudorandom choices; it is not a provenance record. A possibility space is the set of artifacts reachable under a representation and its rules. An expressive range is the distribution of those artifacts under chosen descriptive measures. A hard constraint must hold for every admitted artifact; a soft objective may trade against other preferences only after hard constraints pass. These meanings do not change later.

Diagram source

flowchart LR
  C1[1 Software object] --> C2[2 Controlled randomness]
  C2 --> C3[3 Constructive space]
  C3 --> C4[4 Topology]
  C4 --> C5[5 Grammars and constraints]
  C5 --> C6[6 Search and learning]
  C6 --> C7[7 Simulated past]
  C7 --> C8[8 Authoring]
  C8 --> C9[9 Compile-time AI]
  C9 --> C10[10 Runtime AI]
  C10 --> C11[11 Production architecture]
  C11 --> C12[12 Capstone]

Figure F.1 — Dependency spine (original). Arrows mean “requires.” Runtime language generation appears only after representations, topology, constraints, evaluation, simulation, and authorial control exist.


01Chapter 1The generated artifact is a software object

Opening engineering question. Before choosing an algorithm, what exactly will the generator return, and what evidence lets the rest of the game trust it?

Chapter thesis. Treat generation as a typed, versioned, testable software boundary. Candidate production and artifact admission are different operations; seed count is neither possibility-space size nor expressive range.

Archive dependency. We begin with no dungeon, only the fixed Archive Below contract: seven major spaces, two meaningful cycles, three authored anchors, and a history ledger that later stages must consume.

1.1 Candidate, evidence, and admission

A weak API returns Dungeon. A production API returns a candidate plus enough evidence to reproduce, diagnose, invalidate, or reject it. For an Archive run:

type CandidateRun = Readonly<{
  generatorVersion: string;
  specificationHash: string;
  seed: string;
  streamVersions: Readonly<Record<string, string>>;
  historyTraceHash: string;
  missionGraph: MissionGraph;
  spatialLayout: SpatialLayout;
  placements: readonly Placement[];
  repairLog: readonly RepairEvent[];
  validatorResults: readonly GateResult[];
}>;

The seed appears, but so do code, specification, input, stream, trace, repair, and validator identities. If a balance patch changes the lock rule, regenerating with the same seed may correctly produce a different artifact. Reproducibility means reconstructing the declared generator configuration, not worshiping one integer.

Let hard constraints be H={h1,…,hm}H=\{h_1,\ldots,h_m\}H={h1​,…,hm​}. Define feasibility:

F(a)=⋀i=1mhi(a).(1.1)F(a)=\bigwedge_{i=1}^{m}h_i(a). \tag{1.1}F(a)=i=1⋀m​hi​(a).(1.1)

Only feasible candidates reach soft-objective comparison. With objective weights wjw_jwj​ used for one declared release profile,

Q(a)=∑j=1nwjqj(a),admit⁡(a)=F(a)∧Q(a)≥θ∧Rhuman(a).(1.2)Q(a)=\sum_{j=1}^{n}w_jq_j(a),\qquad \operatorname{admit}(a)=F(a)\land Q(a)\ge \theta\land R_{human}(a). \tag{1.2}Q(a)=j=1∑n​wj​qj​(a),admit(a)=F(a)∧Q(a)≥θ∧Rhuman​(a).(1.2)

Equations 1.1–1.2 are book formalizations. They prevent a beautiful but unreachable dungeon from compensating for broken reachability. The human term is explicit because taste, readability, and retellability are not exhausted by numeric proxies.

Diagram source

flowchart LR
  I[Specification, state, corpus, seed] --> G[Versioned generator]
  G --> A[Candidate artifact]
  G --> E[Generation evidence]
  A --> H{All hard constraints?}
  E --> H
  H -->|no| X[Reject or bounded repair]
  H -->|yes| Q[Soft objectives]
  Q --> R[Human/design gate]
  R --> S[Admitted artifact]

Figure 1.1 — Candidate-to-admission boundary (original). Evidence travels beside the artifact. Repair returns to validation; it does not silently relabel failure as success.

1.2 Three spaces people confuse

For a bbb-bit seed, the numeric seed space is S={0,…,2b−1}\mathcal S=\{0,\ldots,2^b-1\}S={0,…,2b−1}. The reachable possibility space is

PG={a∣∃s∈S:Gv(σ,x,K,s)=(a,e)}.(1.3)\mathcal P_G=\{a\mid \exists s\in\mathcal S:G_v(\sigma,x,K,s)=(a,e)\}. \tag{1.3}PG​={a∣∃s∈S:Gv​(σ,x,K,s)=(a,e)}.(1.3)

Many seeds can collide on one artifact. Some representable artifacts may have no seed path. Admission removes invalid candidates, producing AG={a∈PG:F(a)}\mathcal A_G=\{a\in\mathcal P_G:F(a)\}AG​={a∈PG​:F(a)}. Expressive range is not another set count; it is the empirical distribution of ϕ(a)\phi(a)ϕ(a), where measures might include cycle functions, critical-path length, flooded-area ratio, faction control, evidence density, and route-choice divergence.

Table 1.1 — Twelve illustrative seeds reduced to observable classes. These numbers are authored examples, not measurements.

SeedsDistinct serialized layoutsFeasible runsDistinct ϕ\phiϕ-binsBlindly distinguishable run types
1211943
Main collisiontwo seeds choose same room permutationtwo lock orders failsix layouts share topologymaterial swaps go unnoticed

The table is the oatmeal failure in miniature. Eleven mathematical layouts become three perceived situations: “direct lift,” “flood detour,” and “reliquary gamble.” The right response is not necessarily more entropy. It may be a representation that exposes new strategic relations or history-to-mechanic couplings.

Diagram source

flowchart TD
  S[Numeric seed space] -->|many-to-one mapping| P[Reachable possibility space]
  P -->|hard admission| A[Admitted artifacts]
  A -->|measure phi| D[Expressive-range distribution]
  D -->|player/game observation| U[Perceptually distinct situations]

Figure 1.2 — Seed count collapses through four filters (original). Each edge loses distinctions or reveals that the representation never contained them.

1.3 Representation is an engineering choice

A tile grid makes collision and flood fill cheap but hides mission meaning. A room graph makes reachability, cycles, and lock dependencies explicit but does not say whether geometry overlaps. A simulation trace exposes causal history but not grammatical prose. A token sequence makes phrasing convenient while global state validity is expensive to establish. No representation dominates; strong systems translate through several.

For the Archive, the initial artifact schema separates HistoryTrace, MissionGraph, SpatialLayout, DressingPlan, and TextSurface. Each has validators and provenance. The finale anchor is a graph node before it is a room prefab, and the Glass Regent is a durable entity before its title appears in prose.

1.4 Failure injection: the seed-only cache key

Version 0 caches runs by seed=1842. A designer changes the required cycle count from one to two, but the cache returns the old artifact. The build passes because geometry loads. Telemetry later shows no route choice at the counterweight lift.

The repair is architectural: cache identity includes generator version, specification hash, input history hash, corpus version, and seed. Admission results carry validator versions. Changing a dependency invalidates derived stages. “Same seed” remains useful only inside that complete identity.

What this does not prove

A typed artifact and complete provenance do not make its design good. Hard constraints certify only encoded predicates; soft objectives can reward shallow proxies; a human reviewer can be inconsistent. The cited PCG field maps classify representations and methods but do not establish one universal schema or perceptual measure.

Chapter summary

The Archive now has a generator boundary, staged representations, hard admission, soft comparison, and complete identity. Seed space, reachable space, admitted space, expressive range, and perceived difference are distinct. Chapter 2 can therefore control randomness without confusing additional random bits with additional design.

Review questions

  1. Why is a seed insufficient provenance for an artifact?
  2. How do feasibility and quality differ in Equations 1.1–1.2?
  3. What information does expressive range contain that ∣PG∣|\mathcal P_G|∣PG​∣ does not?
  4. Why should the finale exist as a graph node before geometry?

Design problems

  1. Define ϕ(a)\phi(a)ϕ(a) for an encounter generator so two cosmetic variants occupy the same bin but two tactical roles do not.
  2. Design a cache key and invalidation graph for a generator whose history, topology, and dressing stages release independently.

Implementation lab — Artifact envelope

Implement a serializable candidate envelope and five hard validators: seven major nodes, entrance/finale anchors, at least two cycles, reachable finale, and complete provenance. Observables: hashes, version IDs, gate results, elapsed generation time, and rejection reason. Pass: changing the specification invalidates cached output; an unreachable candidate cannot be admitted regardless of quality score. Fail: a seed alone identifies the artifact, a failed hard gate is averaged into quality, or repair is unlogged.

Source notes

Procedural Content Generation in Games maps representation, generation, and evaluation families (D). Search-Based Procedural Content Generation supplies search representation and evaluation vocabulary (D/A synthesis). The artifact envelope, equations, Archive measures, and thresholds are E-class book formalizations.


02Chapter 2Randomness under control

Opening engineering question. How can a designer change prop dressing without moving the flooded transept, invalidating every regression seed, and obscuring whether variety actually improved?

Chapter thesis. Randomness is an input protocol. Split stable pseudorandom streams by semantic subsystem, shape distributions deliberately, measure sensitivity, and evaluate output distributions rather than celebrating raw entropy.

Archive dependency. Chapter 1 gave the Archive a reproducible envelope. We now assign its topology, geometry, history, placement, and language independent random streams.

2.1 Streams, not one global cursor

A pseudorandom number generator deterministically expands state initialized by a seed. Reproducibility depends on algorithm and consumption order. In the naive design, adding one random urn before room placement shifts every later draw. The artifact changes everywhere for a local code edit.

Derive subsystem seeds with a stable keyed function:

sk=KDF⁡(sroot,generatorVersion,streamLabelk),(2.1)s_k=\operatorname{KDF}(s_{root},\texttt{generatorVersion},\texttt{streamLabel}_k), \tag{2.1}sk​=KDF(sroot​,generatorVersion,streamLabelk​),(2.1)

where labels are semantic—history, mission, geometry, dressing, text—not loop indices. A stream manifest records algorithm and version. Child streams may split again by durable entity ID, so adding a prop in the flooded transept does not alter the finale’s dressing.

Diagram source

flowchart TD
  R[Root seed 1842] --> H[history stream]
  R --> M[mission stream]
  R --> G[geometry stream]
  R --> D[dressing stream]
  R --> T[text stream]
  D --> DT[flooded-transept dressing]
  D --> DF[finale dressing]

Figure 2.1 — Semantic stream isolation (original). A changed draw under one leaf cannot advance an unrelated sequence. Version changes remain explicit in provenance.

Table 2.1 — Failure trace for a shared cursor. Draw values are illustrative.

StepVersion AVersion B after adding one prop choice
history faction draw0.180.18
new prop draw—0.73
mission loop draw0.730.41
finale room draw0.410.92
outcomereliquary reconnaissance loopcounterweight loop removed

With split streams, the new draw consumes only dressing/flooded-transept; the mission and finale values remain unchanged. Isolation makes failures local and comparisons meaningful.

2.2 Shape the distribution

Uniform choice is a design decision, not neutrality. Suppose the history stage chooses material evidence with weights saltstone 5, blue glass 3, and ironwood 2. The normalized categorical distribution is

P(X=i)=wi∑jwj.(2.2)P(X=i)=\frac{w_i}{\sum_j w_j}. \tag{2.2}P(X=i)=∑j​wj​wi​​.(2.2)

Weights control marginal frequency, not spacing. If back-to-back repetition damages legibility, draw without replacement from a shuffled bag, then refill under a boundary rule that avoids repeating the last item. If two features should co-vary—flood damage and salt corrosion—sample a shared latent field or conditional distribution rather than independently flipping coins.

Noise fields produce spatial correlation: nearby samples are similar. Fractal sums combine scales,

n(p)=∑o=0O−1αoN(2op),0<α<1,(2.3)n(p)=\sum_{o=0}^{O-1}\alpha^o N(2^op),\qquad 0<\alpha<1, \tag{2.3}n(p)=o=0∑O−1​αoN(2op),0<α<1,(2.3)

but the equation does not confer meaning. A corrosion field becomes useful only when thresholds affect navigation, cover, evidence, or resource placement under the artifact contract.

2.3 Sensitivity and expressive-range sampling

Randomness should not make a one-bit parameter change rewrite the whole world unless that is intended. For parameter vector θ\thetaθ, define empirical sensitivity over paired seeds:

Sj(δ)=1∣C∣∑s∈Cdϕ ⁣(G(θ,s),G(θ+δej,s)).(2.4)S_j(\delta)=\frac{1}{|C|}\sum_{s\in C}d_\phi\!\left(G(\theta,s),G(\theta+\delta e_j,s)\right). \tag{2.4}Sj​(δ)=∣C∣1​s∈C∑​dϕ​(G(θ,s),G(θ+δej​,s)).(2.4)

This E-class diagnostic uses a fixed seed corpus CCC and a distance over descriptive measures. Very low sensitivity suggests a dead control; very high sensitivity suggests a chaotic or over-coupled one. Examine distributions and concrete artifacts together. Histograms can hide semantic collapse, while favorite screenshots hide distributional failure.

The oatmeal failure appears when seeds differ in microscopic tile noise but share the same critical path, lock order, evidence sequence, and dominant tactic. The blind test asks players to cluster runs by strategic or interpretive situation without seeing seed IDs. If the clusters ignore the variables the generator claims to vary, the representation or coupling is wrong.

2.4 Failure injection: cosmetic entropy

We add 400 inscription surface variants and observe that serialized artifacts are nearly unique. Yet every test run still routes entrance → gallery → lift → finale, the Salt Cartographers always control the shortcut, and the flooded transept always contains the same relic. The expressive-range dashboard reports high text-token diversity and zero coverage in route-choice behavior.

The repair moves variation upstream: history changes control of one access route; topology maps that conflict into a distinct loop function; placement ties relic access to the chosen route. Text then reflects the difference. More phrases were never the missing variable.

What this does not prove

Stream splitting does not guarantee portability across random-number libraries, floating-point implementations, or concurrency schedules. Weighted distributions do not establish good pacing. Sensitivity depends on chosen measures, and blind perceptual tests depend on audience and exposure. The oatmeal diagnosis is a design instrument, not a universal scalar metric.

Chapter summary

The Archive’s randomness is now reproducible, isolated, shaped, and measurable. Correlated fields express spatial relationships; shuffled bags control repetition; paired-seed sensitivity detects dead or explosive parameters. Chapter 3 can use these streams inside constructive spatial algorithms without allowing local edits to erase causal comparisons.

Review questions

  1. Why does a global pseudorandom cursor make local changes nonlocal?
  2. What does weighted sampling control that a shuffled bag does not?
  3. Why can spatially coherent noise remain meaningless?
  4. What do very low and very high parameter sensitivity suggest?

Design problems

  1. Specify streams for loot, enemy composition, and cosmetic dressing so balance edits preserve spatial regression cases.
  2. Design three expressive-range measures that distinguish Archive runs mechanically, interpretively, and spatially.

Implementation lab — Stream isolation and oatmeal test

Generate 256 fixed seeds before and after inserting an extra dressing draw. Observables: per-stage hashes, stream draw counts, ϕ\phiϕ-vectors, paired sensitivity, and blind cluster labels from at least three reviewers. Pass: mission and history hashes remain identical after the dressing-only change; at least two claimed variation axes produce distinguishable clusters. Fail: unrelated hashes shift, output cannot be reconstructed from the manifest, or uniqueness is reported only as serialized inequality.

Source notes

The PCG textbook and its constructive methods chapter provide D-class field vocabulary. The perceptual-uniqueness boundary is supported broadly by evaluation and quality-diversity sources in the ledger; the stream tree, sensitivity equation, distribution values, and Archive blind test are E-class constructions.


03Chapter 3Constructive spatial algorithms

Opening engineering question. Which forward algorithm should shape the Archive’s rooms when the artifact contract demands readable major spaces, navigable damage, and a topology that later chapters will make meaningful?

Chapter thesis. Choose constructive algorithms by the properties their representation exposes. Local shape methods need explicit global connection and repair; no cave-like silhouette implies a playable dungeon.

Archive dependency. Controlled streams now let us compare spatial methods on identical history and mission inputs. We construct geometry for seven named graph placeholders while preserving entrance, false restoration, and finale anchors.

3.1 Families and contracts

Room placement samples rectangles or prefabs, rejects overlap and clearance violations, then connects centers or ports. It gives direct control over major spaces but can waste area under dense packing. Binary space partitioning recursively divides a region and places rooms in leaves. It produces separation and hierarchy cheaply, though repeated axis-aligned partitions can become visually regular.

Cellular automata update grid cells from local neighborhoods. A typical cave rule makes a cell wall if enough nearby cells are walls. It produces clustered organic boundaries, but reachability is an emergent outcome that must be measured. Random walkers or agents carve paths through a grid, naturally guaranteeing at least their own trace, but may create thin spaghetti corridors or overfocus one region. Noise and fractal fields generate correlated scalar values useful for terrain, material, or density; thresholding them does not by itself yield mission structure.

Table 3.1 — Algorithm selection against the Archive contract. Ratings are authored qualitative judgments.

MethodExposes major-room controlOrganic local shapeCheap connectivityCommon failureArchive role
room placementhighlowmediumpacking rejectionseven major envelopes
BSPhighlowhighrepetitive rectanglesmacro allocation fallback
cellular automatalowhighlowdisconnected pocketsflooded transept interior
walker/agentmediummediumhigh for its trailnarrow spaghettidamage and maintenance routes
fractal noiselowhigh correlationnonepretty meaningless fieldsmoisture/corrosion masks

The correct answer is a pipeline. We place major envelopes from graph nodes, synthesize selected interiors with cellular rules, use walkers for damage veins, and sample noise for surface state. Topology remains a separate artifact.

3.2 Connection and repair

Let walkable cells induce graph Gc=(Vc,Ec)G_c=(V_c,E_c)Gc​=(Vc​,Ec​). Flood fill from entrance cell rrr computes

Reach⁡(r)={v∈Vc∣r⇝v}.(3.1)\operatorname{Reach}(r)=\{v\in V_c\mid r\leadsto v\}. \tag{3.1}Reach(r)={v∈Vc​∣r⇝v}.(3.1)

A local layout passes baseline connectivity only if every required anchor port belongs to Reach(r). When it does not, repair should preserve design intent. Connecting the closest component pair with a straight corridor may cut through the finale, bypass a lock, or erase the flooded hazard. Instead, candidate repairs are evaluated against protected zones, port semantics, length, material, and mission-graph edges.

Diagram source

flowchart LR
  R[Seven graph node envelopes] --> P[Place rooms / BSP regions]
  P --> L[Local interiors: CA, walkers, noise]
  L --> C[Connect declared ports]
  C --> F[Flood fill and geometry checks]
  F -->|fail| RP[Bounded contract-aware repair]
  RP --> F
  F -->|pass| O[Spatial candidate + repair log]

Figure 3.1 — Constructive spatial pipeline (original). Global graph intent enters before local shaping and remains a constraint during repair.

3.3 The first complete layout graph

Chapter 4 will assign progression semantics. For now, the spatial stage receives this graph:

E Entrance Hall
G Salt Gallery
T Flooded Transept
L Counterweight Lift
R Reliquary Walk
F False Restoration
V Glass Vault Finale

Edges: E-G, G-T, T-L, L-F, F-V, G-R, R-F, T-R, L-G

It has ∣V∣=7|V|=7∣V∣=7, ∣E∣=9|E|=9∣E∣=9, and one connected component. Its cycle rank is deferred to Chapter 4 because count is a topological property, not yet a gameplay interpretation. Geometry embeds E in the northern anchor bay, F in the fixed reversal chamber, and V in the southern vault. The remaining nodes occupy sampled envelopes.

Diagram source

graph LR
  E[Entrance Hall] --- G[Salt Gallery]
  G --- T[Flooded Transept]
  T --- L[Counterweight Lift]
  L --- F[False Restoration]
  F --- V[Glass Vault Finale]
  G --- R[Reliquary Walk]
  R --- F
  T --- R
  L --- G

Figure 3.2 — Archive graph before progression semantics (original). The graph is complete but not yet good: no edge says why a player would choose it or which dependencies it respects.

3.4 Worked placement trace

Table 3.2 — One illustrative geometry attempt. Coordinates are grid-cell rectangles (x,y,w,h).

NodeInitial envelopeLocal methodCheckAction
E(2,2,8,6)authored prefabfixed anchorkeep
G(14,3,10,8)room placementclears E by 4keep
T(26,2,12,11)cellular interioreast port isolatedopen contract port
L(21,17,8,8)BSP leafcorridor crosses T hazardreroute via south port
R(9,15,9,7)walker damageone-cell chokewiden to two cells
F(31,18,10,7)authored prefabfixed anchorkeep
V(45,20,12,9)authored shellfixed finalekeep

The repair log records why each change occurred. A flood-fill pass then establishes geometry reachability, but it does not authorize opening locked mission edges. Chapter 4 will validate reachable states under inventory and world-state conditions.

3.5 Failure injection: helpful flood-fill repair

The flooded transept’s east port is disconnected. A generic repair joins it directly to the finale because those components are geometrically closest. Every cell becomes reachable, and the geometry test passes. The player now bypasses the false restoration.

The failure came from asking a cell graph to infer mission meaning it did not represent. Repair may connect only port pairs named by the mission graph, and protected anchors reject corridor intersection. If no compliant repair exists within budget, reject the spatial candidate and resample placement; do not weaken topology.

What this does not prove

Constructive methods can be fast and controllable without producing interesting play. Flood-fill reachability ignores locks, one-way traversal, resource costs, enemy pressure, line of sight, and player comprehension. The algorithm comparison is project-specific; the constructive-generation literature maps families but does not identify one universally superior method.

Chapter summary

The Archive now has seven embedded major spaces, organic local treatment, declared connection ports, geometry validation, and bounded repair. The complete nine-edge graph survives intact. Chapter 4 will turn its extra edges into progression choices rather than assuming that connected geometry is meaningful topology.

Review questions

  1. Why does a cellular-automata cave require a global verifier?
  2. Which Archive properties favor room envelopes plus local algorithms?
  3. Why can closest-component corridor repair violate progression?
  4. What does flood fill establish, and what does it leave untested?

Design problems

  1. Choose a constructive pipeline for a stealth map whose global contract includes two sight-line breaks and one flanking route.
  2. Define a corridor-repair cost that respects protected rooms, material rules, width, and mission ports.

Implementation lab — Construct and break the layout

Implement room envelopes, one cellular interior, one walker damage pass, port-based corridors, flood fill, and repair logging for the nine-edge Archive graph. Observables: stage seeds, room bounds, component count, anchor-port reachability, rejected repairs, and final layout hash. Pass: all declared ports connect without intersecting protected anchor interiors; the injected closest-component repair is rejected. Fail: topology edges are invented during geometry repair, a disconnected port ships, or resampling lacks a budget.

Source notes

The constructive methods chapter is a D-class map of rooms, corridors, cellular automata, partitions, and agents. No Man’s Sky: Continuous World Generation is a B-class shipped-system account, and its official art discussion supports authored style constraining procedural mathematics (B). The Archive pipeline, graph, coordinates, and repair policy are E-class.


04Chapter 4Dungeon topology before geometry

Opening engineering question. When nine corridors connect seven rooms, which edges create decisions, which encode progression, and which merely add navigation noise?

Chapter thesis. Author mission topology before spatial embedding. Reachability is state-dependent; lock dependencies must remain acyclic even when movement contains cycles; every cycle needs an explicit gameplay function.

Archive dependency. Chapter 3 embedded a fixed nine-edge graph. We now label its nodes and edges without changing its identities, then feed the annotated graph back to geometry.

4.1 Mission state and reachability

A room graph G=(V,E)G=(V,E)G=(V,E) is only the substrate. Traversal depends on state zzz: held keys, activated mechanisms, flood level, and completed discoveries. Let edge guard ge(z)g_e(z)ge​(z) and effect ue(z)u_e(z)ue​(z) define whether traversal is allowed and how state changes. State-dependent reachability is

Reach⁡(r,z)={v∣∃ path p:r⇝v, ∀e∈p, ge(ze)=1}.(4.1)\operatorname{Reach}(r,z)=\{v\mid \exists\text{ path }p:r\leadsto v,\ \forall e\in p,\ g_e(z_e)=1\}. \tag{4.1}Reach(r,z)={v∣∃ path p:r⇝v, ∀e∈p, ge​(ze​)=1}.(4.1)

The Archive’s critical path is E-G-T-L-F-V. The L-F edge is initially blocked by the counterweight lift. The lift is enabled by a counterseal found at R. R can be reached from G through the reliquary shortcut after observing a tide mark at T, or directly from T through a risky flooded crossing. This makes information and hazard, not only possession, part of route choice.

4.2 Cycles with functions

For an undirected graph with ccc connected components, cycle rank is

μ=∣E∣−∣V∣+c.(4.2)\mu=|E|-|V|+c. \tag{4.2}μ=∣E∣−∣V∣+c.(4.2)

Here 9−7+1=39-7+1=39−7+1=3. The number says three independent cycles exist. It says nothing about whether they matter. We assign functions:

  1. G-T-L-G: reconnaissance loop—the player sees the inactive lift before learning the alternate approach.
  2. G-T-R-G: risk/reward loop—the flooded crossing is short and hazardous; the reliquary shortcut is longer but exposes evidence and a relic.
  3. G-R-F-L-G after activation: return/shortcut loop—the counterweight lift collapses distance after the false restoration.

The third shares edges with the first two; cycle bases are not unique. Gameplay labels attach to intended traversals and state transitions, not to an arbitrary algebraic basis.

Diagram source

graph LR
  E[Entrance Hall] --> G[Salt Gallery]
  G --> T[Flooded Transept]
  T --> L[Counterweight Lift]
  L -. counterseal .-> F[False Restoration]
  F --> V[Glass Vault Finale]
  G -->|reliquary shortcut| R[Reliquary Walk]
  R -->|counterseal| F
  T -->|risky flood| R
  L -->|return route| G

Figure 4.1 — The Chapter 3 graph with mission semantics (original). Dashed traversal is state-guarded. The same physical edge may change function after the counterseal is acquired.

4.3 Lock-and-key invariants

Let source(k) be a reachable node containing key or enabling fact kkk, and blocked(k) the edge it unlocks. Define a dependency graph among locks: ki→kjk_i\to k_jki​→kj​ when acquiring kjk_jkj​ requires passing a guard controlled by kik_iki​. Required progression must satisfy:

∀k:source⁡(k)∈Reach⁡(r,z∖{k}),Gdep is acyclic.(4.3)\forall k:\operatorname{source}(k)\in\operatorname{Reach}(r,z\setminus\{k\}), \qquad G_{dep}\text{ is acyclic}. \tag{4.3}∀k:source(k)∈Reach(r,z∖{k}),Gdep​ is acyclic.(4.3)

The first condition forbids a key behind its own lock. The second prevents mutual dependency deadlock. Optional locks may intentionally remain unresolved, but the finale’s required dependency chain must have a topological order.

Table 4.1 — State trace through the cyclic graph. Illustrative player choices are one valid trace, not the only route.

StepLocationState gainedNewly enabledFunction exposed
0Eentry recordGauthored orientation
1GSalt Cartographer sigilT, view of Rfaction hypothesis
2Ttide-mark observationrisky T-Rhazard inference
3R via shortcutcounterseal, relic clueR-F and lift controloptional reward
4Ffalse restoration revealedV, lift reversalsignature reversal
5Lcounterweight activatedL-G returncompressed backtrack
6Vfinale predicate satisfiedcompletioninterpretation tested

4.4 Graph rewrites and embedding constraints

A rewrite rule matches a typed subgraph and replaces it while preserving interface nodes. An illustrative cycle rule is

[A→B→C]⇒[A→B→C, A→R→C],(4.4)[A\rightarrow B\rightarrow C] \Rightarrow [A\rightarrow B\rightarrow C,\ A\rightarrow R\rightarrow C], \tag{4.4}[A→B→C]⇒[A→B→C, A→R→C],(4.4)

with side conditions: R is optional before C; its reward changes later play; the branch cannot bypass required lock B; and all interface ports can be embedded without overlap. Apply rules to mission graphs, validate dependencies, then embed. A spatial generator does not get permission to drop an edge because it is inconvenient.

Diagram source

flowchart LR
  S[Typed mission graph] --> RW[Apply rewrite with side conditions]
  RW --> GV[Global progression validation]
  GV --> EM[Assign room envelopes and ports]
  EM --> SR[Spatial routing]
  SR --> CV[Collision, distance, and readability checks]
  CV -->|fail| EM
  GV -->|fail| RW

Figure 4.2 — Topology-to-geometry contract (original). Spatial retries may change placement and routing; they may not silently rewrite validated mission meaning.

4.5 Failure injection: three useless cycles

We randomly add three edges, preserving μ=3\mu=3μ=3. One connects adjacent rooms already separated by two seconds, one opens only after the finale, and one bypasses the counterseal. The cycle metric passes. Play becomes flatter.

The repair is not “lower cycle count.” Require each intended cycle to declare a function, availability window, expected decision, and measurable consequence. Reject the bypass because it violates lock dependency. Reject the post-finale edge because the run has no continued play. The short redundant edge can remain only if it serves a legibility, combat, or evidence purpose established in tests.

What this does not prove

A valid mission graph does not ensure that players perceive choices, that spatial travel costs support the intended tradeoff, or that a loop is enjoyable. Cycle rank is necessary bookkeeping, not a design score. Practitioner accounts of cyclic generation demonstrate architectures in named games, not universal superiority over trees.

Chapter summary

The Archive graph now has state-dependent traversal, a required critical path, an acyclic lock dependency, optional content, and three labeled cycle functions. Graph rewrites preserve interfaces and side conditions before embedding. Chapter 5 will show how grammars and constraint systems can produce variations without reducing meaning to local adjacency.

Review questions

  1. Why does ordinary graph reachability understate lock-and-key progression?
  2. What does cycle rank measure, and what can it not measure?
  3. Why must a required key be reachable without itself?
  4. Which decisions belong before spatial embedding?

Design problems

  1. Add one optional lock to the Archive without changing the critical-path dependency order; specify its payoff and failure cases.
  2. Write a graph-rewrite rule that creates a reconnaissance loop and list all semantic and embedding side conditions.

Implementation lab — Mission-graph validator

Represent typed nodes, guarded edges, state effects, and key dependencies. Enumerate or search reachable (node,state) pairs. Observables: cycle rank, intended cycle labels, dependency DAG, critical-path bounds, unreachable states, and embedding-port requirements. Pass: the given graph admits at least one finale trace and two meaningful cycle traces; self-lock and bypass injections fail with distinct diagnostics. Fail: plain connectivity substitutes for state reachability or cycle count substitutes for cycle function.

Source notes

Designing Procedurally Generated Levels provides A-class graph-grammar evidence; Graph-Based Generation using Answer Set Programming and The Dungeon Variations Problem provide A-class structured-generation cases. Unexplored’s Secret is a B-class practitioner account of deliberate cyclic generation. The Archive graph and functions are E-class.


05Chapter 5Grammars and constraint systems

Opening engineering question. How can the Archive vary its mission graph and room dressing while preserving locks, anchors, and local compatibility—and what should happen when propagation reaches a contradiction?

Chapter thesis. Grammars express transformations; constraint systems express allowed assignments. Both need explicit global invariants, bounded recovery, and a representation of meaning above local adjacency.

Archive dependency. Chapter 4 supplies a validated typed mission graph. This chapter varies its optional structure and assigns spatial tiles without changing the critical path, lock dependency, or cycle functions.

5.1 Production rules with contracts

A production grammar replaces a nonterminal with structured content. A room sequence rule might expand HAZARD into approach → flooded chamber → recovery ledge. A graph grammar matches nodes and edges, preserves interface nodes, and may add a branch or cycle. Rule application is not string substitution; match types, guards, negative conditions, and postconditions matter.

Let a rule r=(L,R,I,C)r=(L,R,I,C)r=(L,R,I,C) contain left pattern LLL, replacement RRR, preserved interface III, and side conditions CCC. Applying it to graph GGG at match mmm is valid only when

m:L↪G,C(G,m)=1,G′=G−m(L∖I)+m(R∖I),F(G′)=1.(5.1)m:L\hookrightarrow G,\quad C(G,m)=1,\quad G'=G-m(L\setminus I)+m(R\setminus I),\quad F(G')=1. \tag{5.1}m:L↪G,C(G,m)=1,G′=G−m(L∖I)+m(R∖I),F(G′)=1.(5.1)

This is book notation. The final feasibility check is not redundant: local side conditions can miss interactions with distant locks or previously applied rules.

Table 5.1 — Rewrite trace for the reliquary shortcut. All identifiers remain those introduced earlier.

PhaseMatched structureRewriteRequired postcondition
0critical edge G→T and later node Fmark branch interface at G,Fcritical path unchanged
1branch budget availableinsert R between G,FR optional before counterseal
2flood relation existsadd guarded T→Rcrossing cannot bypass counterseal source
3return-loop budget availableretain L→Gopens only after false restoration
4validatecompute state reachabilityfinale reachable; cycle functions present

An answer-set or general constraint formulation takes a different route. It declares candidate facts—node types, edges, item locations, ordering—and constraints that eliminate illegal models. This can make global conditions concise: exactly one entrance, one finale, seven major nodes, counterseal before lift traversal, and at least two labeled loop functions. Solver success establishes satisfiability of the encoded model, not spatial readability or fun.

5.2 WFC without mysticism

Wave Function Collapse is a name for a family of stochastic constraint-construction techniques; it is not quantum computation. In a tiled formulation, each cell iii has a domain Di⊆TD_i\subseteq TDi​⊆T of allowed tiles. For adjacent cells i,ji,ji,j in direction ddd, a compatibility relation Ad⊆T×TA_d\subseteq T\times TAd​⊆T×T requires

∀t∈Di: ∃u∈Dj such that (t,u)∈Ad.(5.2)\forall t\in D_i:\ \exists u\in D_j\text{ such that }(t,u)\in A_d. \tag{5.2}∀t∈Di​: ∃u∈Dj​ such that (t,u)∈Ad​.(5.2)

Propagation removes unsupported values. When a non-singleton domain must be observed, implementations commonly choose a low-entropy cell and sample a tile by weights. For normalized tile probabilities ptp_tpt​, Shannon entropy is

H(Di)=−∑t∈Diptlog⁡pt.(5.3)H(D_i)=-\sum_{t\in D_i}p_t\log p_t. \tag{5.3}H(Di​)=−t∈Di​∑​pt​logpt​.(5.3)

The original reference implementation describes observation, entropy-based choice, adjacency propagation, and contradictions (C/B); the rational reconstruction analyzes WFC through constraint solving and learned local patterns (A/D). Entropy is a search heuristic. It does not measure narrative uncertainty or gameplay meaning.

Diagram source

flowchart TD
  D[Initialize domains from ports, masks, and tile set] --> C{All singleton?}
  C -->|yes| G[Run global graph and playability checks]
  C -->|no| O[Choose low-entropy cell]
  O --> S[Sample one allowed tile]
  S --> P[Propagate adjacency removals]
  P --> X{Any empty domain?}
  X -->|no| C
  X -->|yes| B[Backtrack, restart, or bounded repair]
  B --> D

Figure 5.1 — WFC as stochastic observation plus propagation (original). The global check is deliberately outside the local solver. Recovery is bounded and recorded.

5.3 A small propagation trace

Consider three cells along the flooded transept’s eastern port. Tiles are W wall, F flooded floor, D dry floor, and P sealed port. The authored boundary fixes cell 3 to P. Only D may touch P on its west side; F may touch D or F; W may not interrupt the required port path.

Table 5.2 — Original domain trace. Braces show remaining values.

StepCell 1Cell 2Cell 3Event
0{W,F,D}{W,F,D}{P}initialize
1{W,F,D}{D}{P}propagate west support from P
2{F,D}{D}{P}required path removes W from cell 1
3{F}{D}{P}weighted observation chooses F

Now inject a style rule saying F cannot touch D. Cell 1 becomes {D}, which remains valid but eliminates water at the port. If another boundary forces cell 1 to F, its domain becomes empty: contradiction. A robust implementation can backtrack the most recent observation, restart the local region with a derived attempt seed, or invoke a narrowly specified repair. It may not erase the sealed port or widen the mission graph.

Bounded recovery has an explicit budget B=(bbacktrack,brestart,brepair)B=(b_{backtrack},b_{restart},b_{repair})B=(bbacktrack​,brestart​,brepair​). Exhaustion returns a rejected candidate with the contradictory cell, removed values, causal constraints, and attempt seeds. Endless restart is not reliability.

5.4 Local compatibility versus global meaning

A tile set can ensure doors meet corridors, wall edges align, and flooded tiles neighbor plausible banks. It cannot, by local adjacency alone, establish that the counterseal is reachable before the lift, that the reliquary loop presents a real decision, or that the false restoration occurs before the finale. Long-range meaning lives in the mission graph, simulation state, and evaluators.

The Archive therefore pins graph ports into the WFC boundary conditions. After tiling, a graph extractor reconstructs walkable connections and compares them with required and forbidden mission edges. It also measures door legibility and path cost. A locally valid room that embeds an accidental bypass is rejected.

5.5 Failure injection: locally perfect bypass

Every tile adjacency is valid, and the output looks coherent. A sequence of compatible balcony tiles creates an unplanned path from R to V, bypassing F. No WFC contradiction occurs because the tile rules know only adjacency.

The global extractor detects reachability of the finale in a state where the false-restoration predicate is false. The candidate fails hard admission. The design repair may add a global forbidden-connectivity constraint, introduce a typed locked balcony tile whose state belongs to the mission graph, or change the embedding. Adding more local samples without representing the predicate would only make the bypass less frequent.

What this does not prove

Constraint satisfaction proves only the encoded constraints. A grammar can generate valid but repetitive structures; a solver can be expensive; WFC can contradict or reproduce training-pattern bias. Low entropy is not high design importance. Local compatibility cannot guarantee pacing, strategic choice, semantic causality, or player comprehension.

Chapter summary

The Archive can now rewrite optional topology under side conditions, solve declared global assignments, and tile rooms through observable constraint propagation. Contradictions produce bounded backtracking, restart, or repair evidence. Chapter 6 turns from constructing one feasible candidate to searching and evaluating populations of alternatives.

Review questions

  1. What information belongs in a graph-rewrite rule beyond left and right patterns?
  2. What does Shannon entropy control in WFC?
  3. Why is an empty domain different from a failed global mission check?
  4. How can a locally compatible balcony violate the artifact contract?

Design problems

  1. Encode the counterseal dependency as answer-set-style facts and integrity constraints.
  2. Design a WFC recovery policy that preserves authored ports and reports causal contradiction evidence.

Implementation lab — Constraint-propagated transept

Implement the four-tile domain example, weighted observation, propagation queue, bounded backtracking, and post-generation graph extraction. Observables: domain sizes per step, chosen cell entropy, removals with causes, attempt seeds, recovered graph edges, and mission-gate results. Pass: the normal trace resolves; the forced F/D conflict terminates within budget; the balcony bypass fails globally. Fail: the code invokes quantum terminology as mechanism, restarts without bounds, or treats local completion as artifact admission.

Source notes

The WaveFunctionCollapse reference implementation is C/B-class evidence for the named mechanism. WFC via Constraint Solving and Machine Learning is an A/D-class rational reconstruction. The graph-grammar, answer-set, and constraint-programming sources from Chapter 4 remain relevant. Archive rules, domains, recovery budgets, and global checks are E-class.


06Chapter 6Search, quality diversity, and learned generators

Opening engineering question. Once the Archive can generate feasible layouts, how do we find a set of strong, behaviorally different runs instead of optimizing every seed toward the same safe solution?

Chapter thesis. Search-based PCG needs an explicit genotype, phenotype, feasibility gate, and evaluation budget. Quality diversity preserves several high-quality behavioral niches; learned generators remain representation- and dataset-bound proposal mechanisms requiring control, repair, and generator-level evaluation.

Archive dependency. Chapters 3–5 provide constructive, grammar, and constraint operators. They now become mutation, crossover, initialization, or repair components inside a search process.

6.1 Genotype, phenotype, and feasibility

A genotype is the representation search operators modify. A phenotype is the realized artifact players encounter. For the Archive, a compact genotype contains room-envelope order, optional rewrite choices, port assignments, hazard parameters, faction-control assignments, and placement priorities. A decoder DDD constructs the full graph, geometry, dressing, and evidence:

a=D(g;σ,x,K),g∈G.(6.1)a=D(g;\sigma,x,K),\qquad g\in\mathcal G. \tag{6.1}a=D(g;σ,x,K),g∈G.(6.1)

The mapping can be many-to-one. A small genotype change may have no phenotype effect after repair, or a large effect after a graph rule toggles. Measure both operator behavior and final artifacts.

Hard feasibility remains a veto. A useful constrained score is not a giant weighted soup:

rank⁡(a)={(0,−violations⁡(a))F(a)=0,(1,Q(a))F(a)=1.(6.2)\operatorname{rank}(a)= \begin{cases} (0,-\operatorname{violations}(a)) & F(a)=0,\\ (1,Q(a)) & F(a)=1. \end{cases} \tag{6.2}rank(a)={(0,−violations(a))(1,Q(a))​F(a)=0,F(a)=1.​(6.2)

Feasible artifacts dominate infeasible ones. Within the infeasible region, violation information may guide search toward repair; it cannot ship.

6.2 Fitness and Pareto tradeoffs

Archive objectives include critical-path duration, optional-content salience, backtrack compression, combat-space variety, evidence coherence, and generation cost. A single weighted sum embeds policy that may be unstable. Pareto dominance is often clearer: artifact aaa dominates bbb if it is no worse on all declared objectives and better on at least one:

a≻b  ⟺  (∀j:qj(a)≥qj(b))∧(∃k:qk(a)>qk(b)).(6.3)a\succ b \iff \big(\forall j:q_j(a)\ge q_j(b)\big)\land \big(\exists k:q_k(a)>q_k(b)\big). \tag{6.3}a≻b⟺(∀j:qj​(a)≥qj​(b))∧(∃k:qk​(a)>qk​(b)).(6.3)

The nondominated set exposes tradeoffs for a designer instead of hiding them in one score. Metaheuristics—evolutionary search, hill climbing, simulated annealing, or other population methods—are allocation strategies over candidates. Their names do not excuse weak representations or evaluators.

Diagram source

flowchart LR
  P[Population of genotypes] --> D[Decode phenotypes]
  D --> H{Hard feasibility}
  H -->|fail| R[Reject or repair evidence]
  H -->|pass| Q[Quality objectives]
  Q --> BD[Behavior descriptors]
  BD --> AR[Archive of niches]
  AR --> S[Select parents / proposals]
  S --> M[Mutate, recombine, or learned propose]
  M --> P

Figure 6.1 — Search with feasibility and quality-diversity archive (original). The word “archive” here means a QD container; it is distinct from the game title The Archive Below.

6.3 Quality diversity

Optimizing average quality tends toward a narrow basin: moderate difficulty, short paths, safe room proportions. Quality-diversity methods seek high-quality candidates across behavioral descriptor bins. Let

b(a)=(risky-route share,shortcut leverage,evidence ambiguity).(6.4)b(a)=(\text{risky-route share},\text{shortcut leverage},\text{evidence ambiguity}). \tag{6.4}b(a)=(risky-route share,shortcut leverage,evidence ambiguity).(6.4)

A cell retains the best feasible candidate for its descriptor region. This does not make the descriptors objective truths. They are a designer’s hypothesis about meaningful difference, to be tested against play.

Table 6.1 — Illustrative QD cells after 2,000 evaluations. Scores are book-created on a 0–1 internal rubric.

NicheRisky routeShortcut leverageEvidence ambiguityBest qualityHuman reading
cautious archaeologylowhighmedium0.82investigate R, activate safe return
desperate salvagehighlowhigh0.76cross flood early, uncertain attribution
political routemediummediumlow0.79faction evidence clarifies optimal path
reversal-heavylowmediumhigh0.74false restoration reinterprets safe route

Coverage means occupied relevant bins, not automatic perceptual uniqueness. The blind evaluation asks whether players detect the intended differences and change decisions or interpretations.

6.4 PCGML and bias

PCG via machine learning learns a content model from data rather than relying entirely on manually specified constructive rules. Surveys define broad families and open problems, including representation, controllability, limited data, co-creation, and repair. A learned tile model inherits what its dataset can express. A corpus of linear dungeons may assign low probability to purposeful cycles. A screenshot model may reproduce visual surface without recoverable topology. A latent control called “difficulty” may correlate with density in the dataset rather than actual player challenge.

Learned generation is therefore one proposal mechanism. Condition on explicit controls where supported, decode into a typed intermediate representation, run deterministic hard gates, and repair only within declared bounds. Compare to constructive and search baselines under equal evaluation budgets. Preserve dataset version, preprocessing, model version, sampling parameters, and output evidence.

6.5 Generator-level evaluation

Use a fixed, versioned seed corpus CCC, including preserved failures and stratified parameter cases. Report at least:

V^=1∣C∣∑s∈C1[F(as)],R^=1∣C∣∑s∈C1[repair(as)],(6.5)\widehat{V}=\frac{1}{|C|}\sum_{s\in C}\mathbf 1[F(a_s)],\quad \widehat{R}=\frac{1}{|C|}\sum_{s\in C}\mathbf 1[\text{repair}(a_s)], \tag{6.5}V=∣C∣1​s∈C∑​1[F(as​)],R=∣C∣1​s∈C∑​1[repair(as​)],(6.5)

plus generation-time and memory distributions, repair cost, expressive-range coverage, duplicate rate, and blind human measures. Keep pre-repair and post-repair metrics separate: a generator with 20% raw validity and aggressive repair is operationally different from one with 95% raw validity.

For human comparison, blind artifact identity and architecture where possible. Ask concrete questions: which route did you choose, what evidence changed your theory, could you distinguish two runs after ten minutes, and which situation would you retell? “Rate procedural quality” is too vague.

6.6 Failure injection: fitness monoculture

We optimize one score combining short completion time, room-area balance, and zero validator failures. After 10,000 evaluations, every elite run uses the safest reliquary route, the minimum allowed critical path, and low ambiguity. Mean score rises; expressive range collapses.

The repair separates hard feasibility, exposes Pareto tradeoffs, and adds behavioral descriptors tied to route risk and evidence interpretation. We also audit the evaluator: if blind players cannot distinguish occupied niches, the descriptors need revision. Diversity in a spreadsheet is not player-observable diversity.

What this does not prove

Search does not discover quality beyond its representation and evaluator. Pareto fronts can be large and unhelpful. QD coverage depends on chosen descriptors and discretization. PCGML results in surveyed or studied systems do not establish transfer to a new game, commercial readiness, or freedom from dataset bias. Human evaluations remain audience-specific.

Chapter summary

The Archive’s constructive and constraint machinery now participates in search over typed genotypes. Feasibility vetoes invalid candidates, Pareto sets expose tradeoffs, QD preserves behavioral niches, and learned models remain gated proposals. Chapter 7 adds the historical state that will make those spatial differences interpretable rather than merely tactical.

Review questions

  1. Why distinguish genotype from phenotype during diagnosis?
  2. How does Pareto dominance differ from a weighted sum?
  3. What makes a behavioral descriptor useful?
  4. Why should raw and repaired validity be reported separately?

Design problems

  1. Create a genotype for the fixed Archive graph that can vary embedding without violating node identities.
  2. Design a blind evaluation that tests whether three QD niches change player strategy rather than only appearance.

Implementation lab — Compare three generators

Implement or wrap a constructive baseline, a search-based variant, and one learned or surrogate proposal model over the same typed intermediate form. Evaluate the same 512-seed corpus under matched wall-clock or candidate budgets. Observables: raw validity, repair rate and cost, latency distribution, objective vectors, QD coverage, duplicate rate, and blind decisions. Pass: no invalid artifact enters comparison; budgets and versions are recorded; at least one architecture’s claimed advantage is falsifiable. Fail: favorite seeds substitute for a corpus, repaired outputs hide raw failures, or model identity replaces evidence.

Source notes

Search-Based PCG is D/A-synthesis for representation, evaluation, and metaheuristics. Quality Diversity for PCG is D-class field framing. PCG via Machine Learning and Deep Learning for PCG are D-class surveys; Experience-Driven PCG is A/D. Archive genotypes, descriptors, values, and evaluation protocol are E-class.


07Chapter 7Worlds with a past

Opening engineering question. How can a seven-room dungeon feel excavated from a specific past rather than decorated with random “ancient” nouns?

Chapter thesis. Generate durable entities and state transitions first, preserve their causal evidence, then project partial and perspective-bound artifacts. A history is more than a chronology, and a simulation trace is not yet a story.

Archive dependency. The generator can now create and evaluate topology. Before choosing each run’s materials, factions, damage, relics, and storylets, we create a small authoritative history ledger.

7.1 Layered simulation and rationalized history

Dwarf Fortress is important here as a B-class practitioner case: creator accounts describe layered world simulation whose events players interpret and retell. The lesson is not “simulate everything.” It is that persistent entities, interacting systems, and inspectable consequences can support emergent histories. Player curation remains load-bearing; the simulation produces events, not a finished literary narrative.

Caves of Qud offers a different technique. Its reported event-first, ex-post-rationalization approach generates events and then explains them through previously established facts and thematic domains (A/B). This can create causal-seeming continuity without simulating every material process. It is not deception if the game treats the resulting ledger consistently; it is a distinct generative architecture.

The Archive combines a very small causal substrate with bounded rationalization. Entities receive durable IDs independent of display names:

type HistoryEvent = Readonly<{
  id: string;
  tick: number;
  kind: "survey" | "decree" | "flood" | "repair" | "schism";
  actors: readonly EntityId[];
  subjects: readonly EntityId[];
  preconditions: readonly FactId[];
  effects: readonly FactMutation[];
  evidenceTags: readonly string[];
  perspectiveClaims: readonly PerspectiveClaim[];
}>;

Names may change by perspective. person/glass-regent/01 remains stable whether Salt Cartographers call the figure “the Usurper in Blue.” This prevents a renamed display string from fragmenting identity.

7.2 Event sourcing and projections

A simulation trace is the ordered sequence T=(e1,…,en)T=(e_1,\ldots,e_n)T=(e1​,…,en​) of admitted state transitions. State is a fold:

xt=fold⁡(U,x0,e1:t),(7.1)x_t=\operatorname{fold}(U,x_0,e_{1:t}), \tag{7.1}xt​=fold(U,x0​,e1:t​),(7.1)

where UUU applies validated effects. Events are append-only authority for this run. Corrections are explicit events or regenerated traces, not silent prose edits. Projections derive current faction relations, damaged materials, known facts, artifact placements, and storylet availability.

Diagram source

flowchart LR
  I[Initial culture and environment] --> E[Admitted history events]
  E --> T[Append-only simulation trace]
  T --> FS[Current fact state]
  T --> M[Material/damage projection]
  T --> P[Perspective claims]
  FS --> A[Artifacts and relic placement]
  M --> A
  P --> ST[Storylets and inscriptions]
  A --> PA[Player archaeology]
  ST --> PA

Figure 7.1 — History authority and partial projections (original). Prose and props are derived views. They cannot mutate the event trace merely by asserting a fact.

7.3 Complete Archive history trace

Table 7.1 — The complete six-event history ledger, evolved in Chapter 8. All content and dates are illustrative.

TickEvent IDAdmitted transitionDurable effectsEvidence tags
12ev-survey-12Salt Cartographers map a saline aquiferfaction gains transept claim; salt charts existetched bearings, saltstone pins
19ev-decree-19Glass Regent nationalizes blue-glass worksfaction tension rises; vault glass markedblue seals, erased maker marks
27ev-flood-27survey breach floods the transeptT becomes flooded; lower route damagedtide lines, warped doors
31ev-repair-31Regent orders counterweight lift repairlift exists; counterseal issued to R custodianiron patches, seal socket
38ev-schism-38Cartographers hide the counterseal in reliquaryshortcut knowledge becomes factionalfalse wall, contradictory charts
44ev-restoration-44court records declare the Archive restoredfalse restoration doctrine; finale contradictionpolished plaque over flood damage

This trace causally explains spatial and mechanical facts: flood damage concentrates at T; the lift combines older saltstone with Regent iron repair; the counterseal belongs at R; and the finale tests whether the player accepts the official restoration. The false restoration is not a random twist pasted onto the last room.

Diagram source

graph TD
  S[Survey 12] --> FL[Flood 27]
  D[Decree 19] --> RP[Repair 31]
  FL --> RP
  RP --> SC[Schism 38]
  D --> SC
  FL --> FR[False restoration 44]
  RP --> FR
  SC --> FR

Figure 7.2 — Causal dependency view of the ledger (original). Chronological order alone would not show that the restoration claim depends rhetorically on suppressing both flood and schism.

7.4 Causal and rhetorical histories

A causal history records state transitions with preconditions and effects. A rhetorical history is a perspective’s selection and framing of those events. The Regent’s plaque calls ev-repair-31 “the restoration of lawful ascent” and omits the Cartographers. A hidden salt chart describes it as appropriation. Neither artifact may invent a seventh authoritative event; each selects facts, adds attributed interpretation, and may lie only within a modeled perspective policy.

Unreliable artifacts need constraint. Store speaker, knownFacts, agenda, claimedFacts, and contradictedBy. A lie is useful when discoverable evidence can challenge it. Unbounded hallucination is not unreliable narration; it is broken canon.

Simulation compression matters. We do not simulate every citizen or water molecule. Aggregate intervals until a threshold relevant to mechanics or evidence is crossed, then emit a durable event. Compression policy is part of generator versioning because it changes which causal distinctions can survive projection.

7.5 Failure injection: chronology soup

A naive generator samples six independent event templates: a coronation, a drought, a duel, a festival, a flood, and a disappearance. Dates are sorted, and an LLM writes connective prose. The result sounds historical but cannot explain any lock, material, faction relation, or evidence trail.

The repair begins before prose. Every event must consume established entities and facts, pass preconditions, change projected state, and nominate discoverable evidence. Event-first rationalization may fill a cause using the existing context pool, but the proposed link must become a typed relation and pass validation. If no mechanically or interpretively relevant consequence exists, the event is compressed away.

What this does not prove

Layered simulation does not automatically create stories, and rationalized causality does not reproduce social reality. The cited games demonstrate distinct successful systems, not a universal narrative-quality model. Player retellings are selective and audience-dependent. Durable IDs and event sourcing establish consistency properties, not historical depth or truth.

Chapter summary

The Archive now has a six-event authoritative trace, durable entities, causal dependencies, material projections, and perspective-bound claims. Every recurring spatial fact has a historical reason. Chapter 8 gives authors tools to turn those facts into controlled storylets and textual surfaces without losing ownership.

Review questions

  1. Why is an ordered chronology not necessarily a usable history?
  2. What does a durable entity ID prevent?
  3. How do causal and rhetorical histories differ?
  4. Why must an unreliable artifact remain linked to authoritative facts?

Design problems

  1. Add one perspective claim about ev-flood-27 that is biased but canon-compatible, plus evidence that can challenge it.
  2. Design a compression policy for fifty quiet years that retains changes relevant to relic placement.

Implementation lab — Event-sourced culture

Implement the six events, fact reducer, dependency validator, material projection, and two perspective projections. Observables: event IDs, precondition failures, state hashes per tick, causal edges, artifact evidence references, and compressed intervals. Pass: replay yields identical authoritative state; deleting ev-repair-31 invalidates the counterseal and lift projections; each shipped claim cites known or explicitly disputed facts. Fail: prose is authoritative, display-name changes break identity, or independent random events ship because they sound plausible.

Source notes

Practices in Procedural Generation, the Bay 12 creator index, and Emergent Narrative in Dwarf Fortress are B/C evidence for named practitioner architectures and the event/story distinction. Subverting Historical Cause & Effect is A/B evidence for Qud’s reported technique. Curating Simulated Storyworlds and Procedural Generation and Information Games are A/D and A sources for curation and archaeology. The Archive trace is E-class.


08Chapter 8Generative authoring

Opening engineering question. How can a writer see, constrain, vary, and repair procedural narrative without surrendering the work to an opaque prompt box?

Chapter thesis. Generative authoring preserves human initiative by exposing rules, canon, alternatives, provenance, and consequences. Grammars, ink-like flows, and storylets provide inspectable structure; generated proposals remain selectable material.

Archive dependency. Chapter 7’s six-event trace is authoritative. We now derive inscriptions, environmental clues, and conditioned narrative units from it while preserving authored entrance, false-restoration, and finale beats.

8.1 Three authoring layers

A Tracery-style grammar expands symbols through author-written alternatives. For example:

origin: "By #authority#, the lift was #verb#."
authority: "the Glass Regent" | "the lawful glass court"
verb: "restored" | "returned to measured ascent"

Tracery was explicitly designed as an author-focused generative text tool (A/B). Its strength is inspectability: a writer can see the corpus and probabilities. Its weakness is that unconstrained symbol expansion can repeat, contradict state, or create combinatorial outputs the writer never reads.

ink is an official narrative scripting language and toolchain with compilation and engine integration (C/B). It expresses authored flow, choices, variables, knots, and stitches; it is not a synonym for procedural text. The Archive uses an ink-like compiled layer for the fixed entrance briefing, the false restoration reveal, and finale choice, while variable lines read verified run facts.

Storylets are small authored narrative units with availability conditions and state effects. For storylet ℓ\ellℓ, define

Aℓ(x,k,p)∈{0,1},Eℓ(x,choice)→x′,(8.1)A_\ell(x,k,p)\in\{0,1\},\qquad E_\ell(x,choice)\rightarrow x', \tag{8.1}Aℓ​(x,k,p)∈{0,1},Eℓ​(x,choice)→x′,(8.1)

where xxx is authoritative run state, kkk is known canon, and ppp is player knowledge. Availability is pure; effects are typed and validated. Text may describe an effect, but only the deterministic effect function applies it.

Diagram source

flowchart LR
  H[History trace and canon pool] --> AV[Storylet availability]
  A[Authored anchors] --> AV
  AV --> C[Candidate storylets]
  C --> W[Writer selection and editing]
  W --> CO[Compiled narrative artifact]
  CO --> RT[Runtime conditions and typed effects]
  RT --> EV[Player evidence and telemetry]
  EV --> W

Figure 8.1 — Mixed-initiative authoring loop (original). The author can inspect candidates and consequences. Runtime state changes only through compiled typed effects.

8.2 Voice corpus, canon pool, and anchors

The voice corpus supplies diction, rhythm, taboo phrases, orthography, and faction registers. The canon pool supplies facts that may be referenced. They are distinct: a phrase can match the voice while contradicting canon, and a factual sentence can sound alien to the game.

The entrance anchor teaches the player that inscriptions are claims, not objective UI. The false restoration anchor juxtaposes the polished plaque with visible flood damage. The finale anchor asks which account the player deposits in the vault record. Procedural connective tissue selects evidence order, minor descriptions, and perspective-specific reactions. If generation cannot preserve these authored purposes, the ratio shifts toward more authored structure.

8.3 The evolved history-to-storylet trace

Table 8.1 — Storylets derived from the Chapter 7 ledger. Text snippets are original illustrative surfaces.

StoryletAvailabilityPresented evidenceTyped effect
salt_bearingsat G; ev-survey-12 known“Seven bearings, one scraped away.”add knowledge survey_omission
tide_argumentat T; tide mark observedCartographer blames decree-driven excavationadd hypothesis court_pressure
sealed_ascentat L; no countersealsocket bears Regent seal over older salt cutsreveal R clue; no unlock
reliquary_confessionat R; two prior cluescustodian hid counterseal after schismgrant counterseal; add fact source
false_restorationat F; counterseal heldpolished restoration plaque covers warped doorset reversal seen; enable finale predicate
vault_depositionat V; reversal seenplayer selects a supported accountrecord interpretation; complete run

Notice that sealed_ascent cannot grant the item. The prose reveals a clue; authoritative inventory changes only at reliquary_confession. This makes phrasing replaceable without changing mechanics.

The authoring tool shows, for each candidate, source events, referenced entities, voice rules, availability, effects, duplicate similarity, unresolved canon references, and every run path on which it appears. It offers alternatives and counterexamples: “This line attributes the flood to the Regent, but the current evidence supports pressure, not direct order.” The writer can edit the claim, strengthen the history trace, or reject the storylet.

8.4 Critique and repair

Mixed initiative means both sides can initiate within explicit roles. A writer may lock a phrase, pin a storylet, adjust weights, add a forbidden claim, or request variants. The tool may surface unreachable storylets, repeated syntax, thin canon support, choice effects that converge immediately, or a voice-corpus gap. It does not silently rewrite locked text.

Repair operates at the earliest broken layer. If a storylet is unreachable, inspect availability and topology. If it contradicts history, repair the claim or reject it—not the authoritative trace merely to save prose. If voice is bland, enrich or retune the corpus. If every route reveals evidence in the same order, change placement or availability, not synonyms.

8.5 Failure injection: invisible authorship

A one-box assistant receives “make the Archive more mysterious” and rewrites all inscriptions. The output is polished. It invents a second Regent, calls the counterseal a key, erases the Salt Cartographers’ register, and removes the clue required to find R. The author sees only final prose and cannot trace what changed.

The production tool instead presents a structured diff: changed rules, affected expansions, canon references, reachability consequences, similarity scores, and source provenance. Locked anchors remain immutable. Candidates enter a review branch, and compilation reruns storylet reachability and effect tests. Mystery is achieved by perspective and evidence gaps, not canon loss.

What this does not prove

Inspectable authoring tools do not guarantee good writing, usable interfaces, or preserved creative ownership in every team. Grammar coverage can be shallow; storylet combinations can produce unintended arcs; human selection can reinforce sameness. Evidence from specific tools and studies does not establish one optimal mixed-initiative workflow.

Chapter summary

The Archive history now projects into a voice corpus, canon pool, compiled anchors, and six stateful storylets. Availability and effects are typed; prose remains a surface over authority. Chapter 9 may now introduce compile-time language and image models as untrusted proposal mechanisms inside this authoring system.

Review questions

  1. Why are voice corpus and canon pool separate?
  2. What must an author see to retain initiative?
  3. Why is storylet availability pure while effects are typed transitions?
  4. Which layer should change when every evidence route feels identical?

Design problems

  1. Add a seventh optional storylet that can disagree with tide_argument without inventing canon.
  2. Design a mixed-initiative UI action that exposes downstream reachability before a writer changes an availability condition.

Implementation lab — Visible storylet editor

Build a small editor or CLI listing the six storylets, their source events, availability, effects, and reachable run states. Add locked text, variant generation from an authored grammar, duplicate detection, and a structured diff. Observables: candidate origin, rule path, canon references, reachable states, effect test, editor decision, and compiled hash. Pass: all required storylets are reachable; no candidate can invent an entity; locked anchors survive regeneration; inventory changes only through typed effects. Fail: a prompt replaces the corpus, generated prose mutates authoritative state, or the author cannot see why a candidate appeared.

Source notes

Tracery is A/B-class evidence for an author-focused grammar tool. ink and Running ink are C/B official sources for the language, compilation, and runtime integration. Emily Short’s Storylets: You Want Them and Storylets Play Together are B-class practitioner models. Mixed-initiative content creation, Tanagra, and Friendly Mixed Initiative PCG provide D/A context. Archive rules and storylets are E-class.


09Chapter 9Compile-time generative AI

Opening engineering question. How can a model help produce hundreds of inscription and dressing candidates without allowing plausible output, uncertain rights, or silent duplication to enter the shipping build?

Chapter thesis. At compile time, a generative model is an untrusted proposal service behind schemas, quarantine, deterministic validators, provenance, human editing, and bake gates. Time for review is the architectural advantage.

Archive dependency. Chapter 8 established an inspectable authoring system with fixed canon, voice, storylet conditions, and typed effects. Models may now propose material into that system; they do not replace it.

9.1 Compile time is a review budget

Compile-time generation occurs before a shipped build or content release. Its output can wait minutes or days because no player is blocked. It can be compared in batches, edited, rights-reviewed, tested in-engine, rejected, cached, and baked into deterministic content. This is categorically different from runtime generation during active play.

Let expected handling cost for candidate class ccc be

Bc=Nc(Cinfer+Cvalidate+Chuman+Cimport),(9.1)B_c=N_c(C_{infer}+C_{validate}+C_{human}+C_{import}), \tag{9.1}Bc​=Nc​(Cinfer​+Cvalidate​+Chuman​+Cimport​),(9.1)

where every value is measured under the studio’s process. At compile time, latency is mostly throughput and editorial scheduling. At runtime, the same latency becomes a player-facing stall. The equation is E-class budgeting notation, not a provider-price claim.

A generation specification names content type, schema version, purpose, allowed canon IDs, forbidden claims, voice profile, maximum length, reference rights, model profile, sampling parameters, prompt-template version, number of candidates, cost ceiling, and admission gates. “Write some lore” is not a specification.

9.2 Quarantine and provenance

Raw model output is immutable input to the pipeline. It enters quarantine with request and response hashes, provider and model identifiers as reported, prompt/spec versions, sampling settings, timestamps, costs, input reference provenance, terms snapshot or internal policy reference, and moderation results. The shipping build cannot reference quarantine.

Diagram source

flowchart LR
  S[Versioned content specification] --> M[Model proposal call]
  M --> Q[Immutable quarantine + manifest]
  Q --> SC[Schema and length]
  SC --> CA[Canon and state references]
  CA --> DU[Duplication and memorized-phrase scan]
  DU --> ST[Voice/style and rights review]
  ST --> ED[Human edit, select, reject]
  ED --> EN[Engine staging and runtime capture]
  EN --> BK[Bake into approved registry]
  SC -->|fail| X[Reject report]
  CA -->|fail| X
  EN -->|fail| X

Figure 9.1 — Compile-time content admission (original). Later judgment never overrides failed schema, canon, provenance, or engine gates. Edited output has a new identity linked to the raw candidate.

Schema validation checks shape, types, IDs, length, markup, locale, and forbidden control tokens. Canon validation resolves every entity and event reference against the allowed pool. Duplication scans compare within the batch, against the approved corpus, and against a project-specific blocklist; similarity is a review signal, not a legal conclusion. Style checking can use deterministic features and a calibrated reviewer, but a fluent model grader may reward the same generic polish as the generator.

Rights and provenance review asks whether input references were authorized, whether contractual terms and studio policy permit the use, whether the candidate resembles protected or disallowed material, and whether required human or legal escalation occurred. It does not ask a model for a legal guarantee. The safest response to material uncertainty may be rejection or fresh human authorship.

9.3 A complete inscription admission trace

The task is to propose four versions of the Regent’s restoration plaque at F. Allowed facts are ev-decree-19, ev-flood-27, ev-repair-31, and ev-restoration-44. The plaque may omit the schism but may not claim the flood never occurred. It must preserve the court register and contain 18–32 words.

Table 9.1 — Compile-time admission sequence for candidate plaque-c3. Values are illustrative.

StageObservable input/outputDecision
requestspec plaque-v4, prompt template court-2, allowed fact IDsadmitted under cost cap
response26-word candidate, provider IDs, raw hashquarantined; not build-visible
schemacorrect JSON, known location and speaker IDs, 26 wordspass
canonreferences repair and restoration; says “flood was mastered”pass as rhetoric, not denial
duplicate0.81 similarity to an approved gallery plaquereview flag
stylecourt register matches; phrase “age of crystal” violates lexiconfail pending edit
rights/provenanceauthorized internal corpus; manifests completepass as process evidence only
human editreplaces stock phrase; adds visible repair seam referencenew edited hash; approve
engine stagingfont fits plaque; localization expansion budget passespass
bakeapproved ID inscription/false-restoration/03included in release registry

The edited artifact is not falsely labeled “model output unchanged.” Its lineage is raw candidate → editor revision → compiled resource → build. Rejected candidates remain available for duplicate analysis under retention policy but cannot be loaded by the game.

9.4 Caching and invalidation

Compilation is reproducible when cache keys name dependencies:

k=H(spec,prompt,modelProfile,sampling,K,policy,validatorVersions).(9.2)k=H(\text{spec},\text{prompt},\text{modelProfile},\text{sampling},K,\text{policy},\text{validatorVersions}). \tag{9.2}k=H(spec,prompt,modelProfile,sampling,K,policy,validatorVersions).(9.2)

Provider nondeterminism may prevent byte-identical regeneration even with identical request fields. Therefore the raw response is cached as an immutable artifact. Revalidation can reuse it when only a downstream validator changes. If canon changes, invalidate canon checks, storylet reachability, and compiled resources that reference affected IDs. If the font importer changes, rerun engine staging without repurchasing prose.

Maintain a dependency DAG. An approved object stores upstream hashes and the gate bundle that admitted it. A release query can answer: “Which inscriptions mention ev-repair-31, which build contains them, and which evidence must be regenerated if that event changes?”

9.5 Dressing plans and prop concepts

The same architecture handles nontext proposals. A model may propose a structured dressing plan: place corroded survey rods near the transept’s original breach, reserve polished blue glass for restoration-era interventions, and avoid blocking navigation ports. Deterministic validators check known prop IDs, placement zones, collision budgets, density, and event references. Engine staging instantiates the plan in a disposable scene, measures overlaps and performance, and captures standard views. A human judges composition and historical legibility.

Prop concept images are references for a later asset supply chain, not engine assets. Their manifest records inputs and use policy. A concept cannot bypass geometry, material, performance, provenance, and creative review merely because it resembles the brief.

9.6 Failure injection: the helpful direct write

A build script calls a model and writes its favorite inscription directly into the content directory. The JSON parses and the game ships. Weeks later, the team discovers that the line invents a second counterseal, duplicates another game’s distinctive phrase, and cannot be traced to a model or prompt version.

The fix is not a better prompt. Networked generation cannot write to the approved registry. The broker writes only immutable quarantine; an admission service copies an edited, validated artifact across the boundary under a new ID. Build jobs consume a frozen registry and never make generative calls. Unknown lineage is release-blocking.

What this does not prove

Schemas do not establish originality, rights, voice, or truth. Similarity scanners have false positives and negatives. Terms snapshots do not resolve jurisdiction-specific legal questions. Human review can miss subtle duplication or canon drift. Compile-time review contains risk and preserves replacement options; it does not make model output inherently safe or valuable.

Chapter summary

The Archive now has a complete proposal-to-bake lane. Raw candidates remain quarantined; schemas, canon, duplication, style, provenance, human editing, engine staging, and build gates create a traceable approved object. Chapter 10 considers the much tighter budget when generation happens in front of a player.

Review questions

  1. What architectural advantage does compile time provide over runtime?
  2. Why does human editing create a new artifact identity?
  3. Which dependencies belong in the content cache key?
  4. Why can a rights manifest support review without proving legality?

Design problems

  1. Design an invalidation graph for a renamed historical event that affects three inscriptions and one dressing plan.
  2. Specify deterministic and human gates for an AI-proposed prop concept before it can influence an engine asset.

Implementation lab — Quarantine-to-bake pipeline

Use a local fixture or model service to produce ten structured plaque candidates. Store raw manifests, then run schema, canon, duplicate, style, provenance, editorial, and engine-fit gates. Observables: hashes, versions, costs, gate decisions, edits, lineage, invalidation edges, and final registry entries. Pass: the build can reference only approved IDs; a canon-version change invalidates affected candidates; direct model output cannot cross the boundary. Fail: a grader overrides a failed canon check, rejected output remains loadable, or lineage is lost after editing.

Source notes

PCG via Generative AI and the AIIDE survey with LLM integration are D-class maps of a moving field. Running ink is C-class evidence for precompiled narrative integration. PANGeA and CALYPSO are A-class studied systems with narrow external validity. The quarantine, gate order, trace, budgets, and invalidation model are E-class.


10Chapter 10Runtime generative AI

Opening engineering question. What may a language model safely improvise while a player waits, and how does the game continue when the model is slow, unavailable, unsafe, contradictory, or irreproducible?

Chapter thesis. Runtime language generation belongs behind a typed boundary: deterministic state selects facts and legal actions; a model may phrase or propose within those facts; validators and fallbacks preserve play. If a model adjudicates the world, that uncertainty is core gameplay and must be evaluated as such.

Archive dependency. The Archive already owns topology, inventory, history, storylets, and compiled content. Runtime generation can now phrase a narrow curator response after the player presents evidence at the finale.

10.1 Historical case and frontier category

AI Dungeon is a useful historical case because it exposed incremental, player-facing language generation at scale. A qualitative study analyzes its “citizen NLP” interaction (A/D), and a creator report describes early scaling to more than one million users (B). Those sources establish a notable system and operational demand in its period; they do not prove long-horizon coherence, safe adjudication, or transfer to other genres.

Recent “AI-native games” work attempts to define games whose core loop depends on runtime generative AI. At the 29 August 2026 cutoff, this is a frontier category mapped mostly by surveys and prototypes, with evidence concentrated in language-forward or studied systems. The external-validity warning is load-bearing: commercial reliability across genres, long sessions, adversarial populations, and changing providers remains unresolved.

10.2 Authority boundary and state projection

The runtime model never sees or owns the complete engine state. A deterministic projector creates a bounded, privacy-reviewed view:

type CuratorRequest = Readonly<{
  requestId: string;
  releaseId: string;
  locale: string;
  playerEvidence: readonly CanonFactId[];
  selectedAccount: "court" | "cartographer" | "uncertain";
  allowedClaims: readonly CanonClaim[];
  toneProfile: "measured-archival";
  maxCharacters: number;
}>;

type CuratorProposal = Readonly<{
  text: string;
  citedFactIds: readonly CanonFactId[];
  proposedAction?: "none";
}>;

There is no field for rewards, inventory, quest completion, damage, topology, or new canon. Completion was already determined by reaching V with the reversal predicate. The response can acknowledge the player’s interpretation but cannot make it true in world state.

Let P(x)P(x)P(x) be the state projection, MMM the model proposal, and JJJ deterministic validation:

y=M(P(x),ρ),display⁡(x)={y.textJ(y,P(x))=1,ffallback(P(x))otherwise.(10.1)y=M(P(x),\rho),\qquad \operatorname{display}(x)= \begin{cases} y.text & J(y,P(x))=1,\\ f_{fallback}(P(x)) & \text{otherwise}. \end{cases} \tag{10.1}y=M(P(x),ρ),display(x)={y.textffallback​(P(x))​J(y,P(x))=1,otherwise.​(10.1)

The fallback is compiled and factually correct. No player loses progression because a provider times out.

Diagram source

sequenceDiagram
  participant G as Deterministic game state
  participant P as State projector
  participant M as Runtime model
  participant V as Validator/moderator
  participant U as Player UI
  G->>P: verified facts + chosen account
  P->>M: bounded typed request
  alt response within budget
    M-->>V: proposed phrasing + fact IDs
    alt valid, safe, timely
      V-->>U: display generated phrasing
    else invalid or unsafe
      V->>G: request compiled fallback
      G-->>U: display fallback
    end
  else timeout or unavailable
    P->>G: fallback reason
    G-->>U: display fallback
  end

Figure 10.1 — Runtime phrasing and fallback sequence (original). Every branch terminates in a playable response. The model has no write edge to authoritative game state.

10.3 Context, memory, and canon

Runtime context is a computed view, not memory or canon. It includes only facts necessary for this turn, the tone profile, recent displayed lines needed to avoid repetition, locale, and typed output contract. The history trace remains authoritative storage. A longer conversation may maintain a deterministic summary of player-known facts and prior response IDs, but generated summaries are not promoted to canon.

Memory policies name representation, read/write rules, scope, retention, deletion, and privacy. Do not send raw player text or identifiers to an external provider without a declared purpose, consent and disclosure appropriate to the product, minimization, protection, and current terms review. Moderation operates on input and output under a product policy; it is not a universal moral oracle.

Canonical state and language surface must be separable under provider replacement. If model A disappears, model B or the compiled fallback consumes the same request schema. Save files store chosen account, evidence IDs, and response provenance—not opaque provider context as the only record of progression.

10.4 Latency, cost, availability, and replay

Runtime has a player-facing service budget. Define deadline LmaxL_{max}Lmax​, per-session generation budget CmaxC_{max}Cmax​, and availability target for the phrasing feature. These are local product specifications. A response arriving after the UI has advanced is discarded under request identity; it does not overwrite newer text.

Table 10.1 — Complete runtime fallback trace. Times and costs are illustrative.

TimeEventState authorityUser-visible result
0 msplayer selects uncertain accountdeterministic choice recordedcurator panel opens
8 msprojector selects four allowed factscanonical tracebrief “consulting archive” state
40 msrequest enters provider adapterno state changeanimation continues
900 mssoft deadline passesfallback becomes eligibleno blocked input
1,200 mshard deadline passesrequest marked timed outcompiled 112-character response shown
1,640 mslate model response arrivesrequest ID stale; discardedno visible overwrite
1,650 mstelemetry records fallback classanalytics onlyrun remains complete

Replay is tiered. State replay reconstructs the same game mechanics and selected account. Surface replay displays the cached approved response when policy permits. Regeneration replay may differ and must be labeled; it is unsuitable for evidence that requires identical phrasing. Store provider/model profile, request hash, response hash, validator results, latency, cost, and fallback class subject to privacy policy.

10.5 Generative phrasing versus generative adjudication

Phrasing describes a decision already made by code. Adjudication interprets free-form input and changes authoritative state: awarding an item, declaring an action succeeds, or adding canon. Adjudication can be a deliberate game mechanic, but it moves model uncertainty into the core rules. Then evaluation must cover fairness, exploitability, consistency, moderation, latency, cost, save semantics, disputes, and provider drift as primary gameplay—not hide them behind “AI dialogue.”

The Archive does not take that risk. If a player types a free-form theory, a classifier may map it to one of the three typed accounts with a confirmation step; the player’s confirmed selection is authoritative. If interpretation confidence is low or service is absent, the UI offers the typed choices directly.

10.6 Failure injection: persuasive state mutation

The model returns: “Your proof clears the Salt Cartographers; I have placed the Regent’s lens in your inventory.” The line cites valid history but invents a reward. A naive parser sees “lens” and creates an item, making language authoritative.

Under the typed boundary, proposedAction permits only none; the extra claim fails canon and action validation. The fallback displays. Telemetry records forbidden_mechanical_claim. If players frequently ask for rewards, designers may author a response acknowledging the request, but they do not widen authority through prompt wording.

What this does not prove

A typed boundary does not make generated language coherent, nonoffensive, private, inexpensive, or available. Moderation has errors; fallbacks can feel repetitive; cached text may create retention obligations. Runtime-AI studies and early products do not establish long-horizon reliability or commercial readiness across genres. AI-native games that intentionally use model adjudication require a different, more demanding contract.

Chapter summary

The Archive now supports optional runtime phrasing without placing mechanics or canon at risk. State projection, typed output, deadlines, moderation, request identity, caching, and compiled fallbacks keep the run playable. Chapter 11 assembles these classical and generative lanes into one operable production system.

Review questions

  1. Why is context not canonical memory?
  2. What distinguishes generative phrasing from adjudication?
  3. Why must a late response carry request identity?
  4. Which replay level is needed to reproduce mechanics but not exact prose?

Design problems

  1. Design a typed confirmation flow for classifying a free-form theory without letting classification mutate canon.
  2. Set a runtime budget and fallback policy for a platform with intermittent connectivity; state which claims your test can support.

Implementation lab — Fail every runtime branch

Implement the curator request, mock provider, validator, timeout, moderation rejection, stale-response handling, cache, and compiled fallback. Observables: projected fact IDs, request/response hashes, latency, cost, validation failures, fallback class, and authoritative state diff. Pass: success, malformed output, forbidden claim, moderation failure, timeout, unavailability, and late response all leave identical mechanical state; every branch returns UI text within budget. Fail: model prose changes inventory or canon, timeout blocks completion, or raw private state enters the request.

Source notes

Playing With Unicorns is A/D-class qualitative analysis of AI Dungeon; How AI Dungeon scaled is a B-class creator report. AI Native Games is a D-class frontier map. PANGeA and CALYPSO remain bounded A-class studies. The typed authority boundary, budgets, fallback trace, and privacy architecture are E-class safety synthesis.


11Chapter 11The hybrid production architecture

Opening engineering question. How do topology, simulation, authored anchors, search, compile-time proposals, and runtime phrasing ship as one replaceable system rather than a chain of hidden dependencies?

Chapter thesis. Put deterministic authority underneath generated surfaces, separate compile/load/runtime lanes, version generator releases, contain failures at stage boundaries, and operate the system through telemetry, invalidation, and rollback.

Archive dependency. Every earlier representation and gate now becomes a node in the production architecture. The game must continue when a generator, model, provider, or optional surface fails.

11.1 Three execution lanes and authority

At compile time, the studio simulates history templates, authors rules, proposes and edits content, validates assets, evaluates seed corpora, and bakes approved registries. At load time, a run seed selects or generates the seven-space mission graph, history trace, spatial layout, placements, and storylet schedule under a bounded initialization latency. At runtime, deterministic mechanics execute the admitted run; optional language surfaces may phrase verified facts.

Authority is narrower at later, more exposed stages. Compile-time humans may change canon through reviewed source edits. Load-time generation instantiates canon but cannot extend the shipped schema. Runtime mechanics mutate run state according to shipped rules. Runtime models cannot mutate authoritative state at all.

Diagram source

flowchart TB
  subgraph CT[Compile-time lane]
    AU[Authored specs, rules, anchors] --> CP[Candidate proposal and simulation]
    CP --> QA[Corpus evaluation, editorial and engine gates]
    QA --> RG[Approved registry + generator release]
  end
  subgraph LT[Load-time lane]
    SD[Run seed] --> HI[History instance]
    RG --> HI
    HI --> TO[Mission topology]
    TO --> GE[Geometry, placement, storylet schedule]
    GE --> SV[Run save + evidence]
  end
  subgraph RT[Runtime lane]
    SV --> DS[Deterministic simulation and mechanics]
    DS --> SF[Generated surfaces]
    DS --> FB[Compiled surfaces and fallbacks]
    SF --> UI[Player experience]
    FB --> UI
  end
  QA -. telemetry and failures .-> AU
  DS -. telemetry .-> QA

Figure 11.1 — Hybrid production authority graph (original). Solid arrows move admitted artifacts or state. Feedback arrows inform future releases but cannot silently rewrite the current one.

11.2 Generator releases and save compatibility

A generator release bundles code, schemas, specifications, corpora, validators, random algorithms, stream labels, repair policies, model profiles, approved content registry, and migration rules. Give it an immutable ID. A save records at least release ID, root seed, generated artifact hashes or serialized admitted artifacts, authoritative run state, history trace, and content references.

There are three compatibility strategies:

  1. Freeze artifacts: saves store the generated graph, history, placements, and storylet schedule. New code interprets or migrates them.
  2. Freeze generator runtime: ship old generator bundles and regenerate from seed. This can be operationally expensive and fragile across engines.
  3. Versioned migration: transform old serialized artifacts to a new schema under tests.

The Archive uses freeze-artifacts for active saves. Seeds remain useful for provenance and bug reproduction, but a patch does not regenerate a player’s world silently. Content IDs are stable or migrated; removal uses tombstones or replacement mappings where the save might reference them.

11.3 Failure containment and patching

Failures should stop at the nearest boundary. A compile-time inscription candidate fails quarantine and never enters the registry. A load-time spatial candidate exhausts repair budget and falls back to a prevalidated seed or a baked layout. A runtime phrasing timeout shows compiled text. A telemetry outage queues bounded local counters or drops optional analytics; it does not block play.

Table 11.1 — Failure-containment matrix. Actions are the book’s production specification.

FailureDetectionContained responseForbidden response
history precondition failurereducer validatorreject attempt; preserve traceinvent connective prose
mission deadlockstate reachabilityresample/rewrite within load budgetremove lock silently
geometry cannot embed graphport/overlap verifierretry placement or baked layoutdrop cycle edge
compile-time model unavailablebroker statususe reviewed cache or human authoringdelay build indefinitely
runtime model timeoutdeadlinecompiled fallbackblock finale
provider/model replacementconformance suitecanary new adapterchange game schema to vendor output
generator regressionfixed seed corpusrollback generator releaseoverwrite old saves

Patches name invalidation scope. A text-only correction can replace a compiled surface and leave topology evidence valid. A history-event semantics change invalidates history projections, placement, storylet availability, and any compile-time content referencing it. A random-stream algorithm change can invalidate every derived load-time artifact and therefore requires a new generator release rather than a silent patch.

11.4 Telemetry and privacy

Generator telemetry measures release ID, stage timings, candidate and repair counts, failure classes, fallback use, seed-corpus coverage, run completion paths, cycle use, optional-content discovery, and storylet exposures. It should answer whether intended possibility-space distinctions survive in play. It need not record raw player prose or uniquely identify a person.

Telemetry is evidence, not automatic optimization. A rarely used reliquary shortcut may be unreadable, intentionally secret, or unattractive because its reward is weak. Diagnose with traces and playtests before changing weights. Updates occur offline through an admitted release; live metrics do not self-modify generator policy.

11.5 Replaceability and cost control

Every volatile dependency sits behind a studio schema. A learned geometry proposer returns a typed graph or scene program, not provider-native state. A language provider consumes CuratorRequest. A compile-time model consumes a content specification. Conformance fixtures test valid response, malformed response, refusal, timeout, rate limit, duplicate billing identity, and provider metadata loss.

Model replacement is not free. Outputs may change distribution, style, token use, moderation behavior, and latency. Run the complete admission suite and seed corpus, compare cost and failure distributions, blind human review, and canary only optional surfaces first. A provider abstraction makes replacement possible; it does not make providers equivalent.

An operating budget separates compile-time batch inference, load-time CPU/memory, runtime calls, storage, validation, and human review. Report tails, not only averages. One pathological seed that spends sixty seconds backtracking can destroy load-time experience even when median generation is fast.

11.6 Failure injection: compatible model swap

A new provider matches the JSON schema and halves median latency. The team swaps it without reevaluation. It cites valid fact IDs but writes longer, more certain sentences; moderation refusals increase for neutral discussion of the flooded dead; cache hit behavior changes; and the finale exceeds the text panel.

The interface was syntactically compatible but behaviorally different. The conformance and evaluation bundle must include output-length distribution, fact-use precision, refusal classes, style judgments, latency tails, cost, and UI fit. Roll back the adapter release while keeping deterministic run state and fallbacks unchanged.

What this does not prove

A layered architecture does not eliminate cross-layer bugs, migration loss, provider dependence, or operational expense. Telemetry can distort design and create privacy risk. A fallback can preserve play while degrading the intended experience. Hybrid architecture is a testable production synthesis, not evidence that current frontier systems are commercially reliable.

Chapter summary

The Archive is now an operable hybrid: reviewed compile-time production, bounded load-time instantiation, deterministic runtime authority, and optional generated surfaces. Generator releases, frozen save artifacts, conformance suites, telemetry, invalidation, and rollback keep the frontier components replaceable. Chapter 12 turns the architecture into a reproducible vertical slice and generator laboratory.

Review questions

  1. Why are compile time, load time, and runtime separate architectures?
  2. What must a generator release bundle contain?
  3. Why should active saves freeze admitted artifacts instead of relying only on seeds?
  4. What did schema conformance miss in the model-swap failure?

Design problems

  1. Draw an invalidation plan for changing the counterseal from an inventory item to a learned gesture.
  2. Design a provider conformance suite that distinguishes syntactic compatibility from behavioral compatibility.

Implementation lab — Operate one generator release

Package all schemas, streams, validators, content registries, and fallbacks under one immutable release ID. Create a save, patch one inscription, inject load-time generation exhaustion, swap a mock runtime provider, and roll back. Observables: dependency DAG, artifact hashes, migration decisions, latency/cost distributions, fallback counts, conformance results, and save-state hashes. Pass: the old save remains mechanically identical; failures contain at their lanes; rollback does not regenerate the world. Fail: seed alone defines save identity, provider output dictates schema, or telemetry silently changes weights.

Source notes

The broad PCG textbook and recent AIIDE field map are D-class synthesis. Procedural Scene Programs is A-class evidence for one recent hybrid scene-program and repair system under studied conditions. The AI Systems of Left 4 Dead is a B-class shipped-system account of pacing control, not proof for this architecture. The three-lane authority model, save policy, matrix, and operations contract are E-class.


12Chapter 12Capstone: build The Archive Below

Opening engineering question. What evidence would let another engineer reproduce, compare, challenge, and release a small procedural game rather than admire a handful of curated seeds?

Chapter thesis. The capstone is both a playable vertical slice and a generator laboratory. It freezes contracts, evaluates alternative architectures across one seed corpus, preserves failures, and binds a release decision to mechanics, expressive range, cost, provenance, and blind human evidence.

Archive dependency. Nothing resets. The seven-node, nine-edge cyclic dungeon; six-event history; six storylets; compile-time plaque; runtime curator fallback; and three authored anchors become one build.

12.1 Vertical-slice contract

A run starts at E, teaches evidence interpretation at G, exposes flood consequences at T, presents the counterweight and reliquary alternatives through L and R, performs the false restoration at F, and ends at V. The player can complete the run through at least two meaningfully different cycles. The history ledger changes faction claims, material interventions, damage, relic location, and storylet order while retaining the fixed entities.

The capstone ships one desktop target, one complete run loop of roughly 20–35 minutes under local testing, and a laboratory command that generates without rendering. The time range is an E-class scope choice. Non-goals include open world, network multiplayer, unbounded dialogue, runtime asset creation, persistent economy, and model-authored mechanics.

Diagram source

flowchart TD
  SP[Freeze artifact contract and hypotheses] --> IM[Implement typed representations]
  IM --> CL[Constructive + constraint baselines]
  CL --> HS[History and storylet projection]
  HS --> AI[Compile-time admission + runtime fallback]
  AI --> SC[Fixed seed corpus evaluation]
  SC --> PL[Playable integration and blind tests]
  PL --> EP[Evidence packet]
  EP --> GD{Release gate}
  GD -->|revise| SP
  GD -->|approve| RC[Versioned candidate]

Figure 12.1 — Capstone evidence loop (original). Revision returns to the earliest false hypothesis. The release gate evaluates a frozen candidate, not a moving branch.

12.2 Implementation phases

Phase 1 implements versioned data structures: history events, facts, mission nodes and guarded edges, spatial envelopes and ports, placements, storylets, candidate evidence, gate results, save state, and release manifest. Every ID is durable and every reducer replayable.

Phase 2 implements controlled randomness and the constructive baseline: split streams, room placement, cellular transept, port routing, flood fill, and contract-aware repair. The fixed graph from Chapter 4 is the first golden fixture.

Phase 3 implements variation: graph-rewrite rules, WFC dressing or local room synthesis, constraint validation, search genotype, objectives, and QD descriptors. All architectures decode to the same intermediate representations so their outcomes are comparable.

Phase 4 implements history and authoring: the six-event ledger, projections, perspectives, voice corpus, six storylets, fixed anchors, and compile-time registry. Phase 5 adds the optional runtime curator behind the typed boundary and compiled fallback.

Phase 6 integrates the engine, instruments run state, captures performance and media, performs blind evaluations, freezes a release candidate, and assembles evidence.

12.3 Seed corpus and test pyramid

Create corpus archive-corpus-v1 with 512 immutable root seeds. Reserve 320 development seeds, 96 regression seeds containing known edge cases, and 96 held-out release seeds. Do not move seeds between sets after inspecting release outcomes. Add hand-constructed adversarial fixtures for self-lock, missing port, contradictory WFC domains, impossible embedding, history precondition failure, duplicate inscription, provider timeout, and stale response.

Property tests cover:

  • exactly seven major spaces and stable authored anchors;
  • connected geometry for required ports;
  • finale reachability under at least one valid state trace;
  • no required key behind its own lock and acyclic lock dependencies;
  • at least two cycle functions with observable use windows;
  • replayable history state and resolvable entity IDs;
  • every placement and storylet claim linked to canonical facts;
  • no raw compile-time candidate referenced by a build;
  • no runtime-generated action changes authoritative state;
  • bounded time, memory, backtracking, repair, and fallback behavior.

12.4 Evidence packet and metrics

For each generator architecture and corpus partition, report raw validity, admitted validity, repair rate, repair severity, generation time distribution, peak memory, constraint contradiction rate, duplicate rate, expressive-range coverage, QD occupancy where applicable, and failure classes. For playable samples, report critical-path time, cycle use, optional-content discovery, interpretation selected, clue recall, fallback frequency, and human preference or distinction with uncertainty and sample details.

The packet should be machine-indexed but readable without custom infrastructure. One possible top-level manifest is:

candidate: archive-below-0.1.0-rc2
source_revision: <revision>
generator_release: archive-generator-0.1.0
evidence_cutoff: 2026-08-29
specification_hash: <sha256>
corpus:
  id: archive-corpus-v1
  development: 320
  regression: 96
  held_out: 96
results:
  generator_report: evidence/generator-summary.json
  failure_index: evidence/failures.jsonl
  expressive_range: evidence/expressive-range.json
  blind_protocol: evidence/blind-protocol.md
  blind_results: evidence/blind-results.csv
build:
  artifact: builds/archive-below-rc2.zip
  sha256: <sha256>
  engine_profile: <versioned-profile>
runtime:
  fallback_suite: evidence/runtime-fallbacks.json
  save_compatibility: evidence/save-compatibility.json
content:
  approved_registry: content/approved-manifest.json
  provenance_audit: evidence/content-provenance.json
decision:
  owner: <human-id>
  outcome: approve | revise | reject | evidence-insufficient
  rationale: evidence/release-decision.md

The manifest points to immutable evidence for the frozen candidate. Reports include tool versions and invocation parameters. Failure records are first-class: seed, stage, category, last valid representation, repair attempts, budget exhaustion, and minimized reproduction. Media carries build and run identity. If a screenshot cannot be connected to a run, release, and state trace, it may aid discussion but cannot certify the candidate.

Review evidence integrity before interpreting quality. Confirm that every held-out seed ran exactly once under the frozen release unless a recorded infrastructure failure required a declared rerun policy. Confirm that timeouts remain in denominators where appropriate. Confirm that repaired candidates retain pre-repair identity and severity. Confirm that blind labels were revealed only after judgments were locked. Confirm that the build hash played by reviewers matches the manifest.

Then inspect distributions. Percentiles are usually more useful than a mean alone for load-time latency and repair work. List the slowest and most repaired seeds. Cross-tabulate validity against descriptor niches so a diverse-looking map cannot hide that one niche survives only through aggressive repair. Compare route-use telemetry with graph intent: a declared risk/reward loop that no participant notices is not rescued by cycle rank.

Finally inspect experience evidence beside artifact traces. If a player calls the false restoration “random,” locate which facts and storylets they encountered. The cause might be evidence placement, wording, route choice, an event projection defect, or a missing observation—not a general dislike of procedural narrative. Preserve the complete observable path without attempting to record hidden reasoning. Ask the participant what they noticed and believed; do not infer an internal causal story from telemetry alone.

The release memo should state four levels of claim. Verified mechanism: named predicates passed under a fixture. Observed distribution: metrics over the fixed corpus. Observed experience: bounded findings from the blind protocol. Unresolved risk: important behavior the evidence does not cover. This ladder makes it difficult to turn “96 held-out seeds passed” into “the generator is reliable for all players.”

If the candidate is rejected, keep the packet. A rejected release is a baseline for the next architecture and prevents the team from rediscovering the same failure. Link the repair to the original evidence, create a new release ID, invalidate affected measurements, and rerun only what the dependency graph says is stale. Selective reruns are acceptable when their scope is explicit; mixing old and new evidence without lineage is not.

Table 12.1 — Generator experiment matrix. Values shown are study plans, not results.

ExperimentArchitecture AArchitecture BControlled variablesPrimary measuresFalsifying result
topologyconstructive rewritesconstraint/ASP formulationnode types, seed set, evaluation budgetvalidity, cycle function, timeB adds cost without coverage or validity gain
local spacecellular + repairWFC + global checkroom envelope, ports, tile budgetcontradiction, repair, legibilityWFC local validity creates more global bypasses
selectionweighted samplingQD searchdecoder, candidate budgetniche coverage, blind distinctionoccupied bins are not player-distinguishable
historycausal reducerevent-first rationalizationentity pool, six events, evidence budgetcoherence, projection coveragerationalization produces more unsupported claims
runtime textcompiled variantsmodel phrasing + fallbackfacts, UI, player promptlatency, fact precision, preferencemodel path adds no detectable value or harms reliability

The experiments compare mechanisms, not brands. A no-difference result is useful. If the constructive baseline is cheaper, more valid, and equally distinguishable, it should remain. Frontier components earn their place through observable benefit under the game’s contract.

12.5 Blind evaluation

Sample artifacts before reading generator labels. For topology, give expert reviewers abstract graphs and state traces, then ask them to identify route decisions and dependency defects. For spatial legibility, use standardized screenshots and short play traces. For history, ask players to reconstruct causal order and identify which evidence supports or contradicts the court account. For runtime text, compare cached responses under identical state, hide architecture, and keep fallback samples in the set.

Do not collapse every judgment into one number. Record distinction rate, route choice, clue recall, confidence, retellings, and rubric comments. Separate players familiar with procedural games from newcomers if the sample permits; their perception of novelty may differ. Report sample size and recruitment limits. This is a local design study, not population science.

12.6 Release gates

A release candidate passes only when:

  1. all hard property tests pass on held-out seeds and adversarial fixtures;
  2. raw and repaired metrics are both reported, with no unbounded repair;
  3. load-time tail latency and memory meet the declared target hardware budget;
  4. at least two cycles are used and understood in blind playable samples;
  5. history evidence supports the fixed reversal and finale without canon errors;
  6. compile-time content has complete lineage and human approval;
  7. runtime success, rejection, timeout, and offline branches preserve identical mechanics;
  8. active saves survive patch/reload tests under the declared compatibility policy;
  9. the evidence packet binds source, generator release, build, tests, media, and human decision;
  10. a named human accepts the game’s legibility, tone, and retellability.

No average quality score compensates for a failed hard gate. A release can be rejected because the sample is too small or a critical measure is missing. Honest insufficiency is better evidence than a confident launch memo built from favorite seeds.

12.7 Failure injection: the showcase build

The team selects six beautiful seeds, records a trailer, and reports that the generator creates “infinite histories.” The held-out corpus later reveals 7% mission deadlock, WFC restart tails above the load budget, repeated plaque structures, and a runtime provider whose offline path blocks the finale.

Every term in the claim was wrong or unsupported. The release gate replaces the gallery with a frozen corpus, generator-level metrics, preserved failures, blind play, and exact fallback checks. Marketing language is outside this book’s evidence contract; the team may say that release 0.1.0 passed its declared 512-seed suite and bounded playtest, not that it produces infinite or universally compelling worlds.

What this does not prove

Passing the capstone does not establish market fit, universal fun, long-term retention, accessibility for all players, security under every adversary, legal certainty, or production reliability at commercial scale. Five hundred twelve seeds sample a distribution; they do not enumerate it. Blind studies remain small and project-specific. The largest evidence limitation is that recent runtime-generative-AI work is concentrated in language-forward prototypes and does not establish long-horizon coherence, safe operation, or commercial reliability across game genres.

Chapter summary

The completed Archive is a game and an experiment: one reproducible artifact contract, multiple generator architectures, a fixed corpus, a causal past, visible authoring, quarantined compile-time proposals, bounded runtime phrasing, and release evidence. The engineering result is not “infinite content.” It is a possibility space whose validity, cost, diversity, meaning, and failures can be inspected and revised.

Review questions

  1. Why are held-out seeds fixed before inspecting release outcomes?
  2. Which generator measures must separate raw and repaired results?
  3. What does blind evaluation protect against?
  4. Why can a simpler baseline defeat a more recent architecture?

Design problems

  1. Write a preregistered comparison between QD search and weighted constructive sampling, including a result that would favor either.
  2. Design an evidence packet for a rejected release whose blocker is uncertain player comprehension rather than a code defect.

Implementation lab — Reproducible vertical slice

Build the entire Archive laboratory and one playable candidate. Run all 512 seeds, adversarial fixtures, five experiments, and a blind evaluation feasible for your setting. Observables: generator release, seed partitions, raw/admitted artifacts, repair traces, metrics with distributions, build hash, save compatibility, captures, participant protocol, and ship decision. Pass: another engineer can reproduce the evaluation, inspect failures, play the candidate, and understand every claim without model transcripts. Fail: only curated seeds are retained, external candidates lack provenance, runtime generation owns state, or the release decision is automated.

Source notes

The evaluation program synthesizes the PCG textbook, Search-Based PCG, Quality Diversity, and mixed-initiative sources (D/A). Recent generative-AI and AI-native-game surveys are D-class frontier maps, not release evidence. The capstone scope, corpus partitions, experiments, thresholds, and release gates are E-class specifications.


Thirty-day capstone schedule

Use one focused day per numbered item. If a task finishes early, improve evidence or reduce scope risk; do not add features. A checkpoint passes only when its observables exist.

Days 1–5 — Contract and representations

  1. Freeze the seven-node, nine-edge graph, three anchors, six history events, six storylets, non-goals, target hardware, and authority policy.
  2. Implement typed IDs and schemas for facts, events, mission nodes, guarded edges, rooms, ports, placements, storylets, evidence, saves, and releases.
  3. Implement artifact envelopes, hashing, specification identity, generator/version manifests, and hard-gate result types.
  4. Implement split random streams with golden vectors and per-stage draw accounting.
  5. Build the generator CLI and one hand-constructed golden artifact. Checkpoint A: replay reproduces every authoritative hash, and changing a specification invalidates dependent stages.

Days 6–10 — Topology and geometry

  1. Implement mission-state reachability, critical-path checks, cycle rank, cycle-function labels, and lock dependency validation.
  2. Implement room envelopes and anchor placement for the fixed graph.
  3. Implement the cellular flooded-transept interior, walker damage, port corridors, flood fill, and protected zones.
  4. Implement bounded spatial repair and preserve rejected attempts with causal diagnostics.
  5. Add graph rewrites and the complete Chapter 4 trace. Checkpoint B: self-lock, bypass, dropped-cycle, and closest-component repair injections all fail distinctly.

Days 11–15 — Constraints, search, and history

  1. Implement WFC domains, weighted entropy observation, propagation, bounded recovery, and global graph extraction.
  2. Implement the search genotype, decoder, hard feasibility rank, objective vector, and Pareto reporting.
  3. Implement QD descriptors and compare a small pilot against constructive sampling under a fixed budget.
  4. Implement the event reducer, six-event ledger, durable IDs, causal edges, and material/faction projections.
  5. Implement two perspective projections and archaeology evidence placement. Checkpoint C: deleting a causal event invalidates every dependent projection; prose cannot restore it.

Days 16–20 — Authoring and generative lanes

  1. Implement the voice corpus, canon pool, locked anchors, six storylet availability functions, typed effects, and reachability view.
  2. Build compile-time quarantine, manifests, schema/canon/duplicate/style/provenance gates, and approved registry.
  3. Admit one plaque and one dressing plan through human edit and engine staging; test dependency invalidation.
  4. Implement the typed runtime curator, state projector, validator, cache, deadlines, privacy minimization, and compiled fallback.
  5. Inject malformed, forbidden, moderated, slow, offline, and stale responses. Checkpoint D: all runtime branches preserve identical mechanics and finish within the UI budget.

Days 21–25 — Evaluation and playable integration

  1. Freeze the 512-seed corpus, partitions, adversarial fixtures, architecture versions, and experiment hypotheses.
  2. Run generator-level validity, repair, cost, latency, expressive-range, duplication, and QD measurements.
  3. Integrate the engine run, save admitted artifacts, instrument cycle use and storylet exposure, and capture standard views.
  4. Conduct expert graph review, blind spatial comparison, history reconstruction, and runtime-text comparison under the written protocol.
  5. Diagnose failures at the earliest broken representation and perform only bounded repairs. Checkpoint E: no hard failure remains hidden by aggregate quality or human preference.

Days 26–30 — Candidate and evidence

  1. Freeze generator release, dependencies, approved registry, engine version, build profile, and save compatibility policy.
  2. Generate held-out artifacts, build from clean state, run packaged scenarios, hash the candidate, and preserve failures.
  3. Complete performance, provenance, privacy, cost, accessibility-scope, fallback, migration, rollback, and known-limit records.
  4. Audit the full evidence packet and have a human play the frozen candidate without generator labels.
  5. Record approve, revise, reject, or evidence-insufficient. Final pass: another engineer can reproduce the laboratory, obtain the same authoritative artifacts where promised, inspect every deviation, and understand the decision without access to hidden reasoning or model conversations.

Frontier map at the evidence cutoff

Dated status: 29 August 2026. This map distinguishes evidence maturity in the frozen ledger. It is not a forecast, product ranking, or claim that every mature technique is easy.

StatusAreaWhat the admitted evidence supportsPrincipal unresolved boundary
Mature practiceseeded constructive generation, graphs, flood fill, grammars, search, explicit constraintslong-standing algorithms and production/research examples with inspectable representationsproject-specific meaning, authoring cost, and player perception
Mature practicedeterministic validation, fixed corpora, repair logs, authored anchorsordinary software and PCG evaluation techniques can bound validity and regressionsno verifier captures fun, taste, or all player strategies
Active engineeringWFC combined with global topology and bounded recoverymaintained implementations and analyses establish local constraint mechanismpredictable contradiction cost and global semantic control at scale
Active engineeringquality diversity and experience-aware evaluationresearch maps diverse high-quality sets and player-model integrationdescriptor validity, evaluation cost, and transfer to shipped games
Active engineeringprocedural history plus player archaeologystrong practitioner and research cases show causal traces, rationalization, and curationgeneral narrative-quality metrics and simulation compression rules
Active engineeringmixed-initiative generative authoringmultiple tools and studies support inspectable human–algorithm collaborationbroad usability evidence and durable creative-ownership measures
Promising researchlearned PCG and hybrid scene programssurveys and studied systems show useful proposal, representation, and repair approachesdata bias, controllability, generalization, and production economics
Promising researchstructured compile-time generative AIcurrent studies and production reasoning support proposal-plus-gate pipelinesoriginality, rights, evaluator correlation, and long-term maintenance
Promising researchruntime language surfaces with deterministic stateearly products, qualitative analysis, and prototypes show viable interactionslong-horizon coherence, moderation, privacy, availability, cost, and genre transfer
Unsupported hype“infinite unique content” from seed countno admitted evidence equates numeric seeds with perceptual uniquenessrequires game- and audience-specific measurement
Unsupported hypelocal adjacency creates globally meaningful levelsWFC evidence supports local compatibility, not progression or narrativeneeds explicit global representation and verification
Unsupported hypegenerative AI replaces designers, simulation, or verificationadmitted evidence supports bounded proposals and hybrid systemshuman taste, authority, provenance, constraints, and operations remain load-bearing
Unsupported hyperuntime AI is generally production-readyrecent evidence is concentrated in language-forward prototypes and surveyscommercial reliability across genres is not established

The largest limitation is external validity at the runtime frontier. The source set can describe mechanisms, prototypes, qualitative experience, and a few production histories. It cannot justify a general claim of safe, coherent, affordable, long-lived runtime generation across game genres and player populations.


Consolidated source notes

The chapter-local notes identify which source carries each important claim. This consolidated map states roles without turning citations into a paper roundup.

  • Field structure: Procedural Content Generation in Games and its constructive chapter are D-class foundations for algorithm and evaluation vocabulary.
  • Search, diversity, and learning: Search-Based PCG, Experience-Driven PCG, PCGML, Deep Learning for PCG, and Quality Diversity are A/D research and survey evidence with task- and representation-specific boundaries.
  • Topology and constraints: the WFC implementation, WFC reconstruction, graph grammar, ASP dungeon generation, constraint-programming variations, and Unexplored practitioner account support named mechanisms (A–C/B), not universal quality.
  • History and narrative: Dwarf Fortress creator sources, Qud’s historical-causation paper, simulated-storyworld curation, and information games support distinct architectures and player-curation arguments (A/B/D).
  • Authoring: mixed initiative, Tanagra, Tracery, ink, and the storylet essays provide A–D evidence for specific tools and design models.
  • Generative-AI frontier: the generative-AI PCG survey, AIIDE field map, AI Dungeon analysis, creator scaling report, and AI-native-games survey are A/B/D evidence for a fast-changing and externally limited frontier.

All Archive Below architectures, equations, graphs, values, metrics, traces, schedules, failure injections, and release gates are E-class book synthesis unless a sentence explicitly attributes a reported result.


Glossary

Admission. The process that turns a candidate into an approved artifact through noncompensable hard gates, scored preferences, provenance, and any required human decision.

Artifact. One generated candidate, such as a room graph, biome, biography, quest, mesh, line of dialogue, or encounter schedule.

Authored anchor. A fixed human-created element whose identity or function constrains procedural connective tissue. In the Archive these include the entrance, false restoration, and finale.

Behavioral descriptor. A measured artifact property used to locate candidates in a quality-diversity map. A descriptor is a design hypothesis about meaningful difference, not proof of player perception.

Canon. The versioned set of authoritative world entities, events, facts, and relations. Perspective claims and generated prose may interpret canon but do not become canon without explicit admission.

Compile-time generation. Generation before the shipped build or content release; outputs can pass offline review, repair, provenance, and build gates.

Constraint-based PCG. Generation that represents allowed relationships and solves for an assignment satisfying them.

Constructive generator. A generator that builds an artifact through a forward procedure without evaluating a population of complete candidates.

Cycle function. The intended gameplay role of a traversal cycle, such as reconnaissance, risk/reward, return, shortcut, or reversal. Cycle count alone does not supply function.

Expressive range. The distribution of reachable artifacts under chosen descriptive measures.

Generate-and-test. Sampling candidates, rejecting failures, and repeating under a declared budget.

Generative authoring. Tools that expand, arrange, critique, or repair author-created rules and content while preserving human editorial control.

Generator. A program that maps a specification, state, corpus, and seed to candidate content plus generation evidence.

Generator release. An immutable compatible bundle of generator code, schemas, specifications, corpora, validators, random protocols, repair policies, approved content, and migration rules.

Genotype. The represented object modified by search operators before decoding into a player-facing phenotype.

Hard constraint. A predicate every admitted artifact must satisfy.

Load-time generation. Generation when a world, run, region, or save is initialized; latency is bounded but content may persist for the session.

Mixed-initiative authoring. Human and computational components iteratively alter, constrain, evaluate, or select content.

Perceptual uniqueness. Player-observable difference that changes interpretation, strategy, or retellability, not mere mathematical difference.

Phenotype. The realized artifact produced by decoding a genotype and encountered or evaluated as content.

Possibility space. The set of artifacts reachable under a generator’s representation and rules, not merely the numeric seed space.

Procedural history. A generated set of durable entities and linked events whose trace can project state, evidence, perspectives, and narrative opportunities.

Quality diversity. Search for a collection of high-quality artifacts distributed across behavioral descriptors rather than one global optimum.

Quarantine. Immutable storage and status in which untrusted generated candidates remain inaccessible to shipping content until admission.

Runtime generation. Generation during active play in response to current state or player input.

Search-based PCG. Search through a represented artifact space using a fitness or quality function.

Seed. Explicit input that initializes pseudorandom choices; it is not a complete provenance record.

Simulation trace. Ordered state transitions from which history or emergent narrative can be reconstructed.

Soft objective. A scored preference that may trade against other preferences after hard constraints pass.

State projection. A bounded derived view of authoritative state prepared for a subsystem. A projection does not replace its source authority.

Storylet. A small authored narrative unit with availability conditions and state effects.

Typed runtime boundary. An interface that limits a runtime proposal to declared fields and effects, keeping deterministic game state authoritative.

Wave Function Collapse (WFC). A family of stochastic constraint-construction methods using domains, local compatibility, observation, and propagation. The name does not imply quantum computation.