@kensnzk/koyu 0.16.0 → 0.17.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 (148) hide show
  1. package/README.ja.md +12 -8
  2. package/README.md +13 -10
  3. package/dist/cli.js +14 -11
  4. package/dist/cli.js.map +1 -1
  5. package/dist/core/derive.d.ts +13 -8
  6. package/dist/core/derive.d.ts.map +1 -1
  7. package/dist/core/derive.js +19 -13
  8. package/dist/core/derive.js.map +1 -1
  9. package/dist/core/diagnose.d.ts +4 -3
  10. package/dist/core/diagnose.d.ts.map +1 -1
  11. package/dist/core/diagnose.js +46 -11
  12. package/dist/core/diagnose.js.map +1 -1
  13. package/dist/core/diff.d.ts +3 -2
  14. package/dist/core/diff.d.ts.map +1 -1
  15. package/dist/core/diff.js +8 -5
  16. package/dist/core/diff.js.map +1 -1
  17. package/dist/core/fabric.d.ts +1 -3
  18. package/dist/core/fabric.d.ts.map +1 -1
  19. package/dist/core/fabric.js +8 -8
  20. package/dist/core/fabric.js.map +1 -1
  21. package/dist/core/graph.d.ts +2 -2
  22. package/dist/core/graph.d.ts.map +1 -1
  23. package/dist/core/graph.js +12 -5
  24. package/dist/core/graph.js.map +1 -1
  25. package/dist/core/light.d.ts.map +1 -1
  26. package/dist/core/light.js +2 -2
  27. package/dist/core/light.js.map +1 -1
  28. package/dist/core/model.d.ts +59 -10
  29. package/dist/core/model.d.ts.map +1 -1
  30. package/dist/core/model.js +128 -26
  31. package/dist/core/model.js.map +1 -1
  32. package/dist/core/parse.d.ts.map +1 -1
  33. package/dist/core/parse.js +83 -82
  34. package/dist/core/parse.js.map +1 -1
  35. package/dist/core/poly.d.ts +0 -4
  36. package/dist/core/poly.d.ts.map +1 -1
  37. package/dist/core/poly.js +1 -5
  38. package/dist/core/poly.js.map +1 -1
  39. package/dist/core/site.d.ts.map +1 -1
  40. package/dist/core/site.js +2 -2
  41. package/dist/core/site.js.map +1 -1
  42. package/dist/core/tolerance.d.ts +1 -1
  43. package/dist/core/tolerance.js +2 -2
  44. package/dist/core/tolerance.js.map +1 -1
  45. package/dist/core/vertical.d.ts +9 -2
  46. package/dist/core/vertical.d.ts.map +1 -1
  47. package/dist/core/vertical.js +8 -1
  48. package/dist/core/vertical.js.map +1 -1
  49. package/dist/core/vocabulary.d.ts.map +1 -1
  50. package/dist/core/vocabulary.js +17 -5
  51. package/dist/core/vocabulary.js.map +1 -1
  52. package/dist/draw/index.js +1 -1
  53. package/dist/draw/index.js.map +1 -1
  54. package/dist/draw/plan.js +5 -5
  55. package/dist/draw/plan.js.map +1 -1
  56. package/dist/index.d.ts +3 -2
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +17 -11
  59. package/dist/index.js.map +1 -1
  60. package/dist/mcp.js +43 -12
  61. package/dist/mcp.js.map +1 -1
  62. package/dist/parse-file.d.ts.map +1 -1
  63. package/dist/parse-file.js +18 -3
  64. package/dist/parse-file.js.map +1 -1
  65. package/dist/validate/access.d.ts.map +1 -1
  66. package/dist/validate/access.js +23 -13
  67. package/dist/validate/access.js.map +1 -1
  68. package/dist/validate/envelope.d.ts.map +1 -1
  69. package/dist/validate/envelope.js +3 -3
  70. package/dist/validate/envelope.js.map +1 -1
  71. package/dist/validate/index.d.ts +1 -1
  72. package/dist/validate/index.d.ts.map +1 -1
  73. package/dist/validate/index.js +1 -1
  74. package/dist/validate/index.js.map +1 -1
  75. package/dist/validate/light.js +1 -1
  76. package/dist/validate/light.js.map +1 -1
  77. package/dist/validate/site.d.ts.map +1 -1
  78. package/dist/validate/site.js +2 -2
  79. package/dist/validate/site.js.map +1 -1
  80. package/editors/vscode/syntaxes/koyu.tmLanguage.json +2 -2
  81. package/examples/basement/main.muro +3 -3
  82. package/examples/complex/main.muro +1 -1
  83. package/examples/complex/podium.muro +1 -1
  84. package/examples/complex/site.muro +6 -6
  85. package/examples/house/L2.muro +1 -1
  86. package/examples/house/main.muro +1 -1
  87. package/examples/house/site.muro +4 -4
  88. package/examples/house.muro +6 -6
  89. package/examples/mansion.muro +2 -2
  90. package/examples/office.muro +3 -3
  91. package/examples/steps/04-exterior.muro +1 -1
  92. package/examples/steps/05-two-storeys.muro +1 -1
  93. package/examples/steps/06-finished.muro +2 -2
  94. package/examples/tower/L2.muro +1 -1
  95. package/examples/tower/main.muro +1 -1
  96. package/examples/tower/site.muro +4 -4
  97. package/examples/twin/main.muro +1 -1
  98. package/examples/twin/podium.muro +4 -4
  99. package/examples/twin/site.muro +8 -8
  100. package/examples/two-rooms.canonical.json +4 -4
  101. package/examples/two-rooms.muro +2 -2
  102. package/package.json +5 -5
  103. package/src/cli.ts +15 -10
  104. package/src/core/derive.ts +32 -15
  105. package/src/core/diagnose.ts +63 -16
  106. package/src/core/diff.ts +10 -6
  107. package/src/core/fabric.ts +18 -9
  108. package/src/core/graph.ts +19 -5
  109. package/src/core/light.ts +2 -2
  110. package/src/core/model.ts +141 -31
  111. package/src/core/parse.ts +100 -85
  112. package/src/core/poly.ts +1 -8
  113. package/src/core/site.ts +2 -2
  114. package/src/core/tolerance.ts +2 -2
  115. package/src/core/vertical.ts +10 -3
  116. package/src/core/vocabulary.ts +18 -5
  117. package/src/draw/index.ts +1 -1
  118. package/src/draw/plan.ts +5 -5
  119. package/src/index.ts +30 -9
  120. package/src/mcp.ts +44 -11
  121. package/src/parse-file.ts +17 -3
  122. package/src/validate/access.ts +24 -12
  123. package/src/validate/envelope.ts +3 -3
  124. package/src/validate/index.ts +2 -2
  125. package/src/validate/light.ts +1 -1
  126. package/src/validate/site.ts +2 -2
  127. package/spec/README.md +0 -28
  128. package/spec/canonical-json.md +0 -98
  129. package/spec/composition.md +0 -121
  130. package/spec/derivation.md +0 -393
  131. package/spec/en/README.md +0 -30
  132. package/spec/en/canonical-json.md +0 -101
  133. package/spec/en/composition.md +0 -121
  134. package/spec/en/derivation.md +0 -393
  135. package/spec/en/language.md +0 -164
  136. package/spec/en/notation-v0.md +0 -145
  137. package/spec/en/scope.md +0 -229
  138. package/spec/en/semantics.md +0 -132
  139. package/spec/en/tools.md +0 -108
  140. package/spec/en/validation.md +0 -79
  141. package/spec/en/vocabulary.md +0 -103
  142. package/spec/language.md +0 -163
  143. package/spec/notation-v0.md +0 -184
  144. package/spec/scope.md +0 -229
  145. package/spec/semantics.md +0 -130
  146. package/spec/tools.md +0 -106
  147. package/spec/validation.md +0 -79
  148. package/spec/vocabulary.md +0 -114
