teaching: run lessons in-app through an iframe-driven console

The teaching console now lives inside Web FreeCAD: web/teaching-console.html
hosts the workbench in a same-origin iframe and drives its DOM directly, with
no Node server and no spawned Chrome. The driver modules run in the framed
page's own realm (bridge.ts publishes window.__teaching), so the proven
driver/assembly code is reused unchanged and the CSP without 'unsafe-eval' is
never crossed.

- steps.ts globs both courses' ui-steps records (skipping their index.json
  manifests) so each lesson downloads only its own chunk
- runner.ts checks prerequisites in dependency order, then runs part or
  assembly lessons; a pass stores the FCStd in OPFS freecad-documents under
  the course document name, which is what assembly lessons consume
- assembly lessons insert, joint, solve and save through lib/assembly.mjs;
  insertLink falls back to UI-suffixed object names (Body1 for Body)
- check-inapp-console.mjs (npm run check:console-inapp) is green: preflight,
  P01 volume within 6e-13, OPFS evidence, both viewports
- run-inapp-lessons.mjs runs a whole course in one browser; reducer 23 parts
  + assembly and carrier 20 parts + assembly all pass in-browser

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 09:18:26 +08:00
parent 3a3077c089
commit fd37b92fd9
22 changed files with 7165 additions and 14 deletions

537
nextTask.md Normal file
View File

