feat(reducer): 二级减速器有头创建工具包与初学者教学

- tools/reducer:目录/前置/单件/批量/装配/自测,复用 cad-ui-rebuild 引擎
- 教学控制台新增「二级减速器」分组:23 件逐件课 + 装配课 + 环境课(job kind reducer-part / reducer-assembly)
- web/teaching/reducer-toolkit.html 初学者配套页(生成物)+ Playwright 双视口门禁
- 首页补工具入口;工具手册随 npm 脚本变更重生成

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 07:31:24 +08:00
parent dd8ba17591
commit b876ad5742
19 changed files with 1790 additions and 15 deletions

83
tools/reducer/README.md Normal file
View File

@@ -0,0 +1,83 @@
# tools/reducer —— 二级减速器「有头」创建工具
在真实界面(有头 Chrome)里逐一重建二级减速器的 23 个零件并完成装配,产出归一化报告。
本包**只做编排与前置检查**:真实点击仍由 `web/tools/cad-ui-rebuild/drive.mjs` /
`assemble.mjs` 完成,零件目录仍来自 `web/tools/reducer-parts-course/project.json`,
内核建模仍由 `web/teaching/cases/secondary-reducer-pro/parts/*.mjs` 与 `tools/fcweb` 完成。
这里不复制任何步骤数据。
## 快速开始
```bash
# 看目录:23 件、分组、步数、记录体积
node tools/reducer/list.mjs
node tools/reducer/list.mjs --json
# 单件:真实界面重建(默认有头)
node tools/reducer/create-part.mjs P06
node tools/reducer/create-part.mjs Bearing6206_Inner --slow # 慢放,便于观察
node tools/reducer/create-part.mjs P21 --dry # 只查前置与步骤
# 批量:按组 / 按列表 / 全部
node tools/reducer/create-all.mjs --group gears
node tools/reducer/create-all.mjs --parts P06,P07 --keep-going
# 装配:32 链接 / 33 关节
node tools/reducer/create-assembly.mjs
```
## 命令与退出码
| 命令 | 说明 |
|---|---|
| `create-part.mjs <P01..P23\|Document>` | 校验前置 → 定位步骤 → 调 `drive.mjs` → 读 `out/ui-run/<Document>.json` → 写 `report.json` |
| `create-assembly.mjs` | 同上,调 `assemble.mjs`,读 `out/ui-run/<document>-assembly.json` |
| `create-all.mjs` | 串行调用 `create-part.mjs`;`--keep-going` 继续,末尾写 `summary.json` |
| `list.mjs` | 分组文本列表;`--json` 输出 `freecad-web/reducer-toolkit/catalog/v1` |
| `self-test.mjs` | 无浏览器自检:目录一致、非法 id 拒绝、前置报告结构 |
退出码统一为:`0` 通过 / `1` 产品不一致(体积或装配不匹配)/ `2` 前置缺失或参数错误。
**前置失败不是产品失败**:只有前置全部满足后的比对不一致才记为 `1`。
## 前置检查(`preflight.mjs`)
8 项:`dist`(`web/dist/index.html`)、`kernel`(wasm 产物)、`chrome`、`display`、
`playwright`、`engine`(`drive.mjs`/`assemble.mjs`)、`parts`(`out/ui-steps` 与 replay 齐全)、
`app`(`project.json` 的 `appOrigin` 可达)。其中 `app` 只作提示:不可达时
`ensureOrigin()` 会用 `tools/static-host.mjs` 在临时端口起静态服务,并把
`appOrigin` 与全部 `paths` 改写为绝对路径,生成一份**派生 project.json** 放到
`docs/current/reducer-toolkit/runtimes/<stamp>/`(`drive.mjs` 只从 project.json 读入口端口)。
## 报告字段
`docs/current/reducer-toolkit/runs/<stamp>-<id>/report.json`:
- 零件(schema `freecad-web/reducer-toolkit/part/v1`):`part{id,document,title,group}`、
`steps/stepsTotal`、`failed`、`volume`(界面实测)、`expectedVolume`(构建记录)、
`relativeError`、`volumeMatches`、`seconds`、`pageErrors`、`stillsDir`、`verdict`。
- 装配(`.../assembly/v1`):`expected{inserts,rotated}`、`inserted`、`rotated`、
`mismatches`、`links`、`fatal`、`pageErrors`、`verdict`。
- 批量(`.../batch/v1`):`items[{id,document,title,exitCode}]`、`passed/failed/blocked/skipped`。
截图落在 `web/tools/reducer-parts-course/ui-stills/<Document>/`。
## 与其它入口的关系
| 入口 | 何时用 |
|---|---|
| `tools/reducer/*`(本包) | 有头界面重建、批量、归一化报告 |
| `web/tools/cad-ui-rebuild/drive.mjs` | 底层点击引擎,本包直接调用 |
| `web/teaching/cases/secondary-reducer-pro/parts/*.mjs` | 内核建模(无浏览器、秒级),适合先验证尺寸 |
| `tools/fcweb/` | 在脚本中直接开文档/零件/装配并导出 OPFS |
| `web/teaching/console.html` | 图形化运行本包课程(每个零件一节课) |
| `web/teaching/reducer-toolkit.html` | 初学者配套讲义(生成物,勿手改) |
配套页面由 `web/tools/teaching-console/build-reducer-page.mjs` 生成,课程由
`web/tools/teaching-console/lessons.mjs` 的 `reducer` 分组定义,运行经
`web/teaching/suite-runner.mjs` 的 `reducer-part` / `reducer-assembly` 作业类型
(参数只接受 `P\d{2}`,走白名单 argv)。
## OPFS 约定
界面上建出的文档由引擎写回 OPFS;报告与截图只是证据快照,放在 `docs/current/` 与
`ui-stills/` 下,不作数据源,也不触发任何自动下载。

