0 Deps
77 KB Pure ESM Kernel (5/5 Purity)
582 / 582
Unit Tests (144,155 Assertions)
1,412
Aymeric House Nodes (0/0/0/0 Errors)
246
Public Pascal Buildings (0 Crashes)

1. Why Four Independent MEP Plugins Started Fighting Over Geometry

Building one deterministic MEP plugin for a browser-based 3D architectural editor is manageable. Building four of them (Structural framing, Plumbing DWV and PEX, HVAC ducting and loads, and NEC Electrical) that have to coexist inside the exact same house exposes a harder systems problem than any single code table.

Before extracting a shared kernel, each of my four MIT plugins (pascal-plugin-structural, pascal-plugin-plumbing, pascal-plugin-hvac, and pascal-plugin-electrical) worked cleanly in isolation. The cracks showed up when I ran all four sequentially against a corpus of 246 real user-authored public buildings exported from Pascal Editor's public scene catalog. Auditing roughly 30,300 lines of engine code across autopopulate.ts, routing.ts, audit.ts, openings.ts, and building-skeleton.ts surfaced three structural failure modes:

  1. Four Incompatible Geometry Stacks: Every plugin had grown its own interpretation of levels, roofs, wall openings, concave footprints, and 3D bounding boxes. pointInPolygon2D was copy-pasted six times. Concave indoor enclosure used three completely different algorithms (planar half-edge faces in Electrical, 8-ray room-first in HVAC, 16-ray raycasting in Structural). Aabb3 did not even share a shape ({ min: Vec3, max: Vec3 } in Electrical versus flat { minX..maxZ } in Plumbing and HVAC). Worse, Pascal Editor levels default to baseElevation: 0 unless explicitly overridden, so sorting stories by baseElevation before explicit level ordinal silently flattened two-story houses into a single floor inside Electrical and inside Plumbing's roof elevation helper.
  2. Post-Hoc Obstacle Dodging Instead of Legal Cavities: HVAC and Plumbing enumerated hardcoded template offsets in free 3D space and repaired clashes afterward; Electrical built a 2D wall graph with a soft +200 penalty for crossing openings followed by an 8-iteration greedy detour patch. Soft penalties look reasonable on simple boxes, yet on a U-shaped courtyard house with 30 doors and windows, a soft penalty eventually loses to path length and lets a cable jump across an open pool courtyard or clip through storefront glass.
  3. 28 Concrete Generator-vs-Auditor Rule Drifts: Almost every code rule had been written twice: once imperatively inside autopopulate.ts or routing.ts, and a second time inside audit.ts. Over weeks of real-world hardening, thresholds drifted apart by centimeters, inches, and feet.
Code Reference Generator / Router Threshold (Before) Post-Hoc Auditor Threshold (Before) Failure Mode Produced
NEC 406.9(C) / 410.10(D) 0.925 m wet-zone clearance 0.914 m (36 in) clearance Subtle placement/audit drift around tubs and showers
NEC 404.4(C) 0.25 m switch separation 0.15 m switch separation Unnecessary switch displacement or missed wet-zone flags
NEC 210.52(C) 0.15 m stove margin, [0.65, 1.75] band 0.08 m margin, [0.75, 1.65] band Countertop receptacle placed legally, flagged immediately on audit
NEC 406.5(E) Sink edge < 0.25 m, height <= 1.2 m Sink edge === 0, height <= 1.05 m Floor-adjacent and vanity outlets diverged between passes
IECC R403.3.1 Attic duct check on vertex > levelH - 0.02 Segment midpoint >= levelH + 0.05 Ducts right along the ceiling plane missed R-8 insulation
IMC 307.2.1 Condensate slope >= 0.125"/ft Condensate audit < 0.12"/ft Borderline floating-point drops behaved inconsistently
IFGC 402.4 Fuel gas length clamp at 15 ft Audit warning threshold at 10 ft Router emitted runs that immediately failed its own audit
IRC R602.6 & M1502.4 3" WC branch wet-wall fit & 35 ft dryer vent unchecked Flagged only during post-hoc audit Dryer vents exceeded 35 ft and 3" hubs entered 2x4 stud bays

