# Hearth procedural composition

Hearth generates furnished timber-and-stone buildings and a connected settlement for Minecraft Java
1.21.1. The default seed is **0**; it produces five buildings, public paths, a well terrace, lights,
planters, trees and grass. Structural choices include room counts/functions/adjacencies, wings,
storeys, stair allocation, roof runs/pitches, porches, foundation strategies and street topology.
There is no whole-building family selector in the kernel or settlement generator.

## Quickstart

```sh
python generate.py
python generate.py --seed 0 --output example.litematic
python generate.py --seed 1 --count 6 --output "samples/six building village.litematic"
python -m pytest -q test
```

A successful command validates the composition, exports a nonempty single region, reloads it and
verifies its semantic content. Each schematic has a `.litematic.structure.json` companion. Keep the
pair together. Explicit paths may be relative, absolute or contain spaces.

No downloads, reference generator, previous output or credentials are used. Python 3.12 and numpy
are required; transport uses the provided MCIO **0.2.0** public API. It is imported normally, then
from `/work/generator/MCIO` in this environment. On another host, install MCIO from its source before
using export/reload. The Java blockstate reference is bundled under `hearth/data/`. Exact versions
observed here are recorded in [reports/dependencies.json](reports/dependencies.json); no additional
packages were installed. Rendering additionally needs the optional supplied MCRender toolset.

## Short compositions

These are intent descriptions; clients do not write voxels, repair geometry or assign block owners.

```python
from hearth.components.building import Blueprint, RoomSpec
from hearth.programs import building_scene

plan = Blueprint((
    RoomSpec(0, 0, 0, "living"),
    RoomSpec(0, 0, 1, "bedroom"),
    RoomSpec(1, 0, 0, "workshop"),
), bay=11, porch=True, roof_axis="auto")
scene = building_scene(plan, seed=17)  # No file export required.
```

Place on a previously generated environment:

```python
from hearth import Scene, Box, Frame
from hearth.environment import Terrain, gradient, wave
from hearth.components.building import adapted

scene = Scene(seed=17, domain=Box((-15, -4, -20), (40, 60, 40)))
field = gradient(x=0.025, base=4) + wave(amplitude=0.7)
scene.place("land", Terrain(scene.domain, field))
scene.compose_choice(adapted("home", plan, "/land", Frame((3, 0, 4), 1)))
scene.finalize()
```

Discover and substitute implementations:

```python
from hearth.kernel import Registry
from hearth.components.interior import Light
from extension_demo import Pendant

registry = Registry()
registry.register(Light())
registry.register(Pendant())
candidates = registry.select("room-light")
# Either implementation can be supplied as Blueprint(..., light_component=...).
public_ports = scene.view.offers("/home", "access")
capability = scene.view.capability("/home")
```

`hearth.composition` provides `encapsulate`, `attach`, `arrange`, `repeat`, `scatter` and `constrain`.
A composition returns `Plan(children=[Child(...), Choice(...)])` and uses the same component protocol
as a light or tree. Building, reading-suite and settlement interfaces support recursive port
forwarding. [ARCHITECTURE.md](ARCHITECTURE.md) documents frames, grants and the complete lifecycle.

## Runnable examples and batches

```sh
python -m examples.prototype --seed 0
python -m examples.building dwelling --seed 3 --output samples/dwelling-demo.litematic
python -m examples.building atelier --seed 5 --output samples/atelier-demo.litematic
python -m examples.building commons --seed 6 --output samples/commons-demo.litematic
python -m examples.courtyard --seed 0
python -m examples.gallery --seed 0
python -m examples.extension --seed 0
python -m examples.inspection --seed 0
python -m examples.assess --seed 0 --output reports/reassessment --artifacts
python -m examples.verify_replay --seed 0
```

The three primary programs are short room-graph recipes in `hearth/programs.py`. The courtyard and
gallery clients were written after the abstractions existed. The independent extension supplies an
actual pendant light and a nested reading suite using public components/validators. The gallery uses
that extension without geometry repairs. The courtyard exposed a generic concave-corner decoration
conflict, corrected by moving facade climbers away from corner installation margins.

The assessment command is an explicit batch output: it writes all inputs, results, rejections,
candidate scores, summaries and selected samples. Unit tests create only cleaned temporary files
under `test/`; they do not silently produce corpus artifacts.

Optional rendering, in the supplied proc-tool environment:

