bimdown-cli 0.1.5 → 0.1.8

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 +661 -70
  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,284 @@ 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
+ let md = `---
1796
+ name: bimdown
1797
+ 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.
1798
+ ---
1799
+
1800
+ # BimDown Agent Skill & Schema Rules
1801
+
1802
+ You are an AI Coder operating within a BimDown project environment.
1803
+ BimDown is an open-source, AI-native building data format using CSV for semantics and SVG for geometry.
1804
+
1805
+ ## Core Architecture & Base Concepts
1806
+
1807
+ - **Global Unit is METERS**: All coordinates, widths, and structural attributes in CSV/SVG MUST strictly use METERS. BimDown simulates real-world dimensions.
1808
+ - **Computed Fields are READ-ONLY**: Any field in the YAML 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\`.
1809
+ - **Dual Nature**: Properties live in \`{name}.csv\`. 2D geometry lives in a sibling \`{name}.svg\` file. The \`id\` fields across both must match perfectly.
1810
+ - **Concrete Example of CSV+SVG Linked State**:
1811
+ > \`lv-1/wall.csv\`:
1812
+ > \`id,name,level_id,thickness\`
1813
+ > \`w-1,MainWall,lv-1,0.2\`
1814
+ >
1815
+ > \`lv-1/wall.svg\`:
1816
+ > \`<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>\`
1817
+
1818
+ ## CLI Tools & Best Practices
1819
+
1820
+ 1. **\`bimdown query <dir> <sql> --json\`**: Runs DuckDB SQL across all tables.
1821
+ - **Spatial SQL Tip**: The CLI extracts geometry from \`.svg\` and injects virtual columns (length, start_x, etc.).
1822
+ - **Example**: \`bimdown query ./proj "SELECT id, length FROM wall WHERE length > 5.0" --json\`
1823
+ 2. **\`bimdown render <dir> [options]\`**: Renders the BimDown project into a beautiful visual blueprint (PNG/SVG). **As a multimodal AI, you MUST use this tool to generate an image and then "view" it to visually QA your geometry modifications.**
1824
+ 3. **\`bimdown validate <dir>\`**: Validates the project directory against schema constraints. **Run this EVERY TIME after your scripts modify CSV or SVG files** to ensure you didn't break topological or ID format constraints!
1825
+ 4. **\`bimdown schema [table]\`**: Prints the full schema data for any element type.
1826
+ 5. **\`bimdown diff <dirA> <dirB>\`**: Emits a \`+\`, \`-\`, \`~\` structural difference between project snapshots.
1827
+
1828
+ ## Critical File & Geometry Rules
1829
+
1830
+ - **Strict ID Formats**: Many elements require specific ID patterns. For example, Grids MUST be \`gr-{number}\` (e.g. \`gr-1\`), Levels MUST be \`lv-{name}\`. **Always run \`bimdown validate\` early to confirm your ID naming is compliant.**
1831
+ - **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.
1832
+ - **CSV vs Inferred Fields**: Only attributes listed in the schema that are NOT marked as 'inferred' should be written to the CSV. Specifically, \`level_id\` is always inferred from the folder structure and MUST be omitted from CSV files.
1833
+
1834
+ ## Base Schema Definitions
1835
+
1836
+ These abstract schemas provide common fields for concrete tables below.
1837
+
1838
+ `;
1839
+ for (const baseName of Array.from(BASE_SCHEMAS).sort()) {
1840
+ const filePath = findSchemaFile(csvSchemaDir, baseName);
1841
+ if (filePath) {
1842
+ md += `### Base: \`${baseName}\`
1843
+ \`\`\`yaml
1844
+ ${readFileSync5(filePath, "utf-8").trim()}
1845
+ \`\`\`
1846
+
1847
+ `;
1848
+ }
1849
+ }
1850
+ md += `## Core Schema Topologies (Concrete Tables)
1851
+
1852
+ Below is a curated whitelist of the **most commonly used** core architectural elements.
1853
+
1854
+ > **IMPORTANT**: The complete list of available elements in this project is:
1855
+ > ${allTableNames}
1856
+ >
1857
+ > If the user asks you to modify or generate elements not listed below, **RUN** \`bimdown schema <table_name>\` to fetch their requirements!
1858
+
1859
+ `;
1860
+ for (const name of sortedNames) {
1861
+ if (!CORE_TABLES.has(name)) continue;
1862
+ const table = registry.get(name);
1863
+ const hasSVG = TABLES_WITH_SVG.has(name);
1864
+ const filePath = findSchemaFile(csvSchemaDir, name);
1865
+ if (filePath) {
1866
+ md += `### Table: \`${table.name}\` (Prefix: \`${table.prefix}\`)
1867
+ `;
1868
+ md += `- **Geometry**: ${hasSVG ? "SVG required" : "CSV only"}
1869
+ `;
1870
+ md += `\`\`\`yaml
1871
+ `;
1872
+ md += `id_prefix: ${table.prefix}
1873
+ `;
1874
+ md += `${readFileSync5(filePath, "utf-8").trim()}
1875
+ `;
1876
+ const computedFields = table.allFields.filter((f) => f.computed || f.name === "level_id").map((f) => f.name);
1877
+ if (computedFields.length > 0) {
1878
+ md += `
1879
+ virtual_fields: [${computedFields.join(", ")}]
1880
+ `;
1881
+ }
1882
+ md += `\`\`\`
1883
+
1884
+ `;
1885
+ }
1886
+ }
1887
+ const rootDir = outputDir ? resolve(outputDir) : process.cwd();
1888
+ const dirPath = join13(rootDir, "agent-skill");
1889
+ if (!existsSync12(dirPath)) mkdirSync5(dirPath, { recursive: true });
1890
+ const outPath = join13(dirPath, "SKILL.md");
1891
+ writeFileSync5(outPath, md, "utf-8");
1892
+ console.log(`\u2705 Agent Skill documentation successfully generated at: ${outPath}`);
1893
+ }
1894
+ function findSchemaFile(baseDir, schemaName) {
1895
+ const dirs = [baseDir, join13(baseDir, "architecture"), join13(baseDir, "mep"), join13(baseDir, "structure"), join13(baseDir, "base")];
1896
+ for (const d of dirs) {
1897
+ if (!existsSync12(d)) continue;
1898
+ const p1 = join13(d, `${schemaName}.yaml`);
1899
+ if (existsSync12(p1)) return p1;
1900
+ const p2 = join13(d, `${schemaName}.yml`);
1901
+ if (existsSync12(p2)) return p2;
1902
+ }
1903
+ return null;
1904
+ }
1905
+ var CORE_TABLES, BASE_SCHEMAS;
1906
+ var init_generate_skill = __esm({
1907
+ "src/commands/generate-skill.ts"() {
1908
+ "use strict";
1909
+ init_registry();
1910
+ init_loader();
1911
+ CORE_TABLES = /* @__PURE__ */ new Set(["level", "grid", "wall", "door", "window", "space"]);
1912
+ BASE_SCHEMAS = /* @__PURE__ */ new Set(["element", "hosted_element", "materialized", "vertical_span", "line_element", "point_element", "polygon_element"]);
1913
+ }
1914
+ });
1915
+
1352
1916
  // src/index.ts