@@ -0,0 +1,537 @@
# FreeCAD Web 对标续接清单
2026-11-26 教学控制台已搬进 Web FreeCAD 本体:`web/teaching-console.html` + `web/src/teaching/{console-page,runner,bridge,in-page-page,steps,report-store,types}`,浏览器内同源 iframe 直接驱动工作台 DOM,不需要 Node 教学服务、不启动外部 Chrome、无 `/api/console/*`。**相对原计划的偏差**:计划的 §1「把 driver 的 page.evaluate 改写成 (win,doc) 具名函数、两套适配器」没有做——CSP 无 `'unsafe-eval'`(`web/vite.config.ts:15`),跨 realm 字符串化本来就走不通;改为把 driver 模块直接 import 进工作台页 realm(`bridge.ts` 发布 `window.__teaching`),`document` 就是被测页,`evaluate` 是普通函数调用,driver/assembly 零改动复用。`web/tsconfig.json` 增 `allowJs`(driver 是 .mjs)与 `resolveJsonModule`(`lessons.json`)。步骤数据由 `steps.ts` 用 `import.meta.glob` 直接引用两个课程的 `out/ui-steps/*.json`(跳过各自目录下的 `index.json` 清单),Vite 按文件出 chunk。门禁 `web/tools/teaching-console/check-inapp-console.mjs`(`npm run check:console-inapp`)全绿:环境自检 pass、P01 在 iframe 里真建模 4/4 步、体积相对误差 5.78e-13、报告写 OPFS `freecad-exports`、`Gear2_80T.FCStd` 落 `freecad-documents`、双 viewport 无溢出;批量驱动 `run-inapp-lessons.mjs --group|--lessons` 同一浏览器内按序跑整课(OPFS 在同一会话内累积,装配课因此有源件)。零件课通过后自动用工作台自带「保存 FCStd 到 OPFS」按钮存盘,再按课程文档名重存(FCStd 文档名取自文件名),这是装配前置。已修两个真实缺陷:两课程同名 `ui-steps/index.json` 被当成 document、页内 `click` 不等控件 enabled(内核启动期点「新建文档」必抛错)。**残余**:`check:carrier-live` 未复验;`run-inapp-lessons.mjs` 的 `--profile` 目录(如 `/tmp/tc-profile-5183`)是浏览器内 OPFS 跨次运行的必要条件,正式环境用真实浏览器 profile 即可。复跑入口:`node web/tools/teaching-console/run-inapp-lessons.mjs --group reducer|carrier --profile <dir>`。
2026-09-09 17:24:Start 官方 SVG 导入与浏览器 Worker 路由已接通,复用 Materials/Part 和 Draft `importSVG`。矩形、圆、折线、多边形、圆弧、变换、混合图形、失败恢复通过;Start 三项和 Draft 四项真实验收通过。Start/Draft 排除误嵌入的编译静态库、字节码缓存、桌面翻译后共减少约 209 MB,原文件保留,不重编译 OCCT。当前有效快照 123/1504;证据、耗时和限制见 `docs/current/start-svg-delivery.md`,后续直接复用。
2026-09-09 16:20:TechDraw 参数、容器策略、响应校验已从共用分发器移入 `web/src/techdraw-desktop-adapter.ts`,后续该模块适配继续编辑此文件,避免又触发全部模块证据失效。Sandbox 已改用真实当前多对象文档保存重开,创建/保存共用 `sandbox.worker.ts`,两项 1.897 秒通过;不再用固定 42 的样例证明业务完成。PartDesign 边身份已修、11 项通过。最新证据、批量复验及边界集中于 `docs/current/partdesign-edge-identity-fix.md`,全项目快照 117/1504,后台继续运行。
2026-09-09 15:45:Fillet/Chamfer 的边身份问题已闭环。StringHasher 不再把 `g1v1` 等无效 IndexedName 留下的数字当作哈希索引;保留真实原生边身份,不按编号重绑。PartDesign 11 项正式通过,连续尺寸编辑、撤销重做、FCStd 重开专项回归通过,两个原始故障均已 resolved。使用 `docs/current/partdesign-edge-identity-fix.md` 的当前证据继续其它业务,下方旧阻塞说明仅作历史。后台未暂停。
2026-09-09 14:20:Revolution/Groove 已在同一 PartDesign 文档中完成参数、原点轴、关联重算、撤销重做及 FCStd/OPFS 闭环。正式 11 项中 9 项通过;Fillet/Chamfer 在 Pad 长度变化后出现原生 `Invalid edge link`,仍失败,最小复现和拓扑数据见 `docs/current/partdesign-finishing-delivery.md`。不要重做已通过旋转/切槽,不得按 Edge 编号强行重绑定。自动构建两处入口已加入构建目录互斥;人工增量构建使用 `tools/web_build_lock.py -- cmake --build ...`,后台已恢复。
2026-09-09 PartDesign 主线:现有 PartDesign WASM 已接通 Body、矩形/圆形全约束草图、真实 Pad/Pocket、依赖重算、原生事务、FCStd/OPFS、多文档切换及旧 AdditiveBox 文件打开。四项桌面业务、一个新增文档业务和原有两项回归共七项通过,耗时 20.689 秒。完整范围新增文档记录后为 1504 项;当前进度以实时审计为准。复用 `docs/current/partdesign-profile-delivery.md` 和该工作区继续其它模式/特征,不重做本轮适配。后台父进程和 watchdog 已恢复。
2026-09-09 11:24:主工作区新增原生 Fuse/Cut/Common、XYZ 平移、撤销重做及依赖保持的 FCStd/OPFS 重开编辑。已修 WASM 布尔并行阻塞、局部异常捕获、空材质继承和半文件发布;不要重做几何算法。Part 18 项、Web 10 项通过,共用分发器变化后直接批量恢复 59 项已有结果。有效验收 93/1503,剩余 1410;详见 `docs/current/part-boolean-delivery.md`。继续既定 Sketcher/PartDesign 用户文档主链,后台按自身检查点推进,复验不计新增业务。
2026-09-08 铁律统一入口:先读 `docs/WEB_BUSINESS_MIGRATION_RULES.md`,再核对当前检查点。用户最新要求优先,其次是铁律、既定方案操作步骤和历史任务卡。下方旧条款只保留追溯,冲突不得覆盖当前铁律。
执行要点:直接利用已编译 WASM;DXF 复用 FreeCAD `src/Mod/Import/App/dxf` 的 C++ 实现与有效证据,不重新移植或寻找旧 Python DXF 库。先接线和本地针对性测试,明确缺陷才增量重建;不要求用户提交源码。恢复使用 `docs/current/scheduler-context.json` 的批次、指纹、首错与下一步,不重复全库读取。实际交付与重复验收、回执刷新、调度轮数分别记账。
2026-09-09 10:20 主工作区业务:已接通原生圆柱、圆锥、球、圆环的参数/角度编辑、同文档重算、Three.js 显示、FCStd/OPFS 保存重开和移除。四项桌面业务新增有效证据,Part 新旧合计 15 项与 Web 工作区 10 项回归通过。原生目标为已有 DocumentProbe,不重编译 OCCT。模块合同 buildOverrides 与分组使文档业务不误建 PartBoxProbe;实际目标源码也纳入指纹。详情见 `docs/current/part-primitives-delivery.md`,后续直接复用。
2026-09-09 09:42 业务推进:Points 四项、OpenSCAD 两项已取得当前真实证据并同步发布。Points 不再被固定三点 Facade 限制;OpenSCAD 接入已提供的 C++ DXF reader 与 Part/OCCT 成面,不再走旧 Python DXF 链。图层名称保留与 Draft 显示分组已分离,默认桌面行为保留。当前总数快照 79/1503,不代表全部移植完成;细节与证据见 `docs/current/points-openscad-delivery.md`。原 watchdog 已恢复,继续其余业务,不重做这些已通过部分。
2026-09-09 08:46 吞吐修复:调度已使用 `delivery-workflow-first-v3`,业务恢复连续两次无结果后安排其它模块缺用例的开发包,原失败和完整范围保留。统一 runner 完整捕获大报告,避免 Node 管道短写损坏 JSON 导致真实成功整批打回。TechDraw 五项 9.906 秒通过;新补 Spreadsheet CSV 两项 1.462 秒通过,没有重编译 WASM。实测和剩余缺口见 `docs/current/migration-throughput-fix.md`;不要把这些恢复结果算成整个项目完成或重做 DXF/OCCT。
2026-09-09 实际修复:Part 的 180 秒阻塞已定位为 MeshCore 递归异步排序耗尽 WASM pthread 池,并在 `src/Mod/Mesh/App/Core/Functional.h` 修复;已增量链接并发布 Part、Mesh。Part 11 项当前业务确认通过,Mesh 7 项通过,保留原始失败和带指纹证据。详细结果与续接策略见 `docs/current/part-mesh-business-unblock.md`。不得根据历史“OBJ 未实现/仍超时”说明重做已通过部分;几何内核使用 OCCT WASM,显示使用 Three.js。
2026-09-09 TechDraw 浏览器解阻:已修正生成的 Worker 路由和取消状态契约,创建、图像任务、保存共享现有原生文档;三项正式业务组 9.071 秒通过,未重编译 OCCT/WASM。见 `docs/current/techdraw-route-unblock.md`,不要按历史 45 秒 `Runtime.evaluate` 超时重做内核。OCCT WASM 已提供,几何算法统一到该唯一内核出口;实际全项目入口贯通需按真实调用确认,不能凭依赖名称宣称完成。
本文件是项目级续接入口。以后用户输入:
```text
按 nextTask.md 接续执行
```
执行者必须从本文件的“当前检查点”开始,先校验机器状态,再按任务卡依赖连续执行,不等待确认,不重复已完成任务,不把未验证能力写成通过。
## 2026-09-07 功能业务移植要求(历史补充)
2026-09-08 项目定位与复用铁律:“本项目是将桌面版的 FreeCAD 移植到 WEB FreeCAD,前期已经做了大部分工作,要充分利用上。” 后续必须承接已有源码移植、适配、模块 WASM、构建缓存、接线、用例和有效证据,只补真实缺口,不得从零重写。缺少当前业务验收证据不等于已有工作未完成;按 `docs/WEB_BUSINESS_MIGRATION_RULES.md` 的“项目定位与已有成果复用铁律”分别记录实现、产物及业务结果。
2026-09-08 用户已明确确认:“我已经提供了桌面版 FreeCAD 的源码和资料。” 所有人工、无人值守及优化回合必须继承这一前提,先按 `docs/current/provided-source-index.md` 使用 `freecad-source` 桌面源码和既有资料、实现、产物及证据。不得把未检索或路径错误当作未提供,不得重复索要或从零重写;发现本地可修复问题应立即定点修复并核对实际结果,不能只监测或等待。执行 `docs/WEB_BUSINESS_MIGRATION_RULES.md` 的“源码与资料优先铁律”。
2026-09-08 无人值守模式以 `docs/UNATTENDED_WORKFLOW.md` 为当前操作说明:自动诊断缺口、完整应用接入工作包、模块级停滞冷却和真实结果闭环。不得把“换任务”本身计为业务结果。已补齐的 CAM JSON 刀轨业务及其证据直接复用。
2026-09-08 失败处理授权:从现在分类,随模块业务同步闭环,最终完成前对账。执行 `docs/FAILURE_RECONCILIATION_POLICY.md`:模块工作包带入相关失败,切换模块安排小批对账;保留原始账本,禁止盲目重跑旧 API gate、删除失败或只写通过元数据。最终还须通过 `tools/failure_reconciliation.py --check`。本节覆盖下方旧的“历史失败全部冻结到最终验证”条款。
坚持以“功能模块业务、功能路由”带动全部移植。执行细则见 `docs/WEB_BUSINESS_MIGRATION_RULES.md`,本节覆盖下方旧策略中的冲突条款。
保留并复用既有源码、回执、WASM、构建缓存和用例;补齐漏列桌面业务,被入口阻断的记录重新排队。846/791 不是分母上限。路由、构建回执和业务完成分开记录;业务完成依赖实际输入/结果证据,不依赖逐 API 数量或历史 Full Parity gate。
持续 planner 依次处理功能路由、格式、React 集成和业务结果确认。外层仅确认当前模块业务,复用指纹匹配的旧证据;历史“不执行验证”不禁止这项必要的业务结果确认。禁止为了消除阻断而仅移除策略保护、添加整族完成标记或返回固定样例。
2026-09-07 后续耗时优化:达到源码读取预算只限制额外检索,不终止尚未编辑的回合;使用已有完整源码片段完成编辑并正常结束,以便复用上下文。没有工具活动的空响应重试保留此前干净会话,发生工具活动、补丁冲突或上下文损坏时仍丢弃不可靠会话。工作包必须包含实际编辑位置和完整源码行。
无人值守防空转:`docs/current/scheduler-progress.json` 按业务 ID 记录新增路由、构建回执和业务结果。连续三次没有新结果的业务默认冷却 300 秒,重复停滞延长至最多 3600 秒;期间调度其他模块或已有前提的格式、产品、业务确认任务,冷却业务不计为完成。所有候选均冷却时显示 `waiting_for_retry`,不启动无任务的模型回合。服务退避单独持久化,重启不清零;代码修改本身不等同于业务完成。混合业务批次按同模块剩余任务合并链接,切换构建目标前刷新上一目标的待构建产物。
2026-09-08 自动发现与修复:续接刷新、保留批次、预检和模型启动必须检查当前冷却 ID;保留批次快速路径不得绕过冷却。watchdog 每轮独立检查新模型回合是否错误执行冷却记录,发现后写 `scheduler-recovery-request.json`,等待正在执行的工具结束,再自动重启和重排。恢复请求与次数保留可见;不通过删除未完成业务、伪造回执或反复启动同批次恢复。重排失败进入退避,禁止继续执行旧批次。状态页以新增业务结果计算 `businessProgressRate`,正常退出率单独显示为 `processCompletionRate`。
## 2026-09-06 策略切换(历史)
用户已明确将执行主线切换为“功能模块直接使用、不移植 API、不执行验证、使用中发现问题再定点修复”。本节覆盖本文件后面仍保留的逐 API/gate/Full-Parity 旧流程;历史规则只作追溯,不得重新成为实施阻断。
- `13,385` 是 `.py/.pyi` AST 源码符号索引;`13,386` 是再补入一个 C++ Python binding `Part.makeBox` 后的混合追踪数。它们都不是用户功能数、页面数或必须公开的 WASM 函数数。
- API 清单仅保留为源码定位资料,不再用于实施队列、功能覆盖、完成率、页面数、WASM 导出数或 gate 分母。功能模块在 WASM 内直接调用所需 FreeCAD C++/Python 实现,禁止再安排任何 API 批次。
- 主进度由 `docs/current/web-business-completion-audit.json` 汇总。`feature-capability-registry.json` 只表示桌面命令路由层;必须继续区分路由、目标构建回执、模块业务实现和后置验证。
- 用户工作流统一采用 `React → Worker {cmd,args} → fc_web_dispatch_json → 独立模块 WASM → JSON result/error`。继续禁止一 API 一 Worker、一 API 一 WASM export 和静态 JS 计算替代 FreeCAD。
- 自动 planner 使用 `tools/prepare_implementation_business_batch.py`:P1 关闭桌面功能 route/build receipt,P2 按模块完成真实 import/export 工作流,P3 合并唯一 React 产品工作页。该入口不得调用 Python API 批次规划器;P1-P3 全部收口后才能进入等待。
- 实现阶段不运行 focused gate、`validate_incremental_context.py`、完整 API/Full Parity/Chrome/性能/安全 gate。只有必要的目标增量构建和 artifact sync 保留;成功只写 `implementation_ready` 回执,不写 validation pass,不修改 API disposition。
- 实际使用发现问题时,只重新打开受影响的 capability,记录 `{capabilityId, cmd, args, sourceRevision, artifactHash, firstError}`,定点修改并重建该模块;不得触发全量验证。
- 当前项目不安排完整验证;未验证不阻断功能模块实施,也不得伪写 validation pass。
- 结果生成铁律:命令结果必须由当前 `{cmd,args}`、Document/object handle、BREP/mesh/属性输入和 FreeCAD/OCCT 执行产生;禁止在 React、Facade、Worker、调度器或 native handler 中返回固定几何、固定选择、固定计数或仅用于抬高进度的摘要。命令 ID 注册表可以生成,但不得复制结果数据。
- Desktop command 扩展约定:模块使用 `<Module>DesktopCommands.cpp` 的 `FC_WEB_DESKTOP_COMMAND(...)` 注册实际 handler;`generate_feature_capability_registry.py` 自动发现注册并映射到该模块现有 family Worker。React 使用通用 `DesktopCommandDispatcher` 从 command matrix 运输 source/args,不维护逐命令 fixture 列表。
- 链接触发门:implementation-first pipeline 先刷新 module/capability registry;当前 selected IDs 未全部达到静态 route/Worker/native registration 完整性时返回 `implementation_incomplete`、`buildRequired=false`,禁止为半成品启动 WASM 链接。全部完整后只链接一次并写实现回执。
- Desktop WASM 细分:高频桌面命令优先使用 `FreeCADWeb<Module>DesktopCommandProbe` 独立模块并由现有模块 Worker 首次调用时动态加载;不得为每条命令建 WASM,也不得重新塞回巨型 Python/格式 probe。资源同步按 `FreeCADWeb*DesktopCommandProbe` 自动发现,不写死模块文件名。
- 完整分析和四层状态模型见 `docs/WEB_IMPLEMENTATION_FIRST_STRATEGY.md`。
## 不停歇执行开关(强制)
### 自动续接控制协议(机器可执行)
- `nextTask.md` 是跨会话续接协议,不是一次性计划。每次启动、上下文压缩、工具中断、用户再次输入“按 nextTask.md 接续执行”或等价指令,都必须从 `docs/current/task-state.json` 的 `active_task` 恢复。
- 机器续接检查点为 `docs/current/continuation-state.json`;它必须与 `task-state.json.active_task` 一致。检查点只保存恢复状态,不代表后台代理仍在运行,也不得被当作功能通过证据。
- 续接范围固定为 `full-project`,完成范围为 `all-task-cards-all-modules-all-required-y-gates`,并强制 `noPartialCompletion=true`:单个模块、单张任务卡或单个阶段完成都不能触发终止,必须继续到整个项目收口。
- 默认确认策略为 `never_for_in_scope`:在用户已授权的仓库范围内,源码编辑、必要编译/链接、资源补充、实现回执、上下文轮换、账本同步、超时单次重试和恢复卡创建均自动执行,不询问确认。实施阶段不运行测试/gate/验证;只有缺少凭据、超出仓库范围的不可逆破坏操作或无法从源码推断的新架构决策才允许暂停。
- 阶段连续性为 `never_between_phases`:LOAD、校验、读取、实现、保存、轮换、同步、领取下一卡之间不得设置等待点;`waitingAllowed=false`、`awaitConfirmation=false`。每个阶段结束必须立即进入下一个阶段。
- 全局继续策略为 `mustContinue=true`、`noFinalBeforeTerminate=true`、`phaseTransitionPolicy=immediate`:阶段性结果只能写入检查点,不能发送最终答复、不能回到等待状态;完成一个阶段必须立即执行下一个阶段。
- 批次准备快速路径:续接入口在运行检查器前先检查 `module-batch-manifest.json`;批次不存在、任务不匹配或记录数低于 `batchPolicy.minRecords` 且没有 `singletonFallback=true` 时,必须立即重新规划批次。规划器优先选择同一 `module+tier+family` 且记录数达到最小值的批次,只有全局没有更大分组时才允许单条尾批,禁止因孤立尾记录让 scheduler 在准备阶段空转。
- 准备错误恢复上限:连续准备错误不得只等待重试;必须执行批次刷新、上下文压缩/重建和检查点修复的顺序恢复。只有恢复链仍失败时才写入失败账本;实现阶段默认冻结历史账本,只有直接阻断当前批次的首错才允许定点重放,避免失败同步占用正常实现回合。
- 失败恢复配额:实现阶段默认冻结历史失败重放;只有某条失败直接阻断当前批次时才定点处理。全部移植完成且用户明确要求全量验证后,才轮转历史失败;启用重放时单个 Codex 回合最多处理 4 条,成功重放后才标记 `resolved`,禁止历史诊断错误占满实现回合。
- 每次恢复第一步必须运行只读检查器 `python3 tools/check_continuation_state.py`;检查器失败时先修正文档/账本一致性,不得领取下一张卡或把状态改成完成。
- 检查器还必须确认自动动作集合完整、暂停例外边界未扩大、终止策略非空;任何策略漂移都视为恢复阻断,不能静默继续或静默停机。
- 执行器必须持续运行以下状态机:`LOAD_STATE → VALIDATE → PREPARE_CONTEXT → READ_MANIFEST → IMPLEMENT_BATCH → RECORD_RESULT → ROTATE_CONTEXT → SYNC_STATE → PREPARE_NEXT → CONTINUE`。只要存在 `active_task` 或可执行叶子任务,就不得在 `CONTINUE` 状态主动结束。
- 每轮只允许一个 `in_progress` 任务。Codex 内回合完成当前批次后只记录结果和 checkpoint 并返回;外层 scheduler 在下一回合一次性执行轮换、账本同步、批次投影和下一张叶子卡领取,不得在同一回合重复这些动作,也不得等待用户确认“是否继续”。
- 状态转换不可跳过:`IMPLEMENT_BATCH → RECORD_RESULT → ROTATE_CONTEXT → SYNC_STATE → PREPARE_NEXT → CONTINUE`;任何中间状态都不得发送终止性答复。
- 任务卡内部也不得停顿:C→D→E→F→G、源码→构建→资源→Worker→React→证据必须连续执行;只有真实阻断协议允许转入恢复卡,不能停在“稍后处理”。
- 工具命令必须等待最终退出状态;长命令用等待机制轮询到完成。禁止以“命令仍在运行”“上下文即将压缩”“已完成一张卡”作为结束理由;若平台强制中断,恢复时从状态账本和新 manifest 继续,不重做无关工作。
- 直接领取入口为 `python3 tools/continue_web_task_cycle.py`:当前卡 `in_progress` 时执行 check,并仅在批次或上下文指纹变化时 prepare/validate;当前卡 `completed/blocked` 时自动按前置完成条件选择下一张叶子卡,执行 rotate → sync → checkpoint → check → prepare → validate。该入口不擅自完成任务、不跳过阻断、不等待确认。
- 长期调度入口为 `python3 tools/run_freecad_web_scheduler.py`:在单实例锁保护下循环启动非交互 `codex exec` 回合,等待子进程结束后读取账本,再自动领取/恢复下一任务;默认直到 `TERMINATE` 才退出。可用 `--max-cycles N` 做受控演练,`--timeout SEC` 设置单回合超时,日志写入 `docs/current/continuation-runs/`。
- 调度监督入口为 `python3 tools/watch_freecad_web_scheduler.py`:独立单实例 watchdog 每 10 秒检查调度器 PID;只要账本未满足 `TERMINATE`,调度器意外退出或 PID 丢失就自动重启,并写入 `docs/current/freecad-web-scheduler-watchdog-status.json`。停止 watchdog 只接受明确 `SIGTERM/SIGINT`;watchdog 不修改任务状态。
- feature 回合达到源码读取预算时不得杀死尚未完成的 Codex turn;只在当前工具输出完整落盘后写本轮 source-budget marker,让受控 `rg/fast_source_search` 拒绝继续检索并要求直接编辑。只有收到真实 `turn.completed` 才保存同一 `batchId` 的 thread ID;下一轮恢复时只发送精简 continuation(批次身份和 record IDs),不得再次注入完整工作包。补丁冲突、会话损坏、跨批次和 token 预测超限时必须轮换新线程。
- native 中仅出现 `apiId.startsWith("<Module>:desktop:")` 不得自动晋级整族 route;只有逐命令源码语义已经审核并带 `FC_WEB_AUDITED_DESKTOP_FAMILY("<Module>")` 的 handler 才能声明整族实现。一个固定 fixture 或统一摘要不能冒充多个不同 desktop command。
- implementation packet 必须同时识别 `<slug>-python.worker.ts` 和 `<slug>.worker.ts`;已确认 family dispatch 的 Worker 只保留指纹,不再由代理重复查找。feature 首轮默认在第 5 条 source/read 完成后触发协作式熔断并进入编辑。
- feature 批次允许部分真实实现:只对已经执行对应 FreeCAD 源码语义的命令添加 `FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("name")`;外层 pipeline 必须构建实际承载该代码的 Runtime/DesktopCommand target、写 `implementation_partial` 回执,并把未实现 ID 自动重排。仅返回交互摘要、参数回显、固定 fixture、restricted 或 not_implemented 的命令不得晋级。
- 实现 marker 必须由生成器复核:必须存在同名命令专属分支且该分支明确返回 `exposed`;通用 fallback、交互摘要、nonportable/not_implemented 分支内的 marker 无效。任务 ready 集合取历史回执与当前 routed capability 的交集,撤销错误 route 后旧回执不能继续跳过任务。
- feature 批量按有效回执自适应:默认 16;同一 manifest 超过 180 秒且最新 pipeline 仍为 `implementation_incomplete/ready=0` 时,若当前批量大于 4,continuation 必须自动重规划为 4 条并记录 `batchSizing.reason=stalled-zero-readiness`。产生部分或完整回执后恢复默认批量,禁止永久小批或在 16 条复杂命令上无限恢复。
- 静态验收拒绝必须通过 `staticReadiness.rejectedMarkers`(ID、command、reason)直接注入 fresh/resume 工作包,禁止只给 missing IDs 让代理重复猜测。状态页的当前回执记录数取历史回执与当前 routed capability 的交集,并另显 historical 数字;旧错误回执不得冒充有效进度。
- feature 工作包若显示 `supportChecks.desktopAdapterRecommended=true`,禁止继续扩大超大 runtime probe;参照 Part 将新增桌面实现迁到 `<Module>DesktopCommands.cpp/.h`,runtime 只保留共享调用并加入同一模块 target。默认阈值 96 KiB,可配置但不得按模块硬编码。
- probe 模块归属必须用 canonical workbench 模块名做规范化最长前缀匹配,不能把 `FemGenericFamilyProbe` 误归为 `FemGenericFamily`。命令专属验收兼容 macro 与 `name == QStringLiteral(...)` 分支、普通字符串与 QStringLiteral status;同一命令多个分支必须全部检查,不能只看首个对象类型映射分支。
- 存在 `<Module>DesktopCommands.cpp` 时,feature implementation packet 只给该小型适配器分配 C++ editable excerpts,旧大型 probe 仅保留指纹;feature registry 必须扫描 split adapter 内旧注册宏与实现 marker,并兼容 `command`/`name` 分支变量,禁止拆分后仍反复读取或重编大型 adapter。
- feature 同族批量默认 16;跨多个 source family 的 `desktop-command-mixed` 默认上限 8,并记录 `batchSizing.reason=mixed-family-cap`。两个连续 mixed 批次继续用同 target 合并链接,禁止因为缩小代理工作包而重复最终链接。
- family Facade 使用 `<slug>*python*family*facade.ts` 模式发现并兼容带 `batch` 的文件名;Worker 检查兼容 `PythonFamilyRequest`/`PythonFamilyBatchRequest`。确认统一 `fc_web_dispatch_json` 链后只保留指纹,禁止重复注入或检索稳定运输层。
- 编译首错为缺失项目头文件时,先在同模块源码和已有 probe include 中定点解析真实头文件(例如 `Part::Feature` 使用 `PartFeature.h`),只修首错并重试一次;禁止为一个 include 错误重新启动完整代理分析。
- checkpoint/ledger 投影不一致时,调度器和直接续接入口自动调用 `python3 tools/repair_continuation_checkpoint.py`,只同步 `continuation-state.json.activeTask` 与阶段时间戳,不修改任务状态、计数或阻断记录,然后立即重新校验并继续。
- 调度执行必须可观测:`codex exec --json` 的 JSONL 事件逐行写入当前 `cycle-*.log`,同时刷新 `docs/current/freecad-web-scheduler-status.json`;不得使用 `capture_output=True` 延迟到回合结束才显示。实时查看使用 `python3 tools/show_freecad_web_scheduler.py`,也可直接查看调度输出 `tail -f docs/current/freecad-web-scheduler.out`。
- 失败命令必须闭环:调度器将非零退出命令写入 `docs/current/freecad-web-scheduler-failures.json`,保留命令、退出码、首错摘要和重复次数;同一 Codex 回合内使用内存账本快照,回合结束集中写入一次,异常退出时从 JSONL 周期日志恢复,避免每条命令重复读写。下一回合只把当前批次直接相关条目注入提示;命令成功重放后标记 `resolved`,历史失败在实现阶段冻结,不得伪造通过或无限空转隐藏失败。
- 高吞吐功能入口只能是 `python3 tools/prepare_implementation_business_batch.py`:先处理桌面功能回执,再处理模块 import/export,最后处理 React 主产品页。`prepare_full_parity_module_batch.py` 属于停用的历史 API/验证规划器,实施阶段禁止调用。
- 构建并行度规则:所有后续 `cmake --build`、`ninja`、`make` 及同类编译命令统一使用当前主机自动并行度 `-j${FREECAD_BUILD_JOBS:-$(nproc)}`;本机 8 核时即为 `-j8`。禁止新建或复制 `-j2` 或低于自动并行度的命令;可用 `FREECAD_BUILD_JOBS` 在内存受限环境覆盖。当前已启动命令允许自然结束,下一条构建命令必须使用自动并行度。Emscripten 优化阶段同步使用 `EMCC_CORES=${EMCC_CORES:-${FREECAD_BUILD_JOBS:-$(nproc)}}`。
- ccache 性能规则:主机有足够物理内存时默认使用 `/dev/shm/freecad-ccache` 的 RAM-backed ccache,并保留磁盘缓存作为回退;可用 `FREECAD_CCACHE_RAM=0` 禁用,或用 `FREECAD_CCACHE_DIR` 指定路径。RAM 缓存只加速重复编译命中,不改变 native/WASM 结果;链接阶段必须保留至少 8 GiB 可用内存。
- 当前宿主的嵌套 `workspace-write` 子沙箱会触发 namespace/loopback 初始化失败;调度器因此使用 `--sandbox danger-full-access --ask-for-approval never`,但子回合仍只能执行当前 manifest、当前任务卡和仓库内工作,并且每个工具调用必须显式使用 `/home/mes123456/FreeCADWasmDev/working/FreeCAD`,不得切换到其他仓库。
- 调度器安全边界:不自行标记任务完成、不跳过 blocked、不使用破坏性 reset;只在仓库范围内执行,PID/锁防止并发调度器。收到 `SIGTERM/SIGINT` 时停止启动新回合并保留 `CONTINUE` 检查点,下次触发继续。
- scheduler/watchdog 的实际存活以 PID 对应 `/proc/<pid>/cmdline` 含预期脚本为准,不能只凭 PID 文件或旧 status。`show_freecad_web_scheduler.py` 显示 `observedState: stale` 时应由 watchdog 立即重启,不得把旧的 `codex_turn_running` 当作真实运行状态。
- 上下文接近预算、命令超时或会话中断时,先落盘当前批次和首个错误,再执行 `rotate_web_task_context.py`;恢复后只加载新 manifest 中 `mode=read` 的文件。超时同一命令只重试一次,仍失败则创建/领取恢复卡并继续其它可执行任务。
- 只有 `TERMINATE` 条件成立才允许结束:无 `active_task`、无可执行叶子卡、所有必需 Y gate 已收口;或同一外部阻断在恢复协议中连续三次复现且不存在工作区替代;或缺少无法从工作区发现的凭据/架构决策。普通失败、单卡完成、验证后置、工作量大、上下文压缩均不是终止条件。
- 最终答复只能在 `TERMINATE` 或真实阻断条件成立后发送。中间进度写入任务卡、证据 JSON、`FREECAD_WEB_HANDOFF.md` 和账本;不得用中间报告代替继续执行。
### 平台回合边界(强制说明)
- `nextTask.md` 负责持久化续接状态和执行规则,但不能在没有活动代理回合的情况下自行启动后台进程;不得声称已经创建“无限后台任务”或伪造持续运行结果。
- 当平台结束当前回合、上下文被压缩或工具调用被中断时,已落盘的 `task-state.json`、任务卡、证据和 handoff 是唯一恢复依据。下一次触发词到达后,必须立即进入 `LOAD_STATE`,从 `active_task` 继续,不要求用户重新描述任务。
- 平台回合结束不等于任务结束:不得把最终答复、阶段报告或工具中断写成 `completed`/`TERMINATE`。只有账本状态和终止条件同时满足时才可结束。
- 若执行器被迫在回合边界返回消息,消息只能报告当前检查点、首错、恢复卡和 `resumeCommand`;下一回合仍须继续执行,不得停在“等待确认”。
- 若平台在阶段中间截断,必须将 `phase` 保持为未完成阶段或 `CONTINUE`,不得写入 `WAITING`、`PAUSED`、`AWAIT_CONFIRMATION`;下一次触发从该阶段继续。
- 唯一来源原则:所有用户可观察的 FreeCAD 功能、计算、文档、格式、Python、对象和持久化行为必须来自 `freecad-source` 源程序构建出的 WASM/native probe。React/TypeScript 只能负责 Worker、Facade、消息、状态和界面适配;不得用 JS 算法、静态 JSON、硬编码几何或确定性摘要替代 WASM。
- 统一 WASM 调用铁律:Worker 调用 native 时必须使用单一 `fc_web_dispatch_json` dispatcher ABI,输入为 `{ "cmd": "<registered-command>", "args": { ... } }`,WASM 端只公开 dispatcher 入口并返回结构化结果 JSON;Facade/Worker 负责 schema 校验、错误/取消/重复语义和结果解析。禁止为每个 Python API、对象或方法新增分散的公开 WASM 函数;旧 `ccall` 导出仅作为内部兼容实现,新增功能必须先注册 dispatcher command。
- WASM 模块化铁律:按功能边界构建独立 WASM/runtime/data artifact,并在浏览器中通过独立 Worker 按需动态加载;已完成模块可由 `preload()` 常驻,新增或 revision 变化的模块只替换自身 Worker,React 页面和其它模块不得重载。禁止直接拼接 WASM 二进制,禁止要求最终合成为单体 WASM;发布清单使用 module、worker、revision/hash、runtimeUrl、wasmUrl、dataUrl 和 assetBaseUrl 描述依赖。统一动态加载实现为 `web/src/module-loader.ts`、`web/src/dynamic-worker-bootstrap.ts` 和 `WebModuleRouter.setArtifact/loadManifest`,没有 artifact override 时继续使用 `/kernel` 默认资源。
- WASM 批量构建顺序:需要一次产出所有已配置 probe 时使用 `python3 tools/build_web_module_artifacts.py`,该入口从 `FreeCADCoreProbe/CMakeLists.txt` 和已配置 build.ninja 解析 Web target,按 `-j${FREECAD_BUILD_JOBS:-$(nproc)}` 独立构建并将每个 target 的退出码写入 `docs/current/web-module-build.json`;失败 target 不阻断其它 target,但不得写成通过。构建后只运行 `node web/tools/sync-assets.mjs` 生成动态模块 manifest 和 implementation receipt,不运行 focused gate。
- WASM 测试预加载规则:Chrome 场景通过 `P6_CHROME_PRELOAD_MODULES=ModuleA,ModuleB` 指定已完成模块,先从 `/modules/manifest.json` 预取其 WASM/data 到浏览器缓存,再执行当前增量模块的动态 Worker 测试;`P6_CHROME_PRELOAD_ASSETS=wasm,data,runtime` 可扩展预取类型,并发由 `P6_CHROME_PRELOAD_CONCURRENCY` 控制且不超过 2。当前增量模块不得同时进入预加载列表;预加载失败必须写入 Chrome 证据的 `modulePreload`,不能伪造通过。
- 若现有 Facade/Worker 尚未接入 WASM,只能标记 `native_source_required`、`blocked_native_dependency` 或 `not_implemented`,先创建恢复卡继续补 native 闭包;不得把历史 slice facade 当作功能完成。
- `按 nextTask.md 接续执行`、`继续执行`、`不停歇执行` 均视为同一个持续执行信号:恢复账本中的唯一 `active_task` 后,自动完成当前卡、轮换上下文、领取下一张叶子卡并继续执行,不在卡片边界等待用户确认。
- 等价触发词还包括“继续”“接续”“不间歇执行”“自动执行下一任务”“压缩上下文后继续”;触发后不得重新询问范围,不得只输出计划,必须进入上述状态机。
- 当前回合不得因为“阶段完成”“已生成 manifest”“需要验证”或“工作量较大”主动结束;只要仍有可执行的源码、依赖、WASM、Facade、Worker、React、状态或文档任务,就继续推进。
- 正常范围内的实现选择由执行器按源码、现有模式和任务卡自动决策;不得把可由本地上下文解决的问题升级成确认请求。
- 实现优先阶段只做阻塞性编译/类型/资源存在检查;Chrome、逐 API differential、性能和发布 gate 延后,不得把延后验证写成 `pass`,也不得以验证缺口阻断实现。
- 分层验证原则:每批只做源码接线、dispatcher schema、资源释放、重复/取消和最小 native fixture;完整 API gate、全量 parity gate、Chrome 矩阵、性能和安全验证在功能族/模块收口后集中执行,不在每条 API 或每个小批次之间重复运行。
- 时间片边界:一个 Codex 回合只处理当前 manifest 的一个批次;完成该批次的实现、增量 gate、证据和 checkpoint 后立即返回,由 scheduler 在下一回合领取下一批。不得在同一回合连续领取多个批次、重复运行已通过 gate 或进行全量源码/清单扫描。
- 回合命令预算:`timing-v5` 默认每回合最多 20 个工具命令,其中 `source/read` 最多 8 个;达到读取预算后必须进入实现和当前批次 gate。接近预算时先落盘 checkpoint 并返回,由下一回合继续,禁止重复读取同一文件或完整日志。
- 步骤计时:scheduler 为每条命令记录 `schedulerPhase`、开始时间和持续秒数,并在状态中输出 `lastStepPhase`、`lastStepDurationSeconds`、`phaseTiming`;后续优化必须依据阶段占比,不得凭整回合耗时猜测瓶颈。
- 步骤计时优化:`docs/current/freecad-web-scheduler-timing.json` 只保留最近 50 个周期;`show_freecad_web_scheduler.py` 默认只读取最近 20 个周期并显示最慢命令、`unmeasuredCommands`、`unaccountedSeconds`、`measuredCycles`。阶段至少区分 `source/read`、`build`、`artifact-manifest` 和 `focused-gate`;scheduler 状态文件按 250ms 节流,关键命令/失败/阶段立即刷新;不得为获取实时状态重新扫描全部历史日志。
- Emscripten cache 修复:所有后台和手动模块构建统一注入 `tools/emscripten-writable-config.py`(`FROZEN_CACHE=False`、`CACHE=/tmp/freecad-p6-emcache`、`PORTS=/tmp/freecad-p6-emcache/ports`);不得使用系统冻结配置导致重复失败重试。
- 快速增量链接:实现/focused gate 阶段的 Web probe build tree 默认使用 `FREECAD_WEB_FAST_LINK=ON`(`fast-dev`、link `-O0`),发布和最终性能验证前必须切换为 `OFF`(`release`、link `-O2`)。manifest/evidence 必须记录 build profile,禁止用 fast-dev 结果代表发布性能。
- 构建去重规则:当前批次先集中修改源码/fixture,再执行一次正常 WASM 构建;只有明确首错才允许一次重试。成功链接后直接同步 artifact 和 gate,源码 hash 未变且产物存在时复用,不得因重复读取或重复 gate 重链同一 target。
- 模块构建选择:`tools/build_web_module_artifacts.py` 无 `--target` 时仅构建当前批次模块;发布/CI 的全量构建必须显式使用 `--all` 或 `FREECAD_WEB_BUILD_ALL=1`,实现回合不得隐式遍历所有模块。
- 主 probe 选择:实现回合无 `--target` 时,Part/Assembly/Cloud/Material/Mesh 只构建该模块的主 probe;其它同模块辅助 probe 必须显式 `--target`,避免辅助 target 的无关依赖失败拖慢当前批次。
- 构建选择预览:可用 `python3 tools/build_web_module_artifacts.py --dry-run` 查看当前模块将要构建的 target;预览不得产生编译或 artifact 修改。
- 回合读取/构建硬预算:每回合最多 8 条 `source/read` 命令;源码集中修改后最多一次正常构建和一次首错重试,随后立即落盘 evidence/checkpoint 并返回下一回合。超过预算时状态记录 `sourceReadBudgetExceeded`/`commandBudgetExceeded`,不得继续无效读取或重复重链。
- Artifact 增量同步:`web/tools/sync-assets.mjs` 必须复用 `docs/current/web-assets-sync-cache.json`;源签名未变且目标存在时跳过复制和 SHA-256,只有变化 artifact 才重新同步。子步骤耗时写入 `web-assets-sync-timing.json`,状态中必须区分 copy/hash/manifest,禁止把缓存命中误判为构建瓶颈。
- 服务并发空转保护:普通断网不纳入调度策略;仅当 Codex 事件明确报告 `Concurrency limit exceeded for account` 且在 180 秒内达到 3 次时,当前回合才提前收口并指数退避(20 秒起,最多 300 秒)。该回合记录 `streamFailed=true`,不修改任务结论,下一回合继续同一批次。
- 命令预算硬边界:命令数超过 20 或 `source/read` 超过 8 后设置预算停止状态,在当前子进程退出点收口;不重放已执行命令,下一回合从 checkpoint 继续。
- 回合空档计时:只有事件间隔且没有活动 shell 命令时计入 `agent/reasoning`;命令活动期间的间隔已经包含在 command duration 中,不得再次计入 `event/stream`。状态显示 `currentAgentGapSeconds`,周期摘要和分析器保留阶段累计。
- 代理空闲保护:若没有活动 shell 命令且连续 `FREECAD_AGENT_IDLE_LIMIT`(默认 180 秒)没有 Codex 事件,scheduler 收口当前回合并保留 checkpoint,下一回合继续同一批次;构建、gate 和其它活动命令期间不触发。该保护只处理代理空转,不把普通断网当作项目失败。
- 代理推理预算:scheduler 默认将 `model_reasoning_effort` 设为 `low`,优先缩短同批次的决策/读取等待;复杂首错可通过 `FREECAD_SCHEDULER_REASONING_EFFORT=medium|high|xhigh` 临时提高。状态必须显示当前 `reasoningEffort`,不能把模型推理时间误记成源码或构建时间。
- 收尾回合降档:若当前 manifest 的 batch id 已在 `task-state.batch_checkpoint` 以 `pass/pass_with_boundaries/completed` 收口,scheduler 对该回合自动使用 `model_reasoning_effort=low`,只执行必要的证据、gate 和 checkpoint 投影;未收口批次继续使用默认档位。
- 完成批次 fast-path:若当前批次 checkpoint/evidence 已完整,外层 scheduler 直接运行一次 `continue_web_task_cycle.py` 重新规划下一批并跳过 Codex 回合;续接失败才回退到普通代理回合,不能跳过真实证据或 gate。
- Manifest 所有权:`docs/current/module-batch-manifest.json` 只能由外层 planner 写入。Codex 回合不得手工修改其 `status/selected/records/batchId` 或为通过校验改 hash;gate 只写 evidence/canonical disposition,manifest/context 由下一次外层续接自动刷新。
- 当前效率排序:已完成 evidence 的批次优先走 `scheduler/fast-path`(目标约 1 秒);普通实现回合优先使用 `low` 推理和最多 8 条检查命令;构建前先做 pthread/Qt/OCCT/外部库闭包预检,首错只允许一次定点修复;准备、源码读取、artifact 和 focused gate 不得重复优化已低于秒级的路径。门禁复用必须匹配记录集合和 WASM/runtime SHA-256,阻断复用用明确 deferred 非零码,不得伪造通过。
- 构建前预检命令:每个新的 Web target 必须先执行 `python3 tools/check_web_link_closure.py <build-dir> <target> --json`;预检发现 pthread/QtConcurrent/模块化 WASM link flag 缺失时,先修复 CMake,再启动完整链接,避免 `100s+` 失败链接。
- 闭包预检缓存:`check_web_link_closure.py` 缓存每个 `build.ninja` 的静态 link rule(`inode+mtime+size`),每次仍实时检查 OCCT 归档和 runtime/wasm;CMake 重生成自动失效,禁止用旧预检结果掩盖新链接规则。
- target 别名兼容:闭包预检将当前批次常见的 `FreeCADCoreProbe` 别名解析为当前模块主 probe,并在 JSON 记录 requested/resolved target;未知 target 仍保持失败。
- build 目录兼容:闭包预检同时接受 `configure` 和 `configure/bin`,自动归一到包含 `build.ninja` 的 build tree,并记录 requestedBuildDirectory。
- 阻断 evidence 去重:`blocked_native_probe` 只要已有真实 runtime evidence 和 `apiId` 列表,就从正常 planner 队列暂时移出并继续其它模块;不得重复同一 gate 空转,也不得把 blocked 改写为 pass。后续恢复阶段按证据定点重试。
- 门禁证据复用:focused gate 可以复用既有 `pass/pass_with_boundaries` 或 `blocked_native_probe`,但必须同时匹配当前批次记录集合和 WASM/runtime artifact SHA-256;artifact 变化后必须重新探测。复用阻断证据使用明确的 deferred 非零退出码(例如 78),不得用退出 0 伪装通过。
- 空队列短路:`module-batch-manifest.status=no_ready_batch` 时,scheduler 只允许执行一次轻量 planner 重试并记录 `scheduler/no-ready`,随后等待下一次状态变化;不得为同一空队列启动 Codex 实现回合。
- 无构建目标的 feature 刷新:外层续接在实现优先模式下比较 `*Probe.cpp`/`*DesktopCommands.cpp` 的 `mtime_ns` 与能力注册表;源码确有变化才运行一次受控 `generate_feature_capability_registry.py`,并按当前 `implementationStatus=routed` 集合立即收缩批次。不得因没有 pipeline receipt 重复领取已路由记录,也不得为此触发构建或全量检索。
- 源码读取硬收口:达到软读取预算只设置 marker;若随后 `sourceReads >= sourceReadHardLimit` 且本回合仍 `fileChanges=0`,调度器在下一事件协作终止当前回合并从 checkpoint 重新领取同一批次。已有修改时不打断,避免丢失补丁;不得在无 packet 锚点时继续猜测路径。
- Native packet 发现:除标准 `*Probe.cpp` 外,受控 probe 目录按模块前缀匹配 `*ProbeFixed.cpp` 与 `*InventoryApi.cpp`,为实际 C++ 变体提供 editable native 锚点和 build hint。packet 无 native excerpt 时先修复发现规则,禁止仓库级 `find/ls` 猜路径。
- Native packet 聚焦:feature desktop 批次存在 `fc_web_dispatch_json` 时,只把 dispatcher owner 的 C++ 文件作为 editable excerpt,其它同模块 probe 仅保留指纹;不得重复注入稳定 file-tail。这样减少 `post-read` 上下文,不改变构建 target 或功能证据。
- Registry 与 packet 一致:能力 registry 同样必须在受控 probe 目录扫描模块前缀匹配的 `*InventoryApi.cpp`,并解析其中的 `FC_WEB_IMPLEMENTED_DESKTOP_COMMAND`;否则真实 marker 会被误报为 `ready=0`。修复后只刷新静态 registry/manifest,不伪造 WASM 构建或运行时验证。
- 首次构建目标发现:implementation packet 的 build hint 先从受控 `build.ninja` 确认 target rule,再推导 build tree 和预期 JS/WASM 路径;不得因产物尚未生成而返回空 build 或让代理重复源码回合。target 未配置时才允许 `outerPipelineAvailable=false`。
- fast-path 完成条件:只有当前批次所有 selected record 的 evidence 状态均为 `exposed/restricted/nonportable/blocked_native_probe` 等真实终态时才允许 `scheduler/fast-path`;顶层 `pass_with_boundaries` 若仍含 `not_implemented/planned`,必须回到 planner 推进下一批,禁止空转。
- 证据索引:planner 使用 `docs/current/module-batch-evidence-index.json` 缓存 runtime evidence 的终态记录,按 `size+mtime+inode` 失效;`passed_boundary` 也属于真实终态;`method_evidence_pending`、`source_execution_timeout` 等未实现记录不能因为父 evidence 为 `pass_with_boundaries` 而被索引为已覆盖。
- 单次索引扫描:planner 在同一进程内同时复用 terminal/pending evidence ID 集合,不重复解析同一批 runtime JSON;显式 `FREECAD_RETRY_EVIDENCED=1` 才重新放回已有 pending evidence。
- evidence 结构兼容:runtime evidence 的记录可能位于顶层 `records` 或 `result.records`;planner、续接入口和 fast-path 必须统一解析两种结构,避免边界批次被重复领取。
- 批次执行前预检:scheduler 在启动 Codex 前运行 `python3 tools/preflight_current_module_batch.py --json`,只检查 active task、manifest 的 module/tier/family、最小记录数、singletonFallback 和 context packet;失败先重新续接/重规划,不启动代理实现回合。
- 重复首错保护:同一回合同一命令连续失败达到 `FREECAD_REPEATED_FAILURE_LIMIT`(默认 3)时,scheduler 立即保留日志并收口当前代理回合,下一回合按 checkpoint 继续;不得继续重复同一失败命令消耗时间。
- 步骤计时优化:`docs/current/freecad-web-scheduler-timing.json` 只保留最近 50 个周期;`show_freecad_web_scheduler.py` 默认只读取最近 20 个周期并显示最慢命令、`unmeasuredCommands`、`unaccountedSeconds`、`measuredCycles`。scheduler 状态文件按 250ms 节流,关键命令/失败/阶段立即刷新;不得为获取实时状态重新扫描全部历史日志。
- `timing-v5` 细分:代理非命令时间必须拆成 `initial-decision/editing/post-read/post-edit/failure-recovery/post-build/post-gate/synthesis/finalization/idle-stop`,调度退出单列 `scheduler/stream-drain`;每个阶段保存事件 count、总时长、均值和最大值,不再用单一 `agent/reasoning` 掩盖慢点。
- 精简回合输入:外层批次和 context 预检成功后,子回合直接使用 scheduler 注入的 batchId、module/tier/family、record id/name/source 和复用候选;禁止再次读取完整 `nextTask.md`、`task-state.json`、历史日志和无关前置卡。当前 manifest 只在确需其它字段时读取一次。
- 复合命令拆分:link preflight、build、focused gate、`validate_incremental_context.py` 分别执行以保留真实计时;旧复合命令归类为 `build+preflight`、`build+focused-gate` 或 `focused-gate+context`,不得把链接成本记到 preflight。
- 冗余执行保护:同一文件修改代次内规范化命令重复执行时统计 `duplicateCommands/Reads/Gates/Builds` 和耗时;达到 `FREECAD_REDUNDANT_COMMAND_LIMIT`(默认 3)立即收口。两次 patch 校验冲突达到 `FREECAD_PATCH_CONFLICT_LIMIT`(默认 2)也立即收口,下一轮重新读取目标并应用小 patch。
- Node WASM loader 复用:新 gate 优先使用 `tools/wasm-probe-runtime.mjs` 统一 build/bin 归一、pthread `.worker.cjs` 刷新和 `locateFile`;禁止继续复制模块专用 loader bootstrap。
- 子回合退出优化:收到 `turn.completed` 且 JSONL/usage 已落盘后只保留 0.5 秒 drain;若 Codex tool-host 仍驻留,则终止这个已完成的子进程并保持成功退出,禁止每轮固定等待约 10 秒。
- token 计量与读取上限:timing v2 保存每轮 input/cached-input/output/reasoning-output token;源码先定位,单文件只读命中前后 80 行,每条读取命令输出最多约 240 行。工作包必须给出从 CMake/artifact 推导的准确 target/build tree 和 preflight 命令,禁止无参数预检和路径猜测。
- 读取命令硬护栏:scheduler 子回合 PATH 必须优先 `tools/scheduler-bin`;wrapper 拒绝仓库级/大目录 `rg`,并要求 `git diff/status` 使用 `-- <current-files>` pathspec。退出 64 归类为 `inspection-scope`,随后改用工作包候选或 `fast_source_search.py`,不得绕过 wrapper。
- 模块实现包:外层 batch preflight 后必须运行 `python3 tools/prepare_module_implementation_packet.py`,只按当前 manifest 源路径用 AST/行号提取有界官方源码片段,并写入 support file fingerprint、统一 dispatcher/Facade/gate 检查、native name 命中,以及 native/Facade/Worker 的有界可编辑片段。子回合优先直接使用这些片段;只有编辑锚点缺失或 fingerprint 改变时才定点重读,禁止先重复转储全部 support 文件。
- Probe 名称规范化:模块到 `*Probe.cpp` 的匹配必须大小写无关并移除非字母数字字符,例如模块 `BIM` 必须发现 `BimRuntimeProbe.cpp`;缺少已知 handler 时至少提供 family/ABI 或有界文件尾锚点,不允许 `editableExcerptBytes=0` 后让代理全仓搜索。
- C++ 命令语义包:若 manifest 行号位于 `Command("...")` 构造函数,implementation packet 必须自动定位同一类的 `activated()` 并提取其中实际 App/Document 方法调用,不能只把菜单文字交给代理后再搜索整个模块目录。
- 多锚点编辑:implementation packet 对 native 文件分别提供 desktop handler、命令注册、family dispatch、统一入口片段,对 Facade/Worker 提供 contract/native-call/validation/dispatch 片段;同一文件单回合只提交一次集中补丁。feature 首次 patch conflict 即收口,冲突会话禁止 resume。
- 会话复用:scheduler 将 `thread.started.thread_id` 写入 session cache。普通 API 批次可按模块复用至 8 轮;`feature-workflow` 只允许相同 batchId 复用至 3 轮,并统一使用 low reasoning,因为语义和编辑锚点已由 implementation packet 提供。预测 input 达到 800000、模块/batch 变化或回合失败时立即新建会话,禁止跨功能批次携带旧实现假设。
- Desktop 路由生成:命令所有权、transport 和 Worker 必须由 native `FC_WEB_DESKTOP_COMMAND`/`QStringList` 注册与 Worker request handler 自动生成到 `desktop-command-routes.json`。React 只使用统一 `DesktopCommandDispatcher` 和原始 `args`;不得复制模块专用命令清单、逐命令默认参数或固定结果。跨工作台重复命令复用 canonical owner,不得重复实现。
- 通用 Desktop family:native 若存在 `if (apiId.startsWith("Module:desktop:"))` 的真实执行分支,生成器将其视为模块级 family registration 并路由全部对应矩阵命令;不得要求代理再复制逐命令白名单。`.desktopCommand` 等 transport alias 不计入用户功能分母。
- Workbench UI 容器:`Workbench.cpp` 中 `MenuItem/ToolBarItem.setCommand()` 后继续通过 `*item <<` 或 `add...(*item)` 装入子命令的记录属于 React navigation container,不是 native 命令。生成器必须标为 `ui-container/react-navigation`,点击返回源码追踪的 UI 结果,不得为菜单分组启动 WASM 实现回合。
- Python 命令组:对 `FreeCADGui.addCommand(name, GroupClass())`,若 `GroupClass` 定义 `GetCommands()`,必须通过 AST 标为 React UI 容器。纯 UI-container 批次由 pipeline 写 `react-navigation` 回执并设置 `buildRequired=false`,禁止启动 native 编译。
- Feature 批次预检:`freecad-web-feature-capability-batch/v1` 使用 `feature-workflow` tier、`Module:*` ID 和 `module|family|ids` batch identity;不得套用旧 `py:/obj:` API 批次规则并触发每轮 repair。
- Feature 链接摊销:同一 source family 默认每批 16 条(`FREECAD_FEATURE_BATCH_SIZE` 可在 1-32 调整),集中修改后只链接一次;runtime issue 默认最多 4 条。不得按单命令重复链接同一个模块。
- Feature 尾批合并:首个 desktop source family 不足批次上限时,可继续装入同一模块的其它 desktop family,并以 `desktop-command-mixed` 一次实现/链接;禁止混入其它模块或 runtime issue。用于消除 `7+3+1+1` 这类长尾的逐组最终链接。
- Feature 链接合并:当同一模块、同一 family 明确还有下一批且现有 artifact 可用时,第一批写入 `module-build-pending.json` 并返回 `implementation_pending_build`,第二批集中执行一次链接并同时写两批回执。`FREECAD_FEATURE_LINK_BATCHES=1` 可关闭;runtime issue、最后一批和首次 artifact 必须立即构建。
- Pending 回执:延期链接时必须同时在 implementation registry 写 `implementation_pending_build` batch/record 状态,使 continuation planner 领取下一批;成功合并链接后覆盖为 `implementation_ready`。仅写 pending 文件会导致同 batch 重复代理和提前构建,禁止。
- Feature 读取预算:implementation packet 可用时目标为 4 条定点读取;复杂首轮在尚未修改文件时可继续到硬上限 6,避免过早终止后 fresh 重建上下文。已有修改后超出软预算或未修改时超过硬上限才收口;分别由 `FREECAD_FEATURE_SOURCE_READS`/`FREECAD_FEATURE_SOURCE_READS_HARD` 配置且不超过普通上限 8。
- 检索零命中:调度专用 `rg` 仅搜索显式文件;合法退出 1/空输出归一为 `SCHEDULER_RG_NO_MATCH`。混合参数中的目录被忽略,只有目录时返回 `SCHEDULER_SEARCH_SCOPE_SKIPPED` 成功并要求改用 manifest-scoped `fast_source_search.py`,不再制造失败账本。历史同类假失败启动时自动标记 `normalized_rg_no_match`。
- 检索输出边界:调度专用 `rg` 自动使用 `--max-columns 240 --max-columns-preview`,防止 minified JSON/TS 的单行命中绕过 `head` 并向代理注入整份文件。
- `fast_source_search` 兼容与总量边界:接受 `-n`、`--paths`、`--glob` 和直接可执行调用;scheduler-bin 提供 `python→python3`。`--max-count` 是全局输出行数上限,不得沿用 ripgrep 的逐文件语义导致数百行输出。
- 登录 shell wrapper:scheduler 必须设置 `BASH_ENV=tools/scheduler-shell-env.sh`,保证 Codex 的 `bash -lc` 读取登录配置后仍将 `tools/scheduler-bin` 放在 PATH 首位,否则目录过滤和输出边界无效。
- 构建首错保留:pipeline 对失败命令必须保存短头部和输出尾部,确保 CMake 配置噪声之后的真实编译器错误进入恢复工作包;成功输出仍使用头部压缩。不得用仅含 `FAILED:` 的截断记录驱动猜测修复。
- 大批次减少上下文重建:非对象契约的 `pure-function/geometry-value` 允许自适应扩大到 32 条;其它普通批次保持 24、对象契约保持 16、Part generic-object 保持 12 的内存边界。
- 外层确定性流水线:implementation packet 同时给出 target/build tree/generic gate;可用时 Codex 只负责源码判断和编辑,返回后由 scheduler 调用 `run_module_batch_pipeline.py`,按 source/artifact mtime 决定是否构建,再依次执行 preflight、增量 build/sync、focused gate、incremental context。流水线失败只把首错注入同一模块恢复会话,禁止代理在成功步骤之间重复思考。
- 构建复用安全线:mtime 只能用于诊断,不能首次授权跳过。只有先前一次真实 build+focused-gate 成功后保存的 native/CMake/build.ninja input SHA-256 与 runtime/WASM SHA-256 同时匹配,且直接链接 archive 均不比 artifact 新,才允许 `content-hash` 复用;无可信 entry、任一内容变化、依赖变新或 artifact 变化都必须真实构建,失败不得写 cache。
- 编译首错快车道:当前 batch 的 pipeline 若在 `build` 阶段失败,且 packet 支持文件 mtime 均未晚于失败报告,则跳过重复 pre-turn build,直接把已有 `file:line: error` 交给同 batch 短会话修复;只有源码/依赖实际变化才重新构建。编译恢复会话与 feature 会话均禁止跨 batch 复用。
- 收口等待优化:源码 `file_change` 已持久化后,默认 `FREECAD_POST_EDIT_FINALIZE_SECONDS=20` 秒无事件即交给外层编译;编译首错恢复默认 `FREECAD_COMPILE_RECOVERY_IDLE_LIMIT=30` 秒无事件收口。两个值保留环境变量覆盖,不能降低已有命令、超时和 patch-conflict 安全边界。
- 实现命令防逃逸:实现回合必须拦截 `npx --prefix <dir> tsc`、`npm --prefix <dir> run build` 以及复合 `git diff/status`,不能让包装参数绕过验证禁令并把既有类型错误写入当前失败账本。
- Gate 编译缓存:模块 gate 的 TypeScript cache key 必须包含所有直接 TS 输入、Node 和 TypeScript 版本;只有 tsc 成功后写 `.complete` marker,marker/输出任一缺失立即重新编译。证据记录 `compileCacheHit/compileSeconds/workerReadySeconds/dispatchSeconds`,不得缓存 native gate 结果。
- 批次自适应使用最近 3 个同 `(module,tier,family)` 的 `effectiveCycleSeconds`、记录吞吐和失败状态;任一失败缩半,平均超过 420 秒减 4,低于 90 秒且吞吐至少 0.25 record/s 增 8,低于 240 秒增 4,并继续遵守各 family 内存上限。
- 效率优化回归门:修改 scheduler、implementation packet、build reuse、session、gate cache 或 pipeline 后必须运行 `python3 tools/test_scheduler_efficiency.py`。该测试覆盖非标准 gate 名选择、拒绝不兼容 gate、hash 失效、直接 link archive 跟踪、批次增减、token 预测轮换,以及 compile cache 仍真实执行 Worker/native dispatch/resources release;失败时不得加载新调度器。
- 状态查询边界:`show_freecad_web_scheduler.py` 的效率统计默认最多读取最近 20 个周期(`FREECAD_EFFICIENCY_WINDOW` 可覆盖但不超过 50),不能使用 scheduler lifetime 回合数扩大日志扫描范围。
- 外层准备计时:状态中的 `preparationTiming` 分别记录 `continue`、`compact`、`continueRetry`、`checkpointRepair`;正常回合只应出现 `continue`,异常回合才允许出现恢复步骤。
- 批次自适应:未显式指定 `--size` 时,planner 根据上一回合同一 `(module,tier,family)` 的耗时/超时自动缩小或放大下一批,并在 manifest 写入 `targetSizeReason`;复杂批次优先避免撞超时,轻量批次逐步提高吞吐。
- 内存边界:Part `generic-object` 批次默认最多 12 条记录,避免多个 OCCT 2D/3D wrapper 同时构造触发 WASM heap 越界;其它族继续遵循 object-contract 16、普通批次 24 的上限。
- Gate 前后去重:scheduler 只运行一次续接入口;批次状态未变时复用 `module-batch-manifest.json`,上下文输入 `bytes+mtime_ns` 未变时复用 context packet;失败账本按回合内存快照集中写入,重启只导入新的完整周期日志。
- 进度口径:实现阶段以 `featureRoutes`、`featureInteractive`、`featureArtifacts`、`implementationReceipts` 和 `runtimeIssues` 为主。`taskCards` 是历史工作流终态;`apiEvidenceExposed`/`apiClassified` 是后置验证与源码索引,不得再解释为 Web 功能完成率。
- 源码检索边界:禁止从仓库根目录对 `freecad-source`、`web/src` 或 `tools` 做全量 `rg`/`find`/批量 `sed`;优先使用 `python3 tools/fast_source_search.py 'Pattern'` 搜索当前批次 manifest 的源码文件,需要 runtime 适配时显式加 `--runtime`,其它文件必须用受控 `--path` 指定。
- 检索参数兼容:`fast_source_search.py` 同时接受重复 `--path` 和其后的显式路径参数,并使用 intermixed parsing;通配展开不会再因参数位置导致退出 2,所有路径仍经过 workspace 边界校验。
- 检索无匹配语义:`fast_source_search.py` 对 ripgrep 的无匹配退出 1 归一为成功探索(返回 0),真实参数/IO 错误仍返回非零,避免 `rg ... &&` 链误阻断实现。
- 已知失败防线总表:见 `docs/KNOWN_FAILURE_PREVENTION.md`;新增失败模式先归类为可预检或运行时边界,再补对应自动防线,禁止只增加重试次数。
- 新失败自动归档:scheduler 每次保存失败账本同步更新 `docs/current/failure-patterns.json`;未匹配错误进入 `other` 并保留代表命令/首错,后续必须从该索引补充预检或恢复规则。
- 失败分类兜底:即使 stderr 为空,也按 `run_p6_`、`cmake --build`、`prepare_/validate_/rotate_` 命令形态归档为 gate/build/orchestration failure,避免新经验丢入不可操作的 `other`。
- 补丁冲突防线:`apply_patch verification failed`、`invalid patch`、`multiple operations target` 单独归类为 `patch-apply-conflict`;重新读取当前文件后拆成单文件/单目标 patch,禁止原补丁盲目重放。
- 状态检查参数兼容:`check_continuation_state.py --json` 输出稳定 machine-readable 结果,默认文本和 `--quiet` 语义保持不变,避免状态检查因参数退出 2。
- 每次上下文接近预算上限、命令超时或会话压缩,先落盘当前结果和首错,再轮换到当前卡或恢复卡;恢复后只读取新 manifest,不重复无关任务。
- 任务卡结果必须包含 `nextTask`、`nextAction`、`contextRotation` 和 `resumeCommand` 字段或等价 Markdown 条目,保证下一个执行器无需依赖本轮对话即可继续。
- `resumeCommand` 的默认值为:`python3 tools/continue_web_task_cycle.py`;该入口内部先检查账本,仅在批次/上下文指纹变化时生成上下文并运行增量校验。恢复后不得读取旧聊天记录替代 manifest。`validate_web_context.py` 是全量验证入口,在全部移植任务完成后仅响应用户明确指令执行。
- 接续文件读取边界:自动回合只读取本文件第 20-70 行的规则和第 72-85 行的当前检查点;后续旧恢复示例、历史报告和重复命令块仅供人工参考,不得再次加载进上下文或执行。结构化状态以 `task-state.json`、`continuation-state.json` 和当前 context manifest 为准。
- 只有满足“无可执行叶子卡且所有 Y gate 已收口”、或同一外部阻断按恢复协议连续三次复现且无本地替代、或确需用户提供无法从工作区发现的凭据/架构决策,才允许结束并发送最终报告。
## 当前检查点
本节是机器投影,不是独立状态源。每次领取或完成任务必须由
`tools/sync_web_task_state.py` 自动刷新;若本节与 `docs/current/task-state.json`
不一致,以 JSON 为准并先运行同步/校验命令。
- 活动任务:`FW-P6-FPA-Y`
- 任务:FreeCAD Web Full Parity 完整出口
- 状态:`in_progress`
- 当前模块:`full-parity`
- 已构建动态模块资产:32 个逻辑模块(这只表示模块化 WASM 基础,不表示完整业务完成)
- 完整业务状态:`incomplete`;实时差距和 P1-P3 阶段见 `docs/current/web-business-completion-audit.json`
- 唯一状态源:`docs/current/task-state.json`
- 当前交接页:`docs/current/FREECAD_WEB_HANDOFF.md`
- 当前上下文摘要:`docs/current/FREECAD_WEB_CONTEXT_MIN.md`
- 对标矩阵:`docs/web-parity-matrix.json`
- 业务完成审计:`docs/current/WEB_BUSINESS_COMPLETION_AUDIT.md`
### 最近阻断续接状态(2026-08-30)
- BIM 调用协议已统一:`fc_web_dispatch_json` 接受 `{cmd,args}` JSON 并返回结果 JSON;`bim.inspectSourceInventory`、`bim.inspectPythonApi`、`bim.createAxis`、`bim.extrusionData`、`bim.nativeProbe`、`bim.pythonFamily` 已全部经该入口运行,`bim.pythonFamily` 已覆盖 28 个 API,证据为 `docs/p6/bim-dispatch-json.json` 与 `docs/p6/bim-python-family-api.json`。
- Fem 依赖闭包已解除:VTK 9.1(含 HDF5/lz4/lzma/zlib/expat)、MEDFile 4.1、wasm HDF5、OCCT `TKMeshVS` 与内部 Salome SMESH 均由源码构建;`FreeCADWebFemGenericFamilyProbe` 已同步 Web,Node smoke 返回 `registered=41/missing=0`。`fem.action` 的 `create/recompute`、`inspect/source-inventory` 走 native probe,Python/save-reopen 仍等待方法级 ABI。
- ArchComponent/FeaturePython 阻断已解除:补回官方 Arch preferences 的 `MoveBase=False`、`MoveWithHost=True` 默认值后,`bim.nativeProbe` 的 `archcomponent-import`、`archcomponent-properties`、`archcomponent-create`、`featurepython-base` 均由 WASM 稳定通过 TypeId/Proxy/重算/资源释放;历史 code 7 仅保留为修复前证据。
- Arch Axis 对象族也已解除:`bim.createAxis` 使用 native `PropertyFloatList::setValues` 后返回 `Part::FeaturePython`/`Axis`、3 条边、重算和资源释放,已从 policy 放行;历史 code 7 仅保留为修复前证据。
- Legacy IFC importer 阻断已解除:BIM staging 纳入同一 Emscripten Python 构建的顶层纯 Python `.py` 模块和本地 Assimp/Qt3D 提供的官方 IFC2X3 EXPRESS schema;修复 parser 的 schema section、`pyopen`、`copy` 缺口后,`legacy-import`、`legacy-python-parser`、`legacy-parser-fixture` 均由 WASM 通过。IfcOpenShell 不在提供的源码树中,专用外部 ABI/导出仍是明确的 `native_source_required` 边界。
- 最新 BIM probe 产物:`freecad-source/build-web/configure/bin/FreeCADWebBimRuntimeProbe.{js,wasm,data}`,已同步到 `web/public/kernel/`;Web `bim.worker` 已接入 `bim.nativeProbe` facade。
## 立即续接
从项目目录执行:
~~~sh
python3 tools/check_continuation_state.py
python3 tools/continue_web_task_cycle.py
python3 - <<'PY'
import json
s=json.load(open('docs/current/continuation-state.json'))
t=json.load(open('docs/current/task-state.json'))
assert s['autoAdvance'] is True and s['activeTask'] == t['active_task']
print('continuation checkpoint:', s['activeTask'], s['phase'])
PY
~~~
需要启动长期自动调度时执行:
~~~sh
python3 tools/run_freecad_web_scheduler.py
~~~
为保证调度器意外退出后自动恢复,长期运行时同时启动独立监督进程(默认每回合 1800 秒时间片):
~~~sh
nohup setsid python3 tools/watch_freecad_web_scheduler.py --interval 10 --timeout 1800 --idle-delay 30 > docs/current/freecad-web-scheduler-watchdog.out 2>&1 < /dev/null &
~~~
状态检查:
~~~sh
cat docs/current/freecad-web-scheduler.pid
python3 tools/check_continuation_state.py
~~~
只读取当前 manifest 中 `mode=read` 的文件,然后执行账本中的活动任务。完成当前卡后,追加卡片 `## 结果`,保存 JSON/日志/hash,使用账本工具关闭当前卡并领取下一张:
```sh
python3 tools/sync_web_task_state.py --set <CURRENT_TASK>=completed --active <NEXT_LEAF_TASK>
python3 tools/prepare_web_task_context.py
python3 tools/validate_incremental_context.py
```
不得读取完整源码树、完整 inventory、原始日志或归档来代替 manifest;不得同时领取多个 `in_progress` 任务。
账本工具在 `--active NEXT` 时会自动清理遗留的旧 `in_progress` 投影,保证始终只有一个可执行活动任务;外部依赖阻断时保留 `blocked` 和恢复卡,再领取不依赖它的任务。
`--active` 必须指向模块目录下的叶子任务卡,不能指向 `FW-P6-<MODULE>` 模块包;被标记为 `blocked` 的卡不能直接领取,必须先有明确恢复动作。每次切换后必须运行校验器;校验失败时不得领取下一卡。
## 连续执行协议(强制)
“按 nextTask.md 接续执行”是连续循环,不是只处理一张卡的建议。执行者必须在当前回合持续推进,不在卡片之间等待确认、询问是否继续或只提交计划。
每轮严格执行(实现优先阶段):
1. `校验`:以 `docs/current/task-state.json` 为唯一状态源,运行 `check_continuation_state.py`;只有批次或上下文指纹变化、缺失或修复后才运行 `prepare_web_task_context.py`,随后运行 `validate_incremental_context.py`。只校验当前活动批次和上下文,活动卡若已 `completed/blocked`,先领取真实的下一个叶子卡。全量 `validate_web_context.py` 不在移植过程中运行。
2. `读取`:只读取当前 manifest 的 `mode=read` 文件;源码只按当前卡命令定点读取,不加载完整源码树、inventory、归档或原始日志。
3. `执行`:优先完成当前卡的源码、依赖闭包、WASM、Facade、Worker、React 入口和跨模块功能链;按功能批次推进,不因 exhaustive Chrome/逐 API smoke 尚未完成而停顿。命令仍必须等待进程结束,超时或断流不得视为通过。
4. `保存`:追加任务卡 `## 结果`,保存实现产物、变更范围、输入/输出路径和已知边界;后置验证阶段再补 JSON、日志、输入/结果/WASM/截图 hash。首次失败只新增 R1/R2 文件,不覆盖已有证据。
5. `闭环`:先校验产物,再运行 `sync_web_task_state.py --set CURRENT=completed --active NEXT_LEAF`,随后立即回到第 1 步。动作拆分卡必须连续执行 C→D→E→F→G,不能在中间停顿。
连续循环伪代码:`while (可执行任务 || active_task) { load_context(); implement(); persist_result(); rotate(); sync(); prepare(); }`。不得在循环体内发送最终答复;中间进度只能写入任务卡、handoff 和账本。
执行者不得因为“当前卡已完成”“已生成报告”“验证尚未集中执行”或“已经取得阶段性进展”而发送最终答复;这些都只是循环中的中间状态。长命令必须用等待机制取得最终结果,随后继续下一卡。只有终止条件成立时才结束回合并发送最终报告。
## 上下文隔离与超时
- 每张任务卡使用独立上下文空间;不得把上一张卡的 manifest、源码扫描、原始日志或大证据带入下一张卡。
- 完成当前卡并保存结果后,由外层 scheduler 执行一次 `rotate_web_task_context.py --reason completed --next-task NEXT_LEAF`、`sync_web_task_state.py --active NEXT_LEAF` 和 `prepare_web_task_context.py`;Codex 回合内部不得重复调用这些轮换/准备工具。上下文 manifest 的 `bytes+mtime_ns` 指纹未变化时直接复用,变化时才重建并增量校验。
- 命令、浏览器、代理或上下文操作超时后,立即保存首个错误摘要,执行 `rotate_web_task_context.py --reason timeout --next-task CURRENT_OR_RECOVERY`,压缩后只重试一次;超时不能写成通过。
- 轮换工具只处理 `docs/current/context/FW-*.json` 机器生成文件;源码、任务卡、证据 JSON、日志、归档和构建产物必须保留。
阻断时:记录首个可复现错误、命令、输入 hash 和恢复卡,将卡标记 `blocked`,立即领取第一个不依赖该阻断的 pending 叶子卡;不得伪造 `pass`,不得反复领取同一 blocked 卡。
compact、代理或网络断流时:从本地账本、交接页和 context manifest 恢复,不重做无关任务;任何仍在运行的命令必须先等待完成或明确终止,再切换下一卡。
只有所有可执行任务和相应 Y gate 完成、同一外部阻断按恢复卡连续三次复现且无本地替代,或需要用户提供本地无法发现的凭据/决策时才终止。普通失败、上下文压缩、单次网络错误、工作量大或单卡完成都不是终止条件。
## 完整对标范围
下表来自当前 `docs/web-parity-matrix.json`。模块只有对应 Y gate 才能变为 `completed`;首切片 X gate 不代表模块完成。每个动作必须独立完成 C-G 子链。
| 模块 | 状态 | 必须对标动作 | 对象数 | 格式 | Python API |
|---|---|---|---:|---|---:|
| Assembly | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 8 | .fcstd | 552 |
| BIM | completed | import/export, inspect/source-inventory, python-api | 0 | .brp, .dae, .dxf, .fcstd, .ifc, .json, .obj, .stp, .svg | 2366 |
| CAM | completed | create/recompute, import/export, inspect/source-inventory, python-api, save/reopen | 12 | .fcstd, .json, .obj, .step, .svg | 2883 |
| Cloud | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 0 | - | 3 |
| Draft | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 0 | .dxf, .obj, .svg | 2043 |
| Fem | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 53 | .brep, .json, .obj, .svg, .txt | 1305 |
| Help | completed | inspect/source-inventory, python-api | 0 | - | 14 |
| Import | completed | create/recompute, import/export, inspect/source-inventory, python-api, save/reopen | 2 | .ifc, .igs, .obj, .step, .stp | 1135 |
| Inspection | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 3 | - | 3 |
| JtReader | completed | create/recompute, inspect/source-inventory, save/reopen | 1 | - | 0 |
| Material | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 22 | - | 178 |
| Measure | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 11 | - | 31 |
| Mesh | completed | create/recompute, import/export, inspect/source-inventory, python-api, save/reopen | 31 | .3mf, .amf, .ast, .obj, .off, .ply, .stl | 211 |
| MeshPart | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 0 | - | 13 |
| OpenSCAD | completed | inspect/source-inventory, python-api | 0 | .dxf | 294 |
| Part | pending | create/recompute, import/export, inspect/source-inventory, python-api, save/reopen | 116 | .brep, .brp, .fcstd, .iges, .igs, .obj, .step, .stp, .svg | 1191 |
| PartDesign | pending | create/recompute, inspect/source-inventory, python-api, save/reopen | 65 | - | 238 |
| Plot | pending | inspect/source-inventory, python-api | 0 | - | 28 |
| Points | pending | create/recompute, inspect/source-inventory, python-api, save/reopen | 8 | .obj, .ply | 12 |
| ReverseEngineering | pending | create/recompute, inspect/source-inventory, python-api, save/reopen | 0 | - | 3 |
| Robot | pending | create/recompute, inspect/source-inventory, python-api, save/reopen | 6 | - | 16 |
| Sandbox | completed | create/recompute, inspect/source-inventory, python-api, save/reopen | 2 | .ast, .obj, .stl | 30 |
| Show | pending | inspect/source-inventory, python-api | 0 | - | 104 |
| Sketcher | pending | create/recompute, inspect/source-inventory, python-api, save/reopen | 10 | - | 141 |
| Spreadsheet | pending | create/recompute, inspect/source-inventory, python-api, save/reopen | 5 | .csv | 63 |
| Start | pending | create/recompute, inspect/source-inventory, python-api, save/reopen | 0 | .fcstd, .svg | 2 |
| Surface | pending | create/recompute, inspect/source-inventory, python-api, save/reopen | 7 | - | 10 |
| TechDraw | pending | create/recompute, import/export, inspect/source-inventory, python-api, save/reopen | 41 | .dxf, .svg | 247 |
| TemplatePyMod | pending | inspect/source-inventory, python-api | 0 | - | 244 |
| Test | pending | inspect/source-inventory | 0 | .fcstd, .obj | 0 |
| Tux | pending | inspect/source-inventory, python-api | 0 | - | 25 |
| Web | pending | create/recompute, inspect/source-inventory, save/reopen | 0 | - | 0 |
## 合同顺序
每个模块先执行:
`A 源码边界` → `B WASM 注册` → `C 一个主要动作` → `D 错误/重算/恢复` → `E Facade/Worker` → `F Chrome` → `G 持久化或不适用边界` → `X 首切片 gate` → `ACT-n C-G` → `Y 完整模块 gate`
统一要求:后台和内核能力必须由真实 FreeCAD C++/Python/WASM 源码执行;JavaScript/TypeScript 只负责 Worker、Facade、消息编排和界面适配。Chrome 只使用 Google Chrome、`headless-new`、`1440x900`、DPR 1,记录版本、网络请求、异常和截图 hash。失败只保留首个可复现错误并新增 R1/R2 恢复卡;不适用必须写清原因。
## 可复制的持续执行提示词
将下列代码块完整复制给 Codex,或直接输入本文件开头约定的 `按 nextTask.md 接续执行`:
```text
按 nextTask.md 接续执行。启用不停歇、无需确认、实现优先模式:在用户已授权仓库范围内自动完成源码编辑、构建、资源补充、同步、证据落盘、上下文轮换、账本切换、超时单次重试和恢复卡创建;阶段之间 `never_between_phases`,不得等待、暂停或请求确认;不要只给计划,不要因单卡完成或验证后置而结束;完成当前卡后立即轮换上下文并领取下一张叶子卡,持续执行到 nextTask.md 的终止条件。只有缺少凭据、超范围不可逆操作或无法从源码推断的新架构决策才暂停,并且必须落盘为真实阻断后继续其它可执行任务。
自动续接状态机固定为:LOAD_STATE → VALIDATE → PREPARE_CONTEXT → READ_MANIFEST → IMPLEMENT_BATCH → RECORD_RESULT → ROTATE_CONTEXT → SYNC_STATE → PREPARE_NEXT → CONTINUE。每轮只保留一个 in_progress;平台单回合结束或上下文压缩后,下一次触发从账本和新 manifest 恢复,不依赖旧对话。除非 TERMINATE 条件成立,否则不得发送最终答复。每次恢复前先运行只读检查器 `python3 tools/check_continuation_state.py`。
从项目根目录读取 `nextTask.md`,以 `docs/current/task-state.json` 为唯一状态源,然后立即运行:
~~~sh
python3 tools/continue_web_task_cycle.py
python3 tools/check_continuation_state.py
python3 - <<'PY'
import json
s=json.load(open('docs/current/continuation-state.json'))
t=json.load(open('docs/current/task-state.json'))
assert s['autoAdvance'] is True and s['activeTask'] == t['active_task']
PY
~~~
只读取当前 context manifest 中 `mode=read` 的文件,并从 `active_task` 继续。始终只有一个 `in_progress` 任务;不等待确认、不询问是否继续、不在任务卡之间停顿。
每张任务卡必须完成以下闭环:
1. 按当前卡命令定点读取源码、CMake、已有 probe 和小型证据;禁止加载完整源码树、完整 inventory、归档或原始大日志。
2. 执行真实 FreeCAD C++/Python/WASM 构建、native smoke、Worker/Facade、Google Chrome 或持久化测试。后台、内核、计算、文档和持久化能力不得用纯 JavaScript、静态 JSON、硬编码几何或假结果替代。
3. 记录输入、命令、FreeCAD revision、WASM/JS/截图/结果 SHA-256;保存 JSON、日志和边界说明。首次失败只新增 R1/R2 证据,不覆盖原始成功或失败证据。
4. 追加当前任务卡 `## 结果`,先验证产物,再关闭当前卡并领取下一张:
~~~sh
python3 tools/rotate_web_task_context.py --reason completed --next-task NEXT_LEAF
python3 tools/sync_web_task_state.py --set CURRENT_TASK=completed --active NEXT_LEAF
python3 tools/prepare_web_task_context.py
python3 tools/validate_incremental_context.py
~~~
当前阶段采用“实现优先、验证后置”的高吞吐模式:先完成真实 FreeCAD C++/Python/WASM 功能链、统一 Worker/Facade、模块入口、生成式 dispatch 和跨模块组合;逐 API/逐对象 exhaustive smoke、Chrome 矩阵、性能和发布 gate 延后到实现批次稳定后集中执行。后置验证期间仍不得把未验证能力写成 `pass`。
不得将“先不验证”解释为“可以跳过编译、资源接线或错误处理”;实现阶段保留最小编译/类型/资源存在检查,所有完整验证集中后置。
全量验证触发规则:当前功能模块实施不运行任何验证,验证不参与完成条件。
## 历史 API/任务卡路线(全部停用,仅保留追溯)
以下旧实现卡、BIM/API family 和验证说明不得被 planner 或调度器执行。当前有效路线从后面的“模块业务包协议”重新开始。
实现快车道当前顺序:`FW-P6-FPA-IMPL-CORE → FW-P6-FPA-IMPL-MAIN-CHAIN → FW-P6-FPA-IMPL-DOCUMENT-STATE → FW-P6-FPA-IMPL-OBJECT-DISPATCH → FW-P6-FPA-IMPL-FORMAT-CHAIN → FW-P6-FPA-IMPL-PYTHON-FAMILY → FW-P6-FPA-IMPL-WORKBENCH → FW-P6-FPA-IMPL-VIEW-INTERACTION → FW-P6-FPA-IMPL-QUALITY → FW-P6-FPA-IMPL-TAIL-FAMILY → FW-P6-FPA-IMPL-TAIL-APP → FW-P6-FPA-IMPL-TAIL-SECONDARY → FW-P6-FPA-IMPL-TAIL-UTILITY → FW-P6-FPA-IMPL-TAIL-CLOUD → FW-P6-FPA-IMPL-MEASURE-API → FW-P6-FPA-IMPL-PART-TIER2 → FW-P6-FPA-IMPL-PARTDESIGN-TIER2 → FW-P6-FPA-IMPL-SKETCHER-TIER2 → FW-P6-FPA-IMPL-TECHDRAW-TIER2 → FW-P6-FPA-IMPL-IMPORT-TIER2 → FW-P6-FPA-IMPL-MESH-TIER2 → FW-P6-FPA-IMPL-TIER2-REMAINDER → FW-P6-FPA-IMPL-TIER3-STATEFUL → FW-P6-FPA-IMPL-TIER3-DOCUMENT → FW-P6-FPA-IMPL-TIER3-FCSTD → FW-P6-FPA-IMPL-TIER3-FAMILY → FW-P6-FPA-IMPL-VIEWPROVIDER-FAMILY → FW-P6-FPA-IMPL-PROPERTY-FAMILY → FW-P6-FPA-IMPL-GEOMETRY-FAMILY → FW-P6-FPA-IMPL-DOCUMENT-GRAPH → FW-P6-FPA-IMPL-RENDER-PIPELINE → FW-P6-FPA-IMPL-PROJECT-SESSION → FW-P6-FPA-IMPL-PYTHON-RUNTIME → FW-P6-FPA-IMPL-PYTHON-API-CALL → FW-P6-FPA-IMPL-CAPABILITY-BOUNDARY → FW-P6-FPA-IMPL-NAVIGATION → FW-P6-FPA-IMPL-SESSION-PERSISTENCE → FW-P6-FPA-IMPL-PLUGIN-MODULE → FW-P6-FPA-IMPL-RECOVERY-CONTROLLER → FW-P6-FPA-IMPL-DOCUMENT-UI → FW-P6-FPA-IMPL-LONGTAIL-ROUTES → FW-P6-FPA-IMPL-TIER1-READONLY → FW-P6-FPA-IMPL-TIER4-RESTRICTED → FW-P6-FPA-IMPL-APP-SERVICES → FW-P6-FPA-IMPL-EXPORT-SERVICE → FW-P6-FPA-IMPL-FORMAT-EXPORT-ABI → FW-P6-FPA-IMPL-IMPORT-USER-FILE → FW-P6-FPA-IMPL-IMPORT-RENDER → FW-P6-FPA-IMPL-SCENE-ISOLATION → FW-P6-FPA-IMPL-QUEUE-RECOVERY-UI → FW-P6-FPA-IMPL-UI-ACCESSIBILITY → FW-P6-FPA-IMPL-API-REPLAY → FW-P6-FPA-IMPL-FULL-ORCHESTRATOR → FW-P6-FPA-IMPL-API-ADAPTER-FILL → FW-P6-FPA-IMPL-API-METHOD-BRIDGE → FW-P6-FPA-IMPL-PART-PYTHON-FUNCTIONS → Document/Part/PartDesign/Sketcher/TechDraw/格式/Python 主链 → 长尾工作台 → 后置 F1/F2/F3/F4 gate`。实现卡只关闭代码和可运行路由合同,验证卡负责最终 disposition,不得混淆两者。
实现阶段主线为:`源码入口/依赖闭包 → native runtime → 统一 Document/Property/Link actor → 生成式 Python/API dispatch → React/Worker 模块入口 → 跨模块功能链 → 后置验证与 gate`。模块只有对应 Y gate 才能变为 `completed`;P6 slice gate 不代表完整 FreeCAD 对标完成。
当前追加连续实现段:`FW-P6-FPA-IMPL-API-ADAPTER-FILL → FW-P6-FPA-IMPL-API-METHOD-BRIDGE → 后续 module+tier+family 功能批次`。每轮先生成批次清单,再一次贯通该批次的源码入口、依赖闭包、native/WASM dispatcher、Facade/Worker/React 适配和批量证据;验证统一后置,不能在单条 API 之间停顿。
当前活动后的下一段实现:`FW-P6-FPA-IMPL-SKETCHER-PYTHON-FUNCTIONS → FW-P6-FPA-IMPL-TECHDRAW-PYTHON-FUNCTIONS → FW-P6-FPA-IMPL-FORMAT-EXTENSIONS → 后续 module+tier+family native bridge`,继续自动领取、实现、落盘、轮换上下文,不等待确认。
格式扩展完成后的连续实现段:`FW-P6-FPA-IMPL-MESH-PYTHON-FUNCTIONS → FW-P6-FPA-IMPL-POINTS-PYTHON-FUNCTIONS → FW-P6-FPA-IMPL-SURFACE-PYTHON-FUNCTIONS → 后续 MeshPart/CAM/Measure family bridge`。
Points 完成后继续:`FW-P6-FPA-IMPL-SURFACE-PYTHON-FUNCTIONS → FW-P6-FPA-IMPL-MESHPART-PYTHON-FUNCTIONS → FW-P6-FPA-IMPL-CAM-PYTHON-FUNCTIONS → 后续 module+tier+family native bridge`。
CAM 完成后继续:`FW-P6-FPA-IMPL-FEM-BOUNDARY → FW-P6-FPA-IMPL-DRAFT-PYTHON-FUNCTIONS → FW-P6-FPA-IMPL-MATERIAL-PYTHON-FUNCTIONS → 后续 module+tier+family native bridge`。
源程序接线优先级:已有 `freecad-source` probe 的命令直接复用其 WASM ABI;没有 probe/ABI 的命令必须保持 `native_source_required` 或 `blocked_native_dependency`,先创建恢复卡,不得回退到历史 JS slice。
当前 BIM 恢复段:`FW-P6-FPA-IMPL-BIM-PYTHON-CLOSURE → FW-P6-FPA-IMPL-BIM-PYTHON-RUNTIME-R1 → 后续 Arch/IFC native bridge`;R1 首先收敛 Emscripten embedded-file FS 布局,再继续官方 ArchCommands callable。
当前 BIM Arch 连续实现段:`FW-P6-FPA-IMPL-BIM-ARCH-FAMILY → 后续 Arch/IFC/format native bridge`。
当前 BIM Component 恢复段已收口:`FW-P6-FPA-IMPL-BIM-COMPONENT-R1` 已完成,`makeComponent` 已通过 native 生命周期 ABI;后续仅扩展 Component 属性/API family,不回退到 JS slice。
当前 BIM IFC 连续实现段:`FW-P6-FPA-IMPL-BIM-IFC-BOUNDARY → 后续 IFC/importer native bridge`。
当前 ArchIFC 连续实现段:`FW-P6-FPA-IMPL-BIM-IFC-PYTHON → 后续 IFC/importer native bridge`。
当前 BIM 对象连续实现段:`FW-P6-FPA-IMPL-BIM-NATIVE-OBJECTS → 后续 Arch/IFC/multi-object native bridge`。
当前 BIM Arch 只读连续实现段:`FW-P6-FPA-IMPL-BIM-ARCH-READONLY → 后续 Arch/IFC/multi-object native bridge`;已完成的 Component/Axis FeaturePython native ABI 继续复用,不回退到 JS slice。
当前 IFC 几何连续实现段:`FW-P6-FPA-IMPL-BIM-IFC-GEOMETRY → 后续 IFC/importer native bridge`。
当前 Legacy IFC 恢复段已收口:`FW-P6-FPA-IMPL-BIM-IFC-LEGACY-BOUNDARY` 已完成内部 Python parser/import fixture;后续 IfcOpenShell 专用 ABI 继续作为显式 native boundary。
当前 BIM metadata 连续实现段已收口:`FW-P6-FPA-IMPL-BIM-METADATA` 已完成;后续 metadata 扩展统一注册到 `fc_web_dispatch_json`,再进入 IFC/importer native bridge。
历史 BIM/API 和 13,386 API 批次规则全部停用。`docs/p6/python-api-manifest.json` 可以作为人工查找 FreeCAD 源码的索引,但自动执行器、planner、完成审计和调度状态不得从中领取实施任务。
### 模块业务包协议(最高优先级)
- 推进单位是可直接使用的完整功能模块;禁止把 API、类、方法或源码符号建成任务、Worker、页面、WASM 或独立编译。
- 每个模块按 `桌面命令 → 对象/几何/属性/Document 内部行为 → 导入导出/持久化 → React 交互` 连续完善。已有 native handler、WASM、Facade、Worker、React 工作流和实现回执必须直接复用,不得重写。
- 一个模块业务包只扩展一个共享 native adapter、统一 `fc_web_dispatch_json({cmd,args})`、模块 Facade/Worker 和动态 WASM;内部类/方法由模块源码直接调用,不建立公开 API 映射。
- 格式阶段按 `(module, direction, extension)` 聚合真实用户工作流,同一模块的多个格式一次实现和链接;忽略只在测试/文档出现、没有 import/export 方向的扩展名记录。
- 最终产品阶段将当前分散的 React/诊断页面合并为唯一工作页面,复用对象树、属性、任务面板、多文档、工作台、3D 视图、格式和 Python Console 模块。
- 实施阶段不运行 focused gate、逐 API smoke、Chrome、Full Parity、性能或发布验证。只执行编译/链接、资源同步和 implementation receipt;编译失败只处理当前模块首错。
- 结构化进度以 `docs/current/web-business-completion-audit.json` 为准;路由、源码分类、构建回执和最终验证不得互相替代。
实现阶段构建策略:
- 优先复用已有依赖闭包和 native probe,避免重复编译;新增模块先完成可运行构建和入口,再集中补 Chrome/性能/内存 gate。
- 大批次按模块功能链拆分,不读取或处理 API 清单;先完成剩余桌面功能回执,再完成模块格式能力和 React 主工作页面。
历史后置验证要求(当前不执行,也不参与完成条件):
- 所有 WASM 链接保持 `ERROR_ON_UNDEFINED_SYMBOLS=1`;不得用 host `.so/.a` 代替 Emscripten archive。
- Chrome 只使用 Google Chrome、`headless-new`、`1440x900`、DPR 1;记录版本、网络请求、外部请求、控制台异常、运行时异常和截图 hash。
- Worker 必须验证 ready、success、expected-error、duplicate、cancel、reset、repeat、异常语义和资源释放。
- FCStd 必须比较对象类型、属性、依赖、重算结果、恢复状态和语义 round-trip;不得只比较 ZIP 字节。
实现批次的收尾顺序固定为:`真实源码行为 → capability route → 目标级增量 build → artifact sync → implementation receipt → planner`。`featureRoutes=100%` 只表示命令已有 Worker/native 路由,不能替代构建回执;只要 `module-build-pending.json` 仍有 target,就不得把实现阶段描述成完全收口。调度器在 `no_ready_batch` 后必须先运行 `flush_deferred_module_builds.py`,成功才移除对应 pending batch;失败保留首错并退避重试,严禁伪造成功或高频空转。全量 runtime/gate 验证仍等待用户明确指令。
最后两个 feature 命令的恢复结果:`Start:desktop:Start_Start` 使用 `start.worker.ts → fc_web_dispatch_json` direct route,目标 `FreeCADWebStartRuntimeProbe` 已增量链接;`TemplatePyMod:desktop:TemplatePyMod_Cmd5` 使用 `templatepymod.pythonFamilyBatch`,由 embedded FreeCAD/Part 创建真实 cone 文档对象,目标 `FreeCADWebTemplatePyModRuntimeProbe` 已增量链接。二者都已有 `implementation_ready` build receipt,验证状态继续保持 deferred,不得写成 full-parity pass。
失败、阻断和超时:
- 遇到问题先利用现有源码、相关资料、已有 probe、依赖缓存和本地资源解决;优先修复初始化、ABI、CMake、依赖闭包、fixture 或批次拆分。
- 超时、代理断流或上下文操作失败时,立即保存首个错误摘要,然后执行:
~~~sh
python3 tools/rotate_web_task_context.py --reason timeout --next-task CURRENT_OR_RECOVERY
~~~
压缩上下文后只重试一次;超时不能写成 pass。
- 外部依赖阻断时记录首错、命令、输入 hash、恢复卡和可替代资源,标记 `blocked`,立即领取第一个不依赖该阻断的 pending 叶子卡。
- 同一外部阻断连续三次复现且没有本地替代时才保持 blocked;不得关闭检查、降低 gate 或伪造 pass。
- `compact`、网络中断或会话恢复时,从 `task-state.json`、`FREECAD_WEB_HANDOFF.md`、`FREECAD_WEB_CONTEXT_MIN.md` 和当前 manifest 恢复,不重做无关任务。
每完成一个实现批次,立即报告当前实现进度;后置验证开启后再追加完整 gate 进度:
- active task;completed/in_progress/planned/blocked 任务数;
- 13,385 API 的 exposed/restricted/nonportable/not_implemented/planned 数量;
- 本次新增实现、测试、证据路径和 SHA-256;
- 当前阻断及恢复卡;下一张活动任务;上下文 validator/prepare 结果。
实现阶段只有在无法继续编译/链接、需要用户提供本地无法发现的凭据或关键架构决策时才暂停;普通测试缺口不得阻止继续实现。后置验证阶段再按所有可执行任务、Y gate 和外部阻断规则收口并发送最终报告。
```
## 安全和保存边界
- 密码、API key、token 不写入配置、提交、远端 URL 或日志。
- 构建目录、dist、node_modules、原始日志和临时文件不作为源码提交物。
- 源码 Git 仓库为 `freecad-source`;外层 `docs/`、`web/` 是否纳入远端,以仓库实际 Git 边界为准,不擅自重组。
- 当前源码远端为 `gitea`;推送前检查差异、提交内容和远端分支,避免提交秘密或生成产物。

View File

@@ -46,6 +46,7 @@
"check:tools-manual": "node ../tools/build-tools-manual.mjs --verify && node ../tools/check-tools-manual.mjs",
"build:console": "node tools/teaching-console/build-console.mjs",
"check:console": "node tools/teaching-console/build-console.mjs --check && node tools/teaching-console/self-test.mjs",
"check:console-inapp": "node tools/teaching-console/check-inapp-console.mjs",
"teach:console": "node teaching/server.mjs",
"reducer:list": "node ../tools/reducer/list.mjs",
"reducer:part": "node ../tools/reducer/create-part.mjs",

82
web/src/navigation.ts Normal file
View File

@@ -0,0 +1,82 @@
export interface NavigationRoute { id: string; label: string; href: string; scope: "core" | "workflow" | "runtime"; }
export interface NavigationContext { documentId?: string; module?: string; command?: string; }
import { WEB_MODULE_REGISTRY } from "./module-registry.generated.js";
export const WEB_NAVIGATION_ROUTES: readonly NavigationRoute[] = [
{ id: "home", label: "3D 视图", href: "/index.html", scope: "core" },
{ id: "document", label: "Document", href: "/document.html", scope: "core" },
{ id: "main-chain", label: "主链", href: "/main-chain.html", scope: "workflow" },
{ id: "project", label: "工程", href: "/project.html", scope: "workflow" },
{ id: "full", label: "全线", href: "/full.html", scope: "workflow" },
{ id: "workbench", label: "工作台", href: "/workbench.html", scope: "workflow" },
{ id: "teaching-console", label: "教学", href: "/teaching-console.html", scope: "workflow" },
{ id: "python", label: "Python", href: "/python.html", scope: "runtime" },
...WEB_MODULE_REGISTRY.map((route) => ({ id: `module-${route.module}`, label: route.module, href: moduleHref(route.module), scope: "workflow" as const })),
];
const CONTEXT_KEYS: readonly [keyof NavigationContext, string][] = [
["documentId", "document"],
["module", "module"],
["command", "command"],
];
function contextValue(value: string | null | undefined): string | undefined {
if (!value) return undefined;
const normalized = value.trim();
return normalized.length > 0 && normalized.length <= 160 ? normalized : undefined;
}
export function readNavigationContext(source: Pick<Location, "search"> = window.location): NavigationContext {
const params = new URLSearchParams(source.search);
return Object.fromEntries(CONTEXT_KEYS.flatMap(([key, queryKey]) => {
const value = contextValue(params.get(queryKey));
return value ? [[key, value]] : [];
})) as NavigationContext;
}
export function navigationHref(route: NavigationRoute, context: NavigationContext = readNavigationContext()): string {
if (route.id.startsWith("module-")) context = { documentId: context.documentId, module: route.id.slice(7) };
const url = new URL(route.href, window.location.origin);
for (const [key, queryKey] of CONTEXT_KEYS) {
const value = contextValue(context[key]);
if (value) url.searchParams.set(queryKey, value);
else url.searchParams.delete(queryKey);
}
return `${url.pathname}${url.search}${url.hash}`;
}
export function updateNavigationContext(context: NavigationContext, mode: "push" | "replace" = "replace"): void {
const url = new URL(window.location.href);
for (const [key, queryKey] of CONTEXT_KEYS) {
const value = contextValue(context[key]);
if (value) url.searchParams.set(queryKey, value);
else url.searchParams.delete(queryKey);
}
const next = `${url.pathname}${url.search}${url.hash}`;
if (mode === "push") window.history.pushState({ navigationContext: context }, "", next);
else window.history.replaceState({ navigationContext: context }, "", next);
document.querySelectorAll<HTMLAnchorElement>(".global-nav a[data-route]").forEach(link => {
const route = WEB_NAVIGATION_ROUTES.find(route => route.id === link.dataset.route);
if (route) link.href = navigationHref(route, context);
});
}
function moduleHref(module: string): string {
return `/workbench.html?module=${encodeURIComponent(module)}`;
}
export function installNavigation(currentId: string, context: NavigationContext = readNavigationContext()): void {
if (document.querySelector(".global-nav")) return;
const nav = document.createElement("nav");
nav.className = "global-nav";
nav.setAttribute("aria-label", "FreeCAD Web navigation");
nav.innerHTML = WEB_NAVIGATION_ROUTES.map((route) => `<a href="${navigationHref(route, context)}" data-route="${route.id}"${route.id === currentId ? " aria-current=page" : ""}>${route.label}</a>`).join("");
if (context.documentId) nav.dataset.documentId = context.documentId;
if (context.module) nav.dataset.module = context.module;
if (context.command) nav.dataset.command = context.command;
const style = document.createElement("style");
style.textContent = ".global-nav{align-items:center;background:#10161dcc;border-bottom:1px solid #2c3b48;box-sizing:border-box;contain:layout paint;display:flex;gap:4px;width:100%;min-width:0;max-width:100%;overflow-x:auto;padding:5px 12px;position:relative;z-index:10}.global-nav a{border:1px solid transparent;border-radius:4px;color:#9cb6c2;flex-shrink:0;font-size:12px;padding:5px 9px;text-decoration:none;white-space:nowrap}.global-nav a:hover,.global-nav a[aria-current=page]{background:#243b47;border-color:#435464;color:#e7edf3}";
document.head.append(style);
document.body.prepend(nav);
}

View File

@@ -1,9 +1,12 @@
import React from "react";
import { createRoot } from "react-dom/client";
import { PartDesignWorkspace } from "./partdesign-workspace-component.js";
import { installTeachingBridge } from "./teaching/bridge.js";
import "./panel-scroll.css";
// Lock the page to the viewport so the tree and property panes scroll on their
// own and the 3D viewport keeps its size (see panel-scroll.css).
document.documentElement.classList.add("stage-lock-pd");
// Lets the in-app teaching console drive this page across the iframe boundary.
installTeachingBridge();
createRoot(document.querySelector<HTMLDivElement>("#app")!).render(<PartDesignWorkspace />);

View File

@@ -0,0 +1,10 @@
// Standalone entry for /teaching-console.html.
import { createRoot } from "react-dom/client";
import { installNavigation, readNavigationContext } from "./navigation.js";
import { TeachingConsole } from "./teaching/console-page.js";
installNavigation("teaching-console", readNavigationContext());
const container = document.querySelector<HTMLDivElement>("#app");
if (!container) throw new Error("teaching console entry: #app container is missing");
createRoot(container).render(<TeachingConsole />);

View File

@@ -0,0 +1,46 @@
// Publishes `window.__teaching` in a workbench page, so the console page can
// drive it across the iframe boundary.
//
// Both sides are same-origin documents, so the console simply reaches into
// `frame.contentWindow.__teaching` and calls `run()`. The request and the report
// are plain data and the progress callback is a plain function, so nothing here
// has to serialise.
//
// The runner is a dynamic import: a workbench page pays nothing for the teaching
// stack until a lesson actually starts, and the per-lesson step chunks stay
// unloaded until then too.
import type { LessonReport, LessonRunRequest, RunEvent, TeachingBridge } from "./types.js";
interface BridgeHost {
__teaching?: TeachingBridge;
}
let running = false;
/** Call once per workbench document, before the app renders. */
export function installTeachingBridge(): void {
const host = window as unknown as BridgeHost;
if (host.__teaching) return;
const bridge: TeachingBridge = {
ready: true,
page: `${location.pathname.replace(/^\/+/, "")}${location.search}`,
running: () => running,
cancel: () => {
// The runner module is already loaded while a lesson runs, so this import
// resolves from cache and the abort lands between steps.
void import("./runner.js").then(runner => runner.cancelLesson());
},
run: async (request: LessonRunRequest, onEvent?: (event: RunEvent) => void): Promise<LessonReport> => {
if (running) throw new Error("已有课程在运行");
running = true;
try {
const runner = await import("./runner.js");
return await runner.executeLesson(request, onEvent);
} finally {
running = false;
}
},
};
host.__teaching = bridge;
}

View File

@@ -0,0 +1,404 @@
// The teaching console, running inside Web FreeCAD.
//
// Left: the lesson list. Centre: the real workbench in a same-origin iframe.
// Bottom: the run's terminal, the results table and the verdict.
//
// Nothing here talks to a server. The frame publishes `__teaching` (see
// `bridge.ts`); this page calls it, streams its progress events into the panes,
// and writes the finished report to OPFS. The only way a report leaves the
// browser is the explicit "下载到本地" button.
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isOpfsSupported } from "../storage.js";
import raw from "./generated/lessons.json";
import { downloadReport, persistReport } from "./report-store.js";
import type {
LessonJob,
LessonReport,
PreflightCheck,
RunEvent,
StepRow,
TeachingBridge,
Verdict,
} from "./types.js";
import "./console.css";
interface LessonEntry {
id: string;
groupId: string;
title: string;
level: string;
durationMin: number;
summary: string;
sees: string[];
expect: string;
job: LessonJob;
}
interface GroupEntry {
id: string;
title: string;
workbench: string;
blurb: string;
}
interface LessonData {
groups: GroupEntry[];
lessons: LessonEntry[];
counts: { lessons: number; parts: number; assemblies: number; steps: number };
}
const DATA = raw as unknown as LessonData;
const LESSONS = DATA.lessons;
const GROUPS = DATA.groups;
/** Which shell page a lesson runs against. The self-check needs no argument. */
function lessonPage(lesson: LessonEntry): string {
return "page" in lesson.job ? lesson.job.page : "partdesign.html";
}
function lessonSteps(lesson: LessonEntry): number {
return "steps" in lesson.job ? lesson.job.steps : 0;
}
function frameBridge(frame: HTMLIFrameElement | null): TeachingBridge | null {
try {
const win = frame?.contentWindow as (Window & { __teaching?: TeachingBridge }) | null;
return win?.__teaching?.ready ? win.__teaching : null;
} catch {
// A frame that is not same-origin cannot be driven, and that includes one
// still at about:blank after a reload.
return null;
}
}
function message(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export function TeachingConsole(): React.ReactElement {
const [selectedId, setSelectedId] = useState<string>(LESSONS[0]?.id ?? "");
const [frameKey, setFrameKey] = useState(0);
const [frameReady, setFrameReady] = useState(false);
const [running, setRunning] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const [checks, setChecks] = useState<PreflightCheck[]>([]);
const [rows, setRows] = useState<StepRow[]>([]);
const [progress, setProgress] = useState({ done: 0, total: 0 });
const [report, setReport] = useState<LessonReport | null>(null);
const [saved, setSaved] = useState<string | null>(null);
const [saveError, setSaveError] = useState<string | null>(null);
const [tab, setTab] = useState<"log" | "table">("log");
const [verdicts, setVerdicts] = useState<Record<string, Verdict>>({});
const frame = useRef<HTMLIFrameElement | null>(null);
/** Resolved by the frame's `onLoad` once the bridge answers. */
const ticket = useRef<((ok: boolean) => void) | null>(null);
const selected = useMemo(
() => LESSONS.find(lesson => lesson.id === selectedId) ?? LESSONS[0],
[selectedId],
);
const opfsOk = isOpfsSupported();
const pushLog = useCallback((line: string) => {
setLogs(previous => [...previous.slice(-500), line]);
}, []);
const onEvent = useCallback((event: RunEvent) => {
switch (event.type) {
case "log":
pushLog(event.line);
break;
case "phase":
pushLog(`· ${event.phase}${event.detail ? `:${event.detail}` : ""}`);
break;
case "preflight":
setChecks(previous => [...previous.filter(check => check.id !== event.check.id), event.check]);
break;
case "step":
setRows(previous => [...previous, event.row]);
setProgress({ done: event.index + 1, total: event.total });
break;
}
}, [pushLog]);
/**
* The frame loads its page, then mounts React, then the kernel. The bridge is
* installed before the first render, so waiting for it proves the document is
* ours to drive; the runner's own preflight waits for the workspace itself.
*/
const handleFrameLoad = useCallback(async () => {
setFrameReady(false);
const deadline = Date.now() + 180000;
while (Date.now() < deadline) {
if (frameBridge(frame.current)) {
setFrameReady(true);
ticket.current?.(true);
ticket.current = null;
return;
}
await new Promise(resolve => setTimeout(resolve, 250));
}
ticket.current?.(false);
ticket.current = null;
}, []);
useEffect(() => {
document.body.dataset.runnerState = running ? "running" : report?.verdict ?? "idle";
}, [running, report]);
function selectLesson(id: string) {
if (running || id === selectedId) return;
setSelectedId(id);
setReport(null);
setSaved(null);
setSaveError(null);
setChecks([]);
setRows([]);
setLogs([]);
// Show the page this lesson needs, from a clean document.
setFrameReady(false);
setFrameKey(key => key + 1);
}
async function runLesson() {
if (!selected || running) return;
const armed = new Promise<boolean>(resolve => { ticket.current = resolve; });
setRunning(true);
setReport(null);
setSaved(null);
setSaveError(null);
setChecks([]);
setRows([]);
setLogs([]);
setTab("log");
setProgress({ done: 0, total: lessonSteps(selected) });
pushLog(`开始:${selected.title}`);
// Every lesson starts from a freshly loaded workbench: no state can leak
// from the previous lesson, and the page matches what the lesson names.
setFrameReady(false);
setFrameKey(key => key + 1);
const errorText = (text: string): LessonReport => ({
schema: "freecad-web/teaching-console/in-app-run/v1",
lessonId: selected.id,
title: selected.title,
kind: selected.job.kind,
document: "document" in selected.job ? selected.job.document : null,
startedAt: new Date().toISOString(),
finishedAt: new Date().toISOString(),
seconds: 0,
verdict: "blocked",
reason: text,
steps: 0,
stepsTotal: lessonSteps(selected),
failed: 0,
volume: null,
expected: null,
relativeError: null,
preflight: [],
results: [],
pageErrors: [],
});
const ready = await armed;
const bridge = ready ? frameBridge(frame.current) : null;
if (!bridge) {
const blocked = errorText(`工作台页 ${lessonPage(selected)} 没有在 iframe 内就绪`);
setReport(blocked);
pushLog(`前置未通过:${blocked.reason}`);
setRunning(false);
return;
}
try {
const result = await bridge.run(
{ lessonId: selected.id, title: selected.title, job: selected.job },
onEvent,
);
setReport(result);
setVerdicts(previous => ({ ...previous, [selected.id]: result.verdict }));
pushLog(`判定:${result.verdict} — ${result.reason}`);
try {
setSaved(await persistReport(result));
} catch (error) {
setSaveError(`报告未能写入 OPFS:${message(error)}`);
}
} catch (error) {
const failed = errorText(message(error));
setReport(failed);
pushLog(`异常:${failed.reason}`);
} finally {
setRunning(false);
}
}
function cancelLesson() {
const bridge = frameBridge(frame.current);
bridge?.cancel();
pushLog("已请求取消:当前步骤结束后停止");
}
const shownChecks = report?.preflight?.length ? report.preflight : checks;
const total = progress.total || lessonSteps(selected);
const percent = total ? Math.min(100, Math.round((progress.done / total) * 100)) : 0;
const canRun = Boolean(selected) && frameReady && !running && opfsOk;
return (
<div className="teaching-console">
<header className="tc-head">
<h1>Web FreeCAD 教学控制台</h1>
<span className="tc-sub" title={selected?.expect}>{selected?.expect ?? ""}</span>
<span className="tc-count">
{DATA.counts.lessons} 课 · {DATA.counts.parts} 件 · {DATA.counts.steps} 步
</span>
</header>
<nav className="tc-list" aria-label="课程列表">
{GROUPS.map(group => (
<details key={group.id} className="tc-group" open>
<summary title={group.blurb}>{group.title}</summary>
{LESSONS.filter(lesson => lesson.groupId === group.id).map(lesson => (
<button
key={lesson.id}
type="button"
className="tc-item"
aria-current={lesson.id === selected?.id}
data-lesson-id={lesson.id}
data-verdict={verdicts[lesson.id] ?? undefined}
title={lesson.summary}
onClick={() => selectLesson(lesson.id)}
>
<span className="tc-name">{lesson.title}</span>
<span className="tc-min">{lesson.durationMin}′</span>
</button>
))}
</details>
))}
</nav>
<div className="tc-stage">
<iframe
key={frameKey}
ref={frame}
className="tc-frame"
title="FreeCAD 工作台"
src={`/${selected ? lessonPage(selected) : "partdesign.html"}`}
onLoad={() => { void handleFrameLoad(); }}
/>
{!frameReady && <span className="tc-stage-note">工作台加载中…</span>}
</div>
<footer className="tc-foot">
<div className="tc-foot-left">
<div className="tc-tabs" role="tablist">
<button
type="button"
role="tab"
className="tc-tab"
aria-selected={tab === "log"}
onClick={() => setTab("log")}
>终端</button>
<button
type="button"
role="tab"
className="tc-tab"
aria-selected={tab === "table"}
onClick={() => setTab("table")}
>结果表{rows.length ? `(${rows.length})` : ""}</button>
</div>
{tab === "log"
? <pre className="tc-log" aria-label="运行日志">{logs.join("\n")}</pre>
: (
// A table is `display: table`, so `overflow` on it does nothing:
// the seven columns keep their intrinsic width and push the page
// sideways on a phone. The wrapper is the scroll container.
<div className="tc-table-wrap">
<table className="tc-table" aria-label="步骤结果">
<thead>
<tr><th>步</th><th>动作</th><th>命令</th><th>体积</th><th>期望</th><th>判定</th><th>用时</th></tr>
</thead>
<tbody>
{rows.map(row => (
<tr key={`${row.step}-${row.label}`} data-status={row.status}>
<td className="tc-num">{row.step}</td>
<td>{row.label}</td>
<td>{row.command}</td>
<td className="tc-num">{row.volume ?? "—"}</td>
<td className="tc-num">{row.expectedVolume ?? "—"}</td>
<td>{row.status === "ok" ? "ok" : row.status}</td>
<td className="tc-num">{row.ms} ms</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
<aside className="tc-foot-right">
<div className="tc-verdict">
判定
<span className="tc-badge" data-verdict={report?.verdict ?? (running ? "blocked" : "idle")}>
{report?.verdict ?? (running ? "运行中" : "未运行")}
</span>
</div>
<p className="tc-reason">{report?.reason ?? selected?.summary ?? ""}</p>
<div className="tc-bar"><span style={{ width: `${running ? percent : report ? 100 : 0}%` }} /></div>
<p className="tc-evidence">
{report
? `步数 ${report.steps}/${report.stepsTotal} · 失败 ${report.failed} · 用时 ${report.seconds.toFixed(1)} s`
: `本课 ${lessonSteps(selected)} 步`}
</p>
<table className="tc-checks" aria-label="前置检查">
<tbody>
<tr>
<td className={opfsOk ? "tc-ok" : "tc-no"}>{opfsOk ? "✓" : "✗"}</td>
<td>OPFS {opfsOk ? "可用" : "不可用(此浏览器不支持,无法保存文档)"}</td>
</tr>
{shownChecks.map(check => (
<tr key={check.id}>
<td className={check.ok ? "tc-ok" : "tc-no"}>{check.ok ? "✓" : "✗"}</td>
<td>{check.label}:{check.detail}</td>
</tr>
))}
</tbody>
</table>
{selected?.sees?.length ? (
<p className="tc-evidence">本课应看到:{selected.sees.join(";")}</p>
) : null}
{report?.pageErrors?.length ? (
<p className="tc-evidence tc-no">页面错误 {report.pageErrors.length} 条,详见证据。</p>
) : null}
<div className="tc-actions">
<button
type="button"
className="tc-button"
data-primary="true"
disabled={!canRun}
onClick={() => { void runLesson(); }}
>{running ? "运行中…" : "运行本课"}</button>
<button type="button" className="tc-button" disabled={!running} onClick={cancelLesson}>取消</button>
<button
type="button"
className="tc-button"
disabled={!report}
onClick={() => { if (report) downloadReport(report); }}
>下载到本地</button>
</div>
<p className="tc-evidence">
{saved ? `证据已写入 OPFS freecad-exports/${saved}` : null}
{saveError ? <span className="tc-no">{saveError}</span> : null}
{!saved && !saveError ? "报告在每课结束后写入 OPFS;下载需手动点击。" : null}
</p>
{!frameReady && !running ? <p className="tc-evidence">工作台尚未就绪,运行按钮暂不可用。</p> : null}
</aside>
</footer>
</div>
);
}

View File

@@ -0,0 +1,184 @@
/* The in-app teaching console: lesson list, live workbench, run report. */
body:has(> #app > .teaching-console) {
display: flex;
flex-direction: column;
height: 100dvh;
margin: 0;
overflow: hidden;
}
body:has(> #app > .teaching-console) > #app {
flex: 1;
min-height: 0;
}
.teaching-console {
--line: #2c3b48;
--panel: #0e141a;
--cell: #131b22;
--ink: #e7edf3;
--dim: #9cb6c2;
--pass: #4fd08a;
--fail: #ff7a6b;
--blocked: #f0c04a;
--cancelled: #8a9aa6;
background: #0b1116;
color: var(--ink);
display: grid;
font: 13px/1.5 system-ui, "Noto Sans CJK SC", sans-serif;
grid-template-areas: "head head" "list stage" "foot foot";
grid-template-columns: 268px minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr) minmax(170px, 32%);
height: 100%;
min-height: 0;
}
.tc-head {
align-items: center;
background: var(--panel);
border-bottom: 1px solid var(--line);
display: flex;
gap: 14px;
grid-area: head;
padding: 8px 14px;
}
.tc-head h1 { font-size: 14px; margin: 0; }
.tc-head .tc-sub { color: var(--dim); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tc-head .tc-count { color: var(--dim); font-variant-numeric: tabular-nums; white-space: nowrap; }
.tc-list {
background: var(--panel);
border-right: 1px solid var(--line);
grid-area: list;
min-height: 0;
overflow: auto;
padding: 6px 0 24px;
}
.tc-group > summary {
color: var(--dim);
cursor: pointer;
font-size: 11px;
letter-spacing: .04em;
list-style: none;
padding: 8px 12px 4px;
text-transform: uppercase;
}
.tc-group > summary::-webkit-details-marker { display: none; }
.tc-item {
align-items: baseline;
background: transparent;
border: 0;
border-left: 2px solid transparent;
color: var(--ink);
cursor: pointer;
display: flex;
gap: 8px;
justify-content: space-between;
padding: 5px 12px;
text-align: left;
width: 100%;
}
.tc-item:hover { background: #16212b; }
.tc-item[aria-current="true"] { background: #1b2b36; border-left-color: var(--dim); }
.tc-item .tc-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tc-item .tc-min { color: var(--dim); font-size: 11px; font-variant-numeric: tabular-nums; }
.tc-item[data-verdict="pass"] .tc-name::after { color: var(--pass); content: " ✓"; }
.tc-item[data-verdict="fail"] .tc-name::after { color: var(--fail); content: " ✗"; }
.tc-item[data-verdict="blocked"] .tc-name::after { color: var(--blocked); content: " !"; }
.tc-item[data-verdict="cancelled"] .tc-name::after { color: var(--cancelled); content: " –"; }
.tc-stage {
background: #05080a;
display: flex;
grid-area: stage;
min-height: 0;
min-width: 0;
position: relative;
}
.tc-frame { border: 0; height: 100%; width: 100%; }
.tc-stage-note {
background: #000a;
border-radius: 4px;
color: var(--dim);
left: 12px;
padding: 4px 8px;
position: absolute;
top: 12px;
}
.tc-foot {
background: var(--panel);
border-top: 1px solid var(--line);
display: grid;
grid-area: foot;
grid-template-columns: minmax(0, 1fr) 300px;
min-height: 0;
}
.tc-foot-left { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
.tc-foot-right { border-left: 1px solid var(--line); min-height: 0; overflow: auto; padding: 8px 12px; }
.tc-tabs { border-bottom: 1px solid var(--line); display: flex; gap: 2px; padding: 4px 8px 0; }
.tc-tab {
background: transparent;
border: 1px solid transparent;
border-bottom: 0;
border-radius: 4px 4px 0 0;
color: var(--dim);
cursor: pointer;
padding: 4px 10px;
}
.tc-tab[aria-selected="true"] { background: var(--cell); border-color: var(--line); color: var(--ink); }
.tc-log {
flex: 1;
font: 12px/1.55 ui-monospace, "Cascadia Mono", monospace;
margin: 0;
min-height: 0;
overflow: auto;
padding: 8px 12px;
white-space: pre-wrap;
}
.tc-log .tc-warn { color: var(--blocked); }
.tc-log .tc-bad { color: var(--fail); }
.tc-table-wrap { display: flex; flex: 1; min-height: 0; min-width: 0; overflow: auto; }
.tc-table { border-collapse: collapse; font-size: 12px; width: 100%; }
.tc-table th, .tc-table td { border-bottom: 1px solid #1d2831; padding: 3px 8px; text-align: left; }
.tc-table th { background: var(--cell); color: var(--dim); font-weight: 600; position: sticky; top: 0; }
.tc-table td.tc-num { font-variant-numeric: tabular-nums; text-align: right; }
.tc-table tr[data-status]:not([data-status="ok"]) td { background: #2a1714; }
.tc-verdict { align-items: center; display: flex; gap: 8px; font-size: 15px; font-weight: 600; margin-bottom: 6px; }
.tc-badge { border: 1px solid currentColor; border-radius: 999px; font-size: 11px; padding: 1px 8px; }
.tc-badge[data-verdict="pass"] { color: var(--pass); }
.tc-badge[data-verdict="fail"] { color: var(--fail); }
.tc-badge[data-verdict="blocked"] { color: var(--blocked); }
.tc-badge[data-verdict="cancelled"] { color: var(--cancelled); }
.tc-reason { color: var(--dim); font-size: 12px; margin: 0 0 10px; }
.tc-checks { border-collapse: collapse; font-size: 12px; width: 100%; }
.tc-checks td { border-bottom: 1px solid #1d2831; padding: 3px 0; vertical-align: top; }
.tc-checks td:first-child { padding-right: 8px; white-space: nowrap; }
.tc-ok { color: var(--pass); }
.tc-no { color: var(--fail); }
.tc-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
.tc-button {
background: #1b2b36;
border: 1px solid var(--line);
border-radius: 4px;
color: var(--ink);
cursor: pointer;
padding: 5px 12px;
}
.tc-button:hover:not(:disabled) { border-color: var(--dim); }
.tc-button:disabled { cursor: not-allowed; opacity: .45; }
.tc-button[data-primary="true"] { background: #1f4b3c; border-color: #2f6f57; }
.tc-bar { background: #1b2b36; border-radius: 999px; height: 4px; margin-top: 8px; overflow: hidden; }
.tc-bar > span { background: var(--dim); display: block; height: 100%; transition: width .2s; }
.tc-evidence { color: var(--dim); font-size: 11px; margin-top: 10px; }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,373 @@
// A Playwright-shaped `page` over the DOM of the window that runs it.
//
// `web/tools/cad-ui-rebuild/lib/{driver,assembly}.mjs` were written against
// Playwright and are proven against the real workspace. The teaching console
// reuses them verbatim by handing them this object instead of a Playwright
// Page: the driver modules are imported *into* the workspace document (see
// `runner.ts`), so a bare `document` already refers to the page under test and
// `evaluate` is a plain function call. That is also the only option here --
// the app's CSP has no `'unsafe-eval'`, so function bodies cannot be
// stringified across a realm boundary.
//
// Only the surface the drivers actually use is implemented. Anything else
// throws by name instead of quietly doing nothing: a driver that silently
// skips a control would report a pass for a model it never built.
const DEFAULT_TIMEOUT = 30000;
type Mutable = any;
interface RoleOptions { name?: string | RegExp; exact?: boolean }
interface FilterOptions { hasText?: string | RegExp }
interface WaitOptions { state?: "visible" | "attached"; timeout?: number }
interface SelectValue { label?: string; value?: string; index?: number }
/**
* Constructors live on the window of their own realm, and a node inside the
* workbench frame is not an instance of this realm's constructors -- so every
* `instanceof` here has to go through the frame's window. `Window` has no typed
* members for them, hence this cast, kept in one place.
*/
interface RealmGlobals {
Event: typeof Event;
KeyboardEvent: typeof KeyboardEvent;
MouseEvent: typeof MouseEvent;
PointerEvent: typeof PointerEvent;
HTMLInputElement: typeof HTMLInputElement;
HTMLSelectElement: typeof HTMLSelectElement;
HTMLTextAreaElement: typeof HTMLTextAreaElement;
}
function realm(win: Window): RealmGlobals { return win as unknown as RealmGlobals; }
export interface InPageLocator {
first(): InPageLocator;
locator(selector: string): InPageLocator;
getByRole(role: string, options?: RoleOptions): InPageLocator;
filter(options: FilterOptions): InPageLocator;
count(): Promise<number>;
click(options?: { timeout?: number }): Promise<void>;
fill(value: string, options?: { timeout?: number }): Promise<void>;
press(key: string): Promise<void>;
selectOption(value: string | SelectValue): Promise<void>;
setChecked(checked: boolean): Promise<void>;
allTextContents(): Promise<string[]>;
isDisabled(): Promise<boolean>;
waitFor(options?: WaitOptions): Promise<void>;
dispatchEvent(type: string, init?: Record<string, unknown>): Promise<void>;
evaluate<R, A = unknown>(fn: (element: Element, arg: A) => R | Promise<R>, arg?: A): Promise<R>;
}
export interface InPagePage {
locator(selector: string): InPageLocator;
getByRole(role: string, options?: RoleOptions): InPageLocator;
evaluate<R, A = unknown>(fn: (arg: A) => R | Promise<R>, arg?: A): Promise<R>;
waitForTimeout(ms: number): Promise<void>;
waitForSelector(selector: string, options?: WaitOptions): Promise<Element>;
waitForFunction<R>(fn: (arg: Mutable) => R, arg?: Mutable, options?: { timeout?: number }): Promise<R>;
goto(url: string, options?: { waitUntil?: string; timeout?: number }): Promise<void>;
}
/** `:text-is("…")` is a Playwright pseudo-class; split it off before querySelector. */
function splitTextIs(selector: string): { css: string; want?: string } {
const match = /^(.*?):text-is\(\s*"((?:[^"\\]|\\.)*)"\s*\)\s*$/.exec(selector);
if (!match) return { css: selector };
return { css: match[1], want: match[2].replace(/\\(.)/g, "$1") };
}
/** Candidate markup for a role, so `getByRole("button")` finds real buttons too. */
function roleSelector(role: string): string {
const native: Record<string, string> = {
button: 'button, input[type="button"], input[type="submit"]',
checkbox: 'input[type="checkbox"]',
combobox: "select",
listbox: "select",
textbox: 'input:not([type]), input[type="text"], textarea',
};
const base = native[role];
return base ? `${base}, [role="${role}"]` : `[role="${role}"]`;
}
/** Accessible name as Playwright computes it, reduced to what the drivers use. */
function accessibleName(win: Window, element: Element): string {
const label = element.getAttribute("aria-label");
if (label) return label;
const by = element.getAttribute("aria-labelledby");
if (by) {
const text = by.split(/\s+/).map((id) => win.document.getElementById(id)?.textContent ?? "").join(" ");
if (text.trim()) return text;
}
if (element instanceof realm(win).HTMLInputElement || element instanceof realm(win).HTMLSelectElement
|| element instanceof realm(win).HTMLTextAreaElement) {
const wrapping = element.closest("label")?.textContent ?? "";
if (wrapping.trim()) return wrapping;
}
return element.textContent ?? "";
}
function norm(text: string): string { return text.replace(/\s+/g, " ").trim(); }
function isVisible(element: Element): boolean {
const html = element as HTMLElement;
if (!html.getClientRects().length) return false;
const style = (element.ownerDocument?.defaultView ?? window).getComputedStyle(html);
return style.visibility !== "hidden" && style.display !== "none";
}
class Locator implements InPageLocator {
constructor(
private readonly win: Window,
private readonly resolve: () => Element[],
private readonly firstOnly = false,
) {}
private all(): Element[] {
const found = this.resolve();
return this.firstOnly ? found.slice(0, 1) : found;
}
private one(): Element {
const found = this.all();
if (!found.length) throw new Error("no element matched the locator");
return found[0];
}
first(): InPageLocator { return new Locator(this.win, this.resolve, true); }
locator(selector: string): InPageLocator {
const parent = this;
return new Locator(this.win, () => {
const { css, want } = splitTextIs(selector);
const out: Element[] = [];
for (const root of parent.all()) {
for (const node of Array.from(root.querySelectorAll(css))) {
// Playwright normalizes whitespace on both sides of `:text-is`.
if (want === undefined || norm(node.textContent ?? "") === norm(want)) out.push(node);
}
}
return out;
}, this.firstOnly);
}
getByRole(role: string, options: RoleOptions = {}): InPageLocator {
const parent = this;
return new Locator(this.win, () => {
const out: Element[] = [];
for (const root of parent.all()) {
for (const node of Array.from(root.querySelectorAll(roleSelector(role)))) {
if (matchesName(accessibleName(this.win, node), options)) out.push(node);
}
}
return out;
}, this.firstOnly);
}
filter(options: FilterOptions): InPageLocator {
const parent = this;
return new Locator(this.win, () => parent.all().filter((node) => {
const text = norm(node.textContent ?? "");
const want = options.hasText;
if (want === undefined) return true;
return want instanceof RegExp ? want.test(node.textContent ?? "") : text.toLowerCase().includes(norm(want).toLowerCase());
}), this.firstOnly);
}
async count(): Promise<number> { return this.all().length; }
async waitFor(options: WaitOptions = {}): Promise<void> {
const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
const state = options.state ?? "visible";
for (;;) {
const found = this.all();
if (state === "attached" ? found.length > 0 : found.some(isVisible)) return;
if (Date.now() > deadline) {
throw new Error(`waitFor(${state}) timed out after ${options.timeout ?? DEFAULT_TIMEOUT} ms`);
}
await this.waitForTimeout(100);
}
}
async click(options: { timeout?: number } = {}): Promise<void> {
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
await this.waitFor({ state: "visible", timeout });
// Playwright's click() waits for the control to be enabled before acting.
// The workspace disables its toolbar until the kernel reports ready, so a
// click that did not wait would either fail outright or, worse, land on a
// page whose document does not exist yet. Re-resolve every poll: React
// replaces the button node on re-render.
const deadline = Date.now() + timeout;
for (;;) {
const candidate = this.all().find(isVisible) as Mutable;
const disabled = !candidate || candidate.disabled === true
|| candidate.getAttribute?.("aria-disabled") === "true";
if (!disabled) break;
if (Date.now() > deadline) {
throw new Error(`cannot click a disabled control (still disabled after ${timeout} ms)`);
}
await this.waitForTimeout(100);
}
const element = this.one() as HTMLElement;
element.scrollIntoView?.({ block: "center" });
// Playwright sends the full pointer sequence; React drag/pointer handlers on
// the workspace need it. `click()` alone only fires a `click` event.
const view = this.win;
const { PointerEvent: Pointer, MouseEvent: Mouse } = realm(view);
const base = { bubbles: true, cancelable: true, composed: true, view, button: 0, detail: 1 };
element.dispatchEvent(new Pointer("pointerover", base));
element.dispatchEvent(new Pointer("pointerenter", { ...base, bubbles: false }));
element.dispatchEvent(new Pointer("pointerdown", base));
element.dispatchEvent(new Mouse("mousedown", base));
element.focus?.();
element.dispatchEvent(new Pointer("pointerup", base));
element.dispatchEvent(new Mouse("mouseup", base));
element.click();
await this.waitForTimeout(0);
}
async fill(value: string, options: { timeout?: number } = {}): Promise<void> {
await this.waitFor({ state: "visible", timeout: options.timeout });
const element = this.one() as Mutable;
element.focus?.();
const proto = element instanceof realm(this.win).HTMLTextAreaElement
? realm(this.win).HTMLTextAreaElement.prototype : realm(this.win).HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
// React keeps its own value tracker; a plain assignment is swallowed.
if (setter) setter.call(element, value); else element.value = value;
// Playwright's fill dispatches `input` only; the drivers that need a
// committed value dispatch `change` themselves.
const { Event: RealmEvent } = realm(this.win);
element.dispatchEvent(new RealmEvent("input", { bubbles: true }));
}
async press(key: string): Promise<void> {
await this.waitFor({ state: "visible" });
const element = this.one() as HTMLElement;
element.focus?.();
const init = { key, code: key, bubbles: true, cancelable: true, view: this.win };
const { KeyboardEvent: Key } = realm(this.win);
element.dispatchEvent(new Key("keydown", init));
if (key === "Enter" || key.length === 1) {
element.dispatchEvent(new Key("keypress", init));
}
element.dispatchEvent(new Key("keyup", init));
}
async selectOption(value: string | SelectValue): Promise<void> {
await this.waitFor({ state: "visible" });
const select = this.one() as HTMLSelectElement;
const options = Array.from(select.options);
let index = -1;
if (typeof value === "string") {
index = options.findIndex((option) => option.value === value);
// Some workspace selects carry no `value` attribute; the text is the value.
if (index < 0) index = options.findIndex((option) => norm(option.text) === norm(value));
if (index < 0) {
throw new Error(`no option "${value}"; available: ${options.map((o) => `${o.value}|${norm(o.text)}`).join(", ")}`);
}
} else if (value.index !== undefined) {
index = value.index;
} else if (value.value !== undefined) {
index = options.findIndex((option) => option.value === value.value);
} else if (value.label !== undefined) {
index = options.findIndex((option) => norm(option.text) === norm(value.label!));
}
if (index < 0 || index >= options.length) throw new Error(`selectOption(${JSON.stringify(value)}) matched nothing`);
select.selectedIndex = index;
const { Event: RealmEvent } = realm(this.win);
select.dispatchEvent(new RealmEvent("input", { bubbles: true }));
select.dispatchEvent(new RealmEvent("change", { bubbles: true }));
}
async setChecked(checked: boolean): Promise<void> {
await this.waitFor({ state: "visible" });
const element = this.one() as HTMLInputElement;
if (Boolean(element.checked) !== checked) await this.click();
}
async allTextContents(): Promise<string[]> {
return this.all().map((element) => element.textContent ?? "");
}
async isDisabled(): Promise<boolean> {
const element = this.one() as Mutable;
return element.disabled === true || element.getAttribute?.("aria-disabled") === "true";
}
async dispatchEvent(type: string, init: Record<string, unknown> = {}): Promise<void> {
const element = this.one();
const { Event: RealmEvent } = realm(this.win);
element.dispatchEvent(new RealmEvent(type, { bubbles: true, cancelable: true, ...init }));
}
async evaluate<R, A = unknown>(fn: (element: Element, arg: A) => R | Promise<R>, arg?: A): Promise<R> {
await this.waitFor({ state: "attached" });
return fn(this.one(), arg as A);
}
private waitForTimeout(ms: number): Promise<void> {
return new Promise((resolve) => this.win.setTimeout(resolve, ms));
}
}
function matchesName(name: string, options: RoleOptions): boolean {
const want = options.name;
if (want === undefined) return true;
if (want instanceof RegExp) return want.test(name);
return options.exact ? name === want : norm(name).toLowerCase() === norm(want).toLowerCase();
}
/**
* Build the page object over `win`.
*
* `goto` cannot navigate: the frame's document is this very script's realm, so
* loading another URL would tear the runner down mid-lesson. The console
* navigates the frame first (see `console/executor.ts`), and `goto` then either
* confirms it is already there or fails loudly.
*/
export function createInPagePage(win: Window): InPagePage {
const root = () => [win.document.documentElement].filter(Boolean) as Element[];
const page: InPagePage = {
locator(selector: string): InPageLocator {
return new Locator(win, () => {
const { css, want } = splitTextIs(selector);
const found = Array.from(win.document.querySelectorAll(css));
return want === undefined ? found : found.filter((node) => norm(node.textContent ?? "") === want);
});
},
getByRole(role: string, options: RoleOptions = {}): InPageLocator {
return new Locator(win, () => Array.from(win.document.querySelectorAll(roleSelector(role)))
.filter((node) => matchesName(accessibleName(win, node), options)));
},
async evaluate<R, A = unknown>(fn: (arg: A) => R | Promise<R>, arg?: A): Promise<R> {
return fn(arg as A);
},
waitForTimeout(ms: number): Promise<void> {
return new Promise((resolve) => win.setTimeout(resolve, ms));
},
async waitForSelector(selector: string, options: WaitOptions = {}): Promise<Element> {
await page.locator(selector).waitFor({ state: options.state ?? "visible", timeout: options.timeout });
const element = win.document.querySelector(splitTextIs(selector).css) ?? root()[0];
if (!element) throw new Error(`waitForSelector(${selector}) found nothing`);
return element;
},
async waitForFunction<R>(fn: (arg: Mutable) => R, arg?: Mutable, options: { timeout?: number } = {}): Promise<R> {
const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
for (;;) {
const value = await fn(arg);
if (value) return value as R;
if (Date.now() > deadline) throw new Error(`waitForFunction timed out after ${options.timeout ?? DEFAULT_TIMEOUT} ms`);
await page.waitForTimeout(100);
}
},
async goto(url: string): Promise<void> {
const target = new URL(url, win.location.href);
const here = win.location;
const samePath = target.pathname === here.pathname && target.origin === here.origin;
const targetQuery = [...target.searchParams].sort().join("&");
const hereQuery = [...new URLSearchParams(here.search)].sort().join("&");
if (samePath && targetQuery === hereQuery) return;
throw new Error(`in-page runner cannot navigate to ${target.pathname}${target.search}; the console must load that page in the frame first`);
},
};
return page;
}

View File

@@ -0,0 +1,31 @@
// Where a finished lesson's report lands: OPFS `freecad-exports`, one file per run.
//
// Kept apart from `runner.ts` so the console page can persist a report without
// bundling the driver into its own chunk. Nothing here downloads anything --
// turning a stored report into a browser download stays an explicit user action.
import { writeExportFile } from "../storage.js";
import type { LessonReport } from "./types.js";
/** `teaching-<lessonId>-<utcstamp>.json`; `writeExportFile` wants a flat name. */
export function reportFileName(report: LessonReport): string {
const stamp = report.finishedAt.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
return `teaching-${report.lessonId}-${stamp}.json`.replace(/[^A-Za-z0-9._-]/g, "-");
}
/** Write the report to OPFS and return the name it was stored under. */
export async function persistReport(report: LessonReport): Promise<string> {
const bytes = new TextEncoder().encode(`${JSON.stringify(report, null, 1)}\n`);
return writeExportFile(reportFileName(report), bytes.buffer as ArrayBuffer);
}
/** Explicit user action only: the browser saves a copy where the user chooses. */
export function downloadReport(report: LessonReport): void {
const blob = new Blob([`${JSON.stringify(report, null, 1)}\n`], { type: "application/json" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = reportFileName(report);
anchor.click();
setTimeout(() => URL.revokeObjectURL(url), 10000);
}

510
web/src/teaching/runner.ts Normal file
View File

@@ -0,0 +1,510 @@
// The in-page executor: runs one lesson against the workbench it lives in.
//
// This module is imported *into the workbench document* (see `bridge.ts`), so
// `window` here is the document under test and `createInPagePage(window)` yields
// the same Playwright-shaped surface `drive.mjs` hands the driver. That is why
// there is no cross-frame plumbing: the driver modules run in the page's own
// realm and `document` already means the right thing.
//
// Prerequisites are checked first and in dependency order. A failing prerequisite
// makes the lesson `blocked` -- never `fail` -- because nothing was asserted yet.
import { newDocumentWithBody, waitForWorkspace } from "../../tools/cad-ui-rebuild/lib/driver.mjs";
import { runPart } from "../../tools/cad-ui-rebuild/lib/run-part.mjs";
import { deleteExportFile, isOpfsSupported, writeExportFile } from "../storage.js";
import { createInPagePage } from "./in-page-page.js";
import { hasSteps, loadSteps } from "./steps.js";
import type {
AssemblyJob,
LessonReport,
LessonRunRequest,
PartJob,
PreflightCheck,
RunEvent,
StepRow,
Verdict,
} from "./types.js";
/** The replay judgement: same tolerance `drive.mjs` writes into `ui-run/v1`. */
const VOLUME_TOLERANCE = 1e-6;
/** One run at a time; `cancelLesson()` clears it between steps. */
let active: AbortController | null = null;
export function cancelLesson(): void {
active?.abort();
}
export function isRunning(): boolean {
return active !== null;
}
/** `page` as the run request names it -- path plus query, both sides normalised. */
function currentPage(): string {
const { pathname, search } = window.location;
return `${pathname.replace(/^\/+/, "")}${search}`;
}
/** Compare a lesson's page with the frame's, ignoring query order. */
function samePage(a: string, b: string): boolean {
const split = (value: string) => {
const [path, query = ""] = value.split("?");
const params = new URLSearchParams(query);
return `${path.replace(/^\/+/, "")}?${[...params.entries()]
.sort(([x], [y]) => x.localeCompare(y))
.map(([key, val]) => `${key}=${val}`)
.join("&")}`;
};
return split(a) === split(b);
}
/**
* Wait for the workspace each kind of page publishes once it is usable.
*
* Part pages mount a landmark element; the assembly shell instead publishes
* `__freecadWorkbenchState` and has no single stable element, so the two wait
* differently. Returns what it waited on, or `null` if the wait timed out.
*/
async function waitForPage(page: ReturnType<typeof createInPagePage>, kind: LessonRunRequest["job"]["kind"]): Promise<string | null> {
const timeout = 60000;
try {
if (kind.endsWith("-assembly")) {
await page.waitForFunction(
() => Boolean((window as unknown as { __freecadWorkbenchState?: unknown }).__freecadWorkbenchState),
undefined,
{ timeout },
);
return "__freecadWorkbenchState";
}
const landmark = '[aria-label="Native PartDesign view"]';
await page.waitForSelector(landmark, { timeout });
return landmark;
} catch {
return null;
}
}
/**
* Can this browser actually persist? `isOpfsSupported` only proves the API is
* there; a private window can still refuse the directory, so write once.
*/
async function checkOpfs(): Promise<PreflightCheck> {
if (!isOpfsSupported()) {
return { id: "opfs", label: "OPFS 可用", ok: false, detail: "此浏览器没有 navigator.storage.getDirectory" };
}
const name = `teaching-probe-${Date.now()}.json`;
try {
const bytes = new TextEncoder().encode('{"probe":true}');
await writeExportFile(name, bytes.buffer as ArrayBuffer);
await deleteExportFile(name);
return { id: "opfs", label: "OPFS 可写", ok: true, detail: "freecad-exports 写入并删除成功" };
} catch (error) {
return { id: "opfs", label: "OPFS 可写", ok: false, detail: message(error) };
}
}
/** The kernel answers: a newly opened document plus a body, then a throwaway. */
async function checkKernel(page: ReturnType<typeof createInPagePage>, kind: LessonRunRequest["job"]["kind"]): Promise<PreflightCheck> {
try {
if (kind.endsWith("-assembly")) {
// The assembly workbench has no PartDesign viewport. Its create panel is
// the landmark, and the shell stage returning to "ready" is the signal
// that the kernel finished booting. No document is created here: the
// lesson's own first step creates the assembly.
await page.waitForSelector('section[aria-label="Create assembly"]', { timeout: 180000 });
await page.waitForFunction(
() => (window as unknown as { __freecadWorkbenchState?: { stage?: string } })
.__freecadWorkbenchState?.stage === "ready",
undefined,
{ timeout: 180000 },
);
const rows = await page.locator('[role="treeitem"]').count();
return { id: "kernel", label: "内核就绪", ok: true, detail: `装配工作台已就绪(模型树 ${rows} 个对象)` };
}
await waitForWorkspace(page);
await newDocumentWithBody(page);
const rows = await page.locator('[role="treeitem"]').count();
return rows >= 1
? { id: "kernel", label: "内核就绪", ok: true, detail: `工作台已建立 ${rows} 个对象` }
: { id: "kernel", label: "内核就绪", ok: false, detail: "新建文档后模型树仍为空" };
} catch (error) {
return { id: "kernel", label: "内核就绪", ok: false, detail: message(error) };
}
}
function message(error: unknown): string {
return error instanceof Error ? error.message.slice(0, 300) : String(error).slice(0, 300);
}
/** Part milestones: what the console renders in the results table. */
function toRow(row: unknown): StepRow {
return row as StepRow;
}
/**
* What the assembly lesson needs on hand before it can start: every source part
* already in OPFS `freecad-documents`. Node seeds these from disk; the browser
* has no such source, so a missing part is a prerequisite, not a bug.
*/
async function checkAssemblySources(job: AssemblyJob): Promise<PreflightCheck> {
const { listDocumentFiles } = await import("../storage.js");
try {
const present = new Set(await listDocumentFiles());
const missing = job.sourceDocuments.filter(document => !present.has(`${document}.FCStd`) && !present.has(document));
return missing.length === 0
? { id: "sources", label: "装配源件在 OPFS", ok: true, detail: `${job.sourceDocuments.length} 个源件齐备` }
: {
id: "sources",
label: "装配源件在 OPFS",
ok: false,
detail: `缺少 ${missing.length} 个源件(先跑对应零件课):${missing.slice(0, 6).join("、")}`,
};
} catch (error) {
return { id: "sources", label: "装配源件在 OPFS", ok: false, detail: message(error) };
}
}
interface RunContext {
page: ReturnType<typeof createInPagePage>;
emit(event: RunEvent): void;
preflight: PreflightCheck[];
controller: AbortController;
}
/** Every prerequisite, in dependency order: storage, kernel, page, data. */
async function preflight(request: LessonRunRequest, context: RunContext): Promise<boolean> {
const { job } = request;
const checks: PreflightCheck[] = [await checkOpfs()];
context.emit({ type: "preflight", check: checks[0] });
if (checks[0].ok) {
const mounted = await waitForPage(context.page, job.kind);
const required = job.kind === "preflight" ? null : job.page;
const matches = mounted != null && (required == null || samePage(currentPage(), required));
const pageCheck: PreflightCheck = matches
? { id: "workbench", label: "工作台页匹配", ok: true, detail: `当前 ${currentPage()},等到 ${mounted}` }
: {
id: "workbench",
label: "工作台页匹配",
ok: false,
detail: mounted == null
? `当前页 ${currentPage()} 的工作台没有出现`
: `当前 ${currentPage()},课程要求 ${required}`,
};
checks.push(pageCheck);
context.emit({ type: "preflight", check: pageCheck });
}
if (checks.every(check => check.ok)) {
const kernel = await checkKernel(context.page, job.kind);
checks.push(kernel);
context.emit({ type: "preflight", check: kernel });
}
// Only part lessons replay a ui-steps record; an assembly lesson carries its
// own inserts/joints/solves, so asking for a steps file would block it forever.
if (checks.every(check => check.ok) && job.kind !== "preflight" && !job.kind.endsWith("-assembly")) {
const document = "document" in job ? job.document : "";
const ok = hasSteps(document);
const steps: PreflightCheck = {
id: "steps",
label: "界面步骤齐备",
ok,
detail: ok ? `${document} 的步骤记录已打包` : `没有 ${document} 的步骤记录(out/ui-steps)`,
};
checks.push(steps);
context.emit({ type: "preflight", check: steps });
}
if (checks.every(check => check.ok) && job.kind.endsWith("-assembly")) {
const sources = await checkAssemblySources(job as AssemblyJob);
checks.push(sources);
context.emit({ type: "preflight", check: sources });
}
context.preflight.push(...checks);
return checks.every(check => check.ok);
}
/** Nothing asserted yet: say why in the user's terms, not the stack's. */
function blockedReason(checks: PreflightCheck[]): string {
return checks.filter(check => !check.ok).map(check => `${check.label}:${check.detail}`).join(";")
|| "前置检查未全部通过";
}
async function runPartLesson(request: LessonRunRequest, context: RunContext): Promise<Partial<LessonReport>> {
const job = request.job as PartJob;
context.emit({ type: "phase", phase: "build", detail: `${job.title}(${job.document})` });
const uiSteps = await loadSteps(job.document);
const outcome = await runPart({
page: context.page,
uiSteps,
// `runPart` types this `number[]`, but reads each slot through `?? null`, so a
// `null` (a step whose replay recorded no volume) skips the comparison.
expectedVolumes: job.volumes as number[],
shouldStop: () => context.controller.signal.aborted,
onStep: (row, index, total) => {
const typed = toRow(row);
context.emit({ type: "step", index, total, row: typed });
context.emit({
type: "log",
line: `#${typed.step} ${typed.label} — ${typed.status === "ok" ? "ok" : typed.status},`
+ `体积 ${typed.volume ?? "—"}(期望 ${typed.expectedVolume ?? "—"})`,
});
},
});
const expected = outcome.expected ?? null;
const relativeError = outcome.relativeError ?? null;
const volumeOk = relativeError != null && relativeError < VOLUME_TOLERANCE;
const failed = outcome.results.filter(row => row.status !== "ok").length;
let verdict: Verdict = "pass";
let reason = `体积 ${outcome.volume} ≈ 期望 ${expected}(相对误差 ${relativeError?.toExponential(2)})`;
if (outcome.stopped) {
verdict = "cancelled";
reason = `已取消:执行 ${outcome.results.length}/${uiSteps.steps.length} 步`;
} else if (failed > 0) {
verdict = "fail";
const first = outcome.results.find(row => row.status !== "ok");
reason = `第 ${first?.step} 步失败:${first?.status}`;
} else if (!volumeOk) {
verdict = "fail";
reason = `体积不符:${outcome.volume},期望 ${expected}(相对误差 ${relativeError?.toExponential(2) ?? "无法比较"})`;
}
// A passing part is the input of an assembly lesson. Persisting it is not
// part of the judgement -- the model is already measured -- so a save that
// fails is logged and reported, never turned into a product failure.
const savedDocument = verdict === "pass" ? await savePartDocument(context, job.document) : null;
return {
verdict,
reason,
steps: outcome.results.length,
stepsTotal: uiSteps.steps.length,
failed,
volume: outcome.volume,
expected,
relativeError,
results: outcome.results as unknown as StepRow[],
savedDocument,
};
}
/**
* Store the just-built document where the assembly lessons look for it.
*
* The workspace saves under the name it gave the document (Design1, Design2,
* …) -- a lesson never names documents. Assembly lessons, the Insert Link task
* and the course data all address a part as `<document>.FCStd`, and an FCStd
* takes its document name from its file name, so re-storing the bytes under the
* course name is the whole contract. The workspace's own save control is used
* rather than a private kernel call, so the OPFS rules stay in one owner.
*/
async function savePartDocument(context: RunContext, documentId: string): Promise<string | null> {
const { readDocumentFile, writeDocumentFile, deleteDocumentFile } = await import("../storage.js");
const target = `${documentId}.FCStd`;
try {
const active = await context.page.locator('select[aria-label="Active document"]').first()
.evaluate(element => (element as HTMLSelectElement).value);
if (!active) throw new Error("找不到当前文档名");
const savedName = `${active}.FCStd`;
await context.page.getByRole("button", { name: "保存 FCStd 到 OPFS" }).first().click({ timeout: 120000 });
await context.page.waitForFunction(
(name) => (document.querySelector(".document-status")?.textContent ?? "").includes(`已保存 ${name}`),
savedName,
{ timeout: 120000 },
);
if (savedName !== target) {
const bytes = await readDocumentFile(savedName);
await writeDocumentFile(target, bytes);
await deleteDocumentFile(savedName);
}
context.emit({ type: "log", line: `文档已存入 OPFS:${target}` });
return target;
} catch (error) {
context.emit({ type: "log", line: `文档未能存入 OPFS(装配课会因缺源件而阻塞):${message(error)}` });
return null;
}
}
/**
* Insert every part, make the joints, solve, and save the bundle -- through the
* same `lib/assembly.mjs` calls the Node channel makes, in the same order. The
* only difference is seeding: Node copies sample FCStd files into OPFS from
* disk; here the part lessons have already stored them (see preflight).
*/
async function runAssemblyLesson(request: LessonRunRequest, context: RunContext): Promise<Partial<LessonReport>> {
const job = request.job as AssemblyJob;
const assembly = await import("../../tools/cad-ui-rebuild/lib/assembly.mjs");
const stop = () => {
if (context.controller.signal.aborted) throw new Error("已取消");
};
context.emit({ type: "phase", phase: "assembly", detail: `创建装配 ${job.document}` });
await assembly.createAssembly(context.page, {
appOrigin: window.location.origin,
pagePath: job.page,
document: job.document,
label: job.document,
});
stop();
context.emit({ type: "phase", phase: "insert", detail: `${job.inserts.length} 个零件` });
const inserted = await assembly.insertAll(context.page, job.inserts, { groundDocument: job.groundDocument });
const listed = await assembly.insertedLinkCount(context.page);
const mismatches: string[] = [];
if (listed != null && listed !== inserted.length) {
mismatches.push(`任务面板列出 ${listed} 个链接,实际插入 ${inserted.length}`);
}
for (const [index, expected] of job.inserts.entries()) {
const actual = inserted[index] as { sourceDocument?: string; position?: number[]; rotation?: number[] } | undefined;
if (!actual) { mismatches.push(`${expected.sourceDocument}: not inserted`); continue; }
if (actual.sourceDocument !== expected.sourceDocument) {
mismatches.push(`#${index + 1} document ${actual.sourceDocument} != ${expected.sourceDocument}`);
}
const quaternion = actual.rotation ?? [0, 0, 0, 1];
const wanted = expected.rotation ?? [0, 0, 0, 1];
if (quaternion.some((value, at) => Math.abs(value - wanted[at]) > 1e-6)) {
mismatches.push(`${expected.sourceDocument}: rotation ${quaternion.join(",")} != ${wanted.join(",")}`);
}
const position = actual.position ?? [0, 0, 0];
const targetPosition = expected.position ?? [0, 0, 0];
if (position.some((value, at) => Math.abs(value - targetPosition[at]) > 1e-6)) {
mismatches.push(`${expected.sourceDocument}: position ${position.join(",")} != ${targetPosition.join(",")}`);
}
}
stop();
context.emit({ type: "phase", phase: "joints", detail: `${job.joints.length} 个关节` });
const joints = job.joints.length ? await assembly.createJoints(context.page, job.joints) : [];
if (joints.length !== job.joints.length) {
mismatches.push(`${joints.length} joints created, replay records ${job.joints.length}`);
}
stop();
context.emit({ type: "phase", phase: "solve", detail: `${job.solves.length} 次求解` });
const solves = [];
for (const step of job.solves) solves.push(await assembly.solveAssembly(context.page, step));
let saved: unknown = null;
if (job.saveBundle && job.bom.length) {
stop();
context.emit({ type: "phase", phase: "bom", detail: "物料清单与保存" });
for (const step of job.bom) await assembly.executeCommand(context.page, step.action, step.args);
saved = await assembly.saveAssemblyBundle(context.page, { document: job.document });
if (!(saved as { manifestStored?: boolean } | null)?.manifestStored) {
mismatches.push(`OPFS 未存储装配清单 ${job.document}.assembly.json`);
}
}
const components = (solves.at(-1)?.components ?? []) as Array<{ position?: unknown; rotation?: unknown }>;
const malformed = components.filter(component => !Array.isArray(component.position) || component.position.length !== 3
|| !component.position.every(Number.isFinite)
|| !Array.isArray(component.rotation) || component.rotation.length !== 4
|| !component.rotation.every(Number.isFinite)).length;
const failed = (job.inserts.length - inserted.length) + Math.abs(job.joints.length - joints.length);
const verdict: Verdict = mismatches.length || malformed ? "fail" : "pass";
const reason = `插入 ${inserted.length}/${job.inserts.length} · 关节 ${joints.length}/${job.joints.length}`
+ ` · 组件 ${components.length}${malformed ? `(畸形 ${malformed})` : ""}`
+ (mismatches.length ? ` · 失配 ${mismatches.length}:${mismatches[0]}` : "");
return {
verdict,
reason,
steps: inserted.length,
stepsTotal: job.inserts.length,
failed,
results: [],
assembly: {
inserted: inserted.length,
expected: job.inserts.length,
joints: joints.length,
expectedJoints: job.joints.length,
solves: solves.length,
mismatches,
components: components.length,
malformed,
saved,
},
};
}
/**
* Run one lesson to completion and hand back a report.
*
* The caller owns persistence; this function only measures.
*/
export async function executeLesson(
request: LessonRunRequest,
onEvent?: (event: RunEvent) => void,
): Promise<LessonReport> {
if (active) throw new Error("已有课程在运行");
const controller = new AbortController();
active = controller;
const startedAt = new Date();
const started = performance.now();
const pageErrors: string[] = [];
const onError = (event: ErrorEvent) => pageErrors.push(String(event.message ?? event.error).slice(0, 300));
const onRejection = (event: PromiseRejectionEvent) => pageErrors.push(message(event.reason));
window.addEventListener("error", onError);
window.addEventListener("unhandledrejection", onRejection);
const emit = (event: RunEvent) => {
try {
onEvent?.(event);
} catch {
// A console that navigated away must not take the lesson down with it.
}
};
const context: RunContext = { page: createInPagePage(window), emit, preflight: [], controller };
const report: LessonReport = {
schema: "freecad-web/teaching-console/in-app-run/v1",
lessonId: request.lessonId,
title: request.title,
kind: request.job.kind,
document: "document" in request.job ? request.job.document : null,
startedAt: startedAt.toISOString(),
finishedAt: startedAt.toISOString(),
seconds: 0,
verdict: "blocked",
reason: "",
steps: 0,
stepsTotal: request.job.kind === "preflight" ? 0 : ("steps" in request.job ? request.job.steps : 0),
failed: 0,
volume: null,
expected: null,
relativeError: null,
preflight: [],
results: [],
pageErrors,
};
try {
emit({ type: "phase", phase: "preflight" });
const ready = await preflight(request, context);
if (!ready) {
report.reason = blockedReason(context.preflight);
emit({ type: "log", line: `前置未通过:${report.reason}` });
return report;
}
const outcome = request.job.kind === "preflight"
? { verdict: "pass" as Verdict, reason: `前置 ${context.preflight.length} 项全部通过` }
: request.job.kind.endsWith("-assembly")
? await runAssemblyLesson(request, context)
: await runPartLesson(request, context);
Object.assign(report, outcome);
} catch (error) {
report.verdict = controller.signal.aborted ? "cancelled" : "fail";
report.reason = message(error);
emit({ type: "log", line: `异常:${report.reason}` });
} finally {
window.removeEventListener("error", onError);
window.removeEventListener("unhandledrejection", onRejection);
active = null;
const finishedAt = new Date();
report.finishedAt = finishedAt.toISOString();
report.seconds = (performance.now() - started) / 1000;
report.preflight = context.preflight;
emit({ type: "phase", phase: "done", detail: report.verdict });
}
return report;
}

