@kensnzk/koyu 0.5.0 → 0.11.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 (128) hide show
  1. package/README.ja.md +43 -11
  2. package/README.md +51 -11
  3. package/dist/check.d.ts +34 -0
  4. package/dist/check.d.ts.map +1 -0
  5. package/dist/check.js +500 -0
  6. package/dist/check.js.map +1 -0
  7. package/dist/cli.d.ts +3 -0
  8. package/dist/cli.d.ts.map +1 -0
  9. package/dist/cli.js +319 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/diff.d.ts +90 -0
  12. package/dist/diff.d.ts.map +1 -0
  13. package/dist/diff.js +522 -0
  14. package/dist/diff.js.map +1 -0
  15. package/dist/graph.d.ts +81 -0
  16. package/dist/graph.d.ts.map +1 -0
  17. package/dist/graph.js +328 -0
  18. package/dist/graph.js.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +10 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/light.d.ts +15 -0
  24. package/dist/light.d.ts.map +1 -0
  25. package/dist/light.js +55 -0
  26. package/dist/light.js.map +1 -0
  27. package/dist/mcp.d.ts +3 -0
  28. package/dist/mcp.d.ts.map +1 -0
  29. package/dist/mcp.js +354 -0
  30. package/dist/mcp.js.map +1 -0
  31. package/dist/model.d.ts +264 -0
  32. package/dist/model.d.ts.map +1 -0
  33. package/dist/model.js +361 -0
  34. package/dist/model.js.map +1 -0
  35. package/dist/parse-file.d.ts +9 -0
  36. package/dist/parse-file.d.ts.map +1 -0
  37. package/dist/parse-file.js +22 -0
  38. package/dist/parse-file.js.map +1 -0
  39. package/dist/parse.d.ts +16 -0
  40. package/dist/parse.d.ts.map +1 -0
  41. package/dist/parse.js +922 -0
  42. package/dist/parse.js.map +1 -0
  43. package/dist/plan.d.ts +8 -0
  44. package/dist/plan.d.ts.map +1 -0
  45. package/dist/plan.js +267 -0
  46. package/dist/plan.js.map +1 -0
  47. package/dist/site.d.ts +24 -0
  48. package/dist/site.d.ts.map +1 -0
  49. package/dist/site.js +53 -0
  50. package/dist/site.js.map +1 -0
  51. package/examples/comparison/README.md +16 -1
  52. package/examples/comparison/gen-ifc4.ts +1 -1
  53. package/examples/comparison/gen-ifcx.ts +2 -2
  54. package/examples/comparison/two-rooms.ifcx +1 -1
  55. package/examples/house/L1.muro +16 -0
  56. package/examples/house/L2.muro +19 -0
  57. package/examples/house/assets.muro +9 -0
  58. package/examples/house/main.muro +27 -0
  59. package/examples/house/site.muro +31 -0
  60. package/examples/house.muro +1 -1
  61. package/examples/mansion.muro +1 -1
  62. package/examples/office.muro +1 -1
  63. package/examples/steps/01-one-room.muro +4 -0
  64. package/examples/steps/02-two-rooms.muro +5 -0
  65. package/examples/steps/03-door.muro +9 -0
  66. package/examples/steps/04-exterior.muro +15 -0
  67. package/examples/steps/05-two-storeys.muro +27 -0
  68. package/examples/steps/06-finished.muro +30 -0
  69. package/examples/steps/README.md +25 -0
  70. package/examples/tower/L1.muro +80 -0
  71. package/examples/tower/L11.muro +47 -0
  72. package/examples/tower/L2.muro +69 -0
  73. package/examples/tower/L3.muro +28 -0
  74. package/examples/tower/assets.muro +13 -0
  75. package/examples/tower/main.muro +37 -0
  76. package/examples/tower/site-geometry.muro +7 -0
  77. package/examples/tower/site.muro +33 -0
  78. package/examples/tower/typical.muro +124 -0
  79. package/examples/two-rooms.canonical.json +5 -2
  80. package/examples/two-rooms.muro +6 -5
  81. package/package.json +28 -2
  82. package/src/check.ts +352 -63
  83. package/src/cli.ts +76 -11
  84. package/src/diff.ts +608 -0
  85. package/src/graph.ts +90 -10
  86. package/src/index.ts +14 -2
  87. package/src/mcp.ts +390 -0
  88. package/src/model.ts +260 -55
  89. package/src/parse-file.ts +28 -0
  90. package/src/parse.ts +562 -44
  91. package/src/plan.ts +33 -4
  92. package/src/site.ts +13 -5
  93. package/.github/workflows/ci.yml +0 -16
  94. package/.zenodo.json +0 -20
  95. package/CITATION.cff +0 -26
  96. package/docs/decisions/0001-notation-v0.md +0 -29
  97. package/docs/decisions/0002-height-and-offsets.md +0 -27
  98. package/docs/decisions/0003-uncounted-divisions.md +0 -36
  99. package/docs/decisions/0004-typical-floors.md +0 -21
  100. package/docs/decisions/0005-zones-and-unions.md +0 -23
  101. package/docs/decisions/0006-voids-and-light.md +0 -31
  102. package/docs/decisions/0007-semi-outdoor-air.md +0 -27
  103. package/docs/decisions/0008-vocabulary-and-level-attr.md +0 -23
  104. package/docs/decisions/0009-site-and-exterior.md +0 -29
  105. package/docs/ifc-coverage.md +0 -82
  106. package/docs/ifcx-notes.md +0 -25
  107. package/docs/img/house-L1.svg +0 -80
  108. package/docs/img/house-L2.svg +0 -53
  109. package/docs/img/mansion-L1.svg +0 -113
  110. package/docs/img/mansion-L10.svg +0 -111
  111. package/docs/img/mansion-L5.svg +0 -160
  112. package/docs/img/office-L1.svg +0 -116
  113. package/docs/img/office-L2.svg +0 -109
  114. package/docs/img/two-rooms.svg +0 -39
  115. package/docs/log/2026-07-22.md +0 -13
  116. package/docs/log/2026-07-23.md +0 -51
  117. package/docs/roadmap.md +0 -55
  118. package/docs/writing-architecture.md +0 -119
  119. package/spec/notation-v0.md +0 -164
  120. package/spec/vocabulary.md +0 -62
  121. package/test/core.test.ts +0 -171
  122. package/test/design2.test.ts +0 -97
  123. package/test/house.test.ts +0 -74
  124. package/test/mansion.test.ts +0 -99
  125. package/test/office.test.ts +0 -71
  126. package/test/uncounted.test.ts +0 -120
  127. package/test/vertical.test.ts +0 -75
  128. package/tsconfig.json +0 -13
