Skip to content

Core

Core — mvp.core

Cluster: Core Infrastructure | Type: component | MCP Tools: None

Overview

core provides the foundation types that every other G6 component builds on, including the generic AIBlock base class, the railway-oriented Result monad, guardrailed SearchTree, resource-bounding primitives, and structural protocols.

Launch readiness boundary

The core infrastructure test suite passes and the component is suitable as the launch foundation for typed results, pipeline execution, resource bounds, update safety, and production metrics. That does not make the full G6 product production-ready by itself. Before first-user or paid-user pilots, still verify the MCP clean install path, Docker images, staging deployment, Stripe end-to-end flow, production environment validation, and onboarding workflow against the launch checklist.

When to use:

  • Defining custom reasoning blocks by subclassing AIBlock
  • Building typed, composable pipelines with PipelineBlock and >> chaining
  • Enforcing token, time, and disk resource bounds on any pipeline execution

Example:

from mvp.core import AIBlock, Result

class DoubleBlock(AIBlock[int, int, None]):
    def infer(self, data: int) -> Result[int]:
        return Result.ok(data * 2)

block = DoubleBlock(name="double")
result = block.infer(21)
# result.ok → True; result.value → 42

Reliability envelope guarantee: when a ReliabilityEnvelope carries conflicting state, the two public state fields (completion_state and reliability_label) are reconciled to the weakest honest label, and any explicit degradation signal (degraded=True or a degradation_reason) caps the result at non-verified — so verified can never coexist with a degraded or blocked state. A legitimately verified result may still carry a green/amber warning_card; the card's verified flag is a derived echo of the reconciled state, not an independent downgrade trigger.

Works well with: every other component — core is the universal dependency

Public API

AIBlock(Generic[Input, Output, State])

The atomic building block of the G6 hyperdistillation system.

Field Type Default
name str required
state State \| None field(default=None)

Methods:

infer(data: Input) -> Result[Output]

Single-shot computation: transform Input → Result[Output].

verify(output: Output, contract: BlockContract | None = None) -> EvidenceBundle

Verify output using a registered per-harness verification method.

bias() -> dict[str, 'Any']

Structural assumptions about this block's hypothesis space.

contract() -> BlockContract

Runtime obligations this block promises to satisfy.

then(other: 'AIBlock[Output, Any, Any]') -> 'PipelineBlock[Input, Any, None]'

Chain self >> other into a sequential pipeline.

PipelineBlock(AIBlock[Input, Output, None])

Two AIBlocks chained sequentially: left.emit() → right.ingest().

Constructor:

Parameter Type Default
name str required
_left AIBlock[Any, Any, Any] required
_right AIBlock[Any, Any, Any] required

Methods:

infer(data: Any) -> Result[Any]

ArtifactSchemaError(ValueError)

Field Type Default
code str required
message str required
artifact_type str 'artifact'
schema_version str '0.0'
current_version str CURRENT_SCHEMA_VERSION

FailureMode

A known way this block can go wrong.

Field Type Default
name str required
detector str ''
severity str 'medium'
description str ''
failure_type str FailureType.UNVERIFIED_OUTPUT.value

TransitionOutcome

A single probability-weighted outcome from a TransitionKernel evaluation.

Field Type Default
probability float required
next_state Any required

ResourceTriple

Abstract formal resource bounds for a BoundedAgent.

Field Type Default
T int required
M int required
N int required
epsilon float 0.05
delta float 0.01

BoundedAgent

Pure formal description of a resource-bounded agent.

Field Type Default
states frozenset[Any] required
transition_kernel TransitionKernel required
initial_state Any required
resources ResourceTriple required
phi_A Callable[[Any], bool] required

SafetyMonitor(ABC)

Abstract base interface for runtime safety monitors.

Methods:

reset() -> None

Reset all accumulated state. Called at the start of each episode.

update(state: Any, inp: Any, hazard: float) -> None

Process one agent step.

is_violated() -> bool

Return True if any safety property has been violated so far.

StepRationale

Audit trace record for a single agent step.

Field Type Default
state Any required
inp Any required
hazard float required
cumulative_hazard float required
note str ''

SafetyDecisionReport

Structured verdict returned by a SafetyVerifier or CSF evaluation.

Field Type Default
method str required
epsilon float required
vub float required
meets_bound bool required
steps list[StepRationale] field(default_factory=list)
explanations list[str] field(default_factory=list)
audit_id str ''
lean_pending bool False
hitl_required bool False
policy_citations list[str] field(default_factory=list)
p_unsafe float 0.0
confidence_interval tuple[float, float] (0.0, 1.0)

