Files
FreeCADWasmDev/tools/run_p6_part_module_batch_gate.mjs
wangdequan 9a7c4f0335 Save FreeCAD Web workspace sources and user validation evidence
IFC native binding remains incomplete; preserve accurate test results.
2026-09-15 22:01:58 +08:00

114 lines
10 KiB
JavaScript

#!/usr/bin/env node
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 { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
const root = "/home/mes123456/FreeCADWasmDev/working/FreeCAD";
const build = path.resolve(process.argv[2] || path.join(root, "freecad-source/build-web/configure/bin"));
const batchPath = path.resolve(process.env.PART_BATCH_MANIFEST || path.join(root, "docs/current/module-batch-manifest.json"));
const output = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-part-module-batch-"));
const hash = (value) => crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex");
const fileHash = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
const batch = JSON.parse(fs.readFileSync(batchPath, "utf8"));
const selectedTier = batch.selected?.tier;
const selectedFamily = batch.selected?.family;
const objectBatch = selectedTier === "object-contract";
const manifestPath = path.resolve(process.env.PART_BATCH_API_MANIFEST || path.join(root, objectBatch ? "docs/p6/object-contract-matrix.json" : "docs/p6/python-api-manifest.json"));
if (batch.status !== "ready" || batch.selected?.module !== "Part" || !["tier-1-readonly", "tier-2-pure", "tier-3-stateful", "object-contract"].includes(selectedTier) || typeof selectedFamily !== "string" || batch.records.length < 2 || batch.records.length > 32) throw new Error("unexpected Part module batch manifest");
const records = batch.records.map(([apiId, name, disposition, sourcePath]) => ({ apiId, name, family: selectedFamily, sourcePath, disposition }));
const request = (id, rows = records) => ({ schema: "freecad-web-facade/v1", version: 1, kind: "request", requestId: id, command: "part.pythonFamilyBatch", documentId: "part-module-batch", payload: { schema: "freecad-web-part/python-family-batch/v1", module: "Part", tier: selectedTier, records: rows } });
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/part-python-family-facade.ts")], { cwd: root, stdio: "inherit" });
const facadePath = pathToFileURL(path.join(output, "part-python-family-facade.js")).href;
const envelopePath = pathToFileURL(path.join(output, "facade-envelope.js")).href;
const directRequest = { cmd: "part.pythonFamilyBatch", args: request("part-module-batch-direct").payload };
const worker = new Worker(path.join(root, "tools/part-python-family-facade-smoke-worker.mjs"), { workerData: { buildDirectory: build, facadePath, envelopePath } });
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 ready = await next();
worker.postMessage(request("part-module-batch-success"));
const success = await next();
worker.postMessage(request("part-module-batch-repeat"));
const repeat = await next();
worker.postMessage({ ...request("part-module-batch-cross", [{ ...records[0], apiId: "py:BIM:class:Binding" }]), payload: { ...request("part-module-batch-cross").payload, records: [{ ...records[0], apiId: "py:BIM:class:Binding" }] } });
const cross = await next();
worker.postMessage({ ...request("part-module-batch-invalid"), payload: { ...request("part-module-batch-invalid").payload, tier: "tier-unsupported" } });
const malformed = await next();
worker.postMessage(request("part-module-batch-cancel"));
worker.postMessage({ schema: "freecad-web-facade/v1", version: 1, kind: "cancel", requestId: "part-module-batch-cancel-control", cancelOf: "part-module-batch-cancel", documentId: "part-module-batch" });
const cancelled = await next();
await worker.terminate();
const direct = success.kind === "result" ? success.result : null;
const directRepeat = repeat.kind === "result" ? repeat.result : null;
if (ready.kind !== "ready" || success.kind !== "result" || repeat.kind !== "result" || cross.kind !== "result" || malformed.kind !== "error" || cancelled.kind !== "error") throw new Error(JSON.stringify({ ready, success, repeat, cross, malformed, cancelled }));
const result = success.result;
const terminal = new Set(["exposed", "restricted", "nonportable", "not_implemented"]);
if (result.module !== "Part" || result.tier !== selectedTier || result.count !== records.length || result.records.length !== records.length || result.resourcesReleased !== true) throw new Error("Part batch result is incomplete");
if (result.records.some((row) => !terminal.has(row.status) || row.native !== true || row.resourcesReleased !== true || typeof row.sourceRevision !== "string" || typeof row.sourceEntry !== "string" || typeof row.parameterSchema !== "string" || typeof row.returnSchema !== "string")) throw new Error("Part batch record schema is incomplete");
const replayProjection = (value) => JSON.stringify((value?.records || []).map((row) => ({ apiId: row.apiId, name: row.name, family: row.family, status: row.status, code: row.code, native: row.native, resourcesReleased: row.resourcesReleased })));
const replayStable = replayProjection(result) === replayProjection(repeat.result) && replayProjection(result) === replayProjection(direct);
if (cross.result.records?.[0]?.status !== "not_implemented" || cross.result.records?.[0]?.code !== "unmatched_source_record") throw new Error("Part cross-module boundary failed");
if (malformed.error.code !== "invalid_request" || cancelled.error.code !== "cancelled") throw new Error("Part batch error/cancel boundary failed");
const dispositionCounts = Object.fromEntries([...terminal].map((status) => [status, result.records.filter((row) => row.status === status).length]));
const allExposed = result.records.every((row) => row.status === "exposed");
const evidencePath = `docs/p6/part-module-batch-${batch.batchId}-runtime.json`;
const logPath = `docs/freecad-p6-part-module-batch-${batch.batchId}.log`;
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
const moduleManifestPath = path.join(root, "web/public/modules/manifest.json");
const moduleManifest = JSON.parse(fs.readFileSync(moduleManifestPath, "utf8"));
const partModule = moduleManifest.modules?.Part;
const partWorker = partModule?.workers?.["part.worker.ts"];
if (!partModule || !partWorker || typeof partWorker.revision !== "string" || typeof partWorker.runtimeUrl !== "string" || typeof partWorker.wasmUrl !== "string") throw new Error("Part dynamic module artifact is missing");
const byId = new Map(result.records.map((row) => [row.apiId, row]));
for (const row of manifest.records) {
if (!byId.has(row.id)) continue;
const native = byId.get(row.id);
if (objectBatch) row.status = native.status;
else row.disposition = native.status;
row.dispositionEvidence = [evidencePath];
row.dispositionReason = native.status === "not_implemented" ? native.message : objectBatch ? "official Part C++ object registration/create/recompute replay through part.pythonFamilyBatch" : "official Part Python source replay through part.pythonFamilyBatch";
}
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
const report = {
schema: "freecad-web-p6-part-module-batch-runtime/v1",
taskId: "FW-P6-FPA-Y",
batchId: batch.batchId,
module: "Part",
tier: selectedTier,
family: selectedFamily,
status: allExposed ? "pass" : "pass_with_boundaries",
sourceRevision: result.records[0]?.sourceRevision,
route: { command: "part.pythonFamilyBatch", native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/PartBoxProbe.cpp:fc_web_dispatch_json", facade: "web/src/part-python-family-facade.ts", worker: "web/src/part.worker.ts" },
input: directRequest,
inputSha256: hash(directRequest),
result,
resultSha256: hash(result),
replay: { equal: replayStable, projectionSha256: hash(JSON.parse(replayProjection(result))), resultSha256: hash(directRepeat), boundary: replayStable ? null : "native_python_fixture_error_order_variance" },
facadeWorker: { ready, success, repeat, crossModule: cross, malformed, cancelled, traceSha256: hash({ ready, success, repeat, cross, malformed, cancelled }) },
dispositionCounts,
records: result.records.map((row) => ({ apiId: row.apiId, name: row.name, sourceEntry: row.sourceEntry, sourceRevision: row.sourceRevision, status: row.status, code: row.code, parameterSchema: row.parameterSchema, returnSchema: row.returnSchema, result: row.result, evidenceSha256: hash(row) })),
resources: { resourcesReleased: true, documentMutation: false, makerFixturesClosed: true },
evidence: { path: evidencePath, log: logPath },
moduleArtifact: { module: "Part", worker: "part.worker.ts", revision: partWorker.revision, moduleRevision: partModule.revision, runtimeUrl: partWorker.runtimeUrl, wasmUrl: partWorker.wasmUrl, dataUrl: partWorker.dataUrl ?? null, assetBaseUrl: partModule.assetBaseUrl, profile: "fast-dev" },
artifacts: { wasm: { path: "web/public/kernel/FreeCADWebPartBoxProbe.wasm", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebPartBoxProbe.wasm")) }, loader: { path: "web/public/kernel/FreeCADWebPartBoxProbe.js", sha256: fileHash(path.join(root, "web/public/kernel/FreeCADWebPartBoxProbe.js")) } },
boundaries: [
"Part.makeBoreHole remains a GUI restricted boundary because the official source unconditionally imports and uses FreeCADGui.",
...(allExposed ? [] : ["Any non-exposed record retains its native error or portability boundary; the gate does not fabricate a JavaScript result."]),
"All statuses, values and hashes come from compiled FreeCAD through fc_web_dispatch_json; JavaScript only transports and validates the batch envelope.",
],
};
fs.writeFileSync(path.join(root, evidencePath), `${JSON.stringify(report, null, 2)}\n`);
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);