On This Page (7)
Why TypeSpec & Contract Architecture
Hardware CAD toolkits rarely stay single-language for long. kicad-monkey parses KiCad S-expressions in Python and Rust, compiles hierarchical schematic graphs and Plotter IR display lists for TypeScript web viewers, emits whole-nanometre fabrication views for Gerber / Excellon / IPC-2581B / Micro-STEP, and hands structured manifests to CI pipelines and AI design-review agents.
Whenever a polyglot toolkit passes ad-hoc JSON dictionaries across those boundaries, silent wire drift sets in almost immediately:
- A Python serializer starts emitting
nullwhere Rust expected an omitted key. - An integer nanometre coordinate crosses
2^53 - 1and silently loses precision inside a JavaScript viewer. - A union discriminator is renamed in one language while a downstream consumer still matches the old string.
- Documentation falls three releases behind the actual payload because nobody wants to audit ten thousand lines of hand-maintained JSON Schema.
Formal wire contracts solve this by putting the shape of the bytes on the wire in one auditable place and treating every language binding as a mechanically verified projection of that shape.
Why TypeSpec?
New and revised wire contracts in kicad-monkey are authored in TypeSpec (.tsp) and compiled to standard JSON Schema Draft 2020-12 (.json), which then drives code generation for Rust, Python, and TypeScript. TypeSpec reads like concise, reviewable type definitions rather than verbose $defs / anyOf / unevaluatedProperties boilerplate, while still emitting standard JSON Schema that any Draft 2020-12 validator can consume with zero TypeSpec toolchain installed.
Wire Shape vs. Adapter Boundary
kicad-monkey draws a sharp line between what crosses the wire and what lives in runtime code:
TypeSpec (.tsp): single source of truth for wire shape
│
▼ @typespec/json-schema (Draft 2020-12, sealed objects, warn-as-error)
Compiled JSON Schema (.json)
├── Rust : kicad-monkey-contracts (strict serde structs, zero schemars)
├── Python : kicad_monkey.contracts.generated (frozen msgspec.Struct)
└── TypeScript: src/ts/kicad_monkey/contracts/generated/ (zero-any strict TS)
│
▼
Handwritten Python, Rust & TypeScript adapters
├── UTF-8 / surrogate framing, duplicate-key rejection, finite-float preflight
├── cross-field semantic invariants & resource budgets
├── out-of-band binary slot transport (source bundles, font payloads)
└── public APIs (KiCadPcb, PcbView, KiCadFabView, kcr / k3 CLIs)- What TypeSpec owns: exact JSON property names, required vs. optional vs. nullable presence, literal contract identity tokens (
schema,type,version,$id), closed object sealing (unevaluatedProperties: {not: {}}), discriminated unions, safe-integer and finite-float ranges, and canonical wire enums. - What handwritten adapters own: raw byte/UTF-8 framing, duplicate-key rejection (
preflight_strict_json), cross-field semantic checks (such as sequential operation indices, operation-count totals, and valid UUIDv7 references), schema version dispatch, and ergonomic query or mutation methods. - What TypeSpec deliberately does NOT model:
- Out-of-band binary buffers: large KiCad source files and OpenType/TrueType font binaries travel alongside manifests by slot index (
SourceBundleManifest,FontBundleManifest) rather than being base64-inlined into JSON envelopes. - Geometry tolerances and numerical kernels: arc-flattening tolerances, boolean offset rules, and stroke-width clamping live in
cad-text-realization,kicad-monkey-fab, andkicad-monkey-core, not in wire schemas. - Config merge precedence and defaults: how CLI flags override project configs or sibling
fab.jsoncfiles is runtime adapter logic, even when the config file shape itself is schema-driven (Field<T>tri-state presence). - Mutable DOMs and stateful caches:
KiCadPcb,KiCadSchematic,PcbView, and.kcr/cacheindexes remain handwritten domain objects designed for lossless editing and fast queries.
- Out-of-band binary buffers: large KiCad source files and OpenType/TrueType font binaries travel alongside manifests by slot index (
The Four Contract Tiers in KiCad Monkey
Not every JSON payload in kicad-monkey and kicad-cruncher comes from the same pipeline. Being explicit about which tier owns a contract avoids confusion when extending or auditing a schema:
| Tier | Source of Truth | Compiled Artifacts | Generated Language Bindings | Scope & Notes |
|---|---|---|---|---|
Tier A — kicad-monkey TypeSpec Core | 8 .tsp modules in src/tsp/kicad_monkey/ (rooted at main.tsp) | 30 Draft 2020-12 JSON Schemas in contracts/generated/schema/*.json | Rust (kicad-monkey-contracts), Python (kicad_monkey.contracts.generated via msgspec), TypeScript (src/ts/kicad_monkey/contracts/generated/) | S-expression scan/build, footprint & symbol library read/edit, Plotter IR (MOD/PCB/SYM/SCH), CompiledSchematicGraph, SourceBundleManifest, FontBundleManifest, ShapingRecord, OutlineVector. |
Tier B — kicad-cruncher Standalone TypeSpec | packages/kicad_cruncher/src/tsp/kicad_cruncher/main.tsp | pcb_svg_config.a0.schema.json | TypeScript (pcb-svg-config.ts) + Rust (kicad-cruncher-cli, projected with Field<T> tri-state presence) | Cruncher-owned pcb.svg.config schema. Intentionally separate from the core Monkey catalog; the Python loader is handwritten. |
Tier C — Vendored Generated Python msgspec Contracts | Shared Wavenumber Data Models / Altium Monkey contract lineage (no local .tsp in cad/kicad_monkey) | 11 embedded Draft 2020-12 schemas in kicad_monkey.fab_view_contracts.generated + urn:dm:schema:geom.a0 in kicad_monkey.geom.generated | Python (msgspec structs & strict codecs) | FabView (kicad_monkey.fab_view.a0), fab_diagnostics.a0, fab_*_options.a0, and analytic 2D geometry (geom.a0). Note: Rust kicad-monkey-fab uses its own handwritten serde model (FabViewData), not these generated Python DTOs. |
| Tier D — Handwritten JSON Schemas & Code-Only Payloads | Handwritten .schema.json files in docs/contracts/ and packages/kicad_cruncher/docs/contracts/, plus code-only JSONC loaders | Standalone JSON Schemas | Handwritten validators / loaders in Python and Rust | kicad_plotter_ir_a0.schema.json, pcb_svg_enrichment_a0.schema.json, schematic_svg_enrichment_a0.schema.json, Cruncher configs (bom_pnp_config.a0.schema.json, pcb_layer_step_config.a0.schema.json, pcb_clean_config.a0.schema.json), design_review_manifest.d0.schema.json (plus a0/b0 predecessors), toon_manifest.a0.schema.json, toon_timings.a0.schema.json, library_extraction_bundle.a0.schema.json, source_relink.a0.schema.json, plus code-only fab.jsonc and vdoc.jsonc. |
Keeping those four tiers distinct matters in practice: Tier A is the full tri-language TypeSpec pipeline; Tier B proves a downstream package can own its own TypeSpec root without modifying kicad-monkey; Tier C gives Python KiCadFabView exact wire parity with sibling Wavenumber CAD libraries without pretending the .tsp source lives in this repo; and Tier D covers legacy or CLI-local payloads that have not needed multi-language codegen.
Benefits for Downstream Consumers
- Python callers: Strict
msgspec.Structmodels (forbid_unknown_fields=True,frozen=True) decode megabyte-scale Plotter IR andFabViewpayloads at C speed while catching unknown keys, wrong numeric bounds, and missing discriminators at the boundary. - Rust integrators:
kicad-monkey-contractsexposes idiomatic,#![forbid(unsafe_code)],serde-only structs and validated newtypes (JavaScriptSafeInteger,NonNegativeFiniteFloat,PositiveU32,StableTextId) with zeroschemarsruntime dependency — suitable for tight CLI binaries and WASM targets. - TypeScript & web viewers: Generated
.tsmodules forbidany, respectexactOptionalPropertyTypes, and guarantee every numeric field fits cleanly inside JavaScript's IEEE-754 safe-integer range (or is explicitly encoded as a canonical decimal string foruint64). - AI agents & CI automation: Every published contract ships as standard JSON Schema Draft 2020-12 with explicit
schema/type/versiondiscriminators, letting automated tools validate review manifests, schematic graphs, and enriched SVGs without importingkicad-monkey.
Revision Scheme & Immutability
Every versioned wire contract uses a <letter><digit> revision token (a0, a1, b0, d0) decoupled from the kicad-monkey / kicad-cruncher package release version:
- Leading letter (
a,b,c,d, …) — major revision. Advances on any breaking change: removing or renaming a field, narrowing a type, changing coordinate units or sign conventions, or restructuring the root layout. - Trailing digit (
0,1,2, …) — minor additive revision within that major family. Existing fields retain their exact type, units, and meaning; new optional fields may be added without breaking existing consumers.
Concrete Example: design_review_manifest (a0 → b0 → d0)
kcr design / k3 design illustrates how the revision scheme works in real life:
kicad_cruncher.design_review_manifest.a0(design_review_manifest.a0.schema.json) shipped the original flat review bundle manifest.kicad_cruncher.design_review_manifest.b0(design_review_manifest.b0.schema.json) restructured the bundle around compiled schematic graphs and per-page drawing companions — a breaking root change, so the major letter moved fromatob.kicad_cruncher.design_review_manifest.d0(design_review_manifest.d0.schema.json) introduced the current D0 bundle layout (review_summary.json,compilation.json,bom.csv,notes.json, schematic SVGs +.layout.json, andpcb/artifacts). (The intermediatec0revision was an internal staging schema never published externally; the manifest versiond0indexes the governed core Design B0 data model and its companion artifacts.)
Immutability rule: Once a revision ID ships, its wire contract is frozen. A breaking change always mints a new major letter rather than silently mutating an existing a0 or d0 schema in place. Consumers should match the contract's schema (or type + version) string explicitly instead of assuming forward compatibility across major letters.
Explore the Contracts Section
- Multi-Language Codegen Pipeline — exact TypeSpec, Python (
msgspec), TypeScript, and Rust (kicad-monkey-codegen/typify) commands, AST transforms, and strict JSON preflight rules. - Complete Contract & Schema Catalog — all 30 TypeSpec core schemas, all 11 FabView schemas +
geom.a0, and every KiCad Cruncher CLI config and output schema, including explicit negative assertions. - Fabrication & Enriched SVG Wire Formats — Gerber RS-274X/X2, Excellon NC Drill, IPC-2581B, Micro-STEP, and enriched PCB/Schematic SVG
data-*attribute conventions. - Rust Workspace &
kicad-monkey-contracts— how the Rust workspace consumes and validates generated contracts with zerounsafecode.