package/src/core/model.ts CHANGED
@@ -11,9 +11,9 @@ export type Attrs = Record<string, AttrValue>;
11
11
  * このツールが受理する言語版 (ADR-0017)。旧版は意味保存の場合のみ受理される (checkが検査する)。
12
12
  * **この並びが版の新旧の順である** — 版の比較はここの添字で行う (辞書順では 0.5 が 1.0 より後になる)
13
13
  */
14
- export const SUPPORTED_LANGUAGE_VERSIONS: readonly string[] = ["0.1", "0.2", "0.3", "0.4", "0.5", "1.0"];
14
+ export const SUPPORTED_LANGUAGE_VERSIONS: readonly string[] = ["0.1", "0.2", "0.3", "0.4", "0.5", "1.0", "1.1"];
15
15
  /** 版宣言を省略したときの解釈 — 常に最新版の意味論 (省略はツール版を跨いで意味安定ではない) */
16
- export const DEFAULT_LANGUAGE_VERSION = "1.0";
16
+ export const DEFAULT_LANGUAGE_VERSION = "1.1";
17
17
 
18
18
  /**
19
19
  * 機械形式 (正準JSON) が自分を名乗る版 (ADR-0036)。**言語版でもツール版でもない** —
@@ -21,7 +21,7 @@ export const DEFAULT_LANGUAGE_VERSION = "1.0";
21
21
  * majorは既存のキーの名前・並び・照合順・正規化・数の綴りが変わったとき (既存の文書のバイトが変わる)。
22
22
  * 意味論の版は muro が持つので、`koyu` キー (書かれた版宣言の素通し) とは別の面である
23
23
  */
24
- export const CANONICAL_FORMAT = "koyu-canonical/1.0";
24
+ export const CANONICAL_FORMAT = "koyu-canonical/1.1";
25
25
 
26
26
  /** 方位。edge指定は「最初に書いた空間」の矩形から見た辺。N=+Y, S=-Y, E=+X, W=-X */
27
27
  export type Edge = "N" | "E" | "S" | "W";
