bimdown-cli 0.1.5 → 0.1.9

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 (51) hide show
  1. package/dist/index.js +709 -72
  2. package/dist/index.js.map +1 -1
  3. package/dist/spec/csv-schema/architecture/ceiling.yaml +9 -0
  4. package/dist/spec/csv-schema/architecture/column.yaml +8 -0
  5. package/dist/spec/csv-schema/architecture/curtain_wall.yaml +31 -0
  6. package/dist/spec/csv-schema/architecture/door.yaml +35 -0
  7. package/dist/spec/csv-schema/architecture/opening.yaml +36 -0
  8. package/dist/spec/csv-schema/architecture/railing.yaml +7 -0
  9. package/dist/spec/csv-schema/architecture/ramp.yaml +7 -0
  10. package/dist/spec/csv-schema/architecture/roof.yaml +22 -0
  11. package/dist/spec/csv-schema/architecture/room_separator.yaml +5 -0
  12. package/dist/spec/csv-schema/architecture/slab.yaml +15 -0
  13. package/dist/spec/csv-schema/architecture/space.yaml +17 -0
  14. package/dist/spec/csv-schema/architecture/stair.yaml +11 -0
  15. package/dist/spec/csv-schema/architecture/wall.yaml +11 -0
  16. package/dist/spec/csv-schema/architecture/window.yaml +13 -0
  17. package/dist/spec/csv-schema/base/element.yaml +60 -0
  18. package/dist/spec/csv-schema/base/hosted_element.yaml +15 -0
  19. package/dist/spec/csv-schema/base/line_element.yaml +25 -0
  20. package/dist/spec/csv-schema/base/materialized.yaml +22 -0
  21. package/dist/spec/csv-schema/base/mep_connected_segment.yaml +17 -0
  22. package/dist/spec/csv-schema/base/mep_system.yaml +7 -0
  23. package/dist/spec/csv-schema/base/point_element.yaml +17 -0
  24. package/dist/spec/csv-schema/base/polygon_element.yaml +14 -0
  25. package/dist/spec/csv-schema/base/section_profile.yaml +16 -0
  26. package/dist/spec/csv-schema/base/spatial_line_element.yaml +13 -0
  27. package/dist/spec/csv-schema/base/structural_section_profile.yaml +21 -0
  28. package/dist/spec/csv-schema/base/vertical_span.yaml +17 -0
  29. package/dist/spec/csv-schema/grid.yaml +26 -0
  30. package/dist/spec/csv-schema/level.yaml +17 -0
  31. package/dist/spec/csv-schema/mep/cable_tray.yaml +8 -0
  32. package/dist/spec/csv-schema/mep/conduit.yaml +8 -0
  33. package/dist/spec/csv-schema/mep/duct.yaml +8 -0
  34. package/dist/spec/csv-schema/mep/equipment.yaml +22 -0
  35. package/dist/spec/csv-schema/mep/mep_node.yaml +6 -0
  36. package/dist/spec/csv-schema/mep/pipe.yaml +8 -0
  37. package/dist/spec/csv-schema/mep/terminal.yaml +19 -0
  38. package/dist/spec/csv-schema/mesh.yaml +40 -0
  39. package/dist/spec/csv-schema/structure/beam.yaml +7 -0
  40. package/dist/spec/csv-schema/structure/brace.yaml +7 -0
  41. package/dist/spec/csv-schema/structure/foundation.yaml +22 -0
  42. package/dist/spec/csv-schema/structure/structure_column.yaml +8 -0
  43. package/dist/spec/csv-schema/structure/structure_slab.yaml +14 -0
  44. package/dist/spec/csv-schema/structure/structure_wall.yaml +9 -0
  45. package/dist/spec/duckdb-strategy.md +93 -0
  46. package/dist/spec/llm-classification.md +453 -0
  47. package/dist/spec/migration-guide.md +248 -0
  48. package/dist/spec/project_metadata.schema.yaml +21 -0
  49. package/dist/spec/readme.md +247 -0
  50. package/dist/spec/svg-schema/readme.md +165 -0
  51. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -62,7 +62,8 @@ function normalizeField(raw) {
62
62
  required: raw.required ?? false,
63
63
  computed: raw.computed ?? false,
64
64
  reference: raw.reference,
65
- values: raw.values
65
+ values: raw.values,
66
+ description: raw.description
66
67
  };
67
68
  }
