A channel's message slots are named from the client, on every backend

The IR called them react-message and django-message, so a FastAPI channel had
to declare a DjangoMessage. They are client-message and server-message now,
and the direction words hold wherever a channel is declared: Params /
ClientMessage / ServerMessage, with mizan-core deriving <Pascal>Params and
friends so no backend names a type itself. Django's ReactChannel and
FastAPI's ReactChannel are both Channel.

mizan-fastapi never registered a channels extension, so build_ir() emitted no
channel at all and every payload type was invisible to codegen. It registers
one now. RegistryExtension is an ABC requiring all(), which is what the IR
reads — an extension that cannot enumerate its registrations no longer exists.

The gate that should have caught the rename could not: tests/afi registered no
channel because mizan-rust had no channel registry to register one in, so a
five-package rename of the wire contract passed byte-parity without a channel
byte crossing it. mizan-rust grows ChannelSlotKind, a CHANNELS slice, a
#[mizan::channel] macro, and KDL emission whose wire_to_pascal matches Python's
split; the AFI fixture now carries a channel with every slot and one with a
single slot, so all three backends prove the contract byte for byte.

MizanChannel held three Option<String> beside three has_*() predicates and
unwrapped them with defaults; it holds an ordered slot vector, so an absent
slot is absent rather than defaulted. The channels target emitted a React
hooks file that a stage1-only consumer could not compile — react emits that
now. The codegen's parity tests byte-compared emitted source against baselines
without ever compiling it: they compile the generated crate and run its tests,
import the generated Python package and call every method, and typecheck each
TypeScript target against a consumer.

Also fixed at source: app_visitor printed its import diagnostic to stdout, the
stream export_mizan_ir writes KDL to, so a failed import silently corrupted the
IR; the apps root was hardcoded to "apps"; _default_literal crashed build_ir on
any non-JSON-serializable field default; Django and mizan-core derived Pascal
names two different ways, disagreeing on every dotted channel name.

ir.py builds a document and renders templates/ir/document.kdl.j2 rather than
appending KDL strings with hand-tracked indentation, and named types resolve to
a fixed point — a model reachable only through a union branch was referenced by
a ref that no type block ever defined.

The rest is the write-gate's own classifiers run over the standing tree:
relative imports, silent swallows, Protocol contracts that should be ABCs,
emitters hand-rendering target source, catch-all arms over closed enums, and
comments narrating the project rather than the code.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-27 14:03:19 -04:00
parent 398c90fc8b
commit 3aafec6dd4
345 changed files with 11054 additions and 17359 deletions

View File