60
web/src/teaching/steps.ts Normal file
View File

@@ -0,0 +1,60 @@
// The `out/ui-steps/<document>.json` records, straight out of the course
// directories.
//
// They are globbed rather than copied: the course tooling owns them, they are
// already tracked in git, and a copy under `src/` would drift the first time a
// course is rebuilt. Vite emits one chunk per file, so a lesson only downloads
// the step list it is about to run.
export interface UiStep {
step: number;
label: string;
kind: string;
command: string;
page?: string;
object: string;
[key: string]: unknown;
}
export interface UiSteps {
schema: string;
document: string;
steps: UiStep[];
}
const FILES: Record<string, () => Promise<unknown>> = {
...import.meta.glob("../../tools/carrier-partdesign-course/out/ui-steps/*.json"),
...import.meta.glob("../../tools/reducer-parts-course/out/ui-steps/*.json"),
};
/**
* `index.json` in those directories is the course manifest
* (`ui-steps-index/v1`), not a document's step list, so it is not addressable
* by document name. Every other file is `<document>.json`.
*/
const MANIFEST = "index";
/** document name → loader. Two courses must not ship the same document. */
const BY_DOCUMENT = new Map<string, () => Promise<unknown>>();
for (const [key, load] of Object.entries(FILES)) {
const document = key.slice(key.lastIndexOf("/") + 1).replace(/\.json$/, "");
if (document === MANIFEST) continue;
const existing = BY_DOCUMENT.get(document);
if (existing && existing !== load) throw new Error(`两份课程都提供了 ${document} 的界面步骤`);
BY_DOCUMENT.set(document, load);
}
export function hasSteps(document: string): boolean {
return BY_DOCUMENT.has(document);
}
export function stepDocuments(): string[] {
return [...BY_DOCUMENT.keys()].sort();
}
export async function loadSteps(document: string): Promise<UiSteps> {
const load = BY_DOCUMENT.get(document);
if (!load) throw new Error(`没有 ${document} 的界面步骤记录(out/ui-steps)`);
const module = await load() as { default: UiSteps };
return module.default;
}