```sh
python -m examples.preview --seed 0 --input output.litematic --output previews/settlement --size 1500
python -m examples.preview --seed 6 --input samples/commons-6.litematic --output previews/commons-6 --cutaways
python -m examples.preview --seed 0 --input samples/adaptation-00.litematic --output previews/adaptation-00 --cutaways
python -m examples.preview --seed 1 --input samples/atelier-1.litematic --output previews/atelier-1
python -m examples.preview --seed 0 --input samples/courtyard.litematic --output previews/courtyard-0 --cutaways
```

The preview command checks the source pair and seed, then uses the supplied MCRender and cutaway
utilities. It writes labeled views, camera records and `views.json`. The stair section is chosen
from an actual stair instance's current cells. Geometry-only slices are not exported as completed
components and have no structural companion. See [previews/README.md](previews/README.md) for inspected
views and observations. Rendering is not needed for generation or tests and must not be invoked on
another host without the optional tools/assets.

## Seeds, domains and adaptation

Seeds are explicit signed Python integers. SHA-256 derives streams from seed, stable instance keys
and purpose; Python `hash()` and ambient randomness are never used. Planning, adaptation, geometry,
materials and decoration use separate purpose keys. `Child(..., seed=...)`, `Scene.place(..., seed=...)`
and `regenerate(..., seed=...)` override a subtree. `Scene.fork(seed=...)` preserves existing frozen
content and changes only the seed for future placements. Stable independent branches commute;
dependent grass/tree replacement intentionally does not.

The delivered building planner supports connected grid rooms with bay sizes **9, 11 or 13**, six
furnishing purposes, supported stacked levels, shared horizontal circulation and one vertical flight
per upper connected group. Ordinary room contracts support the same bay sizes. Walls expose widths
5-64, heights 4-12 and thicknesses 1-3. Other implementations can advertise different feasible domains;
the kernel has no room-grid or building-count dispatch.

Site policy defaults: measured relief at most **5**, bed-to-floor support height at most **8**, at least **two contiguous solid bed cells**, approach
length at most **12**, foundation fill at most **1,600** cells and excavation authority bounded by the
terrain grant (default 2,500 changes per binding). `SiteLimits` and grants expose these values. Contact
alternatives compare actual effects, permitting local piers, stepped perimeter work and access treads.
The default buildings do not excavate; the pool component exercises authorized excavation separately.
Small terraces fill bounded local differences. The major terrain surface is not flattened.

Hard constraints include write authority, existing consumers, declared support/headroom, protected
regions, locked room functions and placement. Preference fields and style roles are public observations.
Preferences do not override constraints. Unknown space is an error. The kernel rejects effects outside
accepted envelopes and derives export bounds from realized content, including vegetation and adapters.
`Limits` controls dimensions, block count, instances, recursion, candidate budget and dense export volume.

A completed standalone building offers an exterior landing. Its enclosing composition is responsible
for a public path beyond that landing; a wet site can offer a boardwalk landing. The settlement fulfills
this obligation and exposes its own public gateway. It can be translated and rotated as a composite.

## Inspection, identity and regeneration

```python
from pathlib import Path
from hearth.persistence import export_scene, load_scene

point = next(p for p, cell in scene.blocks.items() if cell.state == "minecraft:glass")
explanation = scene.inspect(point)
print(explanation["chain"], explanation["related"], explanation["operation"])
cells = scene.cells(explanation["instance"], descendants=True)
export_scene(scene, Path("sample.litematic"))
restored = load_scene(Path("sample.litematic"))
assert restored.inspect(point) == explanation
```

The runnable inspection example selects actual room glass and prints its window, host wall, room and
building chain, typed relationships and exact cells before and after reload. See
[reports/inspection.txt](reports/inspection.txt). `cells(..., descendants=True)` follows semantic
attachment/containment indexes, including windows installed by a higher-level facade program.
`shared=True` includes explicitly shared supports. Removed/displaced objects are not current owners.

World coordinates are `(x,y,z)`. Export coordinates subtract the JSON `offset`; reload restores the
world coordinates. Quarter-turns transform states, ports, claims and ownership consistently. Explicit
property mappings compare regardless of order; omitted properties are never inferred for equality.
Inventory NBT is transported and verified. Missing, unknown or mismatched companions are rejected;
a bare schematic is not claimed to contain its original semantic graph.

