Metadata-Version: 2.4
Name: kir-building
Version: 0.2.2
Summary: Typed, verifiable intermediate representation and compiler for buildings.
Author: Dima
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/5vbkgsghhh-hash/kir
Project-URL: Source, https://github.com/5vbkgsghhh-hash/kir
Keywords: bim,building,cad,compiler,ir,revit
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
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"
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">
  <a href="https://pypi.org/project/kir-building/"><img alt="PyPI kir-building" src="https://img.shields.io/pypi/v/kir-building?label=PyPI"></a>
  <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">
  <code>python3.12 -m pip install kir-building</code>
</p>

<p align="center">
  <a href="#install-and-run-it">Install</a> ·
  <a href="https://pypi.org/project/kir-building/">PyPI</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="docs/KIR.md">KIR chapter</a> ·
  <a href="#repository-state">Repository state</a>
</p>

---

> **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 `kir-building` wheel installs the Python compiler, SDK and connector
> client. The native Revit add-in source stays in this repository under
> `connector/revit/`, because Autodesk API assemblies cannot be redistributed
> through a Python wheel.


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

```bash
python3.12 -m pip install kir-building
```

To install the current source directly from GitHub instead:

```bash
python3.12 -m pip install "git+https://github.com/5vbkgsghhh-hash/kir.git"
```

Or, 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()))"
```

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:

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

For live Revit execution, clone this source repository to obtain `connector/revit/`, then build its
local connector on Windows with Revit 2021–2026:

```powershell
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

```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 and rebuild verification — lives in the public [KIR](docs/KIR.md),
[Building Graph](docs/BUILDING_GRAPH.md), [Runtime](docs/RUNTIME.md) and
[Clash](docs/CLASH.md) 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:

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

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

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

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

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

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

```python
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](docs/KIR.md)
- **Reverse pipeline / Building Graph:** [Building Graph](docs/BUILDING_GRAPH.md)
- **Clash semantics:** [Clash](docs/CLASH.md)
- **Runtime, witnesses and idempotency:** [Runtime](docs/RUNTIME.md)
- **Host adapter boundary:** [Bridge](docs/BRIDGE.md)
- **LLM authoring surface:** `kir/skill.py`

---

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