Files
FreeCADWasmDev/tools/run_p6_cam_generic_object_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
9.4 KiB
JavaScript

#!/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, "freecad-source/build-web/cam-configure-r1/bin"));
const batch = JSON.parse(fs.readFileSync(path.join(root, "docs/current/module-batch-manifest.json"), "utf8"));
const modules = JSON.parse(fs.readFileSync(path.join(root, "web/public/modules/manifest.json"), "utf8"));
const expectedFamily = batch.selected?.family;
if (batch.status !== "ready" || batch.taskId !== "FW-P6-FPA-Y" || batch.selected?.module !== "CAM"
|| batch.selected?.tier !== "object-contract" || !expectedFamily
|| !Array.isArray(batch.records) || batch.records.length !== batch.selected.recordCount) {
throw new Error("unexpected CAM generic-object module batch manifest");
}
const records = batch.records.map(([apiId, name, disposition, sourcePath, sourceLine]) => ({
apiId, name, family: batch.selected.family, 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 sourceEvidence = records.map(row => {
const source = path.join(root, "freecad-source", row.sourcePath);
const content = fs.readFileSync(source, "utf8");
const declaration = content.split(/\r?\n/)[row.sourceLine - 1] ?? "";
assert.ok(declaration.trim(), `missing source declaration for ${row.apiId}`);
assert.ok(content.includes(row.name.split(".").at(-1)), `source symbol missing for ${row.apiId}`);
return { apiId: row.apiId, path: row.sourcePath, line: row.sourceLine, declaration: declaration.trim(), sha256: fileHash(source) };
});
const output = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-cam-generic-object-batch-"));
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/cam-python-family-batch-facade.ts"),
], { cwd: root, stdio: "inherit" });
const facade = await import(pathToFileURL(path.join(output, "cam-python-family-batch-facade.js")));
const envelope = await import(pathToFileURL(path.join(output, "facade-envelope.js")));
const worker = new Worker(path.join(root, "tools/cam-python-family-batch-smoke-worker.mjs"), {
workerData: { buildDirectory: build, facadePath: pathToFileURL(path.join(output, "cam-python-family-batch-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 = (id, rows = records) => facade.createCamPythonFamilyBatchRequest(id, rows, "object-contract");
const ready = await next();
worker.postMessage(request("cam-generic-object-success")); const success = await next();
worker.postMessage(request("cam-generic-object-repeat")); const repeat = await next();
worker.postMessage(request("cam-generic-object-cross", [{ ...records[0], apiId: "py:BIM:class:Binding" }])); const cross = await next();
const malformedRequest = request("cam-generic-object-invalid");
worker.postMessage({ ...malformedRequest, payload: { ...malformedRequest.payload, tier: "tier-unsupported" } }); const malformed = await next();
const cancelRequest = request("cam-generic-object-cancel");
worker.postMessage(cancelRequest); worker.postMessage(envelope.createCancel("cam-generic-object-cancel-control", cancelRequest.requestId)); const cancelled = await next();
worker.postMessage({ kind: "reset", requestId: "cam-generic-object-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 !== "cam-generic-object-reset") {
throw new Error(JSON.stringify({ ready, success, repeat, cross, malformed, cancelled, reset }));
}
const result = success.result;
const terminal = new Set(["exposed", "restricted", "nonportable", "not_implemented"]);
if (result.module !== "CAM" || result.tier !== "object-contract" || result.count !== records.length
|| result.records.length !== records.length || result.resourcesReleased !== true) throw new Error("CAM generic-object result is incomplete");
for (const row of result.records) {
if (!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(`CAM generic-object record schema is incomplete for ${row.name}`);
}
}
if (JSON.stringify(result) !== JSON.stringify(repeat.result)) throw new Error("CAM generic-object replay changed native result");
if (cross.result.records?.[0]?.status !== "not_implemented" || cross.result.records?.[0]?.code !== "unmatched_source_record") throw new Error("CAM cross-module boundary failed");
if (malformed.error.code !== "invalid_request" || cancelled.error.code !== "cancelled") throw new Error("CAM error/cancel boundary failed");
const evidencePath = `docs/p6/cam-${expectedFamily}-module-batch-${batch.batchId}-runtime.json`;
const objectMatrixPath = path.join(root, "docs/p6/object-contract-matrix.json");
const objectMatrix = JSON.parse(fs.readFileSync(objectMatrixPath, "utf8"));
const byId = new Map(result.records.map(row => [row.apiId, row]));
for (const row of objectMatrix.records ?? []) {
const native = byId.get(row.id);
if (!native) continue;
row.status = native.status;
row.dispositionEvidence = [evidencePath];
row.dispositionReason = native.message;
}
fs.writeFileSync(objectMatrixPath, `${JSON.stringify(objectMatrix, null, 2)}\n`);
const dispositionCounts = Object.fromEntries([...terminal].map(status => [status, result.records.filter(row => row.status === status).length]));
const camModule = modules.modules?.CAM ?? modules.CAM;
const camWorker = camModule?.workers?.["cam.worker.ts"];
if (!camModule?.revision || !camModule?.assetBaseUrl || !camWorker?.revision || !camWorker?.runtimeUrl || !camWorker?.wasmUrl) throw new Error("CAM module artifact manifest is incomplete");
const trace = { ready, success, repeat, cross, malformed, cancelled, reset };
const report = {
schema: "freecad-web-cam-generic-object-module-batch-runtime/v1", taskId: "FW-P6-FPA-Y", batchId: batch.batchId,
module: "CAM", tier: "object-contract", family: expectedFamily, status: "pass_with_boundaries", dispatcher: "fc_web_dispatch_json",
sourceRevision: result.records[0]?.sourceRevision,
route: { command: facade.CAM_PYTHON_FAMILY_BATCH_COMMAND, native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/CAMRuntimeProbe.cpp:fc_web_dispatch_json", facade: "web/src/cam-python-family-batch-facade.ts", worker: "web/src/cam.worker.ts" },
input: { cmd: facade.CAM_PYTHON_FAMILY_BATCH_COMMAND, 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, result: row.result ?? null, sourceEntry: row.sourceEntry, sourceRevision: row.sourceRevision, evidenceSha256: hash(row) })), sourceEvidence,
resources: { resourcesReleased: result.resourcesReleased, documentMutation: false },
artifacts: { module: "CAM", worker: "cam.worker.ts", revision: camModule.revision, runtimeUrl: camWorker.runtimeUrl, wasmUrl: camWorker.wasmUrl, dataUrl: camWorker.dataUrl ?? null, assetBaseUrl: camModule.assetBaseUrl, workerRevision: camWorker.revision, runtimeSha256: camWorker.hashes?.runtime ?? fileHash(path.join(build, "FreeCADWebCAMProbe.js")), wasmSha256: camWorker.hashes?.wasm ?? fileHash(path.join(build, "FreeCADWebCAMProbe.wasm")) },
boundaries: ["CAM view-resource APIs are classified by compiled FreeCAD CAM sources through fc_web_dispatch_json.", "GUI-only PathGui resources remain explicit restricted boundaries in the GUI-free Web kernel.", "The CAM runtime remains an independent module artifact loaded by cam.worker.ts; no WASM binary merge is used."],
};
fs.writeFileSync(path.join(root, evidencePath), `${JSON.stringify(report, null, 2)}\n`);
const logPath = `docs/freecad-p6-cam-${expectedFamily}-module-batch-${batch.batchId}.log`;
fs.writeFileSync(path.join(root, logPath), `${JSON.stringify({ status: report.status, batchId: batch.batchId, count: records.length, dispositionCounts, resultSha256: report.resultSha256 })}\n`);
console.log(JSON.stringify({ status: report.status, batchId: batch.batchId, count: records.length, dispositionCounts, resultSha256: report.resultSha256 }));
process.exit(0);