123
web/src/teaching/types.ts Normal file
View File

@@ -0,0 +1,123 @@
// Shapes shared by the in-app teaching console and the runner it drives.
//
// The console page and the runner live in different realms (parent document vs.
// workbench frame) but exchange ordinary objects, so one set of types covers
// both sides. Everything here is data: no DOM, no imports.
export type LessonKind = "preflight" | "carrier-part" | "reducer-part" | "carrier-assembly" | "reducer-assembly";
export interface PartJob {
kind: "carrier-part" | "reducer-part";
partId: string;
document: string;
title: string;
page: string;
steps: number;
/** Reference volume after each step; `null` where the replay recorded none. */
volumes: (number | null)[];
}
export interface AssemblyJob {
kind: "carrier-assembly" | "reducer-assembly";
document: string;
title: string;
page: string;
groundDocument: string | null;
saveBundle: boolean;
sourceDocuments: string[];
inserts: Array<{
sourceDocument: string;
sourceObject: string;
position: number[];
rotation: number[];
}>;
joints: Array<{ action: string; args: Record<string, unknown> | null }>;
solves: Array<{ action: string; args: Record<string, unknown> | null }>;
bom: Array<{ action: string; args: Record<string, unknown> | null }>;
}
export interface PreflightJob { kind: "preflight" }
export type LessonJob = PartJob | AssemblyJob | PreflightJob;
export interface LessonRunRequest {
lessonId: string;
title: string;
job: LessonJob;
}
/** One row of the results table, mirroring `ui-run/v1` so both channels agree. */
export interface StepRow {
step: number;
label: string;
kind: string;
command: string;
uiName: string | null;
volume: number | null;
expectedVolume: number | null;
volumeMatches: boolean | null;
status: string;
ms: number;
}
/** One prerequisite. A failing prerequisite blocks the lesson; it is not a product failure. */
export interface PreflightCheck {
id: string;
label: string;
ok: boolean;
detail: string;
}
export type RunEvent =
| { type: "phase"; phase: string; detail?: string }
| { type: "preflight"; check: PreflightCheck }
| { type: "step"; index: number; total: number; row: StepRow }
| { type: "log"; line: string };
export type Verdict = "pass" | "fail" | "blocked" | "cancelled";
export interface LessonReport {
schema: "freecad-web/teaching-console/in-app-run/v1";
lessonId: string;
title: string;
kind: LessonKind;
document: string | null;
startedAt: string;
finishedAt: string;
seconds: number;
verdict: Verdict;
reason: string;
steps: number;
stepsTotal: number;
failed: number;
volume: number | null;
expected: number | null;
relativeError: number | null;
preflight: PreflightCheck[];
results: StepRow[];
pageErrors: string[];
/** Part lessons: the FCStd stored under the course document name, if it worked. */
savedDocument?: string | null;
/** Assembly only: what the UI actually did, compared against the replay. */
assembly?: {
inserted: number;
expected: number;
joints: number;
expectedJoints: number;
solves: number;
mismatches: string[];
components: number;
malformed: number;
saved: unknown;
};
}
/** The contract the workbench page publishes for the console to call. */
export interface TeachingBridge {
ready: true;
/** `page` is the shell page this workbench is currently showing. */
page: string;
run(request: LessonRunRequest, onEvent?: (event: RunEvent) => void): Promise<LessonReport>;
cancel(): void;
running(): boolean;
}

