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 · Examples · Repository state
The same building, held two ways. As the verified C# that KIR emits for a single Revit version,
the 60-storey tower from examples/tower_numpy.py 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 re-measured 2026-08-31 by running the example in this repo — the KIR side has not moved
since 2026-07-28, the emitted C# has grown; 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. 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()))"
python examples/tower_numpy.py
The python -c line prints 82 82 — one generated builder per registered op. The example after it
builds a 60-storey twisted tower and compiles it for every supported Revit version, offline:
100 строк питона → 6 опов написано → 840 после экспансии → 780 элементов (программ KIR: 3)
этажей 60, талия 30%, закрутка 120°
ломаная против синуса: 217 мм по радиусу
компиляция: 6/6 версий ['2021', '2022', '2023', '2024', '2025', '2026']
(Every command in this section was run verbatim on 2026-08-31 in a venv created from scratch:
pip install . pulled four direct and fifteen total dependencies, exit 0, nothing outside the venv
touched. The shipped examples currently print in Russian.)
Writing into a live model additionally needs a Revit 2021–2026 installation, its API reference assemblies, the .NET Roslyn compile service and a separately running bridge — none of which are part of this repository.
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, rebuild verification — lives in the language contracts under kir/specs/ (SPEC_V1.md, the decompile
spec) and the design specs under docs/laws/.
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/instruments/— instruments that run offline, without Revit:compile_gate_offline,bounds_audit,unwired_census,scope_audit,snapshot_janitor,canon_state, and others;kir/course/,kir/skill.py— the authoring course and the skill an LLM is handed;kir/specs/— the language contracts:SPEC_V1.md, the decompile spec;kir/bridge/— the client side of the bridge protocol, plus a mock server for offline runs;kir/tests/andkir/*/tests/— 621 test files: unit, contract, golden and property tests;examples/— small SDK programs that compile offline, before any Revit is connected;docs/laws/— the design specs behind the honesty, merkle and verified layers.
The Revit bridge itself, the .NET Roslyn compile service, the product's admin routes, runtime data, credentials and logs are intentionally not part of this repository.
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, 1105378)
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 shipped example goes further. In tower_numpy.py, numpy computes a sinusoidal waist and twist
and KIR repeats the storey — 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.
Both demonstrations — the numpy tower and a shapely-cut curved floor plate — ship in examples/ with their measured outputs.
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
(/admin/kir/rebuild, /admin/kir/decompile) are part of the private product and are not in this
open-core slice, but their offline half ships and runs right here, no bridge and no Revit needed:
pytest kir/decompile/tests/test_merkle.py kir/decompile/tests/test_rebuild.py \
kir/decompile/tests/test_journal.py kir/decompile/tests/test_merge3.py
98 passed, 19 subtests passed -- run 2026-08-31, Python 3.12, this repository, no Revit
pytest is not pulled in by pip install . — it arrives with the dev extra; see
Repository state for the one line that installs it.
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) |
| Source size | 284 production modules, 634 test files | 2026-09-01, python3.12 tools/readme_numbers.py --check |
| Python syntax check | 947 files parsed, 0 errors | 2026-09-01, ast.parse over every *.py outside build/ |
| Install into a clean venv | PASS — exit 0, 15 packages, no sudo |
2026-08-31, pip install . in a fresh python3.12 -m venv |
| Offline six-version compile of the shipped example | PASS — 3 programs, 840 ops, 780 elements, 6/6 versions | 2026-08-31, python examples/tower_numpy.py |
| Version-control half, offline | 98 passed, 19 subtests, under 10 s | 2026-08-31, pytest kir/decompile/tests/test_{merkle,rebuild,journal,merge3}.py |
| 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. Each invariant is backed by a test or verification run; a violation stops the build or run.
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 compiler, the reverse pipeline, the instruments, the authoring course and the whole test suite live in this repository and run without Revit. To work against the tree instead of an installed copy:
python3.12 -m venv .venv && . .venv/bin/activate
pip install -e '.[dev]'
PYTHONPATH="$PWD" python -m pytest \
kir/decompile/tests/test_merkle.py kir/decompile/tests/test_rebuild.py \
kir/decompile/tests/test_journal.py kir/decompile/tests/test_merge3.py -q
Three traps worth naming, all bought by measurement rather than reasoning:
-
Name the four files; do not point pytest at the directory.
kir/decompile/testscollects 171 files, and one of them allocates about 5 GB and takes the rest of the run down with it. The four named above are the ones the number in the table refers to. -
PYTHONPATHmust be absolute. A barePYTHONPATH=.is shadowed by any straykir.pybeside you, and the refusal then blames the wrong module. -
Four direct dependencies, and
httpxis one of them. It looks like bridge-only machinery, butcompile_client.pysits in the package import chain; dropping it into an extra madeimport kirfail in a clean venv. The dependency list is settled by a run, not by an argument.
Live execution additionally needs a Revit 2021–2026 installation, its API reference assemblies, the .NET Roslyn compile service and a separately running bridge.
Machine-specific paths: measured, not asserted. An AST sweep over every string literal outside docstrings finds 0 absolute machine paths in the 274 production modules. The test suite is a different matter and is named rather than glossed: 17 test files pin absolute paths of the machine they were measured on, and the tests ship inside the built package. No credentials, keys or device identifiers were found anywhere in the wheel.
For auditors
Beyond the compiler core in kir/:
- Language contracts:
kir/specs/—SPEC_V1.md,KIR_DECOMPILE_SPEC.md - Laws of honesty / verified / merkle:
docs/laws/ - LLM authoring skill + sandbox course:
kir/skill.py,kir/course/ - CI evidence & secret boundary:
.github/workflows/kir-evidence.yml,kir-security.yml - Offline instruments, runnable with no Revit:
kir/instruments/— each one is expected to name what it could not read rather than report a zero it never measured
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.3.0.tar.gz.
File metadata
- Download URL: kir_building-0.3.0.tar.gz
- Upload date:
- Size: 4.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 |
f61f919411457790a494eeedb2b295c6047bb9ab9559d0ea0498faa27339fcfe
|
|
| MD5 |
1e5e08b1be45f18a728299c4698d7256
|
|
| BLAKE2b-256 |
1373c18cec878858027fbab724b4452768f6b0c2baa505ca55d17ccb7ef73d73
|
File details
Details for the file kir_building-0.3.0-py3-none-any.whl.
File metadata
- Download URL: kir_building-0.3.0-py3-none-any.whl
- Upload date:
- Size: 5.3 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 |
2c2385a63e02a42ef8b46aac5103af2c345d48cf9b1d148e8609992ceab7cfaf
|
|
| MD5 |
a3a45b093a2d89ad788a1d43bb42df69
|
|
| BLAKE2b-256 |
3d8c46d07732375932d391268c7fa802fb0f97d5fd7a1c08caaddc6af085a251
|