#!/usr/bin/env python3 """Run one queued contract family and promote only fully passed real cases.""" import argparse import json import os import subprocess import re from pathlib import Path ROOT = Path(__file__).resolve().parents[1] QUEUE = ROOT / "docs/current/contract-generation-queue.json" PROGRESS = ROOT / "docs/current/contract-generation-progress.json" def main(): parser = argparse.ArgumentParser() parser.add_argument("--module") parser.add_argument("--family") parser.add_argument("--apply", action="store_true", help="promote coveredIds only after every selected case passes") parser.add_argument("--confirm-apply", action="store_true", help="second confirmation required with --apply") parser.add_argument("--generate", action="store_true", help="write a non-passing skeleton; never updates coveredIds") args = parser.parse_args() if args.apply and not args.confirm_apply: parser.error("--apply requires --confirm-apply") queue = json.loads(QUEUE.read_text()) batch = next((item for item in queue.get("batches", []) if (not args.module or item["module"] == args.module) and (not args.family or item["family"] == args.family)), None) if not batch: print(json.dumps({"status": "no_batch", "reason": "no queued family matches"})) return 2 if args.generate: slug = re.sub(r"[^a-z0-9]+", "-", f"{batch['module']}-{batch['family']}".lower()).strip("-") output = ROOT / "tools/generated-contracts" / f"{slug}.mjs" output.parent.mkdir(parents=True, exist_ok=True) ids = json.dumps(batch["ids"], ensure_ascii=False, indent=2) source = json.dumps(batch.get("commands", []), ensure_ascii=False) output.write_text("""// Generated contract skeleton. Implement real native/browser assertions before promotion.\nconst ids = %s;\nconst commands = %s;\nconst results = ids.map(capabilityId => ({ capabilityId, status: \"not_implemented\", cases: [{ input: { capabilityId, commands }, assertions: [{ name: \"real business assertion is implemented\", passed: false, actual: \"generation skeleton only\" }] }] }));\nprocess.stdout.write(JSON.stringify({ schema: \"freecad-web-business-cases/v1\", results }) + \"\\n\");\nprocess.exitCode = 1;\n""" % (ids, source)) try: progress = json.loads(PROGRESS.read_text()) except (OSError, json.JSONDecodeError): progress = {"schema": "freecad-web-contract-generation-progress/v1", "batches": {}} progress.setdefault("batches", {})[f"{batch['module']}:{batch['family']}"] = { "status": "skeleton_generated", "path": str(output.relative_to(ROOT)), "generatedAt": __import__("time").time(), "ids": batch["ids"], "coveredIdsUpdated": False} PROGRESS.write_text(json.dumps(progress, ensure_ascii=False, indent=2) + "\n") print(json.dumps({"status": "skeleton_generated", "module": batch["module"], "family": batch["family"], "ids": batch["ids"], "path": str(output.relative_to(ROOT)), "coveredIdsUpdated": False}, ensure_ascii=False)) return 0 contract_path = ROOT / "docs/business-acceptance" / f"{batch['module']}.json" contract = json.loads(contract_path.read_text()) command = contract.get("command", []) if batch["module"] == "Part": command = ["node", "tools/part-family-contract-business-cases.mjs"] if batch["family"].startswith("product-"): command = ["node", "tools/web-acceptance-cases.mjs"] if batch["family"] == "product-extensions": command = ["node", "tools/web-product-extensions-business-cases.mjs"] if batch["family"].startswith("desktop-command-"): command = ["node", "tools/desktop-boundary-business-cases-v2.mjs"] if batch["module"] in {"BIM", "Test", "Assembly", "CAM", "Fem", "Draft", "Sketcher", "TechDraw", "Web"}: command = ["node", "tools/desktop-restricted-boundary-business-cases.mjs"] if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepycheckable": command = ["node", "tools/templatepymod-checkable-business-cases.mjs"] if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepygroup": command = ["node", "tools/templatepymod-group-business-cases.mjs"] if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepygrp": command = ["node", "tools/templatepymod-grp-business-cases.mjs"] if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepymod": command = ["node", "tools/templatepymod-command-business-cases-v2.mjs"] if batch["module"] == "Draft" and batch["family"] == "create-edit-recompute": command = ["node", "tools/draft-action-business-cases.mjs"] if batch["module"] == "Fem" and batch["family"] == "create-edit-recompute": command = ["node", "tools/fem-action-business-cases.mjs"] if not isinstance(command, list) or len(command) < 2: print(json.dumps({"status": "not_ready", "reason": "module contract has no executable command", "batch": batch})) return 78 environment = dict(os.environ, FREECAD_BUSINESS_IDS=json.dumps(batch["ids"])) run = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True) try: report = json.loads(run.stdout) except json.JSONDecodeError: report = {"status": "invalid_report", "stdout": run.stdout[-3000:], "stderr": run.stderr[-3000:]} results = report.get("results", []) if isinstance(report, dict) else [] passed = {row.get("capabilityId") for row in results if row.get("status") == "passed"} all_passed = set(batch["ids"]).issubset(passed) and run.returncode == 0 output = {"status": "passed" if all_passed else "not_ready", "applied": False, "module": batch["module"], "family": batch["family"], "ids": batch["ids"], "passedIds": sorted(passed), "exitCode": run.returncode, "reason": report.get("reason"), "stderr": run.stderr[-600:], "stdout": run.stdout[-600:]} if all_passed and args.apply: covered = list(dict.fromkeys([*contract.get("coveredIds", []), *batch["ids"]])) contract["coveredIds"] = covered contract_path.write_text(json.dumps(contract, ensure_ascii=False, indent=2) + "\n") try: progress = json.loads(PROGRESS.read_text()) except (OSError, json.JSONDecodeError): progress = {"schema": "freecad-web-contract-generation-progress/v1", "batches": {}} key = f"{batch['module']}:{batch['family']}" previous = progress.setdefault("batches", {}).get(key, {}) progress["batches"][key] = {**previous, "status": "verified_and_applied", "verifiedAt": __import__("time").time(), "ids": batch["ids"], "passedIds": sorted(passed), "coveredIdsUpdated": True} PROGRESS.write_text(json.dumps(progress, ensure_ascii=False, indent=2) + "\n") output["applied"] = True print(json.dumps(output, ensure_ascii=False)) return 0 if all_passed else 1 if __name__ == "__main__": raise SystemExit(main())