# Hearth architecture, version 1.1.0

The initial design was written before the kernel or extensive scene geometry. The executable
foundation passed seven tests before the terrain/grass/tree/wall/window prototype, then furnished
rooms and buildings were added, followed by settlements and the finite corpus. The stage sequence and generic fixes
are recorded in [reports/development-findings.md](reports/development-findings.md). This document
describes the implemented design; [GENERATOR.md](GENERATOR.md) contains usage and the R01-R30 evidence ledger.

## Module boundaries

| Layer | Modules | Responsibility |
|---|---|---|
| Values and geometry | `space`, `blocks`, `randomness` | Inclusive integer boxes, frames, Java blockstates, stable random scopes |
| Composition kernel | `kernel/contracts`, `scene`, `view`, `validation`, `errors` | Negotiation, permissions, transactions, instances, graphs, queries and rule scheduling |
| Environments | `environment/fields`, `terrain` | Composable field expressions, frozen sampled strata and water |
| Architectural knowledge | `components/*`, `adapters/site` | Windows, walls, furnishings, rooms, roofs, buildings, contact and access strategies |
| Public composition | `composition`, `programs` | Selection, encapsulation, arrangement, repetition, scattering, room graphs and settlement intent |
| Transport and assessment | `persistence`, `assessment`, `examples/*` | Verified Litematica export/reload, inspection, explicit batches |
| Independent extension | `extension_demo` | A different light and a composite reading suite with a forwarded entrance |

The kernel imports no concrete architectural implementation and never imports the CLI. The CLI is
an ordinary client. A browser adapter could retain the kernel, field expressions, plans and JSON
records, replacing the Python host/transport. No browser runtime or UI is included.

## One protocol for leaves and composites

A component implements:

```python
capability() -> Capability
negotiate(context: Context, parameters: dict) -> Contract
realize(context: Context, contract: Contract) -> Plan
```

`Capability` separates feasible offers from a placed instance. It includes semantic tags, executable
`Domain` checks for constructor inputs and execution parameters, assumptions, adaptation strategies,
guarantees, implementation version and locked decisions. Nested constructor paths such as
`design.bay`, and `frame.turn`, have executable domains. Constructors carry explicit principal intent;
`parameters` contains only advertised runtime overrides. Unknown overrides fail. Recorded inputs
include public constructor fields, execution arguments and negotiated decisions.

`Contract` contains a conservative local envelope, ports, grants, rules, decisions, input regions and
whole-object status. It becomes a world-space contract through the instance frame. Occupied geometry
is derived from effects and indexed exactly; an envelope is never substituted for actual membership.
Rules express support, protected clearance, preservation, enclosure, lighting, furnishing and access.
Effect coordinates must stay within the negotiated envelope, and child envelopes within their
parent's envelope. Expansion requires another negotiation.

A `Port` has a kind, oriented frame, region, capacity, alignment, facts and an optional grant. Wall
ports expose thickness, sill and excluded frame margins. A `Binding` names a host and port, a verb,
and an optional further restriction in **world coordinates**. Installation requires compatible
orientation, anchor alignment, available capacity and a compatible grant. Windows negotiate their
reveal depth against the public port; parents can substitute shuttered and hooded implementations.

Composite ports may delegate to a named child port. The kernel resolves authority through the
chain, while callers bind to the composite. It verifies the realized child's frame, region and kind
against the negotiated public interface, including during later validation. Buildings forward their
street connection; settlements forward a public gateway through their path composition. The
independent reading suite forwards its room entrance. Parents do not name private approach children.

## Plans, candidates and transactions

`Plan` contains writes, children, bounded `Choice` operations and typed relationships. Component
code reads an environmental view and returns effects. It cannot receive the shared mutable store
through its context. The view copies contract/port records and exposes styles through a read-only
mapping. This is a trusted Python programming protocol, not an arbitrary-code security sandbox.

A placement forks the current state. The kernel:

