Home/Docs/Architecture & Contracts/Type Boundaries (L0–L4)

Type & Contract Boundaries (Canonical)🔗

This document records the current boundary rules for how ContextUnity layers wire data, JSON trees, gRPC payloads, and Pydantic domain models. It captures lessons from the packages/core strict-typing sweep (basedpyright 0/0, honest guards, no Any/cast/# type: ignore theater).

Related: core-contracts.md · code-quality.md

Delivery: delivery-readiness.md · TESTS.md

Important
  • INV-TYPE-BOUNDARIES-STRICT-SEAMS: Values cross representation layers (L0 -> L4) only through explicit validators; data claiming JSON passes recursive L2 validation (is_json_value / is_json_dict) before entering a JSON contract, while open L3 maps (StreamPayload / ContextUnitPayload) are sanitized explicitly at the protobuf conversion boundary (to_protobuf).

1. Layer Model (L0 → L4)🔗

LayerNameCanonical typeProduced byConsumed by
L0Bytes / textstr, bytesnetwork, diskparsing.py only
L1Wire treeWireValue (object)json_loads, yaml_load, tomllib via TypeAdapterL2 guards, Pydantic WireValue fields
L2JSON treeJsonValue (PEP 695 type alias), JsonDictis_json_value, is_json_dictconfig load, manifest load, discovery JSON, Pydantic fields via StructDataValue
L3Open gRPC mapContextUnitPayloadSDK clients, service handlers (pre-sanitize)ContextUnit, _call_unary, protobuf Struct
L4Domain modelPydantic / TypedDictmodel_validate, bundle generatorsbusiness logic, tests

Rule: data may only move down the stack (L1→L2→L3→L4) through explicit validators. Never skip L2 when the contract claims JSON.

These L-labels describe data representation and validation only. Config authority and precedence use C0–C3 (deployment → project → graph → node), as defined by ADR-0002. For example, a C1 project-manifest value still crosses L0–L4 while it is read, decoded, validated, and compiled. Use C1/C2 for project/graph configuration; reserve L-labels for representation and validation boundaries.


2. Canonical Types (contextunity.core.types)🔗

from contextunity.core.types import (
    WireValue,           # L1 — parse output only
    JsonValue, JsonDict, JsonPrimitive,
    ConfigMapping,       # alias of JsonDict after L2 validation
    ContextUnitPayload,  # L3 — open gRPC payload dict
    is_json_value, is_json_dict, is_object_dict,
)

# Value-level narrowing (bare object → scalar / JSON, best-effort) — §4.5
from contextunity.core.narrowing import as_str, as_json_dict, object_attr

SDK re-exports (contextunity.core.sdk.types)🔗

contextunity.core.sdk.models owns the shared classification Pydantic models (ClassificationOption, ClassificationRequest, ClassificationResult, and validate_classification_result). Services and extensions import these contracts through contextunity.core.sdk.types. ClassificationRequest keeps the candidate list provider-neutral. The selected classifier adapter owns its API-specific option limits and failure mapping. The Router classify tool may declare tool_config.max_choice_criteria for one node invocation; Router passes that value to the selected API adapter, which validates it against the API's supported capacity and counts any reserved choices. This setting does not add a candidate-count limit to the shared Core request contract.

Services and extensions must not redefine these aliases:

SDK aliasCanonical sourceUse when
ToolPayload, ToolResultContextUnitPayloadbootstrap, federated tools
StructData, StructDataValueJsonDict, JsonValuerouter/brain integration
WorkerBindingsWorkerBindingsBundlemanifest → worker
# ✅ Services
from contextunity.core.types import JsonDict, ContextUnitPayload
from contextunity.core.sdk.types import ToolPayload, StructDataValue

# ❌ Forbidden — duplicate trees
type MyPayload = dict[str, Any]
JsonValue = str | int | ...  # local redefinition

3. Parse Boundary (contextunity.core.parsing)🔗

Only module that may call json.loads / json.dumps inside packages/core/src (enforced by INV-CORE-JSON-LOADS-THROUGH-PARSING and INV-CORE-JSON-DUMPS-THROUGH-PARSING).

from contextunity.core.parsing import json_loads, json_dumps, yaml_load

Why WireValue = object and TypeAdapter?🔗

  • Pyright goal: keep stdlib/PyYAML Any out of application code without vendored stubs.
  • Runtime goal: decode bytes/YAML into Python values — not validate JSON Schema.
  • L1 accepts YAML tags (!!timestamp), Decimal, etc.; L2 rejects them via is_json_value.

Do not replace L1 with a TypeAdapter for JsonValue — Pydantic raises RecursionError on recursive type aliases in model fields (see WorkerBindingsBundle lesson below).


4. Honest Guards (L1 → L2)🔗

Shallow guards are forbidden where the contract says JSON:

# ❌ Theater — accepts YAML dates, NaN, non-JSON objects
def is_json_dict(value: object) -> TypeGuard[JsonDict]:
    return isinstance(value, dict)

# ✅ Honest — recursive L2
def is_json_dict(value: object) -> TypeGuard[JsonDict]:
    return is_object_dict(value) and is_json_value(value)

is_json_value rejects: datetime, NaN, Inf, arbitrary Python objects.

Apply at boundaries:

BoundaryGuardOn failure
load_config_fileis_json_dictConfigurationError
load_manifestis_json_dictreturn None / error path
factory._deep_mergeis_json_value per keyskip non-JSON overlay keys

4.5 Value-Level Narrowing (contextunity.core.narrowing)🔗

Three complementary tools — pick by data shape and contract strictness:

SituationModuleRole
Must reject non-JSON at a hard boundarycontextunity.core.types (is_json_dict, is_json_value)L2 validation — fail or skip
Known key in ContextUnit.payload (L3)contextunity.core.sdk.payload (get_str, get_json_dict, …)Keyed wire accessors
Bare object with no envelope keycontextunity.core.narrowing (as_str, as_json_dict, …)Best-effort L1→L2 narrowing
from contextunity.core.narrowing import (
    as_str, as_int, as_float, as_str_list,
    as_json_dict, as_json_dict_list, as_json_dict_map,
    object_attr, optional_str_field,
    str_list_as_json, json_dict_list_as_json,
    tuple_len, tuple_item_at,
)

When to use narrowing🔗

Use at service boundaries when the value is already object and you need a concrete type for pyright — without cast, Any, or # type: ignore:

SourceTypical helpers
dict.get, graph / LangGraph dictsas_str, as_json_dict, as_str_list
SQLite / Postgres row cells, driver tuplesas_str, as_int, as_float, tuple_item_at
getattr on a third-party objectobject_attr then as_*
ORM / pandas / DuckDB result rowsas_json_dict_list (or a local one-off helper in the sole consumer)
Optional string field inside a loose dictoptional_str_field
Packing Python lists back into L2 JSON treesstr_list_as_json, json_dict_list_as_json

Helpers return safe defaults on mismatch ("", 0, {}, []) — they do not raise. That is intentional for ingestion, storage, and graph-state reads where missing or mistyped keys are common.

When not to use narrowing🔗

NeedUse instead
SDK client mapping a gRPC response fieldget_str, get_json_dict, … from sdk.payload
Config / manifest load — bad file must failis_json_dict → ConfigurationError
Fixed key set at ingressL4 TypedDict + one coerce (model_validate, dedicated coerce fn)
Pydantic domain modelmodel_validate
Must distinguish absent vs empty scalar on wireget_optional_str / inspect raw payload — getters with defaults erase absence

Examples🔗

# ✅ Graph state — open dict, best-effort read
from contextunity.core.narrowing import as_str, as_json_dict

title = as_str(state.get("title"))
meta = as_json_dict(state.get("metadata"))

# ✅ SDK unary response — keyed L3 payload
from contextunity.core.sdk.payload import get_str, get_json_dict

error = get_str(res, "error")
rows = get_json_dict_list(res, "matches")

# ✅ Hard JSON boundary — reject, don't default
from contextunity.core.types import is_json_dict

if not is_json_dict(raw):
    raise ConfigurationError("config root must be a JSON object")

Service rules🔗

  • Import from core — from contextunity.core.narrowing import …. Do not add service-local narrow.py re-exports.
  • No duplicate helpers — prefer one core as_* over repeated inline isinstance blocks (same rule as no inline cast).
  • Domain-only one-offs — e.g. DuckDB result-row parsing used in a single handler — keep a private _helper in that module, built on as_json_dict_list.
  • Match strictness to contract — using as_json_dict where the contract says “invalid shape is a client error” is a semantic bug; use is_json_dict + fail.

Tests: packages/core/tests/test_narrowing.py.


5. gRPC Payload Contract (L3)🔗

ContextUnitPayload🔗

Open dict carried by protobuf Struct before _sanitize_mapping:

ContextUnitPayload: TypeAlias = dict[str, object]

Every SDK client call site, including BaseServiceClient._call_unary, must use the alias:

# ✅
payload: ContextUnitPayload = {"path": path, "tenant_id": tenant_id}
await self._call_unary(self._stub.Scan, payload, rpc_name="Scan")

# ❌ Leaky — contract declared in _base but not at call site
payload: dict[str, object] = {...}

Nested JSON metadata inside payloads → JsonDict:

async def execute_agent(..., payload: ContextUnitPayload | None, metadata: JsonDict | None)

Payload accessors (sdk/payload.py)🔗

Match getter return type to the declared field layer:

Field contractGetterReturns
ContextUnitPayload (open wire sub-map)get_dict, get_dict_listL3 — no L2 recursion
JsonDict / list[JsonDict] in TypedDictget_json_dict, get_json_dict_listL2 — is_json_dict per element
Scalarget_str, get_int, …narrowed primitives

Using get_dict for a TypedDict field typed as JsonDict passes pyright only when both aliases share dict[str, …] — runtime and semantics diverge (non-JSON values can slip through). Always pair TypedDict field type with the matching getter.

SDK unary clients (preserve wire)🔗

Closed-service clients (Shield, Router execute_agent / execute_node, Worker unary RPCs, Brain unary dict RPCs) must return the full unary wire payload, not a getter-only projection or a ContextUnit envelope wrapper:

from contextunity.core.sdk.payload import copy_wire_payload

res = await self._call_unary(self._stub.Scan, payload, rpc_name="Scan")
return copy_wire_payload(res)  # keeps allowed/threats/error/message on the wire

Getter defaults (get_bool → False, get_str → "") erase the difference between “field absent” and “field explicitly false/empty”. TypedDicts document common fields; callers inspect error / message envelope keys when present.

Input: SDK methods take typed kwargs (and optional wire= / provenance= / trace_id= when envelope lineage matters). They do not accept a caller-built ContextUnit — the client assembles the transport envelope internally.

Output: ContextUnitPayload via copy_wire_payload (never a response ContextUnit wrapper).

Router stream wire (StreamPayload)🔗

RouterClient.stream_agent yields open graph state — not a closed per-domain schema:

StreamPayload = ContextUnitPayload  # discriminant: payload["event_type"]

Router sets event_type (progress | result | brain_event | text_delta | tool_start | tool_end | done | error) and may spill arbitrary graph keys (answer, matches, node, …). Text deltas carry delta and node; tool lifecycle events carry call_id and name, with public_args only when the producer has explicitly selected public data. The SDK passes these stream tags through as open payloads and cancels the active RPC when a consumer closes early. Core guards (is_result_event, …) check the discriminant only; they do not enumerate graph fields.

Federated delivery wire (delivery/v1)🔗

Federated delivery argument and result digests cover the JSON object image carried by protobuf Struct. project_struct_json_object validates a finite JSON object, rejects integers outside [-2**53, 2**53], and returns the independent tree a receiver reads after the Struct conversion. Router validates and projects arguments before it records pending work or enqueues a request; the project-side SDK digests and sends the same projected tool result. This keeps the SHA-256 input aligned with the received payload while preserving the v1 message identities and result receipt semantics. A result that cannot be projected after a tool runs is reported as an unknown effect and is not replayed.

Pipeline transformers (BaseTransformer)🔗

class BaseTransformer:
    def configure(self, params: dict[str, object] | None) -> None: ...  # open bag

class JsonConfigurableTransformer(BaseTransformer):
    def configure(self, params: dict[str, object] | None) -> None: ...  # validates L2 at runtime

No separate TransformerConfigureParams alias — the open bag is BaseTransformer.params. JSON-only flow/YAML transformers use JsonConfigurableTransformer; domain objects in configure values stay in service BaseTransformer overrides (e.g. router GraphTransformer).

FlowManager must call transformer.configure after create_transformer, not pass config as **kwargs to __init__.

Introspection seams (stdlib / reflection)🔗

Runtime introspection yields typeshed Any. Name a single choke-point helper and store as dict[str, object] before TypeGuard narrowing:

HelperModuleSource
_class_namespace_memberssdk/toolkit.pytype.__dict__
_record_fieldslogging.pyvars on LogRecord
_metadata_as_dictsecurity/interceptors.pygRPC metadata

Do not pretend these are JsonDict or ContextUnitPayload.

Federated execute wire (BiDi)🔗

from contextunity.core.sdk.payload import parse_federated_execute, FederatedExecuteRequest

execute = parse_federated_execute(payload)  # ContextUnitPayload in
# execute["tool"], execute["args"], … — stable Router → project contract

StructSafe (intentionally separate)🔗

contextunity.core.sdk.contextunit.StructSafe is the protobuf sanitize subtree (str/bool/int/float/list/dict only). Do not merge with JsonValue — different job (reject non-struct types for wire encoding, not JSON Schema).

coerce_struct_data (Brain/Router integration boundaries) normalizes foreign SDK values into L2 JSON trees. Sets/frozensets become sorted JSON arrays (same rule as ContextUnit._sanitize_value) so metadata stays deterministic and JSON-serializable.


6. Pydantic Bundle Pattern (L4)🔗

Compiled manifest artifacts → Pydantic models in manifest/models.py:

class RouterRegistrationBundle(ManifestModel):
    project_id: str = ""
    allowed_tenants: list[str] = Field(default_factory=list)
    graph: dict[str, WireValue] = Field(default_factory=dict)  # not JsonValue!
    ...

    @property
    def enabled(self) -> bool:
        return bool(self.project_id)

Registration bundles are v1alpha8-only: project_id is identity, allowed_tenants is the security scope, and stale tenant_id payload fields are rejected before projection. Router registration state persists under router:registrations:*.

Critical: WireValue in Pydantic fields, not JsonValue🔗

# ❌ RecursionError at model build
workflows: list[dict[str, JsonValue]]

# ✅
workflows: list[dict[str, WireValue]]

Runtime JSON enforcement happens before ContextUnityProject.model_validate (manifest dict is JsonDict). Bundle fields hold compiled projection, not raw YAML.


7. How Services Inherit Types from Core🔗

packages/core/src/contextunity/core/types.py     ← canonical definitions
packages/core/src/contextunity/core/sdk/types.py ← SDK re-exports only
services/*/src/...                               ← import, never redefine
extensions/*/src/...                             ← import, never redefine
NeedImport from
Config / manifest dictcontextunity.core.types.JsonDict, ConfigMapping
gRPC client payloadContextUnitPayload
Tool bootstrap payloadcontextunity.core.sdk.types.ToolPayload
Typed RPC responsescontextunity.core.sdk.responses.* (TypedDict)
Parse untrusted filecontextunity.core.parsing
Bare object → scalar / JSON (best-effort)contextunity.core.narrowing (§4.5)
ContextUnit payload keycontextunity.core.sdk.payload.get_* (§5)
Exceptionscontextunity.core.exceptions (inherit ContextUnityError)

Proto stubs: always from contextunity.core import *_pb2, *_pb2_grpc — never local copies (TestGrpcProtosFromCore).


8. Forbidden Patterns (Lessons Log)🔗

These were tried during the core sweep and rejected:

ApproachWhy it failed
Vendored typeshed-fallback/stdlib/json/Broke stdlib discovery
Hand-written typings/yaml/__init__.pyiFragile, wrong stubPath
UnaryContextUnitRpc custom ProtocolIncompatible with grpc stub types
# type: ignore, --level warning downgradeHides real regressions
cast, AnyBypasses honest contracts
TypeAdapter with JsonValue at L1RecursionError / over-validation at wrong layer
WorkerBindingsBundle with JsonValue fieldsPydantic RecursionError
Shallow isinstance as is_json_dictAccepts YAML dates at runtime
Typing only _call_unary without call sitesPyright green, semantics unchanged
get_dict for TypedDict JsonDict fieldsInvariant lie — use get_json_dict / get_json_dict_list
Closed result TypedDict in coreRouter sends open graph state — use StreamPayload + discriminant guards
Domain-specific settings in a shared transformer APIKeep service-owned settings in the owning service; the shared transformer boundary accepts JSON configuration
Extra type alias for transformer paramsBaseTransformer.params is the open bag; JsonConfigurableTransformer.configure is the L2 seam
Plain recursive TypeAlias for JsonValue in Pydantic consumer fieldsCross-module models (e.g. router ModelRequest with dict[str, StructDataValue]) fail at runtime with PydanticUserError: ... not fully defined; define JsonValue — pyright can still be green
TYPE_CHECKING-only imports in runtime-evaluated annotationsNameError: name 'RedisHuey' is not defined at import (worker engines) when from __future__ import annotations is missing
is_object_list for gRPC invocation_metadataReal metadata is tuple / grpc.aio.Metadata, not list → empty dict → every RPC denied as no token
Mapping[str, object] + coerce at every readMasks weak contracts; readers should use L4 typed store (RegisteredProjectConfig) after one choke-point coerce
dict[str, object] for a known field setImplicit contract — define a TypedDict (e.g. GraphRunConfigInput) and coerce once at L3 ingress; readers take the L4 type, not an open dict
cast / # type: ignore / Any at service boundariesBypasses guards; use TypeGuard, model_validate, contextunity.core.narrowing, or explicit isinstance
Service-local narrow.py re-exporting core helpersDrift and duplicate import paths — import contextunity.core.narrowing directly (§4.5)
as_json_dict where invalid shape must failDefaults hide errors — use is_json_dict + raise at hard boundaries
JsonMetadata Protocol vs SDK JsonDict on BrainProtocol parameter types must match SDK (JsonDict), not a wider local alias
GrpcServicerContext requiring get_trailing_metadataNeither sync nor grpc.aio contexts expose it; @runtime_checkable isinstance fails and @grpc_error_handler masks real errors as Unexpected TypeError

Coerce vs validate vs typed store (L1→L4)🔗

OperationMeaningWhere allowed
CoerceBest-effort normalize unknown wire → typed shape at a boundaryOnly at true choke points: e.g. registration_projection.py (registered_project_config_from_bundle), coerce_struct_data for foreign SDK values
Validatemodel_validate, is_json_dict — reject or fail on bad shapeConfig/manifest load, gRPC ingress before L4
Typed store (L4)After validate/coerce once, all readers use the modele.g. RegisteredProjectConfig in _project_configs; get_node_config reads without re-coerce

Anti-pattern: Mapping[str, object] (or dict[str, object]) plus per-read coercion — weak contract that pyright cannot enforce. Router example: get_node_config must take RegisteredProjectConfig, not Mapping[str, object] with inline coerce_compiler_node_spec on every call.

Router project config types (do not conflate):

TypeLayerRole
ContextUnitPayloadL3Open gRPC map on RegisterManifest / execution requests
RouterRegistrationBundle / ProjectManifestL4 compile-timePydantic from manifest YAML
RegisteredProjectConfigL4 runtime storePost-registration projection; nodes, graph, tools for execution
GraphRunConfigInputL4 execution ingressRunnableConfig subset from ExecuteAgent/ExecuteNode; coerce via coerce_graph_run_config_input on payload

Forbidden / discouraged at service boundaries🔗

  • No cast — use TypeGuard, model_validate, contextunity.core.narrowing, or explicit isinstance + narrowing (§4.5).
  • No # type: ignore or pyright rule downgrades.
  • No Any (including reportAny leakage from untyped third-party returns — narrow at the boundary).
  • Mapping[...] / Callable[...] — only when a stdlib or third-party API requires it; prefer concrete dict, JsonDict, ContextUnitPayload, RegisteredProjectConfig, or a Protocol with named methods aligned to the current SDK signatures.
  • Named TypedDict over open dict[str, object] — when a wire/payload map has a fixed key set (e.g. RunnableConfig subset), define L4 TypedDict + one coerce at ingress; business functions take the typed alias, not dict[str, object] | None.

Protocol vs Callable (domain factories and hooks)🔗

Prefer a Protocol with named methods when the callable carries domain meaning (graph factory, platform adapter, node executor). Reserve bare Callable[[], T] for stdlib/third-party callback hooks, zero-arg thunks with no contract, or APIs that require a function type.

SituationUse
Graph registry / manifest registrationRunnableGraphFactory with build() -> RunnableGraph | StateGraph — see registry.py, resolve_graph, ResolvedGraph in execution/types.py
LangGraph node executorsNodeFunc (__call__(state, config) -> StateUpdate) — cortex/types/graph.py
Decorator factories (register_agent, register_llm, …)Callable[[type[T]], type[T]] — stdlib decorator pattern, no domain product
Retry / telemetry zero-arg async thunkCallable[[], Awaitable[T]] — no named product beyond “run once”

Anti-pattern: GraphBuilder = Callable[[], object] or Callable[[], object] for compiled graphs — weak contract; pyright cannot enforce ainvoke / StateGraph. Use RunnableGraphFactory + is_runnable_graph at execution boundaries.

Do not conflate names: Brain GraphBuilder, router RouterGraphBuilderError, and registry RunnableGraphFactory are different concepts — avoid a shared GraphBuilder type alias.

Legacy override path: router.override_path may still expose build_graph or a bare callable; cortex/builder.py checks RunnableGraphFactory.build first, then build_graph, then callable — prefer registering via graph_registry and RunnableGraphFactory for new code.

8.1 Runtime regression guards (typing refactors)🔗

Static typing (basedpyright) alone does not catch the three failures above. After any change to types.py, security/interceptors.py, Pydantic models using StructDataValue/JsonValue, or engine modules with TYPE_CHECKING imports, run:

# Core contract + security metadata + JsonValue cross-module rebuild
uv run pytest packages/core/tests/test_contract_boundaries.py packages/core/tests/test_security.py -q

# Worker engine import-time annotations (TYPE_CHECKING symbols)
uv run --package contextunity-worker pytest services/worker/tests/test_engine_imports.py -q

Canonical fixes:

SymptomFix
PydanticUserError / define JsonValue on ModelRequest-like modelsKeep JsonValue as PEP 695 type JsonValue = ... in core/types.py (not plain TypeAlias with quoted forward refs)
NameError for RedisHuey, SqliteHuey, etc. at importAdd from __future__ import annotations to the module, or import the symbol at runtime
Shield/Router DENIED / no token with valid client metadataNormalize gRPC metadata with any iterable of (key, value) pairs — test with tuple, grpc.aio.Metadata, and list

Regression tests (do not weaken):

Test locationWhat it pins
packages/core/tests/test_security.py → TestMetadataNormalization_metadata_as_dict for list, tuple, grpc.aio.Metadata
packages/core/tests/test_contract_boundaries.pyJsonValue is TypeAliasType; synthetic cross-module Pydantic probe; router ModelRequest
services/worker/tests/test_engine_imports.pyEngine modules import without NameError
extensions/commerce/tests/test_orm_contracts.pyTier B: all 9 pyright guard modules — ORM JSON, views, admin forms
extensions/commerce/tests/test_django_imports.pyTier A: guard modules import after django.setup
tests/test_commerce_contract_boundaries.pyL2/L3 JSON guards without Django (TypedDict samples, static bypass)

When adding interceptor or auth tests, never pass metadata only as list — parametrize list / tuple / grpc.aio.Metadata (see _METADATA_KINDS in test_security.py).


9. Verification Commands🔗

Run before marking typing/boundary work complete:

# Strict typing (CI: build-contextcore)
uv run basedpyright packages/core/src --warnings

# Lint
uv run ruff check packages/core/src packages/core/tests

# Core tests
uv run pytest packages/core/tests -v --tb=short

# Runtime regression guards (§8.1) — required after typing/security refactors
uv run pytest packages/core/tests/test_contract_boundaries.py packages/core/tests/test_security.py -q
uv run --package contextunity-worker pytest services/worker/tests/test_engine_imports.py -q
uv run pytest tests/test_commerce_contract_boundaries.py -q
cd extensions/commerce && uv run pytest tests/test_django_imports.py tests/test_orm_contracts.py -q

# Architecture invariants (JSON boundary, protos, getenv, etc.)
uv run pytest tests/test_architecture_conformance.py tests/contracts/test_architecture_*.py -v

Pre-commit runs basedpyright --level error repo-wide; CI core job uses --warnings.


10. Agent Checklist (Quick)🔗

When touching types or contracts:

  1. Read this document and the owning package/service AGENTS.md
  2. Pick the lowest layer that fits; narrow upward with guards/models
  3. For bare object reads (graph state, ORM, getattr) → contextunity.core.narrowing (§4.5); for L3 payload keys → sdk.payload.get_*
  4. Use canonical imports — no local alias duplicates or service re-exports
  5. Declare ContextUnitPayload / JsonDict at every call site
  6. Coerce once at registration/ingress choke points; store L4 (RegisteredProjectConfig); no cast/Any/Mapping read-site coercion (§8)
  7. Run verification commands (§9), including §8.1 runtime guards when applicable
  8. If a public API changes, update its owning contract and the affected documentation; verify the published call path against live source.
  9. After security/interceptor changes: metadata tests must cover tuple, grpc.aio.Metadata, and list