@@ -1,26 +1,20 @@
'use client'
// AUTO-GENERATED by mizan — do not edit
import { useChannel, type ChannelSubscription } from 'mizan/channels'
{% if !type_imports.is_empty() -%}
import type { {{ type_imports|join(", ") }} } from './channels'
{% endif -%}
// ── Channel Hooks ─────────────────────────────────────────────────────────
{% for ch in channels -%}
/**
* Hook for the {{ ch.name }} channel.
*/
{% if ch.has_params -%}
export function use{{ ch.pascal_name }}Channel(params: {{ ch.params_type_or_record }}): ChannelSubscription<{{ ch.params_type_or_record }}, {{ ch.django_msg_type_or_never }}, {{ ch.react_msg_type_or_never }}> {
{% for ch in param_channels -%}
export function use{{ ch.pascal_name }}Channel(params: {{ ch.params_type }}): ChannelSubscription<{{ ch.params_type }}, {{ ch.server_message_type }}, {{ ch.client_message_type }}> {
return useChannel('{{ ch.name }}', params)
}
{% else -%}
export function use{{ ch.pascal_name }}Channel(): ChannelSubscription<Record<string, never>, {{ ch.django_msg_type_or_never }}, {{ ch.react_msg_type_or_never }}> {
{% endfor -%}
{% for ch in paramless_channels -%}
export function use{{ ch.pascal_name }}Channel(): ChannelSubscription<Record<string, never>, {{ ch.server_message_type }}, {{ ch.client_message_type }}> {
return useChannel('{{ ch.name }}', {})
}
{% endif %}
{% endfor -%}

View File

@@ -1,25 +1,15 @@
// AUTO-GENERATED by mizan — do not edit
{% for schema in schemas %}{{ schema }}{% if !loop.last %}
{{ schemas_block }}
// ── Channel Registry ──────────────────────────────────────────────────────
{% endif %}{% endfor %}
export const CHANNELS = {
{%- for ch in channels %}
{{ ch.name }}: {
'{{ ch.name }}': {
name: '{{ ch.name }}',
pascalName: '{{ ch.pascal_name }}',
hasParams: {{ ch.has_params }},
hasReactMessage: {{ ch.has_react_message }},
hasDjangoMessage: {{ ch.has_django_message }},
{%- if ch.has_params %}
paramsType: '{{ ch.params_type }}',
{%- endif %}
{%- if ch.has_react_message %}
reactMessageType: '{{ ch.react_message_type }}',
{%- endif %}
{%- if ch.has_django_message %}
djangoMessageType: '{{ ch.django_message_type }}',
{%- endif %}
{%- for slot in ch.slots %}
{{ slot.registry_key }}: '{{ slot.type_name }}',
{%- endfor %}
},
{%- endfor %}
} as const

View File

@@ -0,0 +1,7 @@
#[derive({% for d in derives %}{% if !loop.first %}, {% endif %}{{ d }}{% endfor %})]
#[serde(rename_all = "snake_case")]
pub enum {{ name }} {
{% for v in variants %}{% if v.is_default %} #[default]
{% endif %} {{ v.ident }},
{% endfor %}}

View File

@@ -0,0 +1,2 @@
{{ header }}{% for block in blocks %}{{ block }}{% if !loop.last %}
{% endif %}{% endfor %}

View File

@@ -1,5 +1,3 @@
# AUTO-GENERATED by mizan — do not edit
from .client import MizanClient # noqa: F401
from .types import * # noqa: F401, F403

View File

@@ -1,5 +1,3 @@
# AUTO-GENERATED by mizan — do not edit
from __future__ import annotations
from collections.abc import Callable
@@ -25,8 +23,19 @@ class MizanClient:
csrf_header_name=csrf_header_name,
)
{{ ctx_methods_block }}
{{ call_methods_block }}
{% for ctx in contexts %} def fetch_{{ ctx.snake }}_context(self{% for p in ctx.params %}, {{ p.ident }}: {{ p.ty }}{% if !p.required %} | None = None{% endif %}{% endfor %}) -> "{{ ctx.data_class }}":
raw = self._inner.fetch_context("{{ ctx.name }}", {{ "{" }}{% for p in ctx.params %}{% if !loop.first %}, {% endif %}"{{ p.raw_name }}": {{ p.ident }}{% endfor %}{{ "}" }})
return {{ ctx.data_class }}(**raw)
def subscribe_{{ ctx.snake }}_context(self{% for p in ctx.params %}, {{ p.ident }}: {{ p.ty }}{% if !p.required %} | None = None{% endif %}{% endfor %},
callback: Callable[[dict[str, Any]], None]) -> PyContextSubscription:
return self._inner.subscribe_context("{{ ctx.name }}", {{ "{" }}{% for p in ctx.params %}{% if !loop.first %}, {% endif %}"{{ p.raw_name }}": {{ p.ident }}{% endfor %}{{ "}" }}, callback)
{% if !loop.last %}
{% endif %}{% endfor %}
{% for call in calls %} def call_{{ call.snake }}(self{% match call.input %}{% when CallInput::Typed with (t) %}, args: {{ crate::emit::casing::pascal_case(t) }}{% when CallInput::Absent %}{% endmatch %}) -> {{ call.output }}{% if call.nullable %} | None{% endif %}:
raw = self._inner.call("{{ call.wire_name }}", {% match call.input %}{% when CallInput::Typed with (t) %}args.model_dump(){% when CallInput::Absent %}{}{% endmatch %})
return {{ call.output }}(**raw){% if call.nullable %} if raw is not None else None{% endif %}
{% if !loop.last %}
{% endif %}{% endfor %}
def invalidate(self, context: str) -> None:
self._inner.invalidate(context)
@@ -34,6 +43,8 @@ class MizanClient:
self._inner.invalidate_scoped(context, params)
# ── Context data shapes (per-context bundle) ──────────────────────────────
{{ data_classes_block }}
{% for dc in data_classes %}class {{ dc.class_name }}(BaseModel):
"""Bundled return of fetch_{{ dc.snake }}_context."""
{% for f in dc.fields %} {{ f.ident }}: {{ f.ty }}{% if f.nullable %} | None{% endif %}
{% endfor %}{% if !loop.last %}
{% endif %}{% endfor %}

View File

@@ -0,0 +1,17 @@
{%- match kind -%}
{%- when PySchemaKind::Class with (fields) -%}
class {{ name }}(BaseModel):
{%- if fields.is_empty() %}
pass
{%- else %}
{%- for f in fields %}
{{ f.ident }}: {{ f.ty }}{% if f.append_none %} | None{% endif %}{% if f.optional %} = None{% endif %}
{%- endfor %}
{%- endif %}
{%- when PySchemaKind::ListOf with (inner) -%}
{{ name }} = list[{{ crate::emit::python::py_type(inner) }}]
{%- when PySchemaKind::Literal with (variants) -%}
{{ name }} = Literal[{% for v in variants %}{% if !loop.first %}, {% endif %}"{{ v }}"{% endfor %}]
{%- when PySchemaKind::Alias with (inner) -%}
{{ name }} = {{ crate::emit::python::py_type(inner) }}
{%- endmatch -%}

View File

@@ -0,0 +1,14 @@
{%- match shape -%}
{%- when TypeShape::Ref with (name) -%}
{{ crate::emit::casing::pascal_case(name) }}
{%- when TypeShape::Primitive with (p) -%}
{{ crate::emit::python::primitive_to_py(p) }}
{%- when TypeShape::List with (inner) -%}
list[{{ crate::emit::python::py_type(inner) }}]
{%- when TypeShape::Optional with (inner) -%}
{{ crate::emit::python::py_type(inner) }} | None
{%- when TypeShape::Enum with (variants) -%}
Literal[{% for v in variants %}{% if !loop.first %}, {% endif %}"{{ v }}"{% endfor %}]
{%- when TypeShape::Union with (branches) -%}
{% for b in branches %}{% if !loop.first %} | {% endif %}{{ crate::emit::python::py_type(b) }}{% endfor %}
{%- endmatch -%}

View File

@@ -1,10 +1,9 @@
# AUTO-GENERATED by mizan — do not edit
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel
{{ schemas_block }}
{% for schema in schemas %}{{ schema }}
{% if !loop.last %}
{% endif %}{% endfor %}

View File

@@ -1,7 +1,5 @@
'use client'
// AUTO-GENERATED by mizan — do not edit
{% set has_contexts = has_global || !named_contexts.is_empty() -%}
import {
{% if has_contexts -%}
@@ -30,11 +28,14 @@ import {
} from '@mizan/base'
{% if !stage1_imports.is_empty() -%}
import { {{ stage1_imports|join(", ") }} } from './index'
import {
{%- for p in stage1_imports.contexts %} fetch{{ p }}Context, type {{ p }}ContextData, type {{ p }}ContextParams,{% endfor %}
{%- for p in stage1_imports.calls %} call{{ p }},{% endfor %}
{%- for t in stage1_imports.context_output_types %} type {{ t }},{% endfor %} } from './index'
{% endif -%}
{% if has_contexts -%}
// Internal — runs inside a Provider, registers with the kernel exactly once.
// Runs inside a Provider, registers with the kernel exactly once.
function useContextSubscription<T>(
name: string,
params: Record<string, any>,
@@ -56,7 +57,7 @@ function useContextSubscription<T>(
}
{% endif %}
// Internal — wraps an imperative call() with isPending / error state.
// Wraps an imperative call() with isPending / error state.
interface MutationHook<TArgs, TResult> {
mutate: (args: TArgs) => Promise<TResult>
isPending: boolean
@@ -85,8 +86,6 @@ function useMutation<TArgs, TResult>(
return { mutate, isPending, error }
}
{% if has_global %}
// ── Global Context ──
const GlobalCtx = createContext<ContextState<GlobalContextData> | null>(null)
export function GlobalContextProvider({ children }: { children: ReactNode }) {
@@ -107,8 +106,6 @@ export function use{{ fn.pascal }}(): {{ fn.output_type }} | null {
{% endfor -%}
{% endif -%}
{% for ctx in named_contexts %}
// ── {{ ctx.pascal }} Context ──
const {{ ctx.pascal }}Ctx = createContext<ContextState<{{ ctx.pascal }}ContextData> | null>(null)
{% if ctx.has_params -%}
@@ -144,8 +141,6 @@ export function use{{ call.pascal }}() {
}
{% endif -%}
{% endfor %}
// ── MizanContext root provider ──
export interface MizanContextProps {
/** Base URL for protocol endpoints. Defaults to "/api/mizan". */
baseUrl?: string
@@ -155,8 +150,8 @@ export interface MizanContextProps {
}
/**
* Root provider — calls configure() once and mounts the global context (if defined).
* Must wrap any component using Mizan-generated hooks.
* Calls configure() once and mounts the global context when one is defined.
* Every component reading a generated hook resolves through this provider.
*/
export function MizanContext({ baseUrl, session, children }: MizanContextProps) {
const configured = useRef(false)
@@ -174,12 +169,7 @@ export function MizanContext({ baseUrl, session, children }: MizanContextProps)
{%- endif %}
}
// ── Imperative escape hatch ──
/**
* Returns the imperative kernel API. For test harnesses or rare cases where
* a typed generated hook does not fit. Most app code should use the typed hooks.
*/
/** The untyped kernel entry points, bound to the configured client. */
export function useMizan() {
return { call: mizanCall, fetch: mizanFetch }
}

View File

@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"
[dependencies]
mizan-rust = {{ kernel_dep }}
mizan-rust = { {% for kv in kernel_dep %}{% if !loop.first %}, {% endif %}{{ kv.key }} = "{{ kv.value }}"{% endfor %} }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["rt", "macros"] }

View File

@@ -1,15 +1,12 @@
// AUTO-GENERATED by mizan — do not edit
use serde_json::Value;
use mizan_rust::{MizanClient, MizanError};
{% if !type_imports.is_empty() -%}
use crate::types::{ {{- type_imports|join(", ") -}} };
{% endif -%}
pub async fn call_{{ snake }}(client: &MizanClient{{ input_param }}) -> Result<{{ return_type }}, MizanError> {
let args_value = {{ args_value }};
pub async fn call_{{ snake }}(client: &MizanClient{% match input %}{% when CallInput::Typed with (t) %}, args: &{{ crate::emit::casing::rust_type_ident(t) }}{% when CallInput::Absent %}{% endmatch %}) -> Result<{% if nullable %}Option<{{ output_type }}>{% else %}{{ output_type }}{% endif %}, MizanError> {
let args_value = {% match input %}{% when CallInput::Typed with (t) %}serde_json::to_value(args)
.map_err(|e| MizanError::transport(format!("encode {{ name }} args: {e}")))?{% when CallInput::Absent %}serde_json::Value::Object(Default::default()){% endmatch %};
let raw = client.call("{{ name }}", args_value).await?;
serde_json::from_value(raw)
.map_err(|e| MizanError::transport(format!("decode {{ name }} result: {e}")))

View File

@@ -1,7 +1,4 @@
// AUTO-GENERATED by mizan — do not edit
use serde::{Deserialize, Serialize};
use serde_json::Value;
use mizan_rust::{MizanClient, MizanError};
@@ -12,16 +9,16 @@ use crate::types::{ {{- type_imports|join(", ") -}} };
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {{ pascal }}ContextData {
{% for field in data_fields -%}
{% if field.has_rename %} #[serde(rename = "{{ field.raw_name }}")]
{% endif %} pub {{ field.ident }}: {{ field.ty }},
{% if field.has_rename %} #[serde(rename = "{{ field.wire_name }}")]
{% endif %} pub {{ field.ident }}: {% if field.optional %}Option<{{ field.ty }}>{% else %}{{ field.ty }}{% endif %},
{% endfor -%}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {{ pascal }}ContextParams {
{% for p in params -%}
{% if p.has_rename %} #[serde(rename = "{{ p.raw_name }}")]
{% endif %} pub {{ p.ident }}: {{ p.ty }},
{% if p.has_rename %} #[serde(rename = "{{ p.wire_name }}")]
{% endif %} pub {{ p.ident }}: {% if p.optional %}Option<{{ p.ty }}>{% else %}{{ p.ty }}{% endif %},
{% endfor -%}
}
@@ -29,7 +26,8 @@ pub async fn fetch_{{ snake }}_context(
client: &MizanClient,
params: &{{ pascal }}ContextParams,
) -> Result<{{ pascal }}ContextData, MizanError> {
let params_value = serde_json::to_value(params).unwrap_or(Value::Object(Default::default()));
let params_value = serde_json::to_value(params)
.map_err(|e| MizanError::transport(format!("encode {{ ctx_name }} context params: {e}")))?;
let raw = client.fetch_context("{{ ctx_name }}", &params_value).await?;
serde_json::from_value(raw)
.map_err(|e| MizanError::transport(format!("decode {{ ctx_name }} context: {e}")))

View File

@@ -1,5 +1,3 @@
// AUTO-GENERATED by mizan — do not edit
pub mod types;
{% if has_contexts %}pub mod contexts;
{% endif %}{% if has_mutations %}pub mod mutations;

View File

@@ -1,5 +1,3 @@
// AUTO-GENERATED by mizan — do not edit
{% for name in modules -%}
pub mod {{ name }};
{% endfor %}

View File

@@ -0,0 +1,20 @@
{%- match kind -%}
{%- when RustSchemaKind::Struct with (fields) -%}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct {{ name }} {
{% for f in fields %}{% if f.has_rename %} #[serde(rename = "{{ f.wire_name }}")]
{% endif %} pub {{ f.ident }}: {{ f.ty }},
{% endfor %}}
{%- when RustSchemaKind::StringEnum with (variants) -%}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum {{ name }} {
{% for v in variants %}{% if v.has_rename %} #[serde(rename = "{{ v.wire_name }}")]
{% endif %} {{ v.ident }},
{% endfor %}}
{%- when RustSchemaKind::TransparentArray with (inner) -%}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
pub struct {{ name }}(pub Vec<{{ inner }}>);
{%- when RustSchemaKind::Alias with (inner) -%}
pub type {{ name }} = {{ inner }};
{%- endmatch -%}

View File

@@ -0,0 +1,10 @@
{%- match shape -%}
{%- when RustShape::Named with (name) -%}
{{ name }}
{%- when RustShape::List with (inner) -%}
Vec<{{ crate::emit::rust::rust_type(inner) }}>
{%- when RustShape::Optional with (inner) -%}
Option<{{ crate::emit::rust::rust_type(inner) }}>
{%- when RustShape::Json -%}
serde_json::Value
{%- endmatch -%}

View File

@@ -1,8 +1,9 @@
// AUTO-GENERATED by mizan — do not edit
#![allow(non_camel_case_types)]
use serde::{Deserialize, Serialize};
{{ schemas_block }}
{{ hoisted_enums_block }}
{% for schema in schemas %}{{ schema }}
{% endfor %}{% for hoisted in hoisted_enums %}{{ hoisted }}
{% if !loop.last %}
{% endif %}{% endfor %}

View File

@@ -1,17 +1,15 @@
// AUTO-GENERATED by mizan — do not edit
import { mizanCall } from '@mizan/base'
{% if !type_imports.is_empty() -%}
import type { {{ type_imports|join(", ") }} } from '../types'
{% endif -%}
{% if has_input -%}
export function call{{ pascal }}(args: {{ input_type }}): Promise<{{ output_type }}> {
{% match input %}{% when CallInput::Typed with (t) -%}
export function call{{ pascal }}(args: {{ t }}): Promise<{{ output_type }}> {
return mizanCall('{{ name }}', args)
}
{% else -%}
{% when CallInput::Absent -%}
export function call{{ pascal }}(): Promise<{{ output_type }}> {
return mizanCall('{{ name }}', {})
}
{% endif %}
{% endmatch %}

View File

@@ -1,5 +1,3 @@
// AUTO-GENERATED by mizan — do not edit
import { mizanFetch } from '@mizan/base'
{% if !type_imports.is_empty() -%}

View File

@@ -1,5 +1,3 @@
// AUTO-GENERATED by mizan — do not edit
export * from './types'
{% if !contexts.is_empty() %}
{%- for ctx in contexts %}
@@ -12,7 +10,6 @@ export { call{{ call.pascal }} } from './{{ call.dir }}/{{ call.camel_name }}'
{%- endfor %}
{% endif -%}
{% if !framework_adapters.is_empty() %}
// Stage 2 framework adapter
{%- for name in framework_adapters %}
export * from './{{ name }}'
{%- endfor %}

View File

@@ -0,0 +1,16 @@
{%- match kind -%}
{%- when TsSchemaKind::Interface with (fields) -%}
{%- if fields.is_empty() -%}
export interface {{ name }} {}
{%- else -%}
export interface {{ name }} {
{% for f in fields %} {{ f.name }}{% if !f.required %}?{% endif %}: {{ f.ty }}
{% endfor %}}
{%- endif -%}
{%- when TsSchemaKind::ArrayOf with (inner) -%}
export type {{ name }} = {{ crate::emit::stage1::ts_type(inner) }}[]
{%- when TsSchemaKind::Union with (variants) -%}
export type {{ name }} = {% for v in variants %}{% if !loop.first %} | {% endif %}"{{ v }}"{% endfor %}
{%- when TsSchemaKind::Alias with (inner) -%}
export type {{ name }} = {{ crate::emit::stage1::ts_type(inner) }}
{%- endmatch -%}

View File

@@ -0,0 +1,14 @@
{%- match shape -%}
{%- when TypeShape::Ref with (name) -%}
{{ name }}
{%- when TypeShape::Primitive with (p) -%}
{{ crate::emit::stage1::primitive_to_ts(p) }}
{%- when TypeShape::List with (inner) -%}
{{ crate::emit::stage1::ts_type(inner) }}[]
{%- when TypeShape::Optional with (inner) -%}
{{ crate::emit::stage1::ts_type(inner) }} | null
{%- when TypeShape::Enum with (variants) -%}
{% for v in variants %}{% if !loop.first %} | {% endif %}"{{ v }}"{% endfor %}
{%- when TypeShape::Union with (branches) -%}
{% for b in branches %}{% if !loop.first %} | {% endif %}{{ crate::emit::stage1::ts_type(b) }}{% endfor %}
{%- endmatch -%}

View File

@@ -0,0 +1,3 @@
{% for schema in schemas %}{{ schema }}
{% endfor %}

View File

@@ -1,10 +1,11 @@
// AUTO-GENERATED by mizan — do not edit
import { readable, type Readable } from 'svelte/store'
import { registerContext, type ContextState } from '@mizan/base'
{% if !stage1_imports.is_empty() -%}
import { {{ stage1_imports|join(", ") }} } from '../index'
import {
{%- for p in stage1_imports.contexts %} fetch{{ p }}Context, type {{ p }}ContextData, type {{ p }}ContextParams,{% endfor %}
{%- for p in stage1_imports.calls %} call{{ p }},{% endfor %}
{%- for t in stage1_imports.context_output_types %} type {{ t }},{% endfor %} } from '../index'
{% endif -%}
{% for ctx in contexts -%}

View File

@@ -1,10 +1,11 @@
// AUTO-GENERATED by mizan — do not edit
import { ref, computed, onMounted, onUnmounted, onServerPrefetch, type ComputedRef } from 'vue'
import { registerContext, type ContextState } from '@mizan/base'
{% if !stage1_imports.is_empty() -%}
import { {{ stage1_imports|join(", ") }} } from '../index'
import {
{%- for p in stage1_imports.contexts %} fetch{{ p }}Context, type {{ p }}ContextData, type {{ p }}ContextParams,{% endfor %}
{%- for p in stage1_imports.calls %} call{{ p }},{% endfor %}
{%- for t in stage1_imports.context_output_types %} type {{ t }},{% endfor %} } from '../index'
{% endif -%}
{% for ctx in contexts -%}