View File

@@ -5,11 +5,14 @@
// <WorkbenchShell /> without side effects on its own document.
import { createRoot } from "react-dom/client";
import { installNavigation, readNavigationContext } from "./navigation.js";
import { installTeachingBridge } from "./teaching/bridge.js";
import { installUiAccessibility } from "./ui-accessibility.js";
import { WorkbenchShell } from "./workbench-shell.js";
installNavigation("workbench", readNavigationContext());
installUiAccessibility();
// Lets the in-app teaching console drive this page across the iframe boundary.
installTeachingBridge();
const container = document.querySelector<HTMLDivElement>("#app");
if (!container) throw new Error("workbench entry: #app container is missing");

13
web/teaching-console.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="data:," />
<title>Web FreeCAD 教学控制台</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/teaching-console-entry.tsx"></script>
</body>
</html>

View File

@@ -10,8 +10,9 @@
// Ordering matters and is not obvious: the first inserted link becomes the
// grounded anchor, so the ground part must be inserted first, before anything
// else. `orderedInserts` enforces that.
import fs from "node:fs";
import path from "node:path";
// No Node imports here on purpose: this module is also loaded inside the
// teaching console's workbench frame, where `document` is the real workspace.
// Filesystem reporting lives in `assembly-report.mjs`.
/** Sort inserts so the ground part comes first, keeping the rest in authored order. */
export function orderedInserts(inserts, groundDocument) {
@@ -102,9 +103,22 @@ export async function insertLink(page, { sourceDocument, sourceObject, position,
// documents (`Body` exists in every reducer part), so the bare object name
// cannot be used as the value -- the task would always resolve to whichever
// document was opened first.
const key = `${sourceDocument}:${sourceObject}`;
let key = `${sourceDocument}:${sourceObject}`;
const values = await objectSelect.evaluate(node => [...node.options].map(option => option.value));
if (!values.includes(key)) throw new Error(`source object ${key} not among ${values.join(", ")}`);
if (!values.includes(key)) {
// Documents built through the workbench UI suffix their object names --
// its `unique()` always yields `Body1`, `Sketch1`, … -- while the course
// data was captured from kernel-built reference files that use the bare
// names (`Body`). Fall back to the lowest suffixed match so one replay
// drives both kinds of source document.
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const suffixed = values
.map(value => ({ value, index: Number(new RegExp(`^${escaped}(\\d+)$`).exec(value)?.[1] ?? NaN) }))
.filter(entry => Number.isFinite(entry.index))
.sort((a, b) => a.index - b.index);
if (suffixed.length) key = suffixed[0].value;
}
if (!values.includes(key)) throw new Error(`source object ${sourceDocument}:${sourceObject} not among ${values.join(", ")}`);
await objectSelect.selectOption(key);
for (const [index, axis] of ["X", "Y", "Z"].entries()) {
@@ -135,6 +149,9 @@ export async function acceptLinks(page) {
/**
* Insert every link in the planned order, loading each source document once.
* Returns per-insert evidence so the caller can assert rotation was preserved.
* @param {unknown} page
* @param {Array<{sourceDocument: string, sourceObject: string, position: number[], rotation: number[]}>} inserts
* @param {{groundDocument?: string | null, loadOne?: (page: unknown, fileName: string) => Promise<void>}} [options]
*/
export async function insertAll(page, inserts, { groundDocument, loadOne = loadSource } = {}) {
const ordered = orderedInserts(inserts, groundDocument);
@@ -226,7 +243,11 @@ export async function solveAssembly(page, step) {
* manifest `<documentId>.assembly.json` through writeRawStep (`freecad-1-2`),
* so both stores are checked here.
*/
export async function saveAssemblyBundle(page, { document, timeout = 300000 }) {
// The option is `documentId`, not `document`: the callbacks below run through
// `page.waitForFunction`, and in the in-app console they execute in this very
// scope. A parameter named `document` would shadow the page's global `document`
// there and turn `document.querySelector` into a call on a string.
export async function saveAssemblyBundle(page, { document: documentId, timeout = 300000 }) {
const section = page.locator('section[aria-label="Bill of materials task"]');
await section.waitFor({ timeout: 120000 });
const save = section.getByRole("button", { name: "Save FCStd", exact: true }).first();
@@ -266,13 +287,5 @@ export async function saveAssemblyBundle(page, { document, timeout = 300000 }) {
const steps = await list("freecad-1-2");
const manifest = `${documentId}.assembly.json`;
return { files: documents, manifest, manifestStored: steps.includes(manifest) };
}, document);
}
/** Persist the assembly report next to the run evidence. */
export function writeAssemblyReport(runDir, document, report) {
fs.mkdirSync(runDir, { recursive: true });
const file = path.join(runDir, `${document}-assembly.json`);
fs.writeFileSync(file, `${JSON.stringify(report, null, 2)}\n`);
return file;
}, documentId);
}

View File

@@ -0,0 +1,150 @@
#!/usr/bin/env node
// Generate the small data files the in-app teaching console bundles.
//
// The console runs inside the browser, so it cannot read `tools/**/out/**` or
// the 9.4 MB replays at run time. Everything it needs to *name* and *judge* a
// lesson -- which document, how many steps, the reference volume after each
// step, and the assembly placement numbers -- is extracted here into two
// committed JSON files under `src/teaching/generated/`.
//
// The step files are not copied: `src/teaching/steps.ts` globs them straight
// out of the course directories, so they keep exactly one home in the repo.
//
// Usage: node tools/teaching-console/build-inapp-data.mjs [--check]
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadCatalog } from "./catalog.mjs";
import { buildLessons } from "./lessons.mjs";
import { loadProject, replayPath } from "../cad-ui-rebuild/manifest.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const generatedDir = path.join(webRoot, "src/teaching/generated");
/** Lesson kinds the browser can run. Everything else needs Node (suites). */
const IN_APP_KINDS = new Set(["preflight", "carrier-part", "carrier-assembly", "reducer-part", "reducer-assembly"]);
const PROJECTS = {
carrier: "tools/carrier-partdesign-course",
reducer: "tools/reducer-parts-course",
};
function readJson(file) {
return JSON.parse(fs.readFileSync(file, "utf8"));
}
/** The volumes the replay recorded after each step: the reference to judge against. */
function stepVolumes(replayFile) {
const replay = readJson(replayFile);
return replay.steps.map(step => (typeof step?.volume === "number" ? step.volume : null));
}
/**
* One lesson, as the console needs it at run time.
*
* `document` and `steps` are what the runner loads and how many rows to expect;
* `volumes` is the per-step reference. A `null` entry means the replay recorded
* no volume for that step, so the runner compares nothing there.
*/
function resolveJob(job, projects) {
if (job.kind === "preflight") return { kind: "preflight" };
const project = projects[job.kind.startsWith("carrier") ? "carrier" : "reducer"];
if (job.kind.endsWith("-part")) {
const part = project.parts.find(item => item.id === job.partId);
if (!part) throw new Error(`${project.name} has no part ${job.partId}`);
const stepsFile = path.join(project.paths.stepsDir, `${part.document}.json`);
if (!fs.existsSync(stepsFile)) throw new Error(`missing ui-steps ${stepsFile}`);
const uiSteps = readJson(stepsFile);
return {
kind: job.kind,
partId: part.id,
document: part.document,
title: part.title,
page: uiSteps.steps[0]?.page ?? "partdesign.html",
steps: uiSteps.steps.length,
volumes: stepVolumes(replayPath(project, part.document)),
};
}
// Assembly: the runner inserts what the replay recorded, in replay order.
const assembly = project.assembly;
if (!assembly) throw new Error(`${project.name} has no assembly block`);
const replay = readJson(replayPath(project, assembly.document, { assembly: true }));
const inserts = replay.steps.filter(step => step.insert).map(step => step.insert);
if (!inserts.length) throw new Error(`${project.name} assembly replay has no insertions`);
return {
kind: job.kind,
document: assembly.document,
title: assembly.label ?? assembly.document,
page: project.pages.assembly,
groundDocument: assembly.groundDocument ?? inserts[0]?.sourceDocument ?? null,
saveBundle: Boolean(assembly.saveBundle),
sourceDocuments: [...new Set(inserts.map(item => item.sourceDocument))],
inserts,
joints: replay.steps
.filter(step => typeof step.action === "string" && step.action.startsWith("Assembly_CreateJoint"))
.map(step => ({ action: step.action, args: step.args ?? null })),
solves: replay.steps
.filter(step => step.action === "Assembly_SolveAssembly")
.map(step => ({ action: step.action, args: step.args ?? null })),
bom: replay.steps
.filter(step => step.action === "Assembly_CreateBom")
.map(step => ({ action: step.action, args: step.args ?? null })),
};
}
function build() {
const projects = Object.fromEntries(Object.entries(PROJECTS)
.map(([name, dir]) => [name, loadProject(path.join(webRoot, dir), { requireParts: true })]));
const curriculum = buildLessons(loadCatalog());
const groups = curriculum.groups.filter(group => ["basics", "carrier", "reducer"].includes(group.id));
const lessons = curriculum.lessons
.filter(lesson => IN_APP_KINDS.has(lesson.job?.kind))
.map(lesson => ({
id: lesson.id,
groupId: lesson.groupId,
title: lesson.title,
level: lesson.level,
durationMin: lesson.durationMin,
summary: lesson.summary,
sees: lesson.sees ?? [],
expect: lesson.expect,
job: resolveJob(lesson.job, projects),
}));
// Both preflight lessons point at the same check; the console keeps one.
const preflight = lessons.find(lesson => lesson.job.kind === "preflight");
const kept = [preflight, ...lessons.filter(lesson => lesson !== preflight)].filter(Boolean);
return {
schema: "freecad-web/teaching-console/in-app/v1",
groups,
lessons: kept,
counts: {
lessons: kept.length,
parts: kept.filter(lesson => lesson.job.kind.endsWith("-part")).length,
assemblies: kept.filter(lesson => lesson.job.kind.endsWith("-assembly")).length,
steps: kept.reduce((sum, lesson) => sum + (lesson.job.steps ?? 0), 0),
},
};
}
function serialize(value) {
return `${JSON.stringify(value, null, 1)}\n`;
}
const data = build();
const file = path.join(generatedDir, "lessons.json");
const text = serialize(data);
if (process.argv.includes("--check")) {
const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
if (current !== text) {
console.error(`in-app lesson data is stale: ${path.relative(webRoot, file)}`);
console.error("run: node tools/teaching-console/build-inapp-data.mjs");
process.exit(1);
}
console.log(`in-app lesson data is current (${data.counts.lessons} lessons, ${data.counts.steps} steps)`);
} else {
fs.mkdirSync(generatedDir, { recursive: true });
fs.writeFileSync(file, text);
console.log(JSON.stringify({ file: path.relative(webRoot, file), ...data.counts }));
}

View File

@@ -0,0 +1,209 @@
#!/usr/bin/env node
/**
* Browser gate for the in-app teaching console (web/teaching-console.html).
*
* Proves the console drives the real workbench by itself: no teaching Node
* server, no spawned Chrome, no /api/console/* traffic. It opens the built page
* from an ordinary static server, waits for the iframe to publish its bridge,
* runs 环境自检, then builds P01 (Gear2_80T) inside the iframe and checks the
* report the run wrote to OPFS.
*
* Assertions:
* - the console lists all 48 in-app lessons with the generated counts;
* - the run button stays disabled until the iframe bridge answers;
* - 环境自检 → verdict pass, at least four prerequisite rows green;
* - P01 → verdict pass, 4/4 steps, volume within the replay tolerance;
* - the report lands in OPFS freecad-exports and parses as in-app-run/v1;
* - body[data-runner-state] mirrors the verdict;
* - no page errors, no horizontal overflow at 1440×900 and 390×844.
*
* Prerequisites (checked first, in this order): playwright resolvable from
* web/node_modules, then a running static server serving this build. Either
* missing is exit 2 -- a prerequisite failure, never a product failure.
*
* Usage: node web/tools/teaching-console/check-inapp-console.mjs [--quick]
* --quick stop after 环境自检 (skips the P01 build)
*/
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO = path.resolve(HERE, "../../..");
const require = createRequire(path.join(REPO, "web/package.json"));
const BASE = process.env.TEACHING_BASE ?? "http://127.0.0.1:5183";
const QUICK = process.argv.includes("--quick");
const VERDICTS = ["pass", "fail", "blocked", "cancelled"];
const failures = [];
const note = (message) => { failures.push(message); console.error(`FAIL ${message}`); };
const ok = (message) => { console.log(`ok ${message}`); };
let chromium;
try {
({ chromium } = require("playwright"));
} catch {
console.error("前置缺失:web/node_modules 下没有 playwright");
process.exit(2);
}
const served = await fetch(`${BASE}/teaching-console.html`).then(response => response.ok, () => false);
if (!served) {
console.error(`前置缺失:${BASE} 上没有 teaching-console.html`);
console.error("先在本机构建并预览:npx vite build && npx vite preview --port 5183");
process.exit(2);
}
/** The report a run wrote, straight out of OPFS, plus the name it used. */
const READ_OPFS_REPORT = async (prefix) => {
const root = await navigator.storage.getDirectory();
let dir;
try {
dir = await root.getDirectoryHandle("freecad-exports");
} catch {
return null; // nothing has been written yet
}
const names = [];
for await (const [name] of dir.entries()) if (name.startsWith(prefix)) names.push(name);
names.sort();
if (!names.length) return null;
const file = await (await dir.getFileHandle(names.at(-1))).getFile();
return { name: names.at(-1), text: await file.text() };
};
const badgeText = (page) => page.locator(".tc-badge").textContent().then(text => (text ?? "").trim());
async function waitForBridge(page) {
await page.waitForFunction(() => {
const button = [...document.querySelectorAll("button")].find(item => item.textContent?.includes("运行本课"));
return Boolean(button && !button.disabled);
}, null, { timeout: 240000 });
}
async function runSelected(page, timeout) {
await waitForBridge(page);
await page.getByRole("button", { name: "运行本课" }).click();
await page.waitForFunction(
() => (document.querySelector(".tc-badge")?.textContent ?? "").includes("运行中"),
null,
{ timeout: 60000 },
);
await page.waitForFunction(
verdicts => verdicts.includes((document.querySelector(".tc-badge")?.textContent ?? "").trim()),
VERDICTS,
{ timeout },
);
return badgeText(page);
}
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"] });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const pageErrors = [];
page.on("pageerror", error => pageErrors.push(String(error)));
try {
await page.goto(`${BASE}/teaching-console.html`, { waitUntil: "load" });
await page.waitForSelector(".teaching-console", { timeout: 60000 });
const lessons = await page.locator(".tc-item").count();
if (lessons !== 48) note(`课程列表应有 48 课,实际 ${lessons}`);
else ok(`课程列表 ${lessons} 课`);
const counts = (await page.locator(".tc-count").textContent() ?? "").trim();
if (counts !== "48 课 · 45 件 · 328 步") note(`页头计数不对:${counts}`);
else ok(`页头计数 ${counts}`);
// 1. 环境自检: prerequisites run in the iframe, nothing is asserted yet.
await page.locator(".tc-item").first().click();
const preflightVerdict = await runSelected(page, 300000);
if (preflightVerdict !== "pass") {
const reason = (await page.locator(".tc-reason").textContent() ?? "").trim();
note(`环境自检判定 ${preflightVerdict}:${reason}`);
} else {
const green = await page.locator(".tc-checks .tc-ok").count();
if (green < 4) note(`环境自检通过但只有 ${green} 项前置为绿`);
else ok(`环境自检通过,${green} 项前置全绿`);
}
await page.waitForFunction(
() => document.body.innerText.includes("teaching-lesson-00-preflight-"),
null,
{ timeout: 60000 },
).catch(() => note("环境自检的报告名没有出现在证据栏"));
const preflightReport = await page.evaluate(READ_OPFS_REPORT, "teaching-lesson-00-preflight-");
if (!preflightReport) note("OPFS freecad-exports 里没有环境自检报告");
else {
const parsed = JSON.parse(preflightReport.text);
if (parsed.schema !== "freecad-web/teaching-console/in-app-run/v1") note(`环境自检报告 schema 不对:${parsed.schema}`);
if (parsed.verdict !== "pass") note(`环境自检报告 verdict=${parsed.verdict}:${parsed.reason}`);
else ok(`证据 ${preflightReport.name}(verdict pass)`);
}
const state = await page.locator("body").getAttribute("data-runner-state");
if (state !== "pass") note(`body[data-runner-state]=${state},应为 pass`);
else ok("body[data-runner-state] 与判定一致");
// 2. P01 in the browser: a real part, built by clicking the real UI.
if (!QUICK) {
await page.locator(".tc-item", { hasText: "P01" }).first().click();
// runSelected() waits for the fresh frame's bridge itself; nothing to add here.
const partVerdict = await runSelected(page, 900000);
if (partVerdict !== "pass") {
const reason = (await page.locator(".tc-reason").textContent() ?? "").trim();
note(`P01 判定 ${partVerdict}:${reason}`);
} else {
// The table only mounts on its tab; the console opens on the log tab.
await page.getByRole("tab", { name: /结果表/ }).click();
const rows = await page.locator(".tc-table tbody tr").count();
if (rows !== 4) note(`P01 结果表应有 4 行,实际 ${rows}`);
else ok("P01 通过,4/4 步");
}
const partReport = await page.evaluate(READ_OPFS_REPORT, "teaching-lesson-reducer-p01-");
if (!partReport) note("OPFS 里没有 P01 报告");
else {
const parsed = JSON.parse(partReport.text);
const mismatched = parsed.results.filter(row => row.volumeMatches === false);
if (parsed.verdict !== "pass") note(`P01 报告 verdict=${parsed.verdict}:${parsed.reason}`);
else if (parsed.failed !== 0) note(`P01 报告有 ${parsed.failed} 步失败`);
else if (mismatched.length) note(`P01 有 ${mismatched.length} 步体积不符`);
else if (!(parsed.relativeError < 1e-6)) note(`P01 相对误差 ${parsed.relativeError} 超出容差`);
else ok(`证据 ${partReport.name}:体积 ${parsed.volume} / 期望 ${parsed.expected},相对误差 ${parsed.relativeError.toExponential(2)}`);
}
// The assembly lessons take their parts from OPFS freecad-documents, so a
// passing part lesson must leave its document there under the course name.
const documents = await page.evaluate(async () => {
const root = await navigator.storage.getDirectory();
try {
const dir = await root.getDirectoryHandle("freecad-documents");
const names = [];
for await (const [name] of dir.entries()) names.push(name);
return names.sort();
} catch { return []; }
});
if (documents.includes("Gear2_80T.FCStd")) ok("P01 文档已存入 OPFS freecad-documents(Gear2_80T.FCStd)");
else note(`OPFS freecad-documents 里没有 Gear2_80T.FCStd(现有 ${documents.join("、") || "无"})`);
}
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
await page.setViewportSize(viewport);
await page.waitForTimeout(300);
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
if (overflow > 0) note(`${viewport.width}px 下横向溢出 ${overflow}px`);
else ok(`${viewport.width}×${viewport.height} 无横向溢出`);
}
if (pageErrors.length) note(`页面错误 ${pageErrors.length} 条:${pageErrors[0]}`);
else ok("无页面错误");
} catch (error) {
note(`异常:${error instanceof Error ? error.message : String(error)}`);
} finally {
await browser.close();
}
if (failures.length) {
console.error(`\n${failures.length} 项未通过`);
process.exit(1);
}
console.log("\n教学控制台:全部通过");

View File

@@ -0,0 +1,138 @@
#!/usr/bin/env node
/**
* Run a group of in-app lessons through the console, in lesson order, in one
* browser. Unlike check-inapp-console.mjs this is not a gate: it is the batch
* driver for a whole course (reducer parts + assembly, carrier parts +
* assembly), so the console is exercised the way a teacher would use it.
*
* Every lesson runs in the same browser instance, so the OPFS documents a part
* lesson saves are exactly what the following assembly lesson consumes. A fresh
* launch starts from an empty OPFS; that is expected, not a failure.
*
* Output is one line per lesson; evidence stays in OPFS (`freecad-exports` for
* reports, `freecad-documents` for the parts).
*
* Usage:
* node web/tools/teaching-console/run-inapp-lessons.mjs --group reducer
* node web/tools/teaching-console/run-inapp-lessons.mjs --lessons lesson-reducer-p01,lesson-reducer-assembly
* --base <url> static server (default http://127.0.0.1:5183)
* --timeout <s> per lesson (default 900; assembly gets 2400)
* --profile <dir> keep the browser profile, so OPFS survives between runs
* (a fresh launch otherwise starts with an empty OPFS, and
* an assembly lesson then has no parts to consume)
*/
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath, pathToFileURL } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO = path.resolve(HERE, "../../..");
const require = createRequire(path.join(REPO, "web/package.json"));
const BASE = arg("--base") ?? process.env.TEACHING_BASE ?? "http://127.0.0.1:5183";
const VERDICTS = ["pass", "fail", "blocked", "cancelled"];
function arg(name) {
const index = process.argv.indexOf(name);
return index >= 0 ? process.argv[index + 1] : undefined;
}
const data = JSON.parse(await (await import("node:fs/promises")).readFile(
path.join(REPO, "web/src/teaching/generated/lessons.json"), "utf8"));
const byId = new Map(data.lessons.map(lesson => [lesson.id, lesson]));
const requested = arg("--lessons")?.split(",").map(id => id.trim()).filter(Boolean);
const group = arg("--group");
const ids = requested ?? (group
? data.lessons.filter(lesson => lesson.groupId === group).map(lesson => lesson.id)
: []);
if (!ids.length) {
console.error("用法:--group <groupId> 或 --lessons <id,id,…>");
process.exit(2);
}
const unknown = ids.filter(id => !byId.has(id));
if (unknown.length) {
console.error(`未知课程:${unknown.join("、")}`);
process.exit(2);
}
let chromium;
try {
({ chromium } = require("playwright"));
} catch {
console.error("前置缺失:web/node_modules 下没有 playwright");
process.exit(2);
}
const served = await fetch(`${BASE}/teaching-console.html`).then(response => response.ok, () => false);
if (!served) {
console.error(`前置缺失:${BASE} 上没有 teaching-console.html`);
console.error("先在本机构建并预览:npx vite build && npx vite preview --port 5183");
process.exit(2);
}
const badge = page => page.locator(".tc-badge").textContent().then(text => (text ?? "").trim());
async function runOne(page, id) {
const lesson = byId.get(id);
const timeout = Number(arg("--timeout") ?? (lesson.job.kind.endsWith("-assembly") ? 2400 : 900)) * 1000;
await page.locator(`.tc-item[data-lesson-id="${id}"]`).click();
// The console remounts the frame per lesson; the run button is the readiness signal.
await page.waitForFunction(() => {
const button = [...document.querySelectorAll("button")].find(item => item.textContent?.includes("运行本课"));
return Boolean(button && !button.disabled);
}, null, { timeout: 300000 });
const started = Date.now();
await page.getByRole("button", { name: "运行本课" }).click();
await page.waitForFunction(
() => (document.querySelector(".tc-badge")?.textContent ?? "").includes("运行中"),
null, { timeout: 60000 });
await page.waitForFunction(
verdicts => verdicts.includes((document.querySelector(".tc-badge")?.textContent ?? "").trim()),
VERDICTS, { timeout });
const verdict = await badge(page);
const reason = ((await page.locator(".tc-reason").textContent()) ?? "").trim();
const seconds = Math.round((Date.now() - started) / 1000);
console.log(`${verdict === "pass" ? "ok " : "FAIL"} ${id} ${verdict} ${seconds}s ${reason.slice(0, 160)}`);
return { id, verdict, reason, seconds };
}
const profile = arg("--profile");
const browserArgs = ["--no-sandbox", "--disable-dev-shm-usage"];
const launched = profile ? null : await chromium.launch({ headless: true, args: browserArgs });
const context = launched
? await launched.newContext({ viewport: { width: 1440, height: 900 } })
: await chromium.launchPersistentContext(profile, { headless: true, viewport: { width: 1440, height: 900 }, args: browserArgs });
const page = context.pages()[0] ?? await context.newPage();
const pageErrors = [];
page.on("pageerror", error => pageErrors.push(String(error)));
const results = [];
try {
await page.goto(`${BASE}/teaching-console.html`, { waitUntil: "load" });
await page.waitForSelector(".teaching-console", { timeout: 60000 });
for (const id of ids) results.push(await runOne(page, id));
// Final evidence: what the run left in OPFS, read from the console's origin.
const store = await page.evaluate(async () => {
const root = await navigator.storage.getDirectory();
const list = async (name) => {
try {
const dir = await root.getDirectoryHandle(name);
const names = [];
for await (const [entry] of dir.entries()) names.push(entry);
return names.sort();
} catch { return []; }
};
return { documents: await list("freecad-documents"), reports: await list("freecad-exports") };
});
console.log(`\nOPFS freecad-documents:${store.documents.length} 个`);
console.log(`OPFS freecad-exports:${store.reports.length} 份报告`);
} catch (error) {
console.error(`异常:${error instanceof Error ? error.message : String(error)}`);
results.push({ id: "—", verdict: "fail", reason: String(error).slice(0, 200) });
} finally {
await context.close();
await launched?.close();
}
const failed = results.filter(result => result.verdict !== "pass");
if (pageErrors.length) console.error(`页面错误 ${pageErrors.length} 条:${pageErrors[0]}`);
console.log(`\n${results.length - failed.length}/${results.length} 通过`);
process.exit(failed.length ? 1 : 0);

17
web/tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"allowJs": true,
"resolveJsonModule": true,
"types": ["vite/client"]
},
"include": ["src"]
}

View File

@@ -34,6 +34,7 @@ export default defineConfig({
"shell-preview": "shell-preview.html",
full: "full.html",
workbench: "workbench.html",
"teaching-console": "teaching-console.html",
python: "python.html",
assembly: "assembly.html",
bim: "bim.html",