Metadata-Version: 2.4
Name: kir-building
Version: 0.4.0
Summary: KIR — typed, verifiable IR for buildings. A building is a program.
Author: Dima
License: Apache-2.0
Project-URL: Homepage, https://github.com/5vbkgsghhh-hash/kir
Project-URL: Source, https://github.com/5vbkgsghhh-hash/kir
Keywords: revit,bim,compiler,ir,buildings,cad,llm
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Software Development :: Compilers
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: shapely<3.0,>=2.0
Requires-Dist: networkx<4.0,>=3.0
Requires-Dist: pydantic<3.0,>=2.7.0
Requires-Dist: httpx<1.0,>=0.27.0
Provides-Extra: bridge
Requires-Dist: fastapi<1.0,>=0.115.0; extra == "bridge"
Provides-Extra: dev
Requires-Dist: pytest<9.0,>=8.0; extra == "dev"
Requires-Dist: jsonschema<5.0,>=4.0; extra == "dev"
Provides-Extra: mcp
Requires-Dist: mcp<3.0,>=2.1; extra == "mcp"
Dynamic: license-file


<p align="center">
  <img src="assets/logo.png" width="256" alt="KIR building graph logo"/>
</p>

<h1 align="center">KIR</h1>

<p align="center">
  <b>A building is a program.</b><br/>
  Typed, verifiable IR for Autodesk Revit — Python brains, verified hands.
</p>

<p align="center">
  <img alt="License Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-blue">
  <img alt="Revit 2021-2026" src="https://img.shields.io/badge/Revit-2021%E2%80%932026-005386">
  <img alt="Historical compile gate 1056 checks" src="https://img.shields.io/badge/historical%20compile%20gate-1056%20checks-brightgreen">
  <img alt="82 ops registered" src="https://img.shields.io/badge/registry-82%20ops%20(77%20writing)-success">
  <img alt="Python 3.12+" src="https://img.shields.io/badge/python-3.12%2B-blue">
</p>

<p align="center">
  <a href="#install-and-run-it">Install</a> ·
  <a href="#why">Why</a> ·
  <a href="#the-idea-in-one-picture">The idea</a> ·
  <a href="#show-me-code">Code</a> ·
  <a href="#a-building-has-a-history">History</a> ·
  <a href="#measured-not-promised">Measured results</a> ·
  <a href="#the-five-laws">Invariants</a> ·
  <a href="examples/README.md">Examples</a> ·
  <a href="#repository-state">Repository state</a>
</p>

---


<p align="center">
  <img src="assets/tower-side-by-side.png" alt="The same tower twice in Revit" width="720"/>
</p>

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`](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:

```bash
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:

```text
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.

## Give it to a model: the MCP server

KIR ships an [MCP](https://modelcontextprotocol.io) server, so any MCP host — Claude Desktop,
Claude Code, an IDE — can author, compile and inspect buildings through it. It speaks protocol
revision **2026-07-28** and needs no Revit, no licence and no service:

```bash
pip install "kir-building[mcp]"
python -m kir.mcp            # stdio; --http --port 8765 for Streamable HTTP
```

Register it with Claude Code in one line:

```bash
claude mcp add kir -- python -m kir.mcp
```

Five tools, all offline — nothing is sent anywhere and nothing is written to any model:

| tool | what it does |
|---|---|
| `kir_author` | Python that builds the program, run in a sandbox; returns typed IR ops |
| `kir_spec` | the registry contract for one op — call form, slots, bounds, witness tolerances |
| `kir_compile` | C# for every supported Revit version, inline or as files |
| `kir_rehearse` | which obligations will *not* be checked — before a single round-trip |
| `kir_preview` | a floor plan as deterministic SVG, plus a census of what is **not** on it |

`kir_preview` also carries an [MCP Apps](https://modelcontextprotocol.io/extensions/apps/overview)
UI (`ui://kir/floorplan.html`): hosts that negotiated the extension render the plan inline, with
zoom, per-level sheets and the census panel. Hosts that did not get the same SVG and census as
data — the extension adds handling, never content.

The author sandbox runs the script in a separate process with no reachable network (its own
namespace, probed on every run), an empty root, no writable filesystem and an import allow-list;
its only exit is the list of IR ops, which the compiler then type-checks in full.

*(Every command above was run on 2026-09-02 against `kir-building` 0.3.0 installed from PyPI into
a fresh venv: the door answered `2026-07-28`, listed five tools, and compiled a four-wall house to
6/6 Revit versions.)*

## 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

```mermaid
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/`](kir/specs/) (`SPEC_V1.md`, the decompile
spec) and the design specs under [`docs/laws/`](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/` and `kir/*/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:

```json
{
  "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.

```python
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:

```text
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/**](examples/README.md) with their measured outputs.

### What happens to one op

```mermaid
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:

```text
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](#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.

```mermaid
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.

<a id="repository-state"></a>
## 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:

```bash
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/tests`
  collects **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.

- **`PYTHONPATH` must be absolute.** A bare `PYTHONPATH=.` is shadowed by any stray `kir.py` beside
  you, and the refusal then blames the wrong module.
- **Four direct dependencies, and `httpx` is one of them.** It looks like bridge-only machinery, but
  `compile_client.py` sits in the package import chain; dropping it into an extra made `import kir`
  fail 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/`](kir/specs/) — `SPEC_V1.md`, `KIR_DECOMPILE_SPEC.md`
- **Laws of honesty / verified / merkle:** [`docs/laws/`](docs/laws/)
- **LLM authoring skill + sandbox course:** `kir/skill.py`, [`kir/course/`](kir/course/)
- **CI evidence & secret boundary:** `.github/workflows/kir-evidence.yml`, `kir-security.yml`
- **Offline instruments, runnable with no Revit:** [`kir/instruments/`](kir/instruments/) — each one
  is expected to name what it could not read rather than report a zero it never measured

---

<p align="center">
  <sub>Apache License 2.0 — see <a href="LICENSE">LICENSE</a>.</sub>
</p>