SafetyLevel(str, Enum)

Qualitative safety evaluation outcome from TASP-style tiered evaluation.

RiskClassification(str, Enum)

Risk classification for governance-aware operations.

OperationMode(str, Enum)

Agent autonomy level for governance enforcement.

QualitativeSafetyVerdict

Structured verdict from a qualitative safety evaluation.

Field Type Default
level SafetyLevel required
reason str required
evaluator str required
policy_id str ''
risk_class RiskClassification RiskClassification.NON_DESTRUCTIVE
suggested_action str ''
metadata dict field(default_factory=dict)

StrategySpec

Specification for a strategic orchestration plan.

Field Type Default
id str required
version str required
description str required
policy str required
capabilities tuple[str, ...] ()
recipes tuple[str, ...] ()
failure_modes tuple[str, ...] ()

ImpedanceBounds

Safety envelope for impedance-based motor control.

Field Type Default
k_min float 0.2
k_max float 1.0
c_min float 0.1
c_max float 0.4
max_force_n float \| None None
max_speed_ms float \| None None

Methods:

clamp_k(k: float) -> float

Clamp stiffness to valid range.

clamp_c(c: float) -> float

Clamp damping to valid range.

EnergyModel

Tracks computational energy consumption as analogue of physical energy E(t).

Field Type Default
total_tokens int 0
total_api_calls int 0
total_wall_clock_s float 0.0
cycle_count int 0
token_energy float 0.001
api_call_energy float 0.1
wall_clock_energy float 0.01
cycle_energies list[float] field(default_factory=list)

Methods:

record_cycle(tokens: int = 0, api_calls: int = 0, wall_clock_s: float = 0.0) -> float

Record one cycle's resource consumption. Returns cycle energy.

total_energy() -> float

Total cumulative energy spent.

mean_cycle_energy() -> float

Mean energy per cycle (0.0 if no cycles recorded).

energy_trend() -> float

Energy trend: negative = improving (using less energy per cycle).

G6Error

Structured error with actionable guidance.

Field Type Default
code str required
message str required
suggestion str \| None None
docs_url str \| None None
valid_ops list[str] field(default_factory=list)

Methods:

to_dict() -> dict

to_problem_detail(status: int = 400, request_id: str | None = None, instance: str | None = None) -> dict[str, Any]

Claim

Field Type Default
text str required
claim_type str 'inference'
evidence_refs tuple[str, ...] ()
checked bool False
risk_level str 'R0'
evidence_grade str 'E0'
epistemic_status str 'ASSERTED'
scope dict field(default_factory=dict)
counterevidence_refs tuple[str, ...] ()
falsification_conditions tuple[str, ...] ()
independence_group str ''
confidence float \| None None
confidence_ceiling_applied bool False
disposition str \| None None
as_of datetime \| None None
expires_at datetime \| None None

Methods:

to_dict() -> dict[str, Any]

TestResult

Field Type Default
name str required
passed bool required
command str ''
output_ref str ''

SourceRef

Field Type Default
uri str required
title str ''
source_type str 'file'
excerpt str ''

Assumption

Field Type Default
text str required
risk str 'medium'
validation str ''

EvidenceBundle

Portable evidence returned by per-harness verification.

Field Type Default
claims tuple[Claim, ...] ()
tests_run tuple[TestResult, ...] ()
sources tuple[SourceRef, ...] ()
assumptions tuple[Assumption, ...] ()
unresolved_questions tuple[str, ...] ()
confidence float \| None None
verifier_id str 'unknown'
verified_at datetime field(default_factory=lambda: datetime.now(timezone.utc))
schema_version str '1.0'
evidence_records tuple[EvidenceRecord, ...] ()

Methods:

to_dict() -> dict[str, Any]

ExtensionPoints

What a harness DECLARES about its T3/self-programming surface.

Field Type Default
training_signal_inputs tuple[str, ...] ()
validation_gate str 'none'
allowed_mutation_surfaces tuple[str, ...] ()

FailureModeRecord

Field Type Default
code FailureModeCode required
description str ''
signals tuple[str, ...] ()
detection str ''
prevention str ''
recovery str ''
severity str 'medium'
requires_human_review bool False
source str 'seed'
aliases tuple[str, ...] ()

FailureModeRegistry

Singleton-style registry keyed by runtime-safe string codes.

Methods:

seed_defaults() -> None

register(record: FailureModeRecord) -> None

get(code: str | FailureModeCode) -> FailureModeRecord

list_all() -> list[FailureModeRecord]

is_registered(code: str | FailureModeCode) -> bool

StorableMixin

Opt-in: block supports save/load of internal state.

