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
- 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)🔗
| Layer | Name | Canonical type | Produced by | Consumed by |
|---|---|---|---|---|
| L0 | Bytes / text | str, bytes | network, disk | parsing.py only |
| L1 | Wire tree | WireValue (object) | json_loads, yaml_load, tomllib via TypeAdapter | L2 guards, Pydantic WireValue fields |
| L2 | JSON tree | JsonValue (PEP 695 type alias), JsonDict | is_json_value, is_json_dict | config load, manifest load, discovery JSON, Pydantic fields via StructDataValue |
| L3 | Open gRPC map | ContextUnitPayload | SDK clients, service handlers (pre-sanitize) | ContextUnit, _call_unary, protobuf Struct |
| L4 | Domain model | Pydantic / TypedDict | model_validate, bundle generators | business 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_attrSDK 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 alias | Canonical source | Use when |
|---|---|---|
ToolPayload, ToolResult | ContextUnitPayload | bootstrap, federated tools |
StructData, StructDataValue | JsonDict, JsonValue | router/brain integration |
WorkerBindings | WorkerBindingsBundle | manifest → 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 redefinition3. 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_loadWhy WireValue = object and TypeAdapter?🔗
- Pyright goal: keep stdlib/PyYAML
Anyout 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 viais_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:
| Boundary | Guard | On failure |
|---|---|---|
load_config_file | is_json_dict | ConfigurationError |
load_manifest | is_json_dict | return None / error path |
factory._deep_merge | is_json_value per key | skip non-JSON overlay keys |
4.5 Value-Level Narrowing (contextunity.core.narrowing)🔗
Three complementary tools — pick by data shape and contract strictness:
| Situation | Module | Role |
|---|---|---|
| Must reject non-JSON at a hard boundary | contextunity.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 key | contextunity.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:
| Source | Typical helpers |
|---|---|
dict.get, graph / LangGraph dicts | as_str, as_json_dict, as_str_list |
| SQLite / Postgres row cells, driver tuples | as_str, as_int, as_float, tuple_item_at |
getattr on a third-party object | object_attr then as_* |
| ORM / pandas / DuckDB result rows | as_json_dict_list (or a local one-off helper in the sole consumer) |
| Optional string field inside a loose dict | optional_str_field |
| Packing Python lists back into L2 JSON trees | str_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🔗
| Need | Use instead |
|---|---|
| SDK client mapping a gRPC response field | get_str, get_json_dict, … from sdk.payload |
| Config / manifest load — bad file must fail | is_json_dict → ConfigurationError |
| Fixed key set at ingress | L4 TypedDict + one coerce (model_validate, dedicated coerce fn) |
| Pydantic domain model | model_validate |
| Must distinguish absent vs empty scalar on wire | get_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-localnarrow.pyre-exports. - No duplicate helpers — prefer one core
as_*over repeated inlineisinstanceblocks (same rule as no inlinecast). - Domain-only one-offs — e.g. DuckDB result-row parsing used in a single handler — keep a private
_helperin that module, built onas_json_dict_list. - Match strictness to contract — using
as_json_dictwhere the contract says “invalid shape is a client error” is a semantic bug; useis_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 contract | Getter | Returns |
|---|---|---|
ContextUnitPayload (open wire sub-map) | get_dict, get_dict_list | L3 — no L2 recursion |
JsonDict / list[JsonDict] in TypedDict | get_json_dict, get_json_dict_list | L2 — is_json_dict per element |
| Scalar | get_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 wireGetter 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 runtimeNo 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:
| Helper | Module | Source |
|---|---|---|
_class_namespace_members | sdk/toolkit.py | type.__dict__ |
_record_fields | logging.py | vars on LogRecord |
_metadata_as_dict | security/interceptors.py | gRPC 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 contractStructSafe (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| Need | Import from |
|---|---|
| Config / manifest dict | contextunity.core.types.JsonDict, ConfigMapping |
| gRPC client payload | ContextUnitPayload |
| Tool bootstrap payload | contextunity.core.sdk.types.ToolPayload |
| Typed RPC responses | contextunity.core.sdk.responses.* (TypedDict) |
| Parse untrusted file | contextunity.core.parsing |
Bare object → scalar / JSON (best-effort) | contextunity.core.narrowing (§4.5) |
| ContextUnit payload key | contextunity.core.sdk.payload.get_* (§5) |
| Exceptions | contextunity.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:
| Approach | Why it failed |
|---|---|
Vendored typeshed-fallback/stdlib/json/ | Broke stdlib discovery |
Hand-written typings/yaml/__init__.pyi | Fragile, wrong stubPath |
UnaryContextUnitRpc custom Protocol | Incompatible with grpc stub types |
# type: ignore, --level warning downgrade | Hides real regressions |
cast, Any | Bypasses honest contracts |
TypeAdapter with JsonValue at L1 | RecursionError / over-validation at wrong layer |
WorkerBindingsBundle with JsonValue fields | Pydantic RecursionError |
Shallow isinstance as is_json_dict | Accepts YAML dates at runtime |
Typing only _call_unary without call sites | Pyright green, semantics unchanged |
get_dict for TypedDict JsonDict fields | Invariant lie — use get_json_dict / get_json_dict_list |
Closed result TypedDict in core | Router sends open graph state — use StreamPayload + discriminant guards |
| Domain-specific settings in a shared transformer API | Keep service-owned settings in the owning service; the shared transformer boundary accepts JSON configuration |
| Extra type alias for transformer params | BaseTransformer.params is the open bag; JsonConfigurableTransformer.configure is the L2 seam |
Plain recursive TypeAlias for JsonValue in Pydantic consumer fields | Cross-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 annotations | NameError: name 'RedisHuey' is not defined at import (worker engines) when from __future__ import annotations is missing |
is_object_list for gRPC invocation_metadata | Real metadata is tuple / grpc.aio.Metadata, not list → empty dict → every RPC denied as no token |
Mapping[str, object] + coerce at every read | Masks weak contracts; readers should use L4 typed store (RegisteredProjectConfig) after one choke-point coerce |
dict[str, object] for a known field set | Implicit 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 boundaries | Bypasses guards; use TypeGuard, model_validate, contextunity.core.narrowing, or explicit isinstance |
Service-local narrow.py re-exporting core helpers | Drift and duplicate import paths — import contextunity.core.narrowing directly (§4.5) |
as_json_dict where invalid shape must fail | Defaults hide errors — use is_json_dict + raise at hard boundaries |
JsonMetadata Protocol vs SDK JsonDict on Brain | Protocol parameter types must match SDK (JsonDict), not a wider local alias |
GrpcServicerContext requiring get_trailing_metadata | Neither 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)🔗
| Operation | Meaning | Where allowed |
|---|---|---|
| Coerce | Best-effort normalize unknown wire → typed shape at a boundary | Only at true choke points: e.g. registration_projection.py (registered_project_config_from_bundle), coerce_struct_data for foreign SDK values |
| Validate | model_validate, is_json_dict — reject or fail on bad shape | Config/manifest load, gRPC ingress before L4 |
| Typed store (L4) | After validate/coerce once, all readers use the model | e.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):
| Type | Layer | Role |
|---|---|---|
ContextUnitPayload | L3 | Open gRPC map on RegisterManifest / execution requests |
RouterRegistrationBundle / ProjectManifest | L4 compile-time | Pydantic from manifest YAML |
RegisteredProjectConfig | L4 runtime store | Post-registration projection; nodes, graph, tools for execution |
GraphRunConfigInput | L4 execution ingress | RunnableConfig subset from ExecuteAgent/ExecuteNode; coerce via coerce_graph_run_config_input on payload |
Forbidden / discouraged at service boundaries🔗
- No
cast— useTypeGuard,model_validate,contextunity.core.narrowing, or explicitisinstance+ narrowing (§4.5). - No
# type: ignoreor pyright rule downgrades. - No
Any(includingreportAnyleakage from untyped third-party returns — narrow at the boundary). Mapping[...]/Callable[...]— only when a stdlib or third-party API requires it; prefer concretedict,JsonDict,ContextUnitPayload,RegisteredProjectConfig, or aProtocolwith 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 L4TypedDict+ one coerce at ingress; business functions take the typed alias, notdict[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.
| Situation | Use |
|---|---|
| Graph registry / manifest registration | RunnableGraphFactory with build() -> RunnableGraph | StateGraph — see registry.py, resolve_graph, ResolvedGraph in execution/types.py |
| LangGraph node executors | NodeFunc (__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 thunk | Callable[[], 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 -qCanonical fixes:
| Symptom | Fix |
|---|---|
PydanticUserError / define JsonValue on ModelRequest-like models | Keep JsonValue as PEP 695 type JsonValue = ... in core/types.py (not plain TypeAlias with quoted forward refs) |
NameError for RedisHuey, SqliteHuey, etc. at import | Add from __future__ import annotations to the module, or import the symbol at runtime |
Shield/Router DENIED / no token with valid client metadata | Normalize gRPC metadata with any iterable of (key, value) pairs — test with tuple, grpc.aio.Metadata, and list |
Regression tests (do not weaken):
| Test location | What it pins |
|---|---|
packages/core/tests/test_security.py → TestMetadataNormalization | _metadata_as_dict for list, tuple, grpc.aio.Metadata |
packages/core/tests/test_contract_boundaries.py | JsonValue is TypeAliasType; synthetic cross-module Pydantic probe; router ModelRequest |
services/worker/tests/test_engine_imports.py | Engine modules import without NameError |
extensions/commerce/tests/test_orm_contracts.py | Tier B: all 9 pyright guard modules — ORM JSON, views, admin forms |
extensions/commerce/tests/test_django_imports.py | Tier A: guard modules import after django.setup |
tests/test_commerce_contract_boundaries.py | L2/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 -vPre-commit runs basedpyright --level error repo-wide; CI core job uses --warnings.
10. Agent Checklist (Quick)🔗
When touching types or contracts:
- Read this document and the owning package/service
AGENTS.md - Pick the lowest layer that fits; narrow upward with guards/models
- For bare
objectreads (graph state, ORM, getattr) →contextunity.core.narrowing(§4.5); for L3 payload keys →sdk.payload.get_* - Use canonical imports — no local alias duplicates or service re-exports
- Declare
ContextUnitPayload/JsonDictat every call site - Coerce once at registration/ingress choke points; store L4 (
RegisteredProjectConfig); nocast/Any/Mappingread-site coercion (§8) - Run verification commands (§9), including §8.1 runtime guards when applicable
- If a public API changes, update its owning contract and the affected documentation; verify the published call path against live source.
- After security/interceptor changes: metadata tests must cover
tuple,grpc.aio.Metadata, andlist