// dossier-cli (Phase C): importiert nur src/core, und die Befehle laufen headless gegen das // Beispielprojekt (inkl. der echten WASM-Pakete aus src/engine/pkg*). import { describe, expect, it, beforeAll, vi } from "vitest"; import { existsSync, mkdtempSync, readFileSync, writeFileSync, readdirSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { run } from "./main"; import { projectToModel3d, serializeProject } from "../core"; import { sampleProject } from "../model/sampleProject"; const dir = mkdtempSync(join(tmpdir(), "dossier-cli-")); const file = join(dir, "demo.obp"); beforeAll(() => { process.env.DOSSIER_WASM_DIR = join(process.cwd(), "src", "engine"); writeFileSync(file, serializeProject(sampleProject)); }); const call = async (...a: string[]) => run([file, ...a]); describe("dossier-cli", () => { it("importiert ausschliesslich ../core", () => { const src = readFileSync(join(process.cwd(), "src", "cli", "main.ts"), "utf8"); for (const f of ["main.ts", "mcp.ts", "mcpBridge.ts"]) { const text = readFileSync(join(process.cwd(), "src", "cli", f), "utf8"); const rel = [...text.matchAll(/from\s+"(\.[^"]+)"/g)].map((m) => m[1]); expect(rel.every((r) => r === "../core" || r === "./mcp" || r === "./mcpBridge"), f).toBe(true); } expect(src.length).toBeGreaterThan(0); expect(readdirSync(join(process.cwd(), "src", "cli")).filter((f) => statSync(join(process.cwd(), "src", "cli", f)).isFile() && f.endsWith(".ts") && !f.endsWith(".test.ts")).sort()).toEqual(["main.ts", "mcp.ts", "mcpBridge.ts"]); }); it("info, validate, migrate", async () => { expect(await call("info")).toBe(0); expect(await call("validate")).toBe(0); const out = join(dir, "migriert.obp"); expect(await call("migrate", "--out", out)).toBe(0); expect(JSON.parse(readFileSync(out, "utf8")).formatVersion).toBeGreaterThanOrEqual(1); }); it("validate meldet hängende Verweise als Warnung, Plan rechnet trotzdem", async () => { const broken = join(dir, "haengend.obp"); const p = { ...sampleProject, walls: sampleProject.walls.map((w, i) => (i === 0 ? { ...w, wallTypeId: "nope" } : w)) }; writeFileSync(broken, serializeProject(p)); const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true); try { expect(await run([broken, "validate"])).toBe(0); expect(err.mock.calls.map((c) => String(c[0])).join("")).toContain(`Warnung: Wand „${sampleProject.walls[0].id}": Wandtyp „nope" fehlt.`); } finally { err.mockRestore(); } expect(await run([broken, "plan", "--out", join(dir, "haengend.svg")])).toBe(0); }); it("Plan als SVG", async () => { const out = join(dir, "eg.svg"); expect(await call("plan", "--out", out)).toBe(0); const svg = readFileSync(out, "utf8"); expect(svg).toMatch(/^<\?xml/); expect(svg).toContain(""); }); it("Plan als render2d-Szene (JSON)", async () => { const out = join(dir, "eg.scene.json"); expect(await call("plan", "--format", "json", "--out", out)).toBe(0); const scene = JSON.parse(readFileSync(out, "utf8")); expect(scene.fills.length).toBeGreaterThan(0); expect(scene.fills[0].pts[0]).toHaveLength(2); expect(scene.fills[0].color).toHaveLength(4); expect(Array.isArray(scene.texts)).toBe(true); }); it("Beispielprojekt ohne Datei (:beispiel)", async () => { const out = join(dir, "beispiel.model3d.json"); expect(await run([":beispiel", "model3d", "--out", out])).toBe(0); expect(JSON.parse(readFileSync(out, "utf8")).walls.length).toBe(projectToModel3d(sampleProject).walls.length); }); it("IFC, OBJ, CSV, DXF", async () => { for (const [cmd, ext, needle] of [["ifc", "ifc", "ISO-10303-21"], ["obj", "obj", "v "], ["schedule", "csv", "Typ"], ["dxf", "dxf", "SECTION"]] as const) { const out = join(dir, `x.${ext}`); expect(await call(cmd, "--out", out)).toBe(0); expect(readFileSync(out, "utf8")).toContain(needle); } }); it("schedule --openings: Fenster- und Türliste als CSV und JSON", async () => { const out = join(dir, "fenster.csv"); expect(await call("schedule", "--openings", "--out", out)).toBe(0); expect(readFileSync(out, "utf8")).toContain("Nr.;Typ;Geschoss"); const json = join(dir, "fenster.json"); expect(await call("schedule", "--openings", "--format", "json", "--out", json)).toBe(0); expect(JSON.parse(readFileSync(json, "utf8")).length).toBeGreaterThan(0); await expect(call("schedule", "--openings", "--format", "xls", "--out", out)).rejects.toThrow("--format"); }); it("IFC mit --schema: 4 (Standard) und 2x3 (Coordination View 2.0), anderes ist ein Fehler", async () => { const out = join(dir, "schema.ifc"); expect(await call("ifc", "--out", out)).toBe(0); expect(readFileSync(out, "utf8")).toContain("FILE_SCHEMA(('IFC4'));"); expect(await call("ifc", "--schema", "4", "--out", out)).toBe(0); expect(readFileSync(out, "utf8")).toContain("FILE_SCHEMA(('IFC4'));"); for (const v of ["2x3", "IFC2X3", "ifc2x3"]) { expect(await call("ifc", "--schema", v, "--out", out)).toBe(0); const text = readFileSync(out, "utf8"); expect(text).toContain("FILE_SCHEMA(('IFC2X3'));"); expect(text).toContain("ViewDefinition [CoordinationView_V2.0]"); expect(text).not.toContain("IFCTRIANGULATEDFACESET"); } // convert reicht die Option durch. const conv = join(dir, "convert.ifc"); expect(await run(["convert", file, conv, "--schema", "2x3"])).toBe(0); expect(readFileSync(conv, "utf8")).toContain("FILE_SCHEMA(('IFC2X3'));"); // Unbekanntes Schema: `fail` beendet den Prozess (hier abgefangen) und schreibt keine Datei. const exit = vi.spyOn(process, "exit").mockImplementation((code) => { throw new Error(`exit ${code}`); }); const err = vi.spyOn(process.stderr, "write").mockImplementation(() => true); try { await expect(call("ifc", "--schema", "2x4", "--out", join(dir, "nope.ifc"))).rejects.toThrow("exit 1"); } finally { exit.mockRestore(); err.mockRestore(); } expect(existsSync(join(dir, "nope.ifc"))).toBe(false); }); it("DWG über das Format-WASM (acadrust, R2018)", async () => { const out = join(dir, "eg.dwg"); expect(await call("dwg", "--level", "eg", "--out", out)).toBe(0); const bytes = readFileSync(out); expect(bytes.subarray(0, 6).toString("latin1")).toBe("AC1032"); expect(bytes.length).toBeGreaterThan(10_000); }, 60_000); it("[157] Schnitt und Ansicht mit Höhenkoten wie in der App", async () => { for (const kind of ["section", "elevation"] as const) { const lvl = sampleProject.drawingLevels.find((l) => l.kind === kind); if (!lvl) continue; const out = join(dir, `koten-${kind}.svg`); expect(await call(kind, lvl.name, "--out", out)).toBe(0); expect(readFileSync(out, "utf8")).toContain("±0.00"); } }, 60_000); it("Schnitt und STEP über das WASM", async () => { const section = sampleProject.drawingLevels.find((l) => l.kind === "section"); if (section) { const out = join(dir, "s.svg"); expect(await call("section", section.name, "--out", out)).toBe(0); expect(readFileSync(out, "utf8")).toContain(" { const section = sampleProject.drawingLevels.find((l) => l.kind === "section")!; const elevation = sampleProject.drawingLevels.find((l) => l.kind === "elevation")!; const tpls = [ { id: "t-verdeckt", name: "Verdeckt", hiddenLines: true, cutHatch: true }, { id: "t-skizze", name: "Skizze", sketch: true }, { id: "t-fein", name: "Fein 1:50", detail: "fein" as const, scaleDenominator: 50 }, { id: "t-farbe", name: "Farbig", mono: false }, { id: "t-ohne-wand", name: "Ohne Wände", layerVisibility: { "20": false } }, ]; const tf = join(dir, "vorlagen.obp"); writeFileSync(tf, serializeProject({ ...sampleProject, viewTemplates: tpls })); const svg = async (args: string[], name: string, proj = tf) => { const out = join(dir, `${name}.svg`); expect(await run([proj, ...args, "--out", out])).toBe(0); return readFileSync(out, "utf8"); }; const plain = { section: await svg(["section", section.name], "v-s"), elevation: await svg(["elevation", elevation.name], "v-a"), plan: await svg(["plan"], "v-p") }; // Ebenen-Felder: im Schnitt (verdeckte Kanten, Schraffur) und in Schnitt und Ansicht (Skizzenstil). expect(await svg(["section", section.name, "--template", "Verdeckt"], "v-s1")).not.toBe(plain.section); expect(await svg(["section", section.name, "--template", "t-skizze"], "v-s2")).not.toBe(plain.section); expect(await svg(["elevation", elevation.name, "--template", "Skizze"], "v-a1")).not.toBe(plain.elevation); // Detailgrad und Massstab der Vorlage; ein ausdrückliches --scale geht vor. const fein = await svg(["section", section.name, "--template", "Fein 1:50"], "v-s3"); expect(fein).not.toBe(plain.section); expect(await svg(["section", section.name, "--template", "Fein 1:50", "--scale", "100"], "v-s4")).not.toBe(fein); expect(await svg(["plan", "--template", "Fein 1:50"], "v-p1")).not.toBe(plain.plan); // Farbe statt Tusche; ausgeblendete Kategorie. const farbig = await svg(["elevation", elevation.name, "--template", "Farbig"], "v-a2"); expect(farbig).not.toBe(plain.elevation); expect(farbig).toBe(await svg(["elevation", elevation.name, "--color"], "v-a3")); const ohne = await svg(["plan", "--template", "Ohne Wände"], "v-p2"); expect(ohne).not.toBe(plain.plan); expect(ohne.length).toBeLessThan(plain.plan.length); // Ohne Flag: die an der Ebene verknüpfte Vorlage. const linked = join(dir, "vorlagen-verknuepft.obp"); writeFileSync( linked, serializeProject({ ...sampleProject, viewTemplates: tpls, drawingLevels: sampleProject.drawingLevels.map((l) => (l.id === section.id ? { ...l, templateId: "t-fein", templateLinked: true } : l)), }), ); expect(await svg(["section", section.name], "v-s5", linked)).toBe(fein); }, 120_000); it("unbekannter Befehl und fehlende Datei geben Fehlercode", async () => { expect(await call("gibtsnicht")).toBe(2); expect(await run([])).toBe(2); }); }); import { handleMessage } from "./mcp"; describe("MCP-Server", () => { it("initialize, tools/list, project_info, apply_ops mit Validierung", async () => { const init = (await handleMessage(file, { jsonrpc: "2.0", id: 1, method: "initialize", params: {} })) as { result: { serverInfo: { name: string } } }; expect(init.result.serverInfo.name).toBe("dossier"); const list = (await handleMessage(file, { jsonrpc: "2.0", id: 2, method: "tools/list" })) as { result: { tools: Array<{ name: string }> } }; // gemeinsame Liste (core/aiToolDefs.ts) ohne die App-Werkzeuge const names = list.result.tools.map((t) => t.name); expect(names.slice(0, 4)).toEqual(["project_info", "query", "render_svg", "apply_ops"]); expect(names).toContain("run_command"); expect(names).not.toContain("select"); expect(await handleMessage(file, { jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull(); const call = async (name: string, args: Record) => ((await handleMessage(file, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name, arguments: args } })) as { result: { content: Array<{ text: string }>; isError: boolean }; }).result; const info = await call("project_info", {}); expect(JSON.parse(info.content[0].text).counts.walls).toBe(sampleProject.walls.length); const w = sampleProject.walls[0]; // gültige Änderung → Datei geändert const ok = await call("apply_ops", { ops: [{ kind: "replace", collection: "walls", entity: { ...w, height: 9 } }] }); expect(ok.isError).toBe(false); const q = await call("query", { collection: "walls", id: w.id }); expect(JSON.parse(q.content[0].text)[0].height).toBe(9); // ungültig (NaN → JSON-null ist nicht NaN; Doppel-id wird geprüft) → abgelehnt, Datei unverändert const bad = await call("apply_ops", { ops: [{ kind: "add", collection: "walls", items: [{ ...w }] }] }); expect(bad.isError).toBe(true); const q2 = await call("query", { collection: "walls", limit: 1000 }); expect(JSON.parse(q2.content[0].text).length).toBe(sampleProject.walls.length); expect((await call("validate", {})).isError).toBe(false); expect((await call("render_svg", { kind: "floor" })).content[0].text).toContain("