133
tools/reducer/catalog.mjs Normal file
View File

@@ -0,0 +1,133 @@
/**
* Canonical catalog of the 23 secondary-reducer parts.
*
* This module deliberately owns no part list of its own: it reads the project
* manifest that the shared UI driver already uses
* (web/tools/reducer-parts-course/project.json) and joins it with the two
* evidence trees that already exist on disk:
* - out/ui-steps/<Document>.json — the per-step UI actions drive.mjs replays
* - out/replay/<Document>.json — the build record, including final volume
*
* A part is only offered when both files exist, so `create-part` can never
* start a browser for a part that has nothing to replay.
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
export const REPO_ROOT = path.resolve(HERE, "../..");
export const PROJECT_DIR = path.join(REPO_ROOT, "web/tools/reducer-parts-course");
export const PROJECT_FILE = path.join(PROJECT_DIR, "project.json");
const STEPS_DIR = path.join(PROJECT_DIR, "out/ui-steps");
const RUN_DIR = path.join(PROJECT_DIR, "out/ui-run");
const STILLS_DIR = path.join(PROJECT_DIR, "ui-stills");
/** Document prefix → teaching group. Longest prefix wins. */
const GROUPS = [
{ id: "gears", label: "齿轮", prefixes: ["Gear"] },
{ id: "shafts", label: "轴", prefixes: ["Shaft"] },
{ id: "bearings", label: "轴承", prefixes: ["Bearing"] },
{ id: "keys", label: "平键", prefixes: ["Key"] },
{ id: "seals", label: "骨架油封", prefixes: ["Seal"] },
{ id: "coupling", label: "联轴器", prefixes: ["Coupling"] },
{ id: "housing", label: "箱体与箱盖", prefixes: ["Housing", "Inspection"] },
];
export function groupOf(document) {
const match = GROUPS.find((group) => group.prefixes.some((prefix) => document.startsWith(prefix)));
return match ?? { id: "other", label: "其他", prefixes: [] };
}
function readJson(file) {
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
} catch {
return null;
}
}
function stepsOf(document) {
const payload = readJson(path.join(STEPS_DIR, `${document}.json`));
return Array.isArray(payload?.steps) ? payload.steps : null;
}
function replayOf(document) {
return readJson(path.join(PROJECT_DIR, "out/replay", `${document}.json`))
?? readJson(path.join(REPO_ROOT, "web/teaching/cases/secondary-reducer-pro/out/replay", `${document}.json`));
}
function finalVolume(steps) {
const volumes = (steps ?? []).map((step) => step.volume).filter((volume) => typeof volume === "number" && volume > 0);
return volumes.length ? volumes.at(-1) : null;
}
export function projectManifest() {
const manifest = readJson(PROJECT_FILE);
if (!manifest) throw new Error(`缺少项目清单:${PROJECT_FILE}`);
return manifest;
}
/** All parts, in manifest order, enriched with step counts and recorded volume. */
export function parts() {
const manifest = projectManifest();
return (manifest.parts ?? []).map((entry) => {
const steps = stepsOf(entry.document);
const replay = replayOf(entry.document);
const group = groupOf(entry.document);
return {
id: entry.id,
document: entry.document,
title: entry.title,
group: group.id,
groupLabel: group.label,
steps: steps?.length ?? 0,
volume: finalVolume(replay?.steps),
reconstructable: Boolean(steps && steps.length && replay?.steps?.length),
stepsFile: path.relative(REPO_ROOT, path.join(STEPS_DIR, `${entry.document}.json`)),
runFile: path.relative(REPO_ROOT, path.join(RUN_DIR, `${entry.document}.json`)),
stillsDir: path.relative(REPO_ROOT, path.join(STILLS_DIR, entry.id)),
};
});
}
export function groups() {
return GROUPS.map((group) => {
const members = parts().filter((part) => part.group === group.id);
return { id: group.id, label: group.label, count: members.length, ids: members.map((part) => part.id) };
}).filter((group) => group.count > 0);
}
const ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
/**
* Resolve "P06", "p06" or "Bearing6206_Inner" to a part.
* Rejects anything that is not a plain token so a shell fragment can never be
* forwarded to the driver.
*/
export function find(key) {
if (typeof key !== "string" || !ID_PATTERN.test(key)) {
const error = new Error(`非法零件标识:${String(key).slice(0, 40)}`);
error.code = "E_PART";
throw error;
}
const wanted = key.toLowerCase();
const all = parts();
const match = all.find((part) => part.id.toLowerCase() === wanted)
?? all.find((part) => part.document.toLowerCase() === wanted);
if (!match) {
const error = new Error(`没有该零件:${key}`);
error.code = "E_PART";
throw error;
}
return match;
}
export function stats() {
const all = parts();
return {
parts: all.length,
steps: all.reduce((sum, part) => sum + part.steps, 0),
reconstructable: all.filter((part) => part.reconstructable).length,
};
}

