@kruschdev/pascal-plugin-plumbing 0.0.0-stage → 0.3.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.
@@ -0,0 +1,927 @@
1
+ /**
2
+ * Live IPC / UPC / IFGC / IRC + NEC 110.26(E) & Cross-Trade Electrical Coordination Auditor (`src/ipc/audit.ts`).
3
+ * WeakMap-memoized per scene nodes object reference for zero-jank live React re-renders.
4
+ *
5
+ * Framework-free: zero React, Three.js, or `@pascal-app/*` imports.
6
+ */
7
+
8
+ import { evaluatePlacementCandidate, resolveLevelBuildingId } from '@kruschdev/pascal-mep-kernel'
9
+ import {
10
+ type BonesPlumbingContext,
11
+ type SceneNodeLike,
12
+ checkWetWallPipeFit,
13
+ computePipeFramingPenetrations,
14
+ extractBonesPlumbingContext,
15
+ getLowerWalledLevelIds,
16
+ resolveEffectiveWallThicknessM,
17
+ resolveNodeLevelId,
18
+ } from './framing-interop'
19
+ import {
20
+ type PlumbingObstacle,
21
+ type WallSegment2D,
22
+ countPathElbows,
23
+ detectPlumbingClashes,
24
+ extractPlumbingObstacles,
25
+ extractWallSegments,
26
+ measureDrainPathSlope,
27
+ polylineHorizontalLengthM,
28
+ polylineLengthM,
29
+ } from './routing'
30
+ import { IPC_RULE_THRESHOLDS, getIpcRuleById } from './rules'
31
+ import { buildElectricalCoordination } from './schedule'
32
+ import {
33
+ calculateSupplyHydraulics,
34
+ checkDryerVentRun,
35
+ checkTrapArmDistance,
36
+ computeFuelGasDevelopedLengths,
37
+ getMinRequiredDrainSlopeInPerFt,
38
+ sizeBuildingDrain,
39
+ sizeDrainBranch,
40
+ sizeFuelGasPipe,
41
+ wsfuToGpm,
42
+ } from './sizing'
43
+ import {
44
+ type CodeEdition,
45
+ FIXTURE_SPECS,
46
+ type FixtureKind,
47
+ METERS_TO_FEET,
48
+ METERS_TO_INCHES,
49
+ type OccupancyType,
50
+ PIPE_NOMINAL_INCHES,
51
+ type PipeMaterial,
52
+ type PipeNominalSize,
53
+ type PlumbingSystem,
54
+ comparePipeSizes,
55
+ getPipeOuterDiameterM,
56
+ round2,
57
+ } from './tables'
58
+
59
+ export type PlumbingAuditSeverity = 'error' | 'warning' | 'info'
60
+
61
+ export type PlumbingAuditFinding = {
62
+ id: string
63
+ severity: PlumbingAuditSeverity
64
+ codeRef: string
65
+ title: string
66
+ detail: string
67
+ suggestedFix: string
68
+ nodeIds: string[]
69
+ }
70
+
71
+ export type PlumbingAuditResult = {
72
+ codeEdition: CodeEdition
73
+ errorCount: number
74
+ warningCount: number
75
+ infoCount: number
76
+ findings: PlumbingAuditFinding[]
77
+ }
78
+
79
+ const auditCache = new WeakMap<Readonly<Record<string, SceneNodeLike>>, Map<string, PlumbingAuditResult>>()
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
+
95
+ export function auditScenePlumbing(
96
+ nodes: Readonly<Record<string, SceneNodeLike>>,
97
+ options: { codeEdition?: CodeEdition; occupancy?: OccupancyType } = {},
98
+ ): PlumbingAuditResult {
99
+ const codeEdition = options.codeEdition ?? 'IPC-2021'
100
+ const cacheKey = `${codeEdition}|${options.occupancy ?? '__auto__'}`
101
+
102
+ let byEdition = auditCache.get(nodes)
103
+ if (!byEdition) {
104
+ byEdition = new Map()
105
+ auditCache.set(nodes, byEdition)
106
+ }
107
+ const cached = byEdition.get(cacheKey)
108
+ if (cached) return cached
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
+
125
+ const findings: PlumbingAuditFinding[] = []
126
+ let seq = 1
127
+ const push = (f: Omit<PlumbingAuditFinding, 'id'>) => {
128
+ findings.push({ id: `ipc_finding_${seq++}`, ...f })
129
+ }
130
+
131
+ const equipment = all.filter((n) => n.type === 'plumbing:equipment')
132
+ const pipeRuns = all.filter((n) => n.type === 'plumbing:pipe-run')
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
+ }
139
+
140
+ // Per-level spatial context caches so multi-story scenes never mix level-local coordinates across floors
141
+ const wallsByLevel = new Map<string, WallSegment2D[]>()
142
+ const wallMapByLevel = new Map<string, Map<string, WallSegment2D>>()
143
+ const bonesByLevel = new Map<string, BonesPlumbingContext>()
144
+ const obstaclesByLevel = new Map<string, PlumbingObstacle[]>()
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
+ }
155
+ const getWallMapForLevel = (lvlId: string | null): Map<string, WallSegment2D> => {
156
+ const key = lvlId ?? '__all__'
157
+ let m = wallMapByLevel.get(key)
158
+ if (!m) {
159
+ m = new Map(getWallsForLevel(lvlId).map((w) => [w.id, w]))
160
+ wallMapByLevel.set(key, m)
161
+ }
162
+ return m
163
+ }
164
+ const getBonesForLevel = (lvlId: string | null): BonesPlumbingContext => {
165
+ const key = lvlId ?? '__all__'
166
+ let ctx = bonesByLevel.get(key)
167
+ if (!ctx) {
168
+ ctx = extractBonesPlumbingContext(nodes, lvlId)
169
+ bonesByLevel.set(key, ctx)
170
+ }
171
+ return ctx
172
+ }
173
+ const getObstaclesForLevel = (lvlId: string | null): PlumbingObstacle[] => {
174
+ const key = lvlId ?? '__all__'
175
+ let obs = obstaclesByLevel.get(key)
176
+ if (!obs) {
177
+ obs = extractPlumbingObstacles(nodes, lvlId)
178
+ obstaclesByLevel.set(key, obs)
179
+ }
180
+ return obs
181
+ }
182
+
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
+ }
191
+
192
+ for (const fix of fixtures) {
193
+ const kind = (fix.fixtureKind as FixtureKind) || 'lavatory'
194
+ if (kind === 'hose-bibb' && fix.hasVacuumBreaker === false) {
195
+ push({
196
+ severity: 'error',
197
+ codeRef: 'IPC 608.15.4.2',
198
+ title: 'Hose bibb missing anti-siphon vacuum breaker',
199
+ detail: `${fix.name ?? fix.id} has no backflow/vacuum breaker protection.`,
200
+ suggestedFix: 'Enable frost-proof anti-siphon vacuum breaker on exterior hose bibb.',
201
+ nodeIds: [fix.id],
202
+ })
203
+ }
204
+ const spec = FIXTURE_SPECS[kind]
205
+ if (spec?.needsPTrap && fix.hasPTrap === false) {
206
+ push({
207
+ severity: 'error',
208
+ codeRef: 'IPC 1002.1',
209
+ title: 'Drain fixture missing P-trap',
210
+ detail: `${fix.name ?? fix.id} requires a dedicated trap to block sewer gas.`,
211
+ suggestedFix: `Install ${spec.minTrapIn ?? '1-1/2"'} P-trap at fixture outlet.`,
212
+ nodeIds: [fix.id],
213
+ })
214
+ }
215
+ }
216
+
217
+ // 2. Equipment-level checks (Water Heaters, HPWH clearance, Expansion Tank, T&P, Drain Pan)
218
+ for (const eq of equipment) {
219
+ const kind = String(eq.equipmentKind ?? '')
220
+ const isWaterHeater = kind.startsWith('water-heater-')
221
+ if (isWaterHeater) {
222
+ const eqBldgKey = resolveNodeBuildingKey(nodes, eq)
223
+ if (
224
+ eq.hasExpansionTank === false &&
225
+ !buildingsWithExpansionTank.has(eqBldgKey) &&
226
+ buildingsWithMainShutoff.has(eqBldgKey)
227
+ ) {
228
+ push({
229
+ severity: 'warning',
230
+ codeRef: 'IPC 607.3',
231
+ title: 'Closed domestic system missing thermal expansion tank',
232
+ detail: `${eq.name ?? eq.id} is downstream of a PRV/check valve without an expansion tank.`,
233
+ suggestedFix: 'Add a 2 gal (<= 50 gal WH) or 4.5 gal (> 50 gal WH) expansion tank on cold inlet.',
234
+ nodeIds: [eq.id],
235
+ })
236
+ }
237
+ if (eq.hasTpDischarge === false) {
238
+ push({
239
+ severity: 'error',
240
+ codeRef: 'IPC 504.6',
241
+ title: 'Water heater missing T&P relief discharge pipe',
242
+ detail: `${eq.name ?? eq.id} requires a full-size 3/4" copper/CPVC T&P discharge line to exterior or approved drain.`,
243
+ suggestedFix: 'Route 3/4" T&P discharge line downward to within 6" of floor/exterior.',
244
+ nodeIds: [eq.id],
245
+ })
246
+ }
247
+ if (eq.hasDrainPan === false) {
248
+ push({
249
+ severity: 'warning',
250
+ codeRef: 'IPC 504.7',
251
+ title: 'Water heater missing drain pan',
252
+ detail: `${eq.name ?? eq.id} has no safety drain pan configured.`,
253
+ suggestedFix: 'Install a >= 1.5" deep drain pan with 3/4" drain line where leakage could cause damage.',
254
+ nodeIds: [eq.id],
255
+ })
256
+ }
257
+ if (kind === 'water-heater-hpwh' && typeof eq.roomVolumeCuFt === 'number' && eq.roomVolumeCuFt < 700) {
258
+ push({
259
+ severity: 'warning',
260
+ codeRef: 'Manufacturer / IMC 304',
261
+ title: 'Heat pump water heater room < 700 cu ft',
262
+ detail: `${eq.name ?? eq.id} room volume (${eq.roomVolumeCuFt} cu ft) is below the 700 cu ft unconditioned air minimum.`,
263
+ suggestedFix: 'Relocate HPWH to garage/larger room or add louvered door / ducted intake.',
264
+ nodeIds: [eq.id],
265
+ })
266
+ }
267
+ }
268
+ }
269
+
270
+ // 3. Pipe-run checks (DWV slope, sanitary tee, trap arm, vent flood rim, wet-wall 2x6, velocity, gas, dryer vent, clashes)
271
+ const ventedFixtureIds = new Set<string>()
272
+ for (const r of pipeRuns) {
273
+ if (r.system === 'dwv-vent' && typeof r.sourceNodeId === 'string') {
274
+ ventedFixtureIds.add(r.sourceNodeId)
275
+ }
276
+ }
277
+
278
+ const wcCountByLevel = new Map<string, number>()
279
+ for (const fix of fixtures) {
280
+ if (fix.fixtureKind === 'water-closet') {
281
+ const lvlKey = resolveNodeLevelId(nodes, fix) ?? '__root__'
282
+ wcCountByLevel.set(lvlKey, (wcCountByLevel.get(lvlKey) ?? 0) + 1)
283
+ }
284
+ }
285
+
286
+ const dwvStateByLevel = new Map<
287
+ string,
288
+ { hasAnyDwvDrain: boolean; hasAnyCleanout: boolean; hasMainVentStack: boolean; sampleDrainIds: string[] }
289
+ >()
290
+ const getLevelDwvState = (lvlKey: string) => {
291
+ let st = dwvStateByLevel.get(lvlKey)
292
+ if (!st) {
293
+ st = { hasAnyDwvDrain: false, hasAnyCleanout: false, hasMainVentStack: false, sampleDrainIds: [] }
294
+ dwvStateByLevel.set(lvlKey, st)
295
+ }
296
+ return st
297
+ }
298
+
299
+ const drainSlopeSmallRule = getIpcRuleById('ipc-704-1-drain-slope-small')
300
+ const drainSlopeLargeRule = getIpcRuleById('ipc-704-1-drain-slope-large')
301
+ const dryVentHeightRule = getIpcRuleById('ipc-905-5-dry-vent-height')
302
+ const mainVentStackRule = getIpcRuleById('ipc-903-1-main-vent-stack')
303
+ const cleanoutIntervalRule = getIpcRuleById('ipc-708-1-cleanout-interval')
304
+ const wetWallFitRule = getIpcRuleById('irc-r602-6-wet-wall-fit')
305
+ const dryerVentRule = getIpcRuleById('irc-m1502-4-dryer-vent')
306
+ const dryerVentMaterialRule = getIpcRuleById('irc-m1502-4-1-dryer-vent-material')
307
+ const fuelGasMaxLenRule = getIpcRuleById('ifgc-402-4-fuel-gas-max-len')
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
+
325
+ for (const run of pipeRuns) {
326
+ const system = (run.system as PlumbingSystem) || 'cold-water'
327
+ const material = (run.material as PipeMaterial) || 'pex-a'
328
+ const size = (run.nominalSize as PipeNominalSize) || '1/2"'
329
+ const nominalIn = PIPE_NOMINAL_INCHES[size] ?? 0.5
330
+ const path = Array.isArray(run.path)
331
+ ? (run.path as ReadonlyArray<readonly [number, number, number]>)
332
+ : []
333
+ const runAnchorPos: readonly [number, number, number] = path[0] ?? [0, 0, 0]
334
+ const lengthFt = polylineLengthM(path) * METERS_TO_FEET
335
+ const pipeRadiusM = getPipeOuterDiameterM(size, material) / 2
336
+ const runLevelId = resolveNodeLevelId(nodes, run)
337
+ const runLevelKey = runLevelId ?? '__root__'
338
+ const lvlState = getLevelDwvState(runLevelKey)
339
+
340
+ if (run.hasCleanout === true) lvlState.hasAnyCleanout = true
341
+ if (run.isMainVentStack === true) {
342
+ lvlState.hasMainVentStack = true
343
+ const stackEval = evaluatePlacementCandidate(
344
+ [mainVentStackRule],
345
+ {
346
+ id: run.id,
347
+ kind: 'plumbing:pipe-run',
348
+ system: 'dwv-main-vent-stack',
349
+ pos: runAnchorPos,
350
+ nominalSizeIn: nominalIn,
351
+ },
352
+ 'audit',
353
+ )
354
+ if (!stackEval.legal) {
355
+ push({
356
+ severity: mainVentStackRule.severity,
357
+ codeRef: mainVentStackRule.codeRef,
358
+ title: `Main vent stack (${size}) below ${IPC_RULE_THRESHOLDS.mainVentStackMinNominalIn}" minimum diameter`,
359
+ detail: `${run.name ?? run.id} is marked as a main vent stack but is sized ${size} instead of at least ${IPC_RULE_THRESHOLDS.mainVentStackMinNominalIn}".`,
360
+ suggestedFix: mainVentStackRule.suggestedFix,
361
+ nodeIds: [run.id],
362
+ })
363
+ }
364
+ }
365
+
366
+ // Structural & NEC 110.26(E) obstacle clashes (strictly same-level, deduplicated by base obstacle nodeId)
367
+ if (path.length >= 2) {
368
+ const clashes = detectPlumbingClashes(path, getObstaclesForLevel(runLevelId), pipeRadiusM)
369
+ const reportedObsIds = new Set<string>()
370
+ for (const obs of clashes) {
371
+ const obsNodeId = obs.nodeId ?? obs.id.replace(/:seg\d+$/, '')
372
+ if (reportedObsIds.has(obsNodeId)) continue
373
+ reportedObsIds.add(obsNodeId)
374
+ if (obs.category === 'electrical-dedicated-space') {
375
+ push({
376
+ severity: 'error',
377
+ codeRef: 'NEC 110.26(E)',
378
+ title: 'Plumbing pipe invades electrical panel dedicated overhead space',
379
+ detail: `${run.name ?? run.id} passes directly above ${obs.label}.`,
380
+ suggestedFix: 'Reroute pipe horizontally clear of the electrical panel footprint or install drip-shield protection above structural ceiling.',
381
+ nodeIds: [run.id, obsNodeId],
382
+ })
383
+ } else {
384
+ push({
385
+ severity: 'error',
386
+ codeRef: 'IRC R602 / Structural',
387
+ title: 'Pipe run collides with structural member',
388
+ detail: `${run.name ?? run.id} intersects ${obs.label}.`,
389
+ suggestedFix: 'Offset pipe around structural beam or column; never cut primary structural members.',
390
+ nodeIds: [run.id, obsNodeId],
391
+ })
392
+ }
393
+ }
394
+ }
395
+
396
+ // Wet-wall cavity check (2x4 vs 2x6 for >= 3" DWV, honoring Bones/Structural load-bearing overrides)
397
+ const levelWallMap = getWallMapForLevel(runLevelId)
398
+ const levelWalls = getWallsForLevel(runLevelId)
399
+ const bonesCtx = getBonesForLevel(runLevelId)
400
+ if (typeof run.wallId === 'string' && levelWallMap.has(run.wallId)) {
401
+ const wall = levelWallMap.get(run.wallId)!
402
+ const wallRule = bonesCtx.wallRules.get(wall.id)
403
+ const effectiveWallThicknessM = resolveEffectiveWallThicknessM(wall.thicknessM, bonesCtx, wallRule)
404
+ const declarativeWallFit = evaluatePlacementCandidate(
405
+ [wetWallFitRule],
406
+ {
407
+ id: run.id,
408
+ kind: 'plumbing:pipe-run',
409
+ system,
410
+ pos: runAnchorPos,
411
+ nominalSizeIn: nominalIn,
412
+ wallThicknessM: effectiveWallThicknessM,
413
+ },
414
+ 'audit',
415
+ )
416
+ const fit = checkWetWallPipeFit({
417
+ wallThicknessM: effectiveWallThicknessM,
418
+ pipeSize: size,
419
+ material,
420
+ isLoadBearing: wallRule?.isLoadBearing ?? false,
421
+ })
422
+ if (!declarativeWallFit.legal || !fit.fits) {
423
+ const reason = fit.reason ?? declarativeWallFit.violations[0]?.message ?? wetWallFitRule.title
424
+ push({
425
+ severity: wetWallFitRule.severity,
426
+ codeRef: !fit.fits ? fit.codeRef : wetWallFitRule.codeRef,
427
+ title: `Wet wall too thin for ${size} ${material.toUpperCase()} pipe`,
428
+ detail: `${run.name ?? run.id} inside wall ${wall.id}: ${reason}`,
429
+ suggestedFix: wetWallFitRule.suggestedFix,
430
+ nodeIds: [run.id, wall.id],
431
+ })
432
+ }
433
+ }
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
+
463
+ // DWV Drain checks
464
+ if (system === 'dwv-drain') {
465
+ lvlState.hasAnyDwvDrain = true
466
+ if (lvlState.sampleDrainIds.length < 1) lvlState.sampleDrainIds.push(run.id)
467
+
468
+ // IPC Table 710.1(1) / 710.1(2) DFU & water-closet drain sizing check
469
+ const slopeInfo = path.length >= 2 ? measureDrainPathSlope(path) : null
470
+ const dfuLoad = typeof run.dfuLoad === 'number' && run.dfuLoad > 0 ? run.dfuLoad : 0
471
+ const srcNode = typeof run.sourceNodeId === 'string' ? nodes[run.sourceNodeId] : undefined
472
+ const isMainBuildingDrain =
473
+ Boolean(srcNode?.type === 'plumbing:pipe-run' && srcNode.isMainVentStack === true) ||
474
+ /building drain|main drain/i.test(String(run.name ?? ''))
475
+ const servesWaterCloset = Boolean(
476
+ srcNode?.type === 'plumbing:fixture' && srcNode.fixtureKind === 'water-closet',
477
+ )
478
+ const levelWcCount = (() => {
479
+ if (typeof run.waterClosetCount === 'number' && Number.isFinite(run.waterClosetCount)) {
480
+ return Math.max(0, Math.round(run.waterClosetCount))
481
+ }
482
+ let count = wcCountByLevel.get(runLevelKey) ?? 0
483
+ if (runLevelKey !== '__root__') {
484
+ for (const [otherLvl, otherWcs] of wcCountByLevel.entries()) {
485
+ if (otherLvl !== runLevelKey && otherLvl !== '__root__' && getLowerWalledLevelIds(nodes, otherLvl).includes(runLevelKey)) {
486
+ count += otherWcs
487
+ }
488
+ }
489
+ }
490
+ return count
491
+ })()
492
+ if (isMainBuildingDrain && (dfuLoad > 0 || levelWcCount > 0)) {
493
+ const rawSlopeInPerFt =
494
+ typeof run.slopeInPerFt === 'number' && run.slopeInPerFt > 0
495
+ ? run.slopeInPerFt
496
+ : (slopeInfo?.overallSlopeInPerFt ?? 0.25)
497
+ const effectiveSlope: 0.125 | 0.25 | 0.5 =
498
+ rawSlopeInPerFt < 0.25 ? 0.125 : rawSlopeInPerFt >= 0.5 ? 0.5 : 0.25
499
+ const drainSizing = sizeBuildingDrain({
500
+ totalDfu: dfuLoad,
501
+ slopeInPerFt: effectiveSlope,
502
+ hasWaterCloset: levelWcCount > 0,
503
+ waterClosetCount: levelWcCount,
504
+ codeEdition,
505
+ })
506
+ if (comparePipeSizes(size, drainSizing.recommendedSize) < 0 || dfuLoad > drainSizing.maxAllowedDfuAtSize) {
507
+ push({
508
+ severity: 'error',
509
+ codeRef: drainSizing.codeRef,
510
+ title: `Building drain (${size}) undersized for ${dfuLoad} DFU`,
511
+ detail: `${run.name ?? run.id} (${size} carrying ${dfuLoad} DFU${levelWcCount > 0 ? `, ${levelWcCount} WC(s)` : ''}) requires at least ${drainSizing.recommendedSize} (max ${drainSizing.maxAllowedDfuAtSize} DFU).`,
512
+ suggestedFix: `Upsize building drain to at least ${drainSizing.recommendedSize} per ${drainSizing.codeRef}.`,
513
+ nodeIds: [run.id],
514
+ })
515
+ }
516
+ } else if (!isMainBuildingDrain && (dfuLoad > 0 || servesWaterCloset)) {
517
+ const drainSizing = sizeDrainBranch({
518
+ dfu: dfuLoad,
519
+ hasWaterCloset: servesWaterCloset,
520
+ waterClosetCount: servesWaterCloset ? 1 : 0,
521
+ codeEdition,
522
+ })
523
+ if (comparePipeSizes(size, drainSizing.recommendedSize) < 0 || dfuLoad > drainSizing.maxAllowedDfuAtSize) {
524
+ push({
525
+ severity: 'error',
526
+ codeRef: drainSizing.codeRef,
527
+ title: servesWaterCloset && comparePipeSizes(size, '3"') < 0
528
+ ? `Water closet drain (${size}) below 3" minimum`
529
+ : `DWV drain branch (${size}) undersized for ${dfuLoad} DFU`,
530
+ detail: `${run.name ?? run.id} (${size}, ${dfuLoad} DFU${servesWaterCloset ? ', serves water closet' : ''}) requires at least ${drainSizing.recommendedSize}.`,
531
+ suggestedFix: `Upsize horizontal drain branch to at least ${drainSizing.recommendedSize} per ${drainSizing.codeRef}.`,
532
+ nodeIds: [run.id],
533
+ })
534
+ }
535
+ }
536
+
537
+ const requiredSlope = getMinRequiredDrainSlopeInPerFt(size)
538
+ const isLargeDrain = requiredSlope <= IPC_RULE_THRESHOLDS.drainSlopeLargeInPerFt
539
+ const slopeRule = isLargeDrain ? drainSlopeLargeRule : drainSlopeSmallRule
540
+ const minSlope = slopeRule.params.minSlopeInPerFt!
541
+ if (slopeInfo) {
542
+ if (slopeInfo.hasUphillSegment) {
543
+ push({
544
+ severity: slopeRule.severity,
545
+ codeRef: slopeRule.codeRef,
546
+ title: 'DWV drain routes uphill (gravity flow violated)',
547
+ detail: `${run.name ?? run.id} contains an upward-sloping drainage segment.`,
548
+ suggestedFix: `Re-slope drain continuously downward at >= ${minSlope}"/ft toward the building drain.`,
549
+ nodeIds: [run.id],
550
+ })
551
+ } else if (slopeInfo.horizontalSegments > 0) {
552
+ const slopeEval = evaluatePlacementCandidate(
553
+ [slopeRule],
554
+ {
555
+ id: run.id,
556
+ kind: 'plumbing:pipe-run',
557
+ system: isLargeDrain ? 'dwv-drain-large' : 'dwv-drain-small',
558
+ pos: runAnchorPos,
559
+ slopeInPerFt: slopeInfo.minSegmentSlopeInPerFt + 0.01,
560
+ },
561
+ 'audit',
562
+ )
563
+ if (!slopeEval.legal) {
564
+ push({
565
+ severity: slopeRule.severity,
566
+ codeRef: 'IPC Table 704.1',
567
+ title: `DWV drain slope below ${minSlope}"/ft minimum`,
568
+ detail: `${run.name ?? run.id} (${size}) measures ${slopeInfo.minSegmentSlopeInPerFt}"/ft (requires >= ${minSlope}"/ft).`,
569
+ suggestedFix: `Increase downward pitch to at least ${minSlope}"/ft (${minSlope === 0.25 ? '2.08%' : '1.04%'}).`,
570
+ nodeIds: [run.id],
571
+ })
572
+ }
573
+ }
574
+ }
575
+
576
+ if (run.isHorizontalSanTee === true) {
577
+ push({
578
+ severity: 'error',
579
+ codeRef: 'IPC Table 706.3',
580
+ title: 'Sanitary tee prohibited on horizontal drainage turn',
581
+ detail: `${run.name ?? run.id} uses a sanitary tee for horizontal-to-horizontal or vertical-to-horizontal drainage.`,
582
+ suggestedFix: 'Replace sanitary tee with a 45° wye + eighth bend (combo) or long-sweep 90° elbow.',
583
+ nodeIds: [run.id],
584
+ })
585
+ }
586
+
587
+ let effectiveTrapArmFt: number | null =
588
+ typeof run.trapArmLengthFt === 'number' && run.trapArmLengthFt > 0 ? run.trapArmLengthFt : null
589
+ if (effectiveTrapArmFt === null && typeof run.sourceNodeId === 'string' && path.length >= 2) {
590
+ const src = nodes[run.sourceNodeId]
591
+ if (src && src.type === 'plumbing:fixture' && !ventedFixtureIds.has(src.id)) {
592
+ const srcKind = (src.fixtureKind as FixtureKind) || 'lavatory'
593
+ if (FIXTURE_SPECS[srcKind]?.needsPTrap) {
594
+ const horizFt = round2(polylineHorizontalLengthM(path) * METERS_TO_FEET)
595
+ if (horizFt > 0.25) effectiveTrapArmFt = horizFt
596
+ }
597
+ }
598
+ }
599
+ if (effectiveTrapArmFt !== null) {
600
+ const trapCheck = checkTrapArmDistance(size, effectiveTrapArmFt)
601
+ if (!trapCheck.ok) {
602
+ push({
603
+ severity: 'error',
604
+ codeRef: trapCheck.codeRef,
605
+ title: `Trap-arm length (${trapCheck.distanceFt} ft) exceeds ${trapCheck.maxAllowedFt} ft max`,
606
+ detail: `${run.name ?? run.id} (${size}) exceeds maximum developed distance from trap weir to vent.`,
607
+ suggestedFix: 'Move vent closer to trap, add an AAV (IPC 918), or upsize trap arm.',
608
+ nodeIds: [run.id],
609
+ })
610
+ }
611
+ }
612
+
613
+ const cleanoutEval = evaluatePlacementCandidate(
614
+ [cleanoutIntervalRule],
615
+ {
616
+ id: run.id,
617
+ kind: 'plumbing:pipe-run',
618
+ system: 'dwv-drain',
619
+ pos: runAnchorPos,
620
+ runLengthFt: lengthFt,
621
+ hasCleanout: Boolean(run.hasCleanout),
622
+ },
623
+ 'audit',
624
+ )
625
+ if (!cleanoutEval.legal) {
626
+ push({
627
+ severity: cleanoutIntervalRule.severity,
628
+ codeRef: cleanoutIntervalRule.codeRef,
629
+ title: `Building drain > ${IPC_RULE_THRESHOLDS.cleanoutMaxIntervalFt} ft without intermediate cleanout`,
630
+ detail: `${run.name ?? run.id} spans ${round2(lengthFt)} ft without a cleanout.`,
631
+ suggestedFix: cleanoutIntervalRule.suggestedFix,
632
+ nodeIds: [run.id],
633
+ })
634
+ }
635
+ }
636
+
637
+ // Vent flood-level rim check (IPC 905.5 — single-source declarative rule)
638
+ if (system === 'dwv-vent' && !run.isMainVentStack && typeof run.sourceNodeId === 'string') {
639
+ const src = nodes[run.sourceNodeId]
640
+ if (src && src.type === 'plumbing:fixture' && path.length >= 2) {
641
+ const kind = (src.fixtureKind as FixtureKind) || 'lavatory'
642
+ const floodRimM = FIXTURE_SPECS[kind]?.floodRimHeightM ?? 0.85
643
+ const minHorizontalVentY = floodRimM + IPC_RULE_THRESHOLDS.ventMinAboveFloodRimM
644
+ for (let i = 1; i < path.length; i++) {
645
+ const a = path[i - 1]!
646
+ const b = path[i]!
647
+ const horiz = Math.hypot(b[0] - a[0], b[2] - a[2])
648
+ if (horiz > 0.25) {
649
+ const segMinY = Math.min(a[1], b[1])
650
+ const ventEval = evaluatePlacementCandidate(
651
+ [dryVentHeightRule],
652
+ {
653
+ id: run.id,
654
+ kind: 'dwv-vent',
655
+ pos: [a[0], segMinY + 0.005, a[2]],
656
+ floodRimM,
657
+ },
658
+ 'audit',
659
+ )
660
+ if (!ventEval.legal) {
661
+ push({
662
+ severity: dryVentHeightRule.severity,
663
+ codeRef: dryVentHeightRule.codeRef,
664
+ title: dryVentHeightRule.title,
665
+ detail: `${run.name ?? run.id} runs horizontally at ${(segMinY * METERS_TO_INCHES).toFixed(1)}" AFF (minimum ${(minHorizontalVentY * METERS_TO_INCHES).toFixed(1)}" AFF).`,
666
+ suggestedFix: dryVentHeightRule.suggestedFix,
667
+ nodeIds: [run.id, src.id],
668
+ })
669
+ break
670
+ }
671
+ }
672
+ }
673
+ }
674
+ }
675
+
676
+ // Domestic water supply material & velocity checks
677
+ if (system === 'cold-water' || system === 'hot-water' || system === 'hot-recirc') {
678
+ if (material === 'pvc-dwv' || material === 'abs-dwv' || material === 'cast-iron') {
679
+ push({
680
+ severity: 'error',
681
+ codeRef: 'IPC 605.4',
682
+ title: `Non-potable DWV pipe material (${material.toUpperCase()}) used for domestic water`,
683
+ detail: `${run.name ?? run.id} uses ${material} for pressurized ${system} distribution.`,
684
+ suggestedFix: 'Switch domestic water piping to PEX-A, PEX-B, Type L/M copper, or CPVC per IPC 605.4.',
685
+ nodeIds: [run.id],
686
+ })
687
+ } else if (
688
+ material === 'pex-a' ||
689
+ material === 'pex-b' ||
690
+ material === 'copper-l' ||
691
+ material === 'copper-m' ||
692
+ material === 'cpvc'
693
+ ) {
694
+ const wsfu = typeof run.wsfuLoad === 'number' ? run.wsfuLoad : 0
695
+ if (wsfu > 0) {
696
+ // Hot-water and hot-recirc lines never serve flushometer water closets/urinals
697
+ const bldgFlushType = getFlushTypeForBuilding(resolveNodeBuildingKey(nodes, run))
698
+ const runFlushType = system === 'cold-water' ? bldgFlushType : 'flush-tank'
699
+ const gpm = wsfuToGpm(wsfu, runFlushType)
700
+ const hyd = calculateSupplyHydraulics({
701
+ gpm,
702
+ size,
703
+ material,
704
+ isHot: system === 'hot-water' || system === 'hot-recirc',
705
+ lengthFt: Math.max(10, lengthFt),
706
+ })
707
+ if (!hyd.velocityOk) {
708
+ push({
709
+ severity: 'warning',
710
+ codeRef: hyd.codeRef,
711
+ title: `Water supply velocity (${hyd.velocityFps} ft/s) exceeds ${hyd.maxVelocityFps} ft/s limit`,
712
+ detail: `${run.name ?? run.id} (${size} ${material.toUpperCase()} carrying ${wsfu} WSFU / ${hyd.gpm} GPM) risks erosion-corrosion and water hammer.`,
713
+ suggestedFix: 'Upsize supply pipe one nominal trade size to keep velocity within code limits.',
714
+ nodeIds: [run.id],
715
+ })
716
+ }
717
+ }
718
+ }
719
+ }
720
+
721
+ // Fuel Gas (IFGC 402.4 / 403 / 408.4 / 409.5 — single-source declarative max length & unified sizing floor)
722
+ if (system === 'fuel-gas') {
723
+ if (material !== 'black-iron' && material !== 'csst' && material !== 'copper-l') {
724
+ push({
725
+ severity: 'error',
726
+ codeRef: 'IFGC 403',
727
+ title: `Unapproved material (${material.toUpperCase()}) for indoor fuel gas piping`,
728
+ detail: `${run.name ?? run.id} uses ${material} instead of Schedule 40 black iron or listed CSST.`,
729
+ suggestedFix: 'Switch indoor fuel-gas piping to Schedule 40 black-iron or listed CSST per IFGC 403.',
730
+ nodeIds: [run.id],
731
+ })
732
+ }
733
+ const btuh = typeof run.gasBtuh === 'number' ? run.gasBtuh : 0
734
+ const gasMat = material === 'csst' ? 'csst' : 'black-iron'
735
+ const developedLenFt = gasDevelopedByRunId.get(run.id) ?? lengthFt
736
+ const runLenFt = Math.max(IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthAuditFt, developedLenFt)
737
+ const gasLenEval = evaluatePlacementCandidate(
738
+ [fuelGasMaxLenRule],
739
+ {
740
+ id: run.id,
741
+ kind: 'plumbing:pipe-run',
742
+ system: 'fuel-gas',
743
+ pos: runAnchorPos,
744
+ effectiveLengthFt: runLenFt,
745
+ },
746
+ 'audit',
747
+ )
748
+ if (btuh > 0) {
749
+ const sizing = sizeFuelGasPipe({
750
+ totalBtuh: btuh,
751
+ longestRunFt: runLenFt,
752
+ material: gasMat,
753
+ })
754
+ if (!sizing.ok || !gasLenEval.legal) {
755
+ const exceedsLen = !gasLenEval.legal || runLenFt > IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt
756
+ push({
757
+ severity: fuelGasMaxLenRule.severity,
758
+ codeRef: sizing.codeRef,
759
+ title: exceedsLen
760
+ ? `Fuel gas run (${round2(developedLenFt)} ft) exceeds ${IPC_RULE_THRESHOLDS.fuelGasMaxEffectiveLengthFt} ft IFGC table limit`
761
+ : `Fuel gas load (${Math.round(btuh / 1000)} kBTU/hr) exceeds max ${gasMat} table capacity`,
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`}).`,
763
+ suggestedFix: fuelGasMaxLenRule.suggestedFix,
764
+ nodeIds: [run.id],
765
+ })
766
+ } else if (comparePipeSizes(size, sizing.recommendedSize) < 0) {
767
+ push({
768
+ severity: 'error',
769
+ codeRef: sizing.codeRef,
770
+ title: `Fuel gas pipe (${size}) undersized for ${Math.round(btuh / 1000)} kBTU/hr`,
771
+ detail: `${run.name ?? run.id} (${round2(developedLenFt)} ft developed ${gasMat}) requires at least ${sizing.recommendedSize}.`,
772
+ suggestedFix: `Upsize gas line to ${sizing.recommendedSize} per ${sizing.codeRef}.`,
773
+ nodeIds: [run.id],
774
+ })
775
+ }
776
+ } else if (!gasLenEval.legal) {
777
+ push({
778
+ severity: fuelGasMaxLenRule.severity,
779
+ codeRef: fuelGasMaxLenRule.codeRef,
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.`,
782
+ suggestedFix: fuelGasMaxLenRule.suggestedFix,
783
+ nodeIds: [run.id],
784
+ })
785
+ }
786
+ if (run.hasSedimentTrap === false) {
787
+ push({
788
+ severity: 'error',
789
+ codeRef: 'IFGC 408.4',
790
+ title: 'Fuel gas appliance connection missing sediment trap (drip leg)',
791
+ detail: `${run.name ?? run.id} lacks a sediment trap downstream of the appliance shutoff valve.`,
792
+ suggestedFix: 'Install a vertical tee and >= 3" capped nipple sediment trap ahead of the appliance inlet.',
793
+ nodeIds: [run.id],
794
+ })
795
+ }
796
+ if (run.hasShutoffWithin6Ft === false) {
797
+ push({
798
+ severity: 'error',
799
+ codeRef: 'IFGC 409.5',
800
+ title: 'Fuel gas appliance missing shutoff valve within 6 ft',
801
+ detail: `${run.name ?? run.id} does not indicate an accessible shutoff valve within 6 ft of the appliance.`,
802
+ suggestedFix: 'Install an approved quarter-turn gas shutoff valve in the same room within 6 ft.',
803
+ nodeIds: [run.id],
804
+ })
805
+ }
806
+ }
807
+
808
+ // Dryer Vent (IRC M1502.4 / M1502.4.1 / M1502.4.2 — single-source declarative rules)
809
+ if (system === 'dryer-vent') {
810
+ if (nominalIn < 4) {
811
+ push({
812
+ severity: 'error',
813
+ codeRef: 'IRC M1502.4.2',
814
+ title: `Dryer exhaust duct (${size}) below 4" minimum diameter`,
815
+ detail: `${run.name ?? run.id} is sized ${size} instead of the required 4" nominal diameter.`,
816
+ suggestedFix: 'Upsize dryer exhaust duct to 4" nominal smooth rigid metal per IRC M1502.4.2.',
817
+ nodeIds: [run.id],
818
+ })
819
+ }
820
+ const { elbows90, elbows45 } = countPathElbows(path)
821
+ const check = checkDryerVentRun({ lengthFt, elbows90, elbows45 })
822
+ const dryerEval = evaluatePlacementCandidate(
823
+ [dryerVentRule, dryerVentMaterialRule],
824
+ {
825
+ id: run.id,
826
+ kind: 'plumbing:pipe-run',
827
+ system: 'dryer-vent',
828
+ pos: runAnchorPos,
829
+ effectiveLengthFt: check.effectiveLengthFt,
830
+ material,
831
+ },
832
+ 'audit',
833
+ )
834
+ const lenViol = dryerEval.violations.find((v) => v.ruleId === dryerVentRule.id)
835
+ const matViol = dryerEval.violations.find((v) => v.ruleId === dryerVentMaterialRule.id)
836
+ if (lenViol) {
837
+ push({
838
+ severity: dryerVentRule.severity,
839
+ codeRef: dryerVentRule.codeRef,
840
+ title: `Dryer vent effective length (${check.effectiveLengthFt} ft) exceeds ${IPC_RULE_THRESHOLDS.dryerVentMaxEffectiveLengthFt} ft max`,
841
+ detail: `${run.name ?? run.id} measures ${check.lengthFt} ft + ${elbows90}×90° + ${elbows45}×45° elbows.`,
842
+ suggestedFix: dryerVentRule.suggestedFix,
843
+ nodeIds: [run.id],
844
+ })
845
+ }
846
+ if (matViol) {
847
+ push({
848
+ severity: dryerVentMaterialRule.severity,
849
+ codeRef: dryerVentMaterialRule.codeRef,
850
+ title: dryerVentMaterialRule.title,
851
+ detail: `${run.name ?? run.id} uses ${material} instead of 4" smooth rigid aluminum/galvanized metal.`,
852
+ suggestedFix: dryerVentMaterialRule.suggestedFix,
853
+ nodeIds: [run.id],
854
+ })
855
+ }
856
+ }
857
+ }
858
+
859
+ // Per-level DWV invariants (each level with drainage requires accessible cleanout & vent stack coverage;
860
+ // upper stories in a multi-story building inherit stack-base cleanout & main vent stack coverage from
861
+ // lower walled levels in the same building when present)
862
+ for (const [lvlKey, st] of dwvStateByLevel.entries()) {
863
+ const lvlSuffix = lvlKey !== '__root__' && dwvStateByLevel.size > 1 ? ` (level ${lvlKey})` : ''
864
+ const lowerIds = lvlKey !== '__root__' ? getLowerWalledLevelIds(nodes, lvlKey) : []
865
+ const lowerHasCleanout = lowerIds.some((lid) => dwvStateByLevel.get(lid)?.hasAnyCleanout === true)
866
+ const lowerHasMainVent = lowerIds.some((lid) => dwvStateByLevel.get(lid)?.hasMainVentStack === true)
867
+ const upperHasMainVent =
868
+ lvlKey !== '__root__' &&
869
+ Array.from(dwvStateByLevel.entries()).some(
870
+ ([otherKey, otherSt]) =>
871
+ otherKey !== lvlKey &&
872
+ otherKey !== '__root__' &&
873
+ otherSt.hasMainVentStack &&
874
+ getLowerWalledLevelIds(nodes, otherKey).includes(lvlKey),
875
+ )
876
+ if (st.hasAnyDwvDrain && !st.hasAnyCleanout && !lowerHasCleanout) {
877
+ push({
878
+ severity: 'error',
879
+ codeRef: 'IPC 708.1',
880
+ title: `DWV system missing accessible cleanout${lvlSuffix}`,
881
+ detail: `Drainage network${lvlSuffix} has no stack-base or building-drain cleanout marked.`,
882
+ suggestedFix: 'Add a cleanout at the base of the main soil stack and at the building drain exit.',
883
+ nodeIds: st.sampleDrainIds,
884
+ })
885
+ }
886
+ if (st.hasAnyDwvDrain && !st.hasMainVentStack && !lowerHasMainVent && !upperHasMainVent) {
887
+ push({
888
+ severity: 'warning',
889
+ codeRef: 'IPC 903.1',
890
+ title: `DWV system missing ${IPC_RULE_THRESHOLDS.mainVentStackMinNominalIn}" main vent stack through roof${lvlSuffix}`,
891
+ detail: `Every building level with plumbing drainage${lvlSuffix} requires vent stack connection extending outdoors.`,
892
+ suggestedFix: `Add a ${IPC_RULE_THRESHOLDS.mainVentStackMinNominalIn}" main soil/vent stack terminating outdoors through the roof.`,
893
+ nodeIds: st.sampleDrainIds,
894
+ })
895
+ }
896
+ }
897
+
898
+ // 4. Cross-Trade Electrical Coordination Checks (scoped per building when an electrical panel exists in that building)
899
+ if (buildingsWithElectricalPanel.size > 0) {
900
+ const coord = buildElectricalCoordination(nodes)
901
+ for (const row of coord) {
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
906
+ push({
907
+ severity: 'warning',
908
+ codeRef: 'NEC 210 / Cross-Trade Power',
909
+ title: `Powered plumbing unit unwired: ${row.label}`,
910
+ detail: `${row.label} requires ${row.voltage}V ${row.poles}P ${row.breakerAmps}A (${row.loadVa} VA${row.gfciRequired ? ', GFCI' : ''}${row.dedicatedCircuit ? ', dedicated' : ''}) from the electrical panel.`,
911
+ suggestedFix: 'Run Electrical Auto-Populate or Sync MEP Loads to add the dedicated breaker and 3D power run automatically.',
912
+ nodeIds: [row.sourceNodeId],
913
+ })
914
+ }
915
+ }
916
+ }
917
+
918
+ const result: PlumbingAuditResult = {
919
+ codeEdition,
920
+ errorCount: findings.filter((f) => f.severity === 'error').length,
921
+ warningCount: findings.filter((f) => f.severity === 'warning').length,
922
+ infoCount: findings.filter((f) => f.severity === 'info').length,
923
+ findings,
924
+ }
925
+ byEdition.set(cacheKey, result)
926
+ return result
927
+ }