The diagnosis was clear: adding more special-case if statements inside four separate plugins would only widen the divergence. All four trades needed a single deterministic geometry, routing, and constraint kernel built around construction-by-correctness.

2. The 3-Layer Spatial Kernel Architecture

I froze a specification (spec.md) with 11 hard invariants (INV-MEP-01 through INV-MEP-11) and extracted @kruschdev/pascal-mep-kernel as a standalone MIT package with three strict layers and five subpath exports (., ./types, ./anatomy, ./router, and ./rules).

LAYER 1 · SHARED SPATIAL ANATOMY (@kruschdev/pascal-mep-kernel/anatomy) WeakMap-memoized compileBuildingAnatomy(nodes): story ordering, 7-type roof shell, dual-sill 3D opening prisms, concave half-edge + 16-ray footprints, outdoor courtyard exclusion, and TradeOccupancyGrid rotated OBBs LAYER 2 · LEGAL-SPACE-FIRST CAVITY ROUTER (@kruschdev/pascal-mep-kernel/router) compileLegalCavityGraph + routeInLegalCavities: stud bays minus 3D opening prisms, roof-clamped plenums & attics, 4 physics modes (orthogonal, euclidean-cavity, gravity-slope, non-descending-vent), bend budgets & priority reservations LAYER 3 · SINGLE-SOURCE DECLARATIVE CODE RULES (@kruschdev/pascal-mep-kernel/rules) DeclarativeRule dual projection: filterLegalCandidates (generators) + evaluateDeclarativeRules (auditors) validateRuleTable enforces placementMarginM >= 0 so placement thresholds can never drift looser than audit thresholds #1 STRUCTURAL (IRC) Framing, beams, columns, 62 CAD .glb · 104 tests #2 PLUMBING (IPC) Gravity DWV, vents, PEX, 47 CAD .glb · 79 tests #3 HVAC (IMC) Manual J-D-S, trunks, ERV, 42 CAD .glb · 95 tests #4 ELECTRICAL (NEC) Art. 220 loads, 3D panels, 50 CAD .glb · 135 tests