View File

@@ -0,0 +1,119 @@
#!/usr/bin/env node
/**
* Purpose: 按组或按列表串行重建多个零件(每个零件仍是一个独立运行)。
*
* 逐件调用 tools/reducer/create-part.mjs,保持与单件完全相同的判定。
* 默认遇错即停;--keep-going 继续并在末尾给出汇总。
*
* Usage:
* node tools/reducer/create-all.mjs --group gears --dry
* node tools/reducer/create-all.mjs --parts P03,P04
* node tools/reducer/create-all.mjs --all --keep-going --slow
*
* Exit: 0 全部通过 / 1 至少一件产品失败 / 2 前置缺失或参数错误
*/
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { REPO_ROOT, find, groups, parts } from "./catalog.mjs";
const CREATE_PART = path.join(REPO_ROOT, "tools/reducer/create-part.mjs");
function parseArgs(argv) {
const options = { parts: [], group: null, all: false, keepGoing: false, dry: false, slow: false, out: null };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--parts") options.parts = String(argv[++index] ?? "").split(",").map((item) => item.trim()).filter(Boolean);
else if (arg === "--group") options.group = argv[++index] ?? null;
else if (arg === "--all") options.all = true;
else if (arg === "--keep-going") options.keepGoing = true;
else if (arg === "--dry") options.dry = true;
else if (arg === "--slow") options.slow = true;
else if (arg === "--out") options.out = path.resolve(argv[++index] ?? "");
else if (arg === "--help" || arg === "-h") {
console.log("node tools/reducer/create-all.mjs [--parts P01,P02 | --group gears | --all] [--keep-going] [--dry] [--slow] [--out <dir>]");
process.exit(0);
} else {
console.error(`未知参数:${arg}`);
process.exit(2);
}
}
if (!options.parts.length && !options.group && !options.all) {
console.error("用法:--parts P01,P02 | --group <id> | --all(分组见 node tools/reducer/list.mjs)");
process.exit(2);
}
return options;
}
function selection(options) {
if (options.parts.length) return options.parts.map((key) => find(key));
if (options.group) {
const group = groups().find((item) => item.id === options.group);
if (!group) {
console.error(`没有该分组:${options.group}(可用:${groups().map((item) => item.id).join(", ")})`);
process.exit(2);
}
return group.ids.map((key) => find(key));
}
if (options.out) {
// Reports live under the shared out dir so a whole build is one directory.
return parts();
}
return parts();
}
function runPart(part, options) {
const argv = [process.execPath, CREATE_PART, part.id];
if (options.dry) argv.push("--dry");
if (options.slow) argv.push("--slow");
if (options.out) argv.push("--out", path.join(options.out, part.id));
return new Promise((resolve) => {
const child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, stdio: "inherit" });
child.on("error", () => resolve(2));
child.on("close", (code) => resolve(code ?? 1));
});
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const selected = selection(options);
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const outDir = options.out;
const summary = { schema: "freecad-web/reducer-toolkit/batch/v1", startedAt: new Date().toISOString(), items: [] };
for (const part of selected) {
console.log(`\n=== ${part.id} ${part.document}(${part.title},${part.steps} 步)===`);
const code = await runPart(part, options);
summary.items.push({ id: part.id, document: part.document, title: part.title, exitCode: code });
if (code === 2) {
console.error(`前置缺失,停止:${part.id}`);
break;
}
if (code !== 0 && !options.keepGoing) {
console.error(`零件 ${part.id} 未通过(exit ${code}),停止。用 --keep-going 可继续。`);
break;
}
}
summary.finishedAt = new Date().toISOString();
summary.passed = summary.items.filter((item) => item.exitCode === 0).length;
summary.failed = summary.items.filter((item) => item.exitCode === 1).length;
summary.blocked = summary.items.filter((item) => item.exitCode === 2).length;
summary.skipped = selected.length - summary.items.length;
const dir = outDir ?? path.join(REPO_ROOT, "docs/current/reducer-toolkit/runs", `${stamp}-batch`);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "summary.json"), JSON.stringify(summary, null, 2));
console.log(`\n合计:通过 ${summary.passed} / 失败 ${summary.failed} / 前置 ${summary.blocked} / 未执行 ${summary.skipped}`);
console.log(`汇总:${path.relative(REPO_ROOT, path.join(dir, "summary.json"))}`);
if (summary.failed > 0) process.exit(1);
if (summary.blocked > 0 || summary.skipped > 0) process.exit(2);
process.exit(0);
}
main().catch((error) => {
console.error(`失败:${error?.message ?? error}`);
process.exit(error?.code === "E_PART" ? 2 : 1);
});