Methods:

save(path: str) -> Result[str]

Persist the block's state to path. Returns the written path.

load(path: str) -> Result[bool]

Restore the block's state from path.

LearnableMixin

Opt-in: block supports online learning from supervised signal.

Methods:

learn(data: Any, labels: Any) -> Result[Any]

Update block parameters given supervised signal.

IngestEmitMixin

Opt-in: block supports staged ingest/emit workflow.

Methods:

ingest(data: Any) -> Result[Any]

Accept raw input, validate, and store internally.

emit() -> Result[Any]

Produce output from current internal state.

PipelineStep

One step in a pipeline: component name + operation + params.

Field Type Default
component str required
op str required
params dict[str, Any] field(default_factory=dict)
expected_input_keys frozenset[str] \| None None
expected_output_keys frozenset[str] \| None None

Ingestible(Protocol)

Can accept raw input and return a Result.

Methods:

ingest(data: Any) -> Result[Any]

Emittable(Protocol)

Can produce output from internal state and return a Result.

Methods:

emit() -> Result[Any]

Storable(Protocol)

Can persist and restore its state.

Methods:

save(path: str) -> Result[str]

load(path: str) -> Result[bool]

Inferrable(Protocol)

Can run forward inference given an input.

Methods:

infer(data: Any) -> Result[Any]

Learnable(Protocol)

Can update its parameters given labelled data.

Methods:

learn(data: Any, labels: Any) -> Result[Any]

InductiveBias(Protocol)

Declares its structural assumptions about the hypothesis space.

Methods:

bias() -> dict[str, Any]

ConfigurableBias(Protocol)

Can accept runtime bias parameter updates from the evolution loop.

Methods:

configure_bias(params: dict[str, Any]) -> None

ResourceBounds

Immutable resource constraint envelope for an AIBlock or pipeline.

Field Type Default
max_execution_seconds float \| None None
max_disk_bytes int \| None None
max_tokens_per_minute int \| None None
max_tokens_per_hour int \| None None
max_tokens_per_day int \| None None
max_tokens_per_week int \| None None
max_tokens_per_month int \| None None
max_cost_per_day float \| None None
max_cost_per_month float \| None None

ResourceUsage

Mutable runtime counter — one instance per pipeline execution.

Field Type Default
tokens_used int 0
cost_used float 0.0
disk_bytes_used int 0
last_input_tokens int 0
last_output_tokens int 0

Methods:

record_tokens(count: int, input_tokens: int = 0, output_tokens: int = 0) -> None

Append count tokens to the log and update the running total.

record_cost(amount: float) -> None

Append amount USD to the cost log and update the running total.

cost_in_window(window_seconds: float) -> float

Return total cost recorded within the last window_seconds.

tokens_in_window(window_seconds: float) -> int

Return the total tokens recorded within the last window_seconds.

elapsed_seconds() -> float

Seconds since this ResourceUsage instance was created.

ResourceGuardrail(Guardrail)

Hard constraint that enforces ResourceBounds against a ResourceUsage counter.

Constructor:

Parameter Type Default
bounds ResourceBounds required
usage ResourceUsage required

Methods:

check(node_data: Any) -> Result[bool]

Evaluate all configured bounds against current usage.

Status(Enum)

Result(Generic[Output])

Lightweight railway Result — wraps a value or an error string.

Constructor:

Parameter Type Default
status Status required
value Output \| None required
error str \| None required

Methods:

ok(value: Output) -> 'Result[Output]'

fail(error: str | object) -> 'Result[Output]'

is_ok() -> bool

is_fail() -> bool

is_failure() -> bool

Property alias for is_fail() — for ergonomic boolean checks.

value() -> Output

unwrap() -> Output

Alias for .value — raises ValueError if FAIL.

error() -> str

map(fn: Callable[[Output], T]) -> 'Result[T]'

flat_map(fn: Callable[[Output], 'Result[T]']) -> 'Result[T]'

or_else(default: Output) -> Output

FailureMode(Enum)

Standardised failure categories for tree-node diagnostics.

Guardrail

A hard constraint on tree expansion.

Field Type Default
name str required
predicate Callable[[Any], bool] required
message str 'Guardrail violation'

Methods:

check(node_data: Any) -> Result[bool]

Checkpoint

A soft assertion that logs a diagnostic without halting expansion.

Field Type Default
name str required
predicate Callable[[Any], bool] required
description str ''

Methods:

evaluate(node_data: Any) -> Result[bool]

Breakpoint

An optional debugging hook. When active, invokes callback with the

Field Type Default
name str required
callback Callable[[Any], Any] required
active bool False

Methods:

