dsh-eplan 0.0.0-stage → 0.14.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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -3
  3. package/cordis.patch.yml +182 -0
  4. package/docs/INSTALL.md +86 -0
  5. package/docs/LESSONS.md +224 -0
  6. package/docs/interfaces.md +183 -0
  7. package/docs/merged-skills/eplan-setup.md +63 -0
  8. package/docs/merged-skills/eplan-troubleshooting.md +149 -0
  9. package/icon.png +0 -0
  10. package/icon.svg +13 -0
  11. package/knowledge/KNOWLEDGE.md +413 -0
  12. package/knowledge/symbols/BP.png +0 -0
  13. package/knowledge/symbols/CDPST.png +0 -0
  14. package/knowledge/symbols/CO.png +0 -0
  15. package/knowledge/symbols/FA3.png +0 -0
  16. package/knowledge/symbols/TLRO.png +0 -0
  17. package/knowledge/symbols/TLRU.png +0 -0
  18. package/knowledge/symbols/TOUL.png +0 -0
  19. package/knowledge/symbols/TOUR.png +0 -0
  20. package/knowledge/symbols/manifest.json +91 -0
  21. package/locale/en.json +6 -0
  22. package/locale/zh.json +6 -0
  23. package/native/bridge/build.ps1 +73 -0
  24. package/native/bridge/src/Json.cs +383 -0
  25. package/native/bridge/src/Program.cs +1133 -0
  26. package/native/host/build.ps1 +74 -0
  27. package/native/host/src/ActionsTool.cs +225 -0
  28. package/native/host/src/BoxTool.cs +196 -0
  29. package/native/host/src/CheckTool.cs +186 -0
  30. package/native/host/src/Context.cs +169 -0
  31. package/native/host/src/DarkScheme.cs +111 -0
  32. package/native/host/src/DiagnoseTool.cs +115 -0
  33. package/native/host/src/Dispatcher.cs +51 -0
  34. package/native/host/src/DrawTool.cs +316 -0
  35. package/native/host/src/Entry.cs +111 -0
  36. package/native/host/src/ExportTool.cs +213 -0
  37. package/native/host/src/InspectTool.cs +367 -0
  38. package/native/host/src/KnowledgeTool.cs +166 -0
  39. package/native/host/src/LookTool.cs +257 -0
  40. package/native/host/src/OpLog.cs +289 -0
  41. package/native/host/src/PageCreateTool.cs +521 -0
  42. package/native/host/src/PageOpenTool.cs +62 -0
  43. package/native/host/src/PagesTool.cs +95 -0
  44. package/native/host/src/Paths.cs +91 -0
  45. package/native/host/src/PlacementEditTool.cs +234 -0
  46. package/native/host/src/ProbePropsTool.cs +152 -0
  47. package/native/host/src/ProjectCreateTool.cs +176 -0
  48. package/native/host/src/ProjectTool.cs +167 -0
  49. package/native/host/src/PropWriter.cs +70 -0
  50. package/native/host/src/PropsTool.cs +257 -0
  51. package/native/host/src/StatusTool.cs +168 -0
  52. package/native/host/src/SymbolInfoTool.cs +144 -0
  53. package/native/host/src/SymbolInsertTool.cs +261 -0
  54. package/native/host/src/SymbolsTool.cs +94 -0
  55. package/native/host/src/TagLocTool.cs +108 -0
  56. package/native/script/EplanMcpBootstrap.cs +221 -0
  57. package/native/script/build-symbol-gallery.mjs +231 -0
  58. package/native/script/prepare-install.ps1 +57 -0
  59. package/native/script/prune.mjs +132 -0
  60. package/native/script/verify-bootstrap.ps1 +62 -0
  61. package/package.json +53 -4
  62. package/preset/bootstrap.js +498 -0
  63. package/preset/experience-nudge.js +47 -0
  64. package/preset/image-budget.js +175 -0
  65. package/preset/knowledge-tool.js +180 -0
  66. package/preset/mcp-link.js +100 -0
  67. package/preset/prompt-surface.js +76 -0
  68. package/preset/restrict-tools.js +141 -0
  69. package/preset/skill-docs.js +181 -0
  70. package/preset/video-digest.js +294 -0
  71. package/preset/video-tool.js +92 -0
  72. package/server/compact.mjs +623 -0
  73. package/server/edit-args.mjs +67 -0
  74. package/server/fuzzy.mjs +57 -0
  75. package/server/launch-decision.mjs +26 -0
  76. package/server/measure.mjs +320 -0
  77. package/server/pdf.mjs +185 -0
  78. package/server/pdf2png.ps1 +99 -0
  79. package/server/server.mjs +3797 -0
  80. package/server/video.mjs +857 -0
  81. package/setup.mjs +223 -0
  82. package/skills/eplan-annotations/SKILL.md +55 -0
  83. package/skills/eplan-drawing/SKILL.md +206 -0
  84. package/skills/eplan-project/SKILL.md +41 -0
  85. package/skills/eplan-review/SKILL.md +80 -0
  86. package/skills/eplan-symbols/SKILL.md +142 -0
  87. package/test/check-docs.mjs +106 -0
  88. package/test/foreground.ps1 +21 -0
  89. package/test/smoke-all.mjs +229 -0
