@kruschdev/pascal-plugin-plumbing 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  # 47-Model Clean-Room MIT 3D Plumbing CAD Catalog
2
2
 
3
- All 47 procedural Three.js CAD parts in `src/cad/catalog.ts` export cleanly to binary `.glb` via `bun run export:cad`:
3
+ All 47 procedural Three.js CAD parts in `src/cad/catalog.ts` can be instantiated directly at runtime via `@kruschdev/pascal-plugin-plumbing/cad` (`PLUMBING_CAD_CATALOG` / `buildPlumbingCadPart`), or exported from a source repository clone to binary `.glb` assets (`assets/cad/*.glb` + `assets/cad/catalog.json`) via `bun run export:cad` (`scripts/export-cad-catalog.ts`):
4
4
 
5
5
  - **Water Heaters & Mechanical Equipment (12)**: 50 gal Electric Tank WH, 50 gal Gas Tank WH w/ Flue, Tankless Condensing Gas WH, Hybrid Heat Pump WH, 2 gal Thermal Expansion Tank, Main Shutoff + PRV + Gauge, Whole-House Water Softener, Sump Pump Basin, Sealed Sewage Ejector Basin, Hot Water Recirc Pump, Natural Gas Utility Meter, Mainline Backwater Valve.
6
6
  - **PEX & Fuel-Gas Manifolds (4)**: 12-Port PEX Home-Run Manifold (Open), 24-Port PEX Manifold w/ Enclosure, Type L Copper Header, 8-Port CSST Gas Manifold.
7
- - **Residential & Commercial Fixtures (18)**: Elongated Water Closet, Vanity Lavatory, Kitchen Sink, Alcove Bathtub, Walk-In Shower, Tub/Shower Combo, Dishwasher Rough-In, Washer Outlet Box & Standpipe, Laundry Sink, Bar Sink, Floor Drain, Frost-Proof Hose Bibb, Heated Bidet Seat, Garbage Disposal, Commercial Urinal, Commercial Mop Basin, Commercial Drinking Fountain, Commercial 50 GPM Grease Interceptor.
7
+ - **Residential & Commercial Fixtures (18)** *(exported alongside all other categories via `bun run export:cad` in a source checkout)*: Elongated Water Closet, Vanity Lavatory, Kitchen Sink, Alcove Bathtub, Walk-In Shower, Tub/Shower Combo, Dishwasher Rough-In, Washer Outlet Box & Standpipe, Laundry Sink, Bar Sink, Floor Drain, Frost-Proof Hose Bibb, Heated Bidet Seat, Garbage Disposal, Commercial Urinal, Commercial Mop Basin, Commercial Drinking Fountain, Commercial 50 GPM Grease Interceptor.
8
8
  - **DWV Fittings & Cleanouts (7)**: Solvent-Weld P-Trap, Sanitary Tee, 45° Wye/Combo, Long-Sweep 90°, Two-Way Cleanout Tee, Roof Vent Flashing Boot, Air Admittance Valve (AAV).
9
9
  - **Supply & Fuel-Gas Valves (4)**: Full-Port Brass Ball Valve, Quarter-Turn Angle Stop, Thermostatic Mixing Valve, Gas Drip Leg & Shutoff.
10
10
  - **Pipe Runs, Hangers & Cutaway Assemblies (2)**: Galvanized Clevis Pipe Hanger w/ Threaded Rod, 2x6 Wet-Wall PEX Manifold & 3" PVC Stack Cutaway (plus swept `buildPipeRunCad` with 3D stud bore collars and wall-normal steel nail plates).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kruschdev/pascal-plugin-plumbing",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "Residential & Light-Commercial IPC/UPC/IFGC plumbing authoring, DFU/WSFU/gas load calculations, gravity-sloped DWV & PEX manifold routing, and code audit plugin for Pascal Editor.",
5
5
  "author": "Kevin Ruschman <kruschdev@users.noreply.github.com>",
6
6
  "license": "MIT",
@@ -44,7 +44,7 @@
44
44
  "check": "bun run check-types && bun test && bun run check:render && bun run build"
45
45
  },
