Skip to content
This repository was archived by the owner on Aug 10, 2026. It is now read-only.

Repository files navigation

TCVN Rules-as-Code Engine

Mã hóa quy chuẩn xây dựng & PCCC Việt Nam (QCVN / TCVN) thành DSL có thể query, đánh giá tự động trên mô hình BIM, hồ sơ kiểm định và dữ liệu bảo hiểm công trình.

Important

Kho này đã dừng phát triển. Nội dung luật đã được chuyển sang plancheck.

This repository is archived. Its rule content has moved into plancheck, which encodes the same QCVN/TCVN clauses in a TOML rule format with a fixture for every rule, reads IFC directly, and exports to buildingSMART IDS — with no runtime dependencies.

ở đây / here trong plancheck / in plancheck
rules/qcvn-06-2022-bxd/escape-routes.tcvn plancheck/rules/tcvn/corridor-*.toml, travel-distance-office.toml, stair-landing-width.toml
rules/qcvn-06-2022-bxd/exits.tcvn exits-per-storey-high-rise.toml, exits-assembly-room.toml, exit-capacity.toml
rules/qcvn-06-2022-bxd/fire-resistance.tcvn wall-fire-resistance.toml, floor-fire-resistance.toml, compartment-wall-fire-resistance.toml, compartment-area.toml
rules/qcvn-06-2022-bxd/separation.tcvn separation-distance.toml
rules/qcvn-04-2021-bxd/apartments.tcvn apartment-bedroom-area.toml, elevator-provision.toml, parking-area-ratio.toml
rules/tcvn-2622-1995/legacy.tcvn legacy-escape-width-2622.toml
pip install git+https://github.com/sophie-nguyenthuthuy/plancheck.git
plancheck check my-building.ifc --jurisdiction TCVN

Vì sao gộp / why the merge. Hai kho cùng làm một việc — biến quy chuẩn thành luật máy đánh giá được — bằng hai engine khác nhau. Giữ cả hai nghĩa là mọi điều khoản mới phải mã hoá hai lần, và sớm muộn hai bên sẽ nói khác nhau về cùng một điều khoản. Nội dung luật ở đây là thứ đáng giữ; engine thì plancheck đã có, kèm fixture cho từng luật và xuất được IDS.

Lịch sử commit giữ nguyên. Bốn luật (chiều rộng cửa thoát nạn, chiều rộng bản thang, diện tích căn hộ, chiều rộng hành lang) vốn đã có trong plancheck nên không nhân đôi.

A production-grade rules-as-code engine for Vietnamese construction and fire-safety regulations. Encode the normative text of QCVN/TCVN once, then evaluate it deterministically against:

  • BIM model checkers — Revit/IFC exports validated before submittal.
  • Inspection software — handheld checklists that cite the exact clause behind every finding.
  • Insurance underwriting — programmatic risk scoring against fire-safety class, separation, and egress capacity.

The DSL is small, citation-first, and unit-aware. Every rule carries the QCVN/TCVN clause it implements so violations can be defended in plan review.


Why this is a moat

QCVN/TCVN are revised on the regulator's cadence, not the vendor's. Maintaining a canonical, versioned, machine-evaluable encoding takes:

  1. Vietnamese legal/technical reading of every revision (QCVN 06:2022/BXD already has one published amendment).
  2. Round-trip validation against real BIM exports.
  3. Backward compatibility with legacy permits issued under TCVN 2622:1995, QCVN 06:2010/BXD, QCVN 06:2020/BXD, QCVN 06:2021/BXD.

That work compounds. A late entrant has to redo five years of encoding and keep up with new revisions. This repository structures it so each clause's encoded version is content-addressable (fingerprint), pinned per pack version, and re-evaluable against existing fixtures.


At a glance

make dev                                    # set up local venv + dev deps
tcvn list                                   # see loaded standards
tcvn show "QCVN 06:2022/BXD"                # browse rules
tcvn lint rules/                            # parse-check every .tcvn file
tcvn check "QCVN 06:2022/BXD" tests/fixtures/buildings/noncompliant_apartment.json
tcvn serve                                  # boot FastAPI on :8000

The DSL

rule "escape_route_min_clear_width_residential_mid_rise" {
  clause "QCVN 06:2022/BXD §3.2.5"
  applies_to building
  when building.occupancy_class in ["F1.3", "F1.4"] and building.floors > 5
  require all(r in building.escape_routes: r.clear_width >= 1.2 m)
  severity critical
  tags ["egress", "residential"]
  message vi "Chiều rộng thông thủy của lối thoát hiểm phải ≥ 1,2 m đối với nhà ở > 5 tầng (hạng F1.3/F1.4)."
  message en "Clear width of escape routes must be ≥ 1.2 m for residential buildings > 5 storeys (class F1.3/F1.4)."
}