68
69
  var init_loader = __esm({
@@ -73,6 +74,7 @@ var init_loader = __esm({
73
74
 
74
75
  // src/schema/registry.ts
75
76
  import { join as join2, dirname } from "path";
77
+ import { existsSync } from "fs";
76
78
  import { fileURLToPath } from "url";
77
79
  function buildRegistry(specDir) {
78
80
  if (_registry && _specDir === specDir) return _registry;
@@ -89,6 +91,7 @@ function buildRegistry(specDir) {
89
91
  registry.set(name, {
90
92
  name,
91
93
  prefix,
94
+ description: schema.description,
92
95
  hostType: schema.host_type,
93
96
  allFields,
94
97
  csvFields,
@@ -101,9 +104,18 @@ function buildRegistry(specDir) {
101
104
  }
102
105
  function getSpecDir() {
103
106
  if (process.env.SPEC_DIR) return process.env.SPEC_DIR;
104
- const thisFile = fileURLToPath(import.meta.url);
105
- const thisDir = dirname(thisFile);
106
- return join2(thisDir, "..", "..", "spec");
107
+ const thisDir = dirname(fileURLToPath(import.meta.url));
108
+ const bundledPath = join2(thisDir, "spec");
109
+ if (existsSync(bundledPath)) return bundledPath;
110
+ let current = thisDir;
111
+ for (let i = 0; i < 5; i++) {
112
+ const candidate = join2(current, "spec");
113
+ if (existsSync(candidate)) return candidate;
114
+ const parent = dirname(current);
115
+ if (parent === current) break;
116
+ current = parent;
117
+ }
118
+ return join2(process.cwd(), "spec");
107
119
  }
108
120
  var ID_PREFIXES, GLOBAL_ONLY_TABLES, TABLES_WITHOUT_SVG, SVG_FILE_NAMES, TABLES_WITH_SVG, _registry, _specDir;
109
121
  var init_registry = __esm({
@@ -154,12 +166,12 @@ var init_registry = __esm({
154
166
  });
155
167
 
156
168
  // src/utils/fs.ts
157
- import { readdirSync as readdirSync2, statSync as statSync2, existsSync } from "fs";
169
+ import { readdirSync as readdirSync2, statSync as statSync2, existsSync as existsSync2 } from "fs";
158
170
  import { join as join3 } from "path";
159
171
  function discoverLayout(dir) {
160
172
  const globalDir = join3(dir, "global");
161
173
  const levelDirs = [];
162
- if (existsSync(dir) && statSync2(dir).isDirectory()) {
174
+ if (existsSync2(dir) && statSync2(dir).isDirectory()) {
163
175
  for (const entry of readdirSync2(dir)) {
164
176
  if (entry === "global" || entry.startsWith(".")) continue;
165
177
  const full = join3(dir, entry);
@@ -171,7 +183,7 @@ function discoverLayout(dir) {
171
183
  return { root: dir, globalDir, levelDirs };
172
184
  }
173
185
  function listFiles(dir) {
174
- if (!existsSync(dir)) return [];
186
+ if (!existsSync2(dir)) return [];
175
187
  return readdirSync2(dir).filter((f) => {
176
188
  const full = join3(dir, f);
177
189
  return statSync2(full).isFile();
@@ -506,7 +518,7 @@ var hydrate_exports = {};
506
518
  __export(hydrate_exports, {
507
519
  hydrate: () => hydrate
508
520
  });
509
- import { existsSync as existsSync4 } from "fs";
521
+ import { existsSync as existsSync5 } from "fs";
510
522
  import { join as join6 } from "path";
511
523
  async function hydrate(conn, dir) {
512
524
  const registry = buildRegistry(getSpecDir());
@@ -520,7 +532,7 @@ async function hydrate(conn, dir) {
520
532
  const csvFiles = [];
521
533
  for (const d of allDirs) {
522
534
  const csvPath = join6(d.path, `${tableName}.csv`);
523
- if (existsSync4(csvPath)) {
535
+ if (existsSync5(csvPath)) {
524
536
  csvFiles.push({ dir: d.name, fullPath: csvPath });
525
537
  }
526
538
  }
@@ -554,7 +566,7 @@ async function injectGeometry(conn, tableName, dirs) {
554
566
  for (const d of dirs) {
555
567
  if (d.name === "global") continue;
556
568
  const svgPath = join6(d.path, `${svgName}.svg`);
557
- if (!existsSync4(svgPath)) continue;
569
+ if (!existsSync5(svgPath)) continue;
558
570
  try {
559
571
  const svg = parseSvgFile(svgPath);
560
572
  for (const el of svg.elements) {
@@ -614,7 +626,7 @@ var dehydrate_exports = {};
614
626
  __export(dehydrate_exports, {
615
627
  dehydrate: () => dehydrate
616
628
  });
617
- import { existsSync as existsSync5, mkdirSync } from "fs";
629
+ import { existsSync as existsSync6, mkdirSync } from "fs";
618
630
  import { join as join7 } from "path";
619
631
  async function dehydrate(conn, dir) {
620
632
  const registry = buildRegistry(getSpecDir());
@@ -632,7 +644,7 @@ async function dehydrate(conn, dir) {
632
644
  for (const partRow of partResult.rows) {
633
645
  const partition = String(partRow._partition);
634
646
  const outDir = join7(dir, partition);
635
- if (!existsSync5(outDir)) mkdirSync(outDir, { recursive: true });
647
+ if (!existsSync6(outDir)) mkdirSync(outDir, { recursive: true });
636
648
  const selectCols = csvHeaders.map((h) => `"${h}"`).join(", ");
637
649
  const dataResult = await runQuery(
638
650
  conn,
@@ -662,13 +674,302 @@ var init_dehydrate = __esm({
662
674
  }
663
675
  });
664
676
 
677
+ // src/render.ts
678
+ var render_exports = {};
679
+ __export(render_exports, {
680
+ renderLevel: () => renderLevel
681
+ });
682
+ import { existsSync as existsSync7 } from "fs";
683
+ import { join as join8 } from "path";
684
+ function elementBounds2(el) {
685
+ switch (el.tag) {
686
+ case "path": {
687
+ const d = el.attrs.d ?? "";
688
+ const m = d.match(/M\s*(-?[\d.]+)[,\s]+(-?[\d.]+)\s*L\s*(-?[\d.]+)[,\s]+(-?[\d.]+)/);
689
+ if (!m) return null;
690
+ const x1 = parseFloat(m[1]), y1 = parseFloat(m[2]);
691
+ const x2 = parseFloat(m[3]), y2 = parseFloat(m[4]);
692
+ const sw = parseFloat(el.attrs["stroke-width"] ?? "0.2") / 2;
693
+ return { minX: Math.min(x1, x2) - sw, minY: Math.min(y1, y2) - sw, maxX: Math.max(x1, x2) + sw, maxY: Math.max(y1, y2) + sw };
694
+ }
695
+ case "line": {
696
+ const x1 = parseFloat(el.attrs.x1 ?? "0"), y1 = parseFloat(el.attrs.y1 ?? "0");
697
+ const x2 = parseFloat(el.attrs.x2 ?? "0"), y2 = parseFloat(el.attrs.y2 ?? "0");
698
+ const sw = parseFloat(el.attrs["stroke-width"] ?? "0") / 2;
699
+ return { minX: Math.min(x1, x2) - sw, minY: Math.min(y1, y2) - sw, maxX: Math.max(x1, x2) + sw, maxY: Math.max(y1, y2) + sw };
700
+ }
701
+ case "rect": {
702
+ const x = parseFloat(el.attrs.x ?? "0"), y = parseFloat(el.attrs.y ?? "0");
703
+ const w = parseFloat(el.attrs.width ?? "0"), h = parseFloat(el.attrs.height ?? "0");
704
+ return { minX: x, minY: y, maxX: x + w, maxY: y + h };
705
+ }
706
+ case "circle": {
707
+ const cx = parseFloat(el.attrs.cx ?? "0"), cy = parseFloat(el.attrs.cy ?? "0");
708
+ const r = parseFloat(el.attrs.r ?? "0");
709
+ return { minX: cx - r, minY: cy - r, maxX: cx + r, maxY: cy + r };
710
+ }
711
+ case "polygon": {
712
+ const pts = (el.attrs.points ?? "").trim().split(/\s+/).map((p) => {
713
+ const [x, y] = p.split(",").map(Number);
714
+ return { x: x ?? 0, y: y ?? 0 };
715
+ });
716
+ if (pts.length === 0) return null;
717
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
718
+ for (const p of pts) {
719
+ minX = Math.min(minX, p.x);
720
+ minY = Math.min(minY, p.y);
721
+ maxX = Math.max(maxX, p.x);
722
+ maxY = Math.max(maxY, p.y);
723
+ }
724
+ return { minX, minY, maxX, maxY };
725
+ }
726
+ default:
727
+ return null;
728
+ }
729
+ }
730
+ function renderElement(el, tableName) {
731
+ const color = COLORS[tableName] ?? DEFAULT_COLOR;
732
+ const isDashed = tableName === "room_separator";
733
+ switch (el.tag) {
734
+ case "path": {
735
+ const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
736
+ const sw = el.attrs["stroke-width"] ?? "0.2";
737
+ const dash = isDashed ? ' stroke-dasharray="0.2,0.1"' : "";
738
+ return ` <path ${attrs} stroke="${color.stroke}" stroke-width="${sw}" stroke-linecap="square"${dash} />`;
739
+ }
740
+ case "line": {
741
+ const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
742
+ const sw = el.attrs["stroke-width"] ?? "0.2";
743
+ const dash = isDashed ? ' stroke-dasharray="0.2,0.1"' : "";
744
+ return ` <line ${attrs} stroke="${color.stroke}" stroke-width="${sw}" stroke-linecap="square"${dash} />`;
745
+ }
746
+ case "polygon": {
747
+ const fill = color.fill ?? "none";
748
+ const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
749
+ return ` <polygon ${attrs} fill="${fill}" stroke="${color.stroke}" stroke-width="0.05" />`;
750
+ }
751
+ case "rect": {
752
+ const fill = color.fill ?? "none";
753
+ const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
754
+ return ` <rect ${attrs} fill="${fill}" stroke="${color.stroke}" stroke-width="0.05" />`;
755
+ }
756
+ case "circle": {
757
+ const fill = color.fill ?? "none";
758
+ const attrs = Object.entries(el.attrs).filter(([k]) => !OVERRIDE_ATTRS.has(k)).map(([k, v]) => `${k}="${v}"`).join(" ");
759
+ return ` <circle ${attrs} fill="${fill}" stroke="${color.stroke}" stroke-width="0.05" />`;
760
+ }
761
+ default:
762
+ return "";
763
+ }
764
+ }
765
+ function escapeXml(s) {
766
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
767
+ }
768
+ function renderHostedElements(levelDir, tableName, wallElements) {
769
+ const csvPath = join8(levelDir.path, `${tableName}.csv`);
770
+ if (!existsSync7(csvPath)) return [];
771
+ const csv = readCsv(csvPath);
772
+ const color = COLORS[tableName] ?? DEFAULT_COLOR;
773
+ const results = [];
774
+ for (const row of csv.rows) {
775
+ const hostId = row.host_id;
776
+ const position = parseFloat(row.position ?? "");
777
+ const width = parseFloat(row.width ?? "0");
778
+ if (!hostId || isNaN(position)) continue;
779
+ const wall = wallElements.get(hostId);
780
+ if (!wall) continue;
781
+ let wx1, wy1, wx2, wy2;
782
+ if (wall.tag === "path") {
783
+ const d = wall.attrs.d ?? "";
784
+ const m = d.match(/M\s*(-?[\d.]+)[,\s]+(-?[\d.]+)\s*L\s*(-?[\d.]+)[,\s]+(-?[\d.]+)/);
785
+ if (!m) continue;
786
+ wx1 = parseFloat(m[1]);
787
+ wy1 = parseFloat(m[2]);
788
+ wx2 = parseFloat(m[3]);
789
+ wy2 = parseFloat(m[4]);
790
+ } else {
791
+ wx1 = parseFloat(wall.attrs.x1 ?? "0");
792
+ wy1 = parseFloat(wall.attrs.y1 ?? "0");
793
+ wx2 = parseFloat(wall.attrs.x2 ?? "0");
794
+ wy2 = parseFloat(wall.attrs.y2 ?? "0");
795
+ }
796
+ const cx = wx1 + (wx2 - wx1) * position;
797
+ const cy = wy1 + (wy2 - wy1) * position;
798
+ const dx = wx2 - wx1;
799
+ const dy = wy2 - wy1;
800
+ const len = Math.sqrt(dx * dx + dy * dy);
801
+ if (len === 0) continue;
802
+ const ux = dx / len;
803
+ const uy = dy / len;
804
+ const halfW = width / 2;
805
+ const x1 = cx - ux * halfW;
806
+ const y1 = cy - uy * halfW;
807
+ const x2 = cx + ux * halfW;
808
+ const y2 = cy + uy * halfW;
809
+ const sw = tableName === "door" ? "0.08" : "0.06";
810
+ const markup = ` <line id="${row.id}" x1="${x1.toFixed(3)}" y1="${y1.toFixed(3)}" x2="${x2.toFixed(3)}" y2="${y2.toFixed(3)}" stroke="${color.stroke}" stroke-width="${sw}" />`;
811
+ results.push({
812
+ tableName,
813
+ svgMarkup: markup,
814
+ bounds: {
815
+ minX: Math.min(x1, x2),
816
+ minY: Math.min(y1, y2),
817
+ maxX: Math.max(x1, x2),
818
+ maxY: Math.max(y1, y2)
819
+ }
820
+ });
821
+ }
822
+ return results;
823
+ }
824
+ function renderSpaces(levelDir) {
825
+ const csvPath = join8(levelDir.path, "space.csv");
826
+ if (!existsSync7(csvPath)) return [];
827
+ const csv = readCsv(csvPath);
828
+ const color = COLORS.space ?? DEFAULT_COLOR;
829
+ const results = [];
830
+ for (const row of csv.rows) {
831
+ const x = parseFloat(row.x ?? "");
832
+ const y = parseFloat(row.y ?? "");
833
+ if (isNaN(x) || isNaN(y)) continue;
834
+ const name = row.name ?? row.id ?? "";
835
+ const r = 0.15;
836
+ let markup = ` <circle id="${row.id}" cx="${x.toFixed(3)}" cy="${y.toFixed(3)}" r="${r}" fill="${color.fill ?? "none"}" stroke="${color.stroke}" stroke-width="0.03" />`;
837
+ markup += `
838
+ <text x="${x.toFixed(3)}" y="${(-y).toFixed(3)}" font-size="0.4" fill="${color.stroke}" text-anchor="middle" dominant-baseline="central">${escapeXml(name)}</text>`;
839
+ results.push({
840
+ tableName: "space",
841
+ svgMarkup: markup,
842
+ bounds: { minX: x - 1, minY: y - 1, maxX: x + 1, maxY: y + 1 }
843
+ });
844
+ }
845
+ return results;
846
+ }
847
+ function renderLevel(projectDir, levelId) {
848
+ const layout = discoverLayout(projectDir);
849
+ const levelDir = layout.levelDirs.find((d) => d.name === levelId);
850
+ if (!levelDir) {
851
+ throw new Error(`Level "${levelId}" not found. Available: ${layout.levelDirs.map((d) => d.name).join(", ")}`);
852
+ }
853
+ const allElements = [];
854
+ const csvOnlyElements = [];
855
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
856
+ const wallElements = /* @__PURE__ */ new Map();
857
+ for (const tableName of RENDER_ORDER) {
858
+ if (CSV_ONLY_TABLES.has(tableName)) continue;
859
+ const svgName = SVG_FILE_NAMES[tableName];
860
+ if (!svgName) continue;
861
+ const svgPath = join8(levelDir.path, svgName + ".svg");
862
+ if (!existsSync7(svgPath)) continue;
863
+ const svg = parseSvgFile(svgPath);
864
+ for (const el of svg.elements) {
865
+ allElements.push({ tableName, el });
866
+ if (tableName === "wall") wallElements.set(el.id, el);
867
+ const b = elementBounds2(el);
868
+ if (b) {
869
+ minX = Math.min(minX, b.minX);
870
+ minY = Math.min(minY, b.minY);
871
+ maxX = Math.max(maxX, b.maxX);
872
+ maxY = Math.max(maxY, b.maxY);
873
+ }
874
+ }
875
+ }
876
+ for (const tableName of ["door", "window"]) {
877
+ csvOnlyElements.push(...renderHostedElements(levelDir, tableName, wallElements));
878
+ }
879
+ csvOnlyElements.push(...renderSpaces(levelDir));
880
+ for (const el of csvOnlyElements) {
881
+ minX = Math.min(minX, el.bounds.minX);
882
+ minY = Math.min(minY, el.bounds.minY);
883
+ maxX = Math.max(maxX, el.bounds.maxX);
884
+ maxY = Math.max(maxY, el.bounds.maxY);
885
+ }
886
+ if (allElements.length === 0 && csvOnlyElements.length === 0) {
887
+ return '<?xml version="1.0" encoding="utf-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">\n <text x="5" y="5" text-anchor="middle" font-size="1">No geometry found</text>\n</svg>';
888
+ }
889
+ const pad = Math.max(maxX - minX, maxY - minY) * 0.05;
890
+ const vbX = minX - pad;
891
+ const vbY = -(maxY + pad);
892
+ const vbW = maxX - minX + 2 * pad;
893
+ const vbH = maxY - minY + 2 * pad;
894
+ const parts = [
895
+ '<?xml version="1.0" encoding="utf-8"?>',
896
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vbX.toFixed(3)} ${vbY.toFixed(3)} ${vbW.toFixed(3)} ${vbH.toFixed(3)}">`,
897
+ ` <rect x="${vbX.toFixed(3)}" y="${vbY.toFixed(3)}" width="${vbW.toFixed(3)}" height="${vbH.toFixed(3)}" fill="white" />`,
898
+ ' <g transform="scale(1,-1)">'
899
+ ];
900
+ for (const { tableName, el } of allElements) {
901
+ const line = renderElement(el, tableName);
902
+ if (line) parts.push(line);
903
+ }
904
+ for (const el of csvOnlyElements) {
905
+ parts.push(el.svgMarkup);
906
+ }
907
+ parts.push(" </g>");
908
+ parts.push("</svg>");
909
+ return parts.join("\n");
910
+ }
911
+ var COLORS, DEFAULT_COLOR, OVERRIDE_ATTRS, RENDER_ORDER, CSV_ONLY_TABLES;
912
+ var init_render = __esm({
913
+ "src/render.ts"() {
914
+ "use strict";
915
+ init_fs();
916
+ init_csv();
917
+ init_svg();
918
+ init_registry();
919
+ COLORS = {
920
+ wall: { stroke: "#1a1a2e" },
921
+ structure_wall: { stroke: "#4a4e69" },
922
+ column: { stroke: "#2b2d42", fill: "#2b2d42" },
923
+ structure_column: { stroke: "#6c757d", fill: "#6c757d" },
924
+ slab: { stroke: "#adb5bd", fill: "rgba(173,181,189,0.2)" },
925
+ structure_slab: { stroke: "#868e96", fill: "rgba(134,142,150,0.2)" },
926
+ space: { stroke: "#3a86ff", fill: "rgba(58,134,255,0.15)" },
927
+ room_separator: { stroke: "#adb5bd" },
928
+ door: { stroke: "#e63946" },
929
+ window: { stroke: "#2a9d8f" },
930
+ stair: { stroke: "#f4a261", fill: "rgba(244,162,97,0.2)" },
931
+ beam: { stroke: "#9b5de5" },
932
+ duct: { stroke: "#00b4d8" },
933
+ pipe: { stroke: "#48bfe3" },
934
+ cable_tray: { stroke: "#90be6d" },
935
+ conduit: { stroke: "#43aa8b" },
936
+ equipment: { stroke: "#f94144", fill: "rgba(249,65,68,0.15)" },
937
+ terminal: { stroke: "#f3722c", fill: "rgba(243,114,44,0.15)" }
938
+ };
939
+ DEFAULT_COLOR = { stroke: "#666" };
940
+ OVERRIDE_ATTRS = /* @__PURE__ */ new Set(["stroke", "fill", "stroke-width", "stroke-linecap"]);
941
+ RENDER_ORDER = [
942
+ "slab",
943
+ "structure_slab",
944
+ "wall",
945
+ "structure_wall",
946
+ "room_separator",
947
+ "column",
948
+ "structure_column",
949
+ "beam",
950
+ "brace",
951
+ "stair",
952
+ "duct",
953
+ "pipe",
954
+ "cable_tray",
955
+ "conduit",
956
+ "equipment",
957
+ "terminal",
958
+ "door",
959
+ "window",
960
+ "space"
961
+ ];
962
+ CSV_ONLY_TABLES = /* @__PURE__ */ new Set(["door", "window", "space"]);
963
+ }
964
+ });
965
+
665
966
  // src/commands/resolve-topology.ts
666
967
  var resolve_topology_exports = {};
667
968
  __export(resolve_topology_exports, {
668
969
  resolveTopology: () => resolveTopology
669
970
  });
670
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
671
- import { join as join8 } from "path";
971
+ import { existsSync as existsSync8, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
972
+ import { join as join9 } from "path";
672
973
  function dist3d(a, b) {
673
974
  const dx = a.x - b.x;
674
975
  const dy = a.y - b.y;
@@ -695,14 +996,14 @@ function resolveTopology(dir) {
695
996
  let skippedStart = 0;
696
997
  let skippedEnd = 0;
697
998
  for (const d of allDirs) {
698
- if (!existsSync6(d.path)) continue;
999
+ if (!existsSync8(d.path)) continue;
699
1000
  const files = listFiles(d.path);
700
1001
  for (const tableName of CURVE_TABLES) {
701
1002
  if (!files.includes(`${tableName}.csv`)) continue;
702
1003
  const svgName = SVG_FILE_NAMES[tableName];
703
1004
  if (!svgName || !files.includes(`${svgName}.svg`)) continue;
704
- const csvPath = join8(d.path, `${tableName}.csv`);
705
- const svgPath = join8(d.path, `${svgName}.svg`);
1005
+ const csvPath = join9(d.path, `${tableName}.csv`);
1006
+ const svgPath = join9(d.path, `${svgName}.svg`);
706
1007
  const csv = readCsv(csvPath);
707
1008
  const key = `${d.name}/${tableName}`;
708
1009
  curveData.set(key, { csv, path: csvPath });
@@ -752,14 +1053,14 @@ function resolveTopology(dir) {
752
1053
  }
753
1054
  const nodes = [];
754
1055
  for (const d of allDirs) {
755
- if (!existsSync6(d.path)) continue;
1056
+ if (!existsSync8(d.path)) continue;
756
1057
  const files = listFiles(d.path);
757
1058
  for (const tableName of NODE_TABLES) {
758
1059
  if (!files.includes(`${tableName}.csv`)) continue;
759
1060
  const svgName = SVG_FILE_NAMES[tableName];
760
1061
  if (!svgName || !files.includes(`${svgName}.svg`)) continue;
761
- const csvPath = join8(d.path, `${tableName}.csv`);
762
- const svgPath = join8(d.path, `${svgName}.svg`);
1062
+ const csvPath = join9(d.path, `${tableName}.csv`);
1063
+ const svgPath = join9(d.path, `${svgName}.svg`);
763
1064
  const csv = readCsv(csvPath);
764
1065
  let svgElements;
765
1066
  try {
@@ -854,12 +1155,12 @@ function resolveTopology(dir) {
854
1155
  newNodesByLevel.set(j.levelDir, arr);
855
1156
  }
856
1157
  for (const [levelDir, levelJunctions] of newNodesByLevel) {
857
- const dirPath = levelDir === "global" ? layout.globalDir : join8(dir, levelDir);
858
- if (!existsSync6(dirPath)) mkdirSync2(dirPath, { recursive: true });
859
- const csvPath = join8(dirPath, "mep_node.csv");
860
- const svgPath = join8(dirPath, "mep_node.svg");
1158
+ const dirPath = levelDir === "global" ? layout.globalDir : join9(dir, levelDir);
1159
+ if (!existsSync8(dirPath)) mkdirSync2(dirPath, { recursive: true });
1160
+ const csvPath = join9(dirPath, "mep_node.csv");
1161
+ const svgPath = join9(dirPath, "mep_node.svg");
861
1162
  let csv;
862
- if (existsSync6(csvPath)) {
1163
+ if (existsSync8(csvPath)) {
863
1164
  csv = readCsv(csvPath);
864
1165
  } else {
865
1166
  csv = { headers: ["id", "number", "base_offset", "system_type"], rows: [] };
@@ -868,7 +1169,7 @@ function resolveTopology(dir) {
868
1169
  if (!csv.headers.includes(h)) csv.headers.push(h);
869
1170
  }
870
1171
  let existingSvgElements = [];
871
- if (existsSync6(svgPath)) {
1172
+ if (existsSync8(svgPath)) {
872
1173
  try {
873
1174
  existingSvgElements = parseSvgFile(svgPath).elements;
874
1175
  } catch {
@@ -989,8 +1290,8 @@ var merge_exports = {};
989
1290
  __export(merge_exports, {
990
1291
  merge: () => merge
991
1292
  });
992
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
993
- import { join as join9, basename as basename2 } from "path";
1293
+ import { existsSync as existsSync9, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
1294
+ import { join as join10, basename as basename2 } from "path";
994
1295
  async function merge(dirs, outputDir) {
995
1296
  const registry = buildRegistry(getSpecDir());
996
1297
  console.log(`Scanning ${dirs.length} sources...`);
@@ -1000,10 +1301,10 @@ async function merge(dirs, outputDir) {
1000
1301
  const { canonicalGrids, gridRemaps } = deduplicateGrids(sources);
1001
1302
  console.log(`Merged grids: ${canonicalGrids.rows.length} unique grids`);
1002
1303
  const fullRemaps = buildFullRemaps(sources, levelRemaps, gridRemaps, registry);
1003
- mkdirSync3(join9(outputDir, "global"), { recursive: true });
1004
- writeCsv(join9(outputDir, "global", "level.csv"), canonicalLevels);
1304
+ mkdirSync3(join10(outputDir, "global"), { recursive: true });
1305
+ writeCsv(join10(outputDir, "global", "level.csv"), canonicalLevels);
1005
1306
  if (canonicalGrids.rows.length > 0) {
1006
- writeCsv(join9(outputDir, "global", "grid.csv"), canonicalGrids);
1307
+ writeCsv(join10(outputDir, "global", "grid.csv"), canonicalGrids);
1007
1308
  }
1008
1309
  writeIdMap(outputDir, sources, fullRemaps);
1009
1310
  const levelDirMap = buildLevelDirMap(sources, fullRemaps);
@@ -1014,26 +1315,26 @@ async function merge(dirs, outputDir) {
1014
1315
  function scanSource(dir, registry) {
1015
1316
  const layout = discoverLayout(dir);
1016
1317
  const name = basename2(dir);
1017
- const levelPath = join9(layout.globalDir, "level.csv");
1018
- if (!existsSync7(levelPath)) {
1318
+ const levelPath = join10(layout.globalDir, "level.csv");
1319
+ if (!existsSync9(levelPath)) {
1019
1320
  throw new Error(`Missing level.csv in ${dir}/global/`);
1020
1321
  }
1021
1322
  const levels = readCsv(levelPath);
1022
- const gridPath = join9(layout.globalDir, "grid.csv");
1023
- const grids = existsSync7(gridPath) ? readCsv(gridPath) : null;
1024
- const idMapPath = join9(layout.globalDir, "_IdMap.csv");
1025
- const idMap = existsSync7(idMapPath) ? readCsv(idMapPath) : null;
1323
+ const gridPath = join10(layout.globalDir, "grid.csv");
1324
+ const grids = existsSync9(gridPath) ? readCsv(gridPath) : null;
1325
+ const idMapPath = join10(layout.globalDir, "_IdMap.csv");
1326
+ const idMap = existsSync9(idMapPath) ? readCsv(idMapPath) : null;
1026
1327
  const globalData = /* @__PURE__ */ new Map();
1027
- if (existsSync7(layout.globalDir)) {
1328
+ if (existsSync9(layout.globalDir)) {
1028
1329
  for (const f of listFiles(layout.globalDir)) {
1029
1330
  if (!f.endsWith(".csv")) continue;
1030
1331
  const tableName = f.replace(".csv", "");
1031
1332
  if (tableName === "level" || tableName === "grid" || tableName === "_IdMap") continue;
1032
1333
  if (!registry.has(tableName)) continue;
1033
- const csv = readCsv(join9(layout.globalDir, f));
1334
+ const csv = readCsv(join10(layout.globalDir, f));
1034
1335
  const svgName = SVG_FILE_NAMES[tableName];
1035
- const svgFile = svgName ? join9(layout.globalDir, svgName + ".svg") : null;
1036
- globalData.set(tableName, { csv, svgFile: svgFile && existsSync7(svgFile) ? svgFile : null });
1336
+ const svgFile = svgName ? join10(layout.globalDir, svgName + ".svg") : null;
1337
+ globalData.set(tableName, { csv, svgFile: svgFile && existsSync9(svgFile) ? svgFile : null });
1037
1338
  }
1038
1339
  }
1039
1340
  const levelData = /* @__PURE__ */ new Map();
@@ -1043,10 +1344,10 @@ function scanSource(dir, registry) {
1043
1344
  if (!f.endsWith(".csv")) continue;
1044
1345
  const tableName = f.replace(".csv", "");
1045
1346
  if (!registry.has(tableName)) continue;
1046
- const csv = readCsv(join9(ld.path, f));
1347
+ const csv = readCsv(join10(ld.path, f));
1047
1348
  const svgName = SVG_FILE_NAMES[tableName];
1048
- const svgFile = svgName ? join9(ld.path, svgName + ".svg") : null;
1049
- tables.set(tableName, { csv, svgFile: svgFile && existsSync7(svgFile) ? svgFile : null });
1349
+ const svgFile = svgName ? join10(ld.path, svgName + ".svg") : null;
1350
+ tables.set(tableName, { csv, svgFile: svgFile && existsSync9(svgFile) ? svgFile : null });
1050
1351
  }
1051
1352
  if (tables.size > 0) {
1052
1353
  levelData.set(ld.name, tables);
@@ -1233,7 +1534,7 @@ function writeIdMap(outputDir, sources, remaps) {
1233
1534
  }
1234
1535
  }
1235
1536
  if (rows.length > 0) {
1236
- writeCsv(join9(outputDir, "global", "_IdMap.csv"), { headers: ["id", "uuid"], rows });
1537
+ writeCsv(join10(outputDir, "global", "_IdMap.csv"), { headers: ["id", "uuid"], rows });
1237
1538
  }
1238
1539
  }
1239
1540
  function buildLevelDirMap(sources, remaps) {
@@ -1274,13 +1575,13 @@ function writeGlobalTables(outputDir, sources, remaps, registry) {
1274
1575
  }
1275
1576
  for (const [tableName, entry] of merged) {
1276
1577
  if (entry.rows.length > 0) {
1277
- writeCsv(join9(outputDir, "global", tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1578
+ writeCsv(join10(outputDir, "global", tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1278
1579
  }
1279
1580
  if (entry.svgInputs.length > 0) {
1280
1581
  const svgName = SVG_FILE_NAMES[tableName];
1281
1582
  if (svgName) {
1282
1583
  const content = writeMergedSvg(entry.svgInputs);
1283
- writeFileSync3(join9(outputDir, "global", svgName + ".svg"), content, "utf-8");
1584
+ writeFileSync3(join10(outputDir, "global", svgName + ".svg"), content, "utf-8");
1284
1585
  }
1285
1586
  }
1286
1587
  }
@@ -1312,17 +1613,17 @@ function writeLevelTables(outputDir, sources, remaps, levelDirMap, registry) {
1312
1613
  }
1313
1614
  }
1314
1615
  for (const [outDirName, tables] of merged) {
1315
- const dirPath = join9(outputDir, outDirName);
1616
+ const dirPath = join10(outputDir, outDirName);
1316
1617
  mkdirSync3(dirPath, { recursive: true });
1317
1618
  for (const [tableName, entry] of tables) {
1318
1619
  if (entry.rows.length > 0) {
1319
- writeCsv(join9(dirPath, tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1620
+ writeCsv(join10(dirPath, tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1320
1621
  }
1321
1622
  if (entry.svgInputs.length > 0) {
1322
1623
  const svgName = SVG_FILE_NAMES[tableName];
1323
1624
  if (svgName) {
1324
1625
  const content = writeMergedSvg(entry.svgInputs);
1325
- writeFileSync3(join9(dirPath, svgName + ".svg"), content, "utf-8");
1626
+ writeFileSync3(join10(dirPath, svgName + ".svg"), content, "utf-8");
1326
1627
  }
1327
1628
  }
1328
1629
  }
@@ -1349,21 +1650,327 @@ var init_merge = __esm({
1349
1650
  }
1350
1651
  });
1351
1652
 
1653
+ // src/commands/init.ts
1654
+ var init_exports = {};
1655
+ __export(init_exports, {
1656
+ initProject: () => initProject
1657
+ });
1658
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync4, existsSync as existsSync10 } from "fs";
1659
+ import { join as join11 } from "path";
1660
+ function initProject(absDir) {
1661
+ if (!existsSync10(absDir)) {
1662
+ mkdirSync4(absDir, { recursive: true });
1663
+ }
1664
+ writeFileSync4(join11(absDir, ".bimdown"), "", "utf-8");
1665
+ const globalDir = join11(absDir, "global");
1666
+ if (!existsSync10(globalDir)) {
1667
+ mkdirSync4(globalDir, { recursive: true });
1668
+ }
1669
+ const levelCsvPath = join11(globalDir, "level.csv");
1670
+ if (!existsSync10(levelCsvPath)) {
1671
+ writeFileSync4(levelCsvPath, "id,name,elevation\nlv-1,Level 1,0.0\n", "utf-8");
1672
+ }
1673
+ const gridCsvPath = join11(globalDir, "grid.csv");
1674
+ if (!existsSync10(gridCsvPath)) {
1675
+ const gridContent = [
1676
+ "id,name,role,start_x,start_y,end_x,end_y",
1677
+ "gr-1,A,primary,-10000,0,10000,0",
1678
+ "gr-2,1,primary,0,-10000,0,10000"
1679
+ ].join("\n") + "\n";
1680
+ writeFileSync4(gridCsvPath, gridContent, "utf-8");
1681
+ }
1682
+ console.log(`Initialized empty BimDown project at ${absDir}`);
1683
+ console.log("Created:");
1684
+ console.log(" - global/level.csv (lv-1)");
1685
+ console.log(" - global/grid.csv (A, 1)");
1686
+ }
1687
+ var init_init = __esm({
1688
+ "src/commands/init.ts"() {
1689
+ "use strict";
1690
+ }
1691
+ });
1692
+
1693
+ // src/commands/diff.ts
1694
+ var diff_exports = {};
1695
+ __export(diff_exports, {
1696
+ diffProjects: () => diffProjects
1697
+ });
1698
+ import { existsSync as existsSync11 } from "fs";
1699
+ import { join as join12 } from "path";
1700
+ function diffProjects(dirA, dirB) {
1701
+ if (!existsSync11(dirA)) {
1702
+ console.error(`Directory not found: ${dirA}`);
1703
+ process.exitCode = 1;
1704
+ return;
1705
+ }
1706
+ if (!existsSync11(dirB)) {
1707
+ console.error(`Directory not found: ${dirB}`);
1708
+ process.exitCode = 1;
1709
+ return;
1710
+ }
1711
+ const layoutA = discoverLayout(dirA);
1712
+ const layoutB = discoverLayout(dirB);
1713
+ const pathsA = [
1714
+ { name: "global", abs: layoutA.globalDir },
1715
+ ...layoutA.levelDirs.map((d) => ({ name: d.name, abs: d.path }))
1716
+ ];
1717
+ const pathsB = [
1718
+ { name: "global", abs: layoutB.globalDir },
1719
+ ...layoutB.levelDirs.map((d) => ({ name: d.name, abs: d.path }))
1720
+ ];
1721
+ const allPathNames = /* @__PURE__ */ new Set([...pathsA.map((p) => p.name), ...pathsB.map((p) => p.name)]);
1722
+ for (const pathName of allPathNames) {
1723
+ const dirAAbs = pathsA.find((p) => p.name === pathName)?.abs;
1724
+ const dirBAbs = pathsB.find((p) => p.name === pathName)?.abs;
1725
+ const filesA = new Set(dirAAbs && existsSync11(dirAAbs) ? listFiles(dirAAbs).filter((f) => f.endsWith(".csv")) : []);
1726
+ const filesB = new Set(dirBAbs && existsSync11(dirBAbs) ? listFiles(dirBAbs).filter((f) => f.endsWith(".csv")) : []);
1727
+ const allFiles = /* @__PURE__ */ new Set([...filesA, ...filesB]);
1728
+ let printedPathHeader = false;
1729
+ for (const f of allFiles) {
1730
+ const tableName = f.replace(".csv", "");
1731
+ const pathFileA = dirAAbs ? join12(dirAAbs, f) : null;
1732
+ const pathFileB = dirBAbs ? join12(dirBAbs, f) : null;
1733
+ const rowsA = {};
1734
+ const rowsB = {};
1735
+ if (pathFileA && existsSync11(pathFileA)) {
1736
+ for (const row of readCsv(pathFileA).rows) {
1737
+ if (row.id) rowsA[String(row.id)] = row;
1738
+ }
1739
+ }
1740
+ if (pathFileB && existsSync11(pathFileB)) {
1741
+ for (const row of readCsv(pathFileB).rows) {
1742
+ if (row.id) rowsB[String(row.id)] = row;
1743
+ }
1744
+ }
1745
+ const allIds = /* @__PURE__ */ new Set([...Object.keys(rowsA), ...Object.keys(rowsB)]);
1746
+ const diffs = [];
1747
+ for (const id of allIds) {
1748
+ if (!rowsA[id] && rowsB[id]) {
1749
+ diffs.push({ sign: "+", id });
1750
+ } else if (rowsA[id] && !rowsB[id]) {
1751
+ diffs.push({ sign: "-", id });
1752
+ } else {
1753
+ if (JSON.stringify(rowsA[id]) !== JSON.stringify(rowsB[id])) {
1754
+ diffs.push({ sign: "~", id });
1755
+ }
1756
+ }
1757
+ }
1758
+ if (diffs.length > 0) {
1759
+ if (!printedPathHeader) {
1760
+ console.log(`
1761
+ \u{1F4C1} ${pathName}`);
1762
+ printedPathHeader = true;
1763
+ }
1764
+ console.log(` == ${tableName} ==`);
1765
+ for (const d of diffs) {
1766
+ console.log(` ${d.sign} ${d.id}`);
1767
+ }
1768
+ }
1769
+ }
1770
+ }
1771
+ console.log();
1772
+ }
1773
+ var init_diff = __esm({
1774
+ "src/commands/diff.ts"() {
1775
+ "use strict";
1776
+ init_fs();
1777
+ init_csv();
1778
+ }
1779
+ });
1780
+
1781
+ // src/commands/generate-skill.ts
1782
+ var generate_skill_exports = {};
1783
+ __export(generate_skill_exports, {
1784
+ generateSkill: () => generateSkill
1785
+ });
1786
+ import { existsSync as existsSync12, mkdirSync as mkdirSync5, writeFileSync as writeFileSync5, readFileSync as readFileSync5 } from "fs";
1787
+ import { join as join13, resolve } from "path";
1788
+ function generateSkill(outputDir) {
1789
+ const specDir = getSpecDir();
1790
+ const csvSchemaDir = join13(specDir, "csv-schema");
1791
+ const registry = buildRegistry(specDir);
1792
+ const schemas = loadAllSchemas(csvSchemaDir);
1793
+ const sortedNames = [...registry.keys()].sort();
1794
+ const allTableNames = sortedNames.map((t) => "`" + t + "`").join(", ");
1795
+ const FREEFORM_ID_TABLES = /* @__PURE__ */ new Set(["grid", "level"]);
1796
+ const globalOnlyList = [...GLOBAL_ONLY_TABLES].map((t) => `\`${t}.csv\``).join(", ");
1797
+ const idExamples = Object.entries(ID_PREFIXES).map(([table, prefix]) => {
1798
+ const example = FREEFORM_ID_TABLES.has(table) ? `${table}: \`${prefix}-\` + any string (e.g. \`${prefix}-1\`, \`${prefix}-A\`, \`${prefix}-B2\`)` : `${table} \u2192 \`${prefix}-{n}\``;
1799
+ return example;
1800
+ });
1801
+ const freeformExamples = idExamples.filter((_, i) => FREEFORM_ID_TABLES.has(Object.keys(ID_PREFIXES)[i]));
1802
+ const numericExamples = idExamples.filter((_, i) => !FREEFORM_ID_TABLES.has(Object.keys(ID_PREFIXES)[i]));
1803
+ const today = /* @__PURE__ */ new Date();
1804
+ const publishDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
1805
+ const cliVersion = true ? "0.1.9" : "unknown";
1806
+ let md = `---
1807
+ name: bimdown
1808
+ description: Powerful structural and topological manipulation tool for BimDown architectural BIM projects. Use when asked to query building elements, build new structures (CSV+SVG), resolve MEP topologies, or analyze spatial BIM data.
1809
+ ---
1810
+
1811
+ # BimDown Agent Skill & Schema Rules
1812
+
1813
+ > **Version ${cliVersion}** (published ${publishDate}). If this date is more than 1 week ago, run \`npm update -g bimdown-cli\` to update, then re-download this SKILL.md from https://raw.githubusercontent.com/NovaShang/BimDown/main/agent-skill/SKILL.md
1814
+
1815
+ You are an AI Coder operating within a BimDown project environment.
1816
+ BimDown is an open-source, AI-native building data format using CSV for semantics and SVG for geometry.
1817
+
1818
+ ## Core Architecture & Base Concepts
1819
+
1820
+ - **Global Unit is METERS**: All coordinates, widths, and structural attributes in CSV/SVG MUST strictly use METERS. BimDown simulates real-world dimensions.
1821
+ - **Computed Fields are READ-ONLY**: Any field marked with \`computed: true\` (or listed in \`virtual_fields\`) is automatically calculated by the CLI. **DO NOT** write these fields to CSV files. You can retrieve their values using \`bimdown query\`.
1822
+ - **Dual Nature**: Properties live in \`{name}.csv\`. 2D geometry lives in a sibling \`{name}.svg\` file. The \`id\` fields across both must match perfectly.
1823
+ - **SVG-derived virtual columns**: When you write geometry in SVG, the CLI automatically computes these fields for \`bimdown query\` \u2014 do NOT write them to CSV:
1824
+ - Line elements (wall, beam, pipe, etc.): \`length\`, \`start_x\`, \`start_y\`, \`end_x\`, \`end_y\`
1825
+ - Polygon elements (slab, roof, etc.): \`area\`, \`perimeter\`
1826
+ - All elements: \`level_id\` (inferred from folder name, e.g. \`lv-1/\` \u2192 \`lv-1\`)
1827
+ - **Concrete Example of CSV+SVG Linked State**:
1828
+ > \`lv-1/wall.csv\` (note: NO \`level_id\` column \u2014 it is auto-inferred):
1829
+ > \`id,thickness,material\`
1830
+ > \`w-1,0.2,concrete\`
1831
+ >
1832
+ > \`lv-1/wall.svg\`:
1833
+ > \`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -10 10 10"> <g transform="scale(1,-1)"> <path id="w-1" d="M 0 0 L 10 0" stroke-width="0.2" /> </g> </svg>\`
1834
+ >
1835
+ > After this, \`bimdown query . "SELECT id, length, level_id FROM wall"\` returns \`w-1, 10.0, lv-1\` \u2014 both \`length\` and \`level_id\` are computed automatically.
1836
+
1837
+ ## Project Directory Structure
1838
+
1839
+ \`\`\`
1840
+ project/
1841
+ project_metadata.json # project root marker (format version, name, units)
1842
+ global/ # global-only files \u2014 MUST be here, NOT in lv-N/
1843
+ ${[...GLOBAL_ONLY_TABLES].sort().map((t) => t + ".csv").join("\n ")}
1844
+ lv-1/ # per-level files
1845
+ wall.csv + wall.svg # elements with geometry have paired CSV+SVG
1846
+ door.csv # hosted elements are CSV-only (parametric position on host wall)
1847
+ space.csv # spaces are CSV-only (seed point, boundary auto-derived)
1848
+ ...
1849
+ lv-2/
1850
+ ...
1851
+ \`\`\`
1852
+
1853
+ **Key rules**:
1854
+ - ${globalOnlyList} MUST live in \`global/\`, never in \`lv-N/\` directories
1855
+ - Per-level elements (wall, door, slab, space, etc.) go in \`lv-N/\` directories
1856
+ - The folder name (e.g. \`lv-1\`) becomes the element's \`level_id\` \u2014 do NOT write \`level_id\` to CSV
1857
+
1858
+ ## CLI Tools & Best Practices
1859
+
1860
+ 1. **\`bimdown query <dir> <sql> --json\`**: Runs DuckDB SQL across all tables, including SVG-derived virtual columns.
1861
+ - **Example**: \`bimdown query ./proj "SELECT id, length FROM wall WHERE length > 5.0" --json\`
1862
+ 2. **\`bimdown render <dir> [-l level] [-o output.svg]\`**: Renders a level into a visual blueprint SVG. Use this after modifying geometry to visually verify the result.
1863
+ 3. **\`bimdown validate <dir>\`**: Validates the project directory against schema constraints. **Run this EVERY TIME after modifying CSV or SVG files** to catch ID format, reference, and structure errors early!
1864
+ 4. **\`bimdown schema [table]\`**: Prints the full schema for any element type. Use this to look up fields before creating elements.
1865
+ 5. **\`bimdown diff <dirA> <dirB>\`**: Emits a \`+\`, \`-\`, \`~\` structural difference between project snapshots.
1866
+ 6. **\`bimdown init <dir>\`**: Creates a new empty BimDown project with the correct directory structure.
1867
+
1868
+ ## Critical File & Geometry Rules
1869
+
1870
+ - **ID format**:
1871
+ - **Grid and Level** allow any string after prefix: ${freeformExamples.join("; ")}
1872
+ - **All other elements** use \`{prefix}-{number}\` (digits only): ${numericExamples.slice(0, 6).join(", ")}, ...
1873
+ - **Always run \`bimdown validate\` to confirm your IDs are compliant.**
1874
+ - **SVG Coordinate Y-Flip**: All geometry inside \`.svg\` files **MUST** be wrapped in a Y-axis flip group: \`<g transform="scale(1,-1)"> ... </g>\`. This ensures the 2D SVG matches the right-handed BIM coordinate system.
1875
+ - **CSV vs Computed Fields**: Only write fields that are NOT marked as computed. Specifically, \`level_id\`, \`length\`, \`area\`, \`start_x/y\`, \`end_x/y\`, \`perimeter\`, \`volume\`, \`bbox_*\` are all auto-computed \u2014 never write them to CSV.
1876
+
1877
+ ## Base Schema Definitions
1878
+
1879
+ These abstract schemas provide common fields for concrete tables below.
1880
+
1881
+ `;
1882
+ for (const baseName of Array.from(BASE_SCHEMAS).sort()) {
1883
+ const filePath = findSchemaFile(csvSchemaDir, baseName);
1884
+ if (filePath) {
1885
+ md += `### Base: \`${baseName}\`
1886
+ \`\`\`yaml
1887
+ ${readFileSync5(filePath, "utf-8").trim()}
1888
+ \`\`\`
1889
+
1890
+ `;
1891
+ }
1892
+ }
1893
+ md += `## Core Schema Topologies (Concrete Tables)
1894
+
1895
+ Below is a curated whitelist of the **most commonly used** core architectural elements.
1896
+
1897
+ > **IMPORTANT**: The complete list of available elements in this project is:
1898
+ > ${allTableNames}
1899
+ >
1900
+ > If the user asks you to modify or generate elements not listed below, **RUN** \`bimdown schema <table_name>\` to fetch their requirements!
1901
+
1902
+ `;
1903
+ for (const name of sortedNames) {
1904
+ if (!CORE_TABLES.has(name)) continue;
1905
+ const table = registry.get(name);
1906
+ const hasSVG = TABLES_WITH_SVG.has(name);
1907
+ const filePath = findSchemaFile(csvSchemaDir, name);
1908
+ if (filePath) {
1909
+ md += `### Table: \`${table.name}\` (Prefix: \`${table.prefix}\`)
1910
+ `;
1911
+ md += `- **Geometry**: ${hasSVG ? "SVG required" : "CSV only"}
1912
+ `;
1913
+ md += `\`\`\`yaml
1914
+ `;
1915
+ md += `id_prefix: ${table.prefix}
1916
+ `;
1917
+ md += `${readFileSync5(filePath, "utf-8").trim()}
1918
+ `;
1919
+ const computedFields = table.allFields.filter((f) => f.computed || f.name === "level_id").map((f) => f.name);
1920
+ if (computedFields.length > 0) {
1921
+ md += `
1922
+ virtual_fields: [${computedFields.join(", ")}]
1923
+ `;
1924
+ }
1925
+ md += `\`\`\`
1926
+
1927
+ `;
1928
+ }
1929
+ }
1930
+ const rootDir = outputDir ? resolve(outputDir) : process.cwd();
1931
+ const dirPath = join13(rootDir, "agent-skill");
1932
+ if (!existsSync12(dirPath)) mkdirSync5(dirPath, { recursive: true });
1933
+ const outPath = join13(dirPath, "SKILL.md");
1934
+ writeFileSync5(outPath, md, "utf-8");
1935
+ console.log(`\u2705 Agent Skill documentation successfully generated at: ${outPath}`);
1936
+ }
1937
+ function findSchemaFile(baseDir, schemaName) {
1938
+ const dirs = [baseDir, join13(baseDir, "architecture"), join13(baseDir, "mep"), join13(baseDir, "structure"), join13(baseDir, "base")];
1939
+ for (const d of dirs) {
1940
+ if (!existsSync12(d)) continue;
1941
+ const p1 = join13(d, `${schemaName}.yaml`);
1942
+ if (existsSync12(p1)) return p1;
1943
+ const p2 = join13(d, `${schemaName}.yml`);
1944
+ if (existsSync12(p2)) return p2;
1945
+ }
1946
+ return null;
1947
+ }
1948
+ var CORE_TABLES, BASE_SCHEMAS;
1949
+ var init_generate_skill = __esm({
1950
+ "src/commands/generate-skill.ts"() {
1951
+ "use strict";
1952
+ init_registry();
1953
+ init_loader();
1954
+ CORE_TABLES = /* @__PURE__ */ new Set(["level", "grid", "wall", "door", "window", "space"]);
1955
+ BASE_SCHEMAS = /* @__PURE__ */ new Set(["element", "hosted_element", "materialized", "vertical_span", "line_element", "point_element", "polygon_element"]);
1956
+ }
1957
+ });
1958
+
1352
1959
  // src/index.ts
1353
1960
  import { Command } from "commander";
1354
- import { resolve } from "path";
1961
+ import { resolve as resolve2 } from "path";
1355
1962
 
1356
1963
  // src/validate/index.ts
1357
1964
  init_registry();
1358
1965
  init_fs();
1359
1966
  init_csv();
1360
- import { existsSync as existsSync3 } from "fs";
1967
+ import { existsSync as existsSync4 } from "fs";
1361
1968
  import { join as join5 } from "path";
1362
1969
 
1363
1970
  // src/validate/structure.ts
1364
1971
  init_fs();
1365
1972
  init_registry();
1366
- import { existsSync as existsSync2, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
1973
+ import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
1367
1974
  import { join as join4, extname } from "path";
1368
1975
  var OPTIONAL_SVG_TABLES = /* @__PURE__ */ new Set(["opening"]);
1369
1976
  var KNOWN_CSV_NAMES = new Set(Object.keys(ID_PREFIXES).map((t) => `${t}.csv`));
@@ -1372,7 +1979,7 @@ var KNOWN_GLOBAL_EXTRAS = /* @__PURE__ */ new Set(["_IdMap.csv"]);
1372
1979
  function validateStructure(dir) {
1373
1980
  const issues = [];
1374
1981
  const layout = discoverLayout(dir);
1375
- if (!existsSync2(layout.globalDir)) {
1982
+ if (!existsSync3(layout.globalDir)) {
1376
1983
  issues.push("global/ missing global/ directory");
1377
1984
  return issues;
1378
1985
  }
@@ -1443,7 +2050,7 @@ function validateStructure(dir) {
1443
2050
  issues.push(`${f} unexpected entry in project root \u2014 only global/ and lv-{n}/ directories are allowed`);
1444
2051
  }
1445
2052
  const metadataPath = join4(dir, "project_metadata.json");
1446
- if (existsSync2(metadataPath)) {
2053
+ if (existsSync3(metadataPath)) {
1447
2054
  try {
1448
2055
  const raw = readFileSync3(metadataPath, "utf-8");
1449
2056
  const metadata = JSON.parse(raw);
@@ -1521,9 +2128,12 @@ function validateIdFormat(path, table, data) {
1521
2128
  for (let i = 0; i < data.rows.length; i++) {
1522
2129
  const id = data.rows[i].id;
1523
2130
  if (!id) continue;
1524
- const regex = new RegExp(`^${prefix}-\\d+$`);
2131
+ const freeformTables = /* @__PURE__ */ new Set(["grid", "level"]);
2132
+ const pattern = freeformTables.has(table.name) ? `^${prefix}-.+$` : `^${prefix}-\\d+$`;
2133
+ const regex = new RegExp(pattern);
1525
2134
  if (!regex.test(id)) {
1526
- issues.push(`${path}:${i + 2} id "${id}" has wrong format, expected "${prefix}-{n}"`);
2135
+ const expected = freeformTables.has(table.name) ? `"${prefix}-{name}"` : `"${prefix}-{n}"`;
2136
+ issues.push(`${path}:${i + 2} id "${id}" has wrong format, expected ${expected}`);
1527
2137
  }
1528
2138
  }
1529
2139
  return issues;
@@ -1763,7 +2373,7 @@ function validate(dir) {
1763
2373
  ...layout.levelDirs
1764
2374
  ];
1765
2375
  for (const d of allDirs) {
1766
- if (!existsSync3(d.path)) continue;
2376
+ if (!existsSync4(d.path)) continue;
1767
2377
  const files = listFiles(d.path);
1768
2378
  for (const f of files) {
1769
2379
  if (!f.endsWith(".csv")) continue;
@@ -1818,7 +2428,7 @@ function validate(dir) {
1818
2428
  }
1819
2429
  }
1820
2430
  for (const d of allDirs) {
1821
- if (!existsSync3(d.path) || d.name === "global") continue;
2431
+ if (!existsSync4(d.path) || d.name === "global") continue;
1822
2432
  const files = listFiles(d.path);
1823
2433
  for (const f of files) {
1824
2434
  if (!f.endsWith(".svg")) continue;
@@ -1852,12 +2462,12 @@ function validate(dir) {
1852
2462
  init_registry();
1853
2463
  init_fs();
1854
2464
  init_csv();
1855
- import { existsSync as existsSync8 } from "fs";
1856
- import { join as join10 } from "path";
2465
+ import { existsSync as existsSync13, writeFileSync as writeFileSync6 } from "fs";
2466
+ import { join as join14 } from "path";
1857
2467
  var program = new Command();
1858
2468
  program.name("bimdown").description("BimDown CLI \u2014 validate, query, and manage BimDown projects").version("0.1.0");
1859
2469
  program.command("validate").argument("<dir>", "BimDown project directory").description("Validate a BimDown project directory").action((dir) => {
1860
- const absDir = resolve(dir);
2470
+ const absDir = resolve2(dir);
1861
2471
  const issues = validate(absDir);
1862
2472
  if (issues.length === 0) {
1863
2473
  console.log("No issues found.");
@@ -1871,7 +2481,7 @@ ${issues.length} issue(s) found.`);
1871
2481
  }
1872
2482
  });
1873
2483
  program.command("query").argument("<dir>", "BimDown project directory").argument("<sql>", "SQL query to execute").option("--json", "Output results as JSON").description("Hydrate into DuckDB and execute a SQL query").action(async (dir, sql, opts) => {
1874
- const absDir = resolve(dir);
2484
+ const absDir = resolve2(dir);
1875
2485
  const { getConnection: getConnection2, runQuery: runQuery2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
1876
2486
  const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
1877
2487
  const conn = await getConnection2();
@@ -1888,7 +2498,7 @@ program.command("query").argument("<dir>", "BimDown project directory").argument
1888
2498
  }
1889
2499
  });
1890
2500
  program.command("sync").argument("<dir>", "BimDown project directory").description("Hydrate, then dehydrate back (sync DuckDB changes to files)").action(async (dir) => {
1891
- const absDir = resolve(dir);
2501
+ const absDir = resolve2(dir);
1892
2502
  const { getConnection: getConnection2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
1893
2503
  const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
1894
2504
  const { dehydrate: dehydrate2 } = await Promise.resolve().then(() => (init_dehydrate(), dehydrate_exports));
@@ -1902,12 +2512,24 @@ program.command("sync").argument("<dir>", "BimDown project directory").descripti
1902
2512
  await closeConnection2();
1903
2513
  }
1904
2514
  });
2515
+ program.command("render").argument("<dir>", "BimDown project directory").option("-l, --level <id>", "Level to render (defaults to lv-1)", "lv-1").option("-o, --output <file>", "Output SVG file path (defaults to render.svg)", "render.svg").description("Renders the BimDown project into a beautiful visual blueprint (SVG)").action(async (dir, opts) => {
2516
+ const absDir = resolve2(dir);
2517
+ const { renderLevel: renderLevel2 } = await Promise.resolve().then(() => (init_render(), render_exports));
2518
+ try {
2519
+ const svg = renderLevel2(absDir, opts.level);
2520
+ writeFileSync6(opts.output, svg);
2521
+ console.log(`Rendered ${opts.level} to ${opts.output}`);
2522
+ } catch (err) {
2523
+ console.error(`Render failed: ${err.message}`);
2524
+ process.exitCode = 1;
2525
+ }
2526
+ });
1905
2527
  program.command("info").argument("<dir>", "BimDown project directory").description("Print project summary").action((dir) => {
1906
- const absDir = resolve(dir);
2528
+ const absDir = resolve2(dir);
1907
2529
  const registry = buildRegistry(getSpecDir());
1908
2530
  const layout = discoverLayout(absDir);
1909
- const levelCsv = join10(layout.globalDir, "level.csv");
1910
- if (existsSync8(levelCsv)) {
2531
+ const levelCsv = join14(layout.globalDir, "level.csv");
2532
+ if (existsSync13(levelCsv)) {
1911
2533
  const levels = readCsv(levelCsv);
1912
2534
  console.log("Levels:");
1913
2535
  for (const row of levels.rows) {
@@ -1921,14 +2543,14 @@ program.command("info").argument("<dir>", "BimDown project directory").descripti
1921
2543
  ];
1922
2544
  const totals = {};
1923
2545
  for (const d of allDirs) {
1924
- if (!existsSync8(d.path)) continue;
2546
+ if (!existsSync13(d.path)) continue;
1925
2547
  const files = listFiles(d.path);
1926
2548
  const counts = [];
1927
2549
  for (const f of files) {
1928
2550
  if (!f.endsWith(".csv")) continue;
1929
2551
  const tableName = f.replace(".csv", "");
1930
2552
  if (!registry.has(tableName)) continue;
1931
- const data = readCsv(join10(d.path, f));
2553
+ const data = readCsv(join14(d.path, f));
1932
2554
  counts.push(`${tableName}: ${data.rows.length}`);
1933
2555
  totals[tableName] = (totals[tableName] ?? 0) + data.rows.length;
1934
2556
  }
@@ -1946,7 +2568,7 @@ program.command("info").argument("<dir>", "BimDown project directory").descripti
1946
2568
  console.log(` TOTAL: ${grand}`);
1947
2569
  });
1948
2570
  program.command("resolve-topology").argument("<dir>", "BimDown project directory").description("Auto-resolve MEP topology: detect coincident endpoints, generate mep_nodes, fill connectivity").action(async (dir) => {
1949
- const absDir = resolve(dir);
2571
+ const absDir = resolve2(dir);
1950
2572
  const { resolveTopology: resolveTopology2 } = await Promise.resolve().then(() => (init_resolve_topology(), resolve_topology_exports));
1951
2573
  resolveTopology2(absDir);
1952
2574
  });
@@ -1956,8 +2578,8 @@ program.command("merge").argument("<dirs...>", "Two or more BimDown project dire
1956
2578
  process.exitCode = 1;
1957
2579
  return;
1958
2580
  }
1959
- const absDirs = dirs.map((d) => resolve(d));
1960
- const absOut = resolve(opts.output);
2581
+ const absDirs = dirs.map((d) => resolve2(d));
2582
+ const absOut = resolve2(opts.output);
1961
2583
  const { merge: merge2 } = await Promise.resolve().then(() => (init_merge(), merge_exports));
1962
2584
  await merge2(absDirs, absOut);
1963
2585
  });
@@ -1993,6 +2615,21 @@ program.command("schema").argument("[table]", "Table name (omit for all tables)"
1993
2615
  console.log();
1994
2616
  }
1995
2617
  });
2618
+ program.command("init").argument("<dir>", "BimDown project directory").description("Initialize a new BimDown project structure").action(async (dir) => {
2619
+ const absDir = resolve2(dir);
2620
+ const { initProject: initProject2 } = await Promise.resolve().then(() => (init_init(), init_exports));
2621
+ initProject2(absDir);
2622
+ });
2623
+ program.command("diff").argument("<dirA>", "First BimDown project directory").argument("<dirB>", "Second BimDown project directory").description("Show differences between two BimDown projects").action(async (dirA, dirB) => {
2624
+ const absA = resolve2(dirA);
2625
+ const absB = resolve2(dirB);
2626
+ const { diffProjects: diffProjects2 } = await Promise.resolve().then(() => (init_diff(), diff_exports));
2627
+ diffProjects2(absA, absB);
2628
+ });
2629
+ program.command("generate-skill").description("Generate AI Agent SKILL.md documentation from YAML schemas").action(async () => {
2630
+ const { generateSkill: generateSkill2 } = await Promise.resolve().then(() => (init_generate_skill(), generate_skill_exports));
2631
+ generateSkill2("..");
2632
+ });
1996
2633
  program.parse();
1997
2634
  function printTable(columns, rows) {
1998
2635
  if (rows.length === 0) {