@kruschdev/pascal-mep-kernel 0.0.0-stage → 0.1.1

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,667 @@
1
+ import {
2
+ INCHES_TO_METERS2,
3
+ METERS_TO_FEET2,
4
+ round32
5
+ } from "./chunk-yd3hcm7n.js";
6
+
7
+ // src/rules/evaluator.ts
8
+ var OUTDOOR_ROOM_TOKENS = new Set([
9
+ "exterior",
10
+ "outdoor",
11
+ "outdoors",
12
+ "patio",
13
+ "deck",
14
+ "porch",
15
+ "balcony",
16
+ "yard"
17
+ ]);
18
+ function normalizeToken(value) {
19
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
20
+ }
21
+ function matchesAnyToken(value, targets) {
22
+ if (targets.length === 0)
23
+ return false;
24
+ const norm = normalizeToken(value);
25
+ if (!norm)
26
+ return false;
27
+ for (const t of targets) {
28
+ const nt = normalizeToken(t);
29
+ if (nt === "*" || nt === norm)
30
+ return true;
31
+ }
32
+ return false;
33
+ }
34
+ function clampNonNegativeMargin(margin) {
35
+ if (typeof margin !== "number" || !Number.isFinite(margin) || margin <= 0)
36
+ return 0;
37
+ return margin;
38
+ }
39
+ function effectivePlacementThreshold2(auditLimit, placementMarginM, direction) {
40
+ const margin = clampNonNegativeMargin(placementMarginM);
41
+ return direction === "min" ? auditLimit + margin : auditLimit - margin;
42
+ }
43
+ function resolveThreshold(auditLimit, placementMarginM, direction, mode) {
44
+ return mode === "placement" ? effectivePlacementThreshold2(auditLimit, placementMarginM, direction) : auditLimit;
45
+ }
46
+ function makeViolation(rule, candidate, message) {
47
+ return {
48
+ ruleId: rule.id,
49
+ codeRef: rule.codeRef,
50
+ severity: rule.severity,
51
+ category: rule.category,
52
+ title: rule.title,
53
+ message,
54
+ suggestedFix: rule.suggestedFix,
55
+ nodeIds: candidate.id ? [candidate.id] : []
56
+ };
57
+ }
58
+ function candidateFiniteY(candidate) {
59
+ const y = candidate.pos[1];
60
+ return typeof y === "number" && Number.isFinite(y) ? y : null;
61
+ }
62
+ function evaluateProhibitedZone(rule, candidate, mode) {
63
+ const { params } = rule;
64
+ if (!matchesAnyToken(candidate.kind, params.targetKinds) && !matchesAnyToken(candidate.role, params.targetKinds)) {
65
+ return [];
66
+ }
67
+ const violations = [];
68
+ const roomNorm = normalizeToken(candidate.roomCategory);
69
+ const roomProhibited = roomNorm.length > 0 && matchesAnyToken(roomNorm, params.prohibitedRoomCategories);
70
+ if (roomProhibited) {
71
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} is prohibited in "${candidate.roomCategory}" (${rule.codeRef}).`));
72
+ }
73
+ const isOutdoors = candidate.isOutdoors === true || OUTDOOR_ROOM_TOKENS.has(roomNorm);
74
+ if (isOutdoors && params.forbiddenNemaOutdoors && params.forbiddenNemaOutdoors.length > 0 && matchesAnyToken(candidate.nemaRating, params.forbiddenNemaOutdoors)) {
75
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} with NEMA rating "${candidate.nemaRating}" is forbidden outdoors (${rule.codeRef}).`));
76
+ }
77
+ if (params.requireBelowCeilingForAttic) {
78
+ if (candidate.ceilingHeightM !== undefined) {
79
+ if (!Number.isFinite(candidate.ceilingHeightM)) {
80
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} has non-finite ceiling height (${String(candidate.ceilingHeightM)}) and fails attic/ceiling check (${rule.codeRef}).`));
81
+ } else {
82
+ const y = candidateFiniteY(candidate);
83
+ const maxAllowedY = resolveThreshold(candidate.ceilingHeightM, rule.placementMarginM, "max", mode);
84
+ if (y === null || y > maxAllowedY) {
85
+ violations.push(makeViolation(rule, candidate, y === null ? `${candidate.kind} has non-finite elevation (${String(candidate.pos[1])}) and fails ceiling limit ${round32(maxAllowedY)}m (${rule.codeRef}).` : `${candidate.kind} elevation ${round32(y)}m exceeds ceiling limit ${round32(maxAllowedY)}m (${rule.codeRef}).`));
86
+ }
87
+ }
88
+ } else if (roomNorm === "attic" && !roomProhibited) {
89
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} is prohibited in attic space above the ceiling (${rule.codeRef}).`));
90
+ }
91
+ }
92
+ return violations;
93
+ }
94
+ function evaluateFixtureKeepout(rule, candidate, mode) {
95
+ const { params } = rule;
96
+ if (!matchesAnyToken(candidate.role, params.targetRoles) && !matchesAnyToken(candidate.kind, params.targetRoles)) {
97
+ return [];
98
+ }
99
+ const nearFixtures = candidate.nearFixtures;
100
+ if (!nearFixtures || nearFixtures.length === 0)
101
+ return [];
102
+ const y = candidateFiniteY(candidate);
103
+ const effMinH = resolveThreshold(params.minHorizontalM, rule.placementMarginM, "min", mode);
104
+ if (y !== null) {
105
+ if (params.verticalBandM) {
106
+ const [bandLow, bandHigh] = params.verticalBandM;
107
+ const effLow = resolveThreshold(bandLow, rule.placementMarginM, "max", mode);
108
+ const effHigh = resolveThreshold(bandHigh, rule.placementMarginM, "min", mode);
109
+ if (y < effLow || y > effHigh)
110
+ return [];
111
+ }
112
+ if (params.minVerticalM !== undefined && Number.isFinite(params.minVerticalM)) {
113
+ const effMinV = resolveThreshold(params.minVerticalM, rule.placementMarginM, "max", mode);
114
+ if (y < effMinV)
115
+ return [];
116
+ }
117
+ if (params.maxVerticalM !== undefined && Number.isFinite(params.maxVerticalM)) {
118
+ const effMaxV = resolveThreshold(params.maxVerticalM, rule.placementMarginM, "min", mode);
119
+ if (y > effMaxV)
120
+ return [];
121
+ }
122
+ }
123
+ const violations = [];
124
+ for (const fx of nearFixtures) {
125
+ if (!matchesAnyToken(fx.kind, params.fixtureKinds))
126
+ continue;
127
+ if (params.respectWallSeparation && (fx.separatedByWall === true || candidate.wallSeparated === true)) {
128
+ continue;
129
+ }
130
+ if (!Number.isFinite(fx.horizontalDistM)) {
131
+ violations.push(makeViolation(rule, candidate, `${candidate.role ?? candidate.kind} has non-finite distance (${String(fx.horizontalDistM)}) from "${fx.kind}" (minimum required ${round32(effMinH)}m, ${rule.codeRef}).`));
132
+ continue;
133
+ }
134
+ const violatesHorizontal = effMinH <= 0 ? fx.horizontalDistM <= 0 : fx.horizontalDistM < effMinH;
135
+ if (violatesHorizontal) {
136
+ violations.push(makeViolation(rule, candidate, `${candidate.role ?? candidate.kind} is ${round32(fx.horizontalDistM)}m from "${fx.kind}" (minimum required ${round32(effMinH)}m, ${rule.codeRef}).`));
137
+ }
138
+ }
139
+ return violations;
140
+ }
141
+ function evaluateOpeningKeepout(rule, candidate, mode) {
142
+ const { params } = rule;
143
+ if (!matchesAnyToken(candidate.role, params.targetRoles) && !matchesAnyToken(candidate.kind, params.targetRoles)) {
144
+ return [];
145
+ }
146
+ if (!candidate.openingKind)
147
+ return [];
148
+ if (candidate.openingKind === "door" && !params.blockDoors)
149
+ return [];
150
+ if (candidate.openingKind === "window" && !params.blockWindows)
151
+ return [];
152
+ const effTrim = resolveThreshold(params.trimClearanceM, rule.placementMarginM, "min", mode);
153
+ if (candidate.openingHorizontalDistM !== undefined && Number.isFinite(candidate.openingHorizontalDistM)) {
154
+ const clearHorizontally = effTrim <= 0 ? candidate.openingHorizontalDistM > 0 : candidate.openingHorizontalDistM >= effTrim;
155
+ if (clearHorizontally)
156
+ return [];
157
+ }
158
+ const y = candidateFiniteY(candidate);
159
+ const hasSill = candidate.openingSillYM !== undefined && Number.isFinite(candidate.openingSillYM);
160
+ const hasHead = candidate.openingHeadYM !== undefined && Number.isFinite(candidate.openingHeadYM);
161
+ if (params.floorToCeilingSillThresholdM !== undefined && Number.isFinite(params.floorToCeilingSillThresholdM) && hasSill) {
162
+ const effSillThreshold = resolveThreshold(params.floorToCeilingSillThresholdM, rule.placementMarginM, "min", mode);
163
+ const maxHeadY = hasHead ? candidate.openingHeadYM + effTrim : Number.POSITIVE_INFINITY;
164
+ if (candidate.openingSillYM <= effSillThreshold && (y === null || y <= maxHeadY)) {
165
+ return [
166
+ makeViolation(rule, candidate, `${candidate.role ?? candidate.kind} falls within floor-to-ceiling ${candidate.openingKind} glazing (sill ${round32(candidate.openingSillYM)}m <= ${round32(effSillThreshold)}m, ${rule.codeRef}).`)
167
+ ];
168
+ }
169
+ }
170
+ if (hasSill || hasHead) {
171
+ const lowY = hasSill ? candidate.openingSillYM - effTrim : Number.NEGATIVE_INFINITY;
172
+ const highY = hasHead ? candidate.openingHeadYM + effTrim : Number.POSITIVE_INFINITY;
173
+ if (y === null || y >= lowY && y <= highY) {
174
+ return [
175
+ makeViolation(rule, candidate, y === null ? `${candidate.role ?? candidate.kind} has non-finite elevation (${String(candidate.pos[1])}) and fails ${candidate.openingKind} keepout [${hasSill ? round32(lowY) : "-inf"}m, ${hasHead ? round32(highY) : "+inf"}m] (${rule.codeRef}).` : `${candidate.role ?? candidate.kind} at y=${round32(y)}m intersects ${candidate.openingKind} opening/trim keepout [${hasSill ? round32(lowY) : "-inf"}m, ${hasHead ? round32(highY) : "+inf"}m] (${rule.codeRef}).`)
176
+ ];
177
+ }
178
+ return [];
179
+ }
180
+ return [
181
+ makeViolation(rule, candidate, `${candidate.role ?? candidate.kind} violates ${candidate.openingKind} keepout clearance (${round32(effTrim)}m required, ${rule.codeRef}).`)
182
+ ];
183
+ }
184
+ function evaluateElevationBand(rule, candidate, mode) {
185
+ const { params } = rule;
186
+ if (!matchesAnyToken(candidate.kind, params.targetKinds) && !matchesAnyToken(candidate.role, params.targetKinds)) {
187
+ return [];
188
+ }
189
+ const violations = [];
190
+ const y = candidateFiniteY(candidate);
191
+ if (y === null) {
192
+ const hasExplicitHandleY = candidate.handleHeightM !== undefined && Number.isFinite(candidate.handleHeightM);
193
+ const needsPosY = params.minYM !== undefined && Number.isFinite(params.minYM) || params.maxYM !== undefined && Number.isFinite(params.maxYM) || params.minAboveFloodRimM !== undefined && Number.isFinite(params.minAboveFloodRimM) && candidate.floodRimM !== undefined || params.maxHandleHeightM !== undefined && Number.isFinite(params.maxHandleHeightM) && !hasExplicitHandleY || params.roofMarginM !== undefined && Number.isFinite(params.roofMarginM) && candidate.roofSurfaceYM !== undefined || params.atticThresholdOffsetM !== undefined && Number.isFinite(params.atticThresholdOffsetM) && candidate.ceilingHeightM !== undefined;
194
+ if (needsPosY) {
195
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} has non-finite elevation (${String(candidate.pos[1])}) and fails elevation-band check (${rule.codeRef}).`));
196
+ }
197
+ if (params.maxHandleHeightM !== undefined && Number.isFinite(params.maxHandleHeightM) && hasExplicitHandleY) {
198
+ const effMaxHandle = resolveThreshold(params.maxHandleHeightM, rule.placementMarginM, "max", mode);
199
+ if (candidate.handleHeightM > effMaxHandle) {
200
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} handle height ${round32(candidate.handleHeightM)}m exceeds maximum ${round32(effMaxHandle)}m (${rule.codeRef}).`));
201
+ }
202
+ }
203
+ return violations;
204
+ }
205
+ if (params.minYM !== undefined && Number.isFinite(params.minYM)) {
206
+ const effMinY = resolveThreshold(params.minYM, rule.placementMarginM, "min", mode);
207
+ if (y < effMinY) {
208
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} elevation ${round32(y)}m is below minimum ${round32(effMinY)}m (${rule.codeRef}).`));
209
+ }
210
+ }
211
+ if (params.maxYM !== undefined && Number.isFinite(params.maxYM)) {
212
+ const effMaxY = resolveThreshold(params.maxYM, rule.placementMarginM, "max", mode);
213
+ if (y > effMaxY) {
214
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} elevation ${round32(y)}m exceeds maximum ${round32(effMaxY)}m (${rule.codeRef}).`));
215
+ }
216
+ }
217
+ if (params.minAboveFloodRimM !== undefined && Number.isFinite(params.minAboveFloodRimM) && candidate.floodRimM !== undefined) {
218
+ if (!Number.isFinite(candidate.floodRimM)) {
219
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} has non-finite flood-rim elevation (${String(candidate.floodRimM)}) (${rule.codeRef}).`));
220
+ } else {
221
+ const effClearance = resolveThreshold(params.minAboveFloodRimM, rule.placementMarginM, "min", mode);
222
+ const requiredY = candidate.floodRimM + effClearance;
223
+ if (y < requiredY) {
224
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} elevation ${round32(y)}m is below flood-rim minimum ${round32(requiredY)}m (${round32(candidate.floodRimM)}m + ${round32(effClearance)}m, ${rule.codeRef}).`));
225
+ }
226
+ }
227
+ }
228
+ if (params.maxHandleHeightM !== undefined && Number.isFinite(params.maxHandleHeightM)) {
229
+ if (candidate.handleHeightM !== undefined && !Number.isFinite(candidate.handleHeightM)) {
230
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} has non-finite handle height (${String(candidate.handleHeightM)}) (${rule.codeRef}).`));
231
+ } else {
232
+ const handleY = candidate.handleHeightM !== undefined ? candidate.handleHeightM : y;
233
+ const effMaxHandle = resolveThreshold(params.maxHandleHeightM, rule.placementMarginM, "max", mode);
234
+ if (handleY > effMaxHandle) {
235
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} handle height ${round32(handleY)}m exceeds maximum ${round32(effMaxHandle)}m (${rule.codeRef}).`));
236
+ }
237
+ }
238
+ }
239
+ if (params.roofMarginM !== undefined && Number.isFinite(params.roofMarginM) && candidate.roofSurfaceYM !== undefined) {
240
+ if (!Number.isFinite(candidate.roofSurfaceYM)) {
241
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} has non-finite roof surface elevation (${String(candidate.roofSurfaceYM)}) (${rule.codeRef}).`));
242
+ } else {
243
+ const effRoofMargin = resolveThreshold(params.roofMarginM, rule.placementMarginM, "min", mode);
244
+ const maxAllowedY = candidate.roofSurfaceYM - effRoofMargin;
245
+ if (y > maxAllowedY) {
246
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} elevation ${round32(y)}m encroaches on roof surface ${round32(candidate.roofSurfaceYM)}m (required margin ${round32(effRoofMargin)}m, ${rule.codeRef}).`));
247
+ }
248
+ }
249
+ }
250
+ if (params.atticThresholdOffsetM !== undefined && Number.isFinite(params.atticThresholdOffsetM) && candidate.ceilingHeightM !== undefined) {
251
+ if (!Number.isFinite(candidate.ceilingHeightM)) {
252
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} has non-finite ceiling height (${String(candidate.ceilingHeightM)}) (${rule.codeRef}).`));
253
+ } else {
254
+ const atticBoundary = candidate.ceilingHeightM + params.atticThresholdOffsetM;
255
+ const effBoundary = resolveThreshold(atticBoundary, rule.placementMarginM, "max", mode);
256
+ if (y > effBoundary) {
257
+ violations.push(makeViolation(rule, candidate, `${candidate.kind} elevation ${round32(y)}m exceeds attic threshold ${round32(effBoundary)}m (${rule.codeRef}).`));
258
+ }
259
+ }
260
+ }
261
+ return violations;
262
+ }
263
+ function evaluateWorkingSpace(rule, candidate, mode) {
264
+ const { params } = rule;
265
+ if (!matchesAnyToken(candidate.kind, params.targetKinds) && !matchesAnyToken(candidate.role, params.targetKinds)) {
266
+ return [];
267
+ }
268
+ const violations = [];
269
+ if (candidate.workingSpaceWidthM !== undefined) {
270
+ const effW = resolveThreshold(params.widthM, rule.placementMarginM, "min", mode);
271
+ if (!Number.isFinite(candidate.workingSpaceWidthM) || candidate.workingSpaceWidthM < effW) {
272
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.workingSpaceWidthM) ? `${candidate.kind} has non-finite working space width (${String(candidate.workingSpaceWidthM)}) (required ${round32(effW)}m, ${rule.codeRef}).` : `${candidate.kind} working space width ${round32(candidate.workingSpaceWidthM)}m is below required ${round32(effW)}m (${rule.codeRef}).`));
273
+ }
274
+ }
275
+ if (candidate.workingSpaceDepthM !== undefined) {
276
+ const effD = resolveThreshold(params.depthM, rule.placementMarginM, "min", mode);
277
+ if (!Number.isFinite(candidate.workingSpaceDepthM) || candidate.workingSpaceDepthM < effD) {
278
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.workingSpaceDepthM) ? `${candidate.kind} has non-finite working space depth (${String(candidate.workingSpaceDepthM)}) (required ${round32(effD)}m, ${rule.codeRef}).` : `${candidate.kind} working space depth ${round32(candidate.workingSpaceDepthM)}m is below required ${round32(effD)}m (${rule.codeRef}).`));
279
+ }
280
+ }
281
+ if (candidate.workingSpaceHeightM !== undefined) {
282
+ const effH = resolveThreshold(params.heightM, rule.placementMarginM, "min", mode);
283
+ if (!Number.isFinite(candidate.workingSpaceHeightM) || candidate.workingSpaceHeightM < effH) {
284
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.workingSpaceHeightM) ? `${candidate.kind} has non-finite working space headroom (${String(candidate.workingSpaceHeightM)}) (required ${round32(effH)}m, ${rule.codeRef}).` : `${candidate.kind} working space headroom ${round32(candidate.workingSpaceHeightM)}m is below required ${round32(effH)}m (${rule.codeRef}).`));
285
+ }
286
+ }
287
+ if (params.dedicatedOverheadHeightM !== undefined && Number.isFinite(params.dedicatedOverheadHeightM) && candidate.dedicatedOverheadClearHeightM !== undefined) {
288
+ const effOverhead = resolveThreshold(params.dedicatedOverheadHeightM, rule.placementMarginM, "min", mode);
289
+ if (!Number.isFinite(candidate.dedicatedOverheadClearHeightM) || candidate.dedicatedOverheadClearHeightM < effOverhead) {
290
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.dedicatedOverheadClearHeightM) ? `${candidate.kind} has non-finite dedicated overhead clearance (${String(candidate.dedicatedOverheadClearHeightM)}) (required ${round32(effOverhead)}m, ${rule.codeRef}).` : `${candidate.kind} dedicated overhead clearance ${round32(candidate.dedicatedOverheadClearHeightM)}m is below required ${round32(effOverhead)}m (${rule.codeRef}).`));
291
+ }
292
+ }
293
+ return violations;
294
+ }
295
+ function evaluateMaterialPolicy(rule, candidate) {
296
+ const { params } = rule;
297
+ const systemToken = candidate.system ?? candidate.kind;
298
+ if (!matchesAnyToken(systemToken, params.targetSystems)) {
299
+ return [];
300
+ }
301
+ const violations = [];
302
+ const hasContextFlag = Boolean(params.forbiddenInCommercial || params.forbiddenInPlenum || params.forbiddenInWetCrawlspace);
303
+ const hasForbiddenList = Boolean(params.forbiddenMaterials && params.forbiddenMaterials.length > 0);
304
+ const hasMaterial = candidate.material !== undefined && normalizeToken(candidate.material).length > 0;
305
+ let flaggedByForbidden = false;
306
+ if (!hasContextFlag) {
307
+ if (hasForbiddenList && hasMaterial && matchesAnyToken(candidate.material, params.forbiddenMaterials)) {
308
+ flaggedByForbidden = true;
309
+ violations.push(makeViolation(rule, candidate, `Material "${candidate.material}" is forbidden for system "${systemToken}" (${rule.codeRef}).`));
310
+ }
311
+ } else {
312
+ const materialMatches = hasForbiddenList ? hasMaterial && matchesAnyToken(candidate.material, params.forbiddenMaterials) : true;
313
+ if (materialMatches) {
314
+ const matLabel = hasMaterial ? `Material "${candidate.material}"` : `System "${systemToken}"`;
315
+ if (params.forbiddenInCommercial && candidate.occupancy === "commercial") {
316
+ flaggedByForbidden = true;
317
+ violations.push(makeViolation(rule, candidate, `${matLabel} is forbidden in commercial occupancy (${rule.codeRef}).`));
318
+ }
319
+ if (params.forbiddenInPlenum && candidate.inPlenum === true) {
320
+ flaggedByForbidden = true;
321
+ violations.push(makeViolation(rule, candidate, `${matLabel} is forbidden in environmental air plenums (${rule.codeRef}).`));
322
+ }
323
+ if (params.forbiddenInWetCrawlspace && candidate.inWetCrawlspace === true) {
324
+ flaggedByForbidden = true;
325
+ violations.push(makeViolation(rule, candidate, `${matLabel} is forbidden in wet crawlspaces (${rule.codeRef}).`));
326
+ }
327
+ }
328
+ }
329
+ if (!flaggedByForbidden && params.requiredMaterials && params.requiredMaterials.length > 0 && hasMaterial && !matchesAnyToken(candidate.material, params.requiredMaterials)) {
330
+ violations.push(makeViolation(rule, candidate, `Material "${candidate.material}" is not permitted for "${systemToken}"; required one of [${params.requiredMaterials.join(", ")}] (${rule.codeRef}).`));
331
+ }
332
+ return violations;
333
+ }
334
+ function evaluateRoutingConstraint(rule, candidate, mode) {
335
+ const { params } = rule;
336
+ const systemToken = candidate.system ?? candidate.kind;
337
+ if (!matchesAnyToken(systemToken, params.targetSystems)) {
338
+ return [];
339
+ }
340
+ const violations = [];
341
+ const marginFt = clampNonNegativeMargin(rule.placementMarginM) * METERS_TO_FEET2;
342
+ if (params.maxBendDegrees !== undefined && Number.isFinite(params.maxBendDegrees) && candidate.bendDegrees !== undefined) {
343
+ if (!Number.isFinite(candidate.bendDegrees) || candidate.bendDegrees > params.maxBendDegrees) {
344
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.bendDegrees) ? `${systemToken} has non-finite total bends (${String(candidate.bendDegrees)}) (maximum ${round32(params.maxBendDegrees)}°, ${rule.codeRef}).` : `${systemToken} total bends ${round32(candidate.bendDegrees)}° exceed maximum ${round32(params.maxBendDegrees)}° (${rule.codeRef}).`));
345
+ }
346
+ }
347
+ if (params.minSlopeInPerFt !== undefined && Number.isFinite(params.minSlopeInPerFt) && candidate.slopeInPerFt !== undefined) {
348
+ const slopeMarginInPerFt = clampNonNegativeMargin(params.placementSlopeMarginInPerFt);
349
+ const effMinSlope = resolveThreshold(params.minSlopeInPerFt, slopeMarginInPerFt, "min", mode);
350
+ if (!Number.isFinite(candidate.slopeInPerFt) || candidate.slopeInPerFt < effMinSlope) {
351
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.slopeInPerFt) ? `${systemToken} has non-finite slope (${String(candidate.slopeInPerFt)}) (minimum ${round32(effMinSlope)} in/ft, ${rule.codeRef}).` : `${systemToken} slope ${round32(candidate.slopeInPerFt)} in/ft is below minimum ${round32(effMinSlope)} in/ft (${rule.codeRef}).`));
352
+ }
353
+ }
354
+ if (params.maxEffectiveLengthFt !== undefined && Number.isFinite(params.maxEffectiveLengthFt) && candidate.effectiveLengthFt !== undefined) {
355
+ const effMaxFt = resolveThreshold(params.maxEffectiveLengthFt, marginFt, "max", mode);
356
+ if (!Number.isFinite(candidate.effectiveLengthFt) || candidate.effectiveLengthFt > effMaxFt) {
357
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.effectiveLengthFt) ? `${systemToken} has non-finite effective length (${String(candidate.effectiveLengthFt)}) (maximum ${round32(effMaxFt)} ft, ${rule.codeRef}).` : `${systemToken} effective length ${round32(candidate.effectiveLengthFt)} ft exceeds maximum ${round32(effMaxFt)} ft (${rule.codeRef}).`));
358
+ }
359
+ }
360
+ if (params.maxLengthFtWithoutCleanout !== undefined && Number.isFinite(params.maxLengthFtWithoutCleanout) && candidate.hasCleanout !== true) {
361
+ const runLenFt = candidate.runLengthFt !== undefined ? candidate.runLengthFt : candidate.effectiveLengthFt;
362
+ if (runLenFt !== undefined) {
363
+ const effMaxCleanoutFt = resolveThreshold(params.maxLengthFtWithoutCleanout, marginFt, "max", mode);
364
+ if (!Number.isFinite(runLenFt) || runLenFt > effMaxCleanoutFt) {
365
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(runLenFt) ? `${systemToken} has non-finite run length (${String(runLenFt)}) without a cleanout (limit ${round32(effMaxCleanoutFt)} ft, ${rule.codeRef}).` : `${systemToken} run length ${round32(runLenFt)} ft exceeds ${round32(effMaxCleanoutFt)} ft without a cleanout (${rule.codeRef}).`));
366
+ }
367
+ }
368
+ }
369
+ if (params.minNominalSizeIn !== undefined && Number.isFinite(params.minNominalSizeIn) && candidate.nominalSizeIn !== undefined) {
370
+ if (!Number.isFinite(candidate.nominalSizeIn) || candidate.nominalSizeIn < params.minNominalSizeIn) {
371
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.nominalSizeIn) ? `${systemToken} has non-finite nominal size (${String(candidate.nominalSizeIn)}) (minimum ${round32(params.minNominalSizeIn)}", ${rule.codeRef}).` : `${systemToken} nominal size ${round32(candidate.nominalSizeIn)}" is below minimum ${round32(params.minNominalSizeIn)}" (${rule.codeRef}).`));
372
+ }
373
+ }
374
+ return violations;
375
+ }
376
+ function evaluateWallCavityFit(rule, candidate, mode) {
377
+ const { params } = rule;
378
+ if (candidate.nominalSizeIn === undefined || candidate.wallThicknessM === undefined) {
379
+ return [];
380
+ }
381
+ if (!Number.isFinite(candidate.nominalSizeIn) || !Number.isFinite(candidate.wallThicknessM)) {
382
+ return [
383
+ makeViolation(rule, candidate, `Non-finite wall-cavity-fit measurement (nominalSizeIn=${String(candidate.nominalSizeIn)}, wallThicknessM=${String(candidate.wallThicknessM)}, ${rule.codeRef}).`)
384
+ ];
385
+ }
386
+ if (candidate.nominalSizeIn < params.minPipeNominalIn) {
387
+ return [];
388
+ }
389
+ const effMinWall = resolveThreshold(params.minWallThicknessM, rule.placementMarginM, "min", mode);
390
+ const is2x4Wall = candidate.wallThicknessM <= params.max2x4WallThicknessM;
391
+ if (is2x4Wall || candidate.wallThicknessM < effMinWall) {
392
+ const wallNote = is2x4Wall ? `2x4 wall (${round32(candidate.wallThicknessM)}m <= ${round32(params.max2x4WallThicknessM)}m)` : `wall thickness ${round32(candidate.wallThicknessM)}m`;
393
+ return [
394
+ makeViolation(rule, candidate, `${round32(candidate.nominalSizeIn)}" pipe cannot fit in ${wallNote}; requires wall thickness >= ${round32(effMinWall)}m (${rule.codeRef}).`)
395
+ ];
396
+ }
397
+ return [];
398
+ }
399
+ function evaluateWindSeismicThreshold(rule, candidate, mode) {
400
+ const { params } = rule;
401
+ const violations = [];
402
+ const wind = candidate.designWindMph !== undefined && Number.isFinite(candidate.designWindMph) ? candidate.designWindMph : undefined;
403
+ if (candidate.designWindMph !== undefined && !Number.isFinite(candidate.designWindMph)) {
404
+ violations.push(makeViolation(rule, candidate, `Non-finite design wind speed (${String(candidate.designWindMph)}) (${rule.codeRef}).`));
405
+ }
406
+ const sdc = candidate.seismicDesignCategory;
407
+ const isHighSeismic = sdc !== undefined && matchesAnyToken(sdc, params.highSeismicCategories);
408
+ const isSillBoltSeismic = sdc !== undefined && matchesAnyToken(sdc, params.sillBoltSeismicCategories);
409
+ const marginIn = clampNonNegativeMargin(rule.placementMarginM) / INCHES_TO_METERS2;
410
+ const roofTieByWind = wind !== undefined && wind >= params.roofTieWindMph;
411
+ if (candidate.hasRoofTie === false && (roofTieByWind || isHighSeismic)) {
412
+ violations.push(makeViolation(rule, candidate, `Roof-to-wall tie required at ${roofTieByWind ? `${round32(wind)} mph` : `SDC ${sdc}`} (${rule.codeRef}).`));
413
+ }
414
+ const strapByWind = wind !== undefined && wind >= params.strapWindMph;
415
+ if (candidate.hasStrap === false && (strapByWind || isHighSeismic)) {
416
+ violations.push(makeViolation(rule, candidate, `Uplift strap required at ${strapByWind ? `${round32(wind)} mph` : `SDC ${sdc}`} (${rule.codeRef}).`));
417
+ }
418
+ if (candidate.hasHeavyStrap === false && wind !== undefined && wind >= params.heavyStrapWindMph) {
419
+ violations.push(makeViolation(rule, candidate, `Heavy uplift strap required at ${round32(wind)} mph (>= ${round32(params.heavyStrapWindMph)} mph, ${rule.codeRef}).`));
420
+ }
421
+ const holdDownByWind = wind !== undefined && wind >= params.holdDownWindMph;
422
+ if (candidate.hasHoldDown === false && (holdDownByWind || isHighSeismic)) {
423
+ violations.push(makeViolation(rule, candidate, `Hold-down connector required at ${holdDownByWind ? `${round32(wind)} mph` : `SDC ${sdc}`} (${rule.codeRef}).`));
424
+ }
425
+ if (candidate.hasSillBolt === false && isSillBoltSeismic) {
426
+ violations.push(makeViolation(rule, candidate, `Seismic sill anchor bolt required in SDC "${sdc}" (${rule.codeRef}).`));
427
+ }
428
+ if (candidate.footingWidthIn !== undefined) {
429
+ const effMinFooting = resolveThreshold(params.minFootingWidthIn, marginIn, "min", mode);
430
+ if (!Number.isFinite(candidate.footingWidthIn) || candidate.footingWidthIn < effMinFooting) {
431
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.footingWidthIn) ? `Non-finite spread footing width (${String(candidate.footingWidthIn)}) (minimum ${round32(effMinFooting)}", ${rule.codeRef}).` : `Spread footing width ${round32(candidate.footingWidthIn)}" is below minimum ${round32(effMinFooting)}" (${rule.codeRef}).`));
432
+ }
433
+ }
434
+ if (candidate.bearingIn !== undefined) {
435
+ let effMinBearing;
436
+ if (params.minBearingLengthIn !== undefined && Number.isFinite(params.minBearingLengthIn)) {
437
+ const baseMinBearingIn = Math.max(0, params.minBearingLengthIn);
438
+ const toleranceIn = clampNonNegativeMargin(params.minBearingToleranceIn);
439
+ effMinBearing = mode === "audit" ? Math.max(0, baseMinBearingIn - toleranceIn) : resolveThreshold(baseMinBearingIn, marginIn, "min", mode);
440
+ } else {
441
+ effMinBearing = resolveThreshold(params.minBearingToleranceIn, marginIn, "min", mode);
442
+ }
443
+ if (!Number.isFinite(candidate.bearingIn) || candidate.bearingIn < effMinBearing) {
444
+ violations.push(makeViolation(rule, candidate, !Number.isFinite(candidate.bearingIn) ? `Non-finite bearing length (${String(candidate.bearingIn)}) (minimum ${round32(effMinBearing)}", ${rule.codeRef}).` : `Bearing length ${round32(candidate.bearingIn)}" is below minimum ${round32(effMinBearing)}" (${rule.codeRef}).`));
445
+ }
446
+ }
447
+ return violations;
448
+ }
449
+ function evaluateSingleRule(rule, candidate, mode) {
450
+ switch (rule.kind) {
451
+ case "prohibited-zone":
452
+ return evaluateProhibitedZone(rule, candidate, mode);
453
+ case "fixture-keepout":
454
+ return evaluateFixtureKeepout(rule, candidate, mode);
455
+ case "opening-keepout":
456
+ return evaluateOpeningKeepout(rule, candidate, mode);
457
+ case "elevation-band":
458
+ return evaluateElevationBand(rule, candidate, mode);
459
+ case "working-space":
460
+ return evaluateWorkingSpace(rule, candidate, mode);
461
+ case "material-policy":
462
+ return evaluateMaterialPolicy(rule, candidate);
463
+ case "routing-constraint":
464
+ return evaluateRoutingConstraint(rule, candidate, mode);
465
+ case "wall-cavity-fit":
466
+ return evaluateWallCavityFit(rule, candidate, mode);
467
+ case "wind-seismic-threshold":
468
+ return evaluateWindSeismicThreshold(rule, candidate, mode);
469
+ default: {
470
+ const _exhaustive = rule;
471
+ return _exhaustive;
472
+ }
473
+ }
474
+ }
475
+ function evaluatePlacementCandidate2(rules, candidate, mode = "placement") {
476
+ const violations = [];
477
+ for (const rule of rules) {
478
+ const ruleViolations = evaluateSingleRule(rule, candidate, mode);
479
+ for (const v of ruleViolations) {
480
+ violations.push(v);
481
+ }
482
+ }
483
+ return {
484
+ legal: violations.length === 0,
485
+ violations
486
+ };
487
+ }
488
+ function filterLegalCandidates2(rules, candidates) {
489
+ const legal = [];
490
+ const rejected = [];
491
+ for (const candidate of candidates) {
492
+ const result = evaluatePlacementCandidate2(rules, candidate, "placement");
493
+ if (result.legal) {
494
+ legal.push(candidate);
495
+ } else {
496
+ rejected.push({ candidate, violations: result.violations });
497
+ }
498
+ }
499
+ return { legal, rejected };
500
+ }
501
+ function evaluateDeclarativeRules2(rules, candidates, opts) {
502
+ const activeRules = rules.filter((r) => r.trade === opts.trade);
503
+ const violations = [];
504
+ for (const candidate of candidates) {
505
+ const result = evaluatePlacementCandidate2(activeRules, candidate, "audit");
506
+ for (const v of result.violations) {
507
+ violations.push(v);
508
+ }
509
+ }
510
+ const errorCount = violations.filter((v) => v.severity === "error").length;
511
+ const warningCount = violations.filter((v) => v.severity === "warning").length;
512
+ const infoCount = violations.length - errorCount - warningCount;
513
+ const ok = errorCount === 0;
514
+ const tool = opts.tool ?? "evaluate_declarative_rules";
515
+ const infoPart = infoCount > 0 ? `, ${infoCount} info` : "";
516
+ const summary = violations.length === 0 ? `${opts.trade} audit passed: 0 violations across ${candidates.length} candidate(s) (${activeRules.length} rule(s) evaluated).` : `${opts.trade} audit found ${violations.length} violation(s) (${errorCount} error(s), ${warningCount} warning(s)${infoPart}) across ${candidates.length} candidate(s) (${activeRules.length} rule(s) evaluated).`;
517
+ return {
518
+ ok,
519
+ tool,
520
+ summary,
521
+ data: {
522
+ trade: opts.trade,
523
+ rulesEvaluated: activeRules.length,
524
+ violationCount: violations.length,
525
+ violations
526
+ }
527
+ };
528
+ }
529
+ function validateRuleTable2(rules) {
530
+ const errors = [];
531
+ const seenIds = new Set;
532
+ for (let i = 0;i < rules.length; i++) {
533
+ const rule = rules[i];
534
+ const label = rule.id?.trim() ? `rule "${rule.id}" (index ${i})` : `rule at index ${i}`;
535
+ const trimmedId = typeof rule.id === "string" ? rule.id.trim() : "";
536
+ if (trimmedId.length === 0) {
537
+ errors.push(`${label}: id must be a non-empty string.`);
538
+ } else if (seenIds.has(trimmedId)) {
539
+ errors.push(`${label}: duplicate rule id "${trimmedId}".`);
540
+ } else {
541
+ seenIds.add(trimmedId);
542
+ }
543
+ if (typeof rule.codeRef !== "string" || rule.codeRef.trim().length === 0) {
544
+ errors.push(`${label}: codeRef must be a non-empty string.`);
545
+ }
546
+ if (rule.placementMarginM !== undefined) {
547
+ if (typeof rule.placementMarginM !== "number" || !Number.isFinite(rule.placementMarginM) || rule.placementMarginM < 0) {
548
+ errors.push(`${label}: placementMarginM must be a finite number >= 0 (got ${String(rule.placementMarginM)}).`);
549
+ }
550
+ }
551
+ switch (rule.kind) {
552
+ case "fixture-keepout": {
553
+ if (!Number.isFinite(rule.params.minHorizontalM) || rule.params.minHorizontalM < 0) {
554
+ errors.push(`${label}: minHorizontalM must be a finite number >= 0.`);
555
+ }
556
+ if (rule.params.minVerticalM !== undefined && (!Number.isFinite(rule.params.minVerticalM) || rule.params.minVerticalM < 0)) {
557
+ errors.push(`${label}: minVerticalM must be a finite number >= 0.`);
558
+ }
559
+ if (rule.params.maxVerticalM !== undefined && (!Number.isFinite(rule.params.maxVerticalM) || rule.params.maxVerticalM < 0)) {
560
+ errors.push(`${label}: maxVerticalM must be a finite number >= 0.`);
561
+ }
562
+ if (rule.params.minVerticalM !== undefined && rule.params.maxVerticalM !== undefined && Number.isFinite(rule.params.minVerticalM) && Number.isFinite(rule.params.maxVerticalM) && rule.params.minVerticalM > rule.params.maxVerticalM) {
563
+ errors.push(`${label}: minVerticalM (${rule.params.minVerticalM}) cannot exceed maxVerticalM (${rule.params.maxVerticalM}).`);
564
+ }
565
+ if (rule.params.verticalBandM) {
566
+ const [low, high] = rule.params.verticalBandM;
567
+ if (!Number.isFinite(low) || !Number.isFinite(high) || low > high) {
568
+ errors.push(`${label}: verticalBandM must be finite [low, high] with low <= high.`);
569
+ }
570
+ }
571
+ break;
572
+ }
573
+ case "opening-keepout": {
574
+ if (!Number.isFinite(rule.params.trimClearanceM) || rule.params.trimClearanceM < 0) {
575
+ errors.push(`${label}: trimClearanceM must be a finite number >= 0.`);
576
+ }
577
+ if (rule.params.floorToCeilingSillThresholdM !== undefined && (!Number.isFinite(rule.params.floorToCeilingSillThresholdM) || rule.params.floorToCeilingSillThresholdM < 0)) {
578
+ errors.push(`${label}: floorToCeilingSillThresholdM must be a finite number >= 0.`);
579
+ }
580
+ break;
581
+ }
582
+ case "elevation-band": {
583
+ if (rule.params.minYM !== undefined && !Number.isFinite(rule.params.minYM)) {
584
+ errors.push(`${label}: minYM must be a finite number.`);
585
+ }
586
+ if (rule.params.maxYM !== undefined && !Number.isFinite(rule.params.maxYM)) {
587
+ errors.push(`${label}: maxYM must be a finite number.`);
588
+ }
589
+ if (rule.params.minYM !== undefined && rule.params.maxYM !== undefined && Number.isFinite(rule.params.minYM) && Number.isFinite(rule.params.maxYM) && rule.params.minYM > rule.params.maxYM) {
590
+ errors.push(`${label}: minYM (${rule.params.minYM}) cannot exceed maxYM (${rule.params.maxYM}).`);
591
+ }
592
+ if (rule.params.minAboveFloodRimM !== undefined && (!Number.isFinite(rule.params.minAboveFloodRimM) || rule.params.minAboveFloodRimM < 0)) {
593
+ errors.push(`${label}: minAboveFloodRimM must be a finite number >= 0.`);
594
+ }
595
+ if (rule.params.maxHandleHeightM !== undefined && (!Number.isFinite(rule.params.maxHandleHeightM) || rule.params.maxHandleHeightM <= 0)) {
596
+ errors.push(`${label}: maxHandleHeightM must be a finite number > 0.`);
597
+ }
598
+ if (rule.params.roofMarginM !== undefined && !Number.isFinite(rule.params.roofMarginM)) {
599
+ errors.push(`${label}: roofMarginM must be a finite number.`);
600
+ }
601
+ if (rule.params.atticThresholdOffsetM !== undefined && !Number.isFinite(rule.params.atticThresholdOffsetM)) {
602
+ errors.push(`${label}: atticThresholdOffsetM must be a finite number.`);
603
+ }
604
+ break;
605
+ }
606
+ case "working-space": {
607
+ if (!Number.isFinite(rule.params.widthM) || rule.params.widthM < 0 || !Number.isFinite(rule.params.depthM) || rule.params.depthM < 0 || !Number.isFinite(rule.params.heightM) || rule.params.heightM < 0) {
608
+ errors.push(`${label}: widthM, depthM, and heightM must be finite numbers >= 0.`);
609
+ }
610
+ if (rule.params.dedicatedOverheadHeightM !== undefined && (!Number.isFinite(rule.params.dedicatedOverheadHeightM) || rule.params.dedicatedOverheadHeightM < 0)) {
611
+ errors.push(`${label}: dedicatedOverheadHeightM must be a finite number >= 0.`);
612
+ }
613
+ break;
614
+ }
615
+ case "routing-constraint": {
616
+ const optionalNonNegFields = [
617
+ ["maxBendDegrees", rule.params.maxBendDegrees],
618
+ ["minSlopeInPerFt", rule.params.minSlopeInPerFt],
619
+ ["placementSlopeMarginInPerFt", rule.params.placementSlopeMarginInPerFt],
620
+ ["maxEffectiveLengthFt", rule.params.maxEffectiveLengthFt],
621
+ ["maxLengthFtWithoutCleanout", rule.params.maxLengthFtWithoutCleanout],
622
+ ["minNominalSizeIn", rule.params.minNominalSizeIn]
623
+ ];
624
+ for (const [field, val] of optionalNonNegFields) {
625
+ if (val !== undefined && (!Number.isFinite(val) || val < 0)) {
626
+ errors.push(`${label}: ${field} must be a finite number >= 0.`);
627
+ }
628
+ }
629
+ break;
630
+ }
631
+ case "wall-cavity-fit": {
632
+ if (!Number.isFinite(rule.params.minPipeNominalIn) || rule.params.minPipeNominalIn < 0 || !Number.isFinite(rule.params.minWallThicknessM) || rule.params.minWallThicknessM < 0 || !Number.isFinite(rule.params.max2x4WallThicknessM) || rule.params.max2x4WallThicknessM < 0) {
633
+ errors.push(`${label}: wall-cavity-fit dimensions must be finite numbers >= 0.`);
634
+ }
635
+ break;
636
+ }
637
+ case "wind-seismic-threshold": {
638
+ const nums = [
639
+ rule.params.roofTieWindMph,
640
+ rule.params.strapWindMph,
641
+ rule.params.heavyStrapWindMph,
642
+ rule.params.holdDownWindMph,
643
+ rule.params.minFootingWidthIn,
644
+ rule.params.minBearingToleranceIn
645
+ ];
646
+ if (nums.some((n) => !Number.isFinite(n) || n < 0)) {
647
+ errors.push(`${label}: wind-seismic-threshold numeric limits must be finite numbers >= 0.`);
648
+ }
649
+ if (rule.params.minBearingLengthIn !== undefined && (!Number.isFinite(rule.params.minBearingLengthIn) || rule.params.minBearingLengthIn < 0)) {
650
+ errors.push(`${label}: minBearingLengthIn must be a finite number >= 0.`);
651
+ }
652
+ break;
653
+ }
654
+ case "prohibited-zone":
655
+ case "material-policy":
656
+ break;
657
+ default: {
658
+ const _exhaustive = rule;
659
+ }
660
+ }
661
+ }
662
+ return {
663
+ valid: errors.length === 0,
664
+ errors
665
+ };
666
+ }
667
+ export { effectivePlacementThreshold2, evaluatePlacementCandidate2, filterLegalCandidates2, evaluateDeclarativeRules2, validateRuleTable2 };