1353
1917
  import { Command } from "commander";
1354
- import { resolve } from "path";
1918
+ import { resolve as resolve2 } from "path";
1355
1919
 
1356
1920
  // src/validate/index.ts
1357
1921
  init_registry();
1358
1922
  init_fs();
1359
1923
  init_csv();
1360
- import { existsSync as existsSync3 } from "fs";
1924
+ import { existsSync as existsSync4 } from "fs";
1361
1925
  import { join as join5 } from "path";
1362
1926
 
1363
1927
  // src/validate/structure.ts
1364
1928
  init_fs();
1365
1929
  init_registry();
1366
- import { existsSync as existsSync2, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
1930
+ import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
1367
1931
  import { join as join4, extname } from "path";
1368
1932
  var OPTIONAL_SVG_TABLES = /* @__PURE__ */ new Set(["opening"]);
1369
1933
  var KNOWN_CSV_NAMES = new Set(Object.keys(ID_PREFIXES).map((t) => `${t}.csv`));
@@ -1372,7 +1936,7 @@ var KNOWN_GLOBAL_EXTRAS = /* @__PURE__ */ new Set(["_IdMap.csv"]);
1372
1936
  function validateStructure(dir) {
1373
1937
  const issues = [];
1374
1938
  const layout = discoverLayout(dir);
1375
- if (!existsSync2(layout.globalDir)) {
1939
+ if (!existsSync3(layout.globalDir)) {
1376
1940
  issues.push("global/ missing global/ directory");
1377
1941
  return issues;
1378
1942
  }
@@ -1443,7 +2007,7 @@ function validateStructure(dir) {
1443
2007
  issues.push(`${f} unexpected entry in project root \u2014 only global/ and lv-{n}/ directories are allowed`);
1444
2008
  }
1445
2009
  const metadataPath = join4(dir, "project_metadata.json");
1446
- if (existsSync2(metadataPath)) {
2010
+ if (existsSync3(metadataPath)) {
1447
2011
  try {
1448
2012
  const raw = readFileSync3(metadataPath, "utf-8");
1449
2013
  const metadata = JSON.parse(raw);
@@ -1763,7 +2327,7 @@ function validate(dir) {
1763
2327
  ...layout.levelDirs
1764
2328
  ];
1765
2329
  for (const d of allDirs) {
1766
- if (!existsSync3(d.path)) continue;
2330
+ if (!existsSync4(d.path)) continue;
1767
2331
  const files = listFiles(d.path);
1768
2332
  for (const f of files) {
1769
2333
  if (!f.endsWith(".csv")) continue;
@@ -1818,7 +2382,7 @@ function validate(dir) {
1818
2382
  }
1819
2383
  }
1820
2384
  for (const d of allDirs) {
1821
- if (!existsSync3(d.path) || d.name === "global") continue;
2385
+ if (!existsSync4(d.path) || d.name === "global") continue;
1822
2386
  const files = listFiles(d.path);
1823
2387
  for (const f of files) {
1824
2388
  if (!f.endsWith(".svg")) continue;
@@ -1852,12 +2416,12 @@ function validate(dir) {
1852
2416
  init_registry();
1853
2417
  init_fs();
1854
2418
  init_csv();
1855
- import { existsSync as existsSync8 } from "fs";
1856
- import { join as join10 } from "path";
2419
+ import { existsSync as existsSync13, writeFileSync as writeFileSync6 } from "fs";
2420
+ import { join as join14 } from "path";
1857
2421
  var program = new Command();
1858
2422
  program.name("bimdown").description("BimDown CLI \u2014 validate, query, and manage BimDown projects").version("0.1.0");
1859
2423
  program.command("validate").argument("<dir>", "BimDown project directory").description("Validate a BimDown project directory").action((dir) => {
1860
- const absDir = resolve(dir);
2424
+ const absDir = resolve2(dir);
1861
2425
  const issues = validate(absDir);
1862
2426
  if (issues.length === 0) {
1863
2427
  console.log("No issues found.");
@@ -1871,7 +2435,7 @@ ${issues.length} issue(s) found.`);
1871
2435
  }
1872
2436
  });
1873
2437
  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);
2438
+ const absDir = resolve2(dir);
1875
2439
  const { getConnection: getConnection2, runQuery: runQuery2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
1876
2440
  const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
1877
2441
  const conn = await getConnection2();
@@ -1888,7 +2452,7 @@ program.command("query").argument("<dir>", "BimDown project directory").argument
1888
2452
  }
1889
2453
  });
1890
2454
  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);
2455
+ const absDir = resolve2(dir);
1892
2456
  const { getConnection: getConnection2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
1893
2457
  const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
1894
2458
  const { dehydrate: dehydrate2 } = await Promise.resolve().then(() => (init_dehydrate(), dehydrate_exports));
@@ -1902,12 +2466,24 @@ program.command("sync").argument("<dir>", "BimDown project directory").descripti
1902
2466
  await closeConnection2();
1903
2467
  }
1904
2468
  });
2469
+ 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) => {
2470
+ const absDir = resolve2(dir);
2471
+ const { renderLevel: renderLevel2 } = await Promise.resolve().then(() => (init_render(), render_exports));
2472
+ try {
2473
+ const svg = renderLevel2(absDir, opts.level);
2474
+ writeFileSync6(opts.output, svg);
2475
+ console.log(`Rendered ${opts.level} to ${opts.output}`);
2476
+ } catch (err) {
2477
+ console.error(`Render failed: ${err.message}`);
2478
+ process.exitCode = 1;
2479
+ }
2480
+ });
1905
2481
  program.command("info").argument("<dir>", "BimDown project directory").description("Print project summary").action((dir) => {
1906
- const absDir = resolve(dir);
2482
+ const absDir = resolve2(dir);
1907
2483
  const registry = buildRegistry(getSpecDir());
1908
2484
  const layout = discoverLayout(absDir);
1909
- const levelCsv = join10(layout.globalDir, "level.csv");
1910
- if (existsSync8(levelCsv)) {
2485
+ const levelCsv = join14(layout.globalDir, "level.csv");
2486
+ if (existsSync13(levelCsv)) {
1911
2487
  const levels = readCsv(levelCsv);
1912
2488
  console.log("Levels:");
1913
2489
  for (const row of levels.rows) {
@@ -1921,14 +2497,14 @@ program.command("info").argument("<dir>", "BimDown project directory").descripti
1921
2497
  ];
1922
2498
  const totals = {};
1923
2499
  for (const d of allDirs) {
1924
- if (!existsSync8(d.path)) continue;
2500
+ if (!existsSync13(d.path)) continue;
1925
2501
  const files = listFiles(d.path);
1926
2502
  const counts = [];
1927
2503
  for (const f of files) {
1928
2504
  if (!f.endsWith(".csv")) continue;
1929
2505
  const tableName = f.replace(".csv", "");
1930
2506
  if (!registry.has(tableName)) continue;
1931
- const data = readCsv(join10(d.path, f));
2507
+ const data = readCsv(join14(d.path, f));
1932
2508
  counts.push(`${tableName}: ${data.rows.length}`);
1933
2509
  totals[tableName] = (totals[tableName] ?? 0) + data.rows.length;
1934
2510
  }
@@ -1946,7 +2522,7 @@ program.command("info").argument("<dir>", "BimDown project directory").descripti
1946
2522
  console.log(` TOTAL: ${grand}`);
1947
2523
  });
1948
2524
  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);
2525
+ const absDir = resolve2(dir);
1950
2526
  const { resolveTopology: resolveTopology2 } = await Promise.resolve().then(() => (init_resolve_topology(), resolve_topology_exports));
1951
2527
  resolveTopology2(absDir);
1952
2528
  });
@@ -1956,8 +2532,8 @@ program.command("merge").argument("<dirs...>", "Two or more BimDown project dire
1956
2532
  process.exitCode = 1;
1957
2533
  return;
1958
2534
  }
1959
- const absDirs = dirs.map((d) => resolve(d));
1960
- const absOut = resolve(opts.output);
2535
+ const absDirs = dirs.map((d) => resolve2(d));
2536
+ const absOut = resolve2(opts.output);
1961
2537
  const { merge: merge2 } = await Promise.resolve().then(() => (init_merge(), merge_exports));
1962
2538
  await merge2(absDirs, absOut);
1963
2539
  });
@@ -1993,6 +2569,21 @@ program.command("schema").argument("[table]", "Table name (omit for all tables)"
1993
2569
  console.log();
1994
2570
  }
1995
2571
  });
2572
+ program.command("init").argument("<dir>", "BimDown project directory").description("Initialize a new BimDown project structure").action(async (dir) => {
2573
+ const absDir = resolve2(dir);
2574
+ const { initProject: initProject2 } = await Promise.resolve().then(() => (init_init(), init_exports));
2575
+ initProject2(absDir);
2576
+ });
2577
+ 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) => {
2578
+ const absA = resolve2(dirA);
2579
+ const absB = resolve2(dirB);
2580
+ const { diffProjects: diffProjects2 } = await Promise.resolve().then(() => (init_diff(), diff_exports));
2581
+ diffProjects2(absA, absB);
2582
+ });
2583
+ program.command("generate-skill").description("Generate AI Agent SKILL.md documentation from YAML schemas").action(async () => {
2584
+ const { generateSkill: generateSkill2 } = await Promise.resolve().then(() => (init_generate_skill(), generate_skill_exports));
2585
+ generateSkill2("..");
2586
+ });
1996
2587
  program.parse();
1997
2588
  function printTable(columns, rows) {
1998
2589
  if (rows.length === 0) {