Figure 1: All four MIT Pascal Editor MEP plugins consume one framework-free spatial kernel in real jobsite right-of-way priority order (Structural #1 -> Plumbing #2 -> HVAC #3 -> Electrical #4).

Before writing a single geometry helper, I locked down INV-MEP-01 with an automated purity script (scripts/check-purity.ts). The kernel is strictly forbidden from importing react, react-dom, three, @pascal-app/*, next, zod, zustand, or Node/Bun built-ins (node:*, bun:*). Because the published npm tarball is just 77 KB of precompiled pure ESM + .d.ts with zero dependencies, it drops straight into Next.js App Router, Turbopack, Vite, Bun, Node, or headless MCP agents without React Server Component boundary errors or extra transpilePackages hacks. Across all five repositories, 25/25 boundary and purity gates enforce this separation on every build.

3. Layer 1: Shared Cross-Trade Spatial Anatomy

The first design decision was ensuring all four trades observe the exact same building in O(1) amortized time. Calling compileBuildingAnatomy(nodes) returns a WeakMap-memoized BuildingAnatomy keyed by the scene's nodes record reference. Inside that compiled anatomy sit five canonical primitives that eliminated more than 2,300 lines of duplicated math across the four plugin repos:

The biggest conceptual shift in the kernel happens in Layer 2 (src/router/cavity-graph.ts and src/router/shortest-path.ts). Instead of routing through open air and trying to nudge colliding segments out of windows or courtyards after the fact, compileLegalCavityGraph constructs the navigable graph strictly out of spaces where building codes actually permit pipes, ducts, and cables to travel:

On top of that pre-pruned cavity graph, routeInLegalCavities runs a constrained shortest-path solver across four explicit physics modes: orthogonal (rigid EMT/RMC conduit and rectangular/round HVAC trunks), euclidean-cavity (flexible NM-B/MC cable and PEX inside open attics or dry crawlspaces), gravity-slope (DWV drains and HVAC condensate enforcing strict monotonic fall without ever silently inserting an uphill segment), and non-descending-vent (IPC 905.5 dry re-vents staying at least 6 in / 0.1524 m above flood-level rim with zero inverted-U traps). Cumulative bend angles track against caps like NEC 358.26 (360° between pull points), and every committed route reserves its swept envelope inside TradeOccupancyGrid before the next lower-priority trade routes.

Aymeric House Main Floor Slice in Pascal Editor Showing Coordinated Timber Framing, Blue Dual-Wing HVAC Trunks, Red and Blue Plumbing Runs, and NEC Electrical Circuits Routing Around Every Door, Window, and Courtyard

Figure 2: Live Pascal Editor main-floor slice of Aymeric House. Because the open U-shaped Lanai pool courtyard and all 30 door/window prisms are excluded from the legal cavity graph by construction, HVAC splits cleanly into West 4-Ton and East 2-Ton wings and zero wires cross the courtyard or glass.

5. Layer 3: Single-Source Declarative Code Rules

Fixing geometry alone still leaves half the bug class alive if generators and auditors encode code requirements separately. Layer 3 (src/rules/schema.ts and src/rules/evaluator.ts) defines a compact, typed DeclarativeRule record covering nine constraint kinds (prohibited-zone, fixture-keepout, opening-keepout, elevation-band, working-space, material-policy, routing-constraint, wall-cavity-fit, and wind-seismic-threshold).

ONE DECLARATIVE RULE TABLE IRC / IPC / IMC / NEC Rule Records auditLimit + placementMarginM >= 0 Validated at boot via validateRuleTable() PROJECTION A · GENERATOR / ROUTER FILTER filterLegalCandidates(candidates, rules) uses effectivePlacementThreshold Equal or stricter margin prevents self-inflicted violations before a node is created PROJECTION B · LIVE COMPLIANCE AUDITOR evaluateDeclarativeRules(scene, rules) checks exact code auditLimit Same codeRef, category, severity & suggestedFix; zero generator-vs-auditor drift

Figure 3: Dual-projection rule evaluation guarantees soundness by construction. Because placementMarginM >= 0 is validated at load time, a placement pass can be stricter than the audit threshold for safety cushion, never looser.

import {
  compileBuildingAnatomy,
  compileLegalCavityGraph,
  routeInLegalCavities,
  filterLegalCandidates,
  evaluateDeclarativeRules,
  validateRuleTable,
} from '@kruschdev/pascal-mep-kernel'

// 1. Compile shared O(1) WeakMap-memoized anatomy once for all 4 trades
const anatomy = compileBuildingAnatomy(scene.nodes)
const grid = anatomy.createOccupancyGrid(levelId, { forTrade: 'electrical' })

// 2. Build navigable cavities excluding 3D openings, roof clearances & courtyards
const graph = compileLegalCavityGraph(anatomy, levelId, {
  clearanceM: 0.05,
  allowedBands: ['under-sill', 'mid-wall', 'top-plate', 'overhead-plenum', 'attic'],
})

// 3. Route in priority order with bend caps & automatic occupancy reservation
const route = routeInLegalCavities(graph, grid, {
  trade: 'electrical',
  from: panelPort,
  to: receptaclePort,
  halfXZ: 0.012,
  halfY: 0.012,
  clearanceM: 0.025,
  allowedBands: ['under-sill', 'mid-wall', 'top-plate', 'attic'],
  mode: 'euclidean-cavity',
  maxBendDegrees: 360,
  reserveOnCommit: true,
})

// 4. Enforce identical thresholds across both placement and post-hoc audit
validateRuleTable(NEC_DECLARATIVE_RULES)
const legalSpots = filterLegalCandidates(candidates, NEC_DECLARATIVE_RULES, anatomy)
const auditReport = evaluateDeclarativeRules(placedNodes, NEC_DECLARATIVE_RULES, anatomy)

6. Verification: 582 Unit Tests, 246 Real Public Buildings, and Aymeric House

Refactors that touch geometry math across four engineering disciplines are notorious for breaking edge cases quietly. I gated every wave of the refactor (Layer 1 anatomy adoption, Layer 2 cavity routing adoption, and Layer 3 declarative rule migration) on three checks: the full unit suite across all five repositories, the 25/25 framework purity and Next.js RSC boundary checks, and an automated sweep across 246 real user-built public Pascal buildings fetched via Pascal Editor's public read API.

Priority Repository (MIT) Standards & Scope 3D CAD Models Unit Tests
Core @kruschdev/pascal-mep-kernel v0.1.0 Spatial anatomy, legal-cavity router, declarative rule engine (npm) Zero-dep pure TS 169 / 169 (135,888 assertions)
#1 @kruschdev/pascal-plugin-structural v0.2.0 IRC / AWC NDS / AISC framing, engineered beams, Simpson-class connectors, fire blocking 62 MIT .glb 104 / 104 (1,493 assertions)
#2 @kruschdev/pascal-plugin-plumbing v0.2.0 IPC / UPC / IFGC gravity DWV, dry vents, PEX manifolds, gas, dryer vents 47 MIT .glb 79 / 79 (2,762 assertions)
#3 @kruschdev/pascal-plugin-hvac v0.2.0 IMC / ACCA Manual J-D-S / IECC dual-wing & mini-split HVAC, ERV, condensate 42 MIT .glb 95 / 95 (1,669 assertions)
#4 @kruschdev/pascal-plugin-electrical v0.2.7 NEC / NFPA 72 Art. 220 loads, 3D cover-off panelboards, opening-safe routing (npm) 50 MIT .glb 135 / 135 (2,343 assertions)
Total 5 Coordinated MIT Repositories 4-Trade Jobsite Right-of-Way + 33 Pure-Zod Agent Operations 201 MIT .glb 582 / 582 (144,155 assertions)

On the live flagship stress test, Aymeric House (two stories, 21 zones, a U-shaped open Lanai courtyard with pool, pitched gable wing roofs, and a central flat roof), running all four plugins in priority order stamps 1,412 coordinated nodes with 0 / 0 / 0 / 0 audit errors, zero ducts or electrical cables spanning the open courtyard, zero wires intersecting any of the 30 door and window openings, a 0.09% balanced main panel schedule, and a combined $185,414 priced bill of materials across all four trades. Across all 246 real public Pascal buildings, the suite completes with 0 crashes, 0 NaN geometry outputs, and 145 / 246 buildings completely 0/0/0/0 clean across all four trades simultaneously (PLB 245/246, HVC 222/246, ELC 198/246, STR 167/246; 17/17 Plumbing and 17/17 Electrical zero-error on official Pascal demo scenes). Remote installation of all four hosted-Pascal-packaged plugins together via bun add completes in 2.06 s at 6.1 MB total unpacked.

Full Two-Story Aymeric House 4-Trade MEP Cutaway in Pascal Editor With Framing X-Ray, Structural Framing, Plumbing, Dual-Wing HVAC, and Electrical Routing

Figure 4: Full two-story Aymeric House cutaway rendered live in Pascal Editor with Structural Framing X-Ray active and all four MEP trades layered cleanly beneath pitched wing roofs and the central flat roof.

7. Honest Scope Boundaries and Known Edge Cases

Engineering Disclaimer: @kruschdev/pascal-mep-kernel and all four MIT Pascal MEP plugins are deterministic drafting, visualization, and preliminary engineering aids, never stamped engineering and never a substitute for a licensed Professional Engineer (PE), master tradesperson, or local Authority Having Jurisdiction (AHJ) plan review.

Shipping real geometry code against 246 uncurated user buildings also reveals exactly where deterministic heuristics still have boundaries worth documenting openly:

8. Install and Verify Locally

The kernel and all four Pascal Editor plugins are published under the MIT License and can be installed or verified locally in seconds:

# 1. Install the zero-dependency spatial kernel from npm
npm install @kruschdev/pascal-mep-kernel
# or
bun add @kruschdev/pascal-mep-kernel

# 2. Clone and run full typecheck, 169 unit tests, 5/5 purity gates & ESM build
git clone https://github.com/kruschdev/pascal-mep-kernel.git && cd pascal-mep-kernel
bun install && bun run check

# 3. Install all 4 coordinated MIT plugins in any Pascal Editor host
bun add \
  @kruschdev/pascal-plugin-electrical \
  github:kruschdev/pascal-plugin-structural \
  github:kruschdev/pascal-plugin-plumbing \
  github:kruschdev/pascal-plugin-hvac