46
46
  "dependencies": {
47
- "@kruschdev/pascal-mep-kernel": "^0.1.0"
47
+ "@kruschdev/pascal-mep-kernel": "^0.3.0"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@pascal-app/core": ">=1.0.0 <2",
@@ -624,6 +624,10 @@ export const plumbingAgentOperations = {
624
624
  })
625
625
  const created: Array<{ node: AnyNode; parentId: string }> = []
626
626
  const simulated: Record<string, SceneNodeLike> = { ...origRecord }
627
+ const replacedPipeIds = sync.replacedPipeIds ?? []
628
+ for (const delId of replacedPipeIds) {
629
+ delete simulated[delId]
630
+ }
627
631
  const eqList = sync.fullPlan ? sync.fullPlan.equipment : []
628
632
  const manList = sync.fullPlan ? sync.fullPlan.manifolds : []
629
633
  for (const eq of eqList) {
@@ -669,7 +673,10 @@ export const plumbingAgentOperations = {
669
673
  bonesAnchorsUsed: sync.fullPlan?.bonesAnchorsUsed ?? [],
670
674
  audit,
671
675
  },
672
- changes: { create: created },
676
+ changes: {
677
+ ...(replacedPipeIds.length > 0 ? { delete: replacedPipeIds } : {}),
678
+ create: created,
679
+ },
673
680
  }
674
681
  }
675
682
 