@@ -0,0 +1,623 @@
1
+ // 载荷收敛层:把桥接器返回的原始 JSON 压成「模型真正需要的那一层」。
2
+ //
3
+ // 为什么需要这一层:桥接器的 inspect 返回带缩进的 2 空格 JSON,一页 107 个对象
4
+ // 实测 80,924 字符,其中**缩进和空字段占了一半以上**(紧凑序列化只有 32,927)。
5
+ // 模型拿到的每一步都要为这些字节付一次上下文,而真正要做的判断(有没有重叠、
6
+ // 引脚接没接上、超没超图框)反而要它自己在脑子里算。
7
+ //
8
+ // 这里只做三件事,不改任何 EPLAN 行为:
9
+ // 1) compact:去掉缩进与空串噪声;
10
+ // 2) view:summary / list / full 三档,默认只给结论;
11
+ // 3) geometry:把「重叠 / 共点 / 压字 / 偏栅格 / 超框」算好直接给问题清单。
12
+ import { createHash } from 'node:crypto'
13
+
14
+ /** 桥接器的文本块可能是 JSON,也可能不是(比如渲染信息)。解析失败返回 null。 */
15
+ export function parseJsonText(text) {
16
+ if (typeof text !== 'string') return null
17
+ const trimmed = text.trim()
18
+ if (!trimmed) return null
19
+ if (trimmed[0] !== '{' && trimmed[0] !== '[') return null
20
+ try {
21
+ return JSON.parse(trimmed)
22
+ } catch {
23
+ return null
24
+ }
25
+ }
26
+
27
+ /** 稳定短摘要,用来判断「和上次一模一样」,也用来做内容哈希。 */
28
+ export function digest(value) {
29
+ const text = typeof value === 'string' ? value : JSON.stringify(value ?? null)
30
+ return createHash('sha1').update(text ?? '').digest('hex').slice(0, 12)
31
+ }
32
+
33
+ /**
34
+ * 重复调用记忆:同参数再问一次时,只回「没变」而不是把整包重发一遍。
35
+ *
36
+ * 实测 42 分钟里 341 KB(占全部内层载荷 31%)是字节级重复 —— 5 次相同的
37
+ * symbol_catalog 42,516 B、6 次相同的 10,644 B。模型之所以重问,是因为它
38
+ * 不确定拿到的还是不是同一份;明确回一句 unchanged 比省字节更重要。
39
+ */
40
+ export class RepeatMemo {
41
+ constructor(limit = 64) {
42
+ this.limit = limit
43
+ this.map = new Map()
44
+ }
45
+
46
+ /**
47
+ * @returns {{repeat: boolean, digest: string}}
48
+ */
49
+ check(key, payload) {
50
+ const stamp = digest(payload)
51
+ const previous = this.map.get(key)
52
+ this.map.delete(key)
53
+ this.map.set(key, stamp)
54
+ while (this.map.size > this.limit) {
55
+ const oldest = this.map.keys().next().value
56
+ this.map.delete(oldest)
57
+ }
58
+ return { repeat: previous === stamp, digest: stamp }
59
+ }
60
+
61
+ clear() {
62
+ this.map.clear()
63
+ }
64
+ }
65
+
66
+ const round = (value) => Math.round(value * 1000) / 1000
67
+
68
+ const pointOf = (value) =>
69
+ Array.isArray(value) && value.length >= 2 && Number.isFinite(value[0]) && Number.isFinite(value[1])
70
+ ? [Number(value[0]), Number(value[1])]
71
+ : null
72
+
73
+ /**
74
+ * 一个对象的世界坐标点。
75
+ *
76
+ * 分两种包络,因为它们的含义完全相反:
77
+ * - 「引脚包络」= 元件本体,重叠一定是错的;
78
+ * - 「完整包络」还含属性放置点(设备标识那片文字),相邻元件之间重叠是常态,
79
+ * 只有本体不重叠而文字区域重叠时才值得提醒一句(标签会压字)。
80
+ */
81
+ function pointsOf(item, options = {}) {
82
+ const withProps = options.withProps !== false
83
+ const origin = pointOf(item?.location)
84
+ if (!origin) return []
85
+ const points = [origin]
86
+ for (const pin of item.pins ?? []) {
87
+ const offset = pointOf(pin?.location)
88
+ if (offset) points.push([origin[0] + offset[0], origin[1] + offset[1]])
89
+ }
90
+ if (withProps) {
91
+ for (const prop of item.propertyPlacements ?? []) {
92
+ const offset = pointOf(prop?.at)
93
+ if (offset) points.push([origin[0] + offset[0], origin[1] + offset[1]])
94
+ }
95
+ }
96
+ return points
97
+ }
98
+
99
+ const footprintOf = (item) => pointsOf(item)
100
+ const pinPointsOf = (item) => pointsOf(item, { withProps: false })
101
+
102
+ function bboxOf(points) {
103
+ if (points.length === 0) return null
104
+ let minX = Infinity
105
+ let minY = Infinity
106
+ let maxX = -Infinity
107
+ let maxY = -Infinity
108
+ for (const [x, y] of points) {
109
+ if (x < minX) minX = x
110
+ if (y < minY) minY = y
111
+ if (x > maxX) maxX = x
112
+ if (y > maxY) maxY = y
113
+ }
114
+ return { minX, minY, maxX, maxY }
115
+ }
116
+
117
+ /** 页面上所有对象按类型计数 + 世界坐标范围。 */
118
+ function censusOf(raw) {
119
+ const placements = Array.isArray(raw?.placements) ? raw.placements : []
120
+ const byType = {}
121
+ const bySymbol = {}
122
+ const deviceTags = []
123
+ const seenTags = new Set()
124
+ let pinTotal = 0
125
+ const pins = []
126
+
127
+ const points = []
128
+ for (const item of placements) {
129
+ const type = item?.type ?? 'Unknown'
130
+ byType[type] = (byType[type] ?? 0) + 1
131
+
132
+ if (type === 'Function' || type === 'InterruptionPoint') {
133
+ const symbol = item.symbolName ?? '(匿名)'
134
+ bySymbol[symbol] = (bySymbol[symbol] ?? 0) + 1
135
+
136
+ const origin = pointOf(item.location)
137
+ const itemPins = Array.isArray(item.pins) ? item.pins : []
138
+ pinTotal += itemPins.length
139
+ for (const pin of itemPins) {
140
+ const offset = pointOf(pin?.location)
141
+ if (!origin || !offset) continue
142
+ pins.push({
143
+ x: round(origin[0] + offset[0]),
144
+ y: round(origin[1] + offset[1]),
145
+ direction: pin?.direction ?? '?',
146
+ index: pin?.index ?? -1,
147
+ symbol,
148
+ objectId: item.objectId ?? null,
149
+ })
150
+ }
151
+ for (const point of footprintOf(item)) points.push(point)
152
+ } else {
153
+ const origin = pointOf(item.location)
154
+ if (origin) points.push(origin)
155
+ }
156
+ }
157
+
158
+ for (const fn of raw?.functions ?? []) {
159
+ const name = typeof fn?.name === 'string' ? fn.name : null
160
+ if (name && !seenTags.has(name)) {
161
+ seenTags.add(name)
162
+ deviceTags.push(name)
163
+ }
164
+ }
165
+
166
+ const box = bboxOf(points)
167
+ const bounds = box
168
+ ? {
169
+ min: [round(box.minX), round(box.minY)],
170
+ max: [round(box.maxX), round(box.maxY)],
171
+ width: round(box.maxX - box.minX),
172
+ height: round(box.maxY - box.minY),
173
+ }
174
+ : null
175
+
176
+ return { placements, byType, bySymbol, deviceTags, pinTotal, pins, bounds }
177
+ }
178
+
179
+ /**
180
+ * 几何门禁:把模型以前只能靠看渲染图发现的问题算出来。
181
+ *
182
+ * 只做能从 inspect 数据确定的判断,不确定的一律不报 —— 假阳性比漏报更贵,
183
+ * 因为模型会照着它去「修」一个本来正确的地方。
184
+ *
185
+ * @returns {Array<{kind: string, where: string, detail: string, fix: string}>}
186
+ */
187
+ export function geometryProblems(raw, options = {}) {
188
+ const grid = Number.isFinite(options.grid) ? options.grid : 4
189
+ const pageSize = Array.isArray(options.pageSize) ? options.pageSize : null
190
+ const { placements, pins } = censusOf(raw)
191
+ const problems = []
192
+
193
+ // 1) 同一个符号摆了两遍(同 symbol+变体、位置几乎相同)
194
+ const placed = new Map()
195
+ for (const item of placements) {
196
+ if (item?.type !== 'Function' && item?.type !== 'InterruptionPoint') continue
197
+ const origin = pointOf(item.location)
198
+ if (!origin) continue
199
+ const key = `${item.symbolName ?? '?'}#${item.variant ?? 0}`
200
+ const bucket = placed.get(key) ?? []
201
+ for (const other of bucket) {
202
+ if (Math.abs(other[0] - origin[0]) < 0.05 && Math.abs(other[1] - origin[1]) < 0.05) {
203
+ problems.push({
204
+ kind: 'duplicate_symbol',
205
+ where: `${item.symbolName} @ (${round(origin[0])}, ${round(origin[1])})`,
206
+ detail: '同一个符号变体在同一坐标被放了两次,叠在一起看不出来,但连接点会重复。',
207
+ fix: '删掉其中一个,或确认后把 at 改到别的坐标。',
208
+ })
209
+ }
210
+ }
211
+ bucket.push(origin)
212
+ placed.set(key, bucket)
213
+ }
214
+
215
+ // 2) 共用连接点:两个不同符号的引脚落在同一坐标 —— EPLAN 会报「共用连接点」
216
+ const pinAt = new Map()
217
+ for (const pin of pins) {
218
+ const key = `${pin.x},${pin.y}`
219
+ const bucket = pinAt.get(key) ?? []
220
+ bucket.push(pin)
221
+ pinAt.set(key, bucket)
222
+ }
223
+ const reportedPin = new Set()
224
+ for (const [key, bucket] of pinAt) {
225
+ if (bucket.length < 2) continue
226
+ const symbols = new Set(bucket.map((pin) => pin.symbol))
227
+ if (symbols.size < 2) continue
228
+ if (reportedPin.has(key)) continue
229
+ reportedPin.add(key)
230
+ const [x, y] = key.split(',')
231
+ problems.push({
232
+ kind: 'shared_pin_point',
233
+ where: `(${x}, ${y})`,
234
+ detail: `${[...symbols].join(' / ')} 的引脚落在同一点,EPLAN 视为一个节点;若本意是跨线不连,这里会静默连通。`,
235
+ fix: '确认该点是否应该相连;不该连就把其中一个符号挪开至少一个栅格。',
236
+ })
237
+ }
238
+
239
+ // 3) 本体压本体 / 只有文字区压
240
+ const funcs = placements
241
+ .filter((item) => item?.type === 'Function')
242
+ .map((item) => ({ item, pins: bboxOf(pinPointsOf(item)), box: bboxOf(footprintOf(item)) }))
243
+ .filter((entry) => entry.box !== null)
244
+
245
+ const overlapOf = (a, b, tolerance = 0.5) => {
246
+ if (!a || !b) return null
247
+ const width = Math.min(a.maxX, b.maxX) - Math.max(a.minX, b.minX)
248
+ const height = Math.min(a.maxY, b.maxY) - Math.max(a.minY, b.minY)
249
+ return width > tolerance && height > tolerance ? { width, height } : null
250
+ }
251
+
252
+ for (let i = 0; i < funcs.length; i += 1) {
253
+ for (let j = i + 1; j < funcs.length; j += 1) {
254
+ const body = overlapOf(funcs[i].pins, funcs[j].pins)
255
+ if (body) {
256
+ problems.push({
257
+ kind: 'symbol_overlap',
258
+ where: `${funcs[i].item.symbolName} ∩ ${funcs[j].item.symbolName}`,
259
+ detail: `两个元件的本体(引脚包络)重叠 ${round(body.width)}×${round(body.height)} mm。`,
260
+ fix: '把其中一个按栅格挪开,或改用更小的变体。',
261
+ })
262
+ continue
263
+ }
264
+ const label = overlapOf(funcs[i].box, funcs[j].box, 1)
265
+ if (label) {
266
+ problems.push({
267
+ kind: 'label_overlap',
268
+ where: `${funcs[i].item.symbolName} ∩ ${funcs[j].item.symbolName}`,
269
+ detail:
270
+ `本体没重叠,但设备标识那片文字区重叠 ${round(label.width)}×${round(label.height)} mm,渲染时标签会互相压字。`,
271
+ fix: '把其中一个的设备标识挪到另一侧,或改用更短的标识;不算错误,只影响可读性。',
272
+ })
273
+ }
274
+ }
275
+ }
276
+
277
+ // 4) 文字压在元件本体里(只看引脚包络 —— 标签区本来就是留给文字的)
278
+ for (const item of placements) {
279
+ if (item?.type !== 'Text') continue
280
+ const origin = pointOf(item.location)
281
+ if (!origin) continue
282
+ for (const entry of funcs) {
283
+ const box = entry.pins
284
+ if (!box) continue
285
+ if (
286
+ origin[0] > box.minX + 1 &&
287
+ origin[0] < box.maxX - 1 &&
288
+ origin[1] > box.minY + 1 &&
289
+ origin[1] < box.maxY - 1
290
+ ) {
291
+ problems.push({
292
+ kind: 'text_on_symbol',
293
+ where: `${entry.item.symbolName} @ (${round(origin[0])}, ${round(origin[1])})`,
294
+ detail: '文字落在元件本体内部,渲染时会压住符号或引脚代号。',
295
+ fix: '把文字挪到元件外侧,或改用元件自带的属性放置。',
296
+ })
297
+ break
298
+ }
299
+ }
300
+ }
301
+
302
+ // 5) 元件偏离栅格(文字和属性放置点不算:它们的坐标本来就带小数)
303
+ if (grid > 0) {
304
+ const offenders = []
305
+ for (const item of placements) {
306
+ if (item?.type !== 'Function' && item?.type !== 'InterruptionPoint') continue
307
+ const origin = pointOf(item.location)
308
+ if (!origin) continue
309
+ const dx = Math.abs(origin[0] / grid - Math.round(origin[0] / grid)) * grid
310
+ const dy = Math.abs(origin[1] / grid - Math.round(origin[1] / grid)) * grid
311
+ if (dx > 0.05 || dy > 0.05) {
312
+ offenders.push(`${item.type}@(${round(origin[0])},${round(origin[1])})`)
313
+ }
314
+ }
315
+ if (offenders.length > 0) {
316
+ problems.push({
317
+ kind: 'off_grid',
318
+ where: offenders.slice(0, 6).join(' '),
319
+ detail: `${offenders.length} 个元件不在 ${grid} mm 栅格上。`,
320
+ fix: '用 page_edit 的 relocate 对齐到栅格,或在 page_create 里传 layout 让坐标自动吸附。',
321
+ })
322
+ }
323
+ }
324
+
325
+ // 6) 超出图框
326
+ if (pageSize && pageSize.length >= 2) {
327
+ const [width, height] = pageSize
328
+ const outside = placements.filter((item) => {
329
+ const origin = pointOf(item.location)
330
+ if (!origin) return false
331
+ return origin[0] < 0 || origin[1] < 0 || origin[0] > width || origin[1] > height
332
+ })
333
+ if (outside.length > 0) {
334
+ problems.push({
335
+ kind: 'out_of_frame',
336
+ where: outside.slice(0, 6).map((item) => `${item.type}(${round(item.location[0])},${round(item.location[1])})`).join(' '),
337
+ detail: `${outside.length} 个对象落在 ${width}×${height} 的图框外,打印时会丢。`,
338
+ fix: '挪回图框内;整页都偏就整页平移。',
339
+ })
340
+ }
341
+ }
342
+
343
+ return problems
344
+ }
345
+
346
+ /** summary:只回答「这页有什么、齐不齐、有没有毛病」,通常 1–3 KB。 */
347
+ function inspectSummary(raw, problems) {
348
+ const { byType, bySymbol, deviceTags, pinTotal, bounds } = censusOf(raw)
349
+ const topSymbols = Object.entries(bySymbol)
350
+ .sort((a, b) => b[1] - a[1])
351
+ .slice(0, 12)
352
+
353
+ return {
354
+ page: raw?.page ?? null,
355
+ pageType: raw?.pageType ?? null,
356
+ totals: {
357
+ placements: Array.isArray(raw?.placements) ? raw.placements.length : 0,
358
+ functions: Number.isFinite(raw?.functionTotal) ? raw.functionTotal : (raw?.functions ?? []).length,
359
+ pins: pinTotal,
360
+ ...byType,
361
+ },
362
+ deviceTags: deviceTags.slice(0, 40),
363
+ deviceTagCount: deviceTags.length,
364
+ topSymbols: Object.fromEntries(topSymbols),
365
+ bounds,
366
+ problems,
367
+ hint:
368
+ '要看每个对象的坐标和引脚用 view="list";要全量原始结构用 view="full"。' +
369
+ (problems.length > 0 ? 'problems 里每一项都有 fix,照它改就行。' : ''),
370
+ }
371
+ }
372
+
373
+ /** list:一行一个对象,坐标保留 2 位小数,比全量小一个数量级。 */
374
+ function inspectList(raw, options) {
375
+ const only = Array.isArray(options.only) && options.only.length > 0 ? new Set(options.only) : null
376
+ const limit = Number.isFinite(options.limit) ? options.limit : 200
377
+ const placements = Array.isArray(raw?.placements) ? raw.placements : []
378
+ const rows = []
379
+ let skipped = 0
380
+
381
+ for (const item of placements) {
382
+ const type = item?.type ?? 'Unknown'
383
+ if (only && !only.has(type)) {
384
+ skipped += 1
385
+ continue
386
+ }
387
+ const origin = pointOf(item.location)
388
+ const row = {
389
+ t: type.slice(0, 4),
390
+ x: origin ? round(origin[0]) : null,
391
+ y: origin ? round(origin[1]) : null,
392
+ }
393
+ if (item.symbolName) row.sym = item.symbolName
394
+ if (Number.isFinite(item.variant) && item.variant !== 0) row.v = item.variant
395
+ if (Array.isArray(item.pins) && item.pins.length > 0) row.pins = item.pins.length
396
+ if (item.objectId !== undefined) row.id = String(item.objectId)
397
+ rows.push(row)
398
+ if (rows.length >= limit) break
399
+ }
400
+
401
+ return {
402
+ page: raw?.page ?? null,
403
+ count: rows.length,
404
+ ...(only ? { filter: [...only] } : {}),
405
+ ...(rows.length < placements.length - skipped ? { truncated: true, total: placements.length } : {}),
406
+ rows,
407
+ }
408
+ }
409
+
410
+ /** full:原始结构,只做「去空噪声 + 紧凑」两件事。 */
411
+ function inspectFull(raw, options) {
412
+ const only = Array.isArray(options.only) && options.only.length > 0 ? new Set(options.only) : null
413
+ const limit = Number.isFinite(options.limit) ? options.limit : null
414
+ const placements = Array.isArray(raw?.placements) ? raw.placements : []
415
+
416
+ const cleaned = []
417
+ for (const item of placements) {
418
+ if (only && !only.has(item?.type)) continue
419
+ const copy = { ...item }
420
+ if (Array.isArray(copy.propertyPlacements)) {
421
+ // text/contents 为空、height 是 EPLAN 的占位值时,整条没有信息量。
422
+ const kept = copy.propertyPlacements.filter((prop) => {
423
+ const text = typeof prop?.text === 'string' ? prop.text.trim() : ''
424
+ const contents = typeof prop?.contents === 'string' ? prop.contents.trim() : ''
425
+ return text.length > 0 || contents.length > 0
426
+ })
427
+ if (kept.length > 0) copy.propertyPlacements = kept
428
+ else delete copy.propertyPlacements
429
+ }
430
+ cleaned.push(copy)
431
+ if (limit !== null && cleaned.length >= limit) break
432
+ }
433
+
434
+ return {
435
+ page: raw?.page ?? null,
436
+ pageType: raw?.pageType ?? null,
437
+ placementTotal: Number.isFinite(raw?.placementTotal) ? raw.placementTotal : placements.length,
438
+ placements: cleaned,
439
+ ...(Array.isArray(raw?.functions) ? { functions: raw.functions } : {}),
440
+ ...(raw?.connections === undefined ? {} : { connections: raw.connections }),
441
+ ...(cleaned.length < placements.length ? { truncated: true, note: `只返回前 ${cleaned.length} 个对象` } : {}),
442
+ }
443
+ }
444
+
445
+ /**
446
+ * page_inspect 的收敛入口。
447
+ * @param {object} raw 桥接器原始 JSON
448
+ * @param {{view?: string, only?: string[], limit?: number}} options
449
+ */
450
+ /**
451
+ * 「看相」:把用户嘴里的「散」「挤」「丑」翻译成可核对的数字。
452
+ *
453
+ * 2026-11-24 session-400917a2:5 条用户消息里有 4 条是审美返工
454
+ * (画丑了 / 线修长一点 / 组聚拢一点 / 呈现错页),第 3、4 轮 9.1 分钟 = 全程 38%
455
+ * 全花在这里。返工的根因不是不会画,是**没人告诉它哪里散**:
456
+ * validate 只答「对不对」,不答「好不好看」。
457
+ *
458
+ * 这一段只做几何实测:把元件按邻近关系分组,量组内包围盒、组间空隙、同列相邻间距,
459
+ * 给出一组数字和一句能照做的改法。**不进 errors/warnings**,因为审美不是硬伤;
460
+ * 它作为 advisory 附在 validate 结果里,用户说「散」的时候有据可依。
461
+ */
462
+ export function appearanceReport(raw, { gapJoin = 24, pageSize = null } = {}) {
463
+ const placements = Array.isArray(raw?.placements) ? raw.placements : []
464
+ const items = []
465
+ for (const item of placements) {
466
+ if (item?.type !== 'Function') continue
467
+ const box = bboxOf(footprintOf(item))
468
+ if (!box) continue
469
+ items.push({ name: item.symbolName ?? '(匿名)', tag: item.name ?? null, box })
470
+ }
471
+ if (items.length === 0) return { groups: 0, items: 0, issues: [] }
472
+
473
+ // 并查集:包围盒之间的边距小于 gapJoin 就并成一组(「相关联的一组」)。
474
+ const parent = items.map((_, index) => index)
475
+ const find = (index) => (parent[index] === index ? index : (parent[index] = find(parent[index])))
476
+ const union = (a, b) => {
477
+ const ra = find(a)
478
+ const rb = find(b)
479
+ if (ra !== rb) parent[rb] = ra
480
+ }
481
+ const gapBetween = (a, b) => {
482
+ const dx = Math.max(0, Math.max(a.minX - b.maxX, b.minX - a.maxX))
483
+ const dy = Math.max(0, Math.max(a.minY - b.maxY, b.minY - a.maxY))
484
+ return Math.hypot(dx, dy)
485
+ }
486
+ for (let i = 0; i < items.length; i += 1) {
487
+ for (let j = i + 1; j < items.length; j += 1) {
488
+ if (gapBetween(items[i].box, items[j].box) <= gapJoin) union(i, j)
489
+ }
490
+ }
491
+
492
+ const buckets = new Map()
493
+ for (let index = 0; index < items.length; index += 1) {
494
+ const root = find(index)
495
+ const bucket = buckets.get(root) ?? []
496
+ bucket.push(items[index])
497
+ buckets.set(root, bucket)
498
+ }
499
+ const groups = [...buckets.values()]
500
+ .map((members, index) => ({
501
+ index: index + 1,
502
+ items: members.length,
503
+ tags: members.map((member) => member.tag).filter(Boolean).slice(0, 8),
504
+ bbox: members.reduce(
505
+ (acc, member) => ({
506
+ minX: Math.min(acc.minX, member.box.minX),
507
+ minY: Math.min(acc.minY, member.box.minY),
508
+ maxX: Math.max(acc.maxX, member.box.maxX),
509
+ maxY: Math.max(acc.maxY, member.box.maxY),
510
+ }),
511
+ { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity },
512
+ ),
513
+ }))
514
+ .sort((a, b) => a.bbox.minX - b.bbox.minX || b.bbox.maxY - a.bbox.maxY)
515
+
516
+ const issues = []
517
+ const gaps = []
518
+ for (let i = 0; i < groups.length; i += 1) {
519
+ for (let j = i + 1; j < groups.length; j += 1) {
520
+ gaps.push(round(gapBetween(groups[i].bbox, groups[j].bbox)))
521
+ }
522
+ }
523
+
524
+ // 「挤」= 两个元件之间还有一点缝、但不够放标签。
525
+ //
526
+ // 边界要写清楚:距离恰好 0(完全贴边或完全重合)不算「挤」——
527
+ // 重合是 duplicate_symbol 的地盘,贴边是同列行距太小(short_wires)的地盘。
528
+ // 2026-11-24 实测:一页 25 个元件的真实页面上,按 gap<4 报出来 4 条全是 gap=0,
529
+ // 和已有的 duplicate_symbol 重复,只会稀释注意力。
530
+ for (let i = 0; i < items.length; i += 1) {
531
+ for (let j = i + 1; j < items.length; j += 1) {
532
+ const gap = gapBetween(items[i].box, items[j].box)
533
+ if (gap <= 0.5 || gap >= 4) continue
534
+ issues.push({
535
+ kind: 'group_crowded',
536
+ where: `${items[i].name} ∩ ${items[j].name}`,
537
+ detail: `两个元件之间只有 ${round(gap)} mm,设备标识和引脚代号会互相压字。`,
538
+ fix: '把其中一个按栅格挪开,至少留出标签宽度(一般 10 mm 以上)。',
539
+ })
540
+ }
541
+ }
542
+
543
+ // 同列的「线」有多长:量相邻元件的**中心间距**,不是量空隙 ——
544
+ // 引脚各占 4 mm,元件贴在一起时空隙是 0,但它照样是「线太短」的那条线。
545
+ const columns = new Map()
546
+ for (const item of items) {
547
+ const key = Math.round(item.box.minX / 4) * 4
548
+ const bucket = columns.get(key) ?? []
549
+ bucket.push(item)
550
+ columns.set(key, bucket)
551
+ }
552
+ const pitches = []
553
+ for (const bucket of columns.values()) {
554
+ if (bucket.length < 2) continue
555
+ const sorted = [...bucket].sort((a, b) => a.box.minY - b.box.minY)
556
+ for (let index = 1; index < sorted.length; index += 1) {
557
+ const pitch = sorted[index].box.minY - sorted[index - 1].box.minY
558
+ if (Number.isFinite(pitch) && pitch > 0) pitches.push(round(pitch))
559
+ }
560
+ }
561
+ pitches.sort((a, b) => a - b)
562
+ const median = (list) => (list.length === 0 ? null : list[Math.floor(list.length / 2)])
563
+ const medianPitch = median(pitches)
564
+ if (medianPitch !== null && medianPitch < 12 && pitches.length >= 3) {
565
+ issues.push({
566
+ kind: 'short_wires',
567
+ where: `${pitches.length} 处竖向相邻`,
568
+ detail: `同列相邻元件的中位中心间距只有 ${medianPitch} mm,连出来的线是短桩,看着挤。`,
569
+ fix: '把这一列整体拉开(行间距各加 8~12 mm),引脚仍然同轴就不会丢红线。',
570
+ })
571
+ }
572
+
573
+ const gapList = [...new Set(gaps)].sort((a, b) => a - b)
574
+ const medianGap = median(gapList)
575
+ if (gapList.length > 0 && medianGap !== null && medianGap > 60) {
576
+ issues.push({
577
+ kind: 'groups_scattered',
578
+ where: `${groups.length} 组之间`,
579
+ detail: `组间空隙中位数 ${medianGap} mm,页面上大片空白——这就是「散」。`,
580
+ fix: '把外围的组往主轴收 20~40 mm,先保证同组内聚,再保证组与组之间留一条等宽的走廊。',
581
+ })
582
+ }
583
+
584
+ // 版面余量只给数字,不判对错:EPLAN 的图纸大多从左上角画起,
585
+ // 右下留白是常态,拿它当问题只会让模型对着一张合格的图改个不停。
586
+ let margins = null
587
+ if (Array.isArray(pageSize) && pageSize.length >= 2) {
588
+ const content = groups.reduce(
589
+ (acc, group) => ({
590
+ minX: Math.min(acc.minX, group.bbox.minX),
591
+ minY: Math.min(acc.minY, group.bbox.minY),
592
+ maxX: Math.max(acc.maxX, group.bbox.maxX),
593
+ maxY: Math.max(acc.maxY, group.bbox.maxY),
594
+ }),
595
+ { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity },
596
+ )
597
+ margins = {
598
+ left: round(content.minX),
599
+ bottom: round(content.minY),
600
+ right: round(Number(pageSize[0]) - content.maxX),
601
+ top: round(Number(pageSize[1]) - content.maxY),
602
+ }
603
+ }
604
+
605
+ return {
606
+ items: items.length,
607
+ groups: groups.length,
608
+ groupList: groups,
609
+ gaps: gapList,
610
+ pitches: { median: medianPitch, count: pitches.length },
611
+ ...(margins ? { margins } : {}),
612
+ issues,
613
+ }
614
+ }
615
+
616
+ export function compactInspect(raw, options = {}) {
617
+ if (raw === null || typeof raw !== 'object') return raw
618
+ const view = options.view ?? 'summary'
619
+ const problems = view === 'full' ? null : geometryProblems(raw, { pageSize: options.pageSize })
620
+ if (view === 'list') return { ...inspectList(raw, options), problems: problems ?? [] }
621
+ if (view === 'full') return inspectFull(raw, options)
622
+ return inspectSummary(raw, problems ?? [])
623
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * page_edit 的参数归一化。
3
+ *
4
+ * 为什么单独成文件:这一段全是「同义词收口」,纯函数,值得单独测。
5
+ *
6
+ * 为什么需要它:2026-11-23 session-a18a4a7f 里,模型为了画一个矩形连撞两次
7
+ * (先 items+type,再 rects + at/to),为了挪一个文字再撞两次(to:[x,y] → at:[x,y]),
8
+ * 5 次调用全花在字段名上,一次也没画成。与其让它在错误信息里猜,不如把常见写法都收下来。
9
+ *
10
+ * 边界:只做同义词映射,不猜意图 —— 看不懂的字段原样留着,交给 schema 校验报错。
11
+ */
12
+
13
+ /** 图元类型:给了 type / 只给 text / 只给 points 也能推出 kind。 */
14
+ function kindOf(item) {
15
+ if (item.kind) return item.kind
16
+ if (item.type) return item.type
17
+ if (item.text !== undefined) return 'text'
18
+ if (Array.isArray(item.points)) return 'polyline'
19
+ if (item.from && item.to) return 'rect'
20
+ return undefined
21
+ }
22
+
23
+ export function normalizeEditArgs(input) {
24
+ const args = { ...input }
25
+
26
+ // draw_graphics:draw / items / rects / graphics 都收;矩形给了 at 没给 from 时把 at 当 from。
27
+ const rawItems = args.draw ?? args.items ?? args.rects ?? args.graphics
28
+ if (Array.isArray(rawItems)) {
29
+ args.draw = rawItems.map((item) => {
30
+ if (!item || typeof item !== 'object') return item
31
+ const next = { ...item }
32
+ const kind = kindOf(next)
33
+ if (kind) next.kind = kind
34
+ if (next.kind === 'rect' && !next.from && Array.isArray(next.at)) {
35
+ next.from = next.at
36
+ delete next.at
37
+ }
38
+ delete next.type
39
+ return next
40
+ })
41
+ }
42
+
43
+ if (args.action === 'relocate') {
44
+ // relocate 的目标坐标常被写成 to / position / pos / xy —— 和 relabel 的 to(新标识)
45
+ // 撞名,所以只在 relocate 且值数组时才当坐标。
46
+ for (const field of ['to', 'position', 'pos', 'xy', 'target']) {
47
+ if (!args.at && Array.isArray(args[field])) {
48
+ args.at = args[field]
49
+ if (field === 'to') delete args.to
50
+ }
51
+ }
52
+ if (!args.at && Array.isArray(args.relocate?.to)) args.at = args.relocate.to
53
+ if (!args.at && Array.isArray(args.relocate?.at)) args.at = args.relocate.at
54
+ if (!args.offset && Array.isArray(args.relocate?.offset)) args.offset = args.relocate.offset
55
+ }
56
+
57
+ if (args.action === 'relabel') {
58
+ // 新标识也可能写成 newTag / newDeviceTag / tag;deviceTag 在 relabel 里是「选谁」,
59
+ // 不能当新名字用。
60
+ if (typeof args.to !== 'string') {
61
+ const candidate = args.newTag ?? args.newDeviceTag ?? args.tag
62
+ if (typeof candidate === 'string') args.to = candidate
63
+ }
64
+ }
65
+
66
+ return args
67
+ }