1. Allocates a stable instance path and random scope; checks feasible domains.
2. Negotiates a contract and resolves binding authority.
3. Applies final per-coordinate effects under the executing component/operation identity.
4. Instantiates semantic children through the same protocol.
5. Checks tentative geometry, existing consumers and completed local obligations.
6. Commits the entire state or discards the entire candidate.

Multiple writes inside one candidate component are coalesced to their final operation. They do not
create false collisions with earlier versions of that component's own local plan. Foreign writes
still require authority. The kernel never uses a global priority or identical-state overwrite rule.
Failed transactions preserve geometry, nodes, ownership, ports, relationships, dependencies, history
and sibling random scopes.

`Choice` evaluates complete candidate child compositions in isolated forks. It first checks hard
conditions, then scores actual sitework cost and exposed support proportions. It selects by a scoped
seed among alternatives within an explicit quality tolerance. `adapted(...)` proposes stepped
perimeters and piers under the same locked principal design. Water/high relief constrain the feasible
strategy set. Candidate scores and all rejection diagnostics are recorded. A bounded search with
unvisited alternatives reports `SearchExhausted`; identical hard failures of every declared contact
alternative retain the specific failed constraint. This is not a proof about unimplemented techniques.

## Authority, phases and logical objects

A grant identifies an owner, region, allowed verbs, consumer tags, per-binding change limit and
whether whole-object replacement is allowed. Binding restrictions can narrow a grant. A high planting
preference never grants excavation rights. Soil grants local construction edits, planting consumes
substrate support, and grass explicitly grants whole-object replacement to trees. Existing support
and clearance rules survive unrelated edits. Pools cannot undermine a supported tree. Paired plants
and doors cannot be partially replaced through an ordinary binding.

Property adjustments retain the original semantic owner and require the same block type. Deletions
remove current ownership; erasure history is separate from current cells. Displaced cells are retained
compactly so branch removal/regeneration can restore surviving host content. Retired grass disappears
from current nodes, relationships and ownership, while the operation history can still explain its
replacement.

Explicit shared support records a participant, a capacity use, a support obligation and a typed
association. It does not transfer the primary owner. Shared writes require consumer rebinding;
identical states alone never authorize sharing.

Construction starts with a temporarily open scope. Invariants run throughout; completion rules run
when the scope closes. `complete=False` permits an explicitly unfinished scope, and `finish_scope`
closes it. Unfinished or stale content cannot be finalized or exported. Once a room is complete,
subsequent placements must preserve its access, lighting and enclosure. A building provides internal
circulation and an external landing. The settlement discharges its connection to public paths.

## Environmental observations and adaptation

`View` uses world coordinates and explicit known bounds. `Context.world/local` convert positions;
`Context.elevation/water/state` are local-frame convenience queries. Views expose actual 3D states,
owners, solid support, bounded elevation search, water, slope, substrate depth, clearance, protected
regions, obstacle distance, style roles, preferences and public interfaces. Unknown space raises an
error. A roof is not assumed to be the ground surface: path observations are bounded by the offered
access elevation.

Field expressions support constants, gradients, waves, radial masks, addition, multiplication,
blending, transforms and clamping. They can be nested and supplied by an independent compatible
implementation. Water intersects the sampled strata. Adaptation never inspects an environment class,
recipe label or particular seed. The 64-case assessment freezes sixteen complete 3D terrain scenes
before making four independently seeded building placements on copies of each.

Sitework measures support and water, preserves gravity alignment, and bounds relief, post height,
fill, excavation grants and approach length. Foundations produce support columns/perimeters to the
actual solid bed. The approach examines its full tread width and water surface. The principal room
graph, functions, footprint bays, locked horizontal placement and chosen roof intent remain intact.
No algorithm levels the whole site to guarantee success.

## Three distinct graphs and exact indexes

An instance ID is its stable parent/key path. The kernel automatically records creation type,
constructor inputs, resolved decisions, frame, implementation and random scope. Helper calls do not
create semantic ancestors. Windows, walls, floors, furniture, lights and adapters are actual instances.

* Structural containment and attachment form a graph. Attachment supplies the primary structural
  chain, while containment remains recorded. Bridges/path networks can relate to many structures.
* Data/constraint dependencies have a source, consumer, region, input version and reason. An automatic
  read trace coalesces actual spatial observations and records interface reads, supplementing declared
  regions and bindings. These are not false structural ancestors.
* Operations retain generating actor, operation key, write count, displaced identities and restorable
  old cells. These records do not make a displaced object a current owner.

The sparse coordinate map stores one current owner and operation per occupied cell. Reverse maps
provide exact cells by owner and shared participant. A structural adjacency index supports descendant
queries through attachment as well as containment: a window created by an external facade program
is still included when highlighting its host wall or building. Queries traverse this graph, never
scan the full voxel store or copy ancestor strings onto each cell.

Removing a branch updates all indexes. External attached/dependent consumers must be regenerated or
removed together; otherwise validation rejects the transaction. `regenerate(path, ..., dependents=...)`
restores displaced host output, removes obsolete nodes and replays affected branches from their
original inputs/scopes. It never repeatedly cuts the already modified terrain. Explicit co-regeneration
is intentional: there is no hidden oscillating terrain/building update loop.

## Persistence, coordinates and replay

Positions are `(x,y,z)`, Y up, north -Z. A positive quarter-turn maps `(x,y,z)` to `(-z,y,x)`.
Frames transform coordinates, boxes, rule cells, ports and directional block properties, including
cardinal connection keys, axes, rotation values and supported rail/orientation strings. Custom rule
`data` is uninterpreted; a validator needing directions uses its node frame.

Export bounds are derived from every realized occupied cell. MCIO indexing is converted explicitly
to `(y,z,x)`. Export-local coordinates equal world coordinates minus the companion's `offset`.
The original world frame is restored on reload, including negative coordinates.

`persistence` writes one Java 1.21.1 region (data version 3955) and a versioned structural JSON record.
It retains capabilities/contracts, nodes, frames, random scopes, styles, field inputs, dependency and
structure graphs, current ownership, operation/displacement records, and relevant inventory NBT.
The geometry digest canonicalizes parsed names and **explicit** property mappings and includes world
coordinates and block-entity data. It ignores property order only, not missing/defaulted properties.
Reload reads actual schematic blocks and NBT, verifies dimensions/digest/ownership and reruns the
validators. Missing/unknown metadata or mismatched geometry is rejected as untrusted.

The companion is not a cryptographic signature, and arbitrary geometry cannot reconstruct a graph.
Reload does not execute serialized Python. To regenerate a reloaded branch, explicitly supply its
component implementation; inputs and source programs/manifests support replay. Arbitrary entity types
and a general block-entity migration system are not implemented; these artifacts export no entities.

## Validation model and limits

Validators register through `@validator(name)`; component authors use existing rules or add a named
handler without editing dispatch. Missing handlers are errors, including after reload. The physical
model uses integer standing positions, two air/passable cells, cardinal moves and elevation changes
of at most one block with extra clearance for ascending/descending. Wood doors are considered
operable. Stairs are checked as usable flights and declared clearance volumes. This is not a full
Minecraft collision/fluid/redstone simulator.

Lighting propagates actual source levels through passable/transparent cells with unit attenuation;
closed opaque boundaries block propagation. It checks required room locations, not a claim that all
possible mob-spawning cells are spawn-proof. Enclosure checks actual room floors/ceilings and wall
surfaces. Roof abutments are bounded voxel joins above sealed ceilings; universal flashing or
structural mechanics are not proved. Support checks declared load paths, substrate and support grids,
not an engineering stress solver for arbitrary blocks or decorative cantilevers.

Default limits are 512 blocks per axis, 1,000,000 occupied blocks, depth 40, 10,000 instances and 24
search alternatives, with at most 16,000,000 cells in the dense export bounding box. Demo count limits live in the CLI, not the kernel. Costs, bounds and failure
conditions are public. Existing tests and finite observations establish only the documented scope.