View File

@@ -0,0 +1,146 @@
#!/usr/bin/env node
/**
* Purpose: 在真实界面里把 23 个零件装配成二级减速器(有头 Chrome)。
*
* 复用 web/tools/cad-ui-rebuild/assemble.mjs:新建装配文档、逐个插入链接、
* 按构建记录的位置与旋转落位。本工具只补前置检查与归一化报告。
*
* Usage:
* node tools/reducer/create-assembly.mjs --dry
* node tools/reducer/create-assembly.mjs
* node tools/reducer/create-assembly.mjs --out <dir>
*
* Exit: 0 全部链接插入且无失配 / 1 有失配(产品问题)/ 2 前置缺失
*/
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { REPO_ROOT, PROJECT_DIR, projectManifest } from "./catalog.mjs";
import { ensureOrigin, preflight } from "./preflight.mjs";
const ASSEMBLE = path.join(REPO_ROOT, "web/tools/cad-ui-rebuild/assemble.mjs");
function parseArgs(argv) {
const options = { headed: true, dry: false, serve: true, out: null, json: false };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--headed") options.headed = true;
else if (arg === "--headless") options.headed = false;
else if (arg === "--dry") options.dry = true;
else if (arg === "--no-serve") options.serve = false;
else if (arg === "--json") options.json = true;
else if (arg === "--out") options.out = path.resolve(argv[++index] ?? "");
else if (arg === "--help" || arg === "-h") {
console.log("node tools/reducer/create-assembly.mjs [--headed|--headless] [--dry] [--no-serve] [--out <dir>] [--json]");
process.exit(0);
} else {
console.error(`未知参数:${arg}`);
process.exit(2);
}
}
return options;
}
function stamp() {
return new Date().toISOString().replace(/[:.]/g, "-");
}
function runAssembly(options, projectDir) {
const argv = [process.execPath, ASSEMBLE, "--project", projectDir];
if (options.headed) argv.push("--headed");
if (options.dry) argv.push("--dry");
return new Promise((resolve) => {
const child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, stdio: ["ignore", "pipe", "pipe"] });
let tail = "";
child.stdout.on("data", (chunk) => { process.stdout.write(chunk); tail = (tail + chunk.toString("utf8")).slice(-4000); });
child.stderr.on("data", (chunk) => process.stderr.write(chunk));
child.on("error", (error) => resolve({ code: -1, error, tail }));
child.on("close", (code) => resolve({ code: code ?? -1, tail }));
});
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const manifest = projectManifest();
const report = await preflight();
if (options.dry) {
const assembly = manifest.assembly ?? {};
console.log(`装配:${assembly.document ?? "SecondaryReducer"}(接地 ${assembly.groundDocument ?? "—"})`);
for (const check of report.checks) console.log(` ${check.ok ? "✓" : "✗"} ${check.id}: ${check.detail}`);
console.log(report.ok ? "前置全部满足(dry run,未启动浏览器)" : "前置未满足(dry run)");
process.exit(report.ok ? 0 : 2);
}
if (!report.ok) {
for (const check of report.checks.filter((item) => !item.ok && item.id !== "app")) {
console.error(`前置缺失 ${check.id}: ${check.detail} → ${check.fix}`);
}
console.error("未启动浏览器(前置失败不是产品失败)。");
process.exit(2);
}
let origin = null;
if (options.serve) {
try {
origin = await ensureOrigin(report.origin);
console.log(origin.started ? `已为 ${origin.origin} 启动静态服务` : `复用已在运行的应用入口 ${origin.origin}`);
} catch (error) {
console.error(`前置缺失:${error.message}`);
process.exit(2);
}
}
const startedAt = Date.now();
let result;
try {
result = await runAssembly(options, origin?.projectDir ?? PROJECT_DIR);
} finally {
await origin?.close();
}
const document = manifest.assembly?.document ?? "SecondaryReducer";
const uiReportFile = path.join(PROJECT_DIR, "out/ui-run", `${document}-assembly.json`);
const uiReport = (() => {
try {
return JSON.parse(fs.readFileSync(uiReportFile, "utf8"));
} catch {
return null;
}
})();
const verdict = !uiReport ? "run_fail"
: uiReport.fatal || uiReport.mismatches?.length ? "product_fail"
: uiReport.inserted < (uiReport.expected?.inserts ?? Infinity) ? "product_fail"
: "pass";
const dir = options.out ?? path.join(REPO_ROOT, "docs/current/reducer-toolkit/runs", `${stamp()}-assembly`);
fs.mkdirSync(dir, { recursive: true });
const summary = {
schema: "freecad-web/reducer-toolkit/assembly/v1",
document,
groundDocument: uiReport?.groundDocument ?? manifest.assembly?.groundDocument ?? null,
expected: uiReport?.expected ?? null,
inserted: uiReport?.inserted ?? null,
rotated: uiReport?.rotated ?? null,
mismatches: uiReport?.mismatches?.length ?? null,
seconds: uiReport?.seconds ?? Math.round((Date.now() - startedAt) / 1000),
fatal: uiReport?.fatal ?? null,
pageErrors: uiReport?.pageErrors ?? [],
driverExitCode: result.code,
verdict,
finishedAt: new Date().toISOString(),
};
fs.writeFileSync(path.join(dir, "report.json"), JSON.stringify(summary, null, 2));
if (options.json) console.log(JSON.stringify(summary));
else {
console.log(`装配 ${document}: ${verdict}(插入 ${summary.inserted}/${summary.expected?.inserts ?? "?"},失配 ${summary.mismatches ?? "—"},${summary.seconds}s)`);
console.log(`报告:${path.relative(REPO_ROOT, path.join(dir, "report.json"))}`);
}
process.exit(verdict === "pass" ? 0 : verdict === "product_fail" ? 1 : 2);
}
main().catch((error) => {
console.error(`失败:${error?.message ?? error}`);
process.exit(1);
});

View File

@@ -0,0 +1,174 @@
#!/usr/bin/env node
/**
* Purpose: 在真实界面里重建二级减速器的一个零件(有头 Chrome)。
*
* 本工具只做三件事:校验前置、定位该零件的界面步骤、调用既有引擎
* web/tools/cad-ui-rebuild/drive.mjs 逐步点击,最后把结果归一化成一份报告。
* 步骤数据、点击逻辑与体积比对全部复用已有实现,这里不复制。
*
* Usage:
* node tools/reducer/create-part.mjs P06
* node tools/reducer/create-part.mjs Bearing6206_Inner --slow
* node tools/reducer/create-part.mjs P21 --dry # 只检查前置与步骤
* node tools/reducer/create-part.mjs P06 --out <dir> # 报告目录
*
* Exit: 0 通过 / 1 界面上建出的体积与构建记录不一致(产品问题)/ 2 前置缺失
*/
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { REPO_ROOT, PROJECT_DIR, find, parts } from "./catalog.mjs";
import { ensureOrigin, preflight } from "./preflight.mjs";
const DRIVE = path.join(REPO_ROOT, "web/tools/cad-ui-rebuild/drive.mjs");
const RUN_FILE = (document) => path.join(PROJECT_DIR, "out/ui-run", `${document}.json`);
function parseArgs(argv) {
const options = { key: null, headed: true, slow: false, dry: false, serve: true, out: null, json: false };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === "--headed") options.headed = true;
else if (arg === "--headless") options.headed = false;
else if (arg === "--slow") options.slow = true;
else if (arg === "--dry") options.dry = true;
else if (arg === "--no-serve") options.serve = false;
else if (arg === "--json") options.json = true;
else if (arg === "--out") options.out = path.resolve(argv[++index] ?? "");
else if (arg === "--help" || arg === "-h") {
console.log("node tools/reducer/create-part.mjs <P01|Document> [--headed|--headless] [--slow] [--dry] [--no-serve] [--out <dir>] [--json]");
process.exit(0);
} else if (arg.startsWith("--")) {
console.error(`未知参数:${arg}`);
process.exit(2);
} else if (!options.key) options.key = arg;
else {
console.error(`多余的参数:${arg}`);
process.exit(2);
}
}
if (!options.key) {
console.error("用法:node tools/reducer/create-part.mjs <P01|Document> [--slow] [--dry]");
process.exit(2);
}
return options;
}
function runDir(options, part) {
const root = options.out ?? path.join(REPO_ROOT, "docs/current/reducer-toolkit/runs");
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
return path.join(root, `${stamp}-${part.id}`);
}
function line(text) {
process.stdout.write(`${text}\n`);
}
/** Spawn the shared driver and forward its stdout/stderr unchanged. */
function drive(part, options, projectDir) {
const argv = [process.execPath, DRIVE, "--project", projectDir, part.id];
if (options.headed) argv.push("--headed");
if (options.slow) argv.push("--slow");
return new Promise((resolve) => {
const child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, stdio: ["ignore", "pipe", "pipe"] });
child.stdout.on("data", (chunk) => process.stdout.write(chunk));
child.stderr.on("data", (chunk) => process.stderr.write(chunk));
child.on("error", (error) => resolve({ code: -1, error }));
child.on("close", (code) => resolve({ code: code ?? -1 }));
});
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const part = find(options.key);
const report = await preflight();
if (options.dry) {
line(`零件 ${part.id} ${part.document}(${part.title}):${part.steps} 步,记录体积 ${part.volume ?? "—"}`);
for (const check of report.checks) line(` ${check.ok ? "✓" : "✗"} ${check.id}: ${check.detail}`);
line(report.ok ? "前置全部满足(dry run,未启动浏览器)" : "前置未满足(dry run)");
process.exit(report.ok ? 0 : 2);
}
if (!report.ok) {
for (const check of report.checks.filter((item) => !item.ok && item.id !== "app")) {
console.error(`前置缺失 ${check.id}: ${check.detail} → ${check.fix}`);
}
console.error("未启动浏览器(前置失败不是产品失败)。可先跑 --dry 查看全部检查。");
process.exit(2);
}
if (!part.reconstructable) {
console.error(`前置缺失:${part.document} 缺少界面步骤或构建记录,先运行 node web/tools/reducer-parts-course/build-ui-steps.mjs`);
process.exit(2);
}
line(`零件 ${part.id} ${part.document}(${part.title}):${part.steps} 步,记录体积 ${part.volume ?? "—"}`);
let origin = null;
if (options.serve) {
try {
origin = await ensureOrigin(report.origin);
line(origin.started ? `已为 ${origin.origin} 启动静态服务` : `复用已在运行的应用入口 ${origin.origin}`);
} catch (error) {
console.error(`前置缺失:${error.message}`);
process.exit(2);
}
}
const startedAt = Date.now();
let result;
try {
result = await drive(part, options, origin?.projectDir ?? PROJECT_DIR);
} finally {
await origin?.close();
}
const uiRun = (() => {
try {
return JSON.parse(fs.readFileSync(RUN_FILE(part.document), "utf8"));
} catch {
return null;
}
})();
const dir = options.out ?? runDir(options, part);
fs.mkdirSync(dir, { recursive: true });
const verdict = !uiRun ? "run_fail"
: uiRun.failed > 0 || uiRun.volumeMatches === false ? "product_fail"
: "pass";
const summary = {
schema: "freecad-web/reducer-toolkit/part/v1",
part: { id: part.id, document: part.document, title: part.title, group: part.group },
steps: uiRun?.steps ?? part.steps,
stepsTotal: uiRun?.stepsTotal ?? part.steps,
failed: uiRun?.failed ?? null,
volume: uiRun?.volume ?? null,
expectedVolume: uiRun?.expected ?? part.volume,
relativeError: uiRun?.relativeError ?? null,
volumeMatches: uiRun?.volumeMatches ?? null,
seconds: uiRun?.seconds ?? Math.round((Date.now() - startedAt) / 1000),
pageErrors: uiRun?.pageErrors ?? [],
stillsDir: part.stillsDir,
driverExitCode: result.code,
verdict,
finishedAt: new Date().toISOString(),
};
fs.writeFileSync(path.join(dir, "report.json"), JSON.stringify(summary, null, 2));
if (options.json) line(JSON.stringify(summary));
else {
line(`零件 ${part.id}: ${verdict}(${summary.steps}/${summary.stepsTotal} 步,体积 ${summary.volume ?? "—"},${summary.seconds}s)`);
line(`报告:${path.relative(REPO_ROOT, path.join(dir, "report.json"))}`);
if (summary.stillsDir) line(`截图:${summary.stillsDir}`);
}
if (verdict === "pass") process.exit(0);
if (verdict === "product_fail") {
console.error(`体积不一致:界面 ${summary.volume} / 记录 ${summary.expectedVolume}(相对误差 ${summary.relativeError})`);
process.exit(1);
}
console.error("驱动未产出界面运行报告,按前置/运行失败处理。");
process.exit(2);
}
main().catch((error) => {
console.error(`失败:${error?.message ?? error}`);
process.exit(error?.code === "E_PART" ? 2 : 1);
});

47
tools/reducer/list.mjs Normal file
View File

@@ -0,0 +1,47 @@
#!/usr/bin/env node
/**
* Purpose: 列出二级减速器的 23 个零件与分组(供人看,也供脚本读)。
*
* Usage:
* node tools/reducer/list.mjs
* node tools/reducer/list.mjs --group gears
* node tools/reducer/list.mjs --json
*
* Exit: 0
*/
import { groups, parts, stats } from "./catalog.mjs";
const argv = process.argv.slice(2);
if (argv.includes("--help") || argv.includes("-h")) {
console.log("node tools/reducer/list.mjs [--group <id>] [--json]");
process.exit(0);
}
const groupFilter = argv.includes("--group") ? argv[argv.indexOf("--group") + 1] : null;
const asJson = argv.includes("--json");
const all = parts();
const selected = groupFilter ? all.filter((part) => part.group === groupFilter) : all;
const summary = stats();
if (asJson) {
console.log(JSON.stringify({
schema: "freecad-web/reducer-toolkit/catalog/v1",
stats: summary,
groups: groups(),
parts: selected.map(({ id, document, title, group, groupLabel, steps, volume, reconstructable }) => ({
id, document, title, group, groupLabel, steps, volume, reconstructable,
})),
}, null, 2));
process.exit(0);
}
for (const group of groups()) {
const members = selected.filter((part) => part.group === group.id);
if (!members.length) continue;
console.log(`\n${group.label}(${group.id})`);
for (const part of members) {
const volume = part.volume == null ? "—" : part.volume.toFixed(1);
console.log(` ${part.id} ${part.document.padEnd(30)} ${part.title.padEnd(28)} ${String(part.steps).padStart(2)} 步 体积 ${volume}${part.reconstructable ? "" : " (不可界面重建)"}`);
}
}
console.log(`\n合计 ${summary.parts} 件 / ${summary.steps} 步 / 可界面重建 ${summary.reconstructable} 件`);

153
tools/reducer/preflight.mjs Normal file
View File

@@ -0,0 +1,153 @@
/**
* Prerequisites for a headed reducer rebuild.
*
* Iron law: a missing dist, kernel, Chrome, DISPLAY or dev server is a
* prerequisite failure, never a product failure. `create-*` exits 2 for these
* and only ever exits 1 after the browser actually ran.
*/
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { REPO_ROOT, PROJECT_DIR, parts, projectManifest, stats } from "./catalog.mjs";
import { findChrome, startStaticHost } from "../static-host.mjs";
const require = createRequire(path.join(REPO_ROOT, "web/package.json"));
function originPort(origin) {
try {
const url = new URL(origin);
return Number(url.port || (url.protocol === "https:" ? 443 : 80));
} catch {
return 0;
}
}
async function originReachable(origin, timeoutMs = 1500) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(`${origin}/index.html`, { signal: controller.signal, cache: "no-store" });
return response.ok;
} catch {
return false;
} finally {
clearTimeout(timer);
}
}
export async function preflight() {
const checks = [];
const add = (id, ok, detail, fix) => checks.push({ id, ok, detail, fix });
const manifest = projectManifest();
const origin = manifest.appOrigin;
const distIndex = path.join(REPO_ROOT, "web/dist/index.html");
add("dist", fs.existsSync(distIndex), fs.existsSync(distIndex) ? "web/dist/index.html 已就绪" : "web/dist/index.html 不存在",
"cd web && npx vite build");
const wasm = ["web/dist/kernel", "web/public/kernel"].flatMap((rel) => {
try {
return fs.readdirSync(path.join(REPO_ROOT, rel)).filter((name) => name.endsWith(".wasm"));
} catch {
return [];
}
});
add("kernel", wasm.length > 0, wasm.length ? `内核产物 ${wasm.length} 个 .wasm` : "未找到内核 .wasm 产物",
"cd web && node ../tools/sync-assets.mjs");
let chrome = null;
try {
chrome = findChrome();
} catch {
chrome = null;
}
add("chrome", Boolean(chrome), chrome || "未找到 Chrome/Chromium", "export FREECAD_CHROME=/usr/bin/google-chrome");
const display = process.env.DISPLAY || "";
const displayOk = Boolean(display);
add("display", displayOk, display ? `DISPLAY=${display}` : "DISPLAY 未设置(有头运行需要)", "DISPLAY=:1 node tools/reducer/create-part.mjs …");
let playwright = null;
try {
playwright = require.resolve("playwright");
} catch {
playwright = null;
}
add("playwright", Boolean(playwright), playwright ? "web/node_modules 可解析 playwright" : "web/node_modules 中找不到 playwright",
"cd web && npm install");
const engine = ["web/tools/cad-ui-rebuild/drive.mjs", "web/tools/cad-ui-rebuild/assemble.mjs", "web/tools/cad-ui-rebuild/manifest.mjs"];
const missingEngine = engine.filter((rel) => !fs.existsSync(path.join(REPO_ROOT, rel)));
add("engine", missingEngine.length === 0, missingEngine.length ? `缺少共享引擎:${missingEngine.join(", ")}` : "界面重建引擎完整",
"git status web/tools/cad-ui-rebuild");
const summary = stats();
add("parts", summary.reconstructable === summary.parts,
`${summary.reconstructable}/${summary.parts} 个零件具备界面步骤与构建记录(共 ${summary.steps} 步)`,
"node web/tools/reducer-parts-course/build-ui-steps.mjs");
const originOk = await originReachable(origin);
add("app", originOk, originOk ? `应用入口可达:${origin}` : `应用入口不可达:${origin}(create-part 会自动起静态服务)`,
`cd web && npx vite build && node ../tools/static-host.mjs --root dist --port ${originPort(origin) || 5180}`);
return {
ok: checks.every((check) => check.ok || check.id === "app"),
checks,
origin,
projectDir: PROJECT_DIR,
stats: summary,
};
}
/**
* Write a one-off project manifest that keeps the real paths but points at a
* different app origin. The driver reads appOrigin from project.json only, so
* this is the least invasive way to run it without touching the checked-in
* manifest (port 5180 on this machine is occupied by an unrelated server).
*/
function derivedProject(originMW) {
const raw = projectManifest();
const base = {
...raw,
appOrigin: originMW,
paths: Object.fromEntries(Object.entries(raw.paths ?? {}).map(([key, value]) => [key, path.resolve(PROJECT_DIR, value)])),
};
const dir = path.join(REPO_ROOT, "docs/current/reducer-toolkit/runtimes", new Date().toISOString().replace(/[:.]/g, "-"));
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "project.json"), `${JSON.stringify(base, null, 2)}\n`);
return dir;
}
/**
* Make sure something serves the built app, reusing tools/static-host.mjs.
*
* Returns the project directory the driver should use: the checked-in one when
* its appOrigin already serves the app, otherwise a derived manifest in the run
* evidence tree that points at the ephemeral host we just started.
*/
export async function ensureOrigin(origin = projectManifest().appOrigin) {
if (await originReachable(origin)) return { origin, started: false, projectDir: PROJECT_DIR, close: async () => {} };
const dist = path.join(REPO_ROOT, "web/dist");
if (!fs.existsSync(path.join(dist, "index.html"))) {
throw Object.assign(new Error(`web/dist/index.html 不存在,无法为 ${origin} 起服务`), { code: "E_PREFLIGHT" });
}
// Preferred: take over the manifest port so the manifest itself stays valid.
const port = originPort(origin) || 5180;
try {
const host = await startStaticHost(dist, "index.html", port);
if (host.origin === origin) {
return { origin: host.origin, started: true, projectDir: PROJECT_DIR, close: () => host.close() };
}
await host.close();
} catch {
/* port busy (or refused) — fall through to an ephemeral host */
}
const host = await startStaticHost(dist, "index.html", 0);
return { origin: host.origin, started: true, projectDir: derivedProject(host.origin), close: () => host.close() };
}
export { parts };

View File

@@ -0,0 +1,91 @@
#!/usr/bin/env node
/**
* Purpose: 无浏览器自测二级减速器工具包(目录、分组、前置、参数校验)。
*
* Usage: node tools/reducer/self-test.mjs
* Exit: 0 全部通过 / 1 首个失败
*/
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { REPO_ROOT, PROJECT_FILE, find, groups, parts, projectManifest, stats } from "./catalog.mjs";
import { preflight } from "./preflight.mjs";
let failures = 0;
function check(name, fn) {
try {
fn();
console.log(`ok ${name}`);
} catch (error) {
failures += 1;
console.error(`FAIL ${name}\n ${error instanceof Error ? error.message.split("\n")[0] : error}`);
}
}
function throwsCode(fn, code) {
try {
fn();
} catch (error) {
assert.equal(error.code, code, `expected ${code}, got ${error.code ?? error.message}`);
return;
}
throw new Error(`expected ${code}, nothing thrown`);
}
check("project manifest is the single source", () => {
const manifest = projectManifest();
assert.equal(manifest.parts.length, 23);
assert.ok(fs.existsSync(PROJECT_FILE));
});
check("catalog joins steps and replay for every part", () => {
const all = parts();
assert.equal(all.length, 23);
assert.equal(stats().steps, 104);
for (const part of all) {
assert.ok(part.steps > 0, `${part.id} steps`);
assert.ok(part.volume > 0, `${part.id} volume`);
assert.ok(part.reconstructable, `${part.id} reconstructable`);
assert.ok(fs.existsSync(path.join(REPO_ROOT, part.stepsFile)), `${part.id} stepsFile`);
}
});
check("groups cover all 23 parts", () => {
const grouped = groups().reduce((sum, group) => sum + group.count, 0);
assert.equal(grouped, 23);
assert.ok(groups().some((group) => group.id === "bearings" && group.count === 9));
assert.ok(groups().some((group) => group.id === "gears" && group.count === 2));
});
check("find resolves by id and by document", () => {
assert.equal(find("P06").document, "Bearing6206_Inner");
assert.equal(find("p06").document, "Bearing6206_Inner");
assert.equal(find("HousingCover").id, "P22");
});
check("find rejects unknown ids and shell fragments", () => {
throwsCode(() => find("P99"), "E_PART");
throwsCode(() => find("; rm -rf /"), "E_PART");
throwsCode(() => find("P01 --headed"), "E_PART");
throwsCode(() => find(""), "E_PART");
throwsCode(() => find(undefined), "E_PART");
});
// preflight is async, so it runs before the assertions that depend on it.
const report = await preflight();
check("preflight checks are well formed", () => {
assert.equal(typeof report.ok, "boolean");
assert.ok(report.checks.length >= 7, `checks ${report.checks.length}`);
for (const item of report.checks) assert.equal(typeof item.ok, "boolean", item.id);
assert.match(report.origin, /^http:\/\/127\.0\.0\.1:\d+$/);
assert.equal(report.stats.parts, 23);
for (const id of ["dist", "kernel", "chrome", "display", "playwright", "engine", "parts", "app"]) {
assert.ok(report.checks.some((item) => item.id === id), `missing check ${id}`);
}
});
if (failures) {
console.error(`\nself-test: ${failures} failure(s)`);
process.exit(1);
}
console.log(`self-test: OK(${stats().parts} 件 / ${stats().steps} 步;前置 ${report.ok ? "全部满足" : "有缺项"})`);