Files
FreeCADWasmDev/tools/run_p6_draft_tier2_python_family_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

81 lines
9.8 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 { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
const root = "/home/mes123456/FreeCADWasmDev/working/FreeCAD";
const source = path.join(root, "freecad-source");
const build = path.resolve(process.argv[2] ?? path.join(source, "build-web/configure/bin"));
const docs = path.join(root, "docs/p6");
const out = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-p6-draft-tier2-"));
execFileSync(path.join(root, "web/node_modules/.bin/tsc"), ["--target", "ES2022", "--module", "ESNext", "--moduleResolution", "Bundler", "--strict", "--skipLibCheck", "--outDir", out, "--declaration", "false", "--noEmit", "false", "web/src/facade-envelope.ts", "web/src/draft-facade.ts", "web/src/draft-python-family-facade.ts", "web/src/api-method-bridge.ts"], { cwd: root, stdio: "inherit" });
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 manifestPath = path.join(docs, "python-api-manifest.json");
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
const rows = manifest.records.filter((row) => row.module === "Draft" && row.tier === "tier-2-pure");
if (rows.length !== 1004) throw new Error(`expected 1004 Draft tier-2-pure records, got ${rows.length}`);
const records = rows.map((row) => ({
apiId: row.id,
name: row.name,
family: row.family,
kind: row.kind,
sourcePath: row.evidence?.path,
disposition: row.disposition,
...(row.id === "py:Draft:function:argb_to_rgba" || row.id === "py:Draft:function:rgba_to_argb" ? { args: { color: 0x80112233 } } : {}),
}));
globalThis.__dirname = `${build}${path.sep}`;
globalThis.require = createRequire(import.meta.url);
process.chdir(path.dirname(build));
const facade = await import(pathToFileURL(path.join(out, "draft-python-family-facade.js")));
const envelope = await import(pathToFileURL(path.join(out, "facade-envelope.js")));
const loader = await import(pathToFileURL(path.join(build, "FreeCADWebDraftRuntimeProbe.js")));
const kernel = await loader.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebDraftRuntimeProbe.wasm")), locateFile: (file) => path.join(build, file), print: () => {}, printErr: () => {} });
const queue = new envelope.FacadeSerialQueue();
const dispatch = (request, sourceKernel = kernel) => facade.dispatchDraftPythonFamily(queue, request, sourceKernel);
const apiBridge = await import(pathToFileURL(path.join(out, "api-method-bridge.js")));
const runtimeIndex = JSON.parse(fs.readFileSync(path.join(root, "web/public/api/python-api-index.json"), "utf8"));
const bridgeRouter = { request: async (_module, _command, payload) => envelope.createSuccess("draft-rgba-router", await facade.handleDraftPythonFamily(payload, new AbortController().signal, kernel)) };
const bridge = new apiBridge.ApiMethodBridge(bridgeRouter, runtimeIndex);
const request = facade.createDraftPythonFamilyRequest("draft-tier2-success", records, "tier-2-pure");
const success = await dispatch(request);
const repeated = await dispatch(facade.createDraftPythonFamilyRequest("draft-tier2-replay", records, "tier-2-pure"));
const cross = await dispatch(facade.createDraftPythonFamilyRequest("draft-tier2-cross", [{ ...records[0], apiId: "py:Assembly:class:Binding" }], "tier-2-pure"));
const malformed = await dispatch({ ...request, requestId: "draft-tier2-invalid-tier", payload: { ...request.payload, tier: "tier-unsupported" } });
const cancelRequest = facade.createDraftPythonFamilyRequest("draft-tier2-cancel", records, "tier-2-pure");
const cancelledPromise = dispatch(cancelRequest, new Promise((resolve) => setTimeout(() => resolve(kernel), 25)));
queue.cancel(envelope.createCancel("draft-tier2-cancel-control", cancelRequest.requestId));
const cancelled = await cancelledPromise;
if (success.kind !== "result") throw new Error(`Draft tier-2 dispatch failed: ${JSON.stringify(success)}`);
const result = success.result;
const terminal = new Set(["exposed", "restricted", "nonportable", "not_implemented"]);
if (result.module !== "Draft" || result.tier !== "tier-2-pure" || result.count !== 1004 || result.records.length !== 1004 || result.resourcesReleased !== true) throw new Error("Draft tier-2 result is incomplete");
if (result.records.some((record) => !terminal.has(record.status) || record.native !== true || record.resourcesReleased !== true || !record.sourceEntry || !record.sourceRevision || typeof record.parameterSchema !== "string" || typeof record.returnSchema !== "string")) throw new Error("Draft tier-2 record is not terminal/schema-complete");
if (JSON.stringify(result) !== JSON.stringify(repeated.result)) throw new Error("Draft tier-2 replay changed the native result");
if (cross.kind !== "result" || cross.result.records?.[0]?.status !== "not_implemented" || cross.result.records?.[0]?.code !== "unmatched_source_record") throw new Error("Draft tier-2 cross-module boundary failed");
if (malformed.kind !== "error" || malformed.error.code !== "invalid_request") throw new Error("Draft tier-2 invalid tier was not rejected");
if (cancelled.kind !== "error" || cancelled.error.code !== "cancelled") throw new Error("Draft tier-2 cancellation was not reported");
const argb = result.records.find((record) => record.apiId === "py:Draft:function:argb_to_rgba");
if (!argb || argb.status !== "exposed" || argb.code !== "native_python_method" || argb.result?.rgbaHex !== "0x11223380" || argb.replay !== "native-python-typed") throw new Error(`Draft argb_to_rgba method evidence failed: ${JSON.stringify(argb)}`);
const rgba = result.records.find((record) => record.apiId === "py:Draft:function:rgba_to_argb");
if (!rgba || rgba.status !== "exposed" || rgba.code !== "native_python_method" || rgba.result?.argbHex !== "0x33801122" || rgba.replay !== "native-python-typed") throw new Error(`Draft rgba_to_argb method evidence failed: ${JSON.stringify(rgba)}`);
const bridgeSuccess = await bridge.call({ apiId: "py:Draft:function:rgba_to_argb", args: [0x80112233] });
const bridgeInvalid = await bridge.call({ apiId: "py:Draft:function:rgba_to_argb", args: [0x100000000] });
if (bridgeSuccess.kind !== "result" || bridgeSuccess.result.records?.[0]?.result?.argbHex !== "0x33801122" || bridgeInvalid.kind !== "error" || bridgeInvalid.error.code !== "invalid_arguments") throw new Error(`Draft rgba_to_argb API bridge failed: ${JSON.stringify({ bridgeSuccess, bridgeInvalid })}`);
const dispositionCounts = Object.fromEntries([...terminal].map((status) => [status, result.records.filter((record) => record.status === status).length]));
const byId = new Map(result.records.map((record) => [record.apiId, record]));
for (const row of manifest.records) { if (row.module !== "Draft" || row.tier !== "tier-2-pure") continue; const native = byId.get(row.id); if (!native) throw new Error(`native result missing ${row.id}`); row.disposition = native.status; row.dispositionEvidence = ["docs/p6/draft-tier2-pure-family-runtime.json"]; row.dispositionReason = native.message; }
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
const report = { schema: "freecad-web-p6-draft-tier2-pure-family-runtime/v1", taskId: "FW-P6-FPA-F2-DRAFT", module: "Draft", tier: "tier-2-pure", status: "pass_with_boundaries", sourceRevision: result.records[0]?.sourceRevision, route: { worker: "web/src/draft.worker.ts", facade: "web/src/draft-python-family-facade.ts", apiBridge: "web/src/api-method-bridge.ts", command: facade.DRAFT_PYTHON_FAMILY_COMMAND, native: "freecad-source/src/WebAssembly/FreeCADCoreProbe/DraftRuntimeProbe.cpp:fc_web_dispatch_json" }, input: request, inputSha256: hash(request), result, resultSha256: hash(result), replay: { equal: true, resultSha256: hash(repeated.result) }, crossModuleBoundary: { result: cross, resultSha256: hash(cross) }, malformedRequest: { result: malformed, resultSha256: hash(malformed) }, cancellation: { result: cancelled, resultSha256: hash(cancelled) }, apiBridge: { success: bridgeSuccess, invalid: bridgeInvalid }, dispositionCounts, records: result.records.map((record) => ({ apiId: record.apiId, name: record.name, family: record.family, status: record.status, code: record.code, parameterSchema: record.parameterSchema, returnSchema: record.returnSchema, replay: record.replay, sourceEntry: record.sourceEntry, sourceRevision: record.sourceRevision, evidenceSha256: hash(record) })), resources: { resourcesReleased: true, documentMutation: false }, artifacts: { wasm: { path: path.relative(root, path.join(build, "FreeCADWebDraftRuntimeProbe.wasm")), sha256: fileHash(path.join(build, "FreeCADWebDraftRuntimeProbe.wasm")) } , loader: { path: path.relative(root, path.join(build, "FreeCADWebDraftRuntimeProbe.js")), sha256: fileHash(path.join(build, "FreeCADWebDraftRuntimeProbe.js")) } }, boundaries: ["Draft GUI/view-resource APIs remain restricted in the GUI-free Web kernel.", "Draft tier-2 methods without typed native argument/return fixtures remain not_implemented.", "All statuses, schemas and hashes derive from compiled FreeCAD through fc_web_dispatch_json; no JavaScript API result is substituted."] };
fs.writeFileSync(path.join(docs, "draft-tier2-pure-family-runtime.json"), `${JSON.stringify(report, null, 2)}\n`);
fs.writeFileSync(path.join(root, "docs/freecad-p6-draft-f2-tier2.log"), `${JSON.stringify({ status: report.status, count: records.length, dispositionCounts, resultSha256: report.resultSha256 })}\n`);
console.log(JSON.stringify({ status: report.status, count: records.length, dispositionCounts, resultSha256: report.resultSha256 }));
// The Draft probe uses pthread-enabled dependencies in the combined Web
// configure; terminate after evidence is flushed so worker handles cannot keep
// a successful gate alive.
process.exit(0);