#!/usr/bin/env node import assert from "node:assert/strict"; import crypto from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { execFileSync } from "node:child_process"; import { Worker } from "node:worker_threads"; import { pathToFileURL } from "node:url"; const root = "/home/mes123456/FreeCADWasmDev/working/FreeCAD"; const build = path.resolve(process.argv[2] ?? path.join(root, "web/public/kernel")); const batch = JSON.parse(fs.readFileSync(path.join(root, "docs/current/module-batch-manifest.json"), "utf8")); if (batch.status !== "ready" || batch.taskId !== "FW-P6-FPA-Y" || batch.selected?.module !== "Fem" || batch.selected?.tier !== "object-contract" || batch.selected?.family !== "geometry-recompute" || !Array.isArray(batch.records) || batch.records.length !== batch.selected.recordCount || batch.records.length < batch.minimumRecords) throw new Error("unexpected Fem geometry-recompute module batch manifest"); const records = batch.records.map(([apiId, name, disposition, sourcePath, sourceLine]) => ({ apiId, name, family: batch.selected.family, kind: "object", sourcePath, sourceLine, disposition, })); const hash = value => crypto.createHash("sha256").update(typeof value === "string" || Buffer.isBuffer(value) ? value : JSON.stringify(value)).digest("hex"); const fileHash = file => hash(fs.readFileSync(file)); const terminal = new Set(["exposed", "restricted", "nonportable", "not_implemented"]); const output = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-fem-geometry-recompute-batch-")); const sourceEvidence = records.map(row => { assert.ok(row.sourcePath.startsWith("src/Mod/Fem/") && !row.sourcePath.includes("..")); const source = path.join(root, "freecad-source", row.sourcePath); const declaration = fs.readFileSync(source, "utf8").split(/\r?\n/)[row.sourceLine - 1] ?? ""; assert.ok(declaration.includes(row.name.split("::").at(-1)), `source evidence mismatch for ${row.apiId}`); return { apiId: row.apiId, path: row.sourcePath, line: row.sourceLine, declaration: declaration.trim(), sha256: fileHash(source) }; }); execFileSync(path.join(root, "web/node_modules/.bin/tsc"), [ "--target", "ES2022", "--module", "ESNext", "--moduleResolution", "Bundler", "--strict", "--skipLibCheck", "--outDir", output, "--declaration", "false", "--noEmit", "false", path.join(root, "web/src/facade-envelope.ts"), path.join(root, "web/src/fem-python-family-facade.ts"), ], { cwd: root, stdio: "inherit" }); const facade = await import(pathToFileURL(path.join(output, "fem-python-family-facade.js"))); const envelope = await import(pathToFileURL(path.join(output, "facade-envelope.js"))); const worker = new Worker(path.join(root, "tools/fem-python-family-batch-smoke-worker.mjs"), { workerData: { buildDirectory: build, facadePath: pathToFileURL(path.join(output, "fem-python-family-facade.js")).href, envelopePath: pathToFileURL(path.join(output, "facade-envelope.js")).href, }, }); const next = () => new Promise((resolve, reject) => { const onMessage = value => { worker.off("error", onError); resolve(value); }; const onError = error => { worker.off("message", onMessage); reject(error); }; worker.once("message", onMessage); worker.once("error", onError); }); const request = (requestId, rows = records) => facade.createFemPythonFamilyRequest(requestId, rows, "object-contract"); const ready = await next(); worker.postMessage(request("fem-geometry-recompute-success")); const success = await next(); worker.postMessage(request("fem-geometry-recompute-repeat")); const repeat = await next(); worker.postMessage(request("fem-geometry-recompute-cross", [{ ...records[0], apiId: "obj:BIM:BIM::Building" }])); const cross = await next(); const malformedRequest = request("fem-geometry-recompute-invalid"); worker.postMessage({ ...malformedRequest, payload: { ...malformedRequest.payload, tier: "tier-unsupported" } }); const malformed = await next(); const cancelRequest = request("fem-geometry-recompute-cancel"); worker.postMessage(cancelRequest); worker.postMessage(envelope.createCancel("fem-geometry-recompute-cancel-control", cancelRequest.requestId, "fem-python-family")); const cancelled = await next(); worker.postMessage({ kind: "reset", requestId: "fem-geometry-recompute-reset" }); const reset = await next(); await worker.terminate(); if (ready.kind !== "ready" || success.kind !== "result" || repeat.kind !== "result" || cross.kind !== "result" || malformed.kind !== "error" || cancelled.kind !== "error" || reset.requestId !== "fem-geometry-recompute-reset") { throw new Error(JSON.stringify({ ready, success, repeat, cross, malformed, cancelled, reset })); } const result = success.result; if (result.schema !== "freecad-web-fem/python-family-batch/v1" || result.module !== "Fem" || result.tier !== "object-contract" || result.count !== records.length || result.records.length !== records.length || result.resourcesReleased !== true) throw new Error("Fem geometry-recompute result is incomplete"); for (const row of result.records) { if (!terminal.has(row.status) || row.native !== true || row.resourcesReleased !== true || typeof row.sourceEntry !== "string" || typeof row.sourceLine !== "number" || row.sourceVerified !== true || typeof row.sourceRevision !== "string" || typeof row.parameterSchema !== "string" || typeof row.returnSchema !== "string") { throw new Error(`Fem geometry-recompute record schema is incomplete for ${row.name}`); } if (["Fem::FemMesh", "Fem::PropertyFemMesh"].includes(row.name)) { if (row.status !== "restricted" || row.code !== "non_document_object_type" || row.result?.registered !== true || row.result?.documentObjectType !== false || row.result?.constructible !== false) { throw new Error(`Fem non-document boundary mismatch for ${row.name}: ${JSON.stringify(row)}`); } } else if (row.name === "Fem::FemMeshShapeNetgenObject") { if (row.status !== "restricted" || row.code !== "native_dependency_unavailable" || row.result?.registered !== true || row.result?.constructible !== true || row.result?.recomputed !== false || row.result?.dependencyUnavailable !== true || row.result?.dependency !== "NETGEN") { throw new Error(`Fem NETGEN dependency boundary mismatch for ${row.name}: ${JSON.stringify(row)}`); } } else if (row.status !== "exposed" || row.code !== "native_object_contract" || row.result?.objectType !== row.name || row.result?.constructible !== true || row.result?.recomputed !== true) { throw new Error(`Fem geometry object fixture mismatch for ${row.name}: ${JSON.stringify(row)}`); } } if (JSON.stringify(result) !== JSON.stringify(repeat.result)) throw new Error("Fem geometry-recompute replay changed native result"); if (cross.result.records?.[0]?.status !== "not_implemented" || cross.result.records?.[0]?.code !== "unmatched_source_record") throw new Error("Fem cross-module boundary failed"); if (malformed.error.code !== "invalid_request" || cancelled.error.code !== "cancelled") throw new Error("Fem error/cancel boundary failed"); const evidencePath = `docs/p6/fem-geometry-recompute-module-batch-${batch.batchId}-runtime.json`; const matrixPath = path.join(root, "docs/p6/object-contract-matrix.json"); const matrix = JSON.parse(fs.readFileSync(matrixPath, "utf8")); const byId = new Map(result.records.map(row => [row.apiId, row])); for (const row of matrix.records) { const native = byId.get(row.id); if (!native) continue; row.status = native.status; row.dispositionEvidence = [evidencePath]; row.dispositionReason = native.message; } fs.writeFileSync(matrixPath, `${JSON.stringify(matrix, null, 2)}\n`); const dispositionCounts = Object.fromEntries([...terminal].map(status => [status, result.records.filter(row => row.status === status).length])); const trace = { ready, success, repeat, cross, malformed, cancelled, reset }; const report = { schema: "freecad-web-fem-geometry-recompute-module-batch-runtime/v1", taskId: "FW-P6-FPA-Y", batchId: batch.batchId, module: "Fem", tier: "object-contract", family: "geometry-recompute", status: "pass_with_boundaries", sourceRevision: result.records[0]?.sourceRevision, dispatcher: "fc_web_dispatch_json", route: { command: "fem.pythonFamilyBatch", native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/FemGenericFamilyProbe.cpp:fc_web_dispatch_json", facade: "web/src/fem-python-family-facade.ts", worker: "web/src/fem.worker.ts" }, input: { cmd: "fem.pythonFamilyBatch", args: { tier: "object-contract", records } }, inputSha256: hash(records), result, resultSha256: hash(result), replay: { equal: true, resultSha256: hash(repeat.result) }, facadeWorker: { ready, success, repeat, cross, malformed, cancelled, reset, traceSha256: hash(trace) }, dispositionCounts, records: result.records.map(row => ({ apiId: row.apiId, name: row.name, family: row.family, status: row.status, code: row.code, message: row.message, sourceEntry: row.sourceEntry, sourceLine: row.sourceLine, sourceVerified: row.sourceVerified, sourceRevision: row.sourceRevision, result: row.result, evidenceSha256: hash(row) })), sourceEvidence, resources: { resourcesReleased: result.resourcesReleased, documentMutation: false }, artifacts: { module: "Fem", worker: "fem.worker.ts", revision: result.records[0]?.sourceRevision, loader: { path: path.relative(root, path.join(build, "FreeCADWebFemGenericFamilyProbe.js")), sha256: fileHash(path.join(build, "FreeCADWebFemGenericFamilyProbe.js")) }, wasm: { path: path.relative(root, path.join(build, "FreeCADWebFemGenericFamilyProbe.wasm")), sha256: fileHash(path.join(build, "FreeCADWebFemGenericFamilyProbe.wasm")) }, runtimeUrl: "/kernel/FreeCADWebFemGenericFamilyProbe.js", wasmUrl: "/kernel/FreeCADWebFemGenericFamilyProbe.wasm", dataUrl: null, assetBaseUrl: "/kernel/", }, boundaries: ["FemMesh and PropertyFemMesh are registered source types but are not standalone App::DocumentObject instances, so they remain explicit restricted boundaries.", "Shape-based mesh objects use a native Part::Feature box link before recompute; all other selected objects are independently constructed and recomputed in the FreeCAD source fixture.", "All statuses, source metadata and typed object values originate from compiled FreeCAD through fc_web_dispatch_json; JavaScript only validates and transports the shared batch envelope."], }; fs.writeFileSync(path.join(root, evidencePath), `${JSON.stringify(report, null, 2)}\n`); const logPath = `docs/freecad-p6-fem-geometry-recompute-module-batch-${batch.batchId}.log`; fs.writeFileSync(path.join(root, logPath), `${JSON.stringify({ status: report.status, batchId: report.batchId, count: records.length, dispositionCounts, resultSha256: report.resultSha256 })}\n`); console.log(JSON.stringify({ status: report.status, batchId: report.batchId, count: records.length, dispositionCounts, resultSha256: report.resultSha256 })); process.exit(0);