Highlights:

  • Citations are first-class. Every rule names the clause; every violation surfaces it.
  • Units are normalised to SI at evaluation time. Write 1.2 m, send {"value": 1200, "unit": "mm"} from a BIM exporter, comparison is exact.
  • Quantifiers (all, any, count, sum) make collection-level requirements legible.
  • Bilingual messages out of the box (message vi / message en).

Embed it

from tcvn_rules.sdk import RulesEngine

engine = RulesEngine("rules/")
result = engine.check("QCVN 06:2022/BXD", {"building": revit_export})

if not result.ok:
    for v in result.violations:
        print(f"{v.severity.value}  {v.rule_id}  [{v.clause}]  {v.message}")

Call it over HTTP

curl -X POST http://localhost:8000/v1/evaluate \
  -H "Content-Type: application/json" \
  -d '{"standard": "QCVN 06:2022/BXD", "context": {"building": {...}}}'

See examples/curl-evaluate.sh and the auto-generated OpenAPI at /docs.


What's encoded today

Standard Version Scope Status
QCVN 06:2022/BXD 2022.1 Fire safety: egress, exits, resistance, sites Active
QCVN 04:2021/BXD 2021.1 Apartment buildings: area, lifts, parking Active
TCVN 2622:1995 1995.1 Legacy fire safety (retrofit / heritage only) Superseded

The selection focuses on clauses most commonly checked in plan review. The catalog is designed for additive coverage — drop a new pack under rules/<code>/ with a metadata.yaml and *.tcvn files and load_catalog picks it up.


Architecture

┌──────────────┐   parse    ┌────────────┐   compile   ┌─────────┐
│ .tcvn source │──────────▶│  AST/Tree  │────────────▶│  IR     │
└──────────────┘   (lark)   └────────────┘             └────┬────┘
                                                            │ evaluate
                            ┌────────────┐                  ▼
                            │  Context   │──────▶ ┌──────────────────┐
                            │ (BIM/JSON) │        │ EvaluationResult │
                            └────────────┘        │  + Violations    │
                                                  └──────────────────┘
Module Responsibility
tcvn_rules.dsl Grammar + parser + AST → IR lowering
tcvn_rules.ir Stable rule/expression types, JSON-serialisable
tcvn_rules.engine Evaluator, unit normalisation, quantifier semantics
tcvn_rules.catalog Discover & version .tcvn packs
tcvn_rules.api FastAPI service
tcvn_rules.sdk One-line embedding API
tcvn_rules.cli tcvn command (typer + rich)

Development

make dev          # venv + editable install + dev deps
make lint         # ruff
make typecheck    # mypy --strict
make test         # pytest
make cov          # pytest + coverage (>= 80% gate)
make serve        # uvicorn on :8000
make docker-build && make docker-run

CI (GitHub Actions) runs ruff + mypy + pytest on 3.11 and 3.12, plus a Docker image smoke test.

Adding a rule

  1. Find the QCVN clause and read the published text.
  2. Add a rule "..." { ... } block to the relevant .tcvn file (or a new file in the pack).
  3. Include the clause citation and bilingual message lines.
  4. Add a positive and negative fixture under tests/fixtures/buildings/.
  5. Bump the pack version in metadata.yaml if existing evaluations would change.

Caveats

  • The encoded clauses are an engineering interpretation of the published standard. They do not replace plan review or inspector judgement. The encoded rules under rules/ are Apache-2.0; the underlying QCVN/TCVN text is owned by the issuing authority.
  • The DSL covers the patterns most QCVN clauses use (predicates over geometry/occupancy/material). It is not a full expert system — clauses that require human judgement (e.g. "khoảng cách hợp lý") are deliberately not encoded.
  • Cross-clause interactions (a rule's applicability depends on another rule's result) are not yet modelled. Each rule is independent.

License

Code: Apache License 2.0 — see LICENSE. Standard content: © respective issuing authorities (Bộ Xây dựng / Bộ KHCN). This repository encodes a normative interpretation only.

About

Production-grade Rules-as-Code engine for Vietnamese building & fire-safety standards (QCVN/TCVN). Queryable DSL for BIM model checking, inspection, and insurance underwriting.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages