# gvn.kernel

State machines and their verifier: blueprints you declare, definitions that are proven complete, the machines built from them, decisions, schemas and diagrams. It is the innermost layer and imports nothing else in gvn.

The ideas behind it are explained in [Machines](../../concepts/machines.md), [1. A first machine](../../tutorials/first-machine.md). This page is generated from the source, so it lists every public name with its signature and docstring. [Python API](../python.md) has the other packages and an index of every name.

## Modules

| Module | What it holds | Names |
|---|---|---|
| [`gvn.kernel.blueprint`](#gvn.kernel.blueprint) | Blueprints: the mutable, unverified way to write a definition down | [`MooreBlueprint`](#MooreBlueprint), [`MealyBlueprint`](#MealyBlueprint) |
| [`gvn.kernel.decision`](#gvn.kernel.decision) | Decisions: branching on data without losing completeness | [`UndeclaredOutcome`](#UndeclaredOutcome), [`Decision`](#Decision) |
| [`gvn.kernel.definition`](#gvn.kernel.definition) | Machine definitions: the formal tuple (Q, Sigma, Lambda, delta, omega, q0, F) | [`DefinitionRejected`](#DefinitionRejected), [`Step`](#Step), [`Definition`](#Definition) |
| [`gvn.kernel.diagram`](#gvn.kernel.diagram) | Drawing definitions: a machine as text a person or an agent can read | [`Mermaid`](#Mermaid), [`Dot`](#Dot), [`Table`](#Table) |
| [`gvn.kernel.diff`](#gvn.kernel.diff) | Comparing definitions: exactly what changed between two versions of a machine | [`Change`](#Change), [`Difference`](#Difference) |
| [`gvn.kernel.durable`](#gvn.kernel.durable) | Durability: the Dto protocol | [`Dto`](#Dto), [`DtoOf`](#DtoOf), [`require_own_dto`](#require_own_dto), [`Durable`](#Durable) |
| [`gvn.kernel.machine`](#gvn.kernel.machine) | A running machine: one current state, driven by inputs, never doing I/O | [`DefinitionMismatch`](#DefinitionMismatch), [`Machine`](#Machine) |
| [`gvn.kernel.schema`](#gvn.kernel.schema) | Explicit runtime schemas | [`SchemaViolation`](#SchemaViolation), [`Schema`](#Schema), [`Text`](#Text), [`Integer`](#Integer), [`Number`](#Number), [`Boolean`](#Boolean), [`OneOf`](#OneOf), [`Nullable`](#Nullable), [`ListOf`](#ListOf), [`MapOf`](#MapOf), [`Json`](#Json), [`Record`](#Record) |
| [`gvn.kernel.symbols`](#gvn.kernel.symbols) | The vocabulary of machines: states, symbols and alphabets | [`Symbol`](#Symbol), [`State`](#State), [`UnknownSymbol`](#UnknownSymbol), [`Alphabet`](#Alphabet) |
| [`gvn.kernel.verifier`](#gvn.kernel.verifier) | The verifier: proves a machine definition complete before it can exist | [`Finding`](#Finding), [`Report`](#Report), [`Verifier`](#Verifier) |

## gvn.kernel.blueprint

Blueprints: the mutable, unverified way to write a definition down.

A blueprint accumulates declarations and never complains while doing so (beyond
TypeError for a non-str name). All judgement is the verifier's:
``examine()`` returns the Report, ``build()`` returns a verified Definition or
raises DefinitionRejected. Every declaring method returns the blueprint, so
declarations chain.

    agent = (
        MooreBlueprint("agent")
        .inputs("started", "answered", "failed")
        .outputs("idle", "invoke_model", "done")
        .state("idle", output="idle")
        .state("thinking", output="invoke_model")
        .state("completed", output="done", final=True)
        .initial("idle")
        .on("idle", "started", "thinking")
        .on("thinking", "answered", "completed")
        .on("thinking", "failed", "completed")
        .otherwise_stay()
        .build()
    )

Constants: `MEALY`, `MOORE`.

### MooreBlueprint

```python
from gvn.kernel.blueprint import MooreBlueprint
```

```text
MooreBlueprint(name: str) -> None
```

#### MooreBlueprint.inputs

```text
inputs(*names: str) -> typing.Self
```

Declare input symbols (accumulates across calls).

#### MooreBlueprint.outputs

```text
outputs(*names: str) -> typing.Self
```

Declare output symbols (accumulates across calls).

#### MooreBlueprint.state

```text
state(name: str, output: str, final: bool = False) -> typing.Self
```

Declare a state and the output it emits.

#### MooreBlueprint.initial

```text
initial(name: str) -> typing.Self
```

#### MooreBlueprint.on

```text
on(source: str, input: str, target: str) -> typing.Self
```

Declare a transition: in state ``source``, the input ``input`` moves to ``target``.

#### MooreBlueprint.branch

```text
branch(source: str, outcomes: Alphabet, routes: Mapping[str, str]) -> typing.Self
```

Route the outcomes of a Decision out of ``source``.

``outcomes`` is the Decision's Alphabet; ``routes`` maps outcome name to
target state name. Records an obligation for every outcome and a transition
for every route, so a missing route becomes an ``unmet-obligation`` finding.

#### MooreBlueprint.otherwise_stay

```text
otherwise_stay() -> typing.Self
```

Undeclared inputs leave the state unchanged.

#### MooreBlueprint.otherwise_go

```text
otherwise_go(target: str) -> typing.Self
```

Undeclared inputs in a non-final state move to ``target``.

#### MooreBlueprint.to_dto

```text
to_dto() -> Definition.Dto
```

The Definition.Dto for what has been declared so far, unverified.

Raises SchemaViolation only if the declarations cannot be expressed as a
Dto at all (for example no initial state was named).

#### MooreBlueprint.examine

```text
examine() -> Report
```

The verifier's Report for what has been declared so far.

#### MooreBlueprint.build

```text
build() -> Definition
```

A verified Definition, or DefinitionRejected.

### MealyBlueprint

```python
from gvn.kernel.blueprint import MealyBlueprint
```

```text
MealyBlueprint(name: str) -> None
```

#### MealyBlueprint.inputs

```text
inputs(*names: str) -> typing.Self
```

#### MealyBlueprint.outputs

```text
outputs(*names: str) -> typing.Self
```

#### MealyBlueprint.state

```text
state(name: str, final: bool = False) -> typing.Self
```

#### MealyBlueprint.initial

```text
initial(name: str) -> typing.Self
```

#### MealyBlueprint.on

```text
on(source: str, input: str, target: str, output: str) -> typing.Self
```

Declare a transition and the output it emits: in state ``source``, the input
``input`` moves to ``target`` and emits ``output``.

#### MealyBlueprint.branch

```text
branch(
    source: str,
    outcomes: Alphabet,
    routes: Mapping[str, Sequence[str]],
) -> typing.Self
```

As MooreBlueprint.branch; ``routes`` maps outcome name to ``(target, output)``.

#### MealyBlueprint.otherwise_stay

```text
otherwise_stay(output: str) -> typing.Self
```

Undeclared inputs leave the state unchanged and emit ``output``.

#### MealyBlueprint.otherwise_go

```text
otherwise_go(target: str, output: str) -> typing.Self
```

#### MealyBlueprint.to_dto

```text
to_dto() -> Definition.Dto
```

#### MealyBlueprint.examine

```text
examine() -> Report
```

#### MealyBlueprint.build

```text
build() -> Definition
```

## gvn.kernel.decision

Decisions: branching on data without losing completeness.

A machine's transition function looks only at the control state and the input
symbol. When the next step depends on data, a Decision inspects the data and
answers with exactly one symbol from a finite set it declares up front. The
machine must route every declared outcome, and the verifier checks that it does.

A Decision is pure and synchronous. If deciding needs I/O (a model call, a
lookup), the machine requests that work as an output, the runtime fulfils it,
and a Decision classifies the result.

Constants: `ABC`.

### UndeclaredOutcome

```python
from gvn.kernel.decision import UndeclaredOutcome
```

A Decision answered with something outside its declared outcomes.

### Decision

```python
from gvn.kernel.decision import Decision
```

```text
Decision()
```

Implement ``outcomes`` and ``judge``; callers use ``decide``.

#### Decision.outcomes

```text
outcomes() -> Alphabet
```

The Alphabet of every answer this decision can give. Must not vary over time.

#### Decision.judge

```text
judge(subject: object) -> Symbol
```

Inspect ``subject`` and return one Symbol from ``outcomes()``.

#### Decision.decide

```text
decide(subject: object) -> Symbol
```

The outcome for ``subject``, guaranteed to be a declared one.

Raises UndeclaredOutcome if ``judge`` returns anything else. Exceptions
raised by ``judge`` propagate unchanged.

## gvn.kernel.definition

Machine definitions: the formal tuple (Q, Sigma, Lambda, delta, omega, q0, F).

One class covers both styles; they differ only in the output function omega:

* Moore: omega maps a state to an output. A step's output is the output of the
  state it lands in.
* Mealy: omega maps a (state, input) pair to an output. A step's output is the
  output of the transition taken.

A Definition is immutable and always verified. It cannot be constructed directly:
it comes from a blueprint (gvn.kernel.blueprint) or from ``from_dto``, and both
go through the Verifier. A Dto is untrusted input (an agent may have edited it),
so ``from_dto`` always verifies.

Constants: `MOORE`, `MEALY`.

### DefinitionRejected

```python
from gvn.kernel.definition import DefinitionRejected
```

```text
DefinitionRejected(report: Report) -> None
```

The verifier found problems. ``report()`` returns the gvn.kernel.verifier.Report.

#### DefinitionRejected.report

```text
report() -> Report
```

### Step

```python
from gvn.kernel.definition import Step
```

```text
Step(
    source: State,
    symbol: Symbol,
    target: State,
    output: Symbol,
    declared: bool,
) -> None
```

The result of resolving one input in one state. Immutable value object.

#### Step.source

```text
source() -> State
```

The State before the input.

#### Step.symbol

```text
symbol() -> Symbol
```

The input Symbol.

#### Step.target

```text
target() -> State
```

The State after the input.

#### Step.output

```text
output() -> Symbol
```

The output Symbol (see module docstring for Moore versus Mealy).

#### Step.declared

```text
declared() -> bool
```

True for an explicitly declared transition.

False when the input was absorbed by a final state or handled by the
``otherwise`` rule. Callers use this to tell requested work from a rejection.

#### Step.moved

```text
moved() -> bool
```

True when target differs from source.

### Definition

```python
from gvn.kernel.definition import Definition
```

```text
Definition(*args: object, **kwargs: object) -> None
```

A stateful object that can be turned into a Dto and rebuilt from one.

A subclass that defines ``to_dto`` or ``from_dto`` in its own body must also
define, in its own body, an inner class ``Dto`` that subclasses
``gvn.kernel.durable.Dto``; otherwise TypeError at class definition.

#### Definition.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Verify and build. Raises DefinitionRejected carrying the full report.

#### Definition.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Definition.fingerprint_of

```text
fingerprint_of(dto: Dto) -> str
```

Content hash (hex sha256) of a definition Dto, without verifying it.

Computed over a canonical form, so that two Dtos describing the same machine
have the same fingerprint: every list and map is put in a fixed order;
``finals`` is sorted and de-duplicated (it is a set); ``obligations`` drops
every state whose list is empty (no obligation) and sorts and de-duplicates
each remaining list (a set of symbols). The other lists are not sets: a
repeated state, input, output or transition is rejected by the verifier, so
it never needs normalising. Nothing is verified here.

#### Definition.fingerprint

```text
fingerprint() -> str
```

``fingerprint_of(self.to_dto())``.

#### Definition.name

```text
name() -> str
```

#### Definition.style

```text
style() -> str
```

MOORE or MEALY.

#### Definition.states

```text
states() -> tuple[State, ...]
```

Tuple of every State, in name order.

#### Definition.inputs

```text
inputs() -> Alphabet
```

The input Alphabet.

#### Definition.outputs

```text
outputs() -> Alphabet
```

The output Alphabet.

#### Definition.initial

```text
initial() -> State
```

The initial State.

#### Definition.finals

```text
finals() -> tuple[State, ...]
```

Tuple of the final States, in name order.

#### Definition.is_final

```text
is_final(state: State) -> bool
```

True when ``state`` is final. LookupError for a State not in the definition.

#### Definition.resolve

```text
resolve(state: State, symbol: Symbol) -> Step
```

delta and omega together: the Step for ``symbol`` in ``state``.

Total: defined for every state in ``states()`` and every symbol in
``inputs()``. Raises LookupError for a State not in the definition and
UnknownSymbol for a Symbol not in the input alphabet; TypeError for other types.

Undeclared pairs: in a final state the machine stays (output: the state's
own output for Moore, the otherwise output for Mealy). Elsewhere the
otherwise rule applies. Both give ``declared() == False``.

#### Definition.declared_inputs

```text
declared_inputs(state: State) -> frozenset[Symbol]
```

Frozenset of the Symbols that have a declared transition out of ``state``.

#### Definition.state_output

```text
state_output(state: State) -> Symbol
```

Moore only: the output Symbol of ``state``. Raises TypeError on a Mealy definition.

## gvn.kernel.diagram

Drawing definitions: a machine as text a person or an agent can read.

Rendering is deterministic: the same definition always gives the same text,
whatever order it was declared in, so renderings can be compared and versioned.
Undeclared pairs are not drawn one by one; the ``otherwise`` rule is shown once.

Constants: `MEALY`.

### Mermaid

```python
from gvn.kernel.diagram import Mermaid
```

```text
Mermaid()
```

Renders a Definition as a Mermaid ``stateDiagram-v2`` block.

The initial state is entered from ``[*]`` and final states lead to ``[*]``.
Each transition is one edge labelled with its input (Moore) or
``input / output`` (Mealy). For Moore, each state shows its output. The
``otherwise`` rule appears as a note. State and symbol names are used as they
are (kernel names are already safe in Mermaid identifiers except ``.`` and
``-``, which are replaced in identifiers and kept in labels).

#### Mermaid.render

```text
render(definition: Definition) -> str
```

The diagram as a str ending in a newline. TypeError unless a Definition.

### Dot

```python
from gvn.kernel.diagram import Dot
```

```text
Dot()
```

Renders a Definition as a Graphviz ``digraph``.

Final states are drawn with a double circle; the initial state is entered
from an invisible point node. Labels as for Mermaid. Names are quoted.

#### Dot.render

```text
render(definition: Definition) -> str
```

### Table

```python
from gvn.kernel.diagram import Table
```

```text
Table()
```

Renders a Definition as a plain-text transition table.

One row per state: its name (marked when initial or final), its output
(Moore), and its declared transitions as ``input -> target`` (Moore) or
``input / output -> target`` (Mealy), sorted by input. A last line states the
``otherwise`` rule. Columns are aligned with spaces.

#### Table.render

```text
render(definition: Definition) -> str
```

## gvn.kernel.diff

Comparing definitions: exactly what changed between two versions of a machine.

This is what lets a change to a machine be reviewed, by a person or by an agent
proposing it: not "the hash differs" but "state X was added, transition Y now
goes to Z".

Change kinds (stable; code depends on them) and their subjects:

  renamed               the definition name               subject: "name"
  style-changed         moore &lt;-> mealy                   subject: "style"
  state-added / state-removed                             subject: state name
  input-added / input-removed                             subject: symbol name
  output-added / output-removed                           subject: symbol name
  initial-changed                                         subject: "initial"
  final-added / final-removed                             subject: state name
  transition-added / transition-removed                   subject: "state/symbol"
  transition-retargeted   same pair, different target     subject: "state/symbol"
  transition-output-changed   Mealy: same pair, different output   subject: "state/symbol"
  state-output-changed    Moore: a state's output changed (state in both)  subject: state name
  otherwise-changed       the otherwise rule differs      subject: "otherwise"
  obligation-added / obligation-removed                   subject: "state/symbol"

A state added together with its output (Moore) is one ``state-added``; its
output is not reported separately. Likewise transitions of an added or removed
state are still reported as transition-added/removed, since they are what a
reviewer needs to see.

Constants: `MEALY`, `KINDS`.

### Change

```python
from gvn.kernel.diff import Change
```

```text
Change(kind: str, subject: str, before: str | None, after: str | None) -> None
```

One difference. Immutable; equal by all four parts.

#### Change.kind

```text
kind() -> str
```

#### Change.subject

```text
subject() -> str
```

#### Change.before

```text
before() -> str | None
```

#### Change.after

```text
after() -> str | None
```

#### Change.sentence

```text
sentence() -> str
```

The change as one readable sentence.

### Difference

```python
from gvn.kernel.diff import Difference
```

```text
Difference(old: Definition, new: Definition) -> None
```

Everything that changed from one definition to another. Immutable.

#### Difference.changes

```text
changes() -> tuple[Change, ...]
```

Tuple of Changes, sorted by (kind, subject).

#### Difference.kinds

```text
kinds() -> frozenset[str]
```

Frozenset of the kinds present.

#### Difference.empty

```text
empty() -> bool
```

True when the two definitions describe the same machine (same fingerprint).

#### Difference.summary

```text
summary() -> str
```

Every change as a sentence, one per line; ``"no changes"`` when empty.

## gvn.kernel.durable

Durability: the Dto protocol.

Every stateful class that must survive a process boundary is ``Durable``. It has
an inner class named ``Dto`` describing its serialisable state, an instance method
``to_dto`` and a class method ``from_dto``. ``from_dto`` creates the object with
``cls.__new__(cls)`` and populates its members; it does not call ``__init__``.

    class Counter(Durable):
        class Dto(Dto):
            schema = Record({"count": Integer(minimum=0)})

        def __init__(self):
            self._count = 0

        def to_dto(self) -> Dto:
            return Counter.Dto(count=self._count)

        @classmethod
        def from_dto(cls, dto: Dto) -> typing.Self:
            require_own_dto(cls, dto)
            self = cls.__new__(cls)
            self._count = dto.count
            return self

The durability law, which every Durable must satisfy and is tested for each:
``from_dto(to_dto(x))`` is indistinguishable from ``x`` through its public
interface, now and after any further sequence of calls. The same holds when the
Dto travels through ``to_plain`` -> JSON text -> ``from_plain``.

A Dto is the one sanctioned plain-data shape in the codebase: immutable, with
public read-only fields, validated against an explicit schema on construction.

Constants: `ABC`.

### Dto

```python
from gvn.kernel.durable import Dto
```

```text
Dto(**fields: object) -> None
```

Base for every inner ``Dto`` class.

A subclass must define ``schema`` as a ``Record`` in its own body; defining a
subclass without one raises TypeError at class definition.

Construction takes the fields as keyword arguments and validates them against
the schema (SchemaViolation on failure). List-like fields are stored as tuples.
Fields are read as attributes and cannot be set or deleted afterwards
(AttributeError). Two Dtos are equal when they are the same class and their
plain forms are equal. Dtos are hashable when their content is.

#### Dto.to_plain

```text
to_plain() -> dict[str, typing.Any]
```

The plain (JSON-compatible) dict for this Dto, nested Dtos included.

#### Dto.from_plain

```text
from_plain(plain: object) -> typing.Self
```

Rebuild from a plain dict. Raises SchemaViolation if it does not fit.

#### Dto.replace

```text
replace(**changes: object) -> typing.Self
```

A new Dto of the same class with some fields changed; validated like a new one.

### DtoOf

```python
from gvn.kernel.durable import DtoOf
```

```text
DtoOf(dto_class: type[Dto]) -> None
```

Schema admitting instances of one Dto class; its plain form is that Dto's plain form.

#### DtoOf.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### DtoOf.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### DtoOf.build

```text
build(plain: object, path: str, out: list[str]) -> Dto | None
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### DtoOf.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### require_own_dto

```python
from gvn.kernel.durable import require_own_dto
```

```text
require_own_dto(owner: type[Durable], dto: object) -> None
```

Raise TypeError unless ``dto``'s class is exactly ``owner.Dto``: what every
``from_dto`` checks first, before it reads a field.

``owner`` is the durable class being rebuilt (the ``cls`` of ``from_dto``). Another
class's Dto is refused, and so is an instance of a subclass of ``owner.Dto``: it may
carry fields ``owner`` does not know, and rebuilding from it would silently drop
them. Anything that is not a Dto (a dict, None) is refused too.

### Durable

```python
from gvn.kernel.durable import Durable
```

```text
Durable()
```

A stateful object that can be turned into a Dto and rebuilt from one.

A subclass that defines ``to_dto`` or ``from_dto`` in its own body must also
define, in its own body, an inner class ``Dto`` that subclasses
``gvn.kernel.durable.Dto``; otherwise TypeError at class definition.

#### Durable.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Durable.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate via ``cls.__new__(cls)``. Raises TypeError unless ``dto``'s class is
exactly ``cls.Dto`` (``require_own_dto``).

## gvn.kernel.machine

A running machine: one current state, driven by inputs, never doing I/O.

The machine owns its state. The only way to change it is ``feed``.

A machine can also be reduced to a ``Machine.Position`` (definition fingerprint,
state name, step count) and rebuilt with ``Machine.at``. Owners that hold the
definition in code (agents, workflows) store positions instead of whole definitions.

### DefinitionMismatch

```python
from gvn.kernel.machine import DefinitionMismatch
```

A machine Dto was resumed against a definition other than the one it ran on.

### Machine

```python
from gvn.kernel.machine import Machine
```

```text
Machine(definition: Definition) -> None
```

A stateful object that can be turned into a Dto and rebuilt from one.

A subclass that defines ``to_dto`` or ``from_dto`` in its own body must also
define, in its own body, an inner class ``Dto`` that subclasses
``gvn.kernel.durable.Dto``; otherwise TypeError at class definition.

#### Machine.feed

```text
feed(symbol: Symbol) -> Step
```

Consume one input: move to the next state and return the Step taken.

Raises UnknownSymbol for a Symbol outside the input alphabet and TypeError
for a non-Symbol; in both cases the machine is unchanged.

#### Machine.state

```text
state() -> State
```

The current State.

#### Machine.finished

```text
finished() -> bool
```

True when the current state is final.

#### Machine.expected

```text
expected() -> frozenset[Symbol]
```

Frozenset of Symbols with a declared transition from the current state.

#### Machine.steps

```text
steps() -> int
```

How many inputs have been fed, counting undeclared ones.

#### Machine.definition

```text
definition() -> Definition
```

#### Machine.position

```text
position() -> Machine.Position
```

A Machine.Position: definition fingerprint, current state name, step count.

#### Machine.to_dto

```text
to_dto() -> Dto
```

A Dto capturing the complete internal state. Does not mutate the object.

#### Machine.from_dto

```text
from_dto(dto: Dto) -> typing.Self
```

Rehydrate, rebuilding (and so re-verifying) the embedded definition.

Raises DefinitionRejected if the embedded definition does not verify and
ValueError if ``state`` is not one of its states.

#### Machine.resume

```text
resume(definition: Definition, dto: Dto) -> typing.Self
```

Rehydrate onto an already-built Definition, skipping re-verification.

For rehydrating many machines that share one definition. Raises
DefinitionMismatch unless ``definition.fingerprint()`` equals the
fingerprint of the Dto's embedded definition.

#### Machine.at

```text
at(definition: Definition, position: Machine.Position) -> typing.Self
```

Rehydrate onto ``definition`` from a Position, without re-verifying or re-fingerprinting.

TypeError unless a Definition and a Machine.Position. DefinitionMismatch unless
``position.fingerprint == definition.fingerprint()``. ValueError if ``state`` is not a
state of the definition. Cost is a string compare plus a lookup.

## gvn.kernel.schema

Explicit runtime schemas.

A schema is an object that says what a value must look like and checks it at
runtime. Nothing here reads type hints. Schemas serve three jobs: validating
data that crosses a boundary, converting values to and from their plain
(JSON-compatible) form, and rendering JSON Schema for vendors that need it.

"Plain" means: None, bool, int, float, str, list of plain, dict of str to plain.

Paths in problem messages use JSONPath-like notation rooted at ``$``
(``$.steps``, ``$.items[2].name``).

Writing your own schema: subclass ``Schema`` and implement its four extension
methods, ``check``, ``plain``, ``build`` and ``to_json_schema``, plus ``_key``
when the schema has parameters. The base class turns them into ``problems``,
``admits``, ``require``, ``encode`` and ``decode``, validating a whole tree once
at the top rather than once per level. A composite schema calls its children's
``check``, ``plain`` and ``build``, never their ``problems``, ``encode`` or
``decode``. The ``Schema`` docstring is the full contract; the classes below,
and ``gvn.kernel.durable.DtoOf``, are written against it and nothing more.

Constants: `ABC`.

### SchemaViolation

```python
from gvn.kernel.schema import SchemaViolation
```

```text
SchemaViolation(problems: str | Iterable[object]) -> None
```

A value did not satisfy a schema. Carries every problem found, not just the first.

#### SchemaViolation.problems

```text
problems() -> tuple[str, ...]
```

Tuple of ``"<path>: <message>"`` strings, in a deterministic order. Never empty.

### Schema

```python
from gvn.kernel.schema import Schema
```

```text
Schema()
```

What a value must look like. Immutable. Equal when structurally equal; hashable.

The subclass contract. A subclass implements four public extension methods;
``problems``, ``admits``, ``require``, ``encode`` and ``decode`` are built on
them here and are not overridden.

``check(value, path, out)``
    Append one ``"<path>: <message>"`` string to the list ``out`` for every
    problem with ``value``, in a deterministic order, and return None. Appends
    nothing when ``value`` is admitted. Must not raise, whatever it is given.
``plain(value)``
    The plain form of ``value``, which the caller already knows is admitted.
    Validates nothing; what it does with a value that is not admitted is
    undefined. Returns a fresh object that shares nothing mutable with
    ``value``, and the same plain form every time for the same value.
``build(plain, path, out)``
    The value for the plain form ``plain``, appending every problem to ``out``
    exactly as ``check`` does; the return value is meaningless if anything was
    appended. Must not raise, whatever it is given. Law: for every admitted
    ``v``, ``build(plain(v), path, out)`` appends nothing and returns a value
    equal to ``v``, also after the plain form has been through
    ``json.dumps``/``json.loads``; and whenever ``build`` appends nothing, the
    value it returns is admitted.
``to_json_schema()``
    A JSON Schema (draft 2020-12) dict describing the plain form.

A composite schema calls its children's ``check``, ``plain`` and ``build``
(never their ``problems``, ``encode`` or ``decode``), passing the same ``out``
and the child's path: ``f"{path}.{name}"`` for a field, ``f"{path}[{index}]"``
for an item, ``f"{path}['{key}']"`` for a key that is not an identifier. That
way a whole tree is validated in one pass: ``problems`` and ``decode`` call
``check`` or ``build`` once at the top, and ``encode`` calls ``require`` once at
the top and then ``plain``. As a last line of defence the base class turns an
exception escaping ``check`` or ``build`` into a ``could not be examined`` or
``could not be decoded`` problem, but a subclass must not rely on it.

State and equality. Instances are immutable: ``__setattr__`` and ``__delattr__``
raise AttributeError. A subclass stores its members once, in ``__init__``, by
calling ``self._init(name=value, ...)``, which sets ``self._name`` for each
keyword; it reads them back as ``self._name`` and never changes them, and the
members should themselves be immutable (validate and copy arguments first). A
subclass with parameters overrides ``self._key()`` to return a hashable tuple
of the members that distinguish it, nested schemas included (they compare
structurally). Two schemas are equal when they are of the same class and their
keys are equal, and they hash accordingly; ``repr`` shows the class name and the
key. The default key is ``()``, right for a schema without parameters.
``_init`` and ``_key`` are for the subclass itself; nothing else calls them.

#### Schema.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### Schema.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### Schema.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### Schema.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

#### Schema.problems

```text
problems(value: object, path: str = '$') -> tuple[str, ...]
```

Every way ``value`` fails this schema, as a tuple of ``"<path>: <message>"``.

Empty tuple means the value is admitted. Never raises, for any input.

#### Schema.encode

```text
encode(value: object) -> typing.Any
```

The plain form of an admitted value. Raises SchemaViolation if not admitted.

#### Schema.decode

```text
decode(plain: object, path: str = '$') -> object
```

The value for a plain form; inverse of ``encode``. Raises SchemaViolation.

Law: ``decode(encode(v)) == v`` for every admitted ``v``, including after the
plain form has been through ``json.dumps``/``json.loads``.

#### Schema.admits

```text
admits(value: object) -> bool
```

True when ``problems(value)`` is empty.

#### Schema.require

```text
require(value: object) -> None
```

Raise SchemaViolation listing every problem, or return None.

### Text

```python
from gvn.kernel.schema import Text
```

```text
Text(pattern: str | None = None) -> None
```

A str. Optional ``pattern`` is a regular expression the whole string must match.

#### Text.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### Text.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### Text.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### Text.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### Integer

```python
from gvn.kernel.schema import Integer
```

```text
Integer(minimum: int | None = None, maximum: int | None = None) -> None
```

An int that is not a bool, within optional inclusive bounds.

#### Integer.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### Integer.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### Integer.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### Integer.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### Number

```python
from gvn.kernel.schema import Number
```

```text
Number() -> None
```

An int or float that is not a bool, and is finite (no nan, no infinities).

#### Number.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### Number.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### Number.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### Number.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### Boolean

```python
from gvn.kernel.schema import Boolean
```

```text
Boolean() -> None
```

Exactly True or False.

#### Boolean.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### Boolean.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### Boolean.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### Boolean.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### OneOf

```python
from gvn.kernel.schema import OneOf
```

```text
OneOf(*literals: str) -> None
```

One of a fixed, non-empty set of str literals.

#### OneOf.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### OneOf.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### OneOf.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### OneOf.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### Nullable

```python
from gvn.kernel.schema import Nullable
```

```text
Nullable(inner: Schema) -> None
```

None, or whatever ``inner`` admits.

#### Nullable.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### Nullable.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### Nullable.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### Nullable.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### ListOf

```python
from gvn.kernel.schema import ListOf
```

```text
ListOf(item: Schema) -> None
```

A tuple or list whose items all satisfy ``item``. Decodes to a tuple.

#### ListOf.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### ListOf.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### ListOf.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### ListOf.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### MapOf

```python
from gvn.kernel.schema import MapOf
```

```text
MapOf(value: Schema) -> None
```

A dict with str keys whose values all satisfy ``value``.

#### MapOf.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### MapOf.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### MapOf.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### MapOf.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### Json

```python
from gvn.kernel.schema import Json
```

```text
Json() -> None
```

Any plain value (see module docstring). Tuples are admitted and decode as tuples.

#### Json.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### Json.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### Json.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### Json.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

### Record

```python
from gvn.kernel.schema import Record
```

```text
Record(fields: Mapping[str, Schema], optional: Iterable[str] = ()) -> None
```

A dict with exactly the named fields.

``fields`` maps field name to Schema. Unknown keys are a problem. A missing key
is a problem unless its name is in ``optional``; optional fields that are absent
stay absent through encode/decode.

#### Record.fields

```text
fields() -> dict[str, Schema]
```

Dict of field name to Schema, in declaration order (a copy).

#### Record.optional

```text
optional() -> frozenset[str]
```

Frozenset of optional field names.

#### Record.check

```text
check(value: object, path: str, out: list[str]) -> None
```

Append every problem with ``value`` to ``out`` as ``"<path>: <message>"``.

Returns None. Must never raise, whatever it is given.

#### Record.plain

```text
plain(value: object) -> typing.Any
```

The plain form of a value already known to be admitted. Validates nothing.

#### Record.build

```text
build(plain: object, path: str, out: list[str]) -> object
```

The value for a plain form, appending every problem to ``out``.

The return value is meaningless if anything was appended. Must never raise.

#### Record.to_json_schema

```text
to_json_schema() -> dict[str, typing.Any]
```

A JSON Schema (draft 2020-12) dict describing the plain form.

## gvn.kernel.symbols

The vocabulary of machines: states, symbols and alphabets.

Names match ``[A-Za-z][A-Za-z0-9_.-]*``. Anything else raises ValueError (TypeError
for a non-str). All three classes are immutable value objects.

### Symbol

```python
from gvn.kernel.symbols import Symbol
```

```text
Symbol(name: str) -> None
```

A member of an input or output alphabet. Equal to another Symbol with the same name.

A Symbol is never equal to a State or to a str.

#### Symbol.name

```text
name() -> str
```

### State

```python
from gvn.kernel.symbols import State
```

```text
State(name: str) -> None
```

A control state. Equal to another State with the same name; never equal to a Symbol.

#### State.name

```text
name() -> str
```

### UnknownSymbol

```python
from gvn.kernel.symbols import UnknownSymbol
```

A symbol was used that the alphabet in question does not contain.

### Alphabet

```python
from gvn.kernel.symbols import Alphabet
```

```text
Alphabet(symbols: Iterable[Symbol]) -> None
```

A finite, non-empty set of Symbols.

Built from Symbols (TypeError for anything else). Empty raises ValueError, as
does the same name twice. Supports ``in``, ``len``, iteration in name order,
equality and hashing by content.

#### Alphabet.of

```text
of(*names: str) -> typing.Self
```

Alphabet of Symbols with the given names.

#### Alphabet.named

```text
named(name: str) -> Symbol
```

The Symbol with this name, or UnknownSymbol.

#### Alphabet.names

```text
names() -> tuple[str, ...]
```

Tuple of names, sorted.

## gvn.kernel.verifier

The verifier: proves a machine definition complete before it can exist.

It examines a ``Definition.Dto`` (see gvn.kernel.definition for the fields) and
reports every finding, not just the first. A definition with any finding is
rejected. This module must not import gvn.kernel.definition; it reads the Dto's
documented fields.

Semantics the checks rely on:

* Final states are absorbing: every input in a final state stays there. They
  need no declared transitions and may not have any.
* A (state, symbol) pair with no declared transition is covered only by the
  ``otherwise`` rule. Without that rule, an uncovered pair is a finding.
* For reachability and liveness, the graph has an edge for every declared
  transition, plus an edge from every non-final state with an uncovered pair to
  the ``otherwise`` target when that rule names one.
* Checks that need a sound structure (graph checks) skip pieces already reported
  as broken, so one mistake does not cascade into a wall of findings.

Finding codes (stable; tests and self-improving agents depend on them):

  invalid-name          a state, symbol or definition name is not a valid name
  duplicate-name        a name appears twice in states, inputs or outputs
  unknown-state         initial, a final, a transition end, a state output key, an
                        obligation key or the otherwise target is not in states
  unknown-symbol        a transition symbol or obligation symbol is not in inputs,
                        or an output is not in outputs
  no-final-state        finals is empty
  empty-alphabet        inputs or outputs is empty (subject: "inputs" or "outputs")
  nondeterministic      two transitions share a source and symbol
  incomplete            a (non-final state, input) pair is uncovered and there is no
                        otherwise rule; for Mealy, also when otherwise is absent at
                        all (final states need its output)
  final-not-absorbing   a declared transition leaves a final state
  unreachable-state     a state cannot be reached from the initial state
  dead-end-state        a state cannot reach any final state
  missing-output        Moore: a state has no output. Mealy: a transition, or the
                        otherwise rule, has no output
  misplaced-output      Moore: a transition or the otherwise rule carries an output.
                        Mealy: state outputs are present
  unused-input          an input symbol has no declared transition anywhere
  unused-output         an output symbol is never emitted
  unmet-obligation      a state is obliged to route a symbol explicitly but has no
                        declared transition for it

Compensation (``Verifier.examine_compensations``, a separate examination of a clean
definition; see that method for the model and exactly what it proves):

  bad-compensation      a compensation declaration does not hold together (unknown or
                        final states, a state both effect and compensation, a done or
                        untouched symbol with no declared transition, no undone final
                        state, or too many combinations to check)
  uncompensated-path    some walk reaches an undone final state while an effect state
                        entered on it has not been compensated since
  unordered-compensation some walk compensates an earlier effect while a later one is
                        still outstanding, or re-enters an effect state while a later
                        effect is outstanding (compensations would not run in reverse)

Constants: `COMPENSATION_LIMIT`.

### Finding

```python
from gvn.kernel.verifier import Finding
```

```text
Finding(code: str, subject: str, message: str) -> None
```

One reason a definition is rejected. Immutable; equal by code and subject.

#### Finding.code

```text
code() -> str
```

One of the codes listed in the module docstring.

#### Finding.subject

```text
subject() -> str
```

What it is about, as a short stable str: a state name, ``"state/symbol"``, ...

#### Finding.message

```text
message() -> str
```

A sentence a person or an agent can act on.

### Report

```python
from gvn.kernel.verifier import Report
```

```text
Report(findings: Iterable[Finding]) -> None
```

The result of examining a definition. Immutable; iterates Findings in sorted order.

#### Report.clean

```text
clean() -> bool
```

True when there are no findings.

#### Report.findings

```text
findings() -> tuple[Finding, ...]
```

Tuple of Findings, sorted by (code, subject).

#### Report.codes

```text
codes() -> frozenset[str]
```

Frozenset of the distinct codes present.

### Verifier

```python
from gvn.kernel.verifier import Verifier
```

```text
Verifier()
```

Stateless examiner of definition Dtos.

#### Verifier.examine

```text
examine(dto: Dto) -> Report
```

Report every finding for ``dto``. Never raises for a well-formed Dto instance.

#### Verifier.examine_compensations

```text
examine_compensations(
    dto: Dto,
    compensations: Mapping[str, tuple[str, Iterable[str], Iterable[str]]],
    undone: Iterable[str],
) -> Report
```

Report whether every way to an ``undone`` final state compensates, in reverse.

``compensations``: a mapping of effect state name -> ``(compensating state name,
done, untouched)``. ``done``: a non-empty collection of input names; the
compensating state has compensated the effect when it is left on one of them.
``untouched``: a collection of input names (often empty); the effect state is
left on one of them only when it changed nothing. ``undone``: a collection of
final state names meaning "the run was undone". TypeError if they are not
shaped so (names must be str).

The model. A walk is any sequence of transitions from the initial state: every
declared transition, plus the move an ``otherwise`` rule with a target makes.
Every run of the machine is a walk (the converse need not hold: a walk may take
an outcome a Decision never gives there). Along a walk, entering an effect
state makes it outstanding; leaving its compensating state on a done symbol
compensates it; leaving the effect state on an untouched symbol withdraws it,
but only when this entry made it outstanding (an effect state entered again
while still outstanding keeps the earlier entries' effects outstanding,
whatever the latest one did). The check proves, for every walk:

* when it enters an undone final state, no effect is outstanding
  (``uncompensated-path`` otherwise, subject ``"<effect>/<final>"``);
* compensations run in reverse order of the effects: a done symbol compensates
  only the most recent outstanding effect, and an outstanding effect state is
  not entered again while a later one is outstanding
  (``unordered-compensation`` otherwise, subject ``"<earlier>/<later>"``).

Every finding's message shows the shortest such walk. A done symbol for an
effect that is not outstanding compensates nothing and is allowed. Walks that
end elsewhere (another final state, or never) are not constrained.

What it does not prove: that the declared effect states are all the states
with effects; that a compensating state's work really undoes its effect, or
that an untouched exit really changed nothing (it trusts both declarations);
anything about outputs, data or children. It refuses a declaration whose
violating walk no run could take (it reasons about walks, not runs).

A definition that is not clean is reported as ``examine`` reports it, unchecked.
Declaration problems are ``bad-compensation`` findings, as is a machine with
more than ``COMPENSATION_LIMIT`` combinations of state and outstanding effects
(refused, never passed unchecked).
