@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,854 @@
1
+ /**
2
+ * Pure Agent Operations (`@kruschdev/pascal-plugin-plumbing/agent-operations`).
3
+ * Runs identically in Pascal's MCP server, detached scene runtime, or live editor tab
4
+ * in a single undo step (`DECISIONS.md` E-016 & E-018).
5
+ */
6
+
7
+ import type { AnyNode } from '@pascal-app/core'
8
+ import type { AgentContext, AgentOperations, SceneNodes } from '@pascal-app/core/agent-operations'
9
+ import { refuse } from '@pascal-app/core/agent-tools'
10
+ import { auditScenePlumbing } from './ipc/audit'
11
+ import {
12
+ type BonesIngestionMode,
13
+ planConnectSingleFixture,
14
+ planPlumbingAutoPopulate,
15
+ planSyncPlumbingFixtures,
16
+ } from './ipc/autopopulate'
17
+ import {
18
+ type ElectricalPowerDemand,
19
+ type FramingPenetration,
20
+ type SceneNodeLike,
21
+ type Vec3,
22
+ belongsToLevel,
23
+ computePipeFramingPenetrations,
24
+ extractBonesPlumbingContext,
25
+ getEquipmentElectricalDemand,
26
+ getFixtureElectricalDemand,
27
+ resolveNodeLevelId,
28
+ } from './ipc/framing-interop'
29
+ import { buildPlumbingBom, formatPlumbingBomCsv } from './ipc/pricing'
30
+ import {
31
+ extractPlumbingObstacles,
32
+ extractWallSegments,
33
+ resolveLevelHeightM,
34
+ routeDwvDrainRun,
35
+ routePressurizedPipeRun,
36
+ routeVentRun,
37
+ } from './ipc/routing'
38
+ import { buildPlumbingSchedule, formatPlumbingScheduleCsv } from './ipc/schedule'
39
+ import {
40
+ type CodeEdition,
41
+ type EquipmentKind,
42
+ FIXTURE_SPECS,
43
+ type FixtureKind,
44
+ type FoundationType,
45
+ type ManifoldKind,
46
+ type OccupancyType,
47
+ type PipeMaterial,
48
+ type PipeNominalSize,
49
+ type PlumbingSystem,
50
+ type SupplyTopology,
51
+ getFixtureDfu,
52
+ getFixtureWsfu,
53
+ } from './ipc/tables'
54
+
55
+ function asRecord(nodes: SceneNodes): Readonly<Record<string, SceneNodeLike>> {
56
+ return nodes as unknown as Readonly<Record<string, SceneNodeLike>>
57
+ }
58
+
59
+ function resolveLevelId(nodes: SceneNodes, requested: string | undefined, ctx: AgentContext): string | null {
60
+ const record = asRecord(nodes)
61
+ if (requested && nodes[requested]) {
62
+ if ((nodes[requested] as { type?: string }).type === 'level') return requested
63
+ const resolved = resolveNodeLevelId(record, record[requested]!)
64
+ if (resolved && nodes[resolved] && (nodes[resolved] as { type?: string }).type === 'level') return resolved
65
+ }
66
+ if (ctx.activeLevelId && nodes[ctx.activeLevelId]) {
67
+ if ((nodes[ctx.activeLevelId] as { type?: string }).type === 'level') return ctx.activeLevelId
68
+ const resolved = resolveNodeLevelId(record, record[ctx.activeLevelId]!)
69
+ if (resolved && nodes[resolved] && (nodes[resolved] as { type?: string }).type === 'level') return resolved
70
+ }
71
+ for (const n of Object.values(nodes)) {
72
+ if ((n as { type?: string }).type === 'level') return (n as { id: string }).id
73
+ }
74
+ return null
75
+ }
76
+
77
+ function defaultRoomNameForFixture(kind: FixtureKind): string {
78
+ switch (kind) {
79
+ case 'kitchen-sink':
80
+ case 'dishwasher':
81
+ case 'garbage-disposal':
82
+ case 'grease-interceptor':
83
+ return 'Kitchen'
84
+ case 'clothes-washer':
85
+ case 'laundry-sink':
86
+ return 'Laundry'
87
+ case 'hose-bibb':
88
+ return 'Exterior'
89
+ case 'floor-drain':
90
+ case 'mop-sink':
91
+ return 'Utility'
92
+ case 'bar-sink':
93
+ return 'Bar'
94
+ case 'drinking-fountain':
95
+ return 'Corridor'
96
+ default:
97
+ return 'Bathroom'
98
+ }
99
+ }
100
+
101
+ function deterministicId(prefix: string, nodes: SceneNodes): string {
102
+ let idx = 1
103
+ while (nodes[`${prefix}_${idx}`]) idx += 1
104
+ return `${prefix}_${idx}`
105
+ }
106
+
107
+ function collectAllScenePenetrations(nodes: Readonly<Record<string, SceneNodeLike>>): FramingPenetration[] {
108
+ const out: FramingPenetration[] = []
109
+ const wallsByLevel = new Map<string, ReturnType<typeof extractWallSegments>>()
110
+ const bonesByLevel = new Map<string, ReturnType<typeof extractBonesPlumbingContext>>()
111
+ for (const n of Object.values(nodes)) {
112
+ if (n.type !== 'plumbing:pipe-run' || !Array.isArray(n.path)) continue
113
+ const lvlId = resolveNodeLevelId(nodes, n)
114
+ const cacheKey = lvlId ?? '__root__'
115
+ let walls = wallsByLevel.get(cacheKey)
116
+ if (!walls) {
117
+ walls = extractWallSegments(nodes, lvlId)
118
+ wallsByLevel.set(cacheKey, walls)
119
+ }
120
+ let bones = bonesByLevel.get(cacheKey)
121
+ if (!bones) {
122
+ bones = extractBonesPlumbingContext(nodes, lvlId)
123
+ bonesByLevel.set(cacheKey, bones)
124
+ }
125
+ out.push(
126
+ ...computePipeFramingPenetrations({
127
+ pipeRunId: n.id,
128
+ path: n.path as ReadonlyArray<Vec3>,
129
+ pipeSize: (n.nominalSize as PipeNominalSize) || '1/2"',
130
+ material: (n.material as PipeMaterial) || 'pex-a',
131
+ walls,
132
+ bonesContext: bones,
133
+ }),
134
+ )
135
+ }
136
+ return out
137
+ }
138
+
139
+ export type PlumbingOpChanges = {
140
+ create?: Array<{ node: AnyNode; parentId?: string }>
141
+ delete?: string[]
142
+ }
143
+
144
+ export const plumbingAgentOperations = {
145
+ plumbing_place_equipment: (
146
+ nodes: SceneNodes,
147
+ input: {
148
+ levelId?: string
149
+ name?: string
150
+ equipmentKind?: EquipmentKind
151
+ position: [number, number, number]
152
+ rotation?: number
153
+ roomName?: string
154
+ capacityGal?: number
155
+ gasBtuh?: number
156
+ watts?: number
157
+ roomVolumeCuFt?: number
158
+ },
159
+ ctx: AgentContext,
160
+ ): {
161
+ result: {
162
+ nodeId: string
163
+ name: string | undefined
164
+ equipmentKind: EquipmentKind
165
+ levelId: string
166
+ electricalDemand: ElectricalPowerDemand | null
167
+ }
168
+ changes: PlumbingOpChanges
169
+ } => {
170
+ const levelId = resolveLevelId(nodes, input.levelId, ctx)
171
+ if (!levelId) refuse('level_not_found', 'No level found in scene to host plumbing equipment.')
172
+ const kind = input.equipmentKind ?? 'water-heater-tank-electric'
173
+ const id = deterministicId('plumbeq', nodes)
174
+ const electricalDemand = getEquipmentElectricalDemand(kind, input.watts)
175
+ const defaultCapGal =
176
+ kind === 'water-heater-tank-electric' || kind === 'water-heater-tank-gas' || kind === 'water-heater-hpwh'
177
+ ? 50
178
+ : kind === 'expansion-tank'
179
+ ? 2
180
+ : 0
181
+ const defaultGasBtuh =
182
+ kind === 'water-heater-tank-gas'
183
+ ? 40000
184
+ : kind === 'water-heater-tankless-gas'
185
+ ? 199000
186
+ : 0
187
+ const isWaterHeater = kind.startsWith('water-heater-')
188
+ const node = {
189
+ object: 'node',
190
+ id,
191
+ type: 'plumbing:equipment',
192
+ name: input.name ?? kind,
193
+ parentId: levelId,
194
+ visible: true,
195
+ metadata: {},
196
+ position: input.position,
197
+ rotation: input.rotation ?? 0,
198
+ equipmentKind: kind,
199
+ roomName: input.roomName ?? 'Utility',
200
+ capacityGal: input.capacityGal ?? defaultCapGal,
201
+ gasBtuh: input.gasBtuh ?? defaultGasBtuh,
202
+ watts: input.watts ?? (electricalDemand?.loadVa ?? 0),
203
+ ...(typeof input.roomVolumeCuFt === 'number' ? { roomVolumeCuFt: input.roomVolumeCuFt } : {}),
204
+ hasDrainPan: isWaterHeater,
205
+ hasTpDischarge: isWaterHeater,
206
+ hasExpansionTank: isWaterHeater,
207
+ electricalDemand,
208
+ } as unknown as AnyNode
209
+
210
+ return {
211
+ result: {
212
+ nodeId: id,
213
+ name: node.name,
214
+ equipmentKind: kind,
215
+ levelId,
216
+ electricalDemand,
217
+ },
218
+ changes: { create: [{ node, parentId: levelId }] },
219
+ }
220
+ },
221
+
222
+ plumbing_place_manifold: (
223
+ nodes: SceneNodes,
224
+ input: {
225
+ levelId?: string
226
+ name?: string
227
+ manifoldKind?: ManifoldKind
228
+ position: [number, number, number]
229
+ rotation?: number
230
+ portCount?: number
231
+ coverRemoved?: boolean
232
+ },
233
+ ctx: AgentContext,
234
+ ): {
235
+ result: {
236
+ nodeId: string
237
+ name: string | undefined
238
+ manifoldKind: ManifoldKind
239
+ portCount: number
240
+ levelId: string
241
+ }
242
+ changes: PlumbingOpChanges
243
+ } => {
244
+ const levelId = resolveLevelId(nodes, input.levelId, ctx)
245
+ if (!levelId) refuse('level_not_found', 'No level found in scene to host plumbing manifold.')
246
+ const id = deterministicId('plumbman', nodes)
247
+ const kind = input.manifoldKind ?? 'pex-homerun'
248
+ const portCount = input.portCount ?? 12
249
+ const defaultManifoldName =
250
+ kind === 'gas-csst'
251
+ ? `CSST Fuel-Gas Manifold (${portCount}-Port)`
252
+ : kind === 'copper-header'
253
+ ? `Type L Copper Header (${portCount}-Port)`
254
+ : `PEX Home-Run Manifold (${portCount}-Port)`
255
+ const node = {
256
+ object: 'node',
257
+ id,
258
+ type: 'plumbing:manifold',
259
+ name: input.name ?? defaultManifoldName,
260
+ parentId: levelId,
261
+ visible: true,
262
+ metadata: {},
263
+ position: input.position,
264
+ rotation: input.rotation ?? 0,
265
+ manifoldKind: kind,
266
+ portCount,
267
+ supplyMaterial: kind === 'gas-csst' ? 'csst' : kind === 'copper-header' ? 'copper-l' : 'pex-a',
268
+ coverRemoved: input.coverRemoved ?? false,
269
+ } as unknown as AnyNode
270
+
271
+ return {
272
+ result: { nodeId: id, name: node.name, manifoldKind: kind, portCount, levelId },
273
+ changes: { create: [{ node, parentId: levelId }] },
274
+ }
275
+ },
276
+
277
+ plumbing_place_fixture: (
278
+ nodes: SceneNodes,
279
+ input: {
280
+ levelId?: string
281
+ name?: string
282
+ fixtureKind?: FixtureKind
283
+ position: [number, number, number]
284
+ rotation?: number
285
+ roomName?: string
286
+ codeEdition?: CodeEdition
287
+ autoConnect?: boolean
288
+ occupancy?: OccupancyType
289
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc'
290
+ dwvMaterial?: 'pvc-dwv' | 'abs-dwv' | 'cast-iron'
291
+ foundationType?: FoundationType
292
+ },
293
+ ctx: AgentContext,
294
+ ): {
295
+ result: {
296
+ nodeId: string
297
+ name: string | undefined
298
+ fixtureKind: FixtureKind
299
+ dfu: number
300
+ wsfu: number
301
+ electricalDemand: ElectricalPowerDemand | null
302
+ connectedSystems?: PlumbingSystem[]
303
+ connectedPipeRunCount?: number
304
+ hasSupplySource?: boolean
305
+ hasDwvStack?: boolean
306
+ }
307
+ changes: PlumbingOpChanges
308
+ } => {
309
+ const levelId = resolveLevelId(nodes, input.levelId, ctx)
310
+ if (!levelId) refuse('level_not_found', 'No level found in scene to host plumbing fixture.')
311
+ const kind = input.fixtureKind ?? 'lavatory'
312
+ const spec = FIXTURE_SPECS[kind]
313
+ const id = deterministicId('plumbfix', nodes)
314
+ const electricalDemand = getFixtureElectricalDemand(kind)
315
+ const codeEdition = input.codeEdition ?? 'IPC-2021'
316
+ const occupancy = input.occupancy ?? 'residential'
317
+ const dfu = getFixtureDfu(kind, codeEdition)
318
+ const wsfu = getFixtureWsfu(kind, occupancy)
319
+ const resolvedPos: [number, number, number] = [
320
+ input.position[0],
321
+ input.position[1] === 0 && spec.roughInHeightM > 0 ? spec.roughInHeightM : input.position[1],
322
+ input.position[2],
323
+ ]
324
+ const node = {
325
+ object: 'node',
326
+ id,
327
+ type: 'plumbing:fixture',
328
+ name: input.name ?? spec.label,
329
+ parentId: levelId,
330
+ visible: true,
331
+ metadata: {},
332
+ position: resolvedPos,
333
+ rotation: input.rotation ?? 0,
334
+ fixtureKind: kind,
335
+ roomName: input.roomName ?? defaultRoomNameForFixture(kind),
336
+ dfu,
337
+ wsfuCold: wsfu.cold,
338
+ wsfuHot: wsfu.hot,
339
+ wsfuTotal: wsfu.total,
340
+ trapSize: spec.minTrapIn,
341
+ drainSize: spec.minDrainIn,
342
+ ventSize: spec.minVentIn,
343
+ supplySize: spec.supplySizeIn,
344
+ hasVacuumBreaker: kind === 'hose-bibb',
345
+ hasPTrap: spec.needsPTrap,
346
+ electricalDemand,
347
+ } as unknown as AnyNode
348
+
349
+ const created: Array<{ node: AnyNode; parentId?: string }> = [{ node, parentId: levelId }]
350
+ let connectedSystems: PlumbingSystem[] | undefined
351
+ let connectedPipeRunCount: number | undefined
352
+ let hasSupplySource: boolean | undefined
353
+ let hasDwvStack: boolean | undefined
354
+
355
+ if (input.autoConnect === true) {
356
+ const conn = planConnectSingleFixture(
357
+ asRecord(nodes),
358
+ {
359
+ id,
360
+ name: input.name ?? spec.label,
361
+ fixtureKind: kind,
362
+ position: resolvedPos,
363
+ rotation: input.rotation ?? 0,
364
+ dfu,
365
+ wsfuCold: wsfu.cold,
366
+ wsfuHot: wsfu.hot,
367
+ drainSize: spec.minDrainIn,
368
+ ventSize: spec.minVentIn,
369
+ supplySize: spec.supplySizeIn,
370
+ },
371
+ {
372
+ levelId,
373
+ codeEdition,
374
+ occupancy,
375
+ supplyMaterial: input.supplyMaterial,
376
+ dwvMaterial: input.dwvMaterial,
377
+ foundationType: input.foundationType,
378
+ },
379
+ )
380
+ connectedSystems = conn.connectedSystems
381
+ connectedPipeRunCount = conn.pipeRuns.length
382
+ hasSupplySource = conn.hasSupplySource
383
+ hasDwvStack = conn.hasDwvStack
384
+ for (const r of conn.pipeRuns) {
385
+ const pipeNode = {
386
+ object: 'node',
387
+ ...r,
388
+ type: 'plumbing:pipe-run',
389
+ parentId: levelId,
390
+ visible: true,
391
+ metadata: {},
392
+ showFramingPenetrations: true,
393
+ } as unknown as AnyNode
394
+ created.push({ node: pipeNode, parentId: levelId })
395
+ }
396
+ }
397
+
398
+ return {
399
+ result: {
400
+ nodeId: id,
401
+ name: node.name,
402
+ fixtureKind: kind,
403
+ dfu,
404
+ wsfu: wsfu.total,
405
+ electricalDemand,
406
+ ...(connectedSystems !== undefined
407
+ ? { connectedSystems, connectedPipeRunCount, hasSupplySource, hasDwvStack }
408
+ : {}),
409
+ },
410
+ changes: { create: created },
411
+ }
412
+ },
413
+
414
+ plumbing_route_pipe: (
415
+ nodes: SceneNodes,
416
+ input: {
417
+ levelId?: string
418
+ name?: string
419
+ from: [number, number, number]
420
+ to: [number, number, number]
421
+ system?: PlumbingSystem
422
+ material?: PipeMaterial
423
+ nominalSize?: PipeNominalSize
424
+ foundationType?: FoundationType
425
+ dfuLoad?: number
426
+ wsfuLoad?: number
427
+ gasBtuh?: number
428
+ hasCleanout?: boolean
429
+ },
430
+ ctx: AgentContext,
431
+ ): {
432
+ result: {
433
+ nodeId: string
434
+ system: PlumbingSystem
435
+ lengthFt: number
436
+ slopeInPerFt: number
437
+ detoured: boolean
438
+ clashes: ReturnType<typeof extractPlumbingObstacles>
439
+ penetrations: FramingPenetration[]
440
+ }
441
+ changes: PlumbingOpChanges
442
+ } => {
443
+ const levelId = resolveLevelId(nodes, input.levelId, ctx)
444
+ if (!levelId) refuse('level_not_found', 'No level found in scene to route pipe.')
445
+ const record = asRecord(nodes)
446
+ const system = input.system ?? 'cold-water'
447
+ const material: PipeMaterial =
448
+ input.material ??
449
+ (system.startsWith('dwv')
450
+ ? 'pvc-dwv'
451
+ : system === 'fuel-gas'
452
+ ? 'black-iron'
453
+ : system === 'dryer-vent'
454
+ ? 'rigid-aluminum'
455
+ : system === 'condensate'
456
+ ? 'pvc-dwv'
457
+ : 'pex-a')
458
+ const nominalSize: PipeNominalSize =
459
+ input.nominalSize ??
460
+ (system === 'dwv-drain'
461
+ ? '3"'
462
+ : system === 'dwv-vent'
463
+ ? '2"'
464
+ : system === 'dryer-vent'
465
+ ? '4"'
466
+ : system === 'fuel-gas'
467
+ ? '3/4"'
468
+ : system === 'condensate'
469
+ ? '3/4"'
470
+ : '1/2"')
471
+ const obstacles = extractPlumbingObstacles(record, levelId)
472
+ const levelH = resolveLevelHeightM(record, levelId)
473
+
474
+ let path: Vec3[]
475
+ let slopeInPerFt = 0
476
+ let lengthFt = 0
477
+ let detoured = false
478
+ let clashes: ReturnType<typeof extractPlumbingObstacles> = []
479
+
480
+ if (system === 'dwv-drain') {
481
+ const r = routeDwvDrainRun({
482
+ from: input.from,
483
+ to: input.to,
484
+ nominalSize,
485
+ material,
486
+ foundationType: input.foundationType ?? 'crawlspace',
487
+ obstacles,
488
+ })
489
+ path = r.path
490
+ slopeInPerFt = r.slopeInPerFt
491
+ lengthFt = r.lengthFt
492
+ detoured = r.detoured
493
+ clashes = r.clashes
494
+ } else if (system === 'dwv-vent') {
495
+ const r = routeVentRun({
496
+ from: input.from,
497
+ stackPoint: [input.to[0], input.to[2]],
498
+ floodRimHeightM: 0.9,
499
+ ceilingHeightM: levelH,
500
+ nominalSize,
501
+ material,
502
+ obstacles,
503
+ })
504
+ path = r.path
505
+ lengthFt = r.lengthFt
506
+ detoured = r.detoured
507
+ clashes = r.clashes
508
+ } else {
509
+ const planeY = (input.foundationType ?? 'crawlspace') === 'slab' ? levelH - 0.25 : -0.16
510
+ const r = routePressurizedPipeRun({
511
+ from: input.from,
512
+ to: input.to,
513
+ routingPlaneY: planeY,
514
+ nominalSize,
515
+ material,
516
+ euclideanInCavity: material === 'pex-a' || material === 'pex-b',
517
+ obstacles,
518
+ })
519
+ path = r.path
520
+ lengthFt = r.lengthFt
521
+ detoured = r.detoured
522
+ clashes = r.clashes
523
+ }
524
+
525
+ const id = deterministicId('plumbpipe', nodes)
526
+ const walls = extractWallSegments(record, levelId)
527
+ const bones = extractBonesPlumbingContext(record, levelId)
528
+ const penetrations = computePipeFramingPenetrations({
529
+ pipeRunId: id,
530
+ path,
531
+ pipeSize: nominalSize,
532
+ material,
533
+ walls,
534
+ bonesContext: bones,
535
+ })
536
+
537
+ const node = {
538
+ object: 'node',
539
+ id,
540
+ type: 'plumbing:pipe-run',
541
+ name: input.name ?? `${nominalSize} ${system} (${material})`,
542
+ parentId: levelId,
543
+ visible: true,
544
+ metadata: {},
545
+ path,
546
+ system,
547
+ material,
548
+ nominalSize,
549
+ slopeInPerFt,
550
+ dfuLoad: input.dfuLoad ?? 0,
551
+ wsfuLoad: input.wsfuLoad ?? 0,
552
+ gasBtuh: input.gasBtuh ?? 0,
553
+ hasCleanout: input.hasCleanout ?? false,
554
+ hasSedimentTrap: system === 'fuel-gas',
555
+ hasShutoffWithin6Ft: true,
556
+ isHorizontalSanTee: false,
557
+ isMainVentStack: false,
558
+ showFramingPenetrations: true,
559
+ } as unknown as AnyNode
560
+
561
+ return {
562
+ result: { nodeId: id, system, lengthFt, slopeInPerFt, detoured, clashes, penetrations },
563
+ changes: { create: [{ node, parentId: levelId }] },
564
+ }
565
+ },
566
+
567
+ plumbing_autopopulate: (
568
+ nodes: SceneNodes,
569
+ input: {
570
+ levelId?: string
571
+ occupancy?: OccupancyType
572
+ codeEdition?: CodeEdition
573
+ supplyTopology?: SupplyTopology
574
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc'
575
+ dwvMaterial?: 'pvc-dwv' | 'abs-dwv' | 'cast-iron'
576
+ foundationType?: FoundationType
577
+ waterHeaterKind?:
578
+ | 'water-heater-tank-electric'
579
+ | 'water-heater-tank-gas'
580
+ | 'water-heater-tankless-gas'
581
+ | 'water-heater-hpwh'
582
+ includeFuelGas?: boolean
583
+ includeDryerVent?: boolean
584
+ includeHotRecirc?: boolean
585
+ bonesMode?: BonesIngestionMode
586
+ clearExisting?: boolean
587
+ syncOnly?: boolean
588
+ },
589
+ ctx: AgentContext,
590
+ ): {
591
+ result: {
592
+ levelId: string
593
+ summary: string
594
+ equipmentCount: number
595
+ manifoldCount: number
596
+ fixtureCount: number
597
+ pipeRunCount: number
598
+ bonesAnchorsUsed: string[]
599
+ audit: ReturnType<typeof auditScenePlumbing>
600
+ }
601
+ changes: PlumbingOpChanges
602
+ } => {
603
+ const levelId = resolveLevelId(nodes, input.levelId, ctx)
604
+ if (!levelId) refuse('level_not_found', 'No level found in scene to auto-populate plumbing.')
605
+
606
+ const origRecord = asRecord(nodes)
607
+
608
+ // Incremental sync mode: keep existing plumbing core/pipes intact and connect newly placed
609
+ // real-world catalog/furnishing fixtures & unconnected manual fixtures in one undo step.
610
+ if (input.syncOnly === true) {
611
+ const sync = planSyncPlumbingFixtures(origRecord, {
612
+ levelId,
613
+ occupancy: input.occupancy,
614
+ codeEdition: input.codeEdition,
615
+ supplyTopology: input.supplyTopology,
616
+ supplyMaterial: input.supplyMaterial,
617
+ dwvMaterial: input.dwvMaterial,
618
+ foundationType: input.foundationType,
619
+ waterHeaterKind: input.waterHeaterKind,
620
+ includeFuelGas: input.includeFuelGas,
621
+ includeDryerVent: input.includeDryerVent,
622
+ includeHotRecirc: input.includeHotRecirc,
623
+ bonesMode: input.bonesMode,
624
+ })
625
+ const created: Array<{ node: AnyNode; parentId: string }> = []
626
+ const simulated: Record<string, SceneNodeLike> = { ...origRecord }
627
+ const replacedPipeIds = sync.replacedPipeIds ?? []
628
+ for (const delId of replacedPipeIds) {
629
+ delete simulated[delId]
630
+ }
631
+ const eqList = sync.fullPlan ? sync.fullPlan.equipment : []
632
+ const manList = sync.fullPlan ? sync.fullPlan.manifolds : []
633
+ for (const eq of eqList) {
634
+ const node = { object: 'node', ...eq, type: 'plumbing:equipment', parentId: levelId, visible: true, metadata: {} }
635
+ created.push({ node: node as unknown as AnyNode, parentId: levelId })
636
+ simulated[eq.id] = node as unknown as SceneNodeLike
637
+ }
638
+ for (const m of manList) {
639
+ const node = { object: 'node', ...m, type: 'plumbing:manifold', parentId: levelId, visible: true, metadata: {} }
640
+ created.push({ node: node as unknown as AnyNode, parentId: levelId })
641
+ simulated[m.id] = node as unknown as SceneNodeLike
642
+ }
643
+ for (const f of sync.fixtures) {
644
+ const node = { object: 'node', ...f, type: 'plumbing:fixture', parentId: levelId, visible: true, metadata: {} }
645
+ created.push({ node: node as unknown as AnyNode, parentId: levelId })
646
+ simulated[f.id] = node as unknown as SceneNodeLike
647
+ }
648
+ for (const r of sync.pipeRuns) {
649
+ const node = {
650
+ object: 'node',
651
+ ...r,
652
+ type: 'plumbing:pipe-run',
653
+ parentId: levelId,
654
+ visible: true,
655
+ metadata: {},
656
+ showFramingPenetrations: true,
657
+ }
658
+ created.push({ node: node as unknown as AnyNode, parentId: levelId })
659
+ simulated[r.id] = node as unknown as SceneNodeLike
660
+ }
661
+ const audit = auditScenePlumbing(simulated, {
662
+ codeEdition: input.codeEdition ?? 'IPC-2021',
663
+ occupancy: input.occupancy,
664
+ })
665
+ return {
666
+ result: {
667
+ levelId,
668
+ summary: sync.summary,
669
+ equipmentCount: eqList.length,
670
+ manifoldCount: manList.length,
671
+ fixtureCount: sync.fixtures.length,
672
+ pipeRunCount: sync.pipeRuns.length,
673
+ bonesAnchorsUsed: sync.fullPlan?.bonesAnchorsUsed ?? [],
674
+ audit,
675
+ },
676
+ changes: {
677
+ ...(replacedPipeIds.length > 0 ? { delete: replacedPipeIds } : {}),
678
+ create: created,
679
+ },
680
+ }
681
+ }
682
+
683
+ const deleteIds: string[] = []
684
+ const baseNodes: Record<string, SceneNodeLike> = { ...origRecord }
685
+ if (input.clearExisting !== false) {
686
+ const levelCount = Object.values(origRecord).filter((n) => n.type === 'level').length
687
+ const allowRootOrphans = levelCount <= 1
688
+ for (const [id, n] of Object.entries(origRecord)) {
689
+ if (
690
+ n.type.startsWith('plumbing:') &&
691
+ ((allowRootOrphans && !n.parentId) || belongsToLevel(origRecord, n, levelId))
692
+ ) {
693
+ deleteIds.push(id)
694
+ delete baseNodes[id]
695
+ }
696
+ }
697
+ }
698
+
699
+ const plan = planPlumbingAutoPopulate(baseNodes, {
700
+ levelId,
701
+ occupancy: input.occupancy,
702
+ codeEdition: input.codeEdition,
703
+ supplyTopology: input.supplyTopology,
704
+ supplyMaterial: input.supplyMaterial,
705
+ dwvMaterial: input.dwvMaterial,
706
+ foundationType: input.foundationType,
707
+ waterHeaterKind: input.waterHeaterKind,
708
+ includeFuelGas: input.includeFuelGas,
709
+ includeDryerVent: input.includeDryerVent,
710
+ includeHotRecirc: input.includeHotRecirc,
711
+ bonesMode: input.bonesMode,
712
+ })
713
+
714
+ const created: Array<{ node: AnyNode; parentId: string }> = []
715
+ const simulated: Record<string, SceneNodeLike> = { ...baseNodes }
716
+
717
+ for (const eq of plan.equipment) {
718
+ const node = {
719
+ object: 'node',
720
+ ...eq,
721
+ type: 'plumbing:equipment',
722
+ parentId: levelId,
723
+ visible: true,
724
+ metadata: {},
725
+ }
726
+ created.push({ node: node as unknown as AnyNode, parentId: levelId })
727
+ simulated[eq.id] = node as unknown as SceneNodeLike
728
+ }
729
+ for (const m of plan.manifolds) {
730
+ const node = {
731
+ object: 'node',
732
+ ...m,
733
+ type: 'plumbing:manifold',
734
+ parentId: levelId,
735
+ visible: true,
736
+ metadata: {},
737
+ }
738
+ created.push({ node: node as unknown as AnyNode, parentId: levelId })
739
+ simulated[m.id] = node as unknown as SceneNodeLike
740
+ }
741
+ for (const f of plan.fixtures) {
742
+ const node = {
743
+ object: 'node',
744
+ ...f,
745
+ type: 'plumbing:fixture',
746
+ parentId: levelId,
747
+ visible: true,
748
+ metadata: {},
749
+ }
750
+ created.push({ node: node as unknown as AnyNode, parentId: levelId })
751
+ simulated[f.id] = node as unknown as SceneNodeLike
752
+ }
753
+ for (const r of plan.pipeRuns) {
754
+ const node = {
755
+ object: 'node',
756
+ ...r,
757
+ type: 'plumbing:pipe-run',
758
+ parentId: levelId,
759
+ visible: true,
760
+ metadata: {},
761
+ showFramingPenetrations: true,
762
+ }
763
+ created.push({ node: node as unknown as AnyNode, parentId: levelId })
764
+ simulated[r.id] = node as unknown as SceneNodeLike
765
+ }
766
+
767
+ const audit = auditScenePlumbing(simulated, {
768
+ codeEdition: plan.codeEdition,
769
+ occupancy: input.occupancy,
770
+ })
771
+ return {
772
+ result: {
773
+ levelId,
774
+ summary: plan.summary,
775
+ equipmentCount: plan.equipment.length,
776
+ manifoldCount: plan.manifolds.length,
777
+ fixtureCount: plan.fixtures.length,
778
+ pipeRunCount: plan.pipeRuns.length,
779
+ bonesAnchorsUsed: plan.bonesAnchorsUsed,
780
+ audit,
781
+ },
782
+ changes: {
783
+ ...(deleteIds.length > 0 ? { delete: deleteIds } : {}),
784
+ create: created,
785
+ },
786
+ }
787
+ },
788
+
789
+ plumbing_calculate_loads: (
790
+ nodes: SceneNodes,
791
+ input: {
792
+ codeEdition?: CodeEdition
793
+ occupancy?: OccupancyType
794
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'copper-m' | 'cpvc'
795
+ },
796
+ ) => {
797
+ const schedule = buildPlumbingSchedule(asRecord(nodes), {
798
+ codeEdition: input.codeEdition ?? 'IPC-2021',
799
+ occupancy: input.occupancy ?? 'residential',
800
+ ...(input.supplyMaterial ? { supplyMaterial: input.supplyMaterial } : {}),
801
+ })
802
+ return {
803
+ result: {
804
+ loads: schedule.loads,
805
+ electricalCoordination: schedule.electricalCoordination,
806
+ },
807
+ }
808
+ },
809
+
810
+ plumbing_generate_schedule: (
811
+ nodes: SceneNodes,
812
+ input: {
813
+ codeEdition?: CodeEdition
814
+ occupancy?: OccupancyType
815
+ laborRateUsd?: number
816
+ materialMarkupPct?: number
817
+ salesTaxPct?: number
818
+ },
819
+ ) => {
820
+ const record = asRecord(nodes)
821
+ const schedule = buildPlumbingSchedule(record, {
822
+ codeEdition: input.codeEdition ?? 'IPC-2021',
823
+ occupancy: input.occupancy,
824
+ })
825
+ const bom = buildPlumbingBom(record, {
826
+ codeEdition: input.codeEdition ?? 'IPC-2021',
827
+ occupancy: input.occupancy,
828
+ laborRateUsd: input.laborRateUsd ?? 115,
829
+ materialMarkupPct: input.materialMarkupPct ?? 0,
830
+ salesTaxPct: input.salesTaxPct ?? 0,
831
+ schedule,
832
+ })
833
+ const penetrations = collectAllScenePenetrations(record)
834
+ return {
835
+ result: {
836
+ schedule,
837
+ bom,
838
+ penetrations,
839
+ scheduleCsv: formatPlumbingScheduleCsv(schedule),
840
+ bomCsv: formatPlumbingBomCsv(bom),
841
+ },
842
+ }
843
+ },
844
+
845
+ plumbing_audit_ipc: (nodes: SceneNodes, input: { codeEdition?: CodeEdition; occupancy?: OccupancyType }) => {
846
+ const audit = auditScenePlumbing(asRecord(nodes), {
847
+ codeEdition: input.codeEdition ?? 'IPC-2021',
848
+ occupancy: input.occupancy,
849
+ })
850
+ return {
851
+ result: audit,
852
+ }
853
+ },
854
+ } satisfies AgentOperations