@@ -781,11 +788,16 @@ export const plumbingAgentOperations = {
781
788
 
782
789
  plumbing_calculate_loads: (
783
790
  nodes: SceneNodes,
784
- input: { codeEdition?: CodeEdition; occupancy?: OccupancyType },
791
+ input: {
792
+ codeEdition?: CodeEdition
793
+ occupancy?: OccupancyType
794
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc'
795
+ },
785
796
  ) => {
786
797
  const schedule = buildPlumbingSchedule(asRecord(nodes), {
787
798
  codeEdition: input.codeEdition ?? 'IPC-2021',
788
799
  occupancy: input.occupancy ?? 'residential',
800
+ ...(input.supplyMaterial ? { supplyMaterial: input.supplyMaterial } : {}),
789
801
  })
790
802
  return {
791
803
  result: {
@@ -223,6 +223,7 @@ export const plumbingAgentTools: PluginAgentTools = {
223
223
  input: {
224
224
  codeEdition: z.enum(['IPC-2021', 'UPC-2021']).default('IPC-2021'),
225
225
  occupancy: z.enum(['residential', 'commercial']).default('residential'),
226
+ supplyMaterial: z.enum(['pex-a', 'pex-b', 'copper-l', 'copper-m', 'cpvc']).optional(),
226
227
  },
227
228
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
228
229
  },
@@ -133,6 +133,19 @@ export function buildFittingCad(kind: FittingCadKind): Group {
133
133
  const UP = new Vector3(0, 1, 0)
134
134
  const X_AXIS = new Vector3(1, 0, 0)
135
135
 
136
+ function isFiniteVec3Pt(p: unknown): p is Vec3 {
137
+ return (
138
+ Array.isArray(p) &&
139
+ p.length >= 3 &&
140
+ typeof p[0] === 'number' &&
141
+ typeof p[1] === 'number' &&
142
+ typeof p[2] === 'number' &&
143
+ Number.isFinite(p[0]) &&
144
+ Number.isFinite(p[1]) &&
145
+ Number.isFinite(p[2])
146
+ )
147
+ }
148
+
136
149
  function safeQuatFromUp(dir: Vector3): Quaternion {
137
150
  if (dir.y < -0.99999) {
138
151
  return new Quaternion().setFromAxisAngle(X_AXIS, Math.PI)
@@ -167,7 +180,8 @@ export function buildPipeRunCad(params: {
167
180
  const g = new Group()
168
181
  g.name = `plumbing-pipe-run-${id}`
169
182
 
170
- if (path.length < 2) return g
183
+ const validPath = path.filter(isFiniteVec3Pt)
184
+ if (validPath.length < 2) return g
171
185
 
172
186
  const mat = pipeRunMaterialForSystem(pool, system, material)
173
187
  const odM = getPipeOuterDiameterM(nominalSize, material)
@@ -183,12 +197,12 @@ export function buildPipeRunCad(params: {
183
197
  let plateNailPlateGeo: BoxGeometry | null = null
184
198
  let firstValidSeg: { start: Vector3; dir: Vector3; len: number } | null = null
185
199
 
186
- for (let i = 1; i < path.length; i++) {
187
- const a = new Vector3(path[i - 1]![0], path[i - 1]![1], path[i - 1]![2])
188
- const b = new Vector3(path[i]![0], path[i]![1], path[i]![2])
200
+ for (let i = 1; i < validPath.length; i++) {
201
+ const a = new Vector3(validPath[i - 1]![0], validPath[i - 1]![1], validPath[i - 1]![2])
202
+ const b = new Vector3(validPath[i]![0], validPath[i]![1], validPath[i]![2])
189
203
  const delta = new Vector3().subVectors(b, a)
190
204
  const len = delta.length()
191
- if (len < 0.005) continue
205
+ if (!Number.isFinite(len) || len < 0.005) continue
192
206
 
193
207
  const dir = delta.clone().normalize()
194
208
  if (!firstValidSeg) {
@@ -207,7 +221,7 @@ export function buildPipeRunCad(params: {
207
221
  g.add(seg)
208
222
 
209
223
  // Smooth elbow/wye joint sphere at vertices
210
- if (i < path.length - 1) {
224
+ if (i < validPath.length - 1) {
211
225
  jointGeo ??= new SphereGeometry(isRigid ? hubRadius : radius * 1.06, 12, 10)
212
226
  const joint = new Mesh(jointGeo, mat)
213
227
  joint.position.copy(b)
@@ -248,8 +262,12 @@ export function buildPipeRunCad(params: {
248
262
  // Framing Penetration 3D Bore Sleeves & IRC R602.6 / IPC 305.6 Nail Plates (oriented to wall normal on both faces)
249
263
  const sleeveGeoCache = new Map<string, CylinderGeometry>()
250
264
  for (const pen of penetrations) {
251
- const boreR = Math.max(radius * 1.15, (pen.holeSawIn * 0.0254) / 2)
252
- const rawDir = new Vector3(pen.pipeDirection[0], pen.pipeDirection[1], pen.pipeDirection[2])
265
+ if (!isFiniteVec3Pt(pen.position)) continue
266
+ const holeSawIn = Number.isFinite(pen.holeSawIn) && pen.holeSawIn > 0 ? pen.holeSawIn : 1
267
+ const boreR = Math.max(radius * 1.15, (holeSawIn * 0.0254) / 2)
268
+ const rawDir = isFiniteVec3Pt(pen.pipeDirection)
269
+ ? new Vector3(pen.pipeDirection[0], pen.pipeDirection[1], pen.pipeDirection[2])
270
+ : UP.clone()
253
271
  const pDir = rawDir.lengthSq() < 1e-8 ? UP.clone() : rawDir.normalize()
254
272
  const quat = safeQuatFromUp(pDir)
255
273
  const sleeveMat = pen.codeCompliant ? pool.darkRubber : pool.pexHotRed
@@ -53,7 +53,6 @@ export function buildManifoldCad(params: {
53
53
  manifoldKind,
54
54
  portCount,
55
55
  viewMode: coverRemoved ? 'open-manifold' : 'enclosure-closed',
56
- ports: [],
57
56
  })
58
57
  }
59
58
 
@@ -62,7 +61,7 @@ export function buildManifoldCad(params: {
62
61
  * optionally mounted inside an exposed 2x6 wet-wall framing cutaway with active hot/cold
63
62
  * home-run PEX loops, brass quarter-turn ball valves, nail plates, and adjacent 3" PVC stack.
64
63
  */
65
- export function buildWiredManifoldCutawayCad(params: {
64
+ export function buildWiredManifoldCutawayCad(options: {
66
65
  manifoldKind: ManifoldKind
67
66
  portCount?: number
68
67
  viewMode?: ManifoldCutawayViewMode
@@ -72,8 +71,8 @@ export function buildWiredManifoldCutawayCad(params: {
72
71
  manifoldKind,
73
72
  portCount = 12,
74
73
  viewMode = 'open-manifold',
75
- ports = [],
76
- } = params
74
+ } = options
75
+ const ports = options?.ports ?? []
77
76
  const pool = createPlumbingMaterialPool()
78
77
  const g = new Group()
79
78
  g.name = `plumbing-manifold-${manifoldKind}-${viewMode}`
@@ -131,7 +130,7 @@ export function buildWiredManifoldCutawayCad(params: {
131
130
  add(new Mesh(vertFlangeGeo, pool.galvanizedSteel), -cabinetW / 2, 0, 0)
132
131
  add(new Mesh(vertFlangeGeo, pool.galvanizedSteel), cabinetW / 2, 0, 0)
133
132
 
134
- const hasExplicitPorts = ports.length > 0
133
+ const hasExplicitPorts = options?.ports !== undefined
135
134
 
136
135
  if (manifoldKind === 'gas-csst') {
137
136
  const activeGasIndices = new Set(
@@ -197,7 +196,7 @@ export function buildWiredManifoldCutawayCad(params: {
197
196
  )
198
197
  const hotPortCount = Math.max(perSide, ports.filter((p) => p.side === 'hot').length)
199
198
  const coldPortCount = Math.max(perSide, ports.filter((p) => p.side === 'cold').length)
200
- const rows = Math.min(14, Math.max(hotPortCount, coldPortCount))
199
+ const rows = Math.min(18, Math.max(hotPortCount, coldPortCount))
201
200
 
202
201
  const valveBodyGeo = new CylinderGeometry(0.009, 0.009, 0.075, 10)
203
202
  const valveHandleGeo = new BoxGeometry(0.026, 0.009, 0.012)
package/src/index.ts CHANGED
@@ -106,6 +106,9 @@ export const plumbingScheduleView: EditorHostView = {
106
106
  export const plumbingChatExtension: PluginChatExtension = {
107
107
  pluginId: PLUMBING_PLUGIN_ID,
108
108
  cards: {
109
+ plumbing_place_equipment: () => import('./ui/chat-card'),
110
+ plumbing_place_manifold: () => import('./ui/chat-card'),
111
+ plumbing_place_fixture: () => import('./ui/chat-card'),
109
112
  plumbing_audit_ipc: () => import('./ui/chat-card'),
110
113
  plumbing_generate_schedule: () => import('./ui/chat-card'),
111
114
  plumbing_route_pipe: () => import('./ui/chat-card'),
package/src/ipc/audit.ts CHANGED
@@ -5,11 +5,12 @@
5
5
  * Framework-free: zero React, Three.js, or `@pascal-app/*` imports.
6
6
  */
7
7
 
8
- import { evaluatePlacementCandidate } from '@kruschdev/pascal-mep-kernel'
8
+ import { evaluatePlacementCandidate, resolveLevelBuildingId } from '@kruschdev/pascal-mep-kernel'
9
9
  import {
10
10
  type BonesPlumbingContext,
11
11
  type SceneNodeLike,
12
12
  checkWetWallPipeFit,
13
+ computePipeFramingPenetrations,
13
14
  extractBonesPlumbingContext,
14
15
  getLowerWalledLevelIds,
15
16
  resolveEffectiveWallThicknessM,
@@ -32,6 +33,7 @@ import {
32
33
  calculateSupplyHydraulics,
33
34
  checkDryerVentRun,
34
35
  checkTrapArmDistance,
36
+ computeFuelGasDevelopedLengths,
35
37
  getMinRequiredDrainSlopeInPerFt,
36
38
  sizeBuildingDrain,
37
39
  sizeDrainBranch,
@@ -76,20 +78,26 @@ export type PlumbingAuditResult = {
76
78
 
77
79
  const auditCache = new WeakMap<Readonly<Record<string, SceneNodeLike>>, Map<string, PlumbingAuditResult>>()
78
80
 
81
+ function resolveNodeBuildingKey(
82
+ nodes: Readonly<Record<string, SceneNodeLike>>,
83
+ node: SceneNodeLike,
84
+ ): string {
85
+ const lvlId = resolveNodeLevelId(nodes, node)
86
+ if (lvlId && nodes[lvlId]) {
87
+ return resolveLevelBuildingId(nodes, nodes[lvlId]) ?? '__default_building__'
88
+ }
89
+ if (typeof node.parentId === 'string' && nodes[node.parentId]?.type === 'building') {
90
+ return node.parentId
91
+ }
92
+ return '__default_building__'
93
+ }
94
+
79
95
  export function auditScenePlumbing(
80
96
  nodes: Readonly<Record<string, SceneNodeLike>>,
81
97
  options: { codeEdition?: CodeEdition; occupancy?: OccupancyType } = {},
82
98
  ): PlumbingAuditResult {
83
99
  const codeEdition = options.codeEdition ?? 'IPC-2021'
84
- const all = Object.values(nodes)
85
- const fixtures = all.filter((n) => n.type === 'plumbing:fixture')
86
- const inferredCommercial = fixtures.some((f) => {
87
- const k = f.fixtureKind as FixtureKind | undefined
88
- return k ? Boolean(FIXTURE_SPECS[k]?.commercialOnly) : false
89
- })
90
- const occupancy: OccupancyType = options.occupancy ?? (inferredCommercial ? 'commercial' : 'residential')
91
- const flushType = occupancy === 'commercial' ? 'flushometer' : 'flush-tank'
92
- const cacheKey = `${codeEdition}|${occupancy}`
100
+ const cacheKey = `${codeEdition}|${options.occupancy ?? '__auto__'}`
93
101
 
94
102
  let byEdition = auditCache.get(nodes)
95
103
  if (!byEdition) {
@@ -99,6 +107,21 @@ export function auditScenePlumbing(
99
107
  const cached = byEdition.get(cacheKey)
100
108
  if (cached) return cached
101
109
 
110
+ const all = Object.values(nodes)
111
+ const fixtures = all.filter((n) => n.type === 'plumbing:fixture')
112
+ const commercialBuildingKeys = new Set<string>()
113
+ for (const f of fixtures) {
114
+ const k = f.fixtureKind as FixtureKind | undefined
115
+ if (k && FIXTURE_SPECS[k]?.commercialOnly) {
116
+ commercialBuildingKeys.add(resolveNodeBuildingKey(nodes, f))
117
+ }
118
+ }
119
+ const getFlushTypeForBuilding = (bldgKey: string): 'flushometer' | 'flush-tank' => {
120
+ const occ: OccupancyType =
121
+ options.occupancy ?? (commercialBuildingKeys.has(bldgKey) ? 'commercial' : 'residential')
122
+ return occ === 'commercial' ? 'flushometer' : 'flush-tank'
123
+ }
124
+
102
125
  const findings: PlumbingAuditFinding[] = []
103
126
  let seq = 1
104
127
  const push = (f: Omit<PlumbingAuditFinding, 'id'>) => {
@@ -107,18 +130,33 @@ export function auditScenePlumbing(
107
130
 
108
131
  const equipment = all.filter((n) => n.type === 'plumbing:equipment')
109
132
  const pipeRuns = all.filter((n) => n.type === 'plumbing:pipe-run')
110
- const hasElectricalPanel = all.some((n) => n.type === 'electrical:panel')
133
+ const buildingsWithElectricalPanel = new Set<string>()
134
+ for (const n of all) {
135
+ if (n.type === 'electrical:panel') {
136
+ buildingsWithElectricalPanel.add(resolveNodeBuildingKey(nodes, n))
137
+ }
138
+ }
111
139
 
112
140
  // Per-level spatial context caches so multi-story scenes never mix level-local coordinates across floors
141
+ const wallsByLevel = new Map<string, WallSegment2D[]>()
113
142
  const wallMapByLevel = new Map<string, Map<string, WallSegment2D>>()
114
143
  const bonesByLevel = new Map<string, BonesPlumbingContext>()
115
144
  const obstaclesByLevel = new Map<string, PlumbingObstacle[]>()
116
145
 
146
+ const getWallsForLevel = (lvlId: string | null): WallSegment2D[] => {
147
+ const key = lvlId ?? '__all__'
148
+ let list = wallsByLevel.get(key)
149
+ if (!list) {
150
+ list = extractWallSegments(nodes, lvlId)
151
+ wallsByLevel.set(key, list)
152
+ }
153
+ return list
154
+ }
117
155
  const getWallMapForLevel = (lvlId: string | null): Map<string, WallSegment2D> => {
118
156
  const key = lvlId ?? '__all__'
119
157
  let m = wallMapByLevel.get(key)
120
158
  if (!m) {
121
- m = new Map(extractWallSegments(nodes, lvlId).map((w) => [w.id, w]))
159
+ m = new Map(getWallsForLevel(lvlId).map((w) => [w.id, w]))
122
160
  wallMapByLevel.set(key, m)
123
161
  }
124
162
  return m
@@ -142,9 +180,14 @@ export function auditScenePlumbing(
142
180
  return obs
143
181
  }
144
182
 
145
- // 1. Fixture-level checks
146
- const hasExpansionTank = equipment.some((e) => e.equipmentKind === 'expansion-tank')
147
- const hasMainShutoff = equipment.some((e) => e.equipmentKind === 'main-shutoff-prv')
183
+ // 1. Fixture-level checks & per-building closed-system equipment flags
184
+ const buildingsWithExpansionTank = new Set<string>()
185
+ const buildingsWithMainShutoff = new Set<string>()
186
+ for (const e of equipment) {
187
+ const bldgKey = resolveNodeBuildingKey(nodes, e)
188
+ if (e.equipmentKind === 'expansion-tank') buildingsWithExpansionTank.add(bldgKey)
189
+ if (e.equipmentKind === 'main-shutoff-prv') buildingsWithMainShutoff.add(bldgKey)
190
+ }
148
191
 
149
192
  for (const fix of fixtures) {
150
193
  const kind = (fix.fixtureKind as FixtureKind) || 'lavatory'
@@ -176,7 +219,12 @@ export function auditScenePlumbing(
176
219
  const kind = String(eq.equipmentKind ?? '')
177
220
  const isWaterHeater = kind.startsWith('water-heater-')
178
221
  if (isWaterHeater) {
179
- if (eq.hasExpansionTank === false && !hasExpansionTank && hasMainShutoff) {
222
+ const eqBldgKey = resolveNodeBuildingKey(nodes, eq)
223
+ if (
224
+ eq.hasExpansionTank === false &&
225
+ !buildingsWithExpansionTank.has(eqBldgKey) &&
226
+ buildingsWithMainShutoff.has(eqBldgKey)
227
+ ) {
180
228
  push({
181
229
  severity: 'warning',
182
230
  codeRef: 'IPC 607.3',
@@ -258,6 +306,22 @@ export function auditScenePlumbing(
258
306
  const dryerVentMaterialRule = getIpcRuleById('irc-m1502-4-1-dryer-vent-material')
259
307
  const fuelGasMaxLenRule = getIpcRuleById('ifgc-402-4-fuel-gas-max-len')
260
308
 
309
+ const gasDevelopedByRunId = computeFuelGasDevelopedLengths(
310
+ pipeRuns
311
+ .filter((r) => r.system === 'fuel-gas')
312
+ .map((r) => {
313
+ const p = Array.isArray(r.path)
314
+ ? (r.path as ReadonlyArray<readonly [number, number, number]>)
315
+ : []
316
+ return {
317
+ id: r.id,
318
+ lengthFt: polylineLengthM(p) * METERS_TO_FEET,
319
+ ...(typeof r.sourceNodeId === 'string' && r.sourceNodeId ? { sourceNodeId: r.sourceNodeId } : {}),
320
+ ...(typeof r.targetNodeId === 'string' && r.targetNodeId ? { targetNodeId: r.targetNodeId } : {}),
321
+ }
322
+ }),
323
+ ).byRunId
324
+
261
325
  for (const run of pipeRuns) {
262
326
  const system = (run.system as PlumbingSystem) || 'cold-water'
263
327
  const material = (run.material as PipeMaterial) || 'pex-a'
@@ -331,9 +395,10 @@ export function auditScenePlumbing(
331
395
 
332
396
  // Wet-wall cavity check (2x4 vs 2x6 for >= 3" DWV, honoring Bones/Structural load-bearing overrides)
333
397
  const levelWallMap = getWallMapForLevel(runLevelId)
398
+ const levelWalls = getWallsForLevel(runLevelId)
399
+ const bonesCtx = getBonesForLevel(runLevelId)
334
400
  if (typeof run.wallId === 'string' && levelWallMap.has(run.wallId)) {
335
401
  const wall = levelWallMap.get(run.wallId)!
336
- const bonesCtx = getBonesForLevel(runLevelId)
337
402
  const wallRule = bonesCtx.wallRules.get(wall.id)
338
403
  const effectiveWallThicknessM = resolveEffectiveWallThicknessM(wall.thicknessM, bonesCtx, wallRule)
339
404
  const declarativeWallFit = evaluatePlacementCandidate(
@@ -367,6 +432,34 @@ export function auditScenePlumbing(
367
432
  }
368
433
  }
369
434
 
435
+ // Horizontal stud-bore compliance check (IRC R602.6: <= 40% load-bearing / <= 60% non-load-bearing stud depth)
436
+ if (path.length >= 2 && levelWalls.length > 0) {
437
+ const penetrations = computePipeFramingPenetrations({
438
+ pipeRunId: run.id,
439
+ path,
440
+ pipeSize: size,
441
+ material,
442
+ walls: levelWalls,
443
+ bonesContext: bonesCtx,
444
+ })
445
+ const reportedStudWalls = new Set<string>()
446
+ for (const pen of penetrations) {
447
+ if (pen.memberKind !== 'stud' || pen.codeCompliant) continue
448
+ const wallKey = pen.wallId ?? '__unknown_wall__'
449
+ if (reportedStudWalls.has(wallKey)) continue
450
+ reportedStudWalls.add(wallKey)
451
+ push({
452
+ severity: 'error',
453
+ codeRef: 'IRC R602.6',
454
+ title: `Horizontal stud bore (${pen.holeSawIn}" hole, ${pen.borePctOfStud}% of stud) violates IRC R602.6`,
455
+ detail: `${run.name ?? run.id} bores horizontally through ${pen.memberLabel}${pen.wallId ? ` in wall ${pen.wallId}` : ''}${pen.note ? `: ${pen.note}` : '.'}`,
456
+ suggestedFix:
457
+ 'Reroute pipe below floor joists, through the top-plate chase, or upgrade to a 2x6 non-load-bearing wet wall / soffit chase.',
458
+ nodeIds: pen.wallId ? [run.id, pen.wallId] : [run.id],
459
+ })
460
+ }
461
+ }
462
+
370
463
  // DWV Drain checks
371
464
  if (system === 'dwv-drain') {
372
465
  lvlState.hasAnyDwvDrain = true
@@ -601,7 +694,8 @@ export function auditScenePlumbing(
601
694
  const wsfu = typeof run.wsfuLoad === 'number' ? run.wsfuLoad : 0
602
695
  if (wsfu > 0) {
603
696
  // Hot-water and hot-recirc lines never serve flushometer water closets/urinals
604
- const runFlushType = system === 'cold-water' ? flushType : 'flush-tank'
697
+ const bldgFlushType = getFlushTypeForBuilding(resolveNodeBuildingKey(nodes, run))
698
+ const runFlushType = system === 'cold-water' ? bldgFlushType : 'flush-tank'
605
699
  const gpm = wsfuToGpm(wsfu, runFlushType)
606
700
  const hyd = calculateSupplyHydraulics({
607
701
  gpm,
@@ -638,7 +732,8 @@ export function auditScenePlumbing(
638
732
  }
639
733
  const btuh = typeof run.gasBtuh === 'number' ? run.gasBtuh : 0
640
734
  const gasMat = material === 'csst' ? 'csst' : 'black-iron'
641
- const runLenFt = Math.max(IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthAuditFt, lengthFt)
735
+ const developedLenFt = gasDevelopedByRunId.get(run.id) ?? lengthFt
736
+ const runLenFt = Math.max(IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthAuditFt, developedLenFt)
642
737
  const gasLenEval = evaluatePlacementCandidate(
643
738
  [fuelGasMaxLenRule],
644
739
  {
@@ -662,9 +757,9 @@ export function auditScenePlumbing(
662
757
  severity: fuelGasMaxLenRule.severity,
663
758
  codeRef: sizing.codeRef,
664
759
  title: exceedsLen
665
- ? `Fuel gas run (${round2(lengthFt)} ft) exceeds ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft IFGC table limit`
760
+ ? `Fuel gas run (${round2(developedLenFt)} ft) exceeds ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft IFGC table limit`
666
761
  : `Fuel gas load (${Math.round(btuh / 1000)} kBTU/hr) exceeds max ${gasMat} table capacity`,
667
- detail: `${run.name ?? run.id} (${round2(lengthFt)} ft ${gasMat}) exceeds ${sizing.codeRef} limits (max ${Math.round(sizing.capacityBtuh / 1000)} kBTU/hr ${exceedsLen ? `at <= ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft` : `at ${round2(runLenFt)} ft`}).`,
762
+ detail: `${run.name ?? run.id} (${round2(developedLenFt)} ft developed ${gasMat}) exceeds ${sizing.codeRef} limits (max ${Math.round(sizing.capacityBtuh / 1000)} kBTU/hr ${exceedsLen ? `at <= ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft` : `at ${round2(runLenFt)} ft`}).`,
668
763
  suggestedFix: fuelGasMaxLenRule.suggestedFix,
669
764
  nodeIds: [run.id],
670
765
  })
@@ -673,7 +768,7 @@ export function auditScenePlumbing(
673
768
  severity: 'error',
674
769
  codeRef: sizing.codeRef,
675
770
  title: `Fuel gas pipe (${size}) undersized for ${Math.round(btuh / 1000)} kBTU/hr`,
676
- detail: `${run.name ?? run.id} (${round2(lengthFt)} ft ${gasMat}) requires at least ${sizing.recommendedSize}.`,
771
+ detail: `${run.name ?? run.id} (${round2(developedLenFt)} ft developed ${gasMat}) requires at least ${sizing.recommendedSize}.`,
677
772
  suggestedFix: `Upsize gas line to ${sizing.recommendedSize} per ${sizing.codeRef}.`,
678
773
  nodeIds: [run.id],
679
774
  })
@@ -682,8 +777,8 @@ export function auditScenePlumbing(
682
777
  push({
683
778
  severity: fuelGasMaxLenRule.severity,
684
779
  codeRef: fuelGasMaxLenRule.codeRef,
685
- title: `Fuel gas run (${round2(lengthFt)} ft) exceeds ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft IFGC table limit`,
686
- detail: `${run.name ?? run.id} (${round2(lengthFt)} ft ${gasMat}) exceeds ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft table limit.`,
780
+ title: `Fuel gas run (${round2(developedLenFt)} ft) exceeds ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft IFGC table limit`,
781
+ detail: `${run.name ?? run.id} (${round2(developedLenFt)} ft developed ${gasMat}) exceeds ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft table limit.`,
687
782
  suggestedFix: fuelGasMaxLenRule.suggestedFix,
688
783
  nodeIds: [run.id],
689
784
  })
@@ -800,11 +895,14 @@ export function auditScenePlumbing(
800
895
  }
801
896
  }
802
897
 
803
- // 4. Cross-Trade Electrical Coordination Checks (when an electrical panel exists in scene)
804
- if (hasElectricalPanel) {
898
+ // 4. Cross-Trade Electrical Coordination Checks (scoped per building when an electrical panel exists in that building)
899
+ if (buildingsWithElectricalPanel.size > 0) {
805
900
  const coord = buildElectricalCoordination(nodes)
806
901
  for (const row of coord) {
807
902
  if (!row.wired) {
903
+ const srcNode = nodes[row.sourceNodeId]
904
+ const srcBldgKey = srcNode ? resolveNodeBuildingKey(nodes, srcNode) : '__default_building__'
905
+ if (!buildingsWithElectricalPanel.has(srcBldgKey)) continue
808
906
  push({
809
907
  severity: 'warning',
810
908
  codeRef: 'NEC 210 / Cross-Trade Power',