trigger(node_data: Any) -> Result[Any]

NodeDiagnostic

Per-node structured log entry produced during tree evaluation.

Field Type Default
node_id str required
failure_mode FailureMode FailureMode.NONE
guardrail_results list[Result[bool]] field(default_factory=list)
checkpoint_results list[Result[bool]] field(default_factory=list)
breakpoint_result Result[Any] \| None None
notes str ''

Methods:

passed() -> bool

TreeNode(Generic[Node])

A single node in the search tree.

Field Type Default
data Node required
id str field(default_factory=lambda: str(uuid4()))
parent_id str \| None None
children list['TreeNode[Node]'] field(default_factory=list)
depth int 0
score float 0.0
diagnostic NodeDiagnostic \| None None

Methods:

add_child(child_data: Node) -> 'TreeNode[Node]'

is_leaf() -> bool

SearchTree(Generic[Node])

Guardrailed, diagnostic search tree.

Field Type Default
guardrails list[Guardrail] field(default_factory=list)
checkpoints list[Checkpoint] field(default_factory=list)
breakpoints list[Breakpoint] field(default_factory=list)
max_depth int 32

Methods:

new_root(data: Node) -> TreeNode[Node]

evaluate_node(node: TreeNode[Node]) -> NodeDiagnostic

expand(parent: TreeNode[Node], candidate_nodes: list[Node]) -> Result[list[TreeNode[Node]]]

Attempt to add candidate_nodes as children of parent.

best_leaf(key: Callable[[TreeNode[Node]], float] | None = None) -> Result[TreeNode[Node]]

Return the leaf node with the highest score (or custom key).

iter_nodes() -> Iterator[TreeNode[Node]]

StateSurface

Field Type Default
persistence Persistence 'none'
queryable_via QueryableVia 'none'
retention str 'run'

ModelProfile

Empirical profile for a model family.

Field Type Default
model_id str required
R_bits_per_token dict[str, float] required
W_eff_tokens int required
gamma_degradation float 0.05

StakesConfig

Thresholds indexed by stakes level.

Field Type Default
grounding_coverage float required
tau_auto float \| None required
tau_hitl float required

SelfCorrectionConfig

Field Type Default
quality_threshold float 0.85
fallback_threshold float 0.6
consistency_k int 3
theory_retirement_strength float 0.2
max_theories int 20
theory_strength_init float 0.5

TrustEnvelope

Input envelope for trust evaluation (Codex Sec 4.3).

Field Type Default
stakes str required
grounding_coverage float required
model_quality float required
chain_accuracy float required
decomposition_depth int required
error_risk float required

TrustVerdict

Result of trust evaluation against stakes thresholds.

Field Type Default
action str required
sla_class str required
confidence float required
reason str required

SolvabilityVerdict

Result of solvability check (Thm 10: C(M,W,T) >= V(P)).

Field Type Default
solvable bool required
capacity float required
variety float required
margin float required
reason str required

Functions

ensure_schema_version(payload: dict[str, Any], version: str = CURRENT_SCHEMA_VERSION) -> dict[str, Any]

normalize_schema_version(payload: dict[str, Any], default: str = '0.0') -> str

read_version(payload: dict[str, Any]) -> str

is_compatible(payload: dict[str, Any], current: str = CURRENT_SCHEMA_VERSION) -> bool

assert_compatible(payload: dict[str, Any], current: str = CURRENT_SCHEMA_VERSION, artifact_type: str = 'artifact') -> None

load_versioned_artifact(payload: dict[str, Any], artifact_type: str, current: str = CURRENT_SCHEMA_VERSION, required_fields: tuple[str, ...] = ()) -> dict[str, Any]

new_request_id(prefix: str = 'req') -> str

get_request_id() -> str | None

get_run_id() -> str | None

get_task_id() -> str | None

bind(request_id: str | None = None, run_id: str | None = None, task_id: str | None = None) -> dict[str, Token[str | None]]

reset(tokens: dict[str, Token[str | None]]) -> None

bound(request_id: str | None = None, run_id: str | None = None, task_id: str | None = None)

load_error_catalog() -> dict[str, dict[str, str]]

Load the small local error-code catalog without requiring PyYAML.

error_catalog_record(code: str) -> dict[str, str]

Return catalog metadata for code, or an empty record if unknown.

suggested_action_for_code(code: str, default: str = 'Check the request and retry.') -> str

Return the user-facing recovery action for an error code.

title_for_code(code: str, default: str = 'Request failed') -> str

Return the problem-title text for an error code.

type_for_code(code: str, default_base_url: str = 'https://g6solver.local/problems') -> str