@@ -83,13 +83,17 @@ export interface Space {
83
83
  * パスの第一義は集計の階層 — レベルは既定で先頭セグメントから読むが、
84
84
  * 階を跨ぐくくり (メゾネット) は level: 属性で明示する (ADR-0008) */
85
85
  path: string;
86
- /** 開かれた語彙 (room, corridor, exterior, void, ...) */
87
- type: string;
86
+ /**
87
+ * 自由なラベル。**core はこの語を一切読まない**ので、綴りは何の判定にも効かない。
88
+ * 集計の軸と図面の刷り字にだけ現れる。任意 — 書かなければ何も無い。
89
+ * 構成の事実 (外部・吹抜け) は `outside:` / `void:` の宣言の側にある
90
+ */
91
+ type?: string;
88
92
  /** 所属レベル名 (パス先頭セグメント、または level: 属性) */
89
93
  level?: string;
90
94
  /** グリッド参照。複数矩形の合併でL字などを表す (rectsと同順) */
91
95
  grids: GridRef[];
92
- /** グリッド解決後のmm矩形の合併。exteriorなどは空。**書かれた割付** (セル) であって形ではない */
96
+ /** グリッド解決後のmm矩形の合併。`outside:1` の空間などは空。**書かれた割付** (セル) であって形ではない */
93
97
  rects: Rect[];
94
98
  /**
95
99
  * 導出された領域 — 凸片の集合 (ADR-0022)。既定は rects をそのまま写したもので、
@@ -258,7 +262,7 @@ export interface Model {
258
262
  /** 柱の宣言 (ADR-0023)。位置は書かれない — 通り芯の交点から導出される */
259
263
  columns: ColumnDecl[];
260
264
  /**
261
- * 合成に参加したレイヤー (ローダーのキー)。**この並びが層の強度順序である** (spec/composition.md)。
265
+ * 合成に参加したレイヤー (ローダーのキー)。**この並びが層の強度順序である** (docs/reference/muro/import.md)。
262
266
  * entry が添字0で最も弱く、**後の層ほど強い**。単一ソースの parse では空。
263
267
  *
264
268
  * 並びは import 行を深さ優先で平坦化した順で、同じ層が二度現れれば最初の位置を保つ。
@@ -415,7 +419,7 @@ export class SourceError extends Error {
415
419
  }
416
420
 
417
421
  /**
418
- * 空間の導出された領域 (ADR-0022 / spec/derivation.md §1)。**形を読むときの唯一の入口**。
422
+ * 空間の導出された領域 (ADR-0022 / docs/reference/form/index.md)。**形を読むときの唯一の入口**。
419
423
  * parse の出口で必ず埋まるので、割付への退避は「未parseのModelを手で組んだとき」だけに効く。
420
424
  * この式が各所に散っていたことが、rects と pieces の取り違えを四度生んだ根である。
421
425
  */
@@ -450,8 +454,8 @@ export function columnSites(
450
454
  const floors = [...model.spaces.values()].filter(
451
455
  (s) =>
452
456
  s.level === level &&
453
- s.type !== "exterior" &&
454
- s.type !== "void" &&
457
+ !isOutside(s) &&
458
+ !isVoid(s) &&
455
459
  s.rects.length > 0 &&
456
460
  // 空しか支えない床には柱を立てない (ADR-0030): 半屋外で上に床も無い
457
461
  // 屋上庭園・テラスは、柱が持ち上げるものを持たない
@@ -480,7 +484,7 @@ export function columnSites(
480
484
 
481
485
  /**
482
486
  * そのレベルに立つ柱を導く (ADR-0023)。
483
- * 通り芯の交点のうち、床のある空間 (exterior・void を除く) の内側にあるものへ柱を置く。
487
+ * 通り芯の交点のうち、床のある空間 (`outside:1`・`void:1` を除く) の内側にあるものへ柱を置く。
484
488
  * 位置はどこにも書かれていない — 通りと床という既にある事実の交わりから現れる
485
489
  */
486
490
  export function columnsFor(model: Model, level: string): Column[] {
@@ -507,7 +511,23 @@ export function columnsFor(model: Model, level: string): Column[] {
507
511
  }
508
512
 
509
513
  /**
510
- * 半屋外か — 宣言ではなく導出。外部 (type:exterior) に対して
514
+ * 建物の外部か。**空間の型ではなく `outside:1` の宣言で決まる。**
515
+ *
516
+ * 型の位置は開かれた語彙であって、そこから構成の事実を読むと綴りが意味を持ってしまう。
517
+ * `exteriorr` の一字で外部が屋内になり、延床が倍になりながら check は緑だった。
518
+ * 宣言なら台帳が綴りを守る (ATT03/ATT02) — 開かれた語彙を殺さずに塞ぐ唯一の形である。
519
+ */
520
+ export function isOutside(s: Space): boolean {
521
+ return s.attrs["outside"] === 1;
522
+ }
523
+
524
+ /** 吹抜けか — 床が無いので、面積にも通行にも数えない。[[isOutside]] と同じ理由で宣言である */
525
+ export function isVoid(s: Space): boolean {
526
+ return s.attrs["void"] === 1;
527
+ }
528
+
529
+ /**
530
+ * 半屋外か — 宣言ではなく導出。外部 (outside:1) に対して
511
531
  * open または air:1 (手すり等、遮蔽しない物) の境界で接する空間は半屋外である (ADR-0007)
512
532
  */
513
533
  export function isSemiOutdoor(model: Model, s: Space): boolean {
@@ -516,7 +536,8 @@ export function isSemiOutdoor(model: Model, s: Space): boolean {
516
536
  if (b.kind !== "open" && !b.air) continue;
517
537
  const other = b.a === s.path ? b.b : b.b === s.path ? b.a : undefined;
518
538
  if (!other) continue;
519
- if (model.spaces.get(other)?.type === "exterior") return true;
539
+ const o = model.spaces.get(other);
540
+ if (o && isOutside(o)) return true;
520
541
  }
521
542
  return false;
522
543
  }
@@ -575,7 +596,7 @@ export function zoneAreaM2(model: Model, zonePath: string): number {
575
596
  */
576
597
  export function isIndoor(model: Model, s: Space): boolean {
577
598
  if (s.rects.length === 0) return false;
578
- if (s.type === "exterior" || s.type === "void") return false;
599
+ if (isOutside(s) || isVoid(s)) return false;
579
600
  return !isSemiOutdoor(model, s);
580
601
  }
581
602
 
@@ -617,7 +638,7 @@ export function displayName(s: Space): string {
617
638
  /**
618
639
  * 開口が主張する同一性の名 (ADR-0039)。
619
640
  *
620
- * 開口の同一性は「含む対象 + その中で一意な名」から導かれる (spec/scope.md §5)。だが
641
+ * 開口の同一性は「含む対象 + その中で一意な名」から導かれる (docs/reference/scope.md)。だが
621
642
  * `name:` はアセットからも流れ込む — そしてアセットの `name` は**型の名**である
622
643
  * (`asset W1 window … name:掃き出し窓`)。同じ建具を一枚の壁に二枚並べるのは
623
644
  * ごく普通の設計であり、型の名を同一性の主張として読めば、それが衝突になってしまう。
@@ -692,7 +713,7 @@ export function newUids(model: Model, count = 1): string[] {
692
713
  /** 正準JSONの空間エントリ (書かれた表記・正準順)。semantic diff (ADR-0018) が比較基底として共有する */
693
714
  export function canonicalSpaceEntry(s: Space): Record<string, unknown> {
694
715
  return {
695
- type: s.type,
716
+ ...(s.type !== undefined ? { type: s.type } : {}),
696
717
  // 明示の level: (パス先頭セグメントと異なる所属 — メゾネット等) は書かれた構成として保存する。
697
718
  // これが無いとJSONだけでは所属レベル (垂直検査・集計・既定境界の前提) を復元できない
698
719
  ...(s.level !== undefined && s.path.split("/")[1] !== s.level ? { level: s.level } : {}),
@@ -772,15 +793,77 @@ export function canonicalBoundaryEntry(b: Boundary): Record<string, unknown> {
772
793
  export function canonicalBoundaryOrder(model: Model): Boundary[] {
773
794
  return [...model.boundaries]
774
795
  .map((b, i) => ({ b, key: JSON.stringify(canonicalBoundaryEntry(b)), i }))
775
- .sort((p, q) => (p.key < q.key ? -1 : p.key > q.key ? 1 : p.i - q.i))
796
+ .sort((p, q) => compareCanonical(p.key, q.key) || p.i - q.i)
776
797
  .map((x) => x.b);
777
798
  }
778
799
 
800
+ /**
801
+ * The openings of one boundary in canonical order, and its `seg`s likewise.
802
+ *
803
+ * **The same disease as `canonicalBoundaryOrder`, one level down.** The identity of an opening is
804
+ * `<the boundary's ref>/<index within the boundary>`, and that index used to be the declaration
805
+ * order — which the canonical form discards, since it sorts openings by content
806
+ * (`canonicalBoundaryEntry`). So two sources with byte-identical canonical JSON gave the same
807
+ * spelling to *different* openings: `…@4/0` was the door in one and the window in the other.
808
+ *
809
+ * A generated pair found this — the hand-written witnesses never swapped two openings on one
810
+ * boundary, and neither did any conformance case.
811
+ */
812
+ export function canonicalOpeningOrder(b: Boundary): Opening[] {
813
+ return [...b.openings]
814
+ .map((o, i) => ({ o, key: JSON.stringify(canonicalOpeningEntry(o)), i }))
815
+ .sort((p, q) => compareCanonical(p.key, q.key) || p.i - q.i)
816
+ .map((x) => x.o);
817
+ }
818
+
819
+ export function canonicalSegOrder(b: Boundary): Seg[] {
820
+ return [...b.segs]
821
+ .map((g, i) => ({ g, key: JSON.stringify(canonicalSegEntry(g)), i }))
822
+ .sort((p, q) => compareCanonical(p.key, q.key) || p.i - q.i)
823
+ .map((x) => x.g);
824
+ }
825
+
826
+ /**
827
+ * Spaces in canonical order (path collation).
828
+ *
829
+ * **Declaration order is information the canonical form discards** — `toCanonical` sorts the
830
+ * `spaces` keys by collation. So every derivation that reads spaces in order, such as the
831
+ * ordering of `Form.spaces`, uses this. The `Map` insertion order itself is left alone:
832
+ * diagnostics are contractually in **scan order** (ADR-0028), so another reader needs
833
+ * declaration order.
834
+ */
835
+ export function canonicalSpaceOrder(model: Model): Space[] {
836
+ return [...model.spaces.keys()].sort(compareCanonical).map((p) => model.spaces.get(p)!);
837
+ }
838
+
839
+ /**
840
+ * Puts the spelling of every region into canonical order.
841
+ *
842
+ * **The order the parts of a `+` union were written in is information the canonical form
843
+ * discards** — `canonicalSpaceEntry` runs `at` through `sortBySerial`. Discarded information
844
+ * must not change the shape, so everything that reads `rects` — convex pieces, boundary
845
+ * segments, slabs, plan entities, and the anchor of a room label when two pieces have equal
846
+ * area — is kept off the written order by sorting the spelling. `grids` and `rects` stay
847
+ * parallel.
848
+ */
849
+ export function normalizeRegionOrder(model: Model): void {
850
+ for (const s of model.spaces.values()) {
851
+ if (s.grids.length < 2 || s.grids.length !== s.rects.length) continue;
852
+ const order = s.grids
853
+ .map((g, i) => [JSON.stringify([g.xa, g.ya, g.xb, g.yb]), i] as const)
854
+ .sort(([x], [y]) => compareCanonical(x, y))
855
+ .map(([, i]) => i);
856
+ s.grids = order.map((i) => s.grids[i]!);
857
+ s.rects = order.map((i) => s.rects[i]!);
858
+ }
859
+ }
860
+
779
861
  /** 正準JSON — 機械形式。差分とレイヤー合成の土台 (キーは安定順) */
780
862
  export function toCanonical(model: Model): string {
781
- const spaces: Record<string, unknown> = {};
863
+ // Keys taken from the source go in a Map so the collation order survives serialisation
864
+ const spaces = new Map<string, unknown>();
782
865
  for (const p of [...model.spaces.keys()].sort(compareCanonical)) {
783
- spaces[p] = canonicalSpaceEntry(model.spaces.get(p)!);
866
+ spaces.set(p, canonicalSpaceEntry(model.spaces.get(p)!));
784
867
  }
785
868
  // 境界: 宣言順は意味を持たないため、並びは内容の正準順 (betweenの辞書順、同一betweenは直列化順)。
786
869
  // 既定境界 (derived — ADR-0014) は出さない: 正準JSONは書かれた構成のみで、意味は導出後のModelが持つ
@@ -788,19 +871,19 @@ export function toCanonical(model: Model): string {
788
871
  [...model.boundaries].filter((b) => !b.derived).map(canonicalBoundaryEntry),
789
872
  );
790
873
 
791
- const zones: Record<string, unknown> = {};
874
+ const zones = new Map<string, unknown>();
792
875
  for (const p of [...model.zones.keys()].sort(compareCanonical)) {
793
876
  const z = model.zones.get(p)!;
794
- zones[p] = Object.keys(z.attrs).length ? { attrs: sortObj(z.attrs) } : {};
877
+ zones.set(p, Object.keys(z.attrs).length ? { attrs: sortObj(z.attrs) } : {});
795
878
  }
796
- const assets: Record<string, unknown> = {};
879
+ const assets = new Map<string, unknown>();
797
880
  for (const n of [...model.assets.keys()].sort(compareCanonical)) {
798
881
  const a = model.assets.get(n)!;
799
- assets[n] = { kind: a.kind, ...(Object.keys(a.attrs).length ? { attrs: sortObj(a.attrs) } : {}) };
882
+ assets.set(n, { kind: a.kind, ...(Object.keys(a.attrs).length ? { attrs: sortObj(a.attrs) } : {}) });
800
883
  }
801
- const polygons: Record<string, number[][]> = {};
884
+ const polygons = new Map<string, number[][]>();
802
885
  for (const p of [...model.polygons.keys()].sort(compareCanonical)) {
803
- polygons[p] = model.polygons.get(p)!.points.map((pt) => [pt.x, pt.y]);
886
+ polygons.set(p, model.polygons.get(p)!.points.map((pt) => [pt.x, pt.y]));
804
887
  }
805
888
 
806
889
  const doc = {
@@ -826,8 +909,8 @@ export function toCanonical(model: Model): string {
826
909
  ]),
827
910
  ),
828
911
  ),
829
- ...(Object.keys(assets).length ? { assets } : {}),
830
- ...(Object.keys(polygons).length ? { polygons } : {}),
912
+ ...(assets.size ? { assets } : {}),
913
+ ...(polygons.size ? { polygons } : {}),
831
914
  // **柱の宣言順は意味である。**同じ交点に二本は立たず、先の宣言が勝つ (ADR-0023) ので、
832
915
  // 並べ替えると別の建物が同一のJSONになる。並べ替えてよいのは宣言の**中**の、
833
916
  // 順序に意味の無い通り名の列だけである (ADR-0029)
@@ -843,11 +926,11 @@ export function toCanonical(model: Model): string {
843
926
  })),
844
927
  }
845
928
  : {}),
846
- ...(Object.keys(zones).length ? { zones } : {}),
929
+ ...(zones.size ? { zones } : {}),
847
930
  spaces,
848
931
  boundaries,
849
932
  };
850
- return JSON.stringify(doc, null, 2) + "\n";
933
+ return canonicalStringify(doc) + "\n";
851
934
  }
852
935
 
853
936
  /**
@@ -927,8 +1010,35 @@ function utf8Order(u: number): number {
927
1010
  return u;
928
1011
  }
929
1012
 
930
- function sortObj<T>(o: Record<string, T>): Record<string, T> {
931
- return Object.fromEntries(Object.entries(o).sort(([a], [b]) => compareCanonical(a, b)));
1013
+ function sortObj<T>(o: Record<string, T>): Map<string, T> {
1014
+ return new Map(Object.entries(o).sort(([a], [b]) => compareCanonical(a, b)));
1015
+ }
1016
+
1017
+ /**
1018
+ * Serialises a canonical document, with the same bytes `JSON.stringify(value, null, 2)` produces —
1019
+ * plus `Map`, whose entries are emitted **in insertion order**.
1020
+ *
1021
+ * A plain object cannot carry the collation order: JavaScript keeps integer-like keys
1022
+ * (`"2"`, `"10"`) ahead of the rest, in ascending numeric order, whatever order they were inserted
1023
+ * in. So a level or asset named `2` came out before one named `10`, while collation order — which
1024
+ * this format promises — puts `10` first. `Object.fromEntries` silently undid a correct sort.
1025
+ * A `Map` has no such rule, so keys taken from the source are carried in one.
1026
+ */
1027
+ function canonicalStringify(value: unknown, depth = 0): string {
1028
+ const pad = " ".repeat(depth + 1);
1029
+ const close = " ".repeat(depth);
1030
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
1031
+ if (Array.isArray(value)) {
1032
+ if (value.length === 0) return "[]";
1033
+ const items = value.map((v) => pad + canonicalStringify(v, depth + 1));
1034
+ return `[\n${items.join(",\n")}\n${close}]`;
1035
+ }
1036
+ const entries: Array<[string, unknown]> =
1037
+ value instanceof Map ? [...value.entries()] : Object.entries(value);
1038
+ const kept = entries.filter(([, v]) => v !== undefined);
1039
+ if (kept.length === 0) return "{}";
1040
+ const items = kept.map(([k, v]) => `${pad}${JSON.stringify(k)}: ${canonicalStringify(v, depth + 1)}`);
1041
+ return `{\n${items.join(",\n")}\n${close}}`;
932
1042
  }
933
1043
 
934
1044
  /**
package/src/core/parse.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  type Edge,
14
14
  type Level,
15
15
  type Model,
16
+ normalizeRegionOrder,
16
17
  type Opening,
17
18
  type Pt,
18
19
  type Rect,
@@ -24,7 +25,7 @@ import {
24
25
  } from "./model.js";
25
26
  import { deriveDefaultBoundaries, derivePieces } from "./graph.js";
26
27
 
27
- /** 境界のトポロジー語 — 増やすのは最後の手段である (spec/vocabulary.md 規則1) */
28
+ /** 境界のトポロジー語 — 増やすのは最後の手段である (docs/reference/muro/attributes.md 規則1) */
28
29
  const BOUNDARY_KINDS = new Set(["wall", "open", "stair", "shaft", "void"]);
29
30
 
30
31
  const EDGES = new Set(["N", "E", "S", "W"]);
@@ -50,7 +51,8 @@ interface BandDecl {
50
51
 
51
52
  interface BandMember {
52
53
  path: string;
53
- type: string;
54
+ /** 自由なラベル。space と同じく任意 */
55
+ type?: string;
54
56
  /** 帯の向きの寸法mm。"rest" は残りを吸収する印 (帯に高々一つ) */
55
57
  w: number | "rest";
56
58
  attrTokens: string[];
@@ -85,7 +87,10 @@ export type LayerLoader = (
85
87
  export function parse(source: string): Model {
86
88
  const model = emptyModel();
87
89
  ingest(model, source, undefined, new Set(), undefined);
88
- // 描かれた線で領域を切り分けてから、既定の壁を導く (ADR-0022 / spec/derivation.md §1)。
90
+ // Put the region spellings into canonical order before cutting — both the cutting and the
91
+ // default boundaries read `rects`, so without this the written order of `+` stays in the shape
92
+ normalizeRegionOrder(model);
93
+ // 描かれた線で領域を切り分けてから、既定の壁を導く (ADR-0022 / docs/reference/form/index.md)。
89
94
  // 逆順だと、線で接触が消えた組にも既定境界が生まれ、線分ゼロの境界に
90
95
  // 出所の無い BND04 が出る — 書いていない関係を責めることになる
91
96
  derivePieces(model);
@@ -103,7 +108,10 @@ export function parseWith(loader: LayerLoader, entry: string): Model {
103
108
  throw new SourceError(0, `Cannot read file: ${entry}`);
104
109
  }
105
110
  ingestLayer(model, layer.key, layer.src, new Set(), loader);
106
- // 描かれた線で領域を切り分けてから、既定の壁を導く (ADR-0022 / spec/derivation.md §1)。
111
+ // Put the region spellings into canonical order before cutting — both the cutting and the
112
+ // default boundaries read `rects`, so without this the written order of `+` stays in the shape
113
+ normalizeRegionOrder(model);
114
+ // 描かれた線で領域を切り分けてから、既定の壁を導く (ADR-0022 / docs/reference/form/index.md)。
107
115
  // 逆順だと、線で接触が消えた組にも既定境界が生まれ、線分ゼロの境界に
108
116
  // 出所の無い BND04 が出る — 書いていない関係を責めることになる
109
117
  derivePieces(model);
@@ -149,7 +157,7 @@ function ingestLayer(
149
157
  ): void {
150
158
  if (seen.has(key)) return; // 同じレイヤーは一度だけ合成される (USDのsublayerと同じ)
151
159
  seen.add(key);
152
- // **この push の順序が層の強度順序である** (spec/composition.md 規則1)。
160
+ // **この push の順序が層の強度順序である** (docs/reference/muro/import.md 規則1)。
153
161
  // entry が添字0で最も弱く、後の層ほど強い。同じ層が二度 import されても最初の位置を保つ
154
162
  model.layers.push(key);
155
163
  ingest(model, src, key, seen, loader);
@@ -297,7 +305,7 @@ function ingest(
297
305
  for (const [key, v] of Object.entries(attrs)) {
298
306
  switch (over.kind) {
299
307
  case "space":
300
- applyAttr(model, "space", subject, over.space.attrs, key, v, layer, ln, layerOf(model, over.space.file));
308
+ applySpaceAttr(model, over.space, key, v, layer, ln);
301
309
  break;
302
310
  case "zone":
303
311
  applyAttr(model, "zone", subject, over.zone.attrs, key, v, layer, ln, layerOf(model, over.zone.file));
@@ -416,9 +424,9 @@ function ingest(
416
424
  if (!name) throw new SourceError(ln, "level requires a name");
417
425
  const z = toNumber(rest[1] ?? "", ln, "The level height (z)");
418
426
  const attrs = parseAttrs(rest.slice(2), ln);
419
- const h = takeNumber(attrs, "h", ln);
420
- const slab = takeNumber(attrs, "slab", ln);
421
- const pitch = takeNumber(attrs, "pitch", ln);
427
+ const h = takeNumber(attrs, "h", ln, { positive: true });
428
+ const slab = takeNumber(attrs, "slab", ln, { positive: true });
429
+ const pitch = takeNumber(attrs, "pitch", ln, { positive: true });
422
430
  const under = takeNumber(attrs, "underground", ln);
423
431
  // **level は attrs を持たない。**残ったキーは正準JSONにも痕跡を残さず消えるので、
424
432
  // ここで拒まないと `undergound:1` が黙って地上階になる (ADR-0033)
@@ -488,7 +496,7 @@ function ingest(
488
496
  return [span];
489
497
  })();
490
498
  const attrs = parseAttrs(rest.slice(2), ln);
491
- const depth = takeNumber(attrs, "d", ln);
499
+ const depth = takeNumber(attrs, "d", ln, { positive: true });
492
500
  const names = (key: "x" | "y"): string[] | undefined => {
493
501
  const v = takeString(attrs, key);
494
502
  if (v === undefined) return undefined;
@@ -525,10 +533,7 @@ function ingest(
525
533
  if (!path) throw new SourceError(ln, "space requires a path");
526
534
  // w: は帯の要素の語 — 字下げを落とした要素が「領域なしの空間」として黙って通るのを防ぐ
527
535
  if (rest.some((t) => t === "w:" || t.startsWith("w:"))) {
528
- throw new SourceError(
529
- ln,
530
- "w: may not be written on space (a space written by width sits indented under band)",
531
- );
536
+ throw new SourceError(ln, W_ON_SPACE);
532
537
  }
533
538
  for (const [p] of expandSpan(model, [path], ln)) {
534
539
  const space = parseSpace([p!, ...rest.slice(1)], ln, model);
@@ -587,7 +592,7 @@ function ingest(
587
592
  const leaf = rest[0];
588
593
  const span = rest[1];
589
594
  if (!leaf || leaf.startsWith("/") || !span) {
590
- throw new SourceError(ln, "stack takes the form stack <name> <L?..L?> type:stair|shaft");
595
+ throw new SourceError(ln, "stack takes the form stack <name> <L?..L?> type:stair|shaft|void");
591
596
  }
592
597
  const levels = resolveSpanLevels(model, span, ln);
593
598
  const attrs = parseAttrs(rest.slice(2), ln);
@@ -642,14 +647,21 @@ function parseSpace(rest: string[], ln: number, model: Model): Space {
642
647
  if (!path || !path.startsWith("/")) {
643
648
  throw new SourceError(ln, "space takes the form space /path type [X?..X? Y?..Y? [+ ...]]");
644
649
  }
645
- const type = rest[1];
646
- if (!type) throw new SourceError(ln, `space ${path} requires a type (a word from the vocabulary)`);
647
- guardStructuralType(type, ln);
650
+ // 型は任意である。**位置ではなく形で決まる** — 区画 (`..` を含む)・区画の区切り (`+`)・
651
+ // 属性 (`k:v`) のどれでもない裸の語だけが型になる。
652
+ //
653
+ // 必須をやめたのは、必須である理由が無くなったからである。かつてこの位置には
654
+ // `exterior` と `void` — 構成の事実 — が書かれ、だから必ず一語要った。二語が台帳へ移り、
655
+ // core がこの位置を一切読まなくなった今、残っているのは自由なラベルであり、
656
+ // ラベルを強制する言語は書き手に無意味な語を選ばせる。書かなければ何も無い
657
+ // (既定は捏造しない — docs/why/silence.md)。
658
+ const head = rest[1];
659
+ const type = head !== undefined && head !== "+" && !head.includes("..") && !head.includes(":") ? head : undefined;
648
660
 
649
661
  // 領域は「+」区切りで複数書ける (L字などの合併)
650
662
  const groups: string[][] = [[]];
651
663
  const attrTokens: string[] = [];
652
- for (const t of rest.slice(2)) {
664
+ for (const t of rest.slice(type === undefined ? 1 : 2)) {
653
665
  if (t === "+") {
654
666
  groups.push([]);
655
667
  } else if (t.includes("..")) {
@@ -740,15 +752,12 @@ function parseBandMember(rest: string[], ln: number): BandMember {
740
752
  if (!path?.startsWith("/")) {
741
753
  throw new SourceError(ln, "A band member takes the form space /path type w:(mm)");
742
754
  }
743
- const type = rest[1];
744
- // 型の位置に k:v が来たら「型の書き忘れ」— 幅の欠落として誤報しない
745
- if (!type || type.includes(":")) {
746
- throw new SourceError(ln, `The band member ${path} requires a type (a word from the vocabulary)`);
747
- }
748
- guardStructuralType(type, ln);
755
+ // 帯の要素でも型は任意である (space と同じ規則)。`k:v` は属性であって型ではない
756
+ const head2 = rest[1];
757
+ const type = head2 !== undefined && !head2.includes(":") && !head2.includes("..") && head2 !== "+" ? head2 : undefined;
749
758
  let w: number | "rest" | undefined;
750
759
  const attrTokens: string[] = [];
751
- for (const t of rest.slice(2)) {
760
+ for (const t of rest.slice(type === undefined ? 1 : 2)) {
752
761
  if (t === "+" || t.includes("..")) {
753
762
  throw new SourceError(ln, `A region may not be written on a band member (the band and w: give it): ${t}`);
754
763
  }
@@ -862,7 +871,11 @@ function expandBand(model: Model, band: BandDecl, file: string | undefined): voi
862
871
  const cross = `${band.crossA}..${band.crossB}`;
863
872
  const xTok = axis === "X" ? along : cross;
864
873
  const yTok = axis === "X" ? cross : along;
865
- const space = parseSpace([it[k]!, m.type, xTok, yTok, ...m.attrTokens], m.line, model);
874
+ const space = parseSpace(
875
+ [it[k]!, ...(m.type !== undefined ? [m.type] : []), xTok, yTok, ...m.attrTokens],
876
+ m.line,
877
+ model,
878
+ );
866
879
  const prev = model.spaces.get(space.path);
867
880
  if (prev) {
868
881
  throw new SourceError(
@@ -1063,7 +1076,7 @@ function parseBoundary(rest: string[], ln: number): Boundary {
1063
1076
  throw new SourceError(ln, "boundary takes the form boundary /pathA /pathB [attributes...]");
1064
1077
  }
1065
1078
  const attrs = parseAttrs(rest.slice(2), ln);
1066
- const t = takeNumber(attrs, "t", ln);
1079
+ const t = takeNumber(attrs, "t", ln, { positive: true });
1067
1080
  const kindRaw = takeString(attrs, "type") ?? "wall";
1068
1081
  if (!BOUNDARY_KINDS.has(kindRaw)) {
1069
1082
  throw new SourceError(
@@ -1119,7 +1132,7 @@ function parseOpening(
1119
1132
  if (w === undefined || w <= 0) {
1120
1133
  throw new SourceError(ln, `${kind} requires a width w:(mm) (the asset may supply it)`);
1121
1134
  }
1122
- const h = takeNumber(attrs, "h", ln);
1135
+ const h = takeNumber(attrs, "h", ln, { positive: true });
1123
1136
  const at = parseAt(attrs, ln, model);
1124
1137
  const edge = takeEdge(attrs, ln);
1125
1138
  const hingeRaw = takeString(attrs, "hinge");
@@ -1169,55 +1182,6 @@ export function tokenize(line: string, ln: number): string[] {
1169
1182
  return tokens;
1170
1183
  }
1171
1184
 
1172
- /**
1173
- * 型として構造的に解釈される二語 (spec/vocabulary.md 規則1)。
1174
- * `exterior` は「外部」、`void` は「床面積に算入しない」— どちらも構成の事実である。
1175
- */
1176
- const STRUCTURAL_TYPES = ["exterior", "void"];
1177
-
1178
- /** 編集距離が1以内か (挿入・削除・置換をそれぞれ1と数える) */
1179
- function nearBy1(a: string, b: string): boolean {
1180
- if (a === b) return false;
1181
- if (Math.abs(a.length - b.length) > 1) return false;
1182
- let i = 0;
1183
- let j = 0;
1184
- let diff = 0;
1185
- while (i < a.length && j < b.length) {
1186
- if (a[i] === b[j]) {
1187
- i++;
1188
- j++;
1189
- continue;
1190
- }
1191
- if (++diff > 1) return false;
1192
- if (a.length > b.length) i++;
1193
- else if (a.length < b.length) j++;
1194
- else {
1195
- i++;
1196
- j++;
1197
- }
1198
- }
1199
- return diff + (a.length - i) + (b.length - j) <= 1;
1200
- }
1201
-
1202
- /**
1203
- * 型の綴りを守る (ADR-0033)。**型の語彙は開いている** — `room` も `ldk` も `厨房` も自由である。
1204
- * だが構造として解釈される二語だけは、一字違いが黙って意味を変える:
1205
- * `exteriorr` と書けば外部でなくなり、延床が倍になる。check は緑のままだった。
1206
- *
1207
- * 開かれた語彙を殺さずにこれを塞ぐ唯一の形が、**二語の近傍だけを拒むこと**である。
1208
- * 遠い語 (room / yard / ldk) は何も言われない。
1209
- */
1210
- function guardStructuralType(type: string, ln: number): void {
1211
- for (const w of STRUCTURAL_TYPES) {
1212
- if (nearBy1(type.toLowerCase(), w)) {
1213
- throw new SourceError(
1214
- ln,
1215
- `The type ${type} looks like a misspelling of ${w} (${w} is read structurally — if a different word was meant, spell it further away)`,
1216
- );
1217
- }
1218
- }
1219
- }
1220
-
1221
1185
  /**
1222
1186
  * 上書きの対象 (合成の規則4 — 定義と上書きの区別)。
1223
1187
  * `space` / `boundary` は**定義**であり、重複はエラーである。`over` は**上書き**であり、
@@ -1296,11 +1260,6 @@ function applyAttr(
1296
1260
  model.attrSrc.set(k, layer);
1297
1261
  }
1298
1262
 
1299
- /** 定義された属性の出所を、その層のものとして記録する */
1300
- function recordAttrs(model: Model, kind: string, subject: string, attrs: Attrs, layer: number): void {
1301
- for (const key of Object.keys(attrs)) model.attrSrc.set(srcKey(kind, subject, key), layer);
1302
- }
1303
-
1304
1263
  /** 集合の要素を名で引く (合成の規則3 — 同一性は「含む対象 + その中で一意な名」) */
1305
1264
  function findNamed<T extends { attrs: Attrs }>(list: T[], name: string): T[] {
1306
1265
  return list.filter((x) => String(x.attrs["name"] ?? "") === name);
@@ -1390,6 +1349,46 @@ function applyLevelAttr(
1390
1349
  }
1391
1350
 
1392
1351
  /** 境界の上書き — typed field (type/t/air/edge) と自由属性の両方を受ける */
1352
+ /** The words for a band-member key written on `space`. Declaration and `over` refuse it alike */
1353
+ const W_ON_SPACE = "w: may not be written on space (a space written by width sits indented under band)";
1354
+
1355
+ /**
1356
+ * Applies an attribute an `over` wrote on a space.
1357
+ *
1358
+ * **A word the `space` declaration refuses, `over` refuses too; a word the declaration takes as
1359
+ * a typed field, `over` sets as a typed field.** Otherwise one word means different things
1360
+ * depending on how it was written, and composition rule 5 — an overridden model and one written
1361
+ * that way from the start give the same canonical form — breaks. Handing this to the generic
1362
+ * `applyAttr` looked at no key at all: `w:` let a write meant as "make it this wide" land
1363
+ * silently in `attrs`, and `level:` left a dead attribute behind without moving the space.
1364
+ * Both kept `check` green.
1365
+ */
1366
+ function applySpaceAttr(
1367
+ model: Model,
1368
+ s: Space,
1369
+ key: string,
1370
+ v: AttrValue,
1371
+ layer: number,
1372
+ ln: number,
1373
+ ): void {
1374
+ if (key === "w") throw new SourceError(ln, W_ON_SPACE);
1375
+ if (key !== "level") {
1376
+ applyAttr(model, "space", s.path, s.attrs, key, v, layer, ln, layerOf(model, s.file));
1377
+ return;
1378
+ }
1379
+ // level is a typed field, so it carries its own strength check (same shape as applyBoundaryAttr)
1380
+ const k = srcKey("space", s.path, key);
1381
+ const prev = model.attrSrc.get(k) ?? layerOf(model, s.file);
1382
+ if (prev > layer) return;
1383
+ if (prev === layer) {
1384
+ throw new SourceError(ln, `One layer holds two opinions about level on space ${s.path}`);
1385
+ }
1386
+ const name = String(v);
1387
+ if (!model.levels[name]) throw new SourceError(ln, `Undeclared level: level:${name}`);
1388
+ s.level = name;
1389
+ model.attrSrc.set(k, layer);
1390
+ }
1391
+
1393
1392
  function applyBoundaryAttr(
1394
1393
  model: Model,
1395
1394
  b: Boundary,
@@ -1432,7 +1431,7 @@ function applyBoundaryAttr(
1432
1431
  * - door D9 削除 (名で指す)
1433
1432
  * = door D9 w:1200 置換 (名で指し、書いた属性だけを差し替える)
1434
1433
  *
1435
- * 同一性は「含む対象 + その中で一意な名」である (spec/scope.md §5)。
1434
+ * 同一性は「含む対象 + その中で一意な名」である (docs/reference/scope.md)。
1436
1435
  * 名を持たない要素は編集の対象にできない — 指す言葉が無いからである。
1437
1436
  */
1438
1437
  function applySetEdit(
@@ -1591,7 +1590,20 @@ function toNumber(v: string, ln: number, what: string): number {
1591
1590
  return Number(v);
1592
1591
  }
1593
1592
 
1594
- function takeNumber(attrs: Attrs, key: string, ln: number): number | undefined {
1593
+ /**
1594
+ * Takes a typed field out of the attribute bag.
1595
+ *
1596
+ * `positive` mirrors what the ledger already requires of the keys that stay in the bag — ATT01
1597
+ * says "is written as a positive number". A key lifted into a typed field never reaches ATT01, so
1598
+ * without this the same promise held on one path and not the other: `level L1 0 h:-2400 slab:-150`
1599
+ * went green and put negative values into the canonical JSON, inverting floor and ceiling.
1600
+ */
1601
+ function takeNumber(
1602
+ attrs: Attrs,
1603
+ key: string,
1604
+ ln: number,
1605
+ opts: { positive?: boolean } = {},
1606
+ ): number | undefined {
1595
1607
  const v = attrs[key];
1596
1608
  if (v === undefined) return undefined;
1597
1609
  delete attrs[key];
@@ -1599,6 +1611,9 @@ function takeNumber(attrs: Attrs, key: string, ln: number): number | undefined {
1599
1611
  // NaNの黙認はcheck緑のまま導出を壊す (typo h:24O0 など) — その場のエラーにする
1600
1612
  throw new SourceError(ln, `The attribute ${key} is written as a number: ${v}`);
1601
1613
  }
1614
+ if (opts.positive && !(v > 0)) {
1615
+ throw new SourceError(ln, `${key} is written as a positive number: ${key}:${v}`);
1616
+ }
1602
1617
  return v;
1603
1618
  }
1604
1619