`scene.regenerate("/land", new_terrain, dependents=("/house",))` explicitly replaces affected output
and replays dependent branches. Old displaced terrain is restored before replay. Dependency records
include automatic spatial/interface read traces and input versions. Invalidated branches cannot be
exported as completed. After reload, regeneration requires an explicit component implementation;
serialized metadata is never executed as Python.

## Diagnostics and failure behavior

`ContractError.diagnostic` contains `rule`, `component`, `position` and `conditions`.
`ValidationError.diagnostics` reports actual geometry violations. Examples include `write-authority`,
`whole-object`, `edit-limit`, `protected-region`, `support`, `clearance`, `reachability`, `lighting`,
`door-pair`, `pool-containment`, `forwarded-interface` and `geometry-mismatch`.

Failed candidates leave the entire scene unchanged. `SearchExhausted` distinguishes a search budget
from an established parameter/contact incompatibility. A failed finite search does not prove that
no other algorithm or composition can succeed. Tests include a budget-limited rejection where the
next, unvisited candidate is valid.

## Evidence and limits

The frozen sampling policy is [reports/sampling-policy.json](reports/sampling-policy.json).
The current results are [reports/final-corpus/results.json](reports/final-corpus/results.json),
[summary.json](reports/final-corpus/summary.json) and
[adaptation-inputs.json](reports/final-corpus/adaptation-inputs.json). Earlier result records remain
under `reports/baseline-corpus/` and `reports/corpus/`; their historical sample paths are labeled as
superseded, not current matching artifacts.

[reports/ASSESSMENT.md](reports/ASSESSMENT.md) gives denominators, costs and timings: **134 tests
passed**, **64/64** adaptation inputs, **24/24** building runs and **10/10** settlement runs validated.
The stress batch retained **9 valid / 32 inputs**, plus **23 explicit limit incompatibilities**.
There were no budget-exhausted or unexplained-defect cases in the final corpus. Per-candidate
acceptance is reported separately. Seed-0 content matches across two Python hash seeds in
[reports/replay.json](reports/replay.json). All **24 delivered current artifact pairs** passed reload
and identity checks in [reports/artifact-audit.json](reports/artifact-audit.json).

The assessed finite budget consists of 64 independent environment/building pairings, 24 building
runs (three clients, seeds 0-7), ten settlement runs (seeds 0-7 plus both count boundaries), and 32
unresampled stress inputs. Sixteen complete terrain scenes are frozen independently before placing
buildings. Half the environment expressions use the held-out blend/transform composition. The same
public measured-geometry adapters handle all cases.

The reported successful building corpus has **18** observed principal signatures: dwelling **5/8**,
atelier **8/8**, commons **5/8**. The ten settlement runs have **10** observed signatures. Signatures
exclude names, surface materials and global placement; they include actual room extents, adjacencies,
storeys/stairs, roof geometry and path organization. Foundation/contact signatures are reported
separately and never counted as principal architectural variety. This is finite observation only.

Known limits remain explicit:

* The movement model uses integer standing positions, operable wooden doors, two-cell headroom and
  bounded one-block elevation changes. It is not the full Minecraft collision or jump simulation.
* Lighting uses actual source propagation/occlusion at required room locations; it is not a complete
  skylight, mob-spawning or Minecraft update simulation.
* Declared support paths and bounded spans are checked. Arbitrary structural stress, every decorative
  cantilever, and universal watertight flashing for arbitrary roof intersections are not proved.
  The delivered roof system handles bounded gables, runs and wall abutments over sealed ceilings.
* General block/entity migration, arbitrary entity generation, a browser viewer, and a full city
  planner are not implemented. Exported entity lists are empty; barrel inventories are real NBT.
* Regeneration is explicit and can be coarse. The kernel records affected dependencies and refuses
  stale completion; it does not invent an unbounded automatic replan or resolve every terrain shape.
* The provided style is coherent timber/stone architecture, with visible modular bays. The small
  representative render set supports inspection, not an exhaustive aesthetic judgment or a claim
  to reproduce all sixteen reference images.
* The courtyard example's central planted void is an unoccupied lightwell. Its room ring is connected;
  visitor access to the central garden is not part of that client's contract.

## Requirement ledger

