KIR
A building is a program.
Typed, verifiable IR for Autodesk Revit — Python brains, verified hands.
Install · Why · The idea · Code · History · Measured results · Invariants · KIR chapter · Repository state
Public source snapshot. This repository contains the standalone KIR compiler, authoring surface and portable Revit connector. Historical fixture/test corpora, long-form example programs, operational instrumentation and private hosted integration are deliberately not bundled. Measurements marked historical remain context, not a claim that they can be reproduced from this source cut alone.
The same building, held two ways. As the verified C# that KIR emits for a single Revit version, the documented 60-storey tower weighs 3 902 141 characters — roughly 1M tokens, beyond any model's context window. As the typed KIR program a model actually edits, it weighs 15 508 characters — roughly 4k tokens, 252× less. That is the difference between a model that can re-plan a floor or bend a facade with every change verified, and a model that cannot even read the building it is asked to change. (Sizes were measured 2026-08-31; the render is a visual companion, not the measurement.)
Install and run it
KIR is a Python package. Nothing below needs Revit, a licence, a service to stand up, or sudo —
only Python 3.12 or newer. Install the released package:
python3.12 -m pip install kir-building
To install the current source directly from GitHub instead:
python3.12 -m pip install "git+https://github.com/5vbkgsghhh-hash/kir.git"
Or, from a clone of this repository:
python3.12 -m venv .venv && . .venv/bin/activate
pip install .
python -c "from kir import spec, sdk; print(len(spec.OPS), len(sdk.builders()))"
The python -c line prints 82 82 — one generated builder per registered op. The historical
60-storey twisted tower run compiled the program for every supported Revit version, offline:
100 строк питона → 6 опов написано → 840 после экспансии → 780 элементов (программ KIR: 3)
этажей 60, талия 30%, закрутка 120°
ломаная против синуса: 217 мм по радиусу
компиляция: 6/6 версий ['2021', '2022', '2023', '2024', '2025', '2026']
pip install . and a wheel build were verified in isolated Python 3.12 environments. The full
tower program and fixture corpus are intentionally outside this public source cut.
To execute in a live model, build the included local connector on Windows with Revit 2021–2026:
cd connector\revit
.\scripts\build.ps1 -RevitVersion 2026
.\scripts\install.ps1 -RevitVersion 2026
The connector is disabled by default and must be enabled in Revit by the local user. It builds against that installation's Autodesk API assemblies; Autodesk binaries are not redistributed.
Why
Language models write code well. They do not write buildings well, and the reason is structural rather than a matter of training scale. A building does not fit in a context window — one of the models we measure against holds 90 758 elements. The work is stateful: a wall must exist before a door can be hosted in it, and that state lives inside an application, not in a file you can diff. It is re-entrant, because the same instruction issued twice must not produce two doors. And it is versioned six ways: the same intent compiles differently against Revit 2021 and Revit 2026.
So the practice today is to have the model write Revit C# directly, and the arithmetic of that
practice is available to us. Across 85 374 production compile errors logged over seven weeks,
two codes account for 48.4% — CS1061 (32.3%) and CS0117 (16.1%) — and both are the same
failure: a member of the Revit API that does not exist. Another ~10% (CS0104/CS0012) are
namespace and assembly-reference problems. Roughly 60% of all production compile errors are spent
fighting the surface of an API, not describing a building.
KIR is an attempt to build it: the model concentrates on 3D, geometry and composition; units, transactions, API versions, hosts, witnesses and rollbacks belong to a compiler.
The idea in one picture
flowchart TB
subgraph FWD["FORWARD — intent becomes a building"]
direction LR
SDK["Python SDK<br/>numpy · shapely · the model"]
PROG["Typed program<br/>KIR JSON, ops + refs"]
REG["Registry<br/>one source of truth:<br/>schema · grammar · docs · emitters"]
GRND["ground<br/>symbolic selectors to ElementIds"]
PLAN["typecheck + plan<br/>mm only · DAG · txn partitions"]
EMIT["emit<br/>per-version C#"]
GATE["Roslyn gate<br/>2021–2026 · 1056 checks PASS"]
RUN["live Revit<br/>one TransactionGroup"]
SDK --> PROG --> REG --> GRND --> PLAN --> EMIT --> GATE --> RUN
end
RUN --> WIT["witness<br/>read the RESULT back, not the call"]
WIT --> OUT{"exactly two<br/>typed outcomes"}
OUT -->|ok| OKN["geometry_ok · semantic_ok · topology_ok"]
OUT -->|refused| REFN["diagnostics + candidates + route<br/>KIR-G/T/L/E/C/X/W codes"]
REFN -.->|"IR-level repair, max 3 rounds"| PROG
subgraph REV["REVERSE — a building becomes a program"]
direction LR
DOC["live model"]
L0["extract to L0<br/>48 categories · full-model census"]
L1["lift to typed ops<br/>or a typed ATOM with a reason"]
FOLD["fold to canon<br/>template-canon/4 · fidelity-canon/1"]
MAT["materialize<br/>chunked programs, host-atomic"]
DOC --> L0 --> L1 --> FOLD --> MAT
end
RUN -.-> DOC
MAT -.->|"rebuild · edit · diff"| PROG
Two properties matter more than the boxes.
Every call ends in exactly one of two typed outcomes — an ok carrying a read-back proof, or a
machine-readable refused with candidates and a route to a fallback path. A silently-wrong answer
is the single forbidden state; ok:true wrapping a nested error is a permanent regression case with
its own test.
The IR runs in both directions. Anything the lifter cannot express becomes a typed atom with a reason code, never a silent drop. That reverse direction is what turns "we can build" into "we can edit what already exists".
A stage-by-stage account of both pipelines — the registry as one source of truth, isolation modes, the census, fold and rebuild verification — lives in the public KIR, Building Graph, Runtime and Clash chapters.
Repository layout
Everything here is the compiler and its instruments; the product that hosts them is a separate repository. Revit is one target of several, and the package is agnostic about which one it emits for.
kir/— the forward compiler: registry, typecheck, plan, per-version emitters, typed diagnostics, witness/acceptance machinery;kir/decompile/— the reverse pipeline: extract, lift, fold, materialize, and the version-control half (merkle,journal,rebuild,merge3);kir/checker/,kir/clash/— the judge and the clash pipeline;kir/course/,kir/skill.py— the authoring surface an LLM can be handed;kir/bridge/— compatibility HTTP client plus the local named-pipe connector client and C# envelope;connector/revit/— source-only Revit add-in, Roslyn compiler host, protocol, build and install scripts;docs/— public chapters for the language, Building Graph, clash engine, runtime and bridge.
The repository intentionally excludes remote/hosted product services, credentials, logs, long-form examples, verification corpora and internal design notes. The included connector is local-only; it has no network listener or production control plane.
Show me code
A real program, printed verbatim from the SDK:
{
"ir_version": "1.0",
"intent": "one bay: wall + door + window",
"ops": [
{"op": "create_wall", "id": "wall1",
"p0_mm": [0, 0], "p1_mm": [6000, 0],
"level": {"by": "name", "value": "Level 1"}, "height_mm": 3300},
{"op": "create_door", "id": "door1",
"host": {"by": "ref", "value": "wall1"},
"offset_mm": 1200, "sill_mm": -100,
"symbol": {"by": "name", "value": "0915 x 2134mm"},
"mirrored": false, "hand_flipped": false, "facing_flipped": false}
]
}
Note what is not expressible. A door has no xyz: it is host + offset_mm along the host +
sill_mm. "A window floating in the air" is not a case we validate — it is a sentence the language
cannot form. Every length is millimetres; feet do not exist in the IR.
The Python surface is generated, not written: 82 builders are born from the registry at import
time, one per registry op (len(sdk.builders()) == len(spec.OPS), re-checked 2026-08-31), so a
signature cannot drift from the spec. The SDK adds no semantics of its own — it cannot express
anything the registry lacks, and it cannot hide a refusal.
import numpy as np
from kir import sdk
p = sdk.program(intent="tower with a waist")
with p.stack(levels=20, h_mm=3600,
transform=sdk.transform(scale_xy_top=[0.8, 0.8],
twist_deg_total=24)) as floor:
for a in np.linspace(0, 2 * np.pi, 12, endpoint=False):
floor.add(sdk.create_column(xy=[20000 * np.cos(a), 20000 * np.sin(a)],
level=sdk.BY_MACRO, symbol="К 300x300"))
p.stats() # {'ops_written': 1, 'ops_expanded': 260, 'elements': 240}
snap = {"column_symbols_structural": [{"id": 6011, "name": "К 300x300"}]}
out = p.compile(version="2023", snapshot=snap)
out.ok, len(out.csharp) # (True, 1105222)
The snapshot is what a live Revit document would answer; offline you can hand the compiler the
one pool this program grounds against. Get the name wrong and the refusal names the pool it
looked in — KIR-G101 column_symbols_structural: «К 300x300» не найден — rather than failing
somewhere later.
The reference tower program goes further. Numpy computes a sinusoidal waist and twist and KIR repeats the storey — recorded run on 2026-07-28:
100 lines of Python -> 6 authored ops -> 840 after expansion -> 780 elements (3 KIR programs)
60 storeys, 30% waist, 120 deg total twist
piecewise vs. true sine: 217 mm along the radius
compilation: 6/6 versions ['2021','2022','2023','2024','2025','2026']
That third line is the point. stack.transform interpolates linearly; the requested curve is a
sine. Saying "sine" and building a polyline without naming the divergence would be a silently
wrong answer, so the example prints the error in millimetres.
The full tower and curved-floor programs, plus their fixture corpus, intentionally remain outside this public source cut; the compiler and SDK surface they exercise are present here.
What happens to one op
sequenceDiagram
autonumber
participant M as Model — the LLM
participant K as KIR compiler
participant R as Revit — live document
M->>K: create_wall — p0, p1, level by name, height 3300 mm
K->>K: parse · typecheck · mm to feet · plan the DAG
K->>R: snapshot query — resolve selectors
R-->>K: level id, wall type pool
alt selector missing or ambiguous
K-->>M: refused KIR-G102 + candidates + route
else grounded
K->>K: emit C# for THIS Revit version
K->>R: TransactionGroup — Wall.Create, op_id stamped
R-->>K: new element id
K->>R: read the element BACK
R-->>K: LocationCurve, height param, level id
alt postconditions hold
K-->>M: ok + witness — geometry_ok, semantic_ok, topology_ok
else violated
K->>R: RollBack
K-->>M: refused KIR-X004 + which axis failed
end
end
That stamp is why a retry is idempotent: op ids are written into the model inside the same transaction, so re-running a program skips what is already stamped, and resume-from-op-K is simply "skip what carries a stamp".
A building has a history
A single write is not the whole story. A real project gets read, edited, and read again dozens of times, and for most of this project's life nothing here remembered that revision N and revision N+1 were the same building — every rebuild started from zero. Four modules close that gap, and together they are exactly a version-control system, mapped onto concepts a reader already knows:
| git concept | KIR module | what it actually is |
|---|---|---|
| content-addressed object store | merkle |
a Merkle DAG over the folded building tree — a repeated floor is one node, not N |
| a history you can replay | journal |
append-only per-building revision log; replaying it reconstructs any past revision exactly |
| applying a diff | rebuild |
materializes only the delta between two revisions instead of the whole building |
| three-way merge | merge3 |
base / current document / target revision, with a real conflicting verdict — never a silent overwrite |
It does not replace the addressed building graph shown above. The merged state is deliberately
identity-free — a canonical op carries no ElementId — which is exactly what makes it mergeable;
a program is still materialized from one concrete revision, never from the merge itself. The
routes that drive these four live against an open Revit document are part of a separate host
product. The public source retains the compiler implementation; its fixture-based verification
corpus is intentionally not bundled here.
Measured results
Everything below is derived from an instrument on the date shown, not from memory.
Every row below was produced by running the command in the right-hand column, on commit
3211555. Rows marked
historical are older runs whose instrument or corpus is not shipped here; they carry their date
and cannot be re-run from this repository alone.
| Fact | Value | Date / how |
|---|---|---|
| Ops in the registry | 82 — 77 writing, 5 query | 2026-08-31, len(spec.OPS) |
| Generated SDK builders | 82 — one per op | 2026-08-31, len(sdk.builders()) == len(spec.OPS) |
| Public source size | 281 Python/C# source files | 2026-09-01, published source tree including the local Revit connector |
| Python syntax check | 260 Python files parsed, 0 errors | 2026-09-01, ast.parse over the public package |
| Wheel build | PASS | 2026-09-01, isolated PEP 517 build |
| Offline six-version tower compile | PASS — 3 programs, 840 ops, 780 elements, 6/6 versions | historical run; fixture program is not bundled |
| Version-control half, offline | 98 passed, 19 subtests, under 10 s | historical run; test corpus is not bundled |
| Emitted C# for the 60-storey tower, one version | 3 902 141 characters against 15 508 for the KIR program — 252× | 2026-08-31, Revit 2023 |
| Historical live baseline | 31 of 31 writing ops had a witnessed run — of the 31 that existed then | 2026-07-28 local telemetry; telemetry is not shipped here |
| Historical six-version compile gate | 1 056 Roslyn compilations, PASS | 2026-07-28 local gate run |
| Historical reverse-direction coverage | 48 categories; 92.83% on the 90 758-element R2026 model | 2026-07-27/28 local runs |
| Historical production compile errors structurally inexpressible in KIR | ≈60% of 85 374 over seven weeks | local report; completeness caveats apply |
Checked invariants
The reverse pipeline enforces five checked invariants: full document coverage, a reason recorded for every element it cannot express, witnesses that match the data actually read, contamination marking for partial reads, and neutral identifiers. The public source preserves their contracts and named refusals; the full fixture corpus remains private.
flowchart LR
subgraph LAWS["§18 — five invariants"]
direction TB
L1["1 · CENSUS<br/>lifted + atoms + not_read<br/>= the whole document"]
L2["2 · RECEIPT<br/>every cut emits<br/>element_id + typed_reason"]
L3["3 · WITNESS AXIS<br/>sign only the axis<br/>you actually read"]
L4["4 · CONTAMINATION<br/>a partial read marks<br/>everything derived from it"]
L5["5 · NEUTRALITY<br/>no device ids, install paths,<br/>or locale-only keys"]
end
subgraph CORE["what they enclose"]
direction TB
C1["compile"] --> C2["execute in Revit"] --> C3["read back"] --> C4["publish a number"]
end
L1 -->|"run-fatal identity check + CI fixture"| CORE
L2 -->|"rows + failures contract on every side stage"| CORE
L3 -->|"certificate lint: kind to legal reader"| CORE
L4 -->|"header round-trip test + A5 gate on partial data"| CORE
L5 -->|"CI pattern lint"| CORE
CORE --> R1["built, with a witness"]
CORE --> R2["typed refusal, with a route"]
CORE -.->|forbidden by construction| R3["silently wrong"]
Full account: Five Conservation Laws of Honesty for an AI Agent in CAD.
Read more
- A Building Is a Program — the long-form technical case: what the IR expresses, why it runs in both directions, and the measured number behind each claim.
- Five Conservation Laws of Honesty for an AI Agent in CAD — the five laws, the catch behind each, and how each one is mechanically enforced.
- A Day of Measured Revit API Traps — fourteen Revit API behaviours as symptom, wrong hypothesis, measurement, rule. Useful even if you never touch KIR.
- One Day Inside an AI-led Compiler Team — a first-person account of one working day on this project.
Repository state
The public repository contains the compiler, reverse pipeline, SDK, clash/checker layers, authoring course and a source-only local Revit connector. To work against the tree instead of an installed copy:
python3.12 -m venv .venv && . .venv/bin/activate
pip install -e .
python -c "from kir import spec, sdk; print(len(spec.OPS), len(sdk.builders()))"
For live execution, build and install connector/revit/ against a local Revit 2021–2026 installation.
After the user enables KIR → Local Connector, Python can use the same source contract:
from kir.bridge import LocalConnectorClient
connector = LocalConnectorClient()
context = connector.context()
# snapshot = connector.ground_snapshot(program, context=context) # for a write program
# output, receipt = connector.compile_and_execute(
# program, snapshot=snapshot, context=context
# )
An execution receipt is deliberately not a semantic success claim. Use KIR's independent readback and witness layer before reporting that a requested BIM effect is confirmed.
No credentials, keys, device identifiers, remote production host, test/golden corpus or production data are included in the published package.
For auditors
Beyond the compiler core in kir/:
- Language and compiler: KIR
- Reverse pipeline / Building Graph: Building Graph
- Clash semantics: Clash
- Runtime, witnesses and idempotency: Runtime
- Host adapter boundary: Bridge
- LLM authoring surface:
kir/skill.py
Apache License 2.0 — see LICENSE.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file kir_building-0.2.0.tar.gz.
File metadata
- Download URL: kir_building-0.2.0.tar.gz
- Upload date:
- Size: 3.8 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.12.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7cfdb34d85d8b9f39554c027c94a5cf33ef94a83175cc649e3c3f21404d56b07
|
|
| MD5 |
4441c367b0220114228f122f811f8af9
|
|
| BLAKE2b-256 |
a4d21393b9f120fee9f55c7ba61e909e9075a281c5dba10846621186e73137ca
|
File details
Details for the file kir_building-0.2.0-py3-none-any.whl.
File metadata
- Download URL: kir_building-0.2.0-py3-none-any.whl
- Upload date:
- Size: 4.0 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.12.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cd2ca1c86d8695fd3f9adfed8e9142c2c68a5e1120a003fddc24236ba6b1be02
|
|
| MD5 |
ce97dfed54004a130f8f610c768653ae
|
|
| BLAKE2b-256 |
3d6ac8d176b1b59032090a0dc7f493af9bac03a5aae1bff960e4266bdee868e8
|