package/src/graph.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // 空間の領域は矩形の合併 (L字など)。壁は合併の外周と共有辺から導出される。
5
5
 
6
6
  import type { Boundary, Edge, Model, Opening, Rect, Space } from "./model.js";
7
+ import { srcRef } from "./model.js";
7
8
 
8
9
  /** 壁芯線分 (mm)。水平なら y1===y2、垂直なら x1===x2 */
9
10
  export interface Segment {
@@ -107,6 +108,40 @@ export function mergeCollinear(segs: Segment[]): Segment[] {
107
108
  return out;
108
109
  }
109
110
 
111
+ /**
112
+ * 既定境界の導出 (ADR-0014) — 垂直の「既定は床」と対称の、水平の「既定は壁」。
113
+ * 同一レベル (未特定同士を含む) で平面が接する領域つき空間の組に、宣言境界がその組に
114
+ * 一つも無ければ kind:wall の既定境界を導く。宣言は例外 (open・手すり) と属性のためにある。
115
+ * 領域を持たない空間 (exterior等) との境界は導かない — 相手の名指しが情報のため宣言する。
116
+ * 合成・スパン展開の完了後に呼ぶ (parse / parseWith の出口)。冪等。
117
+ */
118
+ export function deriveDefaultBoundaries(model: Model): void {
119
+ const declared = new Set<string>();
120
+ for (const b of model.boundaries) declared.add([b.a, b.b].sort().join("|"));
121
+ const withRect = [...model.spaces.values()].filter((s) => s.rects.length > 0);
122
+ for (let i = 0; i < withRect.length; i++) {
123
+ for (let j = i + 1; j < withRect.length; j++) {
124
+ const a = withRect[i]!;
125
+ const b = withRect[j]!;
126
+ if (a.level !== b.level) continue;
127
+ const key = [a.path, b.path].sort().join("|");
128
+ if (declared.has(key)) continue;
129
+ if (!a.rects.some((ra) => b.rects.some((rb) => sharedSegment(ra, rb)))) continue;
130
+ model.boundaries.push({
131
+ a: a.path,
132
+ b: b.path,
133
+ kind: "wall",
134
+ derived: true,
135
+ attrs: {},
136
+ openings: [],
137
+ segs: [],
138
+ line: 0,
139
+ });
140
+ declared.add(key);
141
+ }
142
+ }
143
+ }
144
+
110
145
  /** 境界の壁芯線分を導く。壁の位置は空間の割付から生成される — 壁を置く操作は存在しない */
111
146
  export function segmentsFor(model: Model, b: Boundary): Segment[] {
112
147
  const sa = model.spaces.get(b.a);
@@ -179,6 +214,10 @@ export function spacesOverlap(a: Space, b: Space): boolean {
179
214
  export interface Band {
180
215
  w: number;
181
216
  at: number;
217
+ /** 明示位置 (通り参照 at:X2+450 の解決値)。指定時はクランプせず、はみ出しをエラーにする */
218
+ atRef?: string;
219
+ atAbs?: number;
220
+ atAxis?: "X" | "Y";
182
221
  edge?: Edge;
183
222
  line: number;
184
223
  }
@@ -190,32 +229,73 @@ export interface PlacedBand {
190
229
  cy: number;
191
230
  }
192
231
 
232
+ /** 帯の配置失敗 — error は互換の完成文 (位置接頭辞つき)。code/line/message は診断契約 (ADR-0016) の材料 */
233
+ export interface BandError {
234
+ error: string;
235
+ /** 診断コード — 開口は OPN04〜08、seg は SEG04〜08 (呼び手のlabelで決まる) */
236
+ code: string;
237
+ line: number;
238
+ file?: string;
239
+ /** 位置接頭辞を除いた本文 */
240
+ message: string;
241
+ }
242
+
193
243
  /** 帯 (開口・seg) を境界線分上に配置する。曖昧なら error を返す */
194
244
  export function placeBand(
195
245
  model: Model,
196
246
  b: Boundary,
197
247
  band: Band,
198
248
  label: string,
199
- ): PlacedBand | { error: string } {
249
+ ): PlacedBand | BandError {
250
+ // 配置失敗の診断: label が "seg" なら SEG系、開口 (door/window等) なら OPN系のコード
251
+ const fail = (n: string, message: string): BandError => ({
252
+ error: `${srcRef(band.line, b.file)}: ${message}`,
253
+ code: `${label === "seg" ? "SEG" : "OPN"}${n}`,
254
+ line: band.line,
255
+ ...(b.file !== undefined ? { file: b.file } : {}),
256
+ message,
257
+ });
200
258
  let segs = segmentsFor(model, b);
201
259
  if (band.edge) segs = segs.filter((s) => s.edgeOfA === band.edge);
202
260
  if (segs.length === 0) {
203
- return { error: `${band.line}行目: ${label} を置ける境界線分がありません (${b.a} | ${b.b})` };
261
+ return fail("04", `${label} を置ける境界線分がありません (${b.a} | ${b.b})`);
204
262
  }
205
263
  if (segs.length > 1) {
206
- return {
207
- error: `${band.line}行目: 境界線分が複数あります。edge:N/E/S/W で辺を指定してください (${b.a} | ${b.b})`,
208
- };
264
+ return fail("05", `境界線分が複数あります。edge:N/E/S/W で辺を指定してください (${b.a} | ${b.b})`);
209
265
  }
210
266
  const seg = segs[0]!;
211
267
  const len = segmentLength(seg);
212
268
  if (band.w > len) {
213
- return {
214
- error: `${band.line}行目: ${label}の幅 ${band.w} が境界線分の長さ ${len} を超えています`,
215
- };
269
+ return fail("06", `${label}の幅 ${band.w} が境界線分の長さ ${len} を超えています`);
216
270
  }
217
271
  const half = band.w / 2;
218
- const pos = Math.min(Math.max(band.at * len, half), len - half);
272
+ let pos: number;
273
+ if (band.atAbs !== undefined) {
274
+ // 明示位置: 通り参照で置かれたものはクランプしない — はみ出しは言葉のエラーになる
275
+ const axisOk = seg.horizontal ? band.atAxis === "X" : band.atAxis === "Y";
276
+ if (!axisOk) {
277
+ return fail(
278
+ "07",
279
+ `${label} の位置 ${band.atRef} は${
280
+ seg.horizontal ? "水平線分なのでX系" : "垂直線分なのでY系"
281
+ }の通りで指定します`,
282
+ );
283
+ }
284
+ const start = seg.horizontal ? seg.x1 : seg.y1;
285
+ pos = band.atAbs - start;
286
+ if (pos < half - EPS || pos > len - half + EPS) {
287
+ return fail(
288
+ "08",
289
+ `位置 ${band.atRef} では ${label} (幅${band.w}) が境界線分からはみ出します (線分 ${Math.round(
290
+ start,
291
+ )}〜${Math.round(start + len)}mm、中心の許容 ${Math.round(start + half)}〜${Math.round(
292
+ start + len - half,
293
+ )}mm)`,
294
+ );
295
+ }
296
+ } else {
297
+ pos = Math.min(Math.max(band.at * len, half), len - half);
298
+ }
219
299
  return {
220
300
  segment: seg,
221
301
  cx: seg.horizontal ? seg.x1 + pos : seg.x1,
@@ -224,7 +304,7 @@ export function placeBand(
224
304
  }
225
305
 
226
306
  /** 開口を境界線分上に配置する */
227
- export function placeOpening(model: Model, b: Boundary, o: Opening): PlacedBand | { error: string } {
307
+ export function placeOpening(model: Model, b: Boundary, o: Opening): PlacedBand | BandError {
228
308
  return placeBand(model, b, o, o.kind);
229
309
  }
230
310
 
package/src/index.ts CHANGED
@@ -1,8 +1,20 @@
1
1
  // koyu v0 — 公開API
2
2
  export * from "./model.js";
3
- export { parse, tokenize } from "./parse.js";
3
+ export { parse, parseFiles, parseWith, tokenize, type LayerLoader } from "./parse.js";
4
4
  export * from "./graph.js";
5
- export { check, type CheckResult } from "./check.js";
5
+ export { check, checkDiagnostics, DIAGNOSTIC_CODES, type CheckResult, type Diagnostic } from "./check.js";
6
+ export {
7
+ semanticDiff,
8
+ renderDiff,
9
+ type ModelDiff,
10
+ type FieldChange,
11
+ type ChangedItem,
12
+ type RenamedItem,
13
+ type GridChange,
14
+ type SpaceItem,
15
+ type BoundaryItem,
16
+ type BoundaryChange,
17
+ } from "./diff.js";
6
18
  export { daylight, type DaylightResult } from "./light.js";
7
19
  export { siteReport, type SiteReport, type RoadFrontage } from "./site.js";
8
20
  export { svgPlan, type PlanOptions } from "./plan.js";
package/src/mcp.ts ADDED
@@ -0,0 +1,390 @@
1
+ #!/usr/bin/env node
2
+ // koyu MCPサーバー — 建物をLLMエージェントの作業対象にする (ADR-0012 / docs/horizon.md 軸1)。
3
+ // stdio上の手書きJSON-RPC 2.0。依存ゼロの方針をここでも守る (SDKは使わない)。
4
+ // ステートレス: 毎回 parseFile で合成する (towerでも数ms)。書き込みは .muro に限定し、履歴はgitが持つ。
5
+ //
6
+ // 使い方: koyu-mcp (カレントディレクトリ基準の相対パスでファイルを指定)
7
+ // エージェントのループ: layers で読む → write_layer で書く → check が門番 → doors/stats/light/site で帰結を確かめる
8
+
9
+ import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
10
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
11
+ import {
12
+ areaM2,
13
+ daylight,
14
+ displayName,
15
+ doorsBetween,
16
+ effectiveUse,
17
+ isSemiOutdoor,
18
+ levelsSorted,
19
+ toCanonical,
20
+ zoneAreaM2,
21
+ type Model,
22
+ type Space,
23
+ } from "./index.js";
24
+ import { check, checkDiagnostics } from "./check.js";
25
+ import { svgPlan } from "./plan.js";
26
+ import { siteReport } from "./site.js";
27
+ import { parseFile, parseFileWith } from "./parse-file.js";
28
+
29
+ // ---- モデルの読み込みと要約 ----
30
+
31
+ function load(file: string): Model {
32
+ return parseFile(resolve(file));
33
+ }
34
+
35
+ /** 合成に参加した全レイヤー — 要素の有無によらずModelが記録する (grid/levelだけの層も落ちない) */
36
+ function layerFiles(model: Model, entry: string): string[] {
37
+ return [...new Set([resolve(entry), ...model.layers])].sort();
38
+ }
39
+
40
+ /** entryディレクトリ境界の検査 — 文字列prefixではなく相対パスで判定する (ADR-0013) */
41
+ function assertInside(entryDir: string, targetDir: string): void {
42
+ const rel = relative(entryDir, targetDir);
43
+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
44
+ throw new Error("entryのディレクトリの外へは書き込めません");
45
+ }
46
+ }
47
+
48
+ function summarize(model: Model, file: string): unknown {
49
+ const rooms = [...model.spaces.values()].filter((s) => s.rects.length > 0 && s.level);
50
+ const indoor = rooms.filter(
51
+ (s) => s.type !== "void" && s.type !== "exterior" && !isSemiOutdoor(model, s),
52
+ );
53
+ const semi = rooms.filter((s) => s.type !== "void" && isSemiOutdoor(model, s));
54
+ const byLevel: Record<string, { rooms: number; subtotalM2: number }> = {};
55
+ for (const lv of levelsSorted(model)) {
56
+ const rs = indoor.filter((s) => s.level === lv.name);
57
+ if (rs.length === 0) continue;
58
+ byLevel[lv.name] = {
59
+ rooms: rs.length,
60
+ subtotalM2: Math.round(rs.reduce((a, s) => a + (areaM2(s) ?? 0), 0) * 100) / 100,
61
+ };
62
+ }
63
+ const byUse: Record<string, number> = {};
64
+ for (const s of indoor) {
65
+ const u = effectiveUse(model, s) ?? "(未指定)";
66
+ byUse[u] = Math.round(((byUse[u] ?? 0) + (areaM2(s) ?? 0)) * 100) / 100;
67
+ }
68
+ const r = check(model);
69
+ return {
70
+ name: model.name,
71
+ unit: model.unit,
72
+ layers: layerFiles(model, file),
73
+ levels: levelsSorted(model).map((l) => ({
74
+ name: l.name,
75
+ z: l.z,
76
+ ...(l.h !== undefined ? { h: l.h } : {}),
77
+ ...(l.slab !== undefined ? { slab: l.slab } : {}),
78
+ })),
79
+ spaces: model.spaces.size,
80
+ boundaries: model.boundaries.length,
81
+ zones: [...model.zones.values()].map((z) => ({
82
+ path: z.path,
83
+ ...(typeof z.attrs["name"] === "string" ? { name: z.attrs["name"] } : {}),
84
+ areaM2: zoneAreaM2(model, z.path),
85
+ })),
86
+ assets: [...model.assets.values()].map((a) => ({ name: a.name, kind: a.kind, attrs: a.attrs })),
87
+ ...(model.polygons.size
88
+ ? { sitePolygons: [...model.polygons.keys()] }
89
+ : {}),
90
+ totalFloorM2: Math.round(indoor.reduce((a, s) => a + (areaM2(s) ?? 0), 0) * 100) / 100,
91
+ semiOutdoorM2: Math.round(semi.reduce((a, s) => a + (areaM2(s) ?? 0), 0) * 100) / 100,
92
+ floorsM2: byLevel,
93
+ byUseM2: byUse,
94
+ check: { errors: r.errors.length, warnings: r.warnings.length },
95
+ hint: "レイヤーの中身は layers で、検査は check で、変更は write_layer で (checkが門番)。",
96
+ };
97
+ }
98
+
99
+ function spaceInfo(model: Model, s: Space): unknown {
100
+ return {
101
+ path: s.path,
102
+ type: s.type,
103
+ name: displayName(s),
104
+ level: s.level,
105
+ areaM2: areaM2(s),
106
+ semiOutdoor: isSemiOutdoor(model, s),
107
+ ...(s.file ? { layer: s.file } : {}),
108
+ };
109
+ }
110
+
111
+ // ---- ツール定義 ----
112
+
113
+ interface Tool {
114
+ description: string;
115
+ schema: Record<string, unknown>;
116
+ run(args: Record<string, unknown>): unknown;
117
+ }
118
+
119
+ const FILE_PROP = {
120
+ file: { type: "string", description: "entryの.muroファイルパス (importは自動で合成される)" },
121
+ };
122
+ const str = (v: unknown, name: string): string => {
123
+ if (typeof v !== "string" || !v) throw new Error(`${name} (文字列) が必要です`);
124
+ return v;
125
+ };
126
+
127
+ const TOOLS: Record<string, Tool> = {
128
+ model_summary: {
129
+ description:
130
+ "建物の要約 (名前・レベル・レイヤー構成・ゾーン・建具アセット・面積・check結果)。まずこれを呼ぶ",
131
+ schema: { type: "object", properties: FILE_PROP, required: ["file"] },
132
+ run: (a) => {
133
+ const file = str(a.file, "file");
134
+ return summarize(load(file), file);
135
+ },
136
+ },
137
+ check: {
138
+ description:
139
+ "一棟のビルドの門番: 合成して整合を検査する。エラー・警告は出所レイヤー:行つき。編集のたびに呼ぶこと",
140
+ schema: { type: "object", properties: FILE_PROP, required: ["file"] },
141
+ run: (a) => {
142
+ const m = load(str(a.file, "file"));
143
+ const r = check(m);
144
+ return {
145
+ ok: r.errors.length === 0,
146
+ spaces: m.spaces.size,
147
+ boundaries: m.boundaries.length,
148
+ ...r,
149
+ // 構造化診断 (ADR-0016) — errors/warningsの文字列と同件・同順。code/severity/path/relatedつき
150
+ diagnostics: checkDiagnostics(m),
151
+ };
152
+ },
153
+ },
154
+ layers: {
155
+ description: "合成に参加している全レイヤー (.muroファイル) の名前と中身を返す — 原本を読む",
156
+ schema: { type: "object", properties: FILE_PROP, required: ["file"] },
157
+ run: (a) => {
158
+ const file = str(a.file, "file");
159
+ const m = load(file);
160
+ return layerFiles(m, file).map((f) => ({ file: f, source: readFileSync(f, "utf8") }));
161
+ },
162
+ },
163
+ write_layer: {
164
+ description:
165
+ "レイヤー (.muroファイル) を検査してから書き換える。parse不能な合成になる内容は書き込まれない (原本不変)。" +
166
+ "checkのエラーは返すが書き込みは行う (複数レイヤーにまたがる編集の途中を許す) — 直して再度書くこと。履歴はgitに任せる",
167
+ schema: {
168
+ type: "object",
169
+ properties: {
170
+ ...FILE_PROP,
171
+ layer: { type: "string", description: "書き込む.muroファイルパス (entryからの相対または絶対)" },
172
+ content: { type: "string", description: "レイヤーの全文 (全置換)" },
173
+ },
174
+ required: ["file", "layer", "content"],
175
+ },
176
+ run: (a) => {
177
+ const file = str(a.file, "file");
178
+ const content = str(a.content, "content");
179
+ const entryDir = resolve(dirname(resolve(file)));
180
+ const target = resolve(entryDir, str(a.layer, "layer"));
181
+ if (!target.endsWith(".muro")) throw new Error("書き込みは .muro ファイルに限ります");
182
+ assertInside(entryDir, dirname(target));
183
+ // 門番は書き込みの前 — 差し替え内容で仮想合成し、parse不能なら原本に触れない (ADR-0013)。
184
+ // 合成に参加しないファイルの内容は検証されない (importされた時のcheckが捕まえる)
185
+ let m: Model;
186
+ try {
187
+ m = parseFileWith(resolve(file), (p) => (p === target ? content : undefined));
188
+ } catch (e) {
189
+ return {
190
+ written: false,
191
+ target,
192
+ ok: false,
193
+ parseError: e instanceof Error ? e.message : String(e),
194
+ };
195
+ }
196
+ const r = check(m);
197
+ mkdirSync(dirname(target), { recursive: true });
198
+ assertInside(realpathSync(entryDir), realpathSync(dirname(target))); // symlink経由の脱出も塞ぐ
199
+ const tmp = `${target}.tmp-${process.pid}`;
200
+ writeFileSync(tmp, content);
201
+ renameSync(tmp, target); // 同一ディレクトリ内のrename — 中途半端なファイルを残さない
202
+ return { written: target, ok: r.errors.length === 0, spaces: m.spaces.size, ...r };
203
+ },
204
+ },
205
+ doors: {
206
+ description: "避難・動線の問い: 空間Aから空間Bまで扉を何枚通るか (最少扉数の経路)",
207
+ schema: {
208
+ type: "object",
209
+ properties: {
210
+ ...FILE_PROP,
211
+ from: { type: "string", description: "起点の空間パス (例 /L9/A/ldk)" },
212
+ to: { type: "string", description: "終点の空間パス (例 /out/road-s)" },
213
+ },
214
+ required: ["file", "from", "to"],
215
+ },
216
+ run: (a) => {
217
+ const route = doorsBetween(load(str(a.file, "file")), str(a.from, "from"), str(a.to, "to"));
218
+ return route ?? { unreachable: true };
219
+ },
220
+ },
221
+ spaces: {
222
+ description: "空間の一覧 (パス・型・レベル・面積・半屋外・出所レイヤー)。levelで絞り込み可",
223
+ schema: {
224
+ type: "object",
225
+ properties: { ...FILE_PROP, level: { type: "string", description: "レベル名で絞る (省略可)" } },
226
+ required: ["file"],
227
+ },
228
+ run: (a) => {
229
+ const m = load(str(a.file, "file"));
230
+ return [...m.spaces.values()]
231
+ .filter((s) => !a.level || s.level === a.level)
232
+ .map((s) => spaceInfo(m, s));
233
+ },
234
+ },
235
+ light: {
236
+ description: "採光の検査: 住居系の居室で窓面積/床面積 ≥ 1/7 (バルコニー・庇下は0.7掛け)",
237
+ schema: { type: "object", properties: FILE_PROP, required: ["file"] },
238
+ run: (a) => {
239
+ const m = load(str(a.file, "file"));
240
+ return daylight(m).map((r) => ({
241
+ path: r.space.path,
242
+ name: displayName(r.space),
243
+ ok: r.ok,
244
+ windowM2: r.window,
245
+ floorM2: r.floor,
246
+ needM2: r.need,
247
+ }));
248
+ },
249
+ },
250
+ site: {
251
+ description: "敷地の問い: 敷地面積 (宣言/導出の照合)・接道・建築面積・建蔽率・容積率",
252
+ schema: { type: "object", properties: FILE_PROP, required: ["file"] },
253
+ run: (a) => {
254
+ const r = siteReport(load(str(a.file, "file")));
255
+ const site = r.declaredArea ?? r.derivedArea;
256
+ return {
257
+ ...(r.siteZone ? { siteZone: r.siteZone.path } : {}),
258
+ ...(r.polygon ? { polygonVertices: r.polygon.points.length } : {}),
259
+ declaredAreaM2: r.declaredArea,
260
+ derivedAreaM2: r.derivedArea,
261
+ ...(r.declaredArea !== undefined && r.derivedArea !== undefined
262
+ ? { areaMatch: Math.abs(r.declaredArea - r.derivedArea) < 0.05 }
263
+ : {}),
264
+ footprintM2: r.footprint,
265
+ totalFloorM2: r.totalFloor,
266
+ coverageRatio: site ? Math.round((r.footprint / site) * 1000) / 10 : undefined,
267
+ floorAreaRatio: site ? Math.round((r.totalFloor / site) * 1000) / 10 : undefined,
268
+ roads: r.roads.map((rd) => ({
269
+ path: rd.road.path,
270
+ name: displayName(rd.road),
271
+ widthMm: rd.width,
272
+ frontageMm: rd.frontage,
273
+ })),
274
+ };
275
+ },
276
+ },
277
+ plan_svg: {
278
+ description: "指定レベルの平面図SVGを生成して返す (形は生成物 — 最下階は配置図兼用)",
279
+ schema: {
280
+ type: "object",
281
+ properties: { ...FILE_PROP, level: { type: "string", description: "レベル名 (例 L5)" } },
282
+ required: ["file", "level"],
283
+ },
284
+ run: (a) => svgPlan(load(str(a.file, "file")), { level: str(a.level, "level") }),
285
+ },
286
+ canonical_json: {
287
+ description: "正準JSON (機械形式 — 合成後の単一モデル、バイト安定)。diff・外部接続の土台",
288
+ schema: { type: "object", properties: FILE_PROP, required: ["file"] },
289
+ run: (a) => JSON.parse(toCanonical(load(str(a.file, "file")))),
290
+ },
291
+ };
292
+
293
+ // ---- JSON-RPC 2.0 over stdio (行区切りJSON) ----
294
+
295
+ type Json = Record<string, unknown>;
296
+
297
+ function send(msg: Json): void {
298
+ process.stdout.write(JSON.stringify(msg) + "\n");
299
+ }
300
+
301
+ function result(id: unknown, res: unknown): void {
302
+ send({ jsonrpc: "2.0", id, result: res } as Json);
303
+ }
304
+
305
+ function rpcError(id: unknown, code: number, message: string): void {
306
+ send({ jsonrpc: "2.0", id, error: { code, message } } as Json);
307
+ }
308
+
309
+ function handle(msg: Json): void {
310
+ const id = msg.id;
311
+ const method = msg.method as string | undefined;
312
+ if (method === undefined) return; // 応答は来ない想定
313
+ const params = (msg.params ?? {}) as Json;
314
+
315
+ // 通知 (idなし) は応答しない
316
+ if (id === undefined) return;
317
+
318
+ switch (method) {
319
+ case "initialize": {
320
+ result(id, {
321
+ protocolVersion: (params.protocolVersion as string) ?? "2025-06-18",
322
+ capabilities: { tools: {} },
323
+ serverInfo: { name: "koyu", version: "0.11.0" },
324
+ instructions:
325
+ "空間一次の建築記述koyuのサーバー。model_summaryで建物を掴み、layersで原本 (.muroレイヤー群) を読み、" +
326
+ "write_layerで編集する。checkが一棟のビルドの門番 — エラーは出所レイヤー:行つきで返る。" +
327
+ "doors/light/site/spacesは同じ記述への異なる問い。形 (plan_svg) は生成物。",
328
+ });
329
+ return;
330
+ }
331
+ case "ping":
332
+ result(id, {});
333
+ return;
334
+ case "tools/list": {
335
+ result(id, {
336
+ tools: Object.entries(TOOLS).map(([name, t]) => ({
337
+ name,
338
+ description: t.description,
339
+ inputSchema: t.schema,
340
+ })),
341
+ });
342
+ return;
343
+ }
344
+ case "tools/call": {
345
+ const name = params.name as string;
346
+ const tool = TOOLS[name];
347
+ if (!tool) {
348
+ rpcError(id, -32602, `未知のツールです: ${name}`);
349
+ return;
350
+ }
351
+ try {
352
+ const out = tool.run((params.arguments ?? {}) as Json);
353
+ const text = typeof out === "string" ? out : JSON.stringify(out, null, 1);
354
+ result(id, { content: [{ type: "text", text }] });
355
+ } catch (e) {
356
+ result(id, {
357
+ content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }],
358
+ isError: true,
359
+ });
360
+ }
361
+ return;
362
+ }
363
+ case "resources/list":
364
+ result(id, { resources: [] });
365
+ return;
366
+ case "prompts/list":
367
+ result(id, { prompts: [] });
368
+ return;
369
+ default:
370
+ rpcError(id, -32601, `未対応のメソッドです: ${method}`);
371
+ }
372
+ }
373
+
374
+ let buf = "";
375
+ process.stdin.setEncoding("utf8");
376
+ process.stdin.on("data", (chunk: string) => {
377
+ buf += chunk;
378
+ let nl: number;
379
+ while ((nl = buf.indexOf("\n")) >= 0) {
380
+ const line = buf.slice(0, nl).trim();
381
+ buf = buf.slice(nl + 1);
382
+ if (!line) continue;
383
+ try {
384
+ handle(JSON.parse(line) as Json);
385
+ } catch {
386
+ // 壊れた行は黙って捨てる (stdioの流儀)
387
+ }
388
+ }
389
+ });
390
+ process.stdin.on("end", () => process.exit(0));