| ID | Implemented API/module and evidence | Qualification |
|---|---|---|
| R01 | `kernel/*`, initial design, seven foundation tests before content; thin CLI | Executable foundation, not placeholder interfaces |
| R02 | Independent implementation; supplied snapshots unchanged; reference images used as aesthetic goals | No reference generator invoked or imported |
| R03 | `Blueprint`, room graph programs, `Choice`, roof planner, spine/loop paths; finite signatures | Room grid and roof primitives are bounded, openly documented |
| R04 | Module table in architecture; kernel has no component imports; transport separate | Browser host adapter not implemented |
| R05 | `Capability`, executable `Domain`, `Contract`, `Port`, `Grant`, rules and read-only `View` | Free-form descriptive assumptions complement executable checks |
| R06 | `Plan/Child/Choice`, registry, composition operations, forwarded ports; extension/nested tests | New primitives can extend beyond the shipped grid vocabulary |
| R07 | Scoped authority, whole-object replacement, shared support; tree/grass/pool/window/clearance tests | No universal priority or same-state sharing shortcut |
| R08 | Fork/validate/commit kernel, plans and automatic read traces; rollback snapshots | Trusted Python components, not a hostile-code sandbox |
| R09 | Open/complete scopes, ancestor-aware obligations, finalization; unfinished/light and late-edit tests | Standalone landing-to-public-path is an enclosing obligation |
| R10 | Automatic nodes/operation owners, real window/wall instances; inspection and cross-scope attachment tests | No per-voxel client owner maps or post-hoc tagging |
| R11 | Structural graph, dependency graph, operations/displacement records; update/share/removal tests | Historic actors may remain in history, never as current owners |
| R12 | `inspect`, owner/shared reverse indexes, semantic descendant index; regeneration and deletion tests | Headless queries delivered; no clickable viewer |
| R13 | Paired JSON/Litematica, version/digest/offset checks, actual reload validation; mismatch/NBT tests | Pairing integrity is not cryptographic authenticity |
| R14 | General field algebra, masks, transforms, strata, water and constrained scattering | No environment-family dispatch; finite shipped operations are extensible |
| R15 | Domain/version-aware 3D view, elevation cap, support/water/slope/clearance/style/preferences | Unknown space errors; no simulation of every Minecraft behavior |
| R16 | Foundation, approach, window-depth and roof-abutment components | Universal roof-junction/flashing solver not implemented |
| R17 | Frozen terrain, measured site survey, bounded complete candidates, joint tentative validation | Fixed principal intent; failures beyond bounds are retained |
| R18 | Hard checks then actual effect cost/exposure score, seeded near-best choice, rejection records | Search-budget negative test; no claim of exhaustive feasibility |
| R19 | Automatic/declared input dependencies, stale flags, explicit atomic co-regeneration | Dependency updates are conservative; no implicit arbitrary auto-replan |
| R20 | SHA-256 scope keys/purposes, overrides, copied environments; branch/order/retry and hash-seed replay tests | Genuine spatial dependencies may change descendants |
| R21 | Configurable `Limits`, `SiteLimits`, effect envelopes and realized export bounds | Demonstration count bound is only in the CLI |
| R22 | Initial design, kernel tests, prototype, buildings/extension, corpus/render stages | Generic defects and fixes recorded in development findings |
| R23 | `test_kernel`, `test_contracts_provenance`: substitution, independent extension, authority, rollback, sharing, transforms, seeds | Custom validator registration also tested |
| R24 | Glass chain, two identities, external attachment membership, updates/deletions/regeneration, shared cells, transport mismatch tests | Actual structure restored from companion, not inferred from materials |
| R25 | 64 frozen pairings, compatible independent field/environment, protected outside cells, perturbation and stress records | Finite supported domain; 32 stress inputs retained without resampling |
| R26 | Three short clients x eight seeds; settlement x eight seeds plus counts 3 and 6; later courtyard/gallery | Programs use public room/component APIs |
| R27 | Actual blocks/NBT: schema, support, headroom/routes, pair consistency, enclosure, lights, furnishings, pools and path joins; deliberate damage tests | Physical/lighting model limitations above apply |
| R28 | Structural/contact signatures, exterior views, circulation/furnishing cutaways, inspection notes | Modular aesthetic remains visible; no exhaustive beauty claim |
| R29 | `generate.py`, importable scene builders, inspection example, verified one-region transport | Offline runtime uses bundled schema and installed/provided MCIO |
| R30 | Library, docs, CLI, tests, extension, output pair, manifest, reports and labeled previews | Broader simulation, arbitrary entities, browser UI and city planner remain unfinished |