Return the RFC 9457 problem type URL for an error code.

status_for_code(code: str, default: int = 400) -> int

Return the cataloged HTTP status for an error code when available.

problem_detail_for_code(code: str, detail: str, status: int | None = None, request_id: str | None = None, instance: str | None = None) -> dict[str, Any]

Build an RFC 9457-style problem detail from the shared catalog.

to_problem_detail(error: G6Error, status: int = 400, request_id: str | None = None, instance: str | None = None) -> dict[str, Any]

unknown_op_error(component: str, op: str, valid_ops: list[str]) -> G6Error

Factory for the common 'Unknown op' pattern with fuzzy matching.

missing_param_error(component: str, param: str, op: str | None = None) -> G6Error

not_found_error(component: str, resource: str, identifier: str) -> G6Error

validation_error(component: str, detail: str) -> G6Error

dependency_error(component: str, dependency: str) -> G6Error

resource_limit_error(component: str, resource: str, limit: int | float) -> G6Error

to_core(rresult: RResult[Any]) -> Result

Convert returns.Resultmvp.core.Result.

from_core(result: Result) -> RResult[Any]

Convert mvp.core.Resultreturns.Result.

safe_invoke(block: Any, data: Any) -> RResult[Any]

Call block.infer(data) and return a returns.Result.

flow_blocks(*blocks: Any) -> Callable[[Any], RResult[Any]]

Return a function that chains blocks sequentially using bind.

component_maturity(level: Maturity, reason: str = '')

Decorator: mark a component class with a maturity level.

get_maturity(cls) -> Maturity | None

Return the declared maturity level or None if unmarked.

maturity_reason(cls) -> str

component_capabilities(*caps: str)

Decorator: declare capabilities a component provides (e.g. 'llm_routing', 'formal_verification').

get_capabilities(cls) -> tuple[str, ...]

Return declared capabilities for a component class.

observable(cls)

Mark a component as observable — emits lifecycle events for monitoring.

is_observable(cls) -> bool

Return whether the class is marked as observable.

optional_import(module_name: str, pip_name: str | None = None)

Import an optional dependency, returning a proxy if unavailable.

run_pipeline(steps: list[PipelineStep], initial: dict[str, Any], registry: Any = None, stakes: str = 'medium', cancel_check: Callable[[], bool] | None = None) -> RResult[dict, str]

Execute steps sequentially, threading the output of each into

run_parallel(steps: list[PipelineStep], inputs: list[dict[str, Any]], registry: Any = None) -> RResult[list[dict], str]

Execute steps concurrently via trio.open_nursery().

run_pipeline_trio(steps: list[PipelineStep], initial: dict[str, Any], registry: Any = None, stakes: str = 'medium', cancel_check: Callable[[], bool] | None = None) -> RResult[dict, str]

Synchronous wrapper that calls trio.run() to execute

run_pipeline_traced(steps: list[PipelineStep], initial: dict[str, Any], workflow_name: str = 'unnamed', registry: Any = None) -> tuple[RResult[dict, str], 'WorkflowTrace | None']

Synchronous pipeline executor that also returns a WorkflowTrace.

check_compatibility(block_a: Any, block_b: Any) -> RResult[dict, str]

Verify output type of block_a matches input type of block_b.

run_parallel_trio(steps: list[PipelineStep], inputs: list[dict[str, Any]], registry: Any = None) -> RResult[list[dict], str]

Synchronous wrapper that calls trio.run() to execute

list_production() -> list[str]

is_production(harness_id: str) -> bool

resolve_model_profile(model_id: str) -> ModelProfile

Look up a ModelProfile by substring match against known families.

estimate_chain_reliability(n_steps: int, per_step_accuracy: float = DEFAULT_STEP_CONFIDENCE) -> float

Thm 9: A_chain = a^n.

compute_capacity(model_id: str, context_tokens: int, tool_count: int) -> float

C(M, W, T) = C_weights + C_context + C_tools.

hitl_threshold(cost_human: float, cost_error: float) -> float

tau_trust = 1 - C_human / C_error.

minimum_token_budget(model_id: str, domain: str = 'general', estimated_output_bits: float = 100.0, grounding_depth: int = 1, epsilon: float = 0.05) -> int

n_in >= I(y*|x) / R(M) + n_ground(d, epsilon).

evaluate_trust(envelope: TrustEnvelope) -> TrustVerdict

Evaluate trust envelope against stakes thresholds and return verdict.

check_solvability(model_id: str, context_tokens: int, tool_count: int, estimated_difficulty: float) -> SolvabilityVerdict

Check whether model